code
stringlengths 1
13.8M
|
---|
mapdeckGeojsonDependency <- function() {
list(
createHtmlDependency(
name = "geojson",
version = "1.0.0",
src = system.file("htmlwidgets/lib/geojson", package = "mapdeck"),
script = c("geojson.js"),
all_files = FALSE
)
)
}
add_geojson <- function(
map,
data = get_map_data(map),
layer_id = NULL,
stroke_colour = NULL,
stroke_opacity = NULL,
stroke_width = NULL,
dash_size = NULL,
dash_gap = NULL,
fill_colour = NULL,
fill_opacity = NULL,
radius = NULL,
elevation = NULL,
extruded = FALSE,
light_settings = list(),
legend = F,
legend_options = NULL,
legend_format = NULL,
auto_highlight = FALSE,
tooltip = NULL,
highlight_colour = "
palette = "viridis",
na_colour = "
line_width_units = c("meters", "pixels"),
line_width_scale = 1,
line_width_min_pixels = 0,
elevation_scale = 1,
point_radius_scale = 1,
point_radius_min_pixels = 1,
update_view = TRUE,
focus_layer = FALSE,
digits = 6,
transitions = NULL
) {
l <- list()
line_width_units <- match.arg(line_width_units)
l[["stroke_colour"]] <- force( stroke_colour )
l[["stroke_opacity"]] <- force( stroke_opacity )
l[["stroke_width"]] <- force( stroke_width )
l[["dash_size"]] <- force(dash_size)
l[["dash_gap"]] <- force(dash_gap)
l[["fill_colour"]] <- force( fill_colour )
l[["fill_opacity"]] <- force( fill_opacity )
l[["elevation"]] <- force( elevation )
l[["radius"]] <- force( radius )
l[["tooltip"]] <- force( tooltip )
l[["na_colour"]] <- force(na_colour)
bbox <- init_bbox()
update_view <- force( update_view )
focus_layer <- force( focus_layer )
if ( any (
!is.null( l[["stroke_colour"]] ) |
!is.null( l[["stroke_opacity"]] ) |
!is.null( l[["stroke_width"]] ) |
!is.null( l[["dash_size"]] ) |
!is.null( l[["dash_gap"]] ) |
!is.null( l[["fill_colour"]] ) |
!is.null( l[["fill_opacity"]] ) |
!is.null( l[["elevation"]] ) |
!is.null( l[["radius"]] )
) ) {
if( inherits( data, "geojson" ) | inherits( data, "json" ) | inherits( data, "character" ) ) {
data <- geojsonsf::geojson_sf( data )
}
}
l <- resolve_palette( l, palette )
l <- resolve_legend( l, legend )
l <- resolve_legend_options( l, legend_options )
l <- resolve_geojson_data( data, l )
line_width_units <- match.arg(line_width_units)
if( !is.null(l[["data"]] ) ) {
data <- l[["data"]]
l[["data"]] <- NULL
}
if( !is.null( l[["bbox"]] ) ) {
bbox <- l[["bbox"]]
l[["bbox"]] <- NULL
}
layer_id <- layerId( layer_id, "geojson" )
tp <- l[["data_type"]]
l[["data_type"]] <- NULL
if( tp == "sf" ) {
shape <- rcpp_geojson_geojson( data, l, "geometry", digits)
jsfunc <- "add_geojson_sf"
} else if ( tp == "geojson" ) {
jsfunc <- "add_geojson"
shape <- list()
shape[["data"]] <- data
}
light_settings <- jsonify::to_json(light_settings, unbox = T)
js_transitions <- resolve_transitions( transitions, "geojson" )
map <- addDependency(map, mapdeckGeojsonDependency())
if( inherits( legend, "json" ) ) {
shape[["legend"]] <- legend
} else {
shape[["legend"]] <- resolve_legend_format( shape[["legend"]], legend_format )
}
invoke_method(
map, jsfunc, map_type( map ), shape[["data"]], layer_id, light_settings, auto_highlight,
highlight_colour, shape[["legend"]], bbox, update_view, focus_layer,
js_transitions, line_width_units, line_width_scale, line_width_min_pixels,
elevation_scale, point_radius_scale, point_radius_min_pixels, extruded
)
}
clear_geojson <- function( map, layer_id = NULL, update_view = TRUE ) {
layer_id <- layerId(layer_id, "geojson")
invoke_method(map, "md_layer_clear", map_type( map ), layer_id, "geojson", update_view )
} |
parUpdate <-
function(cl, object, n.iter = 1, ...)
{
requireNamespace("rjags")
cl <- evalParallelArgument(cl, quit=TRUE)
if (!inherits(cl, "cluster"))
stop("cl must be of class 'cluster'")
clusterEvalQ(cl, requireNamespace("rjags"))
if (!is.character(object))
object <- as.character(object)
cldata <- list(n.iter=n.iter, name=object)
jagsparallel <- function(i, ...) {
cldata <- pullDcloneEnv("cldata", type = "model")
if (existsDcloneEnv(cldata$name, type = "results")) {
res <- pullDcloneEnv(cldata$name,
type = "results")
update(object=res, n.iter=cldata$n.iter, ...)
pushDcloneEnv(cldata$name, res, type = "results")
}
NULL
}
parDosa(cl, 1:length(cl), jagsparallel, cldata,
lib = c("dclone", "rjags"), balancing = "none", size = 1,
rng.type = getOption("dcoptions")$RNG,
cleanup = TRUE,
dir = NULL,
unload = FALSE, ...)
} |
expected <- eval(parse(text="-0.133986975078774"));
test(id=0, code={
argv <- eval(parse(text="list(-0.133190890463189)"));
do.call(`atanh`, argv);
}, o=expected); |
unlink(test_path("dir_code/.binder"), recursive = TRUE) |
calibrate.BlackCox <- function(V0, cdsrate, r, t, ...){
if(!is.numeric(V0)) stop("V0 must be a number")
if(length(V0) != 1) stop("V0 must be a number and not a vector")
if(!is.numeric(r)) stop("r must be a number")
if(length(r) != 1) stop("r must be constant for all maturities")
if(!is.numeric(cdsrate)) stop("cdsrate must be a numeric vector")
if(!is.numeric(t)) stop("Time t must be a numeric vector")
if(length(cdsrate) != length(t)) stop("cdsrate and t must have the same length")
objfn <- function(par, cdsrate, r, t){
L <- par[1]
K <- par[1] - par[2]
sigma <- abs(par[3])
gamma <- par[4]
intensity <- BlackCox(L = L, K = K, V0 = V0, sigma = sigma, r = r, gamma = gamma, t = t)$Default.Intensity
rate <- cds(t = t, int = intensity, r = r, ...)$Rate
err <- mean((rate - cdsrate)^2)
return(err)
}
par <- c(V0/2, (0.15 * V0/2), 0.2, 0.08)
out <- stats::optim(par = par, fn = objfn, cdsrate = cdsrate, t = t, r = r, method = 'L-BFGS-B', lower = 0 * t)
out <- c(V0, par[1], (par[1] - par[2]), abs(out$par[3]), out$par[4], out$value)
names(out) <- c('V0', 'L', 'K', 'sigma', 'gamma', 'Error')
return(data.frame(t(out)))
} |
\dontrun{
library(listviewer)
library(reactR)
reactjson()
reactjson(head(mtcars,4))
reactjson(I(jsonlite::toJSON(head(mtcars,5))))
library(shiny)
shinyApp(
ui = reactjson(
list(x=1,msg="react+r+shiny",opts=list(use_react=FALSE)),
elementId = "json1"
),
server = function(input, output, session){
observeEvent(
input$json1_change,
str(input$json1_change)
)
}
)
library(miniUI)
ui <- miniUI::miniPage(
miniUI::miniContentPanel(
reactjson(
list(x=1,msg="react+r+shiny",opts=list(use_react=FALSE)),
elementId = "rjeditor"
)
),
miniUI::gadgetTitleBar(
"Edit",
right = miniUI::miniTitleBarButton("done", "Done", primary = TRUE)
)
)
server <- function(input, output, session) {
shiny::observeEvent(input$done, {
shiny::stopApp(
input$rjeditor_change
)
})
shiny::observeEvent(input$cancel, { shiny::stopApp (NULL) })
}
runGadget(
ui,
server,
viewer = shiny::paneViewer()
)
} |
fixedGlmer <-
function(model,observ,fam_link) {
rand_terms<- sapply(findbars(formula(model)),function(x) paste0("(", deparse(x), ")"))
drop_form<- list()
resp_term<- sapply(nobars(formula(model)),function(x) deparse(x))[2]
fixed_terms<- paste(attributes(terms(model))$term.labels)
ftable<- data.frame(term=fixed_terms)
ftable$d.AIC<- NA;ftable$d.BIC<- NA;ftable$Chi.sq<- NA; ftable$p.value<- NA
for (i in 1:length(fixed_terms)) {
drop_form[[i]] <- reformulate(c(rand_terms,fixed_terms[-i]),response=resp_term)
m_new<- glmer(formula=drop_form[[i]],family=fam_link,data=observ)
p_mod<- anova(model,m_new)
ftable[,-1][i,]<-c(p_mod$AIC[1]-p_mod$AIC[2],p_mod$BIC[1]-p_mod$BIC[2],p_mod$Chisq[2],p_mod$'Pr(>Chisq)'[2]) }
invisible(ftable)
} |
lrt2.org <- function(PV.gbd, CLASS.gbd, K, H0.mean = 0.05,
upper.beta = .FC.CT$INIT$BETA.beta.max){
if((H0.mean <= 0) || (H0.mean >= 0.5)){
stop("It should be 0 < H0.mean < 0.5.")
}
K.CLASS <- as.integer(max.gbd(CLASS.gbd))
if(K.CLASS > K){
stop("CLASS.gbd and K are not matched.")
}
beta.scale <- H0.mean / (1 - H0.mean)
fn.H0 <- function(theta, x.gbd){
-sum.gbd(dbeta(x.gbd, beta.scale * theta[1], theta[1], log = TRUE))
}
fn.Ha <- function(theta, x.gbd){
-sum.gbd(dbeta(x.gbd, theta[1], theta[2], log = TRUE))
}
ui.Ha <- rbind(c(1, 0), c(H0.mean - 1, H0.mean))
ci.Ha <- c(0, 0)
ret <- NULL
for(i.k in 1:K){
N.class.gbd <- sum.gbd(CLASS.gbd == i.k)
if(N.class.gbd > 0){
tmp.gbd <- PV.gbd[CLASS.gbd == i.k]
tmp <- optim(c(1.01), fn.H0, NULL, x.gbd = tmp.gbd,
method = "Brent", lower = 0, upper = upper.beta)
H0.beta <- tmp$par[1]
H0.alpha <- beta.scale * H0.beta
logL.0 <- -tmp$value
tmp <- constrOptim(c(beta.scale * 0.99, 1.01), fn.Ha, NULL, ui.Ha, ci.Ha,
method = "Nelder-Mead", x.gbd = tmp.gbd)
Ha.alpha <- tmp$par[1]
Ha.beta <- tmp$par[2]
logL.a <- -tmp$value
lrt <- -2 * (logL.0 - logL.a)
if(lrt < 0){
lrt <- 0
}
p.value <- pchisq(lrt, 1, lower.tail = FALSE)
ret <- rbind(ret, c(i.k, H0.beta, Ha.alpha, Ha.beta,
logL.0, logL.a, lrt, p.value))
} else{
ret <- rbind(ret, c(i.k, rep(NA, 7)))
}
}
colnames(ret) <- c("i.k", "mle.0.beta",
"mle.a.alpha", "mle.a.beta",
"logL.0", "logL.a", "lrt", "p.value")
ret
} |
map_ggmap <- function(...) .Defunct() |
myALS_SVD <- function(Xn, k, L2=1e-10, iter=30){
nr <- nrow(Xn)
nc <- ncol(Xn)
U <- .normMat(matrix(runif(nr*k), nrow=nr, ncol=k), "column")
V <- .normMat(matrix(runif(k*nc), nrow=k, ncol=nc), "row")
for(i in seq(iter)){
U <- .normMat(Xn %*% t(V) %*% ginv(V %*% t(V) + diag(L2, k, k)),
"column")
V <- ginv(t(U) %*% U + diag(L2, k, k)) %*% t(U) %*% Xn
}
U
} |
NULL
marketplaceentitlementservice <- function(config = list()) {
svc <- .marketplaceentitlementservice$operations
svc <- set_config(svc, config)
return(svc)
}
.marketplaceentitlementservice <- list()
.marketplaceentitlementservice$operations <- list()
.marketplaceentitlementservice$metadata <- list(
service_name = "entitlement.marketplace",
endpoints = list("*" = list(endpoint = "entitlement.marketplace.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "entitlement.marketplace.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "entitlement.marketplace.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "entitlement.marketplace.{region}.sc2s.sgov.gov", global = FALSE)),
service_id = "Marketplace Entitlement Service",
api_version = "2017-01-11",
signing_name = "aws-marketplace",
json_version = "1.1",
target_prefix = "AWSMPEntitlementService"
)
.marketplaceentitlementservice$service <- function(config = list()) {
handlers <- new_handlers("jsonrpc", "v4")
new_service(.marketplaceentitlementservice$metadata, handlers, config)
} |
FixedN5Cats <- function(kappa0, n, props, raters=2, alpha=0.05)
{
if ( (raters != 1) && (raters !=2) && (raters !=3) && (raters != 4) && (raters != 5) && (raters != 6) )
stop("Sorry, this function is designed for between 2 to 6 raters.")
if (length(props) != 5)
stop("Sorry, you must enter the anticipated proportions of each of the five categories.")
if ( abs( sum(props) - 1) >= 0.001 )
stop("Sorry, the three proportions must sum to one.")
for (i in 1:5)
{
if ((props[i] >= 1) || (props[i] <= 0) )
stop("Sorry, the proportion, props must lie within (0,1).")
}
if ((kappa0 >= 1) || (kappa0 <= 0) )
stop("Sorry, the null value of kappa must lie within (0,1).")
if (n <=10)
stop("Sorry, your study should enroll at least 10 subjects.")
if ( (alpha >= 1) || (alpha <= 0) )
stop("Sorry, the alpha and power must lie within (0,1).")
X <- NULL;
X$kappa0 <- kappa0;
X$n <- n;
X$props <- props;
X$raters <- raters;
X$alpha <- alpha;
X$ChiCrit <- qchisq((1-2*alpha),1);
if (raters == 2)
{
.CalcIT <- function(rho0, rho1, Pi, n)
{
P1 <- function(k, p)
{
x <- p[1]^2*(-(-p[1]-k+k*p[1])/p[1])
return(x)
}
P2 <- function(k, p)
{
x <- p[2]^2*(-(-p[2]-k+k*p[2])/p[2])
return(x)
}
P3 <- function(k, p)
{
x <- p[3]^2*(-(-p[3]-k+k*p[3])/p[3])
}
P4 <- function(k, p)
{
x <- p[4]^2*(-(-p[4]-k+k*p[4])/p[4])
}
P5 <- function(k, p)
{
x <- p[5]^2*(-(-p[5]-k+k*p[5])/p[5])
}
P0 <- function(k, p)
{
x <- 1 - P1(k,p) - P2(k,p) - P3(k,p) -P4(k,p) - P5(k,p);
return(x)
}
results <- c(0,0,0,0,0,0);
results[1] <- ( (n*P0(k=rho0, p=Pi)) - (n*P0(k=rho1, p = Pi)) )^2/ (n*P0(k=rho1, p = Pi))
results[2] <- ( (n*P1(k=rho0, p=Pi)) - (n*P1(k=rho1, p = Pi)) )^2/ (n*P1(k=rho1, p = Pi))
results[3] <- ( (n*P2(k=rho0, p=Pi)) - (n*P2(k=rho1, p = Pi)) )^2/ (n*P2(k=rho1, p = Pi))
results[4] <- ( (n*P3(k=rho0, p=Pi)) - (n*P3(k=rho1, p = Pi)) )^2/ (n*P3(k=rho1, p = Pi))
results[5] <- ( (n*P4(k=rho0, p=Pi)) - (n*P4(k=rho1, p = Pi)) )^2/ (n*P4(k=rho1, p = Pi))
results[6] <- ( (n*P5(k=rho0, p=Pi)) - (n*P5(k=rho1, p = Pi)) )^2/ (n*P5(k=rho1, p = Pi))
return(sum(results,na.rm=TRUE))
}
}
if (raters == 3)
{
.CalcIT <- function(rho0, rho1, Pi, n)
{
P1 <- function(k, p)
{
x <- p[1]^3*((p[1]^2+3*k*p[1]-2*k*p[1]^2+2*k^2-3*k^2*p[1]+k^2*p[1]^2)/p[1]^2)/(1+k)
return(x)
}
P2 <- function(k, p)
{
x <- p[2]^3*((p[2]^2+3*k*p[2]-2*k*p[2]^2+2*k^2-3*k^2*p[2]+k^2*p[2]^2)/p[2]^2)/(1+k)
return(x)
}
P3 <- function(k, p)
{
x <- p[3]^3*((p[3]^2+3*k*p[3]-2*k*p[3]^2+2*k^2-3*k^2*p[3]+k^2*p[3]^2)/p[3]^2)/(1+k)
return(x)
}
P4 <- function(k, p)
{
x <- p[4]^3*((p[4]^2+3*k*p[4]-2*k*p[4]^2+2*k^2-3*k^2*p[4]+k^2*p[4]^2)/p[4]^2)/(1+k)
return(x)
}
P5 <- function(k, p)
{
x <- p[5]^3*((p[5]^2+3*k*p[5]-2*k*p[5]^2+2*k^2-3*k^2*p[5]+k^2*p[5]^2)/p[5]^2)/(1+k)
return(x)
}
P0 <- function(k, p)
{
x <- 1 - P1(k,p) - P2(k,p) - P3(k,p) -P4(k,p) - P5(k,p);
return(x)
}
results <- c(0,0,0,0,0,0);
results[1] <- ( (n*P0(k=rho0, p=Pi)) - (n*P0(k=rho1, p = Pi)) )^2/ (n*P0(k=rho1, p = Pi))
results[2] <- ( (n*P1(k=rho0, p=Pi)) - (n*P1(k=rho1, p = Pi)) )^2/ (n*P1(k=rho1, p = Pi))
results[3] <- ( (n*P2(k=rho0, p=Pi)) - (n*P2(k=rho1, p = Pi)) )^2/ (n*P2(k=rho1, p = Pi))
results[4] <- ( (n*P3(k=rho0, p=Pi)) - (n*P3(k=rho1, p = Pi)) )^2/ (n*P3(k=rho1, p = Pi))
results[5] <- ( (n*P4(k=rho0, p=Pi)) - (n*P4(k=rho1, p = Pi)) )^2/ (n*P4(k=rho1, p = Pi))
results[6] <- ( (n*P5(k=rho0, p=Pi)) - (n*P5(k=rho1, p = Pi)) )^2/ (n*P5(k=rho1, p = Pi))
return(sum(results,na.rm=TRUE))
}
}
if (raters == 4)
{
.CalcIT <- function(rho0, rho1, Pi, n)
{
P1 <- function(k, p)
{
x <- -p[1]*(-p[1]^3-6*k*p[1]^2+3*k*p[1]^3-11*k^2*p[1]+12*k^2*p[1]^2-3*k^2*p[1]^3-6*k^3+11*k^3*p[1]-6*k^3*p[1]^2+k^3*p[1]^3)/((1+k)*(1+2*k))
return(x)
}
P2 <- function(k, p)
{
x <- -p[2]*(-p[2]^3-6*k*p[2]^2+3*k*p[2]^3-11*k^2*p[2]+12*k^2*p[2]^2-3*k^2*p[2]^3-6*k^3+11*k^3*p[2]-6*k^3*p[2]^2+k^3*p[2]^3)/((1+k)*(1+2*k))
return(x)
}
P3 <- function(k, p)
{
x <- -p[3]*(-p[3]^3-6*k*p[3]^2+3*k*p[3]^3-11*k^2*p[3]+12*k^2*p[3]^2-3*k^2*p[3]^3-6*k^3+11*k^3*p[3]-6*k^3*p[3]^2+k^3*p[3]^3)/((1+k)*(1+2*k))
return(x)
}
P4 <- function(k, p)
{
x <- -p[4]*(-p[4]^3-6*k*p[4]^2+3*k*p[4]^3-11*k^2*p[4]+12*k^2*p[4]^2-3*k^2*p[4]^3-6*k^3+11*k^3*p[4]-6*k^3*p[4]^2+k^3*p[4]^3)/((1+k)*(1+2*k))
return(x)
}
P5 <- function(k, p)
{
x <- -p[5]*(-p[5]^3-6*k*p[5]^2+3*k*p[5]^3-11*k^2*p[5]+12*k^2*p[5]^2-3*k^2*p[5]^3-6*k^3+11*k^3*p[5]-6*k^3*p[5]^2+k^3*p[5]^3)/((1+k)*(1+2*k))
return(x)
}
P0 <- function(k, p)
{
x <- 1 - P1(k,p) - P2(k,p) - P3(k,p) - P4(k,p) - P5(k,p);
return(x)
}
results <- c(0,0,0,0,0,0);
results[1] <- ( (n*P0(k=rho0, p=Pi)) - (n*P0(k=rho1, p = Pi)) )^2/ (n*P0(k=rho1, p = Pi))
results[2] <- ( (n*P1(k=rho0, p=Pi)) - (n*P1(k=rho1, p = Pi)) )^2/ (n*P1(k=rho1, p = Pi))
results[3] <- ( (n*P2(k=rho0, p=Pi)) - (n*P2(k=rho1, p = Pi)) )^2/ (n*P2(k=rho1, p = Pi))
results[4] <- ( (n*P3(k=rho0, p=Pi)) - (n*P3(k=rho1, p = Pi)) )^2/ (n*P3(k=rho1, p = Pi))
results[5] <- ( (n*P4(k=rho0, p=Pi)) - (n*P4(k=rho1, p = Pi)) )^2/ (n*P4(k=rho1, p = Pi))
results[6] <- ( (n*P5(k=rho0, p=Pi)) - (n*P5(k=rho1, p = Pi)) )^2/ (n*P5(k=rho1, p = Pi))
return(sum(results,na.rm=TRUE))
}
}
if (raters == 5)
{
.CalcIT <- function(rho0, rho1, Pi, n)
{
P1 <- function(k, p)
{
x <- p[1]*(p[1]^4+10*k*p[1]^3-4*k*p[1]^4+35*k^2*p[1]^2-30*k^2*p[1]^3+6*k^2*p[1]^4+50*k^3*p[1]-70*k^3*p[1]^2+30*k^3*p[1]^3-4*k^3*p[1]^4+24*k^4-50*k^4*p[1]+35*k^4*p[1]^2-10*k^4*p[1]^3+k^4*p[1]^4)/((1+k)*(1+2*k)*(1+3*k))
return(x)
}
P2 <- function(k, p)
{
x <- p[2]*(p[2]^4+10*k*p[2]^3-4*k*p[2]^4+35*k^2*p[2]^2-30*k^2*p[2]^3+6*k^2*p[2]^4+50*k^3*p[2]-70*k^3*p[2]^2+30*k^3*p[2]^3-4*k^3*p[2]^4+24*k^4-50*k^4*p[2]+35*k^4*p[2]^2-10*k^4*p[2]^3+k^4*p[2]^4)/((1+k)*(1+2*k)*(1+3*k))
return(x)
}
P3 <- function(k, p)
{
x <- p[3]*(p[3]^4+10*k*p[3]^3-4*k*p[3]^4+35*k^2*p[3]^2-30*k^2*p[3]^3+6*k^2*p[3]^4+50*k^3*p[3]-70*k^3*p[3]^2+30*k^3*p[3]^3-4*k^3*p[3]^4+24*k^4-50*k^4*p[3]+35*k^4*p[3]^2-10*k^4*p[3]^3+k^4*p[3]^4)/((1+k)*(1+2*k)*(1+3*k))
return(x)
}
P4 <- function(k, p)
{
x <- p[4]*(p[4]^4+10*k*p[4]^3-4*k*p[4]^4+35*k^2*p[4]^2-30*k^2*p[4]^3+6*k^2*p[4]^4+50*k^3*p[4]-70*k^3*p[4]^2+30*k^3*p[4]^3-4*k^3*p[4]^4+24*k^4-50*k^4*p[4]+35*k^4*p[4]^2-10*k^4*p[4]^3+k^4*p[4]^4)/((1+k)*(1+2*k)*(1+3*k))
return(x)
}
P5 <- function(k, p)
{
x <- p[5]*(p[5]^4+10*k*p[5]^3-4*k*p[5]^4+35*k^2*p[5]^2-30*k^2*p[5]^3+6*k^2*p[5]^4+50*k^3*p[5]-70*k^3*p[5]^2+30*k^3*p[5]^3-4*k^3*p[5]^4+24*k^4-50*k^4*p[5]+35*k^4*p[5]^2-10*k^4*p[5]^3+k^4*p[5]^4)/((1+k)*(1+2*k)*(1+3*k))
return(x)
}
P0 <- function(k, p)
{
x <- 1 - P1(k,p) - P2(k,p) - P3(k,p) - P4(k,p) - P5(k,p);
return(x)
}
results <- c(0,0,0,0,0,0);
results[1] <- ( (n*P0(k=rho0, p=Pi)) - (n*P0(k=rho1, p = Pi)) )^2/ (n*P0(k=rho1, p = Pi))
results[2] <- ( (n*P1(k=rho0, p=Pi)) - (n*P1(k=rho1, p = Pi)) )^2/ (n*P1(k=rho1, p = Pi))
results[3] <- ( (n*P2(k=rho0, p=Pi)) - (n*P2(k=rho1, p = Pi)) )^2/ (n*P2(k=rho1, p = Pi))
results[4] <- ( (n*P3(k=rho0, p=Pi)) - (n*P3(k=rho1, p = Pi)) )^2/ (n*P3(k=rho1, p = Pi))
results[5] <- ( (n*P4(k=rho0, p=Pi)) - (n*P4(k=rho1, p = Pi)) )^2/ (n*P4(k=rho1, p = Pi))
results[6] <- ( (n*P5(k=rho0, p=Pi)) - (n*P5(k=rho1, p = Pi)) )^2/ (n*P5(k=rho1, p = Pi))
return(sum(results,na.rm=TRUE))
}
}
if (raters == 6)
{
.CalcIT <- function(rho0, rho1, Pi, n)
{
P1 <- function(k, p)
{
x <- -p[1]*(-p[1]^5-15*k*p[1]^4+5*k*p[1]^5-85*k^2*p[1]^3-10*k^2*p[1]^5+60*k^2*p[1]^4-225*k^3*p[1]^2-90*k^3*p[1]^4+255*k^3*p[1]^3+10*k^3*p[1]^5-274*k^4*p[1]-255*k^4*p[1]^3-5*k^4*p[1]^5+450*k^4*p[1]^2+60*k^4*p[1]^4-120*k^5+274*k^5*p[1]-225*k^5*p[1]^2+85*k^5*p[1]^3-15*k^5*p[1]^4+k^5*p[1]^5)/((1+k)*(1+2*k)*(1+3*k)*(1+4*k))
return(x)
}
P2 <- function(k, p)
{
x <- -p[2]*(-p[2]^5-15*k*p[2]^4+5*k*p[2]^5-85*k^2*p[2]^3+60*k^2*p[2]^4-10*k^2*p[2]^5-225*k^3*p[2]^2+10*k^3*p[2]^5+255*k^3*p[2]^3-90*k^3*p[2]^4-274*k^4*p[2]-5*k^4*p[2]^5+60*k^4*p[2]^4+450*k^4*p[2]^2-255*k^4*p[2]^3-120*k^5+274*k^5*p[2]-225*k^5*p[2]^2+85*k^5*p[2]^3-15*k^5*p[2]^4+k^5*p[2]^5)/((1+k)*(1+2*k)*(1+3*k)*(1+4*k))
return(x)
}
P3 <- function(k, p)
{
x <- -p[3]*(-p[3]^5-15*k*p[3]^4+5*k*p[3]^5-85*k^2*p[3]^3-10*k^2*p[3]^5+60*k^2*p[3]^4-225*k^3*p[3]^2-90*k^3*p[3]^4+255*k^3*p[3]^3+10*k^3*p[3]^5-274*k^4*p[3]-255*k^4*p[3]^3-5*k^4*p[3]^5+450*k^4*p[3]^2+60*k^4*p[3]^4-120*k^5+274*k^5*p[3]-225*k^5*p[3]^2+85*k^5*p[3]^3-15*k^5*p[3]^4+k^5*p[3]^5)/((1+k)*(1+2*k)*(1+3*k)*(1+4*k))
return(x)
}
P4 <- function(k, p)
{
x <- -p[4]*(-p[4]^5-15*k*p[4]^4+5*k*p[4]^5-85*k^2*p[4]^3-10*k^2*p[4]^5+60*k^2*p[4]^4-225*k^3*p[4]^2-90*k^3*p[4]^4+255*k^3*p[4]^3+10*k^3*p[4]^5-274*k^4*p[4]-255*k^4*p[4]^3-5*k^4*p[4]^5+450*k^4*p[4]^2+60*k^4*p[4]^4-120*k^5+274*k^5*p[4]-225*k^5*p[4]^2+85*k^5*p[4]^3-15*k^5*p[4]^4+k^5*p[4]^5)/((1+k)*(1+2*k)*(1+3*k)*(1+4*k))
return(x)
}
P5 <- function(k, p)
{
x <- -p[5]*(-p[5]^5-15*k*p[5]^4+5*k*p[5]^5-85*k^2*p[5]^3-10*k^2*p[5]^5+60*k^2*p[5]^4-225*k^3*p[5]^2-90*k^3*p[5]^4+255*k^3*p[5]^3+10*k^3*p[5]^5-274*k^4*p[5]-255*k^4*p[5]^3-5*k^4*p[5]^5+450*k^4*p[5]^2+60*k^4*p[5]^4-120*k^5+274*k^5*p[5]-225*k^5*p[5]^2+85*k^5*p[5]^3-15*k^5*p[5]^4+k^5*p[5]^5)/((1+k)*(1+2*k)*(1+3*k)*(1+4*k))
return(x)
}
P0 <- function(k, p)
{
x <- 1 - P1(k,p) - P2(k,p) - P3(k,p) - P4(k,p) - P5(k,p);
return(x)
}
results <- c(0,0,0,0,0,0);
results[1] <- ( (n*P0(k=rho0, p=Pi)) - (n*P0(k=rho1, p = Pi)) )^2/ (n*P0(k=rho1, p = Pi))
results[2] <- ( (n*P1(k=rho0, p=Pi)) - (n*P1(k=rho1, p = Pi)) )^2/ (n*P1(k=rho1, p = Pi))
results[3] <- ( (n*P2(k=rho0, p=Pi)) - (n*P2(k=rho1, p = Pi)) )^2/ (n*P2(k=rho1, p = Pi))
results[4] <- ( (n*P3(k=rho0, p=Pi)) - (n*P3(k=rho1, p = Pi)) )^2/ (n*P3(k=rho1, p = Pi))
results[5] <- ( (n*P4(k=rho0, p=Pi)) - (n*P4(k=rho1, p = Pi)) )^2/ (n*P4(k=rho1, p = Pi))
results[6] <- ( (n*P5(k=rho0, p=Pi)) - (n*P5(k=rho1, p = Pi)) )^2/ (n*P5(k=rho1, p = Pi))
return(sum(results,na.rm=TRUE))
}
}
rhol <- kappa0;
resultsl <- 0;
while (abs(resultsl - 0.001) < X$ChiCrit)
{
rhol <- rhol - 0.001;
resultsl <- .CalcIT(rho0=kappa0, rho1 = rhol, Pi=props, n=n)
}
X$kappaL <- rhol;
class(X) <- "FixedN5Cats";
return(X);
}
print.FixedN5Cats <- function(x, ...)
{
cat("A total of ", x$n, " subjects can produce a lower limit for kappa of ", x$kappaL, ". \n", sep="")
for (i in 1:length(x$props))
{
if (x$props[i] * x$n < 5)
{
cat("Warning: At least one expected cell count is less than five. \n")
}
}
}
summary.FixedN5Cats <- function(object, ...)
{
cat("Lower Expected Limit for Studies of \n")
cat("Interobserver Agreement for Fixed N \n \n")
cat("Assuming:", "\n")
cat("Kappa0:", object$kappa0, "\n")
cat("N:", object$n, "\n")
cat("Event Proportion:", object$props, "\n")
cat("Number of Raters:", object$raters, "\n")
cat("Type I Error Rate (alpha) = ", object$alpha, "\n \n")
cat("A total of ", object$n, " subjects can produce an expected lower limit for kappa of ", object$kappaL, ". \n \n", sep="")
for (i in 1:length(object$props))
{
if (object$props[i] * object$n < 5)
{
cat("Warning: At least one expected cell count is less than five. \n")
}
}
} |
library("mboost")
data("birds", package = "TH.data")
bcr <- boost_control(mstop=200, trace=TRUE)
fm <- SG5 ~ bols(GST) + bols(DBH) + bols(AOT) + bols(AFS) + bols(DWC) +
bols(LOG)
sp <- gamboost(fm, data = birds, family = Poisson(), control = bcr)
birdsaic <- AIC(sp, "classical")
plot(birdsaic)
ms <- mstop(birdsaic)
table(sp$xselect()[1:ms])
coef(sp[ms])
bcr <- boost_control(mstop=500, trace=TRUE)
fm <- SG4 ~ bols(GST) + bols(DBH) + bols(AOT) + bols(AFS) + bols(DWC) +
bols(LOG)
sp <- gamboost(fm, data = birds, family = Poisson(), control = bcr)
table(sp$xselect())
coef(sp, which=1:6)
fm <- SG4 ~ bols(GST) + bols(DBH) + bols(AOT) + bols(AFS) + bols(DWC) +
bols(LOG) + bspatial(x_gk, y_gk, df=5, differences=1, knots=c(12,12))
sp <- gamboost(fm, data = birds, family = Poisson(), control = bcr)
table(sp$xselect())
coef(sp, which=1:6)
fm <- SG4 ~ bols(GST) + bols(DBH) + bols(AOT) + bols(AFS) + bols(DWC) +
bols(LOG) + bspatial(x_gk, y_gk, df=1, differences=1, knots=c(12,12), center=TRUE)
sp <- gamboost(fm, data = birds, family = Poisson(), control = bcr)
table(sp$xselect())
coef(sp, which=1:6)
fm <- SG5 ~ bbs(GST) + bbs(DBH) + bbs(AOT) + bbs(AFS) + bbs(DWC) +
bbs(LOG) + bspatial(x_gk, y_gk, df=4, differences=1, knots=c(12,12))
sp <- gamboost(fm, data = birds, family = Poisson(), control = bcr)
plot(sp)
fm <- SG5 ~ bols(GST) + bbs(GST, df=1, center=TRUE) +
bols(AOT) + bbs(AOT, df=1, center=TRUE) +
bols(AFS) + bbs(AFS, df=1, center=TRUE) +
bols(DWC) + bbs(DWC, df=1, center=TRUE) +
bols(LOG) + bbs(LOG, df=1, center=TRUE) +
bspatial(x_gk, y_gk, df=1, differences=1, knots=c(12,12),
center=TRUE)
sp <- gamboost(fm, data = birds, family = Poisson(), control = bcr)
plot(sp)
bcr <- boost_control(mstop=200, trace=TRUE)
birds$GST <- (birds$GST-min(birds$GST))/(max(birds$GST)-min(birds$GST))
birds$AOT <- (birds$AOT-min(birds$AOT))/(max(birds$AOT)-min(birds$AOT))
birds$AFS <- (birds$AFS-min(birds$AFS))/(max(birds$AFS)-min(birds$AFS))
birds$DWC <- (birds$DWC-min(birds$DWC))/(max(birds$DWC)-min(birds$DWC))
birds$LOG <- (birds$LOG-min(birds$LOG))/(max(birds$LOG)-min(birds$LOG))
fm <- SG5 ~ bols(GST) + bspatial(x_gk, y_gk, by = GST, df=1, differences=1,
knots=c(12, 12), center=TRUE) +
bols(AOT) + bspatial(x_gk, y_gk, by = AOT, df=1, differences=1,
knots=c(12, 12), center=TRUE) +
bols(AFS) + bspatial(x_gk, y_gk, by = AFS, df=1, differences=1,
knots=c(12, 12), center=TRUE) +
bols(DWC) + bspatial(x_gk, y_gk, by = DWC, df=1, differences=1,
knots=c(12, 12), center=TRUE) +
bols(LOG) + bspatial(x_gk, y_gk, by = LOG, df=1, differences=1,
knots=c(12, 12), center=TRUE) +
bspatial(x_gk, y_gk, df=1, differences=1, knots=c(12, 12),
center=TRUE)
sp <- gamboost(fm, data = birds, family = Poisson(), control = bcr)
plot(sp, which = "GST")
plot(sp, which = "AOT")
plot(sp, which = "AFS")
plot(sp, which = "DWC")
plot(sp, which = "LOG") |
if (require("testthat")) {
test_that("describe_distribution", {
x <- describe_distribution(rnorm(100))
expect_equal(c(nrow(x), ncol(x)), c(1, 9))
})
} |
"call_cccp2" <- function(op, X=NULL, opt, quiet=FALSE){
if(class(op$f)=="ratioFun" && op$max){
stop("Rational functions can only be minimized with solver='cccp2'.\n")
}
if(class(op$f)=="quadFun" && op$max){
stop("Quadratic functions can only be minimized with solver='cccp2'.\n")
}
if(length(op$qc)==0){
stop("There are no quadratic or rational constraints, so use solver='cccp' instead.\n")
}
if(!("abstol" %in% names(opt))){opt$abstol = (1e-06)*(10^length(op$qc)) }
if(!("feastol" %in% names(opt))){opt$feastol = 1e-05}
if(!("trace" %in% names(opt))){opt$trace = !quiet}
if(!("stepadj" %in% names(opt))){opt$stepadj = ifelse(class(op$f)=="ratioFun",0.40, 0.90)}
if(!("maxiters" %in% names(opt))){opt$maxiters = 100L}
if(!("reltol" %in% names(opt))){opt$reltol = 1e-06}
if(!("beta" %in% names(opt))){opt$beta = 0.5}
storage.mode(opt$maxiters) <- "integer"
params.opt <- c("maxiters", "abstol", "reltol", "feastol", "stepadj", "beta", "trace")
opt <- opt[intersect(names(opt), params.opt)]
optctrl<- do.call(cccp::ctrl, opt)
if(!quiet){
cat("\n")
cat("Using solver 'cccp2' with parameters: \n")
print(data.frame(Value=as.character(rapply(opt,c)),row.names=names(rapply(opt,c))))
cat("\n")
}
if(length(op$lb$val)>0 || length(op$ub$val)>0){
op <- bounds2lc(op)
}
op <- splitlc(op)
op <- incon2fun(op, multiDim=FALSE, withLinCon=FALSE)
if(class(op$f)=="ratioFun"){
op <- f2fun(op)
}
if(is.null(op$inlc)){
cList <- NULL
}else{
nnoc1 <- nnoc(G=op$inlc$A, h=op$inlc$val)
cList <- list(nnoc1)
}
gc()
myf <- list()
myg <- list()
myh <- list()
for(i in seq_along(op$infun$f0)){
op$infun$val[[i]]<-op$infun$val[[i]]-0.001
}
for(i in seq_along(op$infun$f0)){
if(is.null(X) || op$infun$f0[[i]](X)>=0){
X <- getx(cccp( P = op$infun$Q[[i]],
q = op$infun$a[[i]],
A = op$eqlc$A,
b = op$eqlc$val,
cList = cList,
nlfList= myf,
nlgList= myg,
nlhList= myh,
x0 = X,
optctrl=optctrl))[,1]
if(length(X)==0){X <- rep(NA, length(op$id))}
if(!is.null(op$eqlc)){op$eqlc$val <- c(op$eqlc$A%*%X)}
}
myf[[i]] <- op$infun$f0[[i]]
myg[[i]] <- op$infun$g0[[i]]
myh[[i]] <- op$infun$h0[[i]]
gc()
if(op$infun$f0[[i]](X)>0){
cat("No solution exists.\n");
X <- setNames(X, op$id)
return(list(x=X, solver="cccp2", status="No solution exists."))
}
}
for(i in seq_along(op$infun$f0)){
op$infun$val[[i]] <- op$infun$val[[i]]+0.001
}
gc()
if(class(op$f)=="Fun"){
res <- cccp(f0=op$f$f0, g0=op$f$g0, h0=op$f$h0, x0=X, A=op$eqlc$A, b=op$eqlc$val, cList=cList, nlfList=op$infun$f0, nlgList=op$infun$g0, nlhList=op$infun$h0, optctrl=optctrl)
}else{
res <- cccp(P=op$f$Q, q=0.5*op$f$a, x0=X, A=op$eqlc$A, b=op$eqlc$val, cList=cList, nlfList=op$infun$f0, nlgList=op$infun$g0, nlhList=op$infun$h0, optctrl=optctrl)
}
if(length(getx(res))==0){
x <- rep(NA, length(op$id))
}else{
x <- c(getx(res))
}
x <- setNames(x, op$id)
res <- list(x=x, solver="cccp2", status=res$status)
res
} |
context("surv_model_performance")
source("objects_for_tests.R")
test_that("Creating surv_model_performance", {
expect_is(mp_cph, "surv_model_performance_explainer")
expect_is(mp_cph, "BS")
expect_is(mp_cph_artificial, "surv_model_performance_explainer")
})
test_that("Wrong input",{
expect_error(model_performance(cph_model))
expect_error(model_performance(surve_cph_null_data))
}) |
GeomPointRast <- ggplot2::ggproto(
"GeomPointRast",
ggplot2::GeomPoint,
draw_panel = function(self, data, panel_params, coord, raster.dpi, dev, scale) {
grob <- ggproto_parent(GeomPoint, self)$draw_panel(data, panel_params, coord)
class(grob) <- c("rasteriser", class(grob))
grob$dpi <- raster.dpi
grob$dev <- dev
grob$scale <- scale
return(grob)
}
)
DrawGeomBoxplotJitter <- function(data, panel_params, coord, dev="cairo", ...,
outlier.jitter.width=NULL,
outlier.jitter.height=0,
outlier.colour = NULL,
outlier.fill = NULL,
outlier.shape = 19,
outlier.size = 1.5,
outlier.stroke = 0.5,
outlier.alpha = NULL,
raster=FALSE, raster.dpi=getOption("ggrastr.default.dpi", 300),
raster.width=NULL, raster.height=NULL,
scale = 1
) {
boxplot_grob <- ggplot2::GeomBoxplot$draw_group(data, panel_params, coord, ...)
point_grob <- grep("geom_point.*", names(boxplot_grob$children))
if (length(point_grob) == 0){
return(boxplot_grob)
}
ifnotnull <- function(x, y) if(is.null(x)) y else x
if (is.null(outlier.jitter.width)) {
outlier.jitter.width <- (data$xmax - data$xmin) / 2
}
x <- data$x[1]
y <- data$outliers[[1]]
if (outlier.jitter.width > 0 & length(y) > 1) {
x <- jitter(rep(x, length(y)), amount=outlier.jitter.width)
}
if (outlier.jitter.height > 0 & length(y) > 1) {
y <- jitter(y, amount=outlier.jitter.height)
}
outliers <- data.frame(
x = x, y = y,
colour = ifnotnull(outlier.colour, data$colour[1]),
fill = ifnotnull(outlier.fill, data$fill[1]),
shape = ifnotnull(outlier.shape, data$shape[1]),
size = ifnotnull(outlier.size, data$size[1]),
stroke = ifnotnull(outlier.stroke, data$stroke[1]),
fill = NA,
alpha = ifnotnull(outlier.alpha, data$alpha[1]),
stringsAsFactors = FALSE
)
boxplot_grob$children[[point_grob]] <- GeomPointRast$draw_panel(outliers, panel_params, coord, raster.dpi=raster.dpi, dev=dev, scale = scale)
return(boxplot_grob)
}
GeomBoxplotJitter <- ggplot2::ggproto("GeomBoxplotJitter",
ggplot2::GeomBoxplot,
draw_group = DrawGeomBoxplotJitter)
geom_boxplot_jitter <- function(mapping = NULL, data = NULL, dev = "cairo",
stat = "boxplot", position = "dodge",
na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...,
outlier.jitter.width=NULL,
outlier.jitter.height=0,
raster.dpi=getOption("ggrastr.default.dpi", 300),
scale = 1
) {
ggplot2::layer(
geom = GeomBoxplotJitter, mapping = mapping, data = data, stat = stat,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm,
outlier.jitter.width=outlier.jitter.width,
outlier.jitter.height=outlier.jitter.height,
raster.dpi=raster.dpi, dev=dev, scale = scale, ...))
} |
data_plot.parameters_simulate <- function(x,
data = NULL,
normalize_height = FALSE,
...) {
if (is.null(data)) {
data <- .retrieve_data(x)
}
n_sims <- attr(x, "n_sims")
dat <- parameters::simulate_model(model = data, n_sims = n_sims)
params <- insight::clean_parameters(data)
out <- bayestestR::estimate_density(dat)
if (isTRUE(normalize_height)) {
out$y <- datawizard::data_rescale(out$y, to = c(0, .9))
}
if (length(unique(params$Effects)) > 1) {
out$Effects <- NA
if (length(unique(params$Component)) > 1) {
zi_comp <- params$Component == "zero_inflated"
params$Parameter[zi_comp] <- paste0(params$Parameter[zi_comp], "_zi")
disp_comp <- params$Component == "dispersion"
params$Parameter[disp_comp] <- paste0(params$Parameter[disp_comp], "_disp")
}
for (i in names(dat)) {
if (i %in% params$Parameter && i %in% out$Parameter) {
out$Effects[out$Parameter == i] <- params$Effects[params$Parameter == i]
}
}
if (length(unique(params$Component)) > 1) {
out$Component <- NA
for (i in names(dat)) {
if (i %in% params$Parameter && i %in% out$Parameter) {
out$Component[out$Parameter == i] <- params$Component[params$Parameter == i]
}
}
}
}
if (!is.null(attributes(x)$object_class) && "mlm" %in% attributes(x)$object_class) {
out$Component <- NA
for (i in unique(params$Response)) {
out$Component[grepl(paste0(i, "$"), out$Parameter)] <- i
out$Parameter <- gsub(paste0(i, "$"), "", out$Parameter)
}
}
out
}
plot.see_parameters_simulate <- function(x,
data = NULL,
stack = TRUE,
show_intercept = FALSE,
n_columns = NULL,
normalize_height = FALSE,
size_line = .9,
posteriors_alpha = 0.7,
centrality = "median",
ci = 0.95,
...) {
is_mlm <- !is.null(attributes(x)$object_class) && "mlm" %in% attributes(x)$object_class
if (is.null(n_columns) && isTRUE(is_mlm)) n_columns <- 1
if (missing(centrality) && !is.null(attributes(x)$centrality)) {
centrality <- attributes(x)$centrality
}
if (!"data_plot" %in% class(x)) {
x <- data_plot(x, data = data, normalize_height = normalize_height)
}
plot.see_estimate_density(
x,
stack = stack,
show_intercept = show_intercept,
n_columns = n_columns,
size_line = size_line,
posteriors_alpha = posteriors_alpha,
centrality = centrality,
ci = ci,
...
)
} |
pcoxsurvfit.pcoxtime <- function(fit, newdata, ...){
afit <- predictedHazard(fit)
chaz <- afit$chaz
surv.est <- exp(-chaz)
if (!missing(newdata)){
lp <- predict(fit, newdata = newdata, type = "lp")
surv.est <- t(sapply(surv.est, function(x) x^exp(lp)))
chaz <- -log(surv.est)
}
out <- list(n = afit$n
, events = sum(afit$n.event)
, time = afit$time
, n.risk = afit$n.risk
, n.event = afit$n.event
, n.censor = afit$n.censor
, surv = surv.est
, cumhaz = chaz
)
out$call <- match.call()
class(out) <- "pcoxsurvfit"
out
}
pcoxbasehaz.pcoxtime <- function(fit, centered = TRUE){
sfit <- pcoxsurvfit.pcoxtime(fit)
chaz <- sfit$cumhaz
surv.est <- exp(-chaz)
if (!centered) {
beta.hat <- drop(fit$coef)
X.mean <- fit$means
offset <- drop(X.mean %*% beta.hat)
chaz <- chaz * exp(-offset)
surv.est <- exp(-chaz)
}
out <- list(time = sfit$time, hazard = chaz, surv = surv.est)
out$call <- match.call()
class(out) <- c("pcoxbasehaz", "pcoxsurvfit")
out
}
predict.pcoxtime <- function(object, ..., newdata = NULL, type = c("lp", "risk", "expected", "terms", "survival"), terms = object$predictors, na.action = na.pass){
if (!missing(terms)){
if (any(is.na(match(terms, object$predictors))))
stop("a name given in the terms argument not found in the model")
}
type <- match.arg(type)
if (type == "survival") {
survival <- TRUE
type <- "expected"
} else {
survival <- FALSE
}
beta.hat <- drop(object$coef)
timevar <- object$timevarlabel
eventvar <- object$eventvarlabel
all_terms <- object$predictors
if (!is.null(newdata)) {
if(type == "expected"){
new_form <- object$terms
m <- model.frame(new_form, data = newdata
, xlev = object$xlevels, na.action = na.action
, drop.unused.levels = TRUE
)
newY <- model.extract(m, "response")
} else{
new_form <- delete.response(object$terms)
m <- model.frame(new_form, data = newdata
, xlev = object$xlevels, na.action = na.action
, drop.unused.levels = TRUE
)
}
newX <- model.matrix(new_form, m, contr = object$contrasts, xlev = object$xlevels)
xnames <- colnames(newX)
assign <- setNames(attr(newX, "assign"), xnames)[-1]
xnames <- names(assign)
newX <- newX[ , xnames, drop=FALSE]
} else {
df <- object$data
newY <- object$Y
events <- df[, eventvar]
times <- df[, timevar]
assign <- object$assign
xnames <- names(assign)
newX <- df[, xnames, drop = FALSE]
}
xmeans <- object$means[xnames]
newX.centered <- newX - rep(xmeans, each = NROW(newX))
lp <- unname(drop(newX.centered %*% beta.hat))
if (type == "terms"){
term_list <- list()
tvals <- unique(assign)
for (i in seq_along(tvals)){
w <- assign == tvals[i]
term_list[[i]] <- newX.centered[, w, drop = FALSE] %*% beta.hat[w]
}
terms_df <- do.call("cbind", term_list)
colnames(terms_df) <- all_terms
if(!missing(terms)){ terms_df <- terms_df[, terms, drop = FALSE]}
}
if (type == "expected"){
afit <- predictedHazard(object)
times <- afit$time
afit.n <- length(times)
newrisk <- drop(exp(newX.centered %*% beta.hat))
j1 <- approx(times, 1:afit.n, newY[,1], method = "constant", f = 0, yleft = 0, yright = afit.n)$y
chaz <- c(0, afit$chaz)[j1 + 1]
if (NCOL(newY)==2){
expected <- unname(chaz * newrisk)
} else {
j2 <- approx(times, 1:afit.n, newY[,2], method = "constant", f = 0, yleft = 0, yright = afit.n)$y
chaz2 <- c(0, afit$chaz)[j2 + 1]
expected <- unname((chaz2 - chaz) * newrisk)
}
if (survival){
survival <- exp(-expected)
type <- "survival"
}
}
out <- switch(type
, lp = lp
, risk = exp(lp)
, terms = terms_df
, expected = expected
, survival = survival
)
return(out)
}
predictedHazard <- function(fit){
oldY <- fit$Y
wt <- rep(1, NROW(oldY))
assign <- fit$assign
xnames <- names(assign)
oldX <- fit$data[, xnames, drop = FALSE]
beta.hat <- fit$coef
xmeans <- fit$means
oldX.centered <- oldX - rep(xmeans, each = NROW(oldX))
oldlp <- unname(drop(oldX.centered %*% beta.hat))
oldrisk <- exp(oldlp)
status <- oldY[, ncol(oldY)]
dtime <- oldY[, ncol(oldY) - 1]
death <- (status == 1)
time <- sort(unique(dtime))
nevent <- as.vector(rowsum(wt * death, dtime))
ncens <- as.vector(rowsum(wt * (!death), dtime))
wrisk <- wt * oldrisk
rcumsum <- function(x) rev(cumsum(rev(x)))
nrisk <- rcumsum(rowsum(wrisk, dtime))
irisk <- rcumsum(rowsum(wt, dtime))
if (NCOL(oldY) != 2){
delta <- min(diff(time))/2
etime <- c(sort(unique(oldY[, 1])), max(oldY[, 1]) + delta)
indx <- approx(etime, 1:length(etime), time, method = "constant", rule = 2, f = 1)$y
esum <- rcumsum(rowsum(wrisk, oldY[, 1]))
nrisk <- nrisk - c(esum, 0)[indx]
irisk <- irisk - c(rcumsum(rowsum(wt, oldY[, 1])), 0)[indx]
}
haz <- nevent/nrisk
result <- list(n = NROW(oldY), time = time, n.event = nevent
, n.risk = irisk, n.censor = ncens, hazard = haz, chaz = cumsum(haz)
)
return(result)
}
predictSurvProb.pcoxtime <- function(object, newdata, times, ...){
N <- NROW(newdata)
sfit <- pcoxsurvfit(object, newdata = newdata)
S <- t(sfit$surv)
Time <- sfit$time
if(N == 1) S <- matrix(S, nrow = 1)
p <- cbind(1, S)[, 1 + prodlim::sindex(Time, times),drop = FALSE]
p
}
predictRisk.pcoxtime <- function(object, newdata, times, ...){
p <- 1 - predictSurvProb.pcoxtime(object, newdata, times)
p
}
concordScore.pcoxtime <- function(fit, newdata = NULL, stats = FALSE, reverse = TRUE, ...){
if (is.null(newdata)) {
risk <- predict(fit, type = "risk")
y <- model.extract(model.frame(fit), "response")
} else {
risk <- predict(fit, newdata = newdata, type = "risk")
y <- model.extract(model.frame(fit$terms, data = newdata), "response")
}
conindex <- survival::concordance(y ~ risk, reverse = reverse, ...)
if (!stats){
conindex <- conindex$concordance
}
return(conindex)
}
extractoptimal.pcoxtimecv <- function(object, what=c("optimal", "cvm", "coefs"), ...) {
what <- match.arg(what)
if (what=="optimal") {
out <- object$dfs$min_metrics_df
} else if (what=="cvm") {
out <- object$dfs$cvm
} else {
out <- object$fit$beta
if (is.null(out)) warning("Run the model with refit=TRUE to extract cross-validation coefficients.")
}
return(out)
}
pvimp.pcoxtime <- function(object, newdata, nrep=50
, parallelize=FALSE, nclusters=1, estimate=c("mean", "quantile")
, probs=c(0.025, 0.5, 0.975), seed=NULL, ...) {
if (is.null(seed) || !is.numeric(seed)) {
seed <- 911
set.seed(seed)
}
estimate <- match.arg(estimate)
overall_c <- concordScore.pcoxtime(object, newdata=newdata, stats=FALSE, reverse=TRUE, ...)
xvars <- all.vars(formula(delete.response(terms(object))))
N <- NROW(newdata)
if (parallelize) {
nn <- min(parallel::detectCores(), nclusters)
if (nn < 2){
foreach::registerDoSEQ()
} else{
cl <- parallel::makeCluster(nn)
doParallel::registerDoParallel(cl)
on.exit(parallel::stopCluster(cl))
}
x <- NULL
vi <- foreach(x = xvars, .export="concordScore.pcoxtime") %dopar% {
permute_df <- newdata[rep(seq(N), nrep), ]
if (is.factor(permute_df[,x])) {
permute_var <- as.vector(replicate(nrep, sample(newdata[,x], N, replace = FALSE)))
permute_var <- factor(permute_var, levels = levels(permute_df[,x]))
} else {
permute_var <- as.vector(replicate(nrep, sample(newdata[,x], N, replace = FALSE)))
}
index <- rep(1:nrep, each = N)
permute_df[, x] <- permute_var
perm_c <- unlist(lapply(split(permute_df, index), function(d){
concordScore.pcoxtime(object, newdata = d, stats = FALSE, reverse=TRUE, ...)
}))
est <- (overall_c - perm_c)/overall_c
out <- switch(estimate
, mean={
out2 <- mean(est)
names(out2) <- x
out2
}
, quantile={
out2 <- cbind.data.frame(...xx=x, t(quantile(est, probs = probs, na.rm = TRUE)))
colnames(out2) <- c("terms", "lower", "estimate", "upper")
out2
}
)
out
}
} else {
vi <- sapply(xvars, function(x){
permute_df <- newdata[rep(seq(N), nrep), ]
if (is.factor(permute_df[,x])) {
permute_var <- as.vector(replicate(nrep, sample(newdata[,x], N, replace = FALSE)))
permute_var <- factor(permute_var, levels = levels(permute_df[,x]))
} else {
permute_var <- as.vector(replicate(nrep, sample(newdata[,x], N, replace = FALSE)))
}
index <- rep(1:nrep, each = N)
permute_df[, x] <- permute_var
perm_c <- unlist(lapply(split(permute_df, index), function(d){
concordScore.pcoxtime(object, newdata = d, stats = FALSE, reverse=TRUE, ...)
}))
est <- (overall_c - perm_c)/overall_c
out <- switch(estimate
, mean={
out2 <- mean(est)
out2
}
, quantile={
out2 <- cbind.data.frame(...xx=x, t(quantile(est, probs = probs, na.rm = TRUE)))
colnames(out2) <- c("terms", "lower", "estimate", "upper")
out2
}
)
out
}, simplify = FALSE)
}
out <- switch(estimate
, mean={
unlist(vi)
}
, quantile={
est <- do.call("rbind", vi)
rownames(est) <- NULL
est
}
)
return(out)
}
coefvimp.pcoxtime <- function(object, relative=TRUE, ...) {
out <- data.frame(Overall=coef(object))
out$sign <- sign(out$Overall)
out$Overall <- abs(out$Overall)
if (relative){
out$Overall <- out$Overall/sum(out$Overall, na.rm = TRUE)
}
out$terms <- rownames(out)
rownames(out) <- NULL
out <- out[, c("terms", "Overall", "sign")]
return(out)
}
varimp.pcoxtime <- function(object, newdata, type=c("coef", "perm", "model")
, relative=TRUE, nrep=50, parallelize=FALSE, nclusters=1
, estimate=c("mean", "quantile"), probs=c(0.025, 0.5, 0.975), seed=NULL, ...) {
type <- match.arg(type)
estimate <- match.arg(estimate)
if (type=="model") {
type <- "coef"
}
if (type=="coef") {
out <- coefvimp.pcoxtime(object, relative=relative)
} else if (type=="perm") {
out <- pvimp.pcoxtime(object=object, newdata=newdata, nrep=nrep
, parallelize=parallelize, nclusters=nclusters, estimate=estimate
, probs=probs
)
if (estimate=="mean") {
out <- data.frame(Overall=out)
out$sign <- sign(out$Overall)
out$Overall <- abs(out$Overall)
if (relative) {
out$Overall <- out$Overall/sum(out$Overall, na.rm = TRUE)
}
out$terms <- rownames(out)
rownames(out) <- NULL
out <- out[, c("terms", "Overall", "sign")]
}
}
if (type=="coef") estimate <- "mean"
attr(out, "estimate") <- estimate
class(out) <- c("varimp", class(out))
return(out)
} |
testColoc <- function(im1, im2, hres = 0.1023810, vres = 0.2500000, B=999, alternative = "less", returnSample = TRUE, ...){
centers <- rbind(im1$moments[,c('m.x','m.y','m.z')], im2$moments[,c('m.x','m.y','m.z')])
centers <- t(t(centers) * c(rep(hres,2),vres))
n1 <- nrow(im1$moments)
n2 <- nrow(im2$moments)
w <- c(im1$moments[,'w'], im2$moments[,'w'])
dist <- as.matrix(dist(centers))
return(cnnTest(dist, n1, n2, w, B, alternative, returnSample, ...))
} |
export_csv <- function(graph,
ndf_name = "nodes.csv",
edf_name = "edges.csv",
output_path = getwd(),
colnames_type = NULL) {
fcn_name <- get_calling_fcn()
if (graph_object_valid(graph) == FALSE) {
emit_error(
fcn_name = fcn_name,
reasons = "The graph object is not valid")
}
nodes_df <- get_node_df(graph)
edges_df <- get_edge_df(graph)
if (!is.null(colnames_type)) {
if (colnames_type == "neo4j") {
colnames(nodes_df)[1:3] <-
c("nodes:ID", ":LABEL", "label")
colnames(edges_df)[1:3] <-
c(":START_ID", ":END_ID", ":TYPE")
}
if (colnames_type == "graphframes") {
colnames(nodes_df)[1] <- "id"
colnames(edges_df)[1:2] <-
c("src", "dst")
}
}
utils::write.csv(
nodes_df,
file = paste0(output_path,
"/", ndf_name),
row.names = FALSE, quote = FALSE)
utils::write.csv(
edges_df,
file = paste0(output_path,
"/", edf_name),
row.names = FALSE, quote = FALSE)
} |
class_entropy <- function(conf_mat) {
mle_prob <- function(x) {
prob <- x / sum(x)
sum(abs(prob * ifelse(prob != 0, log2(prob), 0)))
}
list(row_entropy = apply(conf_mat, 1, mle_prob),
col_entropy = apply(conf_mat, 2, mle_prob))
}
class_purity <- function(conf_mat) {
list(row_purity = apply(conf_mat, 1, max) / apply(conf_mat, 1, sum),
col_purity = apply(conf_mat, 2, max) / apply(conf_mat, 2, sum))
} |
optimbase.histset <- function(this=NULL,iter=NULL,key=NULL,value=NULL){
if (!this$storehistory)
stop('optimbase.histset: History disabled ; turn on storehistory option.',
call.=FALSE)
if (iter<1)
stop('optimbase.histset: Negative iteration index are not allowed.',
call.=FALSE)
if (!any(key==c('historyxopt','historyfopt')))
stop(sprintf('optimbase.histset: Unknown key %s',key),
call.=FALSE)
if (key=='historyxopt') this$historyxopt[[iter]] <- value
if (key=='historyfopt') this$historyfopt[iter] <- value
return(this)
} |
context("Test bandit4arm_2par_lapse")
library(hBayesDM)
test_that("Test bandit4arm_2par_lapse", {
skip_on_cran()
expect_output(bandit4arm_2par_lapse(
data = "example", niter = 10, nwarmup = 5, nchain = 1, ncore = 1))
}) |
model_parameters.epi.2by2 <- function(model, verbose = TRUE, ...) {
params <- insight::get_parameters(model)
colnames(params)[2] <- "Coefficient"
coef_names <- grepl("^([^NNT]*)(\\.strata\\.wald)", names(model$massoc.detail), perl = TRUE)
cf <- model$massoc.detail[coef_names]
names(cf) <- gsub(".strata.wald", "", names(cf), fixed = TRUE)
cis <- do.call(rbind, cf)
cis$Parameter <- rownames(cis)
cis$est <- NULL
colnames(cis) <- c("CI_low", "CI_high", "Parameter")
params <- merge(params, cis, sort = FALSE)
fractions <- params$Parameter %in% c("AFRisk", "PAFRisk")
params[fractions, c("Coefficient", "CI_low", "CI_high")] <- 100 * params[fractions, c("Coefficient", "CI_low", "CI_high")]
pretty_names <- params$Parameter
pretty_names[pretty_names == "PR"] <- "Prevalence Ratio"
pretty_names[pretty_names == "OR"] <- "Odds Ratio"
pretty_names[pretty_names == "ARisk"] <- "Attributable Risk"
pretty_names[pretty_names == "PARisk"] <- "Attributable Risk in Population"
pretty_names[pretty_names == "AFRisk"] <- "Attributable Fraction in Exposed (%)"
pretty_names[pretty_names == "PAFRisk"] <- "Attributable Fraction in Population (%)"
stats <- model$massoc.detail$chi2.strata.uncor
attr(params, "footer_text") <- paste0("Test that Odds Ratio = 1: Chi2(", stats[["df"]], ") = ", insight::format_value(stats[["test.statistic"]]), ", ", insight::format_p(stats[["p.value.2s"]]))
attr(params, "pretty_names") <- stats::setNames(pretty_names, params$Parameter)
attr(params, "no_caption") <- TRUE
class(params) <- c("parameters_model", "see_parameters_model", class(params))
params
} |
CI.RMSEA <-
function(rmsea,df,N,clevel=.95){
if(length(rmsea)!=1|rmsea<0){stop('rmsea has to be correctly specified.')}
if(length(df)!=1|df<=0){stop('df has to be correctly specified.')}
if(length(N)!=1|N<=0){stop('N has to be correctly specified.')}
if(length(clevel)!=1|clevel<=0|clevel>=1){stop('clevel has to be correctly specified.')}
tol=.0000001;T=rmsea^2*df*(N-1)+df;C=qchisq(1-(1-clevel)/2,df)
if((T<C|rmsea==0)&N>1){;start=rmsea;O_U_P=(1-clevel)/2;P_LU=1
A=c(.01,.001,.0001,.00001,.000001,.0000001)
for(i in c(1,3,5)){;while(P_LU>O_U_P){
P_LU=pchisq(T,df,start^2*df*(N-1));if(P_LU>O_U_P){start=start+A[i]}}
while(P_LU<O_U_P){;P_LU=pchisq(T,df,start^2*df*(N-1))
if(P_LU<O_U_P){start=start-A[i+1]};if(start<0){start=0}}}
k=0;while(abs(P_LU-O_U_P)>tol&k<20){;P_LU=pchisq(T,df,start^2*df*(N-1))
if(P_LU>O_U_P){start=start+.00000001};if(P_LU<O_U_P){start=start-.00000001}
k=k+1;if(start<0){start=0}};if(k==20){;start1=start;start2=start+.00000001
s1=pchisq(T,df,start1^2*df*(N-1));s2=pchisq(T,df,start2^2*df*(N-1))
start=c(start1,start2)[which((abs(c(s1,s2)-O_U_P))==min(abs(c(s1,s2)-O_U_P)))]}
L.rmsea=0;U.rmsea=start};if(T>C&N>1){;O_U_P=(1-clevel)/2;P_LU=1;start=rmsea
A=c(.01,.001,.0001,.00001,.000001,.0000001)
for(i in c(1,3,5)){;while(P_LU>O_U_P){
P_LU=pchisq(T,df,start^2*df*(N-1));if(P_LU>O_U_P){start=start+A[i]}}
while(P_LU<O_U_P){;P_LU=pchisq(T,df,start^2*df*(N-1))
if(P_LU<O_U_P){start=start-A[i+1]};if(start<0){start=0}}}
k=0;while(abs(P_LU-O_U_P)>tol&k<20){;P_LU=pchisq(T,df,start^2*df*(N-1))
if(P_LU>O_U_P){start=start+.00000001};if(P_LU<O_U_P){start=start-.00000001}
k=k+1;if(start<0){start=0}};if(k==20){;start1=start;start2=start+.00000001
s1=pchisq(T,df,start1^2*df*(N-1));s2=pchisq(T,df,start2^2*df*(N-1))
start=c(start1,start2)[which((abs(c(s1,s2)-O_U_P))==min(abs(c(s1,s2)-O_U_P)))]}
U.rmsea=start;start=0;O_L_P=1-(1-clevel)/2;P_LL=1
A=c(.01,.001,.0001,.00001,.000001,.0000001)
for(i in c(1,3,5)){;while(P_LL>O_L_P){
P_LL=pchisq(T,df,start^2*df*(N-1));if(P_LL>O_L_P){start=start+A[i]}}
while(P_LL<O_L_P){;P_LL=pchisq(T,df,start^2*df*(N-1))
if(P_LL<O_L_P){start=start-A[i+1]};if(start<0){start=0}}}
k=0;while(abs(P_LL-O_L_P)>tol&k<20){;P_LL=pchisq(T,df,start^2*df*(N-1))
if(P_LL>O_L_P){start=start+.00000001};if(P_LL<O_L_P){start=start-.00000001}
k=k+1;if(start<0){start=0}};if(k==20){;start1=start;start2=start+.00000001
s1=pchisq(T,df,start1^2*df*(N-1));s2=pchisq(T,df,start2^2*df*(N-1))
start=c(start1,start2)[which((abs(c(s1,s2)-O_U_P))==min(abs(c(s1,s2)-O_U_P)))]}
L.rmsea=start};if(N==1){L.rmsea=0;U.rmsea=Inf}
list(Lower.CI=L.rmsea,RMSEA=rmsea,Upper.CI=U.rmsea)} |
new_TRI0 <- function(vertex, object, index, crs = NA_character_, meta = NULL) {
meta1 <- tibble::tibble(proj = crs, ctime = Sys.time())
if (!is.null(meta)) {
meta <- rbind(meta1, meta)
}
object[["topology_"]] <- index
structure(list(object = object, vertex = vertex,
meta = meta), class = c("TRI0", "sc"))
}
TRI0 <- function(x, ...) {
UseMethod("TRI0")
}
TRI0.default <- function(x, ...) {
TRI0(PATH0(x), ...)
}
TRI0.mesh3d <- function(x, ...) {
index <- x[["it"]]
if (is.null(index)) {
index <- .quad2tri(x[["ib"]])
}
index <- t(index)
colnames(index) <- c(".vx0", ".vx1", ".vx2")
index <- tibble::as_tibble(index)
object <- tibble::tibble(object_ = 1)
v <- t(x[["vb"]])
colnames(v) <- c("x_", "y_", "z_", "h_")
vertex <- tibble::as_tibble(v)
crs <- NA_character_
if (!is.null(x[["crs"]]) && !is.na(x[["crs"]])) {
crs <- x[["crs"]]
}
new_TRI0(vertex, object, list(index), crs)
}
TRI0.TRI0 <- function(x, ...) {
x
}
TRI0.sfc_TIN <- function(x, ...) {
stop("TRI0 not implemented for TIN")
}
TRI0.TRI <- function(x, ...) {
o <- sc_object(x)
o$object_ <- NULL
topol <- x$triangle
v <- sc_vertex(x)
idx <- split(tibble::tibble(.vx0 = match(topol$.vx0, v$vertex_),
.vx1 = match(topol$.vx1, v$vertex_),
.vx2 = match(topol$.vx2, v$vertex_)),
topol$object_)[unique(topol$object_)]
v$vertex_ <- NULL
crs <- crsmeta::crs_proj(x)
new_TRI0(v, o, idx, crs, meta = x$meta)
}
TRI0.PATH0 <- function(x, ...) {
v <- sc_vertex(x)
v$vertex_ <- 1:nrow(v)
obj <- sc_object(x)
count <- 0
trilist <- list()
for (i in seq_len(nrow(obj))) {
topol <- obj$path_[[i]]
lsubs <- split(topol, topol$subobject)
for (j in seq_along(lsubs)) {
vidx <- lsubs[[j]]
verts <- inner_join(vidx[c("vertex_", "path_")], v[c("x_", "y_", "vertex_")], "vertex_")
holes <- which(c(0, abs(diff(as.integer(as.factor(verts$path_))))) > 0)
if (length(holes) < 1) holes <- 0
count <- count + 1
trindex <- decido::earcut(cbind(verts[["x_"]], verts[["y_"]]), holes)
trimat <- matrix(trindex, ncol = 3L, byrow = TRUE)
trilist[[count]] <- tibble::tibble(.vx0 = verts$vertex_[trimat[,1L]],
.vx1 = verts$vertex_[trimat[,2L]],
.vx2 = verts$vertex_[trimat[,3L]],
object_ = i,
path_ = lsubs[[j]]$path_[1L])
}
}
obj$path_ <- NULL
topology_ <- dplyr::bind_rows(trilist)
index <- split(topology_[c(".vx0", ".vx1",".vx2", "path_")], topology_$object_)
crs <- crsmeta::crs_proj(x)
new_TRI0(sc_vertex(x), obj, index, crs, meta = x$meta)
}
TRI0.PATH <- function(x, ...) {
vertex <- x$vertex
if (nrow(vertex) < 3) stop("need at least 3 coordinates")
if (anyNA(vertex$x_)) stop("missing values in x_")
if (anyNA(vertex$y_)) stop("missing values in y_")
TRI0(PATH0(x), ...)
}
TRI0.sf <- function(x, ...) {
sfcol <- attr(x, "sf_column")
out <- TRI0(x[[sfcol]])
x[[sfcol]] <- NULL
nm <- names(x)
for (i in seq_along(x)) {
if (nm[i] %in% c("topology_", "object_")) next;
out$object[[nm[i]]] <- x[[i]]
}
out
}
TRI0.sfc_GEOMETRYCOLLECTION <- function(x, ...) {
list_sfc <- unclass(x)
lens <- lengths(list_sfc)
corners <- rapply(list_sfc, function(x) dim(x)[1L], classes = "matrix", how = "unlist")
if (!all(corners == 4L)) stop("cannot 'TRI0' a GEOMETRYCOLLECTION not composed of triangles (POLYGON with 4 coordinates)")
coords <- do.call(rbind, lapply(unlist(list_sfc, recursive = FALSE), "[[", 1L))
first <- seq(1, nrow(coords), by = 4L)
fourth <- first + 3
if (!max(first) == (nrow(coords)-3) ||
!all(coords[first,1] == coords[fourth, 1]) ||
!all(coords[first,2] == coords[fourth, 2])) {
stop("GEOMETRYCOLLECTION appears to not be composed of POLYGON triangles")
}
if (ncol(coords) == 2L) {
coords <- cbind(coords, 0)
}
coords <- coords[-fourth, , drop = FALSE]
colnames(coords) <- c("x_", "y_", "z_")
topol <- matrix(1:(dim(coords)[1L]), byrow = TRUE, ncol = 3L)
colnames(topol) <- c(".vx0", ".vx1", ".vx2")
topol <- tibble::as_tibble(topol)
topol <- split(topol, rep(seq_along(lens), lens))
new_TRI0(tibble::as_tibble(coords), tibble::tibble(object_ = seq_along(lens)),
topol, crsmeta::crs_proj(x))
} |
library(googleway)
api_key <- 'your_api_key'
res <- google_places(search_string = "Restaurants in Melbourne, Australia", key = api_key)
df_places <- google_places(search_string = "cafe", location = c(-37.81827, 144.9671), key = key)
df_places$results$name
res_next <- google_places(search_string = "Restaurants in Melbourne, Australia", page_token = res$next_page_token, key = api_key)
google_places(location = c(-37.817839,144.9673254),place_type = "bicycle_store", radius = 20000, key = api_key)
google_places(search_string = "Bicycle shop, Melbourne, Australia", open_now = TRUE, key = api_key) |
GetBootstrapSD <- function(diseaseData,
controlData,
userFormula,
outform,
fixSens,
Nbootstrap = 100,
verbose = TRUE) {
allrec_bt <- matrix(NA, Nbootstrap, length(outform$allvar)+2)
if(verbose) {
message("Estimating standard error using bootstrap...")
}
for (nb in 1:Nbootstrap) {
oneindx1 <- sample(1:nrow(controlData), nrow(controlData), replace = TRUE)
oneindx2 <- sample(1:nrow(diseaseData), nrow(diseaseData), replace = TRUE)
controlData_bt <- controlData[oneindx1, ]
diseaseData_bt <- diseaseData[oneindx2, ]
if (length(outform[[2]]) == 1) {
expr2 <- paste0("controlData_bt$", outform[[2]])
expr3 <- paste0("diseaseData_bt$", outform[[2]])
} else if (length(outform[[2]]) > 1) {
expr2 <- paste0("controlData_bt[, ", outform[2], "]")
expr3 <- paste0("diseaseData_bt[, ", outform[2], "]")
}
Z_C_bt <- as.matrix(eval(parse(text = expr2)))
Z_D_bt <- as.matrix(eval(parse(text = expr3)))
M0_bt <- eval(parse(text = paste("controlData_bt$",outform[[1]])))
M1_bt <- eval(parse(text = paste("diseaseData_bt$",outform[[1]])))
rqfit <- NULL
expr1 <- paste0("rqfit <- rq(", userFormula, ", tau = ", 1-fixSens, ", data = diseaseData_bt)")
eval(parse(text = expr1))
est_b_bt <- as.numeric(rqfit$coefficients)
ctrl_threshold_bt <- cbind(1, Z_C_bt) %*% est_b_bt
case_threshold_bt <- cbind(1, Z_D_bt) %*% est_b_bt
onephi <- sum(M0_bt <= ctrl_threshold_bt)/length(M0_bt)
allrec_bt[nb, 1:(length(outform$allvar)+1)] <- est_b_bt
allrec_bt[nb, length(outform$allvar)+2] <- onephi
}
return(apply(allrec_bt, 2, sd))
} |
data(Traffic, package = "MASS")
head(Traffic)
data(Traffic, package = "fastR2")
head(Traffic) |
library(bayesplot)
context("Shared: misc. functions")
test_that("suggested_package throws correct errors", {
expect_error(suggested_package("NOPACKAGE"),
"Please install the NOPACKAGE package")
expect_error(suggested_package(c("testthat", "gridExtra")), "length")
expect_silent(suggested_package("testthat"))
expect_silent(suggested_package("testthat", min_version = "0.0.1"))
expect_error(suggested_package("testthat", min_version = "100000.0.0"))
})
test_that("check_ignored_arguments throws correct warnings", {
expect_warning(check_ignored_arguments(a = 1, b = "2"),
"The following arguments were unrecognized and ignored: a, b")
expect_warning(check_ignored_arguments(a = 1, b = "2", ok_args = c("a", "c")),
"The following arguments were unrecognized and ignored: b")
expect_silent(check_ignored_arguments(a = 1, b = "2", ok_args = c("a", "b", "c")))
})
all_pars <- c("param_1", "param_2",
"param[1]", "param[2]",
"param[1,3,5]", "param[2,4,5]",
"alpha", "beta")
test_that("select_parameters throws errors if 'explicit' not found", {
expect_error(select_parameters(explicit = c("alpha", "ALPHA"),
complete_pars = all_pars),
"don't match parameter names: ALPHA")
expect_error(select_parameters(c("BETA", "ALPHA"), complete = all_pars),
"don't match parameter names: BETA, ALPHA")
})
test_that("select_parameters throws errors if no regex matches", {
expect_error(select_parameters(explicit = c("alpha", "beta"),
patterns = "tomato|apple",
complete_pars = all_pars),
"No matches for 'regex_pars'")
})
test_that("select_parameters works with regex", {
expect_identical(select_parameters(patterns = "param", complete = all_pars),
all_pars[-c(7:8)])
expect_identical(select_parameters(patterns = c("param", "tomato"), complete_pars = all_pars),
all_pars[-c(7:8)])
expect_identical(select_parameters(patterns = c("param\\[", "tomato"), complete_pars = all_pars),
all_pars[3:6])
expect_identical(select_parameters(patterns = c("param\\_"), complete_pars = all_pars),
all_pars[1:2])
})
test_that("select_parameters works without regex", {
expect_identical(select_parameters(explicit = "alpha", complete_pars = all_pars),
"alpha")
expect_identical(select_parameters(c("alpha", "param[1,3,5]"), complete_pars = all_pars),
c("alpha", "param[1,3,5]"))
})
test_that("select_parameters works with both explicit and regex", {
expect_identical(select_parameters(explicit = "alpha",
patterns = "param",
complete_pars = all_pars),
c("alpha", all_pars[-c(7:8)]))
expect_identical(select_parameters(explicit = "alpha",
patterns = "alpha",
complete_pars = all_pars),
"alpha")
expect_identical(select_parameters(explicit = c("alpha", "beta"),
patterns = "param\\[|param\\_",
complete_pars = all_pars),
c(all_pars[7:8], all_pars[-c(7:8)]))
}) |
dl_trips_data_trondheim <- function(year, month, filetype = "CSV") {
filetype <- tolower(filetype)
base_url <- "http://data.urbansharing.com/trondheimbysykkel.no/trips/v1"
dl_url <- glue::glue("{base_url}/{year}/{sprintf('%0.2d', month)}.{filetype}")
if (httr::http_error(dl_url)) {
stop("The download URL is invalid.")
}
output_file <- glue::glue("trips_trondheim_{year}_{sprintf('%0.2d', month)}.{filetype}")
download.file(url = dl_url, destfile = output_file)
} |
library(testthat)
library(imputeMulti)
context("int- impute multinomial")
test_that("missing value imputation works", {
enum_comp <- enum_w_miss[complete.cases(enum_w_miss),]
enum_miss <- enum_w_miss[!complete.cases(enum_w_miss),]
dat_comp <- dat[complete.cases(dat),]
dat_miss <- dat[!complete.cases(dat),]
iter6 <- multinomial_em(x_y= x_y, z_Os_y= z_Os_y, enum_comp= enum_comp,
n_obs= nrow(dat), conj_prior= "none",
verbose= FALSE, max_iter= 6)
dat_miss2 <- impute_multinomial_all(dat_miss, iter6@mle_x_y, p=ncol(dat))
imputed_data <- rbind(dat_comp, dat_miss2)
expect_equal(sum(!complete.cases(imputed_data)), 0)
expect_equal(sum(complete.cases(dat_miss2)), nrow(dat_miss2))
expect_equal(
lapply(dat_miss2, levels), lapply(dat, levels)
)
}) |
plot.see_check_collinearity <- function(x,
data = NULL,
colors = c("
...) {
if (is.null(data)) {
dat <- .compact_list(.retrieve_data(x))
} else {
dat <- data
}
if (is.null(dat)) {
return(NULL)
}
dat$group <- "low"
dat$group[dat$VIF >= 5 & dat$VIF < 10] <- "moderate"
dat$group[dat$VIF >= 10] <- "high"
if (ncol(dat) == 5) {
colnames(dat) <- c("x", "y", "se", "facet", "group")
dat[, c("x", "y", "facet", "group")]
} else {
colnames(dat) <- c("x", "y", "se", "group")
dat[, c("x", "y", "group")]
}
if (length(unique(dat$facet)) == 1) {
dat <- dat[, -which(colnames(dat) == "facet")]
}
.plot_diag_vif(dat, colors = colors)
} |
source(file.path("aammrtf", "mock.R"))
source(file.path("_helper", "init.R"))
source(file.path("_helper", "pkgs.R"))
old.state <- tracingState(TRUE)
if (is(unitizer:::trace_test_fun, "functionWithTrace"))
untrace("trace_test_fun", where = asNamespace("unitizer"))
unitizer:::trace_at_end("trace_test_fun", quote(if (!inherits(.res,
"try-error")) cat(sprintf("x: %d\n", .res$value))), print = FALSE,
where = asNamespace("unitizer"))
coi(unitizer:::trace_test_fun())
tracingState(FALSE)
identical(capture.output(unitizer:::trace_test_fun()), character())
tracingState(TRUE)
err <- try(unitizer:::trace_test_fun(stop("hello")), silent = TRUE)
cond <- attr(err, "condition")
conditionMessage(cond)
conditionCall(cond)
f <- function(x, y, z = 5) {
if (missing(x)) {
return(TRUE)
}
else if (z > 5) {
stop("OMG, z > 5")
}
else if (identical(substitute(y), "hey")) {
"substitute!"
}
else FALSE
}
unitizer:::trace_at_end("f", quote(cat("hello\n")), FALSE, environment())
res <- f()
res
res2 <- f(1)
res2
err <- try(f(1, z = 6), silent = TRUE)
is(err, "try-error")
attr(err, "condition")
res3 <- f(1, y = "hey")
res3
try(detach("package:unitizerdummypkg1", unload = TRUE), silent = TRUE)
while ("unitizer.dummy.list" %in% search()) try(detach("unitizer.dummy.list"))
unitizer.dummy.list <- list(z = 23, x = 1, y = "hello")
my.env <- new.env()
state.set <- c(search.path = 2L)
untz.glob <- unitizer:::unitizerGlobal$new(par.env = my.env,
enable.which = state.set, set.global = TRUE)
untz.glob$shimFuns()
sp <- search()
curr2 <- sp[[2L]]
identical(environmentName(parent.env(my.env)), curr2)
library("unitizerdummypkg1", lib.loc = TMP.LIB)
identical(environmentName(parent.env(my.env)), "package:unitizerdummypkg1")
attach(unitizer.dummy.list)
identical(environmentName(parent.env(my.env)), "unitizer.dummy.list")
detach("unitizer.dummy.list")
identical(environmentName(parent.env(my.env)), "package:unitizerdummypkg1")
detach("package:unitizerdummypkg1", unload = TRUE)
identical(environmentName(parent.env(my.env)), curr2)
untz.glob$checkShims()
untz.glob$state()
keep.more <- c(getOption("unitizer.search.path.keep.base"))
unitizer:::search_path_trim(keep.more, global = untz.glob)
untz.glob$state()
identical(environmentName(parent.env(my.env)), search()[[2L]])
untz.glob$resetFull()
identical(environmentName(parent.env(my.env)), curr2)
untz.glob$unshimFuns()
!any(vapply(list(library, detach, attach), inherits, logical(1L),
"functionWithTrace"))
untz.glob$release()
untz.glob <- unitizer:::unitizerGlobal$new(par.env = my.env,
enable.which = state.set, set.global = TRUE)
tracingState(FALSE)
untz.glob$shimFuns()
parent.env(my.env)
tracingState(TRUE)
untz.glob$release()
untz.glob <- unitizer:::unitizerGlobal$new(par.env = my.env,
set.global = TRUE)
trace("library", quote(cat("I am traced\n")), where = .BaseNamespaceEnv)
lib.trace <- library
untz.glob$shimFuns()
parent.env(my.env)
inherits(attach, "functionWithTrace")
inherits(detach, "functionWithTrace")
inherits(library, "functionWithTrace")
identical(lib.trace, library)
untrace("library", where = .BaseNamespaceEnv)
untz.glob$release()
untz.glob <- unitizer:::unitizerGlobal$new(par.env = my.env,
set.global = TRUE)
untz.glob$shimFuns()
trace("attach", quote(cat("I am traced\n")), where = .BaseNamespaceEnv)
attach.trace <- attach
untz.glob$checkShims()
parent.env(my.env)
inherits(detach, "functionWithTrace")
inherits(library, "functionWithTrace")
inherits(attach, "functionWithTrace")
identical(attach.trace, attach)
untrace("attach", where = .BaseNamespaceEnv)
untz.glob$release()
untz.glob <- unitizer:::unitizerGlobal$new(par.env = my.env,
set.global = TRUE)
untz.glob$shimFuns()
tracingState(FALSE)
untz.glob$checkShims()
parent.env(my.env)
tracingState(TRUE)
inherits(detach, "functionWithTrace")
inherits(library, "functionWithTrace")
inherits(attach, "functionWithTrace")
untz.glob$shimFuns("baljevzxhjLsdc")
try(untz.glob$shimFun("sum"))
mock(unitizer:::trace_at_end, quote(stop("trace_at_end fail")))
any(
grepl(
"trace_at_end fail",
capture.output(
trace.fail <- untz.glob$shimFun("library"), type = "message"
),
fixed = TRUE
)
)
unmock(unitizer:::trace_at_end)
trace.fail
mock(unitizer:::trace_at_end, quote(message("random message")))
untz.glob$shimFun("library")
unmock(unitizer:::trace_at_end)
mock(unitizer:::trace_at_end, quote(TRUE))
dont.trace <- untz.glob$shimFun("library")
unmock(unitizer:::trace_at_end)
dont.trace
untz.glob$release()
untz.glob <- unitizer:::unitizerGlobal$new(par.env = my.env, set.global = TRUE)
untz.glob$shimFuns()
mock(
unitizer:::untrace_utz,
quote({
message("untrace dummy")
base::untrace(what = what, signature = signature, where = where)
})
)
untz.glob$unshimFuns()
unmock(unitizer:::untrace_utz)
untz.glob$release()
try(detach("package:unitizerdummypkg1", unload = TRUE), silent = TRUE)
while ("unitizer.dummy.list" %in% search()) try(detach("unitizer.dummy.list"))
fun <- function() {
if (TRUE)
return(1)
else {
{
2 + 2
identity(c(1, 2, return(3), {
list(1, 2, 5)
return(return(4))
}))
return(5)
}
return(6)
}
if (TRUE)
return(7)
else return(8)
return(9)
return(10)
}
ret.loc <- unitizer:::find_returns(fun)
ret.loc
all(vapply(unitizer:::get_returns(fun, ret.loc), function(x) x[[1L]] ==
quote(return), logical(1L))) |
layer_spatial <- function(data, mapping, ...) {
UseMethod("layer_spatial")
}
annotation_spatial <- function(data, mapping, ...) {
UseMethod("annotation_spatial")
}
layer_spatial.default <- function(data, mapping = aes(), inherit.aes = FALSE, sf_params = list(), ...) {
ggplot2::geom_sf(
mapping = mapping,
data = do.call(sf::st_as_sf, c(list(data), sf_params)),
inherit.aes = inherit.aes,
...
)
}
annotation_spatial.default <- function(data, mapping = aes(), inherit.aes = FALSE, sf_params = list(), ...) {
ggplot2::geom_sf(
mapping = mapping,
data = do.call(sf::st_as_sf, c(list(data), sf_params)),
inherit.aes = inherit.aes,
na.rm = TRUE,
stat = StatSfAnnotation,
...
)
}
shadow_spatial <- function(data, ...) {
UseMethod("shadow_spatial")
}
shadow_spatial.default <- function(data, ...) {
ggplot2::stat_sf(
mapping = aes(),
data = sf::st_as_sf(data),
inherit.aes = FALSE,
na.rm = FALSE,
geom = GeomBlankSf
)
}
StatSfAnnotation <- ggplot2::ggproto(
"StatSfAnnotation",
ggplot2::StatSf,
compute_group = function(data, scales) {
data$xmin <- NA_real_
data$xmax <- NA_real_
data$ymin <- NA_real_
data$ymax <- NA_real_
data
}
)
GeomBlankSf <- ggplot2::ggproto(
"GeomBlankSf",
ggplot2::GeomBlank,
extra_params = c(ggplot2::GeomBlank$extra_params, "legend")
) |
make_progression_handler <- function(name, reporter = list(), handler = NULL, enable = getOption("progressr.enable", interactive()), enable_after = getOption("progressr.enable_after", 0.0), times = getOption("progressr.times", +Inf), interval = getOption("progressr.interval", 0.0), intrusiveness = 1.0, clear = getOption("progressr.clear", TRUE), target = "terminal", ...) {
enable <- as.logical(enable)
stop_if_not(is.logical(enable), length(enable) == 1L, !is.na(enable))
if (!enable) times <- 0
name <- as.character(name)
stop_if_not(length(name) == 1L, !is.na(name), nzchar(name))
stop_if_not(is.list(reporter))
enable_after <- as.numeric(enable_after)
stop_if_not(is.numeric(enable_after), length(enable_after),
!is.na(enable_after), enable_after >= 0)
times <- as.numeric(times)
stop_if_not(length(times) == 1L, is.numeric(times), !is.na(times),
times >= 0)
interval <- as.numeric(interval)
stop_if_not(length(interval) == 1L, is.numeric(interval),
!is.na(interval), interval >= 0)
clear <- as.logical(clear)
stop_if_not(is.logical(clear), length(clear) == 1L, !is.na(clear))
stop_if_not(is.character(target))
if (times == 0 || is.infinite(interval) || is.infinite(intrusiveness)) {
handler <- function(p) NULL
}
for (key in setdiff(c("reset", "initiate", "update", "finish", "hide", "unhide", "interrupt"), names(reporter))) {
reporter[[key]] <- structure(function(...) NULL, class = "null_function")
}
active <- FALSE
max_steps <- NULL
step <- NULL
message <- NULL
auto_finish <- TRUE
timestamps <- NULL
milestones <- NULL
prev_milestone <- NULL
finished <- FALSE
enabled <- FALSE
owner <- NULL
done <- list()
.validate_internal_state <- function(label = "<no-label>") {
error <- function(...) {
msg <- sprintf(...)
stop(sprintf(".validate_internal_state(%s): %s", sQuote(label), msg))
}
if (!is.null(timestamps)) {
if (length(timestamps) == 0L) {
error(paste("length(timestamps) == 0L but not is.null(timestamps):",
sQuote(deparse(timestamps))))
}
}
}
reporter_args <- function(progression) {
.validate_internal_state("reporter_args() ... begin")
if (!enabled && !is.null(timestamps)) {
dt <- difftime(Sys.time(), timestamps[1L], units = "secs")
enabled <<- (dt >= enable_after)
}
config <- list(
max_steps = max_steps,
times = times,
interval = interval,
enable_after = enable_after,
auto_finish = auto_finish,
clear = clear,
target = target
)
state <- list(
step = step,
message = message,
timestamps = timestamps,
delta = step - prev_milestone,
enabled = enabled
)
if (length(state$delta) == 0L) state$delta <- 0L
.validate_internal_state("reporter_args() ... end")
c(config, state, list(
config = config,
state = state,
progression = progression
))
}
reset_internal_state <- function() {
active <<- FALSE
max_steps <<- NULL
step <<- NULL
message <<- NULL
auto_finish <<- TRUE
timestamps <<- NULL
milestones <<- NULL
prev_milestone <<- NULL
finished <<- FALSE
enabled <<- FALSE
owner <<- NULL
done <<- list()
}
reset_reporter <- function(p) {
args <- reporter_args(progression = p)
debug <- getOption("progressr.debug", FALSE)
if (debug) {
mprintf("reset_reporter() ...")
mstr(args)
}
do.call(reporter$reset, args = args)
.validate_internal_state("reset_reporter() ... done")
if (debug) mprintf("reset_reporter() ... done")
}
initiate_reporter <- function(p) {
args <- reporter_args(progression = p)
debug <- getOption("progressr.debug", FALSE)
if (debug) {
mprintf("initiate_reporter() ...")
mstr(args)
}
stop_if_not(!isTRUE(active))
stop_if_not(is.null(prev_milestone), length(milestones) > 0L)
do.call(reporter$initiate, args = args)
active <<- TRUE
finished <<- FALSE
.validate_internal_state("initiate_reporter() ... done")
if (debug) mprintf("initiate_reporter() ... done")
}
update_reporter <- function(p) {
args <- reporter_args(progression = p)
debug <- getOption("progressr.debug", FALSE)
if (debug) {
mprintf("update_reporter() ...")
mstr(args)
}
stop_if_not(isTRUE(active))
stop_if_not(!is.null(step), length(milestones) > 0L)
do.call(reporter$update, args = args)
.validate_internal_state("update_reporter() ... done")
if (debug) mprintf("update_reporter() ... done")
}
hide_reporter <- function(p) {
args <- reporter_args(progression = p)
debug <- getOption("progressr.debug", FALSE)
if (debug) {
mprintf("hide_reporter() ...")
mstr(args)
}
if (is.null(reporter$hide)) {
if (debug) mprintf("hide_reporter() ... skipping; not supported")
return()
}
do.call(reporter$hide, args = args)
.validate_internal_state("hide_reporter() ... done")
if (debug) mprintf("hide_reporter() ... done")
}
unhide_reporter <- function(p) {
args <- reporter_args(progression = p)
debug <- getOption("progressr.debug", FALSE)
if (debug) {
mprintf("unhide_reporter() ...")
mstr(args)
}
if (is.null(reporter$unhide)) {
if (debug) mprintf("unhide_reporter() ... skipping; not supported")
return()
}
do.call(reporter$unhide, args = args)
.validate_internal_state("unhide_reporter() ... done")
if (debug) mprintf("unhide_reporter() ... done")
}
interrupt_reporter <- function(p) {
args <- reporter_args(progression = p)
debug <- getOption("progressr.debug", FALSE)
if (debug) {
mprintf("interrupt_reporter() ...")
mstr(args)
}
if (is.null(reporter$interrupt)) {
if (debug) mprintf("interrupt_reporter() ... skipping; not supported")
return()
}
do.call(reporter$interrupt, args = args)
.validate_internal_state("interrupt_reporter() ... done")
if (debug) mprintf("interrupt_reporter() ... done")
}
finish_reporter <- function(p) {
args <- reporter_args(progression = p)
debug <- getOption("progressr.debug", FALSE)
if (debug) {
mprintf("finish_reporter() ...")
mstr(args)
}
if (active && !finished) {
do.call(reporter$finish, args = args)
} else {
if (debug) {
why <- if (!active && !finished) {
"not active"
} else if (!active && finished) {
"not active and already finished"
} else if (active && finished) {
"already finished"
}
message(sprintf("- Hmm ... got a request to 'finish' handler, but it's %s. Oh well, will finish it then", why))
}
}
reset_internal_state()
finished <<- TRUE
if (debug) message("- owner: ", deparse(owner))
.validate_internal_state("finish_reporter() ... done")
if (debug) mprintf("finish_reporter() ... done")
}
is_owner <- function(p) {
progressor_uuid <- p[["progressor_uuid"]]
if (is.null(owner)) owner <<- progressor_uuid
(owner == progressor_uuid)
}
is_duplicated <- function(p) {
progressor_uuid <- p[["progressor_uuid"]]
session_uuid <- p[["session_uuid"]]
progression_index <- p[["progression_index"]]
progression_time <- p[["progression_time"]]
progression_id <- sprintf("%s-%d-%s", session_uuid, progression_index, progression_time)
db <- done[["progressor_uuid"]]
res <- is.element(progression_id, db)
if (!res) {
db <- c(db, progression_id)
done[["progressor_uuid"]] <<- db
}
res
}
if (is.null(handler)) {
handler <- function(p) {
stop_if_not(inherits(p, "progression"))
if (is_fork_child()) return(invisible(FALSE))
if (inherits(p, "control_progression")) {
type <- p[["type"]]
if (type == "reset") {
reset_internal_state()
reset_reporter(p)
.validate_internal_state(sprintf("handler(type=%s) ... end", type))
} else if (type == "shutdown") {
finish_reporter(p)
.validate_internal_state(sprintf("handler(type=%s) ... end", type))
} else if (type == "hide") {
hide_reporter(p)
.validate_internal_state(sprintf("handler(type=%s) ... end", type))
} else if (type == "unhide") {
unhide_reporter(p)
.validate_internal_state(sprintf("handler(type=%s) ... end", type))
} else if (type == "interrupt") {
interrupt_reporter(p)
.validate_internal_state(sprintf("handler(type=%s) ... end", type))
} else {
stop("Unknown control_progression type: ", sQuote(type))
}
.validate_internal_state(sprintf("control_progression ... end", type))
return(invisible(finished))
}
debug <- getOption("progressr.debug", FALSE)
if (!is_owner(p)) {
if (debug) message("- not owner of this progression. Skipping")
return(invisible(finished))
}
duplicated <- is_duplicated(p)
type <- p[["type"]]
if (debug) {
mprintf("Progression calling handler %s ...", sQuote(type))
mprintf("- progression:")
mstr(p)
mprintf("- progressor_uuid: %s", p[["progressor_uuid"]])
mprintf("- progression_index: %s", p[["progression_index"]])
mprintf("- duplicated: %s", duplicated)
}
if (duplicated) {
if (debug) mprintf("Progression calling handler %s ... condition already done", sQuote(type))
return(invisible(finished))
} else if (active && finished) {
if (debug) mprintf("Progression calling handler %s ... active but already finished", sQuote(type))
return(invisible(finished))
}
if (type == "initiate") {
if (active) {
if (debug) message("- cannot 'initiate' handler, because it is already active")
return(invisible(finished))
}
max_steps <<- p[["steps"]]
if (debug) mstr(list(max_steps=max_steps))
stop_if_not(!is.null(max_steps), is.numeric(max_steps), length(max_steps) == 1L, max_steps >= 0)
auto_finish <<- p[["auto_finish"]]
times <- min(times, max_steps)
if (debug) mstr(list(auto_finish = auto_finish, times = times, interval = interval, intrusiveness = intrusiveness))
times <- min(c(times / intrusiveness, max_steps), na.rm = TRUE)
times <- max(times, 1L)
interval <- interval * intrusiveness
if (debug) mstr(list(times = times, interval = interval))
milestones <<- if (times == 1L) {
c(max_steps)
} else if (times == 2L) {
c(0L, max_steps)
} else {
seq(from = 0L, to = max_steps, length.out = times + 1L)[-1]
}
timestamps <<- rep(as.POSIXct(NA), times = max_steps)
timestamps[1] <<- Sys.time()
step <<- 0L
message <<- character(0L)
if (debug) mstr(list(finished = finished, milestones = milestones))
initiate_reporter(p)
prev_milestone <<- step
.validate_internal_state(sprintf("handler(type=%s) ... end", type))
} else if (type == "finish") {
if (debug) mstr(list(finished = finished, milestones = milestones))
finish_reporter(p)
.validate_internal_state("type=finish")
} else if (type == "update") {
if (!active) {
if (debug) message("- cannot 'update' handler, because it is not active")
return(invisible(finished))
}
if (debug) mstr(list(step=step, "p$amount"=p[["amount"]], "p$step"=p[["step"]], max_steps=max_steps))
if (!is.null(p[["step"]])) {
p[["amount"]] <- p[["step"]] - step
}
step <<- min(max(step + p[["amount"]], 0L), max_steps)
stop_if_not(step >= 0L)
msg <- conditionMessage(p)
if (length(msg) > 0) message <<- msg
if (step > 0) timestamps[step] <<- Sys.time()
if (debug) mstr(list(finished = finished, step = step, milestones = milestones, prev_milestone = prev_milestone, interval = interval))
.validate_internal_state("type=update")
if ((length(milestones) > 0L && step >= milestones[1]) ||
p[["amount"]] == 0) {
skip <- FALSE
if (interval > 0 && step > 0) {
dt <- difftime(timestamps[step], timestamps[max(prev_milestone, 1L)], units = "secs")
skip <- (dt < interval)
if (debug) mstr(list(dt = dt, timestamps[step], timestamps[prev_milestone], skip = skip))
}
if (!skip) {
if (debug) mstr(list(milestones = milestones))
update_reporter(p)
if (p[["amount"]] > 0) prev_milestone <<- step
}
if (p[["amount"]] > 0) {
milestones <<- milestones[milestones > step]
if (auto_finish && step == max_steps) {
if (debug) mstr(list(type = "finish (auto)", milestones = milestones))
finish_reporter(p)
}
}
}
.validate_internal_state(sprintf("handler(type=%s) ... end", type))
} else {
stop("Unknown 'progression' type: ", sQuote(type))
}
.validate_internal_state(sprintf("handler() ... end", type))
if (debug) mprintf("Progression calling handler %s ... done", sQuote(type))
invisible(finished)
}
}
class(handler) <- c(sprintf("%s_progression_handler", name),
"progression_handler", "calling_handler",
class(handler))
handler
}
print.progression_handler <- function(x, ...) {
print(sys.calls())
s <- sprintf("Progression calling handler of class %s:", sQuote(class(x)[1]))
env <- environment(x)
s <- c(s, " * configuration:")
s <- c(s, sprintf(" - name: %s", sQuote(env$name %||% "<NULL>")))
s <- c(s, sprintf(" - max_steps: %s", env$max_steps %||% "<NULL>"))
s <- c(s, sprintf(" - enable: %s", env$enable))
s <- c(s, sprintf(" - enable_after: %g seconds", env$enable_after))
s <- c(s, sprintf(" - times: %g", env$times))
s <- c(s, sprintf(" - interval: %g seconds", env$interval))
s <- c(s, sprintf(" - intrusiveness: %g", env$intrusiveness))
s <- c(s, sprintf(" - auto_finish: %s", env$auto_finish))
s <- c(s, sprintf(" - clear: %s", env$clear))
s <- c(s, sprintf(" - target: %s", paste(sQuote(env$target), collapse = ", ")))
s <- c(s, sprintf(" - milestones: %s", hpaste(env$milestones %||% "<NULL>")))
s <- c(s, sprintf(" - owner: %s", hpaste(env$owner %||% "<NULL>")))
s <- c(s, " * state:")
s <- c(s, sprintf(" - enabled: %s", env$enabled))
s <- c(s, sprintf(" - finished: %s", env$finished))
s <- c(s, sprintf(" - step: %s", env$step %||% "<NULL>"))
s <- c(s, sprintf(" - message: %s", env$message %||% "<NULL>"))
s <- c(s, sprintf(" - prev_milestone: %s", env$prev_milestone %||% "<NULL>"))
s <- c(s, sprintf(" - delta: %g", (env$step - env$prev_milestone) %||% 0L))
s <- c(s, sprintf(" - timestamps: %s", hpaste(env$timestamps %||% "<NULL>")))
s <- paste(s, collapse = "\n")
cat(s, "\n", sep = "")
}
handler_backend_args <- function(...) {
args <- list(...)
if (length(args) == 0L) return(list())
names <- names(args)
if (is.null(names) || !all(nzchar(names))) {
stop("Additional arguments must be named")
}
names <- setdiff(names, names(formals(make_progression_handler)))
args[names]
} |
test_that("kinshipLR() catches input errors", {
s = singleton(1)
expect_error(kinshipLR(s), "The input must contain at least two pedigrees")
expect_error(kinshipLR(list(s)), "The input must contain at least two pedigrees")
expect_error(kinshipLR(list(s, 1)), "The input is not a list of pedigrees")
expect_error(kinshipLR(list(s, s)), "None of the pedigrees")
expect_error(kinshipLR(s, s), "None of the pedigrees")
expect_error(kinshipLR(s, s, source = 1), "The source pedigree has no attached markers")
expect_error(kinshipLR(list(s, s), source = 1), "The source pedigree has no attached markers")
s1 = setMarkers(s, marker(s))
expect_error(kinshipLR(s1, s1, ref = 3), "Invalid value for `ref`")
expect_error(kinshipLR(s1, s1, ref = 0), "Invalid value for `ref`")
expect_error(kinshipLR(s1, s1, ref = "unrel"), "Invalid value for `ref`")
expect_error(kinshipLR(a=s, a=s1), "Duplicated hypothesis name")
expect_error(kinshipLR(s, H1=s1), "Duplicated hypothesis name")
s2 = setMarkers(s, list(marker(s), marker(s)))
expect_error(kinshipLR(s1, s2), "When `markers = NULL`, all pedigrees must have the same number of attached markers")
})
test_that("kinshipLR() computes correctly in paternity case", {
H1 = nuclearPed(fa = "fa", child = "ch")
H2 = list(singleton("fa"), singleton("ch"))
m = marker(H1, fa = "A/A", ch = "A/A", afreq = c(A=0.05, B=0.95))
H1 = setMarkers(H1, m)
lr = kinshipLR(H1, H2)$LRtotal[[1]]
expect_equal(lr, 20)
}) |
topgenes_extract <- function(generes, padj = 0.05, FC = 1.5, topNum = 30) {
if(class(generes) != "list") {
stop("generes must be of class list.")
}
if(all(is.numeric(padj), is.numeric(FC), is.numeric(topNum))[1] == FALSE) {
stop("padj, FC, and topNum must all be of class numeric.")
}
if(is.null(generes[[1]]$avg_logFC)) {
message("Seurat V4 or later was used to identify cell-type markers, adding 'avg_logFC' column. It has the same data as avg_log2FC but is compatible with downstream functions in scMappR.")
for(z in 1:length(generes))
generes[[z]]$avg_logFC <- generes[[z]]$avg_log2FC
}
topGenes <- list()
for(i in 1:length(generes)) {
genes <- rownames(generes[[i]])[generes[[i]]$avg_logFC > log2(FC) & generes[[i]]$p_val_adj < padj]
if(length(genes) > topNum) {
genes <- genes[1:topNum]
}
topGenes[[i]] <- genes
}
names(topGenes) <- names(generes)
return(topGenes)
} |
rm(list=ls(all=TRUE))
if (!require(DBI)) install.packages("DBI")
if (!require(RSQLite)) install.packages("RSQLite")
if (!require(ggplot2)) install.packages("ggplot2")
if (!require(grid)) install.packages("grid")
if (!require(corrplot)) install.packages("corrplot")
if (!require(zoo)) install.packages("zoo")
if (!require(magrittr)) install.packages("magrittr")
library(DBI)
library(ggplot2)
library(grid)
library(corrplot)
library(zoo)
library(magrittr)
library(dbConnect)
con <- dbConnect(RSQLite::SQLite(), dbname='database.db')
currencies <- dbGetQuery(con, "SELECT * FROM currency")
vals <- dbGetQuery(con, "SELECT * FROM val")
rm(con)
vals$id <- NULL
currencies$id <- NULL
vals$datetime <- as.Date(vals$datetime)
vals <- vals[!duplicated(vals[,6:7]),]
interpolate.missing.data <- function(data) {
currencies <- unique(data$currency_slug)
newrows <- do.call("rbind", lapply(currencies, FUN=missing.date.rows, data))
data <- rbind(data, newrows)
data <- data[order(data$currency_slug,data$datetime),]; rownames(data) <- 1:nrow(data)
for (currency in currencies) {
idx <- colSums(!is.na(data[data$currency_slug==currency,1:5])) > 1
data[data$currency_slug==currency,c(idx,FALSE,FALSE)] <- na.approx(data[data$currency_slug==currency,c(idx,FALSE,FALSE)], na.rm=FALSE)
}
return(data)
}
missing.date.rows <- function(currency, data) {
dates <- unique(data[data$currency_slug==currency,6])
alldates <- seq(dates[1],dates[length(dates)],by="+1 day")
missingdates <- setdiff(alldates, dates)
return(data.frame(price_usd=rep(NA, length(missingdates)),
price_btc=rep(NA, length(missingdates)),
volume_usd=rep(NA, length(missingdates)),
market_cap_usd=rep(NA, length(missingdates)),
available_supply=rep(NA, length(missingdates)),
datetime=as.Date(missingdates, origin="1970-01-01"),
currency_slug=rep(currency, length(missingdates))))
}
vals <- interpolate.missing.data(vals)
market.data <- function(data) {
dates <- sort(unique(data$datetime))
cap <- sapply(dates, FUN=function(date) sum(data[data$datetime==date,4]))
returns <- c(0,diff(cap)/cap[-length(cap)])
logreturns <- c(0,log(cap[-1]/cap[-length(cap)]))
volatility.30d <- sapply(1:length(logreturns), FUN=function(i) sd(logreturns[(max(i-30,0):i)]))*sqrt(365)
volatility.90d <- sapply(1:length(logreturns), FUN=function(i) sd(logreturns[(max(i-90,0):i)]))*sqrt(365)
herfindahl <- sapply(dates, FUN=function(date) sum((data[vals$datetime==date,4]/sum(data[data$datetime==date,4]))^2))
data.frame(datetime=dates, cap=cap, return=returns, logreturn=logreturns, volatility.30d=volatility.30d, volatility.90d=volatility.90d, herfindahl=herfindahl)
}
market <- market.data(vals)
plot.market <- function(market) {
p1 <- ggplot(market, aes(datetime, cap)) +
geom_line() +
labs(x="Date", y="Market cap", title="Overall market") +
theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank())
p2 <- ggplot(market, aes(datetime, logreturn)) +
geom_line() +
labs(x="Date", y="Log return") +
theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank())
p3 <- ggplot(market, aes(datetime, volatility.30d)) +
geom_line() +
labs(x="Date", y="Annualized volatility") +
theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank())
p4 <- ggplot(market, aes(datetime, herfindahl)) + geom_line() + labs(x="Date", y="Herfindahl index")
library(gtable)
library(grid)
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
g3 <- ggplotGrob(p3)
g4 <- ggplotGrob(p4)
g <- rbind(g1, g2, g3, g4, size="first")
g$widths <- unit.pmax(g1$widths, g2$widths, g3$widths, g4$widths)
g$layout[grepl("guide", g$layout$name),c("t","b")] <- c(1,nrow(g))
grid.newpage()
grid.draw(g)
ggsave("Market-statistics.png", g, width=8, height=6, dpi=100, units="in")
}
plot.market(market)
currencies$mcap <- sapply(currencies$slug, FUN=function(x) vals[vals$currency_slug==x & vals$datetime==max(vals[vals$currency_slug==x,]$datetime),]$market_cap_usd)
currencies <- currencies[order(currencies$mcap,currencies$slug, decreasing=TRUE),]; rownames(currencies) <- 1:nrow(currencies)
vals$return <- Reduce(c,sapply(unique(vals$currency_slug), FUN=function(x) c(0,diff(vals[vals$currency_slug==x,]$price_usd)/(vals[vals$currency_slug==x,]$price_usd)[-length(vals[vals$currency_slug==x,]$price_usd)])))
vals$logreturn <- Reduce(c,sapply(unique(vals$currency_slug), FUN=function(x) c(0,log(vals[vals$currency_slug==x,]$price_usd[-1]/vals[vals$currency_slug==x,]$price_usd[-length(vals[vals$currency_slug==x,]$price_usd)]))))
plot.currency <- function(data, slug) {
data <- data[data$currency_slug==slug,]
data$volatility.30d <- sapply(1:nrow(data), FUN=function(i) sd(data$logreturn[(max(i-30,0):i)]))*sqrt(365)
p1 <- ggplot(data, aes(datetime, market_cap_usd)) +
geom_line() +
labs(x="Date", y="Market cap", title=slug) +
theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank())
p2 <- ggplot(data, aes(datetime, logreturn)) +
geom_line() + labs(x="Date", y="Log return") +
theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank())
p3 <- ggplot(data, aes(datetime, volatility.30d)) + geom_line() + labs(x="Date", y="Annualized volatility")
library(gtable)
library(grid)
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
g3 <- ggplotGrob(p3)
g <- rbind(g1, g2, g3, size="first")
g$widths <- unit.pmax(g1$widths, g2$widths, g3$widths)
g$layout[grepl("guide", g$layout$name),c("t","b")] <- c(1,nrow(g))
grid.newpage()
grid.draw(g)
ggsave("Bitcoin-statistics.png", g, width=8, height=6, dpi=100, units="in")
}
plot.currency(vals, "bitcoin")
plot.currencies <- function(data, slugs) {
data <- data[data$currency_slug %in% slugs,]
data$volatility.30d <- Reduce(c,sapply(unique(data$currency_slug), FUN=function(x) sapply(1:length(data[data$currency_slug==x,]$logreturn), FUN=function(i) sd(data[data$currency_slug==x,]$logreturn[(max(i-30,0):i)]))))*sqrt(365)
p1 <- ggplot(data, aes(datetime, market_cap_usd, color=factor(currency_slug))) +
geom_line() +
labs(x="Date", y="Market cap", title=paste(slugs, collapse=", ")) +
theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank(), legend.title=element_blank())
p2 <- ggplot(data, aes(datetime, logreturn, color=factor(currency_slug))) +
geom_line() +
labs(x="Date", y="Log return") +
theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank(), legend.title=element_blank())
p3 <- ggplot(data, aes(datetime, volatility.30d, color=factor(currency_slug))) +
geom_line() +
labs(x="Date", y="Annualized volatility")
library(gtable)
library(grid)
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
g3 <- ggplotGrob(p3)
g <- rbind(g1, g2, g3, size="first")
g$widths <- unit.pmax(g1$widths, g2$widths, g3$widths)
g$layout[grepl("guide", g$layout$name),c("t","b")] <- c(1,nrow(g))
grid.newpage()
grid.draw(g)
ggsave("Coin-statistics.png", g, width=8, height=6, dpi=100, units="in")
}
plot.currencies(vals, c("bitcoin","ethereum", "ripple"))
analysis.data <- function(currencies, data, market=NULL) {
temp <- lapply(currencies, FUN=function(x) subset(data, currency_slug==x))
temp <- Reduce(function(df1, df2) merge(df1, df2, by="datetime"), temp)
if (length(currencies) > 1)
colnames(temp) <- c("datetime", sapply(currencies, function(slug) sapply(colnames(data)[c(1:5,7:9)], function(x) paste(x, slug, sep="_"))))
if (!is.null(market))
temp <- merge(temp, market, by="datetime")
data.frame(temp)
}
plot.return.vs.return <- function(currency1, currency2, data) {
data <- analysis.data(c(currency1, currency2), data)
cor_ <- cor(data[[paste("logreturn_",currency1,sep="")]], data[[paste("logreturn_",currency2,sep="")]])
p <- ggplot(data, aes_string(x=paste("logreturn_",currency1,sep=""), y=paste("logreturn_",currency2,sep="")))
p + geom_point() +
labs(title=paste("Returns: ",currency1," vs ",currency2," (cor = ",round(cor_, digits=4),")",sep=""), x=paste(currency1, "Return"), y=paste(currency2, "Return")) +
theme(legend.title=element_blank())
ggsave("Bitcoin-vs-ethereum-returns.png", width=8, height=4, dpi=100, units="in")
}
plot.return.vs.return("bitcoin", "ethereum", vals[vals$datetime>as.Date("2017-12-31"),])
analysis.return.data <- function(currencies, data) {
data <- reshape(data[data$currency_slug %in% currencies,c(6,7,9)], direction="wide", idvar="datetime", timevar="currency_slug")
colnames(data) <- c("datetime", sort(currencies))
data <- data[,c("datetime", currencies)]
return(data)
}
png(filename="Corrplot.png", width=800, height=700, units="px")
corrplot(cor(analysis.return.data(currencies[1:25,]$slug,vals[vals$datetime>as.Date("2017-12-31"),])[,-1],
use = "pairwise.complete.obs"), method="ellipse")
dev.off()
plot.corr.timeline <- function(currency1, currency2, mindays, maxdays, data) {
data <- analysis.data(c(currency1, currency2), data)
data$corr <- sapply(1:nrow(data), FUN=function(i) if(i<mindays) return(NA) else cor(data[max(1,i-maxdays):i,9],data[max(1,i-maxdays):i,17]))
p <- ggplot(data, aes(datetime, corr))
p + geom_line() + labs(x="Date", y="Correlation", title=paste("Correlation timeline: ", paste(c(currency1, currency2), collapse=", ")))
ggsave("Corr-timeline.png", width=8, height=4, dpi=100, units="in")
}
plot.corr.timeline("bitcoin", "ethereum", 30, 90, vals)
plot.return.vs.market <- function(currency, data, market) {
data <- analysis.data(currency, data, market)
cor_ <- cor(data$logreturn.x, data$logreturn.y)
p <- ggplot(data, aes(x=logreturn.x, y=logreturn.y))
p + geom_point() +
labs(title=paste("Returns: ",currency," vs Market (cor = ",round(cor_, digits=4),")",sep=""), x=paste(currency, "return"), y="Market return") +
theme(legend.title=element_blank())
ggsave("Ethereum-vs-market-return.png", width=8, height=4, dpi=100, units="in")
}
plot.return.vs.market("ethereum", vals[vals$datetime>as.Date("2017-12-31"),], market)
currency.beta <- function(currency, data, market) {
dates <- intersect(data[data$currency_slug==currency,]$datetime, market$datetime)
return(cov(data[data$currency_slug==currency & data$datetime %in% dates,]$logreturn,
market[market$datetime %in% dates,]$logreturn)/var(market[market$datetime %in% dates,]$logreturn))
}
currencies$beta <- sapply(currencies$slug, FUN=currency.beta, vals[vals$datetime>as.Date("2017-12-31"),], market)
plot.beta.vs.mcap.num <- function(num, currencies) {
data <- currencies[order(currencies$mcap, decreasing=TRUE),]
data <- data[0:num,]
p <- ggplot(data, aes(x=mcap, y=beta))
p + geom_point() +
scale_x_log10() +
geom_text(aes(label=name),hjust=0, vjust=0) +
labs(title="Beta vs Market capitalisation", x="Market capitalisation [USD] (log scale)", y="Beta") +
theme(legend.title=element_blank())
ggsave("Beta-vs-mcap.png", width=8, height=5, dpi=100, units="in")
}
plot.beta.vs.mcap.num(25, currencies)
plot.beta.timeline <- function(currencies, mindays, maxdays, data, market) {
data <- data[data$currency_slug %in% currencies,]
dates <- intersect(data$datetime, market$datetime)
result <- data.frame(datetime=as.Date(rep(dates, times=length(currencies)), origin="1970-01-01"), currency=rep(currencies,each=length(dates)))
result$beta <- Reduce(c, sapply(currencies,
function(currency) sapply(dates,
function(date) if(nrow(data[data$currency_slug==currency & date-maxdays<data$datetime & data$datetime<=date,])<mindays) return(NA) else currency.beta(currency, data[data$currency_slug==currency & date-maxdays<data$datetime & data$datetime<=date,], market))))
p <- ggplot(result, aes(datetime, beta, color=factor(currency)))
p + geom_line() + labs(x="Date", y="Beta", title=paste("Beta timeline: ", paste(currencies, collapse=", "))) + theme(legend.title=element_blank())
ggsave("Beta-timeline.png", width=8, height=4, dpi=100, units="in")
}
plot.beta.timeline(c("bitcoin","ethereum","ripple"), 30, 90, vals, market) |
surfaceIndex<-function(Daily){
localDaily <- Daily
bottomLogQ<- min(localDaily$LogQ, na.rm = TRUE) - 0.05
topLogQ <- max(localDaily$LogQ, na.rm = TRUE) + 0.05
stepLogQ <-(topLogQ-bottomLogQ)/13
vectorLogQ <- seq(bottomLogQ,topLogQ,stepLogQ)
stepYear<-1/16
bottomYear<-floor(min(localDaily$DecYear, na.rm = TRUE))
topYear<-ceiling(max(localDaily$DecYear, na.rm = TRUE))
vectorYear<-seq(bottomYear,topYear,stepYear)
nVectorYear<-length(vectorYear)
surfaceIndexParameters<-list(bottomLogQ=bottomLogQ,
stepLogQ=stepLogQ,
nVectorLogQ=14,
bottomYear=bottomYear,
stepYear=stepYear,
nVectorYear=nVectorYear,
vectorYear=vectorYear,
vectorLogQ=vectorLogQ)
return(surfaceIndexParameters)
} |
library(knitr)
options(rmarkdown.html_vignette.check_title = FALSE)
knitr::opts_chunk$set(echo = TRUE,
eval=TRUE,
tidy = FALSE,
cache = FALSE,
warning = FALSE,
message = FALSE,
dpi = 60)
library(manhattanly)
set.seed(12345)
HapMap.subset <- subset(HapMap, CHR %in% 4:7)
significantSNP <- sample(HapMap.subset$SNP, 20)
head(HapMap.subset)
dim(HapMap.subset)
manhattanrObject <- manhattanr(HapMap)
str(manhattanrObject)
head(manhattanrObject[["data"]])
is.data.frame(manhattanrObject[["data"]])
manhattanrObject <- manhattanr(HapMap, snp = "SNP", gene = "GENE",
annotation1 = "DISTANCE", annotation2 = "EFFECTSIZE")
head(manhattanrObject[["data"]])
is.data.frame(manhattanrObject[["data"]])
qqrObject <- qqr(HapMap)
str(qqrObject)
head(qqrObject[["data"]])
volcanorObject <- volcanor(HapMap,
p = "P",
effect_size = "EFFECTSIZE",
snp = "SNP",
gene = "GENE")
str(volcanorObject)
head(volcanorObject[["data"]]) |
context("tests the plotAncStatesPie function")
test_that("plots pies of ancestral states", {
tree_file <-
system.file("extdata",
"dec/small_dec.tre",
package = "RevGadgets")
plot_file <-
system.file("extdata",
"graphs/plotAncStatesPie_df.rds",
package = "RevGadgets")
labs <- c(
"1" = "K",
"2" = "O",
"3" = "M",
"4" = "H",
"5" = "KO",
"6" = "KM",
"7" = "OM",
"8" = "KH",
"9" = "OH",
"10" = "MH",
"11" = "KOM",
"12" = "KOH",
"13" = "KMH",
"14" = "OMH",
"15" = "KOMH"
)
dec_example <- processAncStates(tree_file , state_labels = labs)
colors <-
colorRampPalette(colFun(12))(length(dec_example@state_labels))
names(colors) <- dec_example@state_labels
plot_new <-
plotAncStatesPie(
t = dec_example,
pie_colors = colors,
tip_labels_size = 2,
cladogenetic = TRUE,
tip_labels_offset = 0.01,
timeline = F,
node_pie_size = .5,
tip_pie_size = .3
) +
ggplot2::scale_x_continuous(limits = c(-0.5, 1)) +
ggplot2::theme(legend.position = c(0.1, 0.75))
plot_orig <- readRDS(plot_file)
tmp <- tempdir()
pdf(paste0(tmp,"/Rplots.pdf"))
expect_error(print(plot_new), NA)
dev.off()
expect_equal(plot_new$data, plot_orig)
}) |
library(portfolio)
load("portfolio.performance.test.RData")
result <- performance(test.portfolio, test.market.data)
empty.result <- performance(empty.portfolio, test.market.data)
row.names([email protected]) <- as.character(row.names([email protected]))
stopifnot(
all.equal(result@ret, truth@ret),
all.equal(result@profit, truth@profit),
all.equal([email protected], [email protected]),
all.equal([email protected], [email protected]),
all.equal([email protected], [email protected]),
all.equal([email protected], [email protected]),
all.equal(empty.result, empty.truth)
) |
banding.cv <- function(matrix, n.cv = 10, norm = "F", seed = 142857) {
if ((norm %in% c("F","O","f","o")) == FALSE) {
stop("This function only support two norm: Frobenius and operator")
}
banding.loss <- function(mat1, mat2, k, norm) {
cov.mat1 <- cov(mat1)
cov.mat2 <- cov(mat2)
mat.diff <- banding(cov.mat1, k) - cov.mat2
if (norm %in% c("F","f")) {
loss <- F.norm2(mat.diff)
} else if (norm %in% c("O","o")) {
loss <- O.norm2(mat.diff)
}
return(loss)
}
N <- dim(matrix)[1]
n1 <- ceiling(N*(1 - 1/log(N)))
n2 <- floor(N/log(N))
k.grid <- 0:(ncol(matrix) - 1)
loss.mat <- matrix(0, nrow = n.cv, ncol = length(k.grid))
for (i in 1:n.cv) {
set.seed(seed + i)
index <- sample(1:N, size = n1, replace = FALSE)
mat1 <- matrix[index,]
mat2 <- matrix[-index,]
loss.mat[i,] <- sapply(k.grid, FUN = banding.loss, mat1 = mat1, mat2 = mat2, norm = norm)
}
loss.vec <- colMeans(loss.mat)
k.opt <- k.grid[which.min(loss.vec)]
result <- list(regularization = "Banding",
parameter.opt = k.opt,
cv.error = loss.vec,
n.cv = n.cv, norm = norm, seed = seed
)
class(result) <- "CovCv"
return(result)
} |
q10_bidabe <- function(x, total=TRUE){
cq10 = 3
y <- rep(0, length(x))
y <- (1/24)*cq10^(-x/10)
if (total==TRUE)
return(tail(cumsum(y),n=1))
else return(y)
} |
`Wnet` <-
function(add=FALSE, col = gray(.7), border='black', lwd=1)
{
if(missing(add)) { add=FALSE }
if(missing(col)) { col = gray(.7) }
if(missing(lwd)) { lwd=1 }
if(missing(border)) { border='black' }
if(add==FALSE)
{
plot(c(-1,1),c(-1,1), type='n', xlab='', ylab='', asp=1, axes=FALSE, ann=FALSE)
}
pcirc(gcol=col, border=border, ndiv=72)
lam = pi*seq(from=0, to=180, by=5)/180
lam0 = pi/2
for(j in seq(from=-80, to=80, by=10))
{
phi = j*pi/180
R = 1/2
k = 2/(1+cos(phi)*cos(lam-lam0))
x = R*k*cos(phi)*sin(lam-lam0)
y = R * k*sin(phi)
lines(x,y, col=col, lwd=lwd)
}
phi = seq(from=-90, to=90, by=5)*pi/180
for(j in seq(from=10, to=170, by=10))
{
lam = j*pi/180
R = 1/2
k = 2/(1+cos(phi)*cos(lam-lam0))
x = R*k*cos(phi)*sin(lam-lam0)
y = R * k*sin(phi)
lines(x,y, col=col, lwd=lwd)
}
segments(c(-.02, 0), c(0, -0.02), c(0.02, 0), c(0, 0.02), col='black' )
} |
indicator_plrange <- function(mat,
merge = FALSE,
xmin_bounds = NULL) {
if ( !merge && is.list(mat) ) {
return( lapply(mat, indicator_plrange, merge, xmin_bounds) )
}
psd <- patchsizes(mat, merge = merge)
if ( is.null(xmin_bounds) ) {
xmin_bounds <- range(psd)
}
if ( length(unique(psd)) <= 2 ) {
warning('Not enough different patch sizes to estimate xmin: returning NA')
result <- data.frame(min(psd), max(psd), NA, NA)
} else {
plrange_result <- plrange(psd, xmin_bounds)
result <- data.frame(min(psd), max(psd), plrange_result)
}
names(result) <- c("minsize", "maxsize", "xmin_est", "plrange")
return(result)
}
raw_plrange <- function(mat, xmin_bounds = NULL) {
psd <- patchsizes(mat)
if ( is.null(xmin_bounds) ) {
xmin_bounds <- range(psd)
}
plrange_result <- plrange(psd, xmin_bounds)
return( c(plrange = plrange_result[ ,"plrange"]) )
}
plrange <- function(psd, xmin_bounds) {
if ( length(unique(psd)) <= 1) {
return( data.frame(xmin_est = NA_real_, plrange = NA_real_) )
}
xsmallest <- min(psd)
xmax <- max(psd)
xmin <- xmin_estim(psd, bounds = xmin_bounds)
if ( is.na(xmin) ) {
result <- data.frame(NA_real_, NA_real_)
} else {
result <- data.frame(xmin, 1 - (log10(xmin) - log10(xsmallest)) /
(log10(xmax) - log10(xsmallest)))
}
names(result) <- c('xmin_est', 'plrange')
return(result)
} |
hedModel <- function(estimator,
hed_df,
hed_spec,
...){
if (!'heddata' %in% class(hed_df)){
message('\nIncorrect class for "hed_df" object. Must be of class "hed"')
stop()
}
if (!paste0('hedModel.', class(estimator)) %in% utils::methods(hedModel)){
message('\nInvalid estimator type: "', class(estimator), '" method not available.')
stop()
}
if (nrow(hed_df) < nrow(attr(hed_df, 'period_table'))){
message('\nYou have fewer observations (', nrow(hed_df), ') than number of periods (',
nrow(attr(hed_df, 'period_table')), '). Results will likely be unreliable.')
}
UseMethod("hedModel", estimator)
}
hedModel.base <- function(estimator,
hed_df,
hed_spec,
...){
hed_model <- stats::lm(hed_spec,
data=hed_df)
class(hed_model) <- 'hedmodel'
hed_model
}
hedModel.robust <- function(estimator,
hed_df,
hed_spec,
...){
time_size <- stats::median(table(hed_df$trans_period))
if(time_size > 5){
hed_model <- MASS::rlm(hed_spec, data=hed_df)
} else {
hed_model <- robustbase::lmrob(hed_spec, data=hed_df, setting="KS2014")
}
class(hed_model) <- 'hedmodel'
hed_model
}
hedModel.weighted <- function(estimator,
hed_df,
hed_spec,
...){
wgts <- list(...)$weights
if (length(wgts) != nrow(hed_df)){
wgts <- rep(1, nrow(hed_df))
message('You have supplied a set of weights that do not match the data.',
'Model being run in base OLS format.')
}
attr(hed_spec, '.Environment') <- environment()
hed_model <- stats::lm(stats::as.formula(hed_spec), data=hed_df, weights=wgts)
class(hed_model) <- 'hedmodel'
hed_model
} |
pkg_ref_cache.news <- function(x, name, ...) {
UseMethod("pkg_ref_cache.news")
}
pkg_ref_cache.news.pkg_remote <- function(x, name, ...) {
suppressMatchingConditions(
lapply(x$news_urls, function(news_url) {
response <- httr::GET(news_url)
httr::content(
response,
type = response$headers$`content-type` %||% "text/html")
}),
messages = "default")
}
pkg_ref_cache.news.pkg_install <- function(x, name, ...) {
news_from_dir(system.file(package = x$name))
}
pkg_ref_cache.news.pkg_source <- function(x, name, ...) {
news_from_dir(x$path)
}
news_from_dir <- function(path) {
files <- list.files(path, pattern = "^NEWS\\.", full.names = TRUE)
if (!length(files)) return(list())
content <- rep(list(NULL), length(files))
names(content) <- files
valid <- vector(length(files), mode = "logical")
for (i in seq_along(files)) {
f <- files[[i]]
tryCatch({
if (tolower(tools::file_ext(f)) == "rd") {
content[[i]] <- .tools()$.news_reader_default(f)
} else if (tolower(tools::file_ext(f)) == "md") {
content[[i]] <- readLines(f)
}
valid[[i]] <- TRUE
}, error = function(e) {
valid[[i]] <- FALSE
})
}
content[valid]
} |
ACont.<-function(x,h,n,i=0.04,data,prop=1,assumption="UDD",cap=1){
dig<-getOption("digits")
on.exit(options(digits = dig))
options(digits = 15)
if(x>=0 && is_integer(x)==1 && h>=0 && is_integer(h)==1 && n>=0 && is_integer(n)==1 && i>=0 && prop>0){
if(n==0){
Axhnc<-0
return(Axhnc)
}else{
delta<-log(1+i)
if(assumption=="constant"){
Axhnc<-E(x,h,i,data,prop)-E(x,h+n,i,data,prop,"none",1)-delta*aCont(x,h,n,i,data,prop,"constant",1)
}else if(assumption=="UDD"){
Axhnc<-(i/delta)*A.(x,h,n,1,i,data,prop,"none",1)
}else{
stop("Check assumption")
}
}
Axhnc<-as.numeric(Axhnc)
px1<-Axhnc*cap
return(px1)
}else{
stop("Check Values")
}
} |
NULL
appsync <- function(config = list()) {
svc <- .appsync$operations
svc <- set_config(svc, config)
return(svc)
}
.appsync <- list()
.appsync$operations <- list()
.appsync$metadata <- list(
service_name = "appsync",
endpoints = list("*" = list(endpoint = "appsync.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "appsync.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "appsync.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "appsync.{region}.sc2s.sgov.gov", global = FALSE)),
service_id = "AppSync",
api_version = "2017-07-25",
signing_name = "appsync",
json_version = "1.1",
target_prefix = ""
)
.appsync$service <- function(config = list()) {
handlers <- new_handlers("restjson", "v4")
new_service(.appsync$metadata, handlers, config)
} |
gridPrint <- function(...){
arg <- list(...)
ii <- unlist( lapply(arg, inherits, what = "plotSmooth") )
if ( length(ii) ) {
arg[ii] <- lapply(arg[ii], "[[", "ggObj")
}
if( !is.null(arg$grobs) ){
ii <- unlist( lapply(arg$grobs, inherits, what = "plotSmooth") )
if ( length(ii) ) {
arg$grobs[ii] <- lapply(arg$grobs[ii], "[[", "ggObj")
}
}
out <- do.call("grid.arrange", arg)
return( invisible(out) )
} |
context("expose-helpers")
test_that("guess_pack_type works", {
expect_identical(guess_pack_type(input_data_pack_out), "data_pack")
expect_identical(guess_pack_type(input_group_pack_out), "group_pack")
expect_identical(guess_pack_type(input_col_pack_out), "col_pack")
expect_identical(guess_pack_type(input_row_pack_out), "row_pack")
expect_identical(guess_pack_type(input_cell_pack_out), "cell_pack")
input_col_pack_out_1 <- input_col_pack_out
names(input_col_pack_out_1) <-
gsub("\\._\\.", "\\.___\\.", names(input_col_pack_out_1))
expect_identical(
guess_pack_type(
input_col_pack_out_1,
inside_punct("\\.___\\.")
),
"col_pack"
)
})
test_that("remove_obeyers works", {
input_report <- tibble::tibble(
pack = rep("data_pack", 4), rule = paste0("rule__", 1:4),
var = rep(".all", 4), id = rep(0L, 4),
value = c(TRUE, FALSE, TRUE, NA)
)
expect_identical(remove_obeyers(input_report, FALSE), input_report)
expect_identical(remove_obeyers(input_report, TRUE), input_report[c(2, 4), ])
})
test_that("impute_exposure_pack_names works with NULL reference exposure", {
expect_identical(
impute_exposure_pack_names(input_single_exposures, input_exposure_ref),
input_single_exposures
)
cur_input_single_exposures <- input_single_exposures
names_remove_inds <- c(1, 2, 3, 5, 6, 8)
names(cur_input_single_exposures)[names_remove_inds] <-
rep("", length(names_remove_inds))
expect_identical(
names(impute_exposure_pack_names(cur_input_single_exposures, NULL)),
c(
"data_pack__1", "cell_pack__1", "col_pack__1", "new_col_proper_sums",
"data_pack__2", "row_pack__1", "another_data_pack", "group_pack__1"
)
)
})
test_that("impute_exposure_pack_names works with not NULL reference exposure", {
cur_input_single_exposures <- input_single_exposures
names_remove_inds <- c(1, 2, 3, 5, 6, 8)
names(cur_input_single_exposures)[names_remove_inds] <-
rep("", length(names_remove_inds))
expect_identical(
names(impute_exposure_pack_names(
cur_input_single_exposures,
input_exposure_ref
)),
c(
"data_pack__3", "cell_pack__2", "col_pack__3", "new_col_proper_sums",
"data_pack__4", "row_pack__2", "another_data_pack", "group_pack__2"
)
)
})
test_that("add_pack_names works", {
expect_identical(
add_pack_names(input_single_exposures),
input_exposures
)
})
test_that("bind_exposures works", {
expect_identical(
bind_exposures(list(input_exposure_ref, NULL)),
input_exposure_ref
)
expect_identical(
bind_exposures(list(NULL, NULL)),
NULL
)
output_ref <- new_exposure(
.packs_info = new_packs_info(
rep(input_exposure_ref$packs_info$name, 2),
c(input_exposure_ref$packs_info$fun, input_exposure_ref$packs_info$fun),
rep(input_exposure_ref$packs_info$remove_obeyers, 2)
),
.report = bind_rows(
input_exposure_ref$report,
input_exposure_ref$report
) %>%
add_class_cond("ruler_report")
)
expect_identical(
bind_exposures(list(input_exposure_ref, input_exposure_ref)),
output_ref
)
expect_identical(
bind_exposures(input_exposure_ref, input_exposure_ref),
output_ref
)
})
test_that("filter_not_null works", {
input <- list(NULL, 1, list(2), NULL, "a", "b", list(NULL))
output_ref <- input[-c(1, 4)]
expect_identical(filter_not_null(input), output_ref)
})
test_that("assert_pack_out_one_row works", {
expect_silent(assert_pack_out_one_row(input_data_pack_out, "data_pack"))
expect_error(
assert_pack_out_one_row(input_row_pack_out, "row_pack"),
"row_pack.*not.*row"
)
})
test_that("assert_pack_out_all_logical works", {
expect_silent(assert_pack_out_all_logical(input_data_pack_out, "data_pack"))
input_bad <- tibble::tibble(good = c(TRUE, FALSE), bad = 1:2)
expect_error(
assert_pack_out_all_logical(input_bad, "cell_pack"),
"cell_pack.*not.*logical"
)
})
test_that("assert_pack_out_all_have_separator works", {
expect_silent(
assert_pack_out_all_have_separator(
input_col_pack_out, "col_pack", inside_punct("\\._\\.")
)
)
expect_error(
assert_pack_out_all_have_separator(
input_data_pack_out, "data_pack", inside_punct("\\._\\.")
),
"data_pack.*not.*separator"
)
expect_error(
assert_pack_out_all_have_separator(
input_col_pack_out, "col_pack", inside_punct("\\.___\\.")
),
"col_pack.*not.*separator"
)
}) |
sim_ail_pedigree <-
function(ngen=12, npairs=30, nkids_per=5, design=c("nosib", "random"))
{
design <- match.arg(design)
id <- c(1,2,3,4, (1:(npairs*2)+4))
mom <- c(0,0,1,1,rep(3, npairs*2))
dad <- c(0,0,2,2,rep(4, npairs*2))
sex <- c(0,1,0,1,rep(c(0,1), npairs))
gen <- c(0,0,1,1,rep(2, npairs*2))
if(ngen <= 2)
stop("No. generations should be > 2")
cur_nind <- length(id)
moms <- seq(5, length(id), by=2)
dads <- seq(6, length(id), by=2)
for(i in 3:ngen) {
if(i > 3) {
dads <- sample(dads)
while(design=="nosib" && any(dads - moms == 1)) {
dads <- sample(dads)
}
}
if(i < ngen) {
kids <- 1:(npairs*2)+max(id)
id <- c(id, kids)
mom <- c(mom, rep(moms, each=2))
dad <- c(dad, rep(dads, each=2))
sex <- c(sex, rep(c(0,1), npairs))
gen <- c(gen, rep(i, npairs*2))
moms <- kids[seq(1, length(kids), by=2)]
dads <- kids[seq(2, length(kids), by=2)]
}
else {
kids <- 1:(npairs*nkids_per)+max(id)
id <- c(id, kids)
mom <- c(mom, rep(moms, each=nkids_per))
dad <- c(dad, rep(dads, each=nkids_per))
sex <- c(sex, rep(c(0,1), ceiling(npairs*nkids_per/2))[1:(npairs*nkids_per)])
gen <- c(gen, rep(i, npairs*nkids_per))
}
}
data.frame(id=id, mom=mom, dad=dad, sex=sex, gen=gen)
} |
context("Features: ELA - Curvature")
test_that("Require original function", {
set.seed(2015*03*26)
X = t(replicate(n = 2000, expr = runif(n = 5L, min = -10L, max = 10L)))
feat.object = createFeatureObject(X = X, y = rowSums(X^2))
expect_error(calculateFeatureSet(feat.object, "ela_curv"))
})
test_that("Required sample size is too big for the given data", {
set.seed(2015*03*26)
X = t(replicate(n = 100, expr = runif(n = 3L, min = -10L, max = 10L)))
f = function(x) sum(x^2)
feat.object = createFeatureObject(X = X, fun = f)
expect_warning(calculateFeatureSet(feat.object, "ela_curv"))
})
test_that("Expected Output", {
set.seed(2015*03*26)
X = t(replicate(n = 2000L, expr = runif(n = 5L, min = -10L, max = 10L)))
feat.object = createFeatureObject(X = X, fun = function(x) sum(x^2))
features = calculateFeatureSet(feat.object, "ela_curv")
expect_identical(length(features), 26L)
expect_list(features)
expect_identical(as.character(sapply(features, class)),
c(rep("numeric", 24L), "integer", "numeric"))
expect_true(testNumber(features$ela_curv.grad_norm.min, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_norm.lq, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_norm.mean, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_norm.med, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_norm.uq, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_norm.max, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_norm.sd, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_norm.nas, lower = 0L, upper = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.min, lower = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.lq, lower = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.mean, lower = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.med, lower = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.uq, lower = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.max, lower = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.sd, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_scale.nas, lower = 0L, upper = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.min, lower = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.lq, lower = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.mean, lower = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.med, lower = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.uq, lower = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.max, lower = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.sd, lower = 0L))
expect_true(testNumber(features$ela_curv.hessian_cond.nas, lower = 0L, upper = 1L))
expect_true(testNumber(features$ela_curv.costs_fun_evals, lower = 0L))
expect_true(testNumber(features$ela_curv.costs_runtime, lower = 0L))
grad_norm_features = features[grep("grad_norm", names(features))]
x = unlist(grad_norm_features[grep("min|lq|med|uq|max", names(grad_norm_features))])
expect_true(all(diff(x) >= 0L))
x = unlist(grad_norm_features[grep("min|mean|max", names(grad_norm_features))])
expect_true(all(diff(x) >= 0L))
grad_scale_features = features[grep("grad_scale", names(features))]
x = unlist(grad_scale_features[grep("min|lq|med|uq|max", names(grad_scale_features))])
expect_true(all(diff(x) >= 0L))
x = unlist(grad_scale_features[grep("min|mean|max", names(grad_scale_features))])
expect_true(all(diff(x) >= 0L))
hessian_features = features[grep("hessian", names(features))]
x = unlist(hessian_features[grep("min|lq|med|uq|max", names(hessian_features))])
expect_true(all(diff(x) >= 0L))
x = unlist(hessian_features[grep("min|mean|max", names(hessian_features))])
expect_true(all(diff(x) >= 0L))
})
test_that("Expected Output on Bounds", {
X = cbind(x1 = rep(c(0, 10), 2), x2 = rep(c(0, 10), each = 2))
feat.object = createFeatureObject(X = X, fun = function(x) sum(x^2))
features = calculateFeatureSet(feat.object, "ela_curv", control = list(ela_curv.sample_size = 4))
expect_identical(length(features), 26L)
expect_list(features)
expect_identical(as.character(sapply(features, class)),
c(rep("numeric", 24L), "integer", "numeric"))
expect_true(testNumber(features$ela_curv.grad_norm.lq, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_norm.mean, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_norm.med, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_norm.uq, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_norm.max, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_norm.sd, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_norm.nas, lower = 0L, upper = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.min, lower = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.lq, lower = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.mean, lower = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.med, lower = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.uq, lower = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.max, lower = 1L))
expect_true(testNumber(features$ela_curv.grad_scale.sd, lower = 0L))
expect_true(testNumber(features$ela_curv.grad_scale.nas, lower = 0L, upper = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.min, lower = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.lq, lower = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.mean, lower = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.med, lower = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.uq, lower = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.max, lower = 1L))
expect_true(testNumber(features$ela_curv.hessian_cond.sd, lower = 0L))
expect_true(testNumber(features$ela_curv.hessian_cond.nas, lower = 0L, upper = 1L))
expect_true(testNumber(features$ela_curv.costs_fun_evals, lower = 0L))
expect_true(testNumber(features$ela_curv.costs_runtime, lower = 0L))
grad_norm_features = features[grep("grad_norm", names(features))]
x = unlist(grad_norm_features[grep("min|lq|med|uq|max", names(grad_norm_features))])
expect_true(all(diff(x) >= 0L))
x = unlist(grad_norm_features[grep("min|mean|max", names(grad_norm_features))])
expect_true(all(diff(x) >= 0L))
grad_scale_features = features[grep("grad_scale", names(features))]
x = unlist(grad_scale_features[grep("min|lq|med|uq|max", names(grad_scale_features))])
expect_true(all(diff(x) >= 0L))
x = unlist(grad_scale_features[grep("min|mean|max", names(grad_scale_features))])
expect_true(all(diff(x) >= 0L))
})
test_that("Show Error", {
feat.object = createFeatureObject(init = iris[, -5],
objective = "Sepal.Length")
expect_error(calculateFeatureSet(feat.object, "ela_curv"))
feat.object = createFeatureObject(init = iris[, -5],
objective = "Sepal.Length", fun = function(x) sum(x^2))
expect_error(calculateFeatureSet(feat.object, "ela_curv",
control = list(allow_costs = FALSE)))
}) |
getJenksBreaks <- function(var, k, subset = NULL) {
k <- k - 1;
if (k > length(unique(var))) {
k <- length(unique(var));
}
brks <- rep(1, k + 1);
if (!is.null(subset)) {
if (length(var) > subset) {
ind <- c(seq(from=1, to=length(var), by=floor(length(var)/subset)), length(var));
var <- var[ind];
}
}
d <- sort(var);
length_d <- length(d);
return(.C("jenksBrks", as.double(d), as.integer(k), as.integer(length_d), as.double(brks))[[4]]);
} |
system <- function(command, intern = FALSE,
ignore.stdout = FALSE, ignore.stderr = FALSE,
wait = TRUE, input = NULL,
show.output.on.console = TRUE, minimized = FALSE,
invisible = TRUE)
{
if(!is.logical(intern) || is.na(intern))
stop("'intern' must be TRUE or FALSE")
if(!is.logical(ignore.stdout) || is.na(ignore.stdout))
stop("'ignore.stdout' must be TRUE or FALSE")
if(!is.logical(ignore.stderr) || is.na(ignore.stderr))
stop("'ignore.stderr' must be TRUE or FALSE")
if(!is.logical(wait) || is.na(wait))
stop("'wait' must be TRUE or FALSE")
if(!is.logical(show.output.on.console) || is.na(show.output.on.console))
stop("'show.output.on.console' must be TRUE or FALSE")
if(!is.logical(minimized) || is.na(minimized))
stop("'minimized' must be TRUE or FALSE")
if(!is.logical(invisible) || is.na(invisible))
stop("'invisible' must be TRUE or FALSE")
stdout <- ifelse(ignore.stdout, FALSE, "")
stderr <- ifelse(ignore.stderr, FALSE, "")
f <- ""
if (!is.null(input)) {
f <- tempfile()
on.exit(unlink(f))
writeLines(input, f)
}
if (intern) {
flag <- 3L
if(stdout == "") stdout <- TRUE
if(!ignore.stderr && .Platform$GUI == "Rgui") stderr <- TRUE
} else {
flag <- if (wait) ifelse(show.output.on.console, 2L, 1L) else 0L
}
if (invisible) flag <- 20L + flag
else if (minimized) flag <- 10L + flag
.Internal(system(command, as.integer(flag), f, stdout, stderr))
}
system2 <- function(command, args = character(),
stdout = "", stderr = "", stdin = "", input = NULL,
env = character(),
wait = TRUE, minimized = FALSE, invisible = TRUE)
{
if(!is.logical(wait) || is.na(wait))
stop("'wait' must be TRUE or FALSE")
if(!is.logical(minimized) || is.na(minimized))
stop("'minimized' must be TRUE or FALSE")
if(!is.logical(invisible) || is.na(invisible))
stop("'invisible' must be TRUE or FALSE")
command <- paste(c(shQuote(command), env, args), collapse = " ")
if(is.null(stdout)) stdout <- FALSE
if(is.null(stderr)) stderr <- FALSE
if(length(stdout) != 1L) stop("'stdout' must be of length 1")
if(length(stderr) != 1L) stop("'stderr' must be of length 1")
if (!is.null(input)) {
f <- tempfile()
on.exit(unlink(f))
writeLines(input, f)
} else f <- stdin
flag <- if (isTRUE(stdout) || isTRUE(stderr)) 3L
else if (wait) ifelse(identical(stdout, ""), 2L, 1L)
else 0L
if (invisible) flag <- 20L + flag
else if (minimized) flag <- 10L + flag
.Internal(system(command, flag, f, stdout, stderr))
}
shell <- function(cmd, shell, flag = "/c", intern = FALSE,
wait = TRUE, translate = FALSE, mustWork = FALSE, ...)
{
if(missing(shell)) {
shell <- Sys.getenv("R_SHELL")
if(!nzchar(shell)) shell <- Sys.getenv("COMSPEC")
}
if(missing(flag) &&
any(!is.na(pmatch(c("bash", "tcsh", "sh"), basename(shell)))))
flag <- "-c"
cmd0 <- cmd
if(translate) cmd <- chartr("/", "\\", cmd)
if(!is.null(shell)) cmd <- paste(shell, flag, cmd)
res <- system(cmd, intern = intern, wait = wait | intern,
show.output.on.console = wait, ...)
if(!intern && res && !is.na(mustWork))
if(mustWork)
if(res == -1L)
stop(gettextf("'%s' could not be run", cmd0), domain = NA)
else stop(gettextf("'%s' execution failed with error code %d",
cmd0, res), domain = NA)
else
if(res == -1L)
warning(gettextf("'%s' could not be run", cmd0), domain = NA)
else warning(gettextf("'%s' execution failed with error code %d",
cmd0, res), domain = NA)
if(intern) res else invisible(res)
}
shell.exec <- function(file) .Internal(shell.exec(file))
Sys.timezone <- function(location = TRUE)
{
tz <- Sys.getenv("TZ", names = FALSE)
if(nzchar(tz)) return(tz)
if(location) return(.Internal(tzone_name()))
z <- as.POSIXlt(Sys.time())
zz <- attr(z, "tzone")
if(length(zz) == 3L) zz[2L + z$isdst] else zz[1L]
}
Sys.which <- function(names) .Internal(Sys.which(as.character(names))) |
mutUniformPruefer = makeMutator(
mutator = function(ind, p = 1 / length(ind)) {
n = length(ind)
nrs = 1:(n + 2L)
r = runif(n) < p
if (sum(r) > 0)
ind[r] = sample(nrs, sum(r), replace = TRUE)
return(ind)
},
supported = "custom")
oneEdgeExchange = function(edgelist, edge.id) {
the.edge.idx = edge.id
node1 = edgelist[1L, the.edge.idx]
node2 = edgelist[2L, the.edge.idx]
getRandom = function(set) {
if (length(set) == 1L)
return(set)
return(sample(set, 1L))
}
getReachableNodes = function(edgelist, node) {
nodes = node
nodes2 = nodes
while (length(nodes2) > 0L) {
the.node = nodes2[1L]
is.adjacent = apply(edgelist, 2L, function(x) any(x == the.node))
adjacent.nodes = unique(as.integer(edgelist[, is.adjacent]))
nodes2 = setdiff(c(nodes2, adjacent.nodes), the.node)
nodes = unique(c(nodes, adjacent.nodes))
edgelist = edgelist[, !is.adjacent, drop = FALSE]
}
return(nodes)
}
nodes1 = getReachableNodes(edgelist[, -the.edge.idx], node1)
nodes2 = getReachableNodes(edgelist[, -the.edge.idx], node2)
new.node1 = getRandom(nodes1)
new.node2 = getRandom(nodes2)
edgelist[, the.edge.idx] = c(new.node1, new.node2)
return(edgelist)
}
edgeExchange = function(edgelist, p = 1 / ncol(edgelist)) {
m = ncol(edgelist)
for (i in 1:m) {
if (runif(1L) < p) {
edgelist = oneEdgeExchange(edgelist, i)
}
}
return(edgelist)
}
mutEdgeExchange = makeMutator(
mutator = function(ind, p = 1 / ncol(ind)) {
edgeExchange(ind, p)
},
supported = "custom")
subgraphMST = function(edgelist, sigma, instance) {
m = ncol(edgelist)
n.objectives = instance$n.weights
nsel = sample(3:sigma, 1L)
start = sample(1:m, 1L)
sel.edges = start
sel.nodes = edgelist[, start]
inds = 1:m
while (length(sel.nodes) < nsel) {
rr = apply(edgelist, 2L, function(x) any(x %in% sel.nodes))
rr = setdiff(which(rr), sel.edges)
sel.edges = sort(c(sel.edges, rr))
sel.nodes = unique(as.integer(edgelist[, sel.edges]))
}
sel.nodes = sort(sel.nodes)
obj.idx = sample(1:n.objectives, 1L)
dd = instance$weights[[obj.idx]][sel.nodes, sel.nodes]
mstres = vegan::spantree(d = dd)
repl.edges = matrix(
c(sel.nodes[2:(length(sel.edges) + 1L)],
sel.nodes[mstres$kid]), byrow = TRUE, nrow = 2L)
edgelist[, sel.edges] = repl.edges
return(edgelist)
}
mutSubgraphMST = makeMutator(
mutator = function(ind, sigma = floor(ncol(ind) / 2), instance = NULL) {
subgraphMST(ind, sigma, instance)
},
supported = "custom"
) |
print.summary.robmixglm <- function(x, digits = max(3L, getOption("digits") - 3L), ...) {
if (!inherits(x, "summary.robmixglm"))
stop("Use only with 'summary.robmixglm' objects.\n")
printCoefmat(x$coefficients,digits=digits,na.print="")
cat("\n")
print(data.frame(logLik = x$logLik,AIC = x$AIC, BIC = x$BIC,
row.names = " "))
invisible(x)
} |
"strategies.RPS" |
distrARITH <- function(library = NULL)
{
infoShow(pkg = "distr", filename = "ARITHMETICS", library = library)
}
distrMASK <- function(library = NULL)
{
infoShow(pkg = "distr", filename="MASKING", library = library)
} |
transformPlanarCalibrationCoordinates <- function(tpar, nx, ny, sx, sy=NULL){
if(is.null(sy)) sy <- sx
tpar <- matrix(tpar, ncol=6, byrow=TRUE)
grid <- cbind(rep(0:(nx-1), ny)*sx, c(matrix(t(matrix((ny-1):0, nrow=ny, ncol=nx)), nrow=1, byrow=F))*sy, rep(0, nx*ny))
grid <- grid - matrix(colMeans(grid), nrow=nrow(grid), ncol=3, byrow=TRUE)
coor.3d <- matrix(NA, nrow=nrow(tpar)*nrow(grid), ncol=3)
for(i in 1:nrow(tpar)){
grid_transform <- grid %*% rotationMatrixZYX_SM(t=c(tpar[i, 1:3]))
coor.3d[((i-1)*nrow(grid)+1):(i*nrow(grid)), ] <- grid_transform + matrix(tpar[i, 4:6], nrow=nrow(grid_transform), ncol=3, byrow=TRUE)
}
coor.3d
} |
DAISIE_SR_loglik_all_choosepar <- function(
trparsopt,
trparsfix,
idparsopt,
idparsfix,
idparsnoshift,
pars2,
datalist,
methode,
CS_version,
abstolint = 1E-16,
reltolint = 1E-10
) {
trpars1 <- rep(0, 11)
trpars1[idparsopt] <- trparsopt
if (length(idparsfix) != 0) {
trpars1[idparsfix] <- trparsfix
}
if (length(idparsnoshift) != 0) {
trpars1[idparsnoshift] <- trpars1[idparsnoshift - 5]
}
if (max(trpars1) > 1 | min(trpars1) < 0) {
loglik <- -Inf
} else {
pars1 <- trpars1 / (1 - trpars1)
if (min(pars1) < 0) {
loglik <- -Inf
} else {
loglik <- DAISIE_SR_loglik_CS(
pars1 = pars1,
pars2 = pars2,
datalist = datalist,
methode = methode,
CS_version = CS_version,
abstolint = abstolint,
reltolint = reltolint,
verbose = FALSE
)
}
if (is.nan(loglik) || is.na(loglik)) {
cat("There are parameter values used which cause numerical problems.\n")
loglik <- -Inf
}
}
return(loglik)
}
DAISIE_SR_ML_CS <- DAISIE_SR_ML <- function(
datalist,
initparsopt,
idparsopt,
parsfix,
idparsfix,
idparsnoshift = 6:10,
res = 100,
ddmodel = 0,
cond = 0,
island_ontogeny = NA,
tol = c(1E-4, 1E-5, 1E-7),
maxiter = 1000 * round((1.25) ^ length(idparsopt)),
methode = "lsodes",
optimmethod = "subplex",
CS_version = 1,
verbose = 0,
tolint = c(1E-16, 1E-10),
jitter = 0) {
options(warn = -1)
out2err <- data.frame(lambda_c = NA, mu = NA, K = NA, gamma = NA, lambda_a2 = NA, lambda_c2 = NA, mu2 = NA, K2 = NA, gamma2 = NA, lambda_a2 = NA, tshift = NA, loglik = NA, df = NA, conv = NA)
out2err <- invisible(out2err)
idpars <- sort(c(idparsopt, idparsfix, idparsnoshift))
missnumspec <- unlist(lapply(datalist, function(list) {
list$missing_species
}))
if (CS_version != 1) {
cat("This version of CS is not yet implemented\n")
return(out2err)
}
if (sum(missnumspec) > (res - 1)) {
cat("The number of missing species is too large relative to the resolution of the ODE.\n")
return(out2err)
}
if ((prod(idpars == (1:11)) != 1) || (length(initparsopt) != length(idparsopt)) || (length(parsfix) != length(idparsfix))) {
cat("The parameters to be optimized and/or fixed are incoherent.\n")
return(out2err)
}
if (length(idparsopt) > 11) {
cat("The number of parameters to be optimized is too high.\n")
return(out2err)
}
namepars <- c("lambda_c", "mu", "K", "gamma", "lambda_a", "lambda_c2", "mu2", "K2", "gamma2", "lambda_a2", "tshift")
if (length(namepars[idparsopt]) == 0) {
optstr <- "nothing"
} else {
optstr <- namepars[idparsopt]
}
cat("You are optimizing", optstr, "\n")
if (length(namepars[idparsfix]) == 0) {
fixstr <- "nothing"
} else {
fixstr <- namepars[idparsfix]
}
cat("You are fixing", fixstr, "\n")
if (sum(idparsnoshift == (6:10)) != 5) {
noshiftstring <- namepars[idparsnoshift]
cat("You are not shifting", noshiftstring, "\n")
}
cat("Calculating the likelihood for the initial parameters.", "\n")
utils::flush.console()
trparsopt <- initparsopt / (1 + initparsopt)
trparsopt[which(initparsopt == Inf)] <- 1
trparsfix <- parsfix / (1 + parsfix)
trparsfix[which(parsfix == Inf)] <- 1
pars2 <- c(res, ddmodel, cond, verbose, island_ontogeny, tol, maxiter)
optimpars <- c(tol, maxiter)
initloglik <- DAISIE_SR_loglik_all_choosepar(trparsopt = trparsopt, trparsfix = trparsfix, idparsopt = idparsopt, idparsfix = idparsfix, idparsnoshift = idparsnoshift, pars2 = pars2, datalist = datalist, methode = methode, CS_version = CS_version, abstolint = tolint[1], reltolint = tolint[2])
cat("The loglikelihood for the initial parameter values is", initloglik, "\n")
if (initloglik == -Inf) {
cat("The initial parameter values have a likelihood that is equal to 0 or below machine precision. Try again with different initial values.\n")
return(out2err)
}
cat("Optimizing the likelihood - this may take a while.", "\n")
utils::flush.console()
out <-
DDD::optimizer(
optimmethod = optimmethod,
optimpars = optimpars,
fun = DAISIE_SR_loglik_all_choosepar,
trparsopt = trparsopt,
idparsopt = idparsopt,
trparsfix = trparsfix,
idparsfix = idparsfix,
idparsnoshift = idparsnoshift,
pars2 = pars2,
datalist = datalist,
methode = methode,
CS_version = CS_version,
abstolint = tolint[1],
reltolint = tolint[2],
jitter = jitter
)
if (out$conv != 0) {
cat("Optimization has not converged. Try again with different initial values.\n")
out2 <- out2err
out2$conv <- out$conv
return(out2)
}
MLtrpars <- as.numeric(unlist(out$par))
MLpars <- MLtrpars / (1 - MLtrpars)
ML <- as.numeric(unlist(out$fvalues))
MLpars1 <- rep(0, 11)
MLpars1[idparsopt] <- MLpars
if (length(idparsfix) != 0) {
MLpars1[idparsfix] <- parsfix
}
if (MLpars1[3] > 10 ^ 7) {
MLpars1[3] <- Inf
}
if (length(idparsnoshift) != 0) {
MLpars1[idparsnoshift] <- MLpars1[idparsnoshift - 5]
}
if (MLpars1[8] > 10 ^ 7) {
MLpars1[8] <- Inf
}
out2 <- data.frame(lambda_c = MLpars1[1], mu = MLpars1[2], K = MLpars1[3], gamma = MLpars1[4], lambda_a = MLpars1[5], lambda_c2 = MLpars1[6], mu2 = MLpars1[7], K2 = MLpars1[8], gamma2 = MLpars1[9], lambda_a2 = MLpars1[10], tshift = MLpars1[11], loglik = ML, df = length(initparsopt), conv = unlist(out$conv))
s1 <- sprintf("Maximum likelihood parameter estimates: lambda_c: %f, mu: %f, K: %f, gamma: %f, lambda_a: %f, lambda_c2: %f, mu2: %f, K2: %f, gamma2: %f, lambda_a2: %f, time of shift: %f", MLpars1[1], MLpars1[2], MLpars1[3], MLpars1[4], MLpars1[5], MLpars1[6], MLpars1[7], MLpars1[8], MLpars1[9], MLpars1[10], MLpars1[11])
s2 <- sprintf("Maximum loglikelihood: %f", ML)
cat("\n", s1, "\n", s2, "\n")
return(invisible(out2))
} |
Sub.S <-
function(z, t, Mat, j){
index <- which(Mat[,j] == 1 & rowSums(Mat[, -j]) == 0)
Sj <- sum(z[index])
names(Sj) <- paste("S", j, sep="")
return(Sj)
} |
options(digits = 5)
c(nrd0 = bw.nrd0(precip), nrd = bw.nrd(precip),
ucv = bw.ucv(precip), bcv = bw.bcv(precip),
"SJ-dpi" = bw.SJ(precip, method = "dpi"),
"SJ-ste" = bw.SJ(precip, method = "ste"))
set.seed(1); bw.bcv(rnorm(6000))
set.seed(1); x <- rnorm(47000)
bw.ucv(x); bw.SJ(x, method = "dpi"); bw.SJ(x, method = "ste")
set.seed(1); bw.SJ(c(runif(65537), 1e7)) |
drks_de_version <- function(drksid, versionno) {
versionno <- versionno * 2
out <- tryCatch({
if (versionno != 0) {
version_query <- list(
TRIAL_ID = drksid,
version1 = paste0(
drksid,
"_",
versionno,
"_en.html"
),
version2 = paste0(
drksid,
"_",
versionno,
"_en.html"
)
)
} else {
version_query <- list(
TRIAL_ID = drksid,
version1 = paste0(
drksid,
"_en.html"
),
version2 = paste0(
drksid,
"_en.html"
)
)
}
res <- httr::POST(
"https://drks.de/drks_web/compareTrialVersions.do",
body = version_query,
encode = "form"
)
version <- rvest::read_html(res)
closeAllConnections()
rstatus <- NA
rstatus <- version %>%
rvest::html_nodes("li.state") %>%
rvest::html_text()
rstatus <- substr(rstatus, 23, nchar(rstatus))
enrolno <- NA
enrolno <- version %>%
rvest::html_nodes("li.targetSize") %>%
rvest::html_text() %>%
stringr::str_extract("[0-9]+")
enroltype <- NA
enroltype <- version %>%
rvest::html_nodes("li.running") %>%
rvest::html_text()
enroltype <- substr(enroltype, 19, nchar(enroltype))
startdate <- NA
startdate <- version %>%
rvest::html_nodes("li.schedule") %>%
rvest::html_text() %>%
stringr::str_extract("[0-9]{4}/[0-9]{2}/[0-9]{2}") %>%
as.Date(format = "%Y/%m/%d") %>%
format("%Y-%m-%d")
closingdate <- NA
closingdate <- version %>%
rvest::html_nodes("li.deadline") %>%
rvest::html_text() %>%
stringr::str_extract("[0-9]{4}/[0-9]{2}/[0-9]{2}") %>%
as.Date(format = "%Y/%m/%d") %>%
format("%Y-%m-%d")
primaryoutcomes <- NA
primaryoutcomes <- version %>%
rvest::html_nodes("p.primaryEndpoint") %>%
rvest::html_text2() %>%
jsonlite::toJSON()
secondaryoutcomes <- NA
secondaryoutcomes <- version %>%
rvest::html_nodes("p.secondaryEndpoints") %>%
rvest::html_text2() %>%
jsonlite::toJSON()
min_age <- NA
min_age <- version %>%
rvest::html_node("li.minAge") %>%
rvest::html_text2() %>%
gsub(pattern = "Minimum Age:", replacement = "", .data) %>%
trimws()
max_age <- NA
max_age <- version %>%
rvest::html_node("li.maxAge") %>%
rvest::html_text2() %>%
gsub(pattern = "Maximum Age:", replacement = "", .data) %>%
trimws()
gender <- NA
gender <- version %>%
rvest::html_node("li.gender") %>%
rvest::html_text2() %>%
gsub(pattern = "Gender:", replacement = "", .data) %>%
trimws()
inclusion_criteria <- NA
inclusion_criteria <- version %>%
rvest::html_nodes(".inclusionAdd") %>%
rvest::html_text2() %>%
jsonlite::toJSON()
exclusion_criteria <- NA
exclusion_criteria <- version %>%
rvest::html_nodes(".exclusion") %>%
rvest::html_text2() %>%
jsonlite::toJSON()
contacts <- tibble::tribble(
~label, ~affiliation, ~telephone, ~fax, ~email, ~url
)
addresses <- version %>%
rvest::html_nodes("ul.addresses li.address")
for (address in addresses) {
label <- NA
label <- address %>%
rvest::html_nodes(xpath = "label") %>%
rvest::html_text2()
affiliation <- NA
affiliation <- address %>%
rvest::html_nodes("li.address-affiliation") %>%
rvest::html_text2() %>%
paste(collapse = " ") %>%
trimws()
address_name <- NA
address_name <- address %>%
rvest::html_nodes("li.address-name") %>%
rvest::html_text2() %>%
paste(collapse = " ") %>%
trimws()
telephone <- NA
telephone <- address %>%
rvest::html_nodes(
xpath = paste(
selectr::css_to_xpath(".address-telephone"),
"/node()[not(self::label)]"
)
) %>%
rvest::html_text2() %>%
paste(collapse = " ") %>%
trimws()
fax <- NA
fax <- address %>%
rvest::html_nodes(
xpath = paste(
selectr::css_to_xpath(".address-fax"),
"/node()[not(self::label)]"
)
) %>%
rvest::html_text2() %>%
paste(collapse = " ") %>%
trimws()
email <- NA
email <- address %>%
rvest::html_nodes(
xpath = paste(
selectr::css_to_xpath(".address-email"),
"/node()[not(self::label)]"
)
) %>%
rvest::html_text2() %>%
paste(collapse = " ") %>%
trimws()
url <- NA
url <- address %>%
rvest::html_nodes(
xpath = paste(
selectr::css_to_xpath(".address-url"),
"/node()[not(self::label)]"
)
) %>%
rvest::html_text2() %>%
paste(collapse = " ") %>%
trimws()
contacts <- contacts %>%
dplyr::bind_rows(
tibble::tribble(
~label,
~affiliation,
~name,
~telephone,
~fax,
~email,
~url,
label,
affiliation,
address_name,
telephone,
fax,
email,
url
)
)
}
contacts <- contacts %>%
jsonlite::toJSON()
data <- c(
rstatus,
startdate,
closingdate,
enrolno,
enroltype,
min_age,
max_age,
gender,
inclusion_criteria,
exclusion_criteria,
primaryoutcomes,
secondaryoutcomes,
contacts
)
return(data)
},
error = function(cond) {
message(paste(
"Version caused an error:",
drksid, "version", versionno
))
message("Here's the original error message:")
message(paste(cond, "\n"))
return("Error")
},
warning = function(cond) {
message(paste(
"Version caused a warning:",
drksid, "version", versionno
))
message("Here's the original warning message:")
message(paste(cond, "\n"))
return("Warning")
},
finally = {
})
return(out)
} |
setGeneric("reconstruct",
function(methMat,mBase,chunk.size=1e6,save.db=FALSE,...)
standardGeneric("reconstruct"))
setMethod("reconstruct",signature(mBase="methylBase"),
function(methMat,mBase,save.db=FALSE,...){
if(min(methMat)<0 | max(methMat)>100 ){
stop("make sure 'methMat' is percent methylation " ,
"matrix (values between 0-100)")
}
if(nrow(methMat) != nrow(mBase) | ncol(methMat) != length([email protected]) ){
stop("methMat dimensions do not match number of samples\n",
"and number of bases in methylBase object")
}
df=getData(mBase)
mat=df[,[email protected]]+getData(mBase)[,[email protected]]
numCs=round(methMat*mat/100)
numTs=round((100-methMat)*mat/100)
df[,[email protected]]=numCs
df[,[email protected]]=numTs
if(!save.db) {
new("methylBase",df,[email protected],
assembly=mBase@assembly,context=mBase@context,
treatment=mBase@treatment,[email protected],
[email protected],[email protected],
destranded=mBase@destranded,resolution=mBase@resolution )
} else {
args <- list(...)
if( !( "dbdir" %in% names(args)) ){
dbdir <- .check.dbdir(getwd())
} else { dbdir <- .check.dbdir(args$dbdir) }
if(!( "suffix" %in% names(args) ) ){
suffix <- "_reconstructed"
} else {
suffix <- paste0("_",args$suffix)
}
makeMethylBaseDB(df=df,dbpath=dbdir,dbtype="tabix",[email protected],
assembly=mBase@assembly,context=mBase@context,
treatment=mBase@treatment,[email protected],
[email protected],[email protected],
destranded=mBase@destranded, resolution=mBase@resolution,
suffix=suffix )
}
}
)
assocComp <- function(mBase,sampleAnnotation){
if(length(sampleAnnotation) < 1) {
stop("ERROR: Sample Annotation has to have at least one column.")
}
scale=TRUE
center=TRUE
mat=percMethylation(mBase)
pr=prcomp(mat,scale.=scale,center=center)
vars=100*pr$sdev**2/sum(pr$sdev**2)
res=list()
for(i in 1:ncol(sampleAnnotation)){
if(is.factor(sampleAnnotation[,i]) | is.character(sampleAnnotation[,i]) |
is.logical(sampleAnnotation[,i])){
annot=as.factor(sampleAnnotation[,i])
res[[names(sampleAnnotation)[i]]]=apply(pr$rotation,2,
function(x){
if(length(unique(annot))>2 ){
kruskal.test(split(x,annot) )$p.value
}else{
wilcox.test(split(x,annot)[[1]],
split(x,annot)[[2]] )$p.value
}
})
}else{
annot= sampleAnnotation[,i]
res[[names(sampleAnnotation)[i]]]=apply(pr$rotation,2,function(x){
cor.test(x,annot)$p.value
})
}
}
list(pcs=pr$rotation,vars=vars,association=do.call("rbind",res))
}
setGeneric("removeComp", function(mBase,comp = NULL ,chunk.size=1e6,save.db=FALSE,...)
standardGeneric("removeComp"))
setMethod("removeComp",signature(mBase="methylBase"),
function(mBase,comp,save.db,...){
if(anyNA(comp) || is.null(comp)){
stop("no component to remove\n")
}
if(any(comp > length([email protected]) )){
stop("'comp' elements can only take values between 1 and number of samples\n")
}
scale=TRUE
center=TRUE
mat=percMethylation(mBase)
mat=scale(mat,scale=scale,center=center)
centers <- attr(mat,'scaled:center')
scales <- attr(mat,'scaled:scale')
pr=prcomp(mat,scale.=FALSE,center=FALSE)
pr$rotation[,comp]=0
res=pr$x %*% t(pr$rotation)
res=(scale(res,center=(-centers/scales),scale=1/scales))
attr(res,"scaled:center")<-NULL
attr(res,"scaled:scale")<-NULL
res[res>100]=100
res[res<0]=0
reconstruct(res,mBase,save.db = save.db, ...=...)
}
) |
test.data.table = function(script="tests.Rraw", verbose=FALSE, pkg=".", silent=FALSE, showProgress=interactive()&&!silent) {
stopifnot(isTRUEorFALSE(verbose), isTRUEorFALSE(silent), isTRUEorFALSE(showProgress))
if (exists("test.data.table", .GlobalEnv,inherits=FALSE)) {
if ("package:data.table" %chin% search()) stop("data.table package is loaded. Unload or start a fresh R session.")
rootdir = if (pkg!="." && pkg %chin% dir()) file.path(getwd(), pkg) else Sys.getenv("PROJ_PATH")
subdir = file.path("inst","tests")
} else {
rootdir = getNamespaceInfo("data.table","path")
subdir = "tests"
}
fulldir = file.path(rootdir, subdir)
stopifnot(is.character(script), length(script)==1L, !is.na(script), nzchar(script))
if (!grepl(".Rraw$", script))
stop("script must end with '.Rraw'. If a file ending '.Rraw.bz2' exists, that will be found and used.")
if (identical(script,"*.Rraw")) {
scripts = dir(fulldir, "*.Rraw.*")
scripts = scripts[!grepl("bench|other", scripts)]
scripts = gsub("[.]bz2$","",scripts)
return(sapply(scripts, function(fn) {
err = try(test.data.table(script=fn, verbose=verbose, pkg=pkg, silent=silent, showProgress=showProgress))
cat("\n");
identical(err, TRUE)
}))
}
if (!identical(basename(script), script)) {
subdir = dirname(script)
fulldir = normalizePath(subdir, mustWork=FALSE)
fn = basename(script)
} else {
fn = script
}
if (!file.exists(file.path(fulldir, fn))) {
fn2 = paste0(fn,".bz2")
if (!file.exists(file.path(fulldir, fn2)))
stop(gettextf("Neither %s nor %s exist in %s",fn, fn2, fulldir, domain="R-data.table"))
fn = fn2
}
fn = setNames(file.path(fulldir, fn), file.path(subdir, fn))
oldEnv = Sys.getenv(c("_R_CHECK_LENGTH_1_LOGIC2_", "TZ"), unset=NA_character_)
Sys.setenv("_R_CHECK_LENGTH_1_LOGIC2_" = TRUE)
oldRNG = suppressWarnings(RNGversion("3.5.0"))
if (is.null(options()$warnPartialMatchArgs)) options(warnPartialMatchArgs=FALSE)
if (is.null(options()$warnPartialMatchAttr)) options(warnPartialMatchAttr=FALSE)
if (is.null(options()$warnPartialMatchDollar)) options(warnPartialMatchDollar=FALSE)
oldOptions = options(
datatable.verbose = verbose,
encoding = "UTF-8",
scipen = 0L,
datatable.optimize = Inf,
datatable.alloccol = 1024L,
datatable.print.class = FALSE,
datatable.print.trunc.cols = FALSE,
datatable.rbindlist.check = NULL,
datatable.integer64 = "integer64",
warnPartialMatchArgs = base::getRversion()>="3.6.0",
warnPartialMatchAttr = TRUE,
warnPartialMatchDollar = TRUE,
width = max(getOption('width'), 80L),
datatable.old.fread.datetime.character = FALSE
)
cat("getDTthreads(verbose=TRUE):\n")
getDTthreads(verbose=TRUE)
cat("test.data.table() running:", fn, "\n")
env = new.env(parent=.GlobalEnv)
assign("testDir", function(x) file.path(fulldir, x), envir=env)
txt = eval(parse(text="tryCatch(mean(not__exist__), error = function(e) e$message)"), envir=.GlobalEnv)
foreign = txt != "object 'not__exist__' not found"
if (foreign) {
cat("\n**** This R session's language is not English. Each test will still check that the correct number of errors and/or\n",
"**** warnings are produced. However, to test the text of each error/warning too, please restart R with LANGUAGE=en\n\n", sep="")
}
assign("foreign", foreign, envir=env)
assign("nfail", 0L, envir=env)
assign("ntest", 0L, envir=env)
assign("prevtest", -1L, envir=env)
assign("whichfail", NULL, envir=env)
assign("started.at", proc.time(), envir=env)
assign("lasttime", proc.time()[3L], envir=env)
assign("timings", data.table( ID = seq_len(9999L), time=0.0, nTest=0L ), envir=env)
assign("memtest", as.logical(Sys.getenv("TEST_DATA_TABLE_MEMTEST", "FALSE")), envir=env)
assign("filename", fn, envir=env)
assign("inittime", as.integer(Sys.time()), envir=env)
assign("showProgress", showProgress, envir=env)
err = try(sys.source(fn, envir=env), silent=silent)
options(oldOptions)
for (i in oldEnv) {
if (is.na(oldEnv[i]))
Sys.unsetenv(names(oldEnv)[i])
else
do.call("Sys.setenv", as.list(oldEnv[i]))
}
suppressWarnings(do.call("RNGkind",as.list(oldRNG)))
tz = Sys.getenv("TZ", unset=NA)
cat("\n", date(),
" endian==", .Platform$endian,
", sizeof(long double)==", .Machine$sizeof.longdouble,
", longdouble.digits==", .Machine$longdouble.digits,
", sizeof(pointer)==", .Machine$sizeof.pointer,
", TZ==", if (is.na(tz)) "unset" else paste0("'",tz,"'"),
", Sys.timezone()=='", suppressWarnings(Sys.timezone()), "'",
", Sys.getlocale()=='", Sys.getlocale(), "'",
", l10n_info()=='", paste0(names(l10n_info()), "=", l10n_info(), collapse="; "), "'",
", getDTthreads()=='", paste0(gsub("[ ][ ]+","==",gsub("^[ ]+","",capture.output(invisible(getDTthreads(verbose=TRUE))))), collapse="; "), "'",
", ", .Call(Cdt_zlib_version),
"\n", sep="")
if (inherits(err,"try-error")) {
if (silent) return(FALSE)
stop("Failed after test ", env$prevtest, " before the next test() call in ",fn)
}
nfail = env$nfail
ntest = env$ntest
if (nfail > 0L) {
if (nfail > 1L) {s1="s";s2="s: "} else {s1="";s2=" "}
stop(nfail," error",s1," out of ",ntest,". Search ",names(fn)," for test number",s2,paste(env$whichfail,collapse=", "),".")
}
timings = env$timings
DT = head(timings[-1L][order(-time)], 10L)
if ((x<-sum(timings[["nTest"]])) != ntest) {
warning("Timings count mismatch:",x,"vs",ntest)
}
cat("10 longest running tests took ", as.integer(tt<-DT[, sum(time)]), "s (", as.integer(100*tt/(ss<-timings[,sum(time)])), "% of ", as.integer(ss), "s)\n", sep="")
print(DT, class=FALSE)
cat("All ",ntest," tests (last ",env$prevtest,") in ",names(fn)," completed ok in ",timetaken(env$started.at),"\n",sep="")
invisible(nfail==0L)
}
compactprint = function(DT, topn=2L) {
tt = vapply_1c(DT,function(x)class(x)[1L])
tt[tt=="integer64"] = "i64"
tt = substring(tt, 1L, 3L)
makeString = function(x) paste(x, collapse = ",")
cn = paste0(" [Key=",makeString(key(DT)),
" Types=", makeString(substring(sapply(DT, typeof), 1L, 3L)),
" Classes=", makeString(tt), "]")
if (nrow(DT)) {
print(copy(DT)[,(cn):="",verbose=FALSE], topn=topn, class=FALSE)
} else {
print(DT, class=FALSE)
if (ncol(DT)) cat(cn,"\n")
}
invisible()
}
INT = function(...) { as.integer(c(...)) }
ps_mem = function() {
cmd = sprintf("ps -o rss %s | tail -1", Sys.getpid())
ans = tryCatch(as.numeric(system(cmd, intern=TRUE, ignore.stderr=TRUE)), warning=function(w) NA_real_, error=function(e) NA_real_)
stopifnot(length(ans)==1L)
c("PS_rss"=round(ans / 1024, 1L))
}
gc_mem = function() {
m = apply(gc()[, c(2L, 4L, 6L)], 2L, sum)
names(m) = c("GC_used", "GC_gc_trigger", "GC_max_used")
m
}
test = function(num,x,y=TRUE,error=NULL,warning=NULL,message=NULL,output=NULL,notOutput=NULL,ignore.warning=NULL) {
.test.data.table = exists("nfail", parent.frame())
numStr = sprintf("%.8g", num)
if (.test.data.table) {
prevtest = get("prevtest", parent.frame())
nfail = get("nfail", parent.frame())
whichfail = get("whichfail", parent.frame())
assign("ntest", get("ntest", parent.frame()) + 1L, parent.frame(), inherits=TRUE)
lasttime = get("lasttime", parent.frame())
timings = get("timings", parent.frame())
memtest = get("memtest", parent.frame())
inittime = get("inittime", parent.frame())
filename = get("filename", parent.frame())
foreign = get("foreign", parent.frame())
showProgress = get("showProgress", parent.frame())
time = nTest = NULL
on.exit( {
now = proc.time()[3L]
took = now-lasttime
assign("lasttime", now, parent.frame(), inherits=TRUE)
timings[ as.integer(num), `:=`(time=time+took, nTest=nTest+1L), verbose=FALSE ]
} )
if (showProgress)
cat("\rRunning test id", numStr, " ")
} else {
memtest = FALSE
filename = NA_character_
foreign = FALSE
showProgress = FALSE
}
if (!missing(error) && !missing(y))
stop("Test ",numStr," is invalid: when error= is provided it does not make sense to pass y as well")
string_match = function(x, y, ignore.case=FALSE) {
length(grep(x, y, fixed=TRUE)) ||
length(tryCatch(grep(x, y, ignore.case=ignore.case), error=function(e)NULL))
}
xsub = substitute(x)
ysub = substitute(y)
actual = list("warning"=NULL, "error"=NULL, "message"=NULL)
wHandler = function(w) {
actual$warning <<- c(actual$warning, conditionMessage(w))
invokeRestart("muffleWarning")
}
eHandler = function(e) {
actual$error <<- conditionMessage(e)
e
}
mHandler = function(m) {
actual$message <<- c(actual$message, conditionMessage(m))
m
}
if (memtest) {
timestamp = as.numeric(Sys.time())
}
if (is.null(output) && is.null(notOutput)) {
x = suppressMessages(withCallingHandlers(tryCatch(x, error=eHandler), warning=wHandler, message=mHandler))
} else {
out = capture.output(print(x <- suppressMessages(withCallingHandlers(tryCatch(x, error=eHandler), warning=wHandler, message=mHandler))))
}
if (memtest) {
mem = as.list(c(inittime=inittime, filename=basename(filename), timestamp=timestamp, test=num, ps_mem(), gc_mem()))
fwrite(mem, "memtest.csv", append=TRUE, verbose=FALSE)
}
fail = FALSE
if (.test.data.table) {
if (num<prevtest+0.0000005) {
cat("Test id", numStr, "is not in increasing order\n")
fail = TRUE
}
assign("prevtest", num, parent.frame(), inherits=TRUE)
}
if (!fail) for (type in c("warning","error","message")) {
observed = actual[[type]]
expected = get(type)
if (type=="warning" && length(observed) && !is.null(ignore.warning)) {
stopifnot(length(ignore.warning)==1L, is.character(ignore.warning), !is.na(ignore.warning), nchar(ignore.warning)>=1L)
observed = grep(ignore.warning, observed, value=TRUE, invert=TRUE)
}
if (length(expected) != length(observed)) {
cat("Test ",numStr," produced ",length(observed)," ",type,"s but expected ",length(expected),"\n",sep="")
cat(paste("Expected:",expected), sep="\n")
cat(paste("Observed:",observed), sep="\n")
fail = TRUE
} else {
for (i in seq_along(expected)) {
if (!foreign && !string_match(expected[i], observed[i])) {
cat("Test",numStr,"didn't produce the correct",type,":\n")
cat("Expected:", expected[i], "\n")
cat("Observed:", observed[i], "\n")
fail = TRUE
}
}
}
}
if (fail && exists("out",inherits=FALSE)) {
cat("Output captured before unexpected warning/error/message:\n")
cat(out,sep="\n")
}
if (!fail && !length(error) && (length(output) || length(notOutput))) {
if (out[length(out)] == "NULL") out = out[-length(out)]
out = paste(out, collapse="\n")
output = paste(output, collapse="\n")
if (length(output) && !string_match(output, out)) {
cat("Test",numStr,"did not produce correct output:\n")
cat("Expected: <<",gsub("\n","\\\\n",output),">>\n",sep="")
cat("Observed: <<",gsub("\n","\\\\n",out),">>\n",sep="")
fail = TRUE
}
if (length(notOutput) && string_match(notOutput, out, ignore.case=TRUE)) {
cat("Test",numStr,"produced output but should not have:\n")
cat("Expected absent (case insensitive): <<",gsub("\n","\\\\n",notOutput),">>\n",sep="")
cat("Observed: <<",gsub("\n","\\\\n",out),">>\n",sep="")
fail = TRUE
}
}
if (!fail && !length(error) && (!length(output) || !missing(y))) {
y = try(y,TRUE)
if (identical(x,y)) return(invisible(TRUE))
all.equal.result = TRUE
if (is.data.table(x) && is.data.table(y)) {
if (!selfrefok(x) || !selfrefok(y)) {
cat("Test ",numStr," ran without errors but selfrefok(", if(!selfrefok(x))"x"else"y", ") is FALSE\n", sep="")
fail = TRUE
} else {
xc=copy(x)
yc=copy(y)
if (length(x)) for (i in which(vapply_1b(x,is.factor))) {.xi=x[[i]];xc[,(i):=factor(.xi)]}
if (length(y)) for (i in which(vapply_1b(y,is.factor))) {.yi=y[[i]];yc[,(i):=factor(.yi)]}
setattr(xc,"row.names",NULL)
setattr(yc,"row.names",NULL)
setattr(xc,"index",NULL)
setattr(yc,"index",NULL)
if (identical(xc,yc) && identical(key(x),key(y))) return(invisible(TRUE))
if (isTRUE(all.equal.result<-all.equal(xc,yc,check.environment=FALSE)) && identical(key(x),key(y)) &&
identical(vapply_1c(xc,typeof), vapply_1c(yc,typeof))) return(invisible(TRUE))
}
}
if (is.atomic(x) && is.atomic(y) && isTRUE(all.equal.result<-all.equal(x,y,check.names=!isTRUE(y))) && typeof(x)==typeof(y)) return(invisible(TRUE))
if (!fail) {
cat("Test", numStr, "ran without errors but failed check that x equals y:\n")
failPrint = function(x, xsub) {
cat(">", substitute(x), "=", xsub, "\n")
if (is.data.table(x)) compactprint(x) else {
nn = length(x)
cat(sprintf("First %d of %d (type '%s'): \n", min(nn, 6L), length(x), typeof(x)))
if (length(d <- dim(x))) do.call(`[`, c(list(x, drop = FALSE), lapply(pmin(d, 6L), seq_len)))
else print(head(x))
}
}
failPrint(x, deparse(xsub))
failPrint(y, deparse(ysub))
if (!isTRUE(all.equal.result)) cat(all.equal.result, sep="\n")
fail = TRUE
}
}
if (fail && .test.data.table) {
assign("nfail", nfail+1L, parent.frame(), inherits=TRUE)
assign("whichfail", c(whichfail, numStr), parent.frame(), inherits=TRUE)
}
invisible(!fail)
} |
integerCols <- function(data) {
is.wholenumber <- function(x, tol = .Machine$double.eps ^ 0.5) {
abs(x - round(x)) < tol
}
all.cols <- 1:ncol(data)
integer.cols <- rep(0, ncol(data))
for (i in all.cols) {
x <- na.omit(data[ , i])
if(!is.numeric(x)) next
if(!all(is.finite(x))) next
if(min(is.wholenumber(x) == 1)) integer.cols[i] <- 1
}
multConvert(data, conversion = as.integer, cols = all.cols[integer.cols == 1])
} |
ORSummaryFRRC <- function(dataset, FOMs, ANOVA, alpha, diffTRName) {
readerID <- dataset$descriptions$readerID
modalityID <- dataset$descriptions$modalityID
I <- length(modalityID)
J <- length(readerID)
K <- dim(dataset$ratings$NL)[3]
foms <- FOMs$foms
trtMeanDiffs <- FOMs$trtMeanDiffs
FRRC <- list()
if (I > 1) {
if (J > 1) {
msDen <- ANOVA$VarCom["Var","Estimates"] - ANOVA$VarCom["Cov1","Estimates"] +
(J - 1) * max(ANOVA$VarCom["Cov2","Estimates"] - ANOVA$VarCom["Cov3","Estimates"] ,0)
}
else msDen <- ANOVA$VarCom["Var","Estimates"] - ANOVA$VarCom["Cov1","Estimates"]
chisqVal <- (I-1)*ANOVA$TRanova["T","MS"]/msDen
p <- 1 - pchisq(chisqVal, I - 1)
FRRC$FTests <- data.frame(MS = c(ANOVA$TRanova["T", "MS"], msDen),
Chisq = c(chisqVal,NA),
DF = c(I - 1, NA),
p = c(p,NA),
row.names = c("Treatment", "Error"),
stringsAsFactors = FALSE)
stdErr <- sqrt(2 * msDen/J)
zStat <- vector()
PrGTz <- vector()
CI <- array(dim = c(choose(I,2),2))
for (i in 1:choose(I,2)) {
zStat[i] <- trtMeanDiffs[i,1]/stdErr
PrGTz[i] <- 2 * pnorm(abs(zStat[i]), lower.tail = FALSE)
CI[i, ] <- c(trtMeanDiffs[i,1] + qnorm(alpha/2) * stdErr,
trtMeanDiffs[i,1] + qnorm(1-alpha/2) * stdErr)
}
FRRC$ciDiffTrt <- data.frame(Estimate = trtMeanDiffs,
StdErr = rep(stdErr, choose(I, 2)),
z = zStat,
PrGTz = PrGTz,
CILower = CI[,1],
CIUpper = CI[,2],
row.names = diffTRName,
stringsAsFactors = FALSE)
}
stdErr <- vector()
df <- vector()
CI <- array(dim = c(I,2))
ci <- data.frame()
for (i in 1:I) {
df[i] <- K - 1
stdErr[i] <- sqrt((ANOVA$IndividualTrt[i,"varEachTrt"] +
(J-1)*max(ANOVA$IndividualTrt[i,"cov2EachTrt"],0))/J)
CI[i, ] <- c(FOMs$trtMeans[i,1] + qnorm(alpha/2) * stdErr[i],
FOMs$trtMeans[i,1] + qnorm(1-alpha/2) * stdErr[i])
rowName <- paste0("trt", modalityID[i])
ci <- rbind(ci, data.frame(Estimate = FOMs$trtMeans[i,1],
StdErr = stdErr[i],
DF = df[i],
CILower = CI[i,1],
CIUpper = CI[i,2],
row.names = rowName,
stringsAsFactors = FALSE))
}
FRRC$ciAvgRdrEachTrt <- ci
if (I > 1) {
trtMeanDiffs <- array(dim = c(J, choose(I, 2)))
Reader <- array(dim = c(J, choose(I, 2)))
stdErr <- array(dim = c(J, choose(I, 2)))
zStat <- array(dim = c(J, choose(I, 2)))
trDiffNames <- array(dim = c(J, choose(I, 2)))
PrGTz <- array(dim = c(J, choose(I, 2)))
CIReader <- array(dim = c(J, choose(I, 2),2))
ci <- data.frame()
for (j in 1:J) {
Reader[j,] <- rep(readerID[j], choose(I, 2))
stdErr[j,] <- sqrt(2 * (ANOVA$IndividualRdr[j,"varEachRdr"] - ANOVA$IndividualRdr[j,"cov1EachRdr"]))
pair <- 1
for (i in 1:I) {
if (i == I) break
for (ip in (i + 1):I) {
trtMeanDiffs[j, pair] <- foms[i, j] - foms[ip, j]
trDiffNames[j,pair] <- diffTRName[pair]
zStat[j,pair] <- trtMeanDiffs[j,pair]/stdErr[j,pair]
PrGTz[j,pair] <- 2 * pnorm(abs(zStat[j,pair]), lower.tail = FALSE)
CIReader[j, pair,] <- c(trtMeanDiffs[j,pair] + qnorm(alpha/2) * stdErr[j,pair],
trtMeanDiffs[j,pair] + qnorm(1-alpha/2) * stdErr[j,pair])
rowName <- paste0("rdr", Reader[j,pair], "::", trDiffNames[j, pair])
ci <- rbind(ci, data.frame(Estimate = trtMeanDiffs[j, pair],
StdErr = stdErr[j,pair],
z = zStat[j, pair],
PrGTz = PrGTz[j, pair],
CILower = CIReader[j, pair,1],
CIUpper = CIReader[j, pair,2],
row.names = rowName,
stringsAsFactors = FALSE))
pair <- pair + 1
}
}
}
FRRC$ciDiffTrtEachRdr <- ci
FRRC$IndividualRdrVarCov1 <- ANOVA$IndividualRdr[,3:4]
}
return(FRRC)
} |
if (compareVersion(paste0(version$major, ".", version$minor), "3.6") < 0) {
skip("Randomization algorithm has changed from R 3.6")
}
library(quanteda)
library(magrittr)
if (!"dplyr" %in% rownames(installed.packages())) {
skip("dplyr is not installed")
}
data(data_corpus_inaugural, package = "quanteda")
data_corpus_inaugural <- head(data_corpus_inaugural, n = 58)
data_tokens <- tokens(data_corpus_inaugural, remove_numbers = TRUE,
remove_punct = TRUE, remove_symbols = TRUE,
remove_separators = TRUE, remove_url = TRUE) %>%
tokens_tolower() %>%
tokens_remove(c(stopwords("english"),
"may", "shall", "can",
"must", "upon", "with", "without")) %>%
tokens_select(min_nchar = 3)
data_dfm <- dfm(data_tokens) %>%
dfm_trim(min_termfreq = 5, min_docfreq = 2)
keyATM_docs <- keyATM_read(data_dfm)
keywords <- list(Government = c("laws", "law", "executive"),
Congress = c("congress", "party"),
Peace = c("peace", "world", "freedom"),
Constitution = c("constitution", "rights"),
ForeignAffairs = c("foreign", "war"))
vars <- docvars(data_corpus_inaugural)
vars %>%
tibble::as_tibble() %>%
dplyr::mutate(Period = dplyr::case_when(Year <= 1899 ~ "18_19c",
TRUE ~ "20_21c")) %>%
dplyr::mutate(Party = dplyr::case_when(Party == "Democratic" ~ "Democratic",
Party == "Republican" ~ "Republican",
TRUE ~ "Other")) %>%
dplyr::select(Party, Period) -> vars_selected
vars_selected %>%
dplyr::mutate(Party = factor(Party,
levels = c("Other", "Republican", "Democratic")),
Period = factor(Period,
levels = c("18_19c", "20_21c"))) -> vars_selected
out <- keyATM(docs = keyATM_docs,
no_keyword_topics = 5,
keywords = keywords,
model = "covariates",
model_settings = list(covariates_data = vars_selected,
covariates_formula = ~ Party + Period,
standardize = "all", covariates_model = "DirMulti"),
options = list(seed = 250, iterations = 20),
keep = c("Z", "S")
)
test_that("Covariates info", {
expect_output(mat <- covariates_info(out))
expect_type(mat, "double")
})
test_that("Covariates get", {
mat <- covariates_get(out)
expect_type(mat, "double")
expect_equivalent(dim(mat), c(58L, 4L))
expect_equivalent(colnames(mat), c("(Intercept)", "PartyRepublican", "PartyDemocratic", "Period20_21c"))
})
test_that("Doc Topic", {
skip_on_cran()
strata_topic <- by_strata_DocTopic(out, by_var = "Period20_21c",
labels = c("18_19c", "20_21c"),
posterior_mean = TRUE)
p <- plot(strata_topic, var_name = "Period", show_topic = c(1,2,3,4))
expect_s3_class(p, "keyATM_fig")
skip_on_os("linux")
expect_equal(summary(strata_topic, method = "eti", point = "median")[[2]]$Point[1], 0.09026675, tolerance = 0.000001)
expect_equal(summary(strata_topic, method = "hdi", point = "median")[[2]]$Upper[2], 0.08066711, tolerance = 0.000001)
expect_equal(summary(strata_topic)[[2]]$Lower[3], 0.1319587, tolerance = 0.000001)
})
test_that("Topic Word", {
skip_on_os("linux") ; skip_on_cran()
strata_tw <- by_strata_TopicWord(out, keyATM_docs, by = as.vector(vars_selected$Party))
top <- top_words(strata_tw, n = 3)
expect_equivalent(top$Democratic[1, 3], "world [\U2713]")
expect_equivalent(top$Republican[1, 5], "war [\U2713]")
expect_equivalent(top$Republican[3, 7], "done")
}) |
library("testthat")
library("permute")
context("Testing shuffle()")
test_that("shuffle(n) returns seq_len(n) when not permuting", {
ctrl <- how(within = Within(type = "none"))
expect_that(shuffle(3, control = ctrl), is_identical_to(seq_len(3)))
expect_that(shuffle(1, control = ctrl), is_identical_to(1L))
})
test_that("shuffle() returns integers", {
ctrl <- how(within = Within(type = "none"))
expect_that(shuffle(4), is_a("integer"))
expect_that(shuffle(100), is_a("integer"))
expect_that(shuffle(1, control = ctrl), is_identical_to(1L))
expect_that(shuffle(3, control = ctrl), is_identical_to(c(1L, 2L, 3L)))
})
test_that("shuffle() works for non-contigous blocks of samples", {
Plot <- factor(rep(1:4, 5))
CTRL <- how(plots = Plots(strata = Plot, type = "free"),
within = Within(type = "none"))
n <- 20
suppressWarnings(RNGversion("3.5.0"))
set.seed(2)
result <- shuffle(n, CTRL)
out1 <- as.integer(c( 3, 2, 1, 4,
7, 6, 5, 8,
11,10, 9,12,
15,14,13,16,
19,18,17,20))
expect_that(result, is_identical_to(out1))
out2 <- factor(as.integer(rep(c(3,2,1,4), 5)), levels = 1:4)
expect_that(Plot[result], is_identical_to(out2))
})
test_that("shuffle can permute both plots and within in presence of blocks", {
control <- how(within = Within(type = "free"),
plots = Plots(strata = rep(gl(2,7),2), type = "free"),
blocks = gl(2, 14))
permSet <- shuffle(28, control = control)
expect_identical(length(permSet), 28L)
expect_is(permSet, "integer")
})
test_that("constant within plots works", {
fac <- gl(4, 5)
ctrl <- how(within = Within(type = "series", constant = TRUE),
plots = Plots(strata = fac, type = "none"))
perm <- shuffle(length(fac), control = ctrl)
expect_identical(length(perm), length(fac))
expect_identical(length(perm), 20L)
expect_is(perm, "integer")
ctrl <- how(within = Within(type = "free", constant = TRUE),
plots = Plots(strata = fac, type = "none"))
perm <- shuffle(length(fac), control = ctrl)
expect_identical(length(perm), length(fac))
expect_identical(length(perm), 20L)
expect_is(perm, "integer")
fac <- gl(4, 9)
ctrl <- how(within = Within(type = "grid", nrow = 3, ncol = 3, constant = TRUE),
plots = Plots(strata = fac, type = "none"))
perm <- shuffle(length(fac), control = ctrl)
expect_identical(length(perm), length(fac))
expect_identical(length(perm), 36L)
expect_is(perm, "integer")
})
test_that("shuffel works with objects passed to n", {
obj <- 1:4
p <- shuffle(obj)
expect_is(p, "integer")
expect_identical(length(p), 4L)
obj <- as.integer(1:4)
p <- shuffle(obj)
expect_is(p, "integer")
expect_identical(length(p), 4L)
obj <- as.factor(1:4)
p <- shuffle(obj)
expect_is(p, "integer")
expect_identical(length(p), 4L)
obj <- letters[1:4]
p <- shuffle(obj)
expect_is(p, "integer")
expect_identical(length(p), 4L)
obj <- matrix(1:16, ncol = 4, nrow = 4)
p <- shuffle(obj)
expect_is(p, "integer")
expect_identical(length(p), 4L)
obj <- data.frame(A = 1:4, B = letters[1:4])
p <- shuffle(obj)
expect_is(p, "integer")
expect_identical(length(p), 4L)
}) |
gecko <- function(port = 4567L, version = "latest", check = TRUE,
loglevel = c("info", "fatal", "error", "warn", "config",
"debug", "trace"), verbose = TRUE,
retcommand = FALSE, ...){
assert_that(is_integer(port))
assert_that(is_string(version))
assert_that(is_logical(verbose))
loglevel <- match.arg(loglevel)
geckocheck <- gecko_check(verbose, check = check)
geckoplat <- geckocheck[["platform"]]
geckoversion <- gecko_ver(geckoplat, version)
eopts <- list(...)
args <- c(Reduce(c, eopts[names(eopts) == "args"]))
args[["port"]] <- sprintf("--port=%s", port)
args[["log"]] <- sprintf("--log=%s", loglevel)
if(retcommand){
return(paste(c(geckoversion[["path"]], args), collapse = " "))
}
pfile <- pipe_files()
geckodrv <- spawn_tofile(geckoversion[["path"]],
args, pfile[["out"]], pfile[["err"]])
if(isFALSE(geckodrv$is_alive())){
err <- paste0(readLines(pfile[["err"]]), collapse = "\n")
stop("Geckodriver couldn't be started\n", err)
}
startlog <- generic_start_log(geckodrv,
outfile = pfile[["out"]],
errfile = pfile[["err"]])
if(length(startlog[["stderr"]]) >0){
if(any(grepl("Address already in use", startlog[["stderr"]]))){
geckodrv$kill()
stop("Gecko Driver signals port = ", port, " is already in use.")
}
}
log <- as.environment(startlog)
list(
process = geckodrv,
output = function(timeout = 0L){
infun_read(geckodrv, log, "stdout", timeout = timeout,
outfile = pfile[["out"]], errfile = pfile[["err"]])
},
error = function(timeout = 0L){
infun_read(geckodrv, log, "stderr", timeout = timeout,
outfile = pfile[["out"]], errfile = pfile[["err"]])
},
stop = function(){geckodrv$kill()},
log = function(){
infun_read(geckodrv, log, outfile = pfile[["out"]], errfile = pfile[["err"]])
as.list(log)
}
)
}
gecko_check <- function(verbose, check = TRUE){
geckoyml <- system.file("yaml", "geckodriver.yml", package = "wdman")
gyml <- yaml::yaml.load_file(geckoyml)
platvec <- c("predlfunction", "binman::predl_github_assets","platform")
gyml[[platvec]] <-
switch(Sys.info()["sysname"],
Linux = grep(os_arch("linux"), gyml[[platvec]], value = TRUE),
Windows = grep(os_arch("win"), gyml[[platvec]], value = TRUE),
Darwin = grep("mac", gyml[[platvec]], value = TRUE),
stop("Unknown OS")
)
tempyml <- tempfile(fileext = ".yml")
write(yaml::as.yaml(gyml), tempyml)
if(check){
if(verbose) message("checking geckodriver versions:")
process_yaml(tempyml, verbose)
}
geckoplat <- gyml[[platvec]]
list(yaml = gyml, platform = geckoplat)
}
gecko_ver <- function(platform, version){
geckover <- binman::list_versions("geckodriver")[[platform]]
geckover <- if(identical(version, "latest")){
as.character(max(semver::parse_version(geckover)))
}else{
mtch <- match(version, geckover)
if(is.na(mtch) || is.null(mtch)){
stop("version requested doesnt match versions available = ",
paste(geckover, collapse = ","))
}
geckover[mtch]
}
geckodir <- normalizePath(
file.path(app_dir("geckodriver"), platform, geckover)
)
geckopath <- list.files(geckodir,
pattern = "geckodriver($|.exe$)",
full.names = TRUE)
list(version = geckover, dir = geckodir, path = geckopath)
} |
coef.fcrr <- function(object, ...)
object$coef |
loci_to_genind <- function(x,
ploidy = 2,
na.alleles = c("NA")){
if(!inherits(x, "loci")){
stop("Input 'x' must be a 'loci' object.")
}
if(!all(x$population == x$population[order(x$population)])){
message("Individuals in 'x' were not ordered, they have
been ordered by populations and populations ordered in alphabetic
order for the convertion.")
x <- x[order(x$population), ]
}
data_genind <- pegas::loci2genind(x,
ploidy,
na.alleles)
return(data_genind)
} |
"driverA"
"driverB"
"drivers"
"parameters"
"simulation"
"accumulationRate"
NULL
NULL
NULL
utils::globalVariables(c("Variable", "Value", "Time", "Species", "Suitability", "Driver.density.y", "Driver.weights", "Fecundity", "Age", "Biomass", "Reproductive.age", "ci.max", "ci.min", "Time", "Color", "error", "value", "..scaled..", "driver.A.weight", "maximum.biomass", "growthrate", "carrying.capacity", "fecundity", "pollen.control", "growth.rate")) |
`plot.segratioMCMC` <-
function(x, ..., row.index=c(1:10),
var.index=c(1:6),
marker.index=c(1:8))
{
if (class(x) != "segratioMCMC")
stop("'x' must be of class 'segratioMCMC'")
T.index <- grep("T\\[",coda::varnames(x$mcmc.list))
T.print <- T.index[marker.index]
drop <- T.index
b.index <- grep("b\\[",coda::varnames(x$mcmc.list))
if (length(b.index>0)){
b.print <- b.index[marker.index]
drop <- c(T.index, b.index)
}
var <- c(1:dim(x$mcmc.list[[1]])[2])[-drop]
var.index <- var[var.index]
plot(x$mcmc.list [,c(var.index,T.print)], ... )
} |
test_that("'utf8_encode' can encode an ASCII string", {
expect_equal(utf8_encode("hello"), "hello")
})
test_that("'utf8_encode' can encode NULL or an NA string", {
expect_equal(utf8_encode(NULL), NULL)
expect_equal(utf8_encode(NA_character_), NA_character_)
})
test_that("'utf8_encode' preserves attributes", {
x <- matrix(LETTERS, 2, 13)
x[1, 4] <- "\xa4"
Encoding(x) <- "latin1"
dimnames(x) <- list(c("foo", "bar"), as.character(1:13))
class(x) <- "my_class"
local_ctype("UTF-8")
expect_equal(utf8_encode(x), enc2utf8(x))
})
test_that("'utf8_encode' can encode basic Unicode", {
x <- "\u200b"
Encoding(x) <- "UTF-8"
local_ctype("UTF-8")
expect_equal(utf8_encode(x), x)
})
test_that("'utf8_encode' can encode extended Unicode", {
skip_on_os("windows")
x <- intToUtf8(0x0001f60d)
Encoding(x) <- "UTF-8"
local_ctype("UTF-8")
expect_equal(utf8_encode(x), x)
})
test_that("'utf8_encode' can handle ASCII escapes", {
x <- "\x01\a\b\f\n\r\t\v\x7f"
expect_equal(utf8_encode(x), "\\u0001\\a\\b\\f\\n\\r\\t\\v\\u007f")
})
test_that("'utf8_encode' can handle invalid UTF-8", {
x <- "\xfe"
Encoding(x) <- "bytes"
expect_equal(utf8_encode(x), "\\xfe")
})
test_that("'utf8_encode' can handle bytes", {
x <- "\x01\a\b\f\n\r\t\v\x7f\x80\xff"
Encoding(x) <- "bytes"
expect_equal(
utf8_encode(x),
"\\x01\\a\\b\\f\\n\\r\\t\\v\\x7f\\x80\\xff"
)
})
test_that("'utf8_encode' can handle latin-1", {
x <- "her \xa320"
Encoding(x) <- "latin1"
with_ctype("C", {
latin <- utf8_encode(x)
})
expect_equal(latin, "her \\u00a320")
local_ctype("UTF-8")
expect_equal(utf8_encode(x), "her \u00a320")
})
test_that("'utf8_encode' can handle bytes", {
x <- c("fa\u00E7ile", "fa\xE7ile", "fa\xC3\xA7ile")
Encoding(x) <- c("UTF-8", "UTF-8", "bytes")
local_ctype("UTF-8")
y <- c("fa\u00e7ile", "fa\\xe7ile", "fa\\xc3\\xa7ile")
Encoding(y) <- c("UTF-8", "UTF-8", "bytes")
expect_equal(utf8_encode(x), y)
})
test_that("'utf8_encode escapes controls in UTF-8 text", {
local_ctype("UTF-8")
x <- "\n\u2026"
Encoding(x) <- "UTF-8"
y <- "\\n\u2026"
Encoding(y) <- "UTF-8"
expect_equal(utf8_encode(x), y)
})
test_that("'utf8_encode' can quote", {
x <- c("abcde", "x", "123", "\"", "'")
expect_equal(utf8_encode(x, quote = FALSE), encodeString(x, quote = ""))
expect_equal(utf8_encode(x, quote = TRUE), encodeString(x, quote = '"'))
})
test_that("'utf8_encode' ignores justify if width = 0", {
x <- c("abcde", "x", "123", "\"", "'")
expect_equal(
utf8_encode(x, width = 0, justify = "none"),
encodeString(x, width = 0, justify = "none")
)
expect_equal(
utf8_encode(x, width = 0, justify = "left"),
encodeString(x, width = 0, justify = "left")
)
expect_equal(
utf8_encode(x, width = 0, justify = "centre"),
encodeString(x, width = 0, justify = "centre")
)
expect_equal(
utf8_encode(x, width = 0, justify = "right"),
encodeString(x, width = 0, justify = "right")
)
})
test_that("'utf8_encode' can justify", {
x <- c("abcde", "x", "123", "\"", "'")
expect_equal(
utf8_encode(x, width = NULL, justify = "none"),
encodeString(x, width = NULL, justify = "none")
)
expect_equal(
utf8_encode(x, width = NULL, justify = "left"),
encodeString(x, width = NULL, justify = "left")
)
expect_equal(
utf8_encode(x, width = NULL, justify = "centre"),
encodeString(x, width = NULL, justify = "centre")
)
expect_equal(
utf8_encode(x, width = NULL, justify = "right"),
encodeString(x, width = NULL, justify = "right")
)
})
test_that("'utf8_encode' can justify and quote", {
expect_equal(
utf8_encode(c("1", "10", "100"), width = NULL, quote = TRUE),
encodeString(c("1", "10", "100"), width = NULL, quote = '"')
)
}) |
test_that("has ok print method", {
partial <- partial_factor("x")
expect_known_output(
print(partial),
test_path("test-partial-factor-print-partial.txt")
)
both <- vec_ptype2(partial, factor("y"))
expect_known_output(
print(both),
test_path("test-partial-factor-print-both.txt")
)
empty <- partial_factor()
expect_known_output(
print(empty),
test_path("test-partial-factor-print-empty.txt")
)
learned <- vec_ptype2(empty, factor("y"))
expect_known_output(
print(learned),
test_path("test-partial-factor-print-learned.txt")
)
expect_equal(vec_ptype_abbr(partial), "prtl_fctr")
})
test_that("order of levels comes from data", {
pfctr <- partial_factor(c("y", "x"))
fctr <- factor(levels = c("x", "y"))
expect_equal(levels(vec_ptype_common(pfctr, fctr)), c("x", "y"))
expect_equal(levels(vec_ptype_common(fctr, pfctr)), c("x", "y"))
})
test_that("partial levels added to end if not in data", {
pfctr <- partial_factor("y")
fctr <- factor(levels = "x")
expect_equal(levels(vec_ptype_common(pfctr, fctr)), c("x", "y"))
expect_equal(levels(vec_ptype_common(fctr, pfctr)), c("x", "y"))
})
test_that("can assert partial factors based on level presence", {
pfctr <- partial_factor("y")
expect_true(vec_is(factor("y"), pfctr))
expect_false(vec_is(factor("x"), pfctr))
expect_true(vec_is(factor(c("x", "y")), pfctr))
pfctr <- partial_factor(c("y", "z"))
expect_false(vec_is(factor("y"), pfctr))
expect_true(vec_is(factor(c("y", "z")), pfctr))
expect_true(vec_is(factor(c("x", "y", "z")), pfctr))
}) |
expected <- eval(parse(text="c(\"Min. \", \"1st Qu.\", \"Median \", \"Mean \", \"3rd Qu.\", \"Max. \")"));
test(id=0, code={
argv <- eval(parse(text="list(c(\"Min.\", \"1st Qu.\", \"Median\", \"Mean\", \"3rd Qu.\", \"Max.\"), FALSE, NULL, 0L, NULL, 0L, TRUE, NA)"));
.Internal(`format`(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]], argv[[6]], argv[[7]], argv[[8]]));
}, o=expected); |
find_peaks<-function (x, y = NULL, num_peaks = NULL, adjust = 2, plot = FALSE,
...)
{
x <- as.vector(x)
if (length(x) < 2) {
warning("At least 2 observations must be given in 'x' to find peaks.")
return(NA)
}
if (is.null(y)) {
dens <- density(x, adjust = adjust, ...)
}
else {
y <- as.vector(y)
if (length(x) != length(y)) {
stop("The lengths of 'x' and 'y' must be equal.")
}
dens <- list(x = x, y = y)
}
second_deriv <- diff(sign(diff(dens$y)))
which_maxima <- which(second_deriv == -2) + 1
which_maxima <- which_maxima[findInterval(dens$x[which_maxima],
range(x)) == 1]
which_maxima <- which_maxima[order(dens$y[which_maxima],
decreasing = TRUE)]
if (length(which_maxima) > 0) {
peaks <- dens$x[which_maxima]
if (is.null(num_peaks) || num_peaks > length(peaks)) {
num_peaks <- length(peaks)
}
peaks <- peaks[seq_len(num_peaks)]
}
else {
peaks <- NA
}
peaks <- data.frame(x = peaks, y = dens$y[which_maxima][seq_len(num_peaks)])
if (plot) {
plot(dens, main = paste("adjust =", adjust))
points(peaks, , col = "red")
}
return( peaks )
}
find_valleys<-function (x, y = NULL, num_valleys = NULL, adjust = 2, ...)
{
x <- as.vector(x)
if (length(x) < 2) {
warning("At least 2 observations must be given in 'x' to find valleys.")
return(NA)
}
if (is.null(y)) {
dens <- density(x, adjust = adjust, ...)
}
else {
y <- as.vector(y)
if (length(x) != length(y)) {
stop("The lengths of 'x' and 'y' must be equal.")
}
dens <- list(x = x, y = y)
}
second_deriv <- diff(sign(diff(dens$y)))
which_minima <- which(second_deriv == 2) + 1
which_minima <- which_minima[findInterval(dens$x[which_minima],
range(x)) == 1]
which_minima <- which_minima[order(dens$y[which_minima],
decreasing = FALSE)]
if (length(which_minima) > 0) {
valleys <- dens$x[which_minima]
if (is.null(num_valleys) || num_valleys > length(valleys)) {
num_valleys <- length(valleys)
}
valleys <- valleys[seq_len(num_valleys)]
}
else {
valleys <- NA
}
return( valleys )
}
between_interval<-function (x, interval)
{
x <- x[findInterval(x, interval) == 1]
if (length(x) == 0) {
x <- NA
}
return( x )
}
apply_by<-function(x,by_idx,fun,...){
res<-sapply(unique(by_idx),function(a){
apply(x[,by_idx==a],1,fun,...)}
)
return(res)
}
orderCutpoints <- function(midindex, cutpoints) {
decreasingIdx <- midindex:1
increasingIdx <- (midindex:length(cutpoints))
cutpointsMonotone <- c(cummin(cutpoints[decreasingIdx]),
cummax(cutpoints[increasingIdx])[-1])
stopifnot(length(cutpointsMonotone)==length(cutpoints))
cutpointsMonotone[c(decreasingIdx, increasingIdx[-1])]
}
thresholdSCRNACountMatrix <-function( data_all ,
conditions = NULL ,
cutbins = NULL ,
nbins = 10 ,
bin_by = "median",
qt = 0.975,
min_per_bin = 50 ,
absolute_min= 0.0 ,
data_log = TRUE,
adj = 1
)
{
log_base <- 2
maybelogged <- max(range(data_all))<30
if(!data_log){
if(maybelogged){
warning("Data may already be log transformed! Should you set `data_log=TRUE`?")
}
log_data <- log( data_all+ 1, base = log_base )
} else{
if(!maybelogged){
warning("Data may not have been log transformed! Should you set `data_log=FALSE`?")
}
log_data <- data_all
}
if( is.null( conditions ) ){
conditions <- rep( 1, dim( data_all )[2] )
} else {
conditions <- as.character( conditions )
}
comp_zero_idx <- rowSums( log_data> 0.0 ) == 0
data <- 2^log_data[!comp_zero_idx,]-1
log_data <- log_data[!comp_zero_idx,]
uni_cond <- unique( conditions )
arg <- match.arg( bin_by, c( "quantile", "proportion", "mean", "median","iqr" ) )
if( arg == "median" ){
cond_stat <- apply_by( log_data, conditions, function( x ) if( all( x <= 0.0 ) ){ 0 } else { median( x[x>0.0]) })
} else if( arg == "mean" ){
cond_stat <- apply_by( data, conditions, function( x ) if( all(x <= 0.0 ) ){ 0 } else { log( mean( x[x>0.0])+1, base = log_base) } )
} else if( arg == "proportion" ){
cond_stat <- apply_by( data > 0, conditions, mean )
} else if( arg == "quantile" ){
cond_stat <- apply_by( log_data, conditions, function(x) if( all( x <= 0.0 ) ){ 0 } else { quantile( x[x>0.0], qt ) } )
} else if( arg == "iqr" ){
cond_stat <- apply_by( log_data, conditions, function(x) if( all( x <= 0.0 ) ){ 0 } else { IQR( x[x>0.0]) } )
} else {
stop("choose bin_by from c('proportion', 'mean', 'median' )")
}
rprop <- range( unlist(cond_stat) )
if( is.null(cutbins) ){
rprop <- range( cond_stat )
cutbins <- exp( seq( log( rprop[1] + 1 ),log( rprop[2] + 1 ),length.out = nbins + 1 ) ) - 1
cutbins[1] <- min( cutbins[1], rprop[1] - 1e-10 )
cutbins[ length( cutbins ) ]<- max( cutbins[length( cutbins )], rprop[2] + 1e-10 )
} else{
if( !( min(cutbins)< min(cond_stat) & max(cutbins) > max(cond_stat) ) ){
stop("range of cutbins must include the range of the log expression")
}
}
cond_stat_bins <- cut( cond_stat, cutbins )
t_prop_bins <- table( cond_stat_bins )
cond_stat_bins_array <- array( cond_stat_bins, dim( cond_stat ) )
dimnames( cond_stat_bins_array ) <- dimnames( cond_stat )
while( any( t_prop_bins < min_per_bin ) ){
i <- which.min( t_prop_bins )
if( i == 1 & t_prop_bins[ i ] < min_per_bin ){
cutbins <- cutbins[-( i + 1 )]
} else if( i == length( t_prop_bins ) & t_prop_bins[i] < min_per_bin ){
cutbins <- cutbins[ -i ]
} else if( t_prop_bins[ i ] < min_per_bin ){
cutbins <- cutbins[ -ifelse( t_prop_bins[i-1] < t_prop_bins[ i + 1 ], i, ( i + 1 ) ) ]
}
cond_stat_bins <- cut( cond_stat, cutbins )
t_prop_bins <- table( cond_stat_bins )
}
cond_stat_bins_array<-array(cond_stat_bins, dim(cond_stat))
dimnames(cond_stat_bins_array)<-dimnames(cond_stat)
log_data_list <- vector("list", length(levels(cond_stat_bins)))
names(log_data_list) <- levels(cond_stat_bins)
for( i in levels(cond_stat_bins)){
log_data_list[[i]]<-NULL
for( j in uni_cond){
x<-unlist(log_data[cond_stat_bins_array[,j]==i,conditions==j])
log_data_list[[i]]<-c(log_data_list[[i]],x[x>0.0])
}
}
dens <- lapply( log_data_list, function( x ) { if(length(x)>2){ density( x, adjust = adj ) } else{ NULL } })
peaks <- lapply( dens, function( dd ) { if( is.null(dd) ){ data.frame( x=0, y=0 ) }else{ find_peaks( dd$x,dd$y, adjust = adj )}} )
valleys<- lapply( dens, function( dd ) { if( is.null(dd) ){ list(0)} else{find_valleys( dd$x,dd$y, adjust = adj ) } })
single_modes<-do.call(c,lapply(peaks,function(x)abs(diff(x[1:2,1]))))<1|(lapply(list(do.call(c,lapply(peaks,function(x)abs(diff(x[1:2,2]))))),function(x)(x-median(na.omit(x)))/mad(na.omit(x)))[[1]]>2)
singles <- ldply( lapply( peaks,nrow ),function( x ) x == 1 )[,2]
single_modes[singles] <- TRUE
cutpoints<-lapply( seq_along(peaks), function( j ){
valleys[[j]][which( findInterval( valleys[[j]], sort( peaks[[j]][1:2,1]) ) == 1 )]
})
cutpoints[single_modes]<-NA
cutpoints <- lapply( cutpoints, function(x) ifelse( length( x )==0, NA, max( x ) ) )
names(cutpoints)<- names( peaks )
if( all( is.na( ldply( cutpoints )[,2] ) ) ){
for( i in 1:length( cutpoints ) ){
cutpoints[[i]] <- 0.0
}
} else {
for(i in 1:length( cutpoints ) ){
if( is.na( cutpoints[[i]] ) ){
if( i != length( cutpoints ) ){
cutpoints[[i]]<-do.call(c,cutpoints)[min(which(!is.na(do.call(c,cutpoints))))]
}else{
cutpoints[[i]]<-do.call(c,cutpoints)[max(which(!is.na(do.call(c,cutpoints))))]
}
}
}
}
vals2 <- unlist(valleys[which(unlist(lapply(peaks,nrow))==2)])
if( length(vals2) > 0 ){
midindex <- which(names(peaks)==names(which.min(abs(vals2-quantile(vals2,c(0.75),na.rm=TRUE)))))
} else{
midindex <- length(cutpoints)
}
cutpoints <- orderCutpoints(midindex, cutpoints)
cutpoints <- pmax(cutpoints, absolute_min)
if(data_log){
data_threshold <- log_data
} else {
data_threshold <- data
}
for( j in uni_cond ){
for( i in levels(cond_stat_bins) ){
if(any(cond_stat_bins_array[,j]==i))
data_threshold[cond_stat_bins_array[,j]==i,conditions==j][log_data[cond_stat_bins_array[,j]==i,conditions==j]<cutpoints[i]]<-0
}
}
nms <- names( cutpoints )
cutpoints <- unlist( cutpoints )
names( cutpoints ) <- nms
print( cutpoints )
data_threshold_all <- data_all*0
data_threshold_all[!comp_zero_idx,] <- data_threshold
bin_all <- factor(cond_stat_bins_array)
dim(bin_all) <- dim(cond_stat_bins_array)
res_obj <- list( counts_threshold = data_threshold_all,
original_data = data_all,
cutpoint = cutpoints,
bin = bin_all,
conditions = conditions,
density = dens
,peaks = peaks, valleys= valleys)
class( res_obj )<- c( "list", "thresholdSCRNACountMatrix" )
return( res_obj )
}
plot.thresholdSCRNACountMatrix<-function(x, ask=FALSE, wait.time=0, type='bin', indices=NULL, ...)
{
type <- match.arg(type, c('bin', 'gene'), several.ok=TRUE)
op <- par(ask=ask)
par(mar=c(3,3,2,1), mgp=c(2,.7,0), tck=-.01)
if('bin' %in% type){
for(i in 1:length(x$density)){
if(!is.null(x$density[[i]])){
plot(x$density[[i]],main=names(x$cutpoint)[i], ...)
abline(v=x$cutpoint[i],col="red",lty=2)
Sys.sleep(wait.time)
}
}
}
if('gene' %in% type){
uni_cond <- unique(x$conditions)
num_cond <- as.numeric(as.factor(x$conditions))
if(is.null(indices)){
indices <- 10L
}
if(is.finite(indices) && length(indices)==1){
indices <- sample(ncol(x$original_data), indices)
}
if(any(indices < 1 | indices>ncol(x$original_data))) stop('`indices` must range between 1 and the number of columns of the count matrix.')
for(i in indices){
den <- density(x$original_data[,i])
plot(den, main=paste0('Index ', i, '(', colnames(x$original_data)[i], ')'), ...)
for(j in seq_along(uni_cond)){
abline(v=with(x, cutpoint[bin[i,j]]), col=j, lty=2)
with(x, rug(original_data[j==num_cond,i], col=j))
}
}
}
par(op)
}
summary.thresholdSCRNACountMatrix <- function(object, ...){
zeros <- lapply(object[c('original_data', 'counts_threshold')], function(o){
apply(o>0, 2, mean)
})
vars <- lapply(object[c('original_data', 'counts_threshold')], function(o){
o[o==0] <- NA
apply(o, 2, var, na.rm=TRUE)
})
shapiro <- lapply(object[c('original_data', 'counts_threshold')], function(o){
apply(o, 2, function(x){
})
})
out <- list(zeros=zeros, vars=vars, shapiro=shapiro)
class(out) <- c(class(out), 'summaryThresholdSCRNA')
out
}
if(getRversion() >= "2.15.1") globalVariables(c('L2', 'bin', 'cutpoint', 'original_data'))
print.summaryThresholdSCRNA <- function(x, ...){
class(x) <- class(x)[-length(class(x))]
m <- as.data.table(reshape2::melt(x, na.rm=TRUE))
m <- m[!is.na(value),]
setnames(m, 'L1', 'metric')
summ <- m[,list(stat=names(summary(value)), value=summary(value)),keyby=list(L2, metric)]
summ$stat <- factor(summ$stat, levels=c('Min.', '1st Qu.', 'Median', 'Mean', '3rd Qu.', 'Max.'))
dc <- dcast.data.table(summ, stat + L2 ~ metric)
setnames(dc, c('stat', 'L2', 'vars', 'zeros'), c('Quantile', 'Data', 'variance', 'prop. expressed'))
dcdf <- as.data.frame(dc)
print(dcdf, right=FALSE, row.names=FALSE)
invisible(dc)
} |
initializeModelObject <- function(parameter, model = "ROC", with.phi = FALSE, fix.observation.noise = FALSE, rfp.count.column = 1) {
if(model == "ROC") {
c.model <- new(ROCModel, with.phi, fix.observation.noise)
} else if (model == "FONSE") {
c.model = new(FONSEModel,with.phi,fix.observation.noise)
} else if (model == "PA") {
c.model <- new(PAModel, rfp.count.column,with.phi,fix.observation.noise)
} else if (model == "PANSE") {
c.model <- new(PANSEModel, rfp.count.column,with.phi,fix.observation.noise)
} else {
stop("Unknown model.")
}
c.model$setParameter(parameter)
return(c.model)
} |
CreateWeights <- function(formula,Gorder=3,dif=TRUE,facCons=FALSE,data,side,type.ind,fac.level,ord.fac,
indTwo=NULL, indThree=NULL){
D3function <- function(alevel,blevel,clevel,type="A",ordABC=c(FALSE,FALSE,FALSE)){
if(type=="A"){
D3 <- D3Afunction(alevel=alevel,blevel=blevel,clevel=clevel,ord=ordABC[1])
}else if(type=="B"){
D3 <- D3Bfunction(alevel=alevel,blevel=blevel,clevel=clevel,ord=ordABC[2])
}else if(type=="C"){
D3 <- D3Cfunction(alevel=alevel,blevel=blevel,clevel=clevel,ord=ordABC[3])
}
return(D3)
}
D3Afunction <- function(alevel,blevel,clevel,ord=FALSE){
D3a <- matrix(0,nrow=0,ncol=(alevel*blevel*clevel))
if(ord==FALSE){
for(i in 1:(alevel-1)){
for(j in (i+1):alevel){
base.v <- rep(0,alevel)
base.v[i] <- -1
base.v[j] <- 1
base.mat <- diag((blevel*clevel)) %x% t(base.v)
D3a <- rbind(D3a,base.mat)
}
}
}else if(ord==TRUE){
for(i in 1:(alevel-1)){
base.v <- rep(0,alevel)
base.v[i] <- -1
base.v[(i+1)] <- 1
base.mat <- diag((blevel*clevel)) %x% t(base.v)
D3a <- rbind(D3a,base.mat)
}
}
return(D3a)
}
D3Bfunction <- function(alevel,blevel,clevel,ord=FALSE){
if(ord==FALSE){
D3b <- matrix(0,nrow=0,ncol=(alevel*blevel*clevel))
for(i in 1:(blevel-1)){
left.temp <- matrix(0,ncol=((i-1)*(alevel)),nrow=(alevel))
left.main <- -diag((alevel))
left.final <- cbind(left.temp,left.main)
for(j in (i+1):blevel){
middle.temp <- matrix(0,ncol=((j-i-1)*(alevel)),nrow=(alevel))
right.main <- diag((alevel))
right.temp <- matrix(0,ncol=((blevel-j)*(alevel)),nrow=(alevel))
right.final <- cbind(middle.temp,right.main,right.temp)
D2b <- cbind(left.final,right.final)
D3base <- diag(clevel) %x% D2b
D3b <- rbind(D3b, D3base)
}
}
}else if (ord==TRUE){
D3b <- matrix(0,nrow=0,ncol=(alevel*blevel*clevel))
for(i in 1:(blevel-1)){
left <- matrix(0,ncol=((i-1)*(alevel)),nrow=(alevel))
Main <- cbind(-diag((alevel)),diag((alevel)))
right <- matrix(0,ncol=((blevel-(i+1))*(alevel)),nrow=(alevel))
D2b <- cbind(left,Main,right)
D3base <- diag(clevel) %x% D2b
D3b <- rbind(D3b, D3base)
}
}
return(D3b)
}
D3Cfunction <- function(alevel,blevel,clevel,ord=FALSE){
if(ord==FALSE){
D3c <- matrix(0,nrow=0,ncol=(alevel*blevel*clevel))
for(i in 1:(clevel-1)){
left.temp <- matrix(0,ncol=((i-1)*(alevel*blevel)),nrow=(alevel*blevel))
left.main <- -diag((alevel*blevel))
left.final <- cbind(left.temp,left.main)
for(j in (i+1):clevel){
middle.temp <- matrix(0,ncol=((j-i-1)*(alevel*blevel)),nrow=(alevel*blevel))
right.main <- diag((alevel*blevel))
right.temp <- matrix(0,ncol=((clevel-j)*(alevel*blevel)),
nrow=(alevel*blevel))
right.final <- cbind(middle.temp,right.main,right.temp)
D3c <- rbind(D3c,cbind(left.final,right.final))
}
}
}else if (ord==TRUE){
Left <- cbind(-diag((alevel*blevel)*(clevel-1)),
matrix(0,ncol=(alevel*blevel),nrow=(alevel*blevel)*(clevel-1)))
Right <- cbind(matrix(0,ncol=(alevel*blevel),nrow=(alevel*blevel)*(clevel-1)),
diag((alevel*blevel)*(clevel-1)))
D3c <- Left + Right
}
return(D3c)
}
D2function <- function(alevel,blevel,type,ordAB){
if(type=="A"){
D2 <- D2Afunction(alevel=alevel,blevel=blevel,ord=ordAB[1])
}else if(type=="B"){
D2 <- D2Bfunction(alevel=alevel,blevel=blevel,ord=ordAB[2])
}
return(D2)
}
D2Afunction <- function(alevel,blevel,ord=FALSE){
D2a <- matrix(0,nrow=0,ncol=(alevel*blevel))
if(ord==FALSE){
for(i in 1:(alevel-1)){
for(j in (i+1):alevel){
base.v <- rep(0,alevel)
base.v[i] <- -1
base.v[j] <- 1
base.mat <- diag(blevel) %x% t(base.v)
D2a <- rbind(D2a,base.mat)
}
}
}else if(ord==TRUE){
for(i in 1:(alevel-1)){
base.v <- rep(0,alevel)
base.v[i] <- -1
base.v[(i+1)] <- 1
base.mat <- diag(blevel) %x% t(base.v)
D2a <- rbind(D2a,base.mat)
}
}
return(D2a)
}
D2Bfunction <- function(alevel,blevel,ord=FALSE){
if(ord==FALSE){
D2b <- matrix(0,nrow=0,ncol=(alevel*blevel))
for(i in 1:(blevel-1)){
left.temp <- matrix(0,ncol=((i-1)*(alevel)),nrow=(alevel))
left.main <- -diag((alevel))
left.final <- cbind(left.temp,left.main)
for(j in (i+1):blevel){
middle.temp <- matrix(0,ncol=((j-i-1)*(alevel)),nrow=(alevel))
right.main <- diag((alevel))
right.temp <- matrix(0,ncol=((blevel-j)*(alevel)),nrow=(alevel))
right.final <- cbind(middle.temp,right.main,right.temp)
D2b <- rbind(D2b,cbind(left.final,right.final))
}
}
}else if (ord==TRUE){
Left <- cbind(-diag((alevel)*(blevel-1)),matrix(0,ncol=alevel,nrow=(alevel)*(blevel-1)))
Right <- cbind(matrix(0,ncol=alevel,nrow=(alevel)*(blevel-1)), diag((alevel)*(blevel-1)))
D2b <- Left + Right
}
return(D2b)
}
D1function <- function(nlevel,ord=FALSE){
if(ord==FALSE){
qp = (nlevel)*(nlevel-1)/2
D1.mat <- matrix(0,ncol=(nlevel),nrow=0)
if (qp==1) D1.mat <- matrix(c(-1,1),ncol=2,nrow=1)
if (qp>1){
for(i in 1 : (nlevel-1)){
w.diag <- diag((nlevel-i))
left.v <- c(rep(0,(i-1)),-1)
left.mat <- matrix(rep(left.v,(nlevel-i)),nrow=(nlevel-i),byrow=TRUE)
w.mat <- cbind(left.mat,w.diag)
D1.mat <- rbind(D1.mat,w.mat)
}
}
}else if(ord==TRUE){
if(nlevel==2){
D1.mat <- matrix(c(-1,1),ncol=2,nrow=1)
}else{
D1.mat <- cbind(0,diag(nlevel-1)) + cbind(-diag(nlevel-1),0)
}
}
return(D1.mat)
}
if(dif==TRUE){
data1 <- data[side==1,]
data2 <- data[side==0,]
model.frame <- model.frame(formula,data=data1)
contr <- rep(list("contr.sum"), ncol(model.frame) - 1)
names(contr) <- colnames(model.frame)[-1]
y <- model.frame[,1]
x1 <- model.matrix(formula, data=data1,contrast=contr)[,-1]
x2 <- model.matrix(formula, data=data2,contrast=contr)[,-1]
X <- x1-x2
}else if (dif==FALSE){
model.frame <- model.frame(formula,data=data)
contr <- rep(list("contr.sum"), ncol(model.frame) - 1)
names(contr) <- colnames(model.frame)[-1]
y <- model.frame[,1]
X <- model.matrix(formula, data=data,contrast=contr)[,-1]
}
lm.fit <- lm(y ~ X)
coef.use <- coef(lm.fit)[-1]
levelIndex <- CreatelevelIndex(fac.level=(fac.level-1),ord.fac=ord.fac,Gorder=Gorder,
indTwo=indTwo, indThree=indThree)
use.ind <- (levelIndex$plus==1)*(levelIndex$dif==0)
Index.use <- levelIndex[use.ind==1,]
Fac.index <- levelIndex[,regexpr("Fac",colnames(levelIndex))>0]
Fac.Ind.use <- Fac.index[use.ind==1,]
Fac.level.useC <- (rep(1,nrow(Fac.Ind.use)) %x% t((fac.level-1))) * Fac.Ind.use
Fac.level.use <- (rep(1,nrow(Fac.Ind.use)) %x% t((fac.level))) * Fac.Ind.use
Index.use$start <- c(1,cumsum(Index.use$length)[-nrow(Index.use)]+1)
Index.use$end <- cumsum(Index.use$length)
if(Gorder==2){
Index.use$seq.order <- c(seq(1:sum(Index.use$order==1)),
seq(1:sum(Index.use$order==2)))
}else if(Gorder==3){
Index.use$seq.order <- c(seq(1:sum(Index.use$order==1)),
seq(1:sum(Index.use$order==2)),
seq(1:sum(Index.use$order==3)))
}
Coef.list <- CreateCoef(coef.use=coef.use,
Index.use=Index.use,
Fac.level.use=Fac.level.useC,
Gorder=Gorder)
if(facCons==TRUE){
n.fac <- length(fac.level)
MainDif <- list()
IntDif <- list()
ThreeDif <- list()
for(z in 1:n.fac){
Maincoef <- Coef.list$One.coef[[z]]
MainD1 <- D1function(nlevel=fac.level[z],ord=ord.fac[z])
MainDif[[z]] <- t(MainD1 %*% Maincoef)
}
ind.use.Two <- (Index.use$order==2)
Index.useTwo <- Index.use[ind.use.Two==1,]
Fac.useTwo <- Fac.Ind.use[ind.use.Two==1,]
Fac.level.useTwo <- Fac.level.use[ind.use.Two==1,]
for(z in 1:nrow(Index.useTwo)){
level.use <- as.numeric(Fac.level.useTwo[z,Fac.useTwo[z, ]==1])
ord.use <- ord.fac[Fac.useTwo[z, ]==1]
coef.int <- c(Coef.list$Two.coef[[z]])
D2A <- D2function(alevel=level.use[1],blevel=level.use[2],
type="A",ordAB=ord.use)
D2B <- D2function(alevel=level.use[1],blevel=level.use[2],
type="B",ordAB=ord.use)
IntDif.A <- D2A %*% coef.int
IntDif.B <- D2B %*% coef.int
IntDif[[z]] <- c(IntDif.A, IntDif.B)
if(Gorder>2){
ind.use.Three <- (Index.use$order==3)
Index.useThree <- Index.use[ind.use.Three==1,]
Fac.useThree <- Fac.Ind.use[ind.use.Three==1,]
Fac.level.useThree <- Fac.level.use[ind.use.Three==1,]
ThreeDif <- list()
for(z in 1:nrow(Index.useThree)){
level.use <- as.numeric(Fac.level.useThree[z,Fac.useThree[z, ]==1])
ord.use <- ord.fac[Fac.useThree[z, ]==1]
D3A <- D3function(alevel=level.use[1],blevel=level.use[2],clevel=level.use[3],
type="A",ordABC=ord.use)
D3B <- D3function(alevel=level.use[1],blevel=level.use[2],clevel=level.use[3],
type="B",ordABC=ord.use)
D3C <- D3function(alevel=level.use[1],blevel=level.use[2],clevel=level.use[3],
type="C",ordABC=ord.use)
coef.three <- c(Coef.list$Three.coef[[z]])
ThreeDif.A <- D3A %*% coef.three
ThreeDif.B <- D3B %*% coef.three
ThreeDif.C <- D3C %*% coef.three
ThreeDif[[z]] <- c(ThreeDif.A, ThreeDif.B, ThreeDif.C)
}
}
}
Main.max <- unlist(lapply(1:length(MainDif),function(x) 1/max(abs(MainDif[[x]]))))
Int.max <- unlist(lapply(1:length(IntDif),function(x) 1/max(abs(IntDif[[x]]))))
if(Gorder > 2){
Three.max <- unlist(lapply(1:length(ThreeDif),function(x) 1/max(abs(ThreeDif[[x]]))))
weight <- c(Main.max,Int.max, Three.max)
}else if(Gorder==2){
weight <- c(Main.max,Int.max)
}
}
else if(facCons==FALSE){
Maincoef <- Coef.list$One.coef[[type.ind]]
MainD1 <- D1function(nlevel=fac.level[type.ind],ord=ord.fac[type.ind])
MainDif <- t(MainD1 %*% Maincoef)
qp <- ncol(MainDif)
onlyOne <- sum(Fac.Ind.use[type.ind])==1
yesTwo <- sum((Index.use$order==2)*(Fac.Ind.use[type.ind]==1))>0
yesThree <- sum((Index.use$order==3)*(Fac.Ind.use[type.ind]==1))>0
if(onlyOne==TRUE){
Dif <- abs(MainDif)
}else if(yesTwo==TRUE){
ind.use.Two <- (Index.use$order==2)*(Fac.Ind.use[type.ind]==1)
Index.useTwo <- Index.use[ind.use.Two==1,]
Fac.useTwo <- Fac.Ind.use[ind.use.Two==1,]
Fac.level.useTwo <- Fac.level.use[ind.use.Two==1,]
IntDif <- matrix(0,nrow=0,ncol=qp)
for(z in 1:nrow(Index.useTwo)){
level.use <- as.numeric(Fac.level.useTwo[z,Fac.useTwo[z, ]==1])
ord.use <- ord.fac[Fac.useTwo[z, ]==1]
if(min(which(Fac.useTwo[z,]==1))==type.ind){
type.d2 <- "A"}else{ type.d2 <- "B" }
D2 <- D2function(alevel=level.use[1],blevel=level.use[2],
type=type.d2,ordAB=ord.use)
coef.int <- c(Coef.list$Two.coef[[Index.useTwo[z,"seq.order"]]])
IntDif.t <- D2 %*% coef.int
IntDif.mat <- matrix(IntDif.t,ncol=qp)
IntDif <- rbind(IntDif, IntDif.mat)
}
if(yesThree==FALSE){
Dif <- abs(rbind(MainDif,IntDif))
}else if(yesThree==TRUE){
ind.use.Three <- (Index.use$order==3)*(Fac.Ind.use[type.ind]==1)
Index.useThree <- Index.use[ind.use.Three==1,]
Fac.useThree <- Fac.Ind.use[ind.use.Three==1,]
Fac.level.useThree <- Fac.level.use[ind.use.Three==1,]
ThreeDif <- matrix(0,nrow=0,ncol=qp)
for(z in 1:nrow(Index.useThree)){
level.use <- as.numeric(Fac.level.useThree[z,Fac.useThree[z, ]==1])
ord.use <- ord.fac[Fac.useThree[z, ]==1]
if(min(which(Fac.useThree[z,]==1))==type.ind){
type.d3 <- "A"
}else if (max(which(Fac.useThree[z,]==1))==type.ind){
type.d3 <- "C"
}else{ type.d3 <- "B"}
D3 <- D3function(alevel=level.use[1],blevel=level.use[2],clevel=level.use[3],
type=type.d3,ordABC=ord.use)
coef.three <- c(Coef.list$Three.coef[[Index.useThree[z,"seq.order"]]])
ThreeDif.t <- D3 %*% coef.three
ThreeDif.mat <- matrix(ThreeDif.t,ncol=qp)
ThreeDif <- rbind(ThreeDif, ThreeDif.mat)
}
Dif <- abs(rbind(MainDif,IntDif,ThreeDif))
}
}
weight <- apply(Dif,2,function(x) 1/max(abs(x)))
}
levelIndex <- CreatelevelIndex(fac.level=(fac.level),ord.fac=ord.fac, Gorder=Gorder,
indTwo=indTwo, indThree=indThree)
use.ind <- (levelIndex$plus==1)*(levelIndex$dif==1) * (levelIndex$order==1)
Index.use <- levelIndex[use.ind==1,]
temp.w <- 1/(sqrt(fac.level[type.ind])*(fac.level[type.ind]+1))
weight.u <- rep(temp.w, times=Index.use$length[type.ind])
output <- list("weight.ols"=weight, "weight.fac"=weight.u)
return(output)
} |
setClass("Exhaustive.model.search.algorithm",
contains = "Model.search.algorithm"
) |
q.mle.emg.estimate <- function(complete.lifespans, censored.lifespans)
{
mle(function(mu, sigma, lambda, Q)
{
qsurvival.nllik("emg", complete.lifespans, censored.lifespans, Q, mu, sigma, lambda)
},
method='L-BFGS-B',
lower=list(mu=8, sigma=0.1, lambda=0.01, Q=0),
upper=list(mu=30, sigma=(max(complete.lifespans) - min(complete.lifespans)),
lambda=10, Q=0.999999),
start=list(mu=median(complete.lifespans),
sigma=sd(complete.lifespans),
lambda=1/mean(complete.lifespans),
Q = 0.5))
} |
dcsd <-
function(object, ...)
{
UseMethod("dcsd")
} |
phylomatic_tree <- function(...) {
.Defunct(msg = "This function is defunct - See ?`taxize-defunct`")
} |
hypothesis.test.result = function(p.value, alpha.warning=0.05, alpha.failure = 0.0001, verbose=FALSE) {
if (p.value < alpha.failure) {
if (verbose)
message(" H0 is highly significantly rejected... check fails!")
return(FALSE)
} else if (p.value < alpha.warning) {
if (verbose)
message(paste0(" H0 signicantly rejected... warning!"))
return("warning")
} else {
if (verbose)
cat(paste0("... ok!"))
return(TRUE)
}
}
sigma.test = function (x, sigma = 1, sigmasq = sigma^2,
alternative = c("two.sided", "less", "greater"),
conf.level = 0.95, ...) {
alternative <- match.arg(alternative)
sigma <- sqrt(sigmasq)
n <- length(x)
xs <- var(x)*(n-1)/sigma^2
out <- list(statistic = c("X-squared" = xs))
class(out) <- "htest"
out$parameter <- c(df = n-1)
minxs <- min(c(xs, 1/xs))
maxxs <- max(c(xs, 1/xs))
PVAL <- pchisq(xs, df = n - 1)
out$p.value <- switch(alternative,
two.sided = 2*min(PVAL, 1 - PVAL),
less = PVAL,
greater = 1 - PVAL)
out$conf.int <- switch(alternative,
two.sided = xs * sigma^2 *
1/c(qchisq(1-(1-conf.level)/2, df = n-1), qchisq((1-conf.level)/2, df
= n-1)),
less = c(0, xs * sigma^2 /
qchisq(1-conf.level, df = n-1)),
greater = c(xs * sigma^2 /
qchisq(conf.level, df = n-1), Inf))
attr(out$conf.int, "conf.level") <- conf.level
out$estimate <- c("var of x" = var(x))
out$null.value <- c(variance = sigma^2)
out$alternative <- alternative
out$method <- "One sample Chi-squared test for variance"
out$data.name <- deparse1(substitute(x))
names(out$estimate) <- paste("var of", out$data.name)
return(out)
}
test.H0.rejected = function(test.expr,p.value,test.name="",
alpha.warning = 0.01,alpha.failure =0.05,
short.message="Fail to reject '{{test_name}}', p.value = {{p_value}}",
warning.message="The null hypothesis from the test '{{test_name}}', should not be rejcected, but I get a fairly low p.value of {{p_value}}.",
failure.message="I couldn't significantly reject the null hypothesis from the test '{{test_name}}', p.value = {{p_value}}",
success.message = "Great, I could significantly reject the null hypothesis from the test '{{test_name}}', p.value = {{p_value}}!",
check.warning=TRUE, ps=get.ps(),stud.env = ps$stud.env, part=NULL,...)
{
if (!missing(test.expr)) {
test.expr = substitute(test.expr)
if (test.name=="") {
test.name = deparse1(test.expr)
}
}
if (missing(p.value)) {
test.res = eval(test.expr, stud.env)
p.value = test.res$p.value
}
if (p.value > alpha.failure) {
add.failure(failure.message,test_name=test.name,p_value=p.value)
return(FALSE)
}
add.success(success.message,test_name=test.name,p_value=p.value)
if (p.value > alpha.warning & check.warning) {
add.warning(warning.message,test_name=test.name,p_value=p.value)
return("warning")
}
return(TRUE)
}
test.H0 = function(test.expr,p.value,test.name="",
alpha.warning = 0.05,alpha.failure =0.001,
short.message,warning.message,failure.message,
success.message = "Great, I could not significantly reject the null hypothesis from the test '{{test_name}}', p.value = {{p_value}}!",
check.warning=TRUE, part=NULL,
ps=get.ps(),stud.env = ps$stud.env,...) {
if (!missing(test.expr)) {
test.expr = substitute(test.expr)
if (test.name=="") {
test.name = deparse1(test.expr)
}
}
if (missing(p.value)) {
test.res = eval(test.expr, stud.env)
p.value = test.res$p.value
}
if (missing(short.message)) {
short.message = paste0("rejected '{{test_name}}' has p.value = {{p_value}}")
}
if (missing(failure.message)) {
failure.message = paste0("The null hypothesis from the test '{{test_name}}' shall hold, but it is rejected at p.value = {{p_value}}")
}
if (missing(warning.message)) {
warning.message = paste0("The null hypothesis from the test '{{test_name}}', should not be rejcected, but I get a fairly low p.value of {{p_value}}.")
}
if (p.value < alpha.failure) {
add.failure(failure.message,test_name=test.name,p_value=p.value,...)
return(FALSE)
}
add.success(success.message,test_name=test.name,p_value=p.value,...)
if (p.value < alpha.warning & check.warning) {
add.warning(warning.message,test_name=test.name,p_value=p.value,...)
return("warning")
}
return(TRUE)
}
test.variance = function(vec, true.val, test = "t.test",short.message,warning.message,failure.message, success.message = "Great, I cannot statistically reject that {{var}} has the desired variance {{vari_sol}}!", ps=get.ps(),stud.env = ps$stud.env,part=NULL,...) {
call.str = as.character(match.call())
var.name = call.str[2]
p.value = sigma.test(vec,sigmasq=true.val)$p.value
if (missing(short.message)) {
short.message ="wrong variance {{var}}: is {{vari_stud}} shall {{vari_sol}}, p.value = {{p_value}}"
}
if (missing(failure.message)) {
failure.message = "{{var}} has wrong variance! \n Your random variable {{var}} has a sample variance of {{vari_stud}} but shall have {{vari_sol}}. A chi-square test tells me that if that null hypothesis were true, it would be very unlikely (p.value={{p_value}}) to get a sample as extreme as yours!"
}
if (missing(warning.message)) {
warning.message = "{{var}} has a suspicious variance! \n Your random variable {{var}} has a sample variance of {{vari_stud}} but shall have {{vari_sol}}. A chi-square test tells me that if that null hypthesis were true, the probability would be just around {{p_value}} to get such an extreme sample variance"
}
test.H0(p.value=p.value,short.message=short.message, warning.message=warning.message, failure.message=failure.message, success.message=success.message,
var = var.name, vari_stud = var(vec), vari_sol=true.val,...)
}
test.mean = function(vec, true.val, test = "t.test", short.message,warning.message,failure.message, success.message = "Great, I cannot statistically reject that {{var}} has the desired mean of {{mean_sol}}!", ps=get.ps(),stud.env = ps$stud.env,part=NULL,...) {
call.str = as.character(match.call())
stopifnot(test=="t.test")
var.name = call.str[2]
p.value = t.test(vec,mu=true.val)$p.value
if (missing(short.message)) {
short.message ="wrong mean {{var}}: is {{mean_stud}} shall {{mean_sol}}, p.value = {{p_value}}"
}
if (missing(failure.message)) {
failure.message = "{{var}} has wrong mean! \n Your random variable {{var}} has a sample mean of {{mean_stud}} but shall have {{mean_sol}}. A t-test tells me that if that null hypothesis were true, it would be very unlikely (p.value={{p_value}}) to get a sample mean as extreme as yours!"
}
if (missing(warning.message)) {
warning.message = "{{var}} has a suspicious mean!\n Your random variable {{var}} has a sample mean of {{mean_stud}} but shall have {{mean_sol}}. A t-test tells me that if that null hypthesis were true, the probability would be just around {{p_value}} to get such an extreme sample mean_"
}
test.H0(p.value=p.value,short.message=short.message, warning.message=warning.message, failure.message=failure.message,success.message=success.message,
var = var.name, mean_stud = mean(vec), mean_sol=true.val,...)
}
test.normality = function(vec,short.message,warning.message,failure.message,ps=get.ps(),stud.env = ps$stud.env, success.message = "Great, I cannot statistically reject that {{var}} is indeed normally distributed!",part=NULL,...) {
call.str = as.character(match.call())
restore.point("test.normality")
var.name=call.str[2]
if (length(vec)>5000)
vec = vec[sample.int(n=length(vec), size=5000)]
p.value = shapiro.test(vec)$p.value
if (missing(short.message)) {
short.message ="{{var}} not normally distributed, p.value = {{p_value}}"
}
if (missing(failure.message)) {
failure.message = "{{var}} looks really not normally distributed.\n A Shapiro-Wilk test rejects normality at an extreme significance level of {{p_value}}."
}
if (missing(warning.message)) {
warning.message = "{{var}} looks not very normally distributed.\n A Shapiro-Wilk test rejects normality at a significance level of {{p_value}}."
}
test.H0(p.value=p.value,short.message=short.message, warning.message=warning.message, failure.message=failure.message,success.message=success.message,
var = var.name,...)
} |
suppressMessages(library(fields))
test.for.zero.flag<- 1
x0<- expand.grid( c(-8,-4,0,20,30), c(10,8,4,0))
Krig( ChicagoO3$x, ChicagoO3$y, cov.function = "Exp.cov", aRange=50)-> out
Krig.Amatrix( out, x=x0)-> A
test.for.zero( A%*%ChicagoO3$y, predict( out, x0),tag="Amatrix vs. predict")
Sigma<- out$sigmahat*Exp.cov( ChicagoO3$x, ChicagoO3$x, aRange=50)
S0<- out$sigmahat*c(Exp.cov( x0, x0, aRange=50))
S1<- out$sigmahat*Exp.cov( out$x, x0, aRange=50)
look<- S0 - t(S1)%*% t(A) - A%*%S1 +
A%*% ( Sigma + diag(out$tauHat.MLE**2/out$weightsM))%*% t(A)
test2<- predictSE( out, x= x0)
test.for.zero( sqrt(diag( look)), test2,tag="Marginal predictSE")
out2<- Krig( ChicagoO3$x, ChicagoO3$y, cov.function = "Exp.cov", aRange=50,
lambda=out$lambda)
test2<- predictSE( out2, x= x0)
test.for.zero( sqrt(diag( look)), test2,tag="Marginal predictSE fixed ")
test<- predictSE( out, x= x0, cov=TRUE)
test.for.zero( look, test,tag="Full covariance predictSE")
set.seed( 333)
sim.Krig( out, x0,M=4e3)-> test
var(test)-> look
predictSE( out, x=x0)-> test2
mean( diag( look)/ test2**2)-> look2
test.for.zero(look2, 1.0, tol=1.5e-2, tag="Marginal standard Cond. Sim.")
predictSE( out, x=x0, cov=TRUE)-> test2
eigen( test2, symmetric=TRUE)-> hold
hold$vectors%*% diag( 1/sqrt( hold$values))%*% t( hold$vectors)-> hold
cor(test%*% hold)-> hold2
abs(hold2[ col(hold2)> row( hold2)])-> hold3
test.for.zero( mean(hold3), 0, relative=FALSE, tol=.02,
tag="Full covariance standard Cond. Sim.")
data( ozone2)
as.image(ozone2$y[16,], x= ozone2$lon.lat, ny=24, nx=20,
na.rm=TRUE)-> dtemp
x<- dtemp$xd
y<- dtemp$z[ dtemp$ind]
weights<- dtemp$weights[ dtemp$ind]
Krig( x, y, Covariance="Matern",
aRange=1.0, smoothness=1.0, weights=weights) -> out
set.seed(234)
ind0<- cbind( sample( 1:20, 5), sample( 1:24, 5))
x0<- cbind( dtemp$x[ind0[,1]], dtemp$y[ind0[,2]])
Krig.Amatrix( out, x=x0)-> A
test.for.zero( A%*%out$yM, predict( out, x0),tag="Amatrix vs. predict")
Sigma<- out$sigmahat*stationary.cov(
out$xM, out$xM, aRange=1.0,smoothness=1.0, Covariance="Matern")
S0<- out$sigmahat*stationary.cov(
x0, x0, aRange=1.0,smoothness=1.0, Covariance="Matern")
S1<- out$sigmahat*stationary.cov(
out$xM, x0, aRange=1.0,smoothness=1.0, Covariance="Matern")
look<- S0 - t(S1)%*% t(A) - A%*%S1 +
A%*% ( Sigma + diag(out$tauHat.MLE**2/out$weightsM) )%*% t(A)
test<- predictSE( out, x0, cov=TRUE)
test.for.zero( c( look), c( test), tag="Weighted case and exact for ozone2 full
cov", tol=1e-8)
cat("all done testing predictSE ", fill=TRUE)
options( echo=TRUE) |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(ggmix)
data("admixed")
names(admixed)
popkin::plot_popkin(admixed$kin_train)
fit <- ggmix(x = admixed$xtrain,
y = admixed$ytrain,
kinship = admixed$kin_train)
names(fit)
class(fit)
plot(fit)
coef(fit, s = c(0.1,0.02))
head(predict(fit, s = 0.01, newx = admixed$xtest))
hdbic <- gic(fit)
class(hdbic)
bicfit <- gic(fit, an = log(length(admixed$ytrain)))
plot(hdbic)
hdbic[["lambda.min"]]
plot(bicfit, ylab = "BIC")
bicfit[["lambda.min"]]
coef(hdbic)
coef(hdbic, type = "nonzero")
predict(hdbic, newx = admixed$xtest)
plot(hdbic, type = "predicted", newx = admixed$xtrain, newy = admixed$ytrain)
plot(hdbic, type = "QQranef", newx = admixed$xtrain, newy = admixed$ytrain)
plot(hdbic, type = "QQresid", newx = admixed$xtrain, newy = admixed$ytrain)
plot(hdbic, type = "Tukey", newx = admixed$xtrain, newy = admixed$ytrain) |
arrow3d <- function(p0=c(0,0,0), p1=c(1,1,1), barblen, s=0.05, theta=pi/6, n=3, ...){
if (!requireNamespace("rgl")) stop("rgl package is required.")
extprod3d <- function (x, y)
{
x = matrix(x, ncol = 3)
y = matrix(y, ncol = 3)
drop(cbind(x[, 2] * y[, 3] - x[, 3] * y[, 2], x[, 3] * y[,
1] - x[, 1] * y[, 3], x[, 1] * y[, 2] - x[, 2] * y[,
1]))
}
phi=seq(0,2*pi,len=n+1)[-1]
lp = sqrt(sum((p1-p0)^2))
if (missing(barblen)) {
barblen <- s*lp
}
cpt=(1-(barblen*cos(theta)))*(p1-p0)
line = rgl::lines3d(c(p0[1],p1[1]),c(p0[2],p1[2]),c(p0[3],p1[3]),...)
rpt = jitter(c(
runif(1,min(p0[1],p1[1]),max(p0[1],p1[1])),
runif(1,min(p0[2],p1[2]),max(p0[2],p1[2])),
runif(1,min(p0[3],p1[3]),max(p0[3],p1[3]))
))
r = extprod3d(p1-p0,rpt)
r = r / sqrt(sum(r^2))
pts = list()
for(i in 1:length(phi)){
ptb=rgl::rotate3d(r,phi[i],(p1-p0)[1],(p1-p0)[2],(p1-p0)[3])
rgl::lines3d(
c(p1[1],cpt[1]+p0[1]+barblen*sin(theta)*ptb[1]),
c(p1[2],cpt[2]+p0[2]+barblen*sin(theta)*ptb[2]),
c(p1[3],cpt[3]+p0[3]+barblen*sin(theta)*ptb[3]),
...
)
}
invisible(line)
} |
checkCall <- function(){
badCall <- lapply(sys.calls(), "[[", 1) %in% c("model.frame.default",
"model.matrix.default")
if (any(badCall))
stop(paste(sys.call(-1)[[1]], "terms are only valid in gnm models."))
} |
get_fiscal <- function(year,
period,
cod,
freq = "Q",
annex = NULL,
power = c("E", "L", "J", "M", "D"),
verbose = FALSE) {
get(
type = "rgf",
an_exercicio = year,
nr_periodo = period,
id_ente = cod,
in_periodicidade = freq,
co_tipo_demonstrativo = if (freq == "Q") "RGF" else "RGF Simplificado",
no_anexo = if (!is.null(annex)) paste0("RGF-Anexo 0", annex) else annex,
co_poder = power,
verbose = verbose
)
} |
get_my_profile <- function(authorization = get_spotify_authorization_code()) {
base_url <- 'https://api.spotify.com/v1/me/'
res <- RETRY('GET', base_url, config(token = authorization), encode = 'json')
stop_for_status(res)
res <- fromJSON(content(res, as = 'text', encoding = 'UTF-8'), flatten = TRUE)
res <- t(unlist(res))
return(res)
}
get_user_profile <- function(user_id, authorization = get_spotify_access_token()) {
base_url <- 'https://api.spotify.com/v1/users'
url <- paste0(base_url, "/", user_id)
params = list(access_token = authorization)
res <- RETRY('GET', url, query = params, encode = 'json')
stop_for_status(res)
res <- fromJSON(content(res, as = 'text', encoding = 'UTF-8'), flatten = TRUE)
res <- fromJSON(content(res, as = 'text', encoding = 'UTF-8'), flatten = TRUE)
res <- t(unlist(res))
return(res)
} |
opt62 <- eventReactive(input$RunOpt62, {
Gprint(MODE_DEBUG, "Opt62\n")
ficout = tempfile()
ficin = GenepopFile()$datapath
out = TRUE
if (is.null(ficin)) {
out = FALSE
} else {
Gprint(MODE_DEBUG, ficin)
datatype = input$ploidy62
setRandomSeed(getSeed(input$randomSeed))
show("spinner")
tryCatch(Fst(ficin, pairs = TRUE, outputFile = ficout, dataType = datatype), error = function(e) {
file.create(ficout)
write(paste("Exeption : ", e$message), file = ficout)
}, finally = hide("spinner"))
file.rename("cmdline.txt", "cmdline.old")
}
data.frame(file = ficout, output = out)
})
output$Opt62out <- renderText({
opt <- opt62()
if (opt$output) {
filePath <- toString(opt$file)
if (file.size(filePath) > 300) {
fileText <- readLines(filePath)
nblig = grep("Number of loci detected", fileText)
fileText <- paste(fileText[(nblig + 2):length(fileText)], collapse = "\n")
shinyjs::enable("downloadOpt62All")
} else {
fileText <- readLines(filePath)
}
} else {
fileText <- "No genepop file found! please upload a file"
}
fileText
})
output$downloadOpt62All <- downloadHandler(filename = function() {
paste("result_opt62_", Sys.Date(), ".txt", sep = "")
}, content = function(con) {
opt <- opt62()
if (opt$output) {
filePath <- toString(opt$file)
fileText <- readLines(filePath)
} else {
fileText <- "No genepop file found! please upload a file"
}
write(fileText, con)
}) |
runModule.get.trait.data <- function(settings) {
if (is.null(settings$meta.analysis)) return(settings)
if (PEcAn.settings::is.MultiSettings(settings)) {
pfts <- list()
pft.names <- character(0)
for (i in seq_along(settings)) {
pfts.i <- settings[[i]]$pfts
if (!is.list(pfts.i)) {
PEcAn.logger::logger.severe("settings[[i]]$pfts is not a list")
}
pft.names.i <- sapply(pfts.i, function(x) x$name)
ind <- which(pft.names.i %in% setdiff(pft.names.i, pft.names))
pfts <- c(pfts, pfts.i[ind])
pft.names <- sapply(pfts, function(x) x$name)
}
PEcAn.logger::logger.info(paste0("Getting trait data for all PFTs listed by any Settings object in the list: ",
paste(pft.names, collapse = ", ")))
modeltype <- settings$model$type
dbfiles <- settings$database$dbfiles
database <- settings$database$bety
forceupdate <- ifelse(is.null(settings$meta.analysis$update), FALSE, settings$meta.analysis$update)
settings$pfts <- PEcAn.DB::get.trait.data(pfts = pfts, modeltype = modeltype, dbfiles = dbfiles, database = database, forceupdate = forceupdate)
return(settings)
} else if (PEcAn.settings::is.Settings(settings)) {
pfts <- settings$pfts
if (!is.list(pfts)) {
PEcAn.logger::logger.severe("settings$pfts is not a list")
}
modeltype <- settings$model$type
dbfiles <- settings$database$dbfiles
database <- settings$database$bety
forceupdate <- ifelse(is.null(settings$meta.analysis$update), FALSE, settings$meta.analysis$update)
settings$pfts <- PEcAn.DB::get.trait.data(pfts = pfts, modeltype = modeltype, dbfiles = dbfiles, database = database, forceupdate = forceupdate)
return(settings)
} else {
stop("runModule.get.trait.data only works with Settings or MultiSettings")
}
} |
pull_genoprobpos <-
function(genoprobs, map=NULL, chr=NULL, pos=NULL, marker=NULL)
{
if(is.null(genoprobs)) stop("genoprobs is NULL")
if(is.character(map) && is.null(chr) && is.null(pos) && is.null(marker)) {
marker <- map
map <- NULL
}
if(!is.null(marker) && (!is.null(map) || !is.null(chr) || !is.null(pos))) {
warning("Provide either {map,chr,pos} or marker, not both; using marker")
}
if(is.null(marker)) {
marker <- find_marker(map, chr, pos)
}
if(length(marker) == 0) stop("marker has length 0")
if(length(marker) > 1) {
marker <- marker[1]
warning("marker should have length 1; using the first value")
}
markers <- dimnames(genoprobs)[[3]]
chr <- rep(names(genoprobs), lapply(markers, length))
index <- unlist(lapply(markers, function(a) seq_along(a)))
markers <- unlist(markers)
wh <- (marker == markers)
n_found <- sum(wh)
if(n_found==0) stop('marker "', marker, '" not found')
if(n_found > 1) stop('marker "', marker, '" appears ', n_found, ' times')
result <- genoprobs[[chr[wh]]][,,index[wh], drop=FALSE]
d <- dim(result)
dn <- dimnames(result)
result <- matrix(result[,,1], nrow=d[1], ncol=d[2])
dimnames(result) <- dn[1:2]
result
} |
values_at <- function(x, values = "meansd") {
force(values)
.values_at <- function(x) {
values <- check_rv(values, x)
if (values == "minmax") {
mv.min <- min(x, na.rm = TRUE)
mv.max <- max(x, na.rm = TRUE)
xl <- c(mv.min, mv.max)
} else if (values == "zeromax") {
mv.max <- max(x, na.rm = TRUE)
xl <- c(0, mv.max)
} else if (values == "meansd") {
mv.mean <- mean(x, na.rm = TRUE)
mv.sd <- stats::sd(x, na.rm = TRUE)
xl <- c(mv.mean - mv.sd, mv.mean, mv.mean + mv.sd)
} else if (values == "all") {
xl <- as.vector(unique(sort(x, na.last = NA)))
} else if (values == "quart") {
xl <- as.vector(stats::quantile(x, na.rm = TRUE))
} else if (values == "quart2") {
xl <- as.vector(stats::quantile(x, na.rm = TRUE))[2:4]
}
if (is.numeric(x)) {
if (is.whole(x)) {
rv <- round(xl, 1)
if (length(unique(rv)) < length(rv))
rv <- unique(round(xl, 2))
} else
rv <- round(xl, 2)
if (length(unique(rv)) < length(rv)) {
rv <- unique(round(xl, 3))
if (length(unique(rv)) < length(rv))
rv <- unique(round(xl, 4))
}
} else {
rv <- xl
}
rv
}
if (missing(x)) {
.values_at
} else {
.values_at(x)
}
}
check_rv <- function(values, x) {
if ((is.factor(x) || is.character(x)) && values != "all") {
message(paste0("Cannot use '", values, "' for factors or character vectors. Defaulting `values` to `all`."))
values <- "all"
}
if (is.numeric(x)) {
mvc <- length(unique(as.vector(stats::quantile(x, na.rm = TRUE))))
if (values %in% c("quart", "quart2") && mvc < 3) {
message("Could not compute quartiles, too small range of variable. Defaulting `values` to `minmax`.")
values <- "minmax"
}
}
values
}
representative_values <- values_at |
bls_request <- function(query, api_key = NA, user_agent = 'http://github.com/groditi/blsR' ){
ua <- httr::user_agent(user_agent)
url <- httr::parse_url(query$url)
if(query$is_complex == FALSE){
if(!is.na(api_key))
url <- httr::modify_url(url, query = c(url$query, list(registrationkey = api_key)))
response <- httr::GET(url, ua)
} else{
if('payload' %in% names(query)){
if('seriesid' %in% names(query$payload)){
if(is.na(api_key))
warning('api_key is required for multiple series requests.')
query$payload[['registrationkey']] <- api_key
}
}
response <- httr::POST(url=url, ua, body=query$payload, encode="json")
}
return(
tryCatch(
.process_response(response),
error = function(e) stop(paste(c('Error processing', url, e), ': '))
)
)
}
.process_response <- function(response){
if(httr::http_type(response) != "application/json"){
stop("http request did not return json", call. = FALSE)
}
json_response <- httr::content(response, simplifyVector=FALSE)
if(json_response$status != 'REQUEST_SUCCEEDED') {
stop(paste(json_response$message, '; '), call. = FALSE)
}
return(json_response$Results)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.