code
stringlengths 1
13.8M
|
---|
test_that("error handling works", {
chr <- letters[1:10]
lgc <- rep(c(TRUE, FALSE), 5)
nmr <- 1:10
nmr2 <- 1
expect_error(
percent_change(chr, nmr),
"`baseline` must be numeric; not character.",
class = "error_argument_type"
)
expect_error(
percent_change(lgc, nmr),
"`baseline` must be numeric; not logical.",
class = "error_argument_type"
)
expect_error(
percent_change(nmr, chr),
"`followup` must be numeric; not character.",
class = "error_argument_type"
)
expect_error(
percent_change(nmr, lgc),
"`followup` must be numeric; not logical.",
class = "error_argument_type"
)
expect_error(
percent_change(nmr, nmr2),
"`baseline` and `followup` must have the same length.",
class = "error_argument_diff_length"
)
})
test_that("percent_change() works", {
set.seed(20200525)
change <- c(
1, 1.005, 1.05, 1.5, 2,
0.995, 0.95, 0.5, 0, 1
)
baseline <- sample(1:10)
baseline[10] <- NA
followup <- baseline * change
out <- percent_change(baseline, followup)
expect_s3_class(out, c("lvmisc_percent", "vctrs_vctr"), exact = TRUE)
expected <- vec_c(0, 0.005, 0.05, 0.5, 1, - 0.005, - 0.05, - 0.5, - 1, NA)
expected <- as_percent(expected)
expect_equal(out, expected)
}) |
print.qunormtrain <-
function(x, ...) {
cat("Quantile normalized data with documentation by value.", "\n")
cat(paste("Number of observations: ", nrow(x$xnorm), sep=""), "\n")
cat(paste("Number of variables: ", ncol(x$xnorm), sep=""), "\n")
} |
plot_scatterbar_sd_sc <- function(data, xcol, ycol, colour = "ok_orange", symsize = 2.5, symthick = 1, bwid = 0.7, ewid = 0.3, jitter = 0, b_alpha = 1, s_alpha = 1, TextXAngle = 0, fontsize = 20){
ifelse(grepl("
a <- colour,
a <- get_graf_colours({{ colour }}))
ggplot2::ggplot(data, aes(x = factor({{ xcol }}),
y = {{ ycol }}))+
stat_summary(geom = "bar", colour = "black",
width = {{ bwid }},
fun = "mean",
alpha = {{ b_alpha }}, size = 1,
fill = a)+
geom_point(size = {{ symsize }},
alpha = {{ s_alpha }}, shape = 21,
position = position_jitter(width = {{ jitter }}),
stroke = {{ symthick }},
fill = a)+
stat_summary(geom = "errorbar", size = 1,
fun.data = "mean_sdl",
fun.args = list(mult = 1),
width = {{ ewid }} )+
labs(x = enquo(xcol))+
theme_classic(base_size = {{ fontsize }})+
theme(strip.background = element_blank())+
guides(x = guide_axis(angle = {{ TextXAngle }}))
} |
library(qrmtools)
n <- 2e5
th <- 3
set.seed(271)
X <- rPar(n, shape = th)
stopifnot(th > 1)
Xn <- cumsum(X)/(1:n)
plot(1:n, Xn, type = "l", log = "x", ylab = "",
xlab = expression("Number n of iid random variables"~(X[i])[i == 1]^n),
main = substitute(bold("Strong Law of Large Numbers for Par("*th.*") data"), list(th. = th)))
mu <- 1/(th-1)
abline(h = mu, col = "royalblue3")
legend("bottomright", lty = c(1,1), col = c("black", "royalblue3"),
bty = "n", y.intersp = 1.2,
legend = c(expression((bar(X)[n])[n]),
substitute("true mean"~mu == mu., list(mu. = mu))))
m <- 500
X. <- split(X, f = rep(1:m, each = floor(n/m)))
stopifnot(th > 2)
mu <- 1/(th-1)
sig2 <- 2/((th-2)*(th-1)^2)
Z <- sapply(X., function(x) (sum(x) - length(x) * mu) / (sqrt(length(x) * sig2)))
dens <- density(Z)
hist(Z, probability = TRUE, ylim = c(0, max(dnorm(0), dens$y)), breaks = 20,
main = substitute(bold("Central Limit Theorem for Par("*th.*") data"),
list(th. = th)), xlab = expression("Realizations of"~sqrt(n)*(bar(X)[n]-mu)/sigma))
lines(dens, col = "royalblue3")
curve(dnorm, from = min(Z), to = max(Z), add = TRUE, col = "darkorange2")
box()
legend("topright", lty = c(1,1), col = c("royalblue3", "darkorange2"), bty = "n",
legend = c("Density estimate", "N(0,1) density"))
qq_plot(Z, FUN = qnorm, main = "Central Limit Theorem")
M <- sapply(X., function(x) (max(x) - 0) / qPar(1-1/length(x), shape = th))
dens <- density(M, adjust = 2)
x <- seq(0, max(M), length.out = 257)
true.dens <- dGEV(x, shape = 1/th, loc = 1, scale = 1/th)
hist(M, probability = TRUE, ylim = c(0, max(dens$y, true.dens)), breaks = 60,
main = substitute(bold("Gnedenko's Theorem for Par("*th.*") data"),
list(th. = th)), xlab = expression("Realizations of"~(M[n]-d[n])/c[n]~~
"(for"~c[n] == {F^{-1}}(1-1/n)*";"~~d[n] == 0*")"))
lines(dens, col = "royalblue3")
lines(x, true.dens, col = "darkorange2")
box()
legend("topright", lty = c(1,1), col = c("royalblue3", "darkorange2"), bty = "n",
legend = c("Density estimate", expression("Limiting GEV density"~h[list(xi,mu,sigma)])))
qq_plot(M, FUN = function(p) qGEV(p, shape = 1/th, loc = 1, scale = 1/th),
main = substitute(bold("Gnedenko's Theorem for Par("*th.*") data"),
list(th. = th)))
u <- quantile(X, 0.9)
Y <- X[X>u] - u
dens <- density(Y)
x <- seq(0, max(Y), length.out = 257)
true.dens <- dGPD(x, shape = 1/th, scale = (1/th)*(1+u))
hist(Y, probability = TRUE, ylim = c(0, max(dens$y, true.dens)), breaks = 60,
main = substitute(bold("Pickands-Balkema-de Haan Theorem for Par("*th.*") data"),
list(th. = th)), xlab = "Realizations of excesses Y over the threshold u (90% quantile)")
lines(dens, col = "royalblue3")
lines(x, true.dens, col = "darkorange2")
box()
legend("topright", lty = c(1,1), col = c("royalblue3", "darkorange2"), bty = "n",
legend = c("Density estimate", expression("Limiting GPD density"~g[list(xi,beta(u))])))
x <- 10^seq(-2, 2, length.out = 65)
true.dens <- dGPD(x, shape = 1/th, scale = (1/th)*(1+u))
ii <- dens$x > 0
plot(dens$x[ii], dens$y[ii], type = "l", log = "x", col = "royalblue3",
ylim = c(0, max(dens$y[ii], true.dens)), xlab = "x", ylab = "Density")
lines(x, true.dens, col = "darkorange2")
legend("topright", lty = c(1,1), col = c("royalblue3", "darkorange2"), bty = "n",
legend = c("Density estimate", expression("Limiting GPD density"~g[list(xi,beta(u))])))
qq_plot(Y, FUN = function(p) qGPD(p, shape = 1/th, scale = (1/th)*(1+u)),
main = substitute(bold("Pickands-Balkema-de Haan Theorem for Par("*th.*") data"),
list(th. = th))) |
mod_dispersion_ui <- function(id) {
ns <- NS(id)
titulo_disp <- tags$div(
class = "multiple-select-var",
selectizeInput(
ns("sel_disp"), NULL, multiple = T, choices = c(""),
options = list(maxItems = 3))
)
opc_disp <- tabsOptions(
heights = c(50, 40), tabs.content = list(
list(options.base(), tags$hr(style = "margin-top: 0px;"),
colourpicker::colourInput(
ns("col_disp"), labelInput("selcolor"), value = "steelblue",
allowTransparent = T)),
list(col_12(codigo.monokai(ns("fieldCodeDisp"), height = "25vh"))
)
)
)
tagList(
tabBoxPrmdt(
id = ns("BoxDisp"), opciones = opc_disp, title = titulo_disp,
tabPanel(
title = labelInput("dispersion"), value = "tabDisp",
echarts4rOutput(ns("plot_disp"), height = "75vh")
)
)
)
}
mod_dispersion_server <- function(input, output, session, updateData) {
ns <- session$ns
observeEvent(updateData$datos, {
datos <- var.numericas(updateData$datos)
updateSelectInput(session, "sel_disp", choices = colnames(datos))
})
output$plot_disp <- renderEcharts4r({
datos <- updateData$datos
vars <- input$sel_disp
color <- input$col_disp
if(length(vars) == 2) {
cod <- code.disp.2d(vars, color)
updateAceEditor(session, "fieldCodeDisp", value = cod)
datos <- data.frame(x = datos[[vars[1]]], y = datos[[vars[2]]],
id = row.names(datos))
datos |> e_charts(x) |> e_scatter(y, bind = id, symbol_size = 10) |>
e_x_axis(x) |> e_y_axis(y) |> e_datazoom(show = F) |>
e_color(color) |> e_axis_labels(x = vars[1], y = vars[2]) |>
e_tooltip(formatter = e_JS(paste0(
"function(params) {
return('<b>' + params.name + ' </b><br/>", vars[1],
": ' + params.value[0] + '<br />", vars[2], ": ' + params.value[1])
}"))
) |> e_legend(F) |> e_show_loading()
} else if (length(vars) == 3) {
cod <- code.disp.3d(vars, color)
updateAceEditor(session, "fieldCodeDisp", value = cod)
id <- row.names(datos)
datos <- data.frame(
x = datos[[vars[1]]], y = datos[[vars[2]]],
z = datos[[vars[3]]], id = id
)
datos |> e_charts(x) |> e_scatter_3d(y, z, bind = id) |> e_color(color) |>
e_x_axis_3d(name = vars[1], axisLine = list(lineStyle = list(color = "white"))) |>
e_y_axis_3d(name = vars[2], axisLine = list(lineStyle = list(color = "white"))) |>
e_z_axis_3d(name = vars[3], axisLine = list(lineStyle = list(color = "white"))) |>
e_tooltip(formatter = e_JS(paste0(
"function(params) {
return('<b>' + params.name + ' </b><br/>", vars[1], ": ' + params.value[0] + '<br/>",
vars[2], ": ' + params.value[1] + '<br/>", vars[3], ": ' + params.value[2])
}"))
) |> e_theme("dark") |> e_show_loading()
}
})
} |
binned.kernel.est <- function(data,
kernel = "normal",
bandwidth = NULL,
canonical = FALSE,
scalest = "minim",
level = 2L,
gridsize = 401L,
range.data = range(data),
truncate = TRUE) {
if(is.null(bandwidth)){
bandwidth.estimate <- KernSmooth::dpik( x = data,
scalest = scalest,
level = level,
kernel = kernel,
gridsize = gridsize,
range.x = range.data,
truncate = truncate )
} else {
bandwidth.estimate <- bandwidth
}
est <- KernSmooth::bkde(x = data,
kernel = kernel,
canonical = canonical,
bandwidth = bandwidth.estimate,
gridsize = gridsize,
range.x = range.data,
truncate = truncate
)
return(est)
} |
setMethod("rowMeans",
signature(x = "magpie"),
function(x, na.rm = FALSE, dims = 1, ...) {
out <- rowMeans(as.array(x), na.rm = na.rm, dims = dims, ...)
out <- as.magpie(as.array(x))
return(out)
}
) |
"murders" |
optim.disp.pl = function(disp, counts, eff.lib.sizes, x, method="L-BFGS-B", ...) {
y = counts[disp$subset, ,drop=FALSE];
mustart = irls.nb(y, eff.lib.sizes, x, phi=0.1, beta0 = rep(NA, dim(x)[2]))$mu;
nll = function(par) {
phi = disp$fun(par)[disp$subset,,drop=FALSE];
mu.hat = irls.nb(y, eff.lib.sizes, x, phi=phi, beta0 = rep(NA, dim(x)[2]), mustart=mustart)$mu;
- ll.nb(1/phi, mu.hat, y);
}
if (is.null(disp$lower) | is.null(disp$upper)) {
res = optim(disp$par.init, nll, method=method, ...);
} else {
res = optim(disp$par.init, nll, lower=disp$lower, upper=disp$upper,
method=method, ...);
}
res
}
optim.disp.apl = function(disp, counts, eff.lib.sizes, x, method="L-BFGS-B", print.level=1, ...) {
y = counts[disp$subset, ,drop=FALSE];
mustart = irls.nb(y, eff.lib.sizes, x, phi=0.1, beta0 = rep(NA, dim(x)[2]))$mu;
adj = function(y, mu.hat, phi) {
kappa = 1/phi;
v.hat = drop(mu.hat + phi * mu.hat^2);
j.hat = t(x) %*% diag(mu.hat^2 * (y/mu.hat^2 - (y + kappa)/(mu.hat + kappa)^2) - (y - mu.hat) * mu.hat/v.hat) %*% x;
d = det(j.hat);
if (d > 0) {
return (-0.5 * log(d))
} else {
print(y);
print(mu.hat);
print(phi);
return (0)
}
}
nll = function(par) {
phi = disp$fun(par)[disp$subset,,drop=FALSE];
mu.hat = irls.nb(y, eff.lib.sizes, x, phi=phi, beta0 = rep(NA, dim(x)[2]),
mustart=mustart)$mu;
l.hat = ll.nb(1/phi, mu.hat, y);
m = dim(mu.hat)[1];
for (i in (1:m)) {
l.hat = l.hat + adj(y[i,], mu.hat[i,], phi[i,]);
}
-l.hat
}
if (is.null(disp$lower) | is.null(disp$upper)) {
res = optim(disp$par.init, nll, method=method, ...);
} else {
res = optim(disp$par.init, nll, lower=disp$lower, upper=disp$upper,
method=method, ...);
}
res
} |
library(testthat)
library(merTools)
test_check("merTools", filter = "^[a-m]") |
test_that("ggplotly doesn't leave a new device open", {
devList1 <- dev.list()
p <- ggplotly(ggplot(mtcars) + geom_point(aes(wt, mpg)))
devList2 <- dev.list()
expect_true(length(devList1) == length(devList2))
}) |
WRMF = R6::R6Class(
inherit = MatrixFactorizationRecommender,
classname = "WRMF",
public = list(
initialize = function(rank = 10L,
lambda = 0,
dynamic_lambda = TRUE,
init = NULL,
preprocess = identity,
feedback = c("implicit", "explicit"),
solver = c("conjugate_gradient", "cholesky", "nnls"),
with_user_item_bias = FALSE,
with_global_bias = FALSE,
cg_steps = 3L,
precision = c("double", "float"),
...) {
stopifnot(is.null(init) || is.matrix(init))
solver = match.arg(solver)
feedback = match.arg(feedback)
private$non_negative = ifelse(solver == "nnls", TRUE, FALSE)
if (private$non_negative && with_global_bias == TRUE) {
logger$warn("setting `with_global_bias=FALSE` for 'nnls' solver")
with_global_bias = FALSE
}
private$with_user_item_bias = with_user_item_bias
private$with_global_bias = with_global_bias
self$global_bias = 0
solver_codes = c("cholesky", "conjugate_gradient", "nnls")
private$solver_code = match(solver, solver_codes) - 1L
private$precision = match.arg(precision)
private$feedback = feedback
private$lambda = as.numeric(lambda)
private$dynamic_lambda = as.logical(dynamic_lambda)[1L]
stopifnot(is.integer(cg_steps) && length(cg_steps) == 1)
private$cg_steps = cg_steps
n_threads = getOption("rsparse_omp_threads", 1L)
private$solver = function(x, X, Y, is_bias_last_row, XtX = NULL, cnt_X=NULL, avoid_cg = FALSE) {
solver_use = ifelse(avoid_cg && private$solver_code == 1L, 0L, private$solver_code)
if (private$lambda && dynamic_lambda && is.null(cnt_X)) {
if (private$precision == "double") {
cnt_X = numeric(ncol(X))
} else {
cnt_X = float::float(ncol(X))
}
}
if(feedback == "implicit") {
als_implicit(
x, X, Y,
lambda = private$lambda,
n_threads = n_threads,
solver_code = solver_use,
cg_steps = private$cg_steps,
precision = private$precision,
with_user_item_bias = private$with_user_item_bias,
is_bias_last_row = is_bias_last_row,
global_bias = self$global_bias,
initialize_bias_base = !avoid_cg,
XtX = XtX,
global_bias_base = self$global_bias_base)
} else {
als_explicit(
x, X, Y, cnt_X,
lambda = private$lambda,
n_threads = n_threads,
solver_code = solver_use,
cg_steps = private$cg_steps,
dynamic_lambda = private$dynamic_lambda,
precision = private$precision,
with_user_item_bias = private$with_user_item_bias,
is_bias_last_row = is_bias_last_row)
}
}
private$init_user_item_bias = function(c_ui, c_iu, user_bias, item_bias) {
FUN = ifelse(private$precision == 'double',
initialize_biases_double,
initialize_biases_float)
FUN(c_ui, c_iu, user_bias, item_bias, private$lambda, private$dynamic_lambda,
private$non_negative, private$with_global_bias, feedback == "explicit")
}
self$components = init
if (private$with_user_item_bias) {
private$rank = as.integer(rank) + 2L
} else {
private$rank = as.integer(rank)
}
stopifnot(is.function(preprocess))
private$preprocess = preprocess
},
fit_transform = function(x, n_iter = 10L, convergence_tol = ifelse(private$feedback == "implicit", 0.005, 0.001), ...) {
if (private$feedback == "implicit" ) {
logger$trace("WRMF$fit_transform(): calling `RhpcBLASctl::blas_set_num_threads(1)` (to avoid thread contention)")
blas_threads_keep = RhpcBLASctl::blas_get_num_procs()
RhpcBLASctl::blas_set_num_threads(1)
on.exit({
logger$trace("WRMF$fit_transform(): on exit `RhpcBLASctl::blas_set_num_threads(%d)", blas_threads_keep)
RhpcBLASctl::blas_set_num_threads(blas_threads_keep)
})
}
c_ui = MatrixExtra::as.csc.matrix(x)
c_ui = private$preprocess(c_ui)
c_iu = MatrixExtra::t_shallow(MatrixExtra::as.csr.matrix(x))
private$item_ids = colnames(c_ui)
if ((private$feedback != "explicit") || private$non_negative) {
stopifnot(all(c_ui@x >= 0))
}
n_user = nrow(c_ui)
n_item = ncol(c_ui)
logger$trace("initializing U")
if (private$precision == "double") {
private$U = large_rand_matrix(private$rank, n_user)
if (private$with_user_item_bias) {
private$U[1L, ] = rep(1.0, n_user)
}
} else {
private$U = flrnorm(private$rank, n_user, 0, 0.01)
if (private$with_user_item_bias) {
private$U[1L, ] = float::fl(rep(1.0, n_user))
}
}
if (is.null(self$components)) {
if (private$solver_code == 1L) {
if (private$precision == "double") {
self$components = matrix(0, private$rank, n_item)
if (private$with_user_item_bias) {
self$components[private$rank, ] = rep(1.0, n_item)
}
} else {
self$components = float::float(0, private$rank, n_item)
if (private$with_user_item_bias) {
self$components[private$rank, ] = float::fl(rep(1.0, n_item))
}
}
} else {
if (private$precision == "double") {
self$components = large_rand_matrix(private$rank, n_item)
if (private$with_user_item_bias) {
self$components[private$rank, ] = rep(1.0, n_item)
}
} else {
self$components = flrnorm(private$rank, n_item, 0, 0.01)
if (private$with_user_item_bias) {
self$components[private$rank, ] = float::fl(rep(1.0, n_item))
}
}
}
} else {
stopifnot(is.matrix(self$components) || is.float(self$components))
stopifnot(ncol(self$components) == n_item)
stopifnot(nrow(self$components) == private$rank)
}
if (private$non_negative) {
self$components = abs(self$components)
private$U = abs(private$U)
}
stopifnot(ncol(private$U) == ncol(c_iu))
stopifnot(ncol(self$components) == ncol(c_ui))
if (private$with_user_item_bias) {
logger$debug("initializing biases")
if (private$feedback == "explicit" && private$with_global_bias)
c_ui@x = deep_copy(c_ui@x)
if (private$precision == "double") {
user_bias = numeric(n_user)
item_bias = numeric(n_item)
} else {
user_bias = float(n_user)
item_bias = float(n_item)
}
global_bias = private$init_user_item_bias(c_ui, c_iu, user_bias, item_bias)
self$components[1L, ] = item_bias
private$U[private$rank, ] = user_bias
if(private$with_global_bias) self$global_bias = global_bias
} else if (private$with_global_bias) {
if (private$feedback == "explicit") {
self$global_bias = mean(c_ui@x)
c_ui@x = c_ui@x - self$global_bias
c_iu@x = c_iu@x - self$global_bias
} else {
s = sum(c_ui@x)
self$global_bias = s / (s + as.numeric(nrow(c_ui))*as.numeric(ncol(c_ui)) - length(c_ui@x))
}
}
if (private$feedback == "implicit") {
size_global_bias_base = ifelse(private$with_user_item_bias, 0L, private$rank-1L)
if (private$precision == "double")
self$global_bias_base = numeric(size_global_bias_base)
else
self$global_bias_base = float(size_global_bias_base)
}
logger$info("starting factorization with %d threads", getOption("rsparse_omp_threads", 1L))
loss_prev_iter = Inf
cnt_u = numeric()
cnt_i = numeric()
if (private$dynamic_lambda) {
cnt_u = as.numeric(diff(c_ui@p))
cnt_i = as.numeric(diff(c_iu@p))
}
if (private$precision == "float") {
cnt_u = float::fl(cnt_u)
cnt_i = float::fl(cnt_i)
}
private$cnt_u = cnt_u
for (i in seq_len(n_iter)) {
loss = private$solver(c_ui, private$U, self$components,
is_bias_last_row = TRUE,
cnt_X = cnt_i)
logger$info("iter %d (items) loss = %.4f", i, loss)
loss = private$solver(c_iu, self$components, private$U,
is_bias_last_row = FALSE,
cnt_X = cnt_u)
logger$info("iter %d (users) loss = %.4f", i, loss)
if (loss_prev_iter / loss - 1 < convergence_tol) {
logger$info("Converged after %d iterations", i)
break
}
loss_prev_iter = loss
}
if (private$precision == "double")
data.table::setattr(self$components, "dimnames", list(NULL, colnames(x)))
else
data.table::setattr(self$components@Data, "dimnames", list(NULL, colnames(x)))
rank_ = ifelse(private$with_user_item_bias, private$rank - 1L, private$rank)
ridge = fl(diag(x = private$lambda, nrow = rank_, ncol = rank_))
XX = if (private$with_user_item_bias) self$components[-1L, , drop = FALSE] else self$components
private$XtX = tcrossprod(XX) + ridge
self$transform(x)
},
transform = function(x, ...) {
stopifnot(ncol(x) == ncol(self$components))
if (inherits(x, "RsparseMatrix")) {
x = MatrixExtra::t_shallow(x)
x = MatrixExtra::as.csc.matrix(x)
} else if (inherits(x, "CsparseMatrix")) {
x = MatrixExtra::t_deep(x)
x = MatrixExtra::as.csc.matrix(x)
} else {
x = MatrixExtra::as.csr.matrix(x)
x = MatrixExtra::t_shallow(x)
}
if (private$feedback == "implicit" ) {
logger$trace("WRMF$transform(): calling `RhpcBLASctl::blas_set_num_threads(1)` (to avoid thread contention)")
blas_threads_keep = RhpcBLASctl::blas_get_num_procs()
RhpcBLASctl::blas_set_num_threads(1)
on.exit({
logger$trace("WRMF$transform(): on exit `RhpcBLASctl::blas_set_num_threads(%d)", blas_threads_keep)
RhpcBLASctl::blas_set_num_threads(blas_threads_keep)
})
}
x = private$preprocess(x)
if (self$global_bias != 0. && private$feedback == "explicit")
x@x = x@x - self$global_bias
if (private$precision == "double") {
res = matrix(0, nrow = private$rank, ncol = ncol(x))
} else {
res = float(0, nrow = private$rank, ncol = ncol(x))
}
if (private$with_user_item_bias) {
res[1, ] = if(private$precision == "double") 1.0 else float::fl(1.0)
}
loss = private$solver(
x,
self$components,
res,
is_bias_last_row = FALSE,
XtX = private$XtX,
cnt_X = private$cnt_u,
avoid_cg = TRUE
)
res = t(res)
if (private$precision == "double")
setattr(res, "dimnames", list(colnames(x), NULL))
else
setattr(res@Data, "dimnames", list(colnames(x), NULL))
res
}
),
private = list(
solver_code = NULL,
cg_steps = NULL,
scorers = NULL,
lambda = NULL,
dynamic_lambda = FALSE,
rank = NULL,
non_negative = NULL,
cnt_u = NULL,
U = NULL,
I = NULL,
preprocess = NULL,
feedback = NULL,
precision = NULL,
XtX = NULL,
solver = NULL,
with_user_item_bias = NULL,
with_global_bias = NULL,
init_user_item_bias = NULL
)
)
als_implicit = function(
x, X, Y,
lambda,
n_threads,
solver_code,
cg_steps,
precision,
with_user_item_bias,
is_bias_last_row,
initialize_bias_base,
global_bias = 0.,
XtX = NULL,
global_bias_base = NULL) {
solver = ifelse(precision == "float",
als_implicit_float,
als_implicit_double)
if(is.null(XtX)) {
rank = ifelse(with_user_item_bias, nrow(X) - 1L, nrow(X))
ridge = fl(diag(x = lambda, nrow = rank, ncol = rank))
if (with_user_item_bias) {
index_row_to_discard = ifelse(is_bias_last_row, nrow(X), 1L)
XX = X[-index_row_to_discard, , drop = FALSE]
} else {
XX = X
}
XtX = tcrossprod(XX) + ridge
}
if (is.null(global_bias_base)) {
global_bias_base = numeric()
if (precision == "float")
global_bias_base = float::fl(global_bias_base)
}
loss = solver(x, X, Y, XtX, lambda, n_threads, solver_code, cg_steps,
with_user_item_bias, is_bias_last_row, global_bias,
global_bias_base, initialize_bias_base)
}
als_explicit = function(
x, X, Y, cnt_X,
lambda,
n_threads,
solver_code,
cg_steps,
dynamic_lambda,
precision,
with_user_item_bias,
is_bias_last_row) {
solver = ifelse(precision == "float",
als_explicit_float,
als_explicit_double)
loss = solver(x, X, Y, cnt_X, lambda, n_threads, solver_code, cg_steps, dynamic_lambda, with_user_item_bias, is_bias_last_row)
}
solver_explicit = function(x, X, Y, lambda = 0, non_negative = FALSE) {
res = vector("list", ncol(x))
ridge = diag(x = lambda, nrow = nrow(X), ncol = nrow(X))
for (i in seq_len(ncol(x))) {
p1 = x@p[[i]]
p2 = x@p[[i + 1L]]
j = p1 + seq_len(p2 - p1)
x_nnz = x@x[j]
ind_nnz = x@i[j] + 1L
X_nnz = X[, ind_nnz, drop = F]
XtX = tcrossprod(X_nnz) + ridge
if (non_negative) {
res[[i]] = c_nnls_double(XtX, X_nnz %*% x_nnz, 10000L, 1e-3)
} else {
res[[i]] = solve(XtX, X_nnz %*% x_nnz)
}
}
res = do.call(cbind, res)
res
}
solver_explicit_biases = function(x, X, Y, bias_index = 1L, lambda = 0, non_negative = FALSE) {
ones = rep(1.0, ncol(Y))
y_bias_index = bias_index
x_bias_index = setdiff(c(1, 2), y_bias_index)
biases = X[x_bias_index, ]
res = vector("list", ncol(x))
ridge = diag(x = lambda, nrow = nrow(X) - 1L, ncol = nrow(X) - 1L)
for (i in seq_len(ncol(x))) {
p1 = x@p[[i]]
p2 = x@p[[i + 1L]]
j = p1 + seq_len(p2 - p1)
ind_nnz = x@i[j] + 1L
x_nnz = x@x[j] - biases[ind_nnz]
X_nnz = X[-x_bias_index, ind_nnz, drop = F]
XtX = tcrossprod(X_nnz) + ridge
if (non_negative) {
res[[i]] = c_nnls_double(XtX, X_nnz %*% x_nnz, 10000L, 1e-3)
} else {
res[[i]] = solve(XtX, X_nnz %*% x_nnz)
}
}
res = do.call(cbind, res)
if (y_bias_index == 1) {
res = rbind(res[1, ], ones, res[-1, ], deparse.level = 0 )
} else {
res = rbind(ones, res, deparse.level = 0 )
}
res
} |
use_logger <- function(
pkg = desc::desc_get("Package", rprojroot::find_package_root_file("DESCRIPTION"))[[1]]
){
code <- sprintf(
'.onLoad <- function(...){
assign(
"lg",
lgr::get_logger("%s"),
envir = parent.env(environment())
)
}', pkg
)
msg <- sprintf(
"Add the following to any R file in your package (usually '%s-package.R' or 'zzz.R'):",
pkg
)
message("\n", msg, "\n")
cat(code)
invisible(code)
} |
context("util_tibble2raster")
maptib <- util_raster2tibble(fractal_landscape)
mapras <- util_tibble2raster(maptib)
test_that("basic functionality", {
expect_error(util_tibble2raster(maptib), NA)
})
test_that("nlm_edgegradient behaves like it should", {
expect_that(mapras, is_a("RasterLayer"))
}) |
plot.QTLprof <- function(x, gen.eff = FALSE, mppData, Q.eff, QTL = NULL,
type = "l", main = "QTL profile", threshold = 3,
text.size = 18, ...)
{
if(!inherits(x, "QTLprof")){stop("'x' is not of class ", dQuote("QTLprof"))}
if(!gen.eff){
chr <- x$chr
pos.cM <- x$pos.cM
log10pval <- x$log10pval
Qprof <- data.frame(chr, pos.cM, log10pval)
if(!is.null(QTL)){
if(inherits(QTL, "QTLlist")){
pos.Q <- QTL[, c(2, 4)]
} else{
if(!((is.matrix(QTL)) & (dim(QTL)[2] == 2) & (is.numeric(QTL)))){
stop("'QTL' must be a two columns numeric matrix with ",
"chromosome, and marker position")
}
pos.Q <- data.frame(QTL)
colnames(pos.Q) <- c("chr", "pos.cM")
}
}
if(is.null(QTL)){
if (type == "l") {
ggplot(Qprof, aes(x = pos.cM, y = log10pval, group = chr)) + geom_line() +
facet_wrap(nrow = 1, ~ chr, scales = "free_x") +
geom_hline(yintercept = threshold, colour = "red") + theme_bw() +
xlab("position [cM]") + ylab("-log10(p.val)") +
ggtitle(main) +
theme(axis.title.x = element_text(size=text.size),
axis.title.y = element_text(size=text.size),
axis.text.x = element_text(size=text.size),
axis.text.y = element_text(size = text.size),
plot.title = element_text(size=(text.size + 4)),
strip.text.x = element_text(size=text.size))
} else if (type == "h") {
ggplot(Qprof, aes(x = pos.cM, xend = pos.cM, y = 0, yend = log10pval,
group = chr)) + geom_segment() +
facet_wrap(nrow = 1, ~ chr, scales = "free_x") +
geom_hline(yintercept = threshold, colour = "red") +
theme_bw() + xlab("position [cM]") + ylab("-log10(p.val)") +
ggtitle(main) +
theme(axis.title.x = element_text(size=text.size),
axis.title.y = element_text(size=text.size),
axis.text.x = element_text(size=text.size),
axis.text.y = element_text(size = text.size),
plot.title = element_text(size=(text.size + 4)),
strip.text.x = element_text(size=text.size))
}
} else {
if (type == "l") {
ggplot(Qprof, aes(x = pos.cM, y = log10pval, group = chr)) + geom_line() +
facet_wrap(nrow = 1, ~ chr, scales = "free_x") +
geom_vline(aes(xintercept = pos.cM), pos.Q, linetype = "longdash",
colour = "black") +
geom_hline(yintercept = threshold, colour = "red") + theme_bw() +
xlab("position [cM]") + ylab("-log10(p.val)") +
ggtitle(main) +
theme(axis.title.x = element_text(size=text.size),
axis.title.y = element_text(size=text.size),
axis.text.x = element_text(size=text.size),
axis.text.y = element_text(size = text.size),
plot.title = element_text(size=(text.size + 4)),
strip.text.x = element_text(size=text.size))
} else if (type == "h") {
ggplot(Qprof, aes(x = pos.cM, xend = pos.cM, y = 0, yend = log10pval,
group = chr)) + geom_segment() +
facet_wrap(nrow = 1, ~ chr, scales = "free_x") +
geom_vline(aes(xintercept = pos.cM), pos.Q, linetype = "longdash",
colour = "black") +
geom_hline(yintercept = threshold, colour = "red") +
theme_bw() + xlab("position [cM]") + ylab("-log10(p.val)") +
ggtitle(main) +
theme(axis.title.x = element_text(size=text.size),
axis.title.y = element_text(size=text.size),
axis.text.x = element_text(size=text.size),
axis.text.y = element_text(size = text.size),
plot.title = element_text(size=(text.size + 4)),
strip.text.x = element_text(size=text.size))
}
}
} else {
if(!(Q.eff %in% c("cr", "par", "anc"))){
stop("'Q.eff' must be ", dQuote("cr"), ', ', dQuote("par"), ', ',
dQuote("anc"), ' or ', dQuote("biall"))
}
n.eff <- dim(x)[2] - 5
if(n.eff == 0) {
stop("'x' does not contain any QTL p-value information. ",
"Use plot.gen.eff = TRUE, when you compute the QTL profile")
}
if((Q.eff == "par") || (Q.eff == "anc")){
con.part <- design_connectivity(par_per_cross = mppData$par.per.cross,
plot_des = FALSE)
len.con <- unlist(lapply(X = con.part, FUN = function(x) length(x)))
con.part <- con.part[names(sort(len.con, decreasing = FALSE))]
allele_order <- c()
pval <- data.frame(row.names = 1:dim(x)[1])
ref.ind <- length(con.part) + 1
for(i in seq_along(con.part)){
con.part_i <- con.part[[i]]
pval_i <- x[, con.part_i]
all.ref <- apply(X = pval_i, MARGIN = 2,
FUN = function(x) sum(x == 1))
pval <- cbind.data.frame(pval, pval_i[, names(sort(all.ref))])
allele_ord_i <- names(sort(all.ref))
allele_ord_i <- c(paste(allele_ord_i, paste0("(c", (ref.ind-i),")"),
sep = "\n"))
allele_order <- c(allele_order, allele_ord_i)
}
x <- cbind(x[, 1:5], pval)
y.names <- allele_order
}
if(!is.null(QTL)){
stopifnot(inherits(QTL, "QTLlist"))
pos.Q <- QTL[, c(2, 4)]
}
z <- c(apply(X = x[, 6:dim(x)[2]], MARGIN = c(1, 2),
FUN = color.code))
y <- factor(rep(1:n.eff, each = dim(x)[1]))
chr <- rep(x$chr, n.eff)
x.pos <- rep(x$pos.cM, n.eff)
w <- tapply(X = x$pos.cM, INDEX = x$chr,
FUN = function(x) c(diff(x), 1))
w <- unlist(w)
w <- rep(w, n.eff)
pos.cM <- x$pos.cM
y_lab <- "parents"
if(Q.eff == "cr") {
cross.names <- unique(mppData$cross.ind)
par.cross.names <- paste0("(", mppData$par.per.cross[, 2],
"x", mppData$par.per.cross[, 3], ")")
y.names <- paste(cross.names, par.cross.names, sep = "\n")
y_lab <- "crosses"
}
data <- data.frame(x.pos, y, z, chr, w)
if(is.null(QTL)){
pl <- ggplot(data, aes(x.pos, y, z = z))
pl + geom_tile(aes(fill = z, width = w)) +
facet_wrap(nrow = 1, ~ chr, scales = "free_x") +
scale_fill_gradient2(limits = c(-6, 6), low = "blue", mid = "white",
high = "red") +
theme_bw() + xlab("position [cM]") + ylab(y_lab) +
scale_y_discrete(labels = y.names) + ggtitle(main) +
theme(axis.title.x = element_text(size=text.size),
axis.title.y = element_text(size=text.size),
axis.text.x = element_text(size=text.size),
axis.text.y = element_text(size = text.size),
plot.title = element_text(size=(text.size+4)),
strip.text.x = element_text(size=text.size),
legend.title = element_text(size=(text.size-2)),
legend.text = element_text(size=(text.size-2)))
} else {
pl <- ggplot(data, aes(x.pos, y, z = z))
pl + geom_tile(aes(fill = z, width = w)) +
facet_wrap(nrow = 1, ~ chr, scales = "free_x") +
scale_fill_gradient2(limits = c(-6, 6), low = "blue", mid = "white",
high = "red") +
geom_vline(aes(xintercept = pos.cM), pos.Q, linetype = "longdash") +
theme_bw() + xlab("position [cM]") + ylab(y_lab) +
scale_y_discrete(labels = y.names) + ggtitle(main) +
theme(axis.title.x = element_text(size=text.size),
axis.title.y = element_text(size=text.size),
axis.text.x = element_text(size=text.size),
axis.text.y = element_text(size = text.size),
plot.title = element_text(size=(text.size+4)),
strip.text.x = element_text(size=text.size),
legend.title = element_text(size=(text.size-2)),
legend.text = element_text(size=(text.size-2)))
}
}
} |
TestSet_TMTI <- function (
pvals,
subset,
alpha = 0.05,
tau = NULL,
K = NULL,
earlyStop = FALSE,
verbose = FALSE,
gammalist = NULL,
...
) {
m <- length(pvals)
m2 <- length(subset)
pSub <- sort(pvals[subset])
pRest <- sort(pvals[-subset])
out <- list()
if (!is.null(K) & length(K) < m) {
K <- rep(K, length.out = m)
}
pfirst <- TMTI(pSub, tau = tau, K = K[m2], gamma = gammalist[[m2]], ...)
out[[1]] <- c(
"p" = pfirst,
"layer" = 0,
"Accept" = (pfirst >= alpha)
)
if (earlyStop & out[[1]][3]) {
return(out[[1]][1])
}
stepCounter <- 0
for (i in length(pRest):1) {
stepCounter <- stepCounter + 1
if (verbose) {
cat("\rStep", stepCounter, " of ", length(pRest))
}
ptilde <- c(pSub, pRest[length(pRest):i])
pp <- TMTI (
ptilde,
tau = tau,
K = K[length(ptilde)],
gamma = gammalist[[length(ptilde)]],
...
)
out[[stepCounter + 1]] <- c (
"p" = pp,
"layer" = stepCounter,
"Accept" = (pp >= alpha)
)
if (earlyStop & out[[stepCounter + 1]][3])
break
}
out <- do.call("rbind", out)
max(out[, 1])
} |
r2d <- function(radian) radian*180/pi |
instRemPiFun <- function(p){
M <- nrow(p)
J <- ncol(p)
pi <- matrix(NA, M, J)
p[,1] <- pi[,1] <- 1 - (1 - p[,1])^2
p[,2] <- 1 - (1 - p[,2])^3
p[,3] <- 1 - (1 - p[,3])^5
for(i in 2:J) {
pi[,i] <- pi[, i - 1]/p[, i - 1] * (1 - p[, i - 1]) * p[, i]
}
return(pi)
}
crPiFun <- function(p) {
p1 <- p[,1]
p2 <- p[,2]
p3 <- p[,3]
cbind("001" = (1 - p1) * (1 - p2) * p3,
"010" = (1 - p1) * p2 * (1 - p3),
"011" = (1 - p1) * p2 * p3,
"100" = p1 * (1 - p2) * (1 - p3),
"101" = p1 * (1 - p2) * p3,
"110" = p1 * p2 * (1 - p3),
"111" = p1 * p2 * p3)
}
crPiFun.Mb <- function(p) {
pNaive <- p[,1]
pWise <- p[,3]
cbind("001" = (1 - pNaive) * (1 - pNaive) * pNaive,
"010" = (1 - pNaive) * pNaive * (1 - pWise),
"011" = (1 - pNaive) * pNaive * pWise,
"100" = pNaive * (1 - pWise) * (1 - pWise),
"101" = pNaive * (1 - pWise) * pWise,
"110" = pNaive * pWise * (1 - pWise),
"111" = pNaive * pWise * pWise)
}
MhPiFun <- function(p) {
mu <- qlogis(p[,1])
sig <- exp(qlogis(p[1,2]))
J <- ncol(p)
M <- nrow(p)
il <- matrix(NA, nrow=M, ncol=7)
dimnames(il) <- list(NULL, c("001","010","011","100","101","110","111"))
for(i in 1:M) {
il[i,1] <- integrate( function(x) {
(1-plogis(mu[i]+x))*(1-plogis(mu[i]+x))*plogis(mu[i]+x)*dnorm(x,0,sig)
}, lower=-Inf, upper=Inf, stop.on.error=FALSE)$value
il[i,2] <- integrate( function(x) {
(1-plogis(mu[i]+x))*plogis(mu[i]+x)*(1-plogis(mu[i]+x))*dnorm(x,0,sig)
}, lower=-Inf, upper=Inf, stop.on.error=FALSE)$value
il[i,3] <- integrate( function(x) {
(1-plogis(mu[i]+x))*plogis(mu[i]+x)*plogis(mu[i]+x)*dnorm(x,0,sig)
}, lower=-Inf, upper=Inf, stop.on.error=FALSE)$value
il[i,4] <- integrate( function(x) {
plogis(mu[i]+x)*(1-plogis(mu[i]+x))*(1-plogis(mu[i]+x))*dnorm(x,0,sig)
}, lower=-Inf, upper=Inf, stop.on.error=FALSE)$value
il[i,5] <- integrate( function(x) {
plogis(mu[i]+x)*(1-plogis(mu[i]+x))*plogis(mu[i]+x)*dnorm(x,0,sig)
}, lower=-Inf, upper=Inf, stop.on.error=FALSE)$value
il[i,6] <- integrate( function(x) {
plogis(mu[i]+x)*plogis(mu[i]+x)*(1-plogis(mu[i]+x))*dnorm(x,0,sig)
}, lower=-Inf, upper=Inf, stop.on.error=FALSE)$value
il[i,7] <- integrate( function(x) {
plogis(mu[i]+x)*plogis(mu[i]+x)*plogis(mu[i]+x)*dnorm(x,0,sig)
}, lower=-Inf, upper=Inf, stop.on.error=FALSE)$value
}
return(il)
} |
.extentMatrix <- function(x) {
xy <- matrix(NA, nrow=5, ncol=2)
xy[c(1,4),1] <- x@xmin
xy[2:3,1] <- x@xmax
xy[1:2,2] <- x@ymax
xy[3:4,2] <- x@ymin
xy[5,] <- xy[1,]
return(xy)
}
setMethod("plot", signature(x='Extent', y='missing'),
function(x, y, type='l', add=FALSE, ...) {
xy <- .extentMatrix(x)
if (add) {
lines(xy, ...)
} else {
plot(xy, type=type, ...)
}
}
) |
flexrsurv.ll <- function(formula=formula(data),
data=parent.frame(),
knots.Bh=NULL,
degree.Bh=3,
Spline=c("b-spline","tp-spline","tpi-spline"),
log.Bh=FALSE,
bhlink=c("log", "identity"),
Min_T=0,
Max_T=NULL,
model=c("additive","multiplicative"),
rate=NULL,
weights=NULL,
na.action=NULL,
int_meth=c("GL", "CAV_SIM", "SIM_3_8", "BOOLE", "GLM", "BANDS"),
npoints=20,
stept=NULL,
bands=NULL,
init=NULL,
optim.control=list(trace=100, REPORT=1, fnscale=-1, maxit=25),
optim_meth=c("BFGS", "CG", "Nelder-Mead", "L-BFGS-B", "SANN", "Brent"),
vartype = c("oim", "opg", "none"),
debug=FALSE
){
debug.gr <- debug.ll <- FALSE
if( debug > 100000){
debug.gr <- debug%%1000 + debug%/%100000 * 1000
}
if( debug > 10000){
debug.ll <- debug%%1000 + (debug%/%10000)%%10 * 1000
}
debug <- debug%%1000 + (debug%/%1000)%%10 * 1000
optim.control$fnscale <- -1
vartype <- match.arg(vartype)
optim_meth <- match.arg(optim_meth)
int_meth <- match.arg(int_meth)
if (int_meth == "BANDS" ){
int_meth = "GLM"
}
call <- match.call()
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data", "rate", "weights"), names(mf), 0L)
if (m[1]==0)
stop ("The formula argument is required.")
mf <- mf[c(1L, m)]
mf$drop.unused.levels <- TRUE
mf[[1L]] <- quote(stats::model.frame)
special <- c("NPH","NLL", "NPHNLL", "nl", "td", "nltd")
Terms <- if (missing(data)){
terms(formula, specials=special)
} else {
terms(formula, specials=special, data = data)
}
mf$formula <- Terms
mf <- eval(mf, sys.parent())
mt <- attr(mf, "terms")
na.act <- attr(m, "na.action")
if( !is.null( na.act )) {
data <- data[na.act,]
}
intercept <- attr(mt, "intercept")
Y <- model.extract(mf, "response")
if (!inherits(Y, "Surv")) {
stop("Response must be a survival object")
}
type <- attr(Y, "type")
if ((ncol(Y) == 2) && (type != "right") ) {
stop(gettextf("flexrsurv does not support %s type of censoring with (0, end] survival data", dQuote(type), domaine=NA))
} else if ((ncol(Y) == 3) && (type != "counting") ) {
stop(gettextf("flexrsurv does not support %s type of censoring with (start, end] survival data", dQuote(type), domaine=NA))
}
weights <- as.vector(model.weights(mf))
if (!is.null(weights) && !is.numeric(weights))
stop("'weights' must be a numeric vector")
if (!is.null(weights) && any(weights < 0))
stop("negative weights not allowed")
rate <- as.vector(model.extract(mf, "rate"))
if(!is.null(rate) && !is.numeric(rate))
stop("'rate' must be a numeric vector")
if (is.null(rate)){
data$rate <- 0
} else {
data$rate <- rate
}
if(is.null(Max_T)){
Max_T <- max(Y[,1:(ncol(Y)-1)])
}
if(is.null(Min_T)){
Min_T <- 0
}
if(Spline=="b-spline"){
Spline_t0 <- BSplineBasis(knots=c(Min_T, knots.Bh, Max_T),
degree=degree.Bh,
keep.duplicates=TRUE,
log=log.Bh)
Spline_t<- BSplineBasis(knots=c(Min_T, knots.Bh, Max_T),
degree=degree.Bh,
keep.duplicates=TRUE,
log=FALSE)
} else if(Spline=="tp-spline" || Spline=="tpi-spline"){
Spline_t0 <-TPSplineBasis(knots=knots.Bh,
degree=degree.Bh,
min=Min_T,
max=Max_T,
log=log.Bh,
type="standard")
Spline_t <-TPSplineBasis(knots=knots.Bh,
degree=degree.Bh,
min=Min_T,
max=Max_T,
log=FALSE,
type="standard")
}
list_var_LIN <- all_LIN_vars(Terms)
list_var_NLL <- all_specials_vars(Terms, specials="NLL",
unique = FALSE,
order="formula")
list_var_NPH <- all_specials_vars(Terms, specials="NPH",
unique = FALSE,
order="formula")
list_var_NPHNLL <- all_specials_vars(Terms, specials="NPHNLL",
unique = FALSE,
order="formula")
var_LIN_NPHNLL <- list_var_LIN %in% c(list_var_NLL, list_var_NPH, list_var_NPHNLL)
var_NPH_NLL <- list_var_NPH %in% list_var_NLL
var_NLL_NPHNLL <- list_var_NLL %in% list_var_NPHNLL
var_NPH_NPHNLL <- list_var_NPH %in% list_var_NPHNLL
des <- ReadDesignFlexrsurv(Terms=Terms, modframe=mf, data=data, rate=rate, Spline_t0=Spline_t0)
if(!is.null(des$X) | !is.null(des$Z)){
allSpline_T <- c(des$Spline_XT, des$Spline_ZT)
if(length(allSpline_T) > 1){
for(sb in allSpline_T){
if(!identical(sb, allSpline_T[[1]])){
stop("flexrsurv cannot handle different spline basis for time dependent effects")
}
}
}
Spline_t <-allSpline_T[[1]]
}
therate<-des$rate
X0<-des$X0
if(!is.null(des$X)){
X<-as.matrix(des$X)
Intercept_t_NPH <- rep(TRUE, length(des$XVars))
for (i in attr(des$TermsX, "specials")[["NPH"]]){
thecall <- match.call(NPH, attr(des$TermsX,"variables")[[i+1]])
Intercept_t_NPH[i] <- ifelse( length(thecall[["Intercept.t"]]) == 0 ,
formals(NPH)[["Intercept.t"]],
thecall[["Intercept.t"]] )
}
} else {
X <- NULL
Intercept_t_NPH <- NULL
}
Spline_Z <- des$Spline_Z
if( !is.null(des$Z) ){
Z<-DesignMatrixNPHNLL(Z=des$Z, listsplinebasis=Spline_Z, timesplinebasis=Spline_t)
} else {
Z <- NULL
}
listinit<- list(gamma0 = init[des$coef2param$gamma0],
alpha0 = init[des$coef2param$alpha0],
beta0 = init[des$coef2param$beta0],
alpha = init[des$coef2param$alpha],
beta = init[des$coef2param$beta])
if( int_meth=="GLM" ){
if (is.null(bands)){
bands <- default_bands(Spline_t)
}
method <- list(int_meth=int_meth, bands=bands, optim_meth=optim_meth)
} else if( int_meth == "GL"){
if (is.null(npoints)){
npoints <- 20
}
method <- list(int_meth="Gauss-Legendre", npoints=npoints, optim_meth=optim_meth)
} else {
if (is.null(stept)){
stept <- Max_T /500
}
method <- list(int_meth=int_meth, stept=stept, optim_meth=optim_meth)
}
if(ncol(Y)==2){
fit<-flexrsurv.ll.fit(X0=X0, X=X, Z=Z, Y=Y,
expected_rate=rate,
weights=weights,
Spline_t0=Spline_t0, Intercept_t0=TRUE,
Spline_t = Spline_t, Intercept_t_NPH=Intercept_t_NPH,
bhlink=bhlink,
init=listinit,
optim.control=optim.control,
method=method,
vartype = vartype,
debug=debug,
debug.ll=debug.ll, debug.gr=debug.gr)
} else {
fit<-flexrsurv.ll.fromto.fit(X0=X0, X=X, Z=Z, Y=Y,
expected_rate=rate,
weights=weights,
Spline_t0=Spline_t0, Intercept_t0=TRUE,
Spline_t = Spline_t, Intercept_t_NPH=Intercept_t_NPH,
bhlink=bhlink,
init=listinit,
optim.control=optim.control,
method=method,
vartype = vartype,
debug=debug,
debug.ll=debug.ll, debug.gr=debug.gr)
}
objfit <- fit
objfit$coefficients <- fit$coefficients[des$param2coef]
names(objfit$coefficients)[-(1:des$df.T0)] <- des$names_coef_XZ
if( !is.null(dim(fit$var))){
objfit$var <- (fit$var[des$param2coef, ])[,des$param2coef]
dimnames(objfit$var)[[1]] <- names(objfit$coefficients)
dimnames(objfit$var)[[2]] <- names(objfit$coefficients)
attr(objfit$var, "type") <- vartype
}
if( !is.null(dim(fit$informationMatrix))){
objfit$informationMatrix <- (fit$informationMatrix[des$param2coef, ])[,des$param2coef]
dimnames(objfit$informationMatrix)[[1]] <- names(objfit$coefficients)
dimnames(objfit$informationMatrix)[[2]] <- names(objfit$coefficients)
attr(objfit$informationMatrix, "type") <- vartype
}
objfit$des <- des
objfit$terms <- Terms
objfit$mt <- mt
objfit$assign <- des$assign
objfit$assignList <- des$assignList
objfit$na.action <- attr(m, "na.action")
objfit$optim.control <- optim.control
objfit$converged <- objfit$conv
objfit$conv <- NULL
class(objfit) <- "flexrsurv.mle"
return(objfit)
} |
Return <- MINIF(iris$Species,"virginica",iris$Sepal.Length)
expect_equal(Return,4.9) |
gmult <- function(x, splits, fact) {
if(!is.spam(x)) {
x <- as.spam(x) }
splits <- sort.int(unique(as.integer(splits)))
if(splits[length(splits)] < max(dim(x))+1) {
splits <- c(splits, max(dim(x))+1) }
fact <- as.matrix(fact)
stopifnot(dim(fact) == (length(splits)-1))
ll <- length(x@entries)
if(.format.spam(x)$package == "spam64" || getOption("spam.force64")) {
SS <- .format64()
} else {
SS <- .format32
}
x@entries <- dotCall64::.C64("gmult_f",
SIGNATURE = c("double", SS$signature, SS$signature, SS$signature, SS$signature,
"double", SS$signature, "double"),
a = x@entries,
ia = x@colindices,
ja = x@rowpointers,
na = ll,
splits = splits,
fact = fact,
nfact = dim(fact)[2],
out = dotCall64::numeric_dc(ll),
INTENT = c( "r", "r", "r", "r",
"r", "r", "r", "rw"),
NAOK=getOption("spam.NAOK"),
PACKAGE = SS$package)$out
return(x)
} |
rigidTransform <- function( theta, p0, N, cen ) {
if(missing(N)) N <- dim(p0)[1]
p0cen <- p0 - cen
r <- theta[ 3 ]
p0cen <- cbind(cos(r) * p0cen[, 1] - sin(r) * p0cen[, 2], sin(r) * p0cen[, 1] + cos(r) * p0cen[, 2])
res <- p0cen + matrix(theta[1:2], N, 2, byrow = TRUE) + cen
return(res)
}
rigider <- function(x1, x0, p0, init = c(0, 0, 0), type = c("regular", "fast"), translate = TRUE, rotate = FALSE, loss, loss.args = NULL,
interp = "bicubic", stages = TRUE, verbose = FALSE, ...) {
if(stages && !(translate & rotate)) stages <- FALSE
if(!translate && !rotate) stop("rigider: one of translate or rotate must be true.")
if(verbose) begin.tiid <- Sys.time()
theCall <- match.call()
out <- list()
out$call <- theCall
if(missing(x1)) stop("rigider: x1 argument is missing.")
if(missing(x0)) stop("rigider: x0 argument is missing.")
if(missing(p0)) stop("rigider: p0 argument is missing.")
if(missing(loss)) loss <- "QlossRigid"
type <- tolower(type)
type <- match.arg(type)
bigN <- dim(p0)[ 1 ]
field.center <- matrix(colMeans(p0[x1 > 0,], na.rm = TRUE), bigN, 2, byrow = TRUE)
if(type == "regular") {
xdim <- dim(x1)
if(any(xdim != dim(x0))) stop("rigider: x1 and x0 must have the same dimension.")
outpar <- numeric(0)
if(missing(init)) {
if(verbose) cat("Initial values not passed. Determining good starting values now.\n")
hold1 <- imomenter(x1, loc = p0)
hold0 <- imomenter(x0, loc = p0)
tr <- hold1$centroid - hold0$centroid
if(rotate) init <- c(tr, hold1$orientation.angle - hold0$orientation.angle)
else init <- c(tr, 0)
if(verbose) {
cat( "initial values:\n" )
print( init )
}
}
if(!stages && (!translate || !rotate)) stages <- TRUE
if(stages) {
if(translate) {
ofun <- function(theta, p0, x1, x0, loss, loss.args, interp, N, cen, xdim, tr, ...) {
if(missing(tr)) tr <- NULL
if(any(c(theta[ 1 ] > xdim[ 1 ] / 2 + 1, theta[ 2 ] > xdim[ 2 ] / 2 + 1))) return(1e16)
p1 <- rigidTransform(theta = c(theta, 0), p0 = p0, N = N, cen = cen)
y1 <- Fint2d( X = x1, Ws = p1, s = p0, method = interp )
res <- do.call(loss, c(list(y1 = y1, x0 = x0, p1 = p1, p0 = p0), loss.args))
return(res)
}
if(verbose) cat("Optimizing translation.\n")
res = nlminb( init[ 1:2 ], ofun, p0 = p0, x1 = x1, x0 = x0, loss = loss, loss.args = loss.args,
interp = interp, N = bigN, cen = field.center, xdim = xdim, ... )
if(verbose) cat("Optimal translation found to be: ", res$par, "\nwhere loss value is: ", res$value, "\n")
p1 <- rigidTransform(theta = c(res$par, init[ 3 ]), p0 = p0, N = bigN, cen = field.center)
y1 <- Fint2d( X = x1, Ws = p1, s = p0, method = interp )
res$p1 <- p1
out$x1.translated <- y1
outpar <- res$par
outval = res$objective
}
if(rotate) {
if(translate) init2 <- c(res$par, init[ 3 ])
else init2 <- init
ofun <- function(theta, p0, x1, x0, loss, loss.args, interp, N, cen, xdim, tr, ...) {
if((theta > pi / 2) || (theta < - pi / 2)) return(1e16)
p1 <- rigidTransform(theta = c(tr, theta), p0 = p0, N = N, cen = cen)
y1 <- Fint2d(X = x1, Ws = p1, s = p0, method = interp)
res <- do.call(loss, c(list(y1 = y1, x0 = x0, p1 = p1, p0 = p0), loss.args))
return(res)
}
if(verbose) cat("Optimizing rotation.\n")
res2 = nlminb( init2[ 3 ], ofun, p0 = p0, x1 = x1, x0 = x0, loss = loss, loss.args = loss.args,
interp = interp, N = bigN, cen = field.center, xdim = xdim, tr = init2[ 1:2 ], ... )
if(verbose) cat("Optimal rotation found to be: ", res2$par, "\nwhere loss value is: ", res2$value, "\n")
p1 <- rigidTransform(theta = c(init2[ 1:2 ], res2$par), p0 = p0, N = bigN, cen = field.center)
y1 <- Fint2d(X = x1, Ws = p1, s = p0, method = interp)
outpar <- c(outpar, res2$par)
outval <- res2$objective
}
} else {
ofun <- function(theta, p0, x1, x0, loss, loss.args, interp, N, cen, xdim, tr, ...) {
if(missing(tr)) tr <- NULL
if(any(c(theta[ 1 ] > xdim[ 1 ] / 2 + 1, theta[ 2 ] > xdim[ 2 ] / 2 + 1))) return(1e16)
if((theta > pi / 2) || (theta < - pi / 2)) return(1e16)
p1 <- rigidTransform(theta = theta, p0 = p0, N = N, cen = cen)
y1 <- Fint2d(X = x1, Ws = p1, s = p0, method = interp)
res <- do.call(loss, c(list(y1 = y1, x0 = x0, p1 = p1, p0 = p0), loss.args))
return(res)
}
if(verbose) cat("Optimizing rigid transformation.\n")
res <- optim(init, ofun, p0 = p0, x1 = x1, x0 = x0, loss = loss, loss.args = loss.args,
interp = interp, N = bigN, cen = field.center, xdim = xdim, ...)
res = nlminb( init, ofun, p0 = p0, x1 = x1, x0 = x0, loss = loss, loss.args = loss.args,
interp = interp, N = bigN, cen = field.center, xdim = xdim, ... )
if(verbose) cat("Optimal transformation found to be: ", res$par, "\nwhere loss value is: ", res$value, "\n")
p1 <- rigidTransform(theta = res$par, p0 = p0, N = bigN, cen = field.center)
outpar <- res$par
outval <- res$val
}
if(translate && !rotate) names(outpar) <- c("x", "y")
else if(!translate && rotate) names(outpar) <- "angle"
else names(outpar) <- c("x", "y", "angle")
if(stages) {
if(translate) out$translation.only <- res
if(rotate) out$rotate <- res2
} else out$optim.object <- res
} else if(type == "fast") {
hold1 <- imomenter(x1, loc = p0)
hold0 <- imomenter(x0, loc = p0)
if(translate) tr <- hold1$centroid - hold0$centroid
if(rotate) rot <- hold1$orientation.angle - hold0$orientation.angle
if(translate && rotate) {
outpar <- inpar <- c(tr, rot)
names(outpar) <- c("x", "y", "theta")
} else if(!translate && rotate) {
outpar <- rot
inpar <- c(0, 0, rot)
names(outpar) <- "theta"
} else if(translate && !rotate) {
outpar <- tr
names(outpar) <- c("x", "y")
inpar <- c(tr, 0)
}
if(stages) {
p1.tr <- rigidTransform(theta = tr, p0 = p0, N = bigN, cen = field.center)
y1.tr <- Fint2d(X = x1, Ws = p1.tr, s = p0, method = interp)
out$x1.translated <- y1.tr
}
p1 <- rigidTransform(theta = inpar, p0 = p0, N = bigN, cen = field.center)
}
y1 <- Fint2d(X = x1, Ws = p1, s = p0, method = interp)
out$type <- type
if(type == "regular") {
out$initial <- init
out$value <- outval
out$optim.args <- list(...)
out$loss <- list(name = loss, args = loss.args)
}
out$interp.method <- interp
out$par <- outpar
out$x0 <- x0
out$x1 <- x1
out$p0 <- p0
out$p1 <- p1
out$x1.transformed <- y1
class(out) <- "rigided"
if(verbose) print(Sys.time() - begin.tiid)
return(out)
}
plot.rigided <- function(x, ...) {
zl <- range(c(c(x$x0), c(x$x1)), finite = TRUE)
par(mfrow = c(2, 3))
image(x$x0, col = c("gray", tim.colors(64)), zlim = zl, main = "x0", ...)
image(x$x1, col = c("gray", tim.colors(64)), zlim = zl, main = "x1", ...)
image.plot(x$x1.transformed, col = c("gray", tim.colors(64)), zlim = zl, main = "x1 Rigidly Transformed", ...)
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "")
image.plot(x$x1 - x$x0, col = c("gray", tim.colors(64)), main = "x1 - x0", ...)
image.plot(x$x1.transformed - x$x0, col = c("gray", tim.colors(64)), main = "x1 rigidly transformed - x0", ...)
invisible()
}
print.rigided <- function(x, ...) {
print(x$call)
cat("\n\n")
cat("Optimal rigid transformation: ", x$par, "\n")
cat("Objective function value = ", x$value, "\n")
cat("\n\n")
if(!is.null(x$translation.only)) cat("Translation convergence code (see ?nlminb for details): ", x$translation.only$convergence, "\n")
if(!is.null(x$rotate)) cat("Rotation convergence code (see ?nlminb for details): ", x$rotate$convergence, "\n")
if(!is.null(x$optim.object)) cat("Convergence code (see ?nlminb for details): ", x$optim.object$convergence, "\n")
invisible()
}
summary.rigided <- function(object, ...) {
print(object)
cat("\n\n")
MSE0 <- sum(colSums((object$x1 - object$x0)^2, na.rm = TRUE), na.rm = TRUE)
MSE1 <- sum(colSums((object$x1.transformed - object$x0)^2, na.rm = TRUE), na.rm = TRUE)
res <- ((MSE0 - MSE1) / MSE0) * 100
out <- c(MSE0, MSE1, res)
names(out) <- c("MSE0", "MSE1", "% error reduction")
print(out)
invisible(out)
} |
erptest <-
function (dta, design, design0 = NULL,
method = c("BH", "holm", "hochberg","hommel", "bonferroni", "BY", "fdr", "none"),
alpha = 0.05, pi0 = 1,nbs=NULL) {
method = match.arg(method,choices=c("BH", "holm", "hochberg","hommel", "bonferroni", "BY", "fdr", "none"))
if (is.null(design0))
design0 = matrix(1, nrow = nrow(design), ncol = 1)
erpdta = as.matrix(dta)
design = as.matrix(design)
design0 = as.matrix(design0)
if (typeof(erpdta) != "double")
stop("ERPs should be of type double")
if (nrow(erpdta) != nrow(design))
stop("dta and design should have the same number of rows")
if (nrow(erpdta) != nrow(design0))
stop("dta and design0 should have the same number of rows")
if (ncol(design) <= ncol(design0))
stop("design0 should have fewer columns than design")
idsignal = NULL
for (j in 1:ncol(design)) {
cj = apply(design0, 2, function(x, y) all(x == y), y = design[,j])
if (all(!cj))
idsignal = c(idsignal, j)
}
if (length(idsignal) < (ncol(design) - ncol(design0)))
stop("the null model design0 should be nested into the non-null model design")
if (typeof(alpha) != "double")
stop("alpha should be of type double")
if ((alpha <= 0) | (alpha >= 1))
stop("alpha should be in ]0,1[, typically 0.05")
if (typeof(pi0) != "double")
stop("pi0 should be of type double")
if ((pi0 <= 0) | (pi0 > 1))
stop("pi0 should be in ]0,1]")
n = nrow(erpdta)
T = ncol(erpdta)
if (!is.null(nbs))
if ((nbs <= 2) | (nbs > T))
stop("The number nbs of B-splines should be an integer value in [3,T[")
if (is.null(nbs)) nbs=0
svd.design = fast.svd(design)
if (ncol(design)==1) itxx = (svd.design$v%*%t(svd.design$v))/(svd.design$d[1]^2)
if (ncol(design)>1) itxx = svd.design$v%*%diag(1/svd.design$d^2)%*%t(svd.design$v)
svd.design0 = fast.svd(design0)
Proj = svd.design$u%*%t(svd.design$u)
Proj0 = svd.design0$u%*%t(svd.design0$u)
if (ncol(design)==1) pdesign = (svd.design$v%*%t(svd.design$u))/(svd.design$d[1])
if (ncol(design)>1) pdesign = svd.design$v%*%diag(1/svd.design$d)%*%t(svd.design$u)
rdf1 = nrow(design) - length(svd.design$d)
rdf0 = nrow(design0) - length(svd.design0$d)
coeff = pdesign %*% erpdta
rownames(coeff) = colnames(design)
if (nbs==0) {
beta = coeff[idsignal, ,drop=FALSE]
rownames(beta) = colnames(design)[idsignal]
res1 = erpdta - Proj %*% erpdta
rss1 = as.vector(t(rep(1, n)) %*% res1^2)
res0 = erpdta - Proj0 %*% erpdta
rss0 = as.vector(t(rep(1, n)) %*% res0^2)
fstat = ((rss0 - rss1)/(rdf0 - rdf1))/(rss1/rdf1)
pval = pf(fstat, df1 = rdf0 - rdf1, df2 = rdf1, lower.tail = FALSE)
sigma2 = mean((rss1/rdf1))
if (length(idsignal)>1)
sdsignal = sqrt(sigma2)*sqrt(diag(itxx[idsignal,idsignal]))%*%t(rep(1,T))
if (length(idsignal)==1)
sdsignal = sqrt(sigma2)*sqrt(itxx[idsignal,idsignal])*t(rep(1,T))
}
if (nbs>0) {
if (ncol(design0)==1) pdesign0 = (svd.design0$v%*%t(svd.design0$u))/(svd.design0$d[1])
if (ncol(design0)>1) pdesign0 = svd.design0$v%*%diag(1/svd.design0$d)%*%t(svd.design0$u)
phi = bs(1:T,df=nbs)
beta = coeff
svd.phi = fast.svd(phi)
pphi = svd.phi$v%*%diag(1/svd.phi$d)%*%t(svd.phi$u)
b = beta%*%t(pphi)
fit = design%*%b%*%t(phi)
rdf1 = n-length(svd.design$d)
res1 = erpdta-fit
beta0 = (pdesign0 %*% erpdta)
b0 = beta0%*%t(pphi)
fit0 = design0%*%b0%*%t(phi)
rdf0 = n-length(svd.design0$d)
res0 = erpdta-fit0
rss1 = as.vector(t(rep(1,n))%*%res1^2)
rss0 = as.vector(t(rep(1,n))%*%res0^2)
fstat = ((rss0 - rss1)/(rdf0 - rdf1))/(rss1/rdf1)
pval = pf(fstat, df1 = rdf0 - rdf1, df2 = rdf1, lower.tail = FALSE)
trSm = nbs*length(svd.design$d)
trSm2 = nbs*length(svd.design$d)
rdf = (T*n-2*trSm+trSm2)/T
sigma2 = mean((rss1/rdf))
beta = (b%*%t(phi))[idsignal,,drop=FALSE]
itphiphi = svd.phi$v%*%diag(1/svd.phi$d^2)%*%t(svd.phi$v)
vbeta = sigma2*kronecker(itphiphi,itxx)
lvb = lapply(1:ncol(design),function(i,phi,vbeta,nbs,d)
phi%*%vbeta[seq(i,d*nbs,d),seq(i,d*nbs,d)]%*%t(phi),
phi=phi,vbeta=vbeta,nbs=nbs,d=ncol(design))
lsdsignal = lapply(lvb,function(vb) sqrt(diag(vb)))
sdsignal = matrix(unlist(lsdsignal),nrow=ncol(design),byrow=TRUE)
sdsignal = sdsignal[idsignal,,drop=FALSE]
}
rownames(beta) = colnames(design)[idsignal]
rownames(sdsignal) = colnames(design)[idsignal]
if (is.null(pi0))
pi0 = pval.estimate.eta0(pval, diagnostic.plot = FALSE)
correctedpval = pi0 * p.adjust(pval, method = method)
significant = which(correctedpval <= alpha)
test = fstat
r2 = (1 - 1/(1 + fstat * ((rdf0 - rdf1)/rdf1)))
if (length(idsignal)==1) test = sign(beta[1,])*sqrt(fstat)
return(list(pval = pval, correctedpval = correctedpval, significant = significant,
pi0 = pi0, test = test, df1 = rdf1, df0 = rdf0, signal = beta,sd=sqrt(rss1/rdf1),
r2 = r2,sdsignal=sdsignal,residuals=res1,coef=coeff))
} |
derRegPIV <- function(Pvv, Pvz, Pvy){
dPvv <- derPvv(Pvv, Pvz, Pvy)
dPvz <- derPvz(Pvv, Pvz, Pvy)
dPvy <- derPvy(Pvv, Pvz, Pvy)
return(list(
deriv = rbind(dPvv$deriv, dPvz$deriv, dPvy$deriv),
names = rbind(dPvv$names, dPvz$names, dPvy$names))
)
}
derPvv <- function(Pvv, Pvz, Pvy){
if(dim(Pvv)[1] == 1){
deriv = NULL
names = NULL
} else {
U1 <- solve(t(Pvz) %*% solve(Pvv) %*% Pvz)
U2 <- t(Pvz) %*% solve(Pvv) %*% Pvy
TERM1 <- kronecker(t(solve(Pvv)%*%Pvz%*%U1 %*%U2),U1 %*% t(Pvz)%*%solve(Pvv))
TERM2 <- kronecker(t(solve(Pvv)%*%Pvy),U1 %*% t(Pvz)%*%solve(Pvv))
deriv <- t((TERM1 - TERM2) %*% buildDuplicator(nrow(Pvv)))
names <- t(utils::combn(colnames(Pvv), 2))
}
return(list(deriv = deriv, names = names))
}
derPvz <- function(Pvv, Pvz, Pvy){
if(identical(Pvv,Pvz)){
deriv = NULL
names = NULL
} else {
U <- solve(t(Pvz) %*% solve(Pvv) %*% Pvz)
TH <- U %*% t(Pvz) %*% solve(Pvv) %*% Pvy
ER <- (Pvy) - (Pvz %*% TH)
deriv <- t(kronecker(U, t(solve(Pvv) %*% ER)) -
kronecker(t(TH), U %*% t(Pvz) %*% solve(Pvv)))
names <- as.matrix(expand.grid(rownames(Pvz),colnames(Pvz)))
}
return(list(deriv = deriv, names = names))
}
derPvy <- function(Pvv, Pvz, Pvy){
deriv <- t(solve(t(Pvz) %*% solve(Pvv) %*% Pvz) %*% t(Pvz) %*% solve(Pvv))
names <- as.matrix(expand.grid(rownames(Pvy),colnames(Pvy)))
return(list(deriv = deriv, names = names))
}
buildCategoricalK <- function(eq, mat){
eq$regDerivatives <- derRegPIV(
mat[eq$MIIVs, eq$MIIVs, drop = FALSE],
mat[eq$MIIVs, eq$IVobs, drop = FALSE],
mat[eq$MIIVs, eq$DVobs, drop = FALSE]
)
acmPos <- apply(t(utils::combn(colnames(mat), 2)), 2, function(x){
match(x, colnames(mat))
})
acmPos <- cbind(acmPos, c(1:nrow(acmPos)))
reg.varID <- rbind(apply(eq$regDerivatives$names, 2, function(x){
match(x, colnames(mat))
}))
Var1 <- NULL; Var2 <- NULL
reg.varID <- transform(reg.varID,
min = pmin(Var1, Var2),
max = pmax(Var1, Var2))[,-c(1:2)]
reg.varID$order <- seq(1:nrow(reg.varID))
posInfo <- merge(reg.varID, acmPos, by=c(1,2))
posInfo <- posInfo[order(posInfo$order), ]
rowK <- matrix(0, ncol(eq$regDerivatives$deriv), ncol(utils::combn(colnames(mat), 2)))
rowK[,posInfo[,4]] <- t(eq$regDerivatives$deriv)
rowK
} |
person_external_ids <-
function(api_key, id){
url <- fromJSON(GET(url=paste("http://api.themoviedb.org/3/person/", id, "/external_ids?api_key=",
api_key, sep=""))$url)
return(url)
} |
simgraph_graph <- function(result, nsims = 10, labls = TRUE, steps = TRUE,
moves = TRUE, shadows = TRUE, kinship = NULL, show_area = TRUE,
centred = FALSE, pinwheel = FALSE, scattered = FALSE,
lengths = TRUE, lengthlabs = TRUE, histogram = FALSE,
binwidth = posigma / 5, freqpoly = FALSE) {
posigma <- result[1,]$posigma
dims <- result[1,]$dims
if (is.null(kinship))
kinship <- result[1,]$kinship
if (nsims > nrow(result)){
message(paste0("Too few families in datasource; reducing nsims to datasource maximum (", nrow(result), ")."))
nsims <- nrow(result)
}
if (pinwheel == TRUE | scattered == TRUE) {
centred <- TRUE
}
if (centred == TRUE) {
show_area <- FALSE
}
if (pinwheel == TRUE & nsims > 50) {
labls <- FALSE
}
result <- slice_head(result, n = nsims)
f0x <- result$f0x
f0y <- result$f0y
f1ax <- result$f1ax
f1ay <- result$f1ay
f1bx <- result$f1bx
f1by <- result$f1by
f1cx <- result$f1cx
f1cy <- result$f1cy
f2ax <- result$f2ax
f2ay <- result$f2ay
f2bx <- result$f2bx
f2by <- result$f2by
f3ax <- result$f3ax
f3ay <- result$f3ay
f3bx <- result$f3bx
f3by <- result$f3by
if (centred == TRUE) {
f1ax <- f1ax - f0x
f1ay <- f1ay - f0y
f1bx <- f1bx - f0x
f1by <- f1by - f0y
f1cx <- f1cx - f0x
f1cy <- f1cy - f0y
f2ax <- f2ax - f0x
f2ay <- f2ay - f0y
f2bx <- f2bx - f0x
f2by <- f2by - f0y
f3ax <- f3ax - f0x
f3ay <- f3ay - f0y
f3bx <- f3bx - f0x
f3by <- f3by - f0y
f0x <- f0x - f0x
f0y <- f0y - f0y
}
if (kinship == "PO") {
k1x <- f0x
k1y <- f0y
k2x <- f1ax
k2y <- f1ay
}
if (kinship == "FS" | kinship == "HS") {
k1x <- f1ax
k1y <- f1ay
k2x <- f1bx
k2y <- f1by
}
if (kinship == "AV" | kinship == "HAV") {
k1x <- f2ax
k1y <- f2ay
k2x <- f1bx
k2y <- f1by
}
if (kinship == "GG") {
k1x <- f0x
k1y <- f0y
k2x <- f2ax
k2y <- f2ay
}
if (kinship == "1C") {
k1x <- f2ax
k1y <- f2ay
k2x <- f2bx
k2y <- f2by
}
if (kinship == "GGG") {
k1x <- f0x
k1y <- f0y
k2x <- f3ax
k2y <- f3ay
}
if (kinship == "GAV") {
k1x <- f3ax
k1y <- f3ay
k2x <- f1bx
k2y <- f1by
}
if (kinship == "1C1") {
k1x <- f3ax
k1y <- f3ay
k2x <- f2bx
k2y <- f2by
}
if (kinship == "2C") {
k1x <- f3ax
k1y <- f3ay
k2x <- f3bx
k2y <- f3by
}
if (pinwheel == TRUE | scattered == TRUE) {
k1x <- k1x - k1x
k1y <- k1y - k1y
k2x <- k2x - k1x
k2y <- k2y - k1y
}
if (pinwheel == TRUE & nsims > 50) {
labls <- FALSE
}
kindist <- round(sqrt((k1x - k2x)^2 + (k1y - k2y)^2), digits = 1)
kinmidx <- (k1x + k2x) / 2
kinmidy <- (k1y + k2y) / 2
result <- tibble(
f0x = f0x, f0y = f0y, f1ax = f1ax, f1ay = f1ay,
f1bx = f1bx, f1by = f1by, f1cx = f1cx, f1cy = f1cy,
f2ax = f2ax, f2ay = f2ay, f2bx = f2bx, f2by = f2by,
f3ax = f3ax, f3ay = f3ay, f3bx = f3bx, f3by = f3by,
kindist = kindist, kinmidx = kinmidx, kinmidy = kinmidy,
k1x = k1x, k1y = k1y, k2x = k2x, k2y = k2y
)
arr <- arrow(length = unit(0.05, "inches"), type = "closed")
rectgrid <- tibble(x = c(0, 0, dims, dims), xend = c(0, dims, dims, 0), y = c(0, dims, dims, 0), yend = c(dims, dims, 0, 0))
ggp <- ggplot(result[1:nsims, ]) +
aes(x = .data$f0x, y = .data$f0y, xend = .data$f1ax, yend = .data$f1ay)
if (histogram == TRUE) {
ggp <- ggplot(result[1:nsims, ]) +
aes(x = .data$kindist)
if (freqpoly == FALSE) {
ggp <- ggp + geom_histogram(fill = "white", colour = "black", binwidth = binwidth)
}
if (freqpoly == TRUE) {
ggp <- ggp + geom_freqpoly(colour = "grey10", size = 0.75, binwidth = binwidth)
}
ggp <- ggp + theme_bw() + xlab("Separation (metres)") + ylab("Count") +
ggtitle("Kin Dispersal Histogram", subtitle = paste0("S=", posigma, " N=", nsims, " Category: ", kinship))
ggp <- ggp + theme(
axis.title = element_text(size = 16), plot.title = element_text(hjust = 0.5, size = 20),
legend.title = element_text(size = 14), legend.text = element_text(size = 12),
legend.box.background = element_rect(color = "black", linetype = 1, colour = "black")
)
return(ggp)
}
if (pinwheel == TRUE) {
ggp <- ggp + geom_segment(
mapping = aes(x = .data$k1x, y = .data$k1y, xend = .data$k2x, yend = .data$k2y), colour = "black",
linetype = 1, alpha = 0.7
)
if (labls != FALSE & lengthlabs != FALSE) {
ggp <- ggp + geom_label_repel(
mapping = aes(x = .data$k2x, y = .data$k2y, label = paste(.data$kindist, "m")), colour = "black",
size = 3, hjust = 0.5, vjust = 0.5, alpha = 1, box.padding = unit(0.01, "lines"),
label.padding = unit(0.1, "line"), fontface = "bold"
)
}
ggp <- ggp + coord_fixed() + theme_bw() +
xlab("Metres (x)") + ylab("Metres (y)") +
ggtitle(paste0("Kin Dispersal: sigma ", posigma, "m (pinwheel)"), subtitle = paste("Kin Category:", kinship))
ggp <- ggp + theme(
axis.title = element_text(size = 16), plot.title = element_text(hjust = 0.5, size = 20),
legend.title = element_text(size = 14), legend.text = element_text(size = 12),
legend.box.background = element_rect(color = "black", linetype = 1, colour = "black")
)
return(ggp)
}
if (scattered == TRUE) {
ggp <- ggp + geom_point(
mapping = aes(x = .data$k2x, y = .data$k2y), colour = "black",
alpha = 0.7
)
ggp <- ggp + coord_fixed() + theme_bw() +
xlab("Metres (x)") + ylab("Metres (y)") +
ggtitle(paste0("Kin Dispersal: sigma ", posigma, "m (scatter)"), subtitle = paste("Kin Category:", kinship))
ggp <- ggp + theme(
axis.title = element_text(size = 16), plot.title = element_text(hjust = 0.5, size = 20),
legend.title = element_text(size = 14), legend.text = element_text(size = 12),
legend.box.background = element_rect(color = "black", linetype = 1, colour = "black")
)
return(ggp)
}
if (show_area == TRUE) {
ggp <- ggp + geom_segment(data = rectgrid, mapping = aes(x = .data$x, y = .data$y, xend = .data$xend, yend = .data$yend), linetype = 1, alpha = 0.5)
}
if (steps == TRUE) {
if (shadows == TRUE) {
ggp <- ggp + geom_segment(colour = "black", alpha = 0.5, linetype = 3)
if (kinship %in% c("FS", "HS", "AV", "HAV", "1C", "1C1", "2C", "GAV")) {
ggp <- ggp + geom_segment(mapping = aes(xend = .data$f1bx, yend = .data$f1by), colour = "black", alpha = 0.5, linetype = 3)
}
if (kinship %in% c("AV", "GG", "HAV", "GGG", "1C", "1C1", "2C", "GAV")) {
ggp <- ggp + geom_segment(
mapping = aes(x = .data$f1ax, y = .data$f1ay, xend = .data$f2ax, yend = .data$f2ay),
alpha = 0.5, linetype = 3
)
}
if (kinship %in% c("1C", "1C1", "2C")) {
ggp <- ggp + geom_segment(
mapping = aes(x = .data$f1bx, y = .data$f1by, xend = .data$f2bx, yend = .data$f2by),
alpha = 0.5, linetype = 3
)
}
if (kinship %in% c("GGG", "1C1", "2C", "GAV")) {
ggp <- ggp + geom_segment(
mapping = aes(x = .data$f2ax, y = .data$f2ay, xend = .data$f3ax, yend = .data$f3ay),
alpha = 0.5, linetype = 3
)
}
if (kinship %in% c("2C")) {
ggp <- ggp + geom_segment(
mapping = aes(x = .data$f2bx, y = .data$f2by, xend = .data$f3bx, yend = .data$f3by),
linetype = 3, alpha = 0.5
)
}
}
if (moves == TRUE) {
ggp <- ggp + geom_curve(mapping = aes(colour = "black"), alpha = 0.7, linetype = 1, arrow = arr)
if (kinship %in% c("FS", "HS", "AV", "HAV", "1C", "1C1", "2C", "GAV")) {
ggp <- ggp + geom_curve(mapping = aes(xend = .data$f1bx, yend = .data$f1by, colour = "black"), alpha = 0.7, linetype = 1, arrow = arr)
}
if (kinship %in% c("AV", "GG", "HAV", "GGG", "1C", "1C1", "2C", "GAV")) {
ggp <- ggp + geom_curve(
mapping = aes(x = .data$f1ax, y = .data$f1ay, xend = .data$f2ax, yend = .data$f2ay, colour = "green4"),
alpha = 0.9, arrow = arr, linetype = 1
)
}
if (kinship %in% c("1C", "1C1", "2C")) {
ggp <- ggp + geom_curve(
mapping = aes(x = .data$f1bx, y = .data$f1by, xend = .data$f2bx, yend = .data$f2by, colour = "green4"),
alpha = 0.9, linetype = 1, arrow = arr
)
}
if (kinship %in% c("GGG", "1C1", "2C", "GAV")) {
ggp <- ggp + geom_curve(
mapping = aes(x = .data$f2ax, y = .data$f2ay, xend = .data$f3ax, yend = .data$f3ay, colour = "purple"),
arrow = arr, linetype = 1, alpha = 0.9
)
}
if (kinship %in% c("2C")) {
ggp <- ggp + geom_curve(
mapping = aes(x = .data$f2bx, y = .data$f2by, xend = .data$f3bx, yend = .data$f3by, colour = "purple"),
linetype = 1, alpha = 0.9, arrow = arr
)
}
}
ggp <- ggp + geom_point(alpha = 1, size = 2)
}
if (lengths == TRUE) {
if (centred == TRUE) {
kls <- 0.75
klt <- 5
}
if (centred == FALSE) {
kls <- 0.5
klt <- 2
}
ggp <- ggp + geom_segment(
mapping = aes(x = .data$k1x, y = .data$k1y, xend = .data$k2x, yend = .data$k2y), colour = "black", linetype = klt,
size = kls
)
}
if (labls == TRUE & steps == TRUE) {
if (centred != TRUE) {
ggp <- ggp + geom_label_repel(
label = "0",
size = 2, label.padding = unit(0.1, "lines"), box.padding = unit(0.01, "lines")
)
}
if (centred == TRUE) {
ggp <- ggp + geom_label_repel(
data = result[1, ], label = "0",
size = 2, label.padding = unit(0.1, "lines"), box.padding = unit(0.01, "lines")
)
}
if (kinship %in% c("PO", "FS", "HS", "AV", "GG", "HAV", "GGG", "1C", "1C1", "2C", "GAV")) {
ggp <- ggp + geom_label_repel(
mapping = aes(x = .data$f1ax, y = .data$f1ay), alpha = 0.7, colour = "black", label = "1",
size = 2, label.padding = unit(0.1, "lines"), box.padding = unit(0.01, "lines")
)
}
if (kinship %in% c("FS", "HS", "AV", "HAV", "1C", "1C1", "2C", "GAV")) {
ggp <- ggp + geom_label_repel(
mapping = aes(x = .data$f1bx, y = .data$f1by), alpha = 0.7, colour = "black", label = "1",
size = 2, label.padding = unit(0.1, "lines"), box.padding = unit(0.01, "lines")
)
}
if (kinship %in% c("AV", "GG", "HAV", "GGG", "1C", "1C1", "2C", "GAV")) {
ggp <- ggp + geom_label_repel(
mapping = aes(x = .data$f2ax, y = .data$f2ay), alpha = 0.7, colour = "green4", label = "2",
size = 2, label.padding = unit(0.1, "lines"), box.padding = unit(0.01, "lines")
)
}
if (kinship %in% c("1C", "1C1", "2C")) {
ggp <- ggp + geom_label_repel(
mapping = aes(x = .data$f2bx, y = .data$f2by), alpha = 0.7, colour = "green4", label = "2",
size = 2, label.padding = unit(0.1, "lines"), box.padding = unit(0.01, "lines")
)
}
if (kinship %in% c("GGG", "1C1", "2C", "GAV")) {
ggp <- ggp + geom_label_repel(
mapping = aes(x = .data$f3ax, y = .data$f3ay), alpha = 0.7, colour = "purple", label = "3",
size = 2, label.padding = unit(0.1, "lines"), box.padding = unit(0.1, "lines")
)
}
if (kinship %in% c("2C")) {
ggp <- ggp + geom_label_repel(
mapping = aes(x = .data$f3bx, y = .data$f3by), alpha = 0.7, colour = "purple", label = "3",
size = 2, label.padding = unit(0.1, "lines"), box.padding = unit(0.01, "lines")
)
}
}
if (lengths == TRUE & lengthlabs == TRUE) {
ggp <- ggp + geom_label_repel(
mapping = aes(x = .data$kinmidx, y = .data$kinmidy, label = paste(.data$kindist, "m")), colour = "black",
size = 3, hjust = 0.5, vjust = 0.5, alpha = 1, box.padding = unit(0.01, "lines"),
label.padding = unit(0.1, "line"), fontface = "bold"
)
}
ggp <- ggp + coord_fixed() + theme_bw() +
xlab("Metres (x)") + ylab("Metres (y)") + ggtitle(paste0("Kin Dispersal: sigma ", posigma, "m"), subtitle = paste("Kin Category:", kinship))
if (steps == TRUE & (labls == TRUE | moves == TRUE)) {
ggp <- ggp + scale_colour_identity(
labels = c("F0 -> F1", "F1 -> F2", "F2 -> F3"), breaks = c("black", "green4", "purple"),
guide = guide_legend(title = "Dispersal Generation", override.aes = list(size = 1))
)
}
ggp <- ggp + theme(
axis.title = element_text(size = 16), plot.title = element_text(hjust = 0.5, size = 20),
legend.title = element_text(size = 14), legend.text = element_text(size = 12),
legend.box.background = element_rect(color = "black", linetype = 1, colour = "black")
)
return(ggp)
}
simgraph_basic <- function(result, nsims = 10, labls = F, steps = T,
moves = T, shadows = F, show_area = T, kinship = "2C",
lengths = T, lengthlabs = T) {
return(simgraph_graph(result,
nsims = nsims, labls = labls, steps = steps, moves = moves, shadows = shadows,
show_area = show_area, kinship = kinship, lengths = lengths, lengthlabs = lengthlabs
))
}
simgraph_centred_graph <- function(result, nsims = 5,
labls = F, steps = T, moves = T, shadows = F,
show_area = T, kinship = "2C",
lengths = T, lengthlabs = F) {
return(simgraph_graph(result,
nsims = nsims, labls = labls, steps = steps, moves = moves, shadows = shadows,
show_area = show_area, kinship = kinship, lengths = lengths, lengthlabs = lengthlabs, centred = T
))
}
simgraph_pinwheel <- function(result, nsims = 25, labls = T, kinship = "2C") {
return(simgraph_graph(result, nsims = nsims, labls = labls, kinship = kinship, pinwheel = TRUE))
}
simgraph_scatter <- function(result, nsims = 500, kinship = "2C") {
return(simgraph_graph(result, nsims = nsims, kinship = kinship, scattered = TRUE))
}
simgraph_indv <- function(result, scalefactor = 4, scaled = T,
labls = F, steps = T, moves = T, shadows = F,
show_area = T, kinship = "2C",
lengths = T, lengthlabs = T) {
posigma <- result[1,]$posigma
newtitle <- paste0(kinship, " Dispersal")
newsubtitle <- paste0("Sigma: ", posigma, "m")
if (scaled == TRUE) {
return(simgraph_graph(result,
nsims = 1, labls = labls, steps = steps, moves = moves, shadows = shadows,
show_area = show_area, kinship = kinship, lengths = lengths, lengthlabs = lengthlabs, centred = T
) +
coord_fixed(
xlim = c(-scalefactor * posigma, scalefactor * posigma),
ylim = c(-scalefactor * posigma, scalefactor * posigma)
) + ggtitle(newtitle, newsubtitle))
}
return(simgraph_graph(result,
nsims = 1, labls = labls, steps = steps, moves = moves, shadows = shadows,
show_area = show_area, kinship = kinship, lengths = lengths, lengthlabs = lengthlabs, centred = T
) +
ggtitle(newtitle, newsubtitle))
}
simgraph_histogram <- function(result, nsims = 500, kinship = "2C", binwidth = posigma / 3) {
return(simgraph_graph(result, nsims = nsims, kinship = kinship, histogram = TRUE, binwidth = binwidth))
}
simgraph_freqpoly <- function(result, nsims = 5000, kinship = "2C", binwidth = posigma / 3) {
return(simgraph_graph(result, nsims = nsims, kinship = kinship, histogram = TRUE, binwidth = binwidth, freqpoly = TRUE))
} |
SSR_h <-
function (formula, data, coord, fixed_vars,kernels, H, Model, control=list(),Penalized)
{
model <- MGWRSAR(formula, data, coord, fixed_vars, kernels, H, Model,control)
if(Penalized) corpen=ifelse(Model %in% c('MGWRSAR_1_0_kv','MGWRSAR_1_kc_kv','MGWRSAR_1_kc_0'),sum(abs(model$Betav[,ncol(model$Betav)])>1),0) else corpen=0
SSR(model)*(1+corpen)
} |
rcopula.gauss <- function(n, Sigma){
d <- dim(Sigma)[1]
diagvals <- diag(Sigma)
if(!(all(diagvals == 1))) stop("\n'Sigma' should be correlation matrix.\n")
mnorm <- rmnorm(n, Sigma = Sigma, mu = 0)
matrix(pnorm(mnorm), ncol = d)
}
dcopula.gauss <- function(Udata, Sigma, log = FALSE){
d <- dim(Udata)[2]
Qdata <- apply(Udata, 2, qnorm)
out <- dmnorm(Qdata, rep(0, d), Sigma, log = TRUE) - apply(log(apply(Qdata, 2, dnorm)), 1, sum)
if(!(log)) out <- exp(out)
out
}
fit.gausscopula <- function(Udata, ...){
negloglik <- function(theta, data){
Sigma <- Pconstruct(theta)
-sum(dcopula.gauss(data, Sigma, log = TRUE))
}
theta <- Pdeconstruct(Spearman(Udata))
fit <- nlminb(theta, negloglik, data = Udata, ...)
theta <- fit$par
Sigma <- Pconstruct(theta)
ifelse(fit$convergence == 0, conv <- TRUE, conv <- FALSE)
list(P = Sigma, converged = conv, ll.max = -fit$objective, fit = fit)
} |
updateSliderInput <- function(session, inputId, label = NULL, value = NULL) {
message <- dropNulls(list(label=label, value=value))
session$sendInputMessage(inputId, message)
}
updateInputOptions <- function(session, inputId, label = NULL, choices = NULL,
selected = NULL, inline = FALSE,
type = 'checkbox') {
choices <- choicesWithNames(choices)
if (!is.null(selected))
selected <- validateSelected(selected, choices, inputId)
options <- if (length(choices))
format(tagList(
generateOptions(inputId, choices, selected, inline, type = type)
))
message <- dropNulls(list(label = label, options = options, value = selected))
session$sendInputMessage(inputId, message)
}
updateCheckboxGroupInput <- function(session, inputId, label = NULL,
choices = NULL, selected = NULL,
inline = FALSE) {
updateInputOptions(session, inputId, label, choices, selected, inline)
}
updateRadioButtons <- function(session, inputId, label = NULL, choices = NULL,
selected = NULL, inline = FALSE) {
if (is.null(selected) && !is.null(choices)) selected <- choices[[1]]
updateInputOptions(session, inputId, label, choices, selected, inline, type = 'radio')
} |
substractMatBfromA <- function(A, B) {
namesA <- rownames(A)
namesB <- rownames(B)
namesA2 <- colnames(A)
namesB2 <- colnames(B)
namesAinB <- namesA[namesA %in% namesB]
namesAinB2 <- namesA2[namesA2 %in% namesB2]
A[namesA %in% namesB, namesA2 %in% namesB2] <- A[namesA %in%
namesB, namesA2 %in% namesB2] - B[match(namesAinB, namesB),
match(namesAinB2, namesB2)]
return(A)
} |
dat <- 1:3
named_dat <- `names<-`(1:3, letters[1:3])
res <- c(1:3, (1:3) * 2L, (1:3) * 3L)
mat <- matrix(res, nrow = 3)
arr <- array(c(res, res * 2, res * 3), dim = rep(3, 3))
names <- list(letters[1:3], letters[1:3])
autonames <- list(format(1:3), format(1:3))
test_that("xmap_mat()", {
expect_equivalent(xmap_mat(list(dat, dat), `*`), mat)
expect_equal(dimnames(xmap_mat(list(dat, dat), `*`)), autonames)
expect_equal(dim(xmap_mat(list(dat, dat), `*`)), c(3, 3))
expect_equivalent(xmap_mat(list(named_dat, named_dat), `*`), mat)
expect_equal(dimnames(xmap_mat(list(named_dat, named_dat), `*`)), names)
expect_equal(dim(xmap_mat(list(named_dat, named_dat), `*`)), c(3, 3))
expect_equivalent(xmap_mat(list(dat, dat), `*`, .names = FALSE), mat)
expect_equal(dimnames(xmap_mat(list(dat, dat), `*`, .names = FALSE)), NULL)
expect_equal(dim(xmap_mat(list(dat, dat), `*`, .names = FALSE)), c(3, 3))
})
test_that("xmap_arr()", {
expect_equivalent(xmap_arr(list(dat, dat), `*`, .names = FALSE), mat)
expect_equal(dim(xmap_arr(list(dat, dat), `*`, .names = FALSE)), c(3, 3))
expect_equal(dimnames(xmap_arr(list(dat, dat), `*`, .names = FALSE)), NULL)
expect_equal(xmap_arr(list(dat, dat, dat), prod, .names = FALSE), arr)
expect_equal(
dim(xmap_arr(list(dat, dat, dat), prod, .names = FALSE)), c(3, 3, 3)
)
expect_equal(
dimnames(xmap_arr(list(dat, dat, dat), prod, .names = FALSE)), NULL
)
})
test_that("warn when xmap_mat() returns an array", {
expect_warning(xmap_mat(list(dat, dat, dat), prod, .names = FALSE))
expect_equal(
suppressWarnings(xmap_mat(list(dat, dat, dat), prod, .names = FALSE)), arr
)
}) |
eapEst <-
function( resp,
params,
range = c(-6, 6),
mod = c("brm", "grm"),
ddist = dnorm, quad = 33, ... )
{
params <- rbind(params)
resp <- { if( dim(params)[1] > 1 ) rbind(resp)
else cbind(resp) }
class(params) <- c(mod, "matrix")
if( mode(params) != "numeric" )
stop( "params need to be numeric" )
if( !is.null(resp) & mode(resp) != "numeric" )
stop( "resp needs to be numeric" )
if( !is.null(resp) & ( dim(resp)[2] != dim(params)[1] ) )
stop( "number of params does not match the length of resp" )
if( is.null(range) )
range <- c(-6, 6)
l <- range[1]; u <- range[2]
tmp.x <- seq(l, u, by = .01)
tmp.y <- ddist(x = tmp.x, ... )
l <- min( tmp.x[signif(tmp.y) != 0 & !is.na(tmp.y)] )
u <- max( tmp.x[signif(tmp.y) != 0 & !is.na(tmp.y)] )
est <- NULL
sem <- NULL
LikFun <- function( ... ) exp( get(paste("logLik.", mod, sep = "") )( ... ) )
for( i in 1:dim(resp)[1] ){
resp_i <- resp[i, ]
eap.den <- function( theta ) LikFun(u = resp_i, theta = theta, params = params) * ddist(x = theta, ... )
eap.num <- function( theta ) theta * LikFun(u = resp_i, theta = theta, params = params) * ddist(x = theta, ... )
sem.num <- function( theta ) theta^2 * LikFun(u = resp_i, theta = theta, params = params) * ddist(x = theta, ... )
integrate.eap <- function(f) integrate.s(f, min = l, max = u, quad = quad, method = "S2")
est[i] <- ( integrate.eap(eap.num) / ( const <- integrate.eap(eap.den) ) )
sem[i] <- ( integrate.eap(sem.num) / const ) - est[i]^2
}
est <- round(est, digits = 4)
sem <- sqrt(sem)
info <- get(paste("FI.", mod, sep = ""))( params = params,
theta = est,
type = "observed",
resp = resp )$test
return( list( theta = est, info = info, sem = sem ) )
} |
simRes <- function(Q, target, capacity, surface_area, max_depth, evap,
double_cycle = FALSE, plot = TRUE, S_initial = 1, policy) {
frq <- frequency(Q)
if(length(target)==1){
target <- rep(target, length(Q))
}
if(length(target) != length(Q))
stop("target must be numerical constant or time series of length Q")
target <- ts(target, start = start(Q), frequency = frequency(Q))
if (double_cycle) {
Q <- ts(c(Q, Q), start = start(Q), frequency = frq)
target <- c(target, target)
}
if (missing(evap)) {
evap <- rep(0, length(Q))
}
if(length(evap) == 1) {
evap <- rep(evap, length(Q))
}
if (length(evap) != length(Q)){
stop("Evaporation must be either a vector (or time series) length Q, or a single numeric constant")
}
if (missing(surface_area)) {
surface_area <- 0
}
if (missing(max_depth)){
c <- sqrt(2) / 3 * (surface_area * 10 ^ 6) ^ (3/2) / (capacity * 10 ^ 6)
GetLevel <- function(c, V){
y <- (6 * V / (c ^ 2)) ^ (1 / 3)
return(y)
}
GetArea <- function(c, V){
Ay <- (((3 * c * V) / (sqrt(2))) ^ (2 / 3))
return(Ay)
}
} else {
c <- 2 * capacity / (max_depth * surface_area)
GetLevel <- function(c, V){
y <- max_depth * (V / (capacity * 10 ^ 6)) ^ (c / 2)
return(y)
}
GetArea <- function(c, V){
Ay <- ((2 * (capacity * 10 ^ 6)) / (c * max_depth * (V / (capacity * 10 ^ 6)) ^ (c / 2))) * ((V / (capacity * 10 ^ 6)) ^ (c / 2)) ^ (2 / c)
Ay[which(is.nan(Ay) == TRUE)] <- 0
return(Ay)
}
}
GetEvap <- function(s, q, r, ev){
e <- GetArea(c, V = s * 10 ^ 6) * ev / 10 ^ 6
n <- 0
repeat{
n <- n + 1
s_plus_1 <- max(min(s + q - r - e, capacity), 0)
e_x <- GetArea(c, V = ((s + s_plus_1) / 2) * 10 ^ 6) * ev / 10 ^ 6
if (abs(e_x - e) < 0.001 || n > 20){
break
} else {
e <- e_x
}
}
return(e)
}
S <- vector("numeric", length = length(Q) + 1); S[1] <- capacity * S_initial
R <- vector("numeric", length = length(Q))
E <- vector("numeric", length(Q))
y <- vector("numeric", length(Q))
Spill <- vector("numeric", length(Q))
if (missing(policy)){
for (t in 1:length(Q)) {
E[t] <- GetEvap(s = S[t], q = Q[t], r = target[t], ev = evap[t])
y[t] <- GetLevel(c, S[t] * 10 ^ 6)
if ( (S[t] - target[t] + Q[t] - E[t]) > capacity) {
S[t + 1] <- capacity
Spill[t] <- S[t] - target[t] + Q[t] - capacity - E[t]
R[t] <- target[t]
} else {
if (S[t] - target[t] + Q[t] - E[t] < 0) {
S[t + 1] <- 0
R[t] <- max(0, S[t] + Q[t] - E[t])
} else {
S[t + 1] <- S[t] + Q[t] - target[t] - E[t]
R[t] <- target[t]
}
}
}
}
if (!missing(policy)){
if (is.list(policy) == FALSE) stop("The policy must be the full output returned by the sdp_supply function")
Q_month_mat <- matrix(Q, byrow = TRUE, ncol = frq)
if (length(dim(policy$release_policy)) == 2){
S_disc <- length(policy$release_policy[,1]) - 1
} else {
S_disc <- length(policy$release_policy[,1,1]) - 1
}
S_states <- seq(from = 0, to = capacity, by = capacity / S_disc)
Q.probs <- diff(policy$flow_disc)
Q_class_med <- apply(Q_month_mat, 2, quantile, type = 8,
probs = policy$flow_disc[-1] - (Q.probs / 2))
for (yr in 1:nrow(Q_month_mat)) {
for (month in 1:frq) {
t_index <- (frq * (yr - 1)) + month
S_state <- which.min(abs(S_states - S[t_index]))
Qx <- Q_month_mat[yr, month]
if (length(dim(policy$release_policy)) == 2){
Rx <- target[t_index] * policy$release_policy[S_state, month]
} else {
Q_class <- which.min(abs(as.vector(Q_class_med[,month] - Qx)))
Rx <- target[t_index] * policy$release_policy[S_state, Q_class, month]
}
E[t_index] <- GetEvap(s = S[t_index], q = Qx, r = R, ev = evap[t_index])
y[t_index] <- GetLevel(c, S[t_index] * 10 ^ 6)
if ( (S[t_index] - Rx + Qx - E[t_index]) > capacity) {
S[t_index + 1] <- capacity
R[t_index] <- Rx
Spill[t_index] <- S[t_index] - Rx + Qx - capacity - E[t_index]
}else{
if ( (S[t_index] - Rx + Qx - E[t_index]) < 0) {
S[t_index + 1] <- 0
R[t_index] <- max(0, S[t_index] + Qx - E[t_index])
}else{
S[t_index + 1] <- S[t_index] - Rx + Qx - E[t_index]
R[t_index] <- Rx
}
}
}
}
}
S <- ts(S[1:length(S) - 1], start = start(Q), frequency = frequency(Q))
R <- ts(R, start = start(Q), frequency = frequency(Q))
E <- ts(E, start = start(Q), frequency = frequency(Q))
y <- ts(y, start = start(Q), frequency = frequency(Q))
Spill <- ts(Spill, start = start(Q), frequency = frequency(Q))
results <- list(S, R, E, y, Spill)
names(results) <- c("storage", "releases", "evaporation", "water_level", "spill")
if (plot) {
plot(R, ylab = "Release", ylim = c(0, max(target))); lines(target, lty = 3)
plot(S, ylab = "Storage", ylim = c(0, capacity))
plot(Spill, ylab = "Spill")
}
return(results)
} |
visr <- function(x, ...){
UseMethod("visr", x)
}
visr.default <- function(x, ...){
if (length(class(x)) > 1) {
stop("Objects of type `",
paste0(class(x), collapse = "` / `"),
"` not supported by visr.")
} else if (length(class(x)) == 1) {
stop(paste0("Objects of type `", class(x), "` not supported by visr."))
}
}
visr.survfit <- function(
x = NULL
,x_label = NULL
,y_label = NULL
,x_units = NULL
,x_ticks = NULL
,y_ticks = NULL
,fun = "surv"
,legend_position = "right"
,...
){
if (!(is.null(x_label) | is.character(x_label) | is.expression(x_label))) {
stop("Invalid `x_label` argument, must be either `character` or `expression`.")
}
if (!(is.null(y_label) | is.character(y_label) | is.expression(y_label))) {
stop("Invalid `y_label` argument, must be either `character` or `expression`.")
}
if (!(is.null(x_units) | is.character(x_units))) {
stop("Invalid `x_units` argument, must be `character`.")
}
if (!(is.null(x_ticks) | is.numeric(x_ticks))) {
stop("Invalid `x_ticks` argument, must be `numeric`.")
}
if (!(is.null(y_ticks) | is.numeric(y_ticks))) {
stop("Invalid `y_ticks` argument, must be `numeric`.")
}
if (is.character(legend_position) &&
!legend_position %in% c("top", "bottom", "right", "left", "none")) {
stop(
"Invalid legend position given. Must either be [\"top\", \"bottom\", \"right\", \"left\", \"none\"] or a vector with two numbers indicating the position relative to the axis. For example c(0.5, 0.5) to place the legend in the center of the plot."
)
} else if (is.numeric(legend_position) &&
length(legend_position) != 2) {
stop(
"Invalid legend position given. Must either be [\"top\", \"bottom\", \"right\", \"left\", \"none\"] or a vector with two numbers indicating the position relative to the axis. For example c(0.5, 0.5) to place the legend in the center of the plot."
)
}
valid_funs <- c("surv", "log", "event", "cloglog", "pct", "logpct", "cumhaz")
if (is.character(fun)) {
if (!(fun %in% valid_funs)) {
stop(
"Unrecognized `fun` argument, must be one of [\"surv\", \"log\", \"event\", \"cloglog\", \"pct\", \"logpct\", \"cumhaz\"] or a user-defined function."
)
}
}
if (is.null(y_label) & is.character(fun)){
y_label <- base::switch(
fun,
surv = "survival probability",
log = "log(survival probability)",
event = "failure probability",
cloglog = "log(-log(survival probability))",
pct = "percentage survival",
logpct = "log(percentage survival)",
cumhaz = "cumulative hazard",
stop("Unrecognized fun argument")
)
} else if (is.null(y_label) & is.function(fun)) {
stop("No Y label defined. No default label is available when `fun` is a function.")
}
if (is.character(fun)){
.transfun <- base::switch(
fun,
surv = function(y) y,
log = function(y) log(y),
event = function(y) 1 - y,
cloglog = function(y) log(-log(y)),
pct = function(y) y * 100,
logpct = function(y) log(y *100),
cumhaz = function(y) - log(y)
)
} else if (is.function(fun)) {
.transfun <- function(y) fun(y)
} else {
stop("Error in visr: fun should be a character or a user-defined function.")
}
correctme <- NULL
tidy_object <- tidyme(x)
if ("surv" %in% colnames(tidy_object)) {
tidy_object[["est"]] <- .transfun(tidy_object[["surv"]])
correctme <- c(correctme, "est")
}
if (base::all(c("upper", "lower") %in% colnames(tidy_object))) {
tidy_object[["est.upper"]] <- .transfun(tidy_object[["upper"]])
tidy_object[["est.lower"]] <- .transfun(tidy_object[["lower"]])
correctme <- c(correctme, "est.lower", "est.upper")
}
if (nrow(tidy_object[tidy_object$est == "-Inf",]) > 0) {
warning("NAs introduced by y-axis transformation.")
}
tidy_object[ , correctme] <- sapply(tidy_object[, correctme],
FUN = function(x) {
x[which(x == -Inf)] <- min(x[which(x != -Inf)], na.rm = TRUE)
return(x)
}
)
ymin = min(sapply(tidy_object[, correctme], function(x) min(x[which(x != -Inf)], na.rm = TRUE)), na.rm = TRUE)
ymax = max(sapply(tidy_object[, correctme], function(x) max(x[which(x != -Inf)], na.rm = TRUE)), na.rm = TRUE)
if (is.null(x_label)){
if ("PARAM" %in% names(x)) x_label = x[["PARAM"]]
if (! "PARAM" %in% names(x)) x_label = "time"
if (!is.null(x_units)) x_label = paste0(x_label, " (", x_units, ")")
}
if (is.null(x_ticks)) x_ticks = pretty(x$time, 10)
if (is.null(y_ticks) & is.character(fun)){
y_ticks <- base::switch(
fun,
surv = pretty(c(0, 1), 5),
log = pretty(round(c(ymin, ymax), 0), 5),
event = pretty(c(0, 1), 5),
cloglog = pretty(round(c(ymin, ymax), 0), 5),
pct = pretty(c(0, 100), 5),
logpct = pretty(c(0, 5), 5),
cumhaz = pretty(round(c(ymin, ymax), 0), 5),
stop("Unrecognized fun argument")
)
} else if (is.null(y_ticks) & is.function(fun)) {
y_ticks = pretty(round(c(ymin, ymax), 0), 5)
}
yscaleFUN <- function(x) sprintf("%.2f", x)
gg <- ggplot2::ggplot(tidy_object, ggplot2::aes(x = time, group = strata)) +
ggplot2::geom_step(ggplot2::aes(y = est, col = strata)) +
ggplot2::scale_x_continuous(name = x_label,
breaks = x_ticks,
limits = c(min(x_ticks), max(x_ticks))) +
ggplot2::scale_y_continuous(name = y_label,
breaks = y_ticks,
labels = yscaleFUN,
limits = c(min(y_ticks), max(y_ticks))) +
ggplot2::theme(legend.position = legend_position) +
NULL
class(gg) <- append(class(gg), "ggsurvfit")
return(gg)
}
visr.attrition <- function(x,
description_column_name = "Criteria",
value_column_name = "Remaining N",
complement_column_name="",
box_width = 50,
font_size = 12,
fill="white",
border="black",
...){
if (!description_column_name %in% names(x)) {
stop(paste0("Column \"", description_column_name, "\" cannot be found in the input data. ",
"Please provide the column name as string in the input ",
"data containing the inclusion descriptions."))
}
if (!value_column_name %in% names(x)) {
stop(paste0("Column \"", value_column_name, "\" cannot be found in the input data. ",
"Please provide the column name as string in the input data containing",
"the sample size after applying inclusion criteria."))
}
if (complement_column_name != "" & !complement_column_name %in% names(x)) {
stop(paste0("Column \"", complement_column_name, "\" cannot be found in the input data. ",
"Please provide a valid column name as string in the input data containing",
"complement description or omit this argument for default labels."))
}
if (!is.numeric(box_width)) {
warning("An invalid input was given for `box_width`, must be `numeric` value. Setting it to 50.")
box_width <- 50
}
if (!is.numeric(font_size)) {
warning("An invalid input was given for `font_size`, must be `numeric` value. Setting it to 12.")
font_size <- 12
}
if (!is.character(fill)) {
warning("An invalid input was given for `fill`, must be `character` string. Setting it to \"white\".")
fill <- "white"
}
if (!is.character(border)) {
warning("An invalid input was given for `border`, must be `character` string. Setting it to \"black\".")
border <- "black"
}
label <- complement_label <- NULL
y <- down_ystart <- down_yend <- side_xstart <- side_xend <- side_y <- NULL
cx <- cy <- NULL
field_height <- 100/nrow(x)
box_height <- 0.75 * field_height
plotting_data <- x %>%
.get_labels(description_column_name, value_column_name, complement_column_name, wrap_width = box_width) %>%
.get_labelsizes(label, complement_label) %>%
.get_coordinates(box_width, box_height, field_height)
gg <- plotting_data %>%
ggplot2::ggplot() +
ggplot2::geom_tile(data=plotting_data, ggplot2::aes(x = x,
y = y,
width=box_width,
height=box_height),
color=border, fill=fill) +
ggplot2::geom_text(data=plotting_data, ggplot2::aes(x = x,
y = y,
label = label),
size = font_size / ggplot2::.pt) +
ggplot2::geom_segment(data=plotting_data, ggplot2::aes(x=x,
xend=x,
y=down_ystart,
yend=down_yend),
arrow = ggplot2::arrow(length = 0.5 * ggplot2::unit(font_size, "pt")),
size = .2,
na.rm=TRUE) +
ggplot2::geom_segment(data=plotting_data, ggplot2::aes(x=side_xstart,
xend=side_xend,
y=side_y,
yend=side_y),
arrow = ggplot2::arrow(length = 0.5 * ggplot2::unit(font_size, "pt")),
size = .2,
na.rm=TRUE) +
ggplot2::geom_tile(data=plotting_data, ggplot2::aes(x = cx,
y = cy,
width=box_width,
height=box_height),
color=border, fill=fill,
na.rm=TRUE) +
ggplot2::geom_text(data=plotting_data, ggplot2::aes(x = cx,
y = cy,
label = complement_label),
size = font_size / ggplot2::.pt,
na.rm=TRUE) +
ggplot2::theme_void() +
ggplot2::theme(legend.position = "none")
return(gg)
} |
context("Get precision of number")
test_that("get_precision() works", {
a <- c("1512313.", "13.423", "13.42345", "13.1300014134100")
expect_equal(get_precision(a), c(0, 3, 5, 11))
expect_equal(get_precision(as.numeric(a)), c(0, 3, 5, 11))
b <- c("1512313.", "13.423", NA, NA, "13.42345", NA, "13.1300014134100")
expect_equal(get_precision(b), c(0, 3, NA, NA, 5, NA, 11))
expect_equal(get_precision(as.numeric(b)), c(0, 3, NA, NA, 5, NA, 11))
}) |
labkey.getSchemas <- function(baseUrl=NULL, folderPath)
{
baseUrl=labkey.getBaseUrl(baseUrl)
if (missing(folderPath)) stop (paste("A value must be specified for folderPath."))
folderPath <- encodeFolderPath(folderPath)
myurl <- paste(baseUrl,"query",folderPath,"getSchemas.view?apiVersion=9.3", sep="")
mydata <- labkey.get(myurl)
decode <- fromJSON(mydata, simplifyVector=FALSE, simplifyDataFrame=FALSE)
cn<-names(decode)
newdata<- as.data.frame(cn)
names(newdata)[1]<-"schemaName"
return(newdata)
} |
context('circular dependencies')
test_that('cyclic dependencies load in finite time', {
box::use(mod/cyclic_a)
expect_true(TRUE)
})
test_that('cyclic import fully loads dependencies', {
box::use(a = mod/cyclic_a)
box::use(b = mod/cyclic_b)
expect_equal(a$name, 'a')
expect_equal(b$name, 'b')
expect_equal(a$b_name(), 'b')
expect_equal(b$a_name(), 'a')
expect_equal(a$b$name, 'b')
expect_equal(b$a$name, 'a')
expect_equal(a$b$a$b_name(), 'b')
expect_equal(a$b$a$name, 'a')
expect_equal(b$a$b$a_name(), 'a')
expect_equal(b$a$b$name, 'b')
}) |
E.PPS<-function(y,pk){
y<-cbind(1,y)
y<-as.data.frame(y)
names(y)[1] <- "N"
Total<-matrix(NA,nrow=4,ncol=dim(y)[2])
rownames(Total)=c("Estimation", "Standard Error","CVE","DEFF")
colnames(Total)<-names(y)
m<-length(pk)
for(k in 1:dim(y)[2]){
ty<-sum(y[,k]/pk)/m
Vty<-(1/m)*(1/(m-1))*sum((y[,k]/pk-ty)^2)
CVe<-100*sqrt(Vty)/ty
N<-(1/m)*sum(1/pk)
VMAS<-(N^2)*(1-(m/N))*var(y[,k])/(m)
DEFF<-Vty/VMAS
Total[,k]<-c(ty,sqrt(Vty),CVe,DEFF)
}
return(Total)
} |
get_provinces <- function(geo_only = TRUE) {
base_url <- "https://api.covid19tracker.ca/provinces"
if (geo_only) {
api_params <- "?geo_only=true"
} else {
api_params <- ""
}
url <- paste0(base_url, api_params)
content_parsed <- get_content_parsed(url)
dplyr::bind_rows(content_parsed) %>%
dplyr::mutate(
geographic = .data$geographic == 1,
updated_at = as.POSIXct(.data$updated_at)
)
} |
library(scclust)
context("nng_clustering")
source("config.R", local = TRUE)
source("../replica/replica_findseed.R", local = TRUE)
source("../replica/replica_make_nng.R", local = TRUE)
source("../replica/replica_nng.R", local = TRUE)
source("utils_nng.R", local = TRUE)
test_that("`nng_clustering` returns correct output", {
skip_if_not(!compiled_with_stable_nng, "Only run this when scclust is *not* compiled with the -DSCC_STABLE_NNG flag.")
skip_if_not(!compiled_with_stable_findseed, "Only run this when scclust is *not* compiled with the -DSCC_STABLE_FINDSEED flag.")
test_nng_against_replica(test_distances1,
2L,
"lexical",
"ignore",
NULL,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"ignore",
NULL,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
10L,
"lexical",
"ignore",
NULL,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"inwards_order",
"ignore",
NULL,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
2L,
"inwards_updating",
"ignore",
NULL,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
2L,
"inwards_updating",
"ignore",
NULL,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"exclusion_order",
"ignore",
NULL,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
2L,
"exclusion_updating",
"ignore",
NULL,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"inwards_order",
"ignore",
NULL,
which(primary_data_points),
"ignore",
NULL)
test_nng_against_replica(test_distances1,
2L,
"inwards_updating",
"ignore",
NULL,
which(primary_data_points),
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"inwards_order",
"ignore",
NULL,
primary_data_points,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
2L,
"inwards_updating",
"ignore",
NULL,
primary_data_points,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
2L,
"inwards_updating",
"ignore",
NULL,
primary_data_points,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"exclusion_order",
"ignore",
NULL,
primary_data_points,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
2L,
"exclusion_updating",
"ignore",
NULL,
primary_data_points,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
2L,
"lexical",
"any_neighbor",
NULL,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"closest_assigned",
NULL,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"closest_seed",
NULL,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"estimated_radius_closest_seed",
NULL,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"ignore",
test_radius,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
2L,
"lexical",
"any_neighbor",
test_radius,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"closest_assigned",
test_radius,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"closest_seed",
test_radius,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"estimated_radius_closest_seed",
test_radius,
NULL,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"ignore",
NULL,
primary_data_points,
"ignore",
NULL)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"ignore",
NULL,
primary_data_points,
"closest_assigned",
NULL)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"ignore",
NULL,
primary_data_points,
"closest_seed",
NULL)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"ignore",
NULL,
primary_data_points,
"estimated_radius_closest_seed",
NULL)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"ignore",
NULL,
primary_data_points,
"ignore",
test_radius)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"ignore",
NULL,
primary_data_points,
"closest_assigned",
test_radius)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"ignore",
NULL,
primary_data_points,
"closest_seed",
test_radius)
test_nng_against_replica(test_distances1,
3L,
"lexical",
"ignore",
NULL,
primary_data_points,
"estimated_radius_closest_seed",
test_radius)
})
test_that("`nng_clustering` returns correct output (combinations)", {
skip_on_cran()
skip_if_not(run_slow_tests)
skip_if_not(!compiled_with_stable_nng, "Only run this when scclust is *not* compiled with the -DSCC_STABLE_NNG flag.")
skip_if_not(!compiled_with_stable_findseed, "Only run this when scclust is *not* compiled with the -DSCC_STABLE_FINDSEED flag.")
for (seed_method in c("lexical",
"inwards_order",
"inwards_updating",
"exclusion_order",
"exclusion_updating")) {
for (unassigned_method in c("ignore",
"any_neighbor",
"closest_assigned",
"closest_seed",
"estimated_radius_closest_seed")) {
sc_to_test <- c(2L, 3L, 6L)
if (seed_method %in% c("inwards_updating",
"exclusion_updating")) {
sc_to_test <- 2L
}
for (size_constraint in sc_to_test) {
radius_to_use <- c(0, 0.1, 0.2)
if (size_constraint == 6L) {
radius_to_use <- c(0, 0.3)
}
for (radius in radius_to_use) {
for (secondary_unassigned_method in c("ignore",
"ignore_withmain",
"closest_assigned",
"closest_seed",
"estimated_radius_closest_seed")) {
for (secondary_radius in radius_to_use) {
use_primary_data_points <- NULL
if (secondary_unassigned_method != "ignore") use_primary_data_points <- primary_data_points
use_secondary_unassigned_method <- secondary_unassigned_method
if (use_secondary_unassigned_method == "ignore_withmain") use_secondary_unassigned_method <- "ignore"
use_radius <- radius
if (use_radius == 0) use_radius <- NULL
use_secondary_radius <- secondary_radius
if (use_secondary_radius == 0) use_secondary_radius <- NULL
test_nng_against_replica(test_distances1,
size_constraint,
seed_method,
unassigned_method,
use_radius,
use_primary_data_points,
use_secondary_unassigned_method,
use_secondary_radius)
}
}
}
}
}
}
}) |
magaxis =
function(side=1:2, majorn=5, minorn='auto', tcl=0.5, ratio=0.5, labels=TRUE, unlog='auto',
mgp=c(2,0.5,0), mtline=2, xlab=NULL, ylab=NULL, crunch=TRUE, logpretty=TRUE,
prettybase=10, powbase=10, hersh=FALSE, family='sans', frame.plot=FALSE,
usepar=FALSE, grid=FALSE, grid.col='grey', grid.lty=1, grid.lwd=1, axis.lwd=1,
ticks.lwd=axis.lwd, axis.col='black', do.tick=TRUE, ...){
dots=list(...)
dotskeepaxis=c('cex.axis', 'col.axis', 'font.axis', 'xaxp', 'yaxp', 'tck', 'las', 'fg', 'xpd', 'xaxt', 'yaxt', 'col.ticks')
dotskeepmtext=c('cex.lab', 'col.lab', 'font.lab')
if(length(dots)>0){
dotsaxis=dots[names(dots) %in% dotskeepaxis]
dotsmtext=dots[names(dots) %in% dotskeepmtext]
}else{
dotsaxis={}
dotsmtext={}
}
if(length(mtline)==1){mtline=rep(mtline,2)}
majornlist=majorn
minornlist=minorn
labelslist=labels
unloglist=unlog
crunchlist=crunch
logprettylist=logpretty
prettybaselist=prettybase
powbaselist=powbase
gridlist=grid
if(length(majorn)==1 & length(side)>1){majornlist=rep(majorn,length(side))}
if(length(minorn)==1 & length(side)>1){minornlist=rep(minorn,length(side))}
if(length(labels)==1 & length(side)>1){labelslist=rep(labels,length(side))}
if(length(unlog)==1 & length(side)>1 & (unlog[1]==T | unlog[1]==F | unlog[1]=='auto')){unloglist=rep(unlog,length(side))}
if(length(crunch)==1 & length(side)>1){crunchlist=rep(crunch,length(side))}
if(length(logpretty)==1 & length(side)>1){logprettylist=rep(logpretty,length(side))}
if(length(prettybase)==1 & length(side)>1){prettybaselist=rep(prettybase,length(side))}
if(length(powbase)==1 & length(side)>1){powbaselist=rep(powbase,length(side))}
if(length(grid)==1 & length(side)>1){gridlist=rep(grid,length(side))}
if(!all(is.logical(unlog)) & unlog[1]!='auto'){
unlogsplit = strsplit(unlog[1],'')[[1]]
unloglist=rep(FALSE,length(side))
if(unlog[1]==''){unloglist=rep(FALSE,length(side))}
if('x' %in% unlogsplit){unloglist[side %in% c(1,3)]=TRUE}
if('y' %in% unlogsplit){unloglist[side %in% c(2,4)]=TRUE}
}
if(length(majornlist) != length(side)){stop('Length of majorn vector mismatches number of axes!')}
if(length(minornlist) != length(side)){stop('Length of minorn vector mismatches number of axes!')}
if(length(labelslist) != length(side)){stop('Length of labels vector mismatches number of axes!')}
if(length(unloglist) != length(side)){stop('Length of unlog vector mismatches number of axes!')}
if(length(crunchlist) != length(side)){stop('Length of crunch vector mismatches number of axes!')}
if(length(logprettylist) != length(side)){stop('Length of logpretty vector mismatches number of axes!')}
if(length(prettybaselist) != length(side)){stop('Length of prettybase vector mismatches number of axes!')}
if(length(powbaselist) != length(side)){stop('Length of powbase vector mismatches number of axes!')}
if(length(gridlist) != length(side)){stop('Length of grid vector mismatches number of axes!')}
currentfamily=par('family')
if(hersh & family=='serif'){par(family='HersheySerif')}
if(hersh & family=='sans'){par(family='HersheySans')}
if(hersh==F & family=='serif'){par(family='serif')}
if(hersh==F & family=='sans'){par(family='sans')}
if(missing(axis.lwd)){axis.lwd=par()$lwd}
if(missing(ticks.lwd)){ticks.lwd=par()$lwd}
if(usepar){
if(missing(tcl)){tcl=par()$tcl}
if(missing(mgp)){mgp=par()$mgp}
}
for(i in 1:length(side)){
currentside=side[i]
majorn=majornlist[i]
minorn=minornlist[i]
labels=labelslist[i]
unlog=unloglist[i]
crunch=crunchlist[i]
logpretty=logprettylist[i]
prettybase=prettybaselist[i]
powbase=powbaselist[i]
grid=gridlist[i]
lims=par("usr")
if(currentside %in% c(1,3)){
lims=lims[1:2];if(par('xlog')){logged=T}else{logged=F}
}else{
lims=lims[3:4];if(par('ylog')){logged=T}else{logged=F}
}
lims=sort(lims)
if(unlog=='auto'){if(logged){unlog=T}else{unlog=F}}
if((logged | unlog) & powbase==10){usemultloc=(10^lims[2])/(10^lims[1])<50}else{usemultloc=F}
if(unlog){
sci.tick=maglab(10^lims,n=majorn,log=T,exptext=T,crunch=crunch,logpretty=logpretty,usemultloc=usemultloc,prettybase=prettybase, powbase=powbase, hersh=hersh)
major.ticks = log(sci.tick$tickat,powbase)
uselabels = sci.tick$exp
labloc = log(sci.tick$labat,powbase)
if(usemultloc==F){
if(minorn=='auto'){
splitmin=(powbase^major.ticks[2])/(powbase^major.ticks[1])
}else{
splitmin=minorn+1
}
if(splitmin>10){
minors = seq(major.ticks[1], major.ticks[2])-major.ticks[1]
}else{
minors = log(seq(powbase^major.ticks[1],powbase^major.ticks[2],len=splitmin),powbase)-major.ticks[1]
}
}
}
if(logged & unlog==F){
sci.tick=maglab(10^lims, n=majorn, log=T, exptext=F, crunch=crunch, logpretty=logpretty,usemultloc=usemultloc, prettybase=prettybase, powbase=powbase, hersh=hersh)
major.ticks = log(sci.tick$tickat,powbase)
uselabels = sci.tick$exp
labloc = log(sci.tick$labat,powbase)
if(usemultloc==F){
if(minorn=='auto'){
splitmin=(powbase^major.ticks[2])/(powbase^major.ticks[1])
}else{
splitmin=minorn+1
}
if(splitmin>10){
minors = seq(major.ticks[1], major.ticks[2])-major.ticks[1]
}else{
minors = log(seq(powbase^major.ticks[1],powbase^major.ticks[2],len=splitmin),powbase)-major.ticks[1]
}
}
}
if(logged==F & unlog==F){
sci.tick=maglab(lims,n=majorn,log=F,exptext=F,prettybase=prettybase, hersh=hersh)
major.ticks = sci.tick$tickat
uselabels = sci.tick$exp
labloc = sci.tick$labat
if(minorn=='auto'){splitmin=length(pretty(major.ticks[1:2]))}else{splitmin=minorn+1}
minors = seq(major.ticks[1],major.ticks[2],len=splitmin)-major.ticks[1]
}
if(grid){
if(currentside==1){
if(logged){
abline(v=powbase^labloc, col=grid.col, lty=grid.lty, lwd=grid.lty)
}else{
abline(v=labloc, col=grid.col, lty=grid.lty, lwd=grid.lty)
}
}
if(currentside==2){
if(logged){
abline(h=powbase^labloc, col=grid.col, lty=grid.lty, lwd=grid.lty)
}else{
abline(h=labloc, col=grid.col, lty=grid.lty, lwd=grid.lty)
}
}
}
if(logged){
do.call("axis", c(list(side=currentside,at=powbase^major.ticks,tcl=tcl,labels=FALSE,tick=do.tick,mgp=mgp,lwd=axis.lwd,lwd.ticks=ticks.lwd,col=axis.col),dotsaxis))
}else{
do.call("axis", c(list(side=currentside,at=major.ticks,tcl=tcl,labels=FALSE,tick=do.tick,mgp=mgp,lwd=axis.lwd,lwd.ticks=ticks.lwd,col=axis.col),dotsaxis))
}
if(labels){
if(logged){
do.call("axis", c(list(side=currentside,at=powbase^labloc,tick=F,labels=uselabels,mgp=mgp,lwd=axis.lwd,lwd.ticks=ticks.lwd,col=axis.col),dotsaxis))
}else{
do.call("axis", c(list(side=currentside,at=labloc,tick=F,labels=uselabels,mgp=mgp,lwd=axis.lwd,lwd.ticks=ticks.lwd,col=axis.col),dotsaxis))
}
}
if(usemultloc==F & minorn>1){
minors = minors[-c(1,length(minors))]
minor.ticks = c(outer(minors, major.ticks, `+`))
if(logged){
do.call("axis", c(list(side=currentside,at=powbase^minor.ticks,tcl=tcl*ratio,labels=FALSE,tick=do.tick,mgp=mgp,lwd=axis.lwd,lwd.ticks=ticks.lwd,col=axis.col),dotsaxis))
}else{
do.call("axis", c(list(side=currentside,at=minor.ticks,tcl=tcl*ratio,labels=FALSE,tick=do.tick,mgp=mgp,lwd=axis.lwd,lwd.ticks=ticks.lwd,col=axis.col),dotsaxis))
}
}
}
if(length(dotsmtext)>0){
names(dotsmtext)=c('cex', 'col', 'font')[match(names(dotsmtext), dotskeepmtext)]
}
if(is.null(xlab)==FALSE){
do.call("mtext", c(list(text=xlab, side=ifelse(side[1] %in% c(1,3), side[1], side[2]), line=mtline[1]), dotsmtext))
}
if(is.null(ylab)==FALSE){
do.call("mtext", c(list(text=ylab, side=ifelse(side[2] %in% c(2,4), side[2], side[1]), line=mtline[2]), dotsmtext))
}
if(frame.plot){box()}
par(family=currentfamily)
} |
context("test-SC-sanity")
x <- SC(minimal_mesh)
test_that("SC round trip suite works", {
skip_on_cran()
expect_silent({
SC(x)
SC0(x)
plot(SC(x))
plot(SC0(x))
sc_vertex(x)
sc_coord(x)
sc_node(x)
sc_edge(x)
sc_segment(x)
sc_start(x)
sc_end(x)
sc_object(x)
})
})
test_that("errors when SC0 round trip unsupported", {
expect_error(sc_arc(x))
expect_error(sc_path(x))
expect_error(TRI(x))
expect_error(TRI0(x))
expect_error(ARC(x))
expect_error(ARC0(x))
expect_error(PATH(x))
expect_error(PATH0(x))
}) |
context("testing runSurvReg")
test_that("runSurvReg returns expected values with defaults", {
i <- c(23, 51, 86, 3)
yrestpts <- sample_orig_Ar$DecYear[i]
logqestpts <- sample_orig_Ar$LogQ[i]
yrstart <- min(sample_orig_Ar$DecYear)
yrend <- max(sample_orig_Ar$DecYear)
surv <- runSurvReg(yrestpts, logqestpts, yrstart, yrend, sample_orig_Ar)
expect_equal(dim(surv), c(4,3))
expect_null(names(surv))
expect_is(surv, "matrix")
expect_equal(surv[1,1], -2.8592687416)
expect_equal(surv[3,2], 0.7004624715)
expect_equal(surv[4,3], 0.1019059051)
})
test_that("runSurvReg returns expected values with user args", {
i <- c(19, 171, 512, 303, 11)
yrestpts <- sample_orig_Ch$DecYear[i]
logqestpts <- sample_orig_Ch$LogQ[i]
yrstart <- min(sample_orig_Ch$DecYear)
yrend <- max(sample_orig_Ch$DecYear)
surv <- runSurvReg(yrestpts, logqestpts, yrstart, yrend, sample_orig_Ch,
windowQ = 0.5, minNumObs = 150)
expect_equal(dim(surv), c(5,3))
expect_null(names(surv))
expect_is(surv, "matrix")
expect_equal(surv[5,1], 0.0155175200)
expect_equal(surv[2,2], 0.1936220144)
expect_equal(surv[3,3], 0.6526830391)
}) |
dsal <-
function(x,alpha,sig,mu){
x <- as.matrix(x)
talpha <- as.matrix(alpha,nrow=1,ncol=2);
alpha <- t(talpha);
n <- nrow(x);
p <- ncol(x);
nu <- (2-p)/2;
log.det.sig <- log(det(sig))
if(log.det.sig == "NaN") stop('Degenerate Solution Reached - The Determinate of this matrix is Zero');
ty.t <- sweep(x,2,mu,"-");
inv.sig <- solve(sig)
t1.num <- sweep(ty.t%*%inv.sig%*%talpha,2,log(2),"+");
t1.den <- (p/2)*log(2*pi)+0.5*log.det.sig;
t1 <- sweep(t1.num,2,t1.den,"-");
maha <- mahalanobis(x=x,center=mu,cov=inv.sig,inverted=TRUE);
ata <- 2 + alpha%*%inv.sig%*%talpha;
l.t2.num <- log(maha)
l.t2.den <- log(ata)
l.t2.den <- rep(l.t2.den,n)
t2 <- 0.5*nu*(l.t2.num-l.t2.den)
u <- exp( 0.5*(l.t2.den + l.t2.num) )
t3 <- log(besselK(u,nu,expon.scaled=TRUE)) - u
val1 <- t1+t2+t3
val <- exp(val1)
return(c(val))
} |
.reDate <- function(datedOccs, dateScale){
long=lat=date=parse_date_time=ymd=year=month=day=NULL
if(dateScale == "year"){
out=datedOccs %>% dplyr::select(long,lat,date) %>%
dplyr::mutate(date = as.Date(paste0(date, "-01-01"))) %>%
dplyr::mutate(years = lubridate::year(date))
}
if(dateScale == "month"){
out=datedOccs %>% dplyr::select(long,lat,date) %>%
dplyr::mutate(date = lubridate::parse_date_time(date, "ym")) %>%
dplyr::mutate(months = lubridate::month(date)) %>%
dplyr::mutate(years = lubridate::year(date))
}
if(dateScale == "day"){
out=datedOccs %>% dplyr::select(long,lat,date) %>%
dplyr::mutate(date = lubridate::ymd(date)) %>%
dplyr::mutate(years = lubridate::year(date)) %>%
dplyr::mutate(months = lubridate::month(date)) %>%
dplyr::mutate(days = lubridate::day(date))
}
return(out)
}
.uniDates<-function(occ1, dateScale){
years=days=NULL
if (dateScale == "year"){
out=dplyr::arrange(unique(dplyr::select(occ1, years)), years)
}
if (dateScale == "month"){
out=dplyr::arrange(unique(dplyr::select(occ1, years, months)), years)
}
if (dateScale == "day"){
out=dplyr::arrange(unique(dplyr::select(occ1, years, months, days)), years)
}
return(out)
}
.parseDate <- function(dateScale, occ1, uniqueDates){
years=days=NULL
t1 <- NULL
if (dateScale == "year"){
for (i in 1:nrow(uniqueDates)){
t1[[i]] = dplyr::filter(occ1, years == as.list(uniqueDates)$years[[i]])
}}
if (dateScale == "month"){
t1 <- NULL
for (i in 1:nrow(uniqueDates)){
t1[[i]] = dplyr::filter(occ1, months == as.list(uniqueDates)$years[[i]])
}}
if (dateScale == "day"){
t1 <- NULL
for (i in 1:nrow(uniqueDates)){
t1[[i]] = dplyr::filter(occ1, days == as.list(uniqueDates)$years[[i]])
}}
return(t1)
} |
NULL
read <- function(path) {
path <- normalizePath(path, mustWork = TRUE)
.Call("sourcetools_read", path, PACKAGE = "sourcetools")
}
read_lines <- function(path) {
path <- normalizePath(path, mustWork = TRUE)
.Call("sourcetools_read_lines", path, PACKAGE = "sourcetools")
}
read_bytes <- function(path) {
path <- normalizePath(path, mustWork = TRUE)
.Call("sourcetools_read_bytes", path, PACKAGE = "sourcetools")
}
read_lines_bytes <- function(path) {
path <- normalizePath(path, mustWork = TRUE)
.Call("sourcetools_read_lines_bytes", path, PACKAGE = "sourcetools")
}
tokenize_file <- function(path) {
path <- normalizePath(path, mustWork = TRUE)
.Call("sourcetools_tokenize_file", path, PACKAGE = "sourcetools")
}
tokenize_string <- function(string) {
.Call("sourcetools_tokenize_string", as.character(string), PACKAGE = "sourcetools")
}
tokenize <- function(file = "", text = NULL) {
if (is.null(text))
text <- read(file)
tokenize_string(text)
}
print.RTokens <- function(x, ...) {
print.data.frame(x, ...)
} |
generate.mirt_object <- function(parameters, itemtype, latent_means = NULL,
latent_covariance = NULL, key = NULL,
min_category = rep(0L, length(itemtype))){
if(missing(itemtype))
stop('Must define an itemtype argument', call.=FALSE)
if(missing(parameters))
stop('Must define parameters argument', call.=FALSE)
parameters <- as.matrix(parameters)
if(length(itemtype) == 1L)
itemtype <- rep(itemtype, nrow(parameters))
if(nrow(parameters) != length(itemtype))
stop('nrow(parameters) not equal to length(itemtype)', call.=FALSE)
nitems <- length(itemtype)
K <- integer(nitems)
names <- colnames(parameters)
itemtype[itemtype %in% c('3PL', '3PLu', '4PL')] <- '2PL'
itemtype[itemtype %in% c('3PLNRM', '3PLuNRM', '4PLNRM')] <- '2PLNRM'
itemtype[itemtype == 'PC3PL'] <- 'PC2PL'
for(i in seq_len(nitems)){
pick <- parameters[i, !is.na(parameters[i,]), drop=FALSE]
nms <- colnames(pick)
if(itemtype[i] == 'Rasch'){
itemtype[i] <- if(any(nms == 'd')) '2PL' else 'gpcm'
}
if(itemtype[i] %in% c('2PL', 'ideal', 'PC2PL')){
K[i] <- 2L
} else if(itemtype[i] %in% c('graded', 'grsm', 'gpcm', 'nominal', '2PLNRM')){
K[i] <- max(sapply(strsplit(nms[grepl('d', nms)], 'd'), function(x) as.numeric(x[2]))) + 1
} else {
stop(sprintf('%s is an invalid itemtype argument. Please fix!', itemtype[i]), call.=FALSE)
}
}
dat <- matrix(c(0,1), 2L, nitems)
colnames(dat) <- dnames <- paste0('Item.', 1:nitems)
nfact <- max(which(paste0('a', 1:250) %in% names))
tmp <- parameters[,paste0('a', 1:nfact), drop=FALSE]
tmp[is.na(tmp)] <- 0
parameters[, paste0('a', 1:nfact)] <- tmp
model <- character(nfact)
for(i in seq_len(nfact))
model[i] <- paste0('F', i, ' = 1-', ncol(dat))
model <- mirt.model(paste0(model, collapse = '\n'))
sv <- mirt(dat, model, itemtype=itemtype, key=key, technical=list(customK=K), pars='values')
for(i in seq_len(nitems)){
pick <- parameters[i, !is.na(parameters[i,]), drop=FALSE]
nms <- colnames(pick)
wch <- which(sv$item == dnames[i])
for(j in seq_len(ncol(pick))){
wch2 <- which(sv[wch, ]$name == nms[j])
sv[wch[wch2], ]$value <- pick[,j]
}
}
if(!is.null(latent_means))
sv$value[sv$item == 'GROUP' & grepl('MEAN', sv$name)] <- as.numeric(latent_means)
if(!is.null(latent_covariance)){
if(!is.matrix(latent_covariance))
stop('latent_covariance input must be a matrix', call.=FALSE)
vals <- latent_covariance[lower.tri(latent_covariance, TRUE)]
sv$value[sv$item == 'GROUP' & grepl('COV', sv$name)] <- vals
}
dat <- t(t(dat) + min_category)
ret <- mirt(dat, model, itemtype=itemtype, technical=list(customK=K, warn=FALSE, message=FALSE),
TOL=NA, pars=sv, quadpts = 1, key=key, rotate = 'none')
ret@Options$exploratory <- FALSE
ret
} |
context("gni_details")
test_that("gni_details returns the correct value", {
skip_on_cran()
vcr::use_cassette("gni_details", {
x <- gni_details(id = 17802847)
})
expect_is(x, "data.frame")
expect_match(as.character(x[,3]), "none")
}) |
library(dplyr)
library(freqtables)
data(mtcars)
testthat::context("test-freq_test.R")
testthat::test_that("Group n is returned as expected", {
n <- mtcars %>% get_group_n(cyl == 4)
testthat::expect_match(n, "N = 11")
})
rm(mtcars, df)
detach("package:dplyr", unload=TRUE)
detach("package:freqtables", unload=TRUE) |
context("buildSemanticArgumentName")
test_that("buildSemanticArgumentName", {
expect_equal(buildSemanticArgumentName('s'), 'x_s')
expect_equal(buildSemanticArgumentName('i', 'numberOfItems'), 'numberOfItems_i')
expect_equal(buildSemanticArgumentName('i', 'numberOfItems_'), 'numberOfItems_i')
expect_equal(buildSemanticArgumentName('i_7', 'numberOfItems'), 'numberOfItems_i_7')
expect_equal(buildSemanticArgumentName('_', 'numberOfItems'), 'numberOfItems_')
expect_equal(buildSemanticArgumentName('_', 'numberOfItems_'), 'numberOfItems_')
expect_equal(buildSemanticArgumentName('_'), 'x_')
}) |
weirddate<-function(x){
bad<-NULL
fy<-as.numeric(substring(x[1,1],1,4))
ly<-as.numeric(substring(x[nrow(x),1],1,4))
x$year<-as.numeric(substring(x[,1],1,4));x$month<-as.numeric(substring(x[,1],5,6));x$day<-as.numeric(substring(x[,1],7,8))
k1<-which(x$year < fy | x$year > ly)
k2<-which(x$day > 31)
k3<-which(x$day > 30 & x$month %in% c(4,6,9,11))
k4<-which(x$day > 29 & x$month ==2)
k5<-which(x$day > 28 & x$month == 2 & x$year%%4 !=0 )
k6<-which(x$day > 28 & x$month == 2 & x$year == 1900 )
k7<-which(x$month < 1 | x$month > 12)
bad<-c(k1,k2,k3,k4,k5,k6,k7)
return(bad)
} |
if (Sys.getenv("RunAllRcppTests") != "yes") exit_file("Set 'RunAllRcppTests' to 'yes' to run.")
Rcpp::sourceCpp("cpp/na.cpp")
expect_identical( R_IsNA_(NA_real_), Rcpp_IsNA(NA_real_) )
expect_identical( R_IsNA_(NA_real_+1), Rcpp_IsNA(NA_real_+1) )
expect_identical( R_IsNA_(NA_real_+NaN), Rcpp_IsNA(NA_real_+NaN) )
expect_identical( R_IsNA_(NaN+NA_real_), Rcpp_IsNA(NaN+NA_real_) )
expect_identical( R_IsNaN_(NA_real_), Rcpp_IsNaN(NA_real_) )
expect_identical( R_IsNaN_(NaN), Rcpp_IsNaN(NaN) )
expect_identical( R_IsNaN_(NaN+1), Rcpp_IsNaN(NaN+1) ) |
lav_model_efa_rotate <- function(lavmodel = NULL, lavoptions = NULL) {
if(lavmodel@nefa == 0L || lavoptions$rotation == "none") {
return(lavmodel)
}
x.orig <- lav_model_get_parameters(lavmodel, type = "free", extra = FALSE)
tmp <- lav_model_efa_rotate_x(x = x.orig, lavmodel = lavmodel,
lavoptions = lavoptions, extra = TRUE)
extra <- attr(tmp, "extra"); attr(tmp, "extra") <- NULL
lavmodel@H <- extra$H
[email protected] <- extra$lv.order
lavmodel@GLIST <- extra$GLIST
lavmodel
}
lav_model_efa_rotate_x <- function(x, lavmodel = NULL, lavoptions = NULL,
init.rot = NULL, extra = FALSE,
type = "free") {
method <- lavoptions$rotation
if(method == "none") {
return(x)
}
ropts <- lavoptions$rotation.args
lavmodel.orig <- lav_model_set_parameters(lavmodel, x = x)
GLIST <- lavmodel.orig@GLIST
H <- vector("list", lavmodel@ngroups)
ORDER <- vector("list", lavmodel@ngroups)
for(g in seq_len(lavmodel@ngroups)) {
mm.in.group <- seq_len(lavmodel@nmat[g]) + cumsum(c(0,lavmodel@nmat))[g]
MLIST <- GLIST[ mm.in.group ]
H[[g]] <- Hg <- diag( ncol(MLIST$lambda) )
lv.order <- seq_len( ncol(MLIST$lambda) )
LAMBDA.g <- computeLAMBDA.LISREL(MLIST = MLIST,
ov.y.dummy.ov.idx = [email protected][[g]],
ov.x.dummy.ov.idx = [email protected][[g]],
ov.y.dummy.lv.idx = [email protected][[g]],
ov.x.dummy.lv.idx = [email protected][[g]],
remove.dummy.lv = TRUE)
THETA.g <- computeTHETA.LISREL(MLIST = MLIST,
ov.y.dummy.ov.idx = [email protected][[g]],
ov.x.dummy.ov.idx = [email protected][[g]],
ov.y.dummy.lv.idx = [email protected][[g]],
ov.x.dummy.lv.idx = [email protected][[g]])
for(set in seq_len(lavmodel@nefa)) {
ov.idx <- [email protected][[g]][[set]]
lv.idx <- [email protected][[g]][[set]]
if(length(ov.idx) == 0L) {
next
}
if(length(lv.idx) < 2L) {
next
}
A <- LAMBDA.g[ov.idx, lv.idx, drop = FALSE]
if(ropts$std.ov) {
THETA <- THETA.g[ov.idx, ov.idx, drop = FALSE]
Sigma <- tcrossprod(A) + THETA
this.ov.var <- diag(Sigma)
} else {
this.ov.var <- NULL
}
if(!is.null(init.rot) && lavoptions$rotation.args$jac.init.rot) {
init.ROT <- init.rot[[g]][lv.idx, lv.idx, drop = FALSE]
rstarts <- 0
} else {
init.ROT <- NULL
rstarts <- ropts$rstarts
}
res <- lav_matrix_rotate(A = A,
orthogonal = ropts$orthogonal,
method = method,
method.args = list(
geomin.epsilon = ropts$geomin.epsilon,
orthomax.gamma = ropts$orthomax.gamma,
cf.gamma = ropts$orthomax.gamma,
oblimin.gamma = ropts$oblimin.gamma,
target = ropts$target,
target.mask = ropts$target.mask),
init.ROT = init.ROT,
init.ROT.check = FALSE,
rstarts = rstarts,
row.weights = ropts$row.weights,
std.ov = ropts$std.ov,
ov.var = this.ov.var,
verbose = ropts$verbose,
warn = ropts$warn,
algorithm = ropts$algorithm,
reflect = ropts$reflect,
order.lv.by = ropts$order.lv.by,
gpa.tol = ropts$gpa.tol,
tol = ropts$tol,
max.iter = ropts$max.iter)
H.efa <- res$ROT
Hg[lv.idx, lv.idx] <- H.efa
lv.order[ lv.idx ] <- lv.idx[res$order.idx]
}
MLIST$lambda <- t(solve(Hg, t(MLIST$lambda)))
MLIST$psi <- t(Hg) %*% MLIST$psi %*% Hg
if(!is.null(MLIST$beta)) {
MLIST$beta <- t(Hg) %*% t(solve(Hg, t(MLIST$beta)))
}
if(!is.null(MLIST$alpha)) {
MLIST$alpha <- t(Hg) %*% MLIST$alpha
}
GLIST[ mm.in.group ] <- MLIST
H[[g]] <- Hg
ORDER[[g]] <- lv.order
}
x.rot <- lav_model_get_parameters(lavmodel, GLIST = GLIST, type = type)
if(extra) {
attr(x.rot, "extra") <- list(GLIST = GLIST, H = H, lv.order = ORDER)
}
x.rot
}
lav_model_efa_rotate_border_x <- function(x, lavmodel = NULL,
lavoptions = NULL,
lavpartable = NULL) {
method <- lavoptions$rotation
ropts <- lavoptions$rotation.args
method.args <- list( geomin.epsilon = ropts$geomin.epsilon,
orthomax.gamma = ropts$orthomax.gamma,
cf.gamma = ropts$orthomax.gamma,
oblimin.gamma = ropts$oblimin.gamma,
target = ropts$target,
target.mask = ropts$target.mask )
lavmodel <- lav_model_set_parameters(lavmodel, x = x)
GLIST <- lavmodel@GLIST
res <- numeric(0L)
for(g in seq_len(lavmodel@ngroups)) {
mm.in.group <- seq_len(lavmodel@nmat[g]) + cumsum(c(0,lavmodel@nmat))[g]
MLIST <- GLIST[ mm.in.group ]
LAMBDA.g <- computeLAMBDA.LISREL(MLIST = MLIST,
ov.y.dummy.ov.idx = [email protected][[g]],
ov.x.dummy.ov.idx = [email protected][[g]],
ov.y.dummy.lv.idx = [email protected][[g]],
ov.x.dummy.lv.idx = [email protected][[g]],
remove.dummy.lv = TRUE)
THETA.g <- computeTHETA.LISREL(MLIST = MLIST,
ov.y.dummy.ov.idx = [email protected][[g]],
ov.x.dummy.ov.idx = [email protected][[g]],
ov.y.dummy.lv.idx = [email protected][[g]],
ov.x.dummy.lv.idx = [email protected][[g]])
set.names <- lav_partable_efa_values(lavpartable)
for(set in seq_len(lavmodel@nefa)) {
ind.idx <- which(lavpartable$op == "=~" &
lavpartable$group == g &
lavpartable$efa == set.names[set])
if(!any(lavpartable$user[ind.idx] == 7L)) {
next
}
ov.idx <- [email protected][[g]][[set]]
lv.idx <- [email protected][[g]][[set]]
if(length(ov.idx) == 0L) {
next
}
if(length(lv.idx) < 2L) {
next
}
A <- LAMBDA.g[ov.idx, lv.idx, drop = FALSE]
P <- nrow(A); M <- ncol(A)
if(!ropts$orthogonal) {
PSI <- MLIST$psi[lv.idx, lv.idx, drop = FALSE]
}
if(ropts$std.ov) {
THETA <- THETA.g[ov.idx, ov.idx, drop = FALSE]
Sigma <- tcrossprod(A) + THETA
this.ov.var <- diag(Sigma)
} else {
this.ov.var <- rep(1, P)
}
method <- tolower(method)
if(method %in% c("cf-quartimax", "cf-varimax", "cf-equamax",
"cf-parsimax", "cf-facparsim")) {
method.fname <- "lav_matrix_rotate_cf"
method.args$cf.gamma <- switch(method,
"cf-quartimax" = 0,
"cf-varimax" = 1 / P,
"cf-equamax" = M / (2 * P),
"cf-parsimax" = (M - 1) / (P + M - 2),
"cf-facparsim" = 1)
} else {
method.fname <- paste("lav_matrix_rotate_", method, sep = "")
}
check <- try(get(method.fname), silent = TRUE)
if(inherits(check, "try-error")) {
stop("lavaan ERROR: unknown rotation method: ", method.fname)
}
if(ropts$std.ov) {
A <- A * 1/sqrt(this.ov.var)
}
if(ropts$row.weights == "none") {
weights <- rep(1.0, P)
} else if(ropts$row.weights == "kaiser") {
weights <- lav_matrix_rotate_kaiser_weights(A)
} else if(ropts$row.weights == "cureton-mulaik") {
weights <- lav_matrix_rotate_cm_weights(A)
} else {
stop("lavaan ERROR: row.weights can be none, kaiser or cureton-mulaik")
}
A <- A * weights
Q <- do.call(method.fname,
c(list(LAMBDA = A), method.args, list(grad = TRUE)))
Gq <- attr(Q, "grad"); attr(Q, "grad") <- NULL
Z <- crossprod(A, Gq)
if(ropts$orthogonal) {
tmp <- Z - t(Z)
this.res <- lav_matrix_vech(tmp, diagonal = FALSE)
} else {
PSI.z <- PSI * diag(Z)
tmp <- Z - PSI.z
out1 <- lav_matrix_vech( tmp, diagonal = FALSE)
out2 <- lav_matrix_vechu(tmp, diagonal = FALSE)
this.res <- c(out1, out2)
}
res <- c(res, this.res)
}
}
res
} |
par(ask=TRUE)
opar <- par(no.readonly=TRUE)
attach(mtcars)
plot(wt, mpg,
main="Basic Scatterplot of MPG vs. Weight",
xlab="Car Weight (lbs/1000)",
ylab="Miles Per Gallon ", pch=19)
abline(lm(mpg ~ wt), col="red", lwd=2, lty=1)
lines(lowess(wt, mpg), col="blue", lwd=2, lty=2)
detach(mtcars)
library(car)
scatterplot(mpg ~ wt | cyl, data=mtcars, lwd=2,
main="Scatter Plot of MPG vs. Weight by
xlab="Weight of Car (lbs/1000)",
ylab="Miles Per Gallon", id.method="identify",
legend.plot=TRUE, labels=row.names(mtcars),
boxplots="xy")
pairs(~ mpg + disp + drat + wt, data=mtcars,
main="Basic Scatterplot Matrix")
library(car)
library(car)
scatterplotMatrix(~ mpg + disp + drat + wt, data=mtcars,
spread=FALSE, smoother.args=list(lty=2),
main="Scatter Plot Matrix via car Package")
set.seed(1234)
n <- 10000
c1 <- matrix(rnorm(n, mean=0, sd=.5), ncol=2)
c2 <- matrix(rnorm(n, mean=3, sd=2), ncol=2)
mydata <- rbind(c1, c2)
mydata <- as.data.frame(mydata)
names(mydata) <- c("x", "y")
with(mydata,
plot(x, y, pch=19, main="Scatter Plot with 10000 Observations"))
with(mydata,
smoothScatter(x, y, main="Scatter Plot colored by Smoothed Densities"))
library(hexbin)
with(mydata, {
bin <- hexbin(x, y, xbins=50)
plot(bin, main="Hexagonal Binning with 10,000 Observations")
})
library(scatterplot3d)
attach(mtcars)
scatterplot3d(wt, disp, mpg,
main="Basic 3D Scatter Plot")
scatterplot3d(wt, disp, mpg,
pch=16,
highlight.3d=TRUE,
type="h",
main="3D Scatter Plot with Vertical Lines")
s3d <-scatterplot3d(wt, disp, mpg,
pch=16,
highlight.3d=TRUE,
type="h",
main="3D Scatter Plot with Vertical Lines and Regression Plane")
fit <- lm(mpg ~ wt+disp)
s3d$plane3d(fit)
detach(mtcars)
library(rgl)
attach(mtcars)
plot3d(wt, disp, mpg, col="red", size=5)
library(car)
with(mtcars,
scatter3d(wt, disp, mpg))
attach(mtcars)
r <- sqrt(disp/pi)
symbols(wt, mpg, circle=r, inches=0.30,
fg="white", bg="lightblue",
main="Bubble Plot with point size proportional to displacement",
ylab="Miles Per Gallon",
xlab="Weight of Car (lbs/1000)")
text(wt, mpg, rownames(mtcars), cex=0.6)
detach(mtcars)
opar <- par(no.readonly=TRUE)
par(mfrow=c(1,2))
t1 <- subset(Orange, Tree==1)
plot(t1$age, t1$circumference,
xlab="Age (days)",
ylab="Circumference (mm)",
main="Orange Tree 1 Growth")
plot(t1$age, t1$circumference,
xlab="Age (days)",
ylab="Circumference (mm)",
main="Orange Tree 1 Growth",
type="b")
par(opar)
Orange$Tree <- as.numeric(Orange$Tree)
ntrees <- max(Orange$Tree)
xrange <- range(Orange$age)
yrange <- range(Orange$circumference)
plot(xrange, yrange,
type="n",
xlab="Age (days)",
ylab="Circumference (mm)"
)
colors <- rainbow(ntrees)
linetype <- c(1:ntrees)
plotchar <- seq(18, 18+ntrees, 1)
for (i in 1:ntrees) {
tree <- subset(Orange, Tree==i)
lines(tree$age, tree$circumference,
type="b",
lwd=2,
lty=linetype[i],
col=colors[i],
pch=plotchar[i]
)
}
title("Tree Growth", "example of line plot")
legend(xrange[1], yrange[2],
1:ntrees,
cex=0.8,
col=colors,
pch=plotchar,
lty=linetype,
title="Tree"
)
options(digits=2)
cor(mtcars)
library(corrgram)
corrgram(mtcars, order=TRUE, lower.panel=panel.shade,
upper.panel=panel.pie, text.panel=panel.txt,
main="Corrgram of mtcars intercorrelations")
corrgram(mtcars, order=TRUE, lower.panel=panel.ellipse,
upper.panel=panel.pts, text.panel=panel.txt,
diag.panel=panel.minmax,
main="Corrgram of mtcars data using scatter plots
and ellipses")
cols <- colorRampPalette(c("darkgoldenrod4", "burlywood1",
"darkkhaki", "darkgreen"))
corrgram(mtcars, order=TRUE, col.regions=cols,
lower.panel=panel.shade,
upper.panel=panel.conf, text.panel=panel.txt,
main="A Corrgram (or Horse) of a Different Color")
ftable(Titanic)
library(vcd)
mosaic(Titanic, shade=TRUE, legend=TRUE)
library(vcd)
mosaic(~Class+Sex+Age+Survived, data=Titanic, shade=TRUE, legend=TRUE)
x <- c(1:5)
y <- c(1:5)
par(mfrow=c(2,4))
types <- c("p", "l", "o", "b", "c", "s", "S", "h")
for (i in types){
plottitle <- paste("type=", i)
plot(x,y,type=i, col="red", lwd=2, cex=1, main=plottitle)
} |
Mstep.nh.ARfix.MSAR <-
function(data,theta,FB,covar=NULL,method=method) {
order=attributes(theta)$order
d=dim(data)[3]
if(is.na(d) | is.null(d)){d=1}
M=attributes(theta)$NbRegimes
if (length(covar)==1) {
Lag = covar
covar = array(data[(1):(T-Lag+1),,],c(T-Lag+1,N.samples,d))
data = array(data[Lag:T,,],c(T-Lag+1,N.samples,d))
}
N.samples = dim(covar)[2]
ncov.trans = dim(covar)[3]
par.hh = Mstep.hh.MSAR(data,theta,FB)
theta$transmat[which(theta$transmat<1e-15)] = 1e-15
theta$transmat = mk_stochastic(theta$transmat)
trans = para_trans(theta$transmat)
par.trans = theta$par.trans
nh_transition = attributes(theta)$nh.transitions
par.init = plie2(trans,par.trans)
lxi = dim(FB$probSS)[3]
if (order>0) {deb = order+1}
else {deb = 1}
if (is.null(method)) {method="ucminf"}
if (method=="ucminf") {resopt = ucminf(par.init,fn=loglik_nh_inp,gr=NULL,covar=array(covar[deb+(1:(lxi)),,],c(lxi,N.samples,ncov.trans)),xi=FB$probSS,nh_transition=nh_transition,hessian=0,control = list(trace=FALSE))}
else if (method=="L-BFGS-B"){resopt = optim(par.init,fn=loglik_nh_inp,gr=NULL,covar=array(covar[deb+(1:(lxi)),,],c(lxi,N.samples,ncov.trans)),xi=FB$probSS,nh_transition=nh_transition,hessian=0,control = list(trace=FALSE),method="L-BFGS-B")}
else if (method=="BFGS"){resopt = optim(par.init,fn=loglik_nh_inp,gr=NULL,covar=array(covar[deb+(1:(lxi)),,],c(lxi,N.samples,ncov.trans)),xi=FB$probSS,nh_transition=nh_transition,hessian=0,control = list(trace=FALSE),method="BFGS")}
res = deplie2(resopt$par);
trans = res$trans ;
par.trans = res$par ;
transmat=para_trans_inv(trans);
if (order>0) {
list(A=par.hh$A,sigma=par.hh$sigma,A0=par.hh$A0,prior=par.hh$prior,transmat=transmat,par.trans=par.trans)
} else {
list(sigma=par.hh$sigma,A0=par.hh$A0,prior=par.hh$prior,transmat=transmat,par.trans=par.trans)
}
} |
library(oompaBase)
mat <- matrix(1:1024, ncol=1)
opar <- par(mfrow=c(8, 1), mai=c(0.3, 0.5, 0.2, 0.2))
image(mat, col=jetColors(128), main='jetColors')
image(mat, col=wheel(64, 0.5), main='wheel, half saturation')
image(mat, col=redgreen(64), main='redgreen')
image(mat, col=blueyellow(32), main='blueyellow')
image(mat, col=cyanyellow(32), main='cyanyellow')
image(mat, col=redscale(64), main='redscale')
image(mat, col=bluescale(64), main='bluescale')
image(mat, col=greyscale(64), main='greyscale')
par(opar)
ng <- 10000
ns <- 50
dat <- matrix(rnorm(ng*ns, 0, rep(c(1, 2), each=25)), ncol=ns, byrow=TRUE)
dat[1:500, 1:25] <- dat[1:500, 1:25] + 2
clas <- factor(rep(c('Good', 'Bad'), each=25))
a0 <- proc.time()
myMean <- matrixMean(dat)
used0 <- proc.time() - a0
a1 <- proc.time()
mm <- apply(dat, 1, mean)
used1 <- proc.time() - a1
summary(as.vector(myMean-mm))
used0
used1
a0 <- proc.time()
myVar <- matrixVar(dat, myMean)
a1 <- proc.time()
vv <- apply(dat, 1, var)
a2 <- proc.time()
summary(as.vector(myVar - vv))
a1 - a0
a2 - a1
t0 <- proc.time()
myT <- matrixT(dat, clas)
t1 <- proc.time()
tt <- sapply(1:nrow(dat), function(i) {
t.test(dat[i,clas=="Bad"], dat[i, clas=="Good"], var.equal=T)$statistic
})
t2 <- proc.time()
summary(as.vector(tt - myT))
t1 - t0
t2 - t1
x <- matrix(rnorm(100*3), nrow=100, ncol=3)
class1 <- class2<- rep(FALSE, 100)
class1[sample(100, 20)] <- TRUE
class2[sample(100, 20)] <- TRUE
class3 <- !(class1 | class2)
codes <- list(ColorCoding(class1, "red", 16),
ColorCoding(class2, "blue", 15),
ColorCoding(class3, "black", 17))
par(mfrow=c(2,1))
plot(ColorCodedPair(x[,1], x[,2], codes), xlab="Coord1", ylab="Coord2")
plot(ColorCodedPair(x[,1], x[,3], codes), xlab="Coord1", ylab="Coord3")
par(mfrow=c(1,1)) |
library(testthat)
library(synthACS)
context("macroACS methods")
test_that("fetch - age_by_sex - estimates work", {
options(warn=-1)
age_sex_vector_all <- fetch_data(ca_dat, geography= "*", dataset= "estimate",
choice= "age_by_sex")
age_sex_vector_some <- fetch_data(ca_dat, geography= c("Alameda", "Amador", "Los Angeles"),
dataset= "estimate", choice= "age_by_sex")
age_sex_vector_one <- fetch_data(ca_dat, geography= "San Bernardino", dataset= "estimate",
choice= "age_by_sex")
options(warn=0)
expect_true(exists("age_sex_vector_all"))
expect_true(exists("age_sex_vector_some"))
expect_true(exists("age_sex_vector_one"))
expect_true(is.data.frame(age_sex_vector_all))
expect_true(is.data.frame(age_sex_vector_some))
expect_true(is.data.frame(age_sex_vector_one))
expect_equal(nrow(age_sex_vector_all), nrow(ca_dat$geography))
expect_equal(names(age_sex_vector_all), names(ca_dat$estimates$age_by_sex))
expect_equal(rownames(age_sex_vector_all), ca_dat$geography$NAME)
expect_equal(age_sex_vector_all, ca_dat$estimates$age_by_sex)
expect_equal(nrow(age_sex_vector_some), 3L)
expect_equal(names(age_sex_vector_some), names(ca_dat$estimates$age_by_sex))
expect_equal(rownames(age_sex_vector_some),
c("Alameda County, California", "Amador County, California", "Los Angeles County, California"))
expect_equal(age_sex_vector_some, ca_dat$estimates$age_by_sex[c(1,3,19),])
expect_equal(nrow(age_sex_vector_one), 1L)
expect_equal(names(age_sex_vector_one), names(ca_dat$estimates$age_by_sex))
expect_equal(rownames(age_sex_vector_one), "San Bernardino County, California")
expect_equal(age_sex_vector_one, ca_dat$estimates$age_by_sex[36,])
})
test_that("fetch - age_by_sex - SE work", {
options(warn=-1)
age_sex_vector_all <- fetch_data(ca_dat, geography= "*", dataset= "st.err",
choice= "age_by_sex")
age_sex_vector_some <- fetch_data(ca_dat, geography= c("Alameda", "Amador", "Los Angeles"),
dataset= "st.err", choice= "age_by_sex")
age_sex_vector_one <- fetch_data(ca_dat, geography= "San Bernardino", dataset= "st.err",
choice= "age_by_sex")
options(warn=0)
expect_true(exists("age_sex_vector_all"))
expect_true(exists("age_sex_vector_some"))
expect_true(exists("age_sex_vector_one"))
expect_true(is.data.frame(age_sex_vector_all))
expect_true(is.data.frame(age_sex_vector_some))
expect_true(is.data.frame(age_sex_vector_one))
expect_equal(nrow(age_sex_vector_all), nrow(ca_dat$geography))
expect_equal(names(age_sex_vector_all), names(ca_dat$standard_error$age_by_sex))
expect_equal(rownames(age_sex_vector_all), ca_dat$geography$NAME)
expect_equal(age_sex_vector_all, ca_dat$standard_error$age_by_sex)
expect_equal(nrow(age_sex_vector_some), 3L)
expect_equal(names(age_sex_vector_some), names(ca_dat$standard_error$age_by_sex))
expect_equal(rownames(age_sex_vector_some),
c("Alameda County, California", "Amador County, California", "Los Angeles County, California"))
expect_equal(age_sex_vector_some, ca_dat$standard_error$age_by_sex[c(1,3,19),])
expect_equal(nrow(age_sex_vector_one), 1L)
expect_equal(names(age_sex_vector_one), names(ca_dat$standard_error$age_by_sex))
expect_equal(rownames(age_sex_vector_one), "San Bernardino County, California")
expect_equal(age_sex_vector_one, ca_dat$standard_error$age_by_sex[36,])
})
test_that("fetch - pop_by_race - estimates work", {
options(warn=-1)
vector_all <- fetch_data(ca_dat, geography= "*", dataset= "estimate",
choice= "pop_by_race")
vector_some <- fetch_data(ca_dat, geography= c("Alameda", "Amador", "Los Angeles"),
dataset= "estimate", choice= "pop_by_race")
vector_one <- fetch_data(ca_dat, geography= "San Bernardino", dataset= "estimate",
choice= "pop_by_race")
options(warn=0)
expect_true(exists("vector_all"))
expect_true(exists("vector_some"))
expect_true(exists("vector_one"))
expect_true(is.data.frame(vector_all))
expect_true(is.data.frame(vector_some))
expect_true(is.data.frame(vector_one))
expect_equal(nrow(vector_all), nrow(ca_dat$geography))
expect_equal(names(vector_all), names(ca_dat$estimates$pop_by_race))
expect_equal(rownames(vector_all), ca_dat$geography$NAME)
expect_equal(vector_all, ca_dat$estimates$pop_by_race)
expect_equal(nrow(vector_some), 3L)
expect_equal(names(vector_some), names(ca_dat$estimates$pop_by_race))
expect_equal(rownames(vector_some),
c("Alameda County, California", "Amador County, California", "Los Angeles County, California"))
expect_equal(vector_some, ca_dat$estimates$pop_by_race[c(1,3,19),])
expect_equal(nrow(vector_one), 1L)
expect_equal(names(vector_one), names(ca_dat$estimates$pop_by_race))
expect_equal(rownames(vector_one), "San Bernardino County, California")
expect_equal(vector_one, ca_dat$estimates$pop_by_race[36,])
})
test_that("fetch - pop_by_race - SE work", {
options(warn=-1)
vector_all <- fetch_data(ca_dat, geography= "*", dataset= "st.err",
choice= "pop_by_race")
vector_some <- fetch_data(ca_dat, geography= c("Alameda", "Amador", "Los Angeles"),
dataset= "st.err", choice= "pop_by_race")
vector_one <- fetch_data(ca_dat, geography= "San Bernardino", dataset= "st.err",
choice= "pop_by_race")
options(warn=0)
expect_true(exists("vector_all"))
expect_true(exists("vector_some"))
expect_true(exists("vector_one"))
expect_true(is.data.frame(vector_all))
expect_true(is.data.frame(vector_some))
expect_true(is.data.frame(vector_one))
expect_equal(nrow(vector_all), nrow(ca_dat$geography))
expect_equal(names(vector_all), names(ca_dat$standard_error$pop_by_race))
expect_equal(rownames(vector_all), ca_dat$geography$NAME)
expect_equal(vector_all, ca_dat$standard_error$pop_by_race)
expect_equal(nrow(vector_some), 3L)
expect_equal(names(vector_some), names(ca_dat$standard_error$pop_by_race))
expect_equal(rownames(vector_some),
c("Alameda County, California", "Amador County, California", "Los Angeles County, California"))
expect_equal(vector_some, ca_dat$standard_error$pop_by_race[c(1,3,19),])
expect_equal(nrow(vector_one), 1L)
expect_equal(names(vector_one), names(ca_dat$standard_error$pop_by_race))
expect_equal(rownames(vector_one), "San Bernardino County, California")
expect_equal(vector_one, ca_dat$standard_error$pop_by_race[36,])
})
test_that("span, endyear, geography, dataset names", {
sp <- get_span(ca_dat)
expect_equal(sp, ca_dat$span)
end <- get_endyear(ca_dat)
expect_equal(end, ca_dat$endyear)
g <- get_geography(ca_dat)
expect_equal(g, ca_dat$geo_title)
nn <- get_dataset_names(ca_dat)
expect_equal(nn, names(ca_dat$estimates))
expect_equal(nn, names(ca_dat$standard_error))
})
test_that("split macroACS works", {
ca_split <- split(ca_dat, n_splits= 7)
split_idx <- parallel::splitIndices(nrow(ca_dat$geography), 7)
expect_equal(unlist(lapply(ca_split, class)), rep("macroACS", 7))
expect_equal(unlist(lapply(ca_split, names)), rep(names(ca_dat), 7))
expect_equal(unlist(lapply(ca_split, get_span)), rep(get_span(ca_dat), 7))
expect_equal(unlist(lapply(ca_split, get_endyear)), rep(get_endyear(ca_dat), 7))
expect_equal(unlist(lapply(ca_split, function(l) return(l$geo_title))), rep(NULL, 7))
expect_equal(nrow(ca_split[[1]]$estimates[[1]]), length(split_idx[[1]]))
expect_equal(nrow(ca_split[[2]]$estimates[[7]]), length(split_idx[[2]]))
expect_equal(nrow(ca_split[[3]]$estimates[[8]]), length(split_idx[[3]]))
expect_equal(nrow(ca_split[[4]]$estimates[[5]]), length(split_idx[[4]]))
expect_equal(nrow(ca_split[[5]]$standard_error[[2]]), length(split_idx[[5]]))
expect_equal(nrow(ca_split[[6]]$standard_error[[6]]), length(split_idx[[6]]))
expect_equal(nrow(ca_split[[7]]$standard_error[[10]]), length(split_idx[[7]]))
expect_equal(ca_split[[1]]$geography, ca_dat$geography[ split_idx[[1]], ])
expect_equal(ca_split[[4]]$geography, ca_dat$geography[ split_idx[[4]], ])
expect_equal(ca_split[[7]]$geography, ca_dat$geography[ split_idx[[7]], ])
expect_equal(ca_split[[2]]$estimates, lapply(ca_dat$estimates, function(l, idx) return(l[idx, ]), idx= split_idx[[2]]))
expect_equal(ca_split[[3]]$estimates, lapply(ca_dat$estimates, function(l, idx) return(l[idx, ]), idx= split_idx[[3]]))
expect_equal(ca_split[[5]]$estimates, lapply(ca_dat$estimates, function(l, idx) return(l[idx, ]), idx= split_idx[[5]]))
expect_equal(ca_split[[6]]$standard_error,
lapply(ca_dat$standard_error, function(l, idx) return(l[idx, ]), idx= split_idx[[6]]))
}) |
plotFluxPred<-function(eList, fluxUnit = 3, fluxMax = NA,
printTitle = TRUE, oneToOneLine=TRUE, customPar=FALSE,col="black", lwd=1,
cex=0.8, cex.axis=1.1,cex.main=1.1,
tinyPlot=FALSE, usgsStyle=FALSE,logScale=FALSE,randomCensored = FALSE,...){
localINFO <- getInfo(eList)
localSample <- getSample(eList)
if(!all((c("SE","yHat") %in% names(eList$Sample)))){
stop("This function requires running modelEstimation on eList")
}
if(sum(c("paStart","paLong") %in% names(localINFO)) == 2){
paLong <- localINFO$paLong
paStart <- localINFO$paStart
} else {
paLong <- 12
paStart <- 10
}
possibleGoodUnits <- c("mg/l","mg/l as N", "mg/l as NO2", "mg/L",
"mg/l as NO3","mg/l as P","mg/l as PO3","mg/l as PO4","mg/l as CaCO3",
"mg/l as Na","mg/l as H","mg/l as S","mg/l NH4" )
allCaps <- toupper(possibleGoodUnits)
localUnits <- toupper(localINFO$param.units)
if(!(localUnits %in% allCaps)){
warning("Expected concentration units are mg/l, \nThe INFO dataframe indicates:",localINFO$param.units,
"\nFlux calculations will be wrong if units are not consistent")
}
localSample <- if(paLong == 12) localSample else selectDays(localSample,paLong,paStart)
title2<-if(paLong==12) "" else setSeasonLabelByUser(paStartInput=paStart,paLongInput=paLong)
if (is.numeric(fluxUnit)){
fluxUnit <- fluxConst[shortCode=fluxUnit][[1]]
} else if (is.character(fluxUnit)){
fluxUnit <- fluxConst[fluxUnit][[1]]
}
fluxFactor <- fluxUnit@unitFactor*86.40
x<-localSample$ConcHat*localSample$Q*fluxFactor
Uncen<-localSample$Uncen
if (tinyPlot) {
xLab <- fluxUnit@unitEstimateTiny
yLab <- substitute(a ~ b, list(a="Obs.",b= fluxUnit@unitExpressTiny[[1]]))
} else {
if(usgsStyle){
xLab <- paste("Estimated", tolower(fluxUnit@unitUSGS))
yLab <- paste("Observed", tolower(fluxUnit@unitUSGS))
} else {
xLab <- substitute(a ~ b, list(a = "Estimated" ,
b = fluxUnit@unitEstimate[[1]]))
yLab <- substitute(a ~ b, list(a ="Observed",
b = fluxUnit@unitEstimate[[1]]))
}
}
if(logScale){
logText <- "xy"
minX <- NA
minY <- NA
} else {
logText <- ""
minX <- 0
minY <- 0
}
plotTitle<-if(printTitle) paste(localINFO$shortName,"\n",localINFO$paramShortName,"\n","Observed vs Estimated Flux") else ""
xInfo <- generalAxis(x=x, minVal=minX, maxVal=NA, logScale=logScale, tinyPlot=tinyPlot,padPercent=5)
if(!randomCensored){
yLow<-localSample$ConcLow*localSample$Q*fluxFactor
yHigh<-localSample$ConcHigh*localSample$Q*fluxFactor
yInfo <- generalAxis(x=yHigh, minVal=minY, maxVal=fluxMax, logScale=logScale, tinyPlot=tinyPlot,padPercent=5)
genericEGRETDotPlot(x=x, y=yHigh,
xTicks=xInfo$ticks, yTicks=yInfo$ticks,
xlim=c(xInfo$bottom,xInfo$top), ylim=c(yInfo$bottom,yInfo$top),
xlab=xLab, ylab=yLab,log=logText, customPar=customPar,
plotTitle=plotTitle,oneToOneLine=oneToOneLine, cex=cex,col=col,
tinyPlot=tinyPlot,cex.axis=cex.axis,cex.main=cex.main,...
)
censoredSegments(yBottom=yInfo$bottom, yLow=yLow, yHigh=yHigh, x=x, Uncen=Uncen,col=col,lwd=lwd)
} else {
if(!("rObserved" %in% names(localSample))){
eList <- makeAugmentedSample(eList)
localSample <- eList$Sample
}
yLow<-localSample$rObserved*localSample$Q*fluxFactor
yHigh<-localSample$rObserved*localSample$Q*fluxFactor
yInfo <- generalAxis(x=yHigh, minVal=minY, maxVal=fluxMax, logScale=logScale, tinyPlot=tinyPlot,padPercent=5)
genericEGRETDotPlot(x=x[Uncen == 1], y=yHigh[Uncen == 1],
xTicks=xInfo$ticks, yTicks=yInfo$ticks,
xlim=c(xInfo$bottom,xInfo$top), ylim=c(yInfo$bottom,yInfo$top),
xlab=xLab, ylab=yLab,log=logText, customPar=customPar,
plotTitle=plotTitle,oneToOneLine=oneToOneLine, cex=cex,col=col,
tinyPlot=tinyPlot,cex.axis=cex.axis,cex.main=cex.main,...
)
points(x=x[Uncen == 0], y=yHigh[Uncen == 0], pch=1,cex=cex,col=col)
}
if (!tinyPlot) mtext(title2,side=3,line=-1.5)
} |
handeval <-
function(num1,suit1){
a1 = strflsh1(num1,suit1)
if(a1>0.5) return(8000000+a1)
a1 = four1(num1)
if(a1>0.5) return(7000000+a1)
a1 = full1(num1)
if(a1>0.5) return(6000000+a1)
a1 = flush1(num1,suit1)
if(a1>0.5) return(5000000+a1)
a1 = straight1(num1)
if(a1>0.5) return(4000000+a1)
a1 = trip1(num1)
if(a1>0.5) return(3000000+a1)
a1 = twopair1(num1)
if(a1>0.5) return(2000000+a1)
a1 = onepair1(num1)
if(a1>0.5) return(1000000+a1)
a1 = nothing1(num1)
return(a1)
} |
test_that("wkt_draw_* works", {
x <- "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))"
expect_identical(wkt_plot_new(x, main = "wkt_draw_*()"), x)
expect_identical(wkt_draw_polypath(x, col = "grey90"), x)
expect_identical(wkt_draw_lines(x, col = "red"), x)
expect_identical(wkt_draw_points(x, pch = 16), x)
})
test_that("wkb_draw_* works", {
x <- wkt_translate_wkb("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))")
expect_identical(wkb_plot_new(x, main = "wkb_draw_*()"), x)
expect_identical(wkb_draw_polypath(x, col = "grey90"), x)
expect_identical(wkb_draw_lines(x, col = "red"), x)
expect_identical(wkb_draw_points(x, pch = 16), x)
}) |
snowdepth<-function(element='SD',maxseq=20,blocksizeround=20,blockmanymonth=20,blockmanyyear=200,large=5000,exclude=0,inisia=FALSE){
blend <- getOption("blend")
homefolder <- getOption("homefolder")
if(inisia){inithome()}
tx<-lister(element)
ene<-length(tx)
if(ene==0){return()}
for(i in 1:ene){
name<-paste(homefolder,'raw/',tx[i],sep='')
print(paste(name,i,'of',ene),quote=FALSE)
x<-readecad(input=name) ; print(paste(Sys.time(),'Ended readecad'),quote=FALSE)
if(!'STAID' %in% colnames(x) & ncol(x)==4){x<-cbind(STAID=as.numeric(substring(tx[i],9,14)),x)}
x<-x[,1:4];colnames(x)<-c('STAID','SOUID','date','value')
bad<-duplas(x$date);x$dupli<-0;if(length(bad)!=0){x$dupli[bad]<-1} ; print(paste(Sys.time(),'Ended duplas'),quote=FALSE)
bad<-weirddate(x[,3:4]);x$weirddate<-0;if(length(bad)!=0){x$weirddate[bad]<-1}; print(paste(Sys.time(),'Ended weirddate'),quote=FALSE)
bad<-toomany(x[,3:4],blockmanymonth,1,exclude=0);x$toomanymonth<-0;if(length(bad)!=0){x$toomany[bad]<-1}; print(paste(Sys.time(),'Ended toomany, month'),quote=FALSE)
bad<-toomany(x[,3:4],blockmanyyear,2,exclude=0);x$toomanyyear<-0;if(length(bad)!=0){x$toomany[bad]<-1}; print(paste(Sys.time(),'Ended toomany, year'),quote=FALSE)
bad<-roundprecip(x[,3:4],blocksizeround,exclude =0);x$rounding<-0;if(length(bad)!=0){x$rounding[bad]<-1}; print(paste(Sys.time(),'Ended roundsnow'),quote=FALSE)
bad<-physics(x$value,large,1);x$large<-0;if(length(bad)!=0){x$large[bad]<-1}; print(paste(Sys.time(),'Ended physics, large'),quote=FALSE)
bad<-physics(x$value,0,3);x$small<-0;if(length(bad)!=0){x$small[bad]<-1}; print(paste(Sys.time(),'Ended physics, small'),quote=FALSE)
bad<-flat(x$value,maxseq,exclude=0);x$flat<-0;if(length(bad)!=0){x$flat[bad]<-1}; print(paste(Sys.time(),'Ended flat for values'),quote=FALSE)
consolidator(tx[i],x)
}
} |
if (x) {1 + 1 + +1} else {3}
test_that("x",
{
my_test(call)
})
a =3
data_frame(a = 3)
a <- function(x) x + 1;b;c
a %>%
b %>%
c |
"_PACKAGE"
NULL
utils::globalVariables(c("id", "r", "n")) |
library(tidyverse)
library(wesanderson)
s <- round(runif(1, 0, 100000))
set.seed(s)
n = 10000
pnts <- data.frame(r = 1:n, x = rep(0, n), y = rep(0, n), a = rep(0, n))
for (i in 2:n) {
l = rnorm(1, 3, 1)
b = runif(1, 0, 30) * pi / 180
c = -runif(1, 60, 120) * pi / 180
a = sample(c(b, c), 1)
pnts$a[i] <- pnts$a[i-1] + a
pnts$x[i] <- pnts$x[i-1] + l * cos(pnts$a[i])
pnts$y[i] <- pnts$y[i-1] + l * sin(pnts$a[i])
}
pal = wes_palette("Zissou1", 9, type = "continuous")
ggplot(pnts) +
geom_path(aes(x, y, color = factor(r %% 9)), size = 0.2) +
scale_color_manual(values = pal) +
coord_fixed(expand = FALSE) +
xlim(-150, 150) +
ylim(-150, 150) +
theme_void() +
theme(
legend.position = "none",
plot.background = element_rect(fill = "grey95", color = NA)
)
ggsave(here::here("genuary", "2021", "2021-17", paste0("2021-17-", s, ".png")), dpi = 320, width = 7, height = 7) |
generate.subsamples <-
function(number.of.occurrences, fold, loocv.limit){
if (number.of.occurrences < loocv.limit){
subsamples <- matrix(0,number.of.occurrences, number.of.occurrences-1)
for (i in 1:number.of.occurrences){
if ((i > 1)&&(i < number.of.occurrences)){
subsamples[i,] <- c(1:(i-1),(i+1):number.of.occurrences)
}
if (i==1){
subsamples[i,] <- (i+1):number.of.occurrences
}
if (i == number.of.occurrences){
subsamples[i,] <- 1:(number.of.occurrences-1)
}
}
} else {
members <- 1:number.of.occurrences
number.of.members <- ceiling(number.of.occurrences/fold)
groups <- matrix(0, fold, number.of.members)
for (i in 1:fold){
for (j in 1:number.of.members){
if (length(members)==0){
break
}
chosen <- round(runif(1,0,length(members)))
if (chosen == 0){
chosen <- length(members)
}
groups[i,j] <- members[chosen]
members <- members[which(members != members[chosen])]
}
groups[i,] <- sort(groups[i,])
}
if (length(which(groups[fold,]!=0))==0){
groups <- groups[1:(fold-1),]
}
subsamples <- matrix(0, dim(groups)[1], (dim(groups)[1]-1)*number.of.members)
for (i in 1:dim(groups)[1]){
subsample <- c()
for (j in 1:dim(groups)[1]){
if (j != i){
subsample <- c(subsample, groups[j,])
}
}
subsamples[i,] <- sort(subsample)
}
}
return(subsamples)
} |
context("overflow()")
test_that("adds class", {
div() %>%
overflow("auto") %>%
expect_s3_class("shiny.tag") %>%
expect_html_class("cas-overflow-auto")
div(.style %>% overflow("hidden")) %>%
expect_s3_class("shiny.tag") %>%
expect_html_class("cas-overflow-hidden")
})
test_that("argument scroll shortcuts", {
div() %>%
overflow(FALSE) %>%
expect_html_class("cas-overflow-hidden")
div() %>%
overflow(TRUE) %>%
expect_html_class("cas-overflow-scroll")
}) |
NULL
mask_non_DE_genes_basic <- function(infercnv_obj,
p_val_thresh = 0.05,
test.use="wilcoxon",
center_val=mean([email protected]),
require_DE_all_normals="any"
) {
tumor_groupings = infercnv_obj@observation_grouped_cell_indices
all_DE_results = get_DE_genes_basic(infercnv_obj,
p_val_thresh=p_val_thresh,
test.use=test.use)
infercnv_obj <- .mask_DE_genes(infercnv_obj,
all_DE_results=all_DE_results,
mask_val=center_val,
require_DE_all_normals=require_DE_all_normals)
return(infercnv_obj)
}
.mask_DE_genes <- function(infercnv_obj,
all_DE_results,
mask_val,
require_DE_all_normals,
min_cluster_size_mask=5) {
all_DE_genes_matrix = matrix(data=0, nrow=nrow([email protected]),
ncol=ncol([email protected]),
dimnames = list(rownames([email protected]),
colnames([email protected]) ) )
num_normal_types = length(names(infercnv_obj@reference_grouped_cell_indices))
all_DE_genes_matrix[, unlist(infercnv_obj@reference_grouped_cell_indices)] = num_normal_types
for (DE_results in all_DE_results) {
if (length(DE_results$tumor_indices) < min_cluster_size_mask) {
all_DE_genes_matrix[, DE_results$tumor_indices] = num_normal_types
}
}
for (DE_results in all_DE_results) {
genes = DE_results$de_genes
gene_idx = rownames(all_DE_genes_matrix) %in% genes
cell_idx = DE_results$tumor_indices
if (length(cell_idx) >= min_cluster_size_mask) {
all_DE_genes_matrix[gene_idx, cell_idx] = all_DE_genes_matrix[gene_idx, cell_idx] + 1
}
}
if (require_DE_all_normals == "all") {
[email protected][ all_DE_genes_matrix != num_normal_types ] = mask_val
} else if ( require_DE_all_normals == "most") {
[email protected][ all_DE_genes_matrix < num_normal_types/2 ] = mask_val
} else if ( require_DE_all_normals == "any") {
[email protected][ all_DE_genes_matrix == 0 ] = mask_val
} else {
stop(sprintf("Error, not recognizing require_DE_all_normals=%s", require_DE_all_normals))
}
return(infercnv_obj)
}
get_DE_genes_basic <- function(infercnv_obj,
p_val_thresh = 0.05,
test.use="wilcoxon"
) {
all_DE_results = list()
statfxns = list()
statfxns[[ "t" ]] <- function(x, idx1, idx2) {
vals1 = x[idx1]
vals2 = x[idx2]
res = try(t.test(vals1, vals2), silent=TRUE)
if (is(res, "try-error")) return(NA) else return(res$p.value)
}
statfxns[[ "perm" ]] <- function(x, idx1, idx2) {
vals1 = x[idx1]
vals2 = x[idx2]
allvals = c(vals1, vals2)
facts = factor(rep(c("A","B"), c(length(vals1), length(vals2))))
perm = coin::oneway_test(allvals ~ facts)
pval = coin::pvalue(perm)
return(pval)
}
statfxns[[ "wilcoxon" ]] <- function(x, idx1, idx2) {
vals1 = x[idx1]
vals2 = x[idx2]
vals1 = vals1 + rnorm(n=length(vals1), mean=0.0001, sd=0.0001)
vals2 = vals2 + rnorm(n=length(vals2), mean=0.0001, sd=0.0001)
w = wilcox.test(vals1, vals2)
return(w$p.value)
}
statfxn = statfxns[[ test.use ]]
normal_types = names(infercnv_obj@reference_grouped_cell_indices)
tumor_groupings = infercnv_obj@observation_grouped_cell_indices
for (tumor_type in names(tumor_groupings)) {
indices = infercnv_obj@tumor_subclusters[["subclusters"]][[ tumor_type ]]
if(is.list(indices)) {
tumor_indices_list = indices
}
else {
tumor_indices_list = list(indices)
}
for (tumor_indices_name in names(tumor_indices_list)) {
tumor_indices = tumor_indices_list[[ tumor_indices_name ]]
for (normal_type in normal_types) {
flog.info(sprintf("Finding DE genes between %s and %s", tumor_indices_name, normal_type))
normal_indices = infercnv_obj@reference_grouped_cell_indices[[ normal_type ]]
pvals = apply([email protected], 1, statfxn, idx1=normal_indices, idx2=tumor_indices)
pvals = unlist(pvals)
pvals = p.adjust(pvals, method="BH")
names(pvals) = rownames([email protected])
genes = names(pvals)[pvals<p_val_thresh]
flog.info(sprintf("Found %d genes / %d total as DE", length(genes), length(pvals)))
condition_pair = paste(tumor_indices_name, normal_type, sep=",")
all_DE_results[[condition_pair]] = list(tumor_indices=tumor_indices,
normal=normal_type,
pvals=pvals,
de_genes=genes)
}
}
}
return(all_DE_results)
} |
summary.mcemGLMM <- function(object, ...) {
coef0 <- tail(object$mcemEST, n = 1)[1:ncol(object$x)]
names(coef0) <- colnames(object$mcemEST)[1:ncol(object$x)]
ran.eff0 <- colMeans(object$randeff)
var.est0 <-tail(object$mcemEST, n = 1)[-(1:ncol(object$x))]
names(var.est0) <- colnames(object$mcemEST)[-(1:ncol(object$x))]
cmat0 <- solve(object$iMatrix)
std.err0 <- sqrt(diag(cmat0))
std.err1 <- std.err0[-(1:ncol(object$x))]
std.err0 <- std.err0[1:ncol(object$x)]
zval0 <- coef0/std.err0[1:ncol(object$x)]
zval1 <- var.est0/std.err1
pval0 <- 2 * pnorm(-abs(zval0))
pval1 <- pnorm(-abs(zval1))
resultsFixed <- matrix(0, length(coef0), 4)
resultsFixed[, 1] <- coef0
resultsFixed[, 2] <- std.err0[1:ncol(object$x)]
resultsFixed[, 3] <- zval0
resultsFixed[, 4] <- round(pval0, 8)
rownames(resultsFixed) <- names(coef0)
colnames(resultsFixed) <- c("Estimate", "Std. Error", "z value", "Pr(>|z|)")
resultsVar <- matrix(0, length(var.est0), 4)
resultsVar[, 1] <- var.est0
resultsVar[, 2] <- std.err1
resultsVar[, 3] <- zval1
resultsVar[, 4] <- pval1
rownames(resultsVar) <- names(var.est0)
colnames(resultsVar) <- c("Estimate", "Std. Error", "z value", "Pr(>z)")
cat("Call:\n ")
print(object$call)
cat("\n Two sided Wald tests for fixed effects coefficients:\n\n")
print(resultsFixed)
if (object$call$family %in% c("bernoulli", "poisson")) {
cat("\n\n One sided Wald tests for variance components:\n\n")
print(resultsVar)
} else {
resultsAlpha <- matrix(resultsVar[1, 1:2], 1, 2)
colnames(resultsAlpha) <- c("Estimate", "Std. Error")
rownames(resultsAlpha) <- "alpha"
cat("\n Overdispersion parameter alpha:\n\n")
print(resultsAlpha)
resultsVar <- matrix(resultsVar[-1, ], length(names(var.est0)[-1]), 4)
rownames(resultsVar) <- names(var.est0)[-1]
colnames(resultsVar) <- c("Estimate", "Std. Error", "z value", "Pr(>z)")
cat("\n\n One sided Wald tests for variance components:\n\n")
print(resultsVar)
}
tbr <- list(coefficients = list(fixed = coef0, random = ran.eff0), var.est = var.est0, std.err = c(std.err0, std.err1), z.val = c(zval0, zval1))
invisible(tbr)
} |
PI_2 <- function(t, all_times, gamma_vec, U){
t <- c(-1,t)
time_mat <- matrix(rep(t, length(all_times)), length(all_times), length(t), byrow = T)
event_time_mat <- matrix(rep(all_times, length(t)), length(all_times), length(t))
indexes <- matrix(rep(1:length(all_times), length(t)), length(all_times), length(t))*(event_time_mat >= time_mat)
l <- ncol(as.matrix(U))
simplified_mat <- matrix(U[indexes, rep(1:l, l)]*U[indexes, rep(1:l, rep(l,l))], ncol = l^2)
almost_res <- apply(as.vector(exp(as.matrix(U[indexes, ])%*%gamma_vec))*(simplified_mat), 2, cumsum)[cumsum(colSums(event_time_mat >= time_mat)), ]
almost_res <- as.matrix(almost_res, ncol = l^2)
res <- almost_res - rbind(0, as.matrix(almost_res[-dim(almost_res)[1], , drop = F]))
return(matrix(res[-1,], ncol = l^2))
} |
load(file = "helper_data.rda")
dfSAV <- import_spss(file = "helper_spss_missings.sav")
test_that("Drop missing labels from meta", {
expect_equal(drop_missing_labels(df1$labels[df1$labels$varName == "ID1", ]), df1$labels[df1$labels$varName == "ID1", ])
out <- dfSAV$labels[3, ]
row.names(out) <- NULL
expect_equal(drop_missing_labels(dfSAV$labels[dfSAV$labels$varName == "VAR1", ]), out)
expect_equal(drop_missing_labels(dfSAV$labels[dfSAV$labels$varName == "VAR3", ]),
data.frame(varName = "VAR3", varLabel = "Variable 3", format = "F8.2", display_width = NA_real_, labeled = "no", value = NA_real_, valLabel = NA_character_, missings = NA_character_, stringsAsFactors = FALSE))
})
test_that("Transfer meta information from one GADSdat to another", {
dat2 <- import_DF(dfSAV$dat)
dat3 <- reuseMeta(dat2, varName = "VAR1", dfSAV)
dat3 <- reuseMeta(dat3, varName = "VAR2", dfSAV)
dat3 <- reuseMeta(dat3, varName = "VAR3", dfSAV)
expect_equal(dfSAV, dat3)
dat4 <- changeVarNames(dat2, oldNames = "VAR1", newNames = "v1")
dat5 <- reuseMeta(dat4, varName = "v1", dfSAV, other_varName = "VAR1")
expect_silent(check_GADSdat(dat5))
})
test_that("Use reuseMeta for combining value labels, including adapting meta data on variable level", {
df <- dfSAV$dat[, 2, drop = FALSE]
new_dfSAV <- updateMeta(dfSAV, df)
new_dfSAV$labels <- new_dfSAV$labels[1, ]
new_dfSAV$labels[, "value"] <- 5
test <- reuseMeta(dfSAV, varName = "VAR1", other_GADSdat = new_dfSAV, other_varName = "VAR2", addValueLabels = TRUE)
test_labels <- test$labels[test$labels$varName == "VAR1", ]
expect_equal(test_labels$value, c(-99, -96, 1, 5))
expect_equal(unique(test_labels$varLabel), "Variable 1")
test2 <- reuseMeta(dfSAV, varName = "VAR1", other_GADSdat = new_dfSAV, other_varName = "VAR2", addValueLabels = FALSE)
test2_labels <- test2$labels[test2$labels$varName == "VAR1",]
expect_equal(test2_labels$value, c(5))
expect_equal(unique(test2_labels$varLabel), "Variable 2")
})
test_that("Reuse meta with special missing treatment", {
dat2 <- import_DF(dfSAV$dat)
expect_error(reuseMeta(dat2, varName = "VAR1", dfSAV, missingLabels = "drp"), "Invalid input for argument missingLabels.")
dat3 <- reuseMeta(dat2, varName = "VAR1", dfSAV, missingLabels = "drop")
expect_equal(nrow(dat3$labels), 3)
expect_equal(dat3$labels[1, "value"], 1)
dat2 <- import_DF(dfSAV$dat)
dat3 <- reuseMeta(dfSAV, varName = "VAR1", dat2, missingLabels = "leave")
expect_equal(nrow(dat3$labels), 6)
expect_equal(dat3$labels[1, "value"], -99)
dat3 <- reuseMeta(dfSAV, varName = "VAR1", dat2, missingLabels = "only")
expect_equal(nrow(dat3$labels), 5)
expect_equal(dat3$labels[1, "value"], NA_real_)
dat5 <- reuseMeta(dat2, varName = "VAR1", dfSAV, missingLabels = "only")
expect_equal(nrow(dat5$labels), 4)
expect_equal(dat5$labels[1:2, "value"], c(-99, -96))
expect_equal(dat5$labels[1:2, "valLabel"], c("By design", "Omission"))
expect_equal(dat5$labels[1:2, "missings"], c("miss", "miss"))
})
test_that("Reuse meta adding value labels to an unlabeled variable", {
out <- reuseMeta(df1, varName = "V1", other_GADSdat = dfSAV, other_varName = "VAR1", addValueLabels = TRUE)
expect_equal(out$labels[2, "labeled"], "yes")
expect_equal(out$labels[2, "valLabel"], "By design")
})
test_that("Bugfix if only missing rows and missingLabels = leave", {
out <- reuseMeta(dfSAV, varName = "VAR3", other_GADSdat = dfSAV, other_varName = "VAR1", missingLabels = "leave")
expect_equal(nrow(out$labels), 8)
}) |
estimate_mode <- function(x) {
d <- density(x)
d$x[which.max(d$y)]
}
printSummary<-function(m){
summary<-t(apply(m,2,function(x) round(c(mean=mean(x), sd=sd(x), quantile(x, probs=c(0.025, 0.5, 0.975)),HPDLow95=HPDinterval(mcmc(cbind(reduction=x)), 0.95)[1,1],mode=estimate_mode(x),HPDHigh95=HPDinterval(mcmc(cbind(reduction=x)), 0.95)[1,2]),4)))
rownames(summary)<-colnames(m)
print(summary)
return(summary)
} |
label_pos_values <- c("hidden", "visible", "topleft")
setMethod("c", "SplitVector", function(x, ...) {
arglst = list(...)
stopifnot(all(sapply(arglst, is, "Split")))
tmp = c(unclass(x), arglst)
SplitVector(lst = tmp)
})
setGeneric("split_rows", function(lyt = NULL, spl, pos,
cmpnd_fun = AnalyzeMultiVars) standardGeneric("split_rows"))
setMethod("split_rows", "NULL", function(lyt, spl, pos, cmpnd_fun = AnalyzeMultiVars) {
.Deprecated(msg = "Initializing layouts via NULL is deprecated, please use basic_table() instead")
rl = PreDataRowLayout(SplitVector(spl))
cl = PreDataColLayout()
PreDataTableLayouts(rlayout = rl, clayout = cl)
})
setMethod("split_rows", "PreDataRowLayout",
function(lyt, spl, pos, cmpnd_fun = AnalyzeMultiVars) {
stopifnot(pos >0 && pos <= length(lyt) + 1)
tmp = if (pos <= length(lyt)) {
split_rows(lyt[[pos]], spl, pos, cmpnd_fun)
} else {
SplitVector(spl)
}
lyt[[pos]] = tmp
lyt
})
is_analysis_spl = function(spl) is(spl, "VAnalyzeSplit") || is(spl, "AnalyzeMultiVars")
setMethod("split_rows", "SplitVector",
function(lyt, spl, pos, cmpnd_fun = AnalyzeMultiVars) {
tmp = c(unclass(lyt), spl)
SplitVector(lst = tmp)
})
setMethod("split_rows", "PreDataTableLayouts",
function(lyt, spl, pos){
rlyt <- rlayout(lyt)
addtl <- FALSE
split_label <- obj_label(spl)
if(is(spl, "Split") &&
identical(label_position(spl), "topleft") &&
length(split_label) == 1 && nzchar(split_label)) {
addtl <- TRUE
label_position(spl) <- "hidden"
}
rlyt <- split_rows(rlyt, spl, pos)
rlayout(lyt) <- rlyt
if(addtl) {
lyt <- append_topleft(lyt, indent_string(split_label, .tl_indent(lyt)))
}
lyt
})
setMethod("split_rows", "ANY",
function(lyt, spl, pos) stop("nope. can't add a row split to that (", class(lyt), "). contact the maintaner.")
)
setGeneric("cmpnd_last_rowsplit", function(lyt, spl, constructor) standardGeneric("cmpnd_last_rowsplit"))
setMethod("cmpnd_last_rowsplit", "NULL", function(lyt, spl, constructor) {
stop("no existing splits to compound with. contact the maintainer")
})
setMethod("cmpnd_last_rowsplit", "PreDataRowLayout",
function(lyt, spl, constructor) {
pos = length(lyt)
tmp = cmpnd_last_rowsplit(lyt[[pos]], spl, constructor)
lyt[[pos]] = tmp
lyt
})
setMethod("cmpnd_last_rowsplit", "SplitVector",
function(lyt, spl, constructor) {
pos = length(lyt)
lst = lyt[[pos]]
tmp = if(is(lst, "CompoundSplit")) {
spl_payload(lst) = c(.uncompound(spl_payload(lst)), .uncompound(spl))
obj_name(lst) <- make_ma_name(spl = lst)
lst
} else {
constructor(.payload = list(lst, spl))
}
lyt[[pos]] = tmp
lyt
})
setMethod("cmpnd_last_rowsplit", "PreDataTableLayouts",
function(lyt, spl, constructor){
rlyt = rlayout(lyt)
rlyt = cmpnd_last_rowsplit(rlyt, spl, constructor)
rlayout(lyt)= rlyt
lyt
})
setMethod("cmpnd_last_rowsplit", "ANY",
function(lyt, spl, constructor) stop("nope. can't do cmpnd_last_rowsplit to that (", class(lyt), "). contact the maintaner.")
)
setGeneric("split_cols", function(lyt = NULL, spl, pos) standardGeneric("split_cols"))
setMethod("split_cols", "NULL", function(lyt, spl, pos) {
.Deprecated(msg = "Initializing layouts via NULL is deprecated, please use basic_table() instead")
cl = PreDataColLayout(SplitVector(spl))
rl = PreDataRowLayout()
PreDataTableLayouts(rlayout = rl, clayout = cl)
})
setMethod("split_cols", "PreDataColLayout",
function(lyt, spl, pos) {
stopifnot(pos > 0 && pos <= length(lyt) + 1)
tmp = if (pos <= length(lyt)) {
split_cols(lyt[[pos]], spl, pos)
} else {
SplitVector(spl)
}
lyt[[pos]] = tmp
lyt
})
setMethod("split_cols", "SplitVector",
function(lyt, spl, pos) {
tmp = c(lyt, spl)
SplitVector(lst = tmp)
})
setMethod("split_cols", "PreDataTableLayouts",
function(lyt, spl, pos){
rlyt = lyt@col_layout
rlyt = split_cols(rlyt, spl, pos)
lyt@col_layout = rlyt
lyt
})
setMethod("split_cols", "ANY",
function(lyt, spl, pos) stop("nope. can't add a col split to that (", class(lyt), "). contact the maintaner.")
)
setGeneric("cmpnd_last_colsplit", function(lyt, spl, constructor) standardGeneric("cmpnd_last_colsplit"))
setMethod("cmpnd_last_colsplit", "NULL", function(lyt, spl, constructor) {
stop("no existing splits to compound with. contact the maintainer")
})
setMethod("cmpnd_last_colsplit", "PreDataColLayout",
function(lyt, spl, constructor) {
pos = length(lyt)
tmp = cmpnd_last_colsplit(lyt[[pos]], spl, constructor)
lyt[[pos]] = tmp
lyt
})
setMethod("cmpnd_last_colsplit", "SplitVector",
function(lyt, spl, constructor) {
pos = length(lyt)
lst = lyt[[pos]]
tmp = if(is(lst, "CompoundSplit")) {
spl_payload(lst) = c(spl_payload(lst), spl)
lst
} else {
constructor(.payload = list(lst, spl))
}
lyt[[pos]] = tmp
lyt
})
setMethod("cmpnd_last_colsplit", "PreDataTableLayouts",
function(lyt, spl, constructor){
clyt = clayout(lyt)
clyt = cmpnd_last_colsplit(clyt, spl, constructor)
clayout(lyt)= clyt
lyt
})
setMethod("cmpnd_last_colsplit", "ANY",
function(lyt, spl, constructor) stop("nope. can't do cmpnd_last_colsplit to that (", class(lyt), "). contact the maintaner.")
)
split_cols_by = function(lyt,
var,
labels_var = var,
split_label = var,
split_fun = NULL,
format = NULL,
nested = TRUE,
child_labels = c("default", "visible", "hidden"),
extra_args = list(),
ref_group = NULL) {
if(is.null(ref_group)) {
spl = VarLevelSplit(var = var,
split_label = split_label,
labels_var = labels_var,
split_format = format,
child_labels = child_labels,
split_fun = split_fun,
extra_args = extra_args)
} else {
spl = VarLevWBaselineSplit(var = var,
ref_group = ref_group,
split_label = split_label,
split_fun = split_fun,
labels_var = labels_var,
split_format = format)
}
pos = next_cpos(lyt, nested)
split_cols(lyt, spl, pos)
}
setGeneric(".tl_indent_inner", function(lyt) standardGeneric(".tl_indent_inner"))
setMethod(".tl_indent_inner", "PreDataTableLayouts",
function(lyt) .tl_indent_inner(rlayout(lyt)))
setMethod(".tl_indent_inner", "PreDataRowLayout",
function(lyt) {
if(length(lyt) == 0 || length(lyt[[1]]) == 0)
0L
else
.tl_indent_inner(lyt[[length(lyt)]])
})
setMethod(".tl_indent_inner", "SplitVector",
function(lyt) length(lyt) - 1L)
.tl_indent <- function(lyt, nested = TRUE) {
if(!nested)
0L
else
.tl_indent_inner(lyt)
}
split_rows_by = function(lyt,
var,
labels_var = var,
split_label = var,
split_fun = NULL,
format = NULL,
nested = TRUE,
child_labels = c("default", "visible", "hidden"),
label_pos = "hidden",
indent_mod = 0L) {
label_pos <- match.arg(label_pos, label_pos_values)
child_labels = match.arg(child_labels)
spl = VarLevelSplit(var = var,
split_label = split_label,
label_pos = label_pos,
labels_var = labels_var,
split_fun = split_fun,
split_format = format,
child_labels = child_labels,
indent_mod = indent_mod)
addtl <- identical(label_pos, "topleft")
pos <- next_rpos(lyt, nested)
ret <- split_rows(lyt, spl, pos)
ret
}
split_cols_by_multivar = function(lyt,
vars,
varlabels = vars,
varnames = NULL,
nested = TRUE) {
spl = MultiVarSplit(vars = vars, split_label = "",
varlabels =varlabels,
varnames = varnames)
pos = next_cpos(lyt, nested)
split_cols(lyt, spl, pos)
}
split_rows_by_multivar = function(lyt, vars, split_label, varlabels,
format = NULL,
nested = TRUE,
child_labels = c("default", "visible", "hidden"),
indent_mod = 0L) {
child_labels = match.arg(child_labels)
spl = MultiVarSplit(vars = vars, split_label = split_label, varlabels,
split_format = format,
child_labels = child_labels,
indent_mod = indent_mod)
pos = next_rpos(lyt, nested)
split_rows(lyt, spl, pos)
}
split_cols_by_cuts = function(lyt, var, cuts,
cutlabels = NULL,
split_label = var,
nested = TRUE,
cumulative = FALSE) {
spl = VarStaticCutSplit(var, split_label, cuts, cutlabels)
if(cumulative)
spl = as(spl, "CumulativeCutSplit")
pos = next_cpos(lyt, nested)
split_cols(lyt, spl, pos)
}
split_rows_by_cuts = function(lyt, var, cuts,
cutlabels = NULL,
split_label = var,
nested = TRUE,
cumulative = FALSE,
label_pos = "hidden") {
label_pos <- match.arg(label_pos, label_pos_values)
spl = VarStaticCutSplit(var, split_label, cuts = cuts,
cutlabels = cutlabels,
label_pos = label_pos)
if(cumulative)
spl = as(spl, "CumulativeCutSplit")
pos = next_rpos(lyt, nested)
split_rows(lyt, spl, pos)
}
split_cols_by_cutfun = function(lyt, var,
cutfun = qtile_cuts,
cutlabelfun = function(x) NULL,
split_label = var,
format = NULL,
nested = TRUE,
extra_args = list(),
cumulative = FALSE
) {
spl = VarDynCutSplit(var, split_label,
cutfun = cutfun,
cutlabelfun = cutlabelfun,
split_format = format,
extra_args = extra_args,
cumulative = cumulative,
label_pos = "hidden")
pos = next_cpos(lyt, nested)
split_cols(lyt, spl, pos)
}
split_cols_by_quartiles = function(lyt, var, split_label = var,
format = NULL,
nested = TRUE,
extra_args = list(),
cumulative = FALSE) {
spl = VarDynCutSplit(var, split_label, cutfun = qtile_cuts,
cutlabelfun = function(x) c("[min, Q1]",
"(Q1, Q2]",
"(Q2, Q3]",
"(Q3, max]"),
split_format = format,
extra_args = extra_args,
cumulative = cumulative,
label_pos = "hidden")
pos = next_cpos(lyt, nested)
split_cols(lyt, spl, pos)
}
split_rows_by_quartiles = function(lyt, var, split_label = var,
format = NULL,
nested = TRUE,
child_labels = c("default", "visible", "hidden"),
extra_args = list(),
cumulative= FALSE,
indent_mod = 0L,
label_pos = "hidden") {
label_pos <- match.arg(label_pos, label_pos_values)
spl = VarDynCutSplit(var, split_label, cutfun = qtile_cuts,
cutlabelfun = function(x) c("[min, Q1]",
"(Q1, Q2]",
"(Q2, Q3]",
"(Q3, max]"),
split_format = format,
child_labels = child_labels,
extra_args = extra_args,
cumulative = cumulative,
indent_mod = indent_mod,
label_pos = label_pos)
pos = next_rpos(lyt, nested)
split_rows(lyt, spl, pos)
}
qtile_cuts = function(x) {
ret = quantile(x)
levels(ret) = c("1st qrtile",
"2nd qrtile",
"3rd qrtile",
"4th qrtile")
ret
}
split_rows_by_cutfun = function(lyt, var,
cutfun = qtile_cuts,
cutlabelfun = function(x) NULL,
split_label = var,
format = NULL,
nested = TRUE,
child_labels = c("default", "visible", "hidden"),
extra_args = list(),
cumulative = FALSE,
indent_mod = 0L,
label_pos = "hidden") {
label_pos <- match.arg(label_pos, label_pos_values)
child_labels = match.arg(child_labels)
spl = VarDynCutSplit(var, split_label, cutfun = cutfun,
cutlabelfun = cutlabelfun,
split_format = format,
child_labels = child_labels,
extra_args = extra_args,
cumulative = cumulative,
indent_mod = indent_mod,
label_pos = label_pos)
pos = next_rpos(lyt, nested)
split_rows(lyt, spl, pos)
}
NULL
analyze = function(lyt,
vars,
afun = simple_analysis,
var_labels = vars,
table_names = vars,
format = NULL,
nested = TRUE,
inclNAs = FALSE,
extra_args = list(),
show_labels = c("default", "visible", "hidden"),
indent_mod = 0L) {
show_labels = match.arg(show_labels)
subafun = substitute(afun)
if(is.name(subafun) &&
is.function(afun) &&
identical(mget(as.character(subafun),
mode = "function",
ifnotfound = list(NULL),
inherits = TRUE
)[[1]], afun)) {
defrowlab = as.character(subafun)
} else {
defrowlab = var_labels
}
spl = AnalyzeMultiVars(vars, var_labels,
afun = afun,
split_format = format,
defrowlab = defrowlab,
inclNAs = inclNAs,
extra_args = extra_args,
indent_mod = indent_mod,
child_names = table_names,
child_labels = show_labels)
if(nested &&
(is(last_rowsplit(lyt), "VAnalyzeSplit") ||
is(last_rowsplit(lyt), "AnalyzeMultiVars"))) {
cmpnd_last_rowsplit(lyt, spl, AnalyzeMultiVars)
} else {
pos = next_rpos(lyt, nested)
split_rows(lyt, spl, pos)
}
}
get_acolvar_name <- function(lyt) {
paste(c("ac", get_acolvar_vars(lyt)), collapse = "_")
}
get_acolvar_vars <- function(lyt) {
clyt <- clayout(lyt)
stopifnot(length(clyt) == 1L)
vec = clyt[[1]]
vcls = vapply(vec, class, "")
pos = which(vcls == "MultiVarSplit")
if(length(pos) > 0)
spl_payload(vec[[pos]])
else
"non_multivar"
}
analyze_colvars = function(lyt, afun,
format = NULL,
nested = TRUE,
extra_args = list(),
indent_mod = 0L,
inclNAs = FALSE) {
if(is.function(afun)) {
subafun = substitute(afun)
if(is.name(subafun) &&
is.function(afun) &&
identical(mget(as.character(subafun),
mode = "function",
ifnotfound = list(NULL),
inherits = TRUE
)[[1]], afun)) {
defrowlab = as.character(subafun)
} else {
defrowlab = ""
}
afun = lapply(get_acolvar_vars(lyt),
function(x) afun)
} else {
defrowlab = ""
}
spl = AnalyzeColVarSplit(afun = afun,
defrowlab = defrowlab,
split_format = format,
split_name = get_acolvar_name(lyt),
indent_mod = indent_mod,
extra_args = extra_args,
inclNAs = inclNAs)
pos = next_rpos(lyt, nested, for_analyze = TRUE)
split_rows(lyt, spl, pos)
}
analyze_against_ref_group = function(lyt, var = NA_character_,
afun,
label = if(is.na(var)) "" else var,
compfun = `-`,
format = NULL,
nested = TRUE,
indent_mod = 0L,
show_labels = c("default", "hidden", "visible")) {
.Defunct("analyze", msg = "use analyze with a function that takes .ref_group and .in_ref_col params instead.")
}
add_overall_col = function(lyt, label) {
spl = AllSplit(label)
split_cols(lyt,
spl,
next_cpos(lyt, FALSE))
}
setGeneric(".add_row_summary",
function(lyt,
label,
cfun,
child_labels = c("default", "visible", "hidden"),
cformat = NULL,
indent_mod = 0L,
cvar = "",
extra_args = list()) standardGeneric(".add_row_summary"))
setMethod(".add_row_summary", "PreDataTableLayouts",
function(lyt,
label,
cfun,
child_labels = c("default", "visible", "hidden"),
cformat = NULL,
indent_mod = 0L,
cvar = "",
extra_args = list()) {
child_labels = match.arg(child_labels)
tmp = .add_row_summary(rlayout(lyt), label, cfun,
child_labels = child_labels,
cformat = cformat,
indent_mod = indent_mod,
cvar = cvar,
extra_args = extra_args)
rlayout(lyt) = tmp
lyt
})
setMethod(".add_row_summary", "PreDataRowLayout",
function(lyt,
label,
cfun,
child_labels = c("default", "visible", "hidden"),
cformat = NULL,
indent_mod = 0L,
cvar = "",
extra_args = list()) {
child_labels = match.arg(child_labels)
if(length(lyt) == 0 ||
(length(lyt) == 1 && length(lyt[[1]]) == 0)) {
rt = root_spl(lyt)
rt = .add_row_summary(rt,
label,
cfun,
child_labels = child_labels,
cformat = cformat,
cvar = cvar,
extra_args = extra_args)
root_spl(lyt) = rt
} else {
ind = length(lyt)
tmp = .add_row_summary(lyt[[ind]], label, cfun,
child_labels = child_labels,
cformat = cformat,
indent_mod = indent_mod,
cvar = cvar,
extra_args = extra_args)
lyt[[ind]] = tmp
}
lyt
})
setMethod(".add_row_summary", "SplitVector",
function(lyt,
label,
cfun,
child_labels = c("default", "visible", "hidden"),
cformat = NULL,
indent_mod = 0L,
cvar = "",
extra_args = list()) {
child_labels = match.arg(child_labels)
ind = length(lyt)
if(ind == 0) stop("no split to add content rows at")
spl = lyt[[ind]]
tmp = .add_row_summary(spl,
label,
cfun,
child_labels = child_labels,
cformat = cformat,
indent_mod = indent_mod,
cvar = cvar,
extra_args = extra_args)
lyt[[ind]] = tmp
lyt
})
setMethod(".add_row_summary", "Split",
function(lyt,
label,
cfun,
child_labels = c("default", "visible", "hidden"),
cformat = NULL,
indent_mod = 0L,
cvar = "",
extra_args = list()) {
child_labels = match.arg(child_labels)
content_fun(lyt) = cfun
content_indent_mod(lyt) = indent_mod
content_var(lyt) = cvar
content_format(lyt) <- cformat
if(!identical(child_labels, "default") && !identical(child_labels, label_kids(lyt)))
label_kids(lyt) = child_labels
content_extra_args(lyt) = extra_args
lyt
})
.count_raw_constr = function(var, format, label_fstr) {
function(df, labelstr = "") {
if(grepl("%s", label_fstr, fixed = TRUE))
label <- sprintf(label_fstr, labelstr)
else
label <- label_fstr
if(is(df, "data.frame")) {
if(!is.null(var) && nzchar(var))
cnt <- sum(!is.na(df[[var]]))
else
cnt <- nrow(df)
} else {
cnt <- sum(!is.na(df))
}
ret <- rcell(cnt, format = format,
label = label)
ret
}
}
.count_wpcts_constr = function(var, format, label_fstr) {
function(df, labelstr = "", .N_col) {
if(grepl("%s", label_fstr, fixed = TRUE))
label <- sprintf(label_fstr, labelstr)
else
label <- label_fstr
if(is(df, "data.frame")) {
if(!is.null(var) && nzchar(var))
cnt <- sum(!is.na(df[[var]]))
else
cnt <- nrow(df)
} else {
cnt <- sum(!is.na(df))
}
ret <- rcell(c(cnt, cnt/.N_col),
format = format,
label = label)
ret
}
}
.validate_cfuns <- function(fun) {
if(is.list(fun))
return(unlist(lapply(fun, .validate_cfuns)))
frmls <- formals(fun)
ls_pos <- match("labelstr", names(frmls))
if(is.na(ls_pos)) {
ls_pos <- grep("lbl_{0,1}str", names(frmls))
if(length(ls_pos) == 0)
stop("Invalid content function - does not accept the required labelstr argument")
.Deprecated(old = "Use of content functions which do not accept a named 'labelstr' argument", new = "content functions which explicitly accept 'labelstr'")
names(formals(fun))[ls_pos] <- "labelstr"
}
list(fun)
}
summarize_row_groups = function(lyt,
var = "",
label_fstr = "%s",
format = "xx (xx.x%)",
cfun = NULL,
indent_mod = 0L,
extra_args = list()){
if(is.null(cfun)) {
if(length(gregexpr("xx", format)[[1]]) == 2)
cfun = .count_wpcts_constr(var, format, label_fstr)
else
cfun = .count_raw_constr(var,format, label_fstr)
}
cfun <- .validate_cfuns(cfun)
.add_row_summary(lyt,
cfun = cfun,
cformat = format,
indent_mod = indent_mod,
cvar = var,
extra_args = extra_args)
}
add_colcounts = function(lyt, format = "(N=xx)") {
if(is.null(lyt))
lyt <- PreDataTableLayouts()
disp_ccounts(lyt) <- TRUE
colcount_format(lyt) <- format
lyt
}
add_existing_table = function(lyt, tt, indent_mod = 0) {
indent_mod(tt) = indent_mod
lyt = split_rows(lyt,
tt,
next_rpos(lyt, nested = FALSE))
lyt
}
takes_coln = function(f) {
stopifnot(is(f, "function"))
forms = names(formals(f))
res = ".N_col" %in% forms
res
}
takes_totn = function(f) {
stopifnot(is(f, "function"))
forms = names(formals(f))
res = ".N_total" %in% forms
res
}
setGeneric("fix_dyncuts", function(spl, df) standardGeneric("fix_dyncuts"))
setMethod("fix_dyncuts", "Split", function(spl, df) spl)
setMethod("fix_dyncuts", "VarDynCutSplit",
function(spl, df) {
var = spl_payload(spl)
varvec = df[[var]]
cfun = spl_cutfun(spl)
cuts = cfun(varvec)
cutlabels <- spl_cutlabelfun(spl)(cuts)
if(length(cutlabels) != length(cuts) - 1 &&
!is.null(names(cuts))) {
cutlabels <- names(cuts)[-1]
}
ret = VarStaticCutSplit(var = var, split_label = obj_label(spl),
cuts = cuts, cutlabels = cutlabels)
if(spl_is_cmlcuts(spl))
ret = as(ret, "CumulativeCutSplit")
ret
})
setMethod("fix_dyncuts", "VTableTree",
function(spl, df) spl)
.fd_helper = function(spl, df) {
lst = lapply(spl, fix_dyncuts, df = df)
[email protected] = lst
spl
}
setMethod("fix_dyncuts", "PreDataRowLayout",
function(spl, df) {
ret = .fd_helper(spl, df)
ret
})
setMethod("fix_dyncuts", "PreDataColLayout",
function(spl, df) {
ret = .fd_helper(spl, df)
ret
})
setMethod("fix_dyncuts", "SplitVector",
function(spl, df) {
.fd_helper(spl, df)
})
setMethod("fix_dyncuts", "PreDataTableLayouts",
function(spl, df) {
rlayout(spl) = fix_dyncuts(rlayout(spl), df)
clayout(spl) = fix_dyncuts(clayout(spl), df)
spl
})
manual_cols = function(..., .lst = list(...)) {
if(is.null(names(.lst)))
names(.lst) = paste("colsplit", seq_along(.lst))
splvec = SplitVector(lst = mapply(ManualSplit, levels = .lst, label = names(.lst)))
ctree = splitvec_to_coltree(data.frame(), splvec=splvec, pos = TreePos())
InstantiatedColumnInfo(treelyt = ctree)
}
list_wrap_x = function(f) {
function(x,...) {
vs = as.list(f(x, ...))
ret = mapply(function(v, nm) {
rcell(v, label = nm)
},
v = vs,
nm = names(vs))
ret
}
}
list_wrap_df = function(f) {
function(df,...) {
vs = as.list(f(df,...))
ret = mapply(function(v, nm) {
rcell(v, label = nm)
},
v = vs,
nm = names(vs))
ret
}
}
basic_table <- function(title = "",
subtitles = character(),
main_footer = character(),
prov_footer = character(),
show_colcounts = FALSE) {
ret <- PreDataTableLayouts(title = title,
subtitles = subtitles,
main_footer = main_footer,
prov_footer = prov_footer)
if(show_colcounts)
ret <- add_colcounts(ret)
ret
}
append_topleft <- function(lyt, newlines) {
stopifnot(is(lyt, "PreDataTableLayouts"),
is(newlines, "character"))
lyt@top_left <- c(lyt@top_left, newlines)
lyt
} |
svc <- paws::cognitoidentityprovider() |
test_calc_warnings <- function() {
d <- data.frame(
x = 1:3,
y = 4:6
)
expect_error({
ops <- local_td(d) %.>%
project(.,
x := 1,
x := 2)
})
expect_error({
ops <- local_td(d) %.>%
project(.,
x := 1,
y := x)
})
invisible(NULL)
}
test_calc_warnings() |
.getResTypeAndMethod <- function(fam){
type <- switch(fam,
"shash" = "tnormal",
"gaulss" = "deviance",
"deviance")
method <- switch(fam,
"shash" = "tnormal",
"gaulss" = "normal",
"simul1")
return( list("type" = type, "method" = method) )
} |
cutSpace <- function(pointcloud,v1, v2=NULL, v3=NULL,normal=NULL, upper=TRUE) {
orthopro <- points2plane(pointcloud,v1=v1,v2=v2,v3=v3,normal=normal)
diff <- pointcloud-orthopro
if (is.null(normal)) {
e1 <- v2-v1
e1 <- e1/norm(e1,"2")
e2 <- v3-v1
e2 <- e2/norm(e2,"2")
normal <- crossProduct(e1,e2)
}
ins <- t(normal)%*%t(diff)
if (upper)
upside <- ins > 0
else
upside <- ins <= 0
return(upside)
}
cutMeshPlane <- function(mesh, v1, v2=NULL, v3=NULL, normal=NULL,keep.upper=TRUE) {
pointcloud <- vert2points(mesh)
upper <- cutSpace(pointcloud, v1=v1,v2=v2,v3=v3,normal=normal,upper=keep.upper)
outmesh <- list()
lremain <- length(which(upper))
if (lremain) {
if (lremain < ncol(mesh$vb))
outmesh <- rmVertex(mesh,which(upper),keep = TRUE)
else
outmesh <- mesh
} else {
warning("nothing left")
}
return(outmesh)
}
|
add_tile_suffix <- function(paths, suffix) {
if (missing(suffix)) {
for (sel_upath in names(table(paths))[table(paths)>1]) {
n_paths <- sum(paths==sel_upath)
paths[paths==sel_upath] <- sapply(seq_len(n_paths), function(i) {
gsub(
"(S2[AB][12][AC]\\_[0-9]{8}\\_[0-9]{3})\\_([0-9]{2}[A-Z]{3})\\_([^\\_\\.]+\\_[126]0\\.?[^\\_]*$)",
paste0("\\1_\\2",letters[i],"_\\3"),
sel_upath
)
})
}
paths
} else {
if (is.na(suffix)) {suffix <- ""}
gsub(
"(S2[AB][12][AC]\\_[0-9]{8}\\_[0-9]{3})\\_([0-9]{2}[A-Z]{3})\\_([^\\_\\.]+\\_[126]0\\.?[^\\_]*$)",
paste0("\\1_\\2",suffix,"_\\3"),
paths
)
}
}
remove_tile_suffix <- function(paths) {
accepted_suffixes <- "[a-z]?"
sapply(paths, function(p) {
gsub(
paste0(
"(S2[AB][12][AC]\\_[0-9]{8}\\_[0-9]{3})\\_([0-9]{2}[A-Z]{3})",
accepted_suffixes,
"\\_([^\\_\\.]+\\_[126]0\\.?[^\\_]*$)"
),
"\\1_\\2_\\3",
p
)
}, simplify = TRUE, USE.NAMES = FALSE)
}
extract_tile_suffix <- function(paths) {
accepted_suffixes <- "[a-z]?"
sapply(paths, function(p) {
gsub(
paste0(
"^.*S2[AB][12][AC]\\_[0-9]{8}\\_[0-9]{3}\\_[0-9]{2}[A-Z]{3}",
"(",accepted_suffixes,")",
"\\_[^\\_\\.]+\\_[126]0\\.?[^\\_]*$"
),
"\\1",
p
)
}, simplify = TRUE, USE.NAMES = FALSE)
} |
est_multi_poly_between <- function (S, yv = rep(1, ns), k, X = NULL, start = c("deterministic","random","external"),
link = c("global","local"), disc = FALSE, difl = FALSE, multi = 1:J, Phi = NULL, gat = NULL, De = NULL,
fort = FALSE, tol = 10^-10, maxitc = 10^4, disp = FALSE, output = FALSE, out_se = FALSE, glob = FALSE,
Zth=NULL,zth=NULL, Zbe=NULL,zbe=NULL,Zga=NULL,zga=NULL){
if (k == 1) stop("--> use est_multi_poly")
if (max(S, na.rm = TRUE) == 1 & difl) {
warning("with binary data put difl=FALSE\n")
difl = FALSE
}
link = match.arg(link)
start = match.arg(start)
J = ncol(S)
if(is.vector(multi)) multi = t(multi)
if(!is.null(Zth)){
if(is.vector(Zth)) Zth = t(Zth)
if(is.null(zth)) zth = rep(0,nrow(Zth))
constr.th = TRUE
}else{
constr.th = FALSE
}
if(!is.null(Zbe)){
if(is.vector(Zbe)) Zbe = t(Zbe)
if(is.null(zbe)) zbe = rep(0,nrow(Zbe))
constr.be = TRUE
}else{
constr.be = FALSE
}
if(!is.null(Zga)){
if(is.vector(Zga)) Zga = t(Zga)
if(is.null(zga)) zga = rep(0,nrow(Zga))
constr.ga = TRUE
}else{
constr.ga = FALSE
}
cov = !is.null(X)
if(cov){
X = as.matrix(X)
namesX = colnames(X)
if (glob) logit_cov = "g"
else logit_cov = "m"
}else logit_cov = "m"
miss = any(is.na(S))
ns = nrow(S)
if(miss) {
cat("Missing data in the dataset, units and items without responses are removed\n")
ind = which(apply(is.na(S), 1, all))
if (length(ind) > 0) {
S = S[-ind, ]
yv = yv[-ind]
if (!is.null(X)) X = as.matrix(X[-ind, ])
ind = which(apply(is.na(S), 2, all))
if (length(ind) > 0) {
S = S[, -ind]
miss = any(is.na(S))
}
}
}
if (miss){
R = 1*(!is.na(S))
S[is.na(S)] = 0
}
lv = apply(S,2,max) + 1
if(difl & max(lv)>min(lv))
stop("Option difl=TRUE not allowed in the presence of items with a different number of response categories within the same dimension")
lm = max(lv)
ns = nrow(S)
J = ncol(S)
n = sum(yv)
if (cov) {
ncov = ncol(X)
out = aggr_data(X, fort = fort)
Xdis = as.matrix(out$data_dis)
Xlabel = out$label
Xndis = max(out$label)
if (glob) {
XXdis = array(0, c(k - 1, k - 1 + ncov, Xndis))
for (i in 1:Xndis) XXdis[, , i] = cbind(diag(k - 1), rep(1, k - 1) %o% Xdis[i, ])
}else{
XXdis = array(0, c(k - 1, (k - 1) * (ncov + 1),Xndis))
if (k == 2) II = 1
else II = diag(k - 1)
for (i in 1:Xndis) XXdis[, , i] = II %x% t(c(1,Xdis[i, ]))
}
}else{
ncov = 0
XXdis = array(diag(k - 1), c(k - 1, k - 1, 1))
Xlabel = rep(1, ns)
}
if(link=="global") ltype = "g"
else if (link == "local") ltype = "l"
items = sort(as.vector(multi))
if(any(items == 0)) items = items[items > 0]
Jitems = length(items)
rm = nrow(multi)
fv = multi[, 1]
fve = NULL
count = 0
for(j in 1:J){
if (j %in% fv) fve = c(fve, count + 1)
count = count + lv[j] - 1
}
indgat = setdiff(items,fv)
if(constr.th){
if(ncol(Zth)==0) indtht = NULL
else indtht = 1:ncol(Zth)
}else indtht = 1:(k*rm)
indth = 1:(k*rm)
if(constr.be){
if(ncol(Zbe)==0) indbet = NULL
else{
if(is.null(indth)) tmp = 0
else tmp = max(indth)
indbet = tmp+(1:ncol(Zbe))
}
}else{
if(is.null(indth)) tmp = 0
else tmp = max(indth)
if(difl) indbet = tmp+(1:(J-rm+lm-2))
else indbet = tmp+1:(sum(lv - 1)-rm)
}
indbe = k*rm + (1:sum(lv - 1))
abils = rep(0, J)
if (rm == 1) abils[multi] = 1
else{
for(h in 1:rm){
ind = multi[h, ]
ind = ind[ind > 0]
abils[ind] = h
}
}
ZZ = array(NA, c(lm - 1, k * rm + sum(lv - 1), J * k))
cont = 0
refitem = matrix(0, J * k, 1)
for (c in 1:k){
u1 = matrix(0, 1, k)
u1[c] = 1
for(j in 1:J){
u2 = matrix(0, 1, rm)
u2[abils[j]] = 1
v = matrix(0, 1, J)
v[j] = 1
cont = cont + 1
Te = matrix(0, lv[j] - 1, sum(lv - 1))
if (j == 1) Te[, 1:(lv[j] - 1)] = diag(lv[j] - 1)
else Te[, sum(lv[1:(j - 1)] - 1) + (1:(lv[j] - 1))] = diag(lv[j] - 1)
ZZ[1:(lv[j] - 1), , cont] = cbind(rep(1, lv[j] - 1) %*% (u1 %x% u2), -Te)
refitem[cont] = j
}
}
ZZ0 = ZZ
if (glob) {
II = diag(k - 1)
II = cbind(0, II) - cbind(II, 0)
if (rm > 1) II = II %x% matrix(c(1, rep(0, rm - 1)), 1, rm)
Dis = cbind(II, matrix(0, k - 1, dim(ZZ)[2] - (k * rm)))
}else Dis = NULL
if(!constr.th){
Zth = diag(k*rm); zth = rep(0,k*rm)
}
if(!constr.be){
if(difl){
if(lm-1==2) Tmp = matrix(c(0,1),2,1)
else Tmp = diag(lm-1)[,-1]
Zbe = cbind(diag(J)[,-fv]%x%matrix(1,lm-1,1),matrix(1,J,1)%x%Tmp)
}else{
Zbe = diag(sum(lv - 1))[,-fve]
}
zbe = rep(0,sum(lv - 1))
}
Zpar = blkdiag(Zth,Zbe)
zpar = c(zth,zbe)
if(!constr.ga){
Zga = diag(Jitems)[,-which(items%in%fv)]
zga = rep(0,Jitems); zga[which(items%in%fv)] = 1
}
if(start=="deterministic") {
if(cov){
de = NULL
Piv = matrix(1/k, ns, k)
piv = NULL
}else{
de = NULL
piv = rep(1, k)/k
}
if (k == 1) grid = 0
else grid = seq(-k, k, length.out = k)
Phi = array(NA, c(lm, J, k))
for (j in 1:J) {
dist = rep(0, lv[j])
for (y in 0:(lv[j] - 1)) dist[y + 1] = (sum(yv[S[,j] == y]) + 0.5)/n
out = matr_glob(lv[j])
Co = out$Co
Ma = out$Ma
eta = Co %*% log(Ma %*% dist)
count = 0
for (c in 1:k){
count = count + 1
Phi[1:lv[j], j, count] = inv_glob(eta + grid[c])$p
}
}
}
if(start=="random") {
if (cov) {
if (glob){
de = NULL
Piv = matrix(runif(ns * k), ns, k)
Piv = Piv * (1/rowSums(Piv))
piv = NULL
}else {
de = rnorm((k - 1) * (ncov + 1))/rep(c(1, apply(X, 2, sd)), (k - 1))
if (k > 1) Piv = prob_multi_glob(XXdis, logit_cov, de, Xlabel)$P
piv = NULL
}
}else {
de = NULL
piv = runif(k)
piv = piv/sum(piv)
}
Phi = array(runif(lm * J * k), c(lm, J, k))
for (c in 1:k) for (j in 1:J) {
Phi[1:lv[j], j, c] = Phi[1:lv[j], j, c]/sum(Phi[1:lv[j], j, c])
if (lv[j] < lm) Phi[(lv[j] + 1):lm, j, c] = NA
}
if(glob){
if(runif(1) > 0.5) for (j in 1:J){
mPhi = (0:(lv[j] - 1)) %*% Phi[1:lv[j], j,]
ind = order(mPhi)
Phi[, j, ] = Phi[, j, ind]
}
}
}
if(start=="external"){
de = as.vector(De)
if(cov){
Piv = prob_multi_glob(XXdis, logit_cov, de, Xlabel)$P
piv = NULL
}else{
piv = c(1,exp(de))
piv = piv/sum(piv)
}
}
if (start=="deterministic" || start=="random" || (start=="external" & is.null(gat))){
if(is.null(Zga)) gat = rep(1,0)
else gat = rep(1, ncol(Zga))
}
ga = Zga%*%gat+zga
gac = rep(0,J); gac[items] = ga
Psi = matrix(1, ns, k)
if(miss) for (j in 1:J) for (c in 1:k) Psi[, c] = Psi[, c] * (Phi[S[, j] + 1, j, c] * R[, j] + (1 - R[, j]))
else for (j in 1:J) for (c in 1:k) Psi[, c] = Psi[,c] * Phi[S[, j] + 1, j, c]
if(cov){
if (start=="external") {
if (k > 1) Piv = prob_multi_glob(XXdis, logit_cov, de, Xlabel)$P
}
}else Piv = rep(1, ns) %o% piv
if (k == 1) Pj = Psi
else Pj = Psi * Piv
pm = rowSums(Pj)
lk = sum(yv * log(pm))
cat("*-------------------------------------------------------------------------------*\n")
cat(c("Model with multidimensional structure\n"))
names1 = NULL
for (j in 1:rm) names1 = c(names1, paste("Dimension", j))
rownames(multi) = names1
print(multi)
cat("\n")
cat(c("Number of classes = ", k, "\n"))
cat(c("Link of type = ", link, "\n"))
cat(c("Discrimination index = ", disc, "\n"))
cat(c("Constraints on the difficulty =", difl, "\n"))
cat(c("Type of initialization = ", start, "\n"))
cat("*-------------------------------------------------------------------------------*\n\n")
if (disp) {
if(!disc || length(ga) == 0){
cat("------------|-------------|-------------|-------------|-------------|-------------|\n")
cat(" iteration | lk | lk-lko | dis | min(par) | max(par) |\n")
cat("------------|-------------|-------------|-------------|-------------|-------------|\n")
}
if (disc) {
cat("------------|-------------|-------------|-------------|-------------|-------------|-------------|-------------|\n")
cat(" iteration | lk | lk-lko | dis | min(ga) | max(ga) | min(par) | max(par) |\n")
cat("------------|-------------|-------------|-------------|-------------|-------------|-------------|-------------|\n")
}
cat(sprintf("%11g", c(0, lk)), "\n", sep = " | ")
}
it = 0
lko = lk - 10^10
dis = 0
part = par = dga = lkv = NULL
while (((abs(lk - lko)/abs(lko) > tol) && it < maxitc) || it < 2){
it = it + 1
paro = par
gao = ga
pivo = piv
deo = de
lko = lk
V = ((yv/pm) %o% rep(1, k)) * Piv * Psi
sV = colSums(V)
YY = matrix(NA, J * k, lm)
count = 0
for (c in 1:k) for (j in 1:J) {
count = count + 1
for (y in 1:lv[j]) {
ind = (S[, j] == (y - 1))
if (miss)
YY[count, y] = sum(V[ind, c] * R[ind, j])
else YY[count, y] = sum(V[ind, c])
}
}
if(disc){
if(it > 1 & rm < J){
ZZ = array(NA, c(lm - 1, J, J * k))
count = 0
for(c in 1:k) for(j in 1:J){
count = count + 1
ZZ[1:(lv[j] - 1), , count] = 0
ZZ[1:(lv[j] - 1), j, count] = ZZ0[1:(lv[j] - 1), 1:(k * rm), count] %*% par[1:(k*rm)]
}
ZZ = ZZ[, items, ]
ind = k * rm + 1:sum(lv - 1)
ZZInt = array(NA, c(lm - 1, J * k))
count = 0
for (c in 1:k) for (j in 1:J) {
count = count + 1
ZZInt[1:(lv[j] - 1), count] = ZZ0[1:(lv[j] - 1), ind, count] %*% par[ind]
ZZ0[1:(lv[j] - 1), ind, count] %*% par[ind]
}
if(constr.ga || constr.th){
gat = est_multi_glob_genZ(YY, ZZ, ltype, de = gat, Int = ZZInt,Z=Zga,z=zga)$de
ga = Zga%*%gat+zga; gac = rep(1,J); gac[items] = ga
}else{
gac[items] = est_multi_glob_genZ(YY,ZZ, ltype, de = gac[items], Int = ZZInt)$be
for(j in 1:rm){
tmp = gac[multi[j,1]]
gac[multi[j,]] = gac[multi[j,]]/tmp
ind = seq(j,k*rm,rm)
part[ind] = part[ind]*tmp
}
ga = gac[items]; gat = gac[indgat]
}
par = Zpar%*%part+zpar
}
ZZ = ZZ0
for (j in 1:J) {
ind = (refitem == j)
ZZ[, 1:(k * rm), ind] = ZZ[, 1:(k * rm), ind] * gac[j]
}
}
if(start=="external" & it==1) maxit = 250 else maxit = 10
out = est_multi_glob_genZ(YY,ZZ,ltype,de=part,Z=Zpar,z=zpar,Dis=Dis,maxit=maxit)
part = out$de; par = Zpar%*%part+zpar
P = out$P
Phi = array(t(P), c(lm, J, k))
if (cov) {
if (k > 1) {
out = est_multi_glob(V, XXdis, logit_cov, Xlabel, de)
de = out$be
Pdis = out$Pdis
Piv = out$P
}
}else {
piv = sV/n
Piv = rep(1, ns) %o% piv
}
Psi = matrix(1, ns, k)
if (miss) for (j in 1:J) for (c in 1:k) Psi[, c] = Psi[,c] * (Phi[S[, j] + 1, j, c] * R[, j] + (1 - R[,j]))
else for (j in 1:J) for (c in 1:k) Psi[, c] = Psi[,c] * Phi[S[, j] + 1, j, c]
if (k == 1) Pj = Psi
else Pj = Psi * Piv
pm = rowSums(Pj)
lk = sum(yv * log(pm))
if (it > 1) dis = max(c(abs(par - paro), abs(ga - ga), abs(piv - pivo)))
if (disp) {
if (it/10 == floor(it/10)) {
if (!disc || length(ga) == 0 ) cat(sprintf("%11g", c(it, lk, lk - lko, dis, min(par), max(par))), "\n", sep = " | ")
if (disc) cat(sprintf("%11g", c(it, lk, lk - lko, dis, min(ga), max(ga), min(par), max(par))), "\n", sep = " | ")
}
}
lkv = c(lkv, lk)
}
if (disp) {
if (it/10 > floor(it/10)) {
if (!disc || length(ga) == 0) cat(sprintf("%11g", c(it, lk, lk - lko, dis, min(par), max(par))), "\n", sep = " | ")
if (disc) cat(sprintf("%11g", c(it, lk, lk - lko, dis, min(ga), max(ga), min(par), max(par))), "\n", sep = " | ")
}
if (!disc || length(ga) == 0) cat("------------|-------------|-------------|-------------|-------------|-------------|\n")
if (disc) cat("------------|-------------|-------------|-------------|-------------|-------------|-------------|-------------|\n")
}
np = length(part)
if (disc==1) np=np+length(gat)
if (cov) {
if (glob) np = np + k - 1 + ncov
else np = np + (k-1) * (ncov + 1)
}else np = np + k - 1
aic = -2 * lk + 2 * np
bic = -2 * lk + np * log(n)
tht = part[indtht]
th = par[indth]
bet = part[indbet]
be = par[indbe]
if (difl){
bec1 = rep(0, J)
bec1[(1:J)[-fv]] = bet[1:(J - rm)]
bec2 = rep(0, lm - 1)
bec2[2:(lm - 1)] = bet[J - rm + (1:(lm - 2))]
Bec = list(difficulties = bec1, cutoffs = bec2)
}else{
Bec = matrix(NA, J, lm - 1)
count = 0
for (j in 1:J) {
Bec[j, (1:lv[j] - 1)] = be[count + (1:(lv[j] - 1))]
count = count + lv[j] - 1
}
dimnames(Bec) = list(item = 1:J, cutoff = 1:(lm-1))
}
gac[setdiff(1:J,items)] = NA
Th = matrix(th, rm, k)
dimnames(Th) = list(dimension = 1:rm,class=1:k)
Pp = ((1/pm) %o% rep(1, k)) * Piv * Psi
ent = -sum(V * log(pmax(Pp, 10^-100)))
dimnames(Phi) = list(category = 0:(lm - 1), item = 1:J, class = 1:k)
if (cov) {
if (glob) {
if (k == 1) De = NULL
else {
De = matrix(de, ncov + k - 1, 1)
names_cutoff = paste("cutoff", 1:(k - 1), sep = "")
if (is.null(namesX)) namesX1 = c(names_cutoff, paste("X", 1:ncov, sep = ""))
else namesX1 = c(names_cutoff, namesX)
rownames(De) = namesX
}
}else {
if (is.null(namesX)) namesX = c("intercept", paste("X", 1:ncov, sep = ""))
else namesX = c("intercept", namesX)
if (k == 1) De = NULL
else {
De = matrix(de, ncov + 1, k - 1)
dimnames(De) = list(namesX, logit = 2:k)
}
}
piv = drop(t(Piv)%*%yv/n)
}else{
de = log(piv[-1]/piv[1])
De = t(de); dimnames(De) = list("intercept",logit = 2:k)
}
if (out_se) {
lde = length(de)
lpar = length(par); lpart = length(part)
lga = 0
part_comp = c(de, part)
if (disc) {
lga = length(ga); lgat = length(gat)
part_comp = c(part_comp, gat)
}
if (disp) {
cat("computation of derivatives\n")
cat(length(part_comp), "parameters\n")
}
out = lk_obs_score_between(part_comp, lde, lpart, lgat, S, R, yv, k, rm, lv, J, fv, disc, glob,
refitem, miss, ltype, XXdis, Xlabel, ZZ0, fort, Zpar, zpar,Zga,zga,items)
scn = rep(0, length(part_comp))
Jn = NULL
for (j in 1:length(part_comp)) {
part_comp1 = part_comp
part_comp1[j] = part_comp1[j] + 10^-6
out1 = lk_obs_score_between(part_comp1, lde, lpart, lgat, S, R, yv, k, rm, lv, J, fv, disc, glob,
refitem, miss, ltype, XXdis, Xlabel, ZZ0, fort, Zpar, zpar, Zga,zga,items)
scn[j] = (out1$lk - lk) * 10^6
Jn = cbind(Jn, (out1$sc - out$sc) * 10^6)
if (disp){
if (j/10 > floor(j/10)) cat(".")
else cat(round(j/10))
}
if (disp) if (j/100 == floor(j/100)) cat("\n")
}
if (disp) cat("\n")
Jn = -(Jn + t(Jn))/2
Vnt = ginv(Jn)
ZZZ = blkdiag(diag(lde),Zpar)
if(disc) ZZZ = blkdiag(ZZZ,Zga)
Vn = ZZZ%*%Vnt%*%t(ZZZ)
set = sqrt(abs(diag(Vnt)))
se = sqrt(abs(diag(Vn)))
if (k > 1) sede = se[1:lde]
separt = se[lde + (1:lpart)]
setht = separt[indtht]
sebet = separt[indbet]
separ = se[lde + (1:lpar)]
if(disc){
segat = set[lde + lpart + (1:lgat)]
sega = se[lde + lpar + (1:lga)]
segac = rep(NA, J); segac[items] = sega
}else{
segat = sega = segac = NULL
}
setht = separ[indtht]
seth = separ[indth]
seTh = matrix(seth, rm, k)
dimnames(seTh) = list(dimension = 1:rm,class=1:k)
sebe = separ[indbe]
if (difl) {
sebec1 = rep(0, J)
sebec1[(1:J)[-fv]] = sebe[1:(J - rm)]
sebec2 = rep(0, lm - 1)
sebec2[2:(lm - 1)] = sebe[J - rm + (1:(lm - 2))]
seBec = list(difficulties = sebec1, cutoffs = sebec2)
}else{
seBec = matrix(NA, J, lm - 1)
count = 0
for (j in 1:J) {
seBec[j, (1:lv[j] - 1)] = sebe[count + (1:(lv[j] - 1))]
count = count + lv[j] - 1
}
dimnames(seBec) = list(item = 1:J, cutoff = 1:(lm-1))
}
if (glob){
if (k == 1) seDe = NULL
else{
if(cov){
seDe = matrix(sede, ncov + k - 1, 1)
rownames(seDe) = namesX
}else seDe = sede
}
}else{
if (k == 1) seDe = NULL
else{
if(cov){
seDe = matrix(sede, ncov + 1, k - 1)
rownames(seDe) = namesX
}else seDe = sede
}
}
}
mu = drop(Th%*%piv)
sd = drop(sqrt((Th-mu)^2%*%piv))
ind = order(Th[1,])
Ths = (Th[,ind]-mu)/sd
pivs = piv[ind]
Becs = Bec
gacs = gac
for(j in 1:rm){
tmp = multi[j,]; tmp = tmp[tmp>0]
gacs[tmp] = gac[tmp]*sd[j]
if(difl) Becs$difficulties[tmp] = Becs$difficulties[tmp]-gac[tmp]*mu[j]
else Becs[tmp,] = Becs[tmp,]-gac[tmp]*mu[j]
}
out = list(piv = piv, fv = fv, tht = tht, Th = Th, bet=bet, Bec = Bec, gat=gat, gac = gac, De = De,
Phi = Phi, lk = lk, np = np, aic = aic, bic = bic, ent = ent, pivs=pivs, Ths=Ths, Becs=Becs,
gacs = gacs, call = match.call())
if (output) {
out$Pp = Pp
out$lkv = lkv
if(cov){
out$Xlabel = Xlabel
out$XXdis = XXdis
out$Piv = Piv
}
}
if (out_se) {
out$setht = setht
out$seTh = seTh
out$sebet = sebet
out$seBec = seBec
out$segat = segat
out$segac = segac
out$seDe = seDe
out$Vnt = Vnt
out$Vn = Vn
}
class(out) = "est_multi_poly_between"
return(out)
} |
dualpathTrendX <- function(y, pos, X, D, ord, approx=FALSE, maxsteps=2000,
minlam=0, rtol=1e-7, btol=1e-7, eps=1e-4,
verbose=FALSE, object=NULL) {
if (is.null(object)) {
m = nrow(D)
p = ncol(D)
n = length(y)
y0 = y
X0 = X
if (eps>0) {
y = c(y,rep(0,p))
X = rbind(X,diag(sqrt(eps),p))
n = n+p
}
if (is.null(pos)) pos = 1:p
Pos = matrix(rep(pos,each=ord),ord,p)
basis = matrix(0,p,ord+1)
basis[,1] = rep(1,p)
for (i in Seq(2,ord+1)) {
ii = Seq(1,i-1)
basis[,i] = apply(pmax(Pos[ii,,drop=FALSE]-pos[ii],0),
2,prod)/factorial(i-1)
}
xy = t(X)%*%y
A = X%*%basis
z = t(basis)%*%xy
R = qr.R(qr(A))
e = backsolve(R,forwardsolve(R,z,upper.tri=TRUE,transpose=TRUE))
g = xy-t(X)%*%(A%*%e)
x = qr(t(D))
uhat = backsolveSparse(x,g)
betahat = basis%*%e
ihit = which.max(abs(uhat))
hit = abs(uhat[ihit])
s = sign(uhat[ihit])
if (verbose) {
cat(sprintf("1. lambda=%.3f, adding coordinate %i, |B|=%i...",
hit,ihit,1))
}
buf = min(maxsteps,1000)
lams = numeric(buf)
h = logical(buf)
df = numeric(buf)
u = matrix(0,m,buf)
beta = matrix(0,p,buf)
lams[1] = hit
h[1] = TRUE
df[1] = ncol(basis)
u[,1] = uhat
beta[,1] = betahat
newbv = apply(pmax(Pos-pos[Seq(ihit+1,ihit+ord)],0),
2,prod)/factorial(ord)
newbv[Seq(1,ihit+ord)] = 0
basis = cbind(basis,newbv)
r = 1
B = ihit
I = Seq(1,m)[-ihit]
D1 = D[-ihit,,drop=FALSE]
D2 = D[ihit,,drop=FALSE]
k = 2
}
else {
lambda = NULL
for (j in 1:length(object)) {
if (names(object)[j] != "pathobjs") {
assign(names(object)[j], object[[j]])
}
}
y0 = y
X0 = X
for (j in 1:length(object$pathobjs)) {
assign(names(object$pathobjs)[j], object$pathobjs[[j]])
}
lams = lambda
if (eps>0) X = rbind(X,diag(sqrt(eps),p))
}
tryCatch({
while (k<=maxsteps && lams[k-1]>=minlam) {
if (k > length(lams)) {
buf = length(lams)
lams = c(lams,numeric(buf))
h = c(h,logical(buf))
df = c(df,numeric(buf))
u = cbind(u,matrix(0,m,buf))
beta = cbind(beta,matrix(0,p,buf))
}
x = qr(t(D1))
Ds = as.numeric(t(D2)%*%s)
A = X%*%basis
z = t(basis)%*%cbind(xy,Ds)
R = qr.R(qr(A))
e = backsolve(R,forwardsolve(R,z,upper.tri=TRUE,transpose=TRUE))
ea = e[,1]
eb = e[,2]
ga = xy-t(X)%*%(A%*%ea)
gb = Ds-t(X)%*%(A%*%eb)
fa = basis%*%ea
fb = basis%*%eb
if (r==m) {
hit = 0
}
else {
a = backsolveSparse(x,ga)
b = backsolveSparse(x,gb)
shits = Sign(a)
hits = a/(b+shits)
hits[hits>lams[k-1]+btol] = 0
hits[hits>lams[k-1]] = lams[k-1]
ihit = which.max(hits)
hit = hits[ihit]
shit = shits[ihit]
}
if (r==0 || approx) {
leave = 0
}
else {
c = as.numeric(s*(D2%*%fa))
d = as.numeric(s*(D2%*%fb))
leaves = c/d
leaves[c>=0] = 0
leaves[leaves>lams[k-1]+btol] = 0
leaves[leaves>lams[k-1]] = lams[k-1]
ileave = which.max(leaves)
leave = leaves[ileave]
}
if (hit<=0 && leave<=0) break
if (hit > leave) {
lams[k] = hit
h[k] = TRUE
df[k] = ncol(basis)
uhat = numeric(m)
uhat[B] = hit*s
uhat[I] = a-hit*b
betahat = fa-hit*fb
newbv = apply(pmax(Pos-pos[Seq(I[ihit]+1,I[ihit]+ord)],0),
2,prod)/factorial(ord)
newbv[Seq(1,I[ihit]+ord)] = 0
basis = cbind(basis,newbv)
r = r+1
B = c(B,I[ihit])
I = I[-ihit]
s = c(s,shit)
D2 = rbind(D2,D1[ihit,])
D1 = D1[-ihit,,drop=FALSE]
if (verbose) {
cat(sprintf("\n%i. lambda=%.3f, adding coordinate %i, |B|=%i...",
k,hit,B[r],r))
}
}
else {
lams[k] = leave
h[k] = FALSE
df[k] = ncol(basis)
uhat = numeric(m)
uhat[B] = leave*s
uhat[I] = a-leave*b
betahat = fa-leave*fb
basis = basis[,-(ord+1+ileave)]
r = r-1
I = c(I,B[ileave])
B = B[-ileave]
s = s[-ileave]
D1 = rbind(D1,D2[ileave,])
D2 = D2[-ileave,,drop=FALSE]
if (verbose) {
cat(sprintf("\n%i. lambda=%.3f, deleting coordinate %i, |B|=%i...",
k,leave,I[m-r],r))
}
}
u[,k] = uhat
beta[,k] = betahat
k = k+1
}
}, error = function(err) {
err$message = paste(err$message,"\n(Path computation has been terminated;",
" partial path is being returned.)",sep="")
warning(err)})
lams = lams[Seq(1,k-1)]
h = h[Seq(1,k-1)]
df = df[Seq(1,k-1)]
u = u[,Seq(1,k-1),drop=FALSE]
beta = beta[,Seq(1,k-1),drop=FALSE]
if (k>maxsteps) {
if (verbose) {
cat(sprintf("\nReached the max number of steps (%i),",maxsteps))
cat(" skipping the rest of the path.")
}
completepath = FALSE
}
else if (lams[k-1]<minlam) {
if (verbose) {
cat(sprintf("\nReached the min lambda (%.3f),",minlam))
cat(" skipping the rest of the path.")
}
completepath = FALSE
}
else completepath = TRUE
bls = NULL
if (completepath) bls = fa
if (verbose) cat("\n")
pathobjs = list(type="trend.x", r=r, B=B, I=I, Q1=NA, approx=approx,
Q2=NA, k=k, df=df, D1=D1, D2=D2, Ds=Ds, ihit=ihit, m=m, n=n, p=p,
q=q, h=h, q0=NA, rtol=rtol, btol=btol, eps=eps, s=s, y=y, ord=ord,
pos=pos, Pos=Pos, basis=basis, xy=xy)
colnames(u) = as.character(round(lams,3))
colnames(beta) = as.character(round(lams,3))
return(list(lambda=lams,beta=beta,fit=X0%*%beta,u=u,hit=h,df=df,y=y0,X=X0,
completepath=completepath,bls=bls,pathobjs=pathobjs))
} |
rename_jags_columns <- function(data) {
colnames(data)[colnames(data) %in% c("greenhouse", "ghs")] <- c("ghs", "greenhouse")
colnames(data)[colnames(data) %in% c("site_id", "site")] <- c("site", "site_id")
stat <- NULL
n <- NULL
trt_id <- NULL
citation_id <- NULL
transformed <- transform(data,
Y = mean,
se = stat,
obs.prec = 1 / (sqrt(n) * stat) ^2,
trt = trt_id,
cite = citation_id)
selected <- subset(transformed, select = c('Y', 'n', 'site', 'trt', 'ghs', 'obs.prec',
'se', 'cite',
"greenhouse", "site_id", "treatment_id", "trt_name", "trt_num"))
return(selected)
} |
GumbelVaR<- function(mu, sigma, n, cl, hp){
if (!length(mu) == 1) {
stop("Mean must be a scalar")
}
if (!length(sigma) == 1) {
stop("Standard Deviation must be a scalar")
}
if (!is.vector(cl)) {
stop("cl must be a vector")
}
if (!length(hp) == 1) {
stop("hp must be a scalar")
}
cl <- t(as.matrix(cl))
if (sigma < 0) {
stop("Standard deviation must be non-negative")
}
if (max(cl) >= 1) {
stop("Confidence levels must be less than 1")
}
if (min(cl) <= 0) {
stop("Confidence levels must be less than 1")
}
if (min(hp) <= 0) {
stop("Holding period must be greated than 0")
}
y <- mu * matrix(1, dim(cl)[1], dim(cl)[2]) - sigma * log(- n * log(cl));
return(y)
} |
c2=function(n)
{
lines(m, 1-(2^n-m-1)/2^n, type="b")
}
Pnm=function(n, m)
{
return(1-(2^(2^n-m)-1)/2^2^n)
}
p_disting=function(n)
{
lines(m, Pnm(n, m), type="b")
}
mc_dc_false_prob=function(max_n)
{
lines(1:max_n, Pnm(1:max_n, 2:(max_n+1)), type="b")
}
m=1:10
plot(0, type="n",
yaxs="i",
xlim=c(1, 10), ylim=c(0, 1.02),
xlab="Number of tests", ylab="Probability of false positive\n")
c2(3)
p_disting(2)
p_disting(3)
p_disting(7)
plot(0, type="n",
yaxs="i",
xlim=c(1, 10), ylim=c(0.93, 1.01),
xlab="Number of tests", ylab="Probability of false positive\n")
mc_dc_false_prob(9) |
pcaser2 <-
function(veg,plotlabels,y=1) {
nrel<- length(veg[,1])
nser<-length(table(plotlabels))
ser<- as.integer(plotlabels)
vegt<- veg^y
out.pca<- pca(vegt)
E<- out.pca$sdev^2/out.pca$totdev*100
o.pcas<- list(nrel=nrel,nser=nser,scores=out.pca$scores,plotlab=ser,plotlabels=plotlabels,Eigv=E)
} |
getOrientacoesMestrado <- function(curriculo) {
if (!any(class(curriculo) == 'xml_document')) {
stop("The input file must be XML, imported from `xml2` package.", call. = FALSE)
}
dados_basicos <-
xml2::xml_find_all(curriculo, ".//ORIENTACOES-CONCLUIDAS-PARA-MESTRADO") |>
purrr::map(~ xml2::xml_find_all(., ".//DADOS-BASICOS-DE-ORIENTACOES-CONCLUIDAS-PARA-MESTRADO")) |>
purrr::map(~ xml2::xml_attrs(.)) |>
purrr::map(~ dplyr::bind_rows(.)) |>
purrr::map(~ janitor::clean_names(.))
detalhamento <-
xml2::xml_find_all(curriculo, ".//ORIENTACOES-CONCLUIDAS-PARA-MESTRADO") |>
purrr::map(~ xml2::xml_find_all(., ".//DETALHAMENTO-DE-ORIENTACOES-CONCLUIDAS-PARA-MESTRADO")) |>
purrr::map(~ xml2::xml_attrs(.)) |>
purrr::map(~ dplyr::bind_rows(.)) |>
purrr::map(~ janitor::clean_names(.))
purrr::map2(dados_basicos, detalhamento, dplyr::bind_cols) |>
dplyr::bind_rows() |>
dplyr::mutate(id = getId(curriculo))
} |
CopulaTestTable = function(){
copula = c("normal", "t", "clayton", "gumbel", "frank", "joe", "amh",
"galambos", "huslerReiss", "tawn", "tev", "fgm", "plackett")
tests = c("gofCvM", "gofKS", "gofKendallCvM", "gofKendallKS",
"gofRosenblattSnB", "gofRosenblattSnC","gofRosenblattGamma",
"gofRosenblattChisq", "gofKernel", "gofWhite", "gofPIOSTn",
"gofPIOSRn", "gofArchmSnB", "gofArchmSnC", "gofArchmGamma",
"gofArchmChisq")
tbl = matrix(rbind(c(">=2", ">=2", ">=2", ">=2", ">=2", ">=2", "2", "2", "2",
"2", "2", "2", "2"),
c(">=2", ">=2", ">=2", ">=2", ">=2", ">=2", "2", "2", "2",
"2", "2", "2", "2"),
c(">=2", ">=2", ">=2", ">=2", ">=2", ">=2", "2", "2", "2",
"2", "2", "2", "2"),
c(">=2", ">=2", ">=2", ">=2", ">=2", ">=2", "2", "2", "2",
"2", "2", "2", "2"),
c(">=2", ">=2", ">=2", ">=2", ">=2", ">=2", "2", "2", "-",
"-", "-", "2", "2"),
c(">=2", ">=2", ">=2", ">=2", ">=2", ">=2", "2", "2", "-",
"-", "-", "2", "2"),
c(">=2", ">=2", ">=2", ">=2", ">=2", ">=2", "2", "2", "-",
"-", "-", "2", "2"),
c(">=2", ">=2", ">=2", ">=2", ">=2", ">=2", "2", "2", "-",
"-", "-", "2", "2"),
c("2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2",
"2", "2"),
c("2", "2", "2", "2", "2", "2", "-", "-", "-", "-", "-",
"-", "-"),
c("3", "2", "3", "3", "3", "3", "2", "2", "-", "-", "-",
"2", "2"),
c("3", "2", "3", "3", "3", "3", "2", "2", "-", "-", "-",
"2", "2"),
c("-", "-", ">=2", ">=2", ">=2", ">=2", "2", "-", "-",
"-", "-", "-", "-"),
c("-", "-", ">=2", ">=2", ">=2", ">=2", "2", "-", "-",
"-", "-", "-", "-"),
c("-", "-", ">=2", ">=2", ">=2", ">=2", "2", "-", "-",
"-", "-", "-", "-"),
c("-", "-", ">=2", ">=2", ">=2", ">=2", "2", "-", "-",
"-", "-", "-", "-")),
dimnames = list(tests, copula), nrow = length(tests),
ncol = length(copula))
return(data.frame(tbl))
} |
levelling.resources<-function(duration,prec1and2=matrix(0),prec3and4=matrix(0),resources,int=1){
or1<-order(organize(prec1and2,prec3and4)$Order[,2])
or2<-organize(prec1and2,prec3and4)$Order[,2]
precedence<-organize(prec1and2,prec3and4)$Precedence
durations<-duration[or2]
costes<-resources[or2]
n<-length(durations)
activities<-1:n
early.times<-rep(0,n)
ii<-as.logical(colSums(precedence))
iii<-activities[ii]
nn<-length(iii)
if(nn>0){
prec<-matrix(0,nrow=nn,ncol=n-1)
for(j in 1:nn){
prec[j,1:length(which(precedence[,iii[j]]==1))]<-which(precedence[,iii[j]]==1)
}
prec<-prec[,as.logical(colSums(prec)),drop=FALSE]
for(i in 1:nn) {
early.times[iii[i]]=max(early.times[prec[i,]]+durations[prec[i,]]);
}
}
tiempo.last<-rep(0,n)
ii<-as.logical(rowSums(precedence))
iii<-activities[ii]
tiempo.last[activities[ii==FALSE]]<-max(early.times+durations)
nn<-length(iii)
if(nn>0){
prec<-matrix(0,nrow=nn,ncol=n-1)
for(j in 1:nn){
prec[j,1:length(which(precedence[iii[j],]==1))]<-which(precedence[iii[j],]==1)
}
prec<-prec[,as.logical(colSums(prec)),drop=FALSE]
for(i in length(iii):1) {
tiempo.last[iii[i]]=min(tiempo.last[prec[i,]]-durations[prec[i,]]);
}
}
prec<-matrix(0,nrow=n,ncol=n-1)
for(j in 1:n){
if(sum(which(precedence[j,]==1))!=0){prec[j,1:length(which(precedence[j,]==1))]<-which(precedence[j,]==1)}
}
D.T<-max(early.times+durations)
holguras<-round(tiempo.last-early.times-durations,5)
periods<-seq(int,D.T,by=int)
cost.period<-numeric(length(periods))
X<-function(y){
sum((y-mean(y))^2)
}
for(i in 1:n){
cost.period[(early.times[i]*(1/int)+1):((early.times[i]+durations[i])*(1/int))]<-cost.period[(early.times[i]*(1/int)+1):((early.times[i]+durations[i])*(1/int))]+costes[i]
}
cost.period0<-cost.period
for(i in n:1){
if(holguras[i]!=0){
{
if(sum(prec[i,])==0){times<-seq(early.times[i],early.times[i]+holguras[i],by=int)}
else{times<-seq(early.times[i],min(early.times[prec[i,]])-durations[i],by=int)}
}
new.periods<-numeric(length(times))
cost.periods<-matrix(0,nrow=length(times),ncol=length(periods))
for(j in 1:length(times)){
early.times1<-early.times
early.times1[i]<-times[j]
for(z in 1:n){
cost.periods[j,(early.times1[z]*(1/int)+1):((early.times1[z]+durations[z])*(1/int))]<-cost.periods[j,(early.times1[z]*(1/int)+1):((early.times1[z]+durations[z])*(1/int))]+costes[z]
}
}
minimos<-apply(cost.periods,1,X)
early.times[i]<-times[max(which(minimos==min(minimos)))]
}
}
cost.period<-numeric(length(periods))
for(i in 1:n){
cost.period[(early.times[i]*(1/int)+1):((early.times[i]+durations[i])*(1/int))]<-cost.period[(early.times[i]*(1/int)+1):((early.times[i]+durations[i])*(1/int))]+costes[i]
}
cat("Early times = ", "\n")
print(early.times[or1])
cat("Resources by period= ", "\n")
print(cost.period)
z<-seq(int,D.T,int)-int/2
zz<-seq(0,D.T,int)
{
plot(z,cost.period0,type="b",pch=18,lwd=2,axes=F,xlab="Periods",ylab="Resources")
axis(side=1,at=zz)
axis(side=2,at=1:20)
lines(z,cost.period,type="b",pch=1,lwd=2,col="red")
legend(D.T-4, max(cost.period0), legend=c("First solution", "Readjusted solution"),
col=c("black", "red"), lwd=c(2,2),pch=c(18,1), cex=1.1)
}
} |
par(ask=TRUE)
opar <- par(no.readonly=FALSE)
data(nutrient, package="flexclust")
head(nutrient, 2)
d <- dist(nutrient)
as.matrix(d)[1:4,1:4]
data(nutrient, package="flexclust")
row.names(nutrient) <- tolower(row.names(nutrient))
nutrient.scaled <- scale(nutrient)
d <- dist(nutrient.scaled)
fit.average <- hclust(d, method="average")
plot(fit.average, hang=-1, cex=.8, main="Average Linkage Clustering")
library(NbClust)
nc <- NbClust(nutrient.scaled, distance="euclidean",
min.nc=2, max.nc=15, method="average")
par(opar)
table(nc$Best.n[1,])
barplot(table(nc$Best.n[1,]),
xlab="Numer of Clusters", ylab="Number of Criteria",
main="Number of Clusters Chosen by 26 Criteria")
clusters <- cutree(fit.average, k=5)
table(clusters)
aggregate(nutrient, by=list(cluster=clusters), median)
aggregate(as.data.frame(nutrient.scaled), by=list(cluster=clusters),
median)
plot(fit.average, hang=-1, cex=.8,
main="Average Linkage Clustering\n5 Cluster Solution")
rect.hclust(fit.average, k=5)
wssplot <- function(data, nc=15, seed=1234){
wss <- (nrow(data)-1)*sum(apply(data,2,var))
for (i in 2:nc){
set.seed(seed)
wss[i] <- sum(kmeans(data, centers=i)$withinss)}
plot(1:nc, wss, type="b", xlab="Number of Clusters",
ylab="Within groups sum of squares")}
data(wine, package="rattle")
head(wine)
df <- scale(wine[-1])
wssplot(df)
library(NbClust)
set.seed(1234)
nc <- NbClust(df, min.nc=2, max.nc=15, method="kmeans")
par(opar)
table(nc$Best.n[1,])
barplot(table(nc$Best.n[1,]),
xlab="Numer of Clusters", ylab="Number of Criteria",
main="Number of Clusters Chosen by 26 Criteria")
set.seed(1234)
fit.km <- kmeans(df, 3, nstart=25)
fit.km$size
fit.km$centers
aggregate(wine[-1], by=list(cluster=fit.km$cluster), mean)
ct.km <- table(wine$Type, fit.km$cluster)
ct.km
library(flexclust)
randIndex(ct.km)
library(cluster)
set.seed(1234)
fit.pam <- pam(wine[-1], k=3, stand=TRUE)
fit.pam$medoids
clusplot(fit.pam, main="Bivariate Cluster Plot")
ct.pam <- table(wine$Type, fit.pam$clustering)
ct.pam
randIndex(ct.pam)
library(fMultivar)
set.seed(1234)
df <- rnorm2d(1000, rho=.5)
df <- as.data.frame(df)
plot(df, main="Bivariate Normal Distribution with rho=0.5")
wssplot(df)
library(NbClust)
nc <- NbClust(df, min.nc=2, max.nc=15, method="kmeans")
par(opar)
barplot(table(nc$Best.n[1,]),
xlab="Numer of Clusters", ylab="Number of Criteria",
main ="Number of Clusters Chosen by 26 Criteria")
library(ggplot2)
library(cluster)
fit <- pam(df, k=2)
df$clustering <- factor(fit$clustering)
ggplot(data=df, aes(x=V1, y=V2, color=clustering, shape=clustering)) +
geom_point() + ggtitle("Clustering of Bivariate Normal Data")
plot(nc$All.index[,4], type="o", ylab="CCC",
xlab="Number of clusters", col="blue") |
mnl_RW_once <- function(int1, Obs, n_cat, mu_int_bar1, V_int1, scalar, candcov1) {
oldloglike <- llmnl_int(int = int1, Obs = Obs, n_cat = n_cat)
oldpostlike <- oldloglike + dmvnorm(int1, mu_int_bar1, V_int1, log = TRUE)
probold <- int_to_prob(int1)
int_new <- int1 + rmvnorm(1, rep(0, (n_cat - 1)), scalar^2 * candcov1, method = "svd")
newloglike <- llmnl_int(int = int_new, Obs = Obs, n_cat = n_cat)
newpostlike <- newloglike + dmvnorm(int_new, mu_int_bar1, V_int1, log = TRUE)
probnew <- int_to_prob(int_new)
acc <- min(log(1), (newpostlike - oldpostlike))
if(acc < log(1)) {
unif <- log(runif(1))
} else {
unif <- log(1)
}
if (unif <= acc) {
draw_int <- int_new
accept <- 1
prob <- probnew
} else {
draw_int <- int1
accept <- 0
prob <- probold
}
return(list(draw_int = draw_int, accept = accept, prob = prob))
} |
if (requiet("testthat") &&
requiet("insight") &&
requiet("parameters") &&
requiet("metaBMA") &&
getRversion() >= "3.6.0") {
data(towels)
set.seed(1234)
m <-
suppressWarnings(meta_random(
logOR,
SE,
study,
data = towels,
ci = 0.95,
iter = 100,
logml_iter = 200
))
test_that("model_parameters.meta_random", {
params <- model_parameters(m)
expect_equal(params$Parameter, c(
"Goldstein, Cialdini, & Griskevicius (2008), Exp. 1", "Goldstein, Cialdini, & Griskevicius (2008), Exp. 2",
"Schultz, Khazian, & Zaleski (2008), Exp. 2", "Schultz, Khazian, & Zaleski (2008), Exp. 3",
"Mair & Bergin-Seers (2010), Exp. 1", "Bohner & Schluter (2014), Exp. 1",
"Bohner & Schluter (2014), Exp. 2", "Overall", "tau"
))
expect_equal(
params$Coefficient,
c(0.3806, 0.30494, 0.20554, 0.25084, 0.28768, -0.12154, -1.45792, 0.2004, 0.12107),
tolerance = 1e-3
)
expect_equal(
params$CI_low,
c(-0.00686, 0.03816, -0.16998, -0.0825, -1.32685, -0.60772, -2.94785, 0.00824, 0.01884),
tolerance = 1e-3
)
expect_equal(
colnames(params),
c(
"Parameter", "Coefficient", "SE", "CI", "CI_low", "CI_high", "Weight",
"BF", "Rhat", "ESS", "Component", "Prior_Distribution", "Prior_Location", "Prior_Scale", "Method"
)
)
})
set.seed(1234)
m2 <-
meta_fixed(
logOR,
SE,
study,
data = towels,
ci = 0.95
)
test_that("model_parameters.meta_fixed", {
params <- model_parameters(m2)
expect_equal(params$Parameter, c(
"Goldstein, Cialdini, & Griskevicius (2008), Exp. 1", "Goldstein, Cialdini, & Griskevicius (2008), Exp. 2",
"Schultz, Khazian, & Zaleski (2008), Exp. 2", "Schultz, Khazian, & Zaleski (2008), Exp. 3",
"Mair & Bergin-Seers (2010), Exp. 1", "Bohner & Schluter (2014), Exp. 1",
"Bohner & Schluter (2014), Exp. 2", "Overall"
))
expect_equal(params$Coefficient,
c(0.3806, 0.30494, 0.20554, 0.25084, 0.28768, -0.12154, -1.45792, 0.22141),
tolerance = 1e-3
)
expect_equal(params$CI_low,
c(-0.00686, 0.03816, -0.16998, -0.0825, -1.32685, -0.60772, -2.94785, 0.06638),
tolerance = 1e-3
)
expect_equal(
colnames(params),
c(
"Parameter", "Coefficient", "SE", "CI", "CI_low", "CI_high", "Weight",
"BF", "Rhat", "ESS", "Component", "Prior_Distribution", "Prior_Location", "Prior_Scale", "Method"
)
)
})
set.seed(1234)
m3 <-
suppressWarnings(meta_random(
logOR,
SE,
study,
data = towels,
ci = 0.99,
iter = 100,
logml_iter = 200
))
test_that("model_parameters.meta_random", {
params <- model_parameters(m3)
expect_equal(params$Parameter, c(
"Goldstein, Cialdini, & Griskevicius (2008), Exp. 1", "Goldstein, Cialdini, & Griskevicius (2008), Exp. 2",
"Schultz, Khazian, & Zaleski (2008), Exp. 2", "Schultz, Khazian, & Zaleski (2008), Exp. 3",
"Mair & Bergin-Seers (2010), Exp. 1", "Bohner & Schluter (2014), Exp. 1",
"Bohner & Schluter (2014), Exp. 2", "Overall", "tau"
))
expect_equal(params$Coefficient, c(0.3806, 0.30494, 0.20554, 0.25084, 0.28768, -0.12154, -1.45792, 0.2004, 0.12107), tolerance = 1e-3)
expect_equal(params$CI_low, c(-0.00686, 0.03816, -0.16998, -0.0825, -1.32685, -0.60772, -2.94785, -0.15334, 0.01884), tolerance = 1e-3)
expect_equal(
colnames(params),
c(
"Parameter", "Coefficient", "SE", "CI", "CI_low", "CI_high", "Weight",
"BF", "Rhat", "ESS", "Component", "Prior_Distribution", "Prior_Location", "Prior_Scale", "Method"
)
)
})
} |
logLik.HatchingSuccess <- function(object, ...) {
L <- -object$value
attributes(L) <- list(df=length(object$par),
nobs=nrow(object$data))
return(L)
} |
setGeneric("alphaInterval",
function(object, ...) standardGeneric("alphaInterval"))
setMethod(
f="alphaInterval",
signature(object="FuzzyNumber"),
definition=function(object, ...)
{
if (is.na(object@lower(0)) || is.na(object@upper(0))) return(c(NA_real_, NA_real_))
return(c(
integrateAlpha(object, "lower", 0, 1, weight=identity, ...),
integrateAlpha(object, "upper", 0, 1, weight=identity, ...)
))
}
)
setMethod(
f="alphaInterval",
signature(object="TrapezoidalFuzzyNumber"),
definition=function(object)
{
return(c(
object@a1*0.5+(object@a2-object@a1)/3,
object@a3*0.5+(object@a4-object@a3)/6
))
}
)
setMethod(
f="alphaInterval",
signature(object="PiecewiseLinearFuzzyNumber"),
definition=function(object)
{
xl <- c(object@a1, [email protected], object@a2)
xr <- c(object@a3, [email protected], object@a4)
al <- c(0, [email protected], 1)
ar <- c(1, rev([email protected]), 0)
dxl <- diff(xl)
dxr <- diff(xr)
dal <- diff(al)
dar <- diff(ar)
return(c(
sum( diff(al^2)*(xl[[email protected]]-al[[email protected]]*dxl/dal)/2+diff(al^3)*dxl/dal/3 ),
-sum( diff(ar^2)*(xr[[email protected]]-ar[[email protected]]*dxr/dar)/2+diff(ar^3)*dxr/dar/3 )
))
}
)
setMethod(
f="alphaInterval",
signature(object="PowerFuzzyNumber"),
definition=function(object)
{
return(c(
(2*object@a2*[email protected]+object@a1)/(4*[email protected]+2),
(2*object@a3*[email protected]+object@a4)/(4*[email protected]+2)
))
}
) |
lpmin.setup = function(optvars, cdimn){
Data = optvars$Data
n = NROW(Data)
m = NCOL(Data)
colnames(Data) = NULL
rownames(Data) = NULL
index = optvars$index
if(index[3] == 1){
.ineqx = parma.ineq.lpmin(ineq = rbind(optvars$mu, optvars$ineq.mat),
ineqLB = c(optvars$mutarget, optvars$ineq.LB),
ineqUB = c(Inf, optvars$ineqUB), cdim = cdimn)
} else{
.ineqx = parma.ineq.lpmin(ineq = optvars$ineq.mat, ineqLB = optvars$ineq.LB,
ineqUB = optvars$ineq.UB, cdim = cdimn)
}
ineqcon = .ineqx$ineqcon
ineqB = .ineqx$ineqB
ineqn = .ineqx$ineqn
ineqm = .ineqx$ineqm
if(index[3] == 1){
.eqx = parma.eq.lpmin(optvars$eq.mat, optvars$eqB, reward = NULL,
rewardB = NULL, cdim = cdimn, optvars$budget, m)
} else{
.eqx = parma.eq.lpmin(optvars$eq.mat, optvars$eqB, reward = optvars$mu,
rewardB = optvars$mutarget, cdim = cdimn,
optvars$budget, m)
}
eqcon = .eqx$eqcon
eqB = .eqx$eqB
eqn = .eqx$eqn
eqm = .eqx$eqm
return(list(ineqcon = ineqcon, ineqB = ineqB, ineqn = ineqn, ineqm = ineqm,
eqcon = eqcon, eqB = eqB, eqn = eqn, eqm = eqm))
}
lpopt.setup = function(optvars, cdimn){
Data = optvars$Data
n = NROW(Data)
m = NCOL(Data)
colnames(Data) = NULL
rownames(Data) = NULL
index = optvars$index
.ineqx = parma.ineq.lpopt(ineq = optvars$ineq.mat, ineqLB = optvars$ineq.LB,
ineqUB = optvars$ineq.UB, LB = optvars$LB, UB = optvars$UB,
cdim = cdimn)
ineqcon = .ineqx$ineqcon
ineqB = .ineqx$ineqB
ineqn = .ineqx$ineqn
ineqm = .ineqx$ineqm
.eqx = parma.eq.lpopt(optvars$eq.mat, optvars$eqB, reward = NULL,
rewardB = NULL, cdim = cdimn, optvars$budget, m)
eqcon = .eqx$eqcon
eqB = .eqx$eqB
eqn = .eqx$eqn
eqm = .eqx$eqm
return(list(ineqcon = ineqcon, ineqB = ineqB, ineqn = ineqn, ineqm = ineqm,
eqcon = eqcon, eqB = eqB, eqn = eqn, eqm = eqm))
}
lplpm1.minrisk = function(optvars)
{
Data = optvars$Data
n = NROW(Data)
m = NCOL(Data)
colnames(Data) = NULL
rownames(Data) = NULL
probability = optvars$probability
if(is.null(probability)) probability = rep(1/n, n)
cons = lpmin.setup(optvars, cdimn = n+1)
ineqcon = cons$ineqcon
ineqB = cons$ineqB
ineqn = cons$ineqn
ineqm = cons$ineqm
eqcon = cons$eqcon
eqB = cons$eqB
eqn = cons$eqn
eqm = cons$eqm
LB = optvars$LB
UB = optvars$UB
Amat = cbind( -Data, -diag(n), matrix(optvars$threshold, nrow = n, ncol = 1))
Amat = as.simple_triplet_matrix( rbind( Amat, ineqcon, eqcon ) )
rhs = rep(0, n)
rhs = c( rhs, as.numeric(ineqB), as.numeric(eqB) )
dir = c( rep("<=", n), rep("<=", ineqn), rep("==", eqn) )
objL = c( rep(0, m), probability, 1 )
bounds = list( lower = list( ind = 1L:(m + n + 1), val = c(LB, rep(0, n), 1 ) ),
upper = list( ind = 1L:(m + n + 1), val = c( UB, rep(Inf, n), 1 ) ) )
ans = list(objL = objL, Amat = Amat, dir = dir, rhs = rhs, bounds = bounds,
problem.max = FALSE, reward = optvars$mu,
dataidx = c(n, m), widx = 1:m)
rm(Amat)
rm(Data)
gc()
return( ans )
}
lplpm1.optrisk = function(optvars)
{
Data = optvars$Data
n = NROW(Data)
m = NCOL(Data)
colnames(Data) = NULL
rownames(Data) = NULL
probability = optvars$probability
if(is.null(probability)) probability = rep(1/n, n)
cons = lpopt.setup(optvars, cdimn = n+1)
ineqcon = cons$ineqcon
ineqB = cons$ineqB
ineqn = cons$ineqn
ineqm = cons$ineqm
eqcon = cons$eqcon
eqB = cons$eqB
eqn = cons$eqn
eqm = cons$eqm
Amat = cbind( -Data, -diag(n), matrix(optvars$threshold, ncol = 1, nrow = n) )
Amat = rbind( Amat,
cbind( matrix(optvars$mu, ncol = m, nrow = 1),
matrix(0, ncol = n, nrow = 1),
matrix(0, ncol = 1, nrow = 1) ) )
Amat = rbind( Amat, ineqcon, eqcon )
Amat = as.simple_triplet_matrix(Amat)
rhs = rep(0, n)
rhs = c( rhs, 1, as.numeric(ineqB), as.numeric(eqB) )
dir = c( rep("<=", n), "==", rep("<=", ineqn), rep("==", eqn) )
objL = c( rep(0, m), probability, 0 )
bounds = list( lower = list( ind = 1L:(m + n + 1), val = c( rep(-10000, m), rep(0, n), 0.05 ) ),
upper = list( ind = 1L:(m + n + 1), val = c( rep(10000, m), rep(Inf, n), 10000*m ) ) )
ans = list(objL = objL, Amat = Amat, dir = dir, rhs = rhs, bounds = bounds,
problem.max = FALSE, reward = optvars$mu,
dataidx = c(n, m), widx = 1:m, midx = length(objL))
rm(Amat)
rm(Data)
gc()
return( ans )
}
lpmad.minrisk = function(optvars)
{
Data = optvars$Data
n = NROW(Data)
m = NCOL(Data)
colnames(Data) = NULL
rownames(Data) = NULL
probability = optvars$probability
if(is.null(probability)) probability = rep(1/n, n)
cons = lpmin.setup(optvars, cdimn = 2*n + 1)
ineqcon = cons$ineqcon
ineqB = cons$ineqB
ineqn = cons$ineqn
ineqm = cons$ineqm
eqcon = cons$eqcon
eqB = cons$eqB
eqn = cons$eqn
eqm = cons$eqm
LB = optvars$LB
UB = optvars$UB
Amat = cbind( -Data, matrix(optvars$benchmark, nrow = n, ncol = 1), diag(n), -diag(n) )
Amat = as.simple_triplet_matrix( rbind( Amat, ineqcon, eqcon ) )
rhs = rep(0, n)
rhs = c( rhs, as.numeric(ineqB), as.numeric(eqB) )
dir = c( rep("==", n), rep("<=", ineqn), rep("==", eqn) )
objL = c( rep(0, m), 0, probability, probability )
bounds = list( lower = list( ind = 1L:(m + 2 * n + 1), val = c(LB, 1, rep(0, 2 * n) ) ),
upper = list( ind = 1L:(m + 2 * n + 1), val = c( UB, 1, rep(Inf, 2 * n) ) ) )
ans = list(objL = objL, Amat = Amat, dir = dir, rhs = rhs, bounds = bounds,
problem.max = FALSE, reward = optvars$mu,
dataidx = c(n, m), widx = 1:m)
rm(Amat)
rm(Data)
gc()
return( ans )
}
lpmad.optrisk = function(optvars)
{
Data = optvars$Data
n = NROW(Data)
m = NCOL(Data)
colnames(Data) = NULL
rownames(Data) = NULL
probability = optvars$probability
if(is.null(probability)) probability = rep(1/n, n)
cons = lpopt.setup(optvars, cdimn = 2*n + 1)
ineqcon = cons$ineqcon
ineqB = cons$ineqB
ineqn = cons$ineqn
ineqm = cons$ineqm
eqcon = cons$eqcon
eqB = cons$eqB
eqn = cons$eqn
eqm = cons$eqm
LB = optvars$LB
UB = optvars$UB
Amat = cbind( -Data, diag(n) , -diag(n), matrix(optvars$benchmark, ncol = 1, nrow = n) )
Amat = rbind( Amat,
cbind( matrix(optvars$mu, ncol = m, nrow = 1),
matrix(0, ncol = n, nrow = 1),
matrix(0, ncol = n, nrow = 1),
matrix(0, ncol = 1, nrow = 1) ) )
Amat = rbind( Amat, ineqcon, eqcon )
Amat = as.simple_triplet_matrix(Amat)
rhs = rep(0, n)
rhs = c( rhs, 1, as.numeric(ineqB), as.numeric(eqB) )
dir = c( rep("==", n), "==", rep("<=", ineqn), rep("==", eqn) )
objL = c( rep(0, m), probability, probability, 0 )
bounds = list( lower = list( ind = 1L:(m + 2 * n + 1), val = c( rep(-10000, m), rep(0, 2 * n), 0.05 ) ),
upper = list( ind = 1L:(m + 2 * n + 1), val = c( rep(10000, m), rep(Inf, 2 * n), 10000*m ) ) )
ans = list(objL = objL, Amat = Amat, dir = dir, rhs = rhs, bounds = bounds,
problem.max = FALSE, reward = optvars$mu,
dataidx = c(n, m), widx = 1:m, midx = length(objL))
rm(Amat)
rm(Data)
gc()
return( ans )
}
lpminmax.minrisk = function(optvars)
{
Data = optvars$Data
n = NROW(Data)
m = NCOL(Data)
colnames(Data) = NULL
rownames(Data) = NULL
cons = lpmin.setup(optvars, cdimn = 2)
ineqcon = cons$ineqcon
ineqB = cons$ineqB
ineqn = cons$ineqn
ineqm = cons$ineqm
eqcon = cons$eqcon
eqB = cons$eqB
eqn = cons$eqn
eqm = cons$eqm
LB = optvars$LB
UB = optvars$UB
Amat = cbind( -Data, matrix(optvars$benchmark, nrow = n, ncol = 1), matrix(1, nrow = n, ncol = 1) )
Amat = rbind( Amat, ineqcon, eqcon )
Amat = as.simple_triplet_matrix(Amat)
rhs = rep(0, n)
rhs = c( rhs, as.numeric(ineqB), as.numeric(eqB) )
dir = c( rep("<=", n), rep("<=", ineqn), rep("==", eqn) )
objL = c( rep(0, m), 0, -1 )
bounds = list( lower = list( ind = 1L:(m + 2), val = c(LB, 1, -Inf ) ),
upper = list( ind = 1L:(m + 2), val = c( UB, 1, Inf ) ) )
ans = list(objL = objL, Amat = Amat, dir = dir, rhs = rhs, bounds = bounds,
problem.max = FALSE, reward = optvars$mu,
dataidx = c(n, m), widx = 1:m, vidx = length(objL))
rm(Amat)
rm(Data)
gc()
return( ans )
}
lpminmax.optrisk = function(optvars)
{
Data = optvars$Data
n = NROW(Data)
m = NCOL(Data)
colnames(Data) = NULL
rownames(Data) = NULL
cons = lpopt.setup(optvars, cdimn = 2)
ineqcon = cons$ineqcon
ineqB = cons$ineqB
ineqn = cons$ineqn
ineqm = cons$ineqm
eqcon = cons$eqcon
eqB = cons$eqB
eqn = cons$eqn
eqm = cons$eqm
LB = optvars$LB
UB = optvars$UB
Amat = cbind( -Data, matrix(1, ncol = 1, nrow = n), matrix(optvars$benchmark, ncol = 1, nrow = n) )
Amat = rbind( Amat,
cbind( matrix(optvars$mu, ncol = m, nrow = 1),
matrix(0, nrow = 1, ncol = 1),
matrix(0, nrow = 1, ncol = 1) ) )
Amat = rbind( Amat, ineqcon, eqcon )
Amat = as.simple_triplet_matrix(Amat)
rhs = rep(0, n)
rhs = c( rhs, 1, as.numeric(ineqB), as.numeric(eqB) )
dir = c( rep("<=", n), "==", rep("<=", ineqn), rep("==", eqn) )
objL = c( rep(0, m), -1, 0 )
bounds = list( lower = list( ind = 1L:(m + 2), val = c(rep(-10000, m), -Inf, 0.05 ) ),
upper = list( ind = 1L:(m + 2), val = c( rep(10000, m), Inf, 10000*m ) ) )
ans = list(objL = objL, Amat = Amat, dir = dir, rhs = rhs, bounds = bounds,
problem.max = FALSE, reward = optvars$mu,
dataidx = c(n, m), widx = 1:m, midx = m+2, vidx = m+1)
rm(Amat)
rm(Data)
gc()
return( ans )
}
lpcvar.minrisk = function(optvars)
{
Data = optvars$Data
n = NROW(Data)
m = NCOL(Data)
colnames(Data) = NULL
rownames(Data) = NULL
probability = optvars$probability
if(is.null(probability)) probability = rep(1/n, n)
cons = lpmin.setup(optvars, cdimn = n+2)
ineqcon = cons$ineqcon
ineqB = cons$ineqB
ineqn = cons$ineqn
ineqm = cons$ineqm
eqcon = cons$eqcon
eqB = cons$eqB
eqn = cons$eqn
eqm = cons$eqm
LB = optvars$LB
UB = optvars$UB
Amat = cbind( -Data,
matrix(-1, nrow = n, ncol = 1),
-diag(n),
matrix(optvars$benchmark, nrow = n, ncol = 1) )
Amat = as.simple_triplet_matrix( rbind( Amat, ineqcon, eqcon ) )
rhs = rep(0, n)
rhs = c( rhs, as.numeric(ineqB), as.numeric(eqB) )
dir = c( rep("<=", n), rep("<=", ineqn), rep("==", eqn) )
objL = c( rep(0, m), 1, probability/optvars$alpha, 0)
bounds = list( lower = list( ind = 1L:(m + n + 2), val = c(LB, -1, rep(0, n), 1 ) ),
upper = list( ind = 1L:(m + n + 2), val = c( UB, 1, rep(Inf, n), 1 ) ) )
ans = list(objL = objL, Amat = Amat, dir = dir, rhs = rhs, bounds = bounds,
problem.max = FALSE, reward = optvars$mu,
dataidx = c(n, m), widx = 1:m, vidx = m+1)
rm(Data)
rm(Amat)
gc()
return( ans )
}
lpcvar.optrisk = function(optvars)
{
Data = optvars$Data
n = NROW(Data)
m = NCOL(Data)
colnames(Data) = NULL
rownames(Data) = NULL
probability = optvars$probability
if(is.null(probability)) probability = rep(1/n, n)
cons = lpopt.setup(optvars, cdimn = n+2)
ineqcon = cons$ineqcon
ineqB = cons$ineqB
ineqn = cons$ineqn
ineqm = cons$ineqm
eqcon = cons$eqcon
eqB = cons$eqB
eqn = cons$eqn
eqm = cons$eqm
LB = optvars$LB
UB = optvars$UB
Amat = cbind( -Data, matrix(-1, nrow = n, ncol = 1), -diag(n) , matrix(optvars$benchmark, ncol = 1, nrow = n) )
Amat = rbind( Amat,
cbind( matrix(optvars$mu, ncol = m, nrow = 1),
matrix(0, ncol = 1, nrow = 1),
matrix(0, ncol = n, nrow = 1),
matrix(0, ncol = 1, nrow = 1) ) )
Amat = rbind( Amat, ineqcon, eqcon )
Amat = as.simple_triplet_matrix(Amat)
rhs = rep(0, n)
rhs = c( rhs, 1, as.numeric(ineqB), as.numeric(eqB) )
dir = c( rep("<=", n), "==", rep("<=", ineqn), rep("==", eqn) )
objL = c( rep(0, m), 1, probability/optvars$alpha, 0 )
bounds = list( lower = list( ind = 1L:(m + n + 2), val = c( rep(-10000, m), 0, rep(0, n), 0.05 ) ),
upper = list( ind = 1L:(m + n + 2), val = c( rep(10000, m), 100000, rep(Inf, n), 10000*m ) ) )
ans = list(objL = objL, Amat = Amat, dir = dir, rhs = rhs, bounds = bounds,
problem.max = FALSE, reward = optvars$mu,
dataidx = c(n, m), widx = 1:m, vidx = m+1, midx = length(objL))
rm(Data)
rm(Amat)
gc()
return( ans )
}
lpcdar.minrisk = function(optvars)
{
Data = optvars$Data
n = NROW(Data)
m = NCOL(Data)
colnames(Data) = NULL
rownames(Data) = NULL
probability = optvars$probability
if(is.null(probability)) probability = rep(1/n, n)
cons = lpmin.setup(optvars, cdimn = 2*n+2)
ineqcon = cons$ineqcon
ineqB = cons$ineqB
ineqn = cons$ineqn
ineqm = cons$ineqm
eqcon = cons$eqcon
eqB = cons$eqB
eqn = cons$eqn
eqm = cons$eqm
LB = optvars$LB
UB = optvars$UB
xm = as.matrix( -diag(n) )
idx = which(xm == -1, arr.ind = TRUE)
xrow = idx[,1]
xcol = idx[,2]
xcol[2:length(xcol)] = xcol[2:length(xcol)] - 1
diag(xm[ xrow[2:length(xrow)], xcol[2:length(xcol)] ]) = 1
Amat = cbind(
-Data,
matrix(0, nrow = n, ncol = 1),
matrix(0, nrow = n, ncol = n),
as.matrix(xm),
matrix(optvars$benchmark, nrow = n, ncol = 1))
Amat = rbind( Amat, cbind(
matrix(0, nrow = n, ncol = m),
matrix(-1, nrow = n, ncol = 1),
-1 * diag(n),
diag(n),
matrix(0, nrow = n, ncol = 1)) )
Amat = rbind( Amat, ineqcon, eqcon)
Amat = as.simple_triplet_matrix(Amat)
rhs = rep(0, 2 * n)
rhs = c( rhs, as.numeric(ineqB), as.numeric(eqB) )
dir = c( rep("<=", 2 * n), rep("<=", ineqn), rep("==", eqn) )
objL = c( rep(0, m), 1, probability/optvars$alpha, rep(0, n), 0)
bounds = list( lower = list( ind = 1L:(m + 2 * n + 2), val = c( LB, -1, rep(0, 2 * n), 1) ),
upper = list( ind = 1L:(m + 2 * n + 2), val = c( UB, 1, rep(Inf, 2 * n), 1 ) ) )
ans = list(objL = objL, Amat = Amat, dir = dir, rhs = rhs, bounds = bounds,
problem.max = FALSE, reward = optvars$mu,
dataidx = c(n, m), widx = 1:m, vidx = m+1)
rm(Data)
rm(Amat)
gc()
return( ans )
}
lpcdar.optrisk = function(optvars)
{
Data = optvars$Data
n = NROW(Data)
m = NCOL(Data)
colnames(Data) = NULL
rownames(Data) = NULL
probability = optvars$probability
if(is.null(probability)) probability = rep(1/n, n)
cons = lpopt.setup(optvars, cdimn = 2*n+2)
ineqcon = cons$ineqcon
ineqB = cons$ineqB
ineqn = cons$ineqn
ineqm = cons$ineqm
eqcon = cons$eqcon
eqB = cons$eqB
eqn = cons$eqn
eqm = cons$eqm
LB = optvars$LB
UB = optvars$UB
xm = as.matrix( -diag(n) )
idx = which(xm == -1, arr.ind = TRUE)
xrow = idx[,1]
xcol = idx[,2]
xcol[2:length(xcol)] = xcol[2:length(xcol)] - 1
diag(xm[ xrow[2:length(xrow)], xcol[2:length(xcol)] ]) = 1
Amat = cbind(
-Data,
matrix(0, nrow = n, ncol = 1),
matrix(0, nrow = n, ncol = n),
as.matrix(xm),
matrix(optvars$benchmark, nrow = n, ncol = 1) )
Amat = rbind( Amat, cbind(
matrix(0, nrow = n, ncol = m),
matrix(-1, nrow = n, ncol = 1),
-1 * diag(n),
diag(n),
matrix(0, nrow = n, ncol = 1) ) )
Amat = rbind( Amat, cbind(
matrix(optvars$mu, nrow = 1, ncol = m),
matrix(0, nrow = 1, ncol = 1),
matrix(0, nrow = 1, ncol = n),
matrix(0, nrow = 1, ncol = n),
matrix(0, nrow = 1, ncol = 1) ) )
Amat = rbind( Amat, ineqcon, eqcon)
Amat = as.simple_triplet_matrix(Amat)
rhs = c(rep(0, 2 * n), 1)
rhs = c( rhs, as.numeric(ineqB), as.numeric(eqB) )
dir = c( rep("<=", 2 * n), "==", rep("<=", ineqn), rep("==", eqn) )
objL = c( rep(0, m) , 1, probability/optvars$alpha, rep(0, n), 0)
bounds = list( lower = list( ind = 1L:(m + 2 * n + 2), val = c( rep(-10000, m), -100000, rep(0, 2 * n), 1e-12 ) ),
upper = list( ind = 1L:(m + 2 * n + 2), val = c( rep( 10000, m), 100000, rep(Inf, 2 * n), 10000*m ) ) )
ans = list(objL = objL, Amat = Amat, dir = dir, rhs = rhs, bounds = bounds,
problem.max = FALSE, reward = optvars$mu,
dataidx = c(n, m), widx = 1:m, vidx = m+1, midx = length(objL))
rm(Data)
rm(Amat)
gc()
return( ans )
}
lpport = function(optvars, solver, ...)
{
valid.solvers = c("glpk", "symphony")
solver = match.arg(tolower(solver), valid.solvers)
risk = c("mad", "minimax", "cvar", "cdar", "ev", "lpm", "lpmupm")[optvars$index[4]]
if(optvars$index[5] == 1){
setup = switch(risk,
"mad" = lpmad.minrisk(optvars),
"minimax" = lpminmax.minrisk(optvars),
"cvar" = lpcvar.minrisk(optvars),
"cdar" = lpcdar.minrisk(optvars),
"lpm" = lplpm1.minrisk(optvars))
sol = lpminsolver(setup, solver, optvars, ...)
} else{
setup = switch(risk,
'mad' = lpmad.optrisk(optvars),
'minimax' = lpminmax.optrisk(optvars),
'cvar' = lpcvar.optrisk(optvars),
'cdar' = lpcdar.optrisk(optvars),
'lpm' = lplpm1.optrisk(optvars))
sol = lpoptsolver(setup, solver, optvars, ...)
}
rm(setup)
gc()
return( sol )
}
lpminsolver = function(setup, solver, optvars, ...)
{
if( is.null(list(...)$verbose) ) verbose = FALSE else verbose = as.logical( list(...)$verbose )
m = setup$dataidx[2]
sol = switch(solver,
glpk = try( Rglpk_solve_LP(obj = setup$objL, mat = setup$Amat, dir = setup$dir,
rhs = setup$rhs, bounds = setup$bounds, max = setup$problem.max,
verbose = verbose), silent = FALSE ),
symphony = try( Rsymphony::Rsymphony_solve_LP(obj = setup$objL,
mat = setup$Amat, dir = setup$dir, rhs = setup$rhs,
bounds = setup$bounds, max = setup$problem.max),
silent = FALSE ))
if( inherits(sol, "try-error") ){
status = "non-convergence"
weights = rep(NA, m)
risk = NA
reward = NA
VaR = NA
DaR = NA
} else{
status = sol$status
weights = sol$solution[setup$widx]
risk = switch(solver, glpk = sol$optimum, symphony = sol$objval)
if( !is.null(setup$reward) ){
reward = sum(optvars$mu * weights)
} else {
reward = NULL
}
if(optvars$index[4]==6) risk = risk - 1
if(optvars$index[4]==3) VaR = sol$solution[setup$vidx] else VaR = NA
if(optvars$index[4]==4) DaR = sol$solution[setup$vidx] else DaR = NA
}
rm(setup)
gc()
return( list(status = status, weights = weights, risk = risk, reward = reward,
multiplier = 1, VaR = VaR, DaR = DaR) )
}
lpoptsolver = function(setup, solver, optvars, ...)
{
if( is.null(list(...)$verbose) ) verbose = FALSE else verbose = as.logical( list(...)$verbose )
m = setup$dataidx[2]
sol = switch(solver,
glpk = try( Rglpk_solve_LP(obj = setup$objL, mat = setup$Amat, dir = setup$dir,
rhs = setup$rhs, bounds = setup$bounds, max = setup$problem.max,
verbose = verbose), silent = FALSE ),
symphony = try( Rsymphony::Rsymphony_solve_LP(obj = setup$objL,
mat = setup$Amat, dir = setup$dir, rhs = setup$rhs,
bounds = setup$bounds, max = setup$problem.max),
silent = FALSE ))
ans = list()
if( inherits(sol, "try-error") ){
status = "non-convergence"
weights = rep(NA, m)
risk = NA
reward = NA
optimum = NA
multiplier = NA
VaR = NA
DaR = NA
} else{
status = sol$status
multiplier = sol$solution[setup$midx]
tmp = sol$solution/multiplier
weights = tmp[setup$widx]
risk = sum(setup$objL * sol$solution)/multiplier
reward = sum(optvars$mu * weights)
optimum = switch(solver, glpk = sol$optimum, symphony = sol$objval)
if(optvars$index[4]==3) VaR = sol$solution[setup$vidx]/multiplier else VaR = NA
if(optvars$index[4]==4) DaR = sol$solution[setup$vidx]/multiplier else DaR = NA
}
rm(setup)
return( list(status = status, weights = weights, risk = risk, reward = reward,
optimum = optimum, multiplier = multiplier, VaR = VaR, DaR = DaR) )
} |
accept_rate <-
function(object){
rj<-object$rj_acc
mh<-object$mh_acc
est<-list(rj_ar=100*mean(rj),mh_ar=100*mean(mh))
class(est)<-"acceptrate"
est} |
context("nltts_plot")
test_that("use", {
set.seed(42)
n_tips <- 10
phylos <- c(ape::rcoal(n = n_tips))
testthat::expect_silent(nltts_plot(phylos))
})
test_that("abuse", {
testthat::expect_error(
nltts_plot(NULL),
"there must be at least one phylogeny supplied"
)
testthat::expect_error(
nltts_plot("nonsense"),
"phylogenies must be of class 'multiPhylo' or 'list'"
)
}) |
go2term <- function(goid) {
GO2TERM <- get_GO2TERM_table()
res <- GO2TERM[GO2TERM[,1] %in% goid, ]
rownames(res) <- NULL
return(res)
}
go2ont <- function(goid) {
GO2Ontology <- get_GO2Ontology_table()
res <- GO2Ontology[GO2Ontology[,1] %in% goid,]
rownames(res) <- NULL
return(res)
}
get_GOTERM <- function() {
pos <- 1
envir <- as.environment(pos)
if (!exists(".GOTERM_Env", envir=envir)) {
assign(".GOTERM_Env", new.env(), envir)
}
GOTERM_Env <- get(".GOTERM_Env", envir = envir)
if (exists("GOTERM.df", envir = GOTERM_Env)) {
GOTERM.df <- get("GOTERM.df", envir=GOTERM_Env)
} else {
GOTERM.df <- toTable(GOTERM)
assign("GOTERM.df", GOTERM.df, envir = GOTERM_Env)
}
return(GOTERM.df)
}
get_GO2TERM_table <- function() {
GOTERM.df <- get_GOTERM()
GOTERM.df[, c("go_id", "Term")] %>% unique
}
get_GO2Ontology_table <- function() {
GOTERM.df <- get_GOTERM()
GOTERM.df[, c("go_id", "Ontology")] %>% unique
}
excludeGOlevel <- function(x, ont, level) {
lv <- unlist(lapply(level, getGOLevel, ont=ont))
x <- excludeGOterm(x, lv)
return(x)
}
excludeGOterm <- function(x, term) {
if ( is(x, "enrichResult") ) {
x@result <- x@result[! x@result[, "ID"] %in% term, ]
} else if ( is(x, "compareClusterResult") ) {
x@compareClusterResult <- x@compareClusterResult[! x@compareClusterResult[, "ID"] %in% term, ]
} else {
stop("x should be one of enrichResult of compareClusterResult...")
}
return(x)
}
keepGOlevel <- function(x, ont, level) {
lv <- unlist(lapply(level, getGOLevel, ont=ont))
x <- keepGOterm(x, lv)
return(x)
}
keepGOterm <- function(x, term) {
if ( is(x, "enrichResult") ) {
x@result <- x@result[x@result[, "ID"] %in% term, ]
} else if ( is(x, "compareClusterResult") ) {
x@compareClusterResult <- x@compareClusterResult[x@compareClusterResult[, "ID"] %in% term, ]
} else {
stop("x should be one of enrichResult of compareClusterResult...")
}
return(x)
}
getGOLevel <- function(ont, level) {
switch(ont,
MF = {
topNode <- "GO:0003674"
Children <- GOMFCHILDREN
},
BP = {
topNode <- "GO:0008150"
Children <- GOBPCHILDREN
},
CC = {
topNode <- "GO:0005575"
Children <- GOCCCHILDREN
}
)
max_level <- max(level)
if (any(level == 1)) {
all_nodes <- topNode
} else {
all_nodes <- c()
}
Node <- topNode
for (i in seq_len(max_level-1)) {
Node <- mget(Node, Children, ifnotfound=NA)
Node <- unique(unlist(Node))
Node <- as.vector(Node)
Node <- Node[!is.na(Node)]
if ((i+1) %in% level) {
all_nodes <- c(all_nodes, Node)
}
}
return(all_nodes)
}
add_GO_Ontology <- function(obj, GO_DATA) {
if (is(obj, 'gseaResult')) {
obj@setType <- "GOALL"
} else if (is(obj, 'enrichResult')) {
obj@ontology <- 'GOALL'
}
df <- obj@result
GO2ONT <- get("GO2ONT", envir=GO_DATA)
df <- cbind(ONTOLOGY=GO2ONT[df$ID], df)
obj@result <- df
return(obj)
}
get_go_ontology <- function(x) {
if (is(x, "compareClusterResult")) {
if (x@fun != "enrichGO" && x@fun != "groupGO" && x@fun != "gseGO") {
stop("simplify only work for GO...")
}
ont <- [email protected]$ont
if (is.null(ont) || class(ont) != "character") {
ont <- x@compareClusterResult$ID[1] %>% GOTERM[[.]] %>% Ontology
}
} else if (is(x, "enrichResult")) {
if (!x@ontology %in% c("BP", "MF", "CC"))
stop("ontology should be one of 'MF', 'BP', 'CC'...")
ont <- x@ontology
} else {
stop("x should be an instance of 'enrichResult' or 'compareClusterResult'...")
}
return(ont)
} |
setPredictThreshold = function(learner, predict.threshold) {
learner = checkLearner(learner, type = "classif")
if (learner$predict.type != "prob") {
stopf("predict.type = 'prob' must hold to set a predict.threshold!")
}
assertNumeric(predict.threshold, any.missing = FALSE)
learner$predict.threshold = predict.threshold
return(learner)
} |
xgb.max_mcc <- function(pred, dtrain) {
y_true <- getinfo(dtrain, "label")
DT <- data.table(y_true = y_true, y_prob = pred, key = "y_prob")
cleaner <- !duplicated(DT[, "y_prob"], fromLast = TRUE)
nump <- sum(y_true)
numn <- length(y_true) - nump
DT[, tn_v := as.numeric(cumsum(y_true == 0))]
DT[, fp_v := cumsum(y_true == 1)]
DT[, fn_v := numn - tn_v]
DT[, tp_v := nump - fp_v]
DT <- DT[cleaner, ]
DT[, mcc := (tp_v * tn_v - fp_v * fn_v) / sqrt((tp_v + fp_v) * (tp_v + fn_v) * (tn_v + fp_v) * (tn_v + fn_v))]
best_row <- which.max(DT$mcc)
if (length(best_row) > 0) {
return(list(metric = "mcc", value = DT$mcc[best_row[1]]))
} else {
return(list(metric = "mcc", value = -1))
}
} |
predict_new <- function(model, ...) {
UseMethod("predict_new")
}
process.data.predict.new <- function(model, obj, X=NULL, weight=NULL,
U=NULL, U_bin=NULL,
items=NULL, rows=NULL,
exact=FALSE) {
if (obj$info$only_prediction_info)
stop("Cannot use this function after dropping non-essential matrices.")
exact <- check.bool(exact)
if (!NROW(items))
stop("'items' cannot be empty.")
if (NROW(obj$info$item_mapping))
items <- as.integer(factor(items, obj$info$item_mapping))
if (inherits(items, c("numeric", "character", "matrix")))
items <- as.integer(items)
if (!inherits(items, "integer"))
stop("Invalid 'items'.")
items <- items - 1L
inputs <- process.data.factors(model, obj, X=X, weight=weight,
U=U, U_bin=U_bin,
exact=exact,
matched_shapes=FALSE)
m_max <- max(c(inputs$processed_X$m, inputs$processed_U$m, inputs$processed_U_bin$m))
if (m_max == 1L)
rows <- rep(1L, NROW(items))
if (!is.null(rows)) {
if (NROW(obj$info$item_mapping))
rows <- as.integer(factor(rows, obj$info$user_mapping))
if (inherits(rows, c("numeric", "character", "matrix")))
rows <- as.integer(rows)
if (!inherits(rows, "integer"))
stop("Invalid 'rows'.")
if (NROW(rows) != NROW(items)) {
if (NROW(rows) == 1L) {
rows <- rep(rows, NROW(items))
} else {
stop("'rows' and 'item' must have the same number of entries.")
}
}
} else {
if (NROW(items) != m_max)
stop("Number of entries from 'X'/'U' does not match with entries in 'item'.")
rows <- seq(1L, NROW(items))
}
rows <- rows - 1L
return(list(
rows = rows,
items = items,
m_max = m_max,
exact = exact,
processed_X = inputs$processed_X,
processed_U = inputs$processed_U,
processed_U_bin = inputs$processed_U_bin
))
}
predict_new.CMF <- function(model, items, rows=NULL,
X=NULL, U=NULL, U_bin=NULL, weight=NULL, ...) {
inputs <- process.data.predict.new("CMF", model, X = X, weight = weight,
U = U, U_bin = U_bin,
items = items, rows = rows)
n_predict <- NROW(inputs$rows)
scores <- numeric(length = n_predict)
ret_code <- .Call(call_predict_X_new_collective_explicit,
inputs$m_max,
inputs$rows, inputs$items, scores,
model$info$nthreads,
as.logical(NROW(model$matrices$user_bias)),
inputs$processed_U$Uarr, inputs$processed_U$m, inputs$processed_U$p,
model$info$NA_as_zero_user, model$info$NA_as_zero,
model$info$nonneg,
inputs$processed_U$Urow, inputs$processed_U$Ucol, inputs$processed_U$Uval,
inputs$processed_U$Ucsr_p, inputs$processed_U$Ucsr_i, inputs$processed_U$Ucsr,
inputs$processed_U_bin$Uarr, inputs$processed_U_bin$m, inputs$processed_U_bin$p,
model$matrices$C, model$matrices$Cb,
model$matrices$glob_mean, model$matrices$item_bias,
model$matrices$U_colmeans,
inputs$processed_X$Xval, inputs$processed_X$Xrow, inputs$processed_X$Xcol,
inputs$processed_X$Xcsr_p, inputs$processed_X$Xcsr_i, inputs$processed_X$Xcsr,
inputs$processed_X$Xarr, inputs$processed_X$n,
inputs$processed_X$Warr, inputs$processed_X$Wsp,
model$matrices$B,
model$matrices$Bi, model$info$add_implicit_features,
model$info$k, model$info$k_user, model$info$k_item, model$info$k_main,
model$info$lambda, model$info$l1_lambda,
model$info$scale_lam, model$info$scale_lam_sideinfo,
model$info$scale_bias_const, model$matrices$scaling_biasA,
model$info$w_main, model$info$w_user, model$info$w_implicit,
NCOL(model$matrices$B), model$info$include_all_X,
model$precomputed$BtB,
model$precomputed$TransBtBinvBt,
model$precomputed$BtXbias,
model$precomputed$BeTBeChol,
model$precomputed$BiTBi,
model$precomputed$TransCtCinvCt,
model$precomputed$CtC,
model$precomputed$B_plus_bias,
model$precomputed$CtUbias)
check.ret.code(ret_code)
return(scores)
}
predict_new.CMF_implicit <- function(model, items, rows=NULL,
X=NULL, U=NULL, ...) {
inputs <- process.data.predict.new("CMF_implicit", model, X = X,
U = U,
items = items, rows = rows)
n_predict <- NROW(inputs$rows)
scores <- numeric(length = n_predict)
lambda <- ifelse(NROW(model$info$lambda) == 6L, model$info$lambda[3L], model$info$lambda)
l1_lambda <- ifelse(NROW(model$info$l1_lambda) == 6L, model$info$l1_lambda[3L], model$info$l1_lambda)
ret_code <- .Call(call_predict_X_new_collective_implicit,
inputs$m_max,
inputs$rows, inputs$items, scores,
model$info$nthreads,
inputs$processed_U$Uarr, inputs$processed_U$m, inputs$processed_U$p,
model$info$NA_as_zero_user,
model$info$nonneg,
inputs$processed_U$Urow, inputs$processed_U$Ucol, inputs$processed_U$Uval,
inputs$processed_U$Ucsr_p, inputs$processed_U$Ucsr_i, inputs$processed_U$Ucsr,
inputs$processed_X$Xval, inputs$processed_X$Xrow, inputs$processed_X$Xcol,
inputs$processed_X$Xcsr_p, inputs$processed_X$Xcsr_i, inputs$processed_X$Xcsr,
model$matrices$B, NCOL(model$matrices$B),
model$matrices$C,
model$matrices$U_colmeans,
model$info$k, model$info$k_user, model$info$k_item, model$info$k_main,
lambda, l1_lambda, model$info$alpha, model$info$w_main, model$info$w_user,
model$info$w_main_multiplier,
model$info$apply_log_transf,
model$precomputed$BeTBe,
model$precomputed$BtB,
model$precomputed$BeTBeChol,
model$precomputed$CtUbias)
check.ret.code(ret_code)
return(scores)
}
predict_new.OMF_explicit <- function(model, items, rows=NULL,
X=NULL, U=NULL, weight=NULL,
exact=FALSE, ...) {
inputs <- process.data.predict.new("OMF_explicit", model, X = X, weight = weight,
U = U,
items = items, rows = rows,
exact = exact)
n_predict <- NROW(inputs$rows)
scores <- numeric(length = n_predict)
ret_code <- .Call(call_predict_X_new_offsets_explicit,
inputs$m_max, as.logical(NROW(model$matrices$user_bias)),
inputs$rows, inputs$items, scores,
model$info$nthreads,
inputs$processed_U$Uarr, inputs$processed_U$p,
inputs$processed_U$Urow, inputs$processed_U$Ucol, inputs$processed_U$Uval,
inputs$processed_U$Ucsr_p, inputs$processed_U$Ucsr_i, inputs$processed_U$Ucsr,
inputs$processed_X$Xval, inputs$processed_X$Xrow, inputs$processed_X$Xcol,
inputs$processed_X$Xcsr_p, inputs$processed_X$Xcsr_i, inputs$processed_X$Xcsr,
inputs$processed_X$Xarr, NCOL(model$matrices$Bm),
inputs$processed_X$Warr, inputs$processed_X$Wsp,
model$matrices$Bm, model$matrices$C,
model$matrices$C_bias,
model$matrices$glob_mean, model$matrices$item_bias,
model$info$k, model$info$k_sec, model$info$k_main,
model$info$w_user,
model$info$lambda, inputs$exact,
model$precomputed$TransBtBinvBt,
model$precomputed$BtB,
model$precomputed$Bm_plus_bias)
check.ret.code(ret_code)
return(scores)
}
predict_new.OMF_implicit <- function(model, items, rows=NULL,
X=NULL, U=NULL, ...) {
inputs <- process.data.predict.new("OMF_implicit", model, X = X,
U = U,
items = items, rows = rows)
n_predict <- NROW(inputs$rows)
scores <- numeric(length = n_predict)
ret_code <- .Call(call_predict_X_new_offsets_implicit,
inputs$m_max,
inputs$rows, inputs$items, scores,
NCOL(model$matrices$Bm),
model$info$nthreads,
inputs$processed_U$Uarr, inputs$processed_U$p,
inputs$processed_U$Urow, inputs$processed_U$Ucol, inputs$processed_U$Uval,
inputs$processed_U$Ucsr_p, inputs$processed_U$Ucsr_i, inputs$processed_U$Ucsr,
inputs$processed_X$Xval, inputs$processed_X$Xrow, inputs$processed_X$Xcol,
inputs$processed_X$Xcsr_p, inputs$processed_X$Xcsr_i, inputs$processed_X$Xcsr,
model$matrices$Bm, model$matrices$C,
model$matrices$C_bias,
model$info$k,
model$info$lambda, model$info$alpha,
model$info$apply_log_transf,
model$precomputed$BtB)
check.ret.code(ret_code)
return(scores)
}
predict_new.ContentBased <- function(model, items=NULL, rows=NULL,
U=NULL, I=NULL, ...) {
if (!NROW(U))
stop("'U' cannot be empty")
if (!NROW(items) && !NROW(I))
stop("Must pass at least one of 'items' or 'I'.")
items_pass <- items
rows_pass <- rows
if (is.null(items))
items_pass <- 1L
if (is.null(rows))
rows_pass <- seq(1L, NROW(items_pass))
inputs <- process.data.predict.new("ContentBased", model,
U = U,
items = items_pass, rows = rows_pass)
if (!is.null(items))
items <- inputs$items
if (!is.null(rows))
rows <- inputs$rows
if (!is.null(I)) {
processed_I <- process.new.U(I, model$info$I_cols, NCOL(model$matrices$D),
allow_sparse=TRUE, allow_null=FALSE,
allow_na=FALSE, exact_shapes=TRUE)
if (!processed_I$m)
stop("'I' is empty.")
if (is.null(items)) {
if (is.null(rows)) {
if (processed_I$m != inputs$m_max)
stop("Number of rows in 'U' and 'I' do not match.")
n_predict <- inputs$m_max
} else {
items <- seq(1L, NROW(rows)) - 1L
n_predict <- NROW(rows)
}
} else {
if (NROW(rows) != NROW(items))
stop("'items' and 'rows' must have the same number of entries.")
n_predict <- NROW(rows)
}
if (is.null(items))
items <- integer()
if (is.null(rows))
rows <- integer()
scores <- numeric(length = n_predict)
ret_code <- .Call(call_predict_X_new_content_based,
scores,
inputs$processed_U$m, processed_I$m, model$info$k,
rows, items,
inputs$processed_U$Uarr, inputs$processed_U$p,
inputs$processed_U$Urow, inputs$processed_U$Ucol, inputs$processed_U$Uval,
inputs$processed_U$Ucsr_p, inputs$processed_U$Ucsr_i, inputs$processed_U$Ucsr,
processed_I$Uarr, processed_I$p,
processed_I$Urow, processed_I$Ucol, processed_I$Uval,
processed_I$Ucsr_p, processed_I$Ucsr_i, processed_I$Ucsr,
model$matrices$C, model$matrices$C_bias,
model$matrices$D, model$matrices$D_bias,
model$matrices$glob_mean,
model$info$nthreads)
} else {
if (is.null(rows)) {
if (inputs$processed_U$m == 1L) {
rows <- rep(0L, NROW(items))
} else {
rows <- seq(1L, inputs$processed_U$m) - 1L
}
}
n_predict <- NROW(items)
scores <- numeric(length = n_predict)
ret_code <- .Call(call_predict_X_new_offsets_explicit,
inputs$processed_U$m, FALSE,
rows, items, scores,
model$info$nthreads,
inputs$processed_U$Uarr, inputs$processed_U$p,
inputs$processed_U$Urow, inputs$processed_U$Ucol, inputs$processed_U$Uval,
inputs$processed_U$Ucsr_p, inputs$processed_U$Ucsr_i, inputs$processed_U$Ucsr,
numeric(), integer(), integer(),
raw(), integer(), numeric(),
numeric(), NCOL(model$matrices$Bm),
numeric(), numeric(),
model$matrices$Bm, model$matrices$C,
model$matrices$C_bias,
model$matrices$glob_mean, model$matrices$item_bias,
0L, model$info$k, 0L,
1.,
model$info$lambda, FALSE,
numeric(),
numeric(),
numeric())
}
check.ret.code(ret_code)
return(scores)
} |
terms.Rchoice <- function(x, ...){
terms(x$formula)
}
model.matrix.Rchoice <- function(object, ...){
X <- model.matrix(object$formula, object$mf)
if (has.intercept(object$formula, rhs = 1)) {
namesX <- colnames(X)
namesX[1L] <- "constant"
colnames(X) <- namesX
}
X
}
vcov.Rchoice <- function(object, what = c('coefficient', 'ranp'), type = c('cov', 'cor', 'sd'),
se = FALSE, digits = max(3, getOption("digits") - 2), ...)
{
what <- match.arg(what)
type <- match.arg(type)
if (what == 'coefficient') {
H <- object$logLik$hessian
if (object$family == "ordinal"){
bhat <- coef(object)
ahat <- attr(object$coefficients, "alphas")
J <- length(ahat)
A <- diag(length(bhat))
z.id <- seq(1, J, 1)
Jacob <- jacobian(ahat)
A[z.id, z.id] <- Jacob
result <- A %*% solve(-H) %*% t(A)
rownames(result) <- colnames(result) <- names(bhat)
} else {
result <- (solve(-H))
rownames(result) <- colnames(result) <- names(coef(object))
}
return(result)
}
if (what == 'ranp') {
if (se) {
if (type == 'cov') se.cov.Rchoice(object, sd = FALSE, digits = digits)
if (type == 'sd') se.cov.Rchoice(object, sd = TRUE, digits = digits)
if (type == 'cor') stop("standard error for correlation coefficients not implemented yet")
} else {
if (type == 'cov') print(cov.Rchoice(object))
if (type == 'cor') print(cor.Rchoice(object))
if (type == 'sd') print(sqrt(diag(cov.Rchoice(object))))
}
}
}
coef.Rchoice <- function(object, ...){
result <- object$coefficients
return(result)
}
fitted.Rchoice <- function(object, ...){
result <- object$probabilities
return(result)
}
residuals.Rchoice <- function(object, ...){
result <- object$residuals
result
}
df.residual.Rchoice <- function(object, ...){
n <- length(residuals(object))
K <- length(coef(object))
return(n - K)
}
update.Rchoice <- function(object, new, ...){
call <- object$call
if (is.null(call))
stop("need an object with call component")
extras <- match.call(expand.dots = FALSE)$...
if (!missing(new))
call$formula <- update(formula(object), new)
if (length(extras) > 0) {
existing <- !is.na(match(names(extras), names(call)))
for (a in names(extras)[existing]) call[[a]] <- extras[[a]]
if (any(!existing)) {
call <- c(as.list(call), extras[!existing])
call <- as.call(call)
}
}
eval(call, parent.frame())
}
AIC.Rchoice <- function(object, ..., k = 2) {
return(-2 * object$logLik$maximum[[1]] + k * length(coef(object)))
}
BIC.Rchoice <- function(object, ...) {
return(AIC(object, k = log(object$logLik$nobs)) )
}
logLik.Rchoice <- function(object,...){
structure(object$logLik$maximum[[1]], df = length(object$coefficients),
nobs = object$logLik$nobs, class = "logLik")
}
bread.Rchoice <- function(x, ... ) {
return( vcov( x ) * x$logLik$nobs)
}
estfun.Rchoice <- function(x, ... ) {
return(x$logLik$gradientObs )
}
print.Rchoice <- function(x, digits = max(3,getOption("digits") - 3),
width = getOption("width"), ...)
{
cat("\nCall:\n", deparse(x$call),"\n\n", sep = "")
cat("\nCoefficients:\n")
print.default(format(coef(x), digits = digits), print.gap = 2,
quote = FALSE)
cat("\n")
invisible(x)
}
summary.Rchoice <- function(object, ...){
b <- object$coefficients
std.err <- sqrt(diag(vcov(object)))
z <- b / std.err
p <- 2 * (1 - pnorm(abs(z)))
CoefTable <- cbind(b, std.err, z, p)
colnames(CoefTable) <- c("Estimate", "Std. Error", "z-value", "Pr(>|z|)")
object$CoefTable <- CoefTable
class(object) <- c("summary.Rchoice","Rchoice")
return(object)
}
print.summary.Rchoice <- function(x, digits = max(3, getOption("digits") - 3),
width = getOption("width"),
...)
{
cat(paste("\nModel:", x$family))
cat(paste("\nModel estimated on:", format(Sys.time(), "%a %b %d %X %Y"), "\n"))
cat("\nCall:\n")
cat(paste(deparse(x$call), sep = "\n", collapse = "\n"), "\n\n", sep = "")
if (!(x$family == "poisson")) {
cat("\nFrequencies of categories:\n")
print(prop.table(x$freq), digits = digits)
}
cat(paste("The estimation took:", make.time(x) ,"\n"))
cat("\nCoefficients:\n")
printCoefmat(x$CoefTable, digits = digits)
cat(paste("\nOptimization of log-likelihood by", x$logLik$type))
cat(paste("\nLog Likelihood:", signif(x$logLik$maximum, digits)))
cat(paste("\nNumber of observations:", x$logLik$nobs))
cat(paste("\nNumber of iterations:" , x$logLik$iterations))
cat(paste("\nExit of MLE:", x$logLik$message))
if (x$R.model) {
if (is.null(x$draws)) {
cat(paste("\nSimulation based on", x$R, "pseudo-random draws"))
}else {
cat(paste("\nSimulation based on", x$R, "Halton draws"))
}
}
invisible(x)
}
getSummary.Rchoice <- function(obj, alpha = 0.05, ...){
smry <- summary(obj)
coef <- smry$CoefTable
lower <- coef[, 1] - coef[, 2] * qnorm(alpha/2)
upper <- coef[, 1] + coef[, 2] * qnorm(alpha/2)
coef <- cbind(coef, lower, upper)
colnames(coef) <- c("est", "se", "stat", "p", "lwr", "upr")
N <- obj$logLik$nobs
ll <- logLik(obj)
sumstat <- c(logLik = ll, deviance = NA, AIC = AIC(obj), BIC = BIC(obj), N = N,
LR = NA, df = NA, p = NA, Aldrich.Nelson = NA, McFadden = NA, Cox.Snell = NA,
Nagelkerke = NA)
list(coef = coef, sumstat = sumstat, contrasts = obj$contrasts,
xlevels = NULL, call = obj$call)
}
plot.Rchoice <- function(x, par = NULL, effect = c("ce", "cv"), wrt = NULL,
type = c("density", "histogram"), adjust = 1,
main = NULL, col = "indianred1", breaks = 10, ylab = NULL,
xlab = NULL, ind = FALSE, id = NULL, ...){
if (!x$R.model) stop("the plot method is only relevant for random parameters")
if (is.null(par)) stop("Must specified the name of the random parameters")
type <- match.arg(type)
effect <- match.arg(effect)
if (is.null(xlab)) {
xlab <- switch(effect,
"cv" = expression(E(hat(cv[i]))),
"ce" = expression(E(hat(beta[i]))))
}
if (!ind) {
if (is.null(main)) main <- paste("Conditional Distribution for", par)
if (is.null(ylab)) {
ylab <- switch(type,
"density" = "Density",
"histogram" = "Frequency")
}
rpar <- effect.Rchoice(x, par, effect = effect, wrt = wrt)$mean
if (type == "density") {
pdens <- density(rpar, adjust = adjust)
plot(pdens, ylab = ylab, xlab = xlab, main = main, col = col)
has.pos <- any(pdens$x > 0)
if (has.pos) {
x1 <- min(which(pdens$x >= 0))
x2 <- max(which(pdens$x < max(pdens$x)))
with(pdens, polygon(x = c(x[c(x1, x1:x2, x2)]), y = c(0, y[x1:x2], 0),
col = col, border = NA))
}
} else {
minb <- round(min(rpar), 2)
maxb <- round(max(rpar), 2)
hist(rpar, xlab = xlab, main = main, col = col, breaks = breaks,
xaxs = "i", yaxs = "i", las = 1, xaxt = 'n', ylab = ylab)
axis(1, at = seq(minb, maxb, (maxb - minb) * .05))
}
}
else{
if (is.null(main)) main <- paste("95% Probability Intervals for ", par)
if (is.null(id)) id <- seq(1, 10, 1)
if (is.null(ylab)) ylab <- "Individuals"
f.bran <- effect.Rchoice(x, par, effect = effect, wrt = wrt)$mean
f.sran <- effect.Rchoice(x, par, effect = effect, wrt = wrt)$sd.est
lower <- f.bran - qnorm(0.975) * f.sran
upper <- f.bran + qnorm(0.975) * f.sran
plotrix::plotCI(as.numeric(id), f.bran[id], ui = upper[id], li = lower[id],
xlab = ylab, ylab = xlab,
lty = 2, main = main,
pch = 21, col = col)
}
}
cov.Rchoice <- function(x){
if (!inherits(x, "Rchoice")) stop("not a \"Rchoice\" object")
if (is.null(x$ranp)) stop('\"cov.Rchoice\" only relevant for random coefficient model')
beta.hat <- coef(x)
K <- length(x$ranp)
nr <- names(x$ranp)
if (x$correlation) {
names.stds <- c()
for (i in 1:K) names.stds <- c(names.stds, paste('sd', nr[i], nr[i:K], sep = '.'))
v <- beta.hat[names.stds]
V <- tcrossprod(makeL(v))
colnames(V) <- rownames(V) <- nr
} else{
names.stds <- paste("sd", nr, sep = ".")
sv <- beta.hat[names.stds]
V <- matrix(0, K, K)
diag(V) <- sv ^ 2
colnames(V) <- rownames(V) <- nr
}
V
}
cor.Rchoice <- function(x){
if (!x$correlation) stop('\"cor.Rchoice\" only relevant for correlated random coefficient model')
V <- cov.Rchoice(x)
nr <- names(x$ranp)
D <- diag(sqrt(diag(V)))
Rho <- solve(D) %*% V %*% solve(D)
colnames(Rho) <- rownames(Rho) <- nr
Rho
}
effect.Rchoice <- function(x, par = NULL, effect = c("cv", "ce"), wrt = NULL, ... ){
if (!inherits(x, "Rchoice")) stop("not a \"Rchoice\" object")
type <- match.arg(effect)
ranp <- x$ranp
if (!is.null(par) && !(par %in% names(ranp))) stop("This parameter is not random: ", par)
bi <- x$bi
Qir <- x$Qir
R <- ncol(Qir)
N <- nrow(Qir)
K <- dim(bi)[[3]]
mean <- mean.sq <- array(NA, dim = c(N, R, K))
for (j in 1:K) {
if (type == "cv") {
if (is.null(wrt)) stop("you need to specify wrt")
is.ran <- any(names(ranp) %in% wrt)
gamma <- if (is.ran) bi[, , wrt] else coef(x)[wrt]
mean[, , j] <- (bi[, , j] / gamma) * Qir
mean.sq[, , j] <- ((bi[, , j] / gamma) ^ 2 ) * Qir
} else {
mean[, , j] <- bi[, , j] * Qir
mean.sq[, , j] <- (bi[, , j] ^ 2) * Qir
}
}
mean <- apply(mean, c(1,3), sum)
mean.sq <- apply(mean.sq, c(1,3), sum)
sd.est <- suppressWarnings(sqrt(mean.sq - mean ^ 2))
colnames(mean) <- colnames(mean.sq) <- colnames(sd.est) <- dimnames(bi)[[3]]
rownames(mean) <- rownames(mean.sq) <- rownames(sd.est) <- dimnames(bi)[[1]]
if (!is.null(par)) {
mean <- mean[, par]
sd.est <- sd.est[, par]
}
effe <- list(mean = mean,
sd.est = sd.est)
return(effe)
}
se.cov.Rchoice <- function(x, sd = FALSE, digits = max(3, getOption("digits") - 2)){
if (!inherits(x, "Rchoice")) stop("not a \"Rchoice\" object")
if (!x$correlation) stop('se.cov.Rchoice only relevant for correlated random coefficient')
beta.hat <- x$coefficients
Ka <- length(x$ranp)
nr <- names(x$ranp)
names.stds <- c()
for (i in 1:Ka) names.stds <- c(names.stds, paste('sd', nr[i], nr[i:Ka], sep = '.'))
stds.hat <- beta.hat[names.stds]
sel.vcov <- vcov(x)[names.stds, names.stds]
form <- c()
if (sd) {
for (i in 1:Ka) {
k <- i
if (i == 1) {
form <- paste("~ sqrt(", c(form, paste(paste("x", i, sep = ""), paste("x", k, sep = ""), sep = "*")), ")")
} else {
temp <- paste(paste("x", i, sep = ""), paste("x", k, sep = ""), sep = "*")
j <- 2
while (j <= i) {
temp <- paste(temp, make.add(row = j, col = k, Ka = Ka)[1], sep = "+")
j <- j + 1
}
form <- c(form, paste("~ sqrt(", temp, ")"))
}
}
b <- sqrt(diag(cov.Rchoice(x)))
names(b) <- colnames(cov.Rchoice(x))
} else {
for (i in 1:Ka) {
if (i == 1) {
form <- paste("~", c(form, paste(paste("x", i:Ka, sep = ""), paste("x", i, sep = ""), sep = "*")))
} else {
temp <- paste(paste("x", i:Ka, sep = ""), paste("x", i, sep = ""), sep = "*")
j <- 2
while (j <= i) {
temp <- paste(temp, make.add(row = j, col = i, Ka = Ka), sep = "+")
j <- j + 1
}
form <- c(form, paste("~", temp))
}
}
names.vcov <- c()
for (i in 1:Ka) names.vcov <- c(names.vcov, paste('v', nr[i], nr[i:Ka], sep = '.'))
b <- drop(cov.Rchoice(x)[lower.tri(cov.Rchoice(x), diag = TRUE)])
names(b) <- names.vcov
}
std.err <- c()
for (i in 1:length(form)) {
std.err <- c(std.err, msm::deltamethod(as.formula(form[i]), stds.hat, sel.vcov, ses = TRUE))
}
z <- b / std.err
p <- 2 * (1 - pnorm(abs(z)))
tableChol <- cbind(b, std.err, z, p)
if (!sd) cat(paste("\nElements of the variance-covariance matrix \n\n"))
else cat(paste("\nStandard deviations of the random parameters \n\n"))
colnames(tableChol) <- c("Estimate", "Std. Error", "z-value", "Pr(>|z|)")
printCoefmat(tableChol, digits = digits)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.