code
stringlengths 1
13.8M
|
---|
fitFMM_restr<-function(vData, nback, betaRestrictions, omegaRestrictions,
timePoints = seqTimes(length(vData)), maxiter = nback,
stopFunction = alwaysFalse, lengthAlphaGrid = 48,
lengthOmegaGrid = 24,
alphaGrid = seq(0,2*pi,length.out = lengthAlphaGrid), omegaMin = 0.0001, omegaMax = 1,
omegaGrid = exp(seq(log(omegaMin),log(omegaMax), length.out = lengthOmegaGrid)),
numReps = 3, parallelize = FALSE){
betaRestrictions <- sort(betaRestrictions)
omegaRestrictions <- sort(omegaRestrictions)
numOmegas <- length(unique(omegaRestrictions))
listOmegas <- replicate(n = numOmegas, omegaGrid, simplify = FALSE)
omegasIter <- expand.grid(listOmegas)[,omegaRestrictions]
objectFMMList <- iterateOmegaGrid(vData = vData, omegasIter = omegasIter, betaRestrictions = betaRestrictions,
timePoints = timePoints, alphaGrid = alphaGrid, numReps = numReps,
nback = nback, maxiter = maxiter, stopFunction = stopFunction, parallelize = parallelize)
SSElist <- lapply(objectFMMList, getSSE)
outMobius <- objectFMMList[[which.min(SSElist)]]
uniqueOmegas <- unique(getOmega(outMobius))
uniqueOmegasOptim <- optim(par = uniqueOmegas, fn = stepOmega, indOmegas = omegaRestrictions,
objFMM = outMobius, omegaMax = omegaMax,
control = list(warn.1d.NelderMead = FALSE))$par
beta <- getBeta(outMobius)
alpha <- getAlpha(outMobius)
omega <- uniqueOmegasOptim[omegaRestrictions]
designMatrix <- calculateCosPhi(alpha = alpha, beta = beta, omega = omega, timePoints = timePoints)
regresion <- lm(vData ~ designMatrix)
M <- as.vector(coefficients(regresion)[1])
A <- as.vector(coefficients(regresion)[-1])
fittedFMMvalues <- predict(regresion)
SSE <- sum((fittedFMMvalues-vData)^2)
nIter <- getNIter(outMobius)
explainedVarOrder <- order(getR2(outMobius),decreasing = TRUE)
A <- A[explainedVarOrder]
alpha <- alpha[explainedVarOrder]
beta <- beta[explainedVarOrder]
omega <- omega[explainedVarOrder]
return(FMM(
M = M,
A = A,
alpha = alpha,
beta = beta,
omega = omega,
timePoints = timePoints,
summarizedData = vData,
fittedValues= fittedFMMvalues,
SSE = SSE,
R2 = PVj(vData, timePoints, alpha, beta, omega),
nIter = nIter
))
}
fitFMM_restr_omega_beta<-function(vData, nback, betaRestrictions, omegaRestrictions,
timePoints = seqTimes(length(vData)), maxiter = nback,
stopFunction = alwaysFalse, lengthAlphaGrid = 48, lengthOmegaGrid = 24,
alphaGrid = seq(0, 2*pi, length.out = lengthAlphaGrid), omegaMin = 0.0001, omegaMax = 1,
omegaGrid = exp(seq(log(omegaMin),log(omegaMax), length.out=lengthOmegaGrid)),
numReps = 3, showProgress = TRUE, parallelize = FALSE){
nObs <- length(vData)
if(showProgress){
totalMarks <- 50
partialMarkLength <- 2
progressHeader<-paste(c("|",rep("-",totalMarks),"|\n|"), collapse = "")
cat(progressHeader)
completedPercentage <- 0.00001
previousPercentage <- completedPercentage
}
numBlocks <- length(unique(omegaRestrictions))
fittedValuesPerBlock <- matrix(0, ncol = numBlocks, nrow = nObs)
fittedFMMPerBlock <- list()
prevFittedFMMvalues <- NULL
stopCriteria<-"Stopped by reaching maximum iterations ("
for(i in 1:maxiter){
blockIndex <- 1
for(j in unique(omegaRestrictions)){
currentBlock <- which(omegaRestrictions == j)
nCurrentBlock <- length(currentBlock)
backfittedData <- vData - apply(as.matrix(fittedValuesPerBlock[,-blockIndex]), 1, sum)
fittedFMMPerBlock[[blockIndex]] <- fitFMM_restr(backfittedData, nback = nCurrentBlock,
betaRestrictions = betaRestrictions[currentBlock],
omegaRestrictions = rep(1,nCurrentBlock),
timePoints = timePoints,
maxiter = ifelse(nCurrentBlock > 1,
min(nCurrentBlock + 1, 4), 1),
lengthAlphaGrid = lengthAlphaGrid, lengthOmegaGrid = lengthOmegaGrid,
alphaGrid = alphaGrid, omegaMax = omegaMax, omegaGrid = omegaGrid,
numReps = numReps, parallelize = parallelize)
fittedValuesPerBlock[,blockIndex] <- getFittedValues(fittedFMMPerBlock[[blockIndex]])
blockIndex <- blockIndex + 1
if(showProgress){
completedPercentage <- completedPercentage + 100/(nback*maxiter)
if(ceiling(previousPercentage) < floor(completedPercentage)){
progressDone <- paste(rep("=",sum((seq(ceiling(previousPercentage), floor(completedPercentage), by = 1)
%% partialMarkLength == 0))), collapse = "")
cat(progressDone)
previousPercentage <- completedPercentage
}
}
}
fittedFMMvalues <- apply(fittedValuesPerBlock, 1, sum)
if(!is.null(prevFittedFMMvalues)){
if(PV(vData, prevFittedFMMvalues) > PV(vData, fittedFMMvalues)){
fittedFMMPerBlock <- prevFittedFMMPerBlock
fittedFMMvalues <- prevFittedFMMvalues
stopCriteria <- "Stopped by reaching maximum R2 ("
break
}
if(stopFunction(vData, fittedFMMvalues, prevFittedFMMvalues)){
stopCriteria <- "Stopped by the stopFunction ("
break
}
}
prevFittedFMMvalues <- fittedFMMvalues
prevFittedFMMPerBlock <- fittedFMMPerBlock
}
nIter <- i
if(showProgress){
if(completedPercentage < 100){
completedPercentage <- 100
nMarks <- ifelse(ceiling(previousPercentage) < floor(completedPercentage),
sum((seq(ceiling(previousPercentage), floor(completedPercentage), by = 1)
%% partialMarkLength == 0)), 0)
if (nMarks > 0) {
cat(paste(rep("=",nMarks), collapse = ""))
previousPercentage <- completedPercentage
}
}
cat("|\n", paste(stopCriteria, nIter, sep = ""), "iteration(s))", "\n")
}
alpha <- unlist(lapply(fittedFMMPerBlock, getAlpha))
beta <- unlist(lapply(fittedFMMPerBlock, getBeta))
omega <- unlist(lapply(fittedFMMPerBlock, getOmega))
cosPhi <- calculateCosPhi(alpha = alpha, beta = beta, omega = omega, timePoints = timePoints)
regression <- lm(vData ~ cosPhi)
M <- as.vector(coefficients(regression)[1])
A <- as.vector(coefficients(regression)[-1])
fittedFMMvalues <- predict(regression)
SSE <- sum((fittedFMMvalues - vData)^2)
explainedVarOrder <- order(PVj(vData, timePoints, alpha, beta, omega),decreasing = TRUE)
A <- A[explainedVarOrder]
alpha <- alpha[explainedVarOrder]
beta <- beta[explainedVarOrder]
omega <- omega[explainedVarOrder]
return(FMM(
M = M,
A = A,
alpha = alpha,
beta = beta,
omega = omega,
timePoints = timePoints,
summarizedData = vData,
fittedValues = fittedFMMvalues,
SSE = SSE,
R2 = PVj(vData, timePoints, alpha, beta, omega),
nIter = nIter
))
} |
ScanCBSPlot <-
function(cases, controls, CBSObj, filename, mainTitle, CIObj=NULL, length.out=10000, localWindow=0.5*10^5, localSeparatePlot=TRUE, smoothF=0.025, xlabScale=10^6, width=12, height=18) {
p = length(cases)/(length(cases)+length(controls))
maxCase = max(cases)
maxControl = max(controls)
maxVal = max(c(maxCase, maxControl))
cpts = matrix(CBSObj$statHat[,c(1,2,5)], nrow=nrow(CBSObj$statHat))
tauHatFull = CBSObj$tauHat
tauHat = tauHatFull[c(-1, -length(tauHatFull))]
relCN = CBSObj$relCN
relCN[relCN <= 0] = 1
ylims = c(min(c(0, cpts[,3])), max(c(0, cpts[,3])))
if(!is.null(CIObj)) {
CIBounds = CIObj$CIRes[3:4,]
CIL = as.numeric(CIObj$CIRes[5,])
CIU = as.numeric(CIObj$CIRes[6,])
relCNCIL = CIL/(1-CIL+10^(-5))/(p/(1-p))
relCNCIU = CIU/(1-CIU+10^(-5))/(p/(1-p))
}
grid.fix = seq(1, maxVal, length.out=length.out)
gridSize = grid.fix[2]-grid.fix[1]
casesCountInGrid = getCountsInWindow(cases, 0, maxVal, gridSize, sorted=FALSE)
casesCountInGridSmooth = lowess(x=grid.fix, y=casesCountInGrid, smoothF)
casesCountInGridSmooth$y[casesCountInGridSmooth$y<0] = 0
controlCountInGrid = getCountsInWindow(controls, 0, maxVal, gridSize, sorted=FALSE)
controlCountInGridSmooth = lowess(x=grid.fix, y=controlCountInGrid, smoothF)
controlCountInGridSmooth$y[controlCountInGridSmooth$y<0] = 0
PInGrid = casesCountInGrid/(casesCountInGrid+controlCountInGrid)
PInGrid[is.nan(PInGrid)]=0
relCNInGrid = PInGrid/(1-PInGrid)/(p/(1-p))
relCNInGrid[is.nan(relCNInGrid) | !is.finite(relCNInGrid) | relCNInGrid <= 0]=1
relCNInGrid = log(relCNInGrid, base=2)
relCNlims = c(min(min(log(relCN, base=2)), min(relCNInGrid)), max(max(log(relCN, base=2)), max(relCNInGrid)))
PInGridSmooth = lowess(x=grid.fix, y=PInGrid, smoothF)
tauHatInGrid = grid.fix[tauHat %/% gridSize]/xlabScale
gridYLims = c(min(log(casesCountInGrid+1) - log(controlCountInGrid+1)), log(max(casesCountInGrid, controlCountInGrid)))
plotTauHatInd = c(min(min(cases),min(controls)), tauHat, maxVal) %/% gridSize
plotTauHatInd = sapply(plotTauHatInd, function(x) {max(x,1)})
plotTauHatInd = sapply(plotTauHatInd, function(x) {min(x,max(grid.fix))})
plotTauHat = grid.fix[plotTauHatInd]/xlabScale
pdf(paste(filename, ".pdf", sep=""), width=width, height=height)
par(mfrow=c(3,1))
plot(x=grid.fix/xlabScale, y=rep(0, length(grid.fix)), type="n", ylim=ylims, main=mainTitle, ylab="Statistic", xlab=paste("Base Pairs", xlabScale))
for(i in 1:nrow(cpts)) {
plotX = c(grid.fix[max(floor(cpts[i,1]/gridSize), 1)]/xlabScale, grid.fix[ceiling(cpts[i,2]/gridSize)]/xlabScale)
lines(x=plotX, y=rep(cpts[i,3],2), lwd=3)
}
abline(v=tauHatInGrid, lty=3, col=4)
matplot(x=grid.fix/xlabScale, y=log(cbind(casesCountInGridSmooth$y, controlCountInGridSmooth$y)+1), type="l", lty=c(1,1), col=c(2,1), main="Log Read Intensity", ylab="Read Intensity", xlab=paste("Base Pairs", xlabScale), ylim=gridYLims)
points(x=grid.fix/xlabScale, y=log(casesCountInGrid+1) - log(controlCountInGrid+1), pch=".", col=1)
abline(v=tauHatInGrid, lty=3, col=4)
legend("topright", c("case","control", "case-control"), pch=".", lty=c(1,1,0), col=c(2,1,1))
plot(x=grid.fix/xlabScale, y=relCNInGrid, type="p", pch=20, ylim=relCNlims, main="Log Relative Copy Number", ylab="Log2 Relative CN", xlab=paste("Base Pairs", xlabScale))
lines(x=plotTauHat, y=log(c(relCN, relCN[length(relCN)]), base=2), type="s", col="red")
dev.off()
nTauHat = length(tauHat)
if(localSeparatePlot == FALSE) {
nPlotCol = as.integer(sqrt(nTauHat/(height/width)))
nPlotRow = ceiling(nTauHat/nPlotCol)
pdf(paste(filename, "_localDetails.pdf", sep=""), width=width*2, height=height*2)
par(mfrow=c(nPlotRow, nPlotCol))
}
for(i in 1:nTauHat) {
if(localSeparatePlot) {
pdf(paste(filename, "_local_", i, "_", tauHat[i], ".pdf", sep=""), width=width, height=height/2, pointsize=24)
}
lBound = max(0, tauHat[i]-localWindow)
rBound = min(maxVal, tauHat[i]+localWindow)
localCas = cases[cases >= lBound & cases < rBound]
localCon = controls[controls >= lBound & controls < rBound]
grid.fix = seq(lBound, rBound, length.out=length.out/100)
gridSize = grid.fix[2]-grid.fix[1]
grid.mpt = grid.fix + gridSize/2
CasCountInGrid = getCountsInWindow(localCas, lBound, rBound, gridSize, sorted=FALSE)
ConCountInGrid = getCountsInWindow(localCon, lBound, rBound, gridSize, sorted=FALSE)
pInGrid = CasCountInGrid/(CasCountInGrid+ConCountInGrid)
pInGrid[is.nan(pInGrid)] = 0.0
combLocalCasCon = CombineCaseControlC(localCas, localCon)
plotReadRangeInd = combLocalCasCon$combL >= lBound & combLocalCasCon$combL <= rBound
plotReadX = combLocalCasCon$combL[plotReadRangeInd]
plotReadY = combLocalCasCon$combZ[plotReadRangeInd] > 0
plotPX = cbind(tauHatFull[-length(tauHatFull)], tauHatFull[-1])
pSegment = relCN*p/(1-p)/(1+relCN*p/(1-p))
plotPY = cbind(pSegment, pSegment)
if(!is.null(CIObj)) {
localCIBounds = (CIBounds[1,] <= rBound) & (CIBounds[2,] >= lBound)
localYLims = c(min(CIL[localCIBounds]), max(CIU[localCIBounds])) * c(0.8, 1.2)
if(is.nan(localYLims[1]) || !is.finite(localYLims[1])) localYLims[1] = 0
if(is.nan(localYLims[2]) || !is.finite(localYLims[2])) localYLims[2] = 1
}
else {
localYLims = c(0,1)
}
plot(x=1, y=1, type="n", xlim=c(lBound, rBound), xaxt="n", ylim=localYLims, main=paste("Reads and Inference around", tauHat[i]), xlab="Base Pair Locations", ylab="p(case read)", cex.main=0.75, cex.lab=0.75, cex.axis=0.75)
axis(side=1, at=plotReadX[!plotReadY], labels=FALSE, tcl=0.3)
axis(side=3, at=plotReadX[plotReadY], labels=FALSE, tcl=0.3)
axis(side=1, xaxp=c(lBound, rBound, 10), tcl=-0.5, cex.axis=0.75)
if(is.null(CIObj)) {
if(length(grid.mpt) != length(pInGrid)) {
grid.mpt = grid.mpt[1:max(length(grid.mpt), length(pInGrid))]
pInGrid = pInGrid[1:max(length(grid.mpt), length(pInGrid))]
}
points(x=grid.mpt, y=pInGrid, pch=20, col=3)
}
else {
for(j in 1:ncol(CIBounds)) {
lines(x=CIBounds[,j], y=rep(CIL[j],2), col="
lines(x=CIBounds[,j], y=rep(CIU[j],2), col="
}
}
for(j in 1:nrow(plotPY)) {
lines(x=plotPX[j,], y=plotPY[j,], lwd=3)
}
abline(v=tauHat, lty=3, lwd=2, col="
if(localSeparatePlot) {
dev.off()
}
}
if(localSeparatePlot == FALSE) dev.off()
} |
ff_starters.flea_conn <- function(conn, week = 1:17, ...) {
starters <- ff_schedule(conn, week) %>%
dplyr::filter(!is.na(.data$result)) %>%
dplyr::distinct(.data$week, .data$game_id) %>%
dplyr::mutate(starters = purrr::map2(.data$week, .data$game_id, .flea_starters, conn)) %>%
tidyr::unnest("starters") %>%
dplyr::arrange(.data$week, .data$franchise_id)
}
.flea_starters <- function(week, game_id, conn) {
x <- fleaflicker_getendpoint("FetchLeagueBoxscore",
sport = "NFL",
scoring_period = week,
fantasy_game_id = game_id,
league_id = conn$league_id
) %>%
purrr::pluck("content", "lineups") %>%
list() %>%
tibble::tibble() %>%
tidyr::unnest_longer(1) %>%
tidyr::unnest_wider(1) %>%
tidyr::unnest_longer("slots") %>%
tidyr::unnest_wider("slots") %>%
dplyr::mutate(
position = purrr::map_chr(.data$position, purrr::pluck, "label"),
positionColor = NULL
) %>%
tidyr::pivot_longer(c("home", "away"), names_to = "franchise", values_to = "player") %>%
tidyr::hoist("player", "proPlayer", "owner", "points" = "viewingActualPoints") %>%
tidyr::hoist("proPlayer",
"player_id" = "id",
"player_name" = "nameFull",
"pos" = "position",
"team" = "proTeamAbbreviation"
) %>%
dplyr::filter(!is.na(.data$player_id)) %>%
tidyr::hoist("owner", "franchise_id" = "id", "franchise_name" = "name") %>%
tidyr::hoist("points", "player_score" = "value") %>%
dplyr::select(dplyr::any_of(c(
"franchise_id",
"franchise_name",
"starter_status" = "position",
"player_id",
"player_name",
"pos",
"team",
"player_score"
)))
return(x)
} |
test_that("score_type3",
{
correct_s3_r <- c(387)
correct_s3_p <- c(387)
correct_s3_d <- c(387)
expect_equal(which(score_type3(a, w2) > thr2 & lp2), correct_s3_r)
expect_equal(which(score_type3(a, w2, "periodic") > thr2 & lp2), correct_s3_p)
expect_equal_na_allowed(which(score_type3(a, w2, "discard") > thr2 & lp2), correct_s3_d)
}) |
WCY <- function(x, d, zc = rep(1, length(d)),
wt = rep(1,length(d)), maxit = 25, error = 1e-09)
{
xvec <- as.vector(x)
nn <- length(xvec)
if (nn <= 1)
stop("Need more observations")
if (length(d) != nn)
stop("length of x and d must agree")
if (any((d != 0) & (d != 1) & (d != 2)))
stop("d must be 0(right-censored) or 1(uncensored) or 2(left-censored)")
if (!is.numeric(xvec))
stop("x must be numeric")
temp <- Wdataclean3(z=xvec, d=d, zc=zc, wt=wt)
x <- temp$value
d <- temp$dd
w <- temp$weight
INDEX10 <- which(d != 2)
d[INDEX10[length(INDEX10)]] <- 1
INDEX12 <- which(d != 0)
d[INDEX12[1]] <- 1
xd1 <- x[d == 1]
if (length(xd1) <= 1)
stop("need more distinct uncensored obs.")
xd0 <- x[d == 0]
xd2 <- x[d == 2]
wd1 <- w[d == 1]
wd0 <- w[d == 0]
wd2 <- w[d == 2]
m <- length(xd0)
mleft <- length(xd2)
if ((m > 0) && (mleft > 0)) {
pnew <- wd1/sum(wd1)
n <- length(pnew)
k <- rep(NA, m)
for (i in 1:m) {
k[i] <- 1 + n - sum(xd1 > xd0[i])
}
kk <- rep(NA, mleft)
for (j in 1:mleft) {
kk[j] <- sum(xd1 < xd2[j])
}
num <- 1
while (num < maxit) {
wd1new <- wd1
sur <- cumsumsurv(pnew)
cdf <- 1 - c(sur[-1], 0)
for (i in 1:m) {
wd1new[k[i]:n] <- wd1new[k[i]:n] + wd0[i] * pnew[k[i]:n]/sur[k[i]]
}
for (j in 1:mleft) {
wd1new[1:kk[j]] <- wd1new[1:kk[j]] + wd2[j] * pnew[1:kk[j]]/cdf[kk[j]]
}
pnew <- wd1new/sum(wd1new)
num <- num + 1
}
sur <- cumsumsurv(pnew)
cdf <- 1 - c(sur[-1], 0)
logel<-sum(wd1*log(pnew))+sum(wd0*log(sur[k])) + sum(wd2*log(cdf[kk]))
}
return(list(logEL=logel, time=xd1, jump=pnew, surv=1-cdf, prob=cdf))
} |
.classVectorChecker <- function(dataSet){
checkMark <- FALSE
if(length(dataSet$class) == ncol(dataSet$expr)){
if(length(which(dataSet$class==0)) > 1 && length(which(dataSet$class==1)) > 1){
checkMark <- TRUE
}
}
return(checkMark)
}
.leaveOneOutMetaAnalysisWrapper <- function(originalData,
old = FALSE, maxCores=Inf){
max_cores <- min(length(originalData), maxCores)
if(max_cores>10){
max_cores <- 10
}
return(mclapply(1:length(originalData),
function(i)
invisible(.runMetaAnalysisCore(originalData[-i],old=old)),
mc.cores = max_cores))
}
.runMetaAnalysisCore <- function(originalData,
old = FALSE){
annDB <- .createAnnTable(originalData[[1]])
if(length(originalData) > 1) {
for(i in 2:length(originalData)) {
tempAnnTable <- .createAnnTable(originalData[[i]])
commonProbes <- match(annDB[,1], tempAnnTable[,1])
commonProbes <- commonProbes[!is.na(commonProbes)]
if(length(commonProbes) > 0) {
cat("Found common probes in", i, "\n", sep=" ")
tempAnnTable <- tempAnnTable[-commonProbes,]
}
annDB = rbind(annDB, tempAnnTable)
}
}
rownames(annDB) <- annDB[,1]
annDB <- as.matrix(annDB[,2])
colnames(annDB) <- c("symbol")
cat("Computing effect sizes...")
all.ES <- lapply( originalData,.effect.sizes)
output.REM <- .combine.effect.sizes( all.ES )
cat("\nComputing summary effect sizes...")
pooled.ES <- output.REM$pooled.estimates
pooled.ES$p.fdr <- stats::p.adjust( pooled.ES$p.value, method="fdr" )
pooled.ES <- pooled.ES[ order(pooled.ES$p.fdr), ]
output.Fisher <- NULL
if(old==TRUE){
cat("\nComputing Q-values...")
all.Qvals <- lapply(originalData, .ttest.Qvalues)
cat("\nComputing Fisher's output...")
output.Fisher <- .sum.of.logs(all.Qvals)
}else{
.adjust.fisher <- function(output.Fisher, method="fdr"){
F.Qval.up <- stats::p.adjust(output.Fisher[, "F.pval.up"], method=method)
F.Qval.down <- stats::p.adjust(output.Fisher[, "F.pval.down"], method=method)
return(cbind(output.Fisher, F.Qval.up, F.Qval.down))
}
cat("\nComputing Fisher's output...")
all.Pvals <- lapply(originalData, .ttest.Pvalues)
output.Fisher <- .sum.of.logs(all.Pvals)
output.Fisher <- .adjust.fisher(output.Fisher = output.Fisher)
}
datasetEffectSizes <- output.REM$g
colnames(datasetEffectSizes) <- as.character(strsplit(colnames(datasetEffectSizes), "_g"))
datasetEffectSizeStandardErrors <- output.REM$se.g
colnames(datasetEffectSizeStandardErrors) <- as.character(strsplit(colnames(datasetEffectSizeStandardErrors), "_se.g"))
pooledResults <- pooled.ES[,c('summary',
'se.summary',
'p.value',
'p.fdr',
'tau2',
'n.studies',
'Q',
'pval.het')]
colnames(pooledResults) <- c("effectSize",
"effectSizeStandardError",
"effectSizePval",
"effectSizeFDR",
"tauSquared",
"numStudies",
"cochranesQ",
"heterogeneityPval")
output.Fisher <- output.Fisher[,c('F.stat.up',
'F.pval.up',
'F.Qval.up',
'F.stat.down',
'F.pval.down',
'F.Qval.down')]
colnames(output.Fisher) <- c("fisherStatUp",
"fisherPvalUp",
"fisherFDRUp",
"fisherStatDown",
"fisherPvalDown",
"fisherFDRDown")
pooledResults <- merge(pooledResults,output.Fisher,by=0)
row.names(pooledResults) <- pooledResults$Row.names
pooledResults$Row.names <- NULL
pooledResults <- pooledResults[order(pooledResults$effectSizeFDR,pooledResults$effectSizePval),]
analysisDescription <- "MetaAnalysis: Random Effects Model"
return(list(datasetEffectSizes = datasetEffectSizes,
datasetEffectSizeStandardErrors = datasetEffectSizeStandardErrors,
pooledResults = pooledResults,
analysisDescription = analysisDescription))
}
.originalDataNameChecker <- function(metaObject){
return(all(make.names(names(metaObject$originalData)) == names(metaObject$originalData)))
}
.originalDataNameConverter <- function(metaObject){
if(.originalDataNameChecker(metaObject) == FALSE){
old_names <- names(metaObject$originalData)
new_names <- make.names(old_names)
for(i in 1:length(metaObject$originalData)){
if(is.null(metaObject$originalData[[i]]$formattedName) | metaObject$originalData[[i]]$formattedName =="") {
metaObject$originalData[[i]]$formattedName <- old_names[i]
}
}
names(metaObject$originalData) <- new_names
}
return(metaObject)
}
.filterMetaRun <- function(metaAnalysis,
effectSizeThresh = 0,
effectFDRSizeThresh = 0.05,
fisherFDRThresh = 0.05,
numberStudiesThresh = 1,
heterogeneityPvalThresh = 0.05){
final_results <- metaAnalysis$pooledResults
final_results <- final_results[which(abs(final_results$effectSize) >= effectSizeThresh), ]
final_results <- final_results[which(final_results$effectSizeFDR <= effectFDRSizeThresh), ]
final_results <- final_results[which(final_results$numStudies >= numberStudiesThresh), ]
if(heterogeneityPvalThresh > 0){
final_results <- final_results[which(final_results$heterogeneityPval >= heterogeneityPvalThresh),]
}
posGeneNames <- row.names(final_results[intersect(which(final_results$fisherFDRUp <= fisherFDRThresh),which(final_results$effectSize > 0)),])
negGeneNames <- row.names(final_results[intersect(which(final_results$fisherFDRDown <= fisherFDRThresh),which(final_results$effectSize < 0)),])
final_list <- list(posGeneNames = posGeneNames,
negGeneNames = negGeneNames,
effectSizeThresh = effectSizeThresh,
FDRThresh = effectFDRSizeThresh,
numberStudiesThresh = numberStudiesThresh,
heterogeneityPvalThresh = heterogeneityPvalThresh)
return(final_list)
}
.plotESdistribution <- function(metaObject){
es_plot <- ggplot(reshape2::melt(metaObject$metaAnalysis$datasetEffectSizes, varnames=c("Gene", "Study")),
aes_string(x = "value",
colour = "Study")) +
geom_density(size = 1.1) +
theme_bw() +
scale_color_discrete(name = 'Dataset')
return(es_plot)
} |
snapread <-
function(file){
data = file(file,'rb')
block=readBin(data,'integer',n=1)
Npart=readBin(data,'integer',n=6)
Massarr=readBin(data,'numeric',n=6,size=8)
Time=readBin(data,'numeric',n=1,size=8)
z=readBin(data,'numeric',n=1,size=8)
FlagSfr=readBin(data,'integer',n=1)
FlagFeedback=readBin(data,'integer',n=1)
Nall=readBin(data,'integer',n=6)
FlagCooling=readBin(data,'integer',n=1)
NumFiles=readBin(data,'integer',n=1)
BoxSize=readBin(data,'numeric',n=1,size=8)
OmegaM=readBin(data,'numeric',n=1,size=8)
OmegaL=readBin(data,'numeric',n=1,size=8)
h=readBin(data,'numeric',n=1,size=8)
FlagAge=readBin(data,'integer',n=1)
FlagMetals=readBin(data,'integer',n=1)
NallHW=readBin(data,'integer',n=6)
flag_entr_ics=readBin(data,'integer',n=1)
readBin(data,'integer',n=256-241)
block=readBin(data,'integer',n=1)
block=readBin(data,'integer',n=1)
posall=readBin(data,'numeric',n=block/4,size=4)
block=readBin(data,'integer',n=1)
block=readBin(data,'integer',n=1)
velall=readBin(data,'numeric',n=block/4,size=4)
block=readBin(data,'integer',n=1)
block=readBin(data,'integer',n=1)
ID=readBin(data,'integer',n=block/4)
block=readBin(data,'integer',n=1)
block=readBin(data,'integer',n=1)
if(length(block)>0){
Mass=readBin(data,'numeric',n=block/4,size=4)
}else{
counter=1
Mass=rep(NA,sum(Npart))
whichmass=which(Npart>0)
for(i in 1:length(whichmass)){
N=Npart[whichmass[i]]
Mass[ID>=counter & ID<=counter+N]=Massarr[whichmass[i]]
counter=counter+N
}
}
block=readBin(data,'integer',n=1)
extra=0
extramat={}
while(length(block)>0){
block=readBin(data,'integer',n=1)
if(length(block)>0){
extramat=cbind(extramat,readBin(data,'numeric',n=block/4,size=4))
block=readBin(data,'integer',n=1)
extra=extra+1
}
}
close(data)
extract=((1:sum(Npart))*3)-2
part=data.frame(ID=ID,x=posall[extract],y=posall[extract+1],z=posall[extract+2],vx=velall[extract],vy=velall[extract+1],vz=velall[extract+2],Mass=Mass)
return(list(part=part,head=list(Npart = Npart, Massarr= Massarr, Time= Time, z= z, FlagSfr= FlagSfr, FlagFeedback= FlagFeedback, Nall= Nall, FlagCooling= FlagCooling, NumFiles= NumFiles, BoxSize= BoxSize, OmegaM= OmegaM, OmegaL= OmegaL,h=h, FlagAge= FlagAge, FlagMetals= FlagMetals, NallHW= NallHW,flag_entr_ics=flag_entr_ics),extra=extra,extramat=extramat))} |
context("AppenderFileRotating")
setup({
td <- file.path(tempdir(), "lgr")
assign("td", td, parent.env(environment()))
dir.create(td, recursive = TRUE)
})
teardown({
unlink(td, recursive = TRUE)
})
assert_supported_rotor_version <- function(){
if (packageVersion("rotor") < "0.3.0")
skip("rotor < 0.3.0 is no longer supported")
}
test_that("AppenderFileRotating: works as expected", {
if (!is_zipcmd_available())
skip("Test requires a workings system zip command")
assert_supported_rotor_version()
tf <- file.path(td, "test.log")
app <- AppenderFileRotating$new(file = tf, size = "1tb")
lg <-
lgr::get_logger("test")$
set_propagate(FALSE)$
set_appenders(app)
on.exit({
lg$config(NULL)
file.remove(tf)
app$prune(0)
})
expect_identical(app, lg$appenders[[1]])
lg$fatal("test973")
expect_true(file.exists(app$file))
expect_length(readLines(app$file), 1)
expect_match(readLines(app$file), "test973")
app$rotate(force = TRUE)
expect_gt(lg$appenders[[1]]$backups[1, ]$size, 0L)
expect_identical(nrow(lg$appenders[[1]]$backups), 1L)
expect_length(readLines(app$file), 0)
expect_match(readLines(app$backups$path[[1]]), "test973")
app$rotate(force = TRUE)
expect_equal(app$backups[1, ]$size, 0)
expect_identical(nrow(lg$appenders[[1]]$backups), 2L)
lg$fatal("test987")
lg$appenders[[1]]$set_compression(TRUE)
lg$appenders[[1]]$rotate(force = TRUE)
expect_identical(lg$appenders[[1]]$backups$ext, c("log.zip", "log", "log"))
expect_identical(lg$appenders[[1]]$backups$sfx, as.character(1:3))
con <- unz(app$backups$path[[1]], filename = "test.log")
on.exit(close(con), add = TRUE)
expect_match(readLines(con), "test987")
expect_identical(nrow(app$prune(0)$backups), 0L)
})
test_that("AppenderFileRotating: works with different backup_dir", {
if (!is_zipcmd_available())
skip("Test requires a workings system zip command")
assert_supported_rotor_version()
tf <- file.path(td, "test.log")
bu_dir <- file.path(td, "backups")
expect_error(
app <- AppenderFileRotating$new(file = tf, backup_dir = bu_dir),
class = "DirDoesNotExistError"
)
dir.create(bu_dir)
app <- AppenderFileRotating$new(
file = tf,
backup_dir = bu_dir,
size = 10
)
lg <- get_logger("test")$
set_propagate(FALSE)$
add_appender(app)
on.exit({
app$prune(0)
lg$config(NULL)
unlink(c(tf, bu_dir), recursive = TRUE)
})
lg$info(paste(LETTERS, collapse = "-"))
app$set_compression(TRUE)
lg$info(paste(letters, collapse = "-"))
expect_equal(file.size(tf), 0)
expect_equal(list.files(bu_dir), basename(app$backups$path))
expect_setequal(app$backups$ext, c("log.zip", "log"))
expect_match(app$backups$path[[1]], "lgr/backups")
expect_match(app$backups$path[[2]], "lgr/backups")
con <- unz(app$backups$path[[1]], filename = "test.log")
on.exit(close(con), add = TRUE)
expect_match(readLines(con), "a-b-.*-y-z")
expect_match(readLines(app$backups$path[[2]]), "A-B-.*-Y-Z")
file.remove(app$backups$path)
})
test_that("AppenderFileRotating: `size` argument works as expected", {
assert_supported_rotor_version()
tf <- file.path(td, "test.log")
app <- AppenderFileRotating$new(file = tf)$set_size(-1)
saveRDS(iris, app$file)
on.exit({
unlink(tf)
app$prune(0)
})
app$set_size("3 KiB")
app$rotate()
expect_identical(nrow(app$backups), 0L)
app$set_size("0.5 KiB")
app$rotate()
expect_identical(nrow(app$backups), 1L)
expect_gt(app$backups$size[[1]], 10)
expect_equal(file.size(app$file), 0)
})
test_that("AppenderFileRotatingDate: works as expected", {
if (!is_zipcmd_available())
skip("Test requires a workings system zip command")
assert_supported_rotor_version()
tf <- file.path(td, "test.log")
app <- AppenderFileRotatingDate$new(file = tf, size = "1tb")
lg <-
lgr::get_logger("test")$
set_propagate(FALSE)$
set_appenders(app)
on.exit({
lg$config(NULL)
file.remove(tf)
app$prune(0)
})
expect_identical(app, lg$appenders[[1]])
lg$fatal("test341")
expect_true(file.exists(app$file))
expect_length(readLines(app$file), 1)
expect_match(readLines(app$file), "test341")
expect_identical(nrow(app$backups), 0L)
app$set_size(-1)$set_age("1 day")
app$rotate(now = as.Date("2019-01-01"), force = TRUE)
expect_identical(nrow(app$backups), 1L)
expect_gt(lg$appenders[[1]]$backups[1, ]$size, 0L)
expect_length(readLines(app$file), 0)
expect_match(app$backups$path[[1]], "2019-01-01")
expect_match(readLines(app$backups$path[[1]]), "test341")
app$rotate(now = "2019-01-02")
expect_identical(nrow(app$backups), 2L)
expect_equal(app$backups[1, ]$size, 0)
expect_match(app$backups$path[[1]], "2019-01-02")
app$set_age("10000 years")
lg$fatal("test938")
app$set_age("1 day")
lg$appenders[[1]]$set_compression(TRUE)
lg$appenders[[1]]$rotate(now = as.Date("2019-01-03"))
expect_identical(nrow(app$backups), 3L)
expect_identical(app$backups$ext, c("log.zip", "log", "log"))
expect_identical(lg$appenders[[1]]$backups$sfx, c("2019-01-03", "2019-01-02", "2019-01-01"))
con <- unz(app$backups$path[[1]], filename = "test.log")
on.exit(close(con), add = TRUE)
expect_match(readLines(con), "test938")
expect_identical(nrow(app$prune(0)$backups), 0L)
})
test_that("AppenderFileRotatingDate: works with different backup_dir", {
if (!is_zipcmd_available())
skip("Test requires a workings system zip command")
assert_supported_rotor_version()
tf <- file.path(td, "test.log")
bu_dir <- file.path(td, "backups")
expect_error(
app <- AppenderFileRotatingDate$new(file = tf, backup_dir = bu_dir)
)
dir.create(bu_dir)
app <- AppenderFileRotatingDate$new(
file = tf,
backup_dir = bu_dir,
size = 100
)
lg <- get_logger("test")$set_propagate(FALSE)
lg$add_appender(app)
on.exit({
app$prune(0)
unlink(c(tf, bu_dir), recursive = TRUE)
lg$config(NULL)
})
app$set_age(-1)$set_size(-1)
lg$info(paste(LETTERS))
app$set_compression(TRUE)
lg$info(paste(LETTERS))
expect_equal(file.size(tf), 0)
expect_equal(list.files(bu_dir), basename(app$backups$path))
expect_setequal(app$backups$ext, c("log.zip", "log"))
file.remove(app$backups$path)
})
test_that("AppenderFileRotatingDate: `size` and `age` arguments work as expected", {
assert_supported_rotor_version()
tf <- file.path(td, "test.log")
app <- AppenderFileRotatingDate$new(file = tf)$set_age(-1)
saveRDS(iris, app$file)
on.exit({
unlink(tf)
app$prune(0)
})
app$set_size("3 KiB")
app$rotate()
expect_identical(nrow(app$backups), 0L)
app$set_size("0.5 KiB")
app$rotate(now = "2999-01-01")
expect_identical(nrow(app$backups), 1L)
app$set_size(-1)
app$set_age("1 day")
app$rotate(now = "2999-01-01")
expect_identical(nrow(app$backups), 1L)
app$rotate(now = "2999-01-02")
expect_identical(nrow(app$backups), 2L)
})
test_that("AppenderFileRotatingTime: works as expected", {
if (!is_zipcmd_available())
skip("Test requires a workings system zip command")
assert_supported_rotor_version()
tf <- file.path(td, "test.log")
app <- AppenderFileRotatingTime$new(file = tf)
lg <-
lgr::get_logger("test")$
set_propagate(FALSE)$
set_appenders(app)
on.exit({
app$prune(0)
lg$config(NULL)
unlink(tf)
})
lg$fatal("test")
app$set_size(-1)
app$set_age(-1)
app$rotate(now = "2999-01-03--12-01")
expect_gt(app$backups[1, ]$size, 0)
expect_match(app$backups[1, ]$path, "2999-01-03--12-01-00")
lg$appenders[[1]]$rotate(now = "2999-01-03--12-02")
expect_equal(lg$appenders[[1]]$backups[1, ]$size, 0)
expect_match(app$backups[1, ]$path, "2999-01-03--12-02-00")
lg$appenders[[1]]$set_compression(TRUE)
lg$appenders[[1]]$rotate(now = "2999-01-03--12-03")
expect_identical(lg$appenders[[1]]$backups$ext, c("log.zip", "log", "log"))
expect_match(app$backups[1, ]$path, "2999-01-03--12-03-00.log.zip")
app$prune(0)
expect_identical(nrow(app$backups), 0L)
lg$config(NULL)
})
test_that("AppenderFileRotatingTime: works with different backup_dir", {
if (!is_zipcmd_available())
skip("Test requires a workings system zip command")
assert_supported_rotor_version()
tf <- file.path(td, "test.log")
bu_dir <- file.path(td, "backups")
expect_error(
app <- AppenderFileRotatingTime$new(file = tf, backup_dir = bu_dir)
)
dir.create(bu_dir)
app <- AppenderFileRotatingTime$new(
file = tf,
backup_dir = bu_dir,
size = 100,
age = -1
)
lg <- get_logger("test")$
set_propagate(FALSE)$
add_appender(app)
on.exit({
app$prune(0)
unlink(c(tf, bu_dir), recursive = TRUE)
lg$config(NULL)
})
lg$info(paste(LETTERS))
app$set_compression(TRUE)
Sys.sleep(1)
lg$info(paste(LETTERS))
expect_equal(file.size(tf), 0)
expect_equal(rev(list.files(bu_dir)), basename(app$backups$path))
expect_equal(app$backups$ext, c("log.zip", "log"))
file.remove(app$backups$path)
})
test_that("AppenderFileRotatingTime: `size` and `age` arguments work as expected", {
tf <- file.path(td, "test.log")
app <- AppenderFileRotatingTime$new(file = tf)$set_age(-1)
saveRDS(iris, app$file)
on.exit({
unlink(tf)
app$prune(0)
})
app$set_size(file.size(tf) + 2)
app$rotate()
expect_identical(nrow(app$backups), 0L)
app$set_size(file.size(tf) / 2)
app$rotate(now = "2999-01-01")
expect_identical(nrow(app$backups), 1L)
app$set_size(-1)
app$set_age("1 day")
app$rotate(now = "2999-01-01")
expect_identical(nrow(app$backups), 1L)
app$rotate(now = "2999-01-02")
expect_identical(nrow(app$backups), 2L)
})
test_that("AppenderFileRotatingTime: `size` and `age` arguments work as expected
tf <- file.path(td, "test.log")
log_dir <- file.path(td, "backups")
dir.create(log_dir)
app <- AppenderFileRotatingTime$new(
file = tf,
layout = LayoutJson$new(),
age = -1,
size = "0.5 kb",
max_backups = 5,
backup_dir = log_dir,
overwrite = FALSE,
compression = FALSE,
threshold = "info"
)
on.exit({
unlink(tf)
unlink(log_dir, recursive = TRUE)
app$prune(0)
})
lg <- get_logger("test_issue_39")$
set_propagate(FALSE)$
set_appenders(list(rotating = app))
for (i in 1:100){
lg$info("test")
if (nrow(lg$appenders$rotating$backups) >= 1)
break
}
expect_identical(nrow(lg$appenders$rotating$backups), 1L)
expect_length(list.files(log_dir), 1)
}) |
"%w/o%" <- function( x, y ) x[ !x %in% y ] |
source("ESEUR_config.r")
plot_layout(2, 1)
pal_col=rainbow(2)
depth=read.csv(paste0(ESEUR_dir, "sourcecode/pani-depth.csv.xz"), as.is=TRUE)
depth=subset(depth, (num > 0) & (bound > 0))
cbench=subset(depth, project == "cBench")
CU=subset(depth, project == "coreutils")
fit_expo=function(df)
{
plot(df$num, df$bound, log="y", col=pal_col[2],
xlab="Basic block depth", ylab="Loops\n")
cb_mod=glm(log(bound) ~ num, data=df, subset=(num > 2))
summary(cb_mod)
pred=predict(cb_mod)
lines(df$num[3:25], exp(pred), col=pal_col[1])
return(cb_mod)
}
cb_mod=fit_expo(cbench[1:25, ])
fit_power=function(df)
{
plot(df$num, df$bound, log="xy", col=pal_col[2],
xlab="Basic block depth", ylab="Loops\n")
cb_mod=glm(log(bound) ~ log(num), data=df, subset=(num < 11))
summary(cb_mod)
pred=predict(cb_mod)
lines(df$num[1:10], exp(pred), col=pal_col[1])
return(cb_mod)
}
cb_mod=fit_power(cbench[1:25, ]) |
d = suppressWarnings(subOrigData(taxon = "Homo sapiens", dataset = 10, mask = naMap))
test_that("suOrigData works",{
expect_equal(class(d), "subOrigData")
expect_is(d$data, "SpatialPointsDataFrame")
expect_error(suppressWarnings(subOrigData(taxon = "Turdus philomelos", mask = naMap)))
expect_error(subOrigData(taxon = "Turdus philomelos", marker = "d14C"))
expect_warning(subOrigData(taxon = "Serin serin",
age_code = c("juvenile", "newborn"),
ref_scale = NULL))
expect_warning(subOrigData(taxon = c("Serin serin", "Vanellus malabaricus"),
ref_scale = NULL))
expect_warning(subOrigData(group = c("Indigenous human", "Badgers"),
ref_scale = NULL))
expect_warning(subOrigData(dataset = c(8, "Ma 2020"),
ref_scale = NULL))
expect_warning(subOrigData(dataset = c(8, 100),
ref_scale = NULL))
})
d_hasNA = d
d_hasNA$data$d2H[1] = NA
d_diffProj = d
d_diffProj$data = suppressWarnings(spTransform(d$data, "+init=epsg:28992"))
d_usr_bad = d$data
d_usr_good = d_usr_bad
d_usr_good@data = data.frame(d$data$d2H, d$data$d2H.sd)
d_noCRS = d
crs(d_noCRS$data) = NA
d2h_lrNA_noCRS = d2h_lrNA
crs(d2h_lrNA_noCRS) = NA
mask_diffProj = suppressWarnings(spTransform(naMap, "+init=epsg:28992"))
mask_noCRS = naMap
crs(mask_noCRS) = NA
tempVals = getValues(d2h_lrNA)
tempVals[is.nan(tempVals)] = 9999
d2h_lrNA_with9999 = setValues(d2h_lrNA, tempVals)
s1 = states[states$STATE_ABBR == "UT",]
d2h_lrNA_na = mask(d2h_lrNA, s1)
r = suppressWarnings(calRaster(known = d, isoscape = d2h_lrNA_with9999, NA.value = 9999,
interpMethod = 1, genplot = FALSE, mask = naMap))
test_that("calRaster works",{
expect_is(r, "rescale")
expect_is(suppressWarnings(calRaster(known = d_usr_good, isoscape = d2h_lrNA,
genplot = FALSE)), "rescale")
expect_output(suppressWarnings(calRaster(known = d, isoscape = d2h_lrNA,
outDir = tempdir())))
expect_equal(nlayers(r$isoscape.rescale), 2)
expect_error(calRaster(known = d$data$d2H, isoscape = d2h_lrNA))
expect_error(suppressWarnings(calRaster(known = d, isoscape = d2h_lrNA,
outDir = 2)))
expect_error(suppressWarnings(calRaster(known = d, isoscape = d2h_lrNA,
interpMethod = 3)))
expect_error(suppressWarnings(calRaster(known = d, isoscape = d2h_lrNA,
genplot = 2)))
expect_error(calRaster(known = d, isoscape = d2h_lrNA_noCRS))
expect_error(calRaster(known = d, isoscape = d2h_lrNA$mean))
expect_error(calRaster(known = d_usr_bad, isoscape = d2h_lrNA))
expect_error(suppressWarnings(calRaster(known = d, isoscape = d2h_lrNA,
mask = mask_noCRS)))
expect_error(suppressWarnings(calRaster(known = d, isoscape = d2h_lrNA,
mask = d)))
expect_error(suppressWarnings(calRaster(known = d_noCRS,
isoscape = d2h_lrNA)))
expect_error(suppressWarnings(calRaster(known = d_hasNA, isoscape = d2h_lrNA,
ignore.NA = FALSE)))
expect_error(suppressWarnings(calRaster(known = d, isoscape = d2h_lrNA_na,
ignore.NA = FALSE)))
expect_message(suppressWarnings(calRaster(known = d_diffProj,
isoscape = d2h_lrNA)))
expect_warning(calRaster(known = d, isoscape = d2h_lrNA, mask = mask_diffProj))
expect_warning(calRaster(known = d, isoscape = d2h_lrNA_na))
})
id = c("A", "B", "C", "D")
d2H = c(-110, -90, -105, -102)
un = data.frame(id,d2H)
asn = suppressWarnings(pdRaster(r, unknown = un, mask = naMap))
j = jointP(asn)
test_that("jointP works",{
expect_equal(cellStats(j, sum), 1)
expect_is(j, "RasterLayer")
expect_error(jointP(d))
})
u = unionP(asn)
test_that("unionP works",{
expect_is(u, "RasterLayer")
expect_error(unionP(d2H))
})
s1 = states[states$STATE_ABBR == "UT",]
s2 = states[states$STATE_ABBR == "NM",]
s12 = rbind(s1, s2)
o1 = suppressWarnings(oddsRatio(asn, s12))
pp1 = c(-112,40)
pp2 = c(-105,33)
pp12 = SpatialPoints(coords = rbind(pp1,pp2),
proj4string=CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
o2 = suppressWarnings(oddsRatio(asn, pp12))
o3 = suppressWarnings(oddsRatio(asn, pp12[1]))
o4 = suppressWarnings(oddsRatio(asn$A, pp12))
o5 = suppressWarnings(oddsRatio(asn$A, s12))
s12_diffProj = suppressWarnings(spTransform(s12, CRS("+init=epsg:28992")))
pp12_diffProj = suppressWarnings(spTransform(pp12, CRS("+init=epsg:28992")))
pp12_noCRS = pp12
crs(pp12_noCRS) = NA
s12_noCRS = s12
crs(s12_noCRS) = NA
pp121 = SpatialPoints(coords = rbind(pp1, pp2, pp3 = pp1),
proj4string=CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
test_that("oddsRatio works",{
expect_is(o1, "list")
expect_is(o2, "list")
expect_is(o3, "data.frame")
expect_is(o4, "list")
expect_is(o5, "list")
expect_error(oddsRatio(naMap,s12))
expect_error(oddsRatio(asn, data.frame(30.6, 50.5)))
expect_error(oddsRatio(asn, s12_noCRS))
expect_error(suppressWarnings(oddsRatio(asn, pp121)))
expect_error(oddsRatio(asn, s1))
expect_error(oddsRatio(asn, pp12_noCRS))
expect_message(suppressWarnings(oddsRatio(asn, s12_diffProj)))
expect_message(suppressWarnings(oddsRatio(asn, pp12_diffProj)))
})
q1 = qtlRaster(asn, threshold = 0.1, thresholdType = "area", outDir = tempdir())
q2 = qtlRaster(asn, threshold = 0.1, thresholdType = "prob", genplot = FALSE)
q3 = qtlRaster(asn, threshold = 0, genplot = FALSE)
test_that("qtlRaster works",{
expect_is(q1, "RasterStack")
expect_equal(nlayers(q1), 4)
expect_equal(nlayers(q2), 4)
expect_equal(nlayers(q3), 4)
expect_error(qtlRaster(asn, threshold = "a"))
expect_error(qtlRaster(asn, threshold = 10))
expect_error(qtlRaster(asn, threshold = "a"), thresholdType = "probability")
expect_error(qtlRaster(asn, threshold = 0.1, genplot = "A"))
expect_error(qtlRaster(asn, threshold = 0.1, outDir = 1))
}) |
.writeHdrENVI <- function(r) {
hdrfile <- filename(r)
extension(hdrfile) <- ".hdr"
thefile <- file(hdrfile, "w")
cat("ENVI\n", file = thefile)
cat("samples = ", ncol(r), "\n", file = thefile)
cat("lines = ", nrow(r), "\n", file = thefile)
cat("bands = ", r@file@nbands, "\n", file = thefile)
cat("header offset = 0\n", file = thefile)
cat("file type = ENVI Standard\n", file = thefile)
dsize <- dataSize(r@file@datanotation)
if (.shortDataType(r@file@datanotation) == 'INT') {
if (dsize == 1) { dtype <- 1
} else if (dsize == 2) { dtype <- 2
} else if (dsize == 4) { dtype <- 3
} else if (dsize == 8) { dtype <- 14
} else { stop('what?')
}
} else {
if (dsize == 4) { dtype <- 4
} else if (dsize == 8) { dtype <- 5
} else { stop('what?')
}
}
cat("data type = ", dtype, "\n", file = thefile)
cat("data ignore value=", .nodatavalue(r), "\n", file = thefile, sep='')
cat("interleave = ", r@file@bandorder, "\n", file = thefile)
cat("sensor type = \n", file = thefile)
btorder <- as.integer(r@file@byteorder != 'little')
cat("byte order = ", btorder, "\n",file = thefile)
if (couldBeLonLat(r)) {
cat("map info = {Geographic Lat/Lon, 1, 1,", xmin(r),", ", ymax(r),", ", xres(r),", ", yres(r), "}\n", file = thefile)
} else {
cat("map info = {projection, 1, 1,", xmin(r),", ", ymax(r),", ", xres(r),", ", yres(r), "}\n", file = thefile)
}
if (.requireRgdal(FALSE)) {
cat("coordinate system string = {", wkt(r), "}\n", file = thefile, sep="")
} else {
cat("projection info =", proj4string(r), "\n", file = thefile)
}
cat("z plot range = {", minValue(r),", ", maxValue(r), "}\n", file = thefile)
cat("band names = {", paste(names(r),collapse=","), "}", "\n", file = thefile)
close(thefile)
} |
types.withsamplesize <- c('c', 'np', 'p', 'u')
types.multicolumn <- c('R', 'S', 'xbar')
gettext("Phase I...", domain="R-RcmdrPlugin.UCA")
gettext("Phase I (multiple columns)...", domain="R-RcmdrPlugin.UCA")
gettext("Phase II (multiple columns)...", domain="R-RcmdrPlugin.UCA")
gettext("Phase II from data (multiple columns)...", domain="R-RcmdrPlugin.UCA")
gettext("Phase II from parameters (multiple columns)...", domain="R-RcmdrPlugin.UCA")
.qccMenu <- function(dialogtitle, graphtitle, x1title = "", n1title = "", x2title = "", n2title = "", type, phase = c('1', '2', 'p'), help, recall, reset, apply) {
phase = match.arg(phase)
initializeDialog(title = dialogtitle)
if (phase == 'p') {
centerVar <- tclVar("")
dataFrame <- tkframe(top)
centerEntry <- tkentry(dataFrame, width="8", textvariable=centerVar)
if (type %in% types.multicolumn) {
stddevVar <- tclVar("")
stddevEntry <- tkentry(top, width="8", textvariable=stddevVar)
}
}
x1Box <- variableListBox(top, Numeric(), selectmode=ifelse(type %in% types.multicolumn, "single", "multiple"), initialSelection=NULL, title = x1title)
n1Box <- variableListBox(top, Numeric(), selectmode="single", initialSelection=NULL, title = n1title)
subsetBox(subset.expression = gettextRcmdr("<all valid cases>"))
if (phase == '2' || phase == 'p') {
x2Box <- variableListBox(top, Numeric(), selectmode=ifelse(type %in% types.multicolumn, "single", "multiple"), initialSelection=NULL, title = x2title)
n2Box <- variableListBox(top, Numeric(), selectmode="single", initialSelection=NULL, title = n2title)
subset2Box(subset.expression = gettextRcmdr("<all valid cases>"))
plotall <- tclVar()
renumber <- tclVar()
optionsFrame <- tkframe(top)
plotallcheckBox <- ttkcheckbutton(optionsFrame, variable = plotall)
renumbercheckBox <- ttkcheckbutton(optionsFrame, variable = renumber)
}
onOK <- function() {
if (phase == '2' || phase == 'p') {
plotall <- (tclvalue(plotall) == "1")
renumber <- (tclvalue(renumber) == "1")
} else {
plotall <- FALSE
renumber <- FALSE
}
if (phase == 'p') {
center <- as.numeric(tclvalue(centerVar))
if (is.na(center)) {
errorCondition(recall = recall, message=gettext("No valid numeric value has been provided for the center parameter", domain="R-RcmdrPlugin.UCA"))
return()
}
if (type %in% types.multicolumn) {
stddev <- as.numeric(tclvalue(stddevVar))
}
}
x1 <- getSelection(x1Box)
if (length(x1) == 0) {
errorCondition(recall = recall, message=gettext("No data variable was selected (Phase I)", domain="R-RcmdrPlugin.UCA"))
return()
}
if (length(x1) == 1 && type %in% types.multicolumn) {
errorCondition(recall=recall, message=gettext("Select at least two variables (Phase I)", domain="R-RcmdrPlugin.UCA"))
return()
}
if (type %in% types.withsamplesize) {
n1 <- getSelection(n1Box)
if (length(n1) == 0) {
errorCondition(recall = recall, message=gettext("No sample size variable was selected (Phase I)", domain="R-RcmdrPlugin.UCA"))
return()
}
}
subset <- trim.blanks(tclvalue(subsetVariable))
if (phase == '2' || phase == 'p') {
x2 <- getSelection(x2Box)
if (length(x2) == 0) {
errorCondition(recall = recall, message=gettext("No data variable was selected (Phase II)", domain="R-RcmdrPlugin.UCA"))
return()
}
if (length(x2) == 1 && type %in% types.multicolumn) {
errorCondition(recall=recall, message=gettext("Select at least two variables (Phase II)", domain="R-RcmdrPlugin.UCA"))
return()
}
if (type %in% types.withsamplesize) {
n2 <- getSelection(n2Box)
if (length(n2) == 0) {
errorCondition(recall = recall, message=gettext("No sample size variable was selected (Phase II)", domain="R-RcmdrPlugin.UCA"))
return()
}
}
subset2 <- trim.blanks(tclvalue(subset2Variable))
}
closeDialog()
if (phase == '1' || plotall) {
graphtitle <- paste0(graphtitle, ' ', ifelse(type %in% types.multicolumn, paste0('(', paste(x1, collapse = ','), ')'), x1))
if ((subset != gettextRcmdr("<all valid cases>")) && (subset != "")) graphtitle <- paste0(graphtitle, '[', subset, ifelse(type %in% types.multicolumn, ', ', ''), ']')
}
if (phase == '2' || phase == 'p') {
if (plotall) graphtitle <- paste0(graphtitle, ' ', gettext('and', domain = "R-RcmdrPlugin.UCA"))
graphtitle <- paste0(graphtitle, ' ', ifelse(type %in% types.multicolumn, paste0('(', paste(x2, collapse = ','), ')'), x2))
if ((subset2 != gettextRcmdr("<all valid cases>")) && (subset2 != "")) graphtitle <- paste0(graphtitle, '[', subset2, ifelse(type %in% types.multicolumn, ', ', ''), ']')
}
if (phase == 'p') {
graphtitle <- paste0(graphtitle, '\\n', gettext('with Center', domain = "R-RcmdrPlugin.UCA"), ' ', center)
}
if (phase == 'p' && type %in% types.multicolumn && !is.na(stddev)) {
graphtitle <- paste0(graphtitle, ' ', gettext('and StdDev', domain = "R-RcmdrPlugin.UCA"), ' ', stddev)
}
command <- paste0("with(", ActiveDataSet(), ", qcc(data = ")
command <- paste0(command, ifelse(type %in% types.multicolumn, paste0('cbind(', paste(x1, collapse = ','), ')'), x1))
if ((subset != gettextRcmdr("<all valid cases>")) && (subset != "")) command <- paste0(command, '[', subset, ifelse(type %in% types.multicolumn, ', ', ''), ']')
if (type %in% types.withsamplesize) {
command <- paste0(command, ", sizes = ", n1)
if ((subset != gettextRcmdr("<all valid cases>")) && (subset != "")) {
command <- paste0(command, '[', subset, ']')
}
}
if (phase == '2' || phase == 'p') {
command <- paste0(command, ", newdata = ")
command <- paste0(command, ifelse(type %in% types.multicolumn, paste0('cbind(', paste(x2, collapse = ','), ')'), x2))
if ((subset2 != gettextRcmdr("<all valid cases>")) && (subset2 != "")) command <- paste0(command, '[', subset2, ifelse(type %in% types.multicolumn, ', ', ''), ']')
if (type %in% types.withsamplesize) {
command <- paste0(command, ", newsizes = ", n2)
if ((subset2 != gettextRcmdr("<all valid cases>")) && (subset2 != "")) {
command <- paste0(command, '[', subset2, ']')
}
}
}
command <- paste0(command, ", type = \"", type, "\"")
if (phase == 'p') command <- paste0(command, ", center = ", center)
if (phase == 'p' && type %in% types.multicolumn && !is.na(stddev)) {
command <- paste0(command, ", std.dev =", stddev)
}
command <- paste0(command, ", title = \"", graphtitle, "\"")
if (phase == '2' || phase == 'p') {
if (!plotall) command <- paste0(command, ", chart.all = ", plotall)
if (renumber) {
lx2 <- paste0("with(", ActiveDataSet())
if (type %in% types.multicolumn) {
lx2 <- paste0(lx2, ", nrow(")
} else {
lx2 <- paste0(lx2, ", length(")
}
lx2 <- paste0(lx2, ifelse(type %in% types.multicolumn, paste0('cbind(', paste(x2, collapse = ','), ')'), x2))
if ((subset2 != gettextRcmdr("<all valid cases>")) && (subset2 != "")) lx2 <- paste0(lx2, '[', subset2, ifelse(type %in% types.multicolumn, ', ', ''), ']')
lx2 <- paste0(lx2, "))")
lx2 <- eval(parse(text = lx2))
command <- paste0(command, ", newlabel = 1:", lx2)
}
}
command <- paste0(command, "))")
doItAndPrint(command)
tkdestroy(top)
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject = help, reset = reset, apply = apply)
deltarow <- 0
if (phase == 'p') {
tkgrid(tklabel(dataFrame, text = paste0(gettext("Center", domain="R-RcmdrPlugin.UCA"), " ")), centerEntry, sticky = "w")
deltarow <- 1
if (type %in% types.multicolumn) {
tkgrid(tklabel(dataFrame, text = gettext("Standard Deviation", domain="R-RcmdrPlugin.UCA")), stddevEntry, sticky = "w")
deltarow <- deltarow + 1
}
tkgrid(dataFrame, sticky = "w")
}
tkgrid(getFrame(x1Box), sticky = "w")
if (type %in% types.withsamplesize) {
tkgrid(getFrame(n1Box), sticky = "w", row = 0 + deltarow, column = 1)
}
tkgrid(subsetFrame, sticky = "w")
if (phase == '2' || phase == 'p') {
tkgrid(getFrame(x2Box), sticky = "w")
if (type %in% types.withsamplesize) {
tkgrid(getFrame(n2Box), sticky = "w", row = 2 + deltarow, column = 1)
}
tkgrid(subset2Frame, sticky = "w")
tkgrid(plotallcheckBox, tklabel(optionsFrame, text = gettext("Plot all data", domain="R-RcmdrPlugin.UCA")), sticky = "w")
tkgrid(renumbercheckBox, tklabel(optionsFrame, text = gettext("Renumber 2nd phase data", domain="R-RcmdrPlugin.UCA")), sticky = "w")
tkgrid(optionsFrame, sticky = "w")
}
tkgrid(buttonsFrame, sticky="w", columnspan = 2)
dialogSuffix()
}
cchart1Menu <- function()
{
gettext("Counts", domain="R-RcmdrPlugin.UCA")
gettext("c-chart (rate)...", domain="R-RcmdrPlugin.UCA")
.qccMenu(
dialogtitle = gettext("c-chart (rate)", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("c-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Nonconformities", domain="R-RcmdrPlugin.UCA"),
n1title = gettext("Sizes", domain="R-RcmdrPlugin.UCA"),
type = "c", phase = '1', help = "c-chart", recall = cchart1Menu, reset = "cchart1Menu", apply = "cchart1Menu")
}
cchart2Menu <- function()
{
gettext("Counts", domain="R-RcmdrPlugin.UCA")
gettext("c-chart (rate)...", domain="R-RcmdrPlugin.UCA")
.qccMenu(
dialogtitle = gettext("c-chart (rate) from data", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("c-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Nonconformities (Phase I)", domain="R-RcmdrPlugin.UCA"),
n1title = gettext("Sizes (Phase I)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Nonconformities (Phase II)", domain="R-RcmdrPlugin.UCA"),
n2title = gettext("Sizes (Phase II)", domain="R-RcmdrPlugin.UCA"),
type = "c", phase = "2", help = "c-chart", recall = cchart2Menu, reset = "cchart2Menu", apply = "cchart2Menu")
}
cchartpMenu <- function()
{
gettext("Counts", domain="R-RcmdrPlugin.UCA")
gettext("c-chart (rate)...", domain="R-RcmdrPlugin.UCA")
.qccMenu(
dialogtitle = gettext("c-chart (rate) from parameter", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("c-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Nonconformities (Phase I)", domain="R-RcmdrPlugin.UCA"),
n1title = gettext("Sizes (Phase I)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Nonconformities (Phase II)", domain="R-RcmdrPlugin.UCA"),
n2title = gettext("Sizes (Phase II)", domain="R-RcmdrPlugin.UCA"),
type = "c", phase = "p", help = "c-chart", recall = cchartpMenu, reset = "cchartpMenu", apply = "cchartpMenu")
}
npchart1Menu <- function()
{
gettext("Attributes", domain="R-RcmdrPlugin.UCA")
gettext("np-chart (count)", domain="R-RcmdrPlugin.UCA")
gettext("np-chart (Phase I)...", domain="R-RcmdrPlugin.UCA")
.qccMenu(
dialogtitle = gettext("np-chart", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("np-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Nonconforming units", domain="R-RcmdrPlugin.UCA"),
n1title = gettext("Sample size", domain="R-RcmdrPlugin.UCA"),
type = "np", phase = "1", help = "np-chart", recall = npchart1Menu, reset = "npchart1Menu", apply = "npchart1Menu")
}
npchart2Menu <- function()
{
.qccMenu(
dialogtitle = gettext("np-chart phase II from data", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("np-chart phase II\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Nonconforming units (Phase I)", domain="R-RcmdrPlugin.UCA"),
n1title = gettext("Sample size (Phase I)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Nonconforming units (Phase II)", domain="R-RcmdrPlugin.UCA"),
n2title = gettext("Sample size (Phase II)", domain="R-RcmdrPlugin.UCA"),
type = "np", phase = "2", help = "np-chart", recall = npchart2Menu, reset = "npchart2Menu", apply = "npchart2Menu")
}
npchartpMenu <- function()
{
.qccMenu(
dialogtitle = gettext("np-chart phase II from parameter", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("np-chart phase II\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Nonconforming units (Phase I)", domain="R-RcmdrPlugin.UCA"),
n1title = gettext("Sample size (Phase I)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Nonconforming units (Phase II)", domain="R-RcmdrPlugin.UCA"),
n2title = gettext("Sample size (Phase II)", domain="R-RcmdrPlugin.UCA"),
type = "np", phase = "p", help = "np-chart", recall = npchartpMenu, reset = "npchartpMenu", apply = "npchartpMenu")
}
paretochartMenu <- function() {
gettext("Quality Control", domain="R-RcmdrPlugin.UCA")
initializeDialog(title=gettext("Pareto chart", domain="R-RcmdrPlugin.UCA"))
variablesBox <- variableListBox(top, Factors(), selectmode="single", initialSelection=NULL, title=gettextRcmdr("Variable"))
onOK <- function() {
x <- getSelection(variablesBox)
if (length(x) == 0) {
errorCondition(recall=paretochartMenu, message=gettextRcmdr("No variable was selected."))
return()
}
closeDialog()
doItAndPrint(paste("with(", ActiveDataSet(), ", paretochart(", x, "))", sep = ""))
tkdestroy(top)
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject="paretochart", reset = "paretochartMenu", apply = "paretochartMenu")
tkgrid(getFrame(variablesBox), sticky="nw")
tkgrid(buttonsFrame, sticky="w")
dialogSuffix(rows=6, columns=1)
}
pchart1Menu <- function()
{
gettext("Attributes", domain="R-RcmdrPlugin.UCA")
gettext("p-chart (proportion)", domain="R-RcmdrPlugin.UCA")
gettext("Phase I...", domain="R-RcmdrPlugin.UCA")
.qccMenu(
dialogtitle = gettext("p-chart", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("p-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Nonconforming units", domain="R-RcmdrPlugin.UCA"),
n1title = gettext("Sample size", domain="R-RcmdrPlugin.UCA"),
type = "p", phase = "1", help = "p-chart", recall = pchart1Menu, reset = "pchart1Menu", apply = "pchart1Menu")
}
pchart2Menu <- function()
{
gettext("Phase II from data...", domain="R-RcmdrPlugin.UCA")
.qccMenu(
dialogtitle = gettext("p-chart phase II from data", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("p-chart phase II\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Nonconforming units (Phase I)", domain="R-RcmdrPlugin.UCA"),
n1title = gettext("Sample size (Phase I)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Nonconforming units (Phase II)", domain="R-RcmdrPlugin.UCA"),
n2title = gettext("Sample size (Phase II)", domain="R-RcmdrPlugin.UCA"),
type = "p", phase = "2", help = "p-chart", recall = pchart2Menu, reset = "pchart2Menu", apply = "pchart2Menu")
}
pchartpMenu <- function()
{
gettext("Phase II from parameter...", domain="R-RcmdrPlugin.UCA")
.qccMenu(
dialogtitle = gettext("p-chart phase II from parameter", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("p-chart phase II\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Nonconforming units (Phase I)", domain="R-RcmdrPlugin.UCA"),
n1title = gettext("Sample size (Phase I)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Nonconforming units (Phase II)", domain="R-RcmdrPlugin.UCA"),
n2title = gettext("Sample size (Phase II)", domain="R-RcmdrPlugin.UCA"),
type = "p", phase = "p", help = "p-chart", recall = pchartpMenu, reset = "pchartpMenu", apply = "pchartpMenu")
}
R1mcMenu <- function()
{
gettext("Range", domain="R-RcmdrPlugin.UCA")
.qccMenu(
dialogtitle = gettext("R-chart phase I (multiple columns)", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("R-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Measurements (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
type = "R", phase = "1", help = "R-chart", recall = R1mcMenu, reset = "R1mcMenu", apply = "R1mcMenu")
}
R2mcMenu <- function()
{
.qccMenu(
dialogtitle = gettext("R-chart phase II from data (multiple columns)", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("R-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Measurements phase I from data (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Measurements phase II from data (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
type = "R", phase = "2", help = "R-chart", recall = R2mcMenu, reset = "R2mcMenu", apply = "R2mcMenu")
}
RpmcMenu <- function()
{
.qccMenu(
dialogtitle = gettext("R-chart phase II from parameters (multiple columns)", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("R-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Measurements phase I from parameters (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Measurements phase II from parameters (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
type = "R", phase = "p", help = "R-chart", recall = RpmcMenu, reset = "RpmcMenu", apply = "RpmcMenu")
}
S1mcMenu <- function()
{
.qccMenu(
dialogtitle = gettext("S-chart (multiple columns)", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("S-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Measurements (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
type = "S", phase = "1", help = "S-chart", recall = S1mcMenu, reset = "S1mcMenu", apply = "S1mcMenu")
}
S2mcMenu <- function()
{
.qccMenu(
dialogtitle = gettext("S-chart phase II from data (multiple columns)", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("S-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Measurements phase I (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Measurements phase II (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
type = "S", phase = "2", help = "S-chart", recall = S2mcMenu, reset = "S2mcMenu", apply = "S2mcMenu")
}
SpmcMenu <- function()
{
.qccMenu(
dialogtitle = gettext("S-chart phase II from parameters (multiple columns)", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("S-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Measurements phase I (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Measurements phase II (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
type = "S", phase = "p", help = "S-chart", recall = SpmcMenu, reset = "SpmcMenu", apply = "SpmcMenu")
}
uchart1Menu <- function()
{
gettext("Counts", domain="R-RcmdrPlugin.UCA")
gettext("u-chart (average rate)...", domain="R-RcmdrPlugin.UCA")
.qccMenu(
dialogtitle = gettext("u-chart (average rate)", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("u-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Nonconformities", domain="R-RcmdrPlugin.UCA"),
n1title = gettext("Sizes", domain="R-RcmdrPlugin.UCA"),
type = "u", phase = "1", help = "u-chart", recall = uchart1Menu, reset = "uchart1Menu", apply = "uchart1Menu")
}
uchart2Menu <- function()
{
gettext("Counts", domain="R-RcmdrPlugin.UCA")
gettext("u-chart (average rate)...", domain="R-RcmdrPlugin.UCA")
.qccMenu(
dialogtitle = gettext("u-chart phase II from data", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("u-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Nonconformities (Phase I)", domain="R-RcmdrPlugin.UCA"),
n1title = gettext("Sizes (Phase I)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Nonconformities (Phase II)", domain="R-RcmdrPlugin.UCA"),
n2title = gettext("Sizes (Phase II)", domain="R-RcmdrPlugin.UCA"),
type = "u", phase = "2", help = "u-chart", recall = uchart2Menu, reset = "uchart2Menu", apply = "uchart2Menu")
}
uchartpMenu <- function()
{
gettext("Counts", domain="R-RcmdrPlugin.UCA")
gettext("u-chart (average rate)...", domain="R-RcmdrPlugin.UCA")
.qccMenu(
dialogtitle = gettext("u-chart phase II from parameter", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("u-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Nonconformities (Phase I)", domain="R-RcmdrPlugin.UCA"),
n1title = gettext("Sizes (Phase I)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Nonconformities (Phase II)", domain="R-RcmdrPlugin.UCA"),
n2title = gettext("Sizes (Phase II)", domain="R-RcmdrPlugin.UCA"),
type = "u", phase = "p", help = "u-chart", recall = uchartpMenu, reset = "uchartpMenu", apply = "uchartpMenu")
}
xbarone1Menu <- function()
{
gettext("Continuous", domain="R-RcmdrPlugin.UCA")
gettext("One-at-time data", domain="R-RcmdrPlugin.UCA")
.qccMenu(
dialogtitle = gettext("One-at-time data", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Measurements", domain="R-RcmdrPlugin.UCA"),
type = "xbar.one", help = "xbar.one-chart", recall = xbarone1Menu, reset = "xbarone1Menu", apply = "xbarone1Menu")
}
xbar1mcMenu <- function()
{
.qccMenu(
dialogtitle = gettext("xbar-chart (multiple columns)", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("xbar-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Measurements (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
type = "xbar", phase = "1", help = "xbar-chart", recall = xbar1mcMenu, reset = "xbar1mcMenu", apply = "xbar1mcMenu")
}
xbar2mcMenu <- function()
{
.qccMenu(
dialogtitle = gettext("xbar-chart phase II from data (multiple columns)", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("xbar-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Measurements phase I (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Measurements phase II (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
type = "xbar", phase = "2", help = "xbar-chart", recall = xbar2mcMenu, reset = "xbar2mcMenu", apply = "xbar2mcMenu")
}
xbarpmcMenu <- function()
{
.qccMenu(
dialogtitle = gettext("xbar-chart phase II from parameters (multiple columns)", domain="R-RcmdrPlugin.UCA"),
graphtitle = gettext("xbar-chart\\nfor", domain="R-RcmdrPlugin.UCA"),
x1title = gettext("Measurements phase I (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
x2title = gettext("Measurements phase II (pick two variables or more)", domain="R-RcmdrPlugin.UCA"),
type = "xbar", phase = "p", help = "xbar-chart", recall = xbarpmcMenu, reset = "xbarpmcMenu", apply = "xbarpmcMenu")
} |
use_aos_refresh <- function(){
htmltools::tagList(
html_dependencies_aos(),
htmltools::tags$script(
sprintf(
"$(document).ready(function(){
AOS.refresh();
});",
options
)
)
)
}
use_aos_refresh_hard <- function(){
htmltools::tagList(
html_dependencies_aos(),
htmltools::tags$script(
sprintf(
"$(document).ready(function(){
AOS.refreshHard();
});",
options
)
)
)
} |
mphineq.fit <- function(y, Z, ZF=Z, h.fct=0,derht.fct=0,d.fct=0,derdt.fct=0,
L.fct=0,derLt.fct=0,X=NULL,formula=NULL,names=NULL,lev=NULL,E=NULL,
maxiter=100,step=1,
norm.diff.conv=1e-5,norm.score.conv=1e-5,
y.eps=0,chscore.criterion=2,
m.initial=y,mup=1)
{
start.time <- proc.time()[3]
version <- "mphineq.fit, version 1.0.1, 5/10/06"
Zlist<-cocadise(Z,formula=formula,lev=lev,names=names)
if(is.null(X)){X<-0}
inv <- ginv
y<-as.matrix(y)
lenh<-0
if ((missing(h.fct))&(sum(abs(X)) != 0))
{
if(is.null(E)){U <- create.U(X)}
else{U<-t(E)}
if (sum(abs(U)) == 0) {h.fct <- 0}
else {
h.fct <- function(m) {
t(U)%*%L.fct(m)
}
}
}
else
{
U <- "Not created within the program."
}
if ((is.function(derht.fct)==FALSE)&(sum(abs(X)) != 0)&(is.function(derLt.fct)==TRUE))
{
U <- create.U(X)
if (sum(abs(U)) == 0) {derht.fct <- 0}
else {
derht.fct <- function(m) {
derLt.fct(m)%*%U
}
}
}
if ((is.function(h.fct)==TRUE)||(is.function(d.fct)==TRUE)||(class(formula)
=="formula")) {
lenm <- length(y);
m <- as.matrix(c(m.initial)) + y.eps
m[m==0] <- 0.01
p<-m*c(1/Z%*%t(Z)%*%m)
xi <- Zlist$IMAT%*%log(m)
if ((is.function(d.fct)==FALSE)&(is.function(h.fct)==FALSE)) {
p <- as.matrix(exp(Zlist$DMAT%*%xi))
p<-(p/sum(p))
m<-p*c(Z%*%t(Z)%*%y)
}
if (is.function(h.fct)==TRUE){
h <- hobs <- h.fct(m)
lenh <- length(h)
if (is.function(derht.fct)==FALSE) {
H <- num.deriv.fct(h.fct,m)
}
else {
H <- derht.fct(m)
}
HtDHinvobs <- inv(t(H)%*%(H*c(m)))
}
if (is.function(d.fct)==TRUE)
{
d <- dhobs <- d.fct(m)
lend <- length(d)
if (is.function(derdt.fct)==FALSE)
{
DH <- num.deriv.fct(d.fct,m)
}
else {
DH <- derdt.fct(m)
}
}
lam <- matrix("NA",lenh,1)
Dm <- diag(c(m+1e-08))-((ZF*c(m))%*%t(ZF*c(p)))
if (!is.matrix(Dm)) {return ("unable to reach convergence")}
norm.score <- 999999
theta<-xi
iter <- 0
step.iter <- 0
norm.diff <- 10
while ( ((norm.diff > norm.diff.conv)||(norm.score > norm.score.conv))
&(iter< maxiter))
{
qpmatr<-t(Zlist$DMAT)%*%Dm%*%Zlist$DMAT
if ((is.function(d.fct)==TRUE)&(is.function(h.fct)==TRUE)) {
Amat<-cbind(t(Zlist$DMAT)%*%Dm%*%H,t(Zlist$DMAT)%*%Dm%*%DH)
bvec<-rbind(-h,-d )
}
else {
if (is.function(h.fct)==TRUE){
Amat<- t(Zlist$DMAT)%*%Dm%*%H
bvec<- -h }
if (is.function(d.fct)==TRUE) {
Amat<-t(Zlist$DMAT)%*%Dm%*%DH
bvec<- -d }
if ((is.function(d.fct)==FALSE)&(is.function(h.fct)==FALSE)) {
Amat<-matrix(0,nrow(qpmatr),1)
bvec<-0
}
}
if (any(is.null(qpmatr))||any(is.na(qpmatr))) {
print("matrix in quadratic programming not positive def.")
return("matrix in quadratic programming not positive def.")}
As<- solve.QP(qpmatr,t(Zlist$DMAT)%*%(y-m), Amat, bvec, meq=lenh, factorized=FALSE)
if(is.null(As)){
print("Error in solve.QP")
break}
ff.fct<-function(steptemp){
theta.temp <- theta + steptemp*matrix(As$solution)
p <- as.matrix(exp(Zlist$DMAT%*%theta.temp))
p<-p*c(1/Z%*%t(Z)%*%p)
m<-p*c(Z%*%t(Z)%*%y)
if (is.function(h.fct)==FALSE) {
h<-0}
else{
h <- h.fct(m)
}
if (is.function(d.fct)==FALSE) {
dd<-100
}
else {
dd <- d.fct(m)
}
norm.score.temp <-
as.matrix(2/sum(y)*sum(y[y>0]*(log(y[y>0])-log(m[y>0]))))+
mup*sum(abs(h))
-mup*sum(pmin(dd,dd*0))
norm.score.temp
}
stepco<-optimize(ff.fct, c(step*0.5^5, step), tol = 0.0001)
step.temp<-stepco$minimum
step.iter<-step.temp
theta.temp <- theta + step.temp*matrix(As$solution)
norm.diff <- sqrt(sum((theta-theta.temp)*(theta-theta.temp)))
p <- as.matrix(exp(Zlist$DMAT%*%theta.temp))
p<-p*c(1/Z%*%t(Z)%*%p)
m<-p*c(Z%*%t(Z)%*%y)
if (is.function(h.fct)==FALSE) {
h<-0}
else{
h <- h.fct(m)
if (is.function(derht.fct)==FALSE) {
H <- num.deriv.fct(h.fct,m)
}
else {
H <- derht.fct(m)
}
}
if (is.function(d.fct)==FALSE) {
d<-100
}
else {
d <- d.fct(m)
}
Dm <- diag(c(m+1e-08))-((ZF*c(m))%*%t(ZF*c(p)))
if (!is.matrix(Dm)) {return ("unable to reach convergence")}
norm.score <- sum(abs(h))-sum(pmin(d,d*0))
theta <- theta.temp
iter <- iter + 1
if(chscore.criterion==0){
}
}
}
satflag<-dim(Zlist$DMAT)[1]-dim(Zlist$DMAT)[2]
if ((is.function(h.fct)==TRUE)||( (class(formula)=="formula")&(satflag >1 ) )){
if ((is.function(h.fct)==FALSE)&(class(formula)=="formula")){
M<-cbind(Zlist$DMAT,matrix(1,nrow(Zlist$DMAT) ))
H<-create.U(M)
H<-diag(1/c(m))%*%H
hobs<-t(H)%*%log(m)
lenh <- length(hobs)
lam <- matrix("NA",lenh,1)
HtDHinvobs <- inv(t(H)%*%(H*c(m)))
}
if ((is.function(h.fct)==TRUE)&(class(formula)=="formula")){
M<-cbind(Zlist$DMAT,matrix(1,nrow(Zlist$DMAT) ))
H2<-create.U(M)
H2<-diag(1/c(m))%*%H2
H<-cbind(H,H2)
hobs<-t(H)%*%log(m)
lenh <- length(hobs)
lam <- matrix("NA",lenh,1)
lenh<-lenh-dim(H2)[2]
HtDHinvobs <- inv(t(H)%*%(H*c(m)))
}
HtDHinv <- inv(t(H)%*%(H*c(m)))
HHtDHinv <- H%*%HtDHinv
p <- m*c(1/Z%*%t(Z)%*%y)
resid <- y-m
covresid <- (H*c(m))%*%HtDHinv%*%t(H*c(m))
covm.unadj <- covm <- Dm - covresid
if (sum(ZF) != 0) {
covm <- covm.unadj - ((ZF*c(m))%*%t(ZF*c(m)))*c(1/Z%*%t(Z)%*%y)
}
covp <- t(t((covm.unadj-((Z*c(m))%*%t(Z*c(m)))*c(1/Z%*%t(Z)%*%y))*
c(1/Z%*%t(Z)%*%y))* c(1/Z%*%t(Z)%*%y))
dcovresid <- diag(covresid)
dcovresid[abs(dcovresid)<1e-8] <- 0
adjresid <- resid
adjresid[dcovresid > 0] <- resid[dcovresid>0]/sqrt(dcovresid[dcovresid>0])
presid <- resid/sqrt(m)
covlam <- HtDHinv
Gsq <- as.matrix(2*sum(y[y>0]*(log(y[y>0])-log(m[y>0]))))
Xsq <- as.matrix(t(y-m)%*%((y-m)*c(1/m)))
if(is.function(d.fct)==FALSE){
Wsq <- as.matrix(t(hobs)%*%HtDHinvobs%*%hobs)}
else {Wsq<-as.matrix("NA")}
beta <- "NA"
covbeta <- "NA"
covL <- "NA"
L <- "NA"
Lobs <- "NA"
Lresid <- "NA"
if (sum(abs(X)) != 0) {
L <- L.fct(m)
Lobs <- L.fct(y+y.eps)
if (is.function(derLt.fct)==FALSE) {
derLt <- num.deriv.fct(L.fct,m)
}
else {
derLt <- derLt.fct(m)
}
PX <- inv(t(X)%*%X)%*%t(X)
beta <- PX%*%L
covL <- t(derLt)%*%covm%*%derLt
covbeta <- PX%*%covL%*%t(PX)
Lres <- Lobs - L
covLres <- t(derLt)%*%covresid%*%derLt
dcovLres <- diag(covLres)
dcovLres[abs(dcovLres)<1e-8] <- 0
Lresid <- Lres
Lresid[dcovLres > 0] <- Lres[dcovLres>0]/sqrt(dcovLres[dcovLres>0])
lbeta <- ll <- c()
for (i in 1:length(beta)) {
lbeta <- c(lbeta,paste("beta",i,sep=""))
}
for (i in 1:length(L)) {
ll <- c(ll,paste("link",i,sep=""))
}
dimnames(beta) <- list(lbeta,"BETA")
if(!is.null(colnames(X))){dimnames(beta) <- list(colnames(X),"BETA")}
dimnames(covbeta) <- list(lbeta,lbeta)
dimnames(L) <- list(ll,"ML LINK")
dimnames(Lobs) <- list(ll,"OBS LINK")
dimnames(covL) <- list(ll,ll)
dimnames(Lresid) <- list(ll,"LINK RESID")
}
}
else {
lenh <- 0
lenm <- length(y)
if(is.function( d.fct)==FALSE){
m <- as.matrix(c(m.initial))+y.eps
m[m==0] <- 0.01
xi <- log(m)
Dm <- diag(c(m))
Dminv <- diag(c(1/m))
s <- y-m
norm.score <- sqrt(sum(s*s))
theta <- xi
lentheta <- length(theta)
iter <- 0
norm.diff <- 10
while ( ((norm.diff > norm.diff.conv)||(norm.score > norm.score.conv))
&(iter< maxiter))
{
A <- Dminv
thetanew <- theta + step*(s*c(1/m))
norm.diff <- sqrt(sum((theta-thetanew)*(theta-thetanew)))
theta <- thetanew
m <- exp(theta)
Dm <- diag(c(m))
Dminv <- diag(c(1/m))
s <- y-m
norm.score <- sqrt(sum(s*s))
iter <- iter + 1
}
}
p <- m*c(1/Z%*%t(Z)%*%y)
resid <- 0*y
covm.unadj <- covm <- Dm
covresid <- 0*covm
if (sum(ZF) != 0) {
covm <- covm.unadj - ((ZF*c(m))%*%t(ZF*c(m)))*c(1/Z%*%t(Z)%*%y)
}
covp <- t(t((covm.unadj-((Z*c(m))%*%t(Z*c(m)))*c(1/Z%*%t(Z)%*%y))*
c(1/Z%*%t(Z)%*%y))* c(1/Z%*%t(Z)%*%y))
adjresid <- 0*y
presid <- 0*y
covlam <- as.matrix(0);
lam <- as.matrix(0)
Gsq <- as.matrix(2*sum(y[y>0]*(log(y[y>0])-log(m[y>0]))))
Xsq <- as.matrix(t(y-m)%*%((y-m)*c(1/m)))
if(is.function(d.fct)==FALSE){
Wsq <- as.matrix(0) }
else {Wsq<-as.matrix("NA")}
beta <- "NA"
covbeta <- "NA"
covL <- "NA"
L <- "NA"
Lresid <- "NA"
Lobs <- "NA"
if (sum(abs(X)) != 0) {
L <- L.fct(m)
Lobs <- L.fct(y)
if (is.function(derLt.fct)==FALSE) {
derLt <- num.deriv.fct(L.fct,m)
}
else {
derLt <- derLt.fct(m)
}
PX <- inv(t(X)%*%X)%*%t(X)
beta <- PX%*%L
covL <- t(derLt)%*%covm%*%derLt
Lresid <- 0*L
covbeta <- PX%*%covL%*%t(PX)
lbeta <- ll <- c()
for (i in 1:length(beta)) {
lbeta <- c(lbeta,paste("beta",i,sep=""))
}
for (i in 1:length(L)) {
ll <- c(ll,paste("link",i,sep=""))
}
dimnames(beta) <- list(lbeta,"BETA")
if(!is.null(colnames(X))){dimnames(beta) <- list(colnames(X),"BETA")}
dimnames(covbeta) <- list(lbeta,lbeta)
dimnames(Lobs) <- list(ll,"OBS LINK")
dimnames(L) <- list(ll,"ML LINK")
dimnames(covL) <- list(ll,ll)
dimnames(Lresid) <- list(ll,"LINK RESID")
}
}
lm <- ly <- lp <- lbeta <- lr <- lar <- lpr <- ll <- llam <- c()
if(is.null(rownames(y))){
for (i in 1:lenm) {
lm <- c(lm,paste("m",i,sep=""))
ly <- c(ly,paste("y",i,sep=""))
lp <- c(lp,paste("p",i,sep=""))
lr <- c(lr,paste("r",i,sep=""))
lar <- c(lar,paste("adj.r",i,sep=""))
lpr <- c(lpr,paste("pearson.r",i,sep=""))
}
}
else{ly<-c( paste("y(",rownames(y),")"))
lm<- c( paste("m(",rownames(y),")"))
lp <-c( paste("p(",rownames(y),")"))
lr<- c(paste("r(",rownames(y),")"))
lar<-c(paste("a.r(",rownames(y),")"))
lpr<-c(paste("p.r(",rownames(y),")"))}
for (i in 1:length(lam)) {
llam <- c(llam,paste("lambda",i,sep=""))
}
dimnames(y) <- list(ly,"OBS")
dimnames(m) <- list(lm,"FV")
dimnames(p) <- list(lp,"PROB")
dimnames(resid) <- list(lr,"RAW RESIDS")
dimnames(presid) <- list(lpr,"PEARSON RESIDS")
dimnames(adjresid) <- list(lar, "ADJUSTED RESIDS")
dimnames(lam) <- list(llam,"LAGRANGE MULT")
dimnames(covm) <- list(lm,lm)
dimnames(covp) <- list(lp,lp)
dimnames(covresid) <- list(lr,lr)
dimnames(covlam) <- list(llam,llam)
dimnames(Xsq) <- list("","PEARSON SCORE STATISTIC")
dimnames(Gsq) <- list("","LIKELIHOOD RATIO STATISTIC")
dimnames(Wsq) <- list("","GENERALIZED wALD STATISTIC")
if (is.function(derht.fct)==FALSE) {derht.fct <- "Numerical derivatives used."}
if (is.function(derLt.fct)==FALSE) {derLt.fct <- "Numerical derivatives used."}
lenh<-lenh*(is.function(h.fct)==TRUE)
modlist<-list(y=y,m=m,covm=covm,p=p,covp=covp,
lambda=lam,covlambda=covlam,
resid=resid,presid=presid,adjresid=adjresid,covresid=covresid,
Gsq=Gsq,Xsq=Xsq,Wsq=Wsq,df=lenh,
beta=beta,covbeta=covbeta, Lobs=Lobs, L=L,covL=covL,Lresid=Lresid,
iter=iter, norm.diff=norm.diff,norm.score=norm.score,
h.fct=h.fct,derht.fct=derht.fct,L.fct=L.fct,derLt.fct=derLt.fct,
d.fct=d.fct,derdt.fct=derdt.fct,
X=X,U=U,Z=Z,ZF=ZF,Zlist=Zlist,version=version)
class(modlist)="mphfit"
modlist
} |
print.simexaft <-
function (x, digits = max(3, getOption("digits") - 3), ...)
{
cat("\nSIMEX-Variables: ")
cat(x$SIMEXvariable, sep = ", ")
cat("\nNumber of Simulations: ", paste(x$B), "\n\n", sep = "")
if (length(coef(x))) {
cat("Coefficients:\n")
print.default(format(coef(x), digits = digits), print.gap = 2,
quote = FALSE)
}
else cat("No coefficients\n")
cat("\n")
} |
.download_data_zone <- function(criterion, pollutant, zone, start_date,
end_date) {
url <- paste0("http://www.aire.cdmx.gob.mx/",
"estadisticas-consultas/consultas/resultado_consulta.php")
fd <- list(
diai = day(start_date),
mesi = month(start_date),
anoi = year(start_date),
diaf = day(end_date),
mesf = month(end_date),
anof = year(end_date),
Q = criterion,
inter = "",
consulta = "Consulta"
)
pollutant_tmp <- rep("on", length(pollutant))
names(pollutant_tmp) <- pollutant
fd <- append(fd, pollutant_tmp)
zones_tmp <- rep("on", length(zone))
names(zones_tmp) <- zone
fd <- append(fd, zones_tmp)
result <- POST(url,
add_headers("user-agent" =
"https://github.com/diegovalle/aire.zmvm"),
body = fd,
encode = "form")
if (http_error(result))
stop(sprintf("The request to <%s> failed [%s]",
url,
status_code(result)
), call. = FALSE)
if (http_type(result) != "text/html")
stop(paste0(url, " did not return text/html", call. = FALSE))
poll_table <- read_html(content(result, "text"))
df <- html_table(html_nodes(poll_table, "table")[[1]],
header = TRUE)
df
}
get_zone_imeca <- function(criterion, pollutant, zone, start_date, end_date,
showWarnings = TRUE, show_messages = TRUE) {
if (!missing("showWarnings"))
warning(paste0("`showWarnings` argument deprecated. Use the function ",
"`suppressWarnings` instead."),
call. = FALSE)
if (missing(pollutant))
stop("You need to specify a pollutant", call. = FALSE)
if (missing(zone))
stop("You need to specify a zona", call. = FALSE)
if (missing(criterion))
stop("You need to specify a start date", call. = FALSE)
if (missing(end_date))
stop("You need to specify an end_date (YYYY-MM-DD)", call. = FALSE)
if (!is.Date(end_date))
stop("end_ate should be a date in YYYY-MM-DD format", call. = FALSE)
if (missing(start_date))
stop("You need to specify a start_date (YYYY-MM-DD)", call. = FALSE)
if (!is.Date(start_date))
stop("start_date should be a string in YYYY-MM-DD format", call. = FALSE)
if (start_date < "2008-01-01")
stop(paste0("start_date should be after 2008-01-01, but you can visit",
" http://www.aire.cdmx.gob.mx/",
"default.php?opc=%27aKBhnmI=%27&opcion=aw==",
" to download data going back to 1992"), call. = FALSE)
criterion <- toupper(criterion)
for (i in seq_len(length(pollutant)))
if (!(identical("O3", pollutant[i]) || identical("NO2", pollutant[i]) ||
identical("SO2", pollutant[i]) || identical("CO", pollutant[i]) ||
identical("PM10", pollutant[i]) || identical("TC", pollutant[i])))
stop("Invalid pollutant value", call. = FALSE)
pollutant <- unique(pollutant)
for (i in seq_len(length(zone)))
if (!(identical("NO", zone[i]) || identical("NE", zone[i]) ||
identical("CE", zone[i]) || identical("SO", zone[i]) ||
identical("SE", zone[i]) || identical("TZ", zone[i]) ))
stop("zone should be one of 'NO', 'NE', 'CE', 'SO', 'SE', or 'TZ'",
call. = FALSE)
zone <- unique(zone)
if (!(identical("HORARIOS", criterion) || identical("MAXIMOS", criterion)))
stop("criterion should be 'HORARIOS' or 'MAXIMOS'", call. = FALSE)
criterion <- tolower(criterion)
if (length(base::intersect(pollutant, c("O3", "PM10"))) > 0 && show_messages)
message(paste0("Starting October 28, 2014 the IMECA",
" values for O3 and PM10 are computed using",
" NOM-020-SSA1-2014 and",
" NOM-025-SSA1-2014"))
if (start_date >= "2017-01-01" && show_messages)
message(paste0("Sometime in 2015-2017 the stations",
" ACO, AJU, INN, MON, and MPA were excluded from the",
" index"))
tryCatch({
df <- .download_data_zone(criterion, pollutant, zone, start_date, end_date)
names(df) <- df[1, ]
names(df)[1] <- "date"
names(df) <- str_replace_all(names(df), "\\s", "")
df <- df[2:nrow(df), ]
if (criterion != tolower("HORARIOS")) {
df <- df %>%
gather(zone_pollutant, value, -date) %>%
separate(zone_pollutant, c("zone", "pollutant"), sep = 2)
} else {
names(df)[2] <- "hour"
df <- df %>%
gather(zone_pollutant, value, -date, -hour) %>%
separate(zone_pollutant, c("zone", "pollutant"), sep = 2)
}
df[which(df$value == ""), "value"] <- NA
df[which(df$value == "M"), "value"] <- NA
df$value <- as.numeric(df$value)
df$date <- as.Date(df$date)
df$unit <- "IMECA"
if (criterion != tolower("HORARIOS")) {
as.data.frame(df[, c("date", "zone", "pollutant", "unit", "value")])
} else {
as.data.frame(df[, c("date", "hour", "zone", "pollutant", "unit", "value")])
}
},
error = function(cond) {
message("An error occurred downloading data from www.aire.cdmx.gob.mx:")
message(cond)
return(NULL)
}
)
} |
library("MAPA")
library("parallel")
library("thief")
library("pbmcapply")
ncore = detectCores()-4
set.seed(12345)
perd = "QUARTERLY"
h.fc = 8
freq = 4
load("mydata.full.ts.rda")
forx.b = function(x, h.fc, frequency = freq) {
lambda = BoxCox.lambda(na.contiguous(x), method = "guerrero",lower = 0, upper = 1)
x.bc = BoxCox(x, lambda)
mapa.bc = InvBoxCox(mapa(x.bc, fh = h.fc, outplot = 0)$outfor, lambda = lambda)
thief.bc.ets = InvBoxCox(thief(x.bc,h=h.fc,usemodel ="ets")$mean, lambda = lambda)
thief.bc.arm = InvBoxCox(thief(x.bc,h = h.fc,usemodel ="arima")$mean, lambda = lambda)
return(cbind(mapa.bc = as.vector(mapa.bc), thief.ets = as.vector(thief.bc.ets), thief.arm = as.vector(thief.bc.arm)))
}
system.time(for.M4.mapa<- pbmclapply(mydata.full.ts, forx.b, h.fc = h.fc, frequency = freq, mc.cores = ncore))
save(for.M4.mapa, file = paste0("M4_mapa_", perd, "_srihari.rda")) |
train <- data.frame(ClaimID = c(1,2,3), RearEnd = c(TRUE, FALSE, TRUE), Fraud = c(TRUE, FALSE, TRUE))
train
library(rpart)
mytree <- rpart(Fraud ~ RearEnd, data = train, method = "class")
mytree
mytree <- rpart(Fraud ~ RearEnd, data = train, method = "class", minsplit = 2, minbucket = 1)
mytree
library(rattle)
library(rpart.plot)
library(RColorBrewer)
fancyRpartPlot(mytree)
mytree <- rpart(Fraud ~ RearEnd, data = train, method = "class", parms = list(split = 'information'), minsplit = 2, minbucket = 1)
mytree
train <- data.frame(ClaimID = c(1,2,3), RearEnd = c(TRUE, FALSE, TRUE), Fraud = c(TRUE, FALSE, FALSE))
train
mytree <- rpart(Fraud ~ RearEnd, data = train, method = "class", minsplit = 2, minbucket = 1)
mytree
rpart.plot(mytree)
mytree <- rpart(Fraud ~ RearEnd, data = train, method = "class", minsplit = 2, minbucket = 1, cp=-1)
fancyRpartPlot(mytree)
train
mytree <- rpart(Fraud ~ RearEnd, data = train, method = "class", minsplit = 2, minbucket = 1, weights = c(.4, .4, .2))
mytree
fancyRpartPlot(mytree)
train <- data.frame(ClaimID = c(1,2,3,4,5,6,7), RearEnd = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE), Whiplash = c(TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE),Fraud = c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE))
train
mytree <- rpart(Fraud ~ RearEnd + Whiplash, data = train, method = "class", maxdepth = 1, minsplit = 2, minbucket = 1)
mytree
fancyRpartPlot(mytree)
lossmatrix <- matrix(c(0,1,3,0), byrow=TRUE, nrow=2)
lossmatrix
mytree <- rpart(Fraud ~ RearEnd + Whiplash, data = train, method = "class", maxdepth = 1, minsplit = 2, minbucket = 1,parms = list(loss = lossmatrix))
fancyRpartPlot(mytree)
train <- data.frame(ClaimID = c(1,2,3,4,5,6,7,8,9,10),RearEnd = c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE), Whiplash = c(TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE), Activity = factor(c("active", "very active", "very active", "inactive", "very inactive", "inactive", "very inactive", "active", "active", "very active"),levels=c("very inactive", "inactive", "active", "very active"), ordered=TRUE),Fraud = c(FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE))
train
mytree <- rpart(Fraud ~ RearEnd + Whiplash + Activity, data = train, method = "class", minsplit = 2, minbucket = 1, cp=-1)
fancyRpartPlot(mytree)
mytree$variable.importance
printcp(mytree)
mytree <- prune(mytree, cp=.21)
fancyRpartPlot(mytree)
test <- data.frame(ClaimID = c(1,2,3,4,5,6,7,8,9,10),RearEnd = c(FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE), Whiplash = c(FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE), Activity = factor(c("inactive", "very active", "very active", "inactive", "very inactive", "inactive", "very inactive", "active", "active", "very active"),levels=c("very inactive", "inactive", "active", "very active"), ordered=TRUE))
test
test$FraudClass <- predict(mytree, newdata = test, type="class")
test$FraudProb <- round(predict(mytree, newdata = test, type="prob"),2)
test |
kgvar <- function(y, centers, iter.max = 10, conf.level = 0.95)
UseMethod("kgvar")
kgvar.default <- function(y, centers, iter.max = 10, conf.level = 0.95) {
if(length(centers) > 1){k <- length(centers)}
if(length(centers) == 1){k <- centers}
N <- dim(y)[2]
T <- dim(y)[1]
h <- 0.1
p <- conf.level
K <- floor((0.4258597) * T / (log(T)))
GRID <- seq(0.05, 1, length = 50)
I <- 1:T
HILL <- numeric(N)
G <- function(x)
((15 / 16) * (1 - x^2)^2) * (x <= 1) * (-1 <= x)
a <- numeric(N)
for(l in 1:N) {
y.ord <- sort(y[, l])
U <- y.ord[T - K]
HILL[l] <- (1 / K) * sum(log(y.ord[(T - K + 1):T]) - log(y.ord[T - K]))
SCEDASIS <- function(s)
(1 / (K * h)) * sum((y[, l] > y.ord[T - K]) * G((s - (I / T)) / h))
SS <- numeric(T)
for(j in 1:T)
SS[j] <- (SCEDASIS(j / T))^(1 / HILL[l])
a[l] <- (U * (K)^(HILL[l])) / (sum(SS))^(HILL[l])
}
Varf <- function(s, l) {
y.ord <- sort(y[, l])
log((a[l]/((1-p)^(HILL[l])))*(1 / (K * h)) *
sum((y[, l] > y.ord[T - K]) * G((s - (I / T)) / h)))
}
if(length(centers) > 1){Ik = centers}
if(length(centers) == 1){Ik <- sort(sample(seq(1, N, 1), k))}
mus <- function(s, j)
Varf(s, Ik[j])
M <- matrix(0, nrow = iter.max, ncol = N)
sintegral <- function (x, fx, n.pts = max(256, length(x)))
{
if (class(fx) == "function")
fx = fx(x)
n.x = length(x)
if (n.x != length(fx))
stop("Unequal input vector lengths")
ap = approx(x, fx, n = 2 * n.pts + 1)
h = diff(ap$x)[1]
integral = h * (ap$y[2 * (1:n.pts) - 1] + 4 * ap$y[2 * (1:n.pts)] +
ap$y[2 * (1:n.pts) + 1])/3
results = list(value = sum(integral),
cdf = list(x = ap$x[2 * (1:n.pts)],
y = cumsum(integral)))
class(results) = "sintegral"
return(results)
}
cat(format("\nRendering\n"))
cat(format("=========\n"))
cat(1, "\n")
clasification <- numeric(N)
for(i in 1:N) {
dist <- numeric(k)
for(j in 1:k) {
V<-function(x)
(Varf(x, i) - mus(x, j))^2
dist[j] <- sintegral(GRID, Vectorize(V))$value
}
clasification[i] <- which.min(dist)
}
mus.new <- function(s, j) {
aux.1 <- c()
for(i in 1:N)
aux.1[i] <- Varf(s, i) * (1 * (clasification == j))[i]
sum(aux.1) / sum(1 * (clasification == j))
}
M[1, ] <- clasification
for(z in 2:iter.max) {
cat(format(z), "\n")
for(i in 1:N) {
dist <- numeric(k)
for(j in 1:k) {
V.new<-function(s)
(Varf(s, i) - mus.new(s, j))^2
dist[j] <- sintegral(GRID, Vectorize(V.new))$value
}
clasification[i] <- which.min(dist)
}
mus.new <- function(s, j) {
aux.1 <- c()
for(i in 1:N)
aux.1[i] <- Varf(s, i) * (1 * (clasification == j))[i]
sum(aux.1) / sum(1 * (clasification == j))
}
M[z, ] <- clasification
if(prod(1 * (M[z, ] == M[(z - 1), ])) == 1)
break
}
outputs <- list(Y = y, n.clust = k, scale.param = a,
conf.level = conf.level, hill = HILL, var.new = mus.new,
clusters = M[z - 1,])
class(outputs) <- "kgvar"
return(outputs)
}
plot.kgvar <- function(x, c.c = FALSE, xlab = "w",
ylab = "Value-at-risk function", ...) {
N <- dim(x$Y)[2]
T <- dim(x$Y)[1]
h <- 0.1
a <- x$scale.param
p <- x$conf.level
HILL <- x$hill
K <- floor((0.4258597) * T / (log(T)))
grid <- seq(0, 1, length = 100)
Varf <- function(s, l) {
y.ord <- sort(x$Y[, l])
I <- 1:T
(a[l]/((1-p)^(HILL[l])))*(1 / (K * h)) *
sum((x$Y[, l] > y.ord[T - K]) * G((s - (I / T)) / h))
}
G <- function(x)
((15 / 16) * (1 - x^2)^2) * (x <= 1) * (-1 <= x)
s1 <- lapply(grid, Varf, 1)
plot(grid, s1, type = 'l', xlab = xlab, ylab = ylab, col = 'gray', ...)
for(i in 1:N) {
s <- as.numeric(lapply(grid,Varf,i))
lines(grid, s, type = 'l', lwd = 8, col = 'gray')
}
Newvar2 <- function(s,j){exp(x$var.new(s,j))}
if(c.c) {
for(j in 1:x$n.clust){
y <- lapply(grid, Newvar2, j)
lines(grid, y, type = 'l', lwd = 8, col = "blue", lty = 6)
}
}
} |
knitr::opts_chunk$set(
warning = FALSE,
message = FALSE,
fig.height = 5,
fig.width = 5
)
options(digits=4)
par(mar=c(3,3,1,1)+.1)
set.seed(1)
library(SimDesign)
Design <- createDesign(N = c(10,20,30))
Generate <- function(condition, fixed_objects = NULL) {
ret <- with(condition, rnorm(N))
ret
}
Analyse <- function(condition, dat, fixed_objects = NULL) {
whc <- sample(c(0,1,2,3), 1, prob = c(.7, .20, .05, .05))
if(whc == 0){
ret <- mean(dat)
} else if(whc == 1){
ret <- t.test()
} else if(whc == 2){
ret <- t.test('invalid')
} else if(whc == 3){
stop('Manual error thrown')
}
if(sample(c(TRUE, FALSE), 1, prob = c(.1, .9)))
warning('This warning happens rarely')
if(sample(c(TRUE, FALSE), 1, prob = c(.5, .5)))
warning('This warning happens much more often')
ret
}
Summarise <- function(condition, results, fixed_objects = NULL) {
ret <- c(bias = bias(results, 0))
ret
}
set.seed(1)
result <- runSimulation(Design, replications = 100,
generate=Generate, analyse=Analyse, summarise=Summarise)
print(result)
SimExtract(result, what = 'errors')
seeds <- SimExtract(result, what = 'error_seeds')
head(seeds[,1:3]) |
read_table_nm <- function(
file = NULL,
skip = NULL,
header = NULL,
rm_duplicates = FALSE,
nonmem_tab = TRUE) {
if(is.null(file)) {
stop('Argument \"file\" required.')
}
if(!any(file.exists(file))) {
stop('No file not found.')
} else {
file <- file[file.exists(file)]
}
if(nonmem_tab) {
if(is.null(skip) & is.null(header)) {
test <- readLines(file[1], n = 3)
skip <- ifelse(grepl('TABLE NO', test[1]), 1, 0)
header <- ifelse(grepl('[a-zA-Z]', test[2]), TRUE, FALSE)
}
tab_file <- do.call('cbind', lapply(file, readr::read_table,
skip = skip, col_names = header))
tab_file <- as.data.frame(apply(tab_file, MARGIN = 2, FUN = as.numeric))
tab_file <- na.omit(tab_file)
if(header) {
colnames(tab_file)[grepl('\n',colnames(tab_file))] <-
gsub('\n.+', '', colnames(tab_file)[grepl('\n', colnames(tab_file))])
}
} else {
skip <- max(grep('TABLE NO', readLines(file[1])))
tab_file <- do.call('cbind', lapply(file, read.table, skip = skip,
header = FALSE, fill = TRUE, as.is = TRUE))
colnames(tab_file) <- tab_file[1, ]
tab_file <- suppressWarnings(as.data.frame(apply(tab_file[-1, ], 2, as.numeric)))
}
if(rm_duplicates) {
tab_file <- tab_file[, !duplicated(colnames(tab_file))]
}
return(tab_file)
} |
context("aglm-input")
library(aglm)
createX <- function(nobs, nvar_int, nvar_numeric, nvar_ordered, nvar_factor, seed=12345) {
set.seed(seed)
nobs <- nobs
nvar <- nvar_int + nvar_numeric + nvar_ordered + nvar_factor
data <- list()
if (nvar_int > 0) for (i in 1:nvar_int) data[[paste0("Int", i)]] <- sample(1:10, size=nobs, replace=TRUE)
if (nvar_numeric > 0) for (i in 1:nvar_numeric) data[[paste0("Num", i)]] <- rnorm(nobs)
if (nvar_ordered > 0) for (i in 1:nvar_ordered) data[[paste0("Ord", i)]] <- ordered(sample(1:5, size=nobs, replace=TRUE))
if (nvar_factor > 0) for (i in 1:nvar_factor) data[[paste0("Fac", i)]] <- factor(sample(c("A", "B", "C"), nobs, replace=TRUE))
return(data.frame(data))
}
test_that("Check returned values of newInput() for each input type", {
x <- newInput(createX(10, 1, 1, 1, 1))
expect_equal(x@vars_info[[1]]$id, 1)
expect_equal(x@vars_info[[1]]$data_column_idx, 1)
expect_equal(x@vars_info[[1]]$type, "quan")
expect_equal(x@vars_info[[1]]$use_linear, TRUE)
expect_equal(x@vars_info[[1]]$use_UD, FALSE)
expect_equal(x@vars_info[[1]]$use_OD, TRUE)
expect_true(!is.null(x@vars_info[[1]]$OD_info))
expect_true(is.null(x@vars_info[[1]]$UD_info))
expect_equal(x@vars_info[[2]]$id, 2)
expect_equal(x@vars_info[[2]]$data_column_idx, 2)
expect_equal(x@vars_info[[2]]$type, "quan")
expect_equal(x@vars_info[[2]]$use_linear, TRUE)
expect_equal(x@vars_info[[2]]$use_UD, FALSE)
expect_equal(x@vars_info[[2]]$use_OD, TRUE)
expect_true(!is.null(x@vars_info[[2]]$OD_info))
expect_true(is.null(x@vars_info[[2]]$UD_info))
expect_equal(x@vars_info[[3]]$id, 3)
expect_equal(x@vars_info[[3]]$data_column_idx, 3)
expect_equal(x@vars_info[[3]]$type, "qual")
expect_equal(x@vars_info[[3]]$use_linear, FALSE)
expect_equal(x@vars_info[[3]]$use_UD, TRUE)
expect_equal(x@vars_info[[3]]$use_OD, TRUE)
expect_true(!is.null(x@vars_info[[3]]$UD_info))
expect_true(!is.null(x@vars_info[[3]]$OD_info))
expect_equal(x@vars_info[[4]]$id, 4)
expect_equal(x@vars_info[[4]]$data_column_idx, 4)
expect_equal(x@vars_info[[4]]$type, "qual")
expect_equal(x@vars_info[[4]]$use_linear, FALSE)
expect_equal(x@vars_info[[4]]$use_UD, TRUE)
expect_equal(x@vars_info[[4]]$use_OD, FALSE)
expect_true(!is.null(x@vars_info[[4]]$UD_info))
expect_true(is.null(x@vars_info[[4]]$OD_info))
})
test_that("Check add_xxx flags of newInput()", {
x <- newInput(createX(10, 1, 1, 1, 1), add_interaction_columns=FALSE)
expect_equal(length(x@vars_info), 4)
x <- newInput(createX(10, 1, 1, 1, 1), add_linear_columns=FALSE, add_interaction_columns=FALSE)
expect_true(all(sapply(x@vars_info, function(var) {!var$use_linear})))
x <- newInput(createX(10, 1, 1, 1, 1), add_OD_columns_of_qualitatives=FALSE, add_interaction_columns=FALSE)
expect_true(all(sapply(x@vars_info, function(var) {var$type=="quan" | !var$use_OD})))
})
test_that("Check bins_list of newInput()", {
bins_list <- list(c(0, 1, 2))
x <- newInput(createX(10, 0, 5, 0, 0), bins_list=bins_list)
expect_equal(x@vars_info[[1]]$OD_info$breaks, bins_list[[1]])
bins_names <- list(3)
x <- newInput(createX(10, 0, 5, 0, 0), bins_list=bins_list, bins_names=bins_names)
expect_equal(x@vars_info[[3]]$OD_info$breaks, bins_list[[1]])
bins_names <- list("Num5")
x <- newInput(createX(10, 0, 5, 0, 0), bins_list=bins_list, bins_names=bins_names)
})
test_that("Check return values of getDesignMatrix()", {
x_int <- newInput(createX(10, 1, 0, 0, 0), add_interaction_columns=FALSE)
mat_int <- getDesignMatrix(x_int)
expect_equal(mat_int[,1], x_int@data[,1])
expect_equal(dim(mat_int), c(10, dim(getODummyMatForOneVec(mat_int[,1])$dummy_mat)[2] + 1))
x_num <- newInput(createX(10, 0, 1, 0, 0), add_interaction_columns=FALSE)
mat_num <- getDesignMatrix(x_num)
expect_equal(mat_num[,1], x_num@data[,1])
expect_equal(dim(mat_num), c(10, dim(getODummyMatForOneVec(mat_num[,1])$dummy_mat)[2] + 1))
x_ord <- newInput(createX(10, 0, 0, 1, 0), add_interaction_columns=FALSE)
mat_ord <- getDesignMatrix(x_ord)
expect_equal(dim(mat_ord), c(10,
dim(getODummyMatForOneVec(x_ord@data[,1])$dummy_mat)[2]
+ dim(getUDummyMatForOneVec(x_ord@data[,1], drop_last=FALSE)$dummy_mat)[2]))
x_fac <- newInput(createX(10, 0, 0, 0, 1), add_interaction_columns=FALSE)
mat_fac <- getDesignMatrix(x_fac)
expect_equal(dim(mat_fac), c(10, dim(getUDummyMatForOneVec(x_fac@data[,1], drop_last=FALSE)$dummy_mat)[2]))
x_all <- newInput(data.frame(x_int@data, x_num@data, x_ord@data, x_fac@data), add_interaction_columns=FALSE)
mat_all <- getDesignMatrix(x_all)
expect_equal(mat_all, cbind(mat_int, mat_num, mat_ord, mat_fac))
x_inter <- newInput(data.frame(x_int@data, x_fac@data), add_interaction_columns=TRUE)
mat_inter <- getDesignMatrix(x_inter)
a <- dim(mat_int)[2] + dim(mat_fac)[2]
b <- dim(x_int@data)[2] + dim(mat_fac)[2]
expect_equal(dim(mat_inter), c(10, a + b * (b - 1) / 2))
}) |
LEAPFrOG<-function(data,p,Nudge=0.001,NonLinCon=TRUE){
P<-dim(as.matrix(p))[2]
if(P<2) return(print("Error: LEORAH requires 2 or more reference populations"))
if(length(data)!=dim(as.matrix(p))[1]) return("Error: Number of SNPs in data and reference frequencies is not the same")
if(!(is.numeric(Nudge))) Nudge=0.001
if(!(Nudge>0)) Nudge=0.001
options(warn=-1)
data2=data[!is.na(data)]
p2=p[!is.na(data),]
data2=data2[rowSums(p2)<P]
p2=p2[rowSums(p2)<P,]
data2=data2[rowSums(p2)>0]
p2=p2[rowSums(p2)>0,]
q2=1-p2
nSNP=length(data2)
A <<- matrix( nrow=2*nSNP, ncol=P )
for (j in 1:P) {
A[1:nSNP,j]<-(data2==0)*q2[,j] + (data2==1)*2*p2[,j] + (data2==2)*p2[,j]
A[(nSNP+1):(2*nSNP),j] <- (data2==0)*q2[,j] + (data2==1)*q2[,j] + (data2==2)*p2[,j]
}
Ab<<-matrix(nrow=2*nSNP,ncol=P)
Ab[,P]=A[,P]
for (j in 1:(P-1)) {
Ab[,j] <- A[,j]-A[,P]
}
B<<-matrix( nrow=2*nSNP, ncol=P )
for (j in 1:P) {
B[1:nSNP,j]<-(data2==0)*-1*p2[,j] +(data2==2)*-1*p2[,j]+(data2==1)*2*p2[,j]
B[(nSNP+1):(2*nSNP),j]<-p2[,j]
}
Bb<<-matrix(nrow=2*nSNP,ncol=P-1)
for (j in 1:(P-1)){
Bb[,j] <- B[,P]-B[,j]
}
fadmix <- function(m) {
D=m[P:length(m)]
m=m[1:(P-1)]
Ivec=m*(m<=0.5)+(1-m)*(m>0.5)
BK=as.matrix(0-Bb)%*%as.vector(2*D*Ivec)
BK=BK+(as.matrix(Bb)%*%as.vector(Ivec))
AK=Ab%*%as.vector(c(m,1))
-sum(log(BK[1:nSNP]*BK[(nSNP+1):(nSNP*2)]+AK[1:nSNP]*AK[(nSNP+1):(nSNP*2)]))
}
gadmix <- function(m){
D=m[P:length(m)]
m=m[1:(P-1)]
Ivec=m*(m<=0.5)+(1-m)*(m>0.5)
AK=Ab%*%as.vector(c(m,1))
A1=A[1:nSNP,]
A2=A[(nSNP+1):(2*nSNP),]
B1=B[1:nSNP,]
B2=B[(nSNP+1):(2*nSNP),]
BK=as.matrix(0-Bb)%*%as.vector(2*D*Ivec)
BK=BK+(as.matrix(Bb)%*%as.vector(Ivec))
denom=BK[1:nSNP]*BK[(nSNP+1):(nSNP*2)]+AK[1:nSNP]*AK[(nSNP+1):(2*nSNP)]
grads=matrix(nrow=P-1,ncol=2)
for(j in 1:(P-1)){
BKnoJ=as.matrix(0-Bb[,-j])%*%as.vector(2*D[-j]*Ivec[-j])
BKnoJ=BKnoJ+(as.matrix(Bb[,-j])%*%as.vector(Ivec[-j]))
BKJ=as.matrix(0-Bb[,j])%*%as.vector(2*D[j])
BKJ=BKJ+as.matrix(Bb[,j])
AKnoJ=as.matrix(Ab[,-c(j,P)])%*%as.vector(m[-j])
grads[j,2]=-sum((2*(Ivec[j]^2)*(4*D[j]*B1[,j]*B2[,j]-4*D[j]*B1[,j]*B2[,P]-2*B1[,j]*B2[,j]+2*B1[,j]*B2[,P]+2*B1[,P]*B2[,j]-2*B1[,P]*B2[,P]-4*D[j]*B1[,P]*B2[,j]+4*D[j]*B1[,P]*B2[,P])+2*Ivec[j]*((B1[,j]-B1[,P])*BKnoJ[(nSNP+1):(2*nSNP)]+(B2[,j]-B2[,P])*BKnoJ[1:nSNP]))/denom)
grads[j,1]=-sum((AKnoJ[1:nSNP]*(A2[,j]-A2[,P])+ AKnoJ[(nSNP+1):(2*nSNP)]*(A1[,j]-A1[,P])+A1[,P]*A2[,j]+A1[,j]*A2[,P]+2*(m[j]*A1[,P]*A2[,P]+m[j]*A1[,j]*A2[,j]-A1[,P]*A2[,P]-m[j]*A1[,j]*A2[,P]-m[j]*A1[,P]*A2[,j])+((m[j]<=0.5)-(m[j]>0.5))*(2*((m[j]<=0.5)-(m[j]>0.5))*m[j]*BKJ[1:nSNP]*BKJ[(nSNP+1):(2*nSNP)]+BKJ[(nSNP+1):(2*nSNP)]*BKnoJ[1:nSNP]+2*(m[j]>0.5)*BKJ[1:nSNP]*BKJ[(nSNP+1):(2*nSNP)]+BKJ[1:nSNP]*BKnoJ[(nSNP+1):(2*nSNP)]))/denom)
}
as.vector(grads)
}
if(!NonLinCon){
ui = rbind( diag(P-1),-diag(P-1),rep(-1,P-1))
ui=cbind(ui,matrix(rep(0,(2*(P-1)+1)*(P-1)),nrow=2*(P-1)+1,ncol=P-1))
ui=rbind(ui,cbind(matrix(rep(0,(P-1)*(P-1)),ncol=P-1,nrow=P-1),diag(P-1)))
ui=rbind(ui,cbind(matrix(rep(0,(P-1)*(P-1)),ncol=P-1,nrow=P-1),-diag(P-1)))
ci = c( rep(0,P-1),rep(-1,P),0.5,rep(0,P-2),rep(-1,P-1))
COres <- constrOptim2(theta=c(rep((1/P),P-1),0.5+Nudge,rep(0.5,P-2)),f=fadmix,grad=gadmix, ui=ui, ci=ci,hessian=TRUE)
}else{
hadmix<-function(m){
D=m[P:length(m)]
m=m[1:(P-1)]
mins=vector(length=(2*P)-2);maxs=mins
mins[1:(P-1)]=m
mins[P]=D[1]-0.5
if(P>2){mins[(P+1):length(mins)]=D[2:(P-1)]}
maxs[1:(P-1)]=1-m
maxs[P:length(mins)]=1-D
maxs2=c(1-sum(m),0.5-(sum(D[m<=0.5]*m[m<=0.5])+sum(D[m>0.5]*(1-m[m>0.5]))+sum(m[m>0.5]-0.5)),0.5-(sum((1-D[m<=0.5])*m[m<=0.5])+sum((1-D[m>0.5])*(1-m[m>0.5]))+sum(m[m>0.5]-0.5)))
c(mins,maxs,maxs2)
}
COres <- auglag(par=c(rep((1/P),P-1),0.5+Nudge,rep(0.5,P-2)),fn=fadmix,gr=gadmix,hin=hadmix)
}
P1=vector(length=P-1);P2=P1
mest=unlist(COres$par)[1:(P-1)]
Dest=unlist(COres$par)[P:(2*(P-1))]
P1[mest<=0.5]=2*mest[mest<=0.5]*Dest[mest<=0.5]
P2[mest<=0.5]=2*mest[mest<=0.5]*(1-Dest[mest<=0.5])
P1[mest>0.5]=2*(1-mest[mest>0.5])*Dest[mest>0.5]+2*(mest[mest>0.5]-0.5)
P2[mest>0.5]=2*(1-mest[mest>0.5])*(1-Dest[mest>0.5])+2*(mest[mest>0.5]-0.5)
options(warn=0)
mest=list(m=c(mest,1-sum(mest)));Dest=list(D=c(Dest,1-sum(Dest)))
se=sqrt(diag(ginv(COres$hessian)))
P1=list(P1=c(P1,1-sum(P1)));P2=list(P2=c(P2,1-sum(P2)))
return(c(mest,Dest,list(mse=se[1:(P-1)]),list(Dse=se[P:(2*(P-1))]),P1,P2,COres[2:3]))
}
LEAPFrOG_plot<-function(Results,PopNames,SampNames=NULL){
oldpar=par(mfrow=c(1,3),omi=c(0.9,0,0,0))
P=dim(Results)[2]
barplot(Results[1,,],space=0,names.arg=SampNames,las=2,ylim=c(0,1), col=2:(P+2),main="Admixture in observed individuals")
barplot(Results[2,,],space=0,names.arg=SampNames,las=2,ylim=c(0,1), col=2:(P+2),main="Admixture in parents 'A'")
barplot(Results[3,,],space=0,names.arg=SampNames,las=2,ylim=c(0,1), col=2:(P+2),main="Admixture in parents 'B'")
par(xpd=NA)
legend(x=0,y=-0.25,legend=PopNames,col=2:(P+2),pch=15,cex=1.25)
par(oldpar)
}
LEAPFrOG_EM<-function(data,p,chr,alpha=1e-6){
P=dim(p)[2]
data2=data[rowSums(!is.na(data))==2,]
p2=p[rowSums(!is.na(data))==2,]
data2=data2[rowSums(p2)<P,]
p2=p2[rowSums(p2)<P,]
data2=data2[rowSums(p2)>0,]
p2=p2[rowSums(p2)>0,]
q2=1-p2
nSNP=dim(data2)[1]
nChr<-nlevels(as.factor(chr))
nSNP2<<-vector(length=nChr);y<<-c(1,rep(0.5,nChr-1))
for(c in 1:nChr) nSNP2[c]=sum(chr==c)
write.table(paste("from mpmath import *\nimport sys\nstem = '",getwd(),"/EMPAtemp.txt'\nf = open(stem, 'r')\nvals=[]\nline = str\nwhile line:\n\tline = f.readline()\n\tif line:\n\t\tvals.append(float(line))\nmp.dps=1000\nanswer=exp(vals[0]-log(exp(vals[1])+exp(vals[2])))\nFILE = open('EMPAtemp2.txt','w')\nFILE.write(str(answer)+' ')\n",sep=""),quote=FALSE,row.names=FALSE,col.names=FALSE,file="EMPA.py")
A1<<-array(dim=c(max(nSNP2),P,nChr))
A2<<-A1
for(c in 1:nChr){
for (j in 1:P) {
A1[1:nSNP2[c],j,c]<-(data2[chr==c,1]==0)*q2[chr==c,j]+ (data2[chr==c,1]==1)*p2[chr==c,j]
A2[1:nSNP2[c],j,c]<-(data2[chr==c,2]==0)*q2[chr==c,j]+ (data2[chr==c,2]==1)*p2[chr==c,j]
}
for (j in 1:(P-1)) {
A1[1:nSNP2[c],j,c] <- A1[1:nSNP2[c],j,c]-A1[1:nSNP2[c],P,c]
A2[1:nSNP2[c],j,c] <- A2[1:nSNP2[c],j,c]-A2[1:nSNP2[c],P,c]
}
}
i=1
repeat{
if(i>1){
for(c in 2:nChr){
l1=sum(log((A1[1:nSNP2[c],,c]%*%as.matrix(c(u1,1)))* (A2[1:nSNP2[c],,c]%*%as.matrix(c(u2,1)))))
l0a=l1
l0b=sum(log((A1[1:nSNP2[c],,c]%*%as.matrix(c(u2,1)))* (A2[1:nSNP2[c],,c]%*%as.matrix(c(u1,1)))))
write.table(c(l1,l0a,l0b),file="EMPAtemp.txt",quote=FALSE,row.names=FALSE,col.names=FALSE)
system("python EMPA.py",wait=TRUE)
y[c]<-as.numeric(scan("EMPAtemp2.txt",what=numeric(0),quiet=TRUE))
}
}
l2<-function(m){
u1=m[1:(P-1)]
u2=m[P:(2*(P-1))]
l=vector(length=nChr)
for(c in 1:nChr){ l[c]=sum(log(y[c]*(A1[1:nSNP2[c],,c]%*%as.matrix(c(u1,1)))*(A2[1:nSNP2[c],,c]%*%as.matrix(c(u2,1)))+(1-y[c])*(A1[1:nSNP2[c],,c]%*%as.matrix(c(u2,1)))*(A2[1:nSNP2[c],,c]%*%as.matrix(c(u1,1)))))
}
-sum(l)
}
derivs<-function(m){
u1=m[1:(P-1)]
u2=m[P:(2*(P-1))]
grad1=matrix(ncol=P-1,nrow=nChr);grad2=grad1
for(c in 1:nChr){
for(j in 1:(P-1)){ grad1[c,j]=sum((y[c]*A1[1:nSNP2[c],j,c]*(A2[1:nSNP2[c],,c]%*%as.matrix(c(u2,1)))+(1-y[c])*A2[1:nSNP2[c],j,c]*(A1[1:nSNP2[c],,c]%*%as.matrix(c(u2,1))))/ (y[c]*(A1[1:nSNP2[c],,c]%*%as.matrix(c(u1,1)))*(A2[1:nSNP2[c],,c]%*%as.matrix(c(u2,1)))+(1-y[c])*(A1[1:nSNP2[c],,c]%*%as.matrix(c(u2,1)))*(A2[1:nSNP2[c],,c]%*%as.matrix(c(u1,1)))))
grad2[c,j]=sum(((1-y[c])*A1[1:nSNP2[c],j,c]*(A2[1:nSNP2[c],,c]%*%as.matrix(c(u1,1)))+y[c]*A2[1:nSNP2[c],j,c]*(A1[1:nSNP2[c],,c]%*%as.matrix(c(u1,1))))/ (y[c]*(A1[1:nSNP2[c],,c]%*%as.matrix(c(u1,1)))*(A2[1:nSNP2[c],,c]%*%as.matrix(c(u2,1)))+(1-y[c])*(A1[1:nSNP2[c],,c]%*%as.matrix(c(u2,1)))*(A2[1:nSNP2[c],,c]%*%as.matrix(c(u1,1)))))
}
}
-c(colSums(grad1),colSums(grad2))
}
ui = rbind( diag(2*(P-1)),-diag(2*(P-1)),c(rep(-1,P-1), rep(0,P-1)),c(rep(0,P-1), rep(-1,P-1)))
ci = c(rep(0,2*(P-1)),rep(-1,2*(P)))
if(i>1) oldu=c(u1,u2)
z1=constrOptim(theta=rep(1/P,2*(P-1)),f=l2,grad=derivs,ui=ui,ci=ci,hessian=TRUE)
u1=z1$par[1:(P-1)];u2=z1$par[P:(2*(P-1))]
if(i>1){
change=sum(abs(c(u1,u2)-oldu))
print(paste("Iteration=",i,"::Change=",change,sep=""))
if(change<alpha) break
}
i=i+1
}
errs=sqrt(diag(solve(z1$hessian)))
u1=c(u1,1-sum(u1));u2=c(u2,1-sum(u2))
return(list(m=rowMeans(cbind(u1,u2)),P1=u1,P2=u2,P1se=errs[1:(P-1)],P2se=errs[P:(2*(P-1))],iterations=i,value=z1$value))
}
BEAPFrOG<-function(data,p,nchains=1,iterations=1000,alpha=0.05,prior=1,burn=2000,SampSizes){
P<-dim(as.matrix(p))[2]
if(P<2) return(print("Error: LEORAH requires 2 or more reference populations"))
if(length(data)!=dim(as.matrix(p))[1]) return("Error: Number of SNPs in data and reference frequencies is not the same")
data2=data[!is.na(data)]
p2=p[!is.na(data),]
data2=data2[rowSums(p2)<P]
p2=p2[rowSums(p2)<P,]
data2=data2[rowSums(p2)>0]
p2=p2[rowSums(p2)>0,]
nSNP=length(data2)
fadmix="model {\nfor (i in 1:N){\nG[i]~dcat(probs[i,])\np1[i]<-sum(m1[1:(J-1)]*p[i,1:(J-1)])+(1-sum(m1[1:(J-1)]))*p[i,J]\np2[i]<-sum(m2[1:(J-1)]*p[i,1:(J-1)])+(1-sum(m2[1:(J-1)]))*p[i,J]\nprobs[i,1]<-(1-p1[i])*(1-p2[i])\nprobs[i,2]<-p1[i]*(1-p2[i])+p2[i]*(1-p1[i])\nprobs[i,3]<-p1[i]*p2[i]\nfor(j in 1:J){\np[i,j]~dnorm(pE[i,j],pT[i,j])T(0,1)\n}\n}\nfor(x in 1:J){\nalpha[x]<-prior\n}\nm1~ddirch(alpha)\nm2~ddirch(alpha)\n}\n"
write(fadmix,file="BEAPFrOG.bug")
tau=matrix(ncol=P,nrow=nSNP)
for(j in 1:P){
tau[,j]=(2*SampSizes[j])/(p2[,j]*(1-p2[,j]))
}
JagsModel <- jags.model('BEAPFrOG.bug',data = list('G'=data2+1,'N'=nSNP,'J'=P,'pE'=p2,'pT'=tau,'prior'=prior),n.chains = nchains,n.adapt = burn)
z1=coda.samples(JagsModel,c('m1','m2'),iterations)
cred.intervals=matrix(nrow=2*P,ncol=2)
modes=vector(length=2*P)
z2=as.matrix(z1[[1]])
flip=z2[,1]<0.5
p2flip=z2[flip,(P+1):(2*P)]
z2[flip,(P+1):(2*P)]=z2[flip,1:P]
z2[flip,1:P]=p2flip
for(i in 1:(2*P)){
chains=z2[,i]
chains=sort(chains)
chains=round(chains,digits=2)
modes[i]=as.numeric(names(sort(table(chains),decreasing=TRUE))[1])
IntSize=round(length(chains)*(1-alpha))
interval=chains[c(1,IntSize)]
min=interval[2]-interval[1]
minPos=1
for(x in 2:(length(chains)-IntSize+1)){
interval=chains[c(x,(x-1)+IntSize)]
width=interval[2]-interval[1]
if(width<min){min=width;minPos=x}
}
cred.intervals[i,]=chains[c(minPos,(minPos-1)+IntSize)]
}
P1i=cred.intervals[1:P,]
P2i=cred.intervals[(P+1):(2*P),]
colnames(P1i)=c("Lower_Interval","Upper_Interval")
colnames(P2i)=c("Lower_Interval","Upper_Interval")
return(list(P1est=modes[1:P],P2est=modes[(P+1):(2*P)],P1interval=P1i,P2interval=P2i,Monitor=z1))
}
constrOptim2 <- function (theta, f, grad, ui, ci, mu = 1e-04, control = list(),
method = if (is.null(grad)) "Nelder-Mead" else "BFGS", outer.iterations = 100,
outer.eps = 1e-05, hessian=FALSE, ...)
{
if (!is.null(control$fnscale) && control$fnscale < 0)
mu <- -mu
R <- function(theta, theta.old, ...) {
ui.theta <- ui %*% theta
gi <- ui.theta - ci
if (any(gi < 0))
return(NaN)
gi.old <- ui %*% theta.old - ci
bar <- sum(gi.old * log(gi) - ui.theta)
if (!is.finite(bar))
bar <- -Inf
f(theta, ...) - mu * bar
}
dR <- function(theta, theta.old, ...) {
ui.theta <- ui %*% theta
gi <- drop(ui.theta - ci)
gi.old <- drop(ui %*% theta.old - ci)
dbar <- colSums(ui * gi.old/gi - ui)
grad(theta, ...) - mu * dbar
}
if (any(ui %*% theta - ci <= 0))
stop("initial value not feasible")
obj <- f(theta, ...)
r <- R(theta, theta, ...)
for (i in 1L:outer.iterations) {
obj.old <- obj
r.old <- r
theta.old <- theta
fun <- function(theta, ...) {
R(theta, theta.old, ...)
}
gradient <- function(theta, ...) {
dR(theta, theta.old, ...)
}
a <- optim(theta.old, fun, gradient, control = control,
method = method, hessian=hessian, ...)
r <- a$value
if (is.finite(r) && is.finite(r.old) && abs(r - r.old)/(outer.eps +
abs(r - r.old)) < outer.eps)
break
theta <- a$par
obj <- f(theta, ...)
if (obj > obj.old * sign(mu))
break
}
if (i == outer.iterations) {
a$convergence <- 7
a$message <- "Barrier algorithm ran out of iterations and did not converge"
}
if (mu > 0 && obj > obj.old) {
a$convergence <- 11
a$message <- paste("Objective function increased at outer iteration",
i)
}
if (mu < 0 && obj < obj.old) {
a$convergence <- 11
a$message <- paste("Objective function decreased at outer iteration",
i)
}
a$outer.iterations <- i
a$barrier.value <- a$value
a$value <- f(a$par, ...)
a$barrier.value <- a$barrier.value - a$value
a
} |
print.MFAmix<-function (x, ...)
{
res.mfa <- x
if (!inherits(res.mfa, "MFAmix"))
stop("non convenient data")
cat("**Results of the Multiple Factor Analysis for mixed data (MFAmix)**\n")
cat("The analysis was performed on", nrow(res.mfa$global.pca$rec$X.quanti),
"individuals, described by", ncol(res.mfa$global.pca$rec$X), "variables\n")
cat("*Results are available in the following objects :\n\n")
res <- matrix("",13,2)
colnames(res) <- c("name", "description")
res[1, ] <- c("$eig", "eigenvalues")
res[2, ] <- c("$eig.separate", "eigenvalues of the separate analyses")
res[3, ] <- c("$separate.analyses", "separate analyses for each group of variables")
res[4, ] <- c("$groups", "results for all the groups")
res[5, ] <- c("$partial.axes", "results for the partial axes")
res[6, ] <- c("$ind", "results for the individuals")
res[7, ] <- c("$ind.partial", "results for the partial individuals")
res[8, ] <- c("$quanti", "results for the quantitative variables")
res[9, ] <- c("$levels", "results for the levels of the qualitative variables")
res[10, ] <- c("$quali", "results for the qualitative variables")
res[11,] <- c("$sqload", "squared loadings")
res[12, ] <- c("$listvar.group", "list of variables in each group")
res[13, ] <- c("$global.pca", "results for the global PCA")
if (!(is.null(x$sqload.sup)))
{
sup <- matrix("",6,2)
sup[1,] <- c("$quanti.sup", "results for the supp. quant. variables")
sup[2,] <- c("$levels.sup", "results for the levels of the supp. qual? variables")
sup[3,] <- c("$sqload.sup", "squared loadings of the supp? variables")
sup[4,] <- c("$partial.axes.sup", "results for the partial axes of supp. groups")
sup[5,] <- c("$listvar.group", "list of variables in supp. groups")
sup[6,] <- c("$group.sup", "coordinates of supp. groups")
res <- rbind(res,sup)
}
utils::write.table(res,row.names = FALSE)
} |
flow.frac <- function (A, nodes)
{
diag(A) <- 0
eig <- eigen(A)$values[1]
n <- ncol(A)
A[nodes,] <- 0
A[,nodes] <- 0
eye <- matrix(0,nrow=n,ncol=n)
diag(eye) <- 1
res <- det(eye - 1/eig*A)
return(res)
} |
release <- function(pkg = ".", check = FALSE, args = NULL) {
pkg <- as.package(pkg)
cran_version <- cran_pkg_version(pkg$package)
new_pkg <- is.null(cran_version)
if (yesno("Have you checked for spelling errors (with `spell_check()`)?")) {
return(invisible())
}
if (check) {
cat_rule(
left = "Building and checking",
right = pkg$package,
line = 2
)
check(pkg,
cran = TRUE, remote = TRUE, manual = TRUE,
build_args = args, run_dont_test = TRUE
)
}
if (yesno("Have you run `R CMD check` locally?")) {
return(invisible())
}
release_checks(pkg)
if (yesno("Were devtool's checks successful?")) {
return(invisible())
}
if (!new_pkg) {
show_cran_check <- TRUE
cran_details <- NULL
end_sentence <- " ?"
if (requireNamespace("foghorn", quietly = TRUE)) {
show_cran_check <- has_cran_results(pkg$package)
cran_details <- foghorn::cran_details(pkg = pkg$package)
}
if (show_cran_check) {
if (!is.null(cran_details)) {
end_sentence <- "\n shown above?"
cat_rule(paste0("Details of the CRAN check results for ", pkg$package))
summary(cran_details)
cat_rule()
}
cran_url <- paste0(
cran_mirror(), "/web/checks/check_results_",
pkg$package, ".html"
)
if (yesno(
"Have you fixed all existing problems at \n", cran_url,
end_sentence
)) {
return(invisible())
}
}
}
if (yesno("Have you checked on R-hub (with `check_rhub()`)?")) {
return(invisible())
}
if (yesno("Have you checked on win-builder (with `check_win_devel()`)?")) {
return(invisible())
}
deps <- if (new_pkg) 0 else length(revdep(pkg$package))
if (deps > 0) {
msg <- paste0(
"Have you checked the ", deps, " reverse dependencies ",
"(with the revdepcheck package)?"
)
if (yesno(msg)) {
return(invisible())
}
}
questions <- c(
"Have you updated `NEWS.md` file?",
"Have you updated `DESCRIPTION`?",
"Have you updated `cran-comments.md?`",
if (file_exists("codemeta.json")) "Have you updated codemeta.json with codemetar::write_codemeta()?",
find_release_questions(pkg)
)
for (question in questions) {
if (yesno(question)) return(invisible())
}
if (uses_git(pkg$path)) {
git_checks(pkg)
if (yesno("Were Git checks successful?")) {
return(invisible())
}
}
submit_cran(pkg, args = args)
invisible(TRUE)
}
has_cran_results <- function(pkg) {
cran_res <- foghorn::cran_results(
pkg = pkg,
show = c("error", "fail", "warn", "note")
)
sum(cran_res[, -1]) > 0
}
find_release_questions <- function(pkg = ".") {
pkg <- as.package(pkg)
q_fun <- pkgload::ns_env(pkg$package)$release_questions
if (is.null(q_fun)) {
character()
} else {
q_fun()
}
}
yesno <- function(...) {
yeses <- c("Yes", "Definitely", "For sure", "Yup", "Yeah", "Of course", "Absolutely")
nos <- c("No way", "Not yet", "I forget", "No", "Nope", "Uhhhh... Maybe?")
cat(paste0(..., collapse = ""))
qs <- c(sample(yeses, 1), sample(nos, 2))
rand <- sample(length(qs))
utils::menu(qs[rand]) != which(rand == 1)
}
email <- function(address, subject, body) {
url <- paste(
"mailto:",
utils::URLencode(address),
"?subject=", utils::URLencode(subject),
"&body=", utils::URLencode(body),
sep = ""
)
tryCatch({
utils::browseURL(url, browser = email_browser())
},
error = function(e) {
cli::cli_alert_danger("Sending failed with error: {e$message}")
cat("To: ", address, "\n", sep = "")
cat("Subject: ", subject, "\n", sep = "")
cat("\n")
cat(body, "\n", sep = "")
}
)
invisible(TRUE)
}
email_browser <- function() {
if (!identical(.Platform$GUI, "RStudio")) {
return(getOption("browser"))
}
if (.Platform$OS.type == "windows") {
return(NULL)
}
browser <- Sys.which(c("xdg-open", "open"))
browser[nchar(browser) > 0][[1]]
}
maintainer <- function(pkg = ".") {
pkg <- as.package(pkg)
authors <- pkg$`authors@r`
if (!is.null(authors)) {
people <- eval(parse(text = authors))
if (is.character(people)) {
maintainer <- utils::as.person(people)
} else {
maintainer <- Find(function(x) "cre" %in% x$role, people)
}
} else {
maintainer <- pkg$maintainer
if (is.null(maintainer)) {
stop("No maintainer defined in package.", call. = FALSE)
}
maintainer <- utils::as.person(maintainer)
}
list(
name = paste(maintainer$given, maintainer$family),
email = maintainer$email
)
}
cran_comments <- function(pkg = ".") {
pkg <- as.package(pkg)
path <- path(pkg$path, "cran-comments.md")
if (!file_exists(path)) {
warning("Can't find cran-comments.md.\n",
"This file gives CRAN volunteers comments about the submission,\n",
"Create it with use_cran_comments().\n",
call. = FALSE
)
return(character())
}
paste0(readLines(path, warn = FALSE), collapse = "\n")
}
cran_submission_url <- "https://xmpalantir.wu.ac.at/cransubmit/index2.php"
submit_cran <- function(pkg = ".", args = NULL) {
if (yesno("Is your email address ", maintainer(pkg)$email, "?")) {
return(invisible())
}
pkg <- as.package(pkg)
built_path <- build_cran(pkg, args = args)
if (yesno("Ready to submit ", pkg$package, " (", pkg$version, ") to CRAN?")) {
return(invisible())
}
upload_cran(pkg, built_path)
usethis::with_project(pkg$path,
flag_release(pkg)
)
}
build_cran <- function(pkg, args) {
cli::cli_alert_info("Building")
built_path <- pkgbuild::build(pkg$path, tempdir(), manual = TRUE, args = args)
cli::cli_alert_info("Submitting file: {built_path}")
size <- format(as.object_size(file_info(built_path)$size), units = "auto")
cli::cli_alert_info("File size: {size}")
built_path
}
extract_cran_msg <- function(msg) {
msg <- gsub("CRAN package Submission|Submit package to CRAN", "", msg)
msg <- gsub("<[^>]+>", "", msg)
msg <- gsub("\t+", "", msg)
msg <- gsub("\n+", "\n", msg)
msg
}
upload_cran <- function(pkg, built_path) {
pkg <- as.package(pkg)
maint <- maintainer(pkg)
comments <- cran_comments(pkg)
cli::cli_alert_info("Uploading package & comments")
body <- list(
pkg_id = "",
name = maint$name,
email = maint$email,
uploaded_file = httr::upload_file(built_path, "application/x-gzip"),
comment = comments,
upload = "Upload package"
)
r <- httr::POST(cran_submission_url, body = body)
if (httr::status_code(r) == 404) {
msg <- ""
try({
r2 <- httr::GET(sub("index2", "index", cran_submission_url))
msg <- extract_cran_msg(httr::content(r2, "text"))
})
stop("Submission failed:", msg, call. = FALSE)
}
httr::stop_for_status(r)
new_url <- httr::parse_url(r$url)
cli::cli_alert_info("Confirming submission")
body <- list(
pkg_id = new_url$query$pkg_id,
name = maint$name,
email = maint$email,
policy_check = "1/",
submit = "Submit package"
)
r <- httr::POST(cran_submission_url, body = body)
httr::stop_for_status(r)
new_url <- httr::parse_url(r$url)
if (new_url$query$submit == "1") {
cli::cli_alert_success("Package submission successful")
cli::cli_alert_info("Check your email for confirmation link.")
} else {
stop("Package failed to upload.", call. = FALSE)
}
invisible(TRUE)
}
as.object_size <- function(x) structure(x, class = "object_size")
flag_release <- function(pkg = ".") {
pkg <- as.package(pkg)
if (!uses_git(pkg$path)) {
return(invisible())
}
cli::cli_alert_warning("Don't forget to tag this release once accepted by CRAN")
withr::with_dir(pkg$path, {
sha <- system2("git", c("rev-parse", "HEAD"), stdout = TRUE)
})
dat <- list(
Version = pkg$version,
Date = format(Sys.time(), tz = "UTC", usetz = TRUE),
SHA = sha
)
write.dcf(dat, file = path(pkg$path, "CRAN-SUBMISSION"))
usethis::use_build_ignore("CRAN-SUBMISSION")
}
cran_mirror <- function(repos = getOption("repos")) {
repos[repos == "@CRAN@"] <- "https://cloud.r-project.org"
if (is.null(names(repos))) {
names(repos) <- "CRAN"
}
repos[["CRAN"]]
}
cran_pkg_version <- function(package, available = available.packages()) {
idx <- available[, "Package"] == package
if (any(idx)) {
as.package_version(available[package, "Version"])
} else {
NULL
}
} |
poped.db <- create.poped.database(ff_fun=ff.PK.1.comp.oral.sd.CL,
fg_fun=function(x,a,bpop,b,bocc){
parameters=c(CL=bpop[1]*exp(b[1]),
V=bpop[2]*exp(b[2]),
KA=bpop[3]*exp(b[3]),
Favail=bpop[4],
DOSE=a[1])
return(parameters)
},
fError_fun=feps.add.prop,
bpop=c(CL=0.15, V=8, KA=1.0, Favail=1),
notfixed_bpop=c(1,1,1,0),
d=c(CL=0.07, V=0.02, KA=0.6),
sigma=c(0.01,0.25),
xt=list(c(1,2,3),c(4,5,20,120)),
groupsize=50,
minxt=0.01,
maxxt=120,
a=70,
mina=0.01,
maxa=100)
plot_model_prediction(poped.db)
evaluate_design(poped.db)$rse
optimize_n_rse(poped.db,
bpop_idx=1,
need_rse=10) |
sampleSize.rand = function(power = 0.8, p1 = 0.5, p0 = 0.5,
s1, s0, s.tau = 0,
tau, alpha = 0.05){
V = (1/p1)*s1^2 + (1/p0)*s0^2 - s.tau^2
V.tilde = (1/p1)*s1^2 + (1/p0)*s0^2
z.alpha = qnorm(1 - alpha/2)
z.gamma = qnorm(1-power)
N = ((z.alpha*sqrt(V.tilde) - z.gamma*sqrt(V) )/tau)^2
return(N)
} |
powerShape <- function(x, alpha, center = NULL, normalization = c("det", "trace", "one"), maxiter = 1e4, eps = 1e-6) {
if (any(is.na(x))) {
stop("Missing values found. Use powerShapeNA()")
}
fctCall <- match.call()
powerfct <- powerFunction(alpha)
scatterNormFct <- normalizationFunction(normalization)
try(
{
if (is.null(center)) {
res <- mestimator_mean_cov(x, powerfct, scatterNormFct, maxiter, eps)
} else {
xCentered <- sweep(x, 2, center)
zeroEntry <- rowSums(xCentered) == 0
if (any(zeroEntry)) {
xCentered <- xCentered[!zeroEntry, ]
z <- sum(zeroEntry)
if (z==1) {
message("Found ", z, " observation coinciding with given center.")
} else {
message("Found ", z, " observations coinciding with given center.")
}
}
res <- mestimator_cov(xCentered, powerfct, scatterNormFct, maxiter, eps)
res$mu <- center
}
res$alpha <- alpha
res$call <- fctCall
if (alpha == 1) {
res$scale <- NA
}
return(res)
}
)
} |
context("Test date reference functions")
test_that("dref___m() returns date reference within a month", {
expect_equal(dref_fdom("2020-02-14"), as.Date("2020-02-01"))
expect_equal(dref_fwdom("2020-02-14"), as.Date("2020-02-03"))
expect_equal(dref_ldom("2020-02-14"), as.Date("2020-02-29"))
expect_equal(dref_lwdom("2020-02-14"), as.Date("2020-02-28"))
})
test_that("dref___q() returns date reference within a quarter", {
expect_equal(dref_fdoq("2022-10-14"), as.Date("2022-10-01"))
expect_equal(dref_fwdoq("2022-10-14"), as.Date("2022-10-03"))
expect_equal(dref_ldoq("2022-10-14"), as.Date("2022-12-31"))
expect_equal(dref_lwdoq("2022-10-14"), as.Date("2022-12-30"))
})
test_that("dref___y() returns date reference within a year", {
expect_equal(dref_fdoy("2022-02-14"), as.Date("2022-01-01"))
expect_equal(dref_fwdoy("2022-02-14"), as.Date("2022-01-03"))
expect_equal(dref_ldoy("2022-02-14"), as.Date("2022-12-31"))
expect_equal(dref_lwdoy("2022-02-14"), as.Date("2022-12-30"))
})
test_that("dref_mtd() returns month-to-date", {
expect_equal(dref_mtd("2020-09-21"), as.Date("2020-08-31"))
expect_equal(dref_mtd("2020-03-08"), as.Date("2020-02-29"))
expect_equal(dref_mtd("2020-01-20"), as.Date("2019-12-31"))
})
test_that("dref_qtd() returns quarter-to-date", {
expect_equal(dref_qtd("2020-09-21"), as.Date("2020-06-30"))
expect_equal(dref_qtd("2020-06-30"), as.Date("2020-03-31"))
expect_equal(dref_qtd("2020-03-08"), as.Date("2019-12-31"))
})
test_that("dref_ytd() returns year-to-date", {
expect_equal(dref_ytd("2020-09-21"), as.Date("2019-12-31"))
expect_equal(dref_ytd("2020-06-30"), as.Date("2019-12-31"))
expect_equal(dref_ytd("2019-12-31"), as.Date("2018-12-31"))
}) |
.Random.seed <-
c(403L, 32L, -166095596L, 2013772730L, -744665595L, -501977121L,
825886310L, 2138288624L, 1528258323L, 771743921L, 276112224L,
1235218686L, 1744208009L, -720777285L, 641907082L, -533624724L,
550431215L, -136764891L, -1746995492L, 1055157426L, 488595373L,
1761313639L, -2041184114L, -1829593752L, -37667477L, 1135972105L,
-324378216L, -1030494010L, -677397983L, 1510965939L, -2120429534L,
748210708L, -1569190249L, -1802444659L, 1294816676L, 1203722122L,
1055314933L, 1652660815L, -511435434L, -1176020992L, -2059466429L,
-631782175L, -1601954224L, -968850770L, 85001817L, 1215123051L,
1793516506L, -2030553956L, 1287839391L, -886180619L, -863586932L,
-253726622L, 1924030525L, -1485874505L, -533348002L, 71526552L,
-484035589L, -762773095L, -229490136L, 904213206L, 1170945873L,
284555779L, -2003276398L, -1557464284L, 1812864487L, 2061695549L,
930616500L, -123301094L, 458831973L, -379391745L, 1346208134L,
488634128L, 1095979955L, -724725679L, 1837310976L, -325180194L,
-2129062103L, -1497945381L, 1284686314L, -128620148L, -708555057L,
-1302072699L, -960689860L, -898108398L, 823483149L, -1562605497L,
-1706399186L, 309220232L, 514784907L, -1246547863L, -718988232L,
45051110L, 223450241L, -800013293L, -804023358L, 1305726068L,
-1583136137L, 1541348205L, -2100323324L, 377788202L, 1306944661L,
1831867183L, 444547638L, -297871776L, 1204978851L, -1299148863L,
532908976L, -923701554L, 1854491705L, 752800331L, -533592070L,
-1185807620L, 918980415L, -7329771L, -1300522196L, 445444098L,
7396061L, -1543142953L, 948948158L, -462534920L, 1149433051L,
2121230137L, 1421480584L, 1495922230L, -2100844943L, -1224977245L,
-69935630L, -1895682748L, 1848741383L, 1522265053L, 1739326676L,
406608890L, 586033989L, 1852567455L, 1684792614L, 1998859696L,
1809081939L, 1138041201L, -339343200L, -1671137218L, -1330245815L,
-778455557L, 1371912650L, 1695758124L, -1679767761L, -788773403L,
-580204388L, -444498702L, 1472935277L, 1087910567L, 427629774L,
1144795688L, -1032936917L, -955135927L, -1870055080L, 1781694470L,
-137489951L, 1046338419L, -1923747870L, -824498348L, -966710697L,
-876484019L, 538660324L, 212838346L, 1596516917L, -72322929L,
-1491308138L, -705041088L, 400138243L, 324313633L, 1743168784L,
221702894L, -1979525479L, -1362700501L, 512463386L, 1301377244L,
1063382239L, 1196235445L, -1340797876L, 1420169378L, -409776131L,
-2098287369L, 1698814494L, -1720929064L, 954198075L, -887893543L,
-900544664L, -555005290L, 1284387857L, 2073781699L, 89958866L,
872128612L, -520790105L, 931737853L, -1539988236L, -423328806L,
1006073637L, -1255522753L, 1300096454L, 394199632L, -1811079565L,
-1155378543L, -1466791232L, -350753634L, 2009677929L, -1540146021L,
487028138L, 1519334860L, 481327247L, 167786693L, 703756412L,
1600599250L, -389280691L, 2060893447L, -960585490L, -2133741112L,
-1305831733L, 778315561L, -1382125704L, 2136118438L, -1029556543L,
-1132179629L, 1812868098L, -1255614156L, 713241271L, -229585235L,
-736731196L, 209545194L, -650434475L, 1933958352L, 30071612L,
1568073620L, -530141310L, -499681856L, 712475196L, -1126876784L,
1179859490L, -1838486264L, 1751693964L, -1296148708L, -1458425710L,
-1295818368L, -637484524L, -1652628696L, -1264458182L, 1663031760L,
2038584684L, -742558796L, 1386716178L, 395153888L, -1182014516L,
513093856L, 1820387362L, 1586044200L, -1787808244L, 470065980L,
330290162L, 1918254832L, 1457605188L, 74411608L, -292940998L,
-846622224L, 36748988L, -1952113388L, 1855610562L, 659038304L,
-2140887172L, 1579113424L, -355443422L, 547661480L, -1277129844L,
-958808900L, 1055582002L, -2072284608L, -258369356L, -1143567800L,
-2087551558L, 1361506832L, -1207984404L, -375657132L, -1014205166L,
1002502560L, 156393164L, 921716320L, -1322912830L, 1736262440L,
1146387372L, -907112644L, 398884210L, 2013654832L, -1314015964L,
-162931912L, 1598226138L, -1472593008L, -2064819460L, -1450781804L,
-1893658558L, -21716736L, 1248941116L, -1655306928L, -1279041374L,
-1901208248L, -412927220L, 1278444252L, -422428334L, -1230217088L,
-88961964L, 1291582440L, -1892281094L, 1061732176L, -1059123412L,
-246629004L, -587997294L, 1215757408L, 1462211980L, -2038199456L,
-289135134L, 332587944L, 1734762700L, -1751122948L, -277999182L,
584064496L, 791887812L, 1989730648L, 1359328634L, 567066544L,
1940493756L, -2077465516L, 331810754L, -1884342240L, -124860228L,
-441461168L, -1902219294L, -5932952L, -1857298356L, -710720260L,
1033869298L, 515017984L, -1266813580L, -649254904L, -803736646L,
2060641744L, 1050783724L, -1084584556L, -1823925806L, -1516928672L,
-1822332084L, -1750599392L, 137410434L, -1262745880L, 184471788L,
1825716284L, -1162711182L, 761065072L, -51356636L, -310405320L,
296551578L, -999324976L, 1164167356L, -927996268L, 1680510594L,
-1811584832L, 1645240124L, -444596080L, 1099318818L, 848645128L,
-169857780L, 633568412L, -1220640238L, -1586850944L, 498521620L,
680871464L, -1017303750L, 1460745680L, -1638375316L, -2127661772L,
127845010L, -1639733408L, 1064394572L, 1133821920L, -1121784926L,
506477480L, 464853388L, 187520188L, 1890607474L, 344826096L,
-1963139004L, 2138025304L, -429841862L, -2055835792L, 1419828284L,
-1886938348L, -1180781118L, 1523656416L, -216108164L, -965750064L,
1643914402L, -660256728L, 288397580L, 1810179004L, -354052814L,
-617410112L, 1394922036L, -1782028344L, 77829306L, 944781712L,
461251052L, 1702202964L, -372978542L, -462406880L, -1180945972L,
-1113076256L, -642851134L, 2032009256L, -731042132L, -1318473540L,
372389362L, -1517507280L, 1947686052L, 739267256L, 676137306L,
1569436048L, -1196671108L, -890849004L, -1813938366L, -1327063296L,
1120576444L, 1888619344L, -789024990L, 1090667848L, -855964148L,
-973950884L, -680372014L, -2051947008L, 340003156L, -489425432L,
180057082L, -722027312L, 1798416684L, 480564980L, 1557419410L,
1628356704L, -332020468L, 713118432L, 1068348770L, 968108712L,
2133660236L, 1028156796L, -1450659534L, -139117456L, -1668996284L,
-1007502888L, -2036495238L, 981769776L, 65680060L, 15280980L,
224856445L, -2069262486L, 1023187464L, 411934385L, -796657373L,
-1579128284L, -449412910L, -631359193L, -1847102607L, -695402058L,
-1125320364L, 692959205L, -1030700561L, 1367632168L, -1895923322L,
685149619L, 1673744661L, -1931844750L, -911716416L, -131571671L,
950615195L, 1781168492L, 361378170L, -1995750737L, 1764612537L,
1023755214L, 366115612L, -394014067L, 340908791L, -251326976L,
615000158L, 329630507L, -1714941907L, -1764607846L, -1946735528L,
-1475560511L, 1431000179L, 1960312212L, 176784418L, 905605943L,
1782011393L, 112293638L, -1636938940L, -1123844491L, -1686568993L,
2017022776L, -1772620522L, 420612387L, 1541780197L, 661347074L,
-1326108304L, 27056409L, 861575435L, -1955988996L, 249598506L,
2091287135L, 713155049L, -149951746L, -146996500L, -1784491459L,
1791357447L, 170866160L, -1418898034L, -965620805L, -754367075L,
1431251786L, -1266782360L, 1223524689L, -1004121533L, -1036789948L,
-840672270L, 646828487L, -313686127L, 1148538646L, 324311924L,
1147134469L, -910462385L, 1736945224L, 343805926L, 1921614099L,
663465589L, 351216722L, -527307104L, 1521126281L, 696276923L,
-1422682100L, -1383893606L, 208958735L, 91388761L, -517904914L,
-1030758276L, 2091721965L, 1653732247L, -898257824L, 1396952638L,
-1453447413L, 1791532429L, -2132236614L, -666483464L, -811642207L,
-1937755565L, 455101812L, -112336126L, 79496087L, -1889819295L,
35268006L, -596682844L, -332803499L, 912827135L, 374482840L,
-1712002890L, 1297726787L, 1060445317L, -597039838L, -1625936368L,
795938233L, -1064300949L, 917225820L, -902006646L, -838963073L,
-492789303L, -1015422370L, 1646967052L, 1057242333L, 881179111L,
1911300624L, -546783442L, -116423717L, -441477955L, -1039595990L,
-1690453304L, -899506191L, -56176285L, -1372389020L, -1202559854L,
-1407264409L, 737033009L, 1221443702L, 277977492L, 540868005L,
-67995985L, -234909848L, 14525254L, 18993907L, 1680657493L, 545341490L,
-1769554432L, -1859768599L, -3101349L, -2113478740L, 471393210L,
609934703L, 1221392121L, -829214834L, 1876290140L, -1837438771L,
610269239L, 1280205504L, 812373406L, 102061675L, -435859987L,
-1824924582L, -1629820136L, 907628673L, 2003576371L, 1344379988L,
-935249822L, -1864732937L, -1840815807L, 1782338438L) |
mgpr <- function(Data, m=NULL, meanModel=0, mu=NULL){
N <- length(Data$input)
X <- as.matrix(unlist(Data$input))
ns <- sapply(Data$input, length)
idx <- c(unlist(sapply(1:N, function(i) rep(i, ns[i]))))
response <- Reduce('rbind', Data$response)
Q <- 1
nrep <- ncol(response)
n <- nrow(response)
Y.original <- response
X.original <- X
idx.original <- idx
n.original <- n
if(!is.null(mu)){
if(!length(mu)==n){
stop("'mu' defined by the user must have the same length as the response
variable.")
}
mu <- matrix(rep(mu, nrep), ncol=nrep, byrow=F)
meanModel <- 'userDefined'
}
if(meanModel==0) {
mu <- 0
mu <- matrix(mu, nrow=n, ncol=nrep, byrow=F)
}
if(meanModel==1) {
responseNew <- NULL
mu <- NULL
for(j in 1:N){
mean_j <- mean(response[idx==j,])
nj <- nrow(response[idx==j,,drop=F])
mean_j <- matrix( rep(mean_j, nj*nrep), nrow=nj, byrow=F)
response_j <- response[idx==j,,drop=F] - mean_j
responseNew <- rbind(responseNew, response_j)
mu <- rbind(mu, mean_j)
}
response <- responseNew
}
if(meanModel=='t') {
meanLinearModel <- list()
responseNew <- NULL
mu <- NULL
for(j in 1:N){
trend <- data.frame(yyy=c(response[idx==j,]), xxx=rep(c(X[idx==j,]),
nrep))
meanLinearModel_j <- lm(yyy~xxx, data=trend)
meanLinearModel[[j]] <- meanLinearModel_j
response_j <- matrix(resid(meanLinearModel_j),
nrow=nrow(response[idx==j,,drop=F]), byrow=F)
mean_j <- matrix(fitted(meanLinearModel_j),
nrow=nrow(response[idx==j,,drop=F]), byrow=F)
responseNew <- rbind(responseNew, response_j)
mu <- rbind(mu, mean_j)
}
response <- responseNew
}else{
meanLinearModel <- NULL
}
if(meanModel=='avg') {
if(nrep<3){
stop('Mean function can only be the average across replications when
there are more than two replications.')
}
mu <- apply(response, 1, mean)
mu <- matrix(rep(mu, nrep), ncol=nrep, byrow=F)
response <- response - mu
}
mean.original <- mu
idxSubset <- NULL
if(!is.null(m)){
if(m>n){stop("m cannot be bigger than n.")}
idxSubset <- sort(sample(x=1:n, size=m, replace=F))
response <- response[idxSubset,,drop=F]
X <- X[idxSubset,,drop=F]
idx <- idx[idxSubset]
mu <- mu[idxSubset,,drop=F]
n <- nrow(response)
}
lowerlimits <- c(rep(-50, N), rep(log(1e-3), N+2*N*Q), log(1e-8))
upperlimits <- c(rep(50, N), rep(log(3000), N+2*N*Q), log(3))
nCand <- 100
candidates <- matrix(0, nCand, 2*N + 2*N*Q + 1)
for(iCand in 1:nCand){
nu0s <- sample(c(-1,1), size=N, replace=T)*rep(runif(1, min=-2,max=2), N)
nu1s <- log(abs(nu0s)*5)
a0s <- runif(N, min=log(1.1), max=log(30))
a1s <- runif(N, min=log(1.1), max=log(30))
sigm <- runif(1, min=log(1e-2), max=log(0.1))
candidates[iCand,] <- c(nu0s, nu1s, rep(c(a0s,a1s), Q), sigm)
}
resCand <- apply(candidates, 1, function(x) LogLikCGP(x, response, X, idx))
hp_init_log <- candidates[which.min(resCand),]
res <- nlminb(start=hp_init_log, objective=LogLikCGP, gradient=NULL,
hessian=NULL,
control=list(eval.max=1000, iter.max=1000,
rel.tol=1e-8, x.tol=1e-8, xf.tol=1e-8),
lower=lowerlimits, upper=upperlimits, response=response, X=X,
idx=idx)
hp_opt <- res$par
K <- mgpCovMat(Data=Data, hp=hp_opt)
invK <- chol2inv(chol(K))
varEpsilon <- exp(hp_opt[length(hp_opt)])^2
fitted <- (K-diag(varEpsilon, n.original))%*%invK%*%Y.original + mean.original
fitted.var <- varEpsilon*rowSums((K-diag(varEpsilon, n.original))*t(invK))
result <- list('hyper'=hp_opt,
'fitted.mean'=fitted,
'fitted.sd'=sqrt(fitted.var),
'N'=N,
'X'=X.original, 'Y'=Y.original, 'idx'=idx.original, 'Cov'=K,
'mu'=mean.original[,1],
'meanModel'=meanModel, 'meanLinearModel'=meanLinearModel)
class(result)='mgpr'
return(result)
}
mgprPredict <- function(train,
DataObs=NULL,
DataNew,
noiseFreePred=F,
meanModel=NULL, mu=0){
if(class(train)!='mgpr'){
stop("Argument 'train' must be an object of class 'mgpr'.")
}else{
hyper <- train$hyper
X <- train$X
Y <- train$Y
N <- train$N
idx <- train$idx
Cov <- train$Cov
mu <- train$mu
meanModel <- train$meanModel
meanLinearModel <- train$meanLinearModel
}
if(!is.null(DataObs)){
N <- length(DataObs$input)
X <- as.matrix(unlist(DataObs$input))
if(!is.matrix(DataObs$response[[1]])){
DataObs$response <- lapply(DataObs$response, as.matrix)
}
}
X.new <- as.matrix(unlist(DataNew$input))
ns.new <- sapply(DataNew$input, length)
idx.new <- c(unlist(sapply(1:N, function(i) rep(i, ns.new[i]))))
ns <- sapply(DataObs$input, length)
nsTest <- sapply(DataNew$input, length)
idx <- c(unlist(sapply(1:N, function(i) rep(i, ns[i]))))
Y <- Reduce('rbind', DataObs$response)
nrep <- ncol(Y)
if(meanModel==0){
meanList <- list()
for(j in 1:N){
meanList[[j]] <- rep(0, ns[j])
}
meanY <- do.call(cbind, replicate(nrep, unlist(meanList), simplify=FALSE))
}
if(meanModel=='t'){
meanList <- list()
for(j in 1:N){
newtrend <- data.frame(xxx=DataObs$input[[j]])
meanList[[j]] <- predict(meanLinearModel[[j]], newdata=newtrend)
}
meanY <- do.call(cbind, replicate(nrep, unlist(meanList), simplify=FALSE))
}
Y <- Y - meanY
hp <- TransfToNatScaleCGP(hyper, N)
Q <- 1
va0s <- hp[1:N]
va1s <- hp[(N+1):(2*N)]
AparsMat <- matrix(hp[seq(2*N+1, by=1, length.out=2*N*Q)], ncol=2*Q, byrow=T)
A0s <- A1s <- list()
if(Q==1){
for(j in 1:N){
A0s[[j]] <- as.matrix(AparsMat[j,1:Q])
A1s[[j]] <- as.matrix(AparsMat[j,(Q+1):(2*Q)])
}
}else{
for(j in 1:N){
A0s[[j]] <- diag(AparsMat[j,1:Q])
A1s[[j]] <- diag(AparsMat[j,(Q+1):(2*Q)])
}
}
sig <- hp[length(hp)]
Psi <- KCGP(X=X, idx=idx, va0s=va0s, va1s=va1s, A0s=A0s, A1s=A1s, sig=sig)
Knm <- KCGPnm(X=X, Xp = X.new, idx=idx, idx_new = idx.new, va0s=va0s,
va1s=va1s, A0s=A0s, A1s=A1s, sig=0)
Kstar <- KCGP(X=X.new, idx=idx.new, va0s=va0s, va1s=va1s, A0s=A0s, A1s=A1s,
sig=sig)
invPsi <- chol2inv(chol(Psi))
QR <- invPsi%*%Y
if(meanModel==0){
meanList <- list()
for(j in 1:N){
meanList[[j]] <- rep(0, nsTest[j])
}
mu <- do.call(cbind, replicate(nrep, unlist(meanList), simplify=FALSE))
}
if(meanModel=='t'){
meanList <- list()
for(j in 1:N){
newtrend <- data.frame(xxx=DataNew$input[[j]])
meanList[[j]] <- predict(meanLinearModel[[j]], newdata=newtrend)
}
mu <- do.call(cbind, replicate(nrep, unlist(meanList), simplify=FALSE))
}
pred.mu. <- t(Knm)%*%QR + mu
if(noiseFreePred){
sigma2 <- diag(Kstar)-diag(t(Knm)%*%invPsi%*%Knm) - sig^2
}else{
sigma2 <- diag(Kstar)-diag(t(Knm)%*%invPsi%*%Knm)
}
pred.sd. <- sqrt(sigma2)
pred.mean <- list()
pred.sd <- list()
for(j in 1:N){
pred.mean[[j]] <- pred.mu.[idx.new==j,,drop=F]
pred.sd[[j]] <- pred.sd.[idx.new==j]
}
result=c(list('pred.mean'=pred.mean,
'pred.sd'=pred.sd,
'noiseFreePred'=noiseFreePred))
class(result)='mgpr'
return(result)
}
mgpCovMat <- function(Data, hp){
N <- length(Data$input)
X <- as.matrix(unlist(Data$input))
ns <- sapply(Data$input, length)
idx <- c(unlist(sapply(1:N, function(i) rep(i, ns[i]))))
hp <- TransfToNatScaleCGP(hp, N)
Q <- 1
va0s <- hp[1:N]
va1s <- hp[(N+1):(2*N)]
AparsMat <- matrix(hp[seq(2*N+1, by=1, length.out=2*N*Q)], ncol=2*Q, byrow=T)
A0s <- A1s <- list()
if(Q==1){
for(j in 1:N){
A0s[[j]] <- as.matrix(AparsMat[j,1:Q])
A1s[[j]] <- as.matrix(AparsMat[j,(Q+1):(2*Q)])
}
}else{
for(j in 1:N){
A0s[[j]] <- diag(AparsMat[j,1:Q])
A1s[[j]] <- diag(AparsMat[j,(Q+1):(2*Q)])
}
}
sig <- hp[length(hp)]
K <- KCGP(X=X, idx=idx, va0s=va0s, va1s=va1s, A0s=A0s, A1s=A1s, sig=sig)
return(K)
}
TransfToNatScaleCGP <- function(hp, N){
hp[(N+1):length(hp)] <- exp(hp[(N+1):length(hp)])
return(hp)
}
LogLikCGP <- function(hp, response, X, idx){
Q <- 1
N <- length(unique(idx))
hp <- TransfToNatScaleCGP(hp, N)
va0s <- hp[1:N]
va1s <- hp[(N+1):(2*N)]
AparsMat <- matrix(hp[seq(2*N+1, by=1, length.out=2*N*Q)], ncol=2*Q, byrow=T)
A0s <- A1s <- list()
if(Q==1){
for(j in 1:N){
A0s[[j]] <- as.matrix(AparsMat[j,1:Q])
A1s[[j]] <- as.matrix(AparsMat[j,(Q+1):(2*Q)])
}
}else{
for(j in 1:N){
A0s[[j]] <- diag(AparsMat[j,1:Q])
A1s[[j]] <- diag(AparsMat[j,(Q+1):(2*Q)])
}
}
sig <- hp[length(hp)]
K <- KCGP(X=X, idx=idx, va0s=va0s, va1s=va1s, A0s=A0s, A1s=A1s, sig=sig)
G <- chol(K)
logdetK <- 2*sum(log(diag(G)))
yt.invK.y <- t(response)%*%chol2inv(G)%*%response
n <- nrow(response)
nrep <- ncol(response)
if(nrep==1){
fX <- 0.5*logdetK + 0.5*yt.invK.y + 0.5*n*log(2*pi)
}else{
fX <- nrep*0.5*logdetK + 0.5*sum(diag( yt.invK.y )) + nrep*0.5*n*log(2*pi)
}
fX <- as.numeric(fX)
return(fX)
}
plot.mgpr <- function(x, DataObs, DataNew, realisation, alpha=0.05,
ylim=NULL, mfrow=NULL,
cex=2,
mar=c(4.5,7.1,0.2,0.8), oma=c(0,0,0,0),
cex.lab=2, cex.axis=1.5, ...){
old <- par(mar=mar, oma=oma, cex.lab=cex.lab, cex.axis=cex.axis)
z <- stats::qnorm(1-alpha/2)
if(!is.matrix(DataObs$response[[1]])){
DataObs$response <- lapply(DataObs$response, as.matrix)
}
predCGP <- mgprPredict(train=x,
DataObs=DataObs,
DataNew=DataNew)
N <- length(predCGP$pred.mean)
if(is.null(mfrow)){
if(N<4){
par(mfrow=c(1,N))
}
}else{
par(mfrow=mfrow)
}
for(variable in 1:N){
predMean <- predCGP$pred.mean[[variable]][,realisation]
upper <- predMean+z*predCGP$pred.sd[[variable]]
lower <- predMean-z*predCGP$pred.sd[[variable]]
if(is.null(ylim)){
ylim_i <- range(c(lower, upper))
}else{
ylim_i <- ylim[[variable]]
}
xlim_i <- range(DataObs$input[[variable]], DataNew$input[[variable]])
plot(DataObs$input[[variable]], DataObs$response[[variable]][,realisation],
type="p", xlab="t", ylab=bquote(x[.(variable)]), ylim=ylim_i,
xlim=xlim_i, pch=19, cex=cex, cex.axis=cex.axis, cex.lab=cex.lab, ...)
lines(DataNew$input[[variable]], predMean, col="blue", lwd=2)
polygon(x=c(DataNew$input[[variable]], rev(DataNew$input[[variable]])),
y=c(upper, rev(lower)),
col=rgb(127,127,127,120, maxColorValue=255), border=NA)
}
par(mfrow=c(1,1))
par(old)
}
plotmgpCovFun <- function(type="Cov", output, outputp, Data, hp, idx, ylim=NULL,
xlim=NULL, mar=c(4.5,5.1,2.2,0.8), oma=c(0,0,0,0),
cex.lab=1.5, cex.axis=1, cex.main=1.5){
old <- par(mar=mar, oma=oma, cex.lab=cex.lab, cex.axis=cex.axis, cex.main=cex.main)
Psi <- mgpCovMat(Data=Data, hp=hp)
if(type=="Cor"){
Psi <- cov2cor(Psi)
}
toPlot <- Psi[idx==output, idx==outputp][,1]
tp0 <- Data$input[[outputp]][1]
if(!is.null(ylim)){
ylim <- range(toPlot)
}
plot(Data$input[[output]] - tp0, toPlot, ylim=ylim, xlim=xlim, type="l",
xlab=bquote("t-("*.(tp0)*")"),
ylab=bquote(.(type)*"["*X[.(output)]*"(t),"~
X[.(outputp)]*"("*.(tp0)*")]"))
par(old)
} |
rm(list=ls())
graphics.off()
options(show.error.locations = TRUE)
if("ubiquity" %in% rownames(installed.packages())){require(ubiquity)} else
{source(file.path("library", "r_general", "ubiquity.R")) }
cfg = build_system(system_file="system-mab_pk.txt",
output_directory = file.path(".", "output"),
temporary_directory = file.path(".", "transient"))
cfg = system_load_data(cfg, dsname = "PKDATA",
data_file = "pk_all_md.csv")
my_NCA_opts = list(max.aucinf.pext = 10,
min.hl.r.squared = .9)
cfg = system_nca_run(cfg, dsname = "PKDATA",
dscale = 1e6,
dsfilter = list(ID = c(1:5, 25:30, 45:50)),
NCA_options = my_NCA_opts,
analysis_name = "pk_multiple_dose",
dsmap = list(TIME = "TIME_HR",
NTIME = "NTIME_HR",
CONC = "C_ng_ml",
DOSE = "DOSE",
ROUTE = "ROUTE",
ID = "ID",
DOSENUM = "DOSENUM",
EXTRAP = "EXTRAP"),
dsinc = c("ROUTE"))
NCA_results = system_fetch_nca(cfg, analysis_name = "pk_multiple_dose")
library(tidyr)
NCA_sum = NCA_results[["NCA_summary"]]
NCA_cols = system_fetch_nca_columns(cfg, analysis_name = "pk_multiple_dose")
NCA_results = system_fetch_nca(cfg, analysis_name = "pk_multiple_dose")
cfg = system_rpt_read_template(cfg, template="Word")
NCA_sum = NCA_sum %>%
dplyr::filter(Dose == 30) %>%
dplyr::mutate(cmax_dose= cmax/Dose) %>%
tidyr::pivot_wider(
id_cols = c("ID", "Dose_Number"),
names_from = Dose_Number,
values_from = c(auclast, cmax, cmax_dose, half.life)) %>%
dplyr::mutate(AR_6_1 = auclast_6/auclast_1)
NCA_summary = system_nca_summary(cfg,
analysis_name = "pk_multiple_dose",
params_include = c( "ID", "Dose_Number", "cmax", "tmax", "half.life", "auclast", "ROUTE"),
params_header = list(cmax = c( "<label>", "(ng/ml)"), ROUTE=c("route")),
label_format = "md",
ds_wrangle = "NCA_sum = NCA_sum %>% dplyr::filter(Dose == 30)",
summary_stats = list("<MEAN> (<STD>)" = c("auclast", "half.life"),
"<MEDIAN>" = c("tmax")),
summary_labels = list(MEAN = "Mean (<ff:symbol>m</ff>)",
STD = "Std Dev (<ff:symbol>s</ff>)",
N = "N~obs~",
MEDIAN = "Median",
SE = "Std Err."),
summary_location = "ID")
ds_wrangle_str = 'NCA_sum = NCA_sum %>%
dplyr::filter(Dose == 30) %>%
dplyr::mutate(cmax_dose= cmax/Dose) %>%
tidyr::pivot_wider(
id_cols = c("ID", "Dose_Number"),
names_from = Dose_Number,
values_from = c(auclast, cmax, cmax_dose, half.life)) %>%
dplyr::mutate(AR_6_1 = auclast_6/auclast_1)'
NCA_summary_wide = system_nca_summary(cfg,
analysis_name = "pk_multiple_dose",
params_include = c("ID", "auclast_1", "cmax_1", "cmax_dose_1", "half.life_1",
"auclast_6", "cmax_6", "cmax_dose_6", "half.life_6", "AR_6_1"),
params_header = list("ID" = c("ID", "ID"),
"auclast_1" = c("Day 1", "AUC last", "hr-ng/ml" ),
"cmax_1" = c("", "Cmax", "ng/ml" ),
"cmax_dose_1" = c("", "Cmax/Dose", "ng/ml/(mg/kg)" ),
"half.life_1" = c("", "Halflife", "hr" ),
"auclast_6" = c("Day 6", "AUC last", "hr-ng/ml" ),
"cmax_6" = c("", "Cmax", "ng/ml" ),
"cmax_dose_6" = c("", "Cmax/Dose", "ng/ml/(mg/kg)" ),
"half.life_6" = c("", "Halflife", "hr" ),
"AR_6_1" = c("Day 1/Day 6", "AR")),
ds_wrangle = ds_wrangle_str,
summary_stats = list("<MEAN>" = c("auclast_1", "auclast_6"),
"(<STD>)" = c("auclast_1", "auclast_6")),
summary_labels = list(MEAN = "Mean",
STD = "Std Dev",
N = "N obs",
MEDIAN = "Median",
SE = "Std Err."),
summary_location = "ID")
cfg = system_rpt_read_template(cfg, template="PowerPoint")
cfg = system_rpt_add_slide(cfg,
template = "content_text",
elements = list(
title =
list(content = "NCA of Multiple Dose PK",
type = "text"),
content_body =
list(content = NCA_summary[["nca_summary_ft"]],
type = "flextable_object")))
cfg = system_rpt_nca(cfg=cfg, analysis_name="pk_multiple_dose")
system_rpt_save_report(cfg=cfg, output_file=file.path("output","pk_multiple_dose-report.pptx"))
cfg = system_rpt_read_template(cfg, template="Word")
cfg = system_rpt_add_doc_content(cfg=cfg,
type = "flextable_object",
content = list(caption = "Summary table of NCA outputs",
ft = NCA_summary[["nca_summary_ft"]]))
cfg = system_rpt_add_doc_content(cfg=cfg,
type = "flextable_object",
content = list(caption = "Transformed NCA output",
ft = NCA_summary_wide[["nca_summary_ft"]]))
cfg = system_rpt_nca(cfg=cfg, analysis_name="pk_multiple_dose")
system_rpt_save_report(cfg=cfg, output_file=file.path("output","pk_multiple_dose-report.docx")) |
context("simplify_conditional")
test_that("non-relaxing clause works", {
rules <- validator( r1 = if (x > 1) y > 3
, r2 = y < 2
)
rules_s <- simplify_conditional(rules)
exprs <- to_exprs(rules)
exprs_s <- to_exprs(rules_s)
expect_equal(exprs_s$r1, quote(x <= 1))
expect_equal(exprs_s$r2, quote(y < 2))
})
test_that("non-relaxing clause works (pure categorical)", {
rules <- validator( r1 = B %in% c("b1", "b2")
, r2 = if (A == "a") B == "b1"
, r3 = B == "b2"
)
rules_s <- simplify_conditional(rules)
exprs_s <- to_exprs(rules_s)
expect_equal(exprs_s$r2, quote(A != "a"))
})
test_that("non-constraining clause works", {
rules <- validator( r1 = if (x > 0) y > 0
, r2 = if (x < 1) y > 1
)
rules_s <- simplify_conditional(rules)
exprs <- to_exprs(rules)
exprs_s <- to_exprs(rules_s)
expect_equal(length(rules_s), 2)
expect_equal(exprs_s[[1]], quote(y > 0))
expect_equal(exprs_s[[2]], quote(if (x < 1) y > 1))
})
test_that("non-constraining clause works (pure categorical)", {
rules <- validator( dB = B %in% c("b1", "b2")
, dA = A %in% c("a1", "a2", "a3")
, r1 = if (B == "b1") A %in% c("a1", "a2")
, r2 = if (B == "b2") A %in% c("a2")
)
rules_s <- simplify_conditional(rules)
exprs <- to_exprs(rules_s)
exprs_s <- to_exprs(rules_s)
expect_equal(length(rules_s), 4)
expect_equal(exprs_s$r1, quote(A %in% c("a1", "a2")))
expect_equal(exprs_s$r2, exprs$r2)
expect_equal(exprs_s$dA, exprs$dA)
expect_equal(exprs_s$dB, exprs$dB)
})
test_that("equality constraints work", {
rules <- validator( if (z == 0) y == 0
, z == 0
)
rules_s <- simplify_conditional(rules)
exprs <- to_exprs(rules)
exprs_s <- to_exprs(rules_s)
expect_equal(exprs_s[[1]], quote(y == 0))
expect_equal(exprs_s[[2]], quote(z == 0))
})
test_that("equality constraints work (pure categorical)", {
rules <- validator( dA = A %in% c("a1", "a2")
, dB = B %in% c('b1', 'b2')
, r1 = if (A == "a1") B == "b1"
, r2 = A == "a1"
)
rules_s <- simplify_conditional(rules)
exprs <- to_exprs(rules)
exprs_s <- to_exprs(rules_s)
expect_equal(exprs_s$r1, quote(B == "b1"))
expect_equal(exprs_s$r2, exprs$r2)
expect_equal(exprs_s$dA, exprs$dA)
expect_equal(exprs_s$dB, exprs$dB)
})
test_that("a more complex if statement also works", {
rules <- validator( r1 = if (income > 0 & tvstar != TRUE) age >= 16
, r2 = age < 12
)
rules_s <- simplify_conditional(rules)
exprs <- to_exprs(rules)
exprs_s <- to_exprs(rules_s)
expect_equal(exprs_s$r1, quote(if (income > 0) tvstar == TRUE))
expect_equal(exprs_s$r2, exprs$r2)
rules <- validator( r1 = if (income > 0) age >= 16 | tvstar == TRUE
, r2 = age < 12
)
rules_s <- simplify_conditional(rules)
exprs <- to_exprs(rules)
exprs_s <- to_exprs(rules_s)
expect_equal(exprs_s$r1, quote(if (income > 0) tvstar == TRUE))
expect_equal(exprs_s$r2, exprs$r2)
}) |
prettyScree <- function(eigs,retain.col="mediumorchid4",dismiss.col="gray",perc.exp=1.0,n.comps=NULL,broken.stick=TRUE,kaiser=TRUE,main=""){
add.alpha <- function(col, alpha=1){
apply(sapply(col, col2rgb)/255, 2,
function(x)
rgb(x[1], x[2], x[3], alpha=alpha))
}
eig.length <- length(eigs)
mean.eig <- mean(eigs)
eigs.round <- round(eigs,digits=3)
exp.var <- eigs/sum(eigs)*100
exp.var.round <- round(exp.var,digits=2)
if(is.null(n.comps)){
n.comps <- eig.length
}
if(n.comps > eig.length || n.comps < 1){
n.comps <- eig.length
}
perc.exp.comps <- cumsum(exp.var) < (perc.exp * 100)
perc.exp.comps[head(which(!(perc.exp.comps)),n=1)] <- TRUE
keep.n.comps <- rep(FALSE,eig.length)
keep.n.comps[1:n.comps] <- rep(TRUE,length(1:n.comps))
comps.tests <- rbind(perc.exp.comps,keep.n.comps)
if(broken.stick){
broken.stick.distribution <- unlist(lapply(X=1:eig.length,FUN=function(x,n){return(tail((cumsum(1/x:n))/n,n=1))},n=eig.length)) * 100
broken.stick.comps <- exp.var > broken.stick.distribution
broken.stick.comps[head(which(!broken.stick.comps),n=1):eig.length] <- rep(FALSE,length(head(which(!broken.stick.comps),n=1):eig.length))
comps.tests <- rbind(comps.tests,broken.stick.comps)
}
if(kaiser){
kaiser.mean.comps <- eigs > mean.eig
comps.tests <- rbind(comps.tests,kaiser.mean.comps)
}
comp.sums <- colSums(comps.tests)
alpha.map <- 1/abs((comp.sums-(nrow(comps.tests)+1)))
color.map <- rep(retain.col,eig.length)
for(i in 1:eig.length){color.map[i] <- add.alpha(color.map[i],alpha.map[i])}
color.map[which(comp.sums==0)] <- rep(dismiss.col,sum(comp.sums==0))
dev.new()
par(mar=c(5, 5, 4, 5) + 0.1)
these.sizes <- ((log(exp.var) + abs(min(log(exp.var))))/max(log(exp.var) + abs(min(log(exp.var))))+0.1) * 3
plot(exp.var,axes=FALSE,ylab="",xlab="Components",type="l",main=main,ylim=c(-1,max(exp.var)))
points(exp.var,cex= these.sizes,pch=20,col=dismiss.col)
points(exp.var,cex= these.sizes,pch=21,bg=color.map)
box()
axis(2,at= exp.var,labels=eigs.round,las=2,lwd=3,cex.axis=.65)
mtext("Eigenvalues",2,line=4)
axis(4,at= exp.var,labels=paste(exp.var.round,"%",sep=""),las=2,lwd=3,cex.axis=.65)
mtext("Explained Variance",4,line=4)
axis(1,at=1:length(exp.var),lwd=3)
return(comps.tests)
} |
library(ggplot2)
library(ShinyItemAnalysis)
data(GMAT, package = "difNLR")
data <- GMAT[, 1:20]
score <- rowSums(data)
criterion <- GMAT[, "criterion"]
hist(criterion)
criterionD <- round(criterion)
hist(criterionD)
size <- as.factor(criterionD)
levels(size) <- table(as.factor(criterionD))
size <- as.numeric(paste(sizeD))
df <- data.frame(score, criterionD, size)
ggplot(df, aes(y = score, x = as.factor(criterionD), fill = as.factor(criterionD))) +
geom_boxplot() +
geom_jitter(shape = 16, position = position_jitter(0.2)) +
scale_fill_brewer(palette = "Blues") +
xlab("Criterion group") +
ylab("Total score") +
coord_flip() +
theme_app()
ggplot(df, aes(x = score, y = criterion)) +
geom_point() +
ylab("Criterion variable") +
xlab("Total score") +
geom_smooth(
method = lm,
se = FALSE,
color = "red"
) +
theme_app()
cor.test(criterion, score, method = "pearson", exact = FALSE) |
mmiGEE<-function(object,data, trace = FALSE){
if(!inherits(object, "GEE")) stop("Input model is not of class 'GEE'")
family<-object$family
formula<-object$formula
coord<-object$coord
scale.fix<-object$scale.fix
corstr<-object$corstr
cluster<-object$cluster
moran.params<-object$moran.params
if(!scale.fix){
scale.fix<-TRUE
message("Scale parameter is now fixed")
}
X<-stats::model.matrix(formula,data)
if(dimnames(X)[[2]][1]!="(Intercept)") {
formula <- stats::update(formula, ~ . + 1)
X<-stats::model.matrix(formula,data)
}
nvar<-dim(X)[2]
varnames<-dimnames(X)[[2]][-1]
p<-dim(X)[2]-1
pset <- rje::powerSetMat(p)
ip <- dim(pset)[1]
t <- stats::terms(formula)
coef.vec<-matrix(NA,ip,nvar)
df<-rep(NA,ip)
Qlik<-rep(NA,ip)
QIC<-rep(NA,ip)
for (i in 1:ip) {
if(sum(pset[i,])!=0 & sum(pset[i,])!=p){
t1 <- stats::drop.terms(t,which(pset[i,]==0), keep.response = TRUE)
formula1<- stats::reformulate(attr(t1, "term.labels"), formula[[2]])
formulae<-formula1
}
if(sum(pset[i,])==p) formulae<-formula
if(sum(pset[i,])==0) formulae<-stats::as.formula(paste(formula[[2]],"~1"))
m0<-suppressWarnings({
GEE(formulae,family,data,coord,corstr=corstr,
cluster=cluster,moran.params=moran.params,
scale.fix=scale.fix)
})
kv<-c(1,which(pset[i,]==1)+1)
coef.vec[i,kv]<-m0$b
Xe<-stats::model.matrix(formulae,data)
nvare<-dim(Xe)[2]
K<-nvare
if(family=="gaussian") K<-K+1
df[i]<-K
Qlik[i]<-m0$QLik
QIC[i]<-m0$QIC
}
result<-cbind(round(coef.vec,5),df,round(Qlik,3),round(QIC,1))
delta<-QIC-min(QIC)
weight<-exp(-delta/2)/sum(exp(-delta/2))
result<-cbind(result,round(delta,2),round(weight,3))
ord<-order(delta)
res<-result[ord,]
dimnames(res)[[1]]<-ord
dimnames(res)[[2]]<-c("(Int)",varnames,
"df","QLik","QIC","delta","weight")
if(trace) {
cat("\n","Model selection table:","\n","\n")
print(res,na.print = "")
}
nrowA<-dim(res)[1]
ncolA<-dim(res)[2]
nvar<-dim(res)[2]-6
leg<-dimnames(res)[[2]][2:(nvar+1)]
A<-matrix(NA,nrowA,ncolA)
A<-res
ip<-dim(A)[1]
WeightSums<-rep(NA,nvar)
for(kvar in 2:(nvar+1)){
for (i in 1: ip){
if(!is.na(A[i,kvar])) A[i,kvar]<-A[i,(nvar+6)]
}
}
B<-A[1:ip,2:(nvar+1)]
WeightSums<-colSums(B,na.rm=TRUE)
names(WeightSums)<-leg
if(trace){
cat("\n","---","\n","Relative variable importance:","\n","\n")
print(WeightSums)
}
fit<-list(result=res,rvi=WeightSums)
fit
} |
fit_MRMC_versionTWO<- function(
dataList,
DrawFROCcurve = TRUE,
DrawCFPCTP=TRUE,
version = 2,
mesh.for.drawing.curve=10000,
significantLevel = 0.7,
cha = 1,
war = floor(ite/5),
ite = 10000,
dig = 5,
see = 1234569)
{
viewdata(dataList )
if(version == 2 ){
scr <- system.file("extdata", "Model_Hiera_versionTWO.stan", package="BayesianFROC")
}else{
if(version == 3 ){
scr <- system.file("extdata", "Model_Hiera_versionTHREE.stan", package="BayesianFROC")
} else{
print("version is allowed only two choice; 2 or 3")
}}
data <-metadata_to_fit_MRMC(dataList)
m<-data$m ;S<-data$S; NL<-data$NL;c<-data$c;q<-data$q;
h<-data$h; f<-data$f;
hh<-data$hh; hhN<-data$hhN;
ff<-data$ff;ffN<-data$ffN;
harray<-data$harray; farray<-data$farray;
hharray<-data$hharray; ffarray<-data$ffarray;
hharrayN<-data$hharrayN; ffarrayN<-data$ffarrayN;
C<-as.integer(data$C)
M<-as.integer(data$M)
N<-as.integer(data$N)
Q<-as.integer(data$Q)
ll<- stats::rchisq(mesh.for.drawing.curve, 1)
lll<- 0.99+stats::rchisq(mesh.for.drawing.curve, 1)
l<-append(ll,lll)
x<-list(x=l,mesh=mesh.for.drawing.curve)
ext.data <- c( data,x )
rstan_options(auto_write = TRUE)
fit <- stan(file=scr, model_name=scr, data=ext.data, verbose = TRUE,
seed=see, chains=cha, warmup=war,
iter=ite, control = list(adapt_delta = 0.9999999,
max_treedepth = 15)
)
convergence <- ConfirmConvergence(fit)
if(convergence ==FALSE){message("\n* So, model has no mean, we have to finish a calculation !!\n")
return(fit)}
if(convergence ==TRUE){message("\n* We continue the procedure, since model cannot be said not converged.\n")}
message("---------- Useage of the return value------------------------- \n")
message("\n * Using this return value which is S4 class generated by rstan::stan and another function in this package, you can draw FROC and AFROC curves. \n")
message("\n * Using this return value, you can apply functions in the package rstan, e.g., rstan::traceplot(). \n")
message("\n----------------------------------------- \n")
message(" \n* Now, curve are drawing ... \n")
if( DrawFROCcurve == TRUE|| DrawCFPCTP==TRUE){grDevices::dev.new()}
if( !( DrawFROCcurve == TRUE|| DrawCFPCTP==TRUE) ){message("\n* We do not draw anything according to your input.\n")}
MCMC=(ite-war)*cha
x<- 1-exp(-l)
EAP_a <- rstan::get_posterior_mean(fit,par=c("a"))
EAP_a <- apply(EAP_a, 1, mean)
EAP_b <- rstan::get_posterior_mean(fit,par=c("b"))
EAP_b <- apply(EAP_b, 1, mean)
y<- array(0, dim=c(length(l), M))
for(md in 1:M){
y[ ,md]<-1-stats::pnorm(EAP_b[md] *stats::qnorm(exp(-l ))-EAP_a[md] )
}
graphics::par(bg= "gray12",
fg="gray",
col.lab="bisque2" ,
col.axis="bisque2" ,
col.main="bisque2" ,
cex.lab=1.5,
cex.axis=1.3
);
Colour1 <- array(0, dim=c( 20))
Colour2 <- array(0, dim=c( M))
Colour1[1]<-"antiquewhite1"
Colour1[2]<-"brown1"
Colour1[3]<-"dodgerblue1"
Colour1[4]<-"orange2"
Colour1[5]<-"yellowgreen"
Colour1[6]<-"khaki1"
Colour1[7]<-"darkorange4"
Colour1[8]<-"slateblue4"
for (cc in 9:20) {
Colour1[cc] <- as.character(cc);
};
upper_x <-max(ffarrayN)
upper_y <- max(hharrayN)
lower_y <- min(hharrayN)
if(DrawFROCcurve==TRUE){
message("* Process of drawing FROC curve \n")
for(md in 1:M){
cat("|")
graphics::par(new = TRUE); plot(
l,y[,md],
col =Colour1[md],
bg="gray",
fg="gray",
xlab = 'mean of false positives per nodule',
ylab = 'cumulative hit per nodule',
cex= 0.1,
xlim = c(0,upper_x ),
ylim = c(lower_y,upper_y)
);
message(paste("", ceiling(round(md/M,2)*100/2 +50),"% \n"))
}
}
if(DrawCFPCTP==TRUE){
for(md in 1:M){for(qd in 1:Q){
if( !M ==1){
graphics::par(new=T);plot(
ffarrayN[,md,qd],hharrayN[,md,qd],
xlim = c(0,upper_x ),
ylim = c(lower_y,upper_y),
bg="gray",
fg="gray",
col =Colour1[md],
pch =paste(md),
cex=1,
xlab = '', ylab = ''
,main = 'Each number of Scatter plots denotes modality ID'
)
}
if( M ==1){
graphics::par(new=T);plot(
ffarrayN[,md,qd],hharrayN[,md,qd],
xlim = c(0,upper_x ),
ylim = c(lower_y,upper_y),
bg="gray",
fg="gray",
col =Colour1[qd],
pch =paste(qd),
cex=1,
xlab = '', ylab = ''
,main = 'Each number of Scatter plots denotes reader ID'
)
}
}
}
}
a<-rstan::extract(fit)$a
b<-rstan::extract(fit)$b
yyy.pre <- array(0, dim=c(length(l),MCMC, M))
var.yy <- array(0, dim=c(length(l), M))
message("\n* Process for calculation of y coordinates of FROC curve\n")
cat("/")
sss <-0
Divisor <-100
if(length(l)<100){ Divisor <- 1 }
for (ld in 1:length(l)) {
if(ld %% round(length(l)/Divisor)==0){
sss <- sss +1
if(sss%%10==0){ message("/ [", sss,"% ] \n")}
if(!sss==100){cat("/")}
}
yyy.pre[ld,,]<- 1 - stats::pnorm( b *stats::qnorm(exp(-l[ld])) -a )
}
yyy <- aperm( yyy.pre, c(2,1,3))
var.yy <- apply(yyy, c(2,3), stats::var)
y.lower <- y - var.yy
y.hight <- y + var.yy
for (md in 1:M) {
graphics::par(new = TRUE);plot(l,y.lower[,md], cex= 0.05 ,
col = grDevices::gray(0.4),
xlim = c(0,upper_x ),
ylim = c(lower_y,upper_y),
xlab = '', ylab = ''
)
graphics::par(new = TRUE);plot(l,y.hight[,md], cex= 0.05 ,
col = grDevices::gray(0.4),
xlim = c(0,upper_x ),
ylim = c(lower_y,upper_y),
xlab = '', ylab = ''
)
}
fit.new.class <- methods::as(fit,"stanfitExtended")
fit.new.class@metadata <-data
fit.new.class@dataList <-dataList
fit.new.class@studyDesign <- "MRMC"
fit.new.class@ModifiedPoisson <- TRUE
if(M==1){message("\n* The modality comparison procedure is omitted, since your data has only one modality.\n")}
if(!M==1){
summarize_MRMC(fit.new.class)
}
rstan::check_hmc_diagnostics( fit )
invisible(fit.new.class)
}
Credible_Interval_for_curve <-function(dataList,
StanS4class.fit_MRMC_versionTWO,
mesh.for.drawing.curve=10000,
upper_x=upper_x,
upper_y=upper_y,
lower_y=lower_y
){
message("\n Please wait... for credible curves... \n")
fit <- StanS4class.fit_MRMC_versionTWO
if(missing(upper_x)||missing(lower_y)||missing(upper_y)){
data <- metadata_to_fit_MRMC(dataList)
hharrayN<-data$hharrayN; ffarrayN<-data$ffarrayN;
upper_x <-max(ffarrayN)
upper_y <- max(hharrayN)
lower_y <- min(hharrayN)
}
M <-dataList$M
Q <-dataList$Q
ll <- stats::rchisq(mesh.for.drawing.curve, 1)
lll<- 0.99+stats::rchisq(mesh.for.drawing.curve, 1)
l<-append(ll,lll)
war <- fit@sim$warmup
cha <- fit@sim$chains
ite <- fit@sim$iter
MCMC=(ite-war)*cha
a<-rstan::extract(fit)$a
b<-rstan::extract(fit)$b
yyy <- array(0, dim=c(MCMC,length(l), M))
var.yy <- array(0, dim=c(length(l), M))
for (md in 1:M) {
for (ld in 1:length(l)) {
yyy[,ld,md]<- 1 - stats::pnorm( b[,md] *stats::qnorm(exp(-l[ld])) -a[,md] )
var.yy[ld,md] <-stats::var(yyy[,ld,md])
}
}
y <- array(0, dim=c(length(l), M))
y.lower <- array(0, dim=c(length(l), M))
y.hight <- array(0, dim=c(length(l), M))
EAP_a <- array(0, dim=c( M))
EAP_b <- array(0, dim=c( M))
for(md in 1:M){
EAP_a[md] <- 0
EAP_b[md] <- 0
s<-0
t<-0
for(mc in 1:MCMC){
s<- EAP_a[md]
EAP_a[md] <- s+ a[mc,md]
t<- EAP_b[md]
EAP_b[md] <- t+ b[mc,md]
}
EAP_a[md] <-EAP_a[md] /MCMC
EAP_b[md] <-EAP_b[md] /MCMC
}
for(md in 1:M){
for(ld in 1:length(l)){
y[ld,md]<-1-stats::pnorm(EAP_b[md] *stats::qnorm(exp(-l[ld]))-EAP_a[md] )
y.lower[ld,md] <- y[ld,md] - var.yy[ld,md]
y.hight[ld,md] <- y[ld,md] + var.yy[ld,md]
}}
for (md in 1:M) {
graphics::par(new = TRUE);plot(l,y.lower[,md], cex= 0.1 ,
col = grDevices::gray(0.8),
xlim = c(0,upper_x ),
ylim = c(lower_y,upper_y),
xlab = '', ylab = ''
)
graphics::par(new = TRUE);plot(l,y.hight[,md], cex= 0.1 ,
col = grDevices::gray(0.8),
xlim = c(0,upper_x ),
ylim = c(lower_y,upper_y),
xlab = '', ylab = ''
)
}
} |
eList_Ch <- Choptank_eList
info_stale_Ch <- getInfo(eList_Ch)
daily_stale_Ch <- getDaily(eList_Ch)
sample_stale_Ch <- getSample(eList_Ch)
surfaces_stale_Ch <- getSurfaces(eList_Ch)
info_orig_Ch <- info_stale_Ch[, 1:(which(names(info_stale_Ch) == "bottomLogQ") - 1)]
daily_orig_Ch <- daily_stale_Ch[, 1:(which(names(daily_stale_Ch) == "Q30") - 1)]
sample_orig_Ch <- sample_stale_Ch[, c("Date","ConcLow", "ConcHigh", "Uncen", "ConcAve",
"Julian","Month","Day","DecYear","MonthSeq",
"SinDY","CosDY")]
surfaces_orig_Ch <- NA
eList_orig_Ch <- mergeReport(info_orig_Ch, daily_orig_Ch, sample_orig_Ch, surfaces_orig_Ch, verbose = FALSE)
sample_orig_Ch <- getSample(eList_orig_Ch)
eList_Ar <- Arkansas_eList
info_stale_Ar <- getInfo(eList_Ar)
daily_stale_Ar <- getDaily(eList_Ar)
sample_stale_Ar <- getSample(eList_Ar)
surfaces_stale_Ar <- getSurfaces(eList_Ar)
info_orig_Ar <- info_stale_Ar[, 1:(which(names(info_stale_Ar) == "bottomLogQ") - 1)]
daily_orig_Ar <- daily_stale_Ar[, 1:(which(names(daily_stale_Ar) == "Q30") - 1)]
sample_orig_Ar <- sample_stale_Ar[, 1:(which(names(sample_stale_Ar) == "yHat") - 1)]
surfaces_orig_Ar <- NA
eList_orig_Ar <- mergeReport(info_orig_Ar, daily_orig_Ar, sample_orig_Ar, surfaces_orig_Ar, verbose = FALSE) |
context("NA_explicit_")
test_that("multiplication works", {
exists("NA_explicit_") ->.;
expect_true(.)
NA_explicit_ ->.; expect_is(., 'character')
}) |
sharks_to_sim_update_EKF_interp_joint <- function(env_obj) {
for (s in env_obj$sharks_to_sim) {
z <- env_obj$lambda_matrix[,env_obj$i, s]
prev_region <- env_obj$Xpart_history[env_obj$i-1, "region",,s]
prev_z <- env_obj$Xpart_history[env_obj$i-1, "lambda",,s]
tis <- env_obj$Xpart_history[env_obj$i-1 , "time_in_state",, s]
newV <- env_obj$Xpart_history[env_obj$i, c("log_speed","turn_rad"),,s]
access_mu_alpha <- access_mu_beta <- cbind(env_obj$state_names[z], "alpha", "mu", env_obj$pnames, s)
access_mu_beta[,2] <- "beta"
access_V_alpha <- access_mu_alpha
access_V_beta <- access_mu_beta
access_V_alpha[,3] <- "V"
access_V_beta[,3] <- "V"
mua0 <- env_obj$mu[access_mu_alpha]
mub0 <- env_obj$mu[access_mu_beta]
Va0 <- env_obj$mu[access_V_alpha]
Vb0 <- env_obj$mu[access_V_beta]
env_obj$mu[access_V_alpha] <- 1/(1 + 1/Va0)
env_obj$mu[access_V_beta] <- 1/(1 + 1/Vb0)
env_obj$mu[access_mu_alpha] <- ((1/Va0)*mua0 + newV["log_speed",]*1) * env_obj$mu[access_V_alpha]
theta_vals <- sapply(newV[ "turn_rad", ], function(ff) ff + env_obj$wn_seq)
beta_weights <- sapply(1:env_obj$npart, function(pp) keep_finite(dnorm(x=theta_vals[,pp], mean=env_obj$logv_angle_mu_draw[pp,"turn",z[ pp ],s], sd=sqrt(env_obj$tau_draw[pp,z[ pp ],s]))))
beta_weights <- apply(beta_weights, 2, function(pp) pp/sum(pp))
wtd_x <- colSums(keep_finite(theta_vals * beta_weights))
wtd_x2 <- colSums(keep_finite(keep_finite(theta_vals^2) * beta_weights))
env_obj$mu[access_mu_beta] <- normalize_angle(((1/Vb0)*mub0 + wtd_x*1) * env_obj$mu[access_V_beta])
access_igamma <- cbind(1:env_obj$npart, 2*z)
env_obj$tau_pars[,,s][ access_igamma ] <- env_obj$tau_pars[,,s][ access_igamma ] + 0.5*((mub0^2)/Vb0 + wtd_x2 - (env_obj$mu[access_mu_beta]^2)/env_obj$mu[access_V_beta])
env_obj$sigma_pars[,,s][ access_igamma ] <- env_obj$sigma_pars[,,s][ access_igamma ] + 0.5*((mua0^2)/Va0 + newV["log_speed",]^2 - (env_obj$mu[access_mu_alpha]^2)/env_obj$mu[access_V_alpha])
access_igamma2 <- cbind(1:env_obj$npart, 2*z - 1)
env_obj$sigma_pars[,,s][ access_igamma2 ] <- env_obj$sigma_pars[,,s][ access_igamma2 ] + 0.5
env_obj$tau_pars[,,s][ access_igamma2 ] <- env_obj$tau_pars[,,s][ access_igamma2 ] + 0.5
env_obj$tau_pars[,,s][ access_igamma ] <- pmin(env_obj$tau_pars[,,s][ access_igamma ], 50 * (env_obj$tau_pars[,,s][ access_igamma2 ] - 1) / env_obj$mu[access_V_beta])
env_obj$sigma_pars[,,s][ access_igamma ] <- pmin(env_obj$sigma_pars[,,s][ access_igamma ], 500 * (env_obj$sigma_pars[,,s][ access_igamma2 ] - 1) / env_obj$mu[access_V_alpha])
for (p in 1:env_obj$npart) {
err_tmp <- keep_finite(t(env_obj$mk_actual_history[env_obj$i, c("X","Y"),p,s]) - env_obj$Xpart_history[env_obj$i,c("X","Y"),p,s])
env_obj$SSquare_particle[,,p,s] <- keep_finite(env_obj$SSquare_particle[,,p,s] + keep_finite(t(err_tmp)%*%err_tmp))
env_obj$Particle_errvar[[ s ]][[ p ]]$sig <- keep_finite(as.matrix(Matrix::nearPD(keep_finite(env_obj$Particle_errvar0 + env_obj$SSquare_particle[,,p,s]), ensureSymmetry=TRUE)$mat))
env_obj$Particle_errvar[[ s ]][[ p ]]$dof <- env_obj$Particle_errvar[[ s ]][[ p ]]$dof + 1
if (env_obj$nstates > 1) {
trans_tmp <- paste(env_obj$lambda_matrix[p, (env_obj$i-1):env_obj$i, s], collapse="")
lookup_tmp <- cbind(prev_region[ p ], match(trans_tmp, env_obj$trans_names))
env_obj$transition_mat[[ s ]][[ p ]]$counts[ lookup_tmp ] <- env_obj$transition_mat[[ s ]][[ p ]]$counts[ lookup_tmp ] + 1
if (env_obj$time_dep_trans & (trans_tmp %in% c("12","21"))) {
env_obj$transition_mat[[ s ]][[ p ]]$dirichlet_pars[ prev_region, prev_z[ p ]] <- (env_obj$transition_mat[[ s ]][[ p ]]$dirichlet_pars[ prev_region, prev_z[ p ]]*tis[ p ] + 1)/tis[ p ]
}
else {
env_obj$transition_mat[[ s ]][[ p ]]$dirichlet_pars[ lookup_tmp ] <- env_obj$region_alphas[ lookup_tmp ] + env_obj$transition_mat[[ s ]][[ p ]]$counts[ lookup_tmp ]
for (k in 1:env_obj$nstates) {
env_obj$transition_mat[[ s ]][[ p ]]$mat[[ prev_region[ p ] ]][ k, ] <- MCMCpack::rdirichlet(n=1, alpha=env_obj$transition_mat[[ s ]][[ p ]]$dirichlet_pars[ prev_region[ p ], c(2*k -1, 2*k) ])
}
}
}
}
}
invisible(NULL)
}
|
sb_create_project <- function(path, ...) {
params <- list(...)
dir.create(path = path, showWarnings = FALSE, recursive = TRUE)
from <- system.file(params$scaffold_type, package = "shinybones")
ll <- list.files(path = from, full.names = TRUE)
file.copy(from = ll, to = path, overwrite = TRUE, recursive = TRUE)
} |
context("Least Squares Classifier")
data(testdata)
test_that("Scale invariance",{
g1 <- LeastSquaresClassifier(testdata$X,testdata$y)
t_scale <- scaleMatrix(testdata$X)
Xs <- predict(t_scale,testdata$X)
g2 <- LeastSquaresClassifier(Xs,testdata$y)
g3 <- LeastSquaresClassifier(testdata$X,testdata$y,x_center = TRUE, scale=TRUE)
expect_equal(loss(g1, testdata$X_test, testdata$y_test),
loss(g2, predict(t_scale,testdata$X_test), testdata$y_test)
)
expect_equal(loss(g1, testdata$X_test, testdata$y_test),
loss(g3, testdata$X_test, testdata$y_test)
)
})
test_that("Formula and matrix formulation give same results", {
g_matrix <- LeastSquaresClassifier(testdata$X,testdata$y)
g_model <- LeastSquaresClassifier(testdata$modelform, testdata$D)
expect_that(1-mean(predict(g_matrix,testdata$X_test)==testdata$y_test),
is_equivalent_to(1-mean(predict(g_model,testdata$D_test)==testdata$D_test[,testdata$classname])))
expect_that(loss(g_matrix, testdata$X_test, testdata$y_test),is_equivalent_to(loss(g_model, testdata$D_test)))
expect_that(g_matrix@classnames,is_equivalent_to(g_model@classnames))
})
test_that("Expected Results on simple benchmark dataset",{
t_matrix <- LeastSquaresClassifier(testdata$X,testdata$y)
expect_equivalent(t_matrix@theta, matrix(c(0.50115100,0.05052317,-0.29484188),3))
})
test_that("Multiclass gives an output",{
dmat<-model.matrix(Species~.-1,iris[1:150,])
tvec<-droplevels(iris$Species[1:150])
set.seed(42)
problem<-split_dataset_ssl(dmat,tvec,frac_train=0.5,frac_ssl=0.0)
expect_equal(length(levels(predict(LeastSquaresClassifier(problem$X,problem$y),problem$X_test))),3)
expect_equal(length(predict(LeastSquaresClassifier(problem$X,problem$y),problem$X_test)),75)
})
test_that("PCA does not change the decision values",{
g_norm <- LeastSquaresClassifier(testdata$X,testdata$y)
Xpc <- princomp(testdata$X)$scores
g_pc <- LeastSquaresClassifier(Xpc,testdata$y)
expect_equal(decisionvalues(g_norm,testdata$X), decisionvalues(g_pc,Xpc))
}) |
create_message <-
function(recipient,
body,
...){
out <- imgurPOST('conversations/',
body = list(recipient = recipient,
body = body),
...)
structure(out, class = 'imgur_basic')
} |
ikcirt.fun.mss.lambda <-
function(jj, iimss, jjmss, rndTrys, mxHatLambda, penalty, usetruesigma ) {
valgp <- rndTrys[jj]
mxHatLambda[iimss, jjmss] <- valgp
mxStHE <- get("mxStHE")
mxDelta <- get("mxDelta")
hatMu <- get("hatMu")
mxHatLSE <- mxHatLambda %*% mxStHE
hatZstar <- mxDelta %*% ( hatMu + mxHatLSE )
if(penalty == "L2" | penalty == "L2c") {
if(!usetruesigma) {
mxSlot <- get("mxSlot")
mxHatEta <- get("mxHatEta")
covStochastic <- get("covStochastic")
mxHatDLS <- mxDelta %*% mxHatLambda %*% mxSlot
useSysCov <- mxHatDLS %*% var(mxHatEta) %*% t(mxHatDLS) + covStochastic
} else {
mxSigma <- get("mxSigma")
useSysCov <- mxSigma
}
}
if(penalty == "logit") {
covStochastic <- get("covStochastic")
Y <- get("Y")
xlambda.shrink <- get("xlambda.shrink")
xbool.lambdaShrinkLL <- get("xbool.lambdaShrinkLL")
if(xbool.lambdaShrinkLL) {
xshrinkTerm <- xlambda.shrink * mean( diag(mxHatLambda %*% t(mxHatLambda)) )
} else {
xshrinkTerm <- xlambda.shrink * mean( diag(mxHatLambda)^2 )
}
hatWstar <- hatZstar / sqrt(diag(covStochastic))
hatY <- matrix( pnorm( hatWstar ), nrow(hatWstar), ncol(hatWstar) )
our.cost <- - mean( Y * log(hatY) + (1-Y) * log(1-hatY), na.rm=TRUE ) + xshrinkTerm ; our.cost
}
if(penalty == "L2") {
Z <- get("Z")
hatWstar <- hatZstar / sqrt(diag(useSysCov))
our.cost <- sqrt( mean( (Z - hatWstar)^2, na.rm=TRUE ) ) ; our.cost
}
if(penalty == "L2c") {
varZ <- get("varZ")
Zconv <- get("Zconv")
hatWstar <- varZ %*% hatZstar / sqrt(diag(useSysCov))
our.cost <- sqrt( mean( (Zconv - hatWstar)^2, na.rm=TRUE ) ) ; our.cost
}
if(penalty == "miscat") {
Y <- get("Y")
our.cost <- 1 - sum( (hatZstar > 0 & Y == 1) | (hatZstar <= 0 & Y == 0) , na.rm=TRUE ) / sum(!is.na(Y)) ; our.cost
}
return(our.cost)
} |
perceptron <- function(input_model=NA,
labels=NA,
max_iterations=NA,
test=NA,
training=NA,
verbose=FALSE) {
IO_RestoreSettings("Perceptron")
if (!identical(input_model, NA)) {
IO_SetParamPerceptronModelPtr("input_model", input_model)
}
if (!identical(labels, NA)) {
IO_SetParamURow("labels", to_matrix(labels))
}
if (!identical(max_iterations, NA)) {
IO_SetParamInt("max_iterations", max_iterations)
}
if (!identical(test, NA)) {
IO_SetParamMat("test", to_matrix(test))
}
if (!identical(training, NA)) {
IO_SetParamMat("training", to_matrix(training))
}
if (verbose) {
IO_EnableVerbose()
} else {
IO_DisableVerbose()
}
IO_SetPassed("output")
IO_SetPassed("output_model")
IO_SetPassed("predictions")
perceptron_mlpackMain()
output_model <- IO_GetParamPerceptronModelPtr("output_model")
attr(output_model, "type") <- "PerceptronModel"
out <- list(
"output" = IO_GetParamURow("output"),
"output_model" = output_model,
"predictions" = IO_GetParamURow("predictions")
)
IO_ClearSettings()
return(out)
} |
test_that("get_reps_senate produces the correct manipulated datasets", {
skip_if_offline()
skip_on_cran()
reps_senate <- AustralianPoliticians::get_reps_senate("reps_senate")
expect_true(exists("reps_senate"))
reps <- AustralianPoliticians::get_reps_senate("reps")
expect_true(exists("reps"))
senate <- AustralianPoliticians::get_reps_senate("senate")
expect_true(exists("senate"))
})
test_that("get_reps_seante produces an error code if given an incorrect argument",{
expect_error(AustralianPoliticians::get_reps_senate("all"))
}) |
context("run: library support")
test_that_odin("abs", {
gen <- odin({
deriv(y) <- 0
initial(y) <- 0
output(a) <- abs(t)
})
tt <- seq(-5, 5, length.out = 101)
expect_equal(gen$new()$run(tt)[, "a"], abs(tt))
})
test_that_odin("log", {
gen <- odin({
deriv(y) <- 0
initial(y) <- 0
output(a) <- log(t)
output(b) <- log(t, 2)
output(c) <- log(t, 10)
})
tt <- seq(0.0001, 5, length.out = 101)
yy <- gen$new()$run(tt)
expect_equal(yy[, "a"], log(tt))
expect_equal(yy[, "b"], log2(tt))
expect_equal(yy[, "c"], log10(tt))
})
test_that_odin("pow", {
gen <- odin({
deriv(y) <- 0
initial(y) <- 0
output(a) <- min(t, t^2 - 2, -t)
output(b) <- max(t, t^2 - 2, -t)
})
tt <- seq(0.0001, 5, length.out = 101)
yy <- gen$new()$run(tt)
expect_equal(yy[, "a"], pmin(tt, tt^2 - 2, -tt))
expect_equal(yy[, "b"], pmax(tt, tt^2 - 2, -tt))
})
test_that_odin("%%", {
gen <- odin({
deriv(y) <- 0
initial(y) <- 0
s <- sin(1)
q <- 1.0
output(s1) <- t %% s
output(s2) <- -t %% s
output(s3) <- t %% -s
output(s4) <- -t %% -s
output(q1) <- t %% q
output(q2) <- -t %% q
output(q3) <- t %% -q
output(q4) <- -t %% -q
})
tt <- seq(-5, 5, length.out = 101)
mod <- gen$new()
res <- mod$run(tt)
s <- sin(1)
q <- 1.0
expect_equal(res[, "s1"], tt %% s)
expect_equal(res[, "s2"], -tt %% s)
expect_equal(res[, "s3"], tt %% -s)
expect_equal(res[, "s4"], -tt %% -s)
expect_equal(res[, "q1"], tt %% q)
expect_equal(res[, "q2"], -tt %% q)
expect_equal(res[, "q3"], tt %% -q)
expect_equal(res[, "q4"], -tt %% -q)
})
test_that_odin("%/%", {
gen <- odin({
deriv(y) <- 0
initial(y) <- 0
s <- sin(1)
q <- 1.0
output(s1) <- t %/% s
output(s2) <- -t %/% s
output(s3) <- t %/% -s
output(s4) <- -t %/% -s
output(q1) <- t %/% q
output(q2) <- -t %/% q
output(q3) <- t %/% -q
output(q4) <- -t %/% -q
})
tt <- seq(-5, 5, length.out = 101)
mod <- gen$new()
res <- mod$run(tt)
s <- sin(1)
q <- 1.0
expect_equal(res[, "s1"], tt %/% s)
expect_equal(res[, "s2"], -tt %/% s)
expect_equal(res[, "s3"], tt %/% -s)
expect_equal(res[, "s4"], -tt %/% -s)
expect_equal(res[, "q1"], tt %/% q)
expect_equal(res[, "q2"], -tt %/% q)
expect_equal(res[, "q3"], tt %/% -q)
expect_equal(res[, "q4"], -tt %/% -q)
})
test_that_odin("2-arg round", {
gen <- odin({
deriv(x) <- 1
initial(x) <- 1
output(y) <- TRUE
output(z) <- TRUE
n <- user(0)
y <- round(t, n)
z <- round(t)
})
mod0 <- gen$new(n = 0)
mod1 <- gen$new(n = 1)
mod2 <- gen$new(n = 2)
tt <- seq(0, 1, length.out = 101)
yy0 <- mod0$run(tt)
yy1 <- mod1$run(tt)
yy2 <- mod2$run(tt)
expect_equal(yy0[, "z"], round(tt))
expect_equal(yy1[, "z"], round(tt))
expect_equal(yy2[, "z"], round(tt))
expect_equal(yy0[, "y"], round(tt, 0))
expect_equal(yy1[, "y"], round(tt, 1))
expect_equal(yy2[, "y"], round(tt, 2))
})
test_that_odin("multivariate hypergeometric", {
gen <- odin({
x0[] <- user()
dim(x0) <- user()
n <- user()
nk <- length(x0)
tmp[] <- rmhyper(n, x0)
dim(tmp) <- nk
output(tmp) <- TRUE
initial(x[]) <- 0
update(x[]) <- tmp[i]
dim(x) <- nk
})
k <- c(6, 10, 15, 3, 0, 4)
n <- 20
mod <- gen$new(x0 = k, n = n)
set.seed(1)
res <- mod$run(0:10)
set.seed(1)
cmp <- t(replicate(10, rmhyper(n, k)))
yy <- mod$transform_variables(res)
expect_equal(yy$x[-1L, ], cmp)
expect_equal(yy$tmp[-11L, ], yy$x[-1L, ])
})
test_that_odin("multivariate hypergeometric - integer input", {
gen <- odin({
x0[] <- user()
dim(x0) <- user(integer = TRUE)
n <- user(integer = TRUE)
nk <- length(x0)
tot <- sum(x0)
tmp[] <- rmhyper(tot, x0)
tmp2[] <- rmhyper(n, tmp)
initial(x[]) <- 0
update(x[]) <- tmp[i]
initial(y[]) <- 0
update(y[]) <- tmp2[i]
dim(tmp) <- nk
dim(tmp2) <- nk
dim(x) <- nk
dim(y) <- nk
})
k <- c(6, 10, 15, 3, 0, 4)
n <- 20
mod <- gen$new(x0 = k, n = n)
set.seed(1)
res <- mod$run(0:10)
set.seed(1)
cmp <- t(replicate(10, rmhyper(n, k)))
yy <- mod$transform_variables(res)
expect_equal(yy$x[-1L, ], matrix(k, 10, 6, TRUE))
expect_equal(yy$y[-1L, ], cmp)
})
test_that_odin("Throw an error if requesting more elements than possible", {
gen <- odin({
b[] <- user()
n <- user()
initial(x[]) <- 0
update(x[]) <- x[i] + b[i]
y[] <- rmhyper(n, x)
output(y) <- TRUE
dim(x) <- 3
dim(b) <- 3
dim(y) <- 3
})
b <- c(10, 15, 9)
n <- 10
mod <- gen$new(b = b, n = n)
expect_error(mod$run(step = 2),
"Requesting too many elements in rmhyper (10 from 0)",
fixed = TRUE)
})
test_that_odin("Can use as.numeric", {
gen <- odin({
a <- user(integer = TRUE)
b <- as.numeric(a)
initial(x) <- 0
update(x) <- x + b
})
mod <- gen$new(a = 5L)
y <- mod$run(0:10)
expect_equal(y[, "x"], seq(0, 50, by = 5))
}) |
neglog <- function(object) {
trafo <- "neglog"
woparam(object = object, trafo = trafo)
} |
tex.catwitherror <- function(x, dx, digits=1, with.dollar=TRUE, with.cdot=TRUE, ...) {
if(missing(x) || length(x) == 0) {
stop("x must be a numeric vector with length > 0")
}
if(length(x) == 2){
dx <- x[2]
x <- x[1]
have.error <- TRUE
}else if(!missing(dx)){
have.error <- TRUE
}else{
have.error <- FALSE
}
if(!have.error){
tmp <- formatC(x, digits=digits, ...)
}
else if(is.numeric(dx) && dx == 0){
tmp <- formatC(x, digits=digits, ...)
if(grepl("e", tmp, fixed=TRUE)){
tmp <- sub("e", "(0)e", tmp)
}else{
tmp <- paste0(tmp, "(0)")
}
}
else{
if(requireNamespace('errors')){
tmp <- format(errors::set_errors(x, dx), digits=digits, ...)
}else{
warning("The `errors`-package is not installed. The output of `tex.catwitherror` might not be as you want it.")
tmp <- formatC(x, digits=digits, ...)
tmp <- paste0(tmp, " +- ", formatC(dx, digits=digits, ...))
}
}
if(with.cdot){
if(grepl("e", tmp, fixed=TRUE)){
tmp <- sub("e", "\\\\cdot 10^{", tmp)
tmp <- paste0(tmp, "}")
}
tmp <- sub("+-", "\\\\pm", tmp, fixed=TRUE)
}
if (with.dollar) {
tmp <- paste0("$", tmp, "$")
}
return (tmp)
}
escapeLatexSpecials <- function(x) {
x <- gsub("\\", "$\\backslash$", x, fixed = TRUE)
x <- gsub("
x <- gsub("$", "\\$", x, fixed=TRUE)
x <- gsub("%", "\\%", x, fixed=TRUE)
x <- gsub("&", "\\&", x, fixed=TRUE)
x <- gsub("~", "\\~", x, fixed=TRUE)
x <- gsub("_", "\\_", x, fixed=TRUE)
x <- gsub("^", "\\^", x, fixed=TRUE)
x <- gsub(">", "$>$", x, fixed=TRUE)
x <- gsub("<", "$<$", x, fixed=TRUE)
return(x)
} |
pack <- function(cells, types = data_type, name = "value", drop_types = TRUE,
drop_type_cols = TRUE) {
types <- rlang::ensym(types)
name <- rlang::ensym(name)
type_colnames <- format(unique(dplyr::pull(cells, !!types)),
justify = "none",
trim = TRUE
)
missing_types <- setdiff(type_colnames, colnames(cells))
new_cols <- rep_len(NA, length(missing_types))
names(new_cols) <- missing_types
cells <- dplyr::mutate(
cells,
!!!new_cols,
!!types := format(!!types,
justify = "none",
trim = TRUE
)
)
type_values <- unique(dplyr::pull(cells, !!types))
patterns <-
map(
type_values,
~ rlang::expr(!!types == !!.x ~ as.list(!!rlang::ensym(.x)))
)
out <- dplyr::mutate(cells, !!name := dplyr::case_when(!!!patterns))
names(out[[rlang::expr_text(name)]]) <- dplyr::pull(cells, !!types)
if (drop_types && rlang::expr_text(types) != rlang::expr_text(name)) {
out <- dplyr::select(out, -!!types)
}
if (drop_type_cols) {
type_colnames <- setdiff(type_colnames, rlang::expr_text(name))
out <- dplyr::select(out, -dplyr::one_of(type_colnames))
}
out
}
unpack <- function(cells, values = value, name = "data_type",
drop_packed = TRUE) {
values <- rlang::ensym(values)
name <- rlang::ensym(name)
types <- names(dplyr::pull(cells, !!values))
type_names <- format(unique(types), justify = "none", trim = TRUE)
assignments <- purrr::map(
type_names,
~ rlang::expr(ifelse(types == !!.x,
!!values,
!!list(NULL)
))
)
names(assignments) <- type_names
out <-
dplyr::mutate(cells, !!name := types, !!!assignments) %>%
dplyr::mutate_at(type_names,
concatenate,
combine_factors = FALSE,
fill_factor_na = FALSE
)
first_colnames <- setdiff(colnames(out), type_names)
last_colnames <- sort(type_names)
out <- dplyr::select(out, first_colnames, last_colnames)
if (drop_packed) out <- dplyr::select(out, -!!values)
out
} |
setMethodS3("getOutputIdentifier", "QuantileNormalization", function(this, ..., verbose=FALSE) {
verbose <- Arguments$getVerbose(verbose)
if (verbose) {
pushState(verbose)
on.exit(popState(verbose))
}
verbose && enter(verbose, "Calculating the output identifier")
verbose && enter(verbose, "Retrieving the identifier for input data set")
ds <- getInputDataSet(this)
inputId <- getIdentifier(ds)
verbose && exit(verbose)
verbose && enter(verbose, "Calculating the identifier for parameters")
paramId <- this$.paramId
params <- getParameters(this)
params$.targetDistribution <- attr(params$.targetDistribution, "identifier")
paramId <- getChecksum(list(params))
this$.paramId <- paramId
verbose && exit(verbose)
verbose && enter(verbose, "Calculating the joint identifier")
id <- getChecksum(list(inputId, paramId))
verbose && exit(verbose)
verbose && exit(verbose)
id
}, private=TRUE) |
options(width = 150,tibble.print_max=50)
library(quickReg)
library(ggplot2)
library(rlang)
library(dplyr)
data(diabetes)
head(diabetes)
display_1<-display_table(data=diabetes,variables=c("age","smoking","education"),group="CFHrs2230199")
display_1
display_2<-display_table_group(data=diabetes,variables=c("age","smoking"),group="CFHrs2230199",super_group = "sex")
display_2
display_3<-display_table_group(data=diabetes,variables=c("age","smoking"),group="CFHrs2230199",super_group = c("sex","education"))
display_3
display_4<-display_table_group(data=diabetes,variables=c("age","smoking"),group="CFHrs2230199",super_group = c("sex","education"),group_combine = TRUE)
display_4
reg_1<-reg_x(data = diabetes, y = 5, factors = c(1, 3, 4), model = 'glm')
reg_1
reg_2<-reg_x(data = diabetes, x = c(3:4, 6), y ="diabetes",time=2,factors = c(1, 3, 4), model = 'coxph')
reg_2
reg_3<-reg_x(data = diabetes, x = c("sex","age"), y ="diabetes" ,cov=c("CFBrs641153","CFHrs2230199"), factors ="sex", model = 'glm',cov_show = TRUE)
reg_3
reg_4<-reg_y(data = diabetes, x = c("sex","age","CFHrs1061170"), y =c("systolic","diastolic","BMI") ,cov=c("CFBrs641153","CFHrs2230199"), factors ="sex", model = 'lm')
reg_4
reg_5<-reg(data = diabetes, x = c("age","CFHrs1061170"), y =c("systolic","diastolic") ,cov=c("CFBrs641153","CFHrs2230199"), model = 'lm',group="sex")
reg_5
reg_6<-reg(data = diabetes, x = c("age","CFHrs1061170"), y =c("systolic","diastolic") ,cov=c("CFBrs641153","CFHrs2230199"), model = 'lm',group=c("sex","smoking"))
reg_6
reg_7<-reg(data = diabetes, x = c("age","CFHrs1061170"), y =c("systolic","diastolic") ,cov=c("CFBrs641153","CFHrs2230199"), model = 'lm',group=c("sex","smoking"),group_combine = TRUE)
reg_7
plot(reg_1)
plot(reg_1,limits=c(NA,3))
plot(reg_1,limits=c(NA,3), sort ="alphabetical")
plot(reg_4)
plot(reg_5)+facet_grid(sex~y)
library(ggplot2);library(ggthemes)
plot(reg_1,limits=c(0.5,2))+
labs(list(title = "Regression Model", x = "variables"))+
theme_classic() %+replace%
theme(legend.position ="none",axis.text.x=element_text(angle=45,size=rel(1.5))) |
newstart_allowance <- function(fortnightly_income = 0,
annual_income = 0,
has_partner = FALSE,
partner_pensioner = FALSE,
n_dependants = 0,
nine_months = FALSE,
isjspceoalfofcoahodeoc = FALSE,
principal_carer = FALSE,
fortnightly_partner_income = 0,
annual_partner_income = 0,
age = 22,
fy.year = "2015-16",
assets_value = 0,
homeowner = FALSE,
lower = 102,
upper = 252,
taper_lower = 0.5,
taper_upper = 0.6,
taper_principal_carer = 0.4,
per = c("year", "fortnight")) {
if (!identical(fy.year, "2015-16")) {
stop('`fy.year` can only take value "2015-16" for now')
}
prohibit_vector_recycling(fortnightly_income,
annual_income,
has_partner,
partner_pensioner,
n_dependants,
nine_months,
isjspceoalfofcoahodeoc,
principal_carer,
fortnightly_partner_income,
annual_partner_income,
age,
fy.year,
assets_value,
homeowner,
lower,
upper,
taper_lower,
taper_upper,
taper_principal_carer)
input <-
data.table(fortnightly_income = as.double(fortnightly_income),
annual_income = as.double(annual_income),
has_partner,
partner_pensioner,
n_dependants,
nine_months,
isjspceoalfofcoahodeoc,
principal_carer,
fortnightly_partner_income,
annual_partner_income,
age,
fy.year,
assets_value,
homeowner,
lower,
upper,
taper_lower,
taper_upper,
taper_principal_carer)
if (input[, any(!has_partner & partner_pensioner)]) {
stop('check conflicting values for `has_partner` and `partner_pensioner`')
}
if (input[, any(annual_partner_income > 0 & !has_partner)]) {
stop('check conflicting values for `has_partner` and `annual_partner_income`')
}
if (input[, any(fortnightly_partner_income > 0 & !has_partner)]) {
stop('check conflicting values for `has_partner` and `fortnightly_partner_income`')
}
input[, fortnightly_income := if_else(annual_income > 0 & fortnightly_income == 0,
annual_income / 26,
fortnightly_income)]
input[, fortnightly_partner_income := if_else(annual_partner_income > 0 & fortnightly_partner_income == 0,
annual_partner_income / 26,
fortnightly_partner_income)]
input[, annual_income := if_else(fortnightly_income > 0 & annual_income == 0,
fortnightly_income * 26,
annual_income)]
input[, annual_partner_income := if_else(fortnightly_partner_income > 0 & annual_partner_income == 0,
fortnightly_partner_income * 26,
annual_partner_income)]
if(!input[, isTRUE(all.equal(annual_income, 26 * fortnightly_income, tol = 1e-04))]){
stop('input for `annual_income` is not 26 times larger than `fortnightly_income`')
}
if(!input[, isTRUE(all.equal(annual_partner_income, 26 * fortnightly_partner_income, tol = 1e-04))]){
stop('input for `annual_partner_income` is not 26 times larger than `fortnightly_partner_income`')
}
max_rate_March_2016 <- NULL
input[, max_rate_March_2016 := if_else(isjspceoalfofcoahodeoc,
737.10,
if_else(has_partner,
476.4,
if_else(and(age >= 60, nine_months),
570.80,
if_else(n_dependants > 0,
570.80,
527.60))))]
eligible <- NULL
input[, eligible := 22 <= age & age < 65]
max_income_March_2016 <- NULL
input[, max_income_March_2016 := if_else(isjspceoalfofcoahodeoc,
1974.75,
if_else(has_partner,
934.74,
if_else(and(age > 60, nine_months),
1104.50,
if_else(n_dependants == 0,
1021,
if_else(principal_carer,
1552.75,
1094.17)))))]
input[(partner_pensioner),
fortnightly_income := (fortnightly_partner_income + fortnightly_income) / 2]
income_reduction <- NULL
input %>%
.[, income_reduction := 0] %>%
.[fortnightly_income > lower,
income_reduction := if_else(principal_carer,
if_else(fortnightly_income < max_income_March_2016,
taper_principal_carer * (fortnightly_income - lower),
max_rate_March_2016),
if_else(fortnightly_income < upper,
taper_lower * (fortnightly_income - lower),
if_else(fortnightly_income < max_income_March_2016,
taper_lower * (fortnightly_income - lower) +
(taper_upper - taper_lower) * (fortnightly_income - upper),
max_rate_March_2016)))]
asset_threshold <- NULL
input[, asset_threshold := if_else(has_partner,
if_else(homeowner,
assets_value < 286500,
assets_value < 433000),
if_else(homeowner,
assets_value < 202000,
assets_value < 348500))]
partner_income_reduction <- NULL
input %>%
.[, partner_income_reduction :=
and(has_partner,
(fortnightly_partner_income > max_income_March_2016) & !partner_pensioner) *
taper_upper *
(fortnightly_partner_income -
ceiling((max_rate_March_2016 -
(upper - lower) * taper_lower +
upper * taper_upper) / taper_upper))]
fortnightly_rate <- NULL
input[, fortnightly_rate :=
and(eligible, asset_threshold) *
pmax0(max_rate_March_2016 - income_reduction - partner_income_reduction)]
ans <- input[, fortnightly_rate * 26]
ans / validate_per(per, missing(per))
} |
context("Check plot() function")
source("objects_for_tests.R")
test_that("plotMeasure", {
expect_is(plot(measure), "gg")
})
test_that("plotMeasure2", {
expect_is(plot(measure, color = NULL), "gg")
})
test_that("plotMeasure3", {
expect_is(plot(measure, measure_lm2, color = "_label_model_"), 'gg')
})
test_that("plotMeasure4", {
expect_is(plot(measure, variables = c("floor", "surface")), "gg")
})
test_that("plotMessage5", {
expect_is(plot(measure, variables = c("floor", "surface"), type = "lines"), "gg")
})
test_that("plotMessage5", {
expect_is(plot(measure_lm2, measure, color = "_label_model_", type = "bars"), "gg")
})
test_that("plotMessage6", {
expect_error(plot(measure_lm2, measure, color = "_label_model_", type = "line"))
})
test_that("plotMeasure7", {
expect_error(plot(measure, variables = c("district", "m2.price")))
})
test_that("plotLabel", {
expect_error(plot(measure, measure_lm, color = "_label_model_"))
})
test_that("plotLabel2", {
expect_error(plot(measure, color = "_label_model_"))
})
test_that("plotMessage", {
expect_message(plot(measure, measure_lm), "Measure will be plotted only for the first observation.")
})
test_that("plotMessage2", {
expect_message(plot(measure, measure_lm), "Measure will be plotted only for the first observation.")
})
measure_lm3 <- measure_lm2
measure_lm3$`_label_model_` <- " "
measure_2 <- measure
measure_2$`_label_model_` <- " "
test_that("plotMessage3", {
expect_message(plot(measure_2, measure_lm3, color = "_label_method_"), "Measure will be plotted only for the first observation. Add different labels for each method.")
})
test_that("plotMessage4", {
expect_message(plot(measure_2, measure_lm3, color = "_label_model_"), "Measure will be plotted only for the first observation. Add different labels for each model.")
})
test_that("plotMessage5", {
expect_is(plot(measure_2, color = "_label_method_"), 'gg')
})
p_cp <- plot(measure)
test_that("titlePlot", {
expect_equal(p_cp$labels$title, "Local variable importance")
})
p_cp1 <- plot(measure_lm2, measure, color = "_label_model_", type = "lines")
test_that("titlePlot2", {
expect_equal(p_cp1$labels$title, "Local variable importance")
})
test_that("subtitlePlot", {
expect_equal(p_cp$labels$subtitle, "absolute_deviation = TRUE, point = TRUE, density = TRUE")
})
test_that("subtitlePlot2", {
expect_equal(as.character(p_cp1$labels$subtitle), "absolute_deviation = TRUE, point = TRUE, density = TRUE")
})
test_that("plotGlobalMeasure", {
expect_is(plot(measure_pdp), 'gg')
})
test_that("plotGlobalMeasure2", {
expect_is(plot(measure_pdp, type = "lines"), 'gg')
})
test_that("plotGlobalMeasure3", {
expect_is(plot(measure_pdp, type = "bars"), 'gg')
})
test_that("plotGlobalMeasure4", {
expect_is(plot(measure_pdp, variables = c("surface", "floor")), 'gg')
})
test_that("plotGlobalMeasure5", {
expect_is(plot(measure_pdp, measure_pdp_lm, variables = c("surface", "floor")), 'gg')
})
test_that("plotGlobalMeasure6", {
expect_error(plot(measure_pdp, type = "scatter"))
})
measure_pdp2 <- measure_pdp
measure_pdp2$`_label_model_` <- ""
measure_pdp_lm2 <- measure_pdp_lm
measure_pdp_lm2$`_label_model_` <- ""
test_that("plotGlobalMeasure7", {
expect_message(plot(measure_pdp2, measure_pdp_lm2), "Measure will be plotted only for the first observation. Add different labels for each model.")
})
test_that("plotGlobalMeasure8", {
expect_error(plot(measure_pdp, variables = c("district", "m2.price")))
})
test_that("plotGlobalMeasure9", {
expect_is(plot(measure_pdp, measure_pdp_lm, variables = c("surface", "floor"), type = "lines"), 'gg')
})
p_pdp <- plot(measure_pdp)
test_that("titlePlotGlobal", {
expect_equal(p_pdp$labels$title, "Variable importance")
})
test_that("labsPlotGlobal", {
expect_equal(p_pdp$labels$y, "Measure")
}) |
"pargev" <-
function(lmom,checklmom=TRUE,...) {
para <- rep(NA,3)
names(para) <- c("xi","alpha","kappa")
SMALL <- 1e-5; EPS <- 1e-6; MAXIT <- 20;
EU <- 0.57721566; DL2 <- 0.69314718; DL3 <- 1.0986123
A0 <- 0.28377530; A1 <- -1.21096399; A2 <- -2.50728214
A3 <- -1.13455566; A4 <- -0.07138022
B1 <- 2.06189696; B2 <- 1.31912239; B3 <- 0.25077104
C1 <- 1.59921491; C2 <- -0.48832213; C3 <- 0.01573152
D1 <- -0.64363929; D2 <- 0.08985247
if(length(lmom$L1) == 0) {
lmom <- lmorph(lmom)
}
if(checklmom & ! are.lmom.valid(lmom)) {
warning("L-moments are invalid")
return()
}
T3 <- lmom$TAU3
if(T3 > 0) {
Z <- 1-T3
G <- (-1+Z*(C1+Z*(C2+Z*C3)))/(1+Z*(D1+Z*D2))
if(abs(G) < SMALL) {
para[3] <- 0
para[2] <- lmom$L2/DL2
para[1] <- lmom$L1-EU*para[2]
return(list(type = 'gev', para = para))
}
}
else {
G <- (A0+T3*(A1+T3*(A2+T3*(A3+T3*A4))))/(1+T3*(B1+T3*(B2+T3*B3)))
if(T3 >= -0.80) {
}
else {
if(T3 <= -0.97) G <- 1-log(1+T3)/DL2
T0 <- (T3+3)*0.5
CONVERGE <- FALSE
for(it in seq(1,MAXIT)) {
X2 <- 2^-G
X3 <- 3^-G
XX2 <- 1-X2
XX3 <- 1-X3
T <- XX3/XX2
DERIV <- (XX2*X3*DL3-XX3*X2*DL2)/(XX2*XX2)
GOLD <- G
G <- G-(T-T0)/DERIV
if(abs(G-GOLD) <= EPS*G) CONVERGE <- TRUE
}
if(CONVERGE == FALSE) {
warning("Noconvergence---results might be unreliable")
}
}
}
para[3] <- G
GAM <- exp(lgamma(1+G))
para[2] <- lmom$L2*G/(GAM*(1-2**(-G)))
para[1] <- lmom$L1 - para[2]*(1-GAM)/G
return(list(type = 'gev', para = para, source="pargev"))
} |
transform_coord <- function(x = NULL, lon = NULL, lat = NULL, new.names = "auto", proj.in = 4326, proj.out = NULL, verbose = FALSE, bind = FALSE, na = "ignore") {
if(length(new.names) == 1) {
if(new.names == "auto") {
if(is.null(x)) {
new.names <- c("lon", "lat")
} else if(bind) {
new.names <- c("lon.proj", "lat.proj")
} else {
new.names <- guess_coordinate_columns(x)
}
}
}
if(is.null(proj.out) & !sf::st_is_longlat(proj.in)) stop("proj.in has to be decimal degrees when proj.out = NULL.")
if(!is.null(proj.out)) {
error_test <- quiet(try(match.arg(proj.out, shapefile_list("all")$name), silent = TRUE))
if(class(error_test) != "try-error") {
proj.out <- sf::st_crs(shapefile_list(proj.out)$crs)
}
}
if(is.null(proj.in)) {
if(is.null(x)) stop("a spatial object as x is required when proj.in = NULL")
if("sf" %in% class(x)) {
proj.in <- sf::st_crs(x)
} else if("sp" %in% class(x)) {
proj.in <- raster::crs(x)
} else stop("a spatial object of class sf or sp as x is required when proj.in = NULL")
}
if(!is.null(x) & (is.null(lon) | is.null(lat))) {
tmp <- guess_coordinate_columns(x)
lon <- unname(tmp[names(tmp) == "lon"])
lat <- unname(tmp[names(tmp) == "lat"])
if(verbose) {
message(paste0("Used ", lon, " and ", lat, " as input coordinate column names in x"))
}
}
if(is.null(x) & (!is.numeric(lon) | !is.numeric(lat))) {
stop("Define either x or lon and lat as numeric vectors")
}
if(is.null(x) & (is.numeric(lon) | is.numeric(lat))) {
if(length(lon) != length(lat)) stop("lat and lon must be of equal length")
y <- data.frame(lon = lon, lat = lat)
lon <- "lon"; lat <- "lat"
y$id <- 1:nrow(y)
}
if(!is.null(x)) {
if(!is.data.frame(x)) stop("x must be a data frame")
oldrownames <- rownames(x)
suppressWarnings(rownames(x) <- 1:nrow(x))
if("data.table" %in% class(x)) {
y <- x[, c(lon, lat), with = FALSE]
} else {
y <- x[c(lon, lat)]
}
y$id <- 1:nrow(y)
}
if(na == "ignore") {
z <- y[eval(is.na(y[[lon]]) | is.na(y[[lat]])),]
y <- y[eval(!(is.na(y[[lon]]) | is.na(y[[lat]]))),]
} else if(na == "remove") {
y <- y[eval(!is.na(y[[lon]]) | !is.na(y[[lat]])),]
y <- y[eval(!is.na(y[[lon]]) | !is.na(y[[lat]])),]
message("Removed rows that contained missing coordinates.")
} else {
if(any(c(eval(is.na(y[[lon]])), is.na(y[[lat]])))) {
stop("lon or lat coordinates contain missing values. Adjust the na argument or take care of the NAs.")
}
}
if(is.null(proj.out)) {
limits <- c(range(y[[lon]]), range(y[[lat]]))
shapefile.def <- define_shapefiles(limits)
proj.out <- sf::st_crs(shapefile_list(shapefile.def$shapefile.name)$crs)
}
if("crs" != class(proj.in)) {
error_test <- quiet(try(sf::st_crs(proj.in), silent = TRUE))
if(class(error_test) == "try-error") {
stop("Failed to convert the argument proj.in to sf::st_crs object in the transform_coord function. This is likely a bug. If so, please file a bug report on GitHub.")
} else {
proj.in <- error_test
}
}
if("crs" != class(proj.out)) {
error_test <- quiet(try(sf::st_crs(proj.out), silent = TRUE))
if(class(error_test) == "try-error") {
stop("Failed to convert the argument proj.out to sf::st_crs object in the transform_coord function. This is likely a bug. If so, please file a bug report on GitHub.")
} else {
proj.out <- error_test
}
}
y <- cbind(
stats::setNames(
data.frame(sf::sf_project(from = proj.in, to = proj.out, y[,1:2])),
c(lon, lat)),
id = y$id)
if(na == "ignore" & nrow(z) > 0) {
y <- rbind(y, z)
rownames(y) <- y$id
y <- y[order(y$id), !colnames(y) %in% "id"]
} else {
y <- y[, !colnames(y) %in% "id"]
}
if(!is.null(new.names)) {
if(any(length(new.names) != 2, !is.character(new.names))) {
stop("new.names must be a character vector with length of 2")
}
colnames(y) <- new.names
}
if(verbose) {
if("input" %in% names(proj.in)) {
proj.in.msg <- proj.in$input
} else {
proj.in.msg <- proj.in
}
if("input" %in% names(proj.out)) {
proj.out.msg <- proj.out$input
} else {
proj.out.msg <- proj.out
}
message(paste("projection transformed from", proj.in.msg, "to", proj.out.msg))
}
if(!sf::st_is_longlat(proj.in) & sf::st_is_longlat(proj.out)) {
tmp <- colnames(x)
colnames(x) <- colnames(y)
colnames(y) <- tmp
}
if(bind) {
out <- cbind(x, y)
} else {
out <- y
}
if(exists("oldrownames")) {
rownames(out) <- oldrownames
out <- out
} else {
out <- out
}
attributes(out)$proj.in <- proj.in
attributes(out)$proj.out <- proj.out
out
} |
context("qtestr")
expect_succ_all = function(x, rules) {
xn = deparse(substitute(x))
expect_true(qtestr(x, rules),
info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn)
expect_identical(qassertr(x, rules), x,
info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn)
expect_expectation_successful(qexpectr(x, rules),
info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn)
}
expect_fail_all = function(x, rules, pattern = NULL) {
xn = deparse(substitute(x))
expect_false(qtestr(x, rules),
info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn)
expect_error(qassertr(x, rules), regexp = pattern,
info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn)
expect_expectation_failed(qexpectr(x, rules),
info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn)
}
test_that("qassertr / qtestr", {
x = list(a = 1:10, b = rnorm(10))
expect_succ_all(x, "n+")
expect_succ_all(x, "n10")
expect_succ_all(x, "n>=1")
expect_fail_all(x, "i+")
expect_fail_all(x, "l")
x = list(a = NULL, b = 10)
expect_succ_all(x, "*")
expect_fail_all(x, "0")
expect_fail_all(x, "n")
x = list(a = NULL, b = NULL)
expect_succ_all(x, "0")
expect_fail_all(x, "0+")
x = list()
expect_succ_all(x, "n+")
expect_succ_all(x, "0+")
x = list(1, 2)
expect_fail_all(x, "S1", pattern = "string")
x = list(1:10, NULL)
expect_succ_all(x, c("v", "l", "0"))
rules = c("v", "l")
expect_fail_all(x, c("v", "l"), pattern = "One of")
expect_succ_all(iris, c("f", "n"))
expect_fail_all(iris, c("s", "n"), pattern = "One of")
x = NULL
expect_error(qassertr(x, "x"), "list or data.frame")
expect_error(qtestr(x, "x"), "list or data.frame")
})
test_that("qtestr / depth", {
x = list(letters, 1:10, list(letters, 2:3, runif(10)))
rules = c("v", "l")
expect_true(qtestr(x, rules, depth = 1L))
expect_true(qtestr(x, rules, depth = 2L))
expect_true(qtestr(x, rules, depth = 3L))
x[[3]][[2]] = iris
expect_true(qtestr(x, rules, depth = 1L))
expect_true(qtestr(x, c(rules, "d"), depth = 1L))
expect_false(qtestr(x, rules, depth = 2L))
expect_false(qtestr(x, rules, depth = 3L))
}) |
expected <- eval(parse(text="c(1, 53, 1)"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(49.9, 52.3, 49.4, 51.1, 49.4, 47.9, 49.8, 50.9, 49.3, 51.9, 50.8, 49.6, 49.3, 50.6, 48.4, 50.7, 50.9, 50.6, 51.5, 52.8, 51.8, 51.1, 49.8, 50.2, 50.4, 51.6, 51.8, 50.9, 48.8, 51.7, 51, 50.6, 51.7, 51.5, 52.1, 51.3, 51, 54, 51.4, 52.7, 53.1, 54.6, 52, 52, 50.9, 52.6, 50.2, 52.6, 51.6, 51.9, 50.5, 50.9, 51.7), .Tsp = c(1, 53, 1)), \"tsp\")"));
do.call(`attr`, argv);
}, o=expected); |
vanderMonde <- function (x, order, ...){
if (nargs () > 2)
stop ('Unknown arguments: ', names (c (...)))
outer (x, 0 : order, `^`)
}
setGeneric ("vanderMonde")
setMethod ("vanderMonde", signature = signature (x = "hyperSpec"),
function (x, order, ..., normalize.wl = normalize01){
validObject (x)
wl <- normalize.wl (x@wavelength)
x <- decomposition (x, t (vanderMonde (wl, order)), scores = FALSE, ...)
x$.vdm.order <- 0 : order
x
})
.test (vanderMonde) <- function (){
context ("vanderMonde")
test_that("vector against manual calculation",{
expect_equal (vanderMonde (c (1 : 3, 5), 2),
matrix (c (1, 1, 1, 1, 1, 2, 3, 5, 1, 4, 9, 25), nrow = 4)
)
})
test_that("default method doesn't provide normalization",{
expect_error (vanderMonde (1, 0, normalize.wl = normalize01))
})
test_that ("hyperSpec objects", {
expect_true (chk.hy (vanderMonde (flu, 0)))
expect_true (validObject (vanderMonde (flu, 0)))
tmp <- vanderMonde (paracetamol, 3, normalize.wl = I)
dimnames (tmp$spc) <- NULL
expect_equal (tmp [[]], t (vanderMonde (wl (paracetamol), 3)))
tmp <- vanderMonde (paracetamol, 3, normalize.wl = normalize01)
dimnames (tmp$spc) <- NULL
expect_equal (tmp[[]], t (vanderMonde (normalize01 (wl (paracetamol)), 3)))
})
} |
CH.sel <- function(data, min.nc, max.nc, method){
alls <- lapply(min.nc:max.nc, CH,
data = data, method = method)
res <- sapply(alls, function(i){
i[["CH"]]
}, simplify = TRUE, USE.NAMES = TRUE)
MAX <- max(res)
K <- (min.nc:max.nc)[which(res == MAX)[1]]
names(res) <- paste("k =", min.nc:max.nc)
return(list(Best.nc = K,
CritCF.val = res,
Best.partition = alls[[which(res == MAX)[1]]][["Partition"]]
)
)
}
CH <- function(data, k, method, Seed = 1){
if (!is.null(Seed)) {set.seed(Seed)}
if (method == "kmed"){
kmed <- suppressWarnings(Gmedian::kGmedian(X = data, ncenters = k))
Classif <- kmed$cluster[, 1]
}
if (method == "kproto"){
kprot <- clustMixType::kproto(x = data, k = k,
keep.data = FALSE, verbose = FALSE)
Classif <- kprot$cluster
}
Crit <- clusterCrit::intCriteria(
traj = as.matrix(data[, sapply(data, is.numeric)]),
part = as.integer(Classif),
crit = "Calinski_Harabasz"
)
return(list(CH = Crit[[1]], Partition = Classif))
} |
blwts <- function(xmat, y, robdis2 = mycov.rob(as.matrix(xmat), method = "mcd")$robdis2,
percent = 0.95, k = 2, intest = myltsreg(xmat, y)$coef) {
xmat = as.matrix(xmat)
y = as.matrix(y)
n = dim(xmat)[1]
p = dim(xmat)[2]
cut1 = qchisq(percent, 1)
cutp = qchisq(percent, p)
resids = y - intest[1] - xmat %*% as.matrix(intest[2:(p +
1)])
sigma = mad(resids)
ind1 = as.numeric(abs(resids) > sigma * sqrt(cut1))
ind2 = as.numeric(robdis2 > cutp)
tmp = (cutp/robdis2)^(k/2)
h = 1 - (ind1 * ind2 * (1 - tmp))
tmp2 = pairup(h)
ans = tmp2[, 1] * tmp2[, 2]
ans
}
cellmntest <- function(y, levels, amat = cbind(rep(1, max(levels) - 1), -1 *
diag(max(levels) - 1)), delta = 0.8, param = 2, print.tbl = T) {
amat = rbind(amat)
xcell = cellmnxy(levels)
p = length(xcell[1, ])
xmat = xcell[, 2:p]
amat = amat[, 2:p]
ans = suppressWarnings(droptest(xmat, y, amat, delta, param,
print.tbl))
ans$full$coef = ans$full$coef + c(0, rep(ans$full$coef[1],
p - 1))
invisible(ans)
}
cellmnxy <- function(levels) {
k = max(levels)
n = length(levels)
cellmnxy = matrix(rep(0, n * k), ncol = k)
for (i in 1:k) {
cellmnxy[, i][levels == i] = 1
}
cellmnxy
}
centerx <- function(x) {
x = as.matrix(x)
n = length(x[, 1])
one = matrix(rep(1, n), ncol = 1)
x - (one %*% t(one)/n) %*% x
}
diffwls <- function(x, y, delta = 0.8, param = 2, conf = 0.95) {
x = as.matrix(centerx(x))
n = length(x[, 1])
p = length(x[1, ])
tempw = wwest(x, y, "WIL", print.tbl = F)
residw = tempw$tmp1$residuals
tempvc = varcov.gr(centerx(x), tempw$tmp1$weights, tempw$tmp1$residuals)
vcw = as.matrix(tempvc$varcov)
templs = lsfit(x, y)
diff = tempw$tmp1$coef - templs$coef
vcwint = vcw[1, 1]
pp1 = length(x[1, ]) + 1
vcwbeta = vcw[2:pp1, 2:pp1]
tdbeta = t(diff) %*% solve(vcw) %*% diff
tdint = diff[1]^2/vcwint
bmtd = (4 * pp1^2)/n
xmat = cbind(rep(1, n), x)
diffc = xmat %*% diff[1:pp1]
diffvc = xmat %*% vcw %*% t(xmat)
cd = diffc/(sqrt(diag(diffvc)))
bmcd = 2 * sqrt(pp1/n)
se = sqrt(diag(vcw))
list(tdbeta = tdbeta, tdint = tdint, bmtd = bmtd, cfit = cd,
bmcd = bmcd, est = c("WIL", "LS"), betaw = tempw$tmp1$coef,
betals = templs$coef, vcw = vcw, tau = tempvc$tau, taus = tempvc$tau1,
se = se)
}
droptest <- function(xmat, y, amat, delta = 0.8, param = 2, print.tbl = T) {
xmat = as.matrix(xmat)
amat = rbind(amat)
p = length(xmat[1, ])
pp1 = p + 1
n = length(xmat[, 1])
q = length(amat[, 1])
if (p != dim(amat)[2])
stop("droptest: The number of columns in amat and xmat are different.")
full = wwfit(xmat, y)
dfull = wildisp(full$residuals)
tauhat = wilcoxontau(full$residuals, p, delta, param)
if (q < p) {
xuse = xmat
ause = amat
xred = redmod(xuse, ause)
red = wwfit(xred, y)
dred = wildisp(red$residuals)
rd = dred - dfull
mrd = rd/q
fr = mrd/(tauhat/2)
}
else {
warning("droptest: H_0: beta=0 is being tested since q>=p.",
call. = F)
q = p
dred = wildisp(y)
rd = dred - dfull
mrd = rd/q
fr = mrd/(tauhat/2)
}
df2 = n - p - 1
ts2 = tauhat/2
pval = 1 - pf(fr, q, df2)
if (print.tbl) {
cnames = c("RD", "DF", "MRD", "TS", "PVAL")
rnames = c("H0", "Error")
ans = cbind(c(rd, NA), c(q, df2), c(mrd, ts2), c(fr,
NA), c(pval, NA))
ans = round(ans, 4)
dimnames(ans) = list(rnames, cnames)
cat("\n")
prmatrix(ans, na.print = "")
cat("\n")
}
invisible(list(full = full, dred = dred, dfull = dfull, tauhat = tauhat,
q = q, fr = fr, pval = pval))
}
fitdiag <- function(x, y, est = c("WIL", "GR"), delta = 0.8, param = 2,
conf = 0.95) {
x = as.matrix(centerx(x))
n = dim(x)[1]
p = dim(x)[2]
tempw = wwest(x, y, "WIL", print.tbl = F)
residw = tempw$tmp1$residuals
tempvc = varcov.gr(centerx(x), tempw$tmp1$weights, tempw$tmp1$residuals)
vcw = as.matrix(tempvc$varcov)
tempgr = NULL
temphbr = NULL
templs = NULL
if (any("WIL" == est) & any("GR" == est)) {
tempgr = wwest(x, y, "GR", print.tbl = F)
diff = tempw$tmp1$coef - tempgr$tmp1$coef
}
if (any("WIL" == est) & any("HBR" == est)) {
temphbr = wwest(x, y, "HBR", print.tbl = F)
diff = tempw$tmp1$coef - temphbr$tmp1$coef
}
if (any("GR" == est) & any("HBR" == est)) {
tempgr = wwest(x, y, "GR", print.tbl = F)
temphbr = wwest(x, y, "HBR", print.tbl = F)
diff = tempgr$tmp1$coef - temphbr$tmp1$coef
}
if (any("WIL" == est) & any("LS" == est)) {
templs = lsfit(x, y)
diff = tempw$tmp1$coef - templs$coef
}
if (any("GR" == est) & any("LS" == est)) {
tempgr = wwest(x, y, "GR", print.tbl = F)
templs = lsfit(x, y)
diff = tempgr$tmp1$coef - templs$coef
}
if (any("HBR" == est) & any("LS" == est)) {
temphbr = wwest(x, y, "HBR", print.tbl = F)
templs = lsfit(x, y)
diff = temphbr$tmp1$coef - templs$coef
}
tdbeta = t(cbind(diff)) %*% solve(vcw) %*% cbind(diff)
bmtd = (4 * (p + 1)^2)/n
xmat = cbind(rep(1, n), x)
diffc = xmat %*% diff
diffvc = xmat %*% vcw %*% t(xmat)
cfit = diffc/(sqrt(diag(diffvc)))
bmcf = 2 * sqrt((p + 1)/n)
se = sqrt(diag(vcw))
list(tdbeta = c(tdbeta), bmtd = bmtd, cfit = c(cfit), bmcf = bmcf,
est = est, betaw = tempw$tmp1$coef, betagr = tempgr$tmp1$coef,
betahbr = temphbr$tmp1$coef, betals = templs$coef, vcw = vcw,
tau = tempvc$tau, taus = tempvc$tau1, se = se)
}
grwts <- function(xmat, robdis2 = mycov.rob(as.matrix(xmat), method = "mcd")$robdis2,
percent = 0.95, k = 2) {
xmat = as.matrix(xmat)
n = dim(xmat)[1]
p = dim(xmat)[2]
cut = qchisq(percent, p)
h = pmin(1, ((cut/robdis2)^(k/2)))
tmp = pairup(h)
ans = tmp[, 1] * tmp[, 2]
ans
}
hbrwts <- function(xmat, y, robdis2 = mycov.rob(as.matrix(xmat), method = "mcd")$robdis2,
percent = 0.95, intest = myltsreg(xmat, y)$coef) {
xmat = as.matrix(xmat)
y = as.matrix(y)
n = dim(xmat)[1]
p = dim(xmat)[2]
cut = qchisq(percent, p)
resids = y - intest[1] - xmat %*% as.matrix(intest[2:(p +
1)])
sigma = mad(resids)
m = psi(cut/robdis2)
a = resids/(sigma * m)
c = (median(a) + 3 * mad(a))^2
h = sqrt(c)/a
tmp = pairup(h)
ans = psi(abs(tmp[, 1] * tmp[, 2]))
ans
}
mycov.rob <- function(x, cor = FALSE, quantile.used = floor((n + p + 1)/2),
method = c("mve", "mcd", "classical"), nsamp = "best") {
if (v1.9.0()) {
if (!any(search() == "package:MASS"))
stop("mycov.rob: The 'MASS' package is not loaded.")
PACK = "MASS"
}
else {
if (!any(search() == "package:lqs"))
stop("mycov.rob: The 'lqs' package is not loaded.")
PACK = "lqs"
}
method <- match.arg(method)
x <- as.matrix(x)
xcopy = x
if (any(is.na(x)) || any(is.infinite(x)))
stop("mycov.rob: missing or infinite values are not allowed")
n <- nrow(x)
p <- ncol(x)
if (n < p + 1)
stop(paste("mycov.rob: At least", p + 1, "cases are needed"))
if (method == "classical") {
center = colMeans(x)
cov = var(x)
robdis2 = mymahalanobis(xcopy, center, cov)
ans <- list(center = colMeans(x), cov = var(x), robdis2 = robdis2)
}
else {
if (quantile.used < p + 1)
stop(paste("mycov.rob: quantile must be at least",
p + 1))
divisor <- apply(x, 2, IQR)
if (any(divisor == 0))
stop("mycov.rob: at least one column has IQR 0")
x <- x/rep(divisor, rep(n, p))
qn <- quantile.used
ps <- p + 1
nexact <- choose(n, ps)
if (is.character(nsamp) && nsamp == "best")
nsamp <- if (nexact < 5000)
"exact"
else "sample"
if (is.numeric(nsamp) && nsamp > nexact) {
warning(paste("only", nexact, "sets, so all sets will be tried"))
nsamp <- "exact"
}
samp <- nsamp != "exact"
if (samp) {
if (nsamp == "sample")
nsamp <- min(500 * ps, 3000)
}
else nsamp <- nexact
if (exists(".Random.seed", envir = .GlobalEnv)) {
save.seed <- .Random.seed
on.exit(assign(".Random.seed", save.seed, envir = .GlobalEnv))
}
set.seed(123)
z$sing <- paste(z$sing, "singular samples of size", ps,
"out of", nsamp)
crit <- z$crit + 2 * sum(log(divisor)) + if (method ==
"mcd")
-p * log(qn - 1)
else 0
best <- seq(n)[z$bestone != 0]
if (!length(best))
stop("mycov.rob: x is probably collinear")
means <- colMeans(x[best, , drop = FALSE])
rcov <- var(x[best, , drop = FALSE]) * (1 + 15/(n - p))^2
dist <- mymahalanobis(x, means, rcov)
cut <- qchisq(0.975, p) * quantile(dist, qn/n)/qchisq(qn/n,
p)
center = colMeans(x[dist < cut, , drop = FALSE]) * divisor
cov <- divisor * var(x[dist < cut, , drop = FALSE]) *
rep(divisor, rep(p, p))
robdis2 = mymahalanobis(xcopy, center, cov)
attr(cov, "names") <- NULL
ans <- list(center = center, cov = cov, robdis2 = robdis2,
msg = z$sing, crit = crit, best = best)
}
if (cor) {
sd <- sqrt(diag(ans$cov))
ans <- c(ans, list(cor = (ans$cov/sd)/rep(sd, rep(p,
p))))
}
ans$n.obs <- n
ans
}
mylmsreg <- function(xmat, y) {
if (v1.9.0()) {
if (!any(search() == "package:MASS"))
stop("mycov.rob: The 'MASS' package is not loaded.")
}
else {
if (!any(search() == "package:lqs"))
stop("mycov.rob: The 'lqs' package is not loaded.")
}
xmat = as.matrix(xmat)
if (exists(".Random.seed", envir = .GlobalEnv)) {
save.seed <- .Random.seed
on.exit(assign(".Random.seed", save.seed, envir = .GlobalEnv))
}
set.seed(123)
tmp = lmsreg(xmat, y, intercept = T)
ans = list(coefficients = tmp$coefficients, residuals = tmp$residuals)
ans
}
myltsreg <- function(xmat, y) {
if (v1.9.0()) {
if (!any(search() == "package:MASS"))
stop("mycov.rob: The 'MASS' package is not loaded.")
}
else {
if (!any(search() == "package:lqs"))
stop("mycov.rob: The 'lqs' package is not loaded.")
}
xmat = as.matrix(xmat)
if (exists(".Random.seed", envir = .GlobalEnv)) {
save.seed <- .Random.seed
on.exit(assign(".Random.seed", save.seed, envir = .GlobalEnv))
}
set.seed(123)
tmp = ltsreg(xmat, y, intercept = T)
ans = list(coefficients = tmp$coefficients, residuals = tmp$residuals)
ans
}
mymahalanobis <- function(x, center, cov, inverted = FALSE, tol.inv = 1e-17) {
x <- if (is.vector(x))
matrix(x, nrow = length(x))
else as.matrix(x)
x <- sweep(x, 2, center)
if (!inverted)
cov <- ginv(cov, tol = tol.inv)
retval <- rowSums((x %*% cov) * x)
names(retval) <- rownames(x)
retval
}
pairup.ww <- function(x, type = "less") {
x = as.matrix(x)
n = dim(x)[1]
i = rep(1:n, rep(n, n))
j = rep(1:n, n)
c1 = apply(x, 2, function(y) {
rep(y, rep(length(y), length(y)))
})
c2 = apply(x, 2, function(y) {
rep(y, length(y))
})
ans = cbind(c1, c2)
ans = switch(type, less = ans[(i < j), ], leq = ans[i <=
j, ], neq = ans)
ans
}
plotfitdiag <- function(result) {
n = length(result$cfit)
main1 = paste("CFITS for", result$est[1], "and", result$est[2])
main2 = paste("TDBETA:", round(result$tdbeta, 2), "Benchmark:",
round(result$bmtd, 2))
plot(c(1, n), c(min(result$cfit, -1 * result$bmcf), max(result$cfit,
result$bmcf)), type = "n", main = paste(main1, "\n",
main2), xlab = "CASE", ylab = "CFIT")
points(1:n, result$cfit)
abline(h = c(-1 * result$bmcf, result$bmcf))
}
psi <- function(x) {
x[x == -Inf] = -100
x[x == Inf] = 100
ans = -1 * (x <= -1) + x * (-1 < x & x < 1) + 1 * (x >= 1)
ans
}
pwcomp <- function(y, levels, delta = 0.8, param = 2) {
p <- max(levels)
m <- pairup(1:p)
rnames <- NULL
pval <- NULL
for (i in 1:dim(m)[1]) {
a <- rep(0, p)
a[m[i, 1]] <- 1
a[m[i, 2]] <- -1
rnames[i] <- paste("G", m[i, 1], "-", "G", m[i, 2], sep = "")
pval[i] <- cellmntest(y, levels, a, delta = delta, param = param,
print.tbl = F)$pval
}
pval <- cbind(round(pval, 4))
dimnames(pval) <- list(rnames, "PVAL")
pval
}
redmod <- function(xmat, amat) {
xmat = as.matrix(xmat)
amat = rbind(amat)
q <- length(amat[, 1])
p <- length(xmat[1, ])
temp <- qr(t(amat))
if (temp$rank != q)
stop("redmod: The hypothesis matrix is not full row rank.")
else {
zed <- qr.qty(temp, t(xmat))
redmod <- rbind(zed[(q + 1):p, ])
}
t(redmod)
}
regrtest <- function(xmat, y, delta = 0.8, param = 2, print.tbl = T) {
xmat = as.matrix(xmat)
p = dim(xmat)[2]
ans = suppressWarnings(droptest(xmat, y, diag(rep(1, p)),
delta, param, print.tbl))
invisible(ans)
}
stanresid <- function(x, y, delta = 0.8, param = 2, conf = 0.95) {
xc = as.matrix(centerx(x))
n = length(y)
p = length(xc[1, ])
pp1 = p + 1
tempw = wwest(x, y, "WIL", print.tbl = F)
resid = tempw$tmp1$residuals
hc = diag(xc %*% solve(t(xc) %*% xc) %*% t(xc))
tau = wilcoxontau(resid, p, delta = 0.8, param = 2)
taus = taustar(resid, p, conf = 0.95)
deltas = sum(abs(resid))/(n - pp1)
delta = wildisp(resid)/(n - pp1)
sig = mad(resid)
k1 = (taus^2/sig^2) * (((2 * deltas)/taus) - 1)
k2 = (tau^2/sig^2) * (((2 * delta)/tau) - 1)
s1 = sig^2 * (1 - (k1/n) - k2 * hc)
s2 = s1
s2[s1 <= 0] = sig^2 * (1 - (1/n) - hc[s1 <= 0])
ind = rep(0, n)
ind[s1 <= 0] = 1
stanresid = resid/sqrt(s2)
list(stanr = stanresid, ind = ind, rawresids = resid, betaw = tempw$tmp1$coef,
tau = tau, taustar = taus)
}
studres.gr <- function(x, bmat, res, delta = 0.8, center = T) {
x = as.matrix(x)
if (center) {
x = apply(x, 2, function(x) {
x - mean(x)
})
}
bmat = as.matrix(bmat)
res = as.vector(res)
n = dim(x)[1]
p = dim(x)[2]
diag(bmat) = rep(0, n)
w = -1 * bmat
diag(w) = bmat %*% as.matrix(rep(1, n))
w = (1/n) * w
Kw = x %*% solve(t(x) %*% w %*% x) %*% t(x) %*% w
H = x %*% solve(t(x) %*% x) %*% t(x)
I = diag(n)
J = matrix(1/n, n, n)
sigma2 = (mad(res))^2
tau1 = taustar(res, p)
tau = wilcoxontau(res, p, delta)
delta.s = (n/(n - p - 1)) * mean(abs(res))
K3 = 2 * tau1 * delta.s - (tau1)^2
tmp = pairup(res, "neq")
xi = mean(tmp[, 1] * sign(tmp[, 1] - tmp[, 2]))
K4 = sqrt(12) * tau * xi
delta5 = mean(sign(tmp[, 1]) * sign(tmp[, 1] - tmp[, 2]))
K5 = sqrt(12) * tau * tau1 * delta5
v = sigma2 * I - K3 * J - (K4 * I - K5 * J) %*% t(Kw) + (tau^2) *
Kw %*% t(Kw)
diag(v)[diag(v) <= 0] = sigma2 * diag(I - (1/n + H))[diag(v) <=
0]
as.vector(res/sqrt(diag(v)))
}
studres.hbr <- function(x, bmat, res, delta = 0.8, center = T) {
x = as.matrix(x)
if (center) {
x = apply(x, 2, function(x) {
x - mean(x)
})
}
bmat = as.matrix(bmat)
res = as.vector(res)
n = dim(x)[1]
p = dim(x)[2]
sigma2 = (mad(res))^2
tau1 = taustar(res, p)
tau = wilcoxontau(res, p, delta)
K1 = (n/(n - p - 1)) * mean(abs(res))
K2 = 2 * mean((rank(res)/(n + 1) - 0.5) * res)
H = x %*% solve(t(x) %*% x) %*% t(x)
I = diag(n)
J = matrix(1/n, n, n)
diag(bmat) = rep(0, n)
w = -1 * bmat
diag(w) = bmat %*% as.matrix(rep(1, n))
w = (1/(sqrt(12) * tau)) * w
cmat = (1/n^2) * t(x) %*% w %*% x
cinv = solve(cmat)
u = (1/n) * (bmat - diag(c(bmat %*% cbind(rep(1, n))))) %*%
x
u = u * (1 - 2 * rank(res)/n)
vmat = var(u)
v = sigma2 * I + tau1^2 * J + (1/4) * x %*% ((1/n^2) * cinv) %*%
vmat %*% ((1/n^2) * cinv) %*% t(x) - 2 * tau1 * K1 *
J - sqrt(12) * tau * K2 * (w %*% x %*% ((1/n^2) * cinv) %*%
t(x) + x %*% ((1/n^2) * cinv) %*% t(x) %*% w)
diag(v)[diag(v) <= 0] = sigma2 * diag(I - (1/n + H))[diag(v) <=
0]
as.vector(res/sqrt(diag(v)))
}
taustar <- function(resid, p, conf = 0.95) {
n = length(resid)
zc = qnorm((1 + conf)/2)
c1 = (n/2) - ((sqrt(n) * zc)/2) - 0.5
ic1 = floor(c1)
if (ic1 < 0) {
ic1 = 0
}
z = sort(resid)
l = z[ic1 + 1]
u = z[n - ic1]
df = sqrt(n)/sqrt(n - p - 1)
taustar = df * ((sqrt(n) * (u - l))/(2 * zc))
taustar
}
theilwts <- function(xmat) {
xmat = as.matrix(xmat)
p = dim(xmat)[2]
xpairs = pairup(xmat)
xi = xpairs[, 1:p]
xj = xpairs[, (p + 1):(2 * p)]
diff = as.matrix(xi - xj)
ans = apply(diff, 1, function(y) {
sqrt(sum(y * y))
})
ans = 1/ans
ans[ans == Inf] = 0
ans
}
v1.9.0 <- function() {
major = version$major
minor = version$minor
n = as.numeric(paste(major, minor, sep = ""))
n >= 19
}
varcov.gr <- function(x, bmat, res, delta = 0.8) {
x = as.matrix(x)
xbar = as.matrix(apply(x, 2, mean))
bmat = as.matrix(bmat)
res = as.vector(res)
n = dim(x)[1]
p = dim(x)[2]
diag(bmat) = rep(0, n)
w = -1 * bmat
diag(w) = bmat %*% as.matrix(rep(1, n))
w = (1/n) * w
cmat = (1/n) * t(x) %*% w %*% x
cinv = ginv(cmat)
vmat = (1/n) * t(x) %*% w %*% w %*% x
tau = wilcoxontau(res, p, delta)
tau1 = taustar(res, p)
varcov22 = (tau^2/n) * cinv %*% vmat %*% cinv
varcov12 = -1 * (t(xbar)) %*% varcov22
varcov11 = (tau1^2/n) + (t(xbar)) %*% varcov22 %*% xbar
varcov = cbind(rbind(varcov11, t(varcov12)), rbind(varcov12,
varcov22))
attr(varcov, "names") = NULL
ans = list(varcov = varcov, tau1 = tau1, tau = tau, wmat = w,
cmat = cmat, vmat = vmat)
ans
}
varcov.hbr <- function(x, bmat, res, delta = 0.8) {
x = as.matrix(x)
xbar = as.matrix(apply(x, 2, mean))
bmat = as.matrix(bmat)
res = as.vector(res)
n = dim(x)[1]
p = dim(x)[2]
tau = wilcoxontau(res, p, delta)
tau1 = taustar(res, p)
diag(bmat) = rep(0, n)
w = -1 * bmat
diag(w) = bmat %*% as.matrix(rep(1, n))
w = (1/(sqrt(12) * tau)) * w
cmat = (1/n^2) * t(x) %*% w %*% x
cinv = solve(cmat)
u = (1/n) * (bmat - diag(c(bmat %*% cbind(rep(1, n))))) %*%
x
u = u * (1 - 2 * rank(res)/n)
vmat = var(u)
varcov22 = (1/(4 * n)) * cinv %*% vmat %*% cinv
varcov12 = -1 * (t(xbar)) %*% varcov22
varcov11 = (tau1^2/n) + (t(xbar)) %*% varcov22 %*% xbar
varcov = cbind(rbind(varcov11, t(varcov12)), rbind(varcov12,
varcov22))
attr(varcov, "names") = NULL
ans = list(varcov = varcov, tau1 = tau1, tau = tau, wmat = w,
cmat = cmat, vmat = vmat)
ans
}
wald <- function(est, varcov, amat, true, n) {
true = as.matrix(true)
est = as.matrix(est)
amat = as.matrix(amat)
p = dim(est)[1] - 1
q = dim(amat)[1]
temp1 = as.matrix(amat %*% est - true)
temp2 = as.matrix(amat %*% varcov %*% t(amat))
T2 = t(temp1) %*% solve(temp2) %*% temp1
T2 = T2/q
pvalue = 1 - pf(T2, q, n - p - 1)
c(T2, pvalue)
}
wilcoxonpseudo <- function(x, y, delta = 0.8, param = 2) {
x = as.matrix(x)
n = length(x[, 1])
p = length(x[1, ])
one = matrix(rep(1, n), ncol = 1)
x = x - (one %*% t(one)/n) %*% x
tempw = wwest(x, y, "WIL")
residw = tempw$tmp1$residuals
fitw = y - residw
arr = order(residw)
jr = rep(0, n)
for (i in 1:n) {
jr[arr[i]] = i
}
sc = sqrt(12) * ((jr/(n + 1)) - 0.5)
zeta = sqrt((n - p - 1)/sum(sc^2))
tau = wilcoxontau(residw, p, delta, param)
wilcoxonpseudo = fitw + tau * zeta * sc
wilcoxonpseudo
}
wilcoxontau.ww <- function(resd, p, delta = if ((length(resd)/p) > 5) 0.8 else 0.95,
param = 2) {
eps <- 1e-06
n <- length(resd)
temp <- pairup(resd, type="less")
dresd <- sort(abs(temp[, 1] - temp[, 2]))
dresd = dresd[(p + 1):choose(n, 2)]
tdeltan <- quantile(dresd, delta)/sqrt(n)
w <- rep(0, length(dresd))
w[dresd <= tdeltan] <- 1
cn <- 2/(n * (n - 1))
scores = sqrt(12) * ((1:n)/(n + 1) - 0.5)
mn = mean(scores)
con = sqrt(sum((scores - mn)^2)/(n + 1))
scores = (scores - mn)/con
dn = scores[n] - scores[1]
wilcoxontau <- sqrt(n/(n - p - 1)) * ((2 * tdeltan)/(dn *
sum(w) * cn))
w <- rep(0, n)
stan <- (resd - median(resd))/mad(resd)
w[abs(stan) < param] <- 1
hubcor <- sum(w)/n
if (hubcor < eps) {
hubcor <- eps
}
fincor <- 1 + (((p + 1)/n) * ((1 - hubcor)/hubcor))
wilcoxontau <- fincor * wilcoxontau
names(wilcoxontau) <- NULL
wilcoxontau
}
wildisp <- function(resid) {
n = length(resid)
sresid = sort(resid)
scores = sqrt(12) * ((1:n)/(n + 1) - 0.5)
mn = mean(scores)
con = sqrt(sum((scores - mn)^2)/(n + 1))
scores = (scores - mn)/con
sum(scores * sresid)
}
wilwts <- function(xmat) {
xmat = as.matrix(xmat)
n = dim(xmat)[1]
ans = rep(1, n * (n - 1)/2)
ans
}
wts <- function(xmat, y, type = "WIL", percent = 0.95, k = 2, robdis2 = if (type !=
"WIL") mycov.rob(as.matrix(xmat), method = "mcd")$robdis2 else NULL,
intest = if (type == "HBR" | type == "BL") myltsreg(xmat,
y)$coef else NULL) {
xmat = as.matrix(xmat)
y = as.matrix(y)
switch(type, WIL = wilwts(xmat), THEIL = theilwts(xmat),
GR = grwts(xmat, robdis2, percent, k), HBR = hbrwts(xmat,
y, robdis2, percent, intest), BL = blwts(xmat, y,
robdis2, percent, k, intest), stop("wts: TYPE should be WIL, THEIL, GR, HBR or BL"))
}
wwest <- function(x, y, bij = "WIL", center = F, print.tbl = T) {
if (is.character(bij)) {
type = bij
bij = switch(bij, WIL = wilwts(x), THEIL = theilwts(x),
GR = grwts(x), HBR = hbrwts(x, y), BL = blwts(x,
y), stop("wwest: The weight type should be WIL, THEIL, GR, HBR, or BL"))
}
else {
type = "GR"
}
tmp1 = wwfit(x, y, bij, center)
n = length(y)
p = length(tmp1$coef) - 1
ans = cbind(tmp1$coef)
tmp2 = switch(type, WIL = varcov.gr(x, tmp1$weights, tmp1$residuals),
THEIL = varcov.gr(x, tmp1$weights, tmp1$residuals), GR = varcov.gr(x,
tmp1$weights, tmp1$residuals), HBR = varcov.hbr(x,
tmp1$weights, tmp1$residuals), BL = varcov.hbr(x,
tmp1$weights, tmp1$residuals))
bb <- diag(tmp2$varcov)
bb[bb < 0] <- 0
ans = cbind(ans, sqrt(bb))
ans = cbind(ans, ans[, 1]/ans[, 2])
ans = cbind(ans, 2 * pt(abs(ans[, 3]), n - p - 1, lower.tail = FALSE))
ans = round(ans, 4)
dimnames(ans) = list(paste("BETA", 0:p, sep = ""), c("EST",
"SE", "TVAL", "PVAL"))
if (print.tbl) {
tmp3 = wald(tmp1$coef, tmp2$varcov, amat = cbind(rep(0,
p), diag(p)), true = rep(0, p), n = n)
BETA = ""
for (i in 1:p) {
BETA = paste(BETA, "BETA", i, "=", sep = "")
}
cat("\n")
cat(paste("Wald Test of H0: ", BETA, "0\n", sep = ""))
cat(paste("TS:", round(tmp3[1], 4), "PVAL:", round(tmp3[2],
4), "\n"))
cat("\n")
if (type == "WIL") {
tmp4 = regrtest(x, y, print.tbl = F)
cat(paste("Drop Test of H0: ", BETA, "0\n", sep = ""))
cat(paste("TS:", round(tmp4$fr, 4), "PVAL:", round(tmp4$pval,
4), "\n"))
cat("\n")
}
prmatrix(ans, na.print = "")
repeat {
cat("\n")
cat("Would you like to see residual plots (y/n)?",
"\n")
yn = as.character(readline())
if (yn == "y" | yn == "Y" | yn == "yes") {
studres = switch(type, WIL = studres.gr(x, tmp1$weights,
tmp1$residuals), THEIL = studres.gr(x, tmp1$weights,
tmp1$residuals), GR = studres.gr(x, tmp1$weights,
tmp1$residuals), HBR = studres.hbr(x, tmp1$weights,
tmp1$residuals), BL = studres.hbr(x, tmp1$weights,
tmp1$residuals))
yhat = y - tmp1$residuals
par(mfrow = c(2, 2))
plot(yhat, tmp1$residuals, xlab = "Fit", ylab = "Residual",
main = "Residuals vs. Fits")
hist(tmp1$residuals, freq = FALSE, main = "Histogram of Residuals",
xlab = "Residual")
plot(studres, xlab = "Case", ylab = "Studentized Residual",
main = "Case Plot of\nStudentized Residuals")
abline(h = c(-2, 2))
qqnorm(tmp1$residuals, main = "Normal Q-Q Plot of Residuals")
qqline(tmp1$residuals)
break
}
if (yn == "n" | yn == "N" | yn == "no")
break
}
}
invisible(list(tmp1 = tmp1, tmp2 = tmp2, ans = ans))
}
wwfit <- function(x, y, bij = wilwts(as.matrix(x)), center = F) {
x = as.matrix(x)
n = dim(x)[1]
p = dim(x)[2]
if (center) {
xbar = apply(x, 2, mean)
x = apply(x, 2, function(x) {
x - mean(x)
})
}
ypairs = pairup.ww(y)
yi = ypairs[, 1]
yj = ypairs[, 2]
xpairs = pairup.ww(x)
xi = xpairs[, 1:p]
xj = xpairs[, (p + 1):(2 * p)]
newy = bij * (yi - yj)
newx = bij * (xi - xj)
if (((n * (n - 1)/2) < 5000) & (p < 20))
tmp = rq.fit.br(newx, newy, tau = 0.5, ci = F)
else tmp = rq.fit.fnb(cbind(newx), cbind(newy), tau = 0.5)
est = tmp$coefficients
int = median(y - (x %*% as.matrix(est)))
resid = as.vector(y - int - (x %*% as.matrix(est)))
if (center) {
int = int - (t(as.matrix(est)) %*% as.matrix(xbar))
}
wts = matrix(0, n, n)
index = pairup(1:n)
wts[index] = bij
wts[index[, 2:1]] = bij
ans = list(coefficients = c(int, est), residuals = resid,
weights = wts)
ans
} |
mestimator_mean_cov <- function(x, tol=1e-6, ...) {
UseMethod("mestimator_mean_cov")
}
mestimator_mean_cov.default <- function(x, ...) {
stop("No implementation for object of provided class. Please supply a data matrix of observations.")
}
mestimator_mean_cov.data.frame <- function(x, ...) {
mestimator_mean_cov(as.matrix(x), ...)
}
mestimator_mean_cov.matrix <- function(x, powerfct, normalization, maxiter=1e4, tol=1e-6, ...) {
if (tol <= 0 || maxiter <= 0) {
stop("Nonpositive arguments maxiter or tol.")
}
if (any(is.na(x))) {
return(mestimator_mean_cov.naBlocks(naBlocks(x), powerfct, normalization, maxiter, tol, ...))
}
x_nonCentered <- x
centerAndKeepNonzeroObs <- function(mu) {
x <- sweep(x_nonCentered, 2, mu)
zeroObservation <- rowSums(x) == 0
if (any(zeroObservation)) {
x <- x[!zeroObservation,, drop=FALSE]
message("Remove observation at center")
}
return(x)
}
i <- 0
dist <- 2*tol
n <- nrow(x_nonCentered)
p <- ncol(x_nonCentered)
mu <- numeric(p)
S0 <- diag(p)
while (i < maxiter && dist > tol) {
x <- centerAndKeepNonzeroObs(mu)
n <- nrow(x)
xi <- rowSums(x * t(solve(S0, t(x))))
try(w <- powerfct(xi, p = p))
S <- (crossprod(x, w$w*x))/n
mu2 <- colMeans(sweep(x, 1, w$v, "*"))
dist <- max(norm(S-S0, "M"), max(abs(mu2)))
S0 <- S
mu <- mu+mu2
i <- i+1
}
if (i >= maxiter) {
warning(paste("No convergence in", i, "steps."))
}
shape <- normalization(S0)
res <- list(S=shape$S, scale=shape$scale, mu=mu, alpha=NULL, iterations=i, naBlocks=NULL)
class(res) <- "shapeNA"
return(res)
}
mestimator_mean_cov.naBlocks <- function(x, powerfct, normalization, maxiter, tol, ...) {
if (tol <= 0 || maxiter <= 0) {
stop("Nonpositive arguments maxiter or tol.")
}
y_nonCentered <- x$data
centerAndKeepNonzeroObs <- function(mu) {
x <- sweep(y_nonCentered, 2, mu)
zeroObservation <- rowSums(x, na.rm = TRUE) == 0
if (any(zeroObservation)) {
x <- x[!zeroObservation,, drop=FALSE]
message("Remove observation at center")
}
return(x)
}
i <- 0
dist <- 2*tol
n <- nrow(y_nonCentered)
p <- ncol(y_nonCentered)
covAndMeanOfSubset <- function(x, S, varCount, n) {
Sinv <- solve(S)
if (!isSymmetric(Sinv)) {
Sinv <- (Sinv + t(Sinv))/2
}
rootS <- matroot(Sinv)
xi <- rowSums((x%*%Sinv)* x)
try(
w <- powerfct(xi, p, varCount)
)
a <- (crossprod(x, w$w*x))
b <- sweep(x%*%rootS, 1, w$v, FUN = "*")
return(list(S=Sinv %*% a %*% Sinv - n * Sinv, mu=colSums(b)))
}
S0 <- diag(p)
blockIdx <- x$N
blockPattern <- x$P
mu <- numeric(p)
while (i < maxiter && dist > tol) {
y <- centerAndKeepNonzeroObs(mu)
n <- nrow(y)
rows <- 1:blockIdx[1]
tryCatch(
a <- covAndMeanOfSubset(
y[rows, , drop = FALSE], S0, n=length(rows), varCount=p)
, error = function(e) {
message(paste("Iteration", i))
message(e)
stop("Matrix not positive definite")
}
)
a_Sigma <- a$S
a_mu <- a$mu
for (j in 2:length(blockIdx)) {
rows <- (blockIdx[j-1]+1):blockIdx[j]
cols <- asBinaryVector(blockPattern[j], p)
tryCatch(
a <- covAndMeanOfSubset(
y[rows, cols, drop = FALSE], S0[cols, cols], n=length(rows), varCount=sum(cols))
, error = function(e) {
message(paste("Iteration", i, "block", j))
message(e)
stop("Matrix not positive definite")
}
)
a_Sigma[cols, cols] <- a_Sigma[cols, cols] + a$S
a_mu[cols] <- a_mu[cols] + a$mu
}
a_Sigma <- S0 %*% (a_Sigma/n) %*% S0
a_mu <- (a_mu %*% matroot(S0))/n
dist <- max(norm(a_Sigma, "M"), max(abs(a_mu)))
S0 <- S0 + a_Sigma
mu <- mu + a_mu
i <- i+1
}
if (i >= maxiter) {
warning(paste("No convergence in", i, "steps."))
}
ogOrder <- order(x$permutation)
S0 <- S0[ogOrder, ogOrder]
mu <- mu[ogOrder]
shape <- normalization(S0)
res <- list(S=shape$S, scale=shape$scale, mu=mu, alpha=NULL, iterations=i, naBlocks=x)
class(res) <- "shapeNA"
return(res)
} |
NULL
setClass(
Class="MixmodXmlCheck",
representation=representation(
xmlFile = "character",
xmlType = "character"
)
)
setMethod(
f="initialize",
signature=c("MixmodXmlCheck"),
definition=function(.Object, xmlFile){
.Object@xmlFile <- xmlFile
.Object@xmlType <- "unknown"
return(.Object)
}
)
mixmodXmlCheck <- function(...){
return(new("MixmodXmlCheck", ...))
}
mixmodXmlLoad <- function(xmlFile, numFormat="humanReadable"){
xmlIn <- mixmodXmlInput(xmlFile, numFormat=numFormat, conversionOnly=TRUE)
xem <- new("MixmodXmlCheck", xmlFile)
.Call("xMain", xem, PACKAGE="Rmixmod")
if(xem@xmlType == "clustering"){
return(mixmodCluster(xmlIn=xmlIn))
}
if(xem@xmlType == "learn"){
return(mixmodLearn(xmlIn=xmlIn))
}
if(xem@xmlType == "predict"){
return(mixmodPredict(xmlIn=xmlIn))
}
} |
range_prop <- function(x, name) {
if (is.null(x)) return(list())
if (is.character(x)) {
return(named_list(name, x))
}
assert_that(is.numeric(x), length(x) <= 2)
n_miss <- sum(is.na(x))
if (n_miss == 0) {
named_list(name, x)
} else if (n_miss == 1) {
if (is.na(x[1])) {
named_list(paste0(name, "Max"), x[2])
} else {
named_list(paste0(name, "Min"), x[1])
}
} else if (n_miss == 2) {
list()
}
}
named_list <- function(names, ...) {
stats::setNames(list(...), names)
}
propname_to_scale <- function(prop) {
simplify <- c(
"x2" = "x",
"width" = "x",
"y2" = "y",
"height" = "y",
"fillOpacity" = "opacity",
"strokeOpacity" = "opacity",
"innerRadius" = "radius",
"outerRadius" = "radius",
"startAngle" = "angle",
"endAngle" = "angle"
)
matches <- match(prop, names(simplify))
prop[!is.na(matches)] <- simplify[prop[!is.na(matches)]]
prop
}
scaletype_to_vega_scaletype <- function(type) {
unname(c(
"numeric" = "quantitative",
"ordinal" = "ordinal",
"nominal" = "ordinal",
"logical" = "ordinal",
"datetime" = "time"
)[type])
} |
fitted.GNARfit <- function(object,...){
stopifnot(is.GNARfit(object))
dotarg <- list(...)
if(length(dotarg)!=0){
if(!is.null(names(dotarg))){
warning("... not used here, input(s) ", paste(names(dotarg), collapse=", "), " ignored")
}else{
warning("... not used here, input(s) ", paste(dotarg, collapse=", "), " ignored")
}
}
return(residToMat(object, nnodes=object$frbic$nnodes)$fit)
} |
summary.fechner <-
function(object, level = 2, ...){
if (mode(level) != "numeric")
stop("level must be number")
if (!is.finite(level))
stop("level must be finite, i.e., not be NA, NaN, Inf, or -Inf")
if (as.integer(level) != level)
stop("level must be integer")
if (level < 2)
stop("level must be greater than or equal to 2")
if (attr(object, which = "computation", exact = TRUE) == "short"){
G <- object$overall.Fechnerian.distances
S <- object$S.index
number.links <- object$graph.lengths.of.geodesic.loops
} else
if (attr(object, which = "computation", exact = TRUE) == "long"){
G <- object$overall.Fechnerian.distances.1
S <- object$S.index
number.links <- object$graph.lengths.of.geodesic.loops.1
} else
stop("object attribute computation must have value \"short\" or \"long\"")
pairs <- (number.links[upper.tri(number.links)] >= level)
if (!any(pairs))
stop(paste("summary is not possible: there are no (off-diagonal) pairs of stimuli with geodesic loops containing at least ",
level, " links", sep = ""))
G.level <- G[upper.tri(G)][pairs]
S.level <- S[upper.tri(S)][pairs]
correlation <- cor(S.level, G.level)
if (is.na(correlation))
correlation <- "Pearson's correlation coefficient is not defined"
C.index <- ((2 * sum((S.level - G.level)^2)) / (sum((S.level)^2) + sum((G.level)^2)))
stimuli.pairs <- paste(rownames(S)[row(S)[upper.tri(S)][pairs]], ".", colnames(S)[col(S)[upper.tri(S)][pairs]], sep = "")
comparison.pairs <- data.frame(stimuli.pairs = stimuli.pairs, S.index = S.level, Fechnerian.distance.G = G.level, stringsAsFactors = FALSE)
results <- list(pairs.used.for.comparison = comparison.pairs,
Pearson.correlation = correlation,
C.index = C.index,
comparison.level = level)
class(results) <- "summary.fechner"
return(results)
} |
"df2" |
plot.ensembleBMAgamma <-
function(x, ensembleData, dates=NULL, ask=TRUE, ...)
{
par(ask = ask)
powfun <- function(x,power) x^power
powinv <- function(x,power) x^(1/power)
weps <- 1.e-4
matchITandFH(x,ensembleData)
exchangeable <- x$exchangeable
ensembleData <- ensembleData[,matchEnsembleMembers(x,ensembleData)]
M <- !dataNA(ensembleData)
if (!all(M)) ensembleData <- ensembleData[M,]
fitDates <- modelDates(x)
M <- matchDates( fitDates, ensembleValidDates(ensembleData), dates)
if (!all(M$ens)) ensembleData <- ensembleData[M$ens,]
if (!all(M$fit)) x <- x[fitDates[M$fit]]
dates <- modelDates(x)
Dates <- ensembleValidDates(ensembleData)
obs <- dataVerifObs(ensembleData)
nObs <- length(obs)
if (nObs == 0) obs <- rep(NA,nrow(ensembleData))
nForecasts <- ensembleSize(ensembleData)
ensembleData <- ensembleForecasts(ensembleData)
obs <- powfun( obs, power = x$power)
l <- 0
for (d in dates) {
l <- l + 1
WEIGHTS <- x$weights[,d]
if (all(Wmiss <- is.na(WEIGHTS))) next
I <- which(as.logical(match(Dates, d, nomatch = 0)))
for (i in I) {
f <- ensembleData[i,]
M <- is.na(f) | Wmiss
VAR <- (x$varCoefs[1,d] + x$varCoefs[2,d]*f)^2
fTrans <- sapply(f, powfun, power = x$power)
MEAN <- apply(rbind(1, fTrans) * x$biasCoefs[,d], 2, sum)
W <- WEIGHTS
if (any(M)) {
W <- W + weps
W <- W[!M]/sum(W[!M])
}
plotBMAgamma( WEIGHTS = W, MEAN = MEAN[!M], VAR = VAR[!M],
obs = obs[i], exchangeable = exchangeable, power = x$power)
}
}
invisible()
} |
context("Cashflows")
test_that("Cashflow for a bullet loan", {
l <- loan(rate = 0.1, maturity = 4, amt = 1, type = "bullet", grace_int = 0, grace_amort = 0)
expect_that(l$cf, equals(c(0.1, 0.1, 0.1, 1.1)))
})
test_that("Cashflow for a german loan", {
l <- loan(rate = 0.1, maturity = 4, amt = 1, type = "german", grace_int = 0, grace_amort = 0)
expect_that(l$cf, equals(0.25 + c(1, 0.75, 0.5, 0.25) * 0.1))
})
test_that("Cashflow for a french loan", {
l <- loan(rate = 0.1, maturity = 4, amt = 1, type = "french", grace_int = 0, grace_amort = 0)
pmt <- 1 / sum (1 / (rep_len(1 + 0.1, 4) ^ (1:4)))
expect_that(l$cf, equals(rep_len(pmt, 4)))
}) |
make_activity_fn <- function(..., detector_daily_duration=24){
if (!requireNamespace("activity", quietly = TRUE)){
stop("Package 'activity' not installed!")
}
call <- sys.call(sys.parent())
detector_daily_duration <- eval(substitute(call)$detector_daily_duration,
envir=parent.frame(n=1))
call$detector_daily_duration <- NULL
args <- as.list(match.call(activity::fitact, call=call, expand.dots=TRUE))
args[[1]] <- NULL
args$reps <- 1
args$show <- FALSE
for(i in seq(1, length(args))){
args[[i]] <- eval(args[[i]], envir=parent.frame(n=1))
}
function(){
unname(do.call(activity::fitact, args)@act[3])/(detector_daily_duration/24)
}
} |
get_bearer <- function() {
bearer_token <- Sys.getenv('TWITTER_BEARER')
if (identical(bearer_token, "")) {
stop("Please set envvar TWITTER_BEARER or supply your bearer token in every call. See ?get_bearer for more information.", call. = FALSE)
}
return(bearer_token)
} |
images2matrix <- function(
imgs,
mask = NULL){
if (!is.null(mask)) {
mask = img_data(mask)
check_mask_fail(mask, allow.array = TRUE)
}
imgs <- lapply(imgs, img_data)
if (!same_dims(imgs)) {
stop("Not all images have the same dimensions!")
}
if (!is.null(mask)) {
if (!same_dims(imgs[[1]], mask)) {
stop("Mask is not the same dimensions as the images!")
}
}
if (!is.null(mask)) {
mask = which(mask %in% 1)
imgs = lapply(imgs, function(x){
x[mask]
})
}
imgs <- do.call(cbind, imgs)
return(imgs)
} |
done <- function(msg){
packageStartupMessage(crayon::green(cli::symbol$tick), " ", msg)
}
not_done <- function(msg){
packageStartupMessage(crayon::red(cli::symbol$cross), " ", msg)
}
congrats <- function(msg){
packageStartupMessage(crayon::yellow(cli::symbol$star), " ", msg)
}
info <- function(msg){
packageStartupMessage(crayon::blue(cli::symbol$bullet), " ", msg)
}
red_message <- function(msg) {
message(crayon::red(cli::symbol$cross), " ", msg)
}
green_message <- function(msg){
message(crayon::green(cli::symbol$tick), " ", msg)
} |
setGeneric( "is_extension", function(object){
standardGeneric("is_extension")
} )
setMethod( "is_extension", "FieldDescriptor", function(object){
.Call( "FieldDescriptor__is_extension", object@pointer, PACKAGE = "RProtoBuf" )
})
setMethod( "number", "FieldDescriptor", function(object){
.Call( "FieldDescriptor__number", object@pointer, PACKAGE = "RProtoBuf" )
} )
TYPE_DOUBLE <- 1L
TYPE_FLOAT <- 2L
TYPE_INT64 <- 3L
TYPE_UINT64 <- 4L
TYPE_INT32 <- 5L
TYPE_FIXED64 <- 6L
TYPE_FIXED32 <- 7L
TYPE_BOOL <- 8L
TYPE_STRING <- 9L
TYPE_GROUP <- 10L
TYPE_MESSAGE <- 11L
TYPE_BYTES <- 12L
TYPE_UINT32 <- 13L
TYPE_ENUM <- 14L
TYPE_SFIXED32 <- 15L
TYPE_SFIXED64 <- 16L
TYPE_SINT32 <- 17L
TYPE_SINT64 <- 18L
.TYPES <- sapply(ls( pattern="^TYPE_" ), function(x) get(x))
setGeneric( "type", function(object, as.string = FALSE){
standardGeneric( "type" )
} )
setMethod( "type", "FieldDescriptor", function(object, as.string = FALSE){
type <- .Call( "FieldDescriptor__type", object@pointer, PACKAGE = "RProtoBuf" )
if( as.string ) {
names(which(.TYPES == type))
} else {
type
}
} )
CPPTYPE_INT32 <- 1L
CPPTYPE_INT64 <- 2L
CPPTYPE_UINT32 <- 3L
CPPTYPE_UINT64 <- 4L
CPPTYPE_DOUBLE <- 5L
CPPTYPE_FLOAT <- 6L
CPPTYPE_BOOL <- 7L
CPPTYPE_ENUM <- 8L
CPPTYPE_STRING <- 9L
CPPTYPE_MESSAGE <- 10L
.CPPTYPES <- sapply(ls( pattern="^CPPTYPE_" ), function(x) get(x))
setGeneric( "cpp_type", function(object, as.string = FALSE ){
standardGeneric( "cpp_type" )
} )
setMethod( "cpp_type", "FieldDescriptor", function(object, as.string = FALSE){
cpptype <- .Call( "FieldDescriptor__cpp_type", object@pointer, PACKAGE = "RProtoBuf" )
if( as.string ) {
names(which(.CPPTYPES == cpptype))
} else {
cpptype
}
} )
LABEL_OPTIONAL <- 1L
LABEL_REQUIRED <- 2L
LABEL_REPEATED <- 3L
.LABELS <- sapply(ls( pattern="^LABEL_" ), function(x) get(x))
setGeneric( "label", function(object, as.string = FALSE ){
standardGeneric( "label" )
} )
setMethod( "label", "FieldDescriptor", function(object, as.string = FALSE){
lab <- .Call( "FieldDescriptor__label", object@pointer, PACKAGE = "RProtoBuf" )
if( as.string ) {
names(which(.LABELS == lab))
} else {
lab
}
} )
setGeneric( "is_repeated", function(object ){
standardGeneric( "is_repeated" )
} )
setMethod( "is_repeated", "FieldDescriptor", function(object){
.Call( "FieldDescriptor__is_repeated", object@pointer, PACKAGE = "RProtoBuf" )
} )
setGeneric( "is_optional", function(object){
standardGeneric( "is_optional" )
} )
setMethod( "is_optional", "FieldDescriptor", function(object){
.Call( "FieldDescriptor__is_optional", object@pointer, PACKAGE = "RProtoBuf" )
} )
setGeneric( "is_required", function(object ){
standardGeneric( "is_required" )
} )
setMethod( "is_required", "FieldDescriptor", function(object){
.Call( "FieldDescriptor__is_required", object@pointer, PACKAGE = "RProtoBuf" )
} )
setGeneric( "has_default_value", function(object ){
standardGeneric( "has_default_value" )
} )
setMethod( "has_default_value", "FieldDescriptor", function(object){
.Call( "FieldDescriptor__has_default_value", object@pointer, PACKAGE = "RProtoBuf" )
} )
setGeneric( "default_value", function(object ){
standardGeneric( "default_value" )
} )
setMethod( "default_value", "FieldDescriptor", function(object){
.Call( "FieldDescriptor__default_value", object@pointer, PACKAGE = "RProtoBuf" )
} )
setGeneric( "message_type", function(object ){
standardGeneric( "message_type" )
} )
setMethod( "message_type", "FieldDescriptor", function(object){
.Call( "FieldDescriptor__message_type", object@pointer, PACKAGE = "RProtoBuf" )
} )
setMethod( "enum_type", c( object = "FieldDescriptor", index = "missing", name = "missing"), function(object){
.Call( "FieldDescriptor__enum_type", object@pointer, PACKAGE = "RProtoBuf" )
} ) |
context("shapes")
test_that("show_shapes works", {
x <- 1:10
expect_eqNe(show_shapes(x), x)
})
test_that("show_linetypes works", {
x <- 1:5
expect_eqNe(show_linetypes(x), x)
})
test_that("show_linetypes works with labels = FALSE", {
x <- 1:5
expect_eqNe(show_linetypes(x, labels = FALSE), x)
}) |
print.power <- function(x, digits = 3, latex.output = FALSE, template = 1, ...) {
class(x) <- paste("power", template, sep = "")
print(x, digits, latex.output, ...)
} |
varLmoments <- function (x, matrix=TRUE) {
y <- sort(x)
n <- length(y)
nn <- rep(n-1, n)
pp <- seq(0, n-1)
p1 <- pp/nn
p2 <- p1*(pp-1)/(nn-1)
p3 <- p2*(pp-2)/(nn-2)
b0 <- sum(y)/n
b1 <- sum(p1*y)/n
b2 <- sum(p2*y)/n
b3 <- sum(p3*y)/n
l1 <- b0
l2 <- 2*b1 - b0
l3 <- 6*b2 - 6*b1 + b0
l4 <- 20*b3 - 30*b2 + 12*b1 - b0
tau <- l2/l1
tau3 <- l3/l2
tau4 <- l4/l2
Y1 <- y %*% t(rep(1,n))
Y <- Y1*t(Y1)
Q <- seq(1,n) %*% t(rep(1,n))
P <- t(Q)
varb0 <- b0^2 - 1/n/(n-1) *2* sum(Y*lower.tri(Y))
W11 <- 1/n/(n-1)/(n-2)/(n-3) *2*((P-1)*(Q-3))
V11 <- W11*lower.tri(W11)*Y
varb1 <- b1^2 - sum(V11)
W10 <- 1/n/(n-1)/(n-2)*((Q-2)+(P-1))
V10 <- W10*lower.tri(W10)*Y
covb0b1 <- b0*b1-sum(V10)
W20 <- 1/n/(n-1)/(n-2)/(n-3) * ((Q-2)*(Q-3)+(P-1)*(P-2))
V20 <- W20*lower.tri(W20)*Y
covb0b2 <- b0*b2-sum(V20)
W21 <- 1/n/(n-1)/(n-2)/(n-3)/(n-4)*((P-1)*(Q-3)*(Q-4)+(P-1)*(P-2)*(Q-4))
V21 <- W21*lower.tri(W21)*Y
covb1b2 <- b1*b2-sum(V21)
W22 <- 1/n/(n-1)/(n-2)/(n-3)/(n-4)/(n-5)*2*((P-1)*(P-2)*(Q-4)*(Q-5))
V22 <- W22*lower.tri(W22)*Y
varb2 <- b2*b2-sum(V22)
W30 <- 1/n/(n-1)/(n-2)/(n-3)/(n-4) * ((Q-2)*(Q-3)*(Q-4)+(P-1)*(P-2)*(P-3))
V30 <- W30*lower.tri(W30)*Y
covb0b3 <- b0*b3-sum(V30)
W31 <- 1/n/(n-1)/(n-2)/(n-3)/(n-4)/(n-5)*((P-1)*(Q-3)*(Q-4)*(Q-5)+(P-1)*(P-2)*(P-3)*(Q-5))
V31 <- W31*lower.tri(W31)*Y
covb1b3 <- b1*b3-sum(V31)
W32 <- 1/n/(n-1)/(n-2)/(n-3)/(n-4)/(n-5)/(n-6)*((P-1)*(P-2)*(P-3)*(Q-5)*(Q-6)+(P-1)*(P-2)*(Q-4)*(Q-5)*(Q-6))
V32 <- W32*lower.tri(W32)*Y
covb2b3 <- b2*b3-sum(V32)
W33 <- 1/n/(n-1)/(n-2)/(n-3)/(n-4)/(n-5)/(n-6)/(n-7)*2*((P-1)*(P-2)*(P-3)*(Q-5)*(Q-6)*(Q-7))
V33 <- W33*lower.tri(W33)*Y
varb3 <- b3*b3-sum(V33)
if (n > 7) {
T <- matrix(c(varb0,covb0b1,covb0b2,covb0b3,
covb0b1,varb1,covb1b2,covb1b3,
covb0b2,covb1b2,varb2,covb2b3,
covb0b3,covb1b3,covb2b3,varb3),nrow=4,ncol=4,byrow=TRUE)
C <- matrix(c(1,0,0,0,
-1,2,0,0,
1,-6,6,0,
-1,12,-30,20),nrow=4,ncol=4,byrow=TRUE)
varL <- C %*% T %*% t(C)
dimnames(varL) <- list(c("l1","l2","l3","l4"),c("l1","l2","l3","l4"))
if (matrix==FALSE) {
varl1 <- varL[1,1]
varl2 <- varL[2,2]
varl3 <- varL[3,3]
varl4 <- varL[4,4]
covl1l2 <- varL[1,2]
covl2l3 <- varL[2,3]
covl2l4 <- varL[2,4]
varlcv <- tau^2*(varl1/l1^2+varl2/l2^2-2*covl1l2/l1/l2)
varlca <- tau3^2*(varl2/l2^2+varl3/l3^2-2*covl2l3/l2/l3)
varlkur <- tau4^2*(varl2/l2^2+varl4/l4^2-2*covl2l4/l2/l4)
varL <- c(varl1,varl2,varl3,varl4,varlcv,varlca,varlkur)
names(varL) <- c("var.l1","var.l2","var.l3","var.l4","var.lcv","var.lca","var.lkur")
}
}
else if (n > 5) {
T <- matrix(c(varb0,covb0b1,covb0b2,
covb0b1,varb1,covb1b2,
covb0b2,covb1b2,varb2),nrow=3,ncol=3,byrow=TRUE)
C <- matrix(c(1,0,0,
-1,2,0,
1,-6,6),nrow=3,ncol=3,byrow=TRUE)
varL <- C %*% T %*% t(C)
dimnames(varL) <- list(c("l1","l2","l3"),c("l1","l2","l3"))
if (matrix==FALSE) {
varl1 <- varL[1,1]
varl2 <- varL[2,2]
varl3 <- varL[3,3]
covl1l2 <- varL[1,2]
covl2l3 <- varL[2,3]
varlcv <- tau^2*(varl1/l1^2+varl2/l2^2-2*covl1l2/l1/l2)
varlca <- tau3^2*(varl2/l2^2+varl3/l3^2-2*covl2l3/l2/l3)
varL <- c(varl1,varl2,varl3,varlcv,varlca)
names(varL) <- c("var.l1","var.l2","var.l3","var.lcv","var.lca")
}
}
else if (n > 3) {
T <- matrix(c(varb0,covb0b1,
covb0b1,varb1),nrow=2,ncol=2,byrow=TRUE)
C <- matrix(c(1,0,
-1,2),nrow=2,ncol=2,byrow=TRUE)
varL <- C %*% T %*% t(C)
dimnames(varL) <- list(c("l1","l2"),c("l1","l2"))
if (matrix==FALSE) {
varl1 <- varL[1,1]
varl2 <- varL[2,2]
covl1l2 <- varL[1,2]
varlcv <- tau^2*(varl1/l1^2+varl2/l2^2-2*covl1l2/l1/l2)
varL <- c(varl1,varl2,varlcv)
names(varL) <- c("var.l1","var.l2","var.lcv")
}
}
else {
varL <- varb0
names(varL) <- "var.l1"
}
return(varL)
}
varLCV <- function (x) {
y <- sort(x)
n <- length(y)
nn <- rep(n-1, n)
pp <- seq(0, n-1)
p1 <- pp/nn
b0 <- sum(y)/n
b1 <- sum(p1*y)/n
l1 <- b0
l2 <- 2*b1 - b0
tau <- l2/l1
Y1 <- y %*% t(rep(1,n))
Y <- Y1*t(Y1)
Q <- seq(1,n) %*% t(rep(1,n))
P <- t(Q)
varb0 <- b0^2 - 1/n/(n-1) *2* sum(Y*lower.tri(Y))
W11 <- 1/n/(n-1)/(n-2)/(n-3) *2*((P-1)*(Q-3))
V11 <- W11*lower.tri(W11)*Y
varb1 <- b1^2 - sum(V11)
W10 <- 1/n/(n-1)/(n-2)*((Q-2)+(P-1))
V10 <- W10*lower.tri(W10)*Y
covb0b1 <- b0*b1-sum(V10)
T <- matrix(c(varb0,covb0b1,
covb0b1,varb1),nrow=2,ncol=2,byrow=TRUE)
C <- matrix(c(1,0,
-1,2),nrow=2,ncol=2,byrow=TRUE)
varL <- C %*% T %*% t(C)
varl1 <- varL[1,1]
varl2 <- varL[2,2]
covl1l2 <- varL[1,2]
varlcv <- tau^2*(varl1/l1^2+varl2/l2^2-2*covl1l2/l1/l2)
names(varlcv) <- "var.lcv"
return(varlcv)
}
varLCA <- function (x) {
y <- sort(x)
n <- length(y)
nn <- rep(n-1, n)
pp <- seq(0, n-1)
p1 <- pp/nn
p2 <- p1*(pp-1)/(nn-1)
b0 <- sum(y)/n
b1 <- sum(p1*y)/n
b2 <- sum(p2*y)/n
l1 <- b0
l2 <- 2*b1 - b0
l3 <- 6*b2 - 6*b1 + b0
tau <- l2/l1
tau3 <- l3/l2
Y1 <- y %*% t(rep(1,n))
Y <- Y1*t(Y1)
Q <- seq(1,n) %*% t(rep(1,n))
P <- t(Q)
varb0 <- b0^2 - 1/n/(n-1) *2* sum(Y*lower.tri(Y))
W11 <- 1/n/(n-1)/(n-2)/(n-3) *2*((P-1)*(Q-3))
V11 <- W11*lower.tri(W11)*Y
varb1 <- b1^2 - sum(V11)
W10 <- 1/n/(n-1)/(n-2)*((Q-2)+(P-1))
V10 <- W10*lower.tri(W10)*Y
covb0b1 <- b0*b1-sum(V10)
W20 <- 1/n/(n-1)/(n-2)/(n-3) * ((Q-2)*(Q-3)+(P-1)*(P-2))
V20 <- W20*lower.tri(W20)*Y
covb0b2 <- b0*b2-sum(V20)
W21 <- 1/n/(n-1)/(n-2)/(n-3)/(n-4)*((P-1)*(Q-3)*(Q-4)+(P-1)*(P-2)*(Q-4))
V21 <- W21*lower.tri(W21)*Y
covb1b2 <- b1*b2-sum(V21)
W22 <- 1/n/(n-1)/(n-2)/(n-3)/(n-4)/(n-5)*2*((P-1)*(P-2)*(Q-4)*(Q-5))
V22 <- W22*lower.tri(W22)*Y
varb2 <- b2*b2-sum(V22)
T <- matrix(c(varb0,covb0b1,covb0b2,
covb0b1,varb1,covb1b2,
covb0b2,covb1b2,varb2),nrow=3,ncol=3,byrow=TRUE)
C <- matrix(c(1,0,0,
-1,2,0,
1,-6,6),nrow=3,ncol=3,byrow=TRUE)
varL <- C %*% T %*% t(C)
varl2 <- varL[2,2]
varl3 <- varL[3,3]
covl2l3 <- varL[2,3]
varlca <- tau3^2*(varl2/l2^2+varl3/l3^2-2*covl2l3/l2/l3)
names(varlca) <- "var.lca"
return(varlca)
}
varLkur <- function (x) {
L <- Lmoments(x)
l2 <- L[2]
l4 <- L[5]*L[2]
tau4 <- L[5]
varL <- varLmoments(x)
varl2 <- varL[2,2]
varl4 <- varL[4,4]
covl2l4 <- varL[2,4]
varlkur <- tau4^2*(varl2/l2^2+varl4/l4^2-2*covl2l4/l2/l4)
names(varlkur) <- "var.lkur"
return(varlkur)
} |
cush00<-function(m,ordinal,shelter){
tt0<-proc.time()
freq<-tabulate(ordinal,nbins=m); n<-length(ordinal); aver<-mean(ordinal);
fc<-freq[shelter]/n
deltaest<-max(0.01,(m*fc-1)/(m-1))
esdelta<-sqrt((1-deltaest)*(1+(m-1)*deltaest)/(n*(m-1)))
varmat<-esdelta^2
wald<-deltaest/esdelta
loglik<-loglikcush00(m,ordinal,deltaest,shelter)
AICCUSH<- -2*loglik+2
BICCUSH<- -2*loglik+log(n)
llunif<- -n*log(m); csisb<-(m-aver)/(m-1);
llsb<-loglikcub00(m,freq,1,csisb)
nonzero<-which(freq!=0)
logsat<- -n*log(n)+sum((freq[nonzero])*log(freq[nonzero]))
devian<-2*(logsat-loglik)
LRT<-2*(loglik-llunif)
theorpr<-deltaest*ifelse(seq(1,m)==shelter,1,0)+(1-deltaest)/m
pearson<-((freq-n*theorpr))/sqrt(n*theorpr)
X2<-sum(pearson^2)
relares<-(freq/n-theorpr)/theorpr
diss00<-dissim(theorpr,freq/n)
FF2<-1-diss00
LL2<-1/(1+mean((freq/(n*theorpr)-1)^2))
II2<-(loglik-llunif)/(logsat-llunif)
stampa<-cbind(1:m,freq/n,theorpr,pearson,relares)
durata<-proc.time()-tt0; durata<-durata[1];
results<-list('estimates'=deltaest, 'loglik'=loglik,
'varmat'=varmat,'BIC'= BICCUSH,'time'=durata)
} |
unsys.station.test <- function(x, M=2000, sig.lev=.05, max.scale=NULL, m=NULL, B=200, eps=5, use.all=FALSE, do.parallel=0){
T <- length(x)
if(is.null(max.scale)) max.scale <- round(log(log(T, 2), 2))
if(is.null(m)) m <- round(sqrt(T))
if(do.parallel > 0){ cl <- parallel::makeCluster(do.parallel); doParallel::registerDoParallel(cl) }
`%mydo%` <- ifelse(do.parallel > 0, `%dopar%`, `%do%`)
top.cand0 <- bottom.cand0 <- NULL
y.mat <- matrix(0, ncol=max.scale, nrow=T)
for(k in 1:max.scale){
y.mat[, k] <- y <- func_coef(x, -k)^2
ref <- sort(y, decreasing=TRUE, index.return=TRUE)
top.cand0 <- c(top.cand0, setdiff(ref$ix[1:(eps + 2*2^k)], c(1:(2^k), (T-2^k+1):T))[1:eps])
bottom.cand0 <- c(bottom.cand0, setdiff(ref$ix[T:(T-eps-2*2^k+1)], c(1:(2^k), (T-2^k+1):T))[1:eps])
}
top.cand <- base::sample(top.cand0, M, replace=TRUE); bottom.cand <- base::sample(bottom.cand0, M, replace=TRUE)
fr <- funcRes(y.mat, M, m, rep(1/T, T), top.cand, bottom.cand, apply(y.mat, 2, mean))
ind <- which((!duplicated(fr$res[, 5])) & fr$res[, 5] > 0)
if(use.all) ref <- ind else{
ref <- ind[sort(fr$res[ind, 4+max.scale+1], decreasing=TRUE, index.return=TRUE)$ix[1:(10*M)]]
}
se.mat <- fr$res[ref, 1:4]
I <- length(ind); R <- length(ref)
arx <- stats::ar(x, order.max=log(T), method='yw')
coef <- arx$ar
ep <- arx$resid[!is.na(arx$resid)];
sig <- stats::mad(ep)
ep <- ep[abs(ep-stats::median(ep)) < sig*stats::qt(1-.005, 10)]
ep <- ep-mean(ep)
if(length(coef)==0) boot.x <- matrix(base::sample(ep, B*T, replace=TRUE), ncol=B) else boot.x <- funcSimX(coef, matrix(base::sample(ep, (T+length(coef))*B, replace=TRUE), ncol=B))
b <- 0
null.stat <- foreach::foreach(b=iterators::iter(1:B), .combine=rbind, .packages=c('Rcpp', 'RcppArmadillo', 'unsystation')) %mydo% {
bx <- boot.x[, b]
by.mat <- matrix(0, ncol=max.scale, nrow=T)
for(k in 1:max.scale){
by.mat[, k] <- func_coef(bx, -k)^2
}
tmp <- funcResVar(by.mat, se.mat, apply(by.mat, 2, mean))
c(tmp)
}
stat <- abs(fr$res[ref, 4+1:max.scale])/funcApplyVar(null.stat, max.scale, R)
k <- which.max(apply(stat, 1, max))
intervals <- fr$res[ref[k], 1:4]
test.stat <- max(stat[k,])
test.criterion <- stats::qnorm(1-sig.lev/2/I/max.scale)
test.res <- test.stat > test.criterion
if(do.parallel > 0) parallel::stopCluster(cl)
return(list(intervals=intervals, test.stat=test.stat, test.criterion=test.criterion, test.res=test.res))
} |
context("Load File")
library(activPAL)
test_that("file_loading", {
file_data <- activPAL:::pre.process.events.file(paste(system.file("extdata", "", package = "activPAL"),"/Test_Events.csv",sep=""))
expect_equal(nrow(file_data), 179)
expect_equal(length(which(is.na(file_data$time))), 0)
expect_equal(sum(file_data$steps), 2006)
expect_equal(sum(file_data$interval), 86400)
}) |
"psi" <-
function(flag, var1, var2, S=35, T=20, Patm=1, P=0, Pt=0, Sit=0, pHscale="T", kf="x", k1k2="x", ks="d", eos="eos80", long=1.e20, lat=1.e20){
Sit[is.na(Sit)] <- 0
Pt[is.na(Pt)] <- 0
buf <- buffer(flag=flag, var1=var1, var2=var2, S=S, T=T, Patm=Patm, P=P, Pt=Pt, Sit=Sit, pHscale=pHscale, kf=kf, k1k2=k1k2, ks=ks, eos=eos, long=long, lat=lat)
psi <- -buf$PiC/buf$PiD
out <- psi
attr(out,"unit") <- "mol CO2/mol CaCO3"
return(out)
} |
ga_unsampled <- function(accountId,
webPropertyId,
profileId,
unsampledReportId){
url <- "https://www.googleapis.com/analytics/v3/management/"
unsampled <- gar_api_generator(url,
"GET",
path_args = list(
accounts = accountId,
webproperties = webPropertyId,
profiles = profileId,
unsampledReports = unsampledReportId
),
data_parse_function = function(x) x)
unsampled()
}
ga_unsampled_list <- function(accountId,
webPropertyId,
profileId){
url <- "https://www.googleapis.com/analytics/v3/management/"
unsampled <- gar_api_generator(url,
"GET",
path_args = list(
accounts = accountId,
webproperties = webPropertyId,
profiles = profileId,
unsampledReports = ""
),
data_parse_function = parse_unsampled_list)
pages <- gar_api_page(unsampled, page_f = get_attr_nextLink)
Reduce(bind_rows, pages)
}
parse_unsampled_list <- function(x){
o <- x %>%
management_api_parsing("analytics
if(is.null(o)){
return(data.frame())
}
o
}
ga_unsampled_download <- function(reportTitle,
accountId,
webPropertyId,
profileId,
downloadFile=TRUE){
drive_scope <- "https://www.googleapis.com/auth/drive"
if (!(drive_scope %in% options()$googleAuthR.scopes.selected)) {
stop(
sprintf("The %s scope is missing. Please set option and try again.", drive_scope),
call. = FALSE
)
}
unsamps <- ga_unsampled_list(
accountId = accountId,
webPropertyId = webPropertyId,
profileId = profileId
)
report <- unsamps[unsamps$title == reportTitle, ]
if (nrow(report) == 0) {
stop("Report title not found. Please enter a valid title.
Remember it is case-sensitive",
call. = FALSE
)
}
if (nrow(report) > 1) {
myMessage(sprintf("WARNING: There are multiple reports with the same title of %s.
Choosing the most recently created.", reportTitle),
level = 3
)
report <- report[report$created == max(report$created), ]
}
if (report$status != "COMPLETED") {
stop(sprintf("The unsampled report has not COMPLETED. It is currently %s.
Please try again at a later time.", report$status),
call. = FALSE
)
}
if (length(report$downloadType) == 0) {
stop(
'No download related fields found (downloadType and driveDownloadDetails).
Was expecting "GOOGLE_DRIVE" downloadType.',
call. = FALSE
)
}
if (report$downloadType != "GOOGLE_DRIVE") {
stop(
"Only Google Drive download links are currently supported.
Contact your Analytics 360 account manager if you would like to change
the download location of your unsampled reports.",
call. = FALSE
)
}
url <- sprintf(
"https://www.googleapis.com/drive/v2/files/%s",
toString(report$driveDownloadDetails)
)
document <- gar_api_generator(url, "GET")()
download_link <- document[["content"]][["selfLink"]]
if (isTRUE(downloadFile)) {
filename <- sprintf("%s.csv", toString(report$title))
r <- GET(
download_link,
query = list(alt = "media"),
add_headers(Authorization = document[["request"]][["headers"]][["Authorization"]]),
write_disk(filename, overwrite = TRUE),
progress()
)
stop_for_status(r)
myMessage(sprintf("%s successfully downloaded!", filename),
level = 3
)
out <- filename
} else {
r <- GET(
download_link,
query = list(alt = "media"),
add_headers(Authorization = document[["request"]][["headers"]][["Authorization"]])
)
stop_for_status(r)
out <- content(r)
}
out
} |
object_from_call <- function(call, env, block, file) {
if (is.character(call)) {
if (identical(call, "_PACKAGE")) {
parser_package(call, env, block, file)
} else {
parser_data(call, env, file)
}
} else if (is.call(call)) {
call <- call_standardise(call, env)
name <- deparse(call[[1]])
switch(name,
"=" = ,
"<-" = ,
"<<-" = parser_assignment(call, env, block),
"delayedAssign" = parser_delayedAssign(call, env, block),
"::" = parser_import(call, env, block),
"methods::setClass" = ,
"setClass" = parser_setClass(call, env, block),
"methods::setClassUnion" = ,
"setClassUnion" = parser_setClassUnion(call, env, block),
"methods::setRefClass" = ,
"setRefClass" = parser_setRefClass(call, env, block),
"methods::setGeneric" = ,
"setGeneric" = parser_setGeneric(call, env, block),
"methods::setMethod" = ,
"setMethod" = parser_setMethod(call, env, block),
"methods::setReplaceMethod" = ,
"setReplaceMethod" = parser_setReplaceMethod(call, env, block),
"R.methodsS3::setMethodS3" = ,
"setMethodS3" = parser_setMethodS3(call, env, block),
"R.oo::setConstructorS3" = ,
"setConstructorS3" = parser_setConstructorS3(call, env, block),
NULL
)
} else {
NULL
}
}
object_from_name <- function(name, env, block) {
value <- get(name, env)
if (inherits(value, "R6ClassGenerator")) {
type <- "r6class"
} else if (methods::is(value, "refObjectGenerator")) {
value <- methods::getClass(as.character(value@className), where = env)
type <- "rcclass"
} else if (methods::is(value, "classGeneratorFunction")) {
value <- methods::getClass(as.character(value@className), where = env)
type <- "s4class"
} else if (methods::is(value, "MethodDefinition")) {
[email protected] <- extract_method_fun([email protected])
type <- "s4method"
} else if (methods::is(value, "standardGeneric")) {
type <- "s4generic"
} else if (is.function(value)) {
method <- block_get_tag_value(block, "method")
value <- add_s3_metadata(value, name, env, method)
if (inherits(value, "s3generic")) {
type <- "s3generic"
} else if (inherits(value, "s3method")) {
type <- "s3method"
} else {
type <- "function"
}
} else {
type <- "data"
}
object(value, name, type)
}
parser_data <- function(call, env, block) {
if (isNamespace(env)) {
value <- getExportedValue(call, ns = asNamespace(env))
} else {
value <- get(call, envir = env)
}
object(value, call, type = "data")
}
parser_package <- function(call, env, block, file) {
pkg_path <- dirname(dirname(file))
desc <- read.description(file.path(pkg_path, "DESCRIPTION"))
value <- list(
desc = desc,
path = pkg_path
)
object(value, call, type = "package")
}
parser_assignment <- function(call, env, block) {
name <- as.character(call[[2]])
if (length(name) > 1) {
return()
}
if (!exists(name, env)) {
return()
}
object_from_name(name, env, block)
}
parser_delayedAssign <- function(call, env, block) {
name <- as.character(call$x)
object_from_name(name, env, block)
}
parser_setClass <- function(call, env, block) {
name <- as.character(call$Class)
value <- methods::getClass(name, where = env)
object(value, NULL, "s4class")
}
parser_setClassUnion <- function(call, env, block) {
name <- as.character(call$name)
value <- methods::getClass(name, where = env)
object(value, NULL, "s4class")
}
parser_setRefClass <- function(call, env, block) {
name <- as.character(call$Class)
value <- methods::getClass(name, where = env)
object(value, NULL, "rcclass")
}
parser_setGeneric <- function(call, env, block) {
name <- as.character(call$name)
value <- methods::getGeneric(name, where = env)
object(value, NULL, "s4generic")
}
parser_setMethod <- function(call, env, block) {
name <- as.character(call$f)
value <- methods::getMethod(name, eval(call$signature), where = env)
[email protected] <- extract_method_fun([email protected])
object(value, NULL, "s4method")
}
parser_setReplaceMethod <- function(call, env, block) {
name <- paste0(as.character(call$f), "<-")
value <- methods::getMethod(name, eval(call[[3]]), where = env)
[email protected] <- extract_method_fun([email protected])
object(value, NULL, "s4method")
}
parser_import <- function(call, env, block) {
pkg <- as.character(call[[2]])
fun <- as.character(call[[3]])
object(list(pkg = pkg, fun = fun), alias = fun, type = "import")
}
parser_setMethodS3 <- function(call, env, block) {
method <- as.character(call[[2]])
class <- as.character(call[[3]])
name <- paste(method, class, sep = ".")
method <- block_get_tag_value(block, "method")
value <- add_s3_metadata(get(name, env), name, env, method)
object(value, name, "s3method")
}
parser_setConstructorS3 <- function(call, env, block) {
name <- as.character(call[[2]])
object(get(name, env), name, "function")
}
add_s3_metadata <- function(val, name, env, override = NULL) {
if (!is.null(override)) {
return(s3_method(val, override))
}
if (is_s3_generic(name, env)) {
class(val) <- c("s3generic", "function")
return(val)
}
method <- find_generic(name, env)
if (is.null(method)) {
val
} else {
s3_method(val, method)
}
}
extract_method_fun <- function(fun) {
method_body <- body(fun)
if (!is_call(method_body, "{")) return(fun)
if (length(method_body) < 2) return(fun)
first_line <- method_body[[2]]
if (!is_call(first_line, name = "<-", n = 2)) return(fun)
if (!identical(first_line[[2]], quote(`.local`))) return(fun)
local_fun <- eval(first_line[[3]])
if (!is.function(local_fun)) return(fun)
local_fun
}
object <- function(value, alias, type) {
structure(
list(
alias = alias,
value = value,
methods = if (type == "rcclass") rc_methods(value),
topic = object_topic(value, alias, type)
),
class = c(type, "object")
)
}
format.object <- function(x, ...) {
c(
paste0("<", class(x)[1], "> ", x$name),
paste0(" $topic ", x$topic),
if (!is.null(x$alias)) paste0(" $alias ", x$alias)
)
}
print.object <- function(x, ...) {
cat_line(format(x, ...))
}
object_topic <- function(value, alias, type) {
switch(type,
s4method = paste0(value@generic, ",", paste0(value@defined, collapse = ","), "-method"),
s4class = paste0(value@className, "-class"),
s4generic = value@generic,
rcclass = paste0(value@className, "-class"),
r6class = alias,
rcmethod = value@name,
s3generic = alias,
s3method = alias,
import = alias,
`function` = alias,
package = alias,
data = alias,
stop("Unsupported type '", type, "'", call. = FALSE)
)
}
call_to_object <- function(code, env = pkg_env(), file = NULL) {
code <- enexpr(code)
eval(code, envir = env)
if (is_call(code, "{")) {
call <- code[[length(code)]]
} else {
call <- code
}
object_from_call(call, env, block = NULL, file = file)
} |
library(devtools)
library(repmis)
fgithub <- "https://raw.github.com/alanarnholt/Data/master/"
AGGRESSION <- repmis::source_data(paste(fgithub, "AGGRESSION.csv", sep = ""), stringsAsFactors = TRUE)
use_data(AGGRESSION, AGGRESSION, overwrite = TRUE)
APPLE <- repmis::source_data(paste(fgithub, "APPLE.csv", sep = ""), stringsAsFactors = TRUE)
use_data(APPLE, APPLE, overwrite = TRUE)
APTSIZE <- repmis::source_data(paste(fgithub, "APTSIZE.csv", sep = ""), stringsAsFactors = TRUE)
use_data(APTSIZE, APTSIZE, overwrite = TRUE)
BABERUTH <- repmis::source_data(paste(fgithub, "BABERUTH.csv", sep = ""), stringsAsFactors = TRUE)
use_data(BABERUTH, BABERUTH, overwrite = TRUE)
BAC <- repmis::source_data(paste(fgithub, "BAC.csv", sep = ""), stringsAsFactors = TRUE)
use_data(BAC, BAC, overwrite = TRUE)
BATTERY <- repmis::source_data(paste(fgithub, "BATTERY.csv", sep = ""), stringsAsFactors = TRUE)
use_data(BATTERY, BATTERY, overwrite = TRUE)
BIOMASS <- repmis::source_data(paste(fgithub, "BIOMASS.csv", sep = ""), stringsAsFactors = TRUE)
use_data(BIOMASS, BIOMASS, overwrite = TRUE)
BODYFAT <- repmis::source_data(paste(fgithub, "BODYFAT.csv", sep = ""), stringsAsFactors = TRUE)
use_data(BODYFAT, BODYFAT, overwrite = TRUE)
CALCULUS <- repmis::source_data(paste(fgithub, "CALCULUS.csv", sep = ""), stringsAsFactors = TRUE)
use_data(CALCULUS, CALCULUS, overwrite = TRUE)
CARS2004 <- repmis::source_data(paste(fgithub, "CARS2004EU.csv", sep = ""), stringsAsFactors = TRUE)
use_data(CARS2004, CARS2004, overwrite = TRUE)
CHIPS <- repmis::source_data(paste(fgithub, "CHIPS.csv", sep = ""), stringsAsFactors = TRUE)
use_data(CHIPS, CHIPS, overwrite = TRUE)
CIRCUIT <- repmis::source_data(paste(fgithub, "CIRCUITDESIGNS.csv", sep = ""), stringsAsFactors = TRUE)
use_data(CIRCUIT, CIRCUIT, overwrite = TRUE)
COSAMA <- repmis::source_data(paste(fgithub, "COSAMA.csv", sep = ""), stringsAsFactors = TRUE)
use_data(COSAMA, COSAMA, overwrite = TRUE)
COWS <- repmis::source_data(paste(fgithub, "COWS.csv", sep = ""), stringsAsFactors = TRUE)
use_data(COWS, COWS, overwrite = TRUE)
DEPEND <- repmis::source_data(paste(fgithub, "DEPEND.csv", sep = ""), stringsAsFactors = TRUE)
use_data(DEPEND, DEPEND, overwrite = TRUE)
DROSOPHILA <- repmis::source_data(paste(fgithub, "DROSOPHILA.csv", sep = ""), stringsAsFactors = TRUE)
use_data(DROSOPHILA, DROSOPHILA, overwrite = TRUE)
ENGINEER <- repmis::source_data(paste(fgithub, "ENGINEER.csv", sep = ""), stringsAsFactors = TRUE)
use_data(ENGINEER, ENGINEER, overwrite = TRUE)
EPIDURAL <- repmis::source_data(paste(fgithub, "EPIDURAL.csv", sep = ""), stringsAsFactors = TRUE)
use_data(EPIDURAL, EPIDURAL, overwrite = TRUE)
EPIDURALF <- repmis::source_data(paste(fgithub, "EPIDURALF.csv", sep = ""), stringsAsFactors = TRUE)
use_data(EPIDURALF, EPIDURALF, overwrite = TRUE)
EURD <- repmis::source_data(paste(fgithub, "EURD.csv", sep = ""), stringsAsFactors = TRUE)
use_data(EURD, EURD, overwrite = TRUE)
FAGUS <- repmis::source_data(paste(fgithub, "FAGUS.csv", sep = ""), stringsAsFactors = TRUE)
use_data(FAGUS, FAGUS, overwrite = TRUE)
FCD <- repmis::source_data(paste(fgithub, "FCD.csv", sep = ""), stringsAsFactors = TRUE)
use_data(FCD, FCD, overwrite = TRUE)
FERTILIZE <- repmis::source_data(paste(fgithub, "FERTILIZE.csv", sep = ""), stringsAsFactors = TRUE)
use_data(FERTILIZE, FERTILIZE, overwrite = TRUE)
FOOD <- repmis::source_data(paste(fgithub, "FOOD.csv", sep = ""), stringsAsFactors = TRUE)
use_data(FOOD, FOOD, overwrite = TRUE)
FORMULA1 <- repmis::source_data(paste(fgithub, "FORMULA1.csv", sep = ""), stringsAsFactors = TRUE)
use_data(FORMULA1, FORMULA1, overwrite = TRUE)
GD <- repmis::source_data(paste(fgithub, "GD.csv", sep = ""), stringsAsFactors = TRUE)
use_data(GD, GD, overwrite = TRUE)
GLUCOSE <- repmis::source_data(paste(fgithub, "GLUCOSE.csv", sep = ""), stringsAsFactors = TRUE)
use_data(GLUCOSE, GLUCOSE, overwrite = TRUE)
GRADES <- repmis::source_data(paste(fgithub, "GRADES.csv", sep = ""), stringsAsFactors = TRUE)
use_data(GRADES, GRADES, overwrite = TRUE)
GROCERY <- repmis::source_data(paste(fgithub, "GROCERY.csv", sep = ""), stringsAsFactors = TRUE)
use_data(GROCERY, GROCERY, overwrite = TRUE)
HARDWATER <- repmis::source_data(paste(fgithub, "HARDWATER.csv", sep = ""), stringsAsFactors = TRUE)
use_data(HARDWATER, HARDWATER, overwrite = TRUE)
HOUSE <- repmis::source_data(paste(fgithub, "HOUSE.csv", sep = ""), stringsAsFactors = TRUE)
use_data(HOUSE, HOUSE, overwrite = TRUE)
HSWRESTLER <- repmis::source_data(paste(fgithub, "HSWRESTLER.csv", sep = ""), stringsAsFactors = TRUE)
use_data(HSWRESTLER, HSWRESTLER, overwrite = TRUE)
HUBBLE <- repmis::source_data(paste(fgithub, "HUBBLE.csv", sep = ""), stringsAsFactors = TRUE)
use_data(HUBBLE, HUBBLE, overwrite = TRUE)
INSURQUOTES <- repmis::source_data(paste(fgithub, "INSURQUOTES.csv", sep = ""), stringsAsFactors = TRUE)
use_data(INSURQUOTES, INSURQUOTES, overwrite = TRUE)
JANKA <- repmis::source_data(paste(fgithub, "JANKA.csv", sep = ""), stringsAsFactors = TRUE)
use_data(JANKA, JANKA, overwrite = TRUE)
KINDER <- repmis::source_data(paste(fgithub, "KINDER.csv", sep = ""), stringsAsFactors = TRUE)
use_data(KINDER, KINDER, overwrite = TRUE)
LEDDIODE <- repmis::source_data(paste(fgithub, "LEDDIODE.csv", sep = ""), stringsAsFactors = TRUE)
use_data(LEDDIODE, LEDDIODE, overwrite = TRUE)
LOSTR <- repmis::source_data(paste(fgithub, "LOSTR.csv", sep = ""), stringsAsFactors = TRUE)
use_data(LOSTR, LOSTR, overwrite = TRUE)
MILKCARTON <- repmis::source_data(paste(fgithub, "MILKCARTON.csv", sep = ""), stringsAsFactors = TRUE)
use_data(MILKCARTON, MILKCARTON, overwrite = TRUE)
NC2010DMG <- repmis::source_data(paste(fgithub, "NC2010DMG.csv", sep = ""), stringsAsFactors = TRUE)
use_data(NC2010DMG, NC2010DMG, overwrite = TRUE)
PAMTEMP <- repmis::source_data(paste(fgithub, "PAMTEMP.csv", sep = ""), stringsAsFactors = TRUE)
use_data(PAMTEMP, PAMTEMP, overwrite = TRUE)
PHENYL <- repmis::source_data(paste(fgithub, "PHENYL.csv", sep = ""), stringsAsFactors = TRUE)
use_data(PHENYL, PHENYL, overwrite = TRUE)
PHONE <- repmis::source_data(paste(fgithub, "PHONE.csv", sep = ""), stringsAsFactors = TRUE)
use_data(PHONE, PHONE, overwrite = TRUE)
RAT <- repmis::source_data(paste(fgithub, "RAT.csv", sep = ""), stringsAsFactors = TRUE)
use_data(RAT, RAT, overwrite = TRUE)
RATBP <- repmis::source_data(paste(fgithub, "RATBP.csv", sep = ""), stringsAsFactors = TRUE)
use_data(RATBP, RATBP, overwrite = TRUE)
REFRIGERATOR <- repmis::source_data(paste(fgithub, "REFRIGERATOR.csv", sep = ""), stringsAsFactors = TRUE)
use_data(REFRIGERATOR, REFRIGERATOR, overwrite = TRUE)
ROACHEGGS <- repmis::source_data(paste(fgithub, "ROACHEGGS.csv", sep = ""), stringsAsFactors = TRUE)
use_data(ROACHEGGS, ROACHEGGS, overwrite = TRUE)
SALINITY <- repmis::source_data(paste(fgithub, "SALINITY.csv", sep = ""), stringsAsFactors = TRUE)
use_data(SALINITY, SALINITY, overwrite = TRUE)
SATFRUIT <- repmis::source_data(paste(fgithub, "SATFRUIT.csv", sep = ""), stringsAsFactors = TRUE)
use_data(SATFRUIT, SATFRUIT, overwrite = TRUE)
SBIQ <- repmis::source_data(paste(fgithub, "SBIQ.csv", sep = ""), stringsAsFactors = TRUE)
use_data(SBIQ, SBIQ, overwrite = TRUE)
SCHIZO <- repmis::source_data(paste(fgithub, "SCHIZO.csv", sep = ""), stringsAsFactors = TRUE)
use_data(SCHIZO, SCHIZO, overwrite = TRUE)
SCORE <- repmis::source_data(paste(fgithub, "SCORE.csv", sep = ""), stringsAsFactors = TRUE)
use_data(SCORE, SCORE, overwrite = TRUE)
SDS4 <- repmis::source_data(paste(fgithub, "SDS4.csv", sep = ""), stringsAsFactors = TRUE)
use_data(SDS4, SDS4, overwrite = TRUE)
SIMDATAST <- repmis::source_data(paste(fgithub, "SIMDATAST.csv", sep = ""), stringsAsFactors = TRUE)
use_data(SIMDATAST, SIMDATAST, overwrite = TRUE)
SIMDATAXT <- repmis::source_data(paste(fgithub, "SIMDATAXT.csv", sep = ""), stringsAsFactors = TRUE)
use_data(SIMDATAXT, SIMDATAXT, overwrite = TRUE)
SOCCER <- repmis::source_data(paste(fgithub, "SOCCER.csv", sep = ""), stringsAsFactors = TRUE)
use_data(SOCCER, SOCCER, overwrite = TRUE)
STATTEMPS <- repmis::source_data(paste(fgithub, "STATTEMPS.csv", sep = ""), stringsAsFactors = TRUE)
use_data(STATTEMPS, STATTEMPS, overwrite = TRUE)
STSCHOOL <- repmis::source_data(paste(fgithub, "STSCHOOL.csv", sep = ""), stringsAsFactors = TRUE)
use_data(STSCHOOL, STSCHOOL, overwrite = TRUE)
SUNDIG <- repmis::source_data(paste(fgithub, "SUNDIG.csv", sep = ""), stringsAsFactors = TRUE)
use_data(SUNDIG, SUNDIG, overwrite = TRUE)
SUNFLOWER <- repmis::source_data(paste(fgithub, "SUNFLOWER.csv", sep = ""), stringsAsFactors = TRUE)
use_data(SUNFLOWER, SUNFLOWER, overwrite = TRUE)
SURFACESPAIN <- repmis::source_data(paste(fgithub, "SURFACESPAIN.csv", sep = ""), stringsAsFactors = TRUE)
use_data(SURFACESPAIN, SURFACESPAIN, overwrite = TRUE)
SWIMTIMES <- repmis::source_data(paste(fgithub, "SWIMTIMES.csv", sep = ""), stringsAsFactors = TRUE)
use_data(SWIMTIMES, SWIMTIMES, overwrite = TRUE)
TENNIS <- repmis::source_data(paste(fgithub, "TENNIS.csv", sep = ""), stringsAsFactors = TRUE)
use_data(TENNIS, TENNIS, overwrite = TRUE)
TESTSCORES <- repmis::source_data(paste(fgithub, "TESTSCORES.csv", sep = ""), stringsAsFactors = TRUE)
use_data(TESTSCORES, TESTSCORES, overwrite = TRUE)
TIRE <- repmis::source_data(paste(fgithub, "TIRE.csv", sep = ""), stringsAsFactors = TRUE)
use_data(TIRE, TIRE, overwrite = TRUE)
TIREWEAR <- repmis::source_data(paste(fgithub, "TIREWEAR.csv", sep = ""), stringsAsFactors = TRUE)
use_data(TIREWEAR, TIREWEAR, overwrite = TRUE)
TITANIC3 <- repmis::source_data(paste(fgithub, "TITANIC3.csv", sep = ""), stringsAsFactors = TRUE)
use_data(TITANIC3, TITANIC3, overwrite = TRUE)
TOE <- repmis::source_data(paste(fgithub, "TOE.csv", sep = ""), stringsAsFactors = TRUE)
use_data(TOE, TOE, overwrite = TRUE)
TOP20 <- repmis::source_data(paste(fgithub, "TOP20.csv", sep = ""), stringsAsFactors = TRUE)
use_data(TOP20, TOP20, overwrite = TRUE)
URLADDRESS <- repmis::source_data(paste(fgithub, "URLADDRESS.csv", sep = ""), stringsAsFactors = TRUE)
use_data(URLADDRESS, URLADDRESS, overwrite = TRUE)
VIT2005 <- repmis::source_data(paste(fgithub, "VIT2005.csv", sep = ""), stringsAsFactors = TRUE)
use_data(VIT2005, VIT2005, overwrite = TRUE)
WAIT <- repmis::source_data(paste(fgithub, "WAIT.csv", sep = ""), stringsAsFactors = TRUE)
use_data(WAIT, WAIT, overwrite = TRUE)
WASHER <- repmis::source_data(paste(fgithub, "WASHER.csv", sep = ""), stringsAsFactors = TRUE)
use_data(WASHER, WASHER, overwrite = TRUE)
WATER <- repmis::source_data(paste(fgithub, "WATER.csv", sep = ""), stringsAsFactors = TRUE)
use_data(WATER, WATER, overwrite = TRUE)
WCST <- repmis::source_data(paste(fgithub, "WCST.csv", sep = ""), stringsAsFactors = TRUE)
use_data(WCST, WCST, overwrite = TRUE)
WEIGHTGAIN <- repmis::source_data(paste(fgithub, "WEIGHTGAIN.csv", sep = ""), stringsAsFactors = TRUE)
use_data(WEIGHTGAIN, WEIGHTGAIN, overwrite = TRUE)
WHEATSPAIN <- repmis::source_data(paste(fgithub, "WHEATSPAIN.csv", sep = ""), stringsAsFactors = TRUE)
use_data(WHEATSPAIN, WHEATSPAIN, overwrite = TRUE)
WHEATUSA2004 <- repmis::source_data(paste(fgithub, "WHEATUSA2004.csv", sep = ""), stringsAsFactors = TRUE)
use_data(WHEATUSA2004, WHEATUSA2004, overwrite = TRUE)
WOOL <- repmis::source_data(paste(fgithub, "WOOL.csv", sep = ""), stringsAsFactors = TRUE)
use_data(WOOL, WOOL, overwrite = TRUE) |
get.viewExtent <- function(data) {
bounds <- st_bbox(data)
center.lon <- bounds$xmin + (bounds$xmax - bounds$xmin)/2
center.lat <- bounds$ymin + (bounds$ymax - bounds$ymin)/2
zoom.lon <- log(180/abs(center.lon - bounds$xmin))/log(2)
zoom.lat <- log(90/abs(center.lat - bounds$ymin))/log(2)
center <- c(center.lon, center.lat)
zoom <- mean(zoom.lon, zoom.lat)
return (
list(center, zoom)
)
}
dataLoader <- function() {
modalDialog(
selectInput(
inputId = "filetype",
label = 'Load Data',
choices = c(
`Select a file type` = '',
c(
"GPKG",
"GeoJSON",
"ESRI Shapefile",
"CSV"
)
)
),
conditionalPanel(
condition = "input.filetype == 'CSV'",
span('Please specify the longitude and latitude column names to read from.'),
textInput(
inputId = "x",
label = "longitute column name"
),
textInput(
inputId = "y",
label = "latidude column name"
)
),
conditionalPanel(
condition = "input.filetype == 'ESRI Shapefile'",
span('You must select and upload ALL shapefile required files (.shp, .shx, .dbf, etc.'),
),
footer = tagList(
div(style="display:inline",
fluidRow(
column(
width = 4,
modalButton(label = "Cancel")
),
column(
width = 8,
conditionalPanel(
condition = "input.filetype != '' && input.filetype != 'CSV' ||
input.filetype == 'CSV' && input.x != '' && input.y != ''",
uiOutput(outputId = "dynUpload")
)
)
)
)
),
size = 's'
)
}
getData <- function(filetype, upload, x, y) {
if (filetype == "ESRI Shapefile") {
esri.files <- upload
tempdirname <- dirname(esri.files$datapath[1])
for (i in seq_len(nrow(esri.files))) {
file.rename(
esri.files$datapath[i],
paste0(tempdirname, "/", esri.files$name[i])
)
}
shapefile <- paste(
tempdirname,
esri.files$name[grep(pattern = "*.shp$", esri.files$name)],
sep = "/"
)
data <- st_read(shapefile) %>% st_transform(4326)
name <- esri.files$name[grep(pattern = "*.shp$", esri.files$name)]
}
else if (filetype == "CSV") {
data <- st_read(
upload$datapath,
options=c(
paste0("X_POSSIBLE_NAMES=", x),
paste0("Y_POSSIBLE_NAMES=", y)
)
)
name <- upload$name
}
else {
data <- sf::st_read(upload$datapath) %>% st_transform(4326)
name <- upload$name
}
num_row <- nrow(data)
varnames <- data %>% st_drop_geometry() %>% colnames()
dummy <- 1:num_row
data <- data %>% cbind(dummy)
return(list(data = data, name = name, vars = varnames))
}
calc.dMat <- function(data) {
dp.locat <- sf::st_centroid(data) %>% sf::st_coordinates()
dMat <- geodist::geodist(dp.locat, measure = "cheap")
return(dMat)
} |
fit_hbd_psr_on_best_grid_size = function( tree,
oldest_age = NULL,
age0 = 0,
grid_sizes = c(1,10),
uniform_grid = FALSE,
criterion = "AIC",
exhaustive = TRUE,
min_PSR = 0,
max_PSR = +Inf,
guess_PSR = NULL,
fixed_PSR = NULL,
splines_degree = 1,
condition = "auto",
relative_dt = 1e-3,
Ntrials = 1,
Nbootstraps = 0,
Ntrials_per_bootstrap = NULL,
Nthreads = 1,
max_model_runtime = NULL,
fit_control = list(),
verbose = FALSE,
verbose_prefix = ""){
if(verbose) cat(sprintf("%sChecking input parameters..\n",verbose_prefix))
root_age = get_tree_span(tree)$max_distance
if(is.null(oldest_age)) oldest_age = root_age
if(!is.null(guess_PSR)){
if(class(guess_PSR) != "function"){
if(length(guess_PSR)!=1){
return(list(success=FALSE, error="Expecting either exactly one guess_PSR, or NULL, or a function handle"))
}else{
guess_PSR_value = guess_PSR
guess_PSR = function(ages){ rep(guess_PSR_value, length(ages)) }
}
}
}else{
guess_PSR = function(ages){ rep(NA, length(ages)) }
}
if(!is.null(fixed_PSR)){
if(class(fixed_PSR) != "function"){
if(length(fixed_PSR)!=1){
return(list(success=FALSE, error="Expecting either exactly one fixed_PSR, or NULL, or a function handle"))
}else{
fixed_PSR_value = fixed_PSR
fixed_PSR = function(ages){ rep(fixed_PSR_value, length(ages)) }
}
}
}else{
fixed_PSR = function(ages){ rep(NA, length(ages)) }
}
if(length(min_PSR)!=1) return(list(success=FALSE, error=sprintf("Expecting exactly one min_PSR; instead, received %d",length(min_PSR))))
if(length(max_PSR)!=1) return(list(success=FALSE, error=sprintf("Expecting exactly one max_PSR; instead, received %d",length(max_PSR))))
if(!(criterion %in% c("AIC", "BIC"))) return(list(success=FALSE, error=sprintf("Invalid model selection criterion '%s'. Expected 'AIC' or 'BIC'",criterion)))
Nmodels = length(grid_sizes)
if(!uniform_grid){
LTT = count_lineages_through_time(tree=tree, Ntimes = max(100,10*max(grid_sizes)), regular_grid = TRUE, ultrametric=TRUE)
LTT$ages = root_age - LTT$times
}
if(exhaustive){
model_order = seq_len(Nmodels)
}else{
model_order = order(grid_sizes)
}
if(verbose) cat(sprintf("%sFitting models with %s%d different grid sizes..\n",verbose_prefix,(if(exhaustive) "" else "up to "),Nmodels))
AICs = rep(NA, times=Nmodels)
BICs = rep(NA, times=Nmodels)
best_fit = NULL
for(m in model_order){
Ngrid = grid_sizes[m]
if(uniform_grid || (Ngrid==1)){
age_grid = seq(from=age0, to=oldest_age, length.out=Ngrid)
}else{
age_grid = get_inhomogeneous_grid_1D(Xstart = age0, Xend = oldest_age, Ngrid = Ngrid, densityX = rev(LTT$ages), densityY=sqrt(rev(LTT$lineages)), extrapolate=TRUE)
}
if(verbose) cat(sprintf("%s Fitting model with grid size %d..\n",verbose_prefix,Ngrid))
fit = fit_hbd_psr_on_grid( tree = tree,
oldest_age = oldest_age,
age0 = age0,
age_grid = age_grid,
min_PSR = min_PSR,
max_PSR = max_PSR,
guess_PSR = guess_PSR(age_grid),
fixed_PSR = fixed_PSR(age_grid),
splines_degree = splines_degree,
condition = condition,
relative_dt = relative_dt,
Ntrials = Ntrials,
Nbootstraps = 0,
Nthreads = Nthreads,
max_model_runtime = max_model_runtime,
fit_control = fit_control,
verbose = FALSE,
diagnostics = FALSE,
verbose_prefix = paste0(verbose_prefix," "))
if(!fit$success) return(list(success=FALSE, error=sprintf("Fitting model with grid size %d failed: %s",Ngrid,fit$error)))
criterion_value = fit[[criterion]]
if(is.null(best_fit)){
best_fit = fit
worsened = FALSE
}else if(criterion_value<best_fit[[criterion]]){
best_fit = fit
worsened = FALSE
}else{
worsened = TRUE
}
AICs[m] = fit$AIC
BICs[m] = fit$BIC
if(verbose) cat(sprintf("%s --> %s=%.10g. Best grid size so far: %d\n",verbose_prefix,criterion,criterion_value,length(best_fit$age_grid)))
if((!exhaustive) && worsened) break;
}
if((Nbootstraps>0) && (!is.null(best_fit))){
if(verbose) cat(sprintf("%s Performing boostraps for best model, with grid size %d..\n",verbose_prefix,length(best_fit$age_grid)))
best_fit = fit_hbd_psr_on_grid( tree = tree,
oldest_age = oldest_age,
age0 = age0,
age_grid = best_fit$age_grid,
min_PSR = min_PSR,
max_PSR = max_PSR,
guess_PSR = guess_PSR(best_fit$age_grid),
fixed_PSR = fixed_PSR(best_fit$age_grid),
splines_degree = splines_degree,
condition = condition,
relative_dt = relative_dt,
Ntrials = Ntrials,
Nbootstraps = Nbootstraps,
Ntrials_per_bootstrap = Ntrials_per_bootstrap,
Nthreads = Nthreads,
max_model_runtime = max_model_runtime,
fit_control = fit_control,
verbose = FALSE,
diagnostics = FALSE,
verbose_prefix = paste0(verbose_prefix," "))
}
return(list(success = (if(is.null(best_fit)) FALSE else best_fit$success),
best_fit = best_fit,
grid_sizes = grid_sizes,
AICs = AICs,
BICs = BICs))
} |
context("generate")
test_that ("errors", {
expect_error (ms_generate_map (),
paste0 ("Please provide a 'mapname' \\(with ",
"optional path\\) for the maps"))
})
test_that("generate", {
expect_silent (x <- readRDS ("../x.Rds"))
x@crs@projargs <- .sph_merc()
expect_error (x <- ms_generate_map (raster_brick = x),
paste0 ("Please provide a 'mapname' ",
"\\(with optional path\\)"))
mapname <- file.path (tempdir (), "map")
expect_message (x2 <- ms_generate_map (mapname = mapname,
raster_brick = x),
"Successfully generated")
expect_true (identical (x, x2))
})
test_that("convert bbox", {
expect_error (bbc <- convert_bbox (1:5),
"bbox must have four elements")
expect_silent (bbc <- convert_bbox (1:4))
expect_is (bbc, "matrix")
expect_equal (nrow (bbc), 2)
expect_equal (ncol (bbc), 2)
})
test_that("slippy bbox", {
bb <- convert_bbox (1:4)
expect_silent (s <- slippy_bbox (bb))
expect_is (s, "list")
expect_identical (names (s), c ("tile_bbox", "user_points"))
expect_is (s$tile_bbox, "numeric")
expect_equal (length (s$tile_bbox), 4)
expect_is (s$user_points, "matrix")
})
test_that("url_to_cache", {
query_string <- paste0 ("https://api.mapbox.com/v4/mapbox.light/",
"{zoom}/{x}/{y}.jpg?access_token=",
"123456789")
expect_silent (outfile <- url_to_cache (query_string))
expect_is (outfile, "character")
expect_false (file.exists (outfile))
expect_false (dir.exists (outfile))
})
test_that("raster_brick", {
f <- system.file ("extdata", "omaha.png", package = "mapscanner")
expect_silent (rb <- raster_brick (f))
expect_is (rb, "RasterBrick")
})
test_that ("spherical_mercator", {
expect_silent (x <- spherical_mercator ())
expect_is (x, "tbl")
expect_equal (nrow (x), 1)
expect_equal (ncol (x), 5)
expect_identical (names (x), c ("provider", "maxextent", "A",
"B", "crs"))
}) |
library(testthat)
library(gradethis)
test_check("gradethis") |
map.soa.sbm <-
function(xdata, ydata, date, rts = "crs", orientation = "n",
sg = "ssm", cv = "convex", mk = "dmu"){
if(is.na(match(rts, c("crs", "vrs", "irs", "drs")))) stop('rts must be "crs", "vrs", "irs", or "drs".')
if(is.na(match(orientation, c("n", "i", "o")))) stop('orientation must be "n", "i", or "o".')
if(is.na(match(sg, c("ssm", "max", "min")))) stop('sg must be "ssm", "max", or "min".')
if(is.na(match(mk, c("dmu", "eff")))) stop('mk must be either "dmu" or "eff".')
if(is.na(match(cv, c("convex", "fdh")))) stop('cv must be "convex" or "fdh".')
xdata <- as.matrix(xdata)
ydata <- as.matrix(ydata)
date <- if(!is.null(date)) as.matrix(date)
n <- nrow(xdata)
m <- ncol(xdata)
s <- ncol(ydata)
rts <- ifelse(cv == "fdh", "vrs", rts)
o <- matrix(c(1:n), ncol = 1)
ud <- sort(unique(date))
l <- length(ud)
x <- xdata[order(date),, drop = F]
y <- ydata[order(date),, drop = F]
d <- date [order(date),, drop = F]
o <- o [order(date),, drop = F]
map.soa <- matrix(NA, n, l, dimnames = list(NULL, ud))
for(i in ud){
sbm.t <- dm.sbm(subset(x, d <= i), subset(y, d <= i), rts, orientation, 0,
sg, subset(d, d <= i), cv)
id.soa <- which(round(sbm.t$eff, 8) == 1 &
rowSums(cbind(round(sbm.t$xslack, 8),
round(sbm.t$yslack, 8))) == 0)
if(mk == "dmu"){
if(i == ud[1]){
map.soa[1:length(id.soa), 1] <- o[id.soa]
}else{
p <- which(ud == i)
for(k in 1:length(id.soa)){
id.preb <- which(map.soa[, p - 1] == o[id.soa[k],])
if(length(id.preb) > 0){
map.soa[id.preb, p] <- o[id.soa[k],]
}else{
map.soa[sum(rowSums(map.soa, na.rm = T) > 0) + 1, p] <- o[id.soa[k],]
}
}
}
}else{
gsoa <- if(i == ud[1]) id.soa else union(gsoa, id.soa)
map.soa[1:length(gsoa), which(ud == i)] <- sbm.t$eff[gsoa,]
}
}
map.soa <- map.soa[1:max(which(!is.na(map.soa[, l]))),]
rownames(map.soa) <- if(mk == "dmu") unique(na.omit(c(map.soa))) else c(o[gsoa,])
print(map.soa)
} |
htmlEmbed <- function(children=NULL, id=NULL, n_clicks=NULL, n_clicks_timestamp=NULL, key=NULL, role=NULL, height=NULL, src=NULL, type=NULL, width=NULL, accessKey=NULL, className=NULL, contentEditable=NULL, contextMenu=NULL, dir=NULL, draggable=NULL, hidden=NULL, lang=NULL, spellCheck=NULL, style=NULL, tabIndex=NULL, title=NULL, loading_state=NULL, ...) {
wildcard_names = names(dash_assert_valid_wildcards(attrib = list('data', 'aria'), ...))
props <- list(children=children, id=id, n_clicks=n_clicks, n_clicks_timestamp=n_clicks_timestamp, key=key, role=role, height=height, src=src, type=type, width=width, accessKey=accessKey, className=className, contentEditable=contentEditable, contextMenu=contextMenu, dir=dir, draggable=draggable, hidden=hidden, lang=lang, spellCheck=spellCheck, style=style, tabIndex=tabIndex, title=title, loading_state=loading_state, ...)
if (length(props) > 0) {
props <- props[!vapply(props, is.null, logical(1))]
}
component <- list(
props = props,
type = 'Embed',
namespace = 'dash_html_components',
propNames = c('children', 'id', 'n_clicks', 'n_clicks_timestamp', 'key', 'role', 'height', 'src', 'type', 'width', 'accessKey', 'className', 'contentEditable', 'contextMenu', 'dir', 'draggable', 'hidden', 'lang', 'spellCheck', 'style', 'tabIndex', 'title', 'loading_state', wildcard_names),
package = 'dashHtmlComponents'
)
structure(component, class = c('dash_component', 'list'))
} |
tabPanel('Bivariate Analysis', value = 'tab_bivar', icon = icon('cubes'),
navlistPanel(id = 'navlist_bivar',
well = FALSE,
widths = c(2, 10),
source('ui/ui_woe_iv.R', local = TRUE)[[1]],
source('ui/ui_woe_iv_stats.R', local = TRUE)[[1]],
source('ui/ui_segment_dist.R', local = TRUE)[[1]],
source('ui/ui_2way_segment.R', local = TRUE)[[1]],
source('ui/ui_bivar_analysis.R', local = TRUE)[[1]]
)
) |
spatial_migrate <- function(
data,
d_stations,
d_map,
snr,
v,
dt,
normalise = TRUE,
silent = FALSE
) {
if(is.matrix(data) == FALSE) {
if(class(data)[1] == "list") {
dt <- try(data[[1]]$meta$dt)
if(class(dt)[1] == "try-error") {
stop("Signal object seems to contain no eseis objects!")
}
data <- do.call(rbind, lapply(X = data, FUN = function(data) {
data$signal
}))
} else {
stop("Input signals must be more than one!")
}
}
if(is.matrix(d_stations) == FALSE) {
stop("Station distance matrix must be symmetric matrix!")
}
if(nrow(d_stations) != ncol(d_stations)) {
stop("Station distance matrix must be symmetric matrix!")
}
if(is.list(d_map) == FALSE) {
stop("Distance maps must be list objects with SpatialGridDataFrames!")
}
if(class(d_map[[1]])[1] != "SpatialGridDataFrame") {
stop("Distance maps must be list objects with SpatialGridDataFrames!")
}
if(normalise == TRUE & missing(snr) == TRUE) {
if(silent == FALSE) {
print("No snr given. Will be calculated from signals")
}
snr_flag = TRUE
} else {
snr_flag <- FALSE
}
s_min <- matrixStats::rowMins(data, na.rm = TRUE)
s_max <- matrixStats::rowMaxs(data, na.rm = TRUE)
s_mean <- matrixStats::rowMeans2(data, na.rm = TRUE)
if(snr_flag == TRUE) {
s_snr <- s_max / s_mean
} else {
s_snr <- rep(1, nrow(data))
}
data <- (data - s_min) / (s_max - s_min)
duration <- ncol(data) * dt
pairs <- combn(x = nrow(data),
m = 2)
pairs <- as.list(as.data.frame((pairs)))
maps <-
lapply(X = pairs, FUN = function(pairs, data, duration, dt,
d_stations, v, s_max, s_snr, d_map) {
cc = acf(x = cbind(data[pairs[1],],
data[pairs[2],]),
lag.max = duration * 1 / dt,
plot = FALSE)
lags <- c(rev(cc$lag[-1, 2, 1]),
cc$lag[, 1, 2]) * dt
cors <- c(rev(cc$acf[-1, 2, 1]),
cc$acf[, 1, 2])
lag_lim <- ceiling(d_stations[pairs[1], pairs[2]] / v)
lag_ok <-lags >= -lag_lim & lags <= lag_lim
lags <- lags[lag_ok]
cors <- cors[lag_ok]
if(normalise == TRUE) {
norm <- ((s_snr[pairs[1]] + s_snr[pairs[2]]) / 2) / mean(s_snr)
} else {
norm <- 1
}
t_max <- lags[cors == max(cors)]
lag_model <- (raster::raster(d_map[[pairs[1]]]) -
raster::raster(d_map[[pairs[2]]])) / v
lag_empiric <- d_stations[pairs[1], pairs[2]] / v
cors_map <- exp(-0.5 * (((lag_model - t_max) / lag_empiric)^2)) * norm
return(cors_map@data@values)
}, data, duration, dt, d_stations, v, s_max, s_snr, d_map)
maps_values <- do.call(rbind, maps)
map_out <- raster::raster(d_map[[1]])
map_out@data@values <- matrixStats::colMeans2(x = maps_values)
return(map_out)
} |
utils::globalVariables(c("x", "y"))
.onLoad <- function(libname, pkgname) {
make_discrim_linear_MASS()
make_discrim_linear_mda()
make_discrim_linear_sda()
make_discrim_linear_sparsediscrim()
make_discrim_quad_MASS()
make_discrim_quad_sparsediscrim()
make_discrim_regularized()
make_discrim_flexible()
make_naive_Bayes_klaR()
make_naive_Bayes_naivebayes()
} |
context("coherence")
N = 500
tokens = word_tokenizer(tolower(movie_review$review[1:N]))
it = itoken(tokens, progressbar = FALSE)
v = create_vocabulary(it)
v = prune_vocabulary(v, term_count_min = 5, doc_proportion_max = 0.2)
dtm = create_dtm(it, vocab_vectorizer(v))
n_topics = 100
n_top_terms = 10
lda_model = text2vec::LDA$new(n_topics = n_topics)
fitted = lda_model$fit_transform(dtm)
top_terms = lda_model$get_top_words(n = n_top_terms, topic_number = 1L:n_topics)
topic_word_distribution = lda_model$topic_word_distribution
test_that("coherence, general functionality", {
tcm_intrinsic = Matrix::crossprod(sign(dtm))
coherence_res = coherence(x = top_terms ,tcm = tcm_intrinsic, n_doc_tcm = nrow(dtm))
expect_true(inherits(coherence_res, "matrix"))
expect_equal(typeof(coherence_res), "double")
expect_true(setequal(colnames(coherence_res),
c("mean_logratio", "mean_pmi", "mean_npmi", "mean_difference", "mean_npmi_cosim", "mean_npmi_cosim2")))
expect_equal(nrow(coherence_res), n_topics)
coherence_res_adapted_smooth = coherence(x = top_terms ,tcm = tcm_intrinsic, n_doc_tcm = nrow(dtm), smooth = .01)
expect_false(sum(as.vector(coherence_res)) == sum(as.vector(coherence_res_adapted_smooth)))
tcm_err = tcm_intrinsic[1:2,1:2]
tcm_err[1,2] = 0
tcm_err[2,1] = 0
expect_warning({coherence_err = coherence(x = top_terms, tcm = tcm_err, n_doc_tcm = nrow(dtm))})
expect_true(all(is.na(coherence_err)))
rownames(tcm_err) <- rev(rownames(tcm_err))
expect_error(coherence(x = top_terms, tcm = tcm_err, n_doc_tcm = nrow(dtm)))
})
test_that("coherence, vectorized vs. mapply loop calculation of PMI", {
tcm = matrix(rbind(c(40, 1, 2, 3),
c(1, 30, 4, 5),
c(2, 4,20, 6),
c(3, 5, 6,10)), ncol = 4)
idxs = 1:ncol(tcm)
idxs_combis = t(combn(idxs,2, FUN = function(x) sort(x, decreasing = TRUE)))
pmi = mapply(function(x,y) {log2((tcm[x,y]) + 1e-12) - log2(tcm[x,x]) - log2(tcm[y,y])} ,idxs_combis[,1], idxs_combis[,2])
res = as.matrix(tcm[idxs, idxs])
res[upper.tri(res)] = res[upper.tri(res)] + 1e-12
d = diag(res)
res = res/d
res = res %*% diag(1 / d)
res = res[upper.tri(res)]
pmi_vect = log2(res)
expect_equal(sort(pmi), sort(pmi_vect))
tcm = Matrix::crossprod(dtm)
for (i in 1:10) {
set.seed(i)
idxs = sample(1:ncol(tcm), 4)
idxs_combis = t(combn(idxs,2, FUN = function(x) sort(x, decreasing = TRUE)))
pmi = mapply(function(x,y) {log2((tcm[x,y]) + 1e-12) - log2(tcm[x,x]) - log2(tcm[y,y])} ,idxs_combis[,1], idxs_combis[,2])
res = as.matrix(tcm[idxs, idxs])
res[upper.tri(res)] = res[upper.tri(res)] + 1e-12
d = diag(res)
res = res/d
res = res %*% diag(1 / d)
res = res[upper.tri(res)]
pmi_vect = log2(res)
expect_equal(sort(pmi), sort(pmi_vect))
}
})
test_that("coherence, results of text2vec vs other packages", {
CalcProbCoherence <- function(phi, dtm, M = 5){
if( ! is.numeric(phi) ){
stop("phi must be a numeric matrix whose rows index topics and columns\n",
" index terms or phi must be a numeric vector whose entries index terms.")
}
if( ! is.matrix(dtm) &&
! inherits(dtm, 'Matrix')){
stop("dtm must be a matrix. This can be a standard R dense matrix or a\n",
" matrix of class dgCMatrix, dgTMatrix, dgRMatrix, or dgeMatrix")
}
if( ! is.numeric(M) | M < 1){
stop("M must be an integer in 1:ncol(phi) or 1:length(phi)")
}
if(length(M) != 1){
warning("M is a vector when scalar is expected. Taking only the first value")
M <- M[ 1 ]
}
if(floor(M) != M){
warning("M is expected to be an integer. floor(M) is being used.")
M <- floor(M)
}
if( is.null(colnames(dtm))){
stop("dtm must have colnames")
}
if( ! is.matrix(phi) ){
if(sum(names(phi)[ 1:M ] %in% colnames(dtm)) != length(1:M)){
stop("names(phi)[ 1:M ] are not in colnames(dtm)")
}
}else if(sum(colnames(phi)[ 1:M ] %in% colnames(dtm)) != length(1:M)){
stop("colnames(phi)[ 1:M ] are not in colnames(dtm)")
}
pcoh <- function(topic, dtm, M){
terms <- names(topic)[order(topic, decreasing = TRUE)][1:M]
dtm.t <- dtm[, terms]
dtm.t[dtm.t > 0] <- 1
count.mat <- Matrix::t(dtm.t) %*% dtm.t
num.docs <- nrow(dtm)
p.mat <- count.mat/num.docs
result <- sapply(1:(ncol(count.mat) - 1), function(x) {
p.mat[x, (x + 1):ncol(p.mat)]/p.mat[x, x] -
Matrix::diag(p.mat)[(x + 1):ncol(p.mat)]
})
mean(unlist(result), na.rm = TRUE)
}
if( ! is.matrix(phi) ){
return(pcoh(topic = phi, dtm = dtm, M = M))
}
apply(phi, 1, function(x){
pcoh(topic = x, dtm = dtm, M = M)
})
}
semCoh1beta_adapted <- function(mat, M, beta) {
top.words <- apply(beta, 1, order, decreasing=TRUE)[1:M,]
wordlist <- unique(as.vector(top.words))
mat <- mat[,wordlist]
mat = sign(mat)
cross <- tcrossprod(t(mat))
temp <- match(as.vector(top.words),wordlist)
labels <- split(temp, rep(1:nrow(beta), each=M))
sem <- function(ml,cross) {
m <- ml[1]; l <- ml[2]
log(1e-12 + cross[m,l]) - log(cross[l,l])
}
result <- vector(length=nrow(beta))
for(k in 1:nrow(beta)) {
grid <- expand.grid(labels[[k]],labels[[k]])
colnames(grid) <- c("m", "l")
grid <- grid[grid$m > grid$l,]
calc <- apply(grid,1,sem,cross)
result[k] <- sum(calc)
result[k] <- mean(calc, na.rm = TRUE)
}
return(result)
}
tcm_intrinsic = Matrix::crossprod(sign(dtm))
coherence_text2vec = coherence(x = top_terms ,tcm = tcm_intrinsic, n_doc_tcm = nrow(dtm)
,metrics = c("mean_difference", "mean_logratio"))
logratio_stm_adapted = semCoh1beta_adapted(mat = dtm, M = n_top_terms, beta = topic_word_distribution)
mean_difference_textmineR = CalcProbCoherence(phi = topic_word_distribution, dtm = as.matrix(dtm), M = n_top_terms)
compare = cbind(coherence_text2vec, mean_difference_textmineR, logratio_stm_adapted)
expect_equal(sort(compare[,"mean_logratio"]), sort(compare[,"logratio_stm_adapted"]))
expect_equal(sort(compare[,"mean_difference"]), sort(compare[,"mean_difference_textmineR"]))
}) |
color_loon <- function() {
function(x) {
if (!as.numeric(tcl('::loon::listfns::isColor', x))) {
x <- tcl('::loon::listfns::mapColor', x)
}
hex12 <- as.character(tcl('::loon::listfns::toHexcolor', x))
hex12tohex6(hex12)
}
}
loon_palette <- function(n) {
if (length(n) != 1 && !is.numeric(n))
stop("argument n needs to be numeric and of length 1")
as.character(
.Tcl(paste(
'::loon::hcl::hue_mem_pal', n, '{*}$::loon::Options(colors-palette-hcl)'
))
)
}
hex12tohex6 <- function(x) {
col1 <- paste0( "
col2 <- paste0( "
if (!identical(col1, col2)) {
warning(paste("conversion of 12 digit hexadecimal color representation to",
"a 6 digit hexadecimal representation lost information."))
}
col1
}
as_hex6color <- function(color) {
if(length(color) > 0){
col <- vapply(color, function(x) {
if (x == "") "" else l_hexcolor(x)
}, character(1))
col <- suppressWarnings(hex12tohex6(col))
col[color == ""] <- NA
col
} else {
NA
}
}
l_colorName <- function(color, error = TRUE, precise = FALSE) {
color.id <- function(x, error = TRUE, precise = FALSE, env = environment()) {
invalid.color <- c()
colors <- vapply(x,
function(color) {
tryCatch(
expr = {
color <- as_hex6color(color)
c2 <- grDevices::col2rgb(color)
coltab <- grDevices::col2rgb(colors())
cdist <- apply(coltab, 2, function(z) sum((z - c2)^2))
if(precise) {
if(min(cdist) == 0)
colors()[which(cdist == min(cdist))][1]
else
color
} else {
colors()[which(cdist == min(cdist))][1]
}
},
error = function(e) {
assign("invalid.color",
c(invalid.color, color),
envir = env)
return(color)
}
)
}, character(1))
if(error && length(invalid.color) > 0) {
stop("The input " ,
paste(invalid.color, collapse = ", "),
" are not valid color names", call. = FALSE)
}
colors
}
uniColor <- unique(color)
colorName <- color.id(uniColor, error = error, precise = precise)
len <- length(colorName)
for(i in seq(len)) {
color[color == uniColor[i]] <- colorName[i]
}
color
}
l_hexcolor <- function(color) {
as.character(tcl('::loon::listfns::toHexcolor', color))
}
l_colRemoveAlpha <- function (col) {
if(missing(col)) stop("Please provide a vector of colours.")
rgb(t(col2rgb(col)), maxColorValue = 255)
}
l_setColorList <- function(colors) {
tcl('::loon::setColorList', 'custom', colors)
invisible()
}
l_getColorList <- function() {
as.character(tcl('::loon::getColorList'))
}
l_setColorList_ColorBrewer <- function(palette=c("Set1", "Set2", "Set3",
"Pastel1", "Pastel2", "Paired",
"Dark2", "Accent")) {
palette <- match.arg(palette)
tcl('::loon::setColorList', 'ColorBrewer', palette)
invisible()
}
l_setColorList_hcl <- function(chroma=56, luminance=51, hue_start=231) {
tcl('::loon::setColorList', 'hcl', chroma, luminance, hue_start)
invisible()
}
l_setColorList_ggplot2 <- function() {
tcl('::loon::setColorList', 'ggplot2')
invisible()
}
l_setColorList_baseR <- function() {
tcl('::loon::setColorList', 'baseR')
invisible()
}
l_setColorList_loon <- function() {
tcl('::loon::setColorList', 'loon')
invisible()
} |
source("ESEUR_config.r")
library("compositions")
pal_col=rainbow(3)
hcl_col=rainbow_hcl(3)
pt_col=rainbow(2)
est=read.csv(paste0(ESEUR_dir, "projects/EstimationStudy.csv.xz"), as.is=TRUE)
est=subset(est, !is.na(Design_Phase))
phase=acomp(est, parts=c("Design_Phase", "Code_Phase", "Test_Phase"))
plot(phase, col=pt_col[1], labels="", mp=NULL)
ternaryAxis(side=-1:-3, at=seq(0.25, 0.75, 0.25), labels="",
pos=c(0.5,0.5,0.5), col.axis=hcl_col, col.lab=pal_col,
small=TRUE, aspanel=TRUE,
Xlab="Design", Ylab="Code", Zlab="Test")
est$Test_Sched=est$Systest_Sched+est$Acctest_Sched
est=subset(est, !is.na(Design_Sched))
sched=acomp(est, parts=c("Design_Sched", "Code_Sched", "Test_Sched"))
plot(sched, col=pt_col[2], labels="", mp=NULL, add=TRUE) |
datacounts <- function(response, id, repeated, ncategories) {
response <- as.numeric(factor(response))
data <- data.frame(cbind(response, id, repeated))
data <- stats::reshape(data,
v.names = "response", idvar = "id",
timevar = "repeated", direction = "wide"
)
data <- data[, -1]
data[is.na(data)] <- 0
ntimes <- ncol(data)
notimepairs <- choose(ntimes, 2)
counts <- rep.int(0, notimepairs * (ncategories^2))
x <- rep(1:ncategories, each = notimepairs * ncategories)
y <- rep.int(rep(1:ncategories, each = notimepairs), ncategories)
tp <- rep.int(1:notimepairs, ncategories^2)
ind_1 <- 1
for (categ1 in 1:ncategories) {
for (categ2 in 1:ncategories) {
for (ind_2 in 1:(ntimes - 1)) {
for (ind_3 in (ind_2 + 1):ntimes) {
counts[ind_1] <- sum(
(data[, ind_2] == categ1) & (data[, ind_3] == categ2)
)
ind_1 <- ind_1 + 1
}
}
}
}
data <- data.frame(cbind(counts, x, y, tp))
data
}
fitmm <- function(data, marpars, homogeneous, restricted, add) {
LORstr <- marpars$LORstr
LORem <- marpars$LORem
fmla <- marpars$fmla
ncategories <- max(data$x)
timepairs <- max(data$tp)
if (any(data$counts == 0)) {
data$counts <- data$counts + add
}
LORterm <- matrix(0, timepairs, ncategories^2)
if (LORstr == "uniform" | LORstr == "category.exch") {
suppressWarnings(fitted.mod <- gnm::gnm(fmla,
family = poisson, data = data,
verbose = FALSE, model = FALSE
))
if (is.null(fitted.mod)) {
stop("gnm did not converge algorithm")
}
coefint <- as.vector(coef(fitted.mod)[gnm::pickCoef(fitted.mod, "x:y")])
if (LORem == "2way") {
coefint <- mean(coefint)
}
LORterm <- matrix(coefint, timepairs, ncategories^2)
LORterm <- t(apply(
LORterm, 1,
function(x) exp(x * tcrossprod(1:ncategories))
))
}
if (LORstr == "time.exch") {
data$x <- factor(data$x)
data$y <- factor(data$y)
if (is.null(restricted)) {
if (LORem == "3way") {
if (homogeneous) {
suppressWarnings(fitted.mod <- gnm::gnm(fmla,
family = poisson,
data = data, verbose = FALSE,
model = FALSE
))
if (is.null(fitted.mod)) {
stop("gnm did not converge algorithm")
}
coefint <- as.vector(coef(fitted.mod)[gnm::pickCoef(
fitted.mod,
"MultHomog"
)])
coefint <- c(tcrossprod(coefint))
} else {
suppressWarnings(fitted.mod <- gnm::gnm(fmla,
family = poisson,
data = data, verbose = FALSE,
model = FALSE
))
if (is.null(fitted.mod)) {
stop("gnm did not converge algorithm")
}
coefint <- as.vector(coef(fitted.mod)[gnm::pickCoef(
fitted.mod,
"Mult"
)])
coefint <- c(tcrossprod(
coefint[-c(1:ncategories)],
coefint[1:ncategories]
))
}
LORterm <- exp(matrix(coefint,
nrow = timepairs,
ncol = ncategories^2, TRUE
))
} else {
LORterm2 <- LORterm
for (i in 1:timepairs) {
datamar <- data[data$tp == i, ]
suppressWarnings(fitted.mod <- gnm::gnm(fmla,
family = poisson,
data = datamar, verbose = FALSE,
model = FALSE
))
if (homogeneous) {
coefint <- as.vector(coef(fitted.mod)[gnm::pickCoef(
fitted.mod,
"MultHomog"
)])
coefint <- c(tcrossprod(coefint))
} else {
coefint <- as.vector(coef(fitted.mod)[gnm::pickCoef(
fitted.mod,
"Mult"
)])
coefint <- c(tcrossprod(
coefint[1:ncategories],
coefint[-c(1:ncategories)]
))
}
LORterm2[i, ] <- coefint
}
LORterm2 <- colMeans(LORterm2)
LORterm <- exp(matrix(
LORterm2, timepairs, ncategories^2,
TRUE
))
}
} else {
if (LORem == "3way") {
if (homogeneous) {
coefint <- RRChomog(fmla, data, ncategories)
} else {
coefint <- RRCheter(fmla, data, ncategories)
}
LORterm <- exp(matrix(coefint,
nrow = timepairs,
ncol = ncategories^2, TRUE
))
} else {
LORterm2 <- LORterm
for (i in 1:timepairs) {
datamar <- data[data$tp == i, ]
if (homogeneous) {
coefint <- RRChomog(fmla, datamar, ncategories)
} else {
coefint <- RRCheter(fmla, datamar, ncategories)
}
LORterm2[i, ] <- coefint
}
LORterm2 <- colMeans(LORterm2)
LORterm <- exp(matrix(
LORterm2, timepairs, ncategories^2,
TRUE
))
}
}
}
if (LORstr == "RC") {
data$x <- factor(data$x)
data$y <- factor(data$y)
for (i in 1:timepairs) {
datamar <- data[data$tp == i, ]
suppressWarnings(fitted.mod <- gnm::gnm(fmla,
family = poisson,
data = datamar, verbose = FALSE,
model = FALSE
))
if (is.null(restricted)) {
if (homogeneous) {
coefint <- as.vector(coef(fitted.mod)[gnm::pickCoef(
fitted.mod,
"MultHomog"
)])
coefint <- c(tcrossprod(coefint))
} else {
coefint <- as.vector(coef(fitted.mod)[gnm::pickCoef(
fitted.mod,
"Mult"
)])
coefint <- c(tcrossprod(
coefint[1:ncategories],
coefint[-c(1:ncategories)]
))
}
} else {
coefint <- if (homogeneous) {
RRChomog(fmla, datamar, ncategories)
} else {
RRCheter(fmla, datamar, ncategories)
}
}
LORterm[i, ] <- exp(coefint)
}
}
LORterm <- prop.table(LORterm, 1)
LORterm
}
mmpar <- function(LORem, LORstr, timepairs, homogeneous) {
if (timepairs == 1) {
LORem <- "2way"
LORstr <- switch(LORstr, category.exch = "uniform", RC = "time.exch",
uniform = "uniform", time.exch = "time.exch"
)
if (LORstr == "uniform") {
fmla <- counts ~ factor(x) + factor(y) + x:y
}
if (LORstr == "time.exch") {
fmla <- if (homogeneous) {
counts ~ x + y + MultHomog(x, y)
} else {
counts ~ x + y + Mult(x, y)
}
}
} else if (LORem == "2way") {
if (LORstr == "uniform") {
fmla <-
counts ~ (factor(x) + factor(y)) * factor(tp) + factor(tp):x:y
}
if (LORstr == "time.exch" | LORstr == "RC") {
fmla <- if (homogeneous) {
counts ~ x + y + MultHomog(x, y)
} else {
counts ~ x + y + Mult(x, y)
}
}
} else {
if (LORstr == "category.exch") {
fmla <-
counts ~ (factor(x) + factor(y)) * factor(tp) + factor(tp):x:y
}
if (LORstr == "uniform") {
fmla <- counts ~ (factor(x) + factor(y)) * factor(tp) + x:y
}
if (LORstr == "time.exch") {
fmla <- if (homogeneous) {
counts ~ (x + y) * factor(tp) + MultHomog(x, y)
} else {
counts ~ (x + y) * factor(tp) + Mult(x, y)
}
}
}
list(LORem = LORem, LORstr = LORstr, fmla = fmla)
}
RCconstrains <- function(ncategories, homogeneous) {
ncategories1 <- ncategories - 1
nodf <- helpvec <- rep.int(0, ncategories1)
for (i in 1:(ncategories1 - 1)) {
helpmat <- t(combn(c(1:ncategories1), i))
for (j in seq_len(nrow(helpmat))) {
helpvec <- rep.int(0, ncategories1)
helpvec[helpmat[j, ]] <- 1
nodf <- rbind(nodf, helpvec)
}
}
nodf <- unique(nodf)
n1 <- nrow(nodf)
parscores <- matrix(1:ncategories,
nrow = n1, ncol = ncategories,
byrow = TRUE
)
for (j in 1:ncategories1) {
parscores[nodf[, j] == 1, j + 1] <- parscores[nodf[, j] == 1, j]
}
parscores <- t(apply(parscores, 1, function(x) as.numeric(factor(x))))
ans <- list(parscores = parscores, nodf = as.numeric(rowSums(nodf)))
if (!homogeneous) {
Homogeneous <- ans
n1 <- length(Homogeneous$nodf)
parscores <- cbind(
apply(Homogeneous$parscores, 2, function(x) rep.int(x, n1)),
apply(Homogeneous$parscores, 2, function(x) rep(x, each = n1))
)
nodf <- rep(Homogeneous$nodf, each = n1) + rep.int(
Homogeneous$nodf,
n1
)
orderedindices <- order(nodf)
ans <- list(
parscores = parscores[orderedindices, ],
nodf = nodf[orderedindices]
)
}
ans
}
RRCheter <- function(fmla, data, ncategories) {
Consmat <- RCconstrains(ncategories, FALSE)
dev <- stop.constrains <- Inf
datax <- factor(data$x)
datay <- factor(data$y)
maxcategory <- nlevels(datax)
noglm <- length(Consmat$nodf[Consmat$nodf < 2 * (maxcategory - 2)])
fmla <- update(fmla, ~ . - Mult(x, y) + Mult(z1, z2))
for (i in 1:noglm) {
data$z1 <- datax
data$z2 <- datay
levels(data$z1) <- pickcoefindz1 <-
Consmat$parscores[i, 1:maxcategory]
levels(data$z2) <- pickcoefindz2 <-
Consmat$parscores[i, - (1:maxcategory)]
RRCmod <- suppressWarnings(gnm::gnm(fmla,
data = data, family = poisson,
verbose = FALSE, model = FALSE
))
if (!is.null(RRCmod)) {
if (deviance(RRCmod) < dev & RRCmod$conv) {
scores <- as.numeric(coef(RRCmod)[pickCoef(RRCmod, "Mult")])
pickcoefind <- unique(pickcoefindz1)
scoresmu <- scores[pickcoefind][pickcoefindz1]
mu <- normscores(scoresmu)
if (all(diff(mu) >= 0) | all(diff(mu) <= 0)) {
scoresnu <- scores[-pickcoefind][pickcoefindz2]
nu <- normscores(scoresnu)
if (all(diff(nu) >= 0) | all(diff(nu) <= 0)) {
dev <- deviance(RRCmod)
stop.constrains <- Consmat$nodf[i]
LORterm <- c(tcrossprod(scoresmu, scoresnu))
}
}
}
}
if (stop.constrains < Consmat$nodf[i + 1]) {
break
}
}
if (!is.finite(dev)) {
fmla <- update(fmla, ~ . - Mult(z1, z2) + x1:x2)
for (i in (noglm + 1):length(Consmat$nodf)) {
datax1 <- datax
datay1 <- datay
levels(datax1) <- pickcoefindz1 <-
Consmat$parscores[i, 1:maxcategory]
levels(datay1) <- pickcoefindz2 <- Consmat$parscores[i, - (1:maxcategory)]
data$x1 <- as.numeric(datax1)
data$x2 <- as.numeric(datay1)
RRCmod <- suppressWarnings(glm(fmla, data = data, family = poisson))
if (deviance(RRCmod) < dev & RRCmod$conv) {
LORterm <- c(tcrossprod(pickcoefindz1, pickcoefindz2) *
as.numeric(RRCmod$coef["x1:x2"]))
}
}
}
if (!is.finite(dev)) {
LORterm <- rep(0, nlevels(datax)^2)
}
LORterm
}
RRChomog <- function(fmla, data, ncategories) {
Consmat <- RCconstrains(ncategories, TRUE)
datax <- factor(data$x)
datay <- factor(data$y)
dev <- stop.constrains <- Inf
noglm <- length(Consmat$nodf[Consmat$nodf < (nlevels(datax) - 2)])
fmla <- update(fmla, ~ . - MultHomog(x, y) + MultHomog(z1, z2))
for (i in 1:noglm) {
data$z1 <- datax
data$z2 <- datay
levels(data$z1) <- levels(data$z2) <- pickcoefind <-
Consmat$parscores[i, ]
suppressWarnings(RRCmod <- gnm::gnm(fmla,
family = poisson, data = data,
verbose = FALSE, model = FALSE
))
if (!is.null(RRCmod)) {
if (deviance(RRCmod) < dev & RRCmod$conv) {
pickcoef <- gnm::pickCoef(RRCmod, "MultHomog(.,.)")
scores <- as.numeric(coef(RRCmod)[pickcoef])[pickcoefind]
mu <- normscores(scores)
if (all(diff(mu) >= 0) | all(diff(mu) <= 0)) {
dev <- deviance(RRCmod)
LORterm <- c(tcrossprod(scores))
if (Consmat$nodf[i] < Consmat$nodf[i + 1]) {
break
}
}
}
}
if (stop.constrains < Consmat$nodf[i + 1]) {
break
}
}
if (!is.finite(dev)) {
fmla <- update(fmla, ~ . - MultHomog(z1, z2) + x1:x2)
data$x1 <- as.numeric(datax1)
data$x2 <- as.numeric(datay1)
for (i in (noglm + 1):length(Consmat$nodf)) datax1 <- datax
datay1 <- datay
levels(datax1) <- levels(datay1) <- pickcoefind <-
Consmat$parscores[i, ]
RRCmod <- suppressWarnings(glm(fmla,
data = data, family = poisson,
verbose = FALSE, model = FALSE
))
if (deviance(RRCmod) < dev & RRCmod$conv) {
LORterm <- c(tcrossprod(pickcoefind) *
as.numeric(RRCmod$coef["x1:x2"]))
}
}
if (!is.finite(dev)) {
LORterm <- rep(0, nlevels(datax)^2)
}
LORterm
} |
Falco_GP_C <- function(train, test, population_size=200, max_generations=200, max_deriv_size=20, rec_prob=0.8, mut_prob=0.1, copy_prob=0.01, alpha=0.9, seed=-1){
alg <- RKEEL::R6_Falco_GP_C$new()
alg$setParameters(train, test, population_size, max_generations, max_deriv_size, rec_prob, mut_prob, copy_prob, alpha, seed)
return (alg)
}
R6_Falco_GP_C <- R6::R6Class("R6_Falco_GP_C",
inherit = ClassificationAlgorithm,
public = list(
population_size = 200,
max_generations = 200,
max_deriv_size = 20,
rec_prob = 0.8,
mut_prob = 0.1,
copy_prob = 0.01,
alpha = 0.9,
seed = -1,
setParameters = function(train, test,
population_size=200, max_generations=200,
max_deriv_size=20, rec_prob=0.8, mut_prob=0.1,
copy_prob=0.01, alpha=0.9, seed=-1){
super$setParameters(train, test)
stopText <- ""
if((hasMissingValues(train)) || (hasMissingValues(test))){
stopText <- paste0(stopText, "Dataset has missing values and the algorithm does not accept it.\n")
}
if(stopText != ""){
stop(stopText)
}
self$population_size <- population_size
self$max_generations <- max_generations
self$max_deriv_size <- max_deriv_size
self$rec_prob <- rec_prob
self$mut_prob <- mut_prob
self$copy_prob <- copy_prob
self$alpha <- alpha
if(seed == -1) {
self$seed <- sample(1:1000000, 1)
}
else {
self$seed <- seed
}
}
),
private = list(
jarName = "Falco_GP.jar",
algorithmName = "Falco_GP-C",
algorithmString = "Falco_GP",
getParametersText = function(){
text <- ""
text <- paste0(text, "seed = ", self$seed, "\n")
text <- paste0(text, "population-size = ", self$population_size, "\n")
text <- paste0(text, "max-generations = ", self$max_generations, "\n")
text <- paste0(text, "max-deriv-size = ", self$max_deriv_size, "\n")
text <- paste0(text, "rec-prob = ", self$rec_prob, "\n")
text <- paste0(text, "mut-prob = ", self$mut_prob, "\n")
text <- paste0(text, "copy-prob = ", self$copy_prob, "\n")
text <- paste0(text, "alpha = ", self$alpha, "\n")
return(text)
}
)
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.