code
stringlengths 1
13.8M
|
---|
setMethod(f="monoisotopicPeaks",
signature=signature(object="MassPeaks"),
definition=function(object, minCor=0.95, tolerance=1e-4,
distance=1.00235, size=3L:10L) {
object[.monoisotopic(x=mass(object), y=intensity(object),
minCor=minCor, tolerance=tolerance,
distance=distance, size=size)]
})
setMethod(f="monoisotopicPeaks",
signature=signature(object="list"),
definition=function(object, ...) {
.stopIfNotIsMassPeaksList(object)
.lapply(object, monoisotopicPeaks, ...)
}) |
logitBvs <- function(y, N, X, model = list(), prior = list(), mcmc = list(),
start = NULL, BVS = TRUE){
starttime <- proc.time()[3]
cl <- match.call()
if (is.null(y) || is.null(X)) stop("need 'y' and 'X' argument")
if (!is.matrix(X)) stop("'X' must be a matrix")
if (!is.vector(y)) stop("'y' must be a vector")
if (!is.vector(N)) stop("'N' must be a vector")
if (any(is.na(X))) stop("NA values in 'X' not allowed")
if (any(is.na(y))) stop("NA values in 'y' not allowed")
if (any(is.na(N))) stop("NA values in 'N' not allowed")
if (any(y < 0)) stop("'y' must be positive")
if (any(N < 0)) stop("'N' must be positive")
if (length(y) != length(N)) stop("'y' and 'N' must have same length")
if (length(y) != nrow(X)) stop("'y' and 'nrow(X)' must have same length")
y <- as.integer(y)
N <- as.integer(N)
if (!all(X[, 1] == 1)) X <- cbind(rep(1, dim(X)[1]), X)
if (any((N - y < 0))) stop("number of trials 'N' < number of binomial counts 'y'")
if (any(N==0)){
iN0 <- which(N==0)
X <- X[-iN0, , drop = FALSE]
y <- y[-iN0]
N <- N[-iN0]
}
n <- length(y)
d <- ncol(X) - 1
W <- X
colnames(W) <- paste("W", seq(0,d), sep = "")
defaultModel <- list(
deltafix = matrix(0,1,d),
gammafix = 0,
ri = FALSE,
clusterID = NULL
)
model <- modifyList(defaultModel, as.list(model))
model$deltafix <- as.matrix(model$deltafix)
model$gammafix <- as.matrix(model$gammafix)
model$ri <- as.integer(model$ri)
model$d <- d
model$family <- "logit"
model$Zl <- seq_len(n)
if (model$d > 0){
if (length(model$deltafix) != model$d || !all(model$deltafix %in% c(0, 1))){
stop("invalid specification of effects subject to selection")
}
} else {
if (length(model$deltafix) != model$d){
stop("invalid 'deltafix' argument")
}
}
if (length(model$gammafix)>1 || !(model$gammafix %in% c(0, 1)) || !(model$ri %in% c(0, 1)))
stop("invalid specification of random intercept selection")
if (model$ri == 1){
if (!is.vector(model$clusterID)){
stop("you must specify a cluster ID for random intercept selection")
}
if (min(model$clusterID) != 1 || !(is.numeric(model$clusterID))){
stop("specify the cluster ID as c = 1,...,C")
}
if (any(N == 0)) model$clusterID <- model$clusterID[-iN0]
if (length(model$clusterID) != n){
stop("'y' and 'clusterID' must have same length")
}
model$Zl <- model$clusterID
nC <- max(model$Zl)
atilde <- rnorm(nC, 0, 1)
H <- matrix(0, n, nC)
for (i in 1:nC){
H[which(model$Zl == i), i] <- 1
}
} else {
atilde <- H <- NULL
}
df <- d + 1
deff <- d + model$ri
dall <- deff + 1
defaultPrior <- list(
slab = "Student",
psi.nu = 5,
m0 = 0,
M0 = 100,
aj0 = rep(0, deff),
V = 5,
w = c(wa0=1,wb0=1),
pi = c(pa0=1,pb0=1)
)
prior <- modifyList(defaultPrior, as.list(prior))
if (!all(prior$aj0 == 0)){
prior$slab <- "Normal"
if (BVS){
warning(simpleWarning(paste(strwrap(paste("BVS is not performed if prior
information on the regression
parameters is available:\n",
"'BVS' was set to FALSE", sep = ""),
exdent = 1), collapse = "\n")))
BVS <- FALSE
}
}
if (prior$slab == "Normal"){
prior$psi.Q <- prior$V
prior$psi.nu <- NULL
} else {
prior$psi.Q <- prior$V*(prior$psi.nu - 1)
}
prior$a0 <- matrix(c(prior$m0, prior$aj0), ncol = 1)
prior$invM0 <- solve(prior$M0)
with(prior,
stopifnot(all(w > 0),
all(pi > 0),
V > 0,
M0 > 0,
psi.Q > 0,
slab %in% c("Student", "Normal")
)
)
if (prior$slab == "Student") with(prior, stopifnot(psi.nu > 0))
if (length(prior$aj0) != deff)
stop("invalid specification of prior means for regression effects")
if (model$ri==1) prior$invB0 <- diag(nC)
defaultMCMC <- list(
M = 8000,
burnin = 2000,
startsel = 1000,
thin = 1,
verbose = 500,
msave = FALSE
)
mcmc <- modifyList(defaultMCMC, as.list(mcmc))
mcmc$M <- as.integer(mcmc$M)
mcmc$burnin <- as.integer(mcmc$burnin)
mcmc$startsel <- as.integer(mcmc$startsel)
mcmc$thin <- as.integer(mcmc$thin)
mcmc$verbose <- as.integer(mcmc$verbose)
mcmc$nmc <- with(mcmc, M + burnin)
with(mcmc,
stopifnot(all(c(M, burnin, startsel, thin, verbose) >= c(1, 0, 1, 1, 0)),
typeof(msave) == "logical")
)
if (typeof(BVS) != "logical") stop("invalid 'BVS' argument")
if (BVS && mcmc$startsel > mcmc$nmc){
warning(simpleWarning(paste("invalid 'BVS' or 'startsel' argument:\n",
"'startsel' was set to ", mcmc$burnin/2, sep = "")))
mcmc$startsel <- mcmc$burnin/2
}
if (BVS && sum(sum(model$deltafix) + sum(model$gammafix)) == sum(model$d + model$ri)){
warning(simpleWarning(paste("invalid 'BVS' argument:\n",
"'BVS' was set to ", FALSE, sep="")))
BVS <- FALSE
}
if (!BVS){
mcmc$startsel <- mcmc$M + mcmc$burnin + 1
model$deltafix <- matrix(1, 1, model$d)
if (model$ri) model$gammafix <- 1
txt.verbose <- ""
mcmc$msave <- FALSE
} else {
txt.verbose <- " with variable selection"
}
if (is.null(start)){
start <- list(alpha = rep(0, model$d + 1))
} else {
start <- list(alpha = start)
}
if(length(start$alpha) != (model$d + 1) || !(is.numeric(c(start$alpha)))){
stop("invalid specification of starting values")
}
start$delta <- start$pdelta <- matrix(1, 1, model$d)
start$psi <- matrix(prior$V, 1, deff)
start$omega <- 1
if(model$ri==1){
start$gamma <- start$pgamma <- matrix(1, 1, model$ri)
start$theta <- rnorm(model$ri, 0, 0.1)
start$pi <- matrix(1, 1, model$ri)
} else {
start$gamma <- start$pgamma <- start$theta <- start$pi <- NULL
}
par.logit <- list(
alpha = start$alpha,
delta = start$delta,
pdelta = start$pdelta,
omega = start$omega,
psi = start$psi,
atilde = atilde,
theta = start$theta,
gamma = start$gamma,
pgamma = start$pgamma,
pi = start$pi)
compmix.bin <- dataug_binom_dRUM1(y, N)
alpha <- matrix(0, mcmc$nmc, model$d + 1)
colnames(alpha) <- paste("alpha", seq(0, model$d), sep = ".")
if (model$d > 0){
pdeltaAlpha <- matrix(0, mcmc$nmc, model$d)
colnames(pdeltaAlpha) <- paste("pdeltaA", seq_len(model$d), sep = ".")
} else {
pdeltaAlpha <- NULL
}
if (model$d > 0 && prior$slab=="Student"){
psiAlpha <- matrix(0, mcmc$nmc, deff)
colnames(psiAlpha) <- paste("psiA", seq_len(deff), sep = ".")
} else {
psiAlpha <- NULL
}
if (mcmc$msave && model$d > 0){
omegaAlpha <- matrix(0, mcmc$nmc, 1)
colnames(omegaAlpha) <- "omega"
deltaAlpha <- matrix(0, mcmc$nmc, model$d)
colnames(deltaAlpha) <- paste("deltaA", seq_len(model$d), sep = ".")
}
if (model$ri == 1){
pgammaAlpha <- thetaAlpha <- matrix(0, mcmc$nmc, model$ri)
colnames(pgammaAlpha) <- "pgammaA"
colnames(thetaAlpha) <- "theta"
ai <- matrix(0, mcmc$nmc, nC)
colnames(ai) <- paste("a", seq_len(nC), sep = ".")
if (mcmc$msave){
piAlpha <- gammaAlpha <- matrix(0, mcmc$nmc, model$ri)
colnames(piAlpha) <- "piA"
colnames(gammaAlpha) <- "gammaA"
} else piAlpha <- gammaAlpha <- NULL
} else {
pgammaAlpha <- thetaAlpha <- ai <- piAlpha <- gammaAlpha <- NULL
}
for (imc in 1:mcmc$nmc){
if (mcmc$verbose > 0){
if (imc == 1) cat(paste("\nMCMC for the binomial logit model", txt.verbose, ":\n\n", sep = ""))
if (is.element(imc, c(1:5, 10, 20, 50, 100, 200, 500))){
cat("it =", imc, "/--- duration of MCMC so far:",
round(timediff <- proc.time()[3] - starttime, 2), "sec., expected time to end:",
round((timediff/(imc - 1) * mcmc$nmc - timediff)/60, 2), " min. \n")
flush.console()
} else if (imc %% mcmc$verbose == 0 && imc < mcmc$nmc){
cat("it =", imc, "/--- duration of MCMC so far:",
round(timediff <- proc.time()[3] - starttime, 2), "sec., expected time to end:",
round((timediff/(imc - 1) * mcmc$nmc - timediff)/60, 2), " min. \n")
flush.console()
}
else if (imc == mcmc$nmc) {
cat("it =", imc, "/--- duration of MCMC (total):",
round(timediff <- proc.time()[3] - starttime, 2), "sec. \n \n")
flush.console()
}
}
if (imc == (mcmc$burnin + 1)) starttimeM <- proc.time()[3]
par.logit <- select_logit(y, N, W, H, compmix.bin, model, prior, mcmc, par.logit, imc)
alpha[imc,] <- par.logit$alpha
if (model$d > 0){
pdeltaAlpha[imc,] <- par.logit$pdelta
if (prior$slab=="Student") psiAlpha[imc,] <- par.logit$psi
}
if (mcmc$msave && model$d > 0){
omegaAlpha[imc,] <- par.logit$omega
deltaAlpha[imc,] <- par.logit$delta
}
if (model$ri == 1){
pgammaAlpha[imc] <- par.logit$pgamma
thetaAlpha[imc] <- par.logit$theta
ai[imc,] <- t(par.logit$atilde*par.logit$theta)
if (mcmc$msave){
piAlpha[imc] <- par.logit$pi
gammaAlpha[imc] <- par.logit$gamma
}
}
}
finish <- proc.time()[3]
durT <- finish - starttime
durM <- finish - starttimeM
dur <- list(total = durT, durM = durM)
samplesL <- if (mcmc$msave){
list(alpha = alpha, pdeltaAlpha = pdeltaAlpha, psiAlpha = psiAlpha,
omegaAlpha = omegaAlpha, deltaAlpha = deltaAlpha,
thetaAlpha = thetaAlpha, pgammaAlpha = pgammaAlpha, ai = ai,
piAlpha = piAlpha, gammaAlpha = gammaAlpha)
} else {
list(alpha = alpha, pdeltaAlpha = pdeltaAlpha, psiAlpha = psiAlpha,
thetaAlpha = thetaAlpha, pgammaAlpha = pgammaAlpha, ai = ai)
}
ret <- list(samplesL = samplesL, data = list(y = y, N = N, X = W),
model.logit = model, mcmc=mcmc, prior.logit = prior,
dur = dur, BVS = BVS, start = start, family = model$family,
call = cl)
class(ret) <- "pogit"
return(ret)
}
|
setup.model <-
function(model,nocc,mixtures=1)
{
fdir=system.file(package="RMark")
fdir=file.path(fdir,"models.txt")
model_definitions=read.delim(fdir,header=TRUE,
colClasses=c("numeric","character","character",rep("logical",4),rep("numeric",3),"logical"))
model_def=model_definitions[model_definitions$model==model,]
if(nrow(model_def)==0)
stop("Invalid type of model = ",model," Valid types are\n", paste(model_definitions$model,collapse="\n"))
if(mixtures==1)
model_def$mixtures=model_def$default.mixtures
else
model_def$mixtures=mixtures
model_def$default.mixtures=NULL
model_def$nocc=nocc/model_def$divisor
if(model_def$derived)
{
fdir=system.file(package="RMark")
fdir=file.path(fdir,"DerivedPar.txt")
deriv_pars=read.delim(fdir,header=TRUE, colClasses=c("numeric","character"))
model_def$derived_labels=list(deriv_pars$dpar_label[deriv_pars$MarkNumber==model_def$MarkNumber])
}
return(as.list(model_def))
} |
context("Constructor Objects")
library(rai)
checkPosition = function(object, value) {
expect_equal(object$state()$position, value)
}
checkPrevPosition = function(object, value) {
expect_equal(object$state()$prevPosition, value)
}
rawSource = makeRawSource(10)
test_that("extracting/dropping features works", {
checkPosition(rawSource, 10)
expect_equal(rawSource$feature(), 10)
checkPosition(rawSource, 9)
checkPrevPosition(rawSource, 10)
rawSource$dropLastFeature()
expect_true(is.na(rawSource$state()$active[11]))
expect_equal(rawSource$feature(), 9)
checkPosition(rawSource, 8)
checkPrevPosition(rawSource, 9)
rawSource$ud_pass()
checkPosition(rawSource, 9)
expect_true(is.na(rawSource$state()$prevPosition))
})
TheModelFeatures = list(1,2,3,4,5,6)
scavSource = makeLocalScavenger(TheModelFeatures, "test")
test_that("scavenger tests interactions", {
checkPosition(scavSource, 6)
expect_equal(scavSource$feature(), list(6,6))
checkPosition(scavSource, 5)
checkPrevPosition(scavSource, 6)
scavSource$dropLastFeature()
expect_true(is.na(scavSource$state()$active[7]))
expect_equal(scavSource$feature(), list(5, 6))
checkPosition(scavSource, 4)
checkPrevPosition(scavSource, 5)
scavSource$ud_pass()
checkPosition(scavSource, 5)
expect_true(is.na(scavSource$state()$prevPosition))
}) |
track_alignments <- function(track_data, assembly) {
type <- "AlignmentsTrack"
name <- get_name(track_data)
assembly_name <- get_assembly_name(assembly)
track_id <- stringr::str_c(assembly_name, "_", name)
adapter <- get_alignment_adapter(track_data, assembly)
as.character(
stringr::str_glue(
"{{",
'"type": "{type}", ',
'"name": "{name}", ',
'"assemblyNames": ["{assembly_name}"], ',
'"trackId": "{track_id}", ',
"{adapter} ",
"}}"
)
)
}
get_alignment_adapter <- function(track_data, assembly) {
track_non_gz <- strip_gz(track_data)
if (stringr::str_ends(track_non_gz, ".bam")) {
index <- stringr::str_c(track_data, ".bai")
as.character(
stringr::str_glue(
'"adapter": {{ ',
'"type": "BamAdapter", ',
'"bamLocation": {{ ',
'"uri": "{track_data}" ',
"}}, ",
'"index": {{ "location": {{ "uri": "{index}" }} }} ',
"}}"
)
)
} else if (stringr::str_ends(track_non_gz, ".cram")) {
index <- stringr::str_c(track_data, ".crai")
sequence_adapter <- get_assembly_adapter(assembly)
as.character(
stringr::str_glue(
'"adapter": {{ ',
'"type": "CramAdapter", ',
'"cramLocation": {{ ',
'"uri": "{track_data}" ',
"}}, ",
'"craiLocation": {{ "uri": "{index}" }}, ',
'"sequenceAdapter": {sequence_adapter} ',
"}}"
)
)
} else {
stop("alignment data must be either BAM or CRAM")
}
} |
CGGPpred <- function(CGGP, xp, theta=NULL, outdims=NULL) {
if (!inherits(CGGP, "CGGP")) {
stop("First argument to CGGP must be an CGGP object")
}
if (is.null(CGGP$supplemented)) {
stop("You must run CGGPfit on CGGP object before using CGGPpredict")
}
if (CGGP$supplemented && (is.null(CGGP[["Y"]]) || length(CGGP$Y)==0)) {
return(CGGP_internal_predwithonlysupp(CGGP=CGGP, xp=xp, theta=theta, outdims=outdims))
}
predgroupsize <- 100
if (nrow(xp) >= predgroupsize*2) {
ngroups <- floor(nrow(xp) / predgroupsize)
list_preds <- lapply(1:ngroups,
function(i) {
inds.i <- if (i < ngroups) {1:predgroupsize + (i-1)*predgroupsize} else {((i-1)*predgroupsize+1):(nrow(xp))}
CGGPpred(CGGP=CGGP,
xp=xp[inds.i, , drop=FALSE],
theta=theta,
outdims=outdims)
})
outlist <- list(mean=do.call(rbind, lapply(list_preds, function(ll) ll$mean)),
var= do.call(rbind, lapply(list_preds, function(ll) ll$var ))
)
if (nrow(outlist$mean)!=nrow(xp) || nrow(outlist$var)!=nrow(xp)) {
stop("Error with CGGPpred predicting many points")
}
return(outlist)
}
if (!is.null(theta) && length(theta)!=length(CGGP$thetaMAP)) {stop("Theta is wrong length")}
if (!is.null(theta) && all(theta==CGGP$thetaMAP)) {
theta <- NULL
}
if (is.null(theta)) {
thetaMAP <- CGGP$thetaMAP
recalculate_pw <- FALSE
} else {
thetaMAP <- theta
rm(theta)
recalculate_pw <- TRUE
}
separateoutputparameterdimensions <- is.matrix(CGGP$thetaMAP)
nopd <- if (separateoutputparameterdimensions) {
ncol(CGGP$y)
} else {
1
}
if (nopd > 1) {
meanall2 <- matrix(0, nrow(xp), ncol=ncol(CGGP$Y))
tempvarall <- matrix(0, nrow(xp), ncol=ncol(CGGP$Y))
}
if (!is.null(outdims) && nopd==1) {
stop("outdims can only be given when multiple outputs and separate correlation parameters")
}
opd_values <- if (is.null(outdims)) {1:nopd} else {outdims}
for (opdlcv in opd_values) {
thetaMAP.thisloop <- if (nopd==1) thetaMAP else thetaMAP[, opdlcv]
if (!recalculate_pw) {
pw.thisloop <- if (nopd==1) CGGP$pw else CGGP$pw[,opdlcv]
sigma2MAP.thisloop <- CGGP$sigma2MAP
cholS.thisloop <- if (nopd==1) CGGP$cholSs else CGGP$cholSs[[opdlcv]]
} else {
y.thisloop <- if (nopd==1) CGGP$y else CGGP$y[,opdlcv]
lik_stuff <- CGGP_internal_calc_cholS_lS_sigma2_pw(CGGP=CGGP,
y=y.thisloop,
theta=thetaMAP.thisloop
)
cholS.thisloop = lik_stuff$cholS
sigma2MAP.thisloop <- lik_stuff$sigma2
pw.thisloop = lik_stuff$pw
sigma2MAP.thisloop <- as.vector(sigma2MAP.thisloop)
rm(y.thisloop)
}
mu.thisloop <- if (nopd==1) CGGP$mu else CGGP$mu[opdlcv]
Cp = matrix(0,dim(xp)[1],CGGP$ss)
GGGG = list(matrix(1,dim(xp)[1],length(CGGP$xb)),CGGP$d)
for (dimlcv in 1:CGGP$d) {
V = CGGP$CorrMat(xp[,dimlcv], CGGP$xb[1:CGGP$sizest[max(CGGP$uo[,dimlcv])]],
thetaMAP.thisloop[(dimlcv-1)*CGGP$numpara+1:CGGP$numpara],
returnlogs=TRUE)
GGGG[[dimlcv]] = exp(V)
Cp = Cp+V[,CGGP$designindex[,dimlcv]]
}
Cp = exp(Cp)
ME_t = matrix(1,dim(xp)[1],1)
MSE_v = list(matrix(0,dim(xp)[1],2),(CGGP$d+1)*(CGGP$maxlevel+1))
Q = max(CGGP$uo[1:CGGP$uoCOUNT,])
for (dimlcv in 1:CGGP$d) {
for (levellcv in 1:max(CGGP$uo[1:CGGP$uoCOUNT,dimlcv])) {
Q = max(CGGP$uo[1:CGGP$uoCOUNT,])
gg = (dimlcv-1)*Q
INDSN = 1:CGGP$sizest[levellcv]
INDSN = INDSN[sort(CGGP$xb[1:CGGP$sizest[levellcv]],
index.return = TRUE)$ix]
MSE_v[[(dimlcv)*CGGP$maxlevel+levellcv]] =
CGGP_internal_postvarmatcalc_fromGMat(GGGG[[dimlcv]],
c(),
as.matrix(
cholS.thisloop[[gg+levellcv]]
),
c(),
INDSN,
CGGP$numpara,
returndiag=TRUE)
}
}
for (blocklcv in 1:CGGP$uoCOUNT) {
if(abs(CGGP$w[blocklcv]) > 0.5){
ME_s = matrix(1,nrow=dim(xp)[1],1)
for (dimlcv in 1:CGGP$d) {
levelnow = CGGP$uo[blocklcv,dimlcv]
ME_s = ME_s*MSE_v[[(dimlcv)*CGGP$maxlevel+levelnow]]
}
ME_t = ME_t-CGGP$w[blocklcv]*ME_s
}
}
if (!CGGP$supplemented) {
if(is.vector(pw.thisloop)){
if (nopd == 1) {
mean = (mu.thisloop+Cp%*%pw.thisloop)
var=sigma2MAP.thisloop*ME_t
}
if (nopd > 1) {
meanall2[,opdlcv] <- c(Cp%*%pw.thisloop)
tempM <- diag(nopd)
tempM[-opdlcv,] <- 0
tempsigma2.thisloop <- sigma2MAP.thisloop
tempsigma2.thisloop[-opdlcv] <- 0
tempvar <- (as.vector(ME_t)%*%t(diag(t(tempM)%*%diag(tempsigma2.thisloop)%*%(tempM))))
}
}else{
if(length(sigma2MAP.thisloop)==1){
stop("When is it a matrix but sigma2MAP a scalar???")
}else{
mean = (matrix(rep(mu.thisloop,each=dim(xp)[1]), ncol=ncol(CGGP$Y), byrow=FALSE) +
(Cp%*%pw.thisloop))
var=as.vector(ME_t)%*%t(sigma2MAP.thisloop)
}
}
} else {
if (!recalculate_pw) {
pw_uppad.thisloop <- if (nopd==1) CGGP$pw_uppad else CGGP$pw_uppad[,opdlcv]
supppw.thisloop <- if (nopd==1) CGGP$supppw else CGGP$supppw[,opdlcv]
Sti.thisloop <- if (nopd==1) CGGP$Sti else CGGP$Sti[,,opdlcv]
} else {
stop("Give theta in not implemented in CGGPpred. Need to fix sigma2MAP here too!")
}
Cps = matrix(0,dim(xp)[1],dim(CGGP$Xs)[1])
GGGG2 = list(matrix(0,nrow=dim(xp)[1],ncol=dim(CGGP$Xs)[1]),CGGP$d)
for (dimlcv in 1:CGGP$d) {
V = CGGP$CorrMat(xp[,dimlcv],
CGGP$Xs[,dimlcv],
thetaMAP.thisloop[(dimlcv-1)*CGGP$numpara+1:CGGP$numpara],
returnlogs=TRUE)
Cps = Cps+V
V = CGGP$CorrMat(CGGP$Xs[,dimlcv],
CGGP$xb[1:CGGP$sizest[max(CGGP$uo[,dimlcv])]],
thetaMAP.thisloop[(dimlcv-1)*CGGP$numpara+1:CGGP$numpara],
returnlogs=TRUE)
GGGG2[[dimlcv]] = exp(V)
}
Cps = exp(Cps)
yhatp = Cp%*%pw_uppad.thisloop + Cps%*%supppw.thisloop
MSE_ps = matrix(NaN,nrow=dim(CGGP$Xs)[1]*dim(xp)[1],ncol=(CGGP$d)*(CGGP$maxlevel))
Q = max(CGGP$uo[1:CGGP$uoCOUNT,])
for (dimlcv in 1:CGGP$d) {
gg = (dimlcv-1)*Q
for (levellcv in 1:max(CGGP$uo[1:CGGP$uoCOUNT,dimlcv])) {
INDSN = 1:CGGP$sizest[levellcv]
INDSN = INDSN[sort(CGGP$xb[1:CGGP$sizest[levellcv]],index.return = TRUE)$ix]
REEALL= CGGP_internal_postvarmatcalc_fromGMat_asym(GGGG[[dimlcv]],
GGGG2[[dimlcv]],
as.matrix(cholS.thisloop[[gg+levellcv]]),
INDSN)
MSE_ps[,(dimlcv-1)*CGGP$maxlevel+levellcv] = as.vector(REEALL)
}
}
Cps2 = as.vector(Cps)
rcpp_fastmatclcr(CGGP$uo[1:CGGP$uoCOUNT,], CGGP$w[1:CGGP$uoCOUNT], MSE_ps, Cps2,CGGP$maxlevel)
Cps = matrix(Cps2,ncol=dim(CGGP$Xs)[1] , byrow = FALSE)
ME_adj = rowSums((Cps%*%Sti.thisloop)*Cps)
ME_t = ME_t-ME_adj
if(is.vector(pw.thisloop)){
if (nopd == 1) {
mean = (CGGP$mu+ yhatp)
if (length(CGGP$sigma2MAP)>1) {warning("If this happens, you should fix var here")}
var=CGGP$sigma2MAP[1]*ME_t
}
if (nopd > 1) {
meanall2[,opdlcv] <- yhatp
leftvar <- if (is.null(CGGP$leftover_variance)) {0} else {CGGP$leftover_variance}
tempM <- diag(nopd)
tempM[-opdlcv,] <- 0
tempsigma2.thisloop <- sigma2MAP.thisloop
tempsigma2.thisloop[-opdlcv] <- 0
tempvar <- (as.vector(ME_t)%*%t(
leftvar + diag(t(tempM)%*%diag(tempsigma2.thisloop)%*%(tempM))))
}
}else{
if(length(CGGP$sigma2MAP)==1){
stop("This should never happen
}else{
leftvar <- if (is.null(CGGP$leftover_variance)) {0} else {CGGP$leftover_variance}
mean = matrix(rep(CGGP$mu,each=dim(xp)[1]), ncol=ncol(CGGP$Y), byrow=FALSE)+ yhatp
var=as.vector(ME_t)%*%t(leftvar+CGGP$sigma2MAP)
}
}
}
rm(Cp,ME_t, MSE_v, V)
if (nopd > 1) {tempvarall <- tempvarall + tempvar}
}
if (nopd > 1) {meanall2 <- sweep(meanall2, 2, CGGP$mu, `+`)}
if (nopd > 1) {
GP <- list(mean=meanall2, var=tempvarall)
} else {
GP <- list(mean=mean, var=var)
}
GP$var <- pmax(GP$var, .Machine$double.eps)
return(GP)
}
CGGP_internal_MSEpredcalc <- function(xp,xl,theta,CorrMat) {
S = CorrMat(xl, xl, theta)
n = length(xl)
cholS = chol(S)
Cp = CorrMat(xp, xl, theta)
CiCp = backsolve(cholS,backsolve(cholS,t(Cp), transpose = TRUE))
MSE_val = 1 - rowSums(t(CiCp)*((Cp)))
return(MSE_val)
}
CGGP_internal_postvarmatcalc_fromGMat_asym <- function(GMat1,GMat2,cholS,INDSN) {
CoinvC1o = backsolve(cholS,
backsolve(cholS,t(GMat1[,INDSN]), transpose = TRUE))
Sigma_mat = (t(CoinvC1o)%*%(t(GMat2[,INDSN])))
return(Sigma_mat)
} |
countryname <- function(sourcevar, destination = 'cldr.short.en', warn = TRUE) {
out <- countrycode(sourcevar = sourcevar,
origin = 'country.name.alt',
destination = 'country.name.en',
custom_dict = countrycode::countryname_dict,
warn = FALSE)
idx <- is.na(out)
out[idx] <- countrycode(sourcevar = sourcevar[idx],
origin = 'country.name.en',
destination = 'country.name.en',
warn = warn)
if (destination != 'country.name.en') {
out <- countrycode(sourcevar = out,
origin = 'country.name.en',
destination = destination,
custom_dict = countrycode::codelist,
nomatch = NULL,
warn = warn)
}
return(out)
} |
plot.pcoxsurvfit <- function(x, ..., type = c("surv", "cumhaz"), lsize = 0.3,
lcol = "black", compare = FALSE) {
type <- match.arg(type)
if (inherits(x, "pcoxbasehaz")){
cumhaz <- x$hazard
} else {
cumhaz <- x$cumhaz
}
surv <- x$surv
time <- x$time
plot_df <- data.frame(id = 1, time = time, surv = surv, cumhaz = cumhaz)
if (NCOL(surv) > 1){
nindivs <- NCOL(surv)
individ <- as.factor(rep(1:nindivs, each = length(time)))
surv <- as.vector(surv)
cumhaz <- as.vector(cumhaz)
time <- rep(time, nindivs)
plot_df <- data.frame(id = individ, time = time, surv = surv, cumhaz = cumhaz)
}
id <- NULL
p0 <- (ggplot(plot_df, aes(x = time, group = id), colour = "grey")
+ labs(x = "Time")
+ theme_bw()
+ theme(panel.spacing = grid::unit(0,"lines"), legend.position = "bottom")
)
if (type == "surv"){
p1 <- p0 + geom_step(aes(y = surv), size = lsize, colour=lcol) + labs(y = "Survival probability")
if (compare){
p1 <- p0 + geom_step(aes(y = surv, col = "pcoxtime"), size = lsize) + labs(y = "Survival probability")
}
} else {
p1 <- p0 + geom_step(aes(y = cumhaz), size = lsize) + labs(y = "Cumulative hazard")
if (compare){
p1 <- p0 + geom_step(aes(y = cumhaz, col = "pcoxtime"), size = lsize) + labs(y = "Cumulative hazard")
}
}
return(p1)
}
plot.pcoxtimecv <- function(x, ..., type = c("cve", "fit"), xvar = c("lambda", "l1"), show_nzero = FALSE, seed = 1234, geom=c("point","line"), g.size = 0.2, g.col = "red", bar.col = g.col, scales = "free_x", show_min_cve = TRUE) {
geom <- match.arg(geom)
gm <- getExportedValue("ggplot2", paste0("geom_",geom))
mcall <- match.call()
type <- match.arg(type)
set.seed(seed)
lambda <- cvm <- cvlo <- cvup <- NULL
lambda.min <- lambda.1se <- NULL
estimate <- term <- l1_norm <- NULL
xvar_breaks <- nzero <- NULL
sec_axisLabs <- function(var){
lamb_tmp_df <- beta_df[, c(var, "nzero")]
lamb_tmp_df <- lamb_tmp_df[!duplicated(lamb_tmp_df[[var]]), ]
lamb_tmp_df <- lamb_tmp_df[order(-lamb_tmp_df$nzero),]
if (var=="lambda"){
lambdavals <- log(lamb_tmp_df[[var]])
} else {
lambdavals <- lamb_tmp_df[[var]]
}
nzero_breaks <- base::pretty(lambdavals, 5)
closest_lambda_breaks <- unlist(lapply(nzero_breaks, function(x)which.min(abs(lambdavals - x))))
closest_lambda_to_breaks <- lambdavals[closest_lambda_breaks]
nzero_labels <- lamb_tmp_df[lambdavals %in% closest_lambda_to_breaks, ]
return(data.frame(xvar_breaks = nzero_labels[[var]], nzero = nzero_labels$nzero))
}
if (type == "cve") {
cvm_df <- x$dfs$cvm_df
min_df <- x$dfs$min_metrics_df
if (length(unique(min_df$alpha))==1) show_min_cve <- FALSE
cvm_df$optimal <- ifelse(cvm_df$alpha==x$alpha.optimal & show_min_cve, " (Min.~CV-PLD)", "")
min_df$optimal <- ifelse(min_df$alpha==x$alpha.optimal & show_min_cve, " (Min.~CV-PLD)", "")
cvm_df$alpha <- as.factor(cvm_df$alpha)
cvm_df$alpha_labels <- paste0("alpha== ", cvm_df$alpha, cvm_df$optimal)
min_df$alpha_labels <- paste0("alpha== ", min_df$alpha, min_df$optimal)
cvm_plot <- (ggplot(cvm_df, aes(x = log(lambda), y = cvm))
+ gm(colour = g.col, size = g.size)
+ geom_errorbar(aes(ymin = cvlo, ymax = cvup)
, width = 0.01
, colour = bar.col
, alpha = 0.4
)
+ facet_wrap(~alpha_labels, labeller = label_parsed, scales = scales)
+ geom_vline(data = min_df, aes(xintercept = log(lambda.min)), lty = 2, size = 0.2)
+ geom_vline(data = min_df, aes(xintercept = log(lambda.1se)), lty = 2, size = 0.2)
+ labs(x = expression(log(lambda)), y = "Partial Likelihood Deviance")
)
if (show_nzero){
beta_df <- x$dfs$beta
lamb_tmp_df <- beta_df[, c("lambda", "alpha", "nzero")]
lamb_tmp_df <- lamb_tmp_df[!duplicated(lamb_tmp_df[c("lambda","alpha", "nzero")]), ]
labels_df <- lapply(split(lamb_tmp_df, lamb_tmp_df$alpha), function(dd){
df <- sec_axisLabs("lambda")
df$alpha <- unique(dd$alpha)
df$optimal <- ifelse(df$alpha==x$alpha.optimal & show_min_cve, " (Min.~CV-PLD)", "")
df$alpha_labels <- paste0("alpha== ", df$alpha, df$optimal)
return(df)
})
labels_df <- do.call("rbind", labels_df)
cvm_plot <- (cvm_plot
+ geom_text(data = labels_df, aes(y = Inf, x = log(xvar_breaks), label = nzero)
, hjust = 0, vjust = 1
)
)
}
return(cvm_plot)
} else {
xvar <- match.arg(xvar)
beta_df <- x$fit$beta
facet <- FALSE
if (is.null(beta_df)){
facet <- TRUE
beta_df = x$dfs$beta
if (is.null(beta_df))stop("Run pcoxtimecv with refit = TRUE to plot coefficients!!!")
rand_fold <- sample(unique(beta_df$fold), 1)
beta_df <- beta_df[beta_df$fold==rand_fold, ]
}
base_plot <- (ggplot(beta_df, aes(y = estimate, group = term, colour = term))
+ scale_colour_viridis_d(option = "inferno")
+ labs(y = "Coefficient estimate", colour = "Predictor")
+ theme(legend.position = "none")
)
if (xvar == "lambda"){
coef_plot <- (base_plot + geom_line(aes(x = log(lambda)))
+ scale_x_continuous(sec.axis = sec_axis(~.
, breaks = log(sec_axisLabs("lambda")$xvar_breaks)
, labels = sec_axisLabs("lambda")$nzero
)
)
+ labs(x = expression(log(lambda)))
)
if (!facet){
coef_plot <- (coef_plot
+ geom_vline(xintercept = log(x$lambda.min), lty = 2, size = 0.2)
+ geom_vline(xintercept = log(x$lambda.1se), lty = 2, size = 0.2)
)
}
} else {
coef_plot <- (base_plot
+ geom_line(aes(x = l1_norm))
+ scale_x_continuous(sec.axis = sec_axis(~.
, breaks = sec_axisLabs("l1_norm")$xvar_breaks
, labels = sec_axisLabs("l1_norm")$nzero
)
)
+ labs(x = "L1 Norm")
)
}
if (facet) {
coef_plot <- coef_plot + facet_wrap(~alpha, scales = scales)
message("These are CV coefficient plots. \nSet refit = TRUE to plot estimates based on whole dataset")
}
attr(coef_plot, "call") <- mcall
return(coef_plot)
}
}
plot.Score <- function(x, ..., type = c("roc", "auc", "brier"), pos = 0.3){
type <- match.arg(type)
if (type == "roc"){
df <- x$ROC$plotframe
df$times <- as.factor(df$times)
FPR <- TPR <- model <- AUC <- lower <- upper <- Brier <- NULL
model_cols <- unique(df$model)
p1 <- (ggplot(df, aes(x = FPR, y = TPR, color = model))
+ geom_line(size = 1)
+ geom_abline(size = 1, colour = "grey")
+ facet_wrap(~times)
+ labs(x = "1-Specificity", y = "Sensitivity", colour = "Time")
+ scale_color_manual(breaks = model_cols
, values = rainbow(n = length(model_cols))
)
+ theme(legend.position = "right")
)
} else if (type == "auc"){
df <- x$AUC$score
model_cols <- unique(df$model)
df$times <- as.factor(df$times)
p1 <- (ggplot(df, aes(x = times, y = AUC, group = model, colour = model))
+ geom_point(position = position_dodge(pos))
+ geom_pointrange(aes(ymin = lower, ymax = upper, colour = model), position = position_dodge(pos))
+ scale_color_manual(breaks = model_cols
, values = rainbow(n = length(model_cols))
)
+ labs(x = "Time", y = "AUC", colour = "Model")
+ theme(legend.position = "right")
)
} else {
df <- x$Brier$score
df$times <- as.factor(df$times)
model_cols <- unique(df$model)
p1 <- (ggplot(df, aes(x = times, y = Brier, group = model, colour = model))
+ geom_point(position = position_dodge(pos))
+ geom_pointrange(aes(ymin = lower, ymax = upper, colour = model), position = position_dodge(pos))
+ scale_color_manual(breaks = model_cols
, values = rainbow(n = length(model_cols))
)
+ labs(x = "Time", y = "Brier", colour = "Model")
+ theme(legend.position = "right")
)
}
return(p1)
}
plot.varimp <- function(x, ..., pos = 0.5, drop_zero = TRUE){
xsign <- x$sign
if (!is.null(xsign)) {
x$sign <- ifelse(xsign==1, "+", ifelse(xsign==-1, "-", "0"))
} else {
xsign <- 1
}
est <- attr(x, "estimate")
if (est=="quantile") {
x[ "Overall"] <- x$estimate
}
x <- x[order(x$Overall), ]
if (drop_zero){
x <- x[x$Overall!=0, ]
x <- droplevels(x)
}
Overall <- NULL
lower <- NULL
upper <- NULL
nsigns <- unique(xsign)
pos <- position_dodge(width = pos)
p0 <- ggplot(x, aes(x = reorder(terms, Overall), y = Overall))
if (est=="quantile") {
if (length(nsigns)>1) {
p0 <- (p0
+ geom_point(aes(shape=sign), position = pos)
+ scale_shape_manual(name = "Sign", values=c(1,16, 15))
+ geom_linerange(aes(ymin=lower, ymax=upper, lty = sign), position = pos)
+ labs(linetype = "Sign")
)
} else {
p0 <- (p0
+ geom_point(position = pos)
+ geom_linerange(aes(ymin=lower, ymax=upper), position=pos)
)
}
} else {
if (length(nsigns)>1) {
p0 <- (p0
+ geom_point(aes(shape=sign), position = pos)
+ scale_shape_manual(name = "Sign", values=c(1,16, 15))
+ geom_linerange(aes(ymin = 0, ymax = Overall, lty = sign), position = pos)
+ labs(linetype = "Sign")
)
} else {
p0 <- (p0
+ geom_point(position = pos)
+ geom_linerange(aes(ymin=0, ymax=Overall), position=pos)
)
}
}
p1 <- (p0
+ scale_colour_viridis_d(option = "inferno")
+ labs(x = "", y = "Importance")
+ coord_flip(clip = "off", expand = TRUE)
+ theme_minimal()
)
return(p1)
} |
VeneerRunSource<-function(StartDate=NULL,EndDate=NULL,InputSet=NULL,baseURL="http://localhost:9876")
{
X<-list()
if(!is.null(StartDate)) X[["StartDate"]]<-StartDate
if(!is.null(EndDate)) X[["EndDate"]]<-EndDate
if(!is.null(InputSet)) X[["SelectedInputSet"]]<-InputSet
X<-jsonlite::toJSON(X,auto_unbox = TRUE)
A<-httr::POST(paste0(baseURL,"/runs"),body=X,httr::content_type_json())
if(substr(rawToChar(A[[6]]),3,9)=="Message"){
return(substr(strsplit(rawToChar(A[[6]]),",")[[1]][1],13,1000))
}else{
return("Run Successful")
}
}
VeneerSetFunction<-function(Name,Expression,baseURL="http://localhost:9876")
{
X<-list("Expression"=as.character(Expression),"Name"=paste0("$",Name))
X<-jsonlite::toJSON(X,auto_unbox = TRUE)
httr::PUT(paste0(baseURL,"/functions/",Name),body=X,httr::content_type_json())
}
VeneerSetPiecewise<-function(data,pw_table,baseURL="http://localhost:9876")
{
if(ncol(data)!=2)
{
stop("Data for piecewise linear must have 2 columns")
}
X<-list()
X[["Entries"]]<-as.matrix(data)
X[["XName"]]<-"Lookup"
X[["YName"]]<-"Result"
X<-jsonlite::toJSON(X,auto_unbox = TRUE)
httr::PUT(paste0(baseURL,"/variables/",pw_table,"/Piecewise"),body=X,httr::content_type_json())
}
VeneerGetPiecewise<-function(pw_table,baseURL="http://localhost:9876")
{
D<-jsonlite::fromJSON(URLencode(paste0(baseURL,"/variables/",pw_table,"/Piecewise")))$Entries
return(D)
}
VeneerGetTS<-function(TSURL,baseURL="http://localhost:9876")
{
D<-jsonlite::fromJSON(URLencode(paste0(baseURL,TSURL)))
B<-zoo::zoo(D$Events$Value,zoo::as.Date(D$Events$Date,format="%m/%d/%Y"))
if(D$Units=="m\U00B3/s") B <- B*86.4
if(D$Units == "m\U00B3") B <- B / 1000
if(D$Units == "m\U00B2") B <- B / 10000
if(D$Units == "kg/m\U00B3") B <- B * 1000
return(B)
}
VeneerGetTSbyVariable<-function(variable="Flow",run="latest",baseURL="http://localhost:9876")
{
Results<-jsonlite::fromJSON(paste0(baseURL,"/runs/",run))
X<-Results$Results %>% dplyr::filter(.data$RecordingVariable==variable)
TS<-lapply(X$TimeSeriesUrl,function(x) VeneerGetTS(x,baseURL))
if(length(TS)>0)
{
TS<-zoo::zoo(matrix(unlist(TS),ncol=length(TS)),zoo::index(TS[[1]]))
if(ncol(TS)>1){
colnames(TS)<-X$NetworkElement
}else
{
names(TS)<-X$NetworkElement
}
return(TS)
}else
{
stop(paste("No results for variable",variable,"found for run",run,"\n",
"Recorded variables are:",paste(unique(Results$Results$RecordingVariable))))
}
}
VeneerGetTSVariables<-function(run="latest",baseURL="http://localhost:9876")
{
Results<-jsonlite::fromJSON(paste0(baseURL,"/runs/",run))
return(unique(Results$Results$RecordingVariable))
}
VeneerGetTSbyNode<-function(Node,run="latest",baseURL="http://localhost:9876")
{
Results<-jsonlite::fromJSON(paste0(baseURL,"/runs/",run))
X<-Results$Results %>% dplyr::filter(.data$NetworkElement==Node)
TS<-lapply(X$TimeSeriesUrl,function(x) VeneerGetTS(x,baseURL))
if(length(TS)>0)
{
TS<-zoo::zoo(matrix(unlist(TS),ncol=length(TS)),zoo::index(TS[[1]]))
if(ncol(TS)>1) colnames(TS)<-X$RecordingVariable
return(TS)
}else
{
stop(paste("No results for node",Node,"found for run",run,"\n",
"Recorded Nodes are:",paste(unique(Results$Results$NetworkElement))))
}
}
VeneerGetInputSets<-function(baseURL="http://localhost:9876")
{
return(jsonlite::fromJSON(paste0(baseURL,"/InputSets")))
}
VeneerGetNodesbyType<-function(NodeType,baseURL="http://localhost:9876")
{
A<-jsonlite::fromJSON(paste0(baseURL,"/network"))
iconname<-A$features$properties$icon[grep(NodeType,A$features$properties$icon)[1]]
if(length(iconname)==1 & is.na(iconname)){
stop(paste(NodeType,"not found in the model. Try a different name, capitalisation matters. Search http://localhost:9876/network to see options, look for \"icon\""))
}else{
return(A$features$properties %>% dplyr::filter(.data$icon == iconname) %>% dplyr::select(.data$name))
}
}
VeneerlatestRunNumber<-function(baseURL="http://localhost:9876")
{
A<-jsonlite::fromJSON(paste0(baseURL,"/Runs"))
return(as.integer(strsplit(A[nrow(A),]$RunUrl,"/")[[1]][3]))
} |
"boa.chain.del" <-
function(lnames, pnames)
{
master <- boa.chain("master")
master.support <- boa.chain("master.support")
if(!missing(lnames)) {
lnames <- intersect(lnames, names(master))
for(i in lnames) {
master[[i]] <- NULL
master.support[[i]] <- NULL
}
}
if(!missing(pnames)) {
lnames <- names(master)
for(i in lnames) {
keep <- setdiff(boa.pnames(master[[i]]), pnames)
master[[i]] <- master[[i]][, keep]
master.support[[i]] <- master.support[[i]][, keep]
}
}
if(boa.chain("work.sync")) {
boa.chain(master = master, master.support = master.support,
work = master, work.support = master.support)
} else {
boa.chain(master = master, master.support = master.support)
}
invisible()
} |
combine_into_paired <- function(repertoire_heavy,repertoire_light){
repertoire_light <- repertoire_light[,c(1:5,7:10,13,14,16)]
names(repertoire_light) <- c("sequence_L", "sequence_aa_L", "junction_L", "junction_aa_L", "v_call_L", "j_call_L", "np1_L", "np2_L", "del_v_L","del_j_L", "v_sequence_alignment_L", "j_sequence_alignment_L")
repertoire_paired <- cbind(repertoire_heavy,repertoire_light)
return(repertoire_paired)
} |
knitr::opts_chunk$set(
echo = TRUE,
message = FALSE,
warning = FALSE,
collapse = TRUE,
comment = "
error = TRUE,
purl = FALSE,
fig.width = 6,
fig.asp = 1 / 1.6,
out.width = "70%",
fig.align = "center",
fig.path = "../man/figures/put-workspace-"
)
knitr::knit_hooks$set(inline = function(x) {
if (!is.numeric(x)) {
x
} else if (x >= 10000) {
prettyNum(round(x, 2), big.mark = ",")
} else {
prettyNum(round(x, 2))
}
})
options(tibble.print_min = 8L, tibble.print_max = 8L) |
FRTCI <- function(Y, Z, X = NULL, test.stat = SKS.stat, B=500,
gamma=0.0001, grid.gamma=100*gamma,
grid.size=151,
te.vec=NULL, return.matrix=FALSE,
n.cores=1,
verbose=TRUE, ... ) {
if ( is.null(te.vec) ) {
if ( grid.size %% 2 == 0 ) {
grid.size <- grid.size+1
}
if( is.null(X) ){
te.vec <- get.tau.vector( Y, Z, gamma=gamma, grid.size=grid.size, grid.gamma=grid.gamma )
}else{
te.vec <- get.tau.vector( Y, Z, X, gamma=gamma, grid.size=grid.size, grid.gamma=grid.gamma )
}
} else {
grid.size = length( te.vec )
}
te.hat <- attr( te.vec, "te.hat" )
te.se <- attr( te.vec, "te.se" )
te.MOE <- attr( te.vec, "te.MOE" )
Y1.mat <- sapply(te.vec, function(te) ifelse(Z, Y, Y + te) )
Y0.mat <- sapply(te.vec, function(te) ifelse(Z, Y - te, Y) )
if( is.null(X) ){
res <- generate.permutations( Y, Z=Z, test.stat=test.stat, Y0.mat=Y0.mat, Y1.mat=Y1.mat, B=B, n.cores, verbose=verbose, ... )
}else{
res <- generate.permutations( Y, Z=Z, test.stat=test.stat, Y0.mat=Y0.mat, Y1.mat=Y1.mat, B=B, n.cores, verbose=verbose, X=X, ... )
}
ci.p = res$ci.p + gamma
t = res$ks.obs
p.value = max( ci.p )
n=length(Y)
method = "FRT CI Test for Treatment Effect Heterogeneity"
DAT = paste( n, " observations", sep="")
if ( !return.matrix ) {
ks.mat=NULL
} else {
ks.mat = res$ks.mat
}
structure(list(statistic = t, p.value = p.value,
p.value.plug = ci.p[(grid.size+1)/2],
method=method,
data.name = DAT,
Y=Y, Z=Z, n=n, ci.p=ci.p, te.vec=te.vec,
te.hat=te.hat,
te.SE=te.se,
te.MOE = te.MOE,
B=B, gamma=gamma, ks.mat=ks.mat ),
class = "FRTCI.test")
}
FRTplug <- function( Y, Z, test.stat=SKS.stat, tau.hat=mean(Y[Z == 1]) - mean(Y[Z == 0]), ... ){
mth = FRTCI( Y, Z, test.stat=test.stat, te.vec=c(tau.hat), n.cores = 1, ...)
mth$method = "FRT Plug-in Test for Treatment Effect Heterogeneity"
mth
}
FRTCI.interact <- function( Y, Z, W, X=NULL, test.stat = SKS.stat.int.cov, B=500,
gamma=0.0001, grid.gamma=100*gamma,
grid.size=151, return.matrix=FALSE,
n.cores=1, verbose=TRUE, ... ) {
grid.info = get.testing.grid( Y, Z, W=W, X=X, gamma, grid.size )
te.MOE = NA
te.grid = grid.info$te.grid
Y1.mat <- grid.info$Y1.mat
Y0.mat <- grid.info$Y0.mat
if( is.null(X) ){
res <- generate.permutations( Y, Z, test.stat, Y0.mat, Y1.mat, B=B, n.cores=n.cores, verbose=verbose, W=W, ... )
}else{
res <- generate.permutations( Y, Z, test.stat, Y0.mat, Y1.mat, B=B, n.cores=n.cores, verbose=verbose, X=X, W=W, ... )
}
t = res$ks.obs
ci.p = res$ci.p + gamma
p.value = max( ci.p )
n=length(Y)
method = "FRT CI Test for Tx Effect Heterogeneity Beyond a Systematic Model"
DAT = paste( n, " observations", sep="")
if ( !return.matrix ) {
ks.mat=NULL
} else {
ks.mat = res$ks.mat
}
structure(list(statistic = t, p.value = p.value,
p.value.plug = ci.p[1],
method=method,
data.name = DAT,
Y=Y, Z=Z, n=n, ci.p=ci.p, te.grid=te.grid,
B=B, gamma=gamma, ks.mat=ks.mat,
W=W, X=X ),
class = "FRTCI.test")
} |
hotspot_to_ignition <- function(lon,
lat,
obsTime,
timeUnit,
membership,
ignition) {
if (all(membership == -1)) {
return(list(distToIgnition = NA, timeFromIgnition = NA))
}
tb <- list(s = "secs", m = "mins", h = "hours", d = "days", n = "numeric")
timeUnit <- tb[[timeUnit]]
fin_vec <- rep(0, length(lon))
if (timeUnit != "numeric") {
time_vec <- difftime(rep(obsTime[1], length(lon)),
obsTime[2],
units = timeUnit)
} else {
time_vec <- rep(0, length(lon))
}
for (i in 1:max(membership)){
indexes <- membership == i
vlon <- lon[indexes]
vlat <- lat[indexes]
indexes2 <- ignition$membership == i
plon <- ignition$lon[indexes2]
plat <- ignition$lat[indexes2]
dist_vec <- dist_point_to_vector(plon, plat, vlon, vlat)
fin_vec[indexes] <- dist_vec
if (timeUnit != "numeric") {
time_vec[indexes] <- difftime(obsTime[indexes], ignition$obsTime[indexes2],
units = timeUnit)
} else {
time_vec[indexes] <- obsTime[indexes] - ignition$obsTime[indexes2]
}
}
indexes <- membership == -1
if (length(indexes) > 0) {
fin_vec[indexes] <- 0
if (timeUnit != "numeric") {
time_vec[indexes] <- difftime(obsTime[1], obsTime[1],
units = timeUnit)
} else {
time_vec[indexes] <- 0
}
}
list(distToIgnition = fin_vec, timeFromIgnition = time_vec)
} |
context("main function")
test_that("main function", {
set.seed(314)
x <- generate_train_data()
fit <- sGMRFmix(x, K = 7, rho = 100)
expected <- c("1"=0.5156696, "2"=0.4843304)
expect_equal(fit$pi, expected, tolerance = 1e-7)
})
test_that("compute anomaly", {
set.seed(314)
x <- generate_train_data()
fit <- sGMRFmix(x, K = 7, rho = 100)
anomaly_score <- compute_anomaly_score(fit, generate_test_data())
expect_equal(anomaly_score[1, 1], 0.7737825, tolerance = 1e-7)
}) |
context("interact_plot lm")
states <- as.data.frame(state.x77)
states$HSGrad <- states$`HS Grad`
states$o70 <- 0
states$o70[states$`Life Exp` > 70] <- 1
states$o70n <- states$o70
states$o70 <- factor(states$o70)
states$o70l <- states$`Life Exp` > 70
states$o70c <- ifelse(states$o70l, yes = "yes", no = "no")
set.seed(3)
states$wts <- runif(50, 0, 3)
fit <- lm(Income ~ HSGrad*Murder*Illiteracy + o70 + Area, data = states)
fit2 <- lm(Income ~ HSGrad*o70, data = states)
fit2n <- lm(Income ~ HSGrad*o70n, data = states)
fitw <- lm(Income ~ HSGrad*Murder*Illiteracy + o70 + Area, data = states,
weights = wts)
fitl <- lm(Income ~ HSGrad*o70l, data = states)
fitc <- lm(Income ~ HSGrad*Murder + o70c, data = states)
library(vdiffr)
Sys.setenv("VDIFFR_RUN_TESTS" = FALSE)
if (requireNamespace("survey")) {
suppressMessages(library(survey, quietly = TRUE))
data(api)
dstrat <- svydesign(id = ~1, strata = ~stype, weights = ~pw, data = apistrat,
fpc = ~fpc)
regmodel <- svyglm(api00 ~ ell * meals * both + sch.wide, design = dstrat)
}
test_that("interact_plot works for lm", {
plma <- interact_plot(model = fit, pred = Murder, modx = Illiteracy,
mod2 = HSGrad, centered = "all")
expect_doppelganger("plma", plma)
expect_warning(
plmm <- interact_plot(model = fit, pred = Murder, modx = Illiteracy,
mod2 = HSGrad, centered = "HSGrad")
)
expect_doppelganger("plmm", plmm)
plm1 <- interact_plot(model = fit, pred = Murder, modx = Illiteracy,
mod2 = HSGrad, centered = "Area")
expect_doppelganger("plm1", plm1)
plm0 <- interact_plot(model = fit, pred = Murder, modx = Illiteracy,
mod2 = HSGrad, centered = "none")
expect_doppelganger("plm0", plm0)
})
test_that("interact_plot: robust standard errors work", {
plmrob <- interact_plot(model = fit, pred = Murder, modx = Illiteracy,
mod2 = HSGrad, centered = "all", robust = TRUE)
expect_doppelganger("plmrob", plmrob)
})
test_that("rug plots work", {
plmrugb <- interact_plot(model = fit, pred = Murder, modx = Illiteracy,
mod2 = HSGrad, centered = "all", rug = TRUE)
expect_doppelganger("plmrugb", plmrugb)
plmruglb <- interact_plot(model = fit, pred = Murder, modx = Illiteracy,
mod2 = HSGrad, centered = "all", rug = TRUE,
rug.sides = "lb")
expect_doppelganger("plmruglb", plmruglb)
})
test_that("interact_plot works for weighted lm", {
plmw <- interact_plot(model = fitw, pred = Murder, modx = Illiteracy,
mod2 = HSGrad, modx.values = c(1, 1.5, 2),
centered = "all")
expect_doppelganger("plmw", plmw)
})
test_that("interact_plot works for lm w/ logical", {
plmtf <- interact_plot(model = fitl, pred = HSGrad, modx = o70l)
expect_doppelganger("plmtf", plmtf)
})
test_that("interact_plot works for lm w/ non-focal character", {
plmnfchar <- interact_plot(model = fitc, pred = HSGrad, modx = Murder)
expect_doppelganger("plmnfchar", plmnfchar)
})
test_that("interact_plot accepts user-specified values and labels", {
plmlabelsc <- interact_plot(model = fit, pred = Murder, modx = Illiteracy,
mod2 = HSGrad, centered = "all",
modxvals = c(1.5, 2, 2.5),
modx.labels = c("None","Low","High"),
mod2vals = c(58, 60, 62),
mod2.labels = c("Low","Average","High"))
expect_doppelganger("plmlabelsc", plmlabelsc)
plmlabelsc2 <- interact_plot(model = fit, pred = Murder, modx = Illiteracy,
mod2 = HSGrad, centered = "all",
modxvals = c("None" = 1.5, "Low" = 2,
"High" = 2.5),
mod2vals = c("Low" = 58, "Average" = 60,
"High" = 62))
expect_doppelganger("plmlabelsc2", plmlabelsc2)
expect_error(interact_plot(model = fit2, pred = o70, modx = HSGrad,
pred.labels = c("Under","Over")))
plmlabelscpred <- interact_plot(model = fit2n, pred = o70n, modx = HSGrad,
pred.labels = c("Under","Over"))
expect_doppelganger("plmlabelscpred", plmlabelscpred)
plmlabelscs <- interact_plot(model = fit, pred = Murder, modx = Illiteracy,
mod2 = HSGrad, centered = "all",
modxvals = c(2.5, 2, 1.5),
modx.labels = c("High","Low","None"),
mod2vals = c(62, 60, 58),
mod2.labels = c("High","Average","Low"))
expect_doppelganger("plmlabelscs", plmlabelscs)
})
test_that("interact_plot terciles modxval/mod2val works", {
expect_message(
plmtercs <- interact_plot(model = fit, pred = Murder, modx = Illiteracy,
mod2 = HSGrad, modxvals = "terciles",
mod2vals = "terciles", centered = "none")
)
expect_doppelganger("plmtercs", plmtercs)
})
test_that("interact_plot linearity.check works", {
plmlinearchp <- interact_plot(model = fit, pred = Murder, modx = Illiteracy,
modxvals = "terciles", linearity.check = TRUE,
plot.points = TRUE, jitter = 0)
expect_doppelganger("plmlinearchp", plmlinearchp)
plmlinearchnp <- interact_plot(model = fit, pred = Murder, modx = Illiteracy,
modxvals = "terciles", linearity.check = TRUE)
expect_doppelganger("plmlinearchnp", plmlinearchnp)
})
context("interact_plot svyglm")
if (requireNamespace("survey")) {
test_that("interact_plot works for svyglm", {
psvya <- interact_plot(regmodel, pred = ell, modx = meals, mod2 = both,
centered = "all")
expect_doppelganger("psvya", psvya)
expect_warning(
psvy1 <- interact_plot(regmodel, pred = ell, modx = meals, mod2 = both,
centered = "ell")
)
expect_doppelganger("psvy1", psvy1)
})
}
context("interact_plot merMod")
if (requireNamespace("lme4")) {
library(lme4, quietly = TRUE)
data(VerbAgg)
VerbAgg$mode_numeric <- as.numeric(VerbAgg$mode)
mve <- lmer(Anger ~ Gender * mode + btype + (1 | item), data = VerbAgg)
mv <- lmer(Anger ~ Gender * mode_numeric + btype + (1 | item),
data = VerbAgg)
gm <- glmer(incidence ~ period + (1 | herd), family = poisson, data = cbpp,
offset = log(size))
test_that("interact_plot works for lme4", {
expect_error(interact_plot(mve, pred = mode, modx = Gender))
plme4 <- interact_plot(mv, pred = mode_numeric, modx = Gender)
expect_doppelganger("plme4", plme4)
plme4i <- interact_plot(mv, pred = mode_numeric, modx = Gender,
interval = TRUE)
expect_doppelganger("plme4i", plme4i)
})
}
context("interact_plot offsets")
set.seed(100)
exposures <- rpois(50, 50)
counts <- exposures - rpois(50, 25)
money <- (counts/exposures) + rnorm(50, sd = 1)
talent <- counts*.5 + rnorm(50, sd = 3)
poisdat <- as.data.frame(cbind(exposures, counts, talent, money))
pmod <- glm(counts ~ talent*money, offset = log(exposures), data = poisdat,
family = poisson)
test_that("interact_plot handles offsets", {
expect_message(
pglmoff <- interact_plot(pmod, pred = talent, modx = money)
)
expect_doppelganger("pglmoff", pglmoff)
})
test_that("interact_plot handles offsets with robust SE", {
expect_message(
pglmrob <- interact_plot(pmod, pred = talent, modx = money, robust = TRUE)
)
expect_doppelganger("pglmrob", pglmrob)
})
test_that("sim_slopes handles offsets", {
expect_s3_class(sim_slopes(pmod, pred = talent, modx = money), "sim_slopes")
})
if (requireNamespace("brms")) {
context("brmsfit plots 2")
bfit <- readRDS("brmfit.rds")
test_that("brmsfit objects are supported", {
pbfcat <- cat_plot(bfit, pred = "Trt", interval = TRUE)
expect_doppelganger("pbfcat", pbfcat)
pbfcont <- interact_plot(bfit, pred = "log_Base4_c", modx = "Trt",
interval = TRUE)
expect_doppelganger("pbfcont", pbfcont)
})
}
if (requireNamespace("rstanarm") & requireNamespace("lme4")) {
context("stanreg plots")
rsfit <- readRDS("rsafit.rds")
library(lme4)
data(cbpp)
test_that("stanreg objects are supported", {
prsacont <- interact_plot(rsfit, pred = "size", modx = "period",
interval = TRUE, data = cbpp)
expect_doppelganger("prsacont", prsacont)
})
} |
null.LGRF<-function(Y,time,X=NULL)
{
Y<-as.matrix(Y);n<-nrow(Y);index.cluster<-unique(time[,1])
if(length(X)==0){is.naX<-0;nrowX<-nrow(Y)}else{
is.naX<-is.na(X);nrowX<-nrow(X)
}
N_MISS<-sum(is.naX+sum(is.na(Y))+sum(is.na(time)))
if(N_MISS>0){
msg<-sprintf("X, Y or time has missing values")
stop(msg)
}
if((nrow(Y)-nrow(time))^2+(nrow(Y)-nrowX)^2>0){
msg<-sprintf("Number of observations in Y, X and time does not match")
stop(msg)
}
X1<-cbind(rep(1,n),X);p<-ncol(X1)-1
step.error<-Inf;beta<-rep(0,p+1);eta<-0;iter<-0
while (step.error>0.00001)
{
A<-0;B<-0;x.field<-NULL
for (i in index.cluster)
{
index<-which(time[,1]==i);ni<-length(index)
S.subject<-matrix(1,ni,ni);diag(S.subject)<-0
V<-diag(1,length(index))-eta*S.subject
X.temp<-X1[index,];Y.temp<-Y[index,]
if (ni==1) {X.temp<-t(X.temp)}
A<-A+t(X.temp)%*%V%*%X.temp;B<-B+t(X.temp)%*%V%*%Y.temp
}
beta.new<-solve(A)%*%B;Y.res<-Y-X1%*%beta.new
if(length(index.cluster)==nrow(time))
{
eta.new<-0
}
if(length(index.cluster)!=nrow(time))
{
for (i in index.cluster)
{
index<-which(time[,1]==i);ni<-length(index)
S.subject<-matrix(1,ni,ni);diag(S.subject)<-0
x.field<-rbind(x.field,S.subject%*%Y.res[index,])
}
eta.new<-lm(Y.res~0+x.field)$coefficients
}
step.error<-sum(c(beta.new-beta,eta.new-eta)^2);iter<-iter+1
beta<-beta.new;eta<-eta.new
}
return(list(Y.res=Y.res,time=time,X1=X1,eta=eta))
}
test.LGRF<-function(Z,result.null,Gsub.id=NULL,interGXT=FALSE,similarity='GR',impute.method="fixed")
{
Y.res<-result.null$Y.res;time<-result.null$time
X1<-result.null$X1;eta<-result.null$eta
if(length(Gsub.id)==0){Gsub.id<-unique(time[,1])}
Z<-as.matrix(Z[match(unique(time[,1]),Gsub.id),])
N_MISS<-sum(is.na(Z))
if(N_MISS>0){
msg<-sprintf("The missing genotype rate is %f. Imputation is applied.", N_MISS/nrow(Z)/ncol(Z))
warning(msg,call.=F)
Z<-Impute(Z,impute.method)
}
ID_G<-unique(time[,1]);Z<-as.matrix(Z[match(time[,1],ID_G),])
if (interGXT==FALSE)
{
if (similarity=='IBS'){G<-IBS_pseudo(Z)}
if (similarity=='GR'){G<-apply(Z,2,center)}
dimY<-nrow(Y.res);m<-length(unique(time[,1]));dimX<-ncol(X1);dimG<-ncol(G)
index.cluster<-unique(time[,1])
dS<-matrix(0,2*dimG+dimX,dimX);
S1<-matrix(0,2*dimG,1);S0<-matrix(0,dimX,1);D<-matrix(0,2*dimG+dimX,2*dimG+dimX)
for (i in index.cluster)
{
index<-which(time[,1]==i);ni<-length(index)
S.subject<-matrix(1,ni,ni);diag(S.subject)<-0
Vi<-diag(1,ni)-eta*S.subject
Gi<-G[index,];Xi<-X1[index,];Yi<-as.matrix(Y.res[index,])
if (ni==1) {Gi<-t(Gi);Xi<-t(Xi)}
G.temp<-cbind(Vi%*%Gi,Gi,Xi)
Si<-t(G.temp)%*%Yi;dSi<--t(G.temp)%*%Xi;Di<-Si%*%t(Si)
S1<-S1+Si[1:(2*dimG),];dS<-dS+dSi;D<-D+Di
}
D<-D/m;S1<-S1/sqrt(m);dS<-dS/sqrt(m)
Q<-t(S1[(dimG+1):(2*dimG),])%*%S1[1:dimG,]
P<-dS[1:(2*dimG),]%*%solve(dS[(2*dimG+1):(2*dimG+dimX),])
D11<-D[1:(2*dimG),1:(2*dimG)];D10<-D[1:(2*dimG),(2*dimG+1):(2*dimG+dimX)];D00<-D[(2*dimG+1):(2*dimG+dimX),(2*dimG+1):(2*dimG+dimX)]
M<-D11-P%*%t(D10)-D10%*%t(P)+P%*%D00%*%t(P)
M.rotate<-cbind(M[,(dimG+1):(2*dimG)],M[,1:dimG])
eigen.M<-Re(eigen(M.rotate,symmetric=FALSE,only.values=TRUE)$values)
p.value<-davies(2*Q,eigen.M)$Qq
}
else
{
if (similarity=='IBS'){G<-IBS_pseudo(Z)}
if (similarity=='GR'){G<-apply(Z,2,center)}
Gt<-apply(Z*time[,2],2,center)
dimY<-nrow(Y.res);m<-length(unique(time[,1]));dimX<-ncol(X1);dimG<-(ncol(G)+ncol(Gt))/2
index.cluster<-unique(time[,1])
K.g<-t(G)%*%G;K.gt<-t(Gt)%*%Gt
s2.g<-2*sum(diag(K.g%*%K.g));s2.gt<-2*sum(diag(K.gt%*%K.gt))
alpha.g<-sqrt(s2.gt/(s2.g+s2.gt));alpha.gt<-sqrt(s2.g/(s2.g+s2.gt))
dS<-matrix(0,4*dimG+dimX,dimX);
S1<-matrix(0,4*dimG,1);S0<-matrix(0,dimX,1);D<-matrix(0,4*dimG+dimX,4*dimG+dimX)
for (i in index.cluster)
{
index<-which(time[,1]==i);ni<-length(index)
S.subject<-matrix(1,ni,ni);diag(S.subject)<-0
Vi<-diag(1,ni)-eta*S.subject
Gi<-G[index,];Gti<-Gt[index,];Xi<-X1[index,];Yi<-as.matrix(Y.res[index,])
if (ni==1) {Gi<-t(Gi);Gti<-t(Gti);Xi<-t(Xi)}
G.temp<-cbind(sqrt(alpha.g)*Vi%*%Gi,sqrt(alpha.gt)*Vi%*%Gti,sqrt(alpha.g)*Gi,sqrt(alpha.gt)*Gti,Xi)
Si<-t(G.temp)%*%Yi;dSi<--t(G.temp)%*%Xi;Di<-Si%*%t(Si)
S1<-S1+Si[1:(4*dimG),];dS<-dS+dSi;D<-D+Di
}
D<-D/m;S1<-S1/sqrt(m);dS<-dS/sqrt(m)
Q<-t(S1[(2*dimG+1):(4*dimG),])%*%S1[1:(2*dimG),]
P<-dS[1:(4*dimG),]%*%solve(dS[(4*dimG+1):(4*dimG+dimX),])
D11<-D[1:(4*dimG),1:(4*dimG)];D10<-D[1:(4*dimG),(4*dimG+1):(4*dimG+dimX)];D00<-D[(4*dimG+1):(4*dimG+dimX),(4*dimG+1):(4*dimG+dimX)]
M<-D11-P%*%t(D10)-D10%*%t(P)+P%*%D00%*%t(P)
M.rotate<-cbind(M[,(2*dimG+1):(4*dimG)],M[,1:(2*dimG)])
eigen.M<-Re(eigen(M.rotate,symmetric=FALSE,only.values=TRUE)$values)
p.value<-davies(2*Q,eigen.M)$Qq
}
return(list(p.value=p.value,n.marker=dimG))
}
IBS_pseudo<-function(x)
{
pseudo1<-(0<=x & x<0.5)*sqrt(2)+(0.5<=x & x<1.5)*sqrt(2)/2
pseudo2<-(0.5<=x & x<1.5)*sqrt(2)/2+(1.5<=x & x<2.5)*sqrt(2)
pseudo3<-(0.5<=x & x<1.5)
pseudo<-cbind(pseudo1,pseudo2,pseudo3)
return(pseudo)
}
test.MinP<-function(Z,result.null,Gsub.id=NULL,corstr="exchangeable",MinP.adjust=0.95,impute.method="fixed"){
Y.res<-result.null$Y.res;time<-result.null$time
X1<-result.null$X1;eta<-result.null$eta;dimG<-ncol(Z)
if(length(Gsub.id)==0){Gsub.id<-unique(time[,1])}
Z<-as.matrix(Z[match(unique(time[,1]),Gsub.id),])
N_MISS<-sum(is.na(Z))
if(N_MISS>0){
msg<-sprintf("The missing genotype rate is %f. Imputation is applied.", N_MISS/nrow(Z)/ncol(Z))
warning(msg,call.=F)
Z<-Impute(Z,impute.method)
}
if((length(unique(time[,1]))-nrow(Z))^2>0){
msg<-sprintf("Number of subjects in Y, X, time and Z does not match")
stop(msg)
}
MAF<-apply(Z,2,mean)/2
if(min(MAF)<0.01){
msg<-sprintf("There are rare variants with MAF<0.01. MinP by GEE might be unstable", N_MISS/nrow(Z)/ncol(Z))
warning(msg,call.=F)
}
ID_G<-unique(time[,1]);Z<-Z[match(time[,1],ID_G),]
temp.pvalue<-rep(0,ncol(Z))
for (k in 1:ncol(Z)){
if(ncol(X1)!=1){temp.fit<-geeglm(Y.res~X1[,-1]+Z[,k],id=time[,1],corstr=corstr)}else{
temp.fit<-geeglm(Y.res~Z[,k],id=time[,1],corstr=corstr)
}
temp.pvalue[k]<-summary(temp.fit)$coefficient[nrow(summary(temp.fit)$coefficient),4]
}
eigen.G<-eigen(cor(Z),only.values=TRUE)$values
me.G<-effect.n(eigen.G,MinP.adjust)
p.value<-min(1,min(temp.pvalue)*me.G)
return(list(p.value=p.value,n.marker=dimG))
}
effect.n<-function(x,MinP.adjust){
temp<-0;sum.EV<-sum(x)
for (i in 1:length(x)){
temp<-temp+x[i];if (temp>sum.EV*MinP.adjust){break}
}
return(i)
}
Get.sqrt<-function(A){
a.eig <- eigen(A,symmetric=TRUE)
ID1<-which(a.eig$values > 0)
if(length(ID1)== 0){
stop("Error to obtain matrix square!")
}
a.sqrt <- a.eig$vectors[,ID1] %*% diag(sqrt(a.eig$values[ID1])) %*% t(a.eig$vectors[,ID1])
return(a.sqrt)
}
Check.same<-function(x,y)
{return(as.numeric(x==y))}
Check.near<-function(x,y)
{return(as.numeric(abs(x-y)==1))}
center<-function(x)
{return(x-mean(x))}
Impute<-function(Z, impute.method){
p<-dim(Z)[2]
if(impute.method =="random"){
for(i in 1:p){
IDX<-which(is.na(Z[,i]))
if(length(IDX) > 0){
maf1<-mean(Z[-IDX,i])/2
Z[IDX,i]<-rbinom(length(IDX),2,maf1)
}
}
} else if(impute.method =="fixed"){
for(i in 1:p){
IDX<-which(is.na(Z[,i]))
if(length(IDX) > 0){
maf1<-mean(Z[-IDX,i])/2
Z[IDX,i]<-2 * maf1
}
}
} else if(impute.method =="bestguess") {
for(i in 1:p){
IDX<-which(is.na(Z[,i]))
if(length(IDX) > 0){
maf1<-mean(Z[-IDX,i])/2
Z[IDX,i]<-round(2 * maf1)
}
}
} else {
stop("Error: Imputation method shoud be \"fixed\", \"random\" or \"bestguess\" ")
}
return(as.matrix(Z))
} |
weightedMad <- function(x, w = NULL, idxs = NULL, na.rm = FALSE,
constant = 1.4826, center = NULL, ...) {
if (is.null(w)) {
if (is.null(center)) center <- median(x, na.rm = na.rm)
return(mad(x, center = center, constant = constant, na.rm = na.rm, ...))
}
n <- length(x)
if (length(w) != n) {
stop(sprintf("The number of elements in arguments '%s' and '%s' does not match: %.0f != %.0f", "w", "x", length(w), n))
} else if (!is.null(idxs)) {
w <- w[idxs]
}
if (length(constant) != 1L)
stop(sprintf("Argument '%s' is not a scalar: %.0f", "constant", length(constant)))
if (!is.numeric(constant))
stop(sprintf("Argument '%s' is not numeric: %s", "constant", mode(constant)))
if (!is.null(center) && length(center) != 1L)
stop(sprintf("Argument '%s' is not a scalar or NULL: %.0f", "center", length(center)))
if (!is.null(idxs)) {
x <- x[idxs]
n <- length(x)
}
na_value <- NA
storage.mode(na_value) <- storage.mode(x)
tmp <- (is.na(w) | w > 0)
if (!all(tmp)) {
x <- .subset(x, tmp)
w <- .subset(w, tmp)
n <- length(x)
}
tmp <- NULL
if (na.rm) {
keep <- which(!is.na(x))
x <- .subset(x, keep)
w <- .subset(w, keep)
n <- length(x)
keep <- NULL
} else if (anyMissing(x)) {
return(na_value)
}
if (anyMissing(w)) return(na_value)
tmp <- is.infinite(w)
if (any(tmp)) {
keep <- tmp
x <- .subset(x, keep)
n <- length(x)
w <- rep(1, times = n)
keep <- NULL
}
tmp <- NULL
if (n == 0L) {
return(na_value)
} else if (n == 1L) {
zero_value <- 0
storage.mode(zero_value) <- storage.mode(x)
return(zero_value)
}
if (is.null(center)) {
center <- weightedMedian(x, w = w, na.rm = NA)
} else {
centerOnUse("weightedMad")
}
x <- abs(x - center)
sigma <- weightedMedian(x, w = w, na.rm = NA)
x <- w <- NULL
sigma <- constant * sigma
sigma
}
rowWeightedMads <- function(x, w = NULL, rows = NULL, cols = NULL,
na.rm = FALSE,
constant = 1.4826, center = NULL, ..., useNames = NA) {
if (length(constant) != 1L)
stop(sprintf("Argument '%s' is not a scalar: %.0f", "constant", length(constant)))
if (!is.numeric(constant))
stop(sprintf("Argument '%s' is not numeric: %s", "constant", mode(constant)))
if (!is.null(center)) {
if (length(center) != nrow(x)) {
if (length(center) == 1L && is.null(rows)) {
validateScalarCenter(center, nrow(x), "rows")
center <- rep(center, times = nrow(x))
} else {
stop(sprintf("Argument '%s' should be of the same length as number of %s of '%s': %d != %d", "center", "rows", "x", length(center), nrow(x)))
}
}
if (!is.null(rows)) center <- center[rows]
}
if (!is.null(rows) && !is.null(cols)) x <- x[rows, cols, drop = FALSE]
else if (!is.null(rows)) x <- x[rows, , drop = FALSE]
else if (!is.null(cols)) x <- x[, cols, drop = FALSE]
if (!is.null(w) && !is.null(cols)) w <- w[cols]
y <- numeric(nrow(x))
for (kk in seq_along(y)) {
y[kk] <- weightedMad(x[kk, , drop = TRUE], w = w, na.rm = na.rm,
constant = constant, center = center[kk], ...)
}
if (is.na(useNames) || useNames) {
names(y) <- rownames(x)
} else {
names(y) <- NULL
}
y
}
colWeightedMads <- function(x, w = NULL, rows = NULL, cols = NULL,
na.rm = FALSE,
constant = 1.4826, center = NULL, ..., useNames = NA) {
if (length(constant) != 1L)
stop(sprintf("Argument '%s' is not a scalar: %.0f", "constant", length(constant)))
if (!is.numeric(constant))
stop(sprintf("Argument '%s' is not numeric: %s", "constant", mode(constant)))
if (!is.null(center)) {
if (length(center) != ncol(x)) {
if (length(center) == 1L && is.null(cols)) {
validateScalarCenter(center, ncol(x), "cols")
center <- rep(center, times = ncol(x))
} else {
stop(sprintf("Argument '%s' should be of the same length as number of %s of '%s': %d != %d", "center", "columns", "x", length(center), ncol(x)))
}
}
if (!is.null(cols)) center <- center[cols]
}
if (!is.null(rows) && !is.null(cols)) x <- x[rows, cols, drop = FALSE]
else if (!is.null(rows)) x <- x[rows, , drop = FALSE]
else if (!is.null(cols)) x <- x[, cols, drop = FALSE]
if (!is.null(w) && !is.null(rows)) w <- w[rows]
y <- numeric(ncol(x))
for (kk in seq_along(y)) {
y[kk] <- weightedMad(x[, kk, drop = TRUE], w = w, na.rm = na.rm,
constant = constant, center = center[kk], ...)
}
if (is.na(useNames) || useNames) {
names(y) <- colnames(x)
} else {
names(y) <- NULL
}
y
} |
add_water = function(hillshade, watermap, color="imhof1") {
watermap = t(flipud(watermap))
if (color == "imhof1") {
color = col2rgb("
} else if (color == "imhof2") {
color = col2rgb("
} else if (color == "imhof3") {
color = col2rgb("
} else if (color == "imhof4") {
color = col2rgb("
} else if (color == "desert") {
color = col2rgb("
} else if (color == "bw") {
color = col2rgb("
} else if (color != "unicorn") {
color = col2rgb(color)
}
if (length(dim(hillshade)) != 3) {
if (length(dim(hillshade)) == 2) {
if(any(hillshade > 1 | hillshade < 0)) {
stop("Error: Not a shadow matrix. Intensities must be between 0 and 1. Pass your elevation matrix to ray_shade/lamb_shade/ambient_shade/sphere_shade first.")
}
temp = array(0,dim = c(ncol(hillshade),nrow(hillshade),3))
temp[,,1] = t(flipud(hillshade))
temp[,,2] = t(flipud(hillshade))
temp[,,3] = t(flipud(hillshade))
hillshade = temp
}
}
if(missing(watermap)) {
stop("User must provide matrix indicating locations of bodies of water")
}
if(all(dim(watermap) != dim(hillshade)[1:2])) {
stop("`hillshade` and `watermap` dimensions must be the same; hillshade is ",
paste0(dim(hillshade)[1:2],collapse="x"),", watermap is ", paste0(dim(watermap)[1:2],collapse="x"))
}
for(i in 1:3) {
tempmat = hillshade[,,i]
if(color[1] != "unicorn") {
tempmat[watermap >= 1] = color[i]/256
} else {
unicolors = col2rgb(rainbow(256))
for(row in 1:nrow(watermap)) {
for(col in 1:ncol(watermap)) {
if(watermap[row,col] >= 1) {
tempmat[row,col] = unicolors[i,col %% 256+1]/256
}
}
}
}
hillshade[,,i] = tempmat
}
hillshade
} |
setMethod("dissimilarity", signature(x = "binaryRatingMatrix"),
function(x,
y = NULL,
method = NULL,
args = NULL,
which = "users") {
args <- getParameters(list(alpha = .5), args)
which <- match.arg(tolower(which), c("users", "items"))
if (!is.null(method))
method <- tolower(method)
else
method <- "jaccard"
if (method == "karypis") {
if (!is.null(y) ||
which != "items")
stop(
"Kaypis dissimilarities are not implemented between users or as a cross-dissimilarity!"
)
return(.karypis(as(x, "dgCMatrix"), dist = TRUE, args))
}
if (method == "conditional") {
if (!is.null(y) ||
which != "items")
stop(
"Conditional dissimilarities are not implemented between users or as a cross-dissimilarity!"
)
return(.conditional(as(x, "dgCMatrix"), dist = TRUE, args))
}
if (which == "users")
which <- "transactions"
x <- x@data
if (!is.null(y))
y <- y@data
d <- arules::dissimilarity(x, y, method, args, which)
if (!is.null(y))
d <- structure(as(d, "matrix"), method = method)
d
})
setMethod("dissimilarity", signature(x = "realRatingMatrix"),
function(x,
y = NULL,
method = NULL,
args = NULL,
which = "users") {
args <- getParameters(list(na_as_zero = FALSE, alpha = .5), args)
which <- match.arg(tolower(which), c("users", "items"))
if (!is.null(method))
method <- tolower(method)
else
method <- "cosine"
if (method == "karypis") {
if (!is.null(y) ||
which != "items")
stop(
"Kaypis dissimilarities are not implemented between users or as a cross-dissimilarity!"
)
return(.karypis(as(x, "dgCMatrix"), dist = TRUE, args))
}
if (method == "conditional") {
if (!is.null(y) ||
which != "items")
stop(
"Conditional dissimilarities are not implemented between users or as a cross-dissimilarity!"
)
return(.conditional(as(x, "dgCMatrix"), dist = TRUE, args))
}
x <- as(x, "matrix")
if (which == "items")
x <- t(x)
if (args$na_as_zero)
x[is.na(x)] <- 0
if (!is.null(y)) {
y <- as(y, "matrix")
if (which == "items")
y <- t(y)
if (args$na_as_zero)
y[is.na(y)] <- 0
}
if (method == "pearson") {
if (!is.null(y))
y <- t(y)
pc <- suppressWarnings(cor(t(x), y, method = "pearson",
use = "pairwise.complete.obs"))
pc[pc < 0] <- 0
if (is.null(y))
pc <- as.dist(pc)
return(1 - pc)
}
proxy::dist(x = x, y = y, method = method)
})
setMethod("similarity", signature(x = "ratingMatrix"),
function(x,
y = NULL,
method = NULL,
args = NULL,
which = "users",
min_matching = 0,
min_predictive = 0) {
which <- match.arg(tolower(which), c("users", "items"))
if (!is.null(method))
method <- tolower(method)
else
method <- "cosine"
if (method == "karypis") {
if (!is.null(y) ||
which != "items")
stop("Kaypis similarities are not implemented between users or as a cross-similarity!")
if (min_matching > 0 ||
min_predictive > 0)
warning("min_matching and min_predictive for this method not implemented yet.")
return(.karypis(as(x, "dgCMatrix"), dist = FALSE, args))
}
if (method == "conditional") {
if (!is.null(y) ||
which != "items")
stop(
"Conditional similarities are not implemented between users or as a cross-similarity!"
)
if (min_matching > 0 ||
min_predictive > 0)
warning("min_matching and min_predictive for this method not implemented yet.")
return(.conditional(as(x, "dgCMatrix"), dist = FALSE, args))
}
d <- dissimilarity(x, y, method, args, which)
if (!is.null(attr(d, "method")) && tolower(attr(d, "method"))
%in% c("jaccard", "cosine")) {
sim <- 1 - d
} else{
sim <- 1 / (1 + d)
}
attr(sim, "type") <- "simil"
if (min_matching > 0 || min_predictive > 0) {
x_has_r <- hasRating(x)
y_has_r <- if (!is.null(y))
hasRating(y)
else
x_has_r
if (which == "items") {
x_has_r <- t(x_has_r)
y_has_r <- t(y_has_r)
}
if (min_matching > 0) {
shared <-
as.matrix(tcrossprod(as(x_has_r, "dgCMatrix"), as(y_has_r, "dgCMatrix")))
if (is.matrix(sim))
sim[shared < min_matching] <- NA
else
sim[as.dist(shared) < min_matching] <- NA
}
if (min_predictive > 0) {
predictive <- as.matrix(rowSums(x_has_r) - shared)
if (is.matrix(sim))
sim[predictive < min_predictive] <- NA
else
sim[as.dist(predictive) < min_predictive] <- NA
}
}
sim
})
.conditional <- function(x, dist = TRUE, args = NULL) {
n <- ncol(x)
uv <- crossprod(x)
v <- matrix(colSums(x),
nrow = n,
ncol = n,
byrow = FALSE)
sim <- uv / v
sim[is.na(sim)] <- 0
if (dist)
sim <- as.dist(1 / (1 + sim))
else
attr(sim, "type") <- "simil"
attr(sim, "method") <- "conditional"
sim
}
.karypis <- function(x, dist, args = NULL) {
args <- getParameters(list(na_as_zero = NULL, alpha = .5), args)
n <- ncol(x)
x <- x / rowSums(x)
x[is.na(x)] <- 0
uv <- crossprod(x, x > 0)
v <- matrix(colSums(x),
nrow = n,
ncol = n,
byrow = FALSE)
u <- t(v)
sim <- uv / v / u ^ args$alpha
sim[is.na(sim)] <- 0
if (dist)
sim <- as.dist(1 / (1 + sim))
else
attr(sim, "type") <- "simil"
attr(sim, "method") <- "karypis"
sim
} |
makeRoundUp <- function(int, modulus) {
int + modulus - int %% modulus
} |
factor_scores_mfa <- function (Y, g, q, pivec, B, mu, D, sigma_type,
D_type, tau = NULL, clust = NULL, ...) {
if (!is.matrix(Y))
Y <- as.matrix(Y)
p <- ncol(Y)
n <- nrow(Y)
U <- array(0, c(n, q, g))
if (sigma_type == "common") {
gamma <- matrix(0, nrow = p, ncol = q)
for (i in 1 : g) {
inv_D <- diag(1 / diag(D))
B_inv_D <- B * diag(inv_D)
gamma <- (inv_D - B_inv_D %*%
(chol.inv(diag(q) + t(B_inv_D) %*% B)) %*%
t(B_inv_D)) %*% B
U[,, i] <- sweep(Y, 2, mu[, i, drop = FALSE], '-') %*% gamma
}
} else {
gamma <- array(0, c(p, q))
for (i in 1 : g) {
if (D_type == 'common') {
inv_D <- diag(1 / diag(D))
} else {
inv_D <- diag(1 / diag(D[,, i]))
}
B_inv_D <- B[,, i] * diag(inv_D)
gamma <- (inv_D - B_inv_D %*%
(chol.inv(diag(q) + t(B_inv_D) %*% B[,, i])) %*%
t(B_inv_D)) %*% B[,, i]
U[,, i] <- sweep(Y, 2, mu[, i, drop = FALSE], '-') %*% gamma
}
}
if (is.null(tau)) {
tau <- tau.mfa(Y = Y, g = g, q = q, pivec = pivec, B = B,
mu = mu, D = D, sigma_type = sigma_type, D_type = D_type)
}
if (is.null(clust)) {
clust <- apply(tau, 1, which.max)
}
UC <- array(0, c(n, q))
Umean <- array(0, c(n, q))
for (i in 1 : n) {
UC[i, ] <- U[i,, clust[i]]
Umean[i, ] <- tau[i, ] %*% t(matrix(U[i,, ], c(q, g)))
}
return(list(Uscores = U, Uclust = UC, Umean = Umean))
} |
MHRM.group <- function(pars, constrain, Ls, Data, PrepList, list, random = list(),
lrPars = list(), lr.random = list(), DERIV, solnp_args, control)
{
if(is.null(random)) random <- list()
correction <- 0
itemtype <- sapply(pars[[1]], class)
has_graded <- any(itemtype == 'graded')
RAND <- length(random) > 0L; LR.RAND <- length(lr.random) > 0L
RANDSTART <- list$RANDSTART
LRPARS <- length(lrPars) > 0L
verbose <- list$verbose
nfact <- list$nfact
NCYCLES <- list$NCYCLES
no_stage_3 <- FALSE
if(is.na(NCYCLES)){
NCYCLES <- 1L
no_stage_3 <- TRUE
}
BURNIN <- list$BURNIN
MHDRAWS <- list$MHDRAWS
stopifnot(BURNIN >= RANDSTART)
SEMCYCLES <- list$SEMCYCLES
KDRAWS <- list$KDRAWS
TOL <- list$TOL
CUSTOM.IND <- list$CUSTOM.IND
USE.FIXED <- nrow(pars[[1L]][[1L]]@fixed.design) > 1L
gain <- list$gain
itemloc <- list$itemloc
ngroups <- length(pars)
J <- length(itemloc) - 1L
prodlist <- PrepList[[1L]]$prodlist
nfullpars <- 0L
estpars <- c()
gtheta0 <- gstructgrouppars <- vector('list', ngroups)
for(g in seq_len(ngroups)){
gstructgrouppars[[g]] <- ExtractGroupPars(pars[[g]][[J+1L]])
gtheta0[[g]] <- matrix(0, nrow(Data$fulldata[[g]]), nfact)
for(i in seq_len(J+1L)){
nfullpars <- nfullpars + length(pars[[g]][[i]]@par)
estpars <- c(estpars, pars[[g]][[i]]@est)
}
}
if(RAND){
for(i in seq_len(length(random))){
nfullpars <- nfullpars + length(random[[i]]@par)
estpars <- c(estpars, random[[i]]@est)
}
}
if(LRPARS){
nfullpars <- nfullpars + length(lrPars@par)
estpars <- c(estpars, lrPars@est)
}
if(LR.RAND){
for(i in seq_len(length(lr.random))){
nfullpars <- nfullpars + length(lr.random[[i]]@par)
estpars <- c(estpars, lr.random[[i]]@est)
}
}
if(all(!estpars) && list$SE)
stop('Computing ACOV matrix is meaningless when no parameters are estimated', call.=FALSE)
index <- 1L:nfullpars
N <- nrow(gtheta0[[1L]])
if(LRPARS){
lrPars@beta[] <- lrPars@par
lrPars@mus <- lrPars@X %*% lrPars@beta
gstructgrouppars[[1L]]$gmeans <- lrPars@mus
}
cand.t.var <- if(is.null(list$cand.t.var)) 1 else list$cand.t.var[1L]
tmp <- .1
OffTerm <- matrix(0, 1, J)
for(g in seq_len(ngroups)){
PAs <- CTVs <- rep(NA, 25L)
for(i in seq_len(31L)){
gtheta0[[g]] <- draw.thetas(theta0=gtheta0[[g]], pars=pars[[g]], fulldata=Data$fulldata[[g]],
itemloc=itemloc, cand.t.var=cand.t.var, CUSTOM.IND=CUSTOM.IND,
prior.t.var=gstructgrouppars[[g]]$gcov, OffTerm=OffTerm,
prior.mu=gstructgrouppars[[g]]$gmeans, prodlist=prodlist)
if(is.null(list$cand.t.var)){
if(i > 5L){
pa <- attr(gtheta0[[g]],"Proportion Accepted")
PAs[i-5L] <- pa
CTVs[i-5L] <- cand.t.var
cand.t.var <- update_cand.var(PAs, CTVs)
}
}
}
}
if(RAND) OffTerm <- OffTerm(random, J=J, N=N)
if(list$plausible.draws > 0L){
ret <- vector('list', list$plausible.draws)
for(i in seq_len(length(ret))){
for(j in seq_len(MHDRAWS))
gtheta0[[1L]] <- draw.thetas(theta0=gtheta0[[1L]],
pars=pars[[1L]], fulldata=Data$fulldata[[1L]],
itemloc=itemloc, cand.t.var=cand.t.var, CUSTOM.IND=CUSTOM.IND,
prior.t.var=gstructgrouppars[[g]]$gcov, OffTerm=OffTerm,
prior.mu=gstructgrouppars[[g]]$gmeans, prodlist=prodlist)
ret[[i]] <- gtheta0[[1L]]
}
ret <- lapply(ret, function(x){
attr(x, "Proportion Accepted") <- attr(x, "log.lik") <- attr(x, "log.lik_full") <- NULL
x
})
return(ret)
}
SEM.stores <- matrix(0, SEMCYCLES, nfullpars)
SEM.stores2 <- vector('list', SEMCYCLES)
conv <- 0L
k <- 1L
gamma <- .2
longpars <- rep(NA,nfullpars)
for(g in seq_len(ngroups)){
for(i in seq_len(J+1L))
longpars[pars[[g]][[i]]@parnum] <- pars[[g]][[i]]@par
if(RAND){
for(i in seq_len(length(random)))
longpars[random[[i]]@parnum] <- random[[i]]@par
}
if(LRPARS)
longpars[lrPars@parnum] <- lrPars@par
if(LR.RAND){
for(i in seq_len(length(lr.random)))
longpars[lr.random[[i]]@parnum] <- lr.random[[i]]@par
}
}
names(longpars) <- names(estpars)
stagecycle <- 1L
converge <- TRUE
L <- Ls$L
redun_constr <- Ls$redun_constr
estindex_unique <- index[estpars & !redun_constr]
if(any(attr(L, 'diag')[!estpars] > 0L)){
redindex <- index[!estpars]
stop('Constraint applied to fixed parameter(s) ',
paste(paste0(redindex[attr(L, 'diag')[!estpars] > 0L]), ''), ' but should only be applied to
estimated parameters. Please fix!', call.=FALSE)
}
tmp <- Matrix::rowSums(L)
tmp[tmp == 0L] <- 1L
check <- as.numeric(L %*% longpars) / tmp
longpars[estpars] <- check[estpars]
LBOUND <- UBOUND <- c()
for(g in seq_len(ngroups)){
for(i in seq_len(J+1L)){
LBOUND <- c(LBOUND, pars[[g]][[i]]@lbound)
UBOUND <- c(UBOUND, pars[[g]][[i]]@ubound)
}
}
if(RAND){
for(i in seq_len(length(random))){
LBOUND <- c(LBOUND, random[[i]]@lbound)
UBOUND <- c(UBOUND, random[[i]]@ubound)
}
}
if(LRPARS){
LBOUND <- c(LBOUND, lrPars@lbound)
UBOUND <- c(UBOUND, lrPars@ubound)
}
if(LR.RAND){
for(i in seq_len(length(lr.random))){
LBOUND <- c(LBOUND, lr.random[[i]]@lbound)
UBOUND <- c(UBOUND, lr.random[[i]]@ubound)
}
}
aveAR <- vector('list', NCYCLES)
control$fnscale <- -1
if(is.null(control$maxit)) control$maxit <- 15
if(list$Moptim == 'BFGS')
if(any(is.finite(LBOUND[estindex_unique]) | is.finite(UBOUND[estindex_unique])))
list$Moptim <- 'L-BFGS-B'
for(g in seq_len(ngroups))
for(i in seq_len(J))
pars[[g]][[i]]@dat <- Data$fulldata[[g]][, c(itemloc[i]:(itemloc[i+1L] - 1L))]
Draws.time <- Mstep.time <- 0
for(cycles in seq_len(NCYCLES + BURNIN + SEMCYCLES))
{
if(cycles == BURNIN + 1L) stagecycle <- 2L
if(stagecycle == 3L)
gamma <- gain_fun(gain, t = cycles - SEMCYCLES - BURNIN - 1L)
if(cycles == (BURNIN + SEMCYCLES + 1L)){
stagecycle <- 3L
longpars <- colMeans(SEM.stores)
if(!no_stage_3){
Tau <- SEM.stores2[[1L]]/SEMCYCLES
if(SEMCYCLES > 1L){
for(i in 2L:SEMCYCLES)
Tau <- Tau + SEM.stores2[[i]]/SEMCYCLES
}
}
k <- KDRAWS
gamma <- 0
}
if(list$SE) longpars <- list$startlongpars
tmp <- MHRM.reloadPars(longpars=longpars, pars=pars, gstructgrouppars=gstructgrouppars,
ngroups=ngroups, J=J, has_graded=has_graded, cycles=cycles,
LRPARS=LRPARS, LR.RAND=LR.RAND, RANDSTART=RANDSTART,
RAND=RAND, lrPars=lrPars, lr.random=lr.random, random=random)
pars <- with(tmp, pars)
gstructgrouppars <- with(tmp, gstructgrouppars)
lr.random <- with(tmp, lr.random)
random <- with(tmp, random)
lrPars <- with(tmp, lrPars)
if(cycles == (BURNIN + SEMCYCLES + 1L) && no_stage_3){
cycles <- cycles + SEMCYCLES - 1L
break
}
start <- proc.time()[3L]
tmp <- MHRM.draws(pars=pars, lrPars=lrPars, lr.random=lr.random, random=random,
gstructgrouppars=gstructgrouppars, RAND=RAND, LR.RAND=LR.RAND,
RANDSTART=RANDSTART, gtheta0=gtheta0, OffTerm=OffTerm, J=J, N=N, cycles=cycles,
itemloc=itemloc, CUSTOM.IND=CUSTOM.IND, Data=Data, nfact=nfact,
prodlist=prodlist, ngroups=ngroups, MHDRAWS=MHDRAWS, BURNIN=BURNIN,
SEMCYCLES=SEMCYCLES, cand.t.var=cand.t.var, list=list, verbose=verbose)
lr.random <- with(tmp, lr.random)
random <- with(tmp, random)
gtheta0 <- with(tmp, gtheta0)
OffTerm <- with(tmp, OffTerm)
printmsg <- with(tmp, printmsg)
if(stagecycle == 3L)
aveAR[[cycles - SEMCYCLES - BURNIN]] <- tmp$AR
cand.t.var <- with(tmp, cand.t.var)
gthetatmp <- gtheta0
if(length(prodlist))
gthetatmp <- lapply(gtheta0, function(x, prodlist) prodterms(x, prodlist),
prodlist=prodlist)
if(all(!estpars)) break
Draws.time <- Draws.time + proc.time()[3L] - start
start <- proc.time()[3L]
longpars0 <- longpars
tmp <- MHRM.Mstep(pars=pars, gtheta=gthetatmp, lrPars=lrPars, OffTerm=OffTerm, longpars=longpars,
USE.FIXED=USE.FIXED, list=list, ngroups=ngroups, LR.RAND=LR.RAND,
DERIV=DERIV, gstructgrouppars=gstructgrouppars, nfact=nfact,
CUSTOM.IND=CUSTOM.IND, RAND=RAND, cycles=cycles, lr.random=lr.random,
RANDSTART=RANDSTART, random=random, J=J, LRPARS=LRPARS, L=L, has_graded=has_graded,
constrain=constrain, estpars=estpars, redun_constr=redun_constr,
estindex_unique=estindex_unique,LBOUND=LBOUND, UBOUND=UBOUND,
gfulldata=Data$fulldata, itemloc=itemloc, control=control)
grad <- tmp$grad
ave.h <- tmp$hess
correction <- tmp$correction
if(stagecycle < 3L){
correction[correction > 1] <- 1
correction[correction < -1] <- -1
longpars[estindex_unique] <- longpars[estindex_unique] + gamma*correction
if(any(longpars < LBOUND))
longpars[longpars < LBOUND] <- (longpars0[longpars < LBOUND] + LBOUND[longpars < LBOUND])/2
if(any(longpars > UBOUND))
longpars[longpars > UBOUND] <- (longpars0[longpars > UBOUND] + UBOUND[longpars > UBOUND])/2
if(length(constrain))
for(i in seq_len(length(constrain)))
longpars[constrain[[i]][-1L]] <- longpars[constrain[[i]][1L]]
if(verbose)
cat(printmsg, sprintf(", Max-Change = %.4f", max(abs(gamma*correction))), sep='')
if(stagecycle == 2L){
SEM.stores[cycles - BURNIN, ] <- longpars
if(!no_stage_3)
SEM.stores2[[cycles - BURNIN]] <- ave.h
}
Mstep.time <- Mstep.time + proc.time()[3L] - start
next
}
Tau <- Tau + gamma*(ave.h - Tau)
if(list$Moptim == 'NR1'){
correction <- try(solve(Tau, grad), TRUE)
if(is(correction, 'try-error')){
Tau.inv <- MPinv(Tau)
correction <- as.vector(grad %*% Tau.inv)
}
} else correction <- tmp$correction
longpars[estindex_unique] <- longpars0[estindex_unique] + gamma*correction
if(any(longpars < LBOUND))
longpars[longpars < LBOUND] <- (longpars0[longpars < LBOUND] + LBOUND[longpars < LBOUND])/2
if(any(longpars > UBOUND))
longpars[longpars > UBOUND] <- (longpars0[longpars > UBOUND] + UBOUND[longpars > UBOUND])/2
if(length(constrain))
for(i in seq_len(length(constrain)))
longpars[constrain[[i]][-1L]] <- longpars[constrain[[i]][1L]]
if(verbose)
cat(printmsg, sprintf(", gam = %.4f, Max-Change = %.4f",
gamma, max(abs(gamma*correction))), sep='')
if(hasConverged(longpars0, longpars, TOL)) conv <- conv + 1L
else conv <- 0L
if(!list$SE && conv >= 3L) break
if(list$SE.type == 'MHRM' && list$SE &&
cycles >= (400L + BURNIN + SEMCYCLES) && conv >= 3L) break
if(cycles == (BURNIN + SEMCYCLES + 1L)){
if(list$SE.type == 'MHRM'){
phi <- grad
Phi <- ave.h
} else phi <- Phi <- 0
}
if(list$SE.type != 'none' && list$SE){
if(list$SE.type == 'MHRM'){
phi <- phi + gamma*(grad - phi)
Phi <- Phi + gamma*(ave.h - outer(grad,grad) - Phi)
} else if(list$SE.type == 'FMHRM'){
phi <- phi + 1/NCYCLES * grad
Phi <- Phi + 1/NCYCLES * (ave.h - outer(grad,grad))
}
}
Mstep.time <- Mstep.time + proc.time()[3L] - start
}
if(verbose) cat('\r\n')
if(cycles == NCYCLES + BURNIN + SEMCYCLES && !list$SE && !no_stage_3){
if(list$message)
message('MHRM terminated after ', NCYCLES, ' iterations.')
converge <- FALSE
}
if(list$SE) longpars <- list$startlongpars
tmp <- MHRM.reloadPars(longpars=longpars, pars=pars, gstructgrouppars=gstructgrouppars,
ngroups=ngroups, J=J, has_graded=has_graded, cycles=cycles,
LRPARS=LRPARS, LR.RAND=LR.RAND, RANDSTART=RANDSTART,
RAND=RAND, lrPars=lrPars, lr.random=lr.random, random=random)
pars <- with(tmp, pars)
gstructgrouppars <- with(tmp, gstructgrouppars)
lr.random <- with(tmp, lr.random)
random <- with(tmp, random)
lrPars <- with(tmp, lrPars)
fail_invert_info <- TRUE
if(list$SE){
info <- Phi + outer(phi,phi)
acov <- try(solve(info), TRUE)
if(is(acov, 'try-error')){
if(list$warn)
warning('Could not invert information matrix; may not be identified.',
call.=FALSE)
} else {
fail_invert_info <- FALSE
SEtmp <- diag(acov)
if(any(SEtmp < 0))
SEtmp[SEtmp < 0 ] <- NaN
SEtmp <- sqrt(SEtmp)
SE <- rep(NA, length(longpars))
SE[estindex_unique] <- SEtmp
if(length(constrain) > 0L)
for(i in seq_len(length(constrain)))
SE[constrain[[i]][-1L]] <- SE[constrain[[i]][1L]]
for(g in seq_len(ngroups)){
for(i in seq_len(J+1L))
pars[[g]][[i]]@SEpar <- SE[pars[[g]][[i]]@parnum]
}
if(RAND){
for(i in seq_len(length(random)))
random[[i]]@SEpar <- SE[random[[i]]@parnum]
}
if(LRPARS){
lrPars@SEpar <- SE[lrPars@parnum]
}
if(LR.RAND){
for(i in seq_len(length(lr.random)))
lr.random[[i]]@SEpar <- SE[lr.random[[i]]@parnum]
}
}
}
if(any(estpars)){
names(correction) <- names(estpars)[estindex_unique]
if(list$SE) info <- nameInfoMatrix(info=info, correction=correction, L=L, npars=ncol(L))
else info <- matrix(0, 1L, 1L)
} else {
info <- matrix(0, 1L, 1L)
cycles <- BURNIN + SEMCYCLES
}
ret <- list(pars=pars, cycles = cycles-BURNIN-SEMCYCLES, info=if(list$expl) matrix(0) else as.matrix(info),
correction=correction, longpars=longpars, converge=converge, SElogLik=0, cand.t.var=cand.t.var,
L=L, random=random, lrPars=lrPars, lr.random=lr.random, aveAR=colMeans(do.call(rbind, aveAR)),
time=c(MH_draws = as.numeric(Draws.time), Mstep=as.numeric(Mstep.time)),
estindex_unique=estindex_unique, shortpars=longpars[estpars & !redun_constr],
fail_invert_info=fail_invert_info, Prior=vector('list', ngroups), collectLL=NaN)
ret
} |
compute_stepdownmaxT = function (distribution, alternative) {
alternative <- match.arg(alternative, c("two.sided","greater","less"))
switch (alternative,
"greater" = {
test_rank <- rank(-distribution[1,])
test_order <- sort(unique(test_rank))
p_corrected <-
lapply(seq_along(test_order),function(testi){
ri <- test_order[testi]
coltesti <- which(test_rank==ri)
coldistri <-which(test_rank>=ri)
pvali <- sapply(distribution[1,coltesti],
function(stati){
di = apply(distribution[,which(test_rank>=ri),drop=F],1,max)
compute_pvalue(di, stat = stati,alternative= alternative)})
cbind(cols = coltesti, pvalues = pvali)
})
},
"less" = {
test_rank <- rank(distribution[1,])
test_order <- sort(unique(test_rank))
p_corrected <-
lapply(seq_along(test_order),function(testi){
ri <- test_order[testi]
coltesti <- which(test_rank==ri)
coldistri <-which(test_rank>=ri)
pvali <- sapply(distribution[1,coltesti],
function(stati){
di = apply(distribution[,which(test_rank>=ri),drop=F],1,min)
compute_pvalue(di, stat = stati,alternative= alternative)})
cbind(cols = coltesti, pvalues = pvali)
})
},
"two.sided" = {
test_rank <- rank(-abs(distribution[1,]))
test_order <- sort(unique(test_rank))
p_corrected <-
lapply(seq_along(test_order),function(testi){
ri <- test_order[testi]
coltesti <- which(test_rank==ri)
coldistri <-which(test_rank>=ri)
pvali <- sapply(distribution[1,coltesti],
function(stati){
di = apply(abs(distribution[,which(test_rank>=ri),drop=F]),1,max)
compute_pvalue(di, stat = stati,alternative= alternative)})
cbind(cols = coltesti, pvalues = pvali)
})
}
)
p_corrected = do.call("rbind",p_corrected)
p_corrected = cbind(p_corrected,cummax = cummax(p_corrected[,2]))
p_corrected = p_corrected[order(p_corrected[,1]),]
out <- list(main = cbind(statistic = distribution[1, ], pvalue = p_corrected[,3]))
return(out)
} |
context("Auxiliary functions")
test_that("Output is as expected", {
expect_equal(currentGitHubRef("GuangchuangYu/badger"), "GuangchuangYu/badger")
expect_equal(assembleBadgeOutput("X", "Y", "Z"), "[](https://Y)")
}) |
'small_vgm' |
l_navgraph <- function(data, separator=":", graph=NULL, ...) {
if(!is.data.frame(data)) {
data <- as.data.frame(data)
}
tt <- l_toplevel()
if (is.null(graph)) {
G <- completegraph(nodes=names(data))
LG <- linegraph(G, sep=separator)
LGnot <- loon::complement(LG)
cmb <- utils::combn(names(data),2)
CompG <- completegraph(nodes=apply(cmb[,cmb[1,]!=cmb[2,]],2,
FUN=function(x)paste(x, collapse=separator)))
g <- l_graph(LG, parent=tt)
} else {
g <- l_graph(graph, parent=tt)
}
tktitle(tt) <- paste("loon navigation graph", "--path:", g)
gs <- l_graphswitch(activewidget=g, parent=tt)
if (is.null(graph)) {
l_graphswitch_add(gs, graph=LG, label="3d transition")
l_graphswitch_add(gs, graph=LGnot, label="4d transition")
l_graphswitch_add(gs, graph=CompG, label="3d and 4d transition")
} else {
gid <- l_graphswitch_add(gs, graph=graph, label="user specified")
}
tkpack(gs, side='right', fill='y')
tkpack(g, side='right', fill='both', expand=TRUE)
navigator <- l_navigator_add(g, label="default navgraph")
context <- l_context_add_geodesic2d(navigator, data=data, separator=separator)
plot <- strsplit(context['command'], " ", fixed = TRUE)[[1]][1]
class(plot) <- c("l_plot", "loon")
args <- list(...)
if (length(args)>0) {
l_configure(plot, ...)
}
navgraph <- list(graph=g, plot=plot, graphswitch=gs,
navigator=navigator, context=context)
class(navgraph) <- c("l_navgraph", "l_compound", "loon")
navgraph
}
l_getPlots.l_navgraph <- function(target){
list(graph = target$graph, plot = target$plot)
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(rviewgraph)
oldgui = rViewGraph(sample(1:10,10,TRUE),sample(1:10,10,TRUE))
is.null(oldgui)
if (interactive() && !is.null(oldgui))
{
oldgui.stop()
oldgui.hide()
}
v = vg()
is.null(v)
edges = function(g)
{
dim(g$getEdges())[1] / 2
}
logProb = function(g,a)
{
-edges(g)*a
}
flip = function(g,x,y)
{
if (g$connects(x,y))
g$disconnect(x,y)
else
g$connect(x,y)
}
step = function(g, a, t = 1)
{
delta = logProb(g,a)
x = sample(g$getVertices(),2,replace=FALSE)
g$colour(x,"red")
Sys.sleep(t/3)
flip(g,x[1],x[2])
Sys.sleep(t/3)
delta = logProb(g,a) - delta
if (log(runif(1)) > delta)
flip(g,x[1],x[2])
g$colour(x)
Sys.sleep(t/3)
}
set.seed(1)
n = 20
v$add(1:n)
pen = 0
if (interactive())
{
wait = 1
s = 50
} else
{
wait = 0
s = 1000
for (i in 1:s)
step(v,pen,wait)
}
medge = 0
for (i in 1:s)
{
step(v,pen,wait)
medge = medge + edges(v)
}
c(medge/s, n*(n-1)/4)
pen = 1
medge = 0
for (i in 1:s)
{
step(v,pen,wait)
medge = medge + edges(v)
}
medge/s
pen = -1
medge = 0
for (i in 1:s)
{
step(v,pen,wait)
medge = medge + edges(v)
}
medge/s |
bbd_prob <- function(t, a0, b0, lambda1, lambda2, mu2, gamma, A, B,
nblocks=256, tol=1e-12, computeMode=0, nThreads=4,
maxdepth=400) {
if (a0 < 0) stop("a0 cannot be negative.")
if (a0 > A) stop("a0 cannot be bigger than A.")
if (b0 < 0) stop("b0 cannot be negative.")
if (b0 > B) stop("b0 cannot be bigger than B.")
if (t < 0) stop("t cannot be negative.")
if (t < tol) {
res = matrix(0, nrow=A-a0+1, ncol=B+1)
res[1,b0+1] = 1
colnames(res) = 0:B
rownames(res) = a0:A
return(res)
}
grid = expand.grid(a0:A,0:(B+maxdepth))
l1 = matrix(mapply(lambda1, grid[,1], grid[,2]), ncol=B+1+maxdepth)
l2 = matrix(mapply(lambda2, grid[,1], grid[,2]),ncol=B+1+maxdepth)
m2 = matrix(mapply(mu2, grid[,1], grid[,2]), ncol=B+1+maxdepth)
g = matrix(mapply(gamma, grid[,1], grid[,2]), ncol=B+1+maxdepth)
xf <- function(a,b){
if (b==0) x = 1
else x = - l2[a-a0+1,b]*m2[a-a0+1,b+1]
return(x)
}
x = matrix(mapply(xf, grid[,1], grid[,2]), nrow=B+1+maxdepth, byrow=TRUE)
yf <- function(a,b) {
y = l1[a-a0+1,b+1] + l2[a-a0+1,b+1] + m2[a-a0+1,b+1] + g[a-a0+1,b+1]
return(y)
}
y = matrix(mapply(yf, grid[,1], grid[,2]), nrow=B+1+maxdepth, byrow=TRUE)
res = matrix(bbd_lt_invert_Cpp(t, a0, b0, l1, l2, m2, g, x, y, A, B+1,
nblocks, tol, computeMode, nThreads, maxdepth),
nrow=(A-a0+1), byrow=T)
colnames(res) = 0:B
rownames(res) = a0:A
return(abs(res))
} |
context("`dat` object getters and setters")
test_that("`dat` getters and setter", {
dat <- list(
attr = list(
active = rbinom(100, 1, 0.9)
),
epi = list(),
param = list(),
init = list(),
control = list(
nsteps = 150
)
)
dat <- add_attr(dat, "age")
expect_equal(dat$attr$age, rep(NA, length(dat$attr$active)))
expect_error(dat <- add_attr(dat, "age"))
expect_error(set_attr(dat, "age", 4))
new_ages <- runif(length(dat$attr$active))
dat <- set_attr(dat, "age", new_ages)
expect_equal(dat$attr$age, new_ages)
dat <- set_attr(dat, "age2", new_ages)
expect_silent(dat <- set_attr(dat, "age2", rep(new_ages, 2),
override.length.check = TRUE))
expect_length(get_attr(dat, "age2"), 2 * length(new_ages))
expect_equal(get_attr(dat, "age"), new_ages)
expect_equal(get_attr(dat, "age", c(1, 5)), new_ages[c(1, 5)])
expect_equal(get_attr(dat, "age", new_ages > 0.5), new_ages[new_ages > 0.5])
expect_error(get_attr(dat, "age_absent"))
expect_null(get_attr(dat, "age_absent", override.null.error = TRUE))
expect_error(get_attr(dat, "age", c(1, 1000)))
expect_error(get_attr(dat, "age", c(TRUE, FALSE)))
expect_silent(
dat <- set_attr(dat, "status", rbinom(length(dat$attr$active), 1, 0.4))
)
expect_silent(dat <- set_attr(dat, "age", 2, posit_ids = 1:4))
expect_equal(get_attr(dat, "age", 1:4), rep(2, 4))
posit_ids <- c(rep(TRUE, 4), rep(FALSE, length(dat$attr$active) - 4))
expect_silent(dat <- set_attr(dat, "age", 6, posit_ids = posit_ids))
expect_equal(get_attr(dat, "age", 1:4), rep(6, 4))
expect_error(dat <- set_attr(dat, "age", c(1, 2), posit_ids = 1:4))
expect_error(dat <- set_attr(dat, "age", 1, posit_ids = c(1, 1000)))
expect_error(dat <- set_attr(dat, "age", 1, posit_ids = c("a", "b")))
expect_error(dat <- set_attr(dat, "age", c(1, 2), posit_ids = c(TRUE, FALSE)))
expect_equal(get_attr_list(dat), dat$attr)
expect_equal(get_attr_list(dat, c("age", "status")),
dat$attr[c("age", "status")])
expect_error(get_attr_list(dat, "sex"))
expect_error(dat <- append_attr(dat, "status",
rbinom(length(dat$attr$active), 10)))
expect_error(dat <- append_attr(dat, "status", 1, -1))
dat <- append_attr(dat, "active", 1, 10)
expect_length(get_attr(dat, "active"), 110)
dat <- append_attr(dat, "status", sample(0:1, 10, TRUE), 10)
expect_length(get_attr(dat, "status"), 110)
dat <- add_epi(dat, "i")
expect_equal(dat$epi$i, rep(NA, dat$control$nsteps))
expect_error(set_epi(dat, "i", c(1, 4), 4))
dat <- set_epi(dat, "i", 150, 10)
expect_equal(dat$epi$i[150], 10)
dat <- set_epi(dat, "s", 110, 10)
expect_equal(dat$epi$s[110], 10)
expect_equal(get_epi(dat, "i", c(1, 100)), dat$epi$i[c(1, 100)])
expect_equal(get_epi(dat, "i", dat$epi$i > 0.5), dat$epi$i[dat$epi$i > 0.5])
expect_error(get_epi(dat, "age_absent"))
expect_null(get_epi(dat, "age_absent", override.null.error = TRUE))
expect_error(get_epi(dat, "i", c(1, 300)))
expect_error(get_epi(dat, "i", c(TRUE, FALSE)))
dat$control$nsteps <- 200
dat <- set_epi(dat, "i", 160, 8)
expect_length(dat$epi$i, 200)
expect_equal(get_epi_list(dat), dat$epi)
expect_equal(get_epi_list(dat, c("i", "s")), dat$epi[c("i", "s")])
expect_error(get_epi_list(dat, "r"))
dat <- add_param(dat, "x")
dat <- add_init(dat, "x")
dat <- add_control(dat, "x")
expect_equal(dat$param$x, NA)
expect_equal(dat$init$x, NA)
expect_equal(dat$control$x, NA)
expect_silent(dat <- set_param(dat, "y", 4))
expect_silent(dat <- set_init(dat, "y", 4))
expect_silent(dat <- set_control(dat, "y", 4))
dat <- set_param(dat, "y", 5)
dat <- set_init(dat, "y", 5)
dat <- set_control(dat, "y", 5)
expect_equal(dat$param$y, 5)
expect_equal(dat$init$y, 5)
expect_equal(dat$control$y, 5)
expect_equal(get_param(dat, "y"), 5)
expect_equal(get_init(dat, "y"), 5)
expect_equal(get_control(dat, "y"), 5)
expect_error(get_param(dat, "z"))
expect_error(get_init(dat, "z"))
expect_error(get_control(dat, "z"))
expect_null(get_param(dat, "z", override.null.error = TRUE))
expect_null(get_init(dat, "z", override.null.error = TRUE))
expect_null(get_control(dat, "z", override.null.error = TRUE))
expect_equal(get_param_list(dat), dat$param)
expect_equal(get_init_list(dat), dat$init)
expect_equal(get_control_list(dat), dat$control)
expect_equal(get_param_list(dat, "x"), dat$param["x"])
expect_equal(get_init_list(dat, "x"), dat$init["x"])
expect_equal(get_control_list(dat, "x"), dat$control["x"])
expect_error(get_param_list(dat, "z"))
expect_error(get_init_list(dat, "z"))
expect_error(get_control_list(dat, "z"))
})
test_that("Net core attributes", {
dat <- list(
attr = list(),
epi = list(),
param = list(),
init = list(),
control = list(
nsteps = 150
)
)
dat <- append_core_attr(dat, at = 1, n.new = 100)
expect_equal(get_attr(dat, "active"), rep(1, 100))
expect_equal(get_attr(dat, "unique_id"), 1:100)
dat <- delete_attr(dat, 21:30)
dat <- append_core_attr(dat, at = 2, n.new = 100)
expect_equal(get_attr(dat, "active"), rep(1, 190))
expect_equal(get_attr(dat, "unique_id"), c(1:20, 31:200))
expect_type(get_attr(dat, "unique_id"), "integer")
expect_equal(
get_attr(dat, "unique_id"),
get_unique_ids(dat, seq_along(get_attr(dat, "active")))
)
expect_equal(
seq_along(get_attr(dat, "active")),
get_posit_ids(dat, get_attr(dat, "unique_id"))
)
expect_warning(get_posit_ids(dat, 25:35))
}) |
plot.multicut <-
function(x, which = NULL, cut, sort,
las, ylab="Relative abundance", xlab="Strata",
show_I=TRUE, show_S=TRUE, hr=TRUE, tick=TRUE,
theme, mar=c(5, 4, 4, 4) + 0.1, bty="o",
lower=0, upper=1, pos=0, horizontal=TRUE, ...)
{
if (missing(las))
las <- if (horizontal) 1 else 2
if (pos < -1 || pos > 1)
stop("BTW, pos must be in [-1, 1]")
if (lower < 0 || lower > 1)
stop("BTW, lower must be in [0, 1]")
if (upper < lower || lower > 1)
stop("BTW, upper must be in [lower, 1]")
if (missing(cut))
cut <- getOption("ocoptions")$cut
if (missing(sort))
sort <- getOption("ocoptions")$sort
if (is.logical(sort)) {
sort_r <- sort[1L]
sort_c <- sort[1L]
} else {
sort_r <- 1 %in% sort
sort_c <- 2 %in% sort
}
if (!is.null(which)) {
x$species <- x$species[which]
}
ss <- summary(x)
xx <- ss$summary
bp <- ss$mu
bp <- t(apply(bp, 1, function(z) (z-min(z)) / max(z-min(z))))
bp01 <- ss$bestpart
if (!any(xx$logLR >= cut)) {
warning("All logLR < cut: cut ignored")
rkeep <- rep(TRUE, nrow(xx))
} else {
rkeep <- xx$logLR >= cut
}
if (sort_r) {
bp <- bp[attr(ss$bestpart, "row.order")[rkeep],,drop=FALSE]
bp01 <- bp01[attr(ss$bestpart, "row.order")[rkeep],,drop=FALSE]
xx <- xx[attr(ss$bestpart, "row.order")[rkeep],,drop=FALSE]
}
if (sort_c) {
dm <- diag(1, ncol(bp), ncol(bp))
for (i in seq_len(ncol(bp))) {
for (j in i:ncol(bp)) {
dm[i,j] <- dm[j,i] <- sum(bp[,i] * bp[,j]) / nrow(bp)
}
}
corder <- hclust(as.dist(1 - dm), method = "ward.D2")$order
bp <- bp[,corder,drop=FALSE]
bp01 <- bp01[,corder,drop=FALSE]
}
n <- nrow(bp)
p <- ncol(bp)
Cols <- occolors(theme)(100)
lower <- min(max(lower, 0), 1)
op <- par(las=las, mar=mar)
on.exit(par(op))
if (horizontal) {
plot(0, xlim=c(0, p), ylim=c(n, 0),
type="n", axes=FALSE, ann=FALSE, ...)
title(ylab=ylab, xlab=xlab)
axis(1, at=seq_len(p)-0.5, lwd=0, lwd.ticks=1,
labels=colnames(bp), tick=tick, ...)
axis(2, at=seq_len(n)-0.5, lwd=0, lwd.ticks=1,
labels=rownames(bp), tick=tick, ...)
if (show_S)
axis(3, at=seq_len(ncol(bp))-0.5,
labels=colSums(bp01), tick=FALSE, ...)
if (show_I)
axis(4, at=seq_len(n)-0.5,
labels=format(round(xx$I, 2), nsmall=2), tick=FALSE, ...)
if (hr)
abline(h=1:n-0.5, col=Cols[1L], lwd=0.45)
} else {
plot(0, ylim=c(0, p), xlim=c(n, 0),
type="n", axes=FALSE, ann=FALSE, ...)
title(ylab=xlab, xlab=ylab)
axis(2, at=seq_len(p)-0.5, lwd=0, lwd.ticks=1,
labels=colnames(bp), tick=tick, ...)
axis(1, at=seq_len(n)-0.5, lwd=0, lwd.ticks=1,
labels=rownames(bp), tick=tick, ...)
if (show_S)
axis(4, at=seq_len(ncol(bp))-0.5,
labels=colSums(bp01), tick=FALSE, ...)
if (show_I)
axis(3, at=seq_len(n)-0.5,
labels=format(round(xx$I, 2), nsmall=2), tick=FALSE, ...)
if (hr)
abline(v=1:n-0.5, col=Cols[1L], lwd=0.45)
}
for (i in seq_len(n)) {
for (j in seq_len(p)) {
Max <- 0.5*xx$I[i]+0.5
Min <- 0.5*(1-xx$I[i])
h0 <- bp[i,j] * (Max - Min) + Min
h <- h0 * c(1 - lower) + lower
ColID <- as.integer(pmin(pmax(1, floor(h0 * 100) + 1), 100))
adj <- h * -pos
if (horizontal) {
polygon(
c(0, 1, 1, 0) + j - 1,
upper * 0.5 * (adj + c(-h, -h, h, h)) + i - 0.5,
col=Cols[ColID], border=Cols[ColID], lwd=0.5)
} else {
polygon(
upper * 0.5 * (adj + c(-h, -h, h, h)) + i - 0.5,
c(0, 1, 1, 0) + j - 1,
col=Cols[ColID], border=Cols[ColID], lwd=0.5)
}
}
}
box(col="grey", bty=bty)
invisible(list(summary=xx, bestpart=bp01, mu=bp))
} |
NULL
NULL
setMethod("t", signature(x="madness"),
function(x) {
xtag <- x@xtag
val <- t(x@val)
dvdx <- .do_commutator(val,x@dvdx)
vtag <- paste0('t(',x@vtag,')')
varx <- x@varx
new("madness", val=val, dvdx=dvdx, vtag=vtag, xtag=xtag, varx=varx)
})
setMethod("tril", signature(x="madness"),
function(x,k=0) {
xtag <- x@xtag
val <- x@val
takeus <- row(val) >= col(val) - k
val[!takeus] <- 0
dvdx <- x@dvdx
dvdx[which(!takeus),] <- 0
vtag <- paste0('tril(',x@vtag,', ',k,')')
varx <- x@varx
new("madness", val=val, dvdx=dvdx, vtag=vtag, xtag=xtag, varx=varx)
})
setMethod("triu", signature(x="madness"),
function(x,k=0) {
xtag <- x@xtag
val <- x@val
takeus <- row(val) <= col(val) - k
val[!takeus] <- 0
dvdx <- x@dvdx
dvdx[which(!takeus),] <- 0
vtag <- paste0('triu(',x@vtag,', ',k,')')
varx <- x@varx
new("madness", val=val, dvdx=dvdx, vtag=vtag, xtag=xtag, varx=varx)
})
setMethod("dim<-", signature(x="madness",value="ANY"),
function(x,value) {
xtag <- x@xtag
val <- x@val
dim(val) <- value
dvdx <- x@dvdx
vtag <- paste0('reshape(',x@vtag,', ',
as.character(enquote(value))[2],
')')
varx <- x@varx
new("madness", val=val, dvdx=dvdx, vtag=vtag, xtag=xtag, varx=varx)
})
setMethod("[", signature(x="madness",i="ANY",j="ANY"),
function(x,i,j,...,drop) {
getidx <- vector(length=length(x@val))
dim(getidx) <- dim(x@val)
getidx[i,j,...] <- TRUE
val <- x@val[i,j,...,drop=FALSE]
dvdx <- x@dvdx[which(getidx),,drop=FALSE]
retv <- new("madness", val=val, dvdx=dvdx,
xtag=x@xtag,
vtag=paste0(x@vtag,'[...]'),
varx=x@varx)
})
setMethod("[", signature(x="madness",i="ANY",j="missing"),
function(x,i,j,...,drop) {
getidx <- vector(length=length(x@val))
dim(getidx) <- dim(x@val)
getidx[i,...] <- TRUE
val <- x@val[i,...,drop=FALSE]
dvdx <- x@dvdx[which(getidx),,drop=FALSE]
retv <- new("madness", val=val, dvdx=dvdx,
xtag=x@xtag,
vtag=paste0(x@vtag,'[...]'),
varx=x@varx)
})
aperm.madness <- function(a, perm=NULL, resize=TRUE, ...) {
xtag <- a@xtag
val <- aperm(a@val,perm=perm,resize=resize)
oldids <- array(1:length(a@val),dim=dim(a@val))
prmids <- aperm(oldids,perm=perm,resize=resize)
dvdx <- a@dvdx[as.numeric(prmids),,drop=FALSE]
vtag <- paste0('aperm(',a@vtag,', ',as.character(enquote(perm))[2],')')
varx <- a@varx
new("madness", val=val, dvdx=dvdx, vtag=vtag, xtag=xtag, varx=varx)
} |
context("METAR cloud coverage")
x1 <- "EPWA 281830Z 18009KT 140V200 9999 SCT037 03/M01 Q1008 NOSIG"
x2 <- "CYUL 281800Z 13008KT 30SM BKN240 01/M06 A3005 RMK CI5 SLP180"
x3 <- "201711271930 METAR LEMD 271930Z 02002KT CAVOK 04/M03 Q1025 NOSIG= NOSIG="
x4 <- "201905121244 METAR KDCA 121244Z 05010KT 1 3/4SM R01/6000VP6000FT -RA BR OVC007 14/12 A2978 RMK AO2 P0002 T01390122"
x5 <- "201905121244 SPECI KDCA 121244Z 05010KT 2 1/4SM R01/6000VP6000FT -RA BR OVC007 14/12 A2978 RMK AO2 P0002 T01390122"
x6 <- "CYWG 172000Z 30015G25KT 3/4SM R36/4000FT/D -SN BLSN BKN008 OVC040 M05/M08 A2992 REFZRA WS RWY36 RMK SF5NS3 SLP134"
x7 <- "METAR KJFK 282355Z AUTO 13009KT 10SM -RA SCT028 SCT035 BKN079 23/20 A2972 RMK T02300200 LTG DSNT SE-SW! MADISHF"
x8 <- "RJTT 192000Z 36009KT 9999 FEW025 BKN/// 23/19 Q1013 NOSIG RMK 1SC025 A2993"
x <- c(x1, x2, x3, x4, x5, x6, x7, x8)
dx <- data.frame(metar = x)
test_that("Check cloud coverage output", {
expect_equal(metar_cloud_coverage("EPWA 281830Z 18009KT 140V200 9999 SCT037 03/M01 Q1008 NOSIG"),
"Scattered (3-4 oktas) at 3700 ft (1127.76 m)")
expect_equal(metar_cloud_coverage("CYUL 281800Z 13008KT 30SM BKN240 01/M06 A3005 RMK CI5 SLP180"),
"Broken (5-7 oktas) at 24000 ft (7315.2 m)")
expect_equal(metar_cloud_coverage("METAR CYUL 281800Z 13008KT 30SM BKN240 01/M06 A3005 RMK CI5 SLP180"),
"Broken (5-7 oktas) at 24000 ft (7315.2 m)")
expect_equal(metar_cloud_coverage("SPECI CYUL 281800Z 13008KT 30SM BKN240 01/M06 A3005 RMK CI5 SLP180"),
"Broken (5-7 oktas) at 24000 ft (7315.2 m)")
expect_equal(metar_cloud_coverage(x7),
"Scattered (3-4 oktas) at 2800, 3500 ft (853.44, 1066.8 m), Broken (5-7 oktas) at 7900 ft (2407.92 m)")
expect_equal(metar_cloud_coverage(x8),
"Few (1-2 oktas) at 2500 ft (762 m), Broken clouds at NaN ft ( m)")
expect_equal(metar_cloud_coverage("201711271930 METAR LEMD 271930Z 02002KT CAVOK 04/M03 Q1025 NOSIG= NOSIG="), "")
expect_equal(metar_cloud_coverage("201711271930 SPECI LEMD 271930Z 02002KT CAVOK 04/M03 Q1025 NOSIG= NOSIG="), "")
expect_is(metar_cloud_coverage(x), "character")
expect_is(metar_cloud_coverage(dx$metar), "character")
})
x8 <- "SPECI CYUL 281800Z 13008KT 30SM BKN24 01/M06 A3005 RMK CI5 SLP180"
x9 <- "METAR CYUL 281800Z 13008KT 30SM BKN24 BKN300 01/M06 A3005 RMK CI5 SLP180"
x10 <- "SPECI CYUL 281800Z 13008KT 30SM BKNBKN 01/M06 A3005 RMK CI5 SLP180"
test_that("Incorrect METAR reports", {
expect_equal(metar_cloud_coverage(x8), "")
expect_equal(metar_cloud_coverage(x9),
"Broken (5-7 oktas) at 30000 ft (9144 m)")
expect_equal(metar_cloud_coverage(x10), "")
})
dx <- data.frame(metar = c(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10))
test_that("Correct and incorrect METAR reports", {
expect_is(metar_cloud_coverage(dx$metar), "character")
expect_equal(metar_cloud_coverage(dx$metar)[2], "Broken (5-7 oktas) at 24000 ft (7315.2 m)")
expect_equal(metar_cloud_coverage(dx$metar)[10], "")
})
dxt <- tibble::as_tibble(dx)
test_that("Check invalid input format", {
expect_error(metar_cloud_coverage(dx))
expect_error(metar_cloud_coverage(dxt))
}) |
plot.plsreg1 <-
function(x, what = "variables", comps = c(1,2), where=c("t","t"),
cex = 1, col.xlabels = "
yfont=2, pos=NULL, offset=0.1,
col.xarrows = "
lwd=3, length = 0, angle = 0,
col.points = "
show.names = FALSE, xpd=TRUE,
xlab = NULL, ylab = NULL, main = NULL, col.main="gray35",
cex.main=1.2, col.axis = "gray40",
show.grid = TRUE, col.grid = "gray95", ...)
{
if (!is.numeric(comps) || length(comps)>2)
comps = 1:2
nc = ncol(x$x.scores)
if (!comps[1] %in% 1:nc || !(comps[2] %in% 1:nc))
stop("\nInvalid vector of components")
k1 = comps[1]
k2 = comps[2]
p = nrow(x$cor.xyt)
if (what == "variables")
{
z = seq(0, 2*pi, l=100)
op = par(oma = rep(0,4), mar = c(4,3,3,2), pty = "s", xpd=xpd)
plot.new()
plot.window(xlim=c(-1.1,1.1), ylim=c(-1.1,1.1), asp=1)
axis(side=1, labels=FALSE, lwd=0, lwd.ticks=1, col="gray75")
mtext(seq(-1, 1, 0.5), side=1, at=seq(-1, 1, 0.5), line=0.5,
col=col.axis, cex=0.8)
axis(side=2, labels=FALSE, lwd=0, lwd.ticks=1, col="gray75")
mtext(seq(-1, 1, 0.5), side=2, at=seq(-1, 1, 0.5), line=0.7,
col=col.axis, cex=0.8, las=2)
box(col="gray70")
if (show.grid)
abline(h=seq(-1, 1, 0.5), v=seq(-1, 1, 0.5), col=col.grid, xpd=FALSE)
if (is.null(xlab)) xlab = paste("axis", k1)
if (is.null(ylab)) ylab = paste("axis", k2)
mtext(xlab, side=1, at=0, line=2.5, col=col.axis)
mtext(ylab, side=2, at=0, line=2.5, col=col.axis)
lines(cos(z), sin(z), lwd=2, col="gray90")
segments(-1, 0, 1, 0, col="gray90")
segments(0, -1, 0, 1, col="gray90")
col.arrows = c(rep(col.xarrows, p-1), col.yarrows)
arrows(x0=rep(0,p), y0=rep(0,p), x1=x$cor.xyt[,k1], y1=x$cor.xyt[,k2],
length=length, angle=angle, lwd=lwd, col=col.arrows)
if (is.null(pos))
{
neg <- x$cor.xyt[,k1] < 0
pos = rep(4, p)
pos[neg] = 2
}
col.labels = c(rep(col.xlabels, p-1), col.ylabel)
fonts = c(rep(1,p-1), yfont)
text(x$cor.xyt[,k1], x$cor.xyt[,k2], labels=rownames(x$cor.xyt),
font=fonts, col=col.labels, cex=cex, pos=pos, offset=offset, ...)
if (is.null(main))
main = "Circle of Correlations"
mtext(main, side=3, at=par("usr")[1], line=1, adj=0, cex=cex.main, col=col.main)
par(op)
} else {
if (!is.character(where) || length(where)>2)
where = c("t","t")
waux = paste(where, collapse="")
tmp = grep(waux, c("tt", "tu", "uu"))
if (length(tmp) == 0)
stop("\nInvalid argument 'where'")
ws = switch(as.character(tmp),
'1' = cbind(x$x.scores[,k1], x$x.scores[,k2]),
'2' = cbind(x$x.scores[,k1], x$y.scores[,k2]),
'3' = cbind(x$y.scores[,k1], x$y.scores[,k2]))
axlabs = switch(as.character(tmp),
'1' = c("t","t"),
'2' = c("t","u"),
'3' = c("u","u"))
if (is.null(xlab))
xlab = paste(axlabs[1], k1, sep="_")
if (is.null(ylab))
ylab = paste(axlabs[2], k2, sep="_")
plot(ws[,1], ws[,2], type="n", axes=FALSE,
xlab=xlab, ylab=ylab, col.lab=col.axis)
axis(side=1, col.axis=col.axis, col=col.axis, lwd=0.5, cex.axis=0.9)
axis(side=2, las=2, col.axis=col.axis, col=col.axis, lwd=0.5, cex.axis=0.9)
abline(h=0, v=0, col="gray90", lwd=2)
box(col="gray70")
if (!show.names)
{
points(ws[,1], ws[,2], col=col.points, pch=pch, bg=pt.bg,
lwd=1.5, cex=cex)
} else {
text(ws[,1], ws[,2], labels=rownames(x$x.scores),
col=col.xlabels, cex=cex, pos=pos, offset=offset, ...)
}
if (is.null(main))
main = "Map of Observations"
mtext(main, side=3, at=par("usr")[1], line=1, adj=0, cex=cex.main, col=col.main)
}
} |
library(testthat)
library(rlang)
context("MARS models")
data("two_class_dat", package = "modeldata")
test_that('check mars opt', {
set.seed(36323)
check_pruning <- function(x, ...) {
rlang::eval_tidy(x$call$pmethod) == "backward"
}
mod_1 <-
bagger(
mpg ~ .,
data = mtcars,
base_model = "MARS",
control = control_bag(var_imp = FALSE, extract = check_pruning),
pmethod = "backward"
)
expect_true(all(unlist(mod_1$model_df$extras)))
expect_true(is.null(mod_1$imp))
check_folds <- function(x, ...) {
rlang::eval_tidy(x$call$pmethod) == "backward" &
rlang::eval_tidy(x$call$nfold) == "5" &
is.null(x$glm.coefficients)
}
mod_2 <-
bagger(
mpg ~ .,
data = mtcars,
base_model = "MARS",
control = control_bag(var_imp = TRUE, extract = check_folds),
nfold = 5,
pmethod = "backward"
)
expect_true(all(unlist(mod_2$model_df$extras)))
expect_true(inherits(mod_2$imp, "tbl_df"))
check_classif <- function(x, ...) {
!is.null(x$glm.coefficients)
}
if (compareVersion(as.character(getRversion()), "3.6.0") > 0) {
expect_warning(RNGkind(sample.kind = "Rounding"))
}
set.seed(2234)
expect_warning(
mod_3 <-
bagger(
Class ~ .,
data = two_class_dat,
base_model = "MARS",
control = control_bag(var_imp = TRUE, extract = check_classif)
),
"fitted probabilities numerically 0"
)
expect_true(all(unlist(mod_3$model_df$extras)))
expect_true(inherits(mod_3$imp, "tbl_df"))
})
test_that('check model reduction', {
set.seed(36323)
reduced <-
bagger(
mpg ~ .,
data = mtcars,
base_model = "MARS",
times = 3
)
expect_false(is.matrix(reduced$model_df$model[[1]]$fit$y))
expect_equal(reduced$model_df$model[[1]]$fit$call, rlang::call2("dummy_call"))
expect_equal(reduced$model_df$model[[1]]$fit$residuals, numeric(0))
set.seed(36323)
full <-
bagger(
mpg ~ .,
data = mtcars,
base_model = "MARS",
times = 3,
control = control_bag(reduce = FALSE)
)
expect_true(is.matrix(full$model_df$model[[1]]$fit$y))
expect_true(is.call(full$model_df$model[[1]]$fit$call))
expect_true(is.matrix(full$model_df$model[[1]]$fit$residuals))
})
test_that('check MARS parsnip interface', {
set.seed(4779)
expect_error(
reg_mod <- bag_mars(num_terms = 5, prod_degree = 2) %>%
set_engine("earth", times = 3) %>%
set_mode("regression") %>%
fit(mpg ~ ., data = mtcars),
regexp = NA
)
expect_true(
all(purrr::map_lgl(reg_mod$fit$model_df$model, ~ inherits(.x, "model_fit")))
)
expect_true(
all(purrr::map_lgl(reg_mod$fit$model_df$model, ~ inherits(.x$fit, "earth")))
)
expect_error(
reg_mod_pred <- predict(reg_mod, mtcars[1:5, -1]),
regexp = NA
)
expect_true(tibble::is_tibble(reg_mod_pred))
expect_equal(nrow(reg_mod_pred), 5)
expect_equal(names(reg_mod_pred), ".pred")
set.seed(4779)
expect_error(
reg_class <- bag_mars(num_terms = 5, prod_degree = 2) %>%
set_engine("earth", times = 3) %>%
set_mode("classification") %>%
fit(Class ~ ., data = two_class_dat),
regexp = NA
)
expect_true(
all(purrr::map_lgl(reg_class$fit$model_df$model, ~ inherits(.x, "model_fit")))
)
expect_true(
all(purrr::map_lgl(reg_class$fit$model_df$model, ~ inherits(.x$fit, "earth")))
)
expect_error(
reg_class_pred <- predict(reg_class, two_class_dat[1:5, -3]),
regexp = NA
)
expect_true(tibble::is_tibble(reg_class_pred))
expect_equal(nrow(reg_class_pred), 5)
expect_equal(names(reg_class_pred), ".pred_class")
expect_error(
reg_class_prob <- predict(reg_class, two_class_dat[1:5, -3], type = "prob"),
regexp = NA
)
expect_true(tibble::is_tibble(reg_class_prob))
expect_equal(nrow(reg_class_prob), 5)
expect_equal(names(reg_class_prob), c(".pred_Class1", ".pred_Class2"))
expect_output(print(bag_mars(num_terms = 3)))
expect_equal(update(bag_mars(), num_terms = 3), bag_mars(num_terms = 3))
expect_equal(update(bag_mars(), prod_degree = 1), bag_mars(prod_degree = 1))
expect_equal(update(bag_mars(), prune_method = "none"), bag_mars(prune_method = "none"))
}) |
ir_df_us <- function(quandlkey = quandlkey, ir.sens = 0.01) {
if (!requireNamespace("Quandl", quietly = TRUE)) {
stop("Package \"Quandl\" needed for this function to work. Please install it.",
call. = FALSE
)
}
Quandl::Quandl.api_key(quandlkey)
fedsfund <- tidyquant::tq_get("FED/RIFSPFF_N_D", get = "quandl", from = Sys.Date() - 30) %>%
stats::na.omit() %>%
dplyr::transmute(date = date, FedsFunds0 = log((1 + value / (360))^365))
zero_1yrplus <- Quandl::Quandl("FED/SVENY") %>% dplyr::rename(date = Date)
zero_tb <- c("FED/RIFLGFCM01_N_B", "FED/RIFLGFCM03_N_B", "FED/RIFLGFCM06_N_B") %>%
tidyquant::tq_get(get = "quandl", from = Sys.Date() - 30) %>%
stats::na.omit() %>%
tidyr::pivot_wider(names_from = symbol, values_from = value)
x <- dplyr::inner_join(fedsfund, zero_tb, c("date")) %>% dplyr::inner_join(zero_1yrplus, c("date"))
x <- x %>%
dplyr::filter(date == dplyr::last(date)) %>%
dplyr::select(-date)
x <- x %>%
t() %>%
as.data.frame() %>%
dplyr::transmute(yield = V1 / 100, maturity = readr::parse_number(colnames(x)))
x$maturity[1] <- 1 / 365
x$maturity[2:4] <- x$maturity[2:4] / 12
x <- dplyr::add_row(x, yield = x$yield[1], maturity = 0, .before = 1)
x <- x %>% dplyr::mutate(
discountfactor = exp(-yield * maturity),
discountfactor_plus = exp(-(yield + ir.sens) * maturity),
discountfactor_minus = exp(-(yield - ir.sens) * maturity)
)
return(x)
} |
iRafNet_network <- function(out.iRafNet,out.perm,TH) {
M<-dim(out.perm)[2];
j.np<-sort(out.iRafNet[,3],decreasing=TRUE)
FDR<-rep(0,dim(out.perm)[1]);
for (s in 1:length(j.np)){
FP<-sum(sum(out.perm>=j.np[s]))/M
FDR[s]<-FP/s;
if (FDR[s]>TH) {th<-j.np[s]; break;}
}
return(out.iRafNet[out.iRafNet[,3]>th,seq(1,2)])
} |
rasch.copula3.covariance <- function( f.qk.yi, Sigma, theta.k, N,
mu.fixed, variance.fixed, D, est.corr, irtmodel,
freqwgt ){
Sigma.cov <- Sigma
delta.theta <- 1
indD <- rep( 1:nrow(f.qk.yi), freqwgt )
hwt <- f.qk.yi[ indD, ]
N <- sum( freqwgt)
thetabar <- hwt%*%theta.k
mu <- rep(0,D)
theta.k.adj <- theta.k
for (dd1 in 1:D){
for (dd2 in dd1:D){
tk <- theta.k.adj[,dd1]*theta.k.adj[,dd2]
h1 <- ( hwt %*% tk ) * delta.theta
Sigma.cov[dd1,dd2] <- sum( h1 ) / N
if (dd1 < dd2 ){ Sigma.cov[dd2,dd1] <- Sigma.cov[dd1,dd2] }
}
}
Sigma.cov0 <- Sigma.cov
if ( est.corr ){ Sigma.cov <- stats::cov2cor(Sigma.cov ) }
if ( ! is.null(variance.fixed ) ){
Sigma.cov[ variance.fixed[,1:2,drop=FALSE] ] <- variance.fixed[,3]
Sigma.cov[ variance.fixed[,c(2,1),drop=FALSE] ] <- variance.fixed[,3]
}
diag(Sigma.cov) <- diag(Sigma.cov) + 10^(-10)
pi.k <- sirt_dmvnorm_discrete( theta.k, mean=mu, sigma=Sigma.cov, as_matrix=TRUE )
res <- list( "mu"=mu, "Sigma"=Sigma.cov, "pi.k"=pi.k,
"Sigma0"=Sigma.cov0)
return(res)
} |
selection_table <- function(X, max.dur = 10, path = NULL, whole.recs = FALSE,
extended = FALSE, confirm.extended = TRUE, mar = 0.1, by.song = NULL, pb = TRUE, parallel = 1, ...)
{
on.exit(pbapply::pboptions(type = .Options$pboptions$type), add = TRUE)
argms <- methods::formalArgs(selection_table)
opt.argms <- if(!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0
names(opt.argms)[names(opt.argms) == "wav.path"] <- "path"
opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms]
call.argms <- as.list(base::match.call())[-1]
opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)]
if (length(opt.argms) > 0)
for (q in 1:length(opt.argms))
assign(names(opt.argms)[q], opt.argms[[q]])
if (is.null(path)) path <- getwd() else
if (!dir.exists(path)) stop("'path' provided does not exist")
if (!is.null(by.song))
if (!any(names(X) == by.song)) stop("'by.song' column not found")
if (!is.numeric(parallel)) stop("'parallel' must be a numeric vector of length 1")
if (any(!(parallel %% 1 == 0),parallel < 1)) stop("'parallel' should be a positive integer")
if (whole.recs){
sound.files <- list.files(path = path, pattern = "\\.wav$", ignore.case = TRUE)
if (length(sound.files) == 0) stop("No sound files were found")
X <- data.frame(sound.files, selec = 1, channel = 1, start = 0, end = duration_wavs(files = sound.files, path = path)$duration)
}
if (pb) write(file = "", x ="checking selections (step 1 of 2):")
check.results <- warbleR::check_sels(X, path = path, wav.size = TRUE, pb = pb, ...)
if (any(check.results$check.res != "OK")) stop("Not all selections can be read (use check_sels() to locate problematic selections)")
X <- check.results[ , names(check.results) %in% names(X)]
class(X) <- unique(append("selection_table", class(X)))
check.results <- check.results[, names(check.results) %in% c("sound.files", "selec", by.song, "check.res", "duration", "min.n.sample", "sample.rate", "channels", "bits", "wav.size", "sound.file.samples")]
if (extended)
{
exp.size <- sum(round(check.results$bits * check.results$sample.rate * (check.results$duration + (mar * 2)) / 4) / 1024 )
if (confirm.extended){
cat(crayon::magenta(paste0("Expected 'extended_selection_table' size is ~", ifelse(round(exp.size) == 0, round(exp.size, 2), round(exp.size)), "MB (~", round(exp.size/1024, 5), " GB) \n Do you want to proceed? (y/n): \n")))
answer <- readline(prompt = "")
} else answer <- "yeah dude!"
if (substr(answer, 1, 1) %in% c("y", "Y"))
{
check.results$orig.start <- X$start
check.results$orig.end <- X$end
check.results$mar.after <- check.results$mar.before <- rep(mar, nrow(X))
dur <- duration_wavs(files = as.character(X$sound.files), path = path)$duration
for(i in 1:nrow(X))
{
if (X$start[i] < mar) check.results$mar.before[i] <- X$start[i]
if (X$end[i] + mar > dur[i]) check.results$mar.after[i] <- dur[i] - X$end[i]
}
if (!is.null(by.song))
{
Y <- song_analysis(X = as.data.frame(X), song_colm = by.song, pb = FALSE)
Y <-Y[, names(Y) %in% c("sound.files", by.song, "start", "end")]
check.results$song <- X[, by.song]
check.results$song.TEMP <- paste(X$sound.files, X[, by.song], sep = "-")
Y$song.TEMP <- paste(Y$sound.files, Y[, by.song], sep = "-")
Y$mar.before <- sapply(unique(Y$song.TEMP), function(x) check.results$mar.before[which.min(check.results$orig.start[check.results$song.TEMP == x])])
Y$mar.after <- sapply(unique(Y$song.TEMP), function(x) check.results$mar.after[which.max(check.results$orig.end[check.results$song.TEMP == x])])
check.results$song.TEMP <- NULL
} else {
Y <- X
Y$mar.before <- check.results$mar.before
Y$mar.after <- check.results$mar.after
}
pbapply::pboptions(type = ifelse(pb, "timer", "none"))
if (Sys.info()[1] == "Windows" & parallel > 1)
cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) else cl <- parallel
if (pb) write(file = "", x ="saving wave objects into extended selection table (step 2 of 2):")
attributes(X)$wave.objects <- pbapply::pblapply(1:nrow(Y), cl = cl, function(x) warbleR::read_wave(X = Y, index = x, from = Y$start[x] - Y$mar.before[x], to = Y$end[x] + Y$mar.after[x], path = path))
check.results$start <- X$start <- check.results$mar.before
check.results$end <- X$end <- check.results$mar.before + check.results$duration
names(check.results)[names(check.results) == "sound.files"] <- "orig.sound.files"
names(check.results)[names(check.results) == "selec"] <- "orig.selec"
if (!is.null(by.song))
{
names(attributes(X)$wave.objects) <- paste0(Y$sound.files, "-song_", Y[ , by.song])
X$sound.files <- check.results$sound.files <- paste0(X$sound.files, "-song_", as.data.frame(X)[ , names(X) == by.song,])
for(i in unique(X$sound.files))
check.results$selec[check.results$sound.files == i] <- X$selec[X$sound.files == i] <- 1:nrow(X[X$sound.files == i, drop = FALSE])
check.results$n.samples <- NA
durs <- X$end - X$start
for(w in unique(X$sound.files))
{
check.results$start[check.results$sound.files == w] <- X$start[X$sound.files == w] <- X$start[X$sound.files == w][which.min(check.results$orig.start[check.results$sound.files == w])] + (check.results$orig.start[check.results$sound.files == w] - min(check.results$orig.start[check.results$sound.files == w]))
check.results$n.samples[check.results$sound.files == w] <- length(attr(X, "wave.objects")[[which(names(attr(X, "wave.objects")) == w)]]@left)
}
check.results$end <- X$end <- X$start + durs
} else
{
names(attributes(X)$wave.objects) <- check.results$sound.files <- X$sound.files <- paste(basename(as.character(X$sound.files)), X$selec, sep = "_")
check.results$selec <- X$selec <- 1
check.results$n.samples <- as.vector(sapply(attr(X, "wave.objects"), function(x) length(x@left)))
}
class(X)[class(X) == "selection_table"] <- "extended_selection_table"
}
} else
check.results$n.samples <- check.results$sound.file.samples
check.results <- check.results[,na.omit(match(c("orig.sound.files", "orig.selec", "orig.start", "orig.end", "sound.files", "selec", "start", "end", "check.results", "duration", "sample.rate", "channels", "bits", "wav.size", "mar.before", "mar.after", "n.samples"), names(check.results)))]
attributes(X)$check.results <- check.results
if (is_extended_selection_table(X) & !is.null(by.song)) attributes(X)$by.song <- list(by.song = TRUE, song.column = by.song) else attributes(X)$by.song <- list(by.song = FALSE, song.column = by.song)
attributes(X)$warbleR.version <- packageVersion("warbleR")
if (extended & confirm.extended & !is_extended_selection_table(X)) cat(crayon::silver(crayon::bold("'extended_selection_table' was not created")))
return(X)
}
make.selection.table <- selection_table
is_selection_table <- function(x) inherits(x, "selection_table")
is_extended_selection_table <- function(x) inherits(x, "extended_selection_table")
`[.selection_table` <- function(X, i = NULL, j = NULL, drop = TRUE) {
if (is.character(i)) i <- which(row.names(X) %in% i)
if (is.character(j)) j <- which(names(X) %in% j)
if (is.null(i)) i <- 1:nrow(X)
if (is.null(j)) j <- 1:ncol(X)
Y <- as.data.frame(X)[i, j, drop = drop]
if (is.data.frame(Y))
{
attributes(Y)$check.results <- attributes(X)$check.results[i, ,]
attributes(Y)$by.song <- attributes(X)$by.song
class(Y) <- class(X)
}
return(Y)
}
`[.extended_selection_table` <- function(X, i = NULL, j = NULL, drop = TRUE) {
if (is.character(i)) i <- which(row.names(X) %in% i)
if (is.character(j)) j <- which(names(X) %in% j)
if (is.null(i)) i <- 1:nrow(X)
if (is.null(j)) j <- 1:ncol(X)
Y <- as.data.frame(X)[i, j, drop = drop]
if (is.data.frame(Y))
{
attributes(Y)$wave.objects <- attributes(X)$wave.objects[names(attributes(X)$wave.objects) %in% Y$sound.files]
attributes(Y)$check.results <-
attributes(X)$check.results[paste(attributes(X)$check.results$sound.files, attributes(X)$check.results$selec) %in% paste(Y$sound.files, Y$selec), ]
attributes(Y)$by.song <- attributes(X)$by.song
class(Y) <- class(X)
}
return(Y)
}
print.extended_selection_table <- function(x, ...) {
cat(crayon::cyan(paste("Object of class", crayon::bold("'extended_selection_table' \n"))))
cat(crayon::silver(paste(crayon::bold("Contains:"), "\n* A selection table data frame with"), nrow(x), "rows and", ncol(x), "columns: \n"))
cols <- if (ncol(x) > 6) 1:6 else 1:ncol(x)
kntr_tab <- knitr::kable(head(x[, cols]), escape = FALSE, digits = 4, justify = "centre", format = "pipe")
for(i in 1:length(kntr_tab)) cat(crayon::silver(paste0(kntr_tab[i], "\n")))
if (ncol(x) > 6) cat(crayon::silver(paste0("... ", ncol(x) - 6, " more column(s) (", paste(colnames(x)[7:ncol(x)], collapse = ", "), ")")))
if (nrow(x) > 6) cat(crayon::silver(paste0(if (ncol(x) <= 6) "..." else "", " and ", nrow(x) - 6, " more row(s) \n")))
cat(crayon::silver(paste0("\n* ", length(attr(x, "wave.objects"))," wave objects (as attributes): ")))
cat(crayon::silver(head(names(attr(x, "wave.objects")))))
if (length(attr(x, "wave.objects")) > 6) cat(crayon::silver(paste0("... and ", length(attr(x, "wave.objects")) - 6, " more")))
cat("\n ")
cat(crayon::silver("\n* A data frame (check.results) generated by check_sels() (as attribute) \n"))
if (attr(x, "by.song")[[1]]) cat(crayon::silver(paste0( crayon::bold("\nAdditional information:"), "\n* The selection table was created", crayon::italic(crayon::bold(" by song ")), "(see 'class_extended_selection_table') \n"))) else
cat(crayon::silver(paste0("\nThe selection table was created", crayon::italic(crayon::bold(" by element ")), "(see 'class_extended_selection_table') \n")))
smp.rts <- unique(attr(x, "check.results")$sample.rate)
if (length(smp.rts) == 1)
cat(crayon::silver(paste0("* ", length(smp.rts), " sampling rate(s) (in kHz): ", paste(crayon::bold(smp.rts), collapse = "/"), " \n"))) else
cat(crayon::red(paste0("* ", length(smp.rts), " sampling rate(s): ", paste(crayon::bold(smp.rts), collapse = "/"), " \n")))
bt.dps <- unique(attr(x, "check.results")$bits)
if (length(bt.dps) == 1)
cat(crayon::silver(paste0("* ", length(bt.dps), " bit depth(s): ", paste(crayon::bold(bt.dps), collapse = "/"), " \n"))) else
cat(crayon::red(paste0("* ", length(bt.dps), " bit depth(s): ", paste(crayon::bold(bt.dps), collapse = "/"), " \n")))
if (!is.null(attr(x, "warbleR.version")))
cat(crayon::silver(paste0("* Created by warbleR ", attr(x, "warbleR.version")))) else
cat(crayon::silver("* Created by warbleR < 1.1.21"))
}
print.selection_table <- function(x, ...) {
cat(crayon::cyan(paste("Object of class", crayon::bold("'selection_table' \n"))))
cat(crayon::silver(paste(crayon::bold("\nContains:"), "\n* A selection table data frame with"), nrow(x), "rows and", ncol(x), "columns: \n"))
cols <- if (ncol(x) > 6) 1:6 else 1:ncol(x)
kntr_tab <- knitr::kable(head(x[, cols]), escape = FALSE, digits = 4, justify = "centre", format = "pipe")
for(i in 1:length(kntr_tab)) cat(crayon::silver(paste0(kntr_tab[i], "\n")))
if (ncol(x) > 6) cat(crayon::silver(paste0("... ", ncol(x) - 6, " more column(s) (", paste(colnames(x)[7:ncol(x)], collapse = ", "), ")")))
if (nrow(x) > 6) cat(crayon::silver(paste0(if (ncol(x) <= 6) "..." else "", " and ", nrow(x) - 6, " more row(s) \n")))
cat(crayon::silver("\n * A data frame (check.results) generated by check_sels() (as attribute) \n"))
if (!is.null(attr(x, "warbleR.version")))
cat(crayon::silver(paste0("created by warbleR ", attr(x, "warbleR.version")))) else
cat(crayon::silver("created by warbleR < 1.1.21"))
}
fix_extended_selection_table <- function(X, Y){
if (!is_extended_selection_table(Y)) stop("Y must be a extended selection table")
attributes(X)$wave.objects <- attributes(Y)$wave.objects[names(attributes(Y)$wave.objects) %in% X$sound.files]
attributes(X)$check.results <- attributes(Y)$check.results[attributes(Y)$check.results$sound.files %in% X$sound.files, ]
xtr.attr <- setdiff(names(attributes(Y)[!sapply(attributes(Y), is.null)]), c("names", "row.names", "check.results", "wave.objects", "dim", "dimnames"))
if (length(xtr.attr) > 0)
for(i in xtr.attr) attr(X, i) <- attr(Y, i)
return(X)
}
rbind.selection_table <- function(..., deparse.level = 1) {
mcall <- list(...)
X <- mcall[[1]]
Y <- mcall[[2]]
if (!is_selection_table(X) | !is_selection_table(Y)) stop("both objects must be of class 'selection_table'")
if (any(paste(X$sound.files, X$selec) %in% paste(Y$sound.files, Y$selec))) stop("Some sound files/selec are found in both selection tables")
cl.nms <- intersect(names(X), names(Y))
W <- rbind(as.data.frame(X[ , cl.nms, drop = FALSE]), as.data.frame(Y[ , cl.nms, drop = FALSE]), make.row.names = TRUE,
stringsAsFactors = FALSE)
cl.nms.cr <- intersect(names(attr(X, "check.results")), names(attr(Y, "check.results")))
attr(W, "check.results") <- rbind(attr(X, "check.results")[ , cl.nms.cr, drop = FALSE], attr(Y, "check.results")[ , cl.nms.cr, drop = FALSE], make.row.names = TRUE, stringsAsFactors = FALSE)
attr(W, "by.song") <- attr(X, "by.song")
class(W) <- class(X)
return(W)
}
rbind.extended_selection_table <- function(..., deparse.level = 1) {
mcall <- list(...)
X <- mcall[[1]]
Y <- mcall[[2]]
if (!is_extended_selection_table(X) | !is_extended_selection_table(Y)) stop("both objects must be of class 'selection_table'")
if (attr(X, "by.song")[[1]] != attr(Y, "by.song")[[1]]) stop("both objects should have been created either 'by song' or by element' (see 'by.song' argument in selection_table())")
if (any(paste(X$sound.files, X$selec) %in% paste(Y$sound.files, Y$selec))) stop("Some sound files/selec are found in both extended selection tables")
waves.X <- names(attr(X, "wave.objects"))
waves.Y <- names(attr(Y, "wave.objects"))
if (any(waves.X %in% waves.Y)) cat("Some wave object names are found in both extended selection tables, they are assumed to refer to the same wave object and only one copy will be kept (use rename_est_waves() to change sound file/wave objetc names if needed)")
cl.nms <- intersect(names(X), names(Y))
W <- rbind(as.data.frame(X[ , cl.nms, drop = FALSE]), as.data.frame(Y[ , cl.nms, drop = FALSE]), make.row.names = TRUE)
cl.nms.cr <- intersect(names(attr(X, "check.results")), names(attr(Y, "check.results")))
attr(W, "check.results") <- rbind(attr(X, "check.results")[ , cl.nms.cr, drop = FALSE], attr(Y, "check.results")[ , cl.nms.cr, drop = FALSE], make.row.names = TRUE)
attr(W, "wave.objects") <- c(attr(X, "wave.objects"), attr(Y, "wave.objects"))
attr(W, "by.song") <- attr(X, "by.song")
class(W) <- class(X)
attr(W, "wave.objects") <- attr(W, "wave.objects")[!duplicated(names(attr(W, "wave.objects")))]
attributes(W)$warbleR.version <- packageVersion("warbleR")
return(W)
} |
app <- ShinyDriver$new("../", seed = 1)
app$snapshotInit("basicCreateDOE")
app$setInputs(tabs = "spotConfig")
try(app$setInputs(tabs = "runMode"), silent = T)
try(app$setInputs(runCreateDOE = "click"), silent = T)
try(app$setInputs(evaluateData = "click"), silent = T)
app$snapshot(list(output = "resultTable")) |
`traj.stats` <-
function(infolist, morestats, pvallist, cboxes=c(1:length(infolist$box)), showbounds=TRUE,style=style){
dimsum <- vector(length=length(cboxes))
for (i in 1:length(cboxes)){
dimsum[i] <- sum(infolist$dimlist[[cboxes[i]]]$either)
}
statmat <- cbind(cboxes,infolist$y.mean[cboxes],infolist$marcoverage[cboxes],infolist$mass[cboxes],dimsum)
colnames(statmat) <- c("box index", "density", "coverage", "support","dims")
cat("\n")
cat(" Summary statistics for candidate boxes","\n")
cat("\n")
print(statmat)
cat("\n")
ire <- 0
if(showbounds){
for (i in cboxes){
ire <- ire+1
cat(paste(" Box",i, " Remove Variable Stats"),"\n")
mat <- boxformat(infolist$box[[i]],infolist$dimlist[[i]],morestats[[ire]],pvallist[[i]],style=style)
print(mat[,-4])
cat("\n")
}
}
return(list(statmat,mat))
} |
fread_bib <- function(file.bib,
check.dup.keys = TRUE,
strip.braces = TRUE,
check.unescaped.percent = TRUE,
.bib_expected = TRUE,
halt = TRUE,
rstudio = FALSE,
.report_error) {
stopifnot(length(file.bib) == 1L)
check_TF(check.dup.keys)
check_TF(strip.braces)
check_TF(check.unescaped.percent)
check_TF(.bib_expected)
if (is.null(halt)) {
halt <- getOption("TeXCheckR.halt_on_error")
}
check_TF(halt)
check_TF(rstudio)
if (XOR(.bib_expected, endsWith(file.bib, ".bib"))) {
warning("File extension is not '.bib'.")
}
if (missing(.report_error)) {
.report_error <- report2console
}
bib <-
read_lines(file.bib) %>%
stri_trim_both %>%
.[!startsWith(., "@Comment")]
is_at <- startsWith(bib, "@")
is_closing <- bib == "}"
if (!any(is_at) || !any(is_closing)) {
message("`file.bib = ", file.bib, "` had no bib entries. ",
"Returning empty data.table.")
return(data.table())
}
sep <- NULL
for (sep_candidate in c("\t", "^", "|")){
if (!any(grepl(sep_candidate, bib, fixed = TRUE))){
sep <- sep_candidate
break
}
}
if (is.null(sep)){
stop("No suitable separator found for bibliography file. That is, all candidates tried already appeared in the file")
}
bib_just_key_and_fields <- bib
bib_just_key_and_fields[is_closing] <- ""
bib_just_key_and_fields[is_at] <- sub("@", "key = ", bib_just_key_and_fields[is_at], fixed = TRUE)
bib_just_key_and_fields <- sub("={", "= {", bib_just_key_and_fields, fixed = TRUE)
bib_just_key_and_fields <- sub(" = ", sep, bib_just_key_and_fields, fixed = TRUE)
used_line_nos <- which(nzchar(bib_just_key_and_fields))
bib_just_key_and_fields <- bib_just_key_and_fields[used_line_nos]
x <- line_no <- NULL
bibDT <- setDT(list(line_no = used_line_nos,
x = bib_just_key_and_fields))
field <- value <- NULL
bibDT[, c("field", "value") := tstrsplit(x, sep, fixed = TRUE)]
is_key <- NULL
bibDT[, is_key := field == "key"]
key_value <- NULL
bibDT[(is_key), key_value := tolower(sub("^.*\\{", "", value, perl = TRUE))]
if (check.dup.keys && anyDuplicated(stats::na.omit(bibDT[["key_value"]]))) {
duplicates <- duplicated_rows(bibDT, by = "key_value", na.rm = TRUE)
if (getOption("TeXCheckR.messages", TRUE)) {
print(duplicates[, "bib_file" := file.bib])
}
.report_error(file = file.bib,
line_no = if (!is.null(duplicates[["line_no"]])) first(duplicates[["line_no"]]),
context = first(duplicates[["value"]]),
error_message = "Duplicate bib key used.",
advice = paste0("Compare the two entries above. If they are identical, delete one. ",
"If they are distinct, choose a different bib key. ",
"(Note: keys are case-insensitive.)"),
halt = halt,
rstudio = rstudio)
}
bibDT[, key_value := NULL]
key_line <- entry_type <- NULL
bibDT[(is_key), key_line := value]
bibDT[, key_line := zoo::na.locf(key_line, na.rm = FALSE)]
bibDT <- bibDT[(!is_key)]
bibDT[, x := NULL]
bibDT[, lapply(.SD, stri_trim_both)]
bibDT[, key_line := sub(",$", "", key_line, perl = TRUE)]
bibDT[, c("entry_type", "key") := tstrsplit(key_line, "{", fixed = TRUE)]
bibDT[, field := tolower(stri_trim_both(field))]
if (strip.braces) {
bibDT[, value := gsub("[{}]", "", value, perl = TRUE)]
}
bibDT[, value := sub(",$", "", value, perl = TRUE)]
dups <- NULL
duplicate_fields <-
bibDT[, .(dups = anyDuplicated(field)), by = key]
if (any(duplicate_fields[["dups"]])){
keys <-
duplicate_fields %>%
.[as.logical(dups)] %>%
.[["key"]]
n_keys <- length(keys)
if (n_keys <= 5L){
top_keys <- keys
stop("Duplicate fields found in ", paste0(keys, collapse = " "), ".")
} else {
top_keys <- keys[1:5]
if (n_keys == 6L){
stop("Duplicate fields found in ", paste0(keys, collapse = " "), ".")
} else {
stop("Duplicate fields found in ", paste0(keys, collapse = " "), " and ", n_keys - 5L, " others.")
}
}
}
if (check.unescaped.percent) {
unescaped_percent <-
bibDT[field != "url"][grep("(?<!(?:\\\\))[%]", value, perl = TRUE)]
if (nrow(unescaped_percent)) {
orig_file.bib <- read_lines(file.bib)
first_line_no <- unescaped_percent[1L][["line_no"]]
first_bad_text <- orig_file.bib[first_line_no]
column <-
first_bad_text %>%
stri_locate_all_regex_no_stri("(?<!(?:\\\\))[%]") %>%
.[[1L]] %>%
.[1, "start"] %>%
as.vector
first_bad_field <- unescaped_percent[1L][["field"]]
first_bad_key <- unescaped_percent[1L][["key"]]
.report_error(file = file.bib,
line_no = first_line_no,
column = column,
error_message = paste0("Field <", first_bad_field, "> ",
"in entry <", first_bad_key, "> ",
"contains unescaped %."),
advice = "Insert a backslash before this %.",
context = first_bad_text,
halt = halt,
caret = 2L,
rstudio = rstudio)
}
}
bibDT[, .(line_no, entry_type, key, field, value)]
}
bib2DT <- function(file.bib, to_sort = FALSE){
stopifnot(length(file.bib) == 1L)
if (!grepl("\\.bib$", file.bib)){
warning("File extension is not '.bib'.")
}
bib <-
read_lines(file.bib) %>%
stri_trim_both %>%
.[!grepl("@Comment", ., fixed = TRUE)]
is_at <- substr(bib, 0L, 1L) == "@"
is_closing <- bib == "}"
entry_no <- cumsum(is_at)
n_ats <- sum(is_at)
n_closing_braces <- sum(is_closing)
if (n_ats != n_closing_braces){
cat("@'s: ", n_ats, "\n",
"}'s: ", n_closing_braces, "\n")
stop("Unable to parse: Braces to close a bib entry should be on their own line.")
}
if (any(grepl("{,", bib[is_at], fixed = TRUE))){
cat("At line: ", grep("{,", bib[is_at], fixed = TRUE)[[1]])
stop("All bib entries must have a non-empty key.")
}
line_by_entry_no <- cumsum(is_at)
keys <- gsub("^.*\\{(.*),$", "\\1", bib[is_at], perl = TRUE)
if (uniqueN(keys) != n_ats){
stop("Number of unique keys not equal to number of key entries.")
}
is_field <-
!(is_at | is_closing | bib == "")
extract_field_from <- function(field, from){
pattern <- sprintf("%s%s%s", "^", field, "\\s+[=]\\s+[{](.*)[}],?$")
if_else(grepl(pattern, from, perl = TRUE),
gsub(pattern = pattern,
"\\1",
from),
NA_character_)
}
Line_no <- Surname <- Year <- annote <- author <- booktitle <- chapter <- crossref <- edition <-
editor <- endyear <- howpublished <- institution <- intra_key_line_no <- line_no <-
note <- number <- organization <- pages <- publisher <- related <- school <- series <- title <-
type <- volume <- Year_as_date <- Date <- NULL
bib_orig <- field_name <- NULL
data.table(line_no = seq_along(bib),
bib = bib,
line_by_entry_no = line_by_entry_no,
is_field = is_field,
is_closing = is_closing) %>%
.[, key := if_else(is_at,
gsub("^@[A-Za-z]+\\{(.*),$", "\\1", bib, perl = TRUE),
NA_character_)] %>%
.[, key := zoo::na.locf(key, na.rm = FALSE)] %>%
.[, author := extract_field_from("author", bib)] %>%
.[, title := extract_field_from("title", bib)] %>%
.[, year := extract_field_from("year", bib)] %>%
.[, date := extract_field_from("date", bib)] %>%
{
dot <- .
if (!to_sort){
out <-
dot %>%
.[, address := extract_field_from("address", bib)] %>%
.[, annote := extract_field_from("annote", bib)] %>%
.[, booktitle := extract_field_from("booktitle", bib)] %>%
.[, booktitle := extract_field_from("booktitle", bib)] %>%
.[, chapter := extract_field_from("chapter", bib)] %>%
.[, crossref := extract_field_from("crossref", bib)] %>%
.[, options := extract_field_from("options", bib)] %>%
.[, related := extract_field_from("related", bib)] %>%
.[, edition := extract_field_from("edition", bib)] %>%
.[, editor := extract_field_from("editor", bib)] %>%
.[, howpublished := extract_field_from("howpublished", bib)] %>%
.[, institution := extract_field_from("institution", bib)] %>%
.[, month := extract_field_from("month", bib)] %>%
.[, note := extract_field_from("note", bib)] %>%
.[, number := extract_field_from("number", bib)] %>%
.[, organization := extract_field_from("organization", bib)] %>%
.[, pages := extract_field_from("pages", bib)] %>%
.[, publisher := extract_field_from("publisher", bib)] %>%
.[, school := extract_field_from("school", bib)] %>%
.[, series := extract_field_from("series", bib)] %>%
.[, type := extract_field_from("type", bib)] %>%
.[, volume := extract_field_from("volume", bib)] %>%
.[, url := extract_field_from("url", bib)] %>%
.[, edition := extract_field_from("edition", bib)]
} else {
out <- dot
}
out
} %>%
.[, date := if_else(grepl("/", date, fixed = TRUE),
substr(date, 0, 4),
date)] %>%
.[, Year_as_date := if_else(grepl("[0-9]{4}", year),
paste0(year, "-01-01"),
year)] %>%
.[, Date := coalesce(date, Year_as_date)] %>%
.[, Surname := if_else(!is.na(author),
if_else(grepl("^[{]", author, perl = TRUE),
gsub("[{}]", "", author, perl = TRUE),
if_else(grepl("^[A-Z][a-z]+,", author, perl = TRUE),
author,
rev_forename_surname_bibtex(author))
),
NA_character_)] %>%
.[, intra_key_line_no := seq_len(.N), by = "key"] %>%
.[, Line_no := line_no] %>%
.[, field_name := gsub("[^a-z]", "", gsub("[=].*$", "", bib, perl = TRUE), perl = TRUE)] %>%
.[, field_name := if_else(is_at, "AT", field_name)] %>%
.[, field_name := if_else(is_closing, "}", field_name)] %>%
.[, field_name := factor(field_name,
levels = c("AT", "author", "title", "year", "date", "address", "annote",
"booktitle", "chapter", "crossref", "options", "related", "edition",
"editor", "howpublished", "institution", "month", "note", "number",
"organization", "pages", "publisher", "school", "series", "type",
"volume", "url", "Year_as_date", "Date", "Surname", "intra_key_line_no",
"Line_no", "}"),
ordered = TRUE)] %>%
.[, bib_orig := bib] %>%
.[, lapply(.SD, zoo::na.locf, na.rm = FALSE, fromLast = FALSE), by = "key", .SDcols = author:bib_orig] %>%
.[, lapply(.SD, zoo::na.locf, na.rm = FALSE, fromLast = TRUE) , by = "key", .SDcols = author:bib_orig] %>%
setorder(Surname, Date, title, field_name, Line_no) %>%
.[]
}
reorder_bib <- function(file.bib, outfile.bib = file.bib){
out_no <- bib2DT(file.bib, to_sort = TRUE)[["Line_no"]]
y <- readLines(file.bib, encoding = "UTF-8")
writeLines(y[out_no], outfile.bib, useBytes = TRUE)
} |
mlcc.reps <- function(X, numb.clusters = 2, numb.runs = 30, stop.criterion = 1, max.iter = 30,
initial.segmentations = NULL, max.dim = 4, scale = TRUE, numb.cores = NULL, estimate.dimensions = TRUE,
flat.prior = FALSE, show.warnings = FALSE) {
if (is.data.frame(X)) {
warning("X is not a matrix. Casting to matrix.")
X <- as.matrix(X)
}
if (any(is.na(X))) {
warning("Missing values are imputed by the mean of the variable")
X[is.na(X)] = matrix(apply(X, 2, mean, na.rm = TRUE), ncol = ncol(X), nrow = nrow(X),
byrow = TRUE)[is.na(X)]
}
if (any(!sapply(X, is.numeric))) {
auxi <- NULL
for (j in 1:ncol(X)) if (!is.numeric(X[, j])) {
auxi <- c(auxi, j)
}
stop(paste("\nThe following variables are not quantitative: ", auxi))
}
if (is.null(numb.cores)) {
numb.cores <- max(1, detectCores() - 1)
}
cl <- makeCluster(numb.cores)
registerDoParallel(cl)
if (scale) {
X <- scale(X)
}
i <- NULL
BICs <- NULL
segmentations <- NULL
if (is.null(initial.segmentations)) {
segmentations <- foreach(i = (1:numb.runs)) %dorng% {
MLCC.res <- mlcc.kmeans(X = X, number.clusters = numb.clusters, max.subspace.dim = max.dim,
max.iter = max.iter, estimate.dimensions = estimate.dimensions, show.warnings = show.warnings)
current.segmentation <- MLCC.res$segmentation
current.pcas <- MLCC.res$pcas
list(current.segmentation, cluster.pca.BIC(X, current.segmentation, sapply(current.pcas,
ncol), numb.clusters, max.dim = max.dim, flat.prior = flat.prior),
current.pcas)
}
} else {
segmentations <- foreach(i = (1:length(initial.segmentations))) %dorng% {
MLCC.res <- mlcc.kmeans(X = X, number.clusters = numb.clusters, max.subspace.dim = max.dim,
max.iter = max.iter, initial.segmentation = initial.segmentations[[i]],
estimate.dimensions = estimate.dimensions, show.warnings = show.warnings)
current.segmentation <- MLCC.res$segmentation
current.pcas <- MLCC.res$pcas
list(current.segmentation, cluster.pca.BIC(X, current.segmentation, sapply(current.pcas,
ncol), numb.clusters, max.dim = max.dim, flat.prior = flat.prior),
current.pcas)
}
}
stopCluster(cl)
BICs <- unlist(lapply(segmentations, function(x) x[2]))
basis <- lapply(segmentations, function(x) x[3])
segmentations <- lapply(segmentations, function(x) x[[1]])
result <- list(segmentation = segmentations[[which.max(BICs)]], BIC = BICs[which.max(BICs)],
basis = basis[[which.max(BICs)]][[1]])
class(result) <- "mlcc.reps.fit"
return(result)
} |
abort_nomatch <- function(nodes_names, ests_names) {
rlang::abort(
paste0("The node names in the semPaths graph: \n",
paste(nodes_names, collapse = ", "),
"\ndo not match the variable names in the fitted object: \n",
paste(ests_names, collapse = ", "),
"\nIf the `nodeLabels` argument was used",
"in the original `semPaths()` call, please remove it, ",
"and use the semptools::change_node_label() function",
"to change node labels.")
)
}
check_match_labels <- function(names_in, names_graph) {
if (!all(names_in %in% names_graph)) {
rlang::abort(
paste0("One or more nodes in label_list: \n",
paste(names_in, collapse = ", "),
"\ndo not match the node names in the semPaths graph: \n",
paste(names_graph, collapse = ", "))
)
}
} |
a <- 3
dd <- 33
c() |
ALEPlot <-
function(X, X.model, pred.fun, J, K = 40, NA.plot = TRUE) {
N = dim(X)[1]
d = dim(X)[2]
if (length(J) == 1) {
if (class(X[,J]) == "factor") {
X[,J] <- droplevels(X[,J])
x.count <- as.numeric(table(X[,J]))
x.prob <- x.count/sum(x.count)
K <- nlevels(X[,J])
D.cum <- matrix(0, K, K)
D <- matrix(0, K, K)
for (j in setdiff(1:d, J)) {
if (class(X[,j]) == "factor") {
A=table(X[,J],X[,j])
A=A/x.count
for (i in 1:(K-1)) {
for (k in (i+1):K) {
D[i,k] = sum(abs(A[i,]-A[k,]))/2
D[k,i] = D[i,k]
}
}
D.cum <- D.cum + D
}
else {
q.x.all <- quantile(X[,j], probs = seq(0, 1, length.out = 100), na.rm = TRUE, names = FALSE)
x.ecdf=tapply(X[,j], X[,J], ecdf)
for (i in 1:(K-1)) {
for (k in (i+1):K) {
D[i,k] = max(abs(x.ecdf[[i]](q.x.all)-x.ecdf[[k]](q.x.all)))
D[k,i] = D[i,k]
}
}
D.cum <- D.cum + D
}
}
D1D <- cmdscale(D.cum, k = 1)
ind.ord <- sort(D1D, index.return = T)$ix
ord.ind <- sort(ind.ord, index.return = T)$ix
levs.orig <- levels(X[,J])
levs.ord <- levs.orig[ind.ord]
x.ord <- ord.ind[as.numeric(X[,J])]
row.ind.plus <- (1:N)[x.ord < K]
row.ind.neg <- (1:N)[x.ord > 1]
X.plus <- X
X.neg <- X
X.plus[row.ind.plus,J] <- levs.ord[x.ord[row.ind.plus]+1]
X.neg[row.ind.neg,J] <- levs.ord[x.ord[row.ind.neg]-1]
y.hat <- pred.fun(X.model=X.model, newdata = X)
y.hat.plus <- pred.fun(X.model=X.model, newdata = X.plus[row.ind.plus,])
y.hat.neg <- pred.fun(X.model=X.model, newdata = X.neg[row.ind.neg,])
Delta.plus <- y.hat.plus-y.hat[row.ind.plus]
Delta.neg <- y.hat[row.ind.neg]-y.hat.neg
Delta <- as.numeric(tapply(c(Delta.plus, Delta.neg), c(x.ord[row.ind.plus], x.ord[row.ind.neg]-1), mean))
fJ <- c(0, cumsum(Delta))
fJ = fJ - sum(fJ*x.prob[ind.ord])
x <- levs.ord
barplot(fJ, names=x, xlab=paste("x_", J, " (", names(X)[J], ")", sep=""), ylab= paste("f_",J,"(x_",J,")", sep=""), las =3)
}
else if (class(X[,J]) == "numeric" | class(X[,J]) == "integer") {
z= c(min(X[,J]), as.numeric(quantile(X[,J],seq(1/K,1,length.out=K), type=1)))
z = unique(z)
K = length(z)-1
fJ = numeric(K)
a1=as.numeric(cut(X[,J], breaks=z, include.lowest=TRUE))
X1 = X
X2 = X
X1[,J] = z[a1]
X2[,J] = z[a1+1]
y.hat1 = pred.fun(X.model=X.model, newdata = X1)
y.hat2 = pred.fun(X.model=X.model, newdata = X2)
Delta=y.hat2-y.hat1
Delta = as.numeric(tapply(Delta, a1, mean))
fJ = c(0, cumsum(Delta))
b1 <- as.numeric(table(a1))
fJ = fJ - sum((fJ[1:K]+fJ[2:(K+1)])/2*b1)/sum(b1)
x <- z
plot(x, fJ, type="l", xlab=paste("x_",J, " (", names(X)[J], ")", sep=""), ylab= paste("f_",J,"(x_",J,")", sep=""))
}
else print("error: class(X[,J]) must be either factor or numeric or integer")
}
else if (length(J) == 2) {
if (class(X[,J[2]]) != "numeric" & class(X[,J[2]]) != "integer") {
print("error: X[,J[2]] must be numeric or integer. Only X[,J[1]] can be a factor")
}
if (class(X[,J[1]]) == "factor") {
X[,J[1]] <- droplevels(X[,J[1]])
x.count <- as.numeric(table(X[,J[1]]))
x.prob <- x.count/sum(x.count)
K1 <- nlevels(X[,J[1]])
D.cum <- matrix(0, K1, K1)
D <- matrix(0, K1, K1)
for (j in setdiff(1:d, J[1])) {
if (class(X[,j]) == "factor") {
A=table(X[,J[1]],X[,j])
A=A/x.count
for (i in 1:(K1-1)) {
for (k in (i+1):K1) {
D[i,k] = sum(abs(A[i,]-A[k,]))/2
D[k,i] = D[i,k]
}
}
D.cum <- D.cum + D
}
else {
q.x.all <- quantile(X[,j], probs = seq(0, 1, length.out = 100), na.rm = TRUE, names = FALSE)
x.ecdf=tapply(X[,j], X[,J[1]], ecdf)
for (i in 1:(K1-1)) {
for (k in (i+1):K1) {
D[i,k] = max(abs(x.ecdf[[i]](q.x.all)-x.ecdf[[k]](q.x.all)))
D[k,i] = D[i,k]
}
}
D.cum <- D.cum + D
}
}
D1D <- cmdscale(D.cum, k = 1)
ind.ord <- sort(D1D, index.return = T)$ix
ord.ind <- sort(ind.ord, index.return = T)$ix
levs.orig <- levels(X[,J[1]])
levs.ord <- levs.orig[ind.ord]
x.ord <- ord.ind[as.numeric(X[,J[1]])]
z2 = c(min(X[,J[2]]), as.numeric(quantile(X[,J[2]],seq(1/K,1,length.out=K), type=1)))
z2 = unique(z2)
K2 = length(z2)-1
a2 = as.numeric(cut(X[,J[2]], breaks=z2, include.lowest=TRUE))
row.ind.plus <- (1:N)[x.ord < K1]
X11 = X
X12 = X
X21 = X
X22 = X
X11[row.ind.plus,J[2]] = z2[a2][row.ind.plus]
X12[row.ind.plus,J[2]] = z2[a2+1][row.ind.plus]
X21[row.ind.plus,J[1]] = levs.ord[x.ord[row.ind.plus]+1]
X22[row.ind.plus,J[1]] = levs.ord[x.ord[row.ind.plus]+1]
X21[row.ind.plus,J[2]] = z2[a2][row.ind.plus]
X22[row.ind.plus,J[2]] = z2[a2+1][row.ind.plus]
y.hat11 = pred.fun(X.model=X.model, newdata = X11[row.ind.plus,])
y.hat12 = pred.fun(X.model=X.model, newdata = X12[row.ind.plus,])
y.hat21 = pred.fun(X.model=X.model, newdata = X21[row.ind.plus,])
y.hat22 = pred.fun(X.model=X.model, newdata = X22[row.ind.plus,])
Delta.plus=(y.hat22-y.hat21)-(y.hat12-y.hat11)
row.ind.neg <- (1:N)[x.ord > 1]
X11 = X
X12 = X
X21 = X
X22 = X
X11[row.ind.neg,J[1]] = levs.ord[x.ord[row.ind.neg]-1]
X12[row.ind.neg,J[1]] = levs.ord[x.ord[row.ind.neg]-1]
X11[row.ind.neg,J[2]] = z2[a2][row.ind.neg]
X12[row.ind.neg,J[2]] = z2[a2+1][row.ind.neg]
X21[row.ind.neg,J[2]] = z2[a2][row.ind.neg]
X22[row.ind.neg,J[2]] = z2[a2+1][row.ind.neg]
y.hat11 = pred.fun(X.model=X.model, newdata = X11[row.ind.neg,])
y.hat12 = pred.fun(X.model=X.model, newdata = X12[row.ind.neg,])
y.hat21 = pred.fun(X.model=X.model, newdata = X21[row.ind.neg,])
y.hat22 = pred.fun(X.model=X.model, newdata = X22[row.ind.neg,])
Delta.neg=(y.hat22-y.hat21)-(y.hat12-y.hat11)
Delta = as.matrix(tapply(c(Delta.plus, Delta.neg), list(c(x.ord[row.ind.plus], x.ord[row.ind.neg]-1), a2[c(row.ind.plus, row.ind.neg)]), mean))
NA.Delta = is.na(Delta)
NA.ind = which(NA.Delta, arr.ind=T, useNames = F)
if (nrow(NA.ind) > 0) {
notNA.ind = which(!NA.Delta, arr.ind=T, useNames = F)
range1 =K1-1
range2 = max(z2)-min(z2)
Z.NA = cbind(NA.ind[,1]/range1, (z2[NA.ind[,2]] + z2[NA.ind[,2]+1])/2/range2)
Z.notNA = cbind(notNA.ind[,1]/range1, (z2[notNA.ind[,2]] + z2[notNA.ind[,2]+1])/2/range2)
nbrs <- ann(Z.notNA, Z.NA, k=1, verbose = F)$knnIndexDist[,1]
Delta[NA.ind] = Delta[matrix(notNA.ind[nbrs,], ncol=2)]
}
fJ = matrix(0,K1-1,K2)
fJ = apply(t(apply(Delta,1,cumsum)),2,cumsum)
fJ = rbind(rep(0,K2),fJ)
fJ = cbind(rep(0,K1),fJ)
b=as.matrix(table(x.ord,a2))
b2=apply(b,2,sum)
Delta = fJ[,2:(K2+1)]-fJ[,1:K2]
b.Delta = b*Delta
Delta.Ave = apply(b.Delta,2,sum)/b2
fJ2 = c(0, cumsum(Delta.Ave))
b.ave=matrix((b[1:(K1-1),]+b[2:K1,])/2, K1-1, K2)
b1=apply(b.ave,1,sum)
Delta =matrix(fJ[2:K1,]-fJ[1:(K1-1),], K1-1, K2+1)
b.Delta = matrix(b.ave*(Delta[,1:K2]+Delta[,2:(K2+1)])/2, K1-1, K2)
Delta.Ave = apply(b.Delta,1,sum)/b1
fJ1 = c(0,cumsum(Delta.Ave))
fJ = fJ - outer(fJ1,rep(1,K2+1)) - outer(rep(1,K1),fJ2)
fJ0 = sum(b*(fJ[,1:K2] + fJ[,2:(K2+1)])/2)/sum(b)
fJ = fJ - fJ0
x <- list(levs.ord, z2)
K <- c(K1, K2)
image(1:K1, x[[2]], fJ, xlab=paste("x_",J[1], " (", names(X)[J[1]], ")", sep=""), ylab= paste("x_",J[2], " (", names(X)[J[2]], ")", sep=""), ylim = range(z2), yaxs = "i")
contour(1:K1, x[[2]], fJ, add=TRUE, drawlabels=TRUE)
axis(side=1, labels=x[[1]], at=1:K1, las = 3, padj=1.2)
if (NA.plot == FALSE) {
if (nrow(NA.ind) > 0) {
NA.ind = which(b==0, arr.ind=T, useNames = F)
rect(xleft = NA.ind[,1]-0.5, ybottom = z2[NA.ind[,2]], xright = NA.ind[,1]+0.5, ytop = z2[NA.ind[,2]+1], col="black")
}
}
}
else if (class(X[,J[1]]) == "numeric" | class(X[,J[1]]) == "integer") {
z1 = c(min(X[,J[1]]), as.numeric(quantile(X[,J[1]],seq(1/K,1,length.out=K), type=1)))
z1 = unique(z1)
K1 = length(z1)-1
a1 = as.numeric(cut(X[,J[1]], breaks=z1, include.lowest=TRUE))
z2 = c(min(X[,J[2]]), as.numeric(quantile(X[,J[2]],seq(1/K,1,length.out=K), type=1)))
z2 = unique(z2)
K2 = length(z2)-1
fJ = matrix(0,K1,K2)
a2 = as.numeric(cut(X[,J[2]], breaks=z2, include.lowest=TRUE))
X11 = X
X12 = X
X21 = X
X22 = X
X11[,J] = cbind(z1[a1], z2[a2])
X12[,J] = cbind(z1[a1], z2[a2+1])
X21[,J] = cbind(z1[a1+1], z2[a2])
X22[,J] = cbind(z1[a1+1], z2[a2+1])
y.hat11 = pred.fun(X.model=X.model, newdata = X11)
y.hat12 = pred.fun(X.model=X.model, newdata = X12)
y.hat21 = pred.fun(X.model=X.model, newdata = X21)
y.hat22 = pred.fun(X.model=X.model, newdata = X22)
Delta=(y.hat22-y.hat21)-(y.hat12-y.hat11)
Delta = as.matrix(tapply(Delta, list(a1, a2), mean))
NA.Delta = is.na(Delta)
NA.ind = which(NA.Delta, arr.ind=T, useNames = F)
if (nrow(NA.ind) > 0) {
notNA.ind = which(!NA.Delta, arr.ind=T, useNames = F)
range1 = max(z1)-min(z1)
range2 = max(z2)-min(z2)
Z.NA = cbind((z1[NA.ind[,1]] + z1[NA.ind[,1]+1])/2/range1, (z2[NA.ind[,2]] + z2[NA.ind[,2]+1])/2/range2)
Z.notNA = cbind((z1[notNA.ind[,1]] + z1[notNA.ind[,1]+1])/2/range1, (z2[notNA.ind[,2]] + z2[notNA.ind[,2]+1])/2/range2)
nbrs <- ann(Z.notNA, Z.NA, k=1, verbose = F)$knnIndexDist[,1]
Delta[NA.ind] = Delta[matrix(notNA.ind[nbrs,], ncol=2)]
}
fJ = apply(t(apply(Delta,1,cumsum)),2,cumsum)
fJ = rbind(rep(0,K2),fJ)
fJ = cbind(rep(0,K1+1),fJ)
b=as.matrix(table(a1,a2))
b1=apply(b,1,sum)
b2=apply(b,2,sum)
Delta =fJ[2:(K1+1),]-fJ[1:K1,]
b.Delta = b*(Delta[,1:K2]+Delta[,2:(K2+1)])/2
Delta.Ave = apply(b.Delta,1,sum)/b1
fJ1 = c(0,cumsum(Delta.Ave))
Delta = fJ[,2:(K2+1)]-fJ[,1:K2]
b.Delta = b*(Delta[1:K1,]+Delta[2:(K1+1),])/2
Delta.Ave = apply(b.Delta,2,sum)/b2
fJ2 = c(0, cumsum(Delta.Ave))
fJ = fJ - outer(fJ1,rep(1,K2+1)) - outer(rep(1,K1+1),fJ2)
fJ0 = sum(b*(fJ[1:K1,1:K2] + fJ[1:K1,2:(K2+1)] + fJ[2:(K1+1),1:K2] + fJ[2:(K1+1), 2:(K2+1)])/4)/sum(b)
fJ = fJ - fJ0
x <- list(z1, z2)
K <- c(K1, K2)
image(x[[1]], x[[2]], fJ, xlab=paste("x_",J[1], " (", names(X)[J[1]], ")", sep=""), ylab= paste("x_",J[2], " (", names(X)[J[2]], ")", sep=""), xlim = range(z1), ylim = range(z2), xaxs = "i", yaxs = "i")
contour(x[[1]], x[[2]], fJ, add=TRUE, drawlabels=TRUE)
if (NA.plot == FALSE) {
if (nrow(NA.ind) > 0) {
rect(xleft = z1[NA.ind[,1]], ybottom = z2[NA.ind[,2]], xright = z1[NA.ind[,1]+1], ytop = z2[NA.ind[,2]+1], col="black")
}
}
}
else print("error: class(X[,J[1]]) must be either factor or numeric/integer")
}
else print("error: J must be a vector of length one or two")
list(K=K, x.values=x, f.values = fJ)
} |
setAs("nMatrix", "dMatrix",
function(from) {
cld <- getClassDef(cl <- MatrixClass(class(from)))
isSp <- extends(cld, "sparseMatrix")
sNams <- slotNames(cld)
r <- copyClass(from, sub("^n", "d", cl),
if(isSp) sNams else sNams[sNams != "x"])
r@x <- if(isSp) rep.int(1., nnzSparse(from)) else as.double(from@x)
r
})
setAs("dMatrix", "nMatrix",
function(from) {
if(anyNA(from@x) && ((.w <- isTRUE(getOption("Matrix.warn"))) ||
isTRUE(getOption("Matrix.verbose")))) {
(if(.w) warning else message)(
"\"dMatrix\" object with NAs coerced to \"nMatrix\": NA |-> TRUE")
from@x[is.na(from@x)] <- 1
}
cld <- getClassDef(cl <- MatrixClass(class(from)))
if(extends(cld, "diagonalMatrix"))
return(di2nMat(from))
isSp <- extends(cld, "sparseMatrix")
if(isSp && any(from@x == 0)) {
from <- drop0(from)
if(cl != (c. <- class(from)))
cld <- getClassDef(cl <- c.)
}
sNams <- slotNames(cld)
r <- copyClass(from, sub("^d", "n", cl), sNams[sNams != "x"])
if(!isSp)
r@x <- as.logical(from@x)
r
})
setMethod("zapsmall", signature(x = "dMatrix"),
function(x, digits = getOption("digits")) {
x@x <- zapsmall(x@x, digits)
x
}) |
`unique.splineMatrix` <-
function(list.of.splineMatrices) {
tmp.list.1 <- lapply(list.of.splineMatrices,
function(x) list(Data = [email protected], Content_Areas=x@Content_Areas, Grade_Progression=x@Grade_Progression, Time=x@Time, Time_Lags=x@Time_Lags, Version=x@Version))
if (any(duplicated(tmp.list.1))) {
list.of.splineMatrices <- list.of.splineMatrices[!duplicated(tmp.list.1)]
}
tmp.list.1 <- lapply(list.of.splineMatrices,
function(x) list(Data = [email protected], Content_Areas=x@Content_Areas, Grade_Progression=x@Grade_Progression, Time=x@Time, Time_Lags=x@Time_Lags))
tmp.list.2 <- lapply(list.of.splineMatrices,
function(x) list(Data = [email protected], Content_Areas=x@Content_Areas, Grade_Progression=x@Grade_Progression, Time=x@Time, Time_Lags=x@Time_Lags, Version=x@Version))
if (any(duplicated(tmp.list.1))) {
list.of.splineMatrices[!duplicated(tmp.list.1[order(as.character(unlist(sapply(tmp.list.2, function(x) x$Version[1]))), decreasing=TRUE)])]
} else {
list.of.splineMatrices
}
} |
setGeneric("corridor", function(x, ...) {
standardGeneric("corridor")
})
setMethod(
"corridor",
signature = "goc",
definition = function(x, whichThresh, coords, weight = "meanWeight", ...) {
dots <- list(...)
if (!is.null(dots$doPlot)) {
warning("Argument 'doPlot' is deprecated and will be ignored.")
}
if ((length(whichThresh) > 1) || (!(whichThresh %in% 1:length(x@th)))) {
stop("whichThresh must index a single threshold existing in the GOC object")
}
if (inherits(coords, c("SpatialPoints", "SpatialPointsDataFrame"))) {
coords <- coordinates(coords)
}
if (ncol(coords) != 2) {
stop("coords must be a SpatialPoints object or a matrix of two columns",
"giving X and Y coordinates")
}
if (nrow(coords) > 2) {
warning("using only first two sets of coordinates for corridor start and end points")
coords <- coords[1:2, ]
}
if (!(weight %in% names(edge_attr(x@th[[1]]$goc)))) {
stop("link weight attribute with this name doesn't exist in GOC object")
}
edges <- as_edgelist(x@th[[whichThresh]]$goc)
edges <- cbind(edgeNum = 1:nrow(edges),
v1 = sapply(edges[, 1], function(z) {
which(V(x@th[[whichThresh]]$goc)$name == z)
}),
v2 = sapply(edges[, 2], function(z) {
which(V(x@th[[whichThresh]]$goc)$name == z)
}))
edgesGOC <- apply(edges, 1, function(i) {
cbind(c(V(x@th[[whichThresh]]$goc)$centroidX[i["v1"]],
V(x@th[[whichThresh]]$goc)$centroidX[i["v2"]]),
c(V(x@th[[whichThresh]]$goc)$centroidY[i["v1"]],
V(x@th[[whichThresh]]$goc)$centroidY[i["v2"]])) %>%
Line() %>%
Lines(ID = as.character(i["edgeNum"]))
}) %>%
SpatialLines() %>%
SpatialLinesDataFrame(
data = data.frame(
edgeNum = 1:nrow(edges),
weight = edge_attr(x@th[[whichThresh]]$goc, weight)
)
)
verticesGOC <- SpatialPoints(cbind(V(x@th[[whichThresh]]$goc)$centroidX,
V(x@th[[whichThresh]]$goc)$centroidY))
startEndPolygons <- point(x, coords)$pointPolygon[, whichThresh]
pths <- shortest_paths(
x@th[[whichThresh]]$goc,
which(V(x@th[[whichThresh]]$goc)$polygonId == na.omit(startEndPolygons[1])),
which(V(x@th[[whichThresh]]$goc)$polygonId == na.omit(startEndPolygons[2])),
weights = V(x@th[[whichThresh]]$goc)$meanWeight)
startEndPath <- if (length(pths$vpath) > 0) {
pths %>%
`[[`(1) %>%
`[[`(1) %>%
as.numeric()
} else {
stop("corridor: all 'coords' correspond to cells of value 'NA'.")
}
shortestPathEdges <- cbind(V(x@th[[whichThresh]]$goc)$centroidX[startEndPath],
V(x@th[[whichThresh]]$goc)$centroidY[startEndPath]) %>%
Line() %>%
Lines(ID = "1") %>%
list() %>%
SpatialLines()
shortestPathVertices <- SpatialPoints(cbind(
V(x@th[[whichThresh]]$goc)$centroidX[startEndPath],
V(x@th[[whichThresh]]$goc)$centroidY[startEndPath]))
pathDist <- distances(
x@th[[whichThresh]]$goc,
v = V(x@th[[whichThresh]]$goc)[na.omit(startEndPath[1])],
weights = edge_attr(x@th[[whichThresh]]$goc, weight)
)[na.omit(startEndPath[length(startEndPath)])]
voronoiBound <- boundaries(grain(x, whichThresh = whichThresh)@voronoi, classes = TRUE)
result <- new("corridor",
voronoi = voronoiBound,
linksSP = edgesGOC,
nodesSP = verticesGOC,
shortestLinksSP = shortestPathEdges,
shortestNodesSP = shortestPathVertices,
corridorLength = pathDist)
return(result)
}) |
context("Checking misc: formula() function")
source("settings.r")
dat <- escalc(measure="RR", ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat.bcg)
test_that("formula() works correctly for 'rma.uni' objects.", {
res <- rma(yi, vi, data=dat, method="DL")
expect_null(formula(res, type="mods"))
expect_null(formula(res, type="yi"))
res <- rma(yi, vi, mods = ~ ablat, data=dat, method="DL")
expect_equal(~ablat, formula(res, type="mods"))
expect_null(formula(res, type="yi"))
res <- rma(yi ~ ablat, vi, data=dat, method="DL")
expect_null(formula(res, type="mods"))
expect_equal(yi~ablat, formula(res, type="yi"))
expect_error(formula(res, type="scale"))
})
rm(list=ls()) |
epane<-function(x,h){
d<-length(x)
val<-1
for (i in 1:d){
val<-val*3*(1-(x[i]/h)^2)/2
}
return(val)
} |
lsodes <- function(y, times, func, parms, rtol = 1e-6, atol = 1e-6,
jacvec = NULL, sparsetype = "sparseint", nnz = NULL, inz = NULL,
rootfunc = NULL, verbose = FALSE, nroot = 0,
tcrit = NULL, hmin = 0, hmax = NULL, hini = 0, ynames = TRUE,
maxord = NULL, maxsteps = 5000, lrw = NULL, liw = NULL,
dllname = NULL, initfunc = dllname, initpar = parms,
rpar = NULL, ipar = NULL, nout = 0, outnames = NULL, forcings = NULL,
initforc = NULL, fcontrol = NULL, events = NULL, lags = NULL, ...) {
if (is.list(func)) {
if (!is.null(jacvec) & "jacvec" %in% names(func))
stop("If 'func' is a list that contains jacvec, argument 'jacvec' should be NULL")
if (!is.null(rootfunc) & "rootfunc" %in% names(func))
stop("If 'func' is a list that contains rootfunc, argument 'rootfunc' should be NULL")
if (!is.null(initfunc) & "initfunc" %in% names(func))
stop("If 'func' is a list that contains initfunc, argument 'initfunc' should be NULL")
if (!is.null(dllname) & "dllname" %in% names(func))
stop("If 'func' is a list that contains dllname, argument 'dllname' should be NULL")
if (!is.null(initforc) & "initforc" %in% names(func))
stop("If 'func' is a list that contains initforc, argument 'initforc' should be NULL")
if (!is.null(events$func) & "eventfunc" %in% names(func))
stop("If 'func' is a list that contains eventfunc, argument 'events$func' should be NULL")
if ("eventfunc" %in% names(func)) {
if (! is.null(events))
events$func <- func$eventfunc
else
events <- list(func = func$eventfunc)
}
if (!is.null(func$jacvec)) jacvec <- func$jacvec
if (!is.null(func$rootfunc)) rootfunc <- func$rootfunc
if (!is.null(func$initfunc)) initfunc <- func$initfunc
if (!is.null(func$dllname)) dllname <- func$dllname
if (!is.null(func$initforc)) initforc <- func$initforc
func <- func$func
}
hmax <- checkInput (y, times, func, rtol, atol,
jacvec, tcrit, hmin, hmax, hini, dllname,"jacvec")
n <- length(y)
if (is.null (maxord))
maxord <- 5
if (maxord > 5 )
stop ("'maxord' too large: should be <= 5")
if (maxord < 1 )
stop ("`maxord' must be >1")
if (sparsetype=="sparseusr" && is.null(inz))
stop("'inz' must be specified if 'sparsetype' = 'sparseusr'")
if (sparsetype=="sparsejan" && is.null(inz))
stop("'inz' must be specified if 'sparsetype' = 'sparsejan'")
if (sparsetype=="1D" && ! is.null(jacvec))
stop("cannot combine 'sparsetype=1D' and 'jacvec'")
if (sparsetype %in% c("2D", "2Dmap") && ! is.null(jacvec))
stop("cannot combine 'sparsetype=2D' and 'jacvec'")
if (sparsetype %in% c("3D", "3Dmap") && ! is.null(jacvec))
stop("cannot combine 'sparsetype=3D' and 'jacvec'")
if (! is.null(jacvec) && sparsetype %in% c("sparseusr", "sparsejan"))
imp <- 21
else if (! is.null(jacvec) && !sparsetype=="sparseusr")
imp <- 121
else if (is.null(jacvec) && sparsetype%in%c("sparseusr","1D","2D","2Dmap","3D","3Dmap","sparsejan"))
imp <- 22
else
imp <- 222
if (sparsetype == "1D") {
nspec <- nnz[1]
bandwidth <- 1
Type <- c(2,nnz)
nnz <- n*(2+nspec*bandwidth)-2*nspec
} else if (sparsetype %in% c("2D","2Dmap")) {
nspec <- nnz[1]
dimens <- nnz[2:3]
bandwidth <- 1
maxdim <- max(dimens)
if (sparsetype == "2D") {
Type <- c(3, nnz)
nnz <- n*(4+nspec*bandwidth)-2*nspec*(sum(dimens))
} else {
Type <- c(30, nnz)
nnz <- (nspec*prod(dimens))*(4+nspec*bandwidth)-2*nspec*(sum(dimens))
}
if (Type[5]==1) {
nnz <- nnz + 2*maxdim*nspec*bandwidth
}
if (Type[6] ==1) {
nnz <- nnz + 2*maxdim*nspec*bandwidth
}
} else if (sparsetype %in% c("3D","3Dmap")) {
nspec <- nnz[1]
dimens <- nnz[2:4]
bandwidth <- 1
if (sparsetype == "3D") {
Type <- c(4,nnz)
nnz <- n*(6+nspec*bandwidth)-2*nspec*(sum(dimens))
} else {
Type <- c(40, nnz)
nnz <- (nspec*prod(dimens))*(6+nspec*bandwidth)-2*nspec*(sum(dimens))
}
if (Type[6]== 1) {
nnz <- nnz + 2*dimens[2]*dimens[3]*nspec
}
if (Type[7] == 1) {
nnz <- nnz + 2*dimens[1]*dimens[3]*nspec
}
if (Type[8] == 1) {
nnz <- nnz + 2*dimens[1]*dimens[2]*nspec
}
} else if (sparsetype == "sparseusr") {
Type <- 0
nnz <- nrow(inz)
} else if (sparsetype == "sparsejan") {
Type <- 0
nnz <- length(inz) - n
} else {
Type <- 1
if (is.null(nnz)) nnz <- n*n
}
if (nnz < 1)
stop ("Jacobian should at least contain one non-zero value")
JacFunc <- NULL
Ynames <- attr(y,"names")
RootFunc <- NULL
flist <- list(fmat=0,tmat=0,imat=0,ModelForc=NULL)
ModelInit <- NULL
Eventfunc <- NULL
events <- checkevents(events, times, Ynames, dllname,TRUE)
if (! is.null(events$newTimes)) times <- events$newTimes
if (is.character(func) | inherits(func, "CFunc")) {
DLL <- checkDLL(func,jacvec,dllname,
initfunc,verbose,nout, outnames, JT=2)
if (!is.null(rootfunc)) {
if (!is.character(rootfunc) & !inherits(rootfunc, "CFunc"))
stop("If 'func' is dynloaded, so must 'rootfunc' be")
rootfuncname <- rootfunc
if (inherits(rootfunc, "CFunc"))
RootFunc <- body(rootfunc)[[2]]
else if (is.loaded(rootfuncname, PACKAGE = dllname)) {
RootFunc <- getNativeSymbolInfo(rootfuncname, PACKAGE = dllname)$address
} else
stop(paste("root function not loaded in DLL",rootfunc))
if (nroot == 0)
stop("if 'rootfunc' is specified in a DLL, then 'nroot' should be > 0")
}
ModelInit <- DLL$ModelInit
Func <- DLL$Func
JacFunc <- DLL$JacFunc
Nglobal <- DLL$Nglobal
Nmtot <- DLL$Nmtot
if (! is.null(forcings))
flist <- checkforcings(forcings,times,dllname,initforc,verbose,fcontrol)
if (is.null(ipar)) ipar<-0
if (is.null(rpar)) rpar<-0
Eventfunc <- events$func
if (is.function(Eventfunc))
rho <- environment(Eventfunc)
else
rho <- NULL
} else {
if(is.null(initfunc))
initpar <- NULL
rho <- environment(func)
if (ynames) {
Func <- function(time,state) {
attr(state,"names") <- Ynames
unlist(func (time,state,parms,...))
}
Func2 <- function(time,state) {
attr(state,"names") <- Ynames
func (time,state,parms,...)
}
JacFunc <- function(time,state,J){
attr(state,"names") <- Ynames
jacvec(time,state,J,parms,...)
}
RootFunc <- function(time,state) {
attr(state,"names") <- Ynames
rootfunc(time,state,parms,...)
}
if (! is.null(events$Type))
if (events$Type == 2)
Eventfunc <- function(time,state) {
attr(state,"names") <- Ynames
events$func(time,state,parms,...)
}
} else {
Func <- function(time,state)
unlist(func (time,state,parms,...))
Func2 <- function(time,state)
func (time,state,parms,...)
JacFunc <- function(time,state,J)
jacvec(time,state,J,parms,...)
RootFunc <- function(time,state)
rootfunc(time,state,parms,...)
if (! is.null(events$Type))
if (events$Type == 2)
Eventfunc <- function(time,state)
events$func(time,state,parms,...)
}
FF <- checkFunc(Func2,times,y,rho)
Nglobal<-FF$Nglobal
Nmtot <- FF$Nmtot
if (! is.null(events$Type))
if (events$Type == 2)
checkEventFunc(Eventfunc,times,y,rho)
if (! is.null(rootfunc)) {
tmp2 <- eval(rootfunc(times[1],y,parms,...), rho)
if (!is.vector(tmp2))
stop("root function 'rootfunc' must return a vector\n")
nroot <- length(tmp2)
} else nroot = 0
}
moss <- imp%/%100
meth <- imp%%100%/%10
miter <- imp%%10
lenr = 2
if (is.null(lrw)) {
lrw = 20+n*(maxord+1)+3*n +20
if(miter == 1) lrw = lrw + 2*nnz + 2*n + (nnz+9*n)/lenr
if(miter == 2) lrw = lrw + 2*nnz + 2*n + (nnz+10*n)/lenr
if(miter == 3) lrw = lrw + n + 2
if (sparsetype == "1D") lrw <- lrw*1.2
}
if (moss == 0 && miter %in% c(1,2)) liw <- max(liw, 31+n+nnz +30) else
liw <- max(liw, 30)
lrw <- max(20, lrw) + 3*nroot
rwork <- vector("double",20)
rwork[] <- 0.
if(sparsetype=="sparseusr") {
iwork <- vector("integer",liw)
iwork[] <- 0
iw <- 32+n
iwork[31]<- iw
rr <- inz[,2]
if (min(rr[2:nnz]-rr[1:(nnz-1)])<0)
stop ("cannot proceed: column indices (2nd column of inz) should be sorted")
for(i in 1:n) {
ii <- which (rr==i)
il <- length(ii)
i1 <- iwork[i+30]
i2 <- iwork[i+30]+il-1
iwork[i+31] <- i2+1
if (il>0) iwork[i1:i2] <- inz[ii,1]
}
iwork[31:(31+n)] <- iwork[31:(31+n)]-31-n
} else if(sparsetype=="sparsejan") {
iwork <- vector("integer",liw)
iwork[] <- 0
iw <- 32+n
linz <- 30 + length(inz)
iwork[31:linz] <- inz
} else {
iwork <- vector("integer",30)
iwork[] <- 0
}
iwork[5] <- maxord
iwork[6] <- maxsteps
if(! is.null(tcrit)) rwork[1] <- tcrit
rwork[5] <- hini
rwork[6] <- hmax
rwork[7] <- hmin
if (! is.null(times))
itask <- ifelse (is.null (tcrit), 1,4) else
itask <- ifelse (is.null (tcrit), 2,5)
if(is.null(times)) times <- c(0,1e8)
if (verbose) {
printtask(itask,func,jacvec)
printM("\n--------------------")
printM("Integration method")
printM("--------------------\n")
txt <- ""
if (imp == 21)
txt <- " The user has supplied indices to nonzero elements of Jacobian,
and a Jacobian function" else
if (imp == 22) {
if (sparsetype %in% c("sparseusr","sparsejan"))
txt <-" The user has supplied indices to nonzero elements of Jacobian,
the Jacobian will be estimated internally, by differences"
if (sparsetype=="1D")
txt <-" The nonzero elements are according to a 1-D model,
the Jacobian will be estimated internally, by differences"
if (sparsetype %in% c("2D", "2Dmap"))
txt <-" The nonzero elements are according to a 2-D model,
the Jacobian will be estimated internally, by differences"
if (sparsetype %in% c("3D","3Dmap"))
txt <-" The nonzero elements are according to a 3-D model,
the Jacobian will be estimated internally, by differences"
} else
if (imp == 122)
txt <-" The user has supplied the Jacobian,
its structure (indices to nonzero elements) will be obtained from NEQ+1 calls to jacvec" else
if (imp == 222)
txt <-" The Jacobian will be generated internally,
its structure (indices to nonzero elements) will be obtained from NEQ+1 calls to func"
printM(txt)
}
storage.mode(y) <- storage.mode(times) <- "double"
IN <- 3
if (!is.null(rootfunc)) IN <- 7
lags <- checklags(lags, dllname)
on.exit(.C("unlock_solver"))
out <- .Call("call_lsoda",y,times,Func,initpar,
rtol, atol, rho, tcrit, JacFunc, ModelInit, Eventfunc,
as.integer(verbose), as.integer(itask), as.double(rwork),
as.integer(iwork), as.integer(imp),as.integer(Nglobal),
as.integer(lrw),as.integer(liw),as.integer(IN),
RootFunc, as.integer(nroot), as.double (rpar), as.integer(ipar),
as.integer(Type),flist, events, lags, PACKAGE="deSolve")
if (nroot>0) iroot <- attr(out, "iroot")
out <- saveOut(out, y, n, Nglobal, Nmtot, func, Func2,
iin=c(1,12:20), iout=c(1:3,14,5:9,17))
if (nroot>0) attr(out, "iroot") <- iroot
attr(out, "type") <- "lsodes"
if (verbose) diagnostics(out)
out
} |
as.data.frame.SpatialArray <- function(x, row.names=NULL, optional=FALSE,...){
df <- as.data.frame(proxy(x))
if(ncol(df)==1) colnames(df) <- "X0"
if(!is.null(row.names)){
rownames(df)<- row.names
}
if(optional){
rownames(df) <- NULL
colnames(df) <- NULL
}
return(df)
}
setGeneric("as.SpatialArray", function(from) standardGeneric("as.SpatialArray"))
setMethod(as.SpatialArray, signature=c("SpatialPoints"), definition=function(from){
SpatialArray(SpatialStack(from), index=1)
})
setMethod(as.SpatialArray, signature=c("SpatialPointsDataFrame"), definition=function(from){
SpatialArray(SpatialStack(from), index=1)
})
setMethod(as.SpatialArray, signature=c("SpatialLines"), definition=function(from){
SpatialArray(SpatialStack(from), index=1)
})
setMethod(as.SpatialArray, signature=c("SpatialLinesDataFrame"), definition=function(from){
SpatialArray(SpatialStack(from), index=1)
})
setMethod(as.SpatialArray, signature=c("SpatialPolygons"), definition=function(from){
SpatialArray(SpatialStack(from), index=1)
})
setMethod(as.SpatialArray, signature=c("SpatialPolygonsDataFrame"), definition=function(from){
SpatialArray(SpatialStack(from), index=1)
})
setMethod("as.list","SpatialArray", function(x,...){
x@stack@Spatials
}) |
expect_equal(
construct_CovBlk(c(3,3,3),c(0,0,0)),
diag(3) *9
)
expect_equal(
construct_CovBlk(c(3,3,3),c(1,2,3)),
matrix(c(10,2,3,2,13,6,3,6,18),nrow=3)
)
expect_equal(
construct_CovBlk(c(3,3,3),c(1,1,2),c(1,2,3)),
matrix(c(11,3,5,3,14,8,5,8,22),nrow=3)
) |
upper.dir <- function(dir,end.slash=TRUE){
(dir <- formal_dir(dir,TRUE))
last_slash <- stringr::str_locate_all(dir,'/')[[1]][,1] |> last(2)
if (length(last_slash)==0 | is.na(last_slash)) return(dir)
left(dir,last_slash) |> formal_dir(end.slash)
}
formal_dir <- function(dir,end.slash=FALSE){
if (end.slash){
Trim_right(dir,c('\\\\','/')) |>
Replace('\\\\','/') |>
paste0('/')
}else{
Trim_right(dir,c('\\\\','/')) |>
Replace('\\\\','/')
}
} |
options(digits = 3)
data(aq.trans)
data(aq.census)
head(aq.trans)
aq.trans$survived <- aq.trans$fate != "dead"
aq.trans$flowered <- aq.trans$fate == "flower"
head(aq.trans, 1)
caption <- function(x) {
cat("Press <Enter> to continue...")
readline()
invisible()
}
surv <- subset(aq.trans, stage %in% c("flower", "large", "small") & !is.na(rose))
table(surv$rose)
table(cut(surv$rose, c(-1:7, 45)))
z <- table(cut(surv$rose, c(0:7, 45), labels = c(1:7, "8+")), surv$stage == "flower", surv$survived, dnn = c("State", "Flower", "Alive"))
ftable(z, row.vars = c(2, 1), col.vars = c(3))
caption("Transition frequency table with initial state (flowering and rosette number) and fate (dead or alive)")
y <- table(cut(surv$rose, c(0:7, 45), labels = c(1:7, "8+")),
cut(surv$rose2, c(0:7, 48), labels = c(1:7, "8+")),
surv$stage == "flower", surv$flowered,
dnn = c("State", "Fate", "Flower", "Flower")
)
ftable(y, row.vars = c(3, 1), col.vars = c(4, 2))
caption("Transition frequency table with initial state and fate of live plants")
a <- subset(aq.trans, leaf < 50 & stage != "recruit", c(leaf, survived))
logi.hist.plot(a$leaf, a$survived,
type = "hist", boxp = FALSE, counts = TRUE, las.h = 0, int = 10,
ylabel = "Survival probability", ylabel2 = "Number of plants", xlab = "Number of leaves", main = "Logistic regression leaf vs. survival"
)
flwr <- subset(surv, rose > 0 & rose <= 7 & stage == "flower" & year > 1997)
non.flwr <- subset(surv, rose > 0 & rose <= 7 & stage != "flower" & year > 1997)
rbind(flower = table(flwr$rose), vegetative = table(non.flwr$rose))
a <- table(flwr$year, cut(flwr$rose, c(0, 1, 3, 10), labels = c("rose1", "rose2-3", "rose3+")))
a
table(flwr$year, cut(flwr$rose, c(0, 2, 10), labels = c("rose1-2", "rose3+")))
caption("Potential stage class boundaries and sample sizes of flowering plants using cut")
tapply(flwr$survived, flwr$rose, mean)
tapply(non.flwr$survived, non.flwr$rose, mean)
x.flwr <- table(flwr$rose, flwr$survived)
x.flwr
x.non.flwr <- table(non.flwr$rose, non.flwr$survived)
rose <- 1:7
glm.flwr <- glm(x.flwr ~ rose, binomial)
glm.non.flwr <- glm(x.non.flwr ~ rose, binomial)
summary(glm.flwr)
xrange <- c(.5, 7.5)
plot(rose, prop.table(x.flwr, 1)[, 2],
ylim = c(0.45, 1), xlim = xrange, pch = 1,
col = "royalblue", las = 1,
ylab = expression(paste("Proportion surviving (year ", italic("t+1"), ")")),
xlab = expression(paste("Rosette number (year ", italic("t"), ")")),
main = "Survival rates by flowering state"
)
points(rose, prop.table(x.non.flwr, 1)[, 2], pch = 3, col = "darkgreen")
xp <- seq(1, max(rose), .1)
lines(xp, 1 - predict(glm.flwr, list(rose = xp), type = "response"), col = "royalblue", lwd = 2)
lines(xp, 1 - predict(glm.non.flwr, list(rose = xp), type = "response"), col = "darkgreen", lwd = 2)
legend(.5, 1, c("Flowering", "Vegetative "), pch = c(1, 3), col = c("royalblue", "darkgreen"))
x.flwr <- table(flwr$rose, flwr$flowered)
x.non.flwr <- table(non.flwr$rose, non.flwr$flowered)
glm.flwr <- glm(x.flwr ~ rose, binomial)
glm.non.flwr <- glm(x.non.flwr ~ rose, binomial)
plot(rose, prop.table(x.flwr, 1)[, 2],
ylim = c(0, 1), xlim = xrange, pch = 1, col = "royalblue", las = 1,
ylab = expression(paste("Proportion flowering (year ", italic("t+1"), ")")),
xlab = expression(paste("Rosette number (year ", italic("t"), ")")),
main = "Growth into reproductive stage"
)
points(rose, prop.table(x.non.flwr, 1)[, 2], pch = 3, col = "darkgreen")
lines(xp, 1 - predict(glm.flwr, list(rose = xp), type = "response"), col = "royalblue", lwd = 2)
lines(xp, 1 - predict(glm.non.flwr, list(rose = xp), type = "response"), col = "darkgreen", lwd = 2)
legend(.5, 1, c("Flowering", "Vegetative "), pch = c(1, 3), col = c("royalblue", "darkgreen"))
flwr$growth <- flwr$rose2 - flwr$rose
non.flwr$growth <- non.flwr$rose2 - non.flwr$rose
table(flwr$growth)
x.flwr <- table(flwr$rose, cut(flwr$growth, c(-10, -.5, .5, 10), labels = c("regress", "stasis", "growth")))
x.non.flwr <- table(non.flwr$rose, cut(non.flwr$growth, c(-15, -.5, .5, 15), labels = c("regress", "stasis", "growth")))
x.flwr
caption("Growth rates of flowering plants by rosette number")
a1.f <- cbind(regress = x.flwr[, 1], b = x.flwr[, 2] + x.flwr[, 3])
a2.f <- cbind(stasis = x.flwr[, 2], b = x.flwr[, 1] + x.flwr[, 3])
a3.f <- cbind(grow = x.flwr[, 3], b = x.flwr[, 1] + x.flwr[, 2])
a1.nf <- cbind(regress = x.non.flwr[, 1], b = x.non.flwr[, 2] + x.non.flwr[, 3])
a2.nf <- cbind(stasis = x.non.flwr[, 2], b = x.non.flwr[, 1] + x.non.flwr[, 3])
a3.nf <- cbind(grow = x.non.flwr[, 3], b = x.non.flwr[, 1] + x.non.flwr[, 2])
m1.f <- glm(a1.f ~ rose, binomial)
m2.f <- glm(a2.f ~ rose, binomial)
m3.f <- glm(a3.f ~ rose, binomial)
p.flwr <- prop.table(x.flwr, 1)
p.non.flwr <- prop.table(x.non.flwr, 1)
plot(rose, p.flwr[, 1],
type = "n", ylim = c(0, 1), xlim = xrange, las = 1,
ylab = expression(paste("Proportion (year ", italic("t+1"), ")")),
xlab = expression(paste("Rosette number (year ", italic("t"), ")")),
main = paste("Growth, stasis, and regression\nof flowering plants")
)
points(rose, p.flwr[, 1], pch = 1, col = "darkgreen")
lines(xp, predict(m1.f, list(rose = xp), type = "response"), col = "darkgreen", lwd = 2)
points(rose, p.flwr[, 2], pch = 3, col = "red")
lines(xp, predict(m2.f, list(rose = xp), type = "response"), col = "red", lwd = 2)
points(rose, p.flwr[, 3], pch = 6, col = "royalblue")
lines(xp, predict(m3.f, list(rose = xp), type = "response"), col = "royalblue", lwd = 2)
legend(2.5, 1, c("Growth", "Stasis", "Regress "), pch = c(6, 3, 1), col = c("royalblue", "red", "darkgreen"))
m1.nf <- glm(a1.nf ~ rose, binomial)
m2.nf <- glm(a2.nf ~ rose, binomial)
m3.nf <- glm(a3.nf ~ rose, binomial)
plot(rose, p.non.flwr[, 1],
type = "n", ylim = c(0, 1), xlim = xrange, las = 1,
ylab = expression(paste("Proportion (year ", italic("t+1"), ")")),
xlab = expression(paste("Rosette number (year ", italic("t"), ")")),
main = paste("Growth, stasis, and regression\nof vegetative plants")
)
points(rose, p.non.flwr[, 1], pch = 1, col = "darkgreen")
lines(xp, predict(m1.nf, list(rose = xp), type = "response"), col = "darkgreen", lwd = 2)
points(rose, p.non.flwr[, 2], pch = 3, col = "red")
lines(xp, predict(m2.nf, list(rose = xp), type = "response"), col = "red", lwd = 2)
points(rose, p.non.flwr[, 3], pch = 6, col = "royalblue")
lines(xp, predict(m3.nf, list(rose = xp), type = "response"), col = "royalblue", lwd = 2)
legend(2, 1, c("Growth", "Stasis", "Regress "), pch = c(6, 3, 1), col = c("royalblue", "red", "darkgreen"))
fruit <- subset(aq.trans, stage == "flower" & fruits >= 0 & rose <= 7 & rose > 0, select = c(plant, year, rose, leaf, fruits))
table(fruit$rose)
fruit1 <- glm(fruits ~ rose, poisson, data = fruit)
summary(fruit1)
caption("glm using poisson family")
fruit1 <- glm(fruits ~ rose, quasipoisson, data = fruit)
summary(fruit1)
caption("glm using quasipoisson to correct for overdispersion")
boxplot(fruit$fruits ~ fruit$rose, xlab = "Rosette number", ylab = "Mature fruits", col = "green", ylim = c(0, 12), main = paste("Side-by-side boxplots of\nmature fruits by plant size"))
lines(xp, exp(predict(fruit1, list(rose = xp))), col = "red", lwd = 2) |
bivariate <- function(db, target) {
if (!is.data.frame(db)) {
stop("db is not a data frame.")
}
if (!target%in%names(db)) {
stop("Target variable does not exist in supplied db.")
}
y <- db[, target]
cond.00 <- !sum(y[!is.na(y)]%in%c(0, 1)) == length(y[!is.na(y)])
if (cond.00) {
stop("Target is not 0/1 variable.")
}
rf <- names(db)[!names(db)%in%target]
rfl <- length(rf)
if (rfl == 0) {
stop("There are no risk factors in supplied db.")
}
res <- vector("list", rfl)
info <- vector("list", rfl)
for (i in 1:rfl) {
xl <- rf[i]
x <- db[, xl]
cond.01 <- !(is.character(x) | is.factor(x) | is.logical(x))
cond.02 <- length(unique(x)) > 10
if (cond.01) {
info[[i]] <- data.frame(rf = xl,
reason.code = 1,
comment = "Inappropriate class. It has to be one of: character, factor or logical.")
next
}
if (cond.02) {
info[[i]] <- data.frame(rf = xl,
reason.code = 2,
comment = "More than 10 categories.")
next
}
woe.res <- woe.tbl(tbl = db, x = xl, y = target)
mod.formula <- paste0(target, " ~ ", "`", xl, "`")
lr <- try(glm(mod.formula, family = "binomial", data = db), silent = TRUE)
if ("try-error"%in%class(lr)) {
auc <- NA
} else {
auc <- auc.model(predictions = unname(predict(lr, type = "response", newdata = db)),
observed = y)
}
woe.res$auc <- auc
woe.res <- cbind.data.frame(rf = xl, woe.res)
res[[i]] <- woe.res
}
res <- data.frame(bind_rows(res))
info <- data.frame(bind_rows(info))
return(list(results = res, info = info))
}
woe.tbl <- function(tbl, x, y, y.check = TRUE) {
if (!is.data.frame(tbl)) {
stop("tbl is not a data frame.")
}
if (!y%in%names(tbl)) {
stop("y (target variable) does not exist in supplied tbl.")
}
if (!x%in%names(tbl)) {
stop("x (risk factor) does not exist in supplied tbl.")
}
if (!is.logical(y.check)) {
stop("y.check has to be of logical type.")
}
target <- tbl[, y]
if (y.check) {
cond.00 <- !sum(target[!is.na(target)]%in%c(0, 1)) == length(target[!is.na(target)])
if (cond.00) {
stop("y (target variable) is not 0/1 variable.")
}
}
res <- tbl %>%
group_by_at(c("bin" = x)) %>%
summarise(no = n(),
ng = sum(1 - !!sym(y)),
nb = sum(!!sym(y))) %>%
ungroup() %>%
mutate(pct.o = no / sum(no),
pct.g = ng / sum(ng),
pct.b = nb / sum(nb),
dr = nb / no,
so = sum(no),
sg = sum(ng),
sb = sum(nb),
dist.g = ng / sg,
dist.b = nb / sb,
woe = log(dist.g / dist.b),
iv.b = (dist.g - dist.b) * woe,
iv.s = sum(iv.b))
return(data.frame(res))
}
auc.model <- function(predictions, observed) {
cc <- complete.cases(predictions, observed)
predictions <- predictions[cc]
observed <- observed[cc]
n1 <- sum(observed == 0)
n2 <- sum(observed == 1)
u <- sum(rank(predictions)[observed == 0]) - n1 * (n1 + 1) / 2
auc <- 1 - u / n1 / n2
return(auc)
}
replace.woe <- function(db, target) {
if (!is.data.frame(db)) {
stop("db is not a data frame.")
}
if (!target%in%names(db)) {
stop("Target variable does not exist in supplied db.")
}
y <- db[, target]
cond.00 <- !sum(y[!is.na(y)]%in%c(0, 1)) == length(y[!is.na(y)])
if (cond.00) {
stop("Target is not 0/1 variable.")
}
rf <- names(db)[!names(db)%in%target]
rfl <- length(rf)
if (rfl == 0) {
stop("There are no risk factors in supplied db.")
}
res <- vector("list", rfl)
info <- vector("list", rfl)
for (i in 1:rfl) {
xl <- rf[i]
x <- db[, xl]
cond.01 <- !(is.character(x) | is.factor(x) | is.logical(x))
cond.02 <- length(unique(x)) > 10
if (cond.01) {
info[[i]] <- data.frame(rf = xl,
reason.code = 1,
comment = "Inappropriate class. It has to be one of: character, factor or logical.")
res[[i]] <- data.frame(x)
names(res[[i]]) <- xl
next
}
if (cond.02) {
info[[i]] <- data.frame(rf = xl,
reason.code = 2,
comment = "More than 10 categories.")
}
woe.res <- woe.tbl(tbl = db, x = xl, y = target)
cond.03 <- any(woe.res$woe%in%c(NA, NaN, Inf))
if (cond.03) {
info[[i]] <- data.frame(rf = xl,
reason.code = 3,
comment = "Problem with WoE calculation (NA, NaN, Inf)")
res[[i]] <- data.frame(x)
names(res[[i]]) <- xl
next
}
woe.val <- woe.res$woe
names(woe.val) <- woe.res$bin
woe.rep <- unname(woe.val[x])
res[[i]] <- data.frame(woe.rep)
names(res[[i]]) <- xl
}
res <- data.frame(bind_cols(res), check.names = FALSE)
res <- cbind.data.frame(db[, target, drop = FALSE], res)
info <- data.frame(bind_rows(info))
return(list(results = res, info = info))
} |
NULL
isList <- function(x) {
class(x)[1] == "list"
}
isBoot <- function(x) {
"boot" %in% class(x)
}
isMod <- function(x) {
any(c("lm", "glm", "lmerMod", "glmerMod", "lmerModLmerTest", "gls", "betareg")
%in% class(x))
}
rMapply <- function(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE,
USE.NAMES = TRUE) {
l <- list(...)
n <- length(l)
i <- if (n > 0) l[[1]] else l
j <- if (n > 1) l[[2]] else i
if (!isList(i) || !isList(j)) {
do.call(FUN, c(l, MoreArgs))
} else {
a <- list(FUN = FUN, MoreArgs = MoreArgs, SIMPLIFY = SIMPLIFY,
USE.NAMES = USE.NAMES)
mapply(rMapply, ..., MoreArgs = a, SIMPLIFY = SIMPLIFY,
USE.NAMES = USE.NAMES)
}
}
pSapply <- function(X, FUN, parallel = c("snow", "multicore", "no"),
ncpus = NULL, cl = NULL, add.obj = NULL, ...) {
parallel <- match.arg(parallel); nc <- ncpus; ao <- add.obj; a <- list(...)
if (parallel == "multicore") a$simplify <- NULL else a$SIMPLIFY <- NULL
if (parallel != "no") {
if (is.null(nc)) nc <- parallel::detectCores()
if (parallel == "snow") {
if (is.null(cl)) {
cl <- parallel::makeCluster(getOption("cl.cores", nc))
}
P <- function(...) {
paste(..., collapse = " ")
}
xc <- P(unlist(rMapply(function(i) {
if (isMod(i) || isBoot(i)) P(getCall(i))
}, X)))
fa <- P(sapply(match.call(expand.dots = FALSE)$..., deparse))
fc <- P(xc, enquote(FUN)[2], fa)
o <- unlist(lapply(search(), ls))
o <- o[sapply(o, function(i) grepl(i, fc, fixed = TRUE))]
o <- c("X", o, ao)
parallel::clusterExport(cl, o, environment())
out <- do.call(parallel::parSapply, c(list(cl, X, FUN), a))
parallel::stopCluster(cl)
} else {
out <- parallel::mcmapply(FUN, X, mc.cores = nc, MoreArgs = a)
}
} else {
out <- do.call(sapply, c(list(X, FUN), a))
}
return(out)
} |
require(lavaan)
require(SEMsens)
set.seed(1)
smith10.use <- data(smith19.use, package = "SEMsens")
factornames <- c("P2BEPARN", "P2CHDOES","P2HRDWRM","P2FLTRAP","P2FEELAN","P2CHHARD",
"P2MOREWK", "P2HITCHO","P2HITAPO","P2HITPRV","P2HITWAR","P2ATTENB",
"P2ATTENP", "P2PARADV","P2PARGRP","P2ATTENS","P2VOLUNT","P2FUNDRS",
"P2TVRULE", "P2TVRUL3","P2TVRUL2","P1TELLST","P1SINGSO","P1HELPAR",
"P1CHORES", "P1GAMES","P1NATURE","P1BUILD","P1SPORT","P2LIBRAR",
"P2CONCRT", "P2MUSEUM","P2ZOO")
model1 <- "
C2RSCALE~T2LEARN+T2EXTERN+T2INTERN+T2CONTRO+T2INTERP+f1+f2+f3+f4+f5+f6
T2LEARN~f1 +f2 +f3 +f4 +f5 +f6
T2EXTERN~f1 +f2 +f3 +f4 +f5 +f6
T2INTERN~f1 +f2 +f3 +f4 +f5 +f6
T2CONTRO~f1 +f2 +f3 +f4 +f5 +f6
T2INTERP~f1 +f2 +f3 +f4 +f5 +f6
f1=~P2BEPARN+P2CHDOES+P2HRDWRM+P2FLTRAP+P2FEELAN+P2CHHARD+P2MOREWK
f2=~P2HITCHO+P2HITAPO+P2HITPRV+P2HITWAR
f3=~P2ATTENB+P2ATTENP+P2PARADV+P2PARGRP+P2ATTENS+P2VOLUNT+P2FUNDRS
f4=~P2TVRULE+P2TVRUL3+P2TVRUL2
f5=~P1TELLST+P1SINGSO+P1HELPAR+P1CHORES+P1GAMES+P1NATURE+P1BUILD+P1SPORT
f6=~P2LIBRAR+P2CONCRT+P2MUSEUM+P2ZOO
T2LEARN ~~ T2EXTERN+T2INTERN+T2CONTRO+T2INTERP
T2EXTERN ~~ T2INTERN+T2CONTRO+T2INTERP
T2INTERN ~~ T2CONTRO+T2INTERP
T2CONTRO ~~ T2INTERP
f1 ~~ f2+f3+f4+f5+f6
f2 ~~ f3+f4+f5+f6
f3 ~~ f4+f5+f6
f4 ~~ f5+f6
f5 ~~ f6
"
sens.model1 <- '
C2RSCALE~T2LEARN+T2EXTERN+T2INTERN+T2CONTRO+T2INTERP+f1+f2+f3+f4+f5+f6
T2LEARN~f1 +f2 +f3 +f4 +f5 +f6
T2EXTERN~f1 +f2 +f3 +f4 +f5 +f6
T2INTERN~f1 +f2 +f3 +f4 +f5 +f6
T2CONTRO~f1 +f2 +f3 +f4 +f5 +f6
T2INTERP~f1 +f2 +f3 +f4 +f5 +f6
f1=~P2BEPARN+P2CHDOES+P2HRDWRM+P2FLTRAP+P2FEELAN+P2CHHARD+P2MOREWK
f2=~P2HITCHO+P2HITAPO+P2HITPRV+P2HITWAR
f3=~P2ATTENB+P2ATTENP+P2PARADV+P2PARGRP+P2ATTENS+P2VOLUNT+P2FUNDRS
f4=~P2TVRULE+P2TVRUL3+P2TVRUL2
f5=~P1TELLST+P1SINGSO+P1HELPAR+P1CHORES+P1GAMES+P1NATURE+P1BUILD+P1SPORT
f6=~P2LIBRAR+P2CONCRT+P2MUSEUM+P2ZOO
T2LEARN ~~ T2EXTERN+T2INTERN+T2CONTRO+T2INTERP
T2EXTERN ~~ T2INTERN+T2CONTRO+T2INTERP
T2INTERN ~~ T2CONTRO+T2INTERP
T2CONTRO ~~ T2INTERP
f1 ~~ f2+f3+f4+f5+f6
f2 ~~ f3+f4+f5+f6
f3 ~~ f4+f5+f6
f4 ~~ f5+f6
f5 ~~ f6
T2LEARN ~ phantom1*phantom
T2EXTERN ~ phantom2*phantom
C2RSCALE ~ phantom3*phantom
f3 ~ phantom4*phantom
f4 ~ phantom5*phantom
f5 ~ phantom6*phantom
phantom =~ 0
phantom ~~ 1*phantom
'
old.model = model1
old.out = sem(model = model1, data = smith19.use, estimator="WLSMV",ordered = factornames)
summary(old.out, standardized=TRUE)
old.model.par <- standardizedSolution(old.out,type = "std.all")
old.model.par
load("smith19_6_my.sa.table.rdata")
my.sa.table$sens.summary
my.sa.table$phan.paths
my.sa.table$phan.min
my.sa.table$phan.max
my.sa.table$p.paths |
"employee_performance" |
isZeroOrNanScalar <- function(argument, default = NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL) {
checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = FALSE, n = 1, zeroAllowed = TRUE, negativeAllowed = FALSE, positiveAllowed = FALSE, nonIntegerAllowed = TRUE, naAllowed = FALSE, nanAllowed = TRUE, infAllowed = FALSE, message = message, argumentName = argumentName)
} |
sample_sd <- function(x, na.rm = FALSE) {
sqrt(sample_var(x,na.rm=na.rm))
} |
context('Check theme objects')
test_that('gg_themes objects were properly created', {
expect_true(is.theme(theme_readable()))
expect_true(is.theme(theme_bw2()))
})
test_that('xp_themes objects were properly created', {
expect_true(is.list(theme_xp_default()))
expect_true(is.list(theme_xp_xpose4()))
expect_true(inherits(theme_xp_default(), 'xpose_theme'))
expect_true(inherits(theme_xp_xpose4(), 'xpose_theme'))
}) |
CatDynExp <-
function(x,...) UseMethod("CatDynExp") |
new_model <- function(fit = NULL, model, data, response, transformation){
structure(list(fit = fit, model = model, data = data,
response = response, transformation = transformation),
class = "mdl_ts")
}
format.mdl_ts <- function(x, ...){
model_sum(x)
}
type_sum.mdl_ts <- function(x){
model_sum(x[["fit"]])
}
is_model <- function(x){
inherits(x, "mdl_ts")
}
model_sum <- function(x){
UseMethod("model_sum")
}
model_sum.default <- function(x){
tibble::type_sum(x)
}
model_sum.mdl_ts <- function(x){
model_sum(x[["fit"]])
} |
dcosw<-function(x,alpha,lambda){
(pi/2)*alpha*(lambda^(alpha))*(x^(alpha-1))*exp(-(lambda*x)^alpha)*cos((pi/2)*exp(-(lambda*x)^alpha))
} |
hypo.surf <- function(threeD.out=NULL, PC=1, flim=c(0, 4), tlim=c(0, 0.8), x.length=70, y.length=47, log.scale=TRUE, f=44100, wl=512, ovlp=70, plot.exp=FALSE, plot.as="jpeg", store.at = NULL, rotate.Xaxis=60, rotate.Yaxis=40, cex.axis=0.5, cex.lab=0.9, cex.main=1.1, lwd=0.1, xlab="Time coordinates", ylab="Frequency coordinates", zlab="Amplitude", colkey = list(plot = TRUE, cex.clab = 0.9, cex.axis = 0.8, side = 4, length = 0.5, width = 0.7, labels = TRUE, tick = TRUE, lty = 1, lwd = 1, lwd.ticks = 1))
{
if(is.null(threeD.out))
{stop('Please define threeD.out as an object containing the output of eigensound function with analysis.type="threeDshape')}
if(is.null(PC))
{stop('Choose a Principal Component or "mean" shape configuration to generate hypothetical semilandmark configurations. See help(hypo.surf) for details.')}
if(plot.exp == TRUE && is.null(store.at)){
stop("Use 'store.at' to specify folder path where plots of hypothetical sound surfaces will be stored")}
ref = geomorph::mshape(threeD.out)
e <- seewave::spectro(SoundShape::cuvieri, f=f, wl=wl, ovlp=ovlp, flim=flim, tlim=tlim, plot=F)
freq.seq <- seq(1, length(e$freq), length=y.length)
ifelse(isTRUE(log.scale),
time.seq <- 10^(seq(log10(1), log10(length(e$time)), length.out = x.length)),
time.seq <- seq(1, length(e$time), length.out = x.length))
time.sub <- e$time[time.seq]
freq.sub <- e$freq[freq.seq]
if(is.character(PC)){
if(PC=="mean"){
mean.hPC <- matrix(ref[,3], nrow=y.length, ncol=x.length, byrow = T)
if(plot.exp==TRUE){
oldpar <- graphics::par(no.readonly = TRUE)
base::on.exit(graphics::par(oldpar))
if(plot.as == "jpeg"){
grDevices::jpeg(width=4000,height=3500,units="px",res=500,
filename=paste(store.at,"/", "Hypothetical surfaces - Mean shape", ".jpg", sep=""))}
if(plot.as=="tiff"|plot.as=="tif"){
grDevices::tiff(width=4000, height=3500, units="px", res=500,
filename=paste(store.at,"/", "Hypothetical surfaces - Mean shape",".tif", sep=""))}
}
graphics::par(mar=c(1,2,2,2))
plot3D::persp3D(x=time.sub, y=freq.sub, z=t(mean.hPC), theta=rotate.Xaxis, phi=rotate.Yaxis, resfac=1, r=3,
expand=0.5, scale=T, axes=T, ticktype="detailed", nticks=4,
cex.axis=cex.axis, cex.lab=cex.lab, cex.main=cex.main,
border="black", lwd=lwd, col=seewave::spectro.colors(n=100),
xlab=xlab, ylab=ylab, zlab=zlab, main="Mean shape", clab=expression('Amplitude'),
colkey=colkey)
if(plot.exp==TRUE){grDevices::dev.off()}
}
else{stop('Invalid or misspelled PC argument. Please choose between "mean" (for mean shape configuration) or a number representing the intended Principal Component. See help(hypo.surf) for details.')}
}
if(is.numeric(PC)){
PCmax <- PC*2
PCmin <- (PC*2)-1
PCA.out = stats::prcomp(geomorph::two.d.array(threeD.out))
pcdata = PCA.out$x
p = dim(threeD.out)[1]
k = dim(threeD.out)[2]
shapes <- shape.names <- NULL
for (i in 1:ncol(pcdata)) {
pcaxis.min <- min(pcdata[, i])
pcaxis.max <- max(pcdata[, i])
pc.min <- pc.max <- rep(0, dim(pcdata)[2])
pc.min[i] <- pcaxis.min
pc.max[i] <- pcaxis.max
pc.min <- as.matrix(pc.min %*% (t(PCA.out$rotation))) +
as.vector(t(ref))
pc.max <- as.matrix(pc.max %*% (t(PCA.out$rotation))) +
as.vector(t(ref))
shapes <- rbind(shapes, pc.min, pc.max)
shape.names <- c(shape.names, paste("PC", i, "min", sep = ""),
paste("PC", i, "max", sep = ""))
}
shapes <- geomorph::arrayspecs(shapes, p, k)
shapes <- lapply(seq(dim(shapes)[3]), function(x) shapes[, , x])
names(shapes) <- shape.names
if(PC > (length(shapes)/2)){
stop('Invalid number of Principal Components')}
min.hPC <- matrix(shapes[[PCmin]][,3], nrow=y.length, ncol=x.length, byrow = T)
max.hPC <- matrix(shapes[[PCmax]][,3], nrow=y.length, ncol=x.length, byrow = T)
if(plot.exp==TRUE){
if(plot.as == "jpeg"){
grDevices::jpeg(width=8000,height=3500,units="px",res=500,
filename=paste(store.at,"/", "Hypothetical surfaces - PC", PC, ".jpg", sep=""))}
if(plot.as=="tiff"|plot.as=="tif"){
grDevices::tiff(width=8000, height=3500, units="px", res=500,
filename=paste(store.at,"/", "Hypothetical surfaces - PC", PC,".tif", sep=""))}
}
graphics::par(mfrow=c(1,2), mar=c(0,2,2,2))
plot3D::persp3D(x=time.sub, y=freq.sub, z=t(min.hPC), theta=rotate.Xaxis, phi=rotate.Yaxis, resfac=1, r=3,
expand=0.5, scale=T, axes=T, ticktype="detailed", nticks=4,
cex.axis=cex.axis, cex.lab=cex.lab, cex.main=cex.main,
border="black", lwd=lwd, col=seewave::spectro.colors(n=100),
xlab=xlab, ylab=ylab, zlab=zlab,
clab=expression('Amplitude'), main=paste("PC", PC, " - Minimum", sep=""),
colkey=colkey)
plot3D::persp3D(x=time.sub, y=freq.sub, z=t(max.hPC), theta=rotate.Xaxis, phi=rotate.Yaxis, resfac=1, r=3,
expand=0.5, scale=T, axes=T, ticktype="detailed", nticks=4,
cex.axis=cex.axis, cex.lab=cex.lab, cex.main=cex.main,
border="black", lwd=lwd, col=seewave::spectro.colors(n=100),
xlab=xlab, ylab=ylab, zlab=zlab,
clab=expression('Amplitude'), main=paste("PC", PC, " - Maximum", sep=""),
colkey=colkey)
if(plot.exp==TRUE){grDevices::dev.off()}
}
} |
create_Wlong_mats <- function (model_data, model_info, initial_values, priors,
control) {
betas <- initial_values$betas
b <- initial_values$b
gammas <- initial_values$gammas
bs_gammas <- initial_values$bs_gammas
alphas <- initial_values$alphas
Time_right <- model_data$Time_right
Time_left <- model_data$Time_left
Time_start <- model_data$Time_start
delta <- model_data$delta
which_event <- model_data$which_event
which_right <- model_data$which_right
which_left <- model_data$which_left
which_interval <- model_data$which_interval
W0_H <- model_data$W0_H
W_H <- model_data$W_H
X_H <- model_data$X_H
Z_H <- model_data$Z_H
U_H <- model_data$U_H
W0_h <- model_data$W0_h
W_h <- model_data$W_h
X_h <- model_data$X_h
Z_h <- model_data$Z_h
U_h <- model_data$U_h
W0_H2 <- model_data$W0_H2
W_H2 <- model_data$W_H2
X_H2 <- model_data$X_H2
Z_H2 <- model_data$Z_H2
U_H2 <- model_data$U_H2
n <- model_data$n
idT <- model_data$idT
log_Pwk <- model_data$log_Pwk
log_Pwk2 <- model_data$log_Pwk2
FunForms_per_outcome <- model_info$FunForms_per_outcome
Funs_FunsForms <- model_info$Funs_FunsForms
id_H <- rep(list(rep(unclass(idT), each = control$GK_k)), length(X_H))
eta_H <- linpred_surv(X_H, betas, Z_H, b, id_H)
Wlong_H <- create_Wlong(eta_H, FunForms_per_outcome, U_H, Funs_FunsForms)
if (length(which_event)) {
id_h <- rep(list(unclass(idT)), length(X_h))
eta_h <- linpred_surv(X_h, betas, Z_h, b, id_h)
Wlong_h <- create_Wlong(eta_h, FunForms_per_outcome, U_h,
Funs_FunsForms)
} else {
Wlong_h <- rep(list(matrix(0.0, length(Time_right), 1)), length(Wlong_H))
}
if (length(which_interval)) {
id_H2 <- lapply(X_H2, function (i, n) rep(seq_len(n), each = control$GK_k), n = n)
eta_H2 <- linpred_surv(X_H2, betas, Z_H, b, id_H2)
Wlong_H2 <- create_Wlong(eta_H2, FunForms_per_outcome, U_H2,
Funs_FunsForms)
} else {
Wlong_H2 <- rep(list(matrix(0.0, control$GK_k * n, 1)), length(Wlong_H))
}
list(Wlong_H = Wlong_H, Wlong_h = Wlong_h, Wlong_H2 = Wlong_H2)
} |
set.seed(1234)
subject1 = trunc(rnorm(30, mean=60, sd=15))
range(subject1)
subject1
marks = data.frame(subject1)
head(marks)
marks
sort(marks$subject1)
k2 = kmeans(marks, centers=2)
k2
k2$size
k2$iter
cbind(marks, k2$cluster)
length(marks[k2$cluster==1,])
marks[k2$cluster==2,]
marks[k2$cluster==1,]
mean(marks[k2$cluster==1,])
mean(marks[k2$cluster==2,])
k2$centers
k2a = kmeans(marks, centers=c(50,70))
k2a
k2a$centers
head(iris)
head(mtcars)
marks
subject
subject1 = trunc(rnorm(30, mean=60, sd=15))
subject1
scale(subject1)
cbind(subject1, scale(subject1))
?scale
scale(mtcars) |
context("Dissolution Profile Tolerance Intervals")
test_that("mztia_succeeds_CAPABILITY", {
m_alpha_P <- matrix(c(rep(c(0.01, 0.05, 0.1), each = 3),
1 - rep(c(0.1, 0.05, 0.01), times = 3)),
ncol = 2, byrow = FALSE)
ll <-
apply(m_alpha_P, MARGIN = 1, FUN = function(x)
mztia(data = dip5, shape = "long", tcol = 1, grouping = "type",
reference = "reference", response = "weight", alpha = x[1],
P = x[2], cap = FALSE, bounds = c(0, 100), QS = c(5, 15))
[["Data"]][102, "weight"])
ul <-
apply(m_alpha_P, MARGIN = 1, FUN = function(x)
mztia(data = dip5, shape = "long", tcol = 1, grouping = "type",
reference = "reference", response = "weight", alpha = x[1],
P = x[2], cap = FALSE, bounds = c(0, 100), QS = c(5, 15))
[["Data"]][103, "weight"])
expect_equal(signif(ll, 4), c(11.92, 11.90, 11.86, 11.92, 11.90, 11.87,
11.92, 11.91, 11.88))
expect_equal(signif(ul, 4), c(12.10, 12.12, 12.15, 12.10, 12.11, 12.15,
12.09, 12.11, 12.14))
})
test_that("mztia_succeeds_with_df_shape_long", {
tmp <-
mztia(data = dip5, shape = "long", tcol = 1, grouping = "type",
reference = "reference", response = "weight", alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15))[["Data"]]
expect_equal(signif(tmp[101, "weight"], 9), 12.0093000)
expect_equal(signif(tmp[102, "weight"], 9), 11.8715203)
expect_equal(signif(tmp[103, "weight"], 9), 12.1470797)
expect_equal(signif(tmp[104, "weight"], 9), 6.871520286)
expect_equal(signif(tmp[105, "weight"], 9), 17.1470797)
expect_equal(signif(tmp[106, "weight"], 9), -3.1284797)
expect_equal(signif(tmp[107, "weight"], 9), 27.1470797)
})
test_that("mztia_succeeds_with_df_shape_wide", {
tmp1 <- mztia(data = dip1, shape = "wide", tcol = 3:10, grouping = "type",
reference = "R", response = NULL, alpha = 0.05, P = 0.99,
cap = FALSE, bounds = c(0, 100), QS = c(5, 15))[["Data"]]
tmp2 <- mztia(data = dip1, shape = "wide", tcol = 3:10, grouping = "type",
reference = "R", response = NULL, alpha = 0.05, P = 0.99,
cap = TRUE, bounds = c(0, 100), QS = c(5, 15))[["Data"]]
expect_equal(
signif(tmp1[tmp1$type1 == "Mean" & tmp1$type2 == "Mean", "response"], 9),
c(46.7716667, 60.1333333, 67.2750000, 71.9866667, 78.0700000,
84.8166667, 89.0933333, 91.4383333))
expect_equal(
signif(tmp1[tmp1$type1 == "TL" & tmp1$type2 == "LTL", "response"], 9),
c(27.2264050, 46.1548274, 56.9041726, 65.4435423, 69.5425900, 77.2027513,
76.2458801, 80.2932086))
expect_equal(
signif(tmp1[tmp1$type1 == "TL" & tmp1$type2 == "UTL", "response"], 9),
c(66.3169283, 74.1118393, 77.6458274, 78.5297910, 86.5974100, 92.4305820,
101.940787, 102.583458))
expect_equal(
signif(tmp1[tmp1$type1 == "TL.S1" & tmp1$type2 == "LTL", "response"], 9),
c(22.2264050, 41.1548274, 51.9041726, 60.4435423, 64.5425900, 72.2027513,
71.2458801, 75.2932086))
expect_equal(
signif(tmp1[tmp1$type1 == "TL.S1" & tmp1$type2 == "UTL", "response"], 9),
c(71.3169283, 79.1118393, 82.6458274, 83.5297910, 91.5974100, 97.4305820,
106.940787, 107.583458))
expect_equal(
signif(tmp1[tmp1$type1 == "TL.S2" & tmp1$type2 == "LTL", "response"], 9),
c(12.2264050, 31.1548274, 41.9041726, 50.4435423, 54.5425900, 62.2027513,
61.2458801, 65.2932086))
expect_equal(
signif(tmp1[tmp1$type1 == "TL.S2" & tmp1$type2 == "UTL", "response"], 9),
c(81.3169283, 89.1118393, 92.6458274, 93.5297910, 101.5974100, 107.430582,
116.940787, 117.583458))
expect_equal(
signif(tmp2[tmp2$type1 == "TL" & tmp2$type2 == "UTL", "response"], 9),
c(66.3169283, 74.1118393, 77.6458274, 78.5297910, 86.5974100, 92.4305820,
100.000000, 100.000000))
expect_equal(
signif(tmp2[tmp2$type1 == "TL.S1" & tmp2$type2 == "UTL", "response"], 9),
c(71.3169283, 79.1118393, 82.6458274, 83.5297910, 91.5974100, 97.4305820,
105.000000, 105.000000))
expect_equal(
signif(tmp2[tmp2$type1 == "TL.S2" & tmp2$type2 == "UTL", "response"], 9),
c(81.3169283, 89.1118393, 92.6458274, 93.5297910, 101.5974100, 107.430582,
115.000000, 115.000000))
})
test_that("mztia_fails", {
tmp0 <- dip1
tmp0$t.5 <- as.factor(tmp0$t.5)
tmp1 <- dip1
tmp1$type <- as.character(tmp1$type)
expect_error(
mztia(data = as.matrix(dip1[, 3:10]), shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"data must be provided as data frame")
expect_error(
mztia(data = dip1, shape = 1, tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"shape must be a string")
expect_error(
mztia(data = dip1, shape = "weit", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"specify shape")
expect_error(
mztia(data = dip1, shape = "wide", tcol = "tico",
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"tcol must be an integer")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10 + 0.1,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"tcol must be an integer")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 7:11,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"Some columns specified by tcol were not found")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 7,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"Did you provide a data frame")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 2:6,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"Some names of columns specified by tcol")
expect_error(
mztia(data = tmp0, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"Some columns specified by tcol are not numeric")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = 5, reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"grouping must be a string")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "lot", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"grouping variable was not found")
expect_error(
mztia(data = tmp1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"grouping variable's column in data")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = 1, response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"reference must be a string")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "REF", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"The reference variable was not found")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "type", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"The reference variable was not found")
expect_error(
mztia(data = dip5, shape = "long", tcol = 3, grouping = "type",
reference = "reference", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"data frame provided via data is in long format"
)
expect_error(
mztia(data = dip5, shape = "long", tcol = 3, grouping = "type",
reference = "reference", response = 5, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"response must be a string of length 1"
)
expect_error(
mztia(data = dip5, shape = "long", tcol = 3, grouping = "type",
reference = "reference", response = c("type", "batch"), alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"response must be a string of length 1"
)
expect_error(
mztia(data = dip5, shape = "long", tcol = 3, grouping = "type",
reference = "reference", response = "assay", alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"response variable was not found"
)
expect_error(
mztia(data = dip5, shape = "long", tcol = 3, grouping = "type",
reference = "reference", response = "type", alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"column specified by response is not numeric"
)
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = -1,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"specify alpha")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 9,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"specify alpha")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = -1, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"specify P")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 9, cap = FALSE, bounds = c(0, 100), QS = c(5, 15)),
"specify P")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = 0, bounds = c(0, 100), QS = c(5, 15)),
"cap must be a logical")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c("l", "u"), QS = c(5, 15)),
"bounds must be a numeric vector")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(5, 50, 90), QS = c(5, 15)),
"bounds must be a numeric vector")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(100, 0), QS = c(5, 15)),
"specify bounds in the form")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c("l", "u")),
"QS must be a numeric vector")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 15, 30)),
"QS must be a numeric vector")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(-5, 15)),
"specify QS in the range")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(5, 105)),
"specify QS in the range")
expect_error(
mztia(data = dip1, shape = "wide", tcol = 3:10,
grouping = "type", reference = "R", response = NULL, alpha = 0.05,
P = 0.99, cap = FALSE, bounds = c(0, 100), QS = c(15, 5)),
"Q S1 must be smaller Q S2")
}) |
getPDF <- function(x)
{
txtfiles <- character(length(x))
for (i in 1:length(x))
{
system(paste('pdftotext -q -enc "ASCII7" "', x[i], '"', sep = ""))
if (file.exists(gsub("\\.pdf$", "\\.txt", x[i]))) {
fileName <- gsub("\\.pdf$", "\\.txt", x[i])
txtfiles[i] <- readChar(fileName, file.info(fileName)$size)
} else{
warning(paste("Failure in file", x[i]))
txtfiles[i] <- ""
}
}
return(txtfiles)
}
checkPDFdir <-
function(dir,
subdir = TRUE,
...) {
if (missing(dir))
dir <- tk_choose.dir()
all.files <-
list.files(dir,
pattern = "\\.pdf",
full.names = TRUE,
recursive = subdir)
files <- all.files[grepl("\\.pdf$", all.files)]
if (length(files) == 0)
stop("No PDF found")
txts <- character(length(files))
message("Importing PDF files...")
pb <- txtProgressBar(max = length(files), style = 3)
for (i in 1:length(files))
{
txts[i] <- getPDF(files[i])
setTxtProgressBar(pb, i)
}
close(pb)
names(txts) <- gsub("\\.pdf$", "", basename(files))
return(statcheck(txts, ...))
}
checkPDF <-
function(files, ...) {
if (missing(files))
files <- tk_choose.files()
txts <- sapply(files, getPDF)
names(txts) <-
gsub("\\.pdf$", "", basename(files), perl = TRUE)
return(statcheck(txts, ...))
} |
library(testthat)
test_that("check truncation constructor", {
expect_silent(truncate(Binomial$new(), lower = 1, upper = 5))
expect_silent(truncate(Binomial$new(), upper = 5))
expect_silent(truncate(Binomial$new(), lower = 1))
expect_equal(truncate(Binomial$new())$inf, 1)
expect_equal(truncate(Binomial$new())$sup, 10)
expect_equal(truncate(Binomial$new(), lower = -Inf, upper = Inf)$inf, 1)
expect_equal(truncate(Binomial$new(), lower = -Inf, upper = Inf)$sup, 10)
expect_error(TruncatedDistribution$new(MultivariateNormal$new()), "multivariate")
expect_error(truncate(MixtureDistribution$new(list(Binomial$new(), Normal$new())), 1, 2),
"mixed")
})
t <- truncate(Binomial$new(), lower = 1, upper = 5)
test_that("pdf", {
expect_equal(t$pdf(6), 0)
expect_equal(t$pdf(0), 0)
expect_equal(
t$pdf(4),
dbinom(4, prob = 0.5, size = 10) / ((pbinom(5, prob = 0.5, size = 10) -
pbinom(1, prob = 0.5, size = 10)))
)
expect_equal(
t$pdf(4, log = TRUE),
log(dbinom(4, prob = 0.5, size = 10) / ((pbinom(5, prob = 0.5, size = 10) -
pbinom(1, prob = 0.5, size = 10))))
)
})
test_that("cdf", {
expect_equal(t$cdf(5), 1)
expect_equal(t$cdf(6), 1)
expect_equal(t$cdf(0), 0)
expec <- (pbinom(4, prob = 0.5, size = 10) - pbinom(1, prob = 0.5, size = 10)) /
(pbinom(5, prob = 0.5, size = 10) - pbinom(1, prob = 0.5, size = 10))
expect_equal(t$cdf(4, log.p = FALSE, lower.tail = TRUE), expec)
expect_equal(t$cdf(4, log.p = TRUE, lower.tail = TRUE), log(expec))
expect_equal(t$cdf(4, log.p = FALSE, lower.tail = FALSE), 1 - expec)
expect_equal(t$cdf(4, log.p = TRUE, lower.tail = FALSE), log(1 - expec))
})
test_that("quantile", {
expect_equal(t$.__enclos_env__$private$.quantile(-20), 1)
expect_equal(t$.__enclos_env__$private$.quantile(20), 5)
expect_equal(t$quantile(0.1), 3)
r <- expect_silent({t$rand(5)})
expect_length(r, 5)
expect_true(all(r >= 1) & all(r <= 5))
})
test_that("strprint", {
expect_equal(t$properties$support$strprint(), Interval$new(2, 5, class = "integer")$strprint())
expect_equal(
truncate(Exponential$new(), lower = 2, upper = 3)$properties$support$strprint(),
Interval$new(2, 3, type = "(]")$strprint()
)
})
test_that("check missing", {
expect_error(truncate(Distribution$new("Test", pdf = dnorm), 1, 2))
expect_error(truncate(Distribution$new("Test", cdf = pnorm), 1, 2))
})
test_that("check truncation parameters", {
x <- truncate(Binomial$new(), lower = 1, upper = 5)
expect_equal(x$inf, 2)
expect_equal(x$sup, 5)
expect_equal(x$getParameterValue("trunc__lower"), 1)
expect_equal(x$getParameterValue("trunc__upper"), 5)
expect_silent(x$setParameterValue(trunc__lower = 2))
expect_silent(x$setParameterValue(trunc__upper = 10))
expect_equal(x$inf, 3)
expect_equal(x$sup, 10)
expect_equal(x$getParameterValue("trunc__lower"), 2)
expect_equal(x$getParameterValue("trunc__upper"), 10)
expect_error(x$setParameterValue(trunc__upper = 1))
expect_error(x$setParameterValue(trunc__lower = 12))
expect_error(x$setParameterValue(trunc__lower = 4, trunc__upper = 3))
x <- truncate(Exponential$new(), lower = 1, upper = 5)
expect_silent(x$setParameterValue(trunc__lower = 2, trunc__upper = 10))
expect_equal(x$inf, 2)
expect_equal(x$sup, 10)
expect_true(testInterval(x$properties$support))
})
test_that("missing pdf/cdf", {
expect_error(truncate(Distribution$new("a", pdf = function(x) x, type = Reals$new())),
"pdf and cdf")
}) |
test_that("match-param", {
foo <- function(x = NULL, y = c(1, 2, 3)) {
y <- match_param(y)
x
}
expect_null(foo())
expect_null(foo(y = 1))
expect_error(
foo(y = 4),
'`match_param(y)` failed in `foo(y = 4)`:
`y` [4] must be one of the following: "1", "2", "3"',
fixed = TRUE
)
foo2 <- function(y = 1:3) {
match_param(y)
}
expect_equal(foo2(1), 1)
expect_equal(foo2(1L), 1L)
expect_equal(foo2("1"), 1)
foo <- function(x = NULL) {
match_param(tolower(x), c("a", "b", "c"))
}
expect_error(
foo(),
'`match_param(tolower(x))` failed in `foo()`:
`tolower(x)` [character(0)] must be one of the following: "a", "b", "c"',
fixed = TRUE
)
foo <- function(x = c("a", "b")) {
match_param(x)
}
expect_error(foo(NULL), "non-NULL")
})
test_that("match_arg() works", {
foo <- function(x = c("a", "b"), table) {
match_arg(x, table)
}
expect_null(foo(NULL))
expect_identical(foo(), "a")
expect_identical(foo(table = "a"), "a")
expect_error(foo(table = "c"))
}) |
is_dir <- function(x, .xname = get_name_in_parent(x))
{
x <- coerce_to(x, "character", .xname)
call_and_name(
function(x)
{
ok <- file.info(x)$isdir
causes <- ifelse(
is.na(ok),
"nonexistent",
ifelse(ok, "", "file")
)
ok <- is_true(ok)
set_cause(ok, causes)
},
x
)
}
is_existing_file <- function(x, .xname = get_name_in_parent(x))
{
x <- coerce_to(x, "character", .xname)
x <- sub("[\\/]+$", "", x)
call_and_name(
function(x)
{
ok <- file.exists(x)
set_cause(ok, ifelse(ok, "", "nonexistent"))
},
x
)
}
is_executable_file <- function(x, warn_about_windows = TRUE, .xname = get_name_in_parent(x))
{
if(warn_about_windows)
{
warn_about_file.access_under_windows()
}
x <- coerce_to(x, "character", .xname)
call_and_name(
function(x)
{
ok <- file.access(x, mode = 1) == 0L
set_cause(
ok,
ifelse(file.exists(x), "unexecutable", "nonexistent")
)
},
x
)
}
is_ex_file <- function(x)
{
.Defunct("is_executable_file")
is_executable_file(x)
}
is_library <- function(x, .xname = get_name_in_parent(x))
{
x <- coerce_to(x, "character", .xname)
call_and_name(
function(x)
{
std_x <- normalizePath(path.expand(x), winslash = "/", mustWork = FALSE)
set_cause(std_x %in% .libPaths(), "not a lib")
},
x
)
}
is_readable_file <- function(x, warn_about_windows = TRUE, .xname = get_name_in_parent(x))
{
if(warn_about_windows)
{
warn_about_file.access_under_windows()
}
x <- coerce_to(x, "character", get_name_in_parent(x))
call_and_name(
function(x)
{
ok <- file.access(x, mode = 4) == 0L
set_cause(
ok,
ifelse(file.exists(x), "unreadable", "nonexistent")
)
},
x
)
}
is_writable_file <- function(x, warn_about_windows = TRUE, .xname = get_name_in_parent(x))
{
if(warn_about_windows)
{
warn_about_file.access_under_windows()
}
x <- coerce_to(x, "character", .xname)
call_and_name(
function(x)
{
ok <- file.access(x, mode = 2) == 0L
set_cause(
ok,
ifelse(file.exists(x, "unwritable", "nonexistent"))
)
},
x
)
}
warn_about_file.access_under_windows <- function()
{
if(.Platform$OS.type == "windows")
{
warning(
"This function depends on file.access, which can give unexpected results under Windows."
)
}
} |
test_that("only valid types can be passed to functions", {
expect_error(trajectory() %>% set_attribute("test", "string_value"))
expect_error(trajectory() %>% set_attribute("test", NA))
expect_error(trajectory() %>% set_attribute(NA, 1))
expect_error(trajectory() %>% set_attribute("test", 1, mod="asdf"))
t0 <- trajectory() %>%
set_attribute(c("a", "b", "c"), c(1, 2))
env <- simmer(verbose = TRUE) %>%
add_generator("entity", t0, at(0))
expect_error(run(env))
})
test_that("an arrival attribute is correctly set and returned to a function", {
t0 <- trajectory() %>%
set_attribute(
c("att1", "att2"),
c(1, 2)
) %>%
timeout(1) %>%
set_global(
function() c("glb1", "glb2"),
c(1, 2)
) %>%
timeout(1) %>%
set_attribute(
c("att3", "att4"),
function() get_attribute(env, c("att1", "att2"))
) %>%
timeout(1) %>%
set_global(
function() c("glb3", "glb4"),
function() get_global(env, c("glb1", "glb2"))
) %>%
log_(function()
paste0(get_attribute(env, "att1"),
get_attribute(env, "asdf"),
get_global(env, "glb1"),
get_global(env, "asdf"))) %>%
timeout(1) %>%
set_attribute(
c("att3", "att4"),
c(5, 5), mod="+"
) %>%
timeout(1) %>%
set_global(
function() c("glb3", "glb4"),
c(5, 5), mod="*"
)
env <- simmer(verbose = TRUE) %>%
add_generator("entity", t0, at(0), mon=2)
expect_output(run(env), ".*1NA1NA")
attributes <- env %>% get_mon_attributes()
expect_equal(nrow(attributes), 12)
expect_equal(attributes$time, rep(0:5, each=2))
expect_equal(attributes$name, rep(c("entity0", ""), each=2, times=3))
keys <- c(1, 2, 1, 2, 3, 4, 3, 4, 3, 4, 3, 4)
values <- c(1, 2, 1, 2, 1, 2, 1, 2, 6, 7, 5, 10)
expect_equal(attributes$key, paste0(rep(c("att", "glb"), each=2, times=2), keys))
expect_equal(attributes$value, values)
})
test_that("the attribute dataframe is returned with the expected columns", {
t0 <- trajectory() %>%
set_attribute("test", 123) %>%
set_global("test", 456)
env <-
simmer(verbose = TRUE) %>%
add_generator("entity", t0, at(0), mon = 1) %>%
run()
attributes <- env %>% get_mon_attributes()
expect_true(all(sapply(colnames(attributes), function(x) x %in% colnames(attributes))))
})
test_that("arrival attributes are returned empty when mon level is < 2", {
t0 <- trajectory() %>%
set_attribute("test", 123) %>%
set_global("test", 456)
env <-
simmer(verbose = TRUE) %>%
add_generator("entity", t0, at(0), mon = 1) %>%
run()
attributes <- env %>% get_mon_attributes()
expect_equal(nrow(attributes), 1)
expect_equal(attributes[1, ]$name, "")
expect_equal(attributes[1, ]$key, "test")
expect_equal(attributes[1, ]$value, 456)
})
test_that("attributes are automatically initialised with modifiers", {
t <- trajectory() %>%
set_attribute("asdf", 1, mod="+") %>%
set_global("fdsa", 2, mod="+", init=3)
attr <- simmer() %>%
add_generator("dummy", t, at(0), mon=2) %>%
run() %>%
get_mon_attributes()
expect_equal(attr$value, c(1, 5))
})
test_that("get_global works outside a trajectory", {
expect_equal(get_global(simmer(), "test"), NA_real_)
}) |
mcmc.fmem <-
function(params){
rmvnorm.l <- function(mean, sigma){
d <- length(mean)
sigma2 <- chol(sigma)
t(mean + t(sigma2)%*%rnorm(d))
}
Wishart <- function(df,Omega){
p <- ncol(Omega)
x <- matrix(rnorm(df*p),df,p)
chole <- chol(Omega)
t(chole)%*%(t(x)%*%x)%*%chole
}
burn.in <- params$burn.in
post.sam.s <- params$post.sam.s
thin <- params$thin
y <- params$y
p <- params$p
q <- params$q
ks <- params$ks
u <- params$u
pdf <- params$pdf
cdf <- params$cdf
n <- params$n
kappa <- params$kappa
omeg <- 1/params$omeg
family <- params$family
homo <- params$homo
if(homo == 0) heter <- params$heter
total <- burn.in + post.sam.s*thin
ancho <- floor(seq(2, total, length=10))
bar <- txtProgressBar(min=0, max=ancho[10], initial=0, width=50, char="+", style=3)
mu_m0 <- rep(0,q)
sigma2_mu0 <- diag(q)*1000
sigma2_mu0.I <- solve(sigma2_mu0)
nu_m <- q
omega_m <- diag(q)*1000
a.sigma2_y <- 0.0001/2
b.sigma2_y <- 0.0001/2
rho.a <- matrix(0,total,q)
rho0 <- rep(0,q)
S.rho <- diag(q)*1000
S.rho.I <- solve(S.rho)
rho.a[1,] <- params$rho.i
M <- params$M
params$rho0 <- rho0
params$S.rho <- S.rho
sigma2_m.a <- array(0,c(q,q,total))
sigma2_m.a2 <- array(0,c(q,q,total))
mu_m.a <- matrix(0,total,q)
m_i.a <- matrix(0,n,q)
sigma2_y.a <- matrix(0,total,1)
sigma2_m.a[,,1] <- as.matrix(var(M))
mu_m.a[1,] <- apply(M,2,mean)
m_i.a <- M
sigma2_y.a[1] <- params$sigma2_y
beta.a <- matrix(0,total,p)
beta0 <- rep(0,p)
S.beta <- diag(p)*1000
S.beta.II <- matrix(0,p+q,p+q)
S.beta.II[1:p,1:p] <- solve(S.beta)
S.beta.II[(p+1):(p+q),(p+1):(p+q)] <- S.rho.I
beta_rho0 <- matrix(0,p+q,1)
beta_rho0[1:p] <- beta0
beta_rho0[(p+1):(q+p)] <- rho0
beta.a[1,] <- params$beta.i
X <- params$X
params$beta0 <- beta0
params$S.beta <- S.beta
tau.a <- matrix(0,total,length(ks))
a.tau <- 0.001
b.tau <- 0.001
if(sum(ks) > 0){
alpha.a <- matrix(0,total,sum(ks))
alpha.a[1,] <- params$alpha.i
B <- params$B
}
else{alpha.a <- matrix(0,total,1)
B <- matrix(1,n,1)
}
cont <- 1
uii <- matrix(0,n,1)
inv.omega_m <- solve(omega_m)
if(family!="Normal" && family!="Laplace" && attr(params$eta,"know")==0){
extra.parameter <- params$extra.parameter
nu0 <- params$nu0
nu.a <- matrix(0,total,length(nu0))
nu.a[1,] <- nu0
}else{
nu.a <- kronecker(matrix(1,total,length(params$eta)),t(params$eta))
}
for(l in 2:total){
M_m <- 0
omega_m.a <- matrix(0,ncol(M),ncol(M))
if(homo == 1){
ss <- (y - X%*%beta.a[l-1,] - m_i.a%*%rho.a[l-1,]- B%*%alpha.a[l-1,])^2/sigma2_y.a[l-1] + apply((M - m_i.a)^2,1,sum)/(sigma2_y.a[l-1]*omeg) +
diag((m_i.a-kronecker(t(mu_m.a[l-1,]),matrix(1,n,1)))%*%tcrossprod(sigma2_m.a[,,l-1],(m_i.a-kronecker(t(mu_m.a[l-1,]),matrix(1,n,1)))))
}
else{
ss <- (y - X%*%beta.a[l-1,] - m_i.a%*%rho.a[l-1,]- B%*%alpha.a[l-1,])^2/heter$sigma2y + apply((M - m_i.a)^2/(heter$sigma2xi),1,sum) +
diag((m_i.a-kronecker(t(mu_m.a[l-1,]),matrix(1,n,1)))%*%tcrossprod(sigma2_m.a[,,l-1],(m_i.a-kronecker(t(mu_m.a[l-1,]),matrix(1,n,1)))))
}
if(family!="Hyperbolic" && family!="Laplace") uii <- u(ss,nu.a[l-1,])
if(homo == 1){
sig.m_i.a1 <- solve((omeg*sigma2_y.a[l-1])^(-1)*diag(ncol(M)) + sigma2_m.a[,,l-1] + rho.a[l-1,]%*%t(rho.a[l-1,])/(sigma2_y.a[l-1]))
chole <- chol(sig.m_i.a1)
}
for(i in 1:n){
if(family=="Hyperbolic" || family=="Laplace") uii[i] <- u(ss[i],nu.a[l-1,])
if(homo == 1){
sig.m_i.a <- kappa(uii[i])*sig.m_i.a1
mu.m_i.a <- sig.m_i.a%*%(sigma2_m.a[,,l-1]%*%mu_m.a[l-1,]/kappa(uii[i]) + (kappa(uii[i])*omeg*sigma2_y.a[l-1])^(-1)*diag(ncol(M))%*%M[i,]
+ rho.a[l-1,]*(y[i]-X[i,]%*%beta.a[l-1,] - B[i,]%*%alpha.a[l-1,])/(sigma2_y.a[l-1]*kappa(uii[i])))
m_i.a[i,] <- mu.m_i.a + sqrt(kappa(uii[i]))*crossprod(chole,rnorm(q))
}else{
dfg <- diag(q)
diag(dfg) <- 1/heter$sigma2xi[i,]
sig.m_i.a <- kappa(uii[i])*solve( dfg + sigma2_m.a[,,l-1] + rho.a[l-1,]%*%t(rho.a[l-1,])/(heter$sigma2y[i]))
chole <- chol(sig.m_i.a)
mu.m_i.a <- sig.m_i.a%*%(sigma2_m.a[,,l-1]%*%mu_m.a[l-1,]/kappa(uii[i]) + M[i,]/(heter$sigma2xi[i,]*kappa(uii[i]))
+ rho.a[l-1,]*(y[i]-X[i,]%*%beta.a[l-1,] - B[i,]%*%alpha.a[l-1,])/(heter$sigma2y[i]*kappa(uii[i])))
m_i.a[i,] <- mu.m_i.a + crossprod(chole,rnorm(q))
}
omega_m.a <- omega_m.a + tcrossprod((m_i.a[i,]-mu_m.a[l-1,]),(m_i.a[i,]-mu_m.a[l-1,]))/kappa(uii[i])
M_m <- M_m + crossprod((M[i,]- m_i.a[i,]),(M[i,] - m_i.a[i,]))/kappa(uii[i])
}
if(family!="Normal" && family!="Laplace" && attr(params$eta,"know")==0){
nu.a[l,] <- extra.parameter(nu.a[l-1,], uii, ss)
}
if(homo ==1){
MX <- cbind(X,m_i.a)
sig.beta.a <- solve(S.beta.II + crossprod(MX,matrix(1/(sigma2_y.a[l-1] * kappa(uii)),n,(p+q))*MX))
mu.beta.a <- sig.beta.a%*%(S.beta.II%*%beta_rho0 + crossprod(MX,matrix(1/(sigma2_y.a[l-1]*kappa(uii)),n,1)*(y-B%*%alpha.a[l-1,])))
temp <- rmvnorm.l(mean=mu.beta.a, sigma=sig.beta.a)
beta.a[l,] <- temp[1:p]
rho.a[l,] <- temp[(p+1):(q+p)]
if(sum(ks) > 0){
alpha.a[l,] <- alpha.a[l-1,]
if(length(ks)==1){
alpha0 <- rep(0,ks)
scale.tau <- 2*b.tau + crossprod(alpha.a[l-1,],alpha.a[l-1,])
tau.a[l,1] <- 1/rgamma(1, shape= (ks/2 + a.tau), scale= 2/scale.tau)
sig.alpha.a <- solve(diag(ks)/tau.a[l,1] + crossprod(B,matrix(1/(sigma2_y.a[l-1]*kappa(uii)),n,ks)*B))
mu.alpha.a <- sig.alpha.a%*%(crossprod(B,(1/(sigma2_y.a[l-1]*kappa(uii)))*(y-X%*%beta.a[l,]-m_i.a%*%rho.a[l,] )))
alpha.a[l,] <- rmvnorm.l(mean=mu.alpha.a,sigma=sig.alpha.a)
}
else{
lmi <- 1
for(i in 1:length(ks)){
alpha0 <- rep(0,ks[i])
B.i <- B[,lmi:(lmi+ks[i]-1)]
scale.tau <- 2*b.tau + crossprod(alpha.a[l-1,lmi:(lmi+ks[i]-1)],alpha.a[l-1,lmi:(lmi+ks[i]-1)])
tau.a[l,i] <- 1/rgamma(1, shape= (ks[i]/2 + a.tau), scale= 2/scale.tau)
sig.alpha.a <- solve(diag(ks[i])/tau.a[l,i] + crossprod(B.i,matrix(1/(sigma2_y.a[l-1]*kappa(uii)),n,ks[i])*B.i))
mu.alpha.a <- sig.alpha.a%*%(crossprod(B.i,(1/(sigma2_y.a[l-1]*kappa(uii)))*(y-X%*%beta.a[l,]-m_i.a%*%rho.a[l,] - B[,-c(lmi:(lmi+ks[i]-1))]%*%alpha.a[l,-c(lmi:(lmi+ks[i]-1))])))
alpha.a[l,lmi:(lmi+ks[i]-1)] <- rmvnorm.l(mean=mu.alpha.a,sigma=sig.alpha.a)
lmi <- lmi + ks[i]
}
}
}else{tau.a[l] <- 0
alpha.a[l,] <- 0}
}else{
MX <- cbind(X,m_i.a)
sig.beta.a <- solve(S.beta.II + crossprod(MX,matrix(1/(heter$sigma2y*kappa(uii)),n,(p+q))*MX))
mu.beta.a <- sig.beta.a%*%(S.beta.II%*%beta_rho0 + crossprod(MX,matrix(1/(heter$sigma2y*kappa(uii)),n,1)*(y-B%*%alpha.a[l-1,])))
temp <- rmvnorm.l(mean=mu.beta.a, sigma=sig.beta.a)
beta.a[l,] <- temp[1:p]
rho.a[l,] <- temp[(p+1):(q+p)]
if(sum(ks) > 0){
alpha.a[l,] <- alpha.a[l-1,]
if(length(ks)==1){
alpha0 <- rep(0,ks)
scale.tau <- 2*b.tau + crossprod(alpha.a[l-1,],alpha.a[l-1,])
tau.a[l,1] <- 1/rgamma(1, shape= (ks/2 + a.tau), scale= 2/scale.tau)
sig.alpha.a <- solve(diag(ks)/tau.a[l,1] + crossprod(B,matrix(1/(heter$sigma2y*kappa(uii)),n,ks)*B))
mu.alpha.a <- sig.alpha.a%*%(crossprod(B,(1/(heter$sigma2y*kappa(uii)))*(y-X%*%beta.a[l,]-m_i.a%*%rho.a[l,] )))
alpha.a[l,] <- rmvnorm.l(mean=mu.alpha.a,sigma=sig.alpha.a)
}
else{
lmi <- 1
for(i in 1:length(ks)){
alpha0 <- rep(0,ks[i])
B.i <- B[,lmi:(lmi+ks[i]-1)]
scale.tau <- 2*b.tau + crossprod(alpha.a[l-1,lmi:(lmi+ks[i]-1)],alpha.a[l-1,lmi:(lmi+ks[i]-1)])
tau.a[l,i] <- 1/rgamma(1, shape= (ks[i]/2 + a.tau), scale= 2/scale.tau)
sig.alpha.a <- solve(diag(ks[i])/tau.a[l,i] + crossprod(B.i,matrix(1/(heter$sigma2y*kappa(uii)),n,ks[i])*B.i))
mu.alpha.a <- sig.alpha.a%*%(crossprod(B.i,(1/(heter$sigma2y*kappa(uii)))*(y-X%*%beta.a[l,]-m_i.a%*%rho.a[l,] - B[,-c(lmi:(lmi+ks[i]-1))]%*%alpha.a[l,-c(lmi:(lmi+ks[i]-1))])))
alpha.a[l,lmi:(lmi+ks[i]-1)] <- rmvnorm.l(mean=mu.alpha.a,sigma=sig.alpha.a)
lmi <- lmi + ks[i]
}
}
}else{tau.a[l] <- 0
alpha.a[l,] <- 0}
}
sig.mu_m.a <- solve(sigma2_mu0.I + sigma2_m.a[,,l-1]*n*mean(1/kappa(uii)))
mu.mu_m.a <- sig.mu_m.a%*%(sigma2_mu0.I%*%mu_m0 + n*(sigma2_m.a[,,l-1])%*%apply(as.matrix(m_i.a)/matrix(kappa(uii),n,q),2,mean))
mu_m.a[l,] <- rmvnorm.l(mean=mu.mu_m.a, sigma=sig.mu_m.a)
sigma2_m.a[,,l] <- Wishart(n+q, solve(inv.omega_m + omega_m.a))
sigma2_m.a2[,,l] <- solve(sigma2_m.a[,,l])
if(homo==1){
scale.sigma2_y <- sum((y-X%*%beta.a[l,]-m_i.a%*%rho.a[l,]-B%*%alpha.a[l,])^2/kappa(uii)) + (1/omeg)*M_m + b.sigma2_y
sigma2_y.a[l] <- 1/rgamma(1,shape= ((n*(1+q) + a.sigma2_y)/2), scale=2/scale.sigma2_y)
}
if(l==ancho[cont]){
Sys.sleep(0.5);
setTxtProgressBar(bar,ancho[cont])
cont <- cont + 1
}
l <- l + 1
}
close(bar)
size <- seq(burn.in+thin,total,length=post.sam.s)
if(attr(params$eta,"know")==0){
aa <- matrix(0,post.sam.s,p+3*q+sum(ks)+1+length(nu0)+length(ks))}
else{aa <- matrix(0,post.sam.s,p+3*q+sum(ks)+1+length(ks))}
cad <- as.vector(" ")
aa[,1:p] <- beta.a[size,]
cad <- cbind(cad,t(paste("beta",1:p)))
aa[,(p+1):(p+q)] <- rho.a[size,]
cad <- cbind(cad,t(paste("rho",1:q)))
aa[,(p+q+1):(p+2*q)] <- mu_m.a[size,]
cad <- cbind(cad,t(paste("mu_m",1:q)))
for(i in 1:q){
aa[,(p+2*q+i)] <- as.vector(sigma2_m.a2[i,i,size])
}
cad <- cbind(cad,t(paste("sigma2_m",1:q)))
if(homo==1){
aa[,(p+3*q+1)] <- sigma2_y.a[size]
cad <- cbind(cad,t(paste("sigma2_y")))
}
if(sum(ks) > 0){
aa[,(p+3*q+2):(p+3*q+1+sum(ks))] <- alpha.a[size,]
aa[,(p+3*q+sum(ks)+2):(p+3*q+sum(ks)+1+length(ks))] <- tau.a[size,]
cad <- cbind(cad,t(colnames(B)))
}
if(attr(params$eta,"know")==0){
if(ncol(nu.a)==1) {
cond <- var(nu.a[size])
if(cond==0) nu.a[size[1]] <- 1.1*mean(nu.a[size])
}
if(ncol(nu.a)==2){
cond <- diag(var(nu.a[size,]))
if(cond[1]==0) nu.a[size[1],1] <- 0.98*mean(nu.a[size,1])
if(cond[2]==0) nu.a[size[1],2] <- 0.98*mean(nu.a[size,2])
}
aa[,(p+3*q+sum(ks)+1+length(ks)+1):(p+3*q+sum(ks)+1+length(ks)+length(nu0))] <- nu.a[size,]
}
if(sum(ks)>0) cad <- cbind(cad,t(paste("tau_alpha",1:length(ks))))
if(family!="Normal" && family!="Laplace" && attr(params$eta,"know")==0){
cad <- cbind(cad,t(paste("eta",1:length(nu0))))
}
haver <- apply(aa,2,var)
aa2 <- aa[,haver!=0]
cad <- cad[2:length(cad)]
colnames(aa2) <- cad
mi <- matrix(0,n,post.sam.s)
D_bar <- 0
sigma_mp <- matrix(0,q+1,q+1)
for(i in 1:post.sam.s){
sigma_mp[1,2:(q+1)] <- rho.a[(burn.in+i),]%*%sigma2_m.a2[,,(burn.in+i)]
sigma_mp[2:(q+1),1] <- t(sigma_mp[1,2:(q+1)])
if(homo==1){
sigma_mp[1,1] <- sigma2_y.a[(burn.in+i)] + crossprod(rho.a[(burn.in+i),],sigma2_m.a2[,,(burn.in+i)]%*%rho.a[(burn.in+i),])
sigma_mp[2:(q+1),2:(q+1)] <- omeg*sigma2_y.a[(burn.in+i)] + sigma2_m.a2[,,(burn.in+i)]
inv.sigma_mp <- solve(sigma_mp)
det_sigma_mp <- det(sigma_mp)
}
comp_s <- X%*%beta.a[(burn.in+i),] + B%*%alpha.a[(burn.in+i),] + sum(rho.a[(burn.in+i),]*mu_m.a[(burn.in+i),])
zz <- matrix(0,q+1,1)
for(j in 1:n){
if(homo==0){
dfg <- diag(q)
diag(dfg) <- heter$sigma2xi[j,]
sigma_mp[1,1] <- heter$sigma2y[j] + crossprod(rho.a[(burn.in+i),],sigma2_m.a2[,,(burn.in+i)]%*%rho.a[(burn.in+i),])
sigma_mp[2:(q+1),2:(q+1)] <- dfg + sigma2_m.a2[,,(burn.in+i)]
inv.sigma_mp <- solve(sigma_mp)
det_sigma_mp <- det(sigma_mp)
}
zz[1] <- y[j]- comp_s[j]
zz[2:(q+1)] <- M[j,] - mu_m.a[(burn.in+i),]
ss <- sqrt(crossprod(zz,inv.sigma_mp)%*%zz)
D_bar <- D_bar - 2*log(pdf(ss,nu.a[(burn.in+i),])) + log(det_sigma_mp)
mi[j,i] <- det_sigma_mp^(1/2)/pdf(ss,nu.a[(burn.in+i),])
}
D_bar <- D_bar
}
D_bar <- D_bar/post.sam.s
D_theta <- 0
if(q >1){
comp_s <- X%*%apply(as.matrix(beta.a[size,]),2,mean) + B%*%apply(as.matrix(alpha.a[size,]),2,mean) + sum(apply(as.matrix(rho.a[size,]),2,mean)*apply(as.matrix(mu_m.a[(size),]),2,mean))
sigma_mp[1,1] <- crossprod(apply(as.matrix(rho.a[size,]),2,mean),apply(sigma2_m.a2[,,size],1:2,mean))%*%apply(as.matrix(rho.a[size,]),2,mean)
sigma_mp[1,2:(q+1)] <- crossprod(apply(as.matrix(rho.a[size,]),2,mean),apply(sigma2_m.a2[,,size],1:2,mean))
sigma_mp[2:(q+1),1] <- t(sigma_mp[1,2:(q+1)])
sigma_mp[2:(q+1),2:(q+1)] <- apply(sigma2_m.a2[,,size],1:2,mean)
}else{
comp_s <- X%*%apply(as.matrix(beta.a[size,]),2,mean) + B%*%apply(as.matrix(alpha.a[size,]),2,mean) + sum(apply(as.matrix(rho.a[size,]),2,mean)*apply(as.matrix(mu_m.a[(size),]),2,mean))
sigma_mp[1,1] <- crossprod(apply(as.matrix(rho.a[size,]),2,mean),mean(as.vector(sigma2_m.a2[,,size])))%*%apply(as.matrix(rho.a[size,]),2,mean)
sigma_mp[1,2:(q+1)] <- crossprod(apply(as.matrix(rho.a[size,]),2,mean),mean(as.vector(sigma2_m.a2[,,size])))
sigma_mp[2:(q+1),1] <- t(sigma_mp[1,2:(q+1)])
sigma_mp[2:(q+1),2:(q+1)] <- mean(as.vector(sigma2_m.a2[,,size]))
}
if(homo==1){
sigma_mp[1,1] <- sigma_mp[1,1] + mean(sigma2_y.a[size])
sigma_mp[2:(q+1),2:(q+1)] <- sigma_mp[2:(q+1),2:(q+1)] + omeg*mean(sigma2_y.a[size])
inv.sigma_mp <- solve(sigma_mp)
det_sigma_mp <- det(sigma_mp)
}
zz <- matrix(0,q+1,1)
mu_M.mean <- apply(as.matrix(mu_m.a[size,]),2,mean)
nu.mean <- apply(as.matrix(nu.a[size,]),2,mean)
for(j in 1:n){
if(homo==0){
dfg <- diag(q)
diag(dfg) <- heter$sigma2xi[j,]
sigma_mp[1,1] <- sigma_mp[1,1] + heter$sigma2y[j]
sigma_mp[2:(q+1),2:(q+1)] <- sigma_mp[2:(q+1),2:(q+1)] + dfg
inv.sigma_mp <- solve(sigma_mp)
det_sigma_mp <- det(sigma_mp)
}
zz[1] <- y[j]- comp_s[j]
zz[2:(q+1)] <- M[j,] - mu_M.mean
ss <- sqrt(crossprod(zz,inv.sigma_mp)%*%zz)
D_theta <- D_theta - 2*log(pdf(ss,nu.mean)) + log(det_sigma_mp)
}
D_theta <- D_theta
if(homo==1) res_q <- cdf((y-comp_s)/sqrt(sigma_mp[1,1]), nu.mean)
else res_q <- cdf((y-comp_s)/sqrt(heter$sigma2y), nu.mean)
res_q <- ifelse(res_q < 1e-15, 1e-15, res_q)
res_q <- ifelse(res_q > (1-1e-15), (1-1e-15), res_q)
res_q <- qnorm(res_q)
DIC <- 2*D_bar - D_theta
LMPL <- -sum(log(apply(mi,1,mean)))
KL <- log(apply(mi,1,mean))+ apply(-log(mi),1,mean)
X_2 <- apply(mi^2,1,mean)/(apply(mi,1,mean))^2- 1
list(chains=aa2, DIC=DIC, LMPL=LMPL, residuos=res_q, KL=KL, X_2=X_2)
} |
context("cbind and rbind for scan1 objects")
grav2 <- read_cross2(system.file("extdata", "grav2.zip", package="qtl2"))
grav2 <- grav2[1:20,1:3]
map <- insert_pseudomarkers(grav2$gmap, step=1)
probs <- calc_genoprob(grav2, map, error_prob=0.002)
k <- calc_kinship(probs)
kloco <- calc_kinship(probs, "loco")
test_that("cbind.scan1() works for scan1() results", {
out1 <- scan1(probs, grav2$pheno[,1,drop=FALSE])
out2 <- scan1(probs, grav2$pheno[,2,drop=FALSE])
out12 <- scan1(probs, grav2$pheno[,1:2])
expect_equal(cbind(out1, out2), out12)
})
test_that("cbind.scan1() works for scan1/LMM results", {
out1 <- scan1(probs, grav2$pheno[,1,drop=FALSE], k)
out2 <- scan1(probs, grav2$pheno[,2,drop=FALSE], k)
out12 <- scan1(probs, grav2$pheno[,1:2], k)
expect_equal(cbind(out1, out2), out12, tolerance=1e-6)
out1 <- scan1(probs, grav2$pheno[,1,drop=FALSE], kloco)
out2 <- scan1(probs, grav2$pheno[,2,drop=FALSE], kloco)
out12 <- scan1(probs, grav2$pheno[,1:2], kloco)
expect_equal(cbind(out1, out2), out12, tolerance=1e-6)
})
test_that("rbind.scan1() works for scan1() results", {
skip_on_cran()
phe <- grav2$pheno[,1,drop=FALSE]
out1 <- scan1(probs[,1], phe)
out2 <- scan1(probs[,2:3], phe)
out3 <- scan1(probs[,3], phe)
out12 <- scan1(probs[,1:3], phe)
out123 <- scan1(probs[,c(1:3,3)], phe)
out2123 <- scan1(probs[,c(2:3,1,2:3,3)], phe)
expect_equal(rbind(out1, out2), out12)
expect_equal(rbind(out1, out2, out3), out123)
expect_equal(rbind(out2, out1, out2, out3), out2123)
})
test_that("rbind.scan1() works for scan1() results with multiple columns", {
skip_on_cran()
phe <- grav2$pheno[,15:18,drop=FALSE]
out1 <- scan1(probs[,1], phe)
out2 <- scan1(probs[,2:3], phe)
out3 <- scan1(probs[,3], phe)
out12 <- scan1(probs[,1:3], phe)
out123 <- scan1(probs[,c(1:3,3)], phe)
out2123 <- scan1(probs[,c(2:3,1,2:3,3)], phe)
expect_equal(rbind(out1, out2), out12)
expect_equal(rbind(out1, out2, out3), out123)
expect_equal(rbind(out2, out1, out2, out3), out2123)
})
test_that("rbind.scan1() works for scan1() results", {
skip_on_cran()
phe <- grav2$pheno[,1,drop=FALSE]
out1 <- scan1(probs[,1], phe, k)
out2 <- scan1(probs[,2:3], phe, k)
out3 <- scan1(probs[,3], phe, k)
out12 <- scan1(probs[,1:3], phe, k)
attr(out12, "hsq") <- rbind(attr(out1, "hsq"), attr(out2, "hsq"))
out123 <- scan1(probs[,c(1:3,3)], phe, k)
attr(out123, "hsq") <- rbind(attr(out1, "hsq"), attr(out2, "hsq"), attr(out3, "hsq"))
out2123 <- scan1(probs[,c(2:3,1,2:3,3)], phe, k)
attr(out2123, "hsq") <- rbind(attr(out2, "hsq"), attr(out1, "hsq"), attr(out2, "hsq"), attr(out3, "hsq"))
expect_equal(rbind(out1, out2), out12)
expect_equal(rbind(out1, out2, out3), out123)
expect_equal(rbind(out2, out1, out2, out3), out2123)
out1 <- scan1(probs[,1], phe, kloco[1])
out2 <- scan1(probs[,2:3], phe, kloco[2:3])
out3 <- scan1(probs[,3], phe, kloco[3])
out12 <- scan1(probs[,1:3], phe, kloco[1:3])
out123 <- scan1(probs[,c(1:3,3)], phe, kloco[c(1:3,3)])
out2123 <- scan1(probs[,c(2:3,1,2:3,3)], phe, kloco[c(2:3,1,2:3,3)])
expect_equal(rbind(out1, out2), out12)
expect_equal(rbind(out1, out2, out3), out123)
expect_equal(rbind(out2, out1, out2, out3), out2123)
})
test_that("rbind.scan1() works for scan1() results with multiple columns", {
skip_on_cran()
phe <- grav2$pheno[,15:18,drop=FALSE]
out1 <- scan1(probs[,1], phe, k)
out2 <- scan1(probs[,2:3], phe, k)
out3 <- scan1(probs[,3], phe, k)
out12 <- scan1(probs[,1:3], phe, k)
attr(out12, "hsq") <- rbind(attr(out1, "hsq"), attr(out2, "hsq"))
out123 <- scan1(probs[,c(1:3,3)], phe, k)
attr(out123, "hsq") <- rbind(attr(out1, "hsq"), attr(out2, "hsq"), attr(out3, "hsq"))
out2123 <- scan1(probs[,c(2:3,1,2:3,3)], phe, k)
attr(out2123, "hsq") <- rbind(attr(out2, "hsq"), attr(out1, "hsq"), attr(out2, "hsq"), attr(out3, "hsq"))
expect_equal(rbind(out1, out2), out12)
expect_equal(rbind(out1, out2, out3), out123)
expect_equal(rbind(out2, out1, out2, out3), out2123)
out1 <- scan1(probs[,1], phe, kloco[1])
out2 <- scan1(probs[,2:3], phe, kloco[2:3])
out3 <- scan1(probs[,3], phe, kloco[3])
out12 <- scan1(probs[,1:3], phe, kloco[1:3])
out123 <- scan1(probs[,c(1:3,3)], phe, kloco[c(1:3,3)])
out2123 <- scan1(probs[,c(2:3,1,2:3,3)], phe, kloco[c(2:3,1,2:3,3)])
expect_equal(rbind(out1, out2), out12)
expect_equal(rbind(out1, out2, out3), out123)
expect_equal(rbind(out2, out1, out2, out3), out2123)
}) |
context("RTF parsing")
test_that("bookmark ends only", {
expect_equal(
.rtf_strip(
paste(
"{\\*\\bkmkend 200.05}{\\*\\bkmkend 200.06}{\\*\\bkmkend 200.07}{\\*\\bkmkend 200.08}",
"{\\*\\bkmkend 200.0}\\hich\\af1\\dbch\\af31505\\loch\\f1 200.0\\tab Reticulosarcoma"
)
),
"200.0 Reticulosarcoma"
)
})
test_that(".rtf_strip bug case with combined line", {
expect_equal(
.rtf_strip(
paste(
sep = "", "\\rtlch\\fcs1 \\af1\\afs20\\alang1025 \\ltrch\\fcs0 \\fs20\\cf1",
"\\lang1033\\langfe1033\\loch\\af1\\hich\\af1\\dbch\\af31505\\cgrid",
"\\langnp1033\\langfenp1033 {\\rtlch\\fcs1 \\af1 \\ltrch\\fcs0 ",
"\\insrsid2429293 0\\tab \\hich\\af1\\dbch\\af31505\\loch\\f1 not ",
"stated as uncontrolled\\par }\\pard\\plain \\ltrpar\\s30\\ql \\fi-360",
"\\li1440\\ri0\\widctlpar\\tx180\\tx360\\tx540\\tx720\\tx900\\tx1080\\tx1260",
"\\tx1440\\tx1620\\tx1800\\tx1980\\tx2160\\tx2340\\tx2520\\tx2700\\tx2880\\tx3060",
"\\tx3240\\tx3420\\tx3600\\tx3780\\tx3960\\tx4140\\wrapdefault",
"\\faauto\\rin0\\lin1440\\itap0"
)
),
"0 not stated as uncontrolled"
)
})
test_that(".rtf_strip does what it says on the tin", {
expect_equal(
.rtf_strip(
paste(
sep = "", "\\rtlch\\fcs1 \\af1\\afs20\\alang1025 \\ltrch\\fcs0 ",
"\\fs20\\cf1\\lang1033\\langfe1033\\loch\\af1\\hich\\af1\\dbch\\af31505",
"\\cgrid\\langnp1033\\langfenp1033 {\\rtlch\\fcs1 \\ab\\af1 \\ltrch\\fcs0 ",
"\\b\\insrsid2429293 0\\tab \\hich\\af1\\dbch\\af31505\\loch\\f1 unspecified"
)
),
"0 unspecified"
)
expect_equal(
.rtf_strip(
paste(
"The following fifth-digit subclassification is for use with categories",
"67\\hich\\af1\\dbch\\af31505\\loch\\f1 8-679 to denote the current episode of care:"
)
),
paste(
"The following fifth-digit subclassification is for use with categories 678-679",
"to denote the current episode of care:"
)
)
expect_equal(
.rtf_strip(
paste(
"The following fifth-digit subclassification is for use with",
"category 711; valid digits are in [brackets] under each code.",
"see list at beginning of chapter for definitions:"
)
),
paste(
"The following fifth-digit subclassification is for use with",
"category 711; valid digits are in [brackets] under each code.",
"see list at beginning of chapter for definitions:"
)
)
expect_equal(
.rtf_strip(
"229.8\\tab Othe\\hich\\af1\\dbch\\af31505\\loch\\f1 r specified sites"
),
"229.8 Other specified sites"
)
expect_equal(
.rtf_strip(
paste(
sep = "",
"\\lsdsemihidden0 \\lsdunhideused0 \\lsdpriority71 ",
"\\lsdlocked0 Colorful Shading Accent 6;",
"\\lsdsemihidden0 \\lsdunhideused0 \\lsdpriority72 ",
"\\lsdlocked0 Colorful List Accent 6;",
"\\lsdsemihidden0 \\lsdunhideused0 \\lsdpriority73 ",
"\\lsdlocked0 Colorful Grid Accent 6;"
)
),
""
)
expect_equal(
.rtf_strip(
paste(
sep = "",
"\\par }\\pard\\plain \\ltrpar\\s82\\ql \\fi-1080\\li2160\\ri0",
"\\widctlpar\\tx180\\tx360\\tx540\\tx720\\tx900\\tx1080\\tx1260",
"\\tx1440\\tx1620\\tx1800\\tx1980\\tx2160\\tx2340\\tx2520\\tx2700",
"\\tx2880\\tx3060\\tx3240\\tx3420\\tx3600\\tx3780\\tx3960\\tx4140",
"\\wrapdefault\\faauto\\rin0\\lin2160\\itap0 "
)
),
""
)
})
test_that("extraction from qualifier subset works", {
all2015 <- c(
"[0-6]", "[0-3]", "[0-5,9]", "[0-8]", "[0-2]", "[0-1]", "[0-5]",
"[0,1,3]", "[0-4]", "[0,3]", "[0-1,3]", "[1-2]", "[0, 1, 3]",
"[0,1,4]", "[0,1]", "[0,2,4]", "[0-2,4]", "[0-9]", "[0,4,9]",
"[0,9]", "[0-5,7-9]", "[5]", "[0-7,9]", "[0-6,9]", "[0-3,9]",
"[0-4,9]", "[0-6, 9]", "[0]", "[0-7]", "[0,2-4,8,9]",
"[0,2,4,8,9]", "[0,4,8,9]", "[6-9]", "[0,8,9]"
)
expect_equal(
.rtf_parse_qualifier_subset("[0-6]"),
as.character(c(0, 1, 2, 3, 4, 5, 6))
)
expect_equal(
.rtf_parse_qualifier_subset("[0,2-4,8,9]"),
as.character(c(0, 2, 3, 4, 8, 9))
)
expect_equal(
.rtf_parse_qualifier_subset("[0]"),
"0"
)
expect_true(
all(vapply(all2015,
FUN = function(f) length(.rtf_parse_qualifier_subset(f)) > 0,
FUN.VALUE = logical(1)
))
)
})
context("RTF tests")
test_year <- "2014"
skip_slow()
skip_no_icd_data_cache()
if (rtf_year_ok(test_year)) {
rtf_dat <- .icd9cm_sources[.icd9cm_sources$f_year == test_year, ]
f_info_short <- .unzip_to_data_raw(
url = rtf_dat$rtf_url,
file_name = rtf_dat$rtf_filename
)
rtf <- .rtf_parse_lines(
rtf_lines = readLines(f_info_short$file_path, warn = FALSE),
year = "2014"
)
nrtf <- names(rtf)
test_that("all parsed codes are valid decimals", {
expect_true(all(icd::is_valid(nrtf, short_code = FALSE)),
info = paste(
"invalid codes are :",
paste(icd::get_invalid(nrtf),
collapse = ", "
)
)
)
})
test_that("no rtf formatting left in descriptions", {
expect_false(any(grepl("[\\\\{}]", rtf)),
info = paste(
"rtf codes in descriptions:",
paste(grep("[\\\\{}]", rtf, value = TRUE))
)
)
})
test_that("all defined codes from csv are in rtf extract", {
missing_from_rtf <- setdiff(
icd::short_to_decimal(icd9cm_hierarchy[["code"]]),
nrtf
)
expect_equal(
length(missing_from_rtf), 0,
info = paste(
"missing codes are:",
paste(missing_from_rtf, collapse = ", ")
)
)
})
test_that("majors extracted from web page are the same as those from RTF", {
webmajors <- unlist(icd9_majors)
work <- .swap_names_vals(rtf)
rtfmajors <- work[is_major(work)]
expect_identical(
setdiff(rtfmajors, webmajors), character(0),
info = paste(
"these majors are from RTF but not retrieved from web: ",
paste(setdiff(rtfmajors, webmajors), collapse = ", ")
)
)
expect_identical(
setdiff(webmajors, rtfmajors), character(0),
info = paste(
"these majors are on web but not retrieved from RTF: ",
paste(setdiff(webmajors, rtfmajors), collapse = ", ")
)
)
})
test_that("all leaf codes from TXT are in flat file extract", {
skip_flat_icd9_avail(year = "2014")
skip_if_not_installed("icd", "4.0")
v32 <- .parse_icd9cm_leaf_year(
year = "2014",
)
leaves <- icd::short_to_decimal(v32$code)
expect_true(all(leaves %in% nrtf))
rtf_leaves <- sort(
.swap_names_vals(
rtf[nrtf %in% icd::short_to_decimal(v32$code)]
)
)
})
test_that("RTF extract has no duplicates", {
expect_false(
anyDuplicated(nrtf) > 0,
info = paste(
"first few duplicates: ",
paste(nrtf[duplicated(nrtf)][1:10], collapse = ", ")
)
)
})
test_that("mid-level descriptions are in RTF extract", {
skip_on_no_rtf(test_year)
expect_identical(rtf[["611"]], "Other disorders of breast")
expect_identical(rtf[["611.7"]], "Signs and symptoms in breast")
expect_identical(rtf[["611.8"]], "Other specified disorders of breast")
})
test_that("at this early stage, hotfix failures are present", {
expect_identical(rtf[["038.1"]], "Staphylococcal septicemia")
expect_identical(rtf[["737"]], "Curvature of spine")
expect_identical(rtf[["345.1"]], "Generalized convulsive epilepsy")
expect_identical(rtf[["414.0"]], "Coronary atherosclerosis")
expect_identical(rtf[["414.1"]], "Aneurysm and dissection of heart")
expect_identical(rtf[["291"]], "Alcohol-induced mental disorders")
expect_identical(rtf[["361"]], "Retinal detachments and defects")
expect_identical(
rtf[["414"]],
"Other forms of chronic ischemic heart disease"
)
expect_identical(
rtf[["780.6"]],
"Fever and other physiologic disturbances of temperature regulation"
)
expect_identical(
rtf[["294"]],
"Persistent mental disorders due to conditions classified elsewhere"
)
})
test_that("correct assignment of undefined last digit codes", {
expect_false("640.02" %in% nrtf)
})
test_that("some rtf wierdness single codes should be missing", {
bad_ones <- c(
paste0("010.", 2:7),
paste0("854.", 2:7),
NULL
)
expect_true(all(bad_ones %nin% nrtf))
expect_true(all(icd::children(bad_ones) %nin% nrtf))
expect_true("012.4" %nin% nrtf)
expect_true("012.40" %nin% nrtf)
expect_true("012.46" %nin% nrtf)
})
}
test_that("get chap and subchap for numeric, V, E", {
df <- data.frame(code = c("V201", "E9990", "0101"))
res <- .lookup_icd9_hier(df, short_code = TRUE)
expect_true(res[1, "chapter"] ==
"Infectious And Parasitic Diseases")
}) |
NULL
utils::globalVariables(c(".")) |
"allDomain" |
read_dssbatch <- function(file_name='DSSBatch.V47'){
batch_file <- read_dssat(file_name,left_justified = 'FILEX') %>%
as_DSSAT_tbl()
return(batch_file)
} |
test.combinations <-
function(SpA, SpB){
max.alleles<-length(SpA)
SpA<-SpA[!is.na(SpA)]
SpB<-SpB[!is.na(SpB)]
total.alleles<-length(SpA)
max.delta<-0
obs.delta<-delta(SpA, SpB)
search.complete<-FALSE
spa.alleles<-which(SpA > 0)
spb.alleles<-which(SpB > 0)
if(length(spa.alleles) <= length(spb.alleles)){
nalleles <- length(spa.alleles)
working.alleles<-spa.alleles
}
else{
nalleles<- length(spb.alleles)
working.alleles<-spb.alleles
}
if(nalleles == 1){
focalset<-working.alleles
combo1<-focalset
combo2<-(1:total.alleles)[-focalset]
group.a<-c(sum(SpA[focalset]), sum(SpA[-focalset]))
group.b<-c(sum(SpB[focalset]), sum(SpB[-focalset]))
max.delta<-delta(group.a, group.b)
}
else if (abs(obs.delta - 1) < 0.000001 ){
focalset<-working.alleles
combo1<-focalset
combo2<-(1:total.alleles)[-focalset]
max.delta<-obs.delta
}
else {
my.levels<-nalleles:1
for(i in 1:length(my.levels)){
if(search.complete==TRUE){
break
}
working<-utils::combn(nalleles, my.levels[i])
for (x in 1:ncol(working) ){
focalset<-working.alleles[working[,x]]
group.a<-c(sum(SpA[focalset]), sum(SpA[-focalset]))
group.b<-c(sum(SpB[focalset]), sum(SpB[-focalset]))
new.delta<-delta(group.a, group.b)
if ( abs(new.delta - obs.delta) < 0.00001 ||
abs(max.delta -obs.delta) < 0.00001 ){
combo1<-focalset
combo2<-(1:total.alleles)[-focalset]
search.complete<-TRUE
max.delta<- new.delta
break
}
else if( new.delta > max.delta ){
max.delta<- new.delta
combo1<-focalset
combo2<-(1:total.alleles)[-focalset]
}
}
}
}
class.freq<-matrix(data=c(sum(SpA[combo1]), sum(SpA[combo2]),
sum(SpB[combo1]), sum(SpB[combo2])),
dimnames=list(c("spa", "spb"), c("c1", "c2")),
byrow=TRUE, ncol=2)
padding1<-rep(NA,max.alleles-length(combo1))
padding2<-rep(NA,max.alleles-length(combo2))
return(c(obs.delta, max.delta, combo1, padding1, combo2,
padding2, as.vector(class.freq)))
} |
read_gff <- function(file) {
suppressWarnings(
gff.input <-
readr::read_delim(
file = file,
delim = "\t",
col_names = FALSE,
comment = "
)
)
if (!file.exists(file))
stop("The file path you specified does not seem to exist: '", file,"'.", call. = FALSE)
if (ncol(gff.input) > 9)
stop("The gff file format can not store more than 9 columns!", call. = FALSE)
gffNames <- c("seqid",
"source",
"type",
"start",
"end",
"score",
"strand",
"phase",
"attribute")
names(gff.input)[seq_len(ncol(gff.input))] <-
gffNames[seq_len(ncol(gff.input))]
return(gff.input)
} |
BIFIE_lavaan_summary <- function(object)
{
requireNamespace("lavaan")
lavaan_summary <- methods::getMethod("summary","lavaan")
lavaan_summary(object)
} |
download_data <- function(dest) {
write.csv(mtcars, dest)
}
process_data <- function(filename) {
x <- read.csv(filename)
x$kmpl <- x$mpg * 1.609344 / 3.78541
x
}
myplot <- function(dat) {
plot(kmpl ~ disp, dat)
} |
.BP_threshold <- function(bone, analysis=1) {
if (is.null(RM_get(x=bone, RMname=analysis, valuename = "bg")) |
is.null(RM_get(x=bone, RMname=analysis, valuename = "fg"))) {
stop("You must first setup background and foreground colors")
}
bg <- RM_get(x=bone, RMname=analysis, valuename = "bg")
fg <- RM_get(x=bone, RMname=analysis, valuename = "fg")
Distance_bg <- sqrt((bone[, , 1, 1]-col2rgb(bg)["red", 1]/255)^2+
(bone[, , 1, 2]-col2rgb(bg)["green", 1]/255)^2+
(bone[, , 1, 3]-col2rgb(bg)["blue", 1]/255)^2)
Distance_fg <- sqrt((bone[, , 1, 1]-col2rgb(fg)["red", 1]/255)^2+
(bone[, , 1, 2]-col2rgb(fg)["green", 1]/255)^2+
(bone[, , 1, 3]-col2rgb(fg)["blue", 1]/255)^2)
return(Distance_bg>Distance_fg)
} |
"print.Krig" <- function(x, digits = 4, ...) {
c1 <- "Number of Observations:"
c2 <- length(x$residuals)
if (!is.null(x$args.null$m)) {
c1 <- c(c1, "Degree of polynomial null space ( base model):")
c2 <- c(c2, x$m - 1)
}
c1 <- c(c1, "Number of parameters in the null space")
c2 <- c(c2, x$nt)
c1 <- c(c1, "Parameters for fixed spatial drift")
c2 <- c(c2, sum(x$ind.drift))
c1 <- c(c1, "Model degrees of freedom:")
c2 <- c(c2, format(round(x$eff.df, 1)))
c1 <- c(c1, "Residual degrees of freedom:")
c2 <- c(c2, format(round(length(x$residuals) - x$eff.df,
1)))
c1 <- c(c1, "GCV estimate for tau:")
c2 <- c(c2, format(signif(x$tauHat.GCV, digits)))
c1 <- c(c1, "MLE for tau:")
c2 <- c(c2, format(signif(x$tauHat.MLE, digits)))
c1 <- c(c1, "MLE for sigma:")
c2 <- c(c2, format(signif(x$sigma.MLE, digits)))
c1 <- c(c1, "lambda")
c2 <- c(c2, format(signif(x$lambda, 2)))
c1 <- c(c1, "User supplied sigma")
c2 <- c(c2, format(signif(x$sigma, digits)))
c1 <- c(c1, "User supplied tau^2")
c2 <- c(c2, format(signif(x$tau2, digits)))
sum <- cbind(c1, c2)
dimnames(sum) <- list(rep("", dim(sum)[1]), rep("", dim(sum)[2]))
cat("Call:\n")
dput(x$call)
print(sum, quote = FALSE)
cat("Summary of estimates: \n")
print( x$lambda.est)
invisible(x)
} |
getKmers <- function(.data, .k, .col = c("aa", "nt"), .coding = TRUE) {
seq_col <- switch_type(.col[1])
if (.coding) {
.data <- coding(.data)
}
if (has_class(.data, "list")) {
res <- data.table(split_to_kmers(collect(select(.data[[1]], seq_col), n = Inf)[[1]], .k = .k))
colnames(res)[2] <- names(.data)[1]
for (i in 2:length(.data)) {
tmp <- data.table(split_to_kmers(collect(select(.data[[i]], seq_col), n = Inf)[[1]], .k = .k))
res <- merge(res, tmp, by = "Kmer", all = TRUE, suffixes = c("", ""))
colnames(res)[ncol(res)] <- names(.data)[i]
}
} else {
res <- split_to_kmers(collect(select(.data, seq_col), n = Inf)[[1]], .k = .k)
}
add_class(as_tibble(as.data.frame(res)), "immunr_kmer_table")
}
split_to_kmers <- function(.data, .k) {
max_len <- max(nchar(.data))
tab <- table(unlist(lapply(1:(max_len - .k + 1), function(i) substr(.data, i, i + .k - 1))))
tab <- tab[nchar(names(tab)) == .k]
tab <- as_tibble(as.data.frame(tab, stringsAsFactors = FALSE))
names(tab) <- c("Kmer", "Count")
add_class(tab, "immunr_kmers")
}
kmer_profile <- function(.data, .method = c("freq", "prob", "wei", "self"), .remove.stop = TRUE) {
.method <- .method[1]
if (!(.method %in% c("freq", "prob", "wei", "self"))) {
stop('Error: wrong name for the .method argument. Please provide one of the following: "freq", "prob", "wei" or "self".')
}
if (has_class(.data, "immunr_kmer_table")) {
if (ncol(.data) > 2) {
stop("Error: currently we are not supporting sequence profiles from more than one sample. Will support it soon!")
}
seq_vec <- .data$Kmer
cnt_vec <- .data$Count
} else if (length(table(nchar(.data))) > 1) {
stop("Not all kmers in the input data have the same length.")
} else {
seq_vec <- .data
cnt_vec <- rep.int(1, length(.data))
}
k <- nchar(seq_vec[1])
aas <- sort(unique(AA_TABLE))
if (.remove.stop) {
aas <- aas[3:length(aas)]
cnt_vec <- cnt_vec[grep("[*~]", seq_vec, invert = TRUE)]
seq_vec <- seq_vec[grep("[*~]", seq_vec, invert = TRUE)]
}
res <- matrix(0, length(aas), k)
row.names(res) <- aas
bad_symbols <- c()
for (i in 1:k) {
tab <- tapply(cnt_vec, substr(seq_vec, i, i), sum, simplify = FALSE)
for (aa in names(tab)) {
if (aa %in% row.names(res)) {
res[aa, i] <- res[aa, i] + tab[[aa]]
} else {
bad_symbols <- c(bad_symbols, aa)
}
}
if (.method == "freq") {
} else if (.method == "prob") {
res[, i] <- res[, i] / sum(res[, i])
} else if (.method == "wei") {
res[, i] <- res[, i] / nrow(res)
res[, i] <- log2(res[, i])
} else {
res[, i] <- res[, i] / sum(res[, i])
res[, i] <- -res[, i] * log2(res[, i])
}
}
if (length(bad_symbols)) {
warning(
"Warning: removed ", length(bad_symbols), " non-amino acid symbol(s): ", unique(bad_symbols),
"\nPlease make sure your data doesn't have them in the future."
)
}
if (.method == "freq") {
add_class(res, "immunr_kmer_profile_pfm")
} else if (.method == "prob") {
add_class(res, "immunr_kmer_profile_ppm")
} else if (.method == "wei") {
add_class(res, "immunr_kmer_profile_pwm")
} else {
add_class(res, "immunr_kmer_profile_self")
}
} |
plot.gGeneric <- function(x, CL = 0.90, ...){
ghat <- x$ghat
hwid <- 0.2
cells <- names(ghat)
ncell <- length(cells)
npred <- min(which(grepl("CellNames", colnames(x$predictors)))) - 1
preds <- colnames(x$predictors)[1:npred]
if (ncell == 1){
g <- sort(ghat[[1]])
qtls <- quantile(g, probs = c(0.005, (1 - CL)/2, 0.25, 0.5, 0.75, 1 - (1 - CL)/2, 0.995))
names(qtls) <- c("bot", "lwr", "Q1", "med", "Q3", "upr", "top")
gmin <- min(g)
gmax <- max(g)
nstep <- 11
steps <- seq(gmin, gmax, length.out = nstep)
stepSize <- steps[2] - steps[1]
nrect <- nstep - 1
rectL <- rep(NA, nrect)
rectR <- rep(NA, nrect)
rectY <- rep(NA, nrect)
for (recti in 1:nrect){
rectL[recti] <- steps[recti]
rectR[recti] <- steps[recti + 1]
rectY[recti] <- sum(g >= steps[recti] & g < steps[recti + 1])
}
rectY <- rectY / sum(rectY)
par(mar = c(4, 5, 2, 2), fig = c(0, 1, 0, 1))
ms <- MASS::fitdistr(logit(g), "normal")$estimate
xx <- seq(gmin, gmax, length.out = length(g))
yy <- dnorm(logit(xx), mean = ms[1], sd = ms[2])/(xx - xx^2) *
(xx[2] - xx[1]) * length(xx)/nstep
plot(rectL, rectY, type = "n", xlab = "", ylab = "", las = 1, cex.axis = 1.1,
xlim = c(rectL[1], rectR[nrect]), ylim = c(0, max(yy, max(rectY))))
imin <- min(which(xx >= qtls["lwr"]))
imax <- min(which(xx >= qtls["upr"]))
polygon(x = c(xx[imin], xx[imax], xx[imax:imin]), y = c(0, 0, yy[imax:imin]),
col = colors()[520], border = NA)
lines(xx, yy)
for (ri in 1:nrect) rect(rectL[ri], 0, rectR[ri], rectY[ri])
adj <- ifelse(qtls["med"] <= mean(par("usr")[1:2]), 0.97, 0.03)
cex = 0.9
mtext(side = 3, line = -1, adj = adj, cex = cex,
paste0("Median: ", sprintf("%.2f", qtls["med"])))
mtext(side = 3, line = -2, adj = adj, cex = cex,
paste0(CL * 100, "% CI: [", sprintf("%.1f", qtls["lwr"]), ", ",
sprintf("%.1f", qtls["upr"]), "]"))
mtext(side = 3, line = -3, adj = adj, cex = cex,
paste0("IQR = [",
sprintf("%.3f", qtls["Q1"]), ", ",
sprintf("%.3f", qtls["Q3"]), "]"
)
)
} else {
par(mar = c(8, 4, 3, 1), oma = c(2, 0, 0, 0))
plot (0, xlab = "", ylab = "", xlim = c(0.5, ncell + 0.5), ylim = c(0, 1.03),
xaxs = "i", type = "n", axes = FALSE)
title(main = "Estimated Detection Probability (g)", line = 2.2)
if (npred == 2){
mtext(side = 3, text = preds[2], cex = 1.2)
mtext(side = 1, line = 4, text = preds[1], cex = 1.2)
ngroup <- length(unique(x$predictors[ , preds[2]]))
nper <- length(unique(x$predictors[ , preds[1]]))
for (gi in 1:ngroup){
if (!gi %% 2){
rect((gi - 1) * nper + 0.5, par("usr")[3],
(gi - 1) * nper + nper + 0.5, par("usr")[4],
col = colors()[25], border = NA
)
}
mtext(side = 3, line = -1, at = (gi - 1) * nper + nper/2 + 0.5,
text = unique(x$predictors[ , preds[2]])[gi])
}
} else if (npred == 1){
mtext(side = 1, line = 4, text = preds[1], cex = 1.2)
} else if (npred > 2){
mtext(side = 3, text = paste("Labels = ", paste(preds, collapse = ".")),
adj = 0)
}
axis(2, at = seq(0, 1, 0.2), las = 1, cex.axis = 1)
axis(2, at = seq(0.1, 0.9, by = 0.2), labels = FALSE)
axis(2, at = seq(0.05, 0.95, by = 0.1), labels = FALSE, tck = -0.012)
mtext(side = 2, line = 2.75, "Detection Probability", cex = 1.25)
if (npred %in% 1:2){
text(x = 1:ncell, y = -0.08, labels = x$predictors[ , 1],
srt = 25, adj = 0.9, xpd = TRUE, cex = 1)
axis(1, at = 1:ncell, labels = FALSE)
} else {
axis(1, at = 1:ncell, labels = FALSE)
if (ncell < 10) {
cex = 1
srt = 25
y = -0.08
adj = 0.8
shift = 0.1
} else if (ncell < 16){
cex = 0.9
srt = 45
adj = 0.8
y = -0.1
shift = 0.3
} else {
cex = 0.8
srt = 60
adj = 0.8
y = -0.12
shift = 0.6
}
text(x = 1:ncell - shift, y = y, labels = x$predictors$CellNames,
srt = srt, adj = adj, xpd = TRUE, cex = cex)
}
mtext(side = 1, outer = T, cex = 0.9, line = 1, adj = 0.05,
text = paste0("Box plots show median, IQR, and 99% & ", 100 * CL, "% CIs"))
box()
probs <- c(0.005, (1 - CL)/2, 0.25, 0.5, 0.75, 1 - (1 - CL)/2, 0.995)
for (xi in 1:ncell){
y <- quantile(ghat[[xi]], probs)
med <- hwid * c(-1, 1)
tb <- med/2
rect(xi - hwid, y[3], xi + hwid, y[5], border = 1, col = colors()[520])
lines(xi + med, rep(y[4], 2), lwd = 2)
lines(xi + tb, rep(y[2], 2))
lines(xi + tb, rep(y[6], 2))
lines(rep(xi, 3), y[1:3])
lines(rep(xi, 3), y[5:7])
}
}
par(.par_default)
}
plot.gGenericSize <- function(x, CL = 0.90, ...){
nsizeclass <- length(x)
if (nsizeclass == 1){
return(plot(x[[1]], CL = CL, ...))
}
sizeclasses <- names(x)
increm <- 1 / nsizeclass
y1 <- seq(0, 1, by = increm)
y1 <- y1[-length(y1)]
y2 <- seq(0, 1, by = increm)
y2 <- y2[-1]
names(y1) <- sizeclasses
names(y2) <- sizeclasses
par(fig = c(0, 1, 0, 1))
par(mar = c(3, 3, 1, 1))
plot(1, 1, type = "n", ylab= "", xlab = "", xaxt = "n", yaxt = "n",
bty = "n"
)
mtext(side = 2, line = 2, "Detection Probability", cex = 1)
for (sci in sizeclasses){
par(fig = c(0, 0.9, y1[sci], y2[sci]), new = TRUE)
ghats <- x[[sci]]$ghat
cells <- names(ghats)
ncell <- length(cells)
predsByCell <- strsplit(cells, "\\.")
npred <- length(predsByCell[[1]])
colNames <- colnames(x[[sci]]$predictors)
predNames <- colNames[-grep("CellNames", colNames)]
labelText <- paste("Labels = ", paste(predNames, collapse = "."))
par(mar = c(3, 4, 3, 1))
plot (1, 1, type = "n", xlab = "", ylab = "", xaxt = "n", yaxt = "n",
bty = "o", xlim = c(0.5, ncell + 0.5), ylim = c(0, 1)
)
axis(2, at = seq(0, 1, 0.25), las = 1, cex.axis = 0.5)
axis(1, at = 1:ncell, labels = FALSE, tck = -0.05)
ang <- 0
offx <- NULL
if (ncell > 3){
ang <- 45
offx <- 1
}
text(1:ncell, -0.2, srt = ang, adj = offx, labels = cells, xpd = TRUE,
cex = 0.5
)
if (predNames[1] == "group" & length(predNames) == 1 & cells[1] == "all"){
labelText <- NULL
}
text(0.5, 1.15, labelText, xpd = TRUE, cex = 0.5, adj = 0)
if (!is.null(sci)){
text_sc <- paste("Carcass class: ", sci, sep = "")
text(x = 0.5, y = 1.25, xpd = TRUE, text_sc, adj = 0, cex = 0.5)
}
probs <- c(0, (1 - CL) / 2, 0.25, 0.5, 0.75, 1 - (1 - CL) / 2, 1)
for (celli in 1:ncell){
xx <- celli
yy <- quantile(ghats[[celli]], probs)
med <- c(-0.1, 0.1)
tb <- c(-0.07, 0.07)
rect(xx - 0.1, yy[3], xx + 0.1, yy[5], lwd = 2, border = 1)
points(xx + med, rep(yy[4], 2), type = 'l', lwd = 2, col = 1)
points(xx + tb, rep(yy[2], 2), type = 'l', lwd = 2, col = 1)
points(xx + tb, rep(yy[6], 2), type = 'l', lwd = 2, col = 1)
points(rep(xx, 3), yy[1:3], type = 'l', lwd = 2, col = 1)
points(rep(xx, 3), yy[5:7], type = 'l', lwd = 2, col = 1)
}
}
par(mar = c(2,0,2,0))
par(fig = c(0.9, 1, 0, 1), new = TRUE)
plot(1,1, type = "n", bty = "n", xaxt = "n", yaxt = "n", xlab = "",
ylab = "", ylim = c(0, 1), xlim = c(0, 1)
)
x_s <- 0.1
CL_split <- (1 - CL) / 2
probs_y <- c(0, CL_split, 0.25, 0.5, 0.75, 1 - CL_split, 1)
set.seed(12)
y_s <- quantile(rnorm(1000, 0.5, 0.1), probs = probs_y)
med <- c(-0.1, 0.1)
tb <- c(-0.07, 0.07)
rect(x_s - 0.1, y_s[3], x_s + 0.1, y_s[5], lwd = 2, border = 1)
points(x_s + med, rep(y_s[4], 2), type = 'l', lwd = 2, col = 1)
points(x_s + tb, rep(y_s[2], 2), type = 'l', lwd = 2, col = 1)
points(x_s + tb, rep(y_s[6], 2), type = 'l', lwd = 2, col = 1)
points(rep(x_s, 3), y_s[1:3], type = 'l', lwd = 2, col = 1)
points(rep(x_s, 3), y_s[5:7], type = 'l', lwd = 2, col = 1)
num_CL <- c(CL_split, 1 - CL_split) * 100
text_CL <- paste(num_CL, "%", sep = "")
text_ex <- c("min", text_CL[1], "25%", "50%", "75%", text_CL[2], "max")
text(x_s + 0.2, y_s, text_ex, cex = 0.65, adj = 0)
} |
cv.spcrglm <- function(x, y, k, family=c("binomial","poisson","multinomial"), w=0.1, xi=0.01, nfolds=5, adaptive=FALSE, q=1, center=TRUE, scale=FALSE, lambda.B.length=10, lambda.gamma.length=10, lambda.B=NULL, lambda.gamma=NULL){
if( !is.matrix(x) ) stop("x must be a matrix.")
if( mode(x)!="numeric" ) stop("x must be numeric.")
if ( !is.vector(y) ) stop("y must be a vector.")
if( mode(y)!="numeric" ) stop("y must be numeric.")
if( k < 1 ) stop("k is an integer and larger than one.")
n <- nrow(x)
ini.lambda.beta <- ini.lambda.gamma <- ini.lambda( x=x, y=y, k=k, w=w, xi=xi )
lambda.beta.candidate <- rev( seq( n*0.005, ini.lambda.beta, length=lambda.B.length ) )
lambda.gamma.candidate <- rev( seq(n* 0.005, ini.lambda.gamma, length=lambda.gamma.length ) )
if( is.null(lambda.B) != TRUE ) lambda.beta.candidate <- sort(lambda.B, decreasing=TRUE)
if( is.null(lambda.gamma) != TRUE ) lambda.gamma.candidate <- sort(lambda.gamma, decreasing=TRUE)
if( family=="binomial" ){
if( adaptive==FALSE ){
spcr.object <- CV.SPCRLoG( x, y, k, xi, w, nfolds=nfolds, lambda.beta.candidate=lambda.beta.candidate, lambda.gamma.candidate=lambda.gamma.candidate, center=center, scale=scale, adaptive=adaptive, q=q )
}
if( adaptive==TRUE ){
spcr.object <- CV.SPCRLoG( x, y, k, xi, w, nfolds=nfolds, lambda.beta.candidate=lambda.beta.candidate, lambda.gamma.candidate=lambda.gamma.candidate, center=center, scale=scale, adaptive=adaptive, q=q )
}
}
if( family=="poisson" ){
if( adaptive==FALSE ){
spcr.object <- CV.SPCRPoi( x, y, k, xi, w, nfolds=nfolds, lambda.beta.candidate=lambda.beta.candidate, lambda.gamma.candidate=lambda.gamma.candidate, center=center, scale=scale, adaptive=adaptive, q=q )
}
if( adaptive==TRUE ){
spcr.object <- CV.SPCRPoi( x, y, k, xi, w, nfolds=nfolds, lambda.beta.candidate=lambda.beta.candidate, lambda.gamma.candidate=lambda.gamma.candidate, center=center, scale=scale, adaptive=adaptive, q=q )
}
}
if( family=="multinomial" ){
Y = y
unique.Y = unique(Y)
y = matrix(0, nrow(x), length(unique.Y))
for(i in 1:nrow(x)) for(j in 1:length(unique.Y)) if( Y[i] == unique.Y[j] ) y[i,j] <- 1
if( adaptive==FALSE ){
spcr.object <- CV.SPCRMultiLoG( x, y, k, xi, w, nfolds=nfolds, lambda.beta.candidate=lambda.beta.candidate, lambda.gamma.candidate=lambda.gamma.candidate, center=center, scale=scale, adaptive=adaptive, q=q )
}
if( adaptive==TRUE ){
spcr.object <- CV.SPCRMultiLoG( x, y, k, xi, w, nfolds=nfolds, lambda.beta.candidate=lambda.beta.candidate, lambda.gamma.candidate=lambda.gamma.candidate, center=center, scale=scale, adaptive=adaptive, q=q )
}
}
ans <- list( lambda.gamma.seq = spcr.object$lambda.gamma.candidate, lambda.B.seq = spcr.object$lambda.beta.candidate, CV.mat = - spcr.object$CV.mat, lambda.gamma.cv = spcr.object$lambda.gamma.cv, lambda.B.cv = spcr.object$lambda.beta.cv, cvm = - spcr.object$cvm, call=match.call() )
class(ans) <- "cv.spcrglm"
return( ans )
} |
have_packages <-
require(ggformula) &&
require(dplyr) &&
require(ggplot2) &&
require(mosaicData) &&
require(maps) &&
require(palmerpenguins) &&
requireNamespace("mosaic")
have_extra_packages <-
require(maps) && require(sf) && require(purrr)
knitr::opts_chunk$set(
fig.show = "asis",
fig.align = "center",
fig.width = 6, fig.height = 4,
out.width = "60%",
eval = have_packages
)
theme_set(theme_light())
library(ggformula)
gf_point(mpg ~ hp, data = mtcars)
mtcars %>% gf_point(mpg ~ hp)
gf_point(mpg ~ hp, color = ~ cyl, size = ~ carb, alpha = 0.50, data = mtcars)
library(dplyr)
gf_point(mpg ~ hp, color = ~ factor(cyl), size = ~ carb, alpha = 0.75, data = mtcars)
mtcars %>%
mutate(cylinders = factor(cyl)) %>%
gf_point(mpg ~ hp, color = ~ cylinders, size = ~ carb, alpha = 0.75)
data(penguins, package = "palmerpenguins")
gf_density( ~ bill_length_mm, data = penguins)
gf_density( ~ bill_length_mm, fill = ~ species, alpha = 0.5, data = penguins)
gf_dens( ~ bill_length_mm, color = ~ species, alpha = 0.7, data = penguins)
gf_dens2( ~ bill_length_mm, fill = ~ species, data = penguins,
color = "gray50", alpha = 0.4)
penguins %>% gf_dens( ~ bill_length_mm, color = ~ species, alpha = 0.7, adjust = 0.25)
penguins %>% gf_dens( ~ bill_length_mm, color = ~ species, alpha = 0.7, adjust = 4) |
effectsize.htest <- function(model, type = NULL, verbose = TRUE, ...) {
if (grepl("t-test", model$method)) {
.effectsize_t.test(model, type = type, verbose = verbose, ...)
} else if (grepl("Pearson's Chi-squared", model$method) ||
grepl("Chi-squared test for given probabilities", model$method)) {
.effectsize_chisq.test(model, type = type, verbose = verbose, ...)
} else if (grepl("One-way", model$method)) {
.effectsize_oneway.test(model, type = type, verbose = verbose, ...)
} else if (grepl("McNemar", model$method)) {
.effectsize_mcnemar.test(model, type = type, verbose = verbose, ...)
} else if (grepl("Wilcoxon", model$method)) {
.effectsize_wilcox.test(model, type = type, verbose = verbose, ...)
} else if (grepl("Kruskal-Wallis", model$method)) {
.effectsize_kruskal.test(model, type = type, verbose = verbose, ...)
} else if (grepl("Friedman", model$method)) {
.effectsize_friedman.test(model, type = type, verbose = verbose, ...)
} else {
if (verbose) warning("This 'htest' method is not (yet?) supported.\n",
"Returning 'parameters::model_parameters(model)'.",
call. = FALSE)
parameters::model_parameters(model, verbose = verbose, ...)
}
}
.effectsize_t.test <- function(model, type = NULL, verbose = TRUE, ...) {
data <- insight::get_data(model)
approx <- is.null(data)
dots <- list(...)
if (is.null(type)) type <- "d"
dots$alternative <- model$alternative
dots$ci <- attr(model$conf.int,"conf.level")
dots$mu <- model$null.value
if (type == "cles") {
.fail_if_approx(approx, "cles")
}
if (approx) {
if (verbose) {
warning("Unable to retrieve data from htest object. Using t_to_d() approximation.")
}
f <- t_to_d
args <- list(
t = unname(model$statistic),
df_error = unname(model$parameter),
paired = !grepl("Two", model$method)
)
} else {
if (grepl(" by ", model$data.name, fixed = TRUE)) {
data[[2]] <- factor(data[[2]])
}
f <- switch(tolower(type),
d = ,
cohens_d = cohens_d,
g = ,
hedges_g = hedges_g,
cles = cles
)
args <- list(
x = data[[1]],
y = if (ncol(data) == 2) data[[2]],
paired = !grepl("Two", model$method),
pooled_sd = !grepl("Welch", model$method),
verbose = verbose
)
if (type == "cles") {
if (args$paired || !args$pooled_sd) {
stop("Common language effect size only applicable to 2-sample Cohen's d with pooled SD.")
}
args$pooled_sd <- args$paired <- NULL
}
}
out <- do.call(f, c(args, dots))
attr(out, "approximate") <- approx
out
}
.effectsize_chisq.test <- function(model, type = NULL, verbose = TRUE, ...) {
data <- insight::get_data(model)
approx <- is.null(data)
dots <- list(...)
if (is.null(type)) type <- "cramers_v"
if (grepl("(c|v|w|phi)$", tolower(type))) {
f <- switch(tolower(type),
v = ,
cramers_v = chisq_to_cramers_v,
w = ,
cohens_w = ,
phi = chisq_to_phi,
c = ,
pearsons_c = chisq_to_pearsons_c
)
Obs <- model$observed
Exp <- model$expected
if (!is.null(dim(Exp))) {
if (any(c(colSums(Obs), rowSums(Obs)) == 0L)) {
stop("Cannot have empty rows/columns in the contingency tables.", call. = FALSE)
}
nr <- nrow(Obs)
nc <- ncol(Obs)
} else {
nr <- length(Obs)
nc <- 1
}
out <- f(
chisq = .chisq(Obs, Exp),
n = sum(Obs),
nrow = nr,
ncol = nc,
...
)
attr(out, "approximate") <- FALSE
return(out)
} else {
f <- switch(tolower(type),
or = ,
oddsratio = oddsratio,
rr = ,
riskratio = riskratio,
h = ,
cohens_h = cohens_h
)
}
out <- f(x = model$observed, ...)
out
}
.effectsize_oneway.test <- function(model, type = NULL, verbose = TRUE, ...) {
data <- insight::get_data(model)
approx <- is.null(data)
dots <- list(...)
if ((approx <- grepl("not assuming", model$method, fixed = TRUE)) && verbose) {
warning("`var.equal = FALSE` - effect size is an approximation.", call. = FALSE)
}
if (is.null(type)) type <- "eta"
f <- switch(tolower(type),
eta = ,
eta2 = ,
eta_squared = F_to_eta2,
epsilon = ,
epsilon2 = ,
epsilon_squared = F_to_epsilon2,
omega = ,
omega2 = ,
omega_squared = F_to_omega2,
f = ,
cohens_f = F_to_f,
f2 = ,
f_squared = ,
cohens_f2 = F_to_f2
)
out <- f(
f = model$statistic,
df = model$parameter[1],
df_error = model$parameter[2],
...
)
colnames(out)[1] <- sub("_partial", "", colnames(out)[1])
attr(out, "approximate") <- approx
out
}
.effectsize_mcnemar.test <- function(model, type = NULL, verbose = TRUE, ...) {
data <- insight::get_data(model)
approx <- is.null(data)
dots <- list(...)
.fail_if_approx(approx, "cohens_g")
if (inherits(data, "table")) {
out <- cohens_g(data, ...)
} else {
out <- cohens_g(data[[1]], data[[2]], ...)
}
out
}
.effectsize_wilcox.test <- function(model, type = NULL, verbose = TRUE, ...) {
data <- insight::get_data(model)
approx <- is.null(data)
dots <- list(...)
if (is.null(type)) type <- "rb"
dots$alternative <- model$alternative
dots$ci <- attr(model$conf.int,"conf.level")
dots$mu <- model$null.value
.fail_if_approx(approx, ifelse(type=="cles", "cles", "rank_biserial"))
f <- switch(tolower(type),
r = ,
rb = ,
rbs = ,
r_rank_biserial = ,
rank_biserial = rank_biserial,
cles = cles
)
args <- list(
x = data[[1]],
y = if (ncol(data) == 2) data[[2]],
paired = grepl("signed rank", model$method, fixed = TRUE)
)
if (type == "cles") {
if (args$paired) {
stop("Common language effect size only applicable to 2-sample rank-biserial correlation.")
}
args$paired <- NULL
args$parametric <- FALSE
}
out <- do.call(f, c(args, dots))
out
}
.effectsize_kruskal.test <- function(model, type = NULL, verbose = TRUE, ...) {
data <- insight::get_data(model)
approx <- is.null(data)
dots <- list(...)
.fail_if_approx(approx, "rank_epsilon_squared")
if (inherits(data, "list")) {
out <- rank_epsilon_squared(data, ...)
} else {
out <- rank_epsilon_squared(data[[1]], data[[2]], ...)
}
out
}
.effectsize_friedman.test <- function(model, type = NULL, verbose = TRUE, ...) {
data <- insight::get_data(model)
approx <- is.null(data)
dots <- list(...)
.fail_if_approx(approx, "kendalls_w")
if (inherits(data, "table")) {
data <- as.data.frame(data)[c("Freq", "Var2", "Var1")]
}
out <- kendalls_w(data[[1]], data[[2]], data[[3]], ...)
out
}
.chisq <- function(Obs, Exp) {
sum(((Obs - Exp)^2) / Exp)
}
.fail_if_approx <- function(approx, esf_name) {
if (approx) {
stop("Unable to retrieve data from htest object.",
"\nTry using '", esf_name, "()' directly.",
call. = FALSE
)
}
invisible(NULL)
} |
delete_files_grm <- function(file) {
delete_files_generic(file, exts_grm)
} |
test_that("Test fairness_check_regression", {
data <- data.frame(
x = c(rnorm(500, 500, 100), rnorm(500, 500, 200)),
pop = c(rep("A", 500), rep("B", 500))
)
data$y <- rnorm(length(data$x), 1.5 * data$x, 100)
model <- lm(y ~ ., data = data)
exp <- explain(model, data = data, y = data$y)
protected <- data$pop
privileged <- "A"
fobject <- fairness_check_regression(exp, protected = data$pop, privileged = "A")
expect_equal(fobject$privileged, "A")
expect_equal(
fobject$fairness_check_data,
fairness_check_regression(exp,
protected = data$pop,
privileged = "A", colorize = FALSE
)$fairness_check_data
)
expect_equal(fobject$protected, as.factor(data$pop))
expect_equal(fobject$label, "lm")
expect_equal(sort(as.character(fobject$fairness_check_data$metric)), c("independence", "separation", "sufficiency"))
expect_equal(fobject$epsilon, 0.8)
fobject <- fairness_check_regression(exp,
protected = data$pop,
privileged = "A",
label = "test",
epsilon = 0.45
)
expect_equal(fobject$epsilon, 0.45)
expect_equal(fobject$label, "test")
expect_error(fairness_check_regression(exp, fobject,
protected = data$pop,
privileged = "A",
label = "test"
))
expect_error(fairness_check_regression(exp, fobject,
protected = data$x,
privileged = "A"
))
expect_error(fairness_check_regression(exp, fobject,
protected = data$pop,
privileged = "not existing"
))
expect_error(fairness_check_regression(exp, fobject, epsilon = 10))
expect_error(fairness_check_regression(exp, fobject, epsilon = c(0.1, 0.2)))
exp2 <- exp
exp2$model_info$type <- "classification"
expect_error(fairness_check_regression(exp2, fobject,
protected = data$pop
))
exp$y <- seq(-15, 15, length.out = 1000)
exp$y_hat <- c(rep(-4000, 500), rep(5000, 500))
expect_equal(
capture.output(fairness_check_regression(exp, protected = data$pop, privileged = "A"))[6],
"-> Metric calculation\t\t: 3/3 metrics calculated for all models ( \033[33mapproximation algotithm did not coverage \033[39m )"
)
exp <- explain(model, data = data, y = data$y)
fobject <- fairness_check_regression(exp, protected = data$pop, privileged = "A")
fobject <- fairness_check_regression(exp, fobject, label = "lm2")
plt <- plot(fobject)
expect_equal(plt$labels$subtitle, "Created with lm2, lm")
expect_equal(plt$labels$title, "Fairness check regression")
expect_s3_class(plt, "ggplot")
}) |
CreateCalibOptions <- function(FUN_MOD,
FUN_CALIB = Calibration_Michel,
FUN_TRANSFO = NULL,
IsHyst = FALSE,
IsSD = FALSE,
FixedParam = NULL,
SearchRanges = NULL,
StartParamList = NULL,
StartParamDistrib = NULL) {
ObjectClass <- NULL
FUN_MOD <- match.fun(FUN_MOD)
FUN_CALIB <- match.fun(FUN_CALIB)
if(!is.null(FUN_TRANSFO)) {
FUN_TRANSFO <- match.fun(FUN_TRANSFO)
}
if (!is.logical(IsHyst) | length(IsHyst) != 1L) {
stop("'IsHyst' must be a logical of length 1")
}
if (!is.logical(IsSD) | length(IsSD) != 1L) {
stop("'IsSD' must be a logical of length 1")
}
BOOL <- FALSE
if (identical(FUN_MOD, RunModel_GR4H)) {
ObjectClass <- c(ObjectClass, "GR4H")
BOOL <- TRUE
}
if (identical(FUN_MOD, RunModel_GR5H)) {
ObjectClass <- c(ObjectClass, "GR5H")
BOOL <- TRUE
}
if (identical(FUN_MOD, RunModel_GR4J)) {
ObjectClass <- c(ObjectClass, "GR4J")
BOOL <- TRUE
}
if (identical(FUN_MOD, RunModel_GR5J)) {
ObjectClass <- c(ObjectClass, "GR5J")
BOOL <- TRUE
}
if (identical(FUN_MOD, RunModel_GR6J)) {
ObjectClass <- c(ObjectClass, "GR6J")
BOOL <- TRUE
}
if (identical(FUN_MOD, RunModel_GR2M)) {
ObjectClass <- c(ObjectClass, "GR2M")
BOOL <- TRUE
}
if (identical(FUN_MOD, RunModel_GR1A)) {
ObjectClass <- c(ObjectClass, "GR1A")
BOOL <- TRUE
}
if (identical(FUN_MOD, RunModel_CemaNeige)) {
ObjectClass <- c(ObjectClass, "CemaNeige")
BOOL <- TRUE
}
if (identical(FUN_MOD, RunModel_CemaNeigeGR4H)) {
ObjectClass <- c(ObjectClass, "CemaNeigeGR4H")
BOOL <- TRUE
}
if (identical(FUN_MOD, RunModel_CemaNeigeGR5H)) {
ObjectClass <- c(ObjectClass, "CemaNeigeGR5H")
BOOL <- TRUE
}
if (identical(FUN_MOD, RunModel_CemaNeigeGR4J)) {
ObjectClass <- c(ObjectClass, "CemaNeigeGR4J")
BOOL <- TRUE
}
if (identical(FUN_MOD, RunModel_CemaNeigeGR5J)) {
ObjectClass <- c(ObjectClass, "CemaNeigeGR5J")
BOOL <- TRUE
}
if (identical(FUN_MOD, RunModel_CemaNeigeGR6J)) {
ObjectClass <- c(ObjectClass, "CemaNeigeGR6J")
BOOL <- TRUE
}
if (identical(FUN_MOD, RunModel_Lag)) {
ObjectClass <- c(ObjectClass, "Lag")
if (IsSD) {
stop("RunModel_Lag should not be used with 'isSD=TRUE'")
}
BOOL <- TRUE
}
if (IsHyst) {
ObjectClass <- c(ObjectClass, "hysteresis")
}
if (IsSD) {
ObjectClass <- c(ObjectClass, "SD")
}
if (!BOOL) {
stop("incorrect 'FUN_MOD' for use in 'CreateCalibOptions'")
return(NULL)
}
BOOL <- FALSE
if (identical(FUN_CALIB, Calibration_Michel)) {
ObjectClass <- c(ObjectClass, "HBAN")
BOOL <- TRUE
}
if (!BOOL) {
stop("incorrect 'FUN_CALIB' for use in 'CreateCalibOptions'")
return(NULL)
}
if (is.null(FUN_TRANSFO)) {
if (identical(FUN_MOD, RunModel_GR4H) |
identical(FUN_MOD, RunModel_CemaNeigeGR4H)) {
FUN_GR <- TransfoParam_GR4H
}
if (identical(FUN_MOD, RunModel_GR5H) |
identical(FUN_MOD, RunModel_CemaNeigeGR5H)) {
FUN_GR <- TransfoParam_GR5H
}
if (identical(FUN_MOD, RunModel_GR4J) |
identical(FUN_MOD, RunModel_CemaNeigeGR4J)) {
FUN_GR <- TransfoParam_GR4J
}
if (identical(FUN_MOD, RunModel_GR5J) |
identical(FUN_MOD, RunModel_CemaNeigeGR5J)) {
FUN_GR <- TransfoParam_GR5J
}
if (identical(FUN_MOD, RunModel_GR6J) |
identical(FUN_MOD, RunModel_CemaNeigeGR6J)) {
FUN_GR <- TransfoParam_GR6J
}
if (identical(FUN_MOD, RunModel_GR2M)) {
FUN_GR <- TransfoParam_GR2M
}
if (identical(FUN_MOD, RunModel_GR1A)) {
FUN_GR <- TransfoParam_GR1A
}
if (identical(FUN_MOD, RunModel_CemaNeige)) {
if (IsHyst) {
FUN_GR <- TransfoParam_CemaNeigeHyst
} else {
FUN_GR <- TransfoParam_CemaNeige
}
}
if (identical(FUN_MOD, RunModel_Lag)) {
FUN_GR <- TransfoParam_Lag
}
if (is.null(FUN_GR)) {
stop("'FUN_GR' was not found")
return(NULL)
}
if (IsHyst) {
FUN_SNOW <- TransfoParam_CemaNeigeHyst
} else {
FUN_SNOW <- TransfoParam_CemaNeige
}
if (IsSD) {
FUN_LAG <- TransfoParam_Lag
}
if (sum(ObjectClass %in% c("GR4H", "GR5H", "GR4J", "GR5J", "GR6J", "GR2M", "GR1A", "CemaNeige", "Lag")) > 0) {
if (!IsSD) {
FUN_TRANSFO <- FUN_GR
} else {
FUN_TRANSFO <- function(ParamIn, Direction) {
Bool <- is.matrix(ParamIn)
if (!Bool) {
ParamIn <- rbind(ParamIn)
}
ParamOut <- NA * ParamIn
NParam <- ncol(ParamIn)
ParamOut[, 2:NParam] <- FUN_GR(ParamIn[, 2:NParam], Direction)
ParamOut[, 1 ] <- FUN_LAG(as.matrix(ParamIn[, 1]), Direction)
if (!Bool) {
ParamOut <- ParamOut[1, ]
}
return(ParamOut)
}
}
} else {
if (IsHyst & !IsSD) {
FUN_TRANSFO <- function(ParamIn, Direction) {
Bool <- is.matrix(ParamIn)
if (!Bool) {
ParamIn <- rbind(ParamIn)
}
ParamOut <- NA * ParamIn
NParam <- ncol(ParamIn)
ParamOut[, 1:(NParam - 4) ] <- FUN_GR(ParamIn[, 1:(NParam - 4)], Direction)
ParamOut[, (NParam - 3):NParam] <- FUN_SNOW(ParamIn[, (NParam - 3):NParam], Direction)
if (!Bool) {
ParamOut <- ParamOut[1, ]
}
return(ParamOut)
}
}
if (!IsHyst & !IsSD) {
FUN_TRANSFO <- function(ParamIn, Direction) {
Bool <- is.matrix(ParamIn)
if (!Bool) {
ParamIn <- rbind(ParamIn)
}
ParamOut <- NA * ParamIn
NParam <- ncol(ParamIn)
if (NParam <= 3) {
ParamOut[, 1:(NParam - 2)] <- FUN_GR(cbind(ParamIn[, 1:(NParam - 2)]), Direction)
} else {
ParamOut[, 1:(NParam - 2)] <- FUN_GR(ParamIn[, 1:(NParam - 2)], Direction)
}
ParamOut[, (NParam - 1):NParam] <- FUN_SNOW(ParamIn[, (NParam - 1):NParam], Direction)
if (!Bool) {
ParamOut <- ParamOut[1, ]
}
return(ParamOut)
}
}
if (IsHyst & IsSD) {
FUN_TRANSFO <- function(ParamIn, Direction) {
Bool <- is.matrix(ParamIn)
if (!Bool) {
ParamIn <- rbind(ParamIn)
}
ParamOut <- NA * ParamIn
NParam <- ncol(ParamIn)
ParamOut[, 2:(NParam - 4) ] <- FUN_GR(ParamIn[, 2:(NParam - 4)], Direction)
ParamOut[, (NParam - 3):NParam] <- FUN_SNOW(ParamIn[, (NParam - 3):NParam], Direction)
ParamOut[, 1 ] <- FUN_LAG(as.matrix(ParamIn[, 1]), Direction)
if (!Bool) {
ParamOut <- ParamOut[1, ]
}
return(ParamOut)
}
}
if (!IsHyst & IsSD) {
FUN_TRANSFO <- function(ParamIn, Direction) {
Bool <- is.matrix(ParamIn)
if (!Bool) {
ParamIn <- rbind(ParamIn)
}
ParamOut <- NA * ParamIn
NParam <- ncol(ParamIn)
if (NParam <= 3) {
ParamOut[, 2:(NParam - 2)] <- FUN_GR(cbind(ParamIn[, 2:(NParam - 2)]), Direction)
} else {
ParamOut[, 2:(NParam - 2)] <- FUN_GR(ParamIn[, 2:(NParam - 2)], Direction)
}
ParamOut[, (NParam - 1):NParam] <- FUN_SNOW(ParamIn[, (NParam - 1):NParam], Direction)
ParamOut[, 1 ] <- FUN_LAG(as.matrix(ParamIn[, 1]), Direction)
if (!Bool) {
ParamOut <- ParamOut[1, ]
}
return(ParamOut)
}
}
}
}
if (is.null(FUN_TRANSFO)) {
stop("'FUN_TRANSFO' was not found")
return(NULL)
}
if ("GR4H" %in% ObjectClass) {
NParam <- 4
}
if ("GR5H" %in% ObjectClass) {
NParam <- 5
}
if ("GR4J" %in% ObjectClass) {
NParam <- 4
}
if ("GR5J" %in% ObjectClass) {
NParam <- 5
}
if ("GR6J" %in% ObjectClass) {
NParam <- 6
}
if ("GR2M" %in% ObjectClass) {
NParam <- 2
}
if ("GR1A" %in% ObjectClass) {
NParam <- 1
}
if ("CemaNeige" %in% ObjectClass) {
NParam <- 2
}
if ("CemaNeigeGR4H" %in% ObjectClass) {
NParam <- 6
}
if ("CemaNeigeGR5H" %in% ObjectClass) {
NParam <- 7
}
if ("CemaNeigeGR4J" %in% ObjectClass) {
NParam <- 6
}
if ("CemaNeigeGR5J" %in% ObjectClass) {
NParam <- 7
}
if ("CemaNeigeGR6J" %in% ObjectClass) {
NParam <- 8
}
if ("Lag" %in% ObjectClass) {
NParam <- 1
}
if (IsHyst) {
NParam <- NParam + 2
}
if (IsSD) {
NParam <- NParam + 1
}
if (is.null(FixedParam)) {
FixedParam <- rep(NA, NParam)
} else {
if (!is.vector(FixedParam)) {
stop("FixedParam must be a vector")
}
if (length(FixedParam) != NParam) {
stop("Incompatibility between 'FixedParam' length and 'FUN_MOD'")
}
if (all(!is.na(FixedParam))) {
stop("At least one parameter must be not set (NA)")
}
if (all(is.na(FixedParam))) {
warning("You have not set any parameter in 'FixedParam'")
}
}
if (is.null(SearchRanges)) {
ParamT <- matrix(c(rep(-9.99, NParam), rep(+9.99, NParam)),
ncol = NParam, byrow = TRUE)
SearchRanges <- TransfoParam(ParamIn = ParamT, Direction = "TR", FUN_TRANSFO = FUN_TRANSFO)
} else {
if (!is.matrix(SearchRanges)) {
stop("'SearchRanges' must be a matrix")
}
if (!is.numeric(SearchRanges)) {
stop("'SearchRanges' must be a matrix of numeric values")
}
if (sum(is.na(SearchRanges)) != 0) {
stop("'SearchRanges' must not include NA values")
}
if (nrow(SearchRanges) != 2) {
stop("'SearchRanges' must have 2 rows")
}
if (ncol(SearchRanges) != NParam) {
stop("Incompatibility between 'SearchRanges' ncol and 'FUN_MOD'")
}
}
if (("HBAN" %in% ObjectClass & is.null(StartParamList) & is.null(StartParamDistrib))) {
if ("GR4H" %in% ObjectClass) {
ParamT <- matrix(c(+5.12, -1.18, +4.34, -9.69,
+5.58, -0.85, +4.74, -9.47,
+6.01, -0.50, +5.14, -8.87), ncol = 4, byrow = TRUE)
}
if (("GR5H" %in% ObjectClass) & ("interception" %in% ObjectClass)) {
ParamT <- matrix(c(+3.46, -1.25, +4.04, -9.53, -9.34,
+3.74, -0.41, +4.78, -8.94, -3.33,
+4.29, +0.16, +5.39, -7.39, +3.33), ncol = 5, byrow = TRUE)
}
if (("GR5H" %in% ObjectClass) & !("interception" %in% ObjectClass)) {
ParamT <- matrix(c(+3.28, -0.39, +4.14, -9.54, -7.49,
+3.62, -0.19, +4.80, -9.00, -6.31,
+4.01, -0.04, +5.43, -7.53, -5.33), ncol = 5, byrow = TRUE)
}
if ("GR4J" %in% ObjectClass) {
ParamT <- matrix(c(+5.13, -1.60, +3.03, -9.05,
+5.51, -0.61, +3.74, -8.51,
+6.07, -0.02, +4.42, -8.06), ncol = 4, byrow = TRUE)
}
if ("GR5J" %in% ObjectClass) {
ParamT <- matrix(c(+5.17, -1.13, +3.08, -9.37, -7.45,
+5.55, -0.46, +3.75, -9.09, -4.69,
+6.10, -0.11, +4.43, -8.60, -0.66), ncol = 5, byrow = TRUE)
}
if ("GR6J" %in% ObjectClass) {
ParamT <- matrix(c(+3.60, -1.00, +3.30, -9.10, -0.90, +3.00,
+3.90, -0.50, +4.10, -8.70, +0.10, +4.00,
+4.50, +0.50, +5.00, -8.10, +1.10, +5.00), ncol = 6, byrow = TRUE)
}
if ("GR2M" %in% ObjectClass) {
ParamT <- matrix(c(+5.03, -7.15,
+5.22, -6.74,
+5.85, -6.37), ncol = 2, byrow = TRUE)
}
if ("GR1A" %in% ObjectClass) {
ParamT <- matrix(c(-1.69,
-0.38,
+1.39), ncol = 1, byrow = TRUE)
}
if ("CemaNeige" %in% ObjectClass) {
ParamT <- matrix(c(-9.96, +6.63,
-9.14, +6.90,
+4.10, +7.21), ncol = 2, byrow = TRUE)
}
if ("CemaNeigeGR4H" %in% ObjectClass) {
ParamT <- matrix(c(+5.12, -1.18, +4.34, -9.69, -9.96, +6.63,
+5.58, -0.85, +4.74, -9.47, -9.14, +6.90,
+6.01, -0.50, +5.14, -8.87, +4.10, +7.21), ncol = 6, byrow = TRUE)
}
if (("CemaNeigeGR5H" %in% ObjectClass) & ("interception" %in% ObjectClass)) {
ParamT <- matrix(c(+3.46, -1.25, +4.04, -9.53, -9.34, -9.96, +6.63,
+3.74, -0.41, +4.78, -8.94, -3.33, -9.14, +6.90,
+4.29, +0.16, +5.39, -7.39, +3.33, +4.10, +7.21), ncol = 7, byrow = TRUE)
}
if (("CemaNeigeGR5H" %in% ObjectClass) & !("interception" %in% ObjectClass)) {
ParamT <- matrix(c(+3.28, -0.39, +4.14, -9.54, -7.49, -9.96, +6.63,
+3.62, -0.19, +4.80, -9.00, -6.31, -9.14, +6.90,
+4.01, -0.04, +5.43, -7.53, -5.33, +4.10, +7.21), ncol = 7, byrow = TRUE)
}
if ("CemaNeigeGR4J" %in% ObjectClass) {
ParamT <- matrix(c(+5.13, -1.60, +3.03, -9.05, -9.96, +6.63,
+5.51, -0.61, +3.74, -8.51, -9.14, +6.90,
+6.07, -0.02, +4.42, -8.06, +4.10, +7.21), ncol = 6, byrow = TRUE)
}
if ("CemaNeigeGR5J" %in% ObjectClass) {
ParamT <- matrix(c(+5.17, -1.13, +3.08, -9.37, -7.45, -9.96, +6.63,
+5.55, -0.46, +3.75, -9.09, -4.69, -9.14, +6.90,
+6.10, -0.11, +4.43, -8.60, -0.66, +4.10, +7.21), ncol = 7, byrow = TRUE)
}
if ("CemaNeigeGR6J" %in% ObjectClass) {
ParamT <- matrix(c(+3.60, -1.00, +3.30, -9.10, -0.90, +3.00, -9.96, +6.63,
+3.90, -0.50, +4.10, -8.70, +0.10, +4.00, -9.14, +6.90,
+4.50, +0.50, +5.00, -8.10, +1.10, +5.00, +4.10, +7.21), ncol = 8, byrow = TRUE)
}
if (IsHyst) {
ParamTHyst <- matrix(c(-7.00, -7.00,
-0.00, -0.00,
+7.00, +7.00), ncol = 2, byrow = TRUE)
ParamT <- cbind(ParamT, ParamTHyst)
}
if (IsSD) {
ParamTSD <- matrix(c(+1.25,
+2.50,
+5.00), ncol = 1, byrow = TRUE)
ParamT <- cbind(ParamTSD, ParamT)
}
StartParamList <- NULL
StartParamDistrib <- TransfoParam(ParamIn = ParamT, Direction = "TR", FUN_TRANSFO = FUN_TRANSFO)
}
if ("HBAN" %in% ObjectClass & !is.null(StartParamList)) {
if (!is.matrix(StartParamList)) {
stop("'StartParamList' must be a matrix")
}
if (!is.numeric(StartParamList)) {
stop("'StartParamList' must be a matrix of numeric values")
}
if (sum(is.na(StartParamList)) != 0) {
stop("'StartParamList' must not include NA values")
}
if (ncol(StartParamList) != NParam) {
stop("Incompatibility between 'StartParamList' ncol and 'FUN_MOD'")
}
}
if ("HBAN" %in% ObjectClass & !is.null(StartParamDistrib)) {
if (!is.matrix(StartParamDistrib)) {
stop("'StartParamDistrib' must be a matrix")
}
if (!is.numeric(StartParamDistrib[1, ])) {
stop("'StartParamDistrib' must be a matrix of numeric values")
}
if (sum(is.na(StartParamDistrib[1, ])) != 0) {
stop("'StartParamDistrib' must not include NA values on the first line")
}
if (ncol(StartParamDistrib) != NParam) {
stop("Incompatibility between 'StartParamDistrib' ncol and 'FUN_MOD'")
}
}
CalibOptions <- list(FixedParam = FixedParam, SearchRanges = SearchRanges, FUN_TRANSFO = FUN_TRANSFO)
if (!is.null(StartParamList)) {
CalibOptions <- c(CalibOptions, list(StartParamList = StartParamList))
}
if (!is.null(StartParamDistrib)) {
CalibOptions <- c(CalibOptions, list(StartParamDistrib = StartParamDistrib))
}
class(CalibOptions) <- c("CalibOptions", ObjectClass)
return(CalibOptions)
} |
test_that("unique values returned for strings with duplicate values", {
expect_equal(str_unique(c("a", "a", "a")), "a")
expect_equal(str_unique(c(NA, NA)), NA_character_)
}) |
zgamma <- setRefClass("Zelig-gamma",
contains = "Zelig-glm")
zgamma$methods(
initialize = function() {
callSuper()
.self$name <- "gamma"
.self$family <- "Gamma"
.self$link <- "inverse"
.self$authors <- "Kosuke Imai, Gary King, Olivia Lau"
.self$year <- 2007
.self$category <- "bounded"
.self$description <- "Gamma Regression for Continuous, Positive Dependent Variables"
.self$outcome <- "continous"
.self$wrapper <- "gamma"
}
)
zgamma$methods(
param = function(z.out, method="mvn") {
shape <- MASS::gamma.shape(z.out)
if(identical(method, "mvn")){
simalpha <- rnorm(n = .self$num, mean = shape$alpha, sd = shape$SE)
simparam.local <- mvrnorm(n = .self$num, mu = coef(z.out), Sigma = vcov(z.out))
simparam.local <- list(simparam = simparam.local, simalpha = simalpha)
return(simparam.local)
} else if(identical(method,"point")){
return(list(simparam = t(as.matrix(coef(z.out))), simalpha = shape$alpha ))
}
}
)
zgamma$methods(
qi = function(simparam, mm) {
coeff <- simparam$simparam
eta <- (coeff %*% t(mm) ) * simparam$simalpha
theta <- matrix(1 / eta, nrow = nrow(coeff), ncol=1)
ev <- theta * simparam$simalpha
pv<- matrix(rgamma(nrow(ev), shape = simparam$simalpha, scale = theta), nrow=nrow(ev), ncol=1)
return(list(ev = ev, pv = pv))
}
)
zgamma$methods(
mcfun = function(x, b0=0, b1=1, alpha=1, sim=TRUE){
lambda <- 1/(b0 + b1 * x)
if(sim){
y <- rgamma(n=length(x), shape=alpha, scale = lambda)
return(y)
}else{
return(alpha * lambda)
}
}
) |
ensure_docx <- function(docx) {
if (!inherits(docx, "docx")) stop("Must pass in a 'docx' object", call.=FALSE)
if (!(all(purrr::map_lgl(c("docx", "ns", "tbls", "path"), exists, where=docx))))
stop("'docx' object missing necessary components", call.=FALSE)
}
has_header <- function(tbl, rows, ns) {
look <- try(xml2::xml_find_first(tbl, "./w:tblPr/w:tblLook", ns), silent=TRUE)
if (inherits(look, "try-error")) {
return(NA)
} else {
look_attr <- xml2::xml_attrs(look)
if ("firstRow" %in% names(look_attr)) {
if (look_attr["firstRow"] == "0") {
return(NA)
} else {
return(paste0(xml2::xml_text(xml_find_all(rows[[1]], "./w:tc", ns)), collapse=", "))
}
} else {
return(NA)
}
}
}
is_url <- function(path) { grepl("^(http|ftp)s?://", path) }
is_docx <- function(path) { tolower(tools::file_ext(path)) == "docx" }
is_pptx <- function(path) { tolower(tools::file_ext(path)) == "pptx" }
is_doc <- function(path) { tolower(tools::file_ext(path)) == "doc" }
file_copy <- function(from, to) {
fc <- file.copy(from, to)
if (!fc) stop(sprintf("file copy failure for file %s", from), call.=FALSE)
}
convert_doc_to_docx <- function(docx_dir, doc_file) {
lo_path <- getOption("path_to_libreoffice")
if (is.null(lo_path)) {
stop(lo_path_missing, call. = FALSE)
}
if (Sys.info()["sysname"] == "Windows") {
convert_win(lo_path, docx_dir, doc_file)
} else {
convert_osx(lo_path, docx_dir, doc_file)
}
}
convert_win <- function(lo_path, docx_dir, doc_file,
convert_to = 'docx:"MS Word 2007 XML"') {
cmd <- sprintf('"%s" --convert-to %s -headless -outdir "%s" "%s"',
lo_path,
convert_to,
docx_dir,
doc_file)
system(cmd, show.output.on.console = FALSE)
}
convert_osx <- function(lo_path, docx_dir, doc_file,
convert_to = 'docx:"MS Word 2007 XML"') {
cmd <- sprintf('"%s" --convert-to %s --headless --outdir "%s" "%s"',
lo_path,
convert_to,
docx_dir,
doc_file)
res <- system(cmd, intern = TRUE)
}
set_libreoffice_path <- function(path) {
stopifnot(is.character(path))
if (!file.exists(path)) stop(sprintf("Cannot find '%s'", path), call.=FALSE)
options("path_to_libreoffice" = path)
}
lo_assert <- function() {
lo_path <- getOption("path_to_libreoffice")
if (is.null(lo_path)) {
lo_path <- lo_find()
set_libreoffice_path(lo_path)
}
}
lo_find <- function() {
user_os <- Sys.info()["sysname"]
if (!user_os %in% names(lo_paths_to_check)) {
stop(lo_path_missing, call. = FALSE)
}
lo_path <- NULL
for (path in lo_paths_to_check[[user_os]]) {
if (file.exists(path)) {
lo_path <- path
break
}
}
if (is.null(lo_path)) {
stop(lo_path_missing, call. = FALSE)
}
lo_path
}
lo_paths_to_check <- list(
"Linux" = c("/usr/bin/soffice",
"/usr/local/bin/soffice"),
"Darwin" = c("/Applications/LibreOffice.app/Contents/MacOS/soffice",
"~/Applications/LibreOffice.app/Contents/MacOS/soffice"),
"Windows" = c("C:\\Program Files\\LibreOffice\\program\\soffice.exe",
"C:\\progra~1\\libreo~1\\program\\soffice.exe")
)
lo_path_missing <- paste(
"LibreOffice software required to read '.doc' files.",
"Cannot determine file path to LibreOffice.",
"To download LibreOffice, visit: https://www.libreoffice.org/ \n",
"If you've already downloaded the software, use function",
"'set_libreoffice_path()' to point R to your local 'soffice.exe' file"
) |
priorlevels = function(levelvector) {
sum = 0
priors = c(0)
for (x in 1:length(levelvector)) {
sum = sum + levelvector[x]
priors = c(priors, sum)
}
return(priors)
} |
ebirdtaxonomy <- function(cat=NULL, locale=NULL, key = NULL, ...){
cats <- c("domestic", "form", "hybrid", "intergrade", "issf", "slash", "species", "spuh")
if (!all(vapply(cat, function(x) x %in% cats, FUN.VALUE = logical(1)))) {
stop("You have supplied an invalid species category")
}
cat <- if(!is.null(cat)) cat <- paste0(cat, collapse = ",")
args <- list(fmt='json', cat=cat, locale=locale)
if (is.null(key) && !nzchar(Sys.getenv("EBIRD_KEY"))) {
key <- ""
}
ebird_GET(paste0(ebase(), 'ref/taxonomy/ebird'), args, key = key, ...)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.