code
stringlengths 1
13.8M
|
---|
anova.ppm <- local({
do.gripe <- function(...) warning(paste(...), call.=FALSE)
dont.gripe <- function(...) NULL
nquad <- function(x) { if(is.quad(x)) n.quad(x) else 0 }
fmlaString <- function(z) { paste(as.expression(formula(z))) }
interString <- function(z) { as.interact(z)$creator }
anova.ppm <- function(object, ..., test=NULL, adjust=TRUE, warn=TRUE,
fine=FALSE) {
gripe <- if(warn) do.gripe else dont.gripe
if(!is.null(test)) {
test <- match.arg(test, c("Chisq", "LRT", "Rao", "score", "F", "Cp"))
if(test == "score") test <- "Rao"
if(!(test %in% c("Chisq", "LRT", "Rao")))
stop("test=", dQuote(test), "is not yet implemented")
}
argh <- list(...)
if("override" %in% names(argh)) {
gripe("Argument 'override' is superseded and was ignored")
argh <- argh[-which(names(argh) == "override")]
}
objex <- append(list(object), argh)
if(!all(sapply(objex, is.ppm)))
stop(paste("Arguments must all be", sQuote("ppm"), "objects"))
pois <- all(sapply(objex, is.poisson.ppm))
gibbs <- !pois
newton <- any(sapply(objex, inherits, what="ippm"))
if(gibbs && !is.null(test) && test == "Rao")
stop("Score test is only implemented for Poisson models",
call.=FALSE)
expandedfrom1 <- FALSE
if(length(objex) == 1 && (gibbs || newton)) {
Terms <- drop.scope(object)
if((nT <- length(Terms)) > 0) {
objex <- vector(mode="list", length=nT+1)
for(n in 1L:nT) {
fmla <- paste(". ~ . - ", paste(Terms[n:nT], collapse=" - "))
fmla <- as.formula(fmla)
objex[[n]] <- update(object, fmla)
}
objex[[nT+1L]] <- object
expandedfrom1 <- TRUE
}
}
fitmethod <- unique(sapply(objex, getElement, name="method"))
if(length(fitmethod) > 1)
stop(paste("Models were fitted by different methods",
commasep(sQuote(fitmethod)),
"- comparison is not possible"))
if(!(fitmethod %in% c("mpl", "logi")))
stop(paste("Not implemented for models fitted by method=",
sQuote(fitmethod)))
logi <- (fitmethod == "logi")
refitargs <- list()
fitz <- NULL
if(length(objex) > 1) {
datas <- lapply(objex, data.ppm)
samedata <- all(sapply(datas[-1L], identical, y=datas[[1L]]))
if(!samedata) stop("Models were fitted to different datasets")
quads <- lapply(objex, quad.ppm)
samequad <- all(sapply(quads[-1L], identical, y=quads[[1L]]))
if(!samequad) {
gripe("Models were re-fitted using a common quadrature scheme")
sizes <- sapply(quads, nquad)
imax <- which.max(sizes)
bigQ <- quads[[imax]]
refitargs$Q <- bigQ
}
corrxn <- unique(sapply(objex, getElement, name="correction"))
if(length(corrxn) > 1)
stop(paste("Models were fitting using different edge corrections",
commasep(sQuote(corrxn))))
if(corrxn == "border") {
rbord <- unique(sapply(objex, getElement, name="rbord"))
if(length(rbord) > 1) {
gripe("Models were re-fitted using a common value of 'rbord'")
refitargs$rbord <- max(rbord)
}
}
fitz <- lapply(objex, getglmfit)
trivial <- sapply(fitz, is.null)
if(any(trivial))
refitargs$forcefit <- TRUE
isgam <- sapply(fitz, inherits, what="gam")
isglm <- sapply(fitz, inherits, what="glm")
usegam <- any(isgam)
if(usegam && any(isglm)) {
gripe("Models were re-fitted with use.gam=TRUE")
refitargs$use.gam <- TRUE
refitargs$forcefit <- TRUE
}
if(length(refitargs) > 0) {
objex <- do.call(lapply, append(list(X=objex, FUN=update),
refitargs))
fitz <- lapply(objex, getglmfit)
}
}
subz <- lapply(objex, getglmsubset)
if(length(unique(subz)) > 1) {
subsub <- Reduce("&", subz)
fitz <- lapply(fitz, refittosubset, sub=subsub)
gripe("Models were re-fitted after discarding quadrature points",
"that were illegal under some of the models")
}
if(newton) {
nfree <- sapply(lapply(objex, logLik), attr, which="df")
ncanonical <- lengths(lapply(objex, coef))
nextra <- nfree - ncanonical
if(is.null(fitz))
fitz <- lapply(objex, getglmfit)
for(i in seq_along(fitz))
if(nextra[i] != 0)
fitz[[i]]$df.residual <- fitz[[i]]$df.residual - nextra[i]
}
if(is.null(fitz)) fitz <- lapply(objex, getglmfit)
result <- do.call(anova, append(fitz, list(test=test, dispersion=1)))
result[, "Resid. Dev"] <- NULL
if("Resid. Df" %in% names(result)) {
obj1 <- objex[[1L]]
ss <- getglmsubset(obj1)
nq <- if(!is.null(ss)) sum(ss) else n.quad(quad.ppm(obj1))
result[, "Resid. Df"] <- nq - result[, "Resid. Df"]
names(result)[match("Resid. Df", names(result))] <- "Npar"
}
if(!is.null(h <- attr(result, "heading"))) {
h <- gsub(".mpl.Y", "", h)
h <- gsub(".logi.Y", "", h)
h <- gsub("Model: quasi, link: log", "", h)
h <- gsub("Model: binomial, link: logit", "", h)
h <- gsub("Response: ", "", h)
for(i in 1L:5L)
h <- gsub("\n\n", "\n", h)
if(length(objex) > 1 && length(h) > 1) {
fmlae <- sapply(objex, fmlaString)
intrx <- sapply(objex, interString)
h[2L] <- paste("Model",
paste0(1L:length(objex), ":"),
fmlae,
"\t",
intrx,
collapse="\n")
}
if(expandedfrom1)
h <- c(h[1L], "Terms added sequentially (first to last)\n", h[-1L])
if(!waxlyrical('space'))
h <- gsub("\n$", "", h)
attr(result, "heading") <- h
}
if(adjust && gibbs) {
fitz <- lapply(objex, getglmfit)
usegam <- any(sapply(fitz, inherits, what="gam"))
if(usegam) {
gripe("Deviance adjustment is not available for gam fits;",
"unadjusted composite deviance calculated.")
} else {
if(warn) warn.once("anovaAdjust",
"anova.ppm now computes the *adjusted* deviances",
"when the models are not Poisson processes.")
nmodels <- length(objex)
if(nmodels > 1) {
cfac <- rep(1, nmodels)
for(i in 2:nmodels) {
a <- objex[[i-1]]
b <- objex[[i]]
df <- length(coef(a)) - length(coef(b))
if(df > 0) {
ibig <- i-1
ismal <- i
} else {
ibig <- i
ismal <- i-1
df <- -df
}
bigger <- objex[[ibig]]
smaller <- objex[[ismal]]
if(df == 0) {
gripe("Models", i-1, "and", i, "have the same dimension")
} else {
bignames <- names(coef(bigger))
smallnames <- names(coef(smaller))
injection <- match(smallnames, bignames)
if(any(uhoh <- is.na(injection))) {
gripe("Unable to match",
ngettext(sum(uhoh), "coefficient", "coefficients"),
commasep(sQuote(smallnames[uhoh])),
"of model", ismal,
"to coefficients in model", ibig)
} else {
thetaDot <- 0 * coef(bigger)
thetaDot[injection] <- coef(smaller)
JH <- vcov(bigger, what="internals",
new.coef=thetaDot, fine=fine)
J <- if(!logi) JH$Sigma else (JH$Sigma1log+JH$Sigma2log)
H <- if(!logi) JH$A1 else JH$Slog
G <- H%*%solve(J)%*%H
if(df == 1) {
cfac[i] <- H[-injection,-injection]/G[-injection,-injection]
} else {
Res <- residuals(bigger, type="score",
new.coef=thetaDot, drop=TRUE)
U <- integral.msr(Res)
Uo <- U[-injection]
Uo <- matrix(Uo, ncol=1)
Hinv <- solve(H)
Ginv <- solve(G)
Hoo <- Hinv[-injection,-injection, drop=FALSE]
Goo <- Ginv[-injection,-injection, drop=FALSE]
HooUo <- Hoo %*% Uo
ScoreStat <- t(HooUo) %*% solve(Goo) %*% HooUo
cfac[i] <- ScoreStat/(t(HooUo) %*% Uo)
}
}
}
}
oldresult <- result
result$Deviance <- AdjDev <- result$Deviance * cfac
cn <- colnames(result)
colnames(result)[cn == "Deviance"] <- "AdjDeviance"
if("Pr(>Chi)" %in% colnames(result))
result[["Pr(>Chi)"]] <- c(NA, pchisq(abs(AdjDev[-1L]),
df=abs(result$Df[-1L]),
lower.tail=FALSE))
class(result) <- class(oldresult)
attr(result, "heading") <- attr(oldresult, "heading")
}
}
if(newton) {
cfa <- lapply(lapply(objex, getElement, name="covfunargs"), names)
cfa <- unique(unlist(cfa))
action <- if(adjust && gibbs) "Adjustment to composite likelihood" else
if(test == "Rao") "Score test calculation" else NULL
if(!is.null(action))
gripe(action, "does not account for",
"irregular trend parameters (covfunargs)",
commasep(sQuote(cfa)))
}
}
return(result)
}
refittosubset <- function(fut, sub) {
etf <- environment(terms(fut))
gd <- get("glmdata", envir=etf)
gd$.mpl.SUBSET <- sub
assign("glmdata", gd, envir=etf)
up <- update(fut, evaluate=FALSE)
eval(up, envir=etf)
}
anova.ppm
})
|
library(logmult)
data(occupationalStatus)
occupationalStatus[5,]<-colSums(occupationalStatus[5:6,])
occupationalStatus[,5]<-rowSums(occupationalStatus[,5:6])
occupationalStatus <- occupationalStatus[-6,-6]
model <- rc(occupationalStatus, diagonal=TRUE, symmetric=TRUE, weighting="none", start=NA)
stopifnot(round(model$assoc$phi[1,1], d=3) == 6.10)
stopifnot(isTRUE(all.equal(round(c(model$assoc$row), d=3),
c(0.532, 0.438, 0.206, -0.031,
-0.216, -0.426, -0.503))))
model <- rc(occupationalStatus, diagonal=TRUE, symmetric=TRUE, weighting="uniform", start=NA)
stopifnot(round(model$assoc$phi[1,1], d=3) == 0.871)
stopifnot(isTRUE(all.equal(round(c(model$assoc$row), d=3),
c(1.409, 1.159, 0.544, -0.082,
-0.571, -1.127, -1.332))))
|
bcontSurvG_extended <- function(params, respvec, VC, ps, AT = FALSE){
p1 <- p2 <- pdf1 <- pdf2 <- c.copula.be2 <- c.copula.be1 <- c.copula2.be1be2 <- NA
monP <- monP1 <- k1 <- k2 <- 0; Veq1 <- Veq2 <- list()
monP2 <- matrix(0, length(params),length(params))
rotConst <- 1
params1 <- params[1:VC$X1.d2]
params2 <- params[(VC$X1.d2 + 1):(VC$X1.d2 + VC$X2.d2)]
params1[VC$mono.sm.pos1] <- exp( params1[VC$mono.sm.pos1] )
params2[VC$mono.sm.pos2] <- exp( params2[VC$mono.sm.pos2] )
eta1 <- VC$X1%*%params1
eta2 <- VC$X2%*%params2
eta1.2 <- VC$X1.2%*%params1
eta2.2 <- VC$X2.2%*%params2
etad <- etas1 <- etas2 <- l.ln <- NULL
Xd1P <- VC$Xd1%*%params1
Xd2P <- VC$Xd2%*%params2
etad <- etas1 <- etas2 <- l.ln <- NULL
if( is.null(VC$X3) ){
X3 <- matrix(1, VC$n, 1)
teta.st <- etad <- params[(VC$X1.d2 + VC$X2.d2 + 1)]
}
if( !is.null(VC$X3) ){
X3 <- VC$X3
teta.st <- etad <- X3%*%params[(VC$X1.d2 + VC$X2.d2 + 1):(VC$X1.d2 + VC$X2.d2 + VC$X3.d2)]
}
indNeq1 <- as.numeric(Xd1P < 0)
indNeq2 <- as.numeric(Xd2P < 0)
Xd1P <- ifelse(Xd1P < VC$min.dn, VC$min.dn, Xd1P )
Xd2P <- ifelse(Xd2P < VC$min.dn, VC$min.dn, Xd2P )
resT <- teta.tr(VC, teta.st)
teta.st1 <- teta.st2 <- teta.st <- resT$teta.st
teta1 <- teta2 <- teta <- resT$teta
Cop1 <- Cop2 <- VC$BivD
nC1 <- nC2 <- VC$nC
teta.ind1 <- as.logical(c(1,0,round(runif(VC$n-2))) )
teta.ind2 <- teta.ind1 == FALSE
if(!(VC$BivD %in% VC$BivD2) && length(teta.st) > 1){
teta.st1 <- teta.st[teta.ind1]
teta.st2 <- teta.st[teta.ind2]
teta1 <- teta[teta.ind1]
teta2 <- teta[teta.ind2]
}
if(VC$BivD %in% VC$BivD2){
if(VC$BivD %in% VC$BivD2[c(1:4,13:16)]) teta.ind1 <- ifelse(VC$my.env$signind*teta > exp(VC$zerov), TRUE, FALSE)
if(VC$BivD %in% VC$BivD2[5:12]) teta.ind1 <- ifelse(VC$my.env$signind*teta > exp(VC$zerov) + 1, TRUE, FALSE)
teta.ind2 <- teta.ind1 == FALSE
VC$my.env$signind <- ifelse(teta.ind1 == TRUE, 1, -1)
teta1 <- teta[teta.ind1]
teta2 <- -teta[teta.ind2]
teta.st1 <- teta.st[teta.ind1]
teta.st2 <- teta.st[teta.ind2]
if(length(teta) == 1) teta.ind2 <- teta.ind1 <- rep(TRUE, VC$n)
Cop1Cop2R <- Cop1Cop2(VC$BivD)
Cop1 <- Cop1Cop2R$Cop1
Cop2 <- Cop1Cop2R$Cop2
nC1 <- VC$ct[which(VC$ct[,1] == Cop1),2]
nC2 <- VC$ct[which(VC$ct[,1] == Cop2),2]
}
pd1 <- probmS(eta1, VC$margins[1], min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)
pd2 <- probmS(eta2, VC$margins[2], min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)
pd1.2 <- probmS(eta1.2, VC$margins[1], min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)
pd2.2 <- probmS(eta2.2, VC$margins[2], min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)
p1 <- pd1$pr
p2 <- pd2$pr
p1.2 <- pd1.2$pr
p2.2 <- pd2.2$pr
dS1eta1 <- pd1$dS
dS2eta2 <- pd2$dS
dS1eta1.2 <- pd1.2$dS
dS2eta2.2 <- pd2.2$dS
d2S1eta1 <- pd1$d2S
d2S2eta2 <- pd2$d2S
d2S1eta1.2 <- pd1.2$d2S
d2S2eta2.2 <- pd2.2$d2S
d3S1eta1 <- pd1$d3S
d3S2eta2 <- pd2$d3S
d3S1eta1.2 <- pd1.2$d3S
d3S2eta2.2 <- pd2.2$d3S
if( length(teta1) != 0) dH1 <- copgHs(p1[teta.ind1], p2[teta.ind1], eta1=NULL, eta2=NULL, teta1, teta.st1, Cop1, VC$dof, min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)
if( length(teta2) != 0) dH2 <- copgHs(p1[teta.ind2], p2[teta.ind2], eta1=NULL, eta2=NULL, teta2, teta.st2, Cop2, VC$dof, min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)
if( length(teta1) != 0) dH1.2 <- copgHs(p1.2[teta.ind1], p2.2[teta.ind1], eta1=NULL, eta2=NULL, teta1, teta.st1, Cop1, VC$dof, min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)
if( length(teta2) != 0) dH2.2 <- copgHs(p1.2[teta.ind2], p2.2[teta.ind2], eta1=NULL, eta2=NULL, teta2, teta.st2, Cop2, VC$dof, min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)
if( length(teta1) != 0) dH1.mix1 <- copgHs(p1[teta.ind1], p2.2[teta.ind1], eta1=NULL, eta2=NULL, teta1, teta.st1, Cop1, VC$dof, min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)
if( length(teta2) != 0) dH2.mix1 <- copgHs(p1[teta.ind2], p2.2[teta.ind2], eta1=NULL, eta2=NULL, teta2, teta.st2, Cop2, VC$dof, min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)
if( length(teta1) != 0) dH1.mix2 <- copgHs(p1.2[teta.ind1], p2[teta.ind1], eta1=NULL, eta2=NULL, teta1, teta.st1, Cop1, VC$dof, min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)
if( length(teta2) != 0) dH2.mix2 <- copgHs(p1.2[teta.ind2], p2[teta.ind2], eta1=NULL, eta2=NULL, teta2, teta.st2, Cop2, VC$dof, min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)
c.copula2.be1be2 <- c.copula.be1 <- c.copula.be2 <- p00 <- c.copula.theta <- c.copula.thet <- bit1.th2ATE <- NA
c.copula2.be1be2.2 <- c.copula.be1.2 <- c.copula.be2.2 <- p00.2 <- c.copula.theta.2 <- c.copula.thet.2 <- bit1.th2ATE.2 <- NA
c.copula2.be1be2.mix1 <- c.copula.be1.mix1 <- c.copula.be2.mix1 <- p00.mix1 <- c.copula.theta.mix1 <- c.copula.thet.mix1 <- bit1.th2ATE.mix1 <- NA
c.copula2.be1be2.mix2 <- c.copula.be1.mix2 <- c.copula.be2.mix2 <- p00.mix2 <- c.copula.theta.mix2 <- c.copula.thet.mix2 <- bit1.th2ATE.mix2 <- NA
if( length(teta1) != 0){
c.copula2.be1be2[teta.ind1] <- dH1$c.copula2.be1be2
c.copula.be1[teta.ind1] <- dH1$c.copula.be1
c.copula.be2[teta.ind1] <- dH1$c.copula.be2
c.copula.theta[teta.ind1] <- dH1$c.copula.theta
c.copula.thet[teta.ind1] <- dH1$c.copula.thet
bit1.th2ATE[teta.ind1] <- dH1$bit1.th2ATE
p00[teta.ind1] <- mm(BiCDF(p1[teta.ind1], p2[teta.ind1], nC1, teta1, VC$dof), min.pr = VC$min.pr, max.pr = VC$max.pr )
}
if( length(teta1) != 0){
c.copula2.be1be2.mix1[teta.ind1] <- dH1.mix1$c.copula2.be1be2
c.copula.be1.mix1[teta.ind1] <- dH1.mix1$c.copula.be1
c.copula.be2.mix1[teta.ind1] <- dH1.mix1$c.copula.be2
c.copula.theta.mix1[teta.ind1] <- dH1.mix1$c.copula.theta
c.copula.thet.mix1[teta.ind1] <- dH1.mix1$c.copula.thet
bit1.th2ATE.mix1[teta.ind1] <- dH1.mix1$bit1.th2ATE
p00.mix1[teta.ind1] <- mm(BiCDF(p1[teta.ind1], p2.2[teta.ind1], nC1, teta1, VC$dof), min.pr = VC$min.pr, max.pr = VC$max.pr )
}
if( length(teta1) != 0){
c.copula2.be1be2.mix2[teta.ind1] <- dH1.mix2$c.copula2.be1be2
c.copula.be1.mix2[teta.ind1] <- dH1.mix2$c.copula.be1
c.copula.be2.mix2[teta.ind1] <- dH1.mix2$c.copula.be2
c.copula.theta.mix2[teta.ind1] <- dH1.mix2$c.copula.theta
c.copula.thet.mix2[teta.ind1] <- dH1.mix2$c.copula.thet
bit1.th2ATE.mix2[teta.ind1] <- dH1.mix2$bit1.th2ATE
p00.mix2[teta.ind1] <- mm(BiCDF(p1.2[teta.ind1], p2[teta.ind1], nC1, teta1, VC$dof), min.pr = VC$min.pr, max.pr = VC$max.pr )
}
if( length(teta1) != 0){
c.copula2.be1be2.2[teta.ind1] <- dH1.2$c.copula2.be1be2
c.copula.be1.2[teta.ind1] <- dH1.2$c.copula.be1
c.copula.be2.2[teta.ind1] <- dH1.2$c.copula.be2
c.copula.theta.2[teta.ind1] <- dH1.2$c.copula.theta
c.copula.thet.2[teta.ind1] <- dH1.2$c.copula.thet
bit1.th2ATE.2[teta.ind1] <- dH1.2$bit1.th2ATE
p00.2[teta.ind1] <- mm(BiCDF(p1.2[teta.ind1], p2.2[teta.ind1], nC1, teta1, VC$dof), min.pr = VC$min.pr, max.pr = VC$max.pr )
}
if( length(teta2) != 0){
c.copula2.be1be2[teta.ind2] <- dH2$c.copula2.be1be2
c.copula.be1[teta.ind2] <- dH2$c.copula.be1
c.copula.be2[teta.ind2] <- dH2$c.copula.be2
c.copula.theta[teta.ind2] <- dH2$c.copula.theta
c.copula.thet[teta.ind2] <- dH2$c.copula.thet
bit1.th2ATE[teta.ind2] <- dH2$bit1.th2ATE
p00[teta.ind2] <- mm(BiCDF(p1[teta.ind2], p2[teta.ind2], nC2, teta2, VC$dof), min.pr = VC$min.pr, max.pr = VC$max.pr )
}
if( length(teta2) != 0){
c.copula2.be1be2.mix1[teta.ind2] <- dH2.mix1$c.copula2.be1be2
c.copula.be1.mix1[teta.ind2] <- dH2.mix1$c.copula.be1
c.copula.be2.mix1[teta.ind2] <- dH2.mix1$c.copula.be2
c.copula.theta.mix1[teta.ind2] <- dH2.mix1$c.copula.theta
c.copula.thet.mix1[teta.ind2] <- dH2.mix1$c.copula.thet
bit1.th2ATE.mix1[teta.ind2] <- dH2.mix1$bit1.th2ATE
p00.mix1[teta.ind2] <- mm(BiCDF(p1[teta.ind2], p2.2[teta.ind2], nC2, teta2, VC$dof), min.pr = VC$min.pr, max.pr = VC$max.pr )
}
if( length(teta2) != 0){
c.copula2.be1be2.mix2[teta.ind2] <- dH2.mix2$c.copula2.be1be2
c.copula.be1.mix2[teta.ind2] <- dH2.mix2$c.copula.be1
c.copula.be2.mix2[teta.ind2] <- dH2.mix2$c.copula.be2
c.copula.theta.mix2[teta.ind2] <- dH2.mix2$c.copula.theta
c.copula.thet.mix2[teta.ind2] <- dH2.mix2$c.copula.thet
bit1.th2ATE.mix2[teta.ind2] <- dH2.mix2$bit1.th2ATE
p00.mix2[teta.ind2] <- mm(BiCDF(p1.2[teta.ind2], p2[teta.ind2], nC2, teta2, VC$dof), min.pr = VC$min.pr, max.pr = VC$max.pr )
}
if( length(teta2) != 0){
c.copula2.be1be2.2[teta.ind2] <- dH2.2$c.copula2.be1be2
c.copula.be1.2[teta.ind2] <- dH2.2$c.copula.be1
c.copula.be2.2[teta.ind2] <- dH2.2$c.copula.be2
c.copula.theta.2[teta.ind2] <- dH2.2$c.copula.theta
c.copula.thet.2[teta.ind2] <- dH2.2$c.copula.thet
bit1.th2ATE.2[teta.ind2] <- dH2.2$bit1.th2ATE
p00.2[teta.ind2] <- mm(BiCDF(p1.2[teta.ind2], p2.2[teta.ind2], nC2, teta2, VC$dof), min.pr = VC$min.pr, max.pr = VC$max.pr )
}
der.par1 <- der2.par1 <- params1; der.par2 <- der2.par2 <- params2
der.par1[-c( VC$mono.sm.pos1 )] <- 1
der.par2[-c( VC$mono.sm.pos2 )] <- 1
der2.par1[-c( VC$mono.sm.pos1 )] <- 0
der2.par2[-c( VC$mono.sm.pos2 )] <- 0
der2eta1dery1b1 <- t(t(VC$Xd1)*der.par1)
der2eta2dery2b2 <- t(t(VC$Xd2)*der.par2)
dereta1derb1 <- t(t(VC$X1)*der.par1)
dereta2derb2 <- t(t(VC$X2)*der.par2)
dereta1derb1.2 <- t(t(VC$X1.2)*der.par1)
dereta2derb2.2 <- t(t(VC$X2.2)*der.par2)
if( length(teta1) != 0) BITS1 <- copgHsCont(p1[teta.ind1], p2[teta.ind1], teta1, teta.st1, Cop1, Cont = TRUE, par2 = VC$dof, nu.st = log(VC$dof - 2))
if( length(teta2) != 0) BITS2 <- copgHsCont(p1[teta.ind2], p2[teta.ind2], teta2, teta.st2, Cop2, Cont = TRUE, par2 = VC$dof, nu.st = log(VC$dof - 2))
if( length(teta1) != 0) BITS1.mix1 <- copgHsCont(p1[teta.ind1], p2.2[teta.ind1], teta1, teta.st1, Cop1, Cont = TRUE, par2 = VC$dof, nu.st = log(VC$dof - 2))
if( length(teta2) != 0) BITS2.mix1 <- copgHsCont(p1[teta.ind2], p2.2[teta.ind2], teta2, teta.st2, Cop2, Cont = TRUE, par2 = VC$dof, nu.st = log(VC$dof - 2))
if( length(teta1) != 0) BITS1.mix2 <- copgHsCont(p1.2[teta.ind1], p2[teta.ind1], teta1, teta.st1, Cop1, Cont = TRUE, par2 = VC$dof, nu.st = log(VC$dof - 2))
if( length(teta2) != 0) BITS2.mix2 <- copgHsCont(p1.2[teta.ind2], p2[teta.ind2], teta2, teta.st2, Cop2, Cont = TRUE, par2 = VC$dof, nu.st = log(VC$dof - 2))
if( length(teta1) != 0) BITS1.2 <- copgHsCont(p1.2[teta.ind1], p2.2[teta.ind1], teta1, teta.st1, Cop1, Cont = TRUE, par2 = VC$dof, nu.st = log(VC$dof - 2))
if( length(teta2) != 0) BITS2.2 <- copgHsCont(p1.2[teta.ind2], p2.2[teta.ind2], teta2, teta.st2, Cop2, Cont = TRUE, par2 = VC$dof, nu.st = log(VC$dof - 2))
der2h.derp1p1 <- NA
if( length(teta1) != 0) der2h.derp1p1[teta.ind1] <- BITS1$der2h.derp1p1
if( length(teta2) != 0) der2h.derp1p1[teta.ind2] <- BITS2$der2h.derp1p1
der2h.derp1p1.mix1 <- NA
if( length(teta1) != 0) der2h.derp1p1.mix1[teta.ind1] <- BITS1.mix1$der2h.derp1p1
if( length(teta2) != 0) der2h.derp1p1.mix1[teta.ind2] <- BITS2.mix1$der2h.derp1p1
der2h.derp1p1.mix2 <- NA
if( length(teta1) != 0) der2h.derp1p1.mix2[teta.ind1] <- BITS1.mix2$der2h.derp1p1
if( length(teta2) != 0) der2h.derp1p1.mix2[teta.ind2] <- BITS2.mix2$der2h.derp1p1
der2h.derp1p1.2 <- NA
if( length(teta1) != 0) der2h.derp1p1.2[teta.ind1] <- BITS1.2$der2h.derp1p1
if( length(teta2) != 0) der2h.derp1p1.2[teta.ind2] <- BITS2.2$der2h.derp1p1
der2h.derp1p2 <- NA
if( length(teta1) != 0) der2h.derp1p2[teta.ind1] <- BITS1$der2h.derp1p2
if( length(teta2) != 0) der2h.derp1p2[teta.ind2] <- BITS2$der2h.derp1p2
der2h.derp1p2.mix1 <- NA
if( length(teta1) != 0) der2h.derp1p2.mix1[teta.ind1] <- BITS1.mix1$der2h.derp1p2
if( length(teta2) != 0) der2h.derp1p2.mix1[teta.ind2] <- BITS2.mix1$der2h.derp1p2
der2h.derp1p2.mix2 <- NA
if( length(teta1) != 0) der2h.derp1p2.mix2[teta.ind1] <- BITS1.mix2$der2h.derp1p2
if( length(teta2) != 0) der2h.derp1p2.mix2[teta.ind2] <- BITS2.mix2$der2h.derp1p2
der2h.derp1p2.2 <- NA
if( length(teta1) != 0) der2h.derp1p2.2[teta.ind1] <- BITS1.2$der2h.derp1p2
if( length(teta2) != 0) der2h.derp1p2.2[teta.ind2] <- BITS2.2$der2h.derp1p2
der2h.derp1teta <- NA
derteta.derteta.st <- NA
if( length(teta1) != 0) der2h.derp1teta[teta.ind1] <- BITS1$der2h.derp1teta
if( length(teta2) != 0) der2h.derp1teta[teta.ind2] <- BITS2$der2h.derp1teta
if( length(teta1) != 0) derteta.derteta.st[teta.ind1] <- BITS1$derteta.derteta.st
if( length(teta2) != 0) derteta.derteta.st[teta.ind2] <- BITS2$derteta.derteta.st
der2h.derp1teta.st <- der2h.derp1teta * derteta.derteta.st
der2h.derp1teta.mix1 <- NA
derteta.derteta.st.mix1 <- NA
if( length(teta1) != 0) der2h.derp1teta.mix1[teta.ind1] <- BITS1.mix1$der2h.derp1teta
if( length(teta2) != 0) der2h.derp1teta.mix1[teta.ind2] <- BITS2.mix1$der2h.derp1teta
if( length(teta1) != 0) derteta.derteta.st.mix1[teta.ind1] <- BITS1.mix1$derteta.derteta.st
if( length(teta2) != 0) derteta.derteta.st.mix1[teta.ind2] <- BITS2.mix1$derteta.derteta.st
der2h.derp1teta.st.mix1 <- der2h.derp1teta.mix1 * derteta.derteta.st.mix1
der2h.derp1teta.mix2 <- NA
derteta.derteta.st.mix2 <- NA
if( length(teta1) != 0) der2h.derp1teta.mix2[teta.ind1] <- BITS1.mix2$der2h.derp1teta
if( length(teta2) != 0) der2h.derp1teta.mix2[teta.ind2] <- BITS2.mix2$der2h.derp1teta
if( length(teta1) != 0) derteta.derteta.st.mix2[teta.ind1] <- BITS1.mix2$derteta.derteta.st
if( length(teta2) != 0) derteta.derteta.st.mix2[teta.ind2] <- BITS2.mix2$derteta.derteta.st
der2h.derp1teta.st.mix2 <- der2h.derp1teta.mix2 * derteta.derteta.st.mix2
der2h.derp1teta.2 <- NA
derteta.derteta.st.2 <- NA
if( length(teta1) != 0) der2h.derp1teta.2[teta.ind1] <- BITS1.2$der2h.derp1teta
if( length(teta2) != 0) der2h.derp1teta.2[teta.ind2] <- BITS2.2$der2h.derp1teta
if( length(teta1) != 0) derteta.derteta.st.2[teta.ind1] <- BITS1.2$derteta.derteta.st
if( length(teta2) != 0) derteta.derteta.st.2[teta.ind2] <- BITS2.2$derteta.derteta.st
der2h.derp1teta.st.2 <- der2h.derp1teta.2 * derteta.derteta.st.2
c.copula2.be1 <- c.copula2.be2 <- c.copula2.be1th <- c.copula2.be2th <- bit1.th2 <- c.copula2.be1t <- c.copula2.be2t <- NA
if( length(teta1) != 0){
c.copula2.be1[teta.ind1] <- dH1$c.copula2.be1
c.copula2.be2[teta.ind1] <- dH1$c.copula2.be2
c.copula2.be1th[teta.ind1] <- dH1$c.copula2.be1th
c.copula2.be2th[teta.ind1] <- dH1$c.copula2.be2th
c.copula2.be1t[teta.ind1] <- dH1$c.copula2.be1t
c.copula2.be2t[teta.ind1] <- dH1$c.copula2.be2t
bit1.th2[teta.ind1] <- dH1$bit1.th2
}
c.copula2.be1.mix1 <- c.copula2.be2.mix1 <- c.copula2.be1th.mix1 <- c.copula2.be2th.mix1 <- bit1.th2.mix1 <- c.copula2.be1t.mix1 <- c.copula2.be2t.mix1 <- NA
if( length(teta1) != 0){
c.copula2.be1.mix1[teta.ind1] <- dH1.mix1$c.copula2.be1
c.copula2.be2.mix1[teta.ind1] <- dH1.mix1$c.copula2.be2
c.copula2.be1th.mix1[teta.ind1] <- dH1.mix1$c.copula2.be1th
c.copula2.be2th.mix1[teta.ind1] <- dH1.mix1$c.copula2.be2th
c.copula2.be1t.mix1[teta.ind1] <- dH1.mix1$c.copula2.be1t
c.copula2.be2t.mix1[teta.ind1] <- dH1.mix1$c.copula2.be2t
bit1.th2.mix1[teta.ind1] <- dH1.mix1$bit1.th2
}
c.copula2.be1.mix2 <- c.copula2.be2.mix2 <- c.copula2.be1th.mix2 <- c.copula2.be2th.mix2 <- bit1.th2.mix2 <- c.copula2.be1t.mix2 <- c.copula2.be2t.mix2 <- NA
if( length(teta1) != 0){
c.copula2.be1.mix2[teta.ind1] <- dH1.mix2$c.copula2.be1
c.copula2.be2.mix2[teta.ind1] <- dH1.mix2$c.copula2.be2
c.copula2.be1th.mix2[teta.ind1] <- dH1.mix2$c.copula2.be1th
c.copula2.be2th.mix2[teta.ind1] <- dH1.mix2$c.copula2.be2th
c.copula2.be1t.mix2[teta.ind1] <- dH1.mix2$c.copula2.be1t
c.copula2.be2t.mix2[teta.ind1] <- dH1.mix2$c.copula2.be2t
bit1.th2.mix2[teta.ind1] <- dH1.mix2$bit1.th2
}
c.copula2.be1.2 <- c.copula2.be2.2 <- c.copula2.be1th.2 <- c.copula2.be2th.2 <- bit1.th2.2 <- c.copula2.be1t.2 <- c.copula2.be2t.2 <- NA
if( length(teta1) != 0){
c.copula2.be1.2[teta.ind1] <- dH1.2$c.copula2.be1
c.copula2.be2.2[teta.ind1] <- dH1.2$c.copula2.be2
c.copula2.be1th.2[teta.ind1] <- dH1.2$c.copula2.be1th
c.copula2.be2th.2[teta.ind1] <- dH1.2$c.copula2.be2th
c.copula2.be1t.2[teta.ind1] <- dH1.2$c.copula2.be1t
c.copula2.be2t.2[teta.ind1] <- dH1.2$c.copula2.be2t
bit1.th2.2[teta.ind1] <- dH1.2$bit1.th2
}
if( length(teta2) != 0){
c.copula2.be1[teta.ind2] <- dH2$c.copula2.be1
c.copula2.be2[teta.ind2] <- dH2$c.copula2.be2
c.copula2.be1th[teta.ind2] <- dH2$c.copula2.be1th
c.copula2.be2th[teta.ind2] <- dH2$c.copula2.be2th
c.copula2.be1t[teta.ind2] <- dH2$c.copula2.be1t
c.copula2.be2t[teta.ind2] <- dH2$c.copula2.be2t
bit1.th2[teta.ind2] <- dH2$bit1.th2
}
if( length(teta2) != 0){
c.copula2.be1.mix1[teta.ind2] <- dH2.mix1$c.copula2.be1
c.copula2.be2.mix1[teta.ind2] <- dH2.mix1$c.copula2.be2
c.copula2.be1th.mix1[teta.ind2] <- dH2.mix1$c.copula2.be1th
c.copula2.be2th.mix1[teta.ind2] <- dH2.mix1$c.copula2.be2th
c.copula2.be1t.mix1[teta.ind2] <- dH2.mix1$c.copula2.be1t
c.copula2.be2t.mix1[teta.ind2] <- dH2.mix1$c.copula2.be2t
bit1.th2.mix1[teta.ind2] <- dH2.mix1$bit1.th2
}
if( length(teta2) != 0){
c.copula2.be1.mix2[teta.ind2] <- dH2.mix2$c.copula2.be1
c.copula2.be2.mix2[teta.ind2] <- dH2.mix2$c.copula2.be2
c.copula2.be1th.mix2[teta.ind2] <- dH2.mix2$c.copula2.be1th
c.copula2.be2th.mix2[teta.ind2] <- dH2.mix2$c.copula2.be2th
c.copula2.be1t.mix2[teta.ind2] <- dH2.mix2$c.copula2.be1t
c.copula2.be2t.mix2[teta.ind2] <- dH2.mix2$c.copula2.be2t
bit1.th2.mix2[teta.ind2] <- dH2.mix2$bit1.th2
}
if( length(teta2) != 0){
c.copula2.be1.2[teta.ind2] <- dH2.2$c.copula2.be1
c.copula2.be2.2[teta.ind2] <- dH2.2$c.copula2.be2
c.copula2.be1th.2[teta.ind2] <- dH2.2$c.copula2.be1th
c.copula2.be2th.2[teta.ind2] <- dH2.2$c.copula2.be2th
c.copula2.be1t.2[teta.ind2] <- dH2.2$c.copula2.be1t
c.copula2.be2t.2[teta.ind2] <- dH2.2$c.copula2.be2t
bit1.th2.2[teta.ind2] <- dH2.2$bit1.th2
}
der2c.derrho.derrho <- NA
der2c.derp1.derp1 <- NA
der2c.derp2.derp2 <- NA
der2c.derp1.derp2 <- NA
der2c.derp1.derrho <- NA
der2c.derp2.derrho <- NA
der2teta.derteta.stteta.st <- NA
if( length(teta1) != 0){
der2c.derrho.derrho[teta.ind1] <- BITS1$der2c.derrho.derrho
der2c.derp1.derp1[teta.ind1] <- BITS1$der2c.derp1.derp1
der2c.derp2.derp2[teta.ind1] <- BITS1$der2c.derp2.derp2
der2c.derp1.derp2[teta.ind1] <- BITS1$der2c.derp1.derp2
der2c.derp1.derrho[teta.ind1] <- BITS1$der2c.derp1.derrho
der2c.derp2.derrho[teta.ind1] <- BITS1$der2c.derp2.derrho
}
der2c.derrho.derrho.mix1 <- NA
der2c.derp1.derp1.mix1 <- NA
der2c.derp2.derp2.mix1 <- NA
der2c.derp1.derp2.mix1 <- NA
der2c.derp1.derrho.mix1 <- NA
der2c.derp2.derrho.mix1 <- NA
der2teta.derteta.stteta.st.mix1 <- NA
if( length(teta1) != 0){
der2c.derrho.derrho.mix1[teta.ind1] <- BITS1.mix1$der2c.derrho.derrho
der2c.derp1.derp1.mix1[teta.ind1] <- BITS1.mix1$der2c.derp1.derp1
der2c.derp2.derp2.mix1[teta.ind1] <- BITS1.mix1$der2c.derp2.derp2
der2c.derp1.derp2.mix1[teta.ind1] <- BITS1.mix1$der2c.derp1.derp2
der2c.derp1.derrho.mix1[teta.ind1] <- BITS1.mix1$der2c.derp1.derrho
der2c.derp2.derrho.mix1[teta.ind1] <- BITS1.mix1$der2c.derp2.derrho
}
der2c.derrho.derrho.mix2 <- NA
der2c.derp1.derp1.mix2 <- NA
der2c.derp2.derp2.mix2 <- NA
der2c.derp1.derp2.mix2 <- NA
der2c.derp1.derrho.mix2 <- NA
der2c.derp2.derrho.mix2 <- NA
der2teta.derteta.stteta.st.mix2 <- NA
if( length(teta1) != 0){
der2c.derrho.derrho.mix2[teta.ind1] <- BITS1.mix2$der2c.derrho.derrho
der2c.derp1.derp1.mix2[teta.ind1] <- BITS1.mix2$der2c.derp1.derp1
der2c.derp2.derp2.mix2[teta.ind1] <- BITS1.mix2$der2c.derp2.derp2
der2c.derp1.derp2.mix2[teta.ind1] <- BITS1.mix2$der2c.derp1.derp2
der2c.derp1.derrho.mix2[teta.ind1] <- BITS1.mix2$der2c.derp1.derrho
der2c.derp2.derrho.mix2[teta.ind1] <- BITS1.mix2$der2c.derp2.derrho
}
der2c.derrho.derrho.2 <- NA
der2c.derp1.derp1.2 <- NA
der2c.derp2.derp2.2 <- NA
der2c.derp1.derp2.2 <- NA
der2c.derp1.derrho.2 <- NA
der2c.derp2.derrho.2 <- NA
der2teta.derteta.stteta.st.2 <- NA
if( length(teta1) != 0){
der2c.derrho.derrho.2[teta.ind1] <- BITS1.2$der2c.derrho.derrho
der2c.derp1.derp1.2[teta.ind1] <- BITS1.2$der2c.derp1.derp1
der2c.derp2.derp2.2[teta.ind1] <- BITS1.2$der2c.derp2.derp2
der2c.derp1.derp2.2[teta.ind1] <- BITS1.2$der2c.derp1.derp2
der2c.derp1.derrho.2[teta.ind1] <- BITS1.2$der2c.derp1.derrho
der2c.derp2.derrho.2[teta.ind1] <- BITS1.2$der2c.derp2.derrho
}
if( length(teta2) != 0){
der2c.derrho.derrho[teta.ind2] <- BITS2$der2c.derrho.derrho
der2c.derp1.derp1[teta.ind2] <- BITS2$der2c.derp1.derp1
der2c.derp2.derp2[teta.ind2] <- BITS2$der2c.derp2.derp2
der2c.derp1.derp2[teta.ind2] <- BITS2$der2c.derp1.derp2
der2c.derp1.derrho[teta.ind2] <- BITS2$der2c.derp1.derrho
der2c.derp2.derrho[teta.ind2] <- BITS2$der2c.derp2.derrho
}
if( length(teta2) != 0){
der2c.derrho.derrho.mix1[teta.ind2] <- BITS2.mix1$der2c.derrho.derrho
der2c.derp1.derp1.mix1[teta.ind2] <- BITS2.mix1$der2c.derp1.derp1
der2c.derp2.derp2.mix1[teta.ind2] <- BITS2.mix1$der2c.derp2.derp2
der2c.derp1.derp2.mix1[teta.ind2] <- BITS2.mix1$der2c.derp1.derp2
der2c.derp1.derrho.mix1[teta.ind2] <- BITS2.mix1$der2c.derp1.derrho
der2c.derp2.derrho.mix1[teta.ind2] <- BITS2.mix1$der2c.derp2.derrho
}
if( length(teta2) != 0){
der2c.derrho.derrho.mix2[teta.ind2] <- BITS2.mix2$der2c.derrho.derrho
der2c.derp1.derp1.mix2[teta.ind2] <- BITS2.mix2$der2c.derp1.derp1
der2c.derp2.derp2.mix2[teta.ind2] <- BITS2.mix2$der2c.derp2.derp2
der2c.derp1.derp2.mix2[teta.ind2] <- BITS2.mix2$der2c.derp1.derp2
der2c.derp1.derrho.mix2[teta.ind2] <- BITS2.mix2$der2c.derp1.derrho
der2c.derp2.derrho.mix2[teta.ind2] <- BITS2.mix2$der2c.derp2.derrho
}
if( length(teta2) != 0){
der2c.derrho.derrho.2[teta.ind2] <- BITS2.2$der2c.derrho.derrho
der2c.derp1.derp1.2[teta.ind2] <- BITS2.2$der2c.derp1.derp1
der2c.derp2.derp2.2[teta.ind2] <- BITS2.2$der2c.derp2.derp2
der2c.derp1.derp2.2[teta.ind2] <- BITS2.2$der2c.derp1.derp2
der2c.derp1.derrho.2[teta.ind2] <- BITS2.2$der2c.derp1.derrho
der2c.derp2.derrho.2[teta.ind2] <- BITS2.2$der2c.derp2.derrho
}
if( length(teta1) != 0) der2teta.derteta.stteta.st[teta.ind1] <- BITS1$der2teta.derteta.stteta.st
if( length(teta1) != 0) der2teta.derteta.stteta.st.mix1[teta.ind1] <- BITS1.mix1$der2teta.derteta.stteta.st
if( length(teta1) != 0) der2teta.derteta.stteta.st.mix2[teta.ind1] <- BITS1.mix2$der2teta.derteta.stteta.st
if( length(teta1) != 0) der2teta.derteta.stteta.st.2[teta.ind1] <- BITS1.2$der2teta.derteta.stteta.st
if( length(teta2) != 0) der2teta.derteta.stteta.st[teta.ind2] <- BITS2$der2teta.derteta.stteta.st
if( length(teta2) != 0) der2teta.derteta.stteta.st.mix1[teta.ind2] <- BITS2.mix1$der2teta.derteta.stteta.st
if( length(teta2) != 0) der2teta.derteta.stteta.st.mix2[teta.ind2] <- BITS2.mix2$der2teta.derteta.stteta.st
if( length(teta2) != 0) der2teta.derteta.stteta.st.2[teta.ind2] <- BITS2.2$der2teta.derteta.stteta.st
der3C.derp1p1p1 <- der3C.derp1tetateta <- der2h.derteta.teta.st <- der3C.p1p1teta <- der2h.derp2teta <- der2h.derp2p2 <- NA
der3C.derp1p1p1.mix1 <- der3C.derp1tetateta.mix1 <- der2h.derteta.teta.st.mix1 <- der3C.p1p1teta.mix1 <- der2h.derp2teta.mix1 <- der2h.derp2p2.mix1 <- NA
der3C.derp1p1p1.mix2 <- der3C.derp1tetateta.mix2 <- der2h.derteta.teta.st.mix2 <- der3C.p1p1teta.mix2 <- der2h.derp2teta.mix2 <- der2h.derp2p2.mix2 <- NA
der3C.derp1p1p1.2 <- der3C.derp1tetateta.2 <- der2h.derteta.teta.st.2 <- der3C.p1p1teta.2 <- der2h.derp2teta.2 <- der2h.derp2p2.2 <- NA
if( length(teta1) != 0){der3C.derp1p1p1[teta.ind1] <- BITS1$der3C.derp1p1p1
der2h.derteta.teta.st[teta.ind1] <- BITS1$der2h.derteta.teta.st
der3C.derp1tetateta[teta.ind1] <- BITS1$der3C.derp1tetateta
der3C.p1p1teta[teta.ind1] <- BITS1$der3C.p1p1teta
der2h.derp2teta[teta.ind1] <- BITS1$der2h.derp2teta
der2h.derp2p2[teta.ind1] <- BITS1$der2h.derp2p2
der2h.derp1teta[teta.ind1] <- BITS1$der2h.derp1teta
}
if( length(teta1) != 0){
der3C.derp1p1p1.mix1[teta.ind1] <- BITS1.mix1$der3C.derp1p1p1
der2h.derteta.teta.st.mix1[teta.ind1] <- BITS1.mix1$der2h.derteta.teta.st
der3C.derp1tetateta.mix1[teta.ind1] <- BITS1.mix1$der3C.derp1tetateta
der3C.p1p1teta.mix1[teta.ind1] <- BITS1.mix1$der3C.p1p1teta
der2h.derp2teta.mix1[teta.ind1] <- BITS1.mix1$der2h.derp2teta
der2h.derp2p2.mix1[teta.ind1] <- BITS1.mix1$der2h.derp2p2
der2h.derp1teta.mix1[teta.ind1] <- BITS1.mix1$der2h.derp1teta
}
if( length(teta1) != 0){
der3C.derp1p1p1.mix2[teta.ind1] <- BITS1.mix2$der3C.derp1p1p1
der2h.derteta.teta.st.mix2[teta.ind1] <- BITS1.mix2$der2h.derteta.teta.st
der3C.derp1tetateta.mix2[teta.ind1] <- BITS1.mix2$der3C.derp1tetateta
der3C.p1p1teta.mix2[teta.ind1] <- BITS1.mix2$der3C.p1p1teta
der2h.derp2teta.mix2[teta.ind1] <- BITS1.mix2$der2h.derp2teta
der2h.derp2p2.mix2[teta.ind1] <- BITS1.mix2$der2h.derp2p2
der2h.derp1teta.mix2[teta.ind1] <- BITS1.mix2$der2h.derp1teta
}
if( length(teta1) != 0){
der3C.derp1p1p1.2[teta.ind1] <- BITS1.2$der3C.derp1p1p1
der2h.derteta.teta.st.2[teta.ind1] <- BITS1.2$der2h.derteta.teta.st
der3C.derp1tetateta.2[teta.ind1] <- BITS1.2$der3C.derp1tetateta
der3C.p1p1teta.2[teta.ind1] <- BITS1.2$der3C.p1p1teta
der2h.derp2teta.2[teta.ind1] <- BITS1.2$der2h.derp2teta
der2h.derp2p2.2[teta.ind1] <- BITS1.2$der2h.derp2p2
der2h.derp1teta.2[teta.ind1] <- BITS1.2$der2h.derp1teta
}
if( length(teta2) != 0){
der3C.derp1p1p1[teta.ind2] <- BITS2$der3C.derp1p1p1
der2h.derteta.teta.st[teta.ind2] <- BITS2$der2h.derteta.teta.st
der3C.derp1tetateta[teta.ind2] <- BITS2$der3C.derp1tetateta
der3C.p1p1teta[teta.ind2] <- BITS2$der3C.p1p1teta
der2h.derp2teta[teta.ind2] <- BITS2$der2h.derp2teta
der2h.derp2p2[teta.ind2] <- BITS2$der2h.derp2p2
der2h.derp1teta[teta.ind2] <- BITS2$der2h.derp1teta
}
if( length(teta2) != 0){
der3C.derp1p1p1.mix1[teta.ind2] <- BITS2.mix1$der3C.derp1p1p1
der2h.derteta.teta.st.mix1[teta.ind2] <- BITS2.mix1$der2h.derteta.teta.st
der3C.derp1tetateta.mix1[teta.ind2] <- BITS2.mix1$der3C.derp1tetateta
der3C.p1p1teta.mix1[teta.ind2] <- BITS2.mix1$der3C.p1p1teta
der2h.derp2teta.mix1[teta.ind2] <- BITS2.mix1$der2h.derp2teta
der2h.derp2p2.mix1[teta.ind2] <- BITS2.mix1$der2h.derp2p2
der2h.derp1teta.mix1[teta.ind2] <- BITS2.mix1$der2h.derp1teta
}
if( length(teta2) != 0){
der3C.derp1p1p1.mix2[teta.ind2] <- BITS2.mix2$der3C.derp1p1p1
der2h.derteta.teta.st.mix2[teta.ind2] <- BITS2.mix2$der2h.derteta.teta.st
der3C.derp1tetateta.mix2[teta.ind2] <- BITS2.mix2$der3C.derp1tetateta
der3C.p1p1teta.mix2[teta.ind2] <- BITS2.mix2$der3C.p1p1teta
der2h.derp2teta.mix2[teta.ind2] <- BITS2.mix2$der2h.derp2teta
der2h.derp2p2.mix2[teta.ind2] <- BITS2.mix2$der2h.derp2p2
der2h.derp1teta.mix2[teta.ind2] <- BITS2.mix2$der2h.derp1teta
}
if( length(teta2) != 0){
der3C.derp1p1p1.2[teta.ind2] <- BITS2.2$der3C.derp1p1p1
der2h.derteta.teta.st.2[teta.ind2] <- BITS2.2$der2h.derteta.teta.st
der3C.derp1tetateta.2[teta.ind2] <- BITS2.2$der3C.derp1tetateta
der3C.p1p1teta.2[teta.ind2] <- BITS2.2$der3C.p1p1teta
der2h.derp2teta.2[teta.ind2] <- BITS2.2$der2h.derp2teta
der2h.derp2p2.2[teta.ind2] <- BITS2.2$der2h.derp2p2
der2h.derp1teta.2[teta.ind2] <- BITS2.2$der2h.derp1teta
}
likelihood <- 0
G <- 0
H <- 0
if(sum(VC$indUU)>1){
l.par <- VC$weights*( VC$indUU*( log(c.copula2.be1be2) + log(-dS1eta1) + log(-dS2eta2) + log(Xd1P) + log(Xd2P) ))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*(VC$indUU*(c(c.copula2.be1be2^(-1)*der2h.derp1p1*dS1eta1) * dereta1derb1+
c(dS1eta1^(-1)*d2S1eta1)*dereta1derb1
+c(Xd1P)^(-1)* der2eta1dery1b1
))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*(VC$indUU*(c(c.copula2.be1be2^(-1)*der2h.derp1p2*dS2eta2)*dereta2derb2+
c((dS2eta2)^(-1)*d2S2eta2)*dereta2derb2
+c(Xd2P)^(-1)*der2eta2dery2b2
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*(VC$indUU*(c.copula2.be1be2^(-1)*der2h.derp1teta.st
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indUU*c(-c.copula2.be1be2^-2*der2h.derp1p1^2*dS1eta1^2 + c.copula2.be1be2^-1*der2c.derp1.derp1*dS1eta1^2 + c.copula2.be1be2^-1*der2h.derp1p1*d2S1eta1 -dS1eta1^-2*d2S1eta1^2 + dS1eta1^-1*d3S1eta1)*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indUU*c(c.copula2.be1be2^-1*der2h.derp1p1*dS1eta1 + dS1eta1^-1*d2S1eta1)*VC$X1)*der2.par1 ) ) ) +
crossprod(VC$weights*VC$indUU*c(-Xd1P^-2)*der2eta1dery1b1, der2eta1dery1b1) +
diag( colSums( t( t(VC$weights*VC$indUU*c(Xd1P^-1)*VC$Xd1)*der2.par1 ) ) ) )
be2.be2 <- -(
crossprod(VC$weights*VC$indUU*c(-c.copula2.be1be2^-2*der2h.derp1p2^2*dS2eta2^2 + c.copula2.be1be2^-1*der2c.derp2.derp2*dS2eta2^2 + c.copula2.be1be2^-1*der2h.derp1p2*d2S2eta2 -dS2eta2^-2*d2S2eta2^2 + dS2eta2^-1*d3S2eta2)*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indUU*c(c.copula2.be1be2^-1*der2h.derp1p2*dS2eta2 + dS2eta2^-1*d2S2eta2)*VC$X2)*der2.par2 ) ) ) +
crossprod(VC$weights*VC$indUU*c(-Xd2P^-2)*der2eta2dery2b2, der2eta2dery2b2) +
diag( colSums( t( t(VC$weights*VC$indUU*c(Xd2P^-1)*VC$Xd2)*der2.par2 ) ) )
)
be1.be2 <- -(
crossprod(VC$weights*VC$indUU*c((-c.copula2.be1be2^-2*der2h.derp1p2*der2h.derp1p1 + c.copula2.be1be2^-1*der2c.derp1.derp2)*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indUU*( -c.copula2.be1be2^-2*der2h.derp1teta^2*derteta.derteta.st^2 + c.copula2.be1be2^-1*der2c.derrho.derrho*derteta.derteta.st^2 + c.copula2.be1be2^-1*der2h.derp1teta*der2teta.derteta.stteta.st)
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indUU*c((-c.copula2.be1be2^-2*der2h.derp1p1*der2h.derp1teta + c.copula2.be1be2^-1*der2c.derp1.derrho)*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indUU*c((-c.copula2.be1be2^-2*der2h.derp1p2*der2h.derp1teta + c.copula2.be1be2^-1*der2c.derp2.derrho)*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)
)
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indRR)>1){
l.par <- VC$weights*( VC$indRR*log(p00) )
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*(VC$indRR*(c(p00^(-1)*c.copula.be1*dS1eta1) *dereta1derb1))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*( VC$indRR*(c(p00^(-1)*(c.copula.be2*dS2eta2))*dereta2derb2
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*(VC$indRR*(p00^(-1)*c.copula.theta
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indRR*c(-p00^-2*c.copula.be1^2*dS1eta1^2 + p00^-1*c.copula2.be1*dS1eta1^2 + p00^-1*c.copula.be1*d2S1eta1)*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indRR*c( p00^-1*c.copula.be1*dS1eta1 )*VC$X1)*der2.par1 ) ) )
)
be2.be2 <- -(
crossprod(VC$weights*VC$indRR*c(-p00^-2*c.copula.be2^2*dS2eta2^2 + p00^-1*c.copula2.be2*dS2eta2^2 + p00^-1*c.copula.be2*d2S2eta2)*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indRR*c( p00^-1*c.copula.be2*dS2eta2 )*VC$X2)*der2.par2 ) ) )
)
be1.be2 <- -(
crossprod(VC$weights*VC$indRR*c((-p00^-2*c.copula.be2*c.copula.be1 + p00^-1*c.copula2.be1be2)*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indRR*( -p00^-2*c.copula.thet^2*derteta.derteta.st^2 + p00^-1*bit1.th2ATE*derteta.derteta.st^2 + rotConst*p00^-1*c.copula.thet*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indRR*c(rotConst*(-p00^-2*c.copula.be1*c.copula.thet + p00^-1*c.copula2.be1t)*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indRR*c(rotConst*(-p00^-2*c.copula.be2*c.copula.thet + p00^-1*c.copula2.be2t)*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)
)
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indLL)>1){
l.par <- VC$weights*(VC$indLL*log(c(1-p1-p2+p00)))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*(VC$indLL*(c((1-p1-p2+p00)^(-1))*c(((-dS1eta1)+c.copula.be1*dS1eta1))*dereta1derb1
))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*(VC$indLL*(c((1-p1-p2+p00)^(-1)*((-dS2eta2)+c.copula.be2*dS2eta2))*dereta2derb2
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*(VC$indLL*(c((1-p1-p2+p00)^(-1)*c.copula.theta)
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indLL*c(-(1-p1-p2+p00)^-2*(-dS1eta1+c.copula.be1*dS1eta1)^2 +
(1-p1-p2+p00)^-1*(c.copula2.be1*dS1eta1^2 + c.copula.be1*d2S1eta1-d2S1eta1))*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indLL*c( (1-p1-p2+p00)^-1*(c.copula.be1*dS1eta1 -dS1eta1) )*VC$X1)*der2.par1 ) ) )
)
be2.be2 <- -(
crossprod(VC$weights*VC$indLL*c(-(1-p1-p2+p00)^-2*(-dS2eta2+c.copula.be2*dS2eta2)^2 + (1-p1-p2+p00)^-1*(c.copula2.be2*dS2eta2^2 + c.copula.be2*d2S2eta2-d2S2eta2) )*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indLL*c( (1-p1-p2+p00)^-1*(c.copula.be2*dS2eta2 - dS2eta2) )*VC$X2)*der2.par2 ) ) )
)
be1.be2 <- -(
crossprod(VC$weights*VC$indLL*c((-(1-p1-p2+p00)^-2*((c.copula.be2-1)*(c.copula.be1-1)) + (1-p1-p2+p00)^-1*c.copula2.be1be2)*dS2eta2*dS1eta1)*dereta1derb1, dereta2derb2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indLL*( -(1-p1-p2+p00)^-2*c.copula.thet^2*derteta.derteta.st^2 + (1-p1-p2+p00)^-1*bit1.th2ATE*derteta.derteta.st^2 + rotConst*(1-p1-p2+p00)^-1*c.copula.thet*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indLL*c(rotConst*(-(1-p1-p2+p00)^-2*(c.copula.be1-1)*c.copula.thet + (1-p1-p2+p00)^-1*c.copula2.be1t)*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indLL*c(rotConst*(-(1-p1-p2+p00)^-2*(c.copula.be2-1)*c.copula.thet + (1-p1-p2+p00)^-1*c.copula2.be2t)*dS2eta2*derteta.derteta.st)*dereta2derb2, X3))
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indUR)>1){
l.par <- VC$weights*( VC$indUR*(log(c.copula.be1)+log(-dS1eta1)+log(Xd1P)))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*( VC$indUR*(c(c.copula.be1^(-1)*c.copula2.be1*dS1eta1)*dereta1derb1+
c((dS1eta1)^(-1)*(d2S1eta1)) *dereta1derb1
+c(Xd1P)^(-1)*der2eta1dery1b1
))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*(VC$indUR*(c(c.copula.be1^(-1)*c.copula2.be1be2*dS2eta2)*dereta2derb2
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*(VC$indUR*(c.copula.be1^(-1)*c.copula2.be1th
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indUR*c(-c.copula.be1^-2*c.copula2.be1^2*dS1eta1^2 + c.copula.be1^-1*der3C.derp1p1p1*dS1eta1^2 + c.copula.be1^-1*c.copula2.be1*d2S1eta1 -dS1eta1^-2*d2S1eta1^2 + dS1eta1^-1*d3S1eta1)*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indUR*c(c.copula.be1^-1*c.copula2.be1*dS1eta1 + dS1eta1^-1*d2S1eta1)*VC$X1)*der2.par1 ) ) ) +
crossprod(VC$weights*VC$indUR*c(-Xd1P^-2)*der2eta1dery1b1, der2eta1dery1b1) +
diag( colSums( t( t(VC$weights*VC$indUR*c(Xd1P^-1)*VC$Xd1)*der2.par1 ) ) )
)
be2.be2 <- -(
crossprod(VC$weights*VC$indUR*c(-c.copula.be1^-2*c.copula2.be1be2^2*dS2eta2^2 + c.copula.be1^-1*der2h.derp1p2*dS2eta2^2 + c.copula.be1^-1*c.copula2.be1be2*d2S2eta2)*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indUR*c( c.copula.be1^-1*c.copula2.be1be2*dS2eta2 )*VC$X2)*der2.par2 ) ) )
)
be1.be2 <- -(
crossprod(VC$weights*VC$indUR*c((-c.copula.be1^-2*c.copula2.be1be2*c.copula2.be1 + c.copula.be1^-1*der2h.derp1p1)*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indUR*( -c.copula.be1^-2*c.copula2.be1t^2*derteta.derteta.st^2 + c.copula.be1^-1*der3C.derp1tetateta*derteta.derteta.st^2 + rotConst*c.copula.be1^-1*c.copula2.be1t*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indUR*c((rotConst*-c.copula.be1^-2*c.copula2.be1*c.copula2.be1t + c.copula.be1^-1*der3C.p1p1teta)*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indUR*c((rotConst*-c.copula.be1^-2*c.copula2.be1be2*c.copula2.be1t + c.copula.be1^-1*der2h.derp1teta)*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)
)
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indRU)>1){
l.par <- VC$weights*(VC$indRU*(log(c.copula.be2)+ log(-dS2eta2)+ log(Xd2P)))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*(VC$indRU*(c(c.copula.be2^(-1)*c.copula2.be1be2*dS1eta1)*dereta1derb1))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*(VC$indRU*(c(c.copula.be2^(-1)*c.copula2.be2*dS2eta2)*dereta2derb2+
c((dS2eta2)^(-1)*(d2S2eta2))*dereta2derb2
+c(Xd2P)^(-1)*der2eta2dery2b2
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*(VC$indRU*(c.copula.be2^(-1)*c.copula2.be2th
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indRU*c(-c.copula.be2^-2*c.copula2.be1be2^2*dS1eta1^2 + c.copula.be2^-1*der2h.derp1p1*dS1eta1^2 + c.copula.be2^-1*c.copula2.be1be2*d2S1eta1)*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indRU*c( c.copula.be2^-1*c.copula2.be1be2*dS1eta1 )*VC$X1)*der2.par1 ) ) )
)
be2.be2 <- -(
crossprod(VC$weights*VC$indRU*c(-c.copula.be2^-2*c.copula2.be2^2*dS2eta2^2 + c.copula.be2^-1*der2h.derp2p2*dS2eta2^2 + c.copula.be2^-1*c.copula2.be2*d2S2eta2 -dS2eta2^-2*d2S2eta2^2 + dS2eta2^-1*d3S2eta2)*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indRU*c(c.copula.be2^-1*c.copula2.be2*dS2eta2 + dS2eta2^-1*d2S2eta2)*VC$X2)*der2.par2 ) ) ) +
crossprod(VC$weights*VC$indRU*c(-Xd2P^-2)*der2eta2dery2b2, der2eta2dery2b2) +
diag( colSums( t( t(VC$weights*VC$indRU*c(Xd2P^-1)*VC$Xd2)*der2.par2 ) ) )
)
be1.be2 <- -(
crossprod(VC$weights*VC$indRU*c((-c.copula.be2^-2*c.copula2.be1be2*c.copula2.be2 + c.copula.be2^-1*der2h.derp1p2)*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indRU*( -c.copula.be2^-2*c.copula2.be2t^2*derteta.derteta.st^2 + c.copula.be2^-1*der2h.derteta.teta.st*derteta.derteta.st^2 + rotConst*c.copula.be2^-1*c.copula2.be2t*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indRU*c((rotConst*-c.copula.be2^-2*c.copula2.be1be2*c.copula2.be2t + c.copula.be2^-1*der2h.derp1teta)*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indRU*c((rotConst*-c.copula.be2^-2*c.copula2.be2*c.copula2.be2t + c.copula.be2^-1*der2h.derp2teta)*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)
)
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indUL)>1){
l.par <- VC$weights*(VC$indUL*(log( (c.copula.be1-1) * (dS1eta1) * Xd1P)))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*(VC$indUL*(c((c.copula.be1-1)^(-1)*c.copula2.be1*dS1eta1)*dereta1derb1+
c((dS1eta1^(-1))*d2S1eta1)*dereta1derb1
+c(Xd1P)^(-1)*der2eta1dery1b1
))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*( VC$indUL*(c((c.copula.be1-1)^(-1)*c.copula2.be1be2*dS2eta2)*dereta2derb2
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*(VC$indUL*((c.copula.be1-1)^(-1)*c.copula2.be1th
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indUL*c(-(c.copula.be1-1)^-2*c.copula2.be1^2*dS1eta1^2 + (c.copula.be1-1)^-1*der3C.derp1p1p1*dS1eta1^2 + (c.copula.be1-1)^-1*c.copula2.be1*d2S1eta1 -dS1eta1^-2*d2S1eta1^2 + dS1eta1^-1*d3S1eta1)*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indUL*c((c.copula.be1-1)^-1*c.copula2.be1*dS1eta1 + dS1eta1^-1*d2S1eta1)*VC$X1)*der2.par1 ) ) ) +
crossprod(VC$weights*VC$indUL*c(-Xd1P^-2)*der2eta1dery1b1, der2eta1dery1b1) +
diag( colSums( t( t(VC$weights*VC$indUL*c(Xd1P^-1)*VC$Xd1)*der2.par1 ) ) )
)
be2.be2 <- -(
crossprod(VC$weights*VC$indUL*c(-(c.copula.be1-1)^-2*c.copula2.be1be2^2*dS2eta2^2 + (c.copula.be1-1)^-1*der2h.derp1p2*dS2eta2^2 + (c.copula.be1-1)^-1*c.copula2.be1be2*d2S2eta2)*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indUL*c( (c.copula.be1-1)^-1*c.copula2.be1be2*dS2eta2 )*VC$X2)*der2.par2 ) ) )
)
be1.be2 <- -(
crossprod(VC$weights*VC$indUL*c((-(c.copula.be1-1)^-2*c.copula2.be1*c.copula2.be1be2 + (c.copula.be1-1)^-1*der2h.derp1p1)*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indUL*( -(c.copula.be1-1)^-2*c.copula2.be1t^2*derteta.derteta.st^2 + (c.copula.be1-1)^-1*der3C.derp1tetateta*derteta.derteta.st^2 + rotConst*(c.copula.be1-1)^-1*c.copula2.be1t*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indUL*c(rotConst*(-(c.copula.be1-1)^-2*c.copula2.be1*c.copula2.be1t + (c.copula.be1-1)^-1*der3C.p1p1teta)*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indUL*c(rotConst*(-(c.copula.be1-1)^-2*(c.copula2.be1be2)*c.copula2.be1t + (c.copula.be1-1)^-1*der2h.derp1teta)*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)
)
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indLU)>1){
l.par <- VC$weights*(VC$indLU*(log( (c.copula.be2-1) * (dS2eta2) * Xd2P)))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*(VC$indLU*(c((c.copula.be2-1)^(-1)*c.copula2.be1be2*dS1eta1)*dereta1derb1))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*(VC$indLU*(c((c.copula.be2-1)^(-1)*c.copula2.be2*dS2eta2)*dereta2derb2+
c((dS2eta2)^(-1)*d2S2eta2)*dereta2derb2
+c(Xd2P)^(-1)*der2eta2dery2b2
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*( VC$indLU*((c.copula.be2-1)^(-1)*c.copula2.be2th
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indLU*c(-(c.copula.be2-1)^-2*c.copula2.be1be2^2*dS1eta1^2 + (c.copula.be2-1)^-1*der2h.derp1p1*dS1eta1^2 + (c.copula.be2-1)^-1*c.copula2.be1be2*d2S1eta1)*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indLU*c( (c.copula.be2-1)^-1*c.copula2.be1be2*dS1eta1 )*VC$X1)*der2.par1 ) ) )
)
be2.be2 <- -(
crossprod(VC$weights*VC$indLU*c(-(c.copula.be2-1)^-2*c.copula2.be2^2*dS2eta2^2 + (c.copula.be2-1)^-1*der2h.derp2p2*dS2eta2^2 + (c.copula.be2-1)^-1*c.copula2.be2*d2S2eta2 -dS2eta2^-2*d2S2eta2^2 + dS2eta2^-1*d3S2eta2)*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indLU*c((c.copula.be2-1)^-1*c.copula2.be2*dS2eta2 + dS2eta2^-1*d2S2eta2)*VC$X2)*der2.par2 ) ) ) +
crossprod(VC$weights*VC$indLU*c(-Xd2P^-2)*der2eta2dery2b2, der2eta2dery2b2) +
diag( colSums( t( t(VC$weights*VC$indLU*c(Xd2P^-1)*VC$Xd2)*der2.par2 ) ) )
)
be1.be2 <- -(
crossprod(VC$weights*VC$indLU*c((-(c.copula.be2-1)^-2*c.copula2.be1be2*c.copula2.be2 + (c.copula.be2-1)^-1*der2h.derp1p2)*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indLU*( -(c.copula.be2-1)^-2*c.copula2.be2t^2*derteta.derteta.st^2 + (c.copula.be2-1)^-1*der2h.derteta.teta.st*derteta.derteta.st^2 + rotConst*(c.copula.be2-1)^-1*c.copula2.be2t*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indLU*c(rotConst*(-(c.copula.be2-1)^-2*c.copula2.be1be2*c.copula2.be2t + (c.copula.be2-1)^-1*der2h.derp1teta)*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indLU*c(rotConst*(-(c.copula.be2-1)^-2*(c.copula2.be2)*c.copula2.be2t + (c.copula.be2-1)^-1*der2h.derp2teta)*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)
)
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indRL)>1){
l.par <- VC$weights*(VC$indRL*log(c(p1-p00)))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*( VC$indRL*(c( ((p1-p00)^(-1)) *(
dS1eta1
-c.copula.be1*dS1eta1))*dereta1derb1
))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*( VC$indRL*(c((p1-p00)^(-1)*(-c.copula.be2*dS2eta2))*dereta2derb2
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*( VC$indRL*(c((p1-p00)^(-1)*(-c.copula.theta))
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indRL*c(-(p1-p00)^-2*(dS1eta1-c.copula.be1*dS1eta1)^2 + (p1-p00)^-1*(d2S1eta1-c.copula2.be1*dS1eta1^2-c.copula.be1*d2S1eta1))*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indRL*c( (p1-p00)^-1*(-c.copula.be1*dS1eta1+dS1eta1) )*VC$X1)*der2.par1 ) ) )
)
be2.be2 <- -(
crossprod(VC$weights*VC$indRL*c(-(p1-p00)^-2*(-c.copula.be2)^2*dS2eta2^2 + (p1-p00)^-1*(-c.copula2.be2)*dS2eta2^2 + (p1-p00)^-1*(-c.copula.be2)*d2S2eta2)*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indRL*c( (p1-p00)^-1*(-c.copula.be2)*dS2eta2 )*VC$X2)*der2.par2 ) ) )
)
be1.be2 <- -(
crossprod(VC$weights*VC$indRL*c((-(p1-p00)^-2*(1-c.copula.be1)*(-c.copula.be2) + (p1-p00)^-1*(-c.copula2.be1be2))*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indRL*( -(p1-p00)^-2*(-c.copula.thet)^2*derteta.derteta.st^2 + (p1-p00)^-1*(-bit1.th2ATE)*derteta.derteta.st^2 + rotConst*(p1-p00)^-1*(-c.copula.thet)*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indRL*c(rotConst*(-(p1-p00)^-2*(1-c.copula.be1)*(-c.copula.thet) + (p1-p00)^-1*(-c.copula2.be1t))*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indRL*c(rotConst*(-(p1-p00)^-2*(-c.copula.be2)*(-c.copula.thet) + (p1-p00)^-1*(-c.copula2.be2t))*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)
)
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indLR)>1){
l.par <- VC$weights*(VC$indLR*log(c(p2-p00)))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*( VC$indLR*(c(((p2-p00)^(-1))*(-c.copula.be1*dS1eta1)) * dereta1derb1
))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*(VC$indLR*(c((p2-p00)^(-1))*(
c(dS2eta2)*dereta2derb2
-c(c.copula.be2*dS2eta2)*dereta2derb2)
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*( VC$indLR*(c((p2-p00)^(-1)*(-c.copula.theta))
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indLR*c(-(p2-p00)^-2*(-c.copula.be1*dS1eta1)^2 + (p2-p00)^-1*(-c.copula2.be1*dS1eta1^2-c.copula.be1*d2S1eta1))*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indLR*c( (p2-p00)^-1*(-c.copula.be1*dS1eta1) )*VC$X1)*der2.par1 ) ) )
)
be2.be2 <- -(
crossprod(VC$weights*VC$indLR*c(-(p2-p00)^-2*(dS2eta2-c.copula.be2*dS2eta2)^2 + (p2-p00)^-1*(-c.copula2.be2*dS2eta2^2 -c.copula.be2*d2S2eta2+ d2S2eta2) )*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indLR*c( (p2-p00)^-1*(-c.copula.be2*dS2eta2 + dS2eta2) )*VC$X2)*der2.par2 ) ) )
)
be1.be2 <- -(
crossprod(VC$weights*VC$indLR*c((-(p2-p00)^-2*(1-c.copula.be2)*(-c.copula.be1) + (p2-p00)^-1*(-c.copula2.be1be2))*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indLR*( -(p2-p00)^-2*(-c.copula.thet)^2*derteta.derteta.st^2 + (p2-p00)^-1*(-bit1.th2ATE)*derteta.derteta.st^2 + rotConst*(p2-p00)^-1*(-c.copula.thet)*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indLR*c(rotConst*(-(p2-p00)^-2*(-c.copula.be1)*(-c.copula.thet) + (p2-p00)^-1*(-c.copula2.be1t))*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indLR*c(rotConst*(-(p2-p00)^-2*(1-c.copula.be2)*(-c.copula.thet) + (p2-p00)^-1*(-c.copula2.be2t))*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)
)
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indRI)>1){
l.par <- VC$weights*(VC$indRI*log(mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*(VC$indRI*(mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(
c(c.copula.be1*dS1eta1)*dereta1derb1
-c(c.copula.be1.mix1*dS1eta1)*dereta1derb1)
))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*(VC$indRI*(c(mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1)*(
c(c.copula.be2*dS2eta2)*dereta2derb2
-c(c.copula.be2.mix1*dS2eta2.2)*dereta2derb2.2)
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*(VC$indRI*(c(mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1))*(
c.copula.theta
-c.copula.theta.mix1)
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indRI*c(-mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1*dS1eta1-c.copula.be1.mix1*dS1eta1)^2
+ mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1*dS1eta1^2+c.copula.be1*d2S1eta1
-c.copula2.be1.mix1*dS1eta1^2-c.copula.be1.mix1*d2S1eta1))*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indRI*c( mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be1*dS1eta1-c.copula.be1.mix1*dS1eta1) )*VC$X1)*der2.par1 ) ) )
)
be2.be2 <- -(
crossprod(VC$weights*VC$indRI*c(-mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2*dS2eta2)^2
+ mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2*dS2eta2^2 +
c.copula.be2*d2S2eta2) )*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indRI*c( mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*c.copula.be2*dS2eta2 )*VC$X2)*der2.par2 ) ) )+
crossprod(VC$weights*VC$indRI*c(-mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula.be2.mix1*dS2eta2.2)^2
+ mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-c.copula2.be2.mix1*dS2eta2.2^2
-c.copula.be2.mix1*d2S2eta2.2) )*dereta2derb2.2, dereta2derb2.2) +
diag( colSums( t( t(VC$weights*VC$indRI*c( mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-c.copula.be2.mix1)*dS2eta2.2
)*VC$X2.2)*der2.par2 ) ) )
+
crossprod(VC$weights*VC$indRI*c(-mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula.be2.mix1*c.copula.be2)*dS2eta2*dS2eta2.2 )*dereta2derb2, dereta2derb2.2)+
crossprod(VC$weights*VC$indRI*c(-mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula.be2.mix1*c.copula.be2)*dS2eta2*dS2eta2.2 )*dereta2derb2.2, dereta2derb2)
)
be1.be2 <- -(
crossprod(VC$weights*VC$indRI*c((-mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2)*(c.copula.be1-c.copula.be1.mix1)+
mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(c.copula2.be1be2)
)*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)+
crossprod(VC$weights*VC$indRI*c((-mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula.be2.mix1)*(c.copula.be1-c.copula.be1.mix1) +
mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(-c.copula2.be1be2.mix1)
)*dS1eta1*dS2eta2.2)*dereta1derb1, dereta2derb2.2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indRI*( -mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.thet*derteta.derteta.st-c.copula.thet.mix1*derteta.derteta.st)^2
+ mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(bit1.th2ATE-bit1.th2ATE.mix1)*derteta.derteta.st^2
+ rotConst*mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.thet-c.copula.thet.mix1)*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indRI*c(rotConst*(-mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1-c.copula.be1.mix1)*(c.copula.thet-c.copula.thet.mix1)
+ mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1t-c.copula2.be1t.mix1))*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indRI*c(rotConst*(-mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2)*(c.copula.thet-c.copula.thet.mix1)
+ mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2t))*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)+
crossprod(VC$weights*VC$indRI*c(rotConst*(-mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula.be2.mix1)*(c.copula.thet-c.copula.thet.mix1)
+ mm(p00-p00.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-c.copula2.be2t.mix1))*dS2eta2.2*derteta.derteta.st)*dereta2derb2.2, X3)
)
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indIR)>1){
l.par <- VC$weights*( VC$indIR*log(mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)) )
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*(VC$indIR*(mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(
c(c.copula.be1*dS1eta1)*dereta1derb1
-c(c.copula.be1.mix2*dS1eta1.2)*dereta1derb1.2)
))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*( VC$indIR*(c(mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1))*(
c(c.copula.be2*dS2eta2)*dereta2derb2
-c(c.copula.be2.mix2*dS2eta2)*dereta2derb2)
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*(VC$indIR*(c(mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1))*(
c.copula.theta
-c.copula.theta.mix2)
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indIR*c(-mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1*dS1eta1)^2
+ mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1*dS1eta1^2+c.copula.be1*d2S1eta1
))*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indIR*c( mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be1*dS1eta1) )*VC$X1)*der2.par1 ) ) )+
crossprod(VC$weights*VC$indIR*c(-mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula.be1.mix2*dS1eta1.2)^2
+ mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-c.copula2.be1.mix2*dS1eta1.2^2-c.copula.be1.mix2*d2S1eta1.2
))*dereta1derb1.2, dereta1derb1.2) +
diag( colSums( t( t(VC$weights*VC$indIR*c( mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-c.copula.be1.mix2*dS1eta1.2) )*VC$X1.2)*der2.par1 ) ) )+
crossprod(VC$weights*VC$indIR*c(-mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula.be1.mix2*dS1eta1.2)*(c.copula.be1*dS1eta1)
)*dereta1derb1, dereta1derb1.2) +
crossprod(VC$weights*VC$indIR*c(-mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula.be1.mix2*dS1eta1.2)*(c.copula.be1*dS1eta1)
)*dereta1derb1.2, dereta1derb1)
)
be2.be2 <- -(
crossprod(VC$weights*VC$indIR*c(-mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2*dS2eta2-c.copula.be2.mix2*dS2eta2)^2
+ mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2-c.copula2.be2.mix2)*dS2eta2^2 +
mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be2-c.copula.be2.mix2)*d2S2eta2 )*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indIR*c( mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be2-c.copula.be2.mix2)*dS2eta2
)*VC$X2)*der2.par2 ) ) )
)
be1.be2 <- -(
crossprod(VC$weights*VC$indIR*c((-mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1)*(c.copula.be2-c.copula.be2.mix2)+
mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(c.copula2.be1be2) )*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)+
crossprod(VC$weights*VC$indIR*c((-mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula.be1.mix2)*(c.copula.be2-c.copula.be2.mix2)+
mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(-c.copula2.be1be2.mix2) )*dS1eta1.2*dS2eta2)*dereta1derb1.2, dereta2derb2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indIR*( -mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.thet*derteta.derteta.st-c.copula.thet.mix2*derteta.derteta.st)^2
+ mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(bit1.th2ATE-bit1.th2ATE.mix2)*derteta.derteta.st^2
+ rotConst*mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.thet-c.copula.thet.mix2)*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indIR*c(rotConst*(-mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1)*(c.copula.thet-c.copula.thet.mix2)
+ mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1t))*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)+
crossprod(VC$weights*VC$indIR*c(rotConst*(-mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula.be1.mix2)*(c.copula.thet-c.copula.thet.mix2)
+ mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-c.copula2.be1t.mix2))*dS1eta1.2*derteta.derteta.st)*dereta1derb1.2, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indIR*c(rotConst*(-mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2-c.copula.be2.mix2)*(c.copula.thet-c.copula.thet.mix2)
+ mm(p00-p00.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2t-c.copula2.be2t.mix2))*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)
)
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indLI)>1){
l.par <- VC$weights*(VC$indLI*log(mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*( VC$indLI*(c(mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1))*(
c(c.copula.be1.mix1*dS1eta1
-c.copula.be1*dS1eta1)*dereta1derb1)
))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*(VC$indLI*(c(mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1))*(
c(dS2eta2)*dereta2derb2
-c(dS2eta2.2)*dereta2derb2.2
+c(c.copula.be2.mix1*dS2eta2.2)*dereta2derb2.2
-c(c.copula.be2*dS2eta2)*dereta2derb2)
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*(VC$indLI*(c(mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(
c.copula.theta.mix1
-c.copula.theta))
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indLI*c(-mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1.mix1*dS1eta1-c.copula.be1*dS1eta1)^2
+ mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1.mix1*dS1eta1^2+c.copula.be1.mix1*d2S1eta1
-c.copula2.be1*dS1eta1^2-c.copula.be1*d2S1eta1))*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indLI*c( mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be1.mix1*dS1eta1-c.copula.be1*dS1eta1) )*VC$X1)*der2.par1 ) ) )
)
be2.be2 <- -(
crossprod(VC$weights*VC$indLI*c(-mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(dS2eta2-c.copula.be2*dS2eta2)^2
+ mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-c.copula2.be2)*dS2eta2^2 +
mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(1-c.copula.be2)*d2S2eta2 )*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indLI*c( mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(1-c.copula.be2)*dS2eta2
)*VC$X2)*der2.par2 ) ) )+
crossprod(VC$weights*VC$indLI*c(-mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2.mix1*dS2eta2.2-dS2eta2.2)^2
+ mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2.mix1)*dS2eta2.2^2 +
mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be2.mix1-1)*d2S2eta2.2 )*dereta2derb2.2, dereta2derb2.2) +
diag( colSums( t( t(VC$weights*VC$indLI*c(mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be2.mix1-1)*dS2eta2.2
)*VC$X2.2)*der2.par2 ) ) )+
crossprod(VC$weights*VC$indLI*c(-mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*((dS2eta2-c.copula.be2*dS2eta2)*(c.copula.be2.mix1*dS2eta2.2-dS2eta2.2)) )*dereta2derb2, dereta2derb2.2)+
crossprod(VC$weights*VC$indLI*c(-mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*((dS2eta2-c.copula.be2*dS2eta2)*(c.copula.be2.mix1*dS2eta2.2-dS2eta2.2)) )*dereta2derb2.2, dereta2derb2)
)
be1.be2 <- -(
crossprod(VC$weights*VC$indLI*c((-mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1.mix1-c.copula.be1)*(1-c.copula.be2)+
mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(-c.copula2.be1be2) )*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)+
crossprod(VC$weights*VC$indLI*c((-mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1.mix1-c.copula.be1)*(c.copula.be2.mix1-1)+
mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(c.copula2.be1be2.mix1))*dS1eta1*dS2eta2.2)*dereta1derb1, dereta2derb2.2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indLI*( -mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.thet.mix1*derteta.derteta.st-c.copula.thet*derteta.derteta.st)^2
+ mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(bit1.th2ATE.mix1-bit1.th2ATE)*derteta.derteta.st^2
+ rotConst*mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.thet.mix1-c.copula.thet)*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indLI*c(rotConst*(-mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1.mix1-c.copula.be1)*(c.copula.thet.mix1-c.copula.thet)
+ mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1t.mix1-c.copula2.be1t))*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indLI*c(rotConst*(-mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(1-c.copula.be2)*(c.copula.thet.mix1-c.copula.thet)
+ mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-c.copula2.be2t))*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)+
crossprod(VC$weights*VC$indLI*c(rotConst*(-mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2.mix1-1)*(c.copula.thet.mix1-c.copula.thet)
+ mm(p2-p2.2+p00.mix1-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2t.mix1))*dS2eta2.2*derteta.derteta.st)*dereta2derb2.2, X3)
)
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indIL)>1){
l.par <- VC$weights*(VC$indIL*log(mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*(VC$indIL*(c(mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1))*(
c(dS1eta1-c.copula.be1*dS1eta1)*dereta1derb1
+c(c.copula.be1.mix2*dS1eta1.2-dS1eta1.2)*dereta1derb1.2)
))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*(VC$indIL*(c(mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1))*(
c(c.copula.be2.mix2*dS2eta2)*dereta2derb2
-c(c.copula.be2*dS2eta2)*dereta2derb2)
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*( VC$indIL*(c(mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1))*(
c.copula.theta.mix2
-c.copula.theta)
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indIL*c(-mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(dS1eta1-c.copula.be1*dS1eta1)^2
+ mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(d2S1eta1-c.copula2.be1*dS1eta1^2-c.copula.be1*d2S1eta1))*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indIL*c( mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(dS1eta1-c.copula.be1*dS1eta1) )*VC$X1)*der2.par1 ) ) )+
crossprod(VC$weights*VC$indIL*c(-mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-dS1eta1.2+c.copula.be1.mix2*dS1eta1.2)^2
+ mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-d2S1eta1.2+c.copula2.be1.mix2*dS1eta1.2^2+c.copula.be1.mix2*d2S1eta1.2))*dereta1derb1.2, dereta1derb1.2) +
diag( colSums( t( t(VC$weights*VC$indIL*c( mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-dS1eta1.2+c.copula.be1.mix2*dS1eta1.2) )*VC$X1.2)*der2.par1 ) ) )+
crossprod(VC$weights*VC$indIL*c(-mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-dS1eta1.2+c.copula.be1.mix2*dS1eta1.2)*(dS1eta1-c.copula.be1*dS1eta1)
)*dereta1derb1, dereta1derb1.2)+
crossprod(VC$weights*VC$indIL*c(-mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-dS1eta1.2+c.copula.be1.mix2*dS1eta1.2)*(dS1eta1-c.copula.be1*dS1eta1)
)*dereta1derb1.2, dereta1derb1)
)
be2.be2 <- -(
crossprod(VC$weights*VC$indIL*c(-mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2.mix2*dS2eta2-c.copula.be2*dS2eta2)^2
+ mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2.mix2-c.copula2.be2)*dS2eta2^2 +
mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be2.mix2-c.copula.be2)*d2S2eta2 )*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indIL*c( mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be2.mix2-c.copula.be2)*dS2eta2
)*VC$X2)*der2.par2 ) ) )
)
be1.be2 <- -(
crossprod(VC$weights*VC$indIL*c((-mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(1-c.copula.be1)*(c.copula.be2.mix2-c.copula.be2)+
mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(-c.copula2.be1be2) )*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)+
crossprod(VC$weights*VC$indIL*c((-mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1.mix2-1)*(c.copula.be2.mix2-c.copula.be2)+
mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(c.copula2.be1be2.mix2))*dS1eta1.2*dS2eta2)*dereta1derb1.2, dereta2derb2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indIL*( -mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.thet.mix2*derteta.derteta.st-c.copula.thet*derteta.derteta.st)^2
+ mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(bit1.th2ATE.mix2-bit1.th2ATE)*derteta.derteta.st^2
+ rotConst*mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.thet.mix2-c.copula.thet)*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indIL*c(rotConst*(-mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(1-c.copula.be1)*(c.copula.thet.mix2-c.copula.thet)
+ mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-c.copula2.be1t))*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)+
crossprod(VC$weights*VC$indIL*c(rotConst*(-mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1.mix2-1)*(c.copula.thet.mix2-c.copula.thet)+
mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1t.mix2) )*dS1eta1.2*derteta.derteta.st)*dereta1derb1.2, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indIL*c(rotConst*(-mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2.mix2-c.copula.be2)*(c.copula.thet.mix2-c.copula.thet)
+ mm(p1-p1.2+p00.mix2-p00, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2t.mix2-c.copula2.be2t))*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)
)
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indII)>1){
l.par <- VC$weights*(VC$indII*log( mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr) ))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*(VC$indII*(c(mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1))*(
(c(c.copula.be1*dS1eta1)*dereta1derb1)
-(c(c.copula.be1.mix1*dS1eta1) * dereta1derb1)
-(c(c.copula.be1.mix2*dS1eta1.2)*dereta1derb1.2)
+(c(c.copula.be1.2*dS1eta1.2)*dereta1derb1.2))
))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*(VC$indII*(c(mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1))*(
c(c.copula.be2*dS2eta2)*dereta2derb2
-c(c.copula.be2.mix1*dS2eta2.2)*dereta2derb2.2
-c(c.copula.be2.mix2*dS2eta2)*dereta2derb2
+c(c.copula.be2.2*dS2eta2.2)*dereta2derb2.2)
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*(VC$indII*(c(mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1))*(
c(c.copula.theta
-(c.copula.theta.mix1)
-(c.copula.theta.mix2)
+c.copula.theta.2))
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indII*c(-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1*dS1eta1-c.copula.be1.mix1*dS1eta1)^2 +
mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1*dS1eta1^2+c.copula.be1*d2S1eta1
-c.copula2.be1.mix1*dS1eta1^2-c.copula.be1.mix1*d2S1eta1))*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indII*c( mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be1*dS1eta1-c.copula.be1.mix1*dS1eta1) )*VC$X1)*der2.par1 ) ) ) +
crossprod(VC$weights*VC$indII*c(-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula.be1.mix2*dS1eta1.2+c.copula.be1.2*dS1eta1.2)^2 +
mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1.2*dS1eta1.2^2+c.copula.be1.2*d2S1eta1.2
-c.copula2.be1.mix2*dS1eta1.2^2-c.copula.be1.mix2*d2S1eta1.2))*dereta1derb1.2, dereta1derb1.2) +
diag( colSums( t( t(VC$weights*VC$indII*c( mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be1.2*dS1eta1.2-c.copula.be1.mix2*dS1eta1.2) )*VC$X1.2)*der2.par1 ) ) ) +
crossprod(VC$weights*VC$indII*c(-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-2)*(c.copula.be1*dS1eta1-c.copula.be1.mix1*dS1eta1)*(-c.copula.be1.mix2*dS1eta1.2+c.copula.be1.2*dS1eta1.2)
)*dereta1derb1, dereta1derb1.2)+
crossprod(VC$weights*VC$indII*c(-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-2)*(c.copula.be1*dS1eta1-c.copula.be1.mix1*dS1eta1)*(-c.copula.be1.mix2*dS1eta1.2+c.copula.be1.2*dS1eta1.2)
)*dereta1derb1.2, dereta1derb1)
)
be2.be2 <- -(
crossprod(VC$weights*VC$indII*c(-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2*dS2eta2-c.copula.be2.mix2*dS2eta2)^2
+ mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2-c.copula2.be2.mix2)*dS2eta2^2
+mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be2-c.copula.be2.mix2)*d2S2eta2 )*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indII*c( mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be2-c.copula.be2.mix2)*dS2eta2
)*VC$X2)*der2.par2 ) ) ) +
crossprod(VC$weights*VC$indII*c(-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2.2*dS2eta2.2-c.copula.be2.mix1*dS2eta2.2)^2
+ mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2.2-c.copula2.be2.mix1)*dS2eta2.2^2
+mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be2.2-c.copula.be2.mix1)*d2S2eta2.2 )*dereta2derb2.2, dereta2derb2.2) +
diag( colSums( t( t(VC$weights*VC$indII*c( mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.be2.2-c.copula.be2.mix1)*dS2eta2.2 )*VC$X2.2)*der2.par2 ) ) )+
crossprod(VC$weights*VC$indII*c(-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*((c.copula.be2*dS2eta2-c.copula.be2.mix2*dS2eta2)*(c.copula.be2.2*dS2eta2.2-c.copula.be2.mix1*dS2eta2.2)) )*dereta2derb2, dereta2derb2.2)+
crossprod(VC$weights*VC$indII*c(-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*((c.copula.be2*dS2eta2-c.copula.be2.mix2*dS2eta2)*(c.copula.be2.2*dS2eta2.2-c.copula.be2.mix1*dS2eta2.2)) )*dereta2derb2.2, dereta2derb2)
)
be1.be2 <- -(
crossprod(VC$weights*VC$indII*c((-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2-c.copula.be2.mix2)*(c.copula.be1-c.copula.be1.mix1)+
mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1be2) )*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)+
crossprod(VC$weights*VC$indII*c((-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2.2-c.copula.be2.mix1)*(c.copula.be1-c.copula.be1.mix1)+
mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(-c.copula2.be1be2.mix1) )*dS1eta1*dS2eta2.2)*dereta1derb1, dereta2derb2.2)+
crossprod(VC$weights*VC$indII*c((-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2-c.copula.be2.mix2)*(c.copula.be1.2-c.copula.be1.mix2)+
mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(-c.copula2.be1be2.mix2) )*dS1eta1.2*dS2eta2)*dereta1derb1.2, dereta2derb2)+
crossprod(VC$weights*VC$indII*c((-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2.2-c.copula.be2.mix1)*(c.copula.be1.2-c.copula.be1.mix2)+
mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(c.copula2.be1be2.2) )*dS1eta1.2*dS2eta2.2)*dereta1derb1.2, dereta2derb2.2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indII*( -mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.thet*derteta.derteta.st-c.copula.thet.mix1*derteta.derteta.st-c.copula.thet.mix2*derteta.derteta.st+c.copula.thet.2*derteta.derteta.st)^2
+ mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(bit1.th2ATE-bit1.th2ATE.mix1-bit1.th2ATE.mix2+bit1.th2ATE.2)*derteta.derteta.st^2
+ rotConst*mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula.thet-c.copula.thet.mix1-c.copula.thet.mix2+c.copula.thet.2)*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indII*c(rotConst*(-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1-c.copula.be1.mix1)*(c.copula.thet-c.copula.thet.mix1-c.copula.thet.mix2+c.copula.thet.2)
+ mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1t-c.copula2.be1t.mix1))*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)+
crossprod(VC$weights*VC$indII*c(rotConst*(-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be1.2-c.copula.be1.mix2)*(c.copula.thet-c.copula.thet.mix1-c.copula.thet.mix2+c.copula.thet.2)
+ mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1t.2-c.copula2.be1t.mix2))*dS1eta1.2*derteta.derteta.st)*dereta1derb1.2, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indII*c(rotConst*(-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2-c.copula.be2.mix2)*(c.copula.thet-c.copula.thet.mix1-c.copula.thet.mix2+c.copula.thet.2)
+ mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2t-c.copula2.be2t.mix2))*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)+
crossprod(VC$weights*VC$indII*c(rotConst*(-mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula.be2.2-c.copula.be2.mix1)*(c.copula.thet-c.copula.thet.mix1-c.copula.thet.mix2+c.copula.thet.2)
+ mm(p00-p00.mix1-p00.mix2+p00.2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2t.2-c.copula2.be2t.mix1))*dS2eta2.2*derteta.derteta.st)*dereta2derb2.2, X3)
)
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indUI)>1){
l.par <- VC$weights*( VC$indUI*( log( mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr) ) + log(-dS1eta1)+ log(Xd1P)))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*(VC$indUI*(c(mm(c.copula.be1 - c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)) *
c( (c.copula2.be1 - c.copula2.be1.mix1) * dS1eta1) * dereta1derb1 +
c((dS1eta1)^(-1)*d2S1eta1) * dereta1derb1
+c(Xd1P)^(-1)*der2eta1dery1b1
))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*(VC$indUI*( mm(c.copula.be1 - c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1) *
( c(c.copula2.be1be2 * dS2eta2) * dereta2derb2 - c(c.copula2.be1be2.mix1 * dS2eta2.2) * dereta2derb2.2 )
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*(VC$indUI*(c(mm(c.copula.be1 - c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1))*(
c(c.copula2.be1th - c.copula2.be1th.mix1))
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indUI*c(-mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula2.be1*dS1eta1-c.copula2.be1.mix1*dS1eta1)^2
+ mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(der3C.derp1p1p1-der3C.derp1p1p1.mix1)*dS1eta1^2
+ mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1-c.copula2.be1.mix1)*d2S1eta1
-dS1eta1^-2*d2S1eta1^2 + dS1eta1^-1*d3S1eta1)*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indUI*c(mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1-c.copula2.be1.mix1)*dS1eta1 + dS1eta1^-1*d2S1eta1)*VC$X1)*der2.par1 ) ) ) +
crossprod(VC$weights*VC$indUI*c(-Xd1P^-2)*der2eta1dery1b1, der2eta1dery1b1) +
diag( colSums( t( t(VC$weights*VC$indUI*c(Xd1P^-1)*VC$Xd1)*der2.par1 ) ) )
)
be2.be2 <- -(
crossprod(VC$weights*VC$indUI*c(-mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula2.be1be2*dS2eta2)^2 +
mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(der2h.derp1p2)*dS2eta2^2 +
mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*c.copula2.be1be2*d2S2eta2 )*dereta2derb2, dereta2derb2)+
diag( colSums( t( t(VC$weights*VC$indUI*c( mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1be2)*dS2eta2 )*VC$X2)*der2.par2 ) ) )+
crossprod(VC$weights*VC$indUI*c(-mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula2.be1be2.mix1*dS2eta2.2)^2 +
mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*-der2h.derp1p2.mix1*dS2eta2.2^2 +
mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*-c.copula2.be1be2.mix1*d2S2eta2.2 )*dereta2derb2.2, dereta2derb2.2) +
diag( colSums( t( t(VC$weights*VC$indUI*c(mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*-c.copula2.be1be2.mix1*dS2eta2.2)*VC$X2.2)*der2.par2 ) ) )+
crossprod(VC$weights*VC$indUI*c(-mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula2.be1be2.mix1*c.copula2.be1be2)*dS2eta2*dS2eta2.2 )*dereta2derb2, dereta2derb2.2)+
crossprod(VC$weights*VC$indUI*c(-mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula2.be1be2.mix1*c.copula2.be1be2)*dS2eta2*dS2eta2.2 )*dereta2derb2.2, dereta2derb2)
)
be1.be2 <- -(
crossprod(VC$weights*VC$indUI*c((-mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula2.be1-c.copula2.be1.mix1)*(c.copula2.be1be2)+
mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(der2h.derp1p1) )*dS1eta1*dS2eta2)*dereta1derb1, dereta2derb2)+
crossprod(VC$weights*VC$indUI*c((-mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula2.be1-c.copula2.be1.mix1)*(-c.copula2.be1be2.mix1)+
mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)*(-der2h.derp1p1.mix1))*dS1eta1*dS2eta2.2)*dereta1derb1, dereta2derb2.2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indUI*( -mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula2.be1t*derteta.derteta.st-c.copula2.be1t.mix1*derteta.derteta.st)^2
+ mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(der3C.derp1tetateta-der3C.derp1tetateta.mix1)*derteta.derteta.st^2
+ rotConst*mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be1t-c.copula2.be1t.mix1)*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indUI*c(rotConst*(-mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula2.be1-c.copula2.be1.mix1)*(c.copula2.be1t-c.copula2.be1t.mix1)
+ mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(der3C.p1p1teta-der3C.p1p1teta.mix1))*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indUI*c(rotConst*(-mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula2.be1be2)*(c.copula2.be1t-c.copula2.be1t.mix1)
+ mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(der2h.derp1teta))*dS2eta2*derteta.derteta.st)*dereta2derb2, X3)+
crossprod(VC$weights*VC$indUI*c(rotConst*(-mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula2.be1be2.mix1)*(c.copula2.be1t-c.copula2.be1t.mix1)
+ mm(c.copula.be1-c.copula.be1.mix1, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-der2h.derp1teta.mix1))*dS2eta2.2*derteta.derteta.st)*dereta2derb2.2, X3))
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(sum(VC$indIU)>1){
l.par <- VC$weights*(VC$indIU*( log( mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr) ) + log(-dS2eta2)+log(Xd2P)))
res <- -sum(l.par)
likelihood<-likelihood+ res
dl.dbe1 <- -VC$weights*(VC$indIU*( mm(c.copula.be2 - c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1) *
( c(c.copula2.be1be2 * dS1eta1) * dereta1derb1 - c(c.copula2.be1be2.mix2 * dS1eta1.2) * dereta1derb1.2 )
))
dl.dbe1 <- colSums(dl.dbe1)
dl.dbe2 <- -VC$weights*(VC$indIU*(c(mm(c.copula.be2 - c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1)) *
( c( (c.copula2.be2 - c.copula2.be2.mix2) * dS2eta2 ) * dereta2derb2 )
+ c((dS2eta2)^(-1)*d2S2eta2) * dereta2derb2
+ c(Xd2P)^(-1)*der2eta2dery2b2
))
dl.dbe2 <- colSums(dl.dbe2)
dl.dteta.st <- -VC$weights*(VC$indIU*(c(mm(c.copula.be2 - c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^(-1))*(
c(c.copula2.be2th - c.copula2.be2th.mix2))
))*X3
dl.dteta.st <- colSums( dl.dteta.st)
G <-G+ c( dl.dbe1, dl.dbe2, dl.dteta.st )
be1.be1 <- -(
crossprod(VC$weights*VC$indIU*c(-mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula2.be1be2*dS1eta1)^2
+ mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(der2h.derp1p1*dS1eta1^2 )
+ mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*c.copula2.be1be2*d2S1eta1)*dereta1derb1, dereta1derb1) +
diag( colSums( t( t(VC$weights*VC$indIU*c( mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*c.copula2.be1be2*dS1eta1 )*VC$X1)*der2.par1 ) ) )+
crossprod(VC$weights*VC$indIU*c(-mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula2.be1be2.mix2*dS1eta1.2)^2
+ mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-der2h.derp1p1.mix2*dS1eta1.2^2 )
+ mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-c.copula2.be1be2.mix2*d2S1eta1.2))*dereta1derb1.2, dereta1derb1.2) +
diag( colSums( t( t(VC$weights*VC$indIU*c( (mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1)*(-c.copula2.be1be2.mix2*dS1eta1.2) )*VC$X1.2)*der2.par1 ) ) )+
crossprod(VC$weights*VC$indIU*c(-mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula2.be1be2.mix2*c.copula2.be1be2)*dS1eta1*dS1eta1.2 )*dereta1derb1, dereta1derb1.2)+
crossprod(VC$weights*VC$indIU*c(-mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula2.be1be2.mix2*c.copula2.be1be2)*dS1eta1*dS1eta1.2 )*dereta1derb1.2, dereta1derb1)
)
be2.be2 <- -(
crossprod(VC$weights*VC$indIU*c(-mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula2.be2-c.copula2.be2.mix2)^2*dS2eta2^2
-dS2eta2^-2*(d2S2eta2^2)+dS2eta2^-1*(d3S2eta2)+
+ mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(der2h.derp2p2-der2h.derp2p2.mix2)*dS2eta2^2 +
mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2-c.copula2.be2.mix2)*d2S2eta2 )*dereta2derb2, dereta2derb2) +
diag( colSums( t( t(VC$weights*VC$indIU*c( mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2-c.copula2.be2.mix2)*dS2eta2+
dS2eta2^-1*d2S2eta2 )*VC$X2)*der2.par2 ) ) )+
crossprod(VC$weights*VC$indIU*c(-Xd2P^-2)*der2eta2dery2b2, der2eta2dery2b2) +
diag( colSums( t( t(VC$weights*VC$indIU*c(Xd2P^-1)*VC$Xd2)*der2.par2 ) ) )
)
be1.be2 <- -(
crossprod(VC$weights*VC$indIU*c(-mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*c.copula2.be1be2*dS1eta1*(c.copula2.be2*dS2eta2-c.copula2.be2.mix2*dS2eta2))*dereta1derb1, dereta2derb2)+
crossprod(VC$weights*VC$indIU*c(mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(der2h.derp1p2*dS1eta1*dS2eta2))*dereta1derb1, dereta2derb2)+
crossprod(VC$weights*VC$indIU*c(-mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula2.be1be2.mix2*dS1eta1.2)*(c.copula2.be2*dS2eta2-c.copula2.be2.mix2*dS2eta2))*dereta1derb1.2, dereta2derb2)+
crossprod(VC$weights*VC$indIU*c(mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-der2h.derp1p2.mix2*dS1eta1.2*dS2eta2))*dereta1derb1.2, dereta2derb2)
)
if(VC$BivD %in% c("GAL180","C180","J180","G180","GAL90","C90","J90","G90","GAL270","C270","J270","G270") ) rotConst <- -1
if(VC$BivD %in% VC$BivD2) rotConst <- VC$my.env$signind
d2l.rho.rho <- -(
VC$weights*VC$indIU*( -mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula2.be2t*derteta.derteta.st-c.copula2.be2t.mix2*derteta.derteta.st)^2
+ mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(der2h.derteta.teta.st -der2h.derteta.teta.st.mix2 )*derteta.derteta.st^2
+ rotConst*mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(c.copula2.be2t-c.copula2.be2t.mix2)*der2teta.derteta.stteta.st )
)
rho.rho <- crossprod(X3*c(d2l.rho.rho), X3)
be1.rho <- -(
crossprod(VC$weights*VC$indIU*c(rotConst*(-mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula2.be1be2)*(c.copula2.be2t-c.copula2.be2t.mix2)
+ mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(der2h.derp1teta))*dS1eta1*derteta.derteta.st)*dereta1derb1, X3)+
crossprod(VC$weights*VC$indIU*c(rotConst*(-mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(-c.copula2.be1be2.mix2)*(c.copula2.be2t-c.copula2.be2t.mix2)
+ mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(-der2h.derp1teta.mix2))*dS1eta1.2*derteta.derteta.st)*dereta1derb1.2, X3)
)
be2.rho <- -(
crossprod(VC$weights*VC$indIU*c(rotConst*(-mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-2*(c.copula2.be2-c.copula2.be2.mix2)*(c.copula2.be2t-c.copula2.be2t.mix2)
+ mm(c.copula.be2-c.copula.be2.mix2, min.pr = VC$min.pr, max.pr = VC$max.pr)^-1*(der2h.derp2teta-der2h.derp2teta.mix2))*dS2eta2*derteta.derteta.st)*dereta2derb2, X3))
H <- H+ rbind( cbind( be1.be1 , be1.be2 , be1.rho ),
cbind( t(be1.be2) , be2.be2 , be2.rho ),
cbind( t(be1.rho) , t(be2.rho) , rho.rho ) )
}
if(VC$extra.regI == "pC") H <- regH(H, type = 1)
S.h <- ps$S.h + monP2
S.h1 <- 0.5*crossprod(params, ps$S.h)%*%params + monP
S.h2 <- S.h%*%params + monP1
S.res <- likelihood
res <- S.res + S.h1
G <- G + S.h2
H <- H + S.h
if(VC$extra.regI == "sED") H <- regH(H, type = 2)
list(value=res, gradient=G, hessian=H, S.h=S.h, S.h1=S.h1, S.h2=S.h2,
l=S.res, l.ln = l.ln, l.par=l.par,ps = ps,
eta1=eta1, eta2=eta2, etad=etad, etas1 = 1, etas2 = 1,
BivD=VC$BivD, p1 = p1, p2 = p2, pdf1 = -dS1eta1, pdf2 = -dS2eta2,
c.copula.be2 = c.copula.be2,
c.copula.be1 = c.copula.be1,
c.copula2.be1be2 = c.copula2.be1be2,
dl.dbe1 = NULL,
dl.dbe2 = NULL,
dl.dteta.st = NULL,
teta.ind2 = teta.ind2, teta.ind1 = teta.ind1,
Cop1 = Cop1, Cop2 = Cop2, teta1 = teta1, teta2 = teta2,
indNeq1 = indNeq1, indNeq2 = indNeq2,
Veq1 = Veq1, Veq2 = Veq2,
k1 = VC$my.env$k1, k2 = VC$my.env$k2, monP2 = monP2)
}
|
op_lists <- function(environmental_df, species_df, listOnly=0){
if(missing(environmental_df) | missing(species_df) ) {
print("Select CSV matrices")
Filters <- matrix(c("Comma Separated Values (CSV)", "*.csv"),
1, 2, byrow = TRUE)
print("Select ENVIRONMENTAL matrix first")
env <- read.csv(file.choose())
environmental_df <- read.csv(file.choose())
print("Select SPECIES matrix second")
species_df <- read.csv(file.choose())
}
df_ambientales <- environmental_df
df_densidades <- species_df
if(missing(environmental_df) | missing(species_df) ) {
stop("The correct matrices were not selected, the script will cancel.")
}
list_sites <- t(colnames(df_densidades[2:ncol(df_densidades)]))
list_especies <- as.vector(df_densidades[,1])
list_ambientales <- as.vector(df_ambientales[,1])
if(listOnly==0){
newList <- list(list_sites, list_especies, list_ambientales)
return(newList)
} else if(listOnly==1){
newList <- list(list_sites)
return(newList)
} else if(listOnly==2){
newList <- list(list_especies)
return(newList)
} else if(listOnly==3){
newList <- list(list_ambientales)
return(newList)
}
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
fig.width = 7,
fig.height = 4,
fig.align = "center"
)
library(missMethods)
library(ggplot2)
set.seed(123)
make_simple_MDplot <- function(ds_comp, ds_mis) {
ds_comp$missX <- is.na(ds_mis$X)
ggplot(ds_comp, aes(x = X, y = Y, col = missX)) +
geom_point()
}
ds_comp <- data.frame(X = rnorm(100), Y = rnorm(100))
ds_mcar <- delete_MCAR(ds_comp, 0.3, "X")
make_simple_MDplot(ds_comp, ds_mcar)
ds_mar <- delete_MAR_censoring(ds_comp, 0.3, "X", cols_ctrl = "Y")
make_simple_MDplot(ds_comp, ds_mar)
ds_mar <- delete_MAR_1_to_x(ds_comp, 0.3, "X", cols_ctrl = "Y", x = 2)
make_simple_MDplot(ds_comp, ds_mar)
ds_mar <- delete_MAR_1_to_x(ds_comp, 0.3, "X", cols_ctrl = "Y", x = 10)
make_simple_MDplot(ds_comp, ds_mar)
ds_mnar <- delete_MNAR_censoring(ds_comp, 0.3, "X")
make_simple_MDplot(ds_comp, ds_mnar)
|
context("xgb.Booster")
test_that("xgb.Booster + linear solver + predict() works", {
skip_on_cran()
skip_if_not_installed("xgboost")
library(xgboost)
data(agaricus.train)
data(agaricus.test)
bst <- xgboost(data = agaricus.train$data,
label = agaricus.train$label,
eta = 1,
nthread = 2,
nrounds = 2,
eval_metric = "logloss",
objective = "binary:logistic",
verbose = 0)
x <- axe_call(bst)
expect_equal(x$call, rlang::expr(dummy_call()))
x <- axe_env(bst)
expect_lt(lobstr::obj_size(x), lobstr::obj_size(bst))
x <- axe_ctrl(bst)
expect_equal(x$params, list(NULL))
x <- axe_fitted(bst)
expect_equal(x$raw, raw())
x <- butcher(bst)
expect_equal(xgb.importance(model = x),
xgb.importance(model = bst))
expect_equal(predict(x, agaricus.test$data),
predict(bst, agaricus.test$data))
expect_equal(xgb.dump(x, with_stats = TRUE),
xgb.dump(bst, with_stats = TRUE))
})
test_that("xgb.Booster + tree-learning algo + predict() works", {
skip_on_cran()
skip_if_not_installed("xgboost")
library(xgboost)
data(agaricus.train)
data(agaricus.test)
dtrain <- xgb.DMatrix(data = agaricus.train$data,
label = agaricus.train$label)
bst <- xgb.train(data = dtrain,
booster = "gblinear",
nthread = 2,
nrounds = 2,
eval_metric = "logloss",
objective = "binary:logistic",
print_every_n = 10000L)
x <- axe_call(bst)
expect_equal(x$call, rlang::expr(dummy_call()))
x <- axe_env(bst)
expect_lt(lobstr::obj_size(x), lobstr::obj_size(bst))
x <- axe_ctrl(bst)
expect_equal(x$params, list(NULL))
x <- axe_fitted(bst)
expect_equal(x$raw, raw())
x <- butcher(bst)
expect_equal(xgb.importance(model = x),
xgb.importance(model = bst))
expect_equal(predict(x, agaricus.test$data),
predict(bst, agaricus.test$data))
expect_equal(xgb.dump(x, with_stats = TRUE),
xgb.dump(bst, with_stats = TRUE))
})
|
knitr::opts_chunk$set(fig.width=6, fig.height=4)
options(digits = 4)
library(phangorn)
fdir <- system.file("extdata/trees", package = "phangorn")
primates <- read.phyDat(file.path(fdir, "primates.dna"),
format = "interleaved")
tree <- pratchet(primates, trace=0) |> acctran(primates)
parsimony(tree, primates)
anc.acctran <- ancestral.pars(tree, primates, "ACCTRAN")
anc.mpr <- ancestral.pars(tree, primates, "MPR")
plotAnc(tree, anc.mpr, 17)
title("MPR")
plotAnc(tree, anc.acctran, 17)
title("ACCTRAN")
fit <- pml(tree, primates)
fit <- optim.pml(fit, model="F81", control = pml.control(trace=0))
anc.ml <- ancestral.pml(fit, "ml")
anc.bayes <- ancestral.pml(fit, "bayes")
plotAnc(tree, anc.ml, 17)
title("ML")
plotAnc(tree, anc.bayes, 17)
title("Bayes")
sessionInfo()
|
symbol_legend_y_correction <- function(x) {
is_num <- is.numeric(x)
res <- lapply(x, function(s) {
if (is.numeric(s)) {
ifelse(s %in% c(2, 17, 24), -.025,
ifelse(s %in% c(6, 25), .025, 0))
} else 0
})
if (is_num) {
unlist(res, use.names = FALSE)
} else {
res
}
}
get_symbol_gpar <- function(x, fill, col, lwd, separate=FALSE) {
is_num <- is.numeric(x)
n <- max(length(x), length(fill), length(col), length(lwd))
x <- rep(x, length.out=n)
fill <- rep(fill, length.out=n)
col <- rep(col, length.out=n)
lwd <- rep(lwd, length.out=n)
res <- lapply(1:n, function(i) {
if (is.numeric(x[i])) {
if (x[i] %in% 21:25) {
list(fill=fill[i],
col=col[i],
lwd=lwd[i])
} else {
list(fill=as.character(NA),
col=fill[i],
lwd=lwd[i])
}
} else {
list(fill=fill[i],
col=col[i],
lwd=lwd[i])
}
})
if (separate) {
lapply(res, function(r){
do.call(gpar, r)
})
} else {
fills <- vapply(res, function(r)r$fill, character(1))
cols <- vapply(res, function(r)r$col, character(1))
lwds <- vapply(res, function(r)r$lwd, numeric(1))
gpar(fill=fills, col=cols, lwd=lwds)
}
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(finalfit)
library(dplyr)
dependent = "differ.factor"
explanatory = c("age", "sex.factor",
"extent.factor", "obstruct.factor",
"nodes")
colon_s %>%
select(age, sex.factor, extent.factor, obstruct.factor, nodes) %>%
names() -> explanatory
colon_s %>%
ff_glimpse(dependent, explanatory)
colon_s %>%
summary_factorlist(dependent, explanatory,
p=TRUE, na_include=TRUE) %>%
knitr::kable(row.names=FALSE, align=c("l", "l", "r", "r", "r", "r"))
Hmisc::label(colon_s$nodes) = "Lymph nodes involved"
explanatory = c("age", "sex.factor",
"extent.factor", "nodes")
colon_s %>%
summary_factorlist(dependent, explanatory,
p=TRUE, na_include=TRUE,
add_dependent_label=TRUE) %>%
knitr::kable(row.names=FALSE, align=c("l", "l", "r", "r", "r", "r"))
explanatory = c("age", "sex.factor",
"extent.factor", "nodes", "differ.factor")
dependent = "mort_5yr"
colon_s %>%
finalfit(dependent, explanatory,
dependent_label_prefix = "") %>%
knitr::kable(row.names=FALSE, align=c("l", "l", "r", "r", "r", "r"))
|
print.kcpRS_workflow<-function(x,...){
res_kcpMean=x$kcpMean
res_kcpVar=x$kcpVar
res_kcpAR=x$kcpAR
res_kcpCorr=x$kcpCorr
RMean=ifelse(class(res_kcpMean)=="kcpRS",1,0)
RVar=ifelse(class(res_kcpVar)=="kcpRS",1,0)
RAR=ifelse(class(res_kcpAR)=="kcpRS",1,0)
RCorr=ifelse(class(res_kcpCorr)=="kcpRS",1,0)
ntests=RMean+RVar+RAR+RCorr
if (ntests==0){warning("No running statistic selected.","\n")}
if (ntests>0){
if(RMean==1){
cat("\n")
cat(" KCP-Mean:","\n")
print(res_kcpMean,kcp_details=FALSE)
cat(" ===============================================================================================","\n")
}
if(RVar==1){
cat("\n")
cat(" KCP-Var:","\n")
print(res_kcpVar,kcp_details=FALSE)
cat(" ===============================================================================================","\n")
}
if(RAR==1){
cat("\n")
cat(" KCP-AR:","\n")
print(res_kcpAR,kcp_details=FALSE)
cat(" ===============================================================================================","\n")
}
if(RCorr==1){
cat("\n")
cat(" KCP-Corr:","\n")
print(res_kcpCorr,kcp_details=FALSE)
cat(" ===============================================================================================","\n")
}
}
}
|
norm.appr.param <- function(parammat){
J <- ncol(parammat)
ellipse.param <- list(mu = NULL, Sigmainv = NULL, c = NULL)
ellipse.param$mu <- cbind(parammat[5, ], parammat[6, ])
for (j in 1:J){
kap1 <- parammat[2, j]
kap2 <- parammat[3, j]
lamb <- parammat[4, j]
pi_j <- parammat[1, j]
ellipse.param$Sigmainv[[j]] <-
matrix(c(kap1, rep(lamb, 2), kap2), nrow = 2)
ellipse.param$c[j] <- log(pi_j^2 * (kap1 * kap2 - lamb^2))
}
return(ellipse.param)
}
|
testthat::test_that("DefaultModelFit: initialize function works", {
testthat::expect_is(DefaultModelFit$new(), "DefaultModelFit")
})
testthat::test_that("DefaultModelFit: createFormula function works", {
instances <- data.frame(c(1, 2), c(2, 2))
colnames(instances) <- c("C1", "Class")
testthat::expect_is(DefaultModelFit$new()$createFormula(instances, "Class",
simplify = FALSE),
"formula")
testthat::expect_is(DefaultModelFit$new()$createFormula(instances, "Class",
simplify = TRUE),
"formula")
})
testthat::test_that("DefaultModelFit: createRecipe function works", {
instances <- data.frame(c(1, 2), c(2, 2))
colnames(instances) <- c("C1", "Class")
testthat::expect_is(DefaultModelFit$new()$createRecipe(instances, "Class"),
"recipe")
})
|
library("detectRUNS")
genotypeFilePath <- system.file(
"extdata", "Kijas2016_Sheep_subset.ped", package="detectRUNS")
mapFilePath <- system.file(
"extdata", "Kijas2016_Sheep_subset.map", package="detectRUNS")
slidingRuns <- slidingRUNS.run(
genotypeFile = genotypeFilePath,
mapFile = mapFilePath,
windowSize = 15,
threshold = 0.05,
minSNP = 20,
ROHet = FALSE,
maxOppWindow = 1,
maxMissWindow = 1,
maxGap = 10^6,
minLengthBps = 250000,
minDensity = 1/10^3,
maxOppRun = NULL,
maxMissRun = NULL
)
consecutiveRuns <- consecutiveRUNS.run(
genotypeFile =genotypeFilePath,
mapFile = mapFilePath,
minSNP = 20,
ROHet = FALSE,
maxGap = 10^6,
minLengthBps = 250000,
maxOppRun = 1,
maxMissRun = 1
)
slidingRuns_het <- slidingRUNS.run(
genotypeFile = genotypeFilePath,
mapFile = mapFilePath,
windowSize = 10,
threshold = 0.05,
minSNP = 10,
ROHet = TRUE,
maxOppWindow = 2,
maxMissWindow = 1,
maxGap = 10^6,
minLengthBps = 10000,
minDensity = 1/10^6,
maxOppRun = NULL,
maxMissRun = NULL
)
consecutiveRuns_het <- consecutiveRUNS.run(
genotypeFile =genotypeFilePath,
mapFile = mapFilePath,
minSNP = 10,
ROHet = TRUE,
maxGap = 10^6,
minLengthBps = 10000,
maxOppRun = 2,
maxMissRun = 1
)
summaryList <- summaryRuns(
runs = slidingRuns, mapFile = mapFilePath, genotypeFile = genotypeFilePath,
Class = 6, snpInRuns = TRUE)
summaryList$summary_ROH_count
summaryList$summary_ROH_mean_chr
head(summaryList$SNPinRun)
plot_Runs(runs = slidingRuns)
plot_StackedRuns(runs = slidingRuns)
plot_SnpsInRuns(
runs = slidingRuns[slidingRuns$chrom==2,], genotypeFile = genotypeFilePath,
mapFile = mapFilePath)
plot_SnpsInRuns(
runs = slidingRuns[slidingRuns$chrom==24,], genotypeFile = genotypeFilePath,
mapFile = mapFilePath)
topRuns <- tableRuns(
runs = slidingRuns, genotypeFile = genotypeFilePath, mapFile = mapFilePath,
threshold = 0.7)
print(topRuns)
plot_manhattanRuns(
runs = slidingRuns[slidingRuns$group=="Jacobs",],
genotypeFile = genotypeFilePath, mapFile = mapFilePath)
head(
Froh_inbreeding(runs = slidingRuns,mapFile = mapFilePath,genome_wide = TRUE))
plot_InbreedingChr(
runs = slidingRuns, mapFile = mapFilePath, style = "FrohBoxPlot")
savedRunFile <- system.file(
"extdata", "Kijas2016_Sheep_subset.sliding.csv", package="detectRUNS")
runs <- readExternalRuns(inputFile = savedRunFile, program = "detectRUNS")
head(runs)
|
add_seasons <- function(data, level = "site", season_level = 2,
date_column = "yearmon", summary_funs = NA,
path = get_default_data_path(),
download_if_missing = TRUE, clean = TRUE)
{
date_column <- tolower(date_column)
if (!is.na(summary_funs)) {sumfun <- get(summary_funs)}
grouping <- switch(level,
"plot" = c("seasonyear", "treatment", "plot"),
"treatment" = c("seasonyear", "treatment"),
"site" = c("seasonyear"))
if("species" %in% colnames(data)) {grouping <- c(grouping, "species")}
newmoons_table <- load_datafile(file.path("Rodents", "moon_dates.csv"),
na.strings = "NA", path, download_if_missing)
if (date_column == "period" || date_column == "newmoonnumber") {
date_vars <- setdiff(c("newmoonnumber", "newmoondate", "censusdate", "period"),
date_column)
full_data <- data %>%
dplyr::left_join(newmoons_table, by = date_column) %>%
dplyr::mutate(year = lubridate::year(.data$censusdate),
month = lubridate::month(.data$censusdate)) %>%
dplyr::select(-tidyselect::any_of(date_vars))
} else if (date_column == "date") {
full_data <- data %>%
dplyr::mutate(year = lubridate::year(.data$date),
month = lubridate::month(.data$date))
} else if (date_column == "yearmon") {
full_data <- data
} else {
print("date_column must equal period, newmoonnumber, date, or yearmon")
}
if (season_level == 2 || season_level == 4) {
full_data$wateryear <- full_data$year
if (season_level == 4)
{
seasons <- rep(c("winter", "spring", "summer", "fall"), each = 3)
names(seasons) <- c(12, 1:11)
full_data$wateryear[full_data$month == 12] <- full_data$year[full_data$month == 12] + 1
} else if (season_level == 2) {
seasons <- rep(c("winter", "summer"), each = 6)
names(seasons) <- c(11:12, 1:10)
full_data$wateryear[full_data$month %in% c(11,12)] <-
full_data$year[full_data$month %in% c(11,12)] + 1
}
full_data$season <- seasons[match(unlist(full_data$month), names(seasons))]
full_data$seasonyear <- paste(full_data$season, full_data$wateryear)
full_data <- full_data %>% dplyr::select(-.data$wateryear) %>%
dplyr::mutate(season = factor(.data$season, unique(seasons))) %>%
dplyr::arrange(.data$year, .data$month)
if (!is.na(summary_funs))
{
date_vars <- c("month", "day", "date", "newmoonnumber", "period",
"year", "season")
full_data <- full_data %>% dplyr::ungroup() %>%
dplyr::select(-tidyselect::any_of(date_vars)) %>%
dplyr::group_by_at(grouping) %>%
dplyr::summarize_all(list(sumfun), na.rm = TRUE) %>%
dplyr::mutate(season = sub( " .*$", "", .data$seasonyear ),
year = sub( ".* ", "", .data$seasonyear )) %>%
dplyr::mutate(season = factor(.data$season, unique(seasons))) %>%
dplyr::group_by(.data$year, .data$season) %>%
dplyr::select(-.data$seasonyear) %>%
dplyr::arrange(.data$year, .data$season)
}
} else if (season_level == "year" && !(is.na(summary_funs))) {
grouping <- grouping[-1]
date_vars <- c("month", "day", "date", "newmoonnumber", "period")
full_data <- full_data %>% dplyr::ungroup() %>%
dplyr::select(-tidyselect::any_of(date_vars)) %>%
dplyr::group_by_at(c("year", grouping)) %>%
dplyr::summarize_all(list(sumfun), na.rm = TRUE) %>%
dplyr::arrange(.data$year)
} else {
stop("`season_level` must equal 2, 4, or year")
}
return(full_data)
}
yearly <- function(...) {
add_seasons(..., season_level = "year", summary_funs = "mean")
}
|
setMethod(f = "slingBranchID",
signature = signature(x = "ANY"),
definition = function(x, thresh = NULL){
L <- length(slingLineages(x))
if(is.null(thresh)){
thresh <- 1/L
}else{
if(thresh < 0 | thresh > 1){
stop("'thresh' value must be between 0 and 1.")
}
}
return(factor(apply(slingCurveWeights(x) >= thresh, 1,
function(bin){
paste(which(bin), collapse = ',')
})))
})
setMethod(f = "slingBranchGraph",
signature = signature(x = "ANY"),
definition = function(x, thresh = NULL, max_node_size = 100){
brID <- slingBranchID(x, thresh = thresh)
nodes <- as.character(levels(brID))
which.lin <- strsplit(nodes, split='[,]')
nlins <- vapply(which.lin, length, 0)
maxL <- max(nlins)
if(maxL == 1){
g <- igraph::graph_from_literal(1)
igraph::vertex_attr(g, 'cells') <- length(brID)
igraph::vertex_attr(g, 'size') <- max_node_size
return(g)
}
if(length(nodes)==1){
m <- matrix(0, dimnames = list(nodes[1], nodes[1]))
g <- igraph::graph_from_adjacency_matrix(m)
igraph::vertex_attr(g, 'cells') <- length(brID)
igraph::vertex_attr(g, 'size') <- max_node_size
return(g)
}
el <- NULL
for(l in seq(2,maxL)){
for(n in nodes[nlins==l]){
desc <- .under(n, nodes)
for(d in desc){
if(l - nlins[which(nodes==d)] >= 2){
granddesc <- unique(unlist(lapply(desc, .under,
nodes)))
if(! d %in% granddesc){
el <- rbind(el, c(n, d))
}
}else{
el <- rbind(el, c(n, d))
}
}
}
}
g <- igraph::graph_from_edgelist(el)
igraph::vertex_attr(g, 'cells') <- table(brID)[
igraph::vertex_attr(g)$name]
igraph::vertex_attr(g, 'size') <- max_node_size *
igraph::vertex_attr(g)$cells /
max(igraph::vertex_attr(g)$cells)
return(g)
})
|
PSPMequi <- function(modelname = NULL, biftype = NULL, startpoint = NULL, stepsize = NULL,
parbnds = NULL, parameters = NULL, minvals = NULL, maxvals = NULL,
options = NULL, clean = FALSE, force = FALSE, debug = FALSE, silent = FALSE) {
Oldwd = model.Name = Rmodel = Varlist = Funlist = libfile.Basename = DefaultParameters = NULL;
libfile.Fullname = buildSO("PSPMequi", modelname, debug, force, silent)
setwd(Oldwd)
if (!file.exists(libfile.Fullname)) stop(paste0("\nExecutable ", libfile.Basename, " not found! Computation aborted.\n"))
if (!is.character(biftype)) stop('Bifurcation type should be a string (BP, BPE, EQ, LP, ESS or PIP)')
if ((!length(startpoint)) || (!is.double(startpoint))) stop('Starting values should be a vector with double values')
if ((length(stepsize) != 1) || (!is.double(stepsize))) stop('Step size argument should be a single double value')
if (Rmodel == 1) {
if ((!length(parbnds)) || (!((length(parbnds) == 3) || (length(parbnds) == 6) || (((length(parbnds)-3) %% 4) == 0))))
stop('Parameter bounds values should be a vector of length 3, 6 or 3+4*N (in case of ESS continuation)')
parbnds2 <- NULL
if (is.character(parbnds[1])) {
defpars <- get("DefaultParameters", envir = .GlobalEnv)
if (parbnds[1] %in% names(defpars)) {
indx <- (1:length(defpars))[parbnds[1] == names(defpars)]
parbnds2 <- c(parbnds2, as.integer(indx)-1, as.double(parbnds[2]), as.double(parbnds[3]))
}
else {
stop(paste0("\nName of bifurcation parameter ", parbnds[1], " not found in DefaultParameters! Computation aborted.\n"))
}
}
else {
if (!is.double(parbnds[1:3])) stop('Parameter bounds should be double values')
parbnds2 <- c(parbnds2, as.integer(parbnds[1]), as.double(parbnds[2]), as.double(parbnds[3]))
}
if (length(parbnds) > 3) {
if (length(parbnds) == 6) {
if (is.character(parbnds[4])) {
defpars <- get("DefaultParameters", envir = .GlobalEnv)
if (parbnds[4] %in% names(defpars)) {
indx <- (1:length(defpars))[parbnds[4] == names(defpars)]
parbnds2 <- c(parbnds2, as.integer(indx)-1, as.double(parbnds[5]), as.double(parbnds[6]))
}
else {
stop(paste0("\nName of bifurcation parameter ", parbnds[4], " not found in DefaultParameters! Computation aborted.\n"))
}
}
else {
if (!is.double(parbnds[4:6])) stop('Parameter bounds should be double values')
parbnds2 <- c(parbnds2, as.integer(parbnds[4]), as.double(parbnds[5]), as.double(parbnds[6]))
}
}
else if (((length(parbnds)-3) %% 4) == 0) {
for (i in seq(4, length(parbnds), 4)) {
if (is.character(parbnds[i+1])) {
defpars <- get("DefaultParameters", envir = .GlobalEnv)
if (parbnds[i+1] %in% names(defpars)) {
indx <- (1:length(defpars))[parbnds[i+1] == names(defpars)]
parbnds2 <- c(parbnds2, as.integer(parbnds[i]), as.integer(indx)-1, as.double(parbnds[i+2]), as.double(parbnds[i+3]))
}
else {
stop(paste0("\nName of bifurcation parameter ", parbnds[i+1], " not found in DefaultParameters! Computation aborted.\n"))
}
}
else
{
if (!is.double(parbnds[i:(i+3)])) stop('Parameter bounds should be double values')
parbnds2 <- c(parbnds2, as.integer(parbnds[i]), as.integer(parbnds[i+1]), as.double(parbnds[i+2]), as.double(parbnds[i+3]))
}
}
}
else
stop('Parameter bounds values should be a vector of length 3, 6 or 3+4*N (in case of ESS continuation)')
}
parbnds <- parbnds2
}
if ((!is.double(parbnds)) || (!((length(parbnds) == 3) || (length(parbnds) == 6) || (((length(parbnds)-3) %% 4) == 0))))
stop('Parameter bounds values should be a vector of length 3, 6 or 3+4*N (in case of ESS continuation)')
if ((length(parameters)) && (!is.double(parameters))) stop('If specified parameter values should be a vector with double values')
if ((length(minvals)) && (!is.double(minvals))) stop('If specified minimum values of variables should be a vector with double values')
if ((length(maxvals)) && (!is.double(maxvals))) stop('If specified maximum values of variables should be a vector with double values')
if ((length(options)) && (!is.character(options))) stop('If specified options should be an array with strings')
if (clean) {
outlist=list.files(pattern=paste0(model.Name, "-.*-.*.", "[bcemo][israu][fbrt]"))
if (debug) cat("\nCleaning :", outlist, "\n")
for (i in outlist) file.remove(i)
}
dyn.load(libfile.Fullname)
cout <- .Call("PSPMequi", model.Name, biftype, startpoint, stepsize, parbnds, parameters, options, minvals, maxvals, PACKAGE=paste0(model.Name, "equi"))
dyn.unload(libfile.Fullname)
if (Rmodel == 1) {
rm(list = Filter( exists, Varlist ), envir = .GlobalEnv )
rm(list = Filter( exists, Funlist ), envir = .GlobalEnv )
}
suspendInterrupts(
{
desc = data = bifpoints = biftypes = NULL
if (exists("cout")) {
outfile.name = paste0(cout, ".out")
if (file.exists(outfile.name) && (file.info(outfile.name)$size > 0)) {
desc <- readLines(outfile.name)
data <- as.matrix(read.table(text=desc, blank.lines.skip = TRUE, fill=TRUE))
desc <- desc[grepl("^
lbls <- strsplit(desc[length(desc)], ":")[[1]]
cnames <- gsub("[ ]+[0-9]+$", "", lbls[2:length(lbls)])
colnames(data) <- gsub("\\[[ ]+", "[", cnames)
desc[-length(desc)] <- paste0(desc[-length(desc)], '\n')
desc[1] <- '
}
biffile.name = paste0(cout, ".bif")
if (file.exists(biffile.name) && (file.info(biffile.name)$size > 0)) {
bifinput <- readLines(biffile.name)
bifpoints <- as.matrix(read.table(text=bifinput, blank.lines.skip = TRUE, comment.char='*', fill=TRUE))
colnames(bifpoints) <- gsub("\\[[ ]+", "[", cnames)
biftypes = gsub("^.*\\*\\*\\*\\*\\s+|\\s+\\*\\*\\*\\*.*$", "", bifinput)
}
}
setwd(Oldwd)
if (length(desc) || length(data) || length(bifpoints) || length(biftypes)) {
if (length(bifpoints) || length(biftypes)) {
output = list(curvedesc = desc, curvepoints = data, bifpoints = bifpoints, biftypes = biftypes)
}
else {
if ((biftype == "EQ") || (biftype == "ESS")) cat("\nNo bifurcations points detected during computations with ", modelname, "\n")
output = list(curvedesc = desc, curvepoints = data, bifpoints = NULL, biftypes = NULL)
}
return(output)
} else cat("\nComputations with ", modelname, " produced no output\n")
}
)
}
|
BestDes_SR <- function(p, ridge, workGrid, Cov, CCov, isSequential=FALSE){
if(isSequential == FALSE){
comblist <- utils::combn(1:length(workGrid), p)
temps <- rep(0,ncol(comblist))
for(i in 1:ncol(comblist)){ temps[i] <- SRCri(comblist[,i], ridge, Cov, CCov) }
best <- sort(comblist[,min(which(temps==max(temps)))])
return(list(best=best))
} else{
optdes <- c()
for(iter in 1:p){
candidx <- which(!((1:length(workGrid)) %in% optdes))
seqcri <- rep(NA, length(candidx))
for(i in 1:length(candidx)){
tempdes <- sort(c(optdes,candidx[i]))
seqcri[i] <- SRCri(tempdes, ridge, Cov, CCov)
}
optdes <- sort(c(optdes, candidx[min(which(seqcri == max(seqcri)))]))
}
return(list(best=optdes,med=NULL))
}
}
SRCri <- function(design,ridge,Cov,CCov){
design <- sort(design)
ridgeCov <- Cov + diag(ridge,nrow(Cov))
srcri <- t(CCov[design]) %*% solve(ridgeCov[design,design]) %*% CCov[design]
return(srcri)
}
|
sbn_to_mtx <- function(g, method = c("dwn_mtx", "undir_mtx",
"up_mtx", "n2n_dist_up",
"n2n_dist_dwn", "n2n_dist_undir"),
unconnected = Inf, weights = NULL) {
if (!igraph::is.directed(g)) stop("g must be a downstream directed graph")
if (method == "dwn_mtx") res <- igraph::as_adj(g, sparse = FALSE)
if (method == "up_mtx") res <- t(igraph::as_adj(g, sparse = FALSE))
if (method == "undir_mtx") {
undir_mtx <- igraph::as.undirected(g)
res <- igraph::as_adj(undir_mtx, sparse = FALSE)
}
if (method == "n2n_dist_dwn") {
res <- igraph::shortest.paths(g, mode = "out", weights = weights)
res[is.infinite(res)] <- unconnected
}
if (method == "n2n_dist_up") {
res <- igraph::shortest.paths(g, mode = "in", weights = weights)
res[is.infinite(res)] <- unconnected
}
if (method == "n2n_dist_undir") {
res <- igraph::shortest.paths(g, mode = "all", weights = weights)
res[is.infinite(res)] <- unconnected
}
return(res)
}
|
expected <- eval(parse(text="list(list(2, 2, 6))"));
test(id=0, code={
argv <- eval(parse(text="list(list(list(2, 2, 6), list(1, 3, 9), list(1, 3, -1)), value = 1)"));
do.call(`length<-`, argv);
}, o=expected);
|
library(OpenMx)
library(testthat)
context("gendata-multilevel")
suppressWarnings(RNGversion("3.5"))
set.seed(1)
df <- NULL
for (batch in 1:50) {
df <- rbind(df, expand.grid(case=1:(5+sample.int(4, 1)), Batch=batch, Yield=0))
}
batch <- mxModel(
'batch', type="RAM",
latentVars = c('batch'),
mxData(data.frame(batch=unique(df$Batch)), 'raw', primaryKey='batch'),
mxPath('batch', arrows=2, values=.75, lbound=.001))
trueYield <- mxModel(
'yield', type='RAM', batch,
manifestVars = c('Yield'),
mxData(df, 'raw'),
mxPath('one', 'Yield', values=1e-6),
mxPath('Yield', arrows=2, values=1),
mxPath('batch.batch', 'Yield', free=FALSE, values=1, joinKey="Batch"))
result <- expand.grid(rep=1:5)
for (px in names(coef(trueYield))) result[[px]] <- NA
result$rep <- NULL
for (rep in 1:nrow(result)) {
yield <- mxGenerateData(trueYield, returnModel = TRUE)
yield <- mxRun(yield, silent = TRUE)
result[rep, names(coef(yield))] <- coef(yield)
}
omxCheckCloseEnough(colMeans(result) - coef(trueYield), rep(0,3), .1)
omxCheckCloseEnough(apply(result, 2, var), rep(0,3), .03)
|
igaprobability <- function(withinabund,gatesize,presortabund,nazeros=TRUE){
if(withinabund<0|gatesize<0|presortabund<0){
stop("Abundances and gate size must be greater than or equal to zero.")
}
if(withinabund>1|gatesize>1|presortabund>1){
stop("Abundances and gate size should be less than 1. Function expects values relative to 1 not 100 (i.e. not a percentage).")
}
if(withinabund==0&presortabund==0&nazeros==TRUE){
return(NA)
}
nume <- withinabund*gatesize
denom <- presortabund
if(nume>denom){
ip <- 1
}else if(nume==0&&denom==0){
ip <- NA
}else{
ip <- nume/denom
}
return(ip)
}
|
dis.nness.find.m <- function(comm, ness=FALSE){
min1 <- min(rowSums(comm))
if(ness==TRUE){
if(min1 < 61){
ms <- 1:(min1/2)
} else{
ms <- round(seq(1, (min1/2), length.out=30), digits=0)
}
}
if(ness==FALSE){
if(min1 < 31){
ms <- 1:min1
} else{
ms <- round(seq(1, min1, length.out=30), digits=0)
}
}
comp <- (nrow(comm)*(nrow(comm)-1))/2
ms.n <- length(ms)
dists.m <- matrix(, comp, ms.n)
for(i in 1:ms.n){
dists.m[, i] <- as.vector(dis.nness(comm, m=ms[i], ness=ness))
}
kendall.resu <- cor(dists.m, method="kendall")
rownames(kendall.resu) <- ms
colnames(kendall.resu) <- ms
dif1 <- kendall.resu[, 1] - kendall.resu[, ms.n]
dif2 <- abs(dif1)
posi <- which.min(dif2)
m <- ms[posi]
return(m)
}
|
graph.rmedge <-
function(n,g,fix.edge=TRUE)
{
k=degree(g)
nV=length(V(g))
allp=t(combn(nV,2))
pe=k[allp[,1]]*k[allp[,2]]/(sum(k))
adjm=diag(0,nV)
Sg=NULL
for(i in 1:n)
{
if (fix.edge==TRUE)ce=rmulti.one(size=sum(k)/2,p=pe) else ce=rbinom(n=nrow(allp),size=1,prob=pe)
adjm[allp]=ce
ind <- lower.tri(adjm)
adjm[ind] <- t(adjm)[ind]
sg=graph.adjacency(adjm, mode=c("undirected"))
Sg=c(Sg,list(sg))
}
return(Sg)
}
|
ntwrkEdges<-function(x, importBlocks = FALSE, removeDuplicates = TRUE, parallel = FALSE, nCores = (parallel::detectCores()/2)){
i <- NULL
j <- NULL
k <- NULL
dupAction<-removeDuplicates
par = parallel
cores = nCores
summarizeContacts<- function(x, importBlocks, avg = FALSE, parallel, nCores){
i <- NULL
summaryAgg.block<-function(x,y){
sumTable<-y[which(y$block == unname(unlist(x[1]))),]
if(nrow(sumTable) == 0){output <- NULL
}else{
blockStart<- unique(lubridate::as_datetime(sumTable$block.start))
blockEnd<- unique(lubridate::as_datetime(sumTable$block.end))
blockNum<- unique(sumTable$numBlocks)
sumTable.redac<-sumTable[,-c(match("id", names(sumTable)), match("block", names(sumTable)), match("block.start", names(sumTable)), match("block.end", names(sumTable)), match("numBlocks", names(sumTable)))]
output<-stats::aggregate(sumTable.redac, list(id = sumTable$id), mean)
output$block = unname(unlist(x[1]))
output$block.start = blockStart
output$block.end = blockEnd
output$numBlocks = blockNum
}
return(output)
}
summary.generator<-function(x, importBlocks, parallel, nCores){
blockSum <-function(x,y, indivSeq, areaSeq){
blockDurFrame<-y[which(y$block == unname(unlist(x[1]))),]
indivSeqFrame <- data.frame(indivSeq, stringsAsFactors = TRUE)
summary.contacts<-apply(indivSeqFrame, 1, contSum, blockDurFrame, indivSeq, areaSeq)
indivSum.full<- data.frame(data.table::rbindlist(summary.contacts), stringsAsFactors = TRUE)
indivSum.full$block <- unname(unlist(x[1]))
indivSum.full$block.start <- unique(lubridate::as_datetime(blockDurFrame$block.start))
indivSum.full$block.end <- unique(lubridate::as_datetime(blockDurFrame$block.end))
indivSum.full$numBlocks <- unique(blockDurFrame$numBlocks)
return(indivSum.full)
}
contSum <-function(x,y, indivSeq, areaSeq){
me = (unname(unlist(x[1])))
if(length(y$dyadMember1) > 0){
indivContact1 <- y[c(which(as.character(y$dyadMember1) == me)),]
indivContact2 <- y[c(which(as.character(y$dyadMember2) == me)),]
}else{
indivContact1 <- y[c(which(as.character(y$indiv.id) == me)),]
indivContact2 <- matrix(nrow=0,ncol=0)
}
if((nrow(indivContact1) >= 1) & (nrow(indivContact2) >= 1)){
indivContact.full <- data.frame(data.table::rbindlist(list(indivContact1,indivContact2)), stringsAsFactors = TRUE)
specIndivSeq = unique(c(as.character(indivContact.full$dyadMember1),as.character(indivContact.full$dyadMember2)))
specIndivSeq1 = specIndivSeq[-which(specIndivSeq == me)]
}
if((nrow(indivContact1) >= 1) & (nrow(indivContact2) == 0)){
indivContact.full <- indivContact1
if(length(y$dyadMember1) > 0){
specIndivSeq = unique(c(as.character(indivContact.full$dyadMember1),as.character(indivContact.full$dyadMember2)))
specIndivSeq1 = specIndivSeq[-which(specIndivSeq == me)]
}else{
specIndivSeq1 = unique(as.character(indivContact.full$area.id))
}
}
if((nrow(indivContact2) >= 1) & (nrow(indivContact1) == 0)){
indivContact.full <- indivContact2
specIndivSeq = unique(c(as.character(indivContact.full$dyadMember1),as.character(indivContact.full$dyadMember2)))
specIndivSeq1 = specIndivSeq[-which(specIndivSeq == me)]
}
if((nrow(indivContact2) == 0) & (nrow(indivContact1) == 0)){
indivContact.full <- indivContact1
specIndivSeq1 = 0
}
if(length(y$dyadMember1) > 0){
if(nrow(indivContact.full) > 1){
indivSeqFrame1 <-data.frame(indivSeq, stringsAsFactors = TRUE)
contactSum<-apply(indivSeqFrame1, 1, distributeContacts1, indivContact.full, me)
sumTable <- data.frame(matrix(ncol = (3+length(indivSeq)), nrow = 1), stringsAsFactors = TRUE)
colnames(sumTable) <- c("id","totalDegree","totalContactDurations", paste("contactDuration_Indiv",indivSeq, sep = ""))
sumTable$id = me
sumTable$totalDegree <- length(specIndivSeq1)
sumTable$totalContactDurations = sum(indivContact.full$contactDuration)
sumTable[1,4:ncol(sumTable)] <- contactSum
sumTable[,match(paste("contactDuration_Indiv",me, sep = ""), names(sumTable))] = NA
}else{
if(nrow(indivContact.full) == 1){
sumTable <- data.frame(matrix(ncol = (3+length(indivSeq)), nrow = 1), stringsAsFactors = TRUE)
colnames(sumTable) <- c("id","totalDegree","totalContactDurations", paste("contactDuration_Indiv",indivSeq, sep = ""))
sumTable$id = me
sumTable$totalDegree <- 1
sumTable$totalContactDurations = indivContact.full$contactDuration
sumTable[1,4:ncol(sumTable)] <- 0
sumTable[,match(paste("contactDuration_Indiv",specIndivSeq1, sep = ""), names(sumTable))] = indivContact.full$contactDuration
sumTable[,match(paste("contactDuration_Indiv",me, sep = ""), names(sumTable))] = NA
}
if(nrow(indivContact.full) == 0){
sumTable <- data.frame(matrix(ncol = (3+length(indivSeq)), nrow = 1), stringsAsFactors = TRUE)
colnames(sumTable) <- c("id","totalDegree","totalContactDurations", paste("contactDuration_Indiv",indivSeq, sep = ""))
sumTable$id = me
sumTable[1,2:ncol(sumTable)] <- 0
sumTable[,match(paste("contactDuration_Indiv",me, sep = ""), names(sumTable))] = NA
}
}
}else{
if(nrow(indivContact.full) > 1){
areaSeqFrame <- data.frame(areaSeq, stringsAsFactors = TRUE)
contactSum<-apply(areaSeqFrame, 1, distributeContacts2, indivContact.full)
sumTable <- data.frame(matrix(ncol = (3+length(areaSeq)), nrow = 1), stringsAsFactors = TRUE)
colnames(sumTable) <- c("id","totalDegree","totalContactDurations", paste("contactDuration_Area_",areaSeq, sep = ""))
sumTable$id = me
sumTable$totalDegree <- length(specIndivSeq1)
sumTable$totalContactDurations = sum(indivContact.full$contactDuration)
sumTable[1,4:ncol(sumTable)] <- contactSum
}else{
if(nrow(indivContact.full) == 1){
areaVec <- unique(y$area.id)
sumTable <- data.frame(matrix(ncol = (3+length(areaSeq)), nrow = 1), stringsAsFactors = TRUE)
colnames(sumTable) <- c("id","totalDegree","totalContactDurations", paste("contactDuration_Area_",areaSeq, sep = ""))
sumTable$id = me
sumTable$totalDegree <- 1
sumTable$totalContactDurations = indivContact.full$contactDuration
sumTable[1,4:ncol(sumTable)] <- 0
sumTable[,match(paste("contactDuration_Area_",areaVec, sep = ""), names(sumTable))] = indivContact.full$contactDuration
}
if(nrow(indivContact.full) == 0){
sumTable <- data.frame(matrix(ncol = (3+length(areaSeq)), nrow = 1), stringsAsFactors = TRUE)
colnames(sumTable) <- c("id","totalDegree","totalContactDurations", paste("contactDuration_Area_",areaSeq, sep = ""))
sumTable$id = me
sumTable[1,2:ncol(sumTable)] <- 0
}
}
}
return(sumTable)
}
distributeContacts1<- function(x,y, me){
if(unname(unlist(x[1])) == me){
spec.durations = 0
}else{
contact1 <- y[c(which(as.character(y$dyadMember1) == unname(unlist(x[1])))),]
contact2 <- y[c(which(as.character(y$dyadMember2) == unname(unlist(x[1])))),]
if((nrow(contact1) >= 1) & (nrow(contact2) >= 1)){
contact.full <- data.frame(data.table::rbindlist(list(contact1,contact2)), stringsAsFactors = TRUE)
}
if((nrow(contact1) >= 1) & (nrow(contact2) == 0)){
contact.full <- contact1
}
if((nrow(contact2) >= 1) & (nrow(contact1) == 0)){
contact.full <- contact2
}
if((nrow(contact2) == 0) & (nrow(contact1) == 0)){
contact.full <- contact1
}
spec.durations <- ifelse(nrow(contact.full) >= 1, sum(contact.full$contactDuration),0)
}
return(spec.durations)
}
distributeContacts2<- function(x,y){
contact.full <- y[c(which(y$area.id == unname(unlist(x[1])))),]
spec.durations <- ifelse(nrow(contact.full) >= 1, sum(contact.full$contactDuration),0)
return(spec.durations)
}
if(importBlocks == TRUE){
if(length(x$dyadMember1) > 0){
x<-x[order(x$block,x$dyadMember1,x$dyadMember2),]
indivVec <- c(as.character(x[,match("dyadMember1", names(x))]), as.character(x[,match("dyadMember2", names(x))]))
areaSeq = NULL
}else{
x<-x[order(x$block,x$indiv.id),]
indivVec <- x[,match("indiv.id", names(x))]
areaVec <- x[,match("area.id", names(x))]
areaVec <- areaVec[order(areaVec)]
areaSeq<-as.character(unique(areaVec))
}
indivSeq <- unique(indivVec)
indivSeq<-indivSeq[order(indivSeq)]
indivSeq<-as.character(indivSeq)
if(parallel == TRUE){
cl <- parallel::makeCluster(nCores)
doParallel::registerDoParallel(cl)
on.exit(parallel::stopCluster(cl))
summary.block<- foreach::foreach(i = unique(as.character(x$block))) %dopar% blockSum(i, x, indivSeq, areaSeq)
}else{
blockVecFrame <- data.frame(unique(as.character(x$block)), stringsAsFactors = TRUE)
summary.block <- apply(blockVecFrame, 1, blockSum, x, indivSeq, areaSeq)
}
summaryTable<- data.frame(data.table::rbindlist(summary.block), stringsAsFactors = TRUE)
summaryTable<-summaryTable[order(as.numeric(as.character(summaryTable$block)),summaryTable$id),]
}else{
if(length(x$dyadMember1) > 0){
x<-x[order(x$dyadMember1,x$dyadMember2),]
indivVec <- c(as.character(x[,match("dyadMember1", names(x))]), as.character(x[,match("dyadMember2", names(x))]))
areaSeq = NULL
}else{
x<-x[order(x$indiv.id),]
indivVec <- x[,match("indiv.id", names(x))]
areaVec <- x[,match("area.id", names(x))]
areaVec <- areaVec[order(areaVec)]
areaSeq<-as.character(unique(areaVec))
}
indivSeq <- unique(indivVec)
indivSeq<-indivSeq[order(indivSeq)]
indivSeq<-as.character(indivSeq)
indivSeqFrame <- data.frame(indivSeq, stringsAsFactors = TRUE)
summary.contacts <- apply(indivSeqFrame, 1, contSum, x, indivSeq, areaSeq)
summaryTable<- data.frame(data.table::rbindlist(summary.contacts), stringsAsFactors = TRUE)
summaryTable<-summaryTable[order(summaryTable$id),]
}
return(summaryTable)
}
if(is.data.frame(x) == FALSE & is.list(x) == TRUE){
summaryList<-lapply(x, summary.generator, importBlocks, parallel, nCores)
if(avg == TRUE){
full.summary<- data.frame(data.table::rbindlist(summaryList, fill = TRUE), stringsAsFactors = TRUE)
idSeq<-unique(full.summary$id)
if(importBlocks == TRUE){
blockSeq<-unique(full.summary$block)
sumTab <- apply(data.frame(blockSeq, stringsAsFactors = TRUE), 1, summaryAgg.block, y = full.summary)
sumTab.agg <- data.frame(data.table::rbindlist(sumTab), stringsAsFactors = TRUE)
}else{
sumTab.agg<-stats::aggregate(full.summary[,-match("id", colnames(full.summary))], list(id = full.summary$id), mean)
}
summary.output<-list(sumTab.agg, summaryList)
names(summary.output)<-c("avg.","contactSummaries.")
}else{
summary.output<- summaryList
}
}else{
summary.output <- summary.generator(x, importBlocks, parallel, nCores)
}
return(summary.output)
}
edgeGenerator.noBlock<-function(x, removeDuplicates = dupAction, par = parallel, cores = nCores){
confirm_edges.noBlock<-function(x,y){
if(length(levels(unname(unlist(x[1])))) > 1){
x1.id <- droplevels(unname(unlist(x[1])))
}else{
x1.id <-unname(unlist(x[1]))
}
if(length(levels(unname(unlist(x[2])))) > 1){
x2.id <- droplevels(unname(unlist(x[2])))
}else{
x2.id <-unname(unlist(x[2]))
}
out.frame<-data.frame(from = x1.id, to = x2.id, stringsAsFactors = TRUE)
y.ContactNames<-c(NA,NA,NA,substring((names(y[grep("contactDuration_", names(y))])),22))
duration <- unname(unlist(y[which(y$id == x1.id), which(y.ContactNames == x2.id)]))
duration.corrected<-ifelse(duration > 0, duration, NA)
out.frame$durations<-duration.corrected
return(out.frame)
}
contactSummary<-summarizeContacts(x, importBlocks = FALSE, parallel = par, nCores = cores)
if(is.data.frame(contactSummary) == FALSE & is.list(contactSummary) == TRUE){
if (parallel == TRUE){
cl <- parallel::makeCluster(nCores)
doParallel::registerDoParallel(cl)
on.exit(parallel::stopCluster(cl))
confirmed_edges.list <- foreach::foreach(k = 1:length(contactSummary), .packages = "foreach") %dopar% {
contactSummary.frame <- contactSummary[[k]]
contactSummary.node1 <- unique(contactSummary.frame$id)
contactSummary.node2 <- substring((names(contactSummary.frame[grep("contactDuration_", names(contactSummary.frame))])),22)
potential_edges <- expand.grid(contactSummary.node1, contactSummary.node2, stringsAsFactors = TRUE)
names(potential_edges) <- c("from", "to")
potential.ntwrk <- igraph::simplify(igraph::graph_from_data_frame(potential_edges, directed = FALSE), remove.multiple = TRUE)
potential_edges <- igraph::as_data_frame(potential.ntwrk)
edgelist<-apply(potential_edges,1,confirm_edges.noBlock, y=contactSummary.frame)
edgeFrame<-data.frame(data.table::rbindlist(edgelist), stringsAsFactors = TRUE)
confirmed_edges <- edgeFrame[is.na(edgeFrame$duration) == FALSE,]
if(removeDuplicates == FALSE){
confirmed_edges.reflected <- confirmed_edges
confirmed_edges.reflected[,c(1,2)] <- confirmed_edges.reflected[,c(2,1)]
confirmed_edges <- data.frame(data.table::rbindlist(list(confirmed_edges, confirmed_edges.reflected)))
}
rownames(confirmed_edges)<-seq(1,nrow(confirmed_edges))
return(confirmed_edges)
}
}else{
confirmed_edges.list <- foreach::foreach(k = 1:length(contactSummary), .packages = "foreach") %do% {
contactSummary.frame <- contactSummary[[k]]
contactSummary.node1 <- unique(contactSummary.frame$id)
contactSummary.node2 <- substring((names(contactSummary.frame[grep("contactDuration_", names(contactSummary.frame))])),22)
potential_edges <- expand.grid(contactSummary.node1, contactSummary.node2, stringsAsFactors = TRUE)
names(potential_edges) <- c("from", "to")
potential.ntwrk <- igraph::simplify(igraph::graph_from_data_frame(potential_edges, directed = FALSE), remove.multiple = TRUE)
potential_edges <- igraph::as_data_frame(potential.ntwrk)
edgelist<-apply(potential_edges,1,confirm_edges.noBlock, y=contactSummary.frame)
edgeFrame<-data.frame(data.table::rbindlist(edgelist), stringsAsFactors = TRUE)
confirmed_edges <- edgeFrame[is.na(edgeFrame$duration) == FALSE,]
if(removeDuplicates == FALSE){
confirmed_edges.reflected <- confirmed_edges
confirmed_edges.reflected[,c(1,2)] <- confirmed_edges.reflected[,c(2,1)]
confirmed_edges <- data.frame(data.table::rbindlist(list(confirmed_edges, confirmed_edges.reflected)))
}
rownames(confirmed_edges)<-seq(1,nrow(confirmed_edges))
return(confirmed_edges)
}
}
return(confirmed_edges.list)
}else{
contactSummary.node1 <- unique(contactSummary$id)
contactSummary.node2 <- substring((names(contactSummary[grep("contactDuration_", names(contactSummary))])),22)
potential_edges <- expand.grid(contactSummary.node1, contactSummary.node2, stringsAsFactors = TRUE)
names(potential_edges) <- c("from", "to")
potential.ntwrk <- igraph::simplify(igraph::graph_from_data_frame(potential_edges, directed = FALSE), remove.multiple = TRUE)
potential_edges <- igraph::as_data_frame(potential.ntwrk)
edgelist<-apply(potential_edges,1,confirm_edges.noBlock, y=contactSummary)
edgeFrame<-data.frame(data.table::rbindlist(edgelist), stringsAsFactors = TRUE)
confirmed_edges <- edgeFrame[is.na(edgeFrame$duration) == FALSE,]
if(removeDuplicates == FALSE){
confirmed_edges.reflected <- confirmed_edges
confirmed_edges.reflected[,c(1,2)] <- confirmed_edges.reflected[,c(2,1)]
confirmed_edges <- data.frame(data.table::rbindlist(list(confirmed_edges, confirmed_edges.reflected)))
}
rownames(confirmed_edges)<-seq(1,nrow(confirmed_edges))
return(confirmed_edges)
}
}
edgeGenerator.Block<-function(x, removeDuplicates = dupAction, par = parallel, cores = nCores){
block <-NULL
confirm_edges.Block<-function(x,y){
if(length(levels(unname(unlist(x[2])))) > 1){
x2.id <- droplevels(unname(unlist(x[2])))
}else{
x2.id <-unname(unlist(x[2]))
}
if(length(levels(unname(unlist(x[3])))) > 1){
x3.id <- droplevels(unname(unlist(x[3])))
}else{
x3.id <-unname(unlist(x[3]))
}
out.frame<-data.frame(from = x2.id, to = x3.id, stringsAsFactors = TRUE)
y.ContactNames<-c(NA,NA,NA,substring((names(y[grep("contactDuration_", names(y))])),22))
duration <- unname(unlist(y[which(y$id == x2.id & y$block == unname(unlist(x[1]))), which(y.ContactNames == x3.id)]))
duration.corrected<-ifelse(duration > 0, duration, NA)
out.frame$durations<-duration.corrected
out.frame$block <- unname(unlist(x[1]))
out.frame$block.start <- unname(unlist(as.character(x[4])))
out.frame$block.end <- unname(unlist(as.character(x[5])))
return(out.frame)
}
contactSummary<-summarizeContacts(x, importBlocks = TRUE, parallel = par, nCores = cores)
if(is.data.frame(contactSummary) == FALSE & is.list(contactSummary) == TRUE){
if (parallel == TRUE){
cl <- parallel::makeCluster(nCores)
doParallel::registerDoParallel(cl)
on.exit(parallel::stopCluster(cl))
confirmed_edges.list <- foreach::foreach(k = 1:length(contactSummary), .packages = "foreach") %dopar% {
contactSummary.frame <- contactSummary[[k]]
contactSummary.node1 <- unique(contactSummary.frame$id)
contactSummary.node2 <- substring((names(contactSummary.frame[grep("contactDuration_", names(contactSummary.frame))])),22)
block_info<-data.frame(block = unique(contactSummary.frame$block), block.start = unique(contactSummary.frame$block.start), block.end = unique(contactSummary.frame$block.end), stringsAsFactors = TRUE)
potential_edges1 <- expand.grid(contactSummary.node1, contactSummary.node2, block_info$block, stringsAsFactors = TRUE)
names(potential_edges1) <- c("from", "to", "block")
potential_edges2<-merge(potential_edges1, block_info, by = "block")
potential_edges2<-potential_edges2[order(as.numeric(as.character(potential_edges2$block))),]
blocks.adjusted<- foreach::foreach(j = unique(potential_edges2$block), .packages = "foreach") %do% {
blockSub<- droplevels(subset(potential_edges2, block == j))
potential.ntwrk <- igraph::simplify(igraph::graph_from_data_frame(blockSub[,c(2,3)], directed = FALSE), remove.multiple = TRUE)
blockSub.edges <- igraph::as_data_frame(potential.ntwrk)
blockSub.out <- data.frame(block = unique(blockSub$block), from = blockSub.edges$from, to = blockSub.edges$to, block.start = unique(blockSub$block.start), block.end = unique(blockSub$block.end))
return(blockSub.out)
}
potential_edges2 <- data.frame(data.table::rbindlist(blocks.adjusted))
edgelist<-apply(potential_edges2,1,confirm_edges.Block, y=contactSummary.frame)
edgeFrame<-data.frame(data.table::rbindlist(edgelist), stringsAsFactors = TRUE)
confirmed_edges <- edgeFrame[is.na(edgeFrame$duration) == FALSE,]
if(removeDuplicates == FALSE){
confirmed_edges.reflected <- confirmed_edges
confirmed_edges.reflected[,c(1,2)] <- confirmed_edges.reflected[,c(2,1)]
confirmed_edges <- data.frame(data.table::rbindlist(list(confirmed_edges, confirmed_edges.reflected)))
}
rownames(confirmed_edges)<-seq(1,nrow(confirmed_edges))
return(confirmed_edges)
}
}else{
confirmed_edges.list <- foreach::foreach(k = 1:length(contactSummary), .packages = "foreach") %do% {
contactSummary.frame <- contactSummary[[k]]
contactSummary.node1 <- unique(contactSummary.frame$id)
contactSummary.node2 <- substring((names(contactSummary.frame[grep("contactDuration_", names(contactSummary.frame))])),22)
block_info<-data.frame(block = unique(contactSummary.frame$block), block.start = unique(contactSummary.frame$block.start), block.end = unique(contactSummary.frame$block.end), stringsAsFactors = TRUE)
potential_edges1 <- expand.grid(contactSummary.node1, contactSummary.node2, block_info$block, stringsAsFactors = TRUE)
names(potential_edges1) <- c("from", "to", "block")
potential_edges2<-merge(potential_edges1, block_info, by = "block")
potential_edges2<-potential_edges2[order(as.numeric(as.character(potential_edges2$block))),]
blocks.adjusted<- foreach::foreach(j = unique(potential_edges2$block), .packages = "foreach") %do% {
blockSub<- droplevels(subset(potential_edges2, block == j))
potential.ntwrk <- igraph::simplify(igraph::graph_from_data_frame(blockSub[,c(2,3)], directed = FALSE), remove.multiple = TRUE)
blockSub.edges <- igraph::as_data_frame(potential.ntwrk)
blockSub.out <- data.frame(block = unique(blockSub$block), from = blockSub.edges$from, to = blockSub.edges$to, block.start = unique(blockSub$block.start), block.end = unique(blockSub$block.end))
return(blockSub.out)
}
potential_edges2 <- data.frame(data.table::rbindlist(blocks.adjusted))
edgelist<-apply(potential_edges2,1,confirm_edges.Block, y=contactSummary.frame)
edgeFrame<-data.frame(data.table::rbindlist(edgelist), stringsAsFactors = TRUE)
confirmed_edges <- edgeFrame[is.na(edgeFrame$duration) == FALSE,]
if(removeDuplicates == FALSE){
confirmed_edges.reflected <- confirmed_edges
confirmed_edges.reflected[,c(1,2)] <- confirmed_edges.reflected[,c(2,1)]
confirmed_edges <- data.frame(data.table::rbindlist(list(confirmed_edges, confirmed_edges.reflected)))
}
rownames(confirmed_edges)<-seq(1,nrow(confirmed_edges))
return(confirmed_edges)
}
}
return(confirmed_edges.list)
}else{
contactSummary.node1 <- unique(contactSummary$id)
contactSummary.node2 <- substring((names(contactSummary[grep("contactDuration_", names(contactSummary))])),22)
block_info<-data.frame(block = unique(contactSummary$block), block.start = unique(contactSummary$block.start), block.end = unique(contactSummary$block.end), stringsAsFactors = TRUE)
potential_edges1 <- expand.grid(contactSummary.node1, contactSummary.node2, block_info$block, stringsAsFactors = TRUE)
names(potential_edges1) <- c("from", "to", "block")
potential_edges2<-merge(potential_edges1, block_info, by = "block")
potential_edges2<-potential_edges2[order(as.numeric(as.character(potential_edges2$block))),]
blocks.adjusted<- foreach::foreach(j = unique(potential_edges2$block), .packages = "foreach") %do% {
blockSub<- droplevels(subset(potential_edges2, block == j))
potential.ntwrk <- igraph::simplify(igraph::graph_from_data_frame(blockSub[,c(2,3)], directed = FALSE), remove.multiple = TRUE)
blockSub.edges <- igraph::as_data_frame(potential.ntwrk)
blockSub.out <- data.frame(block = unique(blockSub$block), from = blockSub.edges$from, to = blockSub.edges$to, block.start = unique(blockSub$block.start), block.end = unique(blockSub$block.end))
return(blockSub.out)
}
potential_edges2 <- data.frame(data.table::rbindlist(blocks.adjusted))
edgelist<-apply(potential_edges2,1,confirm_edges.Block, y=contactSummary)
edgeFrame<-data.frame(data.table::rbindlist(edgelist), stringsAsFactors = TRUE)
confirmed_edges <- edgeFrame[is.na(edgeFrame$duration) == FALSE,]
if(removeDuplicates == FALSE){
confirmed_edges.reflected <- confirmed_edges
confirmed_edges.reflected[,c(1,2)] <- confirmed_edges.reflected[,c(2,1)]
confirmed_edges <- data.frame(data.table::rbindlist(list(confirmed_edges, confirmed_edges.reflected)))
}
rownames(confirmed_edges)<-seq(1,nrow(confirmed_edges))
return(confirmed_edges)
}
}
if(importBlocks == FALSE){
edgeSet<-edgeGenerator.noBlock(x)
}else{
edgeSet<-edgeGenerator.Block(x)
}
return(edgeSet)
}
|
saddlepointRuinprob <- function(process, jensen = FALSE, normalize = TRUE) {
stopifnot(is.logical(jensen), is.logical(normalize))
p <- process[['p']]
zeta <- process[['zeta']]
vx <- process[['vx']]
KL <- process[['KL']]
KL.d1 <- process[['KL.d1']]
KL.d2 <- process[['KL.d2']]
if (normalize) {
corrconst <- integrate(
f = function(v) {
exp(KL(v) - v * KL.d1(v)) * sqrt(KL.d2(v)) * dnorm(0.0)
},
lower = -Inf,
upper = adjcoef(process) - .Machine$double.eps^(2.0 / 3.0)
)$value
} else {
corrconst <- 1.0
}
if (jensen) {
psi <- function(x) {
res <- pnorm(vx(x)$z, lower.tail = FALSE)
res[almost.equal(x, 0.0)] <- 1.0
return(res)
}
psi.v <- function(v) {
pnorm(process[['zv']](v), lower.tail = FALSE)
}
psi.1 <- function(x) {
v <- vx(x)
res <- pnorm(v$z - log(1.0 - v$v / (zeta * p * corrconst)) / v$r) - pnorm(v$z)
res[almost.equal(x, 0.0)] <- 1.0
return(res)
}
psi.1.v <- function(v) {
z <- process[['zv']](v)
r <- process[['rv']](v)
pnorm(z - log(1.0 - v / (zeta * p * corrconst)) / r) - pnorm(z)
}
psi.2 <- function(x) {
v <- vx(x)
res <- pnorm(v$z - log(1.0 - v$v / (zeta * p * corrconst)) / v$r, lower.tail = FALSE)
res[almost.equal(x, 0.0)] <- 0.0
return(res)
}
psi.2.v <- function(v) {
z <- process[['zv']](v)
r <- process[['rv']](v)
pnorm(z - log(1.0 - v / (zeta * p * corrconst)) / r, lower.tail = FALSE)
}
} else {
psi <- function(x) {
v <- vx(x)
res <- pnorm(v$r, lower.tail = FALSE) - dnorm(v$r) * (1.0 / v$r - 1.0 / v$s)
res[almost.equal(x, 0.0)] <- 1.0
return(res)
}
psi.v <- function(v) {
r <- process[['rv']](v)
s <- process[['sv']](v)
pnorm(r, lower.tail = FALSE) - dnorm(r) * (1.0 / r - 1.0 / s)
}
psi.1 <- function(x) {
v <- vx(x)
res <- exp(v$value) * dnorm(0.0) / (sqrt(v$hessian) * p * zeta * corrconst)
res[almost.equal(x, 0.0)] <- 1.0
return(res)
}
psi.1.v <- function(v) {
exp(KL(v) - v * KL.d1(v)) / sqrt(KL.d2(v) * p * zeta * corrconst) * dnorm(0.0)
}
psi.2 <- function(x) {
v <- vx(x)
res <- pnorm(v$r, lower.tail = FALSE) - dnorm(v$r) * (1.0 / v$r - 1.0 / v$s * (1.0 - v$v / (p * zeta * corrconst)))
res[almost.equal(x, 0.0)] <- 0.0
return(res)
}
psi.2.v <- function(v) {
r <- process[['rv']](v)
s <- process[['sv']](v)
pnorm(r, lower.tail = FALSE) - dnorm(r) * (1.0 / r - 1.0 / s * (1.0 - v / (p * zeta * corrconst)))
}
}
return(structure(.Data = list(psi = psi,
psi.1 = psi.1,
psi.2 = psi.2),
compmethod = 'saddlepoint',
riskproc = process,
parameters = list(jensen = jensen,
normalize = normalize),
diagnostics = list(corrconst = corrconst,
psi.v = psi.v,
psi.1.v = psi.1.v,
psi.2.v = psi.2.v)))
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
fig.width = 8,
fig.height = 6,
out.width = '100%'
)
library(ggside)
p <- ggplot(mpg, aes(displ, hwy, colour = class)) +
geom_point(size = 2) +
theme_bw()
p
geom_xsidedensity_legacy <- function(mapping = NULL, data = NULL,
stat = "density", position = "identity",
...,
na.rm = FALSE,
orientation = "x",
show.legend = NA,
inherit.aes = TRUE,
outline.type = "upper") {
outline.type <- match.arg(outline.type, c("both", "upper", "lower", "full"))
l <- layer(
data = data,
mapping = mapping,
stat = stat,
geom = ggside:::GeomXsidedensity,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
na.rm = na.rm,
orientation = orientation,
outline.type = outline.type,
...
),
layer_class = ggside:::XLayer
)
structure(l, class = c("ggside_layer",class(l)))
}
p + geom_xsidedensity_legacy(aes(y = after_stat(density)))
p +
geom_xsidedensity() +
geom_ysidedensity()
p +
geom_xsidedensity(aes(y = after_stat(count))) +
geom_ysidedensity(aes(x = after_stat(scaled)))
p +
geom_xsidedensity(orientation = "y")
|
structure(list(url = "https://api.scryfall.com/symbology/parse-mana?cost=k",
status_code = 422L, headers = structure(list(date = "Wed, 05 Jan 2022 05:19:30 GMT",
`content-type` = "application/json; charset=utf-8", `x-frame-options` = "DENY",
`x-xss-protection` = "1; mode=block", `x-content-type-options` = "nosniff",
`x-download-options` = "noopen", `x-permitted-cross-domain-policies` = "none",
`referrer-policy` = "strict-origin-when-cross-origin",
`access-control-allow-origin` = "*", `access-control-allow-methods` = "GET, POST, DELETE, OPTIONS",
`access-control-allow-headers` = "Accept, Accept-Charset, Accept-Language, Authorization, Cache-Control, Content-Language, Content-Type, DNT, Host, If-Modified-Since, Keep-Alive, Origin, Referer, User-Agent, X-Requested-With",
`access-control-max-age` = "300", `x-robots-tag` = "none",
`cache-control` = "no-cache", vary = "Accept-Encoding",
`content-encoding` = "gzip", `strict-transport-security` = "max-age=31536000; includeSubDomains; preload",
via = "1.1 vegur", `cf-cache-status` = "DYNAMIC", `expect-ct` = "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"",
`report-to` = "{\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=K5Hf2jmoK4woQJ%2BjaXd6kR8Xt%2B5r2XlDk3d2uL7NKB9AzjixtIu0mCxFzNuSuatZl2IzzYiM7DBI4nu9SrrNIRfDdrrHBrKsOBI0OwghGRMFNpCtap0IVFbMYI%2BSnysmY70igQrfuqafg0m0JG0%3D\"}],\"group\":\"cf-nel\",\"max_age\":604800}",
nel = "{\"success_fraction\":0,\"report_to\":\"cf-nel\",\"max_age\":604800}",
server = "cloudflare", `cf-ray` = "6c8a4087ce444edd-GRU",
`alt-svc` = "h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400, h3-28=\":443\"; ma=86400, h3-27=\":443\"; ma=86400"), class = c("insensitive",
"list")), all_headers = list(list(status = 422L, version = "HTTP/2",
headers = structure(list(date = "Wed, 05 Jan 2022 05:19:30 GMT",
`content-type` = "application/json; charset=utf-8",
`x-frame-options` = "DENY", `x-xss-protection` = "1; mode=block",
`x-content-type-options` = "nosniff", `x-download-options` = "noopen",
`x-permitted-cross-domain-policies` = "none", `referrer-policy` = "strict-origin-when-cross-origin",
`access-control-allow-origin` = "*", `access-control-allow-methods` = "GET, POST, DELETE, OPTIONS",
`access-control-allow-headers` = "Accept, Accept-Charset, Accept-Language, Authorization, Cache-Control, Content-Language, Content-Type, DNT, Host, If-Modified-Since, Keep-Alive, Origin, Referer, User-Agent, X-Requested-With",
`access-control-max-age` = "300", `x-robots-tag` = "none",
`cache-control` = "no-cache", vary = "Accept-Encoding",
`content-encoding` = "gzip", `strict-transport-security` = "max-age=31536000; includeSubDomains; preload",
via = "1.1 vegur", `cf-cache-status` = "DYNAMIC",
`expect-ct` = "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"",
`report-to` = "{\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=K5Hf2jmoK4woQJ%2BjaXd6kR8Xt%2B5r2XlDk3d2uL7NKB9AzjixtIu0mCxFzNuSuatZl2IzzYiM7DBI4nu9SrrNIRfDdrrHBrKsOBI0OwghGRMFNpCtap0IVFbMYI%2BSnysmY70igQrfuqafg0m0JG0%3D\"}],\"group\":\"cf-nel\",\"max_age\":604800}",
nel = "{\"success_fraction\":0,\"report_to\":\"cf-nel\",\"max_age\":604800}",
server = "cloudflare", `cf-ray` = "6c8a4087ce444edd-GRU",
`alt-svc` = "h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400, h3-28=\":443\"; ma=86400, h3-27=\":443\"; ma=86400"), class = c("insensitive",
"list")))), cookies = structure(list(domain = ".api.scryfall.com",
flag = TRUE, path = "/", secure = FALSE, expiration = structure(1641440572, class = c("POSIXct",
"POSIXt")), name = "heroku-session-affinity", value = "REDACTED"), row.names = c(NA,
-1L), class = "data.frame"), content = charToRaw("{\n \"object\": \"error\",\n \"code\": \"validation_error\",\n \"status\": 422,\n \"details\": \"The string fragment(s) “K” could not be understood as part of mana cost.\"\n}"),
date = structure(1641359970, class = c("POSIXct", "POSIXt"
), tzone = "GMT"), times = c(redirect = 0, namelookup = 3.7e-05,
connect = 3.8e-05, pretransfer = 0.000107, starttransfer = 0.198428,
total = 0.198566)), class = "response")
|
rangemap_enm <- function(model_output, occurrences = NULL, threshold_value = NULL,
threshold_omission = NULL, min_polygon_area = 0,
simplify = FALSE, simplify_level = 0, polygons = NULL,
extent_of_occurrence = TRUE, area_of_occupancy = TRUE,
final_projection = NULL, save_shp = FALSE,
name, overwrite = FALSE, verbose = TRUE) {
if (is.null(model_output)) {
stop("'model_output' is necessary to perform the analysis.")
}
if (save_shp == TRUE) {
if (missing(name)) {
stop("Argument 'name' must be defined if 'save_shp' = TRUE.")
}
if (file.exists(paste0(name, ".shp")) & overwrite == FALSE) {
stop("Files already exist, use 'overwrite' = TRUE.")
}
}
WGS84 <- sp::CRS("+init=epsg:4326")
if (is.null(final_projection)) {
final_projection <- WGS84
} else {
final_projection <- sp::CRS(final_projection)
}
if (!is.null(threshold_value) | !is.null(threshold_omission) |
!is.null(occurrences)) {
if (!is.null(threshold_value)) {
binary <- model_output >= threshold_value
} else {
if (!is.null(threshold_omission) & !is.null(occurrences)) {
occ <- occurrences[, 2:3]
o_suit <- na.omit(raster::extract(model_output, occ))
o_suit_sort <- sort(o_suit)
thres <- o_suit_sort[ceiling(length(occ[, 1]) * threshold_omission / 100) + 1]
binary <- model_output >= thres
} else {
stop(paste0("Parameters 'threshold_omission' and 'occurrences', or 'threshold_value'",
"\nmust be defined to perform the calculations."))
}
}
}
binary[binary[] == 0] <- NA
if (!is.null(occurrences)) {
occ <- as.data.frame(unique(occurrences))[, 1:3]
colnames(occ) <- c("Species", "Longitude", "Latitude")
}
if (is.na(model_output@crs)) {
raster::crs(binary) <- WGS84@projargs
}
enm_range <- as(binary, "SpatialPolygonsDataFrame")
enm_range <- rgeos::gUnaryUnion(enm_range, enm_range$layer)
enm_range <- sp::SpatialPolygonsDataFrame(enm_range, data = data.frame(ID = 1))
enm_range <- keep_big_polygons(polygons = enm_range, min_polygon_area)
if (simplify == TRUE) {
enm_range <- suppressWarnings(rgeos::gSimplify(enm_range, tol = simplify_level))
}
enm_range <- raster::disaggregate(enm_range)
if (is.null(polygons)) {
polygons <- simple_wmap(which = "simple")
}
LAEA <- LAEA_projection(spatial_object = enm_range)
if (!is.null(occurrences)) {
occ_sp <- sp::SpatialPointsDataFrame(coords = occ[, 2:3], data = occ,
proj4string = WGS84)
occ_pr <- sp::spTransform(occ_sp, LAEA)
}
enm_range_pr <- sp::spTransform(enm_range, LAEA)
area <- raster::area(enm_range_pr) / 1000000
areakm2 <- sum(area)
if (is.null(occurrences)) {
df <- data.frame(Species = "Species", area)
clip_area <- sp::SpatialPolygonsDataFrame(enm_range_pr, data = df,
match.ID = FALSE)
if (is.null(final_projection)) {
final_projection <- WGS84
} else {
final_projection <- sp::CRS(final_projection)
}
clip_area <- sp::spTransform(clip_area, final_projection)
if (save_shp == TRUE) {
if (verbose == TRUE) {
message("Writing shapefiles in the working directory.")
}
rgdal::writeOGR(clip_area, ".", name, driver = "ESRI Shapefile")
}
sp_dat <- data.frame(Species = "Species", Range_area = areakm2)
results <- sp_range(name = "ENM", summary = sp_dat, species_range = clip_area)
} else {
if (extent_of_occurrence == TRUE) {
eooc <- eoo(occ_sp@data, polygons)
eocckm2 <- eooc$area
extent_occurrence <- eooc$spolydf
extent_occurrence <- sp::spTransform(extent_occurrence, final_projection)
} else {
eocckm2 <- 0
extent_occurrence <- new("SpatialPolygonsDataFrame")
}
species <- as.character(occurrences[1, 1])
if (area_of_occupancy == TRUE) {
aooc <- aoo(occ_pr, species)
aocckm2 <- aooc$area
area_occupancy <- aooc$spolydf
area_occupancy <- sp::spTransform(area_occupancy, final_projection)
} else {
aocckm2 <- 0
area_occupancy <- new("SpatialPolygonsDataFrame")
}
clip_area <- sp::SpatialPolygonsDataFrame(enm_range_pr,
data = data.frame(species, area),
match.ID = FALSE)
clip_area <- sp::spTransform(clip_area, final_projection)
occ_pr <- sp::spTransform(occ_pr, final_projection)
if (save_shp == TRUE) {
if (verbose == TRUE) {
message("Writing shapefiles in the working directory.")
}
rgdal::writeOGR(clip_area, ".", name, driver = "ESRI Shapefile",
overwrite_layer = overwrite)
rgdal::writeOGR(occ_pr, ".", paste(name, "unique_records", sep = "_"),
driver = "ESRI Shapefile", overwrite_layer = overwrite)
if (!is.null(occurrences)) {
if (extent_of_occurrence == TRUE) {
rgdal::writeOGR(extent_occurrence, ".", paste(name, "extent_occ", sep = "_"),
driver = "ESRI Shapefile", overwrite_layer = overwrite)
}
if (area_of_occupancy == TRUE) {
rgdal::writeOGR(area_occupancy, ".", paste(name, "area_occ", sep = "_"),
driver = "ESRI Shapefile", overwrite_layer = overwrite)
}
}
}
sp_dat <- data.frame(Species = species, Unique_records = dim(occ_pr)[1],
Range_area = areakm2, Extent_of_occurrence = eocckm2,
Area_of_occupancy = aocckm2)
results <- sp_range_iucn(name = "ENM", summary = sp_dat,
species_unique_records = occ_pr,
species_range = clip_area,
extent_of_occurrence = extent_occurrence,
area_of_occupancy = area_occupancy)
}
return(results)
}
|
summary.lbreg <- function(object, ...)
{
se <- object$se
zval <- coef(object) / se
TAB <- cbind(Estimate = coef(object),
StdErr = se,
z.value = zval,
p.value = 2*pnorm(-abs(zval),mean=0,sd=1))
res <- list(call=object$call,
coefficients=TAB,
loglik=object$loglik,
df=object$df,
deviance=object$deviance,
residuals=object$residuals,
X2 = object$X2,
yclass = attr(object$terms, 'dataClasses')[1]
)
class(res) <- "summary.lbreg"
res
}
|
test_that("Test Timing mean", {
skip_on_cran()
data("sample_results", package = "benchmarkme")
expect_true(is.character(benchmarkme:::timings_mean(sample_results)))
}
)
|
require(randomForest)
require(MASS)
attach(Boston)
set.seed(101)
dim(Boston)
train=sample(1:nrow(Boston),300)
?Boston
Boston.rf=randomForest(medv ~ . , data = Boston , subset = train)
Boston.rf
plot(Boston.rf)
oob.err=double(13)
test.err=double(13)
for(mtry in 1:13)
{
rf=randomForest(medv ~ . , data = Boston , subset = train,mtry=mtry,ntree=400)
oob.err[mtry] = rf$mse[400]
pred<-predict(rf,Boston[-train,])
test.err[mtry]= with(Boston[-train,], mean( (medv - pred)^2))
cat(mtry," ")
}
test.err
oob.err
matplot(1:mtry , cbind(oob.err,test.err), pch=19 , col=c("red","blue"),type="b",ylab="Mean Squared Error",xlab="Number of Predictors Considered at each Split")
legend("topright",legend=c("Out of Bag Error","Test Error"),pch=19, col=c("red","blue"))
|
summary.tosANYN <-
function (object, quiet = FALSE, ...)
{
hwtosop <- object
ntests <- length(hwtosop$allpvals)
if (quiet == FALSE) {
cat("There are ", ntests, " hypothesis tests altogether\n")
cat("There were ", hwtosop$nreject, " reject(s)\n")
cat("P-val adjustment method was: ", object$mc.method[1], "\n")
}
rejix <- which(object$allpvals < object$alpha)
vmat <- cbind(object$allbigscale[rejix]-1,
object$alllitscale[rejix],
object$alllv[rejix],
object$allindex[rejix])
v <- as.data.frame(t(vmat))
class(v) <- "list"
if (quiet==FALSE) {
if (hwtosop$nreject != 0) {
cat("Listing rejects...\n")
for(i in 1:hwtosop$nreject) {
cat("P: ", v[[i]][1], " HWTlev: ", v[[i]][2],
" Max Poss Ix: ", v[[i]][3],
" Indices: ", v[[i]][c(-1,-2,-3)], "\n")
}
}
}
vret <- list(rejlist = v, nreject = hwtosop$nreject, mctype = object$p.adjust.method[1])
return(invisible(vret))
}
|
dhnorm <- function(x, sigma = 1, log = FALSE) {
cpp_dhnorm(x, sigma, log[1L])
}
phnorm <- function(q, sigma = 1, lower.tail = TRUE, log.p = FALSE) {
cpp_phnorm(q, sigma, lower.tail[1L], log.p[1L])
}
qhnorm <- function(p, sigma = 1, lower.tail = TRUE, log.p = FALSE) {
cpp_qhnorm(p, sigma, lower.tail[1L], log.p[1L])
}
rhnorm <- function(n, sigma = 1) {
if (length(n) > 1) n <- length(n)
cpp_rhnorm(n, sigma)
}
|
context("checking that the length of pse_pssm feature vector is equal to 40")
test_that("whether the pse_pssm function gives us the expected output",{
ss<-pse_pssm(system.file("extdata","C7GQS7.txt.pssm",package="PSSMCOOL"))
expect_equal(length(ss),40)
})
|
get_nhdplus <- function(AOI = NULL,
comid = NULL, nwis = NULL,
realization = "flowline",
streamorder = NULL,
t_srs = NULL){
if(!is.null(AOI)){
if(all(!methods::is(AOI,"sf"), !methods::is(AOI,"sfc"))){
stop("AOI must be of class sf.", .call = FALSE)
}
if(st_geometry_type(AOI) == "POINT"){
comid <- discover_nhdplus_id(AOI)
AOI <- NULL
}
}
if(!is.null(AOI) & !is.null(c(nwis, comid))){
stop("Either IDs (comid, nwis) or a spatial AOI can be passed.",.call = FALSE)
} else if(is.null(AOI) & is.null(c(nwis, comid))){
stop("IDs (comid, nwis) or a spatial AOI must be passed.",.call = FALSE)
}
hy_realizations = c("flowline", "catchment", 'outlet')
if("all" %in% realization){ realization = hy_realizations}
if(any(!realization %in% hy_realizations)){
stop(paste(realization, "not valid.\n Select from", paste(hy_realizations, collapse = ", ")))
}
geoms = list()
if(!is.null(nwis)){
comid = c(unlist(lapply(nwis, extact_comid_nwis)), comid)
}
if("catchment" %in% realization){
geoms$catchment <- query_usgs_geoserver(AOI = AOI, ids = comid,
type = "catchment",
t_srs = t_srs)
}
if(any(c("flowline", "outlet") %in% realization)){
geoms$flowline <- query_usgs_geoserver(AOI = AOI, ids = comid, type = 'nhd',
filter = streamorder_filter(streamorder),
t_srs = t_srs)
if("outlet" %in% realization){
geoms$outlet <- geoms$flowline
geoms$outlet$geometry <- st_geometry(
get_node(geoms$outlet,
position = "end")
)
}
}
geoms = tc(geoms)
geoms = geoms[names(geoms) %in% realization]
if(length(geoms) == 1){ geoms = geoms[[1]]}
return(geoms)
}
|
test_that("parallel.seeds is currently not reproducible", {
skip_if_not_installed("rjags")
withr::local_seed(11)
seed1 <- rjags::parallel.seeds("base::BaseRNG", 1)
withr::local_seed(11)
seed2 <- rjags::parallel.seeds("base::BaseRNG", 1)
expect_false(identical(seed1, seed2))
})
test_that("rjags replicable when prior in model", {
skip_if_not_installed("rjags")
code <- "model{beta ~ dunif(0,1)}"
inits <- list(
.RNG.name = "base::Wichmann-Hill",
.RNG.seed = 799289926L
)
model1 <- rjags::jags.model(textConnection(code),
data = list(),
inits = inits,
n.adapt = 0, quiet = TRUE
)
sample1 <- rjags::jags.samples(model1, variable.names = "beta", n.iter = 1)
model2 <- rjags::jags.model(textConnection(code),
data = list(),
inits = inits,
n.adapt = 0, quiet = TRUE
)
sample2 <- rjags::jags.samples(model2, variable.names = "beta", n.iter = 1)
expect_identical(sample1, sample2)
})
test_that("rjags not replicable when prior in data", {
skip_if_not_installed("rjags")
code <- "data{beta ~ dunif(0,1)} model{dummy <- 0}"
inits <- list(
.RNG.name = "base::Wichmann-Hill",
.RNG.seed = 799289926L
)
model1 <- rjags::jags.model(textConnection(code),
data = list(),
inits = inits,
n.adapt = 0, quiet = TRUE
)
sample1 <- rjags::jags.samples(model1, variable.names = "beta", n.iter = 1)
model2 <- rjags::jags.model(textConnection(code),
data = list(),
inits = inits,
n.adapt = 0, quiet = TRUE
)
sample2 <- rjags::jags.samples(model2, variable.names = "beta", n.iter = 1)
expect_false(identical(sample1, sample2))
})
|
require(pls)
sessionInfo()
rm(list = ls(all = TRUE))
mydata <- gasoline
form <- octane ~ NIR
nc <- 27
refmod <- mvr(form, nc = nc, data = mydata, method = "oscorespls")
refmod$method <- refmod$call <- refmod$fit.time <- NULL
save.image(file = "ref_singresp.RData")
rm(list = ls(all = TRUE))
mydata <- oliveoil
form <- sensory ~ chemical
nc <- 4
refmod <- mvr(form, nc = nc, data = mydata, method = "oscorespls")
refmod$method <- refmod$call <- refmod$fit.time <-NULL
for (i in 2:7) refmod[[i]] <- abs(refmod[[i]])
save.image(file = "ref_multiresp.RData")
|
outputNetworks_topEdges_matrix<-function(dataMatrix, subpopulationLabels, threshold){
SampleID<-dataMatrix[1,1]
inputMatrix<-cbind(dataMatrix, subpopulationLabels)
labels<-unique(subpopulationLabels)
for(i in 1:length(labels)){
inputMatrix_subpopSubset<-subset(inputMatrix, inputMatrix[,ncol(inputMatrix)] == i)
inputMatrix_subpopSubset_datapoints<-inputMatrix_subpopSubset[,c(2:(ncol(inputMatrix_subpopSubset)-1))]
png(paste(SampleID, '_Subpopulation', "0", i, '.png', sep=""))
MINetworkPlot_topEdges(inputMatrix_subpopSubset_datapoints, threshold)
title(main=paste("Subpopulation", i))
dev.off()
Networks<-MINetwork_matrix_topEdges(inputMatrix_subpopSubset_datapoints, threshold)
save(Networks, file=paste0(SampleID, "_", i, "_subpop_Network.Rdata"))
}
}
|
gdina_prob_item_designmatrix <- function( delta_jj, Mjjj, linkfct, eps_squeeze )
{
irf1 <- ( Mjjj %*% delta_jj )[,1]
if ( linkfct=="log"){
irf1 <- exp(irf1)
}
if ( linkfct=="logit"){
irf1 <- stats::plogis(irf1)
}
irf1 <- cdm_squeeze( irf1, c(eps_squeeze, 1-eps_squeeze) )
return(irf1)
}
|
summary.Multivar.PCA.ContCont <- function(object, ..., Object){
if (missing(Object)){Object <- object}
mode <- function(data) {
x <- data
z <- density(x)
mode_val <- z$x[which.max(z$y)]
fit <- list(mode_val= mode_val)
}
cat("\nFunction call:\n\n")
print(Object$Call)
cat("\n\n
cat("\n
cat("\n
cat(Object$Total.Num.Matrices)
cat("\n\n
cat("\n
cat(Object$Pos.Def)
cat("\n\n\n
cat("\n
cat("Mean (SD) PCA: ", format(round(mean(Object$PCA), 4), nsmall = 4), " (", format(round(sd(Object$PCA), 4), nsmall = 4), ")",
" [min: ", format(round(min(Object$PCA), 4), nsmall = 4), "; max: ", format(round(max(Object$PCA), 4), nsmall = 4), "]", sep="")
cat("\nMode PCA: ", format(round(mode(Object$PCA)$mode_val, 4), nsmall = 4))
cat("\n\nQuantiles of the PCA distribution: \n\n")
quant <- quantile(Object$PCA, probs = c(.05, .10, .20, .50, .80, .90, .95))
print(quant)
}
|
GWPR.pFtest <- function(formula, data, index, SDF, bw = NULL, adaptive = FALSE, p = 2, effect = "individual",
kernel = "bisquare", longlat = FALSE)
{
if(length(index) != 2)
{
stop("The \"index\" have included \"ID\" or/and \"time\" index.")
}
if(!((index[1] %in% colnames(data)) & (index[2] %in% colnames(data))))
{
stop("The data.frame(data) does not have the index columns.")
}
if(!(index[1] %in% colnames(SDF@data)))
{
stop("The SDF does not have the \"ID\" columns.")
}
if(is.null(bw))
{
stop("The bw must be set.")
}
varibale_name_in_equation <- all.vars(formula)
data <- dplyr::select(data, index, varibale_name_in_equation)
data$raw_order_data <- 1:nrow(data)
raw_id <- index[1]
colnames(data)[1] <- "id"
index[1] <- "id"
model <- "within"
.N <- 0
ID <- dplyr::select(data, index[1])
ID_num <- data.table::setDT(ID)[,list(Count=.N),names(ID)]
if(model == "within")
{
data <- drop_ID_with_single_observation(data, ID_num)
ID <- dplyr::select(data, index[1])
ID_num <- data.table::setDT(ID)[,list(Count=.N),names(ID)]
}
if (nrow(ID_num) > 1000)
{
message("Dear my friend, thanks for your patience!. We pass the bandwidth\n",
"selection part. Now, regression! This should be faster. Thanks.\n",
"................................................................\n")
huge_data_size <- TRUE
}
else
{
huge_data_size <- FALSE
}
SDF@data <- dplyr::select(SDF@data, dplyr::all_of(raw_id))
colnames(SDF@data)[1] <- "id"
dp.locat <- sp::coordinates(SDF)
coord <- cbind(as.data.frame(dp.locat), SDF@data$id)
colnames(coord) <- c("X", "Y", "id")
data <- dplyr::left_join(data, coord, by = "id")
lvl1_data <- data
if(huge_data_size)
{
message("Data Prepared! Go!............................................\n")
}
if (adaptive)
{
result <- gwpr_A_pFtest(bw = bw, data = lvl1_data, SDF=SDF, index=index, ID_list = ID_num,
formula = formula, p = p, longlat = longlat, adaptive = adaptive,
kernel = kernel, effect = effect, huge_data_size = huge_data_size)
}
else
{
result <- gwpr_F_pFtest(bw = bw, data = lvl1_data, SDF=SDF, index=index, ID_list = ID_num,
formula = formula, p = p, longlat = longlat, adaptive = adaptive,
kernel = kernel, effect = effect, huge_data_size = huge_data_size)
}
return(result)
}
|
wheel <-
function(color, num=12, bg="gray95", border=NULL,
init.angle=105, cex=1, lty=NULL, main=NULL, verbose=TRUE, ...)
{
if (!is.numeric(num) || any(is.na(num) | num < 0))
stop("\n'num' must be positive")
x <- rep(1, num)
x <- c(0, cumsum(x)/sum(x))
dx <- diff(x)
nx <- length(dx)
col = setColors(color, num)
labels = col
labcol = ifelse( mean(col2rgb(bg)) > 127, "black", "white")
par(bg = bg)
plot.new()
pin <- par("pin")
xlim <- ylim <- c(-1, 1)
if (pin[1L] > pin[2L])
xlim <- (pin[1L]/pin[2L]) * xlim
else ylim <- (pin[2L]/pin[1L]) * ylim
dev.hold()
on.exit(dev.flush())
plot.window(xlim, ylim, "", asp = 1)
if (is.null(border[1])) {
border <- rep(bg, length.out = nx)
} else {
border <- rep(border, length.out = nx)
}
if (!is.null(lty))
lty <- rep(NULL, length.out = nx)
angle <- rep(45, length.out = nx)
radius = seq(1, 0, by=-1/num)[1:num]
twopi <- -2 * pi
t2xy <- function(t, rad) {
t2p <- twopi * t + init.angle * pi/180
list(x = rad * cos(t2p), y = rad * sin(t2p))
}
for (i in 1L:nx)
{
n <- max(2, floor(200 * dx[i]))
P <- t2xy(seq.int(x[i], x[i + 1], length.out = n), rad=radius[1])
polygon(c(P$x, 0), c(P$y, 0), angle = angle[i],
border = border[i], col = col[i], lty = lty[i])
P <- t2xy(mean(x[i + 0:1]), rad=radius[1])
lab <- labels[i]
if (!is.na(lab) && nzchar(lab)) {
adjs = 0.5
if (P$x > 1e-08) adjs <- 0
if (P$x < -1e-08) adjs <- 1
lines(c(1, 1.05) * P$x, c(1, 1.05) * P$y)
text(1.1 * P$x, 1.1 * P$y, labels[i], xpd = TRUE,
adj = adjs, cex=cex, col=labcol, ...)
}
}
title(main = main, ...)
if (verbose)
col
}
|
.Random.seed <-
c(403L, 1L, -788367838L, 165038100L, 79326359L, 1084589709L,
-858183772L, -591177334L, 1733125621L, 494884943L, -1515335850L,
-699963904L, 1538717507L, 35303137L, -1791529904L, 255227054L,
-453349287L, 38236267L, -1868184102L, 33222300L, -1151401825L,
-327804171L, 278390668L, -1144461726L, 643938877L, 1113875639L,
-582247586L, -1235943784L, 1679588859L, 1326145433L, 574412840L,
-1766784810L, 2070021457L, 451572739L, 387595154L, -868542172L,
44277735L, 700580925L, 1457607348L, -155623142L, -242937243L,
2035889919L, -1457280122L, -807080688L, -1608464973L, -194906543L,
-1458522624L, 1097044702L, -1041399511L, -960647973L, -1387045910L,
825961356L, -554603313L, -880520059L, 186998588L, -677143022L,
1873050893L, -1270299065L, 286260270L, -196648568L, 1367357579L,
1495405161L, -688386504L, 1429341926L, -103357823L, -1947120109L,
-186582590L, -2028981644L, 458658935L, -707854995L, -1603624444L,
1392165162L, 42792597L, -2042307281L, 1109682230L, 1385643104L,
-1563856221L, 1110336961L, -1124568656L, 558379214L, 77475385L,
-1618816949L, 510403066L, 278764796L, -2128350913L, 31378965L,
-640496340L, -1920762366L, 1080222941L, 1021755351L, -1657595202L,
648682744L, 352977627L, 386627897L, -980271992L, -2074342346L,
828758129L, -517100893L, 888459250L, 157852484L, 1212623879L,
-975074851L, -167037228L, -1656792582L, 1538389317L, -276225633L,
-1943829722L, 1116773296L, 412747859L, 2099938161L, 1769575072L,
1976731198L, 844148041L, 1659450363L, 1346631626L, -1200133844L,
2132337967L, 235924453L, -1354272100L, 1291777778L, -1079138451L,
1951068327L, 1650840270L, 905650216L, 1761745963L, -358551991L,
1970669400L, 1600459270L, -113640479L, -2102503053L, 284367330L,
-1572233900L, -802958249L, -923232179L, 265100260L, -1809327670L,
727523381L, -1069597041L, -1329524842L, -2005544128L, -1243832829L,
352076833L, 2015176464L, -846701330L, 1772668057L, -43462357L,
798926874L, -1609391396L, 892601055L, -1406419787L, -719693236L,
-428513630L, -1769435651L, -1339955465L, 1555509278L, 1750442712L,
-1708652997L, -533597223L, -225427096L, -1849206634L, 1917654545L,
-814747709L, -1602587694L, -2129645980L, 480681383L, 473043709L,
-989206796L, 132985306L, 1303713061L, 1410200639L, -2132819002L,
-729362352L, 420813939L, 802615441L, 1284640960L, 2041944734L,
-1215662487L, 1369540251L, 1319283626L, -1656926260L, -1470987633L,
449211077L, -1854946692L, 1472990930L, -630502835L, 368903943L,
-117454098L, 935698376L, -63119157L, 239010089L, 1207818616L,
-1359122778L, -1103111999L, -1240927917L, -1207460350L, 1302939444L,
887825591L, -1305488211L, -2113392188L, -598797846L, 607030869L,
1233190895L, 513241078L, 1897474336L, -1970157853L, -1276256383L,
-1138365968L, -718546802L, -1954488327L, 317420939L, 428331450L,
-1658466116L, 1871459327L, 1621442901L, -1144702356L, -1739927870L,
-1476331235L, 528609175L, -1120523522L, 462770360L, -2109556069L,
1988679929L, -581219768L, -396421770L, 3024049L, -1347434269L,
262293426L, 2046015492L, 2110737223L, 1762933488L, 1568427588L,
-377765288L, 419557178L, 510420464L, -499870020L, -1352042220L,
750568130L, 531469408L, -1202838660L, -640567344L, 439968034L,
969054888L, 1371462540L, 1854421180L, 302599986L, 1318341184L,
833182900L, 1198391880L, -2093980230L, -1499028976L, -1008094484L,
-941563564L, 1900339474L, 1496993184L, -1663892788L, -836919712L,
637401026L, -312998104L, -254644308L, -609631428L, 1070983538L,
-1569563856L, -928920284L, -82515144L, 323387098L, -556611696L,
-973091076L, 1055009684L, 1395621954L, 255849728L, -841874372L,
30638416L, -1794649950L, 631406920L, 1740330764L, 999367388L,
-626348718L, 1599259776L, 1816641620L, 656609256L, -193754886L,
-1107236016L, -94437588L, -440809100L, -1442878574L, -977778592L,
-846926452L, -213918880L, 1830410722L, 657699752L, 203175116L,
342499324L, -503011918L, 795710960L, -381203516L, -994818728L,
-2024482438L, 607716272L, 566241724L, -149579692L, -1318045758L,
-1961365472L, 2074892476L, 374026832L, 881816546L, 649150568L,
289473612L, -31639300L, -337703950L, -932263680L, 2038063476L,
201763848L, 1780096954L, 1546301904L, -19416084L, -1212694124L,
1635340754L, 35090784L, 1923215180L, -794494688L, 2031419266L,
323743464L, -348962580L, -947063748L, -937559182L, -329884048L,
321082404L, -259298504L, -2033128294L, 452604624L, -2126569284L,
-378081644L, -1551690110L, 893167808L, 59908924L, -360031088L,
394927650L, -1751183352L, 1897364748L, -265966436L, 1950875154L,
-787218560L, -1049129452L, -1094800856L, 1760998714L, 1211009488L,
1018000492L, 1438288180L, 1571796626L, -869037216L, 1739985740L,
-1227319328L, -187877470L, -1483880536L, 1102556556L, 37103804L,
-1043035790L, -602786576L, -1532112828L, 1625350488L, -1687247302L,
-1741243536L, -1260079044L, -130973932L, -1556240958L, 797965024L,
-720554116L, 225836752L, 583858338L, -1173812184L, -2009905908L,
-1046067268L, -67303118L, -863614528L, -1004467660L, -370754616L,
-1479919430L, 927492496L, -984550932L, 714547796L, -1884139374L,
-1706119392L, 723970508L, 1779930592L, -792512830L, 538821672L,
-1564224852L, -190577476L, -804353550L, 1216816L, -375630684L,
-791402824L, 1831255386L, 1445098896L, 222466940L, -936376044L,
1747444546L, 833903360L, -1676724292L, -12837040L, 1472955170L,
-139322040L, 270600716L, 1231284316L, 1547664594L, -488162816L,
-405729964L, 1081162216L, 994298L, 618594512L, 138087724L, 727966452L,
1951021458L, 763941984L, 1538237708L, 367350496L, 2034583906L,
-1273505112L, -1555185076L, 991637884L, -1619466958L, 354750576L,
605669188L, -189850152L, -1663603590L, 744844848L, -1531041092L,
-1448878252L, 1410094146L, -1114268256L, 859368124L, 1007548880L,
-2032198302L, 356765672L, -1445623860L, 860016380L, 700269042L,
-643544960L, -541891340L, -1734703480L, 1499060026L, 2073727824L,
-2001140116L, 1277083796L, 1188704594L, 1939406560L, 327897804L,
1406259360L, 525908866L, 808719080L, -824429844L, -1098572740L,
-1147334030L, -1966500752L, 1397745188L, -1015479240L, 1872388343L,
-790393856L, -1982861730L, -1031745237L, 1297756717L, 132887194L,
-1354428840L, -381546047L, 126959219L, 101497748L, -76205534L,
-582001353L, 1552227329L, -898629370L, 1477887300L, -2060515211L,
995346911L, -558656200L, 824829718L, 1504618275L, -752143131L,
1893748994L, -1063632016L, -236979431L, 1023105803L, 1705732092L,
-2059770838L, -839489441L, -177356823L, 2147311870L, -1716137748L,
-678415299L, -179058681L, 1547359216L, -1238327410L, -560300613L,
-236856419L, 1552965962L, 276048232L, -446423215L, 2100878403L,
1120781636L, 316704242L, 2008518599L, 56390033L, -477559530L,
870333812L, 595328005L, 522505295L, -796270520L, 1094473190L,
1438706451L, -178746251L, 1501181522L, -1261055840L, 977512841L,
-358602309L, 1104487948L, -1401618534L, -1323948273L, 1396120921L,
-964175890L, 1750187644L, 1602209517L, 1251209623L, 1283021408L,
-606449602L, 167721227L, 1840774029L, -627279686L, -664797448L,
604927137L, -1303793581L, -1734960268L, 186575106L, -1733162601L,
79246177L, -1444075610L, -513531484L, 21854293L, -96801537L,
-1724010088L, 1084263094L, -993000637L, 1776483973L, 1797051170L,
-1251366896L, -125054023L, 766850155L, -858486948L, -868458870L,
-1367889281L, 1063277513L, 653906014L, -603196660L, 2092661469L,
-1306094617L, -495474672L, -29989586L, 1793669595L, 447733437L,
369839146L, -213693240L, 1644562929L, 1043416931L, -1536311452L,
-1892460910L, -365710489L, -361816783L, -16730506L, -1459140716L,
-1130179675L, -658627409L, 2012731752L, -759766714L, -937887501L,
499631701L, -775509454L, 990320640L, -607654679L, -82228389L,
-1484304980L, -463202886L, 942240623L, -323279623L, -1083229810L,
1516006492L, 799325901L, -1915291081L, 2051395776L, 148750238L,
937223275L, -1348123667L, 1347880538L, -982333160L, 1337357953L,
1181600819L, 1908677204L, 712863330L, -98393865L, -1840729279L,
66873798L, -1988308220L, 1740363445L, -1505140321L, 677813752L,
-174623786L, 1755729507L, 630132261L, 234847682L, 2002956976L,
274627289L, -1590461365L, -1463295300L, 225779946L, 193854751L,
28304809L, 1393689406L, -1779081684L, 591981693L, 2002056903L,
235614128L, -1613815346L, -1957299461L, 1333225821L, -1407100278L,
-732911448L, -226796527L, 1326664963L, -1265759059L)
|
VDJ_clonotype <- function(VDJ,
clone.strategy,
homology.threshold,
hierarchical,
VDJ.VJ.1chain,
global.clonotype,
output.format,
platypus.version){
Nr_of_VDJ_chains <- NULL
Nr_of_VJ_chains <- NULL
ccombs1 <- NULL
if(missing(platypus.version)) platypus.version <- "v3"
if(missing(output.format)) output.format <- "vgm"
if(missing(global.clonotype)) global.clonotype <- F
if(missing(clone.strategy)) clone.strategy <- "cdr3.aa"
if(missing(VDJ.VJ.1chain)) VDJ.VJ.1chain <- T
if(missing(VDJ)) stop("Please provide input data as VDJ")
if(missing(hierarchical)) hierarchical <- F
clone.strategy.as.input <- clone.strategy
switch(clone.strategy,
VDJJ.VJJ.cdr3length.CDR3.homology = {clone.strategy <- 'hvj.lvj.CDR3length.CDR3.homology'},
VDJJ.VJJ.cdr3length.VDJCDR3.homology = {clone.strategy <- 'hvj.lvj.CDR3length.CDRH3.homology'},
cdr3.homology = {clone.strategy <- 'CDR3.homology'},
VDJcdr3.homology = {clone.strategy <- 'CDRH3.homology'},
VDJJ.VJJ = {clone.strategy <- "hvj.lvj"},
VDJJ.VJJ.cdr3 = {clone.strategy <- "hvj.lvj.cdr3"},
VDJJ.VJJ.cdr3lengths = {clone.strategy <- "hvj.lvj.cdr3lengths"})
if(platypus.version=="v2"){
clonotype.list <- VDJ
VDJ <- NULL
output.clonotype <- list()
if(missing(homology.threshold) & grepl(clone.strategy,pattern = "homology")) message("No homology threshold supplied. Clonotyping based on 70% amino acid homology.")
if(missing(homology.threshold) & grepl(clone.strategy,pattern = "homology")) homology.threshold<-0.3
for(i in 1:length(clonotype.list)){
if(clone.strategy=="cdr3.nt"){
unique_clones <- unique(clonotype.list[[i]]$CDR3_nt_pasted)
clonotype.list[[i]]$new_clone_unique <- clonotype.list[[i]]$CDR3_nt_pasted
}
else if(clone.strategy=="cdr3.aa"){
unique_clones <- unique(clonotype.list[[i]]$CDR3_aa_pasted)
clonotype.list[[i]]$new_clone_unique <- clonotype.list[[i]]$CDR3_aa_pasted
}
else if(clone.strategy=="hvj.lvj"){
unique_clones <- unique(paste(clonotype.list[[i]]$HC_vgene,
clonotype.list[[i]]$HC_jgene,
clonotype.list[[i]]$LC_vgene,
clonotype.list[[i]]$LC_jgene,sep="_"))
clonotype.list[[i]]$new_clone_unique <- paste(clonotype.list[[i]]$HC_vgene,
clonotype.list[[i]]$HC_jgene,
clonotype.list[[i]]$LC_vgene,
clonotype.list[[i]]$LC_jgene,sep="_")
}
else if(clone.strategy=="hvj.lvj.cdr3lengths"){
unique_clones <- unique(paste(clonotype.list[[i]]$HC_vgene,
clonotype.list[[i]]$HC_jgene,
clonotype.list[[i]]$LC_vgene,
clonotype.list[[i]]$LC_jgene,
nchar(clonotype.list[[i]]$CDRH3_aa),
nchar(clonotype.list[[i]]$CDRL3_aa),sep="_"))
clonotype.list[[i]]$new_clone_unique <- paste(clonotype.list[[i]]$HC_vgene,
clonotype.list[[i]]$HC_jgene,
clonotype.list[[i]]$LC_vgene,
clonotype.list[[i]]$LC_jgene,
nchar(clonotype.list[[i]]$CDRH3_aa),
nchar(clonotype.list[[i]]$CDRL3_aa),sep="_")
}
else if(clone.strategy=="hvj.lvj.cdr3length.CDR3.homology" | clone.strategy=="hvj.lvj.CDR3length.CDRH3.homology"){
clones_temp <- (paste(clonotype.list[[i]]$HC_vgene,
clonotype.list[[i]]$HC_jgene,
clonotype.list[[i]]$LC_vgene,
clonotype.list[[i]]$LC_jgene,
nchar(clonotype.list[[i]]$CDRH3_aa),
nchar(clonotype.list[[i]]$CDRL3_aa),sep="_"))
clonotype.list[[i]]$new_clone_unique <- clones_temp
unique_clones <- unique(clones_temp)
for(j in 1:length(unique_clones)){
original_clone_indices <- which(clones_temp==unique_clones[j])
if (length(original_clone_indices) >= 2){
vh_distance <- stringdist::stringdistmatrix(clonotype.list[[i]]$CDRH3_aa[original_clone_indices],clonotype.list[[i]]$CDRH3_aa[original_clone_indices],method = "lv")/nchar(clonotype.list[[i]]$CDRH3_aa[original_clone_indices])
if (clone.strategy=="hvj.lvj.cdr3length.CDR3.homology"){
vl_distance <- stringdist::stringdistmatrix(clonotype.list[[i]]$CDRL3_aa[original_clone_indices],clonotype.list[[i]]$CDRL3_aa[original_clone_indices],method = "lv")/nchar(clonotype.list[[i]]$CDRL3_aa[original_clone_indices])
}else{
vl_distance <- 0
}
combined_distance <- vh_distance + vl_distance
diag(combined_distance) <- NA
hclust_combined <- stats::hclust(stats::as.dist(combined_distance))
hclust_combined_cut <- stats::cutree(hclust_combined, h = homology.threshold)
clonotype.list[[i]]$new_clone_unique[original_clone_indices] <- paste(clonotype.list[[i]]$new_clone_unique[original_clone_indices],j,hclust_combined_cut)
}else{
clonotype.list[[i]]$new_clone_unique[original_clone_indices] <- paste(clonotype.list[[i]]$new_clone_unique[original_clone_indices],j,"1")
}
}
unique_clones <- unique(clonotype.list[[i]]$new_clone_unique)
}
else if (clone.strategy=="CDR3.homology" | clone.strategy=="CDRH3.homology"){
vh_distance <- stringdist::stringdistmatrix(clonotype.list[[i]]$CDRH3_aa, clonotype.list[[i]]$CDRH3_aa, method = "lv")/nchar(clonotype.list[[i]]$CDRH3_aa)
if(clone.strategy=="CDR3.homology"){
vl_distance <- stringdist::stringdistmatrix(clonotype.list[[i]]$CDRL3_aa, clonotype.list[[i]]$CDRL3_aa, method = "lv")/nchar(clonotype.list[[i]]$CDRL3_aa)
}else{
vl_distance <- 0
}
combined_distance <- vh_distance + vl_distance
diag(combined_distance) <- NA
hclust_combined <- stats::hclust(stats::as.dist(combined_distance))
hclust_combined_cut <- stats::cutree(hclust_combined, h = homology.threshold)
clonotype.list[[i]]$new_clone_unique <- paste(hclust_combined_cut)
unique_clones <- unique(clonotype.list[[i]]$new_clone_unique)
}
clone_number <-length(unique_clones)
output.clonotype[[i]] <- data.frame(clonotype_id=paste("clonotype",1:clone_number,sep=""),frequency=rep(NA,clone_number),proportion=rep("",clone_number),cdr3s_aa=rep("",clone_number),cdr3s_nt=rep("",clone_number),HC_count=rep("",clone_number),IGK_count=rep("",clone_number),IGL_count=rep("",clone_number),LC_count=rep("",clone_number),CDRH3_aa=rep("",clone_number),CDRL3_aa=rep("",clone_number),CDRH3_nt=rep("",clone_number),CDRL3_nt=rep("",clone_number),CDR3_aa_pasted=rep("",clone_number),CDR3_nt_pasted=rep("",clone_number),HC_cgene=rep("",clone_number),HC_vgene=rep("",clone_number),HC_dgene=rep("",clone_number),HC_jgene=rep("",clone_number),LC_cgene=rep("",clone_number),LC_vgene=rep("",clone_number),LC_jgene=rep("",clone_number),barcodes=rep("",clone_number),nt_clone_ids=rep("",clone_number),new_unique_clone=unique_clones,nt_clone_cdrh3s=rep("",clone_number),nt_clone_cdrl3s=rep("",clone_number),stringsAsFactors = F)
for(j in 1:length(unique_clones)){
output.clonotype[[i]]$frequency[j] <- sum(clonotype.list[[i]]$frequency[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])
output.clonotype[[i]]$proportion[j] <- output.clonotype[[i]]$frequency[j]/sum(clonotype.list[[i]]$frequency)
output.clonotype[[i]]$cdr3s_aa[j] <- names(which.max(table(clonotype.list[[i]]$cdr3s_aa[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$cdr3s_nt[j] <- names(which.max(table(clonotype.list[[i]]$cdr3s_nt[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$HC_count[j] <- names(which.max(table(clonotype.list[[i]]$HC_count[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$IGK_count[j] <- names(which.max(table(clonotype.list[[i]]$IGK_count[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$IGL_count[j] <- names(which.max(table(clonotype.list[[i]]$IGL_count[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$LC_count[j] <- names(which.max(table(clonotype.list[[i]]$LC_count[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$CDRH3_aa[j] <- names(which.max(table(clonotype.list[[i]]$CDRH3_aa[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$CDRL3_aa[j] <- names(which.max(table(clonotype.list[[i]]$CDRL3_aa[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$CDRH3_nt[j] <- names(which.max(table(clonotype.list[[i]]$CDRH3_nt[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$CDRL3_nt[j] <- names(which.max(table(clonotype.list[[i]]$CDRL3_nt[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$CDR3_aa_pasted[j] <- names(which.max(table(clonotype.list[[i]]$CDR3_aa_pasted[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$CDR3_nt_pasted[j] <- names(which.max(table(clonotype.list[[i]]$CDR3_nt_pasted[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$HC_cgene[j] <- names(which.max(table(clonotype.list[[i]]$HC_cgene[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$HC_vgene[j] <- names(which.max(table(clonotype.list[[i]]$HC_vgene[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$HC_dgene[j] <- names(which.max(table(clonotype.list[[i]]$HC_dgene[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$HC_jgene[j] <- names(which.max(table(clonotype.list[[i]]$HC_jgene[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$LC_cgene[j] <- names(which.max(table(clonotype.list[[i]]$LC_cgene[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$LC_vgene[j] <- names(which.max(table(clonotype.list[[i]]$LC_vgene[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$LC_jgene[j] <- names(which.max(table(clonotype.list[[i]]$LC_jgene[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])])))
output.clonotype[[i]]$barcodes[j] <- gsub(toString(clonotype.list[[i]]$barcodes[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])]),pattern=", ", replacement = ";")
output.clonotype[[i]]$nt_clone_ids[j] <- gsub(toString(clonotype.list[[i]]$clonotype_id[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])]),pattern = ", ", replacement = ";")
output.clonotype[[i]]$nt_clone_cdrh3s[j] <- gsub(toString(clonotype.list[[i]]$CDRH3_nt[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])]),pattern = ", ",replacement = ";")
output.clonotype[[i]]$nt_clone_cdrl3s[j] <- gsub(toString(clonotype.list[[i]]$CDRL3_aa[which(clonotype.list[[i]]$new_clone_unique==unique_clones[j])],sep=";"),pattern = ", ",replacement = ";")
}
}
return(output.clonotype)
}
if(platypus.version=="v3"){
message("Please consider using the updated function VDJ_clonotype_v3 with increased flexibility for hierarchical clonotyping and overall higher performance.")
VDJ.GEX.matrix <- list()
VDJ.GEX.matrix[[1]] <- VDJ
VDJ <- NULL
if(hierarchical == F){
if(global.clonotype==F){
repertoire.number <- unique(VDJ.GEX.matrix[[1]]$sample_id)
sample_dfs <- list()
for(i in 1:length(repertoire.number)){
sample_dfs[[i]] <- VDJ.GEX.matrix[[1]][which(VDJ.GEX.matrix[[1]]$sample_id==repertoire.number[i]),]
if(VDJ.VJ.1chain== T){
sample_dfs[[i]]<- sample_dfs[[i]][which(sample_dfs[[i]]$Nr_of_VDJ_chains==1 & sample_dfs[[i]]$Nr_of_VJ_chains==1),]
}
if(clone.strategy=="10x.default"){
sample_dfs[[i]]$new_clonal_feature <- sample_dfs[[i]]$clonotype_id_10x
}
if(clone.strategy=="cdr3.nt"){
sample_dfs[[i]]$new_clonal_feature <- paste0(sample_dfs[[i]]$VDJ_cdr3s_nt,
sample_dfs[[i]]$VJ_cdr3s_nt)
}
else if(clone.strategy=="cdr3.aa"){
sample_dfs[[i]]$new_clonal_feature <- paste0(sample_dfs[[i]]$VDJ_cdr3s_aa,
sample_dfs[[i]]$VJ_cdr3s_aa)
}
else if(clone.strategy=="hvj.lvj"){
sample_dfs[[i]]$new_clonal_feature <- paste(sample_dfs[[i]]$VDJ_vgene,
sample_dfs[[i]]$VDJ_jgene,
sample_dfs[[i]]$VJ_jgene,
sample_dfs[[i]]$VJ_jgene,sep="_")
}
else if(clone.strategy=="hvj.lvj.cdr3"){
sample_dfs[[i]]$new_clonal_feature <- paste(sample_dfs[[i]]$VDJ_cdr3s_aa,
sample_dfs[[i]]$VJ_cdr3s_aa,
sample_dfs[[i]]$VDJ_vgene,
sample_dfs[[i]]$VDJ_jgene,
sample_dfs[[i]]$VJ_jgene,
sample_dfs[[i]]$VJ_jgene,sep="_")
}
else if(clone.strategy=="hvj.lvj.cdr3lengths"){
sample_dfs[[i]]$new_clonal_feature <- paste(sample_dfs[[i]]$VDJ_vgene,
sample_dfs[[i]]$VDJ_jgene,
sample_dfs[[i]]$VJ_vgene,
sample_dfs[[i]]$VJ_jgene,
nchar(sample_dfs[[i]]$VDJ_cdr3s_aa),
nchar(sample_dfs[[i]]$VJ_cdr3s_aa),sep="_")
}
else if(clone.strategy=="Hvj.Lvj.CDR3length.CDR3.homology" | clone.strategy=="Hvj.Lvj.CDR3length.CDRH3.homology"){
clones_temp <- (paste(sample_dfs[[i]]$VDJ_vgene,
sample_dfs[[i]]$VDJ_jgene,
sample_dfs[[i]]$VJ_vgene,
sample_dfs[[i]]$VJ_jgene,
nchar(sample_dfs[[i]]$VDJ_cdr3s_aa),
nchar(sample_dfs[[i]]$VJ_cdr3s_aa),sep="_"))
sample_dfs[[i]]$new_clonal_feature <- clones_temp
unique_clones <- unique(clones_temp)
for(j in 1:length(unique_clones)){
original_clone_indices <- which(clones_temp==unique_clones[j])
if(length(original_clone_indices) >= 2){
if(any(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices]) == 0) & !all(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vh <- nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices])
nchars_vh[which(nchars_vh == 0)] <- mean(nchars_vh[nchars_vh > 0])
} else if(all(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vh <- rep(1,length(original_clone_indices))
} else {
nchars_vh <- nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices])
}
vh_distance <- stringdist::stringdistmatrix(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices],sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices],method = "lv")/nchars_vh
if (clone.strategy=="Hvj.Lvj.CDR3length.CDR3.homology"){
if(any(nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices]) == 0) & !all(nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vl <- nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices])
nchars_vl[which(nchars_vl == 0)] <- mean(nchars_vl[nchars_vl > 0])
} else if(all(nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vl <- rep(1,length(original_clone_indices))
} else {
nchars_vl <- nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices])
}
vl_distance <- stringdist::stringdistmatrix(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices],sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices],method = "lv")/nchars_vl
}else{
vl_distance <- 0
}
combined_distance <- vh_distance + vl_distance
diag(combined_distance) <- NA
hclust_combined <- stats::hclust(stats::as.dist(combined_distance))
hclust_combined_cut <- stats::cutree(hclust_combined, h = homology.threshold)
sample_dfs[[i]]$new_clonal_feature[original_clone_indices] <- paste(sample_dfs[[i]]$new_clonal_feature[original_clone_indices],j,hclust_combined_cut)
}else{
sample_dfs[[i]]$new_clonal_feature[original_clone_indices] <- paste(sample_dfs[[i]]$new_clonal_feature[original_clone_indices],j,"1")
}
}
unique_clones <- unique(sample_dfs[[i]]$new_clonal_feature)
}
else if (clone.strategy=="CDR3.homology" | clone.strategy=="CDRH3.homology"){
if(any(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa) == 0) & !all(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa) == 0)){
nchars_vh <- nchar(sample_dfs[[i]]$VDJ_cdr3s_aa)
nchars_vh[which(nchars_vh == 0)] <- mean(nchars_vh[nchars_vh > 0])
} else if(all(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa) == 0)){
nchars_vh <- rep(1,length(sample_dfs[[i]]$VDJ_cdr3s_aa))
} else {
nchars_vh <- nchar(sample_dfs[[i]]$VDJ_cdr3s_aa)
}
vh_distance <- stringdist::stringdistmatrix(sample_dfs[[i]]$VDJ_cdr3s_aa, sample_dfs[[i]]$VDJ_cdr3s_aa, method = "lv")/nchars_vh
if(clone.strategy=="CDR3.homology"){
if(any(nchar(sample_dfs[[i]]$VJ_cdr3s_aa) == 0) & !all(nchar(sample_dfs[[i]]$VJ_cdr3s_aa) == 0)){
nchars_vl <- nchar(sample_dfs[[i]]$VJ_cdr3s_aa)
nchars_vl[which(nchars_vl == 0)] <- mean(nchars_vl[nchars_vl > 0])
} else if(all(nchar(sample_dfs[[i]]$VJ_cdr3s_aa) == 0)){
nchars_vl <- rep(1,length(sample_dfs[[i]]$VJ_cdr3s_aa))
} else {
nchars_vl <- nchar(sample_dfs[[i]]$VJ_cdr3s_aa)
}
vl_distance <- stringdist::stringdistmatrix(sample_dfs[[i]]$VJ_cdr3s_aa, sample_dfs[[i]]$VJ_cdr3s_aa, method = "lv")/nchars_vl
}else{
vl_distance <- 0
}
combined_distance <- vh_distance + vl_distance
diag(combined_distance) <- NA
hclust_combined <- stats::hclust(stats::as.dist(combined_distance))
hclust_combined_cut <- stats::cutree(hclust_combined, h = homology.threshold)
sample_dfs[[i]]$new_clonal_feature <- paste(hclust_combined_cut)
unique_clones <- unique(sample_dfs[[i]]$new_clonal_feature)
}
sample_dfs[[i]]$new_clonotype_id <- rep(NA,nrow(sample_dfs[[i]]))
sample_dfs[[i]]$new_clonal_frequency <- rep(NA,nrow(sample_dfs[[i]]))
sample_dfs[[i]]$new_clonal_rank <- rep(NA,nrow(sample_dfs[[i]]))
unique.clonal.features <- unique(sample_dfs[[i]]$new_clonal_feature)
unique.clonal.frequencies <- rep(NA,length(unique.clonal.features))
for(j in 1:length(unique.clonal.features)){
unique.clonal.frequencies[j] <- length(which(sample_dfs[[i]]$new_clonal_feature==unique.clonal.features[j]))
sample_dfs[[i]]$new_clonal_frequency[which(sample_dfs[[i]]$new_clonal_feature==unique.clonal.features[j])] <- unique.clonal.frequencies[j]
}
sample_dfs[[i]] <-sample_dfs[[i]][with(sample_dfs[[i]], order(-new_clonal_frequency)), ]
unique.clone.frequencies <- unique(sample_dfs[[i]]$new_clonal_frequency)
for(j in 1:length(unique.clone.frequencies)){
sample_dfs[[i]]$new_clonal_rank[which(sample_dfs[[i]]$new_clonal_frequency==unique.clone.frequencies[j])] <- j
}
unique.clonal.features <- unique(sample_dfs[[i]]$new_clonal_feature)
for(j in 1:length(unique.clonal.features)){
sample_dfs[[i]]$new_clonotype_id[which(sample_dfs[[i]]$new_clonal_feature == unique.clonal.features[j])] <- paste0("clonotype",j)
}
}
}
else if(global.clonotype==T){
sample_dfs <- VDJ.GEX.matrix[[1]]
sample_dfs$clonotype_id_10x <- paste0(sample_dfs$clonotype_id_10x,"_",sample_dfs$sample_id)
if(VDJ.VJ.1chain==T){
sample_dfs <- sample_dfs[which(sample_dfs$Nr_of_VDJ_chains==1 & sample_dfs$Nr_of_VJ_chains==1), ]}
if(clone.strategy=="10x.default"){
sample_dfs$new_clonal_feature <- sample_dfs$clonotype_id_10x
}
if(clone.strategy=="cdr3.nt"){
sample_dfs$new_clonal_feature <- paste0(sample_dfs$VDJ_cdr3s_nt,
sample_dfs$VJ_cdr3s_nt)
}
else if(clone.strategy=="cdr3.aa"){
sample_dfs$new_clonal_feature <- paste0(sample_dfs$VDJ_cdr3s_aa,
sample_dfs$VJ_cdr3s_aa)
}
else if(clone.strategy=="hvj.lvj"){
sample_dfs$new_clonal_feature <- paste(sample_dfs$VDJ_vgene,
sample_dfs$VDJ_jgene,
sample_dfs$VJ_vgene,
sample_dfs$VJ_jgene,sep="_")
}
else if(clone.strategy=="hvj.lvj.cdr3"){
sample_dfs$new_clonal_feature <- paste(sample_dfs$VDJ_cdr3s_aa,
sample_dfs$VJ_cdr3s_aa,
sample_dfs$VDJ_vgene,
sample_dfs$VDJ_jgene,
sample_dfs$VJ_jgene,
sample_dfs$VJ_jgene,sep="_")
}
else if(clone.strategy=="hvj.lvj.cdr3lengths"){
sample_dfs$new_clonal_feature <- paste(sample_dfs$VDJ_vgene,
sample_dfs$VDJ_jgene,
sample_dfs$VJ_vgene,
sample_dfs$VJ_jgene,
nchar(sample_dfs$VDJ_cdr3s_aa),
nchar(sample_dfs$VJ_cdr3s_aa),sep="_")
}
else if(clone.strategy=="Hvj.Lvj.CDR3length.CDR3.homology" | clone.strategy=="Hvj.Lvj.CDR3length.CDRH3.homology"){
clones_temp <- (paste(sample_dfs$VDJ_vgene,
sample_dfs$VDJ_jgene,
sample_dfs$VJ_vgene,
sample_dfs$VJ_jgene,
nchar(sample_dfs$VDJ_cdr3s_aa),
nchar(sample_dfs$VJ_cdr3s_aa),sep="_"))
sample_dfs$new_clonal_feature <- clones_temp
unique_clones <- unique(clones_temp)
for(j in 1:length(unique_clones)){
original_clone_indices <- which(clones_temp==unique_clones[j])
if(length(original_clone_indices) >= 2){
if(any(nchar(sample_dfs$VDJ_cdr3s_aa[original_clone_indices]) == 0) & !all(nchar(sample_dfs$VDJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vh <- nchar(sample_dfs$VDJ_cdr3s_aa[original_clone_indices])
nchars_vh[which(nchars_vh == 0)] <- mean(nchars_vh[nchars_vh > 0])
} else if(all(nchar(sample_dfs$VDJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vh <- rep(1,length(original_clone_indices))
} else {
nchars_vh <- nchar(sample_dfs$VDJ_cdr3s_aa[original_clone_indices])
}
vh_distance <- stringdist::stringdistmatrix(sample_dfs$VDJ_cdr3s_aa[original_clone_indices],sample_dfs$VDJ_cdr3s_aa[original_clone_indices],method = "lv")/nchars_vh
if (clone.strategy=="Hvj.Lvj.CDR3length.CDR3.homology"){
if(any(nchar(sample_dfs$VJ_cdr3s_aa[original_clone_indices]) == 0) & !all(nchar(sample_dfs$VJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vl <- nchar(sample_dfs$VJ_cdr3s_aa[original_clone_indices])
nchars_vl[which(nchars_vl == 0)] <- mean(nchars_vl[nchars_vl > 0])
} else if(all(nchar(sample_dfs$VJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vl <- rep(1,length(original_clone_indices))
} else {
nchars_vl <- nchar(sample_dfs$VJ_cdr3s_aa[original_clone_indices])
}
vl_distance <- stringdist::stringdistmatrix(sample_dfs$VJ_cdr3s_aa[original_clone_indices],sample_dfs$VJ_cdr3s_aa[original_clone_indices],method = "lv")/nchars_vl
}else{
vl_distance <- 0
}
combined_distance <- vh_distance + vl_distance
diag(combined_distance) <- NA
hclust_combined <- stats::hclust(stats::as.dist(combined_distance))
hclust_combined_cut <- stats::cutree(hclust_combined, h = homology.threshold)
sample_dfs$new_clonal_feature[original_clone_indices] <- paste(sample_dfs[[i]]$new_clonal_feature[original_clone_indices],j,hclust_combined_cut)
}else{
sample_dfs$new_clonal_feature[original_clone_indices] <- paste(sample_dfs[[i]]$new_clonal_feature[original_clone_indices],j,"1")
}
}
unique_clones <- unique(sample_dfs$new_clonal_feature)
}
else if (clone.strategy=="CDR3.homology" | clone.strategy=="CDRH3.homology"){
if(any(nchar(sample_dfs$VDJ_cdr3s_aa) == 0) & !all(nchar(sample_dfs$VDJ_cdr3s_aa) == 0)){
nchars_vh <- nchar(sample_dfs$VDJ_cdr3s_aa)
nchars_vh[which(nchars_vh == 0)] <- mean(nchars_vh[nchars_vh > 0])
} else if(all(nchar(sample_dfs$VDJ_cdr3s_aa) == 0)){
nchars_vh <- rep(1,length(sample_dfs$VDJ_cdr3s_aa))
} else {
nchars_vh <- nchar(sample_dfs$VDJ_cdr3s_aa)
}
vh_distance <- stringdist::stringdistmatrix(sample_dfs$VDJ_cdr3s_aa, sample_dfs$VDJ_cdr3s_aa, method = "lv")/nchars_vh
if(clone.strategy=="CDR3.homology"){
if(any(nchar(sample_dfs$VJ_cdr3s_aa) == 0) & !all(nchar(sample_dfs$VJ_cdr3s_aa) == 0)){
nchars_vl <- nchar(sample_dfs$VJ_cdr3s_aa)
nchars_vl[which(nchars_vl == 0)] <- mean(nchars_vl[nchars_vl > 0])
} else if(all(nchar(sample_dfs$VJ_cdr3s_aa) == 0)){
nchars_vl <- rep(1,length(sample_dfs$VJ_cdr3s_aa))
} else {
nchars_vl <- nchar(sample_dfs$VJ_cdr3s_aa)
}
vl_distance <- stringdist::stringdistmatrix(sample_dfs$VJ_cdr3s_aa, sample_dfs$VJ_cdr3s_aa, method = "lv")/nchars_vl
}else{
vl_distance <- 0
}
combined_distance <- vh_distance + vl_distance
diag(combined_distance) <- NA
hclust_combined <- stats::hclust(stats::as.dist(combined_distance))
hclust_combined_cut <- stats::cutree(hclust_combined, h = homology.threshold)
sample_dfs$new_clonal_feature <- paste(hclust_combined_cut)
unique_clones <- unique(sample_dfs$new_clonal_feature)
}
sample_dfs$new_clonotype_id <- rep(NA,nrow(sample_dfs))
sample_dfs$new_clonal_frequency <- rep(NA,nrow(sample_dfs))
sample_dfs$new_clonal_rank <- rep(NA,nrow(sample_dfs))
unique.clonal.features <- unique(sample_dfs$new_clonal_feature)
unique.clonal.frequencies <- rep(NA,length(unique.clonal.features))
for(j in 1:length(unique.clonal.features)){
unique.clonal.frequencies[j] <- length(which(sample_dfs$new_clonal_feature==unique.clonal.features[j]))
sample_dfs$new_clonal_frequency[which(sample_dfs$new_clonal_feature==unique.clonal.features[j])] <- unique.clonal.frequencies[j]
}
sample_dfs <-sample_dfs[with(sample_dfs, order(-new_clonal_frequency)), ]
unique.clone.frequencies <- unique(sample_dfs$new_clonal_frequency)
for(j in 1:length(unique.clone.frequencies)){
sample_dfs$new_clonal_rank[which(sample_dfs$new_clonal_frequency==unique.clone.frequencies[j])] <- j
}
unique.clonal.features <- unique(sample_dfs$new_clonal_feature)
for(j in 1:length(unique.clonal.features)){
sample_dfs$new_clonotype_id[which(sample_dfs$new_clonal_feature == unique.clonal.features[j])] <- paste0("clonotype",j)
}
}
}
if(hierarchical){
if(global.clonotype==F){
repertoire.number <- unique(VDJ.GEX.matrix[[1]]$sample_id)
sample_dfs <- list()
for(i in 1:length(repertoire.number)){
sample_dfs[[i]] <- VDJ.GEX.matrix[[1]][which(VDJ.GEX.matrix[[1]]$sample_id==repertoire.number[i]),]
prior_filtering <- nrow(sample_dfs[[i]])
sample_dfs[[i]] <- subset(sample_dfs[[i]], (Nr_of_VDJ_chains > 0 | Nr_of_VJ_chains > 0) & sample_dfs[[i]]$Nr_of_VDJ_chains + sample_dfs[[i]]$Nr_of_VJ_chains < 4)
if(nrow(sample_dfs[[i]]) > 0){
message(paste0("Filtered out ", prior_filtering - nrow(sample_dfs[[i]]), " cells containing more than one VDJ AND VJ chain, as these likely correspond to doublets"))}
if(VDJ.VJ.1chain== T){message("Hierarchical clonotyping is specifically designed to incorporate cells with abberand numbers of chains. Filtering for 1VDJ 1VJ chain thereby defeats its purpose. Function will continue without filtering.")}
aberant_cells <- subset(sample_dfs[[i]], Nr_of_VDJ_chains != 1 | Nr_of_VJ_chains != 1)
onlyVJ_ind <- which(aberant_cells$Nr_of_VJ_chains > 0 & aberant_cells$Nr_of_VDJ_chains == 0)
onlyVDJ_ind <- which(aberant_cells$Nr_of_VDJ_chains > 0 & aberant_cells$Nr_of_VJ_chains == 0)
multVJ_ind <- which(aberant_cells$Nr_of_VJ_chains > 1 & aberant_cells$Nr_of_VDJ_chains == 1)
multVDJ_ind <- which(aberant_cells$Nr_of_VDJ_chains > 1 & aberant_cells$Nr_of_VJ_chains == 1)
aberant_cells$new_clonal_feature <- NA
sample_dfs[[i]] <- subset(sample_dfs[[i]],Nr_of_VDJ_chains == 1 & Nr_of_VJ_chains == 1)
if(clone.strategy=="10x.default"){
sample_dfs[[i]]$new_clonal_feature <- sample_dfs[[i]]$clonotype_id_10x
}
if(clone.strategy=="cdr3.nt"){
sample_dfs[[i]]$new_clonal_feature <- paste0(sample_dfs[[i]]$VDJ_cdr3s_nt,
sample_dfs[[i]]$VJ_cdr3s_nt)
n_new_clones <- length(unique(sample_dfs[[i]]$new_clonal_feature))
print()
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(stringr::str_detect(aberant_cells$VJ_cdr3s_nt[cel], ";")){
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VJ_cdr3s_nt[cel], ";", simplify = T)[1,1])), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VJ_cdr3s_nt[cel], ";", simplify = T)[1,2])))
} else {
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, aberant_cells$VJ_cdr3s_nt[cel]))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- aberant_cells$VJ_cdr3s_nt[cel]
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(stringr::str_detect(aberant_cells$VDJ_cdr3s_nt[cel], ";")){
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VDJ_cdr3s_nt[cel], ";", simplify = T)[1,1])), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VDJ_cdr3s_nt[cel], ";", simplify = T)[1,2])))
} else {
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, aberant_cells$VDJ_cdr3s_nt[cel]))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- aberant_cells$VDJ_cdr3s_nt[cel]
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
VDJs <- aberant_cells$VDJ_cdr3s_nt[cel]
VJs <- stringr::str_split(aberant_cells$VJ_cdr3s_nt[cel], ";", simplify = T)[1,]
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_nt[cel],aberant_cells$VJ_cdr3s_nt[cel])
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
VDJs <- stringr::str_split(aberant_cells$VDJ_cdr3s_nt[cel], ";", simplify = T)[1,]
VJs <- aberant_cells$VJ_cdr3s_nt[cel]
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_nt[cel],aberant_cells$VJ_cdr3s_nt[cel])
}
}
}
}
else if(clone.strategy=="cdr3.aa"){
sample_dfs[[i]]$new_clonal_feature <- paste0(sample_dfs[[i]]$VDJ_cdr3s_aa,
sample_dfs[[i]]$VJ_cdr3s_aa)
n_new_clones <- length(unique(sample_dfs[[i]]$new_clonal_feature))
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(stringr::str_detect(aberant_cells$VJ_cdr3s_aa[cel], ";")){
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1])), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2])))
} else {
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, aberant_cells$VJ_cdr3s_aa[cel]))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- aberant_cells$VJ_cdr3s_aa[cel]
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(stringr::str_detect(aberant_cells$VDJ_cdr3s_aa[cel], ";")){
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])))
} else {
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, aberant_cells$VDJ_cdr3s_aa[cel]))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- aberant_cells$VDJ_cdr3s_aa[cel]
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
VDJs <- aberant_cells$VDJ_cdr3s_aa[cel]
VJs <- stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,]
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel],aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
VDJs <- stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,]
VJs <- aberant_cells$VJ_cdr3s_aa[cel]
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel],aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
}
else if(clone.strategy=="hvj.lvj"){
sample_dfs[[i]]$new_clonal_feature <- paste(sample_dfs[[i]]$VDJ_vgene,
sample_dfs[[i]]$VDJ_jgene,
sample_dfs[[i]]$VJ_vgene,
sample_dfs[[i]]$VJ_jgene,sep="_")
n_new_clones <- length(unique(sample_dfs[[i]]$new_clonal_feature))
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(stringr::str_detect(aberant_cells$VJ_vgene[cel], ";")){
comb1 <- paste0(stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- comb1
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
comb1 <- paste0(stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(aberant_cells$VDJ_vgene[cel], "_",aberant_cells$VDJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- comb1
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
VDJs <- paste0(aberant_cells$VDJ_vgene[cel], "_",aberant_cells$VDJ_jgene[cel])
VJs <- c(paste0(stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1]),paste0(stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2]))
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs[1]
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
VDJs <- c(paste0(stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1]),paste0(stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2]))
VJs <- paste0(aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs[1]
}
}
}
}
else if(clone.strategy=="hvj.lvj.cdr3"){
sample_dfs[[i]]$new_clonal_feature <- paste(sample_dfs[[i]]$VDJ_cdr3s_aa,
sample_dfs[[i]]$VDJ_vgene,
sample_dfs[[i]]$VDJ_jgene,
sample_dfs[[i]]$VJ_cdr3s_aa,
sample_dfs[[i]]$VJ_vgene,
sample_dfs[[i]]$VJ_jgene,sep="_")
n_new_clones <- length(unique(sample_dfs[[i]]$new_clonal_feature))
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(stringr::str_detect(aberant_cells$VJ_vgene[cel], ";")){
comb1 <- paste0(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1], "_" ,stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2], "_" ,stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(aberant_cells$VJ_cdr3s_aa[cel], "_",aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- comb1
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
comb1 <- paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1], "_" ,stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2], "_" ,stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(aberant_cells$VDJ_cdr3s_aa[cel], "_",aberant_cells$VDJ_vgene[cel], "_",aberant_cells$VDJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- comb1
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
VDJs <- paste0(aberant_cells$VDJ_cdr3s_aa[cel], "_",aberant_cells$VDJ_vgene[cel], "_",aberant_cells$VDJ_jgene[cel])
VJs <- c(paste0(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1], "_",stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1]),paste0(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2], "_",stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2]))
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs[1]
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
VDJs <- c(paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1], "_",stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1]),paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2], "_",stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2]))
VJs <- paste0(aberant_cells$VJ_cdr3s_aa[cel], "_", aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs[1]
}
}
}
}
else if(clone.strategy=="hvj.lvj.cdr3lengths"){
sample_dfs[[i]]$new_clonal_feature <- paste(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa),
sample_dfs[[i]]$VDJ_vgene,
sample_dfs[[i]]$VDJ_jgene,
nchar(sample_dfs[[i]]$VJ_cdr3s_aa),
sample_dfs[[i]]$VJ_vgene,
sample_dfs[[i]]$VJ_jgene, sep="_")
n_new_clones <- length(unique(sample_dfs[[i]]$new_clonal_feature))
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(stringr::str_detect(aberant_cells$VJ_vgene[cel], ";")){
comb1 <- paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_" ,stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_" ,stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(nchar(aberant_cells$VJ_cdr3s_aa[cel]), "_",aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- comb1
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
comb1 <- paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_" ,stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_" ,stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(nchar(aberant_cells$VDJ_cdr3s_aa[cel]), "_",aberant_cells$VDJ_vgene[cel], "_", aberant_cells$VDJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- comb1
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
VDJs <- paste0(nchar(aberant_cells$VDJ_cdr3s_aa[cel]), "_",aberant_cells$VDJ_vgene[cel], "_",aberant_cells$VDJ_jgene[cel])
VJs <- c(paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_",stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1]),paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_",stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2]))
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs[1]
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
VDJs <- c(paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_",stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1]),paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_",stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2]))
VJs <- paste0(nchar(aberant_cells$VJ_cdr3s_aa[cel]), "_", aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs[1]
}
}
}
}
else if(clone.strategy=="hvj.lvj.cdr3length.CDR3.homology" | clone.strategy=="hvj.lvj.CDR3length.CDRH3.homology"){
clones_temp <- (paste(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa),
sample_dfs[[i]]$VDJ_vgene,
sample_dfs[[i]]$VDJ_jgene,
nchar(sample_dfs[[i]]$VJ_cdr3s_aa),
sample_dfs[[i]]$VJ_vgene,
sample_dfs[[i]]$VJ_jgene,sep="_"))
sample_dfs[[i]]$new_clonal_feature <- clones_temp
unique_clones <- unique(clones_temp)
for(j in 1:length(unique_clones)){
original_clone_indices <- which(clones_temp==unique_clones[j])
if(length(original_clone_indices) >= 2){
if(any(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices]) == 0) & !all(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vh <- nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices])
nchars_vh[which(nchars_vh == 0)] <- mean(nchars_vh[nchars_vh > 0])
} else if(all(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vh <- rep(1,length(original_clone_indices))
} else {
nchars_vh <- nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices])
}
vh_distance <- stringdist::stringdistmatrix(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices],sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices],method = "lv")/nchars_vh
if (clone.strategy=="hvj.lvj.cdr3length.CDR3.homology"){
if(any(nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices]) == 0) & !all(nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vl <- nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices])
nchars_vl[which(nchars_vl == 0)] <- mean(nchars_vl[nchars_vl > 0])
} else if(all(nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vl <- rep(1,length(original_clone_indices))
} else {
nchars_vl <- nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices])
}
vl_distance <- stringdist::stringdistmatrix(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices],sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices],method = "lv")/nchars_vl
}else{
vl_distance <- 0
}
combined_distance <- vh_distance + vl_distance
diag(combined_distance) <- NA
hclust_combined <- stats::hclust(stats::as.dist(combined_distance))
hclust_combined_cut <- stats::cutree(hclust_combined, h = homology.threshold)
sample_dfs[[i]]$new_clonal_feature[original_clone_indices] <- paste(sample_dfs[[i]]$new_clonal_feature[original_clone_indices],j,hclust_combined_cut)
}else{
sample_dfs[[i]]$new_clonal_feature[original_clone_indices] <- paste(sample_dfs[[i]]$new_clonal_feature[original_clone_indices],j,"1")
}
}
unique_clones <- unique(sample_dfs[[i]]$new_clonal_feature)
sur_clonal_feature <- paste(clones_temp, "_", sample_dfs[[i]]$new_clonal_feature)
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(stringr::str_detect(aberant_cells$VJ_vgene[cel], ";")){
comb1 <- paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_" ,stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_" ,stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sur_clonal_feature, comb1)), which(stringr::str_detect(sur_clonal_feature, comb2)))
} else {
comb1 <- paste0(nchar(aberant_cells$VJ_cdr3s_aa[cel]), "_",aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sur_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
if(clone.strategy=="hvj.lvj.CDR3length.CDRH3.homology"){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(clone.strategy=="hvj.lvj.cdr3length.CDR3.homology"){
if(stringr::str_detect(aberant_cells$VJ_vgene[cel], ";")){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c(dists1,dists2)
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[rep(clone_matches,2)[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VJ_cdr3s_aa[cel])
}
} else {
dists <- stringdist::stringdist(sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches], aberant_cells$VJ_cdr3s_aa[cel]) / nchar(aberant_cells$VJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[clone_matches[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
if(any(stringdist::stringdist(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,],unique(sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]))/nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,]) <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VJ_cdr3s_aa[cel])
}
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
comb1 <- paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_" ,stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_" ,stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(nchar(aberant_cells$VDJ_cdr3s_aa[cel]), "_",aberant_cells$VDJ_vgene[cel], "_", aberant_cells$VDJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
if(clone.strategy=="hvj.lvj.CDR3length.CDRH3.homology"){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c(dists1,dists2)
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[rep(clone_matches,2)[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
} else {
dists <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], aberant_cells$VDJ_cdr3s_aa[cel]) / nchar(aberant_cells$VDJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[clone_matches[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
}
} else if(clone.strategy=="hvj.lvj.cdr3length.CDR3.homology"){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c(dists1,dists2)
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[rep(clone_matches,2)[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
} else {
dists <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], aberant_cells$VJD_cdr3s_aa[cel]) / nchar(aberant_cells$VDJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[clone_matches[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
}
}
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
if(any(stringdist::stringdist(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,],unique(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches]))/nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,]) <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
VDJs <- paste0(nchar(aberant_cells$VDJ_cdr3s_aa[cel]), "_",aberant_cells$VDJ_vgene[cel], "_",aberant_cells$VDJ_jgene[cel])
VJs <- c(paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_",stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1]),paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_",stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2]))
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
if(clone.strategy=="hvj.lvj.CDR3length.CDRH3.homology"){
dists <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], aberant_cells$VDJ_cdr3s_aa[cel]) / nchar(aberant_cells$VDJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[clone_matches[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
} else if(clone.strategy=="hvj.lvj.cdr3length.CDR3.homology"){
dists1 <- stringdist::stringdist(paste0(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches],"_",sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]),
paste0(aberant_cells$VDJ_cdr3s_aa[cel], "_", stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1])) / nchar(paste0(aberant_cells$VDJ_cdr3s_aa[cel], "_", stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]))
dists2 <- stringdist::stringdist(paste0(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches],"_",sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]),
paste0(aberant_cells$VDJ_cdr3s_aa[cel], "_", stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2])) / nchar(paste0(aberant_cells$VDJ_cdr3s_aa[cel], "_", stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]))
dists <- c(dists1,dists2)
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[rep(clone_matches,2)[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(ccombs[1],"_", aberant_cells$VDJ_cdr3s_aa[cel], "_", aberant_cells$VJ_cdr3s_aa[cel])
}
}
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
if(stringdist::stringdist(aberant_cells$VDJ_cdr3s_aa[cel],unique(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches]))/nchar(aberant_cells$VDJ_cdr3s_aa[cel]) <= homology.threshold
& any(stringdist::stringdist(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,],unique(sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]))/nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,]) <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(ccombs[1],"_", aberant_cells$VDJ_cdr3s_aa[cel], "_", aberant_cells$VJ_cdr3s_aa[cel])
}
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(ccombs[1],"_", aberant_cells$VDJ_cdr3s_aa[cel], "_", aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
VDJs <- c(paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_",stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1]),paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_",stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2]))
VJs <- paste0(nchar(aberant_cells$VJ_cdr3s_aa[cel]), "_", aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
if(clone.strategy=="hvj.lvj.CDR3length.CDRH3.homology"){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c(dists1,dists2)
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[rep(clone_matches,2)[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel],"_", aberant_cells$VJ_cdr3s_aa[cel])
}
} else if(clone.strategy=="hvj.lvj.cdr3length.CDR3.homology"){
dists1 <- stringdist::stringdist(paste0(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches],"_",sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]),
paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1], "_", aberant_cells$VJ_cdr3s_aa[cel])) / nchar(paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1], "_", aberant_cells$VJ_cdr3s_aa[cel]))
dists2 <- stringdist::stringdist(paste0(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches],"_",sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]),
paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2], "_", aberant_cells$VJ_cdr3s_aa[cel])) / nchar(paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2], "_", aberant_cells$VJ_cdr3s_aa[cel]))
dists <- c(dists1,dists2)
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[rep(clone_matches,2)[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(ccombs[1],"_", aberant_cells$VDJ_cdr3s_aa[cel], "_", aberant_cells$VJ_cdr3s_aa[cel])
}
}
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
if(stringdist::stringdist(aberant_cells$VJ_cdr3s_aa[cel],unique(sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]))/nchar(aberant_cells$VJ_cdr3s_aa[cel]) <= homology.threshold
& any(stringdist::stringdist(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,],unique(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches]))/nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,]) <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(ccombs[1],"_", aberant_cells$VDJ_cdr3s_aa[cel], "_", aberant_cells$VJ_cdr3s_aa[cel])
}
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(ccombs[1],"_", aberant_cells$VDJ_cdr3s_aa[cel], "_", aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
}
else if (clone.strategy=="CDR3.homology" | clone.strategy=="CDRH3.homology"){
if(any(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa) == 0) & !all(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa) == 0)){
nchars_vh <- nchar(sample_dfs[[i]]$VDJ_cdr3s_aa)
nchars_vh[which(nchars_vh == 0)] <- mean(nchars_vh[nchars_vh > 0])
} else if(all(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa) == 0)){
nchars_vh <- rep(1,length(sample_dfs[[i]]$VDJ_cdr3s_aa))
} else {
nchars_vh <- nchar(sample_dfs[[i]]$VDJ_cdr3s_aa)
}
vh_distance <- stringdist::stringdistmatrix(sample_dfs[[i]]$VDJ_cdr3s_aa, sample_dfs[[i]]$VDJ_cdr3s_aa, method = "lv")/nchars_vh
if(clone.strategy=="CDR3.homology"){
if(any(nchar(sample_dfs[[i]]$VJ_cdr3s_aa) == 0) & !all(nchar(sample_dfs[[i]]$VJ_cdr3s_aa) == 0)){
nchars_vl <- nchar(sample_dfs[[i]]$VJ_cdr3s_aa)
nchars_vl[which(nchars_vl == 0)] <- mean(nchars_vl[nchars_vl > 0])
} else if(all(nchar(sample_dfs[[i]]$VJ_cdr3s_aa) == 0)){
nchars_vl <- rep(1,length(sample_dfs[[i]]$VJ_cdr3s_aa))
} else {
nchars_vl <- nchar(sample_dfs[[i]]$VJ_cdr3s_aa)
}
vl_distance <- stringdist::stringdistmatrix(sample_dfs[[i]]$VJ_cdr3s_aa, sample_dfs[[i]]$VJ_cdr3s_aa, method = "lv")/nchars_vl
}else{
vl_distance <- 0
}
combined_distance <- vh_distance + vl_distance
diag(combined_distance) <- NA
hclust_combined <- stats::hclust(stats::as.dist(combined_distance))
hclust_combined_cut <- stats::cutree(hclust_combined, h = homology.threshold)
sample_dfs[[i]]$new_clonal_feature <- paste(hclust_combined_cut)
unique_clones <- unique(sample_dfs[[i]]$new_clonal_feature)
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(clone.strategy=="CDRH3.homology"){
if(stringr::str_detect(aberant_cells$VJ_cdr3s_aa[cel], ";")){
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1])), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2])))
} else {
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, aberant_cells$VJ_cdr3s_aa[cel]))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- aberant_cells$VJ_cdr3s_aa[cel]
}
} else if(clone.strategy=="CDR3.homology"){
if(stringr::str_detect(aberant_cells$VJ_vgene[cel], ";")){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VJ_cdr3s_aa, stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VJ_cdr3s_aa, stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c()
for(k in 1:length(dists1)){
if(dists1[k] < dists2[k]){
dists <- c(dists, dists1[k])
} else{
dists <- c(dists, dists2[k])
}
}
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VJ_cdr3s_aa[cel])
}
} else {
dists <- stringdist::stringdist(sample_dfs[[i]]$VJ_cdr3s_aa, aberant_cells$VJ_cdr3s_aa[cel]) / nchar(aberant_cells$VJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(clone.strategy=="CDRH3.homology"){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c()
for(k in 1:length(dists1)){
if(dists1[k] < dists2[k]){
dists <- c(dists, dists1[k])
} else{
dists <- c(dists, dists2[k])
}
}
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel])
}
} else {
dists <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, aberant_cells$VDJ_cdr3s_aa[cel]) / nchar(aberant_cells$VDJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel])
}
}
} else if(clone.strategy=="CDR3.homology"){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c()
for(k in 1:length(dists1)){
if(dists1[k] < dists2[k]){
dists <- c(dists, dists1[k])
} else{
dists <- c(dists, dists2[k])
}
}
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel])
}
} else {
dists <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, aberant_cells$VDJ_cdr3s_aa[cel]) / nchar(aberant_cells$VDJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel])
}
}
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
if(clone.strategy=="CDRH3.homology"){
dists <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, aberant_cells$VDJ_cdr3s_aa[cel]) / nchar(aberant_cells$VDJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel])
}
} else if(clone.strategy=="CDR3.homology"){
VDJs <- aberant_cells$VDJ_cdr3s_aa[cel]
VJs <- c(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1], stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
pasted_sample_dfs <- paste0(sample_dfs[[i]]$VDJ_cdr3s_aa, sample_dfs[[i]]$VJ_cdr3s_aa)
dists1 <- stringdist::stringdist(pasted_sample_dfs, ccombs[1]) / nchar(ccombs[1])
dists2 <- stringdist::stringdist(pasted_sample_dfs, ccombs[2]) / nchar(ccombs[2])
dists <- c()
for(k in 1:length(dists1)){
if(dists1[k] < dists2[k]){
dists <- c(dists, dists1[k])
} else{
dists <- c(dists, dists2[k])
}
}
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs1
}
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
if(clone.strategy=="CDRH3.homology"){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c()
for(k in 1:length(dists1)){
if(dists1[k] < dists2[k]){
dists <- c(dists, dists1[k])
} else{
dists <- c(dists, dists2[k])
}
}
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel])
}
} else if(clone.strategy=="CDR3.homology"){
VDJs <- c(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
VJs <- aberant_cells$VJ_cdr3s_aa[cel]
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
pasted_sample_dfs <- paste0(sample_dfs[[i]]$VDJ_cdr3s_aa, sample_dfs[[i]]$VJ_cdr3s_aa)
dists1 <- stringdist::stringdist(pasted_sample_dfs, ccombs[1]) / nchar(ccombs[1])
dists2 <- stringdist::stringdist(pasted_sample_dfs, ccombs[2]) / nchar(ccombs[2])
dists <- c()
for(k in 1:length(dists1)){
if(dists1[k] < dists2[k]){
dists <- c(dists, dists1[k])
} else{
dists <- c(dists, dists2[k])
}
}
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs1
}
}
}
}
}
sample_dfs[[i]] <- rbind(sample_dfs[[i]], aberant_cells)
unique_clones <- unique(sample_dfs[[i]]$new_clonal_feature)
sample_dfs[[i]]$new_clonotype_id <- rep(NA,nrow(sample_dfs[[i]]))
sample_dfs[[i]]$new_clonal_frequency <- rep(NA,nrow(sample_dfs[[i]]))
sample_dfs[[i]]$new_clonal_rank <- rep(NA,nrow(sample_dfs[[i]]))
unique.clonal.features <- unique(sample_dfs[[i]]$new_clonal_feature)
unique.clonal.frequencies <- rep(NA,length(unique.clonal.features))
for(j in 1:length(unique.clonal.features)){
unique.clonal.frequencies[j] <- length(which(sample_dfs[[i]]$new_clonal_feature==unique.clonal.features[j]))
sample_dfs[[i]]$new_clonal_frequency[which(sample_dfs[[i]]$new_clonal_feature==unique.clonal.features[j])] <- unique.clonal.frequencies[j]
}
sample_dfs[[i]] <-sample_dfs[[i]][with(sample_dfs[[i]], order(-new_clonal_frequency)), ]
unique.clone.frequencies <- unique(sample_dfs[[i]]$new_clonal_frequency)
for(j in 1:length(unique.clone.frequencies)){
sample_dfs[[i]]$new_clonal_rank[which(sample_dfs[[i]]$new_clonal_frequency==unique.clone.frequencies[j])] <- j
}
unique.clonal.features <- unique(sample_dfs[[i]]$new_clonal_feature)
for(j in 1:length(unique.clonal.features)){
sample_dfs[[i]]$new_clonotype_id[which(sample_dfs[[i]]$new_clonal_feature == unique.clonal.features[j])] <- paste0("clonotype",j)
}
}
}
else if(global.clonotype==T){
sample_dfs <- list()
sample_dfs[[1]] <- VDJ.GEX.matrix[[1]]
i <- 1
sample_dfs$clonotype_id_10x <- paste0(sample_dfs$clonotype_id_10x,"_",sample_dfs$sample_id)
prior_filtering <- nrow(sample_dfs[[i]])
sample_dfs[[i]] <- subset(sample_dfs[[i]], (Nr_of_VDJ_chains > 0 | Nr_of_VJ_chains > 0) & sample_dfs[[i]]$Nr_of_VDJ_chains + sample_dfs[[i]]$Nr_of_VJ_chains < 4)
if(nrow(sample_dfs[[i]]) > 0){
message(paste0("Filtered out ", prior_filtering - nrow(sample_dfs[[i]]), " cells containing more than one VDJ AND VJ chain, as these likely correspond to doublets"))}
if(VDJ.VJ.1chain== T){message("Hierarchical clonotyping is specifically designed to better incorporate cells with abberand numbers of chains. Filtering for 1VDJ 1VJ chain thereby defeats its purpose. Function will continue with out filtering. For standard clonotyping with filtering set hierarchical = FALSE. ")}
aberant_cells <- subset(sample_dfs[[i]], Nr_of_VDJ_chains != 1 | Nr_of_VJ_chains != 1)
onlyVJ_ind <- which(aberant_cells$Nr_of_VJ_chains > 0 & aberant_cells$Nr_of_VDJ_chains == 0)
onlyVDJ_ind <- which(aberant_cells$Nr_of_VDJ_chains > 0 & aberant_cells$Nr_of_VJ_chains == 0)
multVJ_ind <- which(aberant_cells$Nr_of_VJ_chains > 1 & aberant_cells$Nr_of_VDJ_chains == 1)
multVDJ_ind <- which(aberant_cells$Nr_of_VDJ_chains > 1 & aberant_cells$Nr_of_VJ_chains == 1)
aberant_cells$new_clonal_feature <- NA
sample_dfs[[i]] <- subset(sample_dfs[[i]],Nr_of_VDJ_chains == 1 & Nr_of_VJ_chains == 1)
if(clone.strategy=="10x.default"){
sample_dfs[[i]]$new_clonal_feature <- sample_dfs[[i]]$clonotype_id_10x
}
if(clone.strategy=="cdr3.nt"){
sample_dfs[[i]]$new_clonal_feature <- paste0(sample_dfs[[i]]$VDJ_cdr3s_nt,
sample_dfs[[i]]$VJ_cdr3s_nt)
n_new_clones <- length(unique(sample_dfs[[i]]$new_clonal_feature))
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(stringr::str_detect(aberant_cells$VJ_cdr3s_nt[cel], ";")){
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VJ_cdr3s_nt[cel], ";", simplify = T)[1,1])), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VJ_cdr3s_nt[cel], ";", simplify = T)[1,2])))
} else {
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, aberant_cells$VJ_cdr3s_nt[cel]))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- aberant_cells$VJ_cdr3s_nt[cel]
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(stringr::str_detect(aberant_cells$VDJ_cdr3s_nt[cel], ";")){
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VDJ_cdr3s_nt[cel], ";", simplify = T)[1,1])), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VDJ_cdr3s_nt[cel], ";", simplify = T)[1,2])))
} else {
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, aberant_cells$VDJ_cdr3s_nt[cel]))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- aberant_cells$VDJ_cdr3s_nt[cel]
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
VDJs <- aberant_cells$VDJ_cdr3s_nt[cel]
VJs <- stringr::str_split(aberant_cells$VJ_cdr3s_nt[cel], ";", simplify = T)[1,]
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_nt[cel],aberant_cells$VJ_cdr3s_nt[cel])
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
VDJs <- stringr::str_split(aberant_cells$VDJ_cdr3s_nt[cel], ";", simplify = T)[1,]
VJs <- aberant_cells$VJ_cdr3s_nt[cel]
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_nt[cel],aberant_cells$VJ_cdr3s_nt[cel])
}
}
}
}
else if(clone.strategy=="cdr3.aa"){
sample_dfs[[i]]$new_clonal_feature <- paste0(sample_dfs[[i]]$VDJ_cdr3s_aa,
sample_dfs[[i]]$VJ_cdr3s_aa)
n_new_clones <- length(unique(sample_dfs[[i]]$new_clonal_feature))
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(stringr::str_detect(aberant_cells$VJ_cdr3s_aa[cel], ";")){
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1])), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2])))
} else {
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, aberant_cells$VJ_cdr3s_aa[cel]))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- aberant_cells$VJ_cdr3s_aa[cel]
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(stringr::str_detect(aberant_cells$VDJ_cdr3s_aa[cel], ";")){
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])))
} else {
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, aberant_cells$VDJ_cdr3s_aa[cel]))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- aberant_cells$VDJ_cdr3s_aa[cel]
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
VDJs <- aberant_cells$VDJ_cdr3s_aa[cel]
VJs <- stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,]
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel],aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
VDJs <- stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,]
VJs <- aberant_cells$VJ_cdr3s_aa[cel]
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel],aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
}
else if(clone.strategy=="hvj.lvj"){
sample_dfs[[i]]$new_clonal_feature <- paste(sample_dfs[[i]]$VDJ_vgene,
sample_dfs[[i]]$VDJ_jgene,
sample_dfs[[i]]$VJ_vgene,
sample_dfs[[i]]$VJ_jgene,sep="_")
n_new_clones <- length(unique(sample_dfs[[i]]$new_clonal_feature))
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(stringr::str_detect(aberant_cells$VJ_vgene[cel], ";")){
comb1 <- paste0(stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- comb1
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
comb1 <- paste0(stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(aberant_cells$VDJ_vgene[cel], "_",aberant_cells$VDJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- comb1
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
VDJs <- paste0(aberant_cells$VDJ_vgene[cel], "_",aberant_cells$VDJ_jgene[cel])
VJs <- c(paste0(stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1]),paste0(stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2]))
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs[1]
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
VDJs <- c(paste0(stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1]),paste0(stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2]))
VJs <- paste0(aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs[1]
}
}
}
}
else if(clone.strategy=="hvj.lvj.cdr3"){
sample_dfs[[i]]$new_clonal_feature <- paste(sample_dfs[[i]]$VDJ_cdr3s_aa,
sample_dfs[[i]]$VDJ_vgene,
sample_dfs[[i]]$VDJ_jgene,
sample_dfs[[i]]$VJ_cdr3s_aa,
sample_dfs[[i]]$VJ_vgene,
sample_dfs[[i]]$VJ_jgene,sep="_")
n_new_clones <- length(unique(sample_dfs[[i]]$new_clonal_feature))
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(stringr::str_detect(aberant_cells$VJ_vgene[cel], ";")){
comb1 <- paste0(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1], "_" ,stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2], "_" ,stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(aberant_cells$VJ_cdr3s_aa[cel], "_",aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- comb1
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
comb1 <- paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1], "_" ,stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2], "_" ,stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(aberant_cells$VDJ_cdr3s_aa[cel], "_",aberant_cells$VDJ_vgene[cel], "_",aberant_cells$VDJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- comb1
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
VDJs <- paste0(aberant_cells$VDJ_cdr3s_aa[cel], "_",aberant_cells$VDJ_vgene[cel], "_",aberant_cells$VDJ_jgene[cel])
VJs <- c(paste0(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1], "_",stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1]),paste0(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2], "_",stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2]))
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs[1]
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
VDJs <- c(paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1], "_",stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1]),paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2], "_",stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2]))
VJs <- paste0(aberant_cells$VJ_cdr3s_aa[cel], "_", aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs[1]
}
}
}
}
else if(clone.strategy=="hvj.lvj.cdr3lengths"){
sample_dfs[[i]]$new_clonal_feature <- paste(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa),
sample_dfs[[i]]$VDJ_vgene,
sample_dfs[[i]]$VDJ_jgene,
nchar(sample_dfs[[i]]$VJ_cdr3s_aa),
sample_dfs[[i]]$VJ_vgene,
sample_dfs[[i]]$VJ_jgene, sep="_")
n_new_clones <- length(unique(sample_dfs[[i]]$new_clonal_feature))
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(stringr::str_detect(aberant_cells$VJ_vgene[cel], ";")){
comb1 <- paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_" ,stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_" ,stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(nchar(aberant_cells$VJ_cdr3s_aa[cel]), "_",aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- comb1
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
comb1 <- paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_" ,stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_" ,stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(nchar(aberant_cells$VDJ_cdr3s_aa[cel]), "_",aberant_cells$VDJ_vgene[cel], "_", aberant_cells$VDJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- comb1
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
VDJs <- paste0(nchar(aberant_cells$VDJ_cdr3s_aa[cel]), "_",aberant_cells$VDJ_vgene[cel], "_",aberant_cells$VDJ_jgene[cel])
VJs <- c(paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_",stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1]),paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_",stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2]))
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs[1]
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
VDJs <- c(paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_",stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1]),paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_",stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2]))
VJs <- paste0(nchar(aberant_cells$VJ_cdr3s_aa[cel]), "_", aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs[1]
}
}
}
}
else if(clone.strategy=="hvj.lvj.cdr3length.CDR3.homology" | clone.strategy=="hvj.lvj.CDR3length.CDRH3.homology"){
clones_temp <- (paste(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa),
sample_dfs[[i]]$VDJ_vgene,
sample_dfs[[i]]$VDJ_jgene,
nchar(sample_dfs[[i]]$VJ_cdr3s_aa),
sample_dfs[[i]]$VJ_vgene,
sample_dfs[[i]]$VJ_jgene,sep="_"))
sample_dfs[[i]]$new_clonal_feature <- clones_temp
unique_clones <- unique(clones_temp)
for(j in 1:length(unique_clones)){
original_clone_indices <- which(clones_temp==unique_clones[j])
if(length(original_clone_indices) >= 2){
if(any(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices]) == 0) & !all(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vh <- nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices])
nchars_vh[which(nchars_vh == 0)] <- mean(nchars_vh[nchars_vh > 0])
} else if(all(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vh <- rep(1,length(original_clone_indices))
} else {
nchars_vh <- nchar(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices])
}
vh_distance <- stringdist::stringdistmatrix(sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices],sample_dfs[[i]]$VDJ_cdr3s_aa[original_clone_indices],method = "lv")/nchars_vh
if (clone.strategy=="hvj.lvj.cdr3length.CDR3.homology"){
if(any(nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices]) == 0) & !all(nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vl <- nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices])
nchars_vl[which(nchars_vl == 0)] <- mean(nchars_vl[nchars_vl > 0])
} else if(all(nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices]) == 0)){
nchars_vl <- rep(1,length(original_clone_indices))
} else {
nchars_vl <- nchar(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices])
}
vl_distance <- stringdist::stringdistmatrix(sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices],sample_dfs[[i]]$VJ_cdr3s_aa[original_clone_indices],method = "lv")/nchars_vl
}else{
vl_distance <- 0
}
combined_distance <- vh_distance + vl_distance
diag(combined_distance) <- NA
hclust_combined <- stats::hclust(stats::as.dist(combined_distance))
hclust_combined_cut <- stats::cutree(hclust_combined, h = homology.threshold)
sample_dfs[[i]]$new_clonal_feature[original_clone_indices] <- paste(sample_dfs[[i]]$new_clonal_feature[original_clone_indices],j,hclust_combined_cut)
}else{
sample_dfs[[i]]$new_clonal_feature[original_clone_indices] <- paste(sample_dfs[[i]]$new_clonal_feature[original_clone_indices],j,"1")
}
}
unique_clones <- unique(sample_dfs[[i]]$new_clonal_feature)
sur_clonal_feature <- paste(clones_temp, "_", sample_dfs[[i]]$new_clonal_feature)
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(stringr::str_detect(aberant_cells$VJ_vgene[cel], ";")){
comb1 <- paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_" ,stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_" ,stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sur_clonal_feature, comb1)), which(stringr::str_detect(sur_clonal_feature, comb2)))
} else {
comb1 <- paste0(nchar(aberant_cells$VJ_cdr3s_aa[cel]), "_",aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sur_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
if(clone.strategy=="hvj.lvj.CDR3length.CDRH3.homology"){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(clone.strategy=="hvj.lvj.cdr3length.CDR3.homology"){
if(stringr::str_detect(aberant_cells$VJ_vgene[cel], ";")){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c(dists1,dists2)
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[rep(clone_matches,2)[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VJ_cdr3s_aa[cel])
}
} else {
dists <- stringdist::stringdist(sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches], aberant_cells$VJ_cdr3s_aa[cel]) / nchar(aberant_cells$VJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[clone_matches[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
if(any(stringdist::stringdist(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,],unique(sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]))/nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,]) <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VJ_cdr3s_aa[cel])
}
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
comb1 <- paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_" ,stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1])
comb2 <- paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_" ,stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1)), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb2)))
} else {
comb1 <- paste0(nchar(aberant_cells$VDJ_cdr3s_aa[cel]), "_",aberant_cells$VDJ_vgene[cel], "_", aberant_cells$VDJ_jgene[cel])
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, comb1))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
if(clone.strategy=="hvj.lvj.CDR3length.CDRH3.homology"){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c(dists1,dists2)
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[rep(clone_matches,2)[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
} else {
dists <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], aberant_cells$VDJ_cdr3s_aa[cel]) / nchar(aberant_cells$VDJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[clone_matches[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
}
} else if(clone.strategy=="hvj.lvj.cdr3length.CDR3.homology"){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c(dists1,dists2)
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[rep(clone_matches,2)[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
} else {
dists <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], aberant_cells$VJD_cdr3s_aa[cel]) / nchar(aberant_cells$VDJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[clone_matches[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
}
}
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
if(any(stringdist::stringdist(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,],unique(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches]))/nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,]) <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
VDJs <- paste0(nchar(aberant_cells$VDJ_cdr3s_aa[cel]), "_",aberant_cells$VDJ_vgene[cel], "_",aberant_cells$VDJ_jgene[cel])
VJs <- c(paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_",stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,1]),paste0(nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_",stringr::str_split(aberant_cells$VJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VJ_jgene[cel], ";", simplify = T)[1,2]))
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
if(clone.strategy=="hvj.lvj.CDR3length.CDRH3.homology"){
dists <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], aberant_cells$VDJ_cdr3s_aa[cel]) / nchar(aberant_cells$VDJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[clone_matches[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel])
}
} else if(clone.strategy=="hvj.lvj.cdr3length.CDR3.homology"){
dists1 <- stringdist::stringdist(paste0(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches],"_",sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]),
paste0(aberant_cells$VDJ_cdr3s_aa[cel], "_", stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1])) / nchar(paste0(aberant_cells$VDJ_cdr3s_aa[cel], "_", stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]))
dists2 <- stringdist::stringdist(paste0(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches],"_",sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]),
paste0(aberant_cells$VDJ_cdr3s_aa[cel], "_", stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2])) / nchar(paste0(aberant_cells$VDJ_cdr3s_aa[cel], "_", stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]))
dists <- c(dists1,dists2)
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[rep(clone_matches,2)[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(ccombs[1],"_", aberant_cells$VDJ_cdr3s_aa[cel], "_", aberant_cells$VJ_cdr3s_aa[cel])
}
}
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
if(stringdist::stringdist(aberant_cells$VDJ_cdr3s_aa[cel],unique(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches]))/nchar(aberant_cells$VDJ_cdr3s_aa[cel]) <= homology.threshold
& any(stringdist::stringdist(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,],unique(sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]))/nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,]) <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(ccombs[1],"_", aberant_cells$VDJ_cdr3s_aa[cel], "_", aberant_cells$VJ_cdr3s_aa[cel])
}
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(ccombs[1],"_", aberant_cells$VDJ_cdr3s_aa[cel], "_", aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
VDJs <- c(paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]), "_",stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,1], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,1]),paste0(nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]), "_",stringr::str_split(aberant_cells$VDJ_vgene[cel], ";", simplify = T)[1,2], "_", stringr::str_split(aberant_cells$VDJ_jgene[cel], ";", simplify = T)[1,2]))
VJs <- paste0(nchar(aberant_cells$VJ_cdr3s_aa[cel]), "_", aberant_cells$VJ_vgene[cel], "_",aberant_cells$VJ_jgene[cel])
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[1])),which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature,ccombs[2])))
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
if(clone.strategy=="hvj.lvj.CDR3length.CDRH3.homology"){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c(dists1,dists2)
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[rep(clone_matches,2)[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(comb1,"_", aberant_cells$VDJ_cdr3s_aa[cel],"_", aberant_cells$VJ_cdr3s_aa[cel])
}
} else if(clone.strategy=="hvj.lvj.cdr3length.CDR3.homology"){
dists1 <- stringdist::stringdist(paste0(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches],"_",sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]),
paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1], "_", aberant_cells$VJ_cdr3s_aa[cel])) / nchar(paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1], "_", aberant_cells$VJ_cdr3s_aa[cel]))
dists2 <- stringdist::stringdist(paste0(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches],"_",sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]),
paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2], "_", aberant_cells$VJ_cdr3s_aa[cel])) / nchar(paste0(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2], "_", aberant_cells$VJ_cdr3s_aa[cel]))
dists <- c(dists1,dists2)
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[rep(clone_matches,2)[which.min(dists)]]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(ccombs[1],"_", aberant_cells$VDJ_cdr3s_aa[cel], "_", aberant_cells$VJ_cdr3s_aa[cel])
}
}
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
if(stringdist::stringdist(aberant_cells$VJ_cdr3s_aa[cel],unique(sample_dfs[[i]]$VJ_cdr3s_aa[clone_matches]))/nchar(aberant_cells$VJ_cdr3s_aa[cel]) <= homology.threshold
& any(stringdist::stringdist(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,],unique(sample_dfs[[i]]$VDJ_cdr3s_aa[clone_matches]))/nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,]) <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(ccombs[1],"_", aberant_cells$VDJ_cdr3s_aa[cel], "_", aberant_cells$VJ_cdr3s_aa[cel])
}
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(ccombs[1],"_", aberant_cells$VDJ_cdr3s_aa[cel], "_", aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
}
else if (clone.strategy=="CDR3.homology" | clone.strategy=="CDRH3.homology"){
if(any(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa) == 0) & !all(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa) == 0)){
nchars_vh <- nchar(sample_dfs[[i]]$VDJ_cdr3s_aa)
nchars_vh[which(nchars_vh == 0)] <- mean(nchars_vh[nchars_vh > 0])
} else if(all(nchar(sample_dfs[[i]]$VDJ_cdr3s_aa) == 0)){
nchars_vh <- rep(1,length(sample_dfs[[i]]$VDJ_cdr3s_aa))
} else {
nchars_vh <- nchar(sample_dfs[[i]]$VDJ_cdr3s_aa)
}
vh_distance <- stringdist::stringdistmatrix(sample_dfs[[i]]$VDJ_cdr3s_aa, sample_dfs[[i]]$VDJ_cdr3s_aa, method = "lv")/nchars_vh
if(clone.strategy=="CDR3.homology"){
if(any(nchar(sample_dfs[[i]]$VJ_cdr3s_aa) == 0) & !all(nchar(sample_dfs[[i]]$VJ_cdr3s_aa) == 0)){
nchars_vl <- nchar(sample_dfs[[i]]$VJ_cdr3s_aa)
nchars_vl[which(nchars_vl == 0)] <- mean(nchars_vl[nchars_vl > 0])
} else if(all(nchar(sample_dfs[[i]]$VJ_cdr3s_aa) == 0)){
nchars_vl <- rep(1,length(sample_dfs[[i]]$VJ_cdr3s_aa))
} else {
nchars_vl <- nchar(sample_dfs[[i]]$VJ_cdr3s_aa)
}
vl_distance <- stringdist::stringdistmatrix(sample_dfs[[i]]$VJ_cdr3s_aa, sample_dfs[[i]]$VJ_cdr3s_aa, method = "lv")/nchars_vl
}else{
vl_distance <- 0
}
combined_distance <- vh_distance + vl_distance
diag(combined_distance) <- NA
hclust_combined <- stats::hclust(stats::as.dist(combined_distance))
hclust_combined_cut <- stats::cutree(hclust_combined, h = homology.threshold)
sample_dfs[[i]]$new_clonal_feature <- paste(hclust_combined_cut)
unique_clones <- unique(sample_dfs[[i]]$new_clonal_feature)
if(length(onlyVJ_ind) > 0){
for(cel in onlyVJ_ind){
if(clone.strategy=="CDRH3.homology"){
if(stringr::str_detect(aberant_cells$VJ_cdr3s_aa[cel], ";")){
clone_matches <- c(which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1])), which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2])))
} else {
clone_matches <- which(stringr::str_detect(sample_dfs[[i]]$new_clonal_feature, aberant_cells$VJ_cdr3s_aa[cel]))
}
if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) > 1){
aberant_cells$new_clonal_feature[cel] <- names(which.max(table(sample_dfs[[i]]$new_clonal_feature[clone_matches])))
} else if(length(unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])) == 1){
aberant_cells$new_clonal_feature[cel] <- unique(sample_dfs[[i]]$new_clonal_feature[clone_matches])
} else {
aberant_cells$new_clonal_feature[cel] <- aberant_cells$VJ_cdr3s_aa[cel]
}
} else if(clone.strategy=="CDR3.homology"){
if(stringr::str_detect(aberant_cells$VJ_vgene[cel], ";")){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VJ_cdr3s_aa, stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VJ_cdr3s_aa, stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c()
for(k in 1:length(dists1)){
if(dists1[k] < dists2[k]){
dists <- c(dists, dists1[k])
} else{
dists <- c(dists, dists2[k])
}
}
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VJ_cdr3s_aa[cel])
}
} else {
dists <- stringdist::stringdist(sample_dfs[[i]]$VJ_cdr3s_aa, aberant_cells$VJ_cdr3s_aa[cel]) / nchar(aberant_cells$VJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VJ_cdr3s_aa[cel])
}
}
}
}
}
if(length(onlyVDJ_ind) > 0){
for(cel in onlyVDJ_ind){
if(clone.strategy=="CDRH3.homology"){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c()
for(k in 1:length(dists1)){
if(dists1[k] < dists2[k]){
dists <- c(dists, dists1[k])
} else{
dists <- c(dists, dists2[k])
}
}
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel])
}
} else {
dists <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, aberant_cells$VDJ_cdr3s_aa[cel]) / nchar(aberant_cells$VDJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel])
}
}
} else if(clone.strategy=="CDR3.homology"){
if(stringr::str_detect(aberant_cells$VDJ_vgene[cel], ";")){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c()
for(k in 1:length(dists1)){
if(dists1[k] < dists2[k]){
dists <- c(dists, dists1[k])
} else{
dists <- c(dists, dists2[k])
}
}
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel])
}
} else {
dists <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, aberant_cells$VDJ_cdr3s_aa[cel]) / nchar(aberant_cells$VDJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel])
}
}
}
}
}
if(length(multVJ_ind) > 0){
for(cel in multVJ_ind){
if(clone.strategy=="CDRH3.homology"){
dists <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, aberant_cells$VDJ_cdr3s_aa[cel]) / nchar(aberant_cells$VDJ_cdr3s_aa[cel])
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel])
}
} else if(clone.strategy=="CDR3.homology"){
VDJs <- aberant_cells$VDJ_cdr3s_aa[cel]
VJs <- c(stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,1], stringr::str_split(aberant_cells$VJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
pasted_sample_dfs <- paste0(sample_dfs[[i]]$VDJ_cdr3s_aa, sample_dfs[[i]]$VJ_cdr3s_aa)
dists1 <- stringdist::stringdist(pasted_sample_dfs, ccombs[1]) / nchar(ccombs[1])
dists2 <- stringdist::stringdist(pasted_sample_dfs, ccombs[2]) / nchar(ccombs[2])
dists <- c()
for(k in 1:length(dists1)){
if(dists1[k] < dists2[k]){
dists <- c(dists, dists1[k])
} else{
dists <- c(dists, dists2[k])
}
}
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs1
}
}
}
}
if(length(multVDJ_ind) > 0){
for(cel in multVDJ_ind){
if(clone.strategy=="CDRH3.homology"){
dists1 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1])
dists2 <- stringdist::stringdist(sample_dfs[[i]]$VDJ_cdr3s_aa, stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2]) / nchar(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
dists <- c()
for(k in 1:length(dists1)){
if(dists1[k] < dists2[k]){
dists <- c(dists, dists1[k])
} else{
dists <- c(dists, dists2[k])
}
}
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- paste0(aberant_cells$VDJ_cdr3s_aa[cel])
}
} else if(clone.strategy=="CDR3.homology"){
VDJs <- c(stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,1], stringr::str_split(aberant_cells$VDJ_cdr3s_aa[cel], ";", simplify = T)[1,2])
VJs <- aberant_cells$VJ_cdr3s_aa[cel]
ccombs <- expand.grid(VDJs, VJs)
ccombs <- paste0(ccombs[,1], ccombs[,2])
pasted_sample_dfs <- paste0(sample_dfs[[i]]$VDJ_cdr3s_aa, sample_dfs[[i]]$VJ_cdr3s_aa)
dists1 <- stringdist::stringdist(pasted_sample_dfs, ccombs[1]) / nchar(ccombs[1])
dists2 <- stringdist::stringdist(pasted_sample_dfs, ccombs[2]) / nchar(ccombs[2])
dists <- c()
for(k in 1:length(dists1)){
if(dists1[k] < dists2[k]){
dists <- c(dists, dists1[k])
} else{
dists <- c(dists, dists2[k])
}
}
if(any(dists <= homology.threshold)){
aberant_cells$new_clonal_feature[cel] <- sample_dfs[[i]]$new_clonal_feature[which.min(dists)]
} else {
aberant_cells$new_clonal_feature[cel] <- ccombs1
}
}
}
}
}
sample_dfs[[i]] <- rbind(sample_dfs[[i]], aberant_cells)
unique_clones <- unique(sample_dfs[[i]]$new_clonal_feature)
sample_dfs[[i]]$new_clonotype_id <- rep(NA,nrow(sample_dfs[[i]]))
sample_dfs[[i]]$new_clonal_frequency <- rep(NA,nrow(sample_dfs[[i]]))
sample_dfs[[i]]$new_clonal_rank <- rep(NA,nrow(sample_dfs[[i]]))
unique.clonal.features <- unique(sample_dfs[[i]]$new_clonal_feature)
unique.clonal.frequencies <- rep(NA,length(unique.clonal.features))
for(j in 1:length(unique.clonal.features)){
unique.clonal.frequencies[j] <- length(which(sample_dfs[[i]]$new_clonal_feature==unique.clonal.features[j]))
sample_dfs[[i]]$new_clonal_frequency[which(sample_dfs[[i]]$new_clonal_feature==unique.clonal.features[j])] <- unique.clonal.frequencies[j]
}
sample_dfs[[i]] <-sample_dfs[[i]][with(sample_dfs[[i]], order(-new_clonal_frequency)), ]
unique.clone.frequencies <- unique(sample_dfs[[i]]$new_clonal_frequency)
for(j in 1:length(unique.clone.frequencies)){
sample_dfs[[i]]$new_clonal_rank[which(sample_dfs[[i]]$new_clonal_frequency==unique.clone.frequencies[j])] <- j
}
unique.clonal.features <- unique(sample_dfs[[i]]$new_clonal_feature)
for(j in 1:length(unique.clonal.features)){
sample_dfs[[i]]$new_clonotype_id[which(sample_dfs[[i]]$new_clonal_feature == unique.clonal.features[j])] <- paste0("clonotype",j)
}
}
}
if(output.format=="dataframe.per.sample"){
return(sample_dfs)
} else if(output.format=="vgm"){
if(!global.clonotype) VDJ.GEX.matrix <- do.call("rbind",sample_dfs)
if(global.clonotype){
if(class(sample_dfs)=="list"){
VDJ.GEX.matrix <- sample_dfs[[1]]
} else {
VDJ.GEX.matrix <- sample_dfs
}
}
if("sample_id" %in% names(VDJ.GEX.matrix)){
clono_10x_index <- which(names(VDJ.GEX.matrix) == "sample_id")
VDJ.GEX.matrix<- VDJ.GEX.matrix[,c(1:clono_10x_index, ((ncol(VDJ.GEX.matrix)-3):ncol(VDJ.GEX.matrix)), (clono_10x_index+1):(ncol(VDJ.GEX.matrix)-4))]
}
names(VDJ.GEX.matrix)[which(names(VDJ.GEX.matrix) == "new_clonotype_id")] <- paste0("clonotype_id_",clone.strategy.as.input)
names(VDJ.GEX.matrix)[which(names(VDJ.GEX.matrix) == "new_clonal_feature")] <- paste0("clonal_feature_",clone.strategy.as.input)
names(VDJ.GEX.matrix)[which(names(VDJ.GEX.matrix) == "new_clonal_frequency")] <- paste0("clonotype_frequency_",clone.strategy.as.input)
VDJ.GEX.matrix <- VDJ.GEX.matrix[,-c(which(names(VDJ.GEX.matrix) == "new_clonal_rank"))]
return(VDJ.GEX.matrix)
}
else if(output.format=="clone.level.dataframes" & global.clonotype == F){
clone.dataframe.list <- list()
for(i in 1:length(sample_dfs)){
sample_dfs[[i]]$VDJ_VJ_trimmed <- paste0(sample_dfs[[i]]$VDJ_sequence_nt_trimmed,sample_dfs[[i]]$VJ_sequence_nt_trimmed)
clones_unique <- (sample_dfs[[i]][!duplicated(sample_dfs[[i]]$clonotype_id),])
clones_unique$count.VDJ_VJ_trimmed_majority <- rep(NA,nrow(clones_unique))
clones_unique$VDJ_VJ_trimmed_majority <- rep(NA,nrow(clones_unique))
clones_unique$VDJ_trimmed_majority <- rep(NA,nrow(clones_unique))
clones_unique$count.unique.trimVH.trimVL <- rep(NA,nrow(clones_unique))
for (k in 1:nrow(clones_unique)){
cells.per.clone <- sample_dfs[[i]][sample_dfs[[i]]$clonotype_id %in% clones_unique$clonotype_id[k], ]
cells.per.clone.stats.VDJ_VJ <- sort(table(cells.per.clone$VDJ_VJ_trimmed),decreasing = T)
cells.per.clone.stats.VDJ <- sort(table(cells.per.clone$VDJ_sequence_nt_trimmed),decreasing = T)
cells.per.clone.stats.isotype <- sort(table(cells.per.clone$VDJ_cgene),decreasing = T)
clones_unique$count.VDJ_VJ_trimmed_majority[k] <- cells.per.clone.stats.VDJ_VJ[1]
clones_unique$VDJ_VJ_trimmed_majority[k] <- names(cells.per.clone.stats.VDJ_VJ)[1]
clones_unique$count.unique.trimVH.trimVL[k] <- length(unique(cells.per.clone$VDJ_VJ_trimmed))
clones_unique$count.VDJ_trimmed_majority[k] <- cells.per.clone.stats.VDJ[1]
clones_unique$VDJ_trimmed_majority[k] <- names(cells.per.clone.stats.VDJ)[1]
clones_unique$count.unique.trimVH[k] <- length(unique(cells.per.clone$VDJ_sequence_nt_trimmed))
clones_unique$VDJ_cgene[k] <- names(cells.per.clone.stats.isotype)[1]
}
clone.dataframe.list[[i]] <- clones_unique
}
return(clone.dataframe.list)
}
else if(output.format=="clone.level.dataframes" & global.clonotype == T){
sample_dfs$VDJ_VJ_trimmed <- paste0(sample_dfs$VDJ_sequence_nt_trimmed,sample_dfs$VJ_sequence_nt_trimmed)
clones_unique <- (sample_dfs[!duplicated(sample_dfs$clonotype_id),])
clones_unique$count.VDJ_VJ_trimmed_majority <- rep(NA,nrow(clones_unique))
clones_unique$VDJ_VJ_trimmed_majority <- rep(NA,nrow(clones_unique))
clones_unique$VDJ_trimmed_majority <- rep(NA,nrow(clones_unique))
clones_unique$count.unique.trimVH.trimVL <- rep(NA,nrow(clones_unique))
for (k in 1:nrow(clones_unique)){
cells.per.clone <- sample_dfs[sample_dfs$clonotype_id %in% clones_unique$clonotype_id[k], ]
cells.per.clone.stats.VDJ_VJ <- sort(table(cells.per.clone$VDJ_VJ_trimmed),decreasing = T)
cells.per.clone.stats.VDJ <- sort(table(cells.per.clone$VDJ_sequence_nt_trimmed),decreasing = T)
cells.per.clone.stats.isotype <- sort(table(cells.per.clone$VDJ_cgene),decreasing = T)
clones_unique$count.VDJ_VJ_trimmed_majority[k] <- cells.per.clone.stats.VDJ_VJ[1]
clones_unique$VDJ_VJ_trimmed_majority[k] <- names(cells.per.clone.stats.VDJ_VJ)[1]
clones_unique$count.unique.trimVH.trimVL[k] <- length(unique(cells.per.clone$VDJ_VJ_trimmed))
clones_unique$count.VDJ_trimmed_majority[k] <- cells.per.clone.stats.VDJ[1]
clones_unique$VDJ_trimmed_majority[k] <- names(cells.per.clone.stats.VDJ)[1]
clones_unique$count.unique.trimVH[k] <- length(unique(cells.per.clone$VDJ_sequence_nt_trimmed))
clones_unique$VDJ_cgene[k] <- names(cells.per.clone.stats.isotype)[1]
}
return(clones_unique)
}
else if(output.format=="phylo.dataframes"){
phylo.dataframe.list <- list()
for(i in 1:length(sample_dfs)){
if(VDJ.VJ.1chain==T){
sample_dfs[[i]] <- sample_dfs[[i]][which(sample_dfs[[i]]$clonotype_id!="clonotypeNA"),]
}
phylo.dataframe.list[[i]] <- split(sample_dfs[[i]],sample_dfs[[i]]$clonotype_id)
}
return(phylo.dataframe.list)
}
}
}
|
find_offset <- function(x) {
terms <- find_terms(x, flatten = TRUE)
offset <- NULL
offcol <- grep("^offset\\((.*)\\)", terms)
if (length(offcol)) {
offset <- clean_names(terms[offcol])
}
if (is.null(offset) && .obj_has_name(x, "call") && .obj_has_name(x$call, "offset")) {
offset <- clean_names(.safe_deparse(x$call$offset))
}
offset
}
|
summarise.enrichResult <- function(.data, ...) {
dots <- quos(...)
.data@result %>% summarise(!!!dots)
}
summarise.gseaResult <- summarise.enrichResult
summarise.compareClusterResult <- function(.data, ...) {
dots <- quos(...)
.data@compareClusterResult %>% summarise(!!!dots)
}
|
straightPath<- function(gps, nSmall = 10, nLarge = 60, thresh = 10, plot = FALSE) {
if(is.null(gps$Heading) ||
any(is.na(gps$Heading))) {
head <- bearing(matrix(c(gps$Longitude[1:(nrow(gps)-1)], gps$Latitude[1:(nrow(gps)-1)]), ncol=2),
matrix(c(gps$Longitude[2:(nrow(gps))], gps$Latitude[2:(nrow(gps))]), ncol=2)) %% 360
gps$Heading <- c(head, head[length(head)])
}
gps$realHead <- cos(gps$Heading * pi / 180)
gps$imHead <- sin(gps$Heading * pi / 180)
smallLag <- Arg(complex(real=roll_sumr(gps$realHead, n=nSmall, fill=NA),
imaginary=roll_sumr(gps$imHead, n = nSmall, fill = NA))) * 180 / pi
bigLag <- Arg(complex(real=roll_sumr(gps$realHead, n=nLarge, fill=NA),
imaginary=roll_sumr(gps$imHead, n = nLarge, fill = NA))) * 180 / pi
gps$timeDiff <- gps$UTC - c(gps$UTC[1], gps$UTC[1:(nrow(gps)-1)])
gps$timeGroup <- as.factor(cumsum(gps$timeDiff > 30))
gps$headDiff <- (bigLag - smallLag) %% 360
gps$headDiff <- ifelse(gps$headDiff > 180, gps$headDiff - 360, gps$headDiff)
gps$straight <- abs(gps$headDiff) < thresh
if(plot) {
gpsEnds <- gps[c(1, nrow(gps)), ]
gpsEnds$Type <- c('Start', 'End')
myPlot <- ggplot(gps, aes_string(x='Longitude', y='Latitude')) +
geom_point(data=gpsEnds, aes_string(x='Longitude', y='Latitude', shape='Type', col='straight'), size=4) +
geom_path() +
geom_path(aes_string(group='timeGroup', col='straight'), size = 1.3) +
scale_color_manual(limits=c(TRUE, FALSE), values = c('darkgreen','red')) +
scale_shape_manual(limits=c('Start', 'End'), values = c(16,7)) +
guides(color=guide_legend(override.aes=list(shape=32), title='Straight'),
shape=guide_legend(title='Endpoint', override.aes=list(color=ifelse(gpsEnds$straight, 'darkgreen', 'red'))))
print(myPlot)
}
gps
}
|
hyear <- function(dat, startmonth = 1){
if(startmonth > 6.5){
dat$hyear <- dat$year + (dat$month >= startmonth)
} else {
dat$hyear <- dat$year - (dat$month < startmonth)
}
dat
}
calendar_year <- function(x) {
x <- as.Date(x)
x <- as.numeric(format(x, "%Y"))
return(factor(x, levels = seq(min(x), max(x))))
}
water_year <- function(x, origin = "din", as.POSIX = FALSE,
assign = c("majority", "start", "end"), ...) {
assign <- match.arg(assign)
x <- as.POSIXlt(x, ...)
if (length(origin) != 1)
stop("argument 'origin' must be of length 1.", call. = FALSE)
defs <- c("din" = 11, "usgs" = 10, "swiss" = 10, "glacier" = 9)
if (origin %in% names(defs)) {
idx <- as.numeric(defs[origin])
} else {
idx <- pmatch(gsub(".", "", tolower(origin), fixed = TRUE),
tolower(month.name))
if (is.na(idx)) {
idx <- tryCatch(as.POSIXlt(origin)$mon + 1,
error = function(x) suppressWarnings(as.numeric(origin)))
if(is.na(idx) | !idx %in% 1:12)
stop("argument 'origin' must be either one of ",
paste(sQuote(names(defs)), collapse=", "),
" or a (possibly abbreviated) name of a month,",
" an integer between 1 and 12 or valid POSIX/Date object.")
}
}
origin <- idx
year <- x$year + 1900
month <- x$mon + 1
if(assign == "majority") assign <- ifelse(origin > 6, "end", "start")
offset <- if(assign == "start") 0 else 1
y <- year - (month < origin) + offset
if (as.POSIX) {
y <- as.POSIXct(paste(y, origin, "01", sep = "-"))
} else {
y <- factor(y, levels = seq(min(y), max(y)))
}
return(y)
}
"hyear_start<-" <- function(x, value) {
UseMethod("hyear_start<-")
}
"hyear_start<-.lfobj" <- function(x, value) {
attr(x, "lfobj")$hyearstart <- value
time <- time(x)
x$hyear <- as.numeric(as.character(water_year(x = time, origin = value)))
return(x)
}
"hyear_start<-.xts" <- function(x, value) {
if(!value %in% 1:12) stop("must be an integer between 1 and 12.")
xtsAttributes(x)$hyearstart <- value
return(x)
}
hyear_start <- function(x, abbreviate = FALSE) {
UseMethod("hyear_start")
}
hyear_start.data.frame <- function(x, abbreviate = FALSE){
hy <- attr(x, "lfobj")$hyearstart
if(is.null(hy) || (!hy %in% 1:12)) hy <- .guess_hyearstart(x)
if(is.null(hy)) {
warning("Couldn't determine start of hydrological year from attributes or columns.\nDefaulting to 'January'.",
call. = FALSE)
hy <- 1
}
if(abbreviate) hy <- month.abb[hy]
return(hy)
}
hyear_start.xts <- function(x, abbreviate = FALSE){
hy <- xtsAttributes(x)$hyearstart
if(is.null(hy) || (!hy %in% 1:12)) {
warning("Couldn't determine start of hydrological year from attributes.\nDefaulting to 'January'.",
call. = FALSE)
hy <- 1
}
if(abbreviate) hy <- month.abb[hy]
return(hy)
}
.guess_hyearstart <- function(lfobj) {
if(!"hyear" %in% names(lfobj)) {
hyearstart <- NULL
} else {
ii <- subset(lfobj, year != hyear, month)
if(nrow(ii) == 0){
hyearstart <- 1
} else if(max(ii) < 5.5){
hyearstart <- max(ii) + 1
} else {
hyearstart <- min(ii)
}
}
return(hyearstart)
}
|
niche.Model.Build<-function(prese=NULL,absen=NULL,
prese.env=NULL,absen.env=NULL,
model="RF",
en.vir=NULL,bak.vir=NULL)
{
search.For.Diff.Absen.From.Prese<-function(prese,absen){
eucl.dist.two.vect<-function(v1,v2){
v1minusv2<-v1-v2
squared.v1minusv2<-v1minusv2*v1minusv2
out.sqrt<-sqrt(sum(squared.v1minusv2))
return(out.sqrt)
}
prese<-stats::na.omit(prese)
absen<-stats::na.omit(absen)
prese<-as.matrix(prese)
absen<-as.matrix(absen)
prese<-apply(prese,MARGIN=2,as.numeric)
group.mean.prese<-apply(prese, MARGIN=2, mean, na.rm = T)
dist2center.prese<-apply(prese,1,eucl.dist.two.vect,v2=group.mean.prese)
ci95<-stats::quantile(dist2center.prese,prob=c(0.025,0.975),na.rm = T)
dist2center.absen<-apply(absen,1,eucl.dist.two.vect,v2=group.mean.prese)
dist2center.absen
within.CI95<-function(ci,x){
if(x>=ci[1]&&x<=ci[2]) return(TRUE)
else return (FALSE)
}
out2<-sapply(dist2center.absen, within.CI95,ci=ci95)
out2
return(out2)
}
model<-gsub("randomforest|RandomForest|randomForest","RF",model)
model<-gsub("maxent|Maxent","MAXENT",model)
if (is.null(prese.env) == T & is.null(en.vir) == T){
cat("Environmental layers downloading ... ")
envir<-raster::getData("worldclim",download=TRUE,var="bio",res=10)
en.vir<-raster::brick(envir)
cat("Done!\n")
}
if (is.null(prese)==TRUE & is.null(prese.env)==FALSE){
present.env0<-prese.env
if (nrow(present.env0) < 3){
warning ("prese.env has less than 3 records!\n")
}
}else{
if (!is.data.frame(prese)|dim(prese)[2]!=3){
stop ("The present data must be a dataframe with three columns
(species name, lon, lat)!\n")
}else{
if (is.null(prese.env)==TRUE){
if (nrow(prese) < 10){
prese<-pseudo.present.points(prese,10,10,2,en.vir=en.vir)
}
present.env0<-raster::extract(en.vir,prese[,2:3])
}else{
present.env0<-prese.env
if (nrow(present.env0) < 3){
warning ("prese.env has less than 3 records!\n")
}
}
}
}
if (is.null(absen)==TRUE & is.null(absen.env)==TRUE){
outputNum=nrow(present.env0)*10
if (is.null(bak.vir)==TRUE){
back<-dismo::randomPoints(mask=en.vir,n=outputNum*2,ext=NULL,
extf=1.1,excludep=TRUE,prob=FALSE,
cellnumbers=FALSE,tryf=3,warn=2,
lonlatCorrection=TRUE)
bak.vir<-raster::extract(en.vir,back)
bak0<-bak.vir[,colnames(bak.vir) %in% colnames(present.env0)]
diff.absen.from.prese<-search.For.Diff.Absen.From.Prese(present.env0,bak0)
diff<-bak0[which(diff.absen.from.prese==FALSE),]
samp<-sample(dim(diff)[1],size=outputNum)
absent.env0<-diff[samp,]
}else{
bak0<-bak.vir[,colnames(bak.vir) %in% colnames(present.env0)]
if (nrow(bak.vir) < outputNum*2){
more<-outputNum*2-nrow(bak.vir)
more.back<-dismo::randomPoints(mask=en.vir,n=more,ext=NULL,extf=1.1,
excludep=TRUE,prob=FALSE,cellnumbers=FALSE,
tryf=3,warn=2,lonlatCorrection=TRUE)
more.bak.vir<-raster::extract(en.vir,more.back)
more.bak0<-more.bak.vir[,colnames(more.bak.vir) %in% colnames(present.env0)]
bak0<-rbind(bak0,more.bak0)
}
diff.absen.from.prese<-search.For.Diff.Absen.From.Prese(present.env0,bak0)
diff<-bak0[which(diff.absen.from.prese==FALSE),]
if (is.null(nrow(diff)) || nrow(diff) == 0){
ref.mean<-apply(present.env0,FUN=mean,MARGIN=2)
ref.sd<-apply(present.env0,FUN=stats::sd,MARGIN=2)
ref.range<-apply(present.env0,FUN=max,MARGIN=2)-apply(present.env0,FUN=min,MARGIN=2)
for (rs in 1:length(ref.sd)){
if (ref.sd[rs] == 0){ ref.sd[rs]<-ref.mean[rs]/4 }
if (ref.range[rs] == 0){ ref.range[rs]<-ref.sd[rs]*2 }
}
q.01<-stats::qnorm(0.01,mean=ref.mean,sd=ref.sd)
q.99<-stats::qnorm(0.99,mean=ref.mean,sd=ref.sd)
absent.env0<-matrix(nrow=outputNum,ncol=ncol(present.env0))
for (en in 1:ncol(present.env0)){
tmp.left<-stats::runif(outputNum/2,min=(q.01[en]-2*ref.range[en]),max=q.01[en]-ref.range[en])
tmp.right<-stats::runif(outputNum/2,min=q.99[en]+ref.range[en],max=q.99[en]+2*ref.range[en])
tmp.ab<-c(tmp.left,tmp.right)
absent.env0[,en]<-as.integer(tmp.ab)
}
colnames(absent.env0)<-colnames(present.env0)
warning ("The pseudoabsence data are randomly generated from the 95%CI of the presence data.\n")
}else if(nrow(diff) < outputNum){
absent.env0<-diff
}else{
samp<-sample(dim(diff)[1],size=outputNum)
absent.env0<-diff[samp,]
}
}
}else{
if (is.null(absen.env)==TRUE){
absent.env0<-raster::extract(en.vir,absen)
}else{
absent.env0<-absen.env
}
}
present.env<-cbind(Count=1,present.env0)
present.env<-as.data.frame(apply(present.env,FUN=as.numeric,MARGIN=2))
absent.env<-cbind(Count=0,absent.env0)
absent.env<-as.data.frame(apply(absent.env,FUN=as.numeric,MARGIN=2))
Data<-as.data.frame(rbind(present.env,absent.env))
Data$Count=as.factor(Data$Count)
if (model == "RF"){
mod<-randomForest::randomForest(Count ~., Data, ntree=500,
importance=TRUE,
na.action=randomForest::na.roughfix)
use<-c(rep(1,nrow(present.env)),rep(0,nrow(absent.env)))
prb<-c(stats::predict(mod,present.env,type="prob")[,2],
stats::predict(mod,absent.env,type="prob")[,2])
}else if (model == "MAXENT"){
jar<-paste(system.file(package="dismo"), "/java/maxent.jar", sep='')
if (file.exists(jar)){
mod<-suppressWarnings(dismo::maxent(Data[,-1],Data[,1],
args='outputformat=logistic'))
use<-c(rep(1,nrow(present.env)),rep(0,nrow(absent.env)))
prb<-c(dismo::predict(mod,present.env,args='outputformat=logistic'),
dismo::predict(mod,absent.env,args='outputformat=logistic'))
}else{
stop(paste("Please insure that the maxent.jar file have been placed into\n",
system.file(package="dismo"), "/java",sep=""))
}
}
roc1<-pROC::roc(use,prb,precent=T,auc=T,plot=F,quiet=T)
SST<-pROC::coords(roc1,x="best",ret=c("specificity","sensitivity","threshold"),
transpose=T)
NMB<-list()
NMB$model<-mod
NMB$SST<-SST
return(NMB)
}
|
print.gmnl <- function(x, digits = max(3, getOption("digits") - 3),
width = getOption("width"), ...){
cat("\nCall:\n", deparse(x$call),"\n\n", sep = "")
cat("\nCoefficients:\n")
print.default(format(coef(x), digits = digits), print.gap = 2,
quote = FALSE)
cat("\n")
invisible(x)
}
summary.gmnl <- function(object,...){
b <- object$coefficients
std.err <- sqrt(diag(vcov(object)))
z <- b / std.err
p <- 2 * (1 - pnorm(abs(z)))
CoefTable <- cbind(b, std.err, z, p)
colnames(CoefTable) <- c("Estimate", "Std. Error", "z-value", "Pr(>|z|)")
object$CoefTable <- CoefTable
class(object) <- c("summary.gmnl", "gmnl")
return(object)
}
print.summary.gmnl <- function(x, digits = max(3, getOption("digits") - 2),
width = getOption("width"),
...){
cat(paste("\nModel estimated on:", format(Sys.time(), "%a %b %d %X %Y"), "\n"))
cat("\nCall:\n")
cat(paste(deparse(x$call), sep = "\n", collapse = "\n"), "\n", sep = "")
cat("\nFrequencies of categories:\n")
print(prop.table(x$freq), digits = digits)
cat("\n")
cat(paste("The estimation took:", make.time(x) ,"\n"))
cat("\nCoefficients:\n")
printCoefmat(x$CoefTable, digits = digits)
cat(paste("\nOptimization of log-likelihood by", x$logLik$type))
cat(paste("\nLog Likelihood:", signif(x$logLik$maximum, digits)))
cat(paste("\nNumber of observations:", x$logLik$nobs))
cat(paste("\nNumber of iterations:" , x$logLik$iterations))
cat(paste("\nExit of MLE:", x$logLik$message))
if (!(x$model == "mnl" | x$model == "lc")) cat(paste("\nSimulation based on", x$R, "draws"))
invisible(x)
}
vcov.gmnl <- function(object, what = c('coefficient', 'ranp'), type = c('cov', 'cor', 'sd'),
se = FALSE, Q = NULL, digits = max(3, getOption("digits") - 2), ...)
{
what <- match.arg(what)
type <- match.arg(type)
if (what == 'coefficient') {
H <- object$logLik$hessian
vcov <- solve(-H)
rownames(vcov) <- colnames(vcov) <- names(coef(object))
return(vcov)
}
if (what == 'ranp') {
if (se) {
if (type == 'cov') se.cov.gmnl(object, sd = FALSE, Q = Q, digits = digits)
if (type == 'sd') se.cov.gmnl(object, sd = TRUE, Q = Q, digits = digits)
if (type == 'cor') stop("standard error for correlation coefficients not implemented yet")
} else {
if (type == 'cov') print(cov.gmnl(object, Q = Q))
if (type == 'cor') print(cor.gmnl(object, Q = Q))
if (type == 'sd') print(sqrt(diag(cov.gmnl(object, Q))))
}
}
}
update.gmnl <- function(object, new, ...){
call <- object$call
if (is.null(call))
stop("need an object with call component")
extras <- match.call(expand.dots = FALSE)$...
if (!missing(new))
call$formula <- update(formula(object), new)
if (length(extras) > 0) {
existing <- !is.na(match(names(extras), names(call)))
for (a in names(extras)[existing]) call[[a]] <- extras[[a]]
if (any(!existing)) {
call <- c(as.list(call), extras[!existing])
call <- as.call(call)
}
}
eval(call, parent.frame())
}
coef.gmnl <- function(object, ...){
result <- object$coefficients
return(result)
}
model.matrix.gmnl <- function(object, ...){
model.matrix(object$formula, object$mf)
}
model.response.gmnl <- function(object, ...){
y.name <- paste(deparse(object$formula[[2]]))
object$mf[[y.name]]
}
residuals.gmnl <- function(object, outcome = TRUE, ...){
if (!outcome) {
result <- object$residuals
}
else{
J <- ncol(object$residuals)
y <- matrix(model.response.gmnl(object), ncol = J, byrow = T)
result <- apply(y * object$residuals, 1, sum)
}
result
}
df.residual.gmnl <- function(object, ...){
n <- length(residuals(object))
K <- length(coef(object))
return(n - K)
}
fitted.gmnl <- function(object, outcome = TRUE, ...){
if (outcome) result <- object$prob.ind
else result <- object$prob.alt
return(result)
}
logLik.gmnl <- function(object,...){
structure(object$logLik$maximum[[1]], df = length(object$coefficients),
nobs = object$logLik$nobs, class = "logLik")
}
getSummary.gmnl <- function(obj, alpha = 0.05, ...){
smry <- summary(obj)
coef <- smry$CoefTable
lower <- coef[, 1] - coef[, 2] * qnorm(alpha / 2)
upper <- coef[, 1] + coef[, 2] * qnorm(alpha / 2)
coef <- cbind(coef, lower, upper)
colnames(coef) <- c("est", "se", "stat", "p", "lwr", "upr")
N <- obj$logLik$nobs
ll <- logLik(obj)
sumstat <- c(logLik = ll, deviance = NA, AIC = AIC(obj), BIC = BIC(obj), N = N,
LR = NA, df = NA, p = NA, Aldrich.Nelson = NA, McFadden = NA, Cox.Snell = NA,
Nagelkerke = NA)
list(coef = coef, sumstat = sumstat, contrasts = obj$contrasts,
xlevels = NULL, call = obj$call)
}
AIC.gmnl <- function(object, ..., k = 2){
return(-2 * object$logLik$maximum[[1]] + k * length(coef(object)))
}
BIC.gmnl <- function(object, ...){
return(AIC(object, k = log(object$logLik$nobs)))
}
bread.gmnl <- function(x, ... ){
return( vcov( x ) * x$logLik$nobs)
}
estfun.gmnl <- function(x, ... ){
return(x$logLik$gradientObs )
}
nObs.gmnl <- function(x, ... ){
return(x$logLik$nobs)
}
effect.gmnl <- function(x, par = NULL, effect = c("ce", "wtp"), wrt = NULL, ... ){
if (!inherits(x, "gmnl")) stop("not a \"gmnl\" object")
model <- x$model
if (model == "mnl") stop("This function is valid only for models with individual heterogeneity")
type <- match.arg(effect)
ranp <- x$ranp
if (type == "wtp" & is.null(wrt)) stop("you need to specify wrt")
bi <- x$bi
Qir <- x$Qir
if (model == "mixl" || model == "gmnl" || model == "smnl") {
N <- nrow(Qir)
K <- dim(bi)[[3]]
var_coefn <- dimnames(bi)[[3]]
mean <- mean.sq <- matrix(NA, N, K)
if (type == "wtp") {
if (model != "smnl") {
is.ran <- any(names(ranp) %in% wrt)
gamma <- if (is.ran) bi[, , wrt] else coef(x)[wrt]
} else gamma <- bi[, , wrt]
for (j in 1:K) {
mean[, j] <- rowSums((bi[, , j] / gamma) * Qir)
mean.sq[, j] <- rowSums(((bi[, , j] / gamma) ^ 2) * Qir)
}
} else {
for (j in 1:K) {
mean[, j] <- rowSums(bi[, , j] * Qir)
mean.sq[, j] <- rowSums(bi[, , j] ^ 2 * Qir)
}
}
}
if (model == "lc") {
N <- nrow(Qir)
K <- ncol(bi)
var_coefn <- colnames(bi)
mean <- mean.sq <- matrix(NA, N, K)
if (type == "wtp") {
gamma <- bi[, wrt]
for (j in 1:K) {
mean[, j] <- rowSums(repRows(bi[, j] / gamma, N) * Qir)
mean.sq[, j] <- rowSums(repRows((bi[, j] / gamma) ^ 2, N) * Qir)
}
} else {
for (j in 1:K) {
mean[, j] <- rowSums(repRows(bi[, j], N) * Qir)
mean.sq[, j] <- rowSums(repRows(bi[, j] ^ 2, N) * Qir)
}
}
}
if (model == "mm") {
wnq <- Qir$wnq
Ln <- Qir$Ln
Pnrq <- Qir$Pnrq
N <- length(Ln)
K <- dim(bi)[[4]]
mean <- mean.sq <- matrix(NA, N, K)
var_coefn <- dimnames(bi)[[4]]
if (type == "wtp") {
gamma <- bi[,,,wrt]
for (j in 1:K) {
mean[, j] <- rowSums(wnq * apply((bi[,,,j] / gamma) * Pnrq, c(1, 3), mean) / Ln)
mean.sq[, j] <- rowSums(wnq * apply((bi[,,,j] / gamma) ^ 2 * Pnrq, c(1, 3), mean) / Ln)
}
} else {
for (j in 1:K) {
mean[, j] <- rowSums(wnq * apply(bi[,,,j] * Pnrq, c(1, 3), mean) / Ln)
mean.sq[, j] <- rowSums(wnq * apply(bi[,,,j] ^ 2 * Pnrq, c(1, 3), mean) / Ln)
}
}
}
sd.est <- suppressWarnings(sqrt(mean.sq - mean ^ 2))
colnames(mean) <- colnames(sd.est) <- var_coefn
if (!is.null(par)) {
mean <- mean[, par]
sd.est <- sd.est[, par]
}
effe <- list(
mean = mean,
sd.est = sd.est)
return(effe)
}
plot.gmnl <- function(x, par = NULL, effect = c("ce", "wtp"), wrt = NULL,
type = c("density", "histogram"), adjust = 1,
main = NULL, col = "indianred1", breaks = 10, ylab = NULL,
xlab = NULL, ind = FALSE, id = NULL, ...){
model <- x$model
if (model == "mnl") stop("The plot is valid only for models with individual heterogeneity")
if (is.null(par)) stop("Must specified the name of the parameter")
type <- match.arg(type)
effect <- match.arg(effect)
xlab <- switch(effect,
"wtp" = expression(E(hat(wtp[i]))),
"ce" = expression(E(hat(beta[i]))))
if (!ind) {
if (is.null(main)) main <- paste("Conditional Distribution for", par)
if (is.null(ylab)) {
ylab <- switch(type,
"density" = "Density",
"histogram" = "Frequency")
}
rpar <- effect.gmnl(x, par, effect = effect, wrt = wrt)$mean
if (type == "density") {
pdens <- density(rpar, adjust = adjust)
plot(pdens, ylab = ylab, xlab = xlab, main = main, col = col)
has.pos <- any(pdens$x > 0)
if (has.pos) {
x1 <- min(which(pdens$x >= 0))
x2 <- max(which(pdens$x < max(pdens$x)))
with(pdens, polygon(x = c(x[c(x1, x1:x2, x2)]), y = c(0, y[x1:x2], 0), col = col, border = NA))
}
} else {
minb <- round(min(rpar), 2)
maxb <- round(max(rpar), 2)
hist(rpar, xlab = xlab, main = main, col = col, breaks = breaks,
xaxs = "i", yaxs = "i", las = 1, xaxt = 'n', ylab = ylab)
axis(1, at = seq(minb, maxb, (maxb - minb) * .05))
}
} else {
if (is.null(main)) main <- paste("95% Probability Intervals for ", par)
if (is.null(id)) id <- seq(1, 10, 1)
if (is.null(ylab)) ylab <- "Individuals"
f.bran <- effect.gmnl(x, par, effect = effect, wrt = wrt)$mean
f.sran <- effect.gmnl(x, par, effect = effect, wrt = wrt)$sd.est
lower <- f.bran - qnorm(0.975) * f.sran
upper <- f.bran + qnorm(0.975) * f.sran
plotrix::plotCI(as.numeric(id), f.bran[id], ui = upper[id], li = lower[id],
xlab = ylab, ylab = xlab,
lty = 2, main = main,
pch = 21, col = col)
}
}
cov.gmnl <- function(x, Q = NULL){
if (!inherits(x, "gmnl")) stop("not a \"gmnl\" object")
if (is.null(x$ranp)) stop('cov.gmnl only relevant for random coefficient model')
model <- x$model
if (!is.null(Q) & model != "mm") stop("Q is only relevant for MM-MNL model")
if (model == "mm") {
if (is.null(Q)) stop("MM-MNL model requires Q")
if (Q > x$Q) stop("Q is greater than the number of classes in the fitted model")
}
beta.hat <- x$coefficients
K <- length(x$ranp)
nr <- names(x$ranp)
if (x$correlation) {
names.stds <- c()
if (model == "mm") {
for (i in 1:K) names.stds <- c(names.stds, paste('class', Q, 'sd', nr[i], nr[i:K], sep = '.'))
} else {
for (i in 1:K) names.stds <- c(names.stds, paste('sd', nr[i], nr[i:K], sep = '.'))
}
v <- beta.hat[names.stds]
V <- tcrossprod(makeL(v))
colnames(V) <- rownames(V) <- nr
} else{
names.stds <- if (model != "mm") paste("sd", nr, sep = ".") else paste("class", Q, "sd", nr, sep = ".")
sv <- beta.hat[names.stds]
V <- matrix(0, K, K)
diag(V) <- sv ^ 2
colnames(V) <- rownames(V) <- nr
}
return(V)
}
cor.gmnl <- function(x, Q = NULL){
if (!x$correlation) stop('cor.gmnl only relevant for correlated random coefficient')
V <- cov.gmnl(x, Q = Q)
nr <- names(x$ranp)
D <- diag(sqrt(diag(V)))
Rho <- solve(D) %*% V %*% solve(D)
colnames(Rho) <- rownames(Rho) <- nr
return(Rho)
}
se.cov.gmnl <- function(x, sd = FALSE, Q = NULL, digits = max(3, getOption("digits") - 2)){
if (!inherits(x, "gmnl")) stop("not a \"gmnl\" object")
if (!x$correlation) stop('se.cov.gmnl only relevant for correlated random coefficient')
model <- x$model
if (!is.null(Q) & model != "mm") stop("Q is only relevant for MM-MNL model")
if (model == "mm") {
if (is.null(Q)) stop("MM-MNL model requires Q")
if (Q > x$Q) stop("Q is greater than the number of classes in the fitted model")
}
beta.hat <- x$coefficients
Ka <- length(x$ranp)
nr <- names(x$ranp)
names.stds <- c()
if (model == "mm") {
for (i in 1:Ka) names.stds <- c(names.stds, paste('class', Q, 'sd', nr[i], nr[i:Ka], sep = '.'))
} else {
for (i in 1:Ka) names.stds <- c(names.stds, paste('sd', nr[i], nr[i:Ka], sep = '.'))
}
stds.hat <- beta.hat[names.stds]
sel.vcov <- vcov(x)[names.stds, names.stds]
form <- c()
if (sd) {
for (i in 1:Ka) {
k <- i
if (i == 1) {
form <- paste("~ sqrt(", c(form, paste(paste("x", i, sep = ""), paste("x", k, sep = ""), sep = "*")), ")")
} else {
temp <- paste(paste("x", i, sep = ""), paste("x", k, sep = ""), sep = "*")
j <- 2
while (j <= i) {
temp <- paste(temp, make.add(row = j, col = k, Ka = Ka)[1], sep = "+")
j <- j + 1
}
form <- c(form, paste("~ sqrt(", temp, ")"))
}
}
b <- sqrt(diag(cov.gmnl(x, Q)))
names(b) <- colnames(cov.gmnl(x, Q))
} else {
for (i in 1:Ka) {
if (i == 1) {
form <- paste("~", c(form, paste(paste("x", i:Ka, sep = ""), paste("x", i, sep = ""), sep = "*")))
} else {
temp <- paste(paste("x", i:Ka, sep = ""), paste("x", i, sep = ""), sep = "*")
j <- 2
while (j <= i) {
temp <- paste(temp, make.add(row = j, col = i, Ka = Ka), sep = "+")
j <- j + 1
}
form <- c(form, paste("~", temp))
}
}
names.vcov <- c()
for (i in 1:Ka) names.vcov <- c(names.vcov, paste('v', nr[i], nr[i:Ka], sep = '.'))
b <- drop(cov.gmnl(x, Q)[lower.tri(cov.gmnl(x, Q), diag = TRUE)])
names(b) <- names.vcov
}
std.err <- c()
for (i in 1:length(form)) {
std.err <- c(std.err, msm::deltamethod(as.formula(form[i]), stds.hat, sel.vcov, ses = TRUE))
}
z <- b / std.err
p <- 2 * (1 - pnorm(abs(z)))
tableChol <- cbind(b, std.err, z, p)
if (!sd) cat(paste("\nElements of the variance-covariance matrix \n\n"))
else cat(paste("\nStandard deviations of the random parameters \n\n"))
colnames(tableChol) <- c("Estimate", "Std. Error", "z-value", "Pr(>|z|)")
printCoefmat(tableChol, digits = digits)
}
wtp.gmnl <- function(object, wrt = NULL, digits = max(3, getOption("digits") - 2)){
if (is.null(wrt)) stop("WTP needs the variable in the denominator: wrt")
beta.hat <- coef(object)
posi <- match(wrt, names(beta.hat))
form <- c()
b <- c()
namesb <- names(beta.hat)[-c(posi)]
for (i in 1:length(beta.hat)) {
if (i != posi) {
b <- c(b, beta.hat[i]/ beta.hat[posi])
form <- c(form, paste("~", "x", i, "/", "x", posi, sep = ""))
}
}
names(b) <- namesb
std.err <- c()
for (i in 1:length(form)) {
std.err <- c(std.err, msm::deltamethod(as.formula(form[i]), beta.hat, vcov(object), ses = TRUE))
}
z <- b / std.err
p <- 2 * (1 - pnorm(abs(z)))
tablewtp <- cbind(b, std.err, z, p)
colnames(tablewtp) <- c("Estimate", "Std. Error", "t-value", "Pr(>|t|)")
cat(paste("\nWilligness-to-pay respect to: ", wrt, "\n\n"))
printCoefmat(tablewtp, digits = digits)
}
|
library(animint)
data(generation.loci)
generations <- data.frame(generation=unique(generation.loci$generation))
loci <- data.frame(locus=unique(generation.loci$locus))
two.selectors.not.animated <-
list(ts=ggplot()+
geom_vline(aes(xintercept=generation, clickSelects=generation),
data=generations, alpha=1/2, lwd=4)+
geom_line(aes(generation, frequency, group=population,
showSelected=locus), data=generation.loci),
loci=ggplot()+
geom_vline(aes(xintercept=locus, clickSelects=locus),
data=loci, alpha=1/2, size=4)+
geom_point(aes(locus, frequency, showSelected=generation),
data=generation.loci),
duration=list(generation=1000)
)
animint2dir(two.selectors.not.animated)
colormap <- c(blue="blue",red="red",ancestral="black",neutral="grey30")
ancestral <- subset(generation.loci,population==1 & generation==1)
ancestral$color <- "ancestral"
two.selectors.color <-
list(ts=ggplot()+
make_tallrect(generation.loci, "generation")+
geom_text(aes(generation,frequency,showSelected=locus,
label=sprintf("locus %d",locus)),
data=data.frame(loci,generation=50,frequency=1.05))+
scale_colour_manual(values=colormap)+
geom_line(aes(generation, frequency, group=population,
colour=color, showSelected=locus),
data=generation.loci)+
geom_point(aes(generation, frequency, showSelected=locus),
data=ancestral),
loci=ggplot()+
make_tallrect(generation.loci, "locus")+
scale_fill_manual(values=colormap)+
scale_colour_manual(values=colormap)+
geom_point(aes(locus, frequency, colour=color, fill=color,
showSelected=generation),
data=generation.loci, pch=21)+
geom_point(aes(locus, frequency, colour=color, fill=color),
data=ancestral, pch=21)+
geom_text(aes(locus,frequency,showSelected=generation,
label=sprintf("generation %d",generation)),
data=data.frame(generations,locus=35,frequency=1)),
duration=list(generation=1000))
animint2dir(two.selectors.color)
first <- subset(generation.loci,generation==1)
ancestral <- do.call(rbind,lapply(split(first,first$locus),with,{
stopifnot(all(frequency==frequency[1]))
data.frame(locus=locus[1],ancestral=frequency[1])
}))
gl.list <- split(generation.loci,
with(generation.loci,list(generation,locus)))
generation.pop <- do.call(rbind,lapply(gl.list,with,{
data.frame(generation=generation[1], locus=locus[1],
estimated=mean(frequency))
}))
generation.pop$ancestral <- ancestral$ancestral[generation.pop$locus]
generation.loci.last <- subset(generation.loci,generation==max(generation))
generation.pop.last <- subset(generation.pop,generation==max(generation))
one.selector.not.animated <-
list(ts=ggplot()+
geom_line(aes(generation, frequency, group=population,
showSelected=locus), data=generation.loci),
predictions=ggplot()+
geom_point(aes(ancestral, estimated, clickSelects=locus),
data=generation.pop.last, size=4, alpha=3/4),
loci=ggplot()+
geom_vline(aes(xintercept=locus, clickSelects=locus),
data=loci, alpha=1/2, lwd=4)+
geom_point(aes(locus, frequency), data=generation.loci.last)
)
animint2dir(one.selector.not.animated)
two.selectors.animated <-
list(ts=ggplot()+
geom_vline(aes(xintercept=generation,
clickSelects=generation),
data=generations, alpha=1/2, lwd=4)+
geom_line(aes(generation, frequency, group=population,
showSelected=locus), data=generation.loci),
predictions=ggplot()+
geom_point(aes(ancestral, estimated, showSelected=generation,
clickSelects=locus),
data=generation.pop, size=4, alpha=3/4),
loci=ggplot()+
geom_vline(aes(xintercept=locus, clickSelects=locus),
data=loci, alpha=1/2, lwd=4)+
geom_point(aes(locus, frequency, showSelected=generation),
data=generation.loci),
duration=list(generation=1000),
time=list(variable="generation",ms=2000))
animint2dir(two.selectors.animated)
|
dotplotGUI <- function(){
defaults <- list(initial.x = NULL, initialGroup=NULL, initial.stacked = 0, initial.commonscale = 1)
dialog.values <- getDialog("dotplot", defaults)
initializeDialog(title=gettextRcmdr("Dotplot"))
variablesFrame <- tkframe(top)
.numeric <- Numeric()
xBox <- variableListBox(variablesFrame, .numeric, title=gettextRcmdr("Variable to be ploted (pick one)"),
initialSelection = varPosn (dialog.values$initial.x, "numeric"))
initial.group <- dialog.values$initial.group
.groups <- if (is.null(initial.group)) FALSE else initial.group
onOK <- function(){
x <- getSelection(xBox)
stacked <- tclvalue(stackedVariable)
commonscale <- tclvalue(commonscaleVariable)
if (length(x) != 1){
errorCondition(recall=dotplotGUI, message=gettextRcmdr("You must select one variable."))
return()
}
putDialog ("dotplot", list(initial.x = x,
initial.group=if (.groups == FALSE) NULL else .groups,
initial.stacked = "1"==stacked,
initial.commonscale = "1"==commonscale))
closeDialog()
.activeDataSet <- ActiveDataSet()
if (is.null(.groups) || .groups == FALSE) {
doItAndPrint(paste("dotPlot(", .activeDataSet, "$", x, ", xlab='", x, "',cex=1)", sep=""))
} else {
ngr <- eval(parse(text=paste("length(levels(",.activeDataSet,"$",.groups,"))")))
if(stacked=="1"){
pch.tmp <- c(21,20,17,15,5,4,3)
doItAndPrint(paste("pch <- c(", paste(pch.tmp[1:ngr],sep="",collapse=","),")",sep=""))
doItAndPrint(paste("ord <- order(as.numeric(", .activeDataSet, "$", .groups, "))", sep=""))
doItAndPrint(paste("dotPlot(", .activeDataSet, "$", x, "[ord], xlab='", x, "', pch=pch[",.activeDataSet,"$",.groups,"[ord]], cex=1)", sep=""))
doItAndPrint(paste("legend('topright', legend=c('",paste(eval(parse(text=paste("levels(factor(",.activeDataSet,"$",.groups,"[ord]))",sep=""))),sep="",collapse="','"),"'), pch=pch)",sep=""))
doItAndPrint("rm(list=c('pch','ord'))")
} else {
doItAndPrint(paste("par(mfrow=c(",ngr,",1), mar=c(4,4,1,1), cex=1)",sep=""))
if(commonscale=="1"){
for(i in 1:ngr){
doItAndPrint(paste("dotPlot(", .activeDataSet, "$", x, "[", .activeDataSet,"$",.groups,"==levels(", .activeDataSet,"$",.groups,")[",i,"]],xlim = range(",.activeDataSet,"$",x,", na.rm = TRUE), xlab='", x, " (",eval(parse(text=paste("levels(", .activeDataSet,"$",.groups,")[",i,"]",sep=""))),")')", sep=""))
}
}else{
for(i in 1:ngr){
doItAndPrint(paste("dotPlot(", .activeDataSet, "$", x, "[", .activeDataSet,"$",.groups,"==levels(", .activeDataSet,"$",.groups,")[",i,"]], xlab='", x, " (",eval(parse(text=paste("levels(", .activeDataSet,"$",.groups,")[",i,"]",sep=""))),")')", sep=""))
}
}
doItAndPrint(paste("par(mfrow=c(1,1), mar=c(5,4,4,2)+0.1, cex=1)",sep=""))
}
}
tkfocus(CommanderWindow())
}
groupsBox(dotPlot, initialGroup=initial.group,
initialLabel=if (is.null(initial.group)) gettextRcmdr("Plot by groups") else paste(gettextRcmdr("Plot by:"), initial.group))
OKCancelHelp(helpSubject="dotPlot")
tkgrid(getFrame(xBox), sticky="nw")
tkgrid(variablesFrame, sticky="nw")
tkgrid(groupsFrame, sticky = "w")
stackedFrame <- tkframe(top)
commonscaleFrame <- tkframe(top)
checkBoxes(frame="stackedFrame", boxes=c("stacked"), initialValues=dialog.values$initial.stacked, labels=gettextRcmdr(c("Stack groups")))
checkBoxes(frame="commonscaleFrame", boxes=c("commonscale"), initialValues=dialog.values$initial.commonscale, labels=gettextRcmdr(c("Use common x-scale")))
tkgrid(stackedFrame, sticky="w")
tkgrid(commonscaleFrame, sticky="w")
tkgrid(buttonsFrame, sticky="w")
dialogSuffix(rows=3, columns=1)
}
fittedLinePlot <- function(){
initializeDialog(title=gettextRcmdr("Fitted regression plot"))
variablesXFrame <- tkframe(top)
variablesYFrame <- tkframe(top)
.numeric <- Numeric()
.activeDataSet <- ActiveDataSet()
xBox <- variableListBox(variablesXFrame, .numeric, title=gettextRcmdr("X: regressor variable (pick one)"))
yBox <- variableListBox(variablesYFrame, .numeric, title=gettextRcmdr("Y: response variable (pick one)"))
comboXFrame <- tkframe(top)
comboXVar <- tclVar()
valuesX <- c('none', 'no intercept', 'x^2, x', 'x^3, x^2, x', 'log(x)', '1/x', 'exp(x)')
onOK <- function(){
x <- getSelection(xBox)
y <- getSelection(yBox)
if (length(x) == 0 | length(y) == 0){
errorCondition(recall=fittedLinePlot, message=gettextRcmdr("You must select two variables."))
return()
}
if (x == y){
errorCondition(recall=fittedLinePlot, message=gettextRcmdr("Variables must be different."))
return()
}
level <- tclvalue(confidenceLevel)
range.X <- justDoIt(paste("range(", .activeDataSet, "$", x, ")", sep=""))
new.x <- seq(range.X[1], range.X[2], length.out=200)
if(tclvalue(comboXVar)==""){
selectedTrans <- 1
} else {
selectedTrans <- which(valuesX==tclvalue(comboXVar))}
if(selectedTrans==1){
x.val <- paste(x, sep="")
}
if(selectedTrans==2){
x.val <- paste(x, "-1", sep="")
}
if(selectedTrans==3){
x.val <- paste("I(", x, "^2) + ", x, sep="")
}
if(selectedTrans==4){
x.val <- paste("I(", x, "^3) + I(", x, "^2) + ", x, sep="")
}
if(selectedTrans==5){
x.val <- paste("log(", x, ")", sep="")
}
if(selectedTrans==6){
x.val <- paste("1/", x, sep="")
}
if(selectedTrans==7){
x.val <- paste("exp(", x, ")", sep="")
}
closeDialog()
justDoIt(paste("my.lm <- lm(", y, "~", x.val, ", data=list(", y, "=", .activeDataSet, "$", y, ", ", x, "=", .activeDataSet, "$", x, "))", sep=""))
y.conf <- justDoIt(paste("predict(my.lm, data.frame(", x, "=c(", paste(new.x, sep="", collapse=","), ")), interval='conf', level=", level, ")", sep=""))
y.pred <- justDoIt(paste("predict(my.lm, data.frame(", x, "=c(", paste(new.x, sep="", collapse=","), ")), interval='prediction', level=", level, ")", sep=""))
lm.coef <- coef(my.lm)
fit.text <- paste(y, " ~ ", format(lm.coef[1],digits=2), sep="")
for(i in 2:length(lm.coef))
fit.text <- paste(fit.text, " + ", format(lm.coef[i],digits=2), "*", names(lm.coef)[i], sep="")
sub.text <- paste(100 * as.numeric(level), "% CI and PI, R^2=", format(summary(my.lm)[]$r.squared, digits=2), sep = "")
justDoIt(paste("plot(", .activeDataSet, "$", x, ", ", .activeDataSet, "$", y, ", xlab='", x, "', ylab='", y, "', ylim=c(",min(y.pred),",",max(y.pred),"), main=c('",fit.text,"', '", sub.text,"'))", sep=""))
justDoIt(paste("lines(c(", paste(new.x, sep="", collapse=","), "), c(", paste(y.conf[,1], sep="", collapse=","), "))", sep=""))
justDoIt(paste("lines(c(", paste(new.x, sep="", collapse=","), "), c(", paste(y.conf[,2], sep="", collapse=","), "), lty=2, col='blue')", sep=""))
justDoIt(paste("lines(c(", paste(new.x, sep="", collapse=","), "), c(", paste(y.conf[,3], sep="", collapse=","), "), lty=2, col='blue')", sep=""))
justDoIt(paste("lines(c(", paste(new.x, sep="", collapse=","), "), c(", paste(y.pred[,2], sep="", collapse=","), "), lty=2, col='red')", sep=""))
justDoIt(paste("lines(c(", paste(new.x, sep="", collapse=","), "), c(", paste(y.pred[,3], sep="", collapse=","), "), lty=2, col='red')", sep=""))
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject="lm")
optionsFrame <- tkframe(top)
confidenceFrame <- tkframe(optionsFrame)
confidenceLevel <- tclVar(".95")
confidenceField <- ttkentry(confidenceFrame, width="6", textvariable=confidenceLevel)
tkgrid(getFrame(xBox), sticky="nw")
tkgrid(variablesXFrame, column=1, row=1, columnspan=1, sticky="nw")
tkgrid(getFrame(yBox), sticky="nw")
tkgrid(variablesYFrame, column=2, row=1, columnspan=1, sticky="nw")
comboX <- ttkcombobox(comboXFrame, values=valuesX, textvariable=comboXVar)
tkgrid(labelRcmdr(comboXFrame, text=gettextRcmdr("X transf.:"), fg="blue"), comboX, sticky="w")
tkgrid(comboXFrame, sticky="w", column=1, row=2, columnspan=1)
tkgrid(labelRcmdr(confidenceFrame, text=gettextRcmdr("Confidence Level"), fg="blue"),sticky="w")
tkgrid(confidenceField, sticky="w")
tkgrid(confidenceFrame, labelRcmdr(optionsFrame, text=" "),sticky="nw")
tkgrid(optionsFrame, column=1, row=3, columnspan=2, sticky="nw")
tkgrid(buttonsFrame, column=1, row=4, columnspan=2, sticky="w")
dialogSuffix(rows=4, columns=2)
}
linePlotNMBU <- function(){
initializeDialog(title=gettextRcmdr("Line and point plot"))
variablesFrame <- tkframe(top)
.numeric <- Numeric()
.variable <- Variables()
xBox <- variableListBox(variablesFrame, .numeric, title=gettextRcmdr("x variable (pick one)"))
yBox <- variableListBox(variablesFrame, .numeric, title=gettextRcmdr("y variables (pick one or more)"),
selectmode="multiple", initialSelection=NULL)
zBox <- variableListBox(variablesFrame, .variable, title=gettextRcmdr("Groups (optional)"))
axisLabelVariable <- tclVar(gettextRcmdr("<use y-variable names>"))
axisLabelFrame <- tkframe(top)
axisLabelEntry <- ttkentry(axisLabelFrame, width="40", textvariable=axisLabelVariable)
axisLabelScroll <- ttkscrollbar(axisLabelFrame, orient="horizontal",
command=function(...) tkxview(axisLabelEntry, ...))
tkconfigure(axisLabelEntry, xscrollcommand=function(...) tkset(axisLabelScroll, ...))
legendFrame <- tkframe(top)
legendVariable <- tclVar("0")
legendCheckBox <- tkcheckbutton(legendFrame, variable=legendVariable)
onOK <- function(){
z <- getSelection(zBox)
y <- getSelection(yBox)
x <- getSelection(xBox)
lineType <- as.character(tclvalue(lineTypeVariable))
closeDialog()
if (0 == length(x)) {
errorCondition(recall=linePlotNMBU, message=gettextRcmdr("No x variable selected."))
return()
}
if (0 == length(y)) {
errorCondition(recall=linePlotNMBU, message=gettextRcmdr("No y variables selected."))
return()
}
if (1 < length(y) && length(z) == 1) {
errorCondition(recall=linePlotNMBU, message=gettextRcmdr("Only one y variable can be plotted with groups."))
return()
}
if (is.element(x, y)) {
errorCondition(recall=linePlotNMBU, message=gettextRcmdr("x and y variables must be different."))
return()
}
.activeDataSet <- ActiveDataSet()
.x <- na.omit(eval(parse(text=paste(.activeDataSet, "$", x, sep="")), envir=.GlobalEnv))
if (!identical(order(.x), seq(along.with=.x)) && length(z)==0){
response <- tclvalue(RcmdrTkmessageBox(message=gettextRcmdr("x-values are not in order.\nContinue?"),
icon="warning", type="okcancel", default="cancel"))
if (response == "cancel") {
onCancel()
return()
}
}
axisLabel <- tclvalue(axisLabelVariable)
legend <- tclvalue(legendVariable) == "1"
if (axisLabel == gettextRcmdr("<use y-variable names>")){
axisLabel <- if (legend && length(z)==0) ""
else if(length(y) == 1) y
else paste(paste("(", 1:length(y), ") ", y, sep=""), collapse=", ")
}
pch <- if (length(y) == 1) ", pch=1" else ""
if (legend && length(y) > 1){
mar <- par("mar")
top <- 3.5 + length(y)
command <- paste(".mar <- par(mar=c(", mar[1], ",", mar[2], ",", top, ",", mar[4], "))", sep="")
logger(command)
justDoIt(command)
}
if(length(z)==0){
command <- paste("matplot(", .activeDataSet, "$", x, ", ", .activeDataSet, "[, ",
paste("c(", paste(paste('"', y, '"', sep=""), collapse=","), ")", sep=""),
'], type="',lineType,'", lty=1:',length(y),', ylab="', axisLabel, '"', pch, ")", sep="")
logger(command)
justDoIt(command)
} else {
doItAndPrint(paste("plotByGroups(x.name='",x,"', y.name='",y,"', z.name='",z,"', lineType='",lineType,"', axisLabel='",axisLabel,"', legend=", legend, ")", sep=""))
}
if (legend && length(y) > 1){
n <- length(y)
cols <- rep(1:6, 1 + n %/% 6)[1:n]
logger(".xpd <- par(xpd=TRUE)")
justDoIt(".xpd <- par(xpd=TRUE)")
usr <- par("usr")
command <- paste("legend(", usr[1], ", ", usr[4] + 1.2*top*strheight("x"), ", legend=",
paste("c(", paste(paste('"', y, '"', sep=""), collapse=","), ")", sep=""),
", col=c(", paste(cols, collapse=","), "), lty=1:",length(y),", pch=c(",
paste(paste('"', as.character(1:n), '"', sep=""), collapse=","), "))", sep="")
logger(command)
justDoIt(command)
logger("par(mar=.mar)")
justDoIt("par(mar=.mar)")
logger("par(xpd=.xpd)")
justDoIt("par(xpd=.xpd)")
}
activateMenus()
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject="matplot")
radioButtons(name="lineType",
buttons=c("b", "l", "p"),
values=c("b", "l", "p"), initialValue="b",
labels=gettextRcmdr(c("Lines and points", "Lines", "Points")), title=gettextRcmdr("Plot type"))
tkgrid(getFrame(xBox), labelRcmdr(variablesFrame, text=" "), getFrame(yBox), labelRcmdr(variablesFrame, text=" "), getFrame(zBox), sticky="nw")
tkgrid(variablesFrame, sticky="nw", row=1, column=1, columnspan=2)
tkgrid(labelRcmdr(axisLabelFrame, text=gettextRcmdr("Label for y-axis"), fg="blue"), sticky="w")
tkgrid(axisLabelEntry, sticky="w")
tkgrid(axisLabelScroll, sticky="ew")
tkgrid(axisLabelFrame, sticky="w", row=2, column=1, columnspan=2)
tkgrid(labelRcmdr(legendFrame, text=gettextRcmdr("Plot legend")),
legendCheckBox, sticky="w")
tkgrid(lineTypeFrame, sticky="w", row=3, column=1, columnspan=1)
tkgrid(legendFrame, sticky="w", row=3, column=2, columnspan=1)
tkgrid(buttonsFrame, stick="w", row=4, column=1, columnspan=2)
dialogSuffix(rows=4, columns=2)
}
simplexGUI <- function(){
initializeDialog(title=gettextRcmdr("Plot points in three component mixture designs"))
.numeric <- Numeric()
comboVar <- tclVar()
comboFrame <- tkframe(top)
comboVar2 <- tclVar()
comboFrame2 <- tkframe(top)
formatFrame <- tkframe(top)
zoomFrame <- tkframe(top)
variablesFrame <- tkframe(top)
x1Box <- variableListBox(variablesFrame, .numeric, title=gettextRcmdr("Left variable (pick one)"))
x2Box <- variableListBox(variablesFrame, .numeric, title=gettextRcmdr("Top variable (pick one)"))
x3Box <- variableListBox(variablesFrame, .numeric, title=gettextRcmdr("Right variable (pick one)"))
onOK <- function(){
x1 <- getSelection(x1Box)
x2 <- getSelection(x2Box)
x3 <- getSelection(x3Box)
mix.format <- as.character(tclvalue(label.formatVariable))
zoomed <- tclvalue(zoomedVariable)
if(zoomed == gettextRcmdr("1")){
zoomed <- "TRUE"
} else {
zoomed <- "FALSE"
}
n.ticks <- which(as.character(2:10)==tclvalue(comboVar))+1
if(length(n.ticks)==0) n.ticks <- "6"
n.grade <- which(as.character(seq(5,25,5))==tclvalue(comboVar2))*5
if(length(n.grade)==0) n.grade <- "15"
closeDialog()
.activeDataSet <- ActiveDataSet()
formula1 <- justDoIt(paste("formula(~ ",x1," + ",x2," + ",x3, ")", sep=""))
doItAndPrint(paste("mixture.contour(", .activeDataSet, ", ", paste(formula1[1],formula1[2],sep=" "), ", n.tick=", n.ticks, ", n.grade=", n.grade,", mix.format='",mix.format,"', show.points=TRUE, show.contour=FALSE, zoomed=",zoomed,", pch=21, cex=1.25, col.points='black', fill.points='white')", sep=""))
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject="plot")
tkgrid(getFrame(x1Box), labelRcmdr(variablesFrame, text=" "), getFrame(x2Box), labelRcmdr(variablesFrame, text=" "), getFrame(x3Box), sticky="nw")
tkgrid(variablesFrame, sticky="nw", row=1, column=1, columnspan=2)
combo <- ttkcombobox(comboFrame, values=as.character(2:10), textvariable=comboVar, width=3)
combo2 <- ttkcombobox(comboFrame2, values=as.character(seq(5,25,5)), textvariable=comboVar2, width=3)
tkgrid(labelRcmdr(comboFrame, text=gettextRcmdr("Plot ticks (default=6):")), combo, sticky="w")
tkgrid(labelRcmdr(comboFrame2, text=gettextRcmdr("Plot gradings (approximate, default=15):")), combo2, sticky="w")
tkgrid(comboFrame, sticky="w", column=1, row=2, columnspan=1)
tkgrid(comboFrame2, sticky="w", column=1, row=3, columnspan=1)
radioButtonsNMBU(formatFrame,name="label.format", buttons=c("frac", "dec"), values=c("frac", "dec"), initialValue = "frac",
labels=gettextRcmdr(c("Fraction", "Decimal")))
tkgrid(formatFrame, row=4, column=1, columnspan=1, rowspan=1, sticky="w")
checkBoxes(frame="zoomFrame", boxes=c("zoomed"), initialValues=c("0"), labels=gettextRcmdr(c("Zoom on samples")))
tkgrid(zoomFrame, row=5, column=1, columnspan=1, rowspan=1, sticky="w")
tkgrid(buttonsFrame, sticky="w", row=6, column=1, columnspan=1)
dialogSuffix(rows=6, columns=1)
}
histogram_discrete <- function () {
defaults <- list(initial.x = NULL, initial.scale = "frequency",
initial.bins = gettextRcmdr ("<auto>"), initial.discrete = "0")
dialog.values <- getDialog("histogram_discrete", defaults)
initializeDialog(title = gettextRcmdr("Histogram"))
xBox <- variableListBox(top, Numeric(), title = gettextRcmdr("Variable (pick one)"),
initialSelection = varPosn (dialog.values$initial.x, "numeric"))
discreteFrame <- tkframe(top)
comboVar <- tclVar()
values <- c("normal", "exponential", "gamma", "geometric", "log-normal", "lognormal", "logistic", "negative binomial", "Poisson", "t", "weibull")
comboFrame <- tkframe(top)
onOK <- function() {
x <- getSelection(xBox)
discrete <- tclvalue(discreteVariable)
closeDialog()
if (length(x) == 0) {
errorCondition(recall = histogram_discrete, message = gettextRcmdr("You must select a variable"))
return()
}
fitDens <- tclvalue(comboVar)
bins <- tclvalue(binsVariable)
opts <- options(warn = -1)
binstext <- if (bins == gettextRcmdr("<auto>"))
"\"Sturges\""
else as.numeric(bins)
options(opts)
scale <- tclvalue(scaleVariable)
putDialog ("histogram_discrete", list (initial.x = x, initial.bins = bins, initial.scale = scale, initial.discrete=discrete))
if(discrete == gettextRcmdr("0")){
command <- paste("Hist(", ActiveDataSet(), "$", x, ", scale=\"",
scale, "\", breaks=", binstext, ", col=\"darkgray\", xlab='", x, "')",
sep = "")
doItAndPrint(command)
if(fitDens %in% values){
if(scale=="density"){
command <- paste("plotFitDens(", ActiveDataSet(), "$", x, ", '", fitDens, "')", sep="")
} else {
eval(parse(text=paste("tmp <- hist(", ActiveDataSet(), "$", x, ", breaks=", binstext, ", plot=FALSE)", sep="")))
scaling <- max(tmp$counts)/max(tmp$density)
command <- paste("plotFitDens(", ActiveDataSet(), "$", x, ", '", fitDens, "', scaling=", scaling, ")", sep="")
}
doItAndPrint(command)
}
} else {
if(fitDens %in% values)
errorCondition(recall = histogram_discrete, message = gettextRcmdr("'Density fit' not available for 'Discrete variable'"))
command <- paste("barplot(.tmp, col=\"darkgray\", space=0, xlab='", x, "',",
sep = "")
doItAndPrint(paste(".tmp <- table(factor(", ActiveDataSet(), "$", x, "))",sep=""))
if(scale=="percent"){
doItAndPrint(paste(".tmp <- .tmp/sum(.tmp)*100",sep=""))
command <- paste(command, "ylab='percent')")
} else {
if(scale=="density"){
doItAndPrint(paste(".tmp <- .tmp/sum(.tmp)",sep=""))
command <- paste(command, "ylab='density')")
} else {
command <- paste(command, "ylab='frequency')")
}
}
doItAndPrint(command)
doItAndPrint("rm(.tmp)")
}
activateMenus()
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject = "Hist", reset = "Histogram")
radioButtons(name = "scale", buttons = c("frequency", "percent",
"density"), labels = gettextRcmdr(c("Frequency counts",
"Percentages", "Densities")), title = gettextRcmdr("Axis Scaling"),
initialValue = dialog.values$initial.scale)
binsFrame <- tkframe(top)
binsVariable <- tclVar(dialog.values$initial.bins)
binsField <- ttkentry(binsFrame, width = "8", textvariable = binsVariable)
tkgrid(getFrame(xBox), sticky = "nw")
tkgrid(labelRcmdr(binsFrame, text = gettextRcmdr("Number of bins: ")),
binsField, sticky = "w")
tkgrid(binsFrame, sticky = "w")
tkgrid(scaleFrame, sticky = "w")
checkBoxes(frame="discreteFrame", boxes=c("discrete"), initialValues=dialog.values$initial.discrete, labels=gettextRcmdr(c("Discrete variable")))
tkgrid(discreteFrame, sticky="w")
combo <- ttkcombobox(comboFrame, values=values, textvariable=comboVar)
tkgrid(labelRcmdr(comboFrame, text=gettextRcmdr("Density fit:")), combo, sticky="w")
tkgrid(comboFrame, sticky="w")
tkgrid(buttonsFrame, sticky = "w")
tkgrid.configure(binsField, sticky = "e")
dialogSuffix(rows = 5, columns = 1)
}
boxPlotNMBU <- function () {
defaults <- list(initial.x = NULL, initial.identifyPoints = 0, initialGroup=NULL, initial.means = 0)
dialog.values <- getDialog("boxPlot", defaults)
initializeDialog(title = gettextRcmdr("Boxplot"))
xBox <- variableListBox(top, Numeric(), title = gettextRcmdr("Variable (pick one)"),
initialSelection = varPosn (dialog.values$initial.x, "numeric"))
identifyVariable <- tclVar(dialog.values$initial.identifyPoints)
identifyFrame <- tkframe(top)
identifyCheckBox <- tkcheckbutton(identifyFrame, variable = identifyVariable)
initial.group <- dialog.values$initial.group
.groups <- if (is.null(initial.group)) FALSE else initial.group
onOK <- function() {
x <- getSelection(xBox)
identifyPoints <- "1" == tclvalue(identifyVariable)
means <- tclvalue(meansVariable)
putDialog ("boxPlot", list(initial.x = x, initial.identifyPoints = identifyPoints,
initial.group=if (.groups == FALSE) NULL else .groups, initial.means = "1"==means))
closeDialog()
if (length(x) == 0) {
errorCondition(recall = boxPlotNMBU, message = gettextRcmdr("You must select a variable"))
return()
}
.activeDataSet <- ActiveDataSet()
var <- paste(.activeDataSet, "$", x, sep = "")
if (is.null(.groups) || .groups == FALSE) {
command <- (paste("boxplot(", var, ", ylab=\"", x,
"\")", sep = ""))
logger(command)
justDoIt(command)
if(means=="1")
doItAndPrint(paste("points(1, mean(", var, ", na.rm=TRUE), pch=4)", sep=""))
if (identifyPoints) {
RcmdrTkmessageBox(title = "Identify Points",
message = paste(gettextRcmdr("Use left mouse button to identify points,\n"),
gettextRcmdr(if (MacOSXP())
"esc key to exit."
else "right button to exit."), sep = ""),
icon = "info", type = "ok")
doItAndPrint(paste("identify(rep(1, length(",
var, ")), ", var, ", rownames(", .activeDataSet,
"))", sep = ""))
}
}
else {
command <- (paste("boxplot(", x, "~", .groups, ", ylab=\"",
x, "\", xlab=\"", .groups, "\"", ", data=", .activeDataSet,
")", sep = ""))
logger(command)
justDoIt(command)
if(means=="1")
doItAndPrint(paste("points(1:length(levels(",ActiveDataSet(),"$",.groups,")), tapply(", var, ", ", ActiveDataSet(), "$", .groups, ", mean, na.rm=TRUE), pch=4)", sep=""))
if (identifyPoints) {
RcmdrTkmessageBox(title = "Identify Points",
message = paste(gettextRcmdr("Use left mouse button to identify points,\n"),
gettextRcmdr(if (MacOSXP())
"esc key to exit."
else "right button to exit."), sep = ""),
icon = "info", type = "ok")
doItAndPrint(paste("identify(", .activeDataSet,
"$", .groups, ", ", var, ", rownames(", .activeDataSet,
"))", sep = ""))
}
}
activateMenus()
tkfocus(CommanderWindow())
}
groupsBox(boxPlot, initialGroup=initial.group,
initialLabel=if (is.null(initial.group)) gettextRcmdr("Plot by groups") else paste(gettextRcmdr("Plot by:"), initial.group))
OKCancelHelp(helpSubject = "boxplot", reset = "boxPlotNMBU")
tkgrid(getFrame(xBox), sticky = "nw")
tkgrid(labelRcmdr(identifyFrame, text = gettextRcmdr("Identify outliers with mouse"),
justify = "left"), identifyCheckBox, sticky = "w")
tkgrid(identifyFrame, stick = "w")
meansFrame <- tkframe(top)
checkBoxes(frame="meansFrame", boxes=c("means"), initialValues=dialog.values$initial.means, labels=gettextRcmdr(c("Plot mean value(s)")))
tkgrid(meansFrame, sticky="w")
tkgrid(groupsFrame, sticky = "w")
tkgrid(buttonsFrame, sticky = "w")
dialogSuffix(rows = 4, columns = 1)
}
|
X <- model.matrix(model); X
|
gridPointsFitError <- function(p, nx, points, ny=NULL) mean(sqrt((points - gridPointsFit(p, nx, ny))^2))
|
shade.poi.tck<-function(){
local({
have_ttk <- as.character(tcl("info", "tclversion")) >= "8.5"
if(have_ttk) {
tkbutton <- ttkbutton
tkcheckbutton <- ttkcheckbutton
tkentry <- ttkentry
tkframe <- ttkframe
tklabel <- ttklabel
tkradiobutton <- ttkradiobutton
}
tclServiceMode(FALSE)
dialog.sd <- function(){
tt <- tktoplevel()
tkwm.title(tt,"Depiction of binomial probability")
x.entry <- tkentry(tt, textvariable=X, width = 10)
lambda.entry<-tkentry(tt, textvariable=Lambda, width = 10)
from.entry<-tkentry(tt, textvariable=From, width =10)
to.entry<-tkentry(tt, textvariable=To, width = 10)
Tail.par<-tclVar("X=x")
done <- tclVar(0)
show.p<-tclVar(1)
show.d<-tclVar(0)
show.dist<-tclVar(1)
reset <- function()
{
tclvalue(X)<-"1"
tclvalue(Lambda)<-"5"
tclvalue(From)<-""
tclvalue(To)<-""
tclvalue(show.p)<-"1"
tclvalue(show.d)<-"0"
tclvalue(show.dist)<-"1"
}
reset.but <- tkbutton(tt, text="Reset", command=reset)
submit.but <- tkbutton(tt, text="Submit",command=function()tclvalue(done)<-1)
build <- function()
{
x <- tclvalue(X)
lambda <-tclvalue(Lambda)
from <-tclvalue(From)
to<-tclvalue(To)
tail<-tclvalue(Tail.par)
show.p <- as.logical(tclObj(show.p))
show.d <- as.logical(tclObj(show.d))
show.dist <- as.logical(tclObj(show.dist))
substitute(shade.poi(x=as.numeric(x),lambda=as.numeric(lambda), from = as.numeric(from), to=as.numeric(to),tail=tail,show.p=show.p,show.d=show.d,show.dist=show.dist))
}
p.cbut <- tkcheckbutton(tt, text="Show probability", variable=show.p)
d.cbut <- tkcheckbutton(tt, text="Show density", variable=show.d)
dist.cbut <- tkcheckbutton(tt, text="Show distribution", variable=show.dist)
tkgrid(tklabel(tt,text="Poisson probability"),columnspan=2)
tkgrid(tklabel(tt,text=""))
tkgrid(tklabel(tt,text="x",font=c("Helvetica","9","italic")), x.entry)
tkgrid(tklabel(tt,text='\u03bb', font=c("Helvetica","9","italic")), lambda.entry)
tkgrid(tklabel(tt,text=""))
alt.rbuts <- tkframe(tt)
tkpack(tklabel(alt.rbuts, text="Tail"))
for ( i in c("X=x","lower","upper","two","middle")){
tmp <- tkradiobutton(alt.rbuts, text=i, variable=Tail.par, value=i)
tkpack(tmp,anchor="w")
}
tkgrid(alt.rbuts)
tkgrid(tklabel(tt,text=""))
tkgrid(tklabel(tt,text="Middle 'tail' span"))
tkgrid(tklabel(tt,text="From"),from.entry)
tkgrid(tklabel(tt,text="To"),to.entry)
tkgrid(tklabel(tt,text=""))
tkgrid(p.cbut,sticky="w", columnspan=2)
tkgrid(d.cbut,sticky="w", columnspan=2)
tkgrid(dist.cbut,sticky="w", columnspan=2)
tkgrid(tklabel(tt,text=""))
tkgrid(submit.but,reset.but, sticky ="w")
tkbind(tt, "<Destroy>", function()tclvalue(done)<-2)
tkwait.variable(done)
if(tclvalue(done)=="2") stop("aborted")
tkdestroy(tt)
cmd <- build()
eval.parent(cmd)
tclServiceMode(FALSE)
}
X<-tclVar("1")
Lambda<-tclVar("5")
Tail<-tclVar("X=x")
From<-tclVar("")
To<-tclVar("")
dialog.sd()
})
}
|
hash_e <-
function(x, mode.out = "numeric") {
hash_help_e(x, mode.out = mode.out)
}
hash_help_e <- function(x, mode.out) {
if (is.factor(x[, 2])) {
x[, 2] <- as.character(x[, 2])
FUN <- as.factor
} else {
FUN <- match.fun(paste0("as.", mode(x[, 2])))
}
evnt <- new.env(hash = TRUE, size = nrow(x),
parent = emptyenv())
outmode <- match.fun(paste0("as.", mode.out))
apply(x, 1, function(col) {
assign(col[1], outmode(col[2]), envir = evnt)
})
class(evnt) <- c("qdap_hash", "evir", class(evnt))
attributes(evnt)[["mode"]] <- FUN
evnt
}
hash_look_e <- function(terms, envir, missing = NA) {
hits <- which(!is.na(match(terms, names(as.list(envir)))))
x <- rep(ifelse(is.null(missing), NA, missing), length(terms))
x[hits] <- recoder(terms[hits], envr = envir)
if (is.null(missing)) {
keeps <- which(is.na(x))
x[keeps] <- terms[keeps]
x
}
x
}
recoder <- function(x, envr){
x <- as.character(x)
unlist(lapply(x, get, envir = envr))
}
|
predict.MFA <- function(object, newdata, ...){
ec <- function(V, poids) {
res <- sqrt(sum(V^2 * poids,na.rm=TRUE)/sum(poids[!is.na(V)]))
}
if (!is.null(object$quanti.var$coord)) ncp=ncol(object$quanti.var$coord)
else ncp=ncol(object$quali.var$coord)
tab.supp=matrix(NA,nrow(newdata),0)
for (g in 1:length(object$call$group)){
if (object$call$nature.group[g]=="quanti"){
tab.aux <- t(t(newdata[,(c(1,1+cumsum(object$call$group))[g]):cumsum(object$call$group)[g]]) - object$separate.analyses[[g]][["call"]]$centre)
tab.aux <- t(t(tab.aux) / object$separate.analyses[[g]][["call"]]$ecart.type)
tab.supp <- cbind(tab.supp,as.matrix(tab.aux))
} else {
tab.disj <- tab.disjonctif(object$separate.analyses[[g]][["call"]]$X)
tab.disj.supp <- tab.disjonctif(rbind.data.frame(object$separate.analyses[[g]][["call"]]$X[1:2,],newdata[,(c(1,1+cumsum(object$call$group))[g]):cumsum(object$call$group)[g]])[-(1:2),,drop=FALSE])
if (!is.null(object$call$row.w.init)) SomRow <- sum(object$call$row.w.init)
else SomRow <- length(object$call$row.w)
M <- object$separate.analyses[[g]]$call$marge.col/SomRow
Z <- t(t(tab.disj/SomRow)-M*2)
Zsup <- t(t(tab.disj.supp/SomRow) - M*2)
Zsup <- t(t(Zsup) / apply(Z,2,ec,object$global.pca$call$row.w.init))
tab.supp <- cbind(as.matrix(tab.supp),Zsup)
}
}
tab.supp <- sweep(tab.supp,2,sqrt(object$call$col.w),FUN="*")
coord <- crossprod(t(tab.supp),object$global.pca$svd$V*sqrt(object$call$col.w))
dist2 <- rowSums(tab.supp^2)
cos2 <- (coord)^2/dist2
coord <- coord[, 1:ncp, drop = FALSE]
cos2 <- cos2[, 1:ncp, drop = FALSE]
colnames(coord) <- colnames(cos2) <- paste("Dim", c(1:ncp), sep = ".")
rownames(coord) <- rownames(cos2) <- names(dist2) <- rownames(newdata)
result <- list(coord = coord, cos2 = cos2, dist = sqrt(dist2))
}
|
hypothesize <- function(x, null, p = NULL, mu = NULL, med = NULL, sigma = NULL) {
null <- match_null_hypothesis(null)
hypothesize_checks(x, null)
attr(x, "null") <- null
attr(x, "hypothesized") <- TRUE
dots <- compact(list(p = p, mu = mu, med = med, sigma = sigma))
switch(
null,
independence = {
params <- sanitize_hypothesis_params_independence(dots)
attr(x, "type") <- "permute"
},
point = {
params <- sanitize_hypothesis_params_point(dots, x)
attr(x, "params") <- unlist(params)
if (!is.null(params$p)) {
attr(x, "type") <- "draw"
} else {
if (is.factor(response_variable(x))) {
stop_glue(
'Testing one categorical variable requires `p` to be used as a ',
'parameter.'
)
}
attr(x, "type") <- "bootstrap"
}
}
)
res <- append_infer_class(tibble::as_tibble(x))
copy_attrs(to = res, from = x)
}
hypothesise <- hypothesize
hypothesize_checks <- function(x, null) {
if (!inherits(x, "data.frame")) {
stop_glue("x must be a data.frame or tibble")
}
if ((null == "independence") && !has_explanatory(x)) {
stop_glue(
'Please `specify()` an explanatory and a response variable when ',
'testing a null hypothesis of `"independence"`.'
)
}
}
match_null_hypothesis <- function(null) {
null_hypothesis_types <- c("point", "independence")
if(length(null) != 1) {
stop_glue('You should specify exactly one type of null hypothesis.')
}
i <- pmatch(null, null_hypothesis_types)
if(is.na(i)) {
stop_glue('`null` should be either "point" or "independence".')
}
null_hypothesis_types[i]
}
sanitize_hypothesis_params_independence <- function(dots) {
if (length(dots) > 0) {
warning_glue(
"Parameter values are not specified when testing that two variables are ",
"independent."
)
}
NULL
}
sanitize_hypothesis_params_point <- function(dots, x) {
if(length(dots) != 1) {
stop_glue("You must specify exactly one of `p`, `mu`, `med`, or `sigma`.")
}
if (!is.null(dots$p)) {
dots$p <- sanitize_hypothesis_params_proportion(dots$p, x)
}
dots
}
sanitize_hypothesis_params_proportion <- function(p, x) {
eps <- if (capabilities("long.double")) {sqrt(.Machine$double.eps)} else {0.01}
if(anyNA(p)) {
stop_glue('`p` should not contain missing values.')
}
if(any(p < 0 | p > 1)) {
stop_glue('`p` should only contain values between zero and one.')
}
if(length(p) == 1) {
if(!has_attr(x, "success")) {
stop_glue(
"A point null regarding a proportion requires that `success` ",
"be indicated in `specify()`."
)
}
p <- c(p, 1 - p)
names(p) <- get_success_then_response_levels(x)
} else {
if (sum(p) < 1 - eps | sum(p) > 1 + eps) {
stop_glue(
"Make sure the hypothesized values for the `p` parameters sum to 1. ",
"Please try again."
)
}
}
p
}
|
add_es <- function(eg,eg2,current_rank,ff=0,method=c("esm","isvd")){
if(method=="esm"){
if (missing("current_rank")) {
current_rank = length(eg$d)
}
out = add_eig(eg, eg2, current_rank)}
else{
if (is.null(eg$m)) {
m = dim(eg$u)[1]
}
else
{
m = eg$m
}
B = eg2
if (missing("current_rank")) {
current_rank = dim(B)[2]
}
out = add_svd(eg,B,m,current_rank,ff = ff)
}
return(out)
}
|
test_succeeds("multi_head_attention", {
if (tensorflow::tf_version() < "2.4")
skip("requires tf_version() >= 2.4")
layer <- layer_multi_head_attention(num_heads=2, key_dim=2, name = "hello")
target <- layer_input(shape=c(8, 16))
source <- layer_input(shape=c(4, 16))
expect_equal(layer$name, "hello")
c(output_tensor, weights) %<-% layer(target, source,return_attention_scores=TRUE)
expect_equal(output_tensor$shape$as_list(), list(NULL, 8, 16))
expect_equal(weights$shape$as_list(), list(NULL, 2, 8, 4))
})
|
test_that("works as expected", {
expect_equal( eq( c(NA,'NA',1,2,'c'), c(NA,NA,1,2,'a') ), c( TRUE, FALSE, TRUE, TRUE, FALSE ) )
expect_true( eq( NA, NULL ) )
expect_equal( eq( c('a', 'b'), c('a', 'b', 'c') ), FALSE)
})
|
Time2 = function(
x,
w,
thresh,
smallerthan = TRUE,
bout.length = 1
){
if(missing(w)){
stop("Please input weartime flag vector w with same dimension")
}
if(length(x) != length(w)){
stop("count x and weartime w should have the same length")
}
uwear = unique(c(w))
uwear = as.integer(uwear)
if (!all(uwear %in% c(0, 1, NA))) {
stop("weartime w has non 0-1 data")
}
x = na.omit(x)
w = na.omit(w)
w[w == 0] = NA
y = create.bouts(counts = x, thresh_lower = thresh, bout_length = bout.length)
yw = y * w
if(smallerthan){
time = sum(yw == 0, na.rm = T)
}
if(!smallerthan){
time = sum(yw == 1, na.rm = T)
}
return(time = time)
}
Time_long2 = function(
count.data,
weartime,
thresh,
smallerthan = TRUE,
bout.length = 1
){
n1440<-ncol(count.data)-2
n1441<- n1440+1
n1442<- n1440+2
n2880<- 2*n1440
minuteUnit<-n1440/1440
if(missing(weartime)){
print("No weartime supplied, calculated based on defualt from 05:00 to 23:00")
weartime = wear_flag(count.data = count.data)
} else {
if (length(which(count.data[,1]!= weartime[,1] | count.data[,2]!= weartime[,2]))>=1) stop ("Checking IDs between count.data and weartime in Time_long2 function.")
}
mat = cbind(as.matrix(count.data[,-c(1:2)]),as.matrix(weartime[,-c(1:2)]))
result.list = apply(mat,1,function(x){
Time2(x[1:n1440],x[n1441:n2880],thresh = thresh,bout.length = bout.length, smallerthan = smallerthan)
})
time_all = as.data.frame(cbind(count.data[,c(1,2)],result.list/minuteUnit))
names(time_all) = c("ID","Day","time")
return(time_all = time_all)
}
PAfun = function(count.data,weartime,PA.threshold=c(50,100,400)){
PA.threshold = c(PA.threshold,Inf)
sed_all0<-NULL
for (f in 1:length(PA.threshold)){
temp = Time_long2(count.data = count.data, weartime = weartime, thresh =PA.threshold[f], smallerthan = TRUE)
colnames(temp)[3]<-paste(colnames(temp)[3],PA.threshold[f],sep="")
if (f==1) sed_all0<-temp else {
if (length(which(sed_all0[,1]!=temp[,1]))>=1 | length(which(sed_all0[,2]!=temp[,2]))>=1) stop("check ID+Day in Time_long2 function")
sed_all0<-cbind(sed_all0,temp[,3])
}
}
sed_all<-sed_all0
for (j in 4:6) sed_all[,j]<-sed_all0[,j]-sed_all0[,j-1]
colnames(sed_all)[3:6]<-c("sed_dur","light_dur","mod_dur","vig_dur")
sed_all[,"MVPA_dur"]<-sed_all[,"mod_dur"] + sed_all[,"vig_dur"]
sed_all[,"activity_dur"]<-sed_all[,"light_dur"] +sed_all[,"mod_dur"] + sed_all[,"vig_dur"]
minuteNcol=(ncol(count.data)-2)/1440
for (j in 4:ncol(sed_all)) sed_all[,j]<-sed_all[,j]/minuteNcol
return(sed_all)
}
create.bouts<-function(counts, thresh_lower, bout_length = 1){
S1<-which(counts>=thresh_lower)
S0<-which(counts<thresh_lower)
bouts<-rep(NA,length(counts))
bouts[S1]<-1
bouts[S0]<-0
if (bout_length>1){
for (i in 2:length(S0)){
W<-S0[i]-S0[i-1]
if (W-1<bout_length) bouts[ S0[i-1]:S0[i] ]<-0
}
}
return(bouts)
}
|
sde.sim <- function (t0 = 0, T = 1, X0 = 1, N = 100, delta, drift, sigma,
drift.x, sigma.x, drift.xx, sigma.xx, drift.t, method = c("euler",
"milstein", "KPS", "milstein2", "cdist","ozaki","shoji","EA"),
alpha = 0.5, eta = 0.5, pred.corr = T, rcdist = NULL, theta = NULL,
model = c("CIR", "VAS", "OU", "BS"),
k1, k2, phi, max.psi = 1000, rh, A, M=1)
{
method <- match.arg(method)
if(!missing(model)){
model <- match.arg(model)
method <- "model"
}
x0 <- rep(X0,M)[1:M]
if (missing(drift)){
if (method == "cdist" || !missing(model))
drift <- expression(NULL)
else
stop("please specify al least the drift coefficient of the SDE")
}
if (missing(sigma))
sigma <- expression(1)
if (!is.expression(drift) || !is.expression(sigma))
stop("coefficients must be expressions in `t' and `x'")
if (pred.corr == F) {
alpha <- 0
eta <- 0
sigma.x <- NULL
}
needs.sx <- FALSE
needs.dx <- FALSE
needs.sxx <- FALSE
needs.dxx <- FALSE
needs.dt <- FALSE
if (method == "cdist" && is.null(rcdist))
stop("please provide a random number generator `rcdist'")
if (method == "milstein")
needs.sx = TRUE
if ((method == "euler" && pred.corr == T))
needs.sx = TRUE
if (method == "KPS" || method == "milstein2") {
needs.sx <- TRUE
needs.dx <- TRUE
needs.sxx <- TRUE
needs.dxx <- TRUE
}
if(method == "ozaki" || method == "shoji" || method == "EA")
needs.dx <- TRUE
if(method == "shoji"){
needs.dxx <- TRUE
needs.dt <- TRUE
}
if (needs.sx && missing(sigma.x)) {
message("sigma.x not provided, attempting symbolic derivation.\n")
sigma.x <- D(sigma, "x")
}
if (needs.dx && missing(drift.x)) {
message("drift.x not provided, attempting symbolic derivation.\n")
drift.x <- D(drift, "x")
}
if (needs.dxx && missing(drift.xx)) {
message("drift.xx not provided, attempting symbolic derivation.\n")
drift.xx <- D(D(drift, "x"), "x")
}
if (needs.sxx && missing(sigma.xx)) {
message("sigma.xx not provided, attempting symbolic derivation.\n")
sigma.xx <- D(D(sigma, "x"), "x")
}
if (needs.dt && missing(drift.t)) {
message("drift.t not provided, attempting symbolic derivation.\n")
drift.t <- D(drift, "t")
}
d1 <- function(t, x) eval(drift)
d1.x <- function(t, x) eval(drift.x)
d1.xx <- function(t, x) eval(drift.x)
d1.t <- function(t, x) eval(drift.t)
s1 <- function(t, x) eval(sigma)
s1.x <- function(t, x) eval(sigma.x)
s1.xx <- function(t, x) eval(sigma.xx)
if (t0 < 0 || T < 0)
stop("please use positive times!")
if (missing(delta)) {
t <- seq(t0, T, length = N + 1)
}
else {
t <- c(t0, t0 + cumsum(rep(delta, N)))
T <- t[N + 1]
message(sprintf("\nT set to = %f\n", T))
}
Dt <- (T - t0)/N
if(method == "model"){
if(is.null(theta))
stop("please provide a vector of parameters for the model")
if(model == "CIR")
X <- sde.sim.cdist(x0, t0, Dt, N, M, rcCIR, theta)
if(model == "OU")
X <- sde.sim.cdist(x0, t0, Dt, N, M, rcOU, theta)
if(model == "BS")
X <- sde.sim.cdist(x0, t0, Dt, N, M, rcBS, theta)
}
if (method == "EA")
X <- sde.sim.ea(X0, t0, Dt, N, d1, d1.x, k1, k2, phi, max.psi, rh, A)
if (method == "cdist"){
if(is.null(theta))
stop("please provide a vector of parameters for `rcdist'")
else
X <- sde.sim.cdist(x0, t0, Dt, N, M, rcdist, theta)
}
if (method == "ozaki"){
vd <- all.vars(drift)
vs <- all.vars(sigma)
if((length(vd)!=1) || (length(vs)>0))
stop("drift must depend on `x' and volatility must be constant")
if((length(vd) == 1) && (vd != "x"))
stop("drift must depend on `x'")
X <- sde.sim.ozaki(x0, t0, Dt, N, M, d1, d1.x, s1)
}
if (method == "shoji"){
vd <- all.vars(drift)
vs <- all.vars(sigma)
if(length(vd)>2 || length(vd)<1 || length(vs)>0)
stop("drift must depend on `x' and/or `t' and volatility must be constant")
if((length(vd) == 1) && (vd != "x"))
stop("drift must depend at least on `x'")
X <- sde.sim.shoji(x0, t0, Dt, N, M, d1, d1.x, d1.xx, d1.t, s1)
}
if (method == "euler")
X <- sde.sim.euler(x0, t0, Dt, N, M, d1, s1, s1.x, alpha,
eta, pred.corr)
if (method == "milstein")
X <- sde.sim.milstein(x0, t0, Dt, N, M, d1, s1, s1.x)
if (method == "milstein2")
X <- sde.sim.milstein2(x0, t0, Dt, N, M, d1, d1.x, d1.xx,
s1, s1.x, s1.xx)
if (method == "KPS") {
Sigma <- matrix(c(Dt, 0.5 * Dt^2, 0.5 * Dt^2, 1/3 * Dt^3),
2, 2)
tmp <- mvrnorm(N*M, c(0, 0), Sigma)
Z <- tmp[, 1]
U <- tmp[, 2]
X <- sde.sim.KPS(x0, t0, Dt, N, M, d1, d1.x, d1.xx, s1,
s1.x, s1.xx, Z, U)
}
nm <- "X"
nm <- if(M>1)
paste("X",1:M,sep="")
X <- ts(X, start = t0, deltat = Dt, names=nm)
invisible(X)
}
|
| pacman Function | Base Equivalent | Description |
|----------------------|----------------------|----------------|
| `p_detectOS` | `Sys.info` | Detect Operating System |
| `p_extract` | NONE | Extract Packages from String |
| `p_opendir` | `system`/`shell` | Open a Directory |
|
makeControl <- function (f = list(~1), S = list(0, 0, 1), period = 52,
offset = 1, ...)
{
control <- mapply(function (f, S, period, offset) {
f <- addSeason2formula(f = f, S = S, period = period)
list(f = f, offset = offset)
}, f, S, period, offset, SIMPLIFY = FALSE, USE.NAMES = FALSE)
names(control) <- c("ar", "ne", "end")
control$family <- "NegBin1"
modifyList(control, list(...))
}
|
update_dollar_data <- function(ctl_name, new_data_name) {
if (is_single_na(ctl_name)) {
return(NA)
}
ctl <- ctl_character(ctl_name)
ctl <- gsub("^(\\s*\\$DATA\\s*)[^ ]+(.*)$", paste0("\\1", new_data_name, "\\2"), ctl)
ctl
}
nm_tran <- function(x) UseMethod("nm_tran")
nm_tran.default <- function(x) {
if (is.null(nm_tran_command())) stop("nm_tran not set up, see ?nm_tran_command")
tempdir0 <- basename(tempdir())
dir.create(tempdir0)
on.exit(unlink(tempdir0, recursive = TRUE, force = TRUE))
file.copy(x, tempdir0)
data_path <- file.path(dirname(x), data_name(x))
file.copy(data_path, tempdir0)
dataset.name <- basename(data_path)
suppressMessages({
ctl_text <- update_dollar_data(file.path(tempdir0, basename(x)), dataset.name)
write(ctl_text, file.path(tempdir0, basename(x)))
})
message("running NMTRAN on ", x)
nm_tran_command <- nm_tran_command()
cmd <- stringr::str_glue(nm_tran_command, .envir = list(ctl_name = basename(x)), .na = NULL)
if (cmd == nm_tran_command) cmd <- paste(cmd, "<", basename(x))
system_nm(cmd, dir = tempdir0, wait = TRUE)
}
nm_tran.nm_generic <- function(x) {
xtmp <- x %>% run_in(file.path(run_in(x), "temp"))
xtmp %>% write_ctl(force = TRUE)
nm_tran.default(ctl_path(xtmp))
invisible(x)
}
nm_tran.nm_list <- Vectorize_nm_list(nm_tran.nm_generic, SIMPLIFY = FALSE, invisible = TRUE)
|
get_PMCtable = function(url){
test = getURL(url)
test1 = htmlTreeParse(test,useInternalNodes = T)
test2 = lapply(getNodeSet(test1,"//tr"),function(x){(x)})
table=NULL;for (i in 3:length(test2)){table=rbind(table,getChildrenStrings(test2[[i]])) }
colnames(table)= as.character(getChildrenStrings(test2[[2]]))
return(table)}
|
TML.BetaW <- function(X,y,delta,Beta,sigma,Beta.t,sigma.t,cl,cu,maxit,tol,nitmon)
{
p <- length(Beta); n <- length(y); nu <- sum(delta); nc <- n-nu; zero <- 1e-6
nit <- 1; Beta1 <- rep(100,p)
indu <- (1:n)[delta==1]; indc <- (1:n)[delta==0]
mui.t <- X %*% as.matrix(Beta.t)
rs.t <- (y-mui.t)/sigma.t
wgt <- ww(rs.t, cl, cu)
while ( max(abs(Beta1-Beta)) > tol & (nit < maxit) ) {
D1 <- D2 <- ym <- rep(0,n); vi <- ti <- rep(0,nc)
nit <- nit+1; Beta1 <- Beta
mui <- X %*% as.matrix(Beta1)
rs <- (y-mui)/sigma
gi <- rep(1,nu)
if (nu > 0) {
ru <- rs[indu]
cnd <- ru != 0
gi[cnd] <- ps0(ru[cnd])/ru[cnd]
D1[indu] <- wgt[indu]*gi
D2[indu] <- wgt[indu]*gi
ym[indu] <- y[indu]}
if (nu < n) {
I1 <- I0 <- rep(0,nc)
rc <- rs[delta==0]
muic <- mui[indc]
muit <- mui.t[indc]
ai <- pmax( rc, (sigma.t*cl - muic + muit )/sigma )
bi <- (sigma.t*cu - muic + muit )/sigma
den <- 1-plweibul(rc)
ok <- den > zero
for (i in 1:nc) {
if (bi[i] > ai[i]) I0[i] <- integrate(intg0.TMLW,ai[i],bi[i])$val
if (bi[i] > ai[i]) I1[i] <- dlweibul(ai[i])-dlweibul(bi[i]) }
I1 <- sigma*I1+muic*I0
vi[ok] <- I0[ok]/den[ok]
ti[ok] <- I1[ok]/den[ok]
D1[indc] <- vi
D2[indc] <- ti
ym[indc] <- rep(1,nc)}
A <- t(X)%*%(D2*ym)
B <- t(X)%*%(D1*X)
Beta <- solve(B)%*%A
if(nitmon) cat(nit, Beta, Beta1, "\n")
}
list(Beta=Beta,nit=nit)
}
|
test_that("Test suite aap.R",{
expect_true(Hi*Hj == Hk)
expect_true(Hj*Hi == -Hk)
expect_true(Hj*Hk == Hi)
expect_true(Hk*Hj == -Hi)
expect_true(Hk*Hi == Hj)
expect_true(Hi*Hk == -Hj)
expect_true(Hi*Hi == -H1)
expect_true(Hj*Hj == -H1)
expect_true(Hk*Hk == -H1)
expect_true(H1*H1 == H1)
expect_true(H1*Hi == Hi)
expect_true(H1*Hj == Hj)
expect_true(H1*Hk == Hk)
expect_true(H1*H1 == H1)
expect_true(Hi*H1 == Hi)
expect_true(Hj*H1 == Hj)
expect_true(Hk*H1 == Hk)
expect_true(Hi*Hj*Hk == -H1)
expect_true(H0*H1 == H0)
expect_true(H0*Hi == H0)
expect_true(H0*Hj == H0)
expect_true(H0*Hk == H0)
expect_true(H1*H0 == H0)
expect_true(Hi*H0 == H0)
expect_true(Hj*H0 == H0)
expect_true(Hk*H0 == H0)
expect_true(H1 + Him == Hall)
expect_true(Hi + Hj + Hk == Him)
expect_true(H1 + Hi + Hj + Hk == Hall)
expect_true(Hi - Hi == H0)
expect_true(Hall - Hi - Hj - Hk == H1)
expect_true(Hall - Him == H1)
expect_true(O1*O1 == O1 )
expect_true(O1*Oi == Oi )
expect_true(O1*Oj == Oj )
expect_true(O1*Ok == Ok )
expect_true(O1*Ol == Ol )
expect_true(O1*Oil == Oil)
expect_true(O1*Ojl == Ojl)
expect_true(O1*Okl == Okl)
expect_true(Oi*O1 == Oi )
expect_true(Oi*Oi == -O1 )
expect_true(Oi*Oj == Ok )
expect_true(Oi*Ok == -Oj )
expect_true(Oi*Ol == Oil)
expect_true(Oi*Oil == -Ol )
expect_true(Oi*Ojl == -Okl)
expect_true(Oi*Okl == Ojl)
expect_true(Oj*O1 == Oj )
expect_true(Oj*Oi == -Ok )
expect_true(Oj*Oj == -O1 )
expect_true(Oj*Ok == Oi )
expect_true(Oj*Ol == Ojl)
expect_true(Oj*Oil == Okl)
expect_true(Oj*Ojl == -Ol )
expect_true(Oj*Okl == -Oil)
expect_true(Ok*O1 == Ok )
expect_true(Ok*Oi == Oj )
expect_true(Ok*Oj == -Oi )
expect_true(Ok*Ok == -O1 )
expect_true(Ok*Ol == Okl)
expect_true(Ok*Oil == -Ojl)
expect_true(Ok*Ojl == Oil)
expect_true(Ok*Okl == -Ol )
expect_true(Ol*O1 == Ol )
expect_true(Ol*Oi == -Oil)
expect_true(Ol*Oj == -Ojl)
expect_true(Ol*Ok == -Okl)
expect_true(Ol*Ol == -O1 )
expect_true(Ol*Oil == Oi )
expect_true(Ol*Ojl == Oj )
expect_true(Ol*Okl == Ok )
expect_true(Oil*O1 == Oil)
expect_true(Oil*Oi == Ol )
expect_true(Oil*Oj == -Okl)
expect_true(Oil*Ok == Ojl)
expect_true(Oil*Ol == -Oi )
expect_true(Oil*Oil == -O1 )
expect_true(Oil*Ojl == -Ok )
expect_true(Oil*Okl == Oj )
expect_true(Ojl*O1 == Ojl)
expect_true(Ojl*Oi == Okl)
expect_true(Ojl*Oj == Ol )
expect_true(Ojl*Ok == -Oil)
expect_true(Ojl*Ol == -Oj )
expect_true(Ojl*Oil == Ok )
expect_true(Ojl*Ojl == -O1 )
expect_true(Ojl*Okl == -Oi )
expect_true(Okl*O1 == Okl)
expect_true(Okl*Oi == -Ojl)
expect_true(Okl*Oj == Oil)
expect_true(Okl*Ok == Ol )
expect_true(Okl*Ol == -Ok )
expect_true(Okl*Oil == -Oj )
expect_true(Okl*Ojl == Oi )
expect_true(Okl*Okl == -O1 )
expect_true(O0*O0 == O0)
expect_true(O0*O1 == O0)
expect_true(O0*Oi == O0)
expect_true(O0*Oj == O0)
expect_true(O0*Ok == O0)
expect_true(O0*Ol == O0)
expect_true(O0*Oil == O0)
expect_true(O0*Ojl == O0)
expect_true(O0*Okl == O0)
expect_true(O1*O0 == O0)
expect_true(Oi*O0 == O0)
expect_true(Oj*O0 == O0)
expect_true(Ok*O0 == O0)
expect_true(Ol*O0 == O0)
expect_true(Oil*O0 == O0)
expect_true(Ojl*O0 == O0)
expect_true(Okl*O0 == O0)
expect_true(O1 + Oim == Oall)
expect_true(Oi + Oj + Ok + Ol + Oil + Ojl + Okl == Oim)
expect_true(O1 + Oi + Oj + Ok + Ol + Oil + Ojl + Okl == Oall)
expect_true(Oil - Oil == O0)
expect_true(Oall - Oim == O1)
expect_true(as.onion(1:4,single=TRUE)==1*H1 + 2*Hi + 3*Hj + 4*Hk)
expect_true(as.onion(1:8,single=TRUE)==1*O1 + 2*Oi + 3*Oj + 4*Ok + 5*Ol + 6*Oil + 7*Ojl + 8*Okl)
expect_error(as.onion(matrix(1:25,5,5)))
expect_true(is.quaternion(as.quaternion(rquat(4))))
expect_true(is.octonion(as.octonion(roct(4))))
expect_false(is.octonion(as.quaternion(rquat(4))))
expect_false(is.quaternion(as.octonion(roct(4))))
expect_true(is.quaternion(as.onion(1:4,matrix(rquat(1),2,2))))
expect_false(is.quaternion(as.onion(1:4,matrix(roct(1),2,2))))
expect_false(is.octonion(as.onion(1:4,matrix(rquat(1),2,2))))
expect_true(is.octonion(as.onion(1:4,matrix(roct(1),2,2))))
expect_true(is.onion(drop(matrix(Hi,1,3))))
expect_false(is.onionmat(drop(matrix(Hi,1,3))))
o <- as.onion(c(1,1e-20,1e-20,1e-20),single=TRUE)
expect_false(Im(o)==0)
expect_true(Im(zapsmall(o))==0)
o <- onionmat(o,2,2)
expect_false(all(Im(o)==0))
expect_true(all(Im(zapsmall(o))==0))
})
|
to.unbalanced <- function(data, id.col, times, Y.col, other.col = NA) {
if (length(id.col) > 1) {
stop("Only a single vector of subject identification is possible")
}
if (is.numeric(id.col)) {
pat <- data[, id.col]
} else {
pat <- data[[id.col]]
}
tm <- as.vector(times)
ltt <- length(tm)
if (!is.numeric(Y.col)) {
Y.col <- which(names(data) %in% Y.col)
}
Y.col <- as.vector(Y.col)
nY <- length(Y.col) / length(tm)
if ((nY %% 1) != 0) {
stop("Number of longitudinal variables not consistent with the number of longitudinal time points")
}
time <- rep(tm, times = length(pat))
indv <- rep(pat, each = ltt)
Y <- as.matrix(data[, Y.col])
data.trans <- as.data.frame(cbind(indv, time))
names(data.trans)[1] <- names(data)[id.col]
for (i in 1:nY) {
Y.tt <- c(t(Y[, (ltt * (i - 1) + 1):(ltt * i)]))
data.trans <- cbind(data.trans, Y.tt)
names(data.trans)[dim(data.trans)[2]] <- (names(data)[Y.col])[(i - 1) * ltt + 1]
}
ddt <- dim(data.trans)[2]
if (!identical(NA, other.col)) {
if (!is.numeric(other.col)) {
other.col <- which(names(data) %in% other.col)
}
other.col <- as.vector(other.col)
other <- as.data.frame(data[, other.col])
l.other <- dim(other)[2]
for (i in 1:l.other) {
data.trans <- cbind(data.trans, rep(other[, i], each = ltt))
}
data.trans <- as.data.frame(data.trans)
names(data.trans)[(ddt + 1):(dim(data.trans)[2])] <- names(data)[other.col]
}
row.names(data.trans) <- 1:(dim(data.trans)[1])
return(data.trans)
}
|
fit_topt_VJs <- function(data,
group,
varnames = list(Vcmax = "Vcmax",
Jmax = "Jmax",
Tleaf = "Tleaf"),
limit_jmax = 100000,
limit_vcmax = 100000,
...) {
data$group <- data[, group]
data <- split(data, data$group)
fits <- list()
for (i in 1:length(data)) {
fits[[i]] <- fit_topt_VJ(data = data[[i]],
varnames = varnames,
title = names(data[i]),
limit_jmax = limit_jmax,
limit_vcmax = limit_vcmax,
...)
names(fits)[i] <- names(data[i])
}
return(fits)
}
|
cluster_vars <- function(x = NULL, d = NULL, block = NULL, method = "average",
use = "pairwise.complete.obs", sort.parallel = TRUE,
parallel = c("no", "multicore", "snow"), ncpus = 1L,
cl = NULL) {
parallel <- match.arg(parallel)
do.parallel <- (parallel != "no" && ncpus > 1L)
if (do.parallel && parallel == "multicore" && .Platform$OS.type == "windows") {
stop("The argument parallel = 'multicore' is not available for windows. Use parallel = 'snow' for parallel computing or parallel = 'no' for serial execution of the code.")
}
check_input_cl(x = x, d = d, method = method, block = block, use = use)
if (!is.null(x)) {
if (is.matrix(x)) {
x.all <- x
}
if (is.list(x)) {
len.x <- length(x)
dim.x <- unlist(lapply(x, nrow))
colnames.x <- lapply(x, colnames)
unique.colnames.x <- unique(x = unlist(colnames.x))
x.all <- matrix(NA, nrow = sum(dim.x), ncol = length(unique.colnames.x))
colnames(x.all) <- unique.colnames.x
cumsum.dim <- cumsum(c(0, dim.x))
for (i in seq_len(len.x)) {
x.all[(cumsum.dim[i] + 1):(cumsum.dim[i + 1]), colnames.x[[i]]] <- x[[i]]
}
}
}
resultDendr <-
if (!is.null(x) & !is.null(block)) {
cluster_the_blocks <- local({
x.all
block
method
use
function(givenBlock) {
tryCatch_W_E(cluster_one_block(x = x.all, block = block, d = NULL,
method = method, use = use,
givenBlock = givenBlock),
ret.obj = NA)
}})
if (sort.parallel) {
unique.blocks <- names(sort(table(block[, 2]), decreasing = TRUE))
} else {
unique.blocks <- unique(block[, 2])
}
if (do.parallel) {
if (parallel == "multicore") {
parallel::mclapply(unique.blocks, cluster_the_blocks,
mc.cores = ncpus)
} else if (parallel == "snow") {
if (is.null(cl)) {
cl <- parallel::makePSOCKcluster(rep("localhost", ncpus))
parallel::clusterExport(cl, varlist = getNamespaceExports("hierinf"))
if(RNGkind()[1L] == "L'Ecuyer-CMRG")
parallel::clusterSetRNGStream(cl)
res <- parallel::parLapply(cl, unique.blocks, cluster_the_blocks)
parallel::stopCluster(cl)
res
} else parallel::parLapply(cl, unique.blocks, cluster_the_blocks)
}
} else lapply(unique.blocks, cluster_the_blocks)
} else if (!is.null(x) & is.null(block)) {
list(tryCatch_W_E(cluster_one_block(x = x.all, block = NULL, d = NULL,
method = method, use = use,
givenBlock = NULL),
ret.obj = NA))
} else if (!is.null(d)) {
list(tryCatch_W_E(cluster_one_block(x = NULL, block = NULL, d = d,
method = method, use = use,
givenBlock = NULL),
ret.obj = NA))
}
if (!is.null(x) & !is.null(block)) {
names(resultDendr) <- unique.blocks
}
resultDendr <- do.call(cbind, resultDendr)
resD <- resultDendr["value", ]
attr(resD,"errorMsgs") <- do.call(c, resultDendr["error", ])
attr(resD, "warningMsgs") <- do.call(c, resultDendr["warning", ])
if (!is.null(attr(resD, "errorMsgs"))) {
warning("There occurred some errors while clustering. See attribute 'errorMsgs' of the corresponding list element of the return object for more details.")
}
if (!is.null(attr(resD, "warningMsgs"))) {
warning("There occurred some warnings while clustering. See attribute 'warningMsgs' of the corresponding list element of the return object for more details.")
}
resDD <- list("block" = block, "res.tree" = resD)
resDD <- structure(resDD, class = c("hierD", "list"))
return(resDD)
}
cluster_one_block <- function(x, d, method, block, use, givenBlock) {
if (!is.null(x)) {
if (!is.null(block)) {
indX <- which(colnames(x) %in% block[block[, 2] == givenBlock, 1])
}else{
indX <- seq_len(ncol(x))
}
d <- 1 - abs(stats::cor(x = x[, indX], use = use))^2
}
dist.matrix <- stats::as.dist(m = d)
if (!all(!is.na(dist.matrix))) {
stop("There are NA's in the calculated dissimilarity matrix / distance matrix. The variables cannot be clustered. This might be due to multiple data sets which do not contain all the same variables.")
}
x.hclust <- stats::hclust(d = dist.matrix, method = method)
x.dendr <- stats::as.dendrogram(object = x.hclust)
return(x.dendr)
}
|
context("Functions that create interpretable inputs")
testthat::test_that("Extracting numerical features is okay", {
testthat::expect_equal(
extract_numerical_feature(c("x > 4", "x <= 4"), 5)$label,
"x > 4"
)
testthat::expect_equal(
extract_numerical_feature(c("x > 4", "x <= 4"), 4)$label,
"x <= 4"
)
testthat::expect_equal(
extract_numerical_feature(c("x <= 4 & x <= 5",
"x > 5 & x <= 8"), 3)$label,
"x <= 4"
)
testthat::expect_equal(
extract_numerical_feature(c("x <= 4 & x <= 5",
"x > 5 & x <= 8"), 7)$label,
"5 < x <= 8"
)
})
|
knitr::opts_chunk$set(echo = TRUE)
library(PKNCA)
library(dplyr)
method.choices <- names(PKNCA:::interp.extrap.conc.dose.select)
method.choices <-
factor(method.choices, levels=method.choices, ordered=TRUE)
all_combs <-
expand.grid(event_before=setdiff(unlist(PKNCA:::event_choices_interp.extrap.conc.dose), "output_only"),
event=setdiff(unlist(PKNCA:::event_choices_interp.extrap.conc.dose), "none"),
event_after=setdiff(unlist(PKNCA:::event_choices_interp.extrap.conc.dose), "output_only"),
Method="",
stringsAsFactors=FALSE)
for (n in method.choices) {
mask <-
do.call(PKNCA:::interp.extrap.conc.dose.select[[n]]$select,
list(x=all_combs),
envir=environment(pk.nca))
all_combs$Method[mask] <- n
}
all_combs <-
all_combs[do.call(order,
args=append(as.list(all_combs), list(na.last=FALSE))),]
methodorder <- names(sort(summary(factor(all_combs$Method)), decreasing=TRUE))
for (n in methodorder) {
cat("
cat(PKNCA:::interp.extrap.conc.dose.select[[n]]$description, "\n\n", sep="")
print(knitr::kable(
all_combs[all_combs$Method %in% n,
c("event_before","event", "event_after")],
row.names=FALSE,
col.names=c("Event Before", "Event At", "Event After")))
cat("\n")
}
knitr::kable(
all_combs[,c("event_before", "event", "event_after", "Method")],
row.names=FALSE,
col.names=c("Event Before", "Event At", "Event After", "Method Used"))
|
define_dimension <- function(st,
name = NULL,
attributes = NULL) {
UseMethod("define_dimension")
}
define_dimension.dimensional_model <- function(st,
name = NULL,
attributes = NULL) {
stopifnot(!is.null(name))
stopifnot(!(name %in% names(st$dimension)))
stopifnot(length(attributes) > 0)
stopifnot(length(attributes) == length(unique(attributes)))
attributes_defined <- get_attribute_names(st)
for (attribute in attributes) {
stopifnot(!(attribute %in% attributes_defined))
}
if (is.null(st$dimension)) {
st$dimension <- list(name = attributes)
names(st$dimension) <- name
} else {
dim_names <- names(st$dimension)
st$dimension <- c(st$dimension, list(name = attributes))
names(st$dimension) <- c(dim_names, name)
}
st
}
|
forecast_infections <- function(infections, rts,
gt_mean, gt_sd, gt_max = 30,
ensemble_type = "mean", forecast_model,
CrIs = c(0.2, 0.5, 0.9),
horizon = 14, samples = 1000){
if (!requireNamespace("EpiSoon", quietly = TRUE)) {
stop('The EpiSoon package is missing. Install it with:
install.packages("drat"); drat:::add("epiforecasts"); install.packages("EpiSoon")')
}
data.table::setDTthreads(1)
infections <- data.table::setDT(infections)
rts <- data.table::setDT(rts)
if (missing(forecast_model)) {
stop("A forecasting model has not been supplied so no forecast can be produced. See the documentation for examples.")
}
sample_forecast <- function(df, samples) {
safe_forecast <- purrr::safely(EpiSoon::forecast_rt)
rt_forecasts <-
data.table::setDT(
safe_forecast(rts = df[, .(date, rt = mean)],
model = forecast_model,
horizon = horizon,
samples = samples)[[1]]
)
rt_sd <- df[date == max(date, na.rm = TRUE)]$sd
rt_sd <- ifelse(rt_sd <= 0, 1e-3, rt_sd)
rt_forecasts <- rt_forecasts[, rt := purrr::map_dbl(rt, ~ truncnorm::rtruncnorm(1, a = 0,
mean = .,
sd = rt_sd))][,
.(sample, date, horizon, rt)]
return(rt_forecasts)
}
rt_forecast <- sample_forecast(rts, samples = samples)
generate_pmf <- function(mean, sd, max_value) {
params <- list(
alpha = (mean/sd)^2,
beta = mean/sd^2
)
sample_fn <- function(n, ...) {
c(0, EpiNow2::dist_skel(n = n,
model = "gamma",
params = params,
max_value = max_value,
...))
}
dist_pdf <- sample_fn(0:(max_value - 1), dist = TRUE, cum = FALSE)
return(dist_pdf)
}
generation_pmf <- generate_pmf(gt_mean, gt_sd, max_value = gt_max)
case_forecast <- sample_forecast(infections, samples = samples)[,
`:=`(cases = rt, forecast_type = "case")][, rt := NULL]
case_rt_forecast <-
data.table::setDT(
EpiSoon::forecast_cases(
cases = infections[, .(date, cases = mean)],
fit_samples = rt_forecast,
rdist = rpois,
serial_interval = generation_pmf
)
)
case_rt_forecast <- case_rt_forecast[, cases := purrr::map_dbl(cases,
~ as.integer(truncnorm::rtruncnorm(1, a = 0, mean = ., sd = infections$sd[nrow(infections)])))][,
forecast_type := "rt"]
case_forecast <- data.table::rbindlist(list(
case_forecast, case_rt_forecast), use.names = TRUE)
if (ensemble_type %in% "mean") {
ensemble_forecast <- data.table::copy(case_forecast)[, .(cases = mean(cases, na.rm = TRUE),
forecast_type = "ensemble"),
by = .(sample, date, horizon)]
case_forecast <- data.table::rbindlist(list(case_forecast, ensemble_forecast))
}
forecast <- data.table::rbindlist(list(
rt_forecast[, value := rt][, rt := NULL][, type := "rt"],
case_forecast[, value := cases][, cases := NULL][, type := "case"]
), fill = TRUE)
summarised_forecast <- calc_summary_measures(forecast,
summarise_by = c("date", "type", "forecast_type"),
order_by = c("type", "forecast_type", "date"),
CrIs = CrIs)
out <- list(samples = forecast, summarised = summarised_forecast)
return(out)
}
|
mris_convert_vertex = function(
opts = "",
...
){
opts = paste(opts, collapse = " ")
opts = paste0(opts, " ", "-v ")
outfile = mris_convert(..., opts = opts)
return(outfile)
}
|
setMethod("shape1", "BetaParameter", function(object) object@shape1)
setMethod("shape2", "BetaParameter", function(object) object@shape2)
setMethod("ncp", "BetaParameter", function(object) object@ncp)
setReplaceMethod("shape1", "BetaParameter",
function(object, value){ object@shape1 <- value; object})
setReplaceMethod("shape2", "BetaParameter",
function(object, value){ object@shape2 <- value; object})
setReplaceMethod("ncp", "BetaParameter",
function(object, value){ object@ncp <- value; object})
setValidity("BetaParameter", function(object){
if(length(shape1(object)) != 1)
stop("shape1 has to be a numeric of length 1")
if(shape1(object) <= 0)
stop("shape1 has to be positive")
if(length(shape2(object)) != 1)
stop("shape2 has to be a numeric of length 1")
if(shape2(object) <= 0)
stop("shape2 has to be positive")
if(length(ncp(object)) != 1)
stop("ncp has to be a numeric of length 1")
else return(TRUE)
}
)
Beta <- function(shape1 = 1, shape2 = 2, ncp = 0)
new("Beta", shape1 = shape1, shape2 = shape2, ncp = ncp)
setMethod("shape1", "Beta", function(object) shape1(param(object)))
setMethod("shape2", "Beta", function(object) shape2(param(object)))
setMethod("ncp", "Beta", function(object) ncp(param(object)))
setMethod("shape1<-", "Beta",
function(object, value) new("Beta", shape1 = value,
shape2 = shape2(object), ncp = ncp(object)))
setMethod("shape2<-", "Beta",
function(object, value) new("Beta", shape1 = shape1(object),
shape2 = value, ncp = ncp(object)))
setMethod("ncp<-", "Beta",
function(object, value) new("Beta", shape1 = shape1(object),
shape2 = shape2(object), ncp = value))
setMethod("-", c("numeric","Beta"),
function(e1, e2) {if(isTRUE(all.equal(e1,1))&&
isTRUE(all.equal(ncp(e2),0)))
return(Beta(shape1=shape2(e2),shape2=shape1(e2)))
else e1-as(e2,"AbscontDistribution")})
|
summary.fitdstn <- function(object, ...)
{
object
}
|
`labels.setupSNP` <-
function(object, ...) attr(object,"label.SNPs")
|
formatResult <- function(text, themestring, labelstring, oneline, formatR = TRUE) {
result <- NULL
if (!is.null(themestring) && length(themestring) > 0) {
if (oneline) {
result <- paste0(' + theme(', paste(themestring, collapse = ', '),')')
} else {
result <- paste0(paste(text, ' <- ', text, ' + theme(', themestring, ')', sep = ''), collapse = '\n')
}
}
if (!is.null(labelstring)) {
if (oneline) {
result <- c(result, ' + ', labelstring)
} else {
labelstring <- paste0(text, ' <- ', text, ' + ', labelstring)
result <- paste(c(result, labelstring), collapse = '\n')
}
}
if (oneline) {
if (formatR) {
result <- formatR::tidy_source(text = result, output = FALSE, width.cutoff = 40)$text.tidy
result <- gsub('^\\+theme', ' + theme', result)
}
result <- paste0(text, paste(result, collapse = ' '))
}
result <- paste(result, collapse = "\n")
return(result)
}
|
distr_crit <- function(target, feature, criterion = "ig", iter_limit = 200) {
n <- length(target)
if (length(feature) != n) {
stop("Target and feature have different lengths.")
}
if (!all(target %in% c(0, 1))) {
stop("Target is not {0,1}-valued vector.")
}
if (!all(feature %in% c(0,1)) ) {
stop("Feature is not {0,1}-valued vector.")
}
valid_criterion <- check_criterion(criterion)
crit_function <- function(target, features)
calc_criterion(target, features, valid_criterion[["crit_function"]])
non_zero_target <- sum(target)
non_zero_feat <- sum(feature)
p <- non_zero_target/n
q <- non_zero_feat/n
max_iter <- min(non_zero_target, non_zero_feat)
min_iter <- max(0, non_zero_target + non_zero_feat - n)
cross_tab <- fast_crosstable(target, length(target), sum(target), feature)
if (is.null(iter_limit))
iter_limit <- max_iter
crit_range <- max_iter - min_iter
possible_crit_values <- if(crit_range > iter_limit) {
round(seq(from = min_iter, to = max_iter, length.out = iter_limit), 0)
} else {
min_iter:max_iter
}
diff_conts <- sapply(possible_crit_values, function(i) {
k <- c(i, non_zero_feat - i, non_zero_target - i,
n - non_zero_target - non_zero_feat + i)
prob_log <- dmultinom(x = k,
size = n,
prob = c(p*q, (1-p)*q, p*(1-q), (1-p)*(1-q)),
log = TRUE)
ft_data <- do.call(create_feature_target, as.list(k))
vals <- unname(crit_function(ft_data[,1], ft_data[, 2, drop = FALSE]))
c(prob_log = prob_log, vals = vals)
})
dist_temp <- exp(diff_conts["prob_log", ])/sum(exp(diff_conts["prob_log", ]))
dist_temp <- dist_temp[order(diff_conts["vals", ])]
val_temp <- diff_conts["vals", ][order(diff_conts["vals", ])]
j <- 1
criterion_distribution <- dist_temp[1]
criterion_values <- val_temp[1]
if(length(val_temp) > 1)
for(i in 2L:length(val_temp)) {
if (abs(val_temp[i - 1] - val_temp[i]) < 1e-10) {
criterion_values[j] <- criterion_values[j]
criterion_distribution[j] <- criterion_distribution[j] + dist_temp[i]
}
else {
j <- j + 1
criterion_values[j] <- val_temp[i]
criterion_distribution[j] <- dist_temp[i]
}
}
create_criterion_distribution(criterion_values,
criterion_distribution,
possible_crit_values,
diff_conts["vals", ],
exp(diff_conts["prob_log", ])/sum(exp(diff_conts["prob_log", ])),
valid_criterion[["nice_name"]])
}
|
readRasterFolder <- function(path, samplename = 'sample', filenames = NULL, object = new('rasclass'), asInteger = FALSE){}
setMethod('readRasterFolder', signature(path = 'character'),
function(path, samplename = 'sample', filenames = NULL, object = new('rasclass'), asInteger = FALSE){
if(substr(samplename, nchar(samplename)-3, nchar(samplename)) == '.asc'){
samplename <- substr(samplename, 1, nchar(samplename)-4)
}
object@samplename <- samplename
if(substr(path,nchar(path), nchar(path)) != '/'){
path <- paste(path,'/', sep='')
}
object@path <- path
userwd <- getwd()
on.exit(setwd(userwd))
setwd(path)
if(length(filenames) == 0){
filelist <- Sys.glob('*.asc')
filelist <- filelist[filelist != paste(object@samplename, '.asc' , sep='')]
}
else{
filelist <- NA
for(i in 1:length(filenames)){
file <- filenames[i]
if(substr(file, nchar(file)-3, nchar(file)) == '.asc'){
filelist[i] <- file
} else {
filelist[i] <- paste(file, '.asc', sep='')
}
}
}
namelist <- substr(filelist, 1, nchar(filelist)-4)
cat('\nReading Raster grids from "', getwd(), '"\n', sep ='')
cat(paste(paste(object@samplename),'.asc',sep=''), '\n')
thissample <- readRaster(paste(object@samplename, '.asc', sep=''), asInteger = asInteger)
object@data <- data.frame(thissample@grid)
object@gridSkeleton@ncols <- thissample@ncols
object@gridSkeleton@nrows <- thissample@nrows
object@gridSkeleton@xllcorner <- thissample@xllcorner
object@gridSkeleton@yllcorner <- thissample@yllcorner
object@gridSkeleton@cellsize <- thissample@cellsize
object@gridSkeleton@NAvalue <- thissample@NAvalue
rm(thissample)
for(i in 1:length(filelist)){
cat(filelist[i], '\n')
tempraster <- readRaster(filelist[i], asInteger = asInteger)
if( object@gridSkeleton@nrows != tempraster@nrows |
object@gridSkeleton@ncols != tempraster@ncols |
object@gridSkeleton@xllcorner != tempraster@xllcorner |
object@gridSkeleton@yllcorner != tempraster@yllcorner |
object@gridSkeleton@cellsize != tempraster@cellsize
){ stop('The input raster grids do not all have the same header') }
if(i == 1){
object@data <- data.frame(object@data, tempraster@grid)
object@gridSkeleton@grid <- as.integer(!is.na(tempraster@grid))
}
else{
object@data <- data.frame(object@data, tempraster@grid[as.logical(object@gridSkeleton@grid)])
object@gridSkeleton@grid <- as.integer(object@gridSkeleton@grid * !is.na(tempraster@grid))
}
object@data <- object@data[!is.na(object@data[, i+1]), ]
}
names(object@data) <- append(object@samplename, namelist)
object <- buildFormula(object)
object
}
)
|
chrvec2dl <- function(x, splt="-"){
m <- splt
layers <- length(strsplit(x[1], split = m)[[1]])
rpt <- length(x)
ept_list <- list()
result <- list(ept_list)[rep(1,layers)]
if (rpt==1){
x <- as.character(x)
i <- 1
for (i in 1:layers) {
result[[i]] <- strsplit(x[1], split = m)[[1]][i]
}
}
if (is.vector(x) != TRUE){
stop("input data should be a vector", call. = FALSE)
}
if (is.character(x) != TRUE){
x <- as.character(x)
}
length_vec <- c(1:rpt)
i <- 1
for (i in 1:rpt) {
length_vec[i] <- length(strsplit(x[i], split = m)[[1]])
}
layers <- max(length_vec)
result <- list(ept_list)[rep(1,layers)]
j <- 1
i <- 1
while (j <= layers) {
temp_vec <- c()
for (i in 1:rpt) {
if (j > length_vec[i]){
temp_vec <- append(temp_vec, "*")
} else {
temp_vec <- append(temp_vec, strsplit(x[i], split = m)[[1]][j])
}
}
result[[j]] <- temp_vec
j <- j + 1
}
i <- 1
for (i in 1:layers) {
result[[i]] <- levels(factor(result[[i]]))
}
class(result) <- "Double.List"
return(result)
}
|
StatsBombFreeLineups <- function(MatchesDF = "ALL", Parallel = T){
print("Whilst we are keen to share data and facilitate research, we also urge you to be responsible with the data. Please register your details on https://www.statsbomb.com/resource-centre and read our User Agreement carefully.")
events.df <- tibble()
if(Parallel == T){
if(MatchesDF == "ALL"){
Comp <- FreeCompetitions()
Matches2 <- FreeMatches(Comp$competition_id)
cl <- makeCluster(detectCores())
registerDoParallel(cl)
events.df <- foreach(i = 1:dim(Matches2)[1], .combine=bind_rows, .multicombine = TRUE,
.errorhandling = 'remove', .export = c("get.lineupsFree"),
.packages = c("httr", "jsonlite", "dplyr")) %dopar%
{get.lineupsFree(Matches2[i,])}
stopCluster(cl)
} else {
cl <- makeCluster(detectCores())
registerDoParallel(cl)
events.df <- foreach(i = 1:dim(MatchesDF)[1], .combine=bind_rows, .multicombine = TRUE,
.errorhandling = 'remove', .export = c("get.lineupsFree"),
.packages = c("httr", "jsonlite", "dplyr")) %dopar%
{get.lineupsFree(MatchesDF[i,])}
stopCluster(cl)
}
} else {
if(MatchesDF == "ALL"){
Comp <- FreeCompetitions()
Matches2 <- FreeMatches(Comp$competition_id)
for(i in 1:length(Matches2$match_id)){
events <- get.lineupsFree(Matches2[i,])
events.df <- bind_rows(events.df, events)
}
} else {
for(i in 1:length(MatchesDF$match_id)){
events <- get.lineupsFree(MatchesDF[i,])
events.df <- bind_rows(events.df, events)
}
}
}
return(events.df)
}
|
spark_schema_from_rdd <- function(sc, rdd, column_names) {
columns_typed <- length(names(column_names)) > 0
if (columns_typed) {
schema <- spark_data_build_types(sc, column_names)
return(schema)
}
sampleRows <- rdd %>% invoke(
"take",
cast_scalar_integer(
spark_config_value(sc$config, "sparklyr.apply.schema.infer", 10)
)
)
map_special_types <- list(
date = "date",
posixct = "timestamp",
posixt = "timestamp"
)
colTypes <- NULL
lapply(sampleRows, function(r) {
row <- r %>% invoke("toSeq")
if (is.null(colTypes)) {
colTypes <<- replicate(length(row), "character")
}
lapply(seq_along(row), function(colIdx) {
colVal <- row[[colIdx]]
lowerClass <- tolower(class(colVal)[[1]])
if (lowerClass %in% names(map_special_types)) {
colTypes[[colIdx]] <<- map_special_types[[lowerClass]]
} else if (!is.na(colVal) && !is.null(colVal)) {
colTypes[[colIdx]] <<- typeof(colVal)
}
})
})
if (any(sapply(colTypes, is.null))) {
stop("Failed to infer column types, please use explicit types.")
}
fields <- lapply(seq_along(colTypes), function(idx) {
name <- if (idx <= length(column_names)) {
column_names[[idx]]
} else {
paste0("X", idx)
}
invoke_static(
sc,
"sparklyr.SQLUtils",
"createStructField",
name,
colTypes[[idx]],
TRUE
)
})
invoke_static(
sc,
"sparklyr.SQLUtils",
"createStructType",
fields
)
}
|
context("sjmisc, empty_cols")
library(sjmisc)
tmp <- data.frame(a = c(1, 2, 3, NA, 5),
b = c(1, NA, 3, NA , 5),
c = c(NA, NA, NA, NA, NA),
d = c(1, NA, 3, NA, 5))
test_that("empty_cols", {
expect_equal(unname(empty_cols(tmp)), 3)
})
test_that("empty_rows", {
expect_equal(empty_rows(tmp), 4)
})
|
image.TPCmsm <- function(x, image.type="tc", tr.choice, xlim, ylim, zlim=c(0, 1), col, xlab, ylab, main, sub, key.title, key.axes, las=1, conf.int=FALSE, legend=TRUE, curvlab, contour=TRUE, nlevels=20, levels=pretty(zlim, nlevels), ...) {
if ( !inherits(x, "TPCmsm") ) stop("'x' must be of class 'TPCmsm'")
if ( !( image.type %in% c("tc", "ct") ) ) stop("Argument 'image.type' must be one of 'tc' or 'ct'")
if ( missing(tr.choice) ) tr.choice <- dimnames(x$est)[[3]]
lt <- length(tr.choice)
if (sum( tr.choice %in% dimnames(x$est)[[3]] ) != lt) stop("Argument 'tr.choice' and possible transitions must match")
if ( anyDuplicated(tr.choice) ) stop("Argument 'tr.choice' must be unique")
draw.conf <- conf.int & !is.null(x$inf) & !is.null(x$sup)
itr <- match( tr.choice, dimnames(x$est)[[3]] )
if ( missing(main) ) main <- ""
if ( missing(sub) ) sub <- ""
if ( missing(col) ) col <- heat.colors(nlevels)[nlevels:1]
if ( missing(curvlab) ) curvlab <- tr.choice
mat <- matrix(nrow=2*draw.conf+1, ncol=lt+1)
par.orig <- par( c("mar", "las", "mfrow", "new") )
on.exit( par(par.orig) )
if (draw.conf) {
mat[1,1:lt] <- (lt*2+1):(lt*3)
mat[2,1:lt] <- 1:lt
mat[3,1:lt] <- (lt+1):(lt*2)
} else mat[1,1:lt] <- 1:lt
mat[,ncol(mat)] <- rep( (2*draw.conf+1)*lt+1, nrow(mat) )
mar.orig <- par.orig$mar
if (length(tr.choice) < 2 & !draw.conf) {
w <- (3 + mar.orig[2L]) * par("csi") * 2.54
} else w <- (3 + mar.orig[2L]) * par("csi") * 2
layout( mat, widths=c( rep(1, lt), lcm(w) ) )
mar <- mar.orig
mar[4L] <- 1
par(las=las, mar=mar)
if (image.type == "tc") {
if ( missing(xlab) ) xlab <- "Time"
if ( missing(ylab) ) ylab <- "Covariate"
if ( missing(xlim) ) xlim <- c(x$time[1], x$time[length(x$time)])
if ( missing(ylim) ) ylim <- c(x$covariate[1], x$covariate[length(x$covariate)])
for ( i in seq_len(lt) ) {
image(x=x$time, y=x$covariate, z=x$est[,,itr[i]], xlim=xlim, ylim=ylim, zlim=zlim, col=col, main="", sub="", xlab="", ylab="", breaks=levels, ...)
if (contour) contour(x=x$time, y=x$covariate, z=x$est[,,itr[i]], nlevels=nlevels, levels=levels, xlim=xlim, ylim=ylim, zlim=zlim, axes=FALSE, col=grey(0.4), add=TRUE)
if (legend) title(main=curvlab[i], sub="", xlab="", ylab="", ...)
}
} else if (image.type == "ct") {
if ( missing(xlab) ) xlab <- "Covariate"
if ( missing(ylab) ) ylab <- "Time"
if ( missing(xlim) ) xlim <- c(x$covariate[1], x$covariate[length(x$covariate)])
if ( missing(ylim) ) ylim <- c(x$time[1], x$time[length(x$time)])
for ( i in seq_len(lt) ) {
image(x=x$covariate, y=x$time, z=t(x$est[,,itr[i]]), xlim=xlim, ylim=ylim, zlim=zlim, col=col, main="", sub="", xlab="", ylab="", breaks=levels, ...)
if (contour) contour(x=x$covariate, y=x$time, z=t(x$est[,,itr[i]]), nlevels=nlevels, levels=levels, xlim=xlim, ylim=ylim, zlim=zlim, axes=FALSE, col=grey(0.4), add=TRUE)
if (legend) title(main=curvlab[i], sub="", xlab="", ylab="", ...)
}
}
if (draw.conf) {
if (image.type == "tc") {
for ( i in seq_len(lt) ) {
image(x=x$time, y=x$covariate, z=x$inf[,,itr[i]], xlim=xlim, ylim=ylim, zlim=zlim, col=col, main="", sub="", xlab="", ylab="", breaks=levels, ...)
if (contour) contour(x=x$time, y=x$covariate, z=x$inf[,,itr[i]], nlevels=nlevels, levels=levels, xlim=xlim, ylim=ylim, zlim=zlim, axes=FALSE, col=grey(0.4), add=TRUE)
}
for ( i in seq_len(lt) ) {
image(x=x$time, y=x$covariate, z=x$sup[,,itr[i]], xlim=xlim, ylim=ylim, zlim=zlim, col=col, main="", sub="", xlab="", ylab="", breaks=levels, ...)
if (contour) contour(x=x$time, y=x$covariate, z=x$sup[,,itr[i]], nlevels=nlevels, levels=levels, xlim=xlim, ylim=ylim, zlim=zlim, axes=FALSE, col=grey(0.4), add=TRUE)
}
} else if (image.type == "ct") {
for ( i in seq_len(lt) ) {
image(x=x$covariate, y=x$time, z=t(x$inf[,,itr[i]]), xlim=xlim, ylim=ylim, zlim=zlim, col=col, main="", sub="", xlab="", ylab="", breaks=levels, ...)
if (contour) contour(x=x$covariate, y=x$time, z=t(x$inf[,,itr[i]]), nlevels=nlevels, levels=levels, xlim=xlim, ylim=ylim, zlim=zlim, axes=FALSE, col=grey(0.4), add=TRUE)
}
for ( i in seq_len(lt) ) {
image(x=x$covariate, y=x$time, z=t(x$sup[,,itr[i]]), xlim=xlim, ylim=ylim, zlim=zlim, col=col, main="", sub="", xlab="", ylab="", breaks=levels, ...)
if (contour) contour(x=x$covariate, y=x$time, z=t(x$sup[,,itr[i]]), nlevels=nlevels, levels=levels, xlim=xlim, ylim=ylim, zlim=zlim, axes=FALSE, col=grey(0.4), add=TRUE)
}
}
}
mar <- par("mar")
mar[4L] <- mar[2L]
mar[2L] <- 1
par(mar=mar)
plot.new()
plot.window(xlim=c(0, 1), ylim=range(levels), xaxs="i", yaxs="i")
rect(0, levels[-length(levels)], 1, levels[-1L], col=col)
if ( missing(key.axes) ) {
axis(4)
} else key.axes
box()
if ( missing(key.title) ) {
if (length(tr.choice) < 2 & !draw.conf) {
cex.main <- 0.8
} else cex.main <- 1
title(main="Transition\nprobability", cex.main=cex.main)
} else key.title
par(par.orig)
par(new=TRUE)
plot.new()
title(main=main, sub=sub, xlab=xlab, ylab=ylab, cex.main=1.2, cex.lab=1.2, ...)
invisible()
}
|
material_side_nav <- function(..., fixed = FALSE, image_source = NULL, background_color = NULL){
if(is.null(image_source)){
side_nav_content <- shiny::tagList(...)
} else {
side_nav_content <-
shiny::tagList(
shiny::tags$li(
shiny::tags$div(
style = "height:160px",
class = "user-view",
shiny::tags$div(
class = "background",
shiny::tags$img(
style = "height:160px;width:300px",
src = image_source
)
)
)
),
...
)
}
css_file <-
paste0(
"css/shiny-material-side-nav",
ifelse(
fixed,
"-fixed",
""
),
ifelse(
!is.null(image_source),
"-image",
""
),
".css"
)
shiny::tagList(
shiny::includeCSS(
system.file(
css_file,
package = "shinymaterial"
)
),
shiny::tags$ul(
id = "slide-out",
class = paste0(
"sidenav",
ifelse(
!is.null(background_color),
paste0(" ", background_color),
""
),
ifelse(
fixed,
" sidenav-fixed",
""
)
),
side_nav_content
),
shiny::includeScript(
system.file(
paste0(
"js/shiny-material-side-nav",
ifelse(
fixed,
"-fixed",
""),
".js"
),
package = "shinymaterial"
)
)
)
}
|
plev <-
function(z)
{
exp(-exp(-z))
}
|
"table"
|
generics::augment
augment.dr4pl <- function(x,
data = NULL,
...) {
if (...length()>0) abort("... were used in `augment.dr4pl`. These dots are only present for future extension and should be empty.")
data <- data %||% x$data
mapping <- parse_dr4pl_mapping(x$call)
if (inherits(mapping, "no_mapping")) abort("cannot use `augment.dr4pl` when dr4pl object was constructed with the `dr4pl.default` method.\nConstruct dr4pl with formula or data.frame method.")
.dose <- eval(mapping$Dose, data)
.resp <- eval(mapping$Response, data)
.fitted <- MeanResponse(coef(x), x = .dose)
.resid <- residuals(coef(x), dose = .dose, response = .resp)
data[['.fitted']] <- .fitted
data[['.resid']] <- .resid
if(requireNamespace("tibble", quietly = T)){
return(tibble::as_tibble(data))
} else {
return(data)
}
}
parse_dr4pl_mapping <- function(call){
args <- call_args(call)
args <- switch(names(args)[1],
formula = mapping_parser("parse_formula", args),
data = mapping_parser("parse_data", args),
mapping_parser("parse_default", args))
arg_parse(args)
}
mapping_parser <- function(.class, args) {
structure(args, class = .class)
}
arg_parse <- function(args) UseMethod('arg_parse')
arg_parse.parse_formula <- function(args) {
list(
Response = args[[1]][[2]],
Dose = args[[1]][[3]]
)
}
arg_parse.parse_data <- function(args) {
list(
Response = args$response,
Dose = args$dose
)
}
arg_parse.parse_default <- function(args) {
structure(list(), class = "no_mapping")
}
call_args <- function(call){
args <- as.list(call[-1])
stats::setNames(args, nm = names(args))
}
|
print.treeClust <- function(x, ...)
{
cat("Call:\n")
cat(deparse(x$call), "\n")
if (any (names (x) == "mat"))
cat("Structure is ", nrow(x$mat), "by", ncol(x$mat), "\n")
if (x$final.algorithm == "None")
cat ("No final clustering was performed\n")
else
cat (paste ("Final clustering by", x$final.algorithm, "\n"))
print(x$tbl)
}
|
rehash <- function(prompt = interactive(), ...) {
renv_scope_error_handler()
renv_dots_check(...)
invisible(renv_rehash_impl(prompt))
}
renv_rehash_impl <- function(prompt) {
oldcache <- renv_paths_cache(version = renv_cache_version_previous())[[1L]]
newcache <- renv_paths_cache(version = renv_cache_version())[[1L]]
if (file.exists(oldcache) && !file.exists(newcache))
renv_rehash_cache(oldcache, prompt, renv_file_copy, "copied")
renv_rehash_cache(newcache, prompt, renv_file_move, "moved")
}
renv_rehash_cache <- function(cache, prompt, action, label) {
old <- renv_cache_list(cache = cache)
vprintf("* Re-computing package hashes ... ")
new <- map_chr(old, renv_progress(renv_cache_path, length(old)))
vwritef("Done!")
changed <- which(old != new & file.exists(old) & !file.exists(new))
if (empty(changed)) {
vwritef("* Your cache is already up-to-date -- nothing to do.")
return(TRUE)
}
if (prompt) {
fmt <- "%s [%s -> %s]"
packages <- basename(old)[changed]
oldhash <- renv_path_component(old[changed], 2L)
newhash <- renv_path_component(new[changed], 2L)
renv_pretty_print(
sprintf(fmt, format(packages), format(oldhash), format(newhash)),
"The following packages will be re-cached:",
sprintf("Packages will be %s to their new locations in the cache.", label),
wrap = FALSE
)
if (prompt && !proceed()) {
renv_report_user_cancel()
return(FALSE)
}
}
sources <- old[changed]
targets <- new[changed]
names(sources) <- targets
names(targets) <- sources
vprintf("* Re-caching packages ... ")
enumerate(targets, renv_progress(action, length(targets)))
vwritef("Done!")
n <- length(targets)
fmt <- "Successfully re-cached %i %s."
vwritef(fmt, n, plural("package", n))
renv_cache_clean_empty()
TRUE
}
|
ch_lon <- function(n = 1) {
assert(n, c('integer', 'numeric'))
if (n == 1) {
CoordinateProvider$new()$lon()
} else {
x <- CoordinateProvider$new()
replicate(n, x$lon())
}
}
ch_lat <- function(n = 1) {
assert(n, c('integer', 'numeric'))
if (n == 1) {
CoordinateProvider$new()$lat()
} else {
x <- CoordinateProvider$new()
replicate(n, x$lat())
}
}
ch_position <- function(n = 1, bbox = NULL) {
assert(n, c('integer', 'numeric'))
if (n == 1) {
CoordinateProvider$new()$position(bbox)
} else {
x <- CoordinateProvider$new()
replicate(n, x$position(bbox), FALSE)
}
}
|
"mathpnl"
|
cbs_get_themes <- function(..., select=NULL, verbose = TRUE, cache = FALSE
, base_url = getOption("cbsodataR.base_url", BASE_URL)){
url <- whisker.render("{{BASEURL}}/{{CATALOG}}/Themes?$format=json"
, list( BASEURL = base_url
, CATALOG = CATALOG
)
)
url <- paste0(url, get_query(..., select=select))
themes <- resolve_resource(url, "Retrieving themes from ", verbose = verbose, cache = cache)
themes
}
cbs_get_tables_themes <- function(..., select=NULL, verbose = FALSE, cache = TRUE
, base_url = getOption("cbsodataR.base_url", BASE_URL)){
url <- whisker.render("{{BASEURL}}/{{CATALOG}}/Tables_Themes?$format=json"
, list( BASEURL = base_url
, CATALOG = CATALOG
)
)
url <- paste0(url, get_query(..., select=select))
table_themes <- resolve_resource(url, "Retrieving themes from ", cache = cache, verbose = verbose)
table_themes
}
|
options(stringsAsFactors=TRUE)
file.create("foo1")
try(read.table("foo1"))
read.table("foo1", col.names=LETTERS[1:4])
unlink("foo1")
cat("head\n", file = "foo2")
read.table("foo2")
try(read.table("foo2", header=TRUE))
unlink("foo2")
cat("head\n", 1:2, "\n", 3:4, "\n", file = "foo3")
read.table("foo3", header=TRUE)
read.table("foo3", header=TRUE, col.names="V1")
read.table("foo3", header=TRUE, row.names=1)
read.table("foo3", header=TRUE, row.names="row.names")
read.table("foo3", header=TRUE, row.names="head")
try(read.table("foo3", header=TRUE, col.names=letters[1:4]))
unlink("foo3")
cat("head\n", 1:2, "\n", 3:4, file = "foo4")
read.table("foo4", header=TRUE)
unlink("foo4")
cat("head\n\n", 1:2, "\n", 3:4, "\n\n", file = "foo5")
read.table("foo5", header=TRUE)
read.table("foo5", header=FALSE, fill=TRUE, blank.lines.skip=FALSE)
unlink("foo5")
cat("head\n", 1:2, "\n", 3:5, "\n", 6:9, "\n", file = "foo6")
try(read.table("foo6", header=TRUE))
try(read.table("foo6", header=TRUE, fill=TRUE))
read.table("foo6", header=FALSE, fill=TRUE)
unlink("foo6")
cat("A B C D E F\n",
"1 1 1.1 1.1+0i NA F abc\n",
"2 NA NA NA NA NA NA\n",
"3 1 2 3 NA TRUE def\n",
sep = "", file = "foo7")
(res <- read.table("foo7"))
sapply(res, typeof)
sapply(res, class)
(res2 <- read.table("foo7",
colClasses = c("character", rep("numeric", 2),
"complex", "integer", "logical", "character")))
sapply(res2, typeof)
sapply(res2, class)
unlink("foo7")
type.convert(character(0))
cat("
"
"
"
"
"
" a b c",
"
"1 2 3",
"4 5 6
"
"7 8 9",
"
file= "ex.data", sep="\n")
read.table("ex.data", header = T)
unlink("ex.data")
cat("x1\tx
read.table("test.dat", header=T, comment.char="")
unlink("test.dat")
cat('
'C1\tC2\tC3\n"Panel"\t"Area Examined"\t"
'"1"\t"0.8"\t"3"\n', '"2"\t"0.6"\t"2"\n', '"3"\t"0.8"\t"3"\n',
file = "test.dat", sep="")
read.table("test.dat")
unlink("test.dat")
cat('%comment\n\n%another\n%\n%\n',
'C1\tC2\tC3\n"Panel"\t"Area Examined"\t"% Blemishes"\n',
'"1"\t"0.8"\t"3"\n', '"2"\t"0.6"\t"2"\n', '"3"\t"0.8"\t"3"\n',
file = "test.dat", sep="")
read.table("test.dat", comment.char = "%")
unlink("test.dat")
con <- file(file.path(Sys.getenv("SRCDIR"), "WinUnicode.dat"),
encoding="UCS-2LE")
scan(con, 0, quiet=TRUE)
close(con)
x <- "1 2 3 \\ab\\c"
writeLines(x, "test.dat")
readLines("test.dat")
scan("test.dat", "", allowEscapes=TRUE)
scan("test.dat", "", allowEscapes=FALSE)
read.table("test.dat", header=FALSE, allowEscapes=TRUE)
read.table("test.dat", header=FALSE, allowEscapes=FALSE)
x <- c("TEST", 1, 2, "\\b", 4, 5, "\\040", "\\x20",
"c:\\spencer\\tests",
"\\t", "\\n", "\\r")
writeLines(x, "test.dat")
read.table("test.dat", allowEscapes=FALSE, header = TRUE)
unlink("test.dat")
|
tidy_up_ <- function(data, flatten_weather_ = TRUE, use_underscore_ = TRUE, remove_prefix_ = c("main", "sys")) {
.Deprecated("owmr_as_tibble")
if (flatten_weather_ & "weather" %in% colnames(data)) {
data %<>% cbind_weather()
}
if (!is.null(remove_prefix_)) {
data %<>% remove_prefix(remove_prefix_)
}
if (use_underscore_) {
data %<>% use_underscore()
}
data
}
tidy_up <- function(data, ...) {
data$list %<>% tidy_up_(...)
data
}
|
library("git2r")
sessionInfo()
path <- tempfile(pattern = "git2r-")
dir.create(path)
repo <- init(path, bare = TRUE)
stopifnot(identical(is_bare(repo), TRUE))
stopifnot(identical(is_empty(repo), TRUE))
stopifnot(is.null(workdir(repo)))
setwd(path)
stopifnot(identical(is_bare(), TRUE))
unlink(path, recursive = TRUE)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.