code
stringlengths 1
13.8M
|
---|
expected <- eval(parse(text="logical(0)"));
test(id=0, code={
argv <- eval(parse(text="list(NULL)"));
do.call(`is.infinite`, argv);
}, o=expected); |
fevd.varshrinkest <-
function (x, n.ahead = 10, ...) {
if (!inherits(x, "varest")) {
stop("\nPlease provide an object inheriting class 'varest'.\n")
}
n.ahead <- abs(as.integer(n.ahead))
K <- x$K
p <- x$p
ynames <- names(x$varresult)
msey <- h_fecov(x, n.ahead = n.ahead)
Psi <- Psi(x, nstep = n.ahead)
mse <- matrix(NA, nrow = n.ahead, ncol = K)
Omega <- array(0, dim = c(n.ahead, K, K))
for (i in 1:n.ahead) {
mse[i, ] <- diag(msey[, , i])
temp <- matrix(0, K, K)
for (l in 1:K) {
for (m in 1:K) {
for (j in 1:i) {
temp[l, m] <- temp[l, m] + Psi[l, m, j]^2
}
}
}
temp <- temp/mse[i, ]
for (j in 1:K) {
Omega[i, , j] <- temp[j, ]
}
}
result <- list()
for (i in 1:K) {
result[[i]] <- matrix(Omega[, , i], nrow = n.ahead, ncol = K)
colnames(result[[i]]) <- ynames
}
names(result) <- ynames
class(result) <- "varfevd"
return(result)
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(ActFrag) |
expected <- eval(parse(text="structure(list(fit = structure(numeric(0), .Dim = c(10L, 0L), constant = 0), se.fit = structure(numeric(0), .Dim = c(10L, 0L)), df = 10L, residual.scale = 0.523484262069588), .Names = c(\"fit\", \"se.fit\", \"df\", \"residual.scale\"))"));
test(id=0, code={
argv <- eval(parse(text="list(fit = structure(numeric(0), .Dim = c(10L, 0L), constant = 0), se.fit = structure(numeric(0), .Dim = c(10L, 0L)), df = 10L, residual.scale = 0.523484262069588)"));
do.call(`list`, argv);
}, o=expected); |
binom.blaker.limits <- function(x,n,level=.95,tol=1e-10,...) {
if (n < 1 || x < 0 || x > n) stop("Parameters n = ",n,", x = ",x, " wrong!")
if (level <= 0 || level >= 1) stop("Confidence level ",level," out of (0, 1)!")
if (tol <= 0) stop("Numerical tolerance ",tol," nonpositive!")
lower <- binom.blaker.lower.limit(x,n,level,tol,...)
upper <- 1 - binom.blaker.lower.limit(n-x,n,level,tol,...)
return(c(lower,upper))
} |
difStd <-function(Data,group,focal.name,anchor=NULL,match="score",
stdWeight="focal",thrSTD=0.1,purify=FALSE,nrIter=10,
save.output=FALSE, output=c("out","default"))
{
if (purify & match[1] != "score")
stop("purification not allowed when matching variable is not 'score'",
call. = FALSE)
internalSTD<-function(){
if (length(group) == 1) {
if (is.numeric(group)==TRUE) {
gr <- Data[, group]
DATA <- Data[,(1:ncol(Data))!= group]
colnames(DATA) <- colnames(Data)[(1:ncol(Data))!= group]
}
else {
gr <- Data[, colnames(Data)==group]
DATA <- Data[,colnames(Data)!= group]
colnames(DATA) <- colnames(Data)[colnames(Data)!= group]
}
}
else {
gr <- group
DATA <- Data
}
Group <- rep(0, nrow(DATA))
Group[gr == focal.name] <- 1
if (!is.null(anchor)){
dif.anchor<-anchor
if (is.numeric(anchor)) ANCHOR<-anchor
else{
ANCHOR<-NULL
for (i in 1:length(anchor)) ANCHOR[i]<-(1:ncol(DATA))[colnames(DATA)==anchor[i]]
}
}
else {
ANCHOR<-1:ncol(DATA)
dif.anchor<-NULL
}
if (!purify | match[1] != "score" | !is.null(anchor)) {
resProv<-stdPDIF(DATA,Group,stdWeight=stdWeight,anchor=ANCHOR,match=match)
STATS <- resProv$resStd
ALPHA <- resProv$resAlpha
if (max(abs(STATS))<=thrSTD) DIFitems<-"No DIF item detected"
else DIFitems <-(1:ncol(DATA))[abs(STATS)>thrSTD]
RES <-list(PDIF=STATS,stdAlpha=ALPHA,thr=thrSTD,DIFitems=DIFitems,
match=resProv$match,purification=purify,names=colnames(DATA),
anchor.names=dif.anchor,stdWeight=stdWeight,save.output=save.output,output=output)
if (!is.null(anchor)) {
RES$PDIF[ANCHOR]<-NA
RES$stdAlpha[ANCHOR]<-NA
for (i in 1:length(RES$DIFitems)){
if (sum(RES$DIFitems[i]==ANCHOR)==1) RES$DIFitems[i]<-NA
}
RES$DIFitems<-RES$DIFitems[!is.na(RES$DIFitems)]
}
}
else{
nrPur<-0
difPur<-NULL
noLoop<-FALSE
resProv<-stdPDIF(DATA,Group,stdWeight=stdWeight,match=match)
stats1 <-resProv$resStd
alpha1<-resProv$resAlpha
if (max(abs(stats1))<=thrSTD) {
DIFitems<-"No DIF item detected"
noLoop<-TRUE
}
else{
dif <-(1:ncol(DATA))[abs(stats1)>thrSTD]
difPur<-rep(0,length(stats1))
difPur[dif]<-1
repeat{
if (nrPur>=nrIter) break
else{
nrPur<-nrPur+1
nodif <-NULL
if (is.null(dif)==TRUE) nodif<-1:ncol(DATA)
else{
for (i in 1:ncol(DATA)){
if (sum(i==dif)==0) nodif<-c(nodif,i)
}
}
resProv<-stdPDIF(DATA,Group,anchor=nodif,stdWeight=stdWeight,match=match)
stats2 <-resProv$resStd
alpha2<-resProv$resAlpha
if (max(abs(stats2))<=thrSTD) dif2<-NULL
else dif2<-(1:ncol(DATA))[abs(stats2)>thrSTD]
difPur<-rbind(difPur,rep(0,ncol(DATA)))
difPur[nrPur+1,dif2]<-1
if (length(dif)!=length(dif2)) dif<-dif2
else{
dif<-sort(dif)
dif2<-sort(dif2)
if (sum(dif==dif2)==length(dif)){
noLoop<-TRUE
break
}
else dif<-dif2
}
}
}
stats1<-stats2
alpha1<-alpha2
DIFitems <-(1:ncol(DATA))[abs(stats1)>thrSTD]
}
if (!is.null(difPur)){
ro<-co<-NULL
for (ir in 1:nrow(difPur)) ro[ir]<-paste("Step",ir-1,sep="")
for (ic in 1:ncol(difPur)) co[ic]<-paste("Item",ic,sep="")
rownames(difPur)<-ro
colnames(difPur)<-co
}
RES<-list(PDIF=stats1,stdAlpha=alpha1,thr=thrSTD,DIFitems=DIFitems,
match=resProv$match,purification=purify,nrPur=nrPur,difPur=difPur,convergence=noLoop,
names=colnames(DATA),anchor.names=NULL,stdWeight=stdWeight,save.output=save.output,output=output)
}
class(RES)<-"PDIF"
return(RES)
}
resToReturn<-internalSTD()
if (save.output==TRUE){
if (output[2]=="default") wd<-paste(getwd(),"/",sep="")
else wd<-output[2]
fileName<-paste(wd,output[1],".txt",sep="")
capture.output(resToReturn,file=fileName)
}
return(resToReturn)
}
plot.PDIF <-function(x,pch=8,number=TRUE,col="red",save.plot=FALSE,save.options=c("plot","default","pdf"),...)
{
internalSTD<-function(){
res <- x
if (!number) {
plot(res$PDIF,xlab="Item",ylab="Standardization statistic",ylim=c(max(-1,min(c(res$PDIF,-res$thr)-0.2,na.rm=TRUE)),min(1,max(c(res$PDIF,res$thr)+0.2,na.rm=TRUE))),pch=pch,main="Standardization")
if (!is.character(res$DIFitems)) points(res$DIFitems,res$PDIF[res$DIFitems],pch=pch,col=col)
}
else {
plot(res$PDIF,xlab="Item",ylab="St-PDIF statistic",ylim=c(max(-1,min(c(res$PDIF,-res$thr)-0.2,na.rm=TRUE)),min(1,max(c(res$PDIF,res$thr)+0.2,na.rm=TRUE))),col="white",main="Standardization")
text(1:length(res$PDIF),res$PDIF,1:length(res$PDIF))
if (!is.character(res$DIFitems)) text(res$DIFitems,res$PDIF[res$DIFitems],res$DIFitems,col=col)
}
abline(h=res$thr)
abline(h=-res$thr)
abline(h=0,lty=2)
}
internalSTD()
if (save.plot){
plotype<-NULL
if (save.options[3]=="pdf") plotype<-1
if (save.options[3]=="jpeg") plotype<-2
if (is.null(plotype)) cat("Invalid plot type (should be either 'pdf' or 'jpeg').","\n","The plot was not captured!","\n")
else {
if (save.options[2]=="default") wd<-paste(getwd(),"/",sep="")
else wd<-save.options[2]
fileName<-paste(wd,save.options[1],switch(plotype,'1'=".pdf",'2'=".jpg"),sep="")
if (plotype==1){
{
pdf(file=fileName)
internalSTD()
}
dev.off()
}
if (plotype==2){
{
jpeg(filename=fileName)
internalSTD()
}
dev.off()
}
cat("The plot was captured and saved into","\n"," '",fileName,"'","\n","\n",sep="")
}
}
else cat("The plot was not captured!","\n",sep="")
}
print.PDIF<-function(x, ...){
res <- x
cat("\n")
cat("Detection of Differential Item Functioning using standardization method","\n")
if (res$purification & is.null(res$anchor.names)) pur<-"with "
else pur<-"without "
cat(pur, "item purification","\n","\n",sep="")
if (res$stdWeight=="total") wt<-"both groups (the total group)"
else wt<-paste("the ",res$stdWeight," group",sep="")
cat("Weights based on",wt,"\n" ,"\n")
if (res$purification & is.null(res$anchor.names)){
if (res$nrPur<=1) word<-" iteration"
else word<-" iterations"
if (!res$convergence) {
cat("WARNING: no item purification convergence after ",res$nrPur,word,"\n",sep="")
loop<-NULL
for (i in 1:res$nrPur) loop[i]<-sum(res$difPur[1,]==res$difPur[i+1,])
if (max(loop)!=length(res$PDIF)) cat("(Note: no loop detected in less than ",res$nrPur,word,")","\n",sep="")
else cat("(Note: loop of length ",min((1:res$nrPur)[loop==length(res$PDIF)])," in the item purification process)","\n",sep="")
cat("WARNING: following results based on the last iteration of the purification","\n","\n")
}
else cat("Convergence reached after ",res$nrPur,word,"\n","\n",sep="")
}
if (res$match[1] == "score")
cat("Matching variable: test score", "\n", "\n")
else cat("Matching variable: specified matching variable",
"\n", "\n")
if (is.null(res$anchor.names)) {
itk<-1:length(res$PDIF)
cat("No set of anchor items was provided", "\n", "\n")
}
else {
itk<-(1:length(res$PDIF))[!is.na(res$PDIF)]
cat("Anchor items (provided by the user):", "\n")
if (is.numeric(res$anchor.names)) mm<-res$names[res$anchor.names]
else mm<-res$anchor.names
mm <- cbind(mm)
rownames(mm) <- rep("", nrow(mm))
colnames(mm) <- ""
print(mm, quote = FALSE)
cat("\n", "\n")
}
cat("Standardized P-DIF statistic:","\n","\n")
symb<-symnum(abs(res$PDIF),c(0,0.04,0.05,0.1,0.2,1),symbols=c("",".","*","**","***"))
m1<-cbind(round(res$PDIF[itk],4))
m1<-noquote(cbind(format(m1,justify="right"),symb[itk]))
if (!is.null(res$names)) rownames(m1)<-res$names[itk]
else{
rn<-NULL
for (i in 1:nrow(m1)) rn[i]<-paste("Item",i,sep="")
rownames(m1)<-rn[itk]
}
colnames(m1)<-c("Stat.","")
print(m1)
cat("\n")
cat("Signif. codes (abs. values): 0 ' ' 0.04 '.' 0.05 '*' 0.1 '**' 0.2 '***' 1 ","\n")
cat("\n","Detection thresholds: ",-round(res$thr,4)," and ",round(res$thr,4),"\n","\n",sep="")
if (is.character(res$DIFitems)) cat("Items detected as DIF items:",res$DIFitems,"\n","\n")
else {
cat("Items detected as DIF items:","\n")
if (!is.null(res$names)) m2 <- res$names
else {
rn <- NULL
for (i in 1:length(res$PDIF)) rn[i] <- paste("Item", i, sep = "")
m2 <- rn
}
m2<-cbind(m2[res$DIFitems])
rownames(m2)<-rep("",nrow(m2))
colnames(m2)<-""
print(m2,quote=FALSE)
cat("\n","\n")
}
cat("Effect sizes:", "\n", "\n")
cat("Effect size code:", "\n")
cat(" 'A': negligible effect", "\n")
cat(" 'B': moderate effect", "\n")
cat(" 'C': large effect", "\n", "\n")
r2 <- round(-2.35*log(res$stdAlpha),4)
symb1 <- symnum(abs(res$PDIF), c(0, 0.05, 0.1, Inf), symbols = c("A",
"B", "C"))
symb2 <- symnum(abs(r2), c(0, 1, 1.5, Inf), symbols = c("A",
"B", "C"))
matR2<-cbind(round(res$PDIF[itk],4),round(res$stdAlpha[itk],4),r2[itk])
matR2<- noquote(cbind(format(matR2, justify="right"), symb1[itk], symb2[itk]))
if (!is.null(res$names)) rownames(matR2) <- res$names[itk]
else {
rn <- NULL
for (i in 1:nrow(matR2)) rn[i] <- paste("Item", i, sep = "")
rownames(matR2) <- rn[itk]
}
colnames(matR2) <- c("St-P-DIF","alphaStd","deltaStd","DSB","ETS")
print(matR2)
cat("\n")
cat("Effect size codes:", "\n")
cat(" Dorans, Schmitt & Bleistein (DSB): 0 'A' 0.05 'B' 0.10 'C'","\n")
cat(" (for absolute values of 'St-P-DIF')","\n")
cat(" ETS Delta Scale (ETS): 0 'A' 1 'B' 1.5 'C'","\n")
cat(" (for absolute values of 'deltaStd')","\n")
if (!x$save.output) cat("\n","Output was not captured!","\n")
else {
if (x$output[2]=="default") wd<-paste(getwd(),"/",sep="")
else wd<-x$output[2]
fileName<-paste(wd,x$output[1],".txt",sep="")
cat("\n","Output was captured and saved into file","\n"," '",fileName,"'","\n","\n",sep="")
}
} |
xtable.fdt <- function(x,caption = NULL, label = NULL, align = NULL,
digits = NULL, display = NULL, auto = FALSE,...){
res_DF <- x$table
newclass1 <- res_DF[,1]
newclass2 <- gsub("\\[","$[",newclass1)
newclass3 <- gsub("\\)",")$",newclass2)
res_DF[,1] <- newclass3
newnames <- names(res_DF)
newnames1 <- gsub("\\%","\\\\%",newnames)
names(res_DF) <- newnames1
return(xtable(res_DF,caption = caption, label = label, align = align,
digits = digits, display = display, auto = auto, ...))
} |
coord.interp.linear <- function(coords1,coords2,step,num.steps){
return (coords1 + ((coords2-coords1)*(step/num.steps)))
}
coord.interp.smoothstep <- function(coords1,coords2,step,num.steps){
t <-step/num.steps
return (coords1 + ((coords2-coords1)*(t^2 * (3-2*t))))
} |
setMethodS3("removeDirectory", "default", function(path, recursive=FALSE, mustExist=TRUE, ...) {
path <- Arguments$getReadablePath(path, mustExist=mustExist)
path <- path.expand(path)
path <- Arguments$getReadablePath(path, mustExist=mustExist)
recursive <- Arguments$getLogical(recursive)
pathT <- Sys.readlink2(path, what="corrected")
isSymlink <- (!is.na(pathT) && nchar(pathT, type="chars") > 0L)
if (isSymlink) {
if (.Platform$OS.type == "windows") {
cmd <- sprintf("rmdir %s", dQuote(normalizePath(path)))
shell(cmd, shell=Sys.getenv("COMSPEC"), intern=TRUE, mustWork=TRUE)
} else {
file.remove(path)
}
return(invisible(!isDirectory(path)))
}
pathnames <- list.files(path=path, all.files=TRUE, full.names=FALSE)
pathnames <- setdiff(pathnames, c(".", ".."))
isEmpty <- (length(pathnames) == 0)
if (!isEmpty && !recursive) {
throw("Cannot remove directory. Directory is not empty: ", path)
}
res <- unlink(path, recursive=TRUE)
return(invisible(!isDirectory(path)))
}) |
"GPDIC1" |
slm.class <- setClass("slm",
slots=list(method_cov_st="character",
cov_st = "numeric",
Cov_ST = "matrix",
model_selec = "numeric",
norm_matrix = "matrix",
design_qr = "matrix"),
contains = "lm"
)
slm <- function(myformula,
data = NULL,
model = TRUE,
x = FALSE,
y = FALSE,
qr = TRUE,
method_cov_st="fitAR",
cov_st = NULL,
Cov_ST = NULL,
model_selec = -1,
model_max = 50,
kernel_fonc = NULL,
block_size = NULL,
block_n = NULL,
plot = FALSE){
lm_call <- lm(myformula, data = data, model = model, x = x, y = y, qr = qr)
lm_call$call = "slm(formula = myformula, data = data, x = x, y = y)"
Y = lm_call$model[[1]]
design = model.matrix(lm_call)
p <- lm_call$rank
Qr <- qr(lm_call)
p1 <- 1L:p
design_qr <- chol2inv(Qr$qr[p1, p1, drop = FALSE])
norm_matrix = diag(sqrt(apply(design^2,2,sum)), nrow=dim(design)[2])
if (is.null(cov_st) && is.null(Cov_ST)){
if (method_cov_st=="hac") {
model_selec = NA_real_
cov_st = NA_real_
Cov_ST = matrix(NA_real_)
} else {
mylist = cov_method(epsilon = lm_call$residuals,
method_cov_st = method_cov_st,
model_selec = model_selec,
model_max = model_max,
kernel_fonc = kernel_fonc,
block_size = block_size,
block_n = block_n,
plot = plot)
cov_st = mylist$cov_st
Cov_ST = matrix(NA_real_)
model_selec = mylist$model_selec
}
} else {
if (is.null(Cov_ST)) {
epsilon = lm_call$residuals
method_cov_st = "manual"
model_selec = NA_real_
cov_st = cov_st
Cov_ST = matrix(NA_real_)
} else if (is.null(cov_st)) {
epsilon = lm_call$residuals
method_cov_st = "manual_matrix"
model_selec = NA_real_
cov_st = NA_real_
Cov_ST = Cov_ST
} else {
epsilon = lm_call$residuals
method_cov_st = "manual_matrix"
model_selec = NA_real_
cov_st = NA_real_
Cov_ST = Cov_ST
}
}
out <- slm.class(lm_call,
method_cov_st=method_cov_st,
cov_st = cov_st,
Cov_ST = Cov_ST,
model_selec = model_selec,
norm_matrix = norm_matrix,
design_qr = design_qr )
return(out)
}
cov_method <- function(epsilon, method_cov_st = "fitAR", model_selec = -1,
model_max=NULL, kernel_fonc = NULL, block_size = NULL,
block_n = NULL, plot = FALSE){
switch(method_cov_st,
fitAR={out = cov_AR(epsilon,model_selec = model_selec,plot=plot)},
spectralproj={out = cov_spectralproj(epsilon,model_selec = model_selec,model_max = model_max,plot=plot)},
efromovich={out = cov_efromovich(epsilon,plot=plot)},
kernel={out = cov_kernel(epsilon,model_selec = model_selec,model_max = model_max,kernel_fonc = kernel_fonc
,block_size = block_size,block_n = block_n,plot=plot)},
select={out = cov_select(epsilon,model_selec = model_selec,plot=plot)}
)
return(out)
}
cov_AR <- function(epsilon, model_selec = -1, plot=FALSE){
if (plot == TRUE) {
acf(epsilon, lag.max=sqrt(length(epsilon)), type="correlation", main=" ")
pacf(epsilon, lag.max=sqrt(length(epsilon)), main=" ")
}
n = length(epsilon)
if (model_selec == -1){
my_ar = ar(epsilon, aic = TRUE)
if (my_ar$order==0) {
cov_st = rep(0,n)
cov_st[1] = var(epsilon)
model_selec = my_ar$order
} else {
coef_ar = my_ar$ar
cov_st = ltsa::tacvfARMA(phi=coef_ar, maxLag=n-1, sigma2=my_ar$var.pred)
model_selec = my_ar$order
}
} else {
if (model_selec == 0){
cov_st = rep(0,n)
cov_st[1] = var(epsilon)
} else {
my_ar = ar(epsilon, aic = FALSE, order.max = model_selec)
coef_ar = my_ar$ar
cov_st = ltsa::tacvfARMA(phi=coef_ar, maxLag=n-1, sigma2=my_ar$var.pred)
}
}
return(list(model_selec=model_selec,cov_st=cov_st))
}
cov_spectralproj <- function(epsilon, model_selec = -1, model_max = min(100,length(epsilon)/2), plot=FALSE){
n = length(epsilon)
cov_epsilon = as.vector(acf(epsilon,type="covariance",lag.max = n-1,plot=FALSE)$acf)
if (model_selec==-1) {
mat_a = matrix(0, nrow=model_max, ncol=model_max)
contrast = rep(0,model_max)
pen = rep(0,model_max)
pen_contrast = rep(0,model_max)
for(d in seq(1,model_max)) {
a_hat = rep(0,d)
for (j in seq(1,d)) {
vec = rep(0,n-1)
for (r in seq(1,n-1)) {
vec[r] = (cov_epsilon[r+1]/r)*(sin((pi*j*r)/d) - sin((pi*(j-1)*r)/d))
}
a_hat[j] = sqrt(d/pi)*(cov_epsilon[1]/(2*d) + (1/pi)*sum(vec))
}
mat_a[d,1:d] = a_hat
pen[d] = d
contrast[d] = (-1)*sum(mat_a[d,1:d]^2)
pen_contrast[d] = contrast[d] + pen[d]
}
datacap = matrix(0,nrow=model_max,ncol=4,dimnames = list(seq(1,model_max),c("model","pen","complexity","contrast")))
datacap[,1] = pen
datacap[,2] = pen
datacap[,3] = pen
datacap[,4] = contrast
d_hat = capushe::Djump(datacap)
dhat = as.numeric(d_hat@model)
model_selec = dhat
spec_dens = sqrt(dhat/pi)*mat_a[dhat,(1:dhat)]
} else {
dhat = model_selec
a_hat = rep(0,dhat)
for (j in seq(1,dhat)) {
vec = rep(0,n-1)
for (r in seq(1,n-1)) {
vec[r] = (cov_epsilon[r+1]/r)*(sin((pi*j*r)/dhat) - sin((pi*(j-1)*r)/dhat))
}
a_hat[j] = sqrt(dhat/pi)*(cov_epsilon[1]/(2*dhat) + (1/pi)*sum(vec))
}
spec_dens = sqrt(dhat/pi)*a_hat
}
if (plot==TRUE) {
x = seq(0,pi-(pi/dhat),by=pi/dhat)
plot(x,spec_dens,type="s",ylab="spectral density")
}
cov_st = rep(0,n)
cov_st[1] = ((2*pi)/dhat)*sum(spec_dens)
interm = rep(0,dhat)
for (k in seq(2,n)) {
for (j in seq(1,dhat)) {
interm[j] = spec_dens[j]*(sin(((k-1)*pi*j)/dhat) - sin(((k-1)*pi*(j-1))/dhat))
}
cov_st[k] = (2/(k-1))*sum(interm)
}
return(list(model_selec=model_selec,cov_st=cov_st))
}
cov_select <- function(epsilon, model_selec, plot=FALSE){
n = length(epsilon)
if (plot==TRUE) {
acf(epsilon,type="correlation",lag.max=max(model_selec)+1,main=" ")
}
cov_epsilon = as.vector(acf(epsilon,type="covariance",lag.max = n-1,plot=FALSE)$acf)
cov_st = rep(0,n)
cov_st[1] = cov_epsilon[1]
cov_st[model_selec+1] = cov_epsilon[model_selec+1]
return(list(model_selec=model_selec,cov_st=cov_st))
}
cov_kernel <- function(epsilon, model_selec = -1, model_max = min(50,length(epsilon)/2), kernel_fonc = triangle,
block_size = length(epsilon)/2, block_n = 100, plot=FALSE){
n = length(epsilon)
if (model_selec==-1) {
risk = rep(0,model_max)
SE = rep(0,model_max)
for (treshold in seq(1,model_max)) {
result = Rboot(epsilon,treshold,block_size,block_n,model_max,kernel_fonc)
risk[treshold] = result[1]
SE[treshold] = result[2]
}
model_selec = which.min(risk)
if (plot==TRUE) {
plot(seq(0,model_max-1),risk,type="l",xlab="lag")
acf(epsilon,type="correlation",lag.max=model_selec-1,main=" ")
}
cov_st = rep(0,n)
cov_st[1:model_selec] = acf(epsilon,type="covariance",lag.max=model_selec-1,plot=FALSE)$acf
kern = rep(0,n)
kern[1:model_selec] = kernel_fonc((0:(model_selec-1))/model_selec)
cov_st = kern*cov_st
return(list(model_selec=model_selec-1,cov_st=cov_st))
} else {
if (plot==TRUE) {
acf(epsilon,lag.max=sqrt(length(epsilon)),type="correlation", main=" ")
}
model_selec = model_selec + 1
cov_st = rep(0,n)
cov_st[1:model_selec] = acf(epsilon,type="covariance",lag.max=model_selec-1,plot=FALSE)$acf
kern = rep(0,n)
kern[1:model_selec] = kernel_fonc((0:(model_selec-1))/model_selec)
cov_st = kern*cov_st
return(list(model_selec=model_selec-1,cov_st=cov_st))
}
}
cov_efromovich <- function(epsilon, plot = FALSE) {
n = length(epsilon)
Jn = floor((log(n))^(5/4))
cov_epsilon = as.vector(acf(epsilon,type="covariance",lag.max=n-1,plot=FALSE)$acf)
dn_hat = cov_epsilon[1]^2 + 2*sum(cov_epsilon[2:(Jn+1)]^2)
Gamma_hat = rep(0,(Jn+1))
for (j in seq(1:(Jn+1))) {
Gamma_hat[j] = max(0,(cov_epsilon[j]^2 - dn_hat/n))
}
wn_hat = rep(0,n)
for (j in seq(1:(Jn+1))) {
wn_hat[j] = Gamma_hat[j]/(cov_epsilon[j]^2)
}
sum_jn = rep(0,(Jn+1))
sum_jn[1] = 2*dn_hat/n - (cov_epsilon[1])^2
for (j in seq(2,(Jn+1))) {
sum_jn[j] = sum_jn[j-1] + 2*(2*dn_hat/n - cov_epsilon[j]^2)
}
Jn_hat = which.min(sum_jn)
wn_hat_2 = rep(0,n)
for (j in seq(1:(Jn_hat))) {
wn_hat_2[j] = wn_hat[j]
}
cov_st = wn_hat_2*cov_epsilon
model_selec = Jn_hat - 1
if (plot==TRUE) {
acf(epsilon,type="correlation",lag.max=model_selec,main=" ")
}
return(list(model_selec=model_selec,cov_st=cov_st))
} |
NULL
signer_add_profile_permission <- function(profileName, profileVersion = NULL, action, principal, revisionId = NULL, statementId) {
op <- new_operation(
name = "AddProfilePermission",
http_method = "POST",
http_path = "/signing-profiles/{profileName}/permissions",
paginator = list()
)
input <- .signer$add_profile_permission_input(profileName = profileName, profileVersion = profileVersion, action = action, principal = principal, revisionId = revisionId, statementId = statementId)
output <- .signer$add_profile_permission_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$add_profile_permission <- signer_add_profile_permission
signer_cancel_signing_profile <- function(profileName) {
op <- new_operation(
name = "CancelSigningProfile",
http_method = "DELETE",
http_path = "/signing-profiles/{profileName}",
paginator = list()
)
input <- .signer$cancel_signing_profile_input(profileName = profileName)
output <- .signer$cancel_signing_profile_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$cancel_signing_profile <- signer_cancel_signing_profile
signer_describe_signing_job <- function(jobId) {
op <- new_operation(
name = "DescribeSigningJob",
http_method = "GET",
http_path = "/signing-jobs/{jobId}",
paginator = list()
)
input <- .signer$describe_signing_job_input(jobId = jobId)
output <- .signer$describe_signing_job_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$describe_signing_job <- signer_describe_signing_job
signer_get_signing_platform <- function(platformId) {
op <- new_operation(
name = "GetSigningPlatform",
http_method = "GET",
http_path = "/signing-platforms/{platformId}",
paginator = list()
)
input <- .signer$get_signing_platform_input(platformId = platformId)
output <- .signer$get_signing_platform_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$get_signing_platform <- signer_get_signing_platform
signer_get_signing_profile <- function(profileName, profileOwner = NULL) {
op <- new_operation(
name = "GetSigningProfile",
http_method = "GET",
http_path = "/signing-profiles/{profileName}",
paginator = list()
)
input <- .signer$get_signing_profile_input(profileName = profileName, profileOwner = profileOwner)
output <- .signer$get_signing_profile_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$get_signing_profile <- signer_get_signing_profile
signer_list_profile_permissions <- function(profileName, nextToken = NULL) {
op <- new_operation(
name = "ListProfilePermissions",
http_method = "GET",
http_path = "/signing-profiles/{profileName}/permissions",
paginator = list()
)
input <- .signer$list_profile_permissions_input(profileName = profileName, nextToken = nextToken)
output <- .signer$list_profile_permissions_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$list_profile_permissions <- signer_list_profile_permissions
signer_list_signing_jobs <- function(status = NULL, platformId = NULL, requestedBy = NULL, maxResults = NULL, nextToken = NULL, isRevoked = NULL, signatureExpiresBefore = NULL, signatureExpiresAfter = NULL, jobInvoker = NULL) {
op <- new_operation(
name = "ListSigningJobs",
http_method = "GET",
http_path = "/signing-jobs",
paginator = list()
)
input <- .signer$list_signing_jobs_input(status = status, platformId = platformId, requestedBy = requestedBy, maxResults = maxResults, nextToken = nextToken, isRevoked = isRevoked, signatureExpiresBefore = signatureExpiresBefore, signatureExpiresAfter = signatureExpiresAfter, jobInvoker = jobInvoker)
output <- .signer$list_signing_jobs_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$list_signing_jobs <- signer_list_signing_jobs
signer_list_signing_platforms <- function(category = NULL, partner = NULL, target = NULL, maxResults = NULL, nextToken = NULL) {
op <- new_operation(
name = "ListSigningPlatforms",
http_method = "GET",
http_path = "/signing-platforms",
paginator = list()
)
input <- .signer$list_signing_platforms_input(category = category, partner = partner, target = target, maxResults = maxResults, nextToken = nextToken)
output <- .signer$list_signing_platforms_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$list_signing_platforms <- signer_list_signing_platforms
signer_list_signing_profiles <- function(includeCanceled = NULL, maxResults = NULL, nextToken = NULL, platformId = NULL, statuses = NULL) {
op <- new_operation(
name = "ListSigningProfiles",
http_method = "GET",
http_path = "/signing-profiles",
paginator = list()
)
input <- .signer$list_signing_profiles_input(includeCanceled = includeCanceled, maxResults = maxResults, nextToken = nextToken, platformId = platformId, statuses = statuses)
output <- .signer$list_signing_profiles_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$list_signing_profiles <- signer_list_signing_profiles
signer_list_tags_for_resource <- function(resourceArn) {
op <- new_operation(
name = "ListTagsForResource",
http_method = "GET",
http_path = "/tags/{resourceArn}",
paginator = list()
)
input <- .signer$list_tags_for_resource_input(resourceArn = resourceArn)
output <- .signer$list_tags_for_resource_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$list_tags_for_resource <- signer_list_tags_for_resource
signer_put_signing_profile <- function(profileName, signingMaterial = NULL, signatureValidityPeriod = NULL, platformId, overrides = NULL, signingParameters = NULL, tags = NULL) {
op <- new_operation(
name = "PutSigningProfile",
http_method = "PUT",
http_path = "/signing-profiles/{profileName}",
paginator = list()
)
input <- .signer$put_signing_profile_input(profileName = profileName, signingMaterial = signingMaterial, signatureValidityPeriod = signatureValidityPeriod, platformId = platformId, overrides = overrides, signingParameters = signingParameters, tags = tags)
output <- .signer$put_signing_profile_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$put_signing_profile <- signer_put_signing_profile
signer_remove_profile_permission <- function(profileName, revisionId, statementId) {
op <- new_operation(
name = "RemoveProfilePermission",
http_method = "DELETE",
http_path = "/signing-profiles/{profileName}/permissions/{statementId}",
paginator = list()
)
input <- .signer$remove_profile_permission_input(profileName = profileName, revisionId = revisionId, statementId = statementId)
output <- .signer$remove_profile_permission_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$remove_profile_permission <- signer_remove_profile_permission
signer_revoke_signature <- function(jobId, jobOwner = NULL, reason) {
op <- new_operation(
name = "RevokeSignature",
http_method = "PUT",
http_path = "/signing-jobs/{jobId}/revoke",
paginator = list()
)
input <- .signer$revoke_signature_input(jobId = jobId, jobOwner = jobOwner, reason = reason)
output <- .signer$revoke_signature_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$revoke_signature <- signer_revoke_signature
signer_revoke_signing_profile <- function(profileName, profileVersion, reason, effectiveTime) {
op <- new_operation(
name = "RevokeSigningProfile",
http_method = "PUT",
http_path = "/signing-profiles/{profileName}/revoke",
paginator = list()
)
input <- .signer$revoke_signing_profile_input(profileName = profileName, profileVersion = profileVersion, reason = reason, effectiveTime = effectiveTime)
output <- .signer$revoke_signing_profile_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$revoke_signing_profile <- signer_revoke_signing_profile
signer_start_signing_job <- function(source, destination, profileName, clientRequestToken, profileOwner = NULL) {
op <- new_operation(
name = "StartSigningJob",
http_method = "POST",
http_path = "/signing-jobs",
paginator = list()
)
input <- .signer$start_signing_job_input(source = source, destination = destination, profileName = profileName, clientRequestToken = clientRequestToken, profileOwner = profileOwner)
output <- .signer$start_signing_job_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$start_signing_job <- signer_start_signing_job
signer_tag_resource <- function(resourceArn, tags) {
op <- new_operation(
name = "TagResource",
http_method = "POST",
http_path = "/tags/{resourceArn}",
paginator = list()
)
input <- .signer$tag_resource_input(resourceArn = resourceArn, tags = tags)
output <- .signer$tag_resource_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$tag_resource <- signer_tag_resource
signer_untag_resource <- function(resourceArn, tagKeys) {
op <- new_operation(
name = "UntagResource",
http_method = "DELETE",
http_path = "/tags/{resourceArn}",
paginator = list()
)
input <- .signer$untag_resource_input(resourceArn = resourceArn, tagKeys = tagKeys)
output <- .signer$untag_resource_output()
config <- get_config()
svc <- .signer$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.signer$operations$untag_resource <- signer_untag_resource |
set.seed(1)
knitr::opts_chunk$set(fig.width = 8, fig.height = 6)
library(GillespieSSA)
parms <- c(c = 1)
M <- 50
simName <- "Linear Chain System"
tf <- 5
x0 <- c(1000, rep(0, M))
names(x0) <- paste0("x", seq_len(M+1))
nu <- matrix(rep(0, M * (M+1)), ncol = M)
nu[cbind(seq_len(M), seq_len(M))] <- -1
nu[cbind(seq_len(M)+1, seq_len(M))] <- 1
a <- paste0("c*x", seq_len(M))
set.seed(1)
out <- ssa(
x0 = x0,
a = a,
nu = nu,
parms = parms,
tf = tf,
method = ssa.d(),
simName = simName,
verbose = FALSE,
consoleInterval = 1
)
ssa.plot(out, show.title = TRUE, show.legend = FALSE)
set.seed(1)
out <- ssa(
x0 = x0,
a = a,
nu = nu,
parms = parms,
tf = tf,
method = ssa.etl(tau = .1),
simName = simName,
verbose = FALSE,
consoleInterval = 1
)
ssa.plot(out, show.title = TRUE, show.legend = FALSE)
set.seed(1)
out <- ssa(
x0 = x0,
a = a,
nu = nu,
parms = parms,
tf = tf,
method = ssa.btl(f = 50),
simName = simName,
verbose = FALSE,
consoleInterval = 1
)
ssa.plot(out, show.title = TRUE, show.legend = FALSE)
set.seed(1)
out <- ssa(
x0 = x0,
a = a,
nu = nu,
parms = parms,
tf = tf,
method = ssa.otl(),
simName = simName,
verbose = FALSE,
consoleInterval = 1
)
ssa.plot(out, show.title = TRUE, show.legend = FALSE) |
calculate_level_vector = function(design, model, nointercept) {
factornames = attr(terms(model), "term.labels")
factormatrix = attr(terms(model), "factors")
interactionterms = factornames[apply(factormatrix, 2, sum) > 1]
higherorderterms = factornames[!(gsub("`", "", factornames, fixed = TRUE) %in% colnames(design)) &
!(apply(factormatrix, 2, sum) > 1)]
levelvector = sapply(lapply(design, unique), length)
levelvector[lapply(design, class) == "numeric"] = 2
if (!nointercept) {
levelvector = c(1, levelvector - 1)
} else {
levelvector = levelvector - 1
for (i in 1:ncol(design)) {
if (class(design[, i]) %in% c("character", "factor")) {
levelvector[i] = levelvector[i] + 1
break
}
}
}
higherorderlevelvector = rep(1, length(higherorderterms))
names(higherorderlevelvector) = higherorderterms
levelvector = c(levelvector, higherorderlevelvector)
for (interaction in interactionterms) {
numberlevels = 1
for (term in unlist(strsplit(interaction, split = "(\\s+)?:(\\s+)?|(\\s+)?\\*(\\s+)?"))) {
numberlevels = numberlevels * levelvector[gsub("`", "", term, fixed = TRUE)]
}
levelvector = c(levelvector, numberlevels)
}
levelnames = names(levelvector)
if(length(interactionterms) > 0) {
levelnames[(length(levelnames)-length(interactionterms)+1):length(levelnames)] = interactionterms
}
levelvector = stats::setNames(levelvector, levelnames)
levelvector
} |
NULL
.apigatewayv2$create_api_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiKeySelectionExpression = structure(logical(0), tags = list(locationName = "apiKeySelectionExpression", type = "string")), CorsConfiguration = structure(list(AllowCredentials = structure(logical(0), tags = list(locationName = "allowCredentials", type = "boolean")), AllowHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowHeaders", type = "list")), AllowMethods = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowMethods", type = "list")), AllowOrigins = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowOrigins", type = "list")), ExposeHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "exposeHeaders", type = "list")), MaxAge = structure(logical(0), tags = list(locationName = "maxAge", type = "integer"))), tags = list(locationName = "corsConfiguration", type = "structure")), CredentialsArn = structure(logical(0), tags = list(locationName = "credentialsArn", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), DisableSchemaValidation = structure(logical(0), tags = list(locationName = "disableSchemaValidation", type = "boolean")), DisableExecuteApiEndpoint = structure(logical(0), tags = list(locationName = "disableExecuteApiEndpoint", type = "boolean")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), ProtocolType = structure(logical(0), tags = list(locationName = "protocolType", type = "string")), RouteKey = structure(logical(0), tags = list(locationName = "routeKey", type = "string")), RouteSelectionExpression = structure(logical(0), tags = list(locationName = "routeSelectionExpression", type = "string")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map")), Target = structure(logical(0), tags = list(locationName = "target", type = "string")), Version = structure(logical(0), tags = list(locationName = "version", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_api_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiEndpoint = structure(logical(0), tags = list(locationName = "apiEndpoint", type = "string")), ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ApiId = structure(logical(0), tags = list(locationName = "apiId", type = "string")), ApiKeySelectionExpression = structure(logical(0), tags = list(locationName = "apiKeySelectionExpression", type = "string")), CorsConfiguration = structure(list(AllowCredentials = structure(logical(0), tags = list(locationName = "allowCredentials", type = "boolean")), AllowHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowHeaders", type = "list")), AllowMethods = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowMethods", type = "list")), AllowOrigins = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowOrigins", type = "list")), ExposeHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "exposeHeaders", type = "list")), MaxAge = structure(logical(0), tags = list(locationName = "maxAge", type = "integer"))), tags = list(locationName = "corsConfiguration", type = "structure")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), DisableSchemaValidation = structure(logical(0), tags = list(locationName = "disableSchemaValidation", type = "boolean")), DisableExecuteApiEndpoint = structure(logical(0), tags = list(locationName = "disableExecuteApiEndpoint", type = "boolean")), ImportInfo = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "importInfo", type = "list")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), ProtocolType = structure(logical(0), tags = list(locationName = "protocolType", type = "string")), RouteSelectionExpression = structure(logical(0), tags = list(locationName = "routeSelectionExpression", type = "string")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map")), Version = structure(logical(0), tags = list(locationName = "version", type = "string")), Warnings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "warnings", type = "list"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_api_mapping_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(locationName = "apiId", type = "string")), ApiMappingKey = structure(logical(0), tags = list(locationName = "apiMappingKey", type = "string")), DomainName = structure(logical(0), tags = list(location = "uri", locationName = "domainName", type = "string")), Stage = structure(logical(0), tags = list(locationName = "stage", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_api_mapping_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(locationName = "apiId", type = "string")), ApiMappingId = structure(logical(0), tags = list(locationName = "apiMappingId", type = "string")), ApiMappingKey = structure(logical(0), tags = list(locationName = "apiMappingKey", type = "string")), Stage = structure(logical(0), tags = list(locationName = "stage", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_authorizer_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), AuthorizerCredentialsArn = structure(logical(0), tags = list(locationName = "authorizerCredentialsArn", type = "string")), AuthorizerPayloadFormatVersion = structure(logical(0), tags = list(locationName = "authorizerPayloadFormatVersion", type = "string")), AuthorizerResultTtlInSeconds = structure(logical(0), tags = list(locationName = "authorizerResultTtlInSeconds", type = "integer")), AuthorizerType = structure(logical(0), tags = list(locationName = "authorizerType", type = "string")), AuthorizerUri = structure(logical(0), tags = list(locationName = "authorizerUri", type = "string")), EnableSimpleResponses = structure(logical(0), tags = list(locationName = "enableSimpleResponses", type = "boolean")), IdentitySource = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "identitySource", type = "list")), IdentityValidationExpression = structure(logical(0), tags = list(locationName = "identityValidationExpression", type = "string")), JwtConfiguration = structure(list(Audience = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "audience", type = "list")), Issuer = structure(logical(0), tags = list(locationName = "issuer", type = "string"))), tags = list(locationName = "jwtConfiguration", type = "structure")), Name = structure(logical(0), tags = list(locationName = "name", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_authorizer_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(AuthorizerCredentialsArn = structure(logical(0), tags = list(locationName = "authorizerCredentialsArn", type = "string")), AuthorizerId = structure(logical(0), tags = list(locationName = "authorizerId", type = "string")), AuthorizerPayloadFormatVersion = structure(logical(0), tags = list(locationName = "authorizerPayloadFormatVersion", type = "string")), AuthorizerResultTtlInSeconds = structure(logical(0), tags = list(locationName = "authorizerResultTtlInSeconds", type = "integer")), AuthorizerType = structure(logical(0), tags = list(locationName = "authorizerType", type = "string")), AuthorizerUri = structure(logical(0), tags = list(locationName = "authorizerUri", type = "string")), EnableSimpleResponses = structure(logical(0), tags = list(locationName = "enableSimpleResponses", type = "boolean")), IdentitySource = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "identitySource", type = "list")), IdentityValidationExpression = structure(logical(0), tags = list(locationName = "identityValidationExpression", type = "string")), JwtConfiguration = structure(list(Audience = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "audience", type = "list")), Issuer = structure(logical(0), tags = list(locationName = "issuer", type = "string"))), tags = list(locationName = "jwtConfiguration", type = "structure")), Name = structure(logical(0), tags = list(locationName = "name", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_deployment_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), StageName = structure(logical(0), tags = list(locationName = "stageName", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_deployment_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(AutoDeployed = structure(logical(0), tags = list(locationName = "autoDeployed", type = "boolean")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), DeploymentId = structure(logical(0), tags = list(locationName = "deploymentId", type = "string")), DeploymentStatus = structure(logical(0), tags = list(locationName = "deploymentStatus", type = "string")), DeploymentStatusMessage = structure(logical(0), tags = list(locationName = "deploymentStatusMessage", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_domain_name_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(DomainName = structure(logical(0), tags = list(locationName = "domainName", type = "string")), DomainNameConfigurations = structure(list(structure(list(ApiGatewayDomainName = structure(logical(0), tags = list(locationName = "apiGatewayDomainName", type = "string")), CertificateArn = structure(logical(0), tags = list(locationName = "certificateArn", type = "string")), CertificateName = structure(logical(0), tags = list(locationName = "certificateName", type = "string")), CertificateUploadDate = structure(logical(0), tags = list(locationName = "certificateUploadDate", type = "timestamp", timestampFormat = "iso8601")), DomainNameStatus = structure(logical(0), tags = list(locationName = "domainNameStatus", type = "string")), DomainNameStatusMessage = structure(logical(0), tags = list(locationName = "domainNameStatusMessage", type = "string")), EndpointType = structure(logical(0), tags = list(locationName = "endpointType", type = "string")), HostedZoneId = structure(logical(0), tags = list(locationName = "hostedZoneId", type = "string")), SecurityPolicy = structure(logical(0), tags = list(locationName = "securityPolicy", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "domainNameConfigurations", type = "list")), MutualTlsAuthentication = structure(list(TruststoreUri = structure(logical(0), tags = list(locationName = "truststoreUri", type = "string")), TruststoreVersion = structure(logical(0), tags = list(locationName = "truststoreVersion", type = "string"))), tags = list(locationName = "mutualTlsAuthentication", type = "structure")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_domain_name_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiMappingSelectionExpression = structure(logical(0), tags = list(locationName = "apiMappingSelectionExpression", type = "string")), DomainName = structure(logical(0), tags = list(locationName = "domainName", type = "string")), DomainNameConfigurations = structure(list(structure(list(ApiGatewayDomainName = structure(logical(0), tags = list(locationName = "apiGatewayDomainName", type = "string")), CertificateArn = structure(logical(0), tags = list(locationName = "certificateArn", type = "string")), CertificateName = structure(logical(0), tags = list(locationName = "certificateName", type = "string")), CertificateUploadDate = structure(logical(0), tags = list(locationName = "certificateUploadDate", type = "timestamp", timestampFormat = "iso8601")), DomainNameStatus = structure(logical(0), tags = list(locationName = "domainNameStatus", type = "string")), DomainNameStatusMessage = structure(logical(0), tags = list(locationName = "domainNameStatusMessage", type = "string")), EndpointType = structure(logical(0), tags = list(locationName = "endpointType", type = "string")), HostedZoneId = structure(logical(0), tags = list(locationName = "hostedZoneId", type = "string")), SecurityPolicy = structure(logical(0), tags = list(locationName = "securityPolicy", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "domainNameConfigurations", type = "list")), MutualTlsAuthentication = structure(list(TruststoreUri = structure(logical(0), tags = list(locationName = "truststoreUri", type = "string")), TruststoreVersion = structure(logical(0), tags = list(locationName = "truststoreVersion", type = "string")), TruststoreWarnings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "truststoreWarnings", type = "list"))), tags = list(locationName = "mutualTlsAuthentication", type = "structure")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_integration_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ConnectionId = structure(logical(0), tags = list(locationName = "connectionId", type = "string")), ConnectionType = structure(logical(0), tags = list(locationName = "connectionType", type = "string")), ContentHandlingStrategy = structure(logical(0), tags = list(locationName = "contentHandlingStrategy", type = "string")), CredentialsArn = structure(logical(0), tags = list(locationName = "credentialsArn", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), IntegrationMethod = structure(logical(0), tags = list(locationName = "integrationMethod", type = "string")), IntegrationSubtype = structure(logical(0), tags = list(locationName = "integrationSubtype", type = "string")), IntegrationType = structure(logical(0), tags = list(locationName = "integrationType", type = "string")), IntegrationUri = structure(logical(0), tags = list(locationName = "integrationUri", type = "string")), PassthroughBehavior = structure(logical(0), tags = list(locationName = "passthroughBehavior", type = "string")), PayloadFormatVersion = structure(logical(0), tags = list(locationName = "payloadFormatVersion", type = "string")), RequestParameters = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestParameters", type = "map")), RequestTemplates = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestTemplates", type = "map")), ResponseParameters = structure(list(structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(locationName = "responseParameters", type = "map")), TemplateSelectionExpression = structure(logical(0), tags = list(locationName = "templateSelectionExpression", type = "string")), TimeoutInMillis = structure(logical(0), tags = list(locationName = "timeoutInMillis", type = "integer")), TlsConfig = structure(list(ServerNameToVerify = structure(logical(0), tags = list(locationName = "serverNameToVerify", type = "string"))), tags = list(locationName = "tlsConfig", type = "structure"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_integration_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ConnectionId = structure(logical(0), tags = list(locationName = "connectionId", type = "string")), ConnectionType = structure(logical(0), tags = list(locationName = "connectionType", type = "string")), ContentHandlingStrategy = structure(logical(0), tags = list(locationName = "contentHandlingStrategy", type = "string")), CredentialsArn = structure(logical(0), tags = list(locationName = "credentialsArn", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), IntegrationId = structure(logical(0), tags = list(locationName = "integrationId", type = "string")), IntegrationMethod = structure(logical(0), tags = list(locationName = "integrationMethod", type = "string")), IntegrationResponseSelectionExpression = structure(logical(0), tags = list(locationName = "integrationResponseSelectionExpression", type = "string")), IntegrationSubtype = structure(logical(0), tags = list(locationName = "integrationSubtype", type = "string")), IntegrationType = structure(logical(0), tags = list(locationName = "integrationType", type = "string")), IntegrationUri = structure(logical(0), tags = list(locationName = "integrationUri", type = "string")), PassthroughBehavior = structure(logical(0), tags = list(locationName = "passthroughBehavior", type = "string")), PayloadFormatVersion = structure(logical(0), tags = list(locationName = "payloadFormatVersion", type = "string")), RequestParameters = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestParameters", type = "map")), RequestTemplates = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestTemplates", type = "map")), ResponseParameters = structure(list(structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(locationName = "responseParameters", type = "map")), TemplateSelectionExpression = structure(logical(0), tags = list(locationName = "templateSelectionExpression", type = "string")), TimeoutInMillis = structure(logical(0), tags = list(locationName = "timeoutInMillis", type = "integer")), TlsConfig = structure(list(ServerNameToVerify = structure(logical(0), tags = list(locationName = "serverNameToVerify", type = "string"))), tags = list(locationName = "tlsConfig", type = "structure"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_integration_response_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ContentHandlingStrategy = structure(logical(0), tags = list(locationName = "contentHandlingStrategy", type = "string")), IntegrationId = structure(logical(0), tags = list(location = "uri", locationName = "integrationId", type = "string")), IntegrationResponseKey = structure(logical(0), tags = list(locationName = "integrationResponseKey", type = "string")), ResponseParameters = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseParameters", type = "map")), ResponseTemplates = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseTemplates", type = "map")), TemplateSelectionExpression = structure(logical(0), tags = list(locationName = "templateSelectionExpression", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_integration_response_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ContentHandlingStrategy = structure(logical(0), tags = list(locationName = "contentHandlingStrategy", type = "string")), IntegrationResponseId = structure(logical(0), tags = list(locationName = "integrationResponseId", type = "string")), IntegrationResponseKey = structure(logical(0), tags = list(locationName = "integrationResponseKey", type = "string")), ResponseParameters = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseParameters", type = "map")), ResponseTemplates = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseTemplates", type = "map")), TemplateSelectionExpression = structure(logical(0), tags = list(locationName = "templateSelectionExpression", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_model_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ContentType = structure(logical(0), tags = list(locationName = "contentType", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), Schema = structure(logical(0), tags = list(locationName = "schema", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_model_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ContentType = structure(logical(0), tags = list(locationName = "contentType", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), ModelId = structure(logical(0), tags = list(locationName = "modelId", type = "string")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), Schema = structure(logical(0), tags = list(locationName = "schema", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_route_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ApiKeyRequired = structure(logical(0), tags = list(locationName = "apiKeyRequired", type = "boolean")), AuthorizationScopes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "authorizationScopes", type = "list")), AuthorizationType = structure(logical(0), tags = list(locationName = "authorizationType", type = "string")), AuthorizerId = structure(logical(0), tags = list(locationName = "authorizerId", type = "string")), ModelSelectionExpression = structure(logical(0), tags = list(locationName = "modelSelectionExpression", type = "string")), OperationName = structure(logical(0), tags = list(locationName = "operationName", type = "string")), RequestModels = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestModels", type = "map")), RequestParameters = structure(list(structure(list(Required = structure(logical(0), tags = list(locationName = "required", type = "boolean"))), tags = list(type = "structure"))), tags = list(locationName = "requestParameters", type = "map")), RouteKey = structure(logical(0), tags = list(locationName = "routeKey", type = "string")), RouteResponseSelectionExpression = structure(logical(0), tags = list(locationName = "routeResponseSelectionExpression", type = "string")), Target = structure(logical(0), tags = list(locationName = "target", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_route_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ApiKeyRequired = structure(logical(0), tags = list(locationName = "apiKeyRequired", type = "boolean")), AuthorizationScopes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "authorizationScopes", type = "list")), AuthorizationType = structure(logical(0), tags = list(locationName = "authorizationType", type = "string")), AuthorizerId = structure(logical(0), tags = list(locationName = "authorizerId", type = "string")), ModelSelectionExpression = structure(logical(0), tags = list(locationName = "modelSelectionExpression", type = "string")), OperationName = structure(logical(0), tags = list(locationName = "operationName", type = "string")), RequestModels = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestModels", type = "map")), RequestParameters = structure(list(structure(list(Required = structure(logical(0), tags = list(locationName = "required", type = "boolean"))), tags = list(type = "structure"))), tags = list(locationName = "requestParameters", type = "map")), RouteId = structure(logical(0), tags = list(locationName = "routeId", type = "string")), RouteKey = structure(logical(0), tags = list(locationName = "routeKey", type = "string")), RouteResponseSelectionExpression = structure(logical(0), tags = list(locationName = "routeResponseSelectionExpression", type = "string")), Target = structure(logical(0), tags = list(locationName = "target", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_route_response_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ModelSelectionExpression = structure(logical(0), tags = list(locationName = "modelSelectionExpression", type = "string")), ResponseModels = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseModels", type = "map")), ResponseParameters = structure(list(structure(list(Required = structure(logical(0), tags = list(locationName = "required", type = "boolean"))), tags = list(type = "structure"))), tags = list(locationName = "responseParameters", type = "map")), RouteId = structure(logical(0), tags = list(location = "uri", locationName = "routeId", type = "string")), RouteResponseKey = structure(logical(0), tags = list(locationName = "routeResponseKey", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_route_response_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ModelSelectionExpression = structure(logical(0), tags = list(locationName = "modelSelectionExpression", type = "string")), ResponseModels = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseModels", type = "map")), ResponseParameters = structure(list(structure(list(Required = structure(logical(0), tags = list(locationName = "required", type = "boolean"))), tags = list(type = "structure"))), tags = list(locationName = "responseParameters", type = "map")), RouteResponseId = structure(logical(0), tags = list(locationName = "routeResponseId", type = "string")), RouteResponseKey = structure(logical(0), tags = list(locationName = "routeResponseKey", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_stage_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(AccessLogSettings = structure(list(DestinationArn = structure(logical(0), tags = list(locationName = "destinationArn", type = "string")), Format = structure(logical(0), tags = list(locationName = "format", type = "string"))), tags = list(locationName = "accessLogSettings", type = "structure")), ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), AutoDeploy = structure(logical(0), tags = list(locationName = "autoDeploy", type = "boolean")), ClientCertificateId = structure(logical(0), tags = list(locationName = "clientCertificateId", type = "string")), DefaultRouteSettings = structure(list(DataTraceEnabled = structure(logical(0), tags = list(locationName = "dataTraceEnabled", type = "boolean")), DetailedMetricsEnabled = structure(logical(0), tags = list(locationName = "detailedMetricsEnabled", type = "boolean")), LoggingLevel = structure(logical(0), tags = list(locationName = "loggingLevel", type = "string")), ThrottlingBurstLimit = structure(logical(0), tags = list(locationName = "throttlingBurstLimit", type = "integer")), ThrottlingRateLimit = structure(logical(0), tags = list(locationName = "throttlingRateLimit", type = "double"))), tags = list(locationName = "defaultRouteSettings", type = "structure")), DeploymentId = structure(logical(0), tags = list(locationName = "deploymentId", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), RouteSettings = structure(list(structure(list(DataTraceEnabled = structure(logical(0), tags = list(locationName = "dataTraceEnabled", type = "boolean")), DetailedMetricsEnabled = structure(logical(0), tags = list(locationName = "detailedMetricsEnabled", type = "boolean")), LoggingLevel = structure(logical(0), tags = list(locationName = "loggingLevel", type = "string")), ThrottlingBurstLimit = structure(logical(0), tags = list(locationName = "throttlingBurstLimit", type = "integer")), ThrottlingRateLimit = structure(logical(0), tags = list(locationName = "throttlingRateLimit", type = "double"))), tags = list(type = "structure"))), tags = list(locationName = "routeSettings", type = "map")), StageName = structure(logical(0), tags = list(locationName = "stageName", type = "string")), StageVariables = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "stageVariables", type = "map")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_stage_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(AccessLogSettings = structure(list(DestinationArn = structure(logical(0), tags = list(locationName = "destinationArn", type = "string")), Format = structure(logical(0), tags = list(locationName = "format", type = "string"))), tags = list(locationName = "accessLogSettings", type = "structure")), ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), AutoDeploy = structure(logical(0), tags = list(locationName = "autoDeploy", type = "boolean")), ClientCertificateId = structure(logical(0), tags = list(locationName = "clientCertificateId", type = "string")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), DefaultRouteSettings = structure(list(DataTraceEnabled = structure(logical(0), tags = list(locationName = "dataTraceEnabled", type = "boolean")), DetailedMetricsEnabled = structure(logical(0), tags = list(locationName = "detailedMetricsEnabled", type = "boolean")), LoggingLevel = structure(logical(0), tags = list(locationName = "loggingLevel", type = "string")), ThrottlingBurstLimit = structure(logical(0), tags = list(locationName = "throttlingBurstLimit", type = "integer")), ThrottlingRateLimit = structure(logical(0), tags = list(locationName = "throttlingRateLimit", type = "double"))), tags = list(locationName = "defaultRouteSettings", type = "structure")), DeploymentId = structure(logical(0), tags = list(locationName = "deploymentId", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), LastDeploymentStatusMessage = structure(logical(0), tags = list(locationName = "lastDeploymentStatusMessage", type = "string")), LastUpdatedDate = structure(logical(0), tags = list(locationName = "lastUpdatedDate", type = "timestamp", timestampFormat = "iso8601")), RouteSettings = structure(list(structure(list(DataTraceEnabled = structure(logical(0), tags = list(locationName = "dataTraceEnabled", type = "boolean")), DetailedMetricsEnabled = structure(logical(0), tags = list(locationName = "detailedMetricsEnabled", type = "boolean")), LoggingLevel = structure(logical(0), tags = list(locationName = "loggingLevel", type = "string")), ThrottlingBurstLimit = structure(logical(0), tags = list(locationName = "throttlingBurstLimit", type = "integer")), ThrottlingRateLimit = structure(logical(0), tags = list(locationName = "throttlingRateLimit", type = "double"))), tags = list(type = "structure"))), tags = list(locationName = "routeSettings", type = "map")), StageName = structure(logical(0), tags = list(locationName = "stageName", type = "string")), StageVariables = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "stageVariables", type = "map")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_vpc_link_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Name = structure(logical(0), tags = list(locationName = "name", type = "string")), SecurityGroupIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "securityGroupIds", type = "list")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "subnetIds", type = "list")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$create_vpc_link_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), SecurityGroupIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "securityGroupIds", type = "list")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "subnetIds", type = "list")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map")), VpcLinkId = structure(logical(0), tags = list(locationName = "vpcLinkId", type = "string")), VpcLinkStatus = structure(logical(0), tags = list(locationName = "vpcLinkStatus", type = "string")), VpcLinkStatusMessage = structure(logical(0), tags = list(locationName = "vpcLinkStatusMessage", type = "string")), VpcLinkVersion = structure(logical(0), tags = list(locationName = "vpcLinkVersion", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_access_log_settings_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), StageName = structure(logical(0), tags = list(location = "uri", locationName = "stageName", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_access_log_settings_output <- function(...) {
list()
}
.apigatewayv2$delete_api_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_api_output <- function(...) {
list()
}
.apigatewayv2$delete_api_mapping_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiMappingId = structure(logical(0), tags = list(location = "uri", locationName = "apiMappingId", type = "string")), DomainName = structure(logical(0), tags = list(location = "uri", locationName = "domainName", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_api_mapping_output <- function(...) {
list()
}
.apigatewayv2$delete_authorizer_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), AuthorizerId = structure(logical(0), tags = list(location = "uri", locationName = "authorizerId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_authorizer_output <- function(...) {
list()
}
.apigatewayv2$delete_cors_configuration_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_cors_configuration_output <- function(...) {
list()
}
.apigatewayv2$delete_deployment_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), DeploymentId = structure(logical(0), tags = list(location = "uri", locationName = "deploymentId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_deployment_output <- function(...) {
list()
}
.apigatewayv2$delete_domain_name_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(DomainName = structure(logical(0), tags = list(location = "uri", locationName = "domainName", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_domain_name_output <- function(...) {
list()
}
.apigatewayv2$delete_integration_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), IntegrationId = structure(logical(0), tags = list(location = "uri", locationName = "integrationId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_integration_output <- function(...) {
list()
}
.apigatewayv2$delete_integration_response_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), IntegrationId = structure(logical(0), tags = list(location = "uri", locationName = "integrationId", type = "string")), IntegrationResponseId = structure(logical(0), tags = list(location = "uri", locationName = "integrationResponseId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_integration_response_output <- function(...) {
list()
}
.apigatewayv2$delete_model_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ModelId = structure(logical(0), tags = list(location = "uri", locationName = "modelId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_model_output <- function(...) {
list()
}
.apigatewayv2$delete_route_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), RouteId = structure(logical(0), tags = list(location = "uri", locationName = "routeId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_route_output <- function(...) {
list()
}
.apigatewayv2$delete_route_request_parameter_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), RequestParameterKey = structure(logical(0), tags = list(location = "uri", locationName = "requestParameterKey", type = "string")), RouteId = structure(logical(0), tags = list(location = "uri", locationName = "routeId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_route_request_parameter_output <- function(...) {
list()
}
.apigatewayv2$delete_route_response_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), RouteId = structure(logical(0), tags = list(location = "uri", locationName = "routeId", type = "string")), RouteResponseId = structure(logical(0), tags = list(location = "uri", locationName = "routeResponseId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_route_response_output <- function(...) {
list()
}
.apigatewayv2$delete_route_settings_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), RouteKey = structure(logical(0), tags = list(location = "uri", locationName = "routeKey", type = "string")), StageName = structure(logical(0), tags = list(location = "uri", locationName = "stageName", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_route_settings_output <- function(...) {
list()
}
.apigatewayv2$delete_stage_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), StageName = structure(logical(0), tags = list(location = "uri", locationName = "stageName", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_stage_output <- function(...) {
list()
}
.apigatewayv2$delete_vpc_link_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(VpcLinkId = structure(logical(0), tags = list(location = "uri", locationName = "vpcLinkId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$delete_vpc_link_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$export_api_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ExportVersion = structure(logical(0), tags = list(location = "querystring", locationName = "exportVersion", type = "string")), IncludeExtensions = structure(logical(0), tags = list(location = "querystring", locationName = "includeExtensions", type = "boolean")), OutputType = structure(logical(0), tags = list(location = "querystring", locationName = "outputType", type = "string")), Specification = structure(logical(0), tags = list(location = "uri", locationName = "specification", type = "string")), StageName = structure(logical(0), tags = list(location = "querystring", locationName = "stageName", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$export_api_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(body = structure(logical(0), tags = list(type = "blob"))), tags = list(type = "structure", payload = "body"))
return(populate(args, shape))
}
.apigatewayv2$reset_authorizers_cache_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), StageName = structure(logical(0), tags = list(location = "uri", locationName = "stageName", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$reset_authorizers_cache_output <- function(...) {
list()
}
.apigatewayv2$get_api_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_api_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiEndpoint = structure(logical(0), tags = list(locationName = "apiEndpoint", type = "string")), ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ApiId = structure(logical(0), tags = list(locationName = "apiId", type = "string")), ApiKeySelectionExpression = structure(logical(0), tags = list(locationName = "apiKeySelectionExpression", type = "string")), CorsConfiguration = structure(list(AllowCredentials = structure(logical(0), tags = list(locationName = "allowCredentials", type = "boolean")), AllowHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowHeaders", type = "list")), AllowMethods = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowMethods", type = "list")), AllowOrigins = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowOrigins", type = "list")), ExposeHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "exposeHeaders", type = "list")), MaxAge = structure(logical(0), tags = list(locationName = "maxAge", type = "integer"))), tags = list(locationName = "corsConfiguration", type = "structure")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), DisableSchemaValidation = structure(logical(0), tags = list(locationName = "disableSchemaValidation", type = "boolean")), DisableExecuteApiEndpoint = structure(logical(0), tags = list(locationName = "disableExecuteApiEndpoint", type = "boolean")), ImportInfo = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "importInfo", type = "list")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), ProtocolType = structure(logical(0), tags = list(locationName = "protocolType", type = "string")), RouteSelectionExpression = structure(logical(0), tags = list(locationName = "routeSelectionExpression", type = "string")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map")), Version = structure(logical(0), tags = list(locationName = "version", type = "string")), Warnings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "warnings", type = "list"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_api_mapping_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiMappingId = structure(logical(0), tags = list(location = "uri", locationName = "apiMappingId", type = "string")), DomainName = structure(logical(0), tags = list(location = "uri", locationName = "domainName", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_api_mapping_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(locationName = "apiId", type = "string")), ApiMappingId = structure(logical(0), tags = list(locationName = "apiMappingId", type = "string")), ApiMappingKey = structure(logical(0), tags = list(locationName = "apiMappingKey", type = "string")), Stage = structure(logical(0), tags = list(locationName = "stage", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_api_mappings_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(DomainName = structure(logical(0), tags = list(location = "uri", locationName = "domainName", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_api_mappings_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Items = structure(list(structure(list(ApiId = structure(logical(0), tags = list(locationName = "apiId", type = "string")), ApiMappingId = structure(logical(0), tags = list(locationName = "apiMappingId", type = "string")), ApiMappingKey = structure(logical(0), tags = list(locationName = "apiMappingKey", type = "string")), Stage = structure(logical(0), tags = list(locationName = "stage", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "items", type = "list")), NextToken = structure(logical(0), tags = list(locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_apis_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_apis_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Items = structure(list(structure(list(ApiEndpoint = structure(logical(0), tags = list(locationName = "apiEndpoint", type = "string")), ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ApiId = structure(logical(0), tags = list(locationName = "apiId", type = "string")), ApiKeySelectionExpression = structure(logical(0), tags = list(locationName = "apiKeySelectionExpression", type = "string")), CorsConfiguration = structure(list(AllowCredentials = structure(logical(0), tags = list(locationName = "allowCredentials", type = "boolean")), AllowHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowHeaders", type = "list")), AllowMethods = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowMethods", type = "list")), AllowOrigins = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowOrigins", type = "list")), ExposeHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "exposeHeaders", type = "list")), MaxAge = structure(logical(0), tags = list(locationName = "maxAge", type = "integer"))), tags = list(locationName = "corsConfiguration", type = "structure")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), DisableSchemaValidation = structure(logical(0), tags = list(locationName = "disableSchemaValidation", type = "boolean")), DisableExecuteApiEndpoint = structure(logical(0), tags = list(locationName = "disableExecuteApiEndpoint", type = "boolean")), ImportInfo = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "importInfo", type = "list")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), ProtocolType = structure(logical(0), tags = list(locationName = "protocolType", type = "string")), RouteSelectionExpression = structure(logical(0), tags = list(locationName = "routeSelectionExpression", type = "string")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map")), Version = structure(logical(0), tags = list(locationName = "version", type = "string")), Warnings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "warnings", type = "list"))), tags = list(type = "structure"))), tags = list(locationName = "items", type = "list")), NextToken = structure(logical(0), tags = list(locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_authorizer_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), AuthorizerId = structure(logical(0), tags = list(location = "uri", locationName = "authorizerId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_authorizer_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(AuthorizerCredentialsArn = structure(logical(0), tags = list(locationName = "authorizerCredentialsArn", type = "string")), AuthorizerId = structure(logical(0), tags = list(locationName = "authorizerId", type = "string")), AuthorizerPayloadFormatVersion = structure(logical(0), tags = list(locationName = "authorizerPayloadFormatVersion", type = "string")), AuthorizerResultTtlInSeconds = structure(logical(0), tags = list(locationName = "authorizerResultTtlInSeconds", type = "integer")), AuthorizerType = structure(logical(0), tags = list(locationName = "authorizerType", type = "string")), AuthorizerUri = structure(logical(0), tags = list(locationName = "authorizerUri", type = "string")), EnableSimpleResponses = structure(logical(0), tags = list(locationName = "enableSimpleResponses", type = "boolean")), IdentitySource = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "identitySource", type = "list")), IdentityValidationExpression = structure(logical(0), tags = list(locationName = "identityValidationExpression", type = "string")), JwtConfiguration = structure(list(Audience = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "audience", type = "list")), Issuer = structure(logical(0), tags = list(locationName = "issuer", type = "string"))), tags = list(locationName = "jwtConfiguration", type = "structure")), Name = structure(logical(0), tags = list(locationName = "name", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_authorizers_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_authorizers_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Items = structure(list(structure(list(AuthorizerCredentialsArn = structure(logical(0), tags = list(locationName = "authorizerCredentialsArn", type = "string")), AuthorizerId = structure(logical(0), tags = list(locationName = "authorizerId", type = "string")), AuthorizerPayloadFormatVersion = structure(logical(0), tags = list(locationName = "authorizerPayloadFormatVersion", type = "string")), AuthorizerResultTtlInSeconds = structure(logical(0), tags = list(locationName = "authorizerResultTtlInSeconds", type = "integer")), AuthorizerType = structure(logical(0), tags = list(locationName = "authorizerType", type = "string")), AuthorizerUri = structure(logical(0), tags = list(locationName = "authorizerUri", type = "string")), EnableSimpleResponses = structure(logical(0), tags = list(locationName = "enableSimpleResponses", type = "boolean")), IdentitySource = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "identitySource", type = "list")), IdentityValidationExpression = structure(logical(0), tags = list(locationName = "identityValidationExpression", type = "string")), JwtConfiguration = structure(list(Audience = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "audience", type = "list")), Issuer = structure(logical(0), tags = list(locationName = "issuer", type = "string"))), tags = list(locationName = "jwtConfiguration", type = "structure")), Name = structure(logical(0), tags = list(locationName = "name", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "items", type = "list")), NextToken = structure(logical(0), tags = list(locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_deployment_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), DeploymentId = structure(logical(0), tags = list(location = "uri", locationName = "deploymentId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_deployment_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(AutoDeployed = structure(logical(0), tags = list(locationName = "autoDeployed", type = "boolean")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), DeploymentId = structure(logical(0), tags = list(locationName = "deploymentId", type = "string")), DeploymentStatus = structure(logical(0), tags = list(locationName = "deploymentStatus", type = "string")), DeploymentStatusMessage = structure(logical(0), tags = list(locationName = "deploymentStatusMessage", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_deployments_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_deployments_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Items = structure(list(structure(list(AutoDeployed = structure(logical(0), tags = list(locationName = "autoDeployed", type = "boolean")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), DeploymentId = structure(logical(0), tags = list(locationName = "deploymentId", type = "string")), DeploymentStatus = structure(logical(0), tags = list(locationName = "deploymentStatus", type = "string")), DeploymentStatusMessage = structure(logical(0), tags = list(locationName = "deploymentStatusMessage", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "items", type = "list")), NextToken = structure(logical(0), tags = list(locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_domain_name_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(DomainName = structure(logical(0), tags = list(location = "uri", locationName = "domainName", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_domain_name_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiMappingSelectionExpression = structure(logical(0), tags = list(locationName = "apiMappingSelectionExpression", type = "string")), DomainName = structure(logical(0), tags = list(locationName = "domainName", type = "string")), DomainNameConfigurations = structure(list(structure(list(ApiGatewayDomainName = structure(logical(0), tags = list(locationName = "apiGatewayDomainName", type = "string")), CertificateArn = structure(logical(0), tags = list(locationName = "certificateArn", type = "string")), CertificateName = structure(logical(0), tags = list(locationName = "certificateName", type = "string")), CertificateUploadDate = structure(logical(0), tags = list(locationName = "certificateUploadDate", type = "timestamp", timestampFormat = "iso8601")), DomainNameStatus = structure(logical(0), tags = list(locationName = "domainNameStatus", type = "string")), DomainNameStatusMessage = structure(logical(0), tags = list(locationName = "domainNameStatusMessage", type = "string")), EndpointType = structure(logical(0), tags = list(locationName = "endpointType", type = "string")), HostedZoneId = structure(logical(0), tags = list(locationName = "hostedZoneId", type = "string")), SecurityPolicy = structure(logical(0), tags = list(locationName = "securityPolicy", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "domainNameConfigurations", type = "list")), MutualTlsAuthentication = structure(list(TruststoreUri = structure(logical(0), tags = list(locationName = "truststoreUri", type = "string")), TruststoreVersion = structure(logical(0), tags = list(locationName = "truststoreVersion", type = "string")), TruststoreWarnings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "truststoreWarnings", type = "list"))), tags = list(locationName = "mutualTlsAuthentication", type = "structure")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_domain_names_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_domain_names_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Items = structure(list(structure(list(ApiMappingSelectionExpression = structure(logical(0), tags = list(locationName = "apiMappingSelectionExpression", type = "string")), DomainName = structure(logical(0), tags = list(locationName = "domainName", type = "string")), DomainNameConfigurations = structure(list(structure(list(ApiGatewayDomainName = structure(logical(0), tags = list(locationName = "apiGatewayDomainName", type = "string")), CertificateArn = structure(logical(0), tags = list(locationName = "certificateArn", type = "string")), CertificateName = structure(logical(0), tags = list(locationName = "certificateName", type = "string")), CertificateUploadDate = structure(logical(0), tags = list(locationName = "certificateUploadDate", type = "timestamp", timestampFormat = "iso8601")), DomainNameStatus = structure(logical(0), tags = list(locationName = "domainNameStatus", type = "string")), DomainNameStatusMessage = structure(logical(0), tags = list(locationName = "domainNameStatusMessage", type = "string")), EndpointType = structure(logical(0), tags = list(locationName = "endpointType", type = "string")), HostedZoneId = structure(logical(0), tags = list(locationName = "hostedZoneId", type = "string")), SecurityPolicy = structure(logical(0), tags = list(locationName = "securityPolicy", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "domainNameConfigurations", type = "list")), MutualTlsAuthentication = structure(list(TruststoreUri = structure(logical(0), tags = list(locationName = "truststoreUri", type = "string")), TruststoreVersion = structure(logical(0), tags = list(locationName = "truststoreVersion", type = "string")), TruststoreWarnings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "truststoreWarnings", type = "list"))), tags = list(locationName = "mutualTlsAuthentication", type = "structure")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map"))), tags = list(type = "structure"))), tags = list(locationName = "items", type = "list")), NextToken = structure(logical(0), tags = list(locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_integration_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), IntegrationId = structure(logical(0), tags = list(location = "uri", locationName = "integrationId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_integration_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ConnectionId = structure(logical(0), tags = list(locationName = "connectionId", type = "string")), ConnectionType = structure(logical(0), tags = list(locationName = "connectionType", type = "string")), ContentHandlingStrategy = structure(logical(0), tags = list(locationName = "contentHandlingStrategy", type = "string")), CredentialsArn = structure(logical(0), tags = list(locationName = "credentialsArn", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), IntegrationId = structure(logical(0), tags = list(locationName = "integrationId", type = "string")), IntegrationMethod = structure(logical(0), tags = list(locationName = "integrationMethod", type = "string")), IntegrationResponseSelectionExpression = structure(logical(0), tags = list(locationName = "integrationResponseSelectionExpression", type = "string")), IntegrationSubtype = structure(logical(0), tags = list(locationName = "integrationSubtype", type = "string")), IntegrationType = structure(logical(0), tags = list(locationName = "integrationType", type = "string")), IntegrationUri = structure(logical(0), tags = list(locationName = "integrationUri", type = "string")), PassthroughBehavior = structure(logical(0), tags = list(locationName = "passthroughBehavior", type = "string")), PayloadFormatVersion = structure(logical(0), tags = list(locationName = "payloadFormatVersion", type = "string")), RequestParameters = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestParameters", type = "map")), RequestTemplates = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestTemplates", type = "map")), ResponseParameters = structure(list(structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(locationName = "responseParameters", type = "map")), TemplateSelectionExpression = structure(logical(0), tags = list(locationName = "templateSelectionExpression", type = "string")), TimeoutInMillis = structure(logical(0), tags = list(locationName = "timeoutInMillis", type = "integer")), TlsConfig = structure(list(ServerNameToVerify = structure(logical(0), tags = list(locationName = "serverNameToVerify", type = "string"))), tags = list(locationName = "tlsConfig", type = "structure"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_integration_response_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), IntegrationId = structure(logical(0), tags = list(location = "uri", locationName = "integrationId", type = "string")), IntegrationResponseId = structure(logical(0), tags = list(location = "uri", locationName = "integrationResponseId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_integration_response_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ContentHandlingStrategy = structure(logical(0), tags = list(locationName = "contentHandlingStrategy", type = "string")), IntegrationResponseId = structure(logical(0), tags = list(locationName = "integrationResponseId", type = "string")), IntegrationResponseKey = structure(logical(0), tags = list(locationName = "integrationResponseKey", type = "string")), ResponseParameters = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseParameters", type = "map")), ResponseTemplates = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseTemplates", type = "map")), TemplateSelectionExpression = structure(logical(0), tags = list(locationName = "templateSelectionExpression", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_integration_responses_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), IntegrationId = structure(logical(0), tags = list(location = "uri", locationName = "integrationId", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_integration_responses_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Items = structure(list(structure(list(ContentHandlingStrategy = structure(logical(0), tags = list(locationName = "contentHandlingStrategy", type = "string")), IntegrationResponseId = structure(logical(0), tags = list(locationName = "integrationResponseId", type = "string")), IntegrationResponseKey = structure(logical(0), tags = list(locationName = "integrationResponseKey", type = "string")), ResponseParameters = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseParameters", type = "map")), ResponseTemplates = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseTemplates", type = "map")), TemplateSelectionExpression = structure(logical(0), tags = list(locationName = "templateSelectionExpression", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "items", type = "list")), NextToken = structure(logical(0), tags = list(locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_integrations_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_integrations_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Items = structure(list(structure(list(ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ConnectionId = structure(logical(0), tags = list(locationName = "connectionId", type = "string")), ConnectionType = structure(logical(0), tags = list(locationName = "connectionType", type = "string")), ContentHandlingStrategy = structure(logical(0), tags = list(locationName = "contentHandlingStrategy", type = "string")), CredentialsArn = structure(logical(0), tags = list(locationName = "credentialsArn", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), IntegrationId = structure(logical(0), tags = list(locationName = "integrationId", type = "string")), IntegrationMethod = structure(logical(0), tags = list(locationName = "integrationMethod", type = "string")), IntegrationResponseSelectionExpression = structure(logical(0), tags = list(locationName = "integrationResponseSelectionExpression", type = "string")), IntegrationSubtype = structure(logical(0), tags = list(locationName = "integrationSubtype", type = "string")), IntegrationType = structure(logical(0), tags = list(locationName = "integrationType", type = "string")), IntegrationUri = structure(logical(0), tags = list(locationName = "integrationUri", type = "string")), PassthroughBehavior = structure(logical(0), tags = list(locationName = "passthroughBehavior", type = "string")), PayloadFormatVersion = structure(logical(0), tags = list(locationName = "payloadFormatVersion", type = "string")), RequestParameters = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestParameters", type = "map")), RequestTemplates = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestTemplates", type = "map")), ResponseParameters = structure(list(structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(locationName = "responseParameters", type = "map")), TemplateSelectionExpression = structure(logical(0), tags = list(locationName = "templateSelectionExpression", type = "string")), TimeoutInMillis = structure(logical(0), tags = list(locationName = "timeoutInMillis", type = "integer")), TlsConfig = structure(list(ServerNameToVerify = structure(logical(0), tags = list(locationName = "serverNameToVerify", type = "string"))), tags = list(locationName = "tlsConfig", type = "structure"))), tags = list(type = "structure"))), tags = list(locationName = "items", type = "list")), NextToken = structure(logical(0), tags = list(locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_model_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ModelId = structure(logical(0), tags = list(location = "uri", locationName = "modelId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_model_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ContentType = structure(logical(0), tags = list(locationName = "contentType", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), ModelId = structure(logical(0), tags = list(locationName = "modelId", type = "string")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), Schema = structure(logical(0), tags = list(locationName = "schema", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_model_template_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ModelId = structure(logical(0), tags = list(location = "uri", locationName = "modelId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_model_template_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Value = structure(logical(0), tags = list(locationName = "value", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_models_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_models_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Items = structure(list(structure(list(ContentType = structure(logical(0), tags = list(locationName = "contentType", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), ModelId = structure(logical(0), tags = list(locationName = "modelId", type = "string")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), Schema = structure(logical(0), tags = list(locationName = "schema", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "items", type = "list")), NextToken = structure(logical(0), tags = list(locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_route_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), RouteId = structure(logical(0), tags = list(location = "uri", locationName = "routeId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_route_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ApiKeyRequired = structure(logical(0), tags = list(locationName = "apiKeyRequired", type = "boolean")), AuthorizationScopes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "authorizationScopes", type = "list")), AuthorizationType = structure(logical(0), tags = list(locationName = "authorizationType", type = "string")), AuthorizerId = structure(logical(0), tags = list(locationName = "authorizerId", type = "string")), ModelSelectionExpression = structure(logical(0), tags = list(locationName = "modelSelectionExpression", type = "string")), OperationName = structure(logical(0), tags = list(locationName = "operationName", type = "string")), RequestModels = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestModels", type = "map")), RequestParameters = structure(list(structure(list(Required = structure(logical(0), tags = list(locationName = "required", type = "boolean"))), tags = list(type = "structure"))), tags = list(locationName = "requestParameters", type = "map")), RouteId = structure(logical(0), tags = list(locationName = "routeId", type = "string")), RouteKey = structure(logical(0), tags = list(locationName = "routeKey", type = "string")), RouteResponseSelectionExpression = structure(logical(0), tags = list(locationName = "routeResponseSelectionExpression", type = "string")), Target = structure(logical(0), tags = list(locationName = "target", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_route_response_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), RouteId = structure(logical(0), tags = list(location = "uri", locationName = "routeId", type = "string")), RouteResponseId = structure(logical(0), tags = list(location = "uri", locationName = "routeResponseId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_route_response_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ModelSelectionExpression = structure(logical(0), tags = list(locationName = "modelSelectionExpression", type = "string")), ResponseModels = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseModels", type = "map")), ResponseParameters = structure(list(structure(list(Required = structure(logical(0), tags = list(locationName = "required", type = "boolean"))), tags = list(type = "structure"))), tags = list(locationName = "responseParameters", type = "map")), RouteResponseId = structure(logical(0), tags = list(locationName = "routeResponseId", type = "string")), RouteResponseKey = structure(logical(0), tags = list(locationName = "routeResponseKey", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_route_responses_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), RouteId = structure(logical(0), tags = list(location = "uri", locationName = "routeId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_route_responses_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Items = structure(list(structure(list(ModelSelectionExpression = structure(logical(0), tags = list(locationName = "modelSelectionExpression", type = "string")), ResponseModels = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseModels", type = "map")), ResponseParameters = structure(list(structure(list(Required = structure(logical(0), tags = list(locationName = "required", type = "boolean"))), tags = list(type = "structure"))), tags = list(locationName = "responseParameters", type = "map")), RouteResponseId = structure(logical(0), tags = list(locationName = "routeResponseId", type = "string")), RouteResponseKey = structure(logical(0), tags = list(locationName = "routeResponseKey", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "items", type = "list")), NextToken = structure(logical(0), tags = list(locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_routes_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_routes_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Items = structure(list(structure(list(ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ApiKeyRequired = structure(logical(0), tags = list(locationName = "apiKeyRequired", type = "boolean")), AuthorizationScopes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "authorizationScopes", type = "list")), AuthorizationType = structure(logical(0), tags = list(locationName = "authorizationType", type = "string")), AuthorizerId = structure(logical(0), tags = list(locationName = "authorizerId", type = "string")), ModelSelectionExpression = structure(logical(0), tags = list(locationName = "modelSelectionExpression", type = "string")), OperationName = structure(logical(0), tags = list(locationName = "operationName", type = "string")), RequestModels = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestModels", type = "map")), RequestParameters = structure(list(structure(list(Required = structure(logical(0), tags = list(locationName = "required", type = "boolean"))), tags = list(type = "structure"))), tags = list(locationName = "requestParameters", type = "map")), RouteId = structure(logical(0), tags = list(locationName = "routeId", type = "string")), RouteKey = structure(logical(0), tags = list(locationName = "routeKey", type = "string")), RouteResponseSelectionExpression = structure(logical(0), tags = list(locationName = "routeResponseSelectionExpression", type = "string")), Target = structure(logical(0), tags = list(locationName = "target", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "items", type = "list")), NextToken = structure(logical(0), tags = list(locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_stage_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), StageName = structure(logical(0), tags = list(location = "uri", locationName = "stageName", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_stage_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(AccessLogSettings = structure(list(DestinationArn = structure(logical(0), tags = list(locationName = "destinationArn", type = "string")), Format = structure(logical(0), tags = list(locationName = "format", type = "string"))), tags = list(locationName = "accessLogSettings", type = "structure")), ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), AutoDeploy = structure(logical(0), tags = list(locationName = "autoDeploy", type = "boolean")), ClientCertificateId = structure(logical(0), tags = list(locationName = "clientCertificateId", type = "string")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), DefaultRouteSettings = structure(list(DataTraceEnabled = structure(logical(0), tags = list(locationName = "dataTraceEnabled", type = "boolean")), DetailedMetricsEnabled = structure(logical(0), tags = list(locationName = "detailedMetricsEnabled", type = "boolean")), LoggingLevel = structure(logical(0), tags = list(locationName = "loggingLevel", type = "string")), ThrottlingBurstLimit = structure(logical(0), tags = list(locationName = "throttlingBurstLimit", type = "integer")), ThrottlingRateLimit = structure(logical(0), tags = list(locationName = "throttlingRateLimit", type = "double"))), tags = list(locationName = "defaultRouteSettings", type = "structure")), DeploymentId = structure(logical(0), tags = list(locationName = "deploymentId", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), LastDeploymentStatusMessage = structure(logical(0), tags = list(locationName = "lastDeploymentStatusMessage", type = "string")), LastUpdatedDate = structure(logical(0), tags = list(locationName = "lastUpdatedDate", type = "timestamp", timestampFormat = "iso8601")), RouteSettings = structure(list(structure(list(DataTraceEnabled = structure(logical(0), tags = list(locationName = "dataTraceEnabled", type = "boolean")), DetailedMetricsEnabled = structure(logical(0), tags = list(locationName = "detailedMetricsEnabled", type = "boolean")), LoggingLevel = structure(logical(0), tags = list(locationName = "loggingLevel", type = "string")), ThrottlingBurstLimit = structure(logical(0), tags = list(locationName = "throttlingBurstLimit", type = "integer")), ThrottlingRateLimit = structure(logical(0), tags = list(locationName = "throttlingRateLimit", type = "double"))), tags = list(type = "structure"))), tags = list(locationName = "routeSettings", type = "map")), StageName = structure(logical(0), tags = list(locationName = "stageName", type = "string")), StageVariables = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "stageVariables", type = "map")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_stages_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_stages_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Items = structure(list(structure(list(AccessLogSettings = structure(list(DestinationArn = structure(logical(0), tags = list(locationName = "destinationArn", type = "string")), Format = structure(logical(0), tags = list(locationName = "format", type = "string"))), tags = list(locationName = "accessLogSettings", type = "structure")), ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), AutoDeploy = structure(logical(0), tags = list(locationName = "autoDeploy", type = "boolean")), ClientCertificateId = structure(logical(0), tags = list(locationName = "clientCertificateId", type = "string")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), DefaultRouteSettings = structure(list(DataTraceEnabled = structure(logical(0), tags = list(locationName = "dataTraceEnabled", type = "boolean")), DetailedMetricsEnabled = structure(logical(0), tags = list(locationName = "detailedMetricsEnabled", type = "boolean")), LoggingLevel = structure(logical(0), tags = list(locationName = "loggingLevel", type = "string")), ThrottlingBurstLimit = structure(logical(0), tags = list(locationName = "throttlingBurstLimit", type = "integer")), ThrottlingRateLimit = structure(logical(0), tags = list(locationName = "throttlingRateLimit", type = "double"))), tags = list(locationName = "defaultRouteSettings", type = "structure")), DeploymentId = structure(logical(0), tags = list(locationName = "deploymentId", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), LastDeploymentStatusMessage = structure(logical(0), tags = list(locationName = "lastDeploymentStatusMessage", type = "string")), LastUpdatedDate = structure(logical(0), tags = list(locationName = "lastUpdatedDate", type = "timestamp", timestampFormat = "iso8601")), RouteSettings = structure(list(structure(list(DataTraceEnabled = structure(logical(0), tags = list(locationName = "dataTraceEnabled", type = "boolean")), DetailedMetricsEnabled = structure(logical(0), tags = list(locationName = "detailedMetricsEnabled", type = "boolean")), LoggingLevel = structure(logical(0), tags = list(locationName = "loggingLevel", type = "string")), ThrottlingBurstLimit = structure(logical(0), tags = list(locationName = "throttlingBurstLimit", type = "integer")), ThrottlingRateLimit = structure(logical(0), tags = list(locationName = "throttlingRateLimit", type = "double"))), tags = list(type = "structure"))), tags = list(locationName = "routeSettings", type = "map")), StageName = structure(logical(0), tags = list(locationName = "stageName", type = "string")), StageVariables = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "stageVariables", type = "map")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map"))), tags = list(type = "structure"))), tags = list(locationName = "items", type = "list")), NextToken = structure(logical(0), tags = list(locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_tags_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ResourceArn = structure(logical(0), tags = list(location = "uri", locationName = "resource-arn", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_tags_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_vpc_link_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(VpcLinkId = structure(logical(0), tags = list(location = "uri", locationName = "vpcLinkId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_vpc_link_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), SecurityGroupIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "securityGroupIds", type = "list")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "subnetIds", type = "list")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map")), VpcLinkId = structure(logical(0), tags = list(locationName = "vpcLinkId", type = "string")), VpcLinkStatus = structure(logical(0), tags = list(locationName = "vpcLinkStatus", type = "string")), VpcLinkStatusMessage = structure(logical(0), tags = list(locationName = "vpcLinkStatusMessage", type = "string")), VpcLinkVersion = structure(logical(0), tags = list(locationName = "vpcLinkVersion", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_vpc_links_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$get_vpc_links_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Items = structure(list(structure(list(CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), SecurityGroupIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "securityGroupIds", type = "list")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "subnetIds", type = "list")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map")), VpcLinkId = structure(logical(0), tags = list(locationName = "vpcLinkId", type = "string")), VpcLinkStatus = structure(logical(0), tags = list(locationName = "vpcLinkStatus", type = "string")), VpcLinkStatusMessage = structure(logical(0), tags = list(locationName = "vpcLinkStatusMessage", type = "string")), VpcLinkVersion = structure(logical(0), tags = list(locationName = "vpcLinkVersion", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "items", type = "list")), NextToken = structure(logical(0), tags = list(locationName = "nextToken", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$import_api_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Basepath = structure(logical(0), tags = list(location = "querystring", locationName = "basepath", type = "string")), Body = structure(logical(0), tags = list(locationName = "body", type = "string")), FailOnWarnings = structure(logical(0), tags = list(location = "querystring", locationName = "failOnWarnings", type = "boolean"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$import_api_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiEndpoint = structure(logical(0), tags = list(locationName = "apiEndpoint", type = "string")), ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ApiId = structure(logical(0), tags = list(locationName = "apiId", type = "string")), ApiKeySelectionExpression = structure(logical(0), tags = list(locationName = "apiKeySelectionExpression", type = "string")), CorsConfiguration = structure(list(AllowCredentials = structure(logical(0), tags = list(locationName = "allowCredentials", type = "boolean")), AllowHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowHeaders", type = "list")), AllowMethods = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowMethods", type = "list")), AllowOrigins = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowOrigins", type = "list")), ExposeHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "exposeHeaders", type = "list")), MaxAge = structure(logical(0), tags = list(locationName = "maxAge", type = "integer"))), tags = list(locationName = "corsConfiguration", type = "structure")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), DisableSchemaValidation = structure(logical(0), tags = list(locationName = "disableSchemaValidation", type = "boolean")), DisableExecuteApiEndpoint = structure(logical(0), tags = list(locationName = "disableExecuteApiEndpoint", type = "boolean")), ImportInfo = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "importInfo", type = "list")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), ProtocolType = structure(logical(0), tags = list(locationName = "protocolType", type = "string")), RouteSelectionExpression = structure(logical(0), tags = list(locationName = "routeSelectionExpression", type = "string")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map")), Version = structure(logical(0), tags = list(locationName = "version", type = "string")), Warnings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "warnings", type = "list"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$reimport_api_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), Basepath = structure(logical(0), tags = list(location = "querystring", locationName = "basepath", type = "string")), Body = structure(logical(0), tags = list(locationName = "body", type = "string")), FailOnWarnings = structure(logical(0), tags = list(location = "querystring", locationName = "failOnWarnings", type = "boolean"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$reimport_api_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiEndpoint = structure(logical(0), tags = list(locationName = "apiEndpoint", type = "string")), ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ApiId = structure(logical(0), tags = list(locationName = "apiId", type = "string")), ApiKeySelectionExpression = structure(logical(0), tags = list(locationName = "apiKeySelectionExpression", type = "string")), CorsConfiguration = structure(list(AllowCredentials = structure(logical(0), tags = list(locationName = "allowCredentials", type = "boolean")), AllowHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowHeaders", type = "list")), AllowMethods = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowMethods", type = "list")), AllowOrigins = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowOrigins", type = "list")), ExposeHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "exposeHeaders", type = "list")), MaxAge = structure(logical(0), tags = list(locationName = "maxAge", type = "integer"))), tags = list(locationName = "corsConfiguration", type = "structure")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), DisableSchemaValidation = structure(logical(0), tags = list(locationName = "disableSchemaValidation", type = "boolean")), DisableExecuteApiEndpoint = structure(logical(0), tags = list(locationName = "disableExecuteApiEndpoint", type = "boolean")), ImportInfo = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "importInfo", type = "list")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), ProtocolType = structure(logical(0), tags = list(locationName = "protocolType", type = "string")), RouteSelectionExpression = structure(logical(0), tags = list(locationName = "routeSelectionExpression", type = "string")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map")), Version = structure(logical(0), tags = list(locationName = "version", type = "string")), Warnings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "warnings", type = "list"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$tag_resource_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ResourceArn = structure(logical(0), tags = list(location = "uri", locationName = "resource-arn", type = "string")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$tag_resource_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$untag_resource_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ResourceArn = structure(logical(0), tags = list(location = "uri", locationName = "resource-arn", type = "string")), TagKeys = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(location = "querystring", locationName = "tagKeys", type = "list"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$untag_resource_output <- function(...) {
list()
}
.apigatewayv2$update_api_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ApiKeySelectionExpression = structure(logical(0), tags = list(locationName = "apiKeySelectionExpression", type = "string")), CorsConfiguration = structure(list(AllowCredentials = structure(logical(0), tags = list(locationName = "allowCredentials", type = "boolean")), AllowHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowHeaders", type = "list")), AllowMethods = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowMethods", type = "list")), AllowOrigins = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowOrigins", type = "list")), ExposeHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "exposeHeaders", type = "list")), MaxAge = structure(logical(0), tags = list(locationName = "maxAge", type = "integer"))), tags = list(locationName = "corsConfiguration", type = "structure")), CredentialsArn = structure(logical(0), tags = list(locationName = "credentialsArn", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), DisableSchemaValidation = structure(logical(0), tags = list(locationName = "disableSchemaValidation", type = "boolean")), DisableExecuteApiEndpoint = structure(logical(0), tags = list(locationName = "disableExecuteApiEndpoint", type = "boolean")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), RouteKey = structure(logical(0), tags = list(locationName = "routeKey", type = "string")), RouteSelectionExpression = structure(logical(0), tags = list(locationName = "routeSelectionExpression", type = "string")), Target = structure(logical(0), tags = list(locationName = "target", type = "string")), Version = structure(logical(0), tags = list(locationName = "version", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_api_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiEndpoint = structure(logical(0), tags = list(locationName = "apiEndpoint", type = "string")), ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ApiId = structure(logical(0), tags = list(locationName = "apiId", type = "string")), ApiKeySelectionExpression = structure(logical(0), tags = list(locationName = "apiKeySelectionExpression", type = "string")), CorsConfiguration = structure(list(AllowCredentials = structure(logical(0), tags = list(locationName = "allowCredentials", type = "boolean")), AllowHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowHeaders", type = "list")), AllowMethods = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowMethods", type = "list")), AllowOrigins = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "allowOrigins", type = "list")), ExposeHeaders = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "exposeHeaders", type = "list")), MaxAge = structure(logical(0), tags = list(locationName = "maxAge", type = "integer"))), tags = list(locationName = "corsConfiguration", type = "structure")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), DisableSchemaValidation = structure(logical(0), tags = list(locationName = "disableSchemaValidation", type = "boolean")), DisableExecuteApiEndpoint = structure(logical(0), tags = list(locationName = "disableExecuteApiEndpoint", type = "boolean")), ImportInfo = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "importInfo", type = "list")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), ProtocolType = structure(logical(0), tags = list(locationName = "protocolType", type = "string")), RouteSelectionExpression = structure(logical(0), tags = list(locationName = "routeSelectionExpression", type = "string")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map")), Version = structure(logical(0), tags = list(locationName = "version", type = "string")), Warnings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "warnings", type = "list"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_api_mapping_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(locationName = "apiId", type = "string")), ApiMappingId = structure(logical(0), tags = list(location = "uri", locationName = "apiMappingId", type = "string")), ApiMappingKey = structure(logical(0), tags = list(locationName = "apiMappingKey", type = "string")), DomainName = structure(logical(0), tags = list(location = "uri", locationName = "domainName", type = "string")), Stage = structure(logical(0), tags = list(locationName = "stage", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_api_mapping_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(locationName = "apiId", type = "string")), ApiMappingId = structure(logical(0), tags = list(locationName = "apiMappingId", type = "string")), ApiMappingKey = structure(logical(0), tags = list(locationName = "apiMappingKey", type = "string")), Stage = structure(logical(0), tags = list(locationName = "stage", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_authorizer_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), AuthorizerCredentialsArn = structure(logical(0), tags = list(locationName = "authorizerCredentialsArn", type = "string")), AuthorizerId = structure(logical(0), tags = list(location = "uri", locationName = "authorizerId", type = "string")), AuthorizerPayloadFormatVersion = structure(logical(0), tags = list(locationName = "authorizerPayloadFormatVersion", type = "string")), AuthorizerResultTtlInSeconds = structure(logical(0), tags = list(locationName = "authorizerResultTtlInSeconds", type = "integer")), AuthorizerType = structure(logical(0), tags = list(locationName = "authorizerType", type = "string")), AuthorizerUri = structure(logical(0), tags = list(locationName = "authorizerUri", type = "string")), EnableSimpleResponses = structure(logical(0), tags = list(locationName = "enableSimpleResponses", type = "boolean")), IdentitySource = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "identitySource", type = "list")), IdentityValidationExpression = structure(logical(0), tags = list(locationName = "identityValidationExpression", type = "string")), JwtConfiguration = structure(list(Audience = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "audience", type = "list")), Issuer = structure(logical(0), tags = list(locationName = "issuer", type = "string"))), tags = list(locationName = "jwtConfiguration", type = "structure")), Name = structure(logical(0), tags = list(locationName = "name", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_authorizer_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(AuthorizerCredentialsArn = structure(logical(0), tags = list(locationName = "authorizerCredentialsArn", type = "string")), AuthorizerId = structure(logical(0), tags = list(locationName = "authorizerId", type = "string")), AuthorizerPayloadFormatVersion = structure(logical(0), tags = list(locationName = "authorizerPayloadFormatVersion", type = "string")), AuthorizerResultTtlInSeconds = structure(logical(0), tags = list(locationName = "authorizerResultTtlInSeconds", type = "integer")), AuthorizerType = structure(logical(0), tags = list(locationName = "authorizerType", type = "string")), AuthorizerUri = structure(logical(0), tags = list(locationName = "authorizerUri", type = "string")), EnableSimpleResponses = structure(logical(0), tags = list(locationName = "enableSimpleResponses", type = "boolean")), IdentitySource = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "identitySource", type = "list")), IdentityValidationExpression = structure(logical(0), tags = list(locationName = "identityValidationExpression", type = "string")), JwtConfiguration = structure(list(Audience = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "audience", type = "list")), Issuer = structure(logical(0), tags = list(locationName = "issuer", type = "string"))), tags = list(locationName = "jwtConfiguration", type = "structure")), Name = structure(logical(0), tags = list(locationName = "name", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_deployment_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), DeploymentId = structure(logical(0), tags = list(location = "uri", locationName = "deploymentId", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_deployment_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(AutoDeployed = structure(logical(0), tags = list(locationName = "autoDeployed", type = "boolean")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), DeploymentId = structure(logical(0), tags = list(locationName = "deploymentId", type = "string")), DeploymentStatus = structure(logical(0), tags = list(locationName = "deploymentStatus", type = "string")), DeploymentStatusMessage = structure(logical(0), tags = list(locationName = "deploymentStatusMessage", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_domain_name_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(DomainName = structure(logical(0), tags = list(location = "uri", locationName = "domainName", type = "string")), DomainNameConfigurations = structure(list(structure(list(ApiGatewayDomainName = structure(logical(0), tags = list(locationName = "apiGatewayDomainName", type = "string")), CertificateArn = structure(logical(0), tags = list(locationName = "certificateArn", type = "string")), CertificateName = structure(logical(0), tags = list(locationName = "certificateName", type = "string")), CertificateUploadDate = structure(logical(0), tags = list(locationName = "certificateUploadDate", type = "timestamp", timestampFormat = "iso8601")), DomainNameStatus = structure(logical(0), tags = list(locationName = "domainNameStatus", type = "string")), DomainNameStatusMessage = structure(logical(0), tags = list(locationName = "domainNameStatusMessage", type = "string")), EndpointType = structure(logical(0), tags = list(locationName = "endpointType", type = "string")), HostedZoneId = structure(logical(0), tags = list(locationName = "hostedZoneId", type = "string")), SecurityPolicy = structure(logical(0), tags = list(locationName = "securityPolicy", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "domainNameConfigurations", type = "list")), MutualTlsAuthentication = structure(list(TruststoreUri = structure(logical(0), tags = list(locationName = "truststoreUri", type = "string")), TruststoreVersion = structure(logical(0), tags = list(locationName = "truststoreVersion", type = "string"))), tags = list(locationName = "mutualTlsAuthentication", type = "structure"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_domain_name_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiMappingSelectionExpression = structure(logical(0), tags = list(locationName = "apiMappingSelectionExpression", type = "string")), DomainName = structure(logical(0), tags = list(locationName = "domainName", type = "string")), DomainNameConfigurations = structure(list(structure(list(ApiGatewayDomainName = structure(logical(0), tags = list(locationName = "apiGatewayDomainName", type = "string")), CertificateArn = structure(logical(0), tags = list(locationName = "certificateArn", type = "string")), CertificateName = structure(logical(0), tags = list(locationName = "certificateName", type = "string")), CertificateUploadDate = structure(logical(0), tags = list(locationName = "certificateUploadDate", type = "timestamp", timestampFormat = "iso8601")), DomainNameStatus = structure(logical(0), tags = list(locationName = "domainNameStatus", type = "string")), DomainNameStatusMessage = structure(logical(0), tags = list(locationName = "domainNameStatusMessage", type = "string")), EndpointType = structure(logical(0), tags = list(locationName = "endpointType", type = "string")), HostedZoneId = structure(logical(0), tags = list(locationName = "hostedZoneId", type = "string")), SecurityPolicy = structure(logical(0), tags = list(locationName = "securityPolicy", type = "string"))), tags = list(type = "structure"))), tags = list(locationName = "domainNameConfigurations", type = "list")), MutualTlsAuthentication = structure(list(TruststoreUri = structure(logical(0), tags = list(locationName = "truststoreUri", type = "string")), TruststoreVersion = structure(logical(0), tags = list(locationName = "truststoreVersion", type = "string")), TruststoreWarnings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "truststoreWarnings", type = "list"))), tags = list(locationName = "mutualTlsAuthentication", type = "structure")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_integration_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ConnectionId = structure(logical(0), tags = list(locationName = "connectionId", type = "string")), ConnectionType = structure(logical(0), tags = list(locationName = "connectionType", type = "string")), ContentHandlingStrategy = structure(logical(0), tags = list(locationName = "contentHandlingStrategy", type = "string")), CredentialsArn = structure(logical(0), tags = list(locationName = "credentialsArn", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), IntegrationId = structure(logical(0), tags = list(location = "uri", locationName = "integrationId", type = "string")), IntegrationMethod = structure(logical(0), tags = list(locationName = "integrationMethod", type = "string")), IntegrationSubtype = structure(logical(0), tags = list(locationName = "integrationSubtype", type = "string")), IntegrationType = structure(logical(0), tags = list(locationName = "integrationType", type = "string")), IntegrationUri = structure(logical(0), tags = list(locationName = "integrationUri", type = "string")), PassthroughBehavior = structure(logical(0), tags = list(locationName = "passthroughBehavior", type = "string")), PayloadFormatVersion = structure(logical(0), tags = list(locationName = "payloadFormatVersion", type = "string")), RequestParameters = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestParameters", type = "map")), RequestTemplates = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestTemplates", type = "map")), ResponseParameters = structure(list(structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(locationName = "responseParameters", type = "map")), TemplateSelectionExpression = structure(logical(0), tags = list(locationName = "templateSelectionExpression", type = "string")), TimeoutInMillis = structure(logical(0), tags = list(locationName = "timeoutInMillis", type = "integer")), TlsConfig = structure(list(ServerNameToVerify = structure(logical(0), tags = list(locationName = "serverNameToVerify", type = "string"))), tags = list(locationName = "tlsConfig", type = "structure"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_integration_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ConnectionId = structure(logical(0), tags = list(locationName = "connectionId", type = "string")), ConnectionType = structure(logical(0), tags = list(locationName = "connectionType", type = "string")), ContentHandlingStrategy = structure(logical(0), tags = list(locationName = "contentHandlingStrategy", type = "string")), CredentialsArn = structure(logical(0), tags = list(locationName = "credentialsArn", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), IntegrationId = structure(logical(0), tags = list(locationName = "integrationId", type = "string")), IntegrationMethod = structure(logical(0), tags = list(locationName = "integrationMethod", type = "string")), IntegrationResponseSelectionExpression = structure(logical(0), tags = list(locationName = "integrationResponseSelectionExpression", type = "string")), IntegrationSubtype = structure(logical(0), tags = list(locationName = "integrationSubtype", type = "string")), IntegrationType = structure(logical(0), tags = list(locationName = "integrationType", type = "string")), IntegrationUri = structure(logical(0), tags = list(locationName = "integrationUri", type = "string")), PassthroughBehavior = structure(logical(0), tags = list(locationName = "passthroughBehavior", type = "string")), PayloadFormatVersion = structure(logical(0), tags = list(locationName = "payloadFormatVersion", type = "string")), RequestParameters = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestParameters", type = "map")), RequestTemplates = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestTemplates", type = "map")), ResponseParameters = structure(list(structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(locationName = "responseParameters", type = "map")), TemplateSelectionExpression = structure(logical(0), tags = list(locationName = "templateSelectionExpression", type = "string")), TimeoutInMillis = structure(logical(0), tags = list(locationName = "timeoutInMillis", type = "integer")), TlsConfig = structure(list(ServerNameToVerify = structure(logical(0), tags = list(locationName = "serverNameToVerify", type = "string"))), tags = list(locationName = "tlsConfig", type = "structure"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_integration_response_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ContentHandlingStrategy = structure(logical(0), tags = list(locationName = "contentHandlingStrategy", type = "string")), IntegrationId = structure(logical(0), tags = list(location = "uri", locationName = "integrationId", type = "string")), IntegrationResponseId = structure(logical(0), tags = list(location = "uri", locationName = "integrationResponseId", type = "string")), IntegrationResponseKey = structure(logical(0), tags = list(locationName = "integrationResponseKey", type = "string")), ResponseParameters = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseParameters", type = "map")), ResponseTemplates = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseTemplates", type = "map")), TemplateSelectionExpression = structure(logical(0), tags = list(locationName = "templateSelectionExpression", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_integration_response_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ContentHandlingStrategy = structure(logical(0), tags = list(locationName = "contentHandlingStrategy", type = "string")), IntegrationResponseId = structure(logical(0), tags = list(locationName = "integrationResponseId", type = "string")), IntegrationResponseKey = structure(logical(0), tags = list(locationName = "integrationResponseKey", type = "string")), ResponseParameters = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseParameters", type = "map")), ResponseTemplates = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseTemplates", type = "map")), TemplateSelectionExpression = structure(logical(0), tags = list(locationName = "templateSelectionExpression", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_model_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ContentType = structure(logical(0), tags = list(locationName = "contentType", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), ModelId = structure(logical(0), tags = list(location = "uri", locationName = "modelId", type = "string")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), Schema = structure(logical(0), tags = list(locationName = "schema", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_model_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ContentType = structure(logical(0), tags = list(locationName = "contentType", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), ModelId = structure(logical(0), tags = list(locationName = "modelId", type = "string")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), Schema = structure(logical(0), tags = list(locationName = "schema", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_route_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ApiKeyRequired = structure(logical(0), tags = list(locationName = "apiKeyRequired", type = "boolean")), AuthorizationScopes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "authorizationScopes", type = "list")), AuthorizationType = structure(logical(0), tags = list(locationName = "authorizationType", type = "string")), AuthorizerId = structure(logical(0), tags = list(locationName = "authorizerId", type = "string")), ModelSelectionExpression = structure(logical(0), tags = list(locationName = "modelSelectionExpression", type = "string")), OperationName = structure(logical(0), tags = list(locationName = "operationName", type = "string")), RequestModels = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestModels", type = "map")), RequestParameters = structure(list(structure(list(Required = structure(logical(0), tags = list(locationName = "required", type = "boolean"))), tags = list(type = "structure"))), tags = list(locationName = "requestParameters", type = "map")), RouteId = structure(logical(0), tags = list(location = "uri", locationName = "routeId", type = "string")), RouteKey = structure(logical(0), tags = list(locationName = "routeKey", type = "string")), RouteResponseSelectionExpression = structure(logical(0), tags = list(locationName = "routeResponseSelectionExpression", type = "string")), Target = structure(logical(0), tags = list(locationName = "target", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_route_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), ApiKeyRequired = structure(logical(0), tags = list(locationName = "apiKeyRequired", type = "boolean")), AuthorizationScopes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "authorizationScopes", type = "list")), AuthorizationType = structure(logical(0), tags = list(locationName = "authorizationType", type = "string")), AuthorizerId = structure(logical(0), tags = list(locationName = "authorizerId", type = "string")), ModelSelectionExpression = structure(logical(0), tags = list(locationName = "modelSelectionExpression", type = "string")), OperationName = structure(logical(0), tags = list(locationName = "operationName", type = "string")), RequestModels = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "requestModels", type = "map")), RequestParameters = structure(list(structure(list(Required = structure(logical(0), tags = list(locationName = "required", type = "boolean"))), tags = list(type = "structure"))), tags = list(locationName = "requestParameters", type = "map")), RouteId = structure(logical(0), tags = list(locationName = "routeId", type = "string")), RouteKey = structure(logical(0), tags = list(locationName = "routeKey", type = "string")), RouteResponseSelectionExpression = structure(logical(0), tags = list(locationName = "routeResponseSelectionExpression", type = "string")), Target = structure(logical(0), tags = list(locationName = "target", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_route_response_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), ModelSelectionExpression = structure(logical(0), tags = list(locationName = "modelSelectionExpression", type = "string")), ResponseModels = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseModels", type = "map")), ResponseParameters = structure(list(structure(list(Required = structure(logical(0), tags = list(locationName = "required", type = "boolean"))), tags = list(type = "structure"))), tags = list(locationName = "responseParameters", type = "map")), RouteId = structure(logical(0), tags = list(location = "uri", locationName = "routeId", type = "string")), RouteResponseId = structure(logical(0), tags = list(location = "uri", locationName = "routeResponseId", type = "string")), RouteResponseKey = structure(logical(0), tags = list(locationName = "routeResponseKey", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_route_response_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(ModelSelectionExpression = structure(logical(0), tags = list(locationName = "modelSelectionExpression", type = "string")), ResponseModels = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "responseModels", type = "map")), ResponseParameters = structure(list(structure(list(Required = structure(logical(0), tags = list(locationName = "required", type = "boolean"))), tags = list(type = "structure"))), tags = list(locationName = "responseParameters", type = "map")), RouteResponseId = structure(logical(0), tags = list(locationName = "routeResponseId", type = "string")), RouteResponseKey = structure(logical(0), tags = list(locationName = "routeResponseKey", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_stage_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(AccessLogSettings = structure(list(DestinationArn = structure(logical(0), tags = list(locationName = "destinationArn", type = "string")), Format = structure(logical(0), tags = list(locationName = "format", type = "string"))), tags = list(locationName = "accessLogSettings", type = "structure")), ApiId = structure(logical(0), tags = list(location = "uri", locationName = "apiId", type = "string")), AutoDeploy = structure(logical(0), tags = list(locationName = "autoDeploy", type = "boolean")), ClientCertificateId = structure(logical(0), tags = list(locationName = "clientCertificateId", type = "string")), DefaultRouteSettings = structure(list(DataTraceEnabled = structure(logical(0), tags = list(locationName = "dataTraceEnabled", type = "boolean")), DetailedMetricsEnabled = structure(logical(0), tags = list(locationName = "detailedMetricsEnabled", type = "boolean")), LoggingLevel = structure(logical(0), tags = list(locationName = "loggingLevel", type = "string")), ThrottlingBurstLimit = structure(logical(0), tags = list(locationName = "throttlingBurstLimit", type = "integer")), ThrottlingRateLimit = structure(logical(0), tags = list(locationName = "throttlingRateLimit", type = "double"))), tags = list(locationName = "defaultRouteSettings", type = "structure")), DeploymentId = structure(logical(0), tags = list(locationName = "deploymentId", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), RouteSettings = structure(list(structure(list(DataTraceEnabled = structure(logical(0), tags = list(locationName = "dataTraceEnabled", type = "boolean")), DetailedMetricsEnabled = structure(logical(0), tags = list(locationName = "detailedMetricsEnabled", type = "boolean")), LoggingLevel = structure(logical(0), tags = list(locationName = "loggingLevel", type = "string")), ThrottlingBurstLimit = structure(logical(0), tags = list(locationName = "throttlingBurstLimit", type = "integer")), ThrottlingRateLimit = structure(logical(0), tags = list(locationName = "throttlingRateLimit", type = "double"))), tags = list(type = "structure"))), tags = list(locationName = "routeSettings", type = "map")), StageName = structure(logical(0), tags = list(location = "uri", locationName = "stageName", type = "string")), StageVariables = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "stageVariables", type = "map"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_stage_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(AccessLogSettings = structure(list(DestinationArn = structure(logical(0), tags = list(locationName = "destinationArn", type = "string")), Format = structure(logical(0), tags = list(locationName = "format", type = "string"))), tags = list(locationName = "accessLogSettings", type = "structure")), ApiGatewayManaged = structure(logical(0), tags = list(locationName = "apiGatewayManaged", type = "boolean")), AutoDeploy = structure(logical(0), tags = list(locationName = "autoDeploy", type = "boolean")), ClientCertificateId = structure(logical(0), tags = list(locationName = "clientCertificateId", type = "string")), CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), DefaultRouteSettings = structure(list(DataTraceEnabled = structure(logical(0), tags = list(locationName = "dataTraceEnabled", type = "boolean")), DetailedMetricsEnabled = structure(logical(0), tags = list(locationName = "detailedMetricsEnabled", type = "boolean")), LoggingLevel = structure(logical(0), tags = list(locationName = "loggingLevel", type = "string")), ThrottlingBurstLimit = structure(logical(0), tags = list(locationName = "throttlingBurstLimit", type = "integer")), ThrottlingRateLimit = structure(logical(0), tags = list(locationName = "throttlingRateLimit", type = "double"))), tags = list(locationName = "defaultRouteSettings", type = "structure")), DeploymentId = structure(logical(0), tags = list(locationName = "deploymentId", type = "string")), Description = structure(logical(0), tags = list(locationName = "description", type = "string")), LastDeploymentStatusMessage = structure(logical(0), tags = list(locationName = "lastDeploymentStatusMessage", type = "string")), LastUpdatedDate = structure(logical(0), tags = list(locationName = "lastUpdatedDate", type = "timestamp", timestampFormat = "iso8601")), RouteSettings = structure(list(structure(list(DataTraceEnabled = structure(logical(0), tags = list(locationName = "dataTraceEnabled", type = "boolean")), DetailedMetricsEnabled = structure(logical(0), tags = list(locationName = "detailedMetricsEnabled", type = "boolean")), LoggingLevel = structure(logical(0), tags = list(locationName = "loggingLevel", type = "string")), ThrottlingBurstLimit = structure(logical(0), tags = list(locationName = "throttlingBurstLimit", type = "integer")), ThrottlingRateLimit = structure(logical(0), tags = list(locationName = "throttlingRateLimit", type = "double"))), tags = list(type = "structure"))), tags = list(locationName = "routeSettings", type = "map")), StageName = structure(logical(0), tags = list(locationName = "stageName", type = "string")), StageVariables = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "stageVariables", type = "map")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_vpc_link_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(Name = structure(logical(0), tags = list(locationName = "name", type = "string")), VpcLinkId = structure(logical(0), tags = list(location = "uri", locationName = "vpcLinkId", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.apigatewayv2$update_vpc_link_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(CreatedDate = structure(logical(0), tags = list(locationName = "createdDate", type = "timestamp", timestampFormat = "iso8601")), Name = structure(logical(0), tags = list(locationName = "name", type = "string")), SecurityGroupIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "securityGroupIds", type = "list")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "subnetIds", type = "list")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(locationName = "tags", type = "map")), VpcLinkId = structure(logical(0), tags = list(locationName = "vpcLinkId", type = "string")), VpcLinkStatus = structure(logical(0), tags = list(locationName = "vpcLinkStatus", type = "string")), VpcLinkStatusMessage = structure(logical(0), tags = list(locationName = "vpcLinkStatusMessage", type = "string")), VpcLinkVersion = structure(logical(0), tags = list(locationName = "vpcLinkVersion", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
} |
gevcdn.reshape <-
function (x, weights, n.hidden)
{
N11 <- ncol(x) + 1
N12 <- n.hidden
N1 <- N11*N12
W1 <- weights[1:N1]
W1 <- matrix(W1, nrow = N11, ncol = N12)
N21 <- n.hidden + 1
N22 <- 3
N2 <- N1 + N21*N22
W2 <- weights[(N1 + 1):N2]
W2 <- matrix(W2, nrow = N21, ncol = N22)
list(W1 = W1, W2 = W2)
} |
context("spark-apply-ext")
test_requires("dplyr")
sc <- testthat_spark_connection()
iris_tbl <- testthat_tbl("iris")
dates <- data.frame(dates = c(as.Date("2015/12/19"), as.Date(NA), as.Date("2015/12/19")))
dates_tbl <- testthat_tbl("dates")
colnas <- data.frame(c1 = c("A", "B"), c2 = c(NA, NA))
colnas_tbl <- testthat_tbl("colnas")
test_that("'spark_apply' can filter columns", {
expect_equivalent(
iris_tbl %>% spark_apply(function(e) e[1:1]) %>% collect(),
iris_tbl %>% select(Sepal_Length) %>% collect()
)
})
test_that("'spark_apply' can add columns", {
expect_equivalent(
iris_tbl %>% spark_apply(function(e) cbind(e, 1), names = c(colnames(iris_tbl), "new")) %>% collect(),
iris_tbl %>% mutate(new = 1) %>% collect()
)
})
test_that("'spark_apply' can concatenate", {
expect_equivalent(
iris_tbl %>% spark_apply(function(e) apply(e, 1, paste, collapse = " "), names = "s") %>% collect(),
iris_tbl %>% transmute(s = paste(Sepal_Length, Sepal_Width, Petal_Length, Petal_Width, Species)) %>% collect()
)
})
test_that("'spark_apply' can filter", {
expect_equivalent(
iris_tbl %>% spark_apply(function(e) e[e$Species == "setosa", ]) %>% collect(),
iris_tbl %>% filter(Species == "setosa") %>% collect()
)
})
test_that("'spark_apply' works with 'sdf_repartition'", {
id <- random_string("id")
expect_equivalent(
iris_tbl %>%
sdf_with_sequential_id(id) %>%
sdf_repartition(2L) %>%
spark_apply(function(e) e) %>%
collect() %>%
arrange(!!rlang::sym(id)),
iris_tbl %>%
sdf_with_sequential_id(id) %>%
collect()
)
})
test_that("'spark_apply' works with 'group_by' over multiple columns", {
iris_tbl_ints <- iris_tbl %>%
mutate(Petal_Width_Int = as.integer(Petal_Width))
grouped_lm <- spark_apply(
iris_tbl_ints,
function(e, species, petal_width) {
lm(Petal_Width ~ Petal_Length, e)$coefficients[["(Intercept)"]]
},
names = "Intercept",
group_by = c("Species", "Petal_Width_Int")
) %>% collect()
iris_int <- iris %>% mutate(
Petal_Width_Int = as.integer(Petal.Width),
GroupBy = paste(Species, Petal_Width_Int, sep = "|")
)
lapply(
unique(iris_int$GroupBy),
function(group_by_entry) {
parts <- strsplit(group_by_entry, "\\|")
species_test <- parts[[1]][[1]]
petal_width_test <- as.integer(parts[[1]][[2]])
expect_equal(
grouped_lm[grouped_lm$Species == species_test & grouped_lm$Petal_Width_Int == petal_width_test, ]$Intercept,
lm(Petal.Width ~ Petal.Length, iris_int[iris_int$Species == species_test & iris_int$Petal_Width_Int == petal_width_test, ])$coefficients[["(Intercept)"]]
)
}
)
})
test_that("'spark_apply' works over empty partitions", {
skip_slow("takes too long to measure coverage")
expect_equal(
sdf_len(sc, 2, repartition = 4) %>%
spark_apply(function(e) e) %>%
collect() %>%
as.data.frame(),
data.frame(id = seq_len(2))
)
})
test_that("'spark_apply' works over 'tryCatch'", {
skip_slow("takes too long to measure coverage")
expect_equal(
sdf_len(sc, 1) %>%
spark_apply(function(e) {
tryCatch(
{
stop("x")
},
error = function(e) {
100
}
)
}) %>%
pull() %>%
as.integer(),
100
)
})
test_that("'spark_apply' can filter data.frame", {
skip_slow("takes too long to measure coverage")
expect_equal(
sdf_len(sc, 10) %>%
spark_apply(function(e) as.data.frame(e[e$id > 1, ])) %>%
collect() %>%
nrow(),
9
)
})
test_that("'spark_apply' can filter using dplyr", {
skip_slow("takes too long to measure coverage")
expect_equal(
sdf_len(sc, 10) %>%
spark_apply(function(e) dplyr::filter(e, id > 1)) %>%
collect() %>%
as.data.frame(),
data.frame(id = c(2:10))
)
})
test_that("'spark_apply' can return 'NA's", {
skip_slow("takes too long to measure coverage")
expect_equal(
dates_tbl %>%
spark_apply(function(e) e) %>%
collect() %>%
nrow(),
nrow(dates)
)
})
test_that("'spark_apply' can return 'NA's for dates", {
skip_slow("takes too long to measure coverage")
expect_equal(
sdf_len(sc, 1) %>%
spark_apply(function(e) data.frame(dates = c(as.Date("2001/1/1"), NA))) %>%
collect() %>%
nrow(),
2
)
})
test_that("'spark_apply' can roundtrip dates", {
skip_slow("takes too long to measure coverage")
expect_equal(
dates_tbl %>%
spark_apply(function(e) as.Date(e[[1]], origin = "1970-01-01")) %>%
spark_apply(function(e) e) %>%
collect() %>%
pull() %>%
class(),
"Date"
)
})
test_that("'spark_apply' can roundtrip Date-Time", {
skip_slow("takes too long to measure coverage")
expect_equal(
dates_tbl %>%
spark_apply(function(e) as.POSIXct(e[[1]], origin = "1970-01-01")) %>%
spark_apply(function(e) e) %>%
collect() %>%
pull() %>%
class() %>%
first(),
"POSIXct"
)
})
test_that("'spark_apply' supports grouped empty results", {
skip_slow("takes too long to measure coverage")
process_data <- function(DF, exclude) {
DF <- subset(DF, select = colnames(DF)[!colnames(DF) %in% exclude])
DF[complete.cases(DF), ]
}
data <- data.frame(
grp = rep(c("A", "B", "C"), each = 5),
x1 = 1:15,
x2 = c(1:9, rep(NA, 6)),
stringsAsFactors = FALSE
)
data_spark <- sdf_copy_to(sc, data, "grp_data", memory = TRUE, overwrite = TRUE)
collected <- data_spark %>%
spark_apply(
process_data,
group_by = "grp",
columns = c("x1", "x2"),
packages = FALSE,
context = {
exclude <- "grp"
}
) %>%
collect()
expect_equivalent(
collected %>% arrange(x1),
data %>%
group_by(grp) %>%
do(process_data(., exclude = "grp")) %>%
arrange(x1)
)
})
test_that("'spark_apply' can use anonymous functions", {
skip_slow("takes too long to measure coverage")
expect_equal(
sdf_len(sc, 3) %>% spark_apply(~ .x + 1) %>% collect(),
tibble(id = c(2, 3, 4))
)
})
test_that("'spark_apply' can apply function with 'NA's column", {
skip_slow("takes too long to measure coverage")
if (spark_version(sc) < "2.0.0") skip("automatic column types supported in Spark 2.0+")
expect_equivalent(
colnas_tbl %>% mutate(c2 = as.integer(c2)) %>% spark_apply(~ class(.x[[2]])) %>% pull(),
"integer"
)
expect_equivalent(
colnas_tbl %>%
mutate(c2 = as.integer(c2)) %>%
spark_apply(~ dplyr::mutate(.x, c1 = tolower(c1))) %>%
collect(),
colnas_tbl %>%
mutate(c2 = as.integer(c2)) %>%
mutate(c1 = tolower(c1)) %>%
collect()
)
})
test_that("can infer R package dependencies", {
fn1 <- function(x) {
library(utf8)
x + 1
}
expect_true("utf8" %in% sparklyr:::infer_required_r_packages(fn1))
fn2 <- function(x) {
require(utf8)
x + 2
}
expect_true("utf8" %in% sparklyr:::infer_required_r_packages(fn2))
fn3 <- function(x) {
requireNamespace("utf8")
x + 3
}
expect_true("utf8" %in% sparklyr:::infer_required_r_packages(fn3))
fn4 <- function(x) {
library("sparklyr", quietly = FALSE)
x + 4
}
expected_deps <- tools::package_dependencies(
"sparklyr", db = installed.packages(), recursive = TRUE
)
testthat::expect_setequal(
union(expected_deps$sparklyr, c("base", "sparklyr")),
sparklyr:::infer_required_r_packages(fn4)
)
}) |
context("ez_labels")
test_that("ez_labels works", {
expect_equal(ez_labels(1), "1")
expect_equal(ez_labels(1000), "1k")
expect_equal(ez_labels(2000000), "2m")
expect_equal(ez_labels(1234567), "1.234567m")
expect_equal(ez_labels(1234567, signif = 3), "1.23m")
expect_equal(ez_labels(c(10, 2), as_factor = TRUE), factor(c(10, 2), c("2", "10")))
expect_equal(superscript(321), "\u00B3\u00B2\u00B9")
}) |
context("GPModel_grouped_random_effects")
if(Sys.getenv("GPBOOST_ALL_TESTS") == "GPBOOST_ALL_TESTS"){
sim_rand_unif <- function(n, init_c=0.1){
mod_lcg <- 134456
sim <- rep(NA, n)
sim[1] <- floor(init_c * mod_lcg)
for(i in 2:n) sim[i] <- (8121 * sim[i-1] + 28411) %% mod_lcg
return(sim / mod_lcg)
}
n <- 1000
m <- 100
group <- rep(1,n)
for(i in 1:m) group[((i-1)*n/m+1):(i*n/m)] <- i
Z1 <- model.matrix(rep(1,n) ~ factor(group) - 1)
b1 <- qnorm(sim_rand_unif(n=m, init_c=0.546))
n_gr <- n/20
group2 <- rep(1,n)
for(i in 1:(n/n_gr)) group2[(1:n_gr)+n_gr*(i-1)] <- 1:n_gr
Z2 <- model.matrix(rep(1,n)~factor(group2)-1)
b2 <- qnorm(sim_rand_unif(n=length(unique(group2)), init_c=0.46))
x <- cos((1:n-n/2)^2*5.5*pi/n)
Z3 <- diag(x) %*% Z1
b3 <- qnorm(sim_rand_unif(n=m, init_c=0.69))
xi <- sqrt(0.5) * qnorm(sim_rand_unif(n=n, init_c=0.1))
X <- cbind(rep(1,n),sin((1:n-n/2)^2*2*pi/n))
beta <- c(2,2)
cluster_ids <- c(rep(1,0.4*n),rep(2,0.6*n))
test_that("single level grouped random effects model ", {
y <- as.vector(Z1 %*% b1) + xi
gp_model <- GPModel(group_data = group)
fit(gp_model, y = y, params = list(std_dev = TRUE, optimizer_cov = "fisher_scoring",
convergence_criterion = "relative_change_in_parameters"))
cov_pars <- c(0.49348532, 0.02326312, 1.22299521, 0.17995161)
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-6)
expect_equal(dim(gp_model$get_cov_pars())[2], 2)
expect_equal(dim(gp_model$get_cov_pars())[1], 2)
expect_equal(gp_model$get_num_optim_iter(), 6)
gp_model <- fitGPModel(group_data = group, y = y,
params = list(optimizer_cov = "gradient_descent", std_dev = FALSE,
lr_cov = 0.1, use_nesterov_acc = FALSE, maxit = 1000,
convergence_criterion = "relative_change_in_parameters"))
cov_pars_est <- as.vector(gp_model$get_cov_pars())
expect_lt(sum(abs(cov_pars_est-cov_pars[c(1,3)])),1E-5)
expect_equal(class(cov_pars_est), "numeric")
expect_equal(length(cov_pars_est), 2)
expect_equal(gp_model$get_num_optim_iter(), 9)
gp_model <- fitGPModel(group_data = group, y = y,
params = list(optimizer_cov = "gradient_descent", std_dev = FALSE,
lr_cov = 0.2, use_nesterov_acc = TRUE,
acc_rate_cov = 0.1, maxit = 1000,
convergence_criterion = "relative_change_in_parameters"))
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars[c(1,3)])),1E-5)
expect_equal(gp_model$get_num_optim_iter(), 10)
gp_model <- fitGPModel(group_data = group, y = y,
params = list(optimizer_cov = "gradient_descent", std_dev = FALSE,
lr_cov = 10, use_nesterov_acc = FALSE,
maxit = 1000, convergence_criterion = "relative_change_in_parameters"))
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars[c(1,3)])),1E-6)
expect_equal(gp_model$get_num_optim_iter(), 32)
gp_model <- fitGPModel(group_data = group, y = y,
params = list(optimizer_cov = "fisher_scoring", std_dev = TRUE,
convergence_criterion = "relative_change_in_log_likelihood"))
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-6)
expect_equal(gp_model$get_num_optim_iter(), 5)
gp_model <- fitGPModel(group_data = group, y = y,
params = list(optimizer_cov = "nelder_mead", std_dev = TRUE))
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-3)
expect_equal(gp_model$get_num_optim_iter(), 12)
ll <- gp_model$neg_log_likelihood(y=y,cov_pars=gp_model$get_cov_pars()[1,])
expect_lt(abs(ll-(1228.293)),1E-2)
gp_model <- GPModel(group_data = group)
group_test <- c(1,2,m+1)
expect_error(predict(gp_model, y=y, cov_pars = c(0.5,1.5)))
pred <- predict(gp_model, y=y, group_data_pred = group_test,
cov_pars = c(0.5,1.5), predict_cov_mat = TRUE)
expected_mu <- c(-0.1553877, -0.3945731, 0)
expected_cov <- c(0.5483871, 0.0000000, 0.0000000, 0.0000000,
0.5483871, 0.0000000, 0.0000000, 0.0000000, 2)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-6)
pred <- predict(gp_model, y=y, group_data_pred = group_test,
cov_pars = c(0.5,1.5), predict_var = TRUE)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$var)-expected_cov[c(1,5,9)])),1E-6)
gp_model <- fitGPModel(group_data = group, y = y,
params = list(optimizer_cov = "fisher_scoring",
convergence_criterion = "relative_change_in_parameters"))
group_test <- c(1,2,m+1)
pred <- predict(gp_model, group_data_pred = group_test, predict_cov_mat = TRUE)
expected_mu <- c(-0.1543396, -0.3919117, 0.0000000)
expected_cov <- c(0.5409198 , 0.0000000000, 0.0000000000, 0.0000000000,
0.5409198 , 0.0000000000, 0.0000000000, 0.0000000000, 1.7164805)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-6)
nll <- gp_model$neg_log_likelihood(cov_pars=c(0.1,1),y=y)
expect_lt(abs(nll-2282.073),1E-2)
gp_model <- GPModel(group_data = group)
opt <- optim(par=c(1,1), fn=gp_model$neg_log_likelihood, y=y, method="Nelder-Mead")
expect_lt(sum(abs(opt$par-cov_pars[c(1,3)])),1E-3)
expect_lt(abs(opt$value-(1228.293)),1E-2)
expect_equal(as.integer(opt$counts[1]), 49)
set.seed(1)
shuffle_ind <- sample.int(n=n,size=n,replace=FALSE)
gp_model <- GPModel(group_data = group[shuffle_ind])
fit(gp_model, y = y[shuffle_ind], params = list(optimizer_cov = "fisher_scoring", std_dev = TRUE,
convergence_criterion = "relative_change_in_parameters"))
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-6)
expect_equal(gp_model$get_num_optim_iter(), 6)
})
test_that("linear mixed effects model with grouped random effects ", {
y <- Z1 %*% b1 + X%*%beta + xi
gp_model <- fitGPModel(group_data = group,
y = y, X = X,
params = list(optimizer_cov = "fisher_scoring",
optimizer_coef = "wls", std_dev = TRUE,
convergence_criterion = "relative_change_in_parameters"))
cov_pars <- c(0.49205230, 0.02319557, 1.22064076, 0.17959832)
coef <- c(2.07499902, 0.11269252, 1.94766255, 0.03382472)
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-6)
expect_lt(sum(abs(as.vector(gp_model$get_coef())-coef)),1E-6)
expect_equal(gp_model$get_num_optim_iter(), 7)
group_test <- c(1,2,m+1)
X_test <- cbind(rep(1,3),c(-0.5,0.2,0.4))
expect_error(predict(gp_model,group_data_pred = group_test))
pred <- predict(gp_model, group_data_pred = group_test,
X_pred = X_test, predict_cov_mat = TRUE)
expected_mu <- c(0.886494, 2.043259, 2.854064)
expected_cov <- c(0.5393509 , 0.0000000000, 0.0000000000, 0.0000000000,
0.5393509 , 0.0000000000, 0.0000000000, 0.0000000000, 1.712693)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-6)
gp_model <- fitGPModel(group_data = group,
y = y, X = X,
params = list(optimizer_cov = "gradient_descent", maxit=1000, std_dev = TRUE,
optimizer_coef = "gradient_descent", lr_coef=1, use_nesterov_acc=TRUE))
cov_pars <- c(0.49205012, 0.02319547, 1.22089504, 0.17963425)
coef <- c(2.07513927, 0.11270379, 1.94322756, 0.03382466)
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-6)
expect_lt(sum(abs(as.vector(gp_model$get_coef())-coef)),1E-6)
expect_equal(gp_model$get_num_optim_iter(), 110)
gp_model <- fitGPModel(group_data = group,
y = y, X = X,
params = list(optimizer_cov = "nelder_mead",
optimizer_coef = "nelder_mead", std_dev = TRUE))
cov_pars <- c(0.47524382, 0.02240321, 2.38806490, 0.34445163)
coef <- c(1.45083178, 0.15606729, 1.95360294, 0.03327804)
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-6)
expect_lt(sum(abs(as.vector(gp_model$get_coef())-coef)),1E-6)
expect_equal(gp_model$get_num_optim_iter(), 133)
gp_model <- fitGPModel(group_data = group,
y = y, X = X,
params = list(optimizer_cov = "bfgs", std_dev = TRUE))
cov_pars <- c(0.49205229, 0.02319557, 1.22064060, 0.17959830)
coef <- c(2.07499895, 0.11269251, 1.94766254, 0.03382472)
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-6)
expect_lt(sum(abs(as.vector(gp_model$get_coef())-coef)),1E-6)
expect_equal(gp_model$get_num_optim_iter(), 12)
})
test_that("Multiple grouped random effects ", {
y <- Z1%*%b1 + Z2%*%b2 + xi
gp_model <- fitGPModel(group_data = cbind(group,group2), y = y,
params = list(optimizer_cov = "fisher_scoring", std_dev = TRUE))
expected_values <- c(0.49792062, 0.02408196, 1.21972166, 0.18357646, 1.06962710, 0.22567292)
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-expected_values)),1E-6)
expect_equal(gp_model$get_num_optim_iter(), 5)
group_data_pred = cbind(c(1,1,m+1),c(2,1,length(group2)+1))
pred <- gp_model$predict(y = y, group_data_pred=group_data_pred, predict_var = TRUE)
expected_mu <- c(0.7509175, -0.4208015, 0.0000000)
expected_var <- c(0.5677178, 0.5677178, 2.7872694)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$var)-expected_var)),1E-4)
gp_model <- GPModel(group_data = cbind(group,group2))
pred <- gp_model$predict(y = y, group_data_pred=group_data_pred,
cov_pars = c(0.1,1,2), predict_cov_mat = TRUE)
expected_mu <- c(0.7631462, -0.4328551, 0.000000000)
expected_cov <- c(0.114393721, 0.009406189, 0.0000000, 0.009406189,
0.114393721 , 0.0000000, 0.0000000, 0.0000000, 3.100000000)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-3)
group_data_pred_in = cbind(c(1,1),c(2,1))
pred <- gp_model$predict(y = y, group_data_pred=group_data_pred_in,
cov_pars = c(0.1,1,2), predict_cov_mat = TRUE)
expected_mu <- c(0.7631462, -0.4328551)
expected_cov <- c(0.114393721, 0.009406189, 0.009406189, 0.114393721)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-3)
group_data_pred_out = cbind(c(m+1,m+1,m+1),c(length(group2)+1,length(group2)+2,length(group2)+1))
pred <- gp_model$predict(y = y, group_data_pred=group_data_pred_out,
cov_pars = c(0.1,1,2), predict_cov_mat = TRUE)
expected_mu <- c(rep(0,3))
expected_cov <- c(3.1, 1.0, 3.0, 1.0, 3.1, 1.0, 3.0, 1.0, 3.1)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-3)
y <- Z1%*%b1 + Z2%*%b2 + Z3%*%b3 + xi
gp_model <- fitGPModel(group_data = cbind(group,group2),
group_rand_coef_data = x,
ind_effect_group_rand_coef = 1,
y = y,
params = list(optimizer_cov = "fisher_scoring", maxit=5, std_dev = TRUE))
expected_values <- c(0.49554952, 0.02546769, 1.24880860, 0.18983953, 1.05505134, 0.22337199, 1.13840014, 0.17950490)
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-expected_values)),1E-6)
expect_equal(gp_model$get_num_optim_iter(), 5)
gp_model <- GPModel(group_data = cbind(group,group2),
group_rand_coef_data = x, ind_effect_group_rand_coef = 1)
group_data_pred = cbind(c(1,1,m+1),c(2,1,length(group2)+1))
group_rand_coef_data_pred = c(0,10,0.3)
expect_error(gp_model$predict(group_data_pred = group_data_pred,
cov_pars = c(0.1,1,2,1.5), y=y))
pred <- gp_model$predict(y = y, group_data_pred=group_data_pred,
group_rand_coef_data_pred=group_rand_coef_data_pred,
cov_pars = c(0.1,1,2,1.5), predict_cov_mat = TRUE)
expected_mu <- c(0.7579961, -0.2868530, 0.000000000)
expected_cov <- c(0.11534086, -0.01988167, 0.0000000, -0.01988167, 2.4073302,
0.0000000, 0.0000000, 0.0000000, 3.235)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-3)
pred <- gp_model$predict(y = y, group_data_pred=group_data_pred,
group_rand_coef_data_pred=group_rand_coef_data_pred,
cov_pars = c(0.1,1,2,1.5), predict_var = TRUE)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$var)-expected_cov[c(1,5,9)])),1E-3)
gp_model <- fitGPModel(group_data = cbind(group,group2),
group_rand_coef_data = x,
ind_effect_group_rand_coef = 1,
y = y,
params = list(optimizer_cov = "gradient_descent", std_dev = FALSE))
cov_pars <- c(0.4958303, 1.2493181, 1.0543343, 1.1388604 )
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-6)
expect_equal(gp_model$get_num_optim_iter(),8)
gp_model <- fitGPModel(group_data = cbind(group,group2),
group_rand_coef_data = x,
ind_effect_group_rand_coef = 1,
y = y,
params = list(optimizer_cov = "nelder_mead", std_dev = FALSE))
cov_pars <- c(0.4959521, 1.2408579, 1.0560989, 1.1373089 )
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-6)
gp_model <- fitGPModel(group_data = cbind(group,group2),
group_rand_coef_data = x,
ind_effect_group_rand_coef = 1,
y = y,
params = list(optimizer_cov = "bfgs", std_dev = FALSE))
cov_pars <- c(0.4955502, 1.2488000, 1.0550351, 1.1383709 )
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-6)
nll <- gp_model$neg_log_likelihood(cov_pars=c(0.1,1,2,1.5),y=y)
expect_lt(abs(nll-2335.803),1E-2)
})
test_that("not constant cluster_id's for grouped random effects ", {
y <- Z1 %*% b1 + xi
gp_model <- fitGPModel(group_data = group, cluster_ids = cluster_ids,
y = y,
params = list(optimizer_cov = "fisher_scoring", maxit=100, std_dev = TRUE,
convergence_criterion = "relative_change_in_parameters"))
expected_values <- c(0.49348532, 0.02326312, 1.22299521, 0.17995161)
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-expected_values)),1E-6)
expect_equal(gp_model$get_num_optim_iter(), 6)
gp_model <- fitGPModel(group_data = group, cluster_ids = cluster_ids,
y = y,
params = list(optimizer_cov = "gradient_descent", std_dev = TRUE,
lr_cov = 0.1, use_nesterov_acc = FALSE, maxit = 1000,
convergence_criterion = "relative_change_in_parameters"))
cov_pars_expected <- c(0.49348532, 0.02326312, 1.22299520, 0.17995161)
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars_expected)),1E-6)
expect_equal(gp_model$get_num_optim_iter(), 9)
group_data_pred = c(1,1,m+1)
cluster_ids_pred = c(1,3,1)
gp_model <- GPModel(group_data = group, cluster_ids = cluster_ids)
expect_error(gp_model$predict(group_data_pred = group_data_pred,
cov_pars = c(0.75,1.25), y=y))
pred <- gp_model$predict(y = y, group_data_pred = group_data_pred,
cluster_ids_pred = cluster_ids_pred,
cov_pars = c(0.75,1.25), predict_cov_mat = TRUE)
expected_mu <- c(-0.1514786, 0.000000, 0.000000)
expected_cov <- c(0.8207547, 0.000000, 0.000000, 0.000000,
2.000000, 0.000000, 0.000000, 0.000000, 2.000000)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-6)
cluster_ids_string <- paste0(as.character(cluster_ids),"_s")
gp_model <- fitGPModel(group_data = group, cluster_ids = cluster_ids_string,
y = y,
params = list(optimizer_cov = "fisher_scoring", maxit=100, std_dev = TRUE,
convergence_criterion = "relative_change_in_parameters"))
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars_expected)),1E-6)
expect_equal(gp_model$get_num_optim_iter(), 6)
group_data_pred = c(1,1,m+1)
cluster_ids_pred_string = paste0(as.character(c(1,3,1)),"_s")
pred <- gp_model$predict(y = y, group_data_pred = group_data_pred,
cluster_ids_pred = cluster_ids_pred_string,
cov_pars = c(0.75,1.25), predict_cov_mat = TRUE)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-6)
group_data_pred = c(1,1,m,m)
cluster_ids_pred = c(2,2,1,2)
gp_model <- GPModel(group_data = group, cluster_ids = cluster_ids)
pred <- gp_model$predict(y = y, group_data_pred = group_data_pred,
cluster_ids_pred = cluster_ids_pred,
cov_pars = c(0.75,1.25), predict_var = TRUE)
expected_mu <- c(rep(0,3), 1.179557)
expected_var <- c(rep(2,3), 0.8207547)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$var)-expected_var)),1E-6)
group_data_pred = c(1,1,m,m)
cluster_ids_pred_string = paste0(as.character(c(2,2,1,2)),"_s")
gp_model <- GPModel(group_data = group, cluster_ids = cluster_ids_string)
pred <- gp_model$predict(y = y, group_data_pred = group_data_pred,
cluster_ids_pred = cluster_ids_pred_string,
cov_pars = c(0.75,1.25), predict_var = TRUE)
expect_lt(sum(abs(pred$mu-expected_mu)),1E-6)
expect_lt(sum(abs(as.vector(pred$var)-expected_var)),1E-6)
y <- Z1%*%b1 + Z3%*%b3 + xi
gp_model <- fitGPModel(group_data = group,
cluster_ids = cluster_ids,
group_rand_coef_data = x,
ind_effect_group_rand_coef = 1,
y = y,
params = list(optimizer_cov = "gradient_descent", std_dev = FALSE,
lr_cov = 0.1, use_nesterov_acc = TRUE, maxit = 1000,
convergence_criterion = "relative_change_in_parameters"))
expected_values <- c(0.4927786, 1.2565095, 1.1333656)
expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-expected_values)),1E-6)
expect_equal(gp_model$get_num_optim_iter(), 14)
})
} |
mat.mc <- function (inModern,modTaxa=c(NULL,NULL),probs=c(0.05,0.025,0.01,0.001),freqint=seq(0, 2, 0.02),sampleSize=length(inModern[,1]),method="sawada",withReplace=T,counts=F)
{
outvec = vector("numeric")
if (counts) {
inModern[,modTaxa]=inModern[,modTaxa]/rowSums(inModern[,modTaxa])
}
if(method == "sawada") {
set1=inModern[sample(1:length(inModern[,1]),sampleSize,withReplace),modTaxa]
set2=inModern[sample(1:length(inModern[,1]),sampleSize,withReplace),modTaxa]
set1=sqrt(set1)
set2=sqrt(set2)
set3=set1-set2
set3=set3*set3
sqvec=rowSums(set3)
}
else if (method=="bartlein"){
sqvec = mattools.roc(inModern,inModern,modTaxa,numAnalogs=length(inModern[,1]))
}
tlen=length(sqvec)
for (i in freqint) {
outvec = c(outvec, length(sqvec[sqvec <= i])/tlen)
}
cumcurve = cbind(sqdist=freqint, problteq=outvec)
critvalue=approx(cumcurve[,2],cumcurve[,1],probs)
list(sqdist=sqvec,cumcurve=cumcurve,cutoffs=critvalue,method=method,samplesize=sampleSize,replacement=withReplace,probabilities=probs,wascounts=counts)
} |
shorten_url.semnar <- function(object, service = "Is.gd") {
service <- match.arg(service, choices = c("Is.gd", "V.gd"))
fun <- switch(service,
"Is.gd" = isgd_LinksShorten,
"V.gd" = vgd_LinksShorten)
object$long_link <- object$link
object$link <- sapply(object$link, function(link) {
out <- fun(link)
ifelse(is.null(out), NA, out)
})
object
} |
covLCA <-
function(formula1,formula2,data,nclass=2,maxiter=1000,tol=1e-10,
beta.start=NULL,alpha.start=NULL,gamma.start=NULL,beta.auto=TRUE,alpha.auto=TRUE,gamma.auto=TRUE,nrep=1,verbose=TRUE,calc.se=TRUE)
{
starttime <- Sys.time()
mf1 <- model.response(model.frame(formula1,data,na.action=NULL))
mf2 <- model.response(model.frame(formula2,data,na.action=NULL))
if (any((as.numeric(mf1)-as.numeric(mf2))!=0,na.rm=TRUE))
{
stop("\n ALERT: manifest variables in both formulae must be identical. \n \n")
ret <- NULL
}
if (any(mf1<1,na.rm=TRUE) | any(round(mf1) != mf1,na.rm=TRUE)){
cat("\n ALERT: some manifest variables contain values that are not
positive integers. For covLCA to run, please recode categorical
outcome variables to increment from 1 to the maximum number of
outcome categories for each variable. \n \n")
ret <- NULL}else
{
mframe1 <- model.frame(formula1,data,na.action=NULL)
miss1=is.na(mframe1)
ind.miss1=(apply(miss1,1,sum)>0)
mframe2 <- model.frame(formula2,data,na.action=NULL)
miss2=is.na(mframe2)
ind.miss2=(apply(miss2,1,sum)>0)
mframe1=mframe1[!(ind.miss1)& !(ind.miss2),]
mframe2=mframe2[!(ind.miss1)& !(ind.miss2),]
y <- model.response(mframe1)
if (any(sapply(lapply(as.data.frame(y),table),length)==1))
{
y <- y[,!(sapply(apply(y,2,table),length)==1)]
cat("\n ALERT: at least one manifest variable contained only one outcome category, and has been removed from the analysis. \n \n")
}
x <- model.matrix(formula1,mframe1)
z <- model.matrix(formula2,mframe2)
if (ncol(z)==2){z <- array(z[,2],dim=c(dim(z)[1],1))}else {z <- z[,2:dim(z)[2]]}
N <- nrow(y)
J <- ncol(y)
K.j <- t(matrix(apply(y,2,max)))
if (length(unique(as.vector(K.j)))>1)
{
cat("\n ALERT: all manifest variables must have the same number of outcome categories. \n \n")
ret <- NULL
}
R <- nclass
S1 <- ncol(x)
S2=ncol(z)
eflag <- FALSE
probs.start.ok <- TRUE
ret <- list()
ret$llik <- -Inf
ret$attempts <- NULL
for (repl in 1:nrep)
{
error <- TRUE; firstrun <- TRUE
bet <- beta.init <- beta.start
alph <- alpha.init <- alpha.start
gamm <- gamma.init <- gamma.start
if (beta.auto)
{
bet <- covLCA.initialBeta(y,R,x)
beta.initAuto <- bet
}
if (alpha.auto)
{
alphgamm=covLCA.initialAlphaGamma(y,z,R,K.j,S2)
alph <- alphgamm$Alpha
alpha.initAuto <- alph
}
if (gamma.auto)
{
gamm <- alphgamm$Gamma
gamma.initAuto <- gamm
}
while (error)
{
error <- FALSE
if ((is.null(beta.start)&!beta.auto) | (!firstrun) | (repl>1))
{
bet <- beta.init <- rnorm(S1*(R-1))
}
if ((is.null(alpha.start)& !alpha.auto) | (!firstrun) | (repl>1))
{
alph <- alpha.init <- array(data=rnorm(J*S2*(K.j[1]-1)),dim=c(J,S2*(K.j[1]-1)))
}
if ((is.null(gamma.start)& !gamma.auto) | (!firstrun) | (repl>1))
{
gamm <- gamma.init <- array(data=rnorm(J*K.j[1]*R), dim=c(J,(K.j[1]-1)*R))
}
prior <- covLCA.updatePrior(bet,x,R)
probs <- covLCA.updateCond(alph,gamm,z,R,J,K.j,S2,N)
iter <- 1
llik <- matrix(NA,nrow=maxiter,ncol=1)
llik[iter] <- -Inf
dll <- Inf
while ((iter <= maxiter) & (dll > tol) & (!error))
{
iter <- iter+1
cat("Iteration number ",iter,"\n")
flush.console()
cat("\n")
rgivy <- covLCA.postClass(prior,probs,y,K.j)
dd.bet <- covLCA.dQdBeta(rgivy,prior,x)
bet <- bet + ginv(-dd.bet$hess) %*% dd.bet$grad
prior <- covLCA.updatePrior(bet,x,R)
for (m in 1:J)
{
dd.gam <- covLCA.dQdGamma(rgivy,probs,y,K.j,m)
dd.alph <- covLCA.dQdAlpha(rgivy,probs,z,K.j,m,y,S2)
dd.alph.gam <- covLCA.dQdAlphaGamma(rgivy,probs,z,K.j,m,S2)
hess1=cbind(dd.gam$hess,dd.alph.gam)
hess2=cbind(t(dd.alph.gam),dd.alph$hess)
hess=rbind(hess1,hess2)
new <- c(gamm[m,],alph[m,]) + ginv(-hess) %*% c(dd.gam$grad,dd.alph$grad)
gamm[m,] <- new[1:dim(gamm)[2]]
alph[m,] <- new[(dim(gamm)[2]+1):length(new)]
}
probs <- covLCA.updateCond(alph,gamm,z,R,J,K.j,S2,N)
llik[iter] <- sum(log(rowSums(prior*covLCA.ylik(probs,y,K.j))))
cat("Llik=",llik[iter],"\n")
dll <- llik[iter]-llik[iter-1]
cat("dll=",dll,"\n")
if (is.na(dll))
{
error <- TRUE
}else if ((S1>1) & (dll < -1e-7))
{
error <- TRUE
}
}
rgivy2 <- covLCA.postClass(prior,probs,y,K.j)
if (!error)
{
if (calc.se)
{
ParamVar <- covLCA.paramVariance(prior,probs,rgivy2,R,S1,S2,J,K.j,x,y,z,N)
}
else
{
ParamVar <- NA
}
} else
if (error)
{
eflag <- TRUE
}
firstrun <- FALSE
}
ret$attempts <- c(ret$attempts,llik[iter])
if (llik[iter] > ret$llik)
{
ret$llik <- llik[iter]
ret$beta.start <- beta.init
ret$alpha.start <- alpha.init
ret$gamma.start <- gamma.init
ret$beta.auto <- beta.auto
ret$alpha.auto <- alpha.auto
ret$gamma.auto <- gamma.auto
if(beta.auto) ret$beta.initAuto <- beta.initAuto
if(alpha.auto)ret$alpha.initAuto <- alpha.initAuto
if(gamma.auto)ret$gamma.initAuto <- gamma.initAuto
ret$probs <- probs
ret$prior <- prior
ret$posterior <- rgivy
ret$posterior2 <- rgivy2
ret$predclass <- apply(ret$posterior,1,which.max)
ret$P <- colMeans(ret$posterior)
names(ret$P) <- paste("Latent class",1:R,sep=" ")
ret$numiter <- iter-1
if (S1>1)
{
b <- matrix(bet,nrow=S1)
rownames(b) <- colnames(x)
colnames(b) <- paste(1:(R-1),"vs",R,sep=" ")
ret$coeffBeta <- b
ret$param.se <- sqrt(diag(ParamVar))
ret$param.V <- ParamVar
}
if (S2>=1)
{
g <- gamm
rownames(g) <- colnames(y)
colnames(g) <- paste("LC ",rep(seq(1,R),rep((K.j[1]-1),R)),", k=",rep(1:(K.j[1]-1),R),sep="")
ret$coeffGamma <- g
a <- alph
rownames(a) <- colnames(y)
colnames(a) <- paste("Var. ",rep(seq(1,S2),rep((K.j[1]-1),S2)),", k=",rep(1:(K.j[1]-1),S2),sep="")
ret$coeffAlpha <- a
ret$meanProbs=covLCA.meanCond(a,g,z,J,K.j,R,S2,N)
dimnames(ret$meanProbs)[[1]]=colnames(y)
dimnames(ret$meanProbs)[[2]]=paste("Pr(",1:K.j[1],")",sep="")
dimnames(ret$meanProbs)[[3]]=paste("Latent class",1:R,sep=" ")
}
ret$eflag <- eflag
}
if (nrep>1 & verbose) { cat("Model ",repl,": llik = ",llik[iter]," ... best llik = ",ret$llik,"\n",sep=""); flush.console() }
}
ret$npar <- S1*(R-1)+S2*J*(K.j[1]-1)+J*(K.j[1]-1)*R
ret$aic <- (-2 * ret$llik) + (2 * ret$npar)
ret$bic <- (-2 * ret$llik) + (log(N) * ret$npar)
ret$Nobs <- sum(rowSums(y==0)==0)
ret$identifiability <- covLCA.identifiability(J,K.j,R,x,z,ret$npar,ret$coeffAlpha,ret$coeffBeta,ret$coeffGamma)
ret$y <- data.frame(y)
ret$x <- data.frame(x)
ret$z <- data.frame(z)
ret$N <- N
ret$maxiter <- maxiter
if (ret$numiter==ret$maxiter) cat("ALERT: iterations finished, MAXIMUM LIKELIHOOD NOT FOUND \n \n")
ret$resid.df <- min(ret$N,(prod(K.j)-1))-ret$npar
class(ret) <- "covLCA"
ret$time <- Sys.time()-starttime
}
return(ret)
} |
.plotSpace <- function(asp=1, legend.mar = 3.1, legend.width = 0.5, legend.shrink = 0.5) {
pars <- graphics::par()
char.size <- pars$cin[1] / pars$din[1]
offset <- char.size * pars$mar[4]
legend.width <- char.size * legend.width
legend.mar <- legend.mar * char.size
legendPlot <- pars$plt
legendPlot[2] <- 1 - legend.mar
legendPlot[1] <- legendPlot[2] - legend.width
pr <- (legendPlot[4] - legendPlot[3]) * ((1 - legend.shrink)/2)
legendPlot[4] <- legendPlot[4] - pr
legendPlot[3] <- legendPlot[3] + pr
bp <- pars$plt
bp[2] <- min(bp[2], legendPlot[1] - offset)
aspbp = (bp[4]-bp[3]) / (bp[2]-bp[1])
adj = aspbp / asp
if (adj < 1) {
adjust = (bp[4]-bp[3]) - ((bp[4]-bp[3]) * adj)
} else {
adjust = (bp[4]-bp[3]) / adj - ((bp[4]-bp[3]))
}
adjust <- adjust / 2
bp[3] <- bp[3] + adjust
bp[4] <- bp[4] - adjust
dp <- legendPlot[2] - legendPlot[1]
legendPlot[1] <- min(bp[2] + 0.5 * offset, legendPlot[1])
legendPlot[2] <- legendPlot[1] + dp
return(list(legendPlot = legendPlot, mainPlot = bp))
}
.plotLegend <- function(z, col, legend.at='classic', lab.breaks = NULL, axis.args = NULL, legend.lab = NULL, legend.args = NULL, ...) {
horizontal=FALSE
ix <- 1
zlim <- range(z, na.rm = TRUE, finite=TRUE)
zrange <- zlim[2]-zlim[1]
if (zrange > 10) { decs <- 0
} else if (zrange > 1) { decs <- 1
} else { decs <- ceiling(abs(log10(zrange)) + 1) }
pow <- 10^decs
minz <- floor(zlim[1] * pow) / pow
maxz <- ceiling(zlim[2] * pow) / pow
zrange <- maxz - minz
nlevel = length(col)
binwidth <- c(0, 1:nlevel * (1/nlevel))
iy <- minz + zrange * binwidth
iz <- matrix(iy, nrow = 1, ncol = length(iy))
breaks <- list(...)$breaks
if (!is.null(breaks) & !is.null(lab.breaks)) {
axis.args <- c(list(side = ifelse(horizontal, 1, 4), mgp = c(3, 1, 0), las = ifelse(horizontal, 0, 2), at = breaks, labels = lab.breaks), axis.args)
} else {
if (legend.at == 'quantile') {
z <- z[is.finite(z)]
at = stats::quantile(z, names=F, na.rm=TRUE)
axis.args <- c(list(side = ifelse(horizontal, 1, 4), mgp = c(3, 1, 0), las = ifelse(horizontal, 0, 2), at=at), axis.args)
} else {
at <- graphics::axTicks(2, c(minz, maxz, 4))
}
at <- round(at, decs)
axis.args <- c(list(side = ifelse(horizontal, 1, 4), mgp = c(3, 1, 0), las = ifelse(horizontal, 0, 2), at=at), axis.args)
}
if (!horizontal) {
if (is.null(breaks)) {
image(ix, iy, iz, xaxt="n", yaxt="n", xlab = "", ylab = "", col = col)
} else {
image(ix, iy, iz, xaxt="n", yaxt="n", xlab = "", ylab = "", col = col, breaks = breaks)
}
} else {
if (is.null(breaks)) {
image(iy, ix, t(iz), xaxt = "n", yaxt = "n", xlab = "", ylab = "", col = col)
} else {
image(iy, ix, t(iz), xaxt = "n", yaxt = "n", xlab = "", ylab = "", col = col, breaks = breaks)
}
}
axis.args = c(axis.args, cex.axis=0.75, tcl=-0.15, list(mgp=c(3, 0.4, 0)) )
do.call("axis", axis.args)
graphics::box()
if (!is.null(legend.lab)) {
legend.args <- list(text = legend.lab, side=3, line=0.75)
}
if (!is.null(legend.args)) {
}
}
.plot2 <- function(x, maxpixels=100000, col=rev(terrain.colors(25)), xlab='', ylab='', asp, box=TRUE, add=FALSE, legend=TRUE, legend.at='', ...) {
if (!add & missing(asp)) {
if (couldBeLonLat(x)) {
ym <- mean(x@extent@ymax + x@extent@ymin)
asp <- min(5, 1/cos((ym * pi)/180))
} else {
asp = 1
}
}
plotArea <- .plotSpace(asp)
x <- sampleRegular(x, maxpixels, asRaster=TRUE, useGDAL=TRUE)
xticks <- graphics::axTicks(1, c(xmin(x), xmax(x), 4))
yticks <- graphics::axTicks(2, c(ymin(x), ymax(x), 4))
if (xres(x) %% 1 == 0) xticks = round(xticks)
if (yres(x) %% 1 == 0) yticks = round(yticks)
y <- yFromRow(x, nrow(x):1)
z <- t((getValues(x, format='matrix'))[nrow(x):1,])
x <- xFromCol(x,1:ncol(x))
if (add) {
image(x=x, y=y, z=z, col=col, axes=FALSE, xlab=xlab, ylab=ylab, add=TRUE, ...)
} else {
if (legend) {
graphics::par(pty = "m", plt=plotArea$legendPlot, err = -1)
.plotLegend(z, col, legend.at=legend.at, ...)
graphics::par(new=TRUE, plt=plotArea$mainPlot)
}
image(x=x, y=y, z=z, col=col, axes=FALSE, xlab=xlab, ylab=ylab, asp=asp, ...)
graphics::axis(1, at=xticks, cex.axis=0.67, tcl=-0.3, mgp=c(3, 0.25, 0))
las = ifelse(max(nchar(as.character(yticks)))> 5, 0, 1)
graphics::axis(2, at=yticks, las = las, cex.axis=0.67, tcl=-0.3, mgp=c(3, 0.75, 0) )
if (box) graphics::box()
}
}
|
expected <- eval(parse(text="c(NA, 1, 0, 0, NA, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0)"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, NA, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, NA, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), .Dim = c(16L, 16L), .Dimnames = list(NULL, NULL)), 16, 16, FALSE)"));
.Internal(rowSums(argv[[1]], argv[[2]], argv[[3]], argv[[4]]));
}, o=expected); |
polycFast <- function(x,y,w,ML=FALSE) {
lnl <- function(xytab, cc, rc, corr) {
cc <- c(-Inf, cc, Inf)
rc <- c(-Inf, rc, Inf)
pm <- sapply(1:(length(cc)-1), function(c) {
sapply(1:(length(rc)-1), function(r) {
biv.nt.prob(df=Inf,
lower=c(cc[c], rc[r]),
upper=c(cc[c+1], rc[r+1]),
mean=c(0,0),
S=matrix(c(1,corr,corr,1), nrow=2, ncol=2, byrow=TRUE))
})
})
lnlFast(xytab, pm)
}
optf_all <- function(par, xytab) {
c1 <- ncol(xytab)-1
c2 <- c1 + nrow(xytab)-1
-1 * lnl(xytab, cc=fscale_cutsFast(par[1:c1]), rc=fscale_cutsFast(par[(c1+1):c2]), corr=fscale_corr(par[length(par)] ))
}
optf_corr <- function(par, xytab, theta1, theta2) {
c1 <- ncol(xytab)-1
c2 <- c1 + nrow(xytab)-1
-1 * lnl(xytab, cc=fscale_cutsFast(theta2), rc=fscale_cutsFast(theta1), corr=fscale_corr(par))
}
fscale_corr <- function(par) {
tanh(par)
}
xytab <- tableFast(x,y,w)
temp <- discord(xytab)
if(temp==-1 | temp == 1)
return(temp)
ux <- sort(unique(x))
cut1 <- imapThetaFast( sapply(ux[-length(ux)],function(z) qnorm(sum(w[x<=z])/sum(w)) ))
uy <- sort(unique(y))
cut2 <- imapThetaFast( sapply(uy[-length(uy)],function(z) qnorm(sum(w[y<=z])/sum(w)) ))
cor0 <- atanh(cor(as.numeric(x),as.numeric(y)))
if(ML) {
bob <- bobyqa(c(cut1,cut2,cor0), fn=optf_all, xytab=xytab)
return(fscale_corr(bob$par[length(bob$par)]))
} else {
opt <- optimize(optf_corr, interval=cor0+c(-3,3), xytab=xytab, theta1=cut1,theta2=cut2)
return( fscale_corr(opt$minimum))
}
} |
cdn_cooper<-function(order){
x<-get_cooper(order)
if(is.null(x$m)==F){
if(is.null(x$n)==F)
ret_value<-11
return(ret_value)
}else
return(NULL)
} |
isPositiveNumberOrInfVector <- function(argument, default = NULL, stopIfNot = FALSE, n = NA, message = NULL, argumentName = NULL) {
checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = FALSE, n = NA, zeroAllowed = TRUE, negativeAllowed = FALSE, positiveAllowed = TRUE, nonIntegerAllowed = TRUE, naAllowed = FALSE, nanAllowed = FALSE, infAllowed = TRUE, message = message, argumentName = argumentName)
} |
roofDiff = function(image, bandwidth, blur = FALSE){
if (!is.matrix(image))
stop("image data must be a matrix")
n1 = as.integer(dim(image)[1])
n2 = as.integer(dim(image)[2])
if (n1 != n2)
stop("image data must be a square matrix")
if (!is.numeric(bandwidth))
stop("bandwidth must be numeric")
if (as.integer(bandwidth) < 1)
stop("bandwidth must be a positive integer")
if (length(bandwidth) != 1)
stop("bandwidth must be a positive integer")
if (n1 + 2 * bandwidth + 2 > 600)
stop("bandwidth is too large or the resolution
of the image is too high.")
n1 = dim(image)[1]
z = matrix(as.double(image), ncol = n1)
k = as.integer(bandwidth)
if (blur == FALSE) {
out = .Fortran('roofDiff_denoise', n = as.integer(n1 - 1),
obsImg = z, bandwidth = as.integer(k), diff = z)
}
else {
out = .Fortran('roofDiff_deblur', n = as.integer(n1 - 1),
obsImg = z, bandwidth = as.integer(k), diff = z)
}
return(out$diff)
} |
`pvalcombination` <-
function(esets, classes, moderated=c("limma","SMVar","t")[1],BHth=0.05)
{
nbstudies=length(esets)
if (!(moderated %in% c("limma","SMVar","t")))
{
print("Wrong argument for \"moderated\" in pvalcombi->by default,
limma moderated t-tests will be used")
moderated="limma"
}
if (nbstudies != length(classes))
stop("Length of classes must be equal to length of esets.")
for (i in 1:nbstudies) {
if(length(which(apply(esets[[i]],1,FUN=function(x) sum(is.na(x)))[1:10]==dim(esets[[i]])[2]))!=0)
{stop("Please delete genes with complete missing data in at least one of the studies.
Only missing at random values are allowed in this package")}
if (!is.factor(classes[[i]])) {
classes[[i]] <- factor(classes[[i]])
}
if (nlevels(classes[[i]]) != 2) {
stop("Error: Each list in the argument \"classes\" must contain exactly 2 levels.")
}
else {
Ref <- levels(classes[[i]])[1]
classes[[i]] <- sapply(classes[[i]], function(x) ifelse(x ==
Ref, 0, 1))
}
}
listgd=vector("list", (nbstudies+3))
if (moderated=="limma")
{
for (i in 1:nbstudies)
{
group <- as.factor(classes[[i]])
design <- model.matrix(~-1 + group)
fit = lmFit(esets[[i]], design)
contrast.matrix <- makeContrasts("group0 - group1", levels = design)
fit2i <- contrasts.fit(fit, contrast.matrix)
fit2i <- eBayes(fit2i)
listgd[[i]]=which(p.adjust(fit2i$p.value,method="BH")<=BHth)
p1sidedLimma=pt(fit2i$t,df=(fit2i$df.prior+fit2i$df.residual))
assign(paste("p1sidedLimma",i,sep=""),p1sidedLimma)
}
tempvec=paste("p1sidedLimma",1:nbstudies,sep="")
}
if (moderated=="SMVar")
{
for (i in 1:nbstudies)
{
tempC1=esets[[i]][,which(classes[[i]]==1)]
tempC2=esets[[i]][,which(classes[[i]]==0)]
stati=as.data.frame(SMVar.unpaired(paste("gene",rep(1:dim(tempC1)[1],1),sep=""),
list(tempC1,tempC2),threshold=BHth))
listgd[[i]]=stati$GeneId[which(stati$AdjPValue<=BHth)]
p1sidedSMVartemp=as.vector(pt(stati$TestStat,stati$DegOfFreedom))
p1sidedSMVar=p1sidedSMVartemp[order(stati$GeneId)]
assign(paste("p1sidedSMVar",i,sep=""),p1sidedSMVar)
}
tempvec=paste("p1sidedSMVar",1:nbstudies,sep="")
}
if (moderated=="t")
{
for (i in 1:nbstudies)
{
sti=row.ttest.stat(esets[[i]][,which(classes[[i]]==1)],
esets[[i]][,which(classes[[i]]==0)])
p1sidedsti=pt(sti,df=(length(classes[[i]])-2))
assign(paste("p1sidedst",i,sep=""),p1sidedsti)
rpvalsti=2*(1-pt(abs(sti),df=(length(classes[[i]])-2)))
listgd[[i]]=which(p.adjust(rpvalsti,method="BH")<=BHth)
}
tempvec=paste("p1sidedst",1:nbstudies,sep="")
}
lsinglep=lapply(tempvec,FUN=function(x) get(x,inherits=TRUE))
nrep=unlist(lapply(classes,FUN=function(x)length(x)))
listgd[[(nbstudies+1)]]=unique(unlist(listgd[1:nbstudies]))
restempdirect=directpvalcombi(lsinglep,nrep,BHth)
listgd[[(nbstudies+2)]]=restempdirect$DEindices
listgd[[(nbstudies+3)]]=restempdirect$TestStatistic
names(listgd)=c(paste("study",1:nbstudies,sep=""),"AllIndStudies","Meta","TestStatistic")
restemp=IDDIRR(listgd$Meta,listgd$AllIndStudies)
print(restemp)
invisible(listgd)
} |
setClass(
"ODBCResult",
contains = "DBIResult",
slots= list(
connection="ODBCConnection",
sql="character",
state="environment"
)
)
is_done <- function(x) {
x@state$is_done
}
`is_done<-` <- function(x, value) {
x@state$is_done <- value
x
}
setMethod("dbFetch", "ODBCResult", function(res, n = -1, ...) {
result <- sqlQuery(res@connection@odbc, res@sql, max=ifelse(n==-1, 0, n))
is_done(res) <- TRUE
result
})
setMethod("dbHasCompleted", "ODBCResult", function(res, ...) {
is_done(res)
})
setMethod("dbClearResult", "ODBCResult", function(res, ...) {
name <- deparse(substitute(res))
is_done(res) <- FALSE
TRUE
})
NULL
setMethod("dbGetRowCount", "ODBCResult", function(res, ...) {
df <- sqlQuery(res@connection@odbc, res@sql)
nrow(df)
})
setMethod("dbGetStatement", "ODBCResult", function(res, ...) {
res@sql
})
setMethod("dbGetInfo", "ODBCResult", function(dbObj, ...) {
dbGetInfo(dbObj@connection)
})
setMethod("dbColumnInfo", "ODBCResult", function(res, ...) {
df <- sqlQuery(res@connection@odbc, res@sql, max=1)
data_type <- sapply(df, class)
data.frame(
name=colnames(df),
data.type=data_type,
field.type=-1,
len=-1,
precision=-1,
scale=-1,
nullOK=sapply(df, function(x){any(is.null(x))})
)
}) |
tam_linking_function_haebara_loss <- function(x, type, pow_rob_hae=1, eps=1e-4)
{
if (type=="Hae"){
y <- x^2
}
if (type=="RobHae"){
y <- (x^2 + eps)^(pow_rob_hae/2)
}
return(y)
} |
qat_call_lim_rule <-
function(measurement_vector, workflowlist_part, element=-999, time=NULL, height= NULL, lat=NULL, lon=NULL, vec1=NULL,vec2=NULL,vec3=NULL,vec4=NULL,resultlist=list(), resultlistcounter=1) {
if(!is.null(workflowlist_part$minimum_vector) || !is.null(workflowlist_part$maximum_vector)) {
if (is.null(workflowlist_part$minimum_vector)) {
min_vec <- measurement_vector - 1
} else {
if(workflowlist_part$minimum_vector=='vec1') {
min_vec <- vec1
}
if(workflowlist_part$minimum_vector=='vec2') {
min_vec <- vec2
}
if(workflowlist_part$minimum_vector=='vec3') {
min_vec <- vec3
}
if(workflowlist_part$minimum_vector=='vec4') {
min_vec <- vec4
}
}
if (is.null(workflowlist_part$maximum_vector)) {
max_vec <- measurement_vector + 1
} else {
if(workflowlist_part$maximum_vector=='vec1') {
max_vec <- vec1
}
if(workflowlist_part$maximum_vector=='vec2') {
max_vec <- vec2
}
if(workflowlist_part$maximum_vector=='vec3') {
max_vec <- vec3
}
if(workflowlist_part$maximum_vector=='vec4') {
max_vec <- vec4
}
}
if (is.null(dim(measurement_vector))) {
resultlist[[resultlistcounter <- resultlistcounter+1]] <- list(element=element, method='lim_dynamic', result =qat_analyse_lim_rule_dynamic_1d(measurement_vector, min_vec, max_vec,workflowlist_part$minimum_vector_name, workflowlist_part$maximum_vector_name, workflowlist_part$minimum_vector, workflowlist_part$maximum_vector))
}
if (length(dim(measurement_vector))==2) {
resultlist[[resultlistcounter <- resultlistcounter+1]] <- list(element=element, method='lim_dynamic', result =qat_analyse_lim_rule_dynamic_2d(measurement_vector, min_vec, max_vec,workflowlist_part$minimum_vector_name, workflowlist_part$maximum_vector_name, workflowlist_part$minimum_vector, workflowlist_part$maximum_vector))
}
}
if(!is.null(workflowlist_part$minimum_value) || !is.null(workflowlist_part$maximum_value)) {
if (is.null(workflowlist_part$minimum_value)) {
min_val <- min(measurement_vector) - 1
} else {
min_val <- as.numeric(workflowlist_part$minimum_value)
}
if (is.null(workflowlist_part$maximum_value)) {
max_val <- max(measurement_vector) + 1
} else {
max_val <- as.numeric(workflowlist_part$maximum_value)
}
if (mode(min_val)=="list") {
min_val <- as.numeric(min_val$value)
}
if (mode(max_val)=="list") {
max_val <- as.numeric(max_val$value)
}
if (is.null(dim(measurement_vector))) {
resultlist[[resultlistcounter <- resultlistcounter+1]] <- list(element=element, method='lim_static', result=qat_analyse_lim_rule_static_1d(measurement_vector, min_val, max_val))
}
if (length(dim(measurement_vector))==2) {
resultlist[[resultlistcounter <- resultlistcounter+1]] <- list(element=element, method='lim_static', result=qat_analyse_lim_rule_static_2d(measurement_vector, min_val, max_val))
}
}
if(!is.null(workflowlist_part$sigma_factor)) {
sigma_factor <- as.numeric(workflowlist_part$sigma_factor)
if (mode(sigma_factor)=="list") {
sigma_factor <- as.numeric(as.character(workflowlist_part$sigma_factor)[6])
}
if (is.null(dim(measurement_vector))) {
resultlist[[resultlistcounter <- resultlistcounter+1]] <- list(element=element, method='lim_sigma', result=qat_analyse_lim_rule_sigma_1d(measurement_vector,sigma_factor))
}
if (length(dim(measurement_vector)) ==2) {
resultlist[[resultlistcounter <- resultlistcounter+1]] <- list(element=element, method='lim_sigma', result=qat_analyse_lim_rule_sigma_2d(measurement_vector,sigma_factor))
}
}
return(resultlist)
} |
rf_prep <- function(x, y,...){
rf <-
randomForest(x,
y,
localImp = TRUE,
proximity = TRUE,
...)
return(list(rf = rf, x = x, y = y))
} |
download.file2 <- function(...) {
Call <- as.list(match.call(download.file))
Call[[1]] <- as.symbol("download.file")
the_url <- eval.parent(Call[["url"]])
Call[["url"]] <- the_url
Call[["quiet"]] <- TRUE
destfile <- eval.parent(Call[["destfile"]])
tmpfile <- tempfile()
on.exit(unlink(tmpfile))
Call[["destfile"]] <- tmpfile
retval <- try(eval.parent(as.call(Call)), silent = TRUE)
if (inherits(retval, "try-error") || retval != 0 ||
!file.exists(tmpfile) || file.info(tmpfile)[["size"]] == 0) {
success <- FALSE
for (method in c("wget", "curl")) {
sw <- Sys.which(method)
if (is.na(sw) || !grepl(method, sw, fixed = TRUE)) {
next
}
Call[["method"]] <- method
retval <- try(eval.parent(as.call(Call)), silent = TRUE)
if (!inherits(retval, "try-error") && retval == 0 &&
file.exists(tmpfile) && file.info(tmpfile)[["size"]] > 0) {
success <- TRUE
break
}
}
if (!success &&
!inherits(try(loadNamespace("RCurl"), silent = TRUE),
"try-error")) {
bytes <- try(RCurl::getBinaryURL(the_url), silent = TRUE)
if (!inherits(bytes, "try-error")) {
if (length(bytes) == 0L &&
grepl("^[hH][tT][tT][pP]:", the_url)) {
url2 <- sub("^[hH][tT][tT][pP]", "https", the_url)
bytes <- try(RCurl::getBinaryURL(url2), silent = TRUE)
}
if (!inherits(bytes, "try-error") && length(bytes) > 0L) {
writeBin(bytes, tmpfile)
success <- TRUE
}
}
}
} else {
success <- TRUE
}
if (success) {
file.copy(tmpfile, destfile, overwrite = TRUE)
invisible(0)
} else {
warning(gettextf("could not download %s", the_url),
domain = NA)
invisible(1)
}
}
fromJSON2 <- function(...) {
Call <- as.list(match.call(fromJSON))
Call[[1]] <- as.symbol("fromJSON")
the_url <- eval.parent(Call[["content"]])
tmpfile <- tempfile()
on.exit(unlink(tmpfile))
stopifnot(download.file2(the_url, tmpfile) == 0)
Call[["content"]] <- tmpfile
eval.parent(as.call(Call))
}
read.xkcd <- function(file = NULL)
{
if(!is.null(file) && file.exists(file)) {
xkcd <- file
} else {
path <- system.file("xkcd", package = "RXKCD")
datafiles <- list.files(path)
if(!is.null(file) && file.exists(file.path(path, file))) {
xkcd <- file.path(path, file)
} else {
if(!is.null(file)) stop("sorry, ", sQuote(file), " not found")
file <- datafiles
xkcd <- file.path(path, file)
}
}
out <- readRDS(xkcd)
return(out)
}
load.xkcd <- function(file = NULL)
{
if(!is.null(file) && file.exists(file)) {
xkcd <- file
} else {
path <- system.file("xkcd", package = "RXKCD")
datafiles <- list.files(path)
if(!is.null(file) && file.exists(file.path(path, file))) {
xkcd <- file.path(path, file)
} else {
if(!is.null(file)) stop("sorry, ", sQuote(file), " not found")
file <- datafiles
xkcd <- file.path(path, file)
}
}
out <-readRDS(xkcd)
return(out)
}
updateConfig <- function(){
home <- Sys.getenv("HOME")
if( !file.exists( paste(home, ".Rconfig/rxkcd.rda", sep="/") ) ) {
stop("Use saveConfig() to save your xkcd database locally!")
} else xkcd.df <- readRDS( paste(home, ".Rconfig/rxkcd.rda", sep="/") )
from <- dim(xkcd.df)[[1]]
current <- getXKCD("current", display=FALSE)
if ( current$num == xkcd.df$id[dim(xkcd.df)[[1]]] ) stop("Your local xkcd is already updated!")
tmp <- NULL
for( i in c((from+1):(current$num)) ){
if (is.null(tmp)) tmp <- data.frame(unclass(getXKCD(i, display=FALSE)))
else tmp <- plyr::rbind.fill(tmp, data.frame(unclass(getXKCD(i, display=FALSE))))
}
xkcd2add <- cbind(
"id"=unlist(tmp[["num"]]),
"img"=unlist(tmp[["img"]]),
"title"=unlist(tmp[["title"]]),
"month"=unlist(tmp[["month"]]),
"num"=unlist(tmp[["num"]]),
"link"=unlist(tmp[["link"]]),
"year"=unlist(tmp[["year"]]),
"news"=unlist(tmp[["news"]]),
"safe_title"=unlist(tmp[["safe_title"]]),
"transcript"=unlist(tmp[["transcript"]]),
"alt"=unlist(tmp[["alt"]]),
"day"=unlist(tmp[["day"]])
)
suppressWarnings(xkcd2add <- data.frame(xkcd2add))
xkcd.updated <- rbind(xkcd.df,xkcd2add)
xkcd.updated <- plyr::rbind.fill(xkcd.df,xkcd2add)
xkcd.df <- xkcd.updated
saveRDS( xkcd.df, file=paste(home, ".Rconfig/rxkcd.rda", sep="/") , compress=TRUE)
}
saveConfig <- function(){
home <- Sys.getenv("HOME")
if( file.exists( paste(home, ".Rconfig/rxkcd.rda", sep="/") ) ) stop("Use updateConfig() for updating your local xkcd database")
else {
dir.create( paste(home, ".Rconfig", sep="/") )
xkcd.df <- read.xkcd()
saveRDS( xkcd.df, file=paste(home, ".Rconfig/rxkcd.rda", sep="/") , compress=TRUE)
}
}
searchXKCD <- function(which="significant"){
xkcd.df <- NULL
home <- Sys.getenv("HOME")
if( file.exists( paste(home, ".Rconfig/rxkcd.rda", sep="/") ) ) {
tryCatch(readRDS( paste(home, ".Rconfig/rxkcd.rda", sep="/")), error = function(e) {
e$message <- paste0(e$message, "(RXKCD < 1.9) archive input format! You need to delete", home, "/.Rconfig/rxkcd.rda by typing, for example, file.remove('~/.Rconfig/rxkcd.rda')")
stop(e)
})
xkcd.df <- readRDS( paste(home, ".Rconfig/rxkcd.rda", sep="/"))
} else xkcd.df <- read.xkcd()
if(is.character(which)) {
if(length(which) > 1) which <- sample(which)
which.tt <- grep(which, xkcd.df["title"][[1]], ignore.case = TRUE, useBytes = TRUE)
which.tr <- grep(which, xkcd.df["transcript"][[1]], ignore.case =TRUE, useBytes = TRUE)
which.all <- unique(c(which.tr, which.tt))
}
out <- data.frame(num=xkcd.df[which.all, "num"], title=xkcd.df[which.all, "title"])
return(out)
}
getXKCD <- function(which = "current", display = TRUE, html = FALSE, saveImg = FALSE) {
if (which=="current") xkcd <- fromJSON2("https://xkcd.com/info.0.json")
else if(which=="random" || which=="") {
current <- fromJSON2("https://xkcd.com/info.0.json")
num <- sample(1:current["num"][[1]], 1)
xkcd <- fromJSON2(paste("https://xkcd.com/",num,"/info.0.json",sep=""))
}
else xkcd <- fromJSON2(paste("https://xkcd.com/",which,"/info.0.json",sep=""))
class(xkcd) <- "rxkcd"
if(html) {
display <- FALSE
browseURL( paste("https://xkcd.com/", as.numeric(xkcd["num"][[1]]),sep="") )
}
if (display || saveImg) {
if(grepl(".png",xkcd["img"][[1]])){
download.file2(url=xkcd["img"][[1]], quiet=TRUE, mode="wb", destfile=paste(tempdir(),"xkcd.png",sep="/"))
xkcd.img <- readPNG( paste(tempdir(),"xkcd.png",sep="/") )
}
else if(grepl(".jpg",xkcd["img"][[1]])){
download.file2(url=xkcd["img"][[1]], quiet=TRUE, mode="wb", destfile=paste(tempdir(),"xkcd.jpg",sep="/"))
xkcd.img <- readJPEG( paste(tempdir(),"xkcd.jpg",sep="/") )
} else stop("Unsupported image format! Try html = TRUE")
if(display){
img_dim <- dim(xkcd.img)
plot(c(0, img_dim[2]), c(0, img_dim[1]), type = "n",
axes = FALSE, asp = 1, xaxs = "i", yaxs = "i",
xaxt = "n", yaxt = "n", xlab = "", ylab = "")
rasterImage(xkcd.img, xleft = 0, ybottom = 0,
xright = img_dim[2], ytop = img_dim[1])
}
if(saveImg) writePNG( image=xkcd.img, target=paste(xkcd$title,".png",sep="") )
}
return(xkcd)
}
print.rxkcd <- function(x, ...){
cat("image.url = ", x$img, "\n", sep="")
cat("title = ", x$title, "\n", sep="")
cat("num = ", x$num, "\n", sep="")
cat("year = ", x$year, "\n", sep="")
cat("transcript = ", x$transcript,"\n", sep="")
cat("alt = ", x$alt, "\n", sep="")
} |
bare_combine <- function(){
dados_documento = rstudioapi::getActiveDocumentContext()
texto = dados_documento$selection[[1]]$text
while(endsWith(texto,"\n")){
texto = stringr::str_sub(texto,end=-2)
}
while(endsWith(texto," ")){
texto = stringr::str_sub(texto,end=-1)
}
if(stringr::str_detect(texto,stringr::fixed("\n"))){
texto = stringr::str_split(texto,stringr::fixed("\n"))[[1]]
if(sum(stringr::str_detect(texto,stringr::fixed(";"))) > 0){
texto = stringr::str_split(texto,stringr::fixed(";"))
}
else if(sum(stringr::str_detect(texto,stringr::fixed(","))) > 0){
texto = stringr::str_split(texto,stringr::fixed(","))
}
}
else if(stringr::str_detect(texto,stringr::fixed(";"))){
texto = stringr::str_split(texto,stringr::fixed(";"))
}
else if(stringr::str_detect(texto,stringr::fixed(","))){
texto = stringr::str_split(texto,stringr::fixed(","))
}
else if(stringr::str_detect(texto,stringr::fixed(" "))){
texto = stringr::str_split(texto,stringr::fixed(" "))
}
texto = stringr::str_trim(purrr::as_vector(texto))
df = data.frame(texto)
df = dplyr::filter(df,texto != "")
string = 'c("'
for (i in 1:length(df$texto)){
if(i!=1){
string=stringr::str_c(string,', "')
}
string = stringr::str_c(string,df[i,1])
string = stringr::str_c(string,'"')
}
string = stringr::str_c(string,")")
rstudioapi::insertText(text = string, id = NULL)
} |
exceedance.ci <- function(statistic.sim.obj, conf.level = .95, type = "null")
{
alternative <- statistic.sim.obj$alternative
cv <- statistic.cv(statistic.sim.obj, conf.level = conf.level)
if(alternative == "less")
{
if(type == "null")
{
set <- which(statistic.sim.obj$statistic >= cv)
}else
{
set <- which(statistic.sim.obj$statistic < cv)
}
}else if(alternative == "greater")
{
if(type == "null")
{
set <- which(statistic.sim.obj$statistic <= cv)
}else
{
set <- which(statistic.sim.obj$statistic > cv)
}
}
else
{
if(type == "null")
{
set <- which(statistic.sim.obj$statistic <= cv)
}else
{
set <- which(statistic.sim.obj$statistic > cv)
}
}
return(set)
} |
suppressPackageStartupMessages(library("argparse"))
parser = ArgumentParser()
parser$add_argument("--infercnv_obj", help="infercnv_obj file", required=TRUE, nargs=1)
args = parser$parse_args()
library(infercnv)
library(ggplot2)
library(dplyr)
infercnv_obj_file = args$infercnv_obj
infercnv_obj = readRDS(infercnv_obj_file)
if (! is.null([email protected])) {
hspike_obj = [email protected]
pdf(paste0(infercnv_obj_file, '.hspike.dist_by_numcells.pdf'))
gene_expr_by_cnv <- infercnv:::.get_gene_expr_by_cnv(hspike_obj)
cnv_level_to_mean_sd = list()
for (ncells in c(1,2,3,4,5,10,20,50,100)) {
cnv_to_means = list()
cnv_mean_sd = list()
for (cnv_level in names(gene_expr_by_cnv) ) {
expr_vals = gene_expr_by_cnv[[ cnv_level ]]
nrounds = 100
means = c()
for(i in 1:nrounds) {
vals = sample(expr_vals, size=ncells, replace=T)
m_val = mean(vals)
means = c(means, m_val)
}
cnv_to_means[[ cnv_level ]] = means
cnv_mean_sd[[ cnv_level ]] = list(sd=sd(means), mean=mean(means))
}
df = do.call(rbind, lapply(names(cnv_to_means), function(x) { data.frame(cnv=x, expr=cnv_to_means[[x]]) }))
p = df %>% ggplot(aes(expr, fill=cnv, colour=cnv)) + geom_density(alpha=0.1)
p = p +
stat_function(fun=dnorm, color='black', args=list('mean'=cnv_mean_sd[["cnv:0.01"]]$mean,'sd'=cnv_mean_sd[["cnv:0.01"]]$sd)) +
stat_function(fun=dnorm, color='black', args=list('mean'=cnv_mean_sd[["cnv:0.5"]]$mean,'sd'=cnv_mean_sd[["cnv:0.5"]]$sd)) +
stat_function(fun=dnorm, color='black', args=list('mean'=cnv_mean_sd[["cnv:1"]]$mean,'sd'=cnv_mean_sd[["cnv:1"]]$sd)) +
stat_function(fun=dnorm, color='black', args=list('mean'=cnv_mean_sd[["cnv:1.5"]]$mean,'sd'=cnv_mean_sd[["cnv:1.5"]]$sd)) +
stat_function(fun=dnorm, color='black', args=list('mean'=cnv_mean_sd[["cnv:2"]]$mean,'sd'=cnv_mean_sd[["cnv:2"]]$sd)) +
stat_function(fun=dnorm, color='black', args=list('mean'=cnv_mean_sd[["cnv:3"]]$mean,'sd'=cnv_mean_sd[["cnv:3"]]$sd))
p = p + ggtitle(sprintf("num cells: %g", ncells))
plot(p)
}
dev.off()
} else {
message("no hspike to plot")
} |
setClass("covastat", slots = c(G = "matrix",
cova.h = "matrix",
cova.u = "matrix",
f.G = "array",
B = "array",
A = "matrix",
typetest = "character"))
covastat <- function(matdata, pardata1, pardata2, stpairs, typetest = "sym") {
is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) {abs(x - round(x)) <
tol}
is.scalar <- function (x){length(x) == 1L && is.vector(x, mode = "numeric")}
if (is.scalar(pardata1) == FALSE || is.scalar(pardata2) == FALSE) {
message("Start error message. Some of the arguments are not numeric.")
stop("End error message. Stop running.")
}
if(pardata1 != as.integer(pardata1) || pardata2 != as.integer(pardata2)){
pardata1 <- as.integer(pardata1)
pardata2 <- as.integer(pardata2)
message("Warning message: the arguments expected to be integer are forced to be integer numbers.")
}
if (!inherits(stpairs, "couples")){
message("Start error message. stpairs argument has to be of class couples.")
stop("End error message. Stop running.")
}
if(stpairs@typetest != typetest){
message("Warning message: the argument typetest is different from the one defined in stpairs.")
}
selstaz <- [email protected]
couples <- [email protected]
nstaz <- length(selstaz)
if (is.character(typetest) == FALSE) {
message("Start error message. The argument for typetest is not admissible.")
stop("End error message. Stop running.")
}
if (typetest != "sym" && typetest != "sep" && typetest != "tnSep") {
message("Start error message. The argument for typetest is not admissible.")
stop("End error message. Stop running.")
}
if (typetest == "sym") {
type.test <- 0
}else{if (typetest == "sep"){
type.test <- 1
}else{
type.test <- 2
}
}
if (class(matdata) == "matrix" || class(matdata) == "data.frame") {
iclsp.id <- as.integer(pardata1)
iclvr <- as.integer(pardata2)
}
info.na <- NA
info.nna29 <- NA
info.nna89 <- NA
if (is.vector(selstaz) && length(selstaz) >= 2) {
for (i in 1:length(selstaz)) {
if (class(matdata) == "matrix" || class(matdata) == "data.frame") {
if (is.numeric(matdata[, iclvr]) == TRUE) {
if (i == 1) {
selstaz.names <- matdata[, iclsp.id]
selstaz.inter <- intersect(selstaz.names, selstaz)
if (length(selstaz.inter) != length(selstaz)) {
message("Start error message. No data for some of the selected spatial points. Please go back to the function 'couples' and revise the vector of the selected spatial points.")
stop("End error message. Stop running.")
}
}
datistaz <- matdata[matdata[, iclsp.id] == selstaz[i], iclvr]
} else {
message("Start error message. Check the column in which the values of the variable are stored. Data must be numeric.")
stop("End error message. Stop running.")
}
} else {
if (class(matdata) == "STFDF") {
if (i == 1) {
selstaz.names <- row.names(matdata@sp)
selstaz.inter <- intersect(selstaz.names, selstaz)
if (length(selstaz.inter) != length(selstaz)) {
message("Start error message. No data for some of the selected spatial points. Please go back to the function 'couples' and revise the vector of the selected spatial points.")
stop("End error message. Stop running.")
}
nvr <- as.integer(pardata1)
iclvr <- as.integer(pardata2)
if (nvr == 1) {
iclvr <- 1
}
}
datistaz <- matrix(matdata[selstaz[i], ], ncol = (1 + nvr))[,
iclvr]
} else {
if (class(matdata) == "STSDF") {
matdata <- as(matdata, "STFDF")
if (i == 1) {
selstaz.names <- row.names(matdata@sp)
selstaz.inter <- intersect(selstaz.names, selstaz)
if (length(selstaz.inter) != length(selstaz)) {
message("Start error message. No data for some of the selected spatial points. Please go back to the function 'couples' and revise the vector of the selected spatial points.")
stop("End error message. Stop running.")
}
nvr <- as.integer(pardata1)
iclvr <- as.integer(pardata2)
if (nvr == 1) {
iclvr <- 1
}
}
datistaz <- matrix(matdata[selstaz[i], ], ncol = (1 + nvr))[,
iclvr]
} else {
message("Start error message. The class of data must be matrix (gslib format), data.frame, STFDF or STSDF.")
stop("End error message. Stop running.")
}
}
}
if (i == 1) {
lt <- length(datistaz)
if (lt <= 29) {
message("Start error message. The length of the time series (equal to ", lt,") for each spatial point must be greater than 29.")
stop("End error message. Stop running.")
}
if (lt <= 89 && lt > 29) {
message("*****************************************************************************")
message("* The length of the time series (equal to ",lt, ") for each spatial point *")
message("* is low and may not guarantee the reliability of the some tests. *")
message("* See the manual for more details. *")
message("*****************************************************************************")
}}
count.na <- matrix(0, nrow = lt, ncol = 1)
count.cons.na <- 0
count.nna <- matrix(0, nrow = lt, ncol = 1)
count.cons.nna <- 0
for (ii in 1:lt) {
if(is.na(datistaz[ii]) == TRUE){
count.cons.na <- count.cons.na + 1
count.na[ii, 1] <- count.cons.na
}else{count.cons.na<- 0}
if(is.na(datistaz[ii]) == FALSE){
count.cons.nna <- count.cons.nna + 1
count.nna[ii, 1] <- count.cons.nna
}else{count.cons.nna<- 0}
}
max.count.na <- max(count.na[,])/lt
max.count.nna <- max(count.nna[,])
if(max.count.nna > 29){
if(max.count.nna <= 89){
if(is.na(info.nna89[1]) == TRUE){
info.nna89 <- selstaz[i]
}else{
info.nna89 <- rbind(info.nna89, selstaz[i])
}
}
if(max.count.na > 0.75){
if(is.na(info.na[1]) == TRUE){
info.na <- selstaz[i]
}else{info.na <- rbind(info.na, selstaz[i]) }
}
if (i == 1) {
matdata.sel <- datistaz
}
if (i > 1) {
matdata.sel <- cbind(matdata.sel, datistaz)
}
}else{
if(is.na(info.nna29[1]) == TRUE){
info.nna29 <- selstaz[i]
}else{
info.nna29 <- rbind(info.nna29, selstaz[i])
}
}
}
if(is.na(info.na[1]) == FALSE){
message("Start error message. The following spatial points are non-admissible. Too many consecutive NAs (greater than 75%).")
for (i in 1:length(info.na)){
message((info.na[i]))
}
message("Please exclude/change the non-admissible spatial points from the selection.")
stop("End error message. Stop running.")
}
if(is.na(info.nna29[1]) == FALSE){
message("Start error message. The following spatial points are non-admissible. The number of valid consecutive values must be greater than 29.")
for (i in 1:length(info.nna29)){
message((info.nna29[i]))
}
message("Please exclude/change the non-admissible spatial points from the selection.")
stop("End error message. Stop running.")
}
if(is.na(info.nna89[1]) == FALSE){
message("Warning message: the number of valid consecutive values of the following spatial points is low (<=89) and may not guarantee the reliability of the some tests.")
for (i in 1:length(info.nna89)){
message((info.nna89[i]))
}
}
}else {
message("Start error message. The number of spatial points selected in function 'couples' must be a vector with at least two components.")
stop("End error message. Stop running.")
}
couples.nrow <- nrow(couples)
nct <- 0
for (i in 1:nrow(couples)) {
for (j in 3:ncol(couples)) {
if (couples[i, j] != 0) {
nct <- nct + 1
}
}
}
array.matdata.sel <- array(matdata.sel, dim = c(length(datistaz), 1, length(selstaz)))
cova.nv <- matrix(data = "-", nrow = nrow(couples), ncol = ncol(couples))
vec.na <- matrix(NA, length(datistaz), 1)
info.na.all <- matrix(NA, 1, 5)
nflag.cova.nv <- 0
if (type.test == 0 || type.test == 1 || type.test == 2 || type.test == 3) {
if (type.test == 0 || type.test == 1 || type.test == 2 || type.test == 3) {
cova <- matrix(0, nrow = nct, ncol = 1)
couples.ncol <- as.integer((ncol(couples) - 2))
couples.ncol.r <- 0
for (i in 1:couples.nrow) {
couples.nrow.r <- 0
nf <- 0
for (j in 1:couples.ncol) {
if (couples[i, j + 2] != 0) {
couples.nrow.r <- couples.nrow.r + 1
cov.n <- as.integer(couples.nrow.r + couples.ncol.r)
if (couples[i, j + 2] > 0) {
cova[cov.n, ] <- cov(array.matdata.sel[-(nrow(matdata.sel) -
couples[i, j + 2] + 1:nrow(matdata.sel)), , couples[i,
1]], array.matdata.sel[-(1:couples[i, j + 2]), , couples[i,
2]], use = "pairwise.complete.obs")
if(is.na(cova[cov.n, ]) == TRUE){
if(is.na(info.na.all[1,1]) == TRUE){
info.na.all[1,1] <- couples[i,1]
info.na.all[1,2] <- couples[i,2]
info.na.all[1,5] <- couples[i,j +2]
if(identical(vec.na,array.matdata.sel[-(nrow(matdata.sel) -
couples[i, j + 2] + 1:nrow(matdata.sel)), , couples[i,
1]]) == TRUE){info.na.all[1,3] <- 1}
if(identical(vec.na,array.matdata.sel[-(1:couples[i, j + 2]), , couples[i,
2]]) == TRUE){info.na.all[1,4] <- 2}
}else{
info.na <- rbind(info.na, c(couples[i,1:2],NA,NA,NA))
info.na[1,5] <- couples[i,j +2]
if(identical(vec.na,array.matdata.sel[-(nrow(matdata.sel) -
couples[i, j + 2] + 1:nrow(matdata.sel)), , couples[i,
1]]) == FALSE){info.na.all[1,3] <- 1}
if(identical(vec.na,array.matdata.sel[-(1:couples[i, j + 2]), , couples[i,
2]]) == FALSE){info.na.all[1,4] <- 2}
}
}
}
if (couples[i, j + 2] < 0) {
cova[cov.n, ] <- cov(array.matdata.sel[-(1:(-couples[i,
j + 2])), , couples[i, 1]], array.matdata.sel[-(nrow(matdata.sel) +
couples[i, j + 2] + 1:nrow(matdata.sel)), , couples[i,
2]], use = "pairwise.complete.obs")
if(is.na(cova[cov.n, ]) == TRUE){
if(is.na(info.na.all[1,1]) == TRUE){
info.na.all[1,1] <- couples[i,1]
info.na.all[1,2] <- couples[i,2]
info.na.all[1,5] <- couples[i,j +2]
if(identical(vec.na,array.matdata.sel[-(1:(-couples[i,
j + 2])), , couples[i, 1]]) == TRUE){info.na.all[1,3] <- 1}
if(identical(vec.na,array.matdata.sel[-(nrow(matdata.sel) +
couples[i, j + 2] + 1:nrow(matdata.sel)), , couples[i,
2]]) == TRUE){info.na.all[1,4] <- 2}
}else{
info.na <- rbind(info.na, c(couples[i,1:2],NA,NA,NA))
info.na[1,5] <- couples[i,j +2]
if(identical(vec.na,array.matdata.sel[-(1:(-couples[i,
j + 2])), , couples[i, 1]]) == FALSE){info.na.all[1,3] <- 1}
if(identical(vec.na,array.matdata.sel[-(nrow(matdata.sel) +
couples[i, j + 2] + 1:nrow(matdata.sel)), , couples[i,
2]]) == FALSE){info.na.all[1,4] <- 2}
}
}
}
if (cova[cov.n,] < 0) {
nflag.cova.nv <- nflag.cova.nv + 1
cova.nv[i,1:2] <- selstaz[couples[i,1:2]]
cova.nv[i,j+2] <- couples[i,j+2]
}
}
}
if (nf == 0) {
couples.ncol.r <- couples.ncol.r + couples.nrow.r
}
nf <- 1
}
if(is.na(info.na.all[1,1]) == FALSE){
message("Start error message. There are no enough data for computing the covariance: spatial couples,
for (i in 1:length(info.na.all)){
print(info.na.all[i,])
}
message("Please exclude/change the non-valid spatial couples/points/temporal lag from the selection.")
stop("End error message. Stop running.")
}
if (nflag.cova.nv != 0) {
message("Warning message: ", nflag.cova.nv, " negative spatio-temporal covariance/es are detected.")
message("In the following the spatial points and the temporal lags involved are visualized.")
for (i in 1:couples.nrow) {
if(cova.nv[i,1] != "-" && cova.nv[i,2] != "-"){
print(cova.nv[i,])
}
}
}
}
cova00_vec <- matrix(0, nrow = length(selstaz), ncol = 1)
for (i in 1:length(selstaz)) {
cova00_vec[i, 1] <- var(array.matdata.sel[, , i], na.rm = TRUE)
}
cova00 <- mean(cova00_vec, na.rm = TRUE)
nflag.cova.h.nv <- 0
nflag.cova.u.nv <- 0
if (type.test == 1 || type.test == 2 || type.test == 3) {
cova.h <- matrix(0, nrow(couples), 1)
cova.h.nv <- matrix(NA, nrow(couples), 2)
for (i in 1:nrow(couples)) {
cova.h[i, ] <- cov(array.matdata.sel[, , couples[i, 1]], array.matdata.sel[,
, couples[i, 2]], use = "pairwise.complete.obs")
if(cova.h[i, ] < 0){
nflag.cova.h.nv <- nflag.cova.h.nv + 1
cova.h.nv[i,] <- selstaz[couples[i,1:2]]
}
}
if (nflag.cova.h.nv != 0) {
message("Warning message: ", nflag.cova.h.nv, " negative spatial covariances are detected.")
message("In the following the spatial points and the temporal lags involved are visualized.")
for (i in 1:couples.nrow) {
if(is.na(cova.h.nv[i, 1]) == FALSE && is.na(cova.h.nv[i, 2]) == FALSE){
print(cova.h.nv[i, ])
}
}
}
nstaz <- length(selstaz)
cova.u.ncol <- as.integer(couples.ncol/2)
cova.u <- matrix(0, cova.u.ncol, 1)
cova.u.nv <- matrix(NA, cova.u.ncol, 1)
cova.ui <- matrix(0, nstaz, 1)
jj <- -1
for (j in 1:(couples.ncol/2)) {
jj <- jj + 2
i <- 1
while (couples[i, jj + 2] == 0 && i <= (nrow(couples) - 1)) {
i <- i + 1
}
if (i <= nrow(couples) && couples[i, jj + 2] != 0) {
for (z in 1:length(selstaz)) {
cova.ui[z, ] <- cov(array.matdata.sel[-(nrow(matdata.sel) -
couples[i, jj + 2] + 1:nrow(matdata.sel)), , z], array.matdata.sel[-(1:couples[i,
jj + 2]), , z], use = "pairwise.complete.obs")
}
}
cova.u[j, ] <- mean(cova.ui, na.rm = TRUE)
if(cova.u[j, ] < 0){
nflag.cova.u.nv <- nflag.cova.u.nv + 1
cova.u.nv[j,] <- couples[i,jj+2]
}
}
}
if (nflag.cova.u.nv != 0) {
message("Warning message: ", nflag.cova.u.nv, " negative temporal covariances are detected.")
message("In the following the spatial points and the temporal lags involved are visualized.")
for (i in 1:cova.u.ncol) {
if(is.na(cova.u.nv[i, ]) == FALSE){
print(cova.u.nv[i, ])
}
}
}
if (type.test == 1 || type.test == 2) {
f.cova <- matrix(0, nrow = nct + (couples.ncol/2), ncol = 1)
couples.ncol.r <- 0
for (i in 1:couples.nrow) {
couples.nrow.r <- 0
nf <- 0
for (j in 1:couples.ncol) {
if (couples[i, j + 2] != 0) {
couples.nrow.r <- couples.nrow.r + 1
cov.n <- as.integer(couples.nrow.r + couples.ncol.r)
f.cova[cov.n, ] <- cova[cov.n, ]/cova.h[i, ]
}
}
if (nf == 0) {
couples.ncol.r <- couples.ncol.r + couples.nrow.r
}
nf <- 1
}
for (i in 1:(couples.ncol/2)) {
f.cova[nct + i, ] <- cova.u[i, ]/cova00
}
B <- matrix(0, nrow = (1 + nct + nrow(couples) + (couples.ncol/2)),
ncol = nct + (couples.ncol/2))
for (i in (nct + 1):(nct + couples.ncol/2)) {
B[1, i] <- -f.cova[i, 1]/cova00
}
for (i in 1:nct) {
B[i + 1, i] <- f.cova[i, 1]/cova[i, 1]
}
jj <- 0
couples.ncol.r <- 0
for (i in 1:couples.nrow) {
couples.nrow.r <- 0
nf <- 0
for (j in 1:couples.ncol) {
if (couples[i, j + 2] != 0) {
couples.nrow.r <- couples.nrow.r + 1
cov.n <- as.integer(couples.nrow.r + couples.ncol.r)
jj <- jj + 1
B[i + 1 + nct, jj] <- -f.cova[cov.n, 1]/cova.h[i, ]
}
}
if (nf == 0) {
couples.ncol.r <- couples.ncol.r + couples.nrow.r
}
nf <- 1
}
for (i in 1:(couples.ncol/2)) {
B[i + 1 + nct + nrow(couples), nct + i] <- 1/cova00
}
}
if (type.test == 3) {
B <- matrix(0, nrow = nct + nrow(couples) + (couples.ncol/2), ncol = 2 *
nct)
ii <- -1
for (i in 1:nct) {
ii <- ii + 2
B[i, ii] <- 1
B[i, ii + 1] <- 1
}
jj <- -1
couples.ncol.r <- 0
for (i in 1:couples.nrow) {
couples.nrow.r <- 0
for (j in 1:couples.ncol) {
if (couples[i, j + 2] != 0) {
jj <- jj + 2
B[i + nct, jj] <- -1
}
}
}
couples.ncol.r <- 0
kk <- -1
for (j in 1:((couples.ncol)/2)) {
kk <- kk + 2
lagt <- sort(couples[, kk + 2], decreasing = TRUE)
jj <- -1
for (k in 1:couples.nrow) {
for (i in 1:couples.ncol) {
if (couples[k, i + 2] != 0) {
jj <- jj + 2
}
if (couples[k, i + 2] == lagt[1]) {
B[j + couples.nrow + nct, jj + 1] <- -1
}
}
}
}
}
if (type.test == 1 || type.test == 2) {
cova <- rbind(cova00, cova, cova.h, cova.u)
row.names(cova) <- NULL
}
if (type.test == 3) {
cova <- rbind(cova, cova.h, cova.u)
}
}
if (type.test == 0) {
nct <- 0
for (i in 1:nrow(couples)) {
for (j in 3:ncol(couples)) {
if (couples[i, j] != 0) {
nct <- nct + 1
}
}
}
A.0.nrow <- as.integer(nct/2)
A.0 <- matrix(0, nrow = A.0.nrow, ncol = nct)
n2 <- 1
for (i in 1:A.0.nrow) {
A.0[i, n2] <- (1)
A.0[i, n2 + 1] <- (-1)
n2 <- n2 + 2
}
}
if (type.test == 1 || type.test == 2) {
nct <- 0
for (i in 1:nrow(couples)) {
for (j in 3:ncol(couples)) {
if (couples[i, j] != 0) {
nct <- nct + 1
}
}
}
couples.ncol <- as.integer((ncol(couples) - 2))
A.1 <- matrix(0, nrow = nct, ncol = nct + (couples.ncol/2))
for (i in 1:nct) {
A.1[i, i] <- 1
}
jj <- 0
for (i in 1:nrow(couples)) {
for (j in 1:couples.ncol) {
if (couples[i, j + 2] != 0) {
jj <- jj + 1
kk <- as.integer((j - 1)/2) + 1
A.1[jj, kk + nct] <- -1
}
}
}
}
if (type.test == 3) {
nct <- 0
for (i in 1:nrow(couples)) {
for (j in 3:ncol(couples)) {
if (couples[i, j] != 0) {
nct <- nct + 1
}
}
}
couples.ncol <- as.integer((ncol(couples) - 2))
A.3 <- matrix(0, nrow = 2 * nct, ncol = nct + nrow(couples) + (couples.ncol/2))
jj <- -1
for (i in 1:nct) {
jj <- jj + 2
A.3[jj, i] <- 1
A.3[jj + 1, i] <- 1
}
jj <- -1
for (i in 1:nrow(couples)) {
for (j in 1:couples.ncol) {
if (couples[i, j + 2] != 0) {
jj <- jj + 2
kk <- as.integer((j - 1)/2) + 1
A.3[jj, i + nct] <- -1
A.3[jj + 1, kk + nct + nrow(couples)] <- -1
}
}
}
A.3bis.nrow <- as.integer(nct)
A.3bis <- matrix(0, nrow = A.3bis.nrow, ncol = nct * 2)
n2 <- 1
for (i in 1:A.3bis.nrow) {
A.3bis[i, n2] <- (1)
A.3bis[i, n2 + 1] <- (-1)
n2 <- n2 + 2
}
}
if (type.test == 0) {
cova.h <- matrix(NA, 1, 1)
cova.u <- matrix(NA, 1, 1)
f.G <- matrix(NA, 1, 1)
B <- matrix(NA, 1, 1)
A <- A.0
}
if (type.test == 1 || type.test == 2) {
f.G <- f.cova
A <- A.1
}
if (type.test == 3) {
f.G <- matrix(NA, 1, 1)
A <- A.3
}
new("covastat", G = cova, cova.h = cova.h, cova.u = cova.u, f.G = f.G,
B = B, A = A, typetest = typetest)
}
NULL
setMethod(f="show", signature="covastat", definition=function(object) {
cat("An object of class covastat", "\n")
cat("\n")
cat("Slot 'G':")
cat("\n")
print(object@G)
cat("\n")
cat("Slot 'cova.h':")
cat("\n")
if(object@typetest == "sym"){
print("This slot is not available for the required typetest")
}else{
print([email protected])
}
cat("\n")
cat("Slot 'cov.u':")
cat("\n")
if(object@typetest == "sym"){
print("This slot is not available for the required typetest")
}else{
print([email protected])
}
cat("\n")
cat("Slot 'f.G':")
cat("\n")
if(object@typetest == "sym"){
print("This slot is not available for the required typetest")
}else{
print([email protected])
}
cat("\n")
cat("Slot 'B':")
cat("\n")
if(object@typetest == "sym"){
print("This slot is not available for the required typetest")
}else{
print(object@B)
}
cat("\n")
cat("Slot 'A':")
cat("\n")
print(object@A)
cat("\n")
cat("Slot 'typetest':")
cat("\n")
print(object@typetest)
}
) |
context("APR")
test_that("APR correctly produces values, no FV", {
check <- 0.1766
expect_true(round(APR(12, -10, 110), 4) == check)
check <- c(0.1766, 0.0884)
df <- data.frame(nper = c(12, 24), pmt = c(-10, -10), pv = c(110, 220))
expect_true(identical(round(APR(df$nper, df$pmt, df$pv), 4), check))
})
test_that("APR correctly produces values, FV", {
check <- 0.0895
expect_true(round(APR(12, -10, 110, 5), 4) == check)
check <- c(0.0895, 0.0674)
df <- data.frame(nper = c(12, 24), pmt = c(-10, -10), pv = c(110, 220), fv = c(5, 5))
expect_true(identical(round(APR(df$nper, df$pmt, df$pv, df$fv), 4), check))
})
test_that("APR errors given incorrect inputs", {
expect_error(APR(0, -500, 3000))
expect_error(APR(1, 500, 3000))
expect_error(APR(1, -500, -3000))
expect_error(APR("0", -500, 3000))
expect_error(APR(1, "500", 3000))
expect_error(APR(1, -500, "-3000"))
}) |
test_that("Subsetting cuts rowspan and colspan", {
ht <- hux(a = 1:3, b = 1:3, d = 1:3)
rowspan(ht)[1, 1] <- 3
colspan(ht)[1, 2] <- 2
ss <- ht[1:2, 1:2]
expect_equivalent(rowspan(ss)[1, 1], 2)
expect_equivalent(colspan(ss)[1, 2], 1)
})
test_that("Subsetting works with multirow/multicolumn cells", {
ht <- hux(a = 1:3, b = 1:3)
rowspan(ht)[1, 1] <- 2
expect_silent(ht[c(1, 3), ])
})
test_that("Copying a whole span creates two separate spans", {
ht <- hux(a = 1:2, b = 1:2)
rowspan(ht)[1, 1] <- 2
expect_silent(ht2 <- ht[c(1:2, 1:2), ])
expect_equivalent(rowspan(ht2)[1, 1], 2)
expect_equivalent(rowspan(ht2)[3, 1], 2)
ht3 <- hux(a = 1:2, b = 1:2)
expect_silent(ht4 <- ht3[c(1,1), ])
expect_equivalent(colspan(ht4)[1, 1], 1)
})
test_that("Reordering rows/cols within a span preserves the span unchanged", {
ht <- hux(a = 1:3, b = 1:3)
rowspan(ht)[1, 1] <- 3
expect_silent(ht2 <- ht[c(2, 3, 1), ])
expect_equivalent(rowspan(ht2)[1, 1], 3)
})
test_that("Repeating rows/cols within a span, without reordering, extends the span", {
ht <- hux(a = 1:3, b = 1:3)
rowspan(ht)[1, 1] <- 2
expect_silent(ht2 <- ht[c(1, 1, 2, 3), ])
expect_equivalent(rowspan(ht2)[1, 1], 3)
}) |
plot.clusterlm <- function(x, effect = "all", type = "statistic", multcomp = x$multcomp[1], alternative = "two.sided", enhanced_stat = FALSE,
nbbaselinepts=0, nbptsperunit=1, distinctDVs=NULL, ...) {
par0 <- par()
dotargs <- list(...)
dotargs_par <- dotargs[names(dotargs)%in%names(par())]
dotargs <- dotargs[!names(dotargs)%in%names(par())]
if("all" %in% effect){effect = names(x$multiple_comparison)}
else if(sum(names(x$multiple_comparison)%in%effect) == 0){
warning(" the specified effects do not exist. Plot 'all' effects.")
effect = names(x$multiple_comparison)
}
effect_sel <- names(x$multiple_comparison)%in%effect
switch(alternative,
"two.sided" = {multiple_comparison = x$multiple_comparison[effect_sel]},
"greater" = {multiple_comparison = x$multiple_comparison_greater[effect_sel]},
"less" = {multiple_comparison = x$multiple_comparison_less[effect_sel]})
pvalue = t(sapply(multiple_comparison,function(m){
m[[multcomp]]$main[,2]}))
statistic = t(sapply(multiple_comparison,function(m){
m[["uncorrected"]]$main[,1]}))
if(enhanced_stat){
statistic = t(sapply(multiple_comparison,function(m){
m[[multcomp]]$main[,1]}))
}
switch(type,
"coef"={
data <- x$coef[effect_sel,]
title <- "coefficients"
hl <- NULL
},
"statistic" ={
data <- statistic
title <- paste(x$test, " statistic",sep="",collapse = "")
if(multcomp=="clustermass"){
switch(x$test,
"fisher"={hl <- x$threshold},
"t"={
switch (alternative,
"less" ={hl <- -c(abs(x$threshold))},
"greater" ={hl <- c(abs(x$threshold))},
"two.sided" ={hl <- c(abs(x$threshold))}
)})}
})
title =paste(title," : ", multcomp, " correction",sep="", collapse = "")
p = sum(NROW(data))
rnames = row.names(data)
cnames = colnames(data)
nbDV = ncol(data)
if (is.null(distinctDVs)){
if (multcomp %in% c("clustermass", "tfce"))
distinctDVs = FALSE
else distinctDVs = (nbDV<16)
}
if ((distinctDVs==TRUE) && (multcomp %in% c("clustermass", "tfce")))
warning("Computations and corrections have been based on adjacency of DVs but the the plot will show separated DVs")
par0 <- list(mfcol = par()$mfcol,mar = par()$mar,oma = par()$oma)
if(is.null(dotargs_par$mfcol)){dotargs_par$mfcol = c(p,1)}
if(is.null(dotargs_par$mar)){dotargs_par$mar = c(0,4,0,0)}
if(is.null(dotargs_par$oma)){dotargs_par$oma = c(4,0,4,1)}
par(dotargs_par)
for (i in 1:p) {
if (distinctDVs) {
plot((1:ncol(data)-nbbaselinepts)/nbptsperunit,
data[i,],type = "p", xaxt = "n",xlab = "",ylab = rnames[i], pch=18, cex=2,
)
if(i==p) axis(1, at= (1:ncol(data)-nbbaselinepts)/nbptsperunit, labels=cnames)
}
else{
if(i==p){xaxt = NULL}else{xaxt = "n"}
plot((1:ncol(data)-nbbaselinepts)/nbptsperunit,
data[i,],type = "l", xaxt = xaxt,xlab = "",ylab = rnames[i], ... = ...
)
}
if(type == "statistic"){
xi = which(pvalue[i,]< x$alpha)
y = data[i,xi]
col="red"
points(x = (xi-nbbaselinepts)/nbptsperunit, y = y, pch=18,col=col, cex=distinctDVs+1)
if(multcomp=="clustermass"){
abline(h=hl[i],lty=3)
if(x$test=="t"&alternative=="two.sided"){
abline(h=-hl[i],lty=3)
}
}
}}
title(title,outer = T,cex = 2)
par0 <- par0[!names(par0)%in%c("cin","cra","csi","cxy","din","page")]
par(par0)
} |
oneEdgeDeletedSubgraphComplexity <- function(g, one.eds=NULL) {
if (class(g)[1] != "graphNEL")
stop("'g' has to be a 'graphNEL' object")
stopifnot(.validateGraph(g))
if(numEdges(g)==0)
stop("No edges in current graph object")
if (is.null(one.eds))
one.eds <- edgeDeletedSubgraphs(g)
n <- numNodes(g)
count <- length(one.eds)
lap <- laplaceMatrix(g)
nST_g <- det(lap[2:n, 2:n])
data <- lapply(one.eds, function(M_1e) {
diag_1e <- diag(rowSums(M_1e, na.rm = FALSE, dims = 1))
lap_1e <- diag_1e - M_1e
nST_1e <- det(lap_1e[2:n, 2:n])
EV_lap_1e <- as.double(eigen(lap_1e, only.values = TRUE)$values)
signless_lap_1e <- diag_1e + M_1e
EV_signless_lap_1e <- as.double(eigen(signless_lap_1e, only.values = TRUE)$values)
list(nST = nST_1e, EV_lap = EV_lap_1e, EV_signless_lap = EV_signless_lap_1e)
})
sST <- 0
sSpec <- 0
for (k in 1:(count-1)) {
for (l in (k+1):count) {
if (data[[k]]$nST == data[[l]]$nST) {
sST <- sST + 1
break
}
}
for (l in (k+1):count) {
if (setequal(data[[k]]$EV_lap, data[[l]]$EV_lap) &&
setequal(data[[k]]$EV_signless_lap, data[[l]]$EV_signless_lap)) {
sSpec <- sSpec + 1
break
}
}
}
N_1eST <- count - sST
N_1eSpec <- count - sSpec
m_cu <- n^1.68 - 10
C_1eST <- (N_1eST - 1) / (m_cu - 1)
C_1eSpec <- (N_1eSpec - 1) / (m_cu - 1)
list(`C_1eST` = C_1eST, `C_1eSpec` = C_1eSpec)
} |
NAME <- "html"
source(file.path('_helper', 'init.R'))
all.equal(
as.character(
diffPrint(
letters[1:3], LETTERS[1:3],
style=StyleHtmlLightYb(html.output="diff.only")
) ),
rdsf(100)
)
all.equal(
as.character(
diffPrint(
letters[1:6], LETTERS[1:6],
style=StyleHtmlLightYb(html.output="diff.w.style")
) ),
rdsf(200)
)
all.equal(
as.character(
diffPrint(
letters[1:6], LETTERS[1:6],
style=StyleHtmlLightYb(html.output="page")
) ),
rdsf(300)
)
all.equal(
as.character(
diffPrint(
letters[1:6], LETTERS[1:6], mode="unified",
style=StyleHtmlLightYb(html.output="page")
) ),
rdsf(350)
)
local({
f <- tempfile()
on.exit(unlink(f))
cat("div.row {background-color: red;}\n", file=f)
all.equal(
as.character(
diffPrint(
letters, LETTERS,
style=StyleHtmlLightYb(css=f, html.output="diff.w.style")
)
),
rdsf(400)
)
})
div_a <- div_f("A", c(color="red"))
all.equal(
div_a(c("a", "b")),
c(
"<div class='A' style='color: red;'>a</div>",
"<div class='A' style='color: red;'>b</div>"
)
)
span_a <- span_f()
all.equal(span_a(c("a", "b")), c("<span>a</span>", "<span>b</span>"))
try(div_a(TRUE))
all.equal(div_a(character()),character())
all.equal(nchar_html("<a href='blahblah'>25</a>"), 2)
all.equal(nchar_html("<a href='blahblah'>25 </a>"), 3)
try(cont_f("hello")(1:3)) |
delayedAssign("guaguas", local({
if (requireNamespace("tibble", quietly = TRUE)) {
tibble::as_tibble(guaguas:::guaguas)
} else {
guaguas:::guaguas
}
}))
delayedAssign("guaguas_frecuentes", local({
if (requireNamespace("tibble", quietly = TRUE)) {
tibble::as_tibble(guaguas:::guaguas_frecuentes)
} else {
guaguas:::guaguas_frecuentes
}
})) |
poststrata<-function(data, postnames = NULL)
{
if (missing(data) | missing(postnames)) stop("incomplete input")
data = data.frame(data)
if(is.null(colnames(data))) stop("the column names in data are missing")
index = 1:nrow(data)
m = match(postnames, colnames(data))
if (any(is.na(m)))
stop("the names of the poststrata are wrong")
data2 = cbind.data.frame(data[, m])
x1 = data.frame(unique(data[, m]))
colnames(x1) = postnames
nr_post=0
post=numeric(nrow(data))
nh=numeric(nrow(x1))
for(i in 1:nrow(x1))
{ expr=rep(FALSE, nrow(data2))
for(j in 1:nrow(data2)) expr[j]=all(data2[j, ]==x1[i, ])
y=index[expr]
if(is.matrix(y))
nh[i]=nrow(y)
else nh[i]=length(y)
post[expr]=i
}
result=cbind.data.frame(data,post)
names(result)=c(names(data),"poststratum")
list(data=result, npost=nrow(x1))
} |
ci.gamma.profile.likelihood <-
function (x, shape.mle, scale.mle, ci.type, conf.level, LCL.start,
UCL.start)
{
n <- length(x)
mean.mle <- shape.mle * scale.mle
cv.mle <- 1/sqrt(shape.mle)
sd.mle <- sqrt(shape.mle)/scale.mle
loglik.at.mle <- loglikComplete(theta = c(mean = mean.mle,
cv = cv.mle), x = x, distribution = "gammaAlt")
fcn <- function(CL, loglik.at.mle, mean.mle, cv.mle, x, conf.level) {
cv.mle.at.CL <- egammaAlt.cv.mle.at.fixed.mean(fixed.mean = CL,
mean.mle = mean.mle, cv.mle = cv.mle, x = x)
(2 * (loglik.at.mle - loglikComplete(theta = c(CL, cv.mle.at.CL),
x = x, distribution = "gammaAlt")) - qchisq(conf.level,
df = 1))^2
}
switch(ci.type, `two-sided` = {
LCL <- nlminb(start = LCL.start, objective = fcn, lower = .Machine$double.eps,
upper = mean.mle, loglik.at.mle = loglik.at.mle,
mean.mle = mean.mle, cv.mle = cv.mle, x = x, conf.level = conf.level)$par
UCL <- nlminb(start = UCL.start, objective = fcn, lower = mean.mle,
loglik.at.mle = loglik.at.mle, mean.mle = mean.mle,
cv.mle = cv.mle, x = x, conf.level = conf.level)$par
}, lower = {
LCL <- nlminb(start = LCL.start, objective = fcn, lower = .Machine$double.eps,
upper = mean.mle, loglik.at.mle = loglik.at.mle,
mean.mle = mean.mle, cv.mle = cv.mle, x = x, conf.level = 1 -
2 * (1 - conf.level))$par
UCL <- Inf
}, upper = {
LCL <- 0
UCL <- nlminb(start = UCL.start, objective = fcn, lower = mean.mle,
loglik.at.mle = loglik.at.mle, mean.mle = mean.mle,
cv.mle = cv.mle, x = x, conf.level = 1 - 2 * (1 -
conf.level))$par
})
ci.limits <- c(LCL, UCL)
names(ci.limits) <- c("LCL", "UCL")
interval <- list(name = "Confidence", parameter = "mean",
limits = ci.limits, type = ci.type, method = "Profile Likelihood",
conf.level = conf.level)
oldClass(interval) <- "intervalEstimate"
interval
} |
context("test-melt_list")
test_that("melt_list works", {
expect_silent({
df <- data.frame(year = 2010, day = 1:3, month = 1, site = "A")
l <- list(a = df, b = df)
df_new <- melt_list(l, "id")
df <- data.table(year = 2010, day = 1:3, month = 1, site = "A")
l <- list(a = df, b = df)
df_new <- melt_list(l, "id")
})
}) |
isNumberOrNaOrInfScalarOrNull <- function(argument, default = NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL) {
checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = TRUE, n = 1, zeroAllowed = TRUE, negativeAllowed = TRUE, positiveAllowed = TRUE, nonIntegerAllowed = TRUE, naAllowed = TRUE, nanAllowed = FALSE, infAllowed = TRUE, message = message, argumentName = argumentName)
} |
interaction_to_edges = function(df,a = 1,b = 2,sep = ","){
gs = str_split(df[,b],sep)
edges = data.frame(a1 = rep(df[,a],times = sapply(gs,length)),
a2 = unlist(gs))
edges = distinct(edges,a1,a2)
return(edges)
}
utils::globalVariables(c("a1","a2"))
edges_to_nodes = function(edges){
if(!is.null(colnames(edges))){
m = colnames(edges)
}else{
m = c("A1","A2")
}
a = unique(edges[,1])
b = unique(edges[,2])
nodes = data.frame(gene = c(a,b),
type = c(rep(m[1],times = length(a)),
rep(m[2],times = length(b))))
return(nodes)
} |
knitr::opts_chunk$set(fig.height = 6,
fig.width = 6,
fig.align = "center")
library("briskaR")
library("ggplot2")
library("sf")
library("raster")
library("sp")
library("dplyr")
data("sfMaize65")
ggplot() + theme_minimal() +
scale_fill_manual(values = c("grey", "orange"),
name = "Maize") +
geom_sf(data = sfMaize65,
aes(fill = as.factor(maize)))
sfMaize65$maize_GM<-sfMaize65$maize*c(0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,1,1,0,0,1,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0)
sfMaize65_GM <- sfMaize65[sfMaize65$maize_GM == 1,]
plt_GM <- ggplot() + theme_minimal() +
scale_fill_manual(values = c("grey", "red"),
name = "GM maize") +
geom_sf(data = sfMaize65,
aes(fill = as.factor(maize_GM)))
plt_GM +
geom_sf_text(data = sfMaize65_GM,
aes(label = label))
squareFrame_sfMaize65 <- st_squared_geometry(list(sfMaize65), buffer = 200)
plt_GM +
geom_sf(data = squareFrame_sfMaize65, fill = NA)
stack_dispersal <- brk_dispersal(sfMaize65_GM,
size_raster = 2^8,
kernel = "geometric",
kernel.options = list("a" = -2.63),
squared_frame = squareFrame_sfMaize65)
raster::plot(stack_dispersal[[1:6]])
brk_emission <- function(sf,
keyTime,
key,
FUN
){
if("stackTimeline" %in% colnames(sf)) {
stop("Please rename column 'stackTimeline' in sf object.")
}
sf[["key_temp"]] <- lapply(1:nrow(sf), FUN)
if(all(sapply(sf[[keyTime]], length) != sapply(sf[["key_temp"]], length))){
stop(paste0("element within list returned by FUN' has not the same length as list element of '", keyTime, "' column"))
}
stackTimeline = sort(unique(do.call("c", sf[[keyTime]])))
sf[[key]] = lapply(1:nrow(sf), function(i){
index_matching = match(sf[[keyTime]][[i]], stackTimeline)
res = rep(0,length(stackTimeline))
res[index_matching] = sf[["key_temp"]][[i]]
return(res)
})
sf[[keyTime]] = lapply(1:nrow(sf), function(i) stackTimeline)
warning(paste("The column variable", keyTime, "may have changed"))
sf[["key_temp"]] = NULL
return(sf)
}
sfMaize65_GM_Pollen <- brk_timeline(sf = sfMaize65_GM,
key = "timeline",
from = as.Date("01-07-2018", format = "%d-%m-%y"),
to = as.Date("01-09-2018", format = "%d-%m-%y"),
by = "days")
data("maize.proportion_pollen")
graphics::plot(maize.proportion_pollen, type= "l")
funTimePollen <- function(time){
density = runif(1, 7, 11)
pollen = rgamma(1, shape = 1.6, scale = 1 / (2 * 10 ^ -7))
nbr_days = length(time)
deb = sample(1:(nbr_days - length(maize.proportion_pollen)), 1)
end = (deb + length(maize.proportion_pollen) - 1)
pollen_emission <- rep(0, nbr_days)
pollen_emission[deb:end] <- as.numeric(pollen * density * maize.proportion_pollen)
return(pollen_emission)
}
sfMaize65_GM_Pollen <- brk_emission(sf = sfMaize65_GM_Pollen,
keyTime = "timeline",
key = "EMISSION",
FUN = function(i){
funTimePollen(sfMaize65_GM_Pollen$timeline[[i]])
})
stackTimeline = seq(from = min(do.call("c", sfMaize65_GM_Pollen[["timeline"]])),
to = max(do.call("c", sfMaize65_GM_Pollen[["timeline"]])),
by = "days")
stack_exposure <- brk_exposure(stack_dispersal,
sfMaize65_GM_Pollen,
key = "EMISSION",
keyTime = "timeline",
loss = 0.1,
beta = 0.2,
quiet = TRUE)
raster::plot(stack_exposure[[1:6]])
sfMaize65_outGM <- st_sf(geometry = st_difference(x = st_geometry(squareFrame_sfMaize65),
y = st_union(st_geometry(sfMaize65_GM))))
gridPOINT_squareFrame <- st_make_grid(squareFrame_sfMaize65, n = 30, what = "centers")
gridPOINT_outGM <- st_sf(geometry = st_intersection(x = st_geometry(gridPOINT_squareFrame),
y = st_union(st_geometry(sfMaize65_outGM))))
ggplot() + theme_minimal() +
geom_sf(data = sfMaize65_outGM, fill = "grey30") +
geom_sf(data = gridPOINT_outGM)
df_outGM = as.data.frame(raster::extract(x = stack_exposure,
y = sf::as_Spatial(gridPOINT_outGM)))
sf_outGM = st_as_sf(geometry = st_geometry(gridPOINT_outGM), df_outGM)
ggplot() + theme_minimal() +
labs(title = paste("Exposure at", colnames(df_outGM)[40])) +
scale_color_continuous(low = "green", high = "red",
trans = "log", name = "log scaled") +
geom_sf(data = sf_outGM,
aes(color = df_outGM[,40]))
sfMaize65_receptor = st_multibuffer(sfMaize65_GM,
dist = rep(100, nrow(sfMaize65_GM)))
plt_GMreceptor <-
ggplot() + theme_minimal() +
geom_sf(data = sfMaize65_GM,
fill = "red") +
geom_sf(data = sfMaize65_receptor,
fill = "
plt_GMreceptor
nbrSite = 100
sfLarvae <- brk_newPoints(sf = sfMaize65_receptor, size = nbrSite)
plt_GMreceptor +
geom_sf(data = sfLarvae)
DateEmergence = sample(seq(as.Date("01-07-2018", format = "%d-%m-%y"),
as.Date("01-09-2018", format = "%d-%m-%y"), by = "days"),
size = nbrSite,
replace = TRUE)
sfLarvae = brk_timeline( sf = sfLarvae,
key = "Date",
from = DateEmergence,
to = DateEmergence + 20,
by = "days")
stackTimelineEMISSION = sort(unique(do.call("c", sfMaize65_GM_Pollen[["timeline"]])))
exposureINDIVIDUAL <- brk_exposureMatch(stackRaster_exposure = stack_exposure,
sf = sfLarvae,
stackTimeline = stackTimelineEMISSION,
keyTime = "Date",
key = "EXPOSURE")
damageLethal = function(x,LC50, slope){
return(1/(1+(x/LC50)^slope))
}
LC50DR = 451*10^4
slopeDR = -2.63
damageINDIVIDUAL <- exposureINDIVIDUAL %>%
dplyr::mutate(DAMAGE = lapply(EXPOSURE, function(expos){damageLethal(expos, LC50DR, slopeDR)}))
DFdamage = data.frame(
DAMAGE = do.call("c", damageINDIVIDUAL[["DAMAGE"]]),
Date = do.call("c", damageINDIVIDUAL[["Date"]]) ) %>%
dplyr::group_by(Date) %>%
dplyr::summarise(mean_DAMAGE = mean(DAMAGE, na.rm = TRUE),
q025_DAMAGE = quantile(DAMAGE, probs = 0.025, na.rm = TRUE),
q975_DAMAGE = quantile(DAMAGE, probs = 0.975, na.rm = TRUE),
min_DAMAGE = min(DAMAGE, na.rm = TRUE),
max_DAMAGE = max(DAMAGE, na.rm = TRUE))
minDateDAMAGE = data.frame(Date = do.call("c", damageINDIVIDUAL[["Date"]]))
ggplot() +
theme_minimal() +
labs(x = "Time", y = "Probability Distribution of Damage") +
geom_line(data = DFdamage,
aes(x = Date, y = mean_DAMAGE), color = "red") +
geom_ribbon(data = DFdamage,
aes(x = Date, ymin = q025_DAMAGE, ymax = q975_DAMAGE), alpha = 0.5, color = NA, fill = "grey10") +
geom_ribbon(data = DFdamage,
aes(x = Date, ymin = min_DAMAGE, ymax = max_DAMAGE), alpha = 0.5, color = NA, fill = "grey90") |
setMethodS3("getBaseline", "ChipEffectSet", function(this, force=FALSE, verbose=FALSE, ...) {
verbose <- Arguments$getVerbose(verbose)
if (verbose) {
pushState(verbose)
on.exit(popState(verbose))
}
verbose && enter(verbose, "Getting CEL file to store baseline signals")
key <- list(dataset=getFullName(this), samples=getNames(this))
id <- getChecksum(key)
filename <- sprintf(".baseline,%s.CEL", id)
verbose && enter(verbose, "Searching for an existing file")
path <- getPath(this)
paths <- c(path)
if (getOption(aromaSettings, "devel/dropRootPathTags", TRUE)) {
path <- dropRootPathTags(path, depth=2, verbose=less(verbose, 5))
paths <- c(paths, path)
paths <- unique(paths)
}
verbose && cat(verbose, "Paths:")
verbose && print(verbose, paths)
verbose && cat(verbose, "Filename: ", filename)
pathname <- NULL
for (kk in seq_along(paths)) {
path <- paths[kk]
verbose && enter(verbose, sprintf("Searching path
verbose && cat(verbose, "Path: ", path)
pathnameT <- Arguments$getReadablePathname(filename, path=path, mustExist=FALSE)
verbose && cat(verbose, "Pathname: ", pathnameT)
if (isFile(pathnameT)) {
pathname <- pathnameT
verbose && cat(verbose, "Found an existing file.")
verbose && exit(verbose)
break
}
verbose && exit(verbose)
}
verbose && cat(verbose, "Located pathname: ", pathname)
verbose && exit(verbose)
df <- getOneFile(this)
if (isFile(pathname)) {
verbose && enter(verbose, "Loading existing data file")
res <- newInstance(df, pathname)
verbose && exit(verbose)
} else {
verbose && enter(verbose, "Allocating empty data file")
path <- paths[length(paths)]
verbose && cat(verbose, "Path: ", path)
verbose && cat(verbose, "Filename: ", filename)
pathname <- Arguments$getWritablePathname(filename, path=path, mustNotExist=TRUE)
verbose && enter(verbose, "Retrieving CEL file")
res <- createFrom(df, filename=pathname, path=NULL, methods="create",
clear=TRUE, force=force, verbose=less(verbose))
verbose && print(verbose, res)
verbose && exit(verbose)
verbose && exit(verbose)
}
df <- NULL
verbose && exit(verbose)
res
}, protected=TRUE)
setMethodS3("getBaseline", "SnpChipEffectSet", function(this, ...) {
res <- NextMethod("getBaseline")
res$mergeStrands <- getMergeStrands(this)
res
}, protected=TRUE)
setMethodS3("getBaseline", "CnChipEffectSet", function(this, ...) {
res <- NextMethod("getBaseline")
res$combineAlleles <- getCombineAlleles(this)
res
}, protected=TRUE) |
simulate.jointNmix <-
function(object, ...) {
lam2transform <- object$lam2transform
includepsi <- object$includepsi
parms <- coef(object)
np1 <- ncol(object$Xp1)
np2 <- ncol(object$Xp2)
nl1 <- ncol(object$Xl1)
nl2 <- ncol(object$Xl2)
npsi <- ncol(object$Xpsi)
pr1 <- as.numeric(plogis(object$Xp1 %*% parms[1:np1]))
pr2 <- as.numeric(plogis(object$Xp2 %*% parms[(np1+1):(np1+np2)]))
lam1 <- as.numeric(exp(object$Xl1 %*% parms[(np1+np2+1):(np1+np2+nl1)]))
lam2 <- as.numeric(exp(object$Xl2 %*% parms[(np1+np2+nl1+1):(np1+np2+nl1+nl2)]))
if(lam2transform) lam2 <- lam2/(1+lam2)
if(includepsi) psi <- as.numeric(exp(object$Xpsi %*% parms[(length(parms)-npsi+1):(length(parms))]))
theta1 <- exp(parms[(np1+np2+nl1+nl2+1)])
theta2 <- exp(parms[length(parms)])
R <- dim(object$sp1)[1]
T_ <- dim(object$sp1)[2]
pr1 <- matrix(pr1, byrow=TRUE, ncol=T_)
pr2 <- matrix(pr2, byrow=TRUE, ncol=T_)
if(object$mixture[1]=="P") Ni1 <- rpois(R, lam1)
if(object$mixture[1]=="NB") Ni1 <- rnbinom(R, mu=lam1, size=theta1)
if(object$mixture[2]=="P") {
if(!includepsi) {
Ni2 <- rpois(R, lam2 * Ni1)
} else {
Ni2 <- rpois(R, psi + lam2 * Ni1)
}
}
if(object$mixture[2]=="NB") {
if(!includepsi) {
Ni2 <- rnbinom(R, mu=lam2 * Ni1, size=theta2)
} else {
Ni2 <- rnbinom(R, mu=psi + lam2 * Ni1, size=theta2)
}
}
sdata1 <- matrix(0, ncol=T_, nrow=R)
sdata2 <- matrix(0, ncol=T_, nrow=R)
for(i in 1:T_) sdata1[,i] <- rbinom(R, Ni1, pr1[,i])
for(i in 1:T_) sdata2[,i] <- rbinom(R, Ni2, pr2[,i])
return(list("sp1"=sdata1, "sp2"=sdata2))
} |
library(benchr)
p <- benchr:::timer_precision()
e <- benchr:::timer_error()
expect_equal(class(p), "numeric")
expect_equal(length(p), 1L)
expect_true(p < 0.001)
expect_equal(class(e), "numeric")
expect_equal(length(e), 1L)
expect_true(e > 0)
if (.Platform$OS.type != "windows") {
expect_true(benchr:::do_timing(quote(Sys.sleep(0.1)), .GlobalEnv) >= 0.1)
expect_true(benchr:::do_timing(quote(Sys.sleep(0.2)), .GlobalEnv) >= 0.2)
expect_true(benchr:::do_timing(quote(Sys.sleep(0.3)), .GlobalEnv) >= 0.3)
expect_true(benchr:::do_timing(quote(Sys.sleep(0.1)), .GlobalEnv) >= e)
} |
library(OpenMx)
dn <- paste("m",1:2, sep="")
dataCov <- matrix(c(1,.2,.2,1.5), nrow=2, dimnames=list(dn,dn))
dataMeans <- c(-.2, .3)
names(dataMeans) <- dn
n2 <- mxModel("normal2",
mxData(observed=dataCov, type="cov",
means=dataMeans, numObs=35),
mxMatrix(name="cov", "Symm", 2, 2, free=T, values = c(1, 0, 1),
labels = c("var1", "cov12", "var2"), dimnames=list(dn,dn)),
mxMatrix(name="mean", "Full", 1, 2, free=T, labels=dn, dimnames=list(NULL,dn)),
mxFitFunctionML(),
mxExpectationNormal("cov", "mean"))
plan <- mxComputeSequence(list(
mxComputeNewtonRaphson(),
mxComputeOnce('fitfunction', 'information', 'hessian'),
mxComputeStandardError(),
mxComputeHessianQuality(),
mxComputeReportDeriv()))
for (retry in 1:2) {
if (retry == 2) n2 <- mxModel(n2, plan)
n2Fit <- mxRun(n2)
omxCheckCloseEnough(n2Fit$output$fit, 81.216, .01)
omxCheckCloseEnough(n2Fit$cov$values, (34/35) * dataCov, 1e-4)
omxCheckCloseEnough(c(n2Fit$mean$values), dataMeans, 1e-4)
omxCheckCloseEnough(log(n2Fit$output$conditionNumber), 1.63, .2)
omxCheckCloseEnough(c(n2Fit$output$standardErrors),
c(0.232, 0.203, 0.348, 0.166, 0.204), .01)
} |
readDcp <- function(con, fields=c("rawIntensities", "normalizedIntensities", "calls", "thetas", "thetaStds", "excludes"), cells=NULL, units=NULL, .nbrOfUnits=NULL, ...) {
readElements <- function(con, idxs, nbrOfElements, size=1, skip=FALSE, ..., drop=TRUE) {
readBin2 <- function(con, what, size, signed, n) {
if (mode(what) == "raw") {
n <- n * size;
size <- 1;
}
readBin(con, what=what, size=size, signed=signed, n=n, endian="little")
}
if (skip) {
seek(con, where=size*nbrOfElements, origin="current", rw="read")
return(NULL);
}
values <- readBin2(con=con, size=size, ..., n=nbrOfElements);
if (mode(values) == "raw") {
if (length(values) %% size != 0) {
stop("File format error/read error: The number of bytes read is not a multiple of ", size, ": ", length(values));
}
dim(values) <- c(size, (length(values) %/% size));
if (!is.null(idxs)) {
values <- values[,idxs,drop=FALSE];
}
if (drop)
values <- drop(values);
} else {
if (!is.null(idxs))
values <- values[idxs];
}
values;
}
readCells <- function(con, cells, what=integer(), size=2, signed=FALSE, ...) {
readElements(con=con, idxs=cells, nbrOfElements=nbrOfCells,
what=what, size=size, signed=signed, ...);
}
readUnits <- function(con, units, what=double(), size=2, signed=FALSE, ...) {
readElements(con=con, idxs=units, nbrOfElements=nbrOfUnits,
what=what, size=size, signed=signed, ...);
}
if (is.character(con)) {
pathname <- con;
if (!file.exists(pathname)) {
stop("File not found: ", pathname);
}
con <- file(con, open="rb");
on.exit({
if (!is.null(con))
close(con);
con <- NULL;
});
}
if (!inherits(con, "connection")) {
stop("Argument 'con' must be either a connection or a pathname: ",
mode(con));
}
fields <- match.arg(fields, several.ok=TRUE);
res <- list();
res$header <- readDcpHeader(con=con);
nbrOfCells <- res$header$CellDim^2;
stopifnot(nbrOfCells >= 0)
if (is.null(.nbrOfUnits)) {
conInfo <- summary(con);
if (conInfo$class != "file") {
stop("Cannot infer the value of '.nbrOfUnits' from the connection, because it is not a file: ", conInfo$class);
}
pathname <- conInfo$description;
if (!is.element(res$header$Format, c(3,4))) {
stop("Cannot infer the value of '.nbrOfUnits' from the file. The file format is not v3 or v4 but v", res$header$Format, ": ", pathname);
}
nbrOfBytes <- file.info(pathname)$size;
fileHeaderSize <- 3028;
nbrOfUnitBytes <- nbrOfBytes - fileHeaderSize - 2*2*nbrOfCells;
.nbrOfUnits <- as.integer(nbrOfUnitBytes / 13);
if (nbrOfUnitBytes %% 13 != 0) {
stop("Internal file format assumption error: Cannot infer the value of '.nbrOfUnits' from the file. The number of inferred bytes storing unit data is not a multiple of 13: ", nbrOfUnitBytes);
}
} else {
.nbrOfUnits <- .argAssertRange(as.integer(.nbrOfUnits),
range=c(1, nbrOfCells));
if (length(.nbrOfUnits) != 1)
stop("Argument '.nbrOfUnits' must be a single integer.");
}
nbrOfUnits <- .nbrOfUnits;
if (!is.null(cells)) {
cells <- .argAssertRange(as.integer(cells), range=c(1, nbrOfCells));
}
if (!is.null(units)) {
units <- .argAssertRange(as.integer(units), range=c(1, nbrOfCells));
}
for (field in c("rawIntensities", "normalizedIntensities")) {
res[[field]] <- readCells(con, cells=cells, skip=(!field %in% fields), drop=TRUE);
}
field <- "calls";
res[[field]] <- readUnits(con, units=units, what=raw(), size=1,
skip=(!field %in% fields), drop=TRUE);
skip <- !any(c("thetas", "thetaStds", "excludes") %in% fields);
raw <- readUnits(con, units=units, what=raw(), size=12, skip=skip);
if (!skip) {
n <- ncol(raw);
field <- "thetas";
if (field %in% fields) {
res[[field]] <- .readFloat(con=raw[1:4,], n=n);
}
raw <- raw[-(1:4),,drop=FALSE];
field <- "thetaStds";
if (field %in% fields) {
res[[field]] <- .readFloat(con=raw[1:4,], n=n);
}
raw <- raw[-(1:4),,drop=FALSE];
field <- "excludes";
if (field %in% fields) {
res[[field]] <- .readInt(raw[1:4,], n=n);
}
}
raw <- NULL
res;
} |
if (require("testthat") && require("sjmisc")) {
data(efc)
efc$ID <- sample(1:4, nrow(efc), replace = TRUE)
test_that("de_mean", {
de_mean(efc, c12hour, barthtot, grp = ID)
de_mean(efc, c12hour, barthtot, grp = ID, append = FALSE)
de_mean(efc, c12hour, barthtot, grp = ID, append = FALSE, suffix.dm = "dm", suffix.gm = "gm")
de_mean(efc, c12hour, barthtot, grp = ID, suffix.dm = "dm", suffix.gm = "gm")
de_mean(efc, c12hour, barthtot, grp = "ID")
})
} |
.laser.gsr<-
function (Source, Search, Replace, char = FALSE)
{
if (length(Search) != length(Replace))
stop("Search and Replace Must Have Equal Number of Items\n")
Changed <- as.character(Source)
if (char == FALSE) {
for (i in 1:length(Search)) {
Changed <- replace(Changed, Changed == Search[i],
Replace[i])
}
}
else if (char == TRUE) {
for (i in 1:length(Search)) {
Changed <- replace(Changed, Changed == Search[i],
paste(Replace[i]))
}
}
Changed
}
.laser.gettipdata<-
function (tipdata, phy)
{
if (is.data.frame(tipdata)) {
x <- as.vector(tipdata[, 1])
names(x) <- row.names(tipdata)
}
else {
x <- tipdata
}
if (class(phy) != "phylo")
stop("object \"phy\" is not of class \"phylo\"")
if (is.null(phy$edge.length))
stop("your tree has no branch lengths: invalid input")
tmp <- phy$edge
nb.tip <- length(phy$tip.label)
if (phy$Nnode != nb.tip - 1)
stop("\"phy\" is not fully dichotomous")
if (length(x) != nb.tip)
stop("length of phenotypic and of phylogenetic data do not match")
if (any(is.na(x)))
stop("method can't be used with missing data...")
phenotype <- as.numeric(rep(NA, nb.tip + phy$Nnode))
names(phenotype) <- 1:max(phy$edge)
if (is.null(names(x))) {
phenotype[1:nb.tip] <- x
}
else {
if (!any(is.na(match(names(x), phy$tip.label))))
phenotype[1:nb.tip] <- x[phy$tip.label]
else {
phenotype[1:nb.tip] <- x
warning("the names of argument \"x\" and the names of the tip labels\ndid not match\n")
}
}
phy$phenotype <- rep(NA, (nb.tip + phy$Nnode - 1))
for (i in 1:length(phenotype)) {
phy$phenotype[as.numeric(phy$edge[, 2]) == names(phenotype[i])] <- phenotype[i]
}
return(phy)
}
.laser.splitedgematrix<-
function (phy, node)
{
x <- branching.times(phy)
rootnode <- length(phy$tip.label) + 1
phy$tag <- rep(1, nrow(phy$edge))
if (node >= rootnode) {
node.desc <- node
pos <- 1
phy$tag[phy$edge[, 1] == node.desc[1]] <- 2
while (pos != (length(node.desc) + 1)) {
temp <- .get.desc.of.node(node.desc[pos], phy)
temp <- temp[temp > rootnode]
for (k in 1:length(temp)) {
phy$tag[phy$edge[, 1] == temp[k]] <- 2
}
node.desc <- c(node.desc, temp)
pos <- pos + 1
}
}
else if (node > 0)
phy$tag[phy$edge[, 2] == node] <- 2
z <- cbind(phy$edge, .laser.gsr(phy$edge[, 1], names(x), x), phy$edge.length,
phy$phenotype, phy$tag)
z <- matrix(as.numeric(z), dim(z))
z <- as.data.frame(z)
return(z)
}
.laser.getlambda<-
function (zmat, rootnode, rbounds, para = 0.01, eps, combined = TRUE)
{
int <- zmat[zmat[, 2] > rootnode, ]
term <- zmat[zmat[, 2] < rootnode, ]
nint <- nrow(int)
nterm <- nrow(term)
betaF <- function(r, t1) {
xf <- (exp(r * t1) - 1)/(exp(r * t1) - eps)
xf
}
Lfunc_tax <- function(p) {
r <- p
(sum(log(1 - betaF(r, term[1:nterm, 4]))) + sum((term[1:nterm,
5] - 1) * log(betaF(r, term[1:nterm, 4]))))
}
Lfunc_phy <- function(p) {
r <- p
(nint * log(r) - r * sum(int[1:nint, 4]) - sum(log(1 -
(eps * exp(-r * int[1:nint, 3])))))
}
Lfunc_comb <- function(p) {
r <- p
(sum(log(1 - betaF(r, term[1:nterm, 4]))) + sum((term[1:nterm,
5] - 1) * log(betaF(r, term[1:nterm, 4]))) + nint *
log(r) - r * sum(int[1:nint, 4]) - sum(log(1 - (eps *
exp(-r * int[1:nint, 3])))))
}
res <- list()
if (combined == TRUE) {
if (nrow(int) == 0)
tempres <- optimize(Lfunc_tax, interval = rbounds,
maximum = TRUE)
else tempres <- optimize(Lfunc_comb, interval = rbounds,
maximum = TRUE)
}
else {
tempres <- optimize(Lfunc_tax, interval = rbounds, maximum = TRUE)
}
res$LH <- tempres$objective
res$lambda <- tempres$maximum/(1 - eps)
res$r <- tempres$maximum
res$eps <- eps
res <- as.data.frame(res)
return(res)
}
.laser.fitNDR_1rate<-
function (phy, eps = 0, rbounds = c(1e-04, 0.5), combined = TRUE)
{
z <- .laser.splitedgematrix(phy, phy$Nnode)
r1 <- .laser.getlambda(z, rootnode = (length(phy$tip.label) +
1), rbounds = rbounds, para = 0.01, eps, combined = combined)
res <- list()
res$LH <- r1$LH
res$aic <- (-2 * r1$LH) + 2
res$r <- r1$r
res$lambda <- r1$lambda
res$eps <- eps
res <- as.data.frame(res)
return(res)
}
sim.mecca <-
function(phy, richness, cladeAges, model, prop, makeNewTipTrees = TRUE, mytiptrees = NULL, hotBranches = NULL) {
root.age = max(node.depth.edgelength(phy));
if(makeNewTipTrees == FALSE & is.null(mytiptrees)) stop("there are no tip trees provided");
cladeAncStates <- .mecca.nodesim(phy, model, prop, hotBranches);
Svar <- numeric(length(richness));
Smean <- numeric(length(richness));
if(makeNewTipTrees == TRUE) {
treelist<-list();
treelist[which(richness==1)] <- cladeAges[richness==1];
for(i in which(richness>1)) {
treelist[[i]]<- .mecca.fasttreesim(n=richness[i], lambda = prop$birth, mu=prop$death, rho = 1, origin = cladeAges[i]);
}
} else {
treelist <- mytiptrees;
}
for(i in 1:length(treelist)) {
if(!is.numeric(treelist[[i]])) {
if(!model == "twoRate") dat <- .mecca.tipsim(treelist[[i]], model, prop, cladeAncStates[i], root.age);
if(model == "twoRate") {
if (i %in% hotBranches) { Branch = "hot" } else { Branch <- "not" }
dat <- .mecca.tipsim(phy = treelist[[i]], model = model, prop = prop, cladeAncStates[i], BranchState = Branch);
}
Svar[i]<-var(dat);
Smean[i]<-mean(dat);
} else {
if(model == "twoRate") {
if (i %in% hotBranches) { Branch = "hot" } else { Branch <- "not" }
dat <- .mecca.singletiptrait(model, prop, cladeAges[i], cladeAncStates[i], root.age, BranchState = Branch);
}
else {
dat <- .mecca.singletiptrait(model, prop, cladeAges[i], cladeAncStates[i], root.age);
}
Smean[i] <- dat;
Svar[i] <- 0;
}
}
return(list("trees" = treelist, "Smean" = Smean, "Svar" = Svar));
}
.mecca.makecaloutput<-
function(model, Ncalibrations, Nclades) {
if(model == "BM") k <- 5;
if(model == "Trend" | model == "twoRate") k <- 6;
output <- matrix(NA, nrow = Ncalibrations, ncol = k + 2*Nclades);
if(model == "BM") colnames(output) <- c("birth", "death","logLk", "sigmasq","root", paste("var", seq(1, Nclades), sep = ""), paste("Mean", seq(1, Nclades), sep = ""));
if(model == "Trend") colnames(output) <- c("birth", "death","logLk", "sigmasq","root","mu", paste("var", seq(1, Nclades), sep = ""), paste("Mean", seq(1, Nclades), sep = ""));
if(model == "twoRate") colnames(output) <- c("birth", "death","logLk", "sigmasq1","sigmasq2","root", paste("var", seq(1, Nclades), sep = ""), paste("Mean", seq(1, Nclades), sep = ""));
return(output);
}
.mecca.proposal<-
function(model, trait.params, trait.widths, prior.list, SigmaBounds, scale, ngen) {
if(model == "BM") {
if (ngen %% 2 == 1) {
trait.params$sigmasq <- .mecca.getproposal(trait.params$sigmasq, trait.widths$sigmasq * scale, min = SigmaBounds[1], max = SigmaBounds[2])
} else {
trait.params$root <- .mecca.getproposal(trait.params$root, trait.widths$root * scale, min = prior.list$priorMean[1], max = prior.list$priorMean[2])
}
}
if(model == "twoRate") {
if (ngen %% 2 == 1) {
trait.params$sigmasq1 <- .mecca.getproposal(trait.params$sigmasq1, trait.widths$sigmasq1 * scale, min = SigmaBounds[1], max = SigmaBounds[2])
trait.params$sigmasq2 <- .mecca.getproposal(trait.params$sigmasq2, trait.widths$sigmasq2 * scale, min = SigmaBounds[1], max = SigmaBounds[2])
} else {
trait.params$root <- .mecca.getproposal(trait.params$root, trait.widths$root * scale, min = prior.list$priorMean[1], max = prior.list$priorMean[2])
}
}
if(model == "Trend"){
if (ngen %% 2 == 1) {
trait.params$sigmasq <- .mecca.getproposal(as.numeric(trait.params$sigmasq), as.numeric(trait.widths$sigmasq) * scale, min = SigmaBounds[1], max = SigmaBounds[2])
trait.params$mu <- .mecca.getproposal(trait.params$mu, trait.widths$mu * scale, min = prior.list$priorMu[1], max = prior.list$priorMu[2])
} else {
trait.params$root <- .mecca.getproposal(trait.params$root, trait.widths$root * scale, min = prior.list$priorMean[1], max = prior.list$priorMean[2])
}
}
return(trait.params)
}
.mecca.calproposal <-
function(model, prior.list, sigmaPriorType, SigmaBounds, rootPriorType, thetaB, thetaD, propWidth) {
while(1) {
birth = .mecca.getproposal(thetaB,propWidth, 0, Inf);
death = .mecca.getproposal(thetaD, propWidth, 0, Inf);
if(birth > death) (break);
}
sigma = .mecca.priordrawsig(prior.list$priorSigma[1], prior.list$priorSigma[2], sigmaPriorType, SigmaBounds)
root = .mecca.priordrawmean(prior.list$priorMean[1], prior.list$priorMean[2], rootPriorType);
if(model == "BM") return(prop = list(birth = birth, death = death, sigmasq = sigma, root = root));
if(model == "Trend") return(prop = list(birth = birth, death = death, sigmasq = sigma, root = root, mu = runif(1, min = prior.list$priorMu[1],max = prior.list$priorMu[2])));
if(model == "twoRate") return(prop = list(birth = birth, death = death, sigmasq1 = sigma, sigmasq2 =.mecca.priordrawsig(prior.list$priorSigma[1], prior.list$priorSigma[2], sigmaPriorType, SigmaBounds), root = root));
}
startingpt.mecca <-
function(calibrationOutput, phy, cladeMean, cladeVariance, tolerance = 0.01, plsComponents, BoxCox = TRUE) {
if(BoxCox == TRUE & length(calibrationOutput) < 6) stop("there are no parameters in the calibration output to do boxcox transformation. Try rerunning calibration with BoxCox = TRUE");
m <- match(phy$tip.label, names(cladeMean));
cladeMean <- cladeMean[m];
m <- match(phy$tip.label, names(cladeVariance));
cladeVariance <- cladeVariance[m];
if( length(which(cladeVariance == 0))>0) {
cladeVariance <- cladeVariance[-which(cladeVariance==0)];
}
obs <- c(cladeVariance, cladeMean);
names(obs) <- c(paste(names(cladeVariance), "var", sep = "_"), paste(names(cladeMean), "mean", sep = "_"));
stdobs <- obs;
bdcal <- as.matrix(calibrationOutput$diversification);
bmcal <- as.matrix(calibrationOutput$trait);
startingBirth <- as.numeric(bdcal[1,1]);
startingDeath <- as.numeric(bdcal[1,2]);
if(BoxCox == TRUE) {
stdz <- calibrationOutput$stdz;
lambda <- calibrationOutput$lambda;
GM <- calibrationOutput$GM;
boxcox <- calibrationOutput$BoxCox;
}
K <- ncol(plsComponents);
Nsims <- nrow(bdcal)
if(BoxCox == TRUE) {
for(i in 1:length(stdobs)) {
stdobs[i] <- 1 + (stdobs[i] - stdz$min[i]) / (stdz$max[i] - stdz$min[i]);
stdobs[i] <-(stdobs[i]^lambda[i] - 1) / (lambda[i] * GM[i]^(lambda[i]-1));
stdobs[i] <- (stdobs[i] - boxcox$BCmeans[i])/boxcox$BCstd[i];
}
}
obsPLS <- numeric(K);
for(i in 1:length(obsPLS)) {
obsPLS[i] <- sum(stdobs * plsComponents[, i]);
}
plsSim <- matrix(NA, nrow = Nsims, ncol = K);
params <- bmcal[ , 1: K];
stats <- bmcal[ , - seq(1, K)];
for(i in 1:Nsims) {
plsSim[i, ] <- .mecca.extractpls(stats[i,], plsComponents, K);
}
dmat <- numeric(Nsims);
for (i in 1:Nsims) {
dmat[i] <- dist(rbind(obsPLS, plsSim[i, ]));
}
pdmat <- cbind(params, dmat);
bmretained <- pdmat[order(as.data.frame(pdmat)$dmat),][seq(1, Nsims * tolerance) , ];
tuning <- matrix(data = NA, nrow = K, ncol = 2);
rownames(tuning) <- colnames(bmretained)[1:K];
colnames(tuning) <- c("starting", "width");
for(i in 1:K) {
tuning[i, 1] <- as.numeric(bmretained[1,i]);
tuning[i, 2] <- sd(bmretained[, i]);
}
if(BoxCox == TRUE) {
return(list("tuning" = tuning, "startingBirth" = startingBirth, "startingDeath" = startingDeath, "dcrit" = max(bmretained[,K+1]), "obsTraits" = obs, "plsObserved" = obsPLS, "plsLoadings" = plsComponents, "stdz" = stdz, "lambda" = lambda, "GM" = GM, "BoxCox" = boxcox));
}
if(BoxCox == FALSE) {
return(list("tuning" = tuning, "startingBirth" = startingBirth, "startingDeath" = startingDeath, "dcrit" = max(bmretained[,K+1]), "obsTraits" = obs, "plsObserved" = obsPLS, "plsLoadings" = plsComponents));
}
}
.mecca.nodestatestworate <-
function(phy, prop, hotBranches) {
cbind(phy$edge, phy$edge.length) -> edge.mat
edge.mat <- edge.mat[- which(edge.mat[ ,2] <= length(phy$tip.label)), ];
rootNode <- length(phy$tip.label) + 1;
rootState <- prop$root;
currentNode <- rootNode;
nodeStates <- numeric(length(phy$tip.label) - 1);
names(nodeStates) <- seq(length(phy$tip.label) + 1, (length(phy$tip.label) * 2) - 1, 1);
nodeStates[1] <- rootState
for (i in 2:length(nodeStates)) {
currentNode <- currentNode + 1;
parent <- edge.mat[which(edge.mat[ ,2] == currentNode), 1];
parentValue <- nodeStates[which(names(nodeStates) == parent)];
if(currentNode %in% hotBranches) {
sigma <- prop$sigmasq2;
} else {
sigma <- prop$sigmasq1
}
nodeStates[i] <- rnorm(1, parentValue, sqrt(sigma * edge.mat[which(edge.mat[ ,2] == currentNode), 3]));
}
return(nodeStates);
}
.mecca.normalpriorratio <-
function(currentState, proposedState, mean, sd) {
h <- dnorm(proposedState, mean, sd) / dnorm(currentState, mean, sd);
if(h > 1) { currentState <- proposedState }
if (h < 1) {
rnum <- runif(1);
if (h < rnum) {
currentState <- proposedState;
}else{
currentState <- currentState;
}
}
return(currentState);
}
.mecca.tipsim<-
function(phy, model, prop, node.state, root.age, BranchState = "not") {
if(model == "BM") {
dat <- .mecca.fastbm(phy, node.state, prop$sigmasq, mu = 0)$tipStates;
}
if(model == "Trend") {
dat <- .mecca.fastbm(phy, node.state, prop$sigmasq, prop$mu)$tipStates;
}
if(model == "twoRate") {
if(BranchState == "not") {
dat <- .mecca.fastbm(phy, node.state, prop$sigmasq1, mu = 0)$tipStates;
} else if(BranchState == "hot") {
dat <- .mecca.fastbm(phy, node.state, prop$sigmasq2, mu = 0)$tipStates;
}
}
return(dat);
}
.mecca.acceptance <-
function(trait.params, prop.params, distribution, params) {
if(distribution == "uniform") {
return("accept");
}
if(distribution == "normal") {
curr.rates <- trait.params[grep("sigma", colnames(trait.params))];
prop.rates <- prop.params[grep("sigma", colnames(prop.params))];
k <- length(curr.rates);
priorden <- numeric(k)
for(i in 1:k) {
priorden[i] <- dnorm(as.numeric(prop.rates[i]), mean = params[1], sd = params[2]) / dnorm(as.numeric(curr.rates[i]), mean = params[1], sd = params[2]);
}
priorden <- prod(priorden);
p <- runif(1);
if(priorden >= p) {
return("accept")
} else {
return("reject")
}
}
}
.mecca.allbranches <-
function(phy, node) {
node <- as.numeric(node);
n <- length(phy$tip.label);
if(node <= n) return(node);
l <- .get.desc.of.node(node, phy);
for(j in l) {
if(j > n) l<-c(l, .mecca.allbranches(phy, j));
}
return(l);
}
.mecca.boxcox <-
function(summaries, stdz, lambda, GM, boxcox) {
for(i in 1:length(summaries)) {
summaries[i] <- 1 + (summaries[i] - stdz$min[i]) / (stdz$max[i] - stdz$min[i]);
summaries[i] <-(summaries[i]^lambda[i] - 1) / (lambda[i] * GM[i]^(lambda[i]-1));
summaries[i] <- (summaries[i] - boxcox$BCmeans[i])/boxcox$BCstd[i];
}
return(summaries);
}
calibrate.mecca <-
function(phy, richness, model = c("BM", "Trend", "twoRate"), prior.list = list(priorSigma = c(-4.961845, 4.247066), priorMean = c(-10, 10)), Ncalibrations = 10000, sigmaPriorType = "uniform", rootPriorType = "uniform", divSampleFreq = 0, initPars = "ML", propWidth = 0.1, SigmaBounds = c(-4.961845, 4.247066), hotclade = NULL, BOXCOX = TRUE, optimRange =c(-1000, 10)) {
name.check(phy, richness)->nc;
if(!nc == "OK") { stop("names in tree and data do not match") }
if(!sum(is.na(richness) == 0)) { stop("richness contains missing values") }
Nclades <- length(richness);
phy$node.label <- NULL;
hotBranches <- NULL;
match(phy$tip.label, names(richness)) -> m;
richness[m] -> richness;
cladeAges <- .mecca.cladeage(phy);
if(model =="BM") k <- 2; if(model == "ACDC"| model == "Trend"| model == "twoRate" | model == "SSP") k <- 3; if(model == "OU") k <- 4;
if(model=="twoRate") {
if(is.null(hotclade)) { stop("if using a two rate model you need to specify the hot clade") }
hotBranches <- .mecca.gethotbranches(phy, hotclade[1], hotclade[2]);
}
if(model == "Trend") {
if (is.null(prior.list$priorMu)) {prior.list$priorMu = c(-0.5,0.5); warning("No mu prior specified for Trend model. Using default prior of -0.5:0.5") }
}
output <- .mecca.makecaloutput(model, Ncalibrations, Nclades);
if (length(initPars) > 1) {
thetaB <- initPars[1]; thetaD <- initPars[2];
} else if (initPars == "ML") {
mleBD <- .mecca.getdivMLE(phy, richness); thetaB <- mleBD$lamda; thetaD <- mleBD$mu
}
Lk <- .mecca.logLP(phy, thetaB, thetaD) + .mecca.logLT(phy, richness, thetaB, thetaD);
pb <- txtProgressBar(min = 0, max = Ncalibrations, char = "-", style = 3);
for(ncal in 1:Ncalibrations) {
cvar <- numeric(length(richness));
cmeans <- numeric(length(richness));
prop <- .mecca.calproposal(model, prior.list, sigmaPriorType, SigmaBounds, rootPriorType, thetaB, thetaD, propWidth)
propLk <- .mecca.logLP(phy, prop$birth, prop$death) + .mecca.logLT(phy, richness, prop$birth, prop$death);
if(propLk== - Inf) {
LKratio <- 0 ;
} else {
LKratio <- exp(propLk - Lk);
}
if(LKratio >= 1) {
thetaB <- prop$birth; thetaD <- prop$death; Lk <- propLk;
}
if (LKratio < 1) {
p <- runif(1);
if (p <= LKratio) {
thetaB <- prop$birth; thetaD <- prop$death; Lk <- propLk;
} else {
prop$birth <- thetaB; prop$death <- thetaD;
}
}
if(ncal == 1 | divSampleFreq == 0 |ncal %% divSampleFreq == 0) {
calSim <- sim.mecca(phy = phy, richness = richness, cladeAges = cladeAges, model = model, prop = prop, makeNewTipTrees = TRUE, mytiptrees = NULL, hotBranches = hotBranches);
tipTrees <- calSim$trees;
} else {
calSim <- .mecca.generatetipsummaries(phy, model, tipTrees, prop = prop, hotBranches = hotBranches, richness=richness);
}
output[ncal, ] <- .mecca.paramsample(model, prop, Lk, calSim);
setTxtProgressBar(pb, ncal);
}
close(pb);
div.cal <- output[, c(1,2,3)];
trait.cal <- output[, -c(1,2,3)];
if(length(which(apply(trait.cal, 2, function(x) sum(x) == 0) == TRUE))>0) {
trait.cal <- trait.cal[, -which(apply(trait.cal, 2, function(x) sum(x) == 0) == TRUE)];
}
if(BOXCOX == TRUE) {
trait.cal <- as.data.frame(trait.cal)
stat <- trait.cal[, -(1:k)];
param <- trait.cal[ ,1:k];
myMax<-array(0, dim = length(stat));
myMin<-array(0, dim = length(stat));
lambda<-array(0, dim = length(stat));
myGM<-array(0, dim = length(stat));
myBCMeans <- array(0, dim = length(stat));
myBCSDs <- array(0, dim = length(stat));
for(i in 1:length(stat)){
myMax[i]<-max(stat[,i]);
myMin[i]<-min(stat[,i]);
stat[ ,i] <- 1+(stat[ ,i] - myMin[i])/(myMax[i]-myMin[ i]);
}
mecca.lm <- mecca.env <- NULL
lmreturn=function(stati, param, ...){
mecca.dat=as.data.frame(cbind(y=stati, param))
mecca.lm<-as.formula(mecca.dat)
mecca.env<-environment(mecca.lm)
optimize(.mecca.maxboxcox, ..., env=mecca.env)$maximum
}
for(i in 1:length(stat)) {
lambda[i] = lmreturn(stat[,i], param, interval = optimRange, maximum = TRUE)
print(paste(colnames(stat)[i], lambda[i]))
}
for(i in 1:length(stat)) {
myGM[i]<-exp(mean(log(stat[,i])));
stat[,i]<-(stat[ ,i]^lambda[i] - 1) / (lambda[i] * myGM[i]^(lambda[i]-1));
myBCSDs[i] <- sd(stat[,i]);
myBCMeans[i] <- mean(stat[,i]);
stat[,i]<-(stat[,i] -myBCMeans[i])/myBCSDs[i];
}
res=list("diversification" = div.cal, "trait" = cbind(param, stat), "stdz" = list("min" = myMin, "max" = myMax), "lambda" = lambda, "GM"=myGM, "BoxCox" = list("BCmeans" = myBCMeans, "BCstd" = myBCSDs));
}
if(BOXCOX == FALSE) {
res=list("diversification" = div.cal, "trait" = trait.cal);
}
class(res)=c("mecca", "calibration", class(res))
return(res)
}
.mecca.maxboxcox <-
function(lambda, env) {
myboxcox<-boxcox(env$rval, lambda=lambda, data=env$object, interp=T, eps=1/50, plotit = FALSE);
return(myboxcox$y[1]);
}
.mecca.cladeage <-
function(phy) {
which(phy$edge[ ,2] <= length(phy$tip.label)) -> tips;
cladeAges <- phy$edge.length[tips];
tipNumbers <- phy$edge[tips, 2];
names(cladeAges) <- phy$tip.label[tipNumbers];
match(phy$tip.label, names(cladeAges)) -> m;
cladeAges[m]->cladeAges;
return(cladeAges)
}
.mecca.cladestates <-
function(nodeStates, phy) {
cladeAncStates <- numeric(length(phy$tip.label));
for(k in 1:length(cladeAncStates)) {
parent <- .mecca.parentnode(phy, k);
cladeAncStates[k] <- nodeStates[which(names(nodeStates) == parent)];
}
return(cladeAncStates);
}
.mecca.extractpls <-
function(p, plsdat, Ncomp) {
x <- numeric(Ncomp);
for(i in 1:Ncomp) {
x[i] <- sum(p * plsdat[, i])
}
return(x)
}
.mecca.fastbm <-
function(tree, alpha, sig2, mu) {
n <- length(tree$edge.length);
x <- rnorm(n=n, mean = mu * tree$edge.length, sd=sqrt(sig2*tree$edge.length))
y <- array(alpha, dim=n+1);
for(i in 1:n){
y[tree$edge[i,2]]<-y[tree$edge[i,1]]+x[i];
}
nodeStates<-y[(length(tree$tip.label)+1):(n+1)];
names(nodeStates)<-as.character((length(tree$tip.label)+1):(n+1));
tipStates<-y[1:length(tree$tip.label)];
names(tipStates)<-tree$tip.label;
return(list(nodeStates=nodeStates, tipStates=tipStates));
}
.mecca.fasttreesim <-
function (n, lambda, mu, rho, origin) {
edge<-matrix(data=NA, nrow=2*n-1, ncol=2);
edge[1,]<- c(-1, -2);
leaves <- c(-2)
timecreation <- array(data=0, dim=2*n);
time <- 0
maxspecies <- -2
edge.length <- array(data=0, dim=2*n-1);
specevents = array(dim=n)
specevents[1]<-origin;
r<-runif(n-1, 0,1);
if (lambda > mu) {
lamb1 <- rho * lambda
mu1 <- mu - lambda * (1 - rho)
AA<-exp((-lamb1 + mu1) * origin);
YY<-lamb1 - mu1 * AA;
XX<-(1 - AA) * r;
specevents[2:n] <- 1/(lamb1 - mu1) * log((YY - mu1 * XX)/(YY - lamb1 * XX));
} else {
specevents[2:n] <- (origin * r)/(1 + lambda * rho * origin * (1 + r));
}
specevents <- sort(specevents, decreasing = TRUE)
for (index in 2:n) {
time = time + (specevents[index - 1] - specevents[index]);
species <- sample(leaves, 1)
del <- which(leaves == species)
edge.length[which(edge[,2] == species)] <- time - timecreation[-species]
edge[2*index-2,]<-c(species, maxspecies - 1);
edge[2*index-1,]<-c(species, maxspecies - 2);
leaves <- c(leaves[-del], maxspecies - 1, maxspecies - 2)
maxspecies <- maxspecies - 2
timecreation[2*index-1]<-time;
timecreation[2*index]<-time;
}
m<-match(leaves, edge[,2]);
edge.length[m]<-specevents[1]-timecreation[-edge[m,2]];
nodes <- (length(leaves)) * 2
leaf = 1
interior = length(leaves) + 1
if (nodes != 2) {
for (j in 1:nodes) {
if (sum(match(leaves, -j, 0)) == 0) {
posvalue <- interior;
interior <- interior + 1;
}
else {
posvalue <- leaf
leaf <- leaf + 1
}
edge[which(edge == -j)] <- posvalue;
}
}
phy <- list(edge = edge)
phy$tip.label <- paste("t", sample(length(leaves)), sep = "")
phy$edge.length <- edge.length;
phy$Nnode <- length(leaves)
class(phy) <- "phylo"
return(phy)
}
.mecca.generatetipsummaries <-
function(phy, model, cladeAges, treelist, prop, hotBranches = NULL, richness=richness) {
Smean <- numeric(length(treelist))
Svar <- numeric(length(treelist))
root.age <- max(node.depth.edgelength(phy));
cladeAncStates <- .mecca.nodesim(phy, model, prop, hotBranches);
for(i in 1:length(treelist)) {
if(!is.numeric(treelist[[i]])) {
if(!model == "twoRate") dat <- .mecca.tipsim(treelist[[i]], model, prop, cladeAncStates[i], root.age);
if(model == "twoRate") {
tipNum <- which(phy$tip.label == names(richness)[i]);
if (tipNum %in% hotBranches) { Branch = "hot" } else { Branch <- "not" }
dat <- .mecca.tipsim(phy = treelist[[i]], model = model, prop = prop, cladeAncStates[i], BranchState = Branch);
}
Svar[i]<-var(dat);
Smean[i]<-mean(dat);
} else {
if(model == "twoRate") {
if (i %in% hotBranches) {
Branch = "hot"
} else {
Branch = "not"
}
dat <- .mecca.singletiptrait(model, prop, cladeAges[i], cladeAncStates[i], root.age, BranchState = Branch);
} else {
dat <- .mecca.singletiptrait(model, prop, cladeAges[i], cladeAncStates[i], root.age);
}
Smean[i] <- dat;
Svar[i] <- 0;
}
}
return(list("Smean" = Smean, "Svar" = Svar));
}
.mecca.gethotbranches <-
function(phy, tip1, tip2) {
if(is.null(tip2)) {
if(is.numeric(tip1)) {
return(tip1);
} else {
return(which(phy$tip.label==tip1));
}
} else {
mrca <- .mecca.getmrca(phy, tip1, tip2);
return(.mecca.allbranches(phy, mrca))
}
}
.mecca.getdivMLE <-
function(phy, richness) {
phy2 <- .laser.gettipdata(richness, phy);
ext <- seq(0, 0.99, 0.005);
lik<-numeric(length(ext));
div<-numeric(length(ext));
lam<-numeric(length(ext));
for(i in 1:length(ext)) {
.laser.fitNDR_1rate(phy2, eps = ext[i], rbounds = c(0.0001, .5), combined = TRUE) -> fit;
lik[i] <- fit$LH;
div[i] <- fit$r;
lam[i] <- fit$lambda;
}
names(lik) <- ext;
names(div) <- ext;
names(lam) <- ext;
return(list("lik" = max(lik), "div" = div[which(lik==max(lik))],"lamda" = lam[which(lik==max(lik))], "mu" = ext[which(lik==max(lik))] * lam[which(lik==max(lik))]
));
}
.mecca.getproposal <-
function(currentState, psi, min, max) {
prop <- currentState + ((runif(1) - 0.5) * psi);
if (prop < min) { prop <- min + (min - prop) }
if (prop > max) { prop <- max - (prop - max) }
return(prop);
}
.mecca.getmrca <-
function(phy, tip1, tip2) {
if(is.null(tip2)) {
bb<-which(phy$tip.label==tip1);
mrca<-.mecca.parentnode(phy, bb);
} else {
nn <- phy$Nnode;
nt <- length(phy$tip.label);
minLeaves <- nt;
mrca <- NULL;
for(i in 1:nn) {
leaves <- node.leaves(phy, i + nt);
if(tip1 %in% leaves & tip2 %in% leaves) {
ll <- length(leaves);
if(ll < minLeaves) { mrca <- i + nt; minLeaves <- ll }
}
}
}
return(mrca);
}
.mecca.logLP <-
function(phy, b, d) {
r <- b - d;
a <- d / b;
N <- phy$Nnode - 1;
Xi <- cbind(phy$edge, phy$edge.length);
Xi <- Xi[-which(Xi[ ,2] <= length(phy$tip.label)), ];
Xi <- cbind(Xi, numeric(length(Xi[ ,3])));
bt <- branching.times(phy);
for (i in 1: length(Xi[ ,4])) {
Xi[i, 4] <- bt[which(names(bt)==Xi[i, 1])];
}
part3 <- numeric(length(Xi[ ,4]));
for (p in 1:length(part3)) {
part3[p]<- log(1 - a * exp(-r*Xi[p, 4]));
}
logLp <- (N * log(r) - r * sum(Xi[ ,3]) - sum(part3));
return(logLp);
}
.mecca.logLT <-
function(phy, richness, b, d) {
r <- b-d;
a <- d/b;
t <- .mecca.cladeage(phy);
n <- richness[match(phy$tip.label, names(richness))];
beta <- (exp(r * t) - 1) / (exp(r * t) - a);
logLT <- sum(log(1-beta)) + sum((n-1)*log(beta));
return(logLT);
}
.mecca.nodesim <-
function(phy, model, prop, hotBranches = NULL) {
if(model == "BM") {
cladeAncStates <- .mecca.cladestates(.mecca.fastbm(phy, prop$root, prop$sigmasq, mu = 0)$nodeStates, phy);
}
if(model == "Trend") {
cladeAncStates <- .mecca.cladestates(.mecca.fastbm(phy, prop$root, prop$sigma, prop$mu)$nodeStates, phy);
}
if(model == "twoRate") {
cladeAncStates <- .mecca.cladestates(.mecca.nodestatestworate(phy, prop, hotBranches), phy);
}
return(cladeAncStates)
}
.mecca.paramsample <-
function(model, prop, Lk, calSim) {
if(model == "BM") x <- c(prop$birth, prop$death, Lk, log(prop$sigmasq),prop$root, calSim$Svar, calSim$Smean);
if(model == "Trend") x <- c(prop$birth, prop$death, Lk,log(prop$sigmasq), prop$root, prop$mu, calSim$Svar, calSim$Smean);
if(model == "twoRate") x <- c(prop$birth, prop$death, Lk, log(prop$sigmasq1),log(prop$sigmasq2), prop$root, calSim$Svar, calSim$Smean);
return(x);
}
.mecca.parentnode <-
function(phy, tip){
return(phy$edge[which(phy$edge[ ,2] == tip), 1]);
}
.mecca.priordrawbirth <-
function(min, max) {
return(runif(1, min, max));
}
.mecca.priordrawdeath <-
function(min, max ) {
return(runif(1, min, max));
}
.mecca.priordrawmean <-
function(rootA, rootB, rootPriorType = "uniform") {
if (rootPriorType == "uniform") {
return(runif(1, rootA, rootB));
}
if(rootPriorType == "normal") {
return(rnorm(1, mean = rootA, sd = rootB));
}
}
.mecca.priordrawsig <-
function(min , max, sigmaPriorType, SigmaBounds) {
if(sigmaPriorType == "uniform") return(exp(runif(1, min, max)));
if(sigmaPriorType == "normal") {
if(is.null(SigmaBounds)) {
return(exp(rnorm(1, mean = min, sd = max)))
} else {
while(1) {
s <- rnorm(1, mean = min, sd = max)
if(s > SigmaBounds[1] & s < SigmaBounds[2]) (break)
}
return(exp(s))
}
}
}
mecca <-
function(phy, richness, cladeMean, cladeVariance, model = c("BM", "Trend", "twoRate"), prior.list = list(priorSigma = c(-4.961845, 4.247066), priorMean = c(-10, 10)), start = start, Ngens = 10000, printFreq = 100, sigmaPriorType = "uniform", rootPriorType = "uniform", SigmaBounds = c(-4.961845, 4.247066),hotclade = NULL, divPropWidth = 0.1, scale = 1, divSampleFreq = 0, BoxCox = TRUE, outputName ="mecca") {
name.check(phy, richness) -> nc;
if(!nc == "OK") { stop("names in tree and data do not match") }
if(!sum(is.na(richness) == 0)) { stop("richness contains missing values") }
if(!sum(is.na(cladeMean) == 0)) { stop("cladeMeans contains missing values") }
if(!sum(is.na(cladeVariance) == 0)) { stop("cladeVariance contains missing values") }
phy$node.label <- NULL;
hotBranches <- NULL;
match(phy$tip.label, names(richness)) -> m;
richness[m] -> richness;
cladeMean[m] -> cladeMean;
cladeVariance[m] -> cladeVariance;
cladeVariance <- cladeVariance[-which(cladeVariance==0)];
if(sigmaPriorType == "uniform") SigmaBounds <- prior.list$priorSigma;
cladeAges <- .mecca.cladeage(phy);
dcrit <- start$dcrit;
obs <- start$obsTraits;
plsobs <- start$plsObserved
pls <- start$plsLoadings;
tuning <- as.data.frame(t(start$tuning));
ncomp <- ncol(pls);
if(BoxCox == TRUE) {
stdz <- start$stdz;
lambda <- start$lambda;
GM <- start$GM;
boxcox <- start$BoxCox;
}
if(model =="BM") k <- 2; if(model == "Trend"|model == "twoRate") k <- 3;
if(model=="twoRate") {
if(is.null(hotclade)) { stop("if using a two rate model you need to specify the hot clade") }
hotBranches <- .mecca.gethotbranches(phy, hotclade[1], hotclade[2]);
}
if(model == "Trend") {
if (is.null(prior.list$priorMu)) {prior.list$priorMu = c(-0.5,0.5); warning("No mu prior specified for Trend model. Using default prior of -0.5:0.5") }
}
distSim <- file(paste(outputName, "distSimFile.txt", sep = "_"), "w");
cat(colnames(tuning), paste("pls", 1:length(plsobs), sep = ""), file = distSim, sep = "\t","\n");
bmSim <- file(paste(outputName, "bmSimFile.txt", sep = "_"), "w");
cat(colnames(tuning), names(obs), file = bmSim, sep = "\t","\n");
bdSim <- file(paste(outputName, "bdSimFile.txt", sep = "_"), "w");
cat(paste("Lambda", "Mu", "lkl"), file = bdSim, sep = "\t","\n");
names(plsobs) <- c(paste("pls", 1:length(plsobs), sep = ""));
write.table(t(plsobs), paste(outputName, "distObsFile.txt", sep = "_"), row.names = F, sep = "\t", quote = F);
write.table(t(obs), paste(outputName, "ObsFile.txt", sep = "_"), row.names = F, sep = "\t", quote = F);
nAcceptBD = 0;
nAcceptSigma = 0;
nAcceptRoot = 0;
thetaB <- start$startingBirth;
thetaD <- start$startingDeath;
trait.params <- tuning[1,];
trait.widths <- tuning[2,];
Lk <- .mecca.logLP(phy, thetaB, thetaD) + .mecca.logLT(phy, richness, thetaB, thetaD);
for(ngen in 1:Ngens) {
while(1) {
thetaBprop<-.mecca.getproposal(thetaB, divPropWidth, min = 0, max = Inf);
thetaDprop<-.mecca.getproposal(thetaD, divPropWidth, min = 0, max = Inf);
if(thetaBprop > thetaDprop)
break;
}
propLk <- .mecca.logLP(phy, thetaBprop, thetaDprop) + .mecca.logLT(phy, richness, thetaBprop, thetaDprop);
if(propLk== - Inf) {
LKratio <- 0 ;
} else {
LKratio <- exp(propLk - Lk);
}
if(LKratio >= 1 || runif(1) < LKratio) {
thetaB <- thetaBprop; thetaD <- thetaDprop; Lk <- propLk;
nAcceptBD <- nAcceptBD + 1;
}
cat(thetaB, thetaD, Lk, file = bdSim, sep = "\t","\n")
prop.params <- .mecca.proposal(model, trait.params, trait.widths, prior.list, SigmaBounds, scale, ngen);
sim.props <- .mecca.simparamlist(thetaB, thetaD, prop.params);
while(1) {
if(ngen == 1 || divSampleFreq == 0 || ngen %% divSampleFreq == 0) {
Sim <- sim.mecca(phy, richness, cladeAges, model, sim.props, makeNewTipTrees = TRUE, mytiptrees = NULL, hotBranches = hotBranches);
tipTrees <- Sim$trees;
} else {
Sim <- .mecca.generatetipsummaries(phy, model, cladeAges, tipTrees, prop = sim.props, hotBranches = hotBranches, richness=richness);
}
if(sum(Sim$Svar==0)>0) Sim$Svar <- Sim$Svar[-which(Sim$Svar==0)];
sims <- c(Sim$Svar, Sim$Smean);
names(sims) <- names(obs)
if(BoxCox == TRUE) {
bxsims <- .mecca.boxcox(as.numeric(sims), stdz, lambda, GM, boxcox)
}
if(sum(is.na(bxsims))==0) break;
}
plsSim <- .mecca.extractpls(as.numeric(bxsims), pls, ncomp);
dSim <- abs(dist(rbind(plsobs, plsSim))[1]);
if(dSim <= dcrit) {
if(ngen %% 2 == 1) {
acc <- .mecca.acceptance(trait.params, prop.params, sigmaPriorType, prior.list$priorSigma);
} else acc <- "accept";
} else if(dSim > dcrit) {
acc <- "reject";
}
if(acc == "accept") {
trait.params <- prop.params;
if(ngen %%2 == 1) nAcceptSigma = nAcceptSigma + 1;
if(ngen %% 2 == 0) nAcceptRoot = nAcceptRoot + 1;
cat(as.numeric(trait.params), plsSim, file = distSim, sep = "\t", "\n");
cat(as.numeric(trait.params), sims, file = bmSim, sep = "\t", "\n");
}
if(acc == "reject") {
sim.curr <- .mecca.simparamlist(thetaB, thetaD, trait.params);
while(1) {
Sim <- .mecca.generatetipsummaries(phy,model, cladeAges, tipTrees, sim.curr, hotBranches = hotBranches, richness=richness)
if(sum(Sim$Svar==0)>0) Sim$Svar <- Sim$Svar[-which(Sim$Svar==0)];
sims <- c(Sim$Svar, Sim$Smean);
if(BoxCox == TRUE) {
bxsims <- .mecca.boxcox(sims, stdz, lambda, GM, boxcox)
}
if(sum(is.na(bxsims))==0) break;
}
plsSim <- .mecca.extractpls(bxsims, pls, ncomp);
cat(as.numeric(trait.params), plsSim, file = distSim, sep = "\t", "\n");
cat(as.numeric(trait.params), sims, file = bmSim, sep = "\t", "\n");
}
if(ngen %% printFreq == 0) {
cat("Generation", ngen, "/", round(nAcceptBD/ngen, 2), round(nAcceptSigma/(ngen/2), 2), round(nAcceptRoot/(ngen/2), 2), "\n\n");
}
}
close(bmSim); close(bdSim); close(distSim);
}
.mecca.simparamlist <-
function(birth, death, trait) {
rates <- grep("sigma", colnames(trait));
trait[,rates] <- exp(trait[,rates]);
trait <- as.list(trait);
trait$birth <- birth;
trait$death <- death;
return(trait);
}
.mecca.singletiptrait <-
function(model, prop, clade.age, clade.anc.state, root.age, BranchState="not") {
if(model == "BM") {
dat <- rnorm(1, mean = clade.anc.state, sd = sqrt(prop$sigmasq * clade.age));
}
if(model == "Trend") {
dat <- clade.anc.state + rnorm(1, mean = clade.age*prop$mu, sd =sqrt(prop$sigma * clade.age))
}
if(model == "twoRate") {
if(BranchState == "not") {
dat <- rnorm(1, mean = clade.anc.state, sd = sqrt(prop$sigmasq1 * clade.age));
} else if(BranchState == "hot") {
dat <- rnorm(1, mean = clade.anc.state, sd = sqrt(prop$sigmasq2 * clade.age));
}
}
return(dat);
} |
mHMM <- function(s_data, gen, xx = NULL, start_val, mcmc, return_path = FALSE, print_iter = FALSE,
gamma_hyp_prior = NULL, emiss_hyp_prior = NULL,
gamma_sampler = NULL, emiss_sampler = NULL){
n_dep <- gen$n_dep
dep_labels <- colnames(s_data[,2:(n_dep+1)])
id <- unique(s_data[,1])
n_subj <- length(id)
subj_data <- rep(list(NULL), n_subj)
if(sum(sapply(s_data, is.factor)) > 0 ){
stop("Your data contains factorial variables, which cannot be used as input in the function mHMM. All variables have to be numerical.")
}
for(s in 1:n_subj){
subj_data[[s]]$y <- as.matrix(s_data[s_data[,1] == id[s],][,-1], ncol = n_dep)
}
ypooled <- n <- NULL
n_vary <- numeric(n_subj)
m <- gen$m
q_emiss <- gen$q_emiss
emiss_int_mle <- rep(list(NULL), n_dep)
emiss_mhess <- rep(list(NULL), n_dep)
for(q in 1:n_dep){
emiss_int_mle[[q]] <- matrix(, m, (q_emiss[q] - 1))
emiss_mhess[[q]] <- matrix(, (q_emiss[q] - 1) * m, (q_emiss[q] - 1))
}
for(s in 1:n_subj){
ypooled <- rbind(ypooled, subj_data[[s]]$y)
n <- dim(subj_data[[s]]$y)[1]
n_vary[s] <- n
subj_data[[s]] <- c(subj_data[[s]], n = n, list(gamma_converge = numeric(m), gamma_int_mle = matrix(, m, (m - 1)),
gamma_mhess = matrix(, (m - 1) * m, (m - 1)), emiss_converge =
rep(list(numeric(m)), n_dep), emiss_int_mle = emiss_int_mle, emiss_mhess = emiss_mhess))
}
n_total <- dim(ypooled)[1]
n_dep1 <- 1 + n_dep
nx <- numeric(n_dep1)
if (is.null(xx)){
xx <- rep(list(matrix(1, ncol = 1, nrow = n_subj)), n_dep1)
nx[] <- 1
} else {
if(!is.list(xx) | length(xx) != n_dep1){
stop("If xx is specified, xx should be a list, with the number of elements equal to the number of dependent variables + 1")
}
for(i in 1:n_dep1){
if (is.null(xx[[i]])){
xx[[i]] <- matrix(1, ncol = 1, nrow = n_subj)
nx[i] <- 1
} else {
nx[i] <- ncol(xx[[i]])
if (sum(xx[[i]][,1] != 1)){
stop("If xx is specified, the first column in each element of xx has to represent the intercept. That is, a column that only consists of the value 1")
}
if(nx[i] > 1){
for(j in 2:nx[i]){
if(is.factor(xx[[i]][,j])){
stop("Factors currently cannot be used as covariates, see help file for alternatives")
}
if((length(unique(xx[[i]][,j])) == 2) & (sum(xx[[i]][,j] != 0 & xx[[i]][,j] !=1) > 0)){
stop("Dichotomous covariates in xx need to be coded as 0 / 1 variables. That is, only conisting of the values 0 and 1")
}
if(length(unique(xx[[i]][,j])) > 2){
xx[[i]][,j] <- xx[[i]][,j] - mean(xx[[i]][,j])
}
}
}
}
}
}
J <- mcmc$J
burn_in <- mcmc$burn_in
if(is.null(gamma_sampler)) {
gamma_int_mle0 <- rep(0, m - 1)
gamma_scalar <- 2.93 / sqrt(m - 1)
gamma_w <- .1
} else {
gamma_int_mle0 <- gamma_sampler$gamma_int_mle0
gamma_scalar <- gamma_sampler$gamma_scalar
gamma_w <- gamma_sampler$gamma_w
}
if(is.null(emiss_sampler)){
emiss_int_mle0 <- rep(list(NULL), n_dep)
emiss_scalar <- rep(list(NULL), n_dep)
for(q in 1:n_dep){
emiss_int_mle0[[q]] <- rep(0, q_emiss[q] - 1)
emiss_scalar[[q]] <- 2.93 / sqrt(q_emiss[q] - 1)
}
emiss_w <- .1
} else {
emiss_int_mle0 <- emiss_sampler$emiss_int_mle0
emiss_scalar <- emiss_sampler$emiss_scalar
emiss_w <- emiss_sampler$emiss_w
}
if(is.null(gamma_hyp_prior)){
gamma_mu0 <- rep(list(matrix(0,nrow = nx[1], ncol = m - 1)), m)
gamma_K0 <- diag(1, nx[1])
gamma_nu <- 3 + m - 1
gamma_V <- gamma_nu * diag(m - 1)
} else {
gamma_mu0 <- gamma_hyp_prior$gamma_mu0
gamma_K0 <- gamma_hyp_prior$gamma_K0
gamma_nu <- gamma_hyp_prior$gamma_nu
gamma_V <- gamma_hyp_prior$gamma_V
}
emiss_mu0 <- rep(list(vector("list", m)), n_dep)
emiss_nu <- rep(list(NULL), n_dep)
emiss_V <- rep(list(NULL), n_dep)
emiss_K0 <- rep(list(NULL), n_dep)
if(is.null(emiss_hyp_prior)){
for(q in 1:n_dep){
for(i in 1:m){
emiss_mu0[[q]][[i]] <- matrix(0, ncol = q_emiss[q] - 1, nrow = nx[1 + q])
}
emiss_nu[[q]] <- 3 + q_emiss[q] - 1
emiss_V[[q]] <- emiss_nu[[q]] * diag(q_emiss[q] - 1)
emiss_K0[[q]] <- diag(1, nx[1 + q])
}
} else {
for(q in 1:n_dep){
emiss_mu0[[q]] <- emiss_hyp_prior[[q]]$emiss_mu0
emiss_nu[[q]] <- emiss_hyp_prior[[q]]$emiss_nu
emiss_V[[q]] <- emiss_hyp_prior[[q]]$emiss_V
emiss_K0[[q]] <- diag(emiss_hyp_prior$emiss_K0, nx[1 + q])
}
}
c <- llk <- numeric(1)
sample_path <- lapply(n_vary, dif_matrix, cols = J)
trans <- rep(list(vector("list", m)), n_subj)
gamma_mle_pooled <-gamma_int_mle_pooled <- gamma_mhess_pooled <- gamma_pooled_ll <- vector("list", m)
gamma_c_int <- rep(list(matrix(, n_subj, (m-1))), m)
gamma_mu_int_bar <- gamma_V_int <- vector("list", m)
gamma_mu_prob_bar <- rep(list(numeric(m)), m)
gamma_naccept <- matrix(0, n_subj, m)
cond_y <- lapply(rep(n_dep, n_subj), nested_list, m = m)
emiss_mle_pooled <- emiss_int_mle_pooled <- emiss_mhess_pooled <- emiss_pooled_ll <- rep(list(vector("list", n_dep)), m)
emiss_c_int <- rep(list(lapply(q_emiss - 1, dif_matrix, rows = n_subj)), m)
emiss_mu_int_bar <- emiss_V_int <- rep(list(vector("list", n_dep)), m)
emiss_mu_prob_bar <- rep(list(lapply(q_emiss, dif_vector)), m)
emiss_naccept <- rep(list(matrix(0, n_subj, m)), n_dep)
if(length(start_val) != n_dep + 1){
stop("The number of elements in the list start_val should be equal to 1 + the number of dependent variables,
and should not contain nested lists (i.e., lists within lists)")
}
PD <- matrix(, nrow = J, ncol = sum(m * q_emiss) + m * m + 1)
PD_emiss_names <- paste("q", 1, "_emiss", rep(1:q_emiss[1], m), "_S", rep(1:m, each = q_emiss[1]), sep = "")
if(n_dep > 1){
for(q in 2:n_dep){
PD_emiss_names <- c(PD_emiss_names, paste("q", q, "_emiss", rep(1:q_emiss[q], m), "_S", rep(1:m, each = q_emiss[q]), sep = ""))
}
}
colnames(PD) <- c(PD_emiss_names, paste("S", rep(1:m, each = m), "toS", rep(1:m, m), sep = ""), "LL")
PD[1, ((sum(m * q_emiss) + 1)) :((sum(m * q_emiss) + m * m))] <- unlist(sapply(start_val, t))[1:(m*m)]
PD[1, 1:((sum(m * q_emiss)))] <- unlist(sapply(start_val, t))[(m*m + 1): (m*m + sum(m * q_emiss))]
PD_subj <- rep(list(PD), n_subj)
gamma_prob_bar <- matrix(, nrow = J, ncol = (m * m))
colnames(gamma_prob_bar) <- paste("S", rep(1:m, each = m), "toS", rep(1:m, m), sep = "")
gamma_prob_bar[1,] <- PD[1,(sum(m*q_emiss) + 1):(sum(m * q_emiss) + m * m)]
emiss_prob_bar <- lapply(q_emiss * m, dif_matrix, rows = J)
names(emiss_prob_bar) <- dep_labels
for(q in 1:n_dep){
colnames(emiss_prob_bar[[q]]) <- paste("Emiss", rep(1:q_emiss[q], m), "_S", rep(1:m, each = q_emiss[q]), sep = "")
start <- c(0, q_emiss * m)
emiss_prob_bar[[q]][1,] <- PD[1,(sum(start[1:q]) + 1):(sum(start[1:q]) + (m * q_emiss[q]))]
}
gamma_int_bar <- matrix(, nrow = J, ncol = ((m-1) * m))
colnames(gamma_int_bar) <- paste("int_S", rep(1:m, each = m-1), "toS", rep(2:m, m), sep = "")
gamma_int_bar[1,] <- as.vector(prob_to_int(matrix(gamma_prob_bar[1,], byrow = TRUE, ncol = m, nrow = m)))
if(nx[1] > 1){
gamma_cov_bar <- matrix(, nrow = J, ncol = ((m-1) * m) * (nx[1] - 1))
colnames(gamma_cov_bar) <- paste( paste("cov", 1 : (nx[1] - 1), "_", sep = ""), "S", rep(1:m, each = (m-1) * (nx[1] - 1)), "toS", rep(2:m, m * (nx[1] - 1)), sep = "")
gamma_cov_bar[1,] <- 0
} else{
gamma_cov_bar <- "No covariates where used to predict the transition probability matrix"
}
emiss_int_bar <- lapply((q_emiss-1) * m, dif_matrix, rows = J)
names(emiss_int_bar) <- dep_labels
for(q in 1:n_dep){
colnames(emiss_int_bar[[q]]) <- paste("int_Emiss", rep(2:q_emiss[q], m), "_S", rep(1:m, each = q_emiss[q] - 1), sep = "")
emiss_int_bar[[q]][1,] <- as.vector(prob_to_int(matrix(emiss_prob_bar[[q]][1,], byrow = TRUE, ncol = q_emiss[q], nrow = m)))
}
if(sum(nx[-1]) > n_dep){
emiss_cov_bar <- lapply((q_emiss-1) * m * (nx[-1] - 1 ), dif_matrix, rows = J)
names(emiss_cov_bar) <- dep_labels
for(q in 1:n_dep){
if(nx[1 + q] > 1){
colnames(emiss_cov_bar[[q]]) <- paste( paste("cov", 1 : (nx[1 + q] - 1), "_", sep = ""), "emiss", rep(2:q_emiss[q], m * (nx[1 + q] - 1)), "_S", rep(1:m, each = (q_emiss[q] - 1) * (nx[1 + q] - 1)), sep = "")
emiss_cov_bar[[q]][1,] <- 0
} else {
emiss_cov_bar[[q]] <- "No covariates where used to predict the emission probabilities for this outcome"
}
}
} else{
emiss_cov_bar <- "No covariates where used to predict the emission probabilities"
}
gamma_int_subj <- rep(list(gamma_int_bar), n_subj)
emiss_int_subj <- rep(list(emiss_int_bar), n_subj)
emiss_sep <- vector("list", n_dep)
for(q in 1:n_dep){
start <- c(0, q_emiss * m)
emiss_sep[[q]] <- matrix(PD[1,(sum(start[1:q]) + 1):(sum(start[1:q]) + (m * q_emiss[q]))], byrow = TRUE, ncol = q_emiss[q], nrow = m)
}
emiss <- rep(list(emiss_sep), n_subj)
gamma <- rep(list(matrix(PD[1,(sum(m*q_emiss) + 1):(sum(m * q_emiss) + m * m)], byrow = TRUE, ncol = m)), n_subj)
delta <- rep(list(solve(t(diag(m) - gamma[[1]] + 1), rep(1, m))), n_subj)
itime <- proc.time()[3]
for (iter in 2 : J){
for(s in 1:n_subj){
forward <- cat_Mult_HMM_fw(x = subj_data[[s]]$y, m = m, emiss = emiss[[s]], gamma = gamma[[s]], n_dep = n_dep, delta=NULL)
alpha <- forward$forward_p
c <- max(forward$la[, subj_data[[s]]$n])
llk <- c + log(sum(exp(forward$la[, subj_data[[s]]$n] - c)))
PD_subj[[s]][iter, sum(m * q_emiss) + m * m + 1] <- llk
trans[[s]] <- vector("list", m)
sample_path[[s]][n_vary[[s]], iter] <- sample(1:m, 1, prob = c(alpha[, n_vary[[s]]]))
for(t in (subj_data[[s]]$n - 1):1){
sample_path[[s]][t,iter] <- sample(1:m, 1, prob = (alpha[, t] * gamma[[s]][,sample_path[[s]][t + 1, iter]]))
trans[[s]][[sample_path[[s]][t,iter]]] <- c(trans[[s]][[sample_path[[s]][t, iter]]], sample_path[[s]][t + 1, iter])
}
for (i in 1:m){
trans[[s]][[i]] <- c(trans[[s]][[i]], 1:m)
trans[[s]][[i]] <- rev(trans[[s]][[i]])
for(q in 1:n_dep){
cond_y[[s]][[i]][[q]] <- c(subj_data[[s]]$y[sample_path[[s]][, iter] == i, q], 1:q_emiss[q])
}
}
}
for(i in 1:m){
trans_pooled <- factor(c(unlist(sapply(trans, "[[", i)), c(1:m)))
gamma_mle_pooled[[i]] <- optim(gamma_int_mle0, llmnl_int, Obs = trans_pooled, n_cat = m, method = "BFGS", hessian = TRUE, control = list(fnscale = -1))
gamma_int_mle_pooled[[i]] <- gamma_mle_pooled[[i]]$par
gamma_pooled_ll[[i]] <- gamma_mle_pooled[[i]]$value
for(q in 1:n_dep){
cond_y_pooled <- numeric()
for(s in 1:n_subj){
cond_y_pooled <- c(cond_y_pooled, cond_y[[s]][[i]][[q]])
}
emiss_mle_pooled[[i]][[q]] <- optim(emiss_int_mle0[[q]], llmnl_int, Obs = c(cond_y_pooled, c(1:q_emiss[q])), n_cat = q_emiss[q],
method = "BFGS", hessian = TRUE, control = list(fnscale = -1))
emiss_int_mle_pooled[[i]][[q]] <- emiss_mle_pooled[[i]][[q]]$par
emiss_pooled_ll[[i]][[q]] <- emiss_mle_pooled[[i]][[q]]$value
}
for (s in 1:n_subj){
wgt <- subj_data[[s]]$n / n_total
gamma_out <- optim(gamma_int_mle_pooled[[i]], llmnl_int_frac, Obs = c(trans[[s]][[i]], c(1:m)), n_cat = m,
pooled_likel = gamma_pooled_ll[[i]], w = gamma_w, wgt = wgt, method="BFGS", hessian = TRUE, control = list(fnscale = -1))
if(gamma_out$convergence == 0){
subj_data[[s]]$gamma_converge[i] <- 1
subj_data[[s]]$gamma_mhess[(1 + (i - 1) * (m - 1)):((m - 1) + (i - 1) * (m - 1)), ] <- mnlHess_int(int = gamma_out$par, Obs = c(trans[[s]][[i]], c(1:m)), n_cat = m)
subj_data[[s]]$gamma_int_mle[i,] <- gamma_out$par
} else {
subj_data[[s]]$gamma_converge[i] <- 0
subj_data[[s]]$gamma_mhess[(1 + (i - 1) * (m - 1)):((m - 1) + (i - 1) * (m - 1)),] <- diag(m-1)
subj_data[[s]]$gamma_int_mle[i,] <- rep(0, m - 1)
}
if (iter == 2){
gamma_c_int[[i]][s,] <- gamma_out$par
}
for(q in 1:n_dep){
emiss_out <- optim(emiss_int_mle_pooled[[i]][[q]], llmnl_int_frac, Obs = c(cond_y[[s]][[i]][[q]], c(1:q_emiss[q])),
n_cat = q_emiss[q], pooled_likel = emiss_pooled_ll[[i]][[q]], w = emiss_w, wgt = wgt, method = "BFGS", hessian = TRUE, control = list(fnscale = -1))
if(emiss_out$convergence == 0){
subj_data[[s]]$emiss_converge[[q]][i] <- 1
subj_data[[s]]$emiss_mhess[[q]][(1 + (i - 1) * (q_emiss[q] - 1)):((q_emiss[q] - 1) + (i - 1) * (q_emiss[q] - 1)), ] <- mnlHess_int(int = emiss_out$par, Obs = c(cond_y[[s]][[i]][[q]], c(1:q_emiss[q])), n_cat = q_emiss[q])
subj_data[[s]]$emiss_int_mle[[q]][i,] <- emiss_out$par
} else {
subj_data[[s]]$emiss_converge[[q]][i] <- 0
subj_data[[s]]$emiss_mhess[[q]][(1 + (i - 1) * (q_emiss[q] - 1)):((q_emiss[q] - 1) + (i - 1) * (q_emiss[q] - 1)), ] <- diag(q_emiss[q] - 1)
subj_data[[s]]$emiss_int_mle[[q]][i,] <- rep(0, q_emiss[q] - 1)
}
if (iter == 2){
emiss_c_int[[i]][[q]][s,] <- emiss_out$par
}
}
}
gamma_mu0_n <- solve(t(xx[[1]]) %*% xx[[1]] + gamma_K0) %*% (t(xx[[1]]) %*% gamma_c_int[[i]] + gamma_K0 %*% gamma_mu0[[i]])
gamma_V_n <- gamma_V + t(gamma_c_int[[i]] - xx[[1]] %*% gamma_mu0_n) %*% (gamma_c_int[[i]] - xx[[1]] %*% gamma_mu0_n) + t(gamma_mu0_n - gamma_mu0[[i]]) %*% gamma_K0 %*% (gamma_mu0_n - gamma_mu0[[i]])
gamma_V_int[[i]] <- solve(rwish(S = solve(gamma_V_n), v = gamma_nu + n_subj))
gamma_mu_int_bar[[i]] <- gamma_mu0_n + solve(chol(t(xx[[1]]) %*% xx[[1]] + gamma_K0)) %*% matrix(rnorm((m - 1) * nx[1]), nrow = nx[1]) %*% t(solve(chol(solve(gamma_V_int[[i]]))))
gamma_exp_int <- matrix(exp(c(0, gamma_mu_int_bar[[i]][1,] )), nrow = 1)
gamma_mu_prob_bar[[i]] <- gamma_exp_int / as.vector(gamma_exp_int %*% c(rep(1,(m))))
for(q in 1:n_dep){
emiss_mu0_n <- solve(t(xx[[1 + q]]) %*% xx[[1 + q]] + emiss_K0[[q]]) %*% (t(xx[[1 + q]]) %*% emiss_c_int[[i]][[q]] + emiss_K0[[q]] %*% emiss_mu0[[q]][[i]])
emiss_V_n <- emiss_V[[q]] + t(emiss_c_int[[i]][[q]] - xx[[1 + q]] %*% emiss_mu0_n) %*% (emiss_c_int[[i]][[q]] - xx[[1 + q]] %*% emiss_mu0_n) + t(emiss_mu0_n - emiss_mu0[[q]][[i]]) %*% emiss_K0[[q]] %*% (emiss_mu0_n - emiss_mu0[[q]][[i]])
emiss_V_int[[i]][[q]] <- solve(rwish(S = solve(emiss_V_n), v = emiss_nu[[q]] + n_subj))
emiss_mu_int_bar[[i]][[q]] <- emiss_mu0_n + solve(chol(t(xx[[1 + q]]) %*% xx[[1 + q]] + emiss_K0[[q]])) %*% matrix(rnorm((q_emiss[q] - 1) * nx[1 + q]), nrow = nx[1 + q]) %*% t(solve(chol(solve(emiss_V_int[[i]][[q]]))))
emiss_exp_int <- matrix(exp(c(0, emiss_mu_int_bar[[i]][[q]][1, ])), nrow = 1)
emiss_mu_prob_bar[[i]][[q]] <- emiss_exp_int / as.vector(emiss_exp_int %*% c(rep(1, (q_emiss[q]))))
}
for (s in 1:n_subj){
gamma_candcov_comb <- chol2inv(chol(subj_data[[s]]$gamma_mhess[(1 + (i - 1) * (m - 1)):((m - 1) + (i - 1) * (m - 1)), ] + chol2inv(chol(gamma_V_int[[i]]))))
gamma_RWout <- mnl_RW_once(int1 = gamma_c_int[[i]][s,], Obs = trans[[s]][[i]], n_cat = m, mu_int_bar1 = c(t(gamma_mu_int_bar[[i]]) %*% xx[[1]][s,]), V_int1 = gamma_V_int[[i]], scalar = gamma_scalar, candcov1 = gamma_candcov_comb)
gamma[[s]][i,] <- PD_subj[[s]][iter, c((sum(m * q_emiss) + 1 + (i - 1) * m):(sum(m * q_emiss) + (i - 1) * m + m))] <- gamma_RWout$prob
gamma_naccept[s, i] <- gamma_naccept[s, i] + gamma_RWout$accept
gamma_c_int[[i]][s,] <- gamma_RWout$draw_int
gamma_int_subj[[s]][iter, (1 + (i - 1) * (m - 1)):((m - 1) + (i - 1) * (m - 1))] <- gamma_c_int[[i]][s,]
start <- c(0, q_emiss * m)
for(q in 1:n_dep){
emiss_candcov_comb <- chol2inv(chol(subj_data[[s]]$emiss_mhess[[q]][(1 + (i - 1) * (q_emiss[q] - 1)):((q_emiss[q] - 1) + (i - 1) * (q_emiss[q] - 1)), ] + chol2inv(chol(emiss_V_int[[i]][[q]]))))
emiss_RWout <- mnl_RW_once(int1 = emiss_c_int[[i]][[q]][s,], Obs = cond_y[[s]][[i]][[q]], n_cat = q_emiss[q], mu_int_bar1 = c(t(emiss_mu_int_bar[[i]][[q]]) %*% xx[[1 + q]][s,]), V_int1 = emiss_V_int[[i]][[q]], scalar = emiss_scalar[[q]], candcov1 = emiss_candcov_comb)
emiss[[s]][[q]][i,] <- PD_subj[[s]][iter, (sum(start[1:q]) + 1 + (i - 1) * q_emiss[q]):(sum(start[1:q]) + (i - 1) * q_emiss[q] + q_emiss[q])] <- emiss_RWout$prob
emiss_naccept[[q]][s, i] <- emiss_naccept[[q]][s, i] + emiss_RWout$accept
emiss_c_int[[i]][[q]][s,] <- emiss_RWout$draw_int
emiss_int_subj[[s]][[q]][iter, (1 + (i - 1) * (q_emiss[q] - 1)) : ((q_emiss[q] - 1) + (i - 1) * (q_emiss[q] - 1))] <- emiss_c_int[[i]][[q]][s,]
}
if(i == m){
delta[[s]] <- solve(t(diag(m) - gamma[[s]] + 1), rep(1, m))
}
}
}
gamma_int_bar[iter, ] <- unlist(lapply(gamma_mu_int_bar, "[",1,))
if(nx[1] > 1){
gamma_cov_bar[iter, ] <- unlist(lapply(gamma_mu_int_bar, "[",-1,))
}
gamma_prob_bar[iter,] <- unlist(gamma_mu_prob_bar)
for(q in 1:n_dep){
emiss_int_bar[[q]][iter, ] <- as.vector(unlist(lapply(
lapply(emiss_mu_int_bar, "[[", q), "[",1,)
))
if(nx[1+q] > 1){
emiss_cov_bar[[q]][iter, ] <- as.vector(unlist(lapply(
lapply(emiss_mu_int_bar, "[[", q), "[",-1,)
))
}
emiss_prob_bar[[q]][iter,] <- as.vector(unlist(sapply(emiss_mu_prob_bar, "[[", q)))
}
if(is.whole(iter/10) & print_iter == TRUE){
if(iter == 10){
cat("Iteration:", "\n")
}
cat(c(iter), "\n")
}
}
ctime = proc.time()[3]
message(paste("Total time elapsed (hh:mm:ss):", hms(ctime-itime)))
if(return_path == TRUE){
out <- list(input = list(m = m, n_dep = n_dep, q_emiss = q_emiss, J = J,
burn_in = burn_in, n_subj = n_subj, n_vary = n_vary, dep_labels = dep_labels),
PD_subj = PD_subj, gamma_int_subj = gamma_int_subj, emiss_int_subj = emiss_int_subj,
gamma_int_bar = gamma_int_bar, gamma_cov_bar = gamma_cov_bar, emiss_int_bar = emiss_int_bar,
emiss_cov_bar = emiss_cov_bar, gamma_prob_bar = gamma_prob_bar,
emiss_prob_bar = emiss_prob_bar, gamma_naccept = gamma_naccept, emiss_naccept = emiss_naccept,
sample_path = sample_path)
} else {
out <- list(input = list(m = m, n_dep = n_dep, q_emiss = q_emiss, J = J,
burn_in = burn_in, n_subj = n_subj, n_vary = n_vary, dep_labels = dep_labels),
PD_subj = PD_subj, gamma_int_subj = gamma_int_subj, emiss_int_subj = emiss_int_subj,
gamma_int_bar = gamma_int_bar, gamma_cov_bar = gamma_cov_bar, emiss_int_bar = emiss_int_bar,
emiss_cov_bar = emiss_cov_bar, gamma_prob_bar = gamma_prob_bar,
emiss_prob_bar = emiss_prob_bar, gamma_naccept = gamma_naccept, emiss_naccept = emiss_naccept)
}
class(out) <- append(class(out), "mHMM")
return(out)
} |
shapley_mfoc <-
function(n=NA,a=NA,d=NA,K=NA){
if (is.na(a)==T|sum(is.na(d)==T)==length(d)|sum(is.na(K)==T)==length(K)){
cat("Values for a, d and K are necessary. Please, check them.", sep="\n")
} else {
cat("Shapley-Value", sep="\n")
dk<-order(d/K)
d<-d[dk];K<-K[dk]
cind<-as.vector(mfoc(n,a,d,K,cooperation=0))
shapley<-c();shapley[1]<-cind[1]/n
for (i in 2:n){
aux<-0
for (j in 2:i){aux<-aux+(cind[j]-cind[j-1])/(n-j+1)}
shapley[i]<-shapley[1]+aux
}
return(shapley)
}
} |
tidy_beta <- function(.n = 50, .shape1 = 1, .shape2 = 1, .ncp = 0, .num_sims = 1){
n <- as.integer(.n)
num_sims <- as.integer(.num_sims)
shape1 <- as.numeric(.shape1)
shape2 <- as.numeric(.shape2)
ncp <- as.numeric(.ncp)
if(!is.integer(n) | n < 0){
rlang::abort(
"The parameters '.n' must be of class integer. Please pass a whole
number like 50 or 100. It must be greater than 0."
)
}
if(!is.integer(num_sims) | num_sims < 0){
rlang::abort(
"The parameter `.num_sims' must be of class integer. Please pass a
whole number like 50 or 100. It must be greater than 0."
)
}
if(!is.numeric(shape1) | !is.numeric(shape2) | !is.numeric(ncp) |
shape1 < 0 | shape2 < 0 | ncp < 0){
rlang::abort(
"The parameters of '.shape1', '.shape2', and 'ncp' must be of class numeric.
Please pass a numer like 1 or 1.1 etc. and must be greater than 0."
)
}
x <- seq(1, num_sims, 1)
ps <- seq(-n, n-1, 2)
qs <- seq(0, 1, (1/(n-1)))
df <- dplyr::tibble(sim_number = as.factor(x)) %>%
dplyr::group_by(sim_number) %>%
dplyr::mutate(x = list(1:n)) %>%
dplyr::mutate(y = list(stats::rbeta(n = n, shape1 = shape1, shape2 = shape2, ncp = ncp))) %>%
dplyr::mutate(d = list(density(unlist(y), n = n)[c("x","y")] %>%
purrr::set_names("dx","dy") %>%
dplyr::as_tibble())) %>%
dplyr::mutate(p = list(stats::pbeta(ps, shape1 = shape1, shape2 = shape2, ncp = ncp))) %>%
dplyr::mutate(q = list(stats::qbeta(qs, shape1 = shape1, shape2 = shape2, ncp = ncp))) %>%
tidyr::unnest(cols = c(x, y, d, p, q)) %>%
dplyr::ungroup()
attr(df, ".shape1") <- .shape1
attr(df, ".shape2") <- .shape2
attr(df, ".ncp") <- .ncp
attr(df, ".n") <- .n
attr(df, ".num_sims") <- .num_sims
attr(df, "tibble_type") <- "tidy_beta"
attr(df, "ps") <- ps
attr(df, "qs") <- qs
return(df)
} |
"plot.optMoreParMode" <-
function(
x,
main=NULL,
which=1,
...
){
if(is.null(main)) main <- deparse(substitute(x))
if(which>length(x$best)){
warning("The selected (",which,") best solution does not exist!\nOnly ", length(x$best)," best solution(s) exist(s).\nThe first best solution will be ploted.\n")
which<-1
}
plot.mat(x$M,clu=clu(x,which=which),IM=IM(x,which=which),main=main,...)
}
plot.opt.more.par.mode<-plot.optMoreParMode |
data("WageData")
context("wbm defaults")
wages <- WageData
wages <- wages[8:210,]
wages$wts <- runif(nrow(wages), 0.3, 3)
wages <- panel_data(wages, id = id, wave = t)
wb <- wbm(wks ~ union + lwage | blk, data = wages)
test_that("wbm defaults work", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works (defaults)", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("wbm with lags")
wb <- wbm(wks ~ lag(union) + lag(lwage) | blk, data = wages)
test_that("wbm with lags works", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works (with lags)", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("wbm multiple lags")
wb <- wbm(wks ~ union + lag(union) + lag(lwage) | blk,
data = wages)
test_that("wbm with multiple lags works", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works (with multiple lags)", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("wbm non-standard lags")
wb <- wbm(wks ~ union + lag(union, 2) + lag(lwage) | blk,
data = wages)
test_that("wbm with non-standard lags works", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works (with non-standard lags)", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("wbm with contextual model")
wb <- wbm(wks ~ union + lag(lwage) | blk, data = wages,
model = "contextual")
test_that("wbm with contextual model works", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works (with contextual model)", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("wbm with within model")
test_that("wbm with within model works", {
expect_warning(wb <- wbm(wks ~ union + lag(lwage) | blk, data = wages,
model = "within"))
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works (with within model)", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("wbm with stability model")
wb <- wbm(wks ~ union + lag(lwage) | blk, data = wages, model = "stability")
test_that("wbm with stability model works", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works (with stability model)", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("wbm with between-model")
wb <- wbm(wks ~ union + lag(lwage) | blk, data = wages,
model = "between")
test_that("wbm with between model works", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works (with between model)", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("wbm as poisson glm")
wb <- suppressWarnings(wbm(wks ~ union + lag(lwage) | fem, data = wages,
family = poisson, nAGQ = 0L))
test_that("wbm with poisson family works", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works (as poisson glm)", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("wbm as negbinomial glm")
library(lme4)
wb <- suppressWarnings(wbm(wks ~ union + lag(lwage) | blk, data = wages,
family = negbinomial, nAGQ = 0L))
test_that("wbm with negbinomial family works", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works (as negbinomial glm)", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("wbm with use.wave")
wb <- wbm(wks ~ union + lag(lwage) | blk, data = wages,
use.wave = TRUE)
test_that("wbm with use.wave works", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works (with use.wave)", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("wbm pseudo-R2")
wb <- wbm(wks ~ union + lag(lwage) | blk, data = wages, pR2 = TRUE)
test_that("wbm works", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("wbm p-values on/off")
wb <- wbm(wks ~ union + lag(lwage) | blk, data = wages, pvals = TRUE)
wb2 <- wbm(wks ~ union + lag(lwage) | blk, data = wages, pvals = FALSE)
test_that("wbm works", {
expect_s4_class(wb, "wbm")
expect_s4_class(wb2, "wbm")
})
test_that("wbm summary works", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
expect_s3_class(swb2 <- summary(wb2), "summary.wbm")
expect_output(print(swb2))
})
context("wbm with weights")
wb <- wbm(wks ~ union + lag(lwage) | blk, data = wages, weights = wts)
test_that("wbm works", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("Missing data")
wagesm <- wages
missings <- sample(unique(wagesm$id),5)
inds <- which(wagesm$id %in% missings & wagesm$t == 7)
wagesm <- wagesm[!(1:length(wagesm$id) %in% inds),]
wb <- wbm(wks ~ lag(union) + lag(lwage) | blk, data = wagesm)
test_that("wbm with defaults works", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("Custom random effects")
wb <- wbm(wks ~ union + lag(lwage) | blk | (union | id), data = wages)
test_that("wbm works", {
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
test_that("wbm works with multiple random effects", {
suppressWarnings({
wb <- wbm(wks ~ union + lag(lwage) | blk | (union | id) + (lag(lwage) | id),
data = wages)
})
expect_s4_class(wb, "wbm")
})
test_that("wbm summary works", {
expect_s3_class(swb <- summary(wb), "summary.wbm")
expect_output(print(swb))
})
context("wbm with detrending")
wb1 <- suppressWarnings(wbm(wks ~ union + lag(lwage) | blk | (union | id),
data = wages, pvals = FALSE, detrend = TRUE))
wb2 <- wbm(wks ~ union + lag(lwage) | blk | (union | id),
data = wages, pvals = FALSE, detrend = TRUE,
balance_correction = TRUE)
test_that("wbm works (detrend only)", {
expect_s4_class(wb1, "wbm")
})
test_that("wbm works (w/ balance_correction)", {
expect_s4_class(wb2, "wbm")
})
test_that("wbm summary works (detrend only)", {
expect_s3_class(swb1 <- summary(wb1), "summary.wbm")
expect_output(print(swb1))
})
test_that("wbm summary works (detrend only)", {
expect_s3_class(swb2 <- summary(wb2), "summary.wbm")
expect_output(print(swb2))
})
context("Time-varying factors")
if (requireNamespace("plm")) {
data(Males, package = "plm")
males <- panel_data(Males, id = nr, wave = year)
set.seed(2)
males <- filter(males, nr %in% sample(males$nr, 100))
test_that("Models with time-varying factors work", {
expect_s4_class(wbf <- wbm(wage ~ industry + exper | ethn, data = males),
"wbm")
expect_output(print(summary(wbf)))
expect_s4_class(wbf <- wbm(wage ~ industry * exper | ethn, data = males),
"wbm")
expect_output(print(summary(wbf)))
expect_s4_class(wbf <- wbm(wage ~ industry + exper | ethn | industry * ethn,
data = males),
"wbm")
expect_output(print(summary(wbf)))
})
}
context("wbm_stan")
model <- wbm_stan(lwage ~ lag(union) + wks | blk + fem | blk * lag(union),
data = wages, chains = 1, iter = 2000, fit_model = FALSE)
test_that("wbm_stan makes code and data", {
expect_s3_class(model$stan_data, "standata")
expect_s3_class(model$stan_code, "brmsmodel")
})
library(brms)
model <- wbm_stan(lwage ~ lag(union) + wks | blk + fem | (blk | id),
data = wages, chains = 1, iter = 2000, fit_model = FALSE)
test_that("wbm_stan works w/ custom random effect", {
expect_s3_class(model$stan_data, "standata")
expect_s3_class(model$stan_code, "brmsmodel")
})
model <- wbm_stan(lwage ~ lag(union) + wks, data = wages,
model = "within", fit_model = FALSE, model.cor = TRUE)
model2 <- wbm_stan(lwage ~ lag(union) + wks | blk, data = wages,
model = "between", fit_model = FALSE)
model3 <- wbm_stan(lwage ~ lag(union) + wks | blk, data = wages,
model = "contextual", fit_model = FALSE)
test_that("wbm_stan works w/ other models", {
expect_s3_class(model$stan_data, "standata")
expect_s3_class(model$stan_code, "brmsmodel")
expect_s3_class(model2$stan_data, "standata")
expect_s3_class(model2$stan_code, "brmsmodel")
expect_s3_class(model3$stan_data, "standata")
expect_s3_class(model3$stan_code, "brmsmodel")
})
model <- wbm_stan(lwage ~ lag(union) + wks | blk + fem | (blk | id),
data = wages, chains = 1, iter = 2000, fit_model = FALSE,
detrend = TRUE)
test_that("wbm_stan works w/ detrending", {
expect_s3_class(model$stan_data, "standata")
expect_s3_class(model$stan_code, "brmsmodel")
})
model <- wbm_stan(lwage ~ lag(union) + wks | blk + fem | (blk | id),
data = wages, chains = 1, iter = 2000, fit_model = FALSE,
detrend = TRUE, balance_correction = TRUE)
test_that("wbm_stan works w/ balance correction", {
expect_s3_class(model$stan_data, "standata")
expect_s3_class(model$stan_code, "brmsmodel")
})
context("wbm predictions")
model <- wbm(lwage ~ lag(union) + wks, data = wages)
test_that("wbm predictions work w/o newdata", {
expect_is(predict(model), "numeric")
})
test_that("wbm predictions work w/ non-raw newdata", {
expect_is(predict(model, newdata = data.frame(
union = 1:4,
wks = 40,
lwage = 50,
id = 1,
t = 5
)), "numeric")
expect_is(predict(model, newdata = data.frame(
union = 1:4,
wks = 40,
lwage = 50,
id = 1,
t = 5
), re.form = ~0), "numeric")
expect_is(predict(model, newdata = panel_data(data.frame(
union = 1:4,
wks = 40,
lwage = 50,
id = 1,
t = 5
), id = id, wave = t, strict = FALSE)), "numeric")
expect_is(predict(model, newdata = panel_data(data.frame(
union = 1:4,
wks = 40,
lwage = 50,
id = 1,
t = 5
), id = id, wave = t, strict = FALSE), re.form = ~0), "numeric")
})
test_that("wbm predictions work w/ raw newdata", {
expect_is(predict(model, newdata = data.frame(
`lag(union)` = -2:2,
wks = 0,
`imean(wks)` = 40,
`imean(lag(union))` = 2,
lwage = 50,
id = 1,
t = 5, check.names = FALSE
), raw = TRUE), "numeric")
expect_is(predict(model, newdata = data.frame(
`lag(union)` = -2:2,
wks = 0,
`imean(wks)` = 40,
`imean(lag(union))` = 2,
lwage = 50,
id = 1,
t = 5, check.names = FALSE
), raw = TRUE, re.form = ~0), "numeric")
}) |
DNbuilder.surv <- function(model, data, clevel, m.summary, covariate,
ptype, DNtitle, DNxlab, DNylab, KMtitle, KMxlab, KMylab) {
mclass <- getclass.DN(model)$model.class
mlinkF <- function(mu) exp(-mu)
input.data <- NULL
old.d <- NULL
Surv.in <- length(model$terms[[2]]) != 1
if (!Surv.in)
stop(paste("Error in model syntax: the Surv (survival object) object is created outside of", mclass))
coll=rep(c("
"
if (mclass %in% c("cph")){
model <- update(model, x=T, y=T, surv=T)
}
if (length(attr(model$terms, "term.labels")) == 0)
stop("Error in model syntax: the model is null")
if (any(!is.null(attr(model$terms, "specials")$tt)))
stop("Error in model syntax: coxph models with a time dependent covariate is not supported")
if (any(attr(model$terms, "dataClasses")[[1]] == "nmatrix.3", dim(model$y)[2]==3))
stop("Error in model syntax: start/stop notation not supported")
if (mclass %in% c("coxph")){
strata.l <- attr(model$terms, "specials")$strata
n.strata <- length(attr(model$terms, "specials")$strata)
dim.terms <- length(attr(model$terms, "dataClasses"))
if ("(weights)" %in% names(attr(model$terms, "dataClasses"))){
attr(model$terms,"dataClasses") <- attr(model$terms, "dataClasses")[-c(length(attr(model$terms, "dataClasses")))]
}
mterms <- attr(model$terms, "dataClasses")[-1]
names(mterms)=all.vars(model$terms)[-c(1,2)]
}
if (mclass %in% c("cph")){
strata.l <- levels(model$strata)
n.strata <- length(attr(model$terms, "specials")$strat)
dim.terms <- length(model$Design$units) + 1
mterms=model$Design$assume[model$Design$assume!="interaction"]
names(mterms)=names(model$Design$units)
}
mterms[mterms %in% c("numeric", "asis", "polynomial", "integer", "double", "matrx") |
grepl("nmatrix", mterms, fixed = T) | grepl("spline", mterms, fixed = T)] = "numeric"
mterms[mterms %in% c("factor", "ordered", "logical", "category", "scored", "strata")] = "factor"
preds <- as.list(mterms)
tim <- all.vars(model$terms)[1:2]
ttim <- list(v.min = floor(min(na.omit(data[tim[1]]))),
v.max = ceiling(max(na.omit(data[tim[1]]))),
v.mean = zapsmall(median(data[tim[1]][,1], na.rm=T), digits = 4))
for (i in 1:length(preds)){
if (preds[[i]] == "numeric"){
i.dat <- which(names(preds[i]) == names(data))
preds[[i]] <- list(dataClasses = preds[[i]],
v.min = floor(min(na.omit(data[, as.numeric(i.dat)]))),
v.max = ceiling(max(na.omit(data[, as.numeric(i.dat)]))),
v.mean = mean(data[, as.numeric(i.dat)], na.rm=T)
)
next
}
if (preds[[i]] == "factor"){
i.dat <- which(names(preds[i]) == names(data))
if (mclass %in% c("coxph")){
i.ifstrat <- grepl("strata(", names(attr(model$terms,"dataClasses"))[i+1], fixed=TRUE)
if (grepl("strata(", names(attr(model$terms,"dataClasses"))[i+1], fixed=TRUE)) {
preds[[i]] <- list(dataClasses = preds[[i]], IFstrata = T, v.levels = model$xlevels[[which(grepl(names(preds[i]), names(model$xlevels), fixed=TRUE))]])
} else{
preds[[i]] <- list(dataClasses = preds[[i]], IFstrata = F, v.levels = model$xlevels[[which(names(preds[i]) == names(model$xlevels))]])
}
}
if (mclass %in% c("cph")){
preds[[i]] <- list(dataClasses = preds[[i]], IFstrata = model$Design$assume[i] == "strata", v.levels = model$Design$parms[[which(names(preds[i]) == names(model$Design$parms))]])
}
}
}
if (length(names(preds)) == 1) {
input.data <- data.frame(data[0, names(preds)])
names(input.data)[1] <- names(preds)
} else {
input.data <- data[0, names(preds)]
}
input.data <- data.frame(data.frame(tim1=0)[0,], input.data)
names(input.data)[1] <- tim[1]
if (mclass %in% c("coxph")){
model <- update(model, data=data)
}
wdir <- getwd()
app.dir <- paste(wdir, "DynNomapp", sep="/")
message(paste("creating new directory: ", app.dir, sep=""))
dir.create(app.dir)
setwd(app.dir)
message(paste("Export dataset: ", app.dir, "/dataset.RData", sep=""))
save(data, model, preds, mlinkF, getpred.DN, getclass.DN, ttim, tim, ptype, n.strata, coll, dim.terms, strata.l,
DNtitle, DNxlab, DNylab, KMtitle, KMxlab, KMylab, terms, input.data, file = "data.RData")
message(paste("Export functions: ", app.dir, "/functions.R", sep=""))
dump(c("getpred.DN", "getclass.DN"), file="functions.R")
p1title.bl <- paste(clevel * 100, "% ", "Confidence Interval for Response", sep = "")
p1msg.bl <- paste("Confidence interval is not available as there is no standard errors available by '", mclass, "' ", sep="")
sumtitle.bl = paste("Cox model (", model$call[1],"): ", model$call[2], sep = "")
if (m.summary == "formatted"){
sum.bi <- paste("coef.c <- exp(model$coef)
ci.c <- exp(suppressMessages(confint(model, level = clevel)))
stargazer(model, coef = list(coef.c), ci.custom = list(ci.c), p.auto = F,
type = 'text', omit.stat = c('LL', 'ser', 'f'), ci = TRUE, ci.level = clevel, single.row = TRUE,
title = '", sumtitle.bl,"')", sep="")
}
if (m.summary == "raw"){
sum.bi <- paste("summary(model)")
}
if (mclass == "cph"){
datadist.bl <- paste(paste(model$call[[3]]), "=data
t.dist <- datadist(", paste(model$call[[3]]),")
options(datadist = 't.dist')", sep="")
} else{
datadist.bl <- ""
}
if (mclass == "coxph"){
library.bl <- paste("library(survival)")
}
if (mclass == "cph"){
library.bl <- paste("library(rms)")
}
if (mclass == "cph"){
stratlvl.bl <- paste("if (length(levels(model$strata)) != length(levels(attr(predict(model, new.d(), type='x', expand.na=FALSE), 'strata')))){
levels(model$strata) <- levels(attr(predict(model, new.d(), type='x', expand.na=FALSE), 'strata'))
}")
} else{
stratlvl.bl <- ""
}
if (mclass %in% c("coxph")){
nam0.bl <- paste("nam0=paste(new.d()[[names(preds[i])]], sep = '')")
}
if (mclass %in% c("cph")){
nam0.bl <- paste("nam0 <- paste(names(preds[i]),'=', new.d()[[names(preds[i])]], sep = '')")
}
if (mclass %in% c("coxph")){
nam.bl <- paste("nam <- paste(nam, ', ', nam0, sep = '')")
}
if (mclass %in% c("cph")){
nam.bl <- paste("nam <- paste(nam, '.', nam0, sep = '')")
}
if (mclass %in% c("coxph")){
stcond.bl <- paste("!try.survfit")
}
if (mclass %in% c("cph")){
stcond.bl <- paste("!nam %in% strata.l")
}
GLOBAL=paste("library(ggplot2)
library(shiny)
library(plotly)
library(stargazer)
library(compare)
library(prediction)
", library.bl ,"
load('data.RData')
source('functions.R')
", datadist.bl,"
m.summary <- '",m.summary,"'
covariate <- '", covariate,"'
clevel <- ", clevel,"
", sep="")
UI=paste("ui = bootstrapPage(fluidPage(
titlePanel('", DNtitle,"'),
sidebarLayout(sidebarPanel(uiOutput('manySliders'),
checkboxInput('trans', 'Alpha blending (transparency)', value = TRUE),
actionButton('add', 'Predict'),
br(), br(),
helpText('Press Quit to exit the application'),
actionButton('quit', 'Quit')
),
mainPanel(tabsetPanel(id = 'tabs',
tabPanel('Survival plot', plotOutput('plot')),
tabPanel('Predicted Survival', plotlyOutput('plot2')),
tabPanel('Numerical Summary', verbatimTextOutput('data.pred')),
tabPanel('Model Summary', verbatimTextOutput('summary'))
)
)
)))", sep = "")
SERVER=paste('server = function(input, output){
observe({if (input$quit == 1)
stopApp()})
output$manySliders <- renderUI({
slide.bars <- list()
for (j in 1:length(preds)){
if (preds[[j]]$dataClasses == "factor"){
slide.bars[[j]] <- list(selectInput(names(preds)[j], names(preds)[j], preds[[j]]$v.levels, multiple = FALSE))
}
if (preds[[j]]$dataClasses == "numeric"){
if (covariate == "slider") {
slide.bars[[j]] <- list(sliderInput(names(preds)[j], names(preds)[j],
min = preds[[j]]$v.min, max = preds[[j]]$v.max, value = preds[[j]]$v.mean))
}
if (covariate == "numeric") {
slide.bars[[j]] <- list(numericInput(names(preds)[j], names(preds)[j], value = zapsmall(preds[[j]]$v.mean, digits = 4)))
}}}
if (covariate == "slider") {
slide.bars[[length(preds) + 1]] <-
list(br(), checkboxInput("times", "Predicted Survival at this Follow Up:"),
conditionalPanel(condition = "input.times == true",
sliderInput("tim", tim[1], min = ttim$v.min, max = ttim$v.max, value = ttim$v.mean)))
} else {
slide.bars[[length(preds) + 1]] <-
list(br(), checkboxInput("times", "Predicted Survival at this Follow Up:"),
conditionalPanel(condition = "input.times == true",
numericInput("tim", tim[1], value = zapsmall(ttim$v.mean, digits = 4))))
}
do.call(tagList, slide.bars)
})
a <- 0
old.d <- NULL
new.d <- reactive({
input$add
input.v <- vector("list", length(preds) + 1)
input.v[[1]] <- isolate({ input[["tim"]] })
names(input.v)[1] <- tim[1]
for (i in 1:length(preds)) {
input.v[[i+1]] <- isolate({
input[[names(preds)[i]]]
})
names(input.v)[i+1] <- names(preds)[i]
}
out <- data.frame(lapply(input.v, cbind))
if (a == 0) {
wher <- match(names(out), names(input.data))
out <- out[wher]
input.data <<- rbind(input.data, out)
}
if (a > 0) {
wher <- match(names(out), names(input.data))
out <- out[wher]
if (!isTRUE(compare(old.d, out))) {
input.data <<- rbind(input.data, out)
}}
a <<- a + 1
out
})
p1 <- NULL
old.d <- NULL
data2 <- reactive({
if (input$add == 0)
return(NULL)
if (input$add > 0) {
if (!isTRUE(compare(old.d, new.d()))) {
OUT <- isolate({
new.d <- cbind(st.ind = 1, new.d())
names(new.d)[1] <- tim[2]
DNpred <- getpred.DN(model, new.d)
mpred <- DNpred$pred
se.pred <- DNpred$SEpred
pred <- mlinkF(mpred)
if (is.na(se.pred)) {
lwb <- NULL
upb <- NULL
} else {
lwb <- sort(mlinkF(mpred + cbind(1, -1) * (qnorm(1 - (1 - clevel)/2) * se.pred)))[1]
upb <- sort(mlinkF(mpred + cbind(1, -1) * (qnorm(1 - (1 - clevel)/2) * se.pred)))[2]
if (upb > 1) {
upb <- 1
}}
if (ptype == "st") {
d.p <- data.frame(Prediction = zapsmall(pred, digits = 2),
Lower.bound = zapsmall(lwb, digits = 2),
Upper.bound = zapsmall(upb, digits = 2))
}
if (ptype == "1-st") {
d.p <- data.frame(Prediction = zapsmall(1-pred, digits = 2),
Lower.bound = zapsmall(1-upb, digits = 2),
Upper.bound = zapsmall(1-lwb, digits = 2))
}
old.d <<- new.d[,-1]
data.p <- cbind(d.p, counter = TRUE)
if (DNpred$InRange){
p1 <<- rbind(p1[,-5], data.p)
} else{
p1 <<- rbind(p1[,-5], data.frame(Prediction = NA, Lower.bound = NA, Upper.bound = NA, counter = FALSE))
}
p1
})
} else {
p1$count <- seq(1, dim(p1)[1])
}}
p1
})
s.fr <- NULL
old.d2 <- NULL
b <- 1
dat.p <- reactive({
if (isTRUE(compare(old.d2, new.d())) == FALSE) {
', stratlvl.bl,'
try.survfit <- !any(class(try(survfit(model, newdata = new.d()), silent = TRUE)) == "try-error")
if (try.survfit){
fit1 <- survfit(model, newdata = new.d())
}
if (n.strata == 0) {
sff <- data.frame(summary(fit1)[c("time", "n.risk", "surv")])
sff <- cbind(sff, event=1-sff$surv, part = b)
if (sff$time[1] != 0){
sff <- rbind(data.frame(time=0, n.risk=sff$n.risk[1] ,surv=1, event=0, part=sff$part[1]), sff)
}}
if (n.strata > 0) {
nam <- NULL
new.sub <- T
for (i in 1:(dim.terms-1)) {
if (preds[[i]]$dataClasses == "factor"){
if (preds[[i]]$IFstrata){
', nam0.bl,'
if (new.sub) {
nam <- paste(nam0)
new.sub <- F
} else {
', nam.bl,'
}}}}
if (try.survfit){
sub.fit1 <- subset(as.data.frame(summary(fit1)[c("time", "n.risk", "strata", "surv")]), strata == nam)
} else{
sub.fit1 <- data.frame(time=NA, n.risk=NA, strata=NA, surv=NA, event=NA, part=NA)[0,]
}
if (', stcond.bl,'){
message("The strata levels not found in the original")
sff <- cbind(sub.fit1, event=NULL, part = NULL)
b <<- b - 1
} else{
sff <- cbind(sub.fit1, event=1-sub.fit1$surv, part = b)
if (sff$time[1] != 0) {
sff <- rbind(data.frame(time=0, n.risk=sff$n.risk[1], strata=sff$strata[1] ,surv=1, event=0, part=sff$part[1]), sff)
}
sff$n.risk <- sff$n.risk/sff$n.risk[1]
}
sff$n.risk <- sff$n.risk/sff$n.risk[1]
}
s.fr <<- rbind(s.fr, sff)
old.d2 <<- new.d()
b <<- b + 1
}
s.fr
})
dat.f <- reactive({
if (nrow(data2() > 0))
cbind(input.data, data2()[1:3])
})
output$plot <- renderPlot({
data2()
if (input$add == 0)
return(NULL)
if (input$add > 0) {
if (ptype == "st") {
if (input$trans == TRUE) {
pl <- ggplot(data = dat.p()) +
geom_step(aes(x = time, y = surv, alpha = n.risk, group = part), color = coll[dat.p()$part])
}
if (input$trans == FALSE) {
pl <- ggplot(data = dat.p()) +
geom_step(aes(x = time, y = surv, group = part), color = coll[dat.p()$part])
}}
if (ptype == "1-st") {
if (input$trans == TRUE) {
pl <- ggplot(data = dat.p()) +
geom_step(aes(x = time, y = event, alpha = n.risk, group = part), color = coll[dat.p()$part])
}
if (input$trans == FALSE) {
pl <- ggplot(data = dat.p()) +
geom_step(aes(x = time, y = event, group = part), color = coll[dat.p()$part])
}}
pl <- pl + ylim(0, 1) + xlim(0, max(dat.p()$time) * 1.05) +
labs(title = "', KMtitle,'", x = "', KMxlab,'", y = "', KMylab,'") + theme_bw() +
theme(text = element_text(face = "bold", size = 12), legend.position = "none", plot.title = element_text(hjust = .5))
}
print(pl)
})
output$plot2 <- renderPlotly({
if (input$add == 0)
return(NULL)
if (is.null(new.d()))
return(NULL)
lim <- c(0, 1)
yli <- c(0 - 0.5, 10 + 0.5)
input.data = input.data[data2()$counter,]
in.d <- data.frame(input.data)
xx=matrix(paste(names(in.d), ": ",t(in.d), sep=""), ncol=dim(in.d)[1])
text.cov=apply(xx,2,paste,collapse="<br />")
if (dim(input.data)[1] > 11)
yli <- c(dim(input.data)[1] - 11.5, dim(input.data)[1] - 0.5)
dat2 <- data2()[data2()$counter,]
dat2$count = seq(1, nrow(dat2))
p <- ggplot(data = dat2, aes(x = Prediction, y = count - 1, text = text.cov,
label = Prediction, label2 = Lower.bound, label3=Upper.bound)) +
geom_point(size = 2, colour = coll[dat2$count], shape = 15) +
ylim(yli[1], yli[2]) + coord_cartesian(xlim = lim) +
labs(title = "', p1title.bl,'",
x = "', DNxlab,'", y = "', DNylab,'") + theme_bw() +
theme(axis.text.y = element_blank(), text = element_text(face = "bold", size = 10))
if (is.numeric(dat2$Upper.bound)){
p <- p + geom_errorbarh(xmax = dat2$Upper.bound, xmin = dat2$Lower.bound,
size = 1.45, height = 0.4, colour = coll[dat2$count])
} else{
message("', p1msg.bl,'")
}
if (ptype == "st") {
p <- p + labs(title = paste(clevel * 100, "% ", "Confidence Interval for Survival Probability", sep = ""),
x = DNxlab, y = DNylab)
}
if (ptype == "1-st") {
p <- p + labs(title = paste(clevel * 100, "% ", "Confidence Interval for F(t)", sep = ""),
x = DNxlab, y = DNylab)
}
gp=ggplotly(p, tooltip = c("text","label","label2","label3"))
gp$elementId <- NULL
dat.p()
gp
})
output$data.pred <- renderPrint({
if (input$add > 0) {
if (nrow(data2() > 0)) {
stargazer(dat.f(), summary = FALSE, type = "text")
}}
})
output$summary <- renderPrint({
', sum.bi,'
})
}', sep = "")
output=list(ui=UI, server=SERVER, global=GLOBAL)
text <- paste("This guide will describe how to deploy a shiny application using scripts generated by DNbuilder:
1. Run the shiny app by setting your working directory to the DynNomapp folder, and then run: shiny::runApp() If you are using the RStudio IDE, you can also run it by clicking the Run App button in the editor toolbar after open one of the R scripts.
2. You could modify codes to apply all the necessary changes. Run again to confirm that your application works perfectly.
3. Deploy the application by either clicking on the Publish button in the top right corner of the running app, or use the generated files and deploy it on your server if you host any.
You can find a full guide of how to deploy an application on shinyapp.io server here:
http://docs.rstudio.com/shinyapps.io/getting-started.html
Please cite the package if using in publication.", sep="")
message(paste("writing file: ", app.dir, "/README.txt", sep=""))
writeLines(text, "README.txt")
message(paste("writing file: ", app.dir, "/ui.R", sep=""))
writeLines(output$ui, "ui.R")
message(paste("writing file: ", app.dir, "/server.R", sep=""))
writeLines(output$server, "server.R")
message(paste("writing file: ", app.dir, "/global.R", sep=""))
writeLines(output$global, "global.R")
setwd(wdir)
} |
native_areas <- function(cb = FALSE, year = NULL, ...) {
if (is.null(year)) {
year <- getOption("tigris_year", 2019)
}
if (year < 2011) {
fname <- as.character(match.call())[[1]]
msg <- sprintf("%s is not currently available for years prior to 2011. To request this feature,
file an issue at https://github.com/walkerke/tigris.", fname)
stop(msg, call. = FALSE)
}
cyear <- as.character(year)
if (cb == TRUE) {
url <- sprintf("https://www2.census.gov/geo/tiger/GENZ%s/shp/cb_%s_us_aiannh_500k.zip",
cyear, cyear)
} else {
url <- sprintf("https://www2.census.gov/geo/tiger/TIGER%s/AIANNH/tl_%s_us_aiannh.zip",
cyear, cyear)
}
return(load_tiger(url, ...))
}
tribal_subdivisions_national <- function(year = NULL, ...) {
if (is.null(year)) {
year <- getOption("tigris_year", 2019)
}
if (year < 2011) {
fname <- as.character(match.call())[[1]]
msg <- sprintf("%s is not currently available for years prior to 2011. To request this feature,
file an issue at https://github.com/walkerke/tigris.", fname)
stop(msg, call. = FALSE)
}
if (year == 2015) {
url <- "https://www2.census.gov/geo/tiger/TIGER2015/AITSN/tl_2015_us_aitsn.zip"
} else {
url <- paste0("https://www2.census.gov/geo/tiger/TIGER",
as.character(year),
"/AITS/tl_",
as.character(year),
"_us_aitsn.zip")
}
return(load_tiger(url, ...))
}
alaska_native_regional_corporations <- function(cb = FALSE, year = NULL, ...) {
if (is.null(year)) {
year <- getOption("tigris_year", 2019)
}
if (year < 2011) {
fname <- as.character(match.call())[[1]]
msg <- sprintf("%s is not currently available for years prior to 2011. To request this feature,
file an issue at https://github.com/walkerke/tigris.", fname)
stop(msg, call. = FALSE)
}
cyear <- as.character(year)
if (cb == TRUE) {
url <- sprintf("https://www2.census.gov/geo/tiger/GENZ%s/shp/cb_%s_02_anrc_500k.zip",
cyear, cyear)
} else {
url <- sprintf("https://www2.census.gov/geo/tiger/TIGER%s/ANRC/tl_%s_02_anrc.zip",
cyear, cyear)
}
return(load_tiger(url, ...))
}
tribal_block_groups <- function(year = NULL, ...) {
if (is.null(year)) {
year <- getOption("tigris_year", 2019)
}
if (year < 2011) {
fname <- as.character(match.call())[[1]]
msg <- sprintf("%s is not currently available for years prior to 2011. To request this feature,
file an issue at https://github.com/walkerke/tigris.", fname)
stop(msg, call. = FALSE)
}
url <- sprintf("https://www2.census.gov/geo/tiger/TIGER%s/TBG/tl_%s_us_tbg.zip",
as.character(year), as.character(year))
return(load_tiger(url, ...))
}
tribal_census_tracts <- function(year = NULL, ...) {
if (is.null(year)) {
year <- getOption("tigris_year", 2019)
}
if (year < 2011) {
fname <- as.character(match.call())[[1]]
msg <- sprintf("%s is not currently available for years prior to 2011. To request this feature,
file an issue at https://github.com/walkerke/tigris.", fname)
stop(msg, call. = FALSE)
}
url <- sprintf("https://www2.census.gov/geo/tiger/TIGER%s/TTRACT/tl_%s_us_ttract.zip",
as.character(year), as.character(year))
return(load_tiger(url, ...))
} |
context("Text Interchange Format")
test_that("Can detect a TIF compliant data.frame", {
expect_true(is_corpus_df(docs_df))
bad_df <- docs_df
bad_df$doc_id <- NULL
expect_error(is_corpus_df(bad_df))
})
test_that("Can coerce a TIF compliant data.frame to a character vector", {
output <- docs_df$text
names(output) <- docs_df$doc_id
expect_identical(corpus_df_as_corpus_vector(docs_df), output)
})
test_that("Different methods produce identical output", {
expect_identical(tokenize_words(docs_c), tokenize_words(docs_df))
expect_identical(tokenize_words(docs_l), tokenize_words(docs_df))
expect_identical(tokenize_characters(docs_c), tokenize_characters(docs_df))
expect_identical(tokenize_characters(docs_l), tokenize_characters(docs_df))
expect_identical(tokenize_sentences(docs_c), tokenize_sentences(docs_df))
expect_identical(tokenize_sentences(docs_l), tokenize_sentences(docs_df))
expect_identical(tokenize_lines(docs_c), tokenize_lines(docs_df))
expect_identical(tokenize_lines(docs_l), tokenize_lines(docs_df))
expect_identical(tokenize_paragraphs(docs_c), tokenize_paragraphs(docs_df))
expect_identical(tokenize_paragraphs(docs_l), tokenize_paragraphs(docs_df))
expect_identical(tokenize_regex(docs_c), tokenize_regex(docs_df))
expect_identical(tokenize_regex(docs_l), tokenize_regex(docs_df))
expect_identical(tokenize_tweets(docs_c), tokenize_tweets(docs_df))
expect_identical(tokenize_tweets(docs_l), tokenize_tweets(docs_df))
expect_identical(tokenize_ngrams(docs_c), tokenize_ngrams(docs_df))
expect_identical(tokenize_ngrams(docs_l), tokenize_ngrams(docs_df))
expect_identical(tokenize_skip_ngrams(docs_c), tokenize_skip_ngrams(docs_df))
expect_identical(tokenize_skip_ngrams(docs_l), tokenize_skip_ngrams(docs_df))
expect_identical(tokenize_ptb(docs_c), tokenize_ptb(docs_df))
expect_identical(tokenize_ptb(docs_l), tokenize_ptb(docs_df))
expect_identical(tokenize_character_shingles(docs_c),
tokenize_character_shingles(docs_df))
expect_identical(tokenize_character_shingles(docs_l),
tokenize_character_shingles(docs_df))
expect_identical(tokenize_word_stems(docs_c), tokenize_word_stems(docs_df))
expect_identical(tokenize_word_stems(docs_l), tokenize_word_stems(docs_df))
}) |
ghap.ancplot <- function(
ancsmooth,
labels=TRUE,
pop.ang=45,
group.ang=0,
colors=NULL,
pop.order=NULL,
sortby=NULL,
use.unk=TRUE,
legend=TRUE
){
if(use.unk == TRUE){
admix <- ancsmooth$proportions1
}else{
admix <- ancsmooth$proportions2
}
admix[,-c(1:2)] <- admix[,-c(1:2)]*100
npop <- ncol(admix) - 2
if(is.null(pop.order) == TRUE){
admix$POP <- factor(x = admix$POP)
}else{
admix$POP <- factor(x = admix$POP, levels = unlist(pop.order))
}
if(is.null(sortby) == TRUE){
admix <- admix[order(admix$POP,admix$ID),]
}else{
admix <- admix[order(admix$POP,admix[,sortby]),]
}
if(is.null(colors) == TRUE){
colors <- c("
colors <- colors[1:npop]
if(use.unk == TRUE){
colors[npop] <- "grey"
}
}else if(length(colors) != npop){
stop("Number of colors must match number of groups")
}
oldpar <- par(no.readonly = TRUE)
on.exit(par(oldpar))
if(legend == TRUE){
par(mar=c(5, 4, 4, 2) + 0.1)
par(xpd=T, mar=par()$mar+c(2,0,0,0))
}
p <- barplot(t(admix[,-c(1:2)]), space = 0, border = NA, col = colors, las=1, ylab = "Ancestry (%)",
xaxt="n", ylim=c(0,125), yaxt = "n")
axis(side = 2, at = seq(0,100,by=20), labels = seq(0,100,by=20), las =1)
admix$POS <- p
p <- aggregate(POS ~ POP, data = admix, FUN = median)
xmin <- aggregate(POS ~ POP, data = admix, FUN = min)
xmax <- aggregate(POS ~ POP, data = admix, FUN = max)
u <- par("usr")
if(labels == TRUE){
text(x=p$POS, y=u[3]-0.1*(u[4]-u[3]),
labels=p$POP, srt=pop.ang, adj=1, xpd=TRUE)
}
rect(xleft = min(admix$POS)-0.5, ybottom = 0,
xright = max(admix$POS)+0.5, ytop = 100,
col="
segments(x0 = xmax$POS+0.5, y0 = 0, x1 = xmax$POS+0.5, y1 = 100)
if(is.list(pop.order) == TRUE){
labcol <- rep(c("black","darkgrey"), times = length(pop.order))
labcol <- labcol[1:length(pop.order)]
for(i in 1:length(pop.order)){
segments(x0 = min(xmin$POS[which(xmin$POP %in% pop.order[[i]])])-0.5, y0 = 102.5,
x1 = max(xmax$POS[which(xmax$POP %in% pop.order[[i]])])+0.5, y1 = 102.5,
col = labcol[i], lwd = 3)
text(x = median(p$POS[which(p$POP %in% pop.order[[i]])]), y = 108,
labels = names(pop.order)[i], srt=group.ang, col = "black")
}
}
if(legend == TRUE){
if(use.unk == TRUE){
ltext <- colnames(admix[-c(1,2,ncol(admix),ncol(admix)-1)])
ltext <- c(ltext, "?")
}else{
ltext <- colnames(admix[-c(1,2,ncol(admix),ncol(admix))])
}
legend(x = median(p$POS), y = -40, legend = ltext,
fill = colors, bty="n", ncol=npop, xjust=0.6)
par(mar=c(5, 4, 4, 2) + 0.1)
}
} |
context("ggheatmap")
test_that("ggheatmap works", {
g <- ggheatmap(mtcars, dendrogram = "none")
expect_is(g, "egg")
g <- ggheatmap(mtcars, dendrogram = "row")
expect_is(g, "egg")
g <- ggheatmap(mtcars, dendrogram = "column")
expect_is(g, "egg")
g <- ggheatmap(mtcars, row_dend_left = TRUE)
expect_is(g, "egg")
g <- ggheatmap(mtcars, dendrogram = "row", row_dend_left = TRUE)
expect_is(g, "egg")
g <- ggheatmap(mtcars, row_side_colors = mtcars[, 2])
expect_is(g, "egg")
g <- ggheatmap(mtcars, col_side_colors = t(mtcars[1, ]))
expect_is(g, "egg")
g <- ggheatmap(mtcars, row_side_colors = mtcars[, 2], col_side_colors = t(mtcars[1, ]))
expect_is(g, "egg")
}) |
do_break_edges <- function(nodes, edges) {
sel <- function(id, attr) nodes[match(id, nodes[,1]), attr]
to_break <- which(sel(edges[,2], "x") - sel(edges[,1], "x") > 1)
if (length(to_break) == 0) return(list(nodes = nodes, edges = edges))
col1 <- sel(edges[to_break, 1], "col")
col2 <- sel(edges[to_break, 2], "col")
col <- mean_colors(col1, col2)
new_nodes <- data.frame(
stringsAsFactors = FALSE,
id = make.unique(
paste(edges[to_break, 1], sep = "-", edges[to_break, 2]), sep = "_"
),
x = (sel(edges[to_break, 1], "x") + sel(edges[to_break, 2], "x")) / 2,
label = "",
size = 1,
shape = "invisible",
boxw = 0,
col = col
)
names(new_nodes)[1] <- names(nodes)[1]
edges2 <- edges[to_break, ]
edges[to_break, 2] <- new_nodes[,1]
edges2[,1] <- new_nodes[,1]
edges <- rbind(edges, edges2)
nodes <- merge(nodes, new_nodes, all = TRUE)
list(nodes = nodes, edges = edges)
}
mean_colors <- function(col1, col2) {
vapply(seq_along(col1), FUN.VALUE = "", function(i) {
mrgb <- rowMeans(cbind(col2rgb(col1[i]), col2rgb(col2[i])))
do.call(rgb, as.list(mrgb / 255))
})
} |
approx.posterior <- function(trait.mcmc, priors, trait.data = NULL, outdir = NULL, filename.flag = "") {
posteriors <- priors
do.plot <- !is.null(outdir)
if (do.plot == TRUE) {
pdf(file.path(outdir, paste("posteriors", filename.flag, ".pdf", sep = "")))
}
for (trait in names(trait.mcmc)) {
dat <- trait.mcmc[[trait]]
vname <- colnames(dat[[1]])
if ("beta.o" %in% vname) {
dat <- as.matrix(dat)[, "beta.o"]
}
pdist <- priors[trait, "distn"]
pparm <- as.numeric(priors[trait, 2:3])
ptrait <- trait
zerobound <- c("exp", "gamma", "lnorm", "weibull")
if (pdist %in% "beta") {
m <- mean(dat)
v <- var(dat)
k <- (1 - m)/m
a <- (k / ((1 + k) ^ 2 * v) - 1) / (1 + k)
b <- a * k
fit <- try(suppressWarnings(MASS::fitdistr(dat, "beta", list(shape1 = a, shape2 = b))), silent = TRUE)
if (do.plot) {
x <- seq(0, 1, length = 1000)
plot(density(dat), col = 2, lwd = 2, main = trait)
if (!is.null(trait.data)) {
rug(trait.data[[trait]]$Y, lwd = 2, col = "purple")
}
lines(x, dbeta(x, fit$estimate[1], fit$estimate[2]), lwd = 2, type = "l")
lines(x, dbeta(x, pparm[1], pparm[2]), lwd = 3, type = "l", col = 3)
legend("topleft",
legend = c("data", "prior", "post", "approx"),
col = c("purple", 3, 2, 1), lwd = 2)
}
posteriors[trait, "parama"] <- fit$estimate[1]
posteriors[trait, "paramb"] <- fit$estimate[2]
} else if (pdist %in% zerobound || (pdist == "unif" & pparm[1] >= 0)) {
dist.names <- c("exp", "lnorm", "weibull", "norm")
fit <- list()
fit[[1]] <- try(suppressWarnings(MASS::fitdistr(dat, "exponential")), silent = TRUE)
fit[[2]] <- try(suppressWarnings(MASS::fitdistr(dat, "lognormal")), silent = TRUE)
fit[[3]] <- try(suppressWarnings(MASS::fitdistr(dat, "weibull")), silent = TRUE)
fit[[4]] <- try(suppressWarnings(MASS::fitdistr(dat, "normal")), silent = TRUE)
if (!trait == "cuticular_cond") {
fit[[5]] <- try(suppressWarnings(MASS::fitdistr(dat, "gamma")), silent = TRUE)
dist.names <- c(dist.names, "gamma")
}
failfit.bool <- sapply(fit, class) == "try-error"
fit[failfit.bool] <- NULL
dist.names <- dist.names[!failfit.bool]
fparm <- lapply(fit, function(x) { as.numeric(x$estimate) })
fAIC <- lapply(fit, AIC)
bestfit <- which.min(fAIC)
posteriors[ptrait, "distn"] <- dist.names[bestfit]
posteriors[ptrait, "parama"] <- fit[[bestfit]]$estimate[1]
if (bestfit == 1) {
posteriors[ptrait, "paramb"] <- NA
} else {
posteriors[ptrait, "paramb"] <- fit[[bestfit]]$estimate[2]
}
if (do.plot) {
.dens_plot(posteriors, priors, ptrait, dat, trait, trait.data)
}
} else {
posteriors[trait, "distn"] <- "norm"
posteriors[trait, "parama"] <- mean(dat)
posteriors[trait, "paramb"] <- sd(dat)
if (do.plot) {
.dens_plot(posteriors, priors, ptrait, dat, trait, trait.data)
}
}
}
if (do.plot) {
dev.off()
}
return(posteriors)
}
.dens_plot <- function(posteriors, priors, ptrait, dat, trait, trait.data,
plot_quantiles = c(0.01, 0.99)) {
f <- function(x) {
cl <- call(paste0("d", posteriors[ptrait, "distn"]),
x,
posteriors[ptrait, "parama"],
posteriors[ptrait, "paramb"])
eval(cl)
}
fq <- function(x) {
cl <- call(paste0("q", priors[ptrait, "distn"]),
x,
priors[ptrait, "parama"],
priors[ptrait, "paramb"])
eval(cl)
}
fp <- function(x) {
cl <- call(paste0("d", priors[ptrait, "distn"]),
x,
priors[ptrait, "parama"],
priors[ptrait, "paramb"])
eval(cl)
}
qbounds <- fq(plot_quantiles)
x <- seq(qbounds[1], qbounds[2], length = 1000)
rng <- range(dat)
if (!is.null(trait.data)) {
rng <- range(trait.data[[trait]]$Y)
}
plot(density(dat), col = 2, lwd = 2, main = trait, xlim = rng)
if (!is.null(trait.data)) {
rug(trait.data[[trait]]$Y, lwd = 2, col = "purple")
}
lines(x, f(x), lwd = 2, type = "l")
lines(x, fp(x), lwd = 3, type = "l", col = 3)
legend("topleft",
legend = c("data", "prior", "post", "approx"),
col = c("purple", 3, 2, 1), lwd = 2)
} |
get_enet = function(x,y, lambda, nonzero){
nonzero = nonzero +1
colnames(x) = paste("x", 1:ncol(x),sep=".")
epsilon.enet = enet(x, y ,lambda=lambda, max.steps=nonzero)[[4]]
tmp = rep(0,ncol(x))
tmp[colnames(x) %in% colnames(epsilon.enet)] = epsilon.enet[nonzero,]
names(tmp) <- colnames(x)
tmp
} |
bradford<-function(M){
SO=sort(table(M$SO),decreasing = TRUE)
n=sum(SO)
cumSO=cumsum(SO)
cutpoints=round(c(1,n*0.33,n*0.67,Inf))
groups=cut(cumSO,breaks = cutpoints,labels=c("Zone 1", "Zone 2", "Zone 3"))
a=length(which(cumSO<n*0.33))+1
b=length(which(cumSO<n*0.67))+1
Z=c(rep("Zone 1",a),rep("Zone 2",b-a),rep("Zone 3",length(cumSO)-b))
df=data.frame(SO=names(cumSO),Rank=1:length(cumSO),Freq=as.numeric(SO),cumFreq=cumSO,Zone=Z, stringsAsFactors = FALSE)
x <- c(max(log(df$Rank))-0.02-diff(range(log(df$Rank)))*0.125, max(log(df$Rank))-0.02)
y <- c(min(df$Freq),min(df$Freq)+diff(range(df$Freq))*0.125)+1
data("logo",envir=environment())
logo <- grid::rasterGrob(logo,interpolate = TRUE)
g=ggplot2::ggplot(df, aes(x = log(.data$Rank), y = .data$Freq, text=paste("Source: ",.data$SO,"\nN. of Documents: ",.data$Freq))) +
geom_line(aes(group="NA")) +
geom_area(aes(group="NA"),fill = "dodgerblue", alpha = 0.5) +
annotate("rect", xmin=0, xmax=log(df$Rank[a]), ymin=0, ymax=max(df$Freq), alpha=0.4)+
labs(x = 'Source log(Rank)', y = 'Articles', title = "Bradford's Law") +
annotate("text",x=log(df$Rank[a])/2, y=max(df$Freq)/2, label = "Core\nSources",fontface =2,alpha=0.5,size=10)+
scale_x_continuous(breaks=log(df$Rank)[1:a],labels=as.character(substr(df$SO,1,25))[1:a]) +
theme(text = element_text(color = "
,legend.position="none"
,panel.background = element_rect(fill = '
,panel.grid.minor = element_line(color = '
,panel.grid.major = element_line(color = '
,plot.title = element_text(size = 24)
,axis.title = element_text(size = 14, color = '
,axis.title.y = element_text(vjust = 1, angle = 90)
,axis.title.x = element_text(hjust = 0)
,axis.text.x = element_text(angle=90,hjust=1,size=8,face="bold")
) + annotation_custom(logo, xmin = x[1], xmax = x[2], ymin = y[1], ymax = y[2])
results=list(table=df,graph=g)
return(results)
} |
context("check scan.sim accuracy for different distributions")
set.seed(2)
nsim = 499
data(nydf)
coords = nydf[, c("x", "y")]
nn = nnpop(as.matrix(dist(coords)), pop = nydf$pop, ubpop = 0.1)
cases = floor(nydf$cases)
ty = sum(cases)
e = ty / sum(nydf$population) * nydf$population
ein = nn.cumsum(nn, e)
tpop = sum(nydf$population)
popin = nn.cumsum(nn, nydf$population)
sa = scan.sim(nsim, nn, ty = ty, ex = e, type = "poisson",
ein = ein, eout = ty - ein, simdist = "multinomial",
pop = nydf$pop)
sb = scan.sim(nsim, nn, ty = ty, ex = e, type = "poisson",
ein = ein, eout = ty - ein, simdist = "poisson",
pop = nydf$pop)
sc = scan.sim(nsim, nn, ty = ty, ex = e, type = "binomial",
ein = ein, eout = ty - ein, simdist = "binomial",
tpop = tpop, popin = popin,
popout = tpop - popin, pop = nydf$pop)
summa = summary(sa)
summb = summary(sb)
summc = summary(sc)
test_that("check accuracy for scan.sim", {
expect_true(round(summa[2], 1) - round(summb[2], 1) <= 0.1)
expect_true(round(summb[2], 1) - round(summc[2], 1) <= 0.1)
expect_true(round(summa[3], 1) - round(summb[3], 1) <= 0.1)
expect_true(round(summb[3], 1) - round(summc[3], 1) <= 0.1)
expect_true(round(summa[4], 1) - round(summb[4], 1) <= 0.1)
expect_true(round(summb[4], 1) - round(summc[4], 1) <= 0.1)
}) |
dc <- function(N, recmatrix, group.names=NA, area.names=NA, start=NA){
if(nrow(recmatrix)==ncol(recmatrix)){
nx <- recmatrix
x <- solve(nx, N)
}
if(nrow(recmatrix)<ncol(recmatrix)) print("Number of groups must be at least the number of areas.")
if(nrow(recmatrix)>ncol(recmatrix)){
ss <- function(x){
x.mat <- matrix(x, nrow=nrow(recmatrix), ncol=length(x), byrow=TRUE)
sums <- recmatrix*x.mat
sums1 <- apply(sums, 1, sum)
sum((sums1-N)^2)
}
ifelse(length(start)<2, init <- N[1]/recmatrix[1,]/2, init <- start)
x <- optim(par=init, ss)$par
}
if(length(area.names)<2) area.names <- paste(rep("Area", ncol(recmatrix)), 1:ncol(recmatrix))
rec.probs <- matrix(1/x, nrow=1)
colnames(rec.probs) <- area.names
x.mat <- matrix(x, nrow=nrow(recmatrix), ncol=length(x), byrow=TRUE)
N.mat <- matrix(N, ncol=ncol(recmatrix), nrow=length(N))
mig.rates.obs <- x.mat*recmatrix/N.mat
if(length(group.names)<2) group.names <- paste(rep("Group", nrow(recmatrix)), 1:nrow(recmatrix))
colnames(mig.rates.obs) <- area.names
rownames(mig.rates.obs) <- group.names
result <- list(rec.probs=rec.probs, division.coef=mig.rates.obs)
result
} |
if(require("tcltk"))
{
hue <- tclVar("hue")
chroma <- tclVar("chroma")
luminance <- tclVar("luminance")
fixup <- tclVar("fixup")
hue <- tclVar(230)
hue.sav <- 230
chroma <- tclVar(55)
chroma.sav <- 55
luminance <- tclVar(75)
luminance.sav <- 75
fixup <- tclVar(FALSE)
replot <- function(...) {
hue.sav <- my.h <- as.numeric(tclvalue(hue))
chroma.sav <- my.c <- as.numeric(tclvalue(chroma))
luminance.sav <- my.l <- as.numeric(tclvalue(luminance))
my.fixup <- as.logical(as.numeric(tclvalue(fixup)))
barplot(1, col = hcl2hex(my.h, my.c, my.l, fixup = my.fixup), axes = FALSE)
}
replot.maybe <- function(...)
{
if(!((as.numeric(tclvalue(hue)) == hue.sav) &&
(as.numeric(tclvalue(chroma)) == chroma.sav) &&
(as.numeric(tclvalue(luminance)) == luminance.sav))) replot()
}
base <- tktoplevel()
tkwm.title(base, "HCL Colors")
spec.frm <- tkframe(base, borderwidth = 2)
hue.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2)
chroma.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2)
luminance.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2)
fixup.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2)
tkpack(tklabel(hue.frm, text = "Hue"))
tkpack(tkscale(hue.frm, command = replot.maybe, from = 0, to = 360,
showvalue = TRUE, variable = hue,
resolution = 1, orient = "horiz"))
tkpack(tklabel(chroma.frm, text = "Chroma"))
tkpack(tkscale(chroma.frm, command = replot.maybe, from = 0, to = 100,
showvalue = TRUE, variable = chroma,
resolution = 5, orient = "horiz"))
tkpack(tklabel(luminance.frm, text = "Luminance"))
tkpack(tkscale(luminance.frm, command = replot.maybe, from = 0, to = 100,
showvalue = TRUE, variable = luminance,
resolution = 5, orient = "horiz"))
tkpack(tklabel(fixup.frm, text="Fixup"))
for (i in c("TRUE", "FALSE") ) {
tmp <- tkradiobutton(fixup.frm, command = replot,
text = i, value = as.logical(i), variable = fixup)
tkpack(tmp, anchor="w")
}
tkpack(hue.frm, chroma.frm, luminance.frm, fixup.frm, fill="x")
q.but <- tkbutton(base, text = "Quit",
command = function() tkdestroy(base))
tkpack(spec.frm, q.but)
replot()
} |
E4.GGIR.Export<-function(participant_list,ziplocation,csvlocation.GGIRout,tz){
ts<-E4serial<-NULL
if(participant_list[1]=="helper"){participant_list<-get("participant_list",envir=E4tools.env)}
if(ziplocation=="helper"){ziplocation<-get("ziplocation",envir=E4tools.env)}
if(csvlocation.GGIRout=="helper"){csvlocation.GGIRout<-get("csvlocation.GGIRout",envir=E4tools.env)}
for (NUMB in participant_list) {
message(paste("Starting participant",NUMB))
zipDIR<-paste(ziplocation,NUMB,sep="")
zipfiles <- list.files(zipDIR, pattern="*.zip", full.names=FALSE)
ACC_TEMP<-NULL
for (ZIPS in zipfiles) {
CURR_ZIP<-paste(ziplocation,NUMB,"/",ZIPS,sep="")
if(file.size(CURR_ZIP)>6400){
if(file.size(utils::unzip(CURR_ZIP, unzip = "internal",
exdir=tempdir(),files="ACC.csv"))>500){
ACC_single<-utils::read.csv(utils::unzip(CURR_ZIP, unzip = "internal",exdir=tempdir(),
files="ACC.csv"),sep=",",header=FALSE)
StartTime<-ACC_single[1,1]
SamplingRate<-ACC_single[2,1]
ACC_single<-ACC_single[-c(1:2),]
ACC_single<-as.data.frame(ACC_single)
E4_serial<-substring(ZIPS, regexpr("_", ZIPS) + 1)
E4_serial<-substr(E4_serial,1,6)
EndTime<-(StartTime+round((nrow(ACC_single)/SamplingRate),0))
ACC_single$ts<-seq(from=StartTime*1000,to=EndTime*1000,length.out=nrow(ACC_single))
TEMP_single<-utils::read.csv(utils::unzip(CURR_ZIP, unzip = "internal",exdir=tempdir(),
files="TEMP.csv"),sep=",",header=FALSE)
StartTime_TEMP<-TEMP_single[1,1]
SamplingRate_TEMP<-TEMP_single[2,1]
TEMP_single<-TEMP_single[-c(1:2),]
TEMP_single<-as.data.frame(TEMP_single)
EndTime_TEMP<-(StartTime_TEMP+round((nrow(TEMP_single)/SamplingRate_TEMP),0))
TEMP_single$ts<-seq(from=StartTime_TEMP*1000,to=EndTime_TEMP*1000,length.out=nrow(TEMP_single))
ACC_single_table<-data.table::as.data.table(ACC_single)
TEMP_single_table<-data.table::as.data.table(TEMP_single)
data.table::setkey(ACC_single_table, ts)
data.table::setkey(TEMP_single_table, ts)
ACC_TEMP_SINGLE<-TEMP_single_table[ACC_single_table, roll="nearest"]
ACC_TEMP_SINGLE$serial<-E4_serial
ACC_TEMP<-rbind(ACC_TEMP,ACC_TEMP_SINGLE)
}
}
}
ACC_TEMP$ts<-round(ACC_TEMP$ts/1000,0)
names(ACC_TEMP)<-c("temp","ts","acc_x","acc_y","acc_z","E4serial")
data.table::setcolorder(ACC_TEMP, c("ts","E4serial","acc_x","acc_y","acc_z","temp"))
header_col1<-rbind("device_brand",
"recording_ID",
"device_serial_number",
"N_subfiles",
"timestamp_type",
"timezone_tzdata_format",
"acc_sample_rate",
"acc_unit",
"acc_dynrange_plusmin_g",
"acc_bit_resolution",
"temp_sample_rate",
"temp_units",
"temp_range_min",
"temp_range_max",
"temp_resolution",
"starttime",
"",
"",
"")
overall_start<-((anytime::anytime(min(as.numeric((ACC_TEMP$ts))),tz=tz)))
header_col2<-cbind(c("E4",
NUMB,
as.character(as.factor(ACC_TEMP$E4serial)[1]),
levels(as.factor(ACC_TEMP$E4serial)),
"unix_ms",
tz,
SamplingRate,
"bits",
2,
8,
SamplingRate_TEMP,
"celsius",
-40,
115,
0.2,
as.character(format(overall_start,usetz=TRUE)),
"",
"",
""))
ACC_TEMP_header<-cbind(header_col1,header_col2,"","","")
ACC_TEMP_header<-rbind(ACC_TEMP_header,c("timestamp","acc_x_bits","acc_y_bits","acc_z_bits","temp"))
ACC_TEMP_header<-data.table::as.data.table(ACC_TEMP_header)
ACC_TEMP<-ACC_TEMP[,E4serial:=NULL]
names(ACC_TEMP_header)<-names(ACC_TEMP)
ACC_TEMP<-rbind(ACC_TEMP_header,ACC_TEMP)
if(!dir.exists(csvlocation.GGIRout)==TRUE){dir.create(csvlocation.GGIRout,recursive=TRUE)}
filename<-paste(csvlocation.GGIRout,NUMB,"_GGIR_out.csv",sep="")
utils::write.table(ACC_TEMP,file=filename,quote=TRUE,col.names=FALSE,sep=" ",na="",row.names=FALSE)
}
} |
library(hdi)
suppressWarnings(RNGversion("3.5.0"))
set.seed(123)
x <- matrix(rnorm(100*100), nrow = 100, ncol = 100)
y <- x[,1] + x[,2] + rnorm(100)
suppressWarnings(RNGversion("3.5.0"))
set.seed(3) ; fit.mult <- multi.split(x, y)
suppressWarnings(RNGversion("3.5.0"))
set.seed(3) ; fit.tmp <- multi.split(x, y, verbose = TRUE)
stopifnot(all.equal(fit.mult$pval.corr,c(2.19211217621905e-10, 2.63511914584751e-08, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1)))
stopifnot(all.equal(fit.mult$lci, c(0.845556485400509, 0.592654394654161, -Inf, -Inf, -0.559330600307058,
-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf,
-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -0.494058185775476,
-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -0.935987254184296,
-0.686212365897482, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf,
-Inf, -0.477928536514776, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf,
-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf,
-Inf, -Inf, -Inf, -0.740160526334972, -Inf, -Inf, -Inf, -0.558056531182565,
-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf,
-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -0.476688695088987,
-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -0.353795495366226,
-Inf)))
stopifnot(all.equal(fit.mult$uci, c(1.48387111041928, 1.26688746702801, Inf, Inf, 0.919205974134296,
Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf,
Inf, Inf, Inf, Inf, Inf, Inf, Inf, 0.64068728225218, Inf, Inf,
Inf, Inf, Inf, Inf, Inf, 0.782508357141595, 0.549789868734234,
Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, 0.624958772229364, Inf,
Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf,
Inf, Inf, Inf, Inf, Inf, Inf, 0.221415168229707, Inf, Inf, Inf,
0.545315747796322, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf,
Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, 0.701205415738981,
Inf, Inf, Inf, Inf, Inf, Inf, Inf, 0.637286715741768, Inf)))
|
"sim.Krig" <- function(object, xp, M = 1,
verbose = FALSE, ...) {
tau2 <- object$best.model[2]
sigma <- object$best.model[3]
if (any(duplicated(xp))) {
stop(" predictions locations should be unique")
}
m <- nrow(xp)
n <- nrow(object$xM)
N <- length(object$y)
if (verbose) {
cat(" m,n,N", m, n, N, fill = TRUE)
}
xc <- object$transform$x.center
xs <- object$transform$x.scale
xpM <- scale(xp, xc, xs)
x <- rbind(object$xM, xpM)
if (verbose) {
cat("full x ", fill = TRUE)
print(x)
}
rep.x.info <- fields.duplicated.matrix(x)
x <- as.matrix(x[!duplicated(rep.x.info), ])
if (verbose) {
cat("full x without duplicates ", fill = TRUE)
print(x)
}
N.full <- nrow(x)
if (verbose) {
cat("N.full", N.full, fill = TRUE)
}
xp.ind <- rep.x.info[(1:m) + n]
if (verbose) {
print(N.full)
print(x)
}
if (verbose) {
cat("reconstruction of xp from collapsed locations",
fill = TRUE)
print(x[xp.ind, ])
}
Sigma <- sigma * do.call(object$cov.function.name, c(object$args,
list(x1 = x, x2 = x)))
Schol <- do.call("chol", c(list(x = Sigma), object$chol.args))
N.full <- nrow(x)
out <- matrix(NA, ncol = m, nrow = M)
h.hat <- predict(object, xp, ...)
temp.sd <- 1
if (object$correlation.model) {
if (!is.na(object$sd.obj[1])) {
temp.sd <- predict(object$sd.obj, x)
}
}
W2i <- Krig.make.Wi(object)$W2i
for (k in 1:M) {
h <- t(Schol) %*% rnorm(N.full)
h.data <- h[1:n]
h.data <- h.data[object$rep.info]
y.synthetic <- h.data + sqrt(tau2) * W2i %d*% rnorm(N)
h.true <- (h[xp.ind])
temp.error <- predict(object, xp, y = y.synthetic, eval.correlation.model = FALSE, ...) -
h.true
out[k, ] <- h.hat + temp.error * temp.sd
}
out
} |
"predict.emaxsimB" <-
function(object,dose, dref=0, ...){
warning(paste("\nPredicted values for doses included in the study\n",
"can be obtained from the fitpredv and associated\n",
"standard errors sepredv, sedifv, stored in the emaxsimB\n",
"object. For other doses, emaxsimB must be re-run and\n",
"the predicted values computed using custom code.\n",sep=''))
return(invisible())
} |
context("UNIV_LOG_REG")
set.seed(SEED)
options(bigstatsr.downcast.warning = FALSE)
expect_warning(expect_message(
gwas <- big_univLogReg(FBM(4, 1, init = 0), c(0, 1, 1, 1))))
expect_true(is.na(gwas$score))
TOL <- 1e-4
N <- 73
M <- 43
x <- matrix(rnorm(N * M, mean = 100, sd = 5), N)
y <- sample(0:1, size = N, replace = TRUE)
covar0 <- matrix(rnorm(N * 3), N)
lcovar <- list(NULL, covar0)
getGLM <- function(X, y, covar, ind = NULL) {
res <- matrix(NA, M, 4)
for (i in 1:M) {
mod <- glm(y ~ cbind(X[, i, drop = FALSE], covar),
family = "binomial", subset = ind,
control = list(epsilon = 1e-10, maxit = 100))
if (mod$converged)
res[i, ] <- summary(mod)$coefficients[2, ]
}
res
}
test_that("numerical problems", {
X <- big_copy(x, type = "double")
covar <- cbind(covar0, x[, 1:5])
expect_warning(expect_message(
mod <- big_univLogReg(X, y, covar.train = covar, ncores = test_cores()),
"For 5 columns"),"For 5 columns")
mod$p.value <- predict(mod, log10 = FALSE)
mat <- as.matrix(mod[, -3])
dimnames(mat) <- NULL
expect_true(all(is.na(mat[1:5, ])))
expect_equal(mat[-(1:5), ], getGLM(X, y, covar)[-(1:5), ], tolerance = TOL)
covar2 <- cbind(covar, x[, 1])
expect_error(
big_univLogReg(X, y, covar.train = covar2, ncores = test_cores()),
"'covar.train' is singular.", fixed = TRUE)
})
test_that("equality with glm with all data", {
for (t in TEST.TYPES) {
X <- `if`(t == "raw", asFBMcode(x), big_copy(x, type = t))
for (covar in lcovar) {
mod <- big_univLogReg(X, y, covar.train = covar, ncores = test_cores())
mod$p.value <- predict(mod, log10 = FALSE)
mat <- as.matrix(mod[, -3])
dimnames(mat) <- NULL
expect_equal(mat, getGLM(X, y, covar), tolerance = TOL)
p <- plot(mod, type = sample(c("Manhattan", "Q-Q", "Volcano"), 1))
expect_s3_class(p, "ggplot")
expect_error(predict(mod, abc = 2), "Argument 'abc' not used.")
expect_error(plot(mod, abc = 2), "Argument 'abc' not used.")
}
}
})
test_that("equality with glm with only half the data", {
ind <- sample(N, N / 2)
while (mean(y[ind]) < 0.2 || mean(y[ind]) > 0.8) {
ind <- sample(N, N / 2)
}
for (t in TEST.TYPES) {
X <- `if`(t == "raw", asFBMcode(x), big_copy(x, type = t))
for (covar in lcovar) {
mod <- big_univLogReg(X, y[ind],
covar.train = covar[ind, ],
ind.train = ind,
ncores = test_cores())
mod$p.value <- predict(mod, log10 = FALSE)
mat <- as.matrix(mod[, -3])
dimnames(mat) <- NULL
expect_equal(mat, getGLM(X, y, covar, ind), tolerance = TOL)
p <- plot(mod, type = sample(c("Manhattan", "Q-Q", "Volcano"), 1))
expect_s3_class(p, "ggplot")
}
}
}) |
hoover <- function (x, ref = NULL, weighting = NULL, output = "HC", na.rm = TRUE)
{
n <- nrow(as.matrix(x))
if ((!is.null(ref)) && (n != nrow(as.matrix((ref))))) {
stop("Frequency and reference distribution differ in length", call. = FALSE)
}
if ((!is.null(weighting)) && (n != nrow(as.matrix((weighting))))) {
stop("Frequency and reference distribution differ in length", call. = FALSE)
}
if ((!is.null(ref)) && (!is.null(weighting)) && (nrow(as.matrix((weighting))) != nrow(as.matrix((ref))))) {
stop("Weighting and reference distribution differ in length", call. = FALSE)
}
hooverworkfile <- matrix (ncol = 7, nrow = n)
hooverworkfile[,1] <- x
if (is.null(ref)) {
hooverworkfile[,2] <- rep(1, n)
}
else {
hooverworkfile[,2] <- ref
}
if (is.null(weighting)) {
hooverworkfile[,3] <- rep(0, n)
}
else {
hooverworkfile[,3] <- weighting
}
hooverworkfile[1:n, 4:7] <- 1
if (na.rm == TRUE) {
hooverworkfile <- hooverworkfile[complete.cases(hooverworkfile),]
n <- nrow (hooverworkfile)
}
hooverworkfile[,4] <- hooverworkfile[,1]/(sum((hooverworkfile[,1]), na.rm = TRUE))
hooverworkfile[,5] <- hooverworkfile[,2]/(sum((hooverworkfile[,2]), na.rm = TRUE))
if (!is.null(weighting)) {
hooverworkfile[,6] <- hooverworkfile[,3]/(sum((hooverworkfile[,3]), na.rm = TRUE))
}
else {
hooverworkfile[,6] <- rep(1, n)
}
colnames (hooverworkfile) <- c("x", "r", "w", "x_shares", "r_shares", "w_shares", "diff_xs_rs")
rownames (hooverworkfile) <- 1:n
hooverworkfile[,7] <- hooverworkfile[,6]*(abs(hooverworkfile[,4]-hooverworkfile[,5]))
x_comp_sum <- sum(hooverworkfile[,7])
HC <- x_comp_sum/2
if (output == "data") {
return(hooverworkfile)
}
else {
return(HC)
}
} |
getMids <-
function(ID, hb, lb, ub, alpha_bound = 10/9){
ID <- as.character(ID)
mids.out <- c()
c.out <- c()
alpha.out <- c()
ID.out <- c()
hb.out <- c()
counter <- 0
for(id in unique(ID)){
use.id <- which(ID == id & hb >0)
open.lb <- which(is.na(lb[use.id])==TRUE)
open.ub <- which(is.na(ub[use.id])==TRUE)
if(length(open.lb)==0&length(open.ub)==0){
mids <- (ub[use.id] + lb[use.id])/2
alpha <- NA
c <- NA
}
if(length(open.lb)>0){
stop('The code is not written to handle left censored data',' current ID is ', id,'\n','\n')
}
if(length(open.ub)>2){
stop('The code is not written to handle more than 1 right censored bin',' current ID is ', id,'\n','\n')
}
if(length(open.ub)==1){
mids<-rep(NA, length(ub[use.id]))
mids[-open.ub]<-(ub[use.id][-open.ub] + lb[use.id][-open.ub])/2
use<-which(hb[use.id]>0)
hb.use<-hb[use.id][use]
lb.use<-lb[use.id][use]
ub.use<-ub[use.id][use]
open.ub.use <- which(is.na(ub.use)==TRUE)
a.num<-log((hb.use[(open.ub.use-1)]+hb.use[open.ub.use])/hb.use[open.ub.use])
a.denom<-log(lb.use[open.ub.use]/lb.use[(open.ub.use-1)])
alpha<-a.num/a.denom
if(length(alpha_bound) == 0){
if(counter == 0){
cat('alpha is unbounded', '\n')
counter <- 1
}
}else{
alpha<-max(alpha, alpha_bound)
}
c = alpha/(alpha - 1)
mids[open.ub]<-lb[use.id][open.ub]*c
}
mids.out <- c(mids.out, mids)
c.out <- c(c.out, c)
alpha.out <- c(alpha.out, alpha)
ID.out <- c(ID.out, ID[use.id])
hb.out <- c(hb.out, hb[use.id])
}
mids.return <- data.frame(ID.out,mids.out,hb.out)
colnames(mids.return) <- c('ID', 'mids', 'hb')
return(list('mids' = mids.return, 'c' = c.out, 'alpha' = alpha.out))
} |
context("gg_miss_case")
dat <- tibble::tribble(
~air, ~wind, ~water, ~month,
-99, NA, 23, 1,
-98, NA, NA, 1,
25, 30, 21, 2,
NA, 99, NA, 2,
23, 40, NA, 2
)
gg_miss_case_plot <- gg_miss_case(dat)
test_that("gg_miss_case_works",{
skip_on_cran()
skip_on_ci()
vdiffr::expect_doppelganger("gg_miss_case",
gg_miss_case_plot)
})
gg_miss_case_plot_group <- gg_miss_case(dat, facet = month)
test_that("gg_miss_case_group_works",{
skip_on_cran()
skip_on_ci()
vdiffr::expect_doppelganger("gg_miss_case_group",
gg_miss_case_plot_group)
})
gg_miss_case_plot_sort <- gg_miss_case(dat, order_cases = TRUE)
test_that("gg_miss_case_sort_works",{
skip_on_cran()
skip_on_ci()
vdiffr::expect_doppelganger("gg_miss_case_sort",
gg_miss_case_plot_sort)
})
gg_miss_case_plot_order_group_sort <- gg_miss_case(dat,
facet = month,
order_cases = TRUE)
test_that("gg_miss_case_group_and_sort_works",{
skip_on_cran()
skip_on_ci()
vdiffr::expect_doppelganger("gg_miss_case_group_and_sort",
gg_miss_case_plot_order_group_sort)
})
gg_miss_case_plot_show_pct <- gg_miss_case(dat, show_pct = TRUE)
test_that("gg_miss_case_show_pct_works",{
skip_on_cran()
skip_on_ci()
vdiffr::expect_doppelganger("gg_miss_case_plot_show_pct",
gg_miss_case_plot_show_pct)
})
gg_miss_case_plot_group_show_pct <- gg_miss_case(dat,
facet = month,
show_pct = TRUE)
test_that("gg_miss_case_group_works_show_pct",{
skip_on_cran()
skip_on_ci()
vdiffr::expect_doppelganger("gg_miss_case_group_show_pct",
gg_miss_case_plot_group_show_pct)
})
gg_miss_case_plot_sort_show_pct <- gg_miss_case(dat,
order_cases = TRUE,
show_pct = TRUE)
test_that("gg_miss_case_sort_works_show_pct",{
skip_on_cran()
skip_on_ci()
vdiffr::expect_doppelganger("gg_miss_case_sort_show_pct",
gg_miss_case_plot_sort_show_pct)
})
gg_miss_case_plot_order_group_sort_show_pct <- gg_miss_case(dat,
facet = month,
order_cases = TRUE,
show_pct = TRUE)
test_that("gg_miss_case_group_and_sort_works_show_pct",{
skip_on_cran()
skip_on_ci()
vdiffr::expect_doppelganger("gg_miss_case_group_and_sort_show_pct",
gg_miss_case_plot_order_group_sort_show_pct)
}) |
'.areaIncrement' <- function(x,dist=NA,mul=1,verbose=FALSE)
{
if (!is.ursa(x))
return(NULL)
sparse <- attr(x$value,"sparse")
if ((!is.null(sparse))&&(any(na.omit(sparse)!=0)))
stop("TODO: expand compression")
if (!is.na(x$con$posZ))
{
nb <- length(x$con$posZ)
bn <- x$name[x$con$posZ]
}
else
{
nb <- x$dim[2]
bn <- x$name
}
if (any(is.na(dist)))
dist <- with(x$grid,c(resx,resy))
else if (length(dist)==1)
dist <- rep(dist,2)
else if (length(dist)!=2)
stop("unrecognized argument 'dist'")
dimx <- with(x$grid,c(columns,rows,nb))
x$value <- (.Cursa("areaIncrement",x=as.numeric(x$value),dim=as.integer(dimx)
,res=as.numeric(dist),out=numeric(prod(dimx))
,NAOK=TRUE)$out-1)*mul
dim(x$value) <- with(x$grid,c(columns*rows,nb))
x
} |
sobolowen <- function(model = NULL, X1, X2, X3, nboot = 0, conf = 0.95, varest = 2, ...) {
if ((ncol(X1) != ncol(X2)) | (nrow(X1) != nrow(X2)) | (ncol(X2) != ncol(X3)) | (nrow(X2) != nrow(X3)))
stop("The samples X1, X2 and X3 must have the same dimensions")
p <- ncol(X1)
X <- rbind(X1, X2)
for (i in 1:p) {
Xb <- X1
Xb[,i] <- X3[,i]
X <- rbind(X, Xb)
}
for (i in 1:p) {
Xb <- X2
Xb[,i] <- X1[,i]
X <- rbind(X, Xb)
}
for (i in 1:p) {
Xb <- X3
Xb[,i] <- X2[,i]
X <- rbind(X, Xb)
}
x <- list(model = model, X1 = X1, X2 = X2, X3 = X3, nboot = nboot, conf = conf, X = X,
call = match.call())
class(x) <- "sobolowen"
if (!is.null(x$model)) {
response(x, ...)
tell(x,varest=varest)
}
return(x)
}
estim.sobolowen <- function(data, i=1:nrow(data), varest=2) {
d <- as.matrix(data[i, ])
n <- nrow(d)
p <- (ncol(d)-2)/3
if (varest==1) {
V <- var(d[, 1])
} else {
V <- numeric(0)
for (k in 1:p) {
V[k] <- mean(apply(d[,c(1,2,2+k,2+k+p)]^2,1,mean))-(mean(apply(d[,c(1,2,2+k,2+k+p)],1,mean)))^2
}
}
VCE <- (colSums((d[,1] - d[, 3:(2+p)])*(d[, (3+p):(2+2*p)] - d[,2])) / n)
VCE.compl <- V - (colSums((d[,2] - d[, (3+2*p):(2+3*p)])*(d[, (3+p):(2+2*p)] - d[,1])) / n)
c(V, VCE, VCE.compl)
}
tell.sobolowen <- function(x, y = NULL, return.var = NULL, varest=2, ...) {
id <- deparse(substitute(x))
if (! is.null(y)) {
x$y <- y
} else if (is.null(x$y)) {
stop("y not found")
}
p <- ncol(x$X1)
n <- nrow(x$X1)
data <- matrix(x$y, nrow = n)
if (x$nboot == 0){
V <- data.frame(original = estim.sobolowen(data,varest=varest))
}
else{
func <- function(data,i) {estim.sobolowen(data,i,varest)}
V.boot <- boot(data=data, statistic=func, R = x$nboot)
V <- bootstats(V.boot, x$conf, "basic")
}
rownames(V) <- c(paste("global",colnames(x$X1)), colnames(x$X1), paste("-", colnames(x$X1), sep = ""))
if (varest==1) {
k <- 1
} else {
k <- p
}
if (x$nboot == 0) {
S <- V[(k + 1):(p + k), 1, drop = FALSE] / V[1:k,1]
T <- V[(p + k + 1):(2 * p + k), 1, drop = FALSE] / V[1:k,1]
} else {
S.boot <- V.boot
S.boot$t0 <- V.boot$t0[(k+1):(p + k)] / V.boot$t0[1:k]
S.boot$t <- V.boot$t[,(k+1):(p + k)] / V.boot$t[,(1:k)]
S <- bootstats(S.boot, x$conf, "basic")
T.boot <- V.boot
T.boot$t0 <- V.boot$t0[(p + k + 1):(2 * p + k)] / V.boot$t0[1:k]
T.boot$t <- V.boot$t[,(p + k + 1):(2 * p + k)] / V.boot$t[,(1:k)]
T <- bootstats(T.boot, x$conf, "basic")
}
rownames(S) <- colnames(x$X1)
rownames(T) <- colnames(x$X1)
x$V <- V
x$S <- S
x$T <- T
for (i in return.var) {
x[[i]] <- get(i)
}
assign(id, x, parent.frame())
}
print.sobolowen <- function(x, ...) {
cat("\nCall:\n", deparse(x$call), "\n", sep = "")
if (!is.null(x$y)) {
cat("\nModel runs:", length(x$y), "\n")
cat("\nFirst order indices:\n")
print(x$S)
cat("\nTotal indices:\n")
print(x$T)
}
}
plot.sobolowen <- function(x, ylim = c(0, 1), ...) {
if (!is.null(x$y)) {
p <- ncol(x$X1)
pch = c(21, 24)
nodeplot(x$S, xlim = c(1, p + 1), ylim = ylim, pch = pch[1])
nodeplot(x$T, xlim = c(1, p + 1), ylim = ylim, labels = FALSE,
pch = pch[2], at = (1:p)+.3, add = TRUE)
legend(x = "topright", legend = c("main effect", "total effect"), pch = pch)
}
}
ggplot.sobolowen <- function(x, ylim = c(0, 1), ...) {
if (!is.null(x$y)) {
p <- ncol(x$X1)
pch = c(21, 24)
nodeggplot(listx = list(x$S,x$T), xname = c("Main effet","Total effect"), ylim = ylim, pch = pch)
}
} |
NULL
omega_root <- function(x=0.5,p0_v1=0.5,p0_v2=0.5,p00=p0_v1*p0_v2,correlation=NA) {
if (is.na(correlation)) {
out <- p00-omega(x,p0_v1=p0_v1,p0_v2=p0_v2,correlation=FALSE)
} else {
out <- correlation-omega(x,p0_v1=p0_v1,p0_v2=p0_v2,correlation=TRUE)
}
return(out)
} |
ui.file_upload <- function(id, test = FALSE) {
ns <- NS(id)
wPanel <- wellPanel(
fileInput(ns("upload_file"), "Choose CSV File",
multiple = FALSE,
accept = c(
"text/csv",
"text/comma-separated-values,text/plain",
".csv"
)
),
tags$hr(),
checkboxInput(ns("header"), "Header", TRUE),
radioButtons(ns("sep"), "Separator",
choices = c(
Comma = ",",
Semicolon = ";",
Tab = "\t"
),
selected = ","
),
radioButtons(ns("quote"), "Quote",
choices = c(
None = "",
"Double Quote" = '"',
"Single Quote" = "'"
),
selected = '"'
),
tags$hr(),
radioButtons(ns("disp"), "Display",
choices = c(
Head = "head",
All = "all"
),
selected = "head"
)
)
if (test) {
fluidPage(
titlePanel("Module: Upload File (here for testing only)"),
sidebarLayout(
sidebarPanel = sidebarPanel(
wPanel
),
mainPanel = mainPanel(
tableOutput(ns("contents"))
)
)
)
} else {
wPanel
}
}
server.file_upload <- function(input, output, session) {
userFile <- reactive({
validate(need(input$upload_file, message = FALSE))
input$upload_file
})
output$contents <- renderTable({
message("rendering table")
tryCatch(
{
df <- read.csv(userFile()$datapath,
header = input$header,
sep = input$sep,
quote = input$quote,
stringsAsFactors = FALSE
)
},
error = function(e) {
stop(safeError(e))
}
)
if (input$disp == "head") {
return(head(df))
}
else {
return(df)
}
})
observe({
msg <- sprintf("File %s was uploaded", userFile()$name)
cat(msg, "\n")
})
} |
output$ui_spatial_blocks<-renderUI({
observeEvent(input$block_button,{
observeEvent(input$number_fold,{
load.occ$k<-input$number_fold
})
observeEvent(input$allocation_fold,{
load.occ$allocation_fold<-input$allocation_fold
})
sp_Specdata<-reactive({
dsf<-load.occ$select
dsf[,load.occ$spec_select]<-as.factor(dsf[,load.occ$spec_select])
dsf<-dsf %>% dplyr::rename(lon=load.occ$lon,lat=load.occ$lat)
dsf
})
sp_pa_data<-reactive({
load.occ$sp_pa_data<-sf::st_as_sf(sp_Specdata(), coords = c("lon","lat"), crs = crs(data$Env))
load.occ$sp_pa_data
})
spatialblock<-reactive({
a = try(withProgress(message = 'Spatial blocking',
blockCV::spatialBlock(speciesData = sp_pa_data(),
species = load.occ$spec_select,
rasterLayer = data$var_auto,
theRange = range(),
k = load.occ$k,
showBlocks = TRUE,
selection = load.occ$allocation_fold,
iteration = 100,
biomod2Format = FALSE,
xOffset = 0,
yOffset = 0)))
if(inherits(a, 'try-error'))
{
output$Envbug_sp <- renderUI(p('Spatial blocking failed, please check your inputs and try again!'))
} else {
output$Envbug_sp <- renderUI(p())
load.occ$spatialblock<-a
a
}
})
output$sp_block<-renderPlot({
spatialblock<-spatialblock()
spatialblock$plots + geom_sf(data = sp_pa_data(), alpha = 0.5)
})
output$sum_fold <- DT::renderDataTable({
spatialblock<-spatialblock()
sumfold<-reactive({
a = try(withProgress(message = 'Summary fold...',
summarise_fold(spatialblock)))
if(inherits(a, 'try-error'))
{
output$Envbug_fold <- renderUI(p('Spatial blocking failed, please check your inputs and try again!'))
} else {
output$Envbug_fold <- renderUI(p())
a
}
})
datatable(sumfold(),
rownames = FALSE,
selection="none",
options = list(scrollX=TRUE, scrollY=250, lengthMenu=list(c(20, 50, 100, -1), c('20', '50', '100', 'All')), pageLength=20)
)})
observeEvent(input$test_fold,{
load.occ$fold<-input$test_fold
output$test_train_plot<-renderPlot({
spatialblock<-spatialblock()
sdmApp::sdmApp_fold_Explorer(spatialblock, data$Env, sp_pa_data(),load.occ$fold)
})
})
})
fluidRow(column(12, h4("Spatial blocking"),p("'The spatial blocking procedure can take a long time depending on the number of input variables"), align="center"),
mainPanel(width = 8, tabsetPanel(type = "tabs",
tabPanel("Spatial blocking",
p('Set spatial bloking parameters'),
sliderInput("number_fold", "folds", min=1, max=100, value=5),
selectInput("allocation_fold","allocation of blocks to folds",choices = c("random","systematic"),selected="random"),
sliderInput("test_fold","Select the number of fold to assign as test dataset",min = 1,max=100,value = 1),
myActionButton("block_button",label=("Apply"), "primary"),
uiOutput("Envbug_sp"),
plotOutput("sp_block"),
plotOutput("test_train_plot")),
tabPanel("Fold summary",
p('The percentage values indicate the percentage of data the test dataset corresponds to'),
uiOutput("Envbug_fold"),
DT::dataTableOutput("sum_fold"))
),
id = "tabs")
)
}) |
github.openzh.covid19 <- function(level, state){
if(state=="FL" & level!=1) return(NULL)
if(state=="CH" & level!=2) return(NULL)
url <- "https://raw.githubusercontent.com/openZH/covid_19/master/COVID19_Fallzahlen_CH_total_v2.csv"
x <- read.csv(url)
x <- map_data(x, c(
'date',
'abbreviation_canton_and_fl' = 'code',
'ncumul_conf' = 'confirmed',
'ncumul_tested' = 'tests',
'ncumul_deceased' = 'deaths',
'ncumul_released' = 'recovered',
'current_hosp' = 'hosp',
'current_icu' = 'icu',
'current_vent' = 'vent'
))
if(state=="FL")
x <- x[which(x$code=="FL"),]
if(state=="CH")
x <- x[which(x$code!="FL"),]
x$date <- as.Date(x$date)
return(x)
} |
suppressPackageStartupMessages(library(rrcovNA))
alpha <- 0.55
data(phosphor); x <- y <- phosphor[,1:2]; x[10,2] <- NA; x[15,1] <- NA
mcdc <- CovMcd(y)
ximp <- impSeq(x); mcds <- CovMcd(ximp)
ximp <- impSeqRob(x, alpha=alpha); mcd <- CovMcd(ximp$x)
mcdna <- CovNAMcd(x)
as.vector(which(mcdc@wt==0))
as.vector(which(mcds@wt==0))
as.vector(which(mcd@wt==0))
as.vector(which(mcdna@wt==0))
data(heart); x <- y <- heart; x[10,2] <- NA; x[2,1] <- NA
mcdc <- CovMcd(y)
ximp <- impSeq(x); mcds <- CovMcd(ximp)
ximp <- impSeqRob(x, alpha=alpha); mcd <- CovMcd(ximp$x)
mcdna <- CovNAMcd(x)
as.vector(which(mcdc@wt==0))
as.vector(which(mcds@wt==0))
as.vector(which(mcd@wt==0))
as.vector(which(mcdna@wt==0))
data(starsCYG); x <- y <- starsCYG; x[10,2] <- NA; x[2,1] <- NA; x[33,1] <- NA; x[41,1] <- NA
mcdc <- CovMcd(y)
ximp <- impSeq(x); mcds <- CovMcd(ximp)
ximp <- impSeqRob(x, alpha=alpha); mcd <- CovMcd(ximp$x)
mcdna <- CovNAMcd(x)
as.vector(which(mcdc@wt==0))
as.vector(which(mcds@wt==0))
as.vector(which(mcd@wt==0))
as.vector(which(mcdna@wt==0))
data(stackloss); x <- y <- stack.x; x[10,2] <- NA; x[6,1] <- NA; x[13,3] <- NA
mcdc <- CovMcd(y)
ximp <- impSeq(x); mcds <- CovMcd(ximp)
ximp <- impSeqRob(x, alpha=alpha); mcd <- CovMcd(ximp$x)
mcdna <- CovNAMcd(x)
as.vector(which(mcdc@wt==0))
as.vector(which(mcds@wt==0))
as.vector(which(mcd@wt==0))
as.vector(which(mcdna@wt==0))
data(coleman); x <- y <- data.matrix(subset(coleman, select = -Y)); x[5,2] <- NA; x[8,4] <- NA; x[13,3] <- NA
mcdc <- CovMcd(y)
ximp <- impSeq(x); mcds <- CovMcd(ximp)
ximp <- impSeqRob(x, alpha=alpha); mcd <- CovMcd(ximp$x)
mcdna <- CovNAMcd(x)
data(salinity); x <- y <- data.matrix(subset(salinity, select = -Y)); x[1,2] <- NA; x[8,3] <- NA; x[13,3] <- NA
mcdc <- CovMcd(y)
ximp <- impSeq(x); mcds <- CovMcd(ximp)
ximp <- impSeqRob(x, alpha=alpha); mcd <- CovMcd(ximp$x)
mcdna <- CovNAMcd(x)
as.vector(which(mcdc@wt==0))
as.vector(which(mcds@wt==0))
as.vector(which(mcd@wt==0))
as.vector(which(mcdna@wt==0))
data(wood); x <- y <- data.matrix(subset(wood, select = -y)); x[1,2] <- NA; x[10,3] <- NA; x[13,4] <- NA
mcdc <- CovMcd(y)
ximp <- impSeq(x); mcds <- CovMcd(ximp)
ximp <- impSeqRob(x, alpha=alpha); mcd <- CovMcd(ximp$x)
mcdna <- CovNAMcd(x)
as.vector(which(mcdc@wt==0))
as.vector(which(mcds@wt==0))
as.vector(which(mcd@wt==0))
as.vector(which(mcdna@wt==0))
data(hbk); x <- y <- data.matrix(subset(hbk, select = -Y)); x[30,2] <- NA; x[40,3] <- NA; x[17,3] <- NA
mcdc <- CovMcd(y)
ximp <- impSeq(x); mcds <- CovMcd(ximp)
ximp <- impSeqRob(x, alpha=alpha); mcd <- CovMcd(ximp$x)
mcdna <- CovNAMcd(x)
as.vector(which(mcdc@wt==0))
as.vector(which(mcds@wt==0))
as.vector(which(mcd@wt==0))
as.vector(which(mcdna@wt==0)) |
NormTransformation <-
function(data)
{
data.normal=2*sqrt(data+0.25)
} |
ggwr <- function(formula, data = list(), coords, bandwidth,
gweight=gwr.Gauss, adapt=NULL, fit.points, family=gaussian,
longlat=NULL, type=c("working", "deviance", "pearson", "response")) {
type <- match.arg(type)
resid_name <- paste(type, "resids", sep="_")
this.call <- match.call()
p4s <- as.character(NA)
Polys <- NULL
if (is(data, "SpatialPolygonsDataFrame"))
Polys <- as(data, "SpatialPolygons")
if (is(data, "Spatial")) {
if (!missing(coords))
warning("data is Spatial* object, ignoring coords argument")
coords <- coordinates(data)
p4s <- proj4string(data)
if (is.null(longlat) || !is.logical(longlat)) {
if (!is.na(is.projected(data)) && !is.projected(data)) {
longlat <- TRUE
} else {
longlat <- FALSE
}
}
data <- as(data, "data.frame")
}
if (is.null(longlat) || !is.logical(longlat)) longlat <- FALSE
if (missing(coords))
stop("Observation coordinates have to be given")
if (is.null(colnames(coords)))
colnames(coords) <- c("coord.x", "coord.y")
if (is.character(family))
family <- get(family, mode = "function", envir = parent.frame())
if (is.function(family)) family <- family()
if (is.null(family$family)) {
print(family)
stop("'family' not recognized")
}
if (missing(data)) data <- environment(formula)
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data"), names(mf), 0)
mf <- mf[c(1, m)]
mf$drop.unused.levels <- TRUE
mf[[1]] <- as.name("model.frame")
mf <- eval(mf, parent.frame())
mt <- attr(mf, "terms")
y <- model.extract(mf, "response")
x <- model.matrix(mt, mf)
offset <- model.offset(mf)
if (!is.null(offset) && length(offset) != NROW(y))
stop("number of offsets should equal number of observations")
if (is.null(offset)) offset <- rep(0, length(c(y)))
glm_fit <- glm.fit(x=x, y=y, offset=offset, family=family)
if (missing(fit.points)) {
fp.given <- FALSE
fit.points <- coords
colnames(fit.points) <- colnames(coords)
} else fp.given <- TRUE
griddedObj <- FALSE
if (is(fit.points, "Spatial")) {
Polys <- NULL
if (is(fit.points, "SpatialPolygonsDataFrame")) {
Polys <- Polygons(fit.points)
fit.points <- coordinates(fit.points)
} else {
griddedObj <- gridded(fit.points)
fit.points <- coordinates(fit.points)
}
}
n <- NROW(fit.points)
rownames(fit.points) <- NULL
if (is.null(colnames(fit.points))) colnames(fit.points) <- c("x", "y")
m <- NCOL(x)
if (NROW(x) != NROW(coords))
stop("Input data and coordinates have different dimensions")
if (is.null(adapt)) {
if (!missing(bandwidth)) {
bw <- bandwidth
bandwidth <- rep(bandwidth, n)
} else stop("Bandwidth must be given for non-adaptive weights")
} else {
bandwidth <- gw.adapt(dp=coords, fp=fit.points, quant=adapt,
longlat=longlat)
bw <- bandwidth
}
if (any(bandwidth < 0)) stop("Invalid bandwidth")
gwr.b <- matrix(nrow=n, ncol=m)
v_resids <- numeric(n)
colnames(gwr.b) <- colnames(x)
lhat <- NA
sum.w <- numeric(n)
dispersion <- numeric(n)
for (i in 1:n) {
dxs <- spDistsN1(coords, fit.points[i,], longlat=longlat)
if (any(!is.finite(dxs)))
dxs[which(!is.finite(dxs))] <- .Machine$double.xmax/2
w.i <- gweight(dxs^2, bandwidth[i])
if (any(w.i < 0 | is.na(w.i)))
stop(paste("Invalid weights for i:", i))
lm.i <- glm.fit(y=y, x=x, weights=w.i, offset=offset,
family=family)
sum.w[i] <- sum(w.i)
gwr.b[i,] <- coefficients(lm.i)
if (!fp.given) v_resids[i] <- residuals.glm(lm.i, type=type)[i]
else is.na(v_resids[i]) <- TRUE
df.r <- lm.i$df.residual
if (lm.i$family$family %in% c("poisson", "binomial"))
dispersion[i] <- 1
else {
if (df.r > 0) {
dispersion[i] <- sum((lm.i$weights *
lm.i$residuals^2)[lm.i$weights > 0])/df.r
} else {
dispersion[i] <- NaN
}
}
}
df <- data.frame(sum.w=sum.w, gwr.b, dispersion=dispersion)
df[[resid_name]] <- v_resids
SDF <- SpatialPointsDataFrame(coords=fit.points,
data=df, proj4string=CRS(p4s))
if (griddedObj) {
gridded(SDF) <- TRUE
} else {
if (!is.null(Polys)) {
df <- data.frame(SDF@data)
rownames(df) <- sapply(slot(Polys, "polygons"),
function(i) slot(i, "ID"))
SDF <- SpatialPolygonsDataFrame(Sr=Polys, data=df)
}
}
z <- list(SDF=SDF, lhat=lhat, lm=glm_fit, results=NULL,
bandwidth=bw, adapt=adapt, hatmatrix=FALSE,
gweight=deparse(substitute(gweight)), fp.given=fp.given,
this.call=this.call)
class(z) <- "gwr"
invisible(z)
} |
test_that("dryad_download", {
skip_on_cran()
skip_on_ci()
vcr::use_cassette("dryad_download", {
aa <- dryad_download(dois = "10.5061/dryad.f385721n")
}, match_requests_on = c("method", "uri"))
expect_is(aa, "list")
expect_equal(length(aa), 1)
expect_named(aa, "10.5061/dryad.f385721n")
expect_is(aa[[1]], "character")
expect_true(any(grepl("csv", aa[[1]])))
expect_true(any(grepl("rtf", aa[[1]])))
})
test_that("dryad_download fails well", {
skip_on_cran()
expect_error(dryad_download())
expect_error(dryad_download(5))
}) |
is.gdpc <- function(object, ...) {
if (any(!inherits(object, "list"), !inherits(object, "gdpc"))) {
return(FALSE)
} else if (any(is.null(object$f), is.null(object$initial_f), is.null(object$beta),
is.null(object$alpha), is.null(object$mse), is.null(object$crit),
is.null(object$k), is.null(object$expart), is.null(object$call),
is.null(object$conv), is.null(object$niter))) {
return(FALSE)
} else if (any(!inherits(object$mse, "numeric"), !inherits(object$crit, "numeric"), !inherits(object$alpha, "numeric"),
!inherits(object$beta, "matrix"), !inherits(object$call, "call"), !inherits(object$conv, "logical"),
all(!inherits(object$f,"numeric"), !inherits(object$f, "ts"), !inherits(object$f, "xts"), !inherits(object$f, "zoo")),
all(!inherits(object$k, "numeric"), !inherits(object$k, "integer")), !inherits(object$expart, "numeric"),
all(!inherits(object$initial_f,"numeric"), !inherits(object$initial_f,"ts"), !inherits(object$initial_f,"xts"),
!inherits(object$initial_f, "zoo"))
)) {
return(FALSE)
} else if (any(length(object$alpha) != dim(object$beta)[1], dim(object$beta)[2] != object$k + 1)) {
return(FALSE)
} else {
return(TRUE)
}
}
construct.gdpc <- function(out, data) {
k <- ncol(out$beta) - 2
out$alpha <- out$beta[, k + 2]
out$beta <- out$beta[, (k + 1):1]
if (k != 0) {
out$initial_f <- out$f[1:k]
} else {
out$initial_f <- 0
}
out$alpha <- as.numeric(out$alpha)
out$beta <- as.matrix(out$beta)
rownames(out$beta) <- colnames(data)
out$f <- out$f[(k + 1):length(out$f)]
out$res <- NULL
if (inherits(data, "xts")) {
out$f <- reclass(out$f, match.to = data)
} else if (inherits(data, "zoo")) {
out$f <- zoo(out$f, order.by = index(data))
} else if (inherits(data, "ts")) {
out$f <- ts(out$f, start = start(data), end = end(data), frequency = frequency(data))
}
class(out) <- append("gdpc", class(out))
return(out)
}
construct.gdpc.norm <- function(out, data, comp_num) {
k <- ncol(out$beta) - 2
out$alpha <- out$beta[, k + 2]
out$beta <- out$beta[, (k + 1):1]
if (k != 0) {
out$initial_f <- out$f[1:k]
} else {
out$initial_f <- 0
}
sd_Z <- apply(data, 2, sd)
if (comp_num == 1){
mean_Z <- apply(data, 2, mean)
} else {
mean_Z <- 0
}
out$alpha <- out$alpha * sd_Z + mean_Z
if (k == 0) {
out$beta <- out$beta * sd_Z
} else {
out$beta <- apply(out$beta, 2, function(x, sd) { x * sd }, sd_Z)
}
out$alpha <- as.numeric(out$alpha)
out$beta <- as.matrix(out$beta)
rownames(out$beta) <- colnames(data)
out$f <- out$f[(k + 1):length(out$f)]
if (inherits(data, "xts")) {
out$f <- reclass(out$f, match.to = data)
} else if (inherits(data, "zoo")) {
out$f <- zoo(out$f, order.by = index(data))
} else if (inherits(data, "ts")) {
out$f <- ts(out$f, start = start(data), end = end(data), frequency = frequency(data))
}
class(out) <- append("gdpc", class(out))
return(out)
}
fitted.gdpc <- function(object, ...) {
if (!is.gdpc(object)){
stop("object should be of class gdpc")
}
fitted <- getFitted(object$f, object$initial_f, object$beta, object$alpha, object$k)
if (inherits(object$f, "xts")) {
fitted <- reclass(fitted, match.to = object$f)
} else if (inherits(object$f, "zoo")) {
fitted <- zoo(fitted, order.by = index(object$f))
} else if (inherits(object$f, "ts")) {
fitted <- ts(fitted)
attr(fitted, "tsp") <- attr(object$f, "tsp")
}
return(fitted)
}
plot.gdpc <- function(x, which = "Component", which_load = 0, ...) {
if (!is.gdpc(x)) {
stop("x should be of class gdpc")
}
if (!which %in% c("Component", "Loadings")) {
stop("which should be either Component or Loadings ")
}
if (!inherits(which_load, "numeric")) {
stop("which_load should be numeric")
} else if (any(!(which_load == floor(which_load)), which_load < 0, which_load > ncol(x$beta) - 1)) {
stop("which_load should be a non-negative integer, at most equal to the number of lags")
}
if (which == "Component"){
plot(x$f, type = "l", main = "Principal Component", ...)
} else if (which == "Loadings"){
plot(x$beta[, which_load + 1], type = "l", main = c(paste(which_load, "lag loadings")), ...)
}
}
print.gdpc <- function(x, ...) {
if (!is.gdpc(x)) {
stop("x should be of class gdpc")
}
y <- list(x)
class(y) <- append("gdpcs", class(y))
print(y)
}
construct.gdpcs <- function(out, data, fn_call, normalize) {
if (normalize == 2) {
num_comp <- length(out)
out[[1]] <- construct.gdpc.norm(out[[1]], data, 1)
if (num_comp > 1) {
for (k in 2:num_comp) {
out[[k]] <- construct.gdpc.norm(out[[k]], data, k)
}
}
out <- lapply(out, function(x, fn_call){ x$call <- fn_call; return(x)}, fn_call)
out <- lapply(out, function(x){ x$res <- NULL; return(x)})
} else {
out <- lapply(out, function(x, fn_call){ x$call <- fn_call; return(x)}, fn_call)
out <- lapply(out, construct.gdpc, data)
}
class(out) <- append("gdpcs", class(out))
return(out)
}
is.gdpcs <- function(object, ...) {
if (any(!inherits(object, "gdpcs"), !inherits(object, "list"))) {
return(FALSE)
} else {
return(all(sapply(object, is.gdpc)))
}
}
components <- function(object, which_comp){
UseMethod("components", object)
}
components.gdpcs <- function(object, which_comp = 1) {
if (!is.gdpcs(object)) {
stop("object should be of class gdpcs")
}
if (all(!inherits(which_comp, "numeric"), !inherits(which_comp, "integer"))) {
stop("which_comp should be numeric")
} else if (any(!(which_comp == floor(which_comp)), which_comp <= 0, which_comp > length(object))) {
stop("The entries of which_comp should be positive integers, at most equal to the number of components")
}
object <- object[which_comp]
comps <- sapply(object, function(object){ object$f })
colnames(comps) <- paste("Component number", which_comp)
if (inherits(object[[1]]$f, "xts")) {
comps <- reclass(comps, match.to = object[[1]]$f)
} else if (inherits(object[[1]]$f, "zoo")) {
comps <- zoo(comps, order.by = index(object[[1]]$f))
} else if (inherits(object[[1]]$f, "ts")) {
comps <- ts(comps, start = start(object[[1]]$f), end = end(object[[1]]$f), frequency = frequency(object[[1]]$f))
}
return(comps)
}
fitted.gdpcs <- function(object, num_comp = 1, ...) {
if (!is.gdpcs(object)) {
stop("object should be of class gdpcs")
}
if (all(!inherits(num_comp, "numeric"), !inherits(num_comp, "integer"))) {
stop("num_comp should be numeric")
} else if (any(!(num_comp == floor(num_comp)), num_comp <= 0, num_comp > length(object))) {
stop("num_comp should be a positive integer, at most equal to the number of components")
}
fitted <- Reduce('+', lapply(object[1:num_comp], fitted))
if (inherits(object[[1]]$f, "xts")) {
fitted <- reclass(fitted, match.to = object[[1]]$f)
} else if (inherits(object[[1]]$f, "zoo")) {
fitted <- zoo(fitted, order.by = index(object[[1]]$f))
} else if (inherits(object[[1]]$f, "ts")) {
fitted <- ts(fitted)
attr(fitted, "tsp") <- attr(object[[1]]$f, "tsp")
}
return(fitted)
}
plot.gdpcs <- function(x, which_comp = 1, plot.type = 'multiple',...) {
if (!is.gdpcs(x)) {
stop("x should be of class gdpcs")
}
if (all(!inherits(which_comp, "numeric"), !inherits(which_comp, "integer"))) {
stop("which_comp should be numeric")
} else if (any(!(which_comp == floor(which_comp)), which_comp <= 0, which_comp > length(x))) {
stop("The entries of which_comp should be positive integers, at most equal to the number of components")
}
comps <- components(x, which_comp)
if (inherits(comps, "xts") & length(which_comp)==1) {
plot.xts(comps, main = "Principal Components", ...)
} else if (inherits(comps, "zoo")) {
plot.zoo(comps, main = "Principal Components", plot.type = plot.type, ...)
} else if (inherits(comps, "ts")) {
plot.ts(comps, main = "Principal Components", plot.type = 'multiple', ...)
} else {
comps <- ts(comps)
plot.ts(comps, main = "Principal Components", plot.type = 'multiple', ...)
}
}
print.gdpcs <- function(x, ...) {
if (!is.gdpcs(x)) {
stop("x should be of class gdpcs")
}
lags <- sapply(x, function(x){ round(x$k, 3) })
vars <- sapply(x, function(x){ round(x$expart, 3) })
mses <- sapply(x, function(x){ round(x$mse, 3) })
crits <- sapply(x, function(x){ round(x$crit, 3) })
mat <- cbind(lags, crits, mses, vars)
nums <- paste(1:length(x))
nums <- sapply(nums, function(x){ paste("Component", x)})
fn_call <- x[[1]]$call
crit_name <- fn_call$crit
colnames(mat) <- c("Number of lags", crit_name, "MSE", "Explained Variance")
tab <- data.frame(mat, row.names = nums)
print(tab)
} |
expected <- eval(parse(text="2L"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(NA, 87, 82, 75, 63, 50, 43, 32, 35, 60, 54, 55, 36, 39, NA, NA, 69, 57, 57, 51, 45, 37, 46, 39, 36, 24, 32, 23, 25, 32, NA, 32, 59, 74, 75, 60, 71, 61, 71, 57, 71, 68, 79, 73, 76, 71, 67, 75, 79, 62, 63, 57, 60, 49, 48, 52, 57, 62, 61, 66, 71, 62, 61, 57, 72, 83, 71, 78, 79, 71, 62, 74, 76, 64, 62, 57, 80, 73, 69, 69, 71, 64, 69, 62, 63, 46, 56, 44, 44, 52, 38, 46, 36, 49, 35, 44, 59, 65, 65, 56, 66, 53, 61, 52, 51, 48, 54, 49, 49, 61, NA, NA, 68, 44, 40, 27, 28, 25, 24, 24), .Tsp = c(1945, 1974.75, 4), class = \"ts\"))"));
.Internal(which.max(argv[[1]]));
}, o=expected); |
mdt_moderated <- function(data, IV, DV, M, Mod) {
UseMethod("mdt_moderated")
}
mdt_moderated.data.frame <- function(data, IV, DV, M, Mod) {
IV_var <- enquo(IV)
DV_var <- enquo(DV)
M_var <- enquo(M)
Mod_var <- enquo(Mod)
IV_name <- rlang::quo_name(IV_var)
DV_name <- rlang::quo_name(DV_var)
M_name <- rlang::quo_name(M_var)
Mod_name <- rlang::quo_name(Mod_var)
IVMod_name <- glue("{IV_name}:{Mod_name}")
MMod_name <- glue("{M_name}:{Mod_name}")
IV_data <- data %>% dplyr::pull(!!IV_var)
M_data <- data %>% dplyr::pull(!!M_var)
DV_data <- data %>% dplyr::pull(!!DV_var)
Mod_data <- data %>% dplyr::pull(!!Mod_var)
if (!is.numeric(IV_data)) {
stop(glue("Warning:
IV ({IV_name}) must be numeric (see build_contrast() to
convert a character vector to a contrast code)."))
}
if(!is.numeric(M_data)) {
stop(glue("Warning:
Mediator ({M_name}) must be numeric."))
}
if(!is.numeric(DV_data)) {
stop(glue("Warning:
DV ({DV_name}) must be numeric."))
}
if(!is.numeric(Mod_data)) {
stop(glue("Warning:
Moderator ({DV_name}) must be numeric."))
}
model1 <-
stats::as.formula(glue("{DV} ~ {IV} * {Mod}",
IV = IV_name,
DV = DV_name,
Mod = Mod_name))
model2 <-
stats::as.formula(glue("{M} ~ {IV} * {Mod}",
IV = IV_name,
M = M_name,
Mod = Mod_name))
model3 <-
stats::as.formula(glue("{DV} ~ ({IV} + {M}) * {Mod}",
DV = DV_name,
IV = IV_name,
M = M_name,
Mod = Mod_name))
js_models <-
list("X * Mod -> Y" = model1,
"X * Mod -> M" = model2,
"(X + M) * Mod -> Y" = model3) %>%
purrr::map(~lm(.x, data))
paths <-
list("a" = create_path(js_models, "X * Mod -> M", IV_name),
"a * Mod" = create_path(js_models, "X * Mod -> M", IVMod_name),
"b" = create_path(js_models, "(X + M) * Mod -> Y", M_name),
"b * Mod" = create_path(js_models, "(X + M) * Mod -> Y", MMod_name),
"c" = create_path(js_models, "X * Mod -> Y", IV_name),
"c * Mod" = create_path(js_models, "X * Mod -> Y", IVMod_name),
"c'" = create_path(js_models, "(X + M) * Mod -> Y", IV_name),
"c' * Mod" = create_path(js_models, "(X + M) * Mod -> Y", IVMod_name))
mediation_model(
type = "moderated mediation",
params = list("IV" = IV_name,
"DV" = DV_name,
"M" = M_name,
"Mod" = Mod_name),
paths = paths,
js_models = js_models,
data = data,
subclass = "moderated_mediation"
)
} |
.rasterObjectFromFile <- function(x, band=1, objecttype='RasterLayer', native=FALSE, silent=TRUE, offset=NULL, ncdf=FALSE, ...) {
x <- trim(x)
if (x=="" | x==".") {
stop('provide a valid filename')
}
start <- tolower(substr(x, 1, 3))
if (! start %in% c('htt', 'ftp')) {
y <- NULL
try( y <- normalizePath( x, mustWork=TRUE), silent=TRUE )
if (! is.null(y)) {
x <- y
}
}
fileext <- toupper(extension(x))
if (fileext %in% c(".GRD", ".GRI")) {
grifile <- .setFileExtensionValues(x, 'raster')
grdfile <- .setFileExtensionHeader(x, 'raster')
if ( file.exists( grdfile) & file.exists( grifile)) {
return ( .rasterFromRasterFile(grdfile, band=band, objecttype, ...) )
}
}
if (! file.exists(x) ) {
if (extension(x) == '') {
grifile <- .setFileExtensionValues(x, 'raster')
grdfile <- .setFileExtensionHeader(x, 'raster')
if ( file.exists( grdfile) & file.exists( grifile)) {
return ( .rasterFromRasterFile(grdfile, band=band, objecttype, ...) )
} else {
}
}
}
if (( fileext %in% c(".HE5", ".NC", ".NCF", ".NC4", ".CDF", ".NCDF", ".NETCDF")) | (isTRUE(ncdf))) {
return ( .rasterObjectFromCDF(x, type=objecttype, band=band, ...) )
}
if ( fileext == ".GRD") {
if (.isNetCDF(x)) {
return ( .rasterObjectFromCDF(x, type=objecttype, band=band, ...) )
}
}
if (!is.null(offset)) {
return ( .rasterFromASCIIFile(x, offset, ...) )
}
if (fileext %in% c(".BIN")) {
r <- .rasterFromNSIDCFile(x)
if (!is.null(r)) return(r)
}
if(!native) {
if (! .requireRgdal(FALSE) ) {
native <- TRUE
}
}
if (native) {
if ( fileext == ".ASC" ) {
return ( .rasterFromASCIIFile(x, ...) )
}
if ( fileext %in% c(".BIL", ".BIP", ".BSQ")) {
return ( .rasterFromGenericFile(x, type=objecttype, ...) )
}
if ( fileext %in% c(".RST", ".RDC") ) {
return ( .rasterFromIDRISIFile(x, ...) )
}
if ( fileext %in% c(".DOC", ".IMG") ) {
return ( .rasterFromIDRISIFile(x, old=TRUE, ...))
}
if ( fileext %in% c(".SGRD", ".SDAT") ) {
return ( .rasterFromSAGAFile(x, ...) )
}
}
if ( fileext == ".DOC" ) {
if (file.exists( extension(x, '.img'))) {
return( .rasterFromIDRISIFile(x, old=TRUE, ...))
}
}
if ( fileext %in% c(".SGRD", ".SDAT") ) {
r <- .rasterFromSAGAFile(x, ...)
if (r@file@toptobottom | r@data@gain != 1) {
return(r)
}
}
if (! .requireRgdal(FALSE) ) {
stop("Cannot create RasterLayer object from this file; perhaps you need to install rgdal first")
}
test <- try( r <- .rasterFromGDAL(x, band=band, objecttype, ...), silent=silent )
if (inherits(test, "try-error")) {
if (!file.exists(x)) {
stop("Cannot create a RasterLayer object from this file. (file does not exist)")
}
stop("Cannot create a RasterLayer object from this file.")
} else {
return(r)
}
} |
require("semtree")
require("future")
plan(multisession)
data(lgcm)
lgcm$agegroup <- as.ordered(lgcm$agegroup)
lgcm$training <- as.factor(lgcm$training)
lgcm$noise <- as.numeric(lgcm$noise)
manifests <- names(lgcm)[1:5]
lgcModel <- mxModel("Linear Growth Curve Model Path Specification",
type="RAM",
manifestVars=manifests,
latentVars=c("intercept","slope"),
mxPath(
from=manifests,
arrows=2,
free=TRUE,
values = c(1, 1, 1, 1, 1),
labels=c("residual1","residual2","residual3","residual4","residual5")
),
mxPath(
from=c("intercept","slope"),
connect="unique.pairs",
arrows=2,
free=TRUE,
values=c(1, 1, 1),
labels=c("vari", "cov", "vars")
),
mxPath(
from="intercept",
to=manifests,
arrows=1,
free=FALSE,
values=c(1, 1, 1, 1, 1)
),
mxPath(
from="slope",
to=manifests,
arrows=1,
free=FALSE,
values=c(0, 1, 2, 3, 4)
),
mxPath(
from="one",
to=manifests,
arrows=1,
free=FALSE,
values=c(0, 0, 0, 0, 0)
),
mxPath(
from="one",
to=c("intercept", "slope"),
arrows=1,
free=TRUE,
values=c(1, 1),
labels=c("meani", "means")
),
mxData(lgcm,type="raw")
)
controlOptions <- semtree.control()
controlOptions
controlOptions$alpha <- 0.01
tree <- semtree(model=lgcModel, data=lgcm, control = controlOptions)
constraints <- semtree.constraints(global.invariance = names(omxGetParameters(lgcModel))[1:5])
treeConstrained <- semtree(model=lgcModel, data=lgcm, control = controlOptions,
constraints=constraints)
plot(tree)
summary(tree)
summary(treeConstrained)
print(tree)
parameters(tree)
parameters(tree, leafs.only=FALSE)
treeSub <- subtree(tree, startNode=3)
plot(treeSub) |
hierarchical_correction <- function(cis_assocs, local, global, tests_per_gene=NULL) {
local_pval <- NULL
pvalue <- NULL
n_tests <- NULL
gene <- NULL
statistic <- NULL
global_pval <- NULL
if (!is.null(tests_per_gene)) {
cis_assocs <- merge(cis_assocs, tests_per_gene, by="gene")
cis_assocs[, local_pval := adjust_p(pvalue, method=local, N=unique(n_tests)), by=gene]
} else {
cis_assocs[, local_pval := adjust_p(pvalue, method=local), by=gene]
}
cis_assocs <- cis_assocs[order(abs(statistic), decreasing=TRUE)]
top_assocs <- cis_assocs[, .SD[which.min(local_pval)], by="gene"]
top_assocs[,global_pval := adjust_p(local_pval, method=global)]
cis_assocs <- merge(cis_assocs, top_assocs[,list(gene, global_pval)], by="gene")
return(cis_assocs)
}
adjust_p <- function(pvals, method, N=NULL) {
if (method == "qvalue") {
qvalue::qvalue(pvals)$qvalues
} else if (method == "eigenMT") {
pmin(pvals * N, 1)
} else {
p.adjust(pvals, method, n=ifelse(is.null(N), length(pvals), N))
}
}
get_eSNP_threshold <- function(cis_assocs) {
statistic <- NULL
local_pval <- NULL
global_pval <- NULL
cis_assocs <- cis_assocs[order(abs(statistic), decreasing=TRUE)]
top_assocs <- cis_assocs[, .SD[which.min(local_pval)], by="gene"]
top_assocs <- top_assocs[order(global_pval)]
n_sig <- top_assocs[,sum(global_pval < 0.05)]
eSNP_threshold <- top_assocs[n_sig:(n_sig+1), mean(local_pval)]
return(eSNP_threshold)
} |
initial.surv <-
function (Time, d, W, WintF.vl, WintF.sl, id, times, method,
parameterization, long = NULL, long.deriv = NULL, extra = NULL, LongFormat) {
old <- options(warn = (-1))
on.exit(options(old))
if (!is.null(long)) {
long.id <- tapply(long, id, tail, 1)
if (parameterization == "value")
longD.id <- NULL
}
if (!is.null(long.deriv)) {
longD.id <- tapply(long.deriv, id, tail, 1)
if (parameterization == "slope")
long.id <- NULL
}
idT <- extra$ii
WW <- if (!LongFormat) {
cbind(W, long.id, longD.id)
} else {
cbind(W, long.id[idT], longD.id[idT])
}
if (method %in% c("Cox-PH-GH", "weibull-PH-GH", "piecewise-PH-GH",
"spline-PH-GH", "spline-PH-Laplace")) {
if (!LongFormat) {
DD <- data.frame(id = id, Time = Time[id], d = d[id], times = times)
if (!is.null(long)) {
DD$long <- long * WintF.vl[id, , drop = FALSE]
k <- ncol(DD$long)
}
if (!is.null(long.deriv)) {
DD$longD <- long.deriv * WintF.sl[id, , drop = FALSE]
l <- ncol(DD$longD)
}
dW <- as.data.frame(W[id, , drop = FALSE], row.names = row.names(DD))
if (ncol(dW)) {
names(dW) <- paste("W", seq_along(dW), sep = "")
DD <- cbind(DD, dW)
}
} else {
DD <- data.frame(Time = Time, d = d)
if (!is.null(long)) {
DD$long <- as.vector(long.id[idT]) * WintF.vl
k <- ncol(DD$long)
}
if (!is.null(long.deriv)) {
DD$longD <- as.vector(longD.id[idT]) * WintF.sl
l <- ncol(DD$longD)
}
dW <- as.data.frame(W, row.names = row.names(DD))
if (ncol(dW)) {
names(dW) <- paste("W", seq_along(dW), sep = "")
DD <- cbind(DD, dW)
}
DD$strata <- extra$strata
}
if (!LongFormat) {
DD$start <- DD$times
DD$stop <- unlist(lapply(split(DD[c("id", "start", "Time")], DD$id),
function (d) c(d$start[-1], d$Time[1])))
DD$event <- ave(DD$d, DD$id, FUN = function(x) {
if (length(x) == 1) {
x
} else {
x[seq(length(x) - 1)] <- 0
x
}
})
}
baseCovs <- if (ncol(dW)) {
paste("+", paste(names(dW), collapse = " + "))
} else
NULL
form <- if (!LongFormat) {
switch(parameterization,
"value" = paste("Surv(start, stop, event) ~", "long", baseCovs),
"slope" = paste("Surv(start, stop, event) ~", "longD", baseCovs),
"both" = paste("Surv(start, stop, event) ~", "long + longD", baseCovs))
} else {
switch(parameterization,
"value" = paste("Surv(Time, d) ~", "long", baseCovs),
"slope" = paste("Surv(Time, d) ~", "longD", baseCovs),
"both" = paste("Surv(Time, d) ~", "long + longD", baseCovs))
}
if (!is.null(DD$strata))
form <- paste(form, "+ strata(strata)")
form <- as.formula(form)
cph <- coxph(form, data = DD)
coefs <- cph$coefficients
out <- switch(parameterization,
"value" = list(alpha = coefs[1:k], gammas = coefs[-(1:k)]),
"slope" = list(Dalpha = coefs[1:l], gammas = coefs[-(1:l)]),
"both" = list(alpha = coefs[1:k], Dalpha = coefs[(k+1):(k+l)],
gammas = coefs[-(1:(k+l))])
)
if (method == "Cox-PH-GH") {
out$lambda0 <- basehaz(cph, FALSE)$hazard
}
if (method == "weibull-PH-GH") {
dat <- data.frame(Time = Time, d = d)
init.fit <- survreg(Surv(Time, d) ~ WW, data = dat)
coefs <- - init.fit$coef / init.fit$scale
out$gammas <- c(coefs[1], out$gammas)
out$sigma.t <- 1 / init.fit$scale
}
if (method == "piecewise-PH-GH") {
dat <- data.frame(Time = Time, d = d)
cph. <- coxph(Surv(Time, d) ~ WW, data = dat, x = TRUE)
init.fit <- piecewiseExp.ph(cph., knots = extra$control$knots)
coefs <- init.fit$coef
out$xi <- exp(coefs[grep("xi", names(coefs))])
}
if (method == "spline-PH-GH" || method == "spline-PH-Laplace") {
if (is.null(extra$strata)) {
dat <- data.frame(Time = Time, d = d, as.data.frame(WW))
rn <- tapply(row.names(dat), idT, tail, 1)
ind <- row.names(dat) %in% rn
dat <- dat[ind, ]
init.fit <- survreg(Surv(Time, d) ~ ., data = dat)
coefs <- init.fit$coef
xi <- 1 / init.fit$scale
phi <- exp(coefs[1])
logh <- -log(phi * xi * dat$Time^(xi - 1))
out$gammas.bs <- as.vector(lm.fit(extra$W2[ind, ], logh)$coefficients)
} else {
dat <- data.frame(Time = Time, d = d)
dat <- cbind(dat, as.data.frame(WW))
strata <- extra$strata
split.dat <- split(dat, strata)
gg <- NULL
for (i in seq_along(split.dat)) {
ii <- strata == levels(strata)[i]
SpD.i <- split.dat[[i]]
idT.i <- idT[ii]
W2.i <- extra$W2[ii, ]
rn <- tapply(row.names(SpD.i), idT.i, tail, 1)
ind <- row.names(SpD.i) %in% rn
SpD.i <- SpD.i[ind, ]
init.fit <- survreg(Surv(Time, d) ~ ., data = SpD.i)
coefs <- init.fit$coef
xi <- 1 / init.fit$scale
phi <- exp(coefs[1])
logh <- -log(phi * xi * SpD.i$Time^(xi - 1))
gg <- c(gg, as.vector(lm.fit(W2.i[ind, ], logh)$coefficients))
}
out$gammas.bs <- gg[!is.na(gg)]
}
out
}
}
if (method == "weibull-AFT-GH") {
dat <- data.frame(Time = Time, d = d)
if (!is.null(long.id)) {
long.id <- c(long.id) * WintF.vl
k <- ncol(WintF.vl)
}
if (!is.null(longD.id)) {
longD.id <- c(longD.id) * WintF.sl
l <- ncol(WintF.sl)
}
WW <- cbind(W, long.id, longD.id)
init.fit <- survreg(Surv(Time, d) ~ WW, data = dat)
coefs <- - init.fit$coef
nk <- if (is.null(W)) 1 else ncol(W) + 1
out <- switch(parameterization,
"value" = list(gammas = coefs[1:nk], alpha = coefs[-(1:nk)], sigma.t = 1 / init.fit$scale),
"slope" = list(gammas = coefs[1:nk], Dalpha = coefs[-(1:nk)], sigma.t = 1 / init.fit$scale),
"both" = list(gammas = coefs[1:nk], alpha = coefs[seq(nk+1, nk+k)],
Dalpha = coefs[-seq(1, nk+k)], sigma.t = 1 / init.fit$scale)
)
}
if (method == "ch-Laplace") {
dat <- data.frame(Time = Time, d = d)
init.fit <- survreg(Surv(Time, d) ~ WW, data = dat)
coefs <- - coef(init.fit) / init.fit$scale
min.x <- min(logT)
max.x <- max(logT)
kn <- if (is.null(extra$control$knots)) {
kk <- seq(0, 1, length.out = extra$control$lng.in.kn + 2)[-c(1, extra$control$lng.in.kn + 2)]
quantile(log(Time)[d == 1], kk, names = FALSE)
} else {
extra$control$knots
}
kn <- sort(c(rep(c(min.x, max.x), extra$control$ord), kn))
W <- splineDesign(kn, log(Time), ord = extra$control$ord)
nk <- ncol(W)
nx <- NCOL(X)
logH <- coefs[1] + logT / init.fit$scale
coefs <- c(as.vector(lm.fit(W, logH)$coefficients), coefs[-1])
out <- list(gammas = c(sort(coefs[1:nk]), if (nx > 1) coefs[seq(nk + 1, nk + nx - 1)] else NULL),
alpha = coefs[nk + nx])
}
out
} |
make.appearance.matrix = function( result ) {
mat = phrase.matrix(result)
mat = mat[ result$labeling==1, ]
stopifnot( all( result$model$ngram == colnames(mat) ) )
mat[ mat > 0 ] = 1
if ( !is.matrix( mat ) ) {
mat = matrix( mat, ncol=1, nrow=length(mat) )
}
mat
}
make.similarity.matrix = function( result ) {
if ( is.textreg.result( result ) ) {
mat = make.appearance.matrix( result )
} else {
mat = result
}
hits = sqrt( apply( mat, 2, sum ) )
hits[hits==0] = 1
if ( length(hits) > 1 ) {
dg = diag( 1/hits )
} else {
dg = 1/hits
}
sim.mat = dg %*% t(mat) %*% mat %*% dg
rownames(sim.mat) = colnames(sim.mat) = colnames(mat)
dim( sim.mat )
summary( as.numeric( sim.mat ) )
stopifnot( max( sim.mat, na.rm=TRUE ) <= 1.000001 )
sim.mat[ sim.mat > 1 ] = 1
sim.mat
}
cluster.phrases = function( result, num.groups=5, plot=TRUE, yaxt="n", ylab="", sub="", main="Association of Phrases", ... ) {
requireNamespace( "stats" )
if ( is.textreg.result( result ) ) {
mat = make.appearance.matrix ( result )
sim.mat = make.similarity.matrix( result )
} else {
mat = NULL
sim.mat = result
}
d = 1 - sim.mat[-1,-1]
dim( d )
d = as.dist( d )
d
fit <- hclust(d, method="ward.D")
if( num.groups > nrow( sim.mat ) - 1 ) {
stop( gettextf( "You cannot form %d groups when you only have %d features", num.groups, length(result$rules) ) )
}
groups <- cutree(fit, k=num.groups)
groups
if ( plot ) {
par( mfrow=c(1,1) )
tots = apply( mat, 2, sum )
labs = paste( attr(d,"Labels"), " (", tots[-1], ")", sep="" )
plot( fit, labels=labs, yaxt=yaxt, ylab=ylab,sub=sub,main=main, ... )
rect.hclust(fit, k=num.groups, border="red")
}
colnames(sim.mat[,-1])[ fit$order ]
sim.mat = sim.mat[ c(1,1+fit$order), c(1,1+fit$order) ]
if ( !is.null( mat ) ) {
mat = mat[ , c(1,1+fit$order) ]
stopifnot( all( rownames( sim.mat ) == colnames(mat) ) )
}
groups = c( NA, groups[fit$order] )
names(groups)[1] = "*intercept*"
invisible( list( mat=mat, sim.mat=sim.mat, fit=fit, groups=groups) )
}
make.phrase.correlation.chart = function( result, count=FALSE, num.groups=5, use.corrplot=FALSE, ... ) {
lst = cluster.phrases( result, num.groups=num.groups, plot=FALSE )
nlevel = 8
if ( count || use.corrplot ) {
img.mat = t(lst$mat) %*% lst$mat
img.mat = img.mat[-1,-1]
breaks = c( 0, seq( 1-0.000001,max(img.mat,na.rm=TRUE),length.out= nlevel ) )
} else {
img.mat = lst$sim.mat[-1,-1]
breaks = c( 0, seq(min(img.mat[img.mat>0]),1+0.000001,length.out= nlevel ) )
}
gps = which( lst$groups[-1] != lst$groups[-length(lst$groups)] )
if ( use.corrplot ) {
if (!requireNamespace("corrplot", quietly = TRUE)) {
stop( "need to install corrplot to use the use.corrplot=TRUE option" )
}
corrplot::corrplot( img.mat, is.corr=FALSE, type="lower", method="number", col="black",tl.pos="tp", cl.pos="n" )
corrplot::corrplot( lst$sim.mat[-1,-1], add=TRUE, is.corr=FALSE, type="upper", diag=FALSE, tl.pos="n", ... )
abline( h=(length(lst$groups)-gps) + 0.5, col="red", lty=3 )
abline( v=gps -0.5, col="red", lty=3 )
} else {
np = nrow(img.mat)
par( mar=c(10,10,0.3,0.3), mgp=c(2,1,0) )
image( 1:np, 1:np, img.mat, xaxt="n", yaxt="n", xlab="", ylab="",
breaks=breaks, col = grey(seq(1,0,length.out= nlevel)), ... )
axis( 1, at=1:nrow(img.mat), labels=rownames(img.mat), cex.axis=0.8, las=2 )
axis( 2, at=1:nrow(img.mat), labels=rownames(img.mat), cex.axis=0.8, las=2 )
if ( count ) {
nonz = which( img.mat != 0 )
corx = 1 + (nonz-1) %% ncol(img.mat)
cory = 1 + (nonz-1) %/% ncol(img.mat)
text( corx, cory, as.character( img.mat[nonz] ), col="red", ... )
}
abline( h=gps -0.5, col="red", lty=3 )
abline( v=gps -0.5, col="red", lty=3 )
}
lst$img.mat = img.mat
invisible( lst )
}
if ( FALSE ) {
load( "recycling_results" )
nres = res_no_bale_C3
res = cluster.phrases( nres, num.groups=3 )
res$groups
make.phrase.correlation.chart( nres )
make.phrase.correlation.chart( nres, count=TRUE )
mat = make.appearance.matrix( nres )
sim.mat = make.similarity.matrix( mat )
dim( sim.mat )
head( mat )
p1 = mat[, 3 ]
mt = t(mat) %*% mat
sum( lower.tri( mt ) )
table( mt[ lower.tri( mt ) ] )
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.