code
stringlengths 1
13.8M
|
---|
simAllopoly <- function(ploidy=c(2,2),
n.alleles=c(4,4), n.homoplasy=0,
n.null.alleles=rep(0, length(ploidy)),
alleles=NULL,
freq=NULL, meiotic.error.rate=0,
nSam=100, locname="L1"){
nGenomes <- length(ploidy)
if(nGenomes==1 && meiotic.error.rate != 0)
stop("No meiotic error possible if there is only one subgenome.")
if(is.null(alleles)){
if(length(n.alleles)!=nGenomes)
stop("'n.alleles' must be a vector of the same length as 'ploidy'.")
if(nGenomes>6) stop("More than six subgenomes not supported at this time.")
GenomeNames <- c('A','B','C','D','E','F')[1:nGenomes]
alleles <- list()
length(alleles) <- nGenomes
for(i in 1:nGenomes){
alleles[[i]] <- paste(GenomeNames[i], 1:n.alleles[i], sep="-")
}
if(length(n.homoplasy)!=1) stop("Only one value allowed for n.homoplasy.")
if(n.homoplasy>0){
HAlleles <- paste('H', 1:n.homoplasy, sep="-")
for(i in 1:nGenomes){
alleles[[i]][(n.alleles[i]-n.homoplasy+1):n.alleles[i]] <- HAlleles
}
}
if(length(n.null.alleles)!=nGenomes)
stop("'n.null.alleles' must be a vector the same length as 'ploidy'.")
if(!all(n.null.alleles<=n.alleles))
stop("'n.null.alleles' values must be smaller than 'n.alleles' values.")
for(i in 1:nGenomes){
if(n.null.alleles[i]>0){
alleles[[i]][1:n.null.alleles[i]] <- "N"
}
}
} else {
n.alleles <- sapply(alleles, length)
}
if(is.null(freq)){
freq <- list()
length(freq) <- nGenomes
for(i in 1:nGenomes){
temp <- sample(100, n.alleles[i], replace=TRUE)
freq[[i]] <- temp/sum(temp)
}
}
if(!is.list(alleles) || !is.list(freq))
stop("alleles and freq must each be a list of vectors")
if(!identical(sapply(freq, length), sapply(alleles, length)))
stop("Need same number of values for alleles and frequencies.")
if(nGenomes != length(alleles) || nGenomes != length(freq))
stop("Number of genomes nees to match between ploidy, alleles, and freq")
if(length(meiotic.error.rate)!=1 || meiotic.error.rate<0 ||
meiotic.error.rate>0.5)
stop("meiotic.error.rate should be a single value between 0 and 0.5.")
if(meiotic.error.rate>0 && !all(ploidy %% 2 == 0))
stop("Even (not odd) ploidy is required if simulating meiotic error.")
gen <- new("genambig", samples=1:nSam, loci=locname)
resample <- function(x, ...) x[sample.int(length(x), ...)]
for(s in 1:nSam){
gameteploidy <- ploidy/2
if(sample(c(TRUE,FALSE),size=1,
prob=c(meiotic.error.rate, 1-meiotic.error.rate))){
isolocusLost <- sample(nGenomes,1)
isolocusGained <- resample((1:nGenomes)[-isolocusLost],1)
gamete1ploidy <- gameteploidy
gamete1ploidy[isolocusLost] <- gamete1ploidy[isolocusLost]-1
gamete1ploidy[isolocusGained] <- gamete1ploidy[isolocusGained]+1
} else {
gamete1ploidy <- gameteploidy
}
if(sample(c(TRUE,FALSE),size=1,
prob=c(meiotic.error.rate, 1-meiotic.error.rate))){
isolocusLost <- sample(nGenomes,1)
isolocusGained <- resample((1:nGenomes)[-isolocusLost],1)
gamete2ploidy <- gameteploidy
gamete2ploidy[isolocusLost] <- gamete2ploidy[isolocusLost]-1
gamete2ploidy[isolocusGained] <- gamete2ploidy[isolocusGained]+1
} else {
gamete2ploidy <- gameteploidy
}
tempploidy <- gamete1ploidy + gamete2ploidy
thisgen <- unique(unlist(mapply(resample, alleles,
replace= TRUE,
size = tempploidy, prob = freq,
SIMPLIFY=FALSE)))
thisgen <- thisgen[thisgen!=0 & thisgen!="N"]
if(length(thisgen)==0){
Genotype(gen,s,1) <- Missing(gen)
} else {
Genotype(gen,s,1) <- thisgen
}
}
return(gen)
}
alleleCorrelations <- function(object, samples=Samples(object), locus=1,
alpha=0.05, n.subgen=2, n.start=50){
object <- object[samples,]
mymissing <- isMissing(object, loci=locus)
if(all(mymissing)) stop("All data at locus are missing.")
if(length(locus) > 1) stop("More than one locus")
object <- object[!mymissing,locus]
if(is(object, "genambig")) object <- genambig.to.genbinary(object)
if(!is(object, "genbinary")) stop("genambig or genbinary object needed.")
Absent(object) <- as.integer(0)
Present(object) <- as.integer(1)
gentable <- Genotypes(object)
gentable <- gentable[,apply(gentable, 2,
function(x) !all(x==Absent(object))), drop = FALSE]
gentable.out <- gentable
nonvar <- apply(gentable, 2, function(x) all(x==Present(object)))
mingen <- sum(nonvar)
if(mingen > n.subgen){
stop(paste("Locus",locus,": too many non-variable alleles"))
}
nAl <- dim(gentable)[2]
mysplit <- strsplit(dimnames(gentable)[[2]], split=".", fixed=TRUE)
alleles <- sapply(mysplit, function(x) x[2])
clustmat1 <- matrix(0, nrow=n.subgen, ncol=nAl,
dimnames=list(NULL,alleles))
if(sum(nonvar) > 0){
for(i in 1:sum(nonvar)){
clustmat1[i,alleles[nonvar][i]] <- 1
}
sigmatNeg <- sigmatPos <- oddsRatio <- NULL
pValuesNeg <- pValuesPos <- mydist <- NULL
mytotss <- mybss <- NA
clustmethod <- "fixed alleles"
gentable <- gentable[,!nonvar]
nAl <- nAl - sum(nonvar)
alleles <- alleles[!nonvar]
if(sum(nonvar)==n.subgen){
clustmat1[,alleles] <- 1
}
}
if(sum(rowSums(clustmat1)==0)==1 ||
sum(colSums(clustmat1) == 0) < sum(rowSums(clustmat1) == 0) ){
clustmat1[rowSums(clustmat1)==0,colSums(clustmat1)==0] <- 1
sigmatNeg <- sigmatPos <- oddsRatio <- NULL
pValuesNeg <- pValuesPos <- mydist <- NULL
mytotss <- mybss <- NA
clustmethod <- "fixed alleles"
}
if(sum(colSums(clustmat1) == 0) == sum(rowSums(clustmat1) == 0)){
blankAlleles <- which(colSums(clustmat1) == 0)
blankIsoloci <- which(rowSums(clustmat1) == 0)
for(i in 1:length(blankAlleles)){
clustmat1[blankIsoloci[i], blankAlleles[i]] <- 1
}
sigmatNeg <- sigmatPos <- oddsRatio <- NULL
pValuesNeg <- pValuesPos <- mydist <- NULL
mytotss <- mybss <- NA
clustmethod <- "fixed alleles"
}
if(all(colSums(clustmat1) > 0) && any(rowSums(clustmat1) == 0)){
clustmat1[rowSums(clustmat1)==0,] <- 1
sigmatNeg <- sigmatPos <- oddsRatio <- NULL
pValuesNeg <- pValuesPos <- mydist <- NULL
mytotss <- mybss <- NA
clustmethod <- "fixed alleles"
}
clustmat2 <- clustmat1
if(sum(rowSums(clustmat1)==0)>1){
clustmethod <- "K-means and UPGMA"
pValuesNeg <- matrix(NA, nrow=nAl, ncol=nAl)
pValuesPos <- matrix(NA, nrow=nAl, ncol=nAl)
oddsRatio <- matrix(NA, nrow=nAl, ncol=nAl)
for(a in 1:(nAl-1)){
for(b in (a+1):nAl){
X <- fisher.test(gentable[,a], gentable[,b], alternative="less",
conf.int=FALSE)
pValuesNeg[a,b] <- X$p.value; pValuesNeg[b,a] <- X$p.value
Y <- fisher.test(gentable[,a], gentable[,b], alternative="greater",
conf.int=FALSE)
pValuesPos[a,b] <- Y$p.value; pValuesPos[b,a] <- Y$p.value
oddsRatio[a,b] <- oddsRatio[b,a] <- X$estimate
}
}
pVect <- sort(pValuesNeg[lower.tri(pValuesNeg)])
m <- length(pVect)
kTest <- pVect > alpha/(m + 1 - (1:m))
if(all(!kTest)){
sigmatNeg <- matrix(TRUE, nrow=nAl, ncol=nAl)
} else {
k <- min((1:m)[kTest])
maxP <- pVect[k-1]
if(k > 1){
sigmatNeg <- pValuesNeg <= maxP
} else {
sigmatNeg <- matrix(FALSE, nrow=nAl, ncol=nAl)
}
}
pVect <- sort(pValuesPos[lower.tri(pValuesPos)])
kTest <- pVect > alpha/(m + 1 - (1:m))
if(all(!kTest)){
sigmatPos <- matrix(TRUE, nrow=nAl, ncol=nAl)
} else {
k <- min((1:m)[kTest])
maxP <- pVect[k-1]
if(k > 1){
sigmatPos <- pValuesPos <= maxP
} else {
sigmatPos <- matrix(FALSE, nrow=nAl, ncol=nAl)
}
}
if(!all(!sigmatPos)){
cat(paste("Warning: Significant positive correlations between alleles at locus", Loci(object), "; population structure or scoring error may bias results."), sep="\n")
}
dimnames(sigmatNeg) <- list(alleles,alleles)
dimnames(sigmatPos) <- list(alleles,alleles)
dimnames(pValuesNeg) <- list(alleles, alleles)
dimnames(pValuesPos) <- list(alleles, alleles)
dimnames(oddsRatio) <- list(alleles, alleles)
mydist <- pValuesNeg
mydist[is.na(mydist)] <- 0
n.subgen.adj = n.subgen - sum(rowSums(clustmat1)>0)
kres <- kmeans(mydist, centers=n.subgen.adj, nstart=n.start)
myclust1 <- kres$cluster
mytotss <- kres$totss
mybss <- kres$betweenss
myclust2 <- cutree(hclust(as.dist(mydist), method="average"),
k = n.subgen.adj)
for(i in (n.subgen - n.subgen.adj + 1):n.subgen){
clustmat1[i,alleles[myclust1==(i - n.subgen + n.subgen.adj)]] <- 1
clustmat2[i,alleles[myclust2==(i - n.subgen + n.subgen.adj)]] <- 1
} }
return(list(locus=Loci(object), clustering.method=clustmethod,
significant.neg=sigmatNeg, significant.pos=sigmatPos,
p.values.neg=pValuesNeg, p.values.pos=pValuesPos,
odds.ratio=oddsRatio,
Kmeans.groups=clustmat1, UPGMA.groups=clustmat2,
heatmap.dist=mydist,
totss=mytotss, betweenss=mybss, gentable=gentable.out))
}
testAlGroups <- function(object, fisherResults, SGploidy=2,
samples=Samples(object),
null.weight=0.5, tolerance=0.05,
swap = TRUE, R = 100, rho = 0.95, T0 = 1, maxreps = 100){
if(!is(object, "genambig") && !is(object, "genbinary"))
stop("genambig or genbinary object needed.")
object <- object[samples,]
L <- fisherResults$locus
mymissing <- isMissing(object, loci=L)
nind <- sum(!mymissing)
genobject <- object[!mymissing,L]
if(is(genobject, "genbinary")) genobject <- genbinary.to.genambig(genobject)
alleles <- dimnames(fisherResults$Kmeans.groups)[[2]]
numAlTotal <- length(alleles)
n.subgen <- dim(fisherResults$Kmeans.groups)[1]
numAl <- sapply(Genotypes(genobject), length)
if(!all(numAl <= n.subgen*SGploidy))
stop(paste("One or more genotypes have more than",
n.subgen*SGploidy, "alleles."))
if(!all(as.character(.unal1loc(genobject, samples=Samples(genobject),
locus=L)) %in% alleles))
stop("Alleles found in genobject that aren't in fisherResults.")
tallyInconsistentGen <- function(G, samples=1:nind, currentInconsistent = rep(FALSE, nind)){
tot <- 0
for(s in samples){
gen <- as.character(Genotype(genobject, s, L))
subg <- G[, gen, drop = FALSE]
if(any(rowSums(subg) == 0) ||
any(rowSums(subg[,colSums(subg) == 1, drop = FALSE]) > SGploidy)){
currentInconsistent[s] = TRUE
} else {
currentInconsistent[s] = FALSE
}
}
return(currentInconsistent)
}
Kmat <- fisherResults$Kmeans.groups
Umat <- fisherResults$UPGMA.groups
KsortV <- UsortV <- integer(length(alleles))
Uswap <- Kswap <- integer(n.subgen)
for(i in 1:n.subgen){
KfirstLeft <- match(0, KsortV)
UfirstLeft <- match(0, UsortV)
Kswap[i] <- match(1, Kmat[,KfirstLeft])
Uswap[i] <- match(1, Umat[,UfirstLeft])
KsortV[Kmat[Kswap[i],] == 1] <- i
UsortV[Umat[Uswap[i],] == 1] <- i
}
if(identical(KsortV, UsortV)){
G <- Kmat
} else {
Kok <- nind - sum(tallyInconsistentGen(Kmat))
Uok <- nind - sum(tallyInconsistentGen(Umat))
if(Uok > Kok){
G <- Umat
} else {
G <- Kmat
}
}
randomNewG <- function(G){
alToSwap <- alleles[sample(numAlTotal, 1)]
thisSubgen <- which(G[,alToSwap] == 1)
if(n.subgen == 2){
newSubgen <- (1:2)[-thisSubgen]
} else {
newSubgen <- sample((1:n.subgen)[-thisSubgen], 1)
}
Gnew <- G
Gnew[thisSubgen,alToSwap] <- 0
Gnew[newSubgen, alToSwap] <- 1
return(list(alToSwap, Gnew))
}
nGpossible <- n.subgen ^ numAlTotal
indexG <- function(G){
baseSetup <- n.subgen ^ (1:numAlTotal - 1)
digits <- apply(G, 2, function(x) which(x == 1) - 1)
if(is.list(digits)){
index <- NA
} else {
index <- sum(baseSetup * digits) + 1
}
return(index)
}
iiList <- list()
length(iiList) <- nGpossible
inconsInd <- tallyInconsistentGen(G)
J <- mean(inconsInd)
iG <- indexG(G)
if(!is.na(iG)){
iiList[[iG]] <- inconsInd
}
if(swap && J > 0){
alleleIndex <- list()
length(alleleIndex) <- numAlTotal
names(alleleIndex) <- alleles
for(a in alleles){
alleleIndex[[a]] <- which(fisherResults$gentable[,paste(L, a, sep = ".")] == 1)
}
Ti <- T0
for(rep in 1:maxreps){
done <- TRUE
for(r in 1:R){
temp <- randomNewG(G)
Gnew <- temp[[2]]
a <- temp[[1]]
iGnew <- indexG(Gnew)
if(is.na(iGnew) || is.null(iiList[[iGnew]])){
inconsIndNew <- tallyInconsistentGen(Gnew, alleleIndex[[a]], inconsInd)
if(!is.na(iGnew)){
iiList[[iGnew]] <- inconsIndNew
}
} else {
inconsIndNew <- iiList[[iGnew]]
}
Jnew <- mean(inconsIndNew)
if(Jnew <= J){
G <- Gnew
J <- Jnew
inconsInd <- inconsIndNew
done <- FALSE
if(J == 0){
done <- TRUE
break
}
} else {
D <- Jnew - J
if(sample(10000,1) <= 10000 * exp(-D/Ti)){
G <- Gnew
J <- Jnew
inconsInd <- inconsIndNew
done <- FALSE
}
}
}
Ti <- Ti * rho
if(done) break
}
}
AlOcc <- colSums(fisherResults$gentable)/dim(fisherResults$gentable)[1]
makeA <- function(){
A <- matrix(0, nrow=n.subgen, ncol=length(alleles),
dimnames=list(NULL,alleles))
num.error <- 0
for(s in Samples(genobject)){
gen <- as.character(Genotype(genobject, s, L))
subG <- G[,gen, drop=FALSE]
if(!all(rowSums(subG[,colSums(subG) == 1, drop=FALSE])
<= SGploidy)){
donor <-
(1:n.subgen)[rowSums(subG[,colSums(subG) == 1, drop=FALSE]) >
SGploidy]
recipient <- (1:n.subgen)[rowSums(subG) < SGploidy]
if(length(recipient)==0){
recipient <- (1:n.subgen)[rowSums(subG[,colSums(subG) == 1,
drop=FALSE]) < SGploidy]
}
gendonor <- gen[colSums(subG[recipient,,drop=FALSE]==0)>0 &
colSums(subG[donor,,drop=FALSE]==1)>0]
A[recipient,gendonor] <- A[recipient,gendonor] + 1
num.error <- num.error + 1
} else {
if(!all(rowSums(subG) > 0) && null.weight > 0){
recipient <- (1:n.subgen)[rowSums(subG)==0]
A[recipient,gen] <- A[recipient,gen] + null.weight
num.error <- num.error + 1
}
}
}
prop.error <- num.error/nind
A[G==1] <- 0
return(list(A, prop.error))
}
temp <- makeA()
A <- temp[[1]]
prop.error <- temp[[2]]
numloops <- 0
while(prop.error > tolerance && numloops < 1000){
numloops <- numloops + 1
if(!all(A[,AlOcc != 1] == 0)){
A <- A[,AlOcc != 1, drop = FALSE]
}
tocopy <- which(A == max(A), arr.ind=TRUE)
if(dim(tocopy)[1]==1){
thisallele <- dimnames(A)[[2]][tocopy[,"col"]]
thissubgen <- tocopy[,"row"]
} else {
if(!is.null(fisherResults$p.values.neg)){
meanp <- numeric(dim(tocopy)[1])
for(i in 1:dim(tocopy)[1]){
thisgenal <- alleles[G[tocopy[i,"row"],] == 1]
thisgenal <- thisgenal[!thisgenal %in% alleles[AlOcc == 1]]
thisal <- dimnames(A)[[2]][tocopy[i,"col"]]
meanp <- mean(fisherResults$p.values.neg[thisgenal,thisal])
}
bestp <- which(meanp == min(meanp))
if(length(bestp) > 1){
bestp <- sample(bestp, size=1)
}
thisallele <- dimnames(A)[[2]][tocopy[bestp,"col"]]
thissubgen <- tocopy[bestp,"row"]
} else {
myrand <- sample(dim(tocopy)[1], size=1)
thisallele <- dimnames(A)[[2]][tocopy[myrand,"col"]]
thissubgen <- tocopy[myrand,"row"]
}
}
G[thissubgen, thisallele] <- 1
temp <- makeA()
A <- temp[[1]]
prop.error <- temp[[2]]
}
return(list(locus=L, SGploidy=SGploidy, assignments=G,
proportion.inconsistent.genotypes = prop.error))
}
catalanAlleles <- function(object, samples=Samples(object), locus=1,
n.subgen=2, SGploidy=2, verbose=FALSE){
object <- object[samples,]
mymissing <- isMissing(object, loci=locus)
if(all(mymissing)) stop("All data at locus are missing.")
if(length(locus) > 1) stop("More than one locus")
object <- object[!mymissing,locus]
if(is(object, "genbinary")) object <- genbinary.to.genambig(object)
if(!is(object, "genambig")) stop("genambig or genbinary object needed.")
if(n.subgen<2) stop("Need at least two subgenomes.")
numAl <- sapply(Genotypes(object), length)
if(!all(numAl <= n.subgen*SGploidy))
stop(paste("One or more genotypes have more than",
n.subgen*SGploidy, "alleles."))
if(!all(numAl >= n.subgen)){
result <- list(locus=Loci(object), SGploidy=SGploidy,
assignments="Homoplasy or null alleles: some genotypes have too few alleles")
} else {
alleles <- .unal1loc(object, Samples(object), locus)
G <- matrix(0, nrow=n.subgen, ncol=length(alleles),
dimnames=list(NULL, as.character(alleles)))
X <- Genotypes(object)[numAl==n.subgen,]
if(length(X)==0){
result <- list(locus=Loci(object), SGploidy=SGploidy,
assignments="Unresolvable: no genotypes with n.subgen alleles.")
} else {
X <- unique(X)
AlFreqInX <- sapply(alleles,
function(a) sum(sapply(X,
function(x) a %in% x)))
names(AlFreqInX) <- as.character(alleles)
Xrank <- sapply(X, function(x) sum(AlFreqInX[as.character(x)]))
X <- X[order(Xrank, decreasing=TRUE)]
gen <- as.character(X[[1]])
for(i in 1:n.subgen){
G[i,gen[i]] <- 1
}
ToAssign <- alleles[colSums(G)==0]
Xa <- X[sapply(X, function(x) sum(ToAssign %in% x)==1)]
while(length(Xa)>0){
gen <- as.character(Xa[[1]])
g <- G[,gen]
thissubgen <- rowSums(g)==0
thisallele <- gen[colSums(g)==0]
G[thissubgen,thisallele] <- 1
ToAssign <- alleles[colSums(G)==0]
Xa <- X[sapply(X, function(x) sum(ToAssign %in% x)==1)]
}
if(!all(colSums(G)!=0)){
X <- Genotypes(object)[,1]
X <- unique(X)
Xa <- X[sapply(X, function(x) (sum(ToAssign %in% x)==1 &&
sum(rowSums(G[,as.character(x)])==0)==1) ||
(sum(ToAssign %in% x) > 0 &&
sum(rowSums(G[,as.character(x)])==SGploidy)==n.subgen-1))]
while(length(Xa)>0){
g <- G[,as.character(Xa[[1]])]
thissubgen <- rowSums(g) == min(rowSums(g))
thisallele <- dimnames(g)[[2]][colSums(g)==0]
G[thissubgen,thisallele] <- 1
ToAssign <- alleles[colSums(G)==0]
Xa <- X[sapply(X, function(x) (sum(ToAssign %in% x)==1 &&
sum(rowSums(G[,as.character(x)])==0)==1) ||
(sum(ToAssign %in% x) > 0 &&
sum(rowSums(G[,as.character(x)])==SGploidy)==n.subgen-1))]
}
}
if(!all(colSums(G)!=0)){
result <- list(locus=Loci(object), SGploidy=SGploidy,
assignments="Unresolvable")
if(verbose) print(G)
} else {
badgen <- list()
bgIndex <- 1
for(s in Samples(object)){
g <- G[,as.character(Genotype(object, s, locus))]
gr <- rowSums(g)
if(!all(gr > 0 & gr <= SGploidy)){
badgen[[bgIndex]] <- Genotype(object,s,locus)
bgIndex <- bgIndex+1
}
}
if(length(badgen)==0){
result <- list(locus=Loci(object), SGploidy=SGploidy,
assignments=G)
} else {
if(verbose){
cat("Allele assignments:", sep="\n")
print(G)
cat("Inconsistent genotypes:", sep="\n")
print(badgen)
}
result <- list(locus=Loci(object), SGploidy=SGploidy,
assignments="Homoplasy or null alleles")
}
}
}
}
if(verbose) print(result)
return(result)
}
mergeAlleleAssignments <- function(x){
loci <- sapply(x, function(z) z$locus)
SGp <- sapply(x, function(z) z$SGploidy)
lociU <- unique(loci)
if(is.list(loci) || is.list(SGp) || !all(!is.na(lociU)) || !all(!is.na(SGp)))
stop("Locus and SGploidy value required for each list element.")
results <- list()
length(results) <- length(lociU)
onezero <- function(y,z){
res <- y+z
res[res==2] <- 1
return(res)
}
for(L in 1:length(lociU)){
locus <- lociU[L]
thisSGp <- unique(SGp[loci==locus])
if(length(thisSGp)>1) stop("More than one SGploidy value per locus.")
A <- lapply(x[loci==locus], function(z) z$assignments)
A <- A[sapply(A, function(z) is.matrix(z))]
if(length(A)==0){
G <- "No assignment"
} else {
A <- A[order(-sapply(A, function(x) dim(x)[2]),1:length(A))]
alleles <- unique(unlist(lapply(A, function(z) dimnames(z)[[2]])))
G <- matrix(0, nrow=dim(A[[1]])[1], ncol=length(alleles),
dimnames=list(NULL, alleles))
G[,dimnames(A[[1]])[[2]]] <- A[[1]]
A <- A[-1]
stuckcount <- 0
while(length(A)>0){
if(stuckcount==length(A)){
G <- "No assignment"
break
}
stuckcount <- 0
toremove <- integer(0)
for(i in 1:length(A)){
a <- A[[i]]
assigned <- alleles[colSums(G)>0]
overlap <- assigned[assigned %in% dimnames(a)[[2]][colSums(a)>0]]
if(length(overlap)==0 || all(G[,overlap] == 1) || all(a[,overlap] == 1)){
stuckcount <- stuckcount+1
next
}
groups <- kmeans(rbind(G[,overlap,drop = FALSE],a[,overlap,drop = FALSE]),dim(G)[1])
if(!all(1:dim(G)[1] %in% groups$cluster[1:dim(G)[1]]) ||
groups$betweenss/groups$totss <= 0.5){
stuckcount <- stuckcount + 1
next
}
G[groups$cluster[1:dim(G)[1]],dimnames(a)[[2]]] <-
onezero(G[groups$cluster[1:dim(G)[1]],dimnames(a)[[2]]],
a[groups$cluster[-(1:dim(G)[1])],])
toremove <- c(toremove,i)
}
if(length(toremove)>0) A <- A[-toremove]
}
}
results[[L]] <- list(locus=locus, SGploidy=thisSGp,
assignments=G)
}
return(results)
}
plotSSAllo <- function(AlCorrArray){
loci <- dimnames(AlCorrArray)[[1]]
pops <- dimnames(AlCorrArray)[[2]]
n.subgen <- dim(AlCorrArray[[1,1]]$Kmeans.groups)[1]
SSarray <- array(sapply(AlCorrArray, FUN = function(x) x$betweenss/x$totss), dim = dim(AlCorrArray),
dimnames = list(loci, pops))
SSarray[is.na(SSarray)] <- 0
Earray <- array(sapply(AlCorrArray, FUN = function(x){
propAl <- rowMeans(x$Kmeans.groups)
return(1 - sum(propAl^2))
}), dim = dim(AlCorrArray), dimnames = list(loci, pops))
posCor <- sapply(AlCorrArray, FUN = function(x) any(x$significant.pos, na.rm = TRUE))
posCor <- array(posCor, dim = dim(AlCorrArray), dimnames = list(loci, pops))
if(length(pops) == 1){
popCol = "black"
bgCol = "white"
} else {
bgCol = "lightgrey"
if(length(pops) == 2){
popCol = c("red", "blue")
} else {
popCol = rainbow(length(pops))
}
}
oldBg = par()$bg
par(bg = bgCol)
maxE <- 1 - n.subgen * 1/n.subgen^2
maxNalleles <- max(sapply(AlCorrArray, FUN = function(x) dim(x$Kmeans.groups)[2]))
minE <- 1 - (n.subgen - 1) * 1/maxNalleles^2 - ((maxNalleles - n.subgen + 1)/maxNalleles)^2
minSS <- 0
maxSS <- 1
if(length(pops) == 1){
Xlim <- c(minSS, maxSS)
} else {
Xlim <- c(minSS, maxSS + (maxSS - minSS)/4)
}
Ylim <- c(minE, maxE)
plot(as.vector(SSarray), as.vector(Earray), col = bgCol, main = "K-means results",
xlab = "Sums of squares between isoloci/total sums of squares",
ylab = "Evenness of number of alleles among isoloci", xlim = Xlim, ylim = Ylim)
text(minSS, minE, labels = "Low quality allele clustering", adj = 0)
text(maxSS, maxE, labels = "High quality allele clustering", adj = 1)
for(p in 1:length(pops)){
text(SSarray[,p], Earray[,p], labels = loci, col = popCol[p], font = ifelse(posCor[,p], 3, 1))
}
if(length(pops) > 1){
legend(maxSS, 0.75 * (Ylim[2] - Ylim[1]) + Ylim[1], legend = pops,
text.col = popCol, title = "Populations", title.col = "black")
}
par(bg = oldBg)
return(invisible(list(ssratio = SSarray, evenness = Earray,
max.evenness = maxE, min.evenness = minE,
posCor = posCor)))
}
plotParamHeatmap <- function(propMat, popname = "AllInd", col = grey.colors(12)[12:1],
main = ""){
if(length(dim(propMat)) == 3){
propMat <- propMat[,popname,]
}
if(length(dim(propMat)) != 2){
stop("propMat must have two dimensions.")
}
nloc <- dim(propMat)[1]
nparam <- dim(propMat)[2]
image(1:nparam, 1:nloc, t(propMat), xlab = "Parameter sets", ylab = "Loci",
main = paste(main,popname), axes = FALSE, col = col, zlim = c(0,1))
axis(1, at = 1:nparam)
axis(2, at = 1:nloc, labels = dimnames(propMat)[[1]])
for(i in 1:nloc){
text(which.min(propMat[i,]),i, "best")
}
}
processDatasetAllo <- function(object, samples = Samples(object), loci = Loci(object),
n.subgen = 2, SGploidy = 2, n.start = 50, alpha = 0.05,
parameters = data.frame(tolerance = c(0.05, 0.05, 0.05, 0.05),
swap = c(TRUE, FALSE, TRUE, FALSE),
null.weight = c(0.5, 0.5, 0, 0)),
plotsfile = "alleleAssignmentPlots.pdf", usePops = FALSE, ...){
if(!all(samples %in% Samples(object))){
stop("Sample names in samples and object do not match.")
}
if(!all(loci %in% Loci(object))){
stop("Locus names in loci and object do not match.")
}
if(!all(c("tolerance", "swap", "null.weight") %in% names(parameters))){
stop("Parameters data frame needs column headers tolerance, swap, and null.weight.")
}
object <- object[samples,]
nparam <- dim(parameters)[1]
if(usePops){
popinfo <- PopInfo(object)
if(any(is.na(popinfo))){
stop("PopInfo needed in object if usePops = TRUE.")
}
popnamesTemp <- PopNames(object)[popinfo]
allpops <- unique(popnamesTemp)
popinfo <- match(popnamesTemp, allpops)
npops <- length(allpops)
} else {
popinfo <- rep(1, length(samples))
allpops <- "AllInd"
npops <- 1
}
CorrResults <- array(list(), dim = c(length(loci), npops),
dimnames = list(loci, allpops))
TAGresults <- array(list(), dim = c(length(loci), npops, nparam),
dimnames = list(loci, allpops, NULL))
for(p in 1:npops){
thesesamples <- samples[popinfo == p]
for(L in loci){
CorrResults[[L, p]] <- alleleCorrelations(object, samples = thesesamples, locus = L,
alpha = alpha, n.subgen = n.subgen, n.start = n.start)
for(pm in 1:nparam){
TAGresults [[L, p, pm]] <- testAlGroups(object, CorrResults[[L, p]], SGploidy = SGploidy,
samples = thesesamples, null.weight = parameters$null.weight[pm],
tolerance = parameters$tolerance[pm], swap = parameters$swap[pm], ...)
}
}
}
propHomoplasious <- sapply(TAGresults, FUN = function(x){mean(colSums(x$assignments) > 1)})
propHomoplasious <- array(propHomoplasious, dim = dim(TAGresults), dimnames = dimnames(TAGresults))
if(usePops){
mergedAssignments <- array(list(), dim = c(length(loci), nparam),
dimnames = list(loci, NULL))
for(L in loci){
theseSamples <- samples[!isMissing(object, samples, L)]
for(pm in 1:nparam){
mergedAssignments[L,pm] <- mergeAlleleAssignments(TAGresults[L,,pm])
totInconsistent <- 0
if(is.matrix(mergedAssignments[[L,pm]]$assignments)){
for(s in theseSamples){
gen <- as.character(Genotype(object, s, L))
subg <- mergedAssignments[[L,pm]]$assignments[, gen, drop = FALSE]
if(any(rowSums(subg) == 0) ||
any(rowSums(subg[,colSums(subg) == 1, drop = FALSE]) > SGploidy)){
totInconsistent <- totInconsistent + 1
}
}
} else {
totInconsistent <- length(theseSamples)
}
mergedAssignments[[L,pm]]$proportion.inconsistent.genotypes <- totInconsistent/length(theseSamples)
}
}
propHomoplMerged <- sapply(mergedAssignments, FUN = function(x){
if(is.matrix(x$assignments)){
return(mean(colSums(x$assignments) > 1))
} else {
return(1)
}
})
propHomoplMerged <- array(propHomoplMerged, dim = dim(mergedAssignments),
dimnames = dimnames(mergedAssignments))
} else {
mergedAssignments <- TAGresults[,1,]
propHomoplMerged <- propHomoplasious[,1,]
}
bestpm <- integer(length(loci))
names(bestpm) <- loci
missRate <- matrix(1, nrow = length(loci), ncol = nparam, dimnames = list(loci, NULL))
for(L in loci){
theseAssign <- list()
theseAssignIndex <- integer(nparam)
for(pm in 1:nparam){
if(!is.matrix(mergedAssignments[[L,pm]]$assignments)) next
thisAssign <- data.frame(mergedAssignments[[L,pm]]$assignments)
thisAssign <- thisAssign[do.call(order, thisAssign),]
row.names(thisAssign) <- 1:dim(thisAssign)[1]
matchUn <- sapply(theseAssign, function(x) identical(x, thisAssign))
if(length(theseAssign) == 0 || all(!matchUn)){
theseAssign[[length(theseAssign) + 1]] <- thisAssign
theseAssignIndex[pm] <- length(theseAssign)
} else {
theseAssignIndex[pm] <- which(matchUn)
}
}
if(all(theseAssignIndex == 0)) next
for(a in 1:length(theseAssign)){
amat <- as.matrix(theseAssign[[a]])
dimnames(amat)[[2]] <- gsub("X", "", dimnames(amat)[[2]])
r <- recodeAllopoly(object, list(list(locus = L, SGploidy = SGploidy,
assignments = amat)),
allowAneuploidy = FALSE, loci = L)
oldMissing <- sum(isMissing(object, loci = L))
miss <- (sum(isMissing(r))/n.subgen - oldMissing)/(length(samples) - oldMissing)
missRate[L, which(theseAssignIndex == a)] <- miss
}
bestMiss <- which(missRate[L,] == min(missRate[L,], na.rm = TRUE))
bestpm[L] <- bestMiss[which.min(propHomoplMerged[L, bestMiss])]
}
bestpm[bestpm == 0] <- 1
bestAssign <- list()
for(l in 1:length(loci)){
bestAssign[[l]] <- mergedAssignments[[l, bestpm[l]]]
}
pdf(plotsfile)
plotSS <- plotSSAllo(CorrResults)
for(L in loci){
for(p in allpops){
if(!is.null(CorrResults[[L,p]]$heatmap.dist)){
heatmap(CorrResults[[L,p]]$heatmap.dist, main = paste(L, p, sep = ", "))
} else {
plot(NA, xlim = c(0,10), ylim = c(0,10), main = paste(L, p, sep = ", "))
text(5,5, "Fisher's exact tests not performed.\nOne or more alleles are present in all individuals.")
}
}
}
for(p in allpops){
plotParamHeatmap(propHomoplasious[,p,], popname = p, main = "Proportion homoplasious loci:")
}
if(usePops){
plotParamHeatmap(propHomoplMerged, popname = "Merged across populations", main = "Proportion homoplasious loci:")
}
plotParamHeatmap(missRate, popname = "All Individuals", main = "Missing data after recoding:")
dev.off()
return(list(AlCorrArray = CorrResults, TAGarray = TAGresults, plotSS = plotSS,
propHomoplasious = propHomoplasious, mergedAssignments = mergedAssignments,
propHomoplMerged = propHomoplMerged, missRate = missRate, bestAssign = bestAssign))
}
recodeAllopoly <- function(object, x, allowAneuploidy=TRUE,
samples=Samples(object), loci=Loci(object)){
if(is(object, "genbinary")) object <- genbinary.to.genambig(object)
if(!is(object, "genambig"))
stop("'genbinary' or 'genambig' object required.")
object <- object[samples, loci]
lociA <- sapply(x, function(z) z$locus)
SGp <- sapply(x, function(z) z$SGploidy)
if(is.list(lociA) || is.list(SGp) || !all(!is.na(lociA)) ||
!all(!is.na(SGp)))
stop("Locus and SGploidy value required for each list element in x.")
if(!all(lociA %in% loci)){
warning(paste("Loci", paste(lociA[!lociA %in% loci], collapse=" "),
"found in 'x' but not 'loci'."))
x <- x[lociA %in% loci]
if(length(x)==0)
stop("No recoding possible because locus names do not match")
lociA <- sapply(x, function(z) z$locus)
SGp <- sapply(x, function(z) z$SGploidy)
}
if(!all(table(lociA)==1)){
x <- mergeAlleleAssignments(x)
lociA <- sapply(x, function(z) z$locus)
SGp <- sapply(x, function(z) z$SGploidy)
}
names(SGp) <- lociA
nSG <- sapply(x, function(z) ifelse(is.matrix(z$assignments),
dim(z$assignments)[1], NA))
names(nSG) <- lociA
A <- lapply(x, function(z) z$assignments)
names(A) <- lociA
lociA <- lociA[!is.na(nSG)]
SGp <- SGp[lociA]
nSG <- nSG[lociA]
A <- A[lociA]
newloci <- paste(rep(lociA, times=nSG),unlist(lapply(nSG, function(y) 1:y)),
sep="_")
extraloci <- loci[!loci %in% lociA]
newloci <- c(newloci, extraloci)
result <- new("genambig", samples, newloci)
PopNames(result) <- PopNames(object)
PopInfo(result) <- PopInfo(object)[samples]
Description(result) <- Description(object)
Missing(result) <- Missing(object)
newploidies <- matrix(rep(SGp, times=nSG), nrow=length(samples),
ncol=sum(!newloci %in% extraloci),
byrow=TRUE)
if(length(extraloci) > 0){
if(is(object@Ploidies, "ploidymatrix")){
newploidies <- cbind(newploidies,
Ploidies(object, samples=samples,
loci=extraloci))
}
if(is(object@Ploidies, "ploidylocus")){
newploidies <- cbind(newploidies,
matrix(Ploidies(object, loci=extraloci),
nrow=length(samples), ncol=length(extraloci),
byrow=TRUE))
}
if(is(object@Ploidies, "ploidysample") || is(object@Ploidies, "ploidyone")){
newploidies <- cbind(newploidies,
matrix(Ploidies(object, loci=extraloci),
nrow=length(samples), ncol=length(extraloci),
byrow=FALSE))
}
}
Ploidies(result) <- newploidies
if(!allowAneuploidy && plCollapse(result@Ploidies, na.rm=FALSE, returnvalue=FALSE)){
result <- reformatPloidies(result, output="collapse")
}
for(L in loci){
Lindex <- which(sapply(strsplit(newloci, "_"), function(y) y[1]) == L)
Usatnts(result)[Lindex] <- Usatnts(object)[L]
if(length(Lindex)==1){
Genotypes(result, loci=Lindex) <- Genotypes(object, loci=L)
Ploidies(result)[,Lindex] <- Ploidies(object, Samples(object), L)
} else {
xsamples <- samples[!isMissing(object, samples, L)]
LisInt <- all(sapply(Genotypes(object, xsamples, L),
is.integer, USE.NAMES=FALSE))
LisNum <- all(sapply(Genotypes(object, xsamples, L),
is.numeric, USE.NAMES=FALSE))
AL <- A[[L]]
allelesL <- as.character(.unal1loc(object, xsamples, L))
allelesUA <- allelesL[!allelesL %in% dimnames(AL)[[2]]]
if(length(allelesUA)>0){
toadd <- matrix(1, nrow=length(Lindex), ncol=length(allelesUA),
dimnames=list(NULL, allelesUA))
AL <- cbind(AL, toadd)
}
for(s in xsamples){
thisgen <- as.character(Genotype(object, s, L))
thisA <- AL[,thisgen, drop=FALSE]
if(length(thisgen) > nSG[L]*SGp[L]){
next
}
SGcomplete <- rep(FALSE, nSG[L])
alBySG <- rep(list(character(0)), nSG[L])
stumped <- FALSE
while(sum(!SGcomplete)>0 & !stumped){
stumped <- TRUE
SGtoassign <- (1:nSG[L])[!SGcomplete]
for(sg in SGtoassign){
sgAl <- thisgen[thisA[sg,]==1 &
colSums(thisA)==1]
if(length(sgAl)>=SGp[L]){
alBySG[[sg]] <- sgAl
SGcomplete[sg] <- TRUE
stumped <- FALSE
thisA[sg,-match(sgAl, thisgen)] <- 0
} else {
sgAl <- thisgen[thisA[sg,]==1]
if(length(sgAl)==1 ||
all(colSums(thisA[,sgAl])==1)){
alBySG[[sg]] <- sgAl
SGcomplete[sg] <- TRUE
stumped <- FALSE
}
}
}}
nAl <- sapply(alBySG, length)
if(!all(nAl <= SGp[L])){
if(allowAneuploidy){
newploidies <- nAl
while(sum(newploidies) < nSG[L]*SGp[L]){
newploidies[newploidies==min(newploidies[newploidies!=0])] <-
newploidies[newploidies==min(newploidies[newploidies!=0])] + 1
}
Ploidies(result)[s,Lindex] <- newploidies
} else {
next
}
}
if(LisInt){
alBySG <- lapply(alBySG, as.integer)
} else {
if(LisNum){
alBySG <- lapply(alBySG, as.numeric)
}
}
alBySG[nAl==0] <- Missing(result)
Genotypes(result, samples=s,loci=Lindex) <- alBySG
}
}
}
return(result)
} |
map.mod <- function(object, dim = c(1, 2),
point.shape = "variable", point.alpha = 0.8,
point.fill = "whitesmoke", point.color = "black", point.size = "freq",
label = TRUE, label.repel = FALSE, label.alpha = 0.8, label.color = "black", label.size = 4, label.fill = NULL,
map.title = "mod", labelx = "default", labely = "default", legend = NULL){
plot.type <- "mod"
plot.flow(object,
dim = dim,
point.shape = point.shape,
point.alpha = point.alpha,
point.fill = point.fill,
point.color = point.color,
point.size = point.size,
label = label,
label.repel = label.repel,
label.alpha = label.alpha,
label.color = label.color,
label.size = label.size,
label.fill = label.fill,
map.title = map.title,
labelx = labelx,
labely = labely,
legend = legend,
plot.type = plot.type)
}
map.ctr <- function(object, dim = c(1, 2), ctr.dim = 1,
point.shape = "variable", point.alpha = 0.8, point.fill = "whitesmoke",
point.color = "black", point.size = "freq",
label = TRUE, label.repel = TRUE, label.alpha = 0.8, label.color = "black", label.size = 4, label.fill = NULL,
map.title = "ctr", labelx = "default", labely = "default", legend = NULL){
plot.type <- "ctr"
plot.flow(object,
dim = dim,
ctr.dim = ctr.dim,
point.shape = point.shape,
point.alpha = point.alpha,
point.fill = point.fill,
point.color = point.color,
point.size = point.size,
label = label,
label.repel = label.repel,
label.alpha = label.alpha,
label.color = label.color,
label.size = label.size,
label.fill = label.fill,
map.title = map.title,
labelx = labelx,
labely = labely,
legend = legend,
plot.type = plot.type)
}
map.active <- function(object, dim = c(1, 2),
point.shape = "variable", point.alpha = 0.8, point.fill = "whitesmoke",
point.color = "black", point.size = "freq",
label = TRUE, label.repel = FALSE, label.alpha = 0.8, label.color = "black", label.size = 4, label.fill = NULL,
map.title = "active", labelx = "default", labely = "default", legend = NULL){
plot.type <- "active"
plot.flow(object,
dim = dim,
point.shape = point.shape,
point.alpha = point.alpha,
point.fill = point.fill,
point.color = point.color,
point.size = point.size,
label = label,
label.repel = label.repel,
label.alpha = label.alpha,
label.color = label.color,
label.size = label.size,
label.fill = label.fill,
map.title = map.title,
labelx = labelx,
labely = labely,
legend = legend,
plot.type = plot.type)
}
map.sup <- function(object, dim = c(1, 2),
point.shape = "variable", point.alpha = 0.8, point.fill = "whitesmoke",
point.color = "black", point.size = "freq",
label = TRUE, label.repel = TRUE, label.alpha = 0.8, label.color = "black", label.size = 4, label.fill = NULL,
map.title = "sup", labelx = "default", labely = "default", legend = NULL){
plot.type <- "sup"
plot.flow(object,
dim = dim,
point.shape = point.shape,
point.alpha = point.alpha,
point.fill = point.fill,
point.color = point.color,
point.size = point.size,
label = label,
label.repel = label.repel,
label.alpha = label.alpha,
label.color = label.color,
label.size = label.size,
label.fill = label.fill,
map.title = map.title,
labelx = labelx,
labely = labely,
legend = legend,
plot.type = plot.type)
}
map.ind <- function(object, dim = c(1, 2),
point.shape = 21, point.alpha = 0.8, point.fill = "whitesmoke",
point.color = "black", point.size = 3,
label = FALSE, label.repel = FALSE, label.alpha = 0.8, label.color = "black", label.size = 4, label.fill = NULL,
map.title = "ind", labelx = "default", labely = "default", legend = NULL){
plot.type <- "ind"
plot.flow(object,
dim = dim,
point.shape = point.shape,
point.alpha = point.alpha,
point.fill = point.fill,
point.color = point.color,
point.size = point.size,
label = label,
label.repel = label.repel,
label.alpha = label.alpha,
label.color = label.color,
label.size = label.size,
label.fill = label.fill,
map.title = map.title,
labelx = labelx,
labely = labely,
legend = legend,
plot.type = plot.type)
}
map.select <- function(object, dim = c(1, 2), ctr.dim = 1,
list.mod = NULL, list.sup = NULL, list.ind = NULL,
point.shape = "variable", point.alpha = 0.8, point.fill = "whitesmoke",
point.color = "black", point.size = "freq",
label = TRUE, label.repel = FALSE, label.alpha = 0.8, label.color = "black", label.size = 4, label.fill = NULL,
map.title = "select", labelx = "default", labely = "default", legend = NULL, ...){
modal.list <- list(list.mod = list.mod, list.sup = list.sup, list.ind = list.ind)
plot.type <- "select"
plot.flow(object,
dim = dim,
ctr.dim = ctr.dim,
modal.list = modal.list,
point.shape = point.shape,
point.alpha = point.alpha,
point.fill = point.fill,
point.color = point.color,
point.size = point.size,
label = label,
label.repel = label.repel,
label.alpha = label.alpha,
label.color = label.color,
label.size = label.size,
label.fill = label.fill,
map.title = map.title,
labelx = labelx,
labely = labely,
legend = legend,
plot.type = plot.type)
}
map.add <- function(object, ca.map, plot.type = NULL,
ctr.dim = 1, list.mod = NULL, list.sup = NULL, list.ind = NULL,
point.shape = "variable", point.alpha = 0.8, point.fill = "whitesmoke",
point.color = "black", point.size = "freq",
label = TRUE, label.repel = TRUE, label.alpha = 0.8, label.color = "black", label.size = 4, label.fill = NULL,
labelx = "default", labely = "default", legend = NULL){
p <- ca.map
dim <- ca.map$dimensions
org.scales <- ca.map$ca.scales
modal.list <- list(list.mod = list.mod, list.sup = list.sup, list.ind = list.ind)
gg.data <- data.plot(object,
plot.type = plot.type,
dim = dim,
ctr.dim = ctr.dim,
modal.list = modal.list,
point.size = point.size,
point.variable = point.shape)
if(identical(point.shape,"variable")) point.shape <- gg.data$variable
if(identical(point.size,"freq")) point.size <- gg.data$freq
point.l <- list(x = gg.data$x,
y = gg.data$y,
shape = point.shape,
alpha = point.alpha,
fill = point.fill,
color = point.color,
size = point.size)
p.i <- unlist(lapply(point.l, length)) == 1
point.attributes <- point.l[p.i == TRUE]
point.aes <- point.l[p.i == FALSE]
label.l <- list(x = gg.data$x,
y = gg.data$y,
label = gg.data$names,
alpha = label.alpha,
color = label.color,
fill = label.fill,
size = label.size)
t.i <- unlist(lapply(label.l, length)) == 1
label.attributes <- label.l[t.i == TRUE]
label.aes <- label.l[t.i == FALSE]
gg.input <- list(gg.data = gg.data,
label = label,
repel = label.repel,
point.aes = point.aes,
point.attributes = point.attributes,
label.aes = label.aes,
label.attributes = label.attributes)
point.attributes <- gg.input$point.attributes
point.attributes$mapping <- do.call("aes", gg.input$point.aes)
p <- p + do.call("geom_point", point.attributes, quote = TRUE)
shapes <- c(21, 22, 23, 24, 25, 6, 0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 12, 15, 16, 17, 18,
42, 45, 61, 48, 50:120)
p <- p + scale_shape_manual(values = shapes)
if (gg.input$label == TRUE){
label.attributes <- gg.input$label.attributes
label.attributes$vjust <- 1.8
label.attributes$family <- "sans"
label.attributes$lineheight <- 0.9
label.attributes$mapping <- do.call("aes", gg.input$label.aes)
if(is.null(gg.input$label.aes$fill) & gg.input$repel == TRUE & is.null(label.attributes$fill)){
label.attributes$vjust <- NULL
p <- p + do.call("geom_text_repel", label.attributes, quote = TRUE)
}
if(is.null(gg.input$label.aes$fill) == FALSE | is.null(label.attributes$fill) == FALSE){
label.attributes$vjust <- NULL
p <- p + do.call("geom_label_repel", label.attributes, quote = TRUE)
}
if(is.null(gg.input$label.aes$fill) & gg.input$repel == FALSE){
p <- p + do.call("geom_text", label.attributes, quote = TRUE)
}
}
org.max <- org.scales$lim.max
org.min <- org.scales$lim.min
n.max <- max(c(max(gg.data[,1:2]), org.max))
n.min <- (c(min(gg.data[,1:2]), org.min))
tscales <- gg.data
tscales[1, 1:2] <- n.max
tscales[2, 1:2] <- n.min
scales <- breaksandscales(tscales)
p <- p + scale_x_continuous(breaks = scales$scalebreaks, labels = scales$breaklabel)
p <- p + scale_y_continuous(breaks = scales$scalebreaks, labels = scales$breaklabel)
p$ca.scales <- scales
if(is.null(legend)) p <- p + theme(legend.position = "none")
if(identical(legend,"bottom")) p <- p + theme(legend.position = 'bottom',
legend.direction = "horizontal", legend.box = "horizontal")
p
}
map.density <- function(object, map = map.ind(object), group = NULL,
color = "red", alpha = 0.8, size = 0.5, linetype = "solid"){
dim <- map$dimensions
dens.data <- as.data.frame(object$coord.ind[, dim])
colnames(dens.data) <- c("x", "y")
density.l <- list(color = color,
alpha = alpha,
size = size,
linetype = linetype,
n = 100,
group = group,
na.rm = TRUE)
d.i <- unlist(lapply(density.l, length)) == 1
density.attributes <- density.l[d.i]
density.aes <- density.l[unlist(lapply(density.l, length)) > 1]
density.aes$x <- dens.data$x
density.aes$y <- dens.data$y
density.attributes$mapping <- do.call("aes", density.aes)
p <- map + do.call("geom_density2d", density.attributes, quote = TRUE)
p
}
plot.flow <- function(object, dim = c(1, 2), ctr.dim = NULL, modal.list = NULL,
point.shape = 21, point.alpha = 0.8, point.fill = "whitesmoke",
point.color = "black", point.size = 3,
label = FALSE, label.repel = FALSE, label.alpha = 0.8, label.color = "black", label.size = 4, label.fill = NULL,
map.title = map.title, labelx = "default", labely = "default", legend = NULL,
plot.type = plot.type){
gg.proc <- round(object$adj.inertia[,4])
gg.data <- data.plot(object,
plot.type = plot.type,
dim,
ctr.dim = ctr.dim,
modal.list = modal.list,
point.size = point.size,
point.color = point.color)
axis.labels <- plot.axis(labelx = labelx, labely = labely, gg.proc = gg.proc, dim = dim)
map.title <- plot.title(map.title = map.title, ctr.dim = ctr.dim)
scales <- breaksandscales(gg.data)
if (identical(point.shape,"variable")) point.shape <- gg.data$variable
if (identical(point.size,"freq")) point.size <- gg.data$freq
point.l <- list(x = gg.data$x,
y = gg.data$y,
shape = point.shape,
alpha = point.alpha,
fill = point.fill,
color = point.color,
size = point.size)
p.i <- unlist(lapply(point.l, length)) == 1
point.attributes <- point.l[p.i == TRUE]
point.aes <- point.l[p.i == FALSE]
label.l <- list(x = gg.data$x,
y = gg.data$y,
label = gg.data$names,
alpha = label.alpha,
color = label.color,
fill = label.fill,
size = label.size)
t.i <- unlist(lapply(label.l, length)) == 1
label.attributes <- label.l[t.i == TRUE]
label.aes <- label.l[t.i == FALSE]
gg.input <- list(gg.data = gg.data,
axis.inertia = gg.proc,
map.title = map.title,
labelx = axis.labels$x,
labely = axis.labels$y,
scales = scales,
label = label,
repel = label.repel,
point.aes = point.aes,
point.attributes = point.attributes,
label.aes = label.aes,
label.attributes = label.attributes)
b.plot <- basic.plot(gg.input)
t.plot <- b.plot + theme_min()
if(is.null(legend)) t.plot <- t.plot + theme(legend.position = "none")
if(identical(legend,"bottom")) t.plot <- t.plot + theme(legend.position = 'bottom',
legend.direction = "horizontal", legend.box = "horizontal")
t.plot$dimensions <- dim
return(t.plot)
}
basic.plot <- function(gg.input){
p <- ggplot()
p <- p + geom_hline(yintercept = 0, color = "grey50", size = 0.5, linetype = "solid")
p <- p + geom_vline(xintercept = 0, color = "grey50", size = 0.5, linetype = "solid")
point.attributes <- gg.input$point.attributes
point.attributes$mapping <- do.call("aes", gg.input$point.aes)
p <- p + do.call("geom_point", point.attributes, quote = TRUE)
shapes <- getOption("soc.ca.shape")
p <- p + scale_shape_manual(values = shapes)
if (gg.input$label == TRUE){
label.attributes <- gg.input$label.attributes
label.attributes$vjust <- 1.8
label.attributes$family <- "sans"
label.attributes$lineheight <- 0.9
label.attributes$mapping <- do.call("aes", gg.input$label.aes)
if(is.null(gg.input$label.aes$fill) & gg.input$repel == TRUE & is.null(label.attributes$fill)){
label.attributes$vjust <- NULL
label.attributes$max.iter <- 2000
p <- p + do.call("geom_text_repel", label.attributes, quote = TRUE)
}
if(is.null(gg.input$label.aes$fill) == FALSE | is.null(label.attributes$fill) == FALSE){
label.attributes$vjust <- NULL
label.attributes$max.iter <- 2000
p <- p + do.call("geom_label_repel", label.attributes, quote = TRUE)
}
if(is.null(gg.input$label.aes$fill) & gg.input$repel == FALSE){
p <- p + do.call("geom_text", label.attributes, quote = TRUE)
}
}
p <- p + ggtitle(label = gg.input$map.title)
p <- p + xlab(gg.input$labelx) + ylab(gg.input$labely)
p <- p + labs(alpha = "Alpha", shape = "Shape",
color = "Color", linetype = "Linetype", size = "Size", fill = "Fill")
p <- p + scale_x_continuous(breaks = gg.input$scales$scalebreaks, labels = gg.input$scales$breaklabel)
p <- p + scale_y_continuous(breaks = gg.input$scales$scalebreaks, labels = gg.input$scales$breaklabel)
p <- p + coord_fixed()
p$ca.scales <- gg.input$scales
p
}
plot.title <- function(map.title = NULL, ctr.dim = NULL){
if (identical(map.title, "ctr") == TRUE) {
map.title <- paste("The modalities contributing above average to dimension ",
paste(ctr.dim, collapse = " & "), sep = "")
}
if (identical(map.title, "mod") == TRUE) {
map.title <- "Map of all modalities"
}
if (identical(map.title, "active") == TRUE) {
map.title <- "Map of active modalities"
}
if (identical(map.title, "sup") == TRUE) {
map.title <- "Map of supplementary modalities"
}
if (identical(map.title, "ind") == TRUE) {
map.title <- "Map of individuals"
}
if (identical(map.title, "select") == TRUE) {
map.title <- "Map of selected modalities"
}
return(map.title)
}
plot.axis <- function(labelx = "default", labely = "default", gg.proc = NA, dim = NULL){
if (identical(labelx, "default") == TRUE) {
labelx <- paste(dim[1], ". Dimension: ", gg.proc[dim[1]], "%", sep = "")
}
if (identical(labely, "default") == TRUE) {
labely <- paste(dim[2], ". Dimension: ", gg.proc[dim[2]], "%", sep = "")
}
axis.labels <- list(x = labelx, y = labely)
return(axis.labels)
}
breaksandscales <- function(gg.data){
mround <- function(x, base){
base*round(x/base)
}
lim.min.x <- min(gg.data[, 1])
lim.min.y <- min(gg.data[, 2])
lim.max.x <- max(gg.data[, 1])
lim.max.y <- max(gg.data[, 2])
scalebreaks <- seq(-10,10, by = 0.25)
nolabel <- seq(-10, 10, by = 0.5)
inter <- intersect(scalebreaks, nolabel)
truelabel <- is.element(scalebreaks, nolabel)
breaklabel <- scalebreaks
breaklabel[truelabel == FALSE] <- ""
length.x <- sqrt(lim.min.x^2) + sqrt(lim.max.x^2)
length.y <- sqrt(lim.min.y^2) + sqrt(lim.max.y^2)
scales <- list(scalebreaks = scalebreaks,
breaklabel = breaklabel,
lim.min.x = lim.min.x,
lim.min.y = lim.min.y,
lim.max.x = lim.max.x,
lim.max.y = lim.max.y,
length.x = length.x,
length.y = length.y)
return(scales)
}
data.plot <- function(object, plot.type, dim, ctr.dim = NULL,
modal.list = NULL, point.size = "freq", point.variable = NULL, point.color = NULL){
if (identical(plot.type, "mod") == TRUE){
coord <- rbind(object$coord.mod, object$coord.sup)
mnames <- c(object$names.mod, object$names.sup)
freq <- c(object$freq.mod, object$freq.sup)
variable <- c(object$variable, object$variable.sup)
}
if (identical(plot.type, "ctr") == TRUE){
av.ctr <- contribution(object, ctr.dim, indices = TRUE, mode = "mod")
coord <- object$coord.mod[av.ctr, ]
mnames <- object$names.mod[av.ctr]
freq <- object$freq.mod[av.ctr]
variable <- object$variable[av.ctr]
}
if (identical(plot.type, "active") == TRUE){
coord <- object$coord.mod
mnames <- object$names.mod
freq <- object$freq.mod
variable <- object$variable
}
if (identical(plot.type, "sup") == TRUE){
coord <- object$coord.sup
mnames <- object$names.sup
freq <- object$freq.sup
variable <- object$variable.sup
}
if (identical(plot.type, "ind") == TRUE){
coord <- object$coord.ind
mnames <- object$names.ind
freq <- rep(1, object$n.ind)
if(identical(point.variable, NULL)){
variable <- rep("ind", nrow(object$coord.ind))
}else{
variable <- point.variable
}
if(identical(point.color, NULL) == FALSE)
point.color <- point.color
}
if (identical(plot.type, "select") == TRUE){
coord.mod <- object$coord.mod[modal.list$list.mod, ]
coord.sup <- object$coord.sup[modal.list$list.sup, ]
coord.ind <- object$coord.ind[modal.list$list.ind, ]
names.mod <- object$names.mod[modal.list$list.mod]
names.sup <- object$names.sup[modal.list$list.sup]
names.ind <- object$names.ind[modal.list$list.ind]
coord <- rbind(coord.mod, coord.sup, coord.ind)
rownames(coord) <- NULL
mnames <- c(names.mod, names.sup, names.ind)
freq.mod <- object$freq.mod[modal.list$list.mod]
freq.sup <- object$freq.sup[modal.list$list.sup]
freq.ind <- rep(1, object$n.ind)[modal.list$list.ind]
freq <- c(freq.mod, freq.sup, freq.ind)
variable.mod <- object$variable[modal.list$list.mod]
variable.sup <- object$variable.sup[modal.list$list.sup]
variable.ind <- rep("ind", object$n.ind)[modal.list$list.ind]
variable <- c(variable.mod, variable.sup, variable.ind)
}
if(is.numeric(point.size)) freq <- rep(point.size, length.out = nrow(coord))
if(is.null(point.color)) point.color <- rep("Nothing", length.out = nrow(coord))
gg.data <- data.frame(cbind(coord[, dim[1]], coord[,dim[2]]), mnames, freq, variable, point.color)
colnames(gg.data) <- c("x", "y", "names", "freq", "variable", "point.color")
return(gg.data)
}
add.count <- function(x, p, label = TRUE, ...){
p <- p + geom_point(data = x, x = x$X, y = x$Y, ...) + geom_path(data = x, x = x$X, y = x$Y, ...)
if (identical(label, TRUE)) p <- p + geom_text(data = x, x = x$X, y = x$Y, label = x$label, vjust = 0.2, ...)
}
map.path <- function(object, x, map = map.ind(object, dim), dim = c(1, 2),
label = TRUE, min.size = length(x)/10, ...){
x.c <- x
if (is.numeric(x)) x.c <- min_cut(x, min.size = min.size)
x.av <- average.coord(object = object, x = x.c, dim = dim)
x.av["X"] <- x.av["X"] * sqrt(object$eigen[dim[1]])
x.av["Y"] <- x.av["Y"] * sqrt(object$eigen[dim[2]])
map.p <- add.count(x.av, map, label, ...)
map.p
}
map.top.ind <- function(result, ctr.dim = 1, dim = c(1,2), top = 15){
sc <- list()
sc$fill <- scale_fill_continuous(low = "white", high = "darkblue")
sc$alpha <- scale_alpha_manual(values = c(0.5, 1))
ctr <- result$ctr.ind[, ctr.dim]
above.average <- ctr >= mean(ctr)
important <- rank(ctr) > length(ctr) - top
r <- result
r$names.ind[-which(important)] <- NA
m <- map.ind(r, point.alpha = above.average, label = TRUE, point.shape = 21, point.fill = ctr, label.repel = TRUE, dim = dim, label.size = 3)
m + sc + ggtitle(paste("Map of the", top, "most contributing individuals for dim.", ctr.dim))
} |
drawnorm <- function(mu = 0, sigma = 1, xlab = "A Normally Distributed Variable",
ylab = "Probability Density", main, ps = par("ps"), ...){
dotargs <- list(...)
dotnames <- names(dotargs)
dots.par <- dotargs[names(dotargs)[names(dotargs) %in% c(names(par()), formalArgs(plot.default))]]
sigma.rounded <- if(1 == sigma[1]) 1 else round(sigma[1],2)
mu.rounded <- round(mu, 2)
myx <- seq( mu - 3.5*sigma, mu+ 3.5*sigma, length.out=500)
myDensity <- dnorm(myx,mean=mu,sd=sigma)
if(missing(main)) {
main <- bquote(x %~% Normal~group("(", list(mu == .(mu.rounded),
sigma^2 == .(if(sigma[1] == 1) 1 else sigma.rounded^2)),")"))
}
par.orig <- par(xpd=TRUE, ps = ps)
on.exit(par(par.orig))
plot.parms <- list(x = myx, y = myDensity, type = "l", xlab = xlab, ylab = ylab, main = main, axes = FALSE)
plot.parms <- modifyList(plot.parms, dots.par)
do.call(plot, plot.parms)
axis(2, pos = mu - 3.6*sigma)
ticksat <- c(mu - 2.5 * sigma, mu, mu - sigma, mu + sigma, mu + 2.5 * sigma)
axis(1, pos = 0, at = ticksat)
lines(c(myx[1],myx[length(myx)]),c(0,0))
t1 <- bquote(mu== .(mu))
centerX <- max(which (myx <= mu))
lines( c(mu, mu), c(0, myDensity[centerX]), lty= 14, lwd=.2)
text(mu, 0.4 * max(myDensity), labels = bquote( mu == .(mu.rounded)), pos = 2)
ss = 0.2 * max(myDensity)
arrows( x0=mu, y0= ss, x1=mu+sigma, y1=ss, code=3, angle=90, length=0.1)
t2 <- bquote( sigma== .(round(sigma,2)))
text( mu+0.5*sigma, 1.15*ss, t2)
normalFormula <- expression (f(x) == frac (1, sigma* sqrt(2*pi)) * ~~ e^{~-~frac(1,2)~bgroup("(", frac(x-mu,sigma),")")^2})
text ( mu + 0.5*sigma, max(myDensity)- 0.10 * max(myDensity), normalFormula, pos=4)
criticalValue <- mu -1.96 * sigma
specialX <- myx[myx <= criticalValue]
text ( criticalValue, 0 , label= paste(round(criticalValue,2)), pos=1, cex = .7)
specialY <- myDensity[myx < criticalValue]
polygon(c(specialX[1], specialX, specialX[length(specialX )]), c(0, specialY, 0), density=c(-110),col="lightgray" )
shadedArea <- round(pnorm(mu - 1.96 * sigma, mean=mu, sd=sigma), 4)
criticalValue.rounded <- round(criticalValue, 3)
al1 <- bquote(atop(Prob(x <= .(criticalValue.rounded)),
F(.(criticalValue.rounded)) == .(shadedArea)))
medX <- median(specialX)
indexMed <- max(which(specialX < medX))
medY <- specialY[indexMed]
denMax <- max(specialY)
text(medX, denMax, labels=al1, pos = 3, cex = 0.7)
indexMed <- max(which(specialX < medX))
x1 <- medX + .1 *abs(max(specialX) - min(specialX))
y1 <- 1.2 * myDensity[max(which(specialX < x1))]
arrows(x0=medX, y0=denMax, x1= x1, y1 = y1, length=0.1)
ss <- 0.1 * max(myDensity)
arrows( x0=mu, y0= ss, x1=mu-1.96*sigma, y1=ss, code=3, angle=90, length=0.1)
text( mu - 2.0*sigma, 1.15*ss, bquote(paste(.(criticalValue.rounded)==mu-1.96 * sigma,sep="")),pos=4 )
criticalValue <- mu +1.96 * sigma
criticalValue.rounded <- round(criticalValue, 3)
specialX <- myx[myx >= criticalValue]
text ( criticalValue, 0 , label= paste(criticalValue.rounded), pos=1, cex = 0.7)
specialY <- myDensity[myx >= criticalValue]
polygon(c(specialX[1], specialX, specialX[length(specialX )]), c(0, specialY, 0), density=c(-110), col="lightgray" )
shadedArea <- round(pnorm(mu + 1.96 * sigma, mean=mu, sd=sigma, lower.tail=F),4)
al2 <- bquote(atop(1 - F( .(criticalValue.rounded)),
phantom(0) == .(shadedArea)))
medX <- median(specialX)
denMax <- max(specialY)
text(medX, denMax, labels=al2, pos = 3, cex = 0.7)
x1 <- medX - .1 *abs(max(specialX) - min(specialX))
y1 <- 1.2 * specialY[max(which(specialX < x1))]
arrows( x0=medX, y0=denMax, x1= x1, y1 = y1, length=0.1)
ss <- 0.05 * max(myDensity)
arrows( x0=mu, y0= ss, x1=mu+1.96*sigma, y1=ss, code=3, angle=90, length=0.1)
text( mu + 1.96*sigma,1.15*ss, bquote(paste(.(criticalValue.rounded)==mu+1.96 * sigma,sep="")), pos=2 )
} |
coef.CauseSpecificCox <- function(object, ...){
return(lapply(object$models,coef))
} |
estSimpson <-
function (x)
{
n <- sum(x)
estp <- x/n
Simp <- Simpson(estp) * n/(n - 1)
return(Simp)
} |
discrete_entropy <- function(probs, base = 2, method = c("MLE"),
threshold = 0,
prior.probs = NULL,
prior.weight = 0) {
stopifnot(!any(is.na(probs)),
prior.weight >= 0,
prior.weight <= 1)
if (!all(round(probs, 6) >= 0)) {
stop("Not all probabilities are non-negative.")
}
stopifnot(sum(abs(sum(probs) - 1)) < 1e-6)
method <- match.arg(method)
if (threshold > 0) {
probs[probs < threshold] <- 0
probs <- probs / sum(probs)
}
if (is.null(prior.probs)) {
prior.probs <- rep(1 / length(probs), length = length(probs))
}
stopifnot(length(prior.probs) == length(probs),
all(round(prior.probs, 6) >= 0),
all.equal(target = 1., current = sum(prior.probs), tolerance=1e-5))
if (prior.weight > 0) {
probs <- (1 - prior.weight) * probs + prior.weight * prior.probs
}
if (any(probs == 0)) {
probs <- probs[abs(probs) > 1e-9]
}
stopifnot(all.equal(target = 1., current = sum(probs), tolerance = 1e-5))
switch(method,
MLE = {
entropy.eval <- -sum(probs * log(probs, base = base))
})
attr(entropy.eval, "base") <- as.character(base)
return(entropy.eval)
} |
seqmds.stress <- function(seqdist,mds) {
datadist <- as.dist(seqdist)
res <- numeric(length=ncol(mds$points))
for(i in 1:ncol(mds$points)) {
fitteddist <- dist(mds$points[,1:i],diag=TRUE,upper=TRUE)
res[i] <- sqrt(sum((datadist-fitteddist)^2)/sum(datadist^2))
}
return(res)
} |
cindexes.W <- function(lp, stime, status, groupe, ties, cindex, tau) {
cindexg <- cpeg <- Npairsg <- comparableg <- unusableg <- concordanteg <- discordanteg <- tiedcompg <- tiedtotg <- tiedtimeg <- uno.cindexg <- rep(0,length(unique(groupe)))
if(tau==0) tau=max(stime[status==1])
cens <- kmcens(stime, status, tau)
GXi <- cens$surv[match(stime, cens$distinct, nomatch = 1)]
Wipop <- 1/GXi/GXi * status * as.numeric(stime < tau)
for(g in sort(unique(groupe)) ) {
indiceg <- which(sort(unique(groupe))==g)
cindexesg <- cindexes(lp[groupe==g], stime[groupe==g], status[groupe==g], ties, tau, Wipop[groupe==g], cindex)
Npairsg[indiceg] <- cindexesg$Npairs
cpeg[indiceg] <- cindexesg$CPE
tiedtotg[indiceg] <- cindexesg$tiedtot
uno.cindexg[indiceg] <- cindexesg$c.uno
if(cindex==1){
cindexg[indiceg] <- cindexesg$cindex
comparableg[indiceg] <- cindexesg$comparable
concordanteg[indiceg] <- cindexesg$concordante
discordanteg[indiceg] <- cindexesg$discordante
tiedcompg[indiceg] <- cindexesg$tiedcomp
tiedtimeg[indiceg] <- cindexesg$tiedtime
unusableg[indiceg] <- cindexesg$unusable
}
}
res.cpe <- mean(cpeg, na.rm=TRUE)
uno.cindex <- mean(uno.cindexg, na.rm=TRUE)
out <- list(Npairs=sum(Npairsg, na.rm=T),comparable=sum(comparableg, na.rm=T),tiedtot=sum(tiedtotg, na.rm=T),CPE=res.cpe, CPE.by.group=cpeg,c.uno=uno.cindex,c.uno.by.group=uno.cindexg)
if(cindex==1){
cindex_global <- mean(cindexg, na.rm=TRUE)
out <- c(out,concordante=sum(concordanteg, na.rm=T),discordante=sum(discordanteg, na.rm=T),tiedcomp=sum(tiedcompg, na.rm=T),tiedtime=sum(tiedtimeg, na.rm=T),unusable=sum(unusableg, na.rm=T),cindex=cindex_global,cindex.by.group=cindexg)
}
return(out)
}
|
d.z.mean <- function (mu, m1, sig, sd1, n, a = .05) {
if (missing(m1)){
stop("Be sure to include m1 for the sample mean.")
}
if (missing(mu)){
stop("Be sure to include mu for the population mean.")
}
if (missing(sig)){
stop("Be sure to include sig for the population standard deviation.")
}
if (missing(sd1)){
stop("Be sure to include sd1 for the sample standard deviation")
}
if (missing(n)){
stop("Be sure to include the sample size n for the sample.")
}
if (a < 0 || a > 1) {
stop("Alpha should be between 0 and 1.")
}
d <- (m1 - mu) / sig
se1 <- sig / sqrt(n)
se2 <- sd1 / sqrt(n)
dlow <- d-qnorm(a/2, lower.tail = F)*sig
dhigh <- d+qnorm(a/2, lower.tail = F)*sig
z <- (m1 - mu) / se1
p <- pnorm(abs(z), lower.tail = FALSE)*2
M1low <- m1 - se2 * qnorm(a/2, lower.tail = FALSE)
M1high <- m1 + se2 * qnorm(a/2, lower.tail = FALSE)
if (p < .001) {reportp = "< .001"} else {reportp = paste("= ", apa(p,3,F), sep = "")}
output = list("d" = d,
"dlow" = dlow,
"dhigh" = dhigh,
"M1" = m1,
"sd1" = sd1,
"se1" = se2,
"M1low" = M1low,
"M1high" = M1high,
"Mu" = mu,
"Sigma" = sig,
"se2" = se1,
"z" = z,
"p" = p,
"n" = n,
"estimate" = paste("$d$ = ", apa(d,2,T), ", ", (1-a)*100, "\\% CI [",
apa(dlow,2,T), ", ", apa(dhigh,2,T), "]", sep = ""),
"statistic" = paste("$Z$", " = ", apa(z,2,T), ", $p$ ",
reportp, sep = "")
)
return(output)
} |
tidy_lognormal <- function(.n = 50, .meanlog = 0, .sdlog = 1, .num_sims = 1){
n <- as.integer(.n)
num_sims <- as.integer(.num_sims)
meanlog <- as.numeric(.meanlog)
sdlog <- as.numeric(.sdlog)
if(!is.integer(n) | n < 0){
rlang::abort(
"The parameters '.n' must be of class integer. Please pass a whole
number like 50 or 100. It must be greater than 0."
)
}
if(!is.integer(num_sims) | num_sims < 0){
rlang::abort(
"The parameter `.num_sims' must be of class integer. Please pass a
whole number like 50 or 100. It must be greater than 0."
)
}
if(!is.numeric(meanlog) | !is.numeric(sdlog)){
rlang::abort(
"The parameter of rate must be of class numeric and greater than 0."
)
}
if(sdlog < 0){
rlang::abort("The parameter of .sdlog must be greater than or equal to 0.")
}
x <- seq(1, num_sims, 1)
ps <- seq(-n, n-1, 2)
qs <- seq(0, 1, (1/(n-1)))
df <- dplyr::tibble(sim_number = as.factor(x)) %>%
dplyr::group_by(sim_number) %>%
dplyr::mutate(x = list(1:n)) %>%
dplyr::mutate(y = list(stats::rlnorm(n = n, meanlog = meanlog, sdlog = sdlog))) %>%
dplyr::mutate(d = list(density(unlist(y), n = n)[c("x","y")] %>%
purrr::set_names("dx","dy") %>%
dplyr::as_tibble())) %>%
dplyr::mutate(p = list(stats::plnorm(ps, meanlog = meanlog, sdlog = sdlog))) %>%
dplyr::mutate(q = list(stats::qlnorm(qs, meanlog = meanlog, sdlog = sdlog))) %>%
tidyr::unnest(cols = c(x, y, d, p, q)) %>%
dplyr::ungroup()
attr(df, ".meanlog") <- .meanlog
attr(df, ".sdlog") <- .sdlog
attr(df, ".n") <- .n
attr(df, ".num_sims") <- .num_sims
attr(df, "tibble_type") <- "tidy_lognormal"
attr(df, "ps") <- ps
attr(df, "qs") <- qs
return(df)
} |
aalenBaseC <- function(times, fdata, designX, status, id, clusters, robust = 0,
sim = 0, retur = 0, antsim = 1000, weighted.test = 1, covariance = 0,
resample.iid = 0, namesX = NULL, silent = 0, scale = 1)
{
Ntimes <- length(times)
designX <- as.matrix(designX)
if (is.matrix(designX) == TRUE)
p <- as.integer(dim(designX)[2])
if (is.matrix(designX) == TRUE)
nx <- as.integer(dim(designX)[1])
if (robust == 0 & sim >= 1)
robust <- 1
devi <- rep(0, 1)
cumint <- matrix(0, Ntimes, p + 1)
Vcumint <- cumint
if (retur == 1)
cumAi <- matrix(0, Ntimes, fdata$antpers)
else cumAi <- 0
test <- matrix(0, antsim, 3 * p)
testOBS <- rep(0, 3 * p)
testval <- c()
unifCI <- c()
rani <- -round(runif(1) * 10000)
if (sim >= 1)
simUt <- matrix(0, Ntimes, 50 * p)
else simUt <- NULL
Ut <- matrix(0, Ntimes, p + 1)
if (covariance == 1)
covs <- matrix(0, Ntimes, p * p)
else covs <- 0
if (resample.iid == 1) {
B.iid <- matrix(0, Ntimes, fdata$antclust * p)
}
else B.iid <- NULL
if (robust == 2) {
aalenout <- .C("aalen", as.double(times), as.integer(Ntimes),
as.double(designX), as.integer(nx), as.integer(p),
as.integer(fdata$antpers), as.double(fdata$start),
as.double(fdata$stop), as.double(cumint), as.double(Vcumint),
as.integer(status), PACKAGE = "timereg")
robV <- NULL
cumAI <- NULL
test <- NULL
}
else {
robVar <- Vcumint
aalenout <- .C("robaalenC", as.double(times), as.integer(Ntimes),
as.double(designX), as.integer(nx), as.integer(p),
as.integer(fdata$antpers), as.double(fdata$start),
as.double(fdata$stop), as.double(cumint), as.double(Vcumint),
as.double(robVar), as.integer(sim), as.integer(antsim),
as.integer(retur), as.double(cumAi), as.double(test),
as.integer(rani), as.double(testOBS), as.integer(status),
as.double(Ut), as.double(simUt), as.integer(id),
as.integer(weighted.test), as.integer(robust), as.integer(covariance),
as.double(covs), as.integer(resample.iid), as.double(B.iid),
as.integer(clusters), as.integer(fdata$antclust),
as.double(devi), as.integer(silent), PACKAGE = "timereg")
if (covariance == 1) {
covit <- matrix(aalenout[[26]], Ntimes, p * p)
cov.list <- list()
for (i in 1:Ntimes) cov.list[[i]] <- matrix(covit[i,
], p, p)
}
else cov.list <- NULL
if (resample.iid == 1) {
covit <- matrix(aalenout[[28]], Ntimes, fdata$antclust *
p)
B.iid <- list()
for (i in (0:(fdata$antclust - 1)) * p) {
B.iid[[i/p + 1]] <- as.matrix(covit[, i + (1:p)])
colnames(B.iid[[i/p + 1]]) <- namesX
}
}
robV <- matrix(aalenout[[11]], Ntimes, p + 1)
if (retur == 1) {
cumAi <- matrix(aalenout[[15]], Ntimes, fdata$antpers *
1)
cumAi <- list(time = times, dM = cumAi, dM.iid = cumAi)
}
else cumAi <- NULL
}
if (sim >= 1) {
Uit <- matrix(aalenout[[21]], Ntimes, 50 * p)
UIt <- list()
for (i in (0:49) * p) UIt[[i/p + 1]] <- as.matrix(Uit[,
i + (1:p)])
Ut <- matrix(aalenout[[20]], Ntimes, (p + 1))
test <- matrix(aalenout[[16]], antsim, 3 * p)
testOBS <- aalenout[[18]]
for (i in 1:(3 * p)) testval <- c(testval, pval(test[,
i], testOBS[i]))
for (i in 1:p) unifCI <- as.vector(c(unifCI, percen(test[,
i], 0.95)))
pval.testBeq0 <- as.vector(testval[1:p])
pval.testBeqC <- as.vector(testval[(p + 1):(2 * p)])
pval.testBeqC.is <- as.vector(testval[(2 * p + 1):(3 *
p)])
obs.testBeq0 <- as.vector(testOBS[1:p])
obs.testBeqC <- as.vector(testOBS[(p + 1):(2 * p)])
obs.testBeqC.is <- as.vector(testOBS[(2 * p + 1):(3 *
p)])
sim.testBeq0 <- as.matrix(test[, 1:p])
sim.testBeqC <- as.matrix(test[, (p + 1):(2 * p)])
sim.testBeqC.is <- as.matrix(test[, (2 * p + 1):(3 *
p)])
}
else {
test <- NULL
unifCI <- NULL
Ut <- NULL
UIt <- NULL
pval.testBeq0 <- NULL
pval.testBeqC <- NULL
obs.testBeq0 <- NULL
obs.testBeqC <- NULL
sim.testBeq0 <- NULL
sim.testBeqC <- NULL
sim.testBeqC.is <- NULL
pval.testBeqC.is <- NULL
obs.testBeqC.is <- NULL
}
cumint <- matrix(aalenout[[9]], Ntimes, p + 1)
Vcumint <- matrix(aalenout[[10]], Ntimes, p + 1)
devi <- aalenout[[31]]
list(cum = cumint, var.cum = Vcumint, robvar.cum = robV,
residuals = cumAi, pval.testBeq0 = pval.testBeq0, obs.testBeq0 = obs.testBeq0,
pval.testBeqC = pval.testBeqC, pval.testBeqC.is = pval.testBeqC.is,
obs.testBeqC = obs.testBeqC, obs.testBeqC.is = obs.testBeqC.is,
sim.testBeq0 = sim.testBeq0, sim.testBeqC = sim.testBeqC,
sim.testBeqC.is = sim.testBeqC.is, conf.band = unifCI,
test.procBeqC = Ut, sim.test.procBeqC = UIt, covariance = cov.list,
B.iid = B.iid, deviance = devi)
} |
library('mfx')
set.seed(12345)
n = 1000
x = rnorm(n)
y = rbeta(n, shape1 = plogis(1 + 0.5 * x), shape2 = (abs(0.2*x)))
y = (y*(n-1)+0.5)/n
data = data.frame(y,x)
betaor(y~x|x, data=data) |
pooled.colVars <- function (x, ina, std = FALSE) {
m <- rowsum(x, ina)
m2 <- rowsum(x^2, ina)
ni <- tabulate(ina)
ni <- ni[ni > 0]
s <- (m2 - m^2/ni)
s <- Rfast::colsums(s) / (sum(ni) - length(ni) )
if (std) s <- sqrt(s)
s
} |
Btensorfn <- function(XbasisList, modelList) {
rng <- XbasisList[[1]]$rangeval
Wbasism <- create.constant.basis(rng)
Wfdm <- fd(1,Wbasism)
WfdParm <- fdPar(Wfdm, 0, 0, FALSE)
nvar <- length(modelList)
BtensorList <- vector("list", nvar)
for (ivar in 1:nvar) {
modelListi <- modelList[[ivar]]
if (!is.null(modelListi$XList)) {
nderiv <- modelListi$nallXterm + 1
BtensorListi <- vector("list",nderiv)
for (jx in 1:nderiv) {
BtensorListi[[jx]] <- vector("list",nderiv)
}
BtensorList[[ivar]] <- BtensorListi
for (iw in 1:nderiv) {
if (iw < nderiv) {
modelListiw <- modelListi$XList[[iw]]
WfdParw <- modelListiw$fun
Xbasisw <- XbasisList[[modelListiw$variable]]
jw <- modelListiw$derivative
} else {
WfdParw <- WfdParm
Xbasisw <- XbasisList[[ivar]]
jw <- modelListi$order
}
if (is.fdPar(WfdParw) || is.fd(WfdParw) || is.basis(WfdParw)) {
if (is.basis(WfdParw)) {
Wbasisw <- WfdParw
} else {
if (is.fd(WfdParw)) {
Wbasisw <- WfdParw$basis
} else {
Wbasisw <- WfdParw$fd$basis
}
}
Wtypew <- Wbasisw$type
Xtypew <- Xbasisw$type
nXbasisw <- Xbasisw$nbasis
for (ix in 1:nderiv) {
if (ix < nderiv) {
modelListix <- modelListi$XList[[ix]]
WfdParx <- modelListix$fun
Xbasisx <- XbasisList[[modelListix$variable]]
jx <- modelListix$derivative
} else {
WfdParx <- WfdParm
Xbasisx <- XbasisList[[ivar]]
jx <- modelListi$order
}
if (is.fdPar(WfdParx) || is.fd(WfdParx) || is.basis(WfdParx)) {
if (is.basis(WfdParx)) {
Wbasisx <- WfdParx
} else {
if (is.fd(WfdParx)) {
Wbasisx <- WfdParx$basis
} else {
Wbasisx <- WfdParx$fd$basis
}
}
Wtypex <- Wbasisx$type
Xtypex <- Xbasisx$type
nXbasisx <- Xbasisx$nbasis
if (Wtypew == "const" && Wtypex == "const" &&
Xtypew == "bspline" && Xtypex == "bspline" ) {
XWXWmatij <- inprod(Xbasisw, Xbasisx, jw, jx)
XWXWmatij <- matrix(t(XWXWmatij), nXbasisw*nXbasisx, 1)
} else {
XWXWmatij <- inprod.TPbasis(Xbasisw, Wbasisw, Xbasisx, Wbasisx,
jw, 0, jx, 0)
}
BtensorList[[ivar]][[iw]][[ix]] <- t(XWXWmatij)
}
}
}
}
} else {
BtensorList[[ivar]] <- 0
}
}
return(BtensorList)
} |
fi <- function(EVboot, EVdata, rank) {
fni <- numeric(rank)
for (ii in 1:rank) {
fni[ii] <- det(crossprod(EVdata[, 1:ii], EVboot[, 1:ii]))
}
1 - abs(fni)
}
MAmuse <- function(X, k) {
n <- nrow(X)
prep <- BSSprep(X)
Y <- prep$Y
M <- crossprod(Y[1:(n - k), ], Y[(k + 1):n, ])/(n - k)
M.sym <- (M + t(M))/2
crossprod(M.sym)
}
AMUSEbootLADLE <- function(X, EVdata, tau, rank) {
Mboot <- MAmuse(X, k = tau)
EVboot <- .Call("EIGEN", Mboot, PACKAGE = "tsBSS")$vectors
fi(EVboot, EVdata, rank)
}
MSobi <- function(X, k_set) {
n <- nrow(X)
p <- ncol(X)
prep <- BSSprep(X)
Y <- prep$Y
M_array <- array(0, dim = c(p, p, length(k_set)))
for (t in 1:length(k_set)) {
M_array[ , , t] <- crossprod(Y[1:(n - k_set[t]), ], Y[(k_set[t] + 1):n, ])/(n - k_set[t])
M_array[ , , t] <- (M_array[ , , t] + t(M_array[, , t]))/2
}
M_array
}
SOBIbootLADLE <- function(X, EVdata, tau, rank, maxiter, eps) {
Mboot <- MSobi(X, k_set = tau)
frjdboot <- JADE::frjd.int(Mboot, maxiter = maxiter, eps = eps)
Dfrjd <- diag(apply(frjdboot$D^2, 1:2, sum))
EVboot <- frjdboot$V[ , order(Dfrjd, decreasing = TRUE)]
fi(EVboot, EVdata, rank)
} |
getCloseMatch <-
function(pixelArray, libraryDataFrame, nneig=20) {
libraryMatrix <- libraryDataFrame[2:length(libraryDataFrame)]
nnlist <- RANN::nn2(libraryMatrix, t(pixelArray), k=nneig)
idx <- nnlist$nn.idx[round(runif(1, min=1, max=nneig))]
return(as.character(libraryDataFrame[idx,1]))
} |
vcd::mosaic(~ victim + defendant + death,
shade = TRUE,
data = DeathPenalty %>%
mutate(
victim = abbreviate(victim, 2),
defendant = abbreviate(defendant, 2),
death = abbreviate(death, 1))
) |
hack_sig <- function(expr_data, signatures = "all", method = "original",
direction = "none", sample_norm = "raw", rank_norm = "none",
alpha = 0.25) {
compute_ss_method <- function(sigs, ss_method) {
switch (ss_method,
original = ,
ssgsea = compute_ssgsea(expr_data, sigs,
sample_norm = sample_norm, rank_norm = rank_norm,
alpha = alpha),
zscore = compute_zscore(expr_data, sigs),
singscore = compute_singscore(expr_data, sigs, direction = direction),
stop("Valid choices for 'method' are 'original', 'zscore', 'ssgsea', 'singscore'",
call. = FALSE)
)
}
if (is.matrix(expr_data) == TRUE) {
expr_data <- as.data.frame(expr_data)
}
if (is.list(signatures)) {
signatures <- lapply(signatures, FUN = unique)
signatures <- signatures[lapply(signatures, length) > 1]
if (is.null(names(signatures)) == TRUE) {
names(signatures) <- paste0("sig", seq_along(signatures))
}
check_info <- check_sig(expr_data = expr_data, signatures = signatures)
check_info <- check_info[check_info$n_present == 0,]
if (nrow(check_info) > 0) {
signatures <- signatures[!names(signatures) %in% check_info$signature_id]
rlang::warn(
rlang::format_error_bullets(
c("i" = "No genes are present in 'expr_data' for the following signatures:",
stats::setNames(check_info$signature_id, rep_len("x", nrow(check_info))))
)
)
}
compute_ss_method(signatures, method)
}
else if (is.character(signatures)) {
sig_data <- signatures_data
signatures <- paste0(signatures, collapse = "|")
if (signatures != "all") {
sig_data <- sig_data[grep(signatures, sig_data$signature_keywords,
ignore.case = TRUE), ]
if (nrow(sig_data) == 0) {
stop("Provided keyword in 'signatures' does not match any class of signature.",
call. = FALSE)
}
}
check_info <- check_sig(expr_data = expr_data, signatures = signatures)
check_info <- check_info[check_info$n_present == 0, ]
if (nrow(check_info) > 0) {
sig_data <- sig_data[!sig_data$signature_id %in% check_info$signature_id, ]
rlang::warn(
rlang::format_error_bullets(
c("i" = "No genes are present in 'expr_data' for the following signatures:",
stats::setNames(check_info$signature_id, rep_len("x", nrow(check_info))))
)
)
}
sig_list <- lapply(split(sig_data[, c("signature_id", "gene_symbol")],
sig_data$signature_id),
FUN = `[[`, 2)
sig_list <- sig_list[lapply(sig_list, length) > 1]
if (method != "original") {
compute_ss_method(sig_list, method)
} else {
rlang::inform(
rlang::format_error_bullets(
c("i" = "To obtain CINSARC, ESTIMATE and Immunophenoscore with the original procedures, see:",
c("?hack_cinsarc", "?hack_estimate", "?hack_immunophenoscore"))
)
)
sig_data <- sig_data[!grepl("cinsarc|estimate|ips", sig_data$signature_keywords), ]
sig_list <- sig_list[!grepl("cinsarc|estimate|ips", names(sig_list))]
method_list <- tibble::deframe(
sig_data[!duplicated(sig_data[, c("signature_id", "signature_method")]),
c("signature_id", "signature_method")]
)
method_list <- method_list[match(names(sig_list), names(method_list))]
method_list <- gsub("\\|.*", "", method_list)
weight_list <- lapply(split(sig_data[, c("signature_id", "gene_weight")],
sig_data$signature_id),
FUN = `[[`, 2)
result <- vector("list", length = length(sig_list))
for (i in names(method_list)) {
if (grepl("weighted_sum", method_list[[i]])) {
expr_mat <- expr_data
if (method_list[[i]] == "weighted_sum_rank") {
expr_mat <- apply(expr_mat[sig_list[[i]], ], MARGIN = 2,
FUN = rank, na.last = "keep")
expr_mat <- as.data.frame(expr_mat)
}
temp <- tibble::enframe(
colSums(expr_mat[sig_list[[i]], ] * weight_list[[i]],
na.rm = TRUE),
name = "sample_id",
value = "sig_score"
)
temp$signature_id <- i
} else if (grepl("mean", method_list[[i]])) {
temp <- tibble::enframe(
colMeans(expr_data[sig_list[[i]], ], na.rm = TRUE),
name = "sample_id",
value = "sig_score"
)
temp$signature_id <- i
} else if (grepl("median", method_list[[i]])) {
temp <- tibble::enframe(
apply(expr_data[sig_list[[i]], ], MARGIN = 2,
FUN = stats::median, na.rm = TRUE),
name = "sample_id",
value = "sig_score"
)
temp$signature_id <- i
} else {
temp <- compute_ssgsea(expr_data, sig_list[i],
sample_norm = sample_norm, rank_norm = rank_norm,
alpha = alpha)
temp$sig_score <- temp[, i, drop = TRUE]
temp[, i] <- NULL
temp$signature_id <- i
}
result[[i]] <- temp
}
result <- dplyr::bind_rows(result)
tidyr::pivot_wider(result,
id_cols = "sample_id",
names_from = "signature_id",
values_from = "sig_score")
}
} else stop("Argument 'signatures' must be a named list of gene signatures or a string with a keyword.",
call. = FALSE)
} |
weightsMMD <-
function(data,Y,X1,X2,subject,death,time,interval.death=0,name="weight")
{
if(missing(data)) stop("Please specify the dataset in argument data")
if(missing(Y)) stop("Please specify the outcome in argument Y")
if(missing(subject)) stop("Please specify the group variable in argument subject")
if(missing(death)) stop("Please specify death time in argument death")
if(missing(time)) stop("Please specify time variable in argument time")
if(!is.data.frame(data)) stop("data should be a data frame")
if(!is.character(Y)) stop("Y should be a character")
if(!(Y %in% colnames(data))) stop("data should contain Y")
if(!is.null(X1))
{
if(!all(is.character(X1))) stop("X1 should only contain characters")
if(!all((X1 %in% colnames(data)))) stop("data should contain X1")
}
if(!is.null(X2))
{
if(!all(is.character(X2))) stop("X2 should only contain characters")
if(!all((X2 %in% colnames(data)))) stop("data should contain X2")
}
if(!is.character(subject)) stop("subject should be a character")
if(!(subject %in% colnames(data))) stop("data should contain subject")
if(!is.character(death)) stop("death should be a character")
if(!(death %in% colnames(data))) stop("data should contain death")
if(!is.character(time)) stop("time should be a character")
if(!(time %in% colnames(data))) stop("data should contain time")
if(!all(is.numeric(interval.death))) stop("interval.death should only contain numeric values")
if(!is.character(name)) stop("name should be a character")
data2 <- data[which(!is.na(data[,Y])),c(subject,time,X1,X2,Y,death)]
wide <- reshape(data2, v.names=Y, idvar=subject, timevar=time, direction = "wide")
y.t <- paste(Y,unique(data[,time]),sep=".")
nt <- length(y.t)
matobs <- matrix(-1,nrow(wide),nt)
colnames(matobs) <- paste("obs_t",1:nt,sep="")
for(j in 1:nt)
{
matobs[,j] <- ifelse(!is.na(wide[,y.t[j]]),1,ifelse((is.na(wide[,death])) | (wide[,death]>j),0,NA))
}
wide_avecobs <- data.frame(wide,matobs)
prob <- function(wide,Y,X1,X2,subject,death,suivi,delta)
{
matobs <- wide[,(ncol(wide)-nt+1):ncol(wide)]
sample <- vector("list",nt-1)
for(j in 2:nt)
{
if((j+delta)<=nt)
{
sample[[j-1]] <- subset(wide,!is.na(matobs[,j]) & !is.na(matobs[,j+delta]))
}
}
reponse.var <- paste("obs_t",1:nt,sep="")
nmes <- rep(NA,nt-1)
poole <- NULL
for(j in 1:(nt-1-delta))
{
dat <- sample[[j]][,c(subject,reponse.var[j+1],X1,X2,y.t[j])]
dat$suivi <- j+1
nmes[j] <- nrow(dat)
colnames(dat) <- c(subject,"R",X1,X2,"Yavt","suivi")
poole <- rbind(poole,dat)
}
colnames(poole) <- c(subject,"R",X1,X2,"Yavt","suivi")
poole <- poole[which(!is.na(poole$Yavt)),]
if(delta==0)
{
covar1 <- c(X1,X2)
form1 <- formula(paste("R~-1+factor(suivi)+",paste(covar1,collapse="+")))
reg1 <- glm(form1,family="binomial",data=poole)
if(reg1$converged==TRUE)
{
coefnum <- reg1$coefficients
senum <- sqrt(diag(vcov(reg1)))
}
else
{
coefnum <- NA
senum <- NA
}
}
form2 <- "R~-1+factor(suivi)"
if(length(X1))
{
form2 <- paste(form2,"+(",paste(X1,collapse="+"),")*Yavt",sep="")
}
if(length(X2))
{
form2 <- paste(form2,"+",paste(X2,collapse="+"),sep="")
}
reg2 <- glm(form2,family="binomial",data=poole)
if(reg2$converged==TRUE)
{
coefden <- reg2$coefficients
seden <- sqrt(diag(vcov(reg2)))
}
else
{
coefden <- NA
seden <- NA
}
dtmp <- poole[,c(subject,"R",X1,X2,"Yavt","suivi")]
dpred <- dtmp[order(dtmp$suivi,dtmp[,subject]),]
pred <- predict(reg2,newdata=dpred)
d_avecpred <- data.frame(dpred,pden=1/(1+exp(-pred)))
if(delta==0)
{
d_avecpred <- d_avecpred[order(d_avecpred[,subject],d_avecpred[,"suivi"]),]
pred <- predict(reg1,newdata=d_avecpred)
d_avecpred$pnum <- 1/(1+exp(-pred))
d_avecpred$pnum <- unlist(tapply(d_avecpred$pnum,d_avecpred[,subject],cumprod))
}
colnames(d_avecpred)[which(colnames(d_avecpred)=="pden")] <- paste("pden",delta,sep="")
if(delta==0)
{
res <- list(d_avecpred,coefden,seden,coefnum,senum)
}
else
{
res <- list(d_avecpred,coefden,seden)
}
return(res)
}
for(delta in interval.death)
{
res <- prob(wide=wide_avecobs,Y=Y,X1=X1,
X2=X2,subject=subject,death=death,
suivi=time,delta=delta)
if(delta==0)
{
data3 <- merge(data2,res[[1]][,c(subject,"suivi","Yavt","pnum","pden0")],by.x=c(subject,time),by.y=c(subject,"suivi"),all.x=TRUE)
coef <- list(res[[4]],res[[2]])
se <- list(res[[5]],res[[3]])
}
else
{
data3 <- merge(data3,res[[1]][,c(subject,"suivi",paste("pden",delta,sep=""))],by.x=c(subject,time),by.y=c(subject,"suivi"),all.x=TRUE)
coef <- c(coef,list(res[[2]]))
se <- c(se,list(res[[3]]))
}
}
data3 <- data3[order(data3[,subject],data3[,time]),]
data3[which(data3[,time]==1),paste("pden",interval.death,sep="")] <- 1
for(l in 1:nrow(data3))
{
if(data3[l,time]==1)
{
data3$pden[l] <- 1
data3$pnum[l] <- 1
}
else
{
j <- data3[l,time]
kk <- cut(0:(j-2),breaks=c(interval.death,nt+1),labels=interval.death,right=FALSE)
kk <- as.numeric(as.character(kk))
ll <- l-0:(j-2)
p <- apply(cbind(ll,kk),1,function(x,d) d[x[1],paste("pden",x[2],sep="")],d=data3)
data3$pden[l] <- prod(p)
}
}
data3$poids <- data3$pnum/data3$pden
ajout <- data3[,c(subject,time,"poids")]
colnames(ajout) <- c(subject,time,name)
data_poids <- merge(data,ajout,all.x=TRUE,sort=FALSE)
return(list(data=data_poids,coef=coef,se=se))
} |
modcall <- function(call, newcall, newargs, keepargs, dropargs) {
if (hasArg(keepargs)) {
call_arg <- match(keepargs, names(call), 0)
call <- call[c(1, call_arg)]
}
lcall <- as.list(call)
if (hasArg(newcall)) {
lcall[[1]] <- substitute(newcall)
}
if (hasArg(dropargs)) {
for (i in dropargs) {
lcall[[i]] <- NULL
}
}
if (hasArg(newargs)) {
lcall <- c(lcall, newargs)
}
return(as.call(lcall))
} |
order_probs <- function(draw_size, k, n) {
return(rbeta(draw_size, k, n + 1 - k))
}
order_rnorm <- function (draw_size = 1, mean = 0, sd = 1, k = 1, n =1) {
orders <- order_probs(draw_size, k, n)
return(qnorm(orders, mean, sd))
}
order_rchisq <- function (draw_size, df, k, n) {
orders <- order_probs(draw_size, k, n)
return(qchisq(orders, df))
}
order_rcauchy <- function (draw_size = 1, location = 0, scale = 1, k = 1, n = 1) {
orders <- order_probs(draw_size, k, n)
return(qcauchy(orders, location, scale))
}
order_rlogis <- function (draw_size, location, scale, k, n) {
orders <- order_probs(draw_size, k, n)
return(qlogis(orders, location = location, scale = scale))
}
order_rgamma <- function (draw_size, shape, scale, k, n) {
orders <- order_probs(draw_size, k, n)
return(qgamma(orders, shape = shape, scale = scale))
}
order_rexp <- function (draw_size, rate, k, n) {
orders <- order_probs(draw_size, k, n)
return(qexp(orders, rate = rate))
} |
set.seed(888)
type = c(rep("Tumor", 10), rep("Control", 10))
gender = sample(c("F", "M"), 20, replace = TRUE)
gender[sample(1:20, 2)] = NA
age = runif(20, min = 30, max = 80)
mutation = data.frame(mut1 = sample(c(TRUE, FALSE), 20, p = c(0.2, 0.8), replace = TRUE),
mut2 = sample(c(TRUE, FALSE), 20, p = c(0.3, 0.7), replace = TRUE))
anno = data.frame(type = type, gender = gender, age = age, mutation, stringsAsFactors = FALSE)
anno_col = list(type = c("Tumor" = "red", "Control" = "blue"),
gender = c("F" = "pink", "M" = "darkgreen"),
mutation = c("TRUE" = "black", "FALSE" = "
rand_meth = function(k, mean) {
(runif(k) - 0.5)*min(c(1-mean), mean) + mean
}
mean_meth = c(rand_meth(300, 0.3), rand_meth(700, 0.7))
mat_meth = as.data.frame(lapply(mean_meth, function(m) {
if(m < 0.3) {
c(rand_meth(10, m), rand_meth(10, m + 0.2))
} else if(m > 0.7) {
c(rand_meth(10, m), rand_meth(10, m - 0.2))
} else {
c(rand_meth(10, m), rand_meth(10, m + sample(c(1, -1), 1)*0.2))
}
}))
mat_meth = t(mat_meth)
rownames(mat_meth) = NULL
colnames(mat_meth) = paste0("sample", 1:20)
direction = rowMeans(mat_meth[, 1:10]) - rowMeans(mat_meth[, 11:20])
direction = ifelse(direction > 0, "hyper", "hypo")
library(circlize)
mat_expr = t(apply(mat_meth, 1, function(x) {
x = x + rnorm(length(x), sd = abs(runif(1)-0.5)*0.4 + 0.1)
-scale(x)
}))
dimnames(mat_expr) = dimnames(mat_meth)
cor_pvalue = sapply(seq_len(nrow(mat_meth)), function(i) {
cor.test(mat_meth[i, ], mat_expr[i, ])$p.value
})
gene_type = sample(c("protein_coding", "lincRNA", "microRNA", "psedo-gene", "others"),
nrow(mat_meth), replace = TRUE, prob = c(6, 1, 1, 1, 1))
anno_gene = sapply(mean_meth, function(m) {
if(m > 0.6) {
if(runif(1) < 0.8) return("intragenic")
}
if(m < 0.4) {
if(runif(1) < 0.4) return("TSS")
}
return("intergenic")
})
anno_gene_col = c("intragenic" = "blue", "TSS" = "red", "intergenic" = "grey")
tss_dist = sapply(mean_meth, function(m) {
if(m < 0.3) {
if(runif(1) < 0.5) {
return(round( (runif(1) - 0.5)*1000 + 500))
} else {
return(round( (runif(1) - 0.5)*10000 + 500))
}
} else if(m < 0.6) {
if(runif(1) < 0.8) {
return(round( (runif(1)-0.5)*100000 + 50000 ))
} else {
return(round( (runif(1)-0.5)*1000000 + 500000 ))
}
}
return(round( (runif(1) - 0.5)*1000000 + 500000))
})
rand_tss = function(m) {
if(m < 0.4) {
if(runif(1) < 0.25) return(runif(1))
} else if (runif(1) < 0.1) {
return(runif(1))
}
return(0)
}
rand_enhancer = function(m) {
if(m < 0.4) {
if(runif(1) < 0.6) return(runif(1))
} else if (runif(1) < 0.1) {
return(runif(1))
}
return(0)
}
rand_repressive = function(m) {
if(m > 0.4) {
if(runif(1) < 0.8) return(runif(1))
}
return(0)
}
anno_states = data.frame(
tss = sapply(mean_meth, rand_tss),
enhancer = sapply(mean_meth, rand_enhancer),
repressive = sapply(mean_meth, rand_repressive))
save(mat_meth, mat_expr, anno, anno_col, anno_states, cor_pvalue, direction,
anno_gene, gene_type, tss_dist, file = "random_meth_expr_data.RData") |
ipums_view <- function(x, out_file = NULL, launch = TRUE) {
if (
!requireNamespace("htmltools", quietly = TRUE) ||
!requireNamespace("shiny", quietly = TRUE) ||
!requireNamespace("DT", quietly = TRUE)
) {
stop(custom_format_text(
"Please install htmltools, shiny, and DT using ",
"`install.packages(c('htmltools', 'shiny', 'DT')",
indent = 2, exdent = 2
))
}
if (is.null(out_file)) out_file <- paste0(tempfile(), ".html")
file_info <- ipums_file_info(x)
var_info <- ipums_var_info(x)
var_info <- dplyr::bind_rows(var_info, empty_var_info_df())
html_page <- shiny::basicPage(
htmltools::tags$h1("IPUMS Data Dictionary Viewer"),
file_info_html(file_info),
purrr::pmap(var_info, display_ipums_var_row, project = file_info$ipums_project)
)
html_page <- add_jquery_dependency(html_page)
htmltools::save_html(html_page, out_file)
if (launch) {
if (requireNamespace("rstudioapi", quietly = TRUE)) {
rstudioapi::viewer(out_file)
} else {
shell.exec(out_file)
}
invisible(out_file)
} else {
out_file
}
}
file_info_html <- function(file_info) {
if (is.null(file_info)) {
htmltools::tags$div(
htmltools::tags$h2("Extract Information"),
htmltools::tags$p("Not available")
)
} else {
htmltools::tags$div(
htmltools::tags$h2("Extract Information"),
htmltools::tags$p(htmltools::tags$b("Project: "), file_info$ipums_project),
htmltools::tags$p(htmltools::tags$b("Date Created: "), file_info$extract_date),
htmltools::tags$p(
htmltools::tags$b("Extract Notes: "),
convert_single_linebreak_to_brtags(file_info$extract_notes)
),
htmltools::tags$p(
htmltools::tags$b("Conditions / Citation"),
htmltools::tags$a(
"(Click to expand)",
`data-toggle` = "collapse",
`href` = "
`aria-expanded` = "false"
),
htmltools::tags$div(
split_double_linebreaks_to_ptags(file_info$conditions),
split_double_linebreaks_to_ptags(file_info$citation),
id = "collapseConditions",
class = "collapse"
)
),
htmltools::tags$h2("Variable Information"),
htmltools::tags$p("Click variable name for more details")
)
}
}
display_ipums_var_row <- function(var_name, var_label, var_desc, val_labels, code_instr, project, ...) {
if (is.na(var_label)) var_label <- "-"
if (is.na(var_desc)) var_desc <- "No variable description available..."
vd_html <- split_double_linebreaks_to_ptags(var_desc)
if (is.na(code_instr)) code_instr <- "N/A"
code_instr <- split_double_linebreaks_to_ptags(code_instr)
if (nrow(val_labels) > 0) {
value_labels <- DT::datatable(val_labels, style = "bootstrap", rownames = FALSE, width = "100%")
} else {
value_labels <- htmltools::tags$p("N/A")
}
url <- try(
ipums_website(var = var_name, project = project, launch = FALSE, verbose = FALSE, var_label = var_label),
silent = TRUE
)
if (class(url)[1] == "try-error") {
link <- NULL
} else {
link <- htmltools::a(href = url, "More details")
}
expandable_div(
var_name,
var_label,
shiny::fluidRow(
shiny::column(6, htmltools::tags$h3("Variable Description"), vd_html, link),
shiny::column(
6,
htmltools::tags$h3("Value Labels"),
htmltools::tags$h4("Coding Instructions"),
code_instr,
htmltools::tags$h4("Labelled Values"),
value_labels
)
)
)
}
expandable_div <- function(title, subtitle, content) {
htmltools::tags$div(
class = "panel panel-default",
htmltools::tags$div(
class = "panel-heading",
htmltools::tags$div(
class = "panel-title",
htmltools::tags$a(
class = "accordion-toggle",
`data-toggle` = "collapse",
`data-parent` = "
`aria-expanded` = "false",
href = paste0("
htmltools::tags$div(
htmltools::tags$i(class = "more-less glyphicon glyphicon-plus"),
htmltools::tags$h2(
title,
style = "display:inline-block; padding-right:0.5em"
),
htmltools::tags$h5(subtitle)
)
)
)
),
htmltools::tags$div(
id = title,
class = "panel-colapse collapse",
htmltools::tags$div(
class = "panel-body",
content
)
)
)
}
split_double_linebreaks_to_ptags <- function(x) {
if (is.null(x)) return("")
out <- fostr_split(x, "\n\n")[[1]]
purrr::map(out, htmltools::tags$p)
}
convert_single_linebreak_to_brtags <- function(x) {
if (is.null(x)) return(NULL)
split <- fostr_split(x, "\n")[[1]]
if (length(split) == 1) return(x)
out <- vector(mode = "list", length = (length(split) - 1) * 2 - 1)
for (iii in seq_along(split)){
out[[(iii - 1) * 2 + 1]] <- split[iii]
if (iii != length(split)) out[[(iii - 1) * 2 + 2]] <- htmltools::tags$br()
}
out
}
add_jquery_dependency <- function(page) {
jquery_dir <- c(
href = "shared/jquery",
file = system.file("htmlwidgets/lib/jquery/", package = "DT")
)
page <- htmltools::attachDependencies(
page,
htmltools::htmlDependency("jquery", "1.12.4", jquery_dir, script = "jquery.min.js"),
append = TRUE
)
htmltools::htmlDependencies(page) <- rev(htmltools::htmlDependencies(page))
page
}
empty_var_info_df <- function() {
tibble::tibble(
var_name = character(0),
var_label = character(0),
var_desc = character(0),
val_labels = list(),
code_instr = character(0)
)
} |
riingo_fundamentals_meta <- function(ticker) {
assert_x_inherits(ticker, "ticker", "character")
type <- "tiingo"
endpoint <- "fundamentals-meta"
ticker <- glue::glue_collapse(ticker, ",")
riingo_url <- construct_url(
type,
endpoint,
ticker = NULL,
tickers = ticker
)
cont_df <- content_downloader(riingo_url, ticker)
cont_tbl <- clean_json_df(cont_df, type, endpoint)
cont_tbl
} |
print.summary.learnIQ1main <-
function (x, ...){
cat ("Main Effect Term Regression: \n");
print (summary (x$s1Reg));
} |
summary.bin.bin <- function(object, ...){
cat("\nThe forecasts are binary, the observations are binary.\n")
cat("The contingency table for the forecast \n")
print(object$tab)
cat("\n")
cat(paste("PODy = ", formatC(object$POD, digits = 4), "\n"))
cat(paste("Std. Err. for POD = ", formatC(object$POD.se), "\n"))
cat(paste("TS = ", formatC(object$TS, digits = 4), "\n"))
cat(paste("Std. Err. for TS = ", formatC(object$TS.se), "\n"))
cat(paste("ETS = ", formatC(object$ETS, digits = 4), "\n"))
cat(paste("Std. Err. for ETS = ", formatC(object$ETS.se), "\n"))
cat(paste("FAR = ", formatC(object$FAR, digits = 4), "\n"))
cat(paste("Std. Err. for FAR = ", formatC(object$FAR.se), "\n"))
cat(paste("HSS = ", formatC(object$HSS, digits = 4), "\n"))
cat(paste("Std. Err. for HSS = ", formatC(object$HSS.se), "\n"))
cat(paste("PC = ", formatC(object$PC, digits = 4), "\n"))
cat(paste("Std. Err. for PC = ", formatC(object$PC.se), "\n"))
cat(paste("BIAS = ", formatC(object$BIAS, digits = 4), "\n"))
cat(paste("Odds Ratio = ", formatC(object$theta, digits = 4), "\n"))
cat(paste("Log Odds Ratio = ", formatC(object$log.theta, digits = 4), "\n"))
cat(paste("Std. Err. for log Odds Ratio = ", formatC(object$LOR.se), "\n"))
cat(paste("Odds Ratio Skill Score = ", formatC(object$orss, digits = 4), "\n"))
cat(paste("Std. Err. for Odds Ratio Skill Score = ", formatC(object$ORSS.se), "\n"))
cat(paste("Extreme Dependency Score (EDS) = ", formatC(object$eds, digits = 4), "\n"))
cat(paste("Std. Err. for EDS = ", formatC(object$eds.se, digits=4), "\n"))
cat(paste("Symmetric Extreme Dependency Score (SEDS) = ", formatC(object$seds, digits = 4), "\n"))
cat(paste("Std. Err. for SEDS = ", formatC(object$seds.se, digits=4), "\n"))
cat(paste("Extremal Dependence Index (EDI) = ", formatC(object$EDI, digits=4), "\n"))
cat(paste("Std. Err. for EDI = ", formatC(object$EDI.se, digits=4), "\n"))
cat(paste("Symmetric Extremal Dependence Index (SEDI) = ", formatC(object$SEDI, digits=4), "\n"))
cat(paste("Std. Err. for SEDI = ", formatC(object$SEDI.se, digits=4), "\n"))
} |
RMSD_DIF <- function(pooled_mod, flag = 0, probfun = TRUE, dentype = 'norm'){
dat <- extract.mirt(pooled_mod, 'data')
group <- extract.mirt(pooled_mod, "group")
which.groups <- extract.mirt(pooled_mod, 'groupNames')
ret <- vector('list', length(which.groups))
names(ret) <- which.groups
for(which.group in which.groups){
smod <- extract.group(pooled_mod, which.group)
nfact <- extract.mirt(smod, 'nfact')
stopifnot(nfact == 1L)
sv <- mod2values(smod)
sv$est <- FALSE
Theta <- matrix(seq(-6,6,length.out = 201))
mod_g <- mirt(subset(dat, group == which.group), nfact,
itemtype = extract.mirt(smod, 'itemtype'),
pars = sv, technical = list(storeEtable=TRUE, customTheta=Theta))
Etable <- mod_g@Internals$Etable[[1]]$r1
if(dentype %in% c('norm', 'snorm')){
mu <- sv$value[sv$name == "MEAN_1"]
sigma2 <- sv$value[sv$name == "COV_11"]
if(dentype == 'snorm'){
mu <- 0
sigma2 <- 1
}
f_theta <- dnorm(Theta, mean = mu, sd = sqrt(sigma2))
f_theta <- as.vector(f_theta / sum(f_theta))
} else if(dentype == 'empirical'){
f_theta <- rowSums(Etable) / sum(Etable)
} else stop('dentype not supported', call.=FALSE)
itemloc <- extract.mirt(mod_g, 'itemloc')
which.items <- 1L:ncol(dat)
ret2 <- vector('list', ncol(dat))
names(ret2) <- extract.mirt(mod_g, 'itemnames')
for(i in seq_len(length(which.items))){
pick <- itemloc[which.items[i]]:(itemloc[which.items[i]+1L] - 1L)
O <- Etable[ ,pick]
P_o <- O / rowSums(O)
item <- extract.item(smod, which.items[i])
P_e <- probtrace(item, Theta)
ret2[[i]] <- if(probfun){
sqrt(colSums((P_o - P_e)^2 * f_theta))
} else {
S <- 1L:ncol(P_o)- 1L
c("S(theta)" = sqrt(sum(( colSums(S*t(P_o - P_e)) )^2 * f_theta)))
}
}
nms <- lapply(ret2, names)
unms <- unique(do.call(c, nms))
items <- matrix(NA, length(ret2), length(unms))
rownames(items) <- names(ret2)
colnames(items) <- unms
for(i in seq_len(nrow(items)))
items[i, nms[[i]]] <- ret2[[i]]
if(flag > 0)
items[items < flag] <- NA
items <- as.data.frame(items)
items <- as.mirt_df(items)
ret[[which.group]] <- items
}
ret
} |
test_that("We can compute the vertex neighborhood using igraph.", {
if(requireNamespace("igraph", quietly = TRUE)) {
testthat::skip_on_cran();
fsbrain::download_optional_data();
subjects_dir = fsaverage.path(allow_fetch = TRUE);
subject_id = 'fsaverage';
surface = subject.surface(subjects_dir, subject_id, surface = "white", hemi = "lh");
g = fs.surface.to.igraph(surface);
neighbors_igraph = igraph::neighborhood(g, order = 1, nodes = 15);
neighbors_fsbrain = mesh.vertex.neighbors(surface, source_vertices = 15, k = 1);
testthat::expect_true(all(sort(as.integer(unlist(neighbors_igraph))) == sort(neighbors_fsbrain$vertices)));
neighbors_igraph_wrapped = fsbrain:::fs.surface.vertex.neighbors(surface, nodes = 15, order = 1, include_self = TRUE);
testthat::expect_equal(sort(neighbors_igraph_wrapped), sort(neighbors_fsbrain$vertices));
} else {
testthat::skip("This test requires the 'igraph' package.");
}
}) |
read.emusegs <- function(file)
{
if( is.R() && as.numeric(version$minor) > 3.0 ) {
lines <- scan(file, what = "", sep="\n", comment.char="")
} else {
lines <- scan(file, what = "", sep="\n")
}
inheader <- 1
i <- 1
labels <- start <- end <- utts <- NULL
while( i < length(lines) && inheader) {
if( lines[i] == "
inheader <- 0
} else {
foo <- splitstring( lines[i], ":" )
if( foo[1] == "database" ) database <- paste(foo[-1], sep=":")
if( foo[1] == "query" ) {
query <- paste(foo[-1], sep=":")
}
if( foo[1] == "type" ) type <- paste(foo[-1], sep=":")
i <- i + 1
}
}
if (inheader) {
stop( "End of header (
}
mat <- matscan( file, 4, what="", sk=i )
segs <- make.seglist(mat[,1], mat[,2], mat[,3], mat[,4],
query, type, database )
segs
}
if( version$major >= 5 ) {
setOldClass(c("emusegs", "data.frame"))
}
make.seglist <- function(labels, start, end, utts, query, type, database)
{
seglist <- data.frame(labels=I(as.character(labels)),
start=as.numeric(start),
end=as.numeric(end),
utts=I(as.character(utts)))
if( version$major >= 5 ) {
oldClass(seglist) <- "emusegs"
} else {
class(seglist) <- c("emusegs", "data.frame")
}
attr(seglist, "query") <- query
attr(seglist, "type") <- type
attr(seglist, "database") <- database
seglist
}
is.seglist <- function(object) {
return( inherits(object, "emusegs") )
}
"modify.seglist" <- function( segs,
labels=label.emusegs(segs),
start=start.emusegs(segs),
end=end.emusegs(segs),
utts=utt.emusegs(segs),
query=emusegs.query(segs),
type=emusegs.type(segs),
database=emusegs.database(segs))
{
make.seglist( labels, start, end, utts,
query, type, database )
}
"emusegs.database" <- function(sl)
{
if(is.seglist(sl))
attr(sl, "database")
else
stop( "not an emu segment list" )
}
"emusegs.type" <- function(sl)
{
if(is.seglist(sl))
attr(sl, "type")
else
stop( "not an emu segment list" )
}
"emusegs.query" <- function(sl)
{
if(is.seglist(sl))
attr(sl, "query")
else
stop( "not an emu segment list" )
}
"print.emusegs" <- function(x, ...)
{
cat(attributes(x)$type, " list from database: ", attributes(x)$database, "\n")
cat("query was: ", attributes(x)$query, "\n" )
if( version$major >= 5 ) {
oldClass(x) <- "data.frame"
} else {
class(x) <- "data.frame"
}
print.data.frame(x, ...)
}
summary.emusegs <- function(object, ...)
{
cat(attributes(object)$type, " list from database: ", attributes(object)$database, "\n")
cat("query was: ", attributes(object)$query, "\n" )
cat(" with", length(object$start), "segments\n\n")
cat("Segment distribution:\n")
print(table(object$label))
invisible()
}
"label" <- function(segs) {
UseMethod("label")
}
"label.emusegs" <- function(segs)
{
as.character(segs$label)
}
"as.matrix.emusegs" <- function(x, ...)
{
cbind( as.character(x$label), x$start, x$end, as.character(x$utt) )
}
"write.emusegs" <- function(seglist, file)
{
if(inherits(seglist,"emuRsegs")){
warning("You are using the write function of the legacy class emusegs for an emuRsegs object. The persisted object cannot be read back as emuRsegs object. It is recommended to use standard R function save() instead to persist an emuRsegs object.")
}
cat(paste("database:", attributes(seglist)$database, "\n", sep=""), file=file)
cat(paste("query:", attributes(seglist)$query, "\n", sep=""), file=file, append=TRUE)
cat(paste("type:", attributes(seglist)$type, "\n", sep=""), file=file, append=TRUE)
cat("
write(t(as.matrix(seglist)), file, ncolumns = 4, append=TRUE)
}
"start.emusegs" <- function(x, ...)
{
as.numeric(x$start)
}
"end.emusegs" <- function(x, ...)
{
as.numeric(x$end)
}
"utt" <- function(x) {
UseMethod("utt")
}
"utt.emusegs" <- function(x)
{
as.character(x$utts)
}
"dur" <- function(x) {
UseMethod("dur")
}
"dur.emusegs" <- function (x)
{
if(all(end(x)==0))
d <- end(x)
else
d <- end(x) - start(x)
d
} |
stopifnot(require("testthat"),
require("glmmTMB"),
require("MASS"))
context("weight")
set.seed(1)
nrep <- 20
nsim <- 5
sdi <- .1
sdii <- .2
rho <- -.1
slope <- .8
ni<-100
dat <- expand.grid(i=1:ni, rep=1:nrep , x=c(0 ,.2, .4))
RE <- MASS::mvrnorm(n = ni, mu =c(0, 0),
Sigma = matrix(c(sdi*sdi, rho*sdi*sdii, rho*sdi*sdii ,sdii*sdii),2,2))
inddat <- transform(dat, y=rpois(n=nrow(dat),
lambda = exp(RE[i,1] + x*(slope + RE[i,2]))))
aggdat <- with(inddat,as.data.frame(table(i,x,y),
stringsAsFactors=FALSE))
aggdat <- aggdat[with(aggdat,order(i,x,y)),]
aggdat <- subset(aggdat,Freq>0)
aggdat <- transform(aggdat,
i=as.integer(i),
x=as.numeric(x),
y=as.numeric(y))
test_that("Weights can be an argument", {
wei_glmmtmb <<- glmmTMB(y ~ x+(x|i), data=aggdat, weight=Freq,
family="poisson")
expect_equal(unname(fixef(wei_glmmtmb)$cond),
c(-0.00907013282660578, 0.944062427131668),
tolerance=1e-6)
})
test_that("Return weights", {
expect_equal(weights(wei_glmmtmb), aggdat$Freq)
expect_equal(weights(wei_glmmtmb, type="prior"), aggdat$Freq)
expect_equal(weights(wei_glmmtmb, type="prio"), aggdat$Freq)
expect_error(weights(wei_glmmtmb, type = "working"),"should be one of")
expect_warning(weights(wei_glmmtmb, junk = "abc"),
"unused arguments ignored")
})
ind_glmmtmb <<- glmmTMB(y ~ x+(x|i), data=inddat, family="poisson")
test_that("Estimates are the same", {
expect_equal(summary(wei_glmmtmb)$coefficients$cond, summary(ind_glmmtmb)$coefficients$cond, tolerance=1e-6)
expect_equal(ranef(wei_glmmtmb), ranef(ind_glmmtmb), tolerance=1e-5)
expect_equal(AIC(wei_glmmtmb), AIC(ind_glmmtmb), tolerance=1e-5)
}) |
SAS.uncomment <-
function( SASinput , starting.comment , ending.comment ){
for ( i in 1:length(SASinput) ){
slash_asterisk <- unlist( gregexpr( starting.comment , SASinput[ i ] , fixed = T ) )
asterisk_slash <- unlist( gregexpr( ending.comment , SASinput[ i ] , fixed = T ) )
if ( !( -1 %in% slash_asterisk ) ){
if ( max( asterisk_slash ) > min( slash_asterisk ) ){
SASinput[ i ] <- sub( substr( SASinput[ i ] , slash_asterisk[1] , asterisk_slash[1] + 1 ) , "" , SASinput[ i ] , fixed = T )
i <- i - 1
} else {
SASinput[ i ] <- sub( substr( SASinput[ i ] , slash_asterisk[1] , nchar( SASinput[ i ] ) ) , "" , SASinput[ i ] , fixed = T )
j <- i
while( max( asterisk_slash ) < 0 ){
j <- j + 1
asterisk_slash <- unlist( gregexpr( ending.comment , SASinput[ j ] , fixed = T ) )
if ( max( asterisk_slash ) < 0 ) SASinput[ j ] <- ""
else SASinput[ j ] <- sub( substr( SASinput[ j ] , 1 , asterisk_slash[1] + 1 ) , "" , SASinput[ j ] , fixed = T )
}
}
}
}
SASinput
} |
test_that("classif_bdk", {
requirePackagesOrSkip("kohonen", default.method = "load")
parset.list1 = list(
list(),
list(grid = class::somgrid(xdim = 2L, ydim = 4L)),
list(rlen = 50L)
)
parset.list2 = list(
list(),
list(xdim = 2L, ydim = 4L),
list(rlen = 50L)
)
old.probs.list = old.predicts.list = list()
for (i in seq_along(parset.list1)) {
pars = parset.list1[[i]]
pars$data = as.matrix(binaryclass.train[, -binaryclass.class.col])
pars$Y = binaryclass.train[, binaryclass.class.col]
pars$keep.data = FALSE
set.seed(getOption("mlr.debug.seed"))
m = do.call(kohonen::bdk, pars)
p = predict(m, as.matrix(binaryclass.test[, -binaryclass.class.col]))
old.predicts.list[[i]] = p$prediction
old.probs.list[[i]] = p$unit.predictions[p$unit.classif, 1L]
}
testSimpleParsets("classif.bdk", binaryclass.df, binaryclass.target, binaryclass.train.inds,
old.predicts.list, parset.list2)
testProbParsets("classif.bdk", binaryclass.df, binaryclass.target, binaryclass.train.inds,
old.probs.list, parset.list2)
})
test_that("classif_bdk keep.data is passed correctly", {
train(makeLearner("classif.bdk", keep.data = FALSE), binaryclass.task)
train(makeLearner("classif.bdk", keep.data = TRUE), binaryclass.task)
}) |
setClass("tvMGarch",
slots = c(
out_of_sample_prop = "numeric",
out_of_sample_y = "matrix",
in_sample_y = "matrix"
),
prototype = list(
out_of_sample_prop = .1
),
contains="simMGarch"
) |
ca3basic <-
function(x, p, q, r, test = 10^-6, ctr = T, std = T){
nnom <- dimnames(x)
nomi <- nnom[[1]]
nomj <- nnom[[2]]
nomk <- nnom[[3]]
xs <- standtab(x, ctr = ctr, std = std) * sqrt(sum(x))
res <- tucker(xs, p, q, r, test)
ncore<-dim(res$g)
np <- paste("p", 1:ncore[1], sep = "")
nq <- paste("q", 1:ncore[2], sep = "")
nr <- paste("r", 1:ncore[3], sep = "")
dimnames(res$g) <- list(np, nq, nr)
res$xs <- xs
xhat <- reconst3(res)
nx2 <- sum(xs^2)
res$tot <- nx2
nxhat2 <- sum(xhat^2)
ng2 <- sum(res$g^2)
prp <- ng2/nx2
res$ctr <- list(cti = res$a^2, ctj = res$b^2, ctk = res$cc^2)
comp <- coord(res, x)
res$xinit <- x
dimnames(comp$a) <- list(nomi, np)
dimnames(comp$b) <- list(nomj, nq)
dimnames(comp$cc) <- list(nomk, nr)
dimnames(xhat) <- list(nomi, nomj, nomk)
ca3results<-list( x = x, xs = xs, xhat = xhat, nxhat2 =
nxhat2, prp = prp, a = comp$a, b = comp$b, cc = comp$cc, g = res$g,
iteration = res$cont)
return(ca3results)
} |
message("\n---- Test sen2r_getElements ----")
fs2nc_examplename <- "/path/of/the/product/S2A1C_20170603_022_32TQQ_TOA_20.tif"
testthat::test_that(
"Tests on sen2r_getElements", {
meta <- sen2r_getElements(fs2nc_examplename)
testthat::expect_is(meta, "data.table")
testthat::expect_equal(meta, data.table(
type = "tile", mission = "A",
level = "1C",
sensing_date = structure(17320, class = "Date"),
id_orbit = "022",
extent_name = "32TQQ",
prod_type = "TOA",
res = "20m",
file_ext = "tif")
)
meta <- sen2r_getElements(fs2nc_examplename, format = "data.frame")
testthat::expect_is(meta, "data.frame")
meta <- sen2r_getElements(fs2nc_examplename, format = "list")
testthat::expect_is(meta, "list")
}
) |
library(testthat)
library(ggcharts)
test_check("ggcharts") |
context("plotSTEPCAM")
test_that("plotSTEPCAM: use", {
skip_on_cran()
set.seed(42)
n_traits <- 3
n_plots <- 10
num_species <- 10
x <- generate.Artificial.Data(n_species = num_species, n_traits = n_traits,
n_communities = n_plots,
occurence_distribution = 0.5,
average_richness = 10,
sd_richness = 1,
mechanism_random = FALSE)
data_species <- x$traits
data_species$trait1 <- c(runif(8,0,1), 5, 10)
data_species$trait2 <- c(runif(8,0,1), -10, 30)
data_species$trait3 <- c(runif(8,0,1), -20, 40)
data_abundances <- x$abundances
for(i in 1:8) {
data_abundances[1,i] <- 1
}
data_abundances[1,9] <- 0
data_abundances[1,10] <- 0
output <- STEPCAM_ABC(data_abundances, data_species,
numParticles = 100, n_traits, plot_number = 1,
stopRate = 0.1, stop_at_iteration = 3, continue_from_file = TRUE)
plotSTEPCAM(output)
}) |
DefaultData<-read.csv("./regr/MMM_raw_data_v02.csv")
head(DefaultData)
tail(DefaultData)
summary(DefaultData)
plot(DefaultData$Unit_Sold)
quantile(DefaultData$Unit_Sold, c(0,0.05,0.1,0.25,0.5,0.75,0.90,0.95,0.99,0.995,1))
DefaultData$CappedUnitSold<-ifelse(DefaultData$Unit_Sold>768,768,DefaultData$Unit_Sold)
summary(DefaultData)
names(DefaultData)
DefaultData3<-DefaultData[,-c(2)]
names(DefaultData3)
head(DefaultData3)
plot(DefaultData3$Print_Spend,DefaultData3$CappedUnitSold)
plot(DefaultData3$Radio_Spend,DefaultData3$CappedUnitSold)
plot(DefaultData3$TV_Spend,DefaultData3$CappedUnitSold)
names(DefaultData3)
library("car")
vif_data<-lm(CappedUnitSold~
Print_Spend+
Radio_Spend+
TV_Spend+
Promotion_Dummy,data=DefaultData3)
vif(vif_data)
lin_r1<-lm(CappedUnitSold~
Print_Spend+
Radio_Spend+
TV_Spend+
Promotion_Dummy,data=DefaultData3)
summary(lin_r1)
fitted(lin_r1)
summary(lin_r1)$r.squared
plot(lin_r1)
meancnt1=DefaultData3
meancnt1$pred = 56.7185191 +
0.0098758*DefaultData3$Print_Spend+0.2493764*DefaultData3$Radio_Spend
meancnt1$res = meancnt1$pred - meancnt1$CappedUnitSold
meancnt1$abs_res = abs(meancnt1$res)
meancnt1$mape = 100*meancnt1$abs_res/meancnt1$CappedUnitSold;
meancnt1$mape
plot(meancnt1$pred,meancnt1$res) |
BT <- function(DataSub, BLR){
DataSub <- as.timeSeries(DataSub)
PPrior <- tangencyPortfolio(data = DataSub, spec = MSPrior,
constraints = BoxC)
PBl <- tangencyPortfolio(data = DataSub, spec = MSBl,
constraints = BoxC)
Weights <- rbind(getWeights(PPrior), getWeights(PBl))
colnames(Weights) <- ANames
rownames(Weights) <- c("Prior", "BL")
return(Weights)
}
Backtest <- list()
for(i in 1:length(idx)){
DataSub <- window(R, start = start(AssetsM), end = idx[i])
BLR <- PostDist[[i]]
Backtest[[i]] <- BT(DataSub, BLR)
} |
Interpolate360Days2Caldendar <- function(df, sdate) {
sdate <- as.Date(sdate)
edate <- df[length(df[,1]),1]
fdate <- data.frame(seq(sdate, edate, by=1))
colnames(fdate) <- "date"
df <- merge(fdate, df, by="date", all=T)
df <- zoo::na.approx(df[2:length(df[1,])], na.rm=F)
df[which(is.na(df[,1])),] <- df[which(is.na(df[,1]))-1,]
df <- cbind(fdate,df)
return(df)
} |
checkRaw = function(x, len = NULL, min.len = NULL, max.len = NULL, names = NULL, null.ok = FALSE) {
.Call(c_check_raw, x, len, min.len, max.len, names, null.ok)
}
check_raw = checkRaw
assertRaw = makeAssertionFunction(checkRaw, c.fun = "c_check_raw", use.namespace = FALSE)
assert_raw = assertRaw
testRaw = makeTestFunction(checkRaw, c.fun = "c_check_raw")
test_raw = testRaw
expect_raw = makeExpectationFunction(checkRaw, c.fun = "c_check_raw", use.namespace = FALSE) |
fluidPage(theme = 'zoo.css',
fluidRow(
column(12, align="center",
column(3,align = "left",
radioButtons("radio_rt", label = h5("Correlation Type"),selected = 1,
choices = list("Pearson" = 1, "Spearman" = 2)
)
),
column(9,align = "center",
selectInput("spectrum_list_stocsy_rt","Which spectrum do you want to see?",file_names[], selectize = FALSE),
p(strong("To perform real-time STOCSY analysis, place the cursor on the desired driver peak."))
)
)
),
fluidRow(align = "center",
column(3, align="center",
sidebarPanel(width =12,
fluidRow(
sliderInput("cutoff_stocsy_rt", label = h5("Correlation Cutoff"), min = 0,
max = 1, value = 0.9 , step= 0.1)
),
fluidRow(
tags$button(id = "x2_stocsy_rt",
class = "btn action-button",
tags$img(src = "bx2.png",
height = "35px", width = "40px")
),
tags$button(id = "x8_stocsy_rt",
class = "btn action-button",
tags$img(src = "bx8.png",
height = "35px", width = "40px")
)
),
fluidRow(div(style="height:5px")),
fluidRow(
tags$button(id = "q2_stocsy_rt",
class = "btn action-button",
tags$img(src = "bq2.png",
height = "35px", width = "40px")
),
tags$button(id = "q8_stocsy_rt",
class = "btn action-button",
tags$img(src = "bq8.png",
height = "35px", width = "40px")
)
),
br(),
fluidRow(
tags$button(id = "s_left_stocsy_rt",
class = "btn action-button",
tags$img(src = "s_left.png",
height = "35px", width = "40px")
),
tags$button(id = "s_right_stocsy_rt",
class = "btn action-button",
tags$img(src = "s_right.png",
height = "35px", width = "40px")
)
),
fluidRow(div(style="height:5px")),
fluidRow(
tags$button(id = "s_left_f_stocsy_rt",
class = "btn action-button",
tags$img(src = "s_left_f.png",
height = "35px", width = "40px")
),
tags$button(id = "s_right_f_stocsy_rt",
class = "btn action-button",
tags$img(src = "s_right_f.png",
height = "35px", width = "40px"))),
br(),
fluidRow(
tags$button(id = "all_stocsy_rt",
class = "btn action-button",
tags$img(src = "all.png",
height = "35px", width = "40px")
)
),
br(),
fluidRow(
tags$button(id = "stocsy_rt_print_PDF",
class = "btn action-button",
tags$img(src = "exp_stocsy.png",
height = "35px", width = "40px")),
bsTooltip("stocsy_rt_print_PDF", "Download PDF",
"right", options = list(container = "body")),
)
)),
column(9, align="center",
sidebarPanel(width =12,
plotOutput("plot_stocsy_rt", width = "100%", height = "500px", click = "click_stocsy_rt", dblclick = "dblclick_stocsy_rt",
brush = brushOpts(id = "plot_brush_stocsy_rt",delay = 5000,
fill = "
)
))
)
) |
crwSimulator = function(
object.crwFit,
predTime=NULL,
method="IS",
parIS=1000,
df=Inf,
grid.eps=1,
crit=2.5,
scale=1, quad.ask=TRUE, force.quad) {
data <- object.crwFit$data
driftMod <- object.crwFit$random.drift
mov.mf <- object.crwFit$mov.mf
activity <- object.crwFit$activity
err.mfX <- object.crwFit$err.mfX
err.mfY <- object.crwFit$err.mfY
rho = object.crwFit$rho
par <- object.crwFit$par
n.errX <- object.crwFit$n.errX
n.errY <- object.crwFit$n.errY
n.mov <- object.crwFit$n.mov
tn <- object.crwFit$Time.name
return_posix <- ifelse((inherits(predTime,"POSIXct") | inherits(predTime, "character")) &
inherits(data[,tn],"POSIXct"),
TRUE, FALSE)
if(!return_posix) {
if(inherits(predTime,"numeric") && inherits(data[, tn], "POSIXct")) {
warning("predTime provided as numeric and original data was POSIX! Make sure they are compatible")
}
if(inherits(predTime,"POSIXct") && inherits(data[, tn], "numeric")) {
warning("predTime provided as POSIX and original data was numeric! Make sure they are compatible")
}
}
if (!is.null(predTime)) {
if(inherits(predTime,"character")) {
t_int <- unlist(strsplit(predTime, " "))
if(t_int[2] %in% c("min","mins","hour","hours","day","days")) {
min_dt <- min(data[,tn],na.rm=TRUE)
max_dt <- max(data[,tn],na.rm=TRUE)
min_dt <- round(min_dt,t_int[2])
max_dt <- trunc(max_dt,t_int[2])
predTime <- seq(min_dt, max_dt, by = predTime)
} else {
stop("predTime not specified correctly. see documentation for seq.POSIXt")
}
}
ts = attr(object.crwFit, "time.scale")
predTime = as.numeric(predTime)/ts
if(min(predTime) < data[1, "TimeNum"]) {
warning("Predictions times given before first observation!\nOnly those after first observation will be used.")
predTime <- predTime[predTime>=data[1,"TimeNum"]]
}
origTime <- data$TimeNum
if (is.null(data$locType)) data$locType <- "o"
predData <- data.frame(predTime, "p")
names(predData) <- c("TimeNum", "locType")
data <- merge(data, predData,
by=c("TimeNum", "locType"), all=TRUE)
dups <- duplicated(data$TimeNum)
data <- data[!dups, ]
mov.mf <- as.matrix(expandPred(x=mov.mf, Time=origTime, predTime=predTime))
if (!is.null(activity)) activity <- as.matrix(expandPred(x=activity, Time=origTime, predTime=predTime))
if (!is.null(err.mfX)) err.mfX <- as.matrix(expandPred(x=err.mfX, Time=origTime, predTime=predTime))
if (!is.null(err.mfY)) err.mfY <- as.matrix(expandPred(x=err.mfY, Time=origTime, predTime=predTime))
if (!is.null(rho)) rho <- as.matrix(expandPred(x=rho, Time=origTime, predTime=predTime))
}
data$locType[data[,tn]%in%predTime] <- 'p'
delta <- c(diff(data$TimeNum), 1)
y = as.matrix(data[,object.crwFit$coord])
noObs <- as.numeric(is.na(y[,1]) | is.na(y[,2]))
y[noObs==1,] = 0
N = nrow(y)
out <- list(y=y, noObs=noObs, n.errX=n.errX, n.errY=n.errY, n.mov=n.mov,
delta=delta, driftMod=driftMod, activity=activity, err.mfX=err.mfX,
err.mfY=err.mfY, mov.mf=mov.mf, rho=rho, fixPar=object.crwFit$fixPar,
Cmat=object.crwFit$Cmat, locType=data$locType,
par=object.crwFit$par, nms=object.crwFit$nms, N=nrow(data), lower=object.crwFit$lower,
upper=object.crwFit$upper,
loglik=object.crwFit$loglik, TimeNum=data$TimeNum, Time.name=tn, return_posix=return_posix,
coord=object.crwFit$coord, prior=object.crwFit$prior)
class(out) <- 'crwSimulator'
if(parIS>1 & object.crwFit$need.hess==TRUE) out <- crwSamplePar(out, method=method, size=parIS, df=df, grid.eps=grid.eps, crit=crit, scale=scale, quad.ask=quad.ask, force.quad = force.quad)
if(!is.null(out)){
attr(out,"epsg") <- attr(object.crwFit,"epsg")
attr(out,"proj4") <- attr(object.crwFit,"proj4")
}
return(out)
} |
BachelierPrice <- function(
strike=forward, spot, texp=1, sigma,
intr=0, divr=0, cp=1L,
forward=spot*exp(-divr*texp)/df, df=exp(-intr*texp)
){
stdev <- sigma*sqrt(texp)
stdev[stdev < 1e-32] <- 1e-32
dn <- cp*(forward-strike)/stdev
price <- df * (cp*(forward-strike)*stats::pnorm(dn) + stdev*stats::dnorm(dn))
return( price )
} |
lineups_searcher <- function(df1,n,p1,p2,p3,p4){
if(n==1){
aux2 <- df1[df1$PG==p1,]; aux3 <- df1[df1$SG==p1,]; aux4 <- df1[df1$SF==p1,]; aux5 <- df1[df1$PF==p1,]; aux6 <- df1[df1$C== p1,]
df<-rbind(aux2,aux3,aux4,aux5,aux6)
}else if(n==2){
aux2 <- df1[df1$PG==p1,]; aux3 <- df1[df1$SG==p1,]; aux4 <- df1[df1$SF==p1,]; aux5 <- df1[df1$PF==p1,]; aux6 <- df1[df1$C== p1,]
aux1<-rbind(aux2,aux3,aux4,aux5,aux6)
aux2 <- aux1[aux1$PG==p2,]; aux3 <- aux1[aux1$SG==p2,];aux4 <- aux1[aux1$SF==p2,]; aux5 <- aux1[aux1$PF==p2,]; aux6 <- aux1[aux1$C==p2,]
df<-rbind(aux2,aux3,aux4,aux5,aux6)
}else if (n==3){
aux2 <- df1[df1$PG==p1,]; aux3 <- df1[df1$SG==p1,]; aux4 <- df1[df1$SF==p1,]; aux5 <- df1[df1$PF==p1,]; aux6 <- df1[df1$C== p1,];
aux1<-rbind(aux2,aux3,aux4,aux5,aux6)
aux2 <- aux1[aux1$PG==p2,]; aux3 <- aux1[aux1$SG==p2,]; aux4 <- aux1[aux1$SF==p2,]; aux5 <- aux1[aux1$PF==p2,]; aux6 <- aux1[aux1$C==p2,]
aux<-rbind(aux2,aux3,aux4,aux5,aux6)
aux2 <- aux[aux$PG==p3,]; aux3 <- aux[aux$SG==p3,]; aux4 <- aux[aux$SF==p3,]; aux5 <- aux[aux$PF==p3,]; aux6 <- aux[aux$C==p3,]
df<-rbind(aux2,aux3,aux4,aux5,aux6)
}else if(n==4){
aux2 <- df1[df1$PG==p1,]; aux3 <- df1[df1$SG==p1,]; aux4 <- df1[df1$SF==p1,]; aux5 <- df1[df1$PF==p1,]; aux6 <- df1[df1$C== p1,]
aux1<-rbind(aux2,aux3,aux4,aux5,aux6)
aux2 <- aux1[aux1$PG==p2,]; aux3 <- aux1[aux1$SG==p2,]; aux4 <- aux1[aux1$SF==p2,]; aux5 <- aux1[aux1$PF==p2,]; aux6 <- aux1[aux1$C==p2,]
aux<-rbind(aux2,aux3,aux4,aux5,aux6)
aux2 <- aux[aux$PG==p3,]; aux3 <- aux[aux$SG==p3,]; aux4 <- aux[aux$SF==p3,]; aux5 <- aux[aux$PF==p3,]; aux6 <- aux[aux$C==p3,]
aux<-rbind(aux2,aux3,aux4,aux5,aux6)
aux2 <- aux[aux$PG==p4,]; aux3 <- aux[aux$SG==p4,]; aux4 <- aux[aux$SF==p4,]; aux5 <- aux[aux$PF==p4,]; aux6 <- aux[aux$C==p4,]
df<-rbind(aux2,aux3,aux4,aux5,aux6)
}
return(df)
} |
interact.gbm <- function(x, data, i.var = 1, n.trees = x$n.trees){
if (x$interaction.depth < length(i.var)){
stop("interaction.depth too low in model call")
}
if (all(is.character(i.var))){
i <- match(i.var, x$var.names)
if (any(is.na(i))) {
stop("Variables given are not used in gbm model fit: ", i.var[is.na(i)])
}
else {
i.var <- i
}
}
if ((min(i.var) < 1) || (max(i.var) > length(x$var.names))) {
warning("i.var must be between 1 and ", length(x$var.names))
}
if (n.trees > x$n.trees) {
warning(paste("n.trees exceeds the number of trees in the model, ",
x$n.trees,". Using ", x$n.trees, " trees.", sep = ""))
n.trees <- x$n.trees
}
unique.tab <- function(z,i.var) {
a <- unique(z[,i.var,drop=FALSE])
a$n <- table(factor(apply(z[,i.var,drop=FALSE],1,paste,collapse="\r"),
levels=apply(a,1,paste,collapse="\r")))
return(a)
}
for(j in i.var) {
if(is.factor(data[,x$var.names[j]]))
data[,x$var.names[j]] <-
as.numeric(data[,x$var.names[j]])-1
}
a <- apply(expand.grid(rep(list(c(FALSE,TRUE)), length(i.var)))[-1,],1,
function(x) as.numeric(which(x)))
FF <- vector("list",length(a))
for(j in 1:length(a)) {
FF[[j]]$Z <- data.frame(unique.tab(data, x$var.names[i.var[a[[j]]]]))
FF[[j]]$n <- as.numeric(FF[[j]]$Z$n)
FF[[j]]$Z$n <- NULL
FF[[j]]$f <- .Call("gbm_plot",
X = as.double(data.matrix(FF[[j]]$Z)),
cRows = as.integer(nrow(FF[[j]]$Z)),
cCols = as.integer(ncol(FF[[j]]$Z)),
n.class = as.integer(x$num.classes),
i.var = as.integer(i.var[a[[j]]] - 1),
n.trees = as.integer(n.trees),
initF = as.double(x$initF),
trees = x$trees,
c.splits = x$c.splits,
var.type = as.integer(x$var.type),
PACKAGE = "gbm")
FF[[j]]$f <- matrix(FF[[j]]$f, ncol=x$num.classes, byrow=FALSE)
FF[[j]]$f <- apply(FF[[j]]$f, 2, function(x, w){
x - weighted.mean(x, w, na.rm=TRUE)
}, w=FF[[j]]$n)
FF[[j]]$sign <- ifelse(length(a[[j]]) %% 2 == length(i.var) %% 2, 1, -1)
}
H <- FF[[length(a)]]$f
for(j in 1:(length(a)-1)){
i1 <- apply(FF[[length(a)]]$Z[,a[[j]], drop=FALSE], 1, paste, collapse="\r")
i2 <- apply(FF[[j]]$Z,1,paste,collapse="\r")
i <- match(i1, i2)
H <- H + with(FF[[j]], sign*f[i,])
}
w <- matrix(FF[[length(a)]]$n, ncol=1)
f <- matrix(FF[[length(a)]]$f^2, ncol=x$num.classes, byrow=FALSE)
top <- apply(H^2, 2, weighted.mean, w = w, na.rm = TRUE)
btm <- apply(f, 2, weighted.mean, w = w, na.rm = TRUE)
H <- top / btm
if (x$distribution$name=="multinomial"){
names(H) <- x$classes
}
H[H > 1] <- NaN
return(sqrt(H))
} |
get_param <- function(param.name,Params,calling.func,default=NULL)
{
if (is.null(Params[[param.name]]))
{
if (is.null(default)) stop(paste("Parameter",param.name,"needed in",calling.func))
else return(default)
} else return(Params[[param.name]])
} |
expected <- eval(parse(text="NULL"));
test(id=0, code={
argv <- eval(parse(text="list(logical(0))"));
.Internal(formals(argv[[1]]));
}, o=expected); |
setClass('mapview',
slots = c(object = 'list',
map = 'ANY'))
NULL
setOldClass("leaflet")
setOldClass(c("POINT", "MULTIPOINT",
"POLYGON", "MULTIPOLYGON",
"LINESTRING", "MULTILINESTRING"))
setOldClass("XY")
setOldClass("sf")
setOldClass("sfc")
setOldClass("sfg")
setOldClass("XYM")
setOldClass("XYZM")
setOldClass("bbox")
setOldClass("stars")
setOldClass("stars_proxy") |
Err_exp_item <- function(X,index=NULL,EO){
J <- colnames(X)
nn<-length(J)
cmbf<-combinations(n=nn, r=3, v=J, set=FALSE, repeats.allowed=FALSE)
expe <- NULL
if (is.null(index)){
for (iter in 1:nn){
expe <- c(expe,sum(EO[cmbf[which(apply(cmbf,1, function(x) J[iter] %in%x)),]]))
}
}else{
expe <- c(expe,sum(EO[cmbf[which(apply(cmbf,1, function(x) index %in%x)),]]))
}
return(expe)
} |
Set2expr <-
function(v=NULL ) {
if ( is.null(v) ) stop("The parameter is missing");
u<-list(); U<-list();
nv<-length(v)
for (i in 2:nv) {
u<-c(u, list(v[[i-1]]) )
if ( v[[i]][1]!=v[[i-1]][1] ) {
U<-c(U, list(u)); u<-list();
}
}
u<-c(u, list(v[[nv]]) )
U<-c(U, list(u));
S<-list();
for (m in U) {
lm<-length(m);
for (i in 1:(lm-1) ) {
for (j in (i+1):lm ) {
if( (m[[i]][3]==m[[j]][3]) && (m[[i]][4]>m[[j]][4]) )
{ app_m<- m[[i]];m[[i]]<-m[[j]];m[[j]]<-app_m }
}
}
c<-"1";
for (i in 1:lm ) {
c<-paste0(c,"*",m[[i]][2]);
m[[i]][2]<-1;
}
c<-eval(parse(text=c));
s<-"";
for (i in 1:(lm-1) ) {
k<-strtoi(m[[i]][5]);
for (j in (i+1):lm ) {
if( (m[[i]][3]==m[[j]][3]) && (m[[i]][4]==m[[j]][4]) && (m[[j]][3]!="") )
{ k<-k+strtoi(m[[j]][5]); m[[j]][3]<-""}
}
s<-paste0(s,m[[i]][3],ifelse(m[[i]][4]!="",paste0("[",m[[i]][4],"]"),""),ifelse(k>1,paste0("^",k),""));
}
if (m[[lm]][3]!="") {k<-strtoi(m[[lm]][5]); s<-paste0(s,m[[lm]][3],ifelse(m[[lm]][4]!="",paste0("[",m[[lm]][4],"]"),""),ifelse(k>1,paste0("^",k),""));}
S<-c(S, list(c(c,s)));
}
V<-"";
if (length(S)>1) {
for (i in 1:(length(S)-1)){
if (S[[i]][2]!="") {
c<-S[[i]][1];
for (j in (i+1):length(S)){
if (( S[[i]][2]==S[[j]][2]) && (S[[j]][2]!="")) {
c<-paste0(c,"+",S[[j]][1]);
S[[j]][2]<-"";
}
}
c<-eval(parse(text=c));
signc<-ifelse(c>0," + "," - ");
c<-ifelse( (abs(c)==1),"",abs(c)) ;
if (c!=0) V<-paste0(V,signc,c,S[[i]][2]);
}
}
}
i<-length(S);
c<-S[[i]][1];
c<-eval(parse(text=c));
signc<-ifelse(c>0," + "," - ");
c<-ifelse( (abs(c)==1),"",abs(c)) ;
if ((c!=0) && (S[[i]][2]!="")) V<-paste0(V,signc,c,S[[i]][2]);
if ( substr(V,2,2)=="+") V<-substr(V,4,nchar(V));
noquote(V);
} |
compute_df <- function(k, type){
df <- sapply(k, compute.df, type)
df[df<1] <- 1
return(df)
}
compute.df <- function(k, type){
if(type=="O1" | type=="O2"| type=="O3"){
H.O <- k - 1
k.h.O <- rep(2, H.O)
df <- sum(k.h.O - 1)
}else{
if(type=="S1" | type=="S2"){
H.S <- floor(k/2)
k.h.S <- rep(2, H.S)
if(k %% 2 > 0) k.h.S[H.S] <- 3
df <- sum(k.h.S - 1)
}else{
df <- k-1
}
}
return(df)
} |
convert_gn <- function(container, genes) {
if (!is.null(container$gn_convert)) {
genes <- container$gn_convert[genes,2]
}
return(genes)
} |
context("Basics:")
test_that("class-markup", {
suppressWarnings(
test <- defineClass("test", {
.privateObject <- NULL
publicObject <- public("BAM!")
get <- public(function() .privateObject)
set <- public(function(value) .privateObject <<- value)
doSomethingWithPublicObject <- public(function() publicObject())
})
)
tmp <- test()
expect_is(tmp$get(), "NULL")
expect_equal(tmp$publicObject(), "BAM!")
expect_error(tmp$.privateObject)
expect_equal(tmp$set(2), 2)
expect_equal(tmp$get(), 2)
expect_equal(tmp$publicObject("jiggle"), "jiggle")
expect_equal(tmp$doSomethingWithPublicObject(), "jiggle")
suppressWarnings(tmp2 <- test())
expect_is(tmp2$get(), "NULL")
expect_equal(tmp2$publicObject(), "BAM!")
})
test_that("default-call", {
expect_is(suppressWarnings(defineClass("tmp")), "function")
expect_true(isClass("tmp"))
})
test_that("privacy works", {
class <- suppressWarnings({
defineClass("class", {
private <- private(2)
get <- public(function() 1)
})
})
tmp <- class()
expect_equal(tmp$get(), 1)
expect_error(tmp$private)
expect_error(tmp$something <- 1)
})
test_that("'init' function is executed", {
suppressWarnings({
test <- defineClass("test", {
name <- ""
init <- function(name) {
self$name(name)
}
})
defineClass("TestInit", {
field <- ""
init <- function() {
self$field("b")
}
})
})
expect_equal(test("jaj")$name(), "jaj")
expect_equal(new("test")$name(), "")
expect_equal(new("TestInit")$field(), "b")
})
test_that("Naming of constructor functions", {
constTest <- suppressWarnings({
defineClass("test", {
x <- public()
})
})
tmp <- constTest()
tmp1 <- new("test")
tmp$x(2)
expect_is(tmp, "test")
expect_is(tmp1, "test")
expect_is(tmp1$x(), "NULL")
expect_equal(tmp$x(), 2)
})
test_that("class-markup v2.0", {
suppressWarnings(
test <- defineClass("test2", {
.privateObject <- NULL
publicObject <- "BAM!"
get <- function() .privateObject
set <- function(value) .privateObject <<- value
doSomethingWithPublicObject <- function() publicObject()
})
)
tmp <- test()
expect_is(tmp$get(), "NULL")
expect_equal(tmp$publicObject(), "BAM!")
expect_error(tmp$.privateObject)
expect_equal(tmp$set(2), 2)
expect_equal(tmp$get(), 2)
expect_equal(tmp$publicObject("jiggle"), "jiggle")
expect_equal(tmp$doSomethingWithPublicObject(), "jiggle")
suppressWarnings(tmp2 <- test())
expect_is(tmp2$get(), "NULL")
expect_equal(tmp2$publicObject(), "BAM!")
})
test_that("init function is private by default", {
PrivateInitTest <- defineClass("PrivateInitTest", contains = "Accessor", {
x <- 1
init <- function() {
.self$x <- 2
}
})
expect_equal(PrivateInitTest()$x, 2)
expect_error(PrivateInitTest()$init())
PublicInitTest <- defineClass("PublicInitTest", contains = "Accessor", {
x <- 1
init <- public(function() {
.self$x <- 2
})
})
instance <- PublicInitTest()
instance$x <- 3
expect_equal(instance$x, 3)
instance$init()
expect_equal(instance$x, 2)
}) |
children <- hijack(r_sample,
name = "Children",
x = 0:10,
prob = c(.25, .25, .15, .15, .1, rep(.1/5, 4), .01, .01)
) |
test_that("reduce() stops early on reduced input", {
reducer <- function(result, input) {
if (input %% 2 == 0) {
done(result)
} else {
c(result, input)
}
}
expect_identical(reduce(1:5, reducer), 1L)
expect_identical(reduce(int(1L, 3L, 5:10), reducer), int(1L, 3L, 5L))
})
test_that("reduce_steps() calls initial step for initial value", {
builder <- function(result, input) {
if (missing(result) && missing(input)) {
stop("called for init value")
}
}
steps <- compose(iter_map(`+`, 1), iter_map(`+`, 1))
expect_error(reduce_steps(NULL, steps, builder), "called for init value")
})
test_that("reduce_steps() calls initial step for result completion", {
builder <- function(result, input) {
if (missing(result) && missing(input)) {
return(NULL)
}
if (missing(input)) {
stop("called for init completion")
}
}
steps <- compose(iter_map(`+`, 1), iter_map(`+`, 1))
expect_error(reduce_steps(NULL, steps, builder), "called for init completion")
})
test_that("into() creates vector of requested type", {
expect_identical(into(new_double(3), 1:3), dbl(1:3))
})
test_that("into() shrinks vector if needed", {
expect_identical(into(integer(10), 1:3), 1:3)
})
test_that("into() grows vector if needed", {
expect_identical(into(integer(1), 1:3), 1:3)
})
test_that("collect(n = ) fails if not enough elements", {
expect_error(collect(1:10, n = 15), "10 / 15 elements")
})
test_that("can reduce iterators", {
iter <- as_iterator(1:3)
out <- reduce_steps(iter, NULL, along_builder(chr()))
expect_identical(out, as.character(1:3))
})
test_that("reducing exhausted iterators produces empty output", {
expect_identical(
collect(function() exhausted()),
list()
)
})
test_that("collect() retains `NULL` values", {
g <- function() {
i <- 0
function() {
i <<- i + 1
if (i > 3) {
exhausted()
} else {
out[[i]]
}
}
}
out <- list(1, 2, NULL)
expect_equal(collect(g()), out)
out <- list(1, NULL, 2)
expect_equal(collect(g()), out)
})
test_that("collect() calls `as_iterator()`", {
local_methods(
as_iterator.coro_foobar = function(x) {
called <- FALSE
function() {
out <- if (called) exhausted() else "foo"
called <<- TRUE
out
}
}
)
foobar <- structure(list(), class = "coro_foobar")
expect_equal(
collect(foobar),
list("foo")
)
})
test_that("collect() preserves type (
expect_equal(
collect(gen(for (i in 1:3) yield(i))),
as.list(1:3)
)
expect_equal(
wait_for(async_collect(async_generator(function() for (i in 1:3) yield(i))())),
as.list(1:3)
)
expect_equal(
collect(gen(for (i in 1:3) yield(list(i)))),
lapply(1:3, list)
)
expect_equal(
wait_for(async_collect(async_generator(function() for (i in 1:3) yield(list(i)))())),
lapply(1:3, list)
)
expect_equal(
collect(gen(for (i in 1:3) yield(mtcars[i, 1:3]))),
lapply(1:3, function(i) mtcars[i, 1:3])
)
expect_equal(
wait_for(async_collect(async_generator(function() for (i in 1:3) yield(mtcars[i, 1:3]))())),
lapply(1:3, function(i) mtcars[i, 1:3])
)
}) |
lsm_c_pladj <- function(landscape) {
landscape <- landscape_as_list(landscape)
result <- lapply(X = landscape,
FUN = lsm_c_pladj_calc)
layer <- rep(seq_along(result),
vapply(result, nrow, FUN.VALUE = integer(1)))
result <- do.call(rbind, result)
tibble::add_column(result, layer, .before = TRUE)
}
lsm_c_pladj_calc <- function(landscape) {
if (!inherits(x = landscape, what = "matrix")) {
landscape <- raster::as.matrix(landscape)
}
if (all(is.na(landscape))) {
return(tibble::tibble(level = "class",
class = as.integer(NA),
id = as.integer(NA),
metric = "pladj",
value = as.double(NA)))
}
landscape_padded <- pad_raster_internal(landscape, pad_raster_value = -999,
pad_raster_cells = 1, global = FALSE)
tb <- rcpp_get_coocurrence_matrix(landscape_padded,
directions = as.matrix(4))
pladj <- vapply(X = seq_len(nrow(tb)), FUN = function(x) {
like_adjacencies <- tb[x, x]
total_adjacencies <- sum(tb[x, ])
like_adjacencies / total_adjacencies * 100
}, FUN.VALUE = numeric(1))
pladj <- pladj[-1]
names <- row.names(tb)[-1]
return(tibble::tibble(level = "class",
class = as.integer(names),
id = as.integer(NA),
metric = "pladj",
value = as.double(pladj)))
} |
setConstructorS3("RccViolationException", function(...) {
extend(Exception(...), c("RccViolationException")
)
})
setMethodS3("as.character", "RccViolationException", function(x, ...) {
this <- x
paste("[", getWhen(this), "] ", class(this)[1L], ": ", getMessage(this), ", cf. ", getRccUrl(this), sep="")
})
setMethodS3("getRccUrl", "RccViolationException", function(this, ...) {
"https://aroma-project.org/developers/RCC/"
}, static=TRUE) |
library(testthat)
skip()
skip_on_cran()
skip_on_travis()
source("tensor_functions.R")
context("methods of train_dataset")
train_data_path = file.path('~/mnist_digits_png_full/training/')
test_data_path = file.path('~/mnist_digits_png_full/testing/')
train_dataset <<- torchvision$datasets$ImageFolder(
root = normalizePath(train_data_path),
transform = torchvision$transforms$ToTensor()
)
test_dataset <<- torchvision$datasets$ImageFolder(
root = normalizePath(test_data_path),
transform = torchvision$transforms$ToTensor()
)
context("Sanity of local folder for MNIST images")
test_that("folders exist", {
expect_true(dir.exists("~/"))
expect_true(dir.exists(normalizePath(train_data_path)))
expect_true(dir.exists(normalizePath(test_data_path)))
})
context("methods of train_dataset")
test_that("names of methods", {
expect_equal(names(train_dataset),
c("class_to_idx", "classes", "extensions", "extra_repr",
"imgs", "loader", "root", "samples", "target_transform",
"targets", "transform", "transforms"))
})
test_that("attributes of train_dataset", {
expect_true(all(py_list_attributes(train_dataset) %in% c(
"class_to_idx", "classes", "extensions", "extra_repr",
"imgs", "loader", "root", "samples", "target_transform",
"targets", "transform", "transforms",
"__add__", "__class__", "__delattr__",
"__dict__","__dir__", "__doc__",
"__eq__","__format__", "__ge__",
"__getattribute__", "__getitem__", "__gt__",
"__hash__", "__init__", "__init_subclass__",
"__le__", "__len__", "__lt__",
"__module__", "__ne__", "__new__",
"__reduce__", "__reduce_ex__", "__repr__",
"__setattr__", "__sizeof__", "__str__",
"__subclasshook__", "__weakref__", "_find_classes",
"_format_transform_repr", "_repr_indent"))
)
})
test_that("train_dataset has __getitem()__ method", {
if (rTorch:::is_linux()) expect_error(!train_dataset[0])
if (rTorch:::is_linux()) expect_error(!train_dataset[[0]])
if (rTorch:::is_windows()) expect_true(rTorch:::is_tensor(train_dataset[[2]][[1]]))
result <- train_dataset$`__getitem__`(0L)
expect_equal(length(result), 2)
})
test_that("train_dataset returns a list of 2 elements with py_get_item()", {
result <- py_get_item(train_dataset, 0L)
expect_equal(class(result), "list")
expect_equal(length(result), 2)
})
test_that("train_dataset is a tuple in Python", {
expect_equal(as.character(py_eval("type(r.train_dataset[0])")),
"<class 'tuple'>")
})
test_that("1st member of train_dataset list is a tensor: image", {
result <- py_get_item(train_dataset, 0L)[[1]]
expect_true(rTorch:::is_tensor(result))
})
test_that("2nd member of train_dataset list is an integer: label", {
result <- py_get_item(train_dataset, 0L)[[2]]
expect_true(is.integer(result))
})
test_that("train_dataset is a Python tuple object but an R list", {
result <- train_dataset$`__getitem__`(0L)
expect_equal(class(result), "list")
expect_equal(as.character(py_eval("type(r.train_dataset[0])")),
"<class 'tuple'>")
})
test_that("dimension of the tensor is 3D", {
result <- py_get_item(train_dataset, 0L)[[1]]
expect_equal(tensor_dim_(result), 3)
})
test_that("dimensions of the tensor is 3x28x28", {
result <- py_get_item(train_dataset, 0L)[[1]]
expect_equal(tensor_dim(result), c(3, 28, 28))
})
test_that("length of the train_dataset is 60000", {
result <- py_len(train_dataset)
expect_equal(result, 60000)
})
test_that("length of the test_dataset is 10000", {
result <- py_len(test_dataset)
expect_equal(result, 10000)
})
test_that("1st label of the train_dataset is 0", {
result <- py_get_item(train_dataset, 0L)[[2]]
expect_equal(result, 0)
result <- py_get_item(train_dataset, 59999L)[[2]]
})
test_that("59999th label of the train_dataset is 9", {
result <- py_get_item(train_dataset, 59999L)[[2]]
expect_equal(result, 9)
})
test_that("last label of the train_dataset is 9", {
result <- py_get_item(train_dataset, py_len(train_dataset)-1L)[[2]]
expect_equal(result, 9)
})
test_that("last label of the train_dataset using py_object_last()", {
result <- py_get_item(train_dataset, py_object_last(train_dataset))[[2]]
expect_equal(result, 9)
})
test_that("train and test datasets have __len__ method in Python", {
expect_true(py_has_length(train_dataset))
expect_true(py_has_length(test_dataset))
})
test_that("these objects do not have Python __len__", {
expect_true(py_has_length(py_get_item(train_dataset, 0L)[[1]]))
expect_false(py_has_length(py_get_item(train_dataset, 0L)[[2]]))
expect_false(py_has_length(py_get_item(train_dataset, 0L)))
result <- r_to_py(py_get_item(train_dataset, 0L)[[2]])
expect_equal(as.character(result$`__class__`), "<class 'int'>")
})
test_that("dataset label is of type integer", {
expect_true(is.integer(py_get_item(train_dataset, 0L)[[2]]))
result <- r_to_py(py_get_item(train_dataset, 0L)[[2]])
expect_equal(as.character(result$`__class__`), "<class 'int'>")
}) |
context("charlatan_locales")
test_that("charlatan_locales works", {
expect_is(charlatan_locales, "function")
expect_is(charlatan_locales(), "data.frame")
expect_gt(NROW(charlatan_locales()), 40)
})
test_that("available_locales works", {
expect_is(available_locales, "character")
expect_gt(length(available_locales), 10)
})
test_that("available_locales and charlatan_locales have equal length", {
expect_equal(length(available_locales), nrow(charlatan_locales()))
})
test_that("all provider locales are in available_locales", {
expect_true(all(AddressProvider$new()$allowed_locales() %in% available_locales))
expect_true(all(ColorProvider$new()$allowed_locales() %in% available_locales))
expect_true(all(CompanyProvider$new()$allowed_locales() %in% available_locales))
expect_true(all(FileProvider$new()$allowed_locales() %in% available_locales))
expect_true(all(InternetProvider$new()$allowed_locales() %in% available_locales))
expect_true(all(JobProvider$new()$allowed_locales() %in% available_locales))
expect_true(all(LoremProvider$new()$allowed_locales() %in% available_locales))
expect_true(all(PersonProvider$new()$allowed_locales() %in% available_locales))
expect_true(all(PhoneNumberProvider$new()$allowed_locales() %in% available_locales))
expect_true(all(UserAgentProvider$new()$allowed_locales() %in% available_locales))
}) |
wl1pca <- function(X, projDim = 1, center = TRUE, projections="l2", tolerance = 0.001, iterations = 200, beta = 0.99){
if (inherits(X, "data.frame")) {
X <- as.matrix(X)
}
if(center){
X <- apply(X,2,function(y) y - mean(y))
}
time.begin <- proc.time()
n <- dim(X)[1]
m <- dim(X)[2]
weights.prev <- matrix(2,n,1)
weights <- matrix(1,n,1)
obj.best <- .Machine$double.xmax
my.epsilon <- tolerance
my.epsilon.b <- 0.1
U.weights <- matrix(1,n,1)
num.iteration <- 1
continue.algorithm <- 1
my.beta <- beta^num.iteration
while(continue.algorithm){
if(num.iteration > 1){
my.PC.prev <- my.PC
}
weights.prev <- weights
X.weighted <- diag(as.vector(weights)) %*% X
my.PC <- as.matrix(prcomp(X.weighted)$rotation[,1:projDim])
Reconstuction.Errors <- X - X %*% my.PC %*% t(my.PC)
Reconstructions <- X %*% my.PC %*% t(my.PC)
obj.current <- sum(abs(Reconstuction.Errors))
if(obj.current < obj.best){
obj.best <- obj.current
PC.best <- my.PC
}
max.U <- 0
for(i in 1:n){
L2.norm.obs.i <- sum(Reconstuction.Errors[i,]^2)
L1.norm.obs.i <- sum(abs(Reconstuction.Errors[i,]))
if(L2.norm.obs.i > my.epsilon.b){
U.weights[i,1] <- L1.norm.obs.i/L2.norm.obs.i
max.U <- max(max.U,U.weights[i,1])
}else{
U.weights[i,1] <- -1
}
}
U.weights[U.weights[,1]==(-1),1]<-max.U
weights[U.weights[,1]<weights[,1]*(1-my.beta),1] <- weights[U.weights[,1]<weights[,1]*(1-my.beta),1]*(1-my.beta)
weights[U.weights[,1]>weights[,1]*(1+my.beta),1] <- weights[U.weights[,1]>weights[,1]*(1+my.beta),1]*(1+my.beta)
weights[(weights[,1]*(1-my.beta)<=U.weights[,1]) & (U.weights[,1]<=weights[,1]*(1+my.beta)),1] <- U.weights[(weights[,1]*(1-my.beta)<=U.weights[,1]) & (U.weights[,1]<=weights[,1]*(1+my.beta)),1]
my.beta <- beta^num.iteration
weight.diff <- weights.prev - weights
if((num.iteration >= iterations)||(sum(abs(weight.diff))<my.epsilon)){
continue.algorithm <- 0
}
num.iteration <- num.iteration + 1
if(num.iteration > 2){
if(norm(as.matrix(my.PC) - as.matrix(my.PC.prev),"F") < my.epsilon){
continue.algorithm = 0
}
}
cat(".", file=stderr())
}
cat("\n", file=stderr())
time.exe <- as.numeric((proc.time() - time.begin)[3])
Reconstuction.Errors <- X - X %*% PC.best %*% t(PC.best)
Reconstructions <- X %*% PC.best %*% t(PC.best)
Projected.Points <- X %*% PC.best
if (projections == "l1") {
myl1projection <- l1projection(X, as.matrix(PC.best))
Reconstructions <- myl1projection$projPoints
Projected.Points <- myl1projection$scores
}
solution <- list(loadings = PC.best, scores = Projected.Points, projPoints = Reconstructions, L1error = obj.best, nIter = num.iteration, ElapsedTime = time.exe)
class(solution) <- "wl1pca"
cat("
cat("L1 error = ", obj.best, "\n", file=stderr())
cat("Num iterations = ", num.iteration, "\n", file=stderr())
cat("Elapsed time = ", time.exe, "seconds \n\n", file=stderr())
solution
} |
table_names <- c("table_1", "table_2", "table_3")
quo <- quo(c(table_3_new = table_3, table_1_new = table_1))
test_that("tidyselecting tables works", {
expect_identical(
eval_select_table_indices(quo, table_names),
c(table_3_new = 3L, table_1_new = 1L)
)
expect_identical(
eval_select_table(quo, table_names),
set_names(c("table_3", "table_1"), c("table_3_new", "table_1_new"))
)
expect_identical(
eval_rename_table_all(quo, table_names),
set_names(table_names, c("table_1_new", "table_2", "table_3_new"))
)
})
test_that("output", {
expect_snapshot(error = TRUE, {
dm_for_filter() %>%
dm_select_tbl(tf_7)
dm_for_filter() %>%
dm_rename_tbl(tf_0 = tf_7)
})
}) |
env_returnSoluteGridJVoxels <-
function(xmlResultFile,soluteRequested)
{
return(as.numeric(xmlAttrs(xmlResultFile[[1]][[soluteRequested+1]])[5][[1]]))
} |
redlichpanalysis <- function(Ce, Qe){
x <- Ce
y <- Qe
data <- data.frame(x, y)
n<- nrow(na.omit(data))
print("NLS2 Analysis for Redlich Peterson Isotherm Model")
fit257 <- (Qe ~ (Arp*Ce)/(1+(Krp*(Ce^b))))
start <- data.frame(Arp = c(1, 100), Krp = c(1, 100), b = c(0, 1))
set.seed(511)
fit258 <- nls2(fit257, start = start, control = nls.control(maxiter = 50, warnOnly = TRUE), algorithm = "port")
print(summary(fit258))
error <- function(y){
pv <- (predict(fit258))
rmse<- (rmse(y,predict(fit258)))
mae <- (mae(y,predict(fit258)))
mse <- (mse(y,predict(fit258)))
rae <- (rae(y,predict(fit258)))
PAIC <- AIC(fit258)
PBIC <- BIC(fit258)
SE <-(sqrt(sum(predict(fit258)-x)^2)/(n-2))
colnames(y) <- rownames(y) <- colnames(y)
list("Predicted Values" = pv,
"Relative Mean Square Error" = rmse,
"Mean Absolute Error" = mae,
"Mean Squared Error" = mse,
"Relative Absolute Error" = rae,
"AIC" = PAIC,
"BIC" = PBIC,
"Standard Error Estimate" = SE)
}
e <- error(y)
print(e)
plot(x, y, main = "Redlich Peterson Isotherm", xlab = "Ce", ylab = "Qe")
lines(x, predict(fit258), col = "black")
rsqq <- lm(predict(fit258)~Qe)
print(summary(rsqq))
} |
test_that(".rba_args_opts works", {
.rba_args_opts_nested <- function(...) {
dir_name <- "test"
save_file <- TRUE
.rba_args_opts_nested2 <- function(...) {
.rba_args_opts(...)
}
.rba_args_opts_nested2(...)
}
expect_has_names(obj = .rba_args_opts_nested(what = "cons"),
expected = c("dir_name", "save_file"))
expect_has_names(obj = .rba_args_opts_nested(what = "cond"),
expected = c("dir_name", "save_file"))
}) |
test_that("AndresDiapositiva110", {
data(minimalCert)
expect_equal(round(uncertErrorCorr(reading = 12.4835, calibCert = minimalCert), 9),
0.000100249)
})
test_that("AndresDiapositiva111", {
data(minimalCert)
expect_equal(uncertReading(calibCert = minimalCert, reading = 12.4835)^2, 2.891329e-9)
})
test_that("AndresDiapositiva112", {
data(minimalCert)
expect_equal(round(uncertConvMass(reading = 12.4835, calibCert = minimalCert), 10),
0.0001137598)
}) |
NULL
dada_uniques <- function(seqs, abundances, priors, err, quals, match, mismatch, gap, use_kmers, kdist_cutoff, band_size, omegaA, omegaP, omegaC, detect_singletons, max_clust, min_fold, min_hamming, min_abund, use_quals, final_consensus, vectorized_alignment, homo_gap, multithread, verbose, SSE, gapless, greedy) {
.Call('_dada2_dada_uniques', PACKAGE = 'dada2', seqs, abundances, priors, err, quals, match, mismatch, gap, use_kmers, kdist_cutoff, band_size, omegaA, omegaP, omegaC, detect_singletons, max_clust, min_fold, min_hamming, min_abund, use_quals, final_consensus, vectorized_alignment, homo_gap, multithread, verbose, SSE, gapless, greedy)
}
C_is_bimera <- function(sq, pars, allow_one_off, min_one_off_par_dist, match, mismatch, gap_p, max_shift) {
.Call('_dada2_C_is_bimera', PACKAGE = 'dada2', sq, pars, allow_one_off, min_one_off_par_dist, match, mismatch, gap_p, max_shift)
}
C_table_bimera2 <- function(mat, seqs, min_fold, min_abund, allow_one_off, min_one_off_par_dist, match, mismatch, gap_p, max_shift) {
.Call('_dada2_C_table_bimera2', PACKAGE = 'dada2', mat, seqs, min_fold, min_abund, allow_one_off, min_one_off_par_dist, match, mismatch, gap_p, max_shift)
}
C_nwalign <- function(s1, s2, match, mismatch, gap_p, homo_gap_p, band, endsfree) {
.Call('_dada2_C_nwalign', PACKAGE = 'dada2', s1, s2, match, mismatch, gap_p, homo_gap_p, band, endsfree)
}
C_eval_pair <- function(s1, s2) {
.Call('_dada2_C_eval_pair', PACKAGE = 'dada2', s1, s2)
}
C_pair_consensus <- function(s1, s2, prefer, trim_overhang) {
.Call('_dada2_C_pair_consensus', PACKAGE = 'dada2', s1, s2, prefer, trim_overhang)
}
C_isACGT <- function(seqs) {
.Call('_dada2_C_isACGT', PACKAGE = 'dada2', seqs)
}
kmer_dist <- function(s1, s2, kmer_size) {
.Call('_dada2_kmer_dist', PACKAGE = 'dada2', s1, s2, kmer_size)
}
kord_dist <- function(s1, s2, kmer_size, SSE) {
.Call('_dada2_kord_dist', PACKAGE = 'dada2', s1, s2, kmer_size, SSE)
}
kmer_matches <- function(s1, s2, kmer_size) {
.Call('_dada2_kmer_matches', PACKAGE = 'dada2', s1, s2, kmer_size)
}
kdist_matches <- function(s1, s2, kmer_size) {
.Call('_dada2_kdist_matches', PACKAGE = 'dada2', s1, s2, kmer_size)
}
C_matchRef <- function(seqs, ref, word_size, non_overlapping) {
.Call('_dada2_C_matchRef', PACKAGE = 'dada2', seqs, ref, word_size, non_overlapping)
}
C_matrixEE <- function(inp) {
.Call('_dada2_C_matrixEE', PACKAGE = 'dada2', inp)
}
C_nwvec <- function(s1, s2, match, mismatch, gap_p, band, endsfree) {
.Call('_dada2_C_nwvec', PACKAGE = 'dada2', s1, s2, match, mismatch, gap_p, band, endsfree)
}
C_assign_taxonomy2 <- function(seqs, rcs, refs, ref_to_genus, genusmat, try_rc, verbose) {
.Call('_dada2_C_assign_taxonomy2', PACKAGE = 'dada2', seqs, rcs, refs, ref_to_genus, genusmat, try_rc, verbose)
}
methods::setLoadAction(function(ns) {
.Call('_dada2_RcppExport_registerCCallable', PACKAGE = 'dada2')
}) |
MantelModTest <- function (cor.hypothesis, cor.matrix, ...) UseMethod("MantelModTest")
MantelModTest.default <- function (cor.hypothesis, cor.matrix,
permutations = 1000, MHI = FALSE, ...,
landmark.dim = NULL, withinLandmark = FALSE) {
if(!any(cor.hypothesis == 0 | cor.hypothesis == 1)) stop("modularity hypothesis matrix should be binary")
mantel.output <- MantelCor(cor.matrix, cor.hypothesis, permutations = permutations,
MHI, landmark.dim = landmark.dim, withinLandmark = FALSE, mod = TRUE, ...)
output = c(mantel.output,
CalcAVG(cor.hypothesis, cor.matrix, MHI, landmark.dim))
return (output)
}
MantelModTest.list <- function (cor.hypothesis, cor.matrix,
permutations = 1000, MHI = FALSE,
landmark.dim = NULL, withinLandmark = FALSE,
...,
parallel = FALSE){
output <- SingleComparisonMap(cor.hypothesis, cor.matrix,
function(x, y) MantelModTest(x, y,
permutations, MHI,
landmark.dim = landmark.dim,
withinLandmark = withinLandmark),
parallel = parallel)
return(output)
} |
erpplot <-
function (dta, design=NULL,effect=1, interval=c("none","pointwise","simultaneous"),
alpha=0.05, frames = NULL, ylim = NULL, nbs=NULL, ...) {
interval = match.arg(interval,choices=c("none","pointwise","simultaneous"))
erpdta = as.matrix(dta)
n = nrow(erpdta)
T = ncol(erpdta)
if (typeof(erpdta) != "double")
stop("ERPs should be of type double")
if (!is.null(frames))
if (length(frames) != ncol(erpdta))
stop(paste("frames should be either null or of length",
ncol(erpdta)))
if (!is.null(frames)) {
if (any(frames != sort(frames)))
stop("frames should be an ascending sequence of integers")
tframes = frames
}
if (is.null(frames))
tframes = 1:T
if (is.null(design)) {
if (is.null(ylim))
limy = 1.05 * diag(apply(apply(erpdta, 2, range), 1,range))
if (!is.null(ylim))
limy = ylim
matplot(tframes, t(erpdta), type = "l", ylim = limy, ...)
}
if (!is.null(design)) {
erpfit = erptest(erpdta,design,nbs=nbs)
signal = as.vector(erpfit$signal[effect-1,])
sdsignal = as.vector(erpfit$sdsignal[effect-1,])
if (interval=="none") {
lwr = signal
upr = signal
if (is.null(ylim))
limy = 1.05*range(c(lwr,upr))
if (!is.null(ylim))
limy = ylim
plot(tframes,signal,type="n",ylim=limy,...)
lines(tframes,signal,type="l",col="black",lwd=2,lty=1)
abline(h=0,lty=3,lwd=2)
}
if (interval=="pointwise") {
lwr = signal-qnorm(1-alpha/2)*sdsignal
upr = signal+qnorm(1-alpha/2)*sdsignal
if (is.null(ylim))
limy = 1.05*range(c(lwr,upr))
if (!is.null(ylim))
limy = ylim
plot(tframes,signal,type="n",ylim=limy,...)
polygon(c(tframes,rev(tframes)),c(lwr,rev(upr)),col=gray.colors(24)[24],border="grey")
lines(tframes,signal,type="l",col="black",lwd=2,lty=1)
abline(h=0,lty=3,lwd=2)
}
if (interval=="simultaneous") {
lwr = signal-qnorm(1-alpha/2)*sdsignal
upr = signal+qnorm(1-alpha/2)*sdsignal
lwrs = signal-qnorm(1-alpha/(2*T))*sdsignal
uprs = signal+qnorm(1-alpha/(2*T))*sdsignal
if (is.null(ylim))
limy = 1.05*range(c(lwrs,uprs))
if (!is.null(ylim))
limy = ylim
plot(tframes,signal,type="n",ylim=limy,...)
polygon(c(tframes,rev(tframes)),c(lwrs,rev(uprs)),col=gray.colors(24)[24],border="grey")
polygon(c(tframes,rev(tframes)),c(lwr,rev(upr)),col=gray.colors(24)[12],border="grey")
lines(tframes,signal,type="l",col="black",lwd=2,lty=1)
abline(h=0,lty=3,lwd=2)
}
}
} |
plot_profiles <- function(x, variables = NULL, ci = .95, sd = TRUE, add_line = TRUE, rawdata = TRUE, bw = FALSE, alpha_range = c(0, .1), ...){
deprecated_arguments(
c("to_center" = "plot_profiles simply displays the data as analyzed. Center data prior to analysis.",
"to_scale" = "plot_profiles simply displays the data as analyzed. Scale data prior to analysis.",
"plot_what" = "tidyLPA objects now contain all information required for plotting.",
"plot_error_bars" = "Use the 'ci' argument to specify the desired confidence intervall, or set to NULL to omit error bars.",
"plot_rawdata" = "Renamed to rawdata."))
UseMethod("plot_profiles", x)
}
plot_profiles.default <- function(x, variables = NULL, ci = .95, sd = TRUE, add_line = FALSE, rawdata = TRUE, bw = FALSE, alpha_range = c(0, .1), ...){
df_plot <- droplevels(x[["df_plot"]])
if(rawdata){
df_raw <- droplevels(x[["df_raw"]])
if(!all(unique(df_plot$Variable) %in% unique(df_raw$Variable))){
stop("Could not match raw data to model estimates.")
}
df_raw$Variable <- as.numeric(df_raw$Variable)
}
level_labels <- levels(df_plot$Variable)
df_plot$Variable <- as.numeric(df_plot$Variable)
if (bw) {
classplot <-
ggplot(NULL,
aes_string(
x = "Variable",
y = "Value",
group = "Class",
linetype = "Class",
shape = "Class"
))
} else {
classplot <-
ggplot(
NULL,
aes_string(
x = "Variable",
y = "Value",
group = "Class",
linetype = "Class",
shape = "Class",
colour = "Class"
)
) + scale_colour_manual(values = get_palette(max(df_plot$Classes)))
}
if (rawdata) {
classplot <- classplot +
geom_jitter(
data = df_raw,
width = .2,
aes_string(
x = "Variable",
y = "Value",
shape = "Class",
alpha = "Probability"
)
) +
scale_alpha_continuous(range = alpha_range, guide = FALSE)
}
classplot <- classplot + geom_point(data = df_plot) +
scale_x_continuous(breaks = 1:length(level_labels),
labels = level_labels) +
theme_bw() +
theme(panel.grid.minor.x = element_blank())
if(add_line) classplot <- classplot + geom_line(data = df_plot)
if (!is.null(ci)) {
ci <- qnorm(.5 * (1 - ci))
df_plot$error_min <- df_plot$Value + ci*df_plot$se
df_plot$error_max <- df_plot$Value - ci*df_plot$se
classplot <-
classplot + geom_errorbar(data = df_plot,
aes_string(ymin = "error_min",
ymax = "error_max"),
width = .4)
}
if(sd){
df_plot$sd_xmin <- df_plot$Variable-.2
df_plot$sd_xmax <- df_plot$Variable+.2
df_plot$sd_ymin <- df_plot$Value - sqrt(df_plot$Value.Variances)
df_plot$sd_ymax <- df_plot$Value + sqrt(df_plot$Value.Variances)
if(bw){
classplot <-
classplot + geom_rect(
data = df_plot,
aes_string(
xmin = "sd_xmin",
xmax = "sd_xmax",
ymin = "sd_ymin",
ymax = "sd_ymax",
linetype = "Class"
),
colour = "black",
fill=ggplot2::alpha("grey", 0),
inherit.aes=FALSE
)
} else {
classplot <-
classplot + geom_rect(
data = df_plot,
aes_string(
xmin = "sd_xmin",
xmax = "sd_xmax",
ymin = "sd_ymin",
ymax = "sd_ymax",
colour = "Class"
),
fill=ggplot2::alpha("grey", 0),
inherit.aes=FALSE
)
}
}
if (length(unique(df_plot$Classes)) > 1) {
if(length(unique(df_plot$Model)) > 1){
classplot <- classplot + facet_grid(Model ~ Classes, labeller = label_both)
} else {
classplot <- classplot + facet_wrap(~ Classes, labeller = label_both)
}
} else {
if(length(unique(df_plot$Model)) > 1){
classplot <- classplot + facet_wrap(~ Model, labeller = label_both)
}
}
suppressWarnings(print(classplot))
return(invisible(classplot))
}
plot_profiles.tidyLPA <- function(x, variables = NULL, ci = .95, sd = TRUE, add_line = FALSE, rawdata = TRUE, bw = FALSE, alpha_range = c(0, .1), ...){
Args <- as.list(match.call()[-1])
df_plot <- get_estimates(x)
names(df_plot)[match(c("Estimate", "Parameter"), names(df_plot))] <- c("Value", "Variable")
df_plot$Class <- ordered(df_plot$Class)
if(!"Classes" %in% names(df_plot)){
df_plot$Classes <- length(unique(df_plot$Class))
}
df_plot <- df_plot[grepl("(^Means$|^Variances$)", df_plot$Category),
-match(c("p"), names(df_plot))]
df_plot$Variable <- ordered(df_plot$Variable, levels = unique(df_plot$Variable))
if (!is.null(variables)) {
df_plot <- df_plot[tolower(df_plot$Variable) %in% tolower(variables), ]
}
df_plot$Variable <- droplevels(df_plot$Variable)
variables <- levels(df_plot$Variable)
df_plot$idvar <- paste0(df_plot$Model, df_plot$Classes, df_plot$Class, df_plot$Variable)
df_plot <- reshape(data.frame(df_plot), idvar = "idvar", timevar = "Category", v.names = c("Value", "se"), direction = "wide")
df_plot <- df_plot[, -match("idvar", names(df_plot))]
names(df_plot) <- gsub("\\.Means", "", names(df_plot))
if (rawdata) {
df_raw <- .get_long_data(x)
df_raw <- df_raw[, c("model_number", "classes_number", variables, "Class", "Class_prob", "Probability", "id")]
df_raw$Class <- ordered(df_raw$Class_prob, levels = levels(df_plot$Class))
variable_names <- paste("Value", names(df_raw)[-c(1,2, ncol(df_raw)-c(0:3))], sep = "...")
names(df_raw)[-c(1,2, ncol(df_raw)-c(0:3))] <- variable_names
df_raw <- reshape(
df_raw,
varying = c(Variable = variable_names),
idvar = "new_id",
direction = "long",
timevar = "Variable",
sep = "..."
)
if(any(c("Class_prob", "id", "new_id") %in% names(df_raw))){
df_raw <- df_raw[, -which(names(df_raw) %in% c("Class_prob", "id", "new_id"))]
}
df_raw$Variable <- ordered(df_raw$Variable,
levels = levels(df_plot$Variable))
names(df_raw)[c(1,2)] <- c("Model", "Classes")
} else {
df_raw <- NULL
}
Args[["x"]] <- list(df_plot = df_plot, df_raw = df_raw)
do.call(plot_profiles, Args)
}
plot_profiles.tidyProfile <- function(x, variables = NULL, ci = .95, sd = TRUE, add_line = TRUE, rawdata = TRUE, bw = FALSE, alpha_range = c(0, .1), ...){
Args <- as.list(match.call()[-1])
df_plot <- get_estimates(x)
df_plot$Value <- df_plot$Estimate
df_plot$Class <- ordered(df_plot$Class)
df_plot$Variable <- ordered(df_plot$Parameter, levels = unique(df_plot$Parameter))
df_plot <- df_plot[grepl("(^Means$|^Variances$)", df_plot$Category),
-match(c("p", "Parameter", "Estimate"), names(df_plot))]
if (!is.null(variables)) {
df_plot <- df_plot[tolower(df_plot$Variable) %in% tolower(variables), ]
}
df_plot$idvar <- paste0(df_plot$Model, df_plot$Classes, df_plot$Class, df_plot$Variable)
df_plot <- reshape(data.frame(df_plot), idvar = "idvar", timevar = "Category", v.names = c("Value", "se"), direction = "wide")
df_plot <- df_plot[, -match("idvar", names(df_plot))]
names(df_plot) <- gsub("\\.Means", "", names(df_plot))
if (rawdata) {
df_raw <- .get_long_data(x)
df_raw <- df_raw[, c("model_number", "classes_number", attr(x$dff, "selected"), "Class", "Class_prob", "Probability", "id")]
df_raw$Class <- ordered(df_raw$Class_prob, levels = levels(df_plot$Class))
variable_names <- paste("Value", names(df_raw)[-c(1,2, ncol(df_raw)-c(0:3))], sep = "...")
names(df_raw)[-c(1,2, ncol(df_raw)-c(0:3))] <- variable_names
df_raw <- reshape(
df_raw,
varying = c(Variable = variable_names),
idvar = "new_id",
direction = "long",
timevar = "Variable",
sep = "..."
)
if(any(c("Class_prob", "id", "new_id") %in% names(df_raw))){
df_raw <- df_raw[, -which(names(df_raw) %in% c("Class_prob", "id", "new_id"))]
}
df_raw$Variable <- ordered(df_raw$Variable,
levels = levels(df_plot$Variable))
names(df_raw)[c(1,2)] <- c("Model", "Classes")
} else {
df_raw <- NULL
}
Args[["x"]] <- list(df_plot = df_plot, df_raw = df_raw)
do.call(plot_profiles, Args)
} |
stresc <- function(strings)
{
fromchar <- s2c("\\{}$^_%
tochar <- c("$\\backslash$", "\\{", "\\}", "\\$", "\\^{}", "\\_", "\\%", "\\
"\\lbrack{}", "\\rbrack{}","\\textbar{}")
f <- function(string){
c2s( sapply(s2c(string), function(x) ifelse(x %in% fromchar, tochar[which(x == fromchar)], x)))
}
sapply(strings, f, USE.NAMES = FALSE)
} |
CNOT3_21 <- function(a){
cnot3_21=TensorProd(diag(2), CNOT2_10(diag(4)))
result = cnot3_21 %*% a
result
} |
source("tinytestSettings.R")
using(ttdo)
library(OmicNavigator)
testStudyName <- "ABC"
testStudyObj <- OmicNavigator:::testStudy(name = testStudyName)
testStudyObj <- addPlots(testStudyObj, OmicNavigator:::testPlots())
minimalStudyObj <- OmicNavigator:::testStudyMinimal()
minimalStudyName <- minimalStudyObj[["name"]]
tmplib <- tempfile()
dir.create(tmplib)
tmplibSpace <- file.path(tempdir(), "a space")
dir.create(tmplibSpace)
tmplibQuote <- file.path(tempdir(), "project's results")
dir.create(tmplibQuote)
observed <- exportStudy(testStudyObj, type = "package", path = tmplib)
expected <- file.path(tmplib, OmicNavigator:::studyToPkg(testStudyName))
expect_identical_xl(observed, expected, info = "Export as package directory")
expect_true_xl(dir.exists(expected))
observed <- exportStudy(testStudyObj, type = "package", path = tmplibSpace)
expected <- file.path(tmplibSpace, OmicNavigator:::studyToPkg(testStudyName))
expect_identical_xl(observed, expected,
info = "Export as package directory to path with a space")
expect_true_xl(dir.exists(expected))
observed <- exportStudy(testStudyObj, type = "package", path = tmplibQuote)
expected <- file.path(tmplibQuote, OmicNavigator:::studyToPkg(testStudyName))
expect_identical_xl(observed, expected,
info = "Export as package directory to path with a quote")
expect_true_xl(dir.exists(expected))
observed <- exportStudy(minimalStudyObj, type = "package", path = tmplib)
expected <- file.path(tmplib, OmicNavigator:::studyToPkg(minimalStudyName))
expect_identical_xl(observed, expected,
info = "Export minimal study as package directory")
expect_true_xl(dir.exists(expected))
if (at_home()) {
tarball <- exportStudy(testStudyObj, type = "tarball", path = tmplib)
expect_true_xl(file.exists(tarball))
expect_true_xl(startsWith(tarball, tmplib))
directoryname <- file.path(tmplib, OmicNavigator:::studyToPkg(testStudyName))
expect_false_xl(dir.exists(directoryname))
modtimeOriginal <- file.mtime(tarball)
tarball <- exportStudy(testStudyObj, type = "tarball", path = tmplib)
modtimeReexport <- file.mtime(tarball)
expect_true_xl(
modtimeReexport > modtimeOriginal,
info = "Confirm tarball is overwritten when re-exported"
)
tarball <- exportStudy(testStudyObj, type = "tarball", path = tmplibSpace)
expect_true_xl(file.exists(tarball))
expect_true_xl(startsWith(tarball, tmplibSpace))
directoryname <- file.path(tmplibSpace, OmicNavigator:::studyToPkg(testStudyName))
expect_false_xl(dir.exists(directoryname))
tarball <- exportStudy(testStudyObj, type = "tarball", path = tmplibQuote)
expect_true_xl(file.exists(tarball))
expect_true_xl(startsWith(tarball, tmplibQuote))
directoryname <- file.path(tmplibQuote, OmicNavigator:::studyToPkg(testStudyName))
expect_false_xl(dir.exists(directoryname))
tarball <- exportStudy(minimalStudyObj, type = "tarball", path = tmplib)
expect_true_xl(file.exists(tarball))
expect_true_xl(startsWith(tarball, tmplib))
directoryname <- file.path(tmplib, OmicNavigator:::studyToPkg(minimalStudyName))
expect_false_xl(dir.exists(directoryname))
pkgDir <- tempfile(pattern = OmicNavigator:::getPrefix())
e <- new.env(parent = emptyenv())
e$x <- function() 1 + 1
suppressMessages(
utils::package.skeleton(
name = basename(pkgDir),
path = tempdir(),
environment = e
)
)
expect_warning_xl(
OmicNavigator:::buildPkg(pkgDir),
"ERROR: package installation failed",
info = "Return warning message for failed package build"
)
file.remove(file.path(pkgDir, "man", "x.Rd"))
expect_silent_xl(
tarball <- OmicNavigator:::buildPkg(pkgDir)
)
unlink(pkgDir, recursive = TRUE, force = TRUE)
file.remove(tarball)
}
suppressMessages(installStudy(testStudyObj, library = tmplib))
studyMetadata <- listStudies(libraries = tmplib)
expect_identical_xl(
studyMetadata[[1]][["name"]],
testStudyObj[["name"]]
)
expect_identical_xl(
studyMetadata[[1]][["package"]][["Description"]],
sprintf("The OmicNavigator data package for the study \"%s\"",
testStudyObj[["description"]]),
info = "Default package description when description==name"
)
expect_identical_xl(
studyMetadata[[1]][["package"]][["Version"]],
"0.0.0.9000",
info = "Default package version used when version=NULL"
)
expect_identical_xl(
studyMetadata[[1]][["package"]][["Maintainer"]],
"Unknown <unknown@unknown>",
info = "Default package maintainer"
)
expect_identical_xl(
studyMetadata[[1]][["package"]][["department"]],
"immunology",
info = "Custom study metadata passed via studyMeta"
)
expect_identical_xl(
studyMetadata[[1]][["package"]][["organism"]],
"Mus musculus",
info = "Custom study metadata passed via studyMeta"
)
updatedStudyObj <- testStudyObj
updatedStudyObj[["description"]] <- "A custom description"
updatedStudyObj[["version"]] <- "1.0.0"
updatedStudyObj[["maintainer"]] <- "My Name"
updatedStudyObj[["maintainerEmail"]] <- "[email protected]"
suppressMessages(installStudy(updatedStudyObj, library = tmplib))
studyMetadata <- listStudies(libraries = tmplib)
expect_identical_xl(
studyMetadata[[1]][["name"]],
updatedStudyObj[["name"]]
)
expect_identical_xl(
studyMetadata[[1]][["package"]][["Description"]],
updatedStudyObj[["description"]]
)
expect_identical_xl(
studyMetadata[[1]][["package"]][["Version"]],
updatedStudyObj[["version"]]
)
expect_identical_xl(
studyMetadata[[1]][["package"]][["Maintainer"]],
sprintf("%s <%s>", updatedStudyObj[["maintainer"]],
updatedStudyObj[["maintainerEmail"]])
)
studyToRemoveName <- "remove"
studyToRemove <- OmicNavigator:::testStudy(name = studyToRemoveName)
suppressMessages(installStudy(studyToRemove, library = tmplib))
studyToRemoveDir <- file.path(tmplib, OmicNavigator:::studyToPkg(studyToRemoveName))
expect_true_xl(dir.exists(studyToRemoveDir))
expect_message_xl(
removeStudy(studyToRemove, library = tmplib),
studyToRemoveName
)
expect_false_xl(dir.exists(studyToRemoveDir))
expect_error_xl(
removeStudy(removeStudyName, library = "xyz"),
"This directory does not exist: xyz"
)
expect_error_xl(
removeStudy(1),
"Argument `study` must be a string or an onStudy object"
)
expect_error_xl(
removeStudy("nonExistent"),
"Couldn't find"
)
unlink(c(tmplib, tmplibSpace, tmplibQuote), recursive = TRUE, force = TRUE) |
"fusion_cars" |
.zpolyloglikelihood <- function(alpha, betaNew, values, freq, nSize){
poly <- copula::polylog(z = exp(betaNew), s = alpha, method = 'sum', n.sum = 1000)
alpha*sum(freq*log(values)) +nSize*log(poly) - betaNew*sum(freq*values)
}
.zPoly <- function(params, values, freq, nSize){
beta <- min(0, params[2])
alpha <- params[1]
.zpolyloglikelihood(alpha, beta, values, freq, nSize)
}
zipfPolylogFit <- function(data, init_alpha, init_beta, level = 0.95, ...){
Call <- match.call()
if(!is.numeric(init_alpha) || !is.numeric(init_beta)){
stop('Wrong intial values for the parameters.')
}
tryCatch(
{
estResults <- .paramEstimationBase(data, c(init_alpha, init_beta), .zPoly, ...)
estAlpha <- as.numeric(estResults$results$par[1])
estBeta <- exp(as.numeric(estResults$results$par[2]))
paramSD <- sqrt(diag(solve(estResults$results$hessian)))
paramsCI <- .getConfidenceIntervals(paramSD, estAlpha, estBeta, level)
structure(class = "zipfPolyR", list(alphaHat = estAlpha,
betaHat = estBeta,
alphaSD = paramSD[1],
betaSD = paramSD[2],
alphaCI = c(paramsCI[1,1],paramsCI[1,2]),
betaCI = c(paramsCI[2,1],paramsCI[2,2]),
logLikelihood = -estResults$results$value,
hessian = estResults$results$hessian,
call = Call))
},
error=function(cond) {
print(cond)
return(NA)
})
}
residuals.zipfPolyR <- function(object, ...){
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
residual.values <- dataMatrix[, 2] - fitted(object)
return(residual.values)
}
fitted.zipfPolyR <- function(object, ...) {
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
N <- sum(dataMatrix[, 2])
fitted.values <- N*sapply(dataMatrix[,1], dzipfpolylog, alpha = object[['alphaHat']],
beta = object[['betaHat']])
return(fitted.values)
}
coef.zipfPolyR <- function(object, ...){
estimation <- matrix(nrow = 2, ncol = 4)
estimation[1, ] <- c(object[['alphaHat']], object[['alphaSD']], object[['alphaCI']][1], object[['alphaCI']][2])
estimation[2, ] <- c(object[['betaHat']], object[['betaSD']], object[['betaCI']][1], object[['betaCI']][2])
colnames(estimation) <- c("MLE", "Std. Dev.", paste0("Inf. ", "95% CI"),
paste0("Sup. ", "95% CI"))
rownames(estimation) <- c("alpha", "beta")
estimation
}
plot.zipfPolyR <- function(x, ...){
dataMatrix <- get(as.character(x[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
graphics::plot(dataMatrix[,1], dataMatrix[,2], log="xy",
xlab="Observation", ylab="Frequency",
main="Fitting ZipfPolylog Distribution", ...)
graphics::lines(dataMatrix[,1], fitted(x), col="blue")
graphics::legend("topright", legend = c('Observations', 'ZipfPolylog Distribution'),
col=c('black', 'blue'), pch=c(21,NA),
lty=c(NA, 1), lwd=c(NA, 2))
}
print.zipfPolyR <- function(x, ...){
cat('Call:\n')
print(x[['call']])
cat('\n')
cat('Initial Values:\n')
cat(sprintf('Alpha: %s\n', format(eval(x[['call']]$init_alpha), digits = 3)))
cat(sprintf('Beta: %s\n', format(eval(x[['call']]$init_beta), digits = 3)))
cat('\n')
cat('Coefficients:\n')
print(coef(x))
cat('\n')
cat('Metrics:\n')
cat(sprintf('Log-likelihood: %s\n', logLik(x)))
cat(sprintf('AIC: %s\n', AIC(x)))
cat(sprintf('BIC: %s\n', BIC(x)))
}
summary.zipfPolyR <- function(object, ...){
print(object)
cat('\n')
cat('Fitted values:\n')
print(fitted(object))
}
logLik.zipfPolyR <- function(object, ...){
if(!is.na(object[['logLikelihood']]) || !is.null(object[['logLikelihood']])){
return(object[['logLikelihood']])
}
return(NA)
}
AIC.zipfPolyR <- function(object, ...){
aic <- .get_AIC(object[['logLikelihood']], 2)
return(aic)
}
BIC.zipfPolyR <- function(object, ...){
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
bic <- .get_BIC(object[['logLikelihood']], 2, sum(dataMatrix[, 2]))
return(bic)
} |
theme_tree <- function(bgcolor="white", ...) {
list(xlab(NULL),
ylab(NULL),
theme_tree2_internal() +
theme(panel.background=element_rect(fill=bgcolor, colour=bgcolor),
axis.line.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
...)
)
}
theme_dendrogram <- function(bgcolor = "white", fgcolor = "black", ...) {
theme_tree2(bgcolor = bgcolor,
axis.line.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.line.y = element_line(color=fgcolor),
axis.text.y = element_text(color=fgcolor),
axis.ticks.y = element_line(color=fgcolor),
...)
}
theme_tree2 <- function(bgcolor="white", fgcolor="black", ...) {
list(xlab(NULL),
ylab(NULL),
theme_tree2_internal(bgcolor, fgcolor, ...)
)
}
theme_tree2_internal <- function(bgcolor="white", fgcolor="black",
legend.position="right",
panel.grid.minor=element_blank(),
panel.grid.major=element_blank(),
panel.border=element_blank(),
axis.line.y=element_blank(),
axis.ticks.y=element_blank(),
axis.text.y=element_blank(),...) {
theme_bw() +
theme(legend.position=legend.position,
panel.grid.minor=panel.grid.minor,
panel.grid.major=panel.grid.major,
panel.background=element_rect(fill=bgcolor, colour=bgcolor),
panel.border=panel.border,
axis.line=element_line(color=fgcolor),
axis.line.y=axis.line.y,
axis.ticks.y=axis.ticks.y,
axis.text.y=axis.text.y,
...)
}
theme_inset <- function(legend.position = "none", ...) {
list(xlab(NULL),
ylab(NULL),
theme_tree(legend.position = legend.position, ...),
ggfun::theme_transparent()
)
} |
library(checkargs)
context("isStrictlyPositiveIntegerOrNaOrInfScalarOrNull")
test_that("isStrictlyPositiveIntegerOrNaOrInfScalarOrNull works for all arguments", {
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(0, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull("", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull("X", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyPositiveIntegerOrNaOrInfScalarOrNull(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
}) |
context("bRacatus")
input_data <- giftRegions ("Babiana tubulosa")
test_that("Expected data structure",{
expect_equal(class(input_data),"list")
expect_true("Presence" %in% names(input_data))
expect_true("Native" %in% names(input_data))
expect_true("Alien" %in% names(input_data))
}) |
NULL
if (getRversion() >= "2.15.1") utils::globalVariables(c("."))
utils::globalVariables(c(
"degreeC", "g", "hPa", "J", "K", "kg", "kJ", "kPa",
"m", "mol", "Pa", "PPFD", "s", "umol", "W"
)) |
library("MVA")
set.seed(280875)
library("lattice")
lattice.options(default.theme =
function()
standard.theme("pdf", color = FALSE))
if (file.exists("deparse.R")) {
if (!file.exists("figs")) dir.create("figs")
source("deparse.R")
options(prompt = "R> ", continue = "+ ", width = 64,
digits = 4, show.signif.stars = FALSE, useFancyQuotes = FALSE)
options(SweaveHooks = list(onefig = function() {par(mfrow = c(1,1))},
twofig = function() {par(mfrow = c(1,2))},
figtwo = function() {par(mfrow = c(2,1))},
threefig = function() {par(mfrow = c(1,3))},
figthree = function() {par(mfrow = c(3,1))},
fourfig = function() {par(mfrow = c(2,2))},
sixfig = function() {par(mfrow = c(3,2))},
nomar = function() par("mai" = c(0, 0, 0, 0))))
} |
download_d1_data <- function(data_url, path, dir_name = NULL) {
stopifnot(is.character(data_url), length(data_url) == 1, nchar(data_url) > 0)
stopifnot(is.character(path), length(path) == 1, nchar(path) > 0, dir.exists(path))
data_url <- utils::URLdecode(data_url)
data_versions <- check_version(data_url, formatType = "data")
if (nrow(data_versions) == 1) {
data_id <- data_versions$identifier
} else if (nrow(data_versions) > 1) {
data_versions$dateUploaded <- lubridate::ymd_hms(data_versions$dateUploaded)
data_id <- data_versions$identifier[data_versions$dateUploaded == max(data_versions$dateUploaded)]
} else {
stop("The DataONE ID could not be found for ", data_url)
}
data_nodes <- dataone::resolve(dataone::CNode("PROD"), data_id)
d1c <- dataone::D1Client("PROD", data_nodes$data$nodeIdentifier[[1]])
cn <- dataone::CNode()
meta_id <- dataone::query(
cn,
list(q = sprintf('documents:"%s" AND formatType:"METADATA" AND -obsoletedBy:*', data_id),
fl = "identifier")) %>%
unlist()
if (length(meta_id) == 0) {
meta_id <- dataone::query(
cn,
list(q = sprintf('documents:"%s" AND formatType:"METADATA"', data_id),
fl = "identifier")) %>%
unlist()
}
if (length(meta_id) == 0) {
warning("no metadata records found", immediate. = T)
meta_id <- NULL
} else if (length(meta_id) > 1) {
warning("multiple metadata records found:\n",
paste(meta_id, collapse = "\n"),
"\nThe first record was used", immediate. = T)
meta_id <- meta_id[1]
}
if (!is.null(meta_id)) {
message("\nDownloading metadata ", meta_id, " ...")
meta_obj <- dataone::getObject(d1c@mn, meta_id)
message("Download metadata complete")
metadata_nodes <- dataone::resolve(cn, meta_id)
eml <- tryCatch({emld::as_emld(meta_obj, from = "xml")},
error = function(e) {NULL})
entities <- c("dataTable", "spatialRaster", "spatialVector", "storedProcedure", "view", "otherEntity")
entities <- entities[entities %in% names(eml$dataset)]
entity_objs <- purrr::map(entities, ~EML::eml_get(eml, .x)) %>%
purrr::map_if(~!is.null(.x$entityName), list) %>%
unlist(recursive = FALSE)
entity_data <- entity_objs %>%
purrr::keep(~any(grepl(data_id,
purrr::map_chr(.x$physical$distribution$online$url, utils::URLdecode))))
if (length(entity_data) == 0) {
warning("No data metadata could be found for ", data_url, immediate. = T)
} else {
if (length(entity_data) > 1) {
warning("Multiple data metadata records found:\n",
data_url,
"\nThe first record was used", immediate. = T)
}
entity_data <- entity_data[[1]]
}
if (!is.null(entity_data$attributeList)){
attributeList <- suppressWarnings(EML::get_attributes(entity_data$attributeList, eml))
}
meta_tabular <- tabularize_eml(eml) %>% tidyr::pivot_wider(names_from = name, values_from = value)
entity_meta <- suppressWarnings(list(
Metadata_ID = meta_id[[1]],
Metadata_URL = metadata_nodes$data$url[1],
Metadata_EML_Version = stringr::str_extract(meta_tabular$eml.version, "\\d\\.\\d\\.\\d"),
File_Description = entity_data$entityDescription,
File_Label = entity_data$entityLabel,
Dataset_URL = paste0("https://search.dataone.org/
Dataset_Title = meta_tabular$title,
Dataset_StartDate = meta_tabular$temporalCoverage.beginDate,
Dataset_EndDate = meta_tabular$temporalCoverage.endDate,
Dataset_Location = meta_tabular$geographicCoverage.geographicDescription,
Dataset_WestBoundingCoordinate = meta_tabular$geographicCoverage.westBoundingCoordinate,
Dataset_EastBoundingCoordinate = meta_tabular$geographicCoverage.eastBoundingCoordinate,
Dataset_NorthBoundingCoordinate = meta_tabular$geographicCoverage.northBoundingCoordinate,
Dataset_SouthBoundingCoordinate = meta_tabular$geographicCoverage.southBoundingCoordinate,
Dataset_Taxonomy = meta_tabular$taxonomicCoverage,
Dataset_Abstract = meta_tabular$abstract,
Dataset_Methods = meta_tabular$methods,
Dataset_People = meta_tabular$people
))
}
message("\nDownloading data ", data_id, " ...")
data_sys <- suppressMessages(dataone::getSystemMetadata(d1c@cn, data_id))
data_name <- data_sys@fileName %|||% ifelse(exists("entity_data"), entity_data$physical$objectName %|||% entity_data$entityName, NA) %|||% data_id
data_name <- gsub("[^a-zA-Z0-9. -]+", "_", data_name)
data_extension <- gsub("(.*\\.)([^.]*$)", "\\2", data_name)
data_name <- gsub("\\.[^.]*$", "", data_name)
meta_name <- gsub("[^a-zA-Z0-9. -]+", "_", meta_id)
old_dir_path <- file.path(path, paste0(meta_name, "__", data_name, "__", data_extension))
log_path <- file.path(path, "metajam.log")
old_dir_path_log <- ""
if(file.exists(log_path)){
old_log <- suppressMessages(readr::read_csv(log_path))
if(data_id %in% old_log$Data_ID){
old_dir_path_log <- old_log %>%
dplyr::filter(.data$Data_ID == data_id) %>%
utils::tail(1) %>%
dplyr::pull(.data$Location)
}
}
if(dir.exists(old_dir_path)){
stop(paste("This dataset has already been downloaded here:", old_dir_path, "Please delete or move the folder to download the dataset again.", sep = "\n"))
} else if(dir.exists(old_dir_path_log)) {
stop(paste("This dataset has already been downloaded here:", old_dir_path_log, "Please delete or move the folder to download the dataset again.", sep = "\n"))
}
if(!is.null(dir_name)){
new_dir <- file.path(path, dir_name)
} else {
new_dir <- old_dir_path
}
if(dir.exists(new_dir)){
warning(paste("An old version of the data exists at the specified path:", new_dir, "Please change dir_name or delete/move the folder to download a new version of the data", sep = "\n"))
return(new_dir)
} else{
dir.create(new_dir)
}
out <- dataone::downloadObject(d1c, data_id, path = new_dir)
message("Download complete")
data_files <- list.files(new_dir, full.names = TRUE)
data_files_ext <- stringr::str_extract(data_files, ".[^.]{1,4}$")
file.rename(data_files, file.path(new_dir, paste0(data_name, data_files_ext)))
entity_meta_general <- list(File_Name = data_name,
Date_Downloaded = paste0(Sys.time()),
Data_ID = data_id,
Data_URL = data_nodes$data$url[[1]]
)
if (exists("eml")) {
EML::write_eml(eml, file.path(new_dir, paste0(data_name, "__full_metadata.xml")))
entity_meta_combined <- c(entity_meta_general, entity_meta) %>% unlist() %>% tibble::enframe()
readr::write_csv(entity_meta_combined,
file.path(new_dir, paste0(data_name, "__summary_metadata.csv")))
} else {
entity_meta_general <- entity_meta_general %>% unlist() %>% tibble::enframe()
readr::write_csv(entity_meta_general,
file.path(new_dir, paste0(data_name, "__summary_metadata.csv")))
}
if (exists("attributeList")) {
if (nrow(attributeList$attributes) > 0) {
atts <- attributeList$attributes %>% dplyr::mutate(metadata_pid = meta_id)
readr::write_csv(atts,
file.path(new_dir, paste0(data_name, "__attribute_metadata.csv")))
}
if (!is.null(attributeList$factors)) {
facts <- attributeList$factors %>% dplyr::mutate(metadata_pid = meta_id)
readr::write_csv(facts,
file.path(new_dir, paste0(data_name, "__attribute_factor_metadata.csv")))
}
}
data_to_log <- data.frame(Date_Run = paste0(Sys.time()),
Data_ID = data_id,
Dataset_URL = data_nodes$data$url,
Location = new_dir)
if(file.exists(log_path)){
readr::write_csv(data_to_log, path = log_path, append = TRUE)
} else {
readr::write_csv(data_to_log, path = log_path, append = FALSE, col_names = TRUE)
}
return(new_dir)
} |
test_that("test for errors", {
testthat::skip_on_cran()
local_edition(3)
expect_error(convert_RLum2Risoe.BINfileData(object = NA))
})
test_that("functionality", {
testthat::skip_on_cran()
local_edition(3)
data(ExampleData.RLum.Analysis, envir = environment())
expect_s4_class(convert_RLum2Risoe.BINfileData(IRSAR.RF.Data), "Risoe.BINfileData")
expect_s4_class(convert_RLum2Risoe.BINfileData(IRSAR.RF.Data@records[[1]]), "Risoe.BINfileData")
expect_s4_class(convert_RLum2Risoe.BINfileData(list(IRSAR.RF.Data,IRSAR.RF.Data)), "Risoe.BINfileData")
}) |
neldermead.autorestart <- function(this=NULL){
restartmax <- this$restartmax
reached <- FALSE
for (iloop in 1:(restartmax+1)){
this <- neldermead.log(this=this,
msg='*****************************************************************')
this <- neldermead.log(this=this,msg=sprintf('Try
this <- neldermead.algo(this=this)
tmp <- neldermead.istorestart(this=this)
this <- tmp$this
istorestart <- tmp$istorestart
rm(tmp)
if (istorestart){
this <- neldermead.log(this=this,'Must restart.')
} else {
this <- neldermead.log(this=this,'Must not restart.')
}
if (!istorestart){
reached <- TRUE
break
}
if (iloop<restartmax+1){
this$restartnb <- this$restartnb + 1
this <- neldermead.log(this=this,msg='Updating simplex.')
this <- neldermead.updatesimp(this=this)
}
}
if (reached){
this <- neldermead.log(this=this,
msg=sprintf('Convergence reached after %d restarts.',this$restartnb))
} else {
this <- neldermead.log(this=this,
msg=sprintf('Convergence not reached after maximum %d restarts.',this$restartnb))
this$optbase <- optimbase.set(this=this$optbase,key='status',value='maxrestart')
}
return(this)
} |
N = 20
P = 1e2
grid = seq( 0, 1, length.out = P )
C = roahd::exp_cov_function( grid, alpha = 0.3, beta = 0.4 )
values = roahd::generate_gauss_fdata( N,
centerline = sin( 2 * pi * grid ),
Cov = C )
fD = roahd::fData( grid, values )
x0=list(as.list(grid))
fun=mean_lists()
final.fData = conformal.fun.split(NULL,NULL, fD, x0, fun$train.fun, fun$predict.fun,
alpha=0.1,
split=NULL, seed=FALSE, randomized=FALSE,seed_tau=FALSE,
verbose=TRUE, training_size=0.5,s_type="alpha-max")
plot_fun(final.fData)
N = 1e2
P = 1e3
t0 = 0
t1 = 1
grid = seq( t0, t1, length.out = P )
C = roahd::exp_cov_function( grid, alpha = 0.3, beta = 0.4 )
Data_1 = roahd::generate_gauss_fdata( N, centerline = sin( 2 * pi * grid ), Cov = C )
Data_2 = roahd::generate_gauss_fdata( N, centerline = log(1+ 2 * pi * grid ), Cov = C )
mfD=roahd::mfData( grid, list( Data_1, Data_2 ) )
x0=list(as.list(grid))
fun=mean_lists()
final.mfData = conformal.fun.split(NULL,NULL, mfD, x0, fun$train.fun, fun$predict.fun,
alpha=0.1,
split=NULL, seed=FALSE, randomized=FALSE,seed_tau=FALSE,
verbose=TRUE, training_size=0.5,s_type="alpha-max")
h=plot_fun(final.mfData)
daybasis <- fda::create.fourier.basis(c(0, 365), nbasis=65)
tempfd <- fda::smooth.basis(fda::day.5, fda::CanadianWeather$dailyAv[,,"Temperature.C"],daybasis)$fd
Lbasis <- fda::create.constant.basis(c(0, 365))
Lcoef <- matrix(c(0,(2*pi/365)^2,0),1,3)
bfdobj <- fda::fd(Lcoef,Lbasis)
bwtlist <- fda::fd2list(bfdobj)
harmaccelLfd <- fda::Lfd(3, bwtlist)
Ltempmat <- fda::eval.fd(fda::day.5, tempfd, harmaccelLfd)
t=1:365
x0=list(as.list(grid))
fun=mean_lists()
final.fd = conformal.fun.split(NULL,fda::day.5, tempfd, x0, fun$train.fun, fun$predict.fun,
alpha=0.1,
split=NULL, seed=FALSE, randomized=FALSE,seed_tau=FALSE,
verbose=TRUE, training_size=0.5,s_type="alpha-max")
plot_fun(final.fd) |
context("Triangle")
test_that("Triangle$contains", {
t <- Triangle$new(c(0,0), c(1,5), c(3,3))
set.seed(666)
pts <- t$randomPoints(3, "in")
expect_true(all(apply(pts, 1L, t$contains)))
})
test_that("Malfatti circles are tangent", {
t <- Triangle$new(c(0,0), c(1,5), c(3,3))
Mcircles <- t$MalfattiCircles(tangencyPoints = TRUE)
C1 <- Mcircles[[1L]]; C2 <- Mcircles[[2L]]; C3 <- Mcircles[[3L]]
I1 <- intersectionCircleCircle(C1, C2)
expect_true(is.numeric(I1) && length(I1) == 2L)
I2 <- intersectionCircleCircle(C1, C3)
expect_true(is.numeric(I2) && length(I2) == 2L)
I3 <- intersectionCircleCircle(C2, C3)
expect_true(is.numeric(I3) && length(I3) == 2L)
tpoints <- attr(Mcircles, "tangencyPoints")
expect_equal(tpoints$TA, I3)
expect_equal(tpoints$TB, I2)
expect_equal(tpoints$TC, I1)
})
test_that("Gergonne point is the symmedian point of the Gergonne triangle", {
t <- Triangle$new(c(0,0), c(1,5), c(4,3))
gpoint <- t$GergonnePoint()
intouchTriangle <- t$GergonneTriangle()
sympoint <- intouchTriangle$symmedianPoint()
expect_equal(gpoint, sympoint)
})
test_that("Symmedian point of a right triangle", {
t <- Triangle$new(c(0,0), c(1,5), c(3,3))
sympoint <- t$symmedianPoint()
orthic <- t$orthicTriangle()
H <- orthic$C
expect_equal(sympoint, (t$C+H)/2)
})
test_that("Gergonne triangle of tangential triangle is reference triangle", {
tref <- Triangle$new(c(0,0), c(1,5), c(4,3))
ttref <- tref$tangentialTriangle()
gergonnettref <- ttref$GergonneTriangle()
expect_equal(
cbind(tref$A, tref$B, tref$C),
cbind(gergonnettref$A, gergonnettref$B, gergonnettref$C)
)
})
test_that("Orthogonality Parry circle", {
t <- Triangle$new(c(0,0), c(1,5), c(4,3))
parry <- t$ParryCircle()
brocard <- t$BrocardCircle()
circum <- t$circumcircle()
expect_true(parry$isOrthogonal(brocard))
expect_true(parry$isOrthogonal(circum))
})
test_that("Brocard points - concurrency", {
t <- Triangle$new(c(0,0), c(1,5), c(5,2))
bpoints <- t$BrocardPoints()
bline1 <- Line$new(t$A, bpoints$Z1)
bline2 <- Line$new(t$A, bpoints$Z2)
median <- Line$new(t$B, t$centroid())
symmedian <- Line$new(t$C, t$symmedianPoint())
P <- intersectionLineLine(bline1, median)
expect_true(symmedian$includes(P))
})
test_that("Brocard points - distance from circumcenter", {
t <- Triangle$new(c(0,0), c(1,5), c(5,2))
bpoints <- t$BrocardPoints()
O <- t$circumcenter()
R <- t$circumradius()
edges <- as.list(t$edges())
d <- R * with(edges, sqrt((a^4+b^4+c^4)/(a^2*b^2+a^2*c^2+b^2*c^2)-1))
expect_equal(d, .distance(bpoints$Z1, O))
expect_equal(d, .distance(bpoints$Z2, O))
})
test_that("Pedal triangles", {
t <- Triangle$new(c(1,1), c(0,3), c(2,-3))
I <- t$incircle()$center
ptI <- t$pedalTriangle(I)
gerg <- t$GergonneTriangle()
expect_equal(cbind(gerg$A,gerg$B,gerg$C), cbind(ptI$A,ptI$B,ptI$C))
H <- t$orthocenter()
ptH <- t$pedalTriangle(H)
orthic <- t$orthicTriangle()
expect_equal(cbind(orthic$A,orthic$B,orthic$C), cbind(ptH$A,ptH$B,ptH$C))
O <- t$circumcenter()
ptO <- t$pedalTriangle(O)
medial <- t$medialTriangle()
expect_equal(cbind(medial$A,medial$B,medial$C), cbind(ptO$A,ptO$B,ptO$C))
B <- t$BevanPoint()
ptB <- t$pedalTriangle(B)
nagel <- t$NagelTriangle()
expect_equal(cbind(nagel$A,nagel$B,nagel$C), cbind(ptB$A,ptB$B,ptB$C))
})
test_that("Cevian triangles", {
t <- Triangle$new(c(1,1), c(0,3), c(2,-3))
I <- t$incircle()$center
ctI <- t$CevianTriangle(I)
incentral <- t$incentralTriangle()
expect_equal(cbind(incentral$A,incentral$B,incentral$C),
cbind(ctI$A,ctI$B,ctI$C))
G <- t$centroid()
ctG <- t$CevianTriangle(G)
medial <- t$medialTriangle()
expect_equal(cbind(medial$A,medial$B,medial$C), cbind(ctG$A,ctG$B,ctG$C))
H <- t$orthocenter()
ctH <- t$CevianTriangle(H)
orthic <- t$orthicTriangle()
expect_equal(cbind(orthic$A,orthic$B,orthic$C), cbind(ctH$A,ctH$B,ctH$C))
K <- t$symmedianPoint()
ctK <- t$CevianTriangle(K)
symm <- t$symmedialTriangle()
expect_equal(cbind(symm$A,symm$B,symm$C), cbind(ctK$A,ctK$B,ctK$C))
Ge <- t$GergonnePoint()
ctGe <- t$CevianTriangle(Ge)
gerg <- t$GergonneTriangle()
expect_equal(cbind(gerg$A,gerg$B,gerg$C), cbind(ctGe$A,ctGe$B,ctGe$C))
N <- t$NagelPoint()
ctN <- t$CevianTriangle(N)
extouch <- t$NagelTriangle()
expect_equal(cbind(extouch$A,extouch$B,extouch$C), cbind(ctN$A,ctN$B,ctN$C))
})
test_that("Steiner ellipse/inellipse", {
t <- Triangle$new(c(0,0), c(2,0.5), c(1.5,2))
inell <- t$SteinerInellipse()
ell <- t$medialTriangle()$SteinerEllipse()
expect_true(ell$isEqual(inell))
})
test_that("Hexyl triangle", {
t <- Triangle$new(c(0,0), c(1,5), c(3,3))
ht <- t$hexylTriangle()
et <- t$excentralTriangle()
HA <- ht$A; HB <- ht$B; HC <- ht$C
JA <- et$A; JB <- et$B; JC <- et$C
HAJC <- Line$new(HA, JC)
HCJA <- Line$new(HC, JA)
expect_true(HAJC$isParallel(HCJA))
}) |
context('dbGetRowCount')
source('utilities.R')
test_that('dbGetRowCount works with live database', {
conn <- setup_live_connection()
result <- dbSendQuery(conn, 'SELECT 1 AS n')
expect_equal(dbGetRowCount(result), 0)
expect_equal(dbFetch(result, -1), data.frame(n=1))
expect_equal(dbGetRowCount(result), 1)
result <- dbSendQuery(conn, 'SELECT n FROM (VALUES (1), (2)) AS t (n)')
expect_equal(dbGetRowCount(result), 0)
expect_equal(dbFetch(result, -1), data.frame(n=c(1, 2)))
expect_equal(dbGetRowCount(result), 2)
})
test_that('dbGetRowCount works with mock', {
conn <- setup_mock_connection()
with_mock(
`httr::POST`=mock_httr_replies(
mock_httr_response(
'http://localhost:8000/v1/statement',
status_code=200,
state='QUEUED',
request_body='SELECT n FROM two_rows',
next_uri='http://localhost:8000/query_1/1'
)
),
`httr::GET`=mock_httr_replies(
mock_httr_response(
'http://localhost:8000/query_1/1',
status_code=200,
data=data.frame(n=1, stringsAsFactors=FALSE),
state='FINISHED',
next_uri='http://localhost:8000/query_1/2'
),
mock_httr_response(
'http://localhost:8000/query_1/2',
status_code=200,
data=data.frame(n=2, stringsAsFactors=FALSE),
state='FINISHED'
)
),
{
result <- dbSendQuery(conn, 'SELECT n FROM two_rows')
expect_equal(dbGetRowCount(result), 0)
expect_equal(dbFetch(result), data.frame(n=1))
expect_equal(dbGetRowCount(result), 1)
expect_equal(dbFetch(result), data.frame(n=2))
expect_equal(dbGetRowCount(result), 2)
expect_equal(dbFetch(result), data.frame())
expect_equal(dbGetRowCount(result), 2)
}
)
}) |
quantreg.rfsrc <- function(formula, data, object, newdata,
method = "local", splitrule = NULL,
prob = NULL, prob.epsilon = NULL,
oob = TRUE, fast = FALSE, maxn = 1e3, ...)
{
grow <- FALSE
method <- match.arg(method, c("forest", "local", "gk", "GK", "G-K", "g-k"))
if (missing(object)) {
grow <- TRUE
dots <- list(...)
dots$formula <- dots$data <- NULL
dots$prob <- prob
dots$prob.epsilon <- prob.epsilon
if (is.null(splitrule)) {
splitrule <- "la.quantile.regr"
}
fmly <- parseFormula(formula, data)$family
if (fmly == "regr+" || fmly == "class+" || fmly == "mix+") {
splitrule <- NULL
}
if (!fast) {
rfsrc.grow <- "rfsrc"
}
else {
rfsrc.grow <- "rfsrc.fast"
}
if (method == "forest") {
dots$gk.quantile <- FALSE
dots$forest.wt <- if (oob) "oob" else TRUE
}
else if (method == "local") {
dots$gk.quantile <- FALSE
}
else {
dots$gk.quantile <- TRUE
}
dots$quantile.regr <- TRUE
object <- do.call(rfsrc.grow, c(list(formula = formula, data = data, splitrule = splitrule), dots))
object$yvar.grow <- object$yvar
if (object$family == "regr") {
ynames <- object$yvar.names
}
else {
ynames <- names(object$regrOutput)
}
if (ncol(cbind(object$yvar.grow)) > 1) {
object$res.grow <- do.call(cbind, lapply(ynames, function(yn) {
if (oob && !is.null(object$regrOutput[[yn]]$predicted.oob)) {
object$yvar[, yn] - object$regrOutput[[yn]]$predicted.oob
}
else {
object$yvar[, yn] - object$regrOutput[[yn]]$predicted
}
}))
colnames(object$res.grow) <- ynames
}
else {
if (oob && !is.null(object$predicted.oob)) {
object$res.grow <- object$yvar - object$predicted.oob
}
else {
object$res.grow <- object$yvar - object$predicted
}
}
}
else {
if (sum(grepl("quantreg", class(object))) == 0) {
stop("object must be a quantreg object")
}
}
if (!(object$family == "regr" | !is.null(object$regrOutput))) {
stop("this function only applies to regression settings\n")
}
prob.grow <- object$forest$prob
if (!grow || !missing(newdata)) {
dots <- list(...)
if (!is.null(prob)) {
prob.grow <- dots$prob <- prob
}
else {
dots$prob <- prob.grow
}
dots$prob.epsilon <- prob.epsilon
if (!missing(newdata)) {
oob <- FALSE
}
if (method == "forest") {
dots$gk.quantile <- FALSE
dots$forest.wt <- TRUE
if (missing(newdata) && oob) {
dots$forest.wt <- "oob"
}
}
else if (method == "local") {
dots$gk.quantile <- FALSE
}
else {
dots$gk.quantile <- TRUE
}
yvar.grow <- object$yvar.grow
res.grow <- object$res.grow
if (missing(newdata)) {
object <- do.call(predict, c(list(object = object), dots))
}
else {
object <- do.call(predict, c(list(object = object, newdata = newdata), dots))
}
object$yvar.grow <- yvar.grow
object$res.grow <- res.grow
}
prob <- prob.grow
if (object$family == "regr") {
ynames <- object$yvar.names
}
else {
ynames <- names(object$regrOutput)
}
sIndex <- function(x1, x2) {sapply(1:length(x2), function(j) {sum(x1 <= x2[j])})}
rO <- lapply(ynames, function(yn) {
if (!(method == "forest" || method == "local")) {
if (ncol(cbind(object$yvar.grow)) > 1) {
y <- object$yvar.grow[, yn]
if (oob && !is.null(object$regrOutput[[yn]]$quantile.oob)) {
quant <- object$regrOutput[[yn]]$quantile.oob
}
else {
quant <- object$regrOutput[[yn]]$quantile
}
object$regrOutput[[yn]]$quantile.oob <<- object$regrOutput[[yn]]$quantile <<- NULL
}
else {
y <- object$yvar.grow
if (oob && !is.null(object$quantile.oob)) {
quant <- object$quantile.oob
}
else {
quant <- object$quantile
}
object$quantile.oob <<- object$quantile <<- NULL
}
quant.temp <- cbind(min(y, na.rm = TRUE) - 1, quant, max(y, na.rm = TRUE))
prob.temp <- c(0, prob, 1)
yunq <- sort(unique(y))
if (length(yunq) > maxn) {
yunq <- yunq[unique(round(seq(1, length(yunq), length.out = maxn)))]
}
cdf <- t(apply(quant.temp, 1, function(q) {prob.temp[sIndex(q, yunq)]}))
density <- t(apply(cbind(0, cdf), 1, diff))
}
else {
if (ncol(cbind(object$yvar.grow)) > 1) {
y <- object$yvar.grow[, yn]
res <- object$res.grow[, yn]
if (oob && !is.null(object$regrOutput[[yn]]$predicted.oob)) {
yhat <- object$regrOutput[[yn]]$predicted.oob
}
else {
yhat <- object$regrOutput[[yn]]$predicted
}
}
else {
y <- object$yvar.grow
res <- object$res.grow
if (oob && !is.null(object$predicted.oob)) {
yhat <- object$predicted.oob
}
else {
yhat <- object$predicted
}
}
yunq <- sort(unique(y))
if (method == "forest") {
cdf <- do.call(rbind, mclapply(1:nrow(object$forest.wt), function(i) {
ind.matx <- do.call(rbind, lapply(yunq, function(yy) {res <= (yy - yhat[i])}))
c(ind.matx %*% object$forest.wt[i, ])
}))
}
else {
cdf <- do.call(rbind, mclapply(1:length(yhat), function(i) {
sapply(yunq, function(yy) {mean(res <= (yy - yhat[i]))})
}))
}
quant <- t(apply(cdf, 1, function(pr) {
c(min(yunq, na.rm = TRUE), yunq)[1 + sIndex(pr, prob)]
}))
density <- t(apply(cbind(0, cdf), 1, diff))
}
list(quantiles = quant,
prob = prob,
cdf = cdf,
density = density,
yunq = yunq)
})
if (object$family == "regr") {
rO <- rO[[1]]
}
else {
names(rO) <- ynames
}
object$quantreg <- rO
class(object)[4] <- "quantreg"
object
}
quantreg <- quantreg.rfsrc
extract.quantile <- function(o) {
if (sum(grepl("quantreg", class(o))) == 0) {
stop("object must be a quantreg object")
}
mv.y.names <- intersect(names(o$quantreg), o$yvar.names)
if (length(mv.y.names) == 0) {
q <- list(o$quantreg)
names(q) <- o$yvar.names
}
else {
q <- lapply(mv.y.names, function(m.target) {
o$quantreg[[m.target]]
})
names(q) <- mv.y.names
}
q
}
get.quantile <- function(o, target.prob = NULL, pretty = TRUE) {
qo <- extract.quantile(o)
if (!is.null(target.prob)) {
target.prob <- sort(unique(target.prob))
}
else {
target.prob <- qo[[1]]$prob
}
rO <- lapply(qo, function(q) {
q.dat <- do.call(cbind, lapply(target.prob, function(pr) {
q$quant[, which.min(abs(pr - q$prob))]
}))
colnames(q.dat) <- paste("q.", 100 * target.prob, sep = "")
q.dat
})
if (pretty && length(rO) == 1) {
rO <- rO[[1]]
}
rO
}
get.quantile.crps <- function(o, pretty = TRUE, subset = NULL) {
qO <- extract.quantile(o)
if (sum(grepl("predict", class(o))) > 0 && is.null(o$yvar)) {
stop("no yvar present in quantreg predict object")
}
if (is.null(subset)) {
subset <- 1:o$n
}
else {
if (is.logical(subset)) {
subset <- which(subset)
}
subset <- subset[subset >=1 & subset <= o$n]
}
if (length(subset) == 0) {
stop("requested subset is empty")
}
rO <- lapply(1:length(qO), function(j) {
q <- qO[[j]]
if (is.vector(o$yvar)) {
y <- cbind(o$yvar)
}
else {
y <- o$yvar[, names(qO)[j]]
}
n <- length(y)
brS <- colMeans(do.call(rbind, mclapply(subset, function(i) {
(1 * (y[i] <= q$yunq) - q$cdf[i, ]) ^ 2
})), na.rm = TRUE)
crps <- unlist(lapply(1:length(q$yunq), function(j) {
trapz(q$yunq[1:j], brS[1:j]) / diff(range(q$yunq[1:j]))
}))
data.frame(y = q$yunq, crps = crps)
})
names(rO) <- names(qO)
if (pretty && length(rO) == 1) {
rO <- rO[[1]]
}
rO
}
get.quantile.stat <- function(o, pretty = TRUE) {
qO <- extract.quantile(o)
mdn <- get.quantile(o, .5, FALSE)
rO <- lapply(1:length(qO), function(j) {
q <- qO[[j]]
mn <- q$density %*% q$yunq
std <- sqrt(q$density %*% q$yunq^2 - mn ^ 2)
data.frame(mean = mn, median = c(mdn[[j]]), std = std)
})
names(rO) <- names(qO)
if (pretty && length(rO) == 1) {
rO <- rO[[1]]
}
rO
} |
mvord.fit <- function(rho){
rho$ntheta <- sapply(seq_len(rho$ndim), function(j) nlevels(rho$y[, j]) - 1)
if (is.null(rho$threshold.values)) {
if ((rho$error.structure$type == "correlation") && (rho$intercept.type == "fixed")) {
rho$threshold.values <- lapply(seq_len(rho$ndim), function(j) rep.int(NA, rho$ntheta[j]))
} else if((rho$error.structure$type %in% c("correlation")) && (rho$intercept.type == "flexible")) {
rho$threshold.values <- lapply(seq_len(rho$ndim), function(j) if(rho$ntheta[j] == 1) 0 else c(0,rep.int(NA,max(rho$ntheta[j]-1,0))))
cat("Note: First threshold for each response is fixed to 0 in order to ensure identifiability!\n")
} else if ((rho$error.structure$type %in% c("covariance")) && (rho$intercept.type == "flexible")) {
rho$threshold.values <- lapply(seq_len(rho$ndim), function(j) if(rho$ntheta[j] == 1) 0 else c(0,1,rep.int(NA,max(rho$ntheta[j]-2,0))))
cat("Note: First two thresholds for each response are fixed to 0 and 1 in order to ensure identifiability!\n")
} else if ((rho$error.structure$type %in% c("covariance")) && (rho$intercept.type == "fixed")) {
rho$threshold.values <- lapply(seq_len(rho$ndim), function(j) if(rho$ntheta[j] == 1) 0 else c(0,rep.int(NA,max(rho$ntheta[j]-1,0))))
cat("Note: First threshold for each response is fixed to 0 in order to ensure identifiability!\n")
}
} else {
if (length(rho$threshold.values) != rho$ndim) stop("Length of threshold values does not match number of outcomes")
}
rho$threshold.values.fixed <- lapply(rho$threshold.values, function(x) x[!is.na(x)])
rho$npar.theta <- sapply(seq_len(rho$ndim), function(j) sum(is.na(rho$threshold.values[[j]])))
rho$binary <- any(sapply(seq_len(rho$ndim), function(j) length(rho$threshold.values[[j]]) == 1))
rho$threshold <- set_threshold_type(rho)
rho$ncat <- rho$ntheta + 1
rho$nthetas <- sum(rho$ntheta)
rho$ncat.first.ind <- cumsum(c(1,rho$ntheta))[- (rho$ndim + 1)]
rho$npar.theta.opt <- rho$npar.theta
rho$npar.theta.opt[duplicated(rho$threshold.constraints)] <- 0
rho$npar.thetas <- sum(rho$npar.theta.opt)
rho <- set_offset_up(rho)
rho$coef.names <- attributes(rho$x[[1]])$dimnames[[2]]
rho$constraints <- get_constraints(rho)
rho$npar.beta <- 0
if (length(rho$constraints) > 0) rho$npar.beta <- sapply(rho$constraints, NCOL)
rho$npar.betas <- sum(rho$npar.beta)
check_args_constraints(rho)
check_args_thresholds(rho)
rho$ind.thresholds <- get_ind_thresholds(rho$threshold.constraints, rho)
rho$inf.value <- 10000
rho$evalOnly <- ifelse((rho$npar.thetas + rho$npar.betas + attr(rho$error.structure, "npar") == 0), TRUE, FALSE)
if (is.null(rho$start.values)) {
rho$start <- c(get_start_values(rho), start_values(rho$error.structure))
} else {
if(length(unlist(rho$start.values)) != (rho$npar.thetas + rho$npar.betas)){
cat(paste0("length should be ", rho$npar.thetas + rho$npar.betas))
stop("start.values (theta + beta) has false length", call. = FALSE)
}
theta.start <- rho$threshold.values
gamma.start <- lapply(seq_len(rho$ndim), function(j) {theta.start[[j]][is.na(theta.start[[j]])] <- rho$start.values$theta[[j]]
theta2gamma(theta.start[[j]])
})
rho$start <- c(unlist(lapply(seq_len(rho$ndim), function(j) gamma.start[[j]][is.na(rho$threshold.values[[j]])])),
unlist(rho$start.values$beta),
start_values(rho$error.structure))
}
rho$transf_thresholds <- switch(rho$threshold,
flexible = transf_thresholds_flexible,
fix1first = transf_thresholds_fix1_first,
fix2first = transf_thresholds_fix2_first,
fix2firstlast = transf_thresholds_fix2_firstlast,
fixall = transf_thresholds_fixall)
rho$build_error_struct <- ifelse(attr(rho$error.structure, "npar") == 0, build_error_struct_fixed, build_error_struct)
rho$p <- NCOL(rho$x[[1]])
rho$inds.cat <- lapply(seq_len(rho$ndim), function(j)
seq_len(rho$ntheta[j]) + rho$ncat.first.ind[j] - 1)
rho$indjbeta <- lapply(seq_len(rho$ndim), function(j) {
c(outer(rho$inds.cat[[j]], (seq_len(rho$p) - 1) * rho$nthetas, "+"))
})
dim_ind <- rep.int(seq_len(rho$ndim), rho$ntheta)
x_new <- rho$x
if(rho$p > 0) {
x_center <- vector("list", rho$ndim)
x_scale <- vector("list", rho$ndim)
for (j in seq_len(rho$ndim)) {
mu <- double(rho$p)
sc <- rep.int(1, rho$p)
ind_int <- attr(x_new[[j]], "assign") != 0
tmp <- scale_mvord(x_new[[j]][, ind_int, drop = FALSE])
x_new[[j]][, ind_int] <- tmp$x
mu[ind_int] <- tmp$mu
sc[ind_int] <- tmp$sc
x_center[[j]] <- mu
x_scale[[j]] <- sc
}
constraints_scaled <- lapply(seq_along(rho$constraints), function(p) {
sxp <- sapply(x_scale, "[", p)
x <- rho$constraints[[p]]
fi <- apply(x, 2, function(y) which(y == 1)[1])
fi[is.na(fi)] <- 1
sweep(x * sxp[dim_ind], 2, sxp[dim_ind[fi]], "/")
})
if (length(constraints_scaled) > 0) {
rho$constraints_mat <- bdiag(constraints_scaled)
} else {
rho$constraints_mat <- numeric(0)
}
tmp <- (lapply(seq_along(rho$constraints), function(p) {
sxp <- sapply(x_scale, "[", p)
mxp <- sapply(x_center, "[", p)
fi <- apply(rho$constraints[[p]], 2, function(y) which(y == 1)[1])
fi[is.na(fi)] <- 1
list(scale = sxp[dim_ind[fi]], center = mxp[dim_ind[fi]])
}))
rho$fi_scale <- unlist(sapply(tmp, "[", "scale"))
rho$fi_center <- unlist(sapply(tmp, "[", "center"))
} else rho$constraints_mat <- integer()
rho$XcatU <- vector("list", rho$ndim)
rho$XcatL <- vector("list", rho$ndim)
if (rho$p > 0) {
for (j in seq_len(rho$ndim)) {
ncat <- rho$ntheta[j] + 1
mm <- model.matrix(~ - 1 + rho$y[,j] : x_new[[j]],
model.frame(~ - 1 + rho$y[,j] : x_new[[j]],
na.action = function(x) x))
rho$XcatL[[j]] <- mm[,-(ncat * (seq_len(rho$p) - 1) + 1), drop = F]
rho$XcatU[[j]] <- mm[,-(ncat * seq_len(rho$p)), drop = F]
}
} else {
rho$XcatU <- lapply(seq_len(rho$ndim), function(x) integer())
rho$XcatL <- lapply(seq_len(rho$ndim), function(x) integer())
}
rho$contr_theta <- do.call("rbind", rep.int(list(diag(rho$nthetas)), rho$p))
if(rho$p > 0){
rho$mat_center_scale <- bdiag(rho$constraints) %*% c(rho$fi_center/rho$fi_scale)
} else rho$mat_center_scale <- integer()
rho$thold_correction <- vector("list", rho$ndim)
is.dup <- duplicated(rho$threshold.constraints)
if(rho$p > 0){
rho$thold_correction <-lapply(seq_len(rho$ndim), build_correction_thold_fun0, rho = rho)
if (any(is.dup)) {
tmp <- lapply(which(is.dup), build_correction_thold_fun, rho = rho)
rho$thold_correction[which(is.dup)] <- tmp
}
} else {
rho$thold_correction <-lapply(seq_len(rho$ndim), build_correction_thold_fun0, rho = rho)
}
rho$combis <- combn(rho$ndim, 2, simplify = F)
rho$dummy_pl_lag <- sapply(rho$combis, function(x)
diff(x) <= rho$PL.lag)
rho$combis <- rho$combis[rho$dummy_pl_lag == 1]
ind_i <- rowSums(!is.na(rho$y)) == 1
rho$ind_univ <- which(!is.na(rho$y) & ind_i, arr.ind=T)
rho$n_univ <- NROW(rho$ind_univ)
rho$ind_kl <- lapply(rho$combis, function(kl)
rowSums(!is.na(rho$y[, kl])) == 2)
rho$ind_i <- lapply(seq_along(rho$combis), function(h) which(rho$ind_kl[[h]]))
rho$combis_fast <- lapply(seq_along(rho$combis),function(h){
list("combis" = rho$combis[[h]],
"ind_i" = rho$ind_i[[h]],
"r" = rep(h,length(rho$ind_i[[h]])))
})
rho$n_biv <- sum(sapply(rho$ind_i, length))
rho$weights_fast <- rho$weights[c(unlist(rho$ind_i), rho$ind_univ[,1])]
if(("cor_general" %in% class(rho$error.structure)) & is.null(rho$coef.values_input) & (rho$coef.constraints_VGAM == FALSE) &
attr(rho$error.structure, "formula")[[2]] == 1 & !isTRUE(rho$error.structure$fixed) &
!anyNA(rho$coef.constraints_input) &
all(sapply(seq_len(length(rho$x)-1), function(j){
if((NCOL(rho$x[[j]]) == 0) & (NCOL(rho$x[[j + 1]]) == 0)) {TRUE
}else if(any(sapply(rho$x, anyNA))) FALSE else{
rho$x[[j]] == rho$x[[j + 1]]
}
}))){
rho$fast_fit <- TRUE
} else rho$fast_fit <- FALSE
if(rho$fast_fit){
rho$indjbeta_mat <- do.call("cbind",lapply(rho$constraints, function(x){x[rho$ncat.first.ind,] == 1
}))
rho$indjbeta_fast <- lapply(seq_len(rho$ndim), function(j) {
j + (seq_len(rho$p)-1) * rho$npar.beta
})
rho$fi_scale_fast <- rho$fi_scale[1 + (seq_len(rho$p)-1) * rho$ndim]
rho$fi_center_fast <- rho$fi_center[1 + (seq_len(rho$p)-1) * rho$ndim]
rho$xfast <- x_new[[1]]
}
if (rho$evalOnly) {
rho$optpar <- numeric(0)
rho$objective <- c(value = PLfun_old(rho$start , rho))
} else {
if (is.character(rho$solver)) {
if(rho$fast_fit){
rho$optRes <- suppressWarnings(optimx(rho$start, function(x) PLfun_fast(x, rho),
method = rho$solver,
hessian = FALSE,
control = rho$control))
} else{
rho$optRes <- suppressWarnings(optimx(rho$start, function(x) PLfun(x, rho),
method = rho$solver,
hessian = FALSE,
control = rho$control))
}
rho$optpar <- unlist(rho$optRes[1:length(rho$start)])
rho$objective <- unlist(rho$optRes["value"])
}
if (is.function(rho$solver)){
rho$optRes <- rho$solver(rho$start, function(x) PLfun(x, rho))
if (is.null(rho$optRes$optpar)|is.null(rho$optRes$objvalue)|is.null(rho$optRes$convcode)) stop("Solver function does not return the required objects.")
rho$optpar <- rho$optRes$optpar
rho$objective <- rho$optRes$objvalue
rho$message <- rho$optRes$message
}
if (rho$optRes$convcode != 0){
stop("NO/FALSE CONVERGENCE - choose a different optimizer or different starting values.")
}
}
par_beta <- rho$optpar[rho$npar.thetas + seq_len(rho$npar.betas)]
if(rho$p > 0){
betatilde <- rho$constraints_mat %*% par_beta
par_theta <- rho$transf_thresholds(rho$optpar[seq_len(rho$npar.thetas)], rho, betatilde)
thetatilde <- lapply(seq_len(rho$ndim), function(j)
par_theta[[j]] + rho$thold_correction[[j]](betatilde, k = j, rho = rho))
betatildemu <- betatilde * rho$mat_center_scale
br <- drop(crossprod(rho$contr_theta, betatildemu[,1]))
correction <- lapply(rho$inds.cat, function(k) br[k])
} else {
correction <- rep.int(list(0), rho$ndim)
par_theta <- rho$transf_thresholds(rho$optpar[seq_len(rho$npar.thetas)], rho, 0)
thetatilde <- lapply(seq_len(rho$ndim), function(j) par_theta[[j]])
}
rho$theta <- lapply(seq_len(rho$ndim), function(j) thetatilde[[j]] + correction[[j]])
rho$beta <- par_beta/rho$fi_scale
if (rho$se) {
rho <- PL_se(rho)
}
res <- mvord_finalize(rho)
if (rho$se) {
rownames(rho$varGamma) <- colnames(rho$varGamma) <- c(names(unlist(res$theta))[is.na(unlist(rho$threshold.values))][!duplicated(unlist(rho$ind.thresholds))], names(res$beta), attr(res$error.struct, "parnames"))
}
rho$XcatU <- NULL
rho$XcatL <- NULL
rho$transf_thresholds <- NULL
rho$get_ind_thresholds <- NULL
rho$y.NA.ind <- NULL
rho$binary <- NULL
rho$intercept.type <- NULL
rho$intercept <- NULL
rho$threshold.values.fixed <- NULL
rho$ncat.first.ind <- NULL
rho$constraints_mat <- NULL
rho$ind_univ <- NULL
rho$ind_kl <- NULL
rho$combis <- NULL
rho$fi_scale <- NULL
rho$fi_center <- NULL
rho$mat_center_scale <- NULL
rho$dummy_pl_lag <- NULL
rho$inds.cat <- NULL
rho$thold_correction <- NULL
rho$contr_theta <- NULL
rho$error.structure <- NULL
rho$beta <- NULL
rho$coef.names <- NULL
rho$link$deriv.fun <- NULL
rho$link$F_biv_rect <- NULL
rho$link$F_biv <- NULL
res$rho <- rho
res$rho$formula <- rho$formula.input
res$rho$formula.input <- NULL
attr(res, "contrasts") <- rho$contrasts
res$rho$contrasts <- NULL
rho$timestamp2 <- proc.time()
res$rho$runtime <- rho$timestamp2 - rho$timestamp1
res$rho$timestamp1 <- NULL
class(res) <- "mvord"
return(res)
}
PLfun <- function(par, rho){
tmp <- transf_par(par, rho)
pr <- double(rho[["n_univ"]])
pr <- rho[["link"]][["F_uni"]](tmp[["U_univ"]]) -
rho[["link"]][["F_uni"]](tmp[["L_univ"]])
pr[pr < .Machine$double.eps] <- .Machine$double.eps
prh <- double(rho[["n_biv"]])
prh <- rho[["link"]][["F_biv_rect"]](
U = tmp[["U"]],
L = tmp[["L"]],
r = tmp[["corr_par"]])
prh[prh < .Machine$double.eps] <- .Machine$double.eps
-sum(rho[["weights_fast"]] * log(c(prh, pr)))
}
PLfun_old <- function(par, rho){
tmp <- transf_par_old(par, rho)
pred.upper <- tmp$U
pred.lower <- tmp$L
r_mat <- tmp$corr_par[, rho$dummy_pl_lag == 1, drop = F]
logp <- double(rho$n)
pr <- rho$link$F_uni(pred.upper[rho$ind_univ]) -
rho$link$F_uni(pred.lower[rho$ind_univ])
pr[pr < .Machine$double.eps] <- .Machine$double.eps
logp[rho$ind_univ[,1]] <- log(pr)
for (h in seq_along(rho$combis)){
ind_i <- which(rho$ind_kl[[h]])
r <- r_mat[ind_i, h]
prh <- rho$link$F_biv_rect(
U = pred.upper[ind_i, rho$combis[[h]], drop = F],
L = pred.lower[ind_i, rho$combis[[h]], drop = F],
r = r)
prh[prh < .Machine$double.eps] <- .Machine$double.eps
logp[ind_i] <- logp[ind_i] + log(prh)
}
- sum(rho$weights * logp)
}
.onLoad <- function(library, pkg)
{
library.dynam("mvord", pkg, library)
invisible()
} |
copy_df <-function(x,
row.names = FALSE,
col.names = TRUE,
quietly = FALSE,...) {
utils::write.table(x,"clipboard-50000",
sep="\t",
row.names=row.names,
col.names=col.names,...)
if(quietly==FALSE) print(x)
} |
which.nearest <- function(x, y) {
sapply(y, function(i) {
if (is.na(i) | is.nan(i)) return(i)
if (i < min(x, na.rm = TRUE)) warning("y = ", i, " is less than minimum of x", call. = FALSE)
if (i > max(x, na.rm = TRUE)) warning("y = ", i, " is greater than maximum of x", call. = FALSE)
return(which.min(abs(i - x)))
})
} |
TraCoe <- function(coe = matrix(), fac = dplyr::data_frame()) {
structure(
list(coe = coe, fac = tibble::as_tibble(fac)),
class=c("TraCoe", "Coe")
)
}
print.TraCoe <- function(x, ...) {
TraCoe <- x
cat("A TraCoe object ", rep("-", 20), "\n", sep = "")
shp.nb <- nrow(TraCoe$coe)
var.nb <- ncol(TraCoe$coe)
cat(" - $coe:", shp.nb, "shapes described with", var.nb, "variables\n")
.print_fac(TraCoe$fac)
} |
Sbackward<-function(initsa,x,y,theta=NULL){
n<-length(x)
l<-length(initsa$states)
if(is.null(theta)){
scor_func<-scores(initsa)
}else{
scor_func<-scores(NULL,theta)
}
B<-matrix(data = NA, nrow = n+1,ncol = l)
for(s in 1:l){
B[n+1,s]<-0
}
for(k in n:1){
for(s in l:1){
B[k,s]<-Inf
for(s_dash in l:1){
score_col<-paste(toString(y[k]),toString(initsa$states[s]), sep=',')
score_row<-paste(toString(x[k]),toString(initsa$states[s_dash]), sep=',')
B[k,s]=min(B[k,s],(scor_func$scoress[score_row,score_col]+B[k+1,s_dash]))
}
}
}
colnames(B)<-initsa$states
w<-Inf
for(s in 1:l){
w<-min(w[s],B[1,s])
}
return(B)
} |
library(tinytest)
library(ggiraph)
library(ggplot2)
library(xml2)
source("setup.R")
{
eval(test_geom_layer, envir = list(name = "geom_vline_interactive"))
} |
chk_chr <- function(x, x_name = NULL) {
if (vld_chr(x)) {
return(invisible(x))
}
deprecate_soft(
"0.6.1",
what = "chk::chk_chr()",
details = "Please use `chk::chk_scalar(x);` `chk::chk_character(x)` instead",
id = "chk_chr"
)
if (is.null(x_name)) x_name <- deparse_backtick_chk((substitute(x)))
abort_chk(x_name, " must be a character scalar", x = x)
}
vld_chr <- function(x) {
deprecate_soft(
"0.6.1",
what = "chk::chk_chr()",
details = "Please use `chk::chk_scalar(x);` `chk::chk_character(x)` instead",
id = "chk_chr"
)
is.character(x) && length(x) == 1L
} |
test_that("The code outputs a correct json", {
x <- 'c-Si'
y <- ivallreal_fair(x)
expect_identical(stringr::str_count(y, '<<'), as.integer(0))
expect_identical(stringr::str_count(y, '>>'), as.integer(0))
}) |
.incon <- function(mat) {
sum( (mat - t(mat))[upper.tri(mat)] < 0, na.rm = TRUE)
} |
mw_static <- function(root, set_headers = NULL) {
root; set_headers
function(req, res) {
path <- file.path(root, sub("^/", "", req$path))
if (!file.exists(path)) return("next")
if (file.info(path)$isdir) return("next")
ext <- tools::file_ext(basename(path))
ct <- mime_find(ext)
if (!is.na(ct)) {
res$set_header("Content-Type", ct)
}
if (!is.null(set_headers)) set_headers(req, res)
res$send(read_bin(path))
}
} |
`orditree3d` <-
function(ord, cluster, prune = 0, display = "sites", choices = c(1,2),
col = "blue", text, type = "p", ...)
{
ord <- scores(ord, choices = choices, display = display, ...)
if (ncol(ord) != 2)
stop(gettextf("needs plane in 2d, got %d", ncol(ord)))
ord <- cbind(ord, 0)
if (!inherits(cluster, "hclust"))
cluster <- as.hclust(cluster)
x <- reorder(cluster, ord[,1], agglo.FUN = "mean")$value
y <- reorder(cluster, ord[,2], agglo.FUN = "mean")$value
xyz <- cbind(x, y, "height" = cluster$height)
if (is.factor(col))
col <- as.numeric(col)
col <- rep(col, length = nrow(ord))
lcol <- col2rgb(col)/255
r <- reorder(cluster, lcol[1,], agglo.FUN = "mean")$value
g <- reorder(cluster, lcol[2,], agglo.FUN = "mean")$value
b <- reorder(cluster, lcol[3,], agglo.FUN = "mean")$value
lcol <- rgb(r, g, b)
pl <- scatterplot3d(rbind(ord, xyz), type = "n")
if (type == "p")
pl$points3d(ord, col = col, ...)
else if (type == "t") {
if (missing(text))
text <- rownames(ord)
text(pl$xyz.convert(ord), labels = text, col = col, ...)
}
leaf <- pl$xyz.convert(ord)
node <- pl$xyz.convert(xyz)
merge <- cluster$merge
for (i in seq_len(nrow(merge) - prune))
for (j in 1:2)
if (merge[i,j] < 0)
segments(node$x[i], node$y[i],
leaf$x[-merge[i,j]], leaf$y[-merge[i,j]],
col = col[-merge[i,j]], ...)
else
segments(node$x[i], node$y[i],
node$x[merge[i,j]], node$y[merge[i,j]],
col = lcol[merge[i,j]], ...)
pl$internal <- do.call(cbind, node)
pl$points <- do.call(cbind, leaf)
pl$col.internal <- as.matrix(lcol)
pl$col.points <- as.matrix(col)
class(pl) <- c("orditree3d", "ordiplot3d")
invisible(pl)
}
`ordirgltree` <-
function(ord, cluster, prune = 0, display = "sites", choices = c(1, 2),
col = "blue", text, type = "p", ...)
{
p <- cbind(scores(ord, choices = choices, display = display, ...), 0)
if (ncol(p) != 3)
stop(gettextf("needs 2D ordination plane, but got %d", ncol(p)-1))
if (!inherits(cluster, "hclust"))
cluster <- as.hclust(cluster)
x <- reorder(cluster, p[,1], agglo.FUN = "mean")$value
y <- reorder(cluster, p[,2], agglo.FUN = "mean")$value
z <- cluster$height
merge <- cluster$merge
z <- mean(c(diff(range(x)), diff(range(y))))/diff(range(z)) * z
if (is.factor(col))
col <- as.numeric(col)
col <- rep(col, length = nrow(p))
lcol <- col2rgb(col)/255
r <- reorder(cluster, lcol[1,], agglo.FUN = "mean")$value
g <- reorder(cluster, lcol[2,], agglo.FUN = "mean")$value
b <- reorder(cluster, lcol[3,], agglo.FUN = "mean")$value
lcol <- rgb(r, g, b)
rgl.clear()
if (type == "p")
rgl.points(p, col = col, ...)
else if (type == "t") {
if (missing(text))
text <- rownames(p)
rgl.texts(p, text = text, col = col, ...)
}
for (i in seq_len(nrow(merge) - prune))
for(j in 1:2)
if (merge[i,j] < 0)
rgl.lines(c(x[i], p[-merge[i,j],1]),
c(y[i], p[-merge[i,j],2]),
c(z[i], 0),
col = col[-merge[i,j]], ...)
else
rgl.lines(c(x[i], x[merge[i,j]]),
c(y[i], y[merge[i,j]]),
c(z[i], z[merge[i,j]]),
col = lcol[merge[i,j]], ...)
if (prune <= 0) {
n <- nrow(merge)
rgl.lines(c(x[n],x[n]), c(y[n],y[n]), c(z[n],1.05*z[n]),
col = lcol[n], ...)
}
} |
.computeHost = function(ctree) {
fathers <- rep(NA, nrow(ctree))
fathers[ctree[ ,2] + 1] <- 1:nrow(ctree)
fathers[ctree[ ,3] + 1] <- 1:nrow(ctree)
fathers <- fathers[-1]
host <- rep(0, nrow(ctree))
nsam <- sum(ctree[ ,2] == 0&ctree[ ,3] == 0)
for (i in 1:nsam) {
j <- i
while (1) {
if (host[j]>0) warning('Warning: two leaves in same host')
host[j] <- i
j <- fathers[j]
if (ctree[j,3] == 0) break
}
}
if (nsam==1) return(host)
dispo=nsam+1
f <- which( ctree[,3] == 0 & ctree[,2]>0 & (1:nrow(ctree))<nrow(ctree) )
for (i in 1:length(f)) {
j <- f[i]
tocol <- c()
while (ctree[fathers[j],3]>0&&fathers[j]<nrow(ctree)) {
tocol <- c(tocol,j)
j <- fathers[j]
}
if (host[j]==0) {host[j]=dispo;dispo=dispo+1}
host[tocol] <- host[j]
}
return(host)
} |
library(sommer)
data(DT_example)
DT <- DT_example
A <- A_example
ansSingle <- mmer(Yield~1,
random= ~ vs(Name, Gu=A),
rcov= ~ units,
data=DT, verbose = FALSE)
summary(ansSingle)
ansMain <- mmer(Yield~Env,
random= ~ vs(Name, Gu=A),
rcov= ~ units,
data=DT, verbose = FALSE)
summary(ansMain)
ansDG <- mmer(Yield~Env,
random= ~ vs(ds(Env),Name, Gu=A),
rcov= ~ units,
data=DT, verbose = FALSE)
summary(ansDG)
E <- diag(length(unique(DT$Env)))
rownames(E) <- colnames(E) <- unique(DT$Env)
EA <- kronecker(E,A, make.dimnames = TRUE)
ansCS <- mmer(Yield~Env,
random= ~ vs(Name, Gu=A) + vs(Env:Name, Gu=EA),
rcov= ~ units,
data=DT, verbose = FALSE)
summary(ansCS)
ansMain <- mmer(Yield~Env,
random= ~ vs(Name, Gu=A) + vs(ds(Env),Name, Gu=A),
rcov= ~ units,
data=DT, verbose = FALSE)
summary(ansMain)
ansUS <- mmer(Yield~Env,
random= ~ vs(us(Env),Name, Gu=A),
rcov= ~ units,
data=DT, verbose = FALSE)
summary(ansUS)
library(orthopolynom)
DT$EnvN <- as.numeric(as.factor(DT$Env))
ansRR <- mmer(Yield~Env,
random= ~ vs(leg(EnvN,1),Name),
rcov= ~ units,
data=DT, verbose = FALSE)
summary(ansRR)
library(orthopolynom)
DT$EnvN <- as.numeric(as.factor(DT$Env))
ansRR <- mmer(Yield~Env,
random= ~ vs(us(leg(EnvN,1)),Name),
rcov= ~ units,
data=DT, verbose = FALSE)
summary(ansRR)
E <- AR1(DT$Env)
rownames(E) <- colnames(E) <- unique(DT$Env)
EA <- kronecker(E,A, make.dimnames = TRUE)
ansCS <- mmer(Yield~Env,
random= ~ vs(Name, Gu=A) + vs(Env:Name, Gu=EA),
rcov= ~ units,
data=DT, verbose = FALSE)
summary(ansCS) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.