code
stringlengths 1
13.8M
|
---|
"sim10GDINA" |
library(RNetLogo)
path.to.NetLogo <- "C:/Program Files/NetLogo 6.0/app"
nl.test1 <- "nl.test1"
nl.jarname <- "netlogo-6.0.0.jar"
NLStart(path.to.NetLogo, gui=TRUE, nl.obj=nl.test1, nl.jarname=nl.jarname) |
sim.pois <-
function(lambda,n.obs,n.val)
{
n.integer <- function(x, tol = .Machine$double.eps)
{ abs(x - round(x)) < tol }
if( mean(n.integer(n.obs)) !=1 || n.obs<= 0) stop("Num of Obs must be positive integer")
if( mean(n.integer(n.val)) !=1 || n.val<= 0) stop("Length of Each Obs must be positive integer")
if(any(lambda < 0)) stop("Poisson mean is negative")
dat.sim <- vector("list",length(lambda))
for (i in 1:length(lambda))
{
set.seed(132);set.seed(sample(.Random.seed,1))
X <- matrix(NA,nrow = n.obs, ncol = n.val)
for (j in 1:n.obs)
{
X[j,] <- rpois(n.val,lambda[i])
}
dat.sim[[i]] <- X
}
dat.sim <- do.call(rbind,dat.sim)
rownames(dat.sim) <- 1:dim(dat.sim)[1]
colnames(dat.sim) <- 1:dim(dat.sim)[2]
dat.sim <- dat.sim[sample(rownames(dat.sim),replace=FALSE),]
return(dat.sim)
} |
check_dots_used <- function(env = caller_env(),
call = caller_env(),
error = NULL,
action = deprecated()) {
handler <- function() check_dots(env, error, action, call)
inject(base::on.exit(!!call2(handler), add = TRUE), env)
invisible()
}
check_dots <- function(env = caller_env(), error, action, call) {
if (.Call(ffi_ellipsis_dots_used, env)) {
return(invisible())
}
proms <- ellipsis_dots(env)
unused <- !map_lgl(proms, promise_forced)
action_dots(
error = error,
action = action,
message = "Arguments in `...` must be used.",
dots_i = unused,
class = "rlib_error_dots_unused",
call = call,
env = env
)
}
check_dots_unnamed <- function(env = caller_env(),
error = NULL,
call = caller_env(),
action = abort) {
proms <- ellipsis_dots(env)
if (length(proms) == 0) {
return()
}
unnamed <- names2(proms) == ""
if (all(unnamed)) {
return(invisible())
}
named <- !unnamed
action_dots(
error = error,
action = action,
message = "Arguments in `...` must be passed by position, not name.",
dots_i = named,
class = "rlib_error_dots_named",
call = call,
env = env
)
}
check_dots_empty <- function(env = caller_env(),
error = NULL,
call = caller_env(),
action = abort) {
dots <- ellipsis_dots(env)
if (length(dots) == 0) {
return()
}
if (!is_named(dots)) {
note <- c("i" = "Did you forget to name an argument?")
} else {
note <- NULL
}
action_dots(
error = error,
action = action,
message = "`...` must be empty.",
note = note,
dots_i = TRUE,
class = "rlib_error_dots_nonempty",
call = call,
env = env
)
}
check_dots_empty0 <- function(..., call = caller_env()) {
if (nargs()) {
check_dots_empty(call = call)
}
}
action_dots <- function(error,
action,
message,
dots_i,
env,
class = NULL,
note = NULL,
...) {
if (is_missing(action)) {
action <- abort
} else {
paste_line(
"The `action` argument of ellipsis functions is deprecated as of rlang 1.0.0.",
"Please use the `error` argument instead."
)
}
dots <- substitute(...(), env = env)[dots_i]
names(dots) <- ifelse(
have_name(dots),
names2(dots),
paste0("..", seq_along(dots))
)
bullet_header <- ngettext(
length(dots),
"Problematic argument:",
"Problematic arguments:",
)
bullets <- map2_chr(names(dots), dots, function(name, expr) {
sprintf("%s = %s", name, as_label(expr))
})
if (is_null(error)) {
try_dots <- identity
} else {
try_dots <- function(expr) try_fetch(expr, error = error)
}
try_dots(action(
c(message, "x" = bullet_header, set_names(bullets, "*"), note),
class = c(class, "rlib_error_dots"),
...
))
}
promise_forced <- function(x) {
.Call(ffi_ellipsis_promise_forced, x)
}
ellipsis_dots <- function(env = caller_env()) {
.Call(ffi_ellipsis_dots, env)
}
NULL
NULL |
di_iterate <- function(data, success_vars, group_vars, cohort_vars=NULL, scenario_repeat_by_vars=NULL, exclude_scenario_df=NULL, weight_var=NULL, include_non_disagg_results=TRUE, ppg_reference_groups='overall', min_moe=0.03, use_prop_in_moe=FALSE, prop_sub_0=0.5, prop_sub_1=0.5, di_prop_index_cutoff=0.80, di_80_index_cutoff=0.80, di_80_index_reference_groups='hpg', check_valid_reference=TRUE) {
stopifnot(length(group_vars) == length(ppg_reference_groups) | length(ppg_reference_groups) == 1)
stopifnot(length(group_vars) == length(di_80_index_reference_groups) | length(di_80_index_reference_groups) == 1)
for (i in seq_along(success_vars)) {
if (!(success_vars[i] %in% names(data))) {
stop(paste0("'", success_vars[i], "' specified in `success_vars` is not found in `data`."))
}
}
for (i in seq_along(group_vars)) {
if (!(group_vars[i] %in% names(data))) {
stop(paste0("'", group_vars[i], "' specified in `group_vars` is not found in `data`."))
}
}
if (check_valid_reference) {
for (i in 1:length(ppg_reference_groups)) {
if (!(ppg_reference_groups[i] %in% c(as.character(formals(di_ppg)$reference)[-1], unique(data[[group_vars[i]]])))) {
stop(paste0("'", ppg_reference_groups[i], "'", " is not valid for the argument `ppg_reference_groups` as it does not exist in the group variable `", group_vars[i], "`."))
}
}
for (i in 1:length(di_80_index_reference_groups)) {
if (!(di_80_index_reference_groups[i] %in% c(unique(data[[group_vars[i]]]), c('hpg', 'overall', 'all but current'))) & !is.na(di_80_index_reference_groups[i])) {
stop(paste0("'", di_80_index_reference_groups[i], "'", " is not valid for the argument `di_80_index_reference_groups` as it does not exist in the group variable `", group_vars[i], "`."))
}
}
}
if (include_non_disagg_results) {
data$`- None` <- '- All'
group_vars <- c(group_vars, '- None')
if (length(ppg_reference_groups) > 1) {
ppg_reference_groups <- c(ppg_reference_groups, 'overall')
} else if (length(ppg_reference_groups) == 1 & !(ppg_reference_groups %in% c('overall', 'hpg', 'all but current'))) {
ppg_reference_groups <- c(ppg_reference_groups, 'overall')
}
if (length(di_80_index_reference_groups) > 1) {
di_80_index_reference_groups <- c(di_80_index_reference_groups, NA)
} else if (length(di_80_index_reference_groups) == 1 & !(is.na(di_80_index_reference_groups) | di_80_index_reference_groups %in% c('hpg', 'overall', 'all but current'))) {
di_80_index_reference_groups <- c(di_80_index_reference_groups, NA)
}
}
if (length(unique(sapply(data[, group_vars], class))) > 1) {
stop("All variables specified in `group_vars` should be of the same class. Suggestion: set them all as character data using `as.character`.")
}
if (!is.null(scenario_repeat_by_vars)) {
for (i in seq_along(scenario_repeat_by_vars)) {
if (!(scenario_repeat_by_vars[i] %in% names(data))) {
stop(paste0("'", scenario_repeat_by_vars[i], "' specified in `scenario_repeat_by_vars` is not found in `data`."))
}
}
if (length(unique(sapply(data[, scenario_repeat_by_vars], class))) > 1) {
stop("All variables specified in `scenario_repeat_by_vars` should be of the same class. Suggestion: set them all as character data.")
}
}
if (is.null(cohort_vars)) {
cohort_vars <- '_cohort_'
data[[cohort_vars]] <- '- All'
} else {
for (i in seq_along(cohort_vars)) {
if (!(cohort_vars[i] %in% names(data))) {
stop(paste0("'", cohort_vars[i], "' specified in `cohort_vars` is not found in `data`."))
}
}
}
if (length(cohort_vars) != 1 & length(cohort_vars) != length(success_vars)) {
stop('`cohort_vars` must be of length 1 or the same length as `success_vars` (each success variable corresponds to a cohort variable).')
}
lu_success_cohort <- data.frame(success_var=success_vars, cohort_var=cohort_vars, stringsAsFactors=FALSE)
if (is.null(weight_var)) {
weight_var <- '- Weight'
data <- data %>%
mutate_at(vars(one_of(success_vars)), .funs=list('NA_FLAG'= ~ is.na(.))) %>%
group_by_at(vars(one_of(group_vars, cohort_vars, scenario_repeat_by_vars, if (length(success_vars)==1) {'NA_FLAG'} else {paste0(success_vars, '_NA_FLAG')}))) %>%
mutate(`- Weight`=1) %>%
summarize_at(vars(success_vars, '- Weight'), .funs=sum) %>%
ungroup
} else {
if (!(weight_var %in% names(data))) {
stop(paste0("The weight variable '", weight_var, "'", ' is not in `data`.'))
}
if (any(is.na(data[[weight_var]]))) {
stop(paste0("The specified column corresponding to weight_var='", weight_var, "' contain NA values."))
}
if (any(data[[weight_var]] <= 0)) {
stop(paste0("The specified column corresponding to weight_var='", weight_var, "' contain non-positive values."))
}
}
success_var <- group_var <- cohort_var <- ppg_reference_group <- NULL
if (!is.null(scenario_repeat_by_vars)) {
dRepeatScenarios0 <- data %>%
select(one_of(scenario_repeat_by_vars)) %>%
lapply(function(x) c(unique(x), '- All')) %>%
expand.grid(stringsAsFactors=FALSE)
if (!is.null(exclude_scenario_df)) {
if (!all(names(exclude_scenario_df) %in% scenario_repeat_by_vars)) {
stop('`exclude_scenario_df` contain variables that are not specified in `scenario_repeat_by_vars`.')
}
exclude__ <- NULL
dRepeatScenarios0 <- dRepeatScenarios0 %>%
left_join(exclude_scenario_df %>% mutate(exclude__=1)) %>%
filter(is.na(exclude__)) %>%
select(one_of(names(dRepeatScenarios0)))
}
row_index <- want_indices <- n_rows <- NULL
dRepeatScenarios <- lapply(1:nrow(dRepeatScenarios0)
, FUN=function(i) {
row_index <- want_indices <- n_rows <- NULL
vars_specific <- colnames(dRepeatScenarios0)[!(dRepeatScenarios0[i, ] %in% '- All')]
vars_all <- colnames(dRepeatScenarios0)[dRepeatScenarios0[i, ] %in% '- All']
if (length(vars_specific) != 0) {
d_interm <- dRepeatScenarios0 %>%
slice(i) %>%
select(one_of(vars_specific)) %>%
left_join(data %>% mutate(row_index=row_number())) %>%
filter(!is.na(row_index)) %>%
group_by_at(vars(one_of(vars_specific))) %>%
summarize(want_indices=list(row_index), n_rows=n()) %>%
ungroup
d_interm[, vars_all] <- '- All'
d_interm
} else {
d_interm <- data %>%
mutate(row_index=row_number()) %>%
summarize(want_indices=list(row_index), n_rows=n()) %>%
ungroup
d_interm[, vars_all] <- '- All'
d_interm
}
}
) %>%
bind_rows %>%
filter(n_rows > 0) %>%
select(-n_rows)
}
dRef <- data.frame(group_var=group_vars, ppg_reference_group=ppg_reference_groups, di_80_index_reference_group=di_80_index_reference_groups, stringsAsFactors=FALSE)
ppg_check_valid_reference <- di_80_check_valid_reference <- di_80_index_reference_group <- NULL
dScenarios <- expand.grid(success_var=success_vars, group_var=group_vars, min_moe=min_moe, use_prop_in_moe=use_prop_in_moe, prop_sub_0=prop_sub_0, prop_sub_1=prop_sub_1, ppg_check_valid_reference=FALSE, di_prop_index_cutoff=di_prop_index_cutoff, di_80_index_cutoff=di_80_index_cutoff, di_80_check_valid_reference=FALSE, stringsAsFactors=FALSE) %>%
left_join(lu_success_cohort, by=c('success_var')) %>%
left_join(dRef, by=c('group_var')) %>%
select(success_var, group_var, cohort_var, ppg_reference_group, min_moe, use_prop_in_moe, prop_sub_0, prop_sub_1, ppg_check_valid_reference, di_prop_index_cutoff, di_80_index_cutoff, di_80_index_reference_group, di_80_check_valid_reference)
iterate <- function(success_var, group_var, cohort_var, ppg_reference_group, min_moe, use_prop_in_moe, prop_sub_0, prop_sub_1, ppg_check_valid_reference, di_prop_index_cutoff, di_80_index_cutoff, di_80_index_reference_group, di_80_check_valid_reference, subset_idx) {
data <- data[subset_idx, ]
data <- data[!is.na(data[[success_var]]), ]
if (nrow(data)==0) {
return(NULL)
}
reference_val <- ppg_reference_group
success_variable <- disaggregation <- cohort_variable <- reference_group <- reference <- di_indicator <- cohort <- group <- success <- success_needed_not_di <- success_needed_full_parity <- NULL
di_ppg(success=data[[success_var]], group=data[[group_var]], cohort=data[[cohort_var]], weight=data[[weight_var]], reference=reference_val, min_moe=min_moe, use_prop_in_moe=use_prop_in_moe, prop_sub_0=prop_sub_0, prop_sub_1=prop_sub_1, check_valid_reference=ppg_check_valid_reference) %>%
rename(ppg_reference_group=reference_group, ppg_reference=reference, di_indicator_ppg=di_indicator, success_needed_not_di_ppg=success_needed_not_di, success_needed_full_parity_ppg=success_needed_full_parity) %>%
left_join(
di_prop_index(success=data[[success_var]], group=data[[group_var]], cohort=data[[cohort_var]], weight=data[[weight_var]], di_prop_index_cutoff=di_prop_index_cutoff) %>%
select(cohort, group, n, success, di_prop_index, di_indicator, success_needed_not_di, success_needed_full_parity) %>%
rename(di_indicator_prop_index=di_indicator, success_needed_not_di_prop_index=success_needed_not_di, success_needed_full_parity_prop_index=success_needed_full_parity)
, by=c('cohort', 'group', 'n', 'success')
) %>%
left_join(
di_80_index(success=data[[success_var]], group=data[[group_var]], cohort=data[[cohort_var]], weight=data[[weight_var]], di_80_index_cutoff=di_80_index_cutoff, reference_group=di_80_index_reference_group, check_valid_reference=di_80_check_valid_reference) %>%
select(cohort, group, n, success, reference_group, di_80_index, di_indicator, success_needed_not_di, success_needed_full_parity) %>%
rename(di_indicator_80_index=di_indicator, di_80_index_reference_group=reference_group, success_needed_not_di_80_index=success_needed_not_di, success_needed_full_parity_80_index=success_needed_full_parity)
, by=c('cohort', 'group', 'n', 'success')
) %>%
mutate(
success_variable=success_var
, disaggregation=group_var
, cohort_variable=cohort_var
) %>%
select(success_variable, cohort_variable, cohort, disaggregation, everything())
}
if (is.null(scenario_repeat_by_vars)) {
subset_idx <- 1:nrow(data)
pmap(dScenarios %>% mutate(subset_idx=list(subset_idx)), iterate) %>%
bind_rows
} else {
dRepeatScenarios$df_results <- lapply(1:nrow(dRepeatScenarios)
, FUN=function(i) {
subset_idx <- dRepeatScenarios %>% slice(i) %>% select(want_indices) %>% unlist
pmap(dScenarios %>% mutate(subset_idx=list(subset_idx)), iterate) %>%
bind_rows
}
)
df_results <- NULL
dRepeatScenarios %>%
select(-want_indices) %>%
unnest(df_results)
}
} |
construct_bspline_penalty <- function(variables_length, dimensions, term.number, blockzero, cyclic){
if(variables_length == 1){
P <- get_penalty(dimensions, cyclic = cyclic)
P_wee_list <- list(P = P)
P_list <- list(P = get_block_penalty(P, blockzero = blockzero, i = term.number))
} else if(variables_length > 1){
if(length(dimensions) == 1){
dim.each <- rep(dimensions, variables_length)
} else if(length(dimensions) == variables_length){
dim.each <- dimensions
} else stop("the vector `k' is the wrong length for one of the m() terms")
if(length(cyclic) == 1){
cyclic.each <- rep(cyclic, variables_length)
} else if(length(cyclic) == variables_length){
cyclic.each <- cyclic
} else stop("provided logical vector `cyclic' is the wrong length for one of the m() terms")
marginal_penalty_list <- vector("list", length = variables_length)
for(i in 1:variables_length){
marginal_penalty_list[[i]] <- get_penalty(dim.each[i], cyclic = cyclic.each[i])
}
kronecker_list <- vector("list", length = variables_length)
marginal_id_list <- vector("list", length = variables_length)
for(i in 1:variables_length) marginal_id_list[[i]] <- diag.spam(1, dim.each[i])
for(i in 1:variables_length){
int_list <- marginal_id_list
int_list[[i]] <- marginal_penalty_list[[i]]
kronecker_list[[i]] <- Reduce("kronecker.spam", int_list)
}
P_list <- lapply(kronecker_list, get_block_penalty, blockzero = blockzero, i = term.number)
P_wee_list <- kronecker_list
}
list(P_list = P_list, P_wee_list = P_wee_list)
} |
expected <- eval(parse(text="FALSE"));
test(id=0, code={
argv <- eval(parse(text="list(structure(list(breaks = c(26, 30, 54, 25, 70, 52, 51, 26, 67, 27, 14, 29, 19, 29, 31, 41, 20, 44), wool = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c(\"A\", \"B\"), class = \"factor\"), tension = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c(\"L\", \"M\", \"H\"), class = \"factor\")), .Names = c(\"breaks\", \"wool\", \"tension\"), row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L), class = \"data.frame\"))"));
do.call(`is.array`, argv);
}, o=expected); |
fevd.var2 <- fevd(varsimest, n.ahead = 10)
args(vars:::plot.varfevd)
plot(fevd.var2, addbars = 2) |
geom_shadowpath <- function(mapping = NULL, data = NULL,
stat = "identity", position = "identity",
...,
lineend = "butt",
linejoin = "round",
linemitre = 10,
arrow = NULL,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE) {
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomShadowPath,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
lineend = lineend,
linejoin = linejoin,
linemitre = linemitre,
arrow = arrow,
na.rm = na.rm,
...
)
)
}
GeomShadowPath <- ggproto("GeomShadowPath", Geom,
required_aes = c("x", "y"),
default_aes = aes(colour = "black", size = 0.5, linetype = 1, alpha = NA, shadowcolour=NA, shadowsize=NA, shadowalpha = NA),
handle_na = function(data, params) {
complete <- stats::complete.cases(data[c("x", "y", "size", "colour", "linetype")])
kept <- stats::ave(complete, data$group, FUN = keep_mid_true)
data <- data[kept, ]
if (!all(kept) && !params$na.rm) {
warn(glue("Removed {sum(!kept)} row(s) containing missing values (geom_shadowpath)."))
}
data$shadowcolour[is.na(data$shadowcolour)] <- 'white'
data$shadowsize[is.na(data$shadowsize)] <- data$size * 2.5
data$shadowalpha[is.na(data$shadowalpha)] <- data$alpha * 0.25
data$shadowalpha[is.na(data$shadowalpha)] <- 0.9
data
},
draw_panel = function(data, panel_params, coord, arrow = NULL,
lineend = "butt", linejoin = "round", linemitre = 10,
na.rm = FALSE) {
if (!anyDuplicated(data$group)) {
message("geom_shadowpath: Each group consists of only one observation. Do you need to adjust the group aesthetic?")
}
data <- data[order(data$group), , drop = FALSE]
munched <- coord_munch(coord, data, panel_params)
rows <- stats::ave(seq_len(nrow(munched)), munched$group, FUN = length)
munched <- munched[rows >= 2, ]
if (nrow(munched) < 2) return(zeroGrob())
attr <- dapply(munched, "group", function(df) {
linetype <- unique(df$linetype)
new_data_frame(list(
solid = identical(linetype, 1) || identical(linetype, "solid"),
constant = nrow(unique(df[, c("alpha", "colour","size", "linetype", 'shadowcolour', 'shadowsize', 'shadowalpha')])) == 1
), n = 1)
})
solid_lines <- all(attr$solid)
constant <- all(attr$constant)
if (!solid_lines && !constant) {
abort("geom_shadowpath: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line")
}
n <- nrow(munched)
group_diff <- munched$group[-1] != munched$group[-n]
start <- c(TRUE, group_diff)
end <- c(group_diff, TRUE)
if (!constant) {
munched$start <- start
munched$end <- end
munched.s <- munched
munched.s$shadow <- T
munched.s$colour <- munched.s$shadowcolour
munched.s$size <- munched.s$shadowsize
munched.s$alpha <- munched.s$shadowalpha
munched$shadow <- F
munched <- rbind( munched.s, munched)
munched$id <- 2*match(munched$group, unique(munched$group)) - munched$shadow
munched <- munched[order(munched$group), c('colour', 'size', 'y', 'x', 'linetype','alpha', 'id', 'start', 'end')]
aph <- alpha( munched$colour[munched$start], munched$alpha[munched$start] )
grid::segmentsGrob(
munched$x[!munched$end],
munched$y[!munched$end],
munched$x[!munched$start],
munched$y[!munched$start],
default.units = "native", arrow = arrow,
gp = gpar(
col = alpha(munched$colour, munched$alpha)[!munched$end],
fill = alpha(munched$colour, munched$alpha)[!munched$end],
lwd = munched$size[!munched$end] * .pt,
lty = munched$linetype[!munched$end],
lineend = lineend,
linejoin = linejoin,
linemitre = linemitre
)
)
} else {
munched$start <- start
munched.s <- munched
munched.s$shadow <- T
munched.s$colour <- munched.s$shadowcolour
munched.s$size <- munched.s$shadowsize
munched.s$alpha <- munched.s$shadowalpha
munched$shadow <- F
munched <- rbind( munched.s, munched)
munched$id <- 2*match(munched$group, unique(munched$group)) - munched$shadow
munched <- munched[order(munched$group), c('colour', 'size', 'y', 'x', 'linetype','alpha', 'id', 'start')]
aph <- alpha( munched$colour[munched$start], munched$alpha[munched$start] )
grid::polylineGrob(
munched$x, munched$y, id = munched$id,
default.units = "native", arrow = arrow,
gp = gpar(
col = aph,
fill = aph,
lwd = munched$size[munched$start] * .pt,
lty = munched$linetype[munched$start],
lineend = lineend,
linejoin = linejoin,
linemitre = linemitre
)
)
}
},
draw_key = ggplot2::draw_key_path
)
geom_shadowline <- function(mapping = NULL, data = NULL, stat = "identity",
position = "identity", na.rm = FALSE, orientation = NA,
show.legend = NA, inherit.aes = TRUE, ...) {
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomShadowLine,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
na.rm = na.rm,
orientation = orientation,
...
)
)
}
GeomShadowLine <- ggproto("GeomShadowLine", GeomShadowPath,
setup_params = function(data, params) {
params$flipped_aes <- has_flipped_aes(data, params, ambiguous = TRUE)
params
},
extra_params = c("na.rm", "orientation"),
setup_data = function(data, params) {
data$flipped_aes <- params$flipped_aes
data <- flip_data(data, params$flipped_aes)
data <- data[order(data$PANEL, data$group, data$x), ]
flip_data(data, params$flipped_aes)
}
)
geom_shadowstep <- function(mapping = NULL, data = NULL, stat = "identity",
position = "identity", direction = "hv",
na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) {
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomShadowStep,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
direction = direction,
na.rm = na.rm,
...
)
)
}
GeomShadowStep <- ggproto("GeomShadowStep", GeomShadowPath,
draw_panel = function(data, panel_params, coord, direction = "hv") {
data <- dapply(data, "group", stairstep, direction = direction)
GeomShadowPath$draw_panel(data, panel_params, coord)
}
)
keep_mid_true <- getFromNamespace("keep_mid_true", "ggplot2")
dapply <- getFromNamespace("dapply", "ggplot2")
stairstep <- getFromNamespace("stairstep", "ggplot2")
new_data_frame <- getFromNamespace("new_data_frame", "ggplot2") |
library(portfolio)
load("portfolioBasic.test.RData")
data <- data.frame(id = 1:20, in.var = 1:20)
data$in.var <- as.numeric(data$in.var)
x <- new("portfolioBasic", in.var = "in.var", type = "sigmoid", size = 8, data = data)
x <- create(x)
stopifnot(
all.equal(sum(x@weights$weight), 0),
all.equal(sum(x@weights$weight[x@weights$weight > 0]), 1)
)
x@weights$weight <- x@weights$weight / 2
x <- scaleWeights(x)
stopifnot(
all.equal(sum(x@weights$weight), 0),
all.equal(sum(x@weights$weight[x@weights$weight > 0]), 1)
) |
LV_pm_alpha_global_lambdacov_none_alphacov_none <- function(par,
fitness,
neigh_intra_matrix = NULL,
neigh_inter_matrix,
covariates,
fixed_parameters){
pos <- 1
if(is.null(fixed_parameters[["lambda"]])){
lambda <- par[pos]
pos <- pos + 1
}else{
lambda <- fixed_parameters[["lambda"]]
}
if(is.null(fixed_parameters[["alpha_inter"]])){
alpha_inter <- par[pos]
pos <- pos + 1
}else{
alpha_inter <- fixed_parameters[["alpha_inter"]]
}
sigma <- par[length(par)]
background <- rowSums(neigh_inter_matrix)
pred <- lambda - background*alpha_inter
llik <- dnorm(fitness, mean = (log(pred)), sd = (sigma), log=TRUE)
return(sum(-1*llik))
} |
smbetattest <-
function(X, na, nb, alpha=0.05){
cn<-length(X[1,])
rn<-length(X[,1])
XC<-X[, seq(cn-na-nb)]
Xa<-X[,(cn-na-nb+1):cn]
XX<-na.omit(Xa)
size<-max(apply(XX, 2, sum))
pvalue<-rep(1,rn)
betattest<-betattest(XX,na=na,nb=nb, level="RNA")
prat<-pratio(xx=XX,na=na,nb=nb)
odrat<-oddratio(XX=XX, na=na,nb=nb)
t_value<-betattest[,1]
rho<-(prat*odrat)^0.5
beta_t<-t_value
df<-betattest[,2]
pvalue <-2*(1-pt(abs(beta_t ),df=df))
XD<-cbind(beta_t, pvalue,rho)
XD<-as.data.frame(XD)
XD1<-subset(XD, pvalue<alpha)
if(length(XD1$rho)==0){
XD2<-subset(XD, pvalue<0.1)
Rho<-XD2$rho
}else{
Rho<- XD1$rho
}
return(Rho)
} |
library(simpleCache)
cacheDir = tempdir()
setSharedCacheDir(cacheDir)
simpleCacheShared("normSample", { rnorm(1e7, 0,1) }, recreate=TRUE)
simpleCacheShared("normSample", { rnorm(1e7, 0,1) })
deleteCaches("normSample", force=TRUE) |
get.bound.box <- function(coords){
xmin <- coords[[1]][[1]]$x[1]
ymin <- coords[[1]][[1]]$y[1]
xmax <- coords[[1]][[1]]$x[1]
ymax <- coords[[1]][[1]]$y[1]
for(strata in seq(along = coords)){
for(poly in seq(along = coords[[strata]])){
x.coords <- coords[[strata]][[poly]]$x
y.coords <- coords[[strata]][[poly]]$y
xmin <- min(xmin, x.coords)
ymin <- min(ymin, y.coords)
xmax <- max(xmax, x.coords)
ymax <- max(ymax, y.coords)
}
}
total.bound.box <- c(xmin = xmin, ymin = ymin, xmax = xmax, ymax = ymax)
return(total.bound.box)
} |
eng_extendr <- function(options) {
eng_impl(options, rust_eval)
}
eng_extendrsrc <- function(options) {
eng_impl(options, rust_source)
}
eng_impl <- function(options, rextendr_fun) {
if (!requireNamespace("knitr", quietly = TRUE)) {
ui_throw("The knitr package is required to run the extendr chunk engine.")
}
if (!is.null(options$preamble)) {
preamble <- knitr::knit_code$get(options$preamble)
code <- c(
lapply(options$preamble, function(x) knitr::knit_code$get(x)),
recursive = TRUE
)
code <- c(code, options$code)
} else {
code <- options$code
}
code <- glue_collapse(code, sep = "\n")
code_out <- glue_collapse(options$code, sep = "\n")
opts <- options$engine.opts
if (!is.environment(opts$env)) opts$env <- knitr::knit_global()
if (isTRUE(options$eval)) {
ui_v("Evaluating Rust extendr code chunk...")
out <- utils::capture.output({
result <- withVisible(
do.call(rextendr_fun, c(list(code = code), opts))
)
if (isTRUE(result$visible)) {
print(result$value)
}
})
} else {
out <- ""
}
options$engine <- "rust"
knitr::engine_output(options, code_out, out)
} |
E.QQ = function(K, mu, do.C=TRUE) {
if (!is.matrix(K)) K=as.matrix(K)
if (nrow(K)!=ncol(K)) stop("K is not a square matrix.")
n=nrow(K)
if (length(mu)!=n) stop("mu is not of length n.")
mom=0
if (do.C) {
if (!is.double(K)) K <- as.double(K)
aux=.C("score_var", "_K" = K, "_n"=as.integer(n), "_mu"=as.double(mu), "_mom"=as.double(mom))
mom=aux$"_mom"
} else {
mom = mom + sum((mu*(1-mu)^4 + (1-mu)*mu^4) * diag(K)^2)
for (i in 1:n) {
for (k in 1:n) {
if (k==i) next
mom = mom + mu[i]*(1-mu[i]) * mu[k]*(1-mu[k]) * K[i,i] * K[k,k]
}}
for (i in 1:n) {
for (j in 1:n) {
if (j==i) next
mom = mom + mu[i]*(1-mu[i]) * mu[j]*(1-mu[j]) * K[i,j] * K[i,j] * 2
}}
}
mom
} |
test_that("ts_pick works", {
to.be.picked.and.renamed <- c(`My Dax` = "DAX", `My Smi` = "SMI")
a <- ts_pick(EuStockMarkets, to.be.picked.and.renamed)
b <- ts_pick(EuStockMarkets, `My Dax` = "DAX", `My Smi` = "SMI")
expect_equal(a, b)
b <- ts_pick(EuStockMarkets, `My Dax` = 1, `My Smi` = 2)
expect_equal(a, b)
expect_equal(EuStockMarkets[, c(1, 2)], ts_pick(EuStockMarkets, c(1, 2)))
})
test_that("unknown series drops an error", {
expect_error(ts_pick(ts_df(ts_c(mdeaths, fdeaths)), "hallo"))
}) |
expected <- eval(parse(text="0L"));
test(id=0, code={
argv <- eval(parse(text="list(c(12784, 13149, 13514, 13879, 14245, 14610), FALSE, FALSE)"));
.Internal(`anyDuplicated`(argv[[1]], argv[[2]], argv[[3]]));
}, o=expected); |
setMethodS3("getMaxLengthRepeats", "AromaCellSequenceFile", function(this, cells, positions=1:getProbeLength(this), bases=c("A","C","G","T"), ..., force=FALSE, verbose=FALSE) {
if (!is.null(cells)) {
cells <- Arguments$getIndices(cells, max=nbrOfCells(this))
nbrOfCells <- length(cells)
} else {
nbrOfCells <- nbrOfCells(this)
}
bases <- Arguments$getCharacters(bases)
bases <- unique(bases)
verbose <- Arguments$getVerbose(verbose)
if (verbose) {
pushState(verbose)
on.exit(popState(verbose))
}
verbose && enter(verbose, "Identifying cells with repeats")
verbose && cat(verbose, "Nucleotide positions:")
verbose && str(verbose, positions)
chipType <- getChipType(this)
key <- list(method="getMaxRepeatLength", class=class(this)[1],
chipType=chipType, tags=getTags(this),
cells=cells, ...)
if (getOption(aromaSettings, "devel/useCacheKeyInterface", FALSE)) {
key <- getCacheKey(this, method="getMaxRepeatLength", chipType=chipType,
tags=getTags(this), cells=cells, ...)
}
dirs <- c("aroma.affymetrix", chipType)
if (!force) {
verbose && enter(verbose, "Checking for cached results")
res <- loadCache(key=key, dirs=dirs)
if (!is.null(res)) {
verbose && cat(verbose, "Found cached results")
verbose && exit(verbose)
verbose && exit(verbose)
return(res)
}
verbose && exit(verbose)
}
verbose && enter(verbose, "Searching for repeats")
verbose && cat(verbose, "Cells:")
verbose && str(verbose, cells)
startPosition <- rep(positions[1], times=nbrOfCells)
maxRepeatLength <- rep(as.integer(1), times=nbrOfCells)
verbose && str(verbose, startPosition)
verbose && str(verbose, maxRepeatLength)
verbose && enter(verbose, "Missing probes sequences")
nok <- isMissing(this, cells=cells)
naValue <- NA_integer_
startPosition[nok] <- naValue
maxRepeatLength[nok] <- naValue
if (is.null(cells)) {
cells <- which(!nok)
} else {
cells <- cells[!nok]
}
verbose && str(verbose, startPosition)
verbose && str(verbose, maxRepeatLength)
verbose && exit(verbose)
verbose && enter(verbose, "Remaining probe sequences")
verbose && cat(verbose, "Cells:")
verbose && str(verbose, cells)
if (length(cells) > 0) {
counts <- rep(as.integer(0), times=length(cells))
startPositionT <- rep(as.integer(0), times=length(cells))
maxRepeatLengthT <- rep(as.integer(1), times=length(cells))
for (pp in seq_along(positions)) {
verbose && enter(verbose, sprintf("Position %d of %d", pp, length(positions)))
pos <- positions[pp]
b1 <- readSequenceMatrix(this, cells=cells, position=pos, what="raw", drop=TRUE)
if (pp == 1) {
map <- attr(b1, "map")
basesToKeep <- map[bases]
isRepeat <- rep(TRUE, times=length(cells))
} else {
isRepeat <- (b1 == b0)
}
skip <- !is.element(b1, basesToKeep)
isRepeat[skip] <- FALSE
counts[isRepeat] <- counts[isRepeat] + as.integer(1)
counts[!isRepeat] <- as.integer(1)
isGreater <- rep(FALSE, times=length(cells))
keep <- is.finite(counts)
isGreater[keep] <- (counts[keep] > maxRepeatLengthT[keep])
maxRepeatLengthT[isGreater] <- counts[isGreater]
startPositionT[isGreater] <- pos - maxRepeatLengthT[isGreater] + as.integer(1)
b0 <- b1
verbose && exit(verbose)
}
startPositionT[startPositionT == 0] <- as.integer(-1)
maxRepeatLength[!nok] <- maxRepeatLengthT
startPosition[!nok] <- startPositionT
nok <- startPositionT <- maxRepeatLengthT <- NULL
}
res <- cbind(startPosition, maxRepeatLength)
startPosition <- maxRepeatLength <- NULL
verbose && cat(verbose, "Results:")
verbose && str(verbose, res)
verbose && exit(verbose)
verbose && enter(verbose, "Caching result")
saveCache(res, key=key, dirs=dirs)
verbose && exit(verbose)
verbose && exit(verbose)
res
}) |
drop.tip.fixed <- function(phy, tip, trim.internal = TRUE, subtree =
FALSE, root.edge = 0, rooted = is.rooted(phy)) {
if (!inherits(phy, "phylo"))
stop("object \"phy\" is not of class \"phylo\"")
Ntip <- length(phy$tip.label)
if (is.character(tip))
tip <- which(phy$tip.label %in% tip)
if (!rooted && subtree) {
phy <- root(phy, (1:Ntip)[-tip][1])
root.edge <- 0
}
phy <- reorder(phy)
NEWROOT <- ROOT <- Ntip + 1
Nnode <- phy$Nnode
Nedge <- dim(phy$edge)[1]
if (subtree) {
trim.internal <- TRUE
tr <- reorder(phy, "pruningwise")
N <- node.depth(phy)
}
wbl <- !is.null(phy$edge.length)
edge1 <- phy$edge[, 1]
edge2 <- phy$edge[, 2]
keep <- !logical(Nedge)
if (is.character(tip))
tip <- which(phy$tip.label %in% tip)
if (!rooted && subtree) {
phy <- root(phy, (1:Ntip)[-tip][1])
root.edge <- 0
}
keep[match(tip, edge2)] <- FALSE
if (trim.internal) {
ints <- edge2 > Ntip
repeat {
sel <- !(edge2 %in% edge1[keep]) & ints & keep
if (!sum(sel))
break
keep[sel] <- FALSE
}
if (subtree) {
subt <- edge1 %in% edge1[keep] & edge1 %in% edge1[!keep]
keep[subt] <- TRUE
}
if (root.edge && wbl) {
degree <- tabulate(edge1[keep])
if (degree[ROOT] == 1) {
j <- integer(0)
repeat {
i <- which(edge1 == NEWROOT & keep)
j <- c(i, j)
NEWROOT <- edge2[i]
degree <- tabulate(edge1[keep])
if (degree[NEWROOT] > 1)
break
}
keep[j] <- FALSE
if (length(j) > root.edge)
j <- 1:root.edge
NewRootEdge <- sum(phy$edge.length[j])
if (length(j) < root.edge && !is.null(phy$root.edge))
NewRootEdge <- NewRootEdge + phy$root.edge
phy$root.edge <- NewRootEdge
}
}
}
if (!root.edge)
phy$root.edge <- NULL
phy$edge <- phy$edge[keep, ]
if (wbl)
phy$edge.length <- phy$edge.length[keep]
TERMS <- !(phy$edge[, 2] %in% phy$edge[, 1])
oldNo.ofNewTips <- phy$edge[TERMS, 2]
n <- length(oldNo.ofNewTips)
phy$edge[TERMS, 2] <- rank(phy$edge[TERMS, 2])
if (subtree || !trim.internal) {
tips.kept <- oldNo.ofNewTips <= Ntip & !(oldNo.ofNewTips %in%
tip)
new.tip.label <- character(n)
new.tip.label[tips.kept] <- phy$tip.label[-tip]
node2tip <- oldNo.ofNewTips[!tips.kept]
new.tip.label[!tips.kept] <- if (subtree) {
paste("[", N[node2tip], "_tips]", sep = "")
}
else {
if (is.null(phy$node.label))
rep("NA", length(node2tip))
else phy$node.label[node2tip - Ntip]
}
if (!is.null(phy$node.label))
phy$node.label <- phy$node.label[-(node2tip - Ntip)]
phy$tip.label <- new.tip.label
}
else phy$tip.label <- phy$tip.label[-tip]
if (!is.null(phy$node.label))
phy$node.label <- phy$node.label[sort(unique(phy$edge[,
1])) - Ntip]
phy$Nnode <- dim(phy$edge)[1] - n + 1L
i <- phy$edge > n
phy$edge[i] <- match(phy$edge[i], sort(unique(phy$edge[i]))) + n
storage.mode(phy$edge) <- "integer"
collapse.singles(phy)
}
function(phy, tip, trim.internal = TRUE, subtree = FALSE,
root.edge = 0, rooted = is.rooted(phy)) {
Ntip <- length(phy$tip.label)
if (is.character(tip))
tip <- which(phy$tip.label %in% tip)
phy <- reorder(phy)
NEWROOT <- ROOT <- Ntip + 1
Nnode <- phy$Nnode
Nedge <- nrow(phy$edge)
wbl <- !is.null(phy$edge.length)
edge1 <- phy$edge[, 1]
edge2 <- phy$edge[, 2]
keep <- !(edge2 %in% tip)
ints <- edge2 > Ntip
repeat {
sel <- !(edge2 %in% edge1[keep]) & ints & keep
if (!sum(sel))
break
keep[sel] <- FALSE
}
phy2 <- phy
phy2$edge <- phy2$edge[keep, ]
if (wbl)
phy2$edge.length <- phy2$edge.length[keep]
TERMS <- !(phy2$edge[, 2] %in% phy2$edge[, 1])
oldNo.ofNewTips <- phy2$edge[TERMS, 2]
n <- length(oldNo.ofNewTips)
idx.old <- phy2$edge[TERMS, 2]
phy2$edge[TERMS, 2] <- rank(phy2$edge[TERMS, 2])
phy2$tip.label <- phy2$tip.label[-tip]
if (!is.null(phy2$node.label))
phy2$node.label <-
phy2$node.label[sort(unique(phy2$edge[, 1])) - Ntip]
phy2$Nnode <- nrow(phy2$edge) - n + 1L
i <- phy2$edge > n
phy2$edge[i] <- match(phy2$edge[i], sort(unique(phy2$edge[i]))) + n
storage.mode(phy2$edge) <- "integer"
collapse.singles(phy2)
} |
context("fetchSCAN() -- requires internet connection")
test_that("fetchSCAN() works", {
skip_if_offline()
skip_on_cran()
x <<- fetchSCAN(site.code=2001, year=c(2014))
skip_if(is.null(x))
expect_true(inherits(x, 'list'))
})
test_that("fetchSCAN() returns the right kind of data", {
skip_if_offline()
skip_on_cran()
skip_if(is.null(x))
expect_true(inherits(x, 'list'))
expect_true(inherits(x$metadata, 'data.frame'))
expect_true(inherits(x$STO, 'data.frame'))
expect_true(ncol(x$STO) == 7)
}) |
summary.ptglm = function(object, silent = F, ...) {
ncov = length(object$mle) - 2
beta = object$mle[1:ncov]
D = object$mle[ncov+1]
a = object$mle[ncov+2]
coef.table = cbind(beta)
colnames(coef.table) = 'Estimate'
requireNamespace('matrixcalc')
check.pdef1 = matrixcalc::is.positive.definite(object$fisher.info, tol = 1e-10)
last.eig = tail(eigen(object$fisher.info)$values, 1)
if (check.pdef1 & last.eig > 0.01) {
inv.hess = solve(object$fisher.info)
se.beta = sqrt(diag(inv.hess)[1:ncov])
}
else {
red.hess = object$fisher.info[1:ncov, 1:ncov]
check.pdef2 = matrixcalc::is.positive.definite(red.hess, tol = 1e-10)
last.eig.red = tail(eigen(red.hess)$values, 1)
if (check.pdef2 & last.eig.red > 0.01) {
warning('Full Fisher information matrix not positive definite. Standard errors are estimated
using the hessian of the profile likelihood of beta | (D, a, sigma2)')
inv.hess = solve(red.hess)
se.beta = sqrt(diag(inv.hess))
}
else stop('Fisher information matrix is not positive definite. Standard errors cannot be computed.')
}
z.score = beta/se.beta
p = 2*pnorm(abs(z.score), lower.tail = F)
coef.table = cbind(beta, se.beta, z.score, p)
colnames(coef.table) = c('Estimate', 'Std. error', 'z', 'p.value')
if (!silent) {
cat(paste('Loglikelihood:', round(object$logl, 3), '\n'))
cat('Parameter estimates:\n')
print(round(coef.table, 4))
cat('\n')
cat(paste('Dispersion =', round(D,2), '\n'))
cat(paste('Power =', round(a,2), '\n'))
}
out = list('logl' = round(object$logl,2), 'coefficients' = coef.table,
'D'= D, 'a' = a)
} |
check_mask <- function(mask, allow.NA = FALSE, allow.array = TRUE){
mask = check_nifti(mask, allow.array = allow.array)
allowable = c(0, 1)
if (allow.NA) {
allowable = c(allowable, NA)
}
mask = as(mask, "array")
class(mask) = "numeric"
umask = unique(c(mask))
res = all(umask %in% allowable)
return(res)
}
check_mask_fail <- function(...){
res = check_mask(...)
if (!res) {
stop("Mask must be binary 0/1. If it has NAs, allow.NA must be TRUE")
} else {
return(invisible(NULL))
}
} |
AdditionTCW5 <- function() {
self <- environment()
class(self) <- append('AdditionTCW5', class(self))
addNumeric <- function(x_n, y_n) x_n + y_n
addDouble <- function(x_d, y_d) x_d + y_d
addInteger <- function(x_i, y_i) x_i + y_i
divideByZero <- function(x_n) x_n / 0
generateWarning <- function(x_) suppressWarnings(1:3 + 1:7)
generateError <- function(x_) { stop('generated error'); x_ }
test_case_definitions <- data.table(
function_name = c(rep('addDouble', 9), rep('addInteger', 9), rep('divideByZero', 3), 'generateWarning', 'generateError'),
standard_evaluation = c(rep('correct', 5), 'z', rep('correct', 7), 'wrong', rep('correct', 8), 'failure'),
type_checking_enforcement = c(rep('correct', 5), 'erroneous', rep('failure', 3), rep('correct', 4), rep('failure', 5),
rep('correct', 3), 'correct', 'erroneous'),
test_case = list(
TestCaseDefinition(list(as.double(34L), 44.5), 78.5, 'sum 2 doubles'),
TestCaseDefinition(list(34.0, NA_real_), NA_real_, 'sum 1 double and 1 NA_real_'),
TestCaseDefinition(list(NA_real_, NA_real_), NA_real_, 'sum 2 NA_real_'),
TestCaseDefinition(list(NaN, NaN), NaN, 'sum 2 NAN'),
TestCaseDefinition(list(Inf, Inf), Inf, 'sum 2 Inf'),
TestCaseDefinition(list(as.integer(34.7), as.integer(44.9)), 80, 'sum 2 as.integers confused with sum of rounded value as expectation'),
TestCaseDefinition(list(34L, 44.5), 78.5, 'sum of 1 integer and 1 double'),
TestCaseDefinition(list(34.0, NA_integer_), NA_real_, 'sum of 1 integer and 1 double'),
list(NA, NA),
TestCaseDefinition(list(34L, as.integer(44.5)), 78L, 'sum 2 integers'),
TestCaseDefinition(list(34L, NA_integer_), NA_integer_, 'sum 1 integer and 1 NA_integer'),
TestCaseDefinition(list(NA_integer_, NA_integer_), NA_integer_, 'sum 2 NA_integer'),
TestCaseDefinition(list(as.integer("45.654"), 44L), 89L, 'sum a converted string with one integer'),
TestCaseDefinition(list(34L, 44.5), 78L, 'sum 1 integer and 1 double'),
TestCaseDefinition(list(34L, Inf), Inf, 'sum 1 integer and 1 Inf'),
TestCaseDefinition(list(34L, NaN), NaN, 'sum 1 integer and 1 NAN'),
TestCaseDefinition(list(34L, NA), NA, 'sum 1 integer and 1 NA'),
TestCaseDefinition(list(c(34L, 35L), 44L), c(78L, 79L), 'sum a vector of 2 integers with 1 integer'),
TestCaseDefinition(list(1), Inf, '1 / 0'),
TestCaseDefinition(list(-1), -Inf, '-1 / 0'),
TestCaseDefinition(list(0), NaN, '0 / 0'),
TestCaseDefinition(list(0), 2:8, 'generate warning'),
TestCaseDefinition(list(0), 0, 'generate error')
)
)
label <- 'erroneous test case definition: unknown evaluation keyword'
self
} |
sNCA = function(x, y, dose=0, adm="Extravascular", dur=0, doseUnit="mg", timeUnit="h", concUnit="ug/L", iAUC="", down="Linear", MW=0, returnNA=TRUE)
{
if (!(is.numeric(x) & is.numeric(y) & is.numeric(dose) & is.numeric(dur) & is.character(adm) & is.character(down))) stop("Check input types!")
n = length(x)
if (n != length(y)) stop("Length of y is different from the length of x!")
adm = toupper(adm)
if (UT(adm) == "INFUSION" & !(dur > 0)) stop("Infusion mode should have dur larger than 0!")
NApoints = is.na(x) | is.na(y)
x = x[!NApoints]
y = y[!NApoints]
RetNames1 = c("b0", "CMAX", "CMAXD", "TMAX", "TLAG", "CLST", "CLSTP", "TLST", "LAMZHL", "LAMZ",
"LAMZLL", "LAMZUL", "LAMZNPT", "CORRXY", "R2", "R2ADJ", "C0", "AUCLST", "AUCALL",
"AUCIFO", "AUCIFOD", "AUCIFP", "AUCIFPD", "AUCPEO", "AUCPEP", "AUCPBEO", "AUCPBEP",
"AUMCLST", "AUMCIFO", "AUMCIFP", "AUMCPEO", "AUMCPEP",
"MRTIVLST", "MRTIVIFO", "MRTIVIFP", "MRTEVLST", "MRTEVIFO", "MRTEVIFP",
"VZO", "VZP", "VZFO", "VZFP", "CLO", "CLP", "CLFO", "CLFP", "VSSO", "VSSP")
Res = rep(NA_real_, length(RetNames1))
names(Res) = RetNames1
if (n != length(y) | length(y[y < 0]) > 0) {
Res["LAMZNPT"] = 0
return(Res)
}
uY = unique(y)
if (length(uY) == 1) {
Res["CMAX"] = uY
if (dose > 0) Res["CMAXD"] = uY / dose
Res["TMAX"] = x[y==uY][1]
if (which(y==uY)[1] > 1) {
Res["TLAG"] = x[which(y==uY) - 1]
} else {
Res["TLAG"] = 0
}
Res["CLST"] = uY
Res["TLST"] = x[y==uY][1]
Res["LAMZNPT"] = 0
Res["b0"] = uY
return(Res)
}
iLastNonZero = max(which(y > 0))
x0 = x[1:iLastNonZero]
y0 = y[1:iLastNonZero]
x1 = x0[y0 != 0]
y1 = y0[y0 != 0]
if (UT(adm) == "BOLUS") {
if (y[1] > y[2] & y[2] > 0) {
C0 = exp(-x[1]*(log(y[2]) - log(y[1]))/(x[2] - x[1]) + log(y[1]))
} else {
C0 = y[x==min(x[y > 0])]
}
x2 = c(0, x)
y2 = c(C0, y)
x3 = c(0, x0)
y3 = c(C0, y0)
} else {
if (is.na(x[x==0][1])) {
x2 = c(0, x)
y2 = c(0, y)
x3 = c(0, x0)
y3 = c(0, y0)
} else {
x2 = x
y2 = y
x3 = x0
y3 = y0
}
}
tRes = BestSlope(x1, y1, adm)
if (length(tRes) != 9) tRes = c(NA, NA, 0, NA, NA, NA, NA, NA, NA)
Res[c("R2", "R2ADJ", "LAMZNPT", "LAMZ", "b0", "CORRXY", "LAMZLL", "LAMZUL", "CLSTP")] = tRes
tabAUC = AUC(x3, y3, down)
Res[c("AUCLST","AUMCLST")] = tabAUC[length(x3),]
Res["AUCALL"] = AUC(x2, y2, down)[length(x2),1]
Res["LAMZHL"] = log(2)/Res["LAMZ"]
Res["TMAX"] = x[which.max(y)][1]
Res["CMAX"] = max(y)
Res["TLST"] = x[iLastNonZero]
Res["CLST"] = y[iLastNonZero]
Res["AUCIFO"] = Res["AUCLST"] + Res["CLST"]/Res["LAMZ"]
Res["AUCIFP"] = Res["AUCLST"] + Res["CLSTP"]/Res["LAMZ"]
Res["AUCPEO"] = (1 - Res["AUCLST"]/Res["AUCIFO"])*100
Res["AUCPEP"] = (1 - Res["AUCLST"]/Res["AUCIFP"])*100
Res["AUMCIFO"] = Res["AUMCLST"] + Res["CLST"]*Res["TLST"]/Res["LAMZ"] + Res["CLST"]/Res["LAMZ"]/Res["LAMZ"]
Res["AUMCIFP"] = Res["AUMCLST"] + Res["CLSTP"]*Res["TLST"]/Res["LAMZ"] + Res["CLSTP"]/Res["LAMZ"]/Res["LAMZ"]
Res["AUMCPEO"] = (1 - Res["AUMCLST"]/Res["AUMCIFO"])*100
Res["AUMCPEP"] = (1 - Res["AUMCLST"]/Res["AUMCIFP"])*100
if (!is.na(dose) & dose > 0) {
Res["CMAXD"] = Res["CMAX"]/dose
Res["AUCIFOD"] = Res["AUCIFO"]/dose
Res["AUCIFPD"] = Res["AUCIFP"]/dose
}
if (UT(adm) == "BOLUS") {
Res["C0"] = C0
Res["AUCPBEO"] = tabAUC[2,1]/Res["AUCIFO"]*100
Res["AUCPBEP"] = tabAUC[2,1]/Res["AUCIFP"]*100
} else {
if (sum(y0==0) > 0) Res["TLAG"] = x0[max(which(y0==0))]
else Res["TLAG"] = 0
if (!is.na(x0[x0==0][1])) {
if (y0[x0==0] > 0) Res["TLAG"] = 0
}
}
if (UT(adm) == "EXTRAVASCULAR") {
Res["VZFO"] = dose/Res["AUCIFO"]/Res["LAMZ"]
Res["VZFP"] = dose/Res["AUCIFP"]/Res["LAMZ"]
Res["CLFO"] = dose/Res["AUCIFO"]
Res["CLFP"] = dose/Res["AUCIFP"]
Res["MRTEVLST"] = Res["AUMCLST"]/Res["AUCLST"]
Res["MRTEVIFO"] = Res["AUMCIFO"]/Res["AUCIFO"]
Res["MRTEVIFP"] = Res["AUMCIFP"]/Res["AUCIFP"]
} else {
Res["VZO"] = dose/Res["AUCIFO"]/Res["LAMZ"]
Res["VZP"] = dose/Res["AUCIFP"]/Res["LAMZ"]
Res["CLO"] = dose/Res["AUCIFO"]
Res["CLP"] = dose/Res["AUCIFP"]
Res["MRTIVLST"] = Res["AUMCLST"]/Res["AUCLST"] - dur/2
Res["MRTIVIFO"] = Res["AUMCIFO"]/Res["AUCIFO"] - dur/2
Res["MRTIVIFP"] = Res["AUMCIFP"]/Res["AUCIFP"] - dur/2
Res["VSSO"] = Res["MRTIVIFO"]*Res["CLO"]
Res["VSSP"] = Res["MRTIVIFP"]*Res["CLP"]
}
Units = Unit(doseUnit=doseUnit, timeUnit=timeUnit, concUnit=concUnit, MW=MW)
for (i in 1:length(Res)) Res[i] = Res[i] * Units[names(Res[i]),2]
if (is.data.frame(iAUC)) {
niAUC = nrow(iAUC)
if (niAUC > 0) {
RetNames = union(RetNames1, as.character(iAUC[,"Name"]))
for (i in 1:niAUC) {
if (adm == "BOLUS") Res[as.character(iAUC[i,"Name"])] = IntAUC(x2, y2, iAUC[i,"Start"], iAUC[i,"End"], Res, down=down)
else Res[as.character(iAUC[i,"Name"])] = IntAUC(x, y, iAUC[i,"Start"], iAUC[i,"End"], Res, down=down)
}
}
} else {
niAUC = 0
}
attr(Res, "units") = c(Units[RetNames1,1], rep(Units["AUCLST",1], niAUC))
if (returnNA == FALSE) {
strAttr = attr(Res, "units")
iNotNAs = !is.na(Res)
Res = Res[iNotNAs]
attr(Res, "units") = strAttr[iNotNAs]
}
return(Res)
} |
"ar_stl_wardsClipped" |
context("InputContext")
options('rdhoc_hack' = TRUE)
ic <- InputContext(dummy, dataFilename_s_1 = 'dummy.R')
ic$setUseMarkers(TRUE)
test_that("InputContext - data", {
expect_true(nchar(ic$produceFormat()) > 3L)
expect_true(!is.null(ic$produceSource()))
expect_true(is.character(ic$getName()))
})
ic$setUseMarkers(FALSE)
test_that("InputContext - data", {
expect_true(nchar(ic$produceFormat()) > 3L)
expect_true(is.null(ic$produceSource()))
})
ic1 <- InputContext(ProcessingContext(), methodName_s_1 = 'verifyPostProcessing')
ic1$setUseMarkers(TRUE)
ic2 <- InputContext(ProcessingContext())
test_that("InputContext", {
expect_true(nchar(ic1$produceDescription()) > 3L)
expect_true(nchar(ic2$produceDescription()) > 3L)
expect_true(is.null(ic2$produceSource()))
expect_true(is.null(ic2$produceFormat()))
expect_true(is.character(ic1$getName()))
expect_true(is.character(ic2$getName()))
})
options('rdhoc_hack' = FALSE)
source_file <- 'Addition_TCFI_Partial_R6.R'
source_package <- 'wyz.code.offensiveProgramming'
f <- findFilesInPackage(source_file, source_package)
stopifnot(length(f) == 1)
source(f)
o <- Addition_TCFI_Partial_R6$new()
ic3 <- InputContext(o, methodName_s_1 = 'addInteger')
ic3$setUseMarkers(TRUE)
ic4 <- InputContext(o)
ic4$setUseMarkers(TRUE)
test_that("InputContext", {
expect_true(nchar(ic3$produceDescription()) > 3L)
expect_true(nchar(ic4$produceDescription()) > 3L)
})
source_file <- 'sample-classes.R'
f <- findFilesInPackage(source_file, source_package)
stopifnot(length(f) == 1)
source(f)
o <- EmptyEnv()
ic5 <- InputContext(o, methodName_s_1 = 'addInteger')
ic5$setUseMarkers(TRUE)
ic6 <- InputContext(Accumulator_R6$new(), methodName_s_1 = 'addInteger')
ic6$setUseMarkers(FALSE)
ic7 <- InputContext(NULL, 'sum', packageName_s_1 = 'slot')
ic7$setUseMarkers(TRUE)
test_that("InputContext", {
expect_true(nchar(ic5$produceDescription()) > 3L)
expect_true(is.null(ic6$produceDescription()))
expect_true(is.character(InputContext(NULL, packageName_s_1 = 'slot')$getName()))
expect_true(is.character(ic7$getName()))
expect_true(is.character(ic7$produceDescription()))
}) |
sim.mutants <-
function(n.sites, essential, n.sites2=NULL, n.mutants)
{
n.genes <- length(n.sites)
if(length(essential) != n.genes)
stop("n.sites and essential must be the same length")
if(is.null(n.sites2)) n.sites2 <- rep(0,n.genes)
if(length(n.sites2) != n.genes)
stop("n.sites and n.sites2 must be the same length")
if(any(essential != 0 & essential != 1))
stop("essential must contain only 0's and 1's.")
if(n.mutants <= 0)
stop("n.mutants must be positive")
temp <- c(essential[-1],essential[1])
p <- c(n.sites*(1-essential), n.sites2*(1-essential)*(1-temp))
o <- table(factor(sample(1:(2*n.genes), n.mutants, replace=TRUE,
prob=p), levels=1:(2*n.genes)))
names(o) <- NULL
if(sum(n.sites2)==0) return(o[1:n.genes])
else return(cbind(o[1:n.genes],o[-(1:n.genes)]))
} |
reformat.snps <- function(snps){
snps <- as.character(snps)
tmp1 <- suppressWarnings(which(!is.na(as.integer(gsub(':', '', snps)))))
tmp2 <- which(substr(snps, 1, 1) != ':')
tmp3 <- which(sapply(base::strsplit(snps, ''), tail, 1) != ':')
tmp4 <- grep(':', snps)
non.rs.id <- intersect(intersect(intersect(tmp1, tmp2), tmp3), tmp4)
if(length(non.rs.id) > 0){
snps[non.rs.id] <- paste0('C', snps[non.rs.id])
snps[non.rs.id] <- gsub(':', 'P', snps[non.rs.id])
}
snps
} |
test_that("SA solver works on specific test", {
solver <- annealing_solver(initial_temperature = 10)
g <- igraph::make_ring(5)
V(g)$weight <- 1:-3
E(g)$weight <- 1
solution <- solve_mwcsp(solver, g)
expect_equal(solution$weight, 2)
})
test_that("The SA solver does not crush on GAM instances", {
solver <- annealing_solver()
solution <- solve_mwcsp(solver, gam_example)
expect_gte(length(V(solution$graph)), 0)
})
test_that("The SA solver gives a good solution for a GAM instance", {
solver <- annealing_solver(schedule = "boltzmann",
initial_temperature = 2.0, final_temperature = 0.125)
solution <- solve_mwcsp(solver, gam_example)
expect_gt(solution$weight, 200)
}) |
obj_L12 <-
function(Y, mu, p, L, covmat_inverse, S_bar, graph, lambda1, lambda2, pie) {
log.liklyhood <- 0.0
liklyhood = 0.0
penalty <- 0.0
n=nrow(Y)
nn = round(pie*n, 0)
for (j in 1:n){
liklyhood = 0.0
for (l in 1:L){
tmp_covmat <- covmat_inverse[,((l-1)*p+1):(l*p)]
liklyhood = liklyhood + pie[l] * exp(fmvnorm(p, tmp_covmat, Y[j,], mu[l,]))
}
log.liklyhood = log.liklyhood + log(liklyhood)
}
for (l in 1:L) {
tmp_covmat <- covmat_inverse[,((l-1)*p+1):(l*p)]
tmp_S <- S_bar[,((l-1)*p+1):(l*p)]
penalty <- penalty + lambda1 * (sum(apply(abs(tmp_covmat),2,sum)) - sum(abs(diag(tmp_covmat))))
}
graph <- graph + 1
Num.of.edges <- dim(graph)[2]
for (e in 1:Num.of.edges) {
l1 <- graph[1,e]
l2 <- graph[2,e]
tmp_covmat <- covmat_inverse[,((l1-1)*p+1):(l1*p)] - covmat_inverse[,((l2-1)*p+1):(l2*p)]
penalty <- penalty + lambda2 * (sum(apply(abs(tmp_covmat),1,sum)) - sum(abs(diag(tmp_covmat))))
}
return (log.liklyhood - penalty)
} |
test_that("tune creates a call", {
expect_true(is.call(tune()))
expect_true(is.call(tune("foo")))
})
test_that("tune `id` value", {
expect_identical(tune(), call("tune"))
expect_identical(tune(""), call("tune"))
expect_identical(tune("foo"), call("tune", "foo"))
})
test_that("`id` is validated", {
expect_error(tune(1), "The `id` should be a single character string.")
expect_error(tune(c("x", "y")), "The `id` should be a single character string.")
expect_error(tune(NA_character_), "The `id` can't be missing.")
}) |
residenceTime <- function(lt, radius, maxt, addinfo=FALSE,
units = c("seconds", "hours", "days"))
{
if (!inherits(lt, "ltraj"))
stop("lt should be of class ltraj")
if (length(radius)>1)
stop("Only one radius allowed in this function")
units <- match.arg(units)
if (units == "hours")
maxt <- maxt*3600
if (units == "days")
maxt <- maxt*(3600 * 24)
res <- lapply(1:length(lt), function(i) {
x <- lt[[i]]
uu <- x$date
vv <- .Call("residtime", x, radius, maxt, PACKAGE="adehabitatLT")
if (all(is.na(vv)))
warning(paste("Too large radius for burst", burst(lt)[i],"\n",
"The residence time is missing for all the relocations of this burst\n"))
z <- data.frame(uu,vv)
names(z) <- c("Date", paste("RT", format(radius, scientific=FALSE), sep="."))
return(z)
})
if (addinfo) {
res <- lapply(res, function(x) {
x <- data.frame(x[,2])
names(x) <- paste("RT", format(radius, scientific=FALSE), sep=".")
return(x)
})
if (!is.null(infolocs(lt))) {
il <- infolocs(lt)
res <- lapply(1:length(il), function(j) {
cbind(il[[j]], res[[j]])
})
}
infolocs(lt) <- res
res <- lt
} else {
names(res) <- burst(lt)
class(res) <- "resiti"
attr(res, "radius") <- radius
attr(res, "maxt") <- maxt
}
return(res)
}
print.resiti <- function(x, ...)
{
cat("*****************************\n")
cat("* Object of class resiti\n")
cat("* (residence time method)\n\n")
cat("Radius =", attr(x, "radius"), "\n")
cat("Maximum time allowed before coming back in the circle =", attr(x, "maxt"), "seconds\n")
cat("This object is a list of data.frames.\nThe following bursts are available:\n")
cat(paste("$", names(x), "\n", sep=""))
}
plot.resiti <- function(x, addpoints=FALSE, addlines=TRUE, ...)
{
par(mfrow=n2mfrow(length(x)))
tmp <- lapply(1:length(x), function(i) {
y <- x[[i]]
plot(y[,1], y[,2], ty="n", xlab="Date",
ylab=paste("Residence Time in a circle of", attr(x, "radius")),
main=names(x)[i])
if (addpoints) {
points(y[,1], y[,2], pch=16, ...)
}
if (addlines)
lines(y[,1], y[,2])
})
} |
expected <- eval(parse(text="structure(c(0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667), .Dim = c(9L, 1L))"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667), .Dim = c(1L, 9L)), c(2L, 1L), TRUE)"));
.Internal(aperm(argv[[1]], argv[[2]], argv[[3]]));
}, o=expected); |
aggts <- function(y, levels, forecasts = TRUE) {
if (!is.gts(y)) {
stop("Argument y must be either a hts or gts object.", call. = FALSE)
}
if (!forecasts) {
y$bts <- y$histy
}
if (is.hts(y)) {
gmat <- GmatrixH(y$nodes)
labels <- y$labels
} else {
gmat <- y$groups
labels <- c("Total", y$labels, list(colnames(y$bts)))
}
if (missing(levels)) {
levels <- 1L:nrow(gmat)
} else {
if (is.character(levels)) {
levels <- which(names(y$labels) %in% levels)
}
levels <- as.integer(levels) + 1L
}
rSum <- function(x) rowsum(t(y$bts), gmat[x, ], reorder = FALSE)
ally <- lapply(levels, rSum)
ally <- matrix(unlist(sapply(ally, t)), nrow = nrow(y$bts))
colnames(ally) <- unlist(labels[levels])
tsp.y <- stats::tsp(y$bts)
ally <- ts(ally, start = tsp.y[1L], frequency = tsp.y[3L])
class(ally) <- class(y$bts)
attr(ally, "msts") <- attr(y$bts, "msts")
return(ally)
}
allts <- function(y, forecasts = TRUE) {
if (!is.gts(y)) {
stop("Argument y must be either a hts or gts object.", call. = FALSE)
}
aggts(y = y, forecasts = forecasts)
} |
context("count lines")
f1 <- system.file(package = "fpeek", "datafiles", "cigfou-ISO-8859-1.txt")
f2 <- system.file(package = "fpeek", "datafiles", "ISO-8859-1.txt")
test_that("ckeck number of lines without eof", {
expect_equal(peek_count_lines(f1), 24)
expect_equal(peek_count_lines(f2), 0)
})
test_that("ckeck number of lines with eof", {
expect_equal(peek_count_lines(f1, with_eof = TRUE), 25)
expect_equal(peek_count_lines(f2, with_eof = TRUE), 1)
}) |
library(tm)
library(tm.plugin.webmining)
data(yahoonews)
options(width = 60)
class(yahoonews)
yahoonews
meta(yahoonews[[1]], "description") <-
paste(substring(meta(yahoonews[[1]], "description"), 1, 70), "...", sep = "")
meta(yahoonews[[1]], "id") <-
paste(substring(meta(yahoonews[[1]], "id"), 1, 70), "...", sep = "")
meta(yahoonews[[1]], "origin") <-
paste(substring(meta(yahoonews[[1]], "origin"), 1, 70), "...", sep = "")
meta(yahoonews[[1]])
content(yahoonews[[1]]) <-
paste(substring(yahoonews[[1]], 1, 100), "...", sep = "")
yahoonews[[1]] |
library("robustbase")
data("coleman")
tuning <- list(tuning.psi = c(3.443689, 4.685061))
cvTuning(lmrob, formula = Y ~ ., data = coleman, tuning = tuning,
cost = rtmspe, K = 5, R = 10, costArgs = list(trim = 0.1),
seed = 1234)
call <- call("lmrob", formula = Y ~ .)
cvTuning(call, data = coleman, y = coleman$Y, tuning = tuning,
cost = rtmspe, K = 5, R = 10, costArgs = list(trim = 0.1),
seed = 1234) |
bw.gwr<-function(formula, data, approach="CV",kernel="bisquare",adaptive=FALSE, p=2, theta=0,
longlat=F,dMat,parallel.method=F,parallel.arg=NULL)
{
if (is(data, "Spatial"))
{
dp.locat<-coordinates(data)
data <- as(data, "data.frame")
}
else
{
stop("Given regression data must be Spatial*DataFrame")
}
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")
x <- model.matrix(mt, mf)
dp.n<-nrow(data)
if(dp.n>1500)
{
cat("Take a cup of tea and have a break, it will take a few minutes.\n")
cat(" -----A kind suggestion from GWmodel development group\n")
}
if (missing(dMat))
{
dMat <- NULL
DM.given<-F
if(dp.n + dp.n <= 10000)
{
dMat <- gw.dist(dp.locat=dp.locat, rp.locat=dp.locat, p=p, theta=theta, longlat=longlat)
DM.given<-T
}
}
else
{
DM.given<-T
dim.dMat<-dim(dMat)
if (dim.dMat[1]!=dp.n||dim.dMat[2]!=dp.n)
stop ("Dimensions of dMat are not correct")
}
if(adaptive)
{
upper<-dp.n
lower<-20
}
else
{
if(DM.given)
{
upper<-range(dMat)[2]
lower<-upper/5000
}
else
{
dMat<-NULL
if (p==2)
{
b.box<-bbox(dp.locat)
upper<-sqrt((b.box[1,2]-b.box[1,1])^2+(b.box[2,2]-b.box[2,1])^2)
lower<-upper/5000
}
else
{
upper<-0
for (i in 1:dp.n)
{
dist.vi<-gw.dist(dp.locat=dp.locat, focus=i, p=p, theta=theta, longlat=longlat)
upper<-max(upper, range(dist.vi)[2])
}
lower<-upper/5000
}
}
}
bw<-NA
if (parallel.method == "cluster") {
if (missing(parallel.arg)) {
cl.n <- max(detectCores() - 4, 2)
parallel.arg <- makeCluster(cl.n)
} else cl.n <- length(parallel.arg)
clusterCall(parallel.arg, function() { library(GWmodel) })
}
if(approach == "bic" || approach == "BIC")
bw <- gold(gwr.bic, lower, upper, adapt.bw = adaptive, x, y, kernel, adaptive, dp.locat, p, theta, longlat, dMat, T, parallel.method, parallel.arg)
else if(approach == "aic" || approach == "AIC" || approach == "AICc")
bw <- gold(gwr.aic, lower, upper, adapt.bw = adaptive, x, y, kernel, adaptive, dp.locat, p, theta, longlat, dMat, T, parallel.method, parallel.arg)
else
bw <- gold(gwr.cv, lower, upper, adapt.bw = adaptive, x, y, kernel, adaptive, dp.locat, p, theta, longlat, dMat, T, parallel.method, parallel.arg)
if (parallel.method == "cluster") {
if (missing(parallel.arg)) stopCluster(parallel.arg)
}
bw
}
gwr.cv<-function(bw, X, Y, kernel="bisquare",adaptive=FALSE, dp.locat, p=2, theta=0, longlat=F,dMat, verbose=T,parallel.method=F,parallel.arg=NULL)
{
dp.n<-length(dp.locat[,1])
if (missing(dMat)) dMat <- matrix(0, 0, 0)
else if (is.null(dMat) || !is.matrix(dMat)) {
DM.given<-F
dMat <- matrix(0, 0, 0)
}
else {
DM.given<-T
dim.dMat<-dim(dMat)
if (dim.dMat[1]!=dp.n||dim.dMat[2]!=dp.n)
stop ("Dimensions of dMat are not correct")
}
gw.resi <- NULL
if (parallel.method == FALSE) {
gw.resi <- try(gw_cv_all(X, Y, dp.locat, DM.given, dMat, p, theta, longlat, bw, kernel, adaptive))
if(!inherits(gw.resi, "try-error")) CV.score <- gw.resi
else CV.score <- Inf
} else if (parallel.method == "omp") {
if (missing(parallel.arg)) { threads <- 0 } else {
threads <- ifelse(is(parallel.arg, "numeric"), parallel.arg, 0)
}
gw.resi <- try(gw_cv_all_omp(X, Y, dp.locat, DM.given, dMat, p, theta, longlat, bw, kernel, adaptive, threads))
if(!inherits(gw.resi, "try-error")) CV.score <- gw.resi
else CV.score <- Inf
} else if (parallel.method == "cuda") {
if (missing(parallel.arg)) { groupl <- 0 } else {
groupl <- ifelse(is(parallel.arg, "numeric"), parallel.arg, 0)
}
gw.resi <- try(gw_cv_all_cuda(X, Y, dp.locat, DM.given, dMat, p, theta, longlat, bw, kernel, adaptive, groupl))
if(!inherits(gw.resi, "try-error")) CV.score <- gw.resi
else CV.score <- Inf
} else if (parallel.method == "cluster") {
print("Parallel using cluster.")
cl.n <- length(parallel.arg)
cl.results <- clusterApplyLB(parallel.arg, 1:cl.n, function(group.i, cl.n, x, y, dp.locat, DM.given, dMat, p, theta, longlat, bw, kernel, adaptive) {
cv.result <- try(gw_cv_all(x, y, dp.locat, DM.given, dMat, p, theta, longlat, bw, kernel, adaptive, cl.n, group.i))
if(!inherits(gw.resi, "try-error")) return(cv.result)
else return(Inf)
}, cl.n, X, Y, dp.locat, DM.given, dMat, p, theta, longlat, bw, kernel, adaptive)
gw.resi <- unlist(cl.results)
if (!all(is.infinite(gw.resi))) CV.score <- sum(gw.resi)
else CV.score <- Inf
} else {
CV<-numeric(dp.n)
for (i in 1:dp.n) {
if (DM.given) dist.vi<-dMat[,i]
else dist.vi<-gw.dist(dp.locat=dp.locat, focus=i, p=p, theta=theta, longlat=longlat)
W.i<-gw.weight(dist.vi,bw,kernel,adaptive)
W.i[i]<-0
gw.resi<- try(gw_reg(X, Y, W.i, FALSE, i))
if(!inherits(gw.resi, "try-error")) {
yhat.noi<-X[i,]%*%gw.resi[[1]]
CV[i]<-Y[i]-yhat.noi
} else {
CV[i]<-Inf
break
}
}
if (!any(is.infinite(CV))) CV.score<-t(CV) %*% CV
else CV.score<-Inf
}
if(verbose) {
if(adaptive) cat("Adaptive bandwidth:", bw, "CV score:", CV.score, "\n")
else cat("Fixed bandwidth:", bw, "CV score:", CV.score, "\n")
}
ifelse(is.nan(CV.score), Inf, CV.score)
}
gwr.cv.contrib<-function(bw, X, Y, kernel="bisquare",adaptive=FALSE, dp.locat, p=2, theta=0, longlat=F,dMat,parallel.method=F,parallel.arg=NULL)
{
dp.n<-length(dp.locat[,1])
if (is.null(dMat)) DM.given<-F
else {
if(dim(dMat)[1]==1) {
DM.given <- F
} else {
DM.given<-T
dim.dMat<-dim(dMat)
if (dim.dMat[1]!=dp.n||dim.dMat[2]!=dp.n)
stop("Dimensions of dMat are not correct")
}
}
CV<-numeric(dp.n)
for (i in 1:dp.n)
{
if (DM.given)
dist.vi<-dMat[,i]
else
{
dist.vi<-gw.dist(dp.locat=dp.locat, focus=i, p=p, theta=theta, longlat=longlat)
}
W.i<-gw.weight(dist.vi,bw,kernel,adaptive)
W.i[i]<-0
gw.resi<- try(gw_reg(X, Y, W.i, FALSE, i))
if(!inherits(gw.resi, "try-error"))
{
yhat.noi <- X[i,] %*% gw.resi[[1]]
CV[i] <- Y[i] - yhat.noi
}
else
{
CV[i]<-Inf
break
}
}
CV
}
gwr.aic<-function(bw, X, Y, kernel="bisquare",adaptive=FALSE, dp.locat, p=2, theta=0, longlat=F,dMat, verbose=T,parallel.method=F,parallel.arg=NULL)
{
dp.n<-length(dp.locat[,1])
var.n <- ncol(X)
if (missing(dMat)) {
DM.given <- F
dMat <- matrix(0, 0, 0)
}
else if (is.null(dMat) || !is.matrix(dMat)) {
DM.given<-F
dMat <- matrix(0, 0, 0)
}
else {
DM.given<-T
dim.dMat<-dim(dMat)
if (dim.dMat[1]!=dp.n||dim.dMat[2]!=dp.n)
stop ("Dimensions of dMat are not correct")
}
AICc.value <- Inf
if (parallel.method == FALSE) {
res <- try(gw_reg_all(X, Y, dp.locat, FALSE, dp.locat, DM.given, dMat, TRUE, p, theta, longlat, bw, kernel, adaptive))
if(!inherits(res, "try-error")) {
betas <- res$betas
s_hat <- res$s_hat
AICc.value <- AICc1(Y, X, betas, s_hat)
}
else AICc.value <- Inf
} else if (parallel.method == "omp") {
if (missing(parallel.arg)) { threads <- 0 } else {
threads <- ifelse(is(parallel.arg, "numeric"), parallel.arg, 0)
}
res <- try(gw_reg_all_omp(X, Y, dp.locat, FALSE, dp.locat, DM.given, dMat, TRUE, p, theta, longlat, bw, kernel, adaptive, threads))
if(!inherits(res, "try-error")) {
betas <- res$betas
s_hat <- res$s_hat
AICc.value <- AICc1(Y, X, betas, s_hat)
}
else AICc.value <- Inf
} else if (parallel.method == "cuda") {
if (missing(parallel.arg)) { groupl <- 0 } else {
groupl <- ifelse(is(parallel.arg, "numeric"), parallel.arg, 0)
}
res <- try(gw_reg_all_cuda(X, Y, dp.locat, FALSE, dp.locat, DM.given, dMat, TRUE, p, theta, longlat, bw, kernel, adaptive, groupl))
if(!inherits(res, "try-error")) {
betas <- res$betas
s_hat <- res$s_hat
AICc.value <- AICc1(Y, X, betas, s_hat)
}
else AICc.value <- Inf
} else if (parallel.method == "cluster") {
cl.n <- length(parallel.arg)
cl.results <- clusterApplyLB(parallel.arg, 1:cl.n, function(group.i, cl.n, x, y, dp.locat, DM.given, dMat, p, theta, longlat, bw, kernel, adaptive) {
res <- try(gw_reg_all(x, y, dp.locat, FALSE, dp.locat, DM.given, dMat, TRUE, p, theta, longlat, bw, kernel, adaptive, cl.n, group.i))
if(!inherits(res, "try-error")) return(res)
else return(NULL)
}, cl.n, X, Y, dp.locat, DM.given, dMat, p, theta, longlat, bw, kernel, adaptive)
if (!any(is.null(cl.results))) {
betas <- matrix(0, nrow = dp.n, ncol=var.n)
s_hat <- numeric(2)
for (i in 1:cl.n) {
res <- cl.results[[i]]
betas = betas + res$betas
s_hat = s_hat + res$s_hat
}
AICc.value <- AICc1(Y, X, betas, s_hat)
} else AICc.value <- Inf
} else {
s_hat <- numeric(2)
betas <- matrix(nrow = dp.n, ncol = var.n)
for (i in 1:dp.n) {
if (DM.given) dist.vi <- dMat[,i]
else dist.vi <- gw.dist(dp.locat=dp.locat, focus=i, p=p, theta=theta, longlat=longlat)
W.i <- gw.weight(dist.vi,bw,kernel,adaptive)
res<- try(gw_reg(X,Y,W.i,TRUE,i))
if(!inherits(res, "try-error")) {
si <- res[[2]]
s_hat[1] = s_hat[1] + si[i]
s_hat[2] = s_hat[2] + sum(tcrossprod(si))
betas[i,] <- res[[1]]
} else {
s_hat[1] <- Inf
s_hat[2] <- Inf
break
}
}
if (!any(is.infinite(s_hat))) {
AICc.value <- AICc1(Y, X, betas, s_hat)
} else AICc.value<-Inf
}
if(is.nan(AICc.value)) AICc.value <- Inf
if(verbose) {
if(adaptive) cat("Adaptive bandwidth (number of nearest neighbours):", bw, "AICc value:", AICc.value, "\n")
else cat("Fixed bandwidth:", bw, "AICc value:", AICc.value, "\n")
}
AICc.value
}
gwr.bic<-function(bw, X, Y, kernel="bisquare",adaptive=FALSE, dp.locat, p=2, theta=0, longlat=F,dMat, verbose=T,parallel.method=F,parallel.arg=NULL)
{
dp.n<-length(dp.locat[,1])
var.n <- ncol(X)
if (missing(dMat)) {
DM.given <- F
dMat <- matrix(0, 0, 0)
}
else if (is.null(dMat) || !is.matrix(dMat)) {
DM.given<-F
dMat <- matrix(0, 0, 0)
}
else {
DM.given<-T
dim.dMat<-dim(dMat)
if (dim.dMat[1]!=dp.n||dim.dMat[2]!=dp.n)
stop ("Dimensions of dMat are not correct")
}
BIC.value <- Inf
if (parallel.method == FALSE) {
res <- try(gw_reg_all(X, Y, dp.locat, FALSE, dp.locat, DM.given, dMat, TRUE, p, theta, longlat, bw, kernel, adaptive))
if(!inherits(res, "try-error")) {
betas <- res$betas
s_hat <- res$s_hat
BIC.value <- gw_BIC(Y, X, betas, s_hat)
}
else BIC.value <- Inf
} else if (parallel.method == "omp") {
if (missing(parallel.arg)) { threads <- 0 } else {
threads <- ifelse(is(parallel.arg, "numeric"), parallel.arg, 0)
}
res <- try(gw_reg_all_omp(X, Y, dp.locat, FALSE, dp.locat, DM.given, dMat, TRUE, p, theta, longlat, bw, kernel, adaptive, threads))
if(!inherits(res, "try-error")) {
betas <- res$betas
s_hat <- res$s_hat
BIC.value <- gw_BIC(Y, X, betas, s_hat)
}
else BIC.value <- Inf
} else if (parallel.method == "cuda") {
if (missing(parallel.arg)) { groupl <- 0 } else {
groupl <- ifelse(is(parallel.arg, "numeric"), parallel.arg, 0)
}
res <- try(gw_reg_all_cuda(X, Y, dp.locat, FALSE, dp.locat, DM.given, dMat, TRUE, p, theta, longlat, bw, kernel, adaptive, groupl))
if(!inherits(res, "try-error")) {
betas <- res$betas
s_hat <- res$s_hat
BIC.value <- gw_BIC(Y, X, betas, s_hat)
}
else BIC.value <- Inf
} else if (parallel.method == "cluster") {
cl.n <- length(parallel.arg)
cl.results <- clusterApplyLB(parallel.arg, 1:cl.n, function(group.i, cl.n, x, y, dp.locat, DM.given, dMat, p, theta, longlat, bw, kernel, adaptive) {
res <- try(gw_reg_all(x, y, dp.locat, FALSE, dp.locat, DM.given, dMat, TRUE, p, theta, longlat, bw, kernel, adaptive, cl.n, group.i))
if(!inherits(res, "try-error")) return(res)
else return(NULL)
}, cl.n, X, Y, dp.locat, DM.given, dMat, p, theta, longlat, bw, kernel, adaptive)
if (!any(is.null(cl.results))) {
betas <- matrix(0, nrow = dp.n, ncol=var.n)
s_hat <- numeric(2)
for (i in 1:cl.n) {
res <- cl.results[[i]]
betas = betas + res$betas
s_hat = s_hat + res$s_hat
}
BIC.value <- gw_BIC(Y, X, betas, s_hat)
} else BIC.value <- Inf
} else {
s_hat <- numeric(2)
betas <- matrix(nrow = dp.n, ncol = var.n)
for (i in 1:dp.n) {
if (DM.given) dist.vi <- dMat[,i]
else dist.vi <- gw.dist(dp.locat=dp.locat, focus=i, p=p, theta=theta, longlat=longlat)
W.i <- gw.weight(dist.vi,bw,kernel,adaptive)
res<- try(gw_reg(X,Y,W.i,TRUE,i))
if(!inherits(res, "try-error")) {
si <- res[[2]]
s_hat[1] = s_hat[1] + si[i]
s_hat[2] = s_hat[2] + sum(tcrossprod(si))
betas[i,] <- res[[1]]
} else {
s_hat[1] <- Inf
s_hat[2] <- Inf
break
}
}
if (!any(is.infinite(s_hat))) {
BIC.value <- gw_BIC(Y, X, betas, s_hat)
} else BIC.value <-Inf
}
if(is.nan(BIC.value)) BIC.value <- Inf
if(verbose) {
if(adaptive) cat("Adaptive bandwidth (number of nearest neighbours):", bw, "BIC value:", BIC.value, "\n")
else cat("Fixed bandwidth:", bw, "BIC value:", BIC.value, "\n")
}
BIC.value
}
gold<-function(fun,xL,xU,adapt.bw=F,...){
eps=1e-4
R <- (sqrt(5)-1)/2
iter <- 1
d <- R*(xU-xL)
if (adapt.bw)
{
x1 <- floor(xL+d)
x2 <- round(xU-d)
}
else
{
x1 <- xL+d
x2 <- xU-d
}
f1 <- eval(fun(x1,...))
f2 <- eval(fun(x2,...))
d1<-f2-f1
if (f1 < f2)
xopt <- x1
else xopt <- x2
ea <- 100
while ((abs(d) > eps) && (abs(d1) > eps)) {
d <- R*d
if (f1 < f2) {
xL <- x2
x2 <- x1
if (adapt.bw)
x1 <- round(xL+d)
else
x1 <- xL+d
f2 <- f1
f1 <- eval(fun(x1,...))
}
else {
xU <- x1
x1 <- x2
if (adapt.bw)
x2 <- floor(xU - d)
else
x2 <- xU - d
f1 <- f2
f2 <- eval(fun(x2,...))
}
iter <- iter + 1
if (f1 < f2)
xopt <- x1
else xopt <- x2
d1<-f2-f1
}
xopt
} |
library("RUnit")
library("chngpt")
test.hinge.test <- function() {
suppressWarnings(RNGversion("3.5.0"))
RNGkind("Mersenne-Twister", "Inversion")
tolerance=1e-6
if((file.exists("D:/gDrive/3software/_checkReproducibility") | file.exists("~/_checkReproducibility")) & R.Version()$system %in% c("x86_64, mingw32","x86_64, linux-gnu")) tolerance=1e-6
verbose=0
dat=sim.hinge(threshold.type = 'NA',family = 'binomial',thres='NA',X.ditr = 'norm',mu.X = c(0,0,0),coef.X = c(0,.5,.5,.4),cov.X = diag(3),eps.sd = 1,seed = 1,n=100)
test=hinge.test(Y~X1+X2, "x", family="binomial", data=dat, thres = NA,lb.quantile=.1,ub.quantile=.9,chngpts.cnt=10,'method'='FDB',boot.B=1e2); test$p.value
checkEqualsNumeric(test$p.value, 0.70, tolerance=tolerance)
test=hinge.test(Y~X1+X2, "x", family="binomial", data=dat, thres = NA,lb.quantile=.1,ub.quantile=.9,chngpts.cnt=10,'method'='B',boot.B=1e2); test$p.value
checkEqualsNumeric(test$p.value, 0.76, tolerance=tolerance)
dat=sim.hinge(threshold.type = 'NA',family = 'gaussian',thres='NA',X.ditr = 'norm',mu.X = c(0,0,0),coef.X = c(0,.5,.5,.5),cov.X = diag(3),eps.sd = 1,seed = 1,n=100)
test=hinge.test(Y~X1+X2, "x", family="gaussian", data=dat, thres = NA,lb.quantile=.1,ub.quantile=.9,chngpts.cnt=10,'method'='B',boot.B=1e2); test$p.value
checkEqualsNumeric(test$p.value, .9,tolerance=tolerance)
test=hinge.test(Y~X1+X2, "x", family="gaussian", data=dat, thres = NA,lb.quantile=.1,ub.quantile=.9,chngpts.cnt=10,'method'='FDB',boot.B=1e2); test$p.value
checkEqualsNumeric(test$p.value, .97,tolerance=tolerance)
} |
UseProbability <- R6::R6Class(
classname = "UseProbability",
inherit = SummaryFunction,
portable = TRUE,
public = list(
initialize = function() {
super$initialize(c("ROC", "Sens", "Spec", "Kappa", "Accuracy", "TCR_9", "MCC", "PPV"))
},
execute = function(data, lev = NULL, model = NULL) {
lvls <- levels(data$obs)
if (length(lvls) > 2)
stop("[", class(self)[1], "][FATAL] Your outcome has ", length(lvls),
" levels. The 'UseProbability' function is not appropriate. Aborting...")
if (!all(levels(data[, "pred"]) == lvls))
stop("[", class(self)[1], "][FATAL] Levels of observed and predicted data ",
"do not match. Aborting...")
data$y = as.numeric(data$obs == lvls[2])
data$z = as.numeric(data$pred == lvls[2])
rocAUC <- ModelMetrics::auc(ifelse(data$obs == lev[2], 0, 1), data[, lvls[1]])
confMat <- caret::confusionMatrix(table(data$z, data$y), positive = "1")
mcc <- mltools::mcc(TP = confMat$table[1, 1], FP = confMat$table[1, 2], TN = confMat$table[2, 2], FN = confMat$table[2, 1])
ppv <- (confMat$table[1, 1] / (confMat$table[1, 1] + confMat$table[1, 2]))
fn_tcr_9 <- (9 * confMat$table[1, 2] + confMat$table[2, 1]) / (9 * (confMat$table[1, 2] + confMat$table[2, 2]) +
confMat$table[2, 1] + confMat$table[1, 1])
out <- c(rocAUC,
caret::sensitivity(data[, "pred"], data[, "obs"], lev[1]),
caret::specificity(data[, "pred"], data[, "obs"], lev[2]),
confMat$overall['Kappa'],
confMat$overall['Accuracy'],
fn_tcr_9, mcc, ppv)
names(out) <- c("ROC", "Sens", "Spec", "Kappa", "Accuracy", "TCR_9", "MCC", "PPV")
out
}
)
) |
"predict.quantregForest"<-function(object,newdata=NULL, what=c(0.1,0.5,0.9),... )
{
class(object) <- "randomForest"
if(is.null(newdata)){
if(is.null(object[["valuesOOB"]])) stop("need to fit with option keep.inbag=TRUE \n if trying to get out-of-bag observations")
valuesPredict <- object[["valuesOOB"]]
}else{
predictNodes <- attr(predict(object,newdata=newdata,nodes=TRUE),"nodes")
rownames(predictNodes) <- NULL
valuesPredict <- 0*predictNodes
ntree <- ncol(object[["valuesNodes"]])
for (tree in 1:ntree){
valuesPredict[,tree] <- object[["valuesNodes"]][ predictNodes[,tree],tree]
}
}
if(is.function(what)){
if(is.function(what(1:4))){
result <- apply(valuesPredict,1,what)
}else{
if(length(what(1:4))==1){
result <- apply(valuesPredict,1,what)
}else{
result <- t(apply(valuesPredict,1,what))
}
}
}else{
if( !is.numeric(what)) stop(" `what' needs to be either a function or a vector with quantiles")
if( min(what)<0) stop(" if `what' specifies quantiles, the minimal values needs to be non-negative")
if( max(what)>1) stop(" if `what' specifies quantiles, the maximal values cannot exceed 1")
if(length(what)==1){
result <- apply( valuesPredict,1,quantile, what,na.rm=TRUE)
}else{
result <- t(apply( valuesPredict,1,quantile, what,na.rm=TRUE))
colnames(result) <- paste("quantile=",what)
}
}
return(result)
} |
library(datasets)
X = cbind(attenu$mag, attenu$dist)
colnames(X) = c("mag", "dist")
X_s = cbind(attenu$mag, 1 / attenu$dist)
colnames(X_s) = c("mag", "dist_inv")
fit = lmvar(attenu$accel, X, X_s)
vcov(fit)
vcov(fit, sigma = FALSE)
vcov(fit, mu = FALSE) |
wishart <- "ignored"
blmer <- function(formula, data = NULL, REML = TRUE,
control = lmerControl(), start = NULL,
verbose = 0L, subset, weights, na.action, offset,
contrasts = NULL, devFunOnly = FALSE,
cov.prior = wishart, fixef.prior = NULL,
resid.prior = NULL,
...)
{
mc <- mcout <- match.call()
callingEnv <- parent.frame(1L)
missCtrl <- missing(control)
missCovPrior <- missing(cov.prior)
if (!missCtrl && !inherits(control, "lmerControl")) {
if(!is.list(control)) stop("'control' is not a list; use lmerControl()")
warning("passing control as list is deprecated: please use lmerControl() instead",
immediate.=TRUE)
control <- do.call(lmerControl, control)
}
if (!is.null(list(...)[["family"]])) {
warning("calling lmer with 'family' is deprecated; please use glmer() instead")
mc[[1]] <- quote(lme4::glmer)
if(missCtrl) mc$control <- glmerControl()
return(eval(mc, parent.frame(1L)))
}
fixef.prior <- mc$fixef.prior
cov.prior <- if (!missCovPrior) mc$cov.prior else formals(blmer)$cov.prior
resid.prior <- mc$resid.prior
if (!is.null(mc$var.prior)) resid.prior <- parse(text = mc$var.prior)[[1]]
mc$fixef.prior <- NULL
mc$cov.prior <- NULL
mc$resid.prior <- NULL
mc$var.prior <- NULL
sigmaIsFixed <-
!is.null(resid.prior) && ((is.character(resid.prior) && grepl("^\\W*point", resid.prior)) ||
(is.call(resid.prior) && resid.prior[[1]] == "point"))
if (sigmaIsFixed) {
control$checkControl$check.nobs.vs.nlev <- "ignore"
control$checkControl$check.nobs.vs.rankZ <- "ignore"
control$checkControl$check.nobs.vs.nRE <- "ignore"
}
hasPseudoData <-
!is.null(fixef.prior) && ((is.character(fixef.prior) && grepl("^\\W*normal", fixef.prior)) ||
(is.call(fixef.prior) && fixef.prior[[1]] == "normal"))
if (hasPseudoData) {
control$checkControl$check.rankX <- "ignore"
}
mc$control <- control
mc[[1]] <- quote(lme4::lFormula)
lmod <- eval(mc, parent.frame(1L))
mcout$formula <- lmod$formula
lmod$formula <- NULL
lmerStart <- NULL
if (!is.null(start) && is.list(start) && length(start) > 1)
lmerStart <- start$theta
devfun <- do.call(mkBlmerDevfun,
c(lmod, lmod$X, lmod$reTrms,
list(priors = list(covPriors = cov.prior, fixefPrior = fixef.prior, residPrior = resid.prior),
start = lmerStart, verbose = verbose, control = control, env = callingEnv)))
if (devFunOnly) return(devfun)
devFunEnv <- environment(devfun)
opt <- if (control$optimizer=="none")
list(par=NA,fval=NA,conv=1000,message="no optimization")
else {
optimizeLmer(devfun, optimizer = control$optimizer,
restart_edge = control$restart_edge,
boundary.tol = control$boundary.tol,
control = control$optCtrl,
verbose=verbose,
start=start,
calc.derivs=control$calc.derivs,
use.last.params=control$use.last.params)
}
cc <- NULL
lme4Namespace <- getNamespace("lme4")
if (exists("checkConv", lme4Namespace)) {
checkConv <- get("checkConv", lme4Namespace)
cc <- checkConv(attr(opt, "derivs"), opt$par,
ctrl = control$checkConv,
lbound = environment(devfun)$lower)
}
args <- list(rho = devFunEnv, opt = opt, reTrms = lmod$reTrms, fr = lmod$fr, mc = mcout)
if ("lme4conv" %in% names(formals(mkMerMod))) args$lme4conv <- cc
result <- do.call(mkMerMod, args, TRUE)
result <- repackageMerMod(result, opt, devFunEnv)
return(result)
}
bglmer <- function(formula, data = NULL, family = gaussian,
control = glmerControl(), start = NULL, verbose = 0L, nAGQ = 1L,
subset, weights, na.action, offset,
contrasts = NULL, mustart, etastart, devFunOnly = FALSE,
cov.prior = wishart, fixef.prior = NULL,
...)
{
covPriorMissing <- missing(cov.prior)
callingEnv <- parent.frame(1L)
if (!inherits(control, "glmerControl")) {
if(!is.list(control)) stop("'control' is not a list; use glmerControl()")
msg <- "Use control=glmerControl(..) instead of passing a list"
if(length(cl <- class(control))) msg <- paste(msg, "of class", dQuote(cl[1]))
warning(msg, immediate.=TRUE)
control <- do.call(glmerControl, control)
}
mc <- mcout <- match.call()
fixef.prior <- mc$fixef.prior
cov.prior <- if (!covPriorMissing) mc$cov.prior else formals(bglmer)$cov.prior
mc$fixef.prior <- NULL
mc$cov.prior <- NULL
if (is.character(family))
family <- get(family, mode = "function", envir = parent.frame(2))
if( is.function(family)) family <- family()
if (isTRUE(all.equal(family, gaussian()))) {
warning("calling bglmer() with family=gaussian (identity link) as a shortcut to blmer() is deprecated;",
" please call blmer() directly")
mc[[1]] <- quote(blme::blmer)
mc["family"] <- NULL
return(eval(mc, parent.frame()))
}
mc[[1]] <- quote(lme4::glFormula)
glmod <- eval(mc, parent.frame(1L))
mcout$formula <- glmod$formula
glmod$formula <- NULL
nAGQinit <- if(control$nAGQ0initStep) 0L else 1L
devfun <- do.call(mkBglmerDevfun, c(glmod,
list(priors = list(covPriors = cov.prior, fixefPrior = fixef.prior),
verbose = verbose,
control = control,
nAGQ = nAGQinit,
env = callingEnv)))
if (nAGQ==0 && devFunOnly) return(devfun)
if (is.list(start)) {
start.bad <- setdiff(names(start),c("theta","fixef"))
if (length(start.bad)>0) {
stop(sprintf("bad name(s) for start vector (%s); should be %s and/or %s",
paste(start.bad,collapse=", "),
shQuote("theta"),
shQuote("fixef")),call.=FALSE)
}
if (!is.null(start$fixef) && nAGQ==0)
stop("should not specify both start$fixef and nAGQ==0")
}
if (packageVersion("lme4") <= "1.1-7" || identical(control$nAGQ0initStep, TRUE)) {
args <- list(devfun = devfun,
optimizer = control$optimizer[[1]],
restart_edge = if (nAGQ == 0) control$restart_edge else FALSE,
control = control$optCtrl,
start = start,
nAGQ = 0,
verbose = verbose)
if (!is.null(formals(optimizeGlmer)$boundary.tol)) args$boundary.tol <- if (nAGQ == 0) control$boundary.tol else 0
if (!is.null(formals(optimizeGlmer)[["..."]])) args$calc.derivs <- FALSE
opt <- do.call(optimizeGlmer, args, TRUE)
}
if(nAGQ > 0L) {
start <- get("updateStart", getNamespace("lme4"))(start,theta=opt$par)
devfun <- updateBglmerDevfun(devfun, glmod$reTrms, nAGQ = nAGQ)
if (devFunOnly) return(devfun)
args <- list(devfun = devfun,
optimizer = control$optimizer[[2]],
restart_edge = control$restart_edge,
control = control$optCtrl,
start = start,
nAGQ = nAGQ,
verbose = verbose,
stage = 2)
if (!is.null(formals(optimizeGlmer)$boundary.tol)) args$boundary.tol <- control$boundary.tol
if (!is.null(formals(optimizeGlmer)[["..."]])) {
args$calc.derivs <- control$calc.derivs
args$use.last.params <- control$use.last.params
}
opt <- do.call(optimizeGlmer, args, TRUE)
}
lme4Namespace <- getNamespace("lme4")
cc <- if (!is.null(control$calc.derivs) && !control$calc.derivs) NULL else {
if (exists("checkConv", lme4Namespace)) {
if (verbose > 10) cat("checking convergence\n")
checkConv <- get("checkConv", lme4Namespace)
checkConv(attr(opt,"derivs"), opt$par,
ctrl = control$checkConv,
lbound = environment(devfun)$lower)
}
else NULL
}
args <- list(rho = environment(devfun), opt = opt, reTrms = glmod$reTrms, fr = glmod$fr, mc = mcout)
if ("lme4conv" %in% names(formals(mkMerMod))) args$lme4conv <- cc
result <- do.call(mkMerMod, args, TRUE)
result <- repackageMerMod(result, opt, environment(devfun))
return(result)
}
lmmObjective <- function(pp, resp, sigma, exponentialTerms, polynomialTerm, blmerControl) {
sigma.sq <- sigma^2
result <- resp$objective(pp$ldL2(), pp$ldRX2(), pp$sqrL(1.0), sigma.sq)
exponentialTerm <- 0
for (i in seq_along(exponentialTerms)) {
power <- as.numeric(names(exponentialTerms)[[i]])
value <- exponentialTerms[[i]]
if (!is.finite(value)) return(value)
exponentialTerm <- exponentialTerm + value * sigma^power
}
priorPenalty <- exponentialTerm + polynomialTerm + blmerControl$constant + blmerControl$df * log(sigma.sq)
result <- result + priorPenalty
return(result)
}
repackageMerMod <- function(merMod, opt, devFunEnv) {
isLMM <- is(merMod, "lmerMod")
blmerControl <- devFunEnv$blmerControl
priors <- devFunEnv$priors
sigma <- NULL
if (isLMM) {
expandParsInCurrentFrame(opt$par, devFunEnv$parInfo)
if (blmerControl$fixefOptimizationType != FIXEF_OPTIM_NUMERIC) beta <- merMod@pp$beta(1.0)
else merMod@beta <- beta
if (blmerControl$sigmaOptimizationType == SIGMA_OPTIM_POINT) sigma <- priors$residPrior@value
} else {
beta <- opt$par[-devFunEnv$dpars]
}
if (!is.null(merMod@optinfo)) {
parLength <- devFunEnv$parInfo$theta$length + if (!isLMM) devFunEnv$parInfo$beta$length else 0
if (parLength != length(merMod@optinfo$val)) {
merMod@optinfo$val_full <- merMod@optinfo$val
merMod@optinfo$derivs_full <- merMod@optinfo$derivs
merMod@optinfo$val <- merMod@optinfo$val[parLength]
merMod@optinfo$derivs$gradient <- merMod@optinfo$derivs$gradient[parLength]
merMod@optinfo$derivs$Hessian <- merMod@optinfo$derivs$Hessian[parLength, parLength, drop = FALSE]
}
}
Lambda.ts <- getCovBlocks(merMod@pp$Lambdat, devFunEnv$ranefStructure)
exponentialTerms <- calculatePriorExponentialTerms(priors, beta, Lambda.ts, sigma)
if (isLMM) {
if (blmerControl$fixefOptimizationType == FIXEF_OPTIM_NUMERIC) {
fixefExponentialTerm <- calculateFixefExponentialTerm(beta, merMod@pp$beta(1.0), merMod@pp$RX())
if (is.null(exponentialTerms[["-2"]])) {
exponentialTerms[["-2"]] <- fixefExponentialTerm
} else {
exponentialTerms[["-2"]] <- exponentialTerms[["-2"]] + fixefExponentialTerm
}
}
if (!is.null(exponentialTerms[["-2"]]))
merMod@devcomp$cmp[["pwrss"]] <- merMod@devcomp$cmp[["pwrss"]] + as.numeric(exponentialTerms[["-2"]])
sigmaOptimizationType <- blmerControl$sigmaOptimizationType
if (sigmaOptimizationType %not_in% c(SIGMA_OPTIM_NA, SIGMA_OPTIM_POINT, SIGMA_OPTIM_NUMERIC)) {
profileSigma <- getSigmaProfiler(priors, blmerControl)
sigma <- profileSigma(merMod@pp, merMod@resp, exponentialTerms, blmerControl)
}
numObs <- merMod@devcomp$dims[["n"]]
numFixef <- merMod@devcomp$dims[["p"]]
if (merMod@devcomp$dims[["REML"]] > 0L) {
merMod@devcomp$cmp[["sigmaREML"]] <- sigma
merMod@devcomp$cmp[["sigmaML"]] <- sigma * sqrt((numObs - numFixef) / numObs)
} else {
merMod@devcomp$cmp[["sigmaML"]] <- sigma
merMod@devcomp$cmp[["sigmaREML"]] <- sigma * sqrt(numObs / (numObs - numFixef))
}
objectiveValue <- merMod@resp$objective(merMod@pp$ldL2(), merMod@pp$ldRX2(), merMod@pp$sqrL(1.0), sigma^2)
if (blmerControl$fixefOptimizationType == FIXEF_OPTIM_NUMERIC)
objectiveValue <- objectiveValue + fixefExponentialTerm / sigma^2
if (merMod@devcomp$dims[["REML"]] > 0L) {
priorPenalty <- merMod@devcomp$cmp[["REML"]] - objectiveValue
merMod@devcomp$cmp[["REML"]] <- objectiveValue
} else {
priorPenalty <- merMod@devcomp$cmp[["dev"]] - objectiveValue
merMod@devcomp$cmp[["dev"]] <- objectiveValue
}
merMod@devcomp$cmp[["penalty"]] <- priorPenalty
return(new("blmerMod",
resp = merMod@resp,
Gp = merMod@Gp,
call = merMod@call,
frame = merMod@frame,
flist = merMod@flist,
cnms = merMod@cnms,
lower = merMod@lower,
theta = merMod@theta,
beta = beta,
u = merMod@u,
devcomp = merMod@devcomp,
pp = merMod@pp,
optinfo = merMod@optinfo,
priors = priors))
} else {
if (length(exponentialTerms) > 0)
priorPenalty <- exponentialTerms[[1]] + calculatePriorPolynomialTerm(priors$covPriors, Lambda.ts) + blmerControl$constant
else
priorPenalty <- 0
merMod@devcomp$cmp[["dev"]] <- merMod@devcomp$cmp[["dev"]] - priorPenalty
merMod@devcomp$cmp[["penalty"]] <- priorPenalty
return(new("bglmerMod",
resp = merMod@resp,
Gp = merMod@Gp,
call = merMod@call,
frame = merMod@frame,
flist = merMod@flist,
cnms = merMod@cnms,
lower = merMod@lower,
theta = merMod@theta,
beta = merMod@beta,
u = merMod@u,
devcomp = merMod@devcomp,
pp = merMod@pp,
optinfo = merMod@optinfo,
priors = priors))
}
}
validateRegressionArgument <- function(regression, regressionName) {
if (missing(regression)) stop("'regression' missing.")
if (is.null(regression)) stop("object '", regressionName, "' is null.")
if (!is(regression, "bmerMod")) stop("object '", regressionName, "' does not inherit from S4 class 'bmerMod'.")
}
setPrior <- function(regression, cov.prior = NULL,
fixef.prior = NULL, resid.prior = NULL, envir = parent.frame(1L), ...)
{
matchedCall <- match.call()
covMissing <- missing(cov.prior)
fixefMissing <- missing(fixef.prior)
residMissing <- missing(resid.prior)
validateRegressionArgument(regression, matchedCall$regression)
if (residMissing && !is.null(matchedCall$var.prior)) {
matchedCall$resid.prior <- matchedCall$var.prior
residMissing <- FALSE
}
priors <- evaluatePriorArguments(matchedCall$cov.prior, matchedCall$fixef.prior, matchedCall$resid.prior,
regression@devcomp$dim, colnames(regression@pp$X), regression@cnms,
as.integer(diff(regression@Gp) / sapply(regression@cnms, length)),
envir)
if (!covMissing) regression@covPriors <- priors$covPriors
if (!fixefMissing) regression@fixefPrior <- priors$fixefPrior
if (!residMissing) regression@residPrior <- priors$residPrior
return (regression)
}
parsePrior <- function(regression, cov.prior = NULL,
fixef.prior = NULL, resid.prior = NULL, envir = parent.frame(), ...)
{
matchedCall <- match.call()
covMissing <- missing(cov.prior)
fixefMissing <- missing(fixef.prior)
residMissing <- missing(resid.prior)
validateRegressionArgument(regression, matchedCall$regression)
if (residMissing && !is.null(matchedCall$var.prior)) {
matchedCall$resid.prior <- matchedCall$var.prior
residMissing <- FALSE
}
priors <- evaluatePriorArguments(matchedCall$cov.prior, matchedCall$fixef.prior, matchedCall$resid.prior,
regression@devcomp$dim, colnames(regression@pp$X), regression@cnms,
as.integer(diff(regression@Gp) / sapply(regression@cnms, length)),
envir)
result <- list()
if (!covMissing) result$covPriors <- priors$covPriors
if (!fixefMissing) result$fixefPrior <- priors$fixefPrior
if (!residMissing) result$residPrior <- priors$residPrior
if (length(result) == 1) return(result[[1]])
return(result)
}
if (FALSE) {
runOptimizer <- function(regression, verbose = FALSE)
{
validateRegressionArgument(regression, match.call()$regression)
if (verbose) {
regression@dims[["verb"]] <- as.integer(1)
} else {
regression@dims[["verb"]] <- as.integer(0)
}
return (mer_finalize(regression))
}
runOptimizerWithPrior <- function(regression, cov.prior = NULL,
fixef.prior = NULL, var.prior = NULL,
verbose = FALSE, envir = parent.frame())
{
validateRegressionArgument(regression, match.call()$regression)
regression <- setPrior(regression, cov.prior, fixef.prior, var.prior, envir)
return(runOptimizer(regression, verbose))
}
}
refit.bmerMod <- function(object, newresp = NULL, rename.response = FALSE,
maxit = 100L, ...)
{
lme4Namespace <- getNamespace("lme4")
lme4Version <- packageVersion("lme4")
dotsList <- list(...)
newControl <- NULL
if ("control" %in% names(dotsList)) newControl <- dotsList$control
if (!all(names(dotsList) %in% c("control", "verbose")))
warning("additional arguments to refit.bmerMod ignored")
newrespSub <- substitute(newresp)
if (is.list(newresp)) {
if (length(newresp) == 1) {
na.action <- attr(newresp,"na.action")
newresp <- newresp[[1]]
attr(newresp, "na.action") <- na.action
} else {
stop("refit not implemented for lists with length > 1: ",
"consider ", sQuote("lapply(object, refit)"))
}
}
ignore.pars <- c("xst", "xt")
control.internal <- object@optinfo$control
if (length(ign <- which(names(control.internal) %in% ignore.pars)) > 0L)
control.internal <- control.internal[-ign]
if (!is.null(newControl)) {
control <- newControl
if (length(control$optCtrl) == 0L)
control$optCtrl <- control.internal
} else {
control <- if (isGLMM(object)) glmerControl() else lmerControl()
}
pp <- object@pp$copy()
dc <- object@devcomp
nAGQ <- unname(dc$dims["nAGQ"])
nth <- dc$dims[["nth"]]
verbose <- dotsList$verbose; if (is.null(verbose)) verbose <- 0L
if (!is.null(newresp)) {
rcol <- attr(attr(model.frame(object), "terms"), "response")
if (rename.response) {
attr(object@frame,"formula")[[2L]] <- object@call$formula[[2L]] <- newrespSub
names(object@frame)[rcol] <- deparse(newrespSub)
}
if (!is.null(na.act <- attr(object@frame,"na.action")) &&
is.null(attr(newresp, "na.action"))) {
newresp <- if (is.matrix(newresp))
newresp[-na.act, ]
else newresp[-na.act]
}
object@frame[,rcol] <- newresp
}
rr <- if (isLMM(object))
mkRespMod(model.frame(object), REML = isREML(object))
else if (isGLMM(object)) {
modelFrame <- model.frame(object)
if (lme4Version <= "1.1-6") modelFrame$mustart <- object@resp$mu
mkRespMod(modelFrame, family = family(object))
} else
stop("refit.bmerMod not working for nonlinear mixed models")
if (!is.null(newresp)) {
if (family(object)$family == "binomial") {
if (is.matrix(newresp) && ncol(newresp) == 2) {
ntot <- rowSums(newresp)
newresp <- newresp[,1] / ntot
rr$setWeights(ntot)
}
if (is.factor(newresp)) {
newresp <- as.numeric(newresp) - 1
}
}
stopifnot(length(newresp <- as.numeric(as.vector(newresp))) ==
length(rr$y))
}
glmerPwrssUpdate <- get("glmerPwrssUpdate", lme4Namespace)
if (isGLMM(object)) {
GQmat <- GHrule(nAGQ)
if (nAGQ <= 1) {
if (lme4Version <= "1.1-7")
glmerPwrssUpdate(pp, rr, control$tolPwrss, GQmat)
else
glmerPwrssUpdate(pp, rr, control$tolPwrss, GQmat, maxit = maxit)
} else {
if (lme4Version <= "1.1-7")
glmerPwrssUpdate(pp, rr, control$tolPwrss, GQmat, grpFac = object@flist[[1]])
else
glmerPwrssUpdate(pp, rr, control$tolPwrss, GQmat, maxit = maxit, grpFac = object@flist[[1]])
}
baseOffset <- object@resp$offset
}
devlist <- if (isGLMM(object))
list(tolPwrss = dc$cmp [["tolPwrss"]],
compDev = dc$dims[["compDev"]],
nAGQ = unname(nAGQ),
lp0 = pp$linPred(1),
baseOffset = baseOffset,
pwrssUpdate = glmerPwrssUpdate,
GQmat = GHrule(nAGQ),
fac = object@flist[[1]],
pp = pp,
resp = rr,
u0 = pp$u0,
verbose = verbose,
dpars = seq_len(nth))
else
list(pp = pp,
resp = rr,
u0 = pp$u0,
verbose = verbose,
dpars = seq_len(nth))
ff <- makeRefitDevFun(list2env(devlist), nAGQ = nAGQ, verbose = verbose, maxit = maxit, object = object)
reTrms <- list(flist = object@flist, cnms = object@cnms, Gp = object@Gp, lower = object@lower)
if (isGLMM(object))
ff <- updateBglmerDevfun(ff, reTrms, nAGQ)
lower <- environment(ff)$lower
calc.derivs <- !is.null(object@optinfo$derivs)
opt <-
if (isLMM(object)) {
optimizeLmer(ff,
optimizer = object@optinfo$optimizer,
control = control$optCtrl,
verbose = verbose,
start = extractParameterListFromFit(object, environment(ff)$blmerControl),
calc.derivs = calc.derivs,
use.last.params = if (!is.null(control$use.last.params)) control$use.last.params else FALSE)
} else {
args <- list(devfun = ff,
optimizer = object@optinfo$optimizer,
restart_edge = control$restart_edge,
control = control$optCtrl,
start = extractParameterListFromFit(object, environment(ff)$blmerControl),
nAGQ = nAGQ,
verbose = verbose,
stage = 2)
if (!is.null(formals(optimizeGlmer)$boundary.tol)) args$boundary.tol <- control$boundary.tol
if (!is.null(formals(optimizeGlmer)[["..."]])) {
args$calc.derivs <- control$calc.derivs
args$use.last.params <- if (!is.null(control$use.last.params)) control$use.last.params else FALSE
}
do.call(optimizeGlmer, args, TRUE)
}
cc <- NULL
if (exists("checkConv", lme4Namespace)) {
cc <- get("checkConv", lme4Namespace)(attr(opt,"derivs"), opt$par,
ctrl = control$checkConv,
lbound = lower)
}
if (isGLMM(object)) rr$setOffset(baseOffset)
args <- list(rho = environment(ff), opt = opt,
reTrms = reTrms,
fr = object@frame, mc = getCall(object))
if ("lme4conv" %in% names(formals(mkMerMod))) args$lme4conv <- cc
result <- do.call(mkMerMod, args, TRUE, sys.frame(0))
repackageMerMod(result, opt, environment(ff))
} |
setOldClass("file")
setOldClass("pipe")
setOldClass("fifo")
setOldClass("url")
setOldClass("gzfile")
setOldClass("bzfile")
setOldClass("xzfile")
setOldClass("unz")
setOldClass("socketConnection")
setClassUnion("kRp.connection", members=c("file","pipe","fifo","url","gzfile","bzfile","xzfile","unz","socketConnection")) |
output$TableOfEachPrefectures <- renderDataTable({
dt <- totalConfirmedByRegionData()
columnName <- c("today", "doubleTimeDay")
dt[, (columnName) := replace(.SD, .SD == 0, NA), .SDcols = columnName]
displayColumn <- list(
"region" = i18n$t("自治体"),
"today" = i18n$t("新規"),
"totalToday" = i18n$t("感染者数"),
"diff" = i18n$t("感染推移"),
"active" = i18n$t("現在患者数"),
"doubleTimeDay" = i18n$t("倍加日数"),
"perHundredThousand" = i18n$t("10万対発生数※"),
"group" = i18n$t("カテゴリ"),
"Rt" = i18n$t("実効再生産数"),
"検査人数" = i18n$t("検査人数"),
"前日比" = i18n$t("前日比"),
"検査数推移" = i18n$t("検査推移"),
"detailBullet" = i18n$t("内訳"),
"death" = i18n$t("死亡")
)
datatable(
data = dt[, names(displayColumn), with = FALSE],
colnames = as.vector(unlist(displayColumn)),
escape = FALSE,
extensions = c("RowGroup", "Buttons"),
callback = htmlwidgets::JS(paste0(
"table.rowGroup().",
ifelse(input$tableOfEachPrefecturesBoxSidebar, "enable()", "disable()"),
".draw();"
)),
options = list(
paging = F,
rowGroup = list(dataSrc = 8),
dom = "t",
scrollY = "540px",
scrollX = T,
columnDefs = list(
list(
className = "dt-left",
targets = 1
),
list(
className = "dt-center",
targets = c(3:7, 9)
),
list(
width = "30px",
className = "dt-right",
targets = 2
),
list(
visible = F,
targets = c(6, 8)
),
list(
render = JS(
"
function(data, type, row, meta) {
const split = data.split('|');
return split[1];
}"
),
targets = 1
),
list(
render = JS(
"
function(data, type, row, meta) {
const split = data.split('|');
return Number(split[1]).toLocaleString();
}"
),
targets = 3
),
list(
render = JS(
"function(data, type, row, meta) {
const split = data.split('|');
return split[1];
}"
),
targets = c(7, 9)
)
),
fnDrawCallback = htmlwidgets::JS("
function() {
HTMLWidgets.staticRender();
}
")
)
) %>%
spk_add_deps() %>%
formatStyle(
columns = "totalToday",
background = htmlwidgets::JS(
paste0(
"'linear-gradient(-90deg, transparent ' + (",
max(dt$count),
"- value.split('|')[1])/",
max(dt$count),
" * 100 + '%,
max(dt$count),
"- value.split('|')[1])/",
max(dt$count),
" * 100 + '% ' + (",
max(dt$count),
"- value.split('|')[1] + Number(value.split('|')[2]))/",
max(dt$count),
" * 100 + '%,
max(dt$count),
"- value.split('|')[1] + Number(value.split('|')[2]))/",
max(dt$count),
" * 100 + '%)'"
)
),
backgroundSize = "100% 80%",
backgroundRepeat = "no-repeat",
backgroundPosition = "center"
) %>%
formatCurrency(
columns = "today",
currency = paste(as.character(icon("caret-up")), " "),
digits = 0
) %>%
formatStyle(
columns = "today",
color = do.call(
styleInterval,
generateColorStyle(data = dt$today, colors = c(lightRed, darkRed), by = 5)
),
fontWeight = "bold"
) %>%
formatStyle(
columns = "active",
color = do.call(
styleInterval,
generateColorStyle(data = dt$active, colors = c(lightYellow, darkRed), by = 100)
),
fontWeight = "bold"
) %>%
formatCurrency(
columns = "active",
currency = "",
digits = 0
) %>%
formatStyle(
columns = "doubleTimeDay",
color = do.call(
styleInterval,
generateColorStyle(data = dt$doubleTimeDay, colors = c(darkRed, lightYellow), by = 5)
),
fontWeight = "bold"
) %>%
formatStyle(
columns = "perHundredThousand",
backgroundColor = htmlwidgets::JS(
"isNaN(parseFloat(value.match(/\\|(.+?) /)[1])) ? '' : value.match(/\\|(.+?) /)[1] <= 0 ? \"rgba(0,0,0,0)\" : value.match(/\\|(.+?) /)[1] <= 5 ? \"
),
fontWeight = "bold"
) %>%
formatStyle(
columns = "Rt",
backgroundColor = htmlwidgets::JS(
"isNaN(parseFloat(value.match(/\\|(.+?) /)[1])) ? '' : value.match(/\\|(.+?) /)[1] <= 0.3 ? \"rgba(0,0,0,0)\" : value.match(/\\|(.+?) /)[1] <= 0.6 ? \"
),
fontWeight = "bold"
) %>%
formatCurrency(
columns = "検査人数",
currency = "",
digits = 0
) %>%
formatStyle(
columns = "検査人数",
background = styleColorBar(c(0, max(dt$検査人数, na.rm = T)), middleYellow, angle = -90),
backgroundSize = "98% 80%",
backgroundRepeat = "no-repeat",
backgroundPosition = "center"
) %>%
formatCurrency(
columns = "前日比",
currency = paste(as.character(icon("caret-up")), " "),
digits = 0
) %>%
formatStyle(
columns = "前日比",
color = do.call(
styleInterval,
generateColorStyle(data = dt$前日比, colors = c(lightYellow, darkYellow), by = 50)
),
fontWeight = "bold"
) %>%
formatStyle(
columns = "death",
color = do.call(
styleInterval,
generateColorStyle(data = dt$death, colors = c(lightNavy, darkNavy), by = 10)
),
fontWeight = "bold"
)
}) |
lcra = function(formula, data, family, nclasses, manifest, sampler = "JAGS",
inits = NULL, dir, n.chains = 3, n.iter = 2000, n.burnin = n.iter/2,
n.thin = 1, n.adapt = 1000, useWINE = FALSE, WINE, debug = FALSE, ...) {
if(missing(data)) {
stop("A data set is required to fit the model.")
}
if(!is.data.frame(data)) {
stop("A data.frame is required to fit the model.")
}
if(missing(family)) {
stop("Family must be specified. Currently the options are 'gaussian' (identity link) and 'binomial' which uses a logit link.")
}
if(missing(dir)) {
dir = tempdir()
}
if(missing(formula)) {
stop("Specify an R formula for the regression model to be fitted.
If you only want the latent class analysis, set formula = NULL.")
}
get_os <- function(){
sysinf <- Sys.info()
if (!is.null(sysinf)){
os <- sysinf['sysname']
if (os == 'Darwin')
os <- "osx"
} else {
os <- .Platform$OS.type
if (grepl("^darwin", R.version$os))
os <- "osx"
if (grepl("linux-gnu", R.version$os))
os <- "linux"
}
tolower(os)
}
OS = get_os()
if(OS == 'windows') useWINE = FALSE
else if(OS == 'osx') useWINE = TRUE
else if(OS == 'linux') useWINE = TRUE
N = nrow(data)
n_manifest = length(manifest)
if(is.null(formula)) {do_regression = FALSE}
else {do_regression = TRUE}
mf = match.call(expand.dots = FALSE)
m = match(c("formula", "data"), names(mf))
mf = mf[c(1L, m)]
mf[[1L]] = quote(stats::model.frame)
mf = eval(mf, parent.frame())
mt = attr(mf, "terms")
x = model.matrix(mt, mf)
y = mf[[setdiff(names(mf), colnames(x))]]
if(any(!(manifest %in% colnames(data)))) {
stop("At least one manifest variable name is not in the names of variables
in the data set.")
}
Z = data[,manifest, drop = FALSE]
lapply(Z, function(x) {
if(!is.numeric(x)) {
stop('All manifest variables must be numeric. At least one of the manifest
variables you specified is not numeric.')
}
if(any(x < 0)) {
stop('At least one of the manifest variables you specified contains negative values.
Code levels of manifest variables to take on values 1 through number of levels.')
}
})
manifest.levels = apply(Z, 2, function(x) {length(unique(x))})
unique.manifest.levels = unique(manifest.levels)
p.length = length(unique.manifest.levels)
pclass_prior = round(rep(1/nclasses, nclasses), digits = 3)
if(sum(pclass_prior) != 1){
pclass_prior[length(pclass_prior)] = pclass_prior[length(pclass_prior)] +
(1 - sum(pclass_prior))
}
dat_list = vector(mode = "list", length = 6)
prior_mat = matrix(NA, nrow = ncol(Z), ncol = max(unique.manifest.levels))
for(j in 1:length(manifest.levels)) {
prior = round(rep(1/manifest.levels[j], manifest.levels[j]), digits = 3)
if(sum(prior) != 1){
prior[length(prior)] = prior[length(prior)] +
(1 - sum(prior))
}
if(length(prior) < length(prior_mat[j,])) {
fill = rep(NA, length = (length(prior_mat[j,]) - length(prior)))
prior = c(prior, fill)
prior_mat[j,] = prior
} else {
prior_mat[j,] = prior
}
}
names(dat_list) = c("prior_mat", "prior", "Z", "y", "x", "nlevels")
dat_list[["prior_mat"]] = structure(
.Data=as.vector(prior_mat),
.Dim=c(length(manifest.levels), max(unique.manifest.levels))
)
dat_list[["prior"]] = pclass_prior
dat_list[["Z"]] = structure(
.Data=as.vector(as.matrix(Z)),
.Dim=c(N,n_manifest)
)
dat_list[["y"]] = y
dat_list[["x"]] = structure(
.Data=x,
.Dim=c(N,ncol(x))
)
nlevels = apply(Z, 2, function(x) {length(unique(x))})
names(nlevels) = NULL
dat_list[["nlevels"]] = nlevels
n_beta = ncol(x)
regression = c()
response = c()
tau = c()
i <- NULL
inprod <- NULL
alpha <- NULL
`logit<-` <- NULL
if(family == "gaussian") {
response = expr(y[i] ~ dnorm(yhat[i], tau))
regression = expr(yhat[i] <- inprod(x[i,], beta[]) + inprod(C[i,], alpha[]))
tau = expr(tau~dgamma(0.1,0.1))
parameters.to.save = c("beta", "true", "alpha", "pi", "theta", "tau")
} else if(family == "binomial") {
response = expr(y[i] ~ dbern(p[i]))
regression = expr(logit(p[i]) <- inprod(x[i,], beta[]) + inprod(C[i,], alpha[]))
tau = NULL
parameters.to.save = c("beta", "true", "alpha", "pi", "theta")
}
model = constr_bugs_model(N = N, n_manifest = n_manifest, n_beta = n_beta,
nclasses = nclasses, npriors = unique.manifest.levels,
regression = regression, response = response, tau = tau)
filename <- file.path(dir, "model.text")
write_model(model, filename)
if(sampler == "JAGS") {
model_jags = jags.model(
file = filename,
data = dat_list,
inits = inits,
n.chains = n.chains,
n.adapt = n.adapt,
quiet = FALSE)
samp_lcra = window(
coda.samples(
model = model_jags,
variable.names = parameters.to.save,
n.iter = n.iter,
thin = 1
), start = n.burnin)
} else if(sampler == "WinBUGS") {
samp_lcra = as.mcmc.list(
R2WinBUGS::bugs(data = dat_list,
inits = inits,
model.file = filename,
n.chains = n.chains,
n.iter = n.iter,
parameters.to.save = parameters.to.save,
debug = debug,
n.burnin = n.burnin,
n.thin = n.thin,
useWINE = useWINE,
WINE = WINE, ...))
} else {
stop('Sampler name is not one of the options, which are JAGS and WinBUGS.')
}
return(samp_lcra)
}
constr_bugs_model = function(N, n_manifest, n_beta, nclasses, npriors,
regression, response, tau) {
true <- NULL
constructor = function() {
bugs_model_enque =
quo({
bugs_model_func = function() {
for (i in 1:!!N){
true[i]~dcat(theta[])
for(j in 1:!!n_manifest){
Z[i,j]~dcat(pi[true[i],j,1:nlevels[j]])
}
for(k in 1:(!!(nclasses-1))){
C[i,k] <- step(-true[i]+k) - step(-true[i]+k-1)
}
!!response
!!regression
}
theta[1:!!nclasses]~ddirch(prior[])
for(c in 1:!!nclasses){
for(j in 1:!!n_manifest){
pi[c,j,1:nlevels[j]]~ddirch(prior_mat[j,1:nlevels[j]])
}
}
for(k in 1:!!n_beta){
beta[k]~dnorm(0,0.1)
}
for(k in 1:!!(nclasses-1)){
alpha[k]~dnorm(0,0.1)
}
!!tau
}
})
return(bugs_model_enque)
}
text_fun = as.character(quo_get_expr(constructor()))[2]
return(eval(parse(text = text_fun)))
} |
print.ActivityIndex = function(x, ...) {
x = as.data.frame(x)
cat("Showing head and tail rows\n")
print(head(x), ...)
print(tail(x), ...)
} |
rsi <- function(x) c(1,which(diff(x)!=0)+1) |
hour <- function(n, x = seq(0, 23.5, by = .5), prob = NULL, random = FALSE,
name = "Hour"){
out <- sample(x = x, size = n, replace = TRUE, prob = prob)
if (!random) out <- sort(out)
varname(sec2hms(out), name)
} |
nosof88protoalcove <- function(params = NULL) {
if(is.null(params)) params <- nosof88protoalcove_opt()
bigout <- NULL
h = cbind(c(-2.543,2.641), c(.943,4.341), c(-1.092,1.848),
c(1.558,2.902), c(-2.258,.430), c(.194,.572),
c(2.806,.202), c(-1.177,-1.038), c(1.543,-1.040),
c(-2.775,-3.149), c(.528,-3.766), c(1.709,-3.773))
cat1 <- cbind(h[,1],h[,5],h[,8],h[,10],h[,11],h[,12])
cat1p <- rowMeans(cat1)
cat2 <- cbind(h[,2],h[,3],h[,4],h[,6],h[,7],h[,9])
cat2p <- rowMeans(cat2)
hb <- cbind(cat1p,cat2p)
cat2 <- cbind(h[,2],h[,2],h[,2],h[,2],h[,2],h[,3],h[,4],h[,6],
h[,7],h[,9])
cat2p <- rowMeans(cat2)
he2 <- cbind(cat1p,cat2p)
cat2 <- cbind(h[,2],h[,3],h[,4],h[,6],h[,7],h[,7],h[,7],h[,7],
h[,7],h[,9])
cat2p <- rowMeans(cat2)
he7 <- cbind(cat1p,cat2p)
rm(h,cat1,cat1p,cat2,cat2p)
init.state <- list(colskip = 4, r = 2, q = 1, alpha = c(.5,.5),
w = array(0,dim=c(2,2)), h = hb, c = params[1],
phi = params[2], la = params[3],
lw = params[4])
bigtr <- nosof88train('B',blocks = 3, absval = -1, subjs = 100,
seed = 4182)
init.state$h <- hb
out <- slpALCOVE(init.state,bigtr)
out <- out$p
colnames(out) <- c('p1','p2')
out <- data.frame(cbind(bigtr,out))
out.ag <- aggregate(out$p2,list(out$stim,out$cond),mean)
bigout <- rbind(bigout,out.ag)
bigtr <- nosof88train('E2',blocks = 3, absval = -1, subjs = 100,
seed = 4182)
init.state$h <- he2
out <- slpALCOVE(init.state,bigtr)
out <- out$p
colnames(out) <- c('p1','p2')
out <- data.frame(cbind(bigtr,out))
out.ag <- aggregate(out$p2,list(out$stim,out$cond),mean)
bigout <- rbind(bigout,out.ag)
bigtr <- nosof88train('E7',blocks = 3, absval = -1, subjs = 100,
seed = 4182)
init.state$h <- he7
out <- slpALCOVE(init.state,bigtr)
out <- out$p
colnames(out) <- c('p1','p2')
out <- data.frame(cbind(bigtr,out))
out.ag <- aggregate(out$p2,list(out$stim,out$cond),mean)
bigout <- rbind(bigout,out.ag)
colnames(bigout) <- c('stim','cond','c2acc')
return(bigout)
} |
FWSaturated <- function(data,
sample = "sample",
water.potential = "water.potential",
fresh.weight = "fresh.weight",
dry.weight = "dry.weight") {
data_in <-
ValidityCheck(
data,
sample = sample,
water.potential = water.potential,
fresh.weight = fresh.weight,
dry.weight = dry.weight
)
OrderCheck(
data_in,
sample = sample,
water.potential = water.potential,
fresh.weight = fresh.weight
)
data_in <-
data.frame(data_in[[sample]], data_in[[fresh.weight]], data_in[[water.potential]],
data_in[[dry.weight]])
names(data_in) <-
c(
paste0(sample),
paste0(fresh.weight),
paste0(water.potential),
paste0(dry.weight)
)
data_in$leaf.water <-
data_in[[fresh.weight]] - data_in[[dry.weight]]
sat.fw <- c()
for (i in 1:length(unique(data_in$sample))) {
sub.sample <- unique(data_in$sample)[i]
data_in_subset <- data_in[data_in[[sample]] == sub.sample,]
data_in_subset$water.loss1 <-
100 - (data_in_subset$leaf.water * 100 / max(data_in_subset$leaf.water))
data_in_subset$water.loss <-
data_in_subset$water.loss1 - min(data_in_subset$water.loss1)
tlp <-
suppressWarnings(TurgorLossPoint(data_in_subset, RWD = "water.loss", graph = FALSE))
if (length(tlp) == 0) {
warning(
paste0("sample ", sub.sample),
": the saturated water content could not be calculated due to unsuccessful determination of the tugor loss point"
)
sat.fw_i <- NA
} else{
tlp_param <- ExtractParam(tlp)
data_in_subset_sub <-
data_in_subset[data_in_subset$water.loss < (as.numeric(tlp_param[2]) + min(data_in_subset$water.loss1)), ]
data_in_subset_sub <-
data.frame(fresh.weight = data_in_subset_sub[[fresh.weight]],
water.potential = data_in_subset_sub[[water.potential]])
if (length(data_in_subset_sub[, 1]) < 3) {
warning(
paste0("sample ", sub.sample),
": the saturated water content could not be calculated due to too few (< 3) data points before the tugor loss point"
)
sat.fw_i <- NA
} else{
m <-
lm(fresh.weight ~ water.potential, data = data_in_subset_sub)
sat.fw_i <- as.numeric(coef(m)[1])
}
}
sat.fw <-
c(sat.fw, rep(sat.fw_i, times = length(data_in_subset[, 1])))
}
return(data.frame(data, fresh.weight.saturated = sat.fw))
} |
keybox <- function(p, grob="roundrect", gp=NULL) {
g <- ggplot2::ggplotGrob(p)
i <- grep("guide-box", g$layout$name)
g2 <- g$grob[[i]]
for (j in seq_along(g2)) {
x <- g2[[1]][[j]]
if (inherits(x, 'zeroGrob')) next
if (grob == "rect") {
gr <- grid::rectGrob
} else if (grob == "roundrect") {
gr <- grid::roundrectGrob
} else {
stop("grob not supported...")
}
x[[1]][[1]] <- gr(gp = gp)
g2[[1]][[j]] <- x
}
g[[1]][[i]] <- g2
grid::grid.draw(g)
invisible(g)
} |
test_that("cf ssh", {
skip_on_os("windows")
skip_on_ci()
skip_on_cran()
reg = makeTestRegistry()
if (reg$cluster.functions$name == "Interactive") {
workers = list(Worker$new("localhost", ncpus = 2, max.load = 9999))
reg$cluster.functions = makeClusterFunctionsSSH(workers)
saveRegistry(reg)
fun = function(x) { Sys.sleep(x); is(x, "numeric") }
ids = batchMap(fun, x = c(5, 5), reg = reg)
silent({
submitJobs(1:2, reg = reg)
Sys.sleep(0.2)
expect_equal(findOnSystem(reg = reg), findJobs(reg = reg))
expect_true(killJobs(2, reg = reg)$killed)
expect_true(
waitForJobs(1, sleep = 0.5, reg = reg)
)
})
expect_equal(findDone(reg = reg), findJobs(ids = 1, reg = reg))
expect_equal(findNotDone(reg = reg), findJobs(ids = 2, reg = reg))
expect_true(loadResult(1, reg = reg))
}
})
if (FALSE) {
reg = makeTestRegistry()
workers = list(Worker$new("129.217.207.53"), Worker$new("localhost", ncpus = 1))
reg$cluster.functions = makeClusterFunctionsSSH(workers)
expect_string(workers[[1L]]$script)
expect_string(workers[[2L]]$script)
expect_equal(workers[[1L]]$ncpus, 4L)
expect_equal(workers[[2L]]$ncpus, 1L)
fun = function(x) { Sys.sleep(x); is(x, "numeric") }
ids = batchMap(fun, x = 20 * c(1, 1), reg = reg)
submitJobs(1:2, reg = reg)
expect_equal(findOnSystem(reg = reg), findJobs(reg = reg))
expect_true(killJobs(2, reg = reg)$killed)
expect_true(waitForJobs(1, reg = reg, sleep = 1))
expect_equal(findDone(reg = reg), findJobs(ids = 1, reg = reg))
expect_equal(findNotDone(reg = reg), findJobs(ids = 2, reg = reg))
expect_true(loadResult(1, reg = reg))
} |
source("ESEUR_config.r")
library("visreg")
cpu2006=read.csv(paste0(ESEUR_dir, "benchmark/cpu2006-results-20140206.csv.xz"), as.is=TRUE)
mem2006=read.csv(paste0(ESEUR_dir, "benchmark/cpu2006-memory.csv.xz"), as.is=TRUE)
mem2006$ecc=substr(mem2006$mem_rate, nchar(mem2006$mem_rate), 100)
mem2006$mem_rate=as.numeric(sub("(E|F|P|R|U)$", "", x=mem2006$mem_rate))
mem2006$mem_rate[mem2006$mem_rate == 8600]=8500
mem2006$mem_rate[mem2006$mem_rate == 16000]=17000
cpu2006=cbind(cpu2006, mem2006)
cpu2006$Test.Date=as.Date(paste0("01-", cpu2006$Test.Date), format="%d-%B-%Y")
start_date=as.Date("01-Jan-2006", format="%d-%B-%Y")
cpu2006=subset(cpu2006, Test.Date >= start_date)
cint=subset(cpu2006, Benchmark == "CINT2006")
cint$Benchmark=NULL
cint=subset(cint, Result > 0)
cint=subset(cint, mem_rate >= 3200)
cint=subset(cint, mem_freq < 2500)
PC2=subset(cint, mem_kind == "PC2")
PC3=subset(cint, mem_kind != "PC2")
cint$Processor=sub("[0-9][0-9][0-9][0-9](K|L|M|S|T| EE| HE| SE| v2|V2| v3)*$", "", x=cint$Processor)
cint$main_proc=sub("([^ ]+ [^ ]+) .*$", "\\1", x=cint$Processor)
spec_mod=glm(Result ~ Processor.MHz + I(Processor.MHz^2)+mem_rate + I(mem_rate^2) + mem_freq
, data=cint)
par(ESEUR_orig_par_values)
par(oma=c(2, 2, 1, 1))
par(mar=c(4, 5, 1, 2)+0.1)
t=visreg2d(spec_mod, "Processor.MHz", "mem_rate", plot.type="persp",
plot=FALSE)
plot(t, color=c("red", "green", "blue"),
ylab="mem_rate\n", zlab="") |
test_that("202012142242", {
f <- 'x^2'
x <- laplacian(f, var = c('x','y','z'))
y <- "2"
expect_equal(x,y)
})
test_that("202012142244", {
f <- 'y^2*x^2'
x <- laplacian(f, var = c('x','y'))
y <- "y^2 * 2 + 2 * x^2"
expect_equal(x,y)
})
test_that("202012142245", {
f <- function(x,y) c(x^2*y^2, x^2)
x <- laplacian(f, var = c(x=3,y=5))
y <- array(c(68,2))
expect_equal(x,y)
})
test_that("202012142246", {
f <- function(x,y) array(rep(c(x^2*y^2, x^2), 3), dim = c(2,3))
x <- laplacian(f, var = c(x=3,y=5))
y <- array(rep(c(68,2), 3), dim = c(2,3))
expect_equal(x,y)
})
test_that("202012142310", {
f <- function(x) x^2
x <- laplacian(f, var = 100, coordinates = "spherical")
y <- 2
expect_equal(x,y)
})
test_that("202012142311", {
f.num <- function(x,y,z) array(rep(c(x^2*y*sin(z),z*y,x*z+y^2), 2), dim = c(2,3))
f.sym <- array(rep(c('x^2*y*sin(z)','z*y','x*z+y^2'), 2), dim = c(2,3))
x.num <- laplacian(f.num, var = c(x=2,y=3,z=4), coordinates = "spherical", accuracy = 4)
x.sym <- laplacian(f.sym, var = c(x=2,y=3,z=4), coordinates = "spherical")
expect_equal(x.num,x.sym)
})
test_that("202012142312", {
f.num <- function(x,y,z) array(rep(c(x^2*y*sin(z),z*y,x*z+y^2), 2), dim = c(2,3))
f.sym <- array(rep(c('x^2*y*sin(z)','z*y','x*z+y^2'), 2), dim = c(2,3))
x.num <- laplacian(f.num, var = c(x=2,y=3,z=4), accuracy = 4)
x.sym <- laplacian(f.sym, var = c(x=2,y=3,z=4))
expect_equal(x.num,x.sym)
})
test_that("202012142312", {
f.num <- function(x,y,z,extra) if(extra) array(rep(c(x^2*y*sin(z),z*y,x*z+y^2), 2), dim = c(2,3))
f.sym <- array(rep(c('x^2*y*sin(z)','z*y','a*x*z+y^2'), 2), dim = c(2,3))
x.num <- laplacian(f.num, var = c(x=2,y=3,z=4), accuracy = 4, params = list(extra = TRUE))
x.sym <- laplacian(f.sym, var = c(x=2,y=3,z=4), params = list(a = 1))
expect_equal(x.num,x.sym)
}) |
merge_directed_graph <- function (graph, col_names = c ("flow")) {
if (length (col_names) == 1) {
if (col_names == "flow" & !"flow" %in% names (graph) &
"centrality" %in% names (graph))
col_names <- "centrality"
}
if (!all (col_names %in% names (graph)))
stop (paste0 ("col_names [",
paste (col_names, collapse = ", "),
"] do not match columns in graph"))
gr_cols <- dodgr_graph_cols (graph)
graph2 <- convert_graph (graph, gr_cols)
res <- lapply (col_names, function (i) {
graph2$merge <- graph [[i]]
rcpp_merge_cols (graph2)
})
res <- do.call (cbind, res)
index <- which (rowSums (res) > 0)
graph <- graph [index, , drop = FALSE]
for (i in seq (col_names))
graph [[col_names [i] ]] <- res [index, i]
class (graph) <- c (class (graph), "dodgr_merged")
attr (graph, "hash") <- digest::digest (graph [[gr_cols$edge_id]])
return (graph)
} |
test_that('nucleotide frequencies are correct', {
s = seq('GATTACA')
expected = as.table(c(A = 3L, C = 1L, G = 1L, T = 2L))
expect_equal(table(s)[[1L]], expected)
}) |
context("Hue pal")
test_that("hue_pal arguments are forcely evaluated on each call
col1 <- hue_pal(h.start = 0)
col2 <- hue_pal(h.start = 90)
colours <- list()
hues <- c(0, 90)
for (i in 1:2) {
colours[[i]] <- hue_pal(h.start = hues[i])
}
expect_equal(col1(1), colours[[1]](1))
expect_equal(col2(1), colours[[2]](1))
})
test_that("hue_pal respects direction argument
col1 <- hue_pal()
col2 <- hue_pal(direction = -1)
expect_equal(col1(3), rev(col2(3)))
expect_equal(col1(9), rev(col2(9)))
}) |
setClass(
Class="ChangePointModelCVM",
representation=representation(
),
prototype(
),
contains='ChangePointModel'
)
makeChangePointModelCVM <- function(hs=numeric(),startup=20) {
windowStatistic <- list()
windowStatistic$X <- numeric()
windowStatistic$N <- numeric()
return(new(Class='ChangePointModelCVM',
windowStatistic=windowStatistic,
hs=hs,
changeDetected=FALSE,
startup=startup
))
}
setMethod(f='updateWindowStatistic',signature='ChangePointModelCVM',definition=
function(cpm,x) {
cpm@windowStatistic$X <- c(cpm@windowStatistic$X,x)
cpm@windowStatistic$N <- c(cpm@windowStatistic$N,cpm@n)
return(cpm@windowStatistic)
})
setMethod(f='getTestStatistics',signature='ChangePointModelCVM',definition=
function(cpm) {
X <- cpm@windowStatistic$X
if (length(X) < cpm@startup) {
results <- list();
results$val <- -Inf
results$MLE <- 0
results$Ds <- numeric()
return(results)
}
ord <- order(X)
len <- length(X)
res<-.C('cpmMLECVM',as.double(X),as.integer(length(X)),as.integer(ord),Ds=double(length(X)))
Ds <- res[['Ds']]
Ds[c(1,len-1,len)]<-0
results <- list()
results$val <- max(Ds)
results$MLE <- which.max(Ds)
results$Ds <- Ds
return(results)
}) |
coxplsDR <- function (Xplan, ...) UseMethod("coxplsDR") |
PlaceBetIf <- function(...) {
PlaceBet(...)
} |
ctStanProfileCI <- function(fit, parnames){
ll=fit$stanfit$optimfit$value
cores=1
np=length(fit$stanfit$rawest)
smf=stan_reinitsf(fit$stanmodel,fit$standata)
parsouter <- fit$stanfit$rawest
highpars = fit$stanfit$transformedpars_old[1:np,'97.5%']
lowpars = fit$stanfit$transformedpars_old[1:np,'2.5%']
parrows <- match(parnames,fit$setup$matsetup$parname)
cipars <- paste0('rawpopmeans',fit$setup$matsetup$param[parrows])
optimfit=list()
for(pi in 1:length(cipars)){
for(upperci in c(TRUE,FALSE)){
if(upperci) init=highpars else init=lowpars
neglpgf<-function(parm) {
pars<-parsouter
pars[-which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi])] <- parm
out<-try(log_prob(smf,upars=pars,adjust_transform=TRUE,gradient=TRUE),silent = TRUE)
attributes(out)$gradient <- attributes(out)$gradient[-which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi])]
if('try-error' %in% class(out)|| all(is.nan(out))) {
out[1]=-Inf
}
return(-out)
}
mizelpginner=list(
fg=function(innerpars){
r=neglpgf(innerpars)
r=list(fn=r[1], gr= -attributes(r)$gradient)
return(r)
},
fn=neglpgf,
gr=function(innerpars) -attributes(neglpgf(innerpars))$gradient
)
mizelpgouter_fn <- function(parx){
message('parx = ',parx)
parsouter <<-fit$stanfit$rawest
parsouter[which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi])] <<- parx
pll=abs( (fit$stanfit$optimfit$value - 1.96) - (-mize(parsouter[-which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi])],
fg=mizelpginner,
max_iter=99999,
method="L-BFGS",memory=100,
line_search='Schmidt',c1=1e-10,c2=.9,step0='schmidt',
abs_tol=1e-3,grad_tol=0,rel_tol=0,step_tol=0,ginf_tol=0)$f)) +
ifelse(upperci && parx < fit$stanfit$rawest[which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi])], 100, 0) +
ifelse(!upperci && parx > fit$stanfit$rawest[which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi])], 100, 0)
print(pll)
return(pll)
}
mizelpgouter=list(
fn=mizelpgouter_fn,
gr = function(parx){
parsouter<<-fit$stanfit$rawest
parsouter[which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi])] <<- parx + 1e-6
up=mizelpgouter_fn(parsouter[which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi]) ])
parsouter[which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi])] <<- parx - 1e-6
down=mizelpgouter_fn(parsouter[which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi]) ])
return( (up-down)/(2*1e-6))
}
)
optimfit <- mize(init[which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi]) ],
fg=mizelpgouter,
max_iter=99999,
method="L-BFGS",memory=100,
line_search='Schmidt',c1=1e-10,c2=.9,step0='schmidt',
abs_tol=1e-3,grad_tol=0,rel_tol=0,step_tol=0,ginf_tol=0)$par
if(upperci) highpars[which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi]) ] <- optimfit
if(!upperci) lowpars[which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi]) ] <- optimfit
}
}
lowcipars=lowpars[which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi]) ]
highcipars=highpars[which( rownames(fit$stanfit$transformedpars_old[1:np,]) %in% cipars[pi]) ]
low <- sapply(1:length(lowcipars),function(x) tform(parin = lowcipars[x],
transform = fit$setup$matsetup$transform[parrows[x]],
multiplier = fit$setup$matvalues$multiplier[parrows[x]],
meanscale = fit$setup$matvalues$meanscale[parrows[x]],
offset = fit$setup$matvalues$offset[parrows[x]],
inneroffset = fit$setup$matvalues$inneroffset[parrows[x]]))
high <- sapply(1:length(highcipars),function(x) tform(parin = highcipars[x],
transform = fit$setup$matsetup$transform[parrows[x]],
multiplier = fit$setup$matvalues$multiplier[parrows[x]],
meanscale = fit$setup$matvalues$meanscale[parrows[x]],
offset = fit$setup$matvalues$offset[parrows[x]],
inneroffset = fit$setup$matvalues$inneroffset[parrows[x]]))
out <- data.frame(param=parnames,low=low,high=high)
rownames(out) <- NULL
return(out)
} |
NULL
arid<- function(clim_norm, coeff_rad=NULL, coeff_Hargr = rep(0.75,12), monthly=FALSE, indices= 1:6)
{
if(monthly == FALSE)
{
Ia_y<- sum(clim_norm$P) / mean(clim_norm$Tm + 10)
if(mean(clim_norm$Tm) > 0) R<- sum(clim_norm$P)/mean(clim_norm$Tm) else R<-NA
Q<- 2000*sum(clim_norm$P)/(max(clim_norm$Tx + 273.15)^2 - min(clim_norm$Tn + 273.15)^2)
Io <- 10 * sum(clim_norm$P[clim_norm$Tm >0]) / sum(clim_norm$Tm[clim_norm$Tm >0] * 10)
lmv<-c(31,28.25,31,30,31,30,31,31,30,31,30,31)
ET_hargr<- (0.0023*(clim_norm$Tx - clim_norm$Tn)^(0.5)*(clim_norm$Tm+17.8)*coeff_rad)* lmv * coeff_Hargr
Im_y<-100*(sum(clim_norm$P) / sum(ET_hargr) -1)
Ai <- sum(clim_norm$P) / sum(ET_hargr)
aridity<-round(data.frame(Ia = Ia_y, Im = Im_y, Q=Q, R=R, Io=Io, Ai=Ai), 2)[indices]
} else
{
month_names<-c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
aridity<-NULL
Ia_m<- round(12* clim_norm$P / (clim_norm$Tm + 10), 2); names(Ia_m)<-1:12
Im_m<-round(1.65*(clim_norm$P / (clim_norm$Tm + 12.2))^(10/9), 2); names(Im_m)<-1:12
aridity$Ia<- Ia_m; names(aridity$Ia)<- month_names
aridity$Im<- Im_m; names(aridity$Im)<- month_names
if(length(indices) == 1 & (indices == 1 | indices == 2)[1])
aridity<-aridity[indices]
}
return(aridity)
} |
autplot1 <- function(x, chain=1, lag.max=NULL, partial=FALSE, col=mcmcplotsPalette(1), style=c("gray", "plain"), ylim=NULL, ...){
style <- match.arg(style)
if (partial){
ylab <- "Partial Autocorrelation"
xacf <- pacf(as.ts(x[[chain]]), lag.max = lag.max, plot = FALSE)
} else {
ylab <- "Autocorrelation"
xacf <- acf(as.ts(x[[chain]]), lag.max = lag.max, plot = FALSE)
}
clim <- c(-1, 1)*qnorm(0.975)/sqrt(xacf$n.used)
for (j in 1:nvar(x)) {
if (is.null(ylim)){
ylim <- range(c(clim, xacf$acf[, j, j]))
}
if (style=="gray"){
plot(xacf$lag[, j, j], xacf$acf[, j, j], type = "n", ylab = ylab, xlab = "Lag", ylim = ylim, bty="n", xaxt="n", yaxt="n", ...)
.graypr()
rect(par("usr")[1], clim[1], par("usr")[2], clim[2], col=rgb(0.5, 0.5, 0.5, 0.35), border=NA)
lines(xacf$lag[, j, j], xacf$acf[, j, j], type="h", lwd=2, col=col)
}
if (style=="plain"){
plot(xacf$lag[, j, j], xacf$acf[, j, j], type = "h", ylab = ylab, xlab = "Lag", ylim = ylim, lwd=2, ...)
abline(h=c(0, clim), col="gray")
}
}
} |
expected <- eval(parse(text="0L"));
test(id=0, code={
argv <- eval(parse(text="list(character(0), FALSE, FALSE)"));
.Internal(`unlink`(argv[[1]], argv[[2]], argv[[3]]));
}, o=expected); |
context('doc01')
doc <-
'Usage: prog'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 0)
expect_equivalent(res[NULL], list())
})
test_that('parsing "--xxx" works',{
expect_error(docopt(doc, '--xxx', strict=TRUE))
})
context('doc02')
doc <-
'Usage: prog [options]
Options: -a All.'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-a"], list("-a" = FALSE))
})
test_that('parsing "-a" works',{
res <- docopt(doc, '-a', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-a"], list("-a" = TRUE))
})
test_that('parsing "-x" works',{
expect_error(docopt(doc, '-x', strict=TRUE))
})
context('doc03')
doc <-
'Usage: prog [options]
Options: --all All.'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--all"], list("--all" = FALSE))
})
test_that('parsing "--all" works',{
res <- docopt(doc, '--all', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--all"], list("--all" = TRUE))
})
test_that('parsing "--xxx" works',{
expect_error(docopt(doc, '--xxx', strict=TRUE))
})
context('doc04')
doc <-
'Usage: prog [options]
Options: -v, --verbose Verbose.'
test_that('parsing "--verbose" works',{
res <- docopt(doc, '--verbose', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--verbose"], list("--verbose" = TRUE))
})
test_that('parsing "--ver" works',{
res <- docopt(doc, '--ver', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--verbose"], list("--verbose" = TRUE))
})
test_that('parsing "-v" works',{
res <- docopt(doc, '-v', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--verbose"], list("--verbose" = TRUE))
})
context('doc05')
doc <-
'Usage: prog [options]
Options: -p PATH'
test_that('parsing "-p home/" works',{
res <- docopt(doc, '-p home/', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-p"], list("-p" = "home/"))
})
test_that('parsing "-phome/" works',{
res <- docopt(doc, '-phome/', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-p"], list("-p" = "home/"))
})
test_that('parsing "-p" works',{
expect_error(docopt(doc, '-p', strict=TRUE))
})
context('doc06')
doc <-
'Usage: prog [options]
Options: --path <path>'
test_that('parsing "--path home/" works',{
res <- docopt(doc, '--path home/', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--path"], list("--path" = "home/"))
})
test_that('parsing "--path=home/" works',{
res <- docopt(doc, '--path=home/', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--path"], list("--path" = "home/"))
})
test_that('parsing "--pa home/" works',{
res <- docopt(doc, '--pa home/', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--path"], list("--path" = "home/"))
})
test_that('parsing "--pa=home/" works',{
res <- docopt(doc, '--pa=home/', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--path"], list("--path" = "home/"))
})
test_that('parsing "--path" works',{
expect_error(docopt(doc, '--path', strict=TRUE))
})
context('doc07')
doc <-
'Usage: prog [options]
Options: -p PATH, --path=<path> Path to files.'
test_that('parsing "-proot" works',{
res <- docopt(doc, '-proot', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--path"], list("--path" = "root"))
})
context('doc08')
doc <-
'Usage: prog [options]
Options: -p --path PATH Path to files.'
test_that('parsing "-p root" works',{
res <- docopt(doc, '-p root', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--path"], list("--path" = "root"))
})
test_that('parsing "--path root" works',{
res <- docopt(doc, '--path root', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--path"], list("--path" = "root"))
})
context('doc09')
doc <-
'Usage: prog [options]
Options:
-p PATH Path to files [default: ./]'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-p"], list("-p" = "./"))
})
test_that('parsing "-phome" works',{
res <- docopt(doc, '-phome', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-p"], list("-p" = "home"))
})
context('doc10')
doc <-
'UsAgE: prog [options]
OpTiOnS: --path=<files> Path to files
[dEfAuLt: /root]'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--path"], list("--path" = "/root"))
})
test_that('parsing "--path=home" works',{
res <- docopt(doc, '--path=home', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--path"], list("--path" = "home"))
})
context('doc11')
doc <-
'usage: prog [options]
options:
-a Add
-r Remote
-m <msg> Message'
test_that('parsing "-a -r -m Hello" works',{
res <- docopt(doc, '-a -r -m Hello', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("-a", "-r", "-m")], list("-a" = TRUE, "-r" = TRUE, "-m" = "Hello"))
})
test_that('parsing "-armyourass" works',{
res <- docopt(doc, '-armyourass', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("-a", "-r", "-m")], list("-a" = TRUE, "-r" = TRUE, "-m" = "yourass"))
})
test_that('parsing "-a -r" works',{
res <- docopt(doc, '-a -r', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("-a", "-r", "-m")], list("-a" = TRUE, "-r" = TRUE, "-m" = NULL))
})
context('doc12')
doc <-
'Usage: prog [options]
Options: --version
--verbose'
test_that('parsing "--version" works',{
res <- docopt(doc, '--version', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("--version", "--verbose")], list("--version" = TRUE, "--verbose" = FALSE))
})
test_that('parsing "--verbose" works',{
res <- docopt(doc, '--verbose', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("--version", "--verbose")], list("--version" = FALSE, "--verbose" = TRUE))
})
test_that('parsing "--ver" works',{
expect_error(docopt(doc, '--ver', strict=TRUE))
})
test_that('parsing "--verb" works',{
res <- docopt(doc, '--verb', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("--version", "--verbose")], list("--version" = FALSE, "--verbose" = TRUE))
})
context('doc13')
doc <-
'usage: prog [-a -r -m <msg>]
options:
-a Add
-r Remote
-m <msg> Message'
test_that('parsing "-armyourass" works',{
res <- docopt(doc, '-armyourass', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("-a", "-r", "-m")], list("-a" = TRUE, "-r" = TRUE, "-m" = "yourass"))
})
context('doc14')
doc <-
'usage: prog [-armmsg]
options: -a Add
-r Remote
-m <msg> Message'
test_that('parsing "-a -r -m Hello" works',{
res <- docopt(doc, '-a -r -m Hello', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("-a", "-r", "-m")], list("-a" = TRUE, "-r" = TRUE, "-m" = "Hello"))
})
context('doc15')
doc <-
'usage: prog -a -b
options:
-a
-b'
test_that('parsing "-a -b" works',{
res <- docopt(doc, '-a -b', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = TRUE, "-b" = TRUE))
})
test_that('parsing "-b -a" works',{
res <- docopt(doc, '-b -a', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = TRUE, "-b" = TRUE))
})
test_that('parsing "-a" works',{
expect_error(docopt(doc, '-a', strict=TRUE))
})
test_that('parsing "" works',{
expect_error(docopt(doc, '', strict=TRUE))
})
context('doc16')
doc <-
'usage: prog (-a -b)
options: -a
-b'
test_that('parsing "-a -b" works',{
res <- docopt(doc, '-a -b', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = TRUE, "-b" = TRUE))
})
test_that('parsing "-b -a" works',{
res <- docopt(doc, '-b -a', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = TRUE, "-b" = TRUE))
})
test_that('parsing "-a" works',{
expect_error(docopt(doc, '-a', strict=TRUE))
})
test_that('parsing "" works',{
expect_error(docopt(doc, '', strict=TRUE))
})
context('doc17')
doc <-
'usage: prog [-a] -b
options: -a
-b'
test_that('parsing "-a -b" works',{
res <- docopt(doc, '-a -b', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = TRUE, "-b" = TRUE))
})
test_that('parsing "-b -a" works',{
res <- docopt(doc, '-b -a', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = TRUE, "-b" = TRUE))
})
test_that('parsing "-a" works',{
expect_error(docopt(doc, '-a', strict=TRUE))
})
test_that('parsing "-b" works',{
res <- docopt(doc, '-b', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = FALSE, "-b" = TRUE))
})
test_that('parsing "" works',{
expect_error(docopt(doc, '', strict=TRUE))
})
context('doc18')
doc <-
'usage: prog [(-a -b)]
options: -a
-b'
test_that('parsing "-a -b" works',{
res <- docopt(doc, '-a -b', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = TRUE, "-b" = TRUE))
})
test_that('parsing "-b -a" works',{
res <- docopt(doc, '-b -a', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = TRUE, "-b" = TRUE))
})
test_that('parsing "-a" works',{
expect_error(docopt(doc, '-a', strict=TRUE))
})
test_that('parsing "-b" works',{
expect_error(docopt(doc, '-b', strict=TRUE))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = FALSE, "-b" = FALSE))
})
context('doc19')
doc <-
'usage: prog (-a|-b)
options: -a
-b'
test_that('parsing "-a -b" works',{
expect_error(docopt(doc, '-a -b', strict=TRUE))
})
test_that('parsing "" works',{
expect_error(docopt(doc, '', strict=TRUE))
})
test_that('parsing "-a" works',{
res <- docopt(doc, '-a', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = TRUE, "-b" = FALSE))
})
test_that('parsing "-b" works',{
res <- docopt(doc, '-b', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = FALSE, "-b" = TRUE))
})
context('doc20')
doc <-
'usage: prog [ -a | -b ]
options: -a
-b'
test_that('parsing "-a -b" works',{
expect_error(docopt(doc, '-a -b', strict=TRUE))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = FALSE, "-b" = FALSE))
})
test_that('parsing "-a" works',{
res <- docopt(doc, '-a', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = TRUE, "-b" = FALSE))
})
test_that('parsing "-b" works',{
res <- docopt(doc, '-b', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = FALSE, "-b" = TRUE))
})
context('doc21')
doc <-
'usage: prog <arg>'
test_that('parsing "10" works',{
res <- docopt(doc, '10', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["<arg>"], list("<arg>" = "10"))
})
test_that('parsing "10 20" works',{
expect_error(docopt(doc, '10 20', strict=TRUE))
})
test_that('parsing "" works',{
expect_error(docopt(doc, '', strict=TRUE))
})
context('doc22')
doc <-
'usage: prog [<arg>]'
test_that('parsing "10" works',{
res <- docopt(doc, '10', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["<arg>"], list("<arg>" = "10"))
})
test_that('parsing "10 20" works',{
expect_error(docopt(doc, '10 20', strict=TRUE))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["<arg>"], list("<arg>" = NULL))
})
context('doc23')
doc <-
'usage: prog <kind> <name> <type>'
test_that('parsing "10 20 40" works',{
res <- docopt(doc, '10 20 40', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("<kind>", "<name>", "<type>")], list("<kind>" = "10", "<name>" = "20", "<type>" = "40"))
})
test_that('parsing "10 20" works',{
expect_error(docopt(doc, '10 20', strict=TRUE))
})
test_that('parsing "" works',{
expect_error(docopt(doc, '', strict=TRUE))
})
context('doc24')
doc <-
'usage: prog <kind> [<name> <type>]'
test_that('parsing "10 20 40" works',{
res <- docopt(doc, '10 20 40', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("<kind>", "<name>", "<type>")], list("<kind>" = "10", "<name>" = "20", "<type>" = "40"))
})
test_that('parsing "10 20" works',{
res <- docopt(doc, '10 20', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("<kind>", "<name>", "<type>")], list("<kind>" = "10", "<name>" = "20", "<type>" = NULL))
})
test_that('parsing "" works',{
expect_error(docopt(doc, '', strict=TRUE))
})
context('doc25')
doc <-
'usage: prog [<kind> | <name> <type>]'
test_that('parsing "10 20 40" works',{
expect_error(docopt(doc, '10 20 40', strict=TRUE))
})
test_that('parsing "20 40" works',{
res <- docopt(doc, '20 40', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("<kind>", "<name>", "<type>")], list("<kind>" = NULL, "<name>" = "20", "<type>" = "40"))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("<kind>", "<name>", "<type>")], list("<kind>" = NULL, "<name>" = NULL, "<type>" = NULL))
})
context('doc26')
doc <-
'usage: prog (<kind> --all | <name>)
options:
--all'
test_that('parsing "10 --all" works',{
res <- docopt(doc, '10 --all', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("<kind>", "--all", "<name>")], list("<kind>" = "10", "--all" = TRUE, "<name>" = NULL))
})
test_that('parsing "10" works',{
res <- docopt(doc, '10', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("<kind>", "--all", "<name>")], list("<kind>" = NULL, "--all" = FALSE, "<name>" = "10"))
})
test_that('parsing "" works',{
expect_error(docopt(doc, '', strict=TRUE))
})
context('doc27')
doc <-
'usage: prog [<name> <name>]'
test_that('parsing "10 20" works',{
res <- docopt(doc, '10 20', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["<name>"], list("<name>" = c("10", "20")))
})
test_that('parsing "10" works',{
res <- docopt(doc, '10', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["<name>"], list("<name>" = "10"))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["<name>"], list("<name>" = list()))
})
context('doc28')
doc <-
'usage: prog [(<name> <name>)]'
test_that('parsing "10 20" works',{
res <- docopt(doc, '10 20', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["<name>"], list("<name>" = c("10", "20")))
})
test_that('parsing "10" works',{
expect_error(docopt(doc, '10', strict=TRUE))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["<name>"], list("<name>" = list()))
})
context('doc29')
doc <-
'usage: prog NAME...'
test_that('parsing "10 20" works',{
res <- docopt(doc, '10 20', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["NAME"], list(NAME = c("10", "20")))
})
test_that('parsing "10" works',{
res <- docopt(doc, '10', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["NAME"], list(NAME = "10"))
})
test_that('parsing "" works',{
expect_error(docopt(doc, '', strict=TRUE))
})
context('doc30')
doc <-
'usage: prog [NAME]...'
test_that('parsing "10 20" works',{
res <- docopt(doc, '10 20', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["NAME"], list(NAME = c("10", "20")))
})
test_that('parsing "10" works',{
res <- docopt(doc, '10', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["NAME"], list(NAME = "10"))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["NAME"], list(NAME = list()))
})
context('doc31')
doc <-
'usage: prog [NAME...]'
test_that('parsing "10 20" works',{
res <- docopt(doc, '10 20', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["NAME"], list(NAME = c("10", "20")))
})
test_that('parsing "10" works',{
res <- docopt(doc, '10', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["NAME"], list(NAME = "10"))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["NAME"], list(NAME = list()))
})
context('doc32')
doc <-
'usage: prog [NAME [NAME ...]]'
test_that('parsing "10 20" works',{
res <- docopt(doc, '10 20', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["NAME"], list(NAME = c("10", "20")))
})
test_that('parsing "10" works',{
res <- docopt(doc, '10', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["NAME"], list(NAME = "10"))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["NAME"], list(NAME = list()))
})
context('doc33')
doc <-
'usage: prog (NAME | --foo NAME)
options: --foo'
test_that('parsing "10" works',{
res <- docopt(doc, '10', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("NAME", "--foo")], list(NAME = "10", "--foo" = FALSE))
})
test_that('parsing "--foo 10" works',{
res <- docopt(doc, '--foo 10', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("NAME", "--foo")], list(NAME = "10", "--foo" = TRUE))
})
test_that('parsing "--foo=10" works',{
expect_error(docopt(doc, '--foo=10', strict=TRUE))
})
context('doc34')
doc <-
'usage: prog (NAME | --foo) [--bar | NAME]
options: --foo
options: --bar'
test_that('parsing "10" works',{
res <- docopt(doc, '10', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("NAME", "--foo", "--bar")], list(NAME = "10", "--foo" = FALSE, "--bar" = FALSE))
})
test_that('parsing "10 20" works',{
res <- docopt(doc, '10 20', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("NAME", "--foo", "--bar")], list(NAME = c("10", "20"), "--foo" = FALSE, "--bar" = FALSE))
})
test_that('parsing "--foo --bar" works',{
res <- docopt(doc, '--foo --bar', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("NAME", "--foo", "--bar")], list(NAME = list(), "--foo" = TRUE, "--bar" = TRUE))
})
context('doc35')
doc <-
'Naval Fate.
Usage:
prog ship new <name>...
prog ship [<name>] move <x> <y> [--speed=<kn>]
prog ship shoot <x> <y>
prog mine (set|remove) <x> <y> [--moored|--drifting]
prog -h | --help
prog --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Mored (anchored) mine.
--drifting Drifting mine.'
test_that('parsing "ship Guardian move 150 300 --speed=20" works',{
res <- docopt(doc, 'ship Guardian move 150 300 --speed=20', strict=TRUE)
expect_equivalent(length(res), 15)
expect_equivalent(res[c("--drifting", "--help", "--moored", "--speed", "--version","<name>", "<x>", "<y>", "mine", "move", "new", "remove", "set", "ship", "shoot")], list("--drifting" = FALSE, "--help" = FALSE, "--moored" = FALSE, "--speed" = "20", "--version" = FALSE, "<name>" = "Guardian", "<x>" = "150", "<y>" = "300", mine = FALSE, move = TRUE, new = FALSE, remove = FALSE, set = FALSE, ship = TRUE, shoot = FALSE))
})
context('doc36')
doc <-
'usage: prog --hello'
test_that('parsing "--hello" works',{
res <- docopt(doc, '--hello', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--hello"], list("--hello" = TRUE))
})
context('doc37')
doc <-
'usage: prog [--hello=<world>]'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--hello"], list("--hello" = NULL))
})
test_that('parsing "--hello wrld" works',{
res <- docopt(doc, '--hello wrld', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--hello"], list("--hello" = "wrld"))
})
context('doc38')
doc <-
'usage: prog [-o]'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-o"], list("-o" = FALSE))
})
test_that('parsing "-o" works',{
res <- docopt(doc, '-o', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-o"], list("-o" = TRUE))
})
context('doc39')
doc <-
'usage: prog [-opr]'
test_that('parsing "-op" works',{
res <- docopt(doc, '-op', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("-o", "-p", "-r")], list("-o" = TRUE, "-p" = TRUE, "-r" = FALSE))
})
context('doc40')
doc <-
'usage: prog --aabb | --aa'
test_that('parsing "--aa" works',{
res <- docopt(doc, '--aa', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("--aabb", "--aa")], list("--aabb" = FALSE, "--aa" = TRUE))
})
context('doc41')
doc <-
'Usage: prog -v'
test_that('parsing "-v" works',{
res <- docopt(doc, '-v', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-v"], list("-v" = TRUE))
})
context('doc42')
doc <-
'Usage: prog [-v -v]'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-v"], list("-v" = 0))
})
test_that('parsing "-v" works',{
res <- docopt(doc, '-v', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-v"], list("-v" = 1))
})
test_that('parsing "-vv" works',{
res <- docopt(doc, '-vv', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-v"], list("-v" = 2))
})
context('doc43')
doc <-
'Usage: prog -v ...'
test_that('parsing "" works',{
expect_error(docopt(doc, '', strict=TRUE))
})
test_that('parsing "-v" works',{
res <- docopt(doc, '-v', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-v"], list("-v" = 1))
})
test_that('parsing "-vv" works',{
res <- docopt(doc, '-vv', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-v"], list("-v" = 2))
})
test_that('parsing "-vvvvvv" works',{
res <- docopt(doc, '-vvvvvv', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-v"], list("-v" = 6))
})
context('doc44')
doc <-
'Usage: prog [-v | -vv | -vvv]
This one is probably most readable user-friednly variant.'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-v"], list("-v" = 0))
})
test_that('parsing "-v" works',{
res <- docopt(doc, '-v', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-v"], list("-v" = 1))
})
test_that('parsing "-vv" works',{
res <- docopt(doc, '-vv', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-v"], list("-v" = 2))
})
test_that('parsing "-vvvv" works',{
expect_error(docopt(doc, '-vvvv', strict=TRUE))
})
context('doc45')
doc <-
'usage: prog [--ver --ver]'
test_that('parsing "--ver --ver" works',{
skip("not implemented")
res <- docopt(doc, '--ver --ver', strict=TRUE)
expect_equivalent(length(res), 1)
skip_on_cran()
expect_equivalent(res["--ver"], list("--ver" = 2))
})
context('doc46')
doc <-
'usage: prog [go]'
test_that('parsing "go" works',{
res <- docopt(doc, 'go', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["go"], list(go = TRUE))
})
context('doc47')
doc <-
'usage: prog [go go]'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["go"], list(go = 0))
})
test_that('parsing "go" works',{
skip("not implemented")
res <- docopt(doc, 'go', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["go"], list(go = 1))
})
test_that('parsing "go go" works',{
skip("not implemented")
res <- docopt(doc, 'go go', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["go"], list(go = 2))
})
test_that('parsing "go go go" works',{
expect_error(docopt(doc, 'go go go', strict=TRUE))
})
context('doc48')
doc <-
'usage: prog go...'
test_that('parsing "go go go go go" works',{
skip("not implemented")
res <- docopt(doc, 'go go go go go', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["go"], list(go = 5))
})
test_that('parsing "-a" works',{
skip("not implemented")
res <- docopt(doc, '-a', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-a", "-b")], list("-a" = TRUE, "-b" = FALSE))
})
test_that('parsing "-aa" works',{
expect_error(docopt(doc, '-aa', strict=TRUE))
})
context('doc49')
doc <-
'Usage: prog [options] A
Options:
-q Be quiet
-v Be verbose.'
test_that('parsing "arg" works',{
res <- docopt(doc, 'arg', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("A", "-v", "-q")], list(A = "arg", "-v" = FALSE, "-q" = FALSE))
})
test_that('parsing "-v arg" works',{
res <- docopt(doc, '-v arg', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("A", "-v", "-q")], list(A = "arg", "-v" = TRUE, "-q" = FALSE))
})
test_that('parsing "-q arg" works',{
res <- docopt(doc, '-q arg', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("A", "-v", "-q")], list(A = "arg", "-v" = FALSE, "-q" = TRUE))
})
context('doc50')
doc <-
'usage: prog [-]'
test_that('parsing "-" works',{
res <- docopt(doc, '-', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-"], list("-" = TRUE))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-"], list("-" = FALSE))
})
context('doc51')
doc <-
'usage: prog [NAME [NAME ...]]'
test_that('parsing "a b" works',{
res <- docopt(doc, 'a b', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["NAME"], list(NAME = c("a", "b")))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["NAME"], list(NAME = list()))
})
context('doc52')
doc <-
'usage: prog [options]
options:
-a Add
-m <msg> Message'
test_that('parsing "-a" works',{
res <- docopt(doc, '-a', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-m", "-a")], list("-m" = NULL, "-a" = TRUE))
})
context('doc53')
doc <-
'usage: prog --hello'
test_that('parsing "--hello" works',{
res <- docopt(doc, '--hello', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--hello"], list("--hello" = TRUE))
})
context('doc54')
doc <-
'usage: prog [--hello=<world>]'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--hello"], list("--hello" = NULL))
})
test_that('parsing "--hello wrld" works',{
res <- docopt(doc, '--hello wrld', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--hello"], list("--hello" = "wrld"))
})
context('doc55')
doc <-
'usage: prog [-o]'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-o"], list("-o" = FALSE))
})
test_that('parsing "-o" works',{
res <- docopt(doc, '-o', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-o"], list("-o" = TRUE))
})
context('doc56')
doc <-
'usage: prog [-opr]'
test_that('parsing "-op" works',{
res <- docopt(doc, '-op', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("-o", "-p", "-r")], list("-o" = TRUE, "-p" = TRUE, "-r" = FALSE))
})
context('doc57')
doc <-
'usage: git [-v | --verbose]'
test_that('parsing "-v" works',{
res <- docopt(doc, '-v', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("-v", "--verbose")], list("-v" = TRUE, "--verbose" = FALSE))
})
context('doc58')
doc <-
'usage: git remote [-v | --verbose]'
test_that('parsing "remote -v" works',{
res <- docopt(doc, 'remote -v', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("remote", "-v", "--verbose")], list(remote = TRUE, "-v" = TRUE, "--verbose" = FALSE))
})
context('doc59')
doc <-
'usage: prog'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 0)
expect_equivalent(res[NULL], list())
})
context('doc60')
doc <-
'usage: prog
prog <a> <b>'
test_that('parsing "1 2" works',{
res <- docopt(doc, '1 2', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("<a>", "<b>")], list("<a>" = "1", "<b>" = "2"))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("<a>", "<b>")], list("<a>" = NULL, "<b>" = NULL))
})
context('doc61')
doc <-
'usage: prog <a> <b>
prog'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("<a>", "<b>")], list("<a>" = NULL, "<b>" = NULL))
})
context('doc62')
doc <-
'usage: prog [--file=<f>]'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--file"], list("--file" = NULL))
})
context('doc63')
doc <-
'usage: prog [--file=<f>]
options: --file <a>'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--file"], list("--file" = NULL))
})
context('doc64')
doc <-
'Usage: prog [-a <host:port>]
Options: -a, --address <host:port> TCP address [default: localhost:6283].'
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--address"], list("--address" = "localhost:6283"))
})
context('doc65')
doc <-
'usage: prog --long=<arg> ...'
test_that('parsing "--long one" works',{
res <- docopt(doc, '--long one', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--long"], list("--long" = "one"))
})
test_that('parsing "--long one --long two" works',{
res <- docopt(doc, '--long one --long two', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--long"], list("--long" = c("one", "two")))
})
context('doc66')
doc <-
'usage: prog (go <direction> --speed=<km/h>)...'
test_that('parsing "go left --speed=5 go right --speed=9" works',{
skip("not implemented")
res <- docopt(doc, 'go left --speed=5 go right --speed=9', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("go", "<direction>", "--speed")], list(go = 2, "<direction>" = c("left", "right"), "--speed" = c("5", "9")))
})
context('doc67')
doc <-
'usage: prog [options] -a
options: -a'
skip("not implemented")
test_that('parsing "-a" works',{
res <- docopt(doc, '-a', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-a"], list("-a" = TRUE))
})
context('doc68')
doc <-
'usage: prog [-o <o>]...
options: -o <o> [default: x]'
test_that('parsing "-o this -o that" works',{
res <- docopt(doc, '-o this -o that', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-o"], list("-o" = c("this", "that")))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-o"], list("-o" = "x"))
})
context('doc69')
doc <-
'usage: prog [-o <o>]...
options: -o <o> [default: x y]'
test_that('parsing "-o this" works',{
res <- docopt(doc, '-o this', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-o"], list("-o" = "this"))
})
test_that('parsing "" works',{
res <- docopt(doc, '', strict=TRUE)
expect_equivalent(length(res), 1)
skip("not implemented")
expect_equivalent(res["-o"], list("-o" = c("x", "y")))
})
context('doc70')
doc <-
'usage: prog -pPATH
options: -p PATH'
test_that('parsing "-pHOME" works',{
res <- docopt(doc, '-pHOME', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["-p"], list("-p" = "HOME"))
})
context('doc71')
doc <-
'Usage: foo (--xx=x|--yy=y)...'
test_that('parsing "--xx=1 --yy=2" works',{
res <- docopt(doc, '--xx=1 --yy=2', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("--xx", "--yy")], list("--xx" = "1", "--yy" = "2"))
})
context('doc72')
doc <-
'usage: prog [<input file>]'
test_that('parsing "f.txt" works',{
res <- docopt(doc, 'f.txt', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["<input file>"], list("<input file>" = "f.txt"))
})
context('doc73')
doc <-
'usage: prog [--input=<file name>]...'
test_that('parsing "--input a.txt --input=b.txt" works',{
res <- docopt(doc, '--input a.txt --input=b.txt', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--input"], list("--input" = c("a.txt", "b.txt")))
})
context('doc74')
doc <-
'usage: prog good [options]
prog fail [options]
options: --loglevel=N'
test_that('parsing "fail --loglevel 5" works',{
res <- docopt(doc, 'fail --loglevel 5', strict=TRUE)
expect_equivalent(length(res), 3)
expect_equivalent(res[c("--loglevel", "fail", "good")], list("--loglevel" = "5", fail = TRUE, good = FALSE))
})
context('doc75')
doc <-
'usage:prog --foo'
test_that('parsing "--foo" works',{
res <- docopt(doc, '--foo', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--foo"], list("--foo" = TRUE))
})
context('doc76')
doc <-
'PROGRAM USAGE: prog --foo'
test_that('parsing "--foo" works',{
res <- docopt(doc, '--foo', strict=TRUE)
expect_equivalent(length(res), 1)
expect_equivalent(res["--foo"], list("--foo" = TRUE))
})
context('doc77')
doc <-
'Usage: prog --foo
prog --bar
NOT PART OF SECTION'
test_that('parsing "--foo" works',{
res <- docopt(doc, '--foo', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("--foo", "--bar")], list("--foo" = TRUE, "--bar" = FALSE))
})
context('doc78')
doc <-
'Usage:
prog --foo
prog --bar
NOT PART OF SECTION'
test_that('parsing "--foo" works',{
res <- docopt(doc, '--foo', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("--foo", "--bar")], list("--foo" = TRUE, "--bar" = FALSE))
})
context('doc79')
doc <-
'Usage:
prog --foo
prog --bar
NOT PART OF SECTION'
test_that('parsing "--foo" works',{
res <- docopt(doc, '--foo', strict=TRUE)
expect_equivalent(length(res), 2)
expect_equivalent(res[c("--foo", "--bar")], list("--foo" = TRUE, "--bar" = FALSE))
})
context('doc80')
doc <-
'Usage: prog [options]
global options: --foo
local options: --baz
--bar
other options:
--egg
--spam
-not-an-option-'
test_that('parsing "--baz --egg" works',{
res <- docopt(doc, '--baz --egg', strict=TRUE)
skip("not implemented")
expect_equivalent(length(res), 5)
expect_equivalent(res[c("--foo", "--baz", "--bar", "--egg", "--spam")], list("--foo" = FALSE, "--baz" = TRUE, "--bar" = FALSE, "--egg" = TRUE, "--spam" = FALSE))
}) |
do <- function(.data, ...) {
lifecycle::signal_stage("superseded", "do()")
UseMethod("do")
}
do.NULL <- function(.data, ...) {
NULL
}
do.grouped_df <- function(.data, ...) {
index <- group_rows(.data)
labels <- select(group_data(.data), -last_col())
attr(labels, ".drop") <- NULL
group_data <- ungroup(.data)
args <- enquos(...)
named <- named_args(args)
mask <- new_data_mask(new_environment())
n <- length(index)
m <- length(args)
if (n == 0) {
if (named) {
out <- rep_len(list(list()), length(args))
out <- set_names(out, names(args))
out <- label_output_list(labels, out, groups(.data))
} else {
env_bind_do_pronouns(mask, group_data)
out <- eval_tidy(args[[1]], mask)
out <- out[0, , drop = FALSE]
out <- label_output_dataframe(labels, list(list(out)), group_vars(.data), group_by_drop_default(.data))
}
return(out)
}
group_slice <- function(value) {
if (missing(value)) {
group_data[index[[`_i`]], , drop = FALSE]
} else {
group_data[index[[`_i`]], ] <<- value
}
}
env_bind_do_pronouns(mask, group_slice)
out <- replicate(m, vector("list", n), simplify = FALSE)
names(out) <- names(args)
p <- rlang::with_options(
lifecycle_verbosity = "quiet",
progress_estimated(n * m, min_time = 2)
)
for (`_i` in seq_len(n)) {
for (j in seq_len(m)) {
out[[j]][`_i`] <- list(eval_tidy(args[[j]], mask))
p$tick()$print()
}
}
if (!named) {
label_output_dataframe(labels, out, group_vars(.data), group_by_drop_default(.data))
} else {
label_output_list(labels, out, group_vars(.data))
}
}
do.data.frame <- function(.data, ...) {
args <- enquos(...)
named <- named_args(args)
mask <- new_data_mask(new_environment())
env_bind_do_pronouns(mask, .data)
if (!named) {
out <- eval_tidy(args[[1]], mask)
if (!inherits(out, "data.frame")) {
msg <- glue("Result must be a data frame, not {fmt_classes(out)}.")
abort(msg)
}
} else {
out <- map(args, function(arg) list(eval_tidy(arg, mask)))
names(out) <- names(args)
out <- tibble::as_tibble(out, .name_repair = "minimal")
}
out
}
env_bind_do_pronouns <- function(env, data) {
if (is_function(data)) {
bind <- env_bind_active
} else {
bind <- env_bind
}
bind(env, "." := data, .data = data)
}
label_output_dataframe <- function(labels, out, groups, .drop, error_call = caller_env()) {
data_frame <- vapply(out[[1]], is.data.frame, logical(1))
if (any(!data_frame)) {
msg <- glue(
"Results {bad} must be data frames, not {first_bad_class}.",
bad = fmt_comma(which(!data_frame)),
first_bad_class = fmt_classes(out[[1]][[which.min(data_frame)]])
)
abort(msg, call = error_call)
}
rows <- vapply(out[[1]], nrow, numeric(1))
out <- bind_rows(out[[1]])
if (!is.null(labels)) {
labels <- labels[setdiff(names(labels), names(out))]
labels <- labels[rep(seq_len(nrow(labels)), rows), , drop = FALSE]
rownames(labels) <- NULL
grouped_df(bind_cols(labels, out), groups, .drop)
} else {
rowwise(out)
}
}
label_output_list <- function(labels, out, groups) {
if (!is.null(labels)) {
labels[names(out)] <- out
rowwise(labels)
} else {
class(out) <- "data.frame"
attr(out, "row.names") <- .set_row_names(length(out[[1]]))
rowwise(out)
}
}
named_args <- function(args, error_call = caller_env()) {
named <- sum(names2(args) != "")
if (!(named == 0 || named == length(args))) {
msg <- "Arguments must either be all named or all unnamed."
abort(msg, call = error_call)
}
if (named == 0 && length(args) > 1) {
msg <- glue("Can only supply one unnamed argument, not {length(args)}.")
abort(msg, call = error_call)
}
named != 0
}
do.rowwise_df <- function(.data, ...) {
group_data <- ungroup(.data)
args <- enquos(...)
named <- named_args(args)
mask <- new_data_mask(new_environment())
current_row <- function() lapply(group_data[`_i`, , drop = FALSE], "[[", 1)
env_bind_do_pronouns(mask, current_row)
n <- nrow(.data)
m <- length(args)
out <- replicate(m, vector("list", n), simplify = FALSE)
names(out) <- names(args)
p <- rlang::with_options(
lifecycle_verbosity = "quiet",
progress_estimated(n * m, min_time = 2)
)
for (`_i` in seq_len(n)) {
for (j in seq_len(m)) {
out[[j]][`_i`] <- list(eval_tidy(args[[j]], mask))
p$tick()$print()
}
}
if (!named) {
label_output_dataframe(NULL, out, groups(.data), group_by_drop_default(.data))
} else {
label_output_list(NULL, out, groups(.data))
}
} |
priorPosterior <- function(MCMCPrior, MCMCPosterior = NULL, inputTree, return.density=FALSE, rootCalibration = NULL) {
if(methods::is(MCMCPrior)[1] == "character") MCMCPrior <- utils::read.csv(MCMCPrior, sep="\t")
if(methods::is(MCMCPosterior)[1] == "character") MCMCPosterior <- utils::read.csv(MCMCPosterior, sep="\t")
s <- utils::read.table(inputTree, row.names=1)[,2]
s <- strsplit(as.character(s), "'")[[1]]
nodePr <- c(grep("SN[(]", s), grep("ST[(]", s), grep("B[(]", s), grep("U[(]", s), grep("L[(]", s), grep("U[(]", s))
s[nodePr] <- gsub("[(]", "~",s[nodePr])
s[nodePr] <- gsub("[)]", "",s[nodePr])
s[nodePr] <- gsub(",", "~",s[nodePr])
pl <- paste0(s, collapse="")
phylo <- ladderize(read.tree(text=pl))
nodeInfo <- which(phylo$node.label != "")
priors <- posteriors <- givenPriors <- list()
if (!is.null(rootCalibration)) {
nodeInfo <- c(1, nodeInfo)
phylo$node.label[1] <- rootCalibration
}
for(tt in 1:length(nodeInfo)) {
colNum <- as.numeric(sort(nodeInfo + Ntip(phylo))[tt])
noders <- strsplit(phylo$node.label[nodeInfo[tt]], "~")[[1]]
nodeType <- as.character(noders[1])
if(nodeType == "B") {
nums <- as.numeric(noders[2:5])
pr <- MCMCPrior[, paste0("t_n", colNum)]
if (!is.null(MCMCPosterior)) {
post <- MCMCPosterior[, paste0("t_n", colNum)]
}
names(nums) <- c("tL", "tU", "pL", "pU")[1:length(nums)]
}
if(nodeType == "SN") {
nums <- as.numeric(noders[-1])
pr <- MCMCPrior[, paste0("t_n", colNum)]
if (!is.null(MCMCPosterior)) {
post <- MCMCPosterior[,paste0("t_n", colNum)]
}
names(nums) <- c("location", "scale", "shape")
}
if(nodeType == "ST") {
nums <- as.numeric(noders[-1])
pr <- MCMCPrior[, paste0("t_n", colNum)]
if (!is.null(MCMCPosterior)) {
post <- MCMCPosterior[,paste0("t_n", colNum)]
}
names(nums) <- c("location", "scale", "shape", "df")
}
if(nodeType == "G") {
nums <- as.numeric(noders[2:3])
pr <- MCMCPrior[, paste0("t_n", colNum)]
if (!is.null(MCMCPosterior)) {
post <- MCMCPosterior[,paste0("t_n", colNum)]
}
names(nums) <- c("alpha", "beta")
}
if(nodeType == "L") {
nums <- as.numeric(noders[-1])
pr <- MCMCPrior[, paste0("t_n", colNum)]
if (!is.null(MCMCPosterior)) {
post <- MCMCPosterior[,paste0("t_n", colNum)]
}
names(nums) <- c("tL", "p", "c", "pL")
}
if(return.density) {
pr <- stats::density(pr)
post <- stats::density(post)
}
priors[[tt]] <- pr
names(priors)[tt] <- paste0(colNum, "_", nodeType)
posteriors[[tt]] <- post
names(posteriors)[tt] <- paste0(colNum, "_", nodeType)
givenPriors[[tt]] <- nums
names(givenPriors)[tt] <- paste0(colNum, "_", nodeType)
}
nodeValues <- list()
nodeValues$prior <- priors
nodeValues$posterior <- posteriors
nodeValues$specifiedPriors <- givenPriors
return(nodeValues)
} |
nlm_edgegradient <- function(ncol,
nrow,
resolution = 1,
direction = NA,
rescale = TRUE) {
checkmate::assert_count(ncol, positive = TRUE)
checkmate::assert_count(nrow, positive = TRUE)
checkmate::assert_numeric(resolution)
checkmate::assert_numeric(direction)
checkmate::assert_logical(rescale)
if (is.na(direction)) {
direction <- stats::runif(1, 0, 360)
}
gradient_raster <- nlm_planargradient(ncol, nrow,
resolution = resolution,
direction = direction)
edgegradient_raster <-
(abs(0.5 - gradient_raster) * -2) + 1
raster::extent(edgegradient_raster) <- c(
0,
ncol(edgegradient_raster) * resolution,
0,
nrow(edgegradient_raster) * resolution
)
if (rescale == TRUE) {
edgegradient_raster <- util_rescale(edgegradient_raster)
}
return(edgegradient_raster)
} |
which.at.boundary <- function(object, criterion = 1e-6){
if(class(object)[1]!="lexpit"&class(object)[1]!="blm")
stop("Object must be an instance of a blm or lexpit model.")
if(any(predict(object)<=criterion|predict(object)>=1-criterion)){
which <- which(predict(object)<=criterion|predict(object)>=1-criterion)
if(class(object)[1]=="lexpit")
cbind(model.matrix([email protected],object@data)[,-1],
model.matrix([email protected],object@data)[,-1])[which,]
else
cbind(model.matrix(object@formula,object@data)[,-1])[which,]
}
else{
cat("No boundary constraints using the given criterion.\n\n")
invisible(NA)
}
} |
library("matrixStats")
options(matrixStats.center.onUse = "ignore")
if (!exists("isFALSE", mode="function")) {
isFALSE <- function(x) is.logical(x) && length(x) == 1L && !is.na(x) && !x
}
rowVars_R <- function(x, na.rm = FALSE, center = NULL, ..., useNames = NA) {
suppressWarnings({
res <- apply(x, MARGIN = 1L, FUN = var, na.rm = na.rm)
})
stopifnot(!any(is.infinite(res)))
if (is.null(center) || ncol(x) <= 1L) {
if (is.na(useNames) || isFALSE(useNames)) names(res) <- NULL
}
else if (isFALSE(useNames)) names(res) <- NULL
res
}
colVars_R <- function(x, na.rm = FALSE, center = NULL, ..., useNames = NA) {
suppressWarnings({
res <- apply(x, MARGIN = 2L, FUN = var, na.rm = na.rm)
})
stopifnot(!any(is.infinite(res)))
if (is.null(center) || nrow(x) <= 1L) {
if (is.na(useNames) || isFALSE(useNames)) names(res) <- NULL
}
else if (isFALSE(useNames)) names(res) <- NULL
res
}
rowVars_center <- function(x, rows = NULL, cols = NULL, na.rm = FALSE, ..., useNames = NA) {
center <- rowWeightedMeans(x, cols = cols, na.rm = na.rm, useNames = FALSE)
res <- rowVars(x, rows = rows, cols = cols, center = center, na.rm = na.rm, useNames = useNames)
stopifnot(!any(is.infinite(res)))
res
}
colVars_center <- function(x, rows = NULL, cols = NULL, na.rm = FALSE, ..., useNames = NA) {
center <- colWeightedMeans(x, rows = rows, na.rm = na.rm, useNames = FALSE)
res <- colVars(x, rows = rows, cols = cols, center = center, na.rm = na.rm, useNames = useNames)
stopifnot(!any(is.infinite(res)))
res
}
source("utils/validateIndicesFramework.R")
x <- matrix(runif(6 * 6, min = -6, max = 6), nrow = 6, ncol = 6)
storage.mode(x) <- "integer"
dimnames <- list(letters[1:6], LETTERS[1:6])
for (setDimnames in c(TRUE, FALSE)) {
if (setDimnames) dimnames(x) <- dimnames
else dimnames(x) <- NULL
for (rows in index_cases) {
for (cols in index_cases) {
for (na.rm in c(TRUE, FALSE)) {
for (useNames in c(NA, TRUE, FALSE)) {
validateIndicesTestMatrix(x, rows, cols,
ftest = rowVars, fsure = rowVars_R,
na.rm = na.rm, useNames = useNames)
validateIndicesTestMatrix(x, rows, cols,
ftest = rowVars_center, fsure = rowVars_R,
na.rm = na.rm, center = TRUE, useNames = useNames)
validateIndicesTestMatrix(x, rows, cols,
fcoltest = colVars, fsure = rowVars_R,
na.rm = na.rm, useNames = useNames)
validateIndicesTestMatrix(x, rows, cols,
fcoltest = colVars_center, fsure = rowVars_R,
na.rm = na.rm, center = TRUE, useNames = useNames)
}
}
}
}
} |
NULL
backup <- function(config = list()) {
svc <- .backup$operations
svc <- set_config(svc, config)
return(svc)
}
.backup <- list()
.backup$operations <- list()
.backup$metadata <- list(
service_name = "backup",
endpoints = list("*" = list(endpoint = "backup.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "backup.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "backup.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "backup.{region}.sc2s.sgov.gov", global = FALSE)),
service_id = "Backup",
api_version = "2018-11-15",
signing_name = "backup",
json_version = "1.1",
target_prefix = ""
)
.backup$service <- function(config = list()) {
handlers <- new_handlers("restjson", "v4")
new_service(.backup$metadata, handlers, config)
} |
NULL
p.QFASA <- function(predator.mat,
prey.mat,
cal.mat,
dist.meas,
gamma = 1,
FC = rep(1, nrow(prey.mat)),
start.val = rep(0.99999, nrow(prey.mat)),
ext.fa) {
seal.mat <- predator.mat
seal.mat = as.matrix(seal.mat)
prey.mat = as.matrix(prey.mat)
cal.mat = as.matrix(cal.mat)
if ((is.vector(cal.mat)) || (nrow(cal.mat) == 1.) || (ncol(cal.mat ) == 1.)) {
seal.mat <- t(t(seal.mat)/as.vector(unlist(cal.mat)))
seal.mat <- as.data.frame(seal.mat)[ext.fa]
seal.mat <- seal.mat/apply(seal.mat, 1., sum)
seal.mat <- as.matrix(seal.mat)
}
else {
seal.mat <- seal.mat/t(cal.mat)
seal.mat <- as.data.frame(seal.mat)[ext.fa]
seal.mat <- seal.mat/apply(seal.mat, 1., sum)
seal.mat <- as.matrix(seal.mat)
}
I <- nrow(prey.mat)
ns <- nrow(seal.mat)
p.mat <- matrix(rep(0, nrow(prey.mat) * nrow(seal.mat)),
byrow = T,
nrow(seal.mat),
nrow(prey.mat))
more.list <- vector("list",ns)
if (!(is.matrix(start.val))) {
start.val <- matrix(rep(start.val, ns), byrow = T, ns, I)
}
if (dist.meas == 1) {
for (i in 1.:nrow(seal.mat)) {
p.all <- Rsolnp::solnp(pars = start.val[i, ],
fun = KL.obj,
predator = seal.mat[i, ],
prey.quantiles = prey.mat,
eqfun = QFASA.const.eqn,
eqB = 1,
LB = rep(0, nrow(prey.mat)),
UB = rep(0.999999, nrow(prey.mat)),
control=list(trace=0))
if (p.all$convergence!=0) {
cat("WARNING: DID NOT CONVERGE")
}
p.mat[i, ] <- p.all$par
more.list[[i]] <- KL.more(p.mat[i,],seal.mat[i,],prey.mat)
}
}
else if (dist.meas==2) {
for (i in 1.:nrow(seal.mat)) {
p.all <- Rsolnp::solnp(pars = start.val[i, ],
fun = AIT.obj,
predator = seal.mat[i, ],
prey.quantiles = prey.mat,
eqfun = QFASA.const.eqn,
eqB=1,
LB = rep(0, nrow(prey.mat)),
UB = rep(0.999999, nrow(prey.mat)),
control=list(trace=0))
if (p.all$convergence!=0) {
cat("WARNING: DID NOT CONVERGE")
}
p.mat[i, ] <- p.all$par
more.list[[i]] <- AIT.more(p.mat[i,],seal.mat[i,],prey.mat)
}
}
else {
for (i in 1.:nrow(seal.mat)) {
p.all <- Rsolnp::solnp(pars = start.val[i, ],
fun = CS.obj,
predator = seal.mat[i, ],
prey.quantiles = prey.mat,
gamma = gamma,
eqfun= QFASA.const.eqn,
eqB = 1,
LB = rep(0, nrow(prey.mat)),
UB = rep(0.999999, nrow(prey.mat)),
control=list(trace=0))
if (p.all$convergence!=0) {
cat("WARNING: DID NOT CONVERGE")
}
p.mat[i, ] <- p.all$par
more.list[[i]] <- CS.more(p.mat[i,],seal.mat[i,],prey.mat,gamma)
}
}
if (is.matrix(FC))
{ FC.mat <- FC
} else {
FC.mat <- matrix(rep(FC, nrow(seal.mat)), byrow = T, nrow(seal.mat), I)
}
p.mat <- p.mat/FC.mat
p.mat <- p.mat/apply(p.mat, 1, sum)
colnames(p.mat) <- as.vector(rownames(prey.mat))
out.list <- list(p.mat,more.list)
names(out.list) <- c("Diet Estimates","Additional Measures")
return(out.list)
}
AIT.dist <- function(x.1, x.2) {
return(sqrt(sum((log(x.1/mean.geometric(x.1)) - log(x.2/mean.geometric(x.2)))^2.)))
}
AIT.more <- function(alpha, predator, prey.quantiles) {
seal <- predator
no.zero <- sum(seal == 0.)
seal[seal == 0.] <- 1e-05
seal[seal > 0.] <- (1. - no.zero * 1e-05) * seal[seal > 0.]
sealhat <- t(as.matrix(alpha)) %*% prey.quantiles
no.zero <- sum(sealhat == 0.)
sealhat[sealhat == 0.] <- 1e-05
sealhat[sealhat > 0.] <- (1. - no.zero * 1e-05) * sealhat[sealhat > 0.]
AIT.sq.vec <-
( log(seal/mean.geometric(seal)) - log(sealhat/mean.geometric(sealhat)) )^2
dist <- (sum(AIT.sq.vec))^(1/2)
out.list <- list(sealhat,AIT.sq.vec,AIT.sq.vec/sum(AIT.sq.vec),dist)
names(out.list) <- c("ModFAS","DistCont", "PropDistCont","MinDist")
return(out.list)
}
AIT.obj <- function(alpha, predator, prey.quantiles) {
seal <- predator
no.zero <- sum(seal == 0.)
seal[seal == 0.] <- 1e-05
seal[seal > 0.] <- (1. - no.zero * 1e-05) * seal[seal > 0.]
sealhat <- t(as.matrix(alpha)) %*% prey.quantiles
no.zero <- sum(sealhat == 0.)
sealhat[sealhat == 0.] <- 1e-05
sealhat[sealhat > 0.] <- (1. - no.zero * 1e-05) * sealhat[sealhat > 0.]
return(AIT.dist(seal, sealhat))
}
chisq.dist <- function(x.1, x.2, gamma) {
nfa <- length(x.1)
y.1 <- x.1^(gamma)
y.1 <- y.1/sum(y.1)
y.2 <- x.2^(gamma)
y.2 <- y.2/sum(y.2)
d.sq <- (y.1-y.2)^2
c.vec <- y.1+y.2
if ( any(d.sq!=0) ) {
d.sq[d.sq!=0] <- d.sq[d.sq!=0]/c.vec[d.sq!=0]
}
CS.dist <- 1/gamma*sqrt(2*nfa)*sqrt(sum(d.sq))
return(CS.dist)
}
CS.more <- function(alpha, predator, prey.quantiles, gamma) {
seal <- predator
sealhat <- t(as.matrix(alpha)) %*% prey.quantiles
nfa <- length(seal)
y.1 <- seal^(gamma)
y.1 <- y.1/sum(y.1)
y.2 <- sealhat^(gamma)
y.2 <- y.2/sum(y.2)
d.sq <- (y.1-y.2)^2
c.vec <- y.1+y.2
if ( any(d.sq!=0) ) {
d.sq[d.sq!=0] <- d.sq[d.sq!=0]/c.vec[d.sq!=0]
}
CS.vec.sq <- d.sq
dist <- 1/gamma*sqrt(2*nfa)*sqrt(sum(d.sq))
out.list <- list(sealhat,CS.vec.sq,CS.vec.sq/sum(CS.vec.sq),dist)
names(out.list) <- c("ModFAS","DistCont", "PropDistCont","MinDist")
return(out.list)
}
CS.obj <- function(alpha, predator, prey.quantiles, gamma){
seal <- predator
sealhat <- t(as.matrix(alpha)) %*% prey.quantiles
return(chisq.dist(seal, sealhat, gamma))
}
KL.dist <- function(x.1, x.2) {
return(sum((x.1 - x.2) * log(x.1/x.2)))
}
KL.more <- function(alpha, predator, prey.quantiles) {
no.zero <- sum(predator == 0.)
predator[predator == 0.] <- 1e-05
predator[predator > 0.] <- (1. - no.zero * 1e-05) * predator[predator > 0.]
predatorhat <- t(as.matrix(alpha)) %*% prey.quantiles
no.zero <- sum(predatorhat == 0.)
predatorhat[predatorhat == 0.] <- 1e-05
predatorhat[predatorhat > 0.] <- (1. - no.zero * 1e-05) * predatorhat[predatorhat >0.]
KL.vec <- (predator - predatorhat) * log(predator/predatorhat)
dist <- sum(KL.vec)
out.list <- list(predatorhat,KL.vec,KL.vec/sum(KL.vec),dist)
names(out.list) <- c("ModFAS","DistCont", "PropDistCont","MinDist")
return(out.list)
}
KL.obj <- function(alpha, predator, prey.quantiles) {
predator <- predator
no.zero <- sum(predator == 0.)
predator[predator == 0.] <- 1e-05
predator[predator > 0.] <- (1. - no.zero * 1e-05) * predator[predator > 0.]
predatorhat <- t(as.matrix(alpha)) %*% prey.quantiles
no.zero <- sum(predatorhat == 0.)
predatorhat[predatorhat == 0.] <- 1e-05
predatorhat[predatorhat > 0.] <- (1. - no.zero * 1e-05) * predatorhat[predatorhat >0.]
return(KL.dist(predator, predatorhat))
}
mean.geometric <- function(x) {
D <- length(x)
return(prod(x)^(1./D))
}
MEANmeth <- function(prey.mat) {
prey.means <- apply(prey.mat[, -1], 2, tapply, prey.mat[, 1], mean)
return(prey.means)
}
QFASA.const.eqn <- function(alpha, predator, prey.quantiles, gamma) {
return(sum(alpha))
}
testfordiff.ind.pval <- function(compdata.1, compdata.2, ns1, R=500) {
compdata.1 <- as.matrix(compdata.1)
compdata.2 <- as.matrix(compdata.2)
boot.out <- testfordiff.ind.boot(rbind(compdata.1, compdata.2), ns1, R)
T.orig <- boot.out$t0
T.vec <- boot.out$t
pval.vec <- T.vec >= T.orig
pval <- mean(pval.vec)
return(list(T.orig, T.vec, pval))
}
testfordiff.ind.boot <- function(data, ns1, R) {
data.boot <- boot::boot(data = data, statistic = testfordiff.ind.boot.fun,
ns1 = ns1, sim = "permutation", R = R)
return(data.boot)
}
testfordiff.ind.boot.fun <- function(data, i, ns1, change.zero = 1e-05) {
d <- data[i, ]
ns2 <- nrow(data) - ns1
Y.1 <- d[1.:ns1, ]
Y.2 <- d[(ns1 + 1.):nrow(data), ]
alpha <- 1
Y.1.t <- Y.1^(1/alpha)
Y.1.t <- Y.1.t/apply(Y.1.t,1,sum)
Y.2.t <- Y.2^(1/alpha)
Y.2.t <- Y.2.t/apply(Y.2.t,1,sum)
d.mat <- alpha * create.d.mat(Y.1.t,Y.2.t)*sqrt(ncol(Y.1))
T.chisq <- sum(d.mat)
return(T.chisq)
}
create.d.mat <- function(Y.1,Y.2) {
ns1 <- nrow(Y.1)
ns2 <- nrow(Y.2)
nFA <- ncol(Y.1)
ind.vec <-
as.vector(unlist(tapply(seq(1,ns1,1),seq(1,ns1,1),rep,ns2)))
Y.1.rep <- Y.1[ind.vec, ]
Y.2.rep <- rep(t(Y.2),ns1)
Y.2.rep <- matrix(Y.2.rep,ncol=ncol(Y.2),byrow=T)
Y.1.split <- split(Y.1.rep,seq(1,nrow(Y.1.rep),1))
Y.2.split <- split(Y.2.rep,seq(1,nrow(Y.2.rep),1))
d.mat <- matrix(mapply(chisq.CA,Y.1.split,Y.2.split),byrow=T,ns1,ns2)
return(d.mat)
}
chisq.CA <- function(x1,x2) {
d.sq <- (x1-x2)^2
c.vec <- x1+x2
if ( any(d.sq!=0)) {
d.sq[d.sq!=0] <- d.sq[d.sq!=0]/c.vec[d.sq!=0]
}
d.sq <- 4*sum(d.sq)
d <- sqrt(d.sq/2)
return(d)
} |
runkMeans <- function(X, initial_centroids,
max_iters, plot_progress = FALSE) {
m <- dim(X)[1]
n <- dim(X)[2]
K <- dim(initial_centroids)[1]
centroids <- initial_centroids
previous_centroids <- array(0,dim = c(dim(centroids),max_iters + 1))
previous_centroids[,,1] <- centroids
idx <- rep(0,m)
for (i in 1:max_iters) {
cat(sprintf('K-Means iteration %d/%d...\n', i, max_iters))
idx <- findClosestCentroids(X, centroids)
if (plot_progress) {
plotProgresskMeans(X, centroids, previous_centroids, idx, K, i)
cat(sprintf('Press enter to continue.\n'))
line <- readLines(con = stdin(),1)
}
centroids <- computeCentroids(X, idx, K)
previous_centroids[,,i + 1] <- centroids
}
list(centroids = centroids, idx = idx)
} |
library(knitr)
library(poweRlaw)
options(replace.assign = FALSE)
opts_chunk$set(fig.path = "knitr_figure_poweRlaw/graphicsa-",
cache.path = "knitr_cache_poweRlaw_a/",
fig.align = "center",
dev = "pdf", fig.width = 5, fig.height = 5,
fig.show = "hold", cache = FALSE, par = TRUE,
out.width = "0.4\\textwidth")
knit_hooks$set(crop = hook_pdfcrop)
knit_hooks$set(par = function(before, options, envir) {
if (before && options$fig.show != "none") {
par(mar = c(3, 4, 2, 1), cex.lab = .95, cex.axis = .9,
mgp = c(3, .7, 0), tcl = -.01, las = 1)
}}, crop = hook_pdfcrop)
set.seed(1)
palette(c(rgb(170, 93, 152, maxColorValue = 255),
rgb(103, 143, 57, maxColorValue = 255),
rgb(196, 95, 46, maxColorValue = 255),
rgb(79, 134, 165, maxColorValue = 255),
rgb(205, 71, 103, maxColorValue = 255),
rgb(203, 77, 202, maxColorValue = 255),
rgb(115, 113, 206, maxColorValue = 255)))
library("poweRlaw")
data(bootstrap_moby)
bs = bootstrap_moby
data(bootstrap_p_moby)
bs_p = bootstrap_p_moby
data("moby")
m_m = displ$new(moby)
m_m$getXmin()
m_m$getPars()
m_m$setXmin(5)
m_m$setPars(2)
(est = estimate_pars(m_m))
(est = estimate_xmin(m_m))
m_m$setXmin(est)
par(mfrow = c(2, 2))
plot(m_m, xlab = "x", ylab = "CDF",
pch = 21, bg = 1, cex = 0.6,
panel.first = grid())
lines(m_m, col = 2, lwd = 2)
hist(bs$bootstraps[, 2], xlab = expression(x[min]), ylim = c(0, 1600),
xlim = c(0, 30), main = NULL, breaks = "fd")
grid()
hist(bs$bootstraps[, 3], xlab = expression(alpha),
ylim = c(0, 500), xlim = c(1.8, 2.1), main = NULL, breaks = "fd")
grid()
plot(jitter(bs$bootstraps[, 2], factor = 1.2), bs$bootstraps[, 3],
xlab = expression(x[min]), ylab = expression(alpha),
xlim = c(0, 30), ylim = c(1.8, 2.1), cex = 0.35,
pch = 21, bg = 1, panel.first = grid())
plot(m_m)
lines(m_m, col = 2)
dd = plot(m_m)
head(dd, 3)
parallel::detectCores()
hist(bs$bootstraps[, 2], breaks = "fd")
hist(bs$bootstraps[, 3], breaks = "fd")
plot(jitter(bs$bootstraps[, 2], factor = 1.2), bs$bootstraps[, 3])
par(mfrow = c(1, 3))
hist(bs_p$bootstraps[, 2], xlab = expression(x[min]), ylim = c(0, 1600),
xlim = c(0, 45), main = NULL, breaks = "fd")
grid()
hist(bs_p$bootstraps[, 3], xlab = expression(alpha),
ylim = c(0, 500), xlim = c(1.80, 2.05), main = NULL, breaks = "fd")
grid()
plot(jitter(bs_p$bootstraps[, 2], factor = 1.2), bs_p$bootstraps[, 3],
xlab = expression(x[xmin]), ylab = expression(alpha),
xlim = c(0, 40), ylim = c(1.8, 2.05), cex = 0.35,
pch = 21, bg = 1,
panel.first = grid())
m_m = displ$new(moby)
m_m$setXmin(est)
blackouts = c(570, 210.882, 190, 46, 17, 360, 74, 19, 460, 65, 18.351, 25,
25, 63.5, 1, 9, 50, 114.5, 350, 25, 50, 25, 242.91, 55, 164.5,
877, 43, 1140, 464, 90, 2100, 385, 95.63, 166, 71, 100, 234,
300, 258, 130, 246, 114, 120, 24.506, 36.073, 10, 160, 600, 12,
203, 50.462, 40, 59, 15, 1.646, 500, 60, 133, 62, 173, 81, 20,
112, 600, 24, 37, 238, 50, 50, 147, 32, 40.911, 30.5, 14.273,
160, 230, 92, 75, 130, 124, 120, 11, 235, 50, 94.285, 240, 870,
70, 50, 50, 18, 51, 51, 145, 557.354, 219, 191, 2.9, 163, 257.718,
1660, 1600, 1300, 80, 500, 10, 290, 375, 95, 725, 128, 148, 100,
2, 48, 18, 5.3, 32, 250, 45, 38.5, 126, 284, 70, 400, 207.2,
39.5, 363.476, 113.2, 1500, 15, 7500, 8, 56, 88, 60, 29, 75,
80, 7.5, 82.5, 272, 272, 122, 145, 660, 50, 92, 60, 173, 106.85,
25, 146, 158, 1500, 40, 100, 300, 1.8, 300, 70, 70, 29, 18.819,
875, 100, 50, 1500, 650, 58, 142, 350, 71, 312, 25, 35, 315,
500, 404, 246, 43.696, 71, 65, 29.9, 30, 20, 899, 10.3, 490,
115, 2085, 206, 400, 26.334, 598, 160, 91, 33, 53, 300, 60, 55,
60, 66.005, 11.529, 56, 4.15, 40, 320.831, 30.001, 200) * 1000
m_bl = conpl$new(blackouts)
est = estimate_xmin(m_bl)
m_bl$setXmin(est)
plot(m_bl, panel.first = grid())
lines(m_bl, col = 2)
rm(list = ls(all = TRUE)) |
simul.saemix<-function(saemixObject,nsim=saemixObject["options"]$nb.sim, predictions=TRUE,res.var=TRUE,uncertainty=FALSE) {
saemix.model<-saemixObject["model"]
saemix.data<-saemixObject["data"]
saemix.res<-saemixObject["results"]
xind<-saemix.data["data"][,c(saemix.data["name.predictors"],saemix.data["name.cens"],saemix.data["name.mdv"],saemix.data["name.ytype"]),drop=FALSE]
N<-saemix.data["N"]
ind.eta<-saemix.model["indx.omega"]
nb.etas<-length(ind.eta)
NM <- N*nsim
domega<-cutoff(mydiag(saemix.res["omega"][ind.eta, ind.eta]),.Machine$double.eps)
omega.eta<-saemix.res["omega"][ind.eta,ind.eta]
omega.eta<-omega.eta-mydiag(mydiag(saemix.res["omega"][ind.eta,ind.eta]))+mydiag(domega)
chol.omega<-chol(omega.eta)
phiM<-mean.phiM<-do.call(rbind,rep(list(saemix.res["mean.phi"]),nsim))
etaM<-matrix(rnorm(NM*nb.etas),ncol=nb.etas)%*%chol.omega
phiM[,ind.eta]<-mean.phiM[,ind.eta]+etaM
psiM<-transphi(phiM,saemix.model["transform.par"])
if(predictions) {
index<-rep(1:N,times=saemix.data["nind.obs"])
IdM<-kronecker(c(0:(nsim-1)),rep(N,saemix.data["ntot.obs"]))+rep(index,nsim)
XM<-do.call(rbind,rep(list(xind), nsim))
pres<-saemix.res["respar"]
sim.pred<-sim.data<-NULL
fpred<-saemix.model["model"](psiM, IdM, XM)
sim.pred<-fpred
if(res.var) {
ind.exp<-which(saemix.model["error.model"]=="exponential")
for(ityp in ind.exp) fpred[XM$ytype==ityp]<-log(cutoff(fpred[XM$ytype==ityp]))
gpred<-error(fpred,pres,XM$ytype)
eps<-rnorm(length(fpred))
sim.data<-fpred+gpred*eps
}
} else {
sim.pred<-sim.data<-IdM<-c()
}
sim.psi<-data.frame(id=rep(unique(saemix.data["data"][, saemix.data["name.group"]]),nsim),psiM)
colnames(sim.psi)<-c(saemix.data["name.group"],saemix.model["name.modpar"])
datasim<-data.frame(idsim=rep(index,nsim),irep=rep(1:nsim, each=saemix.data["ntot.obs"]),ypred=sim.pred,ysim=sim.data)
ysim<-new(Class="SaemixSimData",saemix.data,datasim)
ysim["sim.psi"]<-sim.psi
saemixObject["sim.data"]<-ysim
return(saemixObject)
} |
yupana_import <- function(data){
type <- x <- y <- group <- NULL
glab <- legend <- sig <- error <- NULL
model <- test_comp <- sig_level <- NULL
dimension <- gtext <- opt <- NULL
xrotation <- xtext <- ylimits <- NULL
if(!is.data.frame(data)) {
smr <- data$meancomp
stats <- data$stats
stats_args <- data$stats %>%
rownames_to_column() %>%
mutate(across(everything(), as.character)) %>%
pivot_longer(!.data$rowname, ) %>%
select(!.data$rowname) %>%
add_row(name = "model", value = data$model) %>%
deframe() %>%
as.list()
aov <- NULL
plot <- NULL
plot_opts <- list(
type = "bar"
, y = data$response
, x = data$comparison[1]
, group = data$comparison[2]
, xlab = NA
, ylab = NA
, glab = NA
, sig = "sig"
, error = "ste"
, legend = "top"
, ylimits = NA
, xrotation = c(0, 0.5, 0.5)
, gtext = NA
, xtext = NA
, opt = NA
, dimension = c(20, 10, 100)
, color = TRUE
)
factors <- data$factors
info <- data$tabvar
} else if (is.data.frame(data)) {
smr <- data %>%
select(1:.data$`[plot]`) %>%
select(!.data$`[plot]`) %>%
filter(!across(everything(), is.na))
aov <- data %>%
select(.data$`[aov]`:length(.)) %>%
select(!c(.data$`[aov]`)) %>%
filter(!across(everything(), is.na))
stats <- data %>%
select(.data$`[stats]`:.data$`[aov]`) %>%
select(!c(.data$`[stats]`, .data$`[aov]`)) %>%
filter(!across(everything(), is.na))
stats_args <- stats %>%
deframe() %>%
as.list()
plot <- data %>%
select(.data$`[plot]`:.data$`[stats]`) %>%
select(!c(.data$`[plot]`, .data$`[stats]`)) %>%
select(!colors) %>%
filter(!across(everything(), is.na))
plot_args <- plot %>%
deframe() %>%
as.list()
list2env(plot_args, environment())
plot_color <- data %>%
select(colors) %>%
drop_na() %>%
deframe()
plot_opts <- list(
type = if(is.na(plot_args$type)) "bar" else plot_args$type
, x = plot_args$x
, y = plot_args$y
, group = plot_args$group
, xlab = plot_args$xlab
, ylab = plot_args$ylab
, glab = plot_args$glab
, sig = plot_args$sig
, error = plot_args$error
, legend = plot_args$legend
, ylimits = ylimits
, xrotation = xrotation
, gtext = gtext
, xtext = xtext
, opt = opt
, dimension = dimension
, color = plot_color
)
info <- smr %>%
select({{y}}:ncol(.)) %>%
names()
factors <- smr %>%
select(!{{info}}) %>%
names()
}
graph_opt <- list(smr = smr
, stats = stats
, stats_args = stats_args
, aov = aov
, plot = plot
, plot_args = plot_opts
, factors = factors
, tabvar = info
)
} |
cat("tests_HW.R:\n")
locinfile <- genepopExample('sample.txt')
outfile <- test_HW(locinfile,"deficit","sample.txt.D")
testthat::expect_equal(readLines(outfile)[133],
"ADH-5 1.0000 0.0000 -0.3333 -0.3750 19903 switches")
outfile <- test_HW(locinfile,"global deficit")
testthat::expect_equal(readLines(outfile)[48], " 0.3329 0.0048 24797.00")
outfile <- test_HW(locinfile)
testthat::expect_equal(readLines(outfile)[190], " Prob : 0.960718")
outfile <- test_HW(locinfile, enumeration=TRUE)
testthat::expect_equal(readLines(outfile)[193], " Prob : 0.958961")
outfile <- nulls(locinfile, "sample.txt.NUL")
locinfile <- genepopExample('Rhesus.txt')
outfile <- HWtable_analysis(locinfile,which="Proba",batches = 1000,iterations = 1000)
testthat::expect_equal(readLines(outfile)[21],"P-value=0.684292; S.E=0.00830887 (241565 switches)") |
NULL
tidy.tidycrr <- function(x,
exponentiate = FALSE,
conf.int = FALSE,
conf.level = 0.95, ...) {
df_tidy <-
broom::tidy(
x$cmprsk,
exponentiate = exponentiate,
conf.int = conf.int,
conf.level = conf.level, ...
)
if (isTRUE(conf.int)) {
df_tidy <-
df_tidy %>%
dplyr::relocate(.data$conf.low, .data$conf.high, .before = .data$p.value)
}
df_tidy
}
glance.tidycrr <- function(x, ...) {
broom::glance(x$cmprsk, ...)
}
augment.tidycrr <- function(x, times = NULL, probs = NULL, newdata = NULL, ...) {
pred <-
predict.tidycrr(x, times = times, probs = probs, newdata = newdata) %>%
dplyr::bind_cols()
dplyr::bind_cols(
newdata %||% x$data,
pred
) %>%
tibble::as_tibble()
}
NULL
tidy.tidycuminc <- function(x, conf.int = FALSE, conf.level = 0.95,
times = NULL, ...) {
if (!is.numeric(conf.level) || !dplyr::between(conf.level, 0, 1)) {
stop("`conf.level=` must be between 0 and 1")
}
df_outcomes <-
rlang::f_lhs(x$formula) %>%
rlang::eval_tidy(data = x$data) %>%
attr("states") %>%
stats::setNames(seq_len(length(.))) %>%
tibble::enframe("outcome_id", "outcome")
times <-
times %||%
union(0, stats::model.frame(x$formula, data = x$data)[[1]][, 1]) %>%
unique() %>%
sort()
df_est <-
x$cmprsk %>%
cmprsk::timepoints(times = times) %>%
purrr::pluck("est") %>%
cuminc_matrix_to_df(name = "estimate")
df_se <-
x$cmprsk %>%
cmprsk::timepoints(times = times) %>%
purrr::pluck("var") %>%
sqrt() %>%
cuminc_matrix_to_df(name = "std.error")
df_tidy <-
dplyr::full_join(
df_est, df_se,
by = c("strata", "outcome_id", "time")
) %>%
dplyr::full_join(
df_outcomes,
by = "outcome_id"
) %>%
dplyr::select(.data$outcome, dplyr::everything(), -.data$outcome_id)
if (length(unique(df_tidy$strata)) == 1L) {
df_tidy$strata <- NULL
}
if (isTRUE(conf.int)) {
df_tidy <-
df_tidy %>%
dplyr::mutate(
conf.low =
.data$estimate^exp(stats::qnorm((1 - .env$conf.level) / 2) * .data$std.error /
(.data$estimate * log(.data$estimate))),
conf.high =
.data$estimate^exp(-stats::qnorm((1 - .env$conf.level) / 2) * .data$std.error /
(.data$estimate * log(.data$estimate))),
dplyr::across(c(.data$conf.low, .data$conf.high), ~ ifelse(is.nan(.), NA, .))
)
}
df_tidy
}
cuminc_matrix_to_df <- function(x, name) {
as.data.frame(x) %>%
tibble::rownames_to_column() %>%
tibble::as_tibble() %>%
dplyr::mutate(
strata = stringr::word(.data$rowname, 1, -2),
outcome_id = stringr::word(.data$rowname, -1L),
.before = .data$rowname
) %>%
dplyr::select(-.data$rowname) %>%
tidyr::pivot_longer(
cols = -c(.data$strata, .data$outcome_id),
names_to = "time",
values_to = name
) %>%
dplyr::mutate(time = as.numeric(.data$time))
}
glance.tidycuminc <- function(x, ...) {
if (is.null(x$cmprsk$Tests)) {
return(tibble::tibble())
}
select_expr <-
stringr::str_glue("ends_with('_{x$failcode}')") %>%
purrr::map(rlang::parse_expr)
x$cmprsk$Tests %>%
as.data.frame() %>%
tibble::rownames_to_column("failcode_id") %>%
tibble::as_tibble() %>%
dplyr::left_join(
x$failcode %>%
tibble::enframe("outcome", "failcode_id") %>%
dplyr::mutate(failcode_id = as.character(.data$failcode_id)),
by = "failcode_id"
) %>%
select(.data$outcome, .data$failcode_id, statistic = .data$stat,
.data$df, p.value = .data$pv) %>%
tidyr::pivot_wider(
values_from = c(.data$outcome, .data$statistic, .data$df, .data$p.value),
names_from = .data$failcode_id,
names_glue = "{.value}_{failcode_id}"
) %>%
select(!!!select_expr)
} |
`aDist` <-
function(x, y = NULL){
if(!is.null(y)){
if(is.vector(x)) x <- matrix(x, ncol=length(x))
if(is.vector(y)) y <- matrix(y, ncol=length(y))
n <- dim(x)[1]
p <- D <- dim(x)[2]
rn <- rownames(x)
matOrig <- as.numeric(t(x))
matImp <- as.numeric(t(y))
dims <- as.integer(c(n, p))
rowDists <- as.numeric(rep(0.0, n))
distance <- as.numeric(0.0)
out <- .C("da",
matOrig,
matImp,
dims,
rowDists,
distance,
PACKAGE="robCompositions", NUOK=TRUE
)[[5]]
} else {
if(is.vector(x)) x <- matrix(x, ncol=length(x))
n <- dim(x)[1]
p <- D <- dim(x)[2]
rn <- rownames(x)
out <- dist(cenLR(x)$x.clr)
}
return(out)
}
iprod <- function(x, y){
warning("wrong formula, has to be fixed.")
D <- length(x)
if(D != length(y)) stop("x and y should have the same length")
ip <- 1 / D * sum(log(as.numeric(x[1:(D-1)]) / as.numeric(x[2:D])) *
log(as.numeric(y[1:(D-1)]) / as.numeric(y[2:D])))
return(ip)
}
|
`fit.Models.tsm` <-
function(fmla, data.Vector, ...){
arima(data.Vector, order = c(fmla$model$AR, fmla$model$I, fmla$model$MA),
seasonal = list(order=c(fmla$seasonal$model$AR, fmla$seasonal$model$I,
fmla$seasonal$model$MA), period = fmla$seasonal$period))
} |
test_that("primitive functions are never supersets", {
pkgload::load_all(test_path("primitive"), quiet = TRUE)
on.exit(pkgload::unload("primitive"))
expect_false(is_superset("sum", "primitive", "base"))
expect_equal(
superset_principle("sum", c("primitive", "base")),
c("primitive", "base")
)
})
test_that("superset", {
expect_equal(superset_principle("cbind", c("base", "methods")), character())
expect_equal(superset_principle("print", c("base", "Matrix")), character())
expect_equal(superset_principle("rcond", c("base", "Matrix")), character())
})
test_that("functions aren't conflicts with non-functions", {
pkgload::load_all(test_path("funmatch"), quiet = TRUE)
on.exit(pkgload::unload("funmatch"))
expect_equal(function_lookup("pi", c("base", "funmatch")), character())
expect_equal(function_lookup("mean", c("base", "funmatch")), character())
})
test_that("can find conflicts with data", {
pkgload::load_all(test_path("data"), quiet = TRUE)
on.exit(pkgload::unload("data"))
expect_named(conflict_scout(c("datasets", "data")), "mtcars")
})
test_that(".Deprecated call contains function name", {
f <- function() {
.Deprecated("pkg::x")
}
expect_false(has_moved("pkg", "foo", f))
expect_true(has_moved("pkg", "x", f))
})
test_that("returns FALSE for weird inputs", {
expect_false(has_moved(obj = 20))
expect_false(has_moved(obj = mean))
f <- function() {}
expect_false(has_moved(obj = mean))
f <- function() {
.Deprecated()
}
expect_false(has_moved(obj = mean))
f <- function() {
.Deprecated(1)
}
expect_false(has_moved(obj = mean))
}) |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
backup_options <- options()
options(width = 1000)
set.seed(1991)
xgbAvail <- requireNamespace('xgboost', quietly = TRUE)
library("xgboost")
library("ParBayesianOptimization")
data(agaricus.train, package = "xgboost")
Folds <- list(
Fold1 = as.integer(seq(1,nrow(agaricus.train$data),by = 3))
, Fold2 = as.integer(seq(2,nrow(agaricus.train$data),by = 3))
, Fold3 = as.integer(seq(3,nrow(agaricus.train$data),by = 3))
)
scoringFunction <- function(max_depth, min_child_weight, subsample) {
dtrain <- xgb.DMatrix(agaricus.train$data,label = agaricus.train$label)
Pars <- list(
booster = "gbtree"
, eta = 0.01
, max_depth = max_depth
, min_child_weight = min_child_weight
, subsample = subsample
, objective = "binary:logistic"
, eval_metric = "auc"
)
xgbcv <- xgb.cv(
params = Pars
, data = dtrain
, nround = 100
, folds = Folds
, prediction = TRUE
, showsd = TRUE
, early_stopping_rounds = 5
, maximize = TRUE
, verbose = 0)
return(
list(
Score = max(xgbcv$evaluation_log$test_auc_mean)
, nrounds = xgbcv$best_iteration
)
)
}
bounds <- list(
max_depth = c(2L, 10L)
, min_child_weight = c(1, 25)
, subsample = c(0.25, 1)
)
set.seed(1234)
optObj <- bayesOpt(
FUN = scoringFunction
, bounds = bounds
, initPoints = 4
, iters.n = 3
)
optObj$scoreSummary
getBestPars(optObj)
options(backup_options) |
sumalt <- function(f_alt, n) {
b <- 2^(2*n-1)
c <- b
s <- 0.0
for (k in (n-1):0) {
t <- f_alt(k)
s <- s + c*t
b <- b * (2*k+1) * (k+1) / (2 * (n-k) * (n+k))
c <- c + b
}
s <- s / c
return(s)
} |
library(bmrm)
x <- cbind(intercept=100,data.matrix(iris[c("Sepal.Length","Sepal.Width","Petal.Length","Petal.Width")]))
w <- nrbm(softMarginVectorLoss(x,iris$Species))
table(target=iris$Species,prediction=predict(w,x)) |
GPSeq_clus<-function(dat, search_radius_m, window_days, clus_min_locs=2, centroid_calc="mean", show_plots=c(TRUE, "mean"), scale_plot_clus=TRUE, season_breaks_jul=NA, daylight_hrs=NA){
if(is.data.frame(dat)==FALSE){stop("GPSeq_clus requires input as dataframe.")}
if(("AID" %in% colnames(dat))==FALSE){stop("No 'AID' column found.")}
if(("TelemDate" %in% colnames(dat))==FALSE){stop("No 'TelemDate' column found.")}
if(("Long" %in% colnames(dat))==FALSE){stop("No 'Long' column found.")}
if(("Lat" %in% colnames(dat))==FALSE){stop("No 'Lat' column found.")}
if(inherits(dat$TelemDate, 'POSIXct')==FALSE){stop("'TelemDate' must be POSIXct.")}
if(is.na(centroid_calc) | is.null(centroid_calc)){stop("'centroid_calc' argument must = 'median' or 'mean'")}
if((!is.na(centroid_calc) && !is.null(centroid_calc) && (centroid_calc == "mean" | centroid_calc == "median"))==FALSE){stop("'centroid_calc' argument must = 'median' or 'mean'")}
if(is.na(search_radius_m) | is.null(search_radius_m)){stop("invalid 'search_radius_m'")}
if((!is.na(search_radius_m) && !is.null(search_radius_m) && (search_radius_m>=0))==FALSE){warning("No clusters identified when 'search_radius_m' <= 0.")}
if(clus_min_locs<2){warning("Clusters must have at least 2 locations. 'clus_min_locs' argument < 2 returns default of 2.")}
if(!is.na(daylight_hrs[1])){
if((length(daylight_hrs)!=2)==TRUE){stop("Invalid 'daylight_hrs' argument. Must be a vector of 2 numbers representing daylight start and stop times in hours.")}
if(is.numeric(daylight_hrs)==FALSE){stop("Invalid 'daylight_hrs' argument. Must be a vector of 2 numbers representing daylight start and stop times in hours.")}
if(any(daylight_hrs<0 | daylight_hrs>23)==TRUE){stop("Invalid 'daylight_hrs' argument. Arguments must be 0-23.")}
}
if(all(is.na(show_plots))){stop("Invalid 'show_plots' argument. Must be a vector of 2 arguments consisting of c('TRUE/FALSE', 'mean/median').")}
if(length(show_plots)!=2){stop("Invalid 'show_plots' argument. Must be a vector of 2 arguments consisting of c('TRUE/FALSE', 'mean/median').")}
if((show_plots[2]=='mean' | show_plots[2]=='median')==FALSE){stop("Invalid 'show_plots' argument. Must be a vector of 2 arguments consisting of c('TRUE/FALSE', 'mean/median').")}
if(!is.na(season_breaks_jul[1])){
if(any(is.numeric(season_breaks_jul))==FALSE){stop("Invalid 'season_breaks_jul' argument. Must be acending vector of at least 2 numeric values.")}
if(length(season_breaks_jul)<2){stop("Invalid 'season_breaks_jul' argument. Must be acending vector of at least 2 numeric values.")}
if(any(season_breaks_jul<0 | season_breaks_jul>365)==TRUE){stop("Invalid 'season_breaks_jul' argument. Arguments must be 0-365.")}
if((all(diff(season_breaks_jul)>0))==FALSE){stop("Invalid 'season_breaks_jul' argument. Arguments must be in acending order.")}
}
dat<-dat[order(dat$AID,dat$TelemDate),]
dat2<-dat[1,]
dat2$clus_ID<-NA
dat2<-dat2[-1,]
uni_AID<-as.character(unique(dat$AID))
message("TOTAL PROGRESS")
pb <- utils::txtProgressBar(min=0, max=length(uni_AID), style=3)
for(zz in 1:length(uni_AID)) {
out_all<-subset(dat, AID == uni_AID[zz])
if(length(which(is.na(out_all$Lat)))==0){warning(paste(uni_AID[zz], "shows no missed locations. Ensure 'failed' fix attempts are included for accurate cluster attributes."))}
out<-out_all[which(!is.na(out_all$Lat)),]
if(nrow(out)>0){
out$index<-seq(1:nrow(out))
out$ClusID<-0
out<-moveMe(out, "ClusID", "first")
out<-moveMe(out, "index", "first")
c<-1
pb2 <- tcltk::tkProgressBar(min = 0, max = nrow(out), width = 500)
for(j in 1:nrow(out)){
if(out$ClusID[j] == 0){
cent<-c(out[j,"Long"], out[j,"Lat"])
t<- out[which(out$TelemDate > out[j,"TelemDate"] & out$TelemDate <= out[j,"TelemDate"] + as.difftime(window_days, units= "days")),]
AR_Clus<- unique(t[which(t$ClusID >0),"ClusID"])
for(m in 1:length(AR_Clus)){
b<-out[which(out$ClusID == AR_Clus[m]),]
if(nrow(t)>0){
if(centroid_calc == "median"){
t[which(t$ClusID == AR_Clus[m]),"Long"]<-stats::median(b$Long)
t[which(t$ClusID == AR_Clus[m]),"Lat"]<-stats::median(b$Lat)
} else {
t[which(t$ClusID == AR_Clus[m]),"Long"]<-mean(b$Long)
t[which(t$ClusID == AR_Clus[m]),"Lat"]<-mean(b$Lat)
}
}
}
if(nrow(t)>0){
t$centLong<-cent[1]
t$centLat<-cent[2]
t$dist<-geosphere::distm(cbind(t$centLong,t$centLat), cbind(t$Long,t$Lat), fun = geosphere::distHaversine)[1,]
}
if(length(t[which(t$dis<=search_radius_m),"index"])>0){
if(out$ClusID[min(t[which(t$dist<search_radius_m),"index"])]==0){
out$ClusID[j]<-c
out$ClusID[min(t[which(t$dist<search_radius_m),"index"])]<-c
c<-c+1
} else {
out$ClusID[j]<-out$ClusID[min(t[which(t$dist<search_radius_m),"index"])]
}
}
} else {
if(centroid_calc == "median"){
cent<- c(stats::median(out[which(out$ClusID == out$ClusID[j]),"Long"]),stats::median(out[which(out$ClusID == out$ClusID[j]),"Lat"]))
} else {
cent<- c(mean(out[which(out$ClusID == out$ClusID[j]),"Long"]),mean(out[which(out$ClusID == out$ClusID[j]),"Lat"]))
}
t<- out[which(out$TelemDate > out[j,"TelemDate"] & out$TelemDate <= out[j,"TelemDate"] + as.difftime(window_days, units= "days")),]
AR_Clus<- unique(t[which(t$ClusID >0),"ClusID"])
for(m in 1:length(AR_Clus)){
b<-out[which(out$ClusID == AR_Clus[m]),]
if(nrow(t)>0){
if(centroid_calc == "median"){
t[which(t$ClusID == AR_Clus[m]),"Long"]<-stats::median(b$Long)
t[which(t$ClusID == AR_Clus[m]),"Lat"]<-stats::median(b$Lat)
} else {
t[which(t$ClusID == AR_Clus[m]),"Long"]<-mean(b$Long)
t[which(t$ClusID == AR_Clus[m]),"Lat"]<-mean(b$Lat)
}
}
}
if(nrow(t)>0){
t$centLong<-cent[1]
t$centLat<-cent[2]
t$dist<-geosphere::distm(cbind(t$centLong,t$centLat), cbind(t$Long,t$Lat), fun = geosphere::distHaversine)[1,]
}
if(length(t[which(t$dist<=search_radius_m),"index"])>0){
if(out$ClusID[min(t[which(t$dist<search_radius_m),"index"])]==0){
out$ClusID[min(t[which(t$dist<search_radius_m),"index"])]<- out$ClusID[j]
} else{
merge_num<-out[which(out$TelemDate == min(c(out[which(out$ClusID == out$ClusID[j]),"TelemDate"],out[which(out$ClusID == out$ClusID[min(t[which(t$dist<search_radius_m),"index"])]),"TelemDate"]))), "ClusID"]
out[which(out$ClusID == out$ClusID[j]),"ClusID"]<-merge_num
out[which(out$ClusID == out$ClusID[min(t[which(t$dist<search_radius_m),"index"])]),"ClusID"]<-merge_num
rm(merge_num)
}
}
}
tcltk::setTkProgressBar(pb2, j, title=paste("Animal", uni_AID[zz], "...building clusters...", round(j/nrow(out)*100, 0), "% completed"))
}
close(pb2)
rm(pb2,b,c,m,j,t,AR_Clus,cent)
see<-rle(out$ClusID)
bout_end<- cumsum(rle(out$ClusID)$lengths)
bout_start<- as.integer(c(1, bout_end +1))
bout_start<- bout_start[-length(bout_start)]
bout_start<-out$TelemDate[bout_start]
bout_end<-out$TelemDate[bout_end]
bout_duration<-round(difftime(bout_end, bout_start, units= "hours"),1)
bouts<-data.frame(bout_start,bout_end, bout_duration, see[["lengths"]], see[["values"]])
names(bouts)[names(bouts) == "see...values..."]<- "ClusID"
names(bouts)[names(bouts) == "see...lengths..."]<- "consec_locs"
rm(bout_start, bout_end, see)
bouts2<-subset(bouts, ClusID != 0)
bouts2<-bouts2[order(bouts2$ClusID, bouts2$bout_start),]
clus_summary<-plyr::ddply(bouts2, "ClusID", summarize,
clus_start= min(bout_start), clus_end= max(bout_end),
clus_dur_hr=round(difftime(max(bout_end), min(bout_start), units="hours"),1),
n_clus_locs= sum(consec_locs))
clus_summary<-clus_summary[which(clus_summary$n_clus_locs >= clus_min_locs),]
if(nrow(clus_summary)==0){
warning(paste("Zero clusters identified for", uni_AID[zz], "given user-entered parameters."))
out_all$clus_ID<-NA
} else {
clus_summary<-clus_summary[order(clus_summary$clus_start),]
clus_summary$clus_ID3<-seq(1:nrow(clus_summary))
clus_summary<-moveMe(clus_summary, "clus_ID3" , "first")
bouts2$clus_ID3<-NA
bouts2$clus_ID3<-clus_summary[match(bouts2$ClusID, clus_summary$ClusID), "clus_ID3"]
bouts2<-moveMe(bouts2, "clus_ID3" , "first")
bouts2<-bouts2[order(bouts2$clus_ID3, bouts2$bout_start),]
clus_summary$ClusID<-NULL
bouts2$ClusID<-NULL
bouts2<-bouts2[which(!is.na(bouts2$clus_ID3)),]
see<-rle(bouts2$clus_ID3)
clus_summary$visits<-see$lengths
out_all$clus_ID3<-NA
for(k in 1:nrow(bouts2)){
out_all[which(out_all$TelemDate >= bouts2$bout_start[k] & out_all$TelemDate <= bouts2$bout_end[k]), "clus_ID3"]<- bouts2$clus_ID3[k]
}
rm(k, bouts, bouts2, bout_duration, see, out)
names(clus_summary)[names(clus_summary) == "clus_ID3"]<- "clus_ID"
names(out_all)[names(out_all) == "clus_ID3"]<- "clus_ID"
clus_summary$AID<-out_all$AID[1]
clus_summary<-moveMe(clus_summary, "AID", "first")
clus_summary$clus_status<-"Closed"
clus_summary<-moveMe(clus_summary, "clus_status", "after", "clus_end")
clus_summary[which(clus_summary$clus_end >= Sys.time() - as.difftime(window_days, units= "days")), "clus_status"]<- "Open"
xxx<-plyr::ddply(out_all, "clus_ID", summarize,
g_c_Long= mean(Long, na.rm=TRUE), g_c_Lat= mean(Lat, na.rm=TRUE), g_med_Long= stats::median(Long, na.rm=TRUE), g_med_Lat= stats::median(Lat, na.rm=TRUE))
xxx<-xxx[1:nrow(xxx)-1,]
clus_summary<-cbind(clus_summary, xxx[,2:5])
clus_summary<-moveMe(clus_summary,c("g_c_Long", "g_c_Lat", "g_med_Long", "g_med_Lat"), "after", "clus_status")
rm(xxx)
clus_summary$fix_succ_clus_dur<-NA
clus_summary$adj_clus_locs<-NA
clus_summary$fid<-NA
clus_summary$max_foray<-NA
clus_summary$clus_radius<-NA
clus_summary$avg_clus_dist<-NA
clus_summary$n_24_per<-NA
clus_summary$bin_24hr<-NA
clus_summary$season<-NA
clus_summary$night_pts<-NA
clus_summary$night_prop<-NA
if(!is.na(season_breaks_jul[1])){clus_summary$season<-0}
pb3 <- tcltk::tkProgressBar(min = 0, max = nrow(clus_summary), width = 500)
for(i in 1:nrow(clus_summary)){
ggg<-out_all[which(out_all$TelemDate >= clus_summary$clus_start[i] & out_all$TelemDate <= clus_summary$clus_end[i]),]
clus_summary$fix_succ_clus_dur[i]<-round(nrow(ggg[which(!is.na(ggg$Lat)),])/nrow(ggg),2)
clus_summary$adj_clus_locs[i]<- round(clus_summary$n_clus_locs[i] / clus_summary$fix_succ_clus_dur[i],1)
fff<-ggg[which(!is.na(ggg$Lat)),]
fff<-fff[which(fff$clus_ID != clus_summary$clus_ID[i] | is.na(fff$clus_ID)),]
clus_summary$fid[i]<- clus_summary$n_clus_locs[i] - nrow(fff)
ggg$centLong<-clus_summary[i, "g_c_Long"]
ggg$centLat<-clus_summary[i, "g_c_Lat"]
ggg$dist<-geosphere::distm(cbind(ggg$centLong,ggg$centLat), cbind(ggg$Long,ggg$Lat), fun = geosphere::distHaversine)[1,]
ggg$days<-difftime(ggg$TelemDate, ggg$TelemDate[1], units="days")
clus_summary$max_foray[i]<-round(max(ggg$dist, na.rm=T))
clus_summary$clus_radius[i]<-round(max(ggg$dist[which(ggg$clus_ID == clus_summary$clus_ID[i])],na.rm=T))
clus_summary$avg_clus_dist[i]<- round(mean(ggg$dist[which(ggg$clus_ID == clus_summary$clus_ID[i])],na.rm=T))
aa<-ggg[which(ggg$clus_ID == clus_summary$clus_ID[i]),]
clus_summary$n_24_per[i]<-length(unique(floor(aa$days)))
if(clus_summary$n_24_per[i]>1){clus_summary$bin_24hr[i]<-1} else {clus_summary$bin_24hr[i]<-0}
if(!is.na(season_breaks_jul[1])){
for(p in 2:length(season_breaks_jul)){
if(julian_conv(ggg$TelemDate[1])>= season_breaks_jul[p-1] & julian_conv(ggg$TelemDate[1])< season_breaks_jul[p]){
clus_summary$season[i]<-p-1
}
}
rm(p)
}
aa<-aa[which(!is.na(aa$Lat)),]
if(!is.na(daylight_hrs[1])){
aa$hour<-NA
aa$hour<-as.numeric(format(aa$TelemDate, format='%H'))
clus_summary$night_pts[i]<-nrow(aa[which(aa$hour<=daylight_hrs[1] | aa$hour>=daylight_hrs[2]),])
clus_summary$night_prop[i]<-round(clus_summary$night_pts[i] / clus_summary$n_clus_locs[i],2)
} else{
ttt<-aa[,c("TelemDate", "Long", "Lat")]
ttt$date<-as.Date(aa$TelemDate, tz=attr(dat$TelemDate,"tzone"))
names(ttt)[names(ttt) == "Lat"]<- "lat"
names(ttt)[names(ttt) == "Long"]<- "lon"
dd<-suncalc::getSunlightTimes(data=ttt ,tz=attr(dat$TelemDate,"tzone"))
dd$TelemDate<-aa$TelemDate
aa$night<-ifelse(((dd$TelemDate>=dd$sunrise) & (dd$TelemDate<=dd$sunset)),1,0)
clus_summary$night_pts[i]<-length(which(aa$night == 0))
clus_summary$night_prop[i]<-round(clus_summary$night_pts[i] / clus_summary$n_clus_locs[i],2)
rm(dd, ttt)
}
tcltk::setTkProgressBar(pb3, i, title=paste("Animal",uni_AID[zz], "...building cluster covariates...", round(i/nrow(clus_summary)*100, 0), "% completed"))
}
close(pb3)
rm(pb3, ggg, fff, aa, i)
}
if(show_plots[1]==T){
if(nrow(clus_summary)>0){
if(show_plots[2] == "median"){
clus_plot<-clus_summary
clus_plot$Lat<-clus_plot$g_med_Lat
clus_plot$Long<-clus_plot$g_med_Long
} else {
clus_plot<-clus_summary
clus_plot$Lat<-clus_plot$g_c_Lat
clus_plot$Long<-clus_plot$g_c_Long
}
clus_plot$Popup<-NA
clus_plot$Popup<-paste(clus_plot$AID[1], paste("Clus
}
out2<-out_all
out2<-out2[which(!is.na(out2$Lat)),]
out2$Label<-NA
out2$Label<-paste(out2$AID, as.character(out2$TelemDate),"cn", out2$clus_ID, sep=" ")
out2$type<-"location"
if(nrow(clus_summary)>0){
out2[which(out2$clus_ID %in% clus_summary[,"clus_ID"]),"type"]<-"cluster location"
pal2<- leaflet::colorFactor(
palette= c('darkred', 'black'),
domain = out2$type)
} else{
pal2<- leaflet::colorFactor(
palette= c('black'),
domain = out2$type)
}
a<-out2 %>%
leaflet::leaflet() %>%
leaflet::addTiles() %>%
leaflet::addCircleMarkers(lng=~Long, lat=~Lat, radius=.5, opacity=100, label=~Label,color=~pal2(type), group="Locations") %>%
leaflet::addPolylines(data=out2,lng=~Long, lat=~Lat, weight=2, color="black", group="Locations") %>%
leaflet::addProviderTiles(providers$Esri.NatGeoWorldMap)
if(nrow(clus_summary)>0){
if(scale_plot_clus==TRUE){
a<- leaflet::addCircleMarkers(map=a,data=clus_plot, lng=~Long, lat=~Lat, radius=~n_clus_locs, color="yellow",opacity=100,popup=~Popup,group="Clusters")
} else {
a<- leaflet::addCircleMarkers(map=a,data=clus_plot, lng=~Long, lat=~Lat, radius=1, color="yellow",opacity=100,popup=~Popup,group="Clusters")
}
a<-leaflet::addMarkers(map=a, data=clus_plot, lng=~Long, lat=~Lat, group="searchClusters", popup =~Popup,
icon = leaflet::makeIcon(iconUrl = "http://leafletjs.com/examples/custom-icons/leaf-green.png",iconWidth = 1, iconHeight = 1))
}
esri <- providers %>%
purrr::keep(~ grepl('^Esri',.))
esri[[11]]<-NULL
esri[[9]]<-NULL
esri[[8]]<-NULL
esri[[7]]<-NULL
esri[[6]]<-NULL
esri[[2]]<-NULL
esri <- esri[c("Esri.DeLorme", "Esri.WorldImagery", "Esri.WorldTopoMap","Esri.NatGeoWorldMap", "Esri")]
esri %>%
purrr::walk(function(x) a <<- a %>% leaflet::addProviderTiles(x,group=x))
a<-a %>%
leaflet::addLayersControl(
baseGroups = names(esri),
options = leaflet::layersControlOptions(collapsed = TRUE),
overlayGroups = c("Clusters","Locations"))%>%
leaflet::addLegend(pal = pal2, values = out2$type, group = "Locations", opacity=100, position = "bottomleft")
a<-leaflet.extras::addSearchFeatures(map=a, targetGroups = "searchClusters", options = leaflet.extras::searchFeaturesOptions(propertyName = 'popup', openPopup=T, zoom=15, hideMarkerOnCollapse=T))
a <- a %>% addTitle(text=out2$AID[1], color= "black", fontSize= "18px", leftPosition = 50, topPosition=2)
print(a)
if(nrow(clus_summary)>0){rm(clus_plot)}
rm(a, esri, out2, pal2)
}
if(!exists("t_summ") & (ncol(clus_summary)==23)){
t_summ<-clus_summary[1,]
t_summ<-t_summ[-1,]
}
if(ncol(clus_summary)==23){
t_summ<-rbind(t_summ, clus_summary)
}
} else {
warning(paste(uni_AID[zz], "has no 'successful' fixes."))
out_all$clus_ID<-NA
if(!exists("dat2")){
dat2<-out_all[1,]
dat2<-out_all[-1,]
}
}
dat2<-rbind(dat2,out_all)
utils::setTxtProgressBar(pb, zz)
}
close(pb)
dat<-dat2
rm(dat2)
clus_summary<-t_summ
rm(pb, zz, uni_AID, out_all, t_summ)
return(list(dat, clus_summary))
} |
mohrleg <-
function(ES)
{
u = par('usr')
for(i in 1:length(ES$values))
{
tex1 = substitute(sigma[y]==x , list(x=ES$values[i], y=i) )
mtext(tex1, side = 3, line = -i, at=u[2], adj=1 )
}
} |
context("Consistent tradeSeq output with different inputs.")
data("sds", package = "tradeSeq")
set.seed(3)
n <- nrow(reducedDim(sds))
G <- 100
pseudotime <- slingPseudotime(sds, na = FALSE)
cellWeights <- slingCurveWeights(sds)
means <- matrix(rep(rlnorm(n = G, meanlog = 4, sdlog = 1), n),
nrow = G, ncol = n, byrow = FALSE
)
dispersions <- matrix(rep(runif(n = G, min = 0.8, max = 3), n),
nrow = G, ncol = n, byrow = FALSE
)
id <- sample(1:100, 20)
means[id, ] <- sweep(means[id, ], 2, FUN = "*", STATS = (pseudotime[, 1] / 50))
counts <- matrix(rnbinom(n = G * n, mu = means, size = 1 / dispersions),
nrow = G, ncol = n)
rownames(counts) <- 1:100
sce <- SingleCellExperiment(assays = list(counts = counts))
sce@int_metadata$slingshot <- sds
set.seed(3)
sdsFit <- tradeSeq::fitGAM(counts, sds, nknots = 3, verbose = FALSE)
set.seed(3)
sceFit <- tradeSeq::fitGAM(counts, pseudotime = pseudotime,
cellWeights = cellWeights, nknots = 3,
verbose = FALSE)
set.seed(3)
sceInput <- tradeSeq::fitGAM(sce, nknots = 3, verbose = FALSE)
set.seed(3)
listFit <- tradeSeq::fitGAM(counts, pseudotime = pseudotime,
cellWeights = cellWeights, nknots = 3,
verbose = FALSE, sce = FALSE)
set.seed(3)
sparseCount <- Matrix::Matrix(counts, sparse = TRUE)
sparseFit <- tradeSeq::fitGAM(sparseCount, pseudotime = pseudotime,
cellWeights = cellWeights, nknots = 3,
verbose = FALSE)
rm(dispersions, means, G, id, n)
test_that("EvaluateK return all same answers", {
set.seed(3)
sdsFit <- tradeSeq::evaluateK(counts, sds = sds, k = 3:5, verbose = FALSE,
plot = TRUE, nGenes = 20)
set.seed(3)
sceFit <- tradeSeq::evaluateK(counts, pseudotime = pseudotime,
cellWeights = cellWeights, k = 3:5,
verbose = FALSE, plot = FALSE, nGenes = 20)
set.seed(3)
sceInput <- tradeSeq::evaluateK(sce, k = 3:5, verbose = FALSE, plot = FALSE,
nGenes = 20)
set.seed(3)
listFit <- tradeSeq::evaluateK(counts, pseudotime = pseudotime,
cellWeights = cellWeights, k = 3:5,
verbose = FALSE, plot = FALSE, nGenes = 20)
set.seed(3)
sparseFit <- tradeSeq::evaluateK(sparseCount, pseudotime = pseudotime,
cellWeights = cellWeights, k = 3:5,
verbose = FALSE, plot = FALSE, nGenes = 20)
expect_equal(sdsFit, sceFit)
expect_equal(sdsFit, sceInput)
expect_equal(sdsFit, listFit)
expect_equal(sdsFit, sparseFit)
set.seed(3)
sceInput <- tradeSeq::evaluateK(sce, k = 3:5, verbose = FALSE, plot = FALSE,
nGenes = 20, gcv = TRUE)
set.seed(3)
listFit <- tradeSeq::evaluateK(counts, pseudotime = pseudotime,
cellWeights = cellWeights, k = 3:5, gcv = TRUE,
verbose = FALSE, plot = FALSE, nGenes = 20)
expect_equal(listFit$gcv, sceInput$gcv)
expect_equal(listFit$aic, sceInput$aic)
expect_is(tradeSeq::evaluateK(sce, k = 3:4, verbose = FALSE, plot = TRUE,
nGenes = 20),
"matrix")
})
test_that("NB-GAM estimates are equal all input.",{
betaSds <- as.matrix(rowData(sdsFit)$tradeSeq$beta)
betaSce <- as.matrix(rowData(sceFit)$tradeSeq$beta)
betaSceInput <- as.matrix(rowData(sceInput)$tradeSeq$beta)
betaList <- do.call(rbind, lapply(listFit, function(m) coef(m)))
betaSparseInput <- as.matrix(rowData(sparseFit)$tradeSeq$beta)
dimnames(betaSparseInput) <- dimnames(betaSceInput) <- dimnames(betaSce) <-
dimnames(betaSds) <- dimnames(betaList)
expect_equal(betaSds, betaList)
expect_equal(betaSds, betaSce)
expect_equal(betaSds, betaSceInput)
expect_equal(betaSds, betaSparseInput)
SigmaSds <- rowData(sdsFit)$tradeSeq$Sigma
SigmaSce <- rowData(sceFit)$tradeSeq$Sigma
SigmaSceInput <- rowData(sceInput)$tradeSeq$Sigma
SigmaSparseInput <- rowData(sparseFit)$tradeSeq$Sigma
SigmaList <- lapply(listFit, function(m) m$Vp)
names(SigmaSceInput) <- names(SigmaSce) <- names(SigmaSds) <- names(SigmaList)
names(SigmaSceInput) <- names(SigmaSce) <- names(SigmaSds) <-
names(SigmaList) <- names(SigmaSparseInput)
expect_equal(SigmaSds, SigmaList)
expect_equal(SigmaSds, SigmaSce)
expect_equal(SigmaSds, SigmaSceInput)
expect_equal(SigmaSds, SigmaSparseInput)
})
test_that("NB-GAM estimates are equal all input.",{
expect_equal(nknots(sceFit), nknots(sdsFit))
expect_equal(nknots(sceFit), nknots(listFit))
expect_equal(nknots(sceFit), nknots(sceInput))
expect_equal(nknots(sceFit), nknots(sparseFit))
})
test_that("assocationTest results are equal for sds and manual input.",{
assocSds <- tradeSeq::associationTest(sdsFit, global = TRUE, lineages = TRUE)
assocSce <- tradeSeq::associationTest(sceFit, global = TRUE, lineages = TRUE)
assocInput <- tradeSeq::associationTest(sceInput, global = TRUE, lineages = TRUE)
assocList <- tradeSeq::associationTest(listFit, global = TRUE, lineages = TRUE)
assocSparse <- tradeSeq::associationTest(sparseFit, global = TRUE, lineages = TRUE)
dimnames(assocInput) <- dimnames(assocSce) <- dimnames(assocSds) <-
dimnames(assocList) <- dimnames(assocSparse)
expect_equal(assocSds, assocSce)
expect_equal(assocSds, assocInput)
expect_equal(assocSds, assocSparse)
})
test_that("associationTest different l2fc contrasts types run.", {
startRes <- tradeSeq::associationTest(sdsFit, global = TRUE, lineages = TRUE,
l2fc = 1, contrastType = "start")
expect_is(startRes, "data.frame")
endRes <- tradeSeq::associationTest(sdsFit, global = TRUE, lineages = TRUE,
l2fc = 1, contrastType = "end")
expect_is(endRes, "data.frame")
consecRes <- tradeSeq::associationTest(sdsFit, global = TRUE, lineages = TRUE,
l2fc = 1, contrastType = "consecutive")
expect_is(consecRes, "data.frame")
})
test_that("startVsEndTest results are equal for sds and manual input.",{
setSce <- tradeSeq::startVsEndTest(sceFit, global = TRUE, lineages = TRUE)
setSds <- tradeSeq::startVsEndTest(sdsFit, global = TRUE, lineages = TRUE)
setInput <- tradeSeq::startVsEndTest(sceInput, global = TRUE, lineages = TRUE)
setList <- tradeSeq::startVsEndTest(listFit, global = TRUE, lineages = TRUE)
setSparse <- tradeSeq::startVsEndTest(sparseFit, global = TRUE, lineages = TRUE)
dimnames(setInput) <- dimnames(setSce) <- dimnames(setSds) <-
dimnames(setList) <- dimnames(setSparse)
expect_equal(setSce, setList)
expect_equal(setSds, setSce)
expect_equal(setSds, setInput)
expect_equal(setSds, setSparse)
})
test_that("startVsEndTest results are equal for sds and manual input with custom values",{
setSce <- tradeSeq::startVsEndTest(sceFit, global = TRUE, lineages = TRUE,
pseudotimeValues = c(1, 10))
setSds <- tradeSeq::startVsEndTest(sdsFit, global = TRUE, lineages = TRUE,
pseudotimeValues = c(1, 10))
setInput <- tradeSeq::startVsEndTest(sceInput, global = TRUE, lineages = TRUE,
pseudotimeValues = c(1, 10))
setList <- tradeSeq::startVsEndTest(listFit, global = TRUE, lineages = TRUE,
pseudotimeValues = c(1, 10))
setSparse <- tradeSeq::startVsEndTest(sparseFit, global = TRUE, lineages = TRUE,
pseudotimeValues = c(1, 10))
dimnames(setInput) <- dimnames(setSce) <- dimnames(setSds) <-
dimnames(setList) <- dimnames(setSparse)
expect_equal(setSce, setList)
expect_equal(setSds, setSce)
expect_equal(setSds, setInput)
expect_equal(setSds, setSparse)
})
test_that("diffEndTest results are equal for sds and manual input.",{
detSce <- tradeSeq::diffEndTest(sceFit, global = TRUE, pairwise = TRUE)
detSds <- tradeSeq::diffEndTest(sdsFit, global = TRUE, pairwise = TRUE)
detInput <- tradeSeq::diffEndTest(sceInput, global = TRUE, pairwise = TRUE)
detList <- tradeSeq::diffEndTest(listFit, global = TRUE, pairwise = TRUE)
detSparse <- tradeSeq::diffEndTest(sparseFit, global = TRUE, pairwise = TRUE)
dimnames(detInput) <- dimnames(detSce) <- dimnames(detSds) <-
dimnames(detList) <- dimnames(detSparse)
expect_equal(detSce, detList)
expect_equal(detSds, detSce)
expect_equal(detSds, detInput)
expect_equal(detSds, detSparse)
})
test_that("patternTest results are equal for sds and manual input.",{
patSce <- tradeSeq::patternTest(sceFit, global = TRUE, pairwise = TRUE)
patSds <- tradeSeq::patternTest(sdsFit, global = TRUE, pairwise = TRUE)
patInput <- tradeSeq::patternTest(sceInput, global = TRUE, pairwise = TRUE)
patList <- tradeSeq::patternTest(listFit, global = TRUE, pairwise = TRUE)
patSparse <- tradeSeq::patternTest(sparseFit, global = TRUE, pairwise = TRUE)
dimnames(patInput) <- dimnames(patSce) <- dimnames(patSds) <-
dimnames(patList) <- dimnames(patSparse)
expect_equal(patSce, patList, tolerance = 1e-5)
expect_equal(patSds, patSce)
expect_equal(patSds, patInput)
expect_equal(patSds, patSparse)
})
test_that("earlyDETest results are equal for sds and manual input.", {
edtSce <- tradeSeq::earlyDETest(sceFit, global = TRUE, pairwise = TRUE,
knots = 1:2)
edtInput <- tradeSeq::earlyDETest(sceInput, global = TRUE, pairwise = TRUE,
knots = 1:2)
edtSds <- tradeSeq::earlyDETest(sdsFit, global = TRUE, pairwise = TRUE,
knots = 1:2)
edtList <- tradeSeq::earlyDETest(listFit, global = TRUE, pairwise = TRUE,
knots = 1:2)
edtSparse <- tradeSeq::earlyDETest(sparseFit, global = TRUE, pairwise = TRUE,
knots = 1:2)
dimnames(edtInput) <- dimnames(edtSce) <- dimnames(edtSds) <-
dimnames(edtList) <- dimnames(edtSparse)
expect_equal(edtSds, edtList, tolerance = 1e-5)
expect_equal(edtSds, edtSparse, tolerance = 1e-5)
expect_equal(edtSds, edtSce, tolerance = 1e-5)
expect_equal(edtSds, edtInput, tolerance = 1e-5)
})
test_that("clusterExpressionpattern returns the right objects.", {
suppressWarnings({
suppressMessages({
set.seed(179)
PatSce <- tradeSeq::clusterExpressionPatterns(sceFit, nPoints = 20,
genes = 1:50,
k0s = 4:5, alphas = 0.1)
set.seed(179)
PatInput <- tradeSeq::clusterExpressionPatterns(sceInput, nPoints = 20,
genes = 1:50,
k0s = 4:5, alphas = 0.1)
set.seed(179)
PatSds <- tradeSeq::clusterExpressionPatterns(sdsFit, nPoints = 20,
genes = 1:50,
k0s = 4:5, alphas = 0.1)
set.seed(179)
PatList <- tradeSeq::clusterExpressionPatterns(listFit, nPoints = 20,
genes = 1:50,
k0s = 4:5, alphas = 0.1)
set.seed(179)
PatSparse <- tradeSeq::clusterExpressionPatterns(sparseFit, nPoints = 20,
genes = 1:50,
k0s = 4:5, alphas = 0.1)
})
})
dimnames(PatSds$yhatScaled) <- dimnames(PatList$yhatScaled) <-
dimnames(PatSparse$yhatScaled) <- dimnames(PatSce$yhatScaled) <-
dimnames(PatInput$yhatScaled)
expect_equal(PatSds$yhatScaled, PatList$yhatScaled, tolerance = 1e-5)
expect_equal(PatSds$yhatScaled, PatSparse$yhatScaled, tolerance = 1e-5)
expect_equal(PatSds$yhatScaled, PatSce$yhatScaled, tolerance = 1e-5)
expect_equal(PatSds$yhatScaled, PatInput$yhatScaled, tolerance = 1e-5)
})
test_that("fitGAM works with initial row data", {
rowData(sce)$more_info <- sample(1:10, size = nrow(sce), replace = TRUE)
set.seed(3)
sceInput <- tradeSeq::fitGAM(sce, nknots = 3, verbose = FALSE)
expect_is(sce, "SingleCellExperiment")
sceInput <- tradeSeq::fitGAM(sce, nknots = 3, genes = 1:20, verbose = FALSE)
expect_is(sce, "SingleCellExperiment")
}) |
whichIt <- function (burnIn,
iterations,
thinTo) {
if (burnIn == 0) {
return (ceiling(seq(from = 1,
to = iterations,
length.out = thinTo)))
} else {
return (ceiling(seq(from = burnIn * iterations,
to = iterations,
length.out = thinTo)))
}
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(magrittr)
library(dplyr)
library(tidyr)
library(stringr) |
`re.data.frame` <-
function(x,...) {
data.frame(x,...)
}
`as.xts.data.frame` <-
function(x,order.by,dateFormat="POSIXct",frequency=NULL,...,.RECLASS=FALSE) {
if(missing(order.by))
order.by <- do.call(paste('as',dateFormat,sep='.'),list(rownames(x)))
if(.RECLASS) {
xx <- xts(x,
order.by=order.by,
frequency=frequency,
.CLASS='data.frame',
...)
} else {
xx <- xts(x,
order.by=order.by,
frequency=frequency,
...)
}
xx
}
`as.data.frame.xts` <-
function(x,row.names=NULL,optional=FALSE,...) {
if(missing(row.names))
row.names <- as.character(index(x))
as.data.frame(coredata(x),row.names,optional,...)
} |
print.processing_time <- function(x, ...) {
data <- x
if(attr(data, "level") == "log" & is.null(attr(data, "groups"))) {
attr(data, "raw") <- NULL
attr(data, "level") <- NULL
attr(data, "mapping") <- NULL
class(data) <- "numeric"
print.default(data)
}
else {
print(tibble::trunc_mat(data))
}
} |
library(docopt)
doc <- "Usage: install2.r [-l LIBLOC] [-h] [-x] [-s] [-d DEPS] [-n NCPUS] [-r REPOS...] [-m METHOD] [--error] [--] [PACKAGES ...]
-l --libloc LIBLOC location in which to install [default: /usr/local/lib/R/site-library]
-d --deps DEPS install suggested dependencies as well [default: NA]
-n --ncpus NCPUS number of processes to use for parallel install [default: getOption]
-r --repos REPOS repositor(y|ies) to use, or NULL for file [default: getOption]
-e --error throw error and halt instead of a warning [default: FALSE]
-s --skipinstalled skip installing already installed packages [default: FALSE]
-m --method METHOD method to be used for downloading files [default: auto]
-h --help show this help text
-x --usage show help and short example usage"
opt <- docopt(doc)
if (opt$usage) {
cat(doc, "\n\n")
cat("where PACKAGES... can be one or more CRAN package names, or local (binary or source)
package files (where extensions .tar.gz, .tgz and .zip are recognised). Optional
arguments understood by R CMD INSTALL can be passed interspersed in the PACKAGES, though
this requires use of '--'.
Examples:
install2.r -l /tmp/lib Rcpp BH
install2.r -- --with-keep.source drat
install2.r -- --data-compress=bzip2 stringdist
install2.r \".\"
install2.r -n 6 ggplot2
install2.r is part of littler which brings 'r' to the command-line.
See http://dirk.eddelbuettel.com/code/littler.html for more information.\n")
q("no")
}
if (opt$deps == "TRUE" || opt$deps == "FALSE") {
opt$deps <- as.logical(opt$deps)
} else if (opt$deps == "NA") {
opt$deps <- NA
}
if (length(opt$repos) == 1 && "NULL" %in% opt$repos) {
opt$repos <- NULL
}
if ("getOption" %in% opt$repos) {
opt$repos <- c(opt$repos[which(opt$repos != "getOption")], getOption("repos"))
}
if (opt$ncpus == "getOption") {
opt$ncpus <- getOption("Ncpus", 1L)
} else if (opt$ncpus == "-1") {
opt$ncpus <- max(1L, parallel::detectCores())
}
Sys.setenv("_R_SHLIB_STRIP_"="true")
install_packages2 <- function(pkgs, ..., error = FALSE, skipinstalled = FALSE) {
e <- NULL
capture <- function(e) {
if (error) {
catch <-
grepl("download of package .* failed", e$message) ||
grepl("(dependenc|package).*(is|are) not available", e$message) ||
grepl("installation of package.*had non-zero exit status", e$message) ||
grepl("installation of one or more packages failed", e$message)
if (catch) {
e <<- e
}
}
}
if (skipinstalled) {
pkgs <- setdiff(pkgs, installed.packages()[,1])
}
if (length(pkgs) > 0) {
withCallingHandlers(install.packages(pkgs, ...), warning = capture)
if (!is.null(e)) {
stop(e$message, call. = FALSE)
}
}
}
isMatchingFile <- function(f) (file.exists(f) && grepl("(\\.tar\\.gz|\\.tgz|\\.zip)$", f)) || (f == ".")
installArg <- function(f, lib, rep, dep, iopts, error, skipinstalled, ncpus, method) {
install_packages2(pkgs=f,
lib=lib,
repos=if (isMatchingFile(f)) NULL else rep,
dependencies=dep,
INSTALL_opts=iopts,
Ncpus = ncpus,
method = method,
error = error,
skipinstalled = skipinstalled)
}
isArg <- grepl('^--',opt$PACKAGES)
installOpts <- opt$PACKAGES[isArg]
opt$PACKAGES <- opt$PACKAGES[!isArg]
if (length(opt$PACKAGES)==0 && file.exists("DESCRIPTION") && file.exists("NAMESPACE")) {
message("* installing *source* package found in current working directory ...")
opt$PACKAGES <- "."
}
isMatchingFile <-
function(f) (file.exists(f) &&
grepl("(\\.tar\\.gz|\\.tgz|\\.zip)$", f)) || (f == ".")
isLocal <- sapply(opt$PACKAGES, isMatchingFile)
if (any(isLocal)) {
sapply(opt$PACKAGES, installArg, opt$libloc, opt$repos, opt$deps,
installOpts, opt$error, opt$skipinstalled, opt$ncpus, opt$method)
} else {
install_packages2(pkgs = opt$PACKAGES,
lib = opt$libloc,
repos = opt$repos,
dependencies = opt$deps,
INSTALL_opts = installOpts,
Ncpus = opt$ncpus,
method = opt$method,
error = opt$error,
skipinstalled = opt$skipinstalled)
}
sapply(list.files(path=tempdir(), pattern="^(repos|libloc).*\\.rds$", full.names=TRUE), unlink) |
insp.dd <-
function(data, what=c('rate','pop', 'deaths'),
ages=data$age, years=data$year, series = names(data$rate)[1]){
if (class(data) != "demogdata" || data$type != "mortality")
stop("Not mortality data")
what <- match.arg(what)
if (what == 'deaths'){
data <- extract.deaths(data, ages, years, combine.upper=F, series=series)
what <- 'rate'
}
else {
data <- extract.years(data, years)
data <- extract.ages(data, ages=ages, combine.upper=F)
}
data[[what]][[series]]
} |
vardomh <- function(Y, H, PSU, w_final,
ID_level1,
ID_level2,
Dom = NULL,
period = NULL,
N_h = NULL,
PSU_sort = NULL,
fh_zero = FALSE,
PSU_level = TRUE,
Z = NULL,
dataset = NULL,
X = NULL,
periodX = NULL,
X_ID_level1 = NULL,
ind_gr = NULL,
g = NULL,
q = NULL,
datasetX = NULL,
confidence = .95,
percentratio = 1,
outp_lin = FALSE,
outp_res = FALSE) {
fh_zero <- check_var(vars = fh_zero, varn = "fh_zero", varntype = "logical")
PSU_level <- check_var(vars = PSU_level, varn = "PSU_level", varntype = "logical")
outp_lin <- check_var(vars = outp_lin, varn = "outp_lin", varntype = "logical")
outp_res <- check_var(vars = outp_res, varn = "outp_res", varntype = "logical")
percentratio <- check_var(vars = percentratio, varn = "percentratio", varntype = "pinteger")
confidence <- check_var(vars = confidence, varn = "confidence", varntype = "numeric01")
if(!is.null(X)) {
if (is.null(datasetX)) datasetX <- copy(dataset)
if (identical(dataset, datasetX) & !is.null(dataset)) X_ID_level1 <- ID_level1 }
Y <- check_var(vars = Y, varn = "Y", dataset = dataset,
check.names = TRUE, isnumeric = TRUE, grepls = "__")
Ynrow <- nrow(Y)
Yncol <- ncol(Y)
ID_level1 <- check_var(vars = ID_level1, varn = "ID_level1",
dataset = dataset, ncols = 1,
Ynrow = Ynrow, ischaracter = TRUE)
period <- check_var(vars = period, varn = "period",
dataset = dataset, Ynrow = Ynrow,
ischaracter = TRUE, duplicatednames = TRUE,
mustbedefined = FALSE)
ID_level2 <- check_var(vars = ID_level2, varn = "ID_level2",
dataset = dataset, ncols = 1, Ynrow = Ynrow,
ischaracter = TRUE, namesID1 = names(ID_level1),
periods = period)
H <- check_var(vars = H, varn = "H", dataset = dataset,
ncols = 1, Ynrow = Ynrow, ischaracter = TRUE,
namesID1 = names(ID_level1), dif_name = "dataH_stratas")
w_final <- check_var(vars = w_final, varn = "w_final",
dataset = dataset, ncols = 1,
Ynrow = Ynrow, isnumeric = TRUE, isvector = TRUE)
Z <- check_var(vars = Z, varn = "Z", dataset = dataset,
check.names = TRUE, Yncol = Yncol, Ynrow = Ynrow,
isnumeric = TRUE, mustbedefined = FALSE)
Dom <- check_var(vars = Dom, varn = "Dom", dataset = dataset,
Ynrow = Ynrow, ischaracter = TRUE,
mustbedefined = FALSE, duplicatednames = TRUE,
grepls = "__")
PSU <- check_var(vars = PSU, varn = "PSU", dataset = dataset,
ncols = 1, Ynrow = Ynrow, ischaracter = TRUE,
namesID1 = names(ID_level1))
PSU_sort <- check_var(vars = PSU_sort, varn = "PSU_sort", dataset = dataset,
ncols = 1, Ynrow = Ynrow, ischaracter = TRUE,
isvector = TRUE, mustbedefined = FALSE, PSUs = PSU)
if(!is.null(X) | !is.null(ind_gr) |!is.null(g) | !is.null(q) |
!is.null(periodX) | !is.null(X_ID_level1) | !is.null(datasetX)) {
X <- check_var(vars = X, varn = "X", dataset = datasetX,
check.names = TRUE, isnumeric = TRUE,
dif_name = c(names(Y), names(period),
"g", "q", "weight"), dX = "X")
Xnrow <- nrow(X)
ind_gr <- check_var(vars = ind_gr, varn = "ind_gr",
dataset = datasetX, ncols = 1, Xnrow = Xnrow,
ischaracter = TRUE, dX = "X",
dif_name = c(names(Y), names(period), "g", "q", "weight"))
g <- check_var(vars = g, varn = "g", dataset = datasetX,
ncols = 1, Xnrow = Xnrow, isnumeric = TRUE,
isvector = TRUE, dX = "X")
q <- check_var(vars = q, varn = "q", dataset = datasetX,
ncols = 1, Xnrow = Xnrow, isnumeric = TRUE,
isvector = TRUE, dX = "X")
periodX <- check_var(vars = periodX, varn = "periodX",
dataset = datasetX, ncols = 1, Xnrow = Xnrow,
ischaracter = TRUE, mustbedefined = !is.null(period),
duplicatednames = TRUE, varnout = "period",
varname = names(period), periods = period, dX = "X")
X_ID_level1 <- check_var(vars = X_ID_level1, varn = "X_ID_level1",
dataset = datasetX, ncols = 1, Xnrow = Xnrow,
ischaracter = TRUE, varnout = "ID_level1",
varname = names(ID_level1), periods = period,
periodsX = periodX, ID_level1 = ID_level1, dX = "X")
}
N <- dataset <- datasetX <- NULL
np <- sum(ncol(period))
if (!is.null(N_h)) {
N_h <- data.table(N_h)
if (anyNA(N_h)) stop("'N_h' has missing values")
if (ncol(N_h) != np + 2) stop(paste0("'N_h' should be ", np + 2, " columns"))
if (!is.numeric(N_h[[ncol(N_h)]])) stop("The last column of 'N_h' should be numeric")
nams <- c(names(period), names(H))
if (all(nams %in% names(N_h))) {N_h[, (nams) := lapply(.SD, as.character), .SDcols = nams]
} else stop(paste0("All strata titles of 'H'", ifelse(!is.null(period), "and periods titles of 'period'", ""), " have not in 'N_h'"))
if (is.null(period)) {
if (any(is.na(merge(unique(H), N_h, by = names(H), all.x = TRUE)))) stop("'N_h' is not defined for all strata")
if (any(duplicated(N_h[, head(names(N_h), -1), with = FALSE]))) stop("Strata values for 'N_h' must be unique")
} else { pH <- data.table(period, H)
if (any(is.na(merge(unique(pH), N_h, by = names(pH), all.x = TRUE)))) stop("'N_h' is not defined for all strata and periods")
if (any(duplicated(N_h[, head(names(N_h), -1), with = FALSE]))) stop("Strata values for 'N_h' must be unique in all periods")
pH <- NULL
}
setkeyv(N_h, names(N_h)[c(1 : (1 + np))])
}
psusn <- as.integer(!is.null(PSU_sort))
namesDom <- names(Dom)
aPSU <- names(PSU)
if (!is.null(Dom)) Y1 <- domain(Y = Y, D = Dom,
dataset = NULL,
checking = FALSE) else Y1 <- Y
Y <- NULL
n_nonzero <- copy(Y1)
Z1 <- NULL
if (!is.null(Z)) {
if (!is.null(Dom)) Z1 <- domain(Y = Z, D = Dom,
dataset = NULL,
checking = FALSE) else Z1 <- Z
Z0 <- copy(Z1)
setnames(Z0, names(Z0), names(Y1))
n_nonzero <- n_nonzero + Y1
Z0 <- NULL
}
if (!is.null(period)){ n_nonzero <- data.table(period, n_nonzero)
n_nonzero <- n_nonzero[, lapply(.SD, function(x)
sum(as.integer(abs(x) > .Machine$double.eps))),
keyby = names(period),
.SDcols = names(Y1)]
} else n_nonzero <- n_nonzero[, lapply(.SD, function(x)
sum(as.integer(abs(x) > .Machine$double.eps))),
.SDcols = names(Y1)]
respondent_count <- sample_size <- pop_size <- NULL
nhs <- data.table(respondent_count = 1, pop_size = w_final)
if (!is.null(period)) nhs <- data.table(period, nhs)
if (!is.null(Dom)) nhs <- data.table(Dom, nhs)
if (!is.null(c(Dom, period))) {nhs <- nhs[, lapply(.SD, sum, na.rm = TRUE),
keyby = eval(names(nhs)[0 : 1 - ncol(nhs)]),
.SDcols = c("respondent_count", "pop_size")]
} else nhs <- nhs[, lapply(.SD, sum, na.rm = TRUE),
.SDcols = c("respondent_count", "pop_size")]
if (!is.null(X)) {
ID_level1h <- data.table(ID_level1)
if (!is.null(period)) { ID_level1h <- data.table(period, ID_level1h)
X_ID_level1 <- data.table(periodX, X_ID_level1) }
idhx <- data.table(X_ID_level1, g = g)
setnames(idhx, names(idhx)[c(1 : (ncol(idhx) - 1))], names(ID_level1h))
idg <- merge(ID_level1h, idhx, by = names(ID_level1h), sort = FALSE)
w_design <- w_final / idg[["g"]]
idg <- data.table(idg, w_design = w_design)
idh <- idg[, .N, keyby = c(names(ID_level1h), "w_design")]
if (nrow(X) != nrow(idh)) stop("Aggregated 'w_design' length must the same as matrix 'X'")
idg <- idhx <- ID_level1h <- NULL
} else w_design <- w_final
sar_nr <- persort <- linratio_outp <- estim <- NULL
var_est2 <- se <- rse <- cv <- absolute_margin_of_error <- NULL
relative_margin_of_error <- CI_lower <- S2_y_HT <- NULL
S2_y_ca <- S2_res <- CI_upper <- variable <- variableZ <- NULL
.SD <- deff_sam <- deff_est <- deff <- n_eff <- NULL
aH <- names(H)
idper <- ID_level2
period0 <- copy(period)
if (!is.null(period)) idper <- data.table(idper, period)
if (!is.null(Z)) {
if (is.null(period)) {
Y2 <- lin.ratio(Y = Y1, Z = Z1, weight = w_final, Dom = NULL,
dataset = NULL, percentratio = percentratio,
checking = FALSE)
} else {
periodap <- do.call("paste", c(as.list(period), sep="_"))
lin1 <- lapply(split(Y1[, .I], periodap), function(i)
data.table(sar_nr = i,
lin.ratio(Y = Y1[i], Z = Z1[i],
weight = w_final[i],
Dom = NULL, dataset = NULL,
percentratio = percentratio,
checking = FALSE)))
Y2 <- rbindlist(lin1)
setkeyv(Y2, "sar_nr")
Y2[, sar_nr := NULL]
}
if (any(is.na(Y2))) print("Results are calculated, but there are cases where Z = 0")
if (outp_lin) linratio_outp <- data.table(idper, PSU, Y2)
} else {
Y2 <- Y1
}
lin1 <- Y_est <- Z_est <- .SD <- variableDZ <- NULL
hY <- data.table(Y1 * w_final)
if (is.null(period)) { Y_est <- hY[, lapply(.SD, sum, na.rm = TRUE), .SDcols = names(Y1)]
} else { hY <- data.table(period0, hY)
Y_est <- hY[, lapply(.SD, sum, na.rm = TRUE), keyby = names(period), .SDcols = names(Y1)]
}
Y_est <- transpos(Y_est, is.null(period), "Y_est", names(period))
all_result <- Y_est
if (!is.null(Z1)) {
YZnames <- data.table(variable = names(Y1), variableDZ = names(Z1))
setkeyv(YZnames, "variable")
setkeyv(all_result, "variable")
all_result <- merge(all_result, YZnames)
hZ <- data.table(Z1 * w_final)
if (is.null(period)) { Z_est <- hZ[, lapply(.SD, sum, na.rm = TRUE), .SDcols = names(Z1)]
} else { hZ <- data.table(period, hZ)
Z_est <- hZ[, lapply(.SD, sum, na.rm = TRUE), keyby = names(period), .SDcols = names(Z1)]
}
Z_est <- transpos(Z_est, is.null(period), "Z_est", names(period), "variableDZ")
all_result <- merge(all_result, Z_est, all = TRUE, by = c(names(period), "variableDZ"))
}
vars <- data.table(variable = names(Y1), nr_names = 1 : ncol(Y1))
all_result <- merge(vars, all_result, by = "variable")
n_nonzero <- transpos(n_nonzero, is.null(period), "n_nonzero", names(period))
all_result <- merge(all_result, n_nonzero, all = TRUE, by = c(names(period), "variable"))
n_nonzero <- vars <- Y1 <- Z1 <- Y_est <- Z_est <- hY <- hZ <- YZnames <- NULL
YY <- data.table(idper, ID_level1, H, PSU, check.names = TRUE)
if (!is.null(PSU_sort)) YY <- data.table(YY, PSU_sort, check.names = TRUE)
YY <- data.table(YY, w_design, w_final, Y2, check.names = TRUE)
YY2 <- YY[, lapply(.SD, sum, na.rm = TRUE), by = c(names(YY)[c(2 : (6 + np + psusn))]),
.SDcols = names(YY)[-(1 : (6 + np + psusn))]]
Y3 <- YY2[, c(-(1 : (5 + np + psusn))), with = FALSE]
idper <- period <- NULL
if (np > 0) period <- YY2[, c(1 : np), with = FALSE]
ID_level1h <- YY2[, np + 1, with = FALSE]
H <- YY2[, np + 2, with = FALSE]
setnames(H, names(H), aH)
PSU <- YY2[, np + 3, with = FALSE]
setnames(PSU, names(PSU), aPSU)
if (!is.null(PSU_sort)) PSU_sort <- YY2[[np + 4]]
w_design2 <- YY2[[np + 4 + psusn]]
w_final2 <- YY2[[np + 5 + psusn]]
YY <- YY2 <- NULL
betas <- res_outp <- NULL
if (!is.null(X)) {
if (np > 0) ID_level1h <- data.table(period, ID_level1h)
X0 <- data.table(X_ID_level1, ind_gr, q, g, X)
D1 <- merge(ID_level1h, X0, by = names(ID_level1h), sort = FALSE)
ind_gr <- D1[, np + 2, with = FALSE]
if (!is.null(period)) ind_gr <- data.table(D1[, names(periodX), with = FALSE], ind_gr)
ind_period <- do.call("paste", c(as.list(ind_gr), sep = "_"))
lin1 <- lapply(split(Y3[, .I], ind_period), function(i) {
resid <- residual_est(Y = Y3[i],
X = D1[i, (np + 5) : ncol(D1), with = FALSE],
weight = w_design2[i],
q = D1[i][["q"]],
checking = FALSE)
pers0 <- ind_gr[i, .N, keyby = c(names(ind_gr))]
list(data.table(sar_nr = i, resid$residuals),
data.table(pers0[, N := NULL], resid$betas))
})
Y4 <- rbindlist(lapply(lin1, function(x) x[[1]]))
betas <- rbindlist(lapply(lin1, function(x) x[[2]]))
setkeyv(Y4, "sar_nr")
Y4[, sar_nr := NULL]
if (outp_res) res_outp <- data.table(ID_level1h, PSU, w_final2, Y4)
} else Y4 <- Y3
X0 <- D1 <- X_ID_level1 <- ID_level1h <- ind_gr <- lin1 <- X <- g <- q <- NULL
var_est <- variance_est(Y = Y4, H = H, PSU = PSU,
w_final = w_final2,
N_h = N_h, fh_zero = fh_zero,
PSU_level = PSU_level,
PSU_sort = PSU_sort,
period = period, dataset = NULL,
msg = "Current variance estimation",
checking = FALSE)
var_est <- transpos(var_est, is.null(period), "var_est", names(period))
all_result <- merge(all_result, var_est, all = TRUE, by = c(names(period), "variable"))
var_cur_HT <- variance_est(Y = Y3, H = H, PSU = PSU,
w_final = w_design2,
N_h = N_h, fh_zero = fh_zero,
PSU_level = PSU_level,
PSU_sort = PSU_sort,
period = period, dataset = NULL,
msg = "Variance of HT estimator under current design",
checking = FALSE)
var_cur_HT <- transpos(var_cur_HT, is.null(period), "var_cur_HT", names(period))
all_result <- merge(all_result, var_cur_HT, all = TRUE, by = c(names(period), "variable"))
n_nonzero <- var_est <- var_cur_HT <- NULL
H <- PSU <- PSU_sort <- N_h <- NULL
if (is.null(period)) {
varsrs <- var_srs(Y = Y3, w = w_design2)
S2_y_HT <- varsrs$S2p
S2_y_ca <- var_srs(Y = Y3, w = w_final2)$S2p
var_srs_HT <- varsrs$varsrs
} else {
period_agg <- unique(period)
lin1 <- lapply(1 : nrow(period_agg), function(i) {
per <- period_agg[i,][rep(1, nrow(Y3)),]
ind <- (rowSums(per == period) == ncol(period))
varsrs <- var_srs(Y = Y3[ind], w = w_design2[ind])
varsca <- var_srs(Y = Y3[ind], w = w_final2[ind])
list(S2p = data.table(period_agg[i,], varsrs$S2p),
varsrs = data.table(period_agg[i,], varsrs$varsrs),
S2ca = data.table(period_agg[i,], varsca$S2p))
})
S2_y_HT <- rbindlist(lapply(lin1, function(x) x[[1]]))
var_srs_HT <- rbindlist(lapply(lin1, function(x) x[[2]]))
S2_y_ca <- rbindlist(lapply(lin1, function(x) x[[3]]))
}
var_srs_HT <- transpos(var_srs_HT, is.null(period), "var_srs_HT", names(period))
all_result <- merge(all_result, var_srs_HT, all = TRUE, by = c(names(period), "variable"))
S2_y_HT <- transpos(S2_y_HT, is.null(period), "S2_y_HT", names(period))
all_result <- merge(all_result, S2_y_HT, all = TRUE, by = c(names(period), "variable"))
S2_y_ca <- transpos(S2_y_ca, is.null(period), "S2_y_ca", names(period))
all_result <- merge(all_result, S2_y_ca, all = TRUE, by = c(names(period), "variable"))
Y3 <- w_design2 <- var_srs_HT <- S2_y_HT <- S2_y_ca <- NULL
if (is.null(period)) {
varsres <- var_srs(Y4, w = w_final2)
S2_res <- varsres$S2p
var_srs_ca <- varsres$varsrs
} else {
period_agg <- unique(period)
lin1 <- lapply(1 : nrow(period_agg), function(i) {
per <- period_agg[i,][rep(1, nrow(Y4)),]
ind <- (rowSums(per == period) == ncol(period))
varsres <- var_srs(Y = Y4[ind], w = w_final2[ind])
list(S2p = data.table(period_agg[i,], varsres$S2p),
varsrs = data.table(period_agg[i,], varsres$varsrs))
})
S2_res <- rbindlist(lapply(lin1, function(x) x[[1]]))
var_srs_ca <- rbindlist(lapply(lin1, function(x) x[[2]]))
}
var_srs_ca <- transpos(var_srs_ca, is.null(period), "var_srs_ca", names(period), "variable")
all_result <- merge(all_result, var_srs_ca, all = TRUE, by = c(names(period), "variable"))
S2_res <- transpos(S2_res, is.null(period), "S2_res", names(period), "variable")
all_result <- merge(all_result, S2_res, all = TRUE, by = c(names(period), "variable"))
Y4 <- w_final2 <- var_srs_ca <- S2_res <- NULL
all_result[, estim := Y_est]
if (!is.null(all_result$Z_est)) all_result[, estim := Y_est / Z_est * percentratio]
if (nrow(all_result[var_est < 0]) > 0) stop("Estimation of variance are negative!")
all_result[, deff_sam := var_cur_HT / var_srs_HT]
all_result[, deff_est := var_est / var_cur_HT]
all_result[, deff := deff_sam * deff_est]
all_result[, var_est2 := var_est]
all_result[xor(is.na(var_est2), var_est2 < 0), var_est2 := NA]
all_result[, se := sqrt(var_est2)]
all_result[(estim != 0) & !is.nan(estim), rse := se / estim]
all_result[estim == 0 | is.nan(estim), rse := NA]
all_result[, cv := rse * 100]
tsad <- qnorm(0.5 * (1 + confidence))
all_result[, absolute_margin_of_error := tsad * se]
all_result[, relative_margin_of_error := tsad * cv]
all_result[, CI_lower := estim - absolute_margin_of_error]
all_result[, CI_upper := estim + absolute_margin_of_error]
variableD <- NULL
setnames(all_result, c("variable", "var_est"), c("variableD", "var"))
if (!is.null(all_result$Z_est)) {
nosrZ <- data.table(all_result[, "variableDZ"], all_result[, tstrsplit(variableDZ, "__")][, 1])
nosrZ <- nosrZ[!duplicated(nosrZ)]
setnames(nosrZ, "V1", "variableZ")
all_result <- merge(all_result, nosrZ, by = "variableDZ")
nosrZ <- NULL
}
nosr <- data.table(all_result[, "variableD"], all_result[, tstrsplit(variableD, "__")])
nosr <- nosr[!duplicated(nosr)]
nosr <- nosr[, lapply(nosr, as.character)]
setnames(nosr, names(nosr)[2], "variable")
namesDom1 <- namesDom
if (!is.null(Dom)) {
setnames(nosr, names(nosr)[3 : ncol(nosr)], paste0(namesDom, "_new"))
nhs[, (paste0(namesDom, "_new")) := lapply(namesDom, function(x) make.names(paste0(x,".", get(x))))]
namesDom1 <- paste0(namesDom, "_new")
}
all_result <- merge(nosr, all_result, by="variableD")
namesDom <- nosr <- confidence_level <- NULL
if (!is.null(all_result$Z_est)) {
all_result[, variable := paste("R", get("variable"), get("variableZ"), sep="__")] }
if (!is.null(c(Dom, period))) { all_result <- merge(all_result, nhs,
all = TRUE, by = c(namesDom1, names(period)))
} else { all_result[, respondent_count := nhs$respondent_count]
all_result[, pop_size := nhs$pop_size]}
all_result[, confidence_level := confidence]
variab <- c("respondent_count", "n_nonzero", "pop_size")
if (!is.null(all_result$Z_est)) variab <- c(variab, "Y_est", "Z_est")
variab <- c(variab, "estim", "var", "se", "rse", "cv",
"absolute_margin_of_error", "relative_margin_of_error",
"CI_lower", "CI_upper", "confidence_level")
if (is.null(Dom)) variab <- c(variab, "S2_y_HT", "S2_y_ca", "S2_res")
variab <- c(variab, "var_srs_HT", "var_cur_HT", "var_srs_ca",
"deff_sam", "deff_est", "deff")
setkeyv(all_result, c("nr_names", names(Dom), names(period)))
all_result <- all_result[, c("variable", names(Dom), names(period), variab), with = FALSE]
list(lin_out = linratio_outp,
res_out = res_outp,
all_result = all_result)
} |
"wres.dist.qq" <-
function(object,
...) {
if(is.null(xvardef("wres",object))) {
cat("WRES is not set in the database!\n")
return()
}
xplot <- xpose.plot.qq(xvardef("wres",object),
object,
...)
return(xplot)
} |
DispStats <- function(inputrast1, inputrast2, statrast, vfdf,
sourceloc = TRUE, statistic = "var") {
if (is.logical(sourceloc) == FALSE) {
stop("sourceloc must be either TRUE or FALSE")
}
if (is.element(statistic, c("mean", "var", "sum")) == FALSE) {
stop("statistic must be 'mean', 'var', or 'sum'")
}
inputmat1 <- RastToMatrix(inputrast1)
inputmat2 <- RastToMatrix(inputrast2)
inputmat3 <- RastToMatrix(statrast)
dx <- terra::xres(inputrast1)
dy <- terra::yres(inputrast1)
Outdf <- vfdf
shiftx = round(Outdf$dispx/dx)
shifty = round(Outdf$dispy/dy)
shiftx[is.na(shiftx) == TRUE] = 0.0
shiftx[is.infinite(shiftx) == TRUE] = 0.0
shiftx[is.nan(shiftx) == TRUE] = 0.0
shifty[is.na(shifty) == TRUE] = 0.0
shifty[is.infinite(shifty) == TRUE] = 0.0
shifty[is.nan(shifty) == TRUE] = 0.0
for (i in 1:dim(Outdf)[1]) {
mat1sub <- ExtractMat(inputmat1, Outdf$frowmin[i], Outdf$frowmax[i], Outdf$fcolmin[i], Outdf$fcolmax[i])
mat2sub <- inputmat2
if (sourceloc == TRUE) {
mat1bin <- mat1sub
mat1bin[mat1bin > 0] <- 1
mat1bin[mat1bin == 0] <- NA
if (abs(shifty[i]) < (dim(mat2sub)[1] - 1) &
abs(shiftx[i]) < dim(mat2sub)[2] - 1) {
mat2back <- ShiftMat(mat2sub,
shiftrows = -shifty[i],
shiftcols = -shiftx[i])
} else {
mat2back <- matrix(rep(0, dim(mat2sub)[1]*dim(mat2sub)[2]),
nrow = dim(mat2sub)[1])
}
mat2back[mat2back > 0] <- 1
mat2back[mat2back == 0] <- NA
if (statistic == "mean") {
Outdf$Mean[i] <- mean(inputmat3*mat2back*mat1bin, na.rm = TRUE)
}
if (statistic == "var") {
Outdf$Var[i] <- stats::var(as.numeric(inputmat3*mat2back*mat1bin), na.rm = TRUE)
}
if (statistic == "sum") {
Outdf$Sum[i] <- sum(inputmat3*mat2back*mat1bin, na.rm = TRUE)
}
} else {
mat2bin <- mat2sub
mat2bin[mat2bin > 0] <- 1
mat2bin[mat2bin == 0] <- NA
if (abs(shifty[i]) < (dim(mat2sub)[1] - 1) &
abs(shiftx[i]) < dim(mat2sub)[2] - 1) {
mat1forw <- ShiftMat(mat1sub,
shiftrows = shifty[i],
shiftcols = shiftx[i])
} else {
mat1forw <- matrix(rep(0, dim(mat2sub)[1]*dim(mat2sub)[2]),
nrow = dim(mat2sub)[1])
}
mat1forw[mat1forw > 0] <- 1
mat1forw[mat1forw == 0] <- NA
if (statistic == "mean") {
Outdf$Mean[i] <- mean(inputmat3*mat1forw*mat2bin, na.rm = TRUE)
}
if (statistic == "var") {
Outdf$Var[i] <- stats::var(as.numeric(inputmat3*mat1forw*mat2bin), na.rm = TRUE)
}
if (statistic == "sum") {
Outdf$Sum[i] <- sum(inputmat3*mat1forw*mat2bin, na.rm = TRUE)
}
}
}
return(Outdf)
} |
context("extractSTA lme4")
modelLm <- fitTD(testTD, design = "rcbd", traits = "t1", engine = "lme4")
test_that("the output of extractSTA is of the proper type", {
expect_is(extractSTA(modelLm, what = "BLUEs"), "data.frame")
expect_is(extractSTA(modelLm), "list")
expect_length(extractSTA(modelLm)[["E1"]], 21)
expect_is(extractSTA(modelLm, what = c("BLUEs", "BLUPs")), "list")
expect_length(extractSTA(modelLm, what = c("BLUEs", "BLUPs"))[["E1"]], 2)
})
extLm <- extractSTA(modelLm)[["E1"]]
test_that("BLUEs are computed correctly", {
expect_is(extLm$BLUEs, "data.frame" )
expect_equal(dim(extLm$BLUEs), c(15, 2))
expect_named(extLm$BLUEs, c("genotype", "t1"))
expect_equal(extLm$BLUEs$t1,
c(86.959432402627, 60.0587826374786, 94.1691705937487,
74.0099150750079, 90.3428175809651, 66.5671108868047,
67.0747150491462, 63.701127332907, 87.0566508937095,
94.594647452768, 86.5691490691607, 83.6003540781321,
64.9321767034443, 58.9511717976486, 112.067789322994))
})
test_that("SE of BLUEs are computed correctly", {
expect_is(extLm$seBLUEs, "data.frame" )
expect_equal(dim(extLm$seBLUEs), c(15, 2))
expect_named(extLm$seBLUEs, c("genotype", "t1"))
expect_equal(extLm$seBLUEs$t1, rep(x = 19.8671913400323, times = 15))
})
test_that("BLUPs are computed correctly", {
expect_is(extLm$BLUPs, "data.frame" )
expect_equal(dim(extLm$BLUPs), c(15, 2))
expect_named(extLm$BLUPs, c("genotype", "t1"))
expect_equal(extLm$BLUPs$t1,
c(79.3770007251028, 79.3770007251028, 79.3770007251028,
79.3770007251028, 79.3770007251028, 79.3770007251028,
79.3770007251028, 79.3770007251028, 79.3770007251028,
79.3770007251028, 79.3770007251028, 79.3770007251028,
79.3770007251028, 79.3770007251028, 79.3770007251028))
})
test_that("SE of BLUPs are computed correctly", {
expect_is(extLm$seBLUPs, "data.frame" )
expect_equal(dim(extLm$seBLUPs), c(15, 2))
expect_named(extLm$seBLUPs, c("genotype", "t1"))
expect_equal(extLm$seBLUPs$t1, rep(x = 0, times = 15))
})
test_that("unit errors are computed correctly", {
expect_is(extLm$ue, "data.frame" )
expect_equal(dim(extLm$ue), c(15, 2))
expect_named(extLm$ue, c("genotype", "t1"))
expect_equal(extLm$ue$t1, rep(x = 394.705291741457, times = 15))
})
test_that("heritability is computed correctly", {
expect_is(extLm$heritability, "numeric")
expect_length(extLm$heritability, 1)
expect_named(extLm$heritability, "t1")
expect_equivalent(extLm$heritability, 0)
})
test_that("heritability can be coerced to data.frame correctly", {
herit <- extractSTA(modelLm, what= "heritability")
expect_is(herit, "data.frame")
expect_named(herit, c("trial", "t1"))
expect_equal(herit[1, 2], 0)
})
test_that("varGen is computed correctly", {
expect_is(extLm$varGen, "numeric")
expect_length(extLm$varGen, 1)
expect_named(extLm$varGen, "t1")
expect_equivalent(extLm$varGen, 0)
})
test_that("varErr is computed correctly", {
expect_is(extLm$varErr, "numeric")
expect_length(extLm$varErr, 1)
expect_named(extLm$varErr, "t1")
expect_equivalent(extLm$varErr, 638.590646884335)
})
test_that("fitted values are computed correctly", {
expect_is(extLm$fitted, "data.frame" )
expect_equal(dim(extLm$fitted), c(30, 3))
expect_named(extLm$fitted, c("genotype", "repId", "t1"))
expect_equal(extLm$fitted$t1,
c(113.978165854802, 96.0795471255565, 88.4324410491573,
60.8615483294564, 84.6587725373528, 81.6899775463243,
61.9691591692864, 61.7907508010991, 110.157412791186,
96.5050239845758, 85.1462743619017, 57.0407952658408,
88.4795256009685, 75.9202916068157, 58.1484061056708,
88.9670274255173, 68.4774874186125, 72.0995385432001,
65.6115038647147, 92.2531941127729, 63.0218001716365,
85.5107306099399, 85.0490558708192, 65.1643385173384,
88.8698089344348, 92.6842709209602, 64.6567343549969,
66.8425532352521, 68.985091580954, 92.2587940619409))
})
test_that("residuals are computed correctly", {
expect_is(extLm$residF, "data.frame" )
expect_equal(dim(extLm$residF), c(30, 3))
expect_named(extLm$residF, c("genotype", "repId", "t1"))
expect_equal(extLm$residF$t1,
c(-7.63439427908629, -7.68911687633611, 8.80187639497948,
-22.8661163893547, 32.7866964886075, 4.87615892024477,
-9.95913678359087, -1.87108123521764, 7.63439427908628,
-26.8180211716357, -32.99040276989, 22.8661163893547,
-32.7866964886075, 16.4496025710133, 9.95913678359089,
32.99040276989, 8.55271193691682, -16.4496025710133,
1.87108123521765, -8.8018763949795, -13.8443301609181,
-4.87615892024477, -31.7663736521888, -15.9570149776908,
31.7663736521888, 26.8180211716357, -8.55271193691682,
13.8443301609181, 15.9570149776908, 7.6891168763361))
})
test_that("standardized residuals are computed correctly", {
expect_is(extLm$stdResF, "data.frame" )
expect_equal(dim(extLm$stdResF), c(30, 3))
expect_named(extLm$stdResF, c("genotype", "repId", "t1"))
expect_equal(extLm$stdResF$t1,
c(-0.397758732092815, -0.400609828080684, 0.458585588708124,
-1.19134500137515, 1.70821604806888, 0.254052216678513,
-0.518879884240682, -0.0974849965244265, 0.397758732092815,
-1.39724275541933, -1.71882932650333, 1.19134500137515,
-1.70821604806888, 0.857038924489505, 0.518879884240683,
1.71882932650333, 0.445603898832203, -0.857038924489507,
0.0974849965244267, -0.458585588708124, -0.721301914752581,
-0.254052216678513, -1.65505632080001, -0.831374672762121,
1.65505632080002, 1.39724275541933, -0.445603898832203,
0.721301914752581, 0.831374672762121, 0.400609828080684))
})
test_that("rMeans are computed correctly", {
expect_is(extLm$rMeans, "data.frame" )
expect_equal(dim(extLm$rMeans), c(30, 3))
expect_named(extLm$rMeans, c("genotype", "repId", "t1"))
expect_equal(extLm$rMeans$t1,
c(81.2873772569106, 81.2873772569106, 77.466624193295,
81.2873772569106, 77.466624193295, 77.466624193295,
81.2873772569106, 77.466624193295, 77.466624193295,
81.2873772569106, 77.466624193295, 77.466624193295,
81.2873772569106, 81.2873772569106, 77.466624193295,
81.2873772569106, 81.2873772569106, 77.466624193295,
81.2873772569106, 81.2873772569106, 77.466624193295,
81.2873772569106, 77.466624193295, 77.466624193295,
81.2873772569106, 77.466624193295, 77.466624193295,
81.2873772569106, 81.2873772569106, 77.466624193295))
})
test_that("random effects are computed correctly", {
expect_is(extLm$ranEf, "data.frame" )
expect_equal(dim(extLm$ranEf), c(15, 2))
expect_named(extLm$ranEf, c("genotype", "t1"))
expect_equal(extLm$ranEf$t1,
c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
})
test_that("residuals are computed correctly for genotype random", {
expect_is(extLm$residR, "data.frame" )
expect_equal(dim(extLm$residR), c(30, 3))
expect_named(extLm$residR, c("genotype", "repId", "t1"))
expect_equal(extLm$residR$t1,
c(25.0563943188048, 7.10305299230976, 19.7676932508419,
-43.2919453168089, 39.9788448326654, 9.09951227327409,
-29.2773548712151, -17.5469546274135, 40.3251828769773,
-11.6003744439706, -25.3107526012833, 2.44028746190051,
-25.5945481445496, 11.0825169209183, -9.35908130403332,
40.6700529384967, -4.25717790138133, -21.8166882211082,
-13.8047921569782, 2.1639404608828, -28.2891541825766,
-0.652805567215481, -24.1839419746646, -28.2593006536474,
39.348805329713, 42.0356678993009, -21.3626017752149,
-0.600493860740485, 3.65472930173426, 22.481286744982))
})
test_that("standardized residuals are computed correctly", {
expect_is(extLm$stdResR, "data.frame" )
expect_equal(dim(extLm$stdResR), c(30, 3))
expect_named(extLm$stdResR, c("genotype", "repId", "t1"))
expect_equal(extLm$stdResR$t1,
c(0.99153328646432, 0.281082480894285, 0.782248459432799,
-1.71315171174464, 1.58204548115008, 0.360086499068644,
-1.15856541548165, -0.694369244345031, 1.5957507930531,
-0.459050781620821, -1.0015987691733, 0.0965672161856089,
-1.01282914510523, 0.438558089606995, -0.370358181851825,
1.60939801384436, -0.168465324336469, -0.863331423364774,
-0.546284144566353, 0.0856315944581839, -1.11946027273744,
-0.0258328649065675, -0.957008544833016, -1.11827890692418,
1.55711351643815, 1.66343821902723, -0.845362284616925,
-0.0237627826121337, 0.144625188667564, 0.889630959929036))
})
test_that("Waldtest is computed correctly", {
expect_is(extLm$wald$t1, "data.frame")
expect_length(extLm$wald$t1, 4)
expect_equivalent(unlist(extLm$wald$t1),
c(15, 14, 16.54, 2.22715086492192e-06))
})
test_that("CV is computed correctly", {
expect_is(extLm$CV, "numeric")
expect_length(extLm$CV, 1)
expect_named(extLm$CV, "t1")
expect_equivalent(extLm$CV, 35.3962119791326)
})
test_that("rDf is computed correctly", {
expect_is(extLm$rDfF, "integer")
expect_length(extLm$rDfF, 1)
expect_named(extLm$rDfF, "t1")
expect_equivalent(extLm$rDfF, 14)
})
test_that("rDfR is computed correctly", {
expect_is(extLm$rDfR, "integer")
expect_length(extLm$rDfR, 1)
expect_named(extLm$rDfR, "t1")
expect_equivalent(extLm$rDfR, 26)
})
test_that("correct attributes are added", {
expect_equal(attr(x = extLm, which = "traits"), "t1")
expect_equal(attr(x = extLm, which = "design"), "rcbd")
expect_equal(attr(x = extLm, which = "engine"), "lme4")
})
test_that("calculated values are logically correct", {
expect_equal(testTD[["E1"]]$t1, extLm$fitted$t1 + extLm$residF$t1)
expect_equal(testTD[["E1"]]$t1, extLm$rMeans$t1 + extLm$residR$t1)
}) |
.datatable.aware <- TRUE
pubRep <- function(.data, .col = "aa+v", .quant = c("count", "prop"), .coding = TRUE, .min.samples = 1, .max.samples = NA, .verbose = TRUE) {
.validate_repertoires_data(.data)
.preprocess <- function(dt) {
if (has_class(dt, "data.table")) {
dt <- dt %>% lazy_dt()
}
if (.coding) {
dt <- coding(dt)
}
dt <- as.data.table(dt %>% select(.col, .quant) %>% collect(n = Inf))
dt[, sum(get(.quant)), by = .col]
}
.col <- sapply(unlist(strsplit(.col, split = "\\+")), switch_type, USE.NAMES = FALSE)
.quant <- .quant_column_choice(.quant[1])
if (.verbose) {
pb <- set_pb(length(.data))
}
res <- .preprocess(.data[[1]])
setnames(res, colnames(res)[ncol(res)], names(.data)[1])
if (.verbose) {
add_pb(pb)
}
for (i in 2:length(.data)) {
res <- merge(res, .preprocess(.data[[i]]),
all = TRUE,
by = .col, suffixes = c(as.character(i - 1), as.character(i))
)
setnames(res, colnames(res)[ncol(res)], names(.data)[i])
if (.verbose) {
add_pb(pb)
}
}
if (.verbose) {
add_pb(pb)
}
res[["Samples"]] <- rowSums(!is.na(as.matrix(res[, (length(.col) + 1):ncol(res), with = FALSE])))
if (is.na(.max.samples)) {
.max.samples <- max(res[["Samples"]])
}
res <- res[(Samples >= .min.samples) & (Samples <= .max.samples)]
if (.verbose) {
add_pb(pb)
}
col_samples <- colnames(res)[(length(.col) + 1):(ncol(res) - 1)]
res <- setcolorder(res, c(.col, "Samples", col_samples))
res <- res[order(res$Samples, decreasing = TRUE), ]
add_class(res, "immunr_public_repertoire")
}
publicRepertoire <- pubRep
public_matrix <- function(.data) {
sample_i <- match("Samples", colnames(.data)) + 1
max_col <- dim(.data)[2]
.data %>%
dplyr::select(sample_i:max_col) %>%
collect(n = Inf) %>%
as.matrix()
}
num2bin <- function(number, n_bits) {
vec <- as.numeric(intToBits(number))
if (missing(n_bits)) {
vec
} else {
vec[1:n_bits]
}
}
get_public_repertoire_names <- function(.pr) {
sample_i <- match("Samples", names(.pr)) + 1
names(.pr)[sample_i:ncol(.pr)]
}
pubRepFilter <- function(.pr, .meta, .by, .min.samples = 1) {
assertthat::assert_that(has_class(.pr, "immunr_public_repertoire"))
assertthat::assert_that(.min.samples > 0)
if (!check_group_names(.meta, .by)) {
return(NA)
}
data_groups <- lapply(1:length(.by), function(i) {
.meta[["Sample"]][.meta[[names(.by)[i]]] == .by[i]]
})
samples_of_interest <- data_groups[[1]]
if (length(.by) > 1) {
for (i in 2:length(data_groups)) {
samples_of_interest <- intersect(data_groups[[i]], samples_of_interest)
}
}
samples_of_interest <- intersect(samples_of_interest, get_public_repertoire_names(.pr))
if (length(samples_of_interest) == 0) {
message("Warning: no samples found, check group values in the .by argument!")
return(NA)
}
sample_i <- match("Samples", colnames(.pr))
indices <- c(1:(match("Samples", colnames(.pr))), match(samples_of_interest, colnames(.pr)))
new.pr <- .pr %>%
lazy_dt() %>%
dplyr::select(indices) %>%
as.data.table()
new.pr[["Samples"]] <- rowSums(!is.na(as.matrix(new.pr[, (sample_i + 1):ncol(new.pr), with = FALSE])))
new.pr <- new.pr %>%
lazy_dt() %>%
dplyr::filter(Samples >= .min.samples) %>%
as.data.table()
new.pr
}
publicRepertoireFilter <- pubRepFilter
pubRepApply <- function(.pr1, .pr2, .fun = function(x) log10(x[1]) / log10(x[2])) {
col_before_samples <- names(.pr1)[1:(match("Samples", colnames(.pr1)) - 1)]
tmp <- rowMeans(public_matrix(.pr1), na.rm = TRUE)
.pr1[, (match("Samples", colnames(.pr1)) + 1):ncol(.pr1)] <- NULL
.pr1[["Quant"]] <- tmp
tmp <- rowMeans(public_matrix(.pr2), na.rm = TRUE)
.pr2[, (match("Samples", colnames(.pr2)) + 1):ncol(.pr2)] <- NULL
.pr2[["Quant"]] <- tmp
pr.res <- dplyr::inner_join(lazy_dt(.pr1), lazy_dt(.pr2), by = col_before_samples) %>% as.data.table()
pr.res[["Samples.x"]] <- pr.res[["Samples.x"]] + pr.res[["Samples.y"]]
pr.res[, Samples.y := NULL]
names(pr.res)[match("Samples.x", colnames(pr.res))] <- "Samples"
pr.res[["Result"]] <- apply(pr.res[, c("Quant.x", "Quant.y")], 1, .fun)
add_class(pr.res, "immunr_public_repertoire_apply")
}
publicRepertoireApply <- pubRepApply
pubRepStatistics <- function(.data, .by = NA, .meta = NA) {
if (!has_class(.data, "immunr_public_repertoire")) {
stop("Error: please apply pubRepStatistics() to public repertoires, i.e., output from the pubRep() function.")
}
melted_pr <- reshape2::melt(.data, id.vars = colnames(.data)[1:(match("Samples", colnames(.data)))])
melted_pr <- na.omit(melted_pr)
melted_pr <- melted_pr %>%
group_by(CDR3.aa) %>%
mutate(Group = paste0(variable, collapse = "&")) %>%
filter(Samples > 1) %>%
as_tibble()
group_tab <- table(melted_pr$Group)
melted_pr <- as_tibble(group_tab, .name_repair = function(x) c("Group", "Count"))
add_class(melted_pr, "immunr_public_statistics")
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.