code
stringlengths 1
13.8M
|
---|
susie_auto = function (X, y, L_init = 1, L_max = 512, verbose = FALSE,
init_tol = 1, standardize = TRUE, intercept = TRUE,
max_iter = 100,tol = 1e-2, ...) {
L = L_init
if (verbose)
message(paste0("Trying L=",L))
s.0 = susie(X,y,L = L,residual_variance = 0.01*sd(y)^2,tol = init_tol,
scaled_prior_variance = 1,estimate_residual_variance = FALSE,
estimate_prior_variance = FALSE,standardize = standardize,
intercept = intercept,max_iter = max_iter,...)
s.1 = susie(X,y,s_init = s.0,tol = init_tol,
estimate_residual_variance = TRUE,
estimate_prior_variance = FALSE,
standardize = standardize,intercept = intercept,
max_iter = max_iter,...)
s.2 = susie(X,y,s_init = s.1,tol = init_tol,
estimate_residual_variance = TRUE,
estimate_prior_variance = TRUE,
standardize = standardize,intercept = intercept,
max_iter = max_iter,...)
converged = !all(s.2$V > 0)
while (!converged & (L <= L_max)) {
for (i in 1:L) {
s.2 = add_null_effect(s.2,1)
s.2$sigma2 = 0.01*sd(y)^2
}
L = 2*L
if (verbose)
message(paste0("Trying L=",L))
s.0 = susie(X,y,s_init = s.2,tol = init_tol,
estimate_residual_variance = FALSE,
estimate_prior_variance = FALSE,
standardize = standardize,intercept = intercept,
max_iter = max_iter,...)
s.1 = susie(X,y,s_init = s.0,tol = init_tol,
estimate_residual_variance = TRUE,
estimate_prior_variance = FALSE,
standardize = standardize,intercept = intercept,
max_iter = max_iter,...)
s.2 = susie(X,y,s_init = s.1,tol = init_tol,
estimate_residual_variance = TRUE,
estimate_prior_variance = TRUE,
standardize = standardize,intercept = intercept,
max_iter = max_iter,...)
converged = !all(s.2$V > 0)
}
s.2 = susie(X,y,s_init = s.2,estimate_residual_variance = TRUE,
estimate_prior_variance = TRUE,tol = tol,
standardize = standardize,intercept = intercept,
max_iter = max_iter,...)
return(s.2)
} |
item_intercor <- function(x, method = c("pearson", "spearman", "kendall")) {
method <- match.arg(method)
if (inherits(x, "matrix")) {
corr <- x
} else {
x <- stats::na.omit(x)
corr <- stats::cor(x, method = method)
}
mean(corr[lower.tri(corr)])
} |
add.dist.error <- function(no.files, path, cv = NULL, distribution, beta.params = NULL){
for(i in 1:no.files){
load(paste(path,"dataset_",i,".robj", sep = ""))
ddf.data <- [email protected]
if(distribution == "Normal"){
error <- rnorm(nrow(ddf.data), mean = 0, sd = cv*ddf.data$distance)
new.distances <- ddf.data$distance + error
if(range(new.distances)[1] < 0){
warning("Distances less than 0 have been generatesd. The absolute value of these negative values will be used therefore the errors are no longer Normally-distributed.", call. = FALSE, immediate. = TRUE)
}
new.distances <- abs(new.distances)
}else if(distribution == "Log-Normal"){
new.distances <- rep(NA, nrow(ddf.data))
for(j in seq(along = new.distances)){
new.distances[j] <- rlnorm(1, log(ddf.data$distance[j])-0.5*log(1+cv^2), sqrt(log(1+cv^2)))
}
}else if(distribution == "Beta"){
R <- 0.5 + rbeta(nrow(ddf.data), beta.params[1], beta.params[2])
new.distances <- ddf.data$distance*R
}
ddf.data$distance <- new.distances
[email protected] <- ddf.data
save(dist.data, file = paste(path,"dataset_",i,".robj", sep = ""))
}
} |
jomo.lm <-
function(formula, data, beta.start=NULL, l1cov.start=NULL, l1cov.prior=NULL, nburn=1000, nbetween=1000, nimp=5, output=1, out.iter=10) {
cat("This function is beta software. Use carefully and please report any bug to the package mantainer\n")
if (nimp<2) {
nimp=2
cat("Minimum number of imputations:2. For single imputation using function jomo.lm.MCMCchain\n")
}
stopifnot(is.data.frame(data))
stopifnot(any(grepl("~",deparse(formula))))
fit.cr<-lm(formula,data=data, na.action = na.omit)
betaY.start<-coef(fit.cr)
varY.start<-(summary(fit.cr)$sigma)^2
varY.prior<-(summary(fit.cr)$sigma)^2
colnamysub<-all.vars(formula[[2]])
Ysub<-get(colnamysub,pos=data)
Ycov<-data.frame(mget(all.vars(formula[[3]]), envir =as.environment(data)))
terms.sub<-attr(terms(formula), "term.labels")
split.terms<-strsplit(terms.sub,":")
length.sub<-length(terms.sub)
order.sub<-attr(terms(formula), "order")
submod<-matrix(1,4,sum(order.sub))
Y.con<-NULL
Y.cat<-NULL
Y.numcat<-NULL
for (j in 1:ncol(Ycov)) {
if (is.numeric(Ycov[,j])) {
if (is.null(Y.con)) Y.con<-data.frame(Ycov[,j,drop=FALSE])
else Y.con<-data.frame(Y.con,Ycov[,j,drop=FALSE])
}
if (is.factor(Ycov[,j])) {
if (is.null(Y.cat)) Y.cat<-data.frame(Ycov[,j,drop=FALSE])
else Y.cat<-data.frame(Y.cat,Ycov[,j,drop=FALSE])
Y.numcat<-cbind(Y.numcat,nlevels(Ycov[,j]))
}
}
h<-1
for ( j in 1:length.sub) {
for ( k in 1:order.sub[j]) {
current.term<-split.terms[[j]][k]
current.term<-sub(".*I\\(","",current.term)
current.term<-sub("\\)","",current.term)
if (grepl("\\^",current.term)) {
submod[3,h]<-as.integer(sub(".*\\^","",current.term))
current.term<-sub("\\^.*","",current.term)
} else {
submod[3,h]<-1
}
if (length(which(colnames(Y.cat)==current.term))!=0) {
submod[1,h]<-which(colnames(Y.cat)==current.term)
submod[2,h]<-2
submod[4,h]<-Y.numcat[submod[1,h]]-1
} else if (length(which(colnames(Y.con)==current.term))!=0) {
submod[1,h]<-which(colnames(Y.con)==current.term)
submod[2,h]<-1
}
h<-h+1
}
}
Y.auxiliary<-data.frame(data[,-c(which(colnames(data)%in%colnames(Y.con)),which(colnames(data)%in%colnames(Y.cat)),which(colnames(data)==colnamysub)), drop=FALSE])
Y.aux.con<-NULL
Y.aux.cat<-NULL
Y.aux.numcat<-NULL
if (ncol(Y.auxiliary)>0) {
for (j in 1:ncol(Y.auxiliary)) {
if (is.numeric(Y.auxiliary[,j])) {
if (is.null(Y.aux.con)) Y.aux.con<-data.frame(Y.auxiliary[,j,drop=FALSE])
else Y.aux.con<-data.frame(Y.aux.con,Y.auxiliary[,j,drop=FALSE])
}
if (is.factor(Y.auxiliary[,j])) {
if (is.null(Y.aux.cat)) Y.aux.cat<-data.frame(Y.auxiliary[,j,drop=FALSE])
else Y.aux.cat<-data.frame(Y.aux.cat,Y.auxiliary[,j,drop=FALSE])
Y.aux.numcat<-cbind(Y.aux.numcat,nlevels(Y.auxiliary[,j]))
}
}
}
X=matrix(1,max(nrow(Y.cat),nrow(Y.con)),1)
if (is.null(beta.start)) beta.start=matrix(0,ncol(X),(max(as.numeric(!is.null(Y.con)),ncol(Y.con))+max(0,(sum(Y.numcat)-length(Y.numcat)))+max(as.numeric(!is.null(Y.aux.con)),ncol(Y.aux.con))+max(0,(sum(Y.aux.numcat)-length(Y.aux.numcat)))))
if (is.null(l1cov.start)) {
l1cov.start=diag(1,ncol(beta.start))
}
if (is.null(l1cov.prior)) l1cov.prior=diag(1,ncol(l1cov.start))
ncolYcon<-rep(NA,4)
ncolYcon[1]=max(as.numeric(!is.null(Y.con)),ncol(Y.con))+max(as.numeric(!is.null(Y.aux.con)),ncol(Y.aux.con))
ncolYcon[2]=max(as.numeric(!is.null(Y.con)),ncol(Y.con))
ncolYcon[3]=ncolYcon[1]+max(0,(sum(Y.numcat)-length(Y.numcat)))
ncolYcon[4]=max(0,ncol(Y.cat))
stopifnot(((!is.null(Y.con))||(!is.null(Y.cat)&!is.null(Y.numcat))))
if (!is.null(Y.cat)) {
isnullcat=0
previous_levels<-list()
Y.cat<-data.frame(Y.cat)
for (i in 1:ncol(Y.cat)) {
Y.cat[,i]<-factor(Y.cat[,i])
previous_levels[[i]]<-levels(Y.cat[,i])
levels(Y.cat[,i])<-1:nlevels(Y.cat[,i])
}
} else {
isnullcat=1
}
if (!is.null(Y.aux.cat)) {
isnullcataux=0
previous_levelsaux<-list()
Y.aux.cat<-data.frame(Y.aux.cat)
for (i in 1:ncol(Y.aux.cat)) {
Y.aux.cat[,i]<-factor(Y.aux.cat[,i])
previous_levelsaux[[i]]<-levels(Y.aux.cat[,i])
levels(Y.aux.cat[,i])<-1:nlevels(Y.aux.cat[,i])
}
} else {
isnullcataux=1
}
stopifnot(nrow(beta.start)==ncol(X), ncol(beta.start)==(ncolYcon[1]+max(0,(sum(Y.numcat)-length(Y.numcat)))+max(0,(sum(Y.aux.numcat)-length(Y.aux.numcat)))))
stopifnot(nrow(l1cov.start)==ncol(l1cov.start),nrow(l1cov.prior)==nrow(l1cov.start),nrow(l1cov.start)==ncol(beta.start))
stopifnot(nrow(l1cov.prior)==ncol(l1cov.prior))
betait=matrix(0,nrow(beta.start),ncol(beta.start))
for (i in 1:nrow(beta.start)) {
for (j in 1:ncol(beta.start)) betait[i,j]=beta.start[i,j]
}
covit=matrix(0,nrow(l1cov.start),ncol(l1cov.start))
for (i in 1:nrow(l1cov.start)) {
for (j in 1:ncol(l1cov.start)) covit[i,j]=l1cov.start[i,j]
}
if (!is.null(Y.con)) {
colnamycon<-colnames(Y.con)
Y.con<-data.matrix(Y.con)
storage.mode(Y.con) <- "numeric"
} else {
colnamycon<-NULL
}
if (isnullcat == 0) {
colnamycat <- colnames(Y.cat)
Y.cat <- data.matrix(Y.cat)
storage.mode(Y.cat) <- "numeric"
cnycatcomp<-rep(NA,(sum(Y.numcat)-length(Y.numcat)))
count=0
for ( j in 1:ncol(Y.cat)) {
for (k in 1:(Y.numcat[j]-1)) {
cnycatcomp[count+k]<-paste(colnamycat[j],k,sep=".")
}
count=count+Y.numcat[j]-1
}
} else {
cnycatcomp<-NULL
}
if (!is.null(Y.aux.con)) {
colnamyauxcon<-colnames(Y.aux.con)
Y.aux.con<-data.matrix(Y.aux.con)
storage.mode(Y.aux.con) <- "numeric"
} else {
colnamyauxcon<-NULL
}
if (isnullcataux == 0) {
colnamyauxcat <- colnames(Y.aux.cat)
Y.aux.cat <- data.matrix(Y.aux.cat)
storage.mode(Y.aux.cat) <- "numeric"
cnyauxcatcomp<-rep(NA,(sum(Y.aux.numcat)-length(Y.aux.numcat)))
count=0
for ( j in 1:ncol(Y.aux.cat)) {
for (k in 1:(Y.aux.numcat[j]-1)) {
cnyauxcatcomp[count+k]<-paste(colnamyauxcat[j],k,sep=".")
}
count=count+Y.aux.numcat[j]-1
}
} else {
cnyauxcatcomp<-NULL
}
colnamx<-colnames(X)
X<-data.matrix(X)
storage.mode(X) <- "numeric"
Y=cbind(Y.con,Y.aux.con,Y.cat, Y.aux.cat)
Yi=cbind(Y.con, Y.aux.con, switch(is.null(Y.cat)+1, matrix(0,nrow(Y),(sum(Y.numcat)-length(Y.numcat))), NULL), switch(is.null(Y.aux.cat)+1, matrix(0,nrow(Y.aux.cat),(sum(Y.aux.numcat)-length(Y.aux.numcat))), NULL))
h=1
if (isnullcat==0) {
for (i in 1:length(Y.numcat)) {
for (j in 1:nrow(Y)) {
if (is.na(Y.cat[j,i])) {
Yi[j,(ncolYcon[1]+h):(ncolYcon[1]+h+Y.numcat[i]-2)]=NA
}
}
h=h+Y.numcat[i]-1
}
}
if (isnullcataux==0) {
for (i in 1:length(Y.aux.numcat)) {
for (j in 1:nrow(Y)) {
if (is.na(Y.aux.cat[j,i])) {
Yi[j,(ncolYcon[1]+h):(ncolYcon[1]+h+Y.aux.numcat[i]-2)]=NA
}
}
h=h+Y.aux.numcat[i]-1
}
}
if (isnullcat==0||isnullcataux==0) {
Y.cat.tot<-cbind(Y.cat,Y.aux.cat)
Y.numcat.tot<-c(Y.numcat, Y.aux.numcat)
} else {
Y.cat.tot=-999
Y.numcat.tot=-999
}
Ysubimp<-Ysub
if (output == 0) out.iter=nburn+nbetween
imp=matrix(0,nrow(Y)*(nimp+1),ncol(Y)+3)
imp[1:nrow(Y),1]=Ysub
imp[1:nrow(Y),2:(1+ncol(Y))]=Y
imp[1:nrow(X), (ncol(Y)+2)]=c(1:nrow(Y))
Yimp=Yi
Yimp2=matrix(Yimp, nrow(Yimp),ncol(Yimp))
imp[(nrow(X)+1):(2*nrow(X)), (ncol(Y)+2)]=c(1:nrow(Y))
imp[(nrow(X)+1):(2*nrow(X)), (ncol(Y)+3)]=1
betapost<- array(0, dim=c(nrow(beta.start),ncol(beta.start),(nimp-1)))
betaYpost<- array(0, dim=c(1,length(betaY.start),(nimp-1)))
bpost<-matrix(0,nrow(beta.start),ncol(beta.start))
bYpost<-matrix(0,1,length(betaY.start))
omegapost<- array(0, dim=c(nrow(l1cov.start),ncol(l1cov.start),(nimp-1)))
opost<-matrix(0,nrow(l1cov.start),ncol(l1cov.start))
varYpost<-rep(0,(nimp-1))
vYpost<-matrix(0,1,1)
meanobs<-colMeans(Yi,na.rm=TRUE)
for (i in 1:nrow(Yi)) for (j in 1:ncol(Yi)) if (is.na(Yimp[i,j])) Yimp2[i,j]=meanobs[j]
for (i in 1:length(Ysubimp)) if (is.na(Ysubimp[i])) Ysubimp[i]=mean(Ysubimp, na.rm = TRUE)
.Call("jomo1smcC", Ysub, Ysubimp, 0, submod, order.sub, Y, Yimp, Yimp2, Y.cat.tot, X, betaY.start, bYpost, betait,bpost, varY.start, vYpost, covit,opost, nburn, varY.prior, l1cov.prior,Y.numcat.tot,1, ncolYcon,out.iter, 0, 0, PACKAGE = "jomo")
bpost<-matrix(0,nrow(beta.start),ncol(beta.start))
bYpost<-matrix(0,1,length(betaY.start))
opost<-matrix(0,nrow(l1cov.start),ncol(l1cov.start))
vYpost<-matrix(0,1,1)
imp[(nrow(Y)+1):(2*nrow(Y)),1]=Ysubimp
if (!is.null(Y.con)|!is.null(Y.aux.con)) {
imp[(nrow(Y)+1):(2*nrow(Y)),2:(1+max(0,ncol(Y.con))+max(0,ncol(Y.aux.con)))]=Yimp2[,1:(max(0,ncol(Y.con))+max(0,ncol(Y.aux.con)))]
}
if (isnullcat==0|isnullcataux==0) {
imp[(nrow(Y)+1):(2*nrow(Y)),(ncolYcon[1]+2):(1+ncol(Y))]=Y.cat.tot
}
if (output > 0) cat("First imputation registered.", "\n")
for (i in 2:nimp) {
imp[(i*nrow(X)+1):((i+1)*nrow(X)), (ncol(Y)+2)]=c(1:nrow(Y))
imp[(i*nrow(X)+1):((i+1)*nrow(X)), (ncol(Y)+3)]=i
.Call("jomo1smcC", Ysub, Ysubimp, 0, submod, order.sub, Y, Yimp, Yimp2, Y.cat.tot, X, betaY.start, bYpost, betait,bpost, varY.start, vYpost, covit,opost, nbetween, varY.prior, l1cov.prior,Y.numcat.tot,1, ncolYcon,out.iter, 0, 0, PACKAGE = "jomo")
betapost[,,(i-1)]=bpost
betaYpost[,,(i-1)]=bYpost
omegapost[,,(i-1)]=opost
varYpost[i-1]=vYpost
bpost<-matrix(0,nrow(beta.start),ncol(beta.start))
bYpost<-matrix(0,1,length(betaY.start))
opost<-matrix(0,nrow(l1cov.start),ncol(l1cov.start))
vYpost<-matrix(0,1,1)
imp[(i*nrow(X)+1):((i+1)*nrow(X)),1]=Ysubimp
if (!is.null(Y.con)|!is.null(Y.aux.con)) {
imp[(i*nrow(X)+1):((i+1)*nrow(X)),2:(1+max(0,ncol(Y.con))+max(0,ncol(Y.aux.con)))]=Yimp2[,1:(max(0,ncol(Y.con))+max(0,ncol(Y.aux.con)))]
}
if (isnullcat==0||isnullcataux==0) {
imp[(i*nrow(X)+1):((i+1)*nrow(X)),(ncolYcon[1]+2):(1+ncol(Y))]=Y.cat.tot
}
if (output > 0) cat("Imputation number ", i, "registered", "\n")
}
cnamycomp<-c(colnamycon, colnamyauxcon, cnycatcomp, cnyauxcatcomp)
dimnames(betapost)[1] <- list("(Intercept)")
dimnames(betapost)[2] <- list(cnamycomp)
dimnames(omegapost)[1] <- list(cnamycomp)
dimnames(omegapost)[2] <- list(cnamycomp)
betaYpostmean <- apply(betaYpost, c(1, 2), mean)
varYpostmean <- mean(varYpost)
betapostmean <- apply(betapost, c(1, 2), mean)
omegapostmean <- apply(omegapost, c(1, 2), mean)
colnames(betaYpostmean)<-names(fit.cr$coefficients)
rownames(betaYpostmean)<-colnamysub
if (output > 0) {
cat("The posterior mean of the substantive model fixed effects estimates is:\n")
print(betaYpostmean)
cat("The posterior mean of the substantive model residual variance is:\n")
print(varYpostmean)
if ( output == 2 ) {
cat("The posterior mean of the fixed effects estimates is:\n")
print(betapostmean)
cat("The posterior mean of the level 1 covariance matrix is:\n")
print(omegapostmean)
}
}
imp<-data.frame(imp)
if (isnullcat==0) {
for (i in 1:ncol(Y.cat)) {
imp[,(1+ncolYcon[1]+i)]<-as.factor(imp[,(1+ncolYcon[1]+i)])
levels(imp[,(1+ncolYcon[1]+i)])<-previous_levels[[i]]
}
}
if (isnullcataux==0) {
for (i in 1:ncol(Y.aux.cat)) {
imp[,(1+ncolYcon[1]+ncolYcon[4]+i)]<-as.factor(imp[,(1+ncolYcon[1]+ncolYcon[4]+i)])
levels(imp[,(1+ncolYcon[1]+ncolYcon[4]+i)])<-previous_levelsaux[[i]]
}
}
if (ncolYcon[1]>0) {
for (j in 1:(ncolYcon[1])) {
imp[,j+1]=as.numeric(imp[,j+1])
}
}
if (isnullcat==0) {
if (is.null(colnamycat)) colnamycat=paste("Ycat", 1:ncol(Y.cat), sep = "")
} else {
colnamycat=NULL
Y.cat=NULL
Y.numcat=NULL
}
if (isnullcataux==0) {
if (is.null(colnamyauxcat)) colnamyauxcat=paste("Ycat.aux", 1:ncol(Y.aux.cat), sep = "")
} else {
colnamyauxcat=NULL
Y.aux.cat=NULL
Y.aux.numcat=NULL
}
if (!is.null(Y.con)) {
if (is.null(colnamycon)) colnamycon=paste("Ycon", 1:ncol(Y.con), sep = "")
} else {
colnamycon=NULL
}
if (!is.null(Y.aux.con)) {
if (is.null(colnamyauxcon)) colnamyauxcon=paste("Ycon.aux", 1:ncol(Y.aux.con), sep = "")
} else {
colnamyauxcon=NULL
}
if (is.null(colnamysub)) colnamysub="Ysub"
colnames(imp)<-c(colnamysub,colnamycon,colnamyauxcon,colnamycat,colnamyauxcat,"id","Imputation")
return(imp)
} |
skippedMean <- function(x, na.rm = FALSE, constant = 3.0){
stopifnot(is.numeric(x))
if(na.rm) x <- x[!is.na(x)]
stopifnot(constant > 0, length(constant) == 1)
M <- median(x)
MAD <- mad(x)
mean(x[M - constant*MAD < x & x < M + constant*MAD])
}
skippedSD <- function(x, na.rm = FALSE, constant = 3.0){
stopifnot(is.numeric(x))
if(na.rm) x <- x[!is.na(x)]
stopifnot(constant > 0, length(constant) == 1)
M <- median(x)
MAD <- mad(x)
sd(x[M - constant*MAD < x & x < M + constant*MAD])
} |
phihat <- function(object, type = c("pearson", "deviance", "mle", "grcv"), g = NULL, ...){
if(class(object) != "dglars")
stop("this function works only with objects with class 'dglars'")
family_used <- object$family$family
type <- match.arg(type)
if(family_used %in% c("binomial", "poisson"))
phih <- rep.int(1, ifelse(is.null(g), length(object$g), length(g)))
else{
if(type != "grcv") {
n <- dim(object$X)[1]
npar <- predict(object, g = g, type = "nnonzero")
df <- n - npar
dev <- predict(object, g = g, type = "deviance")
phih <- switch(type,
pearson = predict(object, g = g, type = "coefficients")$phi,
deviance = dev / df,
mle = if(family_used != "Gamma") dev / n
else 2 * dev / (n * (1 + sqrt(1 + 2/3 * dev / n))))
} else {
np <- ifelse(is.null(g), length(object$g), length(g))
phih <- grcv(object, ...)
phih <- rep(phih, length.out = np)
}
}
phih
} |
nonbinding <-
function(l, u, theta, sigma, n1, n2, t.vec, type1, type2, gamma = rep(-4,2),
crange=c(-10,10), drange=c(-10,10), force = TRUE,
plot = TRUE, ll=3, ul=6, n.sim=1e4, seed=NULL)
{
HSD <- function(t,error,gamma) error*(1-exp(-gamma*t))/(1-exp(-gamma))
I.vec <- HSD(t.vec,type1, gamma[1])
II.vec <- HSD(t.vec,type2, gamma[2])
K <- length(t.vec)
nn1 <- ceiling(n1 * t.vec); nn1[K] <- n1
nn2 <- ceiling(n2 * t.vec); nn2[K] <- n2
if(!is.null(seed)) set.seed(seed)
simdataL <- data.frame(matrix(0,n.sim*K,3))
colnames(simdataL)<- c("stage", "t.L", "t.U")
x1 <- matrix(rnorm(n1*n.sim, 0, sigma), n.sim, n1)
x2 <- matrix(rnorm(n2*n.sim, l, sigma), n.sim, n2)
for(k in 1:K){
x1.stage <- x1[,1:nn1[k]]
mean1.temp <- apply(x1.stage, 1, mean)
v1.temp <- apply(x1.stage, 1, var)
x2.stage <- x2[,1:nn2[k]]
mean2.temp <- apply(x2.stage, 1, mean)
v2.temp <- apply(x2.stage, 1, var)
v.pool <- (v1.temp*(nn1[k]-1)+ v2.temp*(nn2[k]-1))/(nn1[k]+ nn2[k]-2)
se.pool <- sqrt(v.pool*(1/nn1[k]+1/nn2[k]))
diff <- mean2.temp - mean1.temp
t.L <- (diff - l) / se.pool
t.U <- (diff - u) / se.pool
simdataL[(k-1)*n.sim + 1:n.sim,] <- cbind(k, t.L, t.U)
}
ct2.L <- rep(99, K)
ct2.U <- rep(-99, K)
f <- function(x){
temp1 <- simdataL[(simdataL$stage == 1),]$t.L > x
temp2 <- simdataL[(simdataL$stage == 1),]$t.U < -x
result<- sum(temp1 & temp2) / n.sim - I.vec[1]
return(result)
}
ct2.L[1] <- uniroot(f, crange, tol=0.001)$root
ct2.U[1] <- -ct2.L[1]
for (k in 2:K) {
stagealpha <- I.vec[k] - I.vec[k-1]
temp1 <- (simdataL[(simdataL$stage == k - 1),]$t.L > ct2.L[k - 1])
temp2 <- (simdataL[(simdataL$stage == k - 1),]$t.U < ct2.U[k - 1])
reject.prev <- temp1 & temp2
if(any(is.na(reject.prev))) reject.prev[is.na(reject.prev)] <- TRUE
if(any(reject.prev)){
simdataL[(simdataL$stage == k),][reject.prev,]$t.L <- NA
simdataL[(simdataL$stage == k),][reject.prev,]$t.U <- NA
}
if(all(is.na(simdataL$t.L)) == FALSE){
simdataL.k <- simdataL[(simdataL$stage == k),]
left.k <- simdataL.k[!is.na(simdataL.k$t.L), ]
if(nrow(left.k)< stagealpha*n.sim)
stop(paste("No solutions for the equivalence boundaries at stage ", as.character(k)))
else{
f <- function(x) {
temp1 <- left.k$t.L > x
temp2 <- left.k$t.U < -x
result <- sum( temp1 & temp2) /n.sim - stagealpha
return(result)
}
ct2.L[k] <- uniroot(f, crange, tol=0.001)$root
ct2.U[k] <- -ct2.L[k]
}
}
}
simdata0 <- data.frame(matrix(0,n.sim*K,3))
colnames(simdata0)<- c("stage", "t.L", "t.U")
x1 <- matrix(rnorm(n1*n.sim, 0, sigma), n.sim, n1)
x2 <- matrix(rnorm(n2*n.sim, theta, sigma), n.sim, n2)
for(k in 1:K){
x1.stage <- x1[,1:nn1[k]]
mean1.temp <- apply(x1.stage, 1, mean)
v1.temp <- apply(x1.stage, 1, var)
x2.stage <- x2[,1:nn2[k]]
mean2.temp <- apply(x2.stage, 1, mean)
v2.temp <- apply(x2.stage, 1, var)
v.pool <- (v1.temp*(nn1[k]-1)+ v2.temp*(nn2[k]-1))/(nn1[k]+ nn2[k]-2)
se.pool <- sqrt(v.pool*(1/nn1[k]+1/nn2[k]))
diff <- mean2.temp - mean1.temp
t.L <- (diff - l) / se.pool
t.U <- (diff - u) / se.pool
simdata0[(k-1)*n.sim + 1:n.sim,] <- cbind(k, t.L, t.U)
}
dt2.L <- rep(999, K)
dt2.U <- rep(-999, K)
f <- function(x) {
temp1 <- simdata0[(simdata0$stage == 1),]$t.L <= x
temp2 <- simdata0[(simdata0$stage == 1),]$t.U >= -x
result <- sum( temp1 | temp2) / n.sim - II.vec[1]
return(result)
}
dt2.L[1] <- uniroot(f , drange, tol=0.001)$root
dt2.U[1] <- -dt2.L[1]
for (k in 2:K) {
stagebeta <- II.vec[k] - II.vec[k-1]
temp1 <- (simdata0[(simdata0$stage == k - 1),]$t.L > ct2.L[k - 1])
temp2 <- (simdata0[(simdata0$stage == k - 1),]$t.U < ct2.U[k - 1])
temp3 <- (simdata0[(simdata0$stage == k - 1),]$t.L <= dt2.L[k - 1])
temp4 <- (simdata0[(simdata0$stage == k - 1),]$t.U >= dt2.U[k - 1])
stop.prev <- (temp1 & temp2) | temp3 | temp4
if(any(is.na(stop.prev))) stop.prev[is.na(stop.prev)] <- TRUE
if(all(stop.prev)){
dt2.L<- dt2.L[1:(k-1)]
dt2.U<- dt2.U[1:(k-1)]
break
}
else {
simdata0.k <- simdata0[simdata0$stage == k,];
simdata0.k[stop.prev,]$t.L <- NA
simdata0.k[stop.prev,]$t.U <- NA
left.k <- simdata0.k[!is.na(simdata0.k$t.L),]
f <- function(x) {
temp1 <- left.k$t.L <= x
temp2 <- left.k$t.U >= -x
result <- sum(temp1 | temp2) / n.sim - stagebeta
return(result)
}
if(nrow(left.k) >= stagebeta*n.sim){
dt2.L[k] <- uniroot(f, drange, tol=0.001)$root
dt2.U[k] <- -dt2.L[k]
}
else break;
}
}
if(force & !any(dt2.L==999)) {dt2.L[K]<- ct2.L[K]; dt2.U[K]<- ct2.U[K]}
result <- list(typeI= I.vec, typeII= II.vec, equivL=ct2.L, equivU=ct2.U, futilL=dt2.L, futilU=dt2.U)
if(plot){
if(K<=3) par(mfrow=c(1,K), mar=c(4,2,1,1), ask=T)
else if(K==4) par(mfrow=c(2,2), mar=c(4,2,1,1), ask=T)
else if(K>=5 & K<=6) par(mfrow=c(2,3), mar=c(4,2,1,1), ask=T)
figureEF(result, K, ll, ul)
}
return(result)
} |
options(na.action=na.exclude)
options(contrasts=c('contr.treatment', 'contr.poly'))
library(survival)
aeq <- function(x,y, ...) all.equal(as.vector(x), as.vector(y), ...)
fit1 <- survreg(Surv(futime, fustat) ~ age + ecog.ps, ovarian)
fit4 <- survreg(Surv(log(futime), fustat) ~age + ecog.ps, ovarian,
dist='extreme')
print(fit1)
summary(fit4)
if (exists('censorReg')) {
fit2 <- censorReg(censor(futime, fustat) ~ age + ecog.ps, ovarian)
fit3 <- survreg(Surv(futime, fustat) ~ age + ecog.ps, ovarian,
iter=0, init=c(fit2$coef, log(fit2$scale)))
aeq(resid(fit2, type='working')[,1], resid(fit3, type='working'))
aeq(resid(fit2, type='response')[,1], resid(fit3, type='response'))
temp <- sign(resid(fit3, type='working'))
aeq(resid(fit2, type='deviance')[,1],
temp*abs(resid(fit3, type='deviance')))
aeq(resid(fit2, type='deviance')[,1], resid(fit3, type='deviance'))
}
aeq(fit1$coef, fit4$coef)
resid(fit1, type='working')
resid(fit1, type='response')
resid(fit1, type='deviance')
resid(fit1, type='dfbeta')
resid(fit1, type='dfbetas')
resid(fit1, type='ldcase')
resid(fit1, type='ldresp')
resid(fit1, type='ldshape')
resid(fit1, type='matrix')
aeq(resid(fit1, type='working'),resid(fit4, type='working'))
aeq(resid(fit1, type='deviance'), resid(fit4, type='deviance'))
aeq(resid(fit1, type='dfbeta'), resid(fit4, type='dfbeta'))
aeq(resid(fit1, type='dfbetas'), resid(fit4, type='dfbetas'))
aeq(resid(fit1, type='ldcase'), resid(fit4, type='ldcase'))
aeq(resid(fit1, type='ldresp'), resid(fit4, type='ldresp'))
aeq(resid(fit1, type='ldshape'), resid(fit4, type='ldshape'))
aeq(resid(fit1, type='matrix'), resid(fit4, type='matrix'))
fit1 <- survreg(Surv(time, status) ~ temp, data=imotor)
summary(fit1)
predict(fit1, data.frame(temp=130), type='uquantile', p=c(.5, .1), se=T)
fit2 <- survreg(Surv(time, status) ~ temp, data=imotor, scale=fit1$scale)
predict(fit2, data.frame(temp=130), type='uquantile', p=c(.5, .1), se=T)
fit3 <- fit2
fit3$var <- fit1$var[1:2,1:2]
predict(fit3, data.frame(temp=130), type='uquantile', p=c(.5, .1), se=T)
pp <- seq(.05, .7, length=40)
xx <- predict(fit1, data.frame(temp=130), type='uquantile', se=T,
p=pp)
fit1 <- survreg(Surv(time, status) ~ inst + strata(inst) + age + sex, lung)
qq1 <- predict(fit1, type='quantile', p=.3, se=T)
qq2 <- predict(fit1, type='quantile', p=c(.2, .3, .4), se=T)
aeq <- function(x,y) all.equal(as.vector(x), as.vector(y))
aeq(qq1$fit, qq2$fit[,2])
aeq(qq1$se.fit, qq2$se.fit[,2])
qq3 <- predict(fit1, type='quantile', p=c(.2, .3, .4), se=T,
newdata= lung[1:5,])
aeq(qq3$fit, qq2$fit[1:5,])
qq4 <- predict(fit1, type='quantile', p=c(.2, .3, .4), se=T, newdata=lung[7,])
aeq(qq4$fit, qq2$fit[7,])
qq5 <- predict(fit1, type='quantile', p=c(.2, .3, .4), se=T, newdata=lung)
aeq(qq2$fit, qq5$fit)
aeq(qq2$se.fit, qq5$se.fit) |
test.fTHETA =
function()
{
slotNames("fTHETA")
return()
}
test.thetaSim =
function()
{
x = thetaSim("max")
class(x)
print(x)
x = thetaSim("pair")
class(x)
print(x)
return()
}
test.thetaFit =
function()
{
x.ts = thetaSim("max", n=22000)
class(x.ts)
blockTheta(x.ts)
clusterTheta(x.ts)
runTheta(x.ts)
ferrosegersTheta(x.ts)
x.vec = as.vector(x.ts)
blockTheta(x.vec)
clusterTheta(x.vec)
runTheta(x.vec)
ferrosegersTheta(x.vec)
x.tS = as.timeSeries(x.ts)
blockTheta(x.tS)
clusterTheta(x.tS)
runTheta(x.tS)
ferrosegersTheta(x.tS)
return()
}
test.exindexesPlot =
function()
{
par(mfrow = c(2, 2), cex = 0.7)
par(ask = FALSE)
x = thetaSim("max", n = 22000)
exindexesPlot(x)
y = thetaSim("pair", n = 22000)
exindexesPlot(y)
return()
}
test.exindexPlot =
function()
{
par(mfrow = c(2, 2), cex = 0.7)
par(ask = FALSE)
x = thetaSim("max", n=22000)
exindexPlot(x, block = 22)
y = thetaSim("pair", n=22000)
exindexPlot(y, block = 22)
return()
} |
community_structure <- function(df,
time.var = NULL,
abundance.var,
replicate.var = NULL,
metric = c("Evar", "SimpsonEvenness", "EQ")) {
metric <- match.arg(metric)
if(any(is.na(df[[abundance.var]]))) stop("Abundance column contains missing values")
if(is.null(replicate.var)) {
by <- time.var
} else if(is.null(time.var)) {
by <- replicate.var
} else {
by <- c(time.var, replicate.var)
}
evenness <- get(metric)
comstruct <- aggregate.data.frame(df[abundance.var], df[by],
FUN = function(x) cbind(S(x), evenness(x)))
comstruct <- do.call(data.frame, comstruct)
if (any(is.na(comstruct[[paste(abundance.var, 2, sep = ".")]]))) {
warning("Evenness values contain NAs because there are plots with only one species")
}
names(comstruct) <- c(by, 'richness', metric)
return(comstruct)
}
SimpsonEvenness <- function(x, S = length(x[x != 0]), N = sum(x[x != 0]), ps = x[x != 0]/N, p2 = ps*ps ){
D <- sum(p2)
(1/D)/S
}
EQ <- function(x){
x1 <- x[x != 0]
if (length(x1) == 1) {
return(NA)
}
if (abs(max(x1) - min(x1)) < .Machine$double.eps^0.5) {
return(1)
}
r <- rank(-x1, ties.method = "average")
r_scale <- r/max(r)
x_log <- log(x1)
fit <- lm(r_scale~x_log)
b <- fit$coefficients[[2]]
-2/pi*atan(b)
} |
prepare_id_level_evaluation <- function(data,
target_col,
prediction_cols,
family,
id_col,
id_method,
groups_col,
cutoff = NULL,
apply_softmax = length(prediction_cols) > 1,
new_prediction_col_name = "prediction",
new_std_col_name = "std") {
if (is.null(id_col)) {
stop("'id_col' was NULL.")
}
if (!is.character(id_col)) {
stop("'id_col' must be either the name of a column in 'data' or NULL.")
}
if (id_col %ni% colnames(data)) {
stop(paste0("could not find 'id_col', ", id_col, ", in 'data'."))
}
if (isTRUE(apply_softmax)) {
if (length(prediction_cols) < 2) {
stop("can only apply softmax when there are more than one 'prediction_cols'.")
}
data <- softmax(data, cols = prediction_cols)
}
if (family == "binomial") {
if (is.null(cutoff)) {
stop("when 'family' is 'binomial', 'cutoff' must be numeric between 0 and 1.")
}
if (is.null(cutoff)) {
stop("when 'family' is 'binomial', 'cutoff' must be numeric between 0 and 1.")
}
}
num_groups <- length(unique(data[[groups_col]]))
id_classes <-
extract_id_classes(
data = data,
groups_col = groups_col,
id_col = id_col,
target_col = target_col
)
if (id_method == "mean") {
data_for_id_evaluation <- data %>%
dplyr::group_by(!!as.name(groups_col), !!as.name(id_col))
data_for_id_evaluation_mean <- data_for_id_evaluation %>%
dplyr::summarise_at(dplyr::vars(prediction_cols), .funs = mean)
data_for_id_evaluation_std <- data_for_id_evaluation %>%
dplyr::summarise_at(dplyr::vars(prediction_cols), .funs = sd)
colnames(data_for_id_evaluation_std) <- ifelse(
colnames(data_for_id_evaluation_std) %in% prediction_cols,
paste0(colnames(data_for_id_evaluation_std), "_STD"),
colnames(data_for_id_evaluation_std)
)
data_for_id_evaluation <- data_for_id_evaluation_mean %>%
dplyr::left_join(data_for_id_evaluation_std,
by = c(groups_col, id_col)) %>%
dplyr::left_join(id_classes, by = c(id_col, groups_col)) %>%
dplyr::ungroup()
} else if (id_method == "majority") {
if (family == "multinomial") {
data[["predicted_class_index"]] <- data %>%
base_select(cols = prediction_cols) %>%
argmax()
data[["predicted_class"]] <- purrr::map_chr(
data[["predicted_class_index"]],
.f = function(x) {
prediction_cols[[x]]
}
)
data_majority_count_by_id <- data %>%
dplyr::group_by(!!as.name(groups_col), !!as.name(id_col)) %>%
dplyr::count(.data$predicted_class) %>%
dplyr::left_join(id_classes, by = c(id_col, groups_col)) %>%
dplyr::ungroup()
classes_to_add <- setdiff(
prediction_cols,
data_majority_count_by_id[["predicted_class"]]
)
if (length(classes_to_add) > 0) {
na_cols <- dplyr::bind_rows(setNames(rep(
list(rep(NA, num_groups * nlevels(factor(data_majority_count_by_id[[id_col]])))),
length(classes_to_add)
), classes_to_add))
}
majority_vote_probabilities <- data_majority_count_by_id %>%
tidyr::spread(key = "predicted_class", value = "n")
if (length(classes_to_add) > 0) {
majority_vote_probabilities <- majority_vote_probabilities %>%
dplyr::bind_cols(na_cols) %>%
base_select(cols = c(groups_col, id_col, target_col, prediction_cols))
}
majority_vote_probabilities[is.na(majority_vote_probabilities)] <- 0
majority_vote_probabilities <- majority_vote_probabilities %>%
dplyr::mutate_at(prediction_cols, function(x) {
(x / (x + 1e-30)) * 1e+4
})
data_for_id_evaluation <- majority_vote_probabilities %>%
dplyr::ungroup()
} else if (family == "binomial") {
if (length(prediction_cols) > 1) {
stop("when 'family' is 'binomial', length of 'prediction_cols' should be 1.")
}
data[["predicted_class"]] <- ifelse(data[[prediction_cols]] > cutoff, 1, 0)
data_for_id_evaluation <- data %>%
dplyr::group_by(!!as.name(groups_col), !!as.name(id_col)) %>%
dplyr::summarise(mean_prediction = mean(.data$predicted_class)) %>%
dplyr::mutate(mean_prediction = dplyr::case_when(
mean_prediction > cutoff ~ 1 - 1e-40,
mean_prediction == cutoff ~ cutoff,
mean_prediction < cutoff ~ 1e-40
)) %>%
dplyr::rename_at("mean_prediction", ~prediction_cols) %>%
dplyr::left_join(id_classes, by = c(id_col, groups_col)) %>%
dplyr::ungroup()
} else {
stop(paste0("family ", family, " not currently supported for majority vote aggregated ID evaluation."))
}
}
if (family == "multinomial") {
data_for_id_evaluation <- prepare_multinomial_evaluation(
data_for_id_evaluation,
target_col = target_col,
prediction_cols = prediction_cols,
apply_softmax = TRUE,
new_prediction_col_name = new_prediction_col_name,
new_std_col_name = new_std_col_name
)
} else {
if (id_method == "mean"){
data_for_id_evaluation <- data_for_id_evaluation %>%
base_rename(before = paste0(prediction_cols, "_STD"),
after = new_std_col_name)
}
}
data_for_id_evaluation
}
prepare_multinomial_evaluation <- function(data,
target_col,
prediction_cols,
apply_softmax,
new_prediction_col_name,
new_std_col_name) {
col_split <- extract_and_remove_probability_cols(
data = data,
prediction_cols = prediction_cols
)
predicted_probabilities <- col_split[["predicted_probabilities"]]
standard_deviations <- col_split[["standard_deviations"]]
data <- col_split[["data"]]
if (isTRUE(apply_softmax)) {
predicted_probabilities <- softmax(predicted_probabilities)
}
data[[new_prediction_col_name]] <- predicted_probabilities %>%
nest_rowwise()
if (!is.null(standard_deviations)){
data[[new_std_col_name]] <- standard_deviations %>%
nest_rowwise()
}
if (length(setdiff(levels_as_characters(data[[target_col]]), prediction_cols)) > 0) {
stop("Not all levels in 'target_col' was found in 'prediction_cols'.")
}
data
}
extract_and_remove_probability_cols <- function(data, prediction_cols) {
predicted_probabilities <- data %>%
base_select(cols = prediction_cols)
data <- data %>%
base_deselect(cols = prediction_cols)
if (paste0(prediction_cols[[1]], "_STD") %in% colnames(data)){
standard_deviations <- data %>%
base_select(cols = paste0(prediction_cols, "_STD"))
data <- data %>%
base_deselect(cols = colnames(standard_deviations))
colnames(standard_deviations) <- prediction_cols
} else {
standard_deviations <- NULL
}
if (any(!sapply(predicted_probabilities, is.numeric))) {
stop("the prediction columns must be numeric.")
}
if (any(!sapply(standard_deviations, is.numeric))) {
stop("the standard deviation columns must be numeric.")
}
list(
"data" = data,
"predicted_probabilities" = predicted_probabilities,
"standard_deviations" = standard_deviations
)
}
extract_id_classes <- function(data, groups_col, id_col, target_col) {
id_classes <- data %>%
base_select(cols = c(groups_col, id_col, target_col)) %>%
dplyr::distinct()
check_constant_targets_within_ids(
distinct_data = id_classes,
groups_col = groups_col,
id_col = id_col
)
id_classes
}
check_constant_targets_within_ids <- function(distinct_data, groups_col, id_col) {
counts <- distinct_data %>%
dplyr::group_by(!!as.name(groups_col), !!as.name(id_col)) %>%
dplyr::summarize(n = dplyr::n())
if (any(counts$n > 1)) {
non_constant_ids <- counts %>%
dplyr::filter(.data$n > 1) %>%
dplyr::pull(!!as.name(id_col))
stop(paste0(
"The targets must be constant within the IDs with the current ID method. ",
"These IDs had more than one unique value in the target column: ",
paste0(head(non_constant_ids, 5),
collapse = ", "
),
ifelse(length(non_constant_ids) > 5, ", ...", ""),
"."
))
}
} |
liptak <-
function(p) { sum(pnorm(1-p)) } |
library(testthat)
library(iMRMC)
context("uStat11")
init.lecuyerRNG()
flagSave <- FALSE
if (flagSave) {
saveResult <- list()
}
simRoeMetz.config <- sim.gRoeMetz.config()
simRoeMetz.config$nR <- 8
simRoeMetz.config$nC.neg <- 38
simRoeMetz.config$nC.pos <- 38
df.MRMC <- sim.gRoeMetz(simRoeMetz.config)
df <- undoIMRMCdf(df.MRMC)
df <- droplevels(df[grepl("pos", df$caseID), ])
readers <- levels(df$readerID)
nR <- nlevels(df$readerID)
cases <- levels(df$caseID)
nC <- nlevels(df$caseID)
nG <- 3
readerGroups <- createGroups(readers, nG)
names(readerGroups) <- c("readerID", "readerGroup")
df <- merge(df, readerGroups)
caseGroups <- createGroups(cases, nG)
names(caseGroups) <- c("caseID", "caseGroup")
df <- merge(df, caseGroups)
df <- df[df$caseGroup == df$readerGroup, ]
df <- df[!(df$readerID == "reader5" & df$modalityID == "testA"), ]
df <- df[!(df$caseID == "posCase5" & df$modalityID == "testB"), ]
dA <- convertDFtoDesignMatrix(df, modality = "testA", dropFlag = FALSE)
dB <- convertDFtoDesignMatrix(df, modality = "testB", dropFlag = FALSE)
image(dA)
image(dB)
result.jointD.identity <- uStat11.jointD(
df,
kernelFlag = 1,
keyColumns = c("readerID", "caseID", "modalityID", "score"),
modalitiesToCompare = c("testA", "testB"))
cat("\n")
cat("uStat11.jointD.identity \n")
print(result.jointD.identity[1:2])
if (flagSave) {
saveResult$jointD.identity <- result.jointD.identity
}
result.conditionalD.identity <- uStat11.conditionalD(
df,
kernelFlag = 1,
keyColumns = c("readerID", "caseID", "modalityID", "score"),
modalitiesToCompare = c("testA", "testB"))
cat("\n")
cat("uStat11.conditionalD.identity \n")
print(result.conditionalD.identity[1:2])
if (flagSave) {
saveResult$conditionalD.identity <- result.conditionalD.identity
}
result.jointD.diff <- uStat11.jointD(
df,
kernelFlag = 2,
keyColumns = c("readerID", "caseID", "modalityID", "score"),
modalitiesToCompare = c("testA", "testB", "testB", "testA"))
cat("\n")
cat("uStat11.jointD.diff \n")
print(result.jointD.diff[1:2])
if (flagSave) {
saveResult$jointD.diff <- result.jointD.diff
}
result.conditionalD.diff <- uStat11.conditionalD(
df,
kernelFlag = 2,
keyColumns = c("readerID", "caseID", "modalityID", "score"),
modalitiesToCompare = c("testA", "testB", "testB", "testA"))
cat("\n")
cat("uStat11.conditionalD.diff \n")
print(result.conditionalD.diff[1:2])
if (flagSave) {
saveResult$conditionalD.diff <- result.conditionalD.diff
}
fileName <- "test_uStat11_splitPlot.Rdata"
if (flagSave) {
save(saveResult, file = file.path("tests", "testthat", fileName))
}
saveResult <- 0
if (!file.exists(fileName)) {
fileName <- file.path("tests", "testthat", fileName)
}
load(fileName)
test_that(
"uStat11.jointD, difference kernel, doesn't change", {
expect_equal(saveResult$jointD.diff, result.jointD.diff,tolerance=1e-5)
}
)
test_that(
"uStat11.conditionalD, difference kernel, doesn't change", {
expect_equal(saveResult$conditionalD.diff, result.conditionalD.diff,tolerance=1e-5)
}
)
test_that(
"uStat11.jointD, identity kernel, doesn't change", {
expect_equal(saveResult$jointD.identity, result.jointD.identity,tolerance=1e-5)
}
)
test_that(
"uStat11.conditionalD, identity kernel, doesn't change", {
expect_equal(saveResult$conditionalD.identity, result.conditionalD.identity,tolerance=1e-5)
}
) |
`FromSymmetricStorageUpper` <-
function(x){
n<-floor((-1+sqrt(1+8*length(x)))/2)
z<-matrix(numeric(n^2), nrow=n)
i<-as.vector(lower.tri(z,diag=TRUE))
z[i]<-x
ztranspose<-t(z)
diag(ztranspose)<-0
z+ztranspose
} |
getForm <- function (tree, ...) {
UseMethod("getForm", tree)
}
getForm.data.frame <- function(tree, inv = NULL, mapping = NULL, ...){
tree <- buildTree(tree,
check = "form",
vars = inv,
mapping = mapping)
getForm(tree, inv = inv, mapping = mapping)
}
getForm.list <- function(tree, inv = NULL, mapping = NULL, ...){
tree <- buildTree(tree,
check = "form",
vars = inv,
mapping = mapping)
getForm(tree, inv = inv, mapping = mapping)
}
getForm.datBDAT <- function(tree, inv = NULL, mapping = NULL, ...) {
if (!("datBDAT.form" %in% class(tree)) | !is.null(inv)) {
tree <- buildTree(tree, check = "form", vars = inv, mapping = mapping)
}
if ("datBDAT.form" %in% class(tree)) {
n <- nrow(tree)
if (n >= 1) {
res <- as.vector(
.Fortran("vbdatformtarif",
n = as.integer(n),
vTarif = as.integer(tree$inv),
vBDATBArtNr = as.integer(tree$spp),
vD = as.single(tree$D13),
vH = as.single(tree$H),
vMwQ03BWI = as.single(rep(0, n))
)$vMwQ03BWI
)
} else {
res <- 0
}
}
return(res)
} |
download_wos <- function(query_result, ...) {
rec_cnt <- query_result$rec_cnt
if (rec_cnt >= 100000) {
stop(
"Can't download result sets that have 100,000 or more records.
Try breaking your query into pieces using the PY tag
(see FAQs at https://vt-arc.github.io/wosr/articles/faqs.html
)
}
if (rec_cnt == 0) return(NA)
from <- seq(1, to = rec_cnt, by = 100)
count <- rep(100, times = length(from))
count[length(count)] <- rec_cnt - from[length(count)] + 1
pbapply::pblapply(seq_len(length(from)), function(x, ...) {
response <- one_pull(
query_result$query_id,
first_record = from[x],
count = count[x],
sid = query_result$sid,
...
)
check_resp(response)
response
})
}
one_pull <- function(query_id, first_record, count, sid, ...) {
body <- paste0(
'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:retrieve xmlns:ns2="http://woksearch.v3.wokmws.thomsonreuters.com">
<queryId>', query_id, '</queryId>
<retrieveParameters>
<firstRecord>', first_record, '</firstRecord>
<count>', count, '</count></retrieveParameters>
</ns2:retrieve>
</soap:Body>
</soap:Envelope>'
)
for (i in 1:3) {
response <- wok_search(body, sid, ...)
if (httr::http_error(response)) {
er <- parse_er(response)
if (grepl("throttle", er, ignore.case = TRUE)) {
Sys.sleep(1)
}
} else {
return(response)
}
}
response
}
wok_search <- function(body, sid, ...) {
httr::POST(
"http://search.webofknowledge.com/esti/wokmws/ws/WokSearch",
body = body,
httr::add_headers("cookie" = paste0("SID=", sid)),
ua(),
...
)
} |
dreg <- function(data,y,x=NULL,z=NULL,x.oneatatime=TRUE,
x.base.names=NULL,z.arg=c("clever","base","group","condition"),
fun.=lm,summary.=summary,regex=FALSE,convert=NULL,doSummary=TRUE,
special=NULL,equal=TRUE,test=1,...) {
yxzf <- procform(y,x=x,z=z,data=data,do.filter=FALSE,regex=regex)
yxz <- procformdata(y,x=x,z=z,data=data,do.filter=FALSE,regex=regex)
if (any(yxzf$predictor==""))
yxzf$predictor <- yxzf$predictor[-which(yxzf$predictor=="")]
yy <- yxz$response
xx <- yxz$predictor
if ((length(yxzf$filter))==0) zz <- NULL else if ((length(yxzf$filter[[1]])==1 & yxzf$filter[[1]][1]=="1"))
zz <- NULL else zz <- yxz$group[[1]]
if (!is.null(zz)) {
if (z.arg[1]=="clever")
{
if ((ncol(zz)==1) & is.logical(zz[1,1])) z.arg[1] <- "condition"
else if ((ncol(zz)==1) & is.factor(zz[,1])) z.arg[1] <- "group"
else z.arg[1] <- "base"
}
}
basen <- NULL
if (z.arg[1]=="base")
basen <- yxzf$filter[[1]]
if (z.arg[1]=="condition")
data <- subset(data,eval(yxzf$filter.expression))
if (z.arg[1]=="group")
group <- interaction(zz) else group <- rep(1,nrow(data))
if (z.arg[1]=="group") levell <- levels(group) else levell <-1
res <- sum <- list()
if (test==1) {
if (is.null(summary)) sum <- NULL
for (g in levell) {
if (equal==TRUE) datal <- subset(data,group==g)
else datal <- subset(data,group!=g)
for (y in yxzf$response) {
if (x.oneatatime) {
for (x in yxzf$predictor) {
if (length(c(x,basen))>1)
basel <- paste(c(x,basen),collapse="+")
else basel <- c(x,basen)
form <- as.formula(paste(y,"~",basel))
if (!is.null(special)) form <- timereg::timereg.formula(form,special=special)
val <- do.call(fun.,c(list(formula=form),list(data=datal),list(...)))
val <- list(val)
nn <- paste(y,"~",basel)
if (z.arg[1]=="group") {
if (equal==TRUE) nn <- paste(nn,"|",g) else nn <- paste(nn,"| not",g);
}
names(val) <- nn
val[[1]]$call <- nn
res <- c(res, val)
if (doSummary) {
sval <- list(do.call(summary.,list(val[[1]])))
names(sval) <- nn
sum <- c(sum, sval)
}
}
} else {
basel <- paste(c(yxzf$predictor,basen),collapse="+")
form <- as.formula(paste(y,"~",basel))
if (!is.null(special)) form <- timereg::timereg.formula(form,special=special)
val <- do.call(fun.,c(list(formula=form),list(data=datal),list(...)))
nn <- paste(y,"~",basel)
if (z.arg[1]=="group") {
if (equal==TRUE) nn <- paste(nn,"|",g) else nn <- paste(nn,"| not",g);
}
val <- list(val)
names(val) <- paste(y,"~",basel)
val[[1]]$call <- nn
res <- c(res, val)
if (doSummary) {
sval <- list(do.call(summary.,list(val[[1]])))
names(sval) <- nn
sum <- c(sum, sval)
}
}
}
}
}
res <- list(reg=res,summary=sum)
class(res) <- "dreg"
return(res)
}
print.dreg <- function(x,sep="-",...) {
sep <- paste(rep(sep,50,sep=""),collapse="")
sep <- paste(sep,"\n")
nn <- names(x$reg)
for (i in seq_along(x$reg)) {
cat(paste("Model=",nn[i],"\n"))
print(x$reg[[i]],...)
cat(sep)
}
}
summary.dreg <- function(object,sep="-",...) {
x <- object
sep <- paste(rep(sep,50,sep=""),collapse="")
sep <- paste(sep,"\n")
if (!is.null(x$summary)) {
nn <- names(x$summary)
for (i in seq_along(x$summary)) {
cat(paste("Model=",nn[i],"\n"))
if (!is.null(x$summary))
print(x$summary[[i]],...)
else print(x$reg[[i]],...)
cat(sep)
}
}
} |
pred_ints_exact <-function(object,
l_quant,u_quant,newdata=NULL,
num_cores=1,
root_alg_precision=0.00001){
if(is.null(newdata) && length(object)==16){
ret<-pred_ints_exact_outsamp(object$sumoftrees,object$obs_to_termNodesMatrix,object$response,object$bic,
object$nrowTrain,
nrow(object$test_data),object$a,object$sigma,0,object$nu,
object$lambda,
object$test_data,l_quant,u_quant,num_cores,root_alg_precision
)
}else{if(is.null(newdata) && length(object)==14){
stop("Code not yet written for insample")
}else{
ret<-pred_ints_exact_outsamp(object$sumoftrees,object$obs_to_termNodesMatrix,object$response,object$bic,
object$nrowTrain,
nrow(newdata), object$a,object$sigma,0,object$nu,
object$lambda,
newdata,l_quant,u_quant,num_cores,root_alg_precision
)
}}
names(ret) <- c("PI", "meanpreds")
class(ret)<-"pred_intervals.bartBMA"
ret
} |
simulate.uniNmix <-
function(object, ...) {
parms <- coef(object)
np1 <- ncol(object$Xp)
nl1 <- ncol(object$Xl)
pr1 <- as.numeric(plogis(object$Xp %*% parms[1:np1]))
lam1 <- as.numeric(exp(object$Xl %*% parms[(np1+1):(np1+nl1)]))
if(object$mixture=="NB") theta1 <- exp(parms[(np1+nl1+1)])
if(object$mixture=="NeymanA") lam2 <- exp(parms[(np1+nl1+1)])
R <- dim(object$sp1)[1]
T_ <- dim(object$sp1)[2]
pr1 <- matrix(pr1, byrow=TRUE, ncol=T_)
if(object$mixture=="P") Ni1 <- rpois(R, lam1)
if(object$mixture=="NB") Ni1 <- rnbinom(R, mu=lam1, size=theta1)
if(object$mixture=="NeymanA") {
NN <- rpois(R, lam1)
Ni1 <- rpois(R, lam2 * NN)
}
sdata1 <- matrix(0, ncol=T_, nrow=R)
for(i in 1:T_) sdata1[,i] <- rbinom(R, Ni1, pr1[,i])
return(list("sp1"=sdata1))
} |
nB<-10^5
ns<-c(100, 200, 500, 1000, 2000)
HS<-c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
oneSimulation<-function(ns, HS){
nns<-length(ns)
nHS<-length(HS)
H<-numeric(nns*nHS)
ij<-0
for (i in 1:length(ns)){
n<-ns[i]
for (j in 1:length(HS)){
ij<-ij+1
H0<-HS[j]
z<-SimulateFGN(n, H0)
H[ij]<-GetFitFGN(z)$H
}
}
H
}
library(Rmpi)
mpi.spawn.Rslaves()
mpi.bcast.Robj2slave(ns)
mpi.bcast.Robj2slave(HS)
mpi.bcast.Robj2slave(oneSimulation)
mpi.bcast.cmd(library(FGN))
mpi.setup.rngstream(19480813)
startTime<-proc.time()
out <- mpi.parReplicate(nB, oneSimulation(ns=ns, HS=HS))
averVarH <- apply(out, 1, var)
endTime<-proc.time()
totalTime<-endTime-startTime
totalTime<-(totalTime/3600)[3]
tb<-rep(ns, rep(length(HS),length(ns)))*averVarH
tb<-matrix(tb, ncol=length(ns))
dimnames(tb)<-list(HS,ns)
save(tb, out, totalTime, file="tbVarH.R")
print(paste("Completed Var HHat Simulations. Elapsed Time = ", totalTime , "Hours"))
print(paste("nB = ",nB))
print(tb)
mpi.close.Rslaves()
mpi.quit() |
simSample <- function(x, design = character(), grouping = character(),
collect = FALSE, fun = srs, size = NULL,
prob = NULL, ..., k = 1) {
control <- SampleControl(design=design, grouping=grouping,
collect=collect, fun=fun, size=size, prob=prob, dots=list(...), k=k)
res <- setup(x, control)
call <- match.call()
setCall(res, call)
res
} |
cranPlot <- function(x, statistic, graphics, points, log.count, smooth, se, f,
span, r.version) {
dat <- x$cranlogs.data
last.obs.date <- x$last.obs.date
if (statistic == "count") {
y.nm.case <- "Count"
y.nm <- tolower(y.nm.case)
} else if (statistic == "cumulative") {
y.nm.case <- "Cumulative"
y.nm <- tolower(y.nm.case)
}
type <- ifelse(points, "o", "l")
if (graphics == "base") {
if (any(dat$in.progress)) {
ip.sel <- dat$in.progress == TRUE
ip.data <- dat[ip.sel, ]
complete.data <- dat[!ip.sel, ]
last.obs <- nrow(complete.data)
obs.days <- as.numeric(format(last.obs.date , "%d"))
exp.days <- as.numeric(format(ip.data[, "date"], "%d"))
est.ct <- round(ip.data$count * exp.days / obs.days)
est.data <- ip.data
est.data$count <- est.ct
last.cumulative <- complete.data[nrow(complete.data), "cumulative"]
est.data$cumulative <- last.cumulative + est.ct
xlim <- range(dat$date)
if (statistic == "count") {
ylim <- range(c(dat[, y.nm], est.data$count))
} else if (statistic == "cumulative") {
ylim <- range(c(dat[, y.nm], est.data$cumulative))
}
if (log.count) {
plot(complete.data$date, complete.data[, y.nm], type = type,
xlab = "Date", ylab = paste0("log10 ", y.nm.case), xlim = xlim,
ylim = ylim, log = "y", pch = 16)
} else {
plot(complete.data$date, complete.data[, y.nm], type = type,
xlab = "Date", ylab = y.nm.case, xlim = xlim, ylim = ylim, pch = 16)
}
points(ip.data[, "date"], ip.data[, y.nm], col = "black", pch = 0)
points(est.data[, "date"], est.data[, y.nm], col = "red", pch = 0)
segments(complete.data[last.obs, "date"],
complete.data[last.obs, y.nm],
ip.data$date,
ip.data[, y.nm],
lty = "dotted")
segments(complete.data[last.obs, "date"],
complete.data[last.obs, y.nm],
est.data$date,
est.data[, y.nm],
col = "red")
axis(4, at = ip.data[, y.nm], labels = "obs")
axis(4, at = est.data[, y.nm], labels = "est", col.axis = "red",
col.ticks = "red")
} else {
if (log.count) {
plot(dat$date, dat[, y.nm], type = type, xlab = "Date",
ylab = paste0("log10 ", y.nm.case), log = "y")
} else {
plot(dat$date, dat[, y.nm], type = type, xlab = "Date",
ylab = paste0("log10 ", y.nm.case))
}
}
if (r.version) {
r_v <- rversions::r_versions()
axis(3, at = as.Date(r_v$date), labels = paste("R", r_v$version),
cex.axis = 2/3, padj = 0.9)
}
if (smooth) {
if (any(dat$in.progress)) {
smooth.data <- complete.data
lines(stats::lowess(smooth.data$date, smooth.data[, y.nm], f = f),
col = "blue")
} else {
lines(stats::lowess(dat$date, dat[, y.nm], f = f), col = "blue")
}
}
title(main = "Total Package Downloads")
} else if (graphics == "ggplot2") {
if (statistic == "count") {
p <- ggplot(data = dat, aes_string("date", "count"))
} else if (statistic == "cumulative") {
p <- ggplot(data = dat, aes_string("date", "cumulative"))
}
if (any(dat$in.progress)) {
ip.sel <- dat$in.progress == TRUE
ip.data <- dat[ip.sel, ]
complete.data <- dat[!ip.sel, ]
last.obs <- nrow(complete.data)
obs.days <- as.numeric(format(last.obs.date , "%d"))
exp.days <- as.numeric(format(ip.data[, "date"], "%d"))
est.ct <- round(ip.data$count * exp.days / obs.days)
est.data <- ip.data
est.data$count <- est.ct
last.cumulative <- complete.data[nrow(complete.data), "cumulative"]
est.data$cumulative <- last.cumulative + est.ct
est.seg <- rbind(complete.data[last.obs, ], est.data)
obs.seg <- rbind(complete.data[last.obs, ], ip.data)
p <- p + geom_line(data = complete.data, size = 1/3) +
geom_line(data = est.seg, size = 1/3, col = "red") +
geom_line(data = obs.seg, size = 1/3, linetype = "dotted") +
geom_point(data = est.data, col = "red", shape = 0) +
geom_point(data = ip.data, col = "black", shape = 0)
if (points) p <- p + geom_point(data = complete.data)
if (log.count) p <- p + scale_y_log10()
if (smooth) {
if (any(dat$in.progress)) {
smooth.data <- complete.data
p <- p + geom_smooth(data = smooth.data, method = "loess",
formula = "y ~ x", se = se, span = span)
} else {
p <- p + geom_smooth(method = "loess", formula = "y ~ x", se = se,
span = span)
}
}
} else {
p <- p + geom_line(size = 1/3)
if (points) p <- p + geom_point()
if (log.count) p <- p + scale_y_log10()
if (smooth) {
p <- p + geom_smooth(method = "loess", formula = "y ~ x", se = se,
span = span)
}
}
p <- p + theme_bw() +
ggtitle("Total Package Downloads") +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.title = element_text(hjust = 0.5))
suppressWarnings(print(p))
}
}
singlePlot <- function(x, statistic, graphics, obs.ct, points, smooth,
se, f, span, log.count, package.version, dev.mode, r.version, same.xy) {
dat <- x$cranlogs.data
last.obs.date <- x$last.obs.date
type <- ifelse(points, "o", "l")
if (statistic == "count") {
y.var <- dat$count
y.nm.case <- "Count"
y.nm <- tolower(y.nm.case)
ttl <- "Package Download Counts"
} else if (statistic == "cumulative") {
y.var <- dat$cumulative
y.nm.case <- "Cumulative"
y.nm <- tolower(y.nm.case)
ttl <- "Cumulative Package Downloads"
}
if (graphics == "base") {
if (obs.ct == 1) {
if (log.count) {
dotchart(log10(dat$count), labels = dat$package,
xlab = "log10 Count", main = paste(ttl, unique(dat$date)))
} else {
dotchart(dat$count, labels = dat$package, xlab = "Count",
main = paste(ttl, unique(dat$date)))
}
} else if (obs.ct > 1) {
if (same.xy) {
xlim <- range(dat$date)
} else {
xlim <- NULL
}
if (length(x$packages) > 1) grDevices::devAskNewPage(ask = TRUE)
if (any(dat$in.progress)) {
plot.data <- lapply(x$package, function(pkg) {
pkg.dat <- dat[dat$package == pkg, ]
ip.sel <- pkg.dat$in.progress == TRUE
ip.data <- pkg.dat[ip.sel, ]
complete.data <- pkg.dat[!ip.sel, ]
obs.days <- as.numeric(format(last.obs.date , "%d"))
exp.days <- as.numeric(format(ip.data[, "date"], "%d"))
est.ct <- round(ip.data$count * exp.days / obs.days)
est.data <- ip.data
est.data$count <- est.ct
last.cumulative <- complete.data[nrow(complete.data), "cumulative"]
est.data$cumulative <- last.cumulative + est.ct
list(complete.data = complete.data, ip.data = ip.data,
est.data = est.data)
})
tmp <- lapply(plot.data, function(x) do.call(rbind, x))
tmp <- do.call(rbind, tmp)
ylim <- range(tmp[, y.nm])
invisible(lapply(seq_along(plot.data), function(i) {
complete.data <- plot.data[[i]]$complete.data
ip.data <- plot.data[[i]]$ip.data
est.data <- plot.data[[i]]$est.data
if (log.count) {
plot(complete.data$date, complete.data[, y.nm], type = type,
xlab = "Date", ylab = paste0("log10 ", y.nm.case), xlim = xlim,
ylim = ylim, log = "y", pch = 16)
} else {
plot(complete.data$date, complete.data[, y.nm], type = type,
xlab = "Date", ylab = y.nm.case, xlim = xlim, ylim = ylim,
pch = 16)
}
points(ip.data[, "date"], ip.data[, y.nm], col = "black", pch = 0)
points(est.data[, "date"], est.data[, y.nm], col = "red", pch = 0)
last.obs <- nrow(complete.data)
segments(complete.data[last.obs, "date"],
complete.data[last.obs, y.nm],
ip.data$date,
ip.data[, y.nm],
lty = "dotted")
segments(complete.data[last.obs, "date"],
complete.data[last.obs, y.nm],
est.data$date,
est.data[, y.nm],
col = "red")
axis(4, at = ip.data[, y.nm], labels = "obs")
axis(4, at = est.data[, y.nm], labels = "est", col.axis = "red",
col.ticks = "red")
if (package.version) {
if (dev.mode) p_v <- packageHistory0(est.data$package)
else p_v <- packageHistory(est.data$package)
axis(3, at = p_v$Date, labels = p_v$Version, cex.axis = 2/3,
padj = 0.9, col.axis = "red", col.ticks = "red")
}
if (r.version) {
r_v <- rversions::r_versions()
axis(3, at = as.Date(r_v$date), labels = paste("R", r_v$version),
cex.axis = 2/3, padj = 0.9)
}
if (smooth) {
if (any(dat$in.progress)) {
smooth.data <- complete.data
lines(stats::lowess(smooth.data$date, smooth.data[, y.nm],
f = f), col = "blue")
} else {
lines(stats::lowess(dat$date, dat[, y.nm], f = f), col = "blue")
}
}
title(main = est.data$package)
}))
} else {
ylim <- range(dat[, y.nm])
invisible(lapply(x$package, function(pkg) {
pkg.dat <- dat[dat$package == pkg, ]
type <- ifelse(points, "o", "l")
if (log.count) {
plot(pkg.dat$date, pkg.dat[, y.nm], type = type, xlab = "Date",
ylab = paste0("log10 ", y.nm.case), log = "y", xlim = xlim,
ylim = ylim)
} else {
plot(pkg.dat$date, pkg.dat[, y.nm], type = type, xlab = "Date",
ylab = y.nm.case, xlim = xlim, ylim = ylim)
}
if (package.version) {
if (dev.mode) p_v <- packageHistory0(pkg)
else p_v <- packageHistory(pkg)
axis(3, at = p_v$Date, labels = p_v$Version, cex.axis = 2/3,
padj = 0.9, col.axis = "red", col.ticks = "red")
}
if (r.version) {
r_v <- rversions::r_versions()
axis(3, at = as.Date(r_v$date), labels = paste("R", r_v$version),
cex.axis = 2/3, padj = 0.9)
}
if (smooth) {
lines(stats::lowess(pkg.dat$date, pkg.dat[, y.nm], f = f),
col = "blue")
}
title(main = pkg)
}))
}
if (length(x$packages) > 1) grDevices::devAskNewPage(ask = FALSE)
}
} else if (graphics == "ggplot2") {
if (obs.ct == 1) {
p <- ggplot(data = dat) +
theme_bw() +
theme(panel.grid.major.x = element_blank(),
panel.grid.minor = element_blank()) +
facet_wrap(~ date, nrow = 2)
if (statistic == "count") {
p <- p + geom_point(aes_string("count", "package"), size = 1.5)
} else if (statistic == "cumulative") {
p <- p + geom_point(aes_string("cumulative", "package"), size = 1.5)
}
if (log.count) p <- p + scale_x_log10() + xlab("log10 Count")
} else if (obs.ct > 1) {
if (statistic == "count") {
p <- ggplot(data = dat, aes_string("date", "count"))
} else if (statistic == "cumulative") {
p <- ggplot(data = dat, aes_string("date", "cumulative"))
}
if (any(dat$in.progress)) {
g <- lapply(x$packages, function(pkg) {
pkg.data <- dat[dat$package == pkg, ]
ip.sel <- pkg.data$in.progress == TRUE
ip.data <- pkg.data[ip.sel, ]
complete.data <- pkg.data[!ip.sel, ]
last.obs <- nrow(complete.data)
obs.days <- as.numeric(format(last.obs.date , "%d"))
exp.days <- as.numeric(format(ip.data[, "date"], "%d"))
est.ct <- round(ip.data$count * exp.days / obs.days)
est.data <- ip.data
est.data$count <- est.ct
last.cumulative <- complete.data[nrow(complete.data), "cumulative"]
est.data$cumulative <- last.cumulative + est.ct
list(ip.data = ip.data,
complete.data = complete.data,
est.data = est.data,
est.seg = rbind(complete.data[last.obs, ], est.data),
obs.seg = rbind(complete.data[last.obs, ], ip.data))
})
ip.data <- do.call(rbind, lapply(g, function(x) x$ip.data))
complete.data <- do.call(rbind, lapply(g, function(x) x$complete.data))
est.data <- do.call(rbind, lapply(g, function(x) x$est.data))
est.seg <- do.call(rbind, lapply(g, function(x) x$est.seg))
obs.seg <- do.call(rbind, lapply(g, function(x) x$obs.seg))
p <- p + geom_line(data = complete.data, size = 1/3) +
geom_line(data = est.seg, size = 1/3, col = "red") +
geom_line(data = obs.seg, size = 1/3, linetype = "dotted") +
geom_point(data = est.data, colour = "red", shape = 0) +
geom_point(data = ip.data, colour = "black", shape = 0)
if (points) p <- p + geom_point(data = complete.data)
} else {
p <- p + geom_line(size = 1/3)
if (points) p <- p + geom_point()
}
if (log.count) p <- p + scale_y_log10()
if (smooth) {
if (any(dat$in.progress)) {
smooth.data <- complete.data
p <- p + geom_smooth(data = smooth.data, method = "loess",
formula = "y ~ x", se = se, span = span)
} else {
p <- p + geom_smooth(method = "loess", formula = "y ~ x", se = se,
span = span)
}
}
p <- p + facet_wrap(~ package, nrow = 2) +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
}
suppressWarnings(print(p))
}
}
multiPlot <- function(x, statistic, graphics, obs.ct, log.count, legend.loc,
points, smooth, se, f, span) {
dat <- x$cranlogs.data
last.obs.date <- x$last.obs.date
if (statistic == "count") {
ttl <- "Package Download Counts"
} else if (statistic == "cumulative") {
ttl <- "Cumulative Package Downloads"
}
if (graphics == "base") {
if (obs.ct == 1) {
if (log.count) {
dotchart(log10(dat$count), labels = dat$package, xlab = "log10 Count",
main = paste(ttl, unique(dat$date)))
} else {
dotchart(dat$count, labels = dat$package, xlab = "Count",
main = paste(ttl, unique(dat$date)))
}
} else if (obs.ct > 1) {
if (length(x$packages) > 8) {
stop('Use <= 8 packages when graphics = "base".', call. = FALSE)
} else {
cbPalette <- c("
"
token <- c(1, 0, 2:7)
vars <- c("date", statistic)
type <- ifelse(points, "o", "l")
xlim <- range(dat$date)
ylim <- range(dat[, statistic])
if (any(dat$in.progress)) {
pkg.data <- lapply(x$package, function(pkg) {
tmp <- dat[dat$package == pkg, ]
ip.data <- tmp[tmp$in.progress == TRUE, ]
complete.data <- tmp[tmp$in.progress == FALSE, ]
last.obs <- nrow(complete.data)
obs.days <- as.numeric(format(last.obs.date , "%d"))
exp.days <- as.numeric(format(ip.data[, "date"], "%d"))
est.ct <- round(ip.data$count * exp.days / obs.days)
est.data <- ip.data
est.data$count <- est.ct
last.cumulative <- complete.data[nrow(complete.data), "cumulative"]
est.data$cumulative <- last.cumulative + est.ct
list(complete.data = complete.data, est.data = est.data,
ip.data = ip.data)
})
est.stat <- lapply(pkg.data, function(x) x$est.data)
est.stat <- do.call(rbind, est.stat)[, statistic]
ylim <- range(c(ylim, est.stat))
if (log.count) {
plot(dat[, vars], pch = NA, log = "y", xlim = xlim, ylim = ylim,
main = ttl)
} else {
plot(dat[, vars], pch = NA, xlim = xlim, ylim = ylim, main = ttl)
}
invisible(lapply(seq_along(pkg.data), function(i) {
complete.data <- pkg.data[[i]]$complete.data
est.data <- pkg.data[[i]]$est.data
ip.data <- pkg.data[[i]]$ip.data
last.obs <- nrow(complete.data)
lines(complete.data$date, complete.data[, statistic],
col = cbPalette[i])
segments(complete.data[last.obs, "date"],
complete.data[last.obs, statistic],
ip.data$date,
ip.data[, statistic],
lty = "dotted")
segments(complete.data[last.obs, "date"],
complete.data[last.obs, statistic],
est.data$date,
est.data[, statistic],
col = cbPalette[i])
points(est.data[, "date"], est.data[, statistic], col = "red",
pch = token[i])
points(ip.data[, "date"], ip.data[, statistic],
col = "black", pch = token[i])
if (points) {
points(complete.data[, "date"], complete.data[, statistic],
col = cbPalette[i], pch = token[i])
}
if (smooth) {
smooth.data <- complete.data
lines(stats::lowess(smooth.data$date, smooth.data[, statistic],
f = f), col = cbPalette[i])
}
}))
} else {
if (log.count) {
plot(dat[, vars], pch = NA, log = "y", xlim = xlim, ylim = ylim,
main = ttl)
} else {
plot(dat[, vars], pch = NA, xlim = xlim, ylim = ylim, main = ttl)
}
invisible(lapply(seq_along(x$packages), function(i) {
tmp <- dat[dat$package == x$packages[i], ]
lines(tmp$date, tmp[, statistic], col = cbPalette[i])
if (points) {
points(tmp[, "date"], tmp[, statistic], col = cbPalette[i],
pch = token[i])
}
if (smooth) {
lines(stats::lowess(dat[dat$package == x$packages[i], vars],
f = f), col = cbPalette[i])
}
}))
}
id <- seq_along(x$packages)
legend(x = legend.loc,
legend = x$packages,
col = cbPalette[id],
pch = c(1, token[id]),
bg = "white",
cex = 2/3,
title = NULL,
lwd = 1)
}
}
} else if (graphics == "ggplot2") {
if (obs.ct == 1) {
p <- ggplot(data = dat, aes_string("count", y = "package"))
if (log.count) {
dat2 <- dat
dat2$count <- log10(dat2$count)
p <- ggplot(data = dat2, aes_string(x = "count", y = "package")) +
xlab("log10 Count")
}
p <- p + geom_hline(yintercept = c(1, 2), linetype = "dotted") +
theme(legend.position = "bottom",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
} else if (obs.ct > 1) {
if (statistic == "count") {
p <- ggplot(data = dat, aes_string(x = "date", y = "count",
colour = "package")) + ggtitle("Package Download Counts")
} else if (statistic == "cumulative") {
p <- ggplot(data = dat, aes_string(x = "date", y = "cumulative",
colour = "package")) + ggtitle("Cumulative Package Downloads")
}
if (any(dat$in.progress)) {
g <- lapply(x$packages, function(pkg) {
pkg.data <- dat[dat$package == pkg, ]
ip.sel <- pkg.data$in.progress == TRUE
ip.data <- pkg.data[ip.sel, ]
complete.data <- pkg.data[!ip.sel, ]
last.obs <- nrow(complete.data)
obs.days <- as.numeric(format(last.obs.date , "%d"))
exp.days <- as.numeric(format(ip.data[, "date"], "%d"))
est.ct <- round(ip.data$count * exp.days / obs.days)
est.data <- ip.data
est.data$count <- est.ct
last.cumulative <- complete.data[nrow(complete.data), "cumulative"]
est.data$cumulative <- last.cumulative + est.ct
list(ip.data = ip.data,
complete.data = complete.data,
est.data = est.data,
est.seg = rbind(complete.data[last.obs, ], est.data),
obs.seg = rbind(complete.data[last.obs, ], ip.data))
})
ip.data <- do.call(rbind, lapply(g, function(x) x$ip.data))
complete.data <- do.call(rbind, lapply(g, function(x) x$complete.data))
est.data <- do.call(rbind, lapply(g, function(x) x$est.data))
est.seg <- do.call(rbind, lapply(g, function(x) x$est.seg))
obs.seg <- do.call(rbind, lapply(g, function(x) x$obs.seg))
p <- p + geom_line(data = complete.data, size = 1/3) +
geom_line(data = est.seg, size = 1/3, linetype = "solid") +
geom_line(data = obs.seg, size = 1/3, linetype = "dotted") +
geom_point(data = est.data, shape = 2) +
geom_point(data = ip.data, shape = 0) +
theme(legend.position = "bottom",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.title = element_text(hjust = 0.5))
if (points) {
p <- p + geom_point(data = complete.data)
}
} else {
p <- p + geom_line(size = 1/3) +
theme(legend.position = "bottom",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.title = element_text(hjust = 0.5))
if (points) p <- p + geom_point()
}
if (log.count) p <- p + scale_y_log10()
if (smooth) {
if (any(dat$in.progress)) {
smooth.data <- complete.data
p <- p + geom_smooth(data = smooth.data, method = "loess",
formula = "y ~ x", se = se, span = span)
} else {
p <- p + geom_smooth(method = "loess", formula = "y ~ x", se = se,
span = span)
}
}
}
suppressWarnings(print(p))
}
}
rPlot <- function(x, statistic, graphics, obs.ct, legend.loc, points, log.count,
smooth, se, r.version, f, span, multi.plot) {
dat <- x$cranlogs.data
ylab <- tools::toTitleCase(statistic)
last.obs.date <- x$last.obs.date
type <- ifelse(points, "o", "l")
if (obs.ct == 1) {
if (graphics == "base") {
if (log.count) {
dotchart(log10(dat$count), labels = dat$platform, xlab = "log10 Count",
main = paste("R Downloads:", unique(dat$date)))
} else {
dotchart(dat$count, labels = dat$platform, xlab = "Count",
main = paste("R Downloads:", unique(dat$date)))
}
} else if (graphics == "ggplot2") {
if (log.count) {
dat2 <- dat
dat2$count <- log10(dat2$count)
p <- ggplot(data = dat2, aes_string(x = "count", y = "platform")) +
geom_point(size = 2) +
xlab("log10 Count")
} else {
p <- ggplot(data = dat, aes_string(x = "count", y = "platform")) +
geom_point(size = 2)
}
p + theme_bw() +
ggtitle(paste("R Downloads:", unique(dat$date))) +
theme(panel.grid.major.x = element_blank(),
panel.grid.minor = element_blank(),
plot.title = element_text(hjust = 0.5))
}
} else if (obs.ct > 1) {
if (graphics == "base") {
if (any(dat$in.progress)) {
pltfrm <- unique(dat$platform)
pltfrm.col <- c("red", "dodgerblue", "black")
p.data <- lapply(seq_along(pltfrm), function(i) {
pkg.dat <- dat[dat$platform == pltfrm[i], ]
ip.sel <- pkg.dat$in.progress == TRUE
ip.data <- pkg.dat[ip.sel, ]
complete.data <- pkg.dat[!ip.sel, ]
obs.days <- as.numeric(format(last.obs.date , "%d"))
exp.days <- as.numeric(format(ip.data[, "date"], "%d"))
est.ct <- round(ip.data$count * exp.days / obs.days)
est.data <- ip.data
est.data$count <- est.ct
last.cumulative <- complete.data[nrow(complete.data), "cumulative"]
est.data$cumulative <- last.cumulative + est.ct
list(ip.data = ip.data, complete.data = complete.data,
est.data = est.data)
})
est.stat <- vapply(p.data, function(x) {
x$est.data[, statistic]
}, numeric(1L))
complete.data <- lapply(p.data, function(x) x$complete.data)
est.data <- lapply(p.data, function(x) x$est.data)
ip.data <- lapply(p.data, function(x) x$ip.data)
last.obs <- unique(vapply(complete.data, nrow, integer(1L)))
ylim <- range(c(dat[, statistic], est.stat))
if (log.count) {
plot(dat$date, dat[, statistic], pch = NA, xlab = "Date",
ylab = paste("log10", ylab), ylim = ylim, log = "y")
} else {
plot(dat$date, dat[, statistic], pch = NA, xlab = "Date", ylab = ylab,
ylim = ylim)
}
if (points) {
invisible(lapply(seq_along(complete.data), function(i) {
tmp <- complete.data[[i]]
points(tmp[, "date"], tmp[, statistic], col = pltfrm.col[i],
pch = 16)
}))
}
invisible(lapply(seq_along(complete.data), function(i) {
tmp <- complete.data[[i]]
lines(tmp$date, tmp[, statistic], type = type, col = pltfrm.col[i])
}))
invisible(lapply(seq_along(est.data), function(i) {
tmp <- est.data[[i]]
points(tmp[, "date"], tmp[, statistic], col = pltfrm.col[i], pch = 15)
}))
invisible(lapply(seq_along(ip.data), function(i) {
tmp <- ip.data[[i]]
points(tmp[, "date"], tmp[, statistic], col = pltfrm.col[i], pch = 0)
}))
invisible(lapply(seq_along(complete.data), function(i) {
tmpA <- complete.data[[i]]
tmpB <- ip.data[[i]]
segments(tmpA[last.obs, "date"], tmpA[last.obs, statistic],
tmpB$date, tmpB[, statistic], lty = "dotted")
}))
invisible(lapply(seq_along(complete.data), function(i) {
tmpA <- complete.data[[i]]
tmpB <- est.data[[i]]
segments(tmpA[last.obs, "date"], tmpA[last.obs, statistic], tmpB$date,
tmpB[, statistic], lty = "solid", col = pltfrm.col[i])
}))
if (smooth) {
invisible(lapply(seq_along(complete.data), function(i) {
smooth.data <- complete.data[[i]]
lines(stats::lowess(smooth.data$date, smooth.data[, statistic],
f = f), col = pltfrm.col[i], lty = "solid", lwd = 1.5)
}))
}
legend(x = legend.loc,
legend = c("win", "mac", "src"),
col = c("black", "red", "dodgerblue"),
pch = rep(16, 3),
bg = "white",
cex = 2/3,
title = "Platform",
lwd = 1)
if (r.version) {
r_v <- rversions::r_versions()
axis(3, at = as.Date(r_v$date), labels = paste("R", r_v$version),
cex.axis = 2/3, padj = 0.9)
}
title(main = "R Downloads")
} else {
if (log.count) {
plot(dat[dat$platform == "win", "date"],
dat[dat$platform == "win", statistic],
pch = NA, ylim = range(dat[, statistic]),
xlab = "Date", ylab = paste("log10", ylab), log = "y")
} else {
plot(dat[dat$platform == "win", "date"],
dat[dat$platform == "win", statistic],
pch = NA, ylim = range(dat[, statistic]),
xlab = "Date", ylab = ylab)
}
pltfrm <- unique(dat$platform)
pltfrm.col <- c("red", "dodgerblue", "black")
invisible(lapply(seq_along(pltfrm), function(i) {
lines(dat[dat$platform == pltfrm[i], "date"],
dat[dat$platform == pltfrm[i], statistic],
type = type, pch = 0, col = pltfrm.col[i])
}))
legend(x = legend.loc,
legend = c("win", "mac", "src"),
col = c("black", "red", "dodgerblue"),
pch = c(1, 0, 2),
bg = "white",
cex = 2/3,
title = "Platform",
lwd = 1)
if (smooth) {
invisible(lapply(seq_along(pltfrm), function(i) {
sm.data <- stats::lowess(dat[dat$platform == pltfrm[i], "date"],
dat[dat$platform == pltfrm[i], statistic], f = f)
lines(sm.data, lty = "solid", lwd = 1.5, col = pltfrm.col[i])
}))
}
if (r.version) {
r_v <- rversions::r_versions()
axis(3, at = as.Date(r_v$date), labels = paste("R", r_v$version),
cex.axis = 2/3, padj = 0.9)
}
title(main = "R Downloads")
}
} else if (graphics == "ggplot2") {
if (statistic == "count") {
if (multi.plot) {
p <- ggplot(data = dat, aes_string("date", "count",
colour = "platform"))
} else {
p <- ggplot(data = dat, aes_string("date", "count")) +
facet_wrap(~ platform, nrow = 2)
}
} else {
if (multi.plot) {
p <- ggplot(data = dat, aes_string("date", "cumulative",
colour = "platform"))
} else {
p <- ggplot(data = dat, aes_string("date", "cumulative")) +
facet_wrap(~ platform, nrow = 2)
}
}
if (any(dat$in.progress)) {
pltfrm <- unique(dat$platform)
pltfrm.col <- c("red", "blue", "black")
p.data <- lapply(seq_along(pltfrm), function(i) {
pkg.dat <- dat[dat$platform == pltfrm[i], ]
ip.sel <- pkg.dat$in.progress == TRUE
ip.data <- pkg.dat[ip.sel, ]
complete.data <- pkg.dat[!ip.sel, ]
last.obs <- nrow(complete.data)
obs.days <- as.numeric(format(last.obs.date , "%d"))
exp.days <- as.numeric(format(ip.data[, "date"], "%d"))
est.ct <- round(ip.data$count * exp.days / obs.days)
est.data <- ip.data
est.data$count <- est.ct
last.cumulative <- complete.data[nrow(complete.data), "cumulative"]
est.data$cumulative <- last.cumulative + est.ct
list(ip.data = ip.data,
complete.data = complete.data,
est.data = est.data,
est.seg = rbind(complete.data[last.obs, ], est.data),
obs.seg = rbind(complete.data[last.obs, ], ip.data))
})
est.stat <- vapply(p.data, function(x) {
x$est.data[, statistic]
}, numeric(1L))
ylim <- range(c(dat[, statistic], est.stat))
complete.data <- lapply(p.data, function(x) x$complete.data)
est.data <- lapply(p.data, function(x) x$est.data)
ip.data <- lapply(p.data, function(x) x$ip.data)
complete.data <- do.call(rbind, complete.data)
est.data <- do.call(rbind, est.data)
ip.data <- do.call(rbind, ip.data)
p <- p + geom_line(data = complete.data, size = 1/3)
est.seg <- lapply(p.data, function(z) {
tmp <- z$est.seg
out <- data.frame(date = tmp$date[1], count = tmp[, statistic][1],
xend = tmp$date[2], yend = tmp[, statistic][2],
platform = unique(tmp$platform))
if (statistic == "cumulative") {
names(out)[names(out) == "count"] <- "cumulative"
}
out
})
obs.seg <- lapply(p.data, function(z) {
tmp <- z$obs.seg
out <- data.frame(date = tmp$date[1], count = tmp[, statistic][1],
xend = tmp$date[2], yend = tmp[, statistic][2],
platform = unique(tmp$platform))
if (statistic == "cumulative") {
names(out)[names(out) == "count"] <- "cumulative"
}
out
})
est.seg <- do.call(rbind, est.seg)
obs.seg <- do.call(rbind, obs.seg)
if (multi.plot) {
p <- p + geom_point(data = est.data, shape = 15) +
geom_point(data = ip.data, shape = 0) +
geom_segment(data = est.seg, aes_string(xend = "xend",
yend = "yend"), linetype = "solid") +
geom_segment(data = obs.seg, aes_string(xend = "xend",
yend = "yend"), linetype = "dotted")
} else {
p <- p + geom_point(data = est.data, colour = "red", shape = 15) +
geom_point(data = ip.data, colour = "black", shape = 0) +
geom_segment(data = est.seg, aes_string(xend = "xend",
yend = "yend"), colour = "red") +
geom_segment(data = obs.seg, aes_string(xend = "xend",
yend = "yend"), linetype = "dotted")
}
if (points) p <- p + geom_point(data = complete.data)
if (log.count) p <- p + scale_y_log10() + ylab("log10 Count")
if (smooth) {
if (any(dat$in.progress)) {
smooth.data <- complete.data
p <- p + geom_smooth(data = smooth.data, method = "loess",
formula = "y ~ x", se = se, span = span)
} else {
p <- p + geom_smooth(method = "loess", formula = "y ~ x", se = se,
span = span)
}
}
p <- p + theme_bw() +
ggtitle("R Downloads") +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.title = element_text(hjust = 0.5))
} else {
p <- p + geom_line(size = 0.5) +
ggtitle("R Downloads") +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.title = element_text(hjust = 0.5))
if (points) p <- p + geom_point()
if (log.count) p <- p + scale_y_log10() + ylab("log10 Count")
if (!multi.plot) p <- p + facet_wrap(~ platform, nrow = 2)
if (smooth) {
p <- p + geom_smooth(method = "loess", formula = "y ~ x", se = se,
span = span)
}
}
suppressWarnings(print(p))
}
}
}
rTotPlot <- function(x, statistic, graphics, legend.loc, points,
log.count, smooth, se, r.version, f, span) {
dat <- x$cranlogs.data
last.obs.date <- x$last.obs.date
ct <- tapply(dat$count, dat$date, sum)
if (any(dat$in.progress)) {
dat <- data.frame(date = unique(dat$date),
count = ct,
cumulative = cumsum(ct),
in.progress = dat[dat$platform == "win", "in.progress"],
row.names = NULL)
} else {
dat <- data.frame(date = unique(dat$date),
count = ct,
cumulative = cumsum(ct),
row.names = NULL)
}
ylab <- tools::toTitleCase(statistic)
if (graphics == "base") {
type <- ifelse(points, "o", "l")
if (any(dat$in.progress)) {
ip.sel <- dat$in.progress == TRUE
ip.data <- dat[ip.sel, ]
complete.data <- dat[!ip.sel, ]
last.obs <- nrow(complete.data)
obs.days <- as.numeric(format(last.obs.date , "%d"))
exp.days <- as.numeric(format(ip.data[, "date"], "%d"))
est.ct <- round(ip.data$count * exp.days / obs.days)
est.data <- ip.data
est.data$count <- est.ct
last.cumulative <- complete.data[nrow(complete.data), "cumulative"]
est.data$cumulative <- last.cumulative + est.ct
if (statistic == "count") {
ylim <- range(c(dat[, statistic], est.data$count))
} else if (statistic == "cumulative") {
ylim <- range(c(dat[, statistic], est.data$cumulative))
}
xlim <- range(dat$date)
if (log.count) {
plot(complete.data$date, complete.data[, statistic], type = type,
xlab = "Date", ylab = paste0("log10 ", ylab), xlim = xlim,
ylim = ylim, log = "y", pch = 16)
} else {
plot(complete.data$date, complete.data[, statistic], type = type,
xlab = "Date", ylab = ylab, xlim = xlim, ylim = ylim, pch = 16)
}
points(ip.data[, "date"], ip.data[, statistic], col = "black", pch = 0)
points(est.data[, "date"], est.data[, statistic], col = "red", pch = 0)
segments(complete.data[last.obs, "date"],
complete.data[last.obs, statistic],
ip.data$date,
ip.data[, statistic],
lty = "dotted")
segments(complete.data[last.obs, "date"],
complete.data[last.obs, statistic],
est.data$date,
est.data[, statistic],
col = "red")
axis(4, at = ip.data[, statistic], labels = "obs")
axis(4, at = est.data[, statistic], labels = "est", col.axis = "red",
col.ticks = "red")
if (smooth) {
smooth.data <- complete.data
lines(stats::lowess(smooth.data$date, smooth.data[, statistic], f = f),
col = "blue")
}
if (r.version) {
r_v <- rversions::r_versions()
axis(3, at = as.Date(r_v$date), labels = paste("R", r_v$version),
cex.axis = 2/3, padj = 0.9)
}
title(main = "Total R Downloads")
} else {
if (log.count) {
plot(dat$date, dat[, statistic], type = type, xlab = "Date",
ylab = ylab, log = "y")
} else {
plot(dat$date, dat[, statistic], type = type, xlab = "Date",
ylab = ylab)
}
if (smooth) {
lines(stats::lowess(dat$date, dat[, statistic], f), col = "blue",
lwd = 1.25)
}
if (r.version) {
r_v <- rversions::r_versions()
axis(3, at = as.Date(r_v$date), labels = paste("R", r_v$version),
cex.axis = 2/3, padj = 0.9)
}
title(main = "Total R Downloads")
}
} else if (graphics == "ggplot2") {
if (statistic == "count") {
p <- ggplot(data = dat, aes_string("date", "count"))
} else if (statistic == "cumulative") {
p <- ggplot(data = dat, aes_string("date", "cumulative"))
}
if (any(dat$in.progress)) {
ip.sel <- dat$in.progress == TRUE
ip.data <- dat[ip.sel, ]
complete.data <- dat[!ip.sel, ]
last.obs <- nrow(complete.data)
obs.days <- as.numeric(format(last.obs.date , "%d"))
exp.days <- as.numeric(format(ip.data[, "date"], "%d"))
est.ct <- round(ip.data$count * exp.days / obs.days)
est.data <- ip.data
est.data$count <- est.ct
last.cumulative <- complete.data[nrow(complete.data), "cumulative"]
est.data$cumulative <- last.cumulative + est.ct
est.seg <- rbind(complete.data[last.obs, ], est.data)
obs.seg <- rbind(complete.data[last.obs, ], ip.data)
p <- p + geom_line(data = complete.data, size = 1/3) +
geom_line(data = est.seg, size = 1/3, colour = "red") +
geom_line(data = obs.seg, size = 1/3, colour = "black",
linetype = "dotted") +
geom_point(data = est.data, colour = "red", shape = 0) +
geom_point(data = ip.data, colour = "black", shape = 0)
if (points) p <- p + geom_point(data = complete.data)
} else {
p <- p + geom_line(size = 0.5) +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.title = element_text(hjust = 0.5)) +
ggtitle("Total R Downloads")
if (points) p <- p + geom_point()
}
if (log.count) p <- p + scale_y_log10() + ylab("log10 Count")
if (smooth) {
if (any(dat$in.progress)) {
smooth.data <- complete.data
p <- p + geom_smooth(data = smooth.data, method = "loess",
formula = "y ~ x", se = se, span = span)
} else {
p <- p + geom_smooth(method = "loess", formula = "y ~ x", se = se,
span = span)
}
}
p <- p + theme_bw() +
ggtitle("Total R Downloads") +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.title = element_text(hjust = 0.5))
suppressWarnings(print(p))
}
} |
output$network_proxy_nodes <- renderVisNetwork({
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
visNetwork(nodes, edges)%>%
visNodes(color = "blue", size = 20)
})
observe({
visNetworkProxy("network_proxy_nodes") %>%
visNodes(color = input$color, size = input$size, shadow = input$shadow) %>%
visEdges(dashes = input$dashes, smooth = input$smooth)
})
output$code_proxy_nodes <- renderText({
'
output$network_proxy_nodes <- renderVisNetwork({
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
visNetwork(nodes, edges)
})
observe({
visNetworkProxy("network_proxy_nodes") %>%
visNodes(color = input$color, size = input$size, shadow = input$shadow) %>%
visEdges(dashes = input$dashes, smooth = input$smooth)
})
observe({
visNetworkProxy("network_proxy_nodes") %>%
visSetOptions(options = list(nodes = list(color = input$color, size = input$size, shadow = input$shadow),
edges = list(dashes = input$dashes, smooth = input$smooth)))
})
'
}) |
coxsimLinear <- function(obj, b, qi = "Relative Hazard", Xj = NULL, Xl = NULL,
means = FALSE, nsim = 1000, ci = 0.95, spin = FALSE,
extremesDrop = TRUE)
{
HRValue <- strata <- QI <- SimID <- time <- NULL
if (qi != "Hazard Rate" & isTRUE(means)){
stop("means can only be TRUE when qi = 'Hazard Rate'.", call. = FALSE)
}
if (is.null(Xl) & qi != "Hazard Rate"){
Xl <- rep(0, length(Xj))
message("All Xl set to 0.")
} else if (!is.null(Xl) & qi == "Relative Hazard") {
message("All Xl set to 0.")
}
qiOpts <- c("Relative Hazard", "First Difference", "Hazard Rate",
"Hazard Ratio")
TestqiOpts <- qi %in% qiOpts
if (!isTRUE(TestqiOpts)){
stop("Invalid qi type. qi must be 'Relative Hazard', 'Hazard Rate',
'First Difference', or 'Hazard Ratio'.", call. = FALSE)
}
MeansMessage <- NULL
if (isTRUE(means) & length(obj$coefficients) == 3){
means <- FALSE
MeansMessage <- FALSE
message("Note: means reset to FALSE. The model only includes the interaction variables.")
} else if (isTRUE(means) & length(obj$coefficients) > 3){
MeansMessage <- TRUE
}
SimID <- 1:nsim
Coef <- matrix(obj$coefficients)
VC <- vcov(obj)
Drawn <- mvrnorm(n = nsim, mu = Coef, Sigma = VC)
DrawnDF <- data.frame(Drawn)
dfn <- names(DrawnDF)
if (!isTRUE(means)){
bpos <- match(b, dfn)
Simb <- data.frame(SimID, DrawnDF[, bpos])
names(Simb) <- c("SimID", "Coef")
if (qi == "Relative Hazard"){
Xs <- data.frame(Xj)
names(Xs) <- c("Xj")
Xs$Comparison <- paste(Xs[, 1])
Simb <- merge(Simb, Xs)
Simb$QI <- exp(Simb$Xj * Simb$Coef)
} else if (qi == "First Difference"){
if (length(Xj) != length(Xl)){
stop("Xj and Xl must be the same length.", call. = FALSE)
}
else {
Xs <- data.frame(Xj, Xl)
Simb <- merge(Simb, Xs)
Simb$QI<- (exp((Simb$Xj - Simb$Xl) * Simb$Coef) - 1) * 100
}
}
else if (qi == "Hazard Ratio"){
Xs <- data.frame(Xj, Xl)
Simb <- merge(Simb, Xs)
Simb$QI<- exp((Simb$Xj - Simb$Xl) * Simb$Coef)
}
else if (qi == "Hazard Rate"){
if (!is.null(Xl)) {
Xl <- NULL
message("Xl is ignored.")
}
if (isTRUE(MeansMessage)){
message("All variables values other than b are fitted at 0.")
}
Xs <- data.frame(Xj)
Xs$HRValue <- paste(Xs[, 1])
Simb <- merge(Simb, Xs)
Simb$HR <- exp(Simb$Xj * Simb$Coef)
bfit <- basehaz(obj)
bfit$FakeID <- 1
Simb$FakeID <- 1
bfitDT <- data.table(bfit, key = "FakeID", allow.cartesian = TRUE)
SimbDT <- data.table(Simb, key = "FakeID", allow.cartesian = TRUE)
Simb <- SimbDT[bfitDT, allow.cartesian = TRUE]
Rows <- nrow(Simb)
if (Rows > 2000000){
message(paste("There are", Rows, "simulations. This may take awhile. Consider using nsim to reduce the number of simulations."))
}
Simb$QI <- Simb$hazard * Simb$HR
if (!('strata' %in% names(Simb))){
Simb <- Simb[, list(SimID, time, Xj, QI, HRValue)]
} else if ('strata' %in% names(Simb)){
Simb <- Simb[, list(SimID, time, Xj, QI, HRValue, strata)]
}
Simb <- data.frame(Simb)
}
}
else if (isTRUE(means)){
Xl <- NULL
message("Xl ignored")
NotB <- setdiff(names(DrawnDF), b)
MeanValues <- data.frame(obj$means)
FittedMeans <- function(Z){
ID <- 1:nsim
Temp <- data.frame(ID)
for (i in Z){
BarValue <- MeanValues[i, ]
DrawnCoef <- DrawnDF[, i]
FittedCoef <- outer(DrawnCoef, BarValue)
FCMolten <- MatrixMelter(FittedCoef)
Temp <- cbind(Temp, FCMolten[,3])
}
Names <- c("ID", Z)
names(Temp) <- Names
Temp <- Temp[, -1]
return(Temp)
}
FittedComb <- FittedMeans(NotB)
ExpandFC <- do.call(rbind, rep(list(FittedComb), length(Xj)))
bpos <- match(b, dfn)
Simb <- data.frame(DrawnDF[, bpos])
Xs <- data.frame(Xj)
Xs$HRValue <- paste(Xs[, 1])
Simb <- merge(Simb, Xs)
Simb$CombB <- Simb[, 1] * Simb[, 2]
Simb <- Simb[, 2:4]
Simb <- cbind(Simb, ExpandFC)
Simb$Sum <- rowSums(Simb[, c(-1, -2)])
Simb$HR <- exp(Simb$Sum)
bfit <- basehaz(obj)
bfit$FakeID <- 1
Simb$FakeID <- 1
bfitDT <- data.table(bfit, key = "FakeID", allow.cartesian = TRUE)
SimbDT <- data.table(Simb, key = "FakeID", allow.cartesian = TRUE)
Simb <- SimbDT[bfitDT, allow.cartesian = TRUE]
Rows <- nrow(Simb)
if (Rows > 2000000){
message(paste("There are", Rows,
"simulations. This may take awhile. Consider using nsim to reduce the number of simulations."))
}
Simb$QI <- Simb$hazard * Simb$HR
if (!('strata' %in% names(Simb))){
Simb <- Simb[, list(time, Xj, QI, HRValue)]
} else if ('strata' %in% names(Simb)){
Simb <- Simb[, list(time, Xj, QI, HRValue, strata)]
}
Simb <- data.frame(Simb)
}
if (qi != "Hazard Rate"){
SubVar <- "Xj"
} else if (qi == "Hazard Rate"){
SubVar <- c("time", "Xj")
}
SimbPerc <- IntervalConstrict(Simb = Simb, SubVar = SubVar,
qi = qi, spin = spin, ci = ci,
extremesDrop = extremesDrop)
if (qi == "Hazard Rate" & !isTRUE(means)){
if (!('strata' %in% names(obj))){
SimbPercSub <- data.frame(SimbPerc$SimID,
SimbPerc$time, SimbPerc$QI,
SimbPerc$HRValue)
names(SimbPercSub) <- c("SimID", "Time", "HRate", "HRValue")
} else if ('strata' %in% names(SimbPerc)) {
SimbPercSub <- data.frame(SimbPerc$SimID, SimbPerc$time,
SimbPerc$QI, SimbPerc$strata,
SimbPerc$HRValue)
names(SimbPercSub) <- c("SimID", "Time", "HRate", "Strata",
"HRValue")
}
} else if (qi == "Hazard Rate" & isTRUE(means)){
if (!('strata' %in% names(obj))){
SimbPercSub <- data.frame(SimbPerc$time, SimbPerc$QI,
SimbPerc$HRValue)
names(SimbPercSub) <- c("Time", "HRate", "HRValue")
} else if ('strata' %in% names(SimbPerc)) {
SimbPercSub <- data.frame(SimbPerc$SimID, SimbPerc$time,
SimbPerc$QI, SimbPerc$strata,
SimbPerc$HRValue)
names(SimbPercSub) <- c("SimID", "Time", "HRate",
"Strata", "HRValue")
}
} else if (qi == "Hazard Ratio" | qi == "Relative Hazard" |
qi == "First Difference"){
SimbPercSub <- data.frame(SimbPerc$SimID, SimbPerc$Xj, SimbPerc$QI)
names(SimbPercSub) <- c("SimID", "Xj", "QI")
}
rug <- model.frame(obj)[, b]
out <- list(sims = SimbPercSub, rug = rug)
class(out) <- c("simlinear", qi, "coxsim")
attr(out, 'xaxis') <- b
out
} |
diffPower4ss.LME=function( n,
slope,
m,
sigma.y,
sigma.x,
power = 0.8,
rho=0.8,
FWER=0.05,
nTests=1)
{
power.est = powerLME.default(
slope = slope,
n = n,
m = m,
sigma.y = sigma.y,
sigma.x = sigma.x,
rho=rho,
FWER=FWER,
nTests=nTests)
diff=power.est-power
return(diff)
}
ssLME=function( slope,
m,
sigma.y,
sigma.x,
power = 0.8,
rho=0.8,
FWER=0.05,
nTests=1,
n.lower = 2.01,
n.upper = 1e+30
)
{
res.uni=uniroot(f=diffPower4ss.LME,
interval = c(n.lower, n.upper),
slope = slope,
m = m,
sigma.y = sigma.y,
sigma.x = sigma.x,
power = power,
rho=rho,
FWER=FWER,
nTests=nTests
)
return(res.uni$root)
} |
s2_lnglat <- function(lng, lat) {
recycled <- recycle_common(as.double(lng), as.double(lat))
new_s2_xptr(s2_lnglat_from_numeric(recycled[[1]], recycled[[2]]), "s2_lnglat")
}
as_s2_lnglat <- function(x, ...) {
UseMethod("as_s2_lnglat")
}
as_s2_lnglat.s2_lnglat <- function(x, ...) {
x
}
as_s2_lnglat.s2_point <- function(x, ...) {
new_s2_xptr(s2_lnglat_from_s2_point(x), "s2_lnglat")
}
as_s2_lnglat.s2_geography <- function(x, ...) {
new_s2_xptr(s2_lnglat_from_numeric(cpp_s2_x(x), cpp_s2_y(x)), "s2_lnglat")
}
as_s2_lnglat.matrix <- function(x, ...) {
s2_lnglat(x[, 1, drop = TRUE], x[, 2, drop = TRUE])
}
as_s2_lnglat.character <- function(x, ...) {
as_s2_lnglat.wk_wkt(x)
}
as_s2_lnglat.wk_wkt <- function(x, ...) {
as_s2_lnglat(as_s2_geography(x), ...)
}
as_s2_lnglat.wk_wkb <- function(x, ...) {
as_s2_lnglat(as_s2_geography(x), ...)
}
as.data.frame.s2_lnglat <- function(x, ...) {
as.data.frame(data_frame_from_s2_lnglat(x))
}
as.matrix.s2_lnglat <- function(x, ...) {
as.matrix(as.data.frame(data_frame_from_s2_lnglat(x)))
}
as_wkb.s2_lnglat <- function(x, ...) {
as_wkb(as_s2_geography(x), ...)
}
as_wkt.s2_lnglat <- function(x, ...) {
as_wkt(as_s2_geography(x), ...)
}
`[<-.s2_lnglat` <- function(x, i, value) {
x <- unclass(x)
x[i] <- as_s2_lnglat(value)
new_s2_xptr(x, "s2_lnglat")
}
`[[<-.s2_lnglat` <- function(x, i, value) {
x <- unclass(x)
x[i] <- as_s2_lnglat(value)
new_s2_xptr(x, "s2_lnglat")
}
format.s2_lnglat <- function(x, ...) {
df <- as.data.frame(x)
sprintf("(%s, %s)", format(df$lng, trim = TRUE), format(df$lat, trim = TRUE))
} |
frm_em_calc_likelihood <- function( dat, ind0, NM, eps=1E-30, iter=NULL,
weights0=NULL, dat_resp, ind_resp, ind_miss )
{
weights <- dat$weights
N2 <- nrow(dat)
loglike <- matrix(NA, nrow=N2, ncol=NM+1)
like0 <- loglike
post0 <- loglike
model_results <- NULL
post <- 1 + 0*dat$weights
like <- post
like_obs <- post
post_miss <- post
coefs <- as.list( 1:(NM+1) )
for (mm in 1:(NM+1)){
ind_mm <- ind0[[mm]]
mod <- frm_em_calc_likelihood_estimate_model( ind_mm=ind_mm, dat=dat,
weights=weights )
model_results[[mm]] <- mod
model_results <- frm_em_include_coef_inits( ind=ind0, mm=mm,
model_results=model_results, iter=iter)
model_results[[mm]]$est_sigma <- FALSE
if ( ! is.null(ind_mm$sigma_fixed)){
model_results[[mm]]$sigma <- ind_mm$sigma_fixed
}
mod <- model_results[[mm]]
args <- list(model=mod, y=dat[, ind_mm$dv_vars ], case=dat$case)
args <- frm_em_linreg_density_extend_args(args=args, ind_mm=ind_mm)
dmod <- do.call( what=ind_mm$R_density_fct, args=args )
mod <- model_results[[mm]]
cm <- coef(mod)
if (ind_mm$model=="linreg"){
model_results[[mm]]$NC <- length(cm)
if ( is.null(ind_mm$sigma_fixed) ){
cm["sigma"] <- dmod$sigma
model_results[[mm]]$sigma <- dmod$sigma
model_results[[mm]]$est_sigma <- TRUE
}
cm["R2"] <- dmod$R2
}
if (ind_mm$model=="logistic"){
ind0[[mm]]$R_args$beta_init <- coef(mod)
cm["R2"] <- mod$R2
}
if (ind_mm$model=="bctreg"){
ind0[[mm]]$R_args$beta_init <- coef(mod)
cm["R2"] <- mod$R2
}
if (ind_mm$model=="oprobit"){
if (iter>1){
ind0[[mm]]$R_args$beta_init <- coef(mod)
}
cm["R2"] <- mod$R2
}
coefs[[mm]] <- cm
like0[,mm] <- dmod$like
loglike[,mm] <- log( dmod$like + eps )
post0[,mm] <- dmod$post
post <- post * dmod$post
like <- like * dmod$like
res3 <- frm_em_calc_update_observed_likelihood(like_obs=like_obs,
post_miss=post_miss, dmod=dmod, mm=mm,
ind_resp=ind_resp, ind_miss=ind_miss)
like_obs <- res3$like_obs
post_miss <- res3$post_miss
}
post <- frm_normalize_posterior( post=post, case=dat$case)
dat$weights <- dat$weights0 * post
ll <- frm_em_calc_total_likelihood(dat=dat, weights0=weights0,
like_obs=like_obs, post_miss=post_miss)
res <- list( loglike=loglike, post=post, coefs=coefs,
model_results=model_results, ll=ll, post0=post0,
ind0=ind0, like=like, like0=like0 )
return(res)
} |
options("scipen" = 10000)
fontDir <- "C:\\Users\\Alex\\Desktop\\font_workbooks"
files <- list.files(fontDir, patter = "\\.xlsx$", full.names = TRUE)
files <- files[!grepl("-bold.xlsx", files)]
files2 <- list.files(fontDir, patter = "\\.xlsx$", full.names = FALSE)
files2 <- files2[!grepl("-bold.xlsx", files2)]
font <- tolower(gsub(" ", ".", gsub("\\.xlsx", "", files2)))
strs <- "openxlsxFontSizeLookupTable <- \ndata.frame("
allWidths <- rep(8.43, 29)
names(allWidths) <- 1:29
for(i in seq_along(files)){
f <- font[[i]]
widths <- round(as.numeric(read.xlsx(files[[i]])[2,]), 6)
strs <- c(strs, sprintf('"%s"= c(%s),\n', f, paste(widths, collapse = ", ")))
}
strs[length(strs)] <- gsub(",\n", ")", strs[length(strs)])
fontDir <- "C:\\Users\\Alex\\Desktop\\font_workbooks"
files <- list.files(fontDir, patter = "\\.xlsx$", full.names = TRUE)
files <- files[grepl("-bold.xlsx", files)]
files2 <- list.files(fontDir, patter = "\\.xlsx$", full.names = FALSE)
files2 <- files2[grepl("-bold.xlsx", files2)]
font <- tolower(gsub(" ", ".", gsub("\\-bold.xlsx", "", files2)))
strsBold <- "openxlsxFontSizeLookupTableBold <- \ndata.frame("
allWidths <- rep(8.43, 29)
names(allWidths) <- 1:29
for(i in seq_along(files)){
f <- font[[i]]
widths <- round(as.numeric(read.xlsx(files[[i]])[2,]), 6)
strsBold <- c(strsBold, sprintf('"%s"= c(%s),\n', f, paste(widths, collapse = ", ")))
}
strsBold[length(strsBold)] <- gsub(",\n", ")", strsBold[length(strsBold)])
allStrs <- c(strs, "\n\n\n", strsBold)
cat(allStrs) |
simProjWiz <- function(thepoints,thecentre){
coordinates(thepoints) <- c("long", "lat")
proj4string(thepoints) <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
if((thecentre$lat < 70) & (thecentre$lat > -70)){
CRSstring <- paste("+proj=cea +lon_0=", thecentre$long, " +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs",sep = "")
} else {
CRSstring <- paste("+proj=laea +lat_0=", thecentre$lat," +lon_0=", thecentre$long, " +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs",sep = "")
}
CRS.new <- CRS(CRSstring)
xysp <- spTransform(thepoints, CRS.new)
xy <- as.data.frame(xysp)
colnames (xy) <- c("x","y")
return(xy)
}
trueCOGll <-function(thepoints){
llrad <- deg2rad(thepoints)
cartp <- ll2cart(llrad$lat,llrad$long)
mp <- data.frame(x=mean(cartp$x),y=mean(cartp$y),z=mean(cartp$z))
pmp <- pro2sph(mp$x,mp$y,mp$z)
pmprll <- cart2ll(pmp$x,pmp$y,pmp$z)
pmpll <- rad2deg(pmprll)
return(data.frame(lat=pmpll$latr,long=pmpll$longr))
}
ll2cart <- function(latr,longr){
x <- cos(latr) * cos(longr)
y <- cos(latr) * sin(longr)
z <- sin(latr)
return(data.frame(x,y,z))
}
cart2ll <-function (x,y,z){
latr <- asin(z)
longr <- atan2(y,x)
return(data.frame(latr,longr))
}
pro2sph <- function (x,y,z){
sc <- 1/sqrt(x^2 + y^2 + z^2)
x <- x * sc
y <- y * sc
z <- z * sc
return(data.frame(x,y,z))
}
rad2deg <- function(rad) {(rad * 180) / (pi)}
deg2rad <- function(deg) {(deg * pi) / (180)} |
"drmEMeventtime" <-
function(dose, resp, multCurves, doseScaling = 1)
{
opfct <- function(c)
{
Fstart <- multCurves(dose[, 1] / doseScaling, c)
dose2 <- dose[, 2]
Fend <- multCurves(dose2 / doseScaling, c)
Fend[!is.finite(dose2)] <- 1
return( -sum(resp * log(Fend - Fstart)) )
}
ssfct <- NULL
llfct <- function(object)
{
c(
-object$"fit"$value,
object$"sumList"$"df.residual"
)
}
rvfct <- NULL
vcovfct <- function(object)
{
solve(object$fit$hessian)
}
parmfct <- function(fit, fixed = TRUE)
{
fit$par
}
return(list(llfct = llfct, opfct = opfct, ssfct = ssfct, rvfct = rvfct, vcovfct = vcovfct,
parmfct = parmfct))
}
"drmLOFeventtime" <- function()
{
return(list(anovaTest = NULL, gofTest = NULL))
} |
xtree.reg <- function(x, ...) UseMethod("xtree.reg") |
"psid" |
setClass(
Class = "StandardError",
prototype = prototype(
description = "standard error"
),
contains = "SamplingVariance"
) |
test_that("use_import_from() imports the related package & adds line to package doc", {
create_local_package()
use_package_doc()
use_import_from("tibble", "tibble")
expect_equal(trimws(desc::desc_get("Imports", proj_get()))[[1]], "tibble")
expect_equal(roxygen_ns_show(), "
})
test_that("use_import_from() adds one line for each function", {
create_local_package()
use_package_doc()
use_import_from("tibble", c("tibble", "enframe", "deframe"))
expect_snapshot(roxygen_ns_show())
})
test_that("use_import_from() generates helpful errors", {
create_local_package()
use_package_doc()
expect_snapshot(error = TRUE, {
use_import_from(1)
use_import_from(c("tibble", "rlang"))
use_import_from("tibble", "pool_noodle")
})
}) |
data("apparelTrans")
data("apparelDynCov")
apparelDynCov <- apparelDynCov[Cov.Date > "2005-01-01" ]
skip_on_cran()
context("Runability - PNBD dynamiccov - Basic runability")
mini.apparelTrans <- apparelTrans[Id %in% unique(apparelTrans$Id)[1:100]]
mini.apparelDynCov <- apparelDynCov[Id %in% mini.apparelTrans$Id]
expect_silent(clv.data.trans <- clvdata(data.transactions = mini.apparelTrans, date.format = "ymd",
time.unit = "W", estimation.split = 40))
expect_silent(clv.data.mini.dyncov <-
SetDynamicCovariates(clv.data = clv.data.trans,
data.cov.life = mini.apparelDynCov,
data.cov.trans = mini.apparelDynCov,
names.cov.life = "Gender",
names.cov.trans = "Gender",
name.date = "Cov.Date"))
expect_warning(fitted.dyncov <- pnbd(clv.data.mini.dyncov,
start.params.model = c(r=0.4011475, alpha=22.7155565,
s=0.2630372, beta=19.1752426),
start.params.life = c(Gender=0.9304636),
start.params.trans = c(Gender=1.0934721),
optimx.args = list(method="Nelder-Mead",
hessian=FALSE,
control=list(kkt=FALSE,
reltol = 1000))),
regexp = "Hessian could not be derived.")
fake.hess <- structure(c(979.019728504732, -833.029498091497, -328.098609941573, 258.918547365243, -198.39816295105, 617.835400045399,
-833.029498091497, 850.416620581025, 235.300182628772, -184.286149754065, 137.842394217897, -631.483808344787,
-328.098609941573, 235.300182628772, 265.168175979473, -193.63193759222, 160.709773619312, -177.81494575965,
258.918547365243, -184.286149754065, -193.63193759222, 143.911727169075, -118.898176270749, 137.842394013186,
-198.39816295105, 137.842394217897, 160.709773619312, -118.898176270749, 118.898177254365, -137.842393385251,
617.835400045399, -631.483808344787, -177.81494575965, 137.842394013186, -137.842393385251, 631.483808845486),
.Dim = c(6L, 6L), .Dimnames = list(c("log.r", "log.alpha", "log.s", "log.beta", "life.Gender", "trans.Gender"),
c("log.r", "log.alpha", "log.s", "log.beta", "life.Gender", "trans.Gender")))
[email protected] <- fake.hess
full.names <- c("r", "alpha", "s","beta", "life.Gender", "trans.Gender")
.fct.helper.s3.fitted.coef(clv.fitted = fitted.dyncov, full.names = full.names)
.fct.helper.s3.fitted.vcov(clv.fitted = fitted.dyncov, full.names = full.names)
.fct.helper.s3.fitted.confint(clv.fitted = fitted.dyncov, full.names = full.names)
.fct.helper.s3.fitted.summary(clv.fitted = fitted.dyncov)
.fct.helper.s3.fitted.print(clv.fitted = fitted.dyncov)
.fct.helper.s3.fitted.nobs(clv.fitted = fitted.dyncov)
.fct.helper.s3.fitted.logLik(clv.fitted = fitted.dyncov)
fct.testthat.runability.dynamiccov.LL.is.correct(clv.fitted = fitted.dyncov)
fct.testthat.runability.dynamiccov.plot.works(clv.fitted = fitted.dyncov)
fct.testthat.runability.dynamiccov.plot.has.0.repeat.transactions.expectations(clv.fitted = fitted.dyncov)
fct.testthat.runability.dynamiccov.predict.works(clv.fitted = fitted.dyncov)
fct.testthat.runability.dynamiccov.predict.newdata.works(clv.fitted = fitted.dyncov,
apparelTrans = apparelTrans,
apparelDynCov = apparelDynCov)
dt.additional.cov <- expand.grid(Id = unique(apparelDynCov$Id),
Cov.Date = seq(from=apparelDynCov[, max(Cov.Date)]+lubridate::weeks(1),
length.out = 100, by = "week"), stringsAsFactors = FALSE)
setDT(dt.additional.cov)
dt.additional.cov[, Marketing := rep(c(0,1,2,3),.N/4)]
dt.additional.cov[, Gender := rep(c(0,1),.N/2)]
dt.additional.cov[, Channel := rep(c(0,1),.N/2)]
expect_silent(mini.apparelDynCov.long <- data.table::rbindlist(l = list(mini.apparelDynCov,
dt.additional.cov[Id %in% mini.apparelDynCov$Id]),
use.names = TRUE))
expect_silent(clv.data.mini.extra <- SetDynamicCovariates(clv.data.trans,
data.cov.life = mini.apparelDynCov.long,
data.cov.trans = mini.apparelDynCov.long,
names.cov.life = c("Gender"),
names.cov.trans = c("Gender"),
name.date = "Cov.Date"))
context("Runability - PNBD dynamiccov - newdata")
fct.testthat.runability.dynamiccov.predict.longer.with.newdata(clv.fitted = fitted.dyncov, clv.data.mini.extra = clv.data.mini.extra, clv.data.trans = clv.data.trans)
fct.testthat.runability.dynamiccov.plot.longer.with.newdata(clv.fitted = fitted.dyncov, clv.data.mini.extra = clv.data.mini.extra, clv.data.trans = clv.data.trans)
context("Runability - PNBD dynamiccov - Overlong data")
fct.testthat.runability.dynamiccov.can.predict.plot.beyond.holdout(method = pnbd,
clv.data.trans = clv.data.trans,
mini.apparelDynCov.long = mini.apparelDynCov.long,
start.params.model = c(r=0.4011475, alpha=22.7155565,
s=0.2630372, beta=19.1752426)) |
include_graphics2 <- function(path, alt_path = NULL, handler = function(path) knitr::asis_output(paste('View', tools::file_ext(path), 'at', path)), ...) {
if (knitr::is_latex_output()) {
return(include_graphics_latex(path, alt_path, handler, ...))
} else {
return(knitr::include_graphics(path, ...))
}
}
include_graphics_latex <- function(path, alt_path = NULL, handler = function(path) knitr::asis_output(paste('View', tools::file_ext(path), 'at', path)), ...) {
if (grepl('^https?://', path)) {
ifelse(use_alt_path(path, alt_path),
path <- alt_path,
return(handler(path)))
dir_path <- paste0('downloadFigs4latex_',
file_path_sans_ext(current_input()))
if (!dir.exists(dir_path)) dir.create(dir_path)
file_path <- paste0(dir_path, '/',
knitr::opts_current$get()$label, '.',
file_ext(path))
download.file(path, destfile = file_path)
path <- file_path
}
else {
ifelse(use_alt_path(path, alt_path),
path <- alt_path,
return(handler(path)))
}
return(knitr::include_graphics(path, ...))
}
use_alt_path <- function(path, alt_path) {
if (inval_latex_img(path) && is.null(alt_path)) return(FALSE)
if (inval_latex_img(path) && !is.null(alt_path)) {
stopifnot(!inval_latex_img(alt_path))
return(TRUE)
}
}
inval_latex_img <- function(path) {
invalid_ext <- c('svg', 'SVG', 'GIF', 'gif')
return(tools::file_ext(path) %in% invalid_ext)
} |
graf_col_palette_default <- function(palette = "all_grafify",
reverse = FALSE, ...){
pal <- graf_palettes[[palette]]
if(reverse) pal <- rev(pal)
colorRampPalette(pal, ...)
} |
context("Tests of function spitcenter")
hexatestdf <- data.frame(
x = c(0,1,0,4,5,5,5,5),
y = c(1,1,4,4,1,1,4,4),
z = c(4,8,4,9,4,8,4,6)
)
center <- spitcenter(hexatestdf)
test_that(
"the output is a vector", {
expect_true(
is.vector(center)
)
}
)
test_that(
"the output has the correct length and names", {
expect_equal(
length(center),
3
)
expect_equal(
names(center),
c("x", "y", "z")
)
}
)
countercenter <- c(x = 3.125, y = 2.5, z = 5.875)
test_that(
"the output is as expected", {
expect_identical(
center,
countercenter
)
}
) |
prodB = function(x){
prod = 1
for (a in 1:length(x)) {
prod = prod*x[a]
}
return(prod)
}
dmnormB = function(x, mean, sigma){
dist = Brobdingnag::as.brob(t(x - mean) %*% solve(sigma) %*% (x - mean))
cte = (2*pi)^{-nrow(sigma)/2}*determinant(sigma, logarithm = FALSE)$modulus^{-1/2}
return(cte*exp(-1/2*dist))
}
dwishartB = function(x, nu, S){
k = ncol(x)
producto = Brobdingnag::as.brob(1)
for (i in 1:k) {
producto = producto*exp(Brobdingnag::as.brob(lgamma((nu + 1 - i)/2)))
}
densidades = (Brobdingnag::as.brob(2)^(nu*k/2)*Brobdingnag::as.brob(pi^(k*(k - 1)/4))*producto)^(-1) *
Brobdingnag::as.brob(det((1/nu)*S))^(-nu/2)*Brobdingnag::as.brob(det(x))^((nu - k - 1)/2) *
exp(Brobdingnag::as.brob(-0.5*sum(diag(solve((1/nu)*S) %*% x))))
return(densidades)
} |
estimVarCov_empProcess <- function(x, y, obs.data, known.p = NULL, comp.dist = NULL, comp.param = NULL)
{
if (is.null(obs.data)) {
stopifnot( (length(comp.dist) == 2) & (length(comp.param) == 2) )
if ( any(sapply(comp.dist, is.null)) | any(sapply(comp.param, is.null)) | is.null(known.p)) {
stop("All parameters of the admixture model must be specified to compute the exact Donsker correlation.")
}
exp.comp.dist <- paste0("p", comp.dist)
if (any(exp.comp.dist == "pmultinom")) { exp.comp.dist[which(exp.comp.dist == "pmultinom")] <- "stepfun" }
comp.ro <- sapply(X = exp.comp.dist, FUN = get, pos = "package:stats", mode = "function")
for (i in 1:length(comp.ro)) assign(x = names(comp.ro)[i], value = comp.ro[[i]])
make.expr.step <- function(i) paste(names(comp.ro)[i], "(x = 1:", length(comp.param[[i]][[2]]), paste(", y = ", paste("cumsum(c(0,",
paste(comp.param[[i]][[2]], collapse = ","), "))", sep = ""), ")", sep = ""), sep = "")
make.expr <- function(i) paste(names(comp.ro)[i], "(z,", paste(names(comp.param[[i]]), "=", comp.param[[i]], sep = "", collapse = ","), ")", sep="")
expr <- vector(mode = "character", length = length(exp.comp.dist))
expr[which(exp.comp.dist == "stepfun")] <- sapply(which(exp.comp.dist == "stepfun"), make.expr.step)
expr[which(expr == "")] <- sapply(which(expr == ""), make.expr)
expr <- unlist(expr)
if (any(exp.comp.dist == "stepfun")) {
F1.fun <- eval(parse(text = expr[1]))
F1 <- function(z) F1.fun(z)
G1.fun <- eval(parse(text = expr[2]))
G1 <- function(z) G1.fun(z)
} else {
F1 <- function(z) { eval(parse(text = expr[1])) }
G1 <- function(z) { eval(parse(text = expr[2])) }
}
L.CDF <- function(z) { known.p * F1(z) + (1-known.p) * G1(z) }
} else {
L.CDF <- stats::ecdf(obs.data)
}
res <- L.CDF(min(x,y)) * (1 - L.CDF(max(x,y)))
return(res)
} |
if(getRversion() >= "2.15.1") utils::globalVariables(c("experiment_list1", "observables"))
dream6_design <-
function(knobj, sample_function, seed, credits = 5000, file_to_save = NULL, verbose = T){
next_it <- TRUE
k <- 1
while(next_it){
if(verbose){
print(paste("Sample", k))
}
thetas <- sample_function(knobj)
knobj$datas[[length(knobj$datas)]]$thetas_est <- thetas
knobj$datas[[length(knobj$datas)]]$thetas <- thetas[sample(1:nrow(thetas), size = knobj$global_parameters$final_sample_design),]
risks <- c()
if(!is.null(file_to_save)){
saveRDS(knobj, file_to_save)
}
if(verbose){
print(paste("Estimate risk", k))
}
for(id_exp in 1:length(experiment_list1)){
experiment_fun <- experiment_list1[[id_exp]]
experiment_list1[[id_exp]]
res <- estimate_risk_dream6(thetas, knobj, experiment_fun)
res$Cost <- res$Cost + experiment_fun(NULL, NULL)$cost
res$exp <- names(experiment_list1)[id_exp]
risks <- rbind(risks,res)
print(id_exp)
}
if(verbose){
print(paste("Get data", k))
}
knobj$datas[[length(knobj$datas)]]$risks <- risks
if(!is.null(file_to_save)){
saveRDS(knobj, file_to_save)
}
risks <- risks[risks$Cost <= credits,]
temp_risk <- risks$Risk/risks$Cost
next_exp <- which.max(temp_risk)[1]
nnext_it <- paste(risks$exp[next_exp], risks$Measurement[next_exp]) %in% knobj$experiments
while(nnext_it){
temp_risk[next_exp] <- 0
next_exp <- which.max(temp_risk)[1]
nnext_it <- (paste(risks$exp[next_exp], risks$Measurement[next_exp]) %in% knobj$experiments) & (max(temp_risk)[1] > 0)
}
if(max(temp_risk)[1] <= 0){
break
}
knobj$experiments <- c(knobj$experiments, paste(risks$exp[next_exp], risks$Measurement[next_exp]) )
exp_fun_next_exp <- experiment_list1[[which(names(experiment_list1) == risks[next_exp, 4])]]
data_next_exp <- simulate_experiment(knobj$global_parameters$true_params_T, knobj, exp_fun_next_exp)
data_next_exp <- add_noise(data_next_exp)
to_observe <- observables[[ as.character(risks[next_exp,1]) ]]$obs
time_res <- observables[[ as.character(risks[next_exp,1]) ]]$reso
knobj$datas[[length(knobj$datas) + 1]] <- list(manip = experiment_list1[[which(names(experiment_list1) == risks[next_exp, 4])]], data = data_next_exp[data_next_exp[,1] %in% time_res,to_observe] )
credits <- credits - risks[next_exp,]$Cost
next_it <- (credits >= min(sapply(observables, FUN= function(x){x$cost})))
if(!is.null(file_to_save)){
saveRDS(knobj, file_to_save)
}
k <- k+1
}
if(verbose){
print(paste("Sample", k))
}
thetas <- sample_function(knobj)
knobj$datas[[length(knobj$datas)]]$thetas_est <- thetas
knobj$datas[[length(knobj$datas)]]$thetas <- thetas[sample(1:nrow(thetas), size = knobj$global_parameters$final_sample_design),]
if(!is.null(file_to_save)){
saveRDS(knobj, file_to_save)
}
knobj
} |
ctable <- function(x,
y,
prop = st_options("ctable.prop"),
useNA = "ifany",
totals = st_options("ctable.totals"),
style = st_options("style"),
round.digits = st_options("ctable.round.digits"),
justify = "right",
plain.ascii = st_options("plain.ascii"),
headings = st_options("headings"),
display.labels = st_options("display.labels"),
split.tables = Inf,
dnn = c(substitute(x), substitute(y)),
chisq = FALSE,
OR = FALSE,
RR = FALSE,
weights = NA,
rescale.weights = FALSE,
...) {
if (any(grepl("group_by(", deparse(sys.calls()[[1]]), fixed = TRUE))) {
stop("ctable() doesn't support group_by(); use stby() instead")
}
if (length(dim(x)) == 2) {
x_tmp <- x[[1]]
y <- x[[2]]
x <- x_tmp
flag_by <- TRUE
} else {
flag_by <- FALSE
}
if (inherits(x, "data.frame") && ncol(x) == 1) {
x <- x[[1]]
}
if (inherits(y, "data.frame") && ncol(y) == 1) {
y <- y[[1]]
}
errmsg <- character()
if (!is.factor(x) && !is.atomic(x)) {
x <- try(as.vector(x), silent = TRUE)
if (inherits(x, "try-error")) {
errmsg %+=% "'x' must be a factor or an object coercible to a vector"
}
}
if (!is.factor(y) && !is.atomic(x)) {
y <- try(as.vector(y), silent = TRUE)
if (inherits(y, "try-error")) {
errmsg %+=% "'y' must be a factor or an object coercible to a vector"
}
}
errmsg <- c(errmsg, check_args(match.call(), list(...)))
if (length(errmsg) > 0) {
stop(paste(errmsg, collapse = "\n "))
}
if (style == "rmarkdown" && isTRUE(plain.ascii) &&
(!"plain.ascii" %in% (names(match.call())))) {
plain.ascii <- FALSE
}
if (NaN %in% x) {
message(paste(sum(is.nan(x)), "NaN value(s) converted to NA in x\n"))
x[is.nan(x)] <- NA
}
if (NaN %in% y) {
message(paste(sum(is.nan(y)), "NaN value(s) converted to NA in y\n"))
y[is.nan(y)] <- NA
}
if (isTRUE(flag_by)) {
parse_info_x <- try(
parse_args(sys.calls(), sys.frames(), match.call(),
var = c("x", "y"), silent = "dnn" %in% names(match.call()),
var_label = FALSE, caller = "ctable"),
silent = TRUE)
if (inherits(parse_info_x, "try-error")) {
parse_info_x <- list()
} else {
if (!is.null(parse_info_x$df_name)) {
df_name <- parse_info_x$df_name
}
if (!is.null(parse_info_x$df_label)) {
df_label <- parse_info_x$df_label
}
}
} else {
parse_info_x <- try(
parse_args(sys.calls(), sys.frames(), match.call(),
var = "x", silent = "dnn" %in% names(match.call()),
var_label = FALSE, caller = "ctable"),
silent = TRUE)
if (inherits(parse_info_x, "try-error")) {
parse_info_x <- list()
}
parse_info_y <- try(
parse_args(sys.calls(), sys.frames(), match.call(),
var = "y", silent = "dnn" %in% names(match.call()),
var_label = FALSE, caller = "ctable"),
silent = TRUE)
if (inherits(parse_info_y, "try-error")) {
parse_info_y <- list()
}
if (length(parse_info_x$df_name) == 1 &&
length(parse_info_y$df_name) == 1 &&
isTRUE(parse_info_x$df_name == parse_info_y$df_name)) {
df_name <- parse_info_x$df_name
}
if (length(parse_info_x$df_label) == 1) {
df_label <- parse_info_x$df_label
}
}
if ("dnn" %in% names(match.call())) {
x_name <- dnn[1]
y_name <- dnn[2]
} else if (!isTRUE(flag_by)) {
x_name <- na.omit(c(parse_info_x$var_name, deparse(dnn[[1]])))[1]
y_name <- na.omit(c(parse_info_y$var_name, deparse(dnn[[2]])))[1]
} else {
x_name <- na.omit(c(parse_info_x$var_name[1], deparse(dnn[[1]])))[1]
y_name <- na.omit(c(parse_info_x$var_name[2], deparse(dnn[[2]])))[1]
}
if (identical(NA, weights)) {
freq_table <- table(x, y, useNA = useNA)
freq_table_min <- table(x, y, useNA = "no")
} else {
weights_string <- deparse(substitute(weights))
if (isTRUE(flag_by)) {
pf <- parent.frame(2)
weights <- weights[pf$X[[pf$i]]]
}
if (sum(is.na(weights)) > 0) {
warning("missing values on weight variable have been detected and were ",
"treated as zeroes")
weights[is.na(weights)] <- 0
}
if (isTRUE(rescale.weights)) {
weights <- weights / sum(weights) * length(x)
}
if (useNA == "no") {
freq_table <- xtabs(weights ~ x + y, addNA = FALSE)
freq_table_min <- freq_table
} else {
freq_table <- xtabs(weights ~ x + y, addNA = TRUE)
freq_table_min <- xtabs(weights ~ x + y, addNA = FALSE)
}
}
names(dimnames(freq_table)) <- c(x_name, y_name)
prop_table <- switch(prop,
t = prop.table(freq_table),
r = prop.table(freq_table, 1),
c = prop.table(freq_table, 2),
n = NULL)
freq_table <- addmargins(freq_table)
rownames(freq_table)[nrow(freq_table)] <- trs("total")
colnames(freq_table)[ncol(freq_table)] <- trs("total")
if (!is.null(prop_table)) {
prop_table[is.nan(prop_table)] <- 0
if (prop == "t") {
prop_table <- addmargins(prop_table)
} else if (prop == "r") {
prop_table <- addmargins(prop_table, 2)
sum_props <- c(prop.table(freq_table[nrow(freq_table),
-ncol(freq_table)]),
Total = 1)
prop_table <- rbind(prop_table, sum_props)
} else if (prop == "c") {
prop_table <- addmargins(prop_table, 1)
sum_props <- c(prop.table(freq_table[-nrow(freq_table),
ncol(freq_table)]),
Total = 1)
prop_table <- cbind(prop_table, sum_props)
}
rownames(prop_table)[nrow(prop_table)] <- trs("total")
colnames(prop_table)[ncol(prop_table)] <- trs("total")
}
if (NA %in% rownames(freq_table)) {
row.names(freq_table)[is.na(row.names(freq_table))] <- "<NA>"
if (prop != "n") {
row.names(prop_table)[is.na(row.names(prop_table))] <- "<NA>"
}
}
if (NA %in% colnames(freq_table)) {
colnames(freq_table)[is.na(colnames(freq_table))] <- "<NA>"
if (prop != "n") {
colnames(prop_table)[is.na(colnames(prop_table))] <- "<NA>"
}
}
output <- list(cross_table = freq_table,
proportions = prop_table)
class(output) <- c("summarytools", class(output))
attr(output, "st_type") <- "ctable"
attr(output, "fn_call") <- match.call()
attr(output, "date") <- Sys.Date()
if (isTRUE(chisq)) {
tmp.chisq <- chisq.test(freq_table_min)
tmp.chisq <- c(Chi.squared = round(tmp.chisq$statistic[[1]], 4),
tmp.chisq$parameter,
p.value = round(tmp.chisq$p.value, 4))
attr(output, "chisq") <- tmp.chisq
}
if (!isFALSE(OR) || !isFALSE(RR)) {
if (identical(as.numeric(dim(freq_table_min)), c(2,2))) {
if (!isFALSE(OR)) {
or <- prod(freq_table_min[c(1,4)]) / prod(freq_table_min[c(2,3)])
se <- sqrt(sum(1/freq_table_min))
attr(output, "OR") <- c(or,
exp(log(or) - qnorm(p = 1 - ((1 - OR)/2)) * se),
exp(log(or) + qnorm(p = 1 - ((1 - OR)/2)) * se))
names(attr(output, "OR")) <- c("Odds Ratio", paste0("Lo - ", OR * 100, "%"),
paste0("Hi - ", OR * 100, "%"))
attr(output, "OR-level") <- OR
}
if (!isFALSE(RR)) {
rr <- (freq_table_min[1] / sum(freq_table_min[c(1,3)])) /
(freq_table_min[2] / sum(freq_table_min[c(2,4)]))
se <- sqrt(sum(1/freq_table_min[1],
1/freq_table_min[2],
-1/sum(freq_table_min[c(1,3)]),
-1/sum(freq_table_min[c(2,4)])))
attr(output, "RR") <- c(rr,
exp(log(rr) - qnorm(p = 1 - ((1 - RR)/2)) * se),
exp(log(rr) + qnorm(p = 1 - ((1 - RR)/2)) * se))
names(attr(output, "RR")) <- c("Risk Ratio", paste0("Lo - ", RR * 100, "%"),
paste0("Hi - ", RR * 100, "%"))
attr(output, "RR-level") <- RR
}
} else {
message("OR and RR can only be used with 2 x 2 tables; parameter(s) ignored")
}
}
if (all(c("ordered", "factor") %in% class(x))) {
Data.type.x <- trs("factor.ordered")
} else if ("factor" %in% class(x)) {
Data.type.x <- trs("factor")
} else if (all(c("POSIXct", "POSIXt") %in% class(x))) {
Data.type.x <- trs("datetime")
} else if ("Date" %in% class(x)) {
Data.type.x <- trs("date")
} else if ("logical" %in% class(x)) {
Data.type.x <- trs("logical")
} else if ("character" %in% class(x)) {
Data.type.x <- trs("character")
} else if ("integer" %in% class(x)) {
Data.type.x <- trs("integer")
} else if ("numeric" %in% class(x)) {
Data.type.x <- trs("numeric")
} else {
Data.type.x <- ifelse(mode(x) %in% rownames(.keywords_context),
trs(mode(x)), mode(x))
}
if (all(c("ordered", "factor") %in% class(y))) {
Data.type.y <- trs("factor.ordered")
} else if ("factor" %in% class(y)) {
Data.type.y <- trs("factor")
} else if (all(c("POSIXct", "POSIXt") %in% class(y))) {
Data.type.y <- trs("datetime")
} else if ("Date" %in% class(y)) {
Data.type.y <- trs("date")
} else if ("logical" %in% class(y)) {
Data.type.y <- trs("logical")
} else if ("character" %in% class(y)) {
Data.type.y <- trs("character")
} else if ("integer" %in% class(y)) {
Data.type.y <- trs("integer")
} else if ("numeric" %in% class(y)) {
Data.type.y <- trs("numeric")
} else {
Data.type.y <- ifelse(mode(y) %in% rownames(.keywords_context),
trs(mode(y)), mode(y))
}
dfn <- ifelse(exists("df_name", inherits = FALSE), df_name, NA)
data_info <-
list(Data.frame = ifelse(exists("df_name", inherits = FALSE),
df_name, NA),
Data.frame.label = ifelse(exists("df_label", inherits = FALSE),
df_label, NA),
Row.variable = x_name,
Row.variable.label = ifelse(!is.na(label(x)), label(x), NA),
Col.variable = y_name,
Col.variable.label = ifelse(!is.na(label(y)), label(y), NA),
Row.x.Col = paste(x_name, y_name, sep = " * "),
Proportions = switch(prop,
r = "Row",
c = "Column",
t = "Total",
n = "None"),
Data.type.x = Data.type.x,
Data.type.y = Data.type.y,
Weights = ifelse(identical(weights, NA), NA,
ifelse(is.na(dfn),
weights_string,
sub(pattern = paste0(dfn, "$"),
replacement = "",
x = weights_string,
fixed = TRUE))),
Group = ifelse("by_group" %in% names(parse_info_x),
parse_info_x$by_group, NA),
by_first = ifelse("by_group" %in% names(parse_info_x),
parse_info_x$by_first, NA),
by_last = ifelse("by_group" %in% names(parse_info_x),
parse_info_x$by_last , NA))
attr(output, "data_info") <- data_info[!is.na(data_info)]
attr(output, "format_info") <- list(style = style,
round.digits = round.digits,
plain.ascii = plain.ascii,
justify = justify,
totals = totals,
split.tables = split.tables,
headings = headings,
display.labels = display.labels)
attr(output, "user_fmt") <- list(... = ...)
attr(output, "lang") <- st_options("lang")
return(output)
} |
SSbiologytables <- function (replist = NULL, printfolder="tables", dir="default", fleetnames = "default", selexyr = "default")
{
print.numeric <- function(x, digits) { formatC(x, digits = digits, format = "f") }
inputs <- replist$inputs
biology <- replist$endgrowth
nsexes <- replist$nsexes
nfleets <- replist$nfleets
lbinspop <- replist$lbinspop
nlbinspop <- replist$nlbinspop
sizeselex <- replist$sizeselex
ageselex <- replist$ageselex
accuage <- replist$accuage
FleetNames <- replist$FleetNames
if(dir=="default"){
dir <- inputs$dir }
plotdir <- file.path(dir,printfolder)
plotdir.isdir <- file.info(plotdir)$isdir
if(is.na(plotdir.isdir) | !plotdir.isdir){
dir.create(plotdir) }
if(fleetnames[1]=="default"){
fleetnames <- FleetNames }
if(selexyr[1]=="default"){
selexyr <- replist$endyr }
bio = data.frame(Age = biology[biology$Sex == 1, "Age_Beg"],
Ave_Length_f = print(biology[biology$Sex == 1, "Len_Beg"] ,digits = 1),
Ave_Wght_f = print(biology[biology$Sex == 1, "Wt_Beg"] ,digits = 2),
Mature_f = print(biology[biology$Sex == 1, "Len_Mat"] ,digits = 2),
Fecund_f = print(biology[biology$Sex == 1, "Mat*Fecund"],digits = 2))
if (nsexes == 2){
bio = data.frame(bio,
Ave_Length_m = print(biology[biology$Sex == 2, "Len_Beg"],digits = 1),
Ave_Wght_m = print(biology[biology$Sex == 2, "Wt_Beg"], digits = 2),
Mature_m = print(biology[biology$Sex == 2, "Len_Mat"],digits = 2)) }
write.csv(bio, paste0(plotdir, "/biology_by_age.csv"), row.names = F)
selex.age = selex.age.ret = data.frame(Age = 0:accuage)
for(j in 1:nsexes){
for (i in 1:nfleets){
ind = ageselex[!is.na(ageselex$Fleet), "Fleet"] == i
find = which(ageselex[ind, "Sex"] == j & ageselex[ind, "Yr"] == selexyr & ageselex[ind,"Factor"] == "Asel")
selex.age = data.frame(selex.age, print(as.numeric(ageselex[find,8:dim(ageselex)[2]]), digits = 2))
}
}
colnames(selex.age) = c("Age", paste0(FleetNames, "_f"), paste0(FleetNames, "_m"))
write.csv(selex.age, paste0(plotdir, "/selectivity_by_age.csv"), row.names = F)
retnames = NULL
selex.size = selex.size.ret = data.frame(Length = as.numeric(names(sizeselex[6:dim(sizeselex)[2]])) )
for(j in 1:nsexes){
for (i in 1:nfleets){
find = which(sizeselex$Fleet == i & sizeselex$Sex == j & sizeselex$Yr == selexyr & sizeselex$Factor == "Lsel")
selex.size = data.frame(selex.size, print(as.numeric(sizeselex[find, 6:dim(sizeselex)[2]]), digits = 2))
find = which(sizeselex$Fleet == i & sizeselex$Sex == j & sizeselex$Yr == selexyr & sizeselex$Factor == "Keep")
if (length(find) != 0){
if(j == 1) { retnames = c(retnames, FleetNames[i]) }
selex.size.ret = data.frame(selex.size.ret, print(as.numeric(sizeselex[find, 6:dim(sizeselex)[2]]), digits = 2)) }
}
}
colnames(selex.size) = c("Length", paste0(FleetNames, "_f"), paste0(FleetNames, "_m"))
colnames(selex.size.ret) = c("Length", paste0(retnames, "_f"), paste0(retnames, "_m"))
write.csv(selex.size, paste0(plotdir, "/selectivity_by_size.csv"), row.names = F)
write.csv(selex.size.ret, paste0(plotdir, "/retention_by_size.csv"), row.names = F)
} |
suppressPackageStartupMessages({
library(bcTSNE)
library(data.table)
library(SingleCellExperiment)
library(RSpectra)
library(batchelor)
library(kBET)
library(Rtsne)
library(lisi)
library(harmony)
library(dlfUtils)
library(scater)
})
path <- "mouse_raw_data_allcells_Notscaled.tsv"
dat <- fread(path)
dat <- dat[TREATMENT == "Vehicle"]
dat[ , TREATMENT := NULL]
mCols <- c("CELL", "SEX", "DATE", "NODEID", "MOUSE")
mDat <- dat[ , .SD, .SDcols = mCols]
mDat[ , CELLTYPE := NODEID]
mDat[grepl("Node", NODEID), CELLTYPE := "Other"]
mDat[grepl("Neurons", NODEID), CELLTYPE := "Other"]
mDat[grepl("Vascular", NODEID), CELLTYPE := "Other"]
cCols <- setdiff(names(dat), mCols)
cDat <- data.table(GENE = cCols)
tmp <- t(as.matrix(dat[ , .SD, .SDcols = cCols]))
sce <- SingleCellExperiment(assays = list(counts = tmp),
colData = mDat,
rowData = cDat)
sizeFactors(sce) <- librarySizeFactors(sce)
sce <- normalize(sce, return_log = FALSE)
sce <- normalize(sce)
assay(sce, "centered") <- t(scale(t(normcounts(sce)), scale = FALSE))
SVD <- svds(A = t(assay(sce, "centered")), k = 50)
reducedDim(sce) <- SVD$u %*% diag(SVD$d)
reducedDimNames(sce) <- "PCA"
saveRDS(sce, "real.sce")
rm(dat, tmp, mDat, cDat, SVD, mCols, cCols); gc();
res <- vector(mode = "list", length = 4)
names(res) <- c("tsne", "bcts", "hmny", "mnn")
set.seed(1234)
res$tsne <- Rtsne(reducedDim(sce), pca = FALSE)
set.seed(1234)
res$bcts <- bctsne(X = t(assay(sce, "centered")),
Z = model.matrix( ~ -1 + factor(colData(sce)$MOUSE)),
k = 50,
perplexity = 30,
maxIter = 1000)
set.seed(1234)
sce <- RunHarmony(sce, group.by.vars = "MOUSE")
res$hmny = Rtsne(as.matrix(reducedDim(sce, "HARMONY")), pca = FALSE)
set.seed(1234)
mnnSCE <- fastMNN(sce, batch = factor(colData(sce)$MOUSE))
res$mnn <- Rtsne(reducedDim(mnnSCE), pca = FALSE)
res <- lapply(res, "[[", "Y")
saveRDS(res, "real.res")
calcMetrics <- function(Y, bchLst) {
calcSil <- function(x) {
s <- batch_sil(pca.data = list(x = Y), batch = x, nPCs = 2)
1 - abs(s)
}
calcKBET <- function(x) {
kBET(Y, batch = x, do.pca = FALSE, plot = FALSE)$average
}
calcPCA <- function(x) {
pcRegression(pca.data = prcomp(Y), batch = x, n_top = 2)$pcReg
}
sil <- sapply(bchLst, calcSil)
kbet <- sapply(bchLst, calcKBET)
lisi <- compute_lisi(Y,
meta_data = as.data.frame(bchLst),
label_colnames = names(bchLst))
lisi <- colMeans(lisi)
sizes <- sapply(bchLst, function(x) length(unique(x)))
lisi <- (lisi - 1)/(sizes - 1)
pca <- sapply(bchLst, calcPCA)
res <- list(sil = sil, kbet = kbet, lisi = lisi, pca = pca)
do.call(cbind, res)
}
bchLst <- as.list(colData(sce)[ , c("SEX", "DATE", "MOUSE", "CELLTYPE")])
bchLst <- lapply(bchLst, factor)
metrics <- lapply(res, calcMetrics, bchLst = bchLst)
saveRDS(metrics, "real.metrics") |
get_efforts_list <- function(stoken, id, athlete_id=NULL, start_date_local=NULL, end_date_local=NULL){
queries <- list(athlete_id=athlete_id,
start_date_local=start_date_local,
end_date_local=end_date_local)
dataRaw <- get_pages(url_segment(id, request="all_efforts"), stoken, queries=queries, All=TRUE)
return(dataRaw)
} |
f.post.poo.diff <- function(coeff, covar){
.names <- rownames(coeff[[1]])
.tmp <- f.coefnames(.names)
.cm <- .tmp$child.poo.m
.cf <- .tmp$child.poo.f
.D0 <- diag(length(coeff[[1]]))
dimnames(.D0) <- list(.names, .names)
.Dm <- .D0[.cm, , drop = F]
.Df <- .D0[.cf, , drop = F]
.Dm[, .cf] <- -.Df[, .cf]
rownames(.Dm) <- paste("cm_", .cf, sep = "")
.D <- rbind(.D0, .Dm)
.coef <- lapply(coeff, function(x) .D %*% x)
.cov <- lapply(covar, function(x) .D %*% x %*% t(.D))
.vis <- F
if(.vis){
f.vis(.D, vis = .vis)
f.vis(coeff[[1]], vis = .vis)
f.vis(.D %*% coeff[[1]], vis = .vis)
f.vis(.coef, vis = .vis)
f.vis(.cov, vis = .vis)
}
return(list(coeff = .coef, covar = .cov))
} |
print.summary.stabit2 <- function(x, ...){
if(x$method=="Klein-selection"){
if(x$mfx==TRUE){
cat("\nMarginal effects for two-sided matching model.")
} else{
cat("\nCoefficients for two-sided matching model.")
}
} else{
if(x$mfx==TRUE){
cat("\nMarginal effects for multi-index sample selection model.")
} else{
cat("\nCoefficients for multi-index sample selection model.")
}
}
if(x$method=="Klein-selection"){
cat("\nMethod: Klein (2016)\n")
} else if(x$method=="Klein"){
cat("\nMethod: Klein (2016), two-sided matching market\n")
} else if(x$method=="Sorensen"){
cat("\nMethod: Sorensen (2007), two-sided matching market\n")
} else{
cat("\nMethod: Klein (2015), one-sided matching market\n")
}
cat("\nCall:\n")
print(x$call)
if(x$method!="Outcome-only"){
if(x$method=="Klein" | x$method=="Klein-selection"){
cat("\nSelection equation (Valuation over colleges):")
cat("\n")
printCoefmat(x$college, P.values=TRUE, has.Pvalue=TRUE, signif.legend=FALSE)
cat("\nSelection equation (Valuation over students):")
cat("\n")
printCoefmat(x$student, P.values=TRUE, has.Pvalue=TRUE, signif.legend=FALSE)
} else{
cat("\nSelection equation:")
cat("\n")
printCoefmat(x$selection, P.values=TRUE, has.Pvalue=TRUE, signif.legend=FALSE)
}
}
if(x$method!="Klein-selection"){
cat("\nOutcome equation:")
cat("\n")
printCoefmat(x$outcome, P.values=TRUE, has.Pvalue=TRUE, signif.legend=FALSE)
}
cat("---\nSignif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1")
} |
psf <- function (data, k = seq(2,10), w = seq(1,10), cycle = 24) {
series = convert_datatype(data)
if (is.ts(data)) cycle = frequency(data)
fit = nrow(series) %% cycle
if (fit > 0) {
warning(paste("Time series length is not multiple of", cycle, ". Cutting last", fit, "values!"))
series = series[1:(.N - fit)]
}
dmin = series[, min(data)]; dmax = series[, max(data)]
series[, data := (data - dmin) / (dmax - dmin)]
dataset = as.data.table(t(matrix(series[,data], nrow = cycle)))
if (length(k) > 1)
k = optimum_k(dataset, k)
if (length(w) > 1)
w = optimum_w(dataset, k, w, cycle)
res = list(original_series = data, train_data = dataset, k = k, w = w, cycle = cycle, dmin = dmin, dmax = dmax)
class(res) <- "psf"
return(res)
} |
context("asymptotic cumulative distribution of CUSUM")
test_that("The output of pKSdist and pbessel has the correct format",
{
x <- runif(1, 0, 10)
y <- pKSdist(x)
Y <- pBessel(x, 2L)
expect_true(is.numeric(y))
expect_equal(length(y), 1)
expect_true(is.numeric(Y))
expect_equal(length(Y), 1)
})
test_that("pKSdist returns the correct value",
{
expect_equal(pKSdist(4), 1)
expect_equal(pKSdist(-1), 0)
skip_on_cran()
n <- 1001
times <- seq(0, 1, length.out = n)
res <- replicate(10000,
{
dW <- rnorm(n) / sqrt(n)
W <- cumsum(dW)
B <- W - times * W[n]
max(abs(B))
})
expect_equal(pKSdist(0.5), mean(res <= 0.5), tolerance = 0.05)
expect_equal(pKSdist(1), mean(res <= 1), tolerance = 0.05)
expect_equal(pKSdist(1.5), mean(res <= 1.5), tolerance = 0.05)
})
test_that("pBessel returns the correct value",
{
expect_equal(pBessel(2.114, 2), 0.9, tolerance = 1e-4)
expect_equal(pBessel(3.396, 2), 0.99, tolerance = 1e-5)
expect_equal(pBessel(32.624, 100), 0.9, tolerance = 1e-4)
expect_equal(pBessel(36.783, 100), 0.99, tolerance = 1e-5)
}) |
knitr::opts_chunk$set(echo = TRUE)
backup_options <- options()
options(width = 1000)
set.seed(1991)
knitr::include_graphics("UCB.png")
options(backup_options) |
NULL
setGeneric(name = "setCRS",
def = function(x, crs, ...){
standardGeneric("setCRS")
}
)
setMethod(f = "setCRS",
signature = "ANY",
definition = function(x){
warning(paste0("I can't set a coordinate reference system to an object of class '", paste0(class(x), collapse = ", "), "'."))
}
)
setMethod(f = "setCRS",
signature = "geom",
definition = function(x, crs = NULL){
if(is.na(x@crs)){
x@crs <- crs
} else{
theCoords <- x@point[which(names(x@point) %in% c("x", "y"))]
if(!all(c("+proj=longlat", "+ellps=WGS84") %in% strsplit(x@crs, " ")[[1]])){
geographic <- project(as.matrix(theCoords), proj = as.character(x@crs), inv = TRUE)
} else{
geographic <- as.matrix(theCoords)
}
if(crs != "+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs"){
projected <- project(geographic, proj = as.character(crs))
} else{
projected <- geographic
}
x@point <- data.frame(projected, x@point[which(!names(x@point) %in% c("x", "y"))])
x@crs <- crs
x <- setWindow(x = x, to = getExtent(x))
}
x@history <- c(getHistory(x = x), list(paste0("the crs was set to '", crs, "'.")))
return(x)
}
)
setMethod(f = "setCRS",
signature = signature("Spatial"),
definition = function(x, crs = NULL){
if(is.na(x@proj4string)){
x@proj4string <- crs(crs)
} else{
x <- spTransform(x, CRSobj = crs(crs))
}
return(x)
}
)
setMethod(f = "setCRS",
signature = "sf",
definition = function(x, crs = NULL){
if(is.na(st_crs(x = x)$proj4string)){
x <- st_set_crs(x = x, value = crs)
} else{
x <- st_transform(x, crs = crs)
}
return(x)
}
)
setMethod(f = "setCRS",
signature = "Raster",
definition = function(x, crs = NULL){
if(is.na(x@crs)){
x@crs <- crs(crs)
} else{
x <- projectRaster(from = x, crs = crs(crs))
}
x@history <- c(getHistory(x = x), list(paste0("the crs was set to '", crs, "'.")))
return(x)
}
) |
dataFolder = file.path(mainFolder, "data")
dataFileType.df = read.table( paste(dataFolder, "00filelist.csv", sep="/"), skip=2, sep="," ,stringsAsFactors = TRUE, as.is = FALSE)
dataFiles = fac2char.fn(dataFileType.df[,1])
subjectTypes = fac2char.fn(dataFileType.df[,2])
nFile = length(dataFiles)
dataFileSuffix = ".csv"
sensorIDs = gsub(dataFileSuffix, "", dataFiles, fixed=TRUE)
Skip = 3
Header = FALSE
if( !Header ) columnNames = c("Serial", "Meter", "Time", "Glucose")
Comment.char=""
Sep=","
timeStamp.column = "Time"
responseName = "Glucose"
timeUnit = "minute"
equal.interval = 3
time.format = "yyyy:mm:dd:hh:nn"
idxNA = 0
r <- 0.15
m <- 2
I <- 400000
scaleMax <- 10; scaleStep <- 1
Scales <- seq(1, scaleMax, by=scaleStep)
cFile = "mseLong.c"
Summary = TRUE
Boxplot = TRUE |
sf_analytics_notifications_list <- function(source=c("lightningDashboardSubscribe",
"lightningReportSubscribe",
"waveNotification"),
owner_id=NULL,
record_id=NULL){
source <- match.arg(source, several.ok = TRUE)
.NotYetImplemented()
}
sf_analytics_notifications_limits <- function(source=c("lightningDashboardSubscribe",
"lightningReportSubscribe",
"waveNotification"),
record_id=NULL){
source <- match.arg(source, several.ok = TRUE)
.NotYetImplemented()
}
sf_analytics_notification_create <- function(body){
.NotYetImplemented()
}
sf_analytics_notification_describe <- function(notification_id){
.NotYetImplemented()
}
sf_analytics_notification_update <- function(notification_id, body){
.NotYetImplemented()
}
sf_analytics_notification_delete <- function(notification_id){
.NotYetImplemented()
} |
require(lavaan)
require(SEMsens)
set.seed(1)
lower = '
1.00
.40 1.00
.40 .64 1.00
.41 .66 .61 1.00
.42 .52 .53 .61 1.00
.34 .50 .46 .53 .48 1.00
.42 .47 .41 .43 .47 .55 1.00
.39 .46 .39 .30 .21 .30 .37 1.00
.24 .31 .30 .31 .26 .32 .27 .56 1.00
.33 .35 .35 .40 .31 .25 .35 .51 .42 1.00
.30 .42 .36 .32 .24 .37 .43 .44 .37 .49 1.00'
sample.cov = getCov(lower, sds = c(5.64,14.68,6.57,6.07,3.39,10.16,6.11,4.91,15.59,0.96,0.99),
names = c("Working_memory",
"Vocabulary",
"Grammar",
"Inference",
"ToM",
"TNL",
"Expository",
"Spelling",
"Sentence_copying",
"One_day",
"Castle"))
model <-'Vocabulary~Working_memory
Grammar~Working_memory
Inference~Vocabulary+Grammar+Working_memory
ToM~Vocabulary+Grammar+Working_memory
Spelling~Working_memory
Sentence_copying~Working_memory
Discourse~Inference+ToM+Vocabulary+Grammar+Working_memory
Writing~Spelling+Sentence_copying+Discourse
Discourse=~TNL+Expository
Writing=~One_day+Castle
Vocabulary~~Grammar
Grammar~~Sentence_copying
Vocabulary~~Sentence_copying
Grammar~~Spelling
Vocabulary~~Spelling
Inference~~ToM
Discourse~~Sentence_copying
Discourse~~Spelling
Spelling~~Sentence_copying'
sens.model <- 'Vocabulary~Working_memory
Grammar~Working_memory
Inference~Vocabulary+Grammar+Working_memory
ToM~Vocabulary+Grammar+Working_memory
Spelling~Working_memory
Sentence_copying~Working_memory
Discourse~Inference+ToM+Vocabulary+Grammar+Working_memory
Writing~Spelling+Sentence_copying+Discourse
Discourse=~TNL+Expository
Writing=~One_day+Castle
Vocabulary~~Grammar
Grammar~~Sentence_copying
Vocabulary~~Sentence_copying
Grammar~~Spelling
Vocabulary~~Spelling
Inference~~ToM
Discourse~~Sentence_copying
Discourse~~Spelling
Spelling~~Sentence_copying
Working_memory ~ phantom1*phantom
Grammar ~ phantom2*phantom
Vocabulary ~ phantom3*phantom
ToM ~ phantom4*phantom
Inference ~ phantom5*phantom
Spelling ~ phantom6*phantom
Sentence_copying ~ phantom7*phantom
Discourse ~ phantom8*phantom
Writing ~ phantom9*phantom
phantom =~ 0
phantom ~~ 1*phantom'
paths <- 'Vocabulary~Working_memory
Grammar~Working_memory
Inference~Vocabulary+Grammar+Working_memory
ToM~Vocabulary+Grammar+Working_memory
Spelling~Working_memory
Sentence_copying~Working_memory
Discourse~Inference+ToM+Vocabulary+Grammar+Working_memory
Writing~Spelling+Sentence_copying+Discourse'
my.sa <-sa.aco(model = model, sens.model = sens.model, sample.cov = sample.cov,
sample.nobs = 193, k = 50, max.value= 2000, max.iter = 100,
opt.fun = 4,
paths = paths, seed = 1, verbose = FALSE)
my.table <- sens.tables(my.sa)
my.table[[1]]
my.table[[2]]
my.table[[3]]
my.table[[4]]
my.table[[5]] |
test_that("as.data.frame with src_yaml", {
expect_equal(as.data.frame(supreme(src_yaml(example_yaml()))),
structure(
list(
name = c(
"server",
"customers_tab_module_server",
"items_tab_module_server",
"transactions_tab_module_server",
"module_modal_dialog"
),
input = list(
NA_character_,
"customers_list",
c("items_list", "is_fired"),
c("table", "button_clicked"),
"text"
),
output = list(
NA_character_,
c("paid_customers_table",
"free_customers_table"),
NA_character_,
"transactions_table",
NA_character_
),
return = structure(c(NA, NA, NA, "transactions_keys",
NA), class = "AsIs"),
calling_modules = structure(
list(
list(
list(items_tab_module_server = "ItemsTab"),
list(customers_tab_module_server = "CustomersTab"),
list(transactions_tab_module_server = "TransactionsTab")
),
NA_character_,
list(list(module_modal_dialog = NULL)),
NA_character_,
NA_character_
),
class = "AsIs"
),
src = c(
"app.R",
"module-customers.R",
"module-items.R",
"module-transactions.R",
"module-utils.R"
)
),
row.names = c(NA,-5L),
class = "data.frame"
))
model <- "
- name: childModuleA
input: [input.data, reactive]
calling_modules:
- grandChildModule1: ~
- name: grandChildModule1
input: selected.model
"
obj <- supreme(src_yaml(text = model))
expect_equal(as.data.frame(obj),
structure(
list(
name = c("childModuleA", "grandChildModule1"),
input = structure(list(
c("input.data", "reactive"), "selected.model"
), class = "AsIs"),
output = structure(c(NA_character_, NA_character_), class = "AsIs"),
return = structure(c(NA_character_, NA_character_), class = "AsIs"),
calling_modules = structure(list(list(
list(grandChildModule1 = NULL)
), NA_character_), class = "AsIs"),
src = c(NA_character_, NA_character_)
),
row.names = c(NA,-2L),
class = "data.frame"
))
})
test_that("as.data.frame with src_file", {
expect_equal(as.data.frame(supreme(src_file(example_app_path()))),
structure(
list(
name = c(
"server",
"customers_tab_module_server",
"items_tab_module_server",
"transactions_tab_module_server",
"module_modal_dialog"
),
input = list(
NA_character_,
"customers_list",
c("items_list", "is_fired"),
c("table", "button_clicked"),
"text"
),
output = list(
NA_character_,
c("paid_customers_table",
"free_customers_table"),
NA_character_,
"transactions_table",
NA_character_
),
return = structure(c(NA, NA, NA, "transactions_keys",
NA), class = "AsIs"),
calling_modules = structure(
list(
list(
list(items_tab_module_server = "ItemsTab"),
list(customers_tab_module_server = "CustomersTab"),
list(transactions_tab_module_server = "TransactionsTab")
),
NA_character_,
list(list(module_modal_dialog = NULL)),
NA_character_,
NA_character_
),
class = "AsIs"
),
src = c(
"app.R",
"module-customers.R",
"module-items.R",
"module-transactions.R",
"module-utils.R"
)
),
row.names = c(NA,-5L),
class = "data.frame"
))
}) |
require(testthat)
context("Test mccr")
test_that("calc MCC value",{
set.seed(18)
act <- abs(round(rnorm(100))) %% 2
pred <- abs(round(rnorm(100))) %% 2
score <- mccr(act, pred)
score <- round(score, 1)
expect_equal(0, 0)
}) |
to_network <- function(x){
if (!requireNamespace("network", quietly = TRUE)) {
stop("network package required to coerce data to 'network' type!", call. = FALSE)
}
UseMethod("to_network", x)
}
to_network.network <- function(x){
x
}
to_network.edgeList <- function(x){
if(num.edges(x) > 0){
adj <- as.matrix(get.adjacency.matrix(x))
network::as.network(adj, matrix.type = "adjacency")
} else{
network::network.initialize(num.nodes(x))
}
}
to_network.graphNEL <- function(x){
to_network(to_edgeList(x))
}
to_network.igraph <- function(x){
to_network(to_edgeList(x))
}
to_network.bn <- function(x){
to_network(to_edgeList(x))
}
to_network.sparsebnFit <- function(x){
x$edges <- to_network(x$edges)
x
}
to_network.sparsebnPath <- function(x){
sparsebnPath(lapply(x, to_network))
}
edgeList_to_network_edgelist <- function(el){
edgeList_to_igraph_edgelist(el)
}
to_edgeList.network <- function(x){
edgeList(network_to_edgeList_list(x))
}
network_to_edgeList_list <- function(net){
net.edgelist <- network::as.edgelist(net)
numnode <- network::network.size(net)
edgelist_mat_to_edgeList_list(net.edgelist, numnode)
} |
print.criterionRkh <-
function(x,...){
if (!inherits(x, "criterionRkh")) stop("use only with \"criterionRkh\" objects")
cat("Trace criterion estimated by boostrap", "\n")
cat(" \n")
cat(paste("Reduction method performed:", x$method),"\n")
cat(paste("Number of observations:", x$n),"\n")
cat(" \n")
cat("Value of K tried:")
cat(" \n")
cat(x$K)
cat(" \n")
cat("Value of H tried:")
cat(" \n")
cat(x$H)
cat(" \n")
cat(" \n")
cat("Result of the bootsrap estimate of the trace criterion R(k,h) \n" )
tmp <- x$Rkhbootmean
row.names(tmp) <- x$H
colnames(tmp) <- x$K
cat("\n")
prmatrix(signif(tmp,3))
cat("\n")
} |
cat("this will be hidden; use for general initializations.\n")
library(superb)
library(ggplot2)
options(superb.feedback = 'none')
superb:::is.superbPlot.function("superbPlot.line")
testdata <- GRD(
RenameDV = "score",
SubjectsPerGroup = 25,
BSFactors = "Difficulty(3)",
WSFactors = "Day(day1, day2)",
Population = list(mean = 65,stddev = 12,rho = 0.5),
Effects = list("Day" = slope(-5), "Difficulty" = slope(3) )
)
head(testdata)
mp <- function(data, style, ...) {
superbPlot(data,
WSFactors = "Day(2)",
BSFactors = "Difficulty",
variables = c("score.day1", "score.day2"),
adjustments = list(purpose="difference", decorrelation="CM"),
plotStyle = style,
...
)+labs(title = paste("Layout is ''",style,"''",sep=""))
}
p1 <- mp(testdata, "bar")
p2 <- mp(testdata, "point")
p3 <- mp(testdata, "line")
p4 <- mp(testdata, "pointjitter" )
p5 <- mp(testdata, "pointjitterviolin")
p6 <- mp(testdata, "pointindividualline")
library(gridExtra)
grid.arrange(p1,p2,p3,p4,p5,p6,ncol=2)
mp(testdata, "raincloud") + coord_flip()
ornate = list(
scale_colour_manual( name = "Difference",
labels = c("Easy", "Hard", "Unthinkable"),
values = c("blue", "black", "purple")) ,
scale_fill_manual( name = "Difference",
labels = c("Easy", "Hard", "Unthinkable"),
values = c("blue", "black", "purple")) ,
scale_shape_manual( name = "Difference",
labels = c("Easy", "Hard", "Unthinkable") ,
values = c(0, 10, 13)) ,
theme_bw(base_size = 9) ,
labs(x = "Days of test", y = "Score in points" ),
scale_x_discrete(labels=c("1" = "Former day", "2" = "Latter day"))
)
library(gridExtra)
grid.arrange(
p1+ornate, p2+ornate, p3+ornate,
p4+ornate, p5+ornate, p6+ornate,
ncol=2)
superbPlot.foo <- function(
summarydata,
xfactor,
groupingfactor,
addfactors,
rawdata
) {
plot <- ggplot()
return(plot)
}
superbPlot.simple <- function( summarydata, xfactor, groupingfactor, addfactors, rawdata ) {
plot <- ggplot(
data = summarydata,
mapping = aes_string( x = xfactor, y = "center", group= groupingfactor)
) +
geom_point( ) +
geom_errorbar( mapping = aes_string(ymin = "center + lowerwidth", ymax = "center + upperwidth") )+
facet_grid( addfactors )
return(plot)
}
superbPlot(TMB1964r,
WSFactors = "T(7)",
BSFactors = "Condition",
variables = c("T1","T2","T3","T4","T5","T6","T7"),
plotStyle = "simple"
)
superbPlot.simple <- function(
summarydata, xfactor, groupingfactor, addfactors, rawdata
) {
plot <- ggplot(
data = summarydata,
mapping = aes_string( x = xfactor, y = "center", group=groupingfactor)
) +
geom_point( ) +
geom_errorbar( mapping = aes_string(ymin = "center + lowerwidth",
ymax = "center + upperwidth") )+
facet_grid( addfactors )
return(plot)
}
superb:::is.superbPlot.function("superbPlot.simple")
superbPlot(TMB1964r,
WSFactors = "T(7)",
BSFactors = "Condition",
variables = c("T1","T2","T3","T4","T5","T6","T7"),
plotStyle = "simple"
)
superbPlot.simpleWithOptions <- function(
summarydata, xfactor, groupingfactor, addfactors, rawdata,
myownParams = list()
) {
plot <- ggplot(
data = summarydata,
mapping = aes_string( x = xfactor, y = "center", group="Condition")
) +
do.call( geom_point, modifyList(
list( color ="black" ),
myownParams
)) +
do.call( geom_errorbar, modifyList(
list( mapping = aes_string(ymin = "center + lowerwidth",
ymax = "center + upperwidth") ),
myownParams
)) +
facet_grid( addfactors )
return(plot)
}
superb:::is.superbPlot.function("superbPlot.simpleWithOptions")
superbPlot.empty <- function(
summarydata, xfactor, groupingfactor, addfactors, rawdata
) {
runDebug( 'inempty', "Dumping the two dataframes",
c("summary","raw"), list(summarydata, rawdata))
plot <- ggplot()
return(plot)
}
options(superb.feedback = 'inempty')
superbPlot(TMB1964r,
WSFactors = "T(7)",
BSFactors = "Condition",
variables = c("T1","T2","T3","T4","T5","T6","T7"),
plotStyle = "empty"
)
superbPlot.simple(summary, "T", "Condition", ".~.", raw)
library(emojifont)
superbPlot.smiley <- function(
summarydata, xfactor, groupingfactor, addfactors, rawdata
) {
plot <- ggplot(
data = summarydata,
mapping = aes_string(
x = xfactor, y = "center",
fill = groupingfactor,
shape = groupingfactor,
colour = groupingfactor)
) +
geom_point(position = position_dodge(width = .95)) +
geom_errorbar( width = .6, position = position_dodge(.95),
mapping = aes_string(ymin = "center + lowerwidth", ymax = "center + upperwidth")
)+
geom_text(data = rawdata,
position = position_jitter(0.5),
family="EmojiOne", label=emoji("smile"), size=6,
mapping=aes_string(x=xfactor, y="DV", group = groupingfactor)
) +
facet_grid( addfactors )
return(plot)
}
superb:::is.superbPlot.function("superbPlot.smiley")
superbPlot(TMB1964r,
WSFactors = "T(7)",
BSFactors = "Condition",
variables = c("T1","T2","T3","T4","T5","T6","T7"),
plotStyle = "smiley"
) |
credInt<-function(theta, cdf = NULL, conf = 0.95, type="twosided"){
if(conf <=0 | conf >=1)
stop("conf must be between 0 and 1")
if(length(grep('^[Ll]',type))>0){
type<-'lower'
}else if(length(grep('^[Tt]',type))>0){
type<-'twosided'
}else if(length(grep('^[Uu]',type))>0){
type<-'upper'
}else{
stop("type must be one of lower, upper or twosided")
}
alpha<-1-conf
n<-length(theta)
if(n<10)
stop("theta must have at least ten values")
if(!is.null(cdf)){
suppressWarnings(Finv<-approxfun(cdf, theta))
if(type=='lower'){
lower.bound = Finv(alpha)
cat(paste("Lower credible bound is : ", lower.bound, "\n",sep=""))
invisible(list(lower.bound=lower.bound))
}else if(type=='upper'){
upper.bound<-Finv(1-alpha)
cat(paste("Upper credible bound is : ", upper.bound, "\n",sep=""))
invisible(list(upper.bound=upper.bound))
}else{
lower.bound = Finv(alpha/2)
upper.bound<-Finv(1-alpha/2)
cat(paste("Credible interval is : (", lower.bound,
",", upper.bound,")\n",sep=""))
invisible(list(lower.bound=lower.bound,upper.bound=upper.bound))
}
}else{
if(type=='lower'){
lower.bound <- quantile(theta, alpha)
cat(paste("Lower credible bound is ",
lower.bound, "\n", sep=""))
invisible(list(lower.bound=lower.bound))
}else if(type=='upper'){
upper.bound <- quantile(theta, 1-alpha)
cat(paste("Upper credible bound is ",
upper.bound, "\n", sep=""))
invisible(list(upper.bound=upper.bound))
}else{
bounds<-quantile(theta, c(alpha/2,1-alpha/2))
lower.bound <-bounds[1]
upper.bound <-bounds[2]
cat(paste("Credible interval is (",
lower.bound, ',', upper.bound,")\n", sep=""))
invisible(list(lower.bound=lower.bound,upper.bound=upper.bound))
}
}
} |
library(Hapi)
library(HMM)
data(gmt)
rownames(gmt) <- gmt$pos
head(gmt)
hapOutput <- hapiAutoPhase(gmt = gmt, code = 'atcg')
head(hapOutput)
hetDa <- gmt[,1:4]
ref <- hetDa$ref
alt <- hetDa$alt
gmtDa <- gmt[,-(1:4)]
gmtDa <- base2num(gmt = gmtDa, ref = ref, alt = alt)
head(gmtDa)
hmm = initHMM(States=c("S","D"), Symbols=c("s","d"),
transProbs=matrix(c(0.99999,0.00001,0.00001,0.99999),2),
emissionProbs=matrix(c(0.99,0.01,0.01,0.99),2),
startProbs = c(0.5,0.5))
hmm
gmtDa <- hapiFilterError(gmt = gmtDa, hmm = hmm)
gmtFrame <- hapiFrameSelection(gmt = gmtDa, n = 3)
imputedFrame <- hapiImupte(gmt = gmtFrame, nSPT = 2, allowNA = 0)
head(imputedFrame)
draftHap <- hapiPhase(gmt = imputedFrame)
head(draftHap)
draftHap[draftHap$cvlink>=1,]
cvCluster <- hapiCVCluster(draftHap = draftHap, cvlink = 2)
cvCluster
filter <- c()
for (i in 1:nrow(cvCluster)) {
filter <- c(filter, which (rownames(draftHap) >= cvCluster$left[i] &
rownames(draftHap) <= cvCluster$right[i]))
}
length(filter)
if (length(filter) > 0) {
imputedFrame <- imputedFrame[-filter, ]
draftHap <- hapiPhase(imputedFrame)
}
finalDraft <- hapiBlockMPR(draftHap = draftHap, gmtFrame = gmtFrame, cvlink = 1)
head(finalDraft)
consensusHap <- hapiAssemble(draftHap = finalDraft, gmt = gmtDa)
head(consensusHap)
consensusHap <- hapiAssembleEnd(gmt = gmtDa, draftHap = finalDraft,
consensusHap = consensusHap, k = 300)
hap1 <- sum(consensusHap$hap1==0)
hap2 <- sum(consensusHap$hap1==1)
hap7 <- sum(consensusHap$hap1==7)
max(hap1, hap2)/sum(hap1, hap2)
snp <- which(rownames(hetDa) %in% rownames(consensusHap))
ref <- hetDa$ref[snp]
alt <- hetDa$alt[snp]
consensusHap <- num2base(hap = consensusHap, ref = ref, alt = alt)
head(consensusHap)
hapOutput <- data.frame(gmt[snp,], consensusHap)
head(hapOutput)
data(gamete11)
head(gamete11)
data(hg19)
head(hg19)
hap <- hapOutput[,10:11]
head(hap)
gmt <- hapOutput[,5:9]
head(gmt)
cvOutput <- hapiIdentifyCV(hap = hap, gmt = gmt)
cvOutput
sessionInfo() |
weight_cause_cox <- function(data,
time,
time2 = NULL,
Event.var,
Event,
weight.type,
ties = NULL){
Event. <- ifelse(data[,Event.var]==Event,1,0)
if(is.null(time2)){
s1 <- Surv(time = data[,time], event = Event.)
}else{
s1 <- Surv(time = data[,time], time2 = data[,time2], event = Event.)
}
if(weight.type=="Unstabilized"){
if(is.null(ties)){
fit1 <- coxph(s1 ~ data[,"Trt"],
weights = data[,"ipw_ate_unstab"])
}else{
fit1 <- coxph(s1 ~ data[,"Trt"],
weights = data[,"ipw_ate_unstab"],ties = ties)
}
}else if(weight.type=="Stabilized"){
if(is.null(ties)){
fit1 <- coxph(s1 ~ data[,"Trt"],
weights = data[,"ipw_ate_stab"])
}else{
fit1 <- coxph(s1 ~ data[,"Trt"],
weights = data[,"ipw_ate_stab"],ties = ties)
}
}else{
stop("Weights type misspecified")
}
sand_var <- as.numeric(sandwich(fit1))
out <- summary(fit1)$coefficients[, c(1, 4, 5, 6), drop = FALSE]
out[,2] <- sqrt(sand_var)
out[,3] <- out[,1]/out[,2]
out[,4] <- 2 * pnorm(abs(out[,3]),lower.tail=FALSE)
CIs <- summary(fit1)$conf.int[, c(1, 3:4), drop = FALSE]
CIs[, 1] <- paste('$',round(CIs[,1],3),'$',sep = "")
CIs[, 2] <- paste('($', round(exp(as.numeric(out[,1] - qnorm(0.975) * out[,2])),3), '$, $',
round(exp(as.numeric(out[,1] + qnorm(0.975) * out[,2])),3),
'$)', sep = '')
out <- cbind(out, CIs[, 1:2, drop = FALSE])
out[, 1:3] <- paste('$', round(as.numeric(out[, 1:3]),3), '$', sep = '')
out[, 4] <- pvalFormat(out[, 4])
colnames(out) <- c('Estimate', 'Robust SE', 'z-value',
'p-value', 'Hazard Ratio', '95\\% CI')
rownames(out) <- levels(data[,"Trt"])[2]
return(out)
} |
logAdd <- function(lx, ly) {
max(lx, ly) + log1p(exp(-abs(lx - ly)))
}
mstepMisreport <- function(y, x.misreport, w, treat,
misreport.treatment, weight) {
lrep <- rep(c(1, 0), each = length(y))
if(misreport.treatment == TRUE) {
xrep <- as.matrix(rbind(cbind(x.misreport, treat), cbind(x.misreport, treat)))
} else if(misreport.treatment == FALSE) {
xrep <- as.matrix(rbind(x.misreport, x.misreport))
}
wrep <- c(w[, 1] + log(weight), w[, 2] + log(weight))
lrep <- lrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
wrep <- wrep[wrep > -Inf]
X <- xrep
if(ncol(X) == 1) {
fit.misreport <- glm(cbind(lrep, 1 - lrep) ~ 1, weights = exp(wrep), family = binomial)
} else if(ncol(X) > 1) {
fit.misreport <- glm(cbind(lrep, 1 - lrep) ~ -1 + X, weights = exp(wrep), family = binomial)
}
coefs <- coef(fit.misreport)
names(coefs) <- gsub("^X1|^X2|^X3|^X", "", names(coefs))
return(coefs)
}
mstepSensitive <- function(y, treat, x.sensitive, w, d, sensitive.response,
weight, model.misreport) {
if(model.misreport == TRUE) {
zrep <- rep(c(sensitive.response, abs(1 - sensitive.response)), each = length(y))
xrep <- as.matrix(rbind(x.sensitive, x.sensitive))
wrep <- c(apply(w[, 1:2], 1, function(x) logAdd(x[1], x[2])) + log(weight), w[, 3] + log(weight))
zrep <- zrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
wrep <- wrep[wrep > -Inf]
X <- xrep
if(ncol(X) == 1) fit <- glm(cbind(zrep, 1 - zrep) ~ 1, weights = exp(wrep), family = binomial)
if(ncol(X) > 1) fit <- glm(cbind(zrep, 1 - zrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- coef(fit)
} else {
zrep <- rep(c(1, 0), each = length(y))
xrep <- as.matrix(rbind(x.sensitive, x.sensitive))
wrep <- c(w[, 1] + log(weight), w[, 2] + log(weight))
zrep <- zrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
wrep <- wrep[wrep > -Inf]
X <- xrep
if(ncol(X) == 1) fit <- glm(cbind(zrep, 1 - zrep) ~ 1, weights = exp(wrep), family = binomial)
if(ncol(X) > 1) fit <- glm(cbind(zrep, 1 - zrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- coef(fit)
}
names(coefs) <- gsub("^X1|^X2|^X3|^X", "", names(coefs))
return(coefs)
}
mstepControl <- function(y, treat, J, x.control, w, d, sensitive.response,
weight, model.misreport, control.constraint) {
if(model.misreport == TRUE) {
if(control.constraint == "none") {
yrep <- c((y - treat * as.numeric(sensitive.response == 1)),
(y - treat * as.numeric(sensitive.response == 1)),
(y - treat * as.numeric(sensitive.response == 0)))
xrep <- as.matrix(rbind(x.control, x.control, x.control))
zrep1 <- rep(c(1, 0, 0), each = length(y))
zrep2 <- rep(c(sensitive.response,
sensitive.response,
1 - sensitive.response), each = length(y))
wrep <- c(w[, 1] + log(weight), w[, 2] + log(weight), w[, 3] + log(weight))
yrep <- yrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
zrep1 <- zrep1[wrep > -Inf]
zrep2 <- zrep2[wrep > -Inf]
wrep <- wrep[wrep > -Inf]
X <- cbind(xrep, U = zrep1, Z = zrep2)
control.fit <- glm(cbind(yrep, J - yrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- coef(control.fit)
} else if(control.constraint == "partial") {
yrep <- c((y - treat * as.numeric(sensitive.response == 1)),
(y - treat * as.numeric(sensitive.response == 0)))
xrep <- as.matrix(rbind(x.control, x.control))
zrep1 <- rep(c(sensitive.response, 1 - sensitive.response), each = length(y))
wrep <- c(apply(w[, 1:2], 1, function(x) logAdd(x[1], x[2])) + log(weight), w[, 3] + log(weight))
yrep <- yrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
zrep1 <- zrep1[wrep > -Inf]
wrep <- wrep[wrep > -Inf]
X <- cbind(xrep, Z = zrep1)
control.fit <- glm(cbind(yrep, J - yrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- coef(control.fit)
} else if(control.constraint == "full") {
yrep <- c((y - treat * as.numeric(sensitive.response == 1)),
(y - treat * as.numeric(sensitive.response == 0)))
xrep <- as.matrix(rbind(x.control, x.control))
wrep <- c(apply(w[, 1:2], 1, function(x) logAdd(x[1], x[2])) + log(weight), w[, 3] + log(weight))
yrep <- yrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
wrep <- wrep[wrep > -Inf]
X <- xrep
if(ncol(X) == 1) control.fit <- glm(cbind(yrep, J - yrep) ~ 1 , weights = exp(wrep), family = binomial)
if(ncol(X) > 1) control.fit <- glm(cbind(yrep, J - yrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- coef(control.fit)
}
} else {
yrep <- c(y - treat, y)
xrep <- as.matrix(rbind(x.control, x.control))
zrep1 <- rep(c(1, 0), each = length(y))
zrep2 <- rep(c(0, 1), each = length(y))
wrep <- c(w[, 1] + log(weight), w[, 2] + log(weight))
yrep <- yrep[wrep > -Inf]
xrep <- xrep[wrep > -Inf, , drop = FALSE]
zrep1 <- zrep1[wrep > -Inf]
zrep2 <- zrep2[wrep > -Inf]
wrep <- wrep[wrep > -Inf]
if(control.constraint == "none") {
X <- cbind(xrep, Z = zrep1)
fit.partial <- glm(cbind(yrep, J - yrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- c(coef(fit.partial))
}
if(control.constraint == "full") {
X <- xrep
if(ncol(X) == 1) fit.full <- glm(cbind(yrep, J - yrep) ~ 1 , weights = exp(wrep), family = binomial)
if(ncol(X) > 1) fit.full <- glm(cbind(yrep, J - yrep) ~ -1 + X, weights = exp(wrep), family = binomial)
coefs <- c(coef(fit.full))
}
}
names(coefs) <- gsub("^X1|^X2|^X3|^X", "", names(coefs))
names(coefs)[names(coefs) == "(Intercept):1"] <- "(Intercept)"
return(coefs)
}
mstepOutcome <- function(y, treat, x.outcome, w, d, sensitive.response, o,
trials, weight, outcome.model, model.misreport,
outcome.constrained, control.constraint) {
coefs.aux <- NULL
if(outcome.constrained == TRUE) {
if(model.misreport == TRUE) {
xrep <- as.matrix(rbind(x.outcome, x.outcome))
zrep <- rep(c(1, 0), each = length(y))
orep <- as.matrix(c(o, o))
trialsrep <- as.matrix(c(trials, trials))
wrep <- c(apply(w[, 1:2], 1, function(x) logAdd(x[1], x[2])) + log(weight), w[, 3] + log(weight))
} else {
xrep <- as.matrix(rbind(x.outcome, x.outcome))
zrep <- rep(c(1, 0), each = length(y))
orep <- as.matrix(c(o, o))
trialsrep <- as.matrix(c(trials, trials))
wrep <- c(w[, 1] + log(weight), w[, 2] + log(weight))
}
xrep <- xrep[wrep > -Inf, , drop = FALSE]
zrep <- zrep[wrep > -Inf]
orep <- orep[wrep > -Inf]
trialsrep <- trialsrep[wrep > -Inf]
wrep <- wrep[wrep > -Inf]
X <- cbind(xrep, Z = zrep)[, -1, drop = FALSE]
if(outcome.model == "logistic") {
fit.constrained.logistic <- glm(cbind(orep, 1 - orep) ~ 1 + X, weights = exp(wrep), family = binomial)
coefs <- coef(fit.constrained.logistic)
} else if(outcome.model == "binomial") {
fit.constrained.binomial <- glm(cbind(orep, trialsrep - orep) ~ 1 + X, family = binomial, weights = exp(wrep))
coefs <- coef(fit.constrained.binomial)
} else if(outcome.model == "betabinomial") {
fit.constrained.betabinomial <- VGAM::vglm(cbind(orep, trialsrep - orep) ~ 1 + X, VGAM::betabinomial, weights = exp(wrep))
coefs <- coef(fit.constrained.betabinomial)[-2]
coefs.aux <- c(rho = mean(fit.constrained.betabinomial@misc$rho))
}
} else if(outcome.constrained == FALSE) {
if(model.misreport == TRUE) {
xrep <- as.matrix(rbind(x.outcome, x.outcome, x.outcome))
zrep1 <- rep(c(1, 0, 0), each = length(y))
zrep2 <- rep(c(1, 1, 0), each = length(y))
orep <- as.matrix(c(o, o, o))
trialsrep <- as.matrix(c(trials, trials, trials))
wrep <- c(w[, 1] + log(weight), w[, 2] + log(weight), w[, 3] + log(weight))
} else {
stop("\noutcome.constrained = TRUE is only possible when a direct question is included.")
}
xrep <- xrep[wrep > -Inf, , drop = FALSE]
zrep1 <- zrep1[wrep > -Inf]
zrep2 <- zrep2[wrep > -Inf]
orep <- orep[wrep > -Inf]
trialsrep <- trials[wrep > -Inf]
wrep <- wrep[wrep > -Inf]
X <- cbind(xrep, U = zrep1, Z = zrep2)[, -1, drop = FALSE]
if(outcome.model == "logistic") {
fit.unconstrained.logitistic <- glm(cbind(orep, 1 - orep) ~ 1 + X, weights = log(wrep), family = binomial)
coefs <- coef(fit.unconstrained.logitistic)
} else if(outcome.model == "binomial") {
fit.unconstrained.binomial <- glm(cbind(orep, trialsrep - orep) ~ 1 + X, family = binomial, weights = log(wrep))
coefs <- coef(fit.unconstrained.binomial)
} else if(outcome.model == "betabinomial") {
fit.constrained.betabinomial <- VGAM::vglm(cbind(orep, trialsrep - orep) ~ 1 + X, VGAM::betabinomial, weights = log(wrep))
coefs <- coef(fit.constrained.betabinomial)[-2]
coefs.aux <- c(rho = mean(fit.constrained.betabinomial@misc$rho))
}
}
names(coefs) <- gsub("^X", "", names(coefs))
names(coefs)[names(coefs) == ""] <- "Z"
names(coefs)[names(coefs) == "(Intercept):1"] <- "(Intercept)"
return(list(coefs = coefs, coefs.aux = coefs.aux))
}
estep <- function(y, w, x.control, x.sensitive, x.outcome, x.misreport, treat, J,
par.sensitive, par.control, par.outcome,
par.outcome.aux, par.misreport,
d, sensitive.response, model.misreport,
o, trials, outcome.model, weight,
outcome.constrained, control.constraint, respondentType,
misreport.treatment) {
log.lik <- rep(as.numeric(NA), length(y))
if(model.misreport == TRUE) {
if(control.constraint == "none") {
hX.misreport.sensitive <- plogis(cbind(x.control, 1, sensitive.response) %*% par.control, log.p = TRUE)
hX.truthful.sensitive <- plogis(cbind(x.control, 0, sensitive.response) %*% par.control, log.p = TRUE)
hX.truthful.nonsensitive <- plogis(cbind(x.control, 0, 1 - sensitive.response) %*% par.control, log.p = TRUE)
}
if(control.constraint == "partial") {
hX.misreport.sensitive <- plogis(cbind(x.control, sensitive.response) %*% par.control, log.p = TRUE)
hX.truthful.sensitive <- plogis(cbind(x.control, sensitive.response) %*% par.control, log.p = TRUE)
hX.truthful.nonsensitive <- plogis(cbind(x.control, 1 - sensitive.response) %*% par.control, log.p = TRUE)
}
if(control.constraint == "full") {
hX.misreport.sensitive <- plogis(x.control %*% par.control, log.p = TRUE)
hX.truthful.sensitive <- plogis(x.control %*% par.control, log.p = TRUE)
hX.truthful.nonsensitive <- plogis(x.control %*% par.control, log.p = TRUE)
}
hX.misreport.sensitive <- dbinom((y - treat * as.numeric(sensitive.response == 1)), size = J, prob = exp(hX.misreport.sensitive), log = TRUE)
hX.truthful.sensitive <- dbinom((y - treat * as.numeric(sensitive.response == 1)), size = J, prob = exp(hX.truthful.sensitive), log = TRUE)
hX.truthful.nonsensitive <- dbinom((y - treat * as.numeric(sensitive.response == 0)), size = J, prob = exp(hX.truthful.nonsensitive), log = TRUE)
if(outcome.model != "none") {
if(outcome.constrained == TRUE) {
if(outcome.model %in% c("logistic", "binomial", "betabinomial")) {
fX.misreport.sensitive <- plogis(cbind(x.outcome, 1) %*% par.outcome, log.p = TRUE)
fX.truthful.sensitive <- plogis(cbind(x.outcome, 1) %*% par.outcome, log.p = TRUE)
fX.truthful.nonsensitive <- plogis(cbind(x.outcome, 0) %*% par.outcome, log.p = TRUE)
}
} else {
if(outcome.model %in% c("logistic", "binomial", "betabinomial")) {
fX.misreport.sensitive <- plogis(cbind(x.outcome, 1, 1) %*% par.outcome, log.p = TRUE)
fX.truthful.sensitive <- plogis(cbind(x.outcome, 0, 1) %*% par.outcome, log.p = TRUE)
fX.truthful.nonsensitive <- plogis(cbind(x.outcome, 0, 0) %*% par.outcome, log.p = TRUE)
}
}
} else {
fX.misreport.sensitive <- rep(0, length(y))
fX.truthful.sensitive <- rep(0, length(y))
fX.truthful.nonsensitive <- rep(0, length(y))
}
if(outcome.model == "logistic") {
fX.misreport.sensitive <- dbinom(o, size = 1, prob = exp(fX.misreport.sensitive), log = TRUE)
fX.truthful.sensitive <- dbinom(o, size = 1, prob = exp(fX.truthful.sensitive), log = TRUE)
fX.truthful.nonsensitive <- dbinom(o, size = 1, prob = exp(fX.truthful.nonsensitive), log = TRUE)
} else if(outcome.model == "binomial") {
fX.misreport.sensitive <- dbinom(o, size = trials, prob = exp(fX.misreport.sensitive), log = TRUE)
fX.truthful.sensitive <- dbinom(o, size = trials, prob = exp(fX.truthful.sensitive), log = TRUE)
fX.truthful.nonsensitive <- dbinom(o, size = trials, prob = exp(fX.truthful.nonsensitive), log = TRUE)
} else if(outcome.model == "betabinomial") {
fX.misreport.sensitive <- VGAM::dbetabinom(o, size = trials, prob = exp(fX.misreport.sensitive), rho = par.outcome.aux["rho"], log = TRUE)
fX.truthful.sensitive <- VGAM::dbetabinom(o, size = trials, prob = exp(fX.truthful.sensitive), rho = par.outcome.aux["rho"], log = TRUE)
fX.truthful.nonsensitive <- VGAM::dbetabinom(o, size = trials, prob = exp(fX.truthful.nonsensitive), rho = par.outcome.aux["rho"], log = TRUE)
}
if(sensitive.response == 1) {
gX.misreport.sensitive <- plogis(x.sensitive %*% par.sensitive, log.p = TRUE)
gX.truthful.sensitive <- plogis(x.sensitive %*% par.sensitive, log.p = TRUE)
gX.truthful.nonsensitive <- log1p(-exp(plogis(x.sensitive %*% par.sensitive, log.p = TRUE)))
} else {
gX.misreport.sensitive <- log1p(-exp(plogis(x.sensitive %*% par.sensitive, log.p = TRUE)))
gX.truthful.sensitive <- log1p(-exp(plogis(x.sensitive %*% par.sensitive, log.p = TRUE)))
gX.truthful.nonsensitive <- plogis(x.sensitive %*% par.sensitive, log.p = TRUE)
}
if(misreport.treatment == TRUE) {
lX.misreport.sensitive <- plogis(cbind(x.misreport, treat) %*% par.misreport, log.p = TRUE)
lX.truthful.sensitive <- log1p(-exp(plogis(cbind(x.misreport, treat) %*% par.misreport, log.p = TRUE)))
lX.truthful.nonsensitive <- log(rep(1, length(y)))
} else {
lX.misreport.sensitive <- plogis(x.misreport %*% par.misreport, log.p = TRUE)
lX.truthful.sensitive <- log1p(-exp(plogis(x.misreport %*% par.misreport, log.p = TRUE)))
lX.truthful.nonsensitive <- log(rep(1, length(y)))
}
w[, 1] <- lX.misreport.sensitive + gX.misreport.sensitive + hX.misreport.sensitive + fX.misreport.sensitive
w[, 2] <- lX.truthful.sensitive + gX.truthful.sensitive + hX.truthful.sensitive + fX.truthful.sensitive
w[, 3] <- lX.truthful.nonsensitive + gX.truthful.nonsensitive + hX.truthful.nonsensitive + fX.truthful.nonsensitive
w[respondentType == "Misreport sensitive", 1] <- log(1)
w[respondentType == "Misreport sensitive", 2] <- log(0)
w[respondentType == "Misreport sensitive", 3] <- log(0)
w[respondentType == "Truthful sensitive", 1] <- log(0)
w[respondentType == "Truthful sensitive", 2] <- log(1)
w[respondentType == "Truthful sensitive", 3] <- log(0)
w[respondentType == "Non-sensitive", 1] <- log(0)
w[respondentType == "Non-sensitive", 2] <- log(0)
w[respondentType == "Non-sensitive", 3] <- log(1)
w[respondentType == "Non-sensitive or misreport sensitive", 2] <- log(0)
denominator <- apply(w, 1, function(x) logAdd(logAdd(x[1], x[2]), x[3]))
w[, 1] <- w[, 1] - denominator
w[, 2] <- w[, 2] - denominator
w[, 3] <- w[, 3] - denominator
w[respondentType == "Misreport sensitive", 1] <- log(1)
w[respondentType == "Misreport sensitive", 2] <- log(0)
w[respondentType == "Misreport sensitive", 3] <- log(0)
w[respondentType == "Truthful sensitive", 1] <- log(0)
w[respondentType == "Truthful sensitive", 2] <- log(1)
w[respondentType == "Truthful sensitive", 3] <- log(0)
w[respondentType == "Non-sensitive", 1] <- log(0)
w[respondentType == "Non-sensitive", 2] <- log(0)
w[respondentType == "Non-sensitive", 3] <- log(1)
w[respondentType == "Non-sensitive or misreport sensitive", 2] <- log(0)
log.lik[respondentType == "Non-sensitive or misreport sensitive"] <- apply(data.frame(lX.truthful.nonsensitive[respondentType == "Non-sensitive or misreport sensitive"] +
gX.truthful.nonsensitive[respondentType == "Non-sensitive or misreport sensitive"] +
hX.truthful.nonsensitive[respondentType == "Non-sensitive or misreport sensitive"] +
fX.truthful.nonsensitive[respondentType == "Non-sensitive or misreport sensitive"],
lX.misreport.sensitive[respondentType == "Non-sensitive or misreport sensitive"] +
gX.misreport.sensitive[respondentType == "Non-sensitive or misreport sensitive"] +
hX.misreport.sensitive[respondentType == "Non-sensitive or misreport sensitive"] +
fX.misreport.sensitive[respondentType == "Non-sensitive or misreport sensitive"]),
1, function(x) logAdd(x[1], x[2]))
log.lik[respondentType == "Truthful sensitive"] <- lX.truthful.sensitive[respondentType == "Truthful sensitive"] +
gX.truthful.sensitive[respondentType == "Truthful sensitive"] +
hX.truthful.sensitive[respondentType == "Truthful sensitive"] +
fX.truthful.sensitive[respondentType == "Truthful sensitive"]
log.lik[respondentType == "Non-sensitive"] <- lX.truthful.nonsensitive[respondentType == "Non-sensitive"] +
gX.truthful.nonsensitive[respondentType == "Non-sensitive"] +
hX.truthful.nonsensitive[respondentType == "Non-sensitive"] +
fX.truthful.nonsensitive[respondentType == "Non-sensitive"]
log.lik[respondentType == "Misreport sensitive"] <- lX.misreport.sensitive[respondentType == "Misreport sensitive"] +
gX.misreport.sensitive[respondentType == "Misreport sensitive"] +
hX.misreport.sensitive[respondentType == "Misreport sensitive"] +
fX.misreport.sensitive[respondentType == "Misreport sensitive"]
}
if(model.misreport == FALSE) {
if(control.constraint == "none") {
hX.1 <- plogis(cbind(x.control, 1) %*% par.control)
hX.0 <- plogis(cbind(x.control, 0) %*% par.control)
}
if(control.constraint == "full") {
hX.1 <- plogis(x.control %*% par.control)
hX.0 <- plogis(x.control %*% par.control)
}
hX.1 <- dbinom((y - treat), size = J, prob = hX.1, log = TRUE)
hX.0 <- dbinom(y, size = J, prob = hX.0, log = TRUE)
if(outcome.model %in% c("logistic", "binomial", "betabinomial")) {
fX.1 <- plogis(cbind(x.outcome, 1) %*% par.outcome)
fX.0 <- plogis(cbind(x.outcome, 0) %*% par.outcome)
} else {
fX.1 <- rep(0, length(y))
fX.0 <- rep(0, length(y))
}
if(outcome.model == "logistic") {
fX.1 <- dbinom(o, size = 1, prob = fX.1, log = TRUE)
fX.0 <- dbinom(o, size = 1, prob = fX.0, log = TRUE)
} else if(outcome.model == "binomial") {
fX.1 <- dbinom(o, size = trials, prob = fX.1, log = TRUE)
fX.0 <- dbinom(o, size = trials, prob = fX.0, log = TRUE)
} else if(outcome.model == "betabinomial") {
fX.1 <- VGAM::dbetabinom(o, size = trials, prob = fX.1, rho = par.outcome.aux["rho"], log = TRUE)
fX.0 <- VGAM::dbetabinom(o, size = trials, prob = fX.0, rho = par.outcome.aux["rho"], log = TRUE)
}
gX.1 <- plogis(x.sensitive %*% par.sensitive, log.p = TRUE)
gX.0 <- log(1 - exp(gX.1))
w[, 1] <- gX.1 + hX.1 + fX.1
w[, 2] <- gX.0 + hX.0 + fX.0
w[respondentType == "1", 1] <- log(1)
w[respondentType == "1", 2] <- log(0)
w[respondentType == "0", 1] <- log(0)
w[respondentType == "0", 2] <- log(1)
denominator <- apply(w, 1, function(x) logAdd(x[1], x[2]))
w[, 1] <- w[, 1] - denominator
w[, 2] <- w[, 2] - denominator
w[respondentType == "1", 1] <- log(1)
w[respondentType == "1", 2] <- log(0)
w[respondentType == "0", 1] <- log(0)
w[respondentType == "0", 2] <- log(1)
log.lik[respondentType == "0"] <- gX.0[respondentType == "0"] +
hX.0[respondentType == "0"] +
fX.0[respondentType == "0"]
log.lik[respondentType == "1"] <- gX.1[respondentType == "1"] +
hX.1[respondentType == "1"] +
fX.1[respondentType == "1"]
log.lik[respondentType == "0 or 1"] <- apply(data.frame(gX.1[respondentType == "0 or 1"] +
hX.1[respondentType == "0 or 1"] +
fX.1[respondentType == "0 or 1"],
gX.0[respondentType == "0 or 1"] +
hX.0[respondentType == "0 or 1"] +
fX.0[respondentType == "0 or 1"]),
1, function(x) logAdd(x[1], x[2]))
log.lik[respondentType == "0 or 1"] <- log(exp(gX.1[respondentType == "0 or 1"] +
hX.1[respondentType == "0 or 1"] +
fX.1[respondentType == "0 or 1"]) +
exp(gX.0[respondentType == "0 or 1"] +
hX.0[respondentType == "0 or 1"] +
fX.0[respondentType == "0 or 1"]))
}
return(list(w = w, ll = sum(weight * log.lik)))
}
listExperiment <- function(formula, data, treatment, J,
direct = NULL, sensitive.response = NULL,
outcome = NULL, outcome.trials = NULL,
outcome.model = "logistic",
outcome.constrained = TRUE,
control.constraint = "none",
misreport.treatment = TRUE,
weights = NULL, se = TRUE, tolerance = 1E-8,
max.iter = 10000, n.runs = 3, verbose = TRUE,
get.data = FALSE,
par.control = NULL, par.sensitive = NULL,
par.misreport = NULL, par.outcome = NULL,
par.outcome.aux = NULL,
formula.control = NULL, formula.sensitive = NULL,
formula.misreport = NULL, formula.outcome = NULL,
get.boot = 0, ...) {
function.call <- match.call(expand.dots = FALSE)
if(missing(data)) data <- environment(formula)
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data", "na.action"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf$drop.unused.levels <- TRUE
mf$na.action <- "na.pass"
mf[[1]] <- quote(model.frame)
mt <- attr(eval(mf, parent.frame()), "terms")
xlevels.formula <- .getXlevels(attr(eval(mf, parent.frame()), "terms"), eval(mf, parent.frame()))
if(!is.null(formula.control)) {
mf.control <- mf
mf.control$formula <- formula.control
xlevels.formula.control <- .getXlevels(attr(eval(mf.control, parent.frame()), "terms"), eval(mf.control, parent.frame()))
mf.control <- eval(mf.control, parent.frame())
x.control <- model.matrix(attr(mf.control, "terms"), data = mf.control)
} else {
formula.control <- as.formula(mf$formula)
xlevels.formula.control <- xlevels.formula
mf.control <- eval(mf, parent.frame())
x.control <- model.matrix(attr(mf.control, "terms"), data = mf.control)
}
if(!is.null(formula.sensitive)) {
mf.sensitive <- mf
mf.sensitive$formula <- formula.sensitive
xlevels.formula.sensitive <- .getXlevels(attr(eval(mf.sensitive, parent.frame()), "terms"), eval(mf.sensitive, parent.frame()))
mf.sensitive <- eval(mf.sensitive, parent.frame())
x.sensitive <- model.matrix(attr(mf.sensitive, "terms"), data = mf.sensitive)
} else {
formula.sensitive <- as.formula(mf$formula)
xlevels.formula.sensitive <- xlevels.formula
mf.sensitive <- eval(mf, parent.frame())
x.sensitive <- model.matrix(attr(mf.sensitive, "terms"), data = mf.sensitive)
}
if(!is.null(formula.misreport)) {
mf.misreport <- mf
mf.misreport$formula <- formula.misreport
xlevels.formula.misreport <- .getXlevels(attr(eval(mf.misreport, parent.frame()), "terms"), eval(mf.misreport, parent.frame()))
mf.misreport <- eval(mf.misreport, parent.frame())
x.misreport <- model.matrix(attr(mf.misreport, "terms"), data = mf.misreport)
} else {
formula.misreport <- as.formula(mf$formula)
xlevels.formula.misreport <- xlevels.formula
mf.misreport <- eval(mf, parent.frame())
x.misreport <- model.matrix(attr(mf.misreport, "terms"), data = mf.misreport)
}
if(!is.null(formula.outcome)) {
mf.outcome <- mf
mf.outcome$formula <- formula.outcome
xlevels.formula.outcome <- .getXlevels(attr(eval(mf.outcome, parent.frame()), "terms"), eval(mf.outcome, parent.frame()))
mf.outcome <- eval(mf.outcome, parent.frame())
x.outcome <- model.matrix(attr(mf.outcome, "terms"), data = mf.outcome)
} else {
formula.outcome <- as.formula(mf$formula)
xlevels.formula.outcome <- xlevels.formula
mf.outcome <- eval(mf, parent.frame())
x.outcome <- model.matrix(attr(mf.outcome, "terms"), data = mf.outcome)
}
mf <- eval(mf, parent.frame())
y <- model.response(mf, type = "any")
treat <- data[, paste(treatment)]
xlevels <- c(xlevels.formula,
xlevels.formula.control,
xlevels.formula.sensitive,
xlevels.formula.misreport,
xlevels.formula.outcome)
xlevels <- xlevels[-which(duplicated(xlevels))]
x.control.na <- apply(x.control, 1, function(X) all(!is.na(X)))
x.sensitive.na <- apply(x.sensitive, 1, function(X) all(!is.na(X)))
x.misreport.na <- apply(x.misreport, 1, function(X) all(!is.na(X)))
x.outcome.na <- apply(x.outcome, 1, function(X) all(!is.na(X)))
y.na <- !is.na(y)
treat.na <- !is.na(treat)
if(!is.null(direct)) {
d <- data[, paste(direct)]
d.na <- !is.na(d)
model.misreport <- TRUE
} else {
model.misreport <- FALSE
d <- rep(NA, length(y))
d.na <- rep(TRUE, length(y))
}
if(!is.null(outcome) & outcome.model %in% c("logistic")) {
o <- data[, paste(outcome)]
trials <- rep(NA, length(y))
o.na <- !is.na(o)
} else if(!is.null(outcome) & outcome.model %in% c("binomial", "betabinomial")) {
o <- data[, paste(outcome)]
trials <- data[, paste(outcome.trials)]
o.na <- !is.na(o) & !is.na(trials)
} else {
o <- rep(NA, length(y))
trials <- rep(NA, length(y))
o.na <- rep(TRUE, length(y))
outcome.model <- "none"
}
if(!is.null(weights)) {
weight <- data[, paste(weights)]
weight.na <- !is.na(weight)
} else {
weight <- rep(1, length(y))
weight.na <- !is.na(weight)
}
y <- y[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na]
x.control <- as.matrix(x.control[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na, , drop = FALSE])
x.sensitive <- as.matrix(x.sensitive[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na, , drop = FALSE])
x.outcome <- as.matrix(x.outcome[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na, , drop = FALSE])
x.misreport <- as.matrix(x.misreport[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na, , drop = FALSE])
treat <- treat[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na]
d <- d[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na]
o <- o[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na]
trials <- trials[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na]
weight <- weight[y.na & x.control.na & x.sensitive.na & x.outcome.na & x.misreport.na & treat.na & d.na & weight.na]
n <- nrow(x.control)
if(get.boot > 0) {
boot.sample <- sample(1:length(weight), prob = weight, replace = TRUE)
y <- as.matrix(y)[boot.sample, , drop = FALSE]
x.control <- as.matrix(x.control)[boot.sample, , drop = FALSE]
x.sensitive <- as.matrix(x.sensitive)[boot.sample, , drop = FALSE]
x.outcome <- as.matrix(x.outcome)[boot.sample, , drop = FALSE]
x.misreport <- as.matrix(x.misreport)[boot.sample, , drop = FALSE]
treat <- as.matrix(treat)[boot.sample]
d <- as.matrix(d)[boot.sample, , drop = FALSE]
o <- as.matrix(o)[boot.sample, , drop = FALSE]
trials <- as.matrix(trials)[boot.sample, , drop = FALSE]
weight <- rep(1, length(y))
se <- FALSE
}
respondentType <- rep(as.character(NA), length(y))
if(model.misreport == TRUE) {
respondentType[treat == 0 & d != sensitive.response] <- "Non-sensitive or misreport sensitive"
respondentType[treat == 0 & d == sensitive.response] <- "Truthful sensitive"
if(sensitive.response == 1) respondentType[treat == 1 & y == 0 & d != sensitive.response] <- "Non-sensitive"
if(sensitive.response == 0) respondentType[treat == 1 & y == (J + 1) & d != sensitive.response] <- "Non-sensitive"
respondentType[treat == 1 & y > 0 & y < (J + 1) & d != sensitive.response] <- "Non-sensitive or misreport sensitive"
if(sensitive.response == 1) respondentType[treat == 1 & y == (J + 1) & d != sensitive.response] <- "Misreport sensitive"
if(sensitive.response == 0) respondentType[treat == 1 & y == 0 & d != sensitive.response] <- "Misreport sensitive"
if(sensitive.response == 1) respondentType[treat == 1 & y == (J + 1) & d == sensitive.response] <- "Truthful sensitive"
if(sensitive.response == 0) respondentType[treat == 1 & y == 0 & d == sensitive.response] <- "Truthful sensitive"
if(sensitive.response == 1) respondentType[treat == 1 & y == 0 & d == sensitive.response] <- "Violates assumption"
if(sensitive.response == 0) respondentType[treat == 1 & y == (J + 1) & d == sensitive.response] <- "Violates assumption"
respondentType[treat == 1 & y > 0 & y < (J + 1) & d == sensitive.response] <- "Truthful sensitive"
} else {
respondentType[treat == 1 & y > 0 & y < (J + 1)] <- "0 or 1"
respondentType[treat == 0] <- "0 or 1"
respondentType[treat == 1 & y == 0] <- "0"
respondentType[(treat == 1 & y == (J + 1))] <- "1"
}
if("Violates assumption" %in% respondentType) {
stop("\nSome observations violate the monotonicity assumption.")
}
if(model.misreport == TRUE) {
w <- as.matrix(data.frame(as.numeric(respondentType %in% c("Non-sensitive or misreport sensitive", "Misreport sensitive")),
as.numeric(respondentType == "Truthful sensitive"),
as.numeric(respondentType %in% c("Non-sensitive or misreport sensitive", "Non-sensitive"))))
w <- w / apply(w, 1, sum)
colnames(w) <- c("Misreport sensitive", "Truthful sensitive", "Non-sensitive")
} else {
w <- as.matrix(data.frame(as.numeric(respondentType %in% c("1", "0 or 1")),
as.numeric(respondentType %in% c("0", "0 or 1"))))
w <- w / apply(w, 1, sum)
colnames(w) <- c("1", "0")
}
w <- log(w)
if(get.data == TRUE) {
estep.out <- estep(y = y, w = w, x.control = x.control, x.sensitive = x.sensitive, x.outcome = x.outcome, x.misreport = x.misreport, treat = treat, J = J,
par.sensitive = par.sensitive, par.control = par.control, par.outcome = par.outcome, par.outcome.aux = par.outcome.aux, par.misreport = par.misreport,
d = d, sensitive.response = sensitive.response, model.misreport = model.misreport,
o = o, trials = trials, outcome.model = outcome.model,
weight = weight, respondentType = respondentType,
outcome.constrained = outcome.constrained,
control.constraint = control.constraint,
misreport.treatment = misreport.treatment)
return(list(w = estep.out$w,
ll = estep.out$ll,
x.control = x.control,
x.sensitive = x.sensitive,
x.misreport = x.misreport,
x.outcome = x.outcome))
}
if(model.misreport == TRUE) {
if(misreport.treatment == TRUE) par.misreport <- rep(0, ncol(x.misreport) + 1)
if(misreport.treatment == FALSE) par.misreport <- rep(0, ncol(x.misreport))
} else {
par.misreport <- NULL
}
if(is.null(par.sensitive)) par.sensitive <- rep(0, ncol(x.sensitive))
if(is.null(par.control)) {
if(control.constraint == "none" & model.misreport == FALSE) {
par.control <- rep(0, ncol(x.control) + 1)
} else if(control.constraint == "none" & model.misreport == TRUE) {
par.control <- rep(0, ncol(x.control) + 2)
} else if(control.constraint == "partial" & model.misreport == FALSE) {
stop("If not modeling misreporting, set argument control.constraint to 'none' or 'full'")
} else if(control.constraint == "partial" & model.misreport == TRUE) {
par.control <- rep(0, ncol(x.control) + 1)
} else if(control.constraint == "full") {
par.control <- rep(0, ncol(x.control))
}
}
if(is.null(par.outcome)) {
if(outcome.model != "none") {
if(outcome.constrained == TRUE) par.outcome <- rep(0, ncol(x.outcome) + 1)
if(outcome.constrained == FALSE) par.outcome <- rep(0, ncol(x.outcome) + 2)
} else {
par.outcome <- NULL
}
}
if(is.null(par.outcome.aux)) {
if(outcome.model %in% c("none", "logistic")) {
par.outcome.aux <- NULL
} else if(outcome.model == "betabinomial") {
par.outcome.aux <- list(rho = 0)
}
}
runs <- list()
for(j in 1:n.runs) {
if(j > 1 & verbose == TRUE) cat("\n")
logLikelihood <- rep(as.numeric(NA), max.iter)
while(TRUE) {
par.control <- runif(length(par.control), -2, 2)
par.sensitive <- runif(length(par.sensitive), -2, 2)
if(model.misreport == TRUE) par.misreport <- runif(length(par.misreport), -2, 2)
if(outcome.model != "none") par.outcome <- runif(length(par.outcome), -2, 2)
if(outcome.model != "none" & length(par.outcome.aux) > 0) par.outcome.aux <- runif(length(par.outcome.aux), 0, 1)
templl <- estep(y = y, w = w, x.control = x.control, x.sensitive = x.sensitive, x.outcome = x.outcome, x.misreport = x.misreport, treat = treat, J = J,
par.sensitive = par.sensitive, par.control = par.control, par.outcome = par.outcome, par.outcome.aux = par.outcome.aux, par.misreport = par.misreport,
d = d, sensitive.response = sensitive.response, model.misreport = model.misreport,
o = o, trials = trials, outcome.model = outcome.model,
weight = weight, respondentType = respondentType,
outcome.constrained = outcome.constrained,
control.constraint = control.constraint,
misreport.treatment = misreport.treatment)$ll
templl
if(!is.nan(templl) & templl > -Inf) break()
}
for(i in 1:max.iter) {
estep.out <- estep(y = y, w = w, x.control = x.control, x.sensitive = x.sensitive, x.outcome = x.outcome, x.misreport = x.misreport, treat = treat, J = J,
par.sensitive = par.sensitive, par.control = par.control, par.outcome = par.outcome, par.outcome.aux = par.outcome.aux, par.misreport = par.misreport,
d = d, sensitive.response = sensitive.response, model.misreport = model.misreport,
o = o, trials = trials, outcome.model = outcome.model,
weight = weight, respondentType = respondentType,
outcome.constrained = outcome.constrained,
control.constraint = control.constraint,
misreport.treatment = misreport.treatment)
w <- estep.out$w
logLikelihood[i] <- estep.out$ll
if(i > 1 & verbose == TRUE & get.boot == 0) {
cat("\r\rRun:", paste0(j, "/", n.runs), "Iter:", i,
"llik:", sprintf("%.2f", logLikelihood[i]),
"llik change:", sprintf("%.8f", (logLikelihood[i] - logLikelihood[i-1])),
"(tol =", paste0(as.character(tolerance), ") "))
}
if(i > 1 & verbose == TRUE & get.boot > 0) {
cat("\r\rBoot:", get.boot, "Run:", paste0(j, "/", n.runs), "Iter:", i,
"llik:", sprintf("%.2f", logLikelihood[i]),
"llik change:", sprintf("%.8f", (logLikelihood[i] - logLikelihood[i-1])),
"(tol =", paste0(as.character(tolerance), ") "))
}
if(i > 1 && (logLikelihood[i] - logLikelihood[i - 1]) < 0) {
stop("Log-likelihood increasing.")
}
if(i > 1 && (logLikelihood[i] - logLikelihood[i - 1]) < tolerance) {
break()
}
par.sensitive <- mstepSensitive(y = y, treat = treat, x.sensitive = x.sensitive, w = w,
d = d, sensitive.response = sensitive.response,
weight = weight, model.misreport = model.misreport)
par.control <- mstepControl(y = y, J = J, treat = treat, x.control = x.control, w = w,
d = d, sensitive.response = sensitive.response,
weight = weight, model.misreport = model.misreport,
control.constraint = control.constraint)
if(outcome.model != "none") {
outcome <- mstepOutcome(y = y, treat = treat, x.outcome = x.outcome, w = w,
d = d, sensitive.response = sensitive.response,
o = o, trials = trials, weight = weight,
model.misreport = model.misreport,
outcome.model = outcome.model,
outcome.constrained = outcome.constrained,
control.constraint = control.constraint)
par.outcome <- outcome$coefs
par.outcome.aux <- outcome$coefs.aux
}
if(model.misreport == TRUE) {
par.misreport <- mstepMisreport(y = y, x.misreport = x.misreport,
w = w, treat = treat,
misreport.treatment = misreport.treatment,
weight = weight)
}
}
runs[[j]] <- list(logLikelihood = logLikelihood[i],
par.control = par.control,
par.sensitive = par.sensitive,
par.misreport = par.misreport,
par.outcome = par.outcome,
par.outcome.aux = par.outcome.aux)
}
if(verbose == TRUE) cat("\n")
max.ll <- which(sapply(runs, function(X) X$logLikelihood) == max(sapply(runs, function(X) X$logLikelihood)))
llik <- runs[[max.ll]]$logLikelihood
par.control <- runs[[max.ll]]$par.control
par.sensitive <- runs[[max.ll]]$par.sensitive
par.misreport <- runs[[max.ll]]$par.misreport
par.outcome <- runs[[max.ll]]$par.outcome
par.outcome.aux <- runs[[max.ll]]$par.outcome.aux
par <- c(par.control, par.sensitive, par.misreport, par.outcome, par.outcome.aux)
num <- c(length(par.control), length(par.sensitive), length(par.misreport), length(par.outcome), length(par.outcome.aux))
llik.wrapper <- function(par, num, y, w,
x.control, x.sensitive, x.outcome, x.misreport, treat, J,
d, sensitive.response, model.misreport,
o, trials, outcome.model,
weight, respondentType,
outcome.constrained,
control.constraint,
misreport.treatment) {
par.control <- par[1:num[1]]
par.sensitive <- par[(num[1]+1):sum(num[1:2])]
if(model.misreport == TRUE) {
par.misreport <- par[(sum(num[1:2])+1):sum(num[1:3])]
} else{
par.misreport <- NULL
}
if(outcome.model != "none") {
par.outcome <- par[(sum(num[1:3])+1):sum(num[1:4])]
if(outcome.model %in% c("betabinomial", "linear")) {
par.outcome.aux <- par[(sum(num[1:4])+1):sum(num[1:5])]
} else {
par.outcome.aux <- NULL
}
} else {
par.outcome <- NULL
}
llik <- estep(y = y, w = w, x.control = x.control, x.sensitive = x.sensitive, x.outcome = x.outcome, x.misreport = x.misreport, treat = treat, J = J,
par.sensitive = par.sensitive, par.control = par.control, par.outcome = par.outcome, par.outcome.aux = par.outcome.aux, par.misreport = par.misreport,
d = d, sensitive.response = sensitive.response, model.misreport = model.misreport,
o = o, trials = trials, outcome.model = outcome.model,
weight = weight, respondentType = respondentType,
outcome.constrained = outcome.constrained,
control.constraint = control.constraint,
misreport.treatment)$ll
return(llik)
}
if(se == TRUE & all(weight == 1)) {
num <- c(length(par.control),
length(par.sensitive),
length(par.misreport),
length(par.outcome),
length(par.outcome.aux))
hess <- numDeriv::hessian(llik.wrapper, c(par.control, par.sensitive, par.misreport, par.outcome, par.outcome.aux),
num = num, J = J, y = y, w = w, treat = treat,
x.control = x.control, x.sensitive = x.sensitive, x.outcome = x.outcome, x.misreport = x.misreport,
d = d, sensitive.response = sensitive.response, model.misreport = model.misreport,
o = o, outcome.model = outcome.model,
outcome.constrained = outcome.constrained,
weight = weight,
respondentType = respondentType,
control.constraint = control.constraint,
misreport.treatment = misreport.treatment,
method.args = list(zero.tol = 1e-10))
vcov.mle <- solve(-hess)
se.mle <- sqrt(diag(vcov.mle))
se.control <- se.mle[1:num[1]]
names(se.control) <- names(par.control)
se.sensitive <- se.mle[(num[1]+1):sum(num[1:2])]
names(se.sensitive) <- names(par.sensitive)
if(model.misreport == TRUE) {
se.misreport <- se.mle[(sum(num[1:2])+1):sum(num[1:3])]
names(se.misreport) <- names(par.misreport)
} else {
se.misreport <- NULL
}
if(outcome.model != "none") {
se.outcome <- se.mle[(sum(num[1:3])+1):sum(num[1:4])]
names(se.outcome) <- names(par.outcome)
if(outcome.model %in% c("linear", "betabinomial")) {
se.outcome.aux <- se.mle[(sum(num[1:4])+1):sum(num[1:5])]
names(se.outcome.aux) <- names(par.outcome.aux)
} else {
se.outcome.aux <- NULL
}
} else {
se.outcome <- NULL
se.outcome.aux <- NULL
}
} else {
se.control <- se.sensitive <- se.misreport <- se.outcome <- se.outcome.aux <- vcov.mle <- NULL
if(se == TRUE) {
warning("Standard errors are not implemented for models with survey weights.")
se <- FALSE
}
}
return.object <- list("par.control" = par.control,
"par.sensitive" = par.sensitive,
"par.misreport" = par.misreport,
"par.outcome" = par.outcome,
"par.outcome.aux" = par.outcome.aux,
"df" = n - length(c(par.control, par.sensitive, par.misreport, par.outcome, par.outcome.aux)),
"se.sensitive" = se.sensitive,
"se.control" = se.control,
"se.misreport" = se.misreport,
"se.outcome" = se.outcome,
"se.outcome.aux" = se.outcome.aux,
"vcov.mle" = vcov.mle,
"w" = exp(w),
"data" = data,
"direct" = direct,
"treatment" = treatment,
"model.misreport" = model.misreport,
"outcome.model" = outcome.model,
"outcome.constrained" = outcome.constrained,
"control.constraint" = control.constraint,
"misreport.treatment" = misreport.treatment,
"weights" = weights,
"formula" = formula,
"formula.control" = formula.control,
"formula.sensitive" = formula.sensitive,
"formula.misreport" = formula.misreport,
"formula.outcome" = formula.outcome,
"sensitive.response" = sensitive.response,
"xlevels" = xlevels,
"llik" = llik,
"n" = n,
"J" = J,
"se" = se,
"runs" = runs,
"call" = function.call,
"boot" = FALSE)
class(return.object) <- "listExperiment"
return(return.object)
}
bootListExperiment <- function(formula, data, treatment, J,
direct = NULL, sensitive.response = NULL,
outcome = NULL, outcome.trials = NULL, outcome.model = "logistic",
outcome.constrained = TRUE, control.constraint = "partial",
misreport.treatment = TRUE,
weights = NULL, se = TRUE, tolerance = 1E-8, max.iter = 5000,
n.runs = 1, verbose = TRUE, get.data = FALSE,
par.control = NULL, par.sensitive = NULL, par.misreport = NULL,
par.outcome = NULL, par.outcome.aux = NULL,
formula.control = NULL, formula.sensitive = NULL,
formula.misreport = NULL, formula.outcome = NULL,
boot.iter = 1000, parallel = FALSE, n.cores = 2, cluster = NULL) {
function.call <- match.call()
args.call <- as.list(function.call)[-1]
args.call$se <- FALSE
args.call$get.boot <- 1
args.call <- lapply(args.call, eval)
data <- args.call$data
args.call$data <- as.name("data")
if(parallel == FALSE) {
boot.out <- list()
for(i in 1:boot.iter) {
args.call$get.boot <- i
boot.out[[i]] <- do.call(listExperiment, args.call)
}
}
if(parallel == TRUE) {
args.call$verbose <- FALSE
cat("Running bootstrap in parallel on ", n.cores, " cores/threads (", parallel::detectCores(), " available)...\n", sep = ""); Sys.sleep(0.2)
if(!is.null(cluster)) cl <- cluster
if(is.null(cluster)) cl <- parallel::makeCluster(n.cores)
parallel::clusterExport(cl,
list("args.call", "data", "listExperiment", "logAdd", "estep",
"mstepControl", "mstepSensitive", "mstepMisreport", "mstepOutcome"),
envir = environment())
boot.out <- parallel::parLapply(cl, 1:boot.iter, function(x) do.call(listExperiment, args.call))
parallel::stopCluster(cl)
}
getPars <- function(varName) {
X <- do.call(rbind, sapply(boot.out, function(x) x[varName]))
cov.var <- cov(X)
par.var <- colMeans(X)
se.var <- as.vector(as.matrix(sqrt(diag(cov.var))))
names(se.var) <- row.names(cov.var)
return(list(par = par.var, se = se.var))
}
par.control <- getPars("par.control")$par
se.control <- getPars("par.control")$se
par.sensitive <- getPars("par.sensitive")$par
se.sensitive <- getPars("par.sensitive")$se
if(!is.null(boot.out[[1]]$par.misreport)) {
par.misreport <- getPars("par.misreport")$par
se.misreport <- getPars("par.misreport")$se
} else {
par.misreport <- se.misreport <- NULL
}
if(!is.null(boot.out[[1]]$par.outcome)) {
par.outcome <- getPars("par.outcome")$par
se.outcome <- getPars("par.outcome")$se
} else {
par.outcome <- se.outcome <- NULL
}
if(!is.null(boot.out[[1]]$outcome.model.aux)) {
par.outcome <- getPars("par.outcome.aux")$par
se.outcome <- getPars("par.outcome.aux")$se
} else {
par.outcome.aux <- se.outcome.aux <- NULL
}
se <- TRUE
args.call$get.boot <- 0
args.call$get.data <- TRUE
args.call$par.control <- par.control
args.call$par.sensitive <- par.sensitive
args.call$par.misreport <- par.misreport
args.call$par.outcome <- par.outcome
args.call$par.outcome.aux <- par.outcome.aux
llik <- do.call(listExperiment, args.call)$ll
w <- do.call(listExperiment, args.call)$w
return.object <- boot.out[[1]]
return.object$par.control <- par.control
return.object$par.sensitive <- par.sensitive
return.object$par.misreport <- par.misreport
return.object$par.outcome <- par.outcome
return.object$par.outcome.aux <- par.outcome.aux
return.object$df <- return.object$n - length(c(par.control, par.sensitive, par.misreport, par.outcome, par.outcome.aux))
return.object$se.control <- se.control
return.object$se.sensitive <- se.sensitive
return.object$se.misreport <- se.misreport
return.object$se.outcome <- se.outcome
return.object$se.outcome.aux <- se.outcome.aux
return.object$vcov.model <- NULL
return.object$data <- data
return.object$se <- TRUE
return.object$w <- exp(w)
return.object$llik <- llik
return.object$call <- function.call
return.object$boot.iter <- boot.iter
return.object$boot.out <- boot.out
return.object$boot <- TRUE
class(return.object) <- "listExperiment"
return(return.object)
}
predict.listExperiment <- function(object, newdata = NULL,
treatment.misreport = 0,
par.control = NULL,
par.sensitive = NULL,
par.misreport = NULL,
...) {
if(!is.null(par.control)) object$par.control <- par.control
if(!is.null(par.sensitive)) object$par.sensitive <- par.sensitive
if(!is.null(par.misreport)) object$par.misreport <- par.misreport
if(is.null(newdata)) {
data <- object$data
} else data <- newdata
if(as.character(object$formula[[2]]) %in% names(data)) {
y <- data[, paste(object$formula[[2]])]
} else stop(paste0("The list experiment response ", as.character(object$formula[[2]]), " not found in data."))
if(treatment.misreport == "observed") {
if(object$treatment %in% names(data)) {
treatment <- data[, paste(object$treatment)]
} else {
stop(paste0("Argument treatment.misreport was set to \"observed\", but treatment variable \"", object$treatment, "\" is not in the data."))
}
} else {
treatment <- rep(treatment.misreport, nrow(data))
}
if(!is.null(object$direct)) {
if(object$direct %in% names(data)) {
d <- data[, paste(object$direct)]
} else {
stop(paste0("Direct question variable", object$direct, "\" is not in the data."))
}
} else{
d <- rep(NA, nrow(data))
}
if(!is.null(object$outcome)) {
if(object$outcome %in% names(data)) {
o <- data[, paste(object$outcome)]
} else {
stop(paste0("Outcome variable", object$outcome, "\" is not in the data."))
}
} else {
o <- rep(NA, nrow(data))
}
if(all(all.vars(object$formula.sensitive)[-1] %in% names(data))) {
x.sensitive <- model.matrix(object$formula.sensitive[-2], data = model.frame(~ ., data, na.action = na.pass, xlev = object$xlevels))
} else {
stop(paste0("Not all variables used in the sensitive-item sub-model are available in the data"))
}
if(!is.null(object$par.misreport)) {
if(all(all.vars(object$formula.misreport)[-1] %in% names(data))) {
x.misreport <- model.matrix(object$formula.misreport[-2], data = model.frame(~ ., data, na.action = na.pass, xlev = object$xlevels))
} else {
stop(paste0("Not all variables used in the misreport sub-model are available in the data"))
}
} else {
x.misreport <- rep(NA, nrow(data))
}
z.hat <- as.numeric(plogis(x.sensitive %*% object$par.sensitive))
if(object$model.misreport == TRUE) {
if(object$misreport.treatment == TRUE) {
u.hat <- as.numeric(plogis(as.matrix(data.frame(x.misreport, treatment)) %*% object$par.misreport))
} else {
u.hat <- as.numeric(plogis(as.matrix(data.frame(x.misreport)) %*% object$par.misreport))
}
} else u.hat <- NULL
return(list(z.hat = z.hat, u.hat = u.hat))
}
summary.listExperiment <- function(object, digits = 4, ...) {
cat("\nList experiment sub-models\n\n")
cat("Call: ")
print(object$call)
if(object$se == TRUE) {
cat("\nCONTROL ITEMS Pr(Y* = y)\n")
matrix.control <- cbind(round(object$par.control, digits),
round(object$se.control, digits),
round(object$par.control/object$se.control, digits),
round(2 * pnorm(abs(object$par.control/object$se.control), lower.tail = FALSE), digits))
colnames(matrix.control) <- c("est.", "se", "z", "p")
print(formatC(matrix.control, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---\n")
cat("\nSENSITIVE ITEM Pr(Z* = 1)\n")
matrix.sensitive <- cbind(round(object$par.sensitive, digits),
round(object$se.sensitive, digits),
round(object$par.sensitive/object$se.sensitive, digits),
round(2 * pnorm(abs(object$par.sensitive/object$se.sensitive), lower.tail = FALSE), digits))
colnames(matrix.sensitive) <- c("est.", "se", "z", "p")
print(formatC(matrix.sensitive, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---\n")
if(object$model.misreport == TRUE) {
cat("\nMISREPORT Pr(U* = 1)\n")
matrix.misreport <- cbind(round(object$par.misreport, digits),
round(object$se.misreport, digits),
round(object$par.misreport/object$se.misreport, digits),
round(2 * pnorm(abs(object$par.misreport/object$se.misreport), lower.tail = FALSE), digits))
colnames(matrix.misreport) <- c("est.", "se", "z", "p")
print(formatC(matrix.misreport, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---\n")
}
if(object$outcome.model != "none") {
cat("\nOUTCOME\n")
matrix.outcome <- cbind(round(object$par.outcome, digits),
round(object$se.outcome, digits),
round(object$par.outcome/object$se.outcome, digits),
round(2 * pnorm(abs(object$par.outcome/object$se.outcome), lower.tail = FALSE), digits))
colnames(matrix.outcome) <- c("est.", "se", "z", "p")
print(formatC(matrix.outcome, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---")
}
} else if(object$se == FALSE) {
cat("\nCONTROL ITEMS Pr(Y* = y)\n")
matrix.control <- cbind(round(object$par.control, digits))
colnames(matrix.control) <- c("est.")
print(formatC(matrix.control, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---\n")
cat("\nSENSITIVE ITEM Pr(Z* = 1)\n")
matrix.sensitive <- cbind(round(object$par.sensitive, digits))
colnames(matrix.sensitive) <- c("est.")
print(formatC(matrix.sensitive, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---\n")
if(object$model.misreport == TRUE) {
cat("\nMISREPORT Pr(U* = 1)\n")
matrix.misreport <- cbind(round(object$par.misreport, digits))
colnames(matrix.misreport) <- c("est.")
print(formatC(matrix.misreport, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---\n")
}
if(object$outcome.model != "none") {
cat("\nOUTCOME\n")
matrix.outcome <- cbind(round(object$par.outcome, digits))
colnames(matrix.outcome) <- c("est.")
print(formatC(matrix.outcome, format = "f", digits = digits), quote = FALSE, right = TRUE)
cat("---")
}
}
if(object$boot == TRUE) {
cat("\nStandard errors calculated by non-parametric bootstrap (", format(object$boot.iter, big.mark = ","), " draws).", sep = "")
}
cat("\nObservations:", format(object$n, big.mark = ","))
cat(" (", format(nrow(object$data)-object$n, big.mark = ","), " of ", format(nrow(object$data), big.mark = ","), " observations removed due to missingness)", sep = "")
cat("\nLog-likelihood", object$llik)
}
print.listExperiment <- function(x, ...) {
summary.listExperiment(x, ...)
} |
g <- function(x, w, p, eta, sq.var, theta.fix, theta.var)
{
res <- 0
for(i in 1:length(eta))
for(j in 1:length(eta))
if(p[i,j] != 0)
{
ev.eta.i <- eta[[i]](x, theta.fix[[i]])
sq.sigma.i <- log(1 + sq.var[[i]](x, theta.fix[[i]]) / (ev.eta.i * ev.eta.i))
mu.i <- log(ev.eta.i) - 0.5 * sq.sigma.i
opt.res <- optim(
par = theta.var[[i,j]],
function(theta) KLD.new(x, w, ev.eta.i, sq.sigma.i, mu.i, eta[[j]], sq.var[[j]], theta)
)
theta.var[[i,j]] <- opt.res$par
res <- res + p[i,j] * opt.res$value
}
res
} |
test_that("getHyperPars", {
lrn = makeLearner("classif.rpart")
expect_equal(getHyperPars(lrn), list(xval = 0))
lrn = makeLearner("classif.lda")
named.list = list()
names(named.list) = character(0)
expect_equal(getHyperPars(lrn), named.list)
lrn = makeFilterWrapper(makeLearner("classif.rpart"))
expect_true(setequal(names(getHyperPars(lrn)), c("xval", "fw.method")))
lrn = makeModelMultiplexer(list("classif.rpart", "classif.lda"))
expect_true(setequal(names(getHyperPars(lrn)), c("classif.rpart.xval", "selected.learner")))
lrn = makeLearner("multilabel.rFerns")
expect_true(setequal(getHyperPars(lrn), list()))
lrn = makeMultilabelBinaryRelevanceWrapper("classif.rpart")
expect_true(setequal(getHyperPars(lrn), list(xval = 0)))
lrn = makeLearner("classif.xgboost", missing = NA)
expect_output(print(lrn), "missing=NA")
lrn = makeLearner("regr.xgboost", missing = NA)
expect_output(print(lrn), "missing=NA")
}) |
library(ggplot2)
library(dplyr)
library(tidyr)
importFromExamples("ODETest.R")
ComparisonRK45ODEApp <- function(verbose = FALSE) {
ode <- new("ODETest")
ode_solver <- RK45(ode)
ode_solver <- setStepSize(ode_solver, 1)
setTolerance(ode_solver) <- 1e-6
time <- 0
rowVector <- vector("list")
i <- 1
while (time < 50) {
rowVector[[i]] <- list(t = getState(ode)[2],
ODE = getState(ode)[1],
s2 = getState(ode)[2],
exact = getExactSolution(ode, time),
rate.counts = getRateCounts(ode),
time = time )
ode_solver <- step(ode_solver)
stepSize <- getStepSize(ode_solver)
time <- time + stepSize
ode <- getODE(ode_solver)
state <- getState(ode)
i <- i + 1
}
DT <- data.table::rbindlist(rowVector)
return(DT)
}
solution <- ComparisonRK45ODEApp()
plot(solution)
solution.multi <- solution %>%
select(t, ODE, exact)
plot(solution.multi)
solution.2x1 <- solution.multi %>%
gather(key, value, -t)
g <- ggplot(solution.2x1, mapping = aes(x = t, y = value, color = key))
g <- g + geom_line(size = 1) +
labs(title = "ODE vs Exact solution",
subtitle = "tolerance = 1E-6")
print(g) |
knitr::opts_chunk$set(
collapse = TRUE,
fig.width = 6,
fig.asp = .4,
warning = FALSE,
message = FALSE,
comment = "
)
library(marginaleffects)
library(patchwork)
library(ggplot2)
theme_set(theme_minimal())
library(marginaleffects)
tmp <- mtcars
tmp$am <- as.logical(tmp$am)
mod <- lm(mpg ~ am + factor(cyl), tmp)
mfx <- marginaleffects(mod)
summary(mfx)
library(emmeans)
emm <- emmeans(mod, specs = "cyl")
contrast(emm, method = "revpairwise")
emm <- emmeans(mod, specs = "am")
contrast(emm, method = "revpairwise")
mod_int <- lm(mpg ~ am * factor(cyl), tmp)
marginaleffects(mod_int, newdata = datagrid(cyl = tmp$cyl), variables = "am")
emm <- emmeans(mod_int, specs = "am", by = "cyl")
contrast(emm, method = "revpairwise") |
context("CrulAdapter")
aa <- CrulAdapter$new()
test_that("CrulAdapter bits are correct", {
skip_on_cran()
expect_is(CrulAdapter, "R6ClassGenerator")
expect_is(aa, "CrulAdapter")
expect_null(aa$build_crul_request)
expect_null(aa$build_crul_response)
expect_is(aa$disable, "function")
expect_is(aa$enable, "function")
expect_is(aa$handle_request, "function")
expect_is(aa$remove_stubs, "function")
expect_is(aa$name, "character")
expect_equal(aa$name, "CrulAdapter")
})
test_that("CrulAdapter behaves correctly", {
skip_on_cran()
expect_message(aa$enable(), "CrulAdapter enabled!")
expect_message(aa$disable(), "CrulAdapter disabled!")
})
test_that("build_crul_request/response fail well", {
skip_on_cran()
expect_error(build_crul_request(), "argument \"x\" is missing")
expect_error(build_crul_response(), "argument \"resp\" is missing")
})
test_that("CrulAdapter: works when vcr is loaded but no cassette is inserted", {
skip_on_cran()
skip_if_not_installed("vcr")
webmockr::enable(adapter = "crul")
on.exit({
webmockr::disable(adapter = "crul")
unloadNamespace("vcr")
})
stub_request("get", "https://httpbin.org/get")
library("vcr")
cli <- crul::HttpClient$new("https://httpbin.org")
expect_silent(x <- cli$get("get"))
expect_is(x, "HttpResponse")
vcr::vcr_configure(dir = tempdir())
vcr::insert_cassette("empty")
expect_silent(x <- cli$get("get"))
vcr::eject_cassette("empty")
expect_is(x, "HttpResponse")
})
context("CrulAdapter - with real data")
test_that("CrulAdapter works", {
skip_on_cran()
skip_if_not_installed('vcr')
load("crul_obj.rda")
crul_obj$url$handle <- curl::new_handle()
res <- CrulAdapter$new()
library(vcr)
expect_error(
res$handle_request(crul_obj),
"There is currently no cassette in use"
)
unloadNamespace("vcr")
expect_error(
res$handle_request(crul_obj),
"Real HTTP connections are disabled.\nUnregistered request:\n GET: http://localhost:9000/get\n\nYou can stub this request with the following snippet:\n\n stub_request\\('get', uri = 'http://localhost:9000/get'\\)\n============================================================"
)
invisible(stub_request("get", "http://localhost:9000/get"))
aa <- res$handle_request(crul_obj)
expect_is(res, "CrulAdapter")
expect_is(aa, "HttpResponse")
expect_equal(aa$method, "get")
expect_equal(aa$url, "http://localhost:9000/get")
expect_equal(length(aa$response_headers), 0)
expect_equal(length(aa$response_headers_all), 0)
stub_registry_clear()
x <- stub_request("get", "http://localhost:9000/get")
x <- to_return(x, headers = list('User-Agent' = 'foo-bar'))
aa <- res$handle_request(crul_obj)
expect_is(res, "CrulAdapter")
expect_is(aa, "HttpResponse")
expect_equal(aa$method, "get")
expect_equal(aa$url, "http://localhost:9000/get")
expect_equal(length(aa$response_headers), 1)
expect_is(aa$response_headers, "list")
expect_named(aa$response_headers, "user-agent")
expect_equal(length(aa$response_headers_all), 1)
expect_is(aa$response_headers_all, "list")
expect_named(aa$response_headers_all, NULL)
expect_named(aa$response_headers_all[[1]], "user-agent")
my_url <- "https://doi.org/10.1007/978-3-642-40455-9_52-1"
x <- stub_request("get", my_url)
x <- to_return(x, status = 302, headers =
list(
status = 302,
location = "http://link.springer.com/10.1007/978-3-642-40455-9_52-1"
)
)
crul_obj$url$url <- my_url
res <- CrulAdapter$new()
aa <- res$handle_request(crul_obj)
expect_equal(aa$method, "get")
expect_equal(aa$url, my_url)
expect_equal(aa$status_code, 302)
expect_equal(length(aa$response_headers), 2)
expect_is(aa$response_headers, "list")
expect_equal(sort(names(aa$response_headers)), c('location', 'status'))
expect_equal(length(aa$response_headers_all), 1)
expect_equal(length(aa$response_headers_all[[1]]), 2)
expect_is(aa$response_headers_all, "list")
expect_is(aa$response_headers_all[[1]], "list")
expect_named(aa$response_headers_all, NULL)
expect_equal(sort(names(aa$response_headers_all[[1]])),
c('location', 'status'))
})
test_that("crul requests with JSON-encoded bodies work", {
skip_on_cran()
on.exit(disable(adapter = "crul"))
enable(adapter = "crul")
body <- list(foo = "bar")
url <- "https://httpbin.org"
cli <- crul::HttpClient$new(url)
z <- stub_request("post", uri = file.path(url, "post")) %>%
wi_th(body = jsonlite::toJSON(body, auto_unbox = TRUE))
res <- cli$post("post", body = body, encode = "json")
expect_is(res, "HttpResponse")
expect_error(
cli$post("post", body = list(foo = "bar1"), encode = "json"),
"Unregistered request"
)
expect_error(
cli$post("post", body = body),
"Unregistered request"
)
}) |
is_too_many <-
function(query=NULL, id_list=NULL, start=0, limit=10)
{
toomany <- getOption("aRxiv_toomany")
if(is.null(toomany)) toomany <- 15000
expected_number <- NA
if(is.null(start))
start <- 0
if(is.null(limit))
limit <- expected_number <- arxiv_count(query, id_list)
stopifnot(start >= 0)
stopifnot(limit >= 0)
if(limit > toomany) {
if(is.na(expected_number))
expected_number <- arxiv_count(query, id_list)
message("Total records matching query: ", expected_number)
if(expected_number > toomany)
return(expected_number)
}
0
} |
plot.bpca.2d <- function(x,
type=c('bp', 'eo', 'ev', 'co', 'cv', 'ww', 'dv', 'ms', 'ro', 'rv'),
c.color='darkgray',
c.lwd=1,
c.number=5,
c.radio=1,
obj.id=1:2,
var.id=1,
base.color='red3',
base.lty='dotted',
proj.color='gray',
proj.lty='dotted',
a.color='blue',
a.lty='solid',
a.lwd=2,
a.length=.1,
ref.lines=TRUE,
ref.color='navy',
ref.lty='dotted',
var.factor=1,
var.color='red3',
var.lty='solid',
var.pch=20,
var.pos=4,
var.cex=.6,
var.offset=.2,
obj.factor=1,
obj.color='black',
obj.pch=20,
obj.pos=4,
obj.cex=.6,
obj.offset=.2,
obj.names=TRUE,
obj.labels,
obj.identify=FALSE,
xlim, ylim, xlab, ylab, ...)
{
draw.obj <-
function()
{
if(obj.names) {
points(x=coobj[,d1],
y=coobj[,d2],
pch=obj.pch,
col=obj.color,
cex=obj.cex, ...)
text(x=coobj[,d1],
y=coobj[,d2],
labels=obj.labels,
pos=obj.pos,
offset=obj.offset,
col=obj.color,
cex=obj.cex, ...)
} else {
points(x=coobj[,d1],
y=coobj[,d2],
pch=obj.pch,
col=obj.color,
cex=obj.cex, ...)
}
}
draw.var <-
function()
{
points(x=covar[,d1] * var.factor,
y=covar[,d2] * var.factor,
pch=var.pch,
col=var.color,
cex=var.cex, ...)
text(x=covar[,d1] * var.factor,
y=covar[,d2] * var.factor,
labels=rownames(covar),
pos=var.pos,
offset=var.offset,
col=var.color,
cex=var.cex, ...)
}
draw.var.seg <-
function()
{
segments(x0=0,
y0=0,
x1=covar[,d1] * var.factor,
y1=covar[,d2] * var.factor,
col=var.color,
lty=var.lty, ...)
}
draw.circles <-
function()
{
for (i in 1:c.number)
symbols(x=0,
y=0,
circles=c.radio * i * var.factor,
add=TRUE,
inches=FALSE,
fg=c.color,
lwd=c.lwd, ...)
}
if (!inherits(x, 'bpca.2d'))
stop("Use this function only with 'bpca.2d' class!")
coobj <- x$coord$objects
covar <- x$coord$variables
d1 <- x$number[1]
d2 <- x$number[2]
scores <- rbind(coobj,
covar * var.factor,
rep(0,
ncol(coobj)))
if (missing(obj.labels))
obj.labels <- rownames(coobj)
if (missing(xlim) || missing(ylim)) {
ms <- max(abs(scores)) * 1.2
msp <- c(-ms, ms)
}
if (missing(xlim))
xlim <- msp
if (missing(ylim))
ylim <- msp
if (missing(xlab) || missing(ylab)) {
eigv <- x$eigenvalues
prop <- 100 * eigv^2 / sum(eigv^2)
labs <- paste('PC',
d1:d2,
' (',
round(prop[d1:d2], 2),
'%)',
sep='')
}
if (missing(xlab))
xlab <- labs[1]
if (missing(ylab))
ylab <- labs[2]
plot(scores,
xlim=xlim,
ylim=ylim,
xlab=xlab,
ylab=ylab,
type='n', ...)
if (ref.lines)
abline(h=0,
v=0,
col=ref.color,
lty=ref.lty, ...)
switch(match.arg(type),
bp={
draw.obj()
draw.var()
draw.var.seg()
if(obj.identify)
identify(x=coobj,
labels=obj.labels,
cex=obj.cex)
},
eo={
if (any(class(obj.id) == c('numeric', 'integer')))
obj.lab <- obj.labels[obj.id[1]]
else {
if (obj.id %in% obj.labels){
obj.lab <- obj.labels[match(obj.id,
obj.labels)]
obj.id <- match(obj.id,
obj.labels)
}
else
stop("'obj.id' do not match with 'obj.labels'!")
}
draw.var()
abline(a=0,
b=coobj[obj.id,d2] / coobj[obj.id,d1],
col=base.color,
lty=base.lty, ...)
abline(a=0,
b=-coobj[obj.id,d1] / coobj[obj.id,d2],
col=base.color,
lty=base.lty, ...)
arrows(x0=0,
y0=0,
x1=coobj[obj.id[1],d1] * obj.factor,
y1=coobj[obj.id[1],d2] * obj.factor,
col=a.color,
lty=a.lty,
lwd=a.lwd,
length=a.length, ...)
points(x=coobj[obj.id[1],d1] * obj.factor,
y=coobj[obj.id[1],d2] * obj.factor,
pch=obj.pch,
col=obj.color,
cex=obj.cex, ...)
text(x=coobj[obj.id[1],d1] * obj.factor,
y=coobj[obj.id[1],d2] * obj.factor,
labels=obj.lab,
pos=obj.pos,
offset=obj.offset,
col=obj.color,
cex=obj.cex, ...)
x <- solve(cbind(c(-coobj[obj.id[1],d2],
coobj[obj.id[1],d1]),
c(coobj[obj.id[1],d1],
coobj[obj.id[1],d2])),
rbind(0,
as.numeric(covar[,c(d1, d2)] %*%
coobj[obj.id[1],c(d1, d2)])))
segments(x0=covar[,d1],
y0=covar[,d2],
x1=x[1,],
y1=x[2,],
lty=proj.lty,
col=proj.color)
},
ev={
draw.obj()
abline(a=0,
b=covar[var.id,d2] / covar[var.id,d1],
col=base.color,
lty=base.lty, ...)
abline(a=0,
b=-covar[var.id,d1] / covar[var.id,d2],
col=base.color,
lty=base.lty, ...)
arrows(x0=0,
y0=0,
x1=covar[var.id,d1] * var.factor,
y1=covar[var.id,d2] * var.factor,
col=a.color,
lty=a.lty,
lwd=a.lwd,
length=a.length, ...)
points(x=covar[var.id,d1] * var.factor,
y=covar[var.id,d2] * var.factor,
pch=var.pch,
col=var.color,
cex=var.cex, ...)
text(x=covar[var.id,d1] * var.factor,
y=covar[var.id,d2] * var.factor,
labels=ifelse(mode(var.id) == 'numeric', rownames(covar)[var.id], var.id),
pos=var.pos,
offset=var.offset,
col=var.color,
cex=var.cex, ...)
x <- solve(cbind(c(-covar[var.id,d2],
covar[var.id,d1]),
c(covar[var.id,d1],
covar[var.id,d2])),
rbind(0,
as.numeric(coobj[,c(d1, d2)] %*%
covar[var.id,c(d1, d2)])))
segments(x0=coobj[,d1],
y0=coobj[,d2],
x1=x[1,],
y1=x[2,],
lty=proj.lty,
col=proj.color, ...)
},
co={
if (any(class(obj.id) == c('character', 'factor')))
if (obj.id[1] %in% obj.labels &
obj.id[2] %in% obj.labels) {
obj.id[1] <- match(obj.id[1], obj.labels)
obj.id[2] <- match(obj.id[2], obj.labels)
} else
stop("At last one 'obj.id' do not match with 'obj.labels'!")
draw.obj()
draw.var()
symbols(x=coobj[obj.id[1],d1],
y=coobj[obj.id[1],d2],
circles=c.radio,
add=TRUE,
inches=FALSE,
fg=c.color,
lwd=c.lwd, ...)
symbols(x=coobj[obj.id[2],d1],
y=coobj[obj.id[2],d2],
circles=c.radio,
add=TRUE,
inches=FALSE,
fg=c.color,
lwd=c.lwd, ...)
segments(x0=coobj[obj.id[1],d1],
y0=coobj[obj.id[1],d2],
x1=coobj[obj.id[2],d1],
y1=coobj[obj.id[2],d2],
col=proj.color,
lty=proj.lty, ...)
abline(a=0,
b=-(coobj[obj.id[1],d1] -
coobj[obj.id[2],d1]) /
(coobj[obj.id[1],d2] -
coobj[obj.id[2],d2]),
col=base.color,
lty=base.lty, ...)
},
cv={
draw.obj()
draw.var()
draw.var.seg()
draw.circles()
},
ww={
draw.obj()
draw.var()
indice <- c(chull(coobj[,d1],
coobj[,d2]))
polygon(x=coobj[indice,d1],
y=coobj[indice,d2],
border=proj.color,
lty=proj.lty, ...)
i <- 1
while (is.na(indice[i + 1]) == FALSE) {
m <- (coobj[indice[i],d2] -
coobj[indice[i + 1],d2]) /
(coobj[indice[i],d1] -
coobj[indice[i + 1],d1])
mperp <- -1 / m
c2 <- coobj[indice[i + 1],d2] -
m * coobj[indice[i + 1],d1]
xint <- -c2/(m - mperp)
xint <- ifelse(xint < 0,
min(covar[,d1],
coobj[,d1]),
max(covar[,d1],
coobj[,d1]))
yint <- mperp * xint
segments(x0=0,
y0=0,
x1=xint,
y1=yint,
col=base.color,
lty=base.lty, ...)
i <- i + 1
}
m <- (coobj[indice[i],d2] -
coobj[indice[1],d2]) /
(coobj[indice[i],d1] -
coobj[indice[1],d1])
mperp <- -1 / m
c2 <- coobj[indice[i],d2] -
m * coobj[indice[i],d1]
xint <- -c2 / (m - mperp)
xint <- ifelse(xint < 0,
min(covar[,d1],
coobj[,d1]),
max(covar[,d1],
coobj[,d1]))
yint <- mperp * xint
segments(x0=0,
y0=0,
x1=xint,
y1=yint,
col=base.color,
lty=base.lty, ...)
},
dv={
draw.obj()
draw.var()
draw.circles()
draw.var.seg()
arrows(x0=0,
y0=0,
x1=mean(covar[, d1] * var.factor),
y1=mean(covar[, d2] * var.factor),
col=a.color,
lty=a.lty,
lwd=a.lwd,
length=a.length, ...)
points(mean(covar[, d1] * var.factor),
mean(covar[, d2] * var.factor),
pch=1,
cex=3,
col='blue', ...)
abline(a=0,
b=mean(covar[,d2]) / mean(covar[,d1]),
col=var.color,
lty=base.lty, ...)
},
ms={
m1 <- mean(covar[,d1] * var.factor)
m2 <- mean(covar[,d2] * var.factor)
abline(a=0,
b=m2 / m1,
col=base.color,
lty=base.lty, ...)
abline(a=0,
b=-m1/m2,
col=base.color,
lty=base.lty, ...)
arrows(x0=0,
y0=0,
x1=m1,
y1=m2,
col=a.color,
lty=a.lty,
lwd=a.lwd,
length=a.length, ...)
draw.obj()
draw.var()
for (i in 1:c.number)
symbols(x=m1,
y=m2,
circles=c.radio * i * var.factor,
add=TRUE,
inches=FALSE,
fg=c.color,
lwd=c.lwd, ...)
for (i in 1:nrow(coobj))
{
x <- solve(matrix(c(-m2,
m1,
m1,
m2),
nrow=2),
matrix(c(0,
m2 * coobj[i,d2] +
m1 * coobj[i,d1]),
ncol=1))
segments(x0=coobj[i,d1],
y0=coobj[i,d2],
x1=x[1],
y1=x[2],
col=proj.color,
lty=proj.lty, ...)
}
},
ro={
m1 <- mean(covar[,d1])
m2 <- mean(covar[,d2])
abline(a=0,
b=m2 / m1,
col=base.color,
lty=base.lty, ...)
abline(a=0,
b=-m1 / m2,
col=base.color,
lty=base.lty, ...)
draw.obj()
draw.var()
cox <- 0
coy <- 0
for (i in 1:nrow(coobj))
{
x <- solve(matrix(c(-m2,
m1,
m1,
m2),
nrow=2),
matrix(c(0,
m2 * coobj[i,d2] + m1 * coobj[i,d1]),
ncol=1))
if (sign(x[1]) == sign(m1))
if(abs(x[1]) > abs(cox))
{
cox <- x[1]
coy <- x[2]
}
}
arrows(x0=0,
y0=0,
x1=cox,
y1=coy,
col=a.color,
lty=a.lty,
lwd=a.lwd,
length=a.length, ...)
for (i in 1:c.number)
symbols(x=cox,
y=coy,
circles=c.radio * i,
add=TRUE,
inches=FALSE,
fg=c.color,
lwd=c.lwd, ...)
},
rv={
draw.obj()
draw.var()
m1 <- mean(covar[,d1])
m2 <- mean(covar[,d2])
abline(a=0,
b=m2 / m1,
col=var.color,
lty="solid", ...)
abline(a=0,
b=-m1 / m2,
col=var.color,
lty="solid", ...)
symbols(x=m1,
y=m2,
circles=0.1,
add=TRUE,
inches=FALSE,
fg=c.color,
lwd=c.lwd, ...)
mod <- max((covar[,d1]^2 + covar[,d2]^2)^0.5)
cox <- sign(m1) * (mod^2 / (1 + m2^2 / m1^2))^0.5
coy <- (m2 / m1) * cox
arrows(x0=0,
y0=0,
x1=cox,
y1=coy,
col=a.color,
lty=a.lty,
lwd=a.lwd,
length=a.length, ...)
for (i in 1:c.number)
symbols(x=cox,
y=coy,
circles=c.radio*i,
add=TRUE,
inches=FALSE,
fg=c.color,
lwd=c.lwd, ...)
})
} |
ptweedie.inversion <- function(q, mu, phi, power, exact=FALSE ){
y <- q
cdf <- array( dim=length(y) )
if ( power<1) stop("power must be greater than 1.")
if ( any(phi<= 0) ) stop("phi must be positive.")
if ( any(y<0) ) stop("y must be a non-negative vector.")
if ( any(mu<=0) ) stop("mu must be positive.")
if ( length(mu)>1) {
if ( length(mu)!=length(y) ) stop("mu must be scalar, or the same length as y.")
} else {
mu <- array( dim=length(y), mu )
}
if ( length(phi)>1) {
if ( length(phi)!=length(y) ) stop("phi must be scalar, or the same length as y.")
} else {
phi <- array( dim=length(y), phi )
}
for (i in (1:length(y))) {
if ( ( power > 2 ) & (y[i] < 1.0e-300) ) {
cdf[i] <- 0
} else {
tmp <- .Fortran( "twcdf",
as.double(power),
as.double(phi[i]),
as.double(y[i]),
as.double(mu[i]),
as.integer( exact ),
as.double(0),
as.integer(0),
as.double(0),
as.integer(0))
cdf[i] <- tmp[[6]]
}
}
cdf
}
dtweedie.dldphi.saddle <- function(phi, mu, power, y){
dev <- tweedie.dev( power=power, y=y, mu=mu)
l <- (-1)/(2*phi) + dev/(2*phi^2)
-2* sum(l)
}
dtweedie.logl <- function(phi, y, mu, power) {
sum( log( dtweedie( y=y, mu=mu, phi=phi, power=power) ) )
}
logLiktweedie <- function(glm.obj, dispersion=NULL) {
p <- get("p", envir = environment(glm.obj$family$variance))
if (p==1) message("*** Tweedie index power = 1: Consider using dispersion=1 in call to logLiktweedie().\n")
AICtweedie(glm.obj, dispersion=dispersion, k=0, verbose=FALSE) / (-2)
}
dtweedie.logl.saddle <- function( phi, power, y, mu, eps=0){
sum( log( dtweedie.saddle(power=power, phi=phi, y=y, mu=mu, eps=eps) ) )
}
dtweedie.logv.bigp <- dtweedie.logv.bigp <- function( y, phi, power){
if ( power<2) stop("power must be greater than 2.")
if ( any(phi<= 0) ) stop("phi must be positive.")
if ( any(y<=0) ) stop("y must be a strictly positive vector.")
if ( length(phi)>1) {
if ( length(phi)!=length(y) ) stop("phi must be scalar, or the same length as y.")
} else {
phi <- array( dim = length(y), phi )
}
p <- power
a <- ( 2-p ) / ( 1-p )
a1 <- 1 - a
r <- -a1*log(phi) - log(p-2) - a*log(y) +
a*log(p-1)
drop <- 37
logz <- max(r)
k.max <- max( y^(2-p) / ( phi * (p-2) ) )
k <- max( 1, k.max )
c <- logz + a1 + a*log(a)
vmax <- k.max * a1
estlogv <- vmax
while ( estlogv > (vmax - drop) ) {
k <- k + 2
estlogv <- k*( c - a1*log(k) )
}
hi.k <- ceiling(k)
logz <- min(r)
k.max <- min( y^(2-p) / ( phi * (p-2) ) )
k <- max( 1, k.max )
c <- logz + a1 + a*log(a)
vmax <- k.max * a1
estlogv <- vmax
while ( (estlogv > (vmax-drop) ) && ( k>=2) ) {
k <- max(1, k - 2)
estlogv <- k*( c - a1*log(k) )
}
lo.k <- max(1, floor(k) )
k <- seq(lo.k, hi.k)
o <- matrix( 1, nrow=length(y))
g <- matrix( lgamma( 1+a*k) - lgamma(1+k),
nrow=1, ncol=length(k) )
og <- o %*% g
A <- outer(r, k) + og
C <- matrix( sin( -a*pi*k ) * (-1)^k,
nrow=1, ncol=length(k) )
C <- o %*% C
m <- apply(A, 1, max)
ve <- exp(A - m)
sum.ve <- apply( ve*C, 1, sum )
neg.sum.ve <- (sum.ve<=0)
pos.sum.ve <- (sum.ve>0)
logv <- sum.ve
sum.ve[neg.sum.ve] <- 0
logv[neg.sum.ve] <- -Inf
logv[pos.sum.ve] <- log( sum.ve[pos.sum.ve] ) + m[pos.sum.ve]
list(lo=lo.k, hi=hi.k, logv=logv, k.max=k.max )
}
dtweedie.logw.smallp <- function(y, phi, power){
if ( power<1) stop("power must be between 1 and 2.")
if ( power>2) stop("power must be between 1 and 2.")
if ( any(phi<=0) ) stop("phi must be positive.")
if ( any(y<=0) ) stop("y must be a strictly positive vector.")
p <- power
a <- ( 2-p ) / ( 1-p )
a1 <- 1 - a
r <- -a*log(y) + a*log(p-1) - a1*log(phi) -
log(2-p)
drop <- 37
logz <- max(r)
j.max <- max( y^( 2-p ) / ( phi * (2-p) ) )
j <- max( 1, j.max )
cc <- logz + a1 + a*log(-a)
wmax <- a1*j.max
estlogw <- wmax
while(estlogw > (wmax-drop) ){
j <- j + 2
estlogw <- j*(cc - a1*log(j))
}
hi.j <- ceiling(j)
logz <- min(r)
j.max <- min( y^( 2-power ) / ( phi * (2-power) ) )
j <- max( 1, j.max)
wmax <- a1*j.max
estlogw <- wmax
while ( ( estlogw > (wmax-drop) ) && ( j>=2) ) {
j <- max(1, j - 2)
oldestlogw <- estlogw
estlogw <- j*(cc-a1*log(j))
}
lo.j <- max(1, floor(j))
j <- seq( lo.j, hi.j)
o <- matrix( 1, nrow=length(y))
g <- matrix(lgamma( j+1 ) + lgamma( -a*j ),
nrow=1, ncol=hi.j - lo.j + 1)
og <- o %*% g
A <- outer(r, j) - og
m <- apply(A,1,max)
we <- exp( A - m )
sum.we <- apply( we,1,sum)
logw <- log( sum.we ) + m
list(lo=lo.j, hi=hi.j, logw=logw, j.max=j.max )
}
dtweedie <- function(y, xi=NULL, mu, phi, power=NULL)
{
if ( is.null(power) & is.null(xi) ) stop("Either xi or power must be given\n")
xi.notation <- TRUE
if ( is.null(power) ) {
power <- xi
} else {
xi.notation <- FALSE
}
if ( is.null(xi) ) {
xi.notation <- FALSE
xi <- power
}
if ( xi != power ) {
cat("Different values for xi and power given; the value of xi used.\n")
power <- xi
}
index.par <- ifelse( xi.notation, "xi","p")
index.par.long <- ifelse( xi.notation, "xi","power")
if ( any(power<1) ) stop( paste(index.par.long, "must be greater than 1.\n") )
if ( any(phi<=0) ) stop("phi must be positive.")
if ( any(y<0) ) stop("y must be a non-negative vector.\n")
if ( any(mu<=0) ) stop("mu must be positive.\n")
if ( length(mu)>1) {
if ( length(mu)!=length(y) ) stop("mu must be scalar, or the same length as y.\n")
} else {
mu <- array( dim=length(y), mu )
}
if ( length(phi)>1) {
if ( length(phi)!=length(y) ) stop("phi must be scalar, or the same length as y.\n")
} else {
phi <- array( dim=length(y), phi )
}
density <- y
if ( power==3 ){
density <- statmod::dinvgauss(x=y, mean=mu, dispersion=phi)
return(density)
}
if ( power==2 ) {
density <- dgamma( rate=1/(phi*mu), shape=1/phi, x=y )
return(density)
}
if ( power==0) {
density <- dnorm( mean=mu, sd=sqrt(phi), x=y )
return(density)
}
if ( (power==1) & (all(phi==1))) {
density <- dpois(x=y/phi, lambda=mu/phi )
return(density)
}
id.type0 <- array( dim=length(y) )
id.series <- id.type0
id.interp <- id.type0
id.type0 <- (y==0)
if (any(id.type0)) {
if ( power > 2 ) {
density[id.type0] <- 0
} else {
lambda <- mu[id.type0]^(2-power)/(phi[id.type0]*(2-power))
density[id.type0] <- exp( -lambda )
}
}
xi <- array( dim=length(y) )
xi[id.type0] <- 0
xi[!id.type0] <- phi[!id.type0] * y[!id.type0]^(power-2)
xix <- xi / ( 1 + xi )
if ( (power>1) && (power<=1.1) ) {
id.series <- (!id.type0)
if (any(id.series)){
density[id.series] <- dtweedie.series(y=y[id.series],
mu=mu[id.series], phi=phi[id.series], power=power)
}
return(density=density)
}
if ( power==1 ) {
id.series <- rep(TRUE, length(id.series))
id.interp <- rep(FALSE, length(id.series))
}
if ( (power>1.1) && (power<=1.2) ) {
id.interp <- ( (xix>0) & (xix<0.1) )
id.series <- (!(id.interp|id.type0))
if ( any(id.interp)) {
grid <- stored.grids(power)
p.lo <- 1.1
p.hi <- 1.2
xix.lo <- 0
xix.hi <- 0.1
np <- 15
nx <- 25
}
}
if ( (power>1.2) && (power<=1.3) ) {
id.interp <- ( (xix>0) & (xix<0.3) )
id.series <- (!(id.interp|id.type0))
if ( any(id.interp)) {
grid <- stored.grids(power)
p.lo <- 1.2
p.hi <- 1.3
xix.lo <- 0
xix.hi <- 0.3
np <- 15
nx <- 25
}
}
if ( (power>1.3) && (power<=1.4) ) {
id.interp <- ( (xix>0) & (xix<0.5) )
id.series <- (!(id.interp|id.type0))
if ( any(id.interp)) {
grid <- stored.grids(power)
p.lo <- 1.3
p.hi <- 1.4
xix.lo <- 0
xix.hi <- 0.5
np <- 15
nx <- 25
}
}
if ( (power>1.4) && (power<=1.5) ) {
id.interp <- ( (xix>0) & (xix<0.8) )
id.series <- (!(id.interp|id.type0))
if ( any(id.interp)) {
grid <- stored.grids(power)
p.lo <- 1.4
p.hi <- 1.5
xix.lo <- 0
xix.hi <- 0.8
np <- 15
nx <- 25
}
}
if ( (power>1.5) && (power<2) ) {
id.interp <- ( (xix>0) & (xix<0.9) )
id.series <- (!(id.interp|id.type0))
if ( any(id.interp)) {
grid <- stored.grids(power)
p.lo <- 1.5
p.hi <- 2
xix.lo <- 0
xix.hi <- 0.9
np <- 15
nx <- 25
}
}
if ( (power>2) && (power<3) ) {
id.interp <- ( (xix>0) & (xix<0.9) )
id.series <- (!(id.interp|id.type0))
if ( any(id.interp)) {
grid <- stored.grids(power)
p.lo <- 2
p.hi <- 3
xix.lo <- 0
xix.hi <- 0.9
np <- 15
nx <- 25
}
}
if ( (power>=3) && (power<4) ) {
id.interp <- ( (xix>0) & (xix<0.9) )
id.series <- (!(id.interp|id.type0))
if ( any(id.interp)) {
grid <- stored.grids(power)
p.lo <- 3
p.hi <- 4
xix.lo <- 0
xix.hi <- 0.9
np <- 15
nx <- 25
}
}
if ( (power>=4) && (power<5) ) {
id.interp <- ( (xix>0) & (xix<0.9) )
id.series <- (!(id.interp|id.type0))
if ( any(id.interp)) {
grid <- stored.grids(power)
p.lo <- 4
p.hi <- 5
xix.lo <- 0
xix.hi <- 0.9
np <- 15
nx <- 25
}
}
if ( (power>=5) && (power<7) ) {
id.interp <- ( (xix>0) & (xix<0.5) )
id.series <- (!(id.interp|id.type0))
if ( any(id.interp)) {
grid <- stored.grids(power)
p.lo <- 5
p.hi <- 7
xix.lo <- 0
xix.hi <- 0.5
np <- 15
nx <- 25
}
}
if ( (power>=7) && (power<=10) ) {
id.interp <- ( (xix>0) & (xix<0.3) )
id.series <- (!(id.interp|id.type0))
if ( any(id.interp)) {
grid <- stored.grids(power)
p.lo <- 7
p.hi <- 10
xix.lo <- 0
xix.hi <- 0.3
np <- 15
nx <- 25
}
}
if ( power>10) {
id.series <- (y!=0)
id.interp <- (!(id.series|id.type0))
}
if (any(id.series)) {
density[id.series] <- dtweedie.series(y=y[id.series],
mu=mu[id.series], phi=phi[id.series], power=power)
}
if (any(id.interp)) {
dim( grid ) <- c( nx+1, np+1 )
rho <- dtweedie.interp(grid, np=np, nx=nx,
xix.lo=xix.lo, xix.hi=xix.hi,
p.lo=p.lo, p.hi=p.hi,
power=power, xix=xix[id.interp] )
dev <- tweedie.dev(power = power, mu = mu[id.interp], y = y[id.interp])
front <- rho/(y[id.interp] * sqrt(2 * pi * xi[id.interp]))
density[id.interp] <- front * exp(-1/(2 * phi[id.interp]) * dev)
}
density
}
dtweedie.saddle <- function(y, xi=NULL, mu, phi, eps=1/6, power=NULL) {
if ( is.null(power) & is.null(xi) ) stop("Either xi or power must be given\n")
xi.notation <- TRUE
if ( is.null(power) ) {
power <- xi
} else {
xi.notation <- FALSE
}
if ( is.null(xi) ) {
xi.notation <- FALSE
xi <- power
}
if ( xi != power ) {
cat("Different values for xi and power given; the value of xi used.\n")
power <- xi
}
index.par <- ifelse( xi.notation, "xi","p")
index.par.long <- ifelse( xi.notation, "xi","power")
if( any(phi <= 0) )
stop("phi must be positive.")
if( (power >=1) & any(y < 0))
stop("y must be a non-negative vector.")
if( any(mu <= 0) )
stop("mu must be positive.")
if ( length(mu)==1 )
mu <- array( dim=length(y), mu )
if ( length(phi)==1 )
phi <- array( dim=length(y), phi )
y.eps <- y
if (power<2) y.eps <- y + eps
y0 <- (y == 0)
density <- y
dev <- tweedie.dev(y=y, mu=mu, power=power)
density <- (2*pi*phi*y.eps^power)^(-1/2) * exp( -dev/(2*phi) )
if ( any(y==0) ){
if((power >= 1) && (power < 2)) {
lambda <- mu[y0]^(2 - power)/(phi[y0] * (2 - power))
density[y0] <- exp( -lambda)
} else {
density[y0] <- 0
}
}
density
}
dtweedie.series.bigp <- function(power, y, mu, phi){
if ( power<2) stop("power must be greater than 2.")
if ( any(phi<=0) ) stop("phi must be positive.")
if ( any(y<=0) ) stop("y must be a strictly positive vector.")
if ( any(mu<=0) ) stop("mu must be positive.")
if ( length(mu)>1) {
if ( length(mu)!=length(y) ) stop("mu must be scalar, or the same length as y.")
} else {
mu <- array( dim=length(y), mu )
}
if ( length(phi)>1) {
if ( length(phi)!=length(y) ) stop("phi must be scalar, or the same length as y.")
} else {
phi <- array( dim=length(y), phi )
}
result <- dtweedie.logv.bigp(power=power, y=y, phi=phi)
logv <- result$logv
theta <- mu^(1-power) / ( 1 - power )
kappa <- mu^(2-power) / ( 2 - power )
logfnew <- (y*theta-kappa)/phi - log( pi*y) + logv
f <- exp( logfnew )
list(density=f, logv=logv, lo=result$lo, hi=result$hi )
}
dtweedie.series <- function(y, power, mu, phi){
if ( power<1) stop("power must be between 1 and 2.")
if ( any(phi<=0) ) stop("phi must be positive.")
if ( any(y<0) ) stop("y must be a non-negative vector.")
if ( any(mu<=0) ) stop("mu must be positive.")
if ( length(mu)>1) {
if ( length(mu)!=length(y) ) stop("mu must be scalar, or the same length as y.")
} else {
mu <- array( dim = length(y), mu )
}
if ( length(phi)>1) {
if ( length(phi)!=length(y) ) stop("phi must be scalar, or the same length as y.")
} else {
phi <- array( dim = length(y), phi )
}
y0 <- (y == 0 )
yp <- ( y!=0 )
density <- array( dim=length(y))
if ( (power == 2) | (power==1) ) {
if ( power == 2 ){
density <- dgamma( y, shape=1/phi, rate=1/(phi * mu ) )
}
if ( (power == 1) ){
density <- dpois(x=y/phi, lambda=mu/phi ) / phi
if ( !all(phi==1)){
warnings("The density computations when phi=1 may be subject to errors using floating-point arithmetic\n")
}
}
} else{
if ( any(y==0) ) {
if ( power>2 ) {
density[y0] <- 0*y[y0]
}
if ( ( power>1) && (power<2) ) {
lambda <- mu[y0]^(2-power) / ( phi[y0] * (2-power) )
density[y0] <- exp( -lambda )
}
}
if ( any( y!=0 ) ) {
if ( power > 2 ) {
density[yp] <- dtweedie.series.bigp(
power=power,mu=mu[yp], y=y[yp], phi=phi[yp])$density
}
if ( ( power > 1 ) && ( power < 2 ) ) {
density[yp] <- dtweedie.series.smallp(
power=power,mu=mu[yp], y=y[yp], phi=phi[yp])$density
}
}
}
density
}
dtweedie.series.smallp <- function(power, y, mu, phi){
if ( power<1) stop("power must be between 1 and 2.")
if ( power>2) stop("power must be between 1 and 2.")
if ( any(phi<=0) ) stop("phi must be positive.")
if ( any(y<=0) & (power>=2) ) stop("y must be a strictly positive vector.")
if ( any(y<0) & (power>1) & (power < 2) ) stop("y must be a non-negative vector.")
if ( any(mu<=0) ) stop("mu must be positive.")
if ( length(mu)>1) {
if ( length(mu)!=length(y) ) stop("mu must be scalar, or the same length as y.")
} else {
mu <- array( dim = length(y), mu )
}
if ( length(phi)>1) {
if ( length(phi)!=length(y) ) stop("phi must be scalar, or the same length as y.")
} else {
phi <- array( dim=length(y), phi )
}
result <- dtweedie.logw.smallp( y=y, power=power, phi=phi)
logw <- result$logw
tau <- phi * (power-1) * mu^( power-1 )
lambda <- mu^( 2-power ) / ( phi * ( 2-power ) )
logf <- -y/tau - lambda - log(y) + logw
f <- exp( logf )
list(density=f, logw=logw, hi=result$hi, lo=result$lo)
}
ptweedie <- function(q, xi=NULL, mu, phi, power=NULL) {
if ( is.null(power) & is.null(xi) ) stop("Either xi or power must be given\n")
xi.notation <- TRUE
if ( is.null(power) ) {
power <- xi
} else {
xi.notation <- FALSE
}
if ( is.null(xi) ) {
xi.notation <- FALSE
xi <- power
}
if ( xi != power ) {
cat("Different values for xi and power given; the value of xi used.\n")
power <- xi
}
index.par <- ifelse( xi.notation, "xi","p")
index.par.long <- ifelse( xi.notation, "xi","power")
y <- q
y.negative <- (y<0)
y.original <- y
y <- y[ !y.negative ]
if ( any(power<1) ) stop( paste(index.par.long, "must be greater than 1.\n") )
if ( any(phi<=0) ) stop("phi must be positive.")
if ( any(mu<=0) ) stop("mu must be positive.\n")
if ( length(mu)>1) {
if ( length(mu)!=length(y.original) ) stop("mu must be scalar, or the same length as y.\n")
} else {
mu <- array( dim=length(y.original), mu )
}
mu.original <- mu
mu <- mu[ !y.negative ]
if ( length(phi)>1) {
if ( length(phi)!=length(y.original) ) stop("phi must be scalar, or the same length as y.\n")
} else {
phi <- array( dim=length(y.original), phi )
}
phi.original <- phi
phi <- phi[ !y.negative ]
cdf.positives <- array( dim=length(y) )
cdf <- y.original
if ( power==2 ) {
f <- pgamma( rate=1/(phi*mu), shape=1/phi, q=y )
}
if ( power==0) {
f <- pnorm( mean=mu, sd=sqrt(phi), q=y )
}
if ( power==1) {
f <- ppois(q=y, lambda=mu/phi )
}
if ( power> 2 ) {
f <- ptweedie.inversion(power=power, mu=mu, q=y, phi=phi)
}
if ( (power>1) & (power<2) ) {
if ( power <1.999) {
f <- ptweedie.series(power=power, q=y, mu=mu, phi=phi )
} else{
f <- ptweedie.inversion( power=power, q=y, mu=mu, phi=phi)
}
}
cdf[ !y.negative ] <- f
cdf[ y.negative ] <- 0
cdf[ is.infinite( cdf ) ] <- 1
cdf[ cdf>1 ] <- 1
return(cdf)
}
ptweedie.series <- function(q, power, mu, phi) {
y <- q
if ( power<1) stop("power must be between 1 and 2.\n")
if ( power>2) stop("power must be between 1 and 2.\n")
if ( any(phi<= 0)) stop("phi must be positive.\n")
if ( any(y<0) ) stop("y must be a non-negative vector.\n")
if ( any(mu<=0) ) stop("mu must be positive.\n")
if ( length(mu)>1) {
if ( length(mu)!=length(y) ) stop("mu must be scalar, or the same length as y.\n")
} else {
mu <- array( dim=length(y), mu )
}
if ( length(phi)>1) {
if ( length(phi)!=length(y) ) stop("phi must be scalar, or the same length as y.\n")
} else {
phi <- array( dim=length(y), phi )
}
p <- power
lambda <- mu^(2-p) / ( phi * (2-p) )
tau <- phi * (p-1) * mu^( p-1 )
alpha <- (2-p) / ( 1-p )
drop <- 39
lambda <- max(lambda )
logfmax <- -log(lambda)/2
estlogf <- logfmax
N <- max( lambda )
while ( ( estlogf > (logfmax - drop) ) & ( N > 1 ) ) {
N <- max(1, N - 2)
estlogf <- -lambda + N * ( log(lambda) - log(N) + 1 ) - log(N)/2
}
lo.N <- max(1, floor(N) )
lambda <- mu^(2-p) / ( phi * (2-p) )
lambda <- min( lambda )
logfmax <- -log(lambda)/2
estlogf <- logfmax
N <- max( lambda )
while ( estlogf > (logfmax - drop) ) {
N <- N + 1
estlogf <- -lambda + N * ( log(lambda) - log(N) + 1 ) - log(N)/2
}
hi.N <- max( ceiling(N) )
cdf <- array( dim=length(y), 0 )
lambda <- mu^(2-p) / ( phi * (2-p) )
tau <- phi * (p-1) * mu^( p-1 )
alpha <- (2-p) / ( 1-p )
for (N in (lo.N:hi.N)) {
pois.den <- dpois( N, lambda)
incgamma.den <- pchisq(2*y/tau, -2*alpha*N )
cdf <- cdf + pois.den * incgamma.den
}
cdf <- cdf + exp( -lambda )
its <- hi.N - lo.N + 1
cdf
}
stored.grids <- function(power){
if ( (power>1.5) && ( power<2) ) {
grid <- c(0.619552027046892,
-1.99653020187375,
-8.41322974185725,
-36.5410153849965,
-155.674714429765,
-616.623539139617,
-2200.89580607229,
-6980.89597754589,
-19605.6031284706,
-48857.4648924699,
-108604.369946264,
-216832.50696005,
-391832.053251182,
-646019.900543419,
-979606.689484813,
-1377088.40156071,
-1808605.4504829,
-2236021.71690435,
-2621471.84422418,
-2935291.72910167,
-3160933.2895598,
-3296019.98597692,
-3350191.70672175,
-3341188.71720722,
-3290375.55904795,
-3256251.04779701,
0.55083671442337,
2.79545515380255,
6.43661784251532,
0.0593276289419893,
-88.7776267014812,
-592.599945216246,
-2715.1932676716,
-9995.06110621652,
-31004.2502694815,
-82973.5646780374,
-194644.329882664,
-405395.126655972,
-758085.608783886,
-1285893.38788744,
-1997446.83841278,
-2866954.62503587,
-3834679.24827227,
-4818512.83125468,
-5732403.6885235,
-6504847.15089854,
-7091578.60837028,
-7479819.10447519,
-7684747.8312771,
-7739400.44941064,
-7651256.22196861,
-10780871.374931,
-0.296443816521139,
-0.740400436722078,
13.5437223703132,
132.570369303337,
739.235236905108,
3222.27476321793,
11883.2578358337,
37985.4069102717,
106385.512302156,
263186.759184411,
579709.939191383,
1146196.24715222,
2051166.63217944,
3349844.60761646,
5033457.4421439,
7014240.88296282,
9135328.47624901,
11203377.8720252,
13031732.9028836,
14478751.8662425,
15470353.6878961,
16004512.3987063,
16147291.8371304,
16087058.36173,
17256553.6861257,
-90196970.3516856,
0.212508829604868,
-1.25345600957563,
-33.6344002424504,
-229.413615894842,
-961.2927083918,
-3048.22512983433,
-7865.94887016698,
-16619.1472772416,
-27426.4597246056,
-29170.0602809743,
6910.62618199269,
133529.230915424,
425031.289018802,
962079.672230075,
1805724.1265787,
2970428.54627254,
4407924.65252939,
6009208.15039934,
7623903.3639327,
9090617.14760774,
10273366.8474699,
11112760.9034168,
11783847.5998635,
13967546.0605232,
40580571.9968577,
-1800585369.9502,
-0.117096128441307,
3.86814002139823,
52.1297859521411,
231.959187763769,
297.55942409085,
-2028.44588042558,
-16035.7900988595,
-69727.4207742442,
-231001.098781009,
-634711.96272568,
-1500867.48368527,
-3120952.565006,
-5795192.65274283,
-9728268.26803975,
-14923011.3657198,
-21127733.2735346,
-27877621.6155107,
-34629531.4516162,
-40942366.5228353,
-46618585.271072,
-51693745.2168584,
-56076194.3321918,
-57846478.5394169,
-39555239.6466308,
244583291.9647,
-19387464175.4177,
-0.0251908119117217,
-6.97888536964718,
-57.2053622635109,
-7.59149018702844,
1940.74883722613,
13776.3994355061,
59688.9506688118,
198967.267063524,
554664.181209208,
1342679.76760535,
2880718.85057692,
5556233.09746906,
9746453.11803942,
15705233.9839578,
23444873.7106245,
32630213.4195304,
42473186.150293,
51604301.4143779,
57950838.5609574,
58814629.2970318,
51670532.360853,
37073253.8293895,
31112689.7825927,
166639899.499491,
2285908471.65836,
-142300999941.473,
0.239462332088407,
9.7006247266445,
24.6796376740648,
-621.977746808668,
-6061.14667092794,
-28846.5231563469,
-92974.9043842097,
-229420.907671922,
-455750.587752974,
-720917.683643727,
-798268.858897086,
-142553.959799974,
2227938.90487962,
7722331.28668364,
17902944.5216494,
33799508.0633365,
54727373.5621622,
76699837.6804652,
90928852.1062459,
83791368.1450994,
41369883.2049391,
-33644574.3006822,
-51466205.6969009,
728822186.855893,
12613725489.8081,
-779054232341.425,
-0.531163176360929,
-9.62133388925249,
83.5858879354598,
1749.74435647472,
10388.878276731,
29739.3251394829,
27228.8352302813,
-137459.132798184,
-797275.579291472,
-2522656.85139472,
-6002370.79311501,
-11564879.4570243,
-18293067.3260108,
-23137574.7865943,
-20926214.0959888,
-6386212.74814566,
20947334.9587757,
49084025.5298454,
45674483.7892477,
-43357709.595878,
-274284042.960864,
-630264236.584573,
-707988499.827136,
2768071791.46789,
55323323631.9224,
-3346981844559.16,
0.843274592042774,
1.85634928776026,
-303.233463115877,
-2964.77206695662,
-8035.18601516459,
26623.9135533587,
296203.748735318,
1300209.48867761,
4002931.81502221,
10154091.5309971,
23011763.2727463,
48484290.5041288,
96405481.1482104,
181157702.817844,
319621265.640707,
523128884.608782,
780656497.356576,
1034030709.78307,
1153235261.31943,
934435310.723166,
172736683.699636,
-1059296923.94426,
-1259513524.21048,
11540211151.7843,
202982012848.938,
-11765811129127.3,
-0.971763767126055,
20.7278527481909,
599.216068887268,
2508.62108313741,
-15799.3976275259,
-190836.337882638,
-873333.216664437,
-2412364.04114457,
-4372947.5863571,
-4280053.82275206,
4581124.92368874,
37692021.4517723,
125690565.165227,
317577060.569135,
672918414.800248,
1235540175.83018,
1981789079.14886,
2741889556.9801,
3118003228.13883,
2478792089.71153,
201910662.627241,
-3440015764.71965,
-3701941985.52277,
36624484882.9033,
631340208742.919,
-35016783929182,
0.465205915130579,
-62.4878848976034,
-713.029716677298,
3463.89852940917,
76620.1536606951,
425050.797698706,
1098749.49892239,
830042.192958006,
-3609253.07165929,
-14019647.104919,
-22008231.8565183,
2879363.57573307,
127763068.732814,
471678257.276824,
1199156009.13846,
2449442490.02104,
4177372240.464,
5937970631.74612,
6701001745.26596,
4850964750.68393,
-1252857624.6872,
-11008101341.7195,
-11613916592.1703,
99208893729.6641,
1723996766015.73,
-90686535774445.6,
1.35055309427014,
109.632652005803,
-15.551388984273,
-19110.1792293505,
-151248.805892165,
-326520.136900253,
1323004.57105885,
11263794.9628682,
40182893.7043995,
99473459.937714,
213007606.45782,
462071289.943091,
1036322096.46886,
2233228139.73472,
4392262214.22542,
7778537815.0104,
12326926829.6142,
17068944624.2195,
19342475640.096,
14633223559.5287,
-1238504576.84042,
-24780929364.4666,
-19774890981.5309,
267278604099.047,
4262049717379.08,
-209109831966511,
-4.90254965773785,
-106.16559587471,
2473.32253262609,
39971.9971896279,
105932.466006557,
-940508.183476386,
-7972770.02131952,
-26249511.2854385,
-38016600.0226778,
28952783.4114192,
296603175.897931,
921440155.664983,
2211825458.1676,
4873052470.30472,
9959226055.61093,
18095018536.2409,
28333607390.4192,
37736361000.0061,
42033152625.5253,
35930405200.4038,
11674689966.7752,
-38568497842.5504,
-74929319913.8016,
440819854424.984,
9367147142753.47,
-436516234054193,
9.21654006976202,
-53.4970979572424,
-6659.50032530198,
-38474.8203617517,
310488.103734294,
3845463.04045484,
14525744.8285833,
14191442.4974447,
-71954549.6112557,
-299246254.252719,
-416148031.634689,
348026958.617362,
2939406987.4056,
7971636742.33878,
16399104338.5733,
31135394894.2163,
55589206993.0977,
84773664582.7313,
93124980530.7634,
37204300253.4301,
-100809540619.219,
-211523088540.365,
124648961402.01,
2454987217464.61,
23136880987249.1,
-833737986871973,
-10.6044400547848,
457.68066225078,
9572.011521514,
-37331.5997372033,
-1178378.58119297,
-5650741.83842416,
1857995.74642602,
109904372.796869,
458568718.1367,
915187897.2047,
811019172.09732,
92558199.5987161,
1998081069.83546,
13128498122.3811,
36243363277.9486,
61424177454.5951,
73667085976.0338,
86031421495.4807,
166947042118.509,
384532819727.471,
591661667761.69,
78943846328.2111,
-2527580012466.73,
-6916515802327.55,
21469457257461.8,
-1.4991232719638e+015,
3.17664940253603,
-1029.70926107305,
-5007.37894552437,
206353.644207492,
1762192.60826409,
-794281.059186644,
-59885497.7612809,
-267968880.144224,
-316522642.887633,
1411438830.94685,
7247583561.26104,
15913831315.8407,
19845848486.0143,
17971388397.4505,
42579150295.9815,
155992918698.532,
356278537036.23,
414110925668.561,
-161408422221.427,
-1685255831372.5,
-3094542673159.69,
-53087024607.4896,
16845038275179.6,
63212141053606.3,
202776604073488,
-2.43199634134677e+015 )
}
if ( (power>1.4) && (power<=1.5) ) {
grid <- c(0.52272502143588,
-2.37970276267028,
-4.50105382434541,
2.01559335438892,
26.7080425402173,
53.1211365756307,
56.5864772151065,
83.6551659699119,
218.128756577377,
414.067827117006,
586.302276594556,
925.084114296478,
1629.94052297329,
2248.04335981282,
2325.84860904575,
3056.70827313074,
5936.34902374365,
7512.68000065931,
-494.046409795432,
-14632.889451627,
2555.32119471521,
103793.057384242,
239732.321730146,
57045.261742077,
-1151133.66663602,
-3657091.74594141,
0.775913134802564,
4.5833536253197,
-6.51027140852265,
-110.820592889565,
-302.27161508231,
-170.893952600532,
597.013908647114,
1036.46479866453,
362.328670850611,
1143.67350470972,
5427.58842419152,
7481.1938127866,
3916.80746756334,
10919.4206700089,
37992.348893648,
35578.2283061684,
-48344.4290328334,
-70796.935934355,
307989.153472163,
965852.855353596,
280146.00264422,
-4462973.64355295,
-12247413.3846698,
-7748551.19364459,
47938914.6705982,
196377667.248434,
-1.15101738661085,
-3.82183996501946,
79.2652077448879,
447.712841790259,
183.895349671323,
-4007.2875514913,
-11554.3202406694,
-11119.3558179111,
-3321.49044452746,
-24694.4788687522,
-79648.9320167266,
-73209.1251877769,
-2021.74771903288,
-154892.733325762,
-580785.160917161,
-291546.650641339,
1473778.38160541,
1519601.02525224,
-7163122.30868759,
-21848349.4729583,
-6440961.41109336,
106830967.379257,
319671808.797567,
306212673.299803,
-944079002.967604,
-4580578568.46053,
2.02189579962441,
-10.0772337050698,
-303.024532759887,
-704.351532760201,
4973.76150820855,
26142.4723427423,
31405.9126438149,
-53806.275525627,
-149359.118457136,
16092.9360420975,
206115.379917112,
-509055.061292639,
-1505746.99603438,
440398.507094803,
4047882.74286314,
-3759763.21945456,
-28362810.7587706,
-20497981.7777362,
115049844.871681,
326041126.501133,
57527117.4877412,
-1804448247.28013,
-5607533850.24561,
-6742827026.7323,
11967660233.3111,
137394861109.439,
-2.64873193579361,
68.3499218097747,
718.463817413271,
-1571.25771413107,
-28554.9807730767,
-66684.6392549349,
112682.126175196,
683976.718235879,
693804.971402528,
-977072.064073228,
-991329.886033511,
5636906.19208592,
7342984.59011112,
-20840829.3577062,
-49193222.8209866,
42836025.7323296,
238149829.126778,
-55474045.455026,
-1800027569.31187,
-4174218574.22397,
-583545105.082449,
22566852342.6238,
72170080841.219,
99488552940.42,
-95607027136.1,
2344789183218.79,
0.265173429404147,
-224.175784222991,
-799.783571636822,
14465.1992899084,
83422.4433648738,
-33747.4954822623,
-1182034.20503755,
-2562724.00673901,
1327150.31866679,
9096932.76169983,
-8147841.7628163,
-67997474.423206,
-84381101.1698542,
1167786.45920554,
-290262963.143079,
-1966559598.21217,
-4495910335.48392,
-2778049317.5256,
9570853857.51408,
20045770280.4768,
-39053969152.1498,
-304481715916.404,
-861160659351.957,
-1248601137158.62,
1149200212746.68,
152670892302636,
12.5290983345227,
499.005760177699,
-1884.50478980683,
-52292.5606105439,
-102007.716028595,
974234.695542423,
4265255.61960463,
-518423.706368479,
-37847638.3377804,
-94994579.0086004,
-141430225.033227,
-554077045.707268,
-2621090414.90387,
-7585723619.93884,
-14489129113.1742,
-23451598610.8142,
-52316888100.9028,
-154472187133.545,
-386170628207.441,
-654732126120.445,
-458996711714.355,
1207352849976.42,
5003368112913.01,
8162669646404.62,
10014475965674.9,
4.30099151054367e+015,
-49.3184821796504,
-659.190055418151,
13760.6854640598,
117281.576980704,
-286688.694056081,
-4514692.65697881,
-11833557.5599173,
-13306480.8841683,
-177569989.290577,
-1501492416.77122,
-6595461136.24562,
-20356400466.8674,
-54254546277.6263,
-140855615592.576,
-350477425656.988,
-772978728940.34,
-1445553693725.57,
-2349378847823.61,
-3825995343158.07,
-7818306940077.94,
-19731827478910.9,
-48657002077699.6,
-98504762092397.2,
-121989778390269,
454260903660862,
1.09114573020388e+017,
123.410260081819,
-197.403953092516,
-40101.3176876088,
-52951.2659905612,
2144698.8673286,
1739654.2351533,
-141996380.772718,
-1289342757.59316,
-7156566175.76133,
-32325427550.7015,
-126169094996.878,
-419281859332.1,
-1174950784066.64,
-2822039940568,
-6037668177832.46,
-12096555834995.5,
-23612374044250.6,
-45167080717259.5,
-82416904456952.1,
-138051430229770,
-204193982413479,
-251800695384389,
-208815124278779,
288829117097310,
9.54395313223954e+015,
2.24604455857544e+018,
-210.739560523616,
5859.20505890453,
140328.667144469,
278664.828817554,
-10534350.9218635,
-206287796.083656,
-2616524539.48725,
-22630598386.6276,
-138968736141.657,
-644711350455.876,
-2387358710732.05,
-7357036386363.44,
-19420572655537.7,
-44732883747785.5,
-91030332840422.6,
-165757883253373,
-276320429460859,
-441737780262524,
-728934745124743,
-1.31361122221926e+015,
-2.49168560525055e+015,
-4.31067214964099e+015,
-4.70964682712407e+015,
9.73624002713054e+015,
2.04847011281059e+017,
4.09466705815479e+019,
278.504340481087,
1227.95202954615,
609240.949141676,
8398669.53224352,
-122964349.27965,
-4120134389.77069,
-51789735957.0207,
-413475908382.113,
-2400754425461.51,
-10787324023927.9,
-38888467331936.8,
-115207923139742,
-285196579464986,
-596235892662438,
-1.05638430488185e+015,
-1.57370592252881e+015,
-1.90815996658209e+015,
-1.68347182504384e+015,
-470951786697564,
2.27515760918722e+015,
8.65004127903261e+015,
2.98774925717651e+016,
1.1577555109681e+017,
4.88806957320561e+017,
3.5377171188424e+018,
6.72365027054536e+020,
1302.48019924681,
259560.540734449,
8128828.4793897,
25490162.9304377,
-3094217693.64666,
-72611077275.6044,
-860362188931.341,
-6697568428379.51,
-37943648370441.8,
-165469263635562,
-574639366352108,
-1.61975362474037e+015,
-3.72208462865178e+015,
-6.84085667350701e+015,
-9.24907873336246e+015,
-5.63230537269553e+015,
1.49215241150529e+016,
7.00536184155271e+016,
1.84186220493898e+017,
3.92386129591378e+017,
7.72461936211387e+017,
1.59366458882732e+018,
3.85548874292868e+018,
1.14456878085735e+019,
5.75359458832251e+019,
1.02900591814312e+022,
13286.5118009426,
2546171.88500447,
80098454.5079186,
-575521939.430233,
-60032299026.9678,
-1202606432540.75,
-13452077960416.8,
-101362184753825,
-559725106993583,
-2.37495806056525e+015,
-7.95202306660676e+015,
-2.11888175159205e+016,
-4.40669841594096e+016,
-6.47957726367261e+016,
-3.24083222588877e+016,
1.83291719462516e+017,
8.40260894845939e+017,
2.37093537889737e+018,
5.4317336077623e+018,
1.10375221140593e+019,
2.11436475962051e+019,
4.09291799720987e+019,
8.65527998606027e+019,
2.14451316905219e+020,
8.54313682198285e+020,
1.49594792908599e+023,
203942.274027855,
26468105.5883892,
462332761.175384,
-25284736506.3552,
-1094062620100.06,
-19258710333321.7,
-203938699172942,
-1.48348319911623e+015,
-7.94195851466556e+015,
-3.25428940850727e+016,
-1.03863076023785e+017,
-2.5561068913892e+017,
-4.48713805903153e+017,
-3.40534549726198e+017,
1.18853947957601e+018,
6.7824313161356e+018,
2.1555870304696e+019,
5.41093701368525e+019,
1.17698643723088e+020,
2.32697280763342e+020,
4.35104831467264e+020,
8.06863397336643e+020,
1.57397090527128e+021,
3.47588746977727e+021,
1.24037541169807e+022,
2.082483901283e+024,
2425722.75874371,
168829967.462896,
-6124967796.72205,
-684794159351.057,
-20099159890195.9,
-312088468164664,
-3.08510744950999e+015,
-2.12874367646947e+016,
-1.08016089267394e+017,
-4.13278775037366e+017,
-1.18371276048634e+018,
-2.32798990878473e+018,
-1.62965158901462e+018,
9.87177193402913e+018,
5.68548659646942e+019,
1.93636952907764e+020,
5.21964303390126e+020,
1.21047675802231e+021,
2.51556116094745e+021,
4.81371375246211e+021,
8.68998842506269e+021,
1.52222181674142e+022,
2.68233759254245e+022,
5.09349061051762e+022,
1.81405407714602e+023,
2.73961792646156e+025,
18727182.1067274,
-3856365344.26257,
-418983873891.394,
-17333732195464.3,
-378965106591800,
-5.04766648385378e+015,
-4.45572615875926e+016,
-2.73473979347584e+017,
-1.17835431873962e+018,
-3.3155488196652e+018,
-3.27497940087677e+018,
2.43638130489573e+019,
1.80581815169857e+020,
7.62727068811908e+020,
2.48326825663032e+021,
6.79744241369944e+021,
1.63174880753305e+022,
3.52624193788357e+022,
6.98893205641466e+022,
1.28897681504313e+023,
2.23908254454823e+023,
3.69904872503628e+023,
5.82169304070961e+023,
8.85953055589028e+023,
3.25024671656323e+024,
3.52294080805527e+026 )
}
if ( (power>1.3) && (power<=1.4) ) {
grid <- c(0.897713960567798,
-0.47040810564112,
-1.43992915137813,
-5.23984219701719,
-15.0352102570745,
-13.4481420654518,
87.0680569141198,
319.051289202574,
-18.4506632683117,
-2319.89441748794,
-3118.4617838911,
13713.8934655348,
46257.8044960381,
-39135.1988030987,
-498172.85786169,
-811816.300243115,
2568821.88452726,
15957456.1105785,
30538856.3230172,
-38265076.8403202,
-445019432.131326,
-1535324610.183,
-2685571226.57687,
1844994500.64329,
33799853247.9255,
148548951511.487,
-0.0411924170235428,
-0.280923312875219,
1.85631524787589,
35.4548526987637,
182.842029466341,
186.535484241998,
-1885.62536085722,
-7050.5577782269,
3914.68802807428,
72775.307234475,
81966.2319220996,
-546556.025881189,
-1736496.33116182,
2018406.08511184,
22431395.8530421,
38371009.900033,
-121432141.656335,
-823775133.379304,
-1829474775.72627,
1064685431.79,
23026018217.409,
92967101827.417,
209244156825.792,
108176144299.254,
-1494179320052.26,
-8820798547246.88,
0.335385258677322,
4.50345806518915,
10.608217004451,
-198.77147800601,
-1523.07566142071,
-1500.09456259484,
23139.2326521245,
83055.2779182394,
-113519.71875397,
-1189391.83133768,
-880016.414378636,
11594447.2485996,
32944023.5477499,
-57906962.3154716,
-530418894.202135,
-898586763.98809,
3160587598.72435,
22164670922.5832,
54438271034.5952,
-7405444239.37665,
-615716148031.174,
-2843896714598.56,
-7637460249121.44,
-9706633868213.88,
27251052973973.8,
220225910667289,
-0.792263177969423,
-21.2045420582639,
-91.4401569487452,
1101.7598394385,
10118.5419251243,
5726.65994681374,
-215851.229167288,
-669893.217282033,
1905585.55556376,
13591395.7207961,
2340171.0149139,
-169616173.653862,
-405049039.820392,
1178374485.90503,
8651034672.11598,
13041124217.199,
-63654520224.3913,
-427730047807.293,
-1124157151846.8,
-274204341784.276,
11179066056046.7,
58371933813335.8,
179156520740047,
326715205946158,
-110966263637577,
-7.30089254118998e+015,
1.98088010280869,
88.7205095644789,
451.25451837431,
-6238.38424401488,
-56974.0505836968,
23643.1529279025,
1692687.00100628,
4116879.50794305,
-20945171.4628138,
-107415978.096988,
132557253.129546,
2070091722.93035,
3657706483.5209,
-19429026052.7314,
-118401385300.158,
-176359135255.114,
835686139242.973,
5703797966574.08,
14884329900045.1,
-552681886101.364,
-188818869070189,
-1.00878535432539e+015,
-3.36911029646898e+015,
-7.50185785257662e+015,
-5.12493009299165e+015,
-1.75430627966896e+017,
-6.01808947590792,
-358.631844263425,
-1646.82372824411,
35116.9756113627,
280756.645438638,
-507546.635114422,
-10020156.6805911,
-4945705.75502759,
272336260.80756,
1104711765.97144,
-568290834.123902,
-14088675880.1234,
-12950574108.0922,
210192537963.341,
859065438623.435,
-747462235105.65,
-20708041247987.7,
-104755203973610,
-298469477349205,
-363165453972938,
1.27630293527266e+015,
1.00317977358032e+016,
3.80411831558389e+016,
9.62493626170414e+016,
1.15786608399486e+017,
-1.03118547220491e+019,
22.952229421138,
1405.69142020857,
3967.15419654569,
-181648.014611196,
-997642.253786536,
8248812.38538573,
91248769.6906494,
269940828.639906,
457556637.301566,
7822037651.92945,
72574078872.7822,
285799266923.8,
186491437806.251,
-3589451347123.35,
-20096636648266.9,
-55011152917522.8,
-75141293052079.6,
-68199466557531.5,
-1.03828417550274e+015,
-1.01420393701492e+016,
-5.89973268530095e+016,
-2.54452415456125e+017,
-8.83842320399224e+017,
-2.50090967000384e+018,
-5.75293047799529e+018,
-3.0288264126223e+020,
-99.9878158346858,
-5210.49423696155,
4761.55706178008,
1014983.38061518,
6678222.58484158,
18138060.5674288,
523215144.725566,
8388725586.42611,
65308743699.6125,
317410830648.742,
1134002934158.94,
3498250050884.25,
9275186197008.01,
5168202521004.28,
-177786455579982,
-1.541966007589e+015,
-8.17352077554882e+015,
-3.26417185677986e+016,
-1.04838259404326e+017,
-2.78718323122462e+017,
-6.27055158391557e+017,
-1.27711947908717e+018,
-2.98493427948817e+018,
-1.08753143842026e+019,
-6.81489155059389e+019,
-7.09103794715832e+021,
445.7016632619,
18118.8922546317,
-59575.916393475,
-1546683.20227499,
66577416.4833025,
1581334778.6952,
18270427567.616,
159620726230.676,
1179819333919.81,
7136701581206.33,
33141064579502.4,
108828204724357,
187282794130913,
-416027319900596,
-5.25364928574569e+015,
-2.85113559834757e+016,
-1.22522620595716e+017,
-4.79778248465207e+017,
-1.80908798010203e+018,
-6.6584955339892e+018,
-2.38169794720652e+019,
-8.23438092498963e+019,
-2.75142145405642e+020,
-8.98926942417278e+020,
-3.30676128118007e+021,
-1.39506678075182e+023,
-1872.21347826633,
-46283.567888389,
1588637.59435705,
58147592.3245715,
1251197774.35208,
23222717220.2576,
321130227736.287,
3181320366971.15,
23454746025596.1,
134242541498815,
608809039493410,
2.13579959983314e+015,
4.94319739507647e+015,
-642441041478663,
-8.45372610438658e+016,
-5.78902547364894e+017,
-2.75526324472539e+018,
-1.0840919422109e+019,
-3.76905193553513e+019,
-1.20991644215191e+020,
-3.73703358932369e+020,
-1.16027081029794e+021,
-3.77617115231973e+021,
-1.34025753565226e+022,
-5.99737264585084e+022,
-2.43233695351887e+024,
7556.65517982232,
215106.469973897,
8930450.66728664,
660119294.92026,
21206807863.5722,
398339343315.102,
5190034087210.52,
50568961091221.7,
380791925478234,
2.24722396598682e+015,
1.03784283558222e+016,
3.62656117204867e+016,
8.1707753418827e+016,
-1.42136634601931e+016,
-1.3434681243398e+018,
-8.98526482243229e+018,
-4.27270839102888e+019,
-1.72138580695355e+020,
-6.27800609966133e+020,
-2.15417480180286e+021,
-7.16024766698911e+021,
-2.36639068137229e+022,
-7.98151888085422e+022,
-2.8511432263888e+023,
-1.2325305554076e+024,
-4.09104391632781e+025,
-22430.9879586296,
1389052.54923454,
207349675.587708,
10195666599.2626,
296796553336.983,
5643928776333.53,
74892895567209.3,
732432041468099,
5.49414382342695e+015,
3.23706890283122e+016,
1.50367841248151e+017,
5.32587551175168e+017,
1.22108658524644e+018,
-2.40776349600474e+017,
-2.10569831857027e+019,
-1.42079098762757e+020,
-6.7576612032549e+020,
-2.69444367649145e+021,
-9.63469651591202e+021,
-3.22501888704947e+022,
-1.04839963336164e+023,
-3.43153835335537e+023,
-1.17225158559623e+024,
-4.36196591662948e+024,
-1.98653397314499e+025,
-6.88448478890627e+026,
113277.793293176,
18517911.460342,
2450455304.46694,
133732757996.437,
3939467103342.68,
73996025955050,
973922420426797,
9.51229943083948e+015,
7.14628383239514e+016,
4.211386770595e+017,
1.94758654233723e+018,
6.79901662283943e+018,
1.47957074222858e+019,
-9.95844999508158e+018,
-3.10086406715516e+020,
-2.02215387815306e+021,
-9.57663684541226e+021,
-3.84223024829774e+022,
-1.39073983190476e+023,
-4.72891356250685e+023,
-1.5634530908607e+024,
-5.19829965024042e+024,
-1.79911666610008e+025,
-6.76349804228038e+025,
-3.07798865328979e+026,
-1.20960393431303e+028,
262418.415973756,
250096978.583001,
31172920464.8184,
1642871008200.88,
48188034311242.9,
904074332252990,
1.18607968360778e+016,
1.15420861185206e+017,
8.6517873709592e+017,
5.09510325906077e+018,
2.3530063632105e+019,
8.13726112964088e+019,
1.67367130237733e+020,
-2.20436191917162e+020,
-4.39432362856901e+021,
-2.78056375326784e+022,
-1.30625919423068e+023,
-5.22563427007622e+023,
-1.88958355853632e+024,
-6.42962247956913e+024,
-2.13314085393945e+025,
-7.14689344739656e+025,
-2.50319784231518e+026,
-9.53595733424881e+026,
-4.39966873221631e+027,
-2.25020366975876e+029,
5301456.42169776,
2874720507.00564,
367880928787.512,
19643816240801.3,
579437137354404,
1.09310772186823e+016,
1.44543936097009e+017,
1.42253933395633e+018,
1.08266855728833e+019,
6.5042335654303e+019,
3.08534291740846e+020,
1.11258933788151e+021,
2.54876590864897e+021,
-1.16381734289056e+021,
-5.15203133618314e+022,
-3.49775856982996e+023,
-1.70121626254362e+024,
-6.97428046783589e+024,
-2.57225393421212e+025,
-8.89902171064717e+025,
-2.99264095778419e+026,
-1.01251337109722e+027,
-3.56015066420899e+027,
-1.34824053722105e+028,
-6.3098335548906e+028,
-4.46843594631534e+030,
51969153.4318949,
37970527243.0619,
5016911719944.11,
280591474635532,
8.66499271311873e+015,
1.71435134742076e+017,
2.38968675963669e+018,
2.4977218053678e+019,
2.03817113129374e+020,
1.33075091271939e+021,
7.03087446839742e+021,
2.99159383585797e+022,
9.87178121143328e+022,
2.15294869859065e+023,
-1.70137308294605e+022,
-3.20794310177486e+024,
-2.12464634368172e+025,
-9.96697641227305e+025,
-3.96959854025141e+026,
-1.44146335908902e+027,
-5.00266337924097e+027,
-1.73044335238055e+028,
-6.20780217337989e+028,
-2.41346445464175e+029,
-1.2385425771224e+030,
-9.58840383704782e+031 )
}
if ( (power>1.2) && (power<=1.3) ) {
grid <- c(0.959582735112296,
-0.196662499936635,
-0.301224766165899,
-0.502046137683381,
-1.5895374772965,
-7.89601110410117,
11.3307142810595,
762.363953933895,
7332.01631877668,
29138.4582145098,
-76339.1153989754,
-1796970.2346991,
-11726396.1851003,
-33450515.2165733,
98652180.9916008,
1769595410.03626,
11618980670.3263,
49132193375.8717,
121727250506.162,
-108084821334.712,
-3366026267162.29,
-24251373433568,
-125561039968382,
-532052675965940,
-1.87778088137625e+015,
-5.20253340562286e+015,
-0.0117920451301422,
-0.0865135588789834,
-0.305001740311124,
0.805339553985313,
45.1127229820372,
543.393289708699,
2052.1244600063,
-23479.8112741772,
-378633.827624817,
-2160148.0589237,
-71997.7261576385,
94765697.6597504,
790575791.875542,
3071423100.48738,
-1263803153.75136,
-106897577346.909,
-858303914821.876,
-4302053589524.5,
-14378154556128.4,
-18792439949861.5,
158250693996112,
1.65848181037028e+015,
1.01561192369251e+016,
4.93870814001288e+016,
2.03707862081918e+017,
7.32155754220541e+017,
0.0276487092578896,
0.273727106195384,
3.10493645078303,
6.74883014953071,
-791.517414710189,
-14659.1601086036,
-97513.5598522334,
253826.352485024,
9659750.39303433,
72426555.4027922,
108077398.518517,
-2603530107.50454,
-27142206424.4266,
-129010093038.665,
-115592228710.678,
3373975177466.36,
33069166217378.1,
190970279120807,
775088407219876,
1.95531526988697e+015,
-1.08844022433567e+015,
-5.03041904941278e+016,
-3.88737032793942e+017,
-2.17996177307102e+018,
-1.03733702308722e+019,
-4.56687817243336e+019,
0.00460342184603284,
-1.4191835457503,
-61.0896531126379,
-722.851866770932,
5719.49208464532,
231804.146910697,
2166106.69539304,
160219.206657996,
-174724415.264779,
-1623587498.26411,
-4008185392.86052,
51909707843.9719,
660864914267.222,
3692989887945.52,
7286367447296.07,
-66279529836476.3,
-829978185197398,
-5.3925210853509e+015,
-2.46096213563743e+016,
-7.65535837790057e+016,
-7.14762806859001e+016,
1.1170095179102e+018,
1.09817546139889e+019,
6.89213311167972e+019,
3.45878357931231e+020,
9.50469739120499e+019,
-0.135631224023216,
9.82565018790751,
752.94430372433,
13626.2467481671,
2250.45356087176,
-2801646.63778468,
-34431818.5075219,
-60859775.5058763,
2414520669.31045,
26210017396.4224,
71434279662.7282,
-950461823661.22,
-12870038897298.3,
-75651275138190.2,
-153087109622533,
1.57838782399087e+015,
2.08458508751872e+016,
1.47352057035772e+017,
7.65309425661461e+017,
3.07056896036942e+018,
8.78357943721663e+018,
7.63366506587975e+018,
-1.20231415827737e+020,
-1.19381796423493e+021,
-8.4234840567679e+021,
-2.34505645250979e+023,
2.86398306366288,
4.76124711367818,
-6457.28547283359,
-164758.27150296,
-589766.226217846,
28067458.5191206,
401139336.264519,
416911989.44211,
-40222720768.9054,
-459374207097.421,
-1682302721723.89,
12458076906678.7,
216651931418543,
1.51961566257658e+015,
5.4584519020853e+015,
-5.19685396766197e+015,
-2.27022332259378e+017,
-1.85664800967564e+018,
-9.86237368369173e+018,
-3.61931853333836e+019,
-6.07700089132706e+019,
3.81186434434807e+020,
4.88459347203027e+021,
3.36478940057831e+022,
1.56888688507016e+023,
-1.17704898582546e+025,
-30.8405895817803,
-700.185732152437,
47091.7507004153,
1596708.4034919,
7159288.38315759,
-321689179.440809,
-5431369518.38533,
-21502235882.8679,
277109738167.276,
3653526301164.72,
5678876796467.48,
-241265821098598,
-2.84217859105037e+015,
-1.41758365590388e+016,
1.445542591378e+016,
9.32012909683014e+017,
9.89863985847271e+018,
7.14065483941308e+019,
4.10045064062402e+020,
1.97534191394671e+021,
8.07769891709407e+021,
2.70685067720764e+022,
6.02927395033448e+022,
-9.22337544984228e+022,
-3.1648353300078e+024,
-5.61603302303069e+026,
250.323709544488,
8545.64176293525,
-338614.039444803,
-14362564.9062655,
-92763398.7027217,
2174220601.06076,
29854756860.9811,
-212387816186.495,
-8028244379539.38,
-76503721502058.2,
-140612055233030,
4.75984421187865e+015,
6.87179074752808e+016,
5.46755810778416e+017,
3.00178419969484e+018,
1.15075325799871e+019,
2.56621820643217e+019,
-9.99967497065107e+018,
-2.40812092499658e+020,
1.000269417608e+021,
2.80929218333346e+022,
2.76237750806896e+023,
1.92887184219875e+024,
1.03524743837727e+025,
2.54120088308415e+025,
-1.67374835060249e+028,
-1788.89737939434,
-72709.9323496133,
2484233.26866509,
105824573.878487,
46058548.2567914,
-41008709091.9079,
-661049991528.956,
-2869882451384.02,
34629600071672.9,
584592196626057,
3.85506398038373e+015,
1.85280581626924e+016,
2.40594389635909e+017,
4.39015768159735e+018,
5.68500042585068e+019,
5.46101970218862e+020,
4.19859227844407e+021,
2.71529223079585e+022,
1.52448364339692e+023,
7.57284365298019e+023,
3.350130760701e+024,
1.30047897758996e+025,
4.0904969542102e+025,
5.75746965876781e+025,
-8.76067257210248e+026,
-4.18601579421029e+029,
12278.7581956566,
496755.477226686,
-22174016.5110608,
-982354213.175663,
-7651083547.2257,
74418384151.9456,
-158221447812.226,
-43635118674338.1,
-493258537684304,
3.84848286761028e+015,
1.75887871994533e+017,
2.68669123829776e+018,
2.71502811657687e+019,
2.09549316384593e+020,
1.32297232667709e+021,
7.18370559114638e+021,
3.53542513917885e+022,
1.68168650207952e+023,
8.25241080182299e+023,
4.30466100873181e+024,
2.32738116938991e+025,
1.23477038775956e+026,
6.04371816144202e+026,
2.416150272357e+027,
6.92811011890208e+026,
-8.30613806320748e+030,
-79244.2377537492,
-2985145.62680809,
144884969.0038,
3426964337.87191,
-120514004452.734,
-4568263757378.07,
-41894084093912.4,
490584024082356,
1.9241818444463e+016,
3.11732137423038e+017,
3.73577725478084e+018,
3.90759600611774e+019,
3.77869191059759e+020,
3.36829721948857e+021,
2.71562326419553e+022,
1.95921942858408e+023,
1.26492353680313e+024,
7.3517449416279e+024,
3.87469051660304e+025,
1.86123499753071e+026,
8.13297579530344e+026,
3.16817378492111e+027,
1.01489843927767e+028,
1.5807400240241e+028,
-2.021313503304e+029,
-1.45957971542625e+032,
521788.722135468,
9472176.27503808,
-1834442451.42211,
-67207743391.7279,
-811715015878.492,
-2843970947585.28,
171797242776594,
1.07249545636155e+016,
3.34114929712701e+017,
6.59909611038221e+018,
9.29872040038554e+019,
1.00743611185641e+021,
8.83945953164831e+021,
6.53568861391816e+022,
4.21089667672736e+023,
2.43823913494771e+024,
1.30691447936152e+025,
6.66339503265359e+025,
3.30039394627076e+026,
1.60447868150269e+027,
7.63096240611393e+027,
3.48620982415311e+028,
1.46850577313574e+029,
5.0140288773257e+029,
-3.94001569880189e+029,
-2.26766193173512e+033,
-2825375.34945871,
-61496352.0334524,
2493173658.3079,
-333237181754.782,
-18996407047060.9,
-185565155812803,
9.2705029708914e+015,
3.99039220138775e+017,
8.61232487663729e+018,
1.32051416047768e+020,
1.60969350838808e+021,
1.6490151337151e+022,
1.46466548357974e+023,
1.14951997029669e+024,
8.07500862310061e+024,
5.1281421080201e+025,
2.96949619046387e+026,
1.57946761642313e+027,
7.76011998009655e+027,
3.52921742493438e+028,
1.47769012971021e+029,
5.55807112615323e+029,
1.72069255611094e+030,
2.45634325498066e+030,
-4.33879732862619e+031,
-3.40784734034525e+034,
17658315.6693612,
-1121888367.87085,
-181270807554.95,
-7242038986871.72,
-120082281227313,
2.31291589803502e+015,
2.20848277428698e+017,
7.48543822457755e+018,
1.61954010343843e+020,
2.55218480608558e+021,
3.13237500947909e+022,
3.13138431695314e+023,
2.6379745983487e+024,
1.92552803357783e+025,
1.24720050890185e+026,
7.32106996964179e+026,
3.9678324994807e+027,
2.01741972525514e+028,
9.74388679831022e+028,
4.5059355340519e+029,
1.99801024333608e+030,
8.4241281541234e+030,
3.28635082828553e+031,
1.06272567840542e+032,
-2.16825023052698e+032,
-5.26834661824363e+035,
-48488127.6322903,
-9941368958.95411,
-1701495949545.85,
-115729090727230,
-2.46271860575519e+015,
5.70594335232465e+016,
4.91770401202199e+018,
1.54976753508251e+020,
3.17533901633655e+021,
4.84563283115304e+022,
5.87562438473976e+023,
5.8931457323464e+024,
5.03145371691109e+025,
3.73914198714188e+026,
2.46316680755782e+027,
1.46055114567583e+028,
7.89759555011506e+028,
3.9367543253666e+029,
1.82414003560443e+030,
7.89299615934093e+030,
3.18195160616357e+031,
1.17447804036354e+032,
3.74155783420197e+032,
7.41309337505642e+032,
-9.98125051400098e+033,
-9.74447097008623e+036,
575794042.269378,
-359696847349.006,
-46582766175582.5,
-2.5172826170398e+015,
-4.85788166089857e+016,
1.35929935720063e+018,
1.12759088306295e+020,
3.61755309466896e+021,
7.52761720304016e+022,
1.15671836837518e+024,
1.39982433553636e+025,
1.39034166332529e+026,
1.16802699889137e+027,
8.49867342754942e+027,
5.46129812043187e+028,
3.15144234524267e+029,
1.65678656217278e+030,
8.03580116507344e+030,
3.63383187207197e+031,
1.54337891859975e+032,
6.16359372138549e+032,
2.28426586046228e+033,
7.47381246679803e+033,
1.68250380067942e+034,
-1.71346139855961e+035,
-2.23719793136107e+038 )
}
if ( (power>=1.1) && (power<=1.2) ) {
grid <- c(0.989973425448979,
-0.111802566436515,
-0.128138198419178,
-0.144020752096856,
-0.156865568330961,
-0.139657194482135,
3.536695146237,
303.956020562169,
16971.561119878,
711511.636211499,
23703218.8754648,
650925619.121534,
15122827515.9695,
302907419807.887,
5300237420118.51,
81627637427388.5,
1.10626268382253e+015,
1.30088329870981e+016,
1.26350384665605e+017,
8.34748022753782e+017,
-1.48193266830101e+018,
-1.83141490787536e+020,
-4.36156639238075e+021,
-8.28126332215202e+022,
-1.08728181988638e+024,
-1.54431621438905e+027,
-0.00313462642593353,
-0.0388702138075973,
-0.0903770763700018,
-0.178015741979943,
-0.442864053335794,
-13.4654296356606,
-879.397544291817,
-44326.6781688309,
-1719945.84474206,
-52165024.459267,
-1245203281.74841,
-23434690273.4911,
-352258956554.21,
-4722829656798.21,
-83507513328313.6,
-2.39585027904263e+015,
-7.50927529719736e+016,
-2.07270273612729e+018,
-4.97162068932377e+019,
-1.06766044761913e+021,
-2.12429857352596e+022,
-4.05944617085845e+023,
-7.80448328338183e+024,
-1.62547597498508e+026,
-3.41127169961574e+027,
5.72214427762114e+029,
0.00507283741509471,
0.0611283656924362,
0.118275683282882,
0.0638053314994744,
-22.662058007833,
-2973.06775411472,
-243880.688361423,
-13804096.0539272,
-566905197.509389,
-17310061654.4572,
-391792916235.597,
-6189711302728.5,
-49123570530885.4,
601194433055370,
2.98825837615e+016,
5.47657960626698e+017,
3.5405751519937e+018,
-1.26138966768788e+020,
-5.9951048018011e+021,
-1.65556052103626e+023,
-3.74652939321509e+024,
-7.7582256629277e+025,
-1.58711907280473e+027,
-3.48648576340569e+028,
-7.77485808458045e+029,
1.03410922602955e+031,
0.000415849616352672,
0.0106967682516999,
0.158203224877345,
4.49743806433715,
-1145.2512510092,
-257762.508706388,
-25867475.247582,
-1637247291.63787,
-72907884189.7384,
-2409044555520.72,
-60655326006420.5,
-1.17024127884226e+015,
-1.69507534186056e+016,
-1.73353934726338e+017,
-1.19768287172967e+018,
-1.6925948580369e+019,
-8.40082861320748e+020,
-3.19703011126093e+022,
-9.01680307946117e+023,
-2.10464678914191e+025,
-4.37986494585875e+026,
-8.62023394900792e+027,
-1.70595448526874e+029,
-3.65540979450112e+030,
-7.98948970235937e+031,
-8.72229109997141e+033,
-0.000277296401191326,
0.00785581341291909,
7.70945326818073,
1047.85637415002,
12617.6081671164,
-11318694.4184715,
-1521632559.16444,
-109651752055.073,
-5365129636121.41,
-195049584142469,
-5.55257586362403e+015,
-1.28875628635706e+017,
-2.54416168432133e+018,
-4.52586741722226e+019,
-7.85882741468167e+020,
-1.43675527082477e+022,
-2.81191719043273e+023,
-5.63847556272856e+024,
-1.10380771755939e+026,
-2.06538042850477e+027,
-3.71079218491912e+028,
-6.55949719267708e+029,
-1.19216339970128e+031,
-2.37651568510983e+032,
-4.91119938960528e+033,
-9.19298686871738e+035,
-4.0453365352258e-005,
0.808120615148473,
462.33674259018,
75430.0290598068,
4331914.30073851,
-205449452.816475,
-53008737555.3822,
-4488085605111.43,
-241208396247575,
-9.50346382864154e+015,
-2.94900174959011e+017,
-7.58627631848485e+018,
-1.69435784683881e+020,
-3.4411087434676e+021,
-6.63519114738198e+022,
-1.2514488828429e+024,
-2.32881811283864e+025,
-4.24297462063675e+026,
-7.48476399731269e+027,
-1.27258719106238e+029,
-2.09917093736239e+030,
-3.42920519941086e+031,
-5.77122270489562e+032,
-1.06549974420896e+034,
-2.07816556556317e+035,
-4.87536422889045e+037,
0.00675158161047212,
30.709935211898,
17928.1999465246,
3251282.07045102,
259150408.193801,
4065970794.89839,
-1081487969698.15,
-120396596572924,
-7.24129443659267e+015,
-3.08345729970917e+017,
-1.02588642970565e+019,
-2.83199105144724e+020,
-6.79734935044741e+021,
-1.47579853708826e+023,
-2.99031990839464e+024,
-5.7671579517374e+025,
-1.06688395883241e+027,
-1.89309297237781e+028,
-3.21672741997238e+029,
-5.24303649293225e+030,
-8.26753906534395e+031,
-1.28566458271899e+033,
-2.0446711266049e+034,
-3.53884600906098e+035,
-6.61800844109463e+036,
-1.75572778206776e+039,
0.258679354840137,
840.360258770242,
507444.100015697,
99442112.1901258,
9368084176.4115,
380375494385.308,
-9258609923520.86,
-2.23106090141392e+015,
-1.58174211439346e+017,
-7.3607104165464e+018,
-2.61924232181302e+020,
-7.67289085556648e+021,
-1.94419837765708e+023,
-4.42140613397016e+024,
-9.26766241853947e+025,
-1.82037390050501e+027,
-3.37830777373629e+028,
-5.94348917058151e+029,
-9.9356636154327e+030,
-1.58518493151072e+032,
-2.43604478698234e+033,
-3.67029806957723e+034,
-5.60458388706875e+035,
-9.22449768201003e+036,
-1.6904092353277e+038,
-4.89465564411877e+040,
6.41800151101403,
18182.0558161604,
11380508.3514703,
2361269590.73996,
245103026658.95,
12999718384259.7,
144508294149080,
-3.1075671302527e+016,
-2.81566498473887e+018,
-1.44690887425048e+020,
-5.49152466538323e+021,
-1.692387361606e+023,
-4.47164792383022e+024,
-1.05093110630748e+026,
-2.25304900366832e+027,
-4.47763141879538e+028,
-8.32719512434137e+029,
-1.45736744448634e+031,
-2.41132989810688e+032,
-3.79399183745648e+033,
-5.72975750077454e+034,
-8.44163520665995e+035,
-1.2506421655368e+037,
-1.98161951684487e+038,
-3.63563587421314e+039,
-1.14232297834824e+042,
130.4805948356,
319626.889155575,
206944151.13871,
44870875123.7641,
4947555746666.1,
294990039461152,
6.86125098068619e+015,
-3.63786637655628e+017,
-4.49266130472303e+019,
-2.52923657396585e+021,
-1.01259704639731e+023,
-3.24472934374372e+024,
-8.83324503429516e+025,
-2.1213437136394e+027,
-4.60888186519505e+028,
-9.21064839386007e+029,
-1.71143638740235e+031,
-2.97850907929798e+032,
-4.88496458063687e+033,
-7.6009042549272e+034,
-1.13248736207305e+036,
-1.64007876899463e+037,
-2.37417054431763e+038,
-3.65864990028412e+039,
-6.84510916139291e+040,
-2.35049544393324e+043,
963.245715385098,
4945125.74645911,
3444934228.87347,
766212865526.459,
85513510174417.3,
5.0967420057197e+015,
1.1088205871047e+017,
-7.45318428114027e+018,
-8.70993014114392e+020,
-4.89483272136854e+022,
-1.96863338240187e+024,
-6.33450769555172e+025,
-1.72614090113824e+027,
-4.13046184681991e+028,
-8.89861663528251e+029,
-1.7563102367483e+031,
-3.21437889043872e+032,
-5.50329625743619e+033,
-8.87758069741474e+034,
-1.35900361585279e+036,
-1.99194876368027e+037,
-2.83400436317181e+038,
-4.01653931243524e+039,
-6.05394644066378e+040,
-1.16801065759799e+042,
-4.42572447936007e+044,
51233.824363294,
71261780.1129107,
41401713028.4753,
8934258413489.44,
988188857001118,
5.68035904215963e+016,
8.47175769846526e+017,
-1.32231153172396e+020,
-1.32772648545315e+022,
-7.30083365623776e+023,
-2.93724557054933e+025,
-9.51930409068657e+026,
-2.6176588474417e+028,
-6.31768365981176e+029,
-1.37023407131264e+031,
-2.71586983800496e+032,
-4.97904709617111e+033,
-8.52052408526674e+034,
-1.37148020128378e+036,
-2.09209859073969e+037,
-3.05157815956964e+038,
-4.31198694357118e+039,
-6.0516153334399e+040,
-9.04746158745842e+041,
-1.83089018411669e+043,
-7.85792264499214e+045,
-1497353.00381781,
723041183.21408,
798570121442.665,
179799692875761,
1.75400882707701e+016,
5.90805036793554e+017,
-4.49390336205661e+019,
-7.12757601895464e+021,
-4.99886165418825e+023,
-2.40376807666057e+025,
-8.92056369816489e+026,
-2.71249252736027e+028,
-7.02691152031126e+029,
-1.59610221811831e+031,
-3.25079147118034e+032,
-6.04362056723916e+033,
-1.04033863298669e+035,
-1.67721342078464e+036,
-2.55641247592603e+037,
-3.71487059097827e+038,
-5.19156012641781e+039,
-7.05767849053118e+040,
-9.54079997480186e+041,
-1.37682173010483e+043,
-2.81944608373897e+044,
-1.35568431120779e+047,
50890062.0717611,
14367608874.8046,
-2441428268667.74,
-1.1038760824906e+015,
-1.39748101423647e+017,
-9.39850732312024e+018,
-3.91099001869365e+020,
-1.10065830730325e+022,
-2.72302043182617e+023,
-1.10817009473656e+025,
-6.4123402563569e+026,
-3.20104135366767e+028,
-1.26609617693228e+030,
-4.08925485679342e+031,
-1.11710339860563e+033,
-2.65351306408463e+034,
-5.59921841894524e+035,
-1.06786709570634e+037,
-1.86801008380294e+038,
-3.03739730383572e+039,
-4.65152896853984e+040,
-6.8118589248791e+041,
-9.79544921447061e+042,
-1.51514184913643e+044,
-3.61763707621482e+045,
-2.33635753945665e+048,
-1632017496.10562,
110317600316.58,
330180395951750,
6.7231021628206e+016,
3.97828600685863e+018,
-2.95784859710759e+020,
-6.98592705045258e+022,
-6.25659244735647e+024,
-3.64861751928678e+026,
-1.5833753360599e+028,
-5.45880499049355e+029,
-1.55850222438659e+031,
-3.79783004095228e+032,
-8.08967352013915e+033,
-1.53636362179642e+035,
-2.64622016202475e+036,
-4.19608871034953e+037,
-6.20828443819136e+038,
-8.67464415143325e+039,
-1.15730260817286e+041,
-1.48916975227492e+042,
-1.86658981818677e+043,
-2.31349724473074e+044,
-3.02888770555798e+045,
-5.99835061959248e+046,
-4.23733375004766e+049,
38417214435.0839,
-726039946748.135,
-7.31431915372476e+015,
-1.56745545878788e+018,
-1.02395774227146e+020,
4.67055145073008e+021,
1.3399291038475e+024,
1.20997806353346e+026,
6.95795172708743e+027,
2.95024225282919e+029,
9.86887837596031e+030,
2.71349946947451e+032,
6.30942685965434e+033,
1.26704450603725e+035,
2.23282870445361e+036,
3.49345248902422e+037,
4.88842278953211e+038,
6.12750579137622e+039,
6.82428986341838e+040,
6.55589778514714e+041,
4.93603193443648e+042,
1.70522518557545e+043,
-3.25119471661806e+044,
-1.19081432094687e+046,
-5.38145156298819e+047,
-9.5337915116242e+050 )
}
if ( (power>2) && (power<3) ) {
grid <- c(
0.999320859444135,
-0.00339863996520666,
-0.017405834743935,
-0.094415885413374,
-0.474943122220438,
-2.12217526114901,
-8.28657088560929,
-28.1983730239296,
-83.9866444485264,
-220.714016257597,
-516.840853257854,
-1089.80906886319,
-2091.04653592782,
-3687.84899560698,
-6035.14688398691,
-9245.16287671588,
-13364.8056799522,
-18368.6312623177,
-24170.5284208701,
-30652.0675548239,
-37701.6909476229,
-45257.9298753625,
-53351.6680939871,
-62148.0795745321,
-71944.5580351856,
-92584.6307265222,
0.283341460167403,
1.4198595014972,
7.26323206149768,
39.3470798317175,
197.737872455163,
882.775423162057,
3442.34491552515,
11680.2981292535,
34586.2312661717,
89941.2772399677,
207071.437085722,
425804.06636173,
789124.09455765,
1329886.46550453,
2055949.50037776,
2940437.73707706,
3922432.53173063,
4918772.14066394,
5842643.29870822,
6622148.2558007,
7212994.5161919,
7602717.43947442,
7807280.48778773,
7863250.68212219,
7817746.83340438,
7725050.76243782,
-0.0600764380680103,
-0.392050079124554,
-1.58937633747626,
-6.08664376399068,
-21.2367358176583,
-63.2532442004164,
-151.966790509734,
-262.308768568861,
-171.730813184702,
848.887604105088,
4456.38515028148,
13551.4810243792,
32150.4572347722,
64571.5085421313,
114045.803910683,
181267.784390237,
263555.257000779,
355057.226722376,
447959.727920055,
534210.69005017,
607115.455356772,
662364.32312859,
698095.516091012,
715453.61053991,
709404.020526808,
746938.05963745,
0.0245245775014973,
0.155539966613345,
0.314103723867304,
-0.974507538399082,
-14.3303629251534,
-93.9696323047437,
-452.198879088332,
-1754.67665143518,
-5704.65115146005,
-15896.7164855003,
-38614.4509020089,
-82918.5184841515,
-159371.089358326,
-277309.878496798,
-441509.504984657,
-649717.382851132,
-892380.682977137,
-1154918.2173388,
-1421750.28004424,
-1680648.33849184,
-1926151.40276689,
-2161369.37925071,
-2399069.23604879,
-2658615.89551391,
-2996584.32616847,
-3244309.2211475,
-0.0114761862276732,
-0.0592619852303128,
0.149317524117004,
3.1187422858429,
23.1527784014401,
124.86200951222,
542.858009682394,
1973.11003584607,
6116.61892273702,
16406.537857693,
38528.1580303481,
80007.829774633,
148150.992289522,
246211.713959957,
368704.211125567,
497587.798271825,
601013.469645754,
635274.165995275,
549071.310137826,
288010.646988658,
-203166.790795375,
-982564.60054751,
-2119680.41798567,
-3704741.92691329,
-5931154.48660554,
-8809844.1184798,
0.00575921327240797,
0.0165592415712064,
-0.310297398420674,
-3.50279461877254,
-22.6809711897805,
-113.076858198932,
-465.191104437209,
-1624.40007498999,
-4906.66394460468,
-13042.9156711335,
-31056.3757863278,
-67485.3530473821,
-136357.774862024,
-260555.840068835,
-476923.168849248,
-842508.117841961,
-1440283.41961548,
-2382568.94608435,
-3811813.17259831,
-5900950.25877304,
-8858145.80320564,
-12942579.2179964,
-18500106.3718362,
-26024539.6191355,
-36343654.5689473,
-51760152.8969368,
-0.00300526348269945,
0.00332582644494308,
0.352539219455832,
3.25105798234768,
19.0591425935349,
87.5918992144986,
333.900689176084,
1071.0953680497,
2874.83712283637,
6250.68546381489,
9860.08999845749,
5357.73872252884,
-33652.9231630469,
-170144.676973302,
-528295.164157734,
-1318787.55146601,
-2857009.40475253,
-5568572.63242854,
-9983746.86426784,
-16731892.6976634,
-26555077.5194214,
-40365482.5555169,
-59377234.8688406,
-85360882.1668992,
-121173410.369109,
-177831829.550814,
0.00156864913600111,
-0.0131184236007616,
-0.348599078434079,
-2.77780309250851,
-14.4361149519266,
-58.8320138727439,
-203.569099773387,
-645.03374745931,
-2061.89411085477,
-7067.36215375172,
-25074.4673862501,
-85193.394389473,
-263487.697425328,
-729232.04752068,
-1807739.26844015,
-4046984.43990115,
-8268652.76656352,
-15588975.4539116,
-27412600.48323,
-45427572.5997714,
-71652140.9796545,
-108601600.144071,
-159667231.52998,
-229874415.837102,
-327427911.37296,
-486267279.031203,
-0.000751098308492496,
0.0183607429610277,
0.32560155770289,
2.20414845756873,
9.30362608159624,
27.198466156795,
41.1328701889614,
-147.601617296233,
-1778.48998961713,
-10615.1337836503,
-48121.4524064771,
-180117.812148503,
-576102.516202511,
-1608834.11717014,
-3989140.08790138,
-8909582.40404006,
-18156969.4268232,
-34163633.7942921,
-60005088.1200331,
-99404892.9765117,
-156858144.123099,
-238028512.439587,
-350642272.707905,
-506310271.081071,
-724411047.556449,
-1085756135.90953,
0.00023268753144256,
-0.0214573124116083,
-0.290521160221242,
-1.52935064098677,
-3.59013983096331,
3.92703520664888,
60.9297355136416,
133.554643751598,
-1021.17664549104,
-11590.6683029842,
-66685.879961975,
-281254.304289336,
-960925.358517155,
-2788713.9792639,
-7077864.08967289,
-16041484.6298937,
-33004923.3507173,
-62506118.7968919,
-110299815.326543,
-183381109.539535,
-290240024.52127,
-441647425.450367,
-652423811.084398,
-945103927.138418,
-1358058723.14185,
-2050647607.71471,
0.000141239642755454,
0.0232583731015363,
0.239064459228162,
0.680275724339044,
-3.14242038852734,
-42.3056828515275,
-274.070438394209,
-1492.11348836561,
-7656.84591539787,
-36265.7134048327,
-152004.565173214,
-553517.300322874,
-1753199.12822194,
-4878532.09154446,
-12079077.4876383,
-26959794.0499863,
-54922340.2612081,
-103328174.078604,
-181512150.271794,
-300836965.808012,
-475136824.235409,
-722051548.703595,
-1066029150.12698,
-1544638613.28437,
-2222964632.64711,
-3372045968.09847,
-0.000444860575100238,
-0.0236847905695715,
-0.161058411288511,
0.407895924404698,
10.7548689475349,
73.0538463066281,
281.046556675514,
383.530300181306,
-3421.68161502129,
-33452.5094386606,
-180847.896775903,
-735888.039250597,
-2456210.90539502,
-7010955.43700536,
-17571067.8749036,
-39423967.3829222,
-80439386.6066522,
-151267929.917988,
-265326130.629948,
-438855452.428628,
-691566344.59827,
-1048598947.11475,
-1544960914.68021,
-2234995984.89575,
-3214527134.98847,
-4893933770.89838,
0.000703732261226084,
0.0219231227951077,
0.0425149877267029,
-1.78013554662686,
-18.8024427670158,
-106.878166315772,
-491.309303563418,
-2410.2059871961,
-13085.0171426766,
-67405.3817964102,
-299027.541071522,
-1121165.69781058,
-3591096.47322529,
-9998617.39241346,
-24622492.5304239,
-54479632.7305074,
-109838493.819578,
-204359729.041694,
-354963747.711344,
-581822254.35559,
-909137795.541055,
-1367637645.50103,
-2000281379.29399,
-2874669331.61444,
-4113040594.89626,
-6286557382.99022,
-0.000959178477233191,
-0.0172549225992488,
0.119521088004283,
3.25076886753573,
24.469396043305,
77.1613526002622,
-413.359872941446,
-8197.32770301892,
-68568.1716842124,
-394782.555626955,
-1746273.13505017,
-6261284.87873029,
-18848727.5557636,
-48909488.5602613,
-111724871.937695,
-228668100.175633,
-425755681.178738,
-730883280.355038,
-1170935158.54954,
-1770335830.80924,
-2552404036.30653,
-3544443902.10624,
-4787694880.17175,
-6355795903.3852,
-8395778630.02711,
-11697767237.6242,
-0.000133829436888704,
-0.00402825444711644,
-0.39467858862294,
-4.78902212824088,
-23.5283465754233,
-495.238264820242,
-11644.3071017881,
-143948.075333492,
-1133949.74994485,
-6423704.38453159,
-28106118.540934,
-99563713.8931762,
-295413197.299012,
-753554043.615336,
-1687633184.19881,
-3377063524.57688,
-6129762082.98725,
-10226991209.9182,
-15871393620.5447,
-23160885564.1831,
-32101906559.4075,
-42662039575.6347,
-54852876075.286,
-68836142772.9544,
-85067835018.7585,
-105221455769.378,
-0.0159347723438438,
-0.139677220958585,
-0.501567031055687,
-1.15800906623169,
-0.28145406205746,
-5860.29004848185,
-152251.522259703,
-1873731.64284049,
-14679841.3179456,
-82892307.4814804,
-361969279.219145,
-1280474002.74372,
-3795015931.20803,
-9670673302.28459,
-21636448308.9111,
-43251166651.4325,
-78419385616.2198,
-130679713013.754,
-202537118746.243,
-295128647709.38,
-408391269373.725,
-541723400932.74,
-695004000950.63,
-869822131123.467,
-1070898637903.45,
-1311173239757.92)
}
if ( (power>=3) && (power<4) ) {
grid <- c(
0.807045029092288,
-0.742817271116966,
-3.33628159647649,
-17.1892563957248,
-83.606924206003,
-365.071192253248,
-1400.71893678865,
-4694.58855569616,
-13766.4944192918,
-35518.0066568666,
-81236.2491747527,
-166111.053093699,
-306340.130694687,
-514013.401873071,
-791488.479479209,
-1127820.45893735,
-1499215.00485969,
-1873687.95856514,
-2218215.22065063,
-2505773.30210073,
-2720001.08609826,
-2856885.35011282,
-2921562.04807504,
-2942860.2782209,
-2724727.65113592,
-6393599.83992389,
-0.136539772699055,
-0.3712773738108,
-1.34060216897536,
-6.31281195417687,
-28.7743296376622,
-120.000150401644,
-444.643043043044,
-1450.18256577969,
-4160.32884893442,
-10542.0837079396,
-23750.546686822,
-47945.825282172,
-87450.1861981138,
-145332.756352579,
-221913.780561476,
-313883.835136119,
-414535.3380698,
-515112.581103503,
-606768.028120295,
-682457.909013515,
-738016.337582899,
-773197.016326358,
-785451.127656309,
-832107.719453664,
-65576.1860675511,
-16681644.1359413,
0.0390190571539757,
0.217823357411596,
1.05307617320898,
5.46628587502473,
26.7079674195229,
116.777871575447,
448.243317291106,
1502.23344046383,
4404.21226928853,
11360.1463323601,
25977.6589655352,
53114.6692363956,
97962.628202229,
164425.342777476,
253336.682488931,
361326.799670235,
480960.413361712,
602200.055474944,
714666.469016104,
809833.902052876,
882644.532433897,
931195.500052511,
963253.25246436,
909728.615872677,
2118955.81118029,
-28223901.1772564,
-0.0135344333535702,
-0.105123408597516,
-0.597134560351953,
-3.30138792730478,
-16.7678509371076,
-75.2601777869174,
-294.380322822538,
-1000.62051658493,
-2965.26791173967,
-7710.19873496618,
-17729.923018914,
-36365.1109880616,
-67103.1049888601,
-112342.914312332,
-172033.611258013,
-242814.982348664,
-318156.29116042,
-389547.350581509,
-448309.499169329,
-487358.607042042,
-502288.280654725,
-491896.568009773,
-454167.367329454,
-436702.595676197,
592554.019288957,
-28175511.1369623,
0.00516979878298409,
0.049186369552098,
0.313361035619778,
1.82380477698879,
9.55014857006874,
43.7632364583752,
173.85444871189,
599.000056509861,
1801.41110174687,
4775.62836370548,
11292.324476147,
24116.159116646,
47097.8558813758,
85097.7219846563,
143732.570485074,
228950.891134358,
346463.780768116,
501132.836280051,
696519.783935997,
934868.31070775,
1217737.35915428,
1547476.14417311,
1929941.85114461,
2371249.26369004,
3259938.37856758,
-10481780.2845814,
-0.00210569527115553,
-0.0231405024519351,
-0.161238923976278,
-0.980926414519322,
-5.27476113570811,
-24.596921426023,
-98.4679251076239,
-335.875641752254,
-966.009103975749,
-2295.01927050472,
-4285.53743080301,
-5305.54520561608,
298.828932844618,
25527.1544820149,
93698.0628522327,
239219.913855273,
504807.80240039,
935434.395727312,
1571191.70516859,
2442224.38428192,
3568464.03604572,
4965686.14710397,
6658844.98464334,
8715913.57478651,
11333531.2576485,
12135648.0516836,
0.000904992444600065,
0.0111168052401889,
0.0833664125811974,
0.527134997928565,
2.89808864704583,
13.7770488849601,
57.6536611318659,
222.31978415136,
830.973533709237,
3052.29525500565,
10683.2000738177,
34231.1489571498,
98080.965980282,
249787.613056241,
567853.696586215,
1162730.51664402,
2167379.38902465,
3718634.07876582,
5936186.98691647,
8908850.23901353,
12696377.3865465,
17351472.7681057,
22966767.528756,
29776590.0504127,
38478019.7505486,
50867749.5850808,
-0.000409107208596102,
-0.00550111018040516,
-0.0439376208280782,
-0.288505996551621,
-1.63212078318116,
-7.75520903054617,
-27.7954092957704,
-45.8656633398937,
259.464351955424,
2854.74539011967,
15714.5555070392,
63230.6123114516,
204776.271508092,
558927.74579377,
1323826.85797549,
2780007.90439764,
5266252.25523076,
9131789.73343168,
14682560.3322589,
22146472.0731672,
31679055.6650164,
43421701.98937,
57625070.1381395,
74910568.9517981,
97163770.0643605,
127754334.17767,
0.000194307002727792,
0.00281756674493309,
0.0237136332062326,
0.159405381495387,
0.898230867797415,
4.60345984485858,
27.6400397896721,
205.661534317615,
1448.56631969149,
8291.67719559354,
37903.115045638,
141316.649850398,
441087.624260472,
1180252.50521153,
2763322.5415243,
5761704.22812121,
10864619.9821838,
18782495.180654,
30138958.1231858,
45402276.5830579,
64900090.6565401,
88943149.521878,
118085299.880759,
153669984.92336,
199638879.192562,
263053537.257288,
-9.6813970562699e-005,
-0.00149818930643216,
-0.0133055656398246,
-0.0945115298691158,
-0.579908914141087,
-2.47603853062905,
4.13987484493922,
197.011666853647,
1993.36630427103,
12842.763799835,
61521.7609859012,
234369.520358223,
739791.084258406,
1992499.07342665,
4684730.93725107,
9797208.48563922,
18517157.6071782,
32074859.2918227,
51560378.2551523,
77807929.4600213,
111424466.116615,
153009280.153805,
203615359.468966,
265712174.566699,
346298256.693629,
458843429.853769,
5.0510737242787e-005,
0.000825454278033001,
0.00754236535471132,
0.0518083089767653,
0.274621994126378,
1.98114382300995,
29.5576814444073,
370.652270203056,
3159.13901640118,
19407.1216982271,
91464.1099352158,
346424.449467708,
1091742.85694851,
2941228.74414017,
6923668.63289443,
14504109.9212339,
27468203.8817623,
47684788.4333904,
76836997.6005713,
116252578.587634,
166950731.275237,
229981255.740226,
307139843.974733,
402454023.216751,
526912234.233937,
702818878.857313,
-2.7418070102492e-005,
-0.000471538370173029,
-0.0046165376568393,
-0.036587699748026,
-0.259306297425945,
-0.513545608507554,
24.5167655002064,
422.079080450406,
3864.47708330576,
24364.9020805635,
116380.447641915,
444742.438017592,
1411324.94709018,
3824627.71731913,
9050677.77134831,
19052334.7104253,
36248377.3563104,
63208294.4047604,
102300026.230609,
155465995.050065,
224290351.769315,
310469434.35741,
416810360.956061,
549298562.77482,
723618453.467978,
973334765.794742,
1.5473116821586e-005,
0.000276604798913003,
0.00264969418261052,
0.0174900279365758,
0.0766314928362542,
1.35761435509042,
35.91128539334,
507.476924676718,
4502.64745318921,
28323.9262461144,
135970.357806147,
523202.778300938,
1672239.7082978,
4563033.2399971,
10868160.2019504,
23016985.4182579,
44040524.526026,
77210463.32594,
125613056.798018,
191876531.064486,
278262231.602734,
387270853.524674,
522928872.391834,
693428189.404835,
919453049.166152,
1247727868.46718,
-8.8935422652274e-006,
-0.000166030604502527,
-0.00180320520193969,
-0.0158064250790231,
-0.112690635415925,
0.605792100613844,
35.8920609726225,
549.294618680751,
5007.87803105007,
32039.3397103949,
155789.404879026,
605600.459856101,
1951459.22132761,
5359784.8952449,
12832094.7037116,
27287162.7391152,
52377387.4480437,
92054947.2665312,
150060697.345423,
229605705.993322,
333504156.464628,
464936857.308676,
629016062.372982,
835873005.440438,
1110473643.66999,
1511045682.99279,
5.2836771853153e-006,
0.000101503163727336,
0.000993429510955962,
0.00768536258973886,
0.0762004564807366,
2.5289608455215,
61.1254255902454,
833.768195052616,
7354.03786958471,
46348.1408509856,
223057.664768771,
859057.342688984,
2741866.57069041,
7454083.6797878,
17650308.942397,
37089910.5528786,
70295592.6389546,
121895207.707387,
195915436.6333,
295398279.000812,
422647796.67442,
580244039.797793,
772834327.8546,
1010119774.0892,
1316484399.07765,
1741035939.30733,
-3.064377771159e-006,
-5.980922030261e-005,
-0.000636343983276073,
-0.00078615973385692,
0.104702137517939,
4.49267742988801,
99.9926447089914,
1292.20378864764,
10963.7639617,
66756.6908405897,
310381.696918354,
1152600.74257852,
3536665.37191601,
9209232.17803997,
20794869.4119386,
41458235.608168,
74105805.4180075,
120360968.097685,
179752435.234823,
249520137.896054,
325147964.097433,
401275805.233735,
472066391.64127,
529481285.471072,
561635505.992595,
419706664.414131)
}
if ( (power>=4) && (power<5) ) {
grid <- c(
0.699925346022531,
-0.967077543569014,
-4.01132613691835,
-20.1399473550733,
-96.2422051602767,
-415.365980035549,
-1580.21518068211,
-5262.33523148009,
-15354.0312963513,
-39454.0262740431,
-89938.4982463926,
-183391.698932919,
-337402.996179853,
-564968.193375439,
-868383.335714499,
-1235426.26432415,
-1639939.91489061,
-2046986.48980844,
-2420647.49346844,
-2731722.04945314,
-2962469.78638038,
-3110166.85555429,
-3167407.14273507,
-3347866.5224723,
220066.29635677,
-101623416.405294,
-0.0856827146015816,
-0.129194389632916,
-0.275741081827042,
-0.995185808644477,
-3.44304072656882,
-11.1738124760052,
-32.3161811060365,
-82.0820212947264,
-181.186657587385,
-345.1190334895,
-560.487576581505,
-755.308564356227,
-780.02789704195,
-420.782646552896,
549.203902376783,
2292.75919352824,
4844.65304486468,
8078.19818210918,
11752.1076384033,
15489.0074612448,
19295.1080639715,
20576.2965127781,
43458.6905027808,
-272065.299693591,
7025098.66546232,
-233107902.179985,
0.0168969338431571,
0.0658060047775105,
0.252941889440879,
1.1930373881614,
5.46017018978347,
22.7950867197324,
84.5102486368491,
275.66150811094,
790.803379055727,
2003.61163553412,
4513.25595683332,
9109.342888956,
16611.6941580461,
27601.4176540827,
42137.2784788037,
59588.6192203015,
78680.9563361091,
97750.8199011234,
115126.506416694,
129453.386054272,
140101.469157844,
145829.366024648,
160224.556969174,
-43787.4381679082,
5529231.86708544,
-215530714.274696,
-0.0040335782993408,
-0.0234817794259036,
-0.110587472703672,
-0.561343113249565,
-2.70232831818259,
-11.6848904632598,
-44.472343214546,
-148.047891896767,
-431.69906130895,
-1108.54940295543,
-2525.46917566759,
-5147.26241339181,
-9467.85961656983,
-15855.3598573824,
-24383.2818096163,
-34724.30268989,
-46163.6433390437,
-57734.3395387668,
-68421.6708128944,
-77354.6697154979,
-83913.2169220258,
-87816.2036212983,
-87020.6389051429,
-128645.623351391,
1605434.61145123,
-93593764.193113,
0.00106368144379509,
0.0078728133185123,
0.0423052301671125,
0.226374767743507,
1.12595759435215,
4.97840665743307,
19.2538811192632,
64.8572506879996,
190.743003851787,
492.585067098186,
1125.23986845133,
2291.87964977926,
4195.71676979692,
6958.1794888724,
10533.1890357286,
14663.2366154889,
18914.8130296304,
22801.0859452267,
25968.0905843622,
28413.4033257206,
30721.5445983317,
34434.2563191554,
41999.1412856565,
63751.8453401499,
142903.993721121,
-14773309.479337,
-0.0002988416478197,
-0.0026128755213848,
-0.0155064767814191,
-0.0866816879592185,
-0.442392050536327,
-1.99055510244982,
-7.80955850461462,
-26.7322098215555,
-80.4281213186107,
-215.042835786294,
-517.452034952092,
-1134.82818218957,
-2293.86917654107,
-4310.82691914404,
-7575.43567664562,
-12486.4405956532,
-19320.884708294,
-28032.1935354864,
-37976.4690140615,
-47537.7814603878,
-53537.2289629646,
-50176.3090563924,
-27111.3184862328,
35023.1543546029,
97772.386910872,
1945675.4370755,
8.8111852916931e-005,
0.000874298083941498,
0.00562299485434772,
0.0327030242649852,
0.171726872656,
0.790684116809639,
3.1130199548177,
10.1710449772459,
26.346202329904,
48.3548936424336,
31.8771254839422,
-186.395662514681,
-1016.84516919046,
-3258.27728769355,
-8162.68516490687,
-17312.2380768225,
-32239.1706818026,
-53802.4297241544,
-81382.1575234866,
-111877.895287325,
-138254.603738189,
-146999.311848418,
-113518.232821567,
3726.73086187838,
273817.624118751,
757199.553621758,
-2.7085879774208e-005,
-0.000297498761276123,
-0.00204245827241299,
-0.0121381151934212,
-0.061733063855247,
-0.26699858234589,
-1.1122126687644,
-5.31569083447484,
-27.8731682359897,
-134.874202708192,
-553.327324835573,
-1903.59891170908,
-5566.04749679175,
-14086.3410351293,
-31399.2007566238,
-62614.6499198601,
-113234.321754671,
-187884.675320979,
-288785.120075029,
-414032.58145669,
-555329.364059289,
-694159.031925558,
-795349.360834586,
-800767.324268166,
-634936.677499812,
-1390026.09670781,
8.6547130615233e-006,
0.000103571257343756,
0.000763282155189074,
0.00503495689305218,
0.0339503192962971,
0.201182583372745,
0.679200600696824,
-1.40781922364333,
-34.7607658472872,
-251.167735291424,
-1214.87163835565,
-4539.92881673297,
-13946.9496782576,
-36547.4380325321,
-83834.1134982485,
-171726.961316446,
-319298.861981019,
-546376.82435059,
-870690.377723771,
-1305228.69338149,
-1855917.38613467,
-2519159.50584102,
-3280158.49857154,
-4124134.63935406,
-5101301.89955304,
-8040658.58499969,
-2.863420992543e-006,
-3.6705711047603e-005,
-0.000267736627702962,
-0.00118987631537025,
0.00500374982239699,
0.0906349021665064,
-0.03964765353084,
-8.86995948576699,
-96.4179103903694,
-622.102159599423,
-2925.97709670939,
-10897.5978947285,
-33690.7023380288,
-89258.4433448129,
-207545.201776322,
-431710.061827054,
-816252.874623963,
-1422300.99639821,
-2311804.80050625,
-3543091.25767127,
-5169984.23754927,
-7246834.8839518,
-9846927.88218808,
-13128306.876303,
-17545564.4897858,
-25760072.0632545,
9.862455038939e-007,
1.3687405837123e-005,
0.000130756634353942,
0.00161205842445782,
0.0260978720622342,
0.205692870824142,
-0.217742919739228,
-19.0670830309275,
-201.334161636633,
-1297.1205613785,
-6144.28137107098,
-23122.4216546073,
-72314.544985341,
-193853.872583445,
-455974.877979017,
-958991.306803016,
-1832262.21329924,
-3224343.55883332,
-5290401.34780242,
-8183538.60025336,
-12057410.3744032,
-17089089.6467557,
-23542978.7525315,
-31949315.2967005,
-43603277.3073714,
-61461357.0483208,
-3.3898916523125e-007,
-4.553631043329e-006,
-6.3146792385749e-006,
0.000996685778798012,
0.0283638961892905,
0.205028928564685,
-1.5209878776305,
-40.9193475021547,
-399.642312169516,
-2535.0167059544,
-12007.7742204405,
-45413.275846636,
-142947.623599072,
-385712.615552065,
-912728.368992133,
-1929683.59832148,
-3702976.31241841,
-6539242.01547221,
-10759257.0350438,
-16681448.9101165,
-24632750.0692673,
-35008236.3642549,
-48422810.8521226,
-66089231.9656645,
-90790259.3017384,
-124782634.831774,
1.3670317399056e-007,
2.8922795451404e-006,
8.0311153292009e-005,
0.00209218748382464,
0.042288144829039,
0.224071380381849,
-3.88595477558196,
-80.3828018669491,
-756.261098584473,
-4760.28166814639,
-22556.6461988553,
-85542.2228609317,
-270094.51932018,
-730737.212456536,
-1732553.94919498,
-3667198.87154186,
-7040018.87161964,
-12429346.6875643,
-20436837.3840823,
-31660964.6132857,
-46731285.933596,
-66447851.8147418,
-92106261.376575,
-126229910.642334,
-174276152.679859,
-236992787.643919,
-2.9515402119269e-008,
1.4230937296803e-006,
0.000121964247166344,
0.00353296955768749,
0.065444187405576,
0.228124670269768,
-8.75709483474552,
-158.883665823477,
-1458.29696267044,
-9116.76392174209,
-43122.5389213505,
-163475.6881624,
-516064.788911388,
-1395522.20150944,
-3305660.01902088,
-6987365.36000612,
-13391031.6773161,
-23598208.7876355,
-38732820.725386,
-59928676.182718,
-88431093.3806788,
-125922659.671926,
-175220715.536157,
-241690986.941136,
-336090539.887824,
-458661737.622016,
4.2195953578419e-008,
4.7262596571073e-006,
0.000268409542694463,
0.00711771507088045,
0.117709590133548,
0.185527243324104,
-20.5126719620795,
-341.724384735611,
-3067.30039938492,
-18999.4745727416,
-89434.205638909,
-338004.516140821,
-1064613.61087423,
-2873576.28161018,
-6796130.72493253,
-14346593.3785094,
-27467963.4091078,
-48381210.7295654,
-79426953.5719077,
-123043357.109127,
-182047880.504625,
-260412755.530795,
-364810110.446681,
-507417982.521783,
-710389534.723263,
-981948479.261186,
3.2858256896933e-008,
8.6262465133508e-006,
0.000619619047250753,
0.0177352317421679,
0.286522133653506,
0.930762013518072,
-34.6477998067267,
-621.723655825581,
-5696.25104328862,
-35724.7343454217,
-170023.838772441,
-649865.670726276,
-2071812.51834388,
-5666452.90654193,
-13596350.0025411,
-29159538.9365487,
-56804496.6608088,
-101967267.133786,
-170892032.312482,
-270727256.793951,
-410267304.386682,
-601763640.206147,
-864300376.261109,
-1229059105.40151,
-1743431919.71737,
-2419331563.0187)
}
if ( (power>=5) && (power<7) ) {
grid <- c(
0.786434222068313,
-0.346012079815851,
-0.111403879165884,
-0.37684834413327,
-0.227942819345689,
-0.748816199446288,
-0.429657425382675,
-1.74160208112774,
-0.380029940723467,
-4.75431964095465,
3.04669074354556,
-18.7254127758988,
42.2595203965277,
-127.075610501907,
597.354383371277,
-1783.48701130305,
11845.8231537032,
-56908.6196171327,
443014.347945159,
-3727125.91186479,
41915265.5772462,
-613145856.515179,
12314442848.2845,
-353565282768.735,
15056060852441.6,
-935512014119462,
-0.0372367474176292,
-0.0300330290598776,
0.0194320567856015,
-0.0286632698352744,
0.0445003394042309,
-0.060948400702475,
0.132495375767898,
-0.213544390269728,
0.423844494115997,
-1.61814802662431,
-1.11118707905738,
-26.5227940118242,
-67.7293316745046,
-425.458598662828,
-1001.46373152249,
-5317.32161731875,
-6139.36538655163,
-71044.3658618384,
194667.687528656,
-2788059.62676948,
30424957.0834719,
-488372280.977764,
10689386756.2126,
-340771077349.598,
16472908240969.7,
-1.18753639215006e+015,
0.00272199211678462,
0.00600457935696839,
0.000771571810584139,
0.00448332513732787,
0.00189163733536341,
0.00589886871984612,
0.00239247793636055,
-0.0286338123481378,
-0.315494675308072,
-2.47958187250564,
-14.5308793302688,
-72.977265238482,
-303.738213023504,
-1105.5766522905,
-3387.71681429456,
-9110.18620747135,
-18243.3848321049,
-29784.0538288672,
75227.02534185,
-48264.5575731943,
8222854.19107454,
-103843212.592982,
2899046709.27306,
-108457074214.473,
6391125630551.74,
-572642997373694,
-0.000235725585525655,
-0.000939712997116092,
-0.000628940476056143,
-0.000732868263909586,
-0.00123615938011299,
0.000322710464360014,
0.0114320282205539,
0.137507245882712,
1.1142446434786,
8.13970036772955,
52.4668442088235,
302.39429825616,
1551.75362597238,
7136.34444891635,
29595.0973156719,
111934.511057314,
390212.830424631,
1272109.66953064,
3921732.69419177,
11664373.480828,
33562473.6192614,
96275902.7551133,
386971758.390603,
-7779194558.35237,
869116980003.18,
-120470494442105,
2.2131289395219e-005,
0.000143553411002132,
0.000170793457061453,
0.000168846275141174,
0.000879434613056662,
0.00980484450010389,
0.12801774812558,
1.33913284198253,
11.5110566068305,
82.8906614784825,
510.178293855477,
2728.20581284727,
12861.2337022356,
54151.1413496475,
206133.384228595,
717759.486483854,
2312738.60846531,
6977878.20433018,
19960158.1406384,
54872807.7633121,
147027968.000616,
392467947.201468,
1007010930.32944,
4277401271.27259,
-32175521793.3006,
-5944774644892.04,
-2.1158714077244e-006,
-2.2245962793571e-005,
-3.7048515147495e-005,
2.6733273608329e-005,
0.00159538838855198,
0.0313650954321681,
0.434832189395928,
4.6653031612727,
40.2540676573929,
287.502036146911,
1739.44171649193,
9089.28709664162,
41709.0038241202,
170553.998156786,
629707.080488873,
2124898.97405362,
6629823.09908051,
19347946.9909511,
53449119.9055938,
141603511.259636,
365139375.94298,
931639294.908808,
2399554030.90057,
6365379770.8051,
6629077555.34454,
1325257347799.35,
1.8706218898433e-007,
3.5595867805602e-006,
1.0461142077657e-005,
0.000125822395739863,
0.00343944847191744,
0.0663161997681272,
0.932504916856121,
10.0628718510742,
86.680128866696,
614.451310218334,
3674.06045960846,
18916.695687826,
85354.4120703696,
342720.990999314,
1241358.93947498,
4106484.2634202,
12551665.0365457,
35852478.1688061,
96827356.785738,
250430599.497147,
629495711.021131,
1564844953.08431,
3922964834.69878,
10060076758.7741,
28625631416.721,
59232587864.0314,
-1.0736419206779e-008,
-5.5682318067157e-007,
1.521132088195e-006,
0.000169816881450556,
0.00513471228094518,
0.101321240932149,
1.43787147451134,
15.5501270999697,
133.573873042078,
940.8573571264,
5575.65420221155,
28399.6411897312,
126608.618970022,
501858.833477652,
1793488.15346414,
5851297.04271422,
17631543.2949301,
49624288.1787248,
131965198.165583,
335793721.545266,
829834387.493952,
2027957061.72163,
5001954036.02077,
12663935117.7047,
32689069667.4124,
18114334235.1189,
-1.2346951657342e-009,
1.2206227284162e-007,
3.9297895016142e-006,
0.000197419028183901,
0.00602851603167602,
0.120332460066855,
1.71628779074478,
18.5634802061232,
158.929000041028,
1113.04191204279,
6547.27067245127,
33064.4777866304,
146043.954634495,
573317.997343912,
2028724.86709794,
6553279.09218201,
19550737.044832,
54474555.29211,
143383996.095597,
361033832.339612,
882831234.550636,
2136130396.56957,
5224797761.40674,
13104715569.8387,
32786630095.1341,
37594565903.4031,
7.6808927594202e-010,
3.8884985498993e-009,
3.1693128416737e-006,
0.000185283673344334,
0.00577829446251914,
0.116358132374561,
1.6638196322789,
17.9690172702516,
153.197902136379,
1066.5313667415,
6229.28866525285,
31215.0838976393,
136765.982020265,
532563.383330351,
1869646.06197352,
5993641.65402298,
17752031.0930607,
49122405.022279,
128443983.218799,
321382731.452622,
781396537.897085,
1882476272.22521,
4594300256.1123,
11490195036.7978,
27999004292.5526,
22293146654.9453,
-2.3198818654552e-010,
1.7768432128195e-008,
2.5170398599975e-006,
0.000147600250383574,
0.0046726297592754,
0.0946608920777015,
1.35378607562751,
14.5687692163386,
123.471744448172,
853.19624444289,
4941.88962460754,
24548.7134403604,
106623.582662544,
411715.309842279,
1434104.29957124,
4564806.01096974,
13434953.6203005,
36971805.6020912,
96215692.5085437,
239814563.118944,
581599219.830851,
1400939948.6891,
3430310154.31951,
8605849617.10048,
20412486855.5244,
8789001626.70916,
7.1680465084153e-011,
8.2425411536541e-009,
1.643130414875e-006,
0.000101010537904274,
0.00324768919113633,
0.0660426805148569,
0.941790746358288,
10.06409355469,
84.4700029565598,
577.065123627681,
3301.27606364533,
16190.5323305796,
69436.106953296,
264898.991604471,
912482.279496566,
2875705.99281888,
8390894.88493373,
22923038.4921442,
59301250.3489504,
147168407.593844,
356301731.33071,
860860680.309354,
2129050981.40544,
5406333032.3096,
12477283740.0382,
-626655436.574466,
-1.6592791250243e-011,
4.0243341048155e-009,
9.144573335573e-007,
5.9220160549e-005,
0.00193782694015436,
0.039445147224364,
0.55777780092105,
5.874590816796,
48.3891511020367,
323.416138439675,
1806.1076174669,
8634.35391245784,
36073.4833351782,
134086.227392197,
450406.616132974,
1386158.30589757,
3956483.9824662,
10592449.579616,
26908399.3711585,
65779957.3387473,
157925265.23842,
383776594.467057,
976109761.141651,
2581703121.52396,
5773630017.85034,
-4997652480.24311,
3.0254155247433e-012,
6.480434669686e-010,
3.8358388175966e-007,
2.805883798994e-005,
0.000946081848661616,
0.0191810731660941,
0.265048170865662,
2.69054536709911,
21.1078472872048,
132.823226564838,
690.014628342345,
3029.32274273717,
11460.2837105301,
37977.6328286557,
111736.598497042,
294820.966835864,
701306.659651741,
1501566.94543448,
2865072.81069675,
4832518.62805497,
7836886.63058089,
19150010.6873593,
89185710.2082667,
421423170.310072,
903955723.061903,
-4583125093.25688,
-4.6611488044825e-012,
-1.238013643329e-009,
6.0868733097722e-008,
8.742211953457e-006,
0.000328731139452505,
0.00659863314758232,
0.0844309956857507,
0.742711442123046,
4.57966556822816,
18.4867246619517,
26.504351580449,
-278.749024654208,
-3001.65994744203,
-18452.141557694,
-87884.1942798782,
-354357.650582793,
-1264077.22326902,
-4102494.78750277,
-12352555.6345389,
-34956221.4649815,
-93464824.2667665,
-234738633.43955,
-541385094.991335,
-1108582688.25269,
-2320229645.40791,
-923285695.803153,
-3.6747431215211e-012,
-1.4003818727403e-009,
3.2110392985838e-008,
8.0692472963221e-006,
0.000344137055565625,
0.0076331695212749,
0.108809443680536,
1.09803763922457,
8.2754406180277,
47.8674513539372,
212.505496482315,
684.095100622171,
1139.77502759503,
-3574.08105308545,
-43796.4476172793,
-252629.656994052,
-1124806.21665939,
-4304377.68043652,
-14822703.8520193,
-47098602.6891216,
-140045686.50728,
-391792106.570437,
-1027557566.96914,
-2504246941.83045,
-5877038428.29484,
-2114725574.7047)
}
if ( (power>=7) && (power<=10) ) {
grid <- c(
0.77536534618895,
-0.430563489144848,
0.248933090844648,
-0.776691071939754,
1.42435320848802,
-3.96378215199569,
10.6082763732752,
-32.6646389815812,
107.594392018696,
-385.875807619758,
1554.08106263416,
-6562.13654153062,
33311.2180271377,
-175799.39356045,
1100307.32618603,
-8076936.20134624,
64818006.8415247,
-672272627.675492,
7951846880.99446,
-121489926465.507,
2346719230615.01,
-60597733349803.8,
2.17252324837994e+015,
-1.13969296410995e+017,
9.19134050303596e+018,
-1.13643544485344e+021,
-0.0228287393493532,
-0.0194681344424241,
0.0389473545390899,
-0.084197161744077,
0.22422473111649,
-0.619022478530716,
1.92391840210546,
-5.54851462125942,
31.3124540235083,
32.9263463638783,
1526.62316779162,
8457.00783887994,
82602.3748106012,
435383.429491403,
3109338.73107016,
12375814.1074866,
91668768.6318141,
102755151.774348,
4154874222.20171,
-39332097778.8331,
956298556688.97,
-25984409388026.1,
1.02539880527099e+015,
-6.00621364640884e+016,
5.55452727721829e+018,
-8.10234314733144e+020,
0.000990449241892617,
0.00245658725606492,
-0.00243739393253416,
0.00484724481040902,
-0.00926456300347046,
0.0281306359896192,
0.156239298430668,
4.17858979355244,
62.7520656235757,
780.015382056436,
7975.4456209287,
68984.4386566011,
515762.532144664,
3384991.53977911,
19858782.3438055,
105265045.358707,
514394379.656016,
2317182902.4062,
10175938926.1775,
37656980976.6547,
252620644930.558,
-2174477649470.25,
136934481128099,
-9.59053217215135e+015,
1.11722695207039e+018,
-2.10701957364907e+020,
-4.739402348122e-005,
-0.000231852992426791,
7.5710640928626e-005,
-0.000134980675522712,
0.000354522998021474,
0.0192668478637093,
0.520510022906938,
10.7916294399501,
169.819567472824,
2141.74949227175,
22251.8592082094,
195421.11468649,
1479886.25999519,
9836509.12146506,
58265320.1095556,
312023644.738493,
1530894452.40315,
6980944196.86386,
29986172284.6235,
123833899892.611,
492927274255.622,
2078899780231.5,
6850572520142.16,
-127562576321897,
5.83782301712251e+016,
-2.12174087566134e+019,
2.1161776328178e-006,
2.0906300316289e-005,
7.2258740877989e-006,
-5.5308991127345e-006,
0.000518091195594951,
0.0211849717747649,
0.651125893562394,
14.0232486435453,
229.888540942629,
2996.41818368473,
32119.513737,
290589.577507762,
2266622.81206172,
15520120.3234281,
94786645.0963208,
523940347.205171,
2658194740.25114,
12552187877.3901,
55962360223.2959,
239035772367.959,
991951859205.356,
4061174998315.7,
15708445458792.5,
118144223622463,
-5.07332493452949e+015,
6.4479142073582e+016,
-5.2809354056961e-008,
-1.8733028739588e-006,
-2.173112075266e-006,
-1.4999243577998e-006,
-1.6130806107812e-005,
0.0062857185977922,
0.291729587926022,
7.72340499458176,
144.463644174106,
2082.77967708294,
24311.1198183042,
237511.034262544,
1991173.97650715,
14616262.9410656,
95580256.036951,
565523735.27937,
3071700431.36731,
15529390455.3399,
74043372155.9458,
336948400501.14,
1477696012185.8,
6275079442094.89,
25790455939029,
96328050938412.8,
190447249714597,
1.00992445696896e+017,
-6.18972021646e-009,
1.6716212953349e-007,
1.819435975603e-007,
-1.4425153664549e-005,
-0.000610612063278709,
-0.0167634347715261,
-0.311332599080969,
-3.94138325688247,
-29.7238495417058,
6.2555652775239,
4042.6061664409,
72350.5669137632,
851581.13806843,
7901256.5282858,
61774104.4395478,
422241976.017542,
2587726006.34361,
14498413734.2669,
75443525203.5096,
369254749083.404,
1715435173133.93,
7593311590379.09,
31824142191324.9,
121720773218198,
396847554120315,
-4.20744529251827e+015,
1.6263773828611e-009,
-1.5358949677752e-008,
-2.4571305966315e-007,
-1.8428794010876e-005,
-0.000937415911513019,
-0.0306800211195246,
-0.708070117922537,
-12.1299638962403,
-159.03668317182,
-1618.62979619491,
-12693.3036944218,
-72284.2761884275,
-217166.845678661,
1044589.95460791,
23105099.1246563,
228679026.770271,
1721827459.30268,
11024395805.3666,
62955703260.573,
329358475506.641,
1604477935025.79,
7336606897800.17,
31379245002770.4,
121522052593940,
347347465989858,
370932937610640,
-2.6808728840779e-010,
7.9020135767862e-010,
-1.5514883197396e-007,
-1.6276332336879e-005,
-0.000876562698279347,
-0.0303398354210813,
-0.738225701613061,
-13.3408979363142,
-185.677983898719,
-2038.39425331329,
-17876.6499694802,
-124905.284696409,
-670434.749401926,
-2347535.07095901,
618376.316323485,
94377618.194901,
987830337.872776,
7299222860.15746,
45155167569.2116,
248286662532.449,
1249349399406.29,
5836370519195.45,
25333886840723.4,
99430753191700.9,
299121530322441,
625102006387724,
4.0255310414341e-011,
-4.0075628102411e-010,
-1.0747626938796e-007,
-1.1032436842021e-005,
-0.000614076074677421,
-0.0218656078360402,
-0.54523287925633,
-10.0746614750899,
-143.319283331831,
-1611.54363682135,
-14561.2179931157,
-106231.861503575,
-615725.868813294,
-2629632.88870542,
-5405277.88267556,
35284319.2277274,
545097935.998791,
4473496821.19931,
29049471850.145,
164111610940.043,
839519077635.141,
3964583399582.53,
17362504452757.4,
69068653702018.9,
218680025952334,
491443538772321,
-5.5715190324839e-012,
-1.6407435736789e-010,
-5.7888379466468e-008,
-6.1468686512493e-006,
-0.000349575517522456,
-0.0126681684563627,
-0.320310340444328,
-5.984181303379,
-85.8933670684766,
-973.163367650677,
-8853.94643946026,
-65051.8256679697,
-380371.836571965,
-1650092.93269853,
-3630335.63566798,
19513096.3150577,
321805563.17688,
2676104393.70507,
17469092428.2355,
98920174459.9976,
506594361070.731,
2395294913189.68,
10527983468557,
42415349208286.2,
142117239446790,
424957076182122,
9.0943122447293e-013,
-7.6362405646957e-011,
-2.713727877671e-008,
-2.928550895988e-006,
-0.000169272201914165,
-0.00620868754605586,
-0.158241844155348,
-2.96853021751442,
-42.6197249239258,
-480.920925303812,
-4332.65386909201,
-31222.9264278609,
-175486.089577641,
-686688.578405898,
-700984.246915129,
17606789.7093272,
210224332.113958,
1618919804.83086,
10205343393.9837,
56638977400.7164,
286412959136.382,
1344441166878.75,
5905112905298.04,
24102001115608.5,
86044212091524.3,
330694952809613,
-7.2206827308685e-014,
-2.9539633014077e-011,
-1.1047488592785e-008,
-1.2213639725909e-006,
-7.167213125224e-005,
-0.00265286298445461,
-0.0678318219234301,
-1.2685871768583,
-18.0238255068467,
-199.279184183516,
-1731.66032795093,
-11672.9085946704,
-56607.411359395,
-125551.570376765,
1014540.31262727,
16556288.6301798,
145428947.733874,
1003290094.11754,
5972683400.78656,
32007315379.0508,
158215899080.749,
732613701543.087,
3206486334222.12,
13279647471500.9,
50798414623688.9,
237038150364079,
4.3609819166476e-014,
-8.2019208583295e-012,
-3.8681869833068e-009,
-4.4736540762345e-007,
-2.681092767123e-005,
-0.00100096482939058,
-0.02552849391404,
-0.470191072698517,
-6.46906795194434,
-67.4507414346289,
-524.848782738057,
-2753.53939768566,
-4110.14385245369,
104460.727972183,
1538900.68620935,
14024098.498795,
101919977.04296,
638471700.403706,
3583252863.16384,
18458609364.3726,
88808087125.7936,
404428978510.69,
1762294434820.44,
7420587100023.73,
30447350490820.6,
161257587722473,
1.102927814593e-014,
-2.9833499013762e-013,
-1.0237201386522e-009,
-1.357500505407e-007,
-8.5194681661709e-006,
-0.000321263444569207,
-0.00803242863440226,
-0.139760568118627,
-1.70845294566464,
-13.7392013834384,
-43.3312232463909,
672.210515304308,
14566.0279110099,
170927.78078521,
1525821.93755474,
11366312.5854366,
73868184.8847336,
430610301.867199,
2297726058.33628,
11406906364.7078,
53429633348.726,
239204245061.543,
1037569229691.63,
4440670923491.02,
19385786140661,
108390210481645,
2.4429367439691e-015,
1.4097646088969e-012,
-8.1610167897946e-011,
-2.2790490204496e-008,
-1.5951868755541e-006,
-5.4515698129209e-005,
-0.000902748062402921,
0.000476641583177264,
0.403718060688101,
11.3250139182509,
195.75060974824,
2526.10978407101,
26230.959211931,
228725.678544486,
1724448.556825,
11494565.1027429,
68980892.2243655,
378540210.929366,
1926018147.60076,
9203415540.67664,
41820439362.7481,
183069601908.131,
783979860688.641,
3359830680474.02,
15066614162007.1,
80531744425420.1)
}
grid
}
tweedie.dev <- function(y, mu, power)
{
p <- power
if(p == 1) {
dev <- array( dim=length(y) )
mu <- array( dim=length(y), mu )
dev[y!=0] <- y[y!=0] * log(y[y!=0]/mu[y!=0]) - (y[y!=0] - mu[y!=0])
dev[y==0] <- mu[y==0]
} else{
if(p == 2) {
dev <- log(mu/y) + (y/mu) - 1
} else{
if (p== 0) {
dev <- (y-mu)^2
dev <- dev/2
} else{
dev <- (y^(2 - p))/((1 - p) * (2 - p)) -
(y * (mu^(1 - p)))/(1 - p) +
(mu^(2 - p))/(2 - p)
}
}
}
dev * 2
}
dtweedie.dldphi <- function(phi, mu, power, y ){
if ( (power != 2 ) & ( power != 1 ) ) {
k <- phi^(1/(power-2))
if ( k < 1 & k > 0 ) {
f <- dtweedie( y=k*y, power=power, mu=k*mu, phi=1 )
d <- dtweedie.dlogfdphi( y=k*y, power=power, mu=k*mu, phi=1 )
top <- d * f
d <- -2* sum( top / f * k^(2-power) )
} else{
d <- -2*sum( dtweedie.dlogfdphi(y=y, power=power, mu=mu, phi=phi) )
}
} else{
d <- -2*sum( dtweedie.dlogfdphi(y=y, power=power, mu=mu, phi=phi) )
}
d
}
dtweedie.dlogfdphi <- function(y, mu, phi, power)
{
p <- power
a <- (2 - p)/(1 - p)
if(length(phi) == 1) {
phi <- array(dim = length(y), phi)
}
if(length(mu) == 1) {
mu <- array(dim = length(y), mu)
}
A <- (y * mu^(1 - p))/(phi^2 * (p - 1))
B <- mu^(2 - p)/(phi^2 * (2 - p))
if(power > 2) {
f <- array(dim = c(length(y)))
kv <- dtweedie.kv.bigp(power = power, phi = phi, y = y)$kv
dv.dphi <- (kv * (a - 1))/phi
out.logv <- dtweedie.logv.bigp(power = power, phi = phi, y = y)
logv <- out.logv$logv
probs <- (is.infinite(logv)) | (is.nan(logv)) | (y<1)
if(any(probs)) {
delta <- 1.0e-5
a1 <- dtweedie(power=power, phi=phi[probs], mu=mu[probs], y=y[probs])
a2 <- dtweedie(power=power, phi=phi[probs]+delta, mu=mu[probs], y=y[probs])
f[probs] <- (log(a2) - log(a1) ) / delta
}
f[!probs] <- A[!probs] + B[!probs] + dv.dphi[!probs]/exp(logv[!probs])
}
if(power == 2) {
f <- -log(y) + ( y/mu ) + digamma(1/phi) - 1 + log( mu*phi )
f <- f / (phi^2)
}
if(power == 1) {
f <- mu - y - y*log(mu/phi) + y*digamma(1+(y/phi))
f <- f / (phi^2)
}
if((power > 1) && (power < 2)) {
f <- array( dim = length(y), mu^(2-power) / ( phi^2 * (2-power) ) )
jw <- dtweedie.jw.smallp(power=power, phi=phi[y > 0], y=y[y > 0])$jw
dw.dphi <- (jw * (a - 1)) / phi[y > 0]
logw <- dtweedie.logw.smallp(power=power, phi=phi[y > 0], y=y[y > 0])$logw
f[y>0] <- A[y > 0] + B[y > 0] + dw.dphi/exp(logw)
}
f
}
dtweedie.interp <- function(grid, nx, np, xix.lo, xix.hi,
p.lo, p.hi, power, xix) {
jt <- seq(0, nx, 1)
ts <- cos((2 * jt + 1)/(2 * nx + 2) * pi)
ts <- ((xix.hi + xix.lo) + ts * (xix.hi - xix.lo))/2
jp <- seq(0, np, 1)
ps <- cos((2 * jp + 1)/(2 * np + 2) * pi)
ps <- ((p.hi + p.lo) + ps * (p.hi - p.lo))/2
rho <- array(dim = nx + 1)
dd1 <- array(dim = nx + 1)
for(i in 1:(nx + 1)) {
dd1[i] <- grid[i, np + 1]
for(k in seq(np, 1, -1)) {
dd1[i] <- dd1[i] * (power - ps[k]) + grid[i, k]
}
}
rho <- dd1[nx + 1]
for(k in seq(nx, 1, -1)) {
rho <- rho * (xix - ts[k]) + dd1[k]
}
if ( power >= 3) {
rho <- 1 / rho
}
rho
}
dtweedie.inversion <- function(y, power, mu, phi, exact=TRUE, method=3){
if ( power<1) stop("power must be greater than 1.")
if ( any(phi <= 0)) stop("phi must be positive.")
if ( any(mu <= 0) ) stop("mu must be positive.")
if ( length(mu)>1) {
if ( length(mu)!=length(y) ) {
stop("mu must be scalar, or the same length as y.")
}
} else {
mu <- array( dim=length(y), mu )
}
if ( length(phi)>1) {
if ( length(phi)!=length(y) ) stop("phi must be scalar, or the same length as y.")
} else {
phi <- array( dim=length(y), phi )
}
save.method <- method
if ( !is.null(method)){
if ( length(method)>1 ) {
method <- save.method <- method[1]
}
if ( !(method %in% c(1,2,3)) ) stop("method must be 1, 2 or 3 (or left empty).")
}
y.len <- length(y)
density <- y
its <- y
verbose <- FALSE
if ( is.null(method)){
method <- array( dim=length(y))
} else {
method <- array( method, dim=length(y))
}
for (i in (1:y.len)) {
if ( y[i] <= 0 ) {
if ( (power>1) & (power<2) ) {
if ( y[i]==0 ) {
density[i] <- exp( -mu[i] ^ (2-power) / ( phi[i] * (2-power) ) )
} else {
density[i] <- 0
}
} else {
density[i] <- 0
}
} else {
m2 <- 1/mu[i]
theta <- ( mu[i]^(1-power) - 1 ) / ( 1 - power )
if ( ( abs(power - 2 ) ) < 1.0e-07 ){
kappa <- log(mu[i]) + (2 - power) * ( log(mu[i])^2 ) / 2
} else {
kappa <- ( mu[i]^(2-power) - 1 ) / ( 2 - power )
}
m1 <- exp( (y[i]*theta - kappa )/phi[i] )
dev <- tweedie.dev(y=y[i], mu=mu[i], power=power )
m3 <- exp( -dev/(2*phi[i]) ) / y[i]
min.method <- min( m1, m2, m3 )
if ( is.null(method[i]) ) {
if ( min.method==m1 ){
use.method <- 1
} else {
if ( min.method==m2 ) {
use.method <- 2
} else {
use.method <- 3
}
}
} else {
use.method <- method[i]
}
if ( use.method==2 ) {
tmp <- .Fortran( "twpdf",
as.double(power),
as.double(phi[i] / (mu[i]^(2-power)) ),
as.double(y[i]/mu[i]),
as.double(1),
as.integer( exact ),
as.integer( verbose ),
as.double(0),
as.integer(0),
as.double(0),
as.integer(0))
den <- tmp[[7]]
density[i] <- den * m2
} else {
if ( use.method==1 ) {
tmp <- .Fortran( "twpdf",
as.double(power),
as.double(phi[i]),
as.double(y[i]),
as.double(1),
as.integer( exact ),
as.integer( verbose ),
as.double(0),
as.integer(0),
as.double(0),
as.integer(0))
den <- tmp[[7]]
density[i] <- den * m1
} else {
tmp <- .Fortran( "twpdf",
as.double(power),
as.double(phi[i]/(y[i]^(2-power))),
as.double(1),
as.double(1),
as.integer( exact ),
as.integer( verbose ),
as.double(0),
as.integer(0),
as.double(0),
as.integer(0))
den <- tmp[[7]]
density[i] <- den * m3
}
}
}
}
density
}
dtweedie.jw.smallp <- function(y, phi, power ){
if ( power<1) stop("power must be between 1 and 2.")
if ( power>2) stop("power must be between 1 and 2.")
if ( any(phi<=0) ) stop("phi must be strictly positive.")
if ( any(y<=0) ) stop("y must be a strictly positive vector.")
p <- power
a <- ( 2-p ) / ( 1-p )
a1 <- 1 - a
r <- -a*log(y) + a*log(p-1) - a1*log(phi) -
log(2-p)
drop <- 37
logz <- max(r)
j.max <- max( y^( 2-p ) / ( phi * (2-p) ) )
j <- max( 1, j.max )
c <- logz + a1 + a*log(-a)
wmax <- a1*j.max
estlogw <- wmax
while(estlogw > (wmax-drop) ){
j <- j + 2
estlogw <- j*(c - a1*log(j))
}
hi.j <- ceiling(j)
logz <- min(r)
j.max <- min( y^( 2-power ) / ( phi * (2-power) ) )
j <- max( 1, j.max)
wmax <- a1*j.max
estlogw <- wmax
while ( ( estlogw > (wmax-drop) ) && ( j>=2) ) {
j <- max(1, j-2)
estlogw <- j*(c-a1*log(j))
}
lo.j <- max(1, floor(j))
j <- seq( lo.j, hi.j)
o <- matrix( 1, nrow=length(y))
g <- matrix(lgamma( j+1 ) + lgamma( -a*j ),
nrow=1, ncol=hi.j - lo.j + 1)
logj <- matrix(log(j),
nrow=1, ncol=hi.j - lo.j + 1)
og <- o %*% g
ologj <- o %*% logj
A <- outer(r,j) - og + ologj
m <- apply(A,1,max)
we <- exp( A - m )
sum.we <- apply( we,1,sum)
jw <- sum.we * exp( m )
list(lo=lo.j, hi=hi.j, jw=jw, j.max=j.max )
}
dtweedie.kv.bigp <- function(y, phi, power){
if ( power<2) stop("power must be greater than 2.")
if ( any(phi<=0) ) stop("phi must be positive.")
if ( any(y<=0) ) stop("y must be a strictly positive vector.")
if ( length(phi)>1) {
if ( length(phi)!=length(y) ) stop("phi must be scalar, or the same length as y.")
} else {
phi <- array( dim = length(y), phi )
}
p <- power
a <- ( 2 - p ) / ( 1 - p )
a1 <- 1 - a
r <- -a1*log(phi) - log(p-2) - a*log(y) +
a*log(p-1)
drop <- 37
logz <- max(r)
k.max <- max( y^(2-p) / ( phi * (p-2) ) )
k <- max( 1, k.max )
c <- logz + a1 + a*log(a)
vmax <- k.max * a1
estlogv <- vmax
while ( estlogv > (vmax - drop) ) {
k <- k+2
estlogv <- k*( c -a1*log(k) )
}
hi.k <- ceiling(k)
logz <- min(r)
k.max <- min( y^(2-p) / ( phi * (p-2) ) )
k <- max( 1, k.max )
c <- logz + a1 + a*log(a)
vmax <- k.max * a1
estlogv <- vmax
while ( (estlogv > (vmax-drop) ) && ( k>=2) ) {
k <- max(1, k-2)
estlogv <- k*( c - a1*log(k) )
}
lo.k <- max(1, floor(k) )
k <- seq(lo.k, hi.k)
o <- matrix( 1, nrow=length(y))
g <- matrix( lgamma( 1+a*k) - lgamma(1+k),
nrow=1, ncol=length(k) )
logk <- matrix( log(k),
nrow=1, ncol=length(k) )
og <- o %*% g
ologk <- o %*% logk
A <- outer(r,k) + og + ologk
C <- matrix( sin( -a*pi*k ) * (-1)^k,
nrow=1, ncol=length(k) )
C <- o %*% C
m <- apply(A, 1, max)
ve <- exp(A - m)
sum.ve <- apply( ve*C, 1, sum )
kv <- sum.ve * exp( m )
list(lo=lo.k, hi=hi.k, kv=kv, k.max=k.max )
}
qtweedie <- function(p, xi=NULL, mu, phi, power=NULL){
if ( is.null(power) & is.null(xi) ) stop("Either xi or power must be given\n")
xi.notation <- TRUE
if ( is.null(power) ) {
power <- xi
} else {
xi.notation <- FALSE
}
if ( is.null(xi) ) {
xi.notation <- FALSE
xi <- power
}
if ( xi != power ) {
cat("Different values for xi and power given; the value of xi used.\n")
power <- xi
}
index.par <- ifelse( xi.notation, "xi","p")
index.par.long <- ifelse( xi.notation, "xi","power")
if ( any(power<1) ) stop( paste(index.par.long, "must be greater than 1.\n") )
if ( any(phi <= 0) ) stop("phi must be positive.")
if ( any(p<0) ) stop("p must be between zero and one.\n")
if ( any(p>1) ) stop("p must be between zero and one.\n")
if ( any(mu <= 0) ) stop("mu must be positive.\n")
if ( length(mu)>1) {
if ( length(mu)!=length(p) ) stop("mu must be scalar, or the same length as p.\n")
} else {
mu <- array( dim=length(p), mu )
}
if ( length(phi)>1) {
if ( length(phi)!=length(p) ) stop("phi must be scalar, or the same length as p.\n")
} else {
phi <- array( dim=length(p), phi )
}
if ( length(power) == 1 ) {
if ( length(mu) > 1 ) {
power <- rep( power, length(mu) )
}
}
len <- length(p)
ans <- ans2 <- rep( NA, length=len )
if ( any(p==1) ) ans2[p==1] <- Inf
if ( any(p==0) ) ans2[p==0] <- 0
ans <- ans[ ( (p>0) & (p<1) ) ]
mu.vec <- mu[ ( (p>0) & (p<1) ) ]
phi.vec <- phi[ ( (p>0) & (p<1) ) ]
p.vec <- p[ ( (p>0) & (p<1) ) ]
for (i in (1:length(ans)) ) {
mu.1 <- mu.vec[i]
phi.1 <- phi.vec[i]
p.1 <- p.vec[i]
pwr <- power[i]
prob <- p.1
if ( pwr<2 ) {
qp <- qpois(prob, lambda=mu.1/phi.1)
if ( pwr == 1 ) ans[i] <- qp
}
qg <- qgamma(prob, rate=1/(phi.1*mu.1), shape=1/phi.1 )
if ( pwr==2 ) ans[i] <- qg
if ( (pwr>1) & ( pwr<2) ) {
start <- (qg - qp)*pwr + (2*qp - qg)
}
if ( pwr>2 ) start <- qg
if ( ( pwr>1) & (pwr<2) ) {
step <- dtweedie(y=0, mu=mu.1, phi=phi.1, power=pwr)
if ( prob <= step ) {
ans[i] <- 0
}
}
if ( is.na(ans[i]) ) {
pt2 <- function( q, mu, phi, pwr, p.given=prob ){
ptweedie(q=q, mu=mu, phi=phi, power=pwr ) - p.given
}
pt <- pt2( q=start, mu=mu.1, phi=phi.1, pwr=pwr, p.given=prob)
if ( pt == 0 ) ans2[i] <- start
if ( pt > 0 ) {
loop <- TRUE
start.2 <- start
while ( loop ) {
start.2 <- 0.5*start.2
if (pt2( q=start.2, mu.1, phi.1, pwr, p.given=prob )<0 ) loop=FALSE
}
}
if ( pt < 0) {
loop <- TRUE
start.2 <- start
while ( loop ) {
start.2 <- 1.5*(start.2 + 2)
if (pt2( q=start.2, mu.1, phi.1, pwr, p.given=prob )>0 ) loop=FALSE
}
}
out <- uniroot(pt2, c(start, start.2), mu=mu.1, phi=phi.1, p=pwr,
p.given=prob )
ans[i] <- uniroot(pt2, c(start, start.2), mu=mu.1, phi=phi.1, p=pwr,
p.given=prob, tol=0.000000000001 )$root
}
}
ans2[ is.na(ans2) ] <- ans
ans2
}
rtweedie <- function(n, xi=NULL, mu, phi, power=NULL){
if ( is.null(power) & is.null(xi) ) stop("Either xi or power must be given\n")
xi.notation <- TRUE
if ( is.null(power) ) {
power <- xi
} else {
xi.notation <- FALSE
}
if ( is.null(xi) ) {
xi.notation <- FALSE
xi <- power
}
if ( xi != power ) {
cat("Different values for xi and power given; the value of xi used.\n")
power <- xi
}
index.par <- ifelse( xi.notation, "xi","p")
index.par.long <- ifelse( xi.notation, "xi","power")
if ( any(power<1) ) stop( paste(index.par.long, "must be greater than 1.\n") )
if ( any(phi<=0) ) stop("phi must be positive.")
if ( n<1 ) stop("n must be a positive integer.\n")
if ( any(mu<=0) ) stop("mu must be positive.\n")
if ( length(mu)>1) {
if ( length(mu)!=n ) stop("mu must be scalar, or of length n.\n")
} else {
mu <- array( dim=n, mu )
}
if ( length(phi)>1) {
if ( length(phi)!=n ) stop("phi must be scalar, or of length n.\n")
} else {
phi <- array( dim=n, phi )
}
if (power==1) {
rt <- phi * rpois(n, lambda=mu / ( phi ) )
}
if (power==2) {
alpha <- (2-power)/(1-power)
gam <- phi * (power-1) * mu ^(power-1)
rt <- rgamma( n, shape=1/phi, scale=gam )
}
if ( power>2) {
rt <- qtweedie( runif(n), mu=mu ,phi=phi , power=power)
}
if ( (power>1) & (power<2) ) {
rt <- array( dim=n, NA)
lambda <- mu^(2-power) / ( phi * (2-power) )
alpha <- (2-power)/(1-power)
gam <- phi * (power-1) * mu ^(power-1)
N <- rpois(n, lambda=lambda)
for (i in (1:n) ){
rt[i] <- rgamma(1, shape = -N[i] * alpha, scale=gam[i])
}
}
as.vector(rt)
}
tweedie.profile <- function(formula, p.vec=NULL, xi.vec=NULL, link.power = 0,
data, weights, offset, fit.glm=FALSE,
do.smooth=TRUE, do.plot=FALSE,
do.ci=do.smooth, eps=1/6,
control=list( epsilon=1e-09, maxit=glm.control()$maxit, trace=glm.control()$trace ),
do.points=do.plot, method="inversion", conf.level=0.95,
phi.method=ifelse(method=="saddlepoint","saddlepoint","mle"), verbose=FALSE, add0=FALSE) {
if ( is.logical( verbose ) ) {
verbose <- as.numeric(verbose)
}
if (verbose >= 1 ) {
cat("---\n This function may take some time to complete;\n")
cat(" Please be patient. If it fails, try using method=\"series\"\n")
cat(" rather than the default method=\"inversion\"\n")
cat(" Another possible reason for failure is the range of p:\n")
cat(" Try a different input for p.vec\n---\n")
}
cl <- match.call()
mf <- match.call()
m <- match(c("formula", "data", "weights","offset"), names(mf), 0L)
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.response(mf, "numeric")
X <- if (!is.empty.model(mt))
model.matrix(mt, mf, contrasts)
else matrix(, NROW(Y), 0)
weights <- as.vector(model.weights(mf))
if (!is.null(weights) && !is.numeric(weights))
stop("'weights' must be a numeric vector")
offset <- as.vector(model.offset(mf))
if (!is.null(weights) && any(weights < 0))
stop("negative weights not allowed")
if (!is.null(offset)) {
if (length(offset) == 1)
offset <- rep(offset, NROW(Y))
else if (length(offset) != NROW(Y))
stop(gettextf("number of offsets is %d should equal %d (number of observations)",
length(offset), NROW(Y)), domain = NA)
}
xi.notation <- TRUE
if ( is.null(xi.vec) & !is.null(p.vec) ){
xi.vec <- p.vec
xi.notation <- FALSE
}
if ( is.null(p.vec) & !is.null(xi.vec) ){
p.vec <- xi.vec
xi.notation <- TRUE
}
if ( is.null( p.vec ) & is.null(xi.vec)) {
if ( any(Y==0) ){
p.vec <- seq(1.2, 1.8, by=0.1)
} else {
p.vec <- seq(1.5, 5, by=0.5)
}
xi.vec <- p.vec
xi.notation <- TRUE
}
index.par <- ifelse( xi.notation, "xi","p")
xi.fix <- any( xi.vec<=1 & xi.vec!=0, na.rm=TRUE)
if ( xi.fix ) {
xi.fix.these <- (xi.vec<=1 & xi.vec!=0)
xi.vec[ xi.fix.these ] <- NA
if ( length(xi.vec) == 0 ) {
stop(paste("No values of",index.par,"between 0 and 1, or below 0, are possible.\n"))
} else {
cat("Values of",index.par,"between 0 and 1 and less than zero have been removed: such values are not possible.\n")
}
}
if ( any( Y == 0 ) & any( (xi.vec >= 2) | (xi.vec <=0) ) ) {
xi.fix.these <- (xi.vec>=2 | xi.vec<=0)
xi.vec[ xi.fix.these ] <- NA
if ( length(xi.vec) == 0 ) {
stop(paste("When the response variable contains exact zeros, all values of",index.par,"must be between 1 and 2.\n"))
} else {
cat("When the response variable contains exact zeros, all values of",index.par,"must be between 1 and 2; other values have been removed.\n")
}
}
xi.vec <- xi.vec[ !is.na(xi.vec) ]
if ( do.smooth & (length(xi.vec) < 5) ) {
warning(paste("Smoothing needs at least five values of",index.par,".") )
do.smooth <- FALSE
do.ci <- FALSE
}
if ( (conf.level >= 1) | (conf.level <=0) ){
stop("Confidence level must be between 0 and 1.")
}
if ( !do.smooth & do.ci ) {
do.ci <- FALSE
warning("Confidence intervals only computed if do.smooth=TRUE\n")
}
if ( add0 ) {
p.vec <- c( 0, p.vec )
xi.vec <- c( 0, xi.vec )
}
cat(xi.vec,"\n")
ydata <- Y
model.x <- X
dtweedie.nlogl <- function(phi, y, mu, power) {
ans <- -2 * sum( log( dtweedie( y=y, mu=mu, phi=phi, power=power ) ) )
if ( is.infinite( ans ) ) {
ans <- sum( tweedie.dev(y=y, mu=mu, power=power) )/length( y )
}
attr(ans, "gradient") <- dtweedie.dldphi(y=y, mu=mu, phi=phi, power=power)
ans
}
xi.len <- length(xi.vec)
phi <- NaN
L <- array( dim = xi.len )
phi.vec <- L
b.vec <- L
c.vec <- L
mu.vec <- L
b.mat <- array( dim=c(xi.len, length(ydata) ) )
for (i in (1:xi.len)) {
if ( verbose>0) {
cat( paste(index.par," = ",xi.vec[i],"\n", sep="") )
} else {
cat(".")
}
p <- xi.vec[i]
phi.pos <- 1.0e2
bnd.neg <- -Inf
bnd.pos <- Inf
if (verbose==2) cat("* Fitting initial model:")
catch.possible.error <- try(
fit.model <- glm.fit( x=model.x, y=ydata, weights=weights, offset=offset,
control=control,
family=statmod::tweedie(var.power=p, link.power=link.power)),
silent = TRUE
)
skip.obs <- FALSE
if ( class( catch.possible.error )=="try-error" ) {
skip.obs <- TRUE
}
if( skip.obs ) {
warning(paste(" Problem near ",index.par," = ",p,"; this error reported:\n ",
catch.possible.error,
" Examine the data and function inputs carefully.") )
mu <- rep(NA, length(ydata) )
} else {
mu <- fitted( fit.model )
}
if (verbose==2) cat(" Done\n")
if (verbose>=1) cat("* Phi estimation, method: ", phi.method)
if( skip.obs ) {
if (verbose>=1) cat("; but skipped for this obs\n")
phi.est <- phi <- phi.vec[i] <- NA
} else {
if ( phi.method=="mle"){
if (verbose>=1) cat(" (using optimize): ")
phi.saddle <- sum( tweedie.dev(y=ydata, mu=mu, power=p) )/length( ydata )
if ( is.nan(phi) ) {
phi.est <- phi.saddle
} else {
phi.est <- phi
}
low.limit <- min( 0.001, phi.saddle/2)
if ( p!= 0 ) {
ans <- optimize(f=dtweedie.nlogl, maximum=FALSE, interval=c(low.limit, 10*phi.est),
power=p, mu=mu, y=ydata )
phi <- phi.vec[i] <- ans$minimum
} else {
phi <- phi.vec[i] <- sum( (ydata-mu)^2 ) / length(ydata)
}
if (verbose>=1) cat(" Done (phi =",phi.vec[i],")\n")
} else{
if (verbose>=1) cat(" (using mean deviance/saddlepoint): ")
phi <- phi.est <- phi.vec[i] <- sum( tweedie.dev(y=ydata, mu=mu, power=p) )/length( ydata )
if (verbose>=1) cat(" Done (phi =",phi,")\n")
}
}
if (verbose>=1) cat("* Computing the log-likelihood ")
if (verbose>=1) cat("(method =", method, "):")
if ( skip.obs ) {
if (verbose>=1) cat(" but skipped for this obs\n")
L[i] <- NA
} else {
if ( method=="saddlepoint") {
L[i] <- dtweedie.logl.saddle(y=ydata, mu=mu, power=p, phi=phi, eps=eps)
} else {
if (p==2) {
L[i] <- sum( log( dgamma( rate=1/(phi*mu), shape=1/phi, x=ydata ) ) )
} else {
if ( p == 1 ) {
if ( phi==1 ){
L[i] <- sum( log( dpois(x=ydata/phi, lambda=mu/phi ) ) )
} else {
y.on.phi <- ydata/phi
close.enough <- array( dim=length(y.on.phi))
for (i in (1:length(y.on.phi))){
if (isTRUE(all.equal(y.on.phi, as.integer(y.on.phi)))){
L[i] <- sum( log( dpois(x=round(y/phi), lambda=mu/phi ) ) )
} else {
L[i] <- 0
}
}
}
} else {
if ( p == 0 ) {
L[i] <- sum( dnorm(x=ydata, mean=mu, sd=sqrt(phi), log=TRUE) )
} else {
L[i] <- switch(
pmatch(method, c("interpolation","series", "inversion"),
nomatch=2),
"1" = dtweedie.logl( mu=mu, power=p, phi=phi, y=ydata),
"2" = sum( log( dtweedie.series( y=ydata, mu=mu, power=p, phi=phi) ) ),
"3" = sum( log( dtweedie.inversion( y=ydata, mu=mu, power=p, phi=phi) ) ) )
}
}
}
}
}
if (verbose>=1) {
cat(" Done: L =",L[i],"\n")
}
}
if ( verbose == 0 ) cat("Done.\n")
y <- NA
x <- NA
if ( do.smooth ) {
L.fix <- L
xi.vec.fix <- xi.vec
phi.vec.fix <- phi.vec
if ( any( is.nan(L) ) | any( is.infinite(L) ) | any( is.na(L) ) ) {
retain.these <- !( ( is.nan(L) ) | ( is.infinite(L) ) | ( is.na(L) ) )
xi.vec.fix <- xi.vec.fix[ retain.these ]
phi.vec.fix <- phi.vec.fix[ retain.these ]
L.fix <- L.fix[ retain.these ]
if (verbose>=1) cat("Smooth perhaps inaccurate--log-likelihood contains Inf or NA.\n")
}
if ( length( L.fix ) > 0 ) {
if (verbose>=1) cat(".")
if (verbose>=1) cat(" --- \n")
if (verbose>=1) cat("* Smoothing: ")
ss <- splinefun( xi.vec.fix, L.fix )
xi.smooth <- seq(min(xi.vec.fix), max(xi.vec.fix), length=50 )
L.smooth <- ss(xi.smooth )
if ( do.plot) {
keep.these <- is.finite(L.smooth) & !is.na(L.smooth)
L.smooth <- L.smooth[ keep.these ]
xi.smooth <- xi.smooth[ keep.these ]
if ( verbose>=1 & any( !keep.these ) ) {
cat(" (Some values of L are infinite or NA for the smooth; these are ignored)\n")
}
yrange <- range( L.smooth, na.rm=TRUE )
plot( yrange ~ range(xi.vec),
type="n",
las=1,
xlab=ifelse(xi.notation, expression(paste( xi," index")), expression(paste( italic(p)," index")) ),
ylab=expression(italic(L)))
lines( xi.smooth, L.smooth,
lwd=2)
rug( xi.vec )
if (do.points) {
points( L ~ xi.vec, pch=19)
}
if (add0) lines(xi.smooth[xi.smooth<1], L.smooth[xi.smooth<1], col="gray", lwd=2)
}
x <- xi.smooth
y <- L.smooth
} else {
cat(" No valid values of the likelihood computed: smooth aborted\n",
" Consider trying another value for the input method.\n")
}
} else {
if ( do.plot) {
keep.these <- is.finite(L) & !is.na(L)
xi.vec <- xi.vec[ keep.these ]
L <- L[ keep.these ]
phi.vec <- phi.vec[ keep.these ]
if ( verbose>=1 & any( keep.these ) ) {
cat(" Some values of L are infinite or NA, and hence ignored\n")
}
yrange <- range( L, na.rm=TRUE )
plot( yrange ~ range(xi.vec),
type="n",
las=1,
xlab=ifelse( xi.notation, expression(paste(xi," index")), expression(paste(italic(p)," index")) ),
ylab=expression(italic(L)))
lines( L ~ xi.vec, lwd=2)
rug( xi.vec )
if (do.points) {
points( L ~ xi.vec, pch=19)
}
}
x <- xi.vec
y <- L
}
if (verbose>=2) cat(" Done\n")
if ( do.smooth ){
if (verbose>=2) cat(" Estimating phi: ")
L.max <- max(y, na.rm=TRUE)
xi.max <- x[ y==L.max ]
if ( (xi.max > 0) & ( xi.max < 1 ) ) {
L.max <- max( c( y[xi.vec==0], y[xi.vec==1]) )
xi.max <- xi.vec[ L.max == y ]
cat("MLE of",index.par,"is between 0 and 1, which is impossible.",
"Instead, the MLE of",index.par,"has been set to",xi.max,
". Please check your data and the call to tweedie.profile().")
}
phi.1 <- 2 * max( phi.vec.fix, na.rm=TRUE )
phi.2 <- 0.5 * min( phi.vec.fix, na.rm=TRUE )
if ( phi.1 > phi.2 ) {
phi.hi <- phi.1
phi.lo <- phi.2
} else {
phi.hi <- phi.2
phi.lo <- phi.1
}
if (verbose>=2) cat(" Done\n")
if ( (xi.max==xi.vec[1]) | (xi.max==xi.vec[length(xi.vec)]) ) {
if ( xi.max==xi.vec[1]) phi.max <- phi.vec[1]
if ( xi.max==xi.vec[length(xi.vec)]) phi.max <- phi.vec[length(xi.vec)]
warning("True maximum possibly not detected.")
} else {
if ( phi.method=="saddlepoint"){
mu <- fitted( glm.fit( y=ydata, x=model.x, weights=weights, offset=offset,
family=statmod::tweedie(xi.max, link.power=link.power)))
phi.max <- sum( tweedie.dev(y=ydata, mu=mu, power=xi.max) )/length( ydata )
} else {
mu <- fitted( glm.fit( y=ydata, x=model.x, weights=weights, offset=offset,
family=statmod::tweedie(xi.max, link.power=link.power)))
phi.max <- optimize( f=dtweedie.nlogl, maximum=FALSE, interval=c(phi.lo, phi.hi ),
power=xi.max, mu=mu, y=ydata)$minimum
}
}
} else {
if (verbose>=2) cat(" Finding maximum likelihood estimates: ")
L.max <- max(L)
xi.max <- xi.vec [ L == L.max ]
phi.max <- phi.vec[ L == L.max ]
if (verbose>=2) cat(" Done\n")
}
if ( verbose >= 2 ) {
cat( "ML Estimates: ",index.par,"=",xi.max," with phi=",phi.max," giving L=",L.max,"\n")
cat(" ---\n")
}
ht <- L.max - ( qchisq(conf.level, 1) / 2 )
ci <- array( dim=2, NA )
if ( do.ci ) {
if (verbose==2) cat("* Finding confidence interval:")
if ( !do.smooth ) {
warning("Confidence interval may be very inaccurate without smoothing.\n")
y <- L
x <- xi.vec
}
if ( do.plot ) {
abline(h=ht, lty=2)
title( sub=paste("(",100*conf.level,"% confidence interval)", sep="") )
}
cond.left <- (y < ht ) & (x < xi.max )
if ( all(cond.left==FALSE) ) {
warning("Confidence interval cannot be found: insufficient data to find left CI.\n")
}else{
approx.left <- max( x[cond.left] )
index.left <- seq(1, length(cond.left) )
index.left <- index.left[x==approx.left]
left.left <- max( 1, index.left - 5)
left.right <- min( length(cond.left), index.left + 5)
ss.left <- splinefun( y[left.left:left.right], x[left.left: left.right] )
ci.new.left <- ss.left( ht )
ci[1] <- ci.new.left
}
cond.right <- (y < ht ) & (x > xi.max )
if ( all( cond.right==FALSE ) ) {
warning("Confidence interval cannot be found: insufficient data to find right CI.\n")
}else{
approx.right <- min( x[cond.right] )
index.right <- seq(1, length(cond.right) )
index.right <- index.right[x==approx.right]
right.left <- max( 1, index.right - 5)
right.right <- min( length(cond.left), index.right + 5)
ss.right <- splinefun( y[right.left:right.right], x[right.left: right.right] )
ci.new.right <- ss.right(ht )
ci[2] <- ci.new.right
}
if (verbose==2) cat(" Done\n")
}
if ( fit.glm ) {
out.glm <- glm.fit( x=model.x, y=ydata, weights=weights, offset=offset,
family=statmod::tweedie(var.power=xi.max, link.power=link.power) )
if ( xi.notation){
out <- list( y=y, x=x, ht=ht, L=L, xi=xi.vec, xi.max=xi.max, L.max=L.max,
phi=phi.vec, phi.max=phi.max, ci=ci, method=method, phi.method=phi.method,
glm.obj = out.glm)
} else {
out <- list( y=y, x=x, ht=ht, L=L, p=p.vec, p.max=xi.max, L.max=L.max,
phi=phi.vec, phi.max=phi.max, ci=ci, method=method, phi.method=phi.method,
glm.obj = out.glm)
}
} else {
if (xi.notation ){
out <- list( y=y, x=x, ht=ht, L=L, xi=xi.vec, xi.max=xi.max, L.max=L.max,
phi=phi.vec, phi.max=phi.max, ci=ci, method=method, phi.method=phi.method)
} else {
out <- list( y=y, x=x, ht=ht, L=L, p=p.vec, p.max=xi.max, L.max=L.max,
phi=phi.vec, phi.max=phi.max, ci=ci, method=method, phi.method=phi.method)
}
}
if ( verbose ) cat("\n")
invisible( out )
}
dtweedie.stable <- function(y, power, mu, phi)
{
if ( power<1) stop("power must be greater than 2.\n")
if ( any(phi<=0) ) stop("phi must be positive.")
if ( any(y<0) ) stop("y must be a non-negative vector.\n")
if ( any(mu<=0) ) stop("mu must be positive.\n")
if ( length(mu)>1) {
if ( length(mu)!=length(y) ) stop("mu must be scalar, or the same length as y.\n")
} else {
mu <- array( dim=length(y), mu )
}
if ( length(phi)>1) {
if ( length(phi)!=length(y) ) stop("phi must be scalar, or the same length as y.\n")
} else {
phi <- array( dim=length(y), phi )
}
density <- y
alpha <- (2-power)/(1-power)
beta <- 1
k <- 1
delta <- 0
gamma <- phi * (power-1) *
( 1/(phi*(power-2)) * cos( alpha * pi / 2 ) ) ^ (1/alpha)
ds <- stabledist::dstable(y, alpha=alpha, beta=beta, gamma=gamma, delta=delta, pm=k)
density <- exp((y*mu^(1-power)/(1-power)-mu^(2-power)/(2-power))/phi)*ds
density
}
tweedie.plot <- function(y, xi=NULL, mu, phi, type="pdf", power=NULL,
add=FALSE, ...) {
if ( is.null(power) & is.null(xi) ) stop("Either xi or power must be given\n")
xi.notation <- TRUE
if ( is.null(power) ) {
power <- xi
} else {
xi.notation <- FALSE
}
if ( is.null(xi) ) {
xi.notation <- FALSE
xi <- power
}
if ( xi != power ) {
cat("Different values for xi and power given; the value of xi used.\n")
power <- xi
}
index.par <- ifelse( xi.notation, "xi","p")
index.par.long <- ifelse( xi.notation, "xi","power")
if ( ( power < 0 ) | ( ( power > 0 ) & ( power < 1 ) ) ) {
stop( paste("Plots cannot be produced for",index.par.long,"=",power,"\n") )
}
is.pg <- ( power > 1 ) & ( power < 2 )
if ( type=="pdf") {
fy <- dtweedie( y=y, power=power, mu=mu, phi=phi)
} else {
fy <- ptweedie( q=y, power=power, mu=mu, phi=phi)
}
if ( !add ) {
if ( is.pg ) {
plot( range(fy) ~ range( y ),
type="n", ...)
if ( any( y==0 ) ) {
points( fy[y==0] ~ y[y==0], pch=19, ... )
}
if ( any( y>0 ) ) {
lines( fy[y>0] ~ y[y>0], pch=19, ... )
}
} else {
plot( range(fy) ~ range( y ),
type="n", ...)
lines( fy ~ y, pch=19, ... )
}
} else {
if ( is.pg ) {
if ( any( y==0 ) ) {
points( fy[y==0] ~ y[y==0], pch=19, ... )
}
if ( any( y>0 ) ) {
lines( fy[y>0] ~ y[y>0], pch=19, ... )
}
} else {
lines( fy ~ y, pch=19, ... )
}
}
return(invisible(list(y=fy, x=y) ))
}
AICtweedie <- function( glm.obj, dispersion=NULL, k=2, verbose=TRUE){
wt <- glm.obj$prior.weights
n <- length(glm.obj$residuals)
edf <- glm.obj$rank
mu <- fitted( glm.obj )
y <- glm.obj$y
p <- get("p", envir = environment(glm.obj$family$variance))
if ( is.null(dispersion)) {
if (p==1 & verbose) message("*** Tweedie index power = 1: Consider using dispersion=1 in call to AICtweedie().\n")
dev <- deviance(glm.obj)
disp <- dev/sum(wt)
edf <- edf+1
} else {
disp <- dispersion
}
den <- dtweedie( y=y, mu=mu, phi=disp, power=p)
AIC <- -2*sum( log(den) * wt)
return( AIC + k*(edf) )
}
tweedie.convert <- function(xi=NULL, mu, phi, power=NULL){
if ( is.null(power) & is.null(xi) ) stop("Either xi or power must be given\n")
xi.notation <- TRUE
if ( is.null(power) ) {
if ( !is.numeric(xi)) stop("xi must be numeric.")
power <- xi
} else {
xi.notation <- FALSE
}
if ( is.null(xi) ) {
if ( !is.numeric(power)) stop("power must be numeric.")
xi.notation <- FALSE
xi <- power
}
if ( xi != power ) {
cat("Different values for xi and power given; the value of xi used.\n")
power <- xi
}
index.par <- ifelse( xi.notation, "xi","p")
index.par.long <- ifelse( xi.notation, "xi","power")
if ( power<1) stop( paste(index.par.long, "must be greater than 1.\n") )
if ( power>=2) stop( paste(index.par.long, "must be less than 2.\n") )
if ( any(phi<=0) ) stop("phi must be positive.")
if ( any(mu<=0) ) stop("mu must be positive.\n")
if( length(mu) != length(phi) ){
if ( length(mu) == 1 ) mu <- array(dim=length(phi), mu )
if ( length(phi) == 1 ) phi <- array(dim=length(mu), phi )
}
if( length(mu) != length(phi) ) stop("phi and mu must be scalars, or the same length.\n")
lambda <- ( mu^(2 - xi) ) / ( phi * (2 - xi) )
alpha <- (2 - xi) / (xi - 1)
gam <- phi * (xi - 1) * mu^(xi - 1)
p0 <- exp( -lambda )
phi.g <- (2 - xi) * (xi - 1) * phi^2 * mu^( 2 * (xi-1) )
mu <- gam/phi
list( poisson.lambda = lambda,
gamma.shape = alpha,
gamma.scale = gam,
p0 = p0,
gamma.mean = mu,
gamma.phi = phi.g )
} |
cgraph <- function(ev,cbinit=FALSE,mindist=FALSE) {
if (cbinit) {
diag(ev$m[,]) <- 1
diag(ev$prod1[,]) <- 1
ev$k <- nrow(ev$m) - 1
ev$dists <- ev$m
ev$connected <- FALSE
if (mindist && ev$squaring)
stop("squaring cannot be used with the mindist option")
return()
}
if (ev$i %% 2 == 1) prd <- ev$prod2 else prd <- ev$prod1
if (all(prd > 0)) {
ev$connected <- TRUE
ev$stop <- TRUE
}
if (mindist) {
tmp <- prd[,] > 0
ev$dists[tmp & ev$dists == 0] <- ev$i + 1
}
}
eig <- function(ev,cbinit=FALSE,x=NULL,eps=1e-08) {
if (cbinit) {
if (is.null(x))
x <- rep(1,nrow(ev$m))
ev$x <- x
ev$oldx <- x
ev$eps <- eps
return()
}
ev$x <- ev$x / normvec(ev$x)
cmd <- ev$genmulcmd("ev$m","ev$x","ev$x")
eval(parse(text=cmd))
diff <- normvec(ev$x - ev$oldx)
if (diff / sum(abs(ev$x)) < ev$eps) ev$stop <- TRUE
ev$oldx <- ev$x
}
mc <- function(ev,cbinit=FALSE,eps=1e-08) {
if (cbinit) {
return()
}
diff <- norm(ev$prod1 - ev$prod2)
if (ev$i %% 2 == 1) prd <- ev$prod2 else prd <- ev$prod1
if (diff / norm(prd) < eps) {
ev$stop <- TRUE
ev$pivec <- colMeans(prd)
}
}
mexp <- function(ev,cbinit=FALSE,eps=1e-08) {
if (cbinit) {
if (ev$squaring) stop("squaring not allowed with mexp")
ev$esum <- diag(nrow(ev$m)) + ev$m
ev$esumold <- ev$esum
return()
}
if (ev$i %% 2 == 1) prd <- ev$prod2 else prd <- ev$prod1
ev$esum <- ev$esum + (1/factorial(ev$i+1)) * prd
diff <- norm(ev$esum - ev$esumold)
if (diff / norm(ev$esum) < eps) {
ev$stop <- TRUE
}
ev$esumold <- ev$esum
} |
convert2igraph <- function (A, neural = FALSE)
{
net <- igraph::as.igraph(qgraph::qgraph(A,DoNotPlot=TRUE))
igraph::vertex_attr(net, "name") <- V(net)$label
return(net)
} |
modelProfile <- function(formula,
data,
groups = 10,
group_label = c("I", "D"),
digits_numeric = 1,
digits_factor = 4,
exclude_na = FALSE,
LaTex = FALSE) {
if (!inherits(formula, "formula"))
stop("uplift: Method is only for formula objects.")
if (!groups %in% c(5, 10, 20))
stop("uplift: groups must be either 5, 10 or 20. Aborting...")
if (!tolower(group_label) %in% c("i", "d"))
stop("uplift: group_label must be either 'I' or 'D'. Aborting...")
mf <- match.call(expand.dots = FALSE)
args <- match(c("formula", "data"),
names(mf), 0L)
mf <- mf[c(1L, args)]
mf$drop.unused.levels <- TRUE
mf$na.action <- na.pass
mf[[1L]] <- as.name("model.frame")
mf <- eval(mf, parent.frame())
mt <- attr(mf, "terms")
data_class <- attributes(mt)$dataClasses[-1]
if (!all(unique(data_class) %in% c("numeric", "factor", "ordered")))
stop("uplift: variable types in formula must be either numeric, integer, factor or ordered. Aborting...")
num_vars <- which(data_class == "numeric")
fac_vars <- which(data_class %in% c("factor", "ordered"))
num_var_names <- attributes(mt)$term.labels[num_vars]
fac_var_names <- attributes(mt)$term.labels[fac_vars]
resp_var_name <- names(attributes(mt)$dataClasses[1])
attr(mt, "intercept") <- 0
Y <- model.response(mf, "any")
if (length(dim(Y)) == 1L) {
nm <- rownames(Y)
dim(Y) <- NULL
if (!is.null(nm))
names(Y) <- nm
}
if (!is.numeric(Y))
stop("uplift: the LHS of the model formula must be a numeric vector. Aborting...")
if (group_label == "I")
rank.Y <- rank(Y) else rank.Y <- rank(-Y)
Group <- cut(rank.Y, breaks = quantile(rank.Y, probs = seq(0, 1, 1/groups)),
labels = 1:groups, include.lowest = TRUE)
dframe <- data.frame(mf, Group)
if (exclude_na) dframe_out <-"na.omit(dframe)" else dframe_out <-"dframe"
if (length(num_vars) != 0L) t1 <- paste("+", paste(num_var_names, collapse = " + ")) else
t1 <- ""
if (length(fac_vars) != 0L) {t2 <- paste("+ Format(digits=", digits_factor, ") * ((",
paste("Factor(", fac_var_names, ")", sep = "", collapse = " + "),
") * ",
"(Pctn. = Percent('col')))", sep = "")} else {
t2 <- ""}
tab.form <- paste("tabular((n=1) + Format(digits=", digits_numeric, ")", " * ((",
resp_var_name,
t1, ") * (Avg. = mean))", t2,
" ~ Justify(c) * (Group + 1),",
" data = ", dframe_out, ")", sep ="")
if (LaTex) tab.form <- paste("latex(", tab.form, ")", sep ="")
res <- eval(parse(text=tab.form))
return(res)
}
|
path_script_default <- function() {
"_targets.R"
}
path_script_r <- function(path_script) {
paste0(tools::file_path_sans_ext(path_script), "_r")
}
path_script_r_globals_dir <- function(path_script) {
file.path(path_script_r(path_script), "globals")
}
path_script_r_globals <- function(path_script, name) {
file.path(path_script_r_globals_dir(path_script), paste0(name, ".R"))
}
path_script_r_targets_dir <- function(path_script) {
file.path(path_script_r(path_script), "targets")
}
path_script_r_targets <- function(path_script, name) {
file.path(path_script_r_targets_dir(path_script), paste0(name, ".R"))
}
path_store_default <- function() {
"_targets"
}
path_gitignore <- function(path_store) {
file.path(path_store, ".gitignore")
}
path_objects <- function(path_store, name) {
file.path(path_objects_dir(path_store), name)
}
path_objects_dir <- function(path_store) {
file.path(path_store, "objects")
}
path_objects_dir_cloud <- function() {
file.path(path_store_default(), "objects", fsep = "/")
}
path_meta_dir <- function(path_store) {
file.path(path_store, "meta")
}
path_meta <- function(path_store) {
file.path(path_meta_dir(path_store), "meta")
}
path_progress <- function(path_store) {
file.path(path_meta_dir(path_store), "progress")
}
path_process <- function(path_store) {
file.path(path_meta_dir(path_store), "process")
}
path_scratch <- function(path_store, pattern = "") {
tempfile(pattern = pattern, tmpdir = path_scratch_dir(path_store))
}
path_scratch_dir <- function(path_store) {
file.path(path_store, "scratch")
}
path_scratch_del <- function(path_store) {
unlink(path_scratch_dir(path_store), recursive = TRUE)
}
path_user_dir <- function(path_store) {
file.path(path_store, "user")
}
path_workspace <- function(path_store, name) {
file.path(path_workspaces_dir(path_store), name)
}
path_workspaces_dir <- function(path_store) {
file.path(path_store, "workspaces")
} |
det_guard_width <- function(highriskzone, thresh_const = .5) {
if (class(highriskzone)[1] != "highriskzone")
stop("highriskzone has to be of class highriskzone!")
if (thresh_const < 0 | thresh_const >1)
stop("thres_const has to be in [0,1]")
if(is.null(highriskzone$covmatrix))
stop("highriskzone has to be estimated based on an intensity based approach and information on (estimated) kernel covariance is necessary")
cov_hat <- highriskzone$covmatrix
eigen_cov <- eigen(cov_hat)
cutval <- thresh_const * (1-highriskzone$nxprob) / highriskzone$nxprob * highriskzone$threshold
if (dmvnorm(c(0,0), c(0,0), cov_hat) < cutval) {
buffer_length <- 0
} else {
maj_axis_dir <- sqrt(eigen_cov$values[1]) * eigen_cov$vectors[,1]
mult_fac <- uniroot(function(x) dmvnorm(maj_axis_dir * x,
c(0,0), cov_hat) - cutval,
c(0, 2*max(cov_hat)))
buffer_length <- sqrt(sum((mult_fac$root * maj_axis_dir)^2))
}
buffer_length
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
eval = curl::has_internet()
)
library(stplanr)
library(osrm)
knitr::include_graphics("https://user-images.githubusercontent.com/1825120/86902789-577d1080-c106-11ea-91df-8d0180931562.png")
knitr::include_graphics("https://user-images.githubusercontent.com/1825120/86858225-2970df80-c0b8-11ea-8394-07f98f1c8e8a.png") |
apollo_checkArguments=function(apollo_probabilities=NA,apollo_randCoeff=NA,apollo_lcPars=NA){
if(is.function(apollo_probabilities)){
arguments = formals(apollo_probabilities)
if(!all(names(arguments)==c("apollo_beta", "apollo_inputs", "functionality"))) stop("The arguments for apollo_probabilities need to be apollo_beta, apollo_inputs and functionality")
} else if(!is.na(apollo_probabilities)) stop("The argument \"apollo_probabilities\" should be a function")
if(is.function(apollo_randCoeff)){
arguments = formals(apollo_randCoeff)
if(!all(names(arguments)==c("apollo_beta", "apollo_inputs"))) stop("The arguments for apollo_randCoeff need to be apollo_beta and apollo_inputs")
} else if(!is.na(apollo_randCoeff)) stop("The argument \"apollo_randCoeff\" should be a function")
if(is.function(apollo_lcPars)){
arguments = formals(apollo_lcPars)
if(!all(names(arguments)==c("apollo_beta", "apollo_inputs"))) stop("The arguments for apollo_lcPars need to be apollo_beta and apollo_inputs")
} else if(!is.na(apollo_lcPars)) stop("The argument \"apollo_lcPars\" should be a function")
return(invisible(TRUE))
} |
printHTMLProtocol <- function(testData,
fileName = "",
separateFailureList = TRUE,
traceBackCutOff=9,
testFileToLinkMap=function(x) x) {
if (!is(testData, "RUnitTestData"))
{
stop("Argument 'testData' must be of class 'RUnitTestData'.")
}
if (!is.character(fileName))
{
stop("Argument 'fileName' has to be of type character.")
}
if (length(fileName) != 1)
{
stop("Argument 'fileName' must contain exactly one element.")
}
if (!is.logical(separateFailureList))
{
stop("Argument 'separateFailureList' has to be of type logical.")
}
if (length(separateFailureList) != 1)
{
stop("Argument 'separateFailureList' must contain exactly one element.")
}
if (!is.numeric(traceBackCutOff))
{
stop("Argument 'traceBackCutOff' has to be of type logical.")
}
if (length(traceBackCutOff) != 1)
{
stop("Argument 'traceBackCutOff' must contain exactly one element.")
}
if (traceBackCutOff < 0 || traceBackCutOff > 100)
{
stop("Argument 'traceBackCutOff' out of valid range [0, 100].")
}
sop <- function(number, word, plext="s") {
ifelse(number == 1, paste(number, word),
paste(number, paste(word, plext, sep="")))
}
pr <- function(...) {
writeRaw(paste(...), htmlFile=fileName)
writeRaw("<br/>", htmlFile=fileName)
}
writeP <- function(string, para="") {
writeBeginTag("p", para=para, htmlFile=fileName)
writeRaw(string, htmlFile=fileName)
writeEndTag("p", htmlFile=fileName)
writeCR(htmlFile=fileName)
}
writeLi <- function(..., para="") {
writeBeginTag("li", para=para, htmlFile=fileName)
writeRaw(paste(...), htmlFile=fileName)
writeEndTag("li", htmlFile=fileName)
}
createTestFuncRef <- function(testSuite, srcFileName, testFuncName,
asAnchor=FALSE) {
tmp <- paste(testSuite, srcFileName, testFuncName, sep="_")
if(asAnchor) {
return(paste("
} else {
return(gsub("/", "_", tmp))
}
}
printTraceBack <- function(traceBack) {
if(length(traceBack) > 0) {
writeRaw("Call Stack:<br/>", htmlFile=fileName)
if(traceBackCutOff > length(testFuncInfo$traceBack)) {
writeRaw("(traceBackCutOff argument larger than length of trace back: full trace back printed)<br/>", htmlFile=fileName)
writeBeginTag("ol", htmlFile=fileName)
for(i in seq_along(traceBack)) {
writeBeginTag("li", htmlFile=fileName)
writeRaw(traceBack[i], htmlFile=fileName)
writeEndTag("li", htmlFile=fileName)
}
} else {
writeBeginTag("ol", htmlFile=fileName)
for(i in traceBackCutOff:length(traceBack)) {
writeBeginTag("li", htmlFile=fileName)
writeRaw(traceBack[i], htmlFile=fileName)
writeEndTag("li", htmlFile=fileName)
}
}
writeEndTag("ol", htmlFile=fileName)
}
}
errorStyle <- "color:red"
deactivatedStyle <- "color:black"
title <- paste("RUNIT TEST PROTOCOL", date(), sep="--")
writeHtmlHeader(title, htmlFile=fileName)
writeHtmlSection(title, 1, htmlFile=fileName)
if(length(testData) == 0) {
writeP(" no test cases :-(")
return(invisible(TRUE))
}
errInfo <- getErrors(testData)
writeP(paste("Number of test functions:", errInfo$nTestFunc))
if(errInfo$nDeactivated > 0) {
writeP(paste("Number of deactivated test functions:", errInfo$nDeactivated),
para=ifelse(errInfo$nDeactivated == 0, "", paste("style", deactivatedStyle, sep="=")))
}
writeP(paste("Number of errors:", errInfo$nErr),
para=ifelse(errInfo$nErr == 0, "", paste("style", errorStyle, sep="=")))
writeP(paste("Number of failures:", errInfo$nFail),
para=ifelse(errInfo$nFail == 0, "", paste("style", errorStyle, sep="=")))
writeHtmlSep(htmlFile=fileName)
writeHtmlSection(sop(length(testData), "Test suite"), 3, htmlFile=fileName)
if(errInfo$nDeactivated > 0) {
writeBeginTable(c("Name", "Test functions", "Deactivated", "Errors", "Failures"),
width="80%",
htmlFile=fileName,
columnWidth=c("20%", "20%", "20%", "20%", "20%"))
for(tsName in names(testData)) {
rowString <- c(paste("<a href=\"
testData[[tsName]]$nTestFunc,
testData[[tsName]]$nDeactivated,
testData[[tsName]]$nErr,
testData[[tsName]]$nFail)
rowCols <- c("", "",
ifelse(testData[[tsName]]$nDeactivated==0, "", "yellow"),
ifelse(testData[[tsName]]$nErr==0, "", "red"),
ifelse(testData[[tsName]]$nFail==0, "", "red"))
writeTableRow(row=rowString, bgcolor=rowCols, htmlFile=fileName)
}
writeEndTable(htmlFile=fileName)
}
else {
writeBeginTable(c("Name", "Test functions", "Errors", "Failures"),
width="60%",
htmlFile=fileName,
columnWidth=c("30%", "30%", "20%", "20%"))
for(tsName in names(testData)) {
rowString <- c(paste("<a href=\"
testData[[tsName]]$nTestFunc,
testData[[tsName]]$nErr,
testData[[tsName]]$nFail)
rowCols <- c("", "",
ifelse(testData[[tsName]]$nErr==0, "", "red"),
ifelse(testData[[tsName]]$nFail==0, "", "red"))
writeTableRow(row=rowString, bgcolor=rowCols, htmlFile=fileName)
}
writeEndTable(htmlFile=fileName)
}
writeHtmlSep(htmlFile=fileName)
if(separateFailureList && (errInfo$nErr > 0)) {
writeHtmlSection("Errors", 3, htmlFile=fileName)
writeBeginTable(c("Test suite : test function", "message"),
htmlFile=fileName,
columnWidth=c("30%", "70%"))
for(tsName in names(testData)) {
if(testData[[tsName]]$nErr > 0) {
srcFileRes <- testData[[tsName]]$sourceFileResults
srcFileNames <- names(srcFileRes)
for(i in seq_along(srcFileRes)) {
testFuncNames <- names(srcFileRes[[i]])
for(j in seq_along(testFuncNames)) {
funcList <- srcFileRes[[i]][[testFuncNames[j]]]
if(funcList$kind == "error") {
lnk <- paste("<a href=\"",
createTestFuncRef(tsName, srcFileNames[i],
testFuncNames[j], asAnchor=TRUE),
"\">",
paste(tsName, testFuncNames[j], sep=" : "),
"</a>", sep="")
writeTableRow(row=c(lnk, funcList$msg),
htmlFile=fileName)
}
}
}
}
}
writeEndTable(htmlFile=fileName)
writeHtmlSep(htmlFile=fileName)
}
if(separateFailureList && (errInfo$nFail > 0)) {
writeHtmlSection("Failures", 3, htmlFile=fileName)
writeBeginTable(c("Test suite : test function", "message"),
htmlFile=fileName,
columnWidth=c("30%", "70%"))
for(tsName in names(testData)) {
if(testData[[tsName]]$nFail > 0) {
srcFileRes <- testData[[tsName]]$sourceFileResults
srcFileNames <- names(srcFileRes)
for(i in seq_along(srcFileRes)) {
testFuncNames <- names(srcFileRes[[i]])
for(j in seq_along(testFuncNames)) {
funcList <- srcFileRes[[i]][[testFuncNames[j]]]
if(funcList$kind == "failure") {
lnk <- paste("<a href=\"",
createTestFuncRef(tsName, srcFileNames[i],
testFuncNames[j], asAnchor=TRUE),
"\">",
paste(tsName, testFuncNames[j], sep=" : "),
"</a>", sep="")
writeTableRow(row=c(lnk, funcList$msg),
htmlFile=fileName)
}
}
}
}
}
writeEndTable(htmlFile=fileName)
writeHtmlSep(htmlFile=fileName)
}
if(separateFailureList && (errInfo$nDeactivated > 0)) {
writeHtmlSection("Deactivated", 3, htmlFile=fileName)
writeBeginTable(c("Test suite : test function", "message"),
htmlFile=fileName,
columnWidth=c("30%", "70%"))
for(tsName in names(testData)) {
if(testData[[tsName]]$nDeactivated > 0) {
srcFileRes <- testData[[tsName]]$sourceFileResults
srcFileNames <- names(srcFileRes)
for(i in seq_along(srcFileNames)) {
testFuncNames <- names(srcFileRes[[i]])
for(j in seq_along(testFuncNames)) {
funcList <- srcFileRes[[i]][[testFuncNames[j]]]
if(funcList$kind == "deactivated") {
lnk <- paste("<a href=\"",
createTestFuncRef(tsName, srcFileNames[i],
testFuncNames[j], asAnchor=TRUE),
"\">",
paste(tsName, testFuncNames[j], sep=" : "),
"</a>", sep="")
writeTableRow(row=c(lnk, funcList$msg),
htmlFile=fileName)
}
}
}
}
}
writeEndTable(htmlFile=fileName)
writeHtmlSep(htmlFile=fileName)
}
writeHtmlSection("Details", 3, htmlFile=fileName)
for(tsName in names(testData)) {
tsList <- testData[[tsName]]
writeBeginTag("p", htmlFile=fileName)
writeBeginTag("a", para=paste("name=\"", tsName, "\"", sep=""),
htmlFile=fileName)
writeHtmlSection(paste("Test Suite:", tsName), 5, htmlFile=fileName)
writeEndTag("a", htmlFile=fileName)
pr("Test function regexp:", tsList$testFuncRegexp)
pr("Test file regexp:", tsList$testFileRegexp)
if(length(tsList$dirs) == 0) {
pr("No directories !")
}
else {
if(length(tsList$dirs) == 1) {
pr("Involved directory:")
}
else {
pr("Involved directories:")
}
for(dir in tsList$dirs) {
pr(dir)
}
res <- tsList$sourceFileResults
testFileNames <- names(res)
if(length(res) == 0) {
pr(" no test files")
}
else {
writeBeginTag("ul", htmlFile=fileName)
for(testFileName in testFileNames) {
testFuncNames <- names(res[[testFileName]])
if(length(testFuncNames) > 0) {
writeBeginTag("li", htmlFile=fileName)
writeLink(target=testFileToLinkMap(testFileName),
name=paste("Test file:", basename(testFileName)),
htmlFile=fileName)
writeBeginTag("ul", htmlFile=fileName)
for(testFuncName in testFuncNames) {
writeBeginTag("li", htmlFile=fileName)
testFuncInfo <- res[[testFileName]][[testFuncName]]
anchorName <- createTestFuncRef(tsName, testFileName, testFuncName)
writeBeginTag("a", para=paste("name=\"", anchorName, "\"", sep=""),
htmlFile=fileName)
if(testFuncInfo$kind == "success") {
pr(paste(testFuncName, ": (",testFuncInfo$checkNum, " checks) ... OK (", testFuncInfo$time,
" seconds)", sep=""))
writeEndTag("a", htmlFile=fileName)
}
else {
if(testFuncInfo$kind == "error") {
writeBeginTag("u", para=paste("style", errorStyle, sep="="),
htmlFile=fileName)
writeRaw(paste(testFuncName, ": ERROR !! ", sep=""),
htmlFile=fileName)
writeEndTag("u", htmlFile=fileName)
writeEndTag("a", htmlFile=fileName)
}
else if (testFuncInfo$kind == "failure") {
writeBeginTag("u", para=paste("style", errorStyle, sep="="),
htmlFile=fileName)
writeRaw(paste(testFuncName, ": FAILURE !! (check number ",
testFuncInfo$checkNum, ") ", sep=""),
htmlFile=fileName)
writeEndTag("u", htmlFile=fileName)
writeEndTag("a", htmlFile=fileName)
}
else if (testFuncInfo$kind == "deactivated") {
writeBeginTag("u", para=paste("style", deactivatedStyle, sep="="),
htmlFile=fileName)
writeRaw(paste(testFuncName, ": DEACTIVATED, ", sep=""),
htmlFile=fileName)
writeEndTag("a", htmlFile=fileName)
}
else {
writeLi(paste(testFuncName, ": unknown error kind", sep=""))
writeEndTag("a", htmlFile=fileName)
}
pr(testFuncInfo$msg)
printTraceBack(testFuncInfo$traceBack)
}
writeEndTag("li", htmlFile=fileName)
}
writeEndTag("ul", htmlFile=fileName)
}
writeEndTag("li", htmlFile=fileName)
}
writeEndTag("ul", htmlFile=fileName)
}
}
writeHtmlSep(htmlFile=fileName)
}
ver <- cbind(unlist(version))
ver <- rbind(ver, Sys.info()["nodename"])
rownames(ver)[dim(ver)[1]] <- "host"
colnames(ver) <- "Value"
rhome <- Sys.getenv("R_HOME")
gccVersion <- as.character(NA)
makeconfFile <- file.path(rhome, "etc", "Makeconf")
if (file.exists(makeconfFile) && identical(.Platform$OS.type, "unix")) {
gccVersion <- system(paste("cat ", makeconfFile," | grep \"^CXX =\" "),
intern=TRUE)
gccVersion <- sub("^CXX[ ]* =[ ]*", "", gccVersion)
}
ver <- rbind(ver, gccVersion)
rownames(ver)[dim(ver)[1]] <- "compiler"
writeHtmlTable(ver,
htmlFile=fileName,
border=0,
width="80%",
append=TRUE)
writeHtmlEnd(htmlFile=fileName)
return(invisible(TRUE))
} |
setMethodS3("getConstructorS3", "default", function(name, ...) {
if (!exists(name, mode="function")) {
throw("No such function found: ", name)
}
fcn <- get(name, mode="function")
if (isGenericS3(fcn)) {
throw("The function found is an S3 generic function: ", name)
}
fcn
}) |
.cgarchhessian = function(f, pars, arglist, fname)
{
cluster = arglist$cluster
dccN = arglist$dccN
arglist$returnType = "llh"
fx = f(pars, arglist)
.eps = .Machine$double.eps
n = length(pars)
h = .eps ^ (1/3) * pmax( abs( pars ), 1 )
xh = pars + h
h = xh - pars
ee = as.matrix( diag( h ) )
g = vector(mode = "numeric", length = n)
if( !is.null(cluster) ){
clusterEvalQ(cluster, require(rmgarch))
clusterExport(cluster, c("pars", "ee", "arglist", "n", "fname"),
envir = environment())
tmp = parLapply(cluster, as.list(1:n), fun = function(i){
tmpg = eval(parse(text = paste(fname, "( pars = pars + ee[, i], arglist)", sep = "")))
return( tmpg )
})
g = as.numeric( unlist(tmp) )
} else{
tmp = lapply(as.list(1:n), FUN = function(i){
if(arglist$verbose) cat(paste("Evaluating StepValue ",i," out of ",n,"\n",sep=""))
tmpg = f( pars = pars + ee[, i], arglist)
return( tmpg )
})
g = as.numeric( unlist(tmp) )
}
H = h %*% t( h )
if( !is.null(cluster) ){
clusterEvalQ(cluster, require(rmgarch))
clusterExport(cluster, c("pars", "H", "ee", "n", "dccN",
"g", "fx", "fname", "arglist"), envir = environment())
tmp = parLapply(cluster, as.list(1:n), fun = function(i){
Htmp = H
for(j in (n - dccN + 1):n){
if(i <= j){
Htmp[i, j] = eval(parse(text = paste("(",fname, "( pars = pars + ee[, i] + ee[, j], arglist) - g[i] - g[j] + fx) / Htmp[i, j]", sep = "")))
Htmp[j, i] = Htmp[i, j]
}
}
return(Htmp)
})
for(i in 1:n){
for(j in (n - dccN + 1):n){
if(i <= j){
H[i, j] = tmp[[i]][i, j]
H[j, i] = tmp[[i]][j, i]
}
}
}
} else{
tmp = lapply(as.list(1:n), FUN = function(i){
Htmp = H
for(j in (n - dccN + 1):n){
if(i <= j){
Htmp[i, j] = (f( pars = pars + ee[, i] + ee[, j], arglist) - g[i] - g[j] + fx) / Htmp[i, j]
Htmp[j, i] = Htmp[i, j]
}
}
return(Htmp)
})
for(i in 1:n){
for(j in (n - dccN + 1):n){
if(i <= j){
H[i, j] = tmp[[i]][i, j]
H[j, i] = H[i, j]
}
}
}
}
newH = H[(n - dccN + 1):n, ]
H = newH
return(H)
}
.cgarchmakefitmodel1 = function(f, arglist, timer, message, fname)
{
.eps = .Machine$double.eps
cluster = arglist$cluster
eval.se = arglist$eval.se
fitlist = arglist$fitlist
m = arglist$m
midx = arglist$midx
eidx = arglist$eidx
dccN = arglist$dccN
ipars = arglist$ipars
estidx = arglist$estidx
cnames = arglist$cnames
mpars = arglist$mpars
model = arglist$model
maxgarchOrder = model$maxgarchOrder
resids = residuals(fitlist)
sigmas = sigma(fitlist)
pars = mpars[which(eidx==1, arr.ind = TRUE)]
arglist$returnType = "ALL"
sol = f(pars, arglist)
likelihoods = sol$lik
loglikelihood = sol$llh
Rtout = sol$Rt
Qtout = sol$Qt
N = dim(resids)[1]
np = length(pars)
Ht = array( 0, dim = c(m, m, N) )
stdresid = matrix(0, nrow = N, ncol = m)
if( !is.null(cluster) ){
clusterExport(cluster, c("sigmas", "Rtout", "resids"), envir = environment())
tmp = parLapply(cluster, as.list(1:N), fun = function(i){
tmph = diag( sigmas[i, ] ) %*% Rtout[[i]] %*% diag( sigmas[i, ] )
zz = eigen( tmph )
sqrtzz = ( zz$vectors %*% diag( sqrt( zz$values ) ) %*% solve( zz$vectors ) )
tmpz = as.numeric( resids[i, ] %*% solve( sqrtzz ) )
return( list( H = tmph, Z = tmpz ) )
})
for(i in 1:N){
Ht[,,i] = tmp[[i]]$H
stdresid[i,] = tmp[[i]]$Z
}
} else{
tmp = lapply(as.list(1:N), FUN = function(i){
tmph = diag( sigmas[i, ] ) %*% Rtout[[i]] %*% diag( sigmas[i, ] )
zz = eigen( tmph )
sqrtzz = ( zz$vectors %*% diag( sqrt( zz$values ) ) %*% solve( zz$vectors ) )
tmpz = as.numeric( resids[i, ] %*% solve( sqrtzz ) )
return( list( H = tmph, Z = tmpz ) )
})
for(i in 1:N){
Ht[,,i] = tmp[[i]]$H
stdresid[i,] = tmp[[i]]$Z
}
}
arglist$stdresid = stdresid
arglist$Ht = Ht
if(eval.se){
A = zeros( np, np )
tidx = 1
for(i in 1:m){
cvar = fitlist@fit[[i]]@fit$cvar
workingsize = dim(cvar)[1]
A[(tidx:(tidx + workingsize - 1)), (tidx:(tidx + workingsize - 1))] = solve(cvar)
tidx = tidx + workingsize
}
if(arglist$verbose) cat("\n\nCalculating Standard Errors, this can take a while\n")
otherA = .cgarchhessian(f = f, pars = pars, arglist, fname)
A[(np - dccN + 1):np, ] = otherA
jointscores = zeros(N, np)
tidx = 1
for(i in 1:m){
cf = fitlist@fit[[i]]@model$pars[fitlist@fit[[i]]@model$pars[,4]==1,1]
workingsize = length(cf)
scx = fitlist@fit[[i]]@fit$scores
jointscores[,(tidx:(tidx + workingsize - 1))] = scx
tidx = tidx + workingsize
}
h = pmax( abs( ipars[estidx,1]/2 ), 1e-2 ) * .eps^(1/3)
hplus = ipars[estidx,1] + h
hminus = ipars[estidx,1] - h
likelihoodsplus = zeros( N, dccN )
likelihoodsminus = zeros( N, dccN )
zparsplus = zparsminus = pars
for(i in 1:dccN){
hparameters1 = ipars[estidx,1]
hparameters2 = ipars[estidx,1]
hparameters1[i] = hplus[i]
hparameters2[i] = hminus[i]
zparsplus[(np-dccN+1):np] = hparameters1
zparsminus[(np-dccN+1):np] = hparameters2
arglist$returnType = "lik"
LHT1 = f(pars = zparsplus, arglist)
LHT2 = f(pars = zparsminus, arglist)
likelihoodsplus[, i] = LHT1
likelihoodsminus[, i] = LHT2
}
sctemp = likelihoodsplus - likelihoodsminus
DCCscores = matrix(NA, ncol = dim(sctemp)[2], nrow = dim(sctemp)[1])
sdtemp = 2 * repmat( t( h ), N, 1 )
for(i in 1:dim(sctemp)[2]){
DCCscores[,i] = sctemp[,i] / sdtemp[,i]
}
jointscores[, (np-dccN+1):np] = DCCscores
B = cov( jointscores )
A = A/ (N)
dcccvar = ( solve( A ) %*% B %*% solve( A ) ) / N
se.coef = sqrt(diag(abs(dcccvar)))
tval = as.numeric( pars/se.coef )
pval = 2* ( 1 - pnorm( abs( tval ) ) )
matcoef = matrix(NA, nrow = length(pars), ncol = 4)
matcoef[, 1] = pars
matcoef[, 2] = se.coef
matcoef[, 3] = tval
matcoef[, 4] = pval
allnames = NULL
for(i in 1:m){
allnames = c(allnames, paste("[",cnames[i],"].", rownames(eidx[eidx[,i]==1,i, drop = FALSE]), sep = ""))
}
garchnames = allnames
dccnames = rownames(eidx[eidx[,m+1]==1,m+1, drop = FALSE])
if(!is.null(dccnames)){
allnames = c(garchnames, paste("[Joint]", rownames(eidx[eidx[,m+1]==1,m+1, drop = FALSE]), sep = ""))
} else{
allnames = garchnames
}
allnames = c(garchnames, paste("[Joint]", rownames(eidx[eidx[,m+1]==1,m+1, drop = FALSE]), sep = ""))
dimnames(matcoef) = list(allnames, c(" Estimate",
" Std. Error", " t value", "Pr(>|t|)"))
} else{
se.coef = rep(NA, length(pars))
tval = rep(NA, length(pars))
pval = rep(NA, length(pars))
matcoef = matrix(NA, nrow = length(pars), ncol = 4)
matcoef[, 1] = pars
allnames = NULL
for(i in 1:m){
allnames = c(allnames, paste("[",cnames[i],"].", rownames(eidx[eidx[,i]==1,i, drop = FALSE]), sep = ""))
}
garchnames = allnames
dccnames = rownames(eidx[eidx[,m+1]==1,m+1, drop = FALSE])
if(!is.null(dccnames)){
allnames = c(garchnames, paste("[Joint]", rownames(eidx[eidx[,m+1]==1,m+1, drop = FALSE]), sep = ""))
} else{
allnames = garchnames
}
allnames = c(garchnames, paste("[Joint]", rownames(eidx[eidx[,m+1]==1,m+1, drop = FALSE]), sep = ""))
dimnames(matcoef) = list(allnames, c(" Estimate",
" Std. Error", " t value", "Pr(>|t|)"))
dcccvar = NULL
jointscores = NULL
}
cfit = list()
cfit$coef = pars
names(cfit$coef) = allnames
cfit$matcoef = matcoef
cfit$garchnames = garchnames
cfit$dccnames = dccnames
cfit$cvar = dcccvar
cfit$scores = jointscores
cfit$H = Ht
cfit$stdresid = stdresid
cfit$timer = timer
cfit$convergence = 0
cfit$message = message
return( cfit )
}
.cgarchmakefitmodel2 = function(f, arglist, timer, message, fname)
{
.eps = .Machine$double.eps
cluster = arglist$cluster
eval.se = arglist$eval.se
fitlist = arglist$fitlist
m = arglist$m
midx = arglist$midx
eidx = arglist$eidx
ipars = arglist$ipars
estidx = arglist$estidx
cnames = arglist$cnames
mpars = arglist$mpars
model = arglist$model
method = model$modeldesc$cor.method
maxgarchOrder = model$maxgarchOrder
resids = residuals(fitlist)
sigmas = sigma(fitlist)
pars = mpars[which(eidx==1, arr.ind = TRUE)]
arglist$returnType = "ALL"
sol = f(pars, arglist)
likelihoods = sol$lik
loglikelihood = sol$llh
Rt = sol$R
N = dim(resids)[1]
np = length(pars)
Ht = array( 0, dim = c(m, m, N) )
stdresid = matrix(0, nrow = N, ncol = m)
if( !is.null(cluster) ){
clusterExport(cluster, c("sigmas", "Rt", "resids"), envir = environment())
tmp = parLapply(cluster, as.list(1:N), fun = function(i){
tmph = diag( sigmas[i, ] ) %*% Rt %*% diag( sigmas[i, ] )
zz = eigen( tmph )
sqrtzz = ( zz$vectors %*% diag( sqrt( zz$values ) ) %*% solve( zz$vectors ) )
tmpz = as.numeric( resids[i, ] %*% solve( sqrtzz ) )
return( list( H = tmph, Z = tmpz ) )
})
for(i in 1:N){
Ht[,,i] = tmp[[i]]$H
stdresid[i,] = tmp[[i]]$Z
}
} else{
tmp = lapply(as.list(1:N), FUN = function(i){
tmph = diag( sigmas[i, ] ) %*% Rt %*% diag( sigmas[i, ] )
zz = eigen( tmph )
sqrtzz = ( zz$vectors %*% diag( sqrt( zz$values ) ) %*% solve( zz$vectors ) )
tmpz = as.numeric( resids[i, ] %*% solve( sqrtzz ) )
return( list( H = tmph, Z = tmpz ) )
})
for(i in 1:N){
Ht[,,i] = tmp[[i]]$H
stdresid[i,] = tmp[[i]]$Z
}
}
arglist$stdresid = stdresid
arglist$Ht = Ht
if(eval.se){
if(method == "ML" || model$modeldesc$distribution == "mvt"){
dccN = arglist$npars
arglist$dccN = dccN
A = zeros( np, np )
tidx = 1
for(i in 1:m){
cvar = fitlist@fit[[i]]@fit$cvar
workingsize = dim(cvar)[1]
A[(tidx:(tidx + workingsize - 1)), (tidx:(tidx + workingsize - 1))] = solve(cvar)
tidx = tidx + workingsize
}
if(arglist$verbose) cat("\n\nCalculating Standard Errors, this can take a while\n")
if(dccN>0){
otherA = .cgarchhessian(f = f, pars = pars, arglist, fname)
A[(np - dccN + 1):np, ] = otherA
jointscores = zeros(N, np)
tidx = 1
for(i in 1:m){
cf = fitlist@fit[[i]]@model$pars[fitlist@fit[[i]]@model$pars[,4]==1,1]
workingsize = length(cf)
scx = fitlist@fit[[i]]@fit$scores
jointscores[,(tidx:(tidx + workingsize - 1))] = scx
tidx = tidx + workingsize
}
h = pmax( abs( ipars[estidx,1]/2 ), 1e-2 ) * .eps^(1/3)
hplus = ipars[estidx,1] + h
hminus = ipars[estidx,1] - h
likelihoodsplus = zeros( N, dccN )
likelihoodsminus = zeros( N, dccN )
zparsplus = zparsminus = pars
for(i in 1:dccN){
hparameters1 = ipars[estidx,1]
hparameters2 = ipars[estidx,1]
hparameters1[i] = hplus[i]
hparameters2[i] = hminus[i]
zparsplus[(np-dccN+1):np] = hparameters1
zparsminus[(np-dccN+1):np] = hparameters2
arglist$returnType = "lik"
LHT1 = f(pars = zparsplus, arglist)
LHT2 = f(pars = zparsminus, arglist)
likelihoodsplus[, i] = LHT1
likelihoodsminus[, i] = LHT2
}
sctemp = likelihoodsplus - likelihoodsminus
DCCscores = matrix(NA, ncol = dim(sctemp)[2], nrow = dim(sctemp)[1])
sdtemp = 2 * repmat( t( h ), N, 1 )
for(i in 1:dim(sctemp)[2]){
DCCscores[,i] = sctemp[,i] / sdtemp[,i]
}
jointscores[, (np-dccN+1):np] = DCCscores
B = cov( jointscores )
A = A/ (N)
dcccvar = ( solve( A ) %*% B %*% solve( A ) ) / N
se.coef = sqrt(diag(abs(dcccvar)))
tval = as.numeric( pars/se.coef )
pval = 2* ( 1 - pnorm( abs( tval ) ) )
matcoef = matrix(NA, nrow = length(pars), ncol = 4)
matcoef[, 1] = pars
matcoef[, 2] = se.coef
matcoef[, 3] = tval
matcoef[, 4] = pval
allnames = NULL
for(i in 1:m){
allnames = c(allnames, paste("[",cnames[i],"].", rownames(eidx[eidx[,i]==1,i, drop = FALSE]), sep = ""))
}
garchnames = allnames
dccnames = rownames(eidx[eidx[,m+1]==1,m+1, drop = FALSE])
if(!is.null(dccnames)){
allnames = c(garchnames, paste("[Joint]", rownames(eidx[eidx[,m+1]==1,m+1, drop = FALSE]), sep = ""))
} else{
allnames = garchnames
}
dimnames(matcoef) = list(allnames, c(" Estimate"," Std. Error", " t value", "Pr(>|t|)"))
} else{
jointscores = zeros(N, np)
tidx = 1
for(i in 1:m){
cf = fitlist@fit[[i]]@model$pars[fitlist@fit[[i]]@model$pars[,4]==1,1]
workingsize = length(cf)
scx = fitlist@fit[[i]]@fit$scores
jointscores[,(tidx:(tidx + workingsize - 1))] = scx
tidx = tidx + workingsize
}
B = cov( jointscores )
A = A/ (N)
dcccvar = ( solve( A ) %*% B %*% solve( A ) ) / N
se.coef = sqrt(diag(abs(dcccvar)))
tval = as.numeric( pars/se.coef )
pval = 2* ( 1 - pnorm( abs( tval ) ) )
matcoef = matrix(NA, nrow = length(pars), ncol = 4)
matcoef[, 1] = pars
matcoef[, 2] = se.coef
matcoef[, 3] = tval
matcoef[, 4] = pval
allnames = NULL
for(i in 1:m){
allnames = c(allnames, paste("[",cnames[i],"].", rownames(eidx[eidx[,i]==1,i, drop = FALSE]), sep = ""))
}
garchnames = allnames
dccnames = rownames(eidx[eidx[,m+1]==1,m+1, drop = FALSE])
if(!is.null(dccnames)){
allnames = c(garchnames, paste("[Joint]", rownames(eidx[eidx[,m+1]==1,m+1, drop = FALSE]), sep = ""))
} else{
allnames = garchnames
}
dimnames(matcoef) = list(allnames, c(" Estimate", " Std. Error", " t value", "Pr(>|t|)"))
}
} else{
A = zeros( np, np )
tidx = 1
for(i in 1:m){
cvar = fitlist@fit[[i]]@fit$cvar
workingsize = dim(cvar)[1]
A[(tidx:(tidx + workingsize - 1)), (tidx:(tidx + workingsize - 1))] = solve(cvar)
tidx = tidx + workingsize
}
jointscores = zeros(N, np)
tidx = 1
for(i in 1:m){
cf = fitlist@fit[[i]]@model$pars[fitlist@fit[[i]]@model$pars[,4]==1,1]
workingsize = length(cf)
scx = fitlist@fit[[i]]@fit$scores
jointscores[,(tidx:(tidx + workingsize - 1))] = scx
tidx = tidx + workingsize
}
B = cov( jointscores )
A = A/ (N)
dcccvar = ( solve( A ) %*% B %*% solve( A ) ) / N
se.coef = sqrt(diag(abs(dcccvar)))
tval = as.numeric( pars/se.coef )
pval = 2* ( 1 - pnorm( abs( tval ) ) )
matcoef = matrix(NA, nrow = length(pars), ncol = 4)
matcoef[, 1] = pars
matcoef[, 2] = se.coef
matcoef[, 3] = tval
matcoef[, 4] = pval
allnames = NULL
for(i in 1:m){
allnames = c(allnames, paste("[",cnames[i],"].", rownames(eidx[eidx[,i]==1,i, drop = FALSE]), sep = ""))
}
garchnames = allnames
dccnames = NULL
dimnames(matcoef) = list(allnames, c(" Estimate", " Std. Error", " t value", "Pr(>|t|)"))
}
} else{
se.coef = rep(NA, length(pars))
tval = rep(NA, length(pars))
pval = rep(NA, length(pars))
matcoef = matrix(NA, nrow = length(pars), ncol = 4)
matcoef[, 1] = pars
allnames = NULL
for(i in 1:m){
allnames = c(allnames, paste("[",cnames[i],"].", rownames(eidx[eidx[,i]==1,i, drop = FALSE]), sep = ""))
}
garchnames = allnames
dccnames = rownames(eidx[eidx[,m+1]==1,m+1, drop = FALSE])
if(!is.null(dccnames)){
allnames = c(garchnames, paste("[Joint]", rownames(eidx[eidx[,m+1]==1,m+1, drop = FALSE]), sep = ""))
} else{
allnames = garchnames
}
dimnames(matcoef) = list(allnames, c(" Estimate", " Std. Error", " t value", "Pr(>|t|)"))
dcccvar = NULL
jointscores = NULL
}
cgarchfit = list()
cgarchfit$coef = pars
names(cgarchfit$coef) = allnames
cgarchfit$matcoef = matcoef
cgarchfit$garchnames = garchnames
cgarchfit$dccnames = dccnames
cgarchfit$cvar = dcccvar
cgarchfit$scores = jointscores
cgarchfit$H = Ht
cgarchfit$stdresid = stdresid
cgarchfit$timer = timer
cgarchfit$convergence = 0
cgarchfit$message = message
return( cgarchfit )
} |
monitor_downloadDaily <- function(
parameter='PM2.5',
baseUrl='https://haze.airfire.org/monitoring/latest/RData/',
dataDir = "~/Data/monitoring/RData",
...
) {
filename <- paste0("airnow_", parameter, "_latest45.RData")
downloadDataFile(filename, baseUrl, dataDir, ...)
filename <- paste0("airsis_", parameter, "_latest45.RData")
downloadDataFile(filename, baseUrl, dataDir, ...)
filename <- paste0("wrcc_", parameter, "_latest45.RData")
downloadDataFile(filename, baseUrl, dataDir, ...)
return(invisible(NULL))
} |
ly_hist <- function(
fig, x, data = figure_data(fig),
breaks = "Sturges", freq = TRUE, include.lowest = TRUE, right = TRUE,
color = NULL, alpha = 1,
lname = NULL, lgroup = NULL, ...
) {
validate_fig(fig, "ly_hist")
args <- sub_names(fig, data,
grab(
x,
color,
alpha,
lname,
lgroup,
dots = lazy_dots(...)
)
)
tryres <- try(identity(x), silent = TRUE)
if (inherits(tryres, "histogram")) {
hh <- x
args$info$x_name <- x$xname
} else {
hh <- graphics::hist.default(x = args$data[[2]], breaks = breaks,
include.lowest = include.lowest, right = right, plot = FALSE)
args$info$x_name <- args$info$y_name
}
args$info$y_name <- ifelse(freq, "Frequency", "Density")
args$params <- resolve_color_alpha(args$params, has_line = TRUE, has_fill = TRUE,
fig$x$spec$layers[[args$info$lgroup]], theme = fig$x$spec$theme)
y <- if (freq) {
hh$counts
} else {
hh$density
}
do.call(ly_rect, c(
list(
fig = fig,
xleft = hh$breaks[-length(hh$breaks)],
xright = hh$breaks[-1], ytop = y, ybottom = 0,
xlab = args$info$x_name, ylab = args$info$y_name,
lname = args$info$lname, lgroup = args$info$lgroup
),
args$params
))
}
ly_density <- function(
fig, x, data = figure_data(fig),
bw = "nrd0", adjust = 1,
kernel = c("gaussian", "epanechnikov", "rectangular", "triangular",
"biweight", "cosine", "optcosine"),
weights = NULL, window = kernel, n = 512, cut = 3, na.rm = FALSE,
color = "black", alpha = 1, width = 1, type = 1,
legend = NULL, lname = NULL, lgroup = NULL,
...
) {
validate_fig(fig, "ly_density")
args <- sub_names(fig, data,
grab(
x,
color,
alpha,
width,
type,
legend,
lname,
lgroup,
dots = lazy_dots(...)
)
)
args$data$x <- args$data[[2]]; args$data[[2]] <- NULL
args$info$x_name <- args$info$y_name
args$info$y_name <- "Density"
if (length(unique(args$params$color)) == 1)
args$params$color <- subset_with_attributes(args$params$color, 1)
if (length(unique(args$params$type)) == 1)
args$params$type <- subset_with_attributes(args$params$type, 1)
if (length(unique(args$params$width)) == 1)
args$params$width <- subset_with_attributes(args$params$width, 1)
args$params <- resolve_line_args(fig, args$params)
dd <- stats::density.default(x = args$data$x, bw = bw, adjust = adjust,
kernel = kernel, n = n, cut = 3, na.rm = na.rm)
do.call(ly_lines, c(
list(
fig = fig,
x = dd$x, y = dd$y,
xlab = args$info$x_name, ylab = args$info$y_name
), args$params)
)
}
ly_quantile <- function(
fig, x, group = NULL, data = figure_data(fig),
probs = NULL, distn = stats::qunif, ncutoff = 200,
color = NULL, alpha = 1,
legend = TRUE, lname = NULL, lgroup = NULL,
...
) {
validate_fig(fig, "ly_quantile")
args <- sub_names(fig, data,
grab(
x,
group,
color,
alpha,
legend,
lname,
lgroup,
dots = lazy_dots(...)
)
)
args$data$x <- args$data[[2]]
args$info$x_name <- "f-value"
if (is.null(args$info$group)) {
args$info$group <- rep(1, length(args$data$x))
}
na_idx <- is.na(args$data$x)
args$data$x <- args$data$x[!na_idx]
args$info$group <- args$info$group[!na_idx]
idx <- split(seq_along(args$data$x), args$info$group)
if (length(idx) == 1) {
if (is.logical(args$info$legend))
args$info$legend <- NULL
}
for (ii in idx) {
if (length(ii) > 0) {
if (is.null(probs)) {
if (length(ii) > ncutoff) {
cur_probs <- stats::ppoints(ncutoff)
qq <- stats::quantile(args$data$x[ii], cur_probs, names = FALSE, na.rm = TRUE)
} else {
cur_probs <- stats::ppoints(length(args$data$x[ii]))
qq <- sort(args$data$x[ii])
}
} else {
cur_probs <- probs
qq <- stats::quantile(args$data$x[ii], cur_probs, names = FALSE, na.rm = TRUE)
}
ff <- distn(cur_probs)
cur_legend <- NULL
if (is.logical(args$info$legend)) {
if (args$info$legend) {
cur_legend <- args$info$group[[ii[1]]]
}
} else {
cur_legend <- args$info$legend
}
fig <- do.call(ly_points, c(
list(
fig = fig, x = ff, y = qq,
xlab = args$info$x_name, ylab = args$info$y_name,
lgroup = args$info$lgroup, legend = cur_legend
),
args$params
))
}
}
fig
}
ly_boxplot <- function(
fig, x, y = NULL, data = figure_data(fig),
width = 0.9, coef = 1.5,
color = "blue", alpha = 1,
outlier_glyph = 1, outlier_size = 10,
lname = NULL, lgroup = NULL,
...
) {
validate_fig(fig, "ly_boxplot")
args <- sub_names(fig, data,
grab(
x, y,
color,
alpha,
lname,
lgroup,
dots = lazy_dots(...)
)
)
if (missing(y)) {
args$data$x <- args$data$y
args$data$y <- NULL
args$info$x_name <- args$info$y_name
args$info$y_name <- NULL
}
if (is.factor(args$data$x)) {
args$data$x <- as.character(args$data$x)
}
if (is.factor(args$data$y)) {
args$data$y <- as.character(args$data$y)
}
args$params <- resolve_color_alpha(args$params, has_line = TRUE,
has_fill = TRUE, theme = fig$x$spec$theme)
x <- args$data$x
y <- args$data$y
group_is_numeric <- FALSE
if (is.null(y)) {
x_name <- " "
y_name <- args$info$x_name
group <- rep(x_name, length(x))
} else {
num_ind <- c(is.numeric(x), is.numeric(y))
if (all(num_ind)) {
group_is_numeric <- TRUE
message(
"both x and y are numeric -- choosing numeric variable based on ",
"which has the most unique values")
if (length(unique(x)) > length(unique(y))) {
x_name <- args$info$y_name
y_name <- args$info$x_name
group <- as.character(y)
} else {
x_name <- args$info$x_name
y_name <- args$info$y_name
group <- as.character(x)
x <- y
}
} else if (num_ind[1]) {
x_name <- args$info$y_name
y_name <- args$info$x_name
group <- y
} else if (num_ind[2]) {
x_name <- args$info$x_name
y_name <- args$info$y_name
group <- x
x <- y
} else {
stop("At least one of 'x' or 'y' should be numeric for ly_boxplot.")
}
}
idx <- split(seq_along(x), group)
for (ii in seq_along(idx)) {
bp <- grDevices::boxplot.stats(x = x[idx[[ii]]], coef = coef)
gp <- group[idx[[ii]][1]]
gpl <- paste(gp, ":0.4", sep = "")
gpr <- paste(gp, ":0.6", sep = "")
hgt1 <- bp$stats[3] - bp$stats[2]
md1 <- hgt1 / 2 + bp$stats[2]
hgt2 <- bp$stats[4] - bp$stats[3]
md2 <- hgt2 / 2 + bp$stats[3]
fig <- ly_crect(
fig = fig, x = rep(gp, 2), y = c(md1, md2),
width = width, height = c(hgt1, hgt2),
xlab = x_name, ylab = y_name,
line_color = args$params$line_color,
fill_color = args$params$fill_color,
line_alpha = args$params$line_alpha,
fill_alpha = args$params$fill_alpha)
fig <- ly_segments(
fig = fig,
x0 = c(gp, gp, gpr, gpr),
y0 = c(bp$stats[1], bp$stats[4], bp$stats[1], bp$stats[5]),
x1 = c(gp, gp, gpl, gpl),
y1 = c(bp$stats[2], bp$stats[5], bp$stats[1], bp$stats[5]),
xlab = x_name, ylab = y_name,
line_color = args$params$line_color,
line_alpha = args$params$line_alpha)
if (length(bp$out) > 0 && !(is.na(outlier_size) || is.na(outlier_glyph))) {
fig <- ly_points(
fig = fig,
x = rep(gp, length(bp$out)), y = bp$out,
glyph = rep(outlier_glyph, length(bp$out)),
size = outlier_size,
xlab = x_name, ylab = y_name,
line_color = args$params$line_color,
fill_color = args$params$fill_color,
line_alpha = args$params$line_alpha,
fill_alpha = args$params$fill_alpha)
}
}
if (group_is_numeric && !fig$x$spec$has_x_axis)
fig <- fig %>% x_range(as.character(sort(unique(as.numeric(group)))))
fig
} |
"bitcoin_gold_oil" |
lfqCreate <- function(data, Lname, Dname, Fname = NA, bin_size = 1,
species = NA, stock = NA, comment = "",
Lmin = 0,
length_unit = "cm", plus_group = FALSE,
aggregate_dates = FALSE,
plot = FALSE){
data$length <- get(Lname, data)
data$date <- get(Dname, data)
if(!is.na(Fname)){
data$freq <- get(Fname, data)
}else{
data$freq <- rep(1,nrow(data))
}
if(!inherits(data$date,"Date")) stop(noquote("Please provide the date as 'Date' class (e.g. as.Date())."))
if(length_unit == "m") data$length <- data$length * 100
if(length_unit == "mm") data$length <- data$length / 10
data$length[which(data$length == 0)] <- NA
data <- data[!is.na(data$length),]
data <- data[!is.na(data$date),]
data <- data[order(data$date),]
if(aggregate_dates){
data$samplings <- as.Date(paste(format(data$date, "%Y-%m"),"15",sep="-"))
}else data$samplings <- data$date
bin.breaks <- seq(Lmin, max(data$length) + bin_size, by=bin_size)
midLengths <- bin.breaks + bin_size/2
data2 <- aggregate(list(freq=data$freq),
by=list(date=data$samplings, length=data$length), sum)
data2 <- data2[order(data2$date),]
listi <- vector("list",length(unique(data2$date)))
LF_dat <- data.frame(bin = bin.breaks)
for(i in 1:length(unique(data2$date))){
sampli <- unique(data2$date)[i]
lengthi <- as.numeric(data2$length[data2$date == sampli])
freqi <- as.numeric(data2$freq[data2$date == sampli])
bin.breaks2 <- rep(NA, length(bin.breaks))
for(ii in 1:length(bin.breaks)){
if(ii == length(bin.breaks)){
bin.breaks2[ii] <- length(which(lengthi >= bin.breaks[ii]))
}else{
bin.breaks2[ii] <- length(which(lengthi >= bin.breaks[ii] & lengthi < bin.breaks[ii+1]))
}
}
bin.breaks3 <- rep(bin.breaks, bin.breaks2)
dati <- aggregate(list(freq=freqi), by=list(bin=bin.breaks3), sum)
listi[[i]] <- merge(LF_dat, dati, by.x = "bin", all.x =TRUE)[,2]
}
catch_mat <- do.call(cbind,listi)
catch_mat[is.na(catch_mat)] <- 0
if(plus_group[1]){
if(length(plus_group) == 1){
if(is.vector(catch_mat)){
print(data.frame(midLengths = midLengths, frequency = catch_mat))
}else print(data.frame(midLengths = midLengths, frequency = rowSums(catch_mat)))
writeLines("Check the table above and insert the length of the plus group (Esc to cancel).")
pg = -1
while(pg > max(midLengths) | pg < min(midLengths)){
pg <- readline(paste0("Enter a length group between ", min(midLengths)," and ",
max(midLengths),":"))
pg = as.numeric(as.character(pg))
if(!(pg %in% midLengths)){
writeLines(paste0(pg, " is not an element of midLengths (see table)."))
pg = -1
if(is.na(pg)){break}
}
}
}else if(length(plus_group) == 2){
pg = as.numeric(as.character(plus_group[2]))
}
midLengths <- midLengths[1:which(midLengths == pg)]
if(is.vector(catch_mat)){
addplus <- sum(catch_mat[(which(midLengths == pg):length(catch_mat))])
catch_mat <- catch_mat[1:which(midLengths == pg)]
catch_mat[which(midLengths == pg)] <-
catch_mat[which(midLengths == pg)] + addplus
}else{
addplus <- colSums(catch_mat[(which(midLengths == pg):nrow(catch_mat)),])
catch_mat <- catch_mat[1:which(midLengths == pg),]
catch_mat[which(midLengths == pg),] <-
catch_mat[which(midLengths == pg),] + addplus
}
}
res <- list(species = species,
stock = stock,
dates = unique(data$samplings),
midLengths = midLengths,
catch = catch_mat,
comment = comment)
class(res) <- "lfq"
if(plot) plot(res, Fname = "catch")
return(res)
} |
invGauss.density <-
function(theta, delta) {
theta <- mpfr(theta, 99)
y=(delta*exp(delta^2)*theta^(-3/2)*exp(-((delta^2)/2)*(1/theta + theta)))/(sqrt(2*pi))
return(asNumeric(y))
} |
<p><img src="https://raw.githubusercontent.com/trinker/textmod/master/inst/textmod_logo/r_textmod.png" width="300"/><br/>
<p><a href="http://trinker.github.com/textmod_dev">textmod</a> is a...</p>
<p>Download the development version of textmod <a href="https://github.com/trinker/textmod/">here</a> |
"syllables" |
KPU <- function( level ) {
switch( level,
{
n = c(5.0000000000000000e-001)
w = c(1.0000000000000000e+000)
},
{
n = c(5.0000000000000000e-001, 8.8729829999999998e-001)
w = c(4.4444440000000002e-001, 2.7777780000000002e-001)
},
{
n = c(5.0000000000000000e-001, 8.8729829999999998e-001)
w = c(4.4444440000000002e-001, 2.7777780000000002e-001)
},
{
n = c(5.0000000000000000e-001, 7.1712189999999998e-001, 8.8729829999999998e-001, 9.8024560000000005e-001)
w = c(2.2545832254583223e-001, 2.0069872006987199e-001, 1.3424401342440134e-001, 5.2328105232810521e-002)
},
{
n = c(5.0000000000000000e-001, 7.1712189999999998e-001, 8.8729829999999998e-001, 9.8024560000000005e-001)
w = c(2.2545832254583223e-001, 2.0069872006987199e-001, 1.3424401342440134e-001, 5.2328105232810521e-002)
},
{
n = c(5.0000000000000000e-001, 7.1712189999999998e-001, 8.8729829999999998e-001, 9.8024560000000005e-001)
w = c(2.2545832254583223e-001, 2.0069872006987199e-001, 1.3424401342440134e-001, 5.2328105232810521e-002)
},
{
n = c(5.0000000000000000e-001, 6.1169330000000000e-001, 7.1712189999999998e-001, 8.1055149999999998e-001, 8.8729829999999998e-001, 9.4422960000000000e-001, 9.8024560000000005e-001, 9.9691600000000002e-001)
w = c(1.1275520000000000e-001, 1.0957840000000001e-001, 1.0031430000000000e-001, 8.5755999999999999e-002, 6.7207600000000006e-002, 4.6463600000000001e-002, 2.5801600000000001e-002, 8.5009000000000005e-003)
},
{
n = c(5.0000000000000000e-001, 6.1169330000000000e-001, 7.1712189999999998e-001, 8.1055149999999998e-001, 8.8729829999999998e-001, 9.4422960000000000e-001, 9.8024560000000005e-001, 9.9691600000000002e-001)
w = c(1.1275520000000000e-001, 1.0957840000000001e-001, 1.0031430000000000e-001, 8.5755999999999999e-002, 6.7207600000000006e-002, 4.6463600000000001e-002, 2.5801600000000001e-002, 8.5009000000000005e-003)
},
{
n = c(5.0000000000000000e-001, 6.1169330000000000e-001, 7.1712189999999998e-001, 8.1055149999999998e-001, 8.8729829999999998e-001, 9.4422960000000000e-001, 9.8024560000000005e-001, 9.9691600000000002e-001)
w = c(1.1275520000000000e-001, 1.0957840000000001e-001, 1.0031430000000000e-001, 8.5755999999999999e-002, 6.7207600000000006e-002, 4.6463600000000001e-002, 2.5801600000000001e-002, 8.5009000000000005e-003)
},
{
n = c(5.0000000000000000e-001, 6.1169330000000000e-001, 7.1712189999999998e-001, 8.1055149999999998e-001, 8.8729829999999998e-001, 9.4422960000000000e-001, 9.8024560000000005e-001, 9.9691600000000002e-001)
w = c(1.1275520000000000e-001, 1.0957840000000001e-001, 1.0031430000000000e-001, 8.5755999999999999e-002, 6.7207600000000006e-002, 4.6463600000000001e-002, 2.5801600000000001e-002, 8.5009000000000005e-003)
},
{
n = c(5.0000000000000000e-001, 6.1169330000000000e-001, 7.1712189999999998e-001, 8.1055149999999998e-001, 8.8729829999999998e-001, 9.4422960000000000e-001, 9.8024560000000005e-001, 9.9691600000000002e-001)
w = c(1.1275520000000000e-001, 1.0957840000000001e-001, 1.0031430000000000e-001, 8.5755999999999999e-002, 6.7207600000000006e-002, 4.6463600000000001e-002, 2.5801600000000001e-002, 8.5009000000000005e-003)
},
{
n = c(5.0000000000000000e-001, 6.1169330000000000e-001, 7.1712189999999998e-001, 8.1055149999999998e-001, 8.8729829999999998e-001, 9.4422960000000000e-001, 9.8024560000000005e-001, 9.9691600000000002e-001)
w = c(1.1275520000000000e-001, 1.0957840000000001e-001, 1.0031430000000000e-001, 8.5755999999999999e-002, 6.7207600000000006e-002, 4.6463600000000001e-002, 2.5801600000000001e-002, 8.5009000000000005e-003)
},
{
n = c(5.0000000000000000e-001, 5.5624450000000003e-001, 6.1169330000000000e-001, 6.6556769999999998e-001, 7.1712189999999998e-001, 7.6565989999999995e-001, 8.1055149999999998e-001, 8.5124809999999995e-001, 8.8729829999999998e-001, 9.1836300000000004e-001, 9.4422960000000000e-001, 9.6482740000000000e-001, 9.8024560000000005e-001, 9.9076560000000002e-001, 9.9691600000000002e-001, 9.9954909999999997e-001)
w = c(5.6377600000000014e-002, 5.5978400000000011e-002, 5.4789200000000017e-002, 5.2834900000000011e-002, 5.0157100000000017e-002, 4.6813600000000004e-002, 4.2878000000000006e-002, 3.8439800000000010e-002, 3.3603900000000006e-002, 2.8489800000000006e-002, 2.3231400000000003e-002, 1.7978600000000004e-002, 1.2903800000000003e-002, 8.2230000000000011e-003, 4.2173000000000011e-003, 1.2724000000000001e-003)
},
{
n = c(5.0000000000000000e-001, 5.5624450000000003e-001, 6.1169330000000000e-001, 6.6556769999999998e-001, 7.1712189999999998e-001, 7.6565989999999995e-001, 8.1055149999999998e-001, 8.5124809999999995e-001, 8.8729829999999998e-001, 9.1836300000000004e-001, 9.4422960000000000e-001, 9.6482740000000000e-001, 9.8024560000000005e-001, 9.9076560000000002e-001, 9.9691600000000002e-001, 9.9954909999999997e-001)
w = c(5.6377600000000014e-002, 5.5978400000000011e-002, 5.4789200000000017e-002, 5.2834900000000011e-002, 5.0157100000000017e-002, 4.6813600000000004e-002, 4.2878000000000006e-002, 3.8439800000000010e-002, 3.3603900000000006e-002, 2.8489800000000006e-002, 2.3231400000000003e-002, 1.7978600000000004e-002, 1.2903800000000003e-002, 8.2230000000000011e-003, 4.2173000000000011e-003, 1.2724000000000001e-003)
},
{
n = c(5.0000000000000000e-001, 5.5624450000000003e-001, 6.1169330000000000e-001, 6.6556769999999998e-001, 7.1712189999999998e-001, 7.6565989999999995e-001, 8.1055149999999998e-001, 8.5124809999999995e-001, 8.8729829999999998e-001, 9.1836300000000004e-001, 9.4422960000000000e-001, 9.6482740000000000e-001, 9.8024560000000005e-001, 9.9076560000000002e-001, 9.9691600000000002e-001, 9.9954909999999997e-001)
w = c(5.6377600000000014e-002, 5.5978400000000011e-002, 5.4789200000000017e-002, 5.2834900000000011e-002, 5.0157100000000017e-002, 4.6813600000000004e-002, 4.2878000000000006e-002, 3.8439800000000010e-002, 3.3603900000000006e-002, 2.8489800000000006e-002, 2.3231400000000003e-002, 1.7978600000000004e-002, 1.2903800000000003e-002, 8.2230000000000011e-003, 4.2173000000000011e-003, 1.2724000000000001e-003)
},
{
n = c(5.0000000000000000e-001, 5.5624450000000003e-001, 6.1169330000000000e-001, 6.6556769999999998e-001, 7.1712189999999998e-001, 7.6565989999999995e-001, 8.1055149999999998e-001, 8.5124809999999995e-001, 8.8729829999999998e-001, 9.1836300000000004e-001, 9.4422960000000000e-001, 9.6482740000000000e-001, 9.8024560000000005e-001, 9.9076560000000002e-001, 9.9691600000000002e-001, 9.9954909999999997e-001)
w = c(5.6377600000000014e-002, 5.5978400000000011e-002, 5.4789200000000017e-002, 5.2834900000000011e-002, 5.0157100000000017e-002, 4.6813600000000004e-002, 4.2878000000000006e-002, 3.8439800000000010e-002, 3.3603900000000006e-002, 2.8489800000000006e-002, 2.3231400000000003e-002, 1.7978600000000004e-002, 1.2903800000000003e-002, 8.2230000000000011e-003, 4.2173000000000011e-003, 1.2724000000000001e-003)
},
{
n = c(5.0000000000000000e-001, 5.5624450000000003e-001, 6.1169330000000000e-001, 6.6556769999999998e-001, 7.1712189999999998e-001, 7.6565989999999995e-001, 8.1055149999999998e-001, 8.5124809999999995e-001, 8.8729829999999998e-001, 9.1836300000000004e-001, 9.4422960000000000e-001, 9.6482740000000000e-001, 9.8024560000000005e-001, 9.9076560000000002e-001, 9.9691600000000002e-001, 9.9954909999999997e-001)
w = c(5.6377600000000014e-002, 5.5978400000000011e-002, 5.4789200000000017e-002, 5.2834900000000011e-002, 5.0157100000000017e-002, 4.6813600000000004e-002, 4.2878000000000006e-002, 3.8439800000000010e-002, 3.3603900000000006e-002, 2.8489800000000006e-002, 2.3231400000000003e-002, 1.7978600000000004e-002, 1.2903800000000003e-002, 8.2230000000000011e-003, 4.2173000000000011e-003, 1.2724000000000001e-003)
},
{
n = c(5.0000000000000000e-001, 5.5624450000000003e-001, 6.1169330000000000e-001, 6.6556769999999998e-001, 7.1712189999999998e-001, 7.6565989999999995e-001, 8.1055149999999998e-001, 8.5124809999999995e-001, 8.8729829999999998e-001, 9.1836300000000004e-001, 9.4422960000000000e-001, 9.6482740000000000e-001, 9.8024560000000005e-001, 9.9076560000000002e-001, 9.9691600000000002e-001, 9.9954909999999997e-001)
w = c(5.6377600000000014e-002, 5.5978400000000011e-002, 5.4789200000000017e-002, 5.2834900000000011e-002, 5.0157100000000017e-002, 4.6813600000000004e-002, 4.2878000000000006e-002, 3.8439800000000010e-002, 3.3603900000000006e-002, 2.8489800000000006e-002, 2.3231400000000003e-002, 1.7978600000000004e-002, 1.2903800000000003e-002, 8.2230000000000011e-003, 4.2173000000000011e-003, 1.2724000000000001e-003)
},
{
n = c(5.0000000000000000e-001, 5.5624450000000003e-001, 6.1169330000000000e-001, 6.6556769999999998e-001, 7.1712189999999998e-001, 7.6565989999999995e-001, 8.1055149999999998e-001, 8.5124809999999995e-001, 8.8729829999999998e-001, 9.1836300000000004e-001, 9.4422960000000000e-001, 9.6482740000000000e-001, 9.8024560000000005e-001, 9.9076560000000002e-001, 9.9691600000000002e-001, 9.9954909999999997e-001)
w = c(5.6377600000000014e-002, 5.5978400000000011e-002, 5.4789200000000017e-002, 5.2834900000000011e-002, 5.0157100000000017e-002, 4.6813600000000004e-002, 4.2878000000000006e-002, 3.8439800000000010e-002, 3.3603900000000006e-002, 2.8489800000000006e-002, 2.3231400000000003e-002, 1.7978600000000004e-002, 1.2903800000000003e-002, 8.2230000000000011e-003, 4.2173000000000011e-003, 1.2724000000000001e-003)
},
{
n = c(5.0000000000000000e-001, 5.5624450000000003e-001, 6.1169330000000000e-001, 6.6556769999999998e-001, 7.1712189999999998e-001, 7.6565989999999995e-001, 8.1055149999999998e-001, 8.5124809999999995e-001, 8.8729829999999998e-001, 9.1836300000000004e-001, 9.4422960000000000e-001, 9.6482740000000000e-001, 9.8024560000000005e-001, 9.9076560000000002e-001, 9.9691600000000002e-001, 9.9954909999999997e-001)
w = c(5.6377600000000014e-002, 5.5978400000000011e-002, 5.4789200000000017e-002, 5.2834900000000011e-002, 5.0157100000000017e-002, 4.6813600000000004e-002, 4.2878000000000006e-002, 3.8439800000000010e-002, 3.3603900000000006e-002, 2.8489800000000006e-002, 2.3231400000000003e-002, 1.7978600000000004e-002, 1.2903800000000003e-002, 8.2230000000000011e-003, 4.2173000000000011e-003, 1.2724000000000001e-003)
},
{
n = c(5.0000000000000000e-001, 5.5624450000000003e-001, 6.1169330000000000e-001, 6.6556769999999998e-001, 7.1712189999999998e-001, 7.6565989999999995e-001, 8.1055149999999998e-001, 8.5124809999999995e-001, 8.8729829999999998e-001, 9.1836300000000004e-001, 9.4422960000000000e-001, 9.6482740000000000e-001, 9.8024560000000005e-001, 9.9076560000000002e-001, 9.9691600000000002e-001, 9.9954909999999997e-001)
w = c(5.6377600000000014e-002, 5.5978400000000011e-002, 5.4789200000000017e-002, 5.2834900000000011e-002, 5.0157100000000017e-002, 4.6813600000000004e-002, 4.2878000000000006e-002, 3.8439800000000010e-002, 3.3603900000000006e-002, 2.8489800000000006e-002, 2.3231400000000003e-002, 1.7978600000000004e-002, 1.2903800000000003e-002, 8.2230000000000011e-003, 4.2173000000000011e-003, 1.2724000000000001e-003)
},
{
n = c(5.0000000000000000e-001, 5.5624450000000003e-001, 6.1169330000000000e-001, 6.6556769999999998e-001, 7.1712189999999998e-001, 7.6565989999999995e-001, 8.1055149999999998e-001, 8.5124809999999995e-001, 8.8729829999999998e-001, 9.1836300000000004e-001, 9.4422960000000000e-001, 9.6482740000000000e-001, 9.8024560000000005e-001, 9.9076560000000002e-001, 9.9691600000000002e-001, 9.9954909999999997e-001)
w = c(5.6377600000000014e-002, 5.5978400000000011e-002, 5.4789200000000017e-002, 5.2834900000000011e-002, 5.0157100000000017e-002, 4.6813600000000004e-002, 4.2878000000000006e-002, 3.8439800000000010e-002, 3.3603900000000006e-002, 2.8489800000000006e-002, 2.3231400000000003e-002, 1.7978600000000004e-002, 1.2903800000000003e-002, 8.2230000000000011e-003, 4.2173000000000011e-003, 1.2724000000000001e-003)
},
{
n = c(5.0000000000000000e-001, 5.5624450000000003e-001, 6.1169330000000000e-001, 6.6556769999999998e-001, 7.1712189999999998e-001, 7.6565989999999995e-001, 8.1055149999999998e-001, 8.5124809999999995e-001, 8.8729829999999998e-001, 9.1836300000000004e-001, 9.4422960000000000e-001, 9.6482740000000000e-001, 9.8024560000000005e-001, 9.9076560000000002e-001, 9.9691600000000002e-001, 9.9954909999999997e-001)
w = c(5.6377600000000014e-002, 5.5978400000000011e-002, 5.4789200000000017e-002, 5.2834900000000011e-002, 5.0157100000000017e-002, 4.6813600000000004e-002, 4.2878000000000006e-002, 3.8439800000000010e-002, 3.3603900000000006e-002, 2.8489800000000006e-002, 2.3231400000000003e-002, 1.7978600000000004e-002, 1.2903800000000003e-002, 8.2230000000000011e-003, 4.2173000000000011e-003, 1.2724000000000001e-003)
},
{
n = c(5.0000000000000000e-001, 5.5624450000000003e-001, 6.1169330000000000e-001, 6.6556769999999998e-001, 7.1712189999999998e-001, 7.6565989999999995e-001, 8.1055149999999998e-001, 8.5124809999999995e-001, 8.8729829999999998e-001, 9.1836300000000004e-001, 9.4422960000000000e-001, 9.6482740000000000e-001, 9.8024560000000005e-001, 9.9076560000000002e-001, 9.9691600000000002e-001, 9.9954909999999997e-001)
w = c(5.6377600000000014e-002, 5.5978400000000011e-002, 5.4789200000000017e-002, 5.2834900000000011e-002, 5.0157100000000017e-002, 4.6813600000000004e-002, 4.2878000000000006e-002, 3.8439800000000010e-002, 3.3603900000000006e-002, 2.8489800000000006e-002, 2.3231400000000003e-002, 1.7978600000000004e-002, 1.2903800000000003e-002, 8.2230000000000011e-003, 4.2173000000000011e-003, 1.2724000000000001e-003)
},
{
n = c(5.0000000000000000e-001, 5.2817210000000003e-001, 5.5624450000000003e-001, 5.8411769999999996e-001, 6.1169330000000000e-001, 6.3887490000000002e-001, 6.6556769999999998e-001, 6.9167970000000001e-001, 7.1712189999999998e-001, 7.4180900000000005e-001, 7.6565989999999995e-001, 7.8859789999999996e-001, 8.1055149999999998e-001, 8.3145480000000005e-001, 8.5124809999999995e-001, 8.6987800000000004e-001, 8.8729829999999998e-001, 9.0347029999999995e-001, 9.1836300000000004e-001, 9.3195399999999995e-001, 9.4422960000000000e-001, 9.5518559999999997e-001, 9.6482740000000000e-001, 9.7317140000000002e-001, 9.8024560000000005e-001, 9.8609139999999995e-001, 9.9076560000000002e-001, 9.9434239999999996e-001, 9.9691600000000002e-001, 9.9860309999999997e-001, 9.9954909999999997e-001, 9.9993650000000001e-001)
w = c(2.8188799999999993e-002, 2.8138799999999992e-002, 2.7989199999999992e-002, 2.7740699999999993e-002, 2.7394599999999995e-002, 2.6952699999999993e-002, 2.6417499999999993e-002, 2.5791599999999994e-002, 2.5078599999999993e-002, 2.4282199999999993e-002, 2.3406799999999995e-002, 2.2457299999999996e-002, 2.1438999999999996e-002, 2.0357799999999995e-002, 1.9219899999999998e-002, 1.8032199999999998e-002, 1.6801899999999998e-002, 1.5536799999999996e-002, 1.4244899999999996e-002, 1.2934799999999996e-002, 1.1615699999999998e-002, 1.0297099999999998e-002, 8.9892999999999987e-003, 7.7033999999999983e-003, 6.4518999999999983e-003, 5.2490999999999987e-003, 4.1114999999999988e-003, 3.0577999999999990e-003, 2.1087999999999997e-003, 1.2894999999999998e-003, 6.3259999999999987e-004, 1.8159999999999997e-004)
}
)
return( list( "nodes" = n,
"weights" = w ) )
} |
predict.fcr <- function(object, newdata, type="link", ...){
stopifnot(class(object) == "fcr")
stopifnot(is.data.frame(newdata))
stopifnot("subj" %in% colnames(newdata))
stopifnot(all(is.finite(newdata$subj)))
stopifnot(type %in% c("link","terms","iterms","lpmatrix"))
if(any(grepl("^phi[0-9]+|^sp[0-9]+",colnames(data)))){
stop("column names `sp[0-9]+` and `phi[0-9]+ are reserved`")
}
if("g" %in% colnames(data)){
stop("column name `g` is reserved`")
}
fit <- object$fit
argvals <- object$argvals
outcome <- as.character(object$fit$formula)[2]
if(sum(!newdata[[argvals]] %in% object$face.object$argvals.new) != 0) {
rmidx <- which(!newdata[[argvals]] %in% object$face.object$argvals.new)
newdata <- newdata[-rmidx,]
warning(paste(length(rmidx),
" rows of newdata contained values of the functional domain not fit",
"and were removed. Please refit the model with all desired predicted",
"values supplied using the `argvals.new` argument."))
}
coef_names <- names(coef(fit))
phi_names <- unique(regmatches(coef_names, regexpr("phi[0-9]+", coef_names)))
for(k in phi_names) {
newdata[[k]] <- 0
}
subj_in <- unique(fit$model$g)
data_in <- subset(newdata, newdata$subj %in% subj_in)
data_out <- subset(newdata, !(newdata$subj %in% subj_in))
if(type != "link" & nrow(data_out) > 0){
stop(paste("type", type, "not supported for subjects not included in model fitting."))
}
if(nrow(data_in) > 0){
data_in <- createPhi(object$face.object, data = data_in, argvals = argvals, nPhi = length(phi_names))
data_in[["g"]] <- data_in[["subj"]]
pred_in <- predict(fit, newdata = data_in, type = type, ...)
if(nrow(data_out) == 0) return(list("dynamic_predictions" = NA,
"insample_predictions" = pred_in))
} else {
pred_in <- NA
}
data_out[["g"]] <- sort(unique(fit$model$g))[1]
s2 <- c(fit$sig2)
uid <- unique(data_out$subj)
ut <- object$face.object$argvals.new
if(object$sp) {
sp <- fit$full.sp[grepl("phi", names(fit$full.sp))]
} else if (!object$sp) {
sp <- fit$sp[grepl("phi", names(fit$sp))]
}
preds <- scores <- random <- se <- se_p <- c()
inx_lp <- which(!grepl("s\\(g\\):phi[0-9]+", coef_names))
Vp0 <- fit$Vp[inx_lp,inx_lp]
for(i in 1:length(uid)) {
tmp_f <- subset(data_out, data_out$subj == uid[i])
miss_outcome <- is.na(tmp_f[[outcome]])
tmp <- tmp_f[!miss_outcome,]
Z_f <- matrix(NA, ncol = length(phi_names), nrow = nrow(tmp_f))
for(k in 1:length(phi_names)) {
Z_f[,k] <- vapply(tmp_f[[argvals]], function(x){
object$face.object$eigenfunctions[ut==x,k]
}, numeric(1))
}
Z <- Z_f[!miss_outcome,,drop=FALSE]
Xb_f <- predict(fit,
newdata = tmp_f,
exclude = paste("s(g):", phi_names,")", sep=""))
Xb <- Xb_f[!miss_outcome]
G <- diag(s2/sp)
if(nrow(tmp) > 1) R <- diag(rep(s2, nrow(tmp)))
if(nrow(tmp) == 1) R <- s2
V <- Z %*% G %*% t(Z) + R
ei <- G %*% t(Z) %*% solve(V) %*% (tmp[[outcome]] - Xb)
bi <- as.vector(t(ei) %*% t(Z_f))
v_y <- Z_f %*% (G - G %*% t(Z) %*% solve(V) %*% Z %*% G) %*% t(Z_f)
X1.test <- predict(fit,tmp_f,type="lpmatrix")[,inx_lp]
v_y <- v_y + X1.test%*%Vp0%*%t(X1.test)
scores <- c(scores, ei)
random <- c(random, bi)
se <- c(se, sqrt(diag(v_y)))
se_p <- c(se_p, sqrt(diag(v_y) + s2))
preds <- c(preds, Xb_f + bi)
}
dyn_pred <- list("fitted.values" = data.frame("y.pred" = preds,
"se.fit" = se,
"se.fit.p" = se_p,
"random" = random),
"scores" = matrix(scores, ncol=ncol(object$face.object$eigenfunctions),
nrow=length(uid), byrow=TRUE),
"data" = newdata)
list("dynamic_predictions" = dyn_pred,
"insample_predictions" = pred_in)
}
plot.fcr <- function(x, plot.covariance = FALSE, ...){
stopifnot(class(x) == "fcr")
if(plot.covariance) {
oldpar <- par()$ask
par(ask=TRUE)
tnew <- x$face.object$argvals.new
inx <- which(tnew %in% seq(min(tnew), max(tnew), len = 100))
image.plot(tnew[inx],tnew[inx], x$face.object$Cor.new[inx,inx],
xlab="Functional Domain", ylab="Functional Domain", main = "Correlation Function")
plot(tnew[inx], x$face.object$Chat.raw.diag.new[inx], xlab="Functional Domain",
ylab="", main = "Variance Function", type="l")
matplot(x$face.object$eigenfunctions[inx,], xlab="Functional Domain", ylab="",
main="Eigenfunctions of the Covariance Function", type='l')
evals <- x$face.object$eigenvalues
evals <- sprintf("%5.3f",evals)
evals[evals == "0.000"] <- "<0.000"
legend("top", legend = paste("eval", 1:length(evals), " = ", evals ,sep=""),
col=1:length(evals), lty = 1:length(evals),
bty='n',ncol=3)
par(ask=oldpar)
}
if(!plot.covariance) {
plot(x$fit, ...)
}
} |
source("ESEUR_config.r")
dir_str=paste0(ESEUR_dir, "Rlang/Top500/")
top_files=list.files(dir_str)
top_files=top_files[grep("^TOP500_.*.csv.xz", top_files)]
merge_csv=function(file_str)
{
all_csv <<- merge(all_csv, read.csv(paste(dir_str, file_str, sep="/")), all=TRUE)
return(0)
}
mv_col=function(old_col, new_col)
{
new_csv=subset(all_csv, is.na(all_csv[, old_col]))
t=subset(all_csv, !is.na(all_csv[, old_col]))
t[, new_col]=t[, old_col]
new_csv=rbind(new_csv, t)
new_csv[, old_col]=NULL
return(new_csv)
}
all_csv=0
dummy=sapply(top_files, function(X) merge_csv(X))
all_csv=mv_col("Effeciency....", "Efficiency....")
all_csv=mv_col("Proc..Frequency", "Processor.Speed..MHz.")
all_csv=mv_col("RMax", "Rmax")
all_csv=mv_col("RPeak", "Rpeak")
cpu_power=data.frame(Year=all_csv$Year,
Power=all_csv$Power,
Rmax=all_csv$Rmax,
Rpeak=all_csv$Rpeak,
Nmax=all_csv$Nmax,
Nhalf=all_csv$Nhalf,
Processor.Speed=all_csv$Processor.Speed..MHz.,
Segment=all_csv$Segment)
cpu_power=unique(cpu_power)
plot(cpu_power$Year, log(cpu_power$Power)) |
n <- 50
x <- runif(n)
y <- x + rnorm(n)
fit <- lm(y~x)
library("sandwich")
confint_robust(fit, HC_type = "HC4m") |
transmission <- function(n, external, polarisation = "p"){
alpha <- asin(sin(external) / n)
if(polarisation == 'p'){
4 * n*cos(external)*cos(alpha) /
(n * cos(external) + cos(alpha))^2
} else {
.NotYetImplemented()
}
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
fig <- local({
i <- 0
ref <- list()
list(
cap=function(refName, text) {
i <<- i + 1
ref[[refName]] <<- i
paste("Figure ", i, ": ", text, sep="")
},
ref=function(refName) {
ref[[refName]]
})
})
require(knitr)
library(gdtools)
library(kableExtra)
library(clusterCrit)
library(dplyr)
col1 <- c("1", "2","3","4", "5", "6")
col2 <- c("`data_imputation`","`rates`", "`props`", "`outlier_detect`","`w_spaces`", "`remove_rows_n`")
col3 <- c("Data imputation for longitudinal data", "Conversion of 'counts' to 'rates'", "Conversion of 'counts' (or 'rates') to 'Proportion'", "Outlier detection and replacement","Whitespace removal", "Incomplete rows removal")
col4 <- c("Calculates any missing entries (`NA`, `Inf`, `null`) in a longitudinal data, according to a specified method","Calculates rates from observed 'counts' and its associated denominator data", "Converts 'counts' or 'rates' observation to 'proportion'", "Identifies outlier observations in the data, and replace or remove them","Removes all the leading and trailing whitespaces in a longitudinal data", "Removes rows which contain 'NA' and 'inf' entries")
tble <- data.frame(col1, col2, col3, col4)
tble <- tble
knitr::kable(tble, caption = "Table 1. `Data manipulation` functions", col.names = c("SN","Function","Title","Description")) %>%
kable_styling(full_width = F) %>%
column_spec(1, bold = T, border_right = T) %>%
column_spec(2, width = "8em", background = "white") %>%
column_spec(3, width = "12em", background = "white") %>%
column_spec(4, width = "16em", background = "white")
library(akmedoids)
data(traj)
head(traj)
nrow(traj)
ncol(traj)
imp_traj <- data_imputation(traj, id_field = TRUE, method = 2,
replace_with = 1, fill_zeros = FALSE)
imp_traj <- imp_traj$CompleteData
head(imp_traj)
par(mar=c(2,2,2,2)+0.1)
par(adj = 0)
par(mfrow=c(6,2))
dev.new()
dat <- as.data.frame(traj)
t_name <- as.vector(traj[,1])
dat <- dat[,2:ncol(dat)]
for(k in seq_len(nrow(dat))){
y <- suppressWarnings(as.numeric(as.character(dat[k,])))
x <- seq_len(length(y))
known <- data.frame(x, y)
known_1 <- data.frame(known[is.na(known[,2])|is.infinite(known[,2]),])
known_2 <- data.frame(known[!is.na(known[,2])&!is.infinite(known[,2]),])
model.lm <- lm(y ~ x, data = known_2)
newY <- predict(model.lm, newdata = data.frame(x = known_1[,1]))
l_pred <- predict(model.lm, newdata = data.frame(1:9))
dat[k, known_1[,1]] <- newY
plot (known$x, known$y, type="o", main=paste("traj_id:",t_name[k], sep=" "), font.main = 1)
if(!length(newY)==0){
lines(l_pred, lty="dotted", col="red", lwd=2)
}
points(known_1[,1], newY, col = "red")
}
plot_colors <- c("black","red")
text <- c("Observed points", "Predicted points")
par(xpd=TRUE)
legend("center",legend = text, text.width = max(sapply(text, strwidth)),
col=plot_colors, pch = 1, cex=1, horiz = FALSE)
par(xpd=FALSE)
plot_colors <- c("black","red")
text <- c("line joining observed points", "regression line predicting missing points")
plot.new()
par(xpd=TRUE)
legend("center",legend = text, text.width = max(sapply(text, strwidth)),
col=plot_colors, lwd=1, cex=1, lty=c(1,2), horiz = FALSE)
par(xpd=FALSE)
data(popl)
head(popl)
nrow(popl)
ncol(popl)
pop <- as.data.frame(matrix(0, nrow(popl), ncol(traj)))
colnames(pop) <- names(traj)
pop[,1] <- as.vector(as.character(popl[,1]))
pop[,4] <- as.vector(as.character(popl[,2]))
pop[,8] <- as.vector(as.character(popl[,3]))
list_ <- c(2, 3, 5, 6, 7, 9, 10)
for(u_ in seq_len(length(list_))){
pop[,list_[u_]] <- "NA"
}
head(pop)
population2 <- pop
pop_imp_result <- data_imputation(population2, id_field = TRUE, method = 2,
replace_with = 1, fill_zeros = FALSE)
pop_imp_result <- pop_imp_result$CompleteData
head(pop_imp_result)
crime_per_200_people <- rates(imp_traj, denomin=pop_imp_result, id_field=TRUE,
multiplier = 200)
crime_per_200_people <- crime_per_200_people$rates_estimates
nrow(crime_per_200_people)
prop_crime_per200_people <- props(crime_per_200_people, id_field = TRUE, scale = 1, digits=2)
prop_crime_per200_people
colSums(prop_crime_per200_people[,2:ncol(prop_crime_per200_people)])
library(ggplot2)
coln <- colnames(imp_traj)[2:length(colnames(imp_traj))]
code_ <- rep(imp_traj$location_ids, ncol(imp_traj)-1)
d_bind <- NULL
for(v in seq_len(ncol(imp_traj)-1)){
d_bind <- c(d_bind, as.numeric(imp_traj[,(v+1)]))
}
code <- data.frame(location_ids=as.character(code_))
variable <- data.frame(variable=as.character(rep(coln,
each=length(imp_traj$location_ids))))
value=data.frame(value = as.numeric(d_bind))
imp_traj_long <- bind_cols(code, variable,value)
head(imp_traj_long)
p <- ggplot(imp_traj_long, aes(x=variable, y=value,
group=location_ids, color=location_ids)) +
geom_point() +
geom_line()
print(p)
imp_traj_New <- outlier_detect(imp_traj, id_field = TRUE, method = 2,
threshold = 20, count = 1, replace_with = 2)
imp_traj_New <- imp_traj_New$Outliers_Replaced
print(imp_traj_New)
coln <- colnames(imp_traj_New)[2:length(colnames(imp_traj_New))]
code_ <- rep(imp_traj_New$location_ids, ncol(imp_traj_New)-1)
d_bind <- NULL
for(v in seq_len(ncol(imp_traj_New)-1)){
d_bind <- c(d_bind, as.numeric(imp_traj_New[,(v+1)]))
}
code <- data.frame(location_ids=as.character(code_))
variable <- data.frame(variable=as.character(rep(coln,
each=length(imp_traj_New$location_ids))))
value=data.frame(value = as.numeric(d_bind))
imp_traj_New_long <- bind_cols(code, variable,value)
p <- ggplot(imp_traj_New_long, aes(x=variable, y=value,
group=location_ids, color=location_ids)) +
geom_point() +
geom_line()
print(p)
knitr::include_graphics("inequality.png")
col1 <- c("1", "2", "3")
col2 <- c("`akclustr`","`print_akstats`", "`plot_akstats`")
col3 <- c("`Anchored k-medoids clustering`","`Descriptive (Change) statistics of clusters`", "`Plots of cluster groups`")
col4 <- c("Clusters trajectories into a `k` number of groups according to the similarities in their long-term trend and determines the best solution based on the Silhouette width measure or the Calinski-Harabasz criterion","Generates the descriptive and change statistics of groups, and also plots the groups performances", "Generates different plots of cluster groups")
tble2 <- data.frame(col1, col2, col3, col4)
tble2 <- tble2
knitr::kable(tble2, caption = "Table 2. `Data clustering` functions", col.names = c("SN","Function","Title","Description")) %>%
kable_styling(full_width = F) %>%
column_spec(1, bold = T, border_right = T) %>%
column_spec(2, width = "8em", background = "white") %>%
column_spec(3, width = "12em", background = "white") %>%
column_spec(4, width = "16em", background = "white")
head(prop_crime_per200_people)
coln <- colnames(prop_crime_per200_people)[2:length(colnames(prop_crime_per200_people))]
code_ <- rep(prop_crime_per200_people$location_ids, ncol(prop_crime_per200_people)-1)
d_bind <- NULL
for(v in seq_len(ncol(prop_crime_per200_people)-1)){
d_bind <- c(d_bind, prop_crime_per200_people[,(v+1)])
}
prop_crime_per200_people_melt <- data.frame(cbind(location_ids=as.character(code_), variable =
rep(coln,
each=length(prop_crime_per200_people$location_ids)), value=d_bind))
p <- ggplot(prop_crime_per200_people_melt, aes(x=variable, y=value,
group=location_ids, color=location_ids)) +
geom_point() +
geom_line()
print(p)
akObj <- akclustr(prop_crime_per200_people, id_field = TRUE,
method = "linear", k = c(3,8), crit = "Calinski_Harabasz", verbose=TRUE)
names(akObj)
knitr::include_graphics("caliHara.png")
akObj$solutions[[3]]
knitr::include_graphics("Nquant.png")
prpties = print_akstats(akObj, k = 5, show_plots = FALSE)
prpties
plot_akstats(akObj, k = 5, type="lines", y_scaling="fixed")
plot_akstats(akObj, k = 5, reference = 1, n_quant = 4, type="stacked")
col1 <- c("1", "2","3","4","5","6", "7","8","9","10")
col2 <- c("`group`", "`n`", "`n(%)`", "`%Prop.time1`", "`%Prop.timeT`", "`Change`", "`%Change`", "`%+ve Traj.`", "`%-ve Traj.`", "`Qtl:1st-4th`")
col3 <- c("`group membershp`", "`size (no.of.trajectories.)`", "`% size`", "`% proportion of obs. at time 1 (2001)`", "`proportion of obs. at time T (2009)`", "`absolute change in proportion between time1 and timeT`", "`% change in proportion between time 1 and time T`", "`% of trajectories with positive slopes`", "`% of trajectories with negative slopes`", "`Position of a group medoid in the quantile subdivisions`")
tble3 <- data.frame(col1, col2, col3)
tble3 <- tble3
knitr::kable(tble3, caption = "Table 3. field description of clustering outputs", col.names = c("SN","field","Description")) %>%
kable_styling(full_width = F) %>%
column_spec(1, bold = T, border_right = T) %>%
column_spec(2, width = "8em", background = "white") %>%
column_spec(3, width = "12em", background = "white")
|
waves <- function(date, us = FALSE, ...) {
assert(date, c("character", "Date"))
assert(us, 'logical')
dates <- str_extract_all_(date, "[0-9]+")[[1]]
assert_range(dates[1], 1979:format(Sys.Date(), "%Y"))
assert_range(as.numeric(dates[2]), 1:12)
assert_range(as.numeric(dates[3]), 1:31)
path <- bsw_get(year = dates[1], month = dates[2], day = dates[3],
us = us, ...)
bsw_read(path, us)
}
bsw_get <- function(year, month, day, us, cache = TRUE, overwrite = FALSE, ...) {
bsw_cache$mkdir()
key <- bsw_key(year, month, day, us)
file <- file.path(bsw_cache$cache_path_get(), basename(key))
if (!file.exists(file)) {
suppressMessages(bsw_GET_write(sub("/$", "", key), file, overwrite, ...))
}
return(file)
}
bsw_GET_write <- function(url, path, overwrite = TRUE, ...) {
cli <- crul::HttpClient$new(
url = url,
headers = list(Authorization = "Basic anonymous:[email protected]")
)
if (!overwrite) {
if (file.exists(path)) {
stop("file exists and ovewrite != TRUE", call. = FALSE)
}
}
res <- tryCatch(cli$get(disk = path, ...), error = function(e) e)
if (inherits(res, "error")) {
unlink(path)
stop(res$message, call. = FALSE)
}
return(res)
}
bsw_base_ftp <- function(x) {
base <- "ftp://ftp.cpc.ncep.noaa.gov/precip/bsw_UNI_PRCP"
if (x) file.path(base, "GAUGE_CONUS") else file.path(base, "GAUGE_GLB")
}
bsw_base_file <- function(x) {
base <- "PRCP_CU_GAUGE_V1.0%sdeg.lnx."
if (x) sprintf(base, "CONUS_0.25") else sprintf(base, "GLB_0.50")
}
bsw_key <- function(year, month, day, us) {
sprintf("%s/%s/%s/%s%s%s",
bsw_base_ftp(us),
if (year < 2006) "V1.0" else "RT",
year,
bsw_base_file(us),
paste0(year, month, day),
if (year < 2006) {
".gz"
} else if (year > 2005 && year < 2009) {
if (us && year == 2006) {
".gz"
} else {
".RT.gz"
}
} else {
".RT"
}
)
}
bsw_read <- function(x, us) {
conn <- file(x, "rb")
on.exit(close(conn))
if (us) {
bites <- 120 * 300 * 2
lats <- seq(from = 20.125, to = 49.875, by = 0.25)
longs <- seq(from = 230.125, to = 304.875, by = 0.25)
} else {
bites <- 360 * 720 * 2
lats <- seq(from = 0.25, to = 89.75, by = 0.5)
lats <- c(rev(lats * -1), lats)
longs <- seq(from = 0.25, to = 359.75, by = 0.5)
}
tmp <- readBin(conn, numeric(), n = bites, size = 4, endian = "little")
tmp <- tmp[seq_len(bites/2)] * 0.1
tibble::as_tibble(
stats::setNames(
cbind(expand.grid(longs, lats), tmp),
c('lon', 'lat', 'precip')
)
)
} |
context("standard covariance fit")
library("robmed", quietly = TRUE)
n <- 250
a <- c <- 0.2
b <- 0
seed <- 20150601
set.seed(seed)
X <- rnorm(n)
M1 <- a * X + rnorm(n)
M2 <- rnorm(n)
Y <- b * M1 + c * X + rnorm(n)
C1 <- rnorm(n)
C2 <- rnorm(n)
test_data <- data.frame(X, Y, M1, M2, C1, C2)
foo <- fit_mediation(test_data, x = "X", y = "Y", m = "M1",
method = "covariance", robust = FALSE)
bar <- summary(foo)
ellipse_mx <- setup_ellipse_plot(foo)
ellipse_ym <- setup_ellipse_plot(foo, horizontal = "M1", vertical = "Y",
partial = FALSE)
ellipse_partial <- setup_ellipse_plot(foo, horizontal = "M1", vertical = "Y",
partial = TRUE)
test_that("output has correct structure", {
expect_s3_class(foo, "cov_fit_mediation")
expect_s3_class(foo, "fit_mediation")
expect_s3_class(foo$cov, "cov_ML")
expect_null(foo$control)
})
test_that("arguments are correctly passed", {
expect_identical(foo$x, "X")
expect_identical(foo$y, "Y")
expect_identical(foo$m, "M1")
expect_null(foo$fit$covariates)
expect_false(foo$robust)
expect_null(foo$control)
})
test_that("dimensions are correct", {
expect_length(foo$a, 1L)
expect_length(foo$b, 1L)
expect_length(foo$direct, 1L)
expect_length(foo$total, 1L)
expect_length(foo$ab, 1L)
expect_identical(dim(foo$data), c(as.integer(n), 3L))
})
test_that("values of coefficients are correct", {
expect_equivalent(foo$total, foo$a * foo$b + foo$direct)
expect_equivalent(foo$ab, foo$a * foo$b)
})
test_that("output of coef() method has correct attributes", {
coefficients <- coef(foo)
expect_length(coefficients, 5L)
expect_named(coefficients, c("a", "b", "Direct", "Total", "ab"))
})
test_that("coef() method returns correct values of coefficients", {
expect_equivalent(coef(foo, parm = "a"), foo$a)
expect_equivalent(coef(foo, parm = "b"), foo$b)
expect_equivalent(coef(foo, parm = "Direct"), foo$direct)
expect_equivalent(coef(foo, parm = "Total"), foo$total)
expect_equivalent(coef(foo, parm = "ab"), foo$ab)
})
test_that("summary returns original object", {
expect_identical(foo, bar)
})
test_that("object returned by setup_xxx_plot() has correct structure", {
expect_s3_class(ellipse_mx$data, "data.frame")
expect_s3_class(ellipse_ym$data, "data.frame")
expect_s3_class(ellipse_partial$data, "data.frame")
expect_identical(dim(ellipse_mx$data), c(as.integer(n), 2L))
expect_identical(dim(ellipse_ym$data), c(as.integer(n), 2L))
expect_identical(dim(ellipse_partial$data), c(as.integer(n), 2L))
column_names <- c("x", "y")
expect_named(ellipse_mx$data, column_names)
expect_named(ellipse_ym$data, column_names)
expect_named(ellipse_partial$data, column_names)
expect_s3_class(ellipse_mx$ellipse, "data.frame")
expect_s3_class(ellipse_ym$ellipse, "data.frame")
expect_s3_class(ellipse_partial$ellipse, "data.frame")
expect_identical(ncol(ellipse_mx$ellipse), 2L)
expect_gt(nrow(ellipse_mx$ellipse), 0L)
expect_identical(ncol(ellipse_ym$ellipse), 2L)
expect_gt(nrow(ellipse_ym$ellipse), 0L)
expect_identical(ncol(ellipse_partial$ellipse), 2L)
expect_gt(nrow(ellipse_partial$ellipse), 0L)
column_names <- c("x", "y")
expect_named(ellipse_mx$ellipse, column_names)
expect_named(ellipse_ym$ellipse, column_names)
expect_named(ellipse_partial$ellipse, column_names)
expect_s3_class(ellipse_mx$line, "data.frame")
expect_null(ellipse_ym$line)
expect_s3_class(ellipse_partial$line, "data.frame")
expect_identical(dim(ellipse_mx$line), c(1L, 2L))
expect_identical(dim(ellipse_partial$line), c(1L, 2L))
column_names <- c("intercept", "slope")
expect_named(ellipse_mx$line, column_names)
expect_named(ellipse_partial$line, column_names)
expect_identical(ellipse_partial$line$intercept, 0)
expect_identical(ellipse_mx$horizontal, "X")
expect_identical(ellipse_mx$vertical, "M1")
expect_identical(ellipse_ym$horizontal, "M1")
expect_identical(ellipse_ym$vertical, "Y")
expect_identical(ellipse_partial$horizontal, "M1")
expect_identical(ellipse_partial$vertical, "Y")
expect_false(ellipse_mx$partial)
expect_false(ellipse_ym$partial)
expect_true(ellipse_partial$partial)
expect_false(ellipse_mx$robust)
expect_false(ellipse_ym$robust)
expect_false(ellipse_partial$robust)
expect_false(ellipse_mx$have_methods)
expect_false(ellipse_ym$have_methods)
expect_false(ellipse_partial$have_methods)
expect_error(setup_weight_plot(foo))
})
test_that("covariates not implemented", {
set.seed(seed)
suppressWarnings(
reg_fit <- fit_mediation(test_data, x = "X", y = "Y", m = "M1",
covariates = c("C1", "C2"), method = "regression",
robust = FALSE)
)
set.seed(seed)
expect_warning(
cov_fit <- fit_mediation(test_data, x = "X", y = "Y", m = "M1",
covariates = c("C1", "C2"), method = "covariance",
robust = FALSE)
)
expect_equal(cov_fit, reg_fit)
})
test_that("multiple mediators not implemented", {
set.seed(seed)
suppressWarnings(
reg_fit <- fit_mediation(test_data, x = "X", y = "Y", m = c("M1", "M2"),
method = "regression", robust = FALSE)
)
set.seed(seed)
expect_warning(
cov_fit <- fit_mediation(test_data, x = "X", y = "Y", m = c("M1", "M2"),
method = "covariance", robust = FALSE)
)
expect_equal(cov_fit, reg_fit)
})
fit_f1 <- fit_mediation(Y ~ m(M1) + X, data = test_data,
method = "covariance", robust = FALSE)
fit_f2 <- fit_mediation(Y ~ m(M1) + X,
method = "covariance", robust = FALSE)
med <- m(M1)
fit_f3 <- fit_mediation(Y ~ med + X, data = test_data,
method = "covariance", robust = FALSE)
test_that("formula interface works correctly", {
expect_equal(fit_f1, foo)
expect_equal(fit_f2, foo)
expect_equal(fit_f3, foo)
}) |
ci.exp.exact <-
function (rate, n, ci.type, alpha)
{
df <- 2 * n
denom <- df/rate
switch(ci.type, `two-sided` = {
lcl <- qchisq(alpha/2, df)/denom
ucl <- qchisq(1 - alpha/2, df)/denom
}, lower = {
lcl <- qchisq(alpha, df)/denom
ucl <- Inf
}, upper = {
lcl <- 0
ucl <- qchisq(1 - alpha, df)/denom
})
ci.limits <- c(lcl, ucl)
names(ci.limits) <- c("LCL", "UCL")
ret.obj <- list(name = "Confidence", parameter = "rate",
limits = ci.limits, type = ci.type, method = "Exact",
conf.level = 1 - alpha, sample.size = n)
oldClass(ret.obj) <- "intervalEstimate"
ret.obj
} |
test_that("tidied dags are in good shape", {
tidy_dag <- dagify(y ~ x + z, x ~ z) %>% tidy_dagitty()
expect_true(dagitty::is.dagitty(tidy_dag$dag))
expect_true(dplyr::is.tbl(tidy_dag$data))
dag_col_names <- names(tidy_dag$data)
expected_names <- c("x", "y", "xend", "yend", "name", "direction",
"to", "circular")
expect_true(all(expected_names %in% dag_col_names))
expect_equal(unique(tidy_dag$data$name), c("x", "z", "y"))
expect_equal(tidy_dag$data$direction,
factor(c("->", "->", "->", NA), levels = c("<-", "->", "<->")))
expect_true(is.logical(tidy_dag$data$circular))
expect_true(is.numeric(tidy_dag$data$x))
expect_true(is.numeric(tidy_dag$data$y))
})
test_that("Forbidden layouts error", {
expect_error(
tidy_dagitty(dagify(y ~ x + z, x ~ z), layout = "dendogram"),
"Layout type `dendogram` not supported in ggdag"
)
})
expect_function_produces_name <- function(tidy_dag, column) {
.df <- tidy_dag$data
expect_true(all(column %in% names(.df)))
}
test_that("node functions produce correct columns", {
tidy_dag <- dagify(y ~ x + z, x ~ z) %>% tidy_dagitty()
expect_function_produces_name(node_ancestors(tidy_dag, "y"), "ancestor")
expect_function_produces_name(node_children(tidy_dag, "z"), "children")
expect_function_produces_name(node_collider(tidy_dag), "colliders")
expect_function_produces_name(node_dconnected(tidy_dag, "x", "y"),
c("adjusted", "d_relationship"))
expect_function_produces_name(node_descendants(tidy_dag, "z"), "descendant")
expect_function_produces_name(node_drelationship(tidy_dag, "x", "y"),
c("adjusted", "d_relationship"))
expect_function_produces_name(node_dseparated(tidy_dag, "x", "y"),
c("adjusted", "d_relationship"))
expect_function_produces_name(node_equivalent_class(tidy_dag), "reversable")
expect_function_produces_name(node_equivalent_dags(tidy_dag), "dag")
expect_function_produces_name(node_exogenous(tidy_dag), "exogenous")
expect_function_produces_name(node_instrumental(tidy_dag,
exposure = "x",
outcome = "y"),
c("adjusted", "instrumental"))
expect_function_produces_name(node_parents(tidy_dag, "z"), "parent")
expect_function_produces_name(node_status(tidy_dag), "status")
}) |
context("Try getting results from expression")
test_that("try_get_model_succeeds", {
tmp <- try_get_model(1 + 9)
expect_equal(tmp[["Model"]], 10)
expect_equal(tmp[["Warning"]], NULL)
expect_equal(tmp[["Error"]], NULL)
})
test_that("try_get_model_warns", {
tmp <- suppressWarnings(try_get_model(log(-1)))
expect_equal(tmp[["Model"]], NaN)
expect_s3_class(tmp[["Warning"]], "simpleWarning")
expect_equal(tmp[["Error"]], NULL)
})
test_that("try_get_model_fails", {
tmp <- try_get_model(1 / "a")
expect_equal(tmp[["Model"]], NULL)
expect_equal(tmp[["Warning"]], NULL)
expect_s3_class(tmp[["Error"]], "simpleError")
}) |
dBiMG_expPR <- function(x, a, b, alpha)
{
stopifnot(x > 0, alpha >= -1 && alpha <= 1)
s = exp(a + b) * (1 + alpha * (1 - exp(a))) * (1 - exp(b))
pdf = (1 + alpha) * exp(a + b) / (s * (1 + x)^2) - 2 * alpha * exp(2 * a + b) / (s * (1 + 2 * x)^2) - 2 * alpha * exp(2 * b + a) / (s * (2 + x)^2) + alpha * exp(2 * a + 2 * b) / (s * (1 + x)^2)
return(pdf)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.