code
stringlengths 1
13.8M
|
---|
import_RDS <- function(filePath, checkVarNames = TRUE) {
rawDat <- readRDS(file = filePath)
import_DF(rawDat, checkVarNames = checkVarNames)
} |
dist2chi <- function(X,C) {
ndata = nrow(X)
ncentres = nrow(C)
meanX = apply(X,2,mean)
meanC = apply(C,2,mean)
res = matrix(0,ndata,ncentres)
for (i in 1:ndata)
{
for (j in 1:ncentres)
{
res[i,j] = sum((X[i,]-C[j,])^2/(X[i,]+C[j,]))/2
}
}
return(res)
} |
NULL
print.stan_nma <- function(x, ...) {
if (inherits(x$network, "mlnmr_data")) type <- "ML-NMR"
else type <- "NMA"
cglue("A {x$trt_effects} effects {type} with a {x$likelihood} likelihood ({x$link} link).")
if (x$consistency != "consistency") {
if (x$consistency == "nodesplit")
cglue("An inconsistency model ('{x$consistency}') was fitted, splitting the comparison {x$nodesplit[2]} vs. {x$nodesplit[1]}.")
else
cglue("An inconsistency model ('{x$consistency}') was fitted.")
}
if (!is.null(x$regression)) {
cglue("Regression model: {rlang::as_label(x$regression)}.")
if (!is.null(x$xbar)) {
cglue("Centred covariates at the following overall mean values:")
print(x$xbar)
}
}
sf <- as.stanfit(x)
dots <- list(...)
include <- "pars" %in% names(dots)
dots <- rlang::dots_list(x = sf,
pars = c("log_lik", "resdev",
"fitted_ipd",
"fitted_agd_arm",
"fitted_agd_contrast",
"theta_bar_cum_agd_arm",
"theta_bar_cum_agd_contrast",
"theta2_bar_cum",
"mu", "delta"),
include = include,
use_cache = FALSE,
!!! dots,
.homonyms = "last")
do.call(print, dots)
invisible(x)
}
summary.stan_nma <- function(object, ...,
pars, include,
probs = c(0.025, 0.25, 0.5, 0.75, 0.975)
) {
if (missing(include)) {
include <- !missing(pars)
} else {
if (!rlang::is_bool(include)) abort("`include` should be TRUE or FALSE")
}
if (missing(pars)) {
pars <- c("log_lik", "resdev", "lp__")
if (has_ipd(object$network)) pars <- c(pars, "fitted_ipd")
if (has_agd_arm(object$network)) pars <- c(pars, "fitted_agd_arm")
if (has_agd_contrast(object$network)) pars <- c(pars, "fitted_agd_contrast")
if (inherits(object, "stan_mlnmr")) {
if (has_agd_arm(object$network)) pars <- c(pars, "theta_bar_cum_agd_arm")
if (has_agd_contrast(object$network)) pars <- c(pars, "theta_bar_cum_agd_contrast")
}
if (object$likelihood %in% c("bernoulli2", "binomial2")) {
if (has_agd_arm(object$network)) pars <- c(pars, "theta2_bar_cum")
}
} else {
if (!is.character(pars)) abort("`pars` should be a character vector")
}
sims <- as.array(object, pars = pars, include = include)
sums <- summary_mcmc_array(sims, probs = probs)
ss <- list(summary = sums, sims = sims)
class(ss) <- c("nma_parameter_summary", "nma_summary")
attr(ss, "xlab") <- "Parameter"
attr(ss, "ylab") <- "Value"
return(ss)
}
plot.stan_nma <- function(x, ...,
pars, include,
stat = "pointinterval",
orientation = c("horizontal", "vertical", "y", "x"),
ref_line = NA_real_) {
s <- summary(x, pars = pars, include = include)
p <- plot(s, ..., stat = stat, orientation = orientation, ref_line = ref_line)
return(p)
}
plot_prior_posterior <- function(x, ...,
prior = NULL,
post_args = list(),
prior_args = list(),
overlay = c("prior", "posterior"),
ref_line = NA_real_) {
if (!inherits(x, "stan_nma"))
abort("Not a `stan_nma` object.")
priors_used <-
c("intercept"[!is.null(x$priors$prior_intercept)],
"trt"[!is.null(x$priors$prior_trt)],
"het"[!is.null(x$priors$prior_het)],
"reg"[!is.null(x$priors$prior_reg)],
"aux"[!is.null(x$priors$prior_aux)])
if (is.null(prior)) {
prior <- priors_used
} else if (!rlang::is_character(prior) || !all(prior %in% priors_used)) {
abort(paste0("`prior` should be a character vector, with elements from ",
paste(priors_used, collapse = ", ")))
}
if (!is.list(post_args))
abort("`post_args` should be a list of arguments to pass to ggdist::stat_sample_slabinterval")
if (!is.list(prior_args))
abort("`prior_args` should be a list of arguments to pass to ggdist::stat_dist_slabinterval")
overlay <- rlang::arg_match(overlay)
if (!is.numeric(ref_line) || !is.null(dim(ref_line)))
abort("`ref_line` should be a numeric vector.")
prior_dat <- vector("list", length(prior))
for (i in seq_along(prior)) {
if (prior[i] %in% c("het", "aux")) trunc <- c(0, Inf)
else trunc <- NULL
prior_dat[[i]] <- get_tidy_prior(x$priors[[paste0("prior_", prior[i])]], trunc = trunc) %>%
tibble::add_column(prior = prior[i])
}
prior_dat <- dplyr::bind_rows(prior_dat) %>%
dplyr::mutate(par_base = dplyr::recode(.data$prior,
intercept = "mu",
trt = "d",
het = "tau",
reg = "beta",
aux = switch(x$likelihood, normal = "sigma", ordered = "cc")))
if (inherits(x, "nma_nodesplit")) {
prior_dat <- dplyr::bind_rows(
prior_dat,
dplyr::filter(prior_dat, .data$prior == "trt") %>%
dplyr::mutate(par_base = "omega")
)
}
pars <- unique(prior_dat$par_base)
draws <- tibble::as_tibble(as.matrix(x, pars = pars))
if ("het" %in% prior) {
if (x$priors$prior_het_type == "var") {
draws$tausq <- draws$tau^2
draws <- dplyr::select(draws, -.data$tau)
prior_dat$par_base <- dplyr::recode(prior_dat$par_base, tau = "tausq")
} else if (x$priors$prior_het_type == "prec") {
draws$prec <- draws$tau^-2
draws <- dplyr::select(draws, -.data$tau)
prior_dat$par_base <- dplyr::recode(prior_dat$par_base, tau = "prec")
}
}
if (x$likelihood == "ordered" && "aux" %in% prior) {
l_cat <- if (has_ipd(x$network)) colnames(x$network$ipd$.r) else colnames(x$network$agd_arm$.r)
n_cat <- length(l_cat)
if (n_cat <= 2) {
draws <- dplyr::select(draws, -dplyr::starts_with("cc["))
prior_dat <- dplyr::filter(prior_dat, prior != "aux")
} else {
for (i in 2:(n_cat-1)) {
draws <- dplyr::mutate(draws, !! paste0("diff_cc[", l_cat[i+1], " - ", l_cat[i], "]") :=
!! as.symbol(paste0("cc[", l_cat[i+1], "]")) - !! as.symbol(paste0("cc[", l_cat[i], "]")))
}
draws <- dplyr::select(draws, -dplyr::starts_with("cc["))
}
prior_dat <- dplyr::mutate(prior_dat, par_base = dplyr::recode(.data$par_base, cc = "diff_cc"))
}
if (packageVersion("tidyr") >= "1.0.0") {
draws <- tidyr::pivot_longer(draws, cols = dplyr::everything(),
names_to = "parameter", values_to = "value")
} else {
draws <- tidyr::gather(draws,
key = "parameter",
value = "value",
dplyr::everything())
}
draws$par_base <- stringr::str_remove(draws$parameter, "\\[.*\\]")
draws$parameter <- forcats::fct_inorder(factor(draws$parameter))
draws <- dplyr::left_join(draws, prior_dat[, c("par_base", "prior")], by = "par_base")
if (rlang::has_name(prior_args, "p_limits")) {
p_limits <- prior_args$p_limits
prior_args <- purrr::list_modify(prior_args, p_limits = purrr::zap())
} else {
p_limits <- c(0.001, 0.999)
}
if (rlang::has_name(prior_args, "n")) {
n <- prior_args$n
prior_args <- purrr::list_modify(prior_args, n = purrr::zap())
} else {
n <- 501
}
xseq <- dens <- vector("list", nrow(prior_dat))
for (i in seq_len(nrow(prior_dat))) {
dist <- prior_dat$dist[[i]]
args <- prior_dat$args[[i]]
if (dist == "unif") {
xseq[[i]] <- c(args$min, args$max)
if (is.infinite(args$min) || is.infinite(args$max)) {
dens[[i]] <- c(0, 0)
} else {
dens[[i]] <- dunif(xseq[[i]], min = args$min, max = args$max)
}
} else {
lower <- eval(rlang::call2(paste0("q", dist), p = p_limits[1], !!! args))
upper <- eval(rlang::call2(paste0("q", dist), p = p_limits[2], !!! args))
xseq[[i]] <- seq(from = lower, to = upper, length.out = n)
dens[[i]] <- eval(rlang::call2(paste0("d", dist), x = xseq[[i]], !!! args))
}
}
prior_dat <- tibble::add_column(prior_dat, xseq = xseq, dens = dens)
if (getNamespaceVersion("tidyr") < "1.0.0") {
prior_dat <- tidyr::unnest(prior_dat, .data$xseq, .data$dens)
} else {
prior_dat <- tidyr::unnest(prior_dat, c(.data$xseq, .data$dens))
}
prior_dat <- dplyr::left_join(prior_dat,
dplyr::distinct(draws, .data$par_base, .data$parameter),
by = "par_base")
xlim <- c(min(draws$value, 0), max(draws$value))
p <- ggplot2::ggplot() +
ggplot2::geom_vline(xintercept = ref_line, na.rm = TRUE, colour = "grey60") +
ggplot2::coord_cartesian(xlim = xlim)
g_prior <- rlang::call2(ggplot2::geom_line,
!!! rlang::dots_list(mapping = ggplot2::aes(x = .data$xseq, y = .data$dens),
data = prior_dat,
!!! prior_args,
.homonyms = "last"))
g_post <- rlang::call2(ggplot2::geom_histogram,
!!! rlang::dots_list(mapping = ggplot2::aes_(y = ~..density.., x = ~value, group = ~parameter),
data = draws,
binwidth = function(x) diff(range(x)) / nclass.Sturges(x),
boundary = 0,
position = "identity",
!!! post_args,
.homonyms = "last"))
if (overlay == "prior") {
p <- p + eval(g_post) + eval(g_prior)
} else {
p <- p + eval(g_prior) + eval(g_post)
}
p <- p +
ggplot2::facet_wrap("parameter", scales = "free") +
theme_multinma()
return(p)
}
plot_integration_error <- function(x, ...,
stat = "violin",
orientation = c("vertical", "horizontal", "x", "y"),
show_expected_rate = TRUE) {
if (!inherits(x, "stan_mlnmr"))
abort("Expecting a `stan_mlnmr` object, created by fitting a ML-NMR model with numerical integration using the `nma()` function.")
if (!rlang::is_bool(show_expected_rate))
abort("`show_expected_rate` must be a logical value, TRUE or FALSE.")
if (!rlang::is_string(stat))
abort("`stat` should be a character string specifying the name of a ggdist stat")
stat <- stringr::str_remove(stat, "^(stat_dist_|stat_|geom_)")
if (violin <- stat == "violin") {
stat <- "eye"
}
tb_geom <- tryCatch(getExportedValue("ggdist", paste0("stat_", stat)),
error = function(err) {
abort(paste("`stat` should be a character string specifying the name of a ggdist stat:",
err, sep = "\n"))
})
orientation <- rlang::arg_match(orientation)
if (orientation == "x") orientation <- "vertical"
else if (orientation == "y") orientation <- "horizontal"
horizontal <- orientation == "horizontal"
twoparbin <- x$likelihood %in% c("binomial2", "bernoulli2")
ipars <- c()
if (has_agd_arm(x$network)) {
ipars <- c(ipars, "theta_bar_cum_agd_arm")
}
if (has_agd_contrast(x$network)) {
ipars <- c(ipars, "theta_bar_cum_agd_contrast")
}
if (twoparbin) {
ipars <- c(ipars, "theta2_bar_cum")
}
int_dat <- as.data.frame(x, pars = ipars) %>%
dplyr::mutate(.draw = 1:dplyr::n())
colnames(int_dat) <- stringr::str_remove(colnames(int_dat), "_bar_cum(_agd_arm|_agd_contrast)?")
n_int <- x$network$n_int
rx <- "^(theta2?)\\[(.+): (.+), ([0-9]+)\\]$"
if (packageVersion("tidyr") >= "1.1.0") {
int_dat <- tidyr::pivot_longer(int_dat, cols = -dplyr::one_of(".draw"),
names_pattern = rx,
names_to = c("parameter", "study", "treatment", "n_int"),
names_transform = list(n_int = as.integer),
values_to = "value")
} else {
int_dat <- tidyr::gather(int_dat,
key = "parameter",
value = "value",
-dplyr::one_of(".draw")) %>%
tidyr::extract(.data$parameter,
into = c("parameter", "study", "treatment", "n_int"),
regex = rx,
convert = TRUE)
}
int_dat$study <- factor(int_dat$study, levels = levels(x$network$studies))
int_dat$treatment <- factor(int_dat$treatment, levels = levels(x$network$treatments))
int_dat <- dplyr::left_join(dplyr::filter(int_dat, .data$n_int != max(.data$n_int)),
dplyr::filter(int_dat, .data$n_int == max(.data$n_int)) %>%
dplyr::rename(final_value = .data$value) %>%
dplyr::select(-.data$n_int),
by = c("parameter", "study", "treatment", ".draw")) %>%
dplyr::mutate(diff = .data$value - .data$final_value)
int_thin <- min(int_dat$n_int)
if (show_expected_rate) {
conv_dat <- dplyr::bind_rows(
tibble::tibble(n_int = seq(1, n_int, length.out = 501), diff = n_int^-1, group = "pos"),
tibble::tibble(n_int = seq(1, n_int, length.out = 501), diff = -n_int^-1, group = "neg"))
}
if (horizontal) {
p <- ggplot2::ggplot(int_dat, ggplot2::aes(y = .data$n_int, x = .data$diff)) +
ggplot2::geom_vline(xintercept = 0, colour = "grey60") +
ggplot2::xlab("Estimated integration error") +
ggplot2::ylab("Number of integration points") +
ggplot2::coord_cartesian(xlim = range(int_dat$diff))
} else {
p <- ggplot2::ggplot(int_dat, ggplot2::aes(x = .data$n_int, y = .data$diff)) +
ggplot2::geom_hline(yintercept = 0, colour = "grey60") +
ggplot2::ylab("Estimated integration error") +
ggplot2::xlab("Number of integration points") +
ggplot2::coord_cartesian(ylim = range(int_dat$diff))
}
if (show_expected_rate) {
p <- p +
ggplot2::geom_line(ggplot2::aes(group = .data$group),
data = conv_dat,
colour = "grey60", linetype = 2)
}
v_args <-
if (violin) {
if (twoparbin) {
list(point_interval = NULL,
alpha = 0.8,
slab_size = 0.5)
} else {
list(point_interval = NULL,
slab_colour = "black",
slab_size = 0.5)
}
} else list()
if (twoparbin) {
p <- p +
do.call(tb_geom,
args = rlang::dots_list(ggplot2::aes(colour = .data$parameter,
fill = .data$parameter,
slab_colour = .data$parameter),
orientation = orientation,
...,
!!! v_args,
position = if (!horizontal) ggplot2::position_dodge(width = int_thin / 10) else "identity",
.homonyms = "first")) +
ggplot2::scale_colour_manual("Parameter",
values = c(theta = "
labels = function(x) dplyr::recode(x,
theta = expression(bar(p)),
theta2 = expression(bar(p)^2)),
aesthetics = c("colour", "fill", "slab_colour"))
} else {
p <- p +
do.call(tb_geom,
args = rlang::dots_list(orientation = orientation, ..., !!! v_args, .homonyms = "first"))
}
p <- p +
ggplot2::facet_wrap(~ study + treatment) +
theme_multinma()
return(p)
}
as.stanfit <- function(x, ...) {
UseMethod("as.stanfit")
}
as.stanfit.stan_nma <- function(x, ...) {
return(x[["stanfit"]])
}
as.stanfit.default <- function(x, ...) {
abort(glue::glue("Cannot coerce object of class '{class(x)}' to 'stanfit'."))
}
as.array.stan_nma <- function(x, ..., pars, include = TRUE) {
if (!rlang::is_bool(include))
abort("`include` must be TRUE or FALSE.")
if (!missing(pars)) {
if (!is.character(pars))
abort("`pars` must be a character vector of parameters to include (or missing).")
allpars <- c(x$stanfit@sim$pars_oi, x$stanfit@sim$fnames_oi)
badpars <- setdiff(pars, allpars)
if (length(badpars))
abort(glue::glue("No parameter{if (length(badpars) > 1) 's' else ''} ",
glue::glue_collapse(glue::double_quote(badpars), sep = ", ", last = " or "), "."))
if (include) {
par_base <- stringr::str_remove(pars, "\\[.*$")
} else {
par_base <- setdiff(x$stanfit@sim$pars_oi, pars)
}
a <- as.array(as.stanfit(x), pars = par_base, ...)
par_regex <- paste0("^\\Q", pars, "\\E(\\[|$)")
par_select <- unique(unlist(lapply(par_regex, grep, x = dimnames(a)[[3]],
perl = TRUE, invert = !include)))
out <- a[ , , par_select, drop = FALSE]
} else {
out <- as.array(as.stanfit(x), ...)
}
class(out) <- c("mcmc_array", "array")
return(out)
}
as.data.frame.stan_nma <- function(x, ..., pars, include = TRUE) {
return(as.data.frame(as.matrix(x, ..., pars = pars, include = include)))
}
as.matrix.stan_nma <- function(x, ..., pars, include = TRUE) {
a <- as.array(x, ..., pars = pars, include = include)
names_a <- dimnames(a)
dim_a <- dim(a)
dim(a) <- c(dim_a[1] * dim_a[2], dim_a[3])
dimnames(a) <- names_a[-2]
class(a) <- "matrix"
return(a)
}
loo.stan_nma <- function(x, ...) {
sf <- as.stanfit(x)
return(rstan::loo(sf, ...))
}
waic.stan_nma <- function(x, ...) {
ll <- as.array(x, pars = "log_lik")
return(loo::waic(ll, ...))
}
pairs.stan_nma <- function(x, ..., pars, include = TRUE) {
sf <- as.stanfit(x)
post_array <- as.array(x, pars = pars, include = include)
max_td <- sf@stan_args[[1]]$control$max_treedepth
if (is.null(max_td)) max_td <- 10
args <- rlang::dots_list(x = post_array,
np = bayesplot::nuts_params(sf),
lp = bayesplot::log_posterior(sf),
max_treedepth = max_td,
...,
condition = bayesplot::pairs_condition(nuts = "accept_stat__"),
.homonyms = "first")
thm <- bayesplot::bayesplot_theme_set(theme_multinma())
out <- do.call(bayesplot::mcmc_pairs, args = args)
bayesplot::bayesplot_theme_set(thm)
return(out)
} |
soptdmaeA<-function(trt.N, blk.N, theta, nrep, strt, sary, des0, dtype, Optcrit = " ",...)UseMethod("soptdmaeA") |
"ul1" |
require(hopkins)
X1 <- matrix(c(7,5,
3,3,
8,4,
1,2,
4,3,
7,4), ncol=2, byrow=TRUE)
X2 <- matrix(c(3,3,
3,5,
5,2,
5,4,
5,6,
7,4), ncol=2, byrow=TRUE)
U <- matrix(c(4,2,
3,5,
7,2), ncol=2, byrow=TRUE)
if(FALSE){
plot(NA, xlim=c(0,10), ylim=c(0,10))
text(X1, labels=1:nrow(X1))
text(X1[c(1,5,6),], labels=c("W ", "W ", "W "), col="blue")
text(U, labels=c("U1","U2","U3"), col="red")
debugonce(hopkins)
hopkins(X1, m=3, U=U)
}
test_that("Hopkins statistic", {
set.seed(42)
expect_equal(hopkins(X1, m=3, U=U),
0.75)
})
test_that("japanesepines data", {
jpines <- data.frame(
x = c(
0.09, 0.29, 0.38, 0.39, 0.48, 0.59, 0.65,
0.67, 0.73, 0.79, 0.86, 0.89, 0.98, 0.02, 0.11, 0.42, 0.48, 0.62,
0.73, 0.89, 0.02, 0.03, 0.07, 0.52, 0.64, 0.08, 0.08, 0.12, 0.12,
0.17, 0.31, 0.32, 0.42, 0.52, 0.91, 0.94, 0.34, 0.37, 0.47, 0.52,
0.59, 0.66, 0.76, 0.73, 0.89, 0.94, 0.98, 0.97, 0.12, 0.11, 0.17,
0.21, 0.29, 0.32, 0.35, 0.39, 0.52, 0.58, 0.69, 0.77, 0.36, 0.36,
0.39, 0.43, 0.62),
y = c(
0.09, 0.02, 0.03, 0.18, 0.03, 0.02,
0.16, 0.13, 0.13, 0.03, 0.13, 0.08, 0.02, 0.18, 0.31, 0.22, 0.13,
0.21, 0.23, 0.23, 0.41, 0.44, 0.42, 0.42, 0.43, 0.59, 0.63, 0.63,
0.66, 0.58, 0.53, 0.52, 0.49, 0.52, 0.52, 0.58, 0.68, 0.68, 0.67,
0.67, 0.67, 0.68, 0.66, 0.73, 0.74, 0.78, 0.79, 0.86, 0.84, 0.94,
0.95, 0.79, 0.84, 0.83, 0.86, 0.79, 0.93, 0.83, 0.93, 0.93, 0.97,
0.96, 0.96, 0.96, 0.97))
set.seed(28)
expect_equal( round(hopkins(jpines, m=3, method="simple"),6),
0.313107)
set.seed(28)
expect_equal(round(hopkins(jpines, m=3, method="torus"), 6),
0.217831)
})
test_that("Hopkins p-value", {
expect_equal(hopkins.pval(0.21, 10),
0.00466205, tolerance=1e-6)
expect_equal(hopkins.pval(.84, 10),
0.0004981939, tolerance=1e-6)
}) |
gene_ave<-function(file_gene_ave, k = 1){
x <- file_gene_ave[, -k]
file_gene_ave <- as.matrix(file_gene_ave)
rownames(file_gene_ave) <- file_gene_ave[,k]
ID<- rownames (file_gene_ave)
ID <- factor(ID,levels=unique(ID))
y <- rowsum(x, ID, reorder=FALSE, na.rm=TRUE)
n <- rowsum(1L-is.na(x), ID, reorder=FALSE)
return(y/n)
} |
PsiF <- function(t,w,tol = 1e-9, maxItem=1e2) {
value <- 0
convergence <- 0
for (k in 0:maxItem) {
value.returned <- value
item <- gamma(w)/gamma(w+k)*(w*t)^k/gamma(k+1)
value <- value + item
if (is.infinite(value)) {
convergence <- 0
break
}
if (abs(item/value) < tol) {
value.returned <- value
convergence <- 1
break
}
}
return(c(value.returned, k, convergence))
} |
tau2h_sj2 <- function(y, se) {
k <- length(y)
tau2h0 <- max(0.01, tau2h_vc(y, se)$tau2h)
w <- (1.0 + se^2/tau2h0)^-1
tau2h <- sum(w*(y - sum(y*w)/sum(w)))/(k - 1.0)
return(list(tau2h = tau2h))
} |
centroidCore<-function(v){
paramCheckResult=getEmptyParamCheckResult()
initialParamCheck_centroidCore(paramCheckResult = paramCheckResult, v)
A = v
retVal=NULL
n=getNumberOfPlayers(A)
N=length(A)
retVal=NULL
if(!isBalancedGame(A)){
print("Game is not balanced therefore no centroid of the core can be retrieved")
}else{
setVertices=coreVertices(A)
centroid=colSums(setVertices)/nrow(setVertices)
retVal = centroid
}
return(retVal)
}
drawCentroidCore<-function(v,holdOn=FALSE, colour = NA , label=TRUE, name = "centroid of core"){
A=v
pcn=centroidCore(A);
visualize(A, pointsToDraw=pcn, holdOn=holdOn, colour = colour , label=label, name = name)
}
initialParamCheck_centroidCore=function(paramCheckResult,v=v){
stopOnInvalidGameVector(paramCheckResult, v)
} |
rm(list=ls())
setwd("C:/Users/Tom/Documents/Kaggle/Santander")
library(data.table)
library(bit64)
library(xgboost)
library(stringr)
submissionDate <- "27-11-2016"
loadFile <- "xgboost weighted posFlanks 5, linear increase jun15 times6 back 13-0 no zeroing, exponential normalisation joint"
submissionFile <- "xgboost weighted posFlanks 5, soft average nomina nom_pens linear increase jun15 times6 back 13-0 no zeroing, exponential normalisation joint"
targetDate <- "12-11-2016"
trainModelsFolder <- "trainTrainAll"
trainAll <- grepl("TrainAll", trainModelsFolder)
testFeaturesFolder <- "test"
loadPredictions <- TRUE
loadBaseModelPredictions <- FALSE
savePredictions <- TRUE
saveBaseModelPredictions <- TRUE
savePredictionsBeforeNormalisation <- TRUE
normalizeProdProbs <- TRUE
normalizeMode <- c("additive", "linear", "exponential")[3]
additiveNormalizeProds <- NULL
fractionPosFlankUsers <- 0.035
expectedCountPerPosFlank <- 1.25
marginalNormalisation <- c("linear", "exponential")[2]
monthsBackModels <- 0:13
monthsBackWeightDates <- rev(as.Date(paste(c(rep(2015, 9), rep(2016, 5)),
str_pad(c(4:12, 1:5), 2, pad='0'),
28, sep="-")))
monthsBackModelsWeights <- rev(c(1.2, 1.3, 13, 0.1*(15:25)))
weightSum <- sum(monthsBackModelsWeights)
monthsBackLags <- 16:3
nominaNomPensSoftAveraging <- TRUE
predictSubset <- FALSE
nbLags <- length(monthsBackModelsWeights)
if(nbLags != length(monthsBackModels) ||
nbLags != length(monthsBackLags) ||
nbLags != length(monthsBackWeightDates)) browser()
predictionsFolder <- "Predictions"
ccoNoPurchase <- FALSE
zeroTargets <- NULL
source("Common/exponentialNormaliser.R")
monthProductWeightOverride <- NULL
predictionsPath <- file.path(getwd(), "Submission", submissionDate,
predictionsFolder)
dir.create(predictionsPath, showWarnings = FALSE)
if(saveBaseModelPredictions){
baseModelPredictionsPath <- file.path(predictionsPath, submissionFile)
dir.create(baseModelPredictionsPath, showWarnings = FALSE)
}
if(loadPredictions){
rawPredictionsPath <- file.path(predictionsPath,
paste0("prevNorm", loadFile, ".rds"))
} else{
rawPredictionsPath <- file.path(predictionsPath,
paste0("prevNorm", submissionFile, ".rds"))
}
posFlankClientsFn <- file.path(getwd(), "Feature engineering", targetDate,
"positive flank clients.rds")
posFlankClients <- readRDS(posFlankClientsFn)
modelsBasePath <- file.path(getwd(), "First level learners", targetDate,
trainModelsFolder)
modelGroups <- list.dirs(modelsBasePath)[-1]
nbModelGroups <- length(modelGroups)
baseModelInfo <- NULL
baseModels <- list()
for(i in 1:nbModelGroups){
modelGroup <- modelGroups[i]
slashPositions <- gregexpr("\\/", modelGroup)[[1]]
modelGroupExtension <- substring(modelGroup,
1 + slashPositions[length(slashPositions)])
modelGroupFiles <- list.files(modelGroup)
nbModels <- length(modelGroupFiles)
monthsBack <- as.numeric(substring(gsub("Lag.*$", "", modelGroupExtension),
5))
lag <- as.numeric(gsub("^.*Lag", "", modelGroupExtension))
relativeWeightOrig <- monthsBackModelsWeights[match(monthsBack,
monthsBackModels)]
weightDate <- monthsBackWeightDates[match(monthsBack, monthsBackModels)]
for(j in 1:nbModels){
modelInfo <- readRDS(file.path(modelGroup, modelGroupFiles[j]))
targetProduct <- modelInfo$targetVar
overrideId <- which(monthProductWeightOverride$product == targetProduct &
monthProductWeightOverride$month == weightDate)
if(length(overrideId)>0){
relativeWeight <- monthProductWeightOverride$weight[overrideId]
} else{
relativeWeight <- relativeWeightOrig
}
baseModelInfo <- rbind(baseModelInfo,
data.table(
modelGroupExtension = modelGroupExtension,
targetProduct = targetProduct,
monthsBack = monthsBack,
modelLag = lag,
relativeWeight = relativeWeight)
)
baseModels <- c(baseModels, list(modelInfo))
}
}
baseModelInfo[, modelId := 1:nrow(baseModelInfo)]
uniqueBaseModels <- sort(unique(baseModelInfo$targetProduct))
for(i in 1:length(uniqueBaseModels)){
productIds <- baseModelInfo$targetProduct==uniqueBaseModels[i]
productWeightSum <- baseModelInfo[productIds, sum(relativeWeight)]
normalizeWeightRatio <- weightSum/productWeightSum
baseModelInfo[productIds, relativeWeight := relativeWeight*
normalizeWeightRatio]
}
if(all(is.na(baseModelInfo$modelLag))){
nbGroups <- length(unique(baseModelInfo$modelGroupExtension))
baseModelInfo$monthsBack <- 0
baseModelInfo$modelLag <- 17
baseModelInfo$relativeWeight <- 1
monthsBackLags <- rep(17, nbGroups)
nbLags <- length(monthsBackLags)
monthsBackModelsWeights <- rep(1, nbGroups)
weightSum <- sum(monthsBackModelsWeights)
}
baseModelInfo <- baseModelInfo[order(monthsBack), ]
baseModelNames <- unique(baseModelInfo[monthsBack==0, targetProduct])
testDataLag <- readRDS(file.path(getwd(), "Feature engineering", targetDate,
testFeaturesFolder, "Lag17 features.rds"))
if(predictSubset){
testDataLag <- testDataLag[1:predictFirst]
}
testDataPosFlank <- testDataLag$ncodpers %in% posFlankClients
trainFn <- "train/Back13Lag3 features.rds"
colOrderData <- readRDS(file.path(getwd(), "Feature engineering", targetDate,
trainFn))
targetCols <- grep("^ind_.*_ult1$", names(colOrderData), value=TRUE)
nbBaseModels <- length(targetCols)
countContributions <- readRDS(file.path(getwd(), "Feature engineering",
targetDate,
"monthlyRelativeProductCounts.rds"))
if(!trainAll){
posFlankModelInfo <- baseModelInfo[targetProduct=="hasNewProduct"]
newProdPredictions <- rep(0, nrow(testDataLag))
if(nrow(posFlankModelInfo) != nbLags) browser()
for(i in 1:nbLags){
cat("Generating new product predictions for lag", i, "of", nbLags, "\n")
lag <- posFlankModelInfo[i, lag]
weight <- posFlankModelInfo[i, relativeWeight]
newProdModel <- baseModels[[posFlankModelInfo[i, modelId]]]
testDataLag <- readRDS(file.path(getwd(), "Feature engineering", targetDate,
testFeaturesFolder,
paste0("Lag", lag, " features.rds")))
if(predictSubset){
testDataLag <- testDataLag[1:predictFirst]
}
predictorData <- testDataLag[, newProdModel$predictors, with=FALSE]
predictorDataM <- data.matrix(predictorData)
newProdPredictionsLag <- predict(newProdModel$model, predictorDataM)
newProdPredictions <- newProdPredictions + newProdPredictionsLag*weight
}
newProdPredictions <- newProdPredictions/weightSum
meanGroupPredsMayFlag <-
c(mean(newProdPredictions[testDataLag$hasMay15Data==0]),
mean(newProdPredictions[testDataLag$hasMay15Data==1]))
meanGroupPredsPosFlank <- c(mean(newProdPredictions[!testDataPosFlank]),
mean(newProdPredictions[testDataPosFlank]))
expectedPosFlanks <- sum(newProdPredictions)
leaderboardPosFlanks <- fractionPosFlankUsers*nrow(testDataLag)
normalisedProbRatio <- leaderboardPosFlanks/expectedPosFlanks
cat("Expected/leaderboard positive flank ratio",
round(1/normalisedProbRatio, 2), "\n")
if(marginalNormalisation == "linear"){
newProdPredictions <- newProdPredictions * normalisedProbRatio
} else{
newProdPredictions <- probExponentNormaliser(newProdPredictions,
normalisedProbRatio)
}
} else{
newProdPredictions <- rep(1, nrow(testDataLag))
}
if(loadPredictions && file.exists(rawPredictionsPath)){
allPredictions <- readRDS(rawPredictionsPath)
} else{
allPredictions <- NULL
for(lagId in 1:nbLags){
cat("\nGenerating positive flank predictions for lag", lagId, "of", nbLags,
"@", as.character(Sys.time()), "\n\n")
lag <- monthsBackLags[lagId]
testDataLag <- readRDS(file.path(getwd(), "Feature engineering", targetDate,
testFeaturesFolder,
paste0("Lag", lag, " features.rds")))
if(predictSubset){
testDataLag <- testDataLag[1:predictFirst]
}
for(i in 1:nbBaseModels){
targetVar <- targetCols[i]
targetModelId <- baseModelInfo[targetProduct==targetVar &
modelLag==lag, modelId]
if(length(targetModelId)>1){
targetModelId <- targetModelId[lagId]
}
targetModel <- baseModels[[targetModelId]]
weight <- baseModelInfo[modelId == targetModelId, relativeWeight]
if(targetModel$targetVar != targetVar) browser()
cat("Generating test predictions for model", i, "of", nbBaseModels, "\n")
baseModelPredPath <- file.path(baseModelPredictionsPath,
paste0(targetVar, " Lag ", lag, ".rds"))
if(loadBaseModelPredictions && file.exists(baseModelPredPath)){
predictionsDT <- readRDS(baseModelPredPath)
} else{
if(targetVar %in% zeroTargets){
predictions <- rep(0, nrow(testDataLag))
} else{
predictorData <- testDataLag[, targetModel$predictors, with=FALSE]
predictorDataM <- data.matrix(predictorData)
predictions <- predict(targetModel$model, predictorDataM)
alreadyOwned <- is.na(testDataLag[[paste0(targetVar, "Lag1")]]) |
testDataLag[[paste0(targetVar, "Lag1")]] == 1
predictionsPrevNotOwned <- predictions[!alreadyOwned]
}
predictions[alreadyOwned] <- 0
predictionsDT <- data.table(ncodpers = testDataLag$ncodpers,
predictions = predictions,
product = targetVar)
}
predictionsDT[, weightedPrediction :=
predictionsDT$predictions*weight]
if(targetVar %in% allPredictions$product){
allPredictions[product==targetVar, weightedPrediction:=
weightedPrediction +
predictionsDT$weightedPrediction]
} else{
allPredictions <- rbind(allPredictions, predictionsDT)
}
if(saveBaseModelPredictions && !loadBaseModelPredictions){
predictionsDT[, weightedPrediction:=NULL]
saveRDS(predictionsDT, baseModelPredPath)
}
}
}
allPredictions[, prediction := weightedPrediction / weightSum]
allPredictions[, weightedPrediction := NULL]
allPredictions[, predictions := NULL]
if(savePredictionsBeforeNormalisation){
saveRDS(allPredictions, file=rawPredictionsPath)
}
}
if(nominaNomPensSoftAveraging){
nominaProb <- allPredictions[product == "ind_nomina_ult1", prediction] *
newProdPredictions
nomPensProb <- allPredictions[product == "ind_nom_pens_ult1", prediction] *
newProdPredictions
avIds <- nominaProb>0 & nomPensProb>0 & (nomPensProb-nominaProb < 0.1)
avVals <- (nominaProb[avIds] + nomPensProb[avIds])/2
ncodpers <- unique(allPredictions$ncodpers)
avNcodPers <- ncodpers[avIds]
allPredictions[ncodpers %in% avNcodPers & product == "ind_nomina_ult1",
prediction := avVals]
allPredictions[ncodpers %in% avNcodPers & product == "ind_nom_pens_ult1",
prediction := avVals]
}
probMultipliers <- rep(NA, nbBaseModels)
if(normalizeProdProbs){
for(i in 1:nbBaseModels){
cat("Normalizing product predictions", i, "of", nbBaseModels, "\n")
targetVar <- targetCols[i]
alreadyOwned <- is.na(testDataLag[[paste0(targetVar, "Lag1")]]) |
testDataLag[[paste0(targetVar, "Lag1")]] == 1
predictions <- allPredictions[product==targetVar, prediction]
predictionsPrevNotOwned <- predictions[!alreadyOwned]
if(suppressWarnings(max(predictions[alreadyOwned]))>0) browser()
predictedPosFlankCount <- sum(predictionsPrevNotOwned *
newProdPredictions[!alreadyOwned])
probMultiplier <- nrow(testDataLag) * fractionPosFlankUsers *
expectedCountPerPosFlank * countContributions[17, i] /
predictedPosFlankCount
probMultipliers[i] <- probMultiplier
if(is.finite(probMultiplier)){
if(normalizeMode == "additive" || targetVar %in% additiveNormalizeProds){
predictions[!alreadyOwned] <- predictions[!alreadyOwned] +
(probMultiplier-1)*mean(predictions[!alreadyOwned])
} else{
if(normalizeMode == "linear"){
predictions[!alreadyOwned] <- predictions[!alreadyOwned] *
probMultiplier
} else{
predictions[!alreadyOwned] <- probExponentNormaliser(
predictions[!alreadyOwned], probMultiplier)
}
}
allPredictions[product==targetVar, prediction:=predictions]
}
}
}
if(ccoNoPurchase){
allPredictions[!ncodpers %in% posFlankClients &
ncodpers %in% testDataLag[ind_cco_fin_ult1Lag1==0, ncodpers] &
product == "ind_cco_fin_ult1",
prediction := 10]
}
setkey(allPredictions, ncodpers)
allPredictions[,order_predict := match(1:length(prediction),
order(-prediction)), by=ncodpers]
allPredictions <- allPredictions[order(ncodpers, -prediction), ]
orderCount <- allPredictions[, .N, .(ncodpers, order_predict)]
if(max(orderCount$N)>1) browser()
hist(allPredictions[order_predict==1, prediction])
topPredictions <- allPredictions[order_predict==1, .N, product]
topPredictions <- topPredictions[order(-N)]
topPredictionsPosFlanks <- allPredictions[order_predict==1 &
ncodpers %in% posFlankClients,
.N, product]
topPredictionsPosFlanks <- topPredictionsPosFlanks[order(-N)]
productRankDelaFin <- allPredictions[product=="ind_dela_fin_ult1", .N,
order_predict]
productRankDelaFin <- productRankDelaFin[order(order_predict),]
productRankDecoFin <- allPredictions[product=="ind_deco_fin_ult1", .N,
order_predict]
productRankDecoFin <- productRankDecoFin[order(order_predict),]
productRankTjcrFin <- allPredictions[product=="ind_tjcr_fin_ult1", .N,
order_predict]
productRankTjcrFin <- productRankTjcrFin[order(order_predict),]
productRankRecaFin <- allPredictions[product=="ind_reca_fin_ult1", .N,
order_predict]
productRankRecaFin <- productRankRecaFin[order(order_predict),]
allPredictions[, totalProb := prediction * rep(newProdPredictions,
each = nbBaseModels)]
meanProductProbs <- allPredictions[, .(meanCondProb = mean(prediction),
meanProb = mean(totalProb)), product]
meanProductProbs <- meanProductProbs[order(-meanCondProb), ]
productString <- paste(allPredictions[order_predict==1, product],
allPredictions[order_predict==2, product],
allPredictions[order_predict==3, product],
allPredictions[order_predict==4, product],
allPredictions[order_predict==5, product],
allPredictions[order_predict==6, product],
allPredictions[order_predict==7, product])
if(length(productString) != nrow(testDataLag)) browser()
submission <- data.frame(ncodpers = testDataLag$ncodpers,
added_products = productString)
paddedSubmission <- fread("Data/sample_submission.csv")
paddedSubmission[, added_products := ""]
matchIds <- match(submission$ncodpers, paddedSubmission$ncodpers)
paddedSubmission[matchIds, added_products := submission$added_products]
write.csv(paddedSubmission, file.path(getwd(), "Submission", submissionDate,
paste0(submissionFile, ".csv")),
row.names = FALSE)
if(savePredictions){
saveRDS(allPredictions, file=file.path(predictionsPath,
paste0(submissionFile, ".rds")))
}
cat("Submission file created successfully!\n",
nrow(submission)," records were predicted (",
round(nrow(submission)/nrow(paddedSubmission)*100,2), "%)\n", sep="") |
smoothing_seasonality <- function(d18Oc,
D47,
ages,
SD_d18Oc = 0.1,
SD_D47 = 0.04,
window = "optimize",
N = 1000,
p = 0.05,
d18O_fun = "KimONeil97",
D47_fun = "Bernasconi18",
export = FALSE,
export_raw = FALSE
){
if(length(unique(c(length(d18Oc), length(D47), length(ages)))) > 1){
stop("ERROR: Vectors 'd18Oc', 'D47' and 'ages' should have equal length")
}
Popt <- matrix(NA, ncol = 7, nrow = N)
colnames(Popt) <- c("optimal sample size",
"number of successful simulations",
"Optimum p-value",
"dOsum",
"dOwin",
"Dsum",
"Dwin")
if(length(SD_d18Oc) == 1){
SD_d18Oc <- rep(SD_d18Oc, length(d18Oc))
}
if(length(SD_D47) == 1){
SD_D47 <- rep(SD_D47, length(D47))
}
d18Omat <- as.data.frame(matrix(stats::rnorm(N * length(d18Oc), d18Oc, SD_d18Oc), ncol = N))
colnames(d18Omat) <- paste("Sim", seq(1, N, 1), sep = "")
D47mat <- as.data.frame(matrix(stats::rnorm(N * length(D47), D47, SD_D47), ncol = N))
colnames(D47mat) <- paste("Sim", seq(1, N, 1), sep = "")
if(window == "optimize"){
if(length(d18Oc) / ceiling(diff(range(ages))) < 2){
win <- seq(2, length(d18Oc), 1)
}else{
win <- seq(2, length(d18Oc) / ceiling(diff(range(ages))), 1)
}
recond <- as.data.frame(matrix(NA, ncol = N, nrow = length(ages)))
reconD <- as.data.frame(matrix(NA, ncol = N, nrow = length(ages)))
colnames(recond) <- colnames(reconD) <- paste("Sim", seq(1, N, 1), sep = "")
message("Optimizing moving average iteration ", "\r")
for(i in 1:N){
Dwin <- vapply(win, function(x) max(TTR::runMean(D47mat[, i], x), na.rm = TRUE), 1)
Dsum <- vapply(win, function(x) min(TTR::runMean(D47mat[, i], x), na.rm = TRUE), 1)
dwin <- vapply(win, function(x) max(TTR::runMean(d18Omat[, i], x), na.rm = TRUE), 1)
dsum <- vapply(win, function(x) min(TTR::runMean(d18Omat[, i], x), na.rm = TRUE), 1)
Dwinsd <- vapply(win, function(x) TTR::runSD(D47mat[, i], x)[which.max(TTR::runMean(D47mat[, i], x))], 1)
Dsumsd <- vapply(win, function(x) TTR::runSD(D47mat[, i], x)[which.min(TTR::runMean(D47mat[, i], x))], 1)
dwinsd <- vapply(win, function(x) TTR::runSD(d18Omat[, i], x)[which.max(TTR::runMean(d18Omat[, i], x))], 1)
dsumsd <- vapply(win, function(x) TTR::runSD(d18Omat[, i], x)[which.min(TTR::runMean(d18Omat[, i], x))], 1)
SDpool <- sqrt((Dsumsd ^ 2 + Dwinsd ^ 2) / 2)
T <- (Dsum - Dwin) / (SDpool * sqrt(2 / win))
Pval <- stats::pt(T, win - 1)
Popt[i, ] <- c(win[which(Pval == min(Pval, na.rm = TRUE))],
length(which(Pval < 0.05)),
min(Pval, na.rm = TRUE),
dsum[which(Pval == min(Pval, na.rm = TRUE))],
dwin[which(Pval == min(Pval, na.rm = TRUE))],
Dsum[which(Pval == min(Pval, na.rm = TRUE))],
Dwin[which(Pval == min(Pval, na.rm = TRUE))])
shift <- round(win[which(Pval == min(Pval, na.rm = TRUE))] / 2, 0)
recond[, i] <- c(TTR::runMean(d18Omat[, i], win[which(Pval == min(Pval, na.rm=TRUE))])[(shift + 1):length(d18Omat[, i])], rep(NA, shift))
reconD[, i] <- c(TTR::runMean(D47mat[, i], win[which(Pval == min(Pval, na.rm=TRUE))])[(shift + 1):length(D47mat[, i])], rep(NA, shift))
}
if(export_raw == TRUE){
utils::write.csv(Popt, "Optimized_moveing average_simulations.csv")
}
}else if(is.numeric(window)){
shift <- round(window / 2, 0)
recond <- apply(d18Omat, 2, TTR::runMean, n = window)
recond <- rbind(recond[(shift + 1):nrow(recond), ], matrix(NA, ncol = ncol(recond), nrow = shift))
reconD <- apply(D47mat, 2, TTR::runMean, n = window)
reconD <- rbind(reconD[(shift + 1):nrow(reconD), ], matrix(NA, ncol = ncol(reconD), nrow = shift))
}else{
stop("ERROR: Window input not supported")
}
month <- ceiling((ages %% 1) * 12)
message("Grouping d18Oc data into monthly bins ", "\r")
utils::flush.console()
d18Oc_monthly <- data.frame(d18Oc_mean = vapply(1:12, function(x) mean(as.matrix(recond[which(month == x), ]), na.rm = TRUE), 1),
d18Oc_median = vapply(1:12, function(x) stats::median(as.matrix(recond[which(month == x), ]), na.rm = TRUE), 1),
d18Oc_SD = vapply(1:12, function(x) stats::sd(as.matrix(recond[which(month == x), ]), na.rm = TRUE), 1)
)
d18Oc_monthly$d18Oc_SE <- d18Oc_monthly$d18Oc_SD / sqrt(vapply(1:12, function(x) length(as.matrix(recond[which(month == x), 1])), 1))
message("Grouping D47 data into monthly bins ", "\r")
utils::flush.console()
D47_monthly <- data.frame(D47_mean = vapply(1:12, function(x) mean(as.matrix(reconD[which(month == x), ]), na.rm = TRUE), 1),
D47_median = vapply(1:12, function(x) stats::median(as.matrix(reconD[which(month == x), ]), na.rm = TRUE), 1),
D47_SD = vapply(1:12, function(x) stats::sd(as.matrix(reconD[which(month == x), ]), na.rm = TRUE), 1)
)
D47_monthly$D47_SE <- D47_monthly$D47_SD / sqrt(vapply(1:12, function(x) length(as.matrix(reconD[which(month == x), 1])), 1))
message("Grouping Temperature data into monthly bins ", "\r")
utils::flush.console()
if(D47_fun == "Bernasconi18"){
T_monthly <- data.frame(T_mean = vapply(1:12, function(x) mean(sqrt((0.0449 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.167)) - 273.15, na.rm = TRUE), 1),
T_median = vapply(1:12, function(x) stats::median(sqrt((0.0449 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.167)) - 273.15, na.rm = TRUE), 1),
T_SD = vapply(1:12, function(x) stats::sd(sqrt((0.0449 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.167)) - 273.15, na.rm = TRUE), 1)
)
}else if(D47_fun == "Jautzy20"){
T_monthly <- data.frame(T_mean = vapply(1:12, function(x) mean(sqrt((0.0433 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.119 - 0.066)) - 273.15, na.rm = TRUE), 1),
T_median = vapply(1:12, function(x) stats::median(sqrt((0.0433 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.119 - 0.066)) - 273.15, na.rm = TRUE), 1),
T_SD = vapply(1:12, function(x) stats::sd(sqrt((0.0433 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.119 - 0.066)) - 273.15, na.rm = TRUE), 1)
)
}
T_monthly$T_SE = T_monthly$T_SD / sqrt(vapply(1:12, function(x) length(as.matrix(reconD[which(month == x), 1])), 1))
message("Grouping d18Ow data into monthly bins ", "\r")
utils::flush.console()
if(d18O_fun == "KimONeil97"){
if(D47_fun == "Bernasconi18"){
d18Ow_monthly <- data.frame(d18Ow_mean = vapply(1:12, function(x) mean(((as.matrix(recond[which(month == x), ]) / 1000 + 1) / exp(((18.03 * 10 ^ 3) / sqrt((0.0449 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.167)) - 32.42) / 1000) - 1) * 1000 * 1.03092 + 30.92, na.rm = TRUE), 1),
d18Ow_median = vapply(1:12, function(x) stats::median(((as.matrix(recond[which(month == x), ]) / 1000 + 1) / exp(((18.03 * 10 ^ 3) / sqrt((0.0449 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.167)) - 32.42) / 1000) - 1) * 1000 * 1.03092 + 30.92, na.rm = TRUE), 1),
d18Ow_SD = sqrt((vapply(1:12, function(x) stats::sd(((as.matrix(recond[which(month == x), ]) / 1000 + 1) / exp(((18.03 * 10 ^ 3) / sqrt((0.0449 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.167)) - 32.42) / 1000) - 1) * 1000 * 1.03092 + 30.92, na.rm = TRUE), 1)) ^ 2 + (1.03092 * d18Oc_monthly$d18Oc_SD) ^ 2)
)
}else if(D47_fun == "Jautzy20"){
d18Ow_monthly <- data.frame(d18Ow_mean = vapply(1:12, function(x) mean(((as.matrix(recond[which(month == x), ]) / 1000 + 1) / exp(((18.03 * 10 ^ 3) / sqrt((0.0433 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.119 - 0.066)) - 32.42) / 1000) - 1) * 1000 * 1.03092 + 30.92, na.rm = TRUE), 1),
d18Ow_median = vapply(1:12, function(x) stats::median(((as.matrix(recond[which(month == x), ]) / 1000 + 1) / exp(((18.03 * 10 ^ 3) / sqrt((0.0433 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.119 - 0.066)) - 32.42) / 1000) - 1) * 1000 * 1.03092 + 30.92, na.rm = TRUE), 1),
d18Ow_SD = sqrt((vapply(1:12, function(x) stats::sd(((as.matrix(recond[which(month == x), ]) / 1000 + 1) / exp(((18.03 * 10 ^ 3) / sqrt((0.0433 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.119 - 0.066)) - 32.42) / 1000) - 1) * 1000 * 1.03092 + 30.92, na.rm = TRUE), 1)) ^ 2 + (1.03092 * d18Oc_monthly$d18Oc_SD) ^ 2)
)
}
}else if(d18O_fun == "GrossmanKu86"){
if(D47_fun == "Bernasconi18"){
d18Ow_monthly <- data.frame(d18Ow_mean = vapply(1:12, function(x) mean(as.matrix(recond[which(month == x), ]) + ((sqrt((0.0449 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.167)) - 273.15) - 20.6) / 4.34 - 0.2, na.rm = TRUE), 1),
d18Ow_median = vapply(1:12, function(x) stats::median(as.matrix(recond[which(month == x), ]) + ((sqrt((0.0449 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.167)) - 273.15) - 20.6) / 4.34 - 0.2, na.rm = TRUE), 1),
d18Ow_SD = sqrt((vapply(1:12, function(x) stats::sd(as.matrix(recond[which(month == x), ]) + ((sqrt((0.0449 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.167)) - 273.15) - 20.6) / 4.34 - 0.2, na.rm = TRUE), 1)) ^ 2 + d18Oc_monthly$d18Oc_SD ^ 2)
)
}else if(D47_fun == "Jautzy20"){
d18Ow_monthly <- data.frame(d18Ow_mean = vapply(1:12, function(x) mean(as.matrix(recond[which(month == x), ]) + ((sqrt((0.0433 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.119 - 0.066)) - 273.15) - 20.6) / 4.34 - 0.2, na.rm = TRUE), 1),
d18Ow_median = vapply(1:12, function(x) stats::median(as.matrix(recond[which(month == x), ]) + ((sqrt((0.0433 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.119 - 0.066)) - 273.15) - 20.6) / 4.34 - 0.2, na.rm = TRUE), 1),
d18Ow_SD = sqrt((vapply(1:12, function(x) stats::sd(as.matrix(recond[which(month == x), ]) + ((sqrt((0.0433 * 10 ^ 6) / (as.matrix(reconD[which(month == x), ]) - 0.119 - 0.066)) - 273.15) - 20.6) / 4.34 - 0.2, na.rm = TRUE), 1)) ^ 2 + d18Oc_monthly$d18Oc_SD ^ 2)
)
}
}
d18Ow_monthly$d18Ow_SE = d18Ow_monthly$d18Ow_SD / sqrt(vapply(1:12, function(x) length(as.matrix(recond[which(month == x), 1])), 1))
monthly<-cbind(1:12,
d18Oc_monthly,
D47_monthly,
T_monthly,
d18Ow_monthly)
colnames(monthly)[1] <- "month"
if(export == TRUE){
utils::write.csv(monthly, paste("Monthly_moving average_results.csv"))
}
return(monthly)
} |
unload <- function(packages, msg = " Unloading %s...") {
badbase <- intersect(base_packages(), packages)
if (length(badbase) > 0) {
packages <- setdiff(packages, badbase)
warning("Will not unload base packages: ", paste(badbase, collapse = ", "))
}
if ("pak" %in% packages) {
packages <- setdiff(packages, "pak")
warning("Will not unload pak")
}
badloaded <- setdiff(packages, loadedNamespaces())
if (length(badloaded) > 0) {
packages <- setdiff(packages, badloaded)
warning(
"Will not unload packages that are load not loaded: ",
paste(badloaded, collapse = ", ")
)
}
packages <- unload_order_topo(packages)
gc()
for (pkg in packages) {
message(sprintf(msg, pkg))
unloadNamespace(pkg)
unload_dll(pkg)
}
bad <- intersect(packages, loadedNamespaces())
if (length(bad) > 0) {
stop(
"Could not unload ",
if (length(bad) == 1) "one package: " else "some packages: ",
paste(bad, collapse = ", ")
)
}
message()
invisible(packages)
}
needs_unload <- function(packages) {
packages <- setdiff(packages, c(base_packages(), "pak"))
packages <- intersect(packages, loadedNamespaces())
unload_order_topo(packages)
}
package_imports <- function(package, base = FALSE) {
imp <- unique(names(getNamespaceInfo(package, "imports")))
if (!base) imp <- imp[! imp %in% base_packages()]
imp[imp != ""]
}
unload_order_topo <- function(packages) {
all <- setdiff(loadedNamespaces(), base_packages())
imp <- lapply_with_names(all, package_imports)
imp_by <- lapply_with_names(all, function(p) {
all[vlapply(imp, `%in%`, x = p)]
})
revs <- packages
while (length(more <- setdiff(unlist(imp_by[revs]), revs)) > 0) {
revs <- c(revs, more)
}
imp_by <- lapply(imp_by, intersect, revs)[revs]
topo <- character()
while (length(topo) < length(revs)) {
new <- names(imp_by)[viapply(imp_by, length) == 0]
if (length(new) == 0) stop("Loop in package imports???")
topo <- c(topo, new)
imp_by <- lapply(imp_by, setdiff, new)[setdiff(names(imp_by), new)]
}
topo
}
unload_dll <- function(package) {
pkglibs <- loaded_dlls(package)
for (lib in pkglibs) {
dyn.unload(lib[["path"]])
}
libs <- .dynLibs()
.dynLibs(libs[!(libs %in% pkglibs)])
invisible()
}
loaded_dlls <- function(package) {
libs <- .dynLibs()
matchidx <- vapply(libs, "[[", character(1), "name") == package
libs[matchidx]
} |
normalize <- function(x) { x <- x - min(x); x/max(x); }
standardize <- function(x) {
x <- scale(x)
z <- as.numeric(x)
attr(z,"scaled:center") <- attr(x,"scaled:center")
attr(z,"scaled:scale") <- attr(x,"scaled:scale")
return(z)
}
unstandardize <- function(x) {
scale <- attr(x,"scaled:scale")
center <- attr(x,"scaled:center")
z <- x*scale + center
return( as.numeric(z) )
}
htmlhelp <- function() options(help_type="html")
setcran <- function(themirror="https://cloud.r-project.org/") options(repos=structure(c(CRAN=themirror)))
choose.csv <- function( ... ) read.csv( file=file.choose() , ... )
fclip <- function( x , xmin=NULL , xmax=NULL ) {
if ( !is.null(xmin) ) x <- ifelse( x < xmin , xmin , x )
if ( !is.null(xmax) ) x <- ifelse( x > xmax , xmax , x )
x
}
progbar <- function( current , min=0 , max=100 , starttime , update.interval=100 , show.rate=FALSE ) {
z <- current/update.interval
if ( floor(z)!=z ) return()
progress <- current - min
time.elapsed <- Sys.time() - starttime
elapsed.units <- attr(time.elapsed,"units")
f <- 1
if ( elapsed.units == "mins" ) f <- 60
if ( elapsed.units == "hours" ) f <- 60*60
if ( elapsed.units == "days" ) f <- 60*60*24
rate <- progress / ( as.numeric(time.elapsed) * f )
eta <- (max - current)/rate
etamins <- floor(eta/60)
etahours <- floor(etamins/60)
etasecs <- floor(eta - etamins*60)
if ( etahours > 0 ) etamins <- etamins - etahours*60
percentdone <- floor(current/max * 100)
ETAstring <- paste( etahours , "h " , sep="" )
if ( etahours==0 & etamins>0 ) ETAstring <- paste( etamins , "m " , sep="" )
if ( etahours==0 & etamins==0 ) ETAstring <- paste( etasecs , "s " , sep="" )
Ratestring <- ""
if ( show.rate==TRUE ) Ratestring <- paste( " | Rate: " , round(rate,2) , " samples/sec" , sep="" )
cat( "\r" )
cat( paste( c( current , "/" , max , " (" , percentdone , "%) | Elapsed: " , round(time.elapsed,2) , elapsed.units , " | Remaining: " , ETAstring , Ratestring ) , collapse="" ) )
}
covmat <- function( m , digits=4 ) {
if ( inherits(m, "data.frame") ) mcov <- cov( m ) else mcov <- vcov(m)
mcor <- cov2cor( mcov )
mcov[ lower.tri(mcov) ] <- NA
mcor[ lower.tri(mcor) ] <- NA
result <- list( vcov=round(mcov,digits=digits) , cor=round(mcor,digits=digits) )
result
}
Rho <- function( model , digits=2 ) {
round( cov2cor(vcov(model)) , digits )
}
chainmode <- function( chain , ... ) {
dd <- density(chain , ...)
dd$x[which.max(dd$y)]
}
PIprimes <- c(0.67,0.89,0.97)
HPDI <- function( samples , prob=0.89 ) {
coerce.list <- c( "numeric" , "matrix" , "data.frame" , "integer" , "array" )
if ( inherits(samples, coerce.list) ) {
samples <- coda::as.mcmc( samples )
}
x <- sapply( prob , function(p) coda::HPDinterval( samples , prob=p ) )
n <- length(prob)
result <- rep(0,n*2)
for ( i in 1:n ) {
low_idx <- n+1-i
up_idx <- n+i
result[low_idx] <- x[1,i]
result[up_idx] <- x[2,i]
names(result)[low_idx] <- concat("|",prob[i])
names(result)[up_idx] <- concat(prob[i],"|")
}
return(result)
}
PCI <- function( samples , prob=0.89 ) {
x <- sapply( prob , function(p) {
a <- (1-p)/2
quantile( samples , probs=c(a,1-a) )
} )
n <- length(prob)
result <- rep(0,n*2)
for ( i in 1:n ) {
low_idx <- n+1-i
up_idx <- n+i
result[low_idx] <- x[1,i]
result[up_idx] <- x[2,i]
a <- (1-prob[i])/2
names(result)[low_idx] <- concat(round(a*100,0),"%")
names(result)[up_idx] <- concat(round((1-a)*100,0),"%")
}
return(result)
}
PI <- PCI
se <- function( model ) {
sqrt( diag( vcov(model) ) )
}
confint_quad <- function( model=NULL , est , se , prob=0.89 ) {
if ( !is.null(model) ) {
found.class <- FALSE
if ( class(model)=="lm" ) {
est <- coef(model)
se <- summary(model)$coef[,2]
found.class <- TRUE
}
if ( class(model)=="mle2" ) {
est <- coef(model)
se <- summary(model)@coef[,2]
found.class <- TRUE
}
if ( found.class==FALSE ) {
return( paste("Cannot find handler for model of class",class(model)) )
}
}
n <- length(est)
mat <- matrix(c(rep(-1,n),rep(1,n)),nrow=n)
p <- (1-prob)/2
z <- -qnorm( p )
ci <- est + mat * ( se * z )
rownames(ci) <- names(est)
lowlab <- paste( format( p*100 , nsmall=1 ) , "%" , sep="" )
hilab <- paste( format( (1-p)*100 , nsmall=1 ) , "%" , sep="" )
colnames(ci) <- c( lowlab , hilab )
ci
}
replicate2 <- function (n, expr, interval=0.1, simplify = "array") {
show_progress <- function(i) {
intervaln <- floor( n * interval )
if ( floor(i/intervaln) == i/intervaln ) {
cat( paste( "[" , i , "/" , n , "]\r" ) )
}
}
result <- sapply(1:n,
eval.parent(substitute(function(i,...) { show_progress(i); expr })),
simplify = simplify)
cat("\n")
result
}
mcreplicate <- function (n, expr, refresh = 0.1, mc.cores=2 ) {
show_progress <- function(i) {
intervaln <- floor(n * refresh)
if (floor(i/intervaln) == i/intervaln) {
cat(paste("[", i, "/", n, "]\r"))
}
}
result <- simplify2array(mclapply(1:n, eval.parent(substitute(function(i,
...) {
if (refresh>0) show_progress(i)
expr
})),mc.cores=mc.cores))
if (refresh>0) cat("\n")
result
}
check_index <- function( x ) {
y <- sort(unique(x))
n <- length(y)
message( concat( "Length: ",n ) )
message( concat( "Range: ",min(y)," / ",max(y) ) )
if ( max(y) != n ) message( "Maximum index different than number of unique values" )
diffs <- sapply( 2:n , function(i) y[i] - y[i-1] )
if ( any(diffs)!=1 ) message( "At least one gap in consecutive values" )
}
coerce_index <- function( ... ) {
L <- list(...)
if ( is.list(L[[1]]) && length(L)==1 ) L <- L[[1]]
if ( length(L)==1 ) {
x <- as.integer(L[[1]])
if ( any(is.na(x)) )
x <- as.integer(as.factor(as.character(L[[1]])))
return( x )
} else {
vnames <- match.call()
vnames <- as.character(vnames)[2:(length(L)+1)]
M <- L
for ( i in 1:length(L) ) M[[i]] <- as.character(L[[i]])
Mall <- M[[1]]
for ( i in 2:length(L) ) Mall <- c( Mall , M[[i]] )
Mall <- unique(Mall)
new_levels <- levels(as.factor(Mall))
for ( i in 1:length(L) ) {
M[[i]] <- factor(M[[i]],levels=new_levels)
M[[i]] <- as.integer(M[[i]])
}
names(M) <- paste( vnames , "_idx" , sep="" )
return(M)
}
}
sd2 <- function( x , na.rm=TRUE ) {
sqrt( var2(x,na.rm=na.rm) )
}
var2 <- function( x , na.rm=TRUE ) {
mean(x^2) - mean(x)^2
}
sd_pop <- sd2
var_pop <- var2
format_show <- function( x , digits ) {
r <- as.data.frame(lapply( 1:length(x) ,
function(i) {
if ( class(x[[i]])!="character" ) {
if ( names(x)[i] %in% names(digits) )
round( x[[i]] , digits[names(x)[i]] )
else
round(x[[i]], digits['default__'] );
} else {
return(x[[i]])
}
} ) )
names(r) <- names(x)
rownames(r) <- rownames(x)
return(r)
}
yn2bin <- function(x) ifelse(is.na(x),NA,ifelse(x %in% c("Yes","yes","Y","y"),1,0))
make_ukey <- function( n , m=5 , x=2 ,
bag=c("a","b","c","d","e","f","g","h","j",
"k","m","n","p","q","r","u","w","x",
"y","z",0,2,3,4,6,7,8,9) ) {
y <- rep(NA,n)
genkey <- function() paste( sample(bag,size=m,replace=TRUE) , collapse="" )
keydist <- function( k1 , k2 ) {
as.numeric(adist( k1 , k2 ))
}
checkkey <- function( key , xkeys ) {
dists <- sapply( xkeys , function(k) keydist( key , k ) )
if ( any( dists < x ) ) {
return(FALSE)
} else {
return(TRUE)
}
}
y[1] <- genkey()
for ( i in 2:n ) {
good <- FALSE
while( !good ) {
yn <- genkey()
f <- checkkey( yn , y[ !is.na(y) ] )
if ( f==TRUE ) {
y[i] <- yn
good <- TRUE
}
}
}
return(y)
} |
`as.list.mefa` <-
function(x, ...)
{
if (is.null(x$segm) || length(x$segm) == 1) {
return(list(x$xtab))
} else {
return(x$segm)
}
} |
tropproj.linsp <- function(x, V) {
if (is.vector(x)) x <- t(as.matrix(x))
n <- nrow(x)
pcs <- nrow(V)
e <- ncol(x)
all_dets <- array(NA, dim = (e - pcs +1): e)
all_combns <- comboGeneral(1:e, pcs)
all_combns_list <- lapply(1:nrow(all_combns), function(i) {
all_combns[i, ]
})
all_dets[all_combns] <- unlist(lapply(all_combns_list, function(i) {
tropdet(as.matrix(V[, i]))
}))
if (pcs == 1){
data_proj <- matrix(rep(V, n), nrow = n, byrow = T)
} else{
data_proj <- matrix(0, nrow = n, ncol = e)
for (i in 1:e) {
all_tau <- comboGeneral(c(1:e)[-i], pcs - 1)
all_tau <- lapply(1:nrow(all_tau), function(i) {
all_tau[i, ]
})
temp2 <- lapply(all_tau, function(tau) {
all_j <- c(1:e)[-tau]
temp_block <- eachrow(matrix(x[, all_j], ncol = e - pcs + 1),
all_dets[rowSort(cbind(all_j, matrix(tau, ncol = length(tau), nrow = (e - pcs + 1), byrow = T)))], "-")
return(rowMins(temp_block, T) + tropdet(V[, c(tau, i)]))
})
temp2 <- do.call(cbind, temp2)
data_proj[, i] <- rowMaxs(temp2, T)
}
}
rownames(data_proj) <- rownames(x)
colnames(data_proj) <- colnames(x)
data_proj
} |
"are.parglo.valid" <-
function(para,nowarn=FALSE) {
if(! is.glo(para)) return(FALSE)
if(any(is.na(para$para))) return(FALSE)
A <- para$para[2]
K <- para$para[3]
op <- options()
GO <- TRUE
if(nowarn == TRUE) options(warn=-1)
if(A <= 0) {
warning("Parameter A is not > 0, invalid")
GO <- FALSE
}
if(abs(K) >= 1) {
warning("abs(Parameter K) is not < 1, invalid")
GO <- FALSE
}
options(op)
if(GO) return(TRUE)
return(FALSE)
} |
par()
slices <- c(10, 12,4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pie(slices, labels = lbls, main="Pie Chart of Countries")
slices <- c(10, 12, 4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pct <- round(slices/sum(slices)*100)
lbls <- paste(lbls, pct)
lbls <- paste(lbls,"%",sep="")
pie(slices,labels = lbls, col=rainbow(length(lbls)),
main="Pie Chart of Countries")
library(plotrix)
slices <- c(10, 12, 4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pie3D(slices,labels=lbls,explode=0.1,
main="Pie Chart of Countries ")
mytable <- table(iris$Species)
lbls <- paste(names(mytable), "\n", mytable, sep="")
pie(mytable, labels = lbls,
main="Pie Chart of Species\n (with sample sizes)") |
git_rebase_list <- function(upstream = NULL, repo = '.'){
git_rebase(upstream = upstream, commit_changes = FALSE, repo = repo)
}
git_rebase_commit <- function(upstream = NULL, repo = '.'){
git_rebase(upstream = upstream, commit_changes = TRUE, repo = repo)
}
git_rebase <- function(upstream, commit_changes, repo){
repo <- git_open(repo)
info <- git_info(repo = repo)
if(!length(upstream)){
if(!length(info$upstream) || is.na(info$upstream) || !nchar(info$upstream))
stop("No upstream configured for current HEAD")
git_fetch(info$remote, repo = repo)
upstream <- info$upstream
}
df <- .Call(R_git_rebase, repo, upstream, commit_changes)
if(commit_changes){
new_head <- ifelse(nrow(df) > 0, utils::tail(df$commit, 1), upstream[1])
git_branch_set_target(ref = new_head, repo = repo)
inform("Resetting %s to %s", info$shorthand, new_head)
}
return(df)
}
git_reset_hard <- function(ref = "HEAD", repo = "."){
git_reset("hard", ref = ref, repo = repo)
}
git_reset_soft <- function(ref = "HEAD", repo = "."){
git_reset("soft", ref = ref, repo = repo)
}
git_reset_mixed <- function(ref = "HEAD", repo = "."){
git_reset("mixed", ref = ref, repo = repo)
}
git_reset <- function(type = c("soft", "hard", "mixed"), ref = "HEAD", repo = "."){
typenum <- switch(match.arg(type), soft = 1L, mixed = 2L, hard = 3L)
repo <- git_open(repo)
ref <- as.character(ref)
.Call(R_git_reset, repo, ref, typenum)
git_status(repo = repo)
}
git_cherry_pick <- function(commit, repo = '.'){
repo <- git_open(repo)
assert_string(commit)
.Call(R_git_cherry_pick, repo, commit)
}
git_ahead_behind <- function(upstream = NULL, ref = 'HEAD', repo = '.'){
repo <- git_open(repo)
if(!length(upstream))
upstream <- git_info(repo = repo)$upstream
if(!length(upstream))
stop("No upstream set or specified")
.Call(R_git_ahead_behind, repo, ref, upstream)
} |
pconmul<-function(t,lam,thres,sige){
nume <- sum(lam * t)-thres
term <- nume/sige
n <- exp(1.702*term)
p <- n / (1+n)
} |
ASMR <- function(Data.Name, CL = NULL,
PeriodEnd = NULL, Period = NULL) {
Data.Name <- Data.Name[!Data.Name$v005 == 0, ]
Data.Name$ID <- seq.int(nrow(Data.Name))
if (is.null(CL)) {
Z <- stats::qnorm(.025,lower.tail=FALSE)
} else {
Z <- stats::qnorm((100-CL)/200,lower.tail=FALSE)
}
if (is.null(Period)){Periodmsg = 84} else {Periodmsg = Period}
if (is.null(PeriodEnd)){
PeriodEndy_ <- as.integer((mean(Data.Name$v008) - 1)/12)+1900
PeriodEndm_ <- round(mean(Data.Name$v008) - ((PeriodEndy_ - 1900) * 12),0)
PeriodEndm_m <- round(min(Data.Name$v008) - ((PeriodEndy_ - 1900) * 12),0)
PeriodEndm_x <- round(max(Data.Name$v008) - ((PeriodEndy_ - 1900) * 12),0)
}
else {
dates <- paste(PeriodEnd, "01", sep = "-")
PeriodEndm_ <- as.numeric(format(as.Date(dates), "%m"))
PeriodEndy_ <- as.numeric(format(as.Date(dates), "%Y"))
if (PeriodEndm_ >= round(mean(Data.Name$v008) - (((as.integer((mean(Data.Name$v008) - 1)/12)+1900) - 1900) * 12),0) &
PeriodEndy_ >= as.integer((mean(Data.Name$v008) - 1)/12)+1900)
message(crayon::bold("Note:", "\n",
"You specified a reference period that ends after the survey fieldwork dates....."), "\n",
"1. Make sure the dates in the survey are coded according to the Gregorian calendar.", "\n",
"2. If the dates are coded according to the Gregorian calendar, use a proper PeriodEnd that came before the time of the survey.", "\n",
"3. If the dates are not coded according to the Gregorian calendar, use a PeriodEnd according to the used calendar.")
}
if (is.null(PeriodEnd)){
cat("\n", crayon::white$bgBlue$bold("The current function calculated ASMR based on a reference period of"),
crayon::red$bold$underline(Periodmsg), crayon::white$bold$bgBlue("months"), "\n", crayon::white$bold$bgBlue("The reference period ended at the time of the interview, in"), crayon::red$bold$underline(PeriodEndy_ + round(PeriodEndm_/12,digits=2)), "OR", crayon::red$bold$underline(month.abb[PeriodEndm_m]), "-", crayon::red$bold$underline(month.abb[PeriodEndm_x]), crayon::red$bold$underline(PeriodEndy_), "\n",
crayon::white$bold$bgBlue("The average reference period is"), crayon::red$bold$underline(round((PeriodEndy_ + PeriodEndm_/12)-(Periodmsg/24), digits =2)), "\n")
}
else {
cat("\n", crayon::white$bgBlue$bold("The current function calculated ASMR based on a reference period of"),
crayon::red$bold$underline(Periodmsg), crayon::white$bold$bgBlue("months"), "\n", crayon::white$bold$bgBlue("The reference period ended in"), crayon::red$bold$underline(PeriodEndy_ + round(PeriodEndm_/12,digits=2)), "OR", crayon::red$bold$underline(month.abb[PeriodEndm_]), crayon::red$bold$underline(PeriodEndy_), "\n" ,
crayon::white$bold$bgBlue("The average reference period is"), crayon::red$bold$underline(round((PeriodEndy_ + PeriodEndm_/12)-(Periodmsg/24), digits =2)), "\n")
}
Data.Name$allwoment = 1
DeathEx <- DataPrepareM(Data.Name, PeriodEnd, Period)
options(survey.lonely.psu = "adjust")
dstrat <- survey::svydesign(id = ~ v021, strata = ~ v022, weights = ~ rweight, data = DeathEx)
AGE <- c("15-19", "20-24", "25-29", "30-34", "35-39", "40-44", "45-49")
SEX <- c(rep("FEMALES",7),rep("MALES",7))
WN <- (survey::svyby(~ exposure, by = ~ agegrp+sex, design = dstrat, survey::svytotal))$exposure
asmr <- (survey::svyby(~ death, by = ~ agegrp+sex, denominator = ~ exposure,
design = dstrat, survey::svyratio))[, 3]
deaths <- WN*(asmr/1000)
SE <- (survey::svyby(~ death, by = ~ agegrp+sex, denominator = ~ exposure,
design = dstrat, survey::svyratio))[, 4]
N <- stats::aggregate(DeathEx$exposure, list(DeathEx$agegrp, DeathEx$sex), sum)$x
DEFT <- sqrt(survey::svyby(~ death, by = ~ agegrp+sex, denominator = ~ exposure,
design = dstrat, deff = "replace", survey::svyratio)$DEff)
RSE <- survey::cv(survey::svyby(~ death, by = ~ agegrp+sex, denominator = ~ exposure,
design = dstrat, survey::svyratio))
LCI = asmr - (Z * SE)
LCI[LCI <= 0] = 0
UCI <- asmr + (Z * SE)
RESULTS <- cbind.data.frame(AGE, SEX, round(deaths, 0), round(WN, 0), round(asmr, 3), round(SE, 3), round(N, 0),
round(DEFT, 3), round(RSE, 3), round(LCI, 3), round(UCI, 3), row.names = NULL)
names(RESULTS) <- c("AGE", "SEX", "Deaths","Exposure_years", "ASMR", "SE", "N", "DEFT", "RSE", "LCI", "UCI")
list(RESULTS)
} |
`%p%` <- function(e1, e2) {
paste0(e1, e2)
} |
trinarize.kMeans <- function(vect, nstart=1, iter.max=10, dip.test=TRUE, na.rm=FALSE){
if(!is.numeric(vect))
stop("The input vector must consist of numerical values!")
if (!na.rm && any(is.na(vect)))
stop("Cannot binarize in the presence of NA values!")
else
if (na.rm)
{
vect <- vect[!is.na(vect)]
}
if (any(!is.finite(vect)))
stop("Cannot binarize Inf values!")
if(!is.numeric(nstart))
stop("'nstart' must be numeric!")
if(nstart < 0)
stop("'nstart' must be >= 0!")
if(!is.numeric(iter.max))
stop("'iter.max' must be numeric!")
if(iter.max < 0)
stop("'iter.max' must be >= 0!")
if(length(vect) < 3)
stop("The input vector must have at least 3 entries!")
if(length(unique(vect))==1)
stop("The input vector is constant!")
if (dip.test)
{
p.value <- dip.test(vect)$p.value
}
else
p.value <- as.numeric(NA)
km_res <- kmeans(vect, 3, nstart = nstart, iter.max = iter.max)
cent <- order(km_res$centers)
trinarizeddata <- km_res$cluster
trinarizeddata[km_res$cluster == 1] <- which(cent ==1)
trinarizeddata[km_res$cluster == 2] <- which(cent ==2)
trinarizeddata[km_res$cluster == 3] <- which(cent ==3)
trinarizeddata <- trinarizeddata-1
threshold1 <- (max(vect[trinarizeddata == 0]) + min(vect[trinarizeddata == 1])) / 2
threshold2 <- (max(vect[trinarizeddata == 1]) + min(vect[trinarizeddata == 2])) / 2
return(new("TrinarizationResult",
originalMeasurements = vect,
trinarizedMeasurements = as.integer(trinarizeddata),
threshold1 = threshold1,
threshold2 = threshold2,
p.value = p.value,
method = "k-Means"))
} |
layout_tbl_graph_matrix <- function(graph, circular = FALSE, sort.by = NULL) {
sort.by <- enquo(sort.by)
sort.by <- eval_tidy(sort.by, .N())
if (!is.null(sort.by)) {
pos <- order(order(sort.by))
} else {
pos <- seq_len(gorder(graph))
}
nodes <- new_data_frame(list(x = pos, y = pos))
extra_data <- as_tibble(graph, active = 'nodes')
warn_dropped_vars(nodes, extra_data)
nodes <- cbind(nodes, extra_data[, !names(extra_data) %in% names(nodes), drop = FALSE])
nodes$circular <- FALSE
nodes
} |
context("Complexity meta-features")
test_that("complexity.result", {
aux = complexity(Species ~ ., iris)
dets <- c("C1", "C2", "ClsCoef", "Density", "F1", "F1v", "F2", "F3", "F4",
"Hubs", "L1", "L2", "LSC", "N1", "N2", "N3", "T1", "T2", "T3", "T4")
expect_named(aux, ls.complexity())
expect_equal(aux[dets], complexity(iris[1:4], iris[5], dets))
expect_named(complexity(Species ~ ., iris, ls.complexity()[1:3]),
ls.complexity()[1:3])
})
test_that("complexity.errors",{
expect_error(complexity(iris[1:130, 1:4], iris[5]))
expect_error(complexity(as.matrix(iris[, c(1,2)]), iris$Species))
expect_error(complexity(Species ~ ., iris, features=c("abc", "xdef")))
}) |
modetest<-function(pk,pknum,
h=NULL,N=NULL,Q=NULL,bootnum=NULL,delta=NULL,nsimu=NULL,minim=NULL,
type="boots",kernel="gauss",
n=NULL)
{
run<-1
while (run<=pknum){
curlst<-pk[[run]]
if (type=="boots"){
curh<-h[run]
curmotes<-modetestydin(curlst,curh,N,Q,bootnum,delta,nsimu,minim,kernel)
}
else{
curmotes<-modetestgauss(curlst,n)
}
if (run==1){
if (pknum==1){
moteslist<-curmotes
}
else{
moteslist=list(curmotes)
}
}
else{
moteslist=c(moteslist,list(curmotes))
}
run<-run+1
}
return(moteslist)
} |
round_to_seq <- function(x, nlevels=20, as_factor=FALSE) {
y <- range(x, na.rm = TRUE, finite=TRUE)
y <- seq(y[1], y[2], length.out = nlevels)
y <- sapply(x, function(z) {
if (is.na(z)) return(NA)
y[which.min(abs(y-z))]
})
if (as_factor) as.factor(y)
else y
}
plot_diffnet2 <- function(graph, ...) UseMethod("plot_diffnet2")
plot_diffnet2.diffnet <- function(
graph,
toa,
slice = nslices(graph),
...
) {
if (missing(toa))
toa <- graph$toa
plot_diffnet2.default(
graph = graph$graph[[slice]],
toa = toa,
pers = graph$meta$pers,
...)
}
plot_diffnet2.default <- function(
graph,
toa,
pers = min(toa, na.rm = TRUE):max(toa, na.rm = TRUE),
color.ramp = grDevices::colorRamp(viridisLite::magma(20)),
layout = NULL,
key.width = 0.1,
key.args = list(),
main = "Diffusion dynamics",
add.map = NULL,
diffmap.args = list(kde2d.args=list(n=100)),
diffmap.alpha = .5,
include.white = "first",
vertex.size = "degree",
minmax.relative.size = getOption("diffnet.minmax.relative.size", c(0.01, 0.04)),
no.graph = FALSE,
...) {
oldpar <- graphics::par(no.readonly = TRUE)
on.exit(graphics::par(oldpar))
par(xpd = NA)
igraph.args <- list(...)
nper <- length(pers)
if (length(add.map) && !(add.map %in% c("first", "last")))
stop("When -add.map- is specified it should be either \'first\' or \'last\'.")
if (!length(add.map) & no.graph)
stop("If -no.graph=TRUE- then you should specify some value for -add.map-.")
type_1st <- toa == pers[nper]
type_non <- is.na(toa)
type_adopt <- which(!type_1st & !type_non)
type_1st <- which(type_1st)
type_non <- which(type_non)
t01 <- pers
t01 <- c(t01[1], t01[nper])
col <- color.ramp( (toa - t01[1])/(t01[2] - t01[1]) )
if (ncol(col) < 4)
col <- cbind(col, 255)
col[type_non,] <- 255
col <- rgb(col[,1], col[,2], col[,3], col[,4], maxColorValue = 255)
if (!no.graph && !length(igraph.args$vertex.shape)) {
igraph.args$vertex.shape <- rep("circle", nnodes(graph))
igraph.args$vertex.shape[type_non] <- "square"
}
add_dimnames.mat(graph)
g <- igraph::graph_from_adjacency_matrix(graph, weighted = TRUE)
igraph.args$layout <- if (!length(layout)) igraph::layout_nicely(g)
else if (inherits(layout, "function")) layout(g)
else layout
igraph.args$layout <- igraph::norm_coords(igraph.args$layout)
key.width <- max(0, key.width)
graphics::plot.new()
graphics::plot.window(xlim=c(-1,1 + 5*key.width), ylim=c(-1,1))
graphics::title(main=main)
if (length(add.map)) {
dm <- do.call(diffusionMap.default, c(diffmap.args, list(graph=graph, x=toa,
layout = igraph.args$layout)))
dmlvls <- pretty(range(dm$map$z), diffmap.args$kde2d.args$n)
dmcol <- grDevices::rgb(color.ramp(seq(0,1, length.out = nper*2)), maxColorValue = 255)
if (length(include.white))
if (include.white=="first") dmcol <- c("white", dmcol)
else if (include.white=="last") dmcol <- c(dmcol, "white")
else stop('-include.white- should be either NULL, "first" or "last".')
dmcol <- grDevices::adjustcolor(grDevices::colorRampPalette(dmcol)(length(dmlvls)),
alpha.f=diffmap.alpha)
if (add.map=="first")
graphics::.filled.contour(dm$map$x, dm$map$y, dm$map$z, levels = dmlvls, col=dmcol)
} else dm <- NULL
set_igraph_plotting_defaults("igraph.args")
igraph.args$vertex.size <- rescale_vertex_igraph(
compute_vertex_size(g, vertex.size),
minmax.relative.size = minmax.relative.size
)
igraph.args$vertex.color <- col
if (!no.graph)
do.call(
what = igraph::plot.igraph,
args = c(list(g),igraph.args)
)
if (length(add.map) && (add.map=="last"))
graphics::.filled.contour(dm$map$x, dm$map$y, dm$map$z, levels = dmlvls, col=dmcol)
if (key.width > 0) {
color.palette <- color.ramp(c(0,.5,1))
if (ncol(color.palette) < 4)
color.palette <- cbind(color.palette, 255)
color.palette <- grDevices::rgb(
color.palette[,1], color.palette[,2], color.palette[,3],
color.palette[,4],
maxColorValue = 255)
color.palette <- grDevices::colorRampPalette(color.palette, TRUE)
if (!length(key.args$main)) key.args$main <- "Time of Adoption"
if (!length(key.args$na.col)) key.args$na.col <- "transparent"
if (!length(key.args$na.lab)) key.args$na.lab <- "Non-adopters"
if (!length(key.args$border)) key.args$border <- "transparent"
if (!length(key.args$tick.marks)) {
toaran <- range(toa, na.rm=TRUE)
key.args$tick.marks <-
unique(floor(seq(toaran[1], toaran[2], length.out = 5)))
}
do.call(
what = drawColorKey,
args = c(
list(toa, key.pos = c(1-key.width, 0.975, 0.05, 0.95), nlevels = 100,
color.palette = color.palette(100)),
key.args
)
)
}
invisible(list(
layout = igraph.args$layout,
vertex.color = col,
vertex.size = igraph.args$vertex.size,
vertex.shape = igraph.args$vertex.shape,
diffmap = dm)
)
}
diffusionMap <- function(graph, ...) UseMethod("diffusionMap")
diffmap <- diffusionMap
weighted_var <- function(x,w) {
n <- length(x)
w <- w/sum(w, na.rm=TRUE)*n
m <- sum(x*w/sum(w, na.rm=TRUE), na.rm=TRUE)
sum((x - m)^2*w/(n-1+1e-15), na.rm=TRUE)
}
wvar <- weighted_var
diffusionMap.default <- function(
graph, x, x.adj=round_to_seq, layout=NULL,
jitter.args = list(),
kde2d.args = list(n=100),
sharp.criter=function(x, w) {
wvar(x,w) > (max(x, na.rm=TRUE) - min(x, na.rm=TRUE))^2/12
},...) {
if (length(x.adj)) {
if (!is.function(x.adj)) stop('-x.adj- must be a function')
x <- x.adj(x)
}
if (!length(unlist(dimnames(graph), recursive = TRUE)))
dimnames(graph) <- list(1:nnodes(graph), 1:nnodes(graph))
g <- igraph::graph_from_adjacency_matrix(graph, weighted = TRUE)
coords <- if (is.function(layout)) layout(g)
else if (!length(layout)) igraph::layout_nicely(g)
else if (is.matrix(layout)) layout
if (!length(kde2d.args$h))
kde2d.args$h <- c(MASS::bandwidth.nrd(coords[,1]), MASS::bandwidth.nrd(coords[,2]))
lims <- c(range(coords[,1]), range(coords[,2]))
lvls <- unique(x)
nlvls <- length(unique(x))
Maps <- with(kde2d.args, list(z=array(0, dim=c(n,n,nlvls) )))
Maps$W <- Maps$z
for (i in 1:nlvls) {
if (is.na(lvls[i])) next
dat <- coords[which(x==lvls[i]),,drop=FALSE]
map <- do.call(MASS::kde2d, c(kde2d.args, list(
x = dat[,1], y=dat[,2], lims=lims)))
Maps$W[,,i] <- map$z
Maps$z[,,i] <- map$z*lvls[i]
}
Map <- with(kde2d.args, list(z=matrix(0, ncol=n, nrow=n)))
Map$W <- Map$z
for (i in 1:kde2d.args$n)
for (j in 1:kde2d.args$n) {
if (sharp.criter(lvls,Maps$W[i,j,]) || sum(Maps$W[i,j,]) < 1e-30 ) {
Map$z[i,j] <- sum(Maps$z[i,j,])/(sum(Maps$W[i,j,]) + 1e-15)
} else {
Map$z[i,j] <- sample(lvls, 1, prob=Maps$W[i,j,])
}
}
Map$x <- seq(lims[1], lims[2], length.out = kde2d.args$n)
Map$y <- seq(lims[3], lims[4], length.out = kde2d.args$n)
structure(list(
coords = coords,
map = with(Map, list(x=x,y=y,z=z)),
h = kde2d.args$h,
used_x = x
), class="diffnet_diffmap")
}
diffusionMap.diffnet <- function(graph, slice=nslices(graph), ...) {
with(graph, diffusionMap.default(graph[[slice]], toa, ...))
}
image.diffnet_diffmap <- function(x, ...) {
graphics::image(x$map,...)
}
print.diffnet_diffmap <- function(x, ...) {
cat("An object of class -diffnet_map-\n")
cat(utils::str(x))
cat("Use methods -plot- and -image-.")
}
plot.diffnet_diffmap <- function(x, y=NULL, ...) {
image.diffnet_diffmap(x, ...)
} |
ftm <-
function(d,sampled,k){
size=dim(d)[1]
n=dim(d)[3]
for (i in 1:n){diag(d[,,i])<-0}
unsampled=(1:size)[-sampled]
sampled.matrix=matrix(1,size,size)
sampled.matrix[,unsampled]<-0
sampled.matrix[unsampled,]<-0
unsampled.matrix=(sampled.matrix-1)*(-1)
sampled.knowledge=d
for (i in 1:n)
{
sampled.knowledge[,,i][(1:size)[-sampled[i]],(1:size)[-sampled[i]]]<-0
}
sampled.perception=d-sampled.knowledge
combined.knowledge=matrix(0,size,size)
for (i in 1:n){
combined.knowledge=combined.knowledge+sampled.knowledge[,,i]
}
exact=combined.knowledge*sampled.matrix
exact[exact<2]<-0
exact[exact>=1]<-1
contribution2perception=combined.knowledge*unsampled.matrix
combined.perception=matrix(0,size,size)
for (i in 1:n){
combined.perception=combined.perception+sampled.perception[,,i]
}
active.perception=combined.perception*unsampled.matrix
inactive.perception=combined.perception*sampled.matrix
inactive.perception[inactive.perception<k]<-0
inactive.perception[inactive.perception>=k]<-1
alpha.num=sum((inactive.perception-exact)==1)
alpha.denom=sum(sampled.matrix-exact)
alpha=alpha.num/alpha.denom
beta.num=sum(inactive.perception<exact)
beta.denom=(sum(exact)+0.000001)
beta=beta.num/beta.denom
updated.perception=active.perception+contribution2perception
final.perception=updated.perception
final.perception[final.perception<k]<-0
estimated=exact+final.perception
estimated[estimated>=1]<-1
output=list(estimated,alpha,beta,alpha.num,alpha.denom,beta.num,beta.denom)
names(output)=c("estimatedNetwork","type1Error","type2Error","type1Count","type1Instances","type2Count","type2Instances")
return(output)
} |
`as.ts.permat` <-
function(x, type = "bray", ...)
{
type <- match.arg(type, c("bray", "chisq"))
out <- summary(x)[[type]]
if (!is.ts(out)) {
seqmethods <- sapply(make.commsim(), function(z) make.commsim(z)$isSeq)
seqmethods <- names(seqmethods)[seqmethods]
stop(gettextf("as.ts available only for sequential methods %s",
paste(seqmethods, collapse=", ")))
}
out
} |
bipartition <- function(A, tol = 1e-5, maxit = 100, nonneg = TRUE, samples = 1:ncol(A), seed = NULL, verbose = FALSE, calc_dist = FALSE, diag = TRUE){
if (is(A, "sparseMatrix")) {
A <- as(A, "dgCMatrix")
} else if (canCoerce(A, "matrix")) {
A <- as.matrix(A)
} else stop("'A' was not coercible to a matrix")
if(!is.numeric(seed)) seed <- 0
if(min(samples) == 0) stop("sample indices must be strictly positive")
if(max(samples) > ncol(A)) stop("sample indices must be strictly less than the number of columns in 'A'")
samples <- samples - 1
if(class(A) == "dgCMatrix"){
Rcpp_bipartition_sparse(A, tol, maxit, nonneg, samples, seed, verbose, calc_dist, diag)
} else {
Rcpp_bipartition_dense(A, tol, maxit, nonneg, samples, seed, verbose, calc_dist, diag)
}
} |
if(FALSE)
mahalanobis. <- function(x, center, cov, inverted=FALSE, ...)
{
x <- if(is.vector(x)) matrix(x, ncol=length(x)) else as.matrix(x)
x <- t(sweep(x, 2, center))
setNames(colSums(x * if(inverted) cov%*%x else solve(cov, x, ...)),
rownames(x))
}
mahalanobis <- function(x, center, cov, inverted=FALSE, ...)
{
x <- if(is.vector(x)) matrix(x, ncol=length(x)) else as.matrix(x)
if(!isFALSE(center))
x <- sweep(x, 2L, center)
if(!inverted)
cov <- solve(cov, ...)
setNames(rowSums(x %*% cov * x), rownames(x))
} |
concat.split.compact <- function(data, split.col, sep = ",",
drop = FALSE, fixed = TRUE, ...) {
.Deprecated("cSplit")
cSplit(indt = data, splitCols = split.col, sep = sep,
drop = drop, fixed = fixed, direction = "wide", ...)
}
NULL
cSplit_e <- concat.split.expanded <- function(data, split.col, sep = ",", mode = NULL,
type = "numeric", drop = FALSE,
fixed = TRUE, fill = NA) {
if (is.numeric(split.col)) split.col <- Names(data, split.col)
if (!is.character(data[[split.col]])) a <- as.character(data[[split.col]])
else a <- data[[split.col]]
if (is.null(mode)) mode = "binary"
b <- strsplit(a, sep, fixed = fixed)
b <- lapply(b, trim)
temp1 <- switch(
type,
character = {
temp1 <- charMat(b, fill = fill, mode = mode)
colnames(temp1) <- paste(split.col, colnames(temp1), sep = "_")
temp1
},
numeric = {
nchars <- max(nchar(unlist(b, use.names = FALSE)))
temp1 <- numMat(b, fill = fill, mode = mode)
colnames(temp1) <- paste(split.col, .pad(seq_len(ncol(temp1))), sep = "_")
temp1
},
stop("'type' must be either 'character' or 'numeric'"))
if (isTRUE(drop)) {
if (is.data.table(data)) {
cbind(data, temp1)[, (split.col) := NULL][]
} else {
cbind(data[othernames(data, split.col)], temp1)
}
}
else cbind(data, temp1)
}
NULL
cSplit_l <- concat.split.list <- function(data, split.col, sep = ",",
drop = FALSE, fixed = FALSE) {
if (is.numeric(split.col)) split.col <- Names(data, split.col)
a <- .stripWhite(data[[split.col]], sep)
varname <- paste(split.col, "list", sep="_")
b <- strsplit(a, sep, fixed = fixed)
if (suppressWarnings(is.na(try(max(as.numeric(na.omit(unlist(b)))))))) {
data[[varname]] <- I(b)
} else if (!is.na(try(max(as.numeric(na.omit(unlist(b))))))) {
data[[varname]] <- I(lapply(b, as.numeric))
}
if (isTRUE(drop)) {
if (is.data.table(data)) {
data[, (split.col) := NULL][]
} else {
data[othernames(data, split.col)]
}
}
else data
}
NULL
concat.split <- function(data, split.col, sep = ",", structure = "compact",
mode = NULL, type = NULL, drop = FALSE, fixed = FALSE,
fill = NA, ...) {
M1 <- paste(
c("", "'mode' supplied but ignored.", "'mode' setting only applicable",
"when structure = 'expanded'"), collapse = " ")
M2 <- paste(
c("", "'type' supplied but ignored.", "'type' setting only applicable",
"when structure = 'expanded'"), collapse = " ")
temp <- switch(
structure,
compact = {
if (!is.null(mode)) warning(M1)
if (!is.null(type)) warning(M2)
cSplit(indt = data, splitCols = split.col,
sep = sep, drop = drop, fixed = fixed)
},
list = {
if (!is.null(mode)) warning(M1)
if (!is.null(type)) warning(M2)
cSplit_l(data = data, split.col = split.col,
sep = sep, drop = drop, fixed = fixed)
},
expanded = {
cSplit_e(data = data, split.col = split.col,
sep = sep, mode = mode, type = type,
drop = drop, fixed = fixed, fill = fill)
},
stop("'structure' must be either 'compact', 'expanded', or 'list'"))
temp
}
NULL
concat.split.multiple <- function(data, split.cols, seps = ",",
direction = "wide", ...) {
.Deprecated("cSplit")
message("This function is deprecated. Use `cSplit` instead.")
cSplit(indt = data, splitCols = split.cols,
sep = seps, direction = direction, ...)
}
NULL |
extract_vars = function(f) {
assert_formula(f)
res = named_list(c("lhs", "rhs"))
res$lhs = if (length(f) == 2L) character(0L) else all.vars(f[[2L]])
res$rhs = all.vars(f[[length(f)]])
res
} |
NULL
which_ttf2pt1 <- function() {
if (.Platform$OS.type == "unix") {
bin <- "ttf2pt1"
binpath <- file.path(inst_path(), "exec", .Platform$r_arch, bin)
if (!file.exists(binpath))
binpath <- file.path(inst_path(), "exec", "i386", bin)
} else if (.Platform$OS.type == "windows") {
bin <- "ttf2pt1.exe"
binpath <- file.path(inst_path(), "exec", bin)
} else {
stop("Unknown platform: ", .Platform$OS.type)
}
if (file.exists(binpath))
return(binpath)
binpath <- Sys.which(bin)
if (binpath == "")
stop(bin, " not found in path.")
else
return(binpath)
}
inst_path <- function() {
envname <- environmentName(environment(inst_path))
if (envname == "Rttf2pt1") {
system.file(package = "Rttf2pt1")
} else {
srcfile <- attr(attr(inst_path, "srcref"), "srcfile")
file.path(dirname(dirname(srcfile$filename)), "inst")
}
} |
ttest.func <-
function(x,y,s0=0, sd=NULL) {
n1 <- sum(y==1)
n2 <- sum(y==2)
p <- nrow(x)
m1 <- rowMeans(x[,y==1,drop=F])
m2 <- rowMeans(x[,y==2,drop=F])
if(is.null(sd)) {
sd <- sqrt( ((n2-1) * varr(x[, y==2], meanx=m2) + (n1-1) * varr(x[, y==1], meanx=m1) )*(1/n1+1/n2)/(n1+n2-2) )
}
numer <- m2 - m1
dif.obs <- (numer)/(sd + s0)
return(list(tt=dif.obs,numer=numer, sd=sd))
} |
wy=function(y,x,d,wx=0.1,wy_seq=seq(0.1,1,by=.1),wh=1.5,
B=500,xdensity="normal",method="FM"){
space="pdf"
if(wy_seq[1]==0){
stop("Error!: hy/st2 Sequence should not start with zero")
}
if(method!="FM" || method!="CM"){
stop("Error!: method should be either 'FM' or 'CM'")
}
hy=wy_seq
dj=matrix(0,nrow=B,ncol=1)
dist.r=matrix(0,nrow=length(hy),ncol=1)
y=as.matrix(y)
pb <- txtProgressBar(min = 0, max = length(hy), style = 3)
p=ncol(x)
n=nrow(x)
for(j in 1:length(hy)){
Hy=hy[j]
xy.dr =itdr(y, x, d,wx,Hy,wh,space="pdf",xdensity,method)
s_d = xy.dr$eta_hat
dataframe=data.frame(y,x)
boost.df=dataframe[sample(nrow(x),n,replace = TRUE),]
for(jj in 1:B){
boost.df=dataframe[sample(nrow(x),n,replace = TRUE),]
y.boostrap=boost.df[,1]
x.boostrap=boost.df[,-c(1)]
xy.dr =itdr(y.boostrap, x.boostrap, d,wx,Hy,wh,space="pdf",xdensity,method)
s_dj = xy.dr$eta_hat
dist.dj=dsp(s_dj,s_d)
dj[jj]=dist.dj$r
}
dist.r[j,1]=mean(dj)
setTxtProgressBar(pb, j)
}
close(pb)
disttab=data.frame(hy=wy_seq,dbar=dist.r)
hy.hat=wy_seq[which.min(dist.r)]
list(dis_wy=disttab,wy.hat=hy.hat)
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
warning = F,
fig.align = "center"
)
devtools::load_all()
library(tidyverse)
library(tibbletime)
tidyverse_cran_downloads
tidyverse_cran_downloads_anomalized <- tidyverse_cran_downloads %>%
time_decompose(count, merge = TRUE) %>%
anomalize(remainder) %>%
time_recompose()
tidyverse_cran_downloads_anomalized %>% glimpse()
tidyverse_cran_downloads_anomalized %>%
plot_anomalies(ncol = 3, alpha_dots = 0.25)
lubridate_daily_downloads <- tidyverse_cran_downloads %>%
filter(package == "lubridate") %>%
ungroup()
lubridate_daily_downloads
lubridate_daily_downloads_anomalized <- lubridate_daily_downloads %>%
time_decompose(count) %>%
anomalize(remainder) %>%
time_recompose()
lubridate_daily_downloads_anomalized %>% glimpse()
p1 <- lubridate_daily_downloads_anomalized %>%
plot_anomaly_decomposition() +
ggtitle("Freq/Trend = 'auto'")
p1
get_time_scale_template()
p2 <- lubridate_daily_downloads %>%
time_decompose(count,
frequency = "auto",
trend = "2 weeks") %>%
anomalize(remainder) %>%
plot_anomaly_decomposition() +
ggtitle("Trend = 2 Weeks (Local)")
p1
p2
time_scale_template() %>%
mutate(trend = ifelse(time_scale == "day", "2 weeks", trend)) %>%
set_time_scale_template()
get_time_scale_template()
p3 <- lubridate_daily_downloads %>%
time_decompose(count) %>%
anomalize(remainder) %>%
plot_anomaly_decomposition() +
ggtitle("Trend = 2 Weeks (Global)")
p3
time_scale_template() %>%
set_time_scale_template()
get_time_scale_template()
p4 <- lubridate_daily_downloads %>%
time_decompose(count) %>%
anomalize(remainder, alpha = 0.05, max_anoms = 0.2) %>%
time_recompose() %>%
plot_anomalies(time_recomposed = TRUE) +
ggtitle("alpha = 0.05")
p4
p5 <- lubridate_daily_downloads %>%
time_decompose(count) %>%
anomalize(remainder, alpha = 0.025, max_anoms = 0.2) %>%
time_recompose() %>%
plot_anomalies(time_recomposed = TRUE) +
ggtitle("alpha = 0.025")
p4
p5
p6 <- lubridate_daily_downloads %>%
time_decompose(count) %>%
anomalize(remainder, alpha = 0.3, max_anoms = 0.2) %>%
time_recompose() %>%
plot_anomalies(time_recomposed = TRUE) +
ggtitle("20% Anomalies")
p7 <- lubridate_daily_downloads %>%
time_decompose(count) %>%
anomalize(remainder, alpha = 0.3, max_anoms = 0.05) %>%
time_recompose() %>%
plot_anomalies(time_recomposed = TRUE) +
ggtitle("5% Anomalies")
p6
p7 |
require("dplyr", warn.conflicts = FALSE)
require('base', warn.conflicts = FALSE) |
context("hypothesis tests work with default arguments for different kinds of mainlm argument")
htest <- c("anscombe", "bamset", "bickel",
"breusch_pagan", "carapeto_holt", "cook_weisberg", "diblasi_bowman", "evans_king", "glejser",
"goldfeld_quandt", "harrison_mccabe", "harvey", "honda", "horn",
"li_yao", "rackauskas_zuokas", "simonoff_tsai",
"szroeter", "verbyla", "white_lm", "wilcox_keselman", "zhou_etal")
test_that("simple linear regression works with default arguments and
gives same p-value for lm or list mainlm argument", {
skip_on_cran()
carslm <- lm(dist ~ speed, data = cars)
carslist <- list("y" = cars$dist, "X" = cbind(1, cars$speed))
carslmpvals <- unlist(lapply(htest, function(h) do.call(what = h,
args = list("mainlm" = carslm))$p.value))
carslistpvals <- unlist(lapply(htest, function(h) do.call(what = h,
args = list("mainlm" = carslist))$p.value))
lapply(carslmpvals, function(x) expect_true(is.btwn01(x)))
expect_equal(carslmpvals, carslistpvals)
})
test_that("simple linear regression through origin works with default
arguments and gives same p-value for lm or list mainlm
argument", {
skip_on_cran()
carslm0 <- lm(dist ~ 0 + speed, data = cars)
carslist0 <- list("y" = cars$dist, "X" = as.matrix(cars$speed))
carslm0pvals <- unlist(lapply(htest, function(h) do.call(what = h,
args = list("mainlm" = carslm0))$p.value))
carslist0pvals <- unlist(lapply(htest, function(h) do.call(what = h,
args = list("mainlm" = carslist0))$p.value))
lapply(carslm0pvals, function(x) expect_true(is.btwn01(x)))
expect_equal(carslm0pvals, carslist0pvals)
})
test_that("lm (list) with NA's works with default arguments", {
skip_on_cran()
ChickWeight2 <- rbind(ChickWeight, NA)
chicklistNA <- list("y" = ChickWeight2$weight, "X" = cbind(1,
ChickWeight2$Time))
lapply(htest, function(h) expect_true(is.btwn01(do.call(what = h,
args = list("mainlm" = chicklistNA))$p.value)))
})
test_that("multiple linear regression works with default arguments and
gives same p-value for lm or list mainlm argument", {
skip_on_cran()
chicklm <- lm(weight ~ Time + Diet, data = ChickWeight)
chicklist <- list("y" = ChickWeight$weight,
"X" = stats::model.matrix(chicklm))
chicklmpvals <- unlist(lapply(htest, function(h) do.call(what = h,
args = list("mainlm" = chicklm))$p.value))
chicklistpvals <- unlist(lapply(htest, function(h) do.call(what = h,
args = list("mainlm" = chicklist))$p.value))
lapply(chicklmpvals, function(x) expect_true(is.btwn01(x)))
expect_equal(chicklmpvals, chicklistpvals)
})
htest_nosimonoff <- setdiff(htest, "simonoff_tsai")
test_that("large multiple linear regression (BostonHousing) works with default arguments", {
skip_on_cran()
bostonlm <- lm(medv ~ crim + zn + indus + chas + nox + rm +
age + dis + rad + tax + ptratio + b + lstat, data = BostonHousing)
bostonlmpvals <- unlist(lapply(htest_nosimonoff, function(h) do.call(what = h,
args = list("mainlm" = bostonlm))$p.value))
lapply(bostonlmpvals, function(x) expect_true(is.btwn01(x)))
})
test_that("multiple linear regression through origin works with default
arguments and gives same p-value for lm or list mainlm
argument", {
skip_on_cran()
chicklm0 <- lm(weight ~ 0 + Time + Diet, data = ChickWeight)
chicklist0 <- list("y" = ChickWeight$weight,
"X" = stats::model.matrix(chicklm0))
chicklm0pvals <- unlist(lapply(htest, function(h) do.call(what = h,
args = list("mainlm" = chicklm0))$p.value))
chicklist0pvals <- unlist(lapply(htest, function(h) do.call(what = h,
args = list("mainlm" = chicklist0))$p.value))
lapply(chicklm0pvals, function(x) expect_true(is.btwn01(x)))
expect_equal(chicklm0pvals, chicklist0pvals)
})
test_that("multiple linear regression with random data in vectors rather than
data frames works with default arguments and
gives same p-value for lm or list mainlm argument", {
skip_on_cran()
myn <- 10
myp <- 3
myX <- matrix(data = runif(myn * myp),
nrow = myn, ncol = myp)
myy <- rnorm(myn, mean = rowMeans(myX), sd = rowMeans(myX))
mylm <- lm(myy ~ myX)
mylist <- list("y" = myy, "X" = cbind(1, myX))
mylmpvals <- unlist(lapply(htest_nosimonoff, function(h) do.call(what = h,
args = list("mainlm" = mylm))$p.value))
mylistpvals <- unlist(lapply(htest_nosimonoff, function(h) do.call(what = h,
args = list("mainlm" = mylist))$p.value))
lapply(mylmpvals, function(x) expect_true(is.btwn01(x)))
expect_equal(mylmpvals, mylistpvals)
}) |
rb <-
function(str) mark(str, F, '()') |
test_that("NHL - Get NHL draft", {
skip_on_cran()
x <- nhl_draft()
cols <- c(
"year",
"round",
"pick_overall",
"pick_in_round",
"team_id",
"team_name",
"team_link",
"prospect_id",
"prospect_full_name",
"prospect_link"
)
expect_equal(colnames(x), cols)
expect_s3_class(x, 'data.frame')
}) |
NULL
"SCP16" |
get_linelist <- function(clean = TRUE, report_delay_only = FALSE) {
deprecate_warn(
when = "0.9.0",
what = "covidregionaldata::get_linelist()",
details = c(
"Linelist no longer accessible through this package.",
"The line list is now hosted at: https://global.health/"
)
)
tmpdir <- tempdir()
linelist <- try(csv_reader(file.path(tmpdir, "latestdata.csv")))
if (any(class(linelist) %in% "try-error")) {
message("Downloading linelist")
url <- "https://github.com/beoutbreakprepared/nCoV2019/raw/master/latest_data/latestdata.tar.gz"
download.file(url, destfile = file.path(tmpdir, "tmp.tar.gz"))
untar(file.path(tmpdir, "tmp.tar.gz"),
files = "latestdata.csv", exdir = tmpdir
)
linelist <- try(csv_reader(file.path(tmpdir, "latestdata.csv")))
if (any(class(linelist) %in% "try-error")) {
if (nrow(linelist) == 1) {
stop("Problem reading linelist")
} else {
stop("Problem getting linelist source")
}
}
}
if (clean | report_delay_only) {
linelist <- linelist %>%
mutate(
date_confirm = suppressWarnings(lubridate::dmy(.data$date_confirmation)),
date_onset = suppressWarnings(lubridate::dmy(.data$date_onset_symptoms)),
date_admission_hospital =
suppressWarnings(lubridate::dmy(.data$date_admission_hospital)),
date_death_or_discharge =
suppressWarnings(lubridate::dmy(.data$date_death_or_discharge)),
death = ifelse(.data$outcome %in% c(
"dead", "death", "died",
"deceases", "Dead", "Death",
"Died", "Deceased"
), TRUE, FALSE),
delay_onset_report =
as.integer(as.Date(.data$date_confirm) - as.Date(.data$date_onset)),
delay_onset_admission =
as.integer(as.Date(.data$date_admission_hospital) -
as.Date(.data$date_onset)),
delay_onset_death = ifelse(.data$death == TRUE,
as.integer(as.Date(.data$date_death_or_discharge) -
as.Date(.data$date_onset)),
NA
)
) %>%
select(
id = .data$ID, .data$country, .data$death,
.data$date_onset, .data$date_confirm,
.data$date_admission_hospital, .data$date_death_or_discharge,
.data$delay_onset_report, .data$delay_onset_admission,
.data$delay_onset_death
)
}
if (report_delay_only) {
linelist <- dplyr::filter(
linelist,
!is.na(.data$delay_onset_report)
) %>%
dplyr::select(
.data$id, .data$country,
.data$date_onset, .data$delay_onset_report
)
}
message("Note: This line list covers January to June 2020. We will update when a new data source becomes available.")
return(linelist)
} |
context("IRI computation")
test_that("First test", {
profile <- rnorm(10000)
iri <- CalculateIRIperSegments(profile, IRI_COEF_100, 20)
expect_equal(length(iri), 50)
}) |
logregWBY <- WBYlogreg <- function(x0,y, intercept=1, const=0.5,kmax=1000,maxhalf=10)
{
sigmamin=0.0001
if (!is.numeric(y))
y <- as.numeric(y)
if (!is.null(dim(y))) {
if (ncol(y) != 1)
stop("y is not onedimensional")
y <- as.vector(y)
}
n <- length(y)
x0<-as.matrix(x0)
if (nrow(x0) != n)
stop("Number of observations in x and y not equal")
na.x <- !is.finite(rowSums(x0))
na.y <- !is.finite(y)
ok <- !(na.x | na.y)
if (!all(ok)) {
x0 <- x0[ok, , drop = FALSE]
y <- y[ok]
}
n <- nrow(x0)
if (n == 0)
stop("All observations have missing values!")
p<-ncol(x0)
family <- binomial()
p<-dim(x0)[2]
zz<-rep(0,p)
for (i in 1:p)
{zz[i]<-sum((x0[,i]==0)|(x0[,i]==1))}
tt<-which(zz!=n)
p1<-length(tt)
x0=as.matrix(x0,n,p)
x00<-x0[,tt]
if(p1==1)
{rdx<-abs(x00-median(x00))/mad(x00)
wrd<-(rdx<=qnorm(.9875))}
if(p1>1)
{
mcdx <- robustbase::covMcd(x00,alpha=.75)
rdx <- mahalanobis(x00,center=mcdx$center,cov=mcdx$cov)
vc<-qchisq(0.975,p)
wrd<-(rdx<=vc)}
if(p1==0)
{wrd=1:n}
if (intercept==1)
{out<-glm(y[wrd]~x0[wrd,], family = family)
x <- cbind(Intercept = 1, x0)}
if (intercept==0)
{out<-glm(y[wrd]~x0[wrd,]-1, family = family)
x<-x0}
gstart<-out$coeff
p=ncol(x)
sigmastart=1/sqrt(sum(gstart^2))
xistart=gstart*sigmastart
x0v=x0
xv=x
nv=n
yv=y
x0=x0[wrd,]
y=y[wrd]
x=x[wrd,]
n=sum(wrd)
stscores=x %*% xistart
oldobj=mean(phiBY3(stscores/sigmastart,y,const))
kstep=1
jhalf=1
while (( kstep < kmax) & (jhalf<maxhalf))
{
optimsig=optimize(sigmaBY3,lower=0,upper=10^3,y=y,s=stscores,c3=const)
sigma1=optimsig$minimum
if (sigma1<sigmamin)
{
print("Explosion");kstep=kmax
}
else
{
gamma1=xistart/sigma1
scores=stscores/sigma1
newobj=mean(phiBY3(scores,y,const))
oldobj=newobj
gradBY3=apply((derphiBY3(scores,y,const)%*%t(rep(1,p)))*x,2,mean)
h=-gradBY3+(sum(gradBY3 * xistart) *xistart)
finalstep=h/sqrt(sum(h^2))
xi1=xistart+finalstep
xi1=xi1/(sum(xi1^2))
scores1=(x%*%xi1)/sigma1
newobj=mean(phiBY3(scores1,y,const))
hstep=1
jhalf=1
while ((jhalf <=maxhalf) & (newobj>oldobj))
{
hstep=hstep/2
xi1=xistart+finalstep*hstep
xi1=xi1/sqrt(sum(xi1^2))
scores1=x%*%xi1/sigma1
newobj=mean(phiBY3(scores1,y,const))
jhalf=jhalf+1
}
if ((jhalf==maxhalf+1) & (newobj>oldobj))
{
} else {
jhalf=1
xistart=xi1
oldobj=newobj
stscores=x%*% xi1
kstep=kstep+1
}
}
}
if (kstep == kmax)
{print("No convergence")
resultat=list(convergence=F,objective=0,coef=t(rep(NA,p)))
resultat}
else
{
gammaest=xistart/sigma1
stander=sterby3(x,y,const,gammaest)
fitted.linear<- xv%*%gammaest
fitted.linear<-pmin(fitted.linear,1e2)
fitted.values<-exp(fitted.linear)/(1+exp(fitted.linear))
residual.deviances<-sign(yv-fitted.values)*sqrt(-2*(yv*log(fitted.values)+(1-yv)*log(1-fitted.values)))
result <-list(convergence=TRUE,objective=oldobj, coefficients=gammaest, standard.deviation=stander,fitted.values=t(fitted.values), residual.deviances= t(residual.deviances))
result
}
}
phiBY3=function(s,y,c3)
{
s=as.double(s)
dev=log(1+exp(-abs(s)))+abs(s)*((y-0.5)*s<0)
res=rhoBY3(dev,c3)+GBY3Fs(s,c3)+GBY3Fsm(s,c3)
res
}
rhoBY3 <- function(t,c3)
{
(t*exp(-sqrt(c3))*as.numeric(t <= c3))+
(((exp(-sqrt(c3))*(2+(2*sqrt(c3))+c3))-(2*exp(-sqrt(t))*(1+sqrt(t))))*as.numeric(t >c3))
}
psiBY3 <- function(t,c3)
{
(exp(-sqrt(c3))*as.numeric(t <= c3))+(exp(-sqrt(t))*as.numeric(t >c3))
}
derpsiBY3 <- function(t,c3)
{
(0*as.numeric(t <= c3))+(-(exp(-sqrt(t))/(2*sqrt(t)))*as.numeric(t >c3))
}
sigmaBY3<-function(sigma,s,y,c3)
{
mean(phiBY3(s/sigma,y,c3))
}
derphiBY3=function(s,y,c3)
{
Fs= exp(-(log(1+exp(-abs(s)))+abs(s)*(s<0)))
ds=Fs*(1-Fs)
dev=log(1+exp(-abs(s)))+abs(s)*((y-0.5)*s<0)
Gprim1=log(1+exp(-abs(s)))+abs(s)*(s<0)
Gprim2=log(1+exp(-abs(s)))+abs(s)*(s>0)
-psiBY3(dev,c3)*(y-Fs)+((psiBY3(Gprim1,c3)-psiBY3(Gprim2,c3))*ds)
}
der2phiBY3=function(s,y,c3)
{
s=as.double(s)
Fs= exp(-(log(1+exp(-abs(s)))+abs(s)*(s<0)))
ds=Fs*(1-Fs)
dev=log(1+exp(-abs(s)))+abs(s)*((y-0.5)*s<0)
Gprim1=log(1+exp(-abs(s)))+abs(s)*(s<0)
Gprim2=log(1+exp(-abs(s)))+abs(s)*(s>0)
der2=(derpsiBY3(dev,c3)*(Fs-y)^2)+(ds*psiBY3(dev,c3))
der2=der2+(ds*(1-2*Fs)*(psiBY3(Gprim1,c3)-psiBY3(Gprim2,c3)))
der2=der2-(ds*((derpsiBY3(Gprim1,c3)*(1-Fs))+(derpsiBY3(Gprim2,c3)*Fs)))
der2
}
GBY3Fs <- function(s,c3)
{
Fs= exp(-(log(1+exp(-abs(s)))+abs(s)*(s<0)))
resGinf=exp(0.25)*sqrt(pi)*(pnorm(sqrt(2)*(0.5+sqrt(-log(Fs))))-1)
resGinf=(resGinf+(Fs*exp(-sqrt(-log(Fs)))))*as.numeric(s <= -log(exp(c3)-1))
resGsup=((Fs*exp(-sqrt(c3)))+(exp(0.25)*sqrt(pi)*(pnorm(sqrt(2)*(0.5+sqrt(c3)))-1)))*as.numeric(s > -log(exp(c3)-1))
resG=resGinf+resGsup
resG
}
GBY3Fsm <- function(s,c3)
{
Fsm=exp(-(log(1+exp(-abs(s)))+abs(s)*(s>0)))
resGinf=exp(0.25)*sqrt(pi)*(pnorm(sqrt(2)*(0.5+sqrt(-log(Fsm))))-1)
resGinf=(resGinf+(Fsm*exp(-sqrt(-log(Fsm)))))*as.numeric(s >= log(exp(c3)-1))
resGsup=((Fsm*exp(-sqrt(c3)))+(exp(0.25)*sqrt(pi)*(pnorm(sqrt(2)*(0.5+sqrt(c3)))-1)))*as.numeric(s < log(exp(c3)-1))
resG=resGinf+resGsup
resG
}
sterby3 <- function(z,y,const,estim)
{
n=dim(z)[[1]]
p=dim(z)[[2]]
argum=z %*% estim
matM=matrix(data=0,nrow=p,ncol=p)
for (i in 1:n)
{
matM=matM+(der2phiBY3(argum[i],y[i],const) * (z[i,] %*% t(z[i,])))
}
matM=matM/n
matMinv=solve(matM)
IFsquar=matrix(data=0,nrow=p,ncol=p)
for (i in 1:n)
{
IFsquar=IFsquar+((derphiBY3(argum[i],y[i],const))^2 * (z[i,] %*% t(z[i,])))
}
IFsquar=IFsquar/n
asvBY=matMinv %*% IFsquar %*% t(matMinv)
sqrt(diag(asvBY))/sqrt(n)
} |
print.stslist.rep <- function(x, ...) {
criterion <- attr(x,"criterion")
nbseq <- attr(x,"nbseq")
quality <- attr(x,"Quality")
cat("\n [>] criterion:",criterion,"\n")
cat(" [>]", nbseq,"sequence(s) in the original data set\n")
cat(" [>]", nrow(x),"representative sequence(s)\n")
cat(" [>] overall quality:", round(quality*100,2),"\n\n")
NextMethod(x,...)
}
summary.stslist.rep <- function(object, ...) {
criterion <- attr(object,"criterion")
nbseq <- attr(object,"nbseq")
quality <- attr(object,"Quality")
cat("\n [>] criterion:",criterion,"\n")
cat(" [>]", nbseq,"sequence(s) in the original data set\n")
cat(" [>]", nrow(object),"representative sequences\n")
cat(" [>] overall quality:", quality,"\n")
cat(" [>] statistics for the representative set:\n\n")
print(attr(object,"Statistics"), digits=3, ...)
cat("\n na: number of assigned objects\n")
cat(" nb: number of objects in the neighborhood\n")
cat(" SD: sum of the na distances to the representative\n")
cat(" MD: mean of the na distances to the representative\n")
cat(" DC: sum of the na distances to the center of the complete set\n")
cat(" V: discrepancy of the subset\n")
cat(" Q: quality of the representative\n")
} |
lands.cond.t.prop.density.polar <-
function (theta, nu, zeta)
{
exp((nu - 1) * log(cos(theta)) - (nu/2) * log(nu) + (1 +
nu) * zeta * sin(theta))
} |
print.mave.dim<-function(x,...){
cat('\nCall:\n',paste(deparse(x$call),sep="\n",collapse="\n"),"\n\n",sep="")
arg='central space'
if(substr(x$method,1,2)!='CS') arg='central mean space'
p=length(x$dir)
pp=1
cv = c(x$cv0,x$cv)
idx = which(!is.infinite(cv)) - 1
cat('The cross-validation is run on dimensions of',idx,'\n')
while(pp<=length(idx)){
np=min(pp+10,length(idx))
cat('Dimension\t')
for(i in pp:np) cat(idx[i],'\t')
cat('\n')
cat('CV-value\t')
for(i in pp:np) cat(round(cv[idx[i]+1],2),'\t')
cat('\n')
pp=np+1
}
cat('\n')
d=which.min(cv)-1
cat('The selected dimension of ',arg,' is ',d)
cat('\n\n')
} |
calc.pvalue <- function(x, var, test=c(upper=FALSE,lower=FALSE,twoSided=TRUE)) {
a <- pnorm(x/sqrt(var))
cbind(if(test['upper']) 1 - a,
if(test['lower']) a,
if(test['twoSided']) 2 * ifelse(a > 0.5, 1 - a, a))
} |
set_threshold <- function(x,
col_name, out_name = NULL,
threshold, case = '>='){
check_class(argument = x, target = 'data.frame', arg_name = 'x')
check_class(argument = x[ , 1], target = c('Date', 'POSIXct') , arg_name = 'x[ , 1]')
check_class(argument = c( as.matrix( x[ , -1] ) ),
target = c('numeric') , arg_name = 'x[ , -1]')
check_class(argument = col_name, target = 'character', arg_name = 'col_name')
check_string(argument = col_name,
target = colnames(x)[-1],
arg_name = 'col_name')
if( !is.null(out_name) ){
check_class(argument = out_name, target = 'character', arg_name = 'out_name')
guess <- which( match(x = out_name, table = colnames(x) ) >= 1 )
if( length(guess) != 0){
error_message <-
paste0('Please check for ', out_name,
' argument. The following strins are forbidden: ',
paste( colnames(x) , collapse = ', '), '.')
stop( error_message, call. = FALSE )
}
check_cross(ref_arg = col_name,
eval_arg = out_name,
arg_names = c('col_name', 'out_name') )
}
n_it <- length(col_name)
check_class(argument = threshold, target = c('numeric'), arg_name = 'threshold')
if( n_it > 1 & length(threshold == 1) ){
threshold <- rep(threshold, n_it)
} else {
check_cross(ref_arg = col_name, eval_arg = threshold,
arg_names = c('col_name', 'threshold') )
}
check_class(argument = case, target = c('character'), arg_name = 'case')
if( n_it > 1 & length(case == 1) ){
case <- rep(case, n_it)
} else {
check_cross(ref_arg = col_name, eval_arg = case,
arg_names = c('col_name', 'case') )
}
mat_target <-
x[ , col_name, drop = FALSE] %>%
as.matrix()
mat_thr <- mat_target
for(i in 1:n_it){
if(case[i] == '>='){
pos <- which(mat_target[ , i] >= threshold[i])
mat_thr[pos, i] <- NA_real_
} else if(case[i] == '<='){
pos <- which(mat_target[ , i] <= threshold[i])
mat_thr[pos, i] <- NA_real_
} else{
stop( paste0('Only >= and <= are allowed for case argument!'),
call. = FALSE)
}
}
if( !is.null(out_name) ){
colnames(mat_thr) <- out_name
df_out <- x
df_out[ , out_name] <- mat_thr
} else {
df_out <- x
df_out[ , col_name] <- mat_thr
}
df_out[ , -1] <- as.matrix( df_out[ , -1] )
return(df_out)
} |
library(ggplot2)
receive_point <- function(y) {
geom_point(
mapping = aes(shape = shape),
data = data.frame(
x = 0,
y = y,
shape = "receive"
),
size = 4
)
}
return_point <- function(x, y) {
geom_point(
mapping = aes(shape = shape),
data = data.frame(
x = x,
y = y,
shape = "return"
),
size = 3
)
}
working_line <- function(x, y) {
geom_line(
mapping = aes(group = y, linetype = linetype),
data = data.frame(
x = x,
y = y,
linetype = "working"
),
size = 2
)
}
waiting_line <- function(x, y, group = y) {
geom_line(
mapping = aes(group = group, linetype = linetype),
data = data.frame(
x = x,
y = y,
linetype = "waiting",
group = group
)
)
}
save_image <- function(p, file, height = 4, width = 6, ...) {
p <- p + theme(aspect.ratio = 100/150)
ggsave(file, p, height = height, width = NA, ...)
}
route_type_guide <- function(
future_values = NULL,
plumber_values,
promise_values = NULL
) {
values <- c()
values[plumber_values] <- "
labels <- "plumber"
breaks <- plumber_values[1]
if (!is.null(future_values)) {
values[future_values] <- "
labels <- c("plumber + future", labels)
breaks <- c(future_values[1], breaks)
}
if (!is.null(promise_values)) {
values[promise_values] <- "
labels <- c("plumber + future_promise", labels)
breaks <- c(promise_values[1], breaks)
}
scale_color_manual(
name = "Route Type",
values = values,
labels = labels,
breaks = breaks,
guide = guide_legend(
order = 1,
override.aes = list(
size = 1
)
)
)
}
status_guide <- function(waiting = TRUE, promise = FALSE) {
scale_linetype_manual(
name = "Status",
values = c(
if (waiting) c(waiting = "dashed"),
working = "solid"
),
breaks = c(if (waiting) "waiting", "working"),
labels = if (promise) c("Waiting in promise", "Working in future") else c(if (waiting) "Waiting", "Working"),
guide = guide_legend(
order = 3,
override.aes = list(
linetype = c(if (waiting) "dashed", "solid"),
size = c(if (waiting) 0.5, 1.5)
)
)
)
}
constants <-
list(
labs(
x = "time (s)",
y = NULL
),
xlim(0, 20),
scale_shape_manual(
name = "Execution",
values = c(
"startend" = "X",
"receive" = "|",
"return" = "circle"
),
breaks = c("receive", "startend", "return"),
labels = c("Receive", "Process", "Respond"),
guide = guide_legend(order = 2)
),
status_guide()
)
p <-
ggplot(mapping = aes(x = x, y = y)) +
geom_point(
data = data.frame(x = c(0, 0, 10, 10), y = c("a", "b", "b", "c")),
color = "transparent"
) +
scale_y_discrete(
limits = rev(letters[1:3]),
labels = c("/fast", "/slow", "/fast")
) +
constants
save_image(p, "images/timing-blank.png")
p <-
ggplot(mapping = aes(x = x, y = y, color = y)) +
receive_point(letters[1:4]) +
return_point(
c(0, 10, 20, 20),
letters[1:4]
) +
working_line(
x = c(0, 10, 10, 20),
y = c("b", "b", "c", "c")
) +
waiting_line(
x = c(0, 10, 0, 20),
y = c("c", "c", "d", "d")
) +
route_type_guide(NULL, letters[1:4]) +
scale_y_discrete(
limits = rev(letters[1:4]),
labels = c("/fast/4", "/slow/3", "/slow/2", "/fast/1")
) +
constants
save_image(p, "images/timing-plumber.png", width = 5.5)
p <-
ggplot(mapping = aes(x = x, y = y, color = y)) +
receive_point(letters[1:4]) +
return_point(
c(0, 10, 10, 0),
letters[1:4]
) +
waiting_line(
x = c(0, 0),
y = c("b", "b")
) +
working_line(
x = c(0, 10, 0, 10),
y = c("b", "b", "c", "c")
) +
route_type_guide(c("b", "c"), c("a", "d")) +
scale_y_discrete(
limits = rev(letters[1:4]),
labels = c("/fast/4", "/slow/3", "/slow/2", "/fast/1")
) +
constants
save_image(p, "images/timing-plumber-future.png")
p <-
ggplot(mapping = aes(x = x, y = y, color = y)) +
receive_point(letters[2:6]) +
return_point(
x = c(10, 10, 20, 20, 0),
y = letters[2:6]
) +
working_line(
x = c(0, 10, 0, 10, 10, 20, 10, 20),
y = c("b", "b", "c", "c", "d", "d", "e", "e")
) +
waiting_line(
x = c(0, 10, 0, 10),
y = c("d", "d", "e", "e")
) +
route_type_guide(c("b", "c", "d", "e"), "f") +
scale_y_discrete(
limits = c("f", "e", "d", "c", "b"),
labels = c("/fast/5", "/slow/4", "/slow/3", "/slow/2", "/slow/1")
) +
constants
save_image(p, "images/timing-plumber-limitation.png")
future_constants <- list(
scale_y_discrete(
limits = rev(letters[1:7]),
labels = c("/fast/7", "/slow/6", "/slow/5", "/slow/4", "/slow/3", "/slow/2", "/slow/1")
),
constants[c(-2)],
theme(
legend.position = "right",
)
)
p <-
ggplot(mapping = aes(x = x, y = y, color = y)) +
receive_point(letters[1:7]) +
return_point(
c(20, 20, 20, 20, 20, 30, 30),
c("g", "a", "b", "c", "d", "e", "f")
) +
waiting_line(
x = c(
10, 20,
10, 20,
0, 10,
0, 10,
0, 20,
0, 20,
0, 20
),
y = rep(letters[1:7], c(2, 2, 2, 2, 2, 2, 2)),
group = c(
"a2", "a2",
"b2", "b2",
"c1", "c1",
"d1", "d1",
"e1", "e1",
"f1", "f1",
"g1", "g1"
)
) +
working_line(
x = c(0, 10, 0, 10, 10, 20, 10, 20, 20, 30, 20, 30),
y = rep(letters[1:6], each = 2)
) +
route_type_guide(letters[1:6], letters[7]) +
future_constants
save_image(p, "images/timing-plumber-worker_full-future.png")
p <-
ggplot(mapping = aes(x = x, y = y, color = y)) +
receive_point(letters[1:7]) +
return_point(
c(0, 10, 10, 20, 20, 30, 30),
c("g", "a", "b", "c", "d", "e", "f")
) +
geom_line(
mapping = aes(group = group, linetype = linetype),
data = data.frame(
x = c(
0, 10,
0, 10,
0, 20,
0, 20
),
y = rep(c("c", "d", "e", "f"), each = 2),
group = c(
"c1", "c1",
"d1", "d1",
"e1", "e1",
"f1", "f1"
),
linetype = "waiting"
)
) +
working_line(
x = c(0, 10, 0, 10, 10, 20, 10, 20, 20, 30, 20, 30),
y = rep(letters[1:6], each = 2)
) +
route_type_guide(promise_values = letters[1:6], plumber_values = letters[7]) +
future_constants +
status_guide(promise = TRUE)
save_image(p, "images/timing-plumber-worker_full-promise.png", width = 6.5) |
DupLambda.0<-function( alpha.1, B, Y.ia, Z.i,Z.a, Lambda.0, Lambda.1 ,p.lambda.0){
D<-nrow(B)
N<-nrow(Y.ia)
rbZ.a=Z.a
for(each in 2:nrow(Z.i)){rbZ.a=rbind(Z.a,rbZ.a)}
rbZ.i=Z.i[rep(1:nrow(Z.i), times = rep(nrow(Z.a),nrow(Z.i))), ]
dnj.ia <- rbZ.a - rbZ.i
A.ia <- 1 + 1 / sqrt(det(B)) * exp(- alpha.1) * exp(apply(dnj.ia, 1, function(x) x %*% B %*% x))
f1s2To.ia <- 2 * B %*% (t( dnj.ia / A.ia) %*% dnj.ia) %*% B - sum(1 / A.ia) * B
solve((1 / p.lambda.0^2 * N / 2 + sum(Y.ia)) * diag(D) + f1s2To.ia) * N / 2
} |
print.summary.fechner <-
function(x, ...){
cat("\n")
cat("number of stimuli pairs used for comparison:", length(x$pairs.used.for.comparison[, 1]), "\n")
cat("\n")
cat("summary of corresponding S-index values:\n")
print(summary(x$pairs.used.for.comparison[, 2]))
cat("\n")
cat("summary of corresponding Fechnerian distance G values:\n")
print(summary(x$pairs.used.for.comparison[, 3]))
cat("\n")
cat("Pearson correlation:", x$Pearson.correlation, "\n")
cat("\n")
cat("C-index:", x$C.index, "\n")
cat("\n")
cat("comparison level:", x$comparison.level, "\n")
cat("\n")
invisible(x)
} |
context("hm_show")
path <- system.file('extdata', package = 'hydrotoolbox')
cuevas <-
hm_create() %>%
hm_build(bureau = 'ianigla', path = path,
file_name = 'ianigla_cuevas.csv',
slot_name = c('tair', 'rh', 'patm',
'precip', 'wspd', 'wdir',
'kin', 'hsnow', 'tsoil'),
by = 'hour',
out_name = c('tair(°C)', 'rh(%)', 'patm(mbar)',
'p(mm)', 'wspd(km/hr)', 'wdir(°)',
'kin(kW/m2)', 'hsnow(cm)', 'tsoil(°C)' )
)
test_that("obj bad entry", {
expect_error(
hm_show(obj = cuvas)
)
expect_error(
hm_show(obj = 'cuevas')
)
expect_error(
hm_show(obj = TRUE)
)
expect_error(
hm_show(obj = 1:10)
)
})
test_that("slot_name bad entry", {
expect_error(
hm_show(obj = cuevas,
slot_name = c('tair', 'fill') )
)
expect_error(
hm_show(obj = cuevas,
slot_name = c(month.abb) )
)
expect_error(
hm_show(obj = cuevas,
slot_name = TRUE )
)
expect_error(
hm_show(obj = cuevas,
slot_name = 1:10 )
)
})
test_that("slot_name bad entry", {
expect_error(
hm_show(obj = cuevas,
slot_name = 'rh',
show = c('head', 'tail') )
)
expect_error(
hm_show(obj = cuevas,
slot_name = 'rh',
show = 'any' )
)
expect_error(
hm_show(obj = cuevas,
slot_name = 'rh',
show = 'any' )
)
expect_error(
hm_show(obj = cuevas,
slot_name = 'rh',
show = TRUE )
)
expect_error(
hm_show(obj = cuevas,
slot_name = 'rh',
show = 1:10 )
)
}) |
DearBeggMonotone <- function(y, u, lam = 2, maxiter = 1000, CR = 0.9, NP = NA, trace = TRUE){
n <- length(y)
k <- 1 + floor(n / 2)
teststat <- abs(y) / u
p <- 2 * pnorm(-teststat)
p0 <- p
ind <- order(p)
ind <- rev(ind)
p <- p[ind]
y <- y[ind]
u <- u[ind]
teststat <- teststat[ind]
if (is.na(NP)){size <- 10 * (k + 2)} else {size <- NP}
inipop <- matrix(runif(size * (k + 2)), ncol = k + 2, nrow = size, byrow = TRUE)
for (i in 1:nrow(inipop)){inipop[i, ] <- c(sort(inipop[i, 1:k]), runif(1, -20, 20), runif(1, 0, 20))}
d0 <- DEoptim::DEoptim(fn = DearBeggToMinimize, lower = c(rep(0, k), -20, 0), upper = c(rep(1, k), 20, 50),
control = DEoptim.control(strategy = 2, bs = FALSE, NP = size, trace = trace, itermax = maxiter, CR = CR, F = 0.8,
initialpop = inipop), y, u, lam)
w <- as.numeric(d0$optim$bestmem)[1:k]
theta <- as.numeric(d0$optim$bestmem)[k + 1]
sigma <- as.numeric(d0$optim$bestmem)[k + 2]
hij <- Hij(theta, sigma, y, u, teststat)$Hij
ll.DE <- DearBeggLoglik(w, theta, sigma, y, u, hij, lam)$LL
res <- list("w" = w, "theta" = theta, "sigma" = sigma, "p" = p, "y" = y, "u" = u, "loglik" = ll.DE, "DEoptim.res" = d0)
return(res)
} |
library(dplyr)
library(ggplot2)
library(HTSSIP)
physeq_S2D2_l
padj_cutoff = 0.1
ncores = 2
physeq = physeq_S2D2_l[[1]]
physeq
physeq %>% sample_data %>% .$Substrate %>% table
df_l2fc = HRSIP(physeq,
design = ~Substrate,
padj_cutoff = padj_cutoff,
sparsity_threshold = c(0,0.15,0.3))
df_l2fc %>% head(n=3)
df_l2fc %>%
filter(padj < padj_cutoff) %>%
group_by() %>%
summarize(n_incorp_OTUs = OTU %>% unique %>% length)
df_l2fc_s = df_l2fc %>%
filter(padj < padj_cutoff) %>%
mutate(Rank2 = gsub('^__', '', Rank2)) %>%
group_by(Rank2) %>%
summarize(n_incorp_OTUs = OTU %>% unique %>% length) %>%
ungroup()
ggplot(df_l2fc_s, aes(Rank2, n_incorp_OTUs)) +
geom_bar(stat='identity') +
labs(x='Phylum', y='Number of incorporators') +
theme_bw() +
theme(
axis.text.x = element_text(angle=45, hjust=1)
)
physeq_S2D2_l %>% length
doParallel::registerDoParallel(ncores)
df_l2fc = plyr::ldply(physeq_S2D2_l,
HRSIP,
design = ~Substrate,
padj_cutoff = padj_cutoff,
sparsity_threshold = c(0,0.15,0.3),
.parallel=TRUE)
df_l2fc %>% head(n=3)
df_l2fc %>% .$.id %>% unique
df_l2fc = df_l2fc %>%
mutate(.id = gsub(' \\| ', '\n', .id))
df_l2fc %>% .$.id %>% unique
df_l2fc %>%
filter(padj < padj_cutoff) %>%
group_by(.id, sparsity_threshold) %>%
summarize(n_incorp_OTUs = OTU %>% unique %>% length) %>%
as.data.frame
df_l2fc_s = df_l2fc %>%
filter(padj < padj_cutoff) %>%
mutate(Rank2 = gsub('^__', '', Rank2)) %>%
group_by(.id, Rank2) %>%
summarize(n_incorp_OTUs = OTU %>% unique %>% length) %>%
ungroup()
ggplot(df_l2fc_s, aes(Rank2, n_incorp_OTUs)) +
geom_bar(stat='identity') +
labs(x='Phylum', y='Number of incorporators') +
facet_wrap(~ .id, scales='free') +
theme_bw() +
theme(
axis.text.x = element_text(angle=55, hjust=1)
)
windows = data.frame(density_min=c(1.70, 1.72, 1.74),
density_max=c(1.73, 1.75, 1.77))
windows
doParallel::registerDoParallel(ncores)
df_l2fc = plyr::ldply(physeq_S2D2_l,
HRSIP,
density_windows = windows,
design = ~Substrate,
padj_cutoff = padj_cutoff,
sparsity_threshold = c(0,0.15,0.3),
.parallel = TRUE)
df_l2fc %>% head(n=3)
df_l2fc %>% .$.id %>% unique
df_l2fc %>%
filter(padj < padj_cutoff) %>%
group_by(.id, sparsity_threshold) %>%
summarize(n_incorp_OTUs = OTU %>% unique %>% length) %>%
as.data.frame
df_l2fc_s = df_l2fc %>%
mutate(.id = gsub(' \\| ', '\n', .id)) %>%
filter(padj < padj_cutoff) %>%
mutate(density_range = paste(density_min, density_max, sep='-')) %>%
group_by(.id, sparsity_threshold, density_range) %>%
summarize(n_incorp_OTUs = OTU %>% unique %>% length)
ggplot(df_l2fc_s, aes(.id, n_incorp_OTUs, fill=density_range)) +
geom_bar(stat='identity', position='fill') +
labs(x='Control-treatment comparision', y='Fraction of incorporators') +
scale_y_continuous(expand=c(0,0)) +
theme_bw() +
theme(
axis.text.x = element_text(angle=55, hjust=1)
)
df_l2fc_s = df_l2fc %>%
mutate(.id = gsub(' \\| ', '\n', .id)) %>%
filter(padj < padj_cutoff) %>%
mutate(Rank2 = gsub('^__', '', Rank2)) %>%
group_by(.id, Rank2) %>%
summarize(n_incorp_OTUs = OTU %>% unique %>% length) %>%
ungroup()
ggplot(df_l2fc_s, aes(Rank2, n_incorp_OTUs)) +
geom_bar(stat='identity') +
labs(x='Phylum', y='Number of incorporators') +
facet_wrap(~ .id, scales='free') +
theme_bw() +
theme(
axis.text.x = element_text(angle=55, hjust=1)
)
sessionInfo() |
rareBiosphere <- function(otutab, siteInCol = TRUE, taxhead= NULL, percent=FALSE, threshold = 1, cutRatio = 100, cutPERare = 5, ...) {
if(percent) stop("This function only work for OTUs with absolute reads!")
if(!siteInCol){
otutab <- typeConvert(otutab= data.frame(t(otutab),stringsAsFactors = FALSE),taxhead = taxhead)}
if(!is.null(taxhead)) {
data <- otutab[,which(colnames(otutab) != taxhead)]
tax <- otutab[,which(colnames(otutab) == taxhead)]
} else data <- otutab
per <- sweep(data,2,colSums(data),"/")*100
cutoff <- (which(rowMeans(per)< threshold))
rare <- per[cutoff, ]
rare_count <- data[cutoff, ]
rowsum = rowSums(rare_count)
single = vector(mode="character", length=length(rowsum))
for (z in seq_along(rowsum)) {
if (rowsum[z] ==1) single[z] = "Absolute_singleton"
else if (rowsum[z] == 2) single[z] = "Doubleton"
else single[z] = "Not"
}
len <- apply(rare, 1, function(x) sum(x>0))
mx <- apply(rare, 1, function(x) max(x))
mn <- apply(rare, 1, function(x) min(x[x>0]))
for (k in seq_along(len)) {
if (len[k] ==1) mn[k] = 0
else mn
}
ratio = rep(-1,times=length(len))
for (i in seq_along(len)) {
if (len[i] == 1) next
else ratio[i] = mx[i]/mn[i]
}
identifier = vector(mode="character", length=length(ratio))
for (i in 1:length(ratio)) {
if (ratio[i] > cutRatio) identifier[i] = 'CRT'
else if (ratio[i] < cutPERare) identifier[i] = 'PERare'
else identifier[i] = 'OtherRare'
}
if(!is.null(taxhead)) {tax2 <- tax[cutoff]
smy <- data.frame(max_rabund = mx, min_rabund = mn,ratio, RareType = identifier,singleton=single,taxonomy=tax2)
} else {
smy <- data.frame(max_rabund = mx, min_rabund = mn,ratio, RareType = identifier,singleton=single)}
smy[smy$ratio == -1,'ratio'] <- 'n.a.'
id.crt <- identifier[identifier == 'CRT']
sumTab = table(identifier)
print(paste("Number CRT are", as.vector(sumTab["CRT"])))
print(paste("Number PERare are", as.vector(sumTab["PERare"])))
print(paste("Number OtheRare are", as.vector(sumTab["OtherRare"])))
print(paste("Number absolute singletons are", sum(smy$ratio == 'n.a.')))
print(paste("Number doubletons are", sum(len==2)))
out = data.frame(rare_count, smy)
output = vector("list", length = 4)
output[[1]] <- smy
types = c("CRT","PERare","OtherRare")
nms <- c("summaryTable","CRT","PERare","otherRare")
for(i in 1:length(types)) {
output[[i+1]] <- out[identifier == types[i],]
}
names(output) <- nms
return(output)
} |
install_load <- function (package1, ...) {
packages <- c(package1, ...)
assert_that(qtest(packages, "S"), msg = "One of the provided package(s) is(are) not a string. Please make sure that each packages is a string.")
for (package in packages) {
if (package %fin% rownames(installed.packages()))
try(do.call(library, list(package)))
else {
install.packages(package, repos =
c("https://cloud.r-project.org", "http://owi.usgs.gov/R/"),
dependencies = NA, type = getOption("pkgType"))
try(do.call(library, list(package)))
}
}
} |
context("Confidence intervals and p-values")
test_that("The confint method 'quadratic' is consistent with the summary", {
expect_equivalent(
confint(fit_nw_1, parm = "parent_0", method = "quadratic"),
summary(fit_nw_1)$bpar["parent_0", c("Lower", "Upper")])
expect_equivalent(
confint(fit_nw_1, method = "quadratic"),
summary(fit_nw_1)$bpar[, c("Lower", "Upper")])
expect_equivalent(
confint(fit_nw_1, method = "quadratic", backtransform = FALSE),
summary(fit_nw_1)$par[, c("Lower", "Upper")])
expect_equivalent(
confint(f_1_mkin_notrans, method = "quadratic", transformed = FALSE),
summary(f_1_mkin_notrans)$par[, c("Lower", "Upper")])
expect_equivalent(
confint(f_1_mkin_notrans, method = "quadratic", transformed = FALSE),
summary(f_1_mkin_notrans)$bpar[, c("Lower", "Upper")])
})
test_that("Quadratic confidence intervals for rate constants are comparable to values in summary.nls", {
expect_equivalent(
(f_1_mkin_trans$bparms.optim -coef(f_1_nls_notrans))/f_1_mkin_trans$bparms.optim,
rep(0, 2), tolerance = 1e-6)
expect_equivalent(
(f_1_mkin_trans$par[1:2] - coef(f_1_nls_trans))/f_1_mkin_trans$par[1:2],
rep(0, 2), tolerance = 1e-6)
se_nls <- summary(f_1_nls_trans)$coefficients[, "Std. Error"]
se_mkin <- summary(f_1_mkin_trans)$par[1:2, "Std. Error"]
se_nls_notrans <- summary(f_1_nls_notrans)$coefficients[, "Std. Error"]
se_mkin_notrans <- summary(f_1_mkin_notrans)$par[1:2, "Std. Error"]
expect_equivalent(se_nls[2] / se_mkin[2], sqrt(8/5), tolerance = 0.01)
expect_equivalent(se_nls_notrans[2] / se_mkin_notrans[2], sqrt(8/5), tolerance = 0.01)
se_mkin_2 <- summary(f_2_mkin)$par[1:4, "Std. Error"]
se_nls_2 <- summary(f_2_nls)$coefficients[, "Std. Error"]
nobs_DFOP_par_c_parent <- nrow(subset(DFOP_par_c, name == "parent"))
expect_equivalent(
se_nls_2[c("lrc1", "lrc2")] / se_mkin_2[c("log_k1", "log_k2")],
rep(sqrt(nobs_DFOP_par_c_parent / (nobs_DFOP_par_c_parent - 4)), 2),
tolerance = 0.03)
})
test_that("Likelihood profile based confidence intervals work", {
f <- fits[["SFO", "FOCUS_C"]]
f_nll <- function(parent_0, k_parent, sigma) {
- f$ll(c(parent_0 = as.numeric(parent_0),
k_parent = as.numeric(k_parent),
sigma = as.numeric(sigma)))
}
f_mle <- stats4::mle(f_nll, start = as.list(parms(f)), nobs = nrow(FOCUS_2006_C))
ci_mkin_1_p_0.95 <- expect_message(confint(f, method = "profile", level = 0.95,
cores = n_cores, quiet = FALSE), "Profiling the likelihood")
msg <- capture.output(ci_mle_1_0.95 <- stats4::confint(f_mle, level = 0.95))
rel_diff_ci <- (ci_mle_1_0.95 - ci_mkin_1_p_0.95)/ci_mle_1_0.95
expect_equivalent(as.numeric(rel_diff_ci), rep(0, 6), tolerance = 1e-4)
}) |
gbm.bfcheck <- function(
samples,
resvar,
ZI = "CHECK",
grv = NULL)
{
minbfbin <- 21/nrow(samples)
print(
paste0(" binary bag fraction must be at least ",
round(minbfbin, 3),
". n = ",
nrow(samples)
)
)
if (ZI == "CHECK") if (sum(samples[,resvar] == 0, na.rm = TRUE) / length(samples[,resvar]) >= 0.5) ZI = TRUE else ZI = FALSE
logem <- log1p(samples[,resvar])
dont <- samples[,resvar]
if (ZI) {samples$grv <- logem} else {samples$grv <- dont}
grv_yes <- subset(samples, grv > 0)
minbfgaus <- 21/nrow(grv_yes)
print(
paste0("Gaussian bag fraction must be at least ",
round(minbfgaus,3),
". n = ",
nrow(grv_yes)
)
)
return(c(minbfbin,minbfgaus))
} |
context("ceac")
library(dampack)
test_that("ceac has all methods we'd expect", {
current_methods <- as.vector(methods(class = ceac))
expected_methods <- c("plot.ceac", "summary.ceac")
expect_setequal(current_methods, expected_methods)
})
data("example_psa")
wtp <- example_psa$wtp
psa_obj <- make_psa_obj(example_psa$cost,
example_psa$effectiveness,
example_psa$parameters,
example_psa$strategies)
test_that("result has class 'ceac'", {
c <- ceac(wtp, psa_obj)
expect_true(inherits(c, "data.frame"))
expect_true(inherits(c, "ceac"))
})
test_that("handles missing strategy", {
psa_missing <- make_psa_obj(example_psa$cost,
example_psa$effectiveness,
example_psa$parameters)
c_missing <- ceac(wtp, psa_missing)
expected_generic_strat <- factor(c("Strategy_1", "Strategy_2", "Strategy_3"), ordered = TRUE)
obtained_generic_strat <- sort(unique(c_missing$Strategy))
expect_equal(expected_generic_strat, obtained_generic_strat)
})
test_that("message is correct in summary.ceac", {
c <- ceac(wtp, psa_obj)
sum_df <- summary(c)
expect_equal(sum_df$cost_eff_strat, c("Radio", "Chemo"))
})
test_that("plot.ceac produces ggplot object", {
ceac_obj <- ceac(wtp, psa_obj)
gf <- plot(ceac_obj, frontier = TRUE)
expect_is(gf, "ggplot")
gnof <- plot(ceac_obj, frontier = FALSE)
expect_is(gnof, "ggplot")
custom_breaks <- plot(ceac_obj, xbreaks = seq(0, 140))
expect_is(custom_breaks, "ggplot")
expect_is(plot(ceac_obj, col = "bw"), "ggplot")
}) |
gpUpdateKernels <-
function (model, X, X_u) {
jitter = 1e-6
if (model$approx == "ftc") {
model$K_uu = kernCompute(model$kern, X)
if ((!"isSpherical" %in% names(model)) || model$isSpherical) {
if ("beta" %in% names(model) && length(model$beta)>0) {
model$K_uu[seq(1,length(model$K_uu),by= dim(model$K_uu)[1]+1)] =
model$K_uu[seq(1,length(model$K_uu),by= dim(model$K_uu)[1]+1)] + 1/model$beta
}
invK = .jitCholInv(model$K_uu, silent=TRUE)
model$invK_uu = invK$invM
model$logDetK_uu = 2* sum( log ( diag(invK$chol) ) )
} else {
model$invK_uu=list(); model$logDetK_uu=matrix(0,1,model$d)
for (i in 1:model$d) {
if ("beta" %in% names(model) && length(model$beta)>0) {
if (dim(as.matrix(model$beta))[2] == model$d)
betaAdd = model$beta[, i]
else
betaAdd = model$beta
model$K_uu[seq(1,length(model$K_uu),by= dim(model$K_uu)[1]+1)] =
model$K_uu[seq(1,length(model$K_uu),by= dim(model$K_uu)[1]+1)] + 1/betaAdd
}
ind = gpDataIndices(model, i)
invK = .jitCholInv(model$K_uu[ind,ind], silent=TRUE)
model$invK_uu[[i]] = invK$invM
model$logDetK_uu[i] = 2* sum( log ( diag(invK$chol) ) )
}
}
} else if (model$approx %in% c("dtc", "dtcvar", "fitc", "pitc")) {
model$K_uu = kernCompute(model$kern, X_u)
if ((!"whiteVariance" %in% names(model$kern)) || model$kern$whiteVariance == 0) {
model$K_uu = model$K_uu + diag.spam(jitter, dim(model$K_uu)[1])
}
model$K_uf = kernCompute(model$kern, X_u, X)
invK = .jitCholInv(model$K_uu, silent=TRUE)
model$invK_uu = invK$invM
model$logDetK_uu = 2* sum( log ( diag(invK$chol) ) )
}
if (model$approx %in% c("dtcvar", "fitc"))
model$diagK = kernDiagCompute(model$kern, X)
else if (model$approx == "pitc") {
if ((!"isSpherical" %in% names(model)) || model$isSpherical) {
model$K=list()
for (i in 1:length(model$blockEnd)) {
ind = gpBlockIndices(model, i)
model$K[[i]] = kernCompute(model$kern, X[ind, ,drop=FALSE])
}
} else {
model$K = matrix(0, length(model$blockEnd), model$d)
model$K = lapply(split(model$K,row(model$K)), split, 1:model$d)
for (j in 1:model$d) {
for (i in 1:length(model$blockEnd)) {
ind = gpDataIndices(model, j, i)
model$K[[i]][[j]] = kernCompute(model$kern, X[ind, ,drop=FALSE])
}
}
}
}
model = gpUpdateAD(model, X)
return (model)
} |
p.tfisher <- function(q,n,tau1,tau2,M=NULL,mu=NULL,sigma2=NULL, p0=NULL){
if(is.null(M)){
return((sum(pchisq(q+2*(1:n)*log(tau1/tau2),2*(1:n))*dbinom(1:n, n, tau1)) + (0<q)*dbinom(0, n, tau1)))
}else{
n = length(M[1,])
if(is.null(mu)){
mu = getTFisherMean(n, tau1, tau2)
}
if(is.null(sigma2)){
sigma2 = getTFisherVar_v1(M, tau1, tau2)
}
if(is.null(p0)){
bound = qnorm(1-tau1/2)
p0 = pmvnorm(lower=-rep(bound,n),upper=rep(bound,n),sigma=M)[1]
}
shift = -2*log(tau1/tau2)
a = (mu-shift*(1-p0))^2/((1-p0)*sigma2-p0*mu^2)
s = (mu/(1-p0)-shift)/a
return((0<q)*p0+(1-p0)*pgamma(q-shift, shape=a, scale=s))
}
} |
StatArima <- ggproto("StatArima", Stat,
required_aes = c("x", "y"),
default_aes = aes(x = x, y = y, label = stat(arima_model)),
compute_group = function(data, scales,
method = c("x13", "tramoseats"),
spec = NULL,
frequency = NULL,
message = TRUE,
x_arima = NULL, y_arima = NULL,
new_data = TRUE) {
result <- seasonal_adjustment(data = data,
method = method,
spec = spec,
frequency = frequency,
message = message,
new_data = new_data)
data <- result[["data"]]
sa <- result[["sa"]]
arima_model <- RJDemetra::get_indicators(sa,
sprintf("preprocessing.arima.%s",
c("p","d","q","bp","bd","bq")))
arima_model <- paste0("ARIMA(",arima_model[[1]], ",",
arima_model[[2]], ",",
arima_model[[3]], ")(",
arima_model[[4]], ",",
arima_model[[5]], ",",
arima_model[[6]], ")")
data <- data[1, ]
if (!is.null(x_arima))
data$x <- x_arima
if (!is.null(y_arima))
data$y <- y_arima
data$arima_model <- arima_model
data
}
)
geom_arima <- function(mapping = NULL, data = NULL, stat = "arima",
geom = c("text", "label"),
position = "identity", ...,
method = c("x13", "tramoseats"),
spec = NULL,
frequency = NULL,
message = TRUE,
x_arima = NULL, y_arima = NULL,
show.legend = NA,
inherit.aes = TRUE
) {
geom <- match.arg(geom)
if (geom == "text") {
geom <- GeomText
} else {
geom <- GeomLabel
}
ggplot2::layer(data = data, mapping = mapping, stat = stat, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(method = method, spec = spec,
frequency = frequency, message = message,
x_arima = x_arima, y_arima = y_arima,
new_data = !missing(data) || !is.null(data),
...))
} |
dbQuoteLiteral_MariaDBConnection <- function(conn, x, ...) {
if (inherits(x, "difftime")) return(cast_difftime(callNextMethod()))
callNextMethod()
}
setMethod("dbQuoteLiteral", signature("MariaDBConnection"), dbQuoteLiteral_MariaDBConnection) |
NULL
yield_next <- function(iter) {
stopifnot(is_Iterator(iter))
iter$initial$.iter <- 1L
env <- list2env(iter$initial, parent = caller_env())
eval_bare(iter$result, env = env)
iter$initial <- as.list(env, all.names = TRUE)
iter$initial <- within(iter$initial, rm(.iter))
return(iter$initial[[iter$yield]])
}
yield_more <- function(iter, more = 1L) {
stopifnot(is_Iterator(iter))
vec <- vector(length = more)
env <- list2env(iter$initial, parent = caller_env())
env$.iter <- 1L
expr <- iter$result
char <- iter$yield
for (i in seq_len(more)) {
eval_bare(expr, env = env)
vec[[i]] <- env[[char]]
env$.iter <- i
}
iter$initial <- as.list(env, all.names = TRUE)
iter$initial <- within(iter$initial, rm(.iter))
return(vec)
} |
subset.varbvs <- function (x, subset, ...) {
if (!is(x,"varbvs"))
stop("Input argument object must be an instance of class \"varbvs\".")
e <- substitute(subset)
i <- which(eval(e,x,parent.frame()))
if (length(i) == 0)
stop("No hyperparameter settings are selected.")
out <- x
out$sa <- out$sa[i]
out$logodds <- out$logodds[i]
out$logw <- out$logw[i]
out$w <- normalizelogweights(out$logw)
out$mu.cov <- as.matrix(out$mu.cov[,i])
out$alpha <- as.matrix(out$alpha[,i])
out$mu <- as.matrix(out$mu[,i])
out$s <- as.matrix(out$s[,i])
out$fitted.values <- as.matrix(out$fitted.values)
out$residuals <- as.matrix(out$residuals)
if (!is.null(out$pve))
out$pve <- as.matrix(out$pve[,i])
if (out$family == "gaussian")
out$sigma <- out$sigma[i]
else if (out$family == "binomial")
out$eta <- out$eta[,i]
return(out)
} |
library(ggsolvencyii)
context("fncomputegroup")
testdata <- sii_z_ex1_data
testdata_ggplotformat <- dplyr::rename(testdata, x = time, y = ratio, id = id, description = description , value = value )
testdata_ggplotformat <- dplyr::mutate(testdata_ggplotformat, group = id)
testparams <- NULL
testparams$structure = sii_structure_sf16_eng
testparams$levelmax <- sii_levelmax_sf16_993
testparams$aggregatesuffix <- "_other"
intresultA <- ggsolvencyii:::fn_structure_expansion(testparams)
intresultB <- ggsolvencyii:::fn_structure_data_integration(expandedstructure = intresultA, data = testdata_ggplotformat)
intresultB_group2 <- intresultB[intresultB$group == 2, ]
testparams$maxscrvalue <- ggsolvencyii:::fn_maxscrvalue(data = testdata_ggplotformat, params = testparams)
testparams$tocenter <- FALSE
testparams$plotdetails <- ggsolvencyii:::fn_constructionplotdetails(structure = testparams$structure)
testscales <- NULL
testparams$rotationdescription <- NULL
testparams$rotationdegrees <- NULL
testparams$squared <- TRUE
testparams$purpose <- "surface"
testresultA <- ggsolvencyii:::fn_computegroup(data = intresultB_group2, scales = testscales, siiparams = testparams)
testparams$purpose <- "outline"
testresultB <- ggsolvencyii:::fn_computegroup(data = intresultB_group2, scales = testscales, siiparams = testparams)
rm(testdata)
rm(testresultA)
rm(testresultB) |
mle.wrappedcauchy <- function(x, mu=NULL, rho=NULL, tol = 1e-015, max.iter = 100, control.circular=list()) {
if (tol <= 0) stop("'tol' must be positive")
x <- na.omit(x)
if (length(x)==0) {
warning("No observations (at least after removing missing values)")
return(NULL)
}
if (is.circular(x)) {
datacircularp <- circularp(x)
} else if (is.circular(mu)) {
datacircularp <- circularp(mu)
} else {
datacircularp <- list(type="angles", units="radians", template="none", modulo="asis", zero=0, rotation="counter")
}
dc <- control.circular
if (is.null(dc$type))
dc$type <- datacircularp$type
if (is.null(dc$units))
dc$units <- datacircularp$units
if (is.null(dc$template))
dc$template <- datacircularp$template
if (is.null(dc$modulo))
dc$modulo <- datacircularp$modulo
if (is.null(dc$zero))
dc$zero <- datacircularp$zero
if (is.null(dc$rotation))
dc$rotation <- datacircularp$rotation
x <- conversion.circular(x, units="radians", zero=0, rotation="counter", modulo="2pi")
attr(x, "class") <- attr(x, "circularp") <- NULL
if (!is.null(mu)) {
mu <- conversion.circular(mu, units="radians", zero=0, rotation="counter", modulo="2pi")
attr(mu, "class") <- attr(mu, "circularp") <- NULL
}
res <- MlewrappedcauchyRad(x, mu, rho, tol, max.iter)
mu <- conversion.circular(circular(res[1]), dc$units, dc$type, dc$template, dc$modulo, dc$zero, dc$rotation)
result <- list()
result$call <- match.call()
result$mu <- mu
result$rho <- res[2]
result$est.mu <- res[3]
result$est.rho <- res[4]
result$convergence <- TRUE
if (!is.na(res[5]) && res[5] > max.iter) {
result$convergence <- FALSE
}
class(result) <- "mle.wrappedcauchy"
return(result)
}
MlewrappedcauchyRad <- function(x, mu, rho, tol, max.iter) {
n <- length(x)
est.mu <- FALSE
if (is.null(mu)) {
mu <- MeanCircularRad(x)
est.mu <- TRUE
}
est.rho <- FALSE
if (is.null(rho)) {
rho <- RhoCircularRad(x)
est.rho <- TRUE
}
if (rho < 0 | rho > 1) stop("'rho' must be between 0 and 1")
if (est.mu) {
if (est.rho) {
mu1.old <- (2 * rho * cos(mu))/(1 + rho^2)
mu2.old <- (2 * rho * sin(mu))/(1 + rho^2)
w.old <- 1/(1 - mu1.old * cos(x) - mu2.old * sin(x))
flag <- TRUE
iter <- 0
while (flag & iter <= max.iter) {
iter <- iter + 1
mu1.new <- sum(w.old * cos(x))/sum(w.old)
mu2.new <- sum(w.old * sin(x))/sum(w.old)
diff1 <- abs(mu1.new - mu1.old)
diff2 <- abs(mu2.new - mu2.old)
if ((diff1 < tol) && (diff2 < tol))
flag <- FALSE
else {
mu1.old <- mu1.new
mu2.old <- mu2.new
w.old <- 1/(1 - mu1.old * cos(x) - mu2.old * sin(x))
}
}
mu.const <- sqrt(mu1.new^2 + mu2.new^2)
mu <- atan2(mu2.new, mu1.new) %% (2 * pi)
rho <- (1 - sqrt(1 - mu.const^2))/mu.const
} else {
score <- function(x, data, rho) {
sum(sin(data-x)/(1+rho^2-2*rho*cos(data-x)))
}
res <- uniroot(f=score, lower=mu-pi/2, upper=mu+pi/2, data=x, rho=rho, tol=tol)
mu <- res$root
iter <- NA
}
} else {
if (est.rho) {
wt <- function(x, mu, rho) {
((1-rho^2)*(1+rho^2-2*rho*cos(x-mu)))^(-1)
}
diff <- 1+tol
iter <- 0
rho.old <- rho
while (diff >= tol & iter <= max.iter) {
iter <- iter + 1
w <- wt(x, mu, rho)
sumw <- sum(w)
sumwcos <- w%*%cos(x-mu)
rho <- (sumw - sqrt(sumw^2 - sumwcos^2))/sumwcos
diff <- abs(rho - rho.old)
rho.old <- rho
}
}
}
result <- c(mu, rho, est.mu, est.rho, iter)
return(result)
}
print.mle.wrappedcauchy <- function(x, digits = max(3, getOption("digits") - 3), ...) {
cat("\nCall:\n",deparse(x$call),"\n\n",sep="")
cat("mu: ")
cat(format(x$mu, digits=digits), "\n")
cat("\n")
cat("rho: ")
cat(format(x$rho, digits=digits), "\n")
cat("\n")
if (!x$est.mu) cat("mu is known\n")
if (!x$est.rho) cat("rho is known\n")
if (!x$convergence) cat("\n The convergence is not achieved after the prescribed number of iterations \n")
invisible(x)
} |
report_miss <- function(x, col_name = 'all'){
check_class(argument = x, target = 'data.frame', arg_name = 'x')
check_class(argument = x[ , 1], target = c('Date', 'POSIXct'), arg_name = 'x[ , 1]')
check_class(argument = c( as.matrix( x[ , -1] ) ),
target = 'numeric', arg_name = 'x[ , -1]')
check_class(argument = col_name, target = 'character', arg_name = 'col_name')
if(col_name[1] != 'all'){
check_string(argument = col_name, target = colnames(x)[-1], arg_name = 'col_name')
}
check_length(argument = col_name,
max_allow = length( colnames(x)[-1] ),
arg_name = 'col_name')
all_names <- colnames(x)[-1]
if(col_name[1] == 'all'){
col_name <- all_names
}
col_pos <- match(x = col_name, table = all_names) + 1
n_it <- length(col_pos)
out_list <- list()
for(i in 1:n_it){
na_pos <- which( is.na( x[ , col_pos[i] ] ) )
contiguous <- c( 1, diff(na_pos) )
first_pos <- which(contiguous > 1)
if( length(contiguous) == 1 ){
start_pos <- na_pos[1]
end_pos <- na_pos[1]
} else {
start_pos <- c( na_pos[1], na_pos[first_pos] )
end_pos <- c( na_pos[first_pos - 1], na_pos[ length(na_pos) ] )
}
first_date <- c( x[start_pos, 1], NA_character_ )
last_date <- c( x[end_pos, 1], NA_character_)
delta_t <- end_pos - start_pos + 1
delta_t <- c( delta_t, sum(delta_t) )
out_table <- data.frame(first = first_date, last = last_date, time_steps = delta_t)
out_list[[ col_name[i] ]] <- out_table
rm(na_pos, contiguous, first_pos, start_pos, end_pos,
first_date, last_date, delta_t, out_table)
}
return(out_list)
} |
test_that("trem_delete throws errors - no client", {
expect_error(
trem_post(path = "members",
body = list(email = "[email protected]",
name = "Example Person",
role = "MEMBER"),
),
regexp = "Tremendous API Client required.")
})
test_that("trem_delete works", {
skip_on_cran()
skip_on_travis()
test_client <- trem_client_new(api_key = NULL,
sandbox = TRUE)
trem_post(test_client,
path = "invoices",
body = list(po_number = "from-testthat-invoice-id",
amount = 50)
)
current_invoices <- trem_get(test_client, "invoices")
my_invoice_id <- current_invoices$invoices[which(current_invoices$invoices$po_number == "from-testthat-invoice-id"), "id"]
vcr::use_cassette("trem-delete", {
deleteClient <- trem_delete(test_client,
paste0("invoices/", my_invoice_id))
}, match_requests_on = "method"
)
new_invoices <- trem_get(test_client, "invoices")
expect_type(deleteClient, "list")
expect_named(deleteClient, "invoice")
expect_type(deleteClient$invoice, "list")
expect_named(deleteClient$invoice, c("id", "po_number", "amount", "status"))
expect_type(deleteClient$invoice$id, "character")
expect_type(deleteClient$invoice$po_number, "character")
expect_type(deleteClient$invoice$amount, "double")
expect_equal(deleteClient$invoice$status, "DELETED")
expect_false(deleteClient$invoice$id %in% new_invoices$invoices$id)
on.exit(trem_delete(test_client, paste0("invoices/", my_invoice_id)),
add = TRUE)
}) |
add_cumulative_yield <- function(data,
dates = Date,
values = Value,
groups = STATION_NUMBER,
station_number,
basin_area,
water_year_start = 1,
months = 1:12){
if (missing(data)) {
data <- NULL
}
if (missing(station_number)) {
station_number <- NULL
}
if (missing(basin_area)) {
basin_area <- NA
}
water_year_checks(water_year_start)
months_checks(months)
flow_data <- flowdata_import(data = data,
station_number = station_number)
orig_cols <- names(flow_data)
orig_groups <- dplyr::group_vars(flow_data)
flow_data <- format_all_cols(data = flow_data,
dates = as.character(substitute(dates)),
values = as.character(substitute(values)),
groups = as.character(substitute(groups)))
flow_data <- add_basin_area(flow_data, basin_area = basin_area)
flow_data$Basin_Area_sqkm_temp <- flow_data$Basin_Area_sqkm
flow_data_temp <- analysis_prep(data = flow_data,
water_year_start = water_year_start)
flow_data_temp <- dplyr::filter(flow_data_temp,
Month %in% months)
cumsum_na <- function(x) {
if (any(is.na(x))) {
return(rep(NA, length(x)))
} else {
cumsum(x)
}
}
flow_data_temp <- dplyr::ungroup(flow_data_temp)
flow_data_temp <- dplyr::mutate(dplyr::group_by(flow_data_temp, STATION_NUMBER, WaterYear, .add = TRUE),
Cumul_Yield_mm = cumsum_na(Value) * 86400 / (Basin_Area_sqkm_temp * 1000))
flow_data_temp <- dplyr::ungroup(flow_data_temp)
flow_data_temp <- dplyr::select(flow_data_temp, STATION_NUMBER, Date, Cumul_Yield_mm)
if("Cumul_Yield_mm" %in% orig_cols){
flow_data <- merge(flow_data, flow_data_temp, by = c("STATION_NUMBER", "Date"), all.x = TRUE)
flow_data$Cumul_Yield_mm <- flow_data$Cumul_Yield_mm.y
flow_data <- dplyr::select(flow_data, -Cumul_Yield_mm.y, -Cumul_Yield_mm.x)
} else {
flow_data <- merge(flow_data, flow_data_temp, by = c("STATION_NUMBER", "Date"), all.x = TRUE)
}
names(flow_data)[names(flow_data) == "STATION_NUMBER"] <- as.character(substitute(groups))
names(flow_data)[names(flow_data) == "Date"] <- as.character(substitute(dates))
names(flow_data)[names(flow_data) == "Value"] <- as.character(substitute(values))
if("Cumul_Yield_mm" %in% orig_cols){
flow_data <- flow_data[,c(orig_cols)]
} else {
flow_data <- flow_data[,c(orig_cols, paste("Cumul_Yield_mm"))]
}
flow_data <- dplyr::group_by_at(flow_data, dplyr::vars(orig_groups))
dplyr::as_tibble(flow_data)
} |
scanmeasure <- function(X, ...){
UseMethod("scanmeasure")
}
scanmeasure.ppp <- function(X, r, ..., method=c("counts", "fft")) {
method <- match.arg(method)
check.1.real(r)
R <- as.rectangle(as.owin(X))
M <- as.mask(R, ...)
W <- grow.mask(M, r)
switch(method,
counts = {
dimyx <- W$dim
xr <- W$xrange
yr <- W$yrange
nr <- dimyx[1]
nc <- dimyx[2]
n <- npoints(X)
zz <- .C(SC_scantrans,
x=as.double(X$x),
y=as.double(X$y),
n=as.integer(n),
xmin=as.double(xr[1]),
ymin=as.double(yr[1]),
xmax=as.double(xr[2]),
ymax=as.double(yr[2]),
nr=as.integer(nr),
nc=as.integer(nc),
R=as.double(r),
counts=as.integer(numeric(prod(dimyx))),
PACKAGE="spatstat.core")
zzz <- matrix(zz$counts, nrow=dimyx[1], ncol=dimyx[2], byrow=TRUE)
Z <- im(zzz, xrange=xr, yrange=yr, unitname=unitname(X))
},
fft = {
sigma <- with(W, unique(c(xstep, ystep)))
Y <- density(X, ..., sigma=sigma)
Z <- scanmeasure(Y, r)
Z <- eval.im(as.integer(round(Z)))
})
return(Z)
}
scanmeasure.im <- function(X, r, ...) {
D <- disc(radius=r)
eps <- with(X, c(xstep,ystep))
if(any(eps >= 2 * r)) return(eval.im(X * pi * r^2))
D <- as.im(as.mask(D, eps=eps))
Z <- imcov(X, D)
return(Z)
}
scanPoisLRTS <- function(nZ, nG, muZ, muG, alternative) {
nZco <- nG - nZ
muZco <- muG - muZ
nlogn <- function(n, a) ifelse(n == 0, 0, n * log(n/a))
ll <- nlogn(nZ, muZ) + nlogn(nZco, muZco) - nlogn(nG, muG)
criterion <- (nZ * muZco - muZ * nZco)
switch(alternative,
less={
ll[criterion > 0] <- 0
},
greater={
ll[criterion < 0] <- 0
},
two.sided={})
return(2 * ll)
}
scanBinomLRTS <- function(nZ, nG, muZ, muG, alternative) {
nZco <- nG - nZ
muZco <- muG - muZ
nlogn <- function(n, a) ifelse(n == 0, 0, n * log(n/a))
logbin <- function(k, n) { nlogn(k, n) + nlogn(n-k, n) }
ll <- logbin(nZ, muZ) + logbin(nZco, muZco) - logbin(nG, muG)
criterion <- (nZ * muZco - muZ * nZco)
switch(alternative,
less={
ll[criterion > 0] <- 0
},
greater={
ll[criterion < 0] <- 0
},
two.sided={})
return(2 * ll)
}
scanLRTS <- function(X, r, ...,
method=c("poisson", "binomial"),
baseline=NULL,
case=2,
alternative=c("greater", "less", "two.sided"),
saveopt = FALSE,
Xmask=NULL) {
stopifnot(is.ppp(X))
stopifnot(check.nvector(r))
method <- match.arg(method)
alternative <- match.arg(alternative)
if(is.null(Xmask)) Xmask <- as.mask(as.owin(X), ...)
switch(method,
poisson={
Y <- X
if(is.null(baseline)) {
mu <- as.im(Xmask, value=1)
} else if(is.ppm(baseline)) {
if(is.marked(baseline))
stop("baseline is a marked point process: not supported")
mu <- predict(baseline, locations=Xmask)
} else if(is.im(baseline) || is.function(baseline)) {
mu <- as.im(baseline, W=Xmask)
} else stop(paste("baseline should be",
"a pixel image, a function, or a fitted model"))
nG <- npoints(Y)
},
binomial={
stopifnot(is.multitype(X))
lev <- levels(marks(X))
if(length(lev) != 2)
warning("X should usually be a bivariate (2-type) point pattern")
if(!is.null(baseline))
stop("baseline is not supported in the binomial case")
if(is.character(case) && !(case %in% lev))
stop(paste("Unrecognised label for cases:", sQuote(case)))
if(is.numeric(case) && !(case %in% seq_along(lev)))
stop(paste("Undefined level:", case))
Y <- split(X)[[case]]
nG <- npoints(Y)
mu <- unmark(X)
})
Y$window <- Xmask
nr <- length(r)
lrts <- vector(mode="list", length=nr)
for(i in 1:nr) {
ri <- r[i]
nZ <- scanmeasure(Y, ri)
muZ <- scanmeasure(mu, ri)
if(!compatible.im(nZ, muZ)) {
ha <- harmonise.im(nZ, muZ)
nZ <- ha[[1]]
muZ <- ha[[2]]
}
switch(method,
poisson = {
muG <- integral.im(mu)
lrts[[i]] <- eval.im(scanPoisLRTS(nZ, nG, muZ, muG, alternative))
},
binomial = {
muG <- npoints(mu)
lrts[[i]] <- eval.im(scanBinomLRTS(nZ, nG, muZ, muG, alternative))
})
}
if(length(lrts) == 1) {
result <- lrts[[1]]
} else {
result <- im.apply(lrts, max)
if(saveopt)
attr(result, "iopt") <- im.apply(lrts, which.max)
}
return(result)
}
scan.test <- function(X, r, ...,
method=c("poisson", "binomial"),
nsim = 19,
baseline=NULL,
case = 2,
alternative=c("greater", "less", "two.sided"),
verbose=TRUE) {
dataname <- short.deparse(substitute(X))
stopifnot(is.ppp(X))
method <- match.arg(method)
alternative <- match.arg(alternative)
stopifnot(is.numeric(r))
check.1.real(nsim)
if(!(round(nsim) == nsim && nsim > 1))
stop("nsim should be an integer > 1")
regionname <-
paste("circles of radius",
if(length(r) == 1) r else paste("between", min(r), "and", max(r)))
obsLRTS <- scanLRTS(X=X, r=r,
method=method,
alternative=alternative, baseline=baseline,
case=case, ..., saveopt=TRUE)
obs <- max(obsLRTS)
sim <- numeric(nsim)
switch(method,
binomial={
methodname <- c("Spatial scan test",
"Null hypothesis: constant relative risk",
paste("Candidate cluster regions:", regionname),
"Likelihood: binomial",
paste("Monte Carlo p-value based on",
nsim, "simulations"))
lev <- levels(marks(X))
names(lev) <- lev
casename <- lev[case]
counted <- paste("points with mark", sQuote(casename),
"inside cluster region")
simexpr <- expression(rlabel(X))
},
poisson={
counted <- paste("points inside cluster region")
X <- unmark(X)
Xwin <- as.owin(X)
Xmask <- as.mask(Xwin, ...)
if(is.null(baseline)) {
nullname <- "Complete Spatial Randomness (CSR)"
lambda <- intensity(X)
simexpr <- expression(runifpoispp(lambda, Xwin))
dont.complain.about(lambda)
} else if(is.ppm(baseline)) {
nullname <- baseline$callstring
rmhstuff <- rmh(baseline, preponly=TRUE, verbose=FALSE)
simexpr <- expression(rmhEngine(rmhstuff))
dont.complain.about(rmhstuff)
} else if(is.im(baseline) || is.function(baseline)) {
nullname <- "Poisson process with intensity proportional to baseline"
base <- as.im(baseline, W=Xmask)
alpha <- npoints(X)/integral.im(base)
lambda <- eval.im(alpha * base)
simexpr <- expression(rpoispp(lambda))
dont.complain.about(lambda)
} else stop(paste("baseline should be",
"a pixel image, a function, or a fitted model"))
methodname <- c("Spatial scan test",
paste("Null hypothesis:", nullname),
paste("Candidate cluster regions:", regionname),
"Likelihood: Poisson",
paste("Monte Carlo p-value based on",
nsim, "simulations"))
})
if(verbose) {
cat("Simulating...")
pstate <- list()
}
for(i in 1:nsim) {
if(verbose) pstate <- progressreport(i, nsim, state=pstate)
Xsim <- eval(simexpr)
simLRTS <- scanLRTS(X=Xsim, r=r,
method=method, alternative=alternative,
baseline=baseline,
case=case,
...)
sim[i] <- max(simLRTS)
}
pval <- mean(c(sim,obs) >= obs, na.rm=TRUE)
names(obs) <- "maxLRTS"
nm.alternative <- switch(alternative,
greater="Excess of",
less="Deficit of",
two.sided="Two-sided: excess or deficit of",
stop("Unknown alternative"))
nm.alternative <- paste(nm.alternative, counted)
result <- list(statistic = obs,
p.value = pval,
alternative = nm.alternative,
method = methodname,
data.name = dataname)
class(result) <- c("scan.test", "htest")
attr(result, "obsLRTS") <- obsLRTS
attr(result, "X") <- X
attr(result, "r") <- r
return(result)
}
plot.scan.test <- function(x, ..., what=c("statistic", "radius"),
do.window=TRUE) {
xname <- short.deparse(substitute(x))
what <- match.arg(what)
Z <- as.im(x, what=what)
dont.complain.about(Z)
do.call(plot, resolve.defaults(list(x=quote(Z)), list(...), list(main=xname)))
if(do.window) {
X <- attr(x, "X")
plot(as.owin(X), add=TRUE, invert=TRUE)
}
invisible(NULL)
}
as.im.scan.test <- function(X, ..., what=c("statistic", "radius")) {
Y <- attr(X, "obsLRTS")
what <- match.arg(what)
if(what == "radius") {
iopt <- attr(Y, "iopt")
r <- attr(X, "r")
Y <- eval.im(r[iopt])
}
return(as.im(Y, ...))
} |
cj_anova <-
function(
data,
formula,
id = NULL,
weights = NULL,
by = NULL,
...
) {
stopifnot(inherits(formula, "formula"))
stopifnot(length(formula) > 2L)
stopifnot(attr(terms(formula), "response") == 1L)
by_vars <- all.vars(stats::update(by, 0 ~ . ))
formula_reduced <- formula
formula_full <- update(formula, reformulate(paste0("(.) * ", by_vars)))
if (inherits(data, "data.frame") && is.null(weights)) {
svy_design <- NULL
estimates_full <- stats::glm(formula_full, data = data, ...)
estimates_reduced <- stats::glm(formula_reduced, data = data, ...)
} else if (inherits(data, "data.frame")) {
stop("cj_anova() currently does not support 'weights'")
} else if (inherits(data, "survey.design")) {
stop("cj_anova() currently does not support 'weights'")
} else {
stop("'data' is not a 'data.frame' or 'survey.design' object")
}
anova(estimates_reduced, estimates_full, test = "F")
} |
rdigitsBFOS <- function(n, eta=0.25, alpha=NULL, silent=FALSE) {
stopifnot(eta>0.01 && eta <= 0.5)
z <- rep(c(1,1,1,0,1,1,1,0,0,1,0,0,1,0,1,0,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,
0,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,0,0,1,0,1,1,1,1,1,1,1,1,1,
1,1,0,1,1),n)
if (is.null(alpha)) {
alpha <- (-0.00014393510482067046 + eta*(0.3743903928013429 +
eta*(0.003068677095495819 +
eta*0.003068677095495819)))
} else {
stopifnot(alpha>0 && alpha <= 0.2)
eta <- (-0.00018468194429807232 + alpha*(2.7140277221213913 -
alpha*(0.876012944101314 + alpha*2.51929256972748)))
}
m <- matrix((z + ifelse(runif(length(z)) > alpha, 0, 1))%%2,
byrow=TRUE, ncol=7)
colnames(m) <- paste0("x", 1:7)
ans<-cbind(as.data.frame.matrix(m), digit=rep(factor(0:9),n))
title <- paste("Electronic Digit Recognition Problem, alpha =",
round(alpha, 5),
"BayesRate =", round(eta, 5))
if(!silent) {
cat(title, fill=TRUE)
}
attr(ans, "title") <- title
ans
} |
library(tidyverse)
library(gganimate)
library(ggthemes)
set.seed(32322)
df <- data.frame(Control = c(rep("Control",300),rep("Treatment",300)),
Time=rep(c(rep("Before",150),rep("After",150)),2),
Group = rep(c(rep("Group A",75),rep("Group B",75)),4),
GroupTime=rep(c(rep("Group A Before",75),rep("Group B Before",75),
rep("Group A After",75),rep("Group B After",75)),2)) %>%
mutate(Y = 2+.5*(Control=="Treatment")+.5*(Time=="After") +
.2*(Control=="Treatment")*(Time=="After")+
.4*(GroupTime=="Group B After" & Control == "Treatment")+
2.6*(Group=="Group B")+
rnorm(600)/4,state="1",
xaxisTime = (Time == "Before") + 2*(Time == "After") + (runif(600)-.5)*.95) %>%
group_by(Control,GroupTime) %>%
mutate(mean_Y=mean(Y)) %>%
ungroup()
df$Time <- factor(df$Time,levels=c("Before","After"))
dfseg <- df %>%
group_by(Control,GroupTime) %>%
summarize(mean_Y = mean(mean_Y)) %>%
ungroup()
diffA <- filter(dfseg,GroupTime=='Group A After',Control=='Control')$mean_Y[1] - filter(dfseg,GroupTime=='Group A Before',Control=='Control')$mean_Y[1]
diffB <- filter(dfseg,GroupTime=='Group B After',Control=='Control')$mean_Y[1] - filter(dfseg,GroupTime=='Group B Before',Control=='Control')$mean_Y[1]
DIDA <- filter(dfseg,GroupTime=='Group A After',Control=='Treatment')$mean_Y[1] - filter(dfseg,GroupTime=='Group A Before',Control=='Treatment')$mean_Y[1] - diffA
dffull <- rbind(
df %>% mutate(state='1. Start with raw data.'),
df %>% mutate(state='2. See how Y is explained by Treatment, Time and/or Group.'),
df %>% mutate(Y = mean_Y,state="3. Keep only what's explained by Treatment, Time, and/or Group."),
df %>% mutate(Y = mean_Y,state="4. See how Control changed over Time in each Group."),
df %>% mutate(Y = mean_Y
- (Time=='After')*ifelse(Group=="Group A",diffA,diffB),
state="5. Remove the Before/After difference in each groups."),
df %>% mutate(Y = mean_Y
- (Time=='After')*ifelse(Group=="Group A",diffA,diffB),
state='6. The remaining Before/After difference is the diff-in-diff in each Group.'),
df %>% mutate(Y = mean_Y
- (Time=='After')*ifelse(Group=="Group A",diffA,diffB) - (Time=='After' & Control == "Treatment")*DIDA,
state='7. Remove the difference-in-difference effect from Group A.'),
df %>% mutate(Y = mean_Y
- (Time=='After')*ifelse(Group=="Group A",diffA,diffB) - (Time=='After' & Control == "Treatment")*DIDA,
state='8. The remaining Before/After in Group B is the diff-in-diff-in-diff.')
)
p <- ggplot(dffull,aes(y=Y,x=xaxisTime,color=as.factor(Control)))+geom_point()+
guides(color=guide_legend(title="Group"))+
geom_vline(aes(xintercept=1.5),linetype='dashed')+
geom_hline(aes(yintercept=4),col='black',size=1)+
scale_color_colorblind()+
scale_x_continuous(
breaks = c(1, 2),
label = c("Before Treatment", "After Treatment")
)+xlab("Time")+
scale_y_continuous(
breaks = c(2.5, 5.5),
label = c("Y for Group A", "Y for Group B")
)+ylab("")+
theme(axis.text.y=element_text(angle=90,hjust=.5,size=14),
axis.text.x=element_text(size=14),
legend.text=element_text(size=14))+
geom_segment(aes(x=ifelse(state %in% c('2. See how Y is explained by Treatment, Time and/or Group.',"3. Keep only what's explained by Treatment, Time, and/or Group."),
.5,NA),
xend=1.5,y=filter(dfseg,GroupTime=='Group A Before',Control=='Control')$mean_Y[1],
yend=filter(dfseg,GroupTime=='Group A Before',Control=='Control')$mean_Y[1]),size=1,color='black')+
geom_segment(aes(x=ifelse(state %in% c('2. See how Y is explained by Treatment, Time and/or Group.',"3. Keep only what's explained by Treatment, Time, and/or Group."),
.5,NA),
xend=1.5,y=filter(dfseg,GroupTime=='Group A Before',Control=='Treatment')$mean_Y[1],
yend=filter(dfseg,GroupTime=='Group A Before',Control=='Treatment')$mean_Y[1]),size=1,color="
geom_segment(aes(x=ifelse(state %in% c('2. See how Y is explained by Treatment, Time and/or Group.',"3. Keep only what's explained by Treatment, Time, and/or Group."),
1.5,NA),
xend=2.5,y=filter(dfseg,GroupTime=='Group A After',Control=='Control')$mean_Y[1],
yend=filter(dfseg,GroupTime=='Group A After',Control=='Control')$mean_Y[1]),size=1,color='black')+
geom_segment(aes(x=ifelse(state %in% c('2. See how Y is explained by Treatment, Time and/or Group.',"3. Keep only what's explained by Treatment, Time, and/or Group."),
1.5,NA),
xend=2.5,y=filter(dfseg,GroupTime=='Group A After',Control=='Treatment')$mean_Y[1],
yend=filter(dfseg,GroupTime=='Group A After',Control=='Treatment')$mean_Y[1]),size=1,color="
geom_segment(aes(x=ifelse(state %in% c('2. See how Y is explained by Treatment, Time and/or Group.',"3. Keep only what's explained by Treatment, Time, and/or Group."),
.5,NA),
xend=1.5,y=filter(dfseg,GroupTime=='Group B Before',Control=='Control')$mean_Y[1],
yend=filter(dfseg,GroupTime=='Group B Before',Control=='Control')$mean_Y[1]),size=1,color='black')+
geom_segment(aes(x=ifelse(state %in% c('2. See how Y is explained by Treatment, Time and/or Group.',"3. Keep only what's explained by Treatment, Time, and/or Group."),
.5,NA),
xend=1.5,y=filter(dfseg,GroupTime=='Group B Before',Control=='Treatment')$mean_Y[1],
yend=filter(dfseg,GroupTime=='Group B Before',Control=='Treatment')$mean_Y[1]),size=1,color="
geom_segment(aes(x=ifelse(state %in% c('2. See how Y is explained by Treatment, Time and/or Group.',"3. Keep only what's explained by Treatment, Time, and/or Group."),
1.5,NA),
xend=2.5,y=filter(dfseg,GroupTime=='Group B After',Control=='Control')$mean_Y[1],
yend=filter(dfseg,GroupTime=='Group B After',Control=='Control')$mean_Y[1]),size=1,color='black')+
geom_segment(aes(x=ifelse(state %in% c('2. See how Y is explained by Treatment, Time and/or Group.',"3. Keep only what's explained by Treatment, Time, and/or Group."),
1.5,NA),
xend=2.5,y=filter(dfseg,GroupTime=='Group B After',Control=='Treatment')$mean_Y[1],
yend=filter(dfseg,GroupTime=='Group B After',Control=='Treatment')$mean_Y[1]),size=1,color="
geom_segment(aes(x=1.5,xend=1.5,
y=ifelse(state=="4. See how Control changed over Time in each Group.",
filter(dfseg,GroupTime=='Group B Before',Control=='Control')$mean_Y[1]+diffB,
ifelse(state=="5. Remove the Before/After difference in each groups.",
filter(dfseg,GroupTime=='Group B Before',Control=='Control')$mean_Y[1],NA)),
yend=filter(dfseg,GroupTime=='Group B Before',Control=='Control')$mean_Y[1]),size=1.5,color='blue')+
geom_segment(aes(x=1.5,xend=1.5,
y=ifelse(state=="4. See how Control changed over Time in each Group.",
filter(dfseg,GroupTime=='Group A Before',Control=='Control')$mean_Y[1]+diffA,
ifelse(state=="5. Remove the Before/After difference in each groups.",
filter(dfseg,GroupTime=='Group A Before',Control=='Control')$mean_Y[1],NA)),
yend=filter(dfseg,GroupTime=='Group A Before',Control=='Control')$mean_Y[1]),size=1.5,color='blue')+
geom_segment(aes(x=1.5,xend=1.5,
y=ifelse(state=='6. The remaining Before/After difference is the diff-in-diff in each Group.',
filter(dfseg,GroupTime=='Group A After',Control=='Treatment')$mean_Y[1]-diffA,
ifelse(state=='7. Remove the difference-in-difference effect from Group A.',
filter(dfseg,GroupTime=='Group A Before',Control=='Treatment')$mean_Y[1],NA)),
yend=filter(dfseg,GroupTime=='Group A Before',Control=='Treatment')$mean_Y[1]),size=1.5,color='blue')+
geom_segment(aes(x=1.5,xend=1.5,
y=ifelse(state=='8. The remaining Before/After in Group B is the diff-in-diff-in-diff.',
filter(dfseg,GroupTime=='Group B After',Control=='Treatment')$mean_Y[1]-diffA-DIDA,NA),
yend=filter(dfseg,GroupTime=='Group B Before',Control=='Treatment')$mean_Y[1]),size=1.5,color='blue')+
labs(title = 'The Difference-in-Difference-in-Difference Effect of Treatment \n{next_state}')+
transition_states(state,transition_length=c(6,16,6,16,6,16,16,6),state_length=c(50,22,12,22,30,50,50,50),wrap=FALSE)+
ease_aes('sine-in-out')+
exit_fade()+enter_fade()
animate(p,nframes=250) |
print.SK <- function(x,
digits=2L,
...)
{
cat('Results\n')
print(x$out$Result,
...)
cat('\nSig.level\n',
x$out$Sig.level)
cat('\n\nStatistics\n')
print(x$stat,
digits=digits,
...)
cat('\n\nClusters\n')
cc <- x$clus
i <- 0
while(i < length(cc)){
i <- i+1
cat(paste('
gro <- strsplit(cc[[i]],',')
cat(gro[[1]][1],sep='\n',fill=TRUE,labels = "{G1}:")
cat(gro[[1]][2],sep='\n',fill=TRUE,labels = "{G2}:")
}
} |
loon_reactive.l_hist <- function(loon.grob, output.grob, linkingInfo, buttons, position, selectBy,
linkingGroup, input, colorList, tabPanelName, outputInfo) {
plotBrush <- input$plotBrush
plotClick <- input$plotClick
loonWidgetsInfo <- outputInfo$loonWidgetsInfo
pull <- input[[paste0(tabPanelName, "pull")]]
initialDisplay <- is.null(output.grob)
if(!initialDisplay && (input[["navBarPage"]] != tabPanelName || pull > buttons["pull"])) {
if(pull > buttons["pull"]) {
buttons["pull"] <- pull
linkingGroup <- isolate(input[[paste0(tabPanelName, "linkingGroup")]])
}
if(linkingGroup != "none") {
linkedInfo <- linkingInfo[[linkingGroup]]
order <- match(loonWidgetsInfo$linkingKey, linkedInfo$linkingKey)
modifiedLinkingInfo <- set_linkingInfo(
loon.grob = loon.grob,
output.grob = output.grob,
linkedInfo = linkedInfo,
linkedStates = input[[paste0(tabPanelName, "linkedStates")]],
tabPanelName = tabPanelName,
order = order,
loonWidgetsInfo = loonWidgetsInfo
)
selected <- linkedInfo$selected
brushId <- which(selected)
selectByColor <- linkedInfo$selectByColor
loonWidgetsInfo <- modifiedLinkingInfo$loonWidgetsInfo
output.grob <- modifiedLinkingInfo$output.grob
} else {
brushId <- outputInfo$brushId
selectByColor <- outputInfo$selectByColor
}
} else {
output.grob <- loon.grob
loonColor <- loonWidgetsInfo$loonColor
plotAxes1 <- input[[paste0(tabPanelName, "plotAxes1")]]
plotAxes2 <- input[[paste0(tabPanelName, "plotAxes2")]]
plotShow <- input[[paste0(tabPanelName, "plotShow")]]
swapInShiny <- "swap" %in% plotAxes1
swapInLoon <- loonWidgetsInfo$swapInLoon
loonWidgetsInfo$swapInShiny <- swapInShiny
yshows <- input[[paste0(tabPanelName, "yshows")]]
loonWidgetsInfo$yshows <- yshows
rangeChangedBydensity <- FALSE
origin <- input[[paste0(tabPanelName, "origin")]] - 1e-8
loonWidgetsInfo$origin <- origin
if(abs(buttons["origin"] - origin) > 1e-6) {
if(yshows == "density") rangeChangedBydensity <- TRUE
buttons["origin"] <- origin
}
binwidth <- input[[paste0(tabPanelName, "binwidth")]]
loonWidgetsInfo$binwidth <- binwidth
if(abs(buttons["binwidth"] - binwidth) > 1e-6) {
if(yshows == "density") rangeChangedBydensity <- TRUE
buttons["binwidth"] <- binwidth
}
showStackedColors <- "stackedColors" %in% plotShow
loonWidgetsInfo$showStackedColors <- showStackedColors
showOutlines <- "outlines" %in% plotShow
loonWidgetsInfo$showOutlines <- showOutlines
colorFill <- loonWidgetsInfo$colorFill
colorOutline <- loonWidgetsInfo$colorOutline
color <- loonWidgetsInfo$color
N <- loonWidgetsInfo$N
modifyReactive <- input[[paste0(tabPanelName, "modifyReactive")]]
if (modifyReactive > buttons["reactive"]) {
buttons["reactive"] <- modifyReactive
loonWidgetsInfo$active <- rep(TRUE, N)
}
active <- loonWidgetsInfo$active
binInfo <- get_binInfo(data = loonWidgetsInfo$x,
origin = origin, active = active,
binwidth = binwidth, yshows = yshows)
binId <- binInfo$binId
binX <- binInfo$binX
binHeight <- binInfo$binHeight
binxy <- get_binxy(binX = binX, binId = binId, binwidth = binwidth,
yshows = yshows, color = color, n = N)
scaleToPlot <- input[[paste0(tabPanelName, "scaleToPlot")]]
scaleToWorld <- input[[paste0(tabPanelName, "scaleToWorld")]]
scaleToLayer <- input[[paste0(tabPanelName, "scaleToLayer")]]
sliderxlim <- input[[paste0(tabPanelName, "xlim")]]
sliderylim <- input[[paste0(tabPanelName, "ylim")]]
plotViewXlim <- grDevices::extendrange(c(binxy$xmin, binxy$xmax))
plotViewYlim <- grDevices::extendrange(c(binxy$ymin, binxy$ymax))
loonWidgetsInfo$plotViewXlim <- plotViewXlim
loonWidgetsInfo$plotViewYlim <- plotViewYlim
currentLayerName <- input[[paste0(tabPanelName, "layer")]]
newLayerLabel <- isolate(input[[paste0(tabPanelName, "newLayerLabel")]])
layerSet <- input[[paste0(tabPanelName, "layerSet")]]
if(layerSet > buttons["layerSet"]) {
buttons["layerSet"] <- layerSet
if(newLayerLabel == "") {
message("no valid label")
layers <- loonWidgetsInfo$layers
layersName <- names(layers)
currentLayer <- layers[which(layersName == currentLayerName)]
} else {
layers <- loonWidgetsInfo$layers
layersName <- names(layers)
whichLayerIsEdited <- which(layersName == currentLayerName)
layersName[whichLayerIsEdited] <- newLayerLabel
names(layers) <- layersName
loonWidgetsInfo$layers <- layers
currentLayer <- layers[whichLayerIsEdited]
}
} else {
layers <- loonWidgetsInfo$layers
layersName <- names(layers)
currentLayer <- layers[which(layersName == currentLayerName)]
}
layerMinus <- input[[paste0(tabPanelName, "layerMinus")]]
if(layerMinus > buttons["layerMinus"]) {
buttons["layerMinus"] <- layerMinus
loon.grob <- grid::setGrob(
gTree = loon.grob,
gPath = currentLayer,
newGrob = nullGrob(name = currentLayer)
)
output.grob <- grid::setGrob(
gTree = loon.grob,
gPath = currentLayer,
newGrob = nullGrob(name = currentLayer)
)
worldView <-get_worldViewPort(loon.grob = loon.grob, parent = "histogram",
parentExcluded = TRUE)
if(swapInLoon) {
layerYlim <- worldView$xlim
layerXlim <- worldView$ylim
} else {
layerXlim <- worldView$xlim
layerYlim <- worldView$ylim
}
loonWidgetsInfo$layerXlim <- layerXlim
loonWidgetsInfo$layerYlim <- layerYlim
}
worldViewXlim <- range(c(plotViewXlim, loonWidgetsInfo$layerXlim))
worldViewYlim <- range(c(plotViewYlim, loonWidgetsInfo$layerYlim))
if(swapInLoon != swapInShiny) {
output.grob <- swap_layer_grob(output.grob, parent = "histogram")
}
if(swapInShiny) {
xlabel <- loonWidgetsInfo$ylabel
ylabel <- loonWidgetsInfo$xlabel
if(scaleToPlot > buttons["plot"] || rangeChangedBydensity) {
if(scaleToPlot > buttons["plot"])
buttons["plot"] <- scaleToPlot
ylim <- plotViewXlim
xlim <- plotViewYlim
} else if(scaleToWorld > buttons["world"]) {
buttons["world"] <- scaleToWorld
ylim <- worldViewXlim
xlim <- worldViewYlim
} else if(scaleToLayer > buttons["scaleToLayer"] && length(currentLayer) > 0) {
buttons["scaleToLayer"] <- scaleToLayer
if(currentLayer == "histogram") {
xlim <- loonWidgetsInfo$plotViewYlim
ylim <- loonWidgetsInfo$plotViewXlim
} else {
layerLimits <- get_layer_worldView(loon.grob, layer = currentLayer)
xlim <- layerLimits$ylim
ylim <- layerLimits$xlim
}
} else {
ylim <- sliderxlim
xlim <- sliderylim
}
} else {
xlabel <- loonWidgetsInfo$xlabel
ylabel <- loonWidgetsInfo$ylabel
if(scaleToPlot > buttons["plot"] || rangeChangedBydensity) {
if(scaleToPlot > buttons["plot"])
buttons["plot"] <- scaleToPlot
xlim <- plotViewXlim
ylim <- plotViewYlim
} else if(scaleToWorld > buttons["world"]) {
buttons["world"] <- scaleToWorld
xlim <- worldViewXlim
ylim <- worldViewYlim
} else if (scaleToLayer > buttons["scaleToLayer"] && length(currentLayer) > 0) {
buttons["scaleToLayer"] <- scaleToLayer
if(currentLayer == "histogram") {
xlim <- loonWidgetsInfo$plotViewXlim
ylim <- loonWidgetsInfo$plotViewYlim
} else {
layerLimits <- get_layer_worldView(loon.grob, layer = currentLayer)
xlim <- layerLimits$xlim
ylim <- layerLimits$ylim
}
} else {
xlim <- sliderxlim
ylim <- sliderylim
}
}
loonWidgetsInfo$xlim <- xlim
loonWidgetsInfo$ylim <- ylim
xaxis <- grid.pretty(xlim)
yaxis <- grid.pretty(ylim)
title <- loonWidgetsInfo$title
loonMargins <- loonWidgetsInfo$loonDefaultMargins
margins <- rep(0, 4)
if("scales" %in% plotAxes1) {
output.grob <- set_scales_grob(loon.grob = output.grob,
xaxis = xaxis,
yaxis = yaxis)
margins <- margins + loonMargins$scalesMargins
loonWidgetsInfo$showScales <- TRUE
} else {
output.grob <- grid::setGrob(
gTree = output.grob,
gPath = "axes",
newGrob = nullGrob(name = "axes")
)
loonWidgetsInfo$showScales <- FALSE
}
if("labels" %in% plotAxes2) {
if(yshows == "density") {
if(swapInShiny) {
xlabel <- "Density"
} else {
ylabel <- "Density"
}
} else {
if(swapInShiny) {
xlabel <- "Frequency"
} else {
ylabel <- "Frequency"
}
}
output.grob <- set_labelsGrob(
loon.grob = output.grob,
showScales = loonWidgetsInfo$showScales,
xlabel = xlabel,
ylabel = ylabel,
title = title
)
if(is.null(xlabel) || xlabel == "") loonMargins$labelMargins[1] <- loonMargins$minimumMargins[1]
if(is.null(ylabel) || ylabel == "") loonMargins$labelMargins[2] <- loonMargins$minimumMargins[2]
if(is.null(title) || title == "") loonMargins$labelMargins[3] <- loonMargins$minimumMargins[3]
margins <- margins + loonMargins$labelMargins
loonWidgetsInfo$showLabels <- TRUE
} else {
output.grob <- grid::setGrob(
gTree = output.grob,
gPath = "labels",
newGrob = nullGrob(name = "labels")
)
loonWidgetsInfo$showLabels <- FALSE
}
if(loonWidgetsInfo$showLabels | loonWidgetsInfo$showScales) margins <- apply(cbind(margins, loonMargins$minimumMargins), 1, max)
if("guides" %in% plotAxes2) {
output.grob <- set_guidesGrob(loon.grob = output.grob,
xaxis = xaxis,
yaxis = yaxis,
loonColor = loonColor)
loonWidgetsInfo$showGuides <- TRUE
} else {
output.grob <- grid::setGrob(
gTree = output.grob,
gPath = "guides",
newGrob = nullGrob(name = "guides")
)
loonWidgetsInfo$showGuides <- FALSE
}
output.grob <- set_viewPort_grob(
loon.grob = output.grob,
margins = margins,
xlim = xlim,
ylim = ylim
)
output.grob <- set_boundaryGrob(loon.grob = output.grob,
margins = margins,
loonColor = loonColor)
vp <- grid::vpStack(
grid::plotViewport(margins = margins, name = "plotViewport"),
grid::dataViewport(xscale = xlim,
yscale = ylim,
name = "dataViewport")
)
brushId <- if(initialDisplay) {
outputInfo$brushId
} else {
if(is.null(plotBrush) && is.null(plotClick)) {
outputInfo$brushId
} else {
if(!is.null(position))
get_brushId(
loon.grob = output.grob,
coord = binxy,
swapInShiny = swapInShiny,
position = position,
brushInfo = plotBrush,
vp = vp,
clickInfo = plotClick
)
}
}
loonWidgetsInfo$offset <- get_offset(vp = vp,
l = plotBrush$domain$left %||% plotClick$domain$left %||% -0.04,
r = plotBrush$domain$right %||% plotClick$domain$right %||% 1.04,
b = plotBrush$domain$bottom %||% plotClick$domain$bottom %||% -0.04,
t = plotBrush$domain$top %||% plotClick$domain$top %||% 1.04)
selectDynamic <- input[[paste0(tabPanelName, "selectDynamic")]]
sticky <- input[[paste0(tabPanelName, "sticky")]]
selectByColor <- input[[paste0(tabPanelName, "selectByColor")]]
if(sticky == "off") {
if(!is.null(selectByColor)) {
loonWidgetsInfo$lastSelection <- if(!is.null(plotBrush) || !is.null(plotClick)) brushId else integer(0)
brushId <- which(color %in% selectByColor)
} else {
if(!is.null(outputInfo$selectByColor))
brushId <- loonWidgetsInfo$lastSelection
}
if("deselect" == selectDynamic) {
if(!is.null(plotBrush) || !is.null(plotClick)) brushId <- integer(0)
}
} else {
if(!is.null(selectByColor)) {
whichIsSelected <- union(which(color %in% selectByColor),
which(loonWidgetsInfo$selected))
} else {
whichIsSelected <- which(loonWidgetsInfo$selected)
}
if("invert" == selectDynamic) {
if(is.null(plotBrush)) {
brushId <- whichIsSelected
} else {
brushId <- union(setdiff(whichIsSelected, brushId),
setdiff(brushId, whichIsSelected))
}
} else if("deselect" == selectDynamic) {
if(is.null(plotBrush)) {
brushId <- whichIsSelected
} else {
brushId <- setdiff(whichIsSelected, brushId)
}
} else {
if(is.null(plotBrush)) {
brushId <- whichIsSelected
} else {
brushId <- union(whichIsSelected, brushId)
}
}
}
selectStaticAll <- input[[paste0(tabPanelName, "selectStaticAll")]]
selectStaticNone <- input[[paste0(tabPanelName, "selectStaticNone")]]
selectStaticInvert <- input[[paste0(tabPanelName, "selectStaticInvert")]]
if(selectStaticAll > buttons["all"]) {
buttons["all"] <- selectStaticAll
brushId <- seq(N)
} else if(selectStaticNone > buttons["none"]) {
buttons["none"] <- selectStaticNone
brushId <- integer(0)
} else if(selectStaticInvert > buttons["invert"]) {
buttons["invert"] <- selectStaticInvert
brushId <- setdiff(seq(N), brushId)
} else NULL
loonWidgetsInfo$selected <- rep(FALSE, N)
loonWidgetsInfo$selected[brushId] <- TRUE
colorApply <- input[[paste0(tabPanelName, "colorApply")]]
colorListButtons <- setNames(
lapply(colorList, function(col) input[[paste0(tabPanelName, col)]]),
colorList
)
colorPicker <- isolate(input[[paste0(tabPanelName, "colorPicker")]])
if(colorApply > buttons["colorApply"]) {
buttons["colorApply"] <- colorApply
color[brushId] <- colorPicker
loonWidgetsInfo$color <- color
}
for(col in colorList) {
if(colorListButtons[[col]] > buttons[col]) {
buttons[col] <- colorListButtons[[col]]
color[brushId] <- col
loonWidgetsInfo$color <- color
}
}
modifyDeactive <- input[[paste0(tabPanelName, "modifyDeactive")]]
if(modifyDeactive > buttons["deactive"]) {
buttons["deactive"] <- modifyDeactive
if(length(brushId) > 0) {
active[brushId] <- FALSE
loonWidgetsInfo$active <- active
binInfo <- get_binInfo(data = loonWidgetsInfo$x, origin = origin, active = active,
binwidth = binwidth, yshows = yshows)
binId <- binInfo$binId
binX <- binInfo$binX
binHeight <- binInfo$binHeight
binxy <- get_binxy(binX = binX, binId = binId, binwidth = binwidth,
yshows = yshows, color = color, n = sum(active))
plotViewXlim <- grDevices::extendrange(c(binxy$xmin, binxy$xmax))
plotViewYlim <- grDevices::extendrange(c(binxy$ymin, binxy$ymax))
loonWidgetsInfo$plotViewXlim <- plotViewXlim
loonWidgetsInfo$plotViewYlim <- plotViewYlim
}
}
whichIsDeactive <- which(!active)
output.grob <- get_hist_grob(loon.grob = output.grob, yshows = yshows,
binId = binId, binX = binX, binHeight = binHeight, binwidth = binwidth,
n = N, swapAxes = swapInShiny,
showStackedColors = showStackedColors, showOutlines = showOutlines,
color = color, colorFill = colorFill, colorOutline = colorOutline)
output.grob <- highlight_selected_bin_grob(loon.grob = output.grob, yshows = yshows, active = active, selected = loonWidgetsInfo$selected,
binId = binId, binX = binX, binHeight = binHeight, binwidth = binwidth, n = N,
swapAxes = swapInShiny, showStackedColors = showStackedColors, showOutlines = showOutlines,
color = color, colorFill = colorFill, colorOutline = colorOutline,
loonColor = loonColor)
layerUp <- input[[paste0(tabPanelName, "layerUp")]]
layerDown <- input[[paste0(tabPanelName, "layerDown")]]
layerVisible <- input[[paste0(tabPanelName, "layerVisible")]]
layerInvisible <- input[[paste0(tabPanelName, "layerInvisible")]]
layerPlus <- input[[paste0(tabPanelName, "layerPlus")]]
if(layerUp > buttons["layerUp"]) {
buttons["layerUp"] <- layerUp
loon.grob <- move_layerUp_grob(loon.grob = loon.grob,
currentLayer = currentLayer,
parent = "l_hist_layers")
output.grob <- move_layerUp_grob(loon.grob = output.grob,
currentLayer = currentLayer,
parent = "l_hist_layers")
}
if(layerDown > buttons["layerDown"]) {
buttons["layerDown"] <- layerDown
loon.grob <- move_layerDown_grob(loon.grob = loon.grob,
currentLayer = currentLayer,
parent = "l_hist_layers")
output.grob <- move_layerDown_grob(loon.grob = output.grob,
currentLayer = currentLayer,
parent = "l_hist_layers")
}
if(layerVisible > buttons["layerVisible"]) {
buttons["layerVisible"] <- layerVisible
loon.grob <- move_layerVisible_grob(loon.grob = loon.grob,
currentLayer = currentLayer)
output.grob <- move_layerVisible_grob(loon.grob = output.grob,
currentLayer = currentLayer)
}
if(layerInvisible > buttons["layerInvisible"]) {
buttons["layerInvisible"] <- layerInvisible
loon.grob <- move_layerInvisible_grob(loon.grob = loon.grob,
currentLayer = currentLayer)
output.grob <- move_layerInvisible_grob(loon.grob = output.grob,
currentLayer = currentLayer)
}
if(layerPlus > buttons["layerPlus"]) {
buttons["layerPlus"] <- layerPlus
message("adding layers has not been inplemented so far")
}
push <- input[[paste0(tabPanelName, "push")]]
if(push > buttons["push"]) {
buttons["push"] <- push
linkingGroup <- isolate(input[[paste0(tabPanelName, "linkingGroup")]])
} else {
newLinkingGroup <- isolate(input[[paste0(tabPanelName, "linkingGroup")]])
if(newLinkingGroup == "none") linkingGroup <- newLinkingGroup else NULL
}
linkingInfo <- update_linkingInfo(loon.grob,
tabPanelName = tabPanelName,
linkingInfo = linkingInfo,
linkingGroup = linkingGroup,
linkingKey = loonWidgetsInfo$linkingKey,
selected = loonWidgetsInfo$selected,
color = loonWidgetsInfo$color,
active = loonWidgetsInfo$active,
selectByColor = selectByColor,
linkedStates = input[[paste0(tabPanelName, "linkedStates")]])
}
list(
output.grob = output.grob,
loon.grob = loon.grob,
outputInfo = list(
brushId = brushId,
selectByColor = selectByColor,
linkingGroup = linkingGroup,
linkingInfo = linkingInfo,
loonWidgetsInfo = loonWidgetsInfo,
buttons = buttons
)
)
} |
NULL
the <- new.env(parent = emptyenv())
as_lookup <- function(x, envir = parent.frame(), ...) {
UseMethod("as_lookup")
}
as_lookup.lookup <- function(x, envir = parent.frame(), ...) {
x
}
as_lookup.character <- function(x, envir = parent.frame(), ...) {
res <- list()
tryCatch({
res[c("package", "name")] <- parse_name(x)
res$def <- get(res$name, envir = res$package %||% envir, mode = "function")
res$package <- res$package %||% function_package(res$def)
res$type <- typeof(res$def)
res$visible <- is_visible(res$name)
}, error = function(e) NULL)
class(res) <- "lookup"
res
}
as_lookup.getAnywhere <- function(x, ...) {
lapply(which(!x$dups), function(idx) {
package <- sub("^registered S3 method for [^ ]+ from namespace (\\w+):?.*", "\\1", x$where[[idx]])
package <- sub("^namespace:", "", package)
package <- sub("^package:", "", package)
def <- x$objs[[idx]]
structure(
list(
package = package,
name = x$name,
def = def,
type = typeof(def),
visible = x$visible[[idx]]),
class = "lookup")
})
}
function_package <- function(x) {
if (is.primitive(x)) {
return("base")
}
e <- topenv(environment(x))
nme <- environmentName(e)
if (!nzchar(nme)) {
stop("Could not find associated package", call. = FALSE)
}
nme
}
find_fun_name <- function(x, env) {
for (name in ls(env, all.names = TRUE)) {
if (name == ".Last.value") { next }
if (exists(name, envir = env) &&
identical(x, get(name, envir = env))) {
return(name)
}
}
stop("Function does not exist in ", bq(capture.output(print.default(env))), call. = FALSE)
}
as_lookup.function <- function(x, envir = environment(x), name = substitute(x)) {
res <- list(def = x)
tryCatch({
res$package <- function_package(res$def)
env <- topenv(envir)
res$name <- find_fun_name(x, env)
res$type <- typeof(res$def)
res$visible <- is_visible(res$name)},
error = function(e) NULL)
class(res) <- "lookup"
res
}
as_lookup.MethodDefinition <- function(x, envir = environment(x), name = substitute(x)) {
res <- list(def = x)
res$package <- function_package(res$def)
res$name <- x@generic
res$type <- typeof(res$def)
if (!is(res$def, "genericFunction")) {
res$signature <- methodSignatureMatrix(x)
}
res$visible <- TRUE
class(res) <- "lookup"
res
}
lookup <- function(x, name = substitute(x), envir = environment(x) %||% baseenv(), all = FALSE, ...) {
fun <- as_lookup(x, envir = envir, name = name)
if (is.null(fun$type)) {
return(fun$def)
}
if (fun$type %in% c("builtin", "special")) {
fun$internal <- list(lookup_function(fun$name, type = "internal"))
} else {
fun$internal <- lapply(call_names(fun$def, type = ".Internal", subset = c(2, 1)), lookup_function, type = "internal")
fun$external <- lapply(call_names(fun$def, type = ".External", subset = c(2)), lookup_function, type = "external", package = fun$package)
fun$ccall <- lapply(call_names(fun$def, type = c(".C", ".Call", ".Call2"), subset = c(2)), lookup_function, type = "call", package = fun$package)
}
if (uses_rcpp(fun$package)) {
rcpp_exports <- rcpp_exports(fun$package)
fun$ccall <- c(fun$ccall, lapply(call_names(fun$def, type = rcpp_exports, subset = c(1)), lookup_function, type = "rcpp", package = fun$package))
}
if (isS4(fun$def)) {
if (is(fun$def, "genericFunction")) {
fun$type <- append(fun$type, "S4 generic", 0)
fun$S4_methods <- lookup_S4_methods(fun, envir = envir, all = all)
} else {
fun$type <- append(fun$type, "S4 method")
}
} else {
if (is_s3_method(fun$name, env = envir)) {
fun$type <- append(fun$type, "S3 method", 0)
}
if (is_s3_generic(fun$name, env = envir)) {
fun$type <- append(fun$type, "S3 generic", 0)
fun$S3_methods <- lookup_S3_methods(fun, envir = envir, all = all)
if (.isMethodsDispatchOn()) {
fun$S4_methods <- lookup_S4_methods(fun, envir = envir, all = all)
}
}
}
the$last_lookup <- fun
fun
}
loaded_functions <- memoise(function(envs = loadedNamespaces()) {
fnames <- lapply(envs,
function(e) ls(envir = asNamespace(e), all.names = TRUE))
data.frame(name = unlist(fnames),
package = rep.int(envs, lengths(fnames)),
stringsAsFactors = FALSE)
})
print.function <- function(x, ...) print.lookup(lookup(x, ...))
setMethod("show", "genericFunction", function(object) print(lookup(object)))
parse_name <- function(x) {
split <- strsplit(x, ":::?")[[1]]
if (length(split) == 2) {
list(package = split[[1]],
name = split[[2]])
} else {
list(package = NULL,
name = split[[1]])
}
}
`%==%` <- function(x, y) {
identical(x, as.name(y))
}
lookup_S3_methods <- function(f, envir = parent.frame(), all = FALSE, ...) {
S3_methods <- suppressWarnings(.S3methods(f$name, envir = envir))
if (length(S3_methods) == 0) {
return()
}
res <- flatten_list(lapply(S3_methods, function(name) as_lookup(getAnywhere(name))), "lookup")
pkgs <- vapply(res, `[[`, character(1), "package")
nms <- vapply(res, `[[`, character(1), "name")
visible <- vapply(res, `[[`, logical(1), "visible")
funs <- paste0(pkgs, ifelse(visible, "::", ":::"), nms)
res <- method_dialog(funs, res, "S3")
lapply(res, lookup)
}
lookup_S4_methods <- function(f, envir = parent.frame(), all = FALSE, ...) {
S4_methods <- .S4methods(f$name)
if (length(S4_methods) == 0) {
return()
}
info <- attr(S4_methods, "info")
signatures <- strsplit(sub(paste0("^", escape(f$name), ",", "(.*)-method$"), "\\1", S4_methods), ",")
res <- Map(getMethod, f$name, signatures)
missing_pkg <- !nzchar(info$from)
info$from[missing_pkg] <- lapply(res[missing_pkg], function(x) getNamespaceName(topenv(environment(x))))
funs <- paste0(info$from, ifelse(info$visible, "::", ":::"), info$generic, "(", lapply(signatures, paste0, collapse = ", "), ")")
res <- method_dialog(funs, res, "S4")
lapply(res, lookup)
}
globalVariables("View", "lookup")
print.lookup <-
local({
level <- 0
function(x, ..., envir = parent.frame(), highlight = !in_rstudio() && crayon::has_color(), in_console = getOption("lookup.in_console", rstudioapi::isAvailable())) {
force(x)
force(highlight)
if (in_completion_function() || !is.list(x) || is.null(x$type)) {
cat(highlight_output(base::print.function(x), language = "r", highlight), sep = "\n")
return(invisible(x))
}
level <<- level + 1
on.exit(level <<- level - 1)
str <- capture.output(type = "output", {
colons <- if (x$visible) "::" else ":::"
name <- paste0(bold(x$package, colons, x$name, sep = ""), " [", paste(collapse = ", ", x$type), "]")
filename <- utils::getSrcFilename(x$def)
if (length(filename) > 0) {
ref <- utils::getSrcref(x$def)
name <- paste0(name, " ", crayon::blue(filename, "
}
cat(name, "\n")
if (!is.null(x$signature)) {
cat("getMethod(\"", x$name, "\", c(", paste0(collapse = ", ", "\"", x$signature[1, ], "\""), "))\n", sep = "")
}
def <-
if (isS4(x$def)) {
[email protected]
} else {
x$def
}
if (isTRUE(in_console)) {
View(def, title = name)
} else {
cat(highlight_output(base::print.function(def), language = "r", highlight), sep = "\n")
}
lapply(x[["internal"]], print, envir = envir, highlight = highlight, in_console = in_console)
lapply(x[["external"]], print, envir = envir, highlight = highlight, in_console = in_console)
lapply(x[["ccall"]], print, envir = envir, highlight = highlight, in_console = in_console)
lapply(x[["S3_methods"]], print, envir = envir, highlight = highlight, in_console = in_console)
lapply(x[["S4_methods"]], print, envir = envir, highlight = highlight, in_console = in_console)
invisible()
})
if (level == 1 && should_page(str)) {
page_str(str)
} else if (!isTRUE(in_console)) {
cat(str, sep = "\n")
}
invisible(x)
}
})
escape <- function(x) {
chars <- c("*", ".", "?", "^", "+", "$", "|", "(", ")", "[", "]", "{", "}", "\\")
gsub(paste0("([\\", paste0(collapse = "\\", chars), "])"), "\\\\\\1", x, perl = TRUE)
}
highlight_output <- function(code, language = "r", color = TRUE) {
out <- capture.output(force(code))
if (isTRUE(color)) {
if (language == "c++") {
language <- "c"
}
highlight_string(out, language = language)
} else {
out
}
}
attached_functions <- memoise(function(sp = search()) {
fnames <- lapply(seq_along(sp), ls)
data.frame(name = unlist(fnames),
package = rep.int(sub("package:", "", sp, fixed = TRUE), lengths(fnames)),
stringsAsFactors = FALSE)
})
is_visible <- function(x) {
funs <- attached_functions()
any(funs$name == x)
}
print.getAnywhere <- function(x, ...) {
package <- grepl("^package:", x$where)
namespace <- grepl("^namespace:", x$where)
defs <- x$objs[namespace]
name <- if (any(package)) {
paste0(sub("package:", "", x$where[package]), "::", x$name)
} else if (any(namespace)) {
paste0(sub("namespace:", "", x$where[namespace]), ":::", x$name)
} else {
x$name
}
cat(bold(name), "\n")
lapply(defs, print)
invisible()
}
source_url <- function(x, ...) UseMethod("source_url")
source_url.lookup <- function(x = the$last_lookup, ...) {
stopifnot(inherits(x, "lookup"))
links <- character()
for (nme in c("internal", "external", "ccall", "S3_methods", "S4_methods")) {
links <- append(links, vapply(x[[nme]], source_url, character(1)))
}
links
}
source_url.compiled <- function(x, ...) {
if (x$remote_type == "local") {
x$url
} else {
paste0(x$url, "
}
}
lookup_browse <- function(x = the$last_lookup) {
stopifnot(inherits(x, "lookup"))
browseURL(tail(source_url(x), n = 1))
} |
PrintModelList <-function (operators=FALSE, internal=FALSE,
newstyle=TRUE) {
stopifnot(internal <=2, internal >=0, operators<=1, operators>=0)
.C(C_PrintModelList, as.integer(internal), as.integer(operators),
as.integer(newstyle))
invisible()
}
showManpages <- function(path="/home/schlather/svn/RandomFields/RandomFields/man") {
files <- dir(path)
result <- character(length(files))
for (i in 1:length(files)) {
cat("\n\n\n\n\n")
system(paste("grep \"\\examples\" -A 10000 ", path, "/", files[i], sep=""))
result[i] <- readline(files[i])
}
result <- cbind(files, result)
result <- result[result[, 2]!= "", ]
result[result[, 2]=="t", 2] <- "To Do"
result[result[, 2]=="s", 2] <- "dontshow"
return(result)
}
compareVersions <- function(path = "~/svn", package="RandomFields",
subpaths=c("cran", package)) {
path <- paste(path, package, subpaths[1], sep="/")
l <- list(list(subpath=paste(path, package, subpaths[2], "R", sep="/"),
pattern="*R"),
list(subpath=paste0(path, package, subpaths[2], "/src", sep="/"),
pattern="*\\.h"),
list(subpath = paste0(path, package, subpaths[2], "/src", sep="/"),
pattern = "*\\.cc"))
for (i in 1:length(l)) {
subpath <- l[[i]]$subpath
pattern <- l[[i]]$pattern
files <- dir(path=subpath, pattern=pattern)
for (f in files) {
cmd <- paste("diff ", path, "/", subpath, "/", f, " ",
subpath,"/", f, sep="")
Print(cmd)
system(cmd)
}
}
}
jpegORpdf <- function(graphics=NULL) {
GD <- getOption("device")
ispdf <- is.logical(all.equal(GD, "pdf"))
isjpg <- is.logical(all.equal(GD, "jpeg"))
if (!ispdf && !isjpg) {
ispdf <- is.function(GD) && is.logical(all.equal(args(pdf), args(GD)))
isjpg <- is.function(GD) && is.logical(all.equal(args(jpeg), args(GD)))
}
if (is.null(graphics)) graphics <- RFoptions()$graphics
file <- graphics$file
if (file != "") {
f <- strsplit(file, "\\.")[[1]]
ext <- tolower(f[length(f)])
is_pdf <- ext == "pdf"
is_jpg <- ext == "jpeg" || ext == "jpg"
if (is_pdf || is_jpg) graphics$file <- paste(f[-length(f)], sep=".")
if (ispdf || isjpg) {
if ((is_pdf && isjpg) || (is_jpg && ispdf)) stop("'extension' does not fit given device")
} else {
ispdf <- is_pdf
isjpg <- is_jpg
}
}
if (ispdf) GD <- pdf
else if (isjpg) GD <- jpeg
graphics$ispdf <- ispdf
graphics$isjpg <- isjpg
graphics$ext <- c(".pdf", ".jpg")[isjpg + 1]
graphics$GD <- GD
return(graphics)
}
ScreenDevice <- function(height, width) {
graphics <- jpegORpdf()
if (graphics$ispdf || graphics$isjpg) {
if (graphics$filenumber == 99999)
stop("number of pictures exceeds max. number of pictures")
file <- graphics$file
if (file != "") {
if (!graphics$onefile) {
file <- paste(file,
formatC(format="d", flag="0", graphics$filenumber,
width=5),
graphics$ext, sep="")
RFoptions(graphics.filenumber = graphics$filenumber + 1)
} else file <- paste(file, graphics$ext, sep="")
if (graphics$ispdf)
graphics$GD(height=height, width=width, onefile=FALSE, file=file)
else if (graphics$isjpg) graphics$GD(height=height, width=width,
file=file, units="in", res=graphics$resolution)
else stop("device not recognized by 'RandomFields'")
return()
} else {
if (graphics$isjpg) stop("'file' in 'RFoptions' not set.")
}
}
args <- names(as.list(args(graphics$GD)))
if (all(c("width", "height") %in% args) &&
( !any(c("file", "filename") %in% args)) || graphics$ispdf) {
graphics$GD(height=height, width=width)
return()
}
if (RFoptions()$internal$warn_aspect_ratio) {
RFoptions(warn_aspect_ratio = FALSE)
cat("The graphical device does not seem to be a standard screen device. Hence the\naspect ratio might not be correct. (This message appears only one per session.)")
}
}
ArrangeDevice <- function(graphics, figs, dh=2.8, h.outer=1.2,
dw = 2.5, w.outer=0.7) {
H <- curH <- graphics$height
curW <- graphics$width
if (is.finite(H) && H>0) {
if (is.na(graphics$width) || graphics$width<=0.0) {
H <- H * pmin(1, graphics$increase_upto[1] / figs[1],
graphics$increase_upto[2] / figs[2])
DH <- H * dh / (dh + h.outer)
HO <- H - DH
curH <- figs[1] * DH + HO
W <- H * (dw + w.outer) / (dh + h.outer)
DW <- W * dw / (dw + w.outer)
WO <- W - DW
curW <- figs[2] * DW + WO
}
graphics <- jpegORpdf(graphics)
jpg_pdf <- graphics$isjpg || graphics$ispdf
if (is.na(graphics$always_open_device)) {
open <- interactive() || jpg_pdf
RFoptions(graphics.always_open_device = open)
} else open <- graphics$always_open_device
if (length(dev.list()) > 0 && open) {
close <- graphics$always_close_device
if (is.na(close)) close <- jpg_pdf
if (close) dev.off()
}
if (open) {
ScreenDevice(height=curH, width=curW)
}
} else warning("device could not be opened as 'height' (=", H,
") is not positive.")
if (graphics$split_screen) {
if (length(dev.list()) > 0 && any(par()$mfcol != 1)) par(mfcol=c(1,1))
} else {
if (any(figs != 1) && length(dev.list()) > 0) par(mfcol=figs)
}
return(c(curH, curW))
}
ShowInstallErrors <- function(dir, pkgs)
for (i in 1:length(pkgs)) {
cat(pkgs[i], "\n")
for (f in c("00install.out", "00check.log"))
system(paste("grep [eE][rR][rR][oO][rR] ", dir, "/", pkgs[i],
".Rcheck/", f, sep=""))
}
StartExample <- function(reduced = TRUE, save.seed=TRUE) {
if (save.seed) {
RFopt <- RFoptions()
assign("RandomFields_options", envir=.RandomFields.env, RFopt)
}
if (!interactive()) {
REDUCED <- reduced
RFoptions(examples_reduced = REDUCED)
}
}
FinalizeExample <- function() {
if (!interactive()) {
close.screen(all.screens = TRUE)
n <- length(dev.list()) - 2
if (n > 0) {
for (i in 1:n) {
dev.off()
}
}
}
options <- get("RandomFields_options", envir=.RandomFields.env)
options$examples_reduced <- FALSE
RFoptions(LIST = options)
}
checkExamples <- function(exclude=NULL, include=1:length(.fct.list),
ask=FALSE, echo=TRUE, halt=FALSE, ignore.all=FALSE,
path=package, package="RandomFields",
read.rd.files=TRUE, local = TRUE,
libpath = NULL, single.runs = FALSE) {
.exclude <- exclude
.ask <- ask
.echo <- echo
.halt <- halt
.ignore.all <- ignore.all
.package <- package
.path <- path
.local <- local
useDynLib <- importClassesFrom <- import <-
importFrom <- exportClasses <-
importMethodsFrom <- exportMethods <- S3method <- function(...) NULL
.env <- new.env()
stopifnot(is.na(RFoptions()$basic$seed))
exportPattern <- function(p) {
if (p == "^R\\.") p <- "^R."
all.pattern <- p %in% c("^[^\\.]", "^[^.]", ".") | get("all.pattern", .env)
if (!.ignore.all) assign("all.pattern", all.pattern, .env)
if (all.pattern) return(NULL)
stopifnot(nchar(p)==3, substr(p,1,1)=="^")
assign("p", c(get("p", .env), substring(p, 2)), .env)
}
export <- function(...) {
dots <- match.call(expand.dots = FALSE)$...
z <-deparse(substitute(...))
if (length(dots) && !all(sapply(dots, function(x) is.symbol(x) ||
is.character(x))))
stop("... must contain names or character strings")
z <- sapply(dots, as.character)
cat("export", z, "\n")
assign("export", c(get("export", .env), z), .env)
}
import <- importClassesFrom <- importMethodsFrom <- importFrom <- useDynLib <-
exportClasses <- S3method <- exportMethods <-
function(...) {
dots <- match.call(expand.dots = FALSE)$...
}
assign("export", NULL, .env)
assign("all.pattern", FALSE, .env)
assign("p", NULL, .env)
cat("'source' causes problems in valgrind")
.content <- readLines(paste(.path, "NAMESPACE", sep="/"), -1)
eval(parse(text = .content))
cat("\tend source\n")
if (is.logical(read.rd.files) && !read.rd.files) {
.package.env <- parent.env(.GlobalEnv)
while (attr(.package.env, "name") != paste("package:", .package, sep="")) {
.package.env <- parent.env(.package.env)
}
.orig.fct.list <- ls(envir=.package.env)
.ok <- (get("all.pattern", .env) |
substr(.orig.fct.list, 1, 1) %in% get("p", .env) |
.orig.fct.list %in% get("export", .env))
.fct.list <- .orig.fct.list[.ok]
} else {
if (is.logical(read.rd.files))
.path <- paste("./", .path, "/man", sep="")
else .path <- read.rd.files
.files <- dir(.path, pattern="d$")
.fct.list <- character(length(.files))
for (i in 1:length(.files)) {
.fn <- paste(.path, .files[i], sep="/")
.content <- readLines(.fn, n = 2)
if (substr(.content[1], 1, 5) != "\\name" &&
(substr(.content[1], 1, 1) != "%" || substr(.content[2], 1, 5) != "\\name"))
stop(.files[i], " does not start with '\\name' -- what at least in 2018 has caused problems in valgrind")
.content <- scan(.fn, what=character(), quiet=TRUE)
.content <- strsplit(.content, "alias\\{")
.content <- .content[which(lapply(.content, length) > 1)][[1]][2]
.fct.list[i] <-
strsplit(strsplit(.content,"\\}")[[1]][1], ",")[[1]][1]
}
}
.include <- if (is.numeric(include)) include else 1:99999
.include.name <- include
RFoptions(graphics.close_screen = TRUE, graphics.split_screen = TRUE)
.RFopt <- RFoptions()
.not_working_no <- .not_working <- NULL
.included.fl <- .fct.list[.include]
.not.isna <- !is.na(.included.fl)
.include <- .include[.not.isna]
.included.fl <- .included.fl[.not.isna]
.max.fct.list <- max(.included.fl)
if (single.runs) {
file.in <- "example..R"
file.out <- "example..Rout"
if (file.exists(file.out)) file.remove(file.out)
}
if (is.character(.include.name)) {
.include.name <- sapply(strsplit(.include.name, ".Rd"), function(x) x[1])
}
ENVIR <- new.env()
.allwarnings <- list()
for (.idx in .include) {
if (is.character(.include.name) && !(.fct.list[.idx] %in% .include.name))
next
try(repeat dev.off(), silent=TRUE)
if (.idx %in% .exclude) next
cat("\n\n\n\n\n", .idx, " ", .package, ":", .fct.list[.idx],
" (total=", length(.fct.list), ") \n", sep="")
RFoptions(LIST=.RFopt)
.C(C_ResetWarnings, as.integer(FALSE))
if (.echo) cat(.idx, "")
.tryok <- TRUE
if (single.runs) {
txt <- paste("library(", package,", ", libpath, "); example(",
.fct.list[.idx],
", ask =", .ask,
", echo =", .echo,
")", sep="")
write(file=file.in, txt)
command <- paste("R < ", file.in, ">>", file.out)
} else {
.res <- try(do.call(utils::example, list(.fct.list[.idx], ask=.ask,
echo=.echo, local=.local)))
w <- warnings()
.allwarnings <- c(.allwarnings, list(c("Help page ", .idx)), w)
print(w)
if (is(.res, "try-error")) {
if (.halt) {
stop("\n\n\t***** ",.fct.list[.idx], " (", .idx,
" out of ", max(.include), "). has failed. *****\n\n")
} else {
.not_working_no <- c(.not_working_no, .idx)
.not_working <- c(.not_working, .fct.list[.idx])
.tryok <- FALSE
}
}
RFoptions(storing = FALSE)
cat("****** '", .fct.list[.idx], "' (", .idx, ") done. ******\n")
if (.tryok && !is.na(RFoptions()$basic$seed)) {
Print(.not_working, paste(.not_working_no, collapse=", "),
RFoptions()$basic$seed)
stop("seed not NA: ", .fct.list[.idx])
}
}
}
Print(.not_working, paste(.not_working_no, collapse=", "))
.ret <- list(.not_working, .not_working_no)
names(.ret) <- c(.package, "")
return(.ret)
}
maintainers.machine <- function() .Call(C_maintainers_machine) |
bivariateNormal <-
function(rho=0, layout=c(3,3), lwd=.2,
angle=c(22.5, 67.5, 112.5, 337.5, 157.5, 292.5, 247.5, 202.5),
col.regions=trellis.par.get("regions")$col, ...)
{
x <- seq(-2, 2, length=33)
y <- x
fxy <- 1/(2*pi*sqrt(1-rho^2)) *
exp(-.5/(1-rho^2) * outer(x^2, y^2, "+") - 2*rho*outer(x,y,"*"))
n.angle <- length(angle)
Angle <- rep(angle, rep(length(fxy), n.angle))
Viewing.Angle <- ordered(Angle, angle)
wireframe(rep(fxy, n.angle) ~ rep(x[row(fxy)], n.angle) * rep(y[col(fxy)], n.angle) |
Viewing.Angle, r=rho, layout=layout, lwd=lwd, ...,
panel = function(x, y, subscripts, z, angle, ...)
{
w <- unique(angle[subscripts])
panel.wireframe(x=x, y=y, subscripts=subscripts, z=z,
screen = list(z = w, x = -60, y = 0), ...)
},
angle = Angle,
strip = strip.custom(strip.names = TRUE, style = "1", sep=": "),
skip = c(FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE),
drape = TRUE, distance = 0.3,
main = as.expression(substitute("Bivariate Normal, " * rho == r,
c(alist(rho=rho), list(r=rho)))),
xlab = list("x", cex = 0.6),
ylab = list("y", cex = 0.6),
zlab = list("f(x,y)", cex = 0.6))
} |
augment.mixpoissonreg <- function(x, data = stats::model.frame(x), newdata = NULL, type.predict = c("response", "link", "precision", "variance"),
type.residuals = c("pearson", "score"), se_fit = FALSE, conf_int = TRUE, pred_int = FALSE, ...) {
.index <- .resid <- .resfit <- NULL
type.predict <- rlang::arg_match(type.predict)
type.residuals <- rlang::arg_match(type.residuals)
if(is.null(newdata)){
newdata = stats::model.frame(x)
res <- stats::residuals(x, type = type.residuals)
} else{
res <- NULL
}
df <- as_tibble(newdata)
pred <- stats::predict(x, newdata = newdata, type = type.predict, se.fit = se_fit)
if(se_fit){
df$.fitted <- pred$fit %>% unname()
df$.se.fit <- pred$se.fit %>% unname()
} else{
df$.fitted <- pred %>% unname()
}
if(conf_int){
conf_int <- stats::predict(x, newdata = newdata, type = type.predict, interval = "confidence")
df$.fittedlwrconf <- conf_int[, "lwr"] %>% unname()
df$.fitteduprconf <- conf_int[, "upr"] %>% unname()
}
if(pred_int){
pred_int <- stats::predict(x, newdata = newdata, type = "response", interval = "prediction", ...)
df$.fittedlwrpred <- pred_int[, "lwr"] %>% unname()
df$.fitteduprpred <-pred_int[, "upr"] %>% unname()
}
if(!is.null(res)){
df$.resid <- res
df$.resfit <- stats::residuals(x, type = x$residualname)
df$.hat <- stats::hatvalues(x, parameters = "mean") %>% unname()
df$.cooksd <- stats::cooks.distance(x, type = "CD", hat = "mean") %>% unname()
df$.gencooksd <- stats::cooks.distance(x, type = "GCD", hat = "mean") %>% unname()
env <- x$envelope
if (!is.null(env)) {
df$.index <- 1:nrow(df)
temp_tbl <- tibble(.resfit = df$.resfit, .index = df$.index)
temp_tbl <- temp_tbl %>% dplyr::arrange(.resfit)
temp_tbl$.lwrenv <- env[3,]
temp_tbl$.mdnenv <- env[2,]
temp_tbl$.uprenv = env[1,]
df <- dplyr::left_join(df, temp_tbl, by = c(".index", ".resfit")) %>% select(-.index)
}
}
df
}
glance.mixpoissonreg <- function(x, ...){
tibble(efron.pseudo.r2 = as.numeric(x$efron.pseudo.r2), df.null = x$df.null,
logLik = as.numeric(stats::logLik(x)), AIC = stats::AIC(x),
BIC = stats::BIC(x), df.residual = stats::df.residual(x),
nobs = stats::nobs(x), model.type = x$modeltype, est.method = x$estimation_method)
}
tidy.mixpoissonreg <- function(x, conf.int = FALSE, conf.level = 0.95, ...){
join_term <- NULL
retmean <- as_tibble(summary(x)$coefficients$mean, rownames = "term")
colnames(retmean) <- c("term", "estimate", "std.error", "statistic",
"p.value")
retmean <- retmean %>% add_column(component = "mean", .before = "term")
retprec <- as_tibble(summary(x)$coefficients$precision, rownames = "term")
colnames(retprec) <- c("term", "estimate", "std.error", "statistic",
"p.value")
retprec <- retprec %>% add_column(component = "precision", .before = "term")
ret <- dplyr::bind_rows(retmean,retprec)
if (conf.int) {
ret$join_term <- names(stats::coef(x, parameters = "all"))
ci <- as_tibble(stats::confint(x, level = conf.level), rownames = "term")
names(ci) <- c("join_term", "conf.low", "conf.high")
ret <- dplyr::left_join(ret, ci, by = "join_term") %>% select(-join_term)
}
ret
}
autoplot.mixpoissonreg <- function(object, which = c(1,2,5,6), title = list("Residuals vs Obs. number",
"Normal Q-Q",
"Cook's distance",
"Generalized Cook's distance",
"Cook's dist vs Generalized Cook's dist",
"Response vs Fitted means"),
title.bold = FALSE,
title.size = NULL,
title.colour = NULL,
label.repel = TRUE,
x.axis.col = NULL,
y.axis.col = NULL,
x.axis.size = NULL,
y.axis.size = NULL,
cook.plot.type = "linerange",
cook.plot.pointshape = NULL,
nrow = NULL, ncol = NULL,
qqline = TRUE, ask = prod(graphics::par("mfcol")) <
length(which) && grDevices::dev.interactive(), include.modeltype = TRUE,
include.residualtype = FALSE,
sub.caption = NULL,
sub.caption.col = NULL,
sub.caption.size = NULL,
sub.caption.face = NULL,
sub.caption.hjust = 0.5,
env_alpha = 0.5, env_fill = "grey70", gpar_sub.caption = list(fontface = "bold"),
colour = "
shape = NULL, label = TRUE, label.label = NULL, label.colour = "
label.alpha = NULL, label.size = NULL, label.angle = NULL,
label.family = NULL, label.fontface = NULL, label.lineheight = NULL,
label.hjust = NULL, label.vjust = NULL,
label.n = 3, ad.colour = "
p1 <- p2 <- p3 <- p4 <- p5 <- p6 <- NULL
.resid <- .cooksd <- .gencooksd <- .obs <- .fitted <-.lwrenv <- .uprenv <- .mdnenv <- NULL
if (is.null(sub.caption)) {
cal <- object$call
if (!is.na(m.f <- match("formula", names(cal)))) {
cal <- cal[c(1, m.f)]
names(cal)[2L] <- ""
}
cc <- deparse(cal, 80)
nc <- nchar(cc[1L], "c")
abbr <- length(cc) > 1 || nc > 75
sub.caption <- if (abbr)
paste(substr(cc[1L], 1L, min(75L, nc)), "...")
else cc[1L]
}
plot.data <- augment(object, type.residuals = object$residualname, type.predict = "response")
n <- stats::nobs(object)
plot.data$.index <- 1:n
if(is.null(label.label)){
plot.data$.label <- rownames(plot.data)
} else{
plot.data$.label <- as.vector(label.label)
}
if(is.null(object$y)){
y = object$residuals + object$fitted.values
} else{
y = object$y
}
if(2 %in% which){
ylim <- range(plot.data$.resid, na.rm = TRUE)
ylim[2L] <- ylim[2L] + diff(ylim) * 0.075
qx <- stats::qqnorm(plot.data$.resid, ylim = ylim,
plot.it = FALSE)$x
plot.data$.qqx <- qx
qprobs <- c(0.25, 0.75)
qy <- stats::quantile(plot.data$.resid, probs = qprobs,
names = FALSE, type = 7, na.rm = TRUE)
qx <- stats::qnorm(qprobs)
slope <- diff(qy)/diff(qx)
int <- qy[1L] - slope * qx[1L]
}
plot.data$.obs <- as.vector(y)
plot_label <- function (p, data, x = NULL, y = NULL, label = TRUE, label.label = "rownames",
label.colour = NULL, label.alpha = NULL, label.size = NULL,
label.angle = NULL, label.family = NULL, label.fontface = NULL,
label.lineheight = NULL, label.hjust = NULL, label.vjust = NULL,
label.repel = FALSE, label.show.legend = NA)
{
if (!is.data.frame(data)) {
stop(paste0("Unsupported class: ", class(data)))
}
if (!missing(label.colour) && !is.null(label.colour) && missing(label)) {
label <- TRUE
}
if (label || label.repel) {
if (is.null(label.colour)) {
label.colour <- "
}
if (label.repel) {
textfunc <- ggrepel::geom_text_repel
}
else {
textfunc <- ggplot2::geom_text
}
p <- p + geom_factory(textfunc, data, x = x, y = y, label = ".label",
colour = label.colour, alpha = label.alpha, size = label.size,
angle = label.angle, family = label.family, fontface = label.fontface,
lineheight = label.lineheight, hjust = label.hjust,
vjust = label.vjust, show.legend = label.show.legend)
}
p
}
flatten <- function (df)
{
ismatrix <- vapply(df, is.matrix, logical(1))
if (any(ismatrix)) {
return(data.frame(c(df[!ismatrix], do.call(data.frame,
df[ismatrix])), stringsAsFactors = FALSE))
}
else {
return(df)
}
}
geom_factory <- function (geomfunc, data = NULL, ...)
{
mapping <- list()
option <- list()
columns <- colnames(data)
for (key in names(list(...))) {
value <- list(...)[[key]]
if (is.null(value)) {
}
else if (value %in% columns) {
mapping[[key]] <- value
}
else {
option[[key]] <- value
}
}
if (!is.null(data)) {
option[["data"]] <- data
}
option[["mapping"]] <- do.call(ggplot2::aes_string, mapping)
return(do.call(geomfunc, option))
}
if (is.logical(shape) && !shape) {
if (missing(label)) {
label <- TRUE
}
if (missing(label.n)) {
label.n <- nrow(plot.data)
}
}
dev_ask <- is.null(nrow) & is.null(ncol)
if(dev_ask){
if (ask) {
oask <- grDevices::devAskNewPage(TRUE)
on.exit(grDevices::devAskNewPage(oask))
}
}
plot.data <- flatten(plot.data)
if(any(c(1,2) %in% which)){
residualname <- paste0(toupper(substring(object$residualname, 1, 1)), substring(object$residualname, 2))
}
if (label.n > 0L) {
if (any(c(1,2,6) %in% which)) {
r.data <- dplyr::arrange(plot.data, dplyr::desc(abs(.resid)))
r.data <- utils::head(r.data, label.n)
}
if (3 %in% which) {
cd.data <- dplyr::arrange(plot.data, dplyr::desc(abs(.cooksd)))
cd.data <- utils::head(cd.data, label.n)
}
if (4 %in% which){
gcd.data <- dplyr::arrange(plot.data, dplyr::desc(abs(.gencooksd)))
gcd.data <- utils::head(gcd.data, label.n)
}
if(5 %in% which){
cdgcd.data <- dplyr::arrange(plot.data, dplyr::desc((.gencooksd/sum(.gencooksd))^2 + (.cooksd/sum(.cooksd))^2))
cdgcd.data <- utils::head(cdgcd.data, label.n)
}
if(6 %in% which){
respobs.data <- dplyr::arrange(plot.data, dplyr::desc(abs(.obs - .fitted)))
respobs.data <- utils::head(respobs.data, label.n)
}
}
.decorate.label <- function(p, data) {
if (label & label.n > 0) {
p <- plot_label(p = p, data = data, label = label,
label.label = ".label", label.colour = label.colour,
label.alpha = label.alpha, label.size = label.size,
label.angle = label.angle, label.family = label.family,
label.fontface = label.fontface, label.lineheight = label.lineheight,
label.hjust = label.hjust, label.vjust = label.vjust,
label.repel = label.repel)
}
p
}
.decorate.plot <- function(p, xlab = NULL, ylab = NULL, title = NULL) {
if(title.bold){
p + ggplot2::xlab(xlab) + ggplot2::ylab(ylab) + ggplot2::ggtitle(title) +
theme(plot.title = element_text(size = title.size,
face = "bold", colour = title.colour))
} else{
p + ggplot2::xlab(xlab) + ggplot2::ylab(ylab) + ggplot2::ggtitle(title) +
theme(plot.title = element_text(size = title.size,
colour = title.colour))
}
}
if (1 %in% which) {
if(include.residualtype){
title[[1]] = paste(residualname, title[[1]])
}
ylab <- paste0(residualname, " residuals")
if(include.modeltype){
title[[1]] <- paste0(title[[1]], " - ", object$modeltype, " Regression")
}
t1 <- title[[1]]
mapping <- ggplot2::aes_string(x = ".index", y = ".resid")
p1 <- ggplot2::ggplot(data = plot.data, mapping = mapping)
if (!is.logical(shape) || shape) {
p1 <- p1 + geom_factory(geom_point, plot.data, colour = colour,
size = size, linetype = linetype, alpha = alpha,
fill = fill, shape = shape)
}
p1 <- p1 + ggplot2::geom_hline(yintercept = 0L, linetype = ad.linetype,
size = ad.size, colour = ad.colour)
p1 <- .decorate.label(p1, r.data)
xlab = "Obs. number"
p1 <- .decorate.plot(p1, xlab = xlab, ylab = ylab,
title = t1) + theme(axis.title.x = element_text(colour = x.axis.col, size = x.axis.size),
axis.title.y = element_text(colour = y.axis.col, size = y.axis.size))
if(dev_ask){
p1 <- p1 + labs(caption = sub.caption) + theme(plot.caption = element_text(color = sub.caption.col,
face = sub.caption.face,
size = sub.caption.size,
hjust = sub.caption.hjust))
print(p1)
}
}
if(2 %in% which){
env <- object$envelope
if (!is.null(env)) {
title[[2]] <- paste0(title[[2]]," with simulated envelopes")
}
if(include.modeltype){
title[[2]] <- paste0(title[[2]], " - ", object$modeltype, " Regression")
}
t2 <- title[[2]]
mapping <- ggplot2::aes_string(x = ".qqx", y = ".resid")
p2 <- ggplot2::ggplot(data = plot.data, mapping = mapping)
if(qqline & is.null(env)){
p2 <- p2 + ggplot2::geom_abline(intercept = int, slope = slope,
linetype = ad.linetype, size = ad.size, colour = ad.colour)
}
if(!is.null(env)){
p2 <- p2 + ggplot2::geom_ribbon(aes(ymin=.lwrenv, ymax=.uprenv), alpha=env_alpha, fill = env_fill)
p2 <- p2 + ggplot2::geom_line(aes(y = .mdnenv), linetype = ad.linetype, size = ad.size, colour = ad.colour)
}
if (!is.logical(shape) || shape) {
p2 <- p2 + geom_factory(geom_point, plot.data, colour = colour,
size = size, linetype = linetype, alpha = alpha,
fill = fill, shape = shape)
}
ylab <- paste0(residualname, " residuals")
xlab = "Theoretical Quantiles"
p2 <- .decorate.label(p2, r.data)
p2 <- .decorate.plot(p2, xlab = xlab,
ylab = ylab, title = t2) + theme(axis.title.x = element_text(colour = x.axis.col, size = x.axis.size),
axis.title.y = element_text(colour = y.axis.col, size = y.axis.size))
if(dev_ask){
p2 <- p2 + labs(caption = sub.caption) + theme(plot.caption = element_text(color = sub.caption.col,
face = sub.caption.face,
size = sub.caption.size,
hjust = sub.caption.hjust))
print(p2)
}
}
if(3 %in% which){
if(include.modeltype){
title[[3]] <- paste0(title[[3]], " - ", object$modeltype, " Regression")
}
t3 <- title[[3]]
mapping <- ggplot2::aes_string(x = ".index", y = ".cooksd",
ymin = 0, ymax = ".cooksd")
p3 <- ggplot2::ggplot(data = plot.data, mapping = mapping)
if (!is.logical(shape) || shape) {
if(cook.plot.type == "linerange"){
p3 <- p3 + geom_factory(geom_linerange, plot.data,
colour = colour, size = size, linetype = linetype,
alpha = alpha, fill = fill, shape = shape)
} else if(cook.plot.type == "points"){
p3 <- p3 + geom_factory(geom_point, plot.data,
colour = colour, size = size, linetype = linetype,
alpha = alpha, fill = fill, shape = cook.plot.pointshape)
}
}
p3 <- .decorate.label(p3, cd.data)
xlab = "Obs. Number"
p3 <- .decorate.plot(p3, xlab = xlab, ylab = "Cook's distance",
title = t3) + theme(axis.title.x = element_text(colour = x.axis.col, size = x.axis.size),
axis.title.y = element_text(colour = y.axis.col, size = y.axis.size))
if(dev_ask){
p3 <- p3 + labs(caption = sub.caption) + theme(plot.caption = element_text(color = sub.caption.col,
face = sub.caption.face,
size = sub.caption.size,
hjust = sub.caption.hjust))
print(p3)
}
}
if(4 %in% which){
if(include.modeltype){
title[[4]] <- paste0(title[[4]], " - ", object$modeltype, " Regression")
}
t4 <- title[[4]]
mapping <- ggplot2::aes_string(x = ".index", y = ".gencooksd",
ymin = 0, ymax = ".gencooksd")
p4 <- ggplot2::ggplot(data = plot.data, mapping = mapping)
if (!is.logical(shape) || shape) {
if(cook.plot.type == "linerange"){
p4 <- p4 + geom_factory(geom_linerange, plot.data,
colour = colour, size = size, linetype = linetype,
alpha = alpha, fill = fill, shape = shape)
} else if(cook.plot.type == "points"){
p4 <- p4 + geom_factory(geom_point, plot.data,
colour = colour, size = size, linetype = linetype,
alpha = alpha, fill = fill, shape = cook.plot.pointshape)
}
}
p4 <- .decorate.label(p4, gcd.data)
xlab = "Obs. Number"
p4 <- .decorate.plot(p4, xlab = xlab, ylab = "Generalized Cook's distance",
title = t4) + theme(axis.title.x = element_text(colour = x.axis.col, size = x.axis.size),
axis.title.y = element_text(colour = y.axis.col, size = y.axis.size))
if(dev_ask){
p4 <- p4 + labs(caption = sub.caption) + theme(plot.caption = element_text(color = sub.caption.col,
face = sub.caption.face,
size = sub.caption.size,
hjust = sub.caption.hjust))
print(p4)
}
}
if (5 %in% which) {
if(include.modeltype){
title[[5]] <- paste0(title[[5]], " - ", object$modeltype, " Regression")
}
t5 <- title[[5]]
mapping <- ggplot2::aes_string(x = ".gencooksd", y = ".cooksd")
p5 <- ggplot2::ggplot(data = plot.data, mapping = mapping)
if (!is.logical(shape) || shape) {
p5 <- p5 + geom_factory(geom_point, plot.data, colour = colour,
size = size, linetype = linetype, alpha = alpha,
fill = fill, shape = shape)
}
p5 <- p5 + ggplot2::geom_hline(yintercept = 0L, linetype = ad.linetype,
size = ad.size, colour = ad.colour)
p5 <- .decorate.label(p5, cdgcd.data)
xlab = "Generalized Cook's distance"
p5 <- .decorate.plot(p5, xlab = xlab, ylab = "Cook's distance",
title = t5) + theme(axis.title.x = element_text(colour = x.axis.col, size = x.axis.size),
axis.title.y = element_text(colour = y.axis.col, size = y.axis.size))
if(dev_ask){
p5 <- p5 + labs(caption = sub.caption) + theme(plot.caption = element_text(color = sub.caption.col,
face = sub.caption.face,
size = sub.caption.size,
hjust = sub.caption.hjust))
print(p5)
}
}
if (6 %in% which) {
if(include.modeltype){
title[[6]] <- paste0(title[[6]], " - ", object$modeltype, " Regression")
}
t6 <- title[[6]]
mapping <- ggplot2::aes_string(x = ".fitted", y = ".obs")
p6 <- ggplot2::ggplot(data = plot.data, mapping = mapping)
if (!is.logical(shape) || shape) {
p6 <- p6 + geom_factory(geom_point, plot.data, colour = colour,
size = size, linetype = linetype, alpha = alpha,
fill = fill, shape = shape)
}
p6 <- p6 + ggplot2::geom_abline(intercept = 0L, slope = 1L, linetype = ad.linetype,
size = ad.size, colour = ad.colour)
p6 <- .decorate.label(p6, respobs.data)
xlab = "Predicted values"
p6 <- .decorate.plot(p6, xlab = xlab, ylab = "Response values",
title = t6) + theme(axis.title.x = element_text(colour = x.axis.col, size = x.axis.size),
axis.title.y = element_text(colour = y.axis.col, size = y.axis.size))
if(dev_ask){
p6 <- p6 + labs(caption = sub.caption) + theme(plot.caption = element_text(color = sub.caption.col,
face = sub.caption.face,
size = sub.caption.size,
hjust = sub.caption.hjust))
print(p6)
}
}
if(!dev_ask){
grDevices::devAskNewPage(ask = FALSE)
plot.list <- list(p1, p2, p3, p4, p5, p6)[which]
gpar_multi <- do.call(grid::gpar, gpar_sub.caption)
title_multi <- grid::textGrob(sub.caption, gp=gpar_multi)
gridExtra::grid.arrange(grobs = plot.list, top = title_multi, nrow = nrow, ncol = ncol)
grDevices::devAskNewPage(ask = grDevices::dev.interactive())
} else{
invisible()
}
}
tidy_local_influence.mixpoissonreg <- function(model, perturbation = c("case_weights", "hidden_variable",
"mean_explanatory", "precision_explanatory",
"simultaneous_explanatory"), curvature = c("conformal", "normal"),
direction = c("canonical", "max.eigen"), parameters = c("all", "mean", "precision"),
mean.covariates = NULL, precision.covariates = NULL, ...){
loc_infl <- suppressWarnings(local_influence(model, perturbation = perturbation, curvature = curvature, direction = direction,
parameters = parameters, mean.covariates = mean.covariates, precision.covariates = precision.covariates))
tidy_loc_infl <- tibble(.rows = stats::nobs(model))
for(pert in perturbation){
tidy_loc_infl = tidy_loc_infl %>% add_column(!!pert := loc_infl[[pert]])
}
tidy_loc_infl
}
local_influence_benchmarks.mixpoissonreg <- function(model, perturbation = c("case_weights", "hidden_variable",
"mean_explanatory", "precision_explanatory",
"simultaneous_explanatory"), curvature = c("conformal", "normal"),
direction = c("canonical", "max.eigen"), parameters = c("all", "mean", "precision"),
mean.covariates = NULL, precision.covariates = NULL, ...){
loc_infl <- local_influence(model, perturbation = perturbation, curvature = curvature, direction = direction,
parameters = parameters, mean.covariates = mean.covariates, precision.covariates = precision.covariates)
benchmarks <- c()
for(pert in perturbation){
benchmarks <- c(benchmarks, attr(loc_infl[[pert]], "benchmark"))
}
benchmarks <- matrix(benchmarks, nrow = 1)
colnames(benchmarks) <- perturbation
benchmarks_tbl <- as_tibble(benchmarks)
benchmarks_tbl
}
local_influence_autoplot.mixpoissonreg <- function(model, which = c(1,2,3,4), title = list("Case Weights Perturbation",
"Hidden Variable Perturbation",
"Mean Explanatory Perturbation",
"Precision Explanatory Perturbation",
"Simultaneous Explanatory Perturbation"),
title.size = NULL,
title.bold = FALSE,
title.colour = NULL,
x.axis.col = NULL,
y.axis.col = NULL,
x.axis.size = NULL,
y.axis.size = NULL,
type.plot = "linerange",
curvature = c("conformal", "normal"),
direction = c("canonical", "max.eigen"), parameters = c("all", "mean", "precision"),
mean.covariates = NULL, precision.covariates = NULL,
label.repel = TRUE,
nrow = NULL, ncol = NULL,
ask = prod(graphics::par("mfcol")) <
length(which) && grDevices::dev.interactive(), include.modeltype = TRUE,
sub.caption = NULL,
sub.caption.col = NULL,
sub.caption.size = NULL,
sub.caption.face = NULL,
sub.caption.hjust = 0.5,
gpar_sub.caption = list(fontface = "bold"), detect.influential = TRUE, n.influential = 5,
draw.benchmark = FALSE,
colour = "
shape = NULL, label = TRUE, label.label = NULL, label.colour = "
label.alpha = NULL, label.size = NULL, label.angle = NULL,
label.family = NULL, label.fontface = NULL, label.lineheight = NULL,
label.hjust = NULL, label.vjust = NULL,
ad.colour = "
p <- list()
tmp <- NULL
p[[1]] <- p[[2]] <- p[[3]] <- p[[4]] <- p[[5]] <- NULL
n_beta = length(model$coefficients$mean)
n_alpha = length(model$coefficients$precision)
if(model$intercept[1] & n_beta == 1 & any(c(3,5)%in% which)){
warning("Removing mean explanatory and simultaneous explanatory perturbations since
there is only the intercept for the mean.")
which <- setdiff(which, c(3,5))
}
if(model$intercept[2] & n_alpha == 1 & any(c(4,5)%in% which)){
warning("Removing precision explanatory and simultaneous explanatory perturbations since
there is only the intercept for the precision parameter.")
which <- setdiff(which, c(4,5))
}
if (is.null(sub.caption)) {
cal <- model$call
if (!is.na(m.f <- match("formula", names(cal)))) {
cal <- cal[c(1, m.f)]
names(cal)[2L] <- ""
}
cc <- deparse(cal, 80)
nc <- nchar(cc[1L], "c")
abbr <- length(cc) > 1 || nc > 75
sub.caption <- if (abbr)
paste(substr(cc[1L], 1L, min(75L, nc)), "...")
else cc[1L]
}
direction <- rlang::arg_match(direction)
curvature <- rlang::arg_match(curvature)
pert <- c("case_weights", "hidden_variable",
"mean_explanatory", "precision_explanatory",
"simultaneous_explanatory")
plot.data <- tidy_local_influence(model, perturbation = pert[which], curvature = curvature,
direction = direction, parameters = parameters,
mean.covariates = mean.covariates,
precision.covariates = precision.covariates)
n <- stats::nobs(model)
plot.data$.index <- 1:n
if(is.null(label.label)){
plot.data$.label <- rownames(plot.data)
} else{
plot.data$.label <- as.vector(label.label)
}
plot_label_influential <- function (p, data, x = NULL, y = NULL, label = TRUE, label.label = "rownames",
label.colour = NULL, label.alpha = NULL, label.size = NULL,
label.angle = NULL, label.family = NULL, label.fontface = NULL,
label.lineheight = NULL, label.hjust = NULL, label.vjust = NULL,
label.repel = FALSE, label.show.legend = NA)
{
if (!is.data.frame(data)) {
stop(paste0("Unsupported class: ", class(data)))
}
if (!missing(label.colour) && !is.null(label.colour) && missing(label)) {
label <- TRUE
}
if (label || label.repel) {
if (is.null(label.colour)) {
label.colour <- "
}
if (label.repel) {
textfunc <- ggrepel::geom_text_repel
}
else {
textfunc <- ggplot2::geom_text
}
p <- p + geom_factory_influential(textfunc, data, x = x, y = y, label = ".label",
colour = label.colour, alpha = label.alpha, size = label.size,
angle = label.angle, family = label.family, fontface = label.fontface,
lineheight = label.lineheight, hjust = label.hjust,
vjust = label.vjust, show.legend = label.show.legend)
}
p
}
flatten <- function (df)
{
ismatrix <- vapply(df, is.matrix, logical(1))
if (any(ismatrix)) {
return(data.frame(c(df[!ismatrix], do.call(data.frame,
df[ismatrix])), stringsAsFactors = FALSE))
}
else {
return(df)
}
}
geom_factory_influential <- function (geomfunc, data = NULL, ...)
{
mapping <- list()
option <- list()
columns <- colnames(data)
for (key in names(list(...))) {
value <- list(...)[[key]]
if (is.null(value)) {
}
else if (value %in% columns) {
mapping[[key]] <- value
}
else {
option[[key]] <- value
}
}
if (!is.null(data)) {
option[["data"]] <- data
}
option[["mapping"]] <- do.call(ggplot2::aes_string, mapping)
return(do.call(geomfunc, option))
}
if (is.logical(shape) && !shape) {
if (missing(label)) {
label <- TRUE
}
if (missing(n.influential)) {
n.influential <- nrow(plot.data)
}
}
dev_ask <- is.null(nrow) & is.null(ncol)
if(dev_ask){
if (ask) {
oask <- grDevices::devAskNewPage(TRUE)
on.exit(grDevices::devAskNewPage(oask))
}
}
plot.data <- flatten(plot.data)
if (detect.influential) {
bm <- local_influence_benchmarks(model, perturbation = pert[which], curvature = curvature,
direction = direction, parameters = parameters,
mean.covariates = mean.covariates,
precision.covariates = precision.covariates)
p.data <- list()
for(i in 1:length(pert)){
if(i %in% which){
p.data[[i]] <- plot.data %>% dplyr::mutate(tmp = !!as.name(pert[[i]]), tmp = abs(tmp)) %>% dplyr::arrange(dplyr::desc(tmp))
if(!is.na(bm[[pert[[i]]]])){
p.data[[i]] <- p.data[[i]] %>% dplyr::filter(tmp > bm[[pert[[i]]]])
}
p.data[[i]] <- utils::head(p.data[[i]], n.influential) %>% dplyr::select(-tmp)
}
}
}
.decorate.label.influential <- function(p, data) {
if (label & n.influential > 0) {
p <- plot_label_influential(p = p, data = data, label = label,
label.label = ".label", label.colour = label.colour,
label.alpha = label.alpha, label.size = label.size,
label.angle = label.angle, label.family = label.family,
label.fontface = label.fontface, label.lineheight = label.lineheight,
label.hjust = label.hjust, label.vjust = label.vjust,
label.repel = label.repel)
}
p
}
.decorate.plot <- function(p, xlab = NULL, ylab = NULL, title = NULL) {
if(title.bold){
p + ggplot2::xlab(xlab) + ggplot2::ylab(ylab) + ggplot2::ggtitle(title) + theme(plot.title = element_text(size = title.size, face = "bold", colour = title.colour))
} else{
p + ggplot2::xlab(xlab) + ggplot2::ylab(ylab) + ggplot2::ggtitle(title) + theme(plot.title = element_text(size = title.size, colour = title.colour))
}
}
ylab_infl <- switch(curvature,
"conformal" = {
yl <- switch(direction,
"canonical" = "Total Local Influence (Conformal)",
"max.eigen" = "Largest Curvature Direction (Conformal)")
yl
},
"normal" = {
yl <- switch(direction,
"canonical" = "Total Local Influence (Normal)",
"max.eigen" = "Largest Curvature Direction (Normal)")
}
)
for(i in 1:length(pert)){
if(i %in% which){
if(include.modeltype){
title[[i]] <- paste0(title[[i]], " - ", model$modeltype, " Regression")
}
t <- title[[i]]
mapping <- ggplot2::aes_string(x = ".index", y = pert[[i]],
ymin = 0, ymax = pert[[i]])
p[[i]] <- ggplot2::ggplot(data = plot.data, mapping = mapping)
if (!is.logical(shape) || shape) {
if(type.plot == "linerange"){
p[[i]] <- p[[i]] + geom_factory_influential(geom_linerange, plot.data,
colour = colour, size = size, linetype = linetype,
alpha = alpha, fill = fill, shape = shape)
} else if(type.plot == "points"){
p[[i]] <- p[[i]] + geom_factory_influential(geom_point, plot.data,
colour = colour, size = size, linetype = linetype,
alpha = alpha, fill = fill, shape = shape)
}
}
if(detect.influential){
p[[i]] <- .decorate.label.influential(p[[i]], p.data[[i]])
}
xlab = "Obs. Number"
p[[i]] <- .decorate.plot(p[[i]], xlab = xlab, ylab = ylab_infl,
title = t) + theme(axis.title.x = element_text(colour = x.axis.col, size = x.axis.size),
axis.title.y = element_text(colour = y.axis.col, size = y.axis.size))
bm_i <- bm[[pert[[i]]]]
if(draw.benchmark){
if(!is.na(bm_i)){
p[[i]] <- p[[i]] + ggplot2::geom_abline(intercept = bm_i, slope = 0,
linetype = ad.linetype, size = ad.size, colour = ad.colour)
}
}
if(dev_ask){
p[[i]] <- p[[i]] + labs(caption = sub.caption) + theme(plot.caption = element_text(color = sub.caption.col,
face = sub.caption.face,
size = sub.caption.size,
hjust = sub.caption.hjust))
print(p[[i]])
}
}
}
if(!dev_ask){
grDevices::devAskNewPage(ask = FALSE)
plot.list <- lapply(which, function(i){p[[i]]})
gpar_multi <- do.call(grid::gpar, gpar_sub.caption)
title_multi <- grid::textGrob(sub.caption, gp=gpar_multi)
gridExtra::grid.arrange(grobs = plot.list, top = title_multi, nrow = nrow, ncol = ncol)
grDevices::devAskNewPage(ask = grDevices::dev.interactive())
} else{
invisible()
}
}
local_influence_autoplot <- function(model, ...){
UseMethod("local_influence_autoplot", model)
}
tidy_local_influence <- function(model, ...){
UseMethod("tidy_local_influence", model)
}
local_influence_benchmarks <- function(model, ...){
UseMethod("local_influence_benchmarks", model)
} |
nosof88oat <- function(dta, xtdo = FALSE) {
res1 <- c(
dta$c2acc[dta$cond == 1 & dta$stim == 2],
dta$c2acc[dta$cond == 2 & dta$stim == 2])
res2 <- c(
dta$c2acc[dta$cond == 1 & dta$stim == 7],
dta$c2acc[dta$cond == 3 & dta$stim == 7])
res3 <- c(
dta$c2acc[dta$cond == 1 & dta$stim == 4],
dta$c2acc[dta$cond == 2 & dta$stim == 4])
res4 <- c(
dta$c2acc[dta$cond == 1 & dta$stim == 9],
dta$c2acc[dta$cond == 3 & dta$stim == 9])
pred <- cbind(res1,res2,res3,res4)
colnames(pred) <- c('2','7','4','9')
rownames(pred) <- c('B','E')
oat <- TRUE
if(pred[1,1] >= pred[2,1]) oat <- FALSE
if(pred[1,2] >= pred[2,2]) oat <- FALSE
if(pred[1,3] >= pred[2,3]) oat <- FALSE
if(pred[1,4] >= pred[2,4]) oat <- FALSE
if(xtdo) ret <- pred else ret <- oat
return(ret)
} |
library(testthat)
test_that("K_S test works as expected, compared to the default ks test",{
for (i in 1:10){
x <- stats::runif(1000, 0, 1)
y <- stats::runif(1000, 0, 1)
ks_og <- ks.test(x, y, alternative = "two.sided")
new_ks <- ks_test(x, y, thresh = 0)
expect_equivalent(ks_og$statistic, new_ks$statistic)
expect_equivalent(ks_og$p.value, new_ks$p.value, tolerance = 1e-4)
expect_equal(ks_og$data.name, new_ks$data.name)
}
})
test_that("K_S with equal weights equal ks with no weights",{
for (i in 1:10){
x <- stats::runif(1000, 0, 1)
y <- stats::runif(1000, 0, 1)
ks <- ks_test(x, y)
ks_weights <- ks_test(x, y, w_x = rep(.5, 1000), w_y = rep(906, 1000))
expect_equivalent(ks$statistic, ks_weights$statistic)
expect_equivalent(ks$p.value, ks_weights$p.value)
expect_equal(ks$data.name, ks_weights$data.name)
}
}) |
test_that("tx_new captures all and only new clients", {
expect_identical(
tx_new(
ndr_example,
lubridate::ymd("2020-10-01"),
lubridate::ymd("2020-12-31")
),
ndr_example %>%
dplyr::filter(dplyr::between(
art_start_date,
lubridate::ymd("2020-10-01"),
lubridate::ymd("2020-12-31")
))
)
}) |
"%||%" <- function(a, b) {
if (!is.null(a)) a else b
}
in_data <- function(data, variable) {
length(intersect(names(data), variable)) > 0
}
parse_product_formula <- getFromNamespace("parse_product_formula", "productplots")
product <- function(...) {
rlang::exprs(...)
}
stat_mosaic <- function(mapping = NULL, data = NULL, geom = "mosaic",
position = "identity", na.rm = FALSE, divider = mosaic(),
show.legend = NA, inherit.aes = TRUE, offset = 0.01, ...)
{
if (!is.null(mapping$y)) {
stop("stat_mosaic() must not be used with a y aesthetic.", call. = FALSE)
} else mapping$y <- structure(1L, class = "productlist")
aes_x <- mapping$x
if (!is.null(aes_x)) {
aes_x <- rlang::eval_tidy(mapping$x)
var_x <- paste0("x__", as.character(aes_x))
}
aes_fill <- mapping$fill
var_fill <- ""
if (!is.null(aes_fill)) {
aes_fill <- rlang::quo_text(mapping$fill)
var_fill <- paste0("x__fill__", aes_fill)
if (aes_fill %in% as.character(aes_x)) {
idx <- which(aes_x == aes_fill)
var_x[idx] <- var_fill
} else {
mapping[[var_fill]] <- mapping$fill
}
}
aes_alpha <- mapping$alpha
var_alpha <- ""
if (!is.null(aes_alpha)) {
aes_alpha <- rlang::quo_text(mapping$alpha)
var_alpha <- paste0("x__alpha__", aes_alpha)
if (aes_alpha %in% as.character(aes_x)) {
idx <- which(aes_x == aes_alpha)
var_x[idx] <- var_alpha
} else {
mapping[[var_alpha]] <- mapping$alpha
}
}
if (!is.null(aes_x)) {
mapping$x <- structure(1L, class = "productlist")
for (i in seq_along(var_x)) {
mapping[[var_x[i]]] <- aes_x[[i]]
}
}
aes_conds <- mapping$conds
if (!is.null(aes_conds)) {
aes_conds <- rlang::eval_tidy(mapping$conds)
mapping$conds <- structure(1L, class = "productlist")
var_conds <- paste0("conds", seq_along(aes_conds), "__", as.character(aes_conds))
for (i in seq_along(var_conds)) {
mapping[[var_conds[i]]] <- aes_conds[[i]]
}
}
ggplot2::layer(
data = data,
mapping = mapping,
stat = StatMosaic,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
check.aes = FALSE,
params = list(
na.rm = na.rm,
divider = divider,
offset = offset,
...
)
)
}
StatMosaic <- ggplot2::ggproto(
"StatMosaic", ggplot2::Stat,
non_missing_aes = "weight",
setup_params = function(data, params) {
params
},
setup_data = function(data, params) {
data
},
compute_panel = function(self, data, scales, na.rm=FALSE, divider, offset) {
vars <- names(data)[grep("x__", names(data))]
conds <- names(data)[grep("conds[0-9]+__", names(data))]
if (length(vars) == 0) formula <- "1"
else formula <- paste(vars, collapse="+")
formula <- paste("weight~", formula)
if (length(conds) > 0) formula <- paste(formula, paste(conds, collapse="+"), sep="|")
df <- data
if (!in_data(df, "weight")) {
df$weight <- 1
}
res <- prodcalc(df, formula=as.formula(formula),
divider = divider, cascade=0, scale_max = TRUE,
na.rm = na.rm, offset = offset)
prs <- parse_product_formula(as.formula(formula))
p <- length(c(prs$marg, prs$cond))
if (is.function(divider)) divider <- divider(p)
dflist <- list(data=subset(res, level==max(res$level)), formula=as.formula(formula), divider=divider)
scx <- productplots::scale_x_product(dflist)
scy <- productplots::scale_y_product(dflist)
res <- dplyr::rename(res, xmin=l, xmax=r, ymin=b, ymax=t)
res <- subset(res, level==max(res$level))
cols <- c(prs$marg, prs$cond)
if (length(cols) > 1) {
df <- res[,cols]
df <- tidyr::unite_(df, "label", cols, sep="\n")
res$label <- df$label
} else res$label <- as.character(res[,cols])
res$x <- list(scale=scx)
if (!is.null(scales$y)) {
if ("ScaleContinuousProduct" %in% class(scales$y))
res$y <- list(scale=scy)
}
fill_idx <- grep("x__fill", names(data))
if (length(fill_idx) > 0) {
fill_res_idx <- grep("x__fill", names(res))
res$fill <- res[[fill_res_idx]]
}
alpha_idx <- grep("x__alpha", names(data))
if (length(alpha_idx) > 0) {
alpha_res_idx <- grep("x__alpha", names(res))
res$alpha <- res[[alpha_res_idx]]
}
res$group <- 1
res$PANEL <- unique(data$PANEL)
res
}
) |
context("Test Poisson")
test_that("Predict", {
y <- as.factor(c("Ham", "Ham", "Spam", "Spam", "Spam"))
x <- matrix(
c(2, 3, 2, 1, 2,
5, 3, 4, 2, 4,
0, 1, 3, 1, 0,
3, 4, 4, 3, 5),
nrow = 5,
ncol = 4,
dimnames = list(NULL, c("wo", "mo", "bo", "so")))
df <- as.data.frame(x)
mod <- fnb.poisson(x, y)
df_mod <- fnb.poisson(df, y)
predictions <- predict(mod, x, type = "raw")
risky_predictions <- predict(mod, x, type = "raw", check=FALSE)
df_predictions <- predict(df_mod, df, type = "raw")
expect_equal(sum(round(abs(predictions-df_predictions), digits = 12)), 0)
expect_equal(sum(round(abs(predictions-risky_predictions), digits = 12)), 0)
classification <- predict(mod, x, type = "class")
expect_equal(as.factor(mod$levels[max.col(predictions)]), classification)
expect_warning(predict(mod, x[,1:3], type = "raw"))
dropped_predictions <- predict(mod, x[,1:3], type = "raw", silent = TRUE)
dropped_x <- x[,1:3]
mod <- fnb.poisson(dropped_x, y)
alt_predictions <- predict(mod, x, type = "raw", silent=TRUE)
expect_equal(sum(round(abs(dropped_predictions-alt_predictions), digits = 12)), 0)
mod <- fnb.poisson(x, y)
predictions <- predict(mod, x, type = "raw")
x <- cbind(x, x[,1, drop=FALSE])
colnames(x)[5] <- "womo"
new_predictions <- predict(mod, x, type = "raw", silent=TRUE)
expect_equal(sum(round(abs(predictions-new_predictions), digits = 12)), 0)
all_new_columns_predictions <- predict(mod, x[,5,drop=FALSE], type="raw", silent = TRUE)
predictions <- matrix(
c(2/5,2/5,2/5,2/5,2/5,
3/5,3/5,3/5,3/5,3/5),
nrow = 5,
ncol = 2
)
expect_equal(sum(round(abs(predictions-all_new_columns_predictions), digits = 12)), 0)
})
test_that("Standard 3 classes", {
y <- as.factor(c("Ham", "Ham", "Spam", "Spam", "Spam"))
x <- matrix(
c(2, 3, 2, 1, 2,
5, 3, 4, 2, 4,
0, 1, 3, 1, 0,
3, 4, 4, 3, 5),
nrow = 5,
ncol = 4,
dimnames = list(NULL, c("wo", "mo", "bo", "so")))
actuals <- matrix(
c(
0.67913774, 0.3208623,
0.41976782, 0.5802322,
0.07526245, 0.9247376,
0.23443299, 0.7655670,
0.57454707, 0.4254529
),
nrow = 5,
ncol = 2,
byrow=TRUE,
dimnames = list(NULL, c("Ham", "Spam"))
)
mod <- fnb.poisson(x, y, priors = c(2/5, 3/5))
predictions <- predict(mod, x, type="raw")
expect_equal(sum(round(abs(predictions-actuals), digits = 7)), 0)
sparse_mod <- fnb.poisson(Matrix(x, sparse = TRUE), y, priors = c(2/5, 3/5))
sparse_cast_mod <- fnb.poisson(x, y, sparse = TRUE, priors = c(2/5, 3/5))
sparse_predictions <- predict(sparse_mod, x, type = "raw")
sparse_cast_predictions <- predict(sparse_cast_mod, x, type = "raw")
expect_equal(sum(round(abs(predictions-sparse_predictions), digits = 12)), 0)
expect_equal(sum(round(abs(predictions-sparse_cast_predictions), digits = 12)), 0)
})
test_that("Single column",{
y <- as.factor(c( "Spam", "Spam", "Ham", "Ham", "Ham"))
x <- matrix(
c(2, 3, 2, 1, 2),
nrow = 5,
ncol = 1,
dimnames = list(NULL, c("ho"))
)
actuals_ho_only <- matrix(
c(
0.6053645, 0.3946355,
0.5056005, 0.4943995,
0.6053645, 0.3946355,
0.6970593, 0.3029407,
0.6053645, 0.3946355
),
nrow = 5,
ncol = 2,
byrow = TRUE,
dimnames = list(NULL, c("Ham", "Spam"))
)
mod <- fnb.poisson(x[, 1, drop=FALSE], y)
predictions <- predict(mod, x[, 1, drop=FALSE], type="raw")
expect_equal(sum(round(abs(predictions-actuals_ho_only), digits = 7)), 0)
sparse_mod <- fnb.poisson(Matrix(x[, 1, drop=FALSE], sparse = TRUE), y)
sparse_cast_mod <- fnb.poisson(x[, 1, drop=FALSE], y, sparse = TRUE)
sparse_predictions <- predict(sparse_mod, x[, 1, drop=FALSE], type = "raw")
sparse_cast_predictions <- predict(sparse_cast_mod, x[, 1, drop=FALSE], type = "raw")
expect_equal(sum(round(abs(predictions-sparse_predictions), digits = 12)), 0)
expect_equal(sum(round(abs(predictions-sparse_cast_predictions), digits = 12)), 0)
}) |
NULL
glmnet <- function(x, ...)
UseMethod("glmnet")
glmnet.default <- function(x, y, ...)
{
cl <- match.call()
cl[[1]] <- quote(glmnet::glmnet)
obj <- glmnet::glmnet(x, y, ...)
obj$call <- cl
obj
}
glmnet.formula <- function(formula, data,
family=c("gaussian", "binomial", "poisson", "multinomial", "cox", "mgaussian"),
alpha=1, ..., weights=NULL, offset=NULL, subset=NULL,
na.action=getOption("na.action"), drop.unused.levels=FALSE, xlev=NULL,
sparse=FALSE, use.model.frame=FALSE, relax=FALSE)
{
cl <- match.call(expand.dots=FALSE)
cl[[1]] <- if(use.model.frame)
makeModelComponentsMF
else makeModelComponents
xy <- eval.parent(cl)
if(is.character(family))
family <- match.arg(family)
else
{
if(utils::packageVersion("glmnet") < package_version("4.0.0"))
stop("Enhanced family argument requires glmnet version 4.0 or higher", call.=FALSE)
if(is.function(family))
family <- family()
else if(!inherits(family, "family"))
stop("Invalid family argument; must be either character, function or family object")
}
model <- glmnet::glmnet(xy$x, y=xy$y, family=family, weights=xy$weights, offset=xy$offset, alpha=alpha, ...)
model$call <- match.call()
model$call[[1]] <- parse(text="glmnetUtils:::glmnet.formula")[[1]]
model$terms <- xy$terms
model$xlev <- xy$xlev
model$alpha <- alpha
model$sparse <- sparse
model$use.model.frame <- use.model.frame
model$na.action <- na.action
if(relax)
{
if(utils::packageVersion("glmnet") < package_version("3.0.0"))
stop("Relaxed fit requires glmnet version 3.0 or higher", call.=FALSE)
model <- glmnet::relax.glmnet(model, xy$x, family=family, weights=xy$weights, offset=xy$offset, alpha=alpha,
..., check.args=FALSE)
class(model) <- c("relaxed.formula", class(model))
}
else class(model) <- c("glmnet.formula", class(model))
model
}
predict.glmnet.formula <- function(object, newdata, offset=NULL, na.action=na.pass, ...)
{
if(!inherits(object, "glmnet.formula"))
stop("invalid glmnet.formula object")
cl <- match.call(expand.dots=FALSE)
cl$formula <- delete.response(object$terms)
cl$data <- cl$newdata
cl$newdata <- NULL
cl$xlev <- object$xlev
cl[[1]] <- if(object$use.model.frame)
makeModelComponentsMF
else makeModelComponents
xy <- eval.parent(cl)
x <- xy$x
offset <- xy$offset
class(object) <- class(object)[-1]
predict(object, x, offset=offset, ...)
}
coef.glmnet.formula <- function(object, ...)
{
if(!inherits(object, "glmnet.formula"))
stop("invalid glmnet.formula object")
class(object) <- class(object)[-1]
coef(object, ...)
}
print.glmnet.formula <- function(x, digits=max(3, getOption("digits") - 3), print.deviance.ratios=FALSE, ...)
{
cat("Call:\n")
dput(x$call)
cat("\nModel fitting options:")
cat("\n Sparse model matrix:", x$sparse)
cat("\n Use model.frame:", x$use.model.frame)
cat("\n Alpha:", x$alpha)
cat("\n Lambda summary:\n")
print(summary(x$lambda))
if(print.deviance.ratios)
{
cat("\nDeviance ratios:\n")
print(cbind(Df=x$df, `%Dev`=signif(x$dev.ratio, digits), Lambda=signif(x$lambda, digits)))
}
cat("\n")
invisible(x)
}
print.relaxed.formula <- function(x, digits=max(3, getOption("digits") - 3), print.deviance.ratios=FALSE, ...)
{
print.glmnet.formula(x)
cat("Relaxed fit in component $relaxed\n")
invisible(x)
}
predict.relaxed.formula <- function(object, newdata, offset=NULL, na.action=na.pass, ...)
{
if(!inherits(object, "relaxed.formula"))
stop("invalid relaxed.formula object")
cl <- match.call(expand.dots=FALSE)
cl$formula <- delete.response(object$terms)
cl$data <- cl$newdata
cl$newdata <- NULL
cl$xlev <- object$xlev
cl[[1]] <- if(object$use.model.frame)
makeModelComponentsMF
else makeModelComponents
xy <- eval.parent(cl)
x <- xy$x
offset <- xy$offset
class(object) <- class(object)[-1]
predict(object, x, offset=offset, ...)
}
coef.relaxed.formula <- function(object, ...)
{
if(!inherits(object, "relaxed.formula"))
stop("invalid relaxed.formula object")
class(object) <- class(object)[-1]
coef(object, ...)
} |
batch <- function(x) x@batch
moving <- function(x) x@moving
setGeneric("knobs", function(x,y,...) standardGeneric("knobs"))
setMethod("knobs", c("mrgmod", "missing"), function(x,...) {
input <- list(...)
if(is.element("time", names(input))) stop("time cannot be a knob", call.=FALSE)
has.amt <- is.element("amt", names(input))
if(!has.amt) {
input <- input[!is.element(names(input),c("ii","amt","rate","addl","ss","cmt"))]
}
p <- pars(x)
keep <- is.element(names(input),c(p,c("ii","amt","rate","addl","ss","cmt")))
toupdate <- input[!keep]
input <- input[keep]
whatkn <- names(input)
aremoving <- whatkn[sapply(input, length)>1]
if(any(is.element(c("addl","ss","cmt"), aremoving)))
stop("addl, cmt, and ss can have only one level",call.=FALSE)
if(any(duplicated(aremoving))) stop("Duplicate knobs were found.", call.=FALSE)
if(length(input)==0) stop("No valid knobs found.", call.=FALSE)
data <- do.call("expand.ev", input)
x <- do.call("update", c(list(x),toupdate,list(strict=FALSE)))
if(has.amt) {
x <- x %>% data_set(data)
} else {
x <- x %>% idata_set(data)
}
out <-
x %>%
obsonly %>%
mrgsim(carry.out="",recsort=3)
request <- out@request
outn <- out@outnames
out <- out %>% as.data.frame
out <- out[,unique(setdiff(names(out),whatkn)),drop=FALSE]
data <- data[,unique(c("ID",whatkn)),drop=FALSE]
out <- dplyr::left_join(out,data, by="ID")
new("batch_mrgsims",
data=as.data.frame(out),
mod=x,
batch=data,
knobs=whatkn,
request=request,
moving=aremoving,
outnames=outn,
input=input)
})
setMethod("knobs", c("mrgmod", "batch_mrgsims"), function(x,y,...) {
input <- merge(y@input, list(...), open=TRUE)
do.call("knobs", c(list(x),input))
})
setMethod("as.data.frame","batch_mrgsims", function(x,row.names=NULL, optional=FALSE,...) {
as.data.frame(x@data, row.names,optional,...)
})
setMethod("knobs", "batch_mrgsims", function(x,...) {
x@knobs
})
setMethod("show", "batch_mrgsims", function(object) {
cat("Model: ", model(mod(object)),"\n")
cat("Batch (head): \n")
print(head(object@batch,n=3))
mov <- object@moving
if(all(mov == "")) mov <- "none"
cat("[",mov, "]\n\n")
cat("Head:\n")
print(head(object@data,n=5))
mov <- object@moving
if(all(mov =="")) mov <- "none"
cat("[", mov, "]")
return(invisible(NULL))
})
setMethod("plot", c("batch_mrgsims","missing"), function(x,yval=variables(x),auto.key=list(),mincol=3,...) {
new_plot_knobs(x,yval,auto.key,mincol,...)
})
new_plot_knobs <- function(x,yval,auto.key,mincol,...) {
m <- moving(x)
ny <- length(yval)
y1 <- ny==1
nm <- length(m)
yval <- paste(yval, collapse="+")
form <- paste0(yval,"~time")
df <- as.data.frame(x)
keep <- 1
if(nm >= 2) {
form <- paste0(form, "|", m[2])
df[,m[2]] <- factor(df[,m[2]],labels=paste0(m[2]," ",sort(unique(df[,m[2]]))))
keep <- 2
}
if(ny==1 & nm >=3) {
form <- paste0(form, "*", m[3])
df[,m[3]] <- factor(df[,m[3]],labels=paste0(m[3]," ",sort(unique(df[,m[3]]))))
keep <- 3
}
if(ny > 1 & nm >=2) keep <- 2
grval <- factor(df[,m[1]], labels=paste0(m[1]," ",sort(unique(df[,m[1]]))))
if(nm > keep) {
kp <- unique(df[,m[c(1:keep)],drop=FALSE])
dr <- unique(df[1,m[c((keep+1):nm)],drop=FALSE])
retain <- cbind(kp,dr)
df <- dplyr::inner_join(df,retain, by=names(retain))
message("Dropping knobs: ", paste(names(dr),collapse=","))
}
x@data <- as.data.frame(df)
x@moving <- m[1:keep]
if(identical(auto.key,list())) {
auto.key <- list(columns = min(nlevels(grval),mincol))
}
plot(x,as.formula(form),..., groups=grval,auto.key=auto.key)
}
setMethod("plot", c("batch_mrgsims","formula"), function(x,y,
show.grid=TRUE,
lwd=2,
type="l",
yval=variables(x),
auto.key=list(columns=1),
scales=list(y=list(relation='free')),
...) {
requireNamespace("lattice", quietly=TRUE)
if(y[[3]] == '.') {
yval <- all.vars(y[[2]])
return(plot(x,yval=as.character(yval),
show.grid=show.grid,
lwd=lwd, type=type,
auto.key=auto.key,
scales=scales,...))
}
data <- as.data.frame(x)
lattice::xyplot(y,
data=data,
type=type,
scales=scales,
drop.unused.levels=TRUE,
lwd=lwd,auto.key=auto.key,
panel=function(...) {
if(show.grid) lattice::panel.grid(h=-1,v=-1)
lattice::panel.xyplot(...)
}, ...)
}) |
NULL
appflow <- function(config = list()) {
svc <- .appflow$operations
svc <- set_config(svc, config)
return(svc)
}
.appflow <- list()
.appflow$operations <- list()
.appflow$metadata <- list(
service_name = "appflow",
endpoints = list("*" = list(endpoint = "appflow.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "appflow.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "appflow.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "appflow.{region}.sc2s.sgov.gov", global = FALSE)),
service_id = "Appflow",
api_version = "2020-08-23",
signing_name = "appflow",
json_version = "1.1",
target_prefix = ""
)
.appflow$service <- function(config = list()) {
handlers <- new_handlers("restjson", "v4")
new_service(.appflow$metadata, handlers, config)
} |
ezDesign <-
function(
data
, x
, y
, row = NULL
, col = NULL
, cell_border_size = 10
){
if(inherits(data, "tbl_df")) {
data <- as.data.frame(data)
}
args_to_check = c('x','y','row','col')
args = as.list(match.call()[-1])
for(i in 1:length(args)){
arg_name = names(args)[i]
if(arg_name%in%args_to_check){
if(is.symbol(args[[i]])){
code = paste(arg_name,'=.(',as.character(args[[i]]),')',sep='')
eval(parse(text=code))
}else{
if(is.language(args[[i]])){
arg_vals = as.character(args[[i]])
arg_vals = arg_vals[2:length(arg_vals)]
arg_vals = paste(arg_vals,collapse=',')
code = paste(arg_name,'=.(',arg_vals,')',sep='')
eval(parse(text=code))
}
}
}
}
counts = ddply(
.data = data
, .variables = structure(as.list(c(x,y,row,col)),class = 'quoted')
, .fun = function(z){
to_return = data.frame(
Count = nrow(z)
)
return(to_return)
}
)
y_lab = names(counts)[names(counts)==y]
x_lab = names(counts)[names(counts)==x]
names(counts)[names(counts)==y] = 'y'
names(counts)[names(counts)==x] = 'x'
if(!is.numeric(counts$x)){
counts$x = factor(counts$x)
x_vals = as.character(levels(counts$x))
}else{
x_vals = as.character(sort(unique(counts$x)))
}
counts$x = as.numeric(factor(counts$x))
if(!is.numeric(counts$y)){
counts$y = factor(counts$y)
y_vals = as.character(levels(counts$y))
}else{
y_vals = as.character(sort(unique(counts$y)))
}
counts$y = as.numeric(factor(counts$y))
if(length(unique(counts$y))>length(unique(counts$x))){
cell_border_size = cell_border_size/length(unique(counts$y))
}else{
cell_border_size = cell_border_size/length(unique(counts$x))
}
if(!is.null(row)){
if(!is.factor(counts[,names(counts)==row])){
counts[,names(counts)==row] = factor(counts[,names(counts)==row])
}
levels(counts[,names(counts)==row]) = paste(
names(counts)[names(counts)==row]
, levels(counts[,names(counts)==row])
, sep = ' = '
)
names(counts)[names(counts)==row] = 'row'
}
if(!is.null(col)){
if(!is.factor(counts[,names(counts)==col])){
counts[,names(counts)==col] = factor(counts[,names(counts)==col])
}
levels(counts[,names(counts)==col]) = paste(
names(counts)[names(counts)==col]
, levels(counts[,names(counts)==col])
, sep = ' = '
)
names(counts)[names(counts)==col] = 'col'
}
counts$ymin = counts$y-.5
counts$ymax = counts$y+.5
counts$xmin = counts$x-.5
counts$xmax = counts$x+.5
p = ggplot(
data = counts
,aes_string(
ymin = 'ymin'
, ymax = 'ymax'
, xmin = 'xmin'
, xmax = 'xmax'
, fill = 'Count'
)
)+
geom_rect()+
labs(x=x_lab,y=y_lab)
p = p + theme(
panel.grid.major = element_blank()
, panel.grid.minor = element_blank()
, legend.background = element_rect(colour='transparent',fill='transparent')
)
if(max(counts$Count)==min(counts$Count)){
p = p + scale_fill_gradient(
high = muted('blue')
, low = muted('red')
, limit = c(0,max(counts$Count))
, breaks = max(counts$Count)
)
}else{
p = p + scale_fill_gradient(
high = muted('blue')
, low = muted('red')
, limit = c(min(counts$Count),max(counts$Count))
, breaks = c(min(counts$Count),max(counts$Count))
)
}
if(cell_border_size>0){
p = p + geom_rect(
size = cell_border_size
, colour = 'grey90'
, show.legend = FALSE
)
}
p = p + scale_x_continuous(
breaks = sort(unique(counts$x))
, labels = x_vals
)
p = p + scale_y_continuous(
breaks = sort(unique(counts$y))
, labels = y_vals
)
if(!is.null(row)){
if(!is.null(col)){
p = p + facet_grid(row~col)
}
else{
p = p + facet_grid(row~.)
}
}else{
if(!is.null(col)){
p = p + facet_grid(.~col)
}
}
return(p)
} |
ITNhistdegdist<-function(gs){
net <- cbind(igraph::get.edgelist(gs, names=FALSE),igraph:: E(gs)$weight)
net <- tnet::as.tnet(net, type="weighted one-mode tnet")
WeightDegOut<-tnet::degree_w(net,measure=c("degree","output"), type="out")
WeightDegIn<-tnet::degree_w(net,measure=c("degree","output"), type="in")
WeightDegAll<-tnet::degree_w(net,measure=c("degree","output"), type="all")
Dout<-WeightDegOut[,2]
Din<-WeightDegIn[,2]
Dall<-Din+Dout
plotdata<-cbind(Dout,Din,Dall)
plotdata<-as.data.frame(plotdata)
colnames(plotdata)<-c("Dout","Din","Dall")
OUTplot<-ggplot2::ggplot(data=plotdata, ggplot2::aes(Dout)) +
ggplot2::geom_histogram(fill="darkblue",
alpha = 1,position = 'stack', stat = 'bin',
binwidth = 1) +
ggplot2::labs(title="Out Degree Distribution") +
ggplot2::labs(x="Out Degree", y="Frquency")+
ggplot2::theme_gray()
INplot<-ggplot2::ggplot(data=plotdata, ggplot2::aes(Din)) +
ggplot2::geom_histogram(fill="darkblue",
alpha = 1,position = 'stack', stat = 'bin',
binwidth = 1) +
ggplot2::labs(title="In Degree Distribution") +
ggplot2::labs(x="In Degree", y="Frquency")+
ggplot2::theme_gray()
ALLplot<-ggplot2::ggplot(plotdata, ggplot2::aes(Dall)) +
ggplot2::geom_histogram(fill="darkblue",
alpha = 1,position = 'stack', stat = 'bin',
binwidth = 1) +
ggplot2::labs(title="Degree Distribution") +
ggplot2::labs(x="Degree", y="Frquency")+
ggplot2::theme_gray()
cowplot::plot_grid(INplot,OUTplot,ALLplot,labels=c("A","B","C"),ncol=2)
} |
set.seed(1)
if(.Platform$OS.type == "windows") options(pager = "console")
pdf("reg-examples-1.pdf", encoding = "ISOLatin1.enc")
example(Cstack_info, run.donttest = TRUE)
example(DateTimeClasses, run.donttest = TRUE)
example(Dates, run.donttest = TRUE)
example(Ops.Date, run.donttest = TRUE)
example(Random, run.donttest = TRUE)
example(Sys.getpid, run.donttest = TRUE)
example(Sys.sleep, run.donttest = TRUE)
example(Sys.time, run.donttest = TRUE)
example(as.POSIXlt, run.donttest = TRUE)
example(difftime, run.donttest = TRUE)
example(format.Date, run.donttest = TRUE)
example(Reduce, run.donttest = TRUE)
example(gc, run.donttest = TRUE)
example(memory.profile, run.donttest = TRUE)
paste("Today is", date())
trunc(Sys.time(), "day")
example(srcref, run.donttest = TRUE)
example(strptime, run.donttest = TRUE)
example(sys.parent, run.donttest = TRUE)
example(system.time, run.donttest = TRUE)
example(tempfile, run.donttest = TRUE)
example(weekdays, run.donttest = TRUE)
library(help = "splines")
if(require("microbenchmark")) {
x <- c(NaN, 1:10000)
print(microbenchmark(any(is.na(x)), anyNA(x)))
} else {
x <- c(NaN, 1e6)
nSim <- 2^13
print(rbind(is.na = system.time(replicate(nSim, any(is.na(x)))),
anyNA = system.time(replicate(nSim, anyNA(x)))))
}
example(news, run.donttest = TRUE)
example(sessionInfo, run.donttest = TRUE)
example(JohnsonJohnson, run.donttest = TRUE)
example(ability.cov, run.donttest = TRUE)
example(npk, run.donttest = TRUE)
example(grSoftVersion, run.donttest = TRUE)
if(.Platform$OS.type == "windows") {
example(windowsFonts, run.donttest = TRUE)
} else {
example(X11Fonts, run.donttest = TRUE)
example(quartzFonts, run.donttest = TRUE)
}
library(tools)
example(Rdutils, run.donttest = TRUE)
example(fileutils, run.donttest = TRUE)
example(parseLatex, run.donttest = TRUE)
example(loadRdMacros, run.donttest = TRUE)
gVigns <- pkgVignettes("grid")
str(gVigns)
vind <- system.file(package = "grid", "doc", "index.html")
if(nzchar(vind)) {
`%=f=%` <- function(a, b) normalizePath(a) == normalizePath(b)
with(gVigns,
stopifnot(engines == "utils::Sweave",
pkgdir %=f=% system.file(package="grid"),
dir %=f=% system.file(package = "grid", "doc"),
(n. <- length(docs)) >= 12,
n. == length(names), n. == length(engines),
length(msg) == 0) )
stopifnot("grid" %in% gVigns$names, inherits(gVigns, "pkgVignettes"))
}
example(icuSetCollate, run.donttest = TRUE)
proc.time() |
getirt <- function(x, ...) UseMethod("getirt")
getirt.est_irt <- function(x, what, ...){
rst <- switch(what,
estimates = x$estimates,
par.est = x$par.est,
se.est = x$se.est,
pos.par = x$pos.par,
covariance = x$covariance,
loglikelihood = x$loglikelihood,
aic = x$aic,
bic = x$bic,
group.par = x$group.par,
weights = x$weights,
data = x$data,
ncase = x$ncase,
nitem = x$nitem,
Etol = x$Etol,
MaxE = x$MaxE,
aprior = x$aprior,
bprior = x$bprior,
gprior = x$gprior,
npar.est = x$npar.est,
niter = x$niter,
maxpar.diff = x$maxpar.diff,
EMtime = x$EMtime,
SEtime = x$SEtime,
TotalTime = x$TotalTime,
test.1 = x$test.1,
test.2 = x$test.2,
var.note = x$var.note,
fipc = x$fipc,
fipc.method = x$fipc.method,
fix.loc = x$fix.loc,
stop(sprintf("Could not extract element \'%s\'", what), call.=FALSE)
)
rst
}
getirt.est_item <- function(x, what, ...){
rst <- switch(what,
estimates = x$estimates,
par.est = x$par.est,
se.est = x$se.est,
pos.par = x$pos.par,
covariance = x$covariance,
loglikelihood = x$loglikelihood,
group.par = x$group.par,
data = x$data,
score = x$score,
scale.D = x$scale.D,
convergence = x$convergence,
nitem = x$nitem,
deleted.item = x$deleted.item,
npar.est = x$npar.est,
n.response = x$n.response,
TotalTime = x$TotalTime,
stop(sprintf("Could not extract element \'%s\'", what), call.=FALSE)
)
rst
} |
create_test_bbt_run_output <- function() {
anthus_aco_trees <- c(
ape::read.tree(text = "((A:2, B:2):1, C:3);"),
ape::read.tree(text = "((A:1, B:1):2, C:3);")
)
estimates <- data.frame(
Sample = c(0, 1000),
posterior = c(-1.1, -2.2),
likelihood = c(-3.3, -4.4),
prior = c(-5.5, -6.6),
treeLikelihood = c(-7.7, -8.8),
TreeHeight = c(2.5, 2.8),
YuleModel = c(0.5, 0.6),
birthRate = c(0.1, 0.2)
)
operators <- data.frame(
operator = c(
"treeScaler.t:test-alignment_to_beast_posterior",
"treeRootScaler.t:test-alignment_to_beast_posterior"
),
p = c(0.4, 0.6),
accept = c(1, 2),
reject = c(3, 4),
acceptFC = c(5, 6),
rejectFC = c(7, 8),
rejectIv = c(9, 10),
rejectOp = c(11, 12)
)
output <- babette::create_test_ns_output()
list(
estimates = estimates,
anthus_aco_trees = anthus_aco_trees,
operators = operators,
output = output
)
} |
library(OpenMx)
demo(GrowthMixtureModel_MatrixRaw)
trials <- 10
parNames <- names(omxGetParameters(gmm))
input <- matrix(NA, trials, length(parNames))
dimnames(input) <- list(c(1: trials), c(parNames))
output <- matrix(NA, trials, length(parNames))
dimnames(output) <- list(c(1: trials), c(parNames))
fit <- matrix(NA, trials, 5)
dimnames(fit) <- list(c(1: trials), c("Minus2LL", "Status", "Iterations", "pclass1", "time"))
input[,"p1"] <- runif(trials, 0.1, 0.9)
input[,"p1"] <- input[,"p1"]/(1-input[,"p1"])
v <- c("vari1", "vars1", "vari2", "vars2", "residual")
input[,v] <- runif(trials*5, 0, 10)
m <- c("meani1", "means1", "meani2", "means2")
input[,m] <- runif(trials*4, -5, 5)
r <- runif(trials*2, -0.9, 0.9)
scale <- c(
sqrt(input[,"vari1"]*input[,"vars1"]),
sqrt(input[,"vari2"]*input[,"vars2"]))
input[,c("cov1", "cov2")] <- r * scale
for (i in 1: trials){
temp1 <- omxSetParameters(gmm,
labels=parNames,
values=input[i,]
)
temp1 <- mxModel(name=paste("Starting Values Set", i), temp1)
temp2 <- mxRun(temp1, unsafe=TRUE, suppressWarnings=TRUE)
output[i,] <- omxGetParameters(temp2)
fit[i,] <- c(
temp2$output$Minus2LogLikelihood,
temp2$output$status[[1]],
temp2$output$iterations,
round(temp2$expectation$output$weights[1], 4),
temp2$output$wallTime
)
}
fit
table(round(fit[,1], 3), fit[,2])
makeModel <- function(modelNumber){
temp <- mxModel(gmm,
independent=TRUE,
name=paste("Iteration", modelNumber, sep=""))
temp <- omxSetParameters(temp,
labels=parNames,
values=input[modelNumber,])
return(temp)
}
mySubs <- lapply(1:trials, makeModel)
topModel <- mxModel("Top", mySubs)
results <- mxRun(topModel, suppressWarnings=TRUE)
fitStats <- function(model){
retval <- c(
model$output$Minus2LogLikelihood,
model$output$status[[1]],
model$output$iterations,
round(model$expectation$output$weights[1], 4)
)
return(retval)
}
resultsFit <- t(omxSapply(results$submodels, fitStats))
sum(fit[,5])
results$output$wallTime |
structure(list(url = "http://localhost:8086/api/v2/query?org=bonitoo",
status_code = 404L, headers = structure(list(`content-type` = "application/json; charset=utf-8",
vary = "Accept-Encoding", `x-platform-error-code` = "not found",
date = "Tue, 15 Jun 2021 08:53:14 GMT", `transfer-encoding` = "chunked"), class = c("insensitive",
"list")), all_headers = list(list(status = 404L, version = "HTTP/1.1",
headers = structure(list(`content-type` = "application/json; charset=utf-8",
vary = "Accept-Encoding", `x-platform-error-code` = "not found",
date = "Tue, 15 Jun 2021 08:53:14 GMT", `transfer-encoding` = "chunked"), class = c("insensitive",
"list")))), cookies = structure(list(domain = logical(0),
flag = logical(0), path = logical(0), secure = logical(0),
expiration = structure(numeric(0), class = c("POSIXct",
"POSIXt")), name = logical(0), value = logical(0)), row.names = integer(0), class = "data.frame"),
content = charToRaw("{\"code\":\"not found\",\"message\":\"failed to initialize execute state: could not find bucket \\\"no-bucket\\\"\"}"),
date = structure(1623747194, class = c("POSIXct", "POSIXt"
), tzone = "GMT"), times = c(redirect = 0, namelookup = 0.00201,
connect = 0.0021, pretransfer = 0.002189, starttransfer = 0.012402,
total = 0.012458)), class = "response") |
knitr::opts_chunk$set(echo = TRUE)
library(GlmSimulatoR)
library(ggplot2)
library(cplm, quietly = TRUE)
set.seed(1)
simdata <- simulate_tweedie(weight = .2, ancillary = 1.15, link = "log")
ggplot(simdata, aes(x = Y)) +
geom_histogram(bins = 30)
glmModel <- cpglm(Y ~ X1, data =simdata, link = "log")
summary(glmModel) |
print.altf3 <- function(x, ...)
{
cat("Forecast quality measures: ")
cat("\n")
print(x$summary,quote=FALSE)
cat("\n")
} |
wflow_rename <- function(files,
to,
message = NULL,
git = TRUE,
dry_run = FALSE,
project = ".") {
files <- process_input_files(files, files_only = FALSE,
convert_to_relative_paths = TRUE)
assert_is_character(to)
if (length(to) != length(files))
stop("to must be a character vector of filenames the same length as files")
to <- relative(to)
if (is.null(message)) {
message <- deparse(sys.call())
message <- paste(message, collapse = "\n")
} else if (is.character(message)) {
message <- create_newlines(message)
} else {
stop("message must be NULL or a character vector")
}
assert_is_flag(git)
assert_is_flag(dry_run)
check_wd_exists()
assert_is_single_directory(project)
project <- absolute(project)
p <- wflow_paths(project = project)
use_git <- !is.na(p$git) && git
if (!is.na(p$git)) {
r <- git2r::repository(path = p$git)
}
if (use_git && !dry_run) {
check_git_config(project, "`wflow_rename` with `git = TRUE`")
check_staged_changes(project, "`wflow_rename` with `git = TRUE`")
}
files_ext <- tools::file_ext(files)
rmd <- which(files_ext %in% c("Rmd", "rmd") &
absolute(files) == absolute(file.path(p$analysis, basename(files))))
for (i in rmd) {
html1 <- to_html(files[i], outdir = p$docs)
html2 <- to_html(to[i], outdir = p$docs)
if (fs::file_exists(html1)) {
files <- c(files, html1)
to <- c(to, html2)
}
if (p$docs == ".") {
dir_figs_docs1 <- file.path("figure", basename(files[i]))
dir_figs_docs2 <- file.path("figure", basename(to[i]))
} else {
dir_figs_docs1 <- file.path(p$docs, "figure", basename(files[i]))
dir_figs_docs2 <- file.path(p$docs, "figure", basename(to[i]))
}
if (fs::dir_exists(dir_figs_docs1)) {
files <- c(files, dir_figs_docs1)
to <- c(to, dir_figs_docs2)
}
}
is_dir <- fs::dir_exists(files)
dirs_from <- files[is_dir]
dirs_to <- to[is_dir]
files <- files[!is_dir]
to <- to[!is_dir]
for (i in seq_along(dirs_from)) {
d_files_from <- list.files(path = dirs_from[i], all.files = TRUE,
full.names = TRUE, recursive = TRUE)
d_files_to <- stringr::str_replace(d_files_from, dirs_from[i], dirs_to[i])
files <- c(files, d_files_from)
to <- c(to, d_files_to)
}
if (!is.na(p$git)) {
files_committed <- relative(get_committed_files(r))
logical_files_git <- files %in% files_committed
files_to_commit <- c(files[logical_files_git], to[logical_files_git])
} else {
files_to_commit <- NA_character_
}
if (!dry_run) {
lapply(to, function(x) {
fs::dir_create(dirname(x))
})
fs::file_move(path = files, new_path = to)
lapply(dirs_from, unlink, recursive = TRUE)
}
if (use_git && !dry_run && length(files_to_commit) > 0) {
git2r_add(r, files_to_commit)
git2r::commit(r, message = message)
commit <- git2r::commits(r, n = 1)[[1]]
} else {
commit <- NA
}
o <- list(files = files,
to = to,
message = message,
git = git,
dry_run = dry_run,
commit = commit,
files_git = relative(files_to_commit))
class(o) <- "wflow_rename"
return(o)
}
print.wflow_rename <- function(x, ...) {
cat("Summary from wflow_rename\n\n")
if (x$dry_run) {
cat(wrap("The following file(s) would be renamed:"), "\n\n")
} else {
cat(wrap("The following files(s) were renamed:"), "\n\n")
}
cat(sprintf("%s -> %s", x$files, x$to), sep = "\n")
if (length(x$files_git) > 0 && !all(is.na(x$files_git)) && x$git) {
if (x$dry_run) {
cat("\n", wrap("The following file(s) would be included in the Git commit:"),
"\n\n", sep = "")
} else {
cat("\n", wrap(sprintf(
"The following file(s) were included in Git commit %s:",
stringr::str_sub(x$commit$sha, start = 1, end = 7))),
"\n\n", sep = "")
}
cat(x$files_git, sep = "\n")
cat("\ncommit message:\n")
cat(x$message)
cat("\n")
}
return(invisible(x))
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.