code
stringlengths 1
13.8M
|
---|
if (Sys.getenv("POSTGRES_USER") != "" & Sys.getenv("POSTGRES_HOST") != "" & Sys.getenv("POSTGRES_DATABASE") != "") {
stopifnot(require(RPostgreSQL))
stopifnot(require(datasets))
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv,
user=Sys.getenv("POSTGRES_USER"),
password=Sys.getenv("POSTGRES_PASSWD"),
host=Sys.getenv("POSTGRES_HOST"),
dbname=Sys.getenv("POSTGRES_DATABASE"),
port=ifelse((p<-Sys.getenv("POSTGRES_PORT"))!="", p, 5432))
if (dbExistsTable(con, "rock.data")) {
cat("Removing rock'data\n")
dbRemoveTable(con, "rock.data")
}
dbWriteTable(con, "rock.data", rock)
cat("Does rock.data exist? \n")
res <- dbExistsTable(con, "rock.data")
if(res){
cat("PASS: true\n")
}else{
cat("FAIL: false\n")
}
cat("create schema testschema and change the search_path\n")
dbGetQuery(con, 'CREATE SCHEMA testschema')
dbGetQuery(con, 'SET search_path TO testschema')
cat("Does rock.data exist? \n")
res <- dbExistsTable(con, "rock.data")
if(res){
cat("FAIL: true despite search_path change\n")
}else{
cat("PASS: false as the search_path changed\n")
}
cat("Does testschema.\"rock.data\" exist? \n")
res <- dbExistsTable(con, c('testschema', "rock.data"))
if(res){
cat("FAIL: true despite testschema specified\n")
}else{
cat("PASS: false as the testschema specified\n")
}
cat("Does public.\"rock.data\" exist? \n")
res <- dbExistsTable(con, c('public', "rock.data"))
if(res){
cat("PASS: true despite search_path change\n")
}else{
cat("FAIL: false as the search_path changed\n")
}
cat("write in current schema\n")
dbWriteTable(con, "rock.data", rock)
cat("Does rock.data exist? \n")
res <- dbExistsTable(con, "rock.data")
if(res){
cat("PASS: true\n")
}else{
cat("FAIL: false\n")
}
dbGetQuery(con, 'DROP TABLE "public"."rock.data"')
dbGetQuery(con, 'DROP TABLE "testschema"."rock.data"')
dbGetQuery(con, 'DROP schema "testschema"')
dbDisconnect(con)
} |
dataset_sbb<-function(NUM){
sbb<-rep(0,NUM)
for (i in 1:NUM){
W<-rwiener()
V2<-W+(2*(1:1000)/1000-3*((1:1000)^2)/(1000^2))*W[1000]+(6*((1:1000)^2/(1000^2))-6*(1:1000)/1000)*sum(W)/1000
sbb[i]<-sum(V2^2)/1000
}
return(sbb)
} |
p <- position(c(a = 1, b = 2))
as.data.frame(p)
p <- position(1:2, instrument = c("Equity 1", "Equity 2"))
as.data.frame(p) |
BayesianMass <- function(lambda,r,n){
if(n<=1){
stop('error in Bayesian Mass\n')
}else{
Card=c(0,1);
for(i in 1:(n-1)){
Card=c(Card,(Card+1));
}
}
Card[1]=1;
mt=lambda*(1/Card)^r;
mt[1]=0;
md=mt/sum(mt);
return(md)
} |
srktie_d <- function(n,alpha,eps1,eps2,d) {
u_pl <- 0
for (i in 1:(n-1))
for (j in (i+1):n)
u_pl <- u_pl + trunc(0.5*(sign(d[i]+d[j]) + 1))
u_pl <- u_pl*2/n/(n-1)
u_0 <- 0
for (i in 1:(n-1))
for (j in (i+1):n)
u_0 <- u_0 + 1 - (sign(abs(d[i]+d[j])))
u_0 <- u_0*2/n/(n-1)
qh_pl <- 0
for (i in 1:(n-2))
for (j in (i+1):(n-1))
for (k in (j+1):n)
qh_pl <- qh_pl + trunc(0.5*(sign(min(d[i]+d[j],d[i]+d[k])) + 1)) +
trunc(0.5*(sign(min(d[j]+d[i],d[j]+d[k])) + 1)) +
trunc(0.5*(sign(min(d[k]+d[i],d[k]+d[j])) + 1))
qh_pl <- qh_pl*2/n/(n-1)/(n-2)
qh_0 <- 0
for (i in 1:(n-2))
for (j in (i+1):(n-1))
for (k in (j+1):n)
qh_0 <- qh_0 + 1 - sign(max(abs(d[i]+d[j]),abs(d[i]+d[k]))) +
1 - sign(max(abs(d[i]+d[j]),abs(d[j]+d[k]))) +
1 - sign(max(abs(d[i]+d[k]),abs(d[j]+d[k])))
qh_0 <- qh_0*2/n/(n-1)/(n-2)
qh_0pl <- 0
for (i in 1:(n-2))
for (j in (i+1):(n-1))
for (k in (j+1):n)
qh_0pl <- qh_0pl + trunc(0.5*(sign(d[i]+d[j])+1)) * (1-sign(abs(d[i]+d[k]))) +
trunc(0.5*(sign(d[i]+d[j])+1)) * (1-sign(abs(d[j]+d[k]))) +
trunc(0.5*(sign(d[i]+d[k])+1)) * (1-sign(abs(d[j]+d[k]))) +
trunc(0.5*(sign(d[i]+d[k])+1)) * (1-sign(abs(d[i]+d[j]))) +
trunc(0.5*(sign(d[j]+d[k])+1)) * (1-sign(abs(d[i]+d[j]))) +
trunc(0.5*(sign(d[j]+d[k])+1)) * (1-sign(abs(d[i]+d[k])))
qh_0pl <- qh_0pl/n/(n-1)/(n-2)
ssq_pl <- (4*(n-2)/(n-1)) * (qh_pl-u_pl**2) + (2/(n-1))*u_pl*(1-u_pl)
ssq_0 <- (4*(n-2)/(n-1)) * (qh_0-u_0**2) + (2/(n-1))*u_0*(1-u_0)
ss_0pl <- (4*(n-2)/(n-1)) * (qh_0pl-u_0*u_pl) + (2/(n-1))*u_0*u_pl
tauhsqas <- ssq_pl/(1-u_0)**2 + u_pl**2*ssq_0/(1-u_0)**4 + 2*u_pl*ss_0pl/(1-u_0)**3
uas_pl <- u_pl/(1-u_0)
eqctr <- (1-eps1+eps2)/2
tauhas <- sqrt(tauhsqas)
crit <- sqrt(qchisq(alpha,1,n*(eps1+eps2)**2/4/tauhsqas))
if (sqrt(n)*abs((uas_pl-eqctr)/tauhas) >= crit) rej <- 0
if (sqrt(n)*abs((uas_pl-eqctr)/tauhas) < crit) rej <- 1
if (is.na(tauhas) || is.na(crit)) rej <- 0
cat(" n =",n," alpha =",alpha," eps1 =",eps1," eps2 =",eps2,
" U_PL =",u_pl," U_0 =",u_0," UAS_PL =",uas_pl," TAUHAS =",tauhas,
" CRIT =",crit," REJ =",rej)
} |
.onAttach <- function(libname, pkgname) {
if (stats::runif(1) > .8) {
packageStartupMessage("Learn more about sjPlot with 'browseVignettes(\"sjPlot\")'.")
} else if (stats::runif(1) > .8) {
packageStartupMessage("Install package \"strengejacke\" from GitHub (`devtools::install_github(\"strengejacke/strengejacke\")`) to load all sj-packages at once!")
} else if (stats::runif(1) > .8) {
packageStartupMessage("
}
} |
"margex" |
"metadata_large_example" |
print.poLCA <-
function(x, ...) {
R <- length(x$P)
S <- ifelse(is.na(x$coeff[1]),1,nrow(x$coeff))
cat("Conditional item response (column) probabilities,\n by outcome variable, for each class (row) \n \n")
print(lapply(x$probs,round,4))
cat("Estimated class population shares \n", round(x$P,4), "\n \n")
cat("Predicted class memberships (by modal posterior prob.) \n",round(table(x$predclass)/x$N,4), "\n \n")
cat("========================================================= \n")
cat("Fit for", R, "latent classes: \n")
cat("========================================================= \n")
if (S>1) {
for (r in 2:R) {
cat(r,"/ 1 \n")
disp <- data.frame(coeff=round(x$coeff[,(r-1)],5),
se=round(x$coeff.se[,(r-1)],5),
tval=round(x$coeff[,(r-1)]/x$coeff.se[,(r-1)],3),
pr=round(1-(2*abs(pt(x$coeff[,(r-1)]/x$coeff.se[,(r-1)],x$resid.df)-0.5)),3))
colnames(disp) <- c("Coefficient"," Std. error"," t value"," Pr(>|t|)")
print(disp)
cat("========================================================= \n")
}
}
cat("number of observations:", x$N, "\n")
if(x$N != x$Nobs) cat("number of fully observed cases:", x$Nobs, "\n")
cat("number of estimated parameters:", x$npar, "\n")
cat("residual degrees of freedom:", x$resid.df, "\n")
cat("maximum log-likelihood:", x$llik, "\n \n")
cat("AIC(",R,"): ",x$aic,"\n",sep="")
cat("BIC(",R,"): ",x$bic,"\n",sep="")
if (S==1) cat("G^2(",R,"): ",x$Gsq," (Likelihood ratio/deviance statistic) \n",sep="")
cat("X^2(",R,"): ",x$Chisq," (Chi-square goodness of fit) \n \n",sep="")
if (x$numiter==x$maxiter) cat("ALERT: iterations finished, MAXIMUM LIKELIHOOD NOT FOUND \n \n")
if (!x$probs.start.ok) cat("ALERT: error in user-specified starting values; new start values generated \n \n")
if (x$npar>x$N) cat("ALERT: number of parameters estimated (",x$npar,") exceeds number of observations (",x$N,") \n \n")
if (x$resid.df<0) cat("ALERT: negative degrees of freedom; respecify model \n \n")
if (x$eflag) cat("ALERT: estimation algorithm automatically restarted with new initial values \n \n")
flush.console()
invisible(x)
} |
getPeakVec <- function(peakData = c(10, 100), StartDate = "2020-03-03", EndDate = "2020-06-24") {
observedPeriod <- 1 + as.numeric(as.Date(EndDate) - as.Date(StartDate))
v <- rep(0, observedPeriod)
n <- length(peakData) / 2
for (i in 1:n) {
v[peakData[2 * i - 1]] <- peakData[2 * i]
}
return(v)
} |
merge.tbl_tree <- function(x, y, ...) {
res <- NextMethod()
class(res) <- class(x)
return(res)
} |
library(testthat)
context("ConditionalSet")
test_that("construction", {
expect_silent(ConditionalSet$new(function(x) x == 0))
expect_equal(ConditionalSet$new(function(x) x == 0)$lower, NA)
expect_equal(ConditionalSet$new(function(x) x == 0)$upper, NA)
expect_equal(ConditionalSet$new(function(x) x == 0)$min, NaN)
expect_equal(ConditionalSet$new(function(x) x == 0)$max, NaN)
expect_error(ConditionalSet$new(function(x) x), "'condition' should result")
expect_error(ConditionalSet$new(1), "'condition' must be")
expect_silent(ConditionalSet$new(function(x, y) x + y == 0))
expect_silent(ConditionalSet$new(function(x) TRUE, list(x = Reals$new())))
expect_error(ConditionalSet$new(function(x) TRUE, list(x = Reals)))
})
test_that("contains", {
c <- ConditionalSet$new(function(x, y) x + y == 0)
expect_true(c$contains(Set$new(2, -2)))
expect_true(c$contains(Tuple$new(0, 0)))
expect_false(c$contains(Set$new(1, 2)))
expect_error(c$contains(Set$new(1)), "Set is of length")
expect_equal(c$contains(list(Set$new(0, 1), Set$new(-1, 1))), c(FALSE, TRUE))
expect_false(c$contains(list(Set$new(0, 1), Set$new(-1, 1)), all = TRUE))
expect_true(c$contains(list(Set$new(2, -2), Set$new(-1, 1)), all = TRUE))
expect_error(c$contains(list(Set$new(1), Set$new(1, 1))))
expect_true(ConditionalSet$new(function(x) x == 0)$contains(0))
expect_false(ConditionalSet$new(function(x) x == 0)$contains(1))
})
test_that("equals", {
c1 <- ConditionalSet$new(function(x, y) x + y == 0)
c2 <- ConditionalSet$new(function(z, q) z + q == 0)
c3 <- ConditionalSet$new(function(x, y) x + y == 0)
c4 <- ConditionalSet$new(function(x, y) x == 0)
c5 <- ConditionalSet$new(function(x, y) x + y == 0, argclass = list(x = Complex$new()))
expect_true(c1 == c2)
expect_true(c1 == c3)
expect_true(c1 != c4)
expect_true(c1 != c5)
expect_false(c1 == Set$new())
expect_true(ConditionalSet$new(function(x, y) x == 0) == ConditionalSet$new(function(z) z == 0))
expect_true(ConditionalSet$new(function(z) z == 0) == ConditionalSet$new(function(x, y) x == 0))
})
test_that("strprint", {
useUnicode(TRUE)
expect_equal(ConditionalSet$new(function(x) TRUE)$strprint(), "{x \u2208 \U1D54D}")
useUnicode(FALSE)
expect_equal(ConditionalSet$new(function(x) TRUE)$strprint(), "{x in V}")
useUnicode(TRUE)
})
test_that("summary", {
expect_output(expect_equal(ConditionalSet$new(function(x) TRUE)$summary(), ConditionalSet$new(function(x) TRUE)$print()))
})
test_that("isSubset", {
expect_message(ConditionalSet$new(function(x) TRUE)$isSubset(Set$new(1)), "undefined")
expect_message(ConditionalSet$new(function(x) TRUE)$isSubset(1), "undefined")
})
test_that("fields", {
c <- ConditionalSet$new(function(x) TRUE)
expect_equal(c$condition, function(x) TRUE)
expect_equal(c$class, list(x = Universal$new()))
expect_equal(c$elements, NA)
}) |
Spatial <- function(bbox, proj4string = CRS(as.character(NA))) {
new("Spatial", bbox=bbox, proj4string=proj4string)
}
if (!isGeneric("addAttrToGeom"))
setGeneric("addAttrToGeom", function(x, y, match.ID, ...)
standardGeneric("addAttrToGeom"))
if (!isGeneric("bbox"))
setGeneric("bbox", function(obj)
standardGeneric("bbox"))
if (!isGeneric("coordinates"))
setGeneric("coordinates", function(obj, ...)
standardGeneric("coordinates"))
if (!isGeneric("coordinates<-"))
setGeneric("coordinates<-", function(object, value)
standardGeneric("coordinates<-"))
if (!isGeneric("coordnames"))
setGeneric("coordnames", function(x)
standardGeneric("coordnames"))
if (!isGeneric("coordnames<-"))
setGeneric("coordnames<-", function(x,value)
standardGeneric("coordnames<-"))
if (!isGeneric("dimensions"))
setGeneric("dimensions", function(obj)
standardGeneric("dimensions"))
if (!isGeneric("fullgrid"))
setGeneric("fullgrid", function(obj)
standardGeneric("fullgrid"))
if (!isGeneric("fullgrid<-"))
setGeneric("fullgrid<-", function(obj, value)
standardGeneric("fullgrid<-"))
if (!isGeneric("geometry"))
setGeneric("geometry", function(obj)
standardGeneric("geometry"))
if (!isGeneric("geometry<-"))
setGeneric("geometry<-", function(obj, value)
standardGeneric("geometry<-"))
if (!isGeneric("gridded"))
setGeneric("gridded", function(obj)
standardGeneric("gridded"))
if (!isGeneric("gridded<-"))
setGeneric("gridded<-", function(obj, value)
standardGeneric("gridded<-"))
if (!isGeneric("is.projected"))
setGeneric("is.projected", function(obj)
standardGeneric("is.projected"))
if (!isGeneric("over"))
setGeneric("over", function(x, y, returnList = FALSE, fn = NULL, ...)
standardGeneric("over"))
if (!isGeneric("plot"))
setGeneric("plot", function(x, y, ...)
standardGeneric("plot"))
if (!isGeneric("polygons"))
setGeneric("polygons", function(obj)
standardGeneric("polygons"))
if (!isGeneric("polygons<-"))
setGeneric("polygons<-", function(object, value)
standardGeneric("polygons<-"))
if (!isGeneric("proj4string"))
setGeneric("proj4string", function(obj)
standardGeneric("proj4string"))
if (!isGeneric("proj4string<-"))
setGeneric("proj4string<-", function(obj, value)
standardGeneric("proj4string<-"))
if (!isGeneric("sppanel"))
setGeneric("sppanel", function(obj, ...)
standardGeneric("sppanel"))
if (!isGeneric("spplot"))
setGeneric("spplot", function(obj, ...)
standardGeneric("spplot"))
if (!isGeneric("spsample"))
setGeneric("spsample", function(x, n, type, ...)
standardGeneric("spsample"))
if (!isGeneric("summary"))
setGeneric("summary", function(object, ...)
standardGeneric("summary"))
if (!isGeneric("spChFIDs"))
setGeneric("spChFIDs", function(obj, x)
standardGeneric("spChFIDs"))
if (!isGeneric("spChFIDs<-"))
setGeneric("spChFIDs<-", function(obj, value)
standardGeneric("spChFIDs<-"))
if (!isGeneric("surfaceArea"))
setGeneric("surfaceArea", function(m, ...)
standardGeneric("surfaceArea"))
if (!isGeneric("split"))
setGeneric("split", function(x, f, drop = FALSE, ...)
standardGeneric("split"))
if (!isGeneric("spTransform"))
setGeneric("spTransform", function(x, CRSobj, ...)
standardGeneric("spTransform"))
setMethod("spTransform", signature("Spatial", "CRS"),
function(x, CRSobj, ...) {
if (!requireNamespace("rgdal", quietly = TRUE))
stop("package rgdal is required for spTransform methods")
spTransform(x, CRSobj, ...)
}
)
setMethod("spTransform", signature("Spatial", "character"),
function(x, CRSobj, ...) spTransform(x, CRS(CRSobj), ...)
)
setMethod("spTransform", signature("Spatial", "ANY"),
function(x, CRSobj, ...) stop("second argument needs to be of class CRS")
)
bbox.default <- function(obj) {
is_points <- function(obj) {
is <- FALSE
if(is.array(obj))
if(length(dim(obj))==2)
if(dim(obj)[2]>=2) is <- TRUE
is
}
if(!is_points(obj))stop('object not a >= 2-column array')
xr <- range(obj[,1],na.rm=TRUE)
yr <- range(obj[,2],na.rm=TRUE)
res <- rbind(x=xr, y=yr)
colnames(res) <- c("min","max")
res
}
setMethod("bbox", "ANY", bbox.default)
setMethod("bbox", "Spatial", function(obj) obj@bbox)
setMethod("dimensions", "Spatial", function(obj) nrow(bbox(obj)))
setMethod("polygons", "Spatial", function(obj) {
if (is(obj, "SpatialPolygons"))
as(obj, "SpatialPolygons")
else
stop("polygons method only available for objects of class or deriving from SpatialPolygons")
}
)
summary.Spatial = function(object, ...) {
obj = list()
obj[["class"]] = class(object)
obj[["bbox"]] = bbox(object)
obj[["is.projected"]] = is.projected(object)
obj[["proj4string"]] = object@proj4string@projargs
if (is(object, "SpatialPoints"))
obj[["npoints"]] = nrow(object@coords)
if (is(object, "SpatialGrid") || is(object, "SpatialPixels"))
obj[["grid"]] = gridparameters(object)
if ("data" %in% slotNames(object) && ncol(object@data) > 0)
obj[["data"]] = summary(object@data)
class(obj) = "summary.Spatial"
obj
}
setMethod("summary", "Spatial", summary.Spatial)
print.summary.Spatial = function(x, ...) {
cat(paste("Object of class ", x[["class"]], "\n", sep = ""))
cat("Coordinates:\n")
print(x[["bbox"]], ...)
cat(paste("Is projected:", x[["is.projected"]], "\n"))
pst <- paste(strwrap(x[["proj4string"]]), collapse="\n")
if (nchar(pst) < 40) cat(paste("proj4string : [", pst, "]\n", sep=""))
else cat(paste("proj4string :\n[", pst, "]\n", sep=""))
if (!is.null(x$npoints)) {
cat("Number of points: ")
cat(x$npoints)
cat("\n")
}
if (!is.null(x$n.polygons)) {
cat("Number of polygons: ")
cat(x$n.polygons)
cat("\n")
}
if (!is.null(x$grid)) {
cat("Grid attributes:\n")
print(x$grid, ...)
}
if (!is.null(x$data)) {
cat("Data attributes:\n")
print(x$data, ...)
}
invisible(x)
}
bb2merc = function(x, cls = "ggmap") {
WGS84 = CRS("+init=epsg:4326")
merc = CRS("+init=epsg:3857")
if (cls == "ggmap") {
b = sapply(attr(x, "bb"), c)
pts = cbind(c(b[2],b[4]),c(b[1],b[3]))
} else if (cls == "RgoogleMaps")
pts = rbind(x$BBOX$ll, x$BBOX$ur)[,2:1]
else
stop("unknown cls")
bbox(spTransform(SpatialPoints(pts, WGS84), merc))
}
plot.Spatial <- function(x, xlim = NULL, ylim = NULL,
asp = NA, axes = FALSE, bg = par("bg"), ...,
xaxs, yaxs, lab, setParUsrBB = FALSE, bgMap = NULL, expandBB = c(0,0,0,0)) {
bbox <- bbox(x)
expBB = function(lim, expand) c(lim[1] - expand[1] * diff(lim), lim[2] + expand[2] * diff(lim))
if (is.null(xlim))
xlim <- expBB(bbox[1,], expandBB[c(2,4)])
if (is.null(ylim))
ylim <- expBB(bbox[2,], expandBB[c(1,3)])
if (is.na(asp))
asp <- ifelse(is.na(slot(slot(x, "proj4string"), "projargs")) || is.projected(x), 1.0,
1/cos((mean(ylim) * pi)/180))
plot.new()
args = list(xlim = xlim, ylim = ylim, asp = asp)
if (!missing(xaxs)) args$xaxs = xaxs
if (!missing(yaxs)) args$yaxs = yaxs
if (!missing(lab)) args$lab = lab
do.call(plot.window, args)
if (setParUsrBB)
par(usr=c(xlim, ylim))
pl_reg <- par("usr")
rect(xleft=pl_reg[1], ybottom=pl_reg[3], xright=pl_reg[2],
ytop=pl_reg[4], col=bg, border=FALSE)
if (axes) {
box()
if (identical(is.projected(x), FALSE)) {
degAxis(1, ...)
degAxis(2, ...)
} else {
axis(1, ...)
axis(2, ...)
}
}
localTitle <- function(..., col, bg, pch, cex, lty, lwd) title(...)
localTitle(...)
if (!is.null(bgMap)) {
is3875 = function(x) length(grep("+init=epsg:3857", x@proj4string@projargs)) > 0
mercator = FALSE
if (is(bgMap, "ggmap")) {
bb = bb2merc(bgMap, "ggmap")
mercator = TRUE
} else if (all(c("lat.center","lon.center","zoom","myTile","BBOX") %in% names(bgMap))) {
bb = bb2merc(bgMap, "RgoogleMaps")
bgMap = bgMap$myTile
mercator = TRUE
} else
bb = rbind(xlim, ylim)
if (mercator && !is3875(x))
warning(paste('CRS of plotting object differs from that of bgMap, which is assumed to be CRS("+init=epsg:3857")'))
rasterImage(bgMap, bb[1,1], bb[2,1], bb[1,2], bb[2,2], interpolate = FALSE)
}
}
setMethod("plot", signature(x = "Spatial", y = "missing"),
function(x,y,...) plot.Spatial(x,...))
degAxis = function (side, at, labels, ...) {
if (missing(at))
at = axTicks(side)
if (missing(labels)) {
labels = FALSE
if (side == 1 || side == 3)
labels = parse(text = degreeLabelsEW(at))
else if (side == 2 || side == 4)
labels = parse(text = degreeLabelsNS(at))
}
axis(side, at = at, labels = labels, ...)
}
setReplaceMethod("spChFIDs", signature(obj = "Spatial", value = "ANY"),
function(obj, value) { spChFIDs(obj, as.character(value)) }
)
setReplaceMethod("coordinates", signature(object = "Spatial", value = "ANY"),
function(object, value)
stop("setting coordinates cannot be done on Spatial objects, where they have already been set")
)
setMethod("[[", c("Spatial", "ANY", "missing"),
function(x, i, j, ...) {
if (!("data" %in% slotNames(x)))
stop("no [[ method for object without attributes")
x@data[[i]]
}
)
setReplaceMethod("[[", c("Spatial", "ANY", "missing", "ANY"),
function(x, i, j, value) {
if (!("data" %in% slotNames(x)))
stop("no [[ method for object without attributes")
if (is.character(i) && any(!is.na(match(i, dimnames(coordinates(x))[[2]]))))
stop(paste(i, "is already present as a coordinate name!"))
x@data[[i]] <- value
x
}
)
setMethod("$", "Spatial",
function(x, name) {
if (!("data" %in% slotNames(x)))
stop("no $ method for object without attributes")
x@data[[name]]
}
)
setReplaceMethod("$", "Spatial",
function(x, name, value) {
if (name %in% coordnames(x))
stop(paste(name,
"is a coordinate name, please choose another name"))
if (!("data" %in% slotNames(x))) {
df = list(value); names(df) = name
return(addAttrToGeom(x, data.frame(df), match.ID = FALSE))
}
x@data[[name]] = value
x
}
)
setMethod("geometry", "Spatial",
function(obj) {
if ("data" %in% slotNames(obj))
stop(paste("geometry method missing for class", class(obj)))
obj
}
)
setReplaceMethod("geometry", c("data.frame", "Spatial"),
function(obj, value) addAttrToGeom(value, obj)
)
setReplaceMethod("[", c("Spatial", "ANY", "ANY", "ANY"),
function(x, i, j, value) {
if (!("data" %in% slotNames(x)))
stop("no [ method for object without attributes")
if (is.character(i) && any(!is.na(match(i, dimnames(coordinates(x))[[2]]))))
stop(paste(i, "is already present as a coordinate name!"))
x@data[i,j] <- value
x
}
)
setMethod("rebuild_CRS", signature(obj = "Spatial"),
function(obj) {
slot(obj, "proj4string") <- rebuild_CRS(slot(obj, "proj4string"))
obj
}
)
head.Spatial <- function (x, n = 6L, ...)
{
if (n > 0L) {
n <- min(n, nrow(x))
ix <- seq_len(n)
} else if (n < 0L) {
n <- min(abs(n), nrow(x))
ix <- seq_len(nrow(x) - n)
} else {
ix <- seq_len(0)
}
x[ix, , drop = FALSE]
}
tail.Spatial <- function(x, n=6L, ...) {
ix <- sign(n)*rev(seq(nrow(x), by=-1L, len=abs(n)))
x[ ix , , drop=FALSE]
} |
plot.speMCA <- function(x,type='v',axes=1:2,points='all',col='dodgerblue4',app=0, ...) {
tit1 <- paste('Dim ',axes[1],' (',round(x$eig$mrate[axes[1]],1),'%)',sep='')
tit2 <- paste('Dim ',axes[2],' (',round(x$eig$mrate[axes[2]],1),'%)',sep='')
if (type=='v') {
cmin <- apply(x$var$coord[,axes],2,min)*1.1
cmax <- apply(x$var$coord[,axes],2,max)*1.1
clim <- cbind(cmin,cmax)
nv <- nrow(x$var$coord)
if(points=='all') condi <- 1:nv
if (points=='besth') condi <- x$var$contrib[,axes[1]]>=100/nv
if (points=='bestv') condi <- x$var$contrib[,axes[2]]>=100/nv
if (points=='best') condi <- x$var$contrib[,axes[1]]>=100/nv | x$var$contrib[,axes[2]]>=100/nv
coord <- x$var$coord[condi,axes]
prop <- round(x$var$weight[-x$call$excl]/nrow(x$ind$coord)*2+0.5,1)[condi]
plot(coord,col='white',xlim=clim[1,],ylim=clim[2,],xlab=tit1,ylab=tit2,...)
if(app==0) text(coord,rownames(coord),col=col,cex=1)
if(app==1) text(coord,rownames(coord),col=col,cex=prop)
if(app==2) {
points(coord,pch=17,col=col,cex=prop)
text(coord,rownames(coord),pos=3,col=col,cex=1)
}
}
if (type %in% c('i','inames')) {
cmin <- apply(x$ind$coord[,axes],2,min)*1.1
cmax <- apply(x$ind$coord[,axes],2,max)*1.1
clim <- cbind(cmin,cmax)
ni <- nrow(x$ind$coord)
if(points=='all') condi <- 1:ni
if (points=='besth') condi <- x$ind$contrib[,axes[1]]>=100/ni
if (points=='bestv') condi <- x$ind$contrib[,axes[2]]>=100/ni
if (points=='best') condi <- x$ind$contrib[,axes[1]]>=100/ni | x$ind$contrib[,axes[2]]>=100/ni
coord <- x$ind$coord[condi,axes]
if(type=='i') pcol <- col
if(type=='inames') pcol <- 'white'
plot(coord,col=pcol,xlim=clim[1,],ylim=clim[2,],xlab=tit1,ylab=tit2,pch=19,cex=0.2,...)
if(type=='inames') text(coord,rownames(coord),col=col)
}
abline(h=0,v=0,col='grey')
} |
hook_pdfcrop = function(before, options, envir) {
if (before) return()
in_base_dir(for (f in get_plot_files()) plot_crop(f))
}
get_plot_files = function() {
unique(opts_knit$get('plot_files'))
}
hook_optipng = function(before, options, envir) {
hook_png(before, options, envir, 'optipng')
}
hook_png = function(
before, options, envir, cmd = c('optipng', 'pngquant', 'mogrify'), post_process = identity
) {
if (before) return()
cmd = match.arg(cmd)
if (!nzchar(Sys.which(cmd))) {
warning('cannot find ', cmd, '; please install and put it in PATH'); return()
}
paths = get_plot_files()
paths = grep('[.]png$', paths, ignore.case = TRUE, value = TRUE)
in_base_dir(
lapply(paths, function(x) {
message('optimizing ', x)
cmd = paste(cmd, if (is.character(options[[cmd]])) options[[cmd]], shQuote(x))
(if (is_windows()) shell else system)(cmd)
post_process(x)
})
)
return()
}
hook_pngquant = function(before, options, envir) {
if (is.null(options[['pngquant']])) options$pngquant = '--skip-if-larger'
options[['pngquant']] = paste(options[['pngquant']], '--ext -fs8.png')
hook_png(before, options, envir, 'pngquant', function(x) {
x2 = sub("\\.png$", "-fs8.png", x)
if (file.exists(x2)) file.rename(x2, x)
})
}
hook_mogrify = function(before, options, envir) {
if (is.null(options[['mogrify']])) options$mogrify = '-trim'
hook_png(before, options, envir, cmd = 'mogrify', identity)
}
hook_plot_custom = function(before, options, envir){
if (before) return()
if (options$fig.show == 'hide') return()
ext = dev2ext(options)
hook = knit_hooks$get('plot')
n = options$fig.num
if (n == 0L) n = options$fig.num = 1L
res = unlist(lapply(seq_len(n), function(i) {
options$fig.cur = i
hook(fig_path(ext, options, i), reduce_plot_opts(options))
}), use.names = FALSE)
paste(res, collapse = '')
}
hook_purl = function(before, options, envir) {
if (before || !options$purl || options$engine != 'R') return()
output = .knitEnv$tangle.file
if (isFALSE(.knitEnv$tangle.start)) {
.knitEnv$tangle.start = TRUE
unlink(output)
params = .knitEnv$tangle.params
if (length(params)) write_utf8(params, output)
.knitEnv$tangle.params = NULL
}
code = options$code
if (isFALSE(options$eval)) code = comment_out(code, '
if (is.character(output)) {
code = c(
if (file.exists(output)) read_utf8(output),
label_code(code, options$params.src)
)
write_utf8(code, output)
}
} |
rSCA.env = new.env()
rSCA.env$o_result_tree_p = 0
rSCA.env$n_result_tree_rows_p = 0
rSCA.env$o_mean_y_p = 0
rSCA.env$n_y_cols_p = 0
rSCA.env$o_predictors_p = 0
rSCA.env$n_predictors_rows_p = 0
rSCA.env$o_predictants_p = 0
rSCA.env$s_result_file_p = ""
rSCA.env$s_result_filepath_p = ""
rSCA.env$n_model_type_p = ""
rSCA.inference <- function(xfile, x.row.names = FALSE, x.col.names = FALSE, x.missing.flag = "NA", x.type = ".txt", model)
{
o_xdata = 0
if (x.type == ".txt")
{
if (x.row.names == TRUE && x.col.names == TRUE)
o_xdata = read.table(xfile, header = TRUE, row.names = 1, na.strings = x.missing.flag)
else if (x.row.names == TRUE && x.col.names == FALSE)
o_xdata = read.table(xfile, header = FALSE, row.names = 1, na.strings = x.missing.flag)
else if (x.row.names == FALSE && x.col.names == TRUE)
o_xdata = read.table(xfile, header = TRUE, na.strings = x.missing.flag)
else if (x.row.names == FALSE && x.col.names == FALSE)
o_xdata = read.table(xfile, header = FALSE, na.strings = x.missing.flag)
}
if (x.type == ".csv")
{
if (x.row.names == TRUE && x.col.names == TRUE)
o_xdata = read.csv(xfile, header = TRUE, row.names = 1, na.strings = x.missing.flag)
else if (x.row.names == TRUE && x.col.names == FALSE)
o_xdata = read.csv(xfile, header = FALSE, row.names = 1, na.strings = x.missing.flag)
else if (x.row.names == FALSE && x.col.names == TRUE)
o_xdata = read.csv(xfile, header = TRUE, na.strings = x.missing.flag)
else if (x.row.names == FALSE && x.col.names == FALSE)
o_xdata = read.csv(xfile, header = FALSE, na.strings = x.missing.flag)
}
o_xdata = na.omit(o_xdata)
rSCA.env$o_predictors_p = o_xdata
rSCA.env$n_predictors_rows_p = nrow(o_xdata)
rSCA.env$o_result_tree_p = read.table(model$treefile, header = TRUE)
rSCA.env$n_result_tree_rows_p = nrow(rSCA.env$o_result_tree_p)
rSCA.env$o_mean_y_p = read.table(model$mapfile, header = TRUE)
rSCA.env$n_y_cols_p = ncol(rSCA.env$o_mean_y_p)
rSCA.env$s_result_file_p = model$s_rslfile
rSCA.env$s_result_filepath_p = model$s_rslfilepath
rSCA.env$n_model_type_p = model$type
do_prediction()
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
fig.width=5, fig.height=5 ,fig.align="center"
)
fpath <- "vignettefigs/"
library(condvis2)
library(mclust)
data(banknote)
bankDA <- MclustDA(banknote[,-1], banknote[,1],verbose=F)
table(banknote$Status, CVpredict(bankDA, banknote))
knitr::include_graphics(paste0(fpath, "mclustda1.png"))
bankDAe <- MclustDA(banknote[,-1], banknote[,1], modelType="EDDA",verbose=F)
knitr::include_graphics(paste0(fpath, "mclustda6.png"))
data(banknote)
dens2 <- densityMclust(banknote[,c("Diagonal","Left")],verbose=F)
summary(dens2)
knitr::include_graphics(paste0(fpath, "left1.png"))
dens3 <- densityMclust(banknote[,c("Right", "Bottom", "Diagonal")],verbose=F)
summary(dens3)
library(ks)
kdens3 <- kde(banknote[,c("Right", "Bottom", "Diagonal")])
knitr::include_graphics(paste0(fpath, "dens3Right2.png")) |
IATdescriptives <- function(IATdata, byblock = FALSE)
{
if(!byblock)
{
group_by(IATdata, subject) %>%
summarize(
N_trials = n(),
Nmissing_latency = sum(is.na(latency)),
Nmissing_accuracy = sum(is.na(correct)),
Prop_error = mean(!correct, na.rm = TRUE),
M_latency = mean(latency, na.rm = TRUE),
SD_latency = sd(latency, na.rm = TRUE),
min_latency = min(latency, na.rm = TRUE),
max_latency = max(latency, na.rm = TRUE),
Prop_latency300 = mean(latency < 400, na.rm = TRUE),
Prop_latency400 = mean(latency < 300, na.rm = TRUE),
Prop_latency10s = mean(latency > 10000, na.rm = TRUE)
)
} else
{
group_by(IATdata, subject, blockcode) %>%
summarize(
N_trials = n(),
Nmissing_latency = sum(is.na(latency)),
Nmissing_accuracy = sum(is.na(correct)),
Prop_error = mean(!correct, na.rm = TRUE),
M_latency = mean(latency, na.rm = TRUE),
SD_latency = sd(latency, na.rm = TRUE),
min_latency = min(latency, na.rm = TRUE),
max_latency = max(latency, na.rm = TRUE),
Prop_latency300 = mean(latency < 400, na.rm = TRUE),
Prop_latency400 = mean(latency < 300, na.rm = TRUE),
Prop_latency10s = mean(latency > 10000, na.rm = TRUE)
)
}
} |
get.Q <-
function(TL,beta=0){
p=length(TL)
M=nrow(TL[[1]])
A=Matrix(0,nrow=M,ncol=M,sparse=T)
for(i in 1:p){
A=A+beta[i]*TL[[i]]
}
A@x=exp(A@x)
m=rowSums(A)
Q=Diagonal(M,m)-A
Q=1/2*(Q+t(Q))
rm(A)
Q
} |
data(Chile, package="carData")
RegModel.1 <- lm(income~age, data=Chile)
summary(RegModel.1)
.data <- edit(data.frame(age = numeric(0)))
.data
predict(RegModel.1, .data)
remove(.data) |
calcSpaceMat<- function (adjacent.mat,par.space=0.9){
if( !is.matrix(adjacent.mat)) stop("space matrix must be a square matrix.")
if(!is.numeric(par.space)) stop("par.space must be a number")
if( par.space<=0 | par.space>1 ) stop("par.space must be a number between 0 and 1.")
if( any(c( !is.numeric(adjacent.mat) , length(table(adjacent.mat)) !=2, max(adjacent.mat)!=1, min(adjacent.mat)!=0 )) ) stop("adjacent.mat must contain 0 or 1 ")
if( is.null(rownames(adjacent.mat) ) ) stop("row names of adjacent.mat is necessary!")
if( any( is.na(
as.numeric(rownames(adjacent.mat))
)
)
)stop("row names of adjacent.mat must be matched with location(number)")
diag(adjacent.mat) <- par.space
adjacent.mat[which(adjacent.mat==1)] <- par.space*(1-par.space)
return (adjacent.mat)
} |
NULL
identify_outliers <- function(data, ..., variable = NULL){
is.outlier <- NULL
if(is_grouped_df(data)){
results <- data %>%
doo(identify_outliers, ..., variable = variable)
if(nrow(results) == 0) results <- as.data.frame(results)
return(results)
}
if(!inherits(data, "data.frame"))
stop("data should be a data frame")
variable <- data %>% get_selected_vars(..., vars = variable)
n.vars <- length(variable)
if(n.vars > 1)
stop("Specify only one variable")
values <- data %>% pull(!!variable)
results <- data %>%
mutate(
is.outlier = is_outlier(values),
is.extreme = is_extreme(values)
) %>%
filter(is.outlier == TRUE)
if(nrow(results) == 0) results <- as.data.frame(results)
results
}
is_outlier <- function(x, coef = 1.5){
res <- x
Q1 <- quantile(x, 0.25, na.rm = TRUE)
Q3 <- quantile(x, 0.75, na.rm = TRUE)
.IQR <- IQR(x, na.rm = TRUE)
upper.limit <- Q3 + (coef*.IQR)
lower.limit <- Q1 - (coef*.IQR)
outlier <- ifelse(x < lower.limit | x > upper.limit, TRUE, FALSE )
outlier
}
is_extreme <- function(x){
is_outlier(x, coef = 3)
} |
Dcond <-
function(x,a,b,c,d,zi,zk)
{
res <- a+(x^(b-1))*zi - (x^(d-1))*zk
return(res)
} |
vertboot <- function(m1, boot_rep){
res <- list()
for (i in 1:boot_rep) {
blist <- sample(0:(dim(m1)[1]-1), replace = TRUE)
res <- c(res, list(vertboot_matrix_rcpp(m1,blist)))
}
res
} |
labelLayer <- function(x, spdf, df, spdfid = NULL, dfid = NULL, txt,
col = "black",
cex = 0.7, overlap = TRUE, show.lines = TRUE,
halo = FALSE, bg = "white", r = 0.1, ...){
if (missing(x)){
x <- convertToSf(spdf = spdf, df = df, spdfid = spdfid, dfid = dfid)
}
if (methods::is(x, 'Spatial')){
x <- sf::st_as_sf(x)
}
words <- x[[txt]]
cc <- sf::st_coordinates(sf::st_centroid(
x = sf::st_geometry(x),
of_largest_polygon = max(sf::st_is(sf::st_as_sf(x), "MULTIPOLYGON"))
))
if(nrow(x) == 1){
overlap <- TRUE
}
if (!overlap){
x <- unlist(cc[,1])
y <- unlist(cc[,2])
lay <- wordlayout(x,y,words,cex)
if(show.lines){
for(i in 1:length(x)){
xl <- lay[i,1]
yl <- lay[i,2]
w <- lay[i,3]
h <- lay[i,4]
if(x[i]<xl || x[i]>xl+w ||
y[i]<yl || y[i]>yl+h){
points(x[i],y[i],pch=16,col=col,cex=.5)
nx <- xl+.5*w
ny <- yl+.5*h
lines(c(x[i],nx),c(y[i],ny), col=col, lwd = 1)
}
}
}
cc <- matrix(data = c(lay[,1]+.5*lay[,3], lay[,2]+.5*lay[,4]),
ncol = 2, byrow = FALSE)
}
if (halo){
shadowtext(x = cc[,1], y = cc[,2], labels = words,
cex = cex, col = col, bg = bg, r = r, ...)
}else{
text(x = cc[,1], y = cc[,2], labels = words, cex = cex, col = col, ...)
}
} |
if (requireNamespace("rmarkdown") && !rmarkdown::pandoc_available("1.13.1"))
stop("These vignettes assume pandoc version 1.13.1; older versions will not work.")
library(devtools)
library(recexcavAAR)
library(dplyr)
library(kriging)
library(magrittr)
library(rgl)
edges <- data.frame(
x = c(0, 3, 0, 3, 0, 3, 0, 3),
y = c(0, 0, 0, 0, 1, 1, 1, 1),
z = c(0, 0, 2, 2, 0, 0, 2, 2)
)
open3d(useNULL = TRUE)
plot3d(
edges$x, edges$y, edges$z,
type="s",
aspect = c(3, 1, 2),
xlab = "x", ylab = "y", zlab = "z",
sub = "Grab me and rotate me!"
)
bbox3d(
xat = c(0, 1, 2, 3),
yat = c(0, 0.5, 1),
zat = c(0, 0.5, 1, 1.5, 2),
back = "lines"
)
rglwidget()
df1 <- data.frame(
x = c(rep(0, 6), seq(0.2, 2.8, 0.2), seq(0.2, 2.8, 0.2), rep(3,6)),
y = c(seq(0, 1, 0.2), rep(0, 14), rep(1, 14), seq(0, 1, 0.2)),
z = c(seq(0.95, 1.2, 0.05), 0.9+0.05*rnorm(14), 1.3+0.05*rnorm(14), seq(0.95, 1.2, 0.05))
)
df2 <- data.frame(
x = c(rep(0, 6), seq(0.2, 2.8, 0.2), seq(0.2, 2.8, 0.2), rep(3,6)),
y = c(seq(0, 1, 0.2), rep(0, 14), rep(1, 14), seq(0, 1, 0.2)),
z = c(seq(0.65, 0.9, 0.05), 0.6+0.05*rnorm(14), 1.0+0.05*rnorm(14), seq(0.65, 0.9, 0.05))
)
points3d(
df1$x, df1$y, df1$z,
col = "darkgreen",
add = TRUE
)
points3d(
df2$x, df2$y, df2$z,
col = "blue",
add = TRUE
)
rglwidget()
lpoints <- list(df1, df2)
maps <- kriglist(lpoints, lags = 3, model = "spherical", pixels = 30)
surf1 <- spatialwide(maps[[1]]$x, maps[[1]]$y, maps[[1]]$pred, 3)
surf2 <- spatialwide(maps[[2]]$x, maps[[2]]$y, maps[[2]]$pred, 3)
surface3d(
surf1$x, surf1$y, t(surf1$z),
color = c("black", "white"),
alpha = 0.5,
add = TRUE
)
surface3d(
surf2$x, surf2$y, t(surf2$z),
color = c("black", "white"),
alpha = 0.5,
add = TRUE
)
rglwidget()
hexatestdf <- data.frame(
x = c(1, 1, 1, 1, 2, 2, 2, 2),
y = c(0, 1, 0, 1, 0, 1, 0, 1),
z = c(0.8, 0.8, 1, 1, 0.8, 0.8, 1, 1)
)
cx = fillhexa(hexatestdf, 0.1)
completeraster <- points3d(
cx$x, cx$y, cx$z,
col = "red",
add = TRUE
)
rglwidget()
rgl.pop(id = completeraster)
cuberasterlist <- list(cx)
crlist <- posdeclist(cuberasterlist, maps)
hexa <- crlist[[1]]
a <- filter(
hexa,
pos == 0
)
b <- filter(
hexa,
pos == 1
)
c <- filter(
hexa,
pos == 2
)
points3d(
a$x, a$y, a$z,
col = "red",
add = TRUE
)
points3d(
b$x, b$y, b$z,
col = "blue",
add = TRUE
)
points3d(
c$x, c$y, c$z,
col = "green",
add = TRUE
)
rglwidget()
sapply(
crlist,
function(x){
x$pos %>%
table() %>%
prop.table() %>%
multiply_by(100) %>%
round(2)
}
) %>% t |
"Smokdat" |
weightedSetCover <- function(idsInSet, costs, topN, nThreads=4) {
cat("Begin weighted set cover...\n")
names(costs) <- names(idsInSet)
if (.Platform$OS.type == "windows") {
nThreads = 1
}
multiplier <- 10
max_num_set <- multiplier * topN
if (length(idsInSet) > max_num_set) {
index <- order(abs(costs), decreasing=FALSE)
costs <- costs[index][1:max_num_set]
idsInSet <- idsInSet[index][1:max_num_set]
}
s.hat <- 1.0
all.genes <- unique(unlist(idsInSet))
remain <- s.hat * length(all.genes)
cur.res <- c()
all.set.names <- names(idsInSet)
mc_results <- mclapply(all.set.names, function(cur_name, cur_res, idsInSet, costs) {
cur_gain <- marginalGain(cur_name, cur_res, idsInSet, costs)
cur_size <- length(idsInSet[[cur_name]])
return(data.frame(geneset.name=cur_name, gain=cur_gain, size=cur_size, stringsAsFactors=FALSE))
}, cur_res=cur.res, idsInSet=idsInSet, costs=costs, mc.cores=nThreads)
candidates <- mc_results %>% bind_rows()
topN <- min(topN, nrow(candidates))
for (i in seq(topN)) {
if (nrow(candidates) == 0) {
covered.genes <- unique(unlist(idsInSet[cur.res]))
s.hat <- length(covered.genes) / length(all.genes)
cat("No more candidates, ending weighted set cover\n")
return(list(topSets=cur.res, coverage=s.hat))
}
candidates <- candidates[order(-candidates$gain, -candidates$size), ]
remain <- remain - length(marginalBenefit(candidates[1, "geneset.name"], cur.res, idsInSet))
cur.res <- c(cur.res, candidates[1,"geneset.name"])
if (remain == 0) {
covered.genes <- unique(unlist(idsInSet[cur.res]))
s.hat <- length(covered.genes) / length(all.genes)
cat("Remain is 0, ending weighted set cover\n")
return(list(topSets=cur.res, coverage=s.hat))
}
candidates <- candidates[-1, ]
if (nrow(candidates) > 0) {
mc_results <- mclapply(seq(nrow(candidates)), function(row, candidates, cur_res, idsInSet, costs){
cur_name <- candidates[row, "geneset.name"]
cur_gain <- marginalGain(cur_name, cur_res, idsInSet, costs)
if(cur_gain != 0) {
candidates[candidates$geneset.name == cur_name, "gain"] <- cur_gain
tmp_candidate <- candidates[candidates$geneset.name == cur_name,]
return(tmp_candidate)
}
}, candidates=candidates, cur_res=cur.res, idsInSet=idsInSet, costs=costs, mc.cores=nThreads)
new_candidates <- mc_results %>% bind_rows()
candidates <- new_candidates
}
}
covered.genes <- unique(unlist(idsInSet[cur.res]))
s.hat <- length(covered.genes) / length(all.genes)
cat("End weighted set cover...\n")
return(list(topSets=cur.res, coverage=s.hat))
}
marginalBenefit <- function(cur.set.name, cur.res, idsInSet) {
all.genes <- unique(unlist(idsInSet))
cur.genes <- idsInSet[[cur.set.name]]
if(length(cur.res) == 0){
not.covered.genes <- cur.genes
} else{
covered.genes <- unique(unlist(idsInSet[cur.res]))
not.covered.genes <- setdiff(cur.genes, covered.genes)
}
return(not.covered.genes)
}
marginalGain <- function(cur.set.name, cur.res, idsInSet, costs) {
abs_cur_cost <- abs(costs[cur.set.name])
cur.mben <- marginalBenefit(cur.set.name, cur.res, idsInSet)
return(length(cur.mben) / abs_cur_cost)
} |
stochParamsSetterUI <- function(id, show_var=FALSE, show_biol_sigma = TRUE, show_est_sigma = TRUE, show_est_bias = TRUE, init_biol_sigma=0.0, init_est_sigma=0.0, init_est_bias=0.0){
ns <- NS(id)
show_var <- checkboxInput(ns("show_var"), label = "Show variability options", value = show_var)
options <- list()
if (show_biol_sigma){
options[[length(options)+1]] <-
tags$span(title="Natural variability in the stock biological processes (e.g. recruitment and growth)",
numericInput(ns("biol_sigma"), label = "Biological variability", value = init_biol_sigma, min=0, max=1, step=0.05))
}
if (show_est_sigma){
options[[length(options)+1]] <-
tags$span(title="Simulating the difference between the 'true' biomass and the 'estimated' biomass used by the HCR by applying randomly generated noise",
numericInput(ns("est_sigma"), label = "Estimation variability", value = init_est_sigma, min=0, max=1, step=0.05))
}
if (show_est_bias){
options[[length(options)+1]] <-
tags$span(title="Simulating the difference between the 'true' biomass and the 'estimated' biomass used by the HCR by applying a continuous bias (positive or negative)",
numericInput(ns("est_bias"), label = "Estimation bias", value = init_est_bias, min=-0.5, max=0.5, step=0.05))
}
vars <- conditionalPanel(condition="input.show_var == true", ns=ns, options)
out <- tagList(show_var, vars)
return(out)
}
stochParamsSetterServer <- function(id){
moduleServer(id, function(input, output, session){
reactive({return(set_stoch_params(input))})
})
}
set_stoch_params <- function(input){
params <- c("biol_sigma", "est_sigma", "est_bias")
out <- lapply(params, function(x) ifelse(is.null(input[[x]]), 0.0, input[[x]]))
names(out) <- params
return(out)
} |
which_lto <- function() stoRy_env$active_version
print_lto <- function() {
version <- which_lto()
if (!is_lto_file_cached("metadata_tbl.Rds", version)) {
msg <- get_metadata_tbl_file_not_found_msg(version)
abort(msg, class = "lto_file_not_found")
}
if (isTRUE(version == "demo")) {
metadata_tbl <- metadata_tbl
} else if (isTRUE(version == "latest")) {
file_path <- file.path(stoRy_cache_path(),
get_latest_version_tag(),
"metadata_tbl.Rds"
)
metadata_tbl <- readRDS(file_path)
} else {
file_path <- file.path(stoRy_cache_path(), version, "metadata_tbl.Rds")
metadata_tbl <- readRDS(file_path)
}
timestamp <- metadata_tbl %>%
filter(.data$name == "timestamp") %>%
select(.data$value)
git_commit_id <- metadata_tbl %>%
filter(.data$name == "git_commit_id") %>%
select(.data$value)
encoding <- metadata_tbl %>%
filter(.data$name == "encoding") %>%
select(.data$value)
theme_count <- metadata_tbl %>%
filter(.data$name == "theme_count") %>%
select(.data$value)
story_count <- metadata_tbl %>%
filter(.data$name == "story_count") %>%
select(.data$value)
collection_count <- metadata_tbl %>%
filter(.data$name == "collection_count") %>%
select(.data$value)
cli_text("Version: {.val {version}}")
cli_text("Timestamp: {.val {timestamp}}")
cli_text("Git Commit ID: {.val {git_commit_id}}")
cli_text("Encoding: {.val {encoding}}")
cli_text("Theme Count: {.val {theme_count}}")
cli_text("Story Count: {.val {story_count}}")
cli_text("Collection Count: {.val {collection_count}}")
return(invisible(NULL))
}
fetch_lto_version_tags <- function(verbose = TRUE) {
if (verbose) cli_text("Retrieving LTO version tags...")
response <- httr::GET(lto_repo_url())
fetched_versions <- rawToChar(response$content) %>%
as.tbl_json %>%
gather_array %>%
spread_all %>%
pull(.data$name)
downloadable_versions <- c("dev", fetched_versions[!fetched_versions %in% defunct_versions()])
versions <- c("demo", "dev", fetched_versions)
versions
}
lto_version_statuses <- function(verbose = TRUE) {
if (verbose) cli_text("Summarizing LTO version info...")
versions <- fetch_lto_version_tags(verbose)
version <- "demo"
cli_li("{.val {version}}: A stoRy package included LTO demo version")
cli_alert_info("Enter {.code ?lto-demo} for more details")
downloadable_versions <- versions[which(versions != "demo")]
for (version in downloadable_versions) {
if (are_lto_files_cached(lto_json_file_names(version), version)) {
cli_li("{.val {version}}: Cached in {.file {file.path(stoRy_cache_path(), version)}}")
if (!are_newest_lto_json_files_cached(version)) {
if (isTRUE(version == "dev")) {
cli_alert_warning("A newly updated developmental version is available for download")
} else {
cli_alert_warning("More recently generated JSON files are available for download")
}
}
} else {
cli_li("{.val {version}}: Available for download")
}
}
for (version in defunct_versions()) {
cli_li("{.val {version}}: Defunct version")
}
cli_end()
if (verbose) cli_text("Access LTO version JSON files directly at {.url https://github.com/theme-ontology/theming/releases}")
}
configure_lto <- function(
version,
verbose = TRUE,
overwrite_json = FALSE,
overwrite_rds = FALSE) {
if (is_missing(version)) {
message <- get_missing_arg_msg(variable_name = "version")
abort(message, class = "missing_argument")
}
if (isTRUE(!is.character(version) || length(version) != 1)) {
message <- get_single_string_msg(string = version, variable_name = "version")
abort(message, class = "function_argument_type_check_fail")
}
if (isTRUE(version == "demo")) {
if (verbose) cli_text("The LTO {.val {version}} version does not require configuration")
if (verbose) cli_alert_info("Enter {.code ?lto-demo} for more details")
return(invisible(NULL))
}
if (verbose) cli_text("Verifying that {.val {version}} is a valid version tag...")
if(!is_lto_version_tag_valid(version)) {
message <- get_invalid_lto_version_msg(version)
abort(message, class = "lto_version_tag_not_found")
} else if (verbose) {
cli_text("Version tag verified")
}
are_json_files_cached <- are_lto_files_cached(lto_json_file_names(version), version)
are_rds_files_cached <- are_lto_files_cached(lto_rds_file_names(), version)
if (isTRUE(!overwrite_json && !overwrite_rds && are_json_files_cached && are_rds_files_cached)) {
if (isTRUE(version %in% c("dev", "latest") && verbose)) {
cli_text("LTO {.val {version}} version is already configured")
} else if (verbose) {
cli_text("LTO {.val {version}} is already configured")
}
return(invisible(TRUE))
}
if (isTRUE(overwrite_json && !overwrite_rds)) {
cli_alert_warning("Overwriting LTO JSON files without regenerating cached Rds files is not recommended")
cli_alert_info("Run {.code configure_lto(version = \"{version}\", overwrite_json = TRUE, overwrite_rds = TRUE)} to reinstall LTO {.val {version}} from scratch")
}
if (isTRUE(version == "latest")) version <- get_latest_version_tag()
for (file_name in lto_json_file_names(version)) {
fetch_lto_file(file_name, verbose, overwrite_json)
}
generate_themes_tbl(version, overwrite_rds, verbose)
generate_stories_tbl(version, overwrite_rds, verbose)
generate_collections_tbl(version, overwrite_rds, verbose)
generate_metadata_tbl(version, overwrite_rds, verbose)
generate_background_collection(version, overwrite_rds, verbose)
if (isTRUE(version == "dev" && verbose)) {
cli_text("Successfully configured LTO {.val {version}} version!")
} else if (verbose) {
cli_text("Successfully configured LTO {.val {version}}!")
}
return(invisible(NULL))
}
set_lto <- function(
version,
verbose = TRUE,
load_background_collection = TRUE) {
if (is_missing(version)) {
message <- get_missing_arg_msg(variable_name = "version")
abort(message, class = "missing_argument")
}
if (isTRUE(!is.character(version) || length(version) != 1)) {
msg <- get_single_string_msg(string = version, variable_name = "version")
abort(msg, class = "function_argument_type_check_fail")
}
if (isTRUE(version == stoRy_env$active_version)) {
if (verbose) cli_text("LTO {.val {version}} is already the active version")
return(invisible(NULL))
}
if (verbose) cli_text("Verifying that {.val {version}} is a valid version tag...")
if(!is_lto_version_tag_valid(version)) {
msg <- get_invalid_lto_version_msg(version)
abort(msg, class = "lto_version_tag_not_found")
}
if (!are_lto_files_cached(lto_json_file_names(version), version)) {
msg <- get_lto_json_file_not_found_msg(version)
abort(msg, class = "lto_json_file_not_found")
}
if (isTRUE(!are_lto_files_cached(lto_rds_file_names(), version) && load_background_collection)) {
msg <- get_lto_rds_file_not_found_msg(version)
abort(msg, class = "lto_json_file_not_found")
}
if (isTRUE(version == "latest")) version <- get_latest_version_tag()
base_path <- file.path(stoRy_cache_path(), version)
if (verbose) cli_text("Setting {.pkg stoRy} package level environmental variable {.envvar active_version} to {.val {version}}...")
assign("active_version", version, stoRy_env)
if (isTRUE(version != "demo")) {
if (verbose) cli_text("Loading {.file {file.path(base_path, \"collections_tbl.Rds\")}} into {.pkg stoRy} package level environment")
assign("collections_tbl", readRDS(file.path(base_path, "collections_tbl.Rds")), stoRy_env)
if (verbose) cli_text("Loading {.file {file.path(base_path, \"stories_tbl.Rds\")}} into {.pkg stoRy} package level environment")
assign("stories_tbl", readRDS(file.path(base_path, "stories_tbl.Rds")), stoRy_env)
if (verbose) cli_text("Loading {.file {file.path(base_path, \"themes_tbl.Rds\")}} into {.pkg stoRy} package level environment")
assign("themes_tbl", readRDS(file.path(base_path, "themes_tbl.Rds")), stoRy_env)
if (verbose) cli_text("Loading {.file {file.path(base_path, \"metadata_tbl.Rds\")}} into {.pkg stoRy} package level environment")
assign("metadata_tbl", readRDS(file.path(base_path, "metadata_tbl.Rds")), stoRy_env)
if (load_background_collection) {
if (verbose) cli_text("Loading {.file {file.path(base_path, \"background_collection.Rds\")}} into {.pkg stoRy} package level environment")
assign("background_collection", readRDS(file.path(base_path, "background_collection.Rds")), stoRy_env)
}
}
if (verbose) cli_text("Successfully set active LTO version to {.val {stoRy_env$active_version}}!")
return(invisible(NULL))
}
fetch_lto_file <- function(
file_name,
verbose = TRUE,
overwrite_json = FALSE) {
if (is_missing(file_name)) {
message <- get_missing_arg_msg(variable_name = "file_name")
abort(message, class = "missing_argument")
}
has_lto_file_been_updated <- FALSE
version <- unlist(strsplit(file_name, split = "-"))[2]
base_path <- file.path(stoRy_cache_path(), version)
file_path <- file.path(base_path, file_name)
if (isTRUE(is_lto_file_cached(file_name, version) && !overwrite_json)) {
if (verbose) cli_text("The file {.file {file_path}} is cached and will not be downloaded")
return(invisible(NULL))
}
if (isTRUE(is_lto_file_cached(file_name, version) && overwrite_json && verbose)) {
cli_alert_warning("The cached file {.file {file_path}} will be overwritten")
}
dir.create(base_path, showWarnings = FALSE, recursive = TRUE)
file_url <- file.path(base_url(), file_name)
file_size <- download_size(url = file_url)
temp_file_path <- tempfile()
if (verbose) cli_text("Downloading {.file {file_url}}...")
if (requireNamespace("curl", quietly = TRUE)) {
if (requireNamespace("progress", quietly = TRUE)) {
url_payload <- download_url_with_progress_bar(file_url)
response <- url_payload$response
contents <- url_payload$contents
} else {
cli_alert_warning("{.pkg progress} package not installed, downloading file without an accompanying progress bar")
response <- curl::curl_fetch_stream(file_url)
}
handle_curl_errors(response, file_path)
if (verbose) cli_text("Caching {.file {file_path}}... ({formatted_file_size(file_size)})")
if(requireNamespace("jsonlite", quietly = TRUE)) {
write(jsonlite::prettify(rawToChar(contents)), temp_file_path)
} else {
cli_alert_warning("{.pkg jsonlite} package not installed, falling back to writing unprettified JSON data to file")
write(rawToChar(contents), temp_file_path)
}
file.rename(temp_file_path, file_path)
} else {
cli_alert_warning("{.pkg curl} package not installed, falling back to using {.fn download.file}")
utils::download.file(file_url, file_path)
if (verbose) cli_text("Cached {.file {file_path}}")
}
file_path <- file.path(base_path, "lto_file_timestamps.Rds")
if (!file.exists(file_path)) {
lto_file_timestamps_tbl <- tibble(file = lto_json_file_names(version),
timestamp = "Missing")
} else {
lto_file_timestamps_tbl <- readRDS(file_path)
}
timestamp <- get_website_lto_file_timestamp(file_name)
lto_file_timestamps_tbl$timestamp[which(lto_json_file_names(version) == file_name)] <- timestamp
saveRDS(lto_file_timestamps_tbl,
file = file_path,
compress = TRUE)
file_size <- file.info(file_path)$size
return(invisible(NULL))
}
generate_themes_tbl <- function(
version,
overwrite_rds = FALSE,
verbose = TRUE) {
if (is_missing(version)) {
message <- get_missing_arg_msg(variable_name = "version")
abort(message, class = "missing_argument")
}
outfile_name <- "themes_tbl.Rds"
base_path <- file.path(stoRy_cache_path(), version)
outfile_path <- file.path(base_path, outfile_name)
if (isTRUE(file.exists(outfile_path) && !overwrite_rds && verbose)) {
cli_text("The file {.file {outfile_name}} is already cached and will not be regenerated")
return(invisible(NULL))
}
if (verbose) cli_text("Processing themes...")
infile_name <- paste0("lto-", version, "-themes.json")
infile_path <- file.path(base_path, infile_name)
if (!file.exists(infile_path)) {
message <- get_lto_json_file_not_found_msg(version, infile_path)
abort(message, class = "file_not_found")
}
json <- read_json(infile_path) %>% as.tbl_json()
main <- json %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
spread_values(
theme_name = jstring('name'),
description = jstring('description'),
source = jstring('source')
) %>%
select(-.data$document.id) %>%
as_tibble()
aliases <- json %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('aliases') %>%
gather_array %>%
append_values_string %>%
rename(aliases = string) %>%
select(-.data$document.id, -.data$array.index) %>%
as_tibble()
notes <- json %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('notes') %>%
gather_array %>%
append_values_string %>%
rename(notes = string) %>%
select(-.data$document.id, -.data$array.index) %>%
as_tibble()
parents <- json %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('parents') %>%
gather_array %>%
append_values_string %>%
rename(parents = string) %>%
select(-.data$document.id, -.data$array.index) %>%
as_tibble()
template <- json %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('template') %>%
gather_array %>%
append_values_string %>%
rename(template = string) %>%
select(-.data$document.id, -.data$array.index) %>%
as_tibble()
examples <- json %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('examples') %>%
gather_array %>%
append_values_string %>%
rename(examples = string) %>%
select(-.data$document.id, -.data$array.index) %>%
as_tibble()
references <- json %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('references') %>%
gather_array %>%
append_values_string %>%
rename(references = string) %>%
select(-.data$document.id, -.data$array.index) %>%
as_tibble()
themes_tbl <- main %>%
nest_join(notes, by = "theme_index") %>%
nest_join(aliases, by = "theme_index") %>%
nest_join(template, by = "theme_index") %>%
nest_join(parents, by = "theme_index") %>%
nest_join(examples, by = "theme_index") %>%
nest_join(references, by = "theme_index") %>%
relocate(source, .after = "references")
if (verbose) cli_text("Found {.val {nrow(themes_tbl)}} theme{?/s}")
ancestors_lst <- vector(mode = "list", length = nrow(themes_tbl))
for (i in seq(nrow(themes_tbl))) {
ancestors <- character(0)
theme_queue <- themes_tbl %>% `[[`(i, 2)
while (length(theme_queue) > 0) {
popped_theme_name <- theme_queue[1]
theme_queue <- theme_queue[-1]
parents <- themes_tbl %>%
filter(.data$theme_name == !!popped_theme_name) %>%
pull(parents) %>%
unlist(use.names = FALSE)
ancestors <- c(ancestors, parents)
theme_queue <- c(theme_queue, parents)
}
ancestors_lst[[i]] <- as_tibble_col(ancestors, column_name = "ancestors")
}
themes_tbl <- themes_tbl %>%
add_column(ancestors = ancestors_lst, .after = "parents")
saveRDS(themes_tbl, file = outfile_path, compress = TRUE)
outfile_size <- file.info(outfile_path)$size
if (verbose) cli_text("Cached themes tibble to {.file {outfile_path}} ({formatted_file_size(outfile_size)})")
return(invisible(NULL))
}
generate_stories_tbl <- function(
version,
overwrite_rds = FALSE,
verbose = TRUE) {
if (is_missing(version)) {
message <- get_missing_arg_msg(variable_name = "version")
abort(message, class = "missing_argument")
}
base_path <- file.path(stoRy_cache_path(), version)
stories_outfile_name <- "stories_tbl.Rds"
stories_outfile_path <- file.path(base_path, stories_outfile_name)
stub_stories_outfile_name <- "stub_stories_tbl.Rds"
stub_stories_outfile_path <- file.path(base_path, stub_stories_outfile_name)
if (isTRUE(file.exists(stories_outfile_path) && !overwrite_rds && verbose)) {
cli_text("The file {.file {stories_outfile_name}} is already cached and will not be regenerated")
return(invisible(NULL))
}
if (verbose) cli_text("Processing stories...")
infile_name <- paste0("lto-", version, "-stories.json")
infile_path <- file.path(base_path, infile_name)
if (!file.exists(infile_path)) {
message <- get_lto_json_file_not_found_msg(version, infile_path)
abort(message, class = "file_not_found")
}
json <- read_json(infile_path) %>% as.tbl_json()
main <- json %>%
enter_object('stories') %>%
gather_array('story_index') %>%
spread_values(
story_id = jstring('story-id'),
title = jstring('title'),
date = jstring('date'),
description = jstring('description'),
source = jstring('source')
) %>%
select(-.data$document.id) %>%
as_tibble()
component_story_ids <- json %>%
enter_object('stories') %>%
gather_array('story_index') %>%
enter_object('component-story-ids') %>%
gather_array %>%
append_values_string %>%
rename(component_story_ids = string) %>%
select(-.data$document.id, -.data$array.index) %>%
as_tibble()
collections <- json %>%
enter_object('stories') %>%
gather_array('story_index') %>%
enter_object('collections') %>%
gather_array %>%
append_values_string %>%
rename(collections = string) %>%
select(-.data$document.id, -.data$array.index) %>%
as_tibble()
references <- json %>%
enter_object('stories') %>%
gather_array('story_index') %>%
enter_object('references') %>%
gather_array %>%
append_values_string %>%
rename(references = string) %>%
select(-.data$document.id, -.data$array.index) %>%
as_tibble()
theme_names <- json %>%
enter_object('stories') %>%
gather_array('story_index') %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('name') %>%
append_values_string %>%
rename(theme_name = string) %>%
select(-.data$document.id) %>%
as_tibble()
theme_capacities <- json %>%
enter_object('stories') %>%
gather_array('story_index') %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('capacity') %>%
append_values_string %>%
rename(capacity = string) %>%
select(-.data$document.id) %>%
as_tibble()
theme_levels <- json %>%
enter_object('stories') %>%
gather_array('story_index') %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('level') %>%
append_values_string %>%
rename(level = string) %>%
select(-.data$document.id) %>%
as_tibble()
theme_motivations <- json %>%
enter_object('stories') %>%
gather_array('story_index') %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('motivation') %>%
append_values_string %>%
rename(motivation = string) %>%
select(-.data$document.id) %>%
as_tibble()
themes <- theme_names %>%
right_join(theme_capacities, by = c('story_index', 'theme_index')) %>%
right_join(theme_levels, by = c('story_index', 'theme_index')) %>%
right_join(theme_motivations, by = c('story_index', 'theme_index')) %>%
select(-.data$theme_index) %>%
as_tibble()
stories_tbl <- main %>%
nest_join(component_story_ids, by = "story_index") %>%
nest_join(collections, by = "story_index") %>%
nest_join(references, by = "story_index") %>%
nest_join(themes, by = "story_index") %>%
relocate(source, .after = "themes")
infile_name <- "themes_tbl.Rds"
infile_path <- file.path(base_path, infile_name)
if (!file.exists(infile_path)) {
message <- get_missing_lto_rds_file_msg(version, infile_path)
abort(message, class = "file_not_found")
}
themes_tbl <- readRDS(infile_path)
all_theme_names <- themes_tbl %>% pull(.data$theme_name)
for (i in seq(nrow(stories_tbl))) {
story_index <- stories_tbl$story_index[i]
story_id <- stories_tbl$story_id[story_index]
themes <- stories_tbl %>%
filter(.data$story_id == !!story_id) %>%
select(.data$themes) %>%
unnest(cols = .data$themes)
if(nrow(themes) > 0) {
undefined_theme_names <- stories_tbl %>%
filter(.data$story_id == !!story_id) %>%
select(.data$themes) %>%
unnest(cols = .data$themes) %>%
pull(.data$theme_name) %>%
setdiff(all_theme_names)
has_undefined_theme <- ifelse(identical(undefined_theme_names, character(0)), FALSE, TRUE)
for (j in seq_along(undefined_theme_names)) {
themes <- themes %>% filter(.data$theme_name != undefined_theme_names[j])
if (verbose) cli_text("Dropped undefined theme {.val {undefined_theme_names[j]}} from {.val {story_id}}")
}
themes <- themes %>%
mutate(themes, theme_index = 1:nrow(themes), .before = .data$theme_name)
duplicate_themes <- themes %>%
filter(duplicated(cbind(.data$theme_name, .data$capacity)))
duplicate_theme_index <- duplicate_themes %>% pull(.data$theme_index)
duplicate_theme_names <- duplicate_themes %>% pull(.data$theme_name)
duplicate_theme_capacities <- duplicate_themes %>% pull(.data$capacity)
has_duplicated_theme <- ifelse(identical(duplicate_theme_names, character(0)), FALSE, TRUE)
for (j in seq_along(duplicate_theme_names)) {
if (verbose) {
if (isTRUE(duplicate_theme_capacities[j] == "")) {
cli_text("Dropped duplicate theme {.val {duplicate_theme_names[j]}} from {.val {story_id}}")
} else {
cli_text("Dropped duplicate theme {.val {duplicate_theme_names[j]}} <{.val {duplicate_theme_capacities[j]}}> from {.val {story_id}}")
}
themes <- themes %>% filter(.data$theme_index != duplicate_theme_index[j])
}
}
themes <- themes %>% select(-.data$theme_index)
if (isTRUE(has_undefined_theme || has_duplicated_theme)) {
stories_tbl$themes[story_index][[1]] <- themes %>%
distinct(.data$theme_name, .keep_all = TRUE)
}
}
}
if (isTRUE(file.exists(stub_stories_outfile_path) && !overwrite_rds && verbose)) {
cli_text("The file {.file {stub_stories_outfile_name}} is already cached and will not be regenerated")
} else {
stub_story_indices <- NULL
for (i in seq(nrow(stories_tbl))) {
story_index <- stories_tbl$story_index[i]
story_id <- stories_tbl$story_id[story_index]
component_story_ids <- stories_tbl %>%
filter(.data$story_id == !!story_id) %>%
select(.data$component_story_ids) %>%
unlist(use.names = FALSE)
number_of_component_stories <- length(component_story_ids)
number_of_themes <- stories_tbl %>%
filter(.data$story_id == !!story_id) %>%
select(.data$themes) %>%
unnest(cols = .data$themes) %>%
nrow()
total_number_of_component_story_themes <- 0
for (component_story_id in component_story_ids) {
number_of_component_story_themes <- stories_tbl %>%
filter(.data$story_id == !!component_story_id) %>%
select(.data$themes) %>%
unnest(cols = .data$themes) %>%
nrow()
total_number_of_component_story_themes <- total_number_of_component_story_themes + length(number_of_component_story_themes)
}
if (isTRUE(number_of_themes == 0 && total_number_of_component_story_themes == 0)) {
stub_story_indices <- c(stub_story_indices, story_index)
}
}
if (isTRUE(length(stub_story_indices) > 0)) {
stub_stories_tbl <- stories_tbl[stub_story_indices, ]
} else {
stub_stories_tbl <- stories_tbl[-stories_tbl$story_index, ]
}
}
if (verbose) cli_text("Found {.val {nrow(stories_tbl)}} stor{?y/ies} of which {.val {nrow(stub_stories_tbl)}} {?is/are} stub{?/s}")
if (isTRUE(nrow(stub_stories_tbl) > 0)) {
stories_tbl <- stories_tbl[-stub_story_indices, ]
stories_tbl$story_index <- 1 : nrow(stories_tbl)
stub_stories_tbl$story_index <- (nrow(stories_tbl) + 1) : (nrow(stub_stories_tbl) + nrow(stories_tbl))
}
saveRDS(stories_tbl, file = stories_outfile_path, compress = TRUE)
stories_outfile_size <- file.info(stories_outfile_path)$size
if (verbose) cli_text("Cached stories tibble to {.file {stories_outfile_path}} ({formatted_file_size(stories_outfile_size)})")
saveRDS(stub_stories_tbl, file = stub_stories_outfile_path, compress = TRUE)
stub_stories_outfile_size <- file.info(stub_stories_outfile_path)$size
if (verbose) cli_text("Cached stub stories tibble to {.file {stub_stories_outfile_path}} ({formatted_file_size(stub_stories_outfile_size)})")
return(invisible(NULL))
}
generate_collections_tbl <- function(
version,
overwrite_rds = FALSE,
verbose = TRUE) {
if (is_missing(version)) {
message <- get_missing_arg_msg(variable_name = "version")
abort(message, class = "missing_argument")
}
base_path <- file.path(stoRy_cache_path(), version)
collections_outfile_name <- "collections_tbl.Rds"
collections_outfile_path <- file.path(base_path, collections_outfile_name)
stub_collections_outfile_name <- "stub_collections_tbl.Rds"
stub_collections_outfile_path <- file.path(base_path, stub_collections_outfile_name)
if (isTRUE(file.exists(collections_outfile_path) && !overwrite_rds && verbose)) {
cli_text("The file {.file {collections_outfile_name}} is already cached and will not be regenerated")
return(invisible(NULL))
}
if (verbose) cli_text("Processing collections...")
infile_name <- paste0("lto-", version, "-collections.json")
infile_path <- file.path(base_path, infile_name)
if (!file.exists(infile_path)) {
message <- get_lto_json_file_not_found_msg(version, infile_path)
abort(message, class = "file_not_found")
}
json <- read_json(infile_path) %>% as.tbl_json()
main <- json %>%
enter_object('collections') %>%
gather_array('collection_index') %>%
spread_values(
collection_id = jstring('collection-id'),
title = jstring('title'),
date = jstring('date'),
description = jstring('description'),
source = jstring('source')
) %>%
select(-.data$document.id) %>%
as_tibble()
component_story_ids <- json %>%
enter_object('collections') %>%
gather_array('collection_index') %>%
enter_object('component-story-ids') %>%
gather_array %>%
append_values_string %>%
rename(component_story_ids = string) %>%
select(-.data$document.id, -.data$array.index) %>%
as_tibble()
references <- json %>%
enter_object('collections') %>%
gather_array('collection_index') %>%
enter_object('references') %>%
gather_array %>%
append_values_string %>%
rename(references = string) %>%
select(-.data$document.id, -.data$array.index) %>%
as_tibble()
theme_names <- json %>%
enter_object('collections') %>%
gather_array('collection_index') %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('name') %>%
append_values_string %>%
rename(theme_name = string) %>%
select(-.data$document.id) %>%
as_tibble()
theme_capacities <- json %>%
enter_object('collections') %>%
gather_array('collection_index') %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('capacity') %>%
append_values_string %>%
rename(capacity = string) %>%
select(-.data$document.id) %>%
as_tibble()
theme_levels <- json %>%
enter_object('collections') %>%
gather_array('collection_index') %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('level') %>%
append_values_string %>%
rename(level = string) %>%
select(-.data$document.id) %>%
as_tibble()
theme_motivations <- json %>%
enter_object('collections') %>%
gather_array('collection_index') %>%
enter_object('themes') %>%
gather_array('theme_index') %>%
enter_object('motivation') %>%
append_values_string %>%
rename(motivation = string) %>%
select(-.data$document.id) %>%
as_tibble()
themes <- theme_names %>%
right_join(theme_capacities, by = c('collection_index', 'theme_index')) %>%
right_join(theme_levels, by = c('collection_index', 'theme_index')) %>%
right_join(theme_motivations, by = c('collection_index', 'theme_index')) %>%
select(-.data$theme_index) %>%
as_tibble()
collections_tbl <- main %>%
nest_join(component_story_ids, by = "collection_index") %>%
nest_join(references, by = "collection_index") %>%
nest_join(themes, by = "collection_index") %>%
relocate(source, .after = "themes")
infile_name <- "themes_tbl.Rds"
infile_path <- file.path(base_path, infile_name)
if (!file.exists(infile_path)) {
message <- get_missing_lto_rds_file_msg(version, infile_path)
abort(message, class = "file_not_found")
}
themes_tbl <- readRDS(infile_path)
all_theme_names <- themes_tbl %>% pull(.data$theme_name)
for (i in seq(nrow(collections_tbl))) {
collection_index <- collections_tbl$collection_index[i]
collection_id <- collections_tbl$collection_id[collection_index]
themes <- collections_tbl %>%
filter(.data$collection_id == !!collection_id) %>%
select(.data$themes) %>%
unnest(cols = .data$themes)
has_undefined_theme <- FALSE
undefined_theme_names <- collections_tbl %>%
filter(.data$collection_id == !!collection_id) %>%
select(.data$themes) %>%
unnest(cols = .data$themes) %>%
pull(.data$theme_name) %>%
setdiff(all_theme_names)
for (j in seq_along(undefined_theme_names)) {
has_undefined_theme <- TRUE
themes <- themes %>%
filter(.data$theme_name != undefined_theme_names[j])
if (verbose) cli_text("Dropped undefined theme {.val {undefined_theme_names[j]}} from {.val {collection_id}}")
}
duplicate_theme_name_tokens <- themes %>%
filter(duplicated(.data$theme_name)) %>%
pull(.data$theme_name)
duplicate_theme_counts <- table(duplicate_theme_name_tokens)
duplicate_theme_names <- duplicate_theme_name_tokens %>% unique()
has_duplicated_theme <- ifelse(identical(duplicate_theme_names, character(0)), FALSE, TRUE)
for (j in seq_along(duplicate_theme_names)) {
duplicate_theme_count <- as.numeric(duplicate_theme_counts[duplicate_theme_names[j]])
if (isTRUE(duplicate_theme_count > 1 && verbose)) {
cli_text("Dropped {.val {duplicate_theme_count - 1}} of {.val {duplicate_theme_count}} occurrences of {.val {duplicate_theme_names[j]}} from {.val {story_id}}")
}
}
if (isTRUE(has_undefined_theme || has_duplicated_theme)) {
stories_tbl$themes[.data$story_index][[1]] <- themes %>%
distinct(.data$theme_name, .keep_all = TRUE)
}
}
infile_name <- "stub_stories_tbl.Rds"
infile_path <- file.path(base_path, infile_name)
if (!file.exists(infile_path)) {
message <- get_missing_lto_rds_file_msg(version, infile_path)
abort(message, class = "file_not_found")
}
stub_stories_tbl <- readRDS(infile_path)
stub_collection_indices <- NULL
candidate_stub_collection_ids <- intersect(collections_tbl$collection_id, str_c("Collection: ", stub_stories_tbl$story_id))
for (i in seq(nrow(collections_tbl))) {
collection_index <- collections_tbl$collection_index[i]
collection_id <- collections_tbl$collection_id[collection_index]
if (isTRUE(collection_id %in% candidate_stub_collection_ids)) {
component_story_ids <- collections_tbl %>%
filter(.data$collection_id == !!collection_id) %>%
select(.data$component_story_ids) %>%
unlist(use.names = FALSE)
nonstub_component_story_ids <- setdiff(component_story_ids, stub_stories_tbl$story_id)
if (isTRUE(length(nonstub_component_story_ids) == 0)) {
stub_collection_indices <- c(stub_collection_indices, collection_index)
}
}
}
if (isTRUE(length(stub_collection_indices) > 0)) {
stub_collections_tbl <- collections_tbl[stub_collection_indices, ]
} else {
stub_collections_tbl <- collections_tbl[-collections_tbl$collection_index, ]
}
if (isTRUE(nrow(collections_tbl) > 0)) {
for (i in seq(nrow(collections_tbl))) {
collection_index <- collections_tbl$collection_index[i]
collection_id <- collections_tbl$collection_id[collection_index]
component_story_ids <- collections_tbl %>%
filter(.data$collection_id == !!collection_id) %>%
pull(.data$component_story_ids) %>%
unlist(use.names = FALSE)
nonstub_component_story_ids <- setdiff(component_story_ids , stub_stories_tbl$story_id)
number_of_stub_component_story_ids <- length(component_story_ids) - length(nonstub_component_story_ids)
if (isTRUE(number_of_stub_component_story_ids > 0)) {
if (verbose) cli_text("Dropped {.val {number_of_stub_component_story_ids}} stub component stor{?y/ies} from {.val {collection_id}}")
collections_tbl$component_story_ids[collection_index][[1]] <- tibble(component_story_ids = nonstub_component_story_ids)
}
}
}
if (isTRUE(length(stub_collection_indices) > 0)) {
collections_tbl <- collections_tbl[-stub_collection_indices, ]
collections_tbl$collection_index <- 1 : nrow(collections_tbl)
stub_collections_tbl$collection_index <- (nrow(collections_tbl) + 1) : (nrow(stub_collections_tbl) + nrow(collections_tbl))
}
if (verbose) cli_text("Found {.val {nrow(collections_tbl)}} collection{?/s} of which {.val {nrow(stub_collections_tbl)}} {?is a/are} stub{?/s}")
infile_name <- "stories_tbl.Rds"
infile_path <- file.path(base_path, infile_name)
if (!file.exists(infile_path)) {
message <- get_missing_lto_rds_file_msg(version, infile_path)
abort(message, class = "file_not_found")
}
stories_tbl <- readRDS(infile_path)
collections_tbl <- collections_tbl %>% add_row(tibble(
collection_index = NA,
collection_id = "Collection: All Stories",
title = "All Stories",
date = NA,
description = "All LTO thematically annotated stories.",
component_story_ids = list(tibble(component_story_ids = stories_tbl$story_id)),
references = list(tibble(references = character(0))),
themes = list(tibble(data.frame(theme_name = character(0), level = character(0), motivation = character(0)))),
source = NA))
collections_tbl$collection_index <- 1 : nrow(collections_tbl)
saveRDS(collections_tbl, file = collections_outfile_path, compress = TRUE)
collections_outfile_size <- file.info(collections_outfile_path)$size
if (verbose) cli_text("Cached collections tibble to {.file {collections_outfile_path}} ({formatted_file_size(collections_outfile_size)})")
saveRDS(stub_collections_tbl, file = stub_collections_outfile_path, compress = TRUE)
stub_collections_outfile_size <- file.info(stub_collections_outfile_path)$size
if (verbose) cli_text("Cached stub collections tibble to {.file {stub_collections_outfile_path}} ({formatted_file_size(stub_collections_outfile_size)})")
return(invisible(NULL))
}
generate_metadata_tbl <- function(
version,
overwrite_rds = FALSE,
verbose = TRUE) {
if (is_missing(version)) {
message <- get_missing_arg_msg(variable_name = "version")
abort(message, class = "missing_argument")
}
outfile_name <- "metadata_tbl.Rds"
base_path <- file.path(stoRy_cache_path(), version)
outfile_path <- file.path(base_path, outfile_name)
if (isTRUE(file.exists(outfile_path) && !overwrite_rds && verbose)) {
cli_text("The file {.file {outfile_name}} is already cached and will not be regenerated")
return(invisible(NULL))
}
if (verbose) cli_text("Processing metadata...")
metadata_tbl <- tibble(
name = character(),
value = character()
)
infile_name <- paste0("lto-", version, "-themes.json")
infile_path <- file.path(base_path, infile_name)
if (!file.exists(infile_path)) {
message <- get_lto_json_file_not_found_msg(version, infile_path)
abort(message, class = "file_not_found")
}
json <- read_json(infile_path) %>% as.tbl_json()
themes_metadata_tbl <- json %>%
enter_object('lto') %>%
gather_object %>%
append_values_string
metadata_tbl <- metadata_tbl %>%
add_row(name = "version", value = themes_metadata_tbl %>% `[[`(1, 3))
metadata_tbl <- metadata_tbl %>%
add_row(name = "timestamp", value = themes_metadata_tbl %>% `[[`(2, 3))
metadata_tbl <- metadata_tbl %>%
add_row(name = "git_commit_id", value = themes_metadata_tbl %>% `[[`(3, 3))
metadata_tbl <- metadata_tbl %>%
add_row(name = "encoding", value = themes_metadata_tbl %>% `[[`(4, 3))
infile_name <- "themes_tbl.Rds"
infile_path <- file.path(base_path, infile_name)
if (!file.exists(infile_path)) {
message <- get_missing_lto_rds_file_msg(version, infile_path)
abort(message, class = "file_not_found")
}
themes_tbl <- readRDS(infile_path)
metadata_tbl <- metadata_tbl %>%
add_row(name = "theme_count", value = as.character(nrow(themes_tbl)))
infile_name <- "stories_tbl.Rds"
infile_path <- file.path(base_path, infile_name)
if (!file.exists(infile_path)) {
message <- get_lto_json_file_not_found_msg(version, infile_path)
abort(message, class = "file_not_found")
}
stories_tbl <- readRDS(infile_path)
metadata_tbl <- metadata_tbl %>%
add_row(name = "story_count", value = as.character(nrow(stories_tbl)))
infile_name <- "collections_tbl.Rds"
infile_path <- file.path(base_path, infile_name)
if (!file.exists(infile_path)) {
message <- get_missing_lto_rds_file_msg(version, infile_path)
abort(message, class = "file_not_found")
}
collections_tbl <- readRDS(infile_path)
metadata_tbl <- metadata_tbl %>%
add_row(name = "collection_count", value = as.character(nrow(collections_tbl)))
saveRDS(metadata_tbl, file = outfile_path, compress = TRUE)
outfile_size <- file.info(outfile_path)$size
if (verbose) cli_text("Cached metadata tibble to {.file {outfile_path}} ({formatted_file_size(outfile_size)})")
return(invisible(NULL))
}
generate_background_collection <- function(
version,
overwrite_rds = FALSE,
verbose = TRUE) {
if (is_missing(version)) {
message <- get_missing_arg_msg(variable_name = "version")
abort(message, class = "missing_argument")
}
outfile_name <- "background_collection.Rds"
base_path <- file.path(stoRy_cache_path(), version)
outfile_path <- file.path(base_path, outfile_name)
if (isTRUE(file.exists(outfile_path) && !overwrite_rds && verbose)) {
cli_text("The file {.file {outfile_name}} is already cached and will not be regenerated")
return(invisible(NULL))
}
if (verbose) cli_text("Generating default background collection...")
old_active_version <- which_lto()
set_lto(version, verbose = FALSE, load_background_collection = FALSE)
collections_tbl <- get_collections_tbl() %>%
filter(.data$collection_id == "Collection: All Stories")
background_collection <- Collection$new(collection_id = "Collection: All Stories")
set_lto(version = old_active_version, verbose = FALSE)
saveRDS(background_collection, file = outfile_path, compress = TRUE)
outfile_size <- file.info(outfile_path)$size
if (verbose) cli_text("Cached default background collection to {.file {outfile_path}} ({formatted_file_size(outfile_size)})")
return(invisible(NULL))
} |
register_namespace_callback = function(pkgname, namespace, callback) {
assert_string(pkgname)
assert_string(namespace)
assert_function(callback)
remove_hook = function(event) {
hooks = getHook(event)
pkgnames = vapply(hooks, function(x) {
ee = environment(x)
if (isNamespace(ee)) environmentName(ee) else environment(x)$pkgname
}, NA_character_)
setHook(event, hooks[pkgnames != pkgname], action = "replace")
}
remove_hooks = function(...) {
remove_hook(packageEvent(namespace, "onLoad"))
remove_hook(packageEvent(pkgname, "onUnload"))
}
if (isNamespaceLoaded(namespace)) {
callback()
}
setHook(packageEvent(namespace, "onLoad"), callback, action = "append")
setHook(packageEvent(pkgname, "onUnload"), remove_hooks, action = "append")
} |
plotSEMM_setup2 <- function(setup, alpha = .025, boot = NULL, boot.CE=FALSE, boot.CI=TRUE,
points = 50, fixed_value=NA){
if(!is.na(fixed_value)) points <- points + 1
nclass <- classes <- setup$nclass
nparam <- setup$nparm; acov <- setup$acov; loc <- setup$loc
c_loc <- loc$c_loc; alpha_loc <- loc$alpha_loc; beta_loc <- loc$beta_loc;
psi_loc <- loc$psi_loc
locations <- c(c_loc,alpha_loc,beta_loc,psi_loc[seq(from=1, to=length(psi_loc), by=2)])
p <- nclass*(4)+(nclass-1)
p1 <- length(unique(locations))
pars <- setup$pars
alphaarray <- pars$alphaarray; psiarray <- pars$psiarray;
gamma <- betavec <- pars$betavec; ci_v <- pars$ci_v
means <- setup$means
if(any(psiarray < 0))
stop('Negative variances supplied. Please fix.')
sum_expi <- sum(exp(ci_v))
pi_v <- exp(ci_v) / sum_expi
alphaarray2 <- array(data = NA, c(2, 1, classes))
betaarray <- array(data = NA, c(2, 2, classes))
psiarray2 <- array(data = NA, c(2, 2, classes))
for (i in 1:classes) {
alphaarray2[, , i] <- matrix(c(alphaarray[1, i], alphaarray[2, i]), 2, 1, byrow = TRUE)
betaarray[, , i] <- matrix(c(0, 0, betavec[i], 0), 2, 2, byrow = TRUE)
psiarray2[, , i] <- matrix(c(psiarray[1, i], 0, 0, psiarray[2, i]), 2, 2, byrow = TRUE)
}
IMPCOV <- array(data = NA, c(2, 2, classes))
IMPMEAN <- array(data = NA, c(2, 2, classes))
for (i in 1:classes) {
IMPCOV[, , i] <- solve(diag(x = 1, nrow = 2, ncol = 2) - betaarray[, , i]) %*% (psiarray2[, , i]) %*% t(solve(diag(x = 1,
nrow = 2, ncol = 2) - betaarray[, , i]))
IMPMEAN[, , i] <- solve(diag(x = 1, nrow = 2, ncol = 2) - betaarray[, , i]) %*% (alphaarray2[, , i])
}
MuEta_1 <- vector(mode = "numeric", length = classes)
MuEta_2 <- vector(mode = "numeric", length = classes)
VEta_1 <- vector(mode = "numeric", length = classes)
VEta_2 <- vector(mode = "numeric", length = classes)
COVKSIETA <- vector(mode = "numeric", length = classes)
for (i in 1:classes) {
MuEta_1[i] = IMPMEAN[1, 1, i]
MuEta_2[i] = IMPMEAN[2, 2, i]
VEta_1[i] = IMPCOV[1, 1, i]
VEta_2[i] = IMPCOV[2, 2, i]
COVKSIETA[i] = IMPCOV[1, 2, i]
}
muEta1 <- 0
muEta2 <- 0
for (i in 1:classes) {
muEta1 <- muEta1 + pi_v[i] * MuEta_1[i]
muEta2 <- muEta2 + pi_v[i] * MuEta_2[i]
}
vEta1 <- 0
vEta2 <- 0
for (i in 1:classes) {
for (j in 1:classes) {
if (i < j) {
vEta1 <- vEta1 + pi_v[i] * pi_v[j] * (MuEta_1[i] - MuEta_1[j])^2
vEta2 <- vEta2 + pi_v[i] * pi_v[j] * (MuEta_2[i] - MuEta_2[j])^2
}
}
}
for (i in 1:classes) {
vEta1 <- vEta1 + pi_v[i] * VEta_1[i]
vEta2 <- vEta2 + pi_v[i] * VEta_2[i]
}
LEta1 = muEta1 - 3 * sqrt(vEta1)
UEta1 = muEta1 + 3 * sqrt(vEta1)
LEta2 = muEta2 - 3 * sqrt(vEta2)
UEta2 = muEta2 + 3 * sqrt(vEta2)
LB = min(LEta1, LEta2)
UB = max(UEta1, UEta2)
Eta1 <- seq(LEta1, UEta1, length = points - !is.na(fixed_value))
Eta2 <- seq(LEta2, UEta2, length = points - !is.na(fixed_value))
if(!is.na(fixed_value)){
Eta1 <- c(Eta1, fixed_value)
Eta2 <- c(Eta2, fixed_value)
}
r <- vector(mode = "numeric", length = classes)
for (i in 1:classes) {
r[i] <- COVKSIETA[i]/sqrt(VEta_1[i] * VEta_2[i])
}
denKE <- function(Eta1, Eta2) {
placeholder <- 0
denKE_ <- matrix(data = 0, nrow = length(Eta1), ncol = classes)
for (i in 1:classes) {
z <- ((Eta1 - MuEta_1[i])^2)/VEta_1[i] + ((Eta2 - MuEta_2[i])^2)/VEta_2[i] - 2 * r[i] * (Eta1 - MuEta_1[i]) * (Eta2 -
MuEta_2[i])/sqrt(VEta_1[i] * VEta_2[i])
denKE_[, i] <- (1/(2 * 22/7 * sqrt(VEta_1[i]) * sqrt(VEta_2[i]) * sqrt(1 - r[i]^2))) * exp(-z/(2 * (1 - r[i]^2)))
}
for (i in 1:classes) {
placeholder <- placeholder + pi_v[i] * denKE_[, i]
}
denKE <- placeholder
}
z <- outer(Eta1, Eta2, denKE)
x <- Eta1
x2 <- Eta2
phi <- array(data = 0, c(points, classes))
for (i in 1:classes) {
phi[, i] <- dnorm(x, mean = alphaarray[1, i], sd = sqrt(psiarray[1, i]))
}
a_pi <- array(data = 0, c(points, classes))
a_pi2 <- array(data = 0, c(points, classes))
for (i in 1:classes) {
a_pi[, i] <- pi_v[i] * dnorm(x, mean = MuEta_1[i], sd = sqrt(VEta_1[i]))
a_pi2[, i] <- pi_v[i] * dnorm(x2, mean = MuEta_2[i], sd = sqrt(VEta_2[i]))
}
sumpi <- array(data = 0, c(points, 1))
sumpi2 <- array(data = 0, c(points, 1))
for (i in 1:classes) {
sumpi[, 1] <- sumpi[, 1] + a_pi[, i]
sumpi2[, 1] <- sumpi2[, 1] + a_pi2[, i]
}
pi <- array(data = 0, c(points, classes))
for (i in 1:classes) {
pi[, i] <- a_pi[, i]/sumpi[, 1]
}
y <- 0
for (i in 1:classes) {
y <- y + pi[, i] * (alphaarray[2, i] + gamma[i] * x)
}
D <- 0
for (i in 1:classes) {
D = D + exp(ci_v[i]) * phi[, i]
}
dalpha <- array(data = 0, c(points, classes))
dphi <- array(data = 0, c(points, classes))
dc <- array(data = 0, c(points, classes - 1))
for (i in 1:classes) {
for (j in 1:classes) {
if (i != j) {
dalpha[, i] <- dalpha[, i] + ((exp(ci_v[j]) * phi[, j] * ((alphaarray[2, i] - alphaarray[2, j]) + (gamma[i] -
gamma[j]) * x)))
dphi[, i] <- dphi[, i] + ((exp(ci_v[j]) * phi[, j] * ((alphaarray[2, i] - alphaarray[2, j]) + (gamma[i] - gamma[j]) *
x)))
}
}
dalpha[, i] <- (dalpha[, i] * exp(ci_v[i]) * phi[, i] * ((x - alphaarray[1, i])/psiarray[1, i])) * (1/D^2)
dphi[, i] <- dphi[, i] * exp(ci_v[i]) * phi[, i] * (((x - alphaarray[1, i])^2 - 1)/psiarray[1, i]) * (1/(2 * psiarray[1,
i])) * (1/D^2)
}
if(classes > 1){
for (i in 1:(classes - 1)) {
for (j in 1:(classes)) {
if (i != j) {
dc[, i] <- dc[, i] + (exp(ci_v[j]) * phi[, j] * ((alphaarray[2, i] - alphaarray[2, j]) + (gamma[i] - gamma[j]) *
x))
}
}
dc[, i] <- dc[, i] * exp(ci_v[i]) * phi[, i] * (1/D^2)
}
}
dkappa <- array(data = 0, c(points, classes))
dgamma <- array(data = 0, c(points, classes))
for (i in 1:classes) {
dkappa[, i] <- exp(ci_v[i]) * phi[, i]/D
dgamma[, i] <- exp(ci_v[i]) * phi[, i] * x/D
}
ct <- 0
varordered <- c()
for (i in 1:classes) {
varordered <- c(varordered, alpha_loc[i + ct], alpha_loc[i + 1 + ct], beta_loc[i])
ct <- ct + 1
}
varordered <- c(varordered, c_loc)
ct <- 0
for (i in 1:classes) {
varordered <- c(varordered, psi_loc[i + ct])
ct <- ct + 1
}
acovd <- acov[varordered, varordered]
deriv <- c()
for (i in 1:classes) {
deriv <- cbind(deriv, dalpha[, i], dkappa[, i], dgamma[, i])
}
deriv <- c(deriv, dc, dphi)
deriv <- matrix(deriv, nrow = points, ncol = p)
se <- sqrt(diag(deriv %*% acovd %*% t(deriv)))
q <- abs(qnorm(alpha/2, mean = 0, sd = 1))
sq <- sqrt(qchisq(1 - alpha, p))
lo <- y - q * se
hi <- y + q * se
slo <- y - sq * se
shi <- y + sq * se
if(boot.CI){
draws <- 1000
bs <- bs.CE(boot, x=x, alpha=alpha, boot=TRUE)
yall <- bs$bs.yall
yall <- apply(yall, 2, sort)
LCL = (alpha/2) * draws
UCL = (1 - (alpha/2)) * draws
LCLall = yall[LCL, ]
UCLall = yall[UCL, ]
} else {
LCLall <- UCLall <- numeric(length(lo))
}
Ksi <- Eta1
Eta <- Eta2
denKsi <- sumpi
denEta <- sumpi2
post <- pi
pKsi <- a_pi
pEta <- a_pi2
etahmat <- matrix(data = 0, nrow = length(Ksi), ncol = classes)
for (i in 1:classes) {
etahmat[, i] <- alphaarray[2, i] + gamma[i] * Ksi
}
etah_ <- y
lo_ <- lo
hi_ <- hi
slo_ <- slo
shi_ <- shi
LCLall_ <- LCLall
UCLall_ <- UCLall
bs_lo <- bs_high <- 0
if(boot.CE){
bs <- bs.CE(boot, x=x, alpha=alpha, boot=FALSE)
bs_lo <- bs$lb
bs_high <- bs$ub
}
SEMLIdatapks <- data.frame(Eta1=Ksi, Eta2=Eta, agg_denEta1=denKsi, agg_denEta2=denEta,
agg_pred=etah_, class_pred=I(etahmat),
contour=I(z), classes=classes, class_prob=I(post), class_denEta1=I(pKsi),
class_denEta2=I(pEta), bs_CIlo=LCLall_,
bs_CIhi=UCLall_, delta_CIlo=lo_, delta_CIhi=hi_, delta_CElo=slo_,
delta_CEhi=shi_, x, alpha=alpha, setup2=TRUE,
boot=boot.CE, bs_CElo=bs_lo, bs_CEhi=bs_high)
SEMLIdatapks
} |
ReadGem_v0.85C = function(nums = 0:9999, path = './', SN = character(), alloutput = FALSE, verbose = TRUE, requireGPS = FALSE, requireAbsoluteGPS = FALSE, t0 = '2000-01-01 00:01:00'){
tf0 = strptime(t0, format = '%Y-%m-%d %H:%M:%OS', tz = 'GMT')
last_millis = NaN
preamble_length = 4
fn = list.files(path, '^FILE[[:digit:]]{4}\\.[[:alnum:]]{3}$')
num_strings = paste('000', nums, sep = '')
num_strings = substr(num_strings, nchar(num_strings) - 3, nchar(num_strings))
fn = fn[substr(fn, 1, 8) %in% paste('FILE', num_strings, sep = '')]
fn = paste(path, fn, sep = '/')
ext = substr(fn, nchar(fn)-2, nchar(fn))
if(0 == length(SN) || is.na(SN)){
uext = unique(ext[ext != 'TXT'])
SN = uext[which.max(sapply(uext, function(x)sum(ext == x)))]
if(0 != length(SN) && !is.na(SN)){
warning(paste('Serial number not set; using', SN))
}
}
if(0 != length(SN)){
fn = fn[ext %in% c(SN, 'TXT')]
}
empty_time = Sys.time()[-1]
OUTPUT = list(t = empty_time, p = numeric(), header = list(), metadata = list(), gps = list())
for(i in 1:length(fn)){
if(verbose) print(paste('File', i, 'of', length(fn), ':', fn[i]))
L = list()
SN_i = scan(fn[i], skip = preamble_length, nlines = 1, sep = ',', what = character(), quiet = TRUE)[2]
if((0 == length(SN) || is.na(SN)) && i == 1){
SN = SN_i
warning(paste('Serial number not set; using', SN_i))
}else if(length(SN_i) == 0 || is.na(SN_i) || SN_i != SN){
warning(paste('Skipping file ', fn[i], ': wrong or missing serial number', sep = ''))
next
}
L$SN = SN_i
R = readLines(fn[i])
if(length(R) == 0){
warning(paste('Skipping empty file', fn[i]))
next
}
body = R[(preamble_length+2):length(R)]
body = body[!is.na(iconv(body))]
linetype = substr(body, 1, 1)
wg = which(linetype == 'G')
wp = which(linetype == 'P')
if(length(wg) == 0 && requireAbsoluteGPS){
warning(paste('Skipping file (no GPS strings): ', fn[i]))
next
}else if(length(wp) == 0 && requireGPS){
warning(paste('Skipping file (no GPS at all): ', fn[i]))
next
}
wm = which(linetype == 'M')
wd = which(linetype == 'D')
wr = which(linetype == 'R')
if(length(wd) == 0){
next
}
L2M_input = paste('D,', substring(body[wd], first = 2))
L$d = Lines2Matrix(L2M_input, 2)
if(length(wp) > 0){
pps = Lines2Matrix(body[wp], 1)
}else{
pps = NULL
}
if(length(attr(L$d, 'na.values')) > 0){
warning('Skipping ', length(attr(L$d, 'na.values')), ' corrupt data lines in file ', fn[i], ': could cause timing errors')
wd = wd[-attr(L$d, 'na.values')]
}
L$d = as.data.frame(L$d); names(L$d) = c('millis', 'pressure')
L$d$pressure = cumsum(L$d$pressure)
if(length(wg) > 0){
L$g = Lines2Matrix(body[wg], 10)
if(length(attr(L$g, 'na.values')) > 0){
warning('Skipping ', length(attr(L$g, 'na.values')), ' corrupt GPS lines in file ', fn[i], ': could cause timing errors')
wg = wg[-attr(L$g, 'na.values')]
}
L$g = as.data.frame(L$g); names(L$g) = c('millis', 'millisLag', 'yr', 'mo', 'day', 'hr', 'min', 'sec', 'lat', 'lon')
L$g$td = getjul(L$g$yr, L$g$mo, L$g$day) + L$g$hr/24 + L$g$min/1440 + L$g$sec/86400
L$g$tf = 0 + strptime(paste(paste(L$g$yr, L$g$mo, L$g$day, sep = '-'), paste(L$g$hr, L$g$min, L$g$sec, sep=':')), format = '%Y-%m-%d %H:%M:%OS', tz = 'GMT')
}else if(length(wp) > 0){
L$g = vector('list', 10)
L$g$millis = pps
}
if(length(wm) > 0){
L$m = Lines2Matrix(body[wm], 12)
if(length(attr(L$m, 'na.values')) > 0){
warning('Skipping ', length(attr(L$m, 'na.values')), ' corrupt metadata lines in file ', fn[i], ': could cause timing errors')
wm = wm[-attr(L$m, 'na.values')]
}
L$m = as.data.frame(L$m); names(L$m) = c('millis', 'batt', 'temp', 'A2', 'A3', 'maxWriteTime', 'minFifoFree', 'maxFifoUsed', 'maxOverruns', 'gpsOnFlag', 'unusedStack1', 'unusedStackIdle')
L$m$t = rep(NA, length(L$m$millis))
class(L$m$t) = c('POSIXct', 'POSIXt')
}
if(!(requireAbsoluteGPS && length(wg)==0)){
millis = 0*1:length(body)
millis[wd] = L$d$millis
if(length(wg) > 0){
millis[wg] = L$g$millis
}
if(length(wm) > 0){
millis[wm] = L$m$millis
}
if(length(wp) > 0){
millis[wp] = pps
}
wn = which(!((1:length(millis)) %in% c(wd, wm, wg, wp)))
if(length(wn) > 0){
millis[wn[wn>1]] = millis[wn[wn>1]-1]
if(any(wn == 1)){
millis[1] = millis[2]
}
}
millis_unwrap = unwrap(millis, 2^13)
L$d$millis = millis_unwrap[wd]
if(length(wg) > 0){
L$g$millis = millis_unwrap[wg]
}
if(length(wm) > 0){
L$m$millis = millis_unwrap[wm]
}
if(length(wg) > 1){
n = length(L$g$tf)
time_min = 0+strptime('1776-07-04 00:00:00', '%Y-%m-%d %H:%M:%S', 'GMT')
time_max = 0+strptime('9999-12-31 23:59:59', '%Y-%m-%d %H:%M:%S', 'GMT')
wna = (L$g$yr == 2000 | L$g$sec != round(L$g$sec) | L$g$lat == 0 | L$g$millisLag > 1000 | L$g$yr > 2025 | L$g$yr < 2014 | L$g$mo > 12 | L$g$day > 31 | L$g$hr > 23 | L$g$min > 59 | L$g$sec > 60 | L$g$tf[1:n] > c(L$g$tf[2:n],time_max) | L$g$tf[1:n] < c(time_min, L$g$tf[1:(n-1)]) )
wna = wna & !is.na(wna)
wgood = !wna
if(sum(wgood) > 1){
l = lm(L$g$tf[wgood] ~ L$g$millis[wgood])
l$residuals = as.numeric(l$residuals)
}
while(any(abs(l$residuals) > 3*sd(l$residuals)) && sum(wgood) > 1){
wgood[which(wgood)[abs(l$residuals) > 3*sd(l$residuals)]] = FALSE
wna = !wgood
l = lm(L$g$tf[wgood] ~ L$g$millis[wgood])
l$residuals = as.numeric(l$residuals)
}
if(sum(wna)>0){
L$g[wna,3:11] = NaN
wg = wg[wgood]
L$g = L$g[wgood,]
}
}else if(length(pps) > 1){
L$g$millis = millis_unwrap[wp]
objective_function = function(pars){
offset = pars[1]
drift = pars[2]
mean(mod_pm(L$g$millis - offset, 1000 * (1 + drift))^2) + (drift/3e-5)^2/10000
}
l = optim(c(mod_pm(L$g$millis[1], 1000), 0), objective_function)
L$g$tf = tf0 + (L$g$millis - l$par[1]) / (1000 * (1 + l$par[2]))
L$g$yr = as.numeric(format(L$g$tf, format = '%Y'))
L$g$mo = as.numeric(format(L$g$tf, format = '%m'))
L$g$day = as.numeric(format(L$g$tf, format = '%d'))
L$g$hr = as.numeric(format(L$g$tf, format = '%H'))
L$g$min = as.numeric(format(L$g$tf, format = '%M'))
L$g$sec = as.numeric(format(L$g$tf, format = '%OS'))
L$g$lat = rep(NaN, length(L$g$yr))
L$g$lon = rep(NaN, length(L$g$yr))
L$g$td = getjul(L$g$yr, L$g$mo, L$g$day) + L$g$hr/24 + L$g$min/1440 + L$g$sec/86400
}
if(length(L$g$tf) > 1){
l = lm(L$g$tf ~ L$g$millis)
l$residuals = as.numeric(l$residuals)
timecorrected = as.POSIXct(l$coefficients[1] + millis_unwrap * l$coefficients[2], origin = '1970-01-01')
L$g$t = timecorrected[wg]
L$d$t = timecorrected[wd]
if(length(wm) > 0){
L$m$t = timecorrected[wm]
}
}else{
if(length(wm) > 0){
L$m$t = L$m$millis + NA
class(L$m$t) = c('POSIXct', 'POSIXt')
}
L$d$t = L$d$millis + NA
}
sampledelayerrors = abs((diff(L$d$t) - 0.01))
if(any(sampledelayerrors > 0.0025, na.rm = TRUE)){
warning('File ', fn[i], ': ', sum(sampledelayerrors > 0.0025), ' samples with time errors > 0.0025 s; max time error ', max(sampledelayerrors))
}
}
if(is.na(last_millis)) last_millis = millis[wd[1]]
OUTPUT$p = c(OUTPUT$p, L$d$pressure)
if(length(wm) > 0){
OUTPUT$metadata = rbind(OUTPUT$metadata, L$m)
}
if(length(wg) > 1){
OUTPUT$gps = rbind(OUTPUT$gps, as.data.frame(cbind(year = L$g$yr, date = L$g$td, lat = L$g$lat, lon = L$g$lon)))
}
if(length(wp) > 1){
pps_combined = list(millis = sort(unique(millis_unwrap[c(wp,wg)])))
w = (pps_combined$millis %in% millis_unwrap[wg])
for(k in c('tf', 'td', 'lat', 'lon')){
pps_combined[[k]][w] = L$g[[k]]
pps_combined[[k]][!w] = NaN
}
pps_combined$millis = pps_combined$millis - L$d$millis[1] + (millis[wd[1]] - last_millis)
OUTPUT$pps = rbind(OUTPUT$pps, as.data.frame(pps_combined))
}
OUTPUT$header$file[i] = fn[i]
OUTPUT$header$SN[i] = L$SN
if(length(wg) != 0){
OUTPUT$header$lat[i] = median(L$g$lat, na.rm=TRUE)
OUTPUT$header$lon[i] = median(L$g$lon, na.rm = TRUE)
OUTPUT$header$t1[i] = min(L$d$t)
OUTPUT$header$t2[i] = max(L$d$t)
}else{
OUTPUT$header$lat[i] = NaN
OUTPUT$header$lon[i] = NaN
OUTPUT$header$t1[i] = NaN
OUTPUT$header$t2[i] = NaN
}
if(alloutput){
OUTPUT$header$alloutput[[i]] = L
}
if(!requireGPS && length(wg) == 0 && length(wp) == 0){
warning('File ', fn[i], ': No timing/location info available from GPS')
OUTPUT$t = c(OUTPUT$t, L$d$t)
}else if(!requireGPS && length(wg) == 0 && length(wp) > 0){
warning('File ', fn[i], ': Clock drift corrected, but no absolute timing/location info available from GPS')
OUTPUT$t = c(OUTPUT$t, tf0 + (millis[wd[1]] - last_millis)/1000 + (L$d$t-L$d$t[1]))
}else{
OUTPUT$t = c(OUTPUT$t, L$d$t)
}
if(length(wm) == 0){
warning('File ', fn[i], ': No metadata available')
}
print(c(length(L$d$t), length(L$d$pressure)))
tf0 = OUTPUT$t[length(OUTPUT$t)]
last_millis = millis[wd[length(wd)]]
}
OUTPUT$p = to_int16(OUTPUT$p)
invisible(OUTPUT)
}
Lines2Matrix = function(x, n){
NaNcheck = function(x){
q = as.numeric(x[1 + 1:n])
if(any(is.na(q))) rep(NaN, n) else q
}
y = t(sapply(strsplit(x, ','), NaNcheck))
w = is.na(y[,1])
y = y[!w,]
if(length(y) == n) y = matrix(y, 1, n)
attr(y, 'na.values') = which(w)
y
}
unwrap = function(x, m){
cumsum(c(x[1], (((diff(x)+m/2) %% m)-m/2)))
}
to_int16 = function(x){
((x + 2^15) %% 2^16) - 2^15
}
mod_pm = function(x, m){
((x + m/2) %% m) - m/2
} |
rbind.compareGroups<-function(..., caption)
{
list.names <- function(...) {
deparse.level<-1
l <- as.list(substitute(list(...)))[-1L]
nm <- names(l)
fixup <- if (is.null(nm))
seq_along(l)
else nm == ""
dep <- sapply(l[fixup], function(x) switch(deparse.level + 1, "", if (is.symbol(x)) as.character(x) else "",
deparse(x, nlines = 1)[1L]))
if (is.null(nm))
dep
else {
nm[fixup] <- dep
nm
}
}
args<-list(...)
if (missing(caption))
caption<-list.names(...)
else{
if (!is.null(caption))
if (length(caption)!=length(args))
stop("length of caption must be the number of 'compareGroups' objects to be combined")
}
cc<-unlist(lapply(args, function(x) !inherits(x,"compareGroups")))
if (any(cc))
stop("arguments must be of class 'compareGroups'")
out<-list()
nn<-varnames.orig<-character(0)
k<-1
for (i in 1:length(args)){
args.i<-args[[i]]
if (!is.null(caption) && !is.null(attr(args.i,"caption")))
warning(paste("Captions for",caption[i],"table will be removed"))
for (j in 1:length(args.i)){
out[[k]]<-args.i[[j]]
k<-k+1
}
nn<-c(nn,names(args.i))
varnames.orig<-c(varnames.orig,attr(args.i,"varnames.orig"))
}
Xlong <- as.data.frame(lapply(args, function(args.i) attr(args.i,"Xlong")))
names(out)<-nn
attr(out,"yname")<-attr(args[[1]],"yname")
attr(out,"yname.orig")<-attr(args[[1]],"yname.orig")
attr(out,"ny")<-attr(args[[1]],"ny")
attr(out,"groups")<-attr(args[[1]],"groups")
attr(out,"varnames.orig")<-varnames.orig
attr(out,"Xlong")<-Xlong
attr(out,"ylong")<-attr(args.i,"ylong")
if (!is.null(caption)){
lc<-cumsum(unlist(lapply(args,length)))
cc<-rep("",sum(unlist(lapply(args,length))))
lc<-c(0,lc[-length(lc)])+1
cc[lc]<-caption
attr(out,"caption")<-cc
}
class(out)<-c("rbind.compareGroups","compareGroups")
out
} |
bwconncomp = function(infile,
outfile = NULL,
retimg = TRUE,
conn = 26,
reorient = FALSE,
spmdir = spm_dir(),
verbose = TRUE,
install_dir = NULL){
install_spm12(verbose = verbose,
install_dir = install_dir)
infile = checkimg(infile, gzipped = FALSE)
infile = path.expand(infile)
if (retimg) {
if (is.null(outfile)) {
outfile = tempfile(fileext = ".nii")
}
} else {
stopifnot(!is.null(outfile))
}
outfile = path.expand(outfile)
if (grepl("\\.gz$", infile)) {
infile = R.utils::gunzip(infile,
remove = FALSE,
temporary = TRUE,
overwrite = TRUE)
} else {
infile = paste0(nii.stub(infile), ".nii")
}
stopifnot(file.exists(infile))
gzip_outfile = FALSE
if (grepl("\\.gz$", outfile)) {
gzip_outfile = TRUE
outfile = nii.stub(outfile)
outfile = paste0(outfile, ".nii")
}
cmd = ""
if (!is.null(spmdir)) {
spmdir = path.expand(spmdir)
cmd = paste(cmd, sprintf("addpath(genpath('%s'));", spmdir))
}
cmds = c(cmd,
sprintf("ROI = '%s'", infile),
sprintf("ROIf = '%s'", outfile),
"%-Connected Component labelling",
"V = spm_vol(ROI);",
"dat = spm_read_vols(V);",
paste0("cc = bwconncomp(dat > 0, ", conn, ");"),
"dat = labelmatrix(cc);",
"%-Write new image",
"V.fname = ROIf;",
"V.private.cal = [0 1];",
"spm_write_vol(V,dat);")
sname = paste0(tempfile(), ".m")
writeLines(cmds, con = sname)
if (verbose) {
message(paste0("
}
res = run_matlab_script(sname)
if (gzip_outfile) {
R.utils::gzip(outfile, overwrite = TRUE, remove = TRUE)
outfile = paste0(nii.stub(outfile), ".nii.gz")
}
if (retimg) {
if (verbose) {
message(paste0("
}
res = readnii(outfile, reorient = reorient)
} else {
res = outfile
}
return(res)
} |
lp.control <- function(lprec, ..., reset = FALSE)
{
if(reset)
.Call(RlpSolve_reset_params, lprec)
status <- list()
dots <- list(...)
dot.names <- names(dots)
controls <- c("anti.degen", "basis.crash", "bb.depthlimit", "bb.floorfirst",
"bb.rule", "break.at.first", "break.at.value", "epslevel",
"epsb", "epsd", "epsel", "epsint", "epsperturb", "epspivot",
"improve", "infinite", "maxpivot", "mip.gap", "negrange",
"obj.in.basis", "pivoting", "presolve", "scalelimit", "scaling",
"sense", "simplextype", "timeout", "verbose")
dot.names <- match.arg(dot.names, controls, several.ok = TRUE)
for(dot.name in dot.names) {
switch(dot.name,
"anti.degen" = {
anti.degen <- dots[[dot.name]]
methods <- c("none", "fixedvars", "columncheck", "stalling",
"numfailure", "lostfeas", "infeasible", "dynamic",
"duringbb", "rhsperturb", "boundflip")
anti.degen <- match.arg(anti.degen, methods, several.ok = TRUE)
if(any(anti.degen == "none"))
anti.degen <- 0
else {
idx <- 2^(0:9)
names(idx) <- methods[-1]
anti.degen <- sum(idx[anti.degen])
}
.Call(RlpSolve_set_anti_degen, lprec, as.integer(anti.degen))
},
"basis.crash" = {
basis.crash <- dots[[dot.name]]
methods <- c("none", "mostfeasible", "leastdegenerate")
basis.crash <- match.arg(basis.crash, methods, several.ok = FALSE)
idx <- c(0, 2, 3)
names(idx) <- methods
basis.crash <- idx[basis.crash]
.Call(RlpSolve_set_basiscrash, lprec, as.integer(basis.crash))
},
"bb.depthlimit" = {
bb.depthlimit <- dots[[dot.name]]
.Call(RlpSolve_set_bb_depthlimit, lprec, as.integer(bb.depthlimit))
},
"bb.floorfirst" = {
bb.floorfirst <- dots[[dot.name]]
methods <- c("ceiling", "floor", "automatic")
bb.floorfirst <- match.arg(bb.floorfirst, methods, several.ok = FALSE)
idx <- c(0, 1, 2)
names(idx) <- methods
bb.floorfirst <- idx[bb.floorfirst]
.Call(RlpSolve_set_bb_floorfirst, lprec, as.integer(bb.floorfirst))
},
"bb.rule" = {
bb.rule <- dots[[dot.name]]
rules <- c("first", "gap", "range", "fraction", "pseudocost",
"pseudononint", "pseudoratio")
rule <- match.arg(bb.rule[1], rules, several.ok = FALSE)
idx <- 0:6
names(idx) <- rules
rule <- idx[rule]
bb.rule <- bb.rule[-1]
if(length(bb.rule)) {
all.values <- c("weightreverse", "branchreverse", "greedy",
"pseudocost", "depthfirst", "randomize", "gub",
"dynamic", "restart", "breadthfirst", "autoorder",
"rcostfixing", "stronginit")
values <- match.arg(bb.rule, all.values, several.ok = TRUE)
idx <- 2^(3:15)
names(idx) <- all.values
values <- idx[values]
}
else
values <- double(0)
bb.rule <- sum(c(rule, values))
.Call(RlpSolve_set_bb_rule, lprec, as.integer(bb.rule))
},
"break.at.first" = {
break.at.first <- dots[[dot.name]]
.Call(RlpSolve_set_break_at_first, lprec, as.logical(break.at.first))
},
"break.at.value" = {
break.at.value <- dots[[dot.name]]
.Call(RlpSolve_set_break_at_value, lprec, as.double(break.at.value))
},
"epslevel" = {
epslevel <- dots[[dot.name]]
methods <- c("tight", "medium", "loose", "baggy")
epslevel <- match.arg(epslevel, methods, several.ok = FALSE)
idx <- 0:3
names(idx) <- methods
epslevel <- idx[epslevel]
.Call(RlpSolve_set_epslevel, lprec, as.integer(epslevel))
},
"epsb" = {
epsb <- dots[[dot.name]]
.Call(RlpSolve_set_epsb, lprec, as.double(epsb))
},
"epsd" = {
epsd <- dots[[dot.name]]
.Call(RlpSolve_set_epsd, lprec, as.double(epsd))
},
"epsel" = {
epsel <- dots[[dot.name]]
.Call(RlpSolve_set_epsel, lprec, as.double(epsel))
},
"epsint" = {
epsint <- dots[[dot.name]]
.Call(RlpSolve_set_epsint, lprec, as.double(epsint))
},
"epsperturb" = {
epsperturb <- dots[[dot.name]]
.Call(RlpSolve_set_epsperturb, lprec, as.double(epsperturb))
},
"epspivot" = {
epspivot <- dots[[dot.name]]
.Call(RlpSolve_set_epspivot, lprec, as.double(epspivot))
},
"improve" = {
improve <- dots[[dot.name]]
methods <- c("none", "solution", "dualfeas", "thetagap", "bbsimplex")
improve <- match.arg(improve, methods, several.ok = TRUE)
if(any(improve == "none"))
improve <- 0
else {
idx <- 2^(0:3)
names(idx) <- methods[-1]
improve <- sum(idx[improve])
}
.Call(RlpSolve_set_improve, lprec, as.integer(improve))
},
"infinite" = {
infinite <- dots[[dot.name]]
.Call(RlpSolve_set_infinite, lprec, as.double(infinite))
},
"maxpivot" = {
maxpivot <- dots[[dot.name]]
.Call(RlpSolve_set_maxpivot, lprec, as.integer(maxpivot))
},
"mip.gap" = {
mip.gap <- dots[[dot.name]]
if(length(mip.gap) != 2)
mip.gap <- rep(mip.gap[1], 2)
.Call(RlpSolve_set_mip_gap, lprec, as.logical(TRUE),
as.double(mip.gap[1]))
.Call(RlpSolve_set_mip_gap, lprec, as.logical(FALSE),
as.double(mip.gap[2]))
},
"negrange" = {
negrange <- dots[[dot.name]]
.Call(RlpSolve_set_negrange, lprec, as.double(negrange))
},
"obj.in.basis" = {
obj.in.basis <- dots[[dot.name]]
.Call(RlpSolve_set_obj_in_basis, lprec, as.logical(obj.in.basis))
},
"pivoting" = {
pivoting <- dots[[dot.name]]
rules <- c("firstindex", "dantzig", "devex", "steepestedge")
rule <- match.arg(pivoting[1], rules, several.ok = FALSE)
idx <- 0:3
names(idx) <- rules
rule <- idx[rule]
pivoting <- pivoting[-1]
if(length(pivoting)) {
all.modes <- c("primalfallback", "multiple", "partial", "adaptive",
"randomize", "autopartial", "loopleft",
"loopalternate", "harristwopass", "truenorminit")
modes <- match.arg(pivoting, all.modes, several.ok = TRUE)
idx <- c(4, 8, 16, 32, 128, 512, 1024, 2048, 4096, 16384)
names(idx) <- all.modes
modes <- idx[modes]
}
else
modes <- double(0)
pivoting <- sum(c(rule, modes))
.Call(RlpSolve_set_pivoting, lprec, as.integer(pivoting))
},
"presolve" = {
presolve <- dots[[dot.name]]
methods <- c("none", "rows", "cols", "lindep", "sos", "reducemip",
"knapsack", "elimeq2", "impliedfree", "reducedgcd",
"probefix", "probereduce", "rowdominate", "coldominate",
"mergerows", "impliedslk", "colfixdual", "bounds", "duals",
"sensduals")
presolve <- match.arg(presolve, methods, several.ok = TRUE)
if(any(presolve == "none"))
presolve <- 0
else {
idx <- c(2^(0:2), 2^(5:20))
names(idx) <- methods[-1]
presolve <- sum(idx[presolve])
}
loops <- .Call(RlpSolve_get_presolveloops, lprec)
.Call(RlpSolve_set_presolve, lprec, as.integer(presolve),
as.integer(loops))
},
"scalelimit" = {
scalelimit <- dots[[dot.name]]
.Call(RlpSolve_set_scalelimit, lprec, as.double(scalelimit))
},
"scaling" = {
scaling <- dots[[dot.name]]
types <- c("none", "extreme", "range", "mean", "geometric",
"curtisreid")
type <- match.arg(scaling[1], types, several.ok = FALSE)
if(any(type == "none"))
scaling <- 0
else {
idx <- c(0, 1, 2, 3, 4, 7)
names(idx) <- types
type <- idx[type]
scaling <- scaling[-1]
if(length(scaling)) {
all.modes <- c("quadratic", "logarithmic", "power2", "equilibrate",
"integers", "dynupdate", "rowsonly", "colsonly")
modes <- match.arg(scaling, all.modes, several.ok = TRUE)
idx <- 2^(3:10)
names(idx) <- all.modes
modes <- idx[modes]
}
else
modes <- double(0)
scaling <- sum(c(type, modes))
}
.Call(RlpSolve_set_scaling, lprec, as.integer(scaling))
},
"sense" = {
sense <- dots[[dot.name]]
sense <- match.arg(sense, c("minimize", "maximize"))
sense <- sense == "maximize"
.Call(RlpSolve_set_sense, lprec, as.logical(sense))
},
"simplextype" = {
simplextype <- dots[[dot.name]]
simplextype <- match.arg(simplextype, c("primal", "dual"),
several.ok = TRUE)
if(length(simplextype) != 2)
simplextype <- rep(simplextype[1], 2)
if(simplextype[1] == "primal" && simplextype[2] == "primal")
simplextype <- 5
else if(simplextype[1] == "primal" && simplextype[2] == "dual")
simplextype <- 9
else if(simplextype[1] == "dual" && simplextype[2] == "primal")
simplextype <- 6
else if(simplextype[1] == "dual" && simplextype[2] == "dual")
simplextype <- 10
.Call(RlpSolve_set_simplextype, lprec, as.integer(simplextype))
},
"timeout" = {
timeout <- dots[[dot.name]]
.Call(RlpSolve_set_timeout, lprec, as.integer(timeout))
},
"verbose" = {
verbose <- dots[[dot.name]]
ch <- c("neutral", "critical", "severe", "important", "normal",
"detailed", "full")
verbose <- match.arg(verbose, choices = ch)
verbose <- match(verbose, table = ch) - 1
.Call(RlpSolve_set_verbose, lprec, as.integer(verbose))
}
)
}
anti.degen <- .Call(RlpSolve_is_anti_degen, lprec,
as.integer(c(0,1,2,4,8,16,32,64,128,256,512)))
anti.degen <- c("none", "fixedvars", "columncheck", "stalling", "numfailure",
"lostfeas", "infeasible", "dynamic", "duringbb", "rhsperturb",
"boundflip")[anti.degen]
basis.crash <- .Call(RlpSolve_get_basiscrash, lprec)
basis.crash <- c("none", "NOT USED", "mostfeasible",
"leastdegenerate")[1 + basis.crash]
bb.depthlimit <- .Call(RlpSolve_get_bb_depthlimit, lprec)
bb.floorfirst <- .Call(RlpSolve_get_bb_floorfirst, lprec)
bb.floorfirst <- c("ceiling", "floor", "automatic")[1 + bb.floorfirst]
bb.rule.index <- .Call(RlpSolve_get_bb_rule, lprec)
bb.rule <- bb.rule.index %% 8
bb.rule <- c("first", "gap", "range", "fraction", "pseudocost",
"pseudononint", "pseudoratio", "user")[1 + bb.rule]
bb.value.index <- integer(0)
for(i in 15:3) {
temp <- 2^i
if(floor(bb.rule.index / temp) == 1) {
bb.value.index <- c(i, bb.value.index)
bb.rule.index <- bb.rule.index - temp
}
}
bb.rule <- c(bb.rule, c("weightreverse", "branchreverse", "greedy",
"pseudocost", "depthfirst", "randomize", "gub", "dynamic",
"restart", "breadthfirst", "autoorder", "rcostfixing",
"stronginit")[bb.value.index - 2])
break.at.first <- .Call(RlpSolve_is_break_at_first, lprec)
break.at.value <- .Call(RlpSolve_get_break_at_value, lprec)
epsilon <- c(epsb = .Call(RlpSolve_get_epsb, lprec),
epsd = .Call(RlpSolve_get_epsd, lprec),
epsel = .Call(RlpSolve_get_epsel, lprec),
epsint = .Call(RlpSolve_get_epsint, lprec),
epsperturb = .Call(RlpSolve_get_epsperturb, lprec),
epspivot = .Call(RlpSolve_get_epspivot, lprec))
improve <- .Call(RlpSolve_get_improve, lprec)
improve.index <- integer(0)
for(i in 3:0) {
temp <- 2^i
if(floor(improve / temp) == 1) {
improve.index <- c(i, improve.index)
improve <-improve - temp
}
}
if(length(improve.index))
improve <- c("solution", "dualfeas", "thetagap",
"bbsimplex")[1 + improve.index]
else
improve <- "none"
infinite <- .Call(RlpSolve_get_infinite, lprec)
maxpivot <- .Call(RlpSolve_get_maxpivot, lprec)
mip.gap <- c(absolute = .Call(RlpSolve_get_mip_gap, lprec, TRUE),
relative = .Call(RlpSolve_get_mip_gap, lprec, FALSE))
negrange <- .Call(RlpSolve_get_negrange, lprec)
obj.in.basis <- .Call(RlpSolve_is_obj_in_basis, lprec)
pivot.rule <- .Call(RlpSolve_is_piv_rule, lprec, as.integer(0:3))
pivot.rule <- c("firstindex", "dantzig", "devex", "steepestedge")[pivot.rule]
pivot.mode <- .Call(RlpSolve_is_piv_mode, lprec,
as.integer(c(2^(2:5), 128, 2^(9:12), 16384)))
pivot.mode <- c("primalfallback", "multiple", "partial", "adaptive",
"randomize", "autopartial", "loopleft", "loopalternate",
"harristwopass", "truenorminit")[pivot.mode]
pivoting <- c(pivot.rule, pivot.mode)
presolve <- .Call(RlpSolve_is_presolve, lprec,
as.integer(c(0, 2^(0:2), 2^(5:20))))
presolve <- c("none", "rows", "cols", "lindep", "sos", "reducemip",
"knapsack", "elimeq2", "impliedfree", "reducedgcd", "probefix",
"probereduce", "rowdominate", "coldominate", "mergerows",
"impliedslk", "colfixdual", "bounds", "duals",
"sensduals")[presolve]
scalelimit <- .Call(RlpSolve_get_scalelimit, lprec)
scale.type <- .Call(RlpSolve_is_scaletype, lprec, as.integer(c(0, 1,2,3,4,7)))
scale.type <- c("none", "extreme", "range", "mean", "geometric",
"curtisreid")[scale.type]
scale.mode <- .Call(RlpSolve_is_scalemode, lprec,
as.integer(c(8, 16, 2^(5:10))))
scale.mode <- c("quadratic", "logarithmic", "power2", "equilibrate",
"integers", "dynupdate", "rowsonly", "colsonly")[scale.mode]
scaling <- c(scale.type, scale.mode)
sense <- ifelse(.Call(RlpSolve_is_maxim, lprec), "maximize", "minimize")
simplextype <- switch(as.character(.Call(RlpSolve_get_simplextype, lprec)),
"5" = c("primal", "primal"),
"6" = c("dual", "primal"),
"9" = c("primal", "dual"),
"10" = c("dual", "dual")
)
timeout <- .Call(RlpSolve_get_timeout, lprec)
ch <- c("neutral", "critical", "severe", "important", "normal", "detailed",
"full")
verbose <- ch[1+.Call(RlpSolve_get_verbose, lprec)]
list(anti.degen = anti.degen, basis.crash = basis.crash,
bb.depthlimit = bb.depthlimit, bb.floorfirst = bb.floorfirst,
bb.rule = bb.rule, break.at.first = break.at.first,
break.at.value = break.at.value, epsilon = epsilon, improve = improve,
infinite = infinite, maxpivot = maxpivot, mip.gap = mip.gap,
negrange = negrange, obj.in.basis = obj.in.basis, pivoting = pivoting,
presolve = presolve, scalelimit = scalelimit, scaling = scaling,
sense = sense, simplextype = simplextype, timeout = timeout,
verbose = verbose)
} |
library(ggplot2)
data=data.frame(group=c("A ","B ","C ","D ") , value=c(33,62,56,67) , number_of_obs=c(100,500,459,342))
data$right=cumsum(data$number_of_obs) + 30*c(0:(nrow(data)-1))
data$left=data$right - data$number_of_obs
ggplot(data, aes(ymin = 0)) +
geom_rect(aes(xmin = left, xmax = right, ymax = value, colour = group, fill = group)) +
xlab("number of obs") + ylab("value") |
insert_paragraphs <- function(
denv,
vec
){
vec <- unlist(vec, recursive = TRUE)
valid_elements <- gsub("[[:space:]]|\n|\n\r|\r", "", vec) != ""
vec <- vec[valid_elements]
vec <- gsub("\n$|\n\r$", "", vec)
vec <- vec[vec != ""]
iteration <- 0
for(i in vec){
officer::cursor_end(denv$docx)
cursor_pos <- denv$docx$doc_obj$get_at_cursor()
iteration <- iteration + 1
string <- i
new_string <- paste0(
'<w:p xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/',
'2006/main\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/',
'2006/wordprocessingDrawing\" xmlns:r=\"http://schemas.openxmlformats.',
'org/officeDocument/2006/relationships\" xmlns:w14=\"http://schemas.',
'microsoft.com/office/word/2010/wordml\">',
htmltools::htmlEscape(string),
'</w:p>'
)
tryCatch(
{
new_string <- iconv(new_string, to = "latin1")
new_string <- xml2::as_xml_document(new_string)
xml2::xml_add_sibling(
cursor_pos,
new_string,
.where = "after",
.copy = TRUE
)
},
error = function(e){}
)
}
} |
long_to_wide_converter <- function(data,
x,
y,
subject.id = NULL,
paired = TRUE,
spread = TRUE,
...) {
data %<>%
select({{ x }}, {{ y }}, rowid = {{ subject.id }}) %>%
mutate({{ x }} := droplevels(as.factor({{ x }}))) %>%
arrange({{ x }})
if (!"rowid" %in% names(data)) {
if (paired) data %<>% group_by({{ x }})
data %<>% mutate(rowid = row_number())
}
data %<>%
ungroup(.) %>%
nest_by(rowid, .key = "df") %>%
filter(sum(is.na(df)) == 0) %>%
tidyr::unnest(cols = c(df))
if (spread && paired) data %<>% tidyr::pivot_wider(names_from = {{ x }}, values_from = {{ y }})
as_tibble(relocate(data, rowid) %>% arrange(rowid))
} |
`chron.stabilized` <-
function(x, winLength, biweight = TRUE, running.rbar = FALSE)
{
if(!is.int(winLength)) stop("'winLength' must be an integer.")
if(winLength > nrow(x)) stop("'winLength' must be (considerably) shorter than the chronology length.")
if(winLength <= 30) warning("'winLength' < 30 is not recommended.\n Consider a longer window.")
if(winLength/nrow(x) > 0.5) warning("'winLength' > 50% of chronology length is not recommended.\n Consider a shorter window.")
rbarWinLength <-function (x, WL=winLength) {
corMat <- cor(x, use="pairwise.complete.obs")
diag(corMat) <- NA
presenceMatrix <- ifelse(is.na(x),0,1)
overlapMatrix <- t(presenceMatrix)%*%presenceMatrix
corMat[overlapMatrix < (WL/3)] <- NA
res <- mean(corMat, na.rm=TRUE)
res
}
mean.x <-mean(rowMeans(x,na.rm=TRUE,dims=1))
x0 <- x-mean.x
nSamps <- rowSums(!is.na(x0))
xCrn <- rowMeans(x0,na.rm=T)
if(biweight) {
xCrn <- apply(x0,1,tbrm)
}
xCorrelMat <- cor(x0,use="pairwise.complete.obs")
diag(xCorrelMat) <- NA
rbar <- mean(xCorrelMat, na.rm =TRUE)
movingRbarVec <- rep(NA,nrow(x0))
if(winLength%%2 == 1){
for(i in 1:(nrow(x0)-winLength+1)){
movingRbarVec[i+(winLength-1)/2] <- rbarWinLength(x0[i:(i+winLength-1),])
}
}
else{
for(i in 1:(nrow(x0)-winLength+1)){
movingRbarVec[i+(winLength)/2] <- rbarWinLength(x0[i:(i+winLength-1),])
}
}
idxNA <- which(!is.na(movingRbarVec))
padLow <- min(idxNA)
padHigh <- max(idxNA)
movingRbarVec[1:padLow] <- movingRbarVec[padLow]
movingRbarVec[padHigh:length(movingRbarVec)] <- movingRbarVec[padHigh]
movingRbarVec[nSamps==0] <- NA
nSampsEff <- nSamps/(1+(nSamps-1)*movingRbarVec)
nSampsEff <- pmin(nSampsEff,nSamps,na.rm=TRUE)
xCrnAdjusted <- xCrn*(nSampsEff*rbar)^.5
xCrnAdjusted <- scale(xCrnAdjusted,
center=-mean.x, scale=FALSE)[,1]
if(running.rbar){
res <- data.frame(adj.crn = xCrnAdjusted,
running.rbar = movingRbarVec,
samp.depth = nSamps)
}
else{
res <- data.frame(adj.crn = xCrnAdjusted,
samp.depth = nSamps)
}
rownames(res)<-rownames(x0)
return(res)
} |
reduc <- function(R,B=c(0,1),hm=FALSE,cm=FALSE)
{
storage.mode(R) <- "double"
storage.mode(B) <- "integer"
storage.mode(hm) <- "integer"
storage.mode(cm) <- "integer"
.Call("ReductionStepForR", R, B, hm, cm)
} |
add_css_header <- function(tableHTML,
css,
headers) {
if (!inherits(tableHTML, 'tableHTML')) stop('tableHTML needs to be a tableHTML object')
if (length(css[[1]]) != length(css[[2]])) stop('css needs to be a list of two elements of the
same length')
attributes <- attributes(tableHTML)
css_comp <- paste0(css[[1]], ':', css[[2]], ';')
css_comp <- paste(css_comp, collapse = '')
style <- paste0('style="', css_comp, '"')
if (grepl('id="tableHTML_header_0"', tableHTML)) {
for (i in (headers - 1)) {
tableHTML <- gsub(paste0('id="tableHTML_header_', i, '" style='),
paste0('id="tableHTML_header_', i, '"'), tableHTML)
tableHTML <- gsub(paste0('id="tableHTML_header_', i, '"'),
paste0('id="tableHTML_header_', i, '" ', style), tableHTML)
tableHTML <- gsub(';""', ';', tableHTML)
}
} else {
for (i in headers) {
tableHTML <- gsub(paste0('id="tableHTML_header_', i, '" style='),
paste0('id="tableHTML_header_', i, '"'), tableHTML)
tableHTML <- gsub(paste0('id="tableHTML_header_', i, '"'),
paste0('id="tableHTML_header_', i, '" ', style), tableHTML)
tableHTML <- gsub(';""', ';', tableHTML)
}
}
attributes(tableHTML) <- attributes
tableHTML
} |
data("airquality")
dsc = "Daily air quality measurements in New York, May to September 1973.
This data is taken from R."
cit = "Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P. A. (1983) Graphical
Methods for Data Analysis. Belmont, CA: Wadsworth."
desc_airquality = makeOMLDataSetDescription(name = "airquality",
description = dsc,
creator = "New York State Department of Conservation (ozone data) and the National
Weather Service (meteorological data)",
collection.date = "May 1, 1973 to September 30, 1973",
language = "English",
licence = "GPL-2",
url = "https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/00Index.html",
default.target.attribute = "Ozone",
citation = cit,
tags = "R")
airquality_oml = makeOMLDataSet(desc = desc_airquality,
data = airquality,
colnames.old = colnames(airquality),
colnames.new = colnames(airquality),
target.features = "Ozone") |
make_poisson_reg <- function() {
parsnip::set_new_model("poisson_reg")
parsnip::set_model_mode("poisson_reg", "regression")
parsnip::set_model_engine("poisson_reg", "regression", "glm")
parsnip::set_dependency("poisson_reg", "glm", "stats")
parsnip::set_dependency("poisson_reg", "glm", "poissonreg")
parsnip::set_fit(
model = "poisson_reg",
eng = "glm",
mode = "regression",
value = list(
interface = "formula",
protect = c("formula", "data", "weights"),
func = c(pkg = "stats", fun = "glm"),
defaults = list(family = expr(stats::poisson))
)
)
parsnip::set_encoding(
model = "poisson_reg",
eng = "glm",
mode = "regression",
options = list(
predictor_indicators = "traditional",
compute_intercept = TRUE,
remove_intercept = TRUE,
allow_sparse_x = FALSE
)
)
parsnip::set_pred(
model = "poisson_reg",
eng = "glm",
mode = "regression",
type = "numeric",
value = list(
pre = NULL,
post = NULL,
func = c(fun = "predict"),
args =
list(
object = expr(object$fit),
newdata = expr(new_data),
type = "response"
)
)
)
parsnip::set_pred(
model = "poisson_reg",
eng = "glm",
mode = "regression",
type = "raw",
value = list(
pre = NULL,
post = NULL,
func = c(fun = "predict"),
args = list(object = expr(object$fit), newdata = expr(new_data))
)
)
parsnip::set_model_engine("poisson_reg", "regression", "hurdle")
parsnip::set_dependency("poisson_reg", "hurdle", "pscl")
parsnip::set_dependency("poisson_reg", "hurdle", "poissonreg")
parsnip::set_fit(
model = "poisson_reg",
eng = "hurdle",
mode = "regression",
value = list(
interface = "formula",
protect = c("formula", "data", "weights"),
func = c(pkg = "pscl", fun = "hurdle"),
defaults = list()
)
)
parsnip::set_encoding(
model = "poisson_reg",
eng = "hurdle",
mode = "regression",
options = list(
predictor_indicators = "none",
compute_intercept = FALSE,
remove_intercept = FALSE,
allow_sparse_x = FALSE
)
)
parsnip::set_pred(
model = "poisson_reg",
eng = "hurdle",
mode = "regression",
type = "numeric",
value = list(
pre = NULL,
post = NULL,
func = c(fun = "predict"),
args =
list(
object = expr(object$fit),
newdata = expr(new_data)
)
)
)
parsnip::set_pred(
model = "poisson_reg",
eng = "hurdle",
mode = "regression",
type = "raw",
value = list(
pre = NULL,
post = NULL,
func = c(fun = "predict"),
args = list(object = expr(object$fit), newdata = expr(new_data))
)
)
parsnip::set_model_engine("poisson_reg", "regression", "zeroinfl")
parsnip::set_dependency("poisson_reg", "zeroinfl", "pscl")
parsnip::set_dependency("poisson_reg", "zeroinfl", "poissonreg")
parsnip::set_fit(
model = "poisson_reg",
eng = "zeroinfl",
mode = "regression",
value = list(
interface = "formula",
protect = c("formula", "data", "weights"),
func = c(pkg = "pscl", fun = "zeroinfl"),
defaults = list()
)
)
parsnip::set_encoding(
model = "poisson_reg",
eng = "zeroinfl",
mode = "regression",
options = list(
predictor_indicators = "none",
compute_intercept = FALSE,
remove_intercept = FALSE,
allow_sparse_x = FALSE
)
)
parsnip::set_pred(
model = "poisson_reg",
eng = "zeroinfl",
mode = "regression",
type = "numeric",
value = list(
pre = NULL,
post = NULL,
func = c(fun = "predict"),
args =
list(
object = expr(object$fit),
newdata = expr(new_data)
)
)
)
parsnip::set_pred(
model = "poisson_reg",
eng = "zeroinfl",
mode = "regression",
type = "raw",
value = list(
pre = NULL,
post = NULL,
func = c(fun = "predict"),
args = list(object = expr(object$fit), newdata = expr(new_data))
)
)
parsnip::set_model_engine("poisson_reg", "regression", "glmnet")
parsnip::set_dependency("poisson_reg", "glmnet", "glmnet")
parsnip::set_dependency("poisson_reg", "glmnet", "poissonreg")
parsnip::set_model_arg(
model = "poisson_reg",
eng = "glmnet",
parsnip = "penalty",
original = "lambda",
func = list(pkg = "dials", fun = "penalty"),
has_submodel = TRUE
)
parsnip::set_model_arg(
model = "poisson_reg",
eng = "glmnet",
parsnip = "mixture",
original = "alpha",
func = list(pkg = "dials", fun = "mixture"),
has_submodel = FALSE
)
parsnip::set_fit(
model = "poisson_reg",
eng = "glmnet",
mode = "regression",
value = list(
interface = "matrix",
protect = c("x", "y", "weights"),
func = c(pkg = "glmnet", fun = "glmnet"),
defaults = list(family = "poisson")
)
)
parsnip::set_encoding(
model = "poisson_reg",
eng = "glmnet",
mode = "regression",
options = list(
predictor_indicators = "traditional",
compute_intercept = TRUE,
remove_intercept = TRUE,
allow_sparse_x = TRUE
)
)
parsnip::set_pred(
model = "poisson_reg",
eng = "glmnet",
mode = "regression",
type = "numeric",
value = list(
pre = NULL,
post = organize_glmnet_pred,
func = c(fun = "predict"),
args =
list(
object = expr(object$fit),
newx = expr(as.matrix(new_data[, rownames(object$fit$beta)])),
type = "response",
s = expr(object$spec$args$penalty)
)
)
)
parsnip::set_pred(
model = "poisson_reg",
eng = "glmnet",
mode = "regression",
type = "raw",
value = list(
pre = NULL,
post = NULL,
func = c(fun = "predict"),
args =
list(object = expr(object$fit),
newx = expr(as.matrix(new_data[, rownames(object$fit$beta)])))
)
)
parsnip::set_model_engine("poisson_reg", "regression", "stan")
parsnip::set_dependency("poisson_reg", "stan", "rstanarm")
parsnip::set_dependency("poisson_reg", "stan", "poissonreg")
parsnip::set_fit(
model = "poisson_reg",
eng = "stan",
mode = "regression",
value = list(
interface = "formula",
protect = c("formula", "data", "weights"),
func = c(pkg = "rstanarm", fun = "stan_glm"),
defaults = list(family = expr(stats::poisson))
)
)
parsnip::set_encoding(
model = "poisson_reg",
eng = "stan",
mode = "regression",
options = list(
predictor_indicators = "none",
compute_intercept = FALSE,
remove_intercept = FALSE,
allow_sparse_x = FALSE
)
)
parsnip::set_pred(
model = "poisson_reg",
eng = "stan",
mode = "regression",
type = "numeric",
value = list(
pre = NULL,
post = NULL,
func = c(fun = "predict"),
args = list(object = expr(object$fit), newdata = expr(new_data))
)
)
parsnip::set_pred(
model = "poisson_reg",
eng = "stan",
mode = "regression",
type = "conf_int",
value = list(
pre = NULL,
post = function(results, object) {
res <-
tibble(
.pred_lower =
parsnip::convert_stan_interval(
results,
level = object$spec$method$pred$conf_int$extras$level
),
.pred_upper =
parsnip::convert_stan_interval(
results,
level = object$spec$method$pred$conf_int$extras$level,
lower = FALSE
),
)
if (object$spec$method$pred$conf_int$extras$std_error)
res$.std_error <- apply(results, 2, sd, na.rm = TRUE)
res
},
func = c(pkg = "rstanarm", fun = "posterior_linpred"),
args =
list(
object = expr(object$fit),
newdata = expr(new_data),
transform = TRUE,
seed = expr(sample.int(10^5, 1))
)
)
)
parsnip::set_pred(
model = "poisson_reg",
eng = "stan",
mode = "regression",
type = "pred_int",
value = list(
pre = NULL,
post = function(results, object) {
res <-
tibble(
.pred_lower =
parsnip::convert_stan_interval(
results,
level = object$spec$method$pred$pred_int$extras$level
),
.pred_upper =
parsnip::convert_stan_interval(
results,
level = object$spec$method$pred$pred_int$extras$level,
lower = FALSE
),
)
if (object$spec$method$pred$pred_int$extras$std_error)
res$.std_error <- apply(results, 2, sd, na.rm = TRUE)
res
},
func = c(pkg = "rstanarm", fun = "posterior_predict"),
args =
list(
object = expr(object$fit),
newdata = expr(new_data),
seed = expr(sample.int(10^5, 1))
)
)
)
parsnip::set_pred(
model = "poisson_reg",
eng = "stan",
mode = "regression",
type = "raw",
value = list(
pre = NULL,
post = NULL,
func = c(fun = "predict"),
args = list(object = expr(object$fit), newdata = expr(new_data))
)
)
} |
xvals <- seq(0, 20, length = 1000)
plot(xvals, dexp(xvals, 1/5), xlab = "Survival time in years",
ylab = "density",
frame = FALSE,
type = "l")
polygon(c(xvals[xvals >= 6], rev(xvals[xvals >= 6])),
c(dexp(xvals[xvals >= 6], 1/5), rep(0, sum(xvals >= 6))),
col = grey(.5)
) |
expected <- eval(parse(text="structure(c(-0.56047564655221-1.68669331074241i, 0.7424437487+0.837787044494525i, 1.39139505579429+0.15337311783652i, 0.92871076411383-1.13813693701195i, -0.46926798541295+1.25381492106993i, 0.7424437487+0.426464221476814i, 0.460916205989202-0.295071482992271i, -0.452623703774585+0.895125661045022i, -0.094501186832143+0.878133487533042i, -0.331818442379127+0.821581081637487i, 1.39139505579429+0.68864025410009i, -0.452623703774585+0.553917653537589i, 0.400771450594052-0.061911710576722i, -0.927967220342259-0.305962663739917i, -0.790922791530657-0.380471001012383i, 0.928710764113827-0.694706978920513i, -0.094501186832143-0.207917278019599i, -0.92796722034226-1.26539635156826i, 0.70135590156369+2.16895596533851i, -0.60084131850954+1.20796199830499i, -0.46926798541295-1.12310858320335i, -0.331818442379127-0.402884835299076i, -0.790922791530657-0.466655353623219i, -0.600841318509537+0.779965118336318i, -0.625039267849257-0.083369066471829i), .Dim = c(5L, 5L))"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(-0.560475646552213+0i, 0.7424437487+0i, 1.39139505579429+0i, 0.928710764113827+0i, -0.469267985412949+0i, 0.7424437487+0i, 0.460916205989202+0i, -0.452623703774585+0i, -0.0945011868321433+0i, -0.331818442379127+0i, 1.39139505579429+0i, -0.452623703774585+0i, 0.400771450594052+0i, -0.927967220342259+0i, -0.790922791530657+0i, 0.928710764113827+0i, -0.0945011868321433+0i, -0.927967220342259+0i, 0.701355901563686+0i, -0.600841318509537+0i, -0.469267985412949+0i, -0.331818442379127+0i, -0.790922791530657+0i, -0.600841318509537+0i, -0.625039267849257+0i), .Dim = c(5L, 5L)), c(0-1.68669331074241i, 0+0.837787044494525i, 0+0.153373117836515i, 0-1.13813693701195i, 0+1.25381492106993i, 0+0.426464221476814i, 0-0.295071482992271i, 0+0.895125661045022i, 0+0.878133487533042i, 0+0.821581081637487i, 0+0.688640254100091i, 0+0.553917653537589i, 0-0.0619117105767217i, 0-0.305962663739917i, 0-0.380471001012383i, 0-0.694706978920513i, 0-0.207917278019599i, 0-1.26539635156826i, 0+2.16895596533851i, 0+1.20796199830499i, 0-1.12310858320335i, 0-0.402884835299076i, 0-0.466655353623219i, 0+0.779965118336318i, 0-0.0833690664718293i))"));
do.call(`+`, argv);
}, o=expected); |
NULL
NULL
memeApp <- function(){
shiny::runApp(system.file("shiny", "memeApp", package = "memery"))
}
.no_magick <- "The `magick` package must be installed to use `meme_gif`."
.check_for_magick <- function(){
requireNamespace("magick", quietly = TRUE)
} |
context("PipeOpEnsemble")
test_that("PipeOpEnsemble - basic properties", {
op = PipeOpEnsemble$new(4, id = "ensemble", param_vals = list())
expect_pipeop(op)
expect_pipeop_class(PipeOpEnsemble, list(3, id = "ensemble", param_vals = list()))
expect_pipeop_class(PipeOpEnsemble, list(1, id = "ensemble", param_vals = list()))
expect_pipeop_class(PipeOpEnsemble, list(0, id = "ensemble", param_vals = list()))
truth = rnorm(70)
prds = replicate(4, PredictionRegr$new(row_ids = seq_len(70), truth = truth, response = truth + rnorm(70, sd = 0.1)))
expect_list(train_pipeop(op, rep(list(NULL), 4)), len = 1)
expect_error(predict_pipeop(op, prds), "Abstract")
op = PipeOpEnsemble$new(0, id = "ensemble", param_vals = list())
expect_pipeop(op)
op = PipeOpEnsemble$new(0, collect_multiplicity = TRUE, id = "ensemble", param_vals = list())
expect_pipeop(op)
expect_list(train_pipeop(op, list(as.Multiplicity(rep(list(NULL), 4)))), len = 1)
expect_error(predict_pipeop(op, list(as.Multiplicity(prds))), "Abstract")
expect_error(PipeOpEnsemble$new(1, collect_multiplicity = TRUE, id = "ensemble", param_vals = list()), regexp = "collect_multiplicity only works with innum == 0")
})
test_that("PipeOpWeightedRegrAvg - train and predict", {
truth = rnorm(70)
prds = replicate(4, PredictionRegr$new(row_ids = seq_len(70), truth = truth, response = truth + rnorm(70, sd = 0.1)), simplify = FALSE)
po = PipeOpRegrAvg$new(4)
expect_pipeop(po)
expect_list(train_pipeop(po, rep(list(NULL), 4)), len = 1)
out = predict_pipeop(po, prds)
po = PipeOpRegrAvg$new(4)
po$param_set$values$weights = c(0, 0, 1, 0)
expect_list(train_pipeop(po, rep(list(NULL), 4)), len = 1)
out = predict_pipeop(po, prds)
expect_equal(out, list(output = prds[[3]]))
po = PipeOpRegrAvg$new()
expect_pipeop(po)
expect_list(train_pipeop(po, rep(list(NULL), 4)), len = 1)
out = predict_pipeop(po, prds)
po = PipeOpRegrAvg$new()
po$param_set$values$weights = c(0, 0, 1, 0)
expect_list(train_pipeop(po, rep(list(NULL), 4)), len = 1)
out = predict_pipeop(po, prds)
expect_equal(out, list(output = prds[[3]]))
})
test_that("PipeOpWeightedClassifAvg - response - train and predict", {
nulls = rep(list(NULL), 4)
prds = replicate(4,
make_prediction_obj_classif(n = 100, noise = TRUE,
predict_types = "response", nclasses = 3),
simplify = FALSE
)
lapply(prds, function(x) x$data$tab$truth = prds[[1]]$data$tab$truth)
po = PipeOpClassifAvg$new(4)
expect_pipeop(po)
expect_list(train_pipeop(po, nulls), len = 1)
out = predict_pipeop(po, prds)
expect_class(out[[1]], "PredictionClassif")
po = PipeOpClassifAvg$new(4)
po$param_set$values$weights = c(0, 0, 0, 1)
expect_list(train_pipeop(po, nulls), len = 1)
out = predict_pipeop(po, prds)
expect_class(out[[1]], "PredictionClassif")
expect_equal(out[[1]]$data$tab, prds[[4]]$data$tab)
po = PipeOpClassifAvg$new()
expect_pipeop(po)
expect_list(train_pipeop(po, nulls), len = 1)
out = predict_pipeop(po, prds)
expect_class(out[[1]], "PredictionClassif")
po = PipeOpClassifAvg$new()
po$param_set$values$weights = c(0, 0, 0, 1)
expect_list(train_pipeop(po, nulls), len = 1)
out = predict_pipeop(po, prds)
expect_class(out[[1]], "PredictionClassif")
expect_equal(out[[1]]$data$tab, prds[[4]]$data$tab)
})
test_that("PipeOpWeightedClassifAvg - prob - train and predict", {
nulls = rep(list(NULL), 4)
prds = replicate(4,
make_prediction_obj_classif(n = 100, noise = TRUE,
predict_types = c("response", "prob"), nclasses = 3),
simplify = FALSE
)
lapply(prds, function(x) x$data$truth = prds[[1]]$data$truth)
po = PipeOpClassifAvg$new(4)
expect_pipeop(po)
expect_list(train_pipeop(po, nulls), len = 1)
out = predict_pipeop(po, prds)
expect_class(out[[1]], "PredictionClassif")
po = PipeOpClassifAvg$new(4)
po$param_set$values$weights = c(0, 0, 0, 1)
expect_list(train_pipeop(po, nulls), len = 1)
out = predict_pipeop(po, prds)
expect_class(out[[1]], "PredictionClassif")
expect_equivalent(as.data.table(out[[1]]), as.data.table(prds[[4]]))
po = PipeOpClassifAvg$new()
expect_pipeop(po)
expect_list(train_pipeop(po, nulls), len = 1)
out = predict_pipeop(po, prds)
expect_class(out[[1]], "PredictionClassif")
po = PipeOpClassifAvg$new()
po$param_set$values$weights = c(0, 0, 0, 1)
expect_list(train_pipeop(po, nulls), len = 1)
out = predict_pipeop(po, prds)
expect_class(out[[1]], "PredictionClassif")
expect_equivalent(as.data.table(out[[1]]), as.data.table(prds[[4]]))
}) |
hypothmat <-
function(sfit,mmat,n,p){
q <- length(mmat[,1])
bpart <- mmat%*%sfit$coefficients
varpart <- mmat%*%sfit$betacov%*%t(mmat)
tst <- t(bpart)%*%solve(varpart)%*%bpart
pvf <- 1 - pf(tst/q,q,n-p)
hypothmat <- c(tst,pvf)
return(hypothmat)
} |
bayescopulaglm <- function(
formula.list,
family.list,
data,
histdata = NULL,
b0 = NULL,
c0 = NULL,
alpha0 = NULL,
gamma0 = NULL,
Gamma0 = NULL,
S0beta = NULL,
sigma0logphi = NULL,
v0 = NULL,
V0 = NULL,
beta0 = NULL,
phi0 = NULL,
M = 10000,
burnin = 2000,
thin = 1,
adaptive = TRUE
) {
if ( burnin > 0 ) {
smpl <- bayescopulaglm_wrapper(
formula.list, family.list, data, M = burnin, histdata, b0,
c0, alpha0, gamma0, Gamma0, S0beta, sigma0logphi, v0, V0,
beta0, phi0, thin = 1
)
beta0 <- lapply(smpl$betasample, function(x) as.matrix(x)[nrow(x), ] )
beta0 <- lapply(beta0, as.numeric)
phi0 <- smpl$phisample[burnin, ]
Gamma0 <- smpl$Gammasample[, , burnin]
if ( adaptive ) {
cd.sq <- sapply(smpl$betasample, ncol)
cd.sq <- 2.4 ^ 2 / cd.sq
smpl$betasample <- lapply(smpl$betasample, function(x) as.matrix(x)[-(1:ceiling(burnin / 2)), , drop = F] )
S0beta <- mapply(function(a, b) a * cov(b), a = cd.sq, b = smpl$betasample, SIMPLIFY = FALSE)
sigma0logphi <- apply( log( smpl$phisample[-(1:ceiling(burnin/2)), ] ), 2, sd )
sigma0logphi <- ifelse(sigma0logphi == 0, .1, sigma0logphi)
}
}
smpl <- bayescopulaglm_wrapper(
formula.list, family.list, data, M = M, histdata, b0,
c0, alpha0, gamma0, Gamma0, S0beta, sigma0logphi, v0, V0,
beta0, phi0, thin = thin
)
smpl$formula.list <- formula.list
smpl$family.list <- family.list
class(smpl) <- c(class(smpl), 'bayescopulaglm')
return(smpl)
}
bayescopulaglm_wrapper <- function(
formula.list,
family.list,
data,
M = 10000,
histdata = NULL,
b0 = NULL,
c0 = NULL,
alpha0 = NULL,
gamma0 = NULL,
Gamma0 = NULL,
S0beta = NULL,
sigma0logphi = NULL,
v0 = NULL,
V0 = NULL,
beta0 = NULL,
phi0 = NULL,
thin = 1
) {
if ( class(formula.list) != 'list' ) {
stop('formula.list must be a list of formulas')
}
if ( any( sapply(formula.list, class) != 'formula') ) {
stop('At least one element of formula.list is not a formula')
}
J <- length(formula.list)
if ( M <= 0 ) { stop("M must be a positive integer") }
if ( class(data) != 'data.frame' ) {
stop('data must be a data.frame')
}
if (!is.null(histdata)) {
if(class(histdata) != 'data.frame') {
stop('histdata must be a NULL or a data.frame')
}
}
if ( is.null(b0) ) {
if ( ! is.null(histdata) ) {
stop('b0 must be a number in (0, 1] if histdata is specified')
}
}
if ( !is.null(b0) ) {
if( is.null(histdata) ) {
stop('b0 must be NULL if histdata is NULL')
}
}
famlist <- sapply(family.list, function(f)f$family)
if ( any( !( famlist %in% c('gaussian', 'poisson', 'Gamma', 'binomial') ) ) ) {
stop("Family must be one of gaussian, poisson, Gamma, or binomial")
}
if( is.null(b0) ) {
b0 <- 0
}
get_depvar <- function(f, data) {
data[, all.vars(f, data)[1] ]
}
get_desmat <- function(f, data) {
model.matrix(f, data)
}
ymat <- sapply(formula.list, get_depvar, data)
Xlist <- lapply(formula.list, get_desmat, data)
if( !is.null( histdata ) ) {
y0mat <- sapply(formula.list, get_depvar, histdata)
Xlist <- lapply(formula.list, get_desmat, histdata)
} else {
b0 <- 0
y0mat <- matrix(rep(0, J), ncol = J)
X0list <- lapply(rep(0, J), function(x) as.matrix(x))
n0 <- 0
}
distnamevec <- sapply(family.list, function(x) x$family)
linknamevec <- sapply(family.list, function(x) x$link)
if ( is.null(alpha0) ) {
alpha0 = rep(.1, J)
}
if ( is.null(gamma0) ) {
gamma0 = rep(.1, J)
}
if ( length(alpha0) != J ) {
stop('alpha0 must have length = number of endpoints')
}
if ( length(gamma0) != J ) {
stop('gamma0 must have length = number of endpoints')
}
if ( is.null( S0beta ) ) {
get_cov_mtx <- function(f, data) {
X <- model.matrix(f, data)
chol2inv(chol(crossprod(X)))
}
S0beta <- lapply(formula.list, get_cov_mtx, data = data)
}
if ( class(S0beta) != 'list' ) {
stop('S0beta must be a list of matrices')
}
if ( is.null(sigma0logphi) ) {
sigma0logphi <- rep(0.1, times = J)
}
if ( length(sigma0logphi) != J ) {
stop('sigma0logphi must have length = number of endpoints')
}
if ( is.null(v0) ) {
v0 <- J + 2
}
if ( v0 <= J ) {
stop("v0 must be larger than number of endpoints")
}
if ( is.null(V0) ) {
V0 <- diag(.001, J)
}
if (nrow(V0) != J | ncol(V0) != J) {
stop('V0 must be a square matrix of dimension = number of endpoints')
}
if ( is.null(c0) ) {
c0 <- rep(10000, J)
}
if ( length(c0) < J) {
stop("c0 must have same length as formula.list")
}
if ( is.null(beta0) ) {
get_glm_coef <- function(fmla, fam, data) {
coef( glm( fmla, fam, data ) )
}
beta0 <- mapply(get_glm_coef, formula.list, family.list, MoreArgs = list('data' = data), SIMPLIFY = FALSE )
}
if ( class(beta0) != 'list' | length(beta0) != J | any(sapply(beta0, class) != 'numeric')) {
stop('beta0 must be a list of dimension = number of endpoint and each element of the list must be of type numeric')
}
if ( is.null( phi0 ) ) {
get_glm_disp <- function(fmla, fam, data) {
summary( glm( fmla, fam, data ) )$dispersion
}
phi0 <- mapply(get_glm_disp, formula.list, family.list, MoreArgs = list('data' = data), SIMPLIFY = TRUE )
}
if ( length(phi0) != J ) {
stop('phi0 must be a numeric vector with length = number of endpoints')
}
if ( is.null( Gamma0 ) ) {
Gamma0 <- cor(ymat)
}
if (nrow(Gamma0) != J | ncol(Gamma0) != J) {
stop('Gamma0 must be a square matrix of dimension = number of endpoints')
}
smpl <- sample_copula_cpp (
ymat, Xlist, distnamevec, linknamevec, c0, S0beta, sigma0logphi,
alpha0, gamma0, Gamma0, v0, V0, b0, y0mat, X0list, M, beta0, phi0, thin
)
get_col_names <- function(f, data) {
colnames(model.matrix(f, data))
}
colNames <- lapply(formula.list, get_col_names, data = data)
for(j in 1:J) {
colnames( smpl$betasample[[j]] ) <- colNames[[j]]
}
smpl
} |
bootIsotonicResample <- function (data, mle) {
.responseSequence <- data$responseSequence;
.doseSequence <- data$doseSequence;
.sequenceLength <- length(.responseSequence)
.shortSequenceLength <- .sequenceLength - 1;
.pavaProbability <- mle$baselinePava$pavaProbability;
.nDoses <- mle$baselinePava$nDoses;
.firstDose <- mle$firstDose;
PROBABILITY.GAMMA <- mle$PROBABILITY.GAMMA;
isGAMMALow <- PROBABILITY.GAMMA < 0.5;
isGAMMAMid <- PROBABILITY.GAMMA == 0.5;
isGAMMAHigh <- PROBABILITY.GAMMA > 0.5;
PROBABILITY.BETA <-
{
if (PROBABILITY.GAMMA < 0.5) {
PROBABILITY.BETA <- PROBABILITY.GAMMA/(1 -PROBABILITY.GAMMA);
} else if (PROBABILITY.GAMMA == 0.5) {
PROBABILITY.BETA <- 1;
} else
PROBABILITY.BETA <- (1 - PROBABILITY.GAMMA)/PROBABILITY.GAMMA;
}
{
if (runif(1) <= .pavaProbability[.nDoses == .firstDose]) {
.firstResponse <- 1;
} else {
.firstResponse <- 0;
}
}
.resampleDoseSequence <-
c(.firstDose, rep(0, times = .shortSequenceLength));
.resampleResponseSequence <-
c(.firstResponse, rep(0, times = .shortSequenceLength));
for (i in 1:.shortSequenceLength) {
isResponsePositive <- .resampleResponseSequence[i] == 1;
isResponseNegative <- !isResponsePositive;
isDoseMinimum <- .resampleDoseSequence[i] == min(.nDoses);
isDoseMaximum <- .resampleDoseSequence[i] == max(.nDoses);
isDoseBetween <- .resampleDoseSequence[i] != min(.nDoses) &&
.resampleDoseSequence[i] != max(.nDoses);
isBeta <- runif(1) <= PROBABILITY.BETA;
isNotBeta <- !isBeta;
{
if (isGAMMALow && isDoseMinimum && isResponsePositive) {
.resampleDoseSequence[i + 1] <- .resampleDoseSequence[i];
} else if (isGAMMALow && isDoseMinimum && isResponseNegative && isNotBeta) {
.resampleDoseSequence[i + 1] <- .resampleDoseSequence[i];
} else if (isGAMMALow && isDoseMinimum && isResponseNegative && isBeta) {
.resampleDoseSequence[i + 1] <- .nDoses[match(.resampleDoseSequence[i], .nDoses) + 1];
} else if (isGAMMALow && isDoseBetween && isResponsePositive) {
.resampleDoseSequence[i + 1] <- .nDoses[match(.resampleDoseSequence[i], .nDoses) - 1];
} else if (isGAMMALow && isDoseBetween && isResponseNegative && isNotBeta) {
.resampleDoseSequence[i + 1] <- .resampleDoseSequence[i];
} else if (isGAMMALow && isDoseBetween && isResponseNegative && isBeta) {
.resampleDoseSequence[i + 1] <- .nDoses[match(.resampleDoseSequence[i], .nDoses) + 1];
} else if (isGAMMALow && isDoseMaximum && isResponseNegative) {
.resampleDoseSequence[i + 1] <- .resampleDoseSequence[i];
} else if (isGAMMALow && isDoseMaximum && isResponsePositive) {
.resampleDoseSequence[i + 1] <- .nDoses[match(.resampleDoseSequence[i], .nDoses) - 1];
} else if (isGAMMAMid && isDoseMinimum && isResponsePositive) {
.resampleDoseSequence[i + 1] <- .resampleDoseSequence[i];
} else if (isGAMMAMid && isDoseMinimum && isResponseNegative) {
.resampleDoseSequence[i + 1] <- .nDoses[match(.resampleDoseSequence[i], .nDoses) + 1];
} else if (isGAMMAMid && isDoseBetween && isResponsePositive) {
.resampleDoseSequence[i + 1] <- .nDoses[match(.resampleDoseSequence[i], .nDoses) - 1];
} else if (isGAMMAMid && isDoseBetween && isResponseNegative) {
.resampleDoseSequence[i + 1] <- .nDoses[match(.resampleDoseSequence[i], .nDoses) + 1];
} else if (isGAMMAMid && isDoseMaximum && isResponsePositive) {
.resampleDoseSequence[i + 1] <- .nDoses[match(.resampleDoseSequence[i], .nDoses) - 1];
} else if (isGAMMAMid && isDoseMaximum && isResponseNegative) {
.resampleDoseSequence[i + 1] <- .resampleDoseSequence[i];
} else if (isGAMMAHigh && isDoseMinimum && isResponsePositive) {
.resampleDoseSequence[i + 1] <- .resampleDoseSequence[i];
} else if (isGAMMAHigh && isDoseMinimum && isResponseNegative) {
.resampleDoseSequence[i + 1] <- .nDoses[match(.resampleDoseSequence[i], .nDoses) + 1];
} else if (isGAMMAHigh && isDoseBetween && isResponsePositive && isBeta) {
.resampleDoseSequence[i + 1] <- .nDoses[match(.resampleDoseSequence[i], .nDoses) - 1];
} else if (isGAMMAHigh && isDoseBetween && isResponsePositive && isNotBeta) {
.resampleDoseSequence[i + 1] <- .resampleDoseSequence[i];
} else if (isGAMMAHigh && isDoseBetween && isResponseNegative) {
.resampleDoseSequence[i + 1] <- .nDoses[match(.resampleDoseSequence[i], .nDoses) + 1];
} else if (isGAMMAHigh && isDoseMaximum && isResponsePositive && isBeta) {
.resampleDoseSequence[i + 1] <- .nDoses[match(.resampleDoseSequence[i], .nDoses) - 1];
} else if (isGAMMAHigh && isDoseMaximum && isResponsePositive && isNotBeta) {
.resampleDoseSequence[i + 1] <- .resampleDoseSequence[i];
} else if (isGAMMAHigh && isDoseMaximum && isResponseNegative) {
.resampleDoseSequence[i + 1] <- .resampleDoseSequence[i];
}
}
{
if (runif(1) <= .pavaProbability[.nDoses == .resampleDoseSequence[i + 1]]) {
.resampleResponseSequence[i + 1] <- 1;
} else {
.resampleResponseSequence[i + 1] <- 0;
}
}
}
estimates <- data.frame(
responseSequence = .resampleResponseSequence,
doseSequence = .resampleDoseSequence);
} |
equivalent_at <- function(result) {
if (any(result$region_high != abs(result$region_low))) {
warning(paste(
"Asymmetrical equivalence region(s) detected, which violates",
"code\n assumptions in `equivalent_at`.",
"This needs fixing."
))
}
result <- split(result, seq(nrow(result)))
result <- lapply(
result, function(x) {
x$equivalent_at <- get_absolute_equivalent_at(x)
if (x$scale == "relative") {
x$equivalent_at <- x$equivalent_at / x$mean_y
}
x
}
)
do.call(rbind, result)
}
get_absolute_equivalent_at <- function(result) {
eq_at <- max(
abs(c(result$CI_low, result$CI_high))
)
eq_at + (0.001 * eq_at)
} |
.align.timeSeries <-
function(x, by = "1d", offset = "0s",
method = c("before", "after", "interp", "fillNA", "fmm", "periodic",
"natural", "monoH.FC"), include.weekends = FALSE, ...)
{
Title <- x@title
Documentation <- x@documentation
if (x@format == "counts")
stop(as.character(match.call())[1],
" is for time series and not for signal series.")
if (is.unsorted(x)) x <- sort(x)
Method <- match.arg(method)
fun <- switch(Method,
before = function(x, u, v)
approxfun(x = u, y = v, method = "constant", f = 0, ...)(x),
after = function(x, u, v)
approxfun(x = u, y = v, method = "constant", f = 1, ...)(x),
interp = ,
fillNA = function(x, u, v)
approxfun(x = u, y = v, method = "linear", f = 0.5, ...)(x),
fmm = ,
periodic = ,
natural = ,
monoH.FC = function(x, u, v)
splinefun(x = u, y = v, method = Method, ...)(x))
td1 <- time(x)
td2 <- align(td1, by = by, offset = offset)
u <- as.numeric(td1, units = "secs")
xout <- as.numeric(td2, units = "secs")
N = NCOL(x)
data <- matrix(ncol = N, nrow = length(td2))
xx <- getDataPart(x)
for (i in 1:N) {
v <- as.vector(xx[, i])
yout <- fun(xout, u, v)
if (Method == "fillNA") yout[!(xout %in% u)] = NA
data[, i] = yout
}
ans <- timeSeries(data, td2, units = colnames(x))
if(!include.weekends) ans <- ans[isWeekday(td2), ]
ans@title <- Title
ans@documentation <- Documentation
ans
}
setMethod("align", "timeSeries", .align.timeSeries) |
tv.bib <- function(x='all', db, dict = tv.dict(db), quiet=FALSE, tv_home, ...) {
if(missing(tv_home)) tv_home <- tv.home()
if(missing(db) & missing(dict)) {
message('Using tvrefenc.dbf from default dictionary.')
dict = ''
}
if(dict == 'default') dict <- ''
bibliopath <- file.path(tv_home, 'Popup', dict, 'tvrefenc.dbf')
biblio <- read.dbf(bibliopath, as.is=TRUE)
for(i in c('AUTHOR','TITLE','PUBLISHED', 'ADDRESS'))
if(i %in% names(biblio)) biblio[,i] <- iconv(biblio[,i], getOption('tv.iconv'), "")
if(x[1] != 'all') {
x <- as.numeric(unique(x))
biblio <- biblio[match(x, as.numeric(biblio$REFERENCE)),]
if(!quiet) print(biblio)
}
invisible(biblio)
}
tv.biblio <- tv.bib |
test_that("good input", {
mock_res = structure(
list(),
class = "gh_response",
response = list(
"x-ratelimit-limit" = "5000",
"x-ratelimit-remaining" = "4999",
"x-ratelimit-reset" = "1580507619"
)
)
limit = gh_rate_limit(mock_res)
expect_equal(limit$limit, 5000L)
expect_equal(limit$remaining, 4999L)
expect_s3_class(limit$reset, "POSIXct")
})
test_that("errors", {
expect_error(gh_rate_limit(list()))
expect_error(gh_rate_limit(.token = "bad"))
})
test_that("missing rate limit", {
mock_res = structure(
list(),
class = "gh_response",
response = list(
)
)
limit = gh_rate_limit(mock_res)
expect_equal(limit$limit, NA_integer_)
expect_equal(limit$remaining, NA_integer_)
expect_equal(as.double(limit$reset), NA_real_)
}) |
model <- function(y, components, seas.period = NULL, cycle.period = NULL){
y <- as.matrix(y)
if("trend" %in% components & "slope" %in% components){
mt<-paste("SSM","trend","(", "degree = 2", " , ", "Q = list(matrix(NA), matrix(NA))",")", sep="")
} else if ("trend" %in% components & !("slope" %in% components)) {
mt<-paste("SSM","trend","(", "degree = 1", " , ", "Q = matrix(NA)",")", sep="")
} else { mt <- NULL }
if("seasonal" %in% components){
if(is.null(seas.period)){ stop("A seasonal model needs a seas.period") }
ms <- paste("SSM","seasonal", "(", "period = ", seas.period, " , ", "Q = matrix(NA)", ")", sep="")
} else { ms <- NULL }
if("cycle" %in% components){
if(is.null(cycle.period)){ stop("A cyclical model needs a cycle.period") }
mc <- paste("SSM","cycle", "(", "period = ", cycle.period, " , ", "Q = matrix(NA)", ")", sep="")
} else { mc <- NULL }
formula <- as.formula(paste("y ~ ", paste(unlist(list(mt,ms,mc)), collapse = " + ")))
m <- SSModel(formula)
return(m)
} |
detectKit <- function(data, index = FALSE, debug = FALSE) {
if (is.data.frame(data)) {
if (!"Marker" %in% colnames(data)) {
stop("Data frame must contain a column 'Marker'")
}
} else if (is.vector(data)) {
if (!is.character(data)) {
stop("Vector must be a character vector with marker names")
}
}
attribute <- attr(x = data, which = "kit", exact = TRUE)
if (!is.null(attribute)) {
if (!index) {
detectedKit <- getKit(attribute, what = "Short.Name")
} else {
detectedKit <- getKit(attribute, what = "Index")
}
if (!is.na(detectedKit)) {
message(paste(
"Found matching attribute 'kit':",
detectedKit, "(attr =", attribute, ")"
))
if (debug) {
print("Attribute:")
print(attribute)
print("Detected kit:")
print(detectedKit)
}
return(detectedKit)
}
}
if (is.data.frame(data)) {
markers <- unique(data$Marker)
} else if (is.vector(data)) {
markers <- unique(data)
} else {
stop("'data' must be a data.frame or character vector.")
}
if (any(is.na(markers))) {
markers <- markers[!is.na(markers)]
message("Removed NA from markers.")
}
kits <- getKit()
kitMarkers <- list()
score <- vector()
detectedKit <- vector()
for (k in seq(along = kits)) {
kitMarkers[[k]] <- getKit(kits[k], what = "Marker")
}
if (debug) {
print("Kit markers:")
print(kitMarkers)
print("Data markers:")
print(markers)
}
for (k in seq(along = kitMarkers)) {
score[k] <- sum(markers %in% kitMarkers[[k]])
score[k] <- score[k] / length(kitMarkers[[k]])
}
bestFit <- max(score, na.rm = TRUE)
detectedKit <- which(score %in% bestFit)
candidates <- length(detectedKit)
if (debug) {
print("Number of matching markers:")
print(score)
print("Detected kit:")
print(detectedKit)
}
prevDetected <- detectedKit
if (candidates > 1) {
if (debug) {
print("Multiple kits with equal score!")
print("Trying to resolve by closest match of marker order.")
}
kitScore <- vector()
for (c in seq(along = detectedKit)) {
kitString <- paste(kitMarkers[[detectedKit[c]]], collapse = "")
score <- vector()
matchStart <- 0
matchEnd <- 0
prevPos <- 0
for (m in seq(along = markers)) {
match <- regexpr(
pattern = markers[m], text = kitString,
ignore.case = FALSE, perl = FALSE,
fixed = TRUE, useBytes = FALSE
)
if (match < 0) {
score <- NA
break
} else {
matchStart <- match
matchEnd <- match + attr(match, "match.length")
if (matchStart < prevPos) {
score[m] <- -1
} else {
score[m] <- 1
}
}
prevPos <- matchEnd
}
kitScore[c] <- sum(score)
}
bestFit <- suppressWarnings(max(kitScore, na.rm = TRUE))
kitIndex <- which(kitScore %in% bestFit)
detectedKit <- detectedKit[kitIndex]
if (debug) {
print("Marker position matching:")
print(kitScore)
print("Detected kit:")
print(detectedKit)
}
}
candidates <- length(detectedKit)
if (candidates == 0) {
detectedKit <- prevDetected
if (debug) {
print("No match with this method!")
print("Revert to previous match:")
print(detectedKit)
}
} else {
prevDetected <- detectedKit
}
if (candidates > 1) {
message("Could not resolve kit. Multiple candidates returned.")
}
if (!index) {
detectedKit <- getKit(detectedKit, what = "Short.Name")
}
message(paste("Detected kit(s):", paste(detectedKit, collapse = ", ")))
if (debug) {
print("Detected kit:")
print(detectedKit)
}
return(detectedKit)
} |
ui.mfssa <- fluidPage(
tags$head(tags$style(HTML("body { max-width: 1250px !important; }"))),
titlePanel("MFSSA Illustration"),
sidebarLayout(
sidebarPanel(
width = 3, tags$head(tags$style(type = "text/css", ".well { max-width: 300px; }")),
radioButtons("bs.fr", "Choose Basis:", choices = c("B-spline", "Fourier"), selected = "B-spline", inline = TRUE),
uiOutput("xdeg", width = "250px"), uiOutput("xdf", width = "250px"),
tags$hr(style = "border-color: red;", width = "150px"),
column(6, uiOutput("g")), column(6, uiOutput("sg")), column(6, uiOutput("d")), column(6, uiOutput("dmd.uf")),
sliderInput("mssaL", HTML("Win.L. (MSSA):"), min = 1, max = 50, value = 50, step = 1, width = "210px"),
sliderInput("fssaL", HTML("Win.L. (MFSSA):"), min = 1, max = 50, value = 20, step = 1, width = "210px"),
column(6, uiOutput("run.fpca")), column(6, uiOutput("run.ssa"))
),
mainPanel(
width = 9, tags$style(type = "text/css", ".shiny-output-error { visibility: hidden; }", ".shiny-output-error:before { visibility: hidden; },"),
tabsetPanel(
id = "Panel", type = "tabs",
tabPanel(
title = "Data", value = "Data",
column(12, uiOutput("ts.selected", align = "center"), style = "color:red;"),
fluidRow(
column(4, radioButtons("f.choice", "Choose from:", c("Server" = "server", "Upload" = "upload", "Simulate" = "sim"), selected = "sim", inline = TRUE, width = "250px")),
column(4, uiOutput("s.choice", width = "250px"), column(6, uiOutput("a1.f")), column(6, uiOutput("a1.l"))), column(2, uiOutput("noise.t", width = "125px")), column(2, uiOutput("noise.p", width = "125px")),
column(4, uiOutput("file")), column(4, uiOutput("sep"), uiOutput("header"))
),
column(4, uiOutput("model")), column(4, uiOutput("t.len")), column(2, uiOutput("a2.f")), column(2, uiOutput("n.sd")),
column(12, plotOutput("data.plot", height = 500, width = 900))
),
tabPanel(
"Basis Functions",
column(8, plotOutput("basis.desc", height = 600, width = 600)), column(4, uiOutput("basis.n", width = "300px"))
),
tabPanel(
"Data Description (SSA Summary)",
column(4, uiOutput("desc", width = "250px")), column(4, uiOutput("as.choice", width = "400px"), uiOutput("run.fda.gcv", width = "200px"), uiOutput("rec.type", width = "300px")), column(2, uiOutput("freq")), column(2, uiOutput("sts.choice")),
fluidRow(
column(
8, conditionalPanel(condition = "output.flag_plot", plotOutput("res.plot", height = 600, width = 600)),
conditionalPanel(condition = "output.flag_plotly", plotlyOutput("res.ly", height = 600, width = 600))
),
column(4, uiOutput("var.which"), uiOutput("s.plot"), fluidRow(column(8, uiOutput("b.indx")), column(4, uiOutput("s.CI"))), column(12, uiOutput("comp.obs"), verbatimTextOutput("RMSEs")))
)
),
tabPanel(
"Forecasting",
column(3, checkboxGroupInput("fcast.method", "Forecasting Method:", choices = c("Recurrent" = "recurrent", "Vector" = "vector"), selected = "recurrent", width = "250px")),
column(4, uiOutput("fcast.horizon")), column(2, uiOutput("run.fcast")), column(3, uiOutput("fcast.type")),
fluidRow(column(8, plotlyOutput("fcast.ly", height = 600, width = 600)), column(4, uiOutput("fcast.select"), uiOutput("fcast.var")))
),
tabPanel("Manual", includeMarkdown(system.file("shiny/rmd", "report.Rmd", package = "Rfssa")))
)
)
)
)
server.mfssa <- function(input, output, clientData, session) {
iTs <- reactiveVal(list())
iTrs <- reactiveVal(list())
iXs <- reactiveVal(list())
itmp <- reactiveVal(0)
df <- 100
vf <- 20
T <- 100
output$flag_plotly <- reactive(input$desc %in% c("mfssa.reconst", "ssa.reconst") && input$rec.type %in% c("heatmap", "line", "3Dline", "3Dsurface"))
output$flag_plot <- reactive(!(input$desc %in% c("mfssa.reconst", "ssa.reconst") && input$rec.type %in% c("heatmap", "line", "3Dline", "3Dsurface")))
outputOptions(output, "flag_plotly", suspendWhenHidden = FALSE)
outputOptions(output, "flag_plot", suspendWhenHidden = FALSE)
hideTab(inputId = "Panel", target = "Forecasting")
rfar <- function(N, norm, psi, Eps, basis) {
OpsMat <- function(kernel, basis) {
u <- seq(0, 1, by = 0.01)
n <- length(u)
K_mat <- outer(u, u, FUN = kernel)
K_t <- smooth.basis(u, K_mat, basis)$fd
A <- inprod(K_t, basis)
K <- smooth.basis(u, A, basis)$fd
B <- inprod(K, basis)
return(B)
}
Psi_mat0 <- OpsMat(psi, basis)
Gram <- inprod(basis, basis)
Psi_mat <- solve(Gram) %*% Psi_mat0
E <- Eps$coefs
X <- E
for (i in 2:N) X[, i] <- Psi_mat %*% X[, i - 1] + E[, i]
X_fd <- fd(X, basis)
return(X_fd)
}
gamma0 <- function(norm) {
f <- function(x) {
g <- function(y) psi0(x, y)^2
return(integrate(g, 0, 1)$value)
}
f <- Vectorize(f)
A <- integrate(f, 0, 1)$value
return(norm / A)
}
psi0 <- function(x, y) 2 - (2 * x - 1)^2 - (2 * y - 1)^2
fpca_proj <- function(i, U) {
harm <- U$harmonics[i]
scores <- U$scores[, i]
m <- nrow(harm$coefs)
n <- length(scores)
coef <- matrix(NA, nrow = m, ncol = n)
for (i0 in 1:m) for (j in 1:n) coef[i0, j] <- harm$coefs[i0] * scores[j]
pc <- fd(coef, harm$basis)
return(pc)
}
fpca_rec <- function(d1, d2, U) {
s <- fpca_proj(d1, U)
if (d2 > d1) for (i0 in (d1 + 1):d2) s <- s + fpca_proj(i0, U)
return(s)
}
Tr1 <- function(tau, t) {
tr1 <- ifelse("f1" %in% input$model, 1, 0) * (cos(2 * pi * input$a1.f * (t + input$a1.l)) * exp(tau^2) - sin(2 * pi * input$a1.f * t) * cos(4 * pi * tau))
if ("f2" %in% input$model) tr1 <- tr1 + (cos(2 * pi * input$a2.f * t) * exp(1 - tau^2) + sin(2 * pi * input$a2.f * t) * sin(pi * tau))
return(tr1)
}
Tr2 <- function(tau, t) {
ifelse("f1" %in% input$model, 1, 0) * (sin(2 * pi * input$a1.f * t) * exp(tau^2) + cos(2 * pi * input$a1.f * (t - input$a1.l)) * cos(4 * pi * tau))
}
simulate <- function() {
if (is.null(input$a1.f) || ("f2" %in% input$model && is.null(input$a2.f))) {
return()
}
tau <- seq(0, 1, length = T)
t <- 1:input$t.len
noise <- list()
Trs <- list(outer(tau, t, FUN = Tr1), outer(tau, t, FUN = Tr2))
set.seed(T * input$t.len * input$n.sd)
for (i in 1:length(Trs)) {
noise[[i]] <- Z <- matrix(rnorm(input$t.len * T, 0, input$n.sd), nrow = T)
if (input$noise.t == "ar1") {
if (input$noise.p) {
Z[1, ] <- 0
A <- diag(1, T)
if (T > 2) for (j in 1:(T - 2)) diag(A[-(1:j), ]) <- input$noise.p^j
if (T > 1) A[T, 1] <- input$noise.p^(T - 1)
noise[[i]] <- A %*% Z
}
}
if (input$noise.t == "swn") {
Z <- matrix(rnorm(input$t.len * input$xdf, 0, input$n.sd), ncol = input$t.len)
basis.Z <- fda::create.bspline.basis(c(0, 1), input$xdf)
tau <- seq(0, 1, length = T)
basis.noise <- fda::fd(Z, basis.Z)
noise[[i]] <- eval.fd(tau, basis.noise)
}
if (input$noise.t == "far1") {
k0 <- gamma0(input$noise.p)
psi <- function(x, y) k0 * psi0(x, y)
Z[1, ] <- 0
noise[[i]] <- apply(Z, 2, cumsum)
if (input$bs.fr == "B-spline") {
basis.Z <- fda::create.bspline.basis(c(0, 1), input$xdf)
} else {
basis.Z <- fda::create.fourier.basis(c(0, 1), input$xdf)
}
tau <- seq(0, 1, length = T)
Eps <- smooth.basis(tau, noise[[i]], basis.Z)$fd
basis.noise <- rfar(input$t.len, input$noise.p, psi, Eps, basis.Z)
noise[[i]] <- eval.fd(tau, basis.noise)
}
}
return(list(Trs = Trs, noise = noise))
}
observeEvent(input$dmd.uf, {
updateTabsetPanel(session, "Panel", selected = "Data")
updateCheckboxGroupInput(session, "s.plot", selected = "")
})
observeEvent(input$run.ssa, {
showTab(inputId = "Panel", target = "Forecasting")
})
output$xdeg <- renderUI({
if (input$bs.fr == "Fourier") {
return()
}
sliderInput("xdeg", HTML("Degree of B-spline Basis:"), min = 0, max = 5, value = 3, step = 1, width = "250px")
})
output$xdf <- renderUI({
sliderInput("xdf", paste("Deg. of freedom of", input$bs.fr, "Basis:"), min = ifelse(input$bs.fr == "B-spline", input$xdeg + 1, 3), max = df, value = vf, step = ifelse(input$bs.fr == "B-spline", 1, 2), width = "250px")
})
output$g <- renderUI({
textInput("g", "Groups", value = "1:2")
})
output$sg <- renderUI({
m <- length(eval(parse(text = paste0("list(", input$g, ")"))))
sliderInput("sg", "Select G:", min = 1, max = m, value = c(1, m), step = 1)
})
output$dmd.uf <- renderUI({
checkboxGroupInput("dmd.uf", "Functions", choices = c("Demean" = "dmd", "Dbl Range" = "dbl", "Univ. FSSA" = "uf"), selected = "uf")
})
output$d <- renderUI({
sliderInput("d", "d", min = 1, max = min(input$fssaL, input$mssaL), value = c(1, 2), step = 1)
})
output$run.ssa <- renderUI({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model))) {
return()
}
actionButton("run.ssa", paste("run M(F)SSA"))
})
output$run.fpca <- renderUI({
return()
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model))) {
return()
}
actionButton("run.fpca", paste("run (D)FPCA"))
})
run_ssa <- eventReactive(input$run.ssa, {
withProgress(message = "MSSA.MFSSA: Running", value = 0, {
if (input$bs.fr == "B-spline") {
bas.fssa <- fda::create.bspline.basis(c(0, 1), nbasis = input$xdf, norder = input$xdeg + 1)
} else {
bas.fssa <- fda::create.fourier.basis(c(0, 1), nbasis = input$xdf)
}
tau <- seq(0, 1, length = nrow(iTs()[[1]]))
uUf <- list()
if ("uf" %in% input$dmd.uf) {
for (i in 1:length(iTs())) {
uUf[[i]] <- fssa(Rfssa::fts(X = list(iTs()[[i]]), B = list(eval.basis(tau, bas.fssa)), grid = list(tau)), input$fssaL)
}
}
fts.Y <- Rfssa::fts(X = iTs(), B = rep(list(eval.basis(tau, bas.fssa)), length(iTs())), grid = rep(list(tau), length(iTs())))
mUf <- fssa(fts.Y, input$fssaL)
Ys <- NULL
for (i in 1:length(iTs())) {
Ys <- cbind(Ys, t(iTs()[[i]]))
}
Us <- ssa(Ys, input$mssaL, kind = "mssa")
return(list(Us = Us, mUf = mUf, uUf = uUf, tau = tau, bas.fssa = bas.fssa))
})
})
run_fpca <- function() {
withProgress(message = "(D)FPCA: Running", value = 0, {
if (input$bs.fr == "B-spline") {
bas.fssa <- fda::create.bspline.basis(c(0, 1), nbasis = input$xdf, norder = input$xdeg + 1)
} else {
bas.fssa <- fda::create.fourier.basis(c(0, 1), nbasis = input$xdf)
}
tau <- seq(0, 1, length = nrow(iTs()[[1]]))
Y <- smooth.basis(tau, iTs()[[ifelse(is.null(input$var.which), 1, as.numeric(input$var.which))]], bas.fssa)$fd
f.pca <- pca.fd(Y, nharm = min(input$d[2], input$xdf), centerfns = FALSE)
fpca.rec <- fpca_rec(min(input$d[1], input$xdf), min(input$d[2], input$xdf), f.pca)
fpca.re <- eval.fd(tau, fpca.rec)
return(list(fpca = fpca.re, dfpca = fpca.re))
})
}
output$s.choice <- renderUI({
if (input$f.choice != "server") {
return()
}
if (!length(iXs())) {
load_github_data("https://github.com/haghbinh/Rfssa/blob/master/data/Callcenter.RData")
load_github_data("https://github.com/haghbinh/Rfssa/blob/master/data/Jambi.RData")
Callcenter <- get("Callcenter", envir = .GlobalEnv)
Jambi <- get("Jambi", envir = .GlobalEnv)
Xs <- list()
Xs[[1]] <- matrix(sqrt(Callcenter$calls), nrow = 240)
Xs[[2]] <- Xs[[3]] <- matrix(NA, nrow = 128, ncol = dim(Jambi$NDVI)[3])
for (i in 1:dim(Jambi$NDVI)[3]) {
Xs[[2]][, i] <- density(Jambi$NDVI[, , i], from = 0, to = 1, n = 128)$y
Xs[[3]][, i] <- density(Jambi$EVI[, , i], from = 0, to = 1, n = 128)$y
}
colnames(Xs[[2]]) <- colnames(Xs[[3]]) <- Jambi$Date
names(Xs) <- c("Callcenter", "NDVI", "EVI")
Xs[[4]] <- Xs[2:3]
names(Xs) <- c(names(Xs[1:3]), "xDI")
iXs(Xs)
}
s.choices <- 1:length(iXs())
names(s.choices) <- names(iXs())
selectInput("s.choice", "Select a file from server: ", choices = s.choices, width = "250px")
})
output$noise.t <- renderUI({
if (input$f.choice != "sim") {
return()
}
selectInput("noise.t", "Type of noice: ", choices = c("AR(1)" = "ar1", "FAR(1)" = "far1", "Smooth WN" = "swn"), width = "125px")
})
output$noise.p <- renderUI({
if (input$f.choice != "sim") {
return()
}
if (!is.null(input$noise.t)) {
if (input$noise.t == "swn") {
return()
}
}
sliderInput("noise.p", "AR Parameter:", min = 0, max = 1, value = 0, step = 0.01, width = "125px")
})
output$model <- renderUI({
if (input$f.choice != "sim") {
return()
}
choices <- c("A.1t(w1,l) F1 +" = "f1", "A.2t(w2) F2" = "f2")
checkboxGroupInput("model", "Model:", choices = choices, selected = "f1", inline = TRUE, width = "250px")
})
output$t.len <- renderUI({
if (input$f.choice != "sim") {
return()
}
sliderInput("t.len", "Length of TS", min = 1, max = 200, value = 50, width = "250px")
})
output$n.sd <- renderUI({
if (input$f.choice != "sim") {
return()
}
sliderInput("n.sd", "Noise SD:", min = 0, max = 1, value = 0.05, width = "125px")
})
output$a1.f <- renderUI({
if (input$f.choice != "sim" || !("f1" %in% input$model)) {
return()
}
sliderInput("a1.f", HTML("ω1, Ang. Freq:"), min = 0, max = 0.5, value = 0.1, step = 0.01, width = "125px")
})
output$a1.l <- renderUI({
if (input$f.choice != "sim" || !("f1" %in% input$model)) {
return()
}
sliderInput("a1.l", HTML("Par. ℓ in A<sub>1t</sub>:"), min = -10, max = 10, value = 0, step = 1, width = "125px")
})
output$a2.f <- renderUI({
if (input$f.choice != "sim" || !("f2" %in% input$model)) {
return()
}
sliderInput("a2.f", HTML("ω2, Ang. Freq:"), min = 0, max = 0.5, value = 0.25, step = 0.01, width = "125px")
})
output$file <- renderUI({
if (input$f.choice != "upload") {
return()
}
fileInput("file", "Choose CSV File", accept = c("text/csv", "text/comma-separated-values,text/plain", ".csv"))
})
output$sep <- renderUI({
if (input$f.choice != "upload") {
return()
}
radioButtons("sep", "Separator", c("," = ",", ":" = ":", ";" = ";", Tab = "\t"), ",", inline = TRUE)
})
output$header <- renderUI({
if (input$f.choice != "upload") {
return()
}
checkboxInput("header", "Header", TRUE)
})
output$ts.selected <- renderText({
if (input$f.choice == "upload" && is.null(input$file)) {
return("<b>Select a 'csv' file that contain the time series in its columns</b>")
}
if (input$f.choice == "upload") {
Ts <- as.matrix(read.table(input$file$datapath, header = input$header, sep = input$sep))
if (!input$header && !is.numeric(Ts)) {
headers <- as.factor(Ts[1, ])
TS <- list()
for (l in levels(headers)) TS[[l]] <- matrix(as.numeric(Ts[-1, headers == l]), nrow = nrow(Ts) - 1)
Ts <- TS
} else {
Ts <- list(Ts)
}
} else if (input$f.choice == "server") {
if (is.null(input$s.choice)) {
return()
}
i <- as.numeric(input$s.choice)
Ts <- iXs()[[i]]
if (is.matrix(Ts)) Ts <- list(Ts)
} else {
simul <- simulate()
Ts <- Map("+", simul$Trs, simul$noise)
}
if (!length(Ts)) {
return()
}
if (is.null(colnames(Ts[[1]]))) {
for (i in 1:length(Ts)) colnames(Ts[[i]]) <- paste("fn", 1:ncol(Ts[[i]]))
}
if ("dmd" %in% input$dmd.uf) {
for (i in length(Ts)) {
Ts[[i]] <- Ts[[i]] - mean(Ts[[i]])
if (input$f.choice == "sim") simul$Trs[[i]] <- simul$Trs[[i]] - mean(simul$Trs[[i]])
}
}
if (is.null(names(Ts)) || sum(is.na(names(Ts)))) names(Ts) <- paste("Variable", 1:length(Ts))
updateSelectInput(session, "desc", selected = "ts")
updateSliderInput(session, "dimn", max = min(10, ncol(Ts[[1]])), value = min(2, ncol(Ts[[1]])))
updateSliderInput(session, "mssaL", max = trunc(ncol(Ts[[1]]) / 2))
updateSliderInput(session, "fssaL", max = min(120, trunc(ncol(Ts[[1]]) / 2)))
text <- paste("<b>", ncol(Ts[[1]]), ifelse(length(Ts) == 1, "Univariate", "Multivariate"), "Time series of length", nrow(Ts[[1]]), "</b>")
if (input$f.choice == "sim") iTrs(simul$Trs)
iTs(Ts)
return(text)
})
output$data.plot <- renderPlot({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model)) || !length(iTs())) {
return()
}
if (input$f.choice == "server") {
i <- as.numeric(input$s.choice)
fname <- names(iXs())[i]
} else if (input$f.choice == "upload") {
fname <- input$file$name
} else {
fname <- "Simulation"
}
par(mfrow = c(1, length(iTs())), mgp = c(1.5, .5, 0), mar = c(3, 3, 2.5, 1.75))
for (i in 1:length(iTs())) {
ts.plot(iTs()[[i]], main = paste("Time Series -", fname, "-", names(iTs()[i])), ylab = "", ylim = range(iTs()[[i]]), gpars = list(xaxt = "n"), xlab = "tau")
if (input$f.choice == "sim") for (j in 1:ncol(iTrs()[[i]])) points(iTrs()[[i]][, j], type = "l", col = 2)
}
})
output$basis.n <- renderUI({
sliderInput("basis.n", "Basis
})
output$basis.desc <- renderPlot({
if (is.null(input$basis.n)) {
return()
}
xs <- seq(0, 1, length.out = 1000)
if (input$bs.fr == "B-spline") {
Bx <- fda::bsplineS(xs, breaks = seq(0, 1, length.out = input$xdf - input$xdeg + 1), norder = input$xdeg + 1)
} else {
Bx <- fda::fourier(xs, nbasis = input$xdf)
}
ts.plot(Bx, col = 8, main = "B-spline Basis", xlab = "Grid Points", gpars = list(xaxt = "n"))
points(Bx[, input$basis.n], type = "l", lwd = 2, col = 2)
axis(1, trunc(summary(1:nrow(Bx))[-4]))
})
output$desc <- renderUI({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model))) {
return()
}
choices <- list(
Summary = c("Functional Time Series" = "ts", "How many basis? (GCV)" = "gcv"),
MFSSA = c("Scree" = "mfssa.scree", "W.Correlation" = "mfssa.wcor", "Paired" = "mfssa.pair", "Singular Vectors" = "mfssa.singV", "Periodogram" = "mfssa.perGr", "Singular Functions" = "mfssa.singF", "Reconstruction" = "mfssa.reconst"),
MSSA = c("Scree" = "ssa.scree", "W.Correlation" = "ssa.wcor", "Paired" = "ssa.pair", "Singular Vectors" = "ssa.vec", "Functions" = "ssa.funs", "Reconstruction" = "ssa.reconst")
)
selectInput("desc", "Select", choices = choices, width = "250px")
})
output$as.choice <- renderUI({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model))) {
return()
}
if (is.null(input$desc)) {
return()
} else if (input$desc != "ts") {
return()
}
radioButtons("as.choice", "Plot Choices:", c("All" = "all", "Multiple" = "mult", "Single" = "single"), selected = "all", inline = TRUE, width = "400px")
})
output$sts.choice <- renderUI({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model))) {
return()
}
if (((input$desc == "ts" && input$as.choice != "all")) && !(input$s.plot == "bf" && length(input$s.plot) == 1) && length(input$s.plot)) {
if (input$as.choice == "single") {
sliderInput("sts.choice", "Choose function:", min = 1, max = ncol(iTs()[[1]]), value = ifelse(is.null(input$sts.choice), 1, input$sts.choice), step = 1, width = "400px")
} else {
sliderInput("sts.choice", "Choose clusters:", min = 1, max = input$freq, value = ifelse(is.null(input$sts.choice), 0, input$sts.choice), step = 1, width = "200px")
}
}
})
output$rec.type <- renderUI({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model))) {
return()
}
if (is.null(input$desc)) {
return()
} else if (!input$desc %in% c("mfssa.reconst", "mfssa.singF", "ssa.reconst")) {
return()
}
if (input$desc == "mfssa.singF") {
selectInput("rec.type", "Type", choices = c("Heat plot" = "lheats", "Regular Plot" = "lcurves"), width = "250px")
} else if (input$desc == "ssa.reconst") {
selectInput("rec.type", "Type", choices = c("Heat Plot" = "heatmap", "Regular Plot" = "line", "3D Plot (line)" = "3Dline", "3D Plot (surface)" = "3Dsurface"), width = "250px")
} else {
selectInput("rec.type", "Type", choices = c("Heat Plot" = "heatmap", "Regular Plot" = "line", "3D Plot (line)" = "3Dline", "3D Plot (surface)" = "3Dsurface"), width = "250px")
}
})
output$freq <- renderUI({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model))) {
return()
}
if (((input$desc == "ts" && input$as.choice == "mult")) && !(input$s.plot == "bf" && length(input$s.plot) == 1) && length(input$s.plot)) {
sliderInput("freq", "Period:", min = 1, max = trunc(ncol(iTs()[[1]]) / 2), value = ifelse(is.null(input$freq), 1, input$freq), step = 1, width = "200px")
}
})
output$var.which <- renderUI({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model)) || is.null(input$desc)) {
return()
}
if (!input$desc %in% c("ts", "gcv", "ssa.reconst", "mfssa.reconst", "mfssa.singF") || length(iTs()) == 1) {
return()
}
choic <- as.character(1:length(iTs()))
names(choic) <- names(iTs())
if (!is.null(input$rec.type) && input$desc == "mfssa.reconst" && length(choic) != 1) if (input$rec.type %in% c("heatmap", "line")) choic <- c("All Variables" = "all", choic)
selectInput("var.which", NULL, choices = choic, selected = "1", width = "125px")
})
output$s.plot <- renderUI({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model))) {
return()
}
if (is.null(input$desc)) {
return()
} else if (input$desc != "ts") {
return()
}
choices <- c("Time Series" = "ts", "True Functions" = "tf", "Basis Func." = "bf", "Smoothing" = "bss", "Functional PCA" = "fpca", "Multivariate SSA" = "ssa", "Multivariate FSSA" = "mfssa")
if ("uf" %in% input$dmd.uf) {
choices <- append(choices, "fssa", 6)
names(choices)[7] <- "Functional SSA"
}
if (input$f.choice != "sim") {
choices <- choices[-2]
}
checkboxGroupInput("s.plot", "Plot:", choices = choices, selected = choices[1], width = "250px")
})
output$b.indx <- renderUI({
if ((input$f.choice == "upload" && is.null(input$file)) || !input$desc %in% c("ts") || !length(intersect(input$s.plot, c("bf", "bss")))) {
return()
}
val <- c(1, input$xdf)
if (length(input$b.indx) == 2) val <- input$b.indx
sliderInput("b.indx", "Basis Contr.", min = 1, max = input$xdf, value = val, dragRange = TRUE, step = 1, width = "200px")
})
output$s.CI <- renderUI({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model))) {
return()
}
if (input$desc == "ts" && length(intersect(input$s.plot, c("bss")))) {
if (input$as.choice == "single") checkboxInput("s.CI", "Show CI", ifelse(is.null(input$s.CI), FALSE, input$s.CI), width = "200px")
}
})
output$comp.obs <- renderUI({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model))) {
return()
}
if (is.null(input$desc)) {
return()
} else if (input$desc != "ts") {
return()
}
checkboxInput("comp.obs", "Compare fit. vs obs.", FALSE, width = "200px")
})
output$run.fda.gcv <- renderUI({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model))) {
return()
}
if (is.null(input$desc)) {
return()
} else if (input$desc != "gcv") {
return()
}
actionButton("run.fda.gcv", paste("update GCV"))
})
fda.gcv <- eventReactive(input$run.fda.gcv, {
withProgress(message = "FDA.GCV:
GCV <- NULL
df <- min(df, nrow(iTs()[[1]]))
if (input$bs.fr == "B-spline") nbasis <- (input$xdeg + 1):(df - 1) else nbasis <- seq(3, df, by = 2)
for (l in 1:length(nbasis)) {
if (input$bs.fr == "B-spline") {
bas.fssa <- fda::create.bspline.basis(c(0, 1), nbasis = nbasis[l], norder = input$xdeg + 1)
} else {
bas.fssa <- fda::create.fourier.basis(c(0, 1), nbasis = nbasis[l])
}
GCV[l] <- sum(smooth.basis(seq(0, 1, length.out = nrow(iTs()[[1]])), iTs()[[ifelse(is.null(input$var.which), 1, min(length(iTs()), as.numeric(input$var.which)))]], bas.fssa)$gcv)
incProgress(1 / length(nbasis), detail = l)
}
itmp(1)
return(list(GCV = GCV, nbasis = nbasis))
})
})
output$res.plot <- renderPlot({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model))) {
return()
}
if (input$desc %in% c("mfssa.reconst", "ssa.reconst") && !is.null(input$rec.type)) {
if (input$rec.type %in% c("heatmap", "line", "3Dline", "3Dsurface")) {
return()
}
}
if (!is.null(input$var.which) && length(iTs()) != 1) var.which <- as.numeric(input$var.which) else var.which <- 1
if (input$f.choice == "server") {
fname <- names(iXs())[as.numeric(input$s.choice)]
} else if (input$f.choice == "upload") {
fname <- input$file$name
} else {
fname <- "Simulation"
}
indx <- as.numeric(input$sts.choice)
Ts <- iTs()[[var.which]]
name.Ts <- names(iTs())[var.which]
if (length(intersect(input$s.plot, c("bf", "bss")))) {
if (is.null(input$b.indx)) {
return()
}
b.indx <- input$b.indx[1]:input$b.indx[2]
}
if (length(intersect(input$s.plot, c("bss")))) {
if (input$bs.fr == "B-spline") {
B <- fda::bsplineS(seq(0, 1, length.out = nrow(Ts)), breaks = seq(0, 1, length.out = input$xdf - input$xdeg + 1), norder = input$xdeg + 1)
} else {
B <- fda::fourier(seq(0, 1, length.out = nrow(Ts)), nbasis = input$xdf)
}
if ("bss" %in% input$s.plot) {
cB <- solve(t(B) %*% B) %*% t(B)
if (input$desc == "ts") {
S <- B %*% cB
vB <- ifelse(nrow(Ts) > ncol(B), sum((Ts - S %*% Ts)^2) / ((nrow(Ts) - ncol(B)) * ncol(Ts)) * diag(S), 0)
}
}
}
if ("bf" %in% input$s.plot || input$desc == "basis") {
if (input$bs.fr == "B-spline") {
Bs <- fda::bsplineS(seq(0, 1, length.out = 1000), breaks = seq(0, 1, length.out = input$xdf - input$xdeg + 1), norder = input$xdeg + 1)
} else {
Bs <- fda::fourier(seq(0, 1, length.out = 1000), nbasis = input$xdf)
}
Bs <- Bs * sd(Ts)
}
if (substr(input$desc, 1, 5) == "mfssa" || sum(c("mfssa", "fssa", "ssa") %in% input$s.plot) || substr(input$desc, 1, 3) == "ssa") {
sr <- run_ssa()
input.g <- eval(parse(text = paste0("list(", input$g, ")")))
mQ <- uQ <- Qs <- matrix(0, nrow = nrow(Ts), ncol = ncol(Ts))
isolate(sr$Qs <- reconstruct(sr$Us, groups = input.g))
if ("uf" %in% input$dmd.uf) {
isolate(sr$uQf <- freconstruct(sr$uUf[[var.which]], input.g))
uQf <- sr$uQf[[1]]
uQf@C[[1]][, ] <- 0
}
isolate(sr$mQf <- freconstruct(sr$mUf, input.g))
mQf <- uQf
for (i in input$sg[1]:input$sg[2]) {
Qs <- Qs + t(sr$Qs[[i]][, ((var.which - 1) * nrow(Ts) + 1):(var.which * nrow(Ts))])
if ("uf" %in% input$dmd.uf) {
uQf@C[[1]] <- uQf@C[[1]] + sr$uQf[[i]]@C[[1]]
}
mQf@C[[1]] <- mQf@C[[1]] + sr$mQf[[i]]@C[[var.which]]
}
if ("uf" %in% input$dmd.uf) uQ <- uQf@B[[1]] %*% uQf@C[[1]]
mQ <- mQf@B[[1]] %*% mQf@C[[1]]
}
if ("fpca" %in% input$s.plot || "dfpca" %in% input$s.plot) {
f.pca <- run_fpca()
fpca <- f.pca$fpca
dfpca <- f.pca$dfpca
}
if (substr(input$desc, 1, 5) == "mfssa") {
if (input$desc == "mfssa.scree") {
plot(sr$mUf, type = "values", d = input$d[2])
} else if (input$desc == "mfssa.wcor") {
mfwcor <- fwcor(sr$mUf, groups = input$d[1]:input$d[2])
wplot(W = mfwcor, cuts = 10)
}
else if (input$desc == "mfssa.pair") {
plot(sr$mUf, type = "paired", idx = input$d[1]:input$d[2])
} else if (input$desc == "mfssa.singV") {
plot(sr$mUf, type = "vectors", idx = input$d[1]:input$d[2])
} else if (input$desc == "mfssa.perGr") {
plot(sr$mUf, type = "periodogram", idx = input$d[1]:input$d[2])
} else if (input$desc == "mfssa.singF") {
plot(sr$mUf, type = ifelse(is.null(input$rec.type), "lheats", input$rec.type), var = var.which, idx = input$d[1]:input$d[2])
}
} else if (substr(input$desc, 1, 3) == "ssa") {
if (input$desc == "ssa.scree") {
plot(sr$Us, type = "values", numvalues = input$d[2])
} else if (input$desc == "ssa.wcor") {
plot(sr$Us, type = "wcor", groups = input$d[1]:input$d[2])
} else if (input$desc == "ssa.pair") {
plot(sr$Us, type = "paired", idx = input$d[1]:input$d[2])
} else if (input$desc == "ssa.vec") {
plot(sr$Us, type = "vectors", idx = input$d[1]:input$d[2])
} else if (input$desc == "ssa.funs") plot(sr$Us, type = "series", groups = input$d[1]:input$d[2])
} else if (input$desc == "gcv") {
res <- fda.gcv()
ind.m <- which(res$GCV == min(res$GCV))
plot(res$nbasis, res$GCV, type = "b", xlab = "n.basis", log = "y", ylab = "GCV", main = paste("Gen. Cross Validation -", fname), cex.lab = 1.5, pch = 20)
if (itmp()) {
updateSliderInput(session, "xdf", value = res$nbasis[ind.m])
itmp(0)
}
abline(v = input$xdf, col = 1, lty = 2)
} else {
m.lab <- paste(fname, "-", colnames(Ts)[indx])
if (input$as.choice == "all") {
indx <- 1:ncol(Ts)
m.lab <- fname
} else if (input$as.choice == "mult") {
indt <- 1:ncol(Ts) %% input$freq
indt[indt == 0] <- input$freq
indx <- (1:ncol(Ts))[which(indt == indx)]
}
if ("ts" %in% input$s.plot) {
clcol <- rep(1, ncol(Ts))
} else {
clcol <- rep(0, ncol(Ts))
}
if ("dbl" %in% input$dmd.uf) rng <- range(Ts, -Ts) else rng <- range(Ts)
ts.plot(Ts[, indx], col = clcol[indx], main = paste("Time Series -", m.lab, "-", name.Ts), ylab = "", ylim = rng, gpars = list(xaxt = "n"))
if ("ssa" %in% input$s.plot) {
for (i in indx) points(Qs[, i], type = "l", col = 5)
}
if ("fssa" %in% input$s.plot) {
for (i in indx) points(uQ[, i], type = "l", col = 7)
}
if ("mfssa" %in% input$s.plot) {
for (i in indx) points(mQ[, i], type = "l", col = 6)
}
if ("fpca" %in% input$s.plot) {
for (i in indx) points(fpca[, i], type = "l", col = 2, lty = 2)
}
if ("dfpca" %in% input$s.plot) {
for (i in indx) points(dfpca[, i], type = "l", col = 3, lty = 2)
}
if ("bss" %in% input$s.plot) {
f.est <- matrix(0, nrow = nrow(Ts), ncol = ncol(Ts))
for (i in indx) {
f.est[, i] <- as.matrix(B[, b.indx]) %*% (cB %*% Ts[, i])[b.indx]
if (input$as.choice == "single") {
if (input$s.CI) {
polygon(c(1:nrow(Ts), nrow(Ts):1), c(f.est[, i] - 2 * sqrt(vB), rev(f.est[, i]) + 2 * rev(sqrt(vB))), border = 4, lwd = 1, col = 5)
if ("ts" %in% input$s.plot) points(Ts[, i], type = "l", col = 1)
}
}
points(f.est[, i], col = 4, type = "l")
}
}
if ("tf" %in% input$s.plot) {
for (i in indx) points(iTrs()[[var.which]][, i], type = "l", col = 2)
}
if ("bf" %in% input$s.plot) {
for (i in b.indx) points(seq(1, nrow(Ts), length.out = 1000), Bs[, i], col = 8, type = "l", lty = 2)
}
axis(1, trunc(summary(1:nrow(Ts))[-4]))
if (input$f.choice == "sim" || input$comp.obs) {
if (input$comp.obs) Ys <- Ts else Ys <- iTrs()[[var.which]]
if (input$comp.obs) RMSEs <- NULL else RMSEs <- paste(" RMSE.obs =", round(sqrt(mean((Ts[, indx] - Ys[, indx])^2)), 4), "\n")
if ("bss" %in% input$s.plot) RMSEs <- paste(RMSEs, "RMSE.bs.smooth =", round(sqrt(mean((f.est[, indx] - Ys[, indx])^2)), 4), "\n")
if ("fpca" %in% input$s.plot) RMSEs <- paste(RMSEs, "RMSE.fpca =", round(sqrt(mean((fpca[, indx] - Ys[, indx])^2)), 4), "\n")
if ("ssa" %in% input$s.plot) RMSEs <- paste(RMSEs, "RMSE.ssa =", round(sqrt(mean((Qs[, indx] - Ys[, indx])^2)), 4), "\n")
if ("fssa" %in% input$s.plot) RMSEs <- paste(RMSEs, "RMSE.fssa =", round(sqrt(mean((uQ[, indx] - Ys[, indx])^2)), 4), "\n")
if ("mfssa" %in% input$s.plot) RMSEs <- paste(RMSEs, "RMSE.mfssa =", round(sqrt(mean((mQ[, indx] - Ys[, indx])^2)), 4), "\n")
if (input$comp.obs) RMSEs <- paste(RMSEs, "\n") else RMSEs <- paste(RMSEs, "\n Ang.obs =", round(max(acos(diag(t(scale(Ts[, indx], center = F)) %*% scale(Ys[, indx], center = F)) / (nrow(Ts) - 1)) * 180 / pi), 4), "\n")
if ("bss" %in% input$s.plot) RMSEs <- paste(RMSEs, "Ang.bs.smooth =", round(max(acos(diag(t(scale(f.est[, indx], center = F)) %*% scale(Ys[, indx], center = F)) / (nrow(Ts) - 1)) * 180 / pi), 4), "\n")
if ("fpca" %in% input$s.plot) RMSEs <- paste(RMSEs, "Ang.fpca =", round(max(acos(diag(t(scale(fpca[, indx], center = F)) %*% scale(Ys[, indx], center = F)) / (nrow(Ts) - 1)) * 180 / pi), 4), "\n")
if ("ssa" %in% input$s.plot) RMSEs <- paste(RMSEs, "Ang.ssa =", round(max(acos(diag(t(scale(Qs[, indx], center = F)) %*% scale(Ys[, indx], center = F)) / (nrow(Ts) - 1)) * 180 / pi), 4), "\n")
if ("fssa" %in% input$s.plot) RMSEs <- paste(RMSEs, "Ang.fssa =", round(max(acos(diag(t(scale(uQ[, indx], center = F)) %*% scale(Ys[, indx], center = F)) / (nrow(Ts) - 1)) * 180 / pi), 4), "\n")
if ("mfssa" %in% input$s.plot) RMSEs <- paste(RMSEs, "Ang.mfssa =", round(max(acos(diag(t(scale(mQ[, indx], center = F)) %*% scale(Ys[, indx], center = F)) / (nrow(Ts) - 1)) * 180 / pi), 4), "\n")
output$RMSEs <- renderText({
RMSEs
})
} else {
output$RMSEs <- renderText({
"Real Data"
})
}
}
})
output$res.ly <- renderPlotly({
if ((input$f.choice == "upload" && is.null(input$file)) || (input$f.choice == "sim" && !length(input$model))) {
return()
}
if (input$desc %in% c("mfssa.reconst", "ssa.reconst")) {
if (!input$rec.type %in% c("heatmap", "line", "3Dline", "3Dsurface")) {
return()
}
}
sr <- run_ssa()
input.g <- eval(parse(text = paste0("list(", input$g, ")")))
if (input$desc == "mfssa.reconst") {
isolate(sr$mQf <- freconstruct(sr$mUf, input.g))
mQf <- 0
if (input$var.which == "all" || is.null(input$var.which)) {
var.which <- NULL
types <- rep(input$rec.type, length(sr$mQf[[1]]@C))
vars <- 1:length(sr$mQf[[1]]@C)
} else {
var.which <- as.numeric(input$var.which)
types <- input$rec.type
vars <- var.which
}
for (i in input$sg[1]:input$sg[2]) {
mQf <- mQf + sr$mQf[[i]]
}
myplot <- plot(mQf, types = types, vars = vars)
} else {
if (is.null(input$var.which)) var.which <- 1 else var.which <- as.numeric(input$var.which)
isolate(sr$Qs <- reconstruct(sr$Us, groups = input.g))
Qs <- matrix(0, nrow = nrow(iTs()[[1]]), ncol = ncol(iTs()[[1]]))
for (i in input$sg[1]:input$sg[2]) {
Qs <- Qs + t(sr$Qs[[i]][, ((var.which - 1) * nrow(iTs()[[1]]) + 1):(var.which * nrow(iTs()[[1]]))])
}
Qs <- Rfssa::fts(X = list(Qs), B = list(eval.basis(sr$tau, sr$bas.fssa)), grid = list(sr$tau))
myplot <- plot(Qs, type = input$rec.type)
}
if (substr(input$rec.type, 1, 2) != "3D") print(myplot) else print(myplot[[1]])
})
output$fcast.horizon <- renderUI({
if (is.null(nrow(iTs()[[1]]))) {
return()
}
sliderInput("fcast.horizon", HTML("Forecasting Horizon:"), min = 0, max = ncol(iTs()[[1]]), value = min(50, ncol(iTs()[[1]]) / 2), step = 1, width = "250px")
})
output$run.fcast <- renderUI({
if (is.null(nrow(iTs()[[1]]))) {
return()
}
actionButton("run.fcast", paste("run Forecast"))
})
output$fcast.type <- renderUI({
if (is.null(input$run.fcast)) {
return()
}
selectInput("fcast.type", "Type", choices = c("Heat Plot" = "heatmap", "Regular Plot" = "line", "3D Plot (line)" = "3Dline", "3D Plot (surface)" = "3Dsurface"), width = "250px")
})
run_fcast <- eventReactive(input$run.fcast, {
withProgress(message = "MFSSA Forecast: Running", value = 0, {
sr <- run_ssa()
input.g <- eval(parse(text = paste0("list(", input$g, ")")))
fc <- list()
if ("recurrent" %in% input$fcast.method) fc$rec <- fforecast(U = sr$mUf, groups = input.g, h = input$fcast.horizon, method = "recurrent")
if ("vector" %in% input$fcast.method) fc$vector <- fforecast(U = sr$mUf, groups = input.g, h = input$fcast.horizon, method = "vector")
return(fc)
})
})
output$fcast.var <- renderUI({
if (is.null(input$run.fcast) || input$run.fcast == 0 || length(iTs()) == 1) {
return()
}
choic <- as.character(1:length(iTs()))
names(choic) <- names(iTs())
if (!is.null(input$fcast.type) && length(choic) != 1) if (input$fcast.type %in% c("heatmap", "line")) choic <- c("All Variables" = "all", choic)
selectInput("fcast.var", NULL, choices = choic, width = "125px")
})
output$fcast.select <- renderUI({
if (is.null(input$run.fcast) || input$run.fcast == 0) {
return()
}
if (length(input$fcast.method) > 1) selectInput("fcast.select", "Select Output", choices = c("Recurrent Forecasting" = "1", "Vector Forecasting" = "2"), width = "250px")
})
output$fcast.ly <- renderPlotly({
if (is.null(input$run.fcast)) {
return()
}
fc <- run_fcast()
mQf <- 0
if (length(fc) == 1) i <- 1 else i <- as.numeric(input$fcast.select)
if (input$fcast.var == "all" || is.null(input$fcast.var)) {
types <- rep(input$fcast.type, length(fc[[1]][[1]]@C))
vars <- 1:length(fc[[1]][[1]]@C)
} else {
types <- input$fcast.type
vars <- as.numeric(input$fcast.var)
}
for (j in input$sg[1]:input$sg[2]) {
mQf <- mQf + fc[[i]][[j]]
}
myplot <- plot(mQf, types = types, vars = vars)
if (substr(input$fcast.type, 1, 2) != "3D") print(myplot) else print(myplot[[1]])
})
} |
MVTMLEsymm2 <- function(X, nu = 1, eps = 1e-06, maxiter = 100)
{
.Call( "cMVTMLEsymm2", X, nu, eps, maxiter, PACKAGE = "fastM")
} |
predict.AccurateGLM <- function(object,
newx=NULL,
s=NULL,
type=c("link","response","coefficients","nonzero","class"),
exact=FALSE,
newoffset,
...) {
model <- object
type <- match.arg(type)
if (class(newx)[1] != "data.frame") newx <- data.frame(newx)
for (i in seq(dim(newx)[2])) {
var_info <- model@vars_info[[i]]
if (var_info$type == "quan") newx[, i] <- as.numeric(newx[, i])
else if (var_info$type == "qual") {
if (var_info$use_OD & !is.ordered(newx[, i])) newx[, i] <- ordered(newx[, i])
else if (!is.factor(newx[, i])) newx[, i] <- factor(newx[, i])
}
}
newx <- new("AGLM_Input", vars_info=model@vars_info, data=newx)
x_for_backend <- getDesignMatrix(newx)
backend_model <- model@backend_models[[1]]
model_name <- names(model@backend_models)[[1]]
if (model_name == "cv.glmnet") {
if (is.character(s)) {
if (s == "lambda.min")
s <- [email protected]
if (s == "lambda.1se")
s <- [email protected]
}
}
glmnet_result <- predict(backend_model,
x_for_backend,
s=s,
type=type,
exact=exact,
newoffset,
...)
return(glmnet_result)
} |
layerStats <- function(x, stat, w, asSample=TRUE, na.rm=FALSE, ...) {
stat <- tolower(stat)
stopifnot(stat %in% c('cov', 'weighted.cov', 'pearson'))
stopifnot(is.logical(asSample) & !is.na(asSample))
nl <- nlayers(x)
n <- ncell(x)
mat <- matrix(NA, nrow=nl, ncol=nl)
colnames(mat) <- rownames(mat) <- names(x)
pb <- pbCreate(nl^2, label='layerStats', ...)
if (stat == 'weighted.cov') {
if (missing(w)) {
stop('to compute weighted covariance a weights layer should be provided')
}
stopifnot( nlayers(w) == 1 )
if (na.rm) {
nas <- calc(x, function(i) sum(i)) * w
x <- mask(x, nas)
w <- mask(w, nas)
}
sumw <- cellStats(w, stat='sum', na.rm=na.rm)
means <- cellStats(x * w, stat='sum', na.rm=na.rm) / sumw
sumw <- sumw - asSample
x <- (x - means) * sqrt(w)
for(i in 1:nl) {
for(j in i:nl) {
r <- raster(x, layer=i) * raster(x,layer=j)
v <- cellStats(r, stat='sum', na.rm=na.rm) / sumw
mat[j,i] <- mat[i,j] <- v
pbStep(pb)
}
}
pbClose(pb)
cov.w <- list(mat, means)
names(cov.w) <- c("weigthed covariance", "weighted mean")
return(cov.w)
} else if (stat == 'cov') {
means <- cellStats(x, stat='mean', na.rm=na.rm)
x <- (x - means)
for(i in 1:nl) {
for(j in i:nl) {
r <- raster(x, layer=i) * raster(x, layer=j)
if (na.rm) {
v <- cellStats(r, stat='sum', na.rm=na.rm) / (n - cellStats(r, stat='countNA') - asSample)
} else {
v <- cellStats(r, stat='sum', na.rm=na.rm) / (n - asSample)
}
mat[j,i] <- mat[i,j] <- v
pbStep(pb)
}
}
pbClose(pb)
covar <- list(mat, means)
names(covar) <- c("covariance", "mean")
return(covar)
} else if (stat == 'pearson') {
means <- cellStats(x, stat='mean', na.rm=na.rm)
sds <- cellStats(x, stat='sd', na.rm=na.rm)
x <- (x - means)
for(i in 1:nl) {
for(j in i:nl) {
r <- raster(x, layer=i) * raster(x, layer=j)
if (na.rm) {
v <- cellStats(r, stat='sum', na.rm=na.rm) / ((n - cellStats(r, stat='countNA') - asSample) * sds[i] * sds[j])
} else {
v <- cellStats(r, stat='sum', na.rm=na.rm) / ((n - asSample) * sds[i] * sds[j])
}
mat[j,i] <- mat[i,j] <- v
pbStep(pb)
}
}
pbClose(pb)
covar <- list(mat, means)
names(covar) <- c("pearson correlation coefficient", "mean")
return(covar)
}
} |
generate_c_equations <- function(dat, rewrite) {
lapply(dat$equations, generate_c_equation, dat, rewrite)
}
generate_c_equation <- function(eq, dat, rewrite) {
f <- switch(
eq$type,
expression_scalar = generate_c_equation_scalar,
expression_inplace = generate_c_equation_inplace,
expression_array = generate_c_equation_array,
alloc = generate_c_equation_alloc,
alloc_interpolate = generate_c_equation_alloc_interpolate,
alloc_ring = generate_c_equation_alloc_ring,
copy = generate_c_equation_copy,
interpolate = generate_c_equation_interpolate,
user = generate_c_equation_user,
delay_index = generate_c_equation_delay_index,
delay_continuous = generate_c_equation_delay_continuous,
delay_discrete = generate_c_equation_delay_discrete,
stop("Unknown type"))
data_info <- dat$data$elements[[eq$lhs]]
stopifnot(!is.null(data_info))
f(eq, data_info, dat, rewrite)
}
generate_c_equation_scalar <- function(eq, data_info, dat, rewrite) {
location <- data_info$location
if (location == "transient") {
lhs <- sprintf("%s %s", data_info$storage_type, eq$lhs)
} else if (location == "internal") {
lhs <- rewrite(eq$lhs)
} else {
offset <- dat$data[[location]]$contents[[data_info$name]]$offset
storage <- if (location == "variable") dat$meta$result else dat$meta$output
lhs <- sprintf("%s[%s]", storage, rewrite(offset))
}
rhs <- rewrite(eq$rhs$value)
sprintf("%s = %s;", lhs, rhs)
}
generate_c_equation_inplace <- function(eq, data_info, dat, rewrite) {
location <- data_info$location
lhs <- rewrite(eq$lhs)
fn <- eq$rhs$value[[1]]
args <- lapply(eq$rhs$value[-1], rewrite)
switch(
fn,
rmultinom = generate_c_equation_inplace_rmultinom(eq, lhs, dat, rewrite),
rmhyper = generate_c_equation_inplace_rmhyper(
eq, lhs, data_info, dat, rewrite),
stop("unhandled array expression [odin bug]"))
}
generate_c_equation_inplace_rmultinom <- function(eq, lhs, dat, rewrite) {
args <- eq$rhs$value[-1]
len <- rewrite(dat$data$elements[[args[[2]]]]$dimnames$length)
stopifnot(!is.null(len))
sprintf_safe("Rf_rmultinom(%s, %s, %s, %s);",
rewrite(args[[1]]), rewrite(args[[2]]), len, lhs)
}
generate_c_equation_inplace_rmhyper <- function(eq, lhs, data_info, dat,
rewrite) {
len <- data_info$dimnames$length
n <- eq$rhs$value[[2]]
src <- eq$rhs$value[[3]]
src_type <- dat$data$elements[[src]]$storage_type
fn <- if (src_type == "int") "rmhyper_i" else "rmhyper_d"
sprintf_safe("%s(%s, %s, %s, %s);",
fn, rewrite(n), rewrite(src), rewrite(len), lhs)
}
generate_c_equation_array <- function(eq, data_info, dat, rewrite) {
lhs <- generate_c_equation_array_lhs(eq, data_info, dat, rewrite)
lapply(eq$rhs, function(x)
generate_c_equation_array_rhs(x$value, x$index, lhs, rewrite))
}
generate_c_equation_alloc <- function(eq, data_info, dat, rewrite) {
lhs <- rewrite(eq$lhs)
ctype <- data_info$storage_type
len <- rewrite(data_info$dimnames$length)
c(sprintf_safe("Free(%s);", lhs),
sprintf_safe("%s = (%s*) Calloc(%s, %s);", lhs, ctype, len, ctype))
}
generate_c_equation_alloc_interpolate <- function(eq, data_info, dat, rewrite) {
data_info_target <- dat$data$elements[[eq$interpolate$equation]]
data_info_t <- dat$data$elements[[eq$interpolate$t]]
data_info_y <- dat$data$elements[[eq$interpolate$y]]
len_t <- rewrite(data_info_t$dimnames$length)
lhs <- rewrite(eq$lhs)
if (data_info_target$rank == 0L) {
len_result <- rewrite(1L)
len_y <- rewrite(data_info_y$dimnames$length)
check <- sprintf_safe(
'interpolate_check_y(%s, %s, 0, "%s", "%s");',
len_t, len_y, data_info_y$name, eq$interpolate$equation)
} else {
len_result <- rewrite(data_info_target$dimnames$length)
rank <- data_info_target$rank
len_y <- vcapply(data_info_y$dimnames$dim, rewrite)
i <- seq_len(rank + 1)
if (rank == 1L) {
len_expected <- c(len_t, rewrite(data_info_target$dimnames$length))
} else {
len_expected <- c(
len_t,
vcapply(data_info_target$dimnames$dim[seq_len(rank)], rewrite))
}
check <- sprintf_safe(
'interpolate_check_y(%s, %s, %d, "%s", "%s");',
len_expected, len_y, seq_len(rank + 1), data_info_y$name,
eq$interpolate$equation)
}
rhs <- sprintf_safe(
'cinterpolate_alloc("%s", %s, %s, %s, %s, true, false)',
eq$interpolate$type, len_t, len_result, rewrite(eq$interpolate$t),
rewrite(eq$interpolate$y))
c(check,
sprintf_safe("cinterpolate_free(%s);", lhs),
sprintf_safe("%s = %s;", lhs, rhs))
}
generate_c_equation_interpolate <- function(eq, data_info, dat, rewrite) {
if (data_info$rank == 0L) {
lhs <- rewrite(eq$lhs)
ret <- sprintf_safe("cinterpolate_eval(%s, %s, &%s);",
dat$meta$time, rewrite(eq$interpolate),
rewrite(eq$lhs))
if (data_info$location == "transient") {
ret <- c(sprintf_safe("double %s = 0.0;", eq$lhs), ret)
}
} else {
ret <- sprintf_safe("cinterpolate_eval(%s, %s, %s);",
dat$meta$time, rewrite(eq$interpolate),
rewrite(eq$lhs))
}
ret
}
generate_c_equation_alloc_ring <- function(eq, data_info, dat, rewrite) {
data_info_contents <- dat$data$elements[[eq$delay]]
lhs <- rewrite(eq$lhs)
n_history <- DEFAULT_HISTORY_SIZE
if (data_info_contents$rank == 0L) {
len <- 1L
} else {
len <- rewrite(data_info_contents$dimnames$length)
}
c(sprintf_safe("if (%s) {", lhs),
sprintf_safe(" ring_buffer_destroy(%s);", lhs),
sprintf_safe("}"),
sprintf_safe("%s = ring_buffer_create(%s, %s * sizeof(double), %s);",
lhs, n_history, len, "OVERFLOW_OVERWRITE"))
}
generate_c_equation_copy <- function(eq, data_info, dat, rewrite) {
x <- dat$data$output$contents[[data_info$name]]
target <- c_variable_reference(x, data_info, "output", rewrite)
if (data_info$rank == 0L) {
sprintf_safe("%s = %s;", target, rewrite(eq$lhs))
} else {
len <- rewrite(data_info$dimnames$length)
lhs <- rewrite(eq$lhs)
if (data_info$storage_type == "double") {
sprintf_safe("memcpy(%s, %s, %s * sizeof(%s));",
target, lhs, len, data_info$storage_type)
} else {
offset <- rewrite(x$offset)
c(sprintf_safe("for (int i = 0; i < %s; ++i) {", len),
sprintf_safe(" output[%s + i] = %s[i];", offset, lhs),
sprintf_safe("}"))
}
}
}
generate_c_equation_user <- function(eq, data_info, dat, rewrite) {
user <- dat$meta$user
rank <- data_info$rank
lhs <- rewrite(eq$lhs)
storage_type <- data_info$storage_type
is_integer <- if (storage_type == "int") "true" else "false"
min <- rewrite(eq$user$min %||% "NA_REAL")
max <- rewrite(eq$user$max %||% "NA_REAL")
previous <- lhs
if (eq$user$dim) {
free <- sprintf_safe("Free(%s);", lhs)
len <- data_info$dimnames$length
if (rank == 1L) {
ret <-
sprintf_safe(
'%s = (%s*) user_get_array_dim(%s, %s, %s, "%s", %d, %s, %s, &%s);',
lhs, storage_type, user, is_integer, previous, eq$lhs, rank, min, max,
rewrite(len))
} else {
ret <- c(
sprintf_safe("int %s[%d];", len, rank + 1),
sprintf_safe(
'%s = (%s*) user_get_array_dim(%s, %s, %s, "%s", %d, %s, %s, %s);',
lhs, storage_type, user, is_integer, previous, eq$lhs, rank,
min, max, len),
sprintf_safe("%s = %s[%d];", rewrite(len), len, 0),
sprintf_safe("%s = %s[%d];",
vcapply(data_info$dimnames$dim, rewrite), len,
seq_len(rank)))
}
} else {
if (rank == 0L) {
ret <- sprintf_safe(
'%s = user_get_scalar_%s(%s, "%s", %s, %s, %s);',
lhs, data_info$storage_type, user, eq$lhs, lhs, min, max)
} else {
if (rank == 1L) {
dim <- rewrite(data_info$dimnames$length)
} else {
dim <- paste(vcapply(data_info$dimnames$dim, rewrite), collapse = ", ")
}
ret <- sprintf_safe(
'%s = (%s*) user_get_array(%s, %s, %s, "%s", %s, %s, %d, %s);',
lhs, storage_type, user, is_integer, previous, eq$lhs,
min, max, rank, dim)
}
}
ret
}
generate_c_equation_delay_index <- function(eq, data_info, dat, rewrite) {
delay <- dat$equations[[eq$delay]]$delay
lhs <- rewrite(eq$lhs)
state <- rewrite(delay$state)
alloc <- c(sprintf_safe("Free(%s);", lhs),
sprintf_safe("%s = Calloc(%s, int);",
lhs, rewrite(delay$variables$length)),
sprintf_safe("Free(%s);", state),
sprintf_safe("%s = Calloc(%s, double);",
state, rewrite(delay$variables$length)))
index1 <- function(v) {
d <- dat$data$elements[[v$name]]
offset <- dat$data$variable$contents[[v$name]]$offset
if (d$rank == 0L) {
sprintf_safe("%s[%s] = %s;", lhs, v$offset, offset)
} else {
loop <- sprintf_safe(
"for (int i = 0, j = %s; i < %s; ++i, ++j) {",
rewrite(offset), rewrite(d$dimnames$length))
c(loop,
sprintf_safe(" %s[%s + i] = j;", lhs, rewrite(v$offset)),
"}")
}
}
index <- c_flatten_eqs(lapply(delay$variables$contents, index1))
c(alloc, index)
}
generate_c_equation_delay_continuous <- function(eq, data_info, dat, rewrite) {
delay <- eq$delay
time <- dat$meta$time
time_true <- sprintf("%s_true", time)
initial_time <- rewrite(dat$meta$initial_time)
state <- rewrite(delay$state)
index <- rewrite(delay$index)
len <- rewrite(delay$variables$length)
if (is.recursive(delay$time)) {
dt <- rewrite(call("(", delay$time))
} else {
dt <- rewrite(delay$time)
}
time_set <- c(
sprintf_safe("const double %s = %s;", time_true, time),
sprintf_safe("const double %s = %s - %s;", time, time_true, dt))
lookup_vars <- sprintf_safe(
"lagvalue(%s, %s, %s, %s, %s);",
time, rewrite(dat$meta$c$use_dde), index, len, state)
unpack_vars <- c_flatten_eqs(lapply(
delay$variables$contents, c_unpack_variable2,
dat$data$elements, state, rewrite))
eqs_src <- ir_substitute(dat$equations[delay$equations], delay$substitutions)
eqs <- c_flatten_eqs(lapply(eqs_src, generate_c_equation, dat, rewrite))
unpack_initial1 <- function(x) {
d <- dat$data$elements[[x$name]]
sprintf_safe("%s = %s;", x$name, rewrite(x$initial))
}
decl1 <- function(x) {
d <- dat$data$elements[[x$name]]
fmt <- if (d$rank == 0L) "%s %s;" else "%s *%s;"
sprintf_safe(fmt, d$storage_type, x$name)
}
decl <- c_flatten_eqs(lapply(delay$variables$contents, decl1))
rhs_expr <- ir_substitute_sexpr(eq$rhs$value, delay$substitutions)
if (data_info$rank == 0L) {
lhs <- rewrite(eq$lhs)
expr <- sprintf_safe("%s = %s;", lhs, rewrite(rhs_expr))
} else {
lhs <- generate_c_equation_array_lhs(eq, data_info, dat, rewrite)
expr <- generate_c_equation_array_rhs(rhs_expr, eq$rhs$index, lhs, rewrite)
}
needs_variables <- length(delay$variables$contents) > 0L
if (is.null(delay$default)) {
if (needs_variables) {
unpack_initial <-
lapply(dat$data$variable$contents[names(delay$variables$contents)],
unpack_initial1)
unpack <- c(decl,
c_expr_if(
sprintf_safe("%s <= %s", time, initial_time),
c_flatten_eqs(unpack_initial),
c(lookup_vars, unpack_vars)))
} else {
unpack <- NULL
}
body <- c(time_set, unpack, eqs, expr)
} else {
if (data_info$rank == 0L) {
default <- sprintf_safe("%s = %s;", lhs, rewrite(delay$default))
} else {
default <- generate_c_equation_array_rhs(delay$default, eq$rhs$index,
lhs, rewrite)
}
if (needs_variables) {
unpack <- c(lookup_vars, unpack_vars)
} else {
unpack <- NULL
}
body <- c(time_set,
c_expr_if(
sprintf_safe("%s <= %s", time, initial_time),
default,
c(decl, unpack, eqs, expr)))
}
if (data_info$location == "transient") {
setup <- sprintf_safe("%s %s;", data_info$storage_type, eq$lhs)
} else {
setup <- NULL
}
header <- sprintf_safe("// delay block for %s", eq$name)
c(header, setup, "{", paste0(" ", body), "}")
}
generate_c_equation_delay_discrete <- function(eq, data_info, dat, rewrite) {
if (!is.null(eq$delay$default)) {
stop("Discrete delays with default not yet supported [odin bug]")
}
stopifnot(data_info$storage_type == "double")
head <- sprintf("%s_head", eq$delay$ring)
tail <- sprintf("%s_tail", eq$delay$ring)
ring <- rewrite(eq$delay$ring)
lhs <- rewrite(eq$lhs)
get_ring_head <- sprintf_safe(
"double * %s = (double*) ring_buffer_head(%s);",
head, ring)
if (data_info$rank == 0L) {
push <- sprintf("%s[0] = %s;", head, rewrite(eq$rhs$value))
} else {
data_info_ring <- data_info
data_info_ring$name <- head
lhs_ring <- generate_c_equation_array_lhs(eq, data_info_ring, dat, rewrite)
push <- generate_c_equation_array_rhs(eq$rhs$value, eq$rhs$index,
lhs_ring, rewrite)
}
advance <- sprintf_safe("ring_buffer_head_advance(%s);", ring)
time_check <- sprintf_safe(
"(int)%s - %s <= %s",
dat$meta$time, rewrite(eq$delay$time), rewrite(dat$meta$initial_time))
data_initial <- sprintf_safe(
"%s = (double*)ring_buffer_tail(%s);", tail, ring)
data_offset <- sprintf_safe(
"%s = (double*) ring_buffer_head_offset(%s, %s);",
tail, ring, rewrite(eq$delay$time))
if (data_info$rank == 0L) {
assign <- sprintf("double %s = %s[0];", lhs, tail)
} else {
assign <- sprintf("memcpy(%s, %s, %s * sizeof(double));",
lhs, tail, rewrite(data_info$dimnames$length))
}
c(get_ring_head,
push,
advance,
sprintf_safe("double * %s;", tail),
c_expr_if(time_check, data_initial, data_offset),
assign) -> ret
}
generate_c_equation_array_lhs <- function(eq, data_info, dat, rewrite) {
if (eq$type == "expression_array") {
index <- vcapply(eq$rhs[[1]]$index, "[[", "index")
} else {
index <- lapply(eq$rhs$index, "[[", "index")
}
location <- data_info$location
f <- function(i) {
if (i == 1) {
sprintf("%s - 1", index[[i]])
} else {
sprintf("%s * (%s - 1)",
rewrite(data_info$dimnames$mult[[i]]), index[[i]])
}
}
pos <- paste(vcapply(seq_along(index), f), collapse = " + ")
if (location == "internal") {
lhs <- sprintf("%s[%s]", rewrite(data_info$name), pos)
} else {
offset <- rewrite(dat$data[[location]]$contents[[data_info$name]]$offset)
storage <- if (location == "variable") dat$meta$result else dat$meta$output
lhs <- sprintf("%s[%s + %s]", storage, offset, pos)
}
lhs
}
generate_c_equation_array_rhs <- function(value, index, lhs, rewrite) {
ret <- sprintf("%s = %s;", lhs, rewrite(value))
seen_range <- FALSE
for (idx in rev(index)) {
if (idx$is_range) {
seen_range <- TRUE
loop <- sprintf_safe("for (int %s = %s; %s <= %s; ++%s) {",
idx$index, rewrite(idx$value[[2]]),
idx$index, rewrite(idx$value[[3]]),
idx$index)
ret <- c(loop, paste0(" ", ret), "}")
} else {
ret <- c(sprintf("int %s = %s;", idx$index, rewrite(idx$value)),
ret)
}
}
if (!seen_range || !index[[1]]$is_range) {
ret <- c("{", paste(" ", ret), "}")
}
ret
} |
context("labels")
test_that("can add a row labels to single horizontal heatmap",{
test_plot <- main_heatmap(a) %>% add_row_labels()
expect_iheatmap(test_plot, "row_labels_horizontal")
})
test_that("can add a row labels to single vertical heatmap",{
test_plot <- main_heatmap(a, orientation = "vertical") %>%
add_row_labels()
expect_iheatmap(test_plot, "row_labels_vertical", "vertical")
})
test_that("can add a column labels to single horizontal heatmap",{
test_plot <- main_heatmap(a) %>% add_col_labels()
expect_iheatmap(test_plot, "col_labels_horizontal")
})
test_that("can add a column labels to single vertical heatmap",{
test_plot <- main_heatmap(a, orientation = "vertical") %>%
add_col_labels()
expect_iheatmap(test_plot, "col_labels_vertical","vertical")
})
test_that("can add a row labels with custom ticktext of same length",{
test_plot <- main_heatmap(a) %>%
add_row_labels(ticktext = as.character(1:20 - 5))
expect_iheatmap(test_plot, "row_labels_custom_ticktext1_horizontal")
})
test_that("can add a row labels with custom ticktext selection",{
test_plot <- main_heatmap(a) %>%
add_row_labels(ticktext = c("1","5"))
expect_iheatmap(test_plot, "row_labels_custom_ticktext2_horizontal")
})
test_that("get errors on invalid ticktext for row labels",{
expect_error(main_heatmap(a) %>%
add_row_labels(ticktext = c("-1","5")))
expect_error(main_heatmap(a) %>%
add_row_labels(ticktext = 1:21))
})
test_that("can add a row labels with custom tickvals selection",{
test_plot <- main_heatmap(a) %>%
add_row_labels(ticktext = c(1,5))
expect_iheatmap(test_plot, "row_labels_custom_tickvals_horizontal")
})
test_that("get errors on invalid tickvals for row labels",{
expect_error(main_heatmap(a) %>%
add_row_labels(tickvals = c(-1,5)))
expect_error(main_heatmap(a) %>%
add_row_labels(tickvals = 1:21))
})
test_that("can add a row labels with custom tickvals and ticktext selection",{
test_plot <- main_heatmap(a) %>%
add_row_labels(tickvals = c(1,5), ticktext = c("A","B"))
expect_iheatmap(test_plot, "row_labels_custom_ticktext_tickvals_horizontal")
})
test_that("get errors on invalid tickvals and ticktext for row labels",{
expect_error(main_heatmap(a) %>%
add_row_labels(tickvals = c(1,5), ticktext = letters[1:3]))
})
test_that("can add a row labels to single horizontal heatmap",{
test_plot <- main_heatmap(a, y_categorical = TRUE) %>% add_row_labels()
expect_iheatmap(test_plot, "row_labels_continuous_horizontal")
})
test_that("can add a row labels to single vertical heatmap",{
test_plot <- main_heatmap(a, orientation = "vertical",
y_categorical = TRUE) %>%
add_row_labels()
expect_iheatmap(test_plot, "row_labels_continuous_vertical", "vertical")
})
test_that("can add a column labels to single horizontal heatmap",{
test_plot <- main_heatmap(a, x_categorical = TRUE) %>% add_col_labels()
expect_iheatmap(test_plot, "col_labels_continuous_horizontal")
})
test_that("can add a column labels to single vertical heatmap",{
test_plot <- main_heatmap(a, orientation = "vertical",
x_categorical = TRUE) %>%
add_col_labels()
expect_iheatmap(test_plot, "col_labels_continuous_vertical","vertical")
})
test_that("can add continuous row labels with custom ticktext of same length",{
test_plot <- main_heatmap(a, y_categorical = TRUE) %>%
add_row_labels(ticktext = as.character(1:20 - 5))
expect_iheatmap(test_plot, "row_labels_custom_ticktext1_horizontal")
})
test_that("can add continuous row labels with custom ticktext selection",{
test_plot <- main_heatmap(a, y_categorical = TRUE) %>%
add_row_labels(ticktext = c("1","5"))
expect_iheatmap(test_plot, "row_labels_custom_ticktext2_horizontal")
})
test_that("get errors on invalid ticktext for continuous row labels",{
expect_error(main_heatmap(a, y_categorical = TRUE) %>%
add_row_labels(ticktext = c("-1","5")))
expect_error(main_heatmap(a) %>%
add_row_labels(ticktext = 1:21))
})
test_that("can add continuous row labels with custom tickvals selection",{
test_plot <- main_heatmap(a, y_categorical = TRUE) %>%
add_row_labels(ticktext = c(1,5))
expect_iheatmap(test_plot, "row_labels_custom_tickvals_horizontal")
})
test_that("get errors on invalid tickvals for continuous row labels",{
expect_error(main_heatmap(a, y_categorical = TRUE) %>%
add_row_labels(tickvals = c(-1,5)))
expect_error(main_heatmap(a, y_categorical = TRUE) %>%
add_row_labels(tickvals = 1:21))
})
test_that("can add continuous row labels with custom tickvals and ticktext",{
test_plot <- main_heatmap(a, y_categorical = TRUE) %>%
add_row_labels(tickvals = c(1,5), ticktext = c("A","B"))
expect_iheatmap(test_plot, "row_labels_custom_ticktext_tickvals_horizontal")
})
test_that("get errors on bad tickvals and ticktext for continuous row labels",{
expect_error(main_heatmap(a, y_categorical = TRUE) %>%
add_row_labels(tickvals = c(1,5), ticktext = letters[1:3]))
}) |
tm_freq <- function(data,
token = "words",
stopwords = NULL,
keep = 100,
return = "plot"){
text_df <- suppressMessages(tm_clean(data = data,
token = token,
stopwords = stopwords))
text_count <-
text_df %>%
count(word, sort = TRUE) %>%
stats::na.omit() %>%
top_n(keep)
p <-
ggplot(text_count, aes(x=as.factor(word), y=n)) +
geom_bar(stat="identity", fill=alpha("skyblue", 0.7)) +
ylim(-100,max(text_count$n) + 10) +
theme_minimal() +
theme(
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
plot.margin = unit(rep(-1,4), "cm")
) +
coord_polar(start = 0) +
ggrepel::geom_text_repel(
data = text_count,
aes(x=word, y=n+10, label=word),
color = "black",
fontface = "bold",
alpha = 0.6,
size = 2.5,
inherit.aes = FALSE)
if(return == "table"){
text_count %>%
as_tibble() %>%
return()
} else if(return == "plot"){
return(p)
} else {
stop("Please enter a valid input for `return`.")
}
} |
GowerProximities<- function(x, y=NULL, Binary=NULL, Classes=NULL, transformation=3, IntegerAsOrdinal=FALSE, BinCoef= "Simple_Matching", ContCoef="Gower", NomCoef="GOW", OrdCoef="GOW") {
if (!is.data.frame(x)) stop("Main data is not organized as a data frame")
NewX=AdaptDataFrame(x, Binary=Binary, IntegerAsOrdinal=IntegerAsOrdinal)
if (is.null(y)) NewY=NewX
else{
if (!is.data.frame(y)) stop("Suplementary data is not organized as a data frame")
NewY=AdaptDataFrame(y, Binary=Binary, IntegerAsOrdinal=IntegerAsOrdinal)
}
n = dim(NewX$X)[1]
p = dim(NewX$X)[2]
n1 = dim(NewY$X)[1]
p1 = dim(NewY$X)[2]
if (!(p==p1)) stop("Number of columns of the two matrices are not the same")
transformations= c("Identity", "1-S", "sqrt(1-S)", "-log(s)", "1/S-1", "sqrt(2(1-S))", "1-(S+1)/2", "1-abs(S)", "1/(S+1)")
if (is.numeric(transformation)) transformation=transformations[transformation]
if (transformation==1) Type="similarity"
else Type="dissimilarity"
if ( (BinCoef== "Simple_Matching") & (ContCoef=="Gower") & (NomCoef=="GOW") & (OrdCoef=="GOW"))
coefficient="Gower Similarity"
else
paste("Binary: ",BinCoef, ", Continuous: ", ContCoef, ", Nominal: ", NomCoef, ", Ordinal: ", OrdCoef)
result= list()
result$TypeData="Mixed"
result$Type=Type
result$Coefficient=coefficient
result$Transformation=transformation
result$Data=NewX$X
result$SupData=NewY$X
result$Types=NewX$Types
result$Proximities=GowerSimilarities(NewX$X, y=NewY$X, transformation=transformation, Classes=NewX$Types, BinCoef= BinCoef, ContCoef=ContCoef, NomCoef=NomCoef, OrdCoef=OrdCoef)
rownames(result$Proximities)=rownames(x)
colnames(result$Proximities)=rownames(x)
result$SupProximities=NULL
if (!is.null(y)) result$SupProximities=GowerSimilarities(x,y, transformation)
class(result)="proximities"
return(result)
} |
sample.quantile<-function(x,tau){
if (!is.numeric(tau)|!is.vector(tau)|any(!is.finite(tau))){stop("The quantile order 'tau' must be a single number")}
if(sum((tau>=1)|(tau<=0))!=0) stop("The parameter 'tau' must be a single number or a vector between 0 and 1")
if (!is.numeric(x)|!is.vector(x)){stop("The sample 'x' must be a numeric vector")}
if(sum(is.na(x))!=0){x=x[-which(is.na(x))]; warning("Missing values have been removed from 'x'")}
if (any(!is.finite(x))){stop(" The sample 'x' must be a numeric vector")}
if(!length(x)>1){stop("'x' must be a sample of size bigger than one")}
x=sort(x)
quant=numeric(length(tau))
for(i in 1:length(tau)){
if((tau[i]<=0) | (tau[i]>=1)) stop("The parameter tau must be a vector of numbers between zero and one")
ord=tau[i]*length(x)
if(ord==as.integer(ord)){
quant[i]=(x[ord]+x[ord+1])/2
}else{
quant[i]=x[as.integer(ord)+1]
}
}
return(quant)
} |
hhg.example.datagen = function(n, example) {
if (example == '') {
} else if (example == '4indclouds') {
.datagen4indclouds(n)
} else if (example == '2Parabolas') {
.datagen2Parabolas(n)
} else if (example == 'W') {
.datagenW(n)
} else if (example == 'Parabola') {
.datagenParabola(n)
} else if (example == 'Diamond') {
.datagenDiamond(n)
} else if (example == 'Circle') {
.datagenCircle(n)
} else if (example == 'TwoClassUniv') {
.datagenTwoClassUniv(n)
} else if (example == 'FourClassUniv') {
.datagenFourClassUniv(n)
} else if (example == 'TwoClassMultiv') {
.datagenTwoClassMultiv(n)
} else {
stop('Unexpected example specified. Please consult the documentation.')
}
}
.datagen4indclouds = function(n) {
dx = rnorm(n) / 3
dy = rnorm(n) / 3
cx = sample(c(-1, 1), size = n, replace = T)
cy = sample(c(-1, 1), size = n, replace = T)
u = cx + dx
v = cy + dy
return (rbind(u, v))
}
.datagen2Parabolas = function(n) {
x = seq(-1, 1, length = n)
y = (x ^ 2 + runif(n) / 2) * (sample(c(-1, 1), size = n, replace = T))
return (rbind(x, y))
}
.datagenW = function(n) {
x = seq(-1, 1, length = n)
u = x + runif(n)/3
v = 4*( ( x^2 - 1/2 )^2 + runif(n)/500 )
return (rbind(u,v))
}
.datagenParabola = function(n) {
x = seq(-1, 1, length = n)
y = (x ^ 2 + runif(n)) / 2
return (rbind(x,y))
}
.datagenDiamond = function(n) {
x = runif(n, min = -1, max = 1)
y = runif(n, min = -1, max = 1)
theta = -pi / 4
rr = rbind(c(cos(theta), -sin(theta)),
c(sin(theta), cos(theta)))
tmp = cbind(x, y) %*% rr
u = tmp[,1]
v = tmp[,2]
return (rbind(u, v))
}
.datagenCircle = function(n) {
x = seq(-1, 1, length = n)
u = sin(x * pi) + rnorm(n) / 8
v = cos(x * pi) + rnorm(n) / 8
return (rbind(u, v))
}
.datagenTwoClassUniv = function(n) {
y = as.double(runif(n) < 0.5)
x = y * rnorm(n, mean = -0.2) + (1 - y) * rnorm(n, mean = 0.2)
return (list(x = x, y = y))
}
.datagenFourClassUniv = function(n) {
y = as.double(sample(x = 0:3, size = n, replace = T))
x = (y == 1) * rnorm(n, mean = -0.4) +
(y == 2) * rnorm(n, mean = -0.2) +
(y == 3) * rnorm(n, mean = 0.2) +
(y == 4) * rnorm(n, mean = 0.4)
return (list(x = x, y = y))
}
.datagenTwoClassMultiv = function(n) {
m = 10
x = matrix(as.double((runif(n * m) < 0.4) + (runif(n * m) < 0.4)), ncol = m)
y = as.double(xor(rowSums(x[, 1:5] > 0) > 2, rowSums(x[, 6:10] > 0) > 2))
return (list(x = x, y = y))
} |
source("helper-chromer.R")
context("Testing data processing and summary")
cp <- chrom_counts("Castilleja", "genus")
sum_res <- summarize_counts(cp)
parse_counts <- chromer:::parse_counts
get_counts_n <- chromer:::get_counts_n
test_that("Summary returns correct object", {
expect_that(sum_res, is_a("data.frame"))
expect_that(ncol(sum_res), equals(5))
coln <- c("resolved_binomial", "count_type", "count",
"inferred_n", "num_records")
expect_that(colnames(sum_res), equals(coln))
sp_cnt <- unique(cp$resolved_binomial)
sp_sum <- sum_res$resolved_binomial
expect_that(all(sp_sum %in% sp_cnt), is_true())
expect_that(all(is.numeric(sum_res$count)), is_true())
expect_that(all(is.numeric(sum_res$num_records)), is_true())
})
test_that("Only takes a chrom.counts object", {
tmp <- cp
attr(tmp, "class") <- "data.frame"
expect_that(summarize_counts(tmp), throws_error())
})
test_that("Parsing works properly", {
tmp <- c(1,2,3)
expect_that(parse_counts(as.character(tmp)), equals(tmp))
tmp2 <- c(0,1,2,3)
expect_that(parse_counts(as.character(tmp2)), equals(tmp))
tmp3 <- c(1, 2, "3-4", "c.5", "6/7")
expect_that(parse_counts(tmp3), equals(seq_len(7)))
}) |
is_valid_primary_key <- function(data, key, verbose = TRUE) {
is_valid <- identical(nrow(data), nrow(unique(data[key])))
if (isTRUE(verbose)) {
if (is_valid) {
message("[", paste(key, collapse = ", "), "]",
" is a valid primary key for ",
deparse(substitute(data)), ".")
} else {
warning("[", paste(key, collapse = ", "), "]",
" is not a valid primary key for `",
deparse(substitute(data)), "`!")
}
}
return(is_valid)
} |
context("Testing dual-host without structure")
test_that("Transmission is coherent with single introduction (host A) same for both hosts", {
skip_if_not_installed("igraph")
library(igraph)
t_incub_fct <- function(x){rnorm(x,mean = 5,sd=1)}
p_max_fct <- function(x){rbeta(x,shape1 = 5,shape2=2)}
p_Exit_fct <- function(t){return(0.08)}
proba <- function(t,p_max,t_incub){
if(t <= t_incub){p=0}
if(t >= t_incub){p=p_max}
return(p)
}
time_contact = function(t){round(rnorm(1, 3, 1), 0)}
set.seed(66)
test.nosoiA <- nosoiSim(type="dual", popStructure="none",
length.sim=40,
max.infected.A=100,
max.infected.B=100,
init.individuals.A=1,
init.individuals.B=0,
pExit.A = p_Exit_fct,
param.pExit.A = NA,
timeDep.pExit.A=FALSE,
nContact.A = time_contact,
param.nContact.A = NA,
timeDep.nContact.A=FALSE,
pTrans.A = proba,
param.pTrans.A = list(p_max=p_max_fct,
t_incub=t_incub_fct),
timeDep.pTrans.A=FALSE,
prefix.host.A="H",
pExit.B = p_Exit_fct,
param.pExit.B = NA,
timeDep.pExit.B=FALSE,
nContact.B = time_contact,
param.nContact.B = NA,
timeDep.nContact.B=FALSE,
pTrans.B = proba,
param.pTrans.B = list(p_max=p_max_fct,
t_incub=t_incub_fct),
timeDep.pTrans.B=FALSE,
prefix.host.B="V")
expect_output(print(test.nosoiA), "a dual host with no structure")
full.results.nosoi <- rbindlist(list(getHostData(test.nosoiA, "table.host", "A"),getHostData(test.nosoiA, "table.host", "B")))
g <- graph.data.frame(full.results.nosoi[inf.by != "NA-1",c(1,2)],directed=F)
expect_equal(transitivity(g, type="global"), 0)
expect_equal(clusters(g, "weak")$no, 1)
expect_equal(diameter(g, directed=F, weights=NA), 6)
expect_equal(all(grepl("H-", getHostData(test.nosoiA, "table.host", "A")$inf.by) == FALSE),TRUE)
expect_equal(all(grepl("V-", getHostData(test.nosoiA, "table.host", "A")[-1]$inf.by) == TRUE),TRUE)
expect_equal(all(grepl("V-", getHostData(test.nosoiA, "table.host", "B")$inf.by) == FALSE),TRUE)
expect_equal(all(grepl("H-", getHostData(test.nosoiA, "table.host", "B")[-1]$inf.by) == TRUE),TRUE)
expect_equal(test.nosoiA$total.time, 20)
expect_equal(getHostData(test.nosoiA, "N.infected", "A"), 126)
expect_equal(getHostData(test.nosoiA, "N.infected", "B"), 87)
expect_equal(test.nosoiA$type, "dual")
expect_equal(getHostData(test.nosoiA, "popStructure", "A"), "none")
expect_equal(getHostData(test.nosoiA, "popStructure", "B"), "none")
test <- summary(test.nosoiA)
expect_equal(test$R0$N.inactive.A, 20)
expect_equal(test$R0$N.inactive.B, 7)
expect_equal(test$R0$R0.hostA.mean, 0)
expect_equal(test$R0$R0.hostB.mean, 0.2857143)
expect_equal(test$dynamics[21]$t, 10)
expect_equal(test$dynamics[21]$Count, 1)
expect_equal(test$dynamics[21]$type, "H")
expect_equal(test$cumulative[26]$t, 12)
expect_equal(test$cumulative[26]$Count, 9)
expect_equal(test$cumulative[26]$type, "V")
expect_error(test.stateTable.A <- getTableState(test.nosoiA, pop="B"),
"There is no state information kept when the host population B has no structure.")
skip_if_not_installed("dplyr")
dynOld <- getDynamicOld(test.nosoiA)
dynNew <- getDynamic(test.nosoiA)
expect_equal(dynOld, dynNew)
r_0 <- getR0(test.nosoiA)
expect_equal(r_0$N.inactive.A,
ifelse(length(r_0$R0.hostA.dist) == 1 && is.na(r_0$R0.hostA.dist),
0, length(r_0$R0.hostA.dist)))
expect_equal(r_0$N.inactive.B,
ifelse(length(r_0$R0.hostB.dist) == 1 && is.na(r_0$R0.hostB.dist),
0, length(r_0$R0.hostB.dist)))
})
test_that("Transmission is coherent with single introduction (host A) differential according to host, shared parameter", {
skip_if_not_installed("igraph")
library(igraph)
t_infectA_fct <- function(x){rnorm(x,mean = 12,sd=3)}
pTrans_hostA <- function(t,t_infectA){
if(t/t_infectA <= 1){p=sin(pi*t/t_infectA)}
if(t/t_infectA > 1){p=0}
return(p)
}
p_Exit_fctA <- function(t,t_infectA){
if(t/t_infectA <= 1){p=0}
if(t/t_infectA > 1){p=1}
return(p)
}
time_contact_A = function(t){sample(c(0,1,2),1,prob=c(0.2,0.4,0.4))}
t_incub_fct_B <- function(x){rnorm(x,mean = 5,sd=1)}
p_max_fct_B <- function(x){rbeta(x,shape1 = 5,shape2=2)}
p_Exit_fct_B <- function(t){return(0.08)}
pTrans_hostB <- function(t,p_max,t_incub){
if(t <= t_incub){p=0}
if(t >= t_incub){p=p_max}
return(p)
}
time_contact_B = function(t){round(rnorm(1, 3, 1), 0)}
set.seed(150)
test.nosoiA <- nosoiSim(type="dual", popStructure="none",
length.sim=40,
max.infected.A=100,
max.infected.B=200,
init.individuals.A=1,
init.individuals.B=0,
pExit.A = p_Exit_fctA,
param.pExit.A = list(t_infectA = t_infectA_fct),
timeDep.pExit.A=FALSE,
nContact.A = time_contact_A,
param.nContact.A = NA,
timeDep.nContact.A=FALSE,
pTrans.A = pTrans_hostA,
param.pTrans.A = list(t_infectA=t_infectA_fct),
timeDep.pTrans.A=FALSE,
prefix.host.A="H",
pExit.B = p_Exit_fct_B,
param.pExit.B = NA,
timeDep.pExit.B=FALSE,
nContact.B = time_contact_B,
param.nContact.B = NA,
timeDep.nContact.B=FALSE,
pTrans.B = pTrans_hostB,
param.pTrans.B = list(p_max=p_max_fct_B,
t_incub=t_incub_fct_B),
timeDep.pTrans.B=FALSE,
prefix.host.B="V")
full.results.nosoi <- rbindlist(list(getHostData(test.nosoiA, "table.host", "A")[,c(1,2)],getHostData(test.nosoiA, "table.host", "B")[,c(1,2)]))
g <- graph.data.frame(full.results.nosoi[inf.by != "NA-1",c(1,2)],directed=F)
expect_equal(transitivity(g, type="global"), 0)
expect_equal(clusters(g, "weak")$no, 1)
expect_equal(diameter(g, directed=F, weights=NA), 10)
expect_equal(all(grepl("H-", getHostData(test.nosoiA, "table.host", "A")$inf.by) == FALSE),TRUE)
expect_equal(all(grepl("V-", getHostData(test.nosoiA, "table.host", "A")[-1]$inf.by) == TRUE),TRUE)
expect_equal(all(grepl("V-", getHostData(test.nosoiA, "table.host", "B")$inf.by) == FALSE),TRUE)
expect_equal(all(grepl("H-", getHostData(test.nosoiA, "table.host", "B")[-1]$inf.by) == TRUE),TRUE)
expect_equal(test.nosoiA$total.time, 17)
expect_equal(getHostData(test.nosoiA, "N.infected", "A"), 105)
expect_equal(getHostData(test.nosoiA, "N.infected", "B"), 226)
expect_equal(colnames(getHostData(test.nosoiA, "table.host", "A"))[6],"t_infectA")
skip_if_not_installed("dplyr")
dynOld <- getDynamicOld(test.nosoiA)
dynNew <- getDynamic(test.nosoiA)
expect_equal(dynOld, dynNew)
r_0 <- getR0(test.nosoiA)
expect_equal(r_0$N.inactive.A,
ifelse(length(r_0$R0.hostA.dist) == 1 && is.na(r_0$R0.hostA.dist),
0, length(r_0$R0.hostA.dist)))
expect_equal(r_0$N.inactive.B,
ifelse(length(r_0$R0.hostB.dist) == 1 && is.na(r_0$R0.hostB.dist),
0, length(r_0$R0.hostB.dist)))
})
test_that("Transmission is coherent with single introduction (host A) differential according to host, shared parameter, time dependancy for host B pExit", {
skip_if_not_installed("igraph")
library(igraph)
t_infectA_fct <- function(x){rnorm(x,mean = 12,sd=3)}
pTrans_hostA <- function(t,t_infectA){
if(t/t_infectA <= 1){p=sin(pi*t/t_infectA)}
if(t/t_infectA > 1){p=0}
return(p)
}
p_Exit_fctA <- function(t,t_infectA){
if(t/t_infectA <= 1){p=0}
if(t/t_infectA > 1){p=1}
return(p)
}
time_contact_A = function(t){sample(c(0,1,2),1,prob=c(0.2,0.4,0.4))}
t_incub_fct_B <- function(x){rnorm(x,mean = 5,sd=1)}
p_max_fct_B <- function(x){rbeta(x,shape1 = 5,shape2=2)}
p_Exit_fct_B <- function(t,prestime){(sin(prestime/12)+1)/5}
pTrans_hostB <- function(t,p_max,t_incub){
if(t <= t_incub){p=0}
if(t >= t_incub){p=p_max}
return(p)
}
time_contact_B = function(t){round(rnorm(1, 3, 1), 0)}
set.seed(90)
test.nosoiA <- nosoiSim(type="dual", popStructure="none",
length.sim=40,
max.infected.A=100,
max.infected.B=200,
init.individuals.A=1,
init.individuals.B=0,
pExit.A = p_Exit_fctA,
param.pExit.A = list(t_infectA = t_infectA_fct),
timeDep.pExit.A=FALSE,
nContact.A = time_contact_A,
param.nContact.A = NA,
timeDep.nContact.A=FALSE,
pTrans.A = pTrans_hostA,
param.pTrans.A = list(t_infectA=t_infectA_fct),
timeDep.pTrans.A=FALSE,
prefix.host.A="H",
pExit.B = p_Exit_fct_B,
param.pExit.B = NA,
timeDep.pExit.B=TRUE,
nContact.B = time_contact_B,
param.nContact.B = NA,
timeDep.nContact.B=FALSE,
pTrans.B = pTrans_hostB,
param.pTrans.B = list(p_max=p_max_fct_B,
t_incub=t_incub_fct_B),
timeDep.pTrans.B=FALSE,
prefix.host.B="V")
full.results.nosoi <- rbindlist(list(getHostData(test.nosoiA, "table.host", "A")[,c(1,2)],getHostData(test.nosoiA, "table.host", "B")[,c(1,2)]))
g <- graph.data.frame(full.results.nosoi[inf.by != "NA-1",c(1,2)],directed=F)
expect_equal(transitivity(g, type="global"), 0)
expect_equal(clusters(g, "weak")$no, 1)
expect_equal(diameter(g, directed=F, weights=NA), 12)
expect_equal(all(grepl("H-", getHostData(test.nosoiA, "table.host", "A")$inf.by) == FALSE),TRUE)
expect_equal(all(grepl("V-", getHostData(test.nosoiA, "table.host", "A")[-1]$inf.by) == TRUE),TRUE)
expect_equal(all(grepl("V-", getHostData(test.nosoiA, "table.host", "B")$inf.by) == FALSE),TRUE)
expect_equal(all(grepl("H-", getHostData(test.nosoiA, "table.host", "B")[-1]$inf.by) == TRUE),TRUE)
expect_equal(test.nosoiA$total.time, 39)
expect_equal(getHostData(test.nosoiA, "N.infected", "A"), 71)
expect_equal(getHostData(test.nosoiA, "N.infected", "B"), 221)
skip_if_not_installed("dplyr")
dynOld <- getDynamicOld(test.nosoiA)
dynNew <- getDynamic(test.nosoiA)
expect_equal(dynOld, dynNew)
r_0 <- getR0(test.nosoiA)
expect_equal(r_0$N.inactive.A,
ifelse(length(r_0$R0.hostA.dist) == 1 && is.na(r_0$R0.hostA.dist),
0, length(r_0$R0.hostA.dist)))
expect_equal(r_0$N.inactive.B,
ifelse(length(r_0$R0.hostB.dist) == 1 && is.na(r_0$R0.hostB.dist),
0, length(r_0$R0.hostB.dist)))
})
test_that("Epidemic dying out", {
skip_if_not_installed("igraph")
library(igraph)
t_incub_fct <- function(x){rnorm(x,mean = 5,sd=1)}
p_max_fct <- function(x){rbeta(x,shape1 = 5,shape2=2)}
p_Exit_fct <- function(t){return(0.08)}
proba <- function(t,p_max,t_incub){
if(t <= t_incub){p=0}
if(t >= t_incub){p=p_max}
return(p)
}
time_contact = function(t){round(rnorm(1, 3, 1), 0)}
set.seed(2)
test.nosoiA <- nosoiSim(type="dual", popStructure="none",
length.sim=40,
max.infected.A=100,
max.infected.B=100,
init.individuals.A=1,
init.individuals.B=0,
pExit.A = p_Exit_fct,
param.pExit.A = NA,
timeDep.pExit.A=FALSE,
nContact.A = time_contact,
param.nContact.A = NA,
timeDep.nContact.A=FALSE,
pTrans.A = proba,
param.pTrans.A = list(p_max=p_max_fct,
t_incub=t_incub_fct),
timeDep.pTrans.A=FALSE,
prefix.host.A="H",
pExit.B = p_Exit_fct,
param.pExit.B = NA,
timeDep.pExit.B=FALSE,
nContact.B = time_contact,
param.nContact.B = NA,
timeDep.nContact.B=FALSE,
pTrans.B = proba,
param.pTrans.B = list(p_max=p_max_fct,
t_incub=t_incub_fct),
timeDep.pTrans.B=FALSE,
prefix.host.B="V")
expect_equal(all(grepl("H-", getHostData(test.nosoiA, "table.host", "A")$inf.by) == FALSE),TRUE)
expect_equal(all(grepl("V-", getHostData(test.nosoiA, "table.host", "A")[-1]$inf.by) == TRUE),TRUE)
expect_equal(test.nosoiA$total.time, 5)
expect_equal(getHostData(test.nosoiA, "N.infected", "A"), 1)
expect_equal(getHostData(test.nosoiA, "N.infected", "B"), 0)
expect_equal(test.nosoiA$type, "dual")
expect_equal(getHostData(test.nosoiA, "popStructure", "A"), "none")
expect_equal(getHostData(test.nosoiA, "popStructure", "B"), "none")
skip_if_not_installed("dplyr")
dynOld <- getDynamicOld(test.nosoiA)
dynNew <- getDynamic(test.nosoiA)
expect_equal(dynOld, dynNew)
r_0 <- getR0(test.nosoiA)
expect_equal(r_0$N.inactive.A,
ifelse(length(r_0$R0.hostA.dist) == 1 && is.na(r_0$R0.hostA.dist),
0, length(r_0$R0.hostA.dist)))
expect_equal(r_0$N.inactive.B,
ifelse(length(r_0$R0.hostB.dist) == 1 && is.na(r_0$R0.hostB.dist),
0, length(r_0$R0.hostB.dist)))
}) |
add_best_levels <- function(d, longsheet, id, groups, outcome, n_levels = 100,
min_obs = 1, positive_class = "Y", cohesion_weight = 2,
levels = NULL, fill, fun = sum, missing_fill = NA) {
id <- rlang::enquo(id)
groups <- rlang::enquo(groups)
outcome <- rlang::enquo(outcome)
fill <- rlang::enquo(fill)
add_as_empty <- character()
if (is.null(levels)) {
to_add <- get_best_levels(d, longsheet, !!id, !!groups, !!outcome,
n_levels, min_obs, positive_class)
add_as_empty <- character()
} else {
levels_name <- paste0(rlang::quo_name(groups), "_levels")
if (is.model_list(levels) || is.data.frame(levels)) {
levels <- attr(levels, "best_levels")[[levels_name]]
if (is.null(levels))
stop("Looked for ", levels_name, " as an attribute of ",
match.call()$levels, " but it was NULL.")
} else if (is.list(levels)) {
levels <- levels[[levels_name]]
} else if (!is.character(levels)) {
stop("You passed a ", class(levels), " to levels. It should be a data frame ",
"returned from add_best_levels, a model_list trained on such a data frame ",
"the 'best_levels' attribute from such a data frame, or a character ",
"vector of levels to use.")
}
present_levels <- unique(dplyr::pull(longsheet, !!groups))
to_add <- levels[levels %in% present_levels]
add_as_empty <- levels[!levels %in% present_levels]
}
if (purrr::is_empty(to_add)) {
simplified_id <-
d %>%
dplyr::select(!!id)
empty_col_names <- paste0(quo_name(eval(groups)), "_", add_as_empty)
class(missing_fill) <- class(d[[rlang::quo_name(fill)]])
pivoted <-
matrix(missing_fill,
nrow = length(simplified_id), ncol = length(empty_col_names),
dimnames = list(NULL, empty_col_names)) %>%
tibble::as_tibble() %>%
bind_cols(simplified_id, .)
} else {
longsheet <- dplyr::filter(longsheet, (!!groups) %in% to_add)
pivot_args <- list(
d = longsheet,
grain = eval(id),
spread = eval(groups),
fun = fun,
missing_fill = missing_fill
)
if (!missing(fill))
pivot_args$fill <- eval(fill)
if (length(add_as_empty))
pivot_args$extra_cols <- add_as_empty
pivoted <- do.call(pivot, pivot_args)
}
pivoted <-
pivoted %>%
dplyr::left_join(d, ., by = rlang::quo_name(id))
new_cols <- setdiff(names(pivoted), names(d))
if (!is.na(missing_fill)) {
pivoted[new_cols][is.na(pivoted[new_cols])] <- missing_fill
}
attr(pivoted, "best_levels") <-
c(attr(d, "best_levels"),
setNames(list(dplyr::union(to_add, add_as_empty)), paste0(rlang::quo_name(groups), "_levels")))
return(pivoted)
}
get_best_levels <- function(d, longsheet, id, groups, outcome, n_levels = 100,
min_obs = 1, positive_class = "Y",
cohesion_weight = 2) {
id <- rlang::enquo(id)
groups <- rlang::enquo(groups)
outcome <- rlang::enquo(outcome)
missing_check(d, outcome)
if (!is.numeric(n_levels) || !is.numeric(min_obs))
stop("n_levels and min_obs should both be integers")
id_ft <- dplyr::count(d, !!id) %>% dplyr::filter(n > 1)
if (nrow(id_ft))
stop("d can have only one row per observation. The following ID(s) had more ",
"than one observation: ", list_variables(dplyr::pull(id_ft, !!id)))
if (isTRUE(all.equal(d, longsheet))) {
longsheet <- longsheet %>% select_not(outcome)
d <- select_not(d, groups)
}
tomodel <-
longsheet %>%
dplyr::distinct(!!id, !!groups) %>%
dplyr::filter(!is.na(!!groups)) %>%
dplyr::inner_join(d, ., by = rlang::quo_name(id)) %>%
group_by(!!groups) %>%
filter(n_distinct(!!sym(quo_name(id))) >= min_obs) %>%
ungroup()
if (!nrow(tomodel)) {
warning("No levels present in at least ", min_obs, " observations")
return(character())
}
if (is.numeric(dplyr::pull(tomodel, !!outcome))) {
tomodel <-
tomodel %>%
mutate(!!rlang::quo_name(outcome) := !!outcome - mean(!!outcome)) %>%
group_by(!!groups) %>%
summarize(mean_ssd = mean(!!outcome) / sqrt(stats::var(!!outcome) / n())) %>%
arrange(desc(abs(mean_ssd)))
tozip <-
split(tomodel, sign(tomodel$mean_ssd)) %>%
purrr::map(~ pull(.x, !!groups))
} else {
total_observations <- n_distinct(dplyr::pull(tomodel, !!id))
levs <-
tomodel %>%
group_by(!!groups) %>%
summarize(fraction_positive = mean(!!outcome == positive_class),
fraction_positive = dplyr::case_when(
fraction_positive == 1 ~ 1 - (.5 / total_observations),
fraction_positive == 0 ~ .5 / total_observations,
TRUE ~ fraction_positive),
present_in = ifelse(n_distinct(rlang::quo_name(id)) == total_observations,
total_observations - .5, n_distinct(rlang::quo_name(id))),
log_dist_from_in_all = -log(present_in / total_observations)) %>%
dplyr::select(-present_in)
median_positive <- stats::median(levs$fraction_positive)
levs <-
levs %>%
mutate(predictor_of = as.integer(fraction_positive > stats::median(fraction_positive)),
log_loss = - (predictor_of * log(fraction_positive) + (1 - predictor_of) * log(1 - fraction_positive)),
badness = log_loss ^ cohesion_weight * log_dist_from_in_all) %>%
arrange(badness)
tozip <-
split(levs, levs$predictor_of) %>%
purrr::map(~ pull(.x, !!groups))
}
out <-
if (length(tozip) == 1) {
tozip[[1]]
} else {
zip_vectors(tozip[[1]], tozip[[2]])
}
if (length(out) > n_levels)
out <- out[seq_len(n_levels)]
return(out)
}
zip_vectors <- function(v1, v2) {
ll <- list(v1, v2)
lengths <- purrr::map_int(ll, length)
zipped <-
lapply(seq_len(min(lengths)), function(i) {
c(ll[[1]][i], ll[[2]][i])
}) %>%
unlist()
if (length(unique(lengths)) > 1)
zipped <- c(zipped, ll[[which.max(lengths)]][(min(lengths) + 1):max(lengths)])
return(zipped)
} |
geo_address_lookup_sf <- function(osm_ids,
type = c("N", "W", "R"),
full_results = FALSE,
return_addresses = TRUE,
verbose = FALSE,
custom_query = list(),
points_only = TRUE) {
api <- "https://nominatim.openstreetmap.org/lookup?"
nodes <- paste0(type, osm_ids, collapse = ",")
url <- paste0(api, "osm_ids=", nodes, "&format=geojson")
if (!isTRUE(points_only)) {
url <- paste0(url, "&polygon_geojson=1")
}
if (full_results) {
url <- paste0(url, "&addressdetails=1")
}
if (length(custom_query) > 0) {
opts <- NULL
for (i in seq_len(length(custom_query))) {
nlist <- names(custom_query)[i]
val <- paste0(custom_query[[i]], collapse = ",")
opts <- paste0(opts, "&", nlist, "=", val)
}
url <- paste0(url, "&", opts)
}
json <- tempfile(fileext = ".geojson")
res <- api_call(url, json, quiet = isFALSE(verbose))
if (isFALSE(res)) {
message(url, " not reachable.")
result_out <- data.frame(query = paste0(type, osm_ids))
return(invisible(result_out))
}
sfobj <- sf::st_read(json,
stringsAsFactors = FALSE,
quiet = isFALSE(verbose)
)
if (length(names(sfobj)) == 1) {
message("No results for query ", nodes)
result_out <- data.frame(query = paste0(type, osm_ids))
return(invisible(result_out))
}
result_out <- data.frame(query = paste0(type, osm_ids))
df_sf <- tibble::as_tibble(sf::st_drop_geometry(sfobj))
names(df_sf) <-
gsub("address", "osm.address", names(df_sf))
names(df_sf) <- gsub("display_name", "address", names(df_sf))
if (return_addresses || full_results) {
disp_name <- df_sf["address"]
result_out <- cbind(result_out, disp_name)
}
if (full_results) {
rest_cols <- df_sf[, !names(df_sf) %in% "address"]
result_out <- cbind(result_out, rest_cols)
}
result_out <- sf::st_sf(result_out, geometry = sf::st_geometry(sfobj))
return(result_out)
} |
FindDistm <- function(x, normalize = FALSE, method = 'euclidean'){
if(!inherits(x, 'data.frame') && !inherits(x, 'matrix')) stop('arg x must be data frame or matrix')
if(nrow(x) == 0) stop('x is empty. Cannot calculate distance matrix.')
if(!inherits(normalize, 'logical')) stop('arg normalize must be boolean')
if(normalize){
sds <- apply(x, 2, stats::sd)
distm <- stats::dist(scale(x, center = FALSE, scale = sds), method = method, upper = TRUE)
}else{
distm <- stats::dist(x, upper = TRUE, method = method)
}
return(distm)
} |
SNPtm <-
function(trange,tsl,x6,r6,...) UseMethod("SNPtm") |
loglikedw3<-function(par,x)
{
sum(-log(ddweibull3(x,par[1],par[2])))
} |
BEMM.1PLG=function(data,
PriorBeta=c(0,4),
PriorGamma=c(-1.39,0.25),
InitialBeta=NA,
InitialGamma=NA,
Tol=0.0001,
max.ECycle=2000L,
max.MCycle=100L,
n.decimal=3L,
n.Quadpts =31L,
Theta.lim=c(-6,6),
Missing=-9,
ParConstraint=FALSE,
BiasSE=FALSE){
Time.Begin=Sys.time()
Model='1PLG'
D=1
Check.results=Input.Checking(Model=Model, data=data, PriorBeta=PriorBeta, PriorGamma=PriorGamma,
InitialBeta=InitialBeta, InitialGamma=InitialGamma, Tol=Tol,
max.ECycle=max.ECycle, max.MCycle=max.MCycle, n.Quadpts =n.Quadpts, n.decimal=n.decimal,
Theta.lim=Theta.lim, Missing=Missing, ParConstraint=ParConstraint, BiasSE=BiasSE)
data=Check.results$data
data.simple=Check.results$data.simple
CountNum=Check.results$CountNum
I=Check.results$I
J=Check.results$J
n.class=Check.results$n.class
PriorBeta=Check.results$PriorBeta
PriorGamma=Check.results$PriorGamma
Prior=list(PriorBeta=PriorBeta, PriorGamma=PriorGamma)
InitialBeta=Check.results$InitialBeta
InitialGamma=Check.results$InitialGamma
max.ECycle=Check.results$max.ECycle
max.MCycle=Check.results$max.MCycle
n.Quadpts=Check.results$n.Quadpts
n.decimal=Check.results$n.decimal
ParConstraint=Check.results$ParConstraint
BiasSE=Check.results$BiasSE
Par.est0=list(Beta=InitialBeta, Gamma=InitialGamma)
Par.SE0=list(SEBeta=InitialBeta*0, SEGamma=InitialGamma*0)
np=J*2
Est.results=BEMM.1PLG.est(Model=Model, data=data, data.simple=data.simple, CountNum=CountNum, n.class=n.class,
Prior=Prior, Par.est0=Par.est0, Par.SE0=Par.SE0, D=D, np,
Tol=Tol, max.ECycle=max.ECycle, max.MCycle=max.MCycle, n.Quadpts =n.Quadpts, n.decimal=n.decimal,
Theta.lim=Theta.lim, Missing=Missing, ParConstraint=ParConstraint, BiasSE=BiasSE, I=I, J=J, Time.Begin=Time.Begin)
if (Est.results$StopNormal==1){
message('PROCEDURE TERMINATED NORMALLY')
}else{
message('PROCEDURE TERMINATED WITH ISSUES')
}
message('IRTEMM version: 1.0.7')
message('Item Parameter Calibration for the 1PL-G Model.','\n')
message('Quadrature: ', n.Quadpts, ' nodes from ', Theta.lim[1], ' to ', Theta.lim[2], ' were used to approximate Gaussian distribution.')
message('Method for Items: Ability-based Bayesian Expectation-Maximization-Maximization (BEMM) Algorithm.')
if (BiasSE){
message('Method for Item SEs: directly estimating SEs from inversed Hession matrix.')
warning('Warning: The SEs maybe not trustworthy!', sep = '')
}else{
message('Method for Item SEs: Updated SEM algorithm.')
}
message('Method for Theta: Expected A Posteriori (EAP).')
if (Est.results$StopNormal==1){
message('Converged at LL-Change < ', round(Est.results$cr, 6), ' after ', Est.results$Iteration, ' EMM iterations.', sep = '')
}else{
warning('Warning: Estimation cannot converged under current max.ECycle and Tol!', sep = '')
warning('Warning: The reults maybe not trustworthy!', sep = '')
message('Terminated at LL-Change = ', round(Est.results$cr, 6), ' after ', Est.results$Iteration, ' EMM iterations.', sep = '')
}
message('Running time:', Est.results$Elapsed.time, '\n')
message('Log-likelihood (LL):', as.character(round(Est.results$Loglikelihood, n.decimal)))
message('Estimated Parameters:', as.character(np))
message('AIB: ', round(Est.results$fits.test$AIC, n.decimal), ', BIC: ', round(Est.results$fits.test$BIC, n.decimal), ', RMSEA = ', round(Est.results$fits.test$RMSEA, n.decimal))
message('G2 (', round(Est.results$fits.test$G2.df, n.decimal), ') = ', round(Est.results$fits.test$G2, n.decimal), ', p = ', round(Est.results$fits.test$G2.P, n.decimal), ', G2/df = ', round(Est.results$fits.test$G2.ratio, n.decimal), sep='')
return(Est.results)
}
BEMM.1PLG.est=function(Model=Model, data=data, data.simple=data.simple, CountNum=CountNum, n.class=n.class,
Prior=Prior, Par.est0=Par.est0, Par.SE0=Par.SE0, D=D, np,
Tol=Tol, max.ECycle=max.ECycle, max.MCycle=max.MCycle, n.Quadpts =n.Quadpts, n.decimal=n.decimal,
Theta.lim=Theta.lim, Missing=Missing, ParConstraint=ParConstraint, BiasSE=BiasSE, I=I, J=J, Time.Begin=Time.Begin){
node.Quadpts=seq(Theta.lim[1],Theta.lim[2],length.out = n.Quadpts)
weight.Quadpts=dnorm(node.Quadpts,0,1)
weight.Quadpts=weight.Quadpts/sum(weight.Quadpts)
InitialValues=Par.est0
LH=rep(0,max.ECycle)
IBeta=rep(0,J)
IGamma=rep(0,J)
TBeta=matrix(0,max.ECycle,J)
TGamma=matrix(0,max.ECycle,J)
deltahat.Beta=rep(0,J)
deltahat.Gamma=rep(0,J)
n.ECycle=1L
StopNormal=0L
E.exit=0L
LLinfo=LikelihoodInfo(data.simple, CountNum, Model, Par.est0, n.Quadpts, node.Quadpts, weight.Quadpts, D)
LH0=LLinfo$LH
f=LLinfo$f
r=LLinfo$r
fz=LLinfo$fz
rz=LLinfo$rz
while(E.exit==0L && (n.ECycle <= max.ECycle)){
for (j in 1:J){
gt0 = Par.est0$Gamma[j]
bt0 = Par.est0$Beta[j]
n.MCycle = 1
M.exit = 0L
while (M.exit==0L && (n.MCycle <= max.MCycle)){
pstar = 1 / (1 + exp(-(node.Quadpts - bt0)))
ag = 1 / (1 + exp(-(gt0)))
lg1 = sum(r[j,] - rz[j,] - (f - fz[j,]) * ag)
lgg = sum(-(f - fz[j,]) * ag * (1 - ag))
lb1 = sum(-(rz[j,] - f * pstar))
lbb = sum(-(f * pstar * (1 - pstar)))
if (Prior$PriorBeta[j]!=-9 && Prior$PriorBeta[j + J]!=-9) {
lb1 = lb1 -((bt0-Prior$PriorBeta[j])/Prior$PriorBeta[j + J])
lbb = lbb -1/Prior$PriorBeta[j + J]
}
Ibb = - 1 / lbb
bt1 = bt0 + (Ibb * lb1)
if (abs(bt1-bt0) >= 0.01){
bt0 = bt1
}
if (Prior$PriorGamma[j]!=-9 && Prior$PriorGamma[j + J]!=-9) {
lg1 = lg1 -((gt0-Prior$PriorGamma[j])/Prior$PriorGamma[j + J])
lgg = lgg -1/Prior$PriorGamma[j + J]
}
Igg = - 1 / lgg
gt1 = gt0 + (Igg * lg1)
if (abs(gt1-gt0) >= 0.01){
gt0 = gt1
}
if (abs(bt1-bt0) < 0.01 && abs(gt1-gt0) < 0.01){
bt0 = bt1
gt0 = gt1
M.exit = 1L
} else{
bt0 = bt1
gt0 = gt1
n.MCycle = n.MCycle+1
}
}
if (is.finite(gt0) && is.finite(bt0)){
if (ParConstraint){
if (bt0>=-6 && bt0<=6){
Par.est0$Beta[j] = bt0
TBeta[n.ECycle,j] = bt0
IBeta[j] = Ibb
}
if (gt0>=-7 && gt0<=0){
Par.est0$Gamma[j] = gt0
TGamma[n.ECycle,j] = gt0
IGamma[j] = Igg
}
}else{
Par.est0$Beta[j] = bt0
Par.est0$Gamma[j] = gt0
TBeta[n.ECycle,j] = bt0
TGamma[n.ECycle,j] = gt0
IBeta[j] = Ibb
IGamma[j] = Igg
}
}else{
if (n.ECycle!=1){
TBeta[n.ECycle,j] = TBeta[n.ECycle-1,j]
TGamma[n.ECycle,j] = TGamma[n.ECycle-1,j]
}else{
TBeta[n.ECycle,j] = Par.est0$Beta[j]
TGamma[n.ECycle,j] = Par.est0$Gamma[j]
}
}
}
LLinfo=LikelihoodInfo(data.simple, CountNum, Model, Par.est0, n.Quadpts, node.Quadpts, weight.Quadpts, D)
LH[n.ECycle]=LLinfo$LH
f=LLinfo$f
r=LLinfo$r
fz=LLinfo$fz
rz=LLinfo$rz
cr=LH[n.ECycle]-LH0
LH0=LH[n.ECycle]
if (abs(cr)<Tol){
n.ECycle = n.ECycle + 1
E.exit=1
StopNormal=1L
}else{
n.ECycle = n.ECycle + 1
}
}
n.ECycle = n.ECycle - 1
if (BiasSE==FALSE){
start.SEM=0
end.SEM=n.ECycle
delta=rep(0,2)
delta0=rep(0,2)
delta1=rep(0,2)
cr.SEM0=1
cr.SEM1=1
cr.SEM2=1
for (i in 1:(n.ECycle-1)){
deltatemp=exp(-(LH[i+1]-LH[i]))
if (deltatemp>=0.9 && deltatemp<=0.999){
if (cr.SEM0==0){
end.SEM=i
}else{
start.SEM=i
cr.SEM0=0
}
}
}
Time.Mid=Sys.time()
message(paste('Estimating SEs via USEM algorithm (Requires about ',as.character(round(difftime(Time.Mid, Time.Begin, units="mins"), 2)), ' mins).', sep=''),'\n')
for (j in 1:J){
z=start.SEM
SEM.exit=0
cr.SEM1=1
cr.SEM2=1
while (SEM.exit==0 && z<=end.SEM){
for (ParClass in 1:2){
if (ParClass==1 && z>=2 && cr.SEM1<sqrt(Tol)){
next
}
if (ParClass==2 && z>=2 && cr.SEM2<sqrt(Tol)){
next
}
deltahat=Par.est0
if (ParClass==1){deltahat$Beta[j]=TBeta[z,j]}
if (ParClass==2){deltahat$Gamma[j]=TGamma[z,j]}
LLinfo=LikelihoodInfo(data.simple, CountNum, Model, deltahat, n.Quadpts, node.Quadpts, weight.Quadpts, D)
f=LLinfo$f
r=LLinfo$r
fz=LLinfo$fz
rz=LLinfo$rz
bt0 = deltahat$Beta[j]
gt0 = deltahat$Gamma[j]
n.MCycle = 1
M.exit = 0
while (M.exit==0 && (n.MCycle <= max.MCycle)) {
if (ParClass==1){
pstar = 1 / (1 + exp(-(node.Quadpts - bt0)))
lb1 = sum(-(rz[j,] - f * pstar))
lbb = sum(-(f * pstar * (1 - pstar)))
if (Prior$PriorBeta[j]!=-9 && Prior$PriorBeta[j + J]!=-9) {
lb1 = lb1 -((bt0-Prior$PriorBeta[j])/Prior$PriorBeta[j + J])
lbb = lbb -1/Prior$PriorBeta[j + J]
}
Ibb = - 1 / lbb
bt1 = bt0 + (Ibb * lb1)
if (abs(bt1-bt0) < 0.01){
bt0 = bt1
M.exit = 1
} else{
bt0 = bt1
n.MCycle = n.MCycle + 1
}
}
if (ParClass==2){
ag = 1 / (1 + exp(-(gt0)))
lg1 = sum(r[j,] - rz[j,] - (f - fz[j,]) * ag)
lgg = sum(-(f - fz[j,]) * ag * (1 - ag))
if (Prior$PriorGamma[j]!=-9 && Prior$PriorGamma[j + J]!=-9) {
lg1 = lg1 -((gt0-Prior$PriorGamma[j])/Prior$PriorGamma[j + J])
lgg = lgg -1/Prior$PriorGamma[j + J]
}
Igg = - 1 / lgg
gt1 = gt0 + (Igg * lg1)
if (abs(gt1-gt0) < 0.01){
gt0 = gt1
M.exit =1
} else{
gt0 = gt1
n.MCycle = n.MCycle + 1
}
}
}
if (is.finite(gt0) && is.finite(bt0)){
if (ParConstraint){
if (bt0>=-6 && bt0<=6){
deltahat$Beta[j] = bt0
}
if (gt0>=-7 && gt0<=0){
deltahat$Gamma[j] = gt0
}
}else{
deltahat$Beta[j] = bt0
deltahat$Gamma[j] = gt0
}
}
if (ParClass==1){
delta1[1]=(deltahat$Beta[j]-Par.est0$Beta[j])/(TBeta[z,j]-Par.est0$Beta[j]+0.0001)
break
}
if (ParClass==2){
delta1[2]=(deltahat$Gamma[j]-Par.est0$Gamma[j])/(TGamma[z,j]-Par.est0$Gamma[j]+0.0001)
break
}
}
cr_SEM1=abs(delta1[1]-delta0[1]);
cr_SEM2=abs(delta1[2]-delta0[2]);
if (cr.SEM1<sqrt(Tol) && cr.SEM2<sqrt(Tol) && z>=2){
SEM.exit=1
}else{
z=z+1
}
delta0[is.finite(delta1)] = delta1[is.finite(delta1)]
}
delta[1]=1-delta0[1];
delta[2]=1-delta0[2];
delta1[1] = 1 / delta[1];
delta1[2] = 1 / delta[2];
if (is.finite(delta1[1])==F || delta1[1]<=0){delta1[1] = 1}
if (is.finite(delta1[2])==F || delta1[2]<=0){delta1[2] = 0}
Par.SE0$SEBeta[j]= sqrt(IBeta[j] * delta1[1])
Par.SE0$SEGamma[j]= sqrt(IGamma[j] * delta1[2])
if (is.finite(Par.SE0$SEBeta[j])){if (Par.SE0$SEBeta[j]>1){Par.SE0$SEBeta[j]= sqrt(IBeta[j])}}
if (is.finite(Par.SE0$SEGamma[j])){if (Par.SE0$SEGamma[j]>1){Par.SE0$SEGamma[j]= sqrt(IGamma[j])}}
}
}else{
message('Directly estimating SEs from inversed Hession matrix.', '\n')
for (j in 1:J){
Par.SE0$SEBeta[j]= sqrt(IBeta[j])
Par.SE0$SEGamma[j]= sqrt(IGamma[j])
}
}
Par.est0$Beta=round(Par.est0$Beta, n.decimal)
Par.est0$Gamma=round(Par.est0$Gamma, n.decimal)
Par.SE0$SEBeta=round(Par.SE0$SEBeta, n.decimal)
Par.SE0$SEGamma=round(Par.SE0$SEGamma, n.decimal)
EM.Map=list(Map.Beta=TBeta[1:n.ECycle,], Map.Gamma=TGamma[1:n.ECycle,])
Est.ItemPars=as.data.frame(list(est.beta=Par.est0$Beta, est.gamma=Par.est0$Gamma, se.beta=Par.SE0$SEBeta, se.gamma=Par.SE0$SEGamma))
P.Quadpts=lapply(as.list(node.Quadpts), Prob.model, Model=Model, Par.est0=Par.est0, D=D)
Joint.prob=mapply('*',lapply(P.Quadpts, function(P,data){apply(data*P+(1-data)*(1-P),2,prod,na.rm = T)}, data=t(data)),
as.list(weight.Quadpts), SIMPLIFY = FALSE)
Whole.prob=Reduce("+", Joint.prob)
LogL=sum(log(Whole.prob))
Posterior.prob=lapply(Joint.prob, '/', Whole.prob)
EAP.JP=simplify2array(Joint.prob)
EAP.Theta=rowSums(matrix(1,I,1)%*%node.Quadpts*EAP.JP)/rowSums(EAP.JP)
EAP.WP=EAP.JP*simplify2array(lapply(as.list(node.Quadpts), function(node.Quadpts, Est.Theta){(node.Quadpts-Est.Theta)^2}, Est.Theta=EAP.Theta))
hauteur=node.Quadpts[2:n.Quadpts]-node.Quadpts[1:(n.Quadpts-1)]
base.JP=colSums(t((EAP.JP[,1:(n.Quadpts-1)]+EAP.JP[,2:n.Quadpts])/2)*hauteur)
base.WP=colSums(t((EAP.WP[,1:(n.Quadpts-1)]+EAP.WP[,2:n.Quadpts])/2)*hauteur)
EAP.Theta.SE=sqrt(base.WP/base.JP)
Est.Theta=as.data.frame(list(Theta=EAP.Theta, Theta.SE=EAP.Theta.SE))
N2loglike=-2*LogL
AIC=2*np+N2loglike
BIC=N2loglike+log(I)*np
Theta.uni=sort(unique(EAP.Theta))
Theta.uni.len=length(Theta.uni)
G2=NA
df=NA
G2.P=NA
G2.ratio=NA
G2.size=NA
RMSEA=NA
if (Theta.uni.len>=11){
n.group=10
cutpoint=rep(NA,n.group)
cutpoint[1]=min(Theta.uni)-0.001
cutpoint[11]=max(Theta.uni)+0.001
for (i in 2:n.group){
cutpoint[i]=Theta.uni[(i-1)*Theta.uni.len/n.group]
}
Index=cut(EAP.Theta, cutpoint, labels = FALSE)
}
if (Theta.uni.len>=3 & Theta.uni.len<11){
n.group=Theta.uni.len-1
cutpoint=rep(NA,n.group)
cutpoint[1]=min(Theta.uni)-0.001
cutpoint[n.group]=max(Theta.uni)+0.001
if (Theta.uni.len>=4){
for (i in 2:(Theta.uni.len-2)){
cutpoint[i]=Theta.uni[i]
}
}
Index=cut(EAP.Theta, cutpoint, labels = FALSE)
}
if (Theta.uni.len>=3){
X2.item=matrix(NA, n.group, J)
G2.item=matrix(NA, n.group, J)
Index.Uni=unique(Index)
for (k in 1:n.group){
data.group=data[Index==Index.Uni[k],]
Theta.group=EAP.Theta[Index==Index.Uni[k]]
Obs.P=colMeans(data.group)
Exp.P=Reduce('+',lapply(Theta.group, Prob.model, Model=Model, Par.est0=Par.est0, D=D))/nrow(data.group)
Obs.P[Obs.P>=1]=0.9999
Obs.P[Obs.P<=0]=0.0001
Exp.P[Exp.P>=1]=0.9999
Exp.P[Exp.P<=0]=0.0001
X2.item[k,]=nrow(data.group)*(Obs.P-Exp.P)^2/(Exp.P*(1-Exp.P))
Odds1=log(Obs.P/Exp.P)
Odds2=log((1-Obs.P)/(1-Exp.P))
G2.item[k,]=nrow(data.group)*(Obs.P*Odds1+(1-Obs.P)*Odds2)
}
X2=sum(colSums(X2.item, na.rm = T))
G2=sum(2*colSums(G2.item, na.rm = T))
df=J*(n.group-3)
G2.P=1-pchisq(G2,df)
G2.ratio=G2/df
RMSEA=sqrt(((X2-df)/(nrow(data)-1))/X2)
}else{
warning('The frequence table is too small to do fit tests.')
}
fits.test=list(G2=G2, G2.df=df, G2.P=G2.P, G2.ratio=G2.ratio, RMSEA=RMSEA, AIC=AIC, BIC=BIC)
Time.End=Sys.time()
Elapsed.time=paste('Elapsed time:', as.character(round(difftime(Time.End, Time.Begin, units="mins"), digits = 4)), 'mins')
return(list(Est.ItemPars=Est.ItemPars, Est.Theta=Est.Theta, Loglikelihood=LogL, Iteration=n.ECycle, EM.Map=EM.Map,
fits.test=fits.test, Elapsed.time=Elapsed.time, StopNormal=StopNormal, InitialValues=InitialValues, cr=cr))
} |
context("Guides")
skip_on_cran()
test_that("colourbar trains without labels", {
g <- guide_colorbar()
sc <- scale_colour_continuous(limits = c(0, 4), labels = NULL)
out <- guide_train(g, sc)
expect_equal(names(out$key), c("colour", ".value"))
})
test_that("Colorbar respects show.legend in layer", {
df <- data_frame(x = 1:3, y = 1)
p <- ggplot(df, aes(x = x, y = y, color = x)) +
geom_point(size = 20, shape = 21, show.legend = FALSE)
expect_false("guide-box" %in% ggplotGrob(p)$layout$name)
p <- ggplot(df, aes(x = x, y = y, color = x)) +
geom_point(size = 20, shape = 21, show.legend = TRUE)
expect_true("guide-box" %in% ggplotGrob(p)$layout$name)
})
test_that("show.legend handles named vectors", {
n_legends <- function(p) {
g <- ggplotGrob(p)
gb <- which(g$layout$name == "guide-box")
if (length(gb) > 0) {
n <- length(g$grobs[[gb]]) - 1
} else {
n <- 0
}
n
}
df <- data_frame(x = 1:3, y = 20:22)
p <- ggplot(df, aes(x = x, y = y, color = x, shape = factor(y))) +
geom_point(size = 20)
expect_equal(n_legends(p), 2)
p <- ggplot(df, aes(x = x, y = y, color = x, shape = factor(y))) +
geom_point(size = 20, show.legend = c(color = FALSE))
expect_equal(n_legends(p), 1)
p <- ggplot(df, aes(x = x, y = y, color = x, shape = factor(y))) +
geom_point(size = 20, show.legend = c(color = FALSE, shape = FALSE))
expect_equal(n_legends(p), 0)
p <- ggplot(df, aes(x = x, y = y, color = x, shape = factor(y))) +
geom_point(size = 20, show.legend = c(shape = FALSE, color = TRUE))
expect_equal(n_legends(p), 1)
})
test_that("axis_label_overlap_priority always returns the correct number of elements", {
expect_identical(axis_label_priority(0), numeric(0))
expect_setequal(axis_label_priority(1), seq_len(1))
expect_setequal(axis_label_priority(5), seq_len(5))
expect_setequal(axis_label_priority(10), seq_len(10))
expect_setequal(axis_label_priority(100), seq_len(100))
})
test_that("axis_label_element_overrides errors when angles are outside the range [0, 90]", {
expect_is(axis_label_element_overrides("bottom", 0), "element")
expect_error(axis_label_element_overrides("bottom", 91), "`angle` must")
expect_error(axis_label_element_overrides("bottom", -91), "`angle` must")
})
test_that("a warning is generated when guides are drawn at a location that doesn't make sense", {
plot <- ggplot(mpg, aes(class, hwy)) +
geom_point() +
scale_y_continuous(guide = guide_axis(position = "top"))
built <- expect_silent(ggplot_build(plot))
expect_warning(ggplot_gtable(built), "Position guide is perpendicular")
})
test_that("a warning is not generated when a guide is specified with duplicate breaks", {
plot <- ggplot(mpg, aes(class, hwy)) +
geom_point() +
scale_y_continuous(breaks = c(20, 20))
built <- expect_silent(ggplot_build(plot))
expect_silent(ggplot_gtable(built))
})
test_that("a warning is generated when more than one position guide is drawn at a location", {
plot <- ggplot(mpg, aes(class, hwy)) +
geom_point() +
guides(
y = guide_axis(position = "left"),
y.sec = guide_axis(position = "left")
)
built <- expect_silent(ggplot_build(plot))
expect_warning(ggplot_gtable(built), "Discarding guide")
})
test_that("a warning is not generated when properly changing the position of a guide_axis()", {
plot <- ggplot(mpg, aes(class, hwy)) +
geom_point() +
guides(
y = guide_axis(position = "right")
)
built <- expect_silent(ggplot_build(plot))
expect_silent(ggplot_gtable(built))
})
test_that("guide_none() can be used in non-position scales", {
p <- ggplot(mpg, aes(cty, hwy, colour = class)) +
geom_point() +
scale_color_discrete(guide = guide_none())
built <- ggplot_build(p)
plot <- built$plot
guides <- build_guides(
plot$scales,
plot$layers,
plot$mapping,
"right",
theme_gray(),
plot$guides,
plot$labels
)
expect_identical(guides, zeroGrob())
})
test_that("Using non-position guides for position scales results in an informative error", {
p <- ggplot(mpg, aes(cty, hwy)) +
geom_point() +
scale_x_continuous(guide = guide_legend())
built <- ggplot_build(p)
expect_error(ggplot_gtable(built), "does not implement guide_transform()")
})
test_that("guide merging for guide_legend() works as expected", {
merge_test_guides <- function(scale1, scale2) {
scale1$guide <- guide_legend(direction = "vertical")
scale2$guide <- guide_legend(direction = "vertical")
scales <- scales_list()
scales$add(scale1)
scales$add(scale2)
guide_list <- guides_train(scales, theme = theme_gray(), labels = labs(), guides = guides())
guides_merge(guide_list)
}
different_limits <- merge_test_guides(
scale_colour_discrete(limits = c("a", "b", "c", "d")),
scale_linetype_discrete(limits = c("a", "b", "c"))
)
expect_length(different_limits, 2)
same_limits <- merge_test_guides(
scale_colour_discrete(limits = c("a", "b", "c")),
scale_linetype_discrete(limits = c("a", "b", "c"))
)
expect_length(same_limits, 1)
expect_equal(same_limits[[1]]$key$.label, c("a", "b", "c"))
same_labels_different_limits <- merge_test_guides(
scale_colour_discrete(limits = c("a", "b", "c")),
scale_linetype_discrete(limits = c("one", "two", "three"), labels = c("a", "b", "c"))
)
expect_length(same_labels_different_limits, 1)
expect_equal(same_labels_different_limits[[1]]$key$.label, c("a", "b", "c"))
same_labels_different_scale <- merge_test_guides(
scale_colour_continuous(limits = c(0, 4), breaks = 1:3, labels = c("a", "b", "c")),
scale_linetype_discrete(limits = c("a", "b", "c"))
)
expect_length(same_labels_different_scale, 1)
expect_equal(same_labels_different_scale[[1]]$key$.label, c("a", "b", "c"))
repeated_identical_labels <- merge_test_guides(
scale_colour_discrete(limits = c("one", "two", "three"), labels = c("label1", "label1", "label2")),
scale_linetype_discrete(limits = c("1", "2", "3"), labels = c("label1", "label1", "label2"))
)
expect_length(repeated_identical_labels, 1)
expect_equal(repeated_identical_labels[[1]]$key$.label, c("label1", "label1", "label2"))
})
test_that("axis guides are drawn correctly", {
theme_test_axis <- theme_test() + theme(axis.line = element_line(size = 0.5))
test_draw_axis <- function(n_breaks = 3,
break_positions = seq_len(n_breaks) / (n_breaks + 1),
labels = as.character,
positions = c("top", "right", "bottom", "left"),
theme = theme_test_axis,
...) {
break_labels <- labels(seq_along(break_positions))
axes <- lapply(positions, function(position) {
draw_axis(break_positions, break_labels, axis_position = position, theme = theme, ...)
})
axes_grob <- gTree(children = do.call(gList, axes))
gt <- gtable(
widths = unit(c(0.05, 0.9, 0.05), "npc"),
heights = unit(c(0.05, 0.9, 0.05), "npc")
)
gt <- gtable_add_grob(gt, list(axes_grob), 2, 2, clip = "off")
plot(gt)
}
expect_doppelganger("axis guides basic", function() test_draw_axis())
expect_doppelganger("axis guides, zero breaks", function() test_draw_axis(n_breaks = 0))
expect_doppelganger(
"axis guides, check overlap",
function() test_draw_axis(20, labels = function(b) comma(b * 1e9), check.overlap = TRUE)
)
expect_doppelganger(
"axis guides, zero rotation",
function() test_draw_axis(10, labels = function(b) comma(b * 1e3), angle = 0)
)
expect_doppelganger(
"axis guides, positive rotation",
function() test_draw_axis(10, labels = function(b) comma(b * 1e3), angle = 45)
)
expect_doppelganger(
"axis guides, negative rotation",
function() test_draw_axis(10, labels = function(b) comma(b * 1e3), angle = -45)
)
expect_doppelganger(
"axis guides, vertical rotation",
function() test_draw_axis(10, labels = function(b) comma(b * 1e3), angle = 90)
)
expect_doppelganger(
"axis guides, vertical negative rotation",
function() test_draw_axis(10, labels = function(b) comma(b * 1e3), angle = -90)
)
expect_doppelganger(
"axis guides, text dodged into rows/cols",
function() test_draw_axis(10, labels = function(b) comma(b * 1e9), n.dodge = 2)
)
})
test_that("axis guides are drawn correctly in plots", {
expect_doppelganger("align facet labels, facets horizontal",
qplot(hwy, reorder(model, hwy), data = mpg) +
facet_grid(manufacturer ~ ., scales = "free", space = "free") +
theme_test() +
theme(strip.text.y = element_text(angle = 0))
)
expect_doppelganger("align facet labels, facets vertical",
qplot(reorder(model, hwy), hwy, data = mpg) +
facet_grid(. ~ manufacturer, scales = "free", space = "free") +
theme_test() +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
)
expect_doppelganger("thick axis lines",
qplot(wt, mpg, data = mtcars) +
theme_test() +
theme(axis.line = element_line(size = 5, lineend = "square"))
)
})
test_that("axis guides can be customized", {
plot <- ggplot(mpg, aes(class, hwy)) +
geom_point() +
scale_y_continuous(
sec.axis = dup_axis(guide = guide_axis(n.dodge = 2)),
guide = guide_axis(n.dodge = 2)
) +
scale_x_discrete(guide = guide_axis(n.dodge = 2))
expect_doppelganger("guide_axis() customization", plot)
})
test_that("guides can be specified in guides()", {
plot <- ggplot(mpg, aes(class, hwy)) +
geom_point() +
guides(
x = guide_axis(n.dodge = 2),
y = guide_axis(n.dodge = 2),
x.sec = guide_axis(n.dodge = 2),
y.sec = guide_axis(n.dodge = 2)
)
expect_doppelganger("guides specified in guides()", plot)
})
test_that("guides have the final say in x and y", {
df <- data_frame(x = 1, y = 1)
plot <- ggplot(df, aes(x, y)) +
geom_point() +
guides(
x = guide_none(title = "x (primary)"),
y = guide_none(title = "y (primary)"),
x.sec = guide_none(title = "x (secondary)"),
y.sec = guide_none(title = "y (secondary)")
)
expect_doppelganger("position guide titles", plot)
})
test_that("guides are positioned correctly", {
df <- data_frame(x = 1, y = 1, z = factor("a"))
p1 <- ggplot(df, aes(x, y, colour = z)) +
geom_point() +
labs(title = "title of plot") +
theme_test() +
theme(
axis.text.x = element_text(angle = 90, vjust = 0.5),
legend.background = element_rect(fill = "grey90"),
legend.key = element_rect(fill = "grey90")
) +
scale_x_continuous(breaks = 1, labels = "very long axis label") +
scale_y_continuous(breaks = 1, labels = "very long axis label")
expect_doppelganger("legend on left",
p1 + theme(legend.position = "left")
)
expect_doppelganger("legend on bottom",
p1 + theme(legend.position = "bottom")
)
expect_doppelganger("legend on right",
p1 + theme(legend.position = "right")
)
expect_doppelganger("legend on top",
p1 + theme(legend.position = "top")
)
expect_doppelganger("facet_grid, legend on left",
p1 + facet_grid(x~y) + theme(legend.position = "left")
)
expect_doppelganger("facet_grid, legend on bottom",
p1 + facet_grid(x~y) + theme(legend.position = "bottom")
)
expect_doppelganger("facet_grid, legend on right",
p1 + facet_grid(x~y) + theme(legend.position = "right")
)
expect_doppelganger("facet_grid, legend on top",
p1 + facet_grid(x~y) + theme(legend.position = "top")
)
expect_doppelganger("facet_wrap, legend on left",
p1 + facet_wrap(~ x) + theme(legend.position = "left")
)
expect_doppelganger("facet_wrap, legend on bottom",
p1 + facet_wrap(~ x) + theme(legend.position = "bottom")
)
expect_doppelganger("facet_wrap, legend on right",
p1 + facet_wrap(~ x) + theme(legend.position = "right")
)
expect_doppelganger("facet_wrap, legend on top",
p1 + facet_wrap(~ x) + theme(legend.position = "top")
)
dat <- data_frame(x = LETTERS[1:3], y = 1)
p2 <- ggplot(dat, aes(x, y, fill = x, colour = 1:3)) +
geom_bar(stat = "identity") +
guides(color = "colorbar") +
theme_test() +
theme(legend.background = element_rect(colour = "black"))
expect_doppelganger("padding in legend box", p2)
expect_doppelganger("legend inside plot, centered",
p2 + theme(legend.position = c(.5, .5))
)
expect_doppelganger("legend inside plot, bottom left",
p2 + theme(legend.justification = c(0,0), legend.position = c(0,0))
)
expect_doppelganger("legend inside plot, top right",
p2 + theme(legend.justification = c(1,1), legend.position = c(1,1))
)
expect_doppelganger("legend inside plot, bottom left of legend at center",
p2 + theme(legend.justification = c(0,0), legend.position = c(.5,.5))
)
})
test_that("guides title and text are positioned correctly", {
df <- data_frame(x = 1:3, y = 1:3)
p <- ggplot(df, aes(x, y, color = factor(x), fill = y)) +
geom_point(shape = 21) +
guides(color = guide_legend(order = 2),
fill = guide_colorbar(order = 1)) +
theme_test()
expect_doppelganger("multi-line guide title works",
p +
scale_color_discrete(name = "the\ndiscrete\ncolorscale") +
scale_fill_continuous(name = "the\ncontinuous\ncolorscale")
)
expect_doppelganger("vertical gap of 1cm between guide title and guide",
p + theme(legend.spacing.y = grid::unit(1, "cm"))
)
expect_doppelganger("horizontal gap of 1cm between guide and guide text",
p + theme(legend.spacing.x = grid::unit(1, "cm"))
)
df <- data_frame(x = c(1, 10, 100))
p <- ggplot(df, aes(x, x, color = x, size = x)) +
geom_point() +
guides(shape = guide_legend(order = 1),
color = guide_colorbar(order = 2)) +
theme_test()
expect_doppelganger("guide title and text positioning and alignment via themes",
p + theme(
legend.title = element_text(hjust = 0.5, margin = margin(t = 30)),
legend.text = element_text(hjust = 1, margin = margin(l = 5, t = 10, b = 10))
)
)
df <- data_frame(x = c(5, 10, 15))
p <- ggplot(df, aes(x, x, color = x, fill = 15 - x)) +
geom_point(shape = 21, size = 5, stroke = 3) +
scale_colour_continuous(
name = "value",
guide = guide_colorbar(
title.theme = element_text(size = 11, angle = 0, hjust = 0.5, vjust = 1),
label.theme = element_text(size = 0.8*11, angle = 270, hjust = 0.5, vjust = 1),
order = 2
)
) +
scale_fill_continuous(
breaks = c(5, 10, 15),
limits = c(5, 15),
labels = paste("long", c(5, 10, 15)),
name = "fill value",
guide = guide_legend(
direction = "horizontal",
title.position = "top",
label.position = "bottom",
title.theme = element_text(size = 11, angle = 180, hjust = 0, vjust = 1),
label.theme = element_text(size = 0.8*11, angle = 90, hjust = 1, vjust = 0.5),
order = 1
)
)
expect_doppelganger("rotated guide titles and labels", p )
})
test_that("colorbar can be styled", {
df <- data_frame(x = c(0, 1, 2))
p <- ggplot(df, aes(x, x, color = x)) + geom_point()
expect_doppelganger("white-to-red colorbar, white ticks, no frame",
p + scale_color_gradient(low = 'white', high = 'red')
)
expect_doppelganger("white-to-red colorbar, thick black ticks, green frame",
p + scale_color_gradient(
low = 'white', high = 'red',
guide = guide_colorbar(
frame.colour = "green",
frame.linewidth = 1.5,
ticks.colour = "black",
ticks.linewidth = 2.5
)
)
)
})
test_that("guides can handle multiple aesthetics for one scale", {
df <- data_frame(x = c(1, 2, 3),
y = c(6, 5, 7))
p <- ggplot(df, aes(x, y, color = x, fill = y)) +
geom_point(shape = 21, size = 3, stroke = 2) +
scale_colour_viridis_c(
name = "value",
option = "B", aesthetics = c("colour", "fill")
)
expect_doppelganger("one combined colorbar for colour and fill aesthetics", p)
})
test_that("bin guide can be styled correctly", {
df <- data_frame(x = c(1, 2, 3),
y = c(6, 5, 7))
p <- ggplot(df, aes(x, y, size = x)) +
geom_point() +
scale_size_binned()
expect_doppelganger("guide_bins looks as it should", p)
expect_doppelganger("guide_bins can show limits",
p + guides(size = guide_bins(show.limits = TRUE))
)
expect_doppelganger("guide_bins can show arrows",
p + guides(size = guide_bins(axis.arrow = arrow(length = unit(1.5, "mm"), ends = "both")))
)
expect_doppelganger("guide_bins can remove axis",
p + guides(size = guide_bins(axis = FALSE))
)
expect_doppelganger("guide_bins work horizontally",
p + guides(size = guide_bins(direction = "horizontal"))
)
})
test_that("coloursteps guide can be styled correctly", {
df <- data_frame(x = c(1, 2, 4),
y = c(6, 5, 7))
p <- ggplot(df, aes(x, y, colour = x)) +
geom_point() +
scale_colour_binned(breaks = c(1.5, 2, 3))
expect_doppelganger("guide_coloursteps looks as it should", p)
expect_doppelganger("guide_coloursteps can show limits",
p + guides(colour = guide_coloursteps(show.limits = TRUE))
)
expect_doppelganger("guide_coloursteps can have bins relative to binsize",
p + guides(colour = guide_coloursteps(even.steps = FALSE))
)
expect_doppelganger("guide_bins can show ticks",
p + guides(colour = guide_coloursteps(ticks = TRUE))
)
})
test_that("a warning is generated when guides(<scale> = FALSE) is specified", {
df <- data_frame(x = c(1, 2, 4),
y = c(6, 5, 7))
expect_warning(g <- guides(colour = FALSE), "`guides(<scale> = FALSE)` is deprecated.", fixed = TRUE)
expect_equal(g[["colour"]], "none")
p <- ggplot(df, aes(x, y, colour = x)) + scale_colour_continuous(guide = FALSE)
built <- expect_silent(ggplot_build(p))
expect_warning(ggplot_gtable(built), "It is deprecated to specify `guide = FALSE`")
}) |
draw.t=function(nrep,dof){
if (dof<=1){
stop("Degrees of freedom must be greater than 1!\n")
}
x=numeric(nrep)
for (i in 1:nrep){
index=0
while (index<1){
v1=runif(1,-1,1)
v2=runif(1,-1,1)
r2=v1^2+v2^2
r=sqrt(r2)
w=(r2<1)
x[i]=v1*sqrt(abs((dof*(r^(-4/dof)-1)/r2)))
index=sum(w)
}
}
if(dof>1){
emp.mean=round(mean(x), 5)
theo.mean=0
theo.mean=round(theo.mean, 5)
} else {
warning("Mean only defined when dof>1.")
theo.mean="Mean only defined when dof>1."
emp.mean=NA
}
if(dof>2){
emp.var=round(var(x), 5)
theo.var=dof/(dof-2)
theo.var=round(theo.var, 5)
} else {
warning("Variance only defined when dof>2.")
theo.var="Variance only defined when dof>2."
emp.var=NA
}
return(list(y=x, theo.mean=theo.mean, emp.mean=emp.mean, theo.var=theo.var, emp.var=emp.var))
} |
stableFit <-
function(x, alpha = 1.75, beta = 0, gamma = 1, delta = 0,
type = c("q", "mle"), doplot = TRUE, control = list(),
trace = FALSE, title = NULL, description = NULL)
{
ans = .qStableFit(x, doplot, title, description)
if (type[1] == "mle") {
Alpha = ans@fit$estimate[1]
Beta = ans@fit$estimate[2]
Gamma = ans@fit$estimate[3]
Delta = ans@fit$estimate[4]
if (is.na(Alpha)) Alpha = alpha
if (is.na(Beta)) Beta = beta
if (is.na(Gamma)) Gamma = gamma
if (is.na(Delta)) Delta = delta
ans = .mleStableFit(x, Alpha, Beta, Gamma, Delta, doplot,
control, trace, title, description)
}
ans
}
.phiStable <-
function()
{
alpha = c(seq(0.50, 1.95, by = 0.1), 1.95, 1.99)
beta = c(-0.95, seq(-0.90, 0.90, by = 0.10), 0.95)
m = length(alpha)
n = length(beta)
phi1 = function(alpha, beta)
{
( stabledist::qstable(0.95, alpha, beta) -
stabledist::qstable(0.05, alpha, beta) ) /
( stabledist::qstable(0.75, alpha, beta) -
stabledist::qstable(0.25, alpha, beta) )
}
phi2 = function(alpha, beta)
{
( ( stabledist::qstable(0.95, alpha, beta) -
stabledist::qstable(0.50, alpha, beta) ) -
( stabledist::qstable(0.50, alpha, beta) -
stabledist::qstable(0.05, alpha, beta) ) ) /
( stabledist::qstable(0.95, alpha, beta) -
stabledist::qstable(0.05, alpha, beta) )
}
Phi1 = Phi2 = matrix(rep(0, n*m), ncol = n)
for ( i in 1:m ) {
for ( j in 1:n ) {
Phi1[i,j] = phi1(alpha[i], beta[j])
Phi2[i,j] = phi2(alpha[i], beta[j])
print( c(alpha[i], beta[j], Phi1[i,j], Phi2[i,j]) )
}
}
contour(alpha, beta, Phi1, levels = c(2.5, 3, 5, 10, 20, 40),
xlab = "alpha", ylab = "beta", labcex = 1.5, xlim = c(0.5, 2.0))
contour(alpha, beta, Phi2, levels = c(-0.8, -0.6, -0.4, -0.2, 0,
0.2, 0.4, 0.6, 0.8), col = "red", labcex = 1.5, add = TRUE)
.PhiStable <- list(Phi1 = Phi1, Phi2 = Phi2, alpha = alpha, beta = beta)
if (FALSE) dump(".PhiStable", "PhiStable.R")
.PhiStable
}
.PhiStable <-
structure(
list(
Phi1 = structure(c(28.1355600962322, 15.7196640771722,
10.4340722145276, 7.72099712337154, 6.14340919629241, 5.14081963876442,
4.45927409495436, 3.97057677836415, 3.60450193720703, 3.31957820409758,
3.09091185492284, 2.9029090263133, 2.74659551412658, 2.61782756430233,
2.51560631141019, 2.47408801877228, 2.44525363752631, 28.3483300097440,
15.8035063527296, 10.4727953966709, 7.74141823634036, 6.15576314177463,
5.14915506532249, 4.46531988542058, 3.97505189771183, 3.60736868847651,
3.32104702700423, 3.09111342044363, 2.90219825204304, 2.74552084086904,
2.61707392900167, 2.51531961206501, 2.47401179006119, 2.44525268403340,
28.9048147202382, 16.0601313263480, 10.6117049719320, 7.8237753182648,
6.20955682299195, 5.18679961805621, 4.49216000186678, 3.99373973242068,
3.61933010719953, 3.3275594162867, 3.09331226057454, 2.90155994459038,
2.74368539137288, 2.61555847928520, 2.51479444686423, 2.47387109904253,
2.44525093764076, 29.8026200973137, 16.5596243974224, 10.9360864131028,
8.04563520952583, 6.35889612112486, 5.28397230078563, 4.55431822343012,
4.03266384946799, 3.64246979110989, 3.33973615437707, 3.09810405845187,
2.90191073816964, 2.7422687239301, 2.61421528380001, 2.51433181630644,
2.47374639426837, 2.44524854839106, 31.1711919144382, 17.3256645589998,
11.4257682914949, 8.37916374365985, 6.59111369941092, 5.4435297531592,
4.65827423282770, 4.09593909348039, 3.67827370972420, 3.35788028768518,
3.10538249512478, 2.90322430476313, 2.7411383952518, 2.61307358265729,
2.51393064512464, 2.47363793686619, 2.44524473760244, 33.1948934984822,
18.4071500759968, 12.0794579487667, 8.80181848446003, 6.8744516193679,
5.6351929385469, 4.78568154439060, 4.17585254205654, 3.72404890551037,
3.38077811930023, 3.11457663716798, 2.90522469731234, 2.74043557937936,
2.61209710262770, 2.51359601849030, 2.47354590407541, 2.44523688699559,
35.9578028398622, 19.7936882741385, 12.8664734285429, 9.28349135864713,
7.18278427917665, 5.83729171895546, 4.91779143967590, 4.25960094973301,
3.77307337255403, 3.4057709031586, 3.12469898537975, 2.90767817230573,
2.7399388028832, 2.61130578115398, 2.51330169831474, 2.47347041290067,
2.4452243360266, 38.9647018181828, 21.2269841758554, 13.6587928142908,
9.75737930074977, 7.47910500668215, 6.02679068365276, 5.03975173429821,
4.33641171958119, 3.81844774991854, 3.42948489228359, 3.13453596844362,
2.91006724722144, 2.73965159366498, 2.61068126597691, 2.51309087992836,
2.47342375837911, 2.44524639012562, 41.7818369588849, 22.4602363370435,
14.3128567516975, 10.1435099877839, 7.72005687380391, 6.18048140792379,
5.13779081982581, 4.39769218775219, 3.85488105109873, 3.44880791704519,
3.14262443869137, 2.91215029990006, 2.73947335432536, 2.61026149741526,
2.51293721037603, 2.47333463795113, 2.44523871005695, 43.8597008728084,
23.308181530155, 14.7432127411421, 10.3930748979735, 7.87518470289541,
6.2796283727218, 5.20095216574708, 4.43724315622136, 3.87838777226609,
3.46128790559551, 3.14792806986726, 2.91355836113947, 2.7394048824397,
2.60999397178590, 2.51287974154683, 2.4733261698261, 2.44523291863013,
44.6351177921226, 23.612190997173, 14.8937659530932, 10.4791077126402,
7.9285095195091, 6.31375867971341, 5.2228691158165, 4.45085115209764,
3.88645952709398, 3.46562279514434, 3.14978921717977, 2.91402779433739,
2.73939000980242, 2.60993524495366, 2.51289337121820, 2.47330017392183,
2.44524525291192, 43.8597008728085, 23.3081815301550, 14.7432127411420,
10.3930748979735, 7.87518470289542, 6.2796283727218, 5.20095216574709,
4.43724315622136, 3.87838777226609, 3.46128790559551, 3.14792806986726,
2.91355836113947, 2.7394048824397, 2.60999397178590, 2.51287974154683,
2.4733261698261, 2.44523291863013, 41.7818369588849, 22.4602363370436,
14.3128567516975, 10.1435099877840, 7.72005687380392, 6.18048140792379,
5.13779081982581, 4.39769218775219, 3.85488105109874, 3.44880791704519,
3.14262443869137, 2.91215029990006, 2.73947335432536, 2.61026149741526,
2.51293721037603, 2.47333463795113, 2.44523871005695, 38.9647018181828,
21.2269841758554, 13.6587928142909, 9.75737930074976, 7.47910500668216,
6.02679068365277, 5.0397517342982, 4.33641171958119, 3.81844774991854,
3.42948489228359, 3.13453596844362, 2.91006724722144, 2.73965159366498,
2.61068126597691, 2.51309087992836, 2.47342375837911, 2.44524639012562,
35.9578028398623, 19.7936882741384, 12.8664734285429, 9.28349135864712,
7.18278427917667, 5.83729171895546, 4.91779143967590, 4.25960094973301,
3.77307337255403, 3.4057709031586, 3.12469898537975, 2.90767817230572,
2.7399388028832, 2.61130578115398, 2.51330169831474, 2.47347041290067,
2.4452243360266, 33.1948934984822, 18.4071500759967, 12.0794579487667,
8.80181848446, 6.8744516193679, 5.6351929385469, 4.78568154439059,
4.17585254205653, 3.72404890551037, 3.38077811930023, 3.11457663716797,
2.90522469731234, 2.74043557937936, 2.61209710262770, 2.51359601849030,
2.47354590407541, 2.44523688699559, 31.1711919144381, 17.3256645589999,
11.4257682914948, 8.37916374365983, 6.59111369941092, 5.44352975315921,
4.65827423282769, 4.09593909348039, 3.67827370972420, 3.35788028768518,
3.10538249512478, 2.90322430476312, 2.7411383952518, 2.61307358265729,
2.51393064512464, 2.47363793686619, 2.44524473760245, 29.8026200973136,
16.5596243974222, 10.9360864131028, 8.04563520952581, 6.35889612112487,
5.28397230078562, 4.55431822343012, 4.03266384946799, 3.64246979110989,
3.33973615437707, 3.09810405845187, 2.90191073816964, 2.7422687239301,
2.61421528380001, 2.51433181630644, 2.47374639426837, 2.44524854839106,
28.904814720238, 16.0601313263481, 10.6117049719320, 7.82377531826481,
6.20955682299195, 5.18679961805620, 4.49216000186678, 3.99373973242068,
3.61933010719952, 3.3275594162867, 3.09331226057455, 2.90155994459037,
2.74368539137288, 2.61555847928520, 2.51479444686423, 2.47387109904253,
2.44525093764076, 28.3483300097438, 15.8035063527296, 10.4727953966709,
7.74141823634038, 6.15576314177465, 5.1491550653225, 4.46531988542057,
3.97505189771183, 3.60736868847651, 3.32104702700424, 3.09111342044363,
2.90219825204304, 2.74552084086904, 2.61707392900167, 2.51531961206501,
2.47401179006119, 2.44525268403340, 28.1355600962322, 15.7196640771723,
10.4340722145275, 7.72099712337151, 6.1434091962924, 5.14081963876442,
4.45927409495435, 3.97057677836415, 3.60450193720703, 3.31957820409757,
3.09091185492284, 2.9029090263133, 2.74659551412658, 2.61782756430233,
2.51560631141019, 2.47408801877228, 2.44525363752631),
.Dim = as.integer(c(17, 21))),
Phi2 = structure(c(-0.984831521754346, -0.96178750287388,
-0.925815277018118, -0.877909786944587, -0.820184465666658,
-0.755031918545081, -0.684592921700777, -0.610570901457792,
-0.534175805219629, -0.456236240234657, -0.377306837254648,
-0.297867095171864, -0.218666685919607, -0.141143940005887,
-0.0674987199592516, -0.0328701597273596, -0.00642990194045526,
-0.984833720280198, -0.96124832221758, -0.92402252050786,
-0.87419335313835, -0.81415246030398, -0.74662653505109,
-0.674063099101783, -0.598388680797427, -0.520979416823626,
-0.442739494396008, -0.364272193075272, -0.286088382456793,
-0.208957354222478, -0.1342789733294, -0.0640144100029875,
-0.0311490271069921, -0.006091726394748, -0.979153629182453,
-0.95106168789293, -0.909673941239617, -0.85602448791855,
-0.791828629762056, -0.720369142925194, -0.644748722301942,
-0.567214164881932, -0.489279988980024, -0.411880943403832,
-0.335605401995838, -0.260987626602553, -0.188786833912990,
-0.120269390643364, -0.0570145517746281, -0.0277025095388298,
-0.0054153433806392, -0.956099620177616, -0.91510100889139,
-0.863494586547947, -0.804340589970157, -0.739811913292119,
-0.670992067490536, -0.598508014750715, -0.523938483324115,
-0.449119649196787, -0.375320171482799, -0.303334211640077,
-0.233819259537015, -0.167632931803862,
-0.105970645511563, -0.0499759998221647, -0.0242509183116938,
-0.00473892214395457, -0.91091521430624, -0.854269872890404,
-0.792380659464175, -0.728324327412516, -0.663641470500818,
-0.598766118303959, -0.533390833007158, -0.466958108675312,
-0.399718402638334, -0.332810169846175, -0.267433026630897,
-0.204649764654678, -0.145582752525226, -0.0913961065988934,
-0.042902827489912, -0.0207949382390745, -0.004062467796571,
-0.838142578217344, -0.767730556629547, -0.699387193072487,
-0.634346095207953, -0.572568000770375, -0.513428073110925,
-0.456016815864829, -0.399237447140644, -0.342164056355244,
-0.284798223846443, -0.228151639956042, -0.173628819918976,
-0.122674652213850, -0.0765638152109311, -0.0358016086121756,
-0.0173352283908653, -0.00338423605633909, -0.732960648615699,
-0.655211639338905, -0.586717060962992, -0.525770503418058,
-0.470570307907465, -0.419573011635011, -0.371434023729476,
-0.324886123523844, -0.278750785874156, -0.232309518692667,
-0.185933156371725, -0.140978784025337, -0.0990680854456507,
-0.0615175707971035, -0.0286670029088599, -0.0138724303903631,
-0.00270395845154647, -0.592691443906747, -0.517917221384721,
-0.456902886405761, -0.405327421204478, -0.360251537992231,
-0.319685291504111, -0.282167838420900, -0.246496132463733,
-0.211596523966543, -0.176602222829403, -0.141397972727901,
-0.106937786396409, -0.0748572933895385, -0.0462908166605395,
-0.0215205174484398, -0.0104071747947459, -0.00203767706388774,
-0.418561278354954, -0.359043286074154, -0.313110693536944,
-0.275656631235694, -0.243720459128403, -0.215493360906447,
-0.18976206222188, -0.165585707487220, -0.142157842427747,
-0.118764989711438, -0.0951531051692878, -0.0718822809574559,
-0.0501702371114745, -0.0309413187181704, -0.0143569748225324,
-0.00693928545290556, -0.00135914851834483, -0.217058958479026,
-0.183957984146554, -0.159253973812649, -0.139529858864502,
-0.122956050946611, -0.108468261383110,
-0.095363933833862, -0.0831489044941912, -0.0713807547092049,
-0.0596749091239935, -0.0478406346829651, -0.0361189030171852,
-0.0251638752545685, -0.0154951657479659, -0.00718251696063777,
-0.00347157285038577, -0.000682830247122471, -1.30195010613456e-15,
-7.12101008020212e-16, -9.8472751183435e-16, -1.13492047149954e-15,
-1.21096413626332e-15, -1.05505102779748e-15, -1.11782289130157e-15,
-8.13224377427617e-16, -5.85149540688739e-16, 4.61239028385592e-16,
1.45510576814449e-16, -4.733934001018e-16, -3.36773719381392e-16,
0, 9.23542032962673e-17, -1.87944839722067e-16, -2.8550539469612e-16,
0.217058958479025, 0.183957984146551, 0.159253973812647,
0.139529858864502, 0.12295605094661, 0.108468261383109,
0.0953639338338615, 0.0831489044941909, 0.0713807547092042,
0.0596749091239931, 0.0478406346829641, 0.036118903017185,
0.0251638752545679, 0.0154951657479665, 0.00718251696063749,
0.00347157285038558, 0.00068283024712209, 0.418561278354956,
0.359043286074156, 0.313110693536942, 0.275656631235694,
0.243720459128404, 0.215493360906444, 0.189762062221879,
0.165585707487219, 0.142157842427746, 0.118764989711438,
0.0951531051692875, 0.0718822809574556, 0.0501702371114741,
0.0309413187181703, 0.0143569748225322, 0.00693928545290556,
0.00135914851834492, 0.59269144390675, 0.517917221384721,
0.456902886405764, 0.405327421204478, 0.360251537992232,
0.319685291504111, 0.2821678384209, 0.246496132463732,
0.211596523966543, 0.176602222829402, 0.141397972727901,
0.106937786396409, 0.074857293389538, 0.0462908166605391,
0.0215205174484394, 0.0104071747947454, 0.00203767706388774,
0.7329606486157, 0.655211639338903, 0.58671706096299,
0.525770503418055, 0.470570307907467, 0.419573011635009,
0.371434023729475, 0.324886123523844, 0.278750785874155,
0.232309518692667, 0.185933156371724, 0.140978784025336,
0.0990680854456504, 0.0615175707971032, 0.0286670029088598,
0.0138724303903627, 0.00270395845154656, 0.838142578217343,
0.767730556629544, 0.699387193072486, 0.634346095207951,
0.572568000770374, 0.513428073110924, 0.456016815864827,
0.399237447140644, 0.342164056355244, 0.284798223846443,
0.228151639956042, 0.173628819918976, 0.122674652213850,
0.0765638152109311, 0.0358016086121755, 0.0173352283908648,
0.00338423605633909, 0.910915214306239, 0.854269872890404,
0.792380659464175, 0.728324327412515, 0.663641470500817,
0.598766118303959, 0.533390833007157, 0.466958108675312,
0.399718402638334, 0.332810169846175, 0.267433026630897,
0.204649764654678, 0.145582752525226, 0.0913961065988931,
0.0429028274899118, 0.020794938239074, 0.00406246779657053,
0.956099620177616, 0.915101008891389, 0.863494586547946,
0.804340589970156, 0.739811913292119, 0.670992067490536,
0.598508014750714, 0.523938483324114, 0.449119649196786,
0.375320171482798, 0.303334211640076, 0.233819259537015,
0.167632931803862, 0.105970645511562, 0.0499759998221642,
0.0242509183116936, 0.00473892214395428, 0.979153629182453,
0.95106168789293, 0.909673941239617, 0.85602448791855,
0.791828629762055, 0.720369142925193, 0.644748722301942,
0.567214164881931, 0.489279988980024, 0.411880943403833,
0.335605401995838, 0.260987626602552, 0.188786833912991,
0.120269390643364, 0.0570145517746277, 0.0277025095388299,
0.00541534338063891, 0.984833720280198, 0.96124832221758,
0.92402252050786, 0.87419335313835, 0.81415246030398,
0.746626535051091, 0.674063099101783, 0.598388680797427,
0.520979416823626, 0.442739494396008, 0.364272193075271,
0.286088382456793, 0.208957354222478, 0.1342789733294,
0.0640144100029874, 0.0311490271069919, 0.00609172639474771,
0.984831521754346, 0.96178750287388, 0.925815277018118,
0.877909786944586, 0.820184465666658, 0.75503191854508,
0.684592921700776, 0.610570901457792, 0.534175805219629,
0.456236240234657, 0.377306837254648, 0.297867095171864,
0.218666685919607, 0.141143940005886, 0.0674987199592513,
0.0328701597273591, 0.00642990194045459),
.Dim = as.integer(c(17, 21))),
alpha = c(0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4,
1.5, 1.6, 1.7, 1.8, 1.9, 1.95, 1.99),
beta = c(-0.95, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1,
0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95)),
.Names = c("Phi1", "Phi2", "alpha", "beta")
)
.qStableFit <-
function(x, doplot = TRUE, title = NULL, description = NULL)
{
CALL = match.call()
Phi1 = .PhiStable$Phi1
Phi2 = .PhiStable$Phi2
alpha = .PhiStable$alpha
beta = .PhiStable$beta
r = sort(x)
N = length(r)
q95 = r[round(0.95*N)]
q75 = r[round(0.75*N)]
q50 = r[round(0.50*N)]
q25 = r[round(0.25*N)]
q05 = r[round(0.05*N)]
phi1 = max( (q95-q05) / (q75-q25), 2.4389 )
phi2 = ((q95-q50)-(q50-q05)) / (q95-q05)
if (doplot) {
contour(alpha, beta, Phi1, levels = c(2.5, 3, 5, 10, 20, 40),
xlab = "alpha", ylab = "beta", xlim = c(0.5, 2.0))
contour(alpha, beta, Phi2, levels = c(-0.8, -0.6, -0.4, -0.2,
0.2, 0.4, 0.6, 0.8), col = "red", add = TRUE)
lines(c(0.5, 2), c(0, 0), col = "red")
contour(alpha, beta, Phi1, levels = phi1, add = TRUE, lty = 3,
col = "blue")
contour(alpha, beta, Phi2, levels = phi2, add = TRUE, lty = 3,
col = "blue")
title(main = "Stable Quantiles")
}
u = contourLines(alpha, beta, Phi1, levels = phi1)
Len = length(u)
if( Len > 0) {
u = u[[1]][-1]
v = contourLines(alpha, beta, Phi2, levels = phi2)
v = v[[1]][-1]
xout = seq(min(v$y), max(v$y), length = 200)
z = approx(v$y, v$x, xout = xout)$y - approx(u$y, u$x, xout = xout)$y
index = which.min(abs(z))
V = round(xout[index], 3)
U = round(approx(v$y, v$x, xout = xout[index])$y, 3)
if (doplot) points(U, V, pch = 19, cex = 1)
} else {
U = V = NA
}
if (is.null(title)) title = "Stable Parameter Estimation"
if (is.null(description)) description = description()
if (is.na(U) | is.na(V)) {
GAM = NA
} else {
phi3 = stabledist::qstable(0.75, U, V) -
stabledist::qstable(0.25, U, V)
GAM = (q75-q25) / phi3
}
if (is.na(U) | is.na(V)) {
DELTA = NA
} else {
phi4 = -stabledist::qstable(0.50, U, V) + V*tan(pi*U/2)
DELTA = phi4*GAM - V*GAM*tan(pi*U/2) + q50
}
fit = list(estimate = c(alpha = U, beta = V, gamma = GAM, delta = DELTA))
new("fDISTFIT",
call = as.call(CALL),
model = "Stable Distribution",
data = as.data.frame(x),
fit = fit,
title = as.character(title),
description = description() )
}
.mleStableFit <-
function(x, alpha = 1.75, beta = 0, gamma = 1, delta = 0, doplot = TRUE,
control = list(), trace = FALSE, title = NULL, description = NULL)
{
x.orig = x
x = as.vector(x)
CALL = match.call()
obj = function(x, y = x, trace = FALSE) {
f = -mean(log(stabledist::dstable(y,
alpha = x[1], beta = x[2], gamma = x[3], delta = x[4])))
if (trace) {
cat("\n Objective Function Value: ", -f)
cat("\n Stable Estimate: ", x)
cat("\n")
}
f
}
eps = 1e-4
r <- nlminb(
objective = obj,
start = c(alpha, beta, gamma, delta),
lower = c( eps, -1+eps, 0+eps, -Inf),
upper = c(2-eps, 1-eps, Inf, Inf),
y = x, control = control, trace = trace)
alpha = r$par[1]
beta = r$par[2]
gamma = r$par[3]
delta = r$par[4]
if (doplot) .stablePlot(x, alpha, beta, gamma, delta)
if (is.null(title)) title = "Stable Parameter Estimation"
if (is.null(description)) description = description()
fit = list(estimate = c(alpha, beta, gamma, delta),
minimum = -r$objective, code = r$convergence, gradient = r$gradient)
new("fDISTFIT",
call = as.call(CALL),
model = "Stable Distribution",
data = as.data.frame(x.orig),
fit = fit,
title = as.character(title),
description = description() )
}
.stablePlot <-
function(x, alpha, beta, gamma, delta)
{
span.min <- stabledist::qstable(0.01, alpha, beta, gamma, delta)
span.max <- stabledist::qstable(0.99, alpha, beta, gamma, delta)
span = seq(span.min, span.max, length = 100)
par(err = -1)
z = density(x, n = 100)
x = z$x[z$y > 0]
y = z$y[z$y > 0]
y.points = stabledist::dstable(span, alpha, beta, gamma, delta)
ylim = log(c(min(y.points), max(y.points)))
plot(x, log(y), xlim = c(span[1], span[length(span)]),
ylim = ylim, type = "p", xlab = "x", ylab = "log f(x)")
title("Stable Distribution: Parameter Estimation")
lines(x = span, y = log(y.points), col = "steelblue")
grid()
invisible()
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
fig.width = 7,
fig.height = 6,
fig.align = 'center'
)
library(NFCP)
set.seed(412)
model_parameters_2F <- NFCP_parameters(N_factors = 2,
GBM = TRUE,
initial_states = FALSE,
N_ME = 5)
print(model_parameters_2F)
SS_oil_stitched <- stitch_contracts(futures = SS_oil$contracts,
futures_TTM = c(1, 5, 9, 13, 17)/12, maturity_matrix = SS_oil$contract_maturities,
rollover_frequency = 1/12, verbose = TRUE)
matplot(as.Date(rownames(SS_oil_stitched$maturities)), SS_oil_stitched$maturities,
type = 'l', main = "Stitched Contract Maturities",
ylab = "Time To Maturity (Years)", xlab = "Date", col = 1)
print(SS_oil$two_factor)
Oil_2F <- NFCP_Kalman_filter(
parameter_values = SS_oil$two_factor,
parameter_names = names(SS_oil$two_factor),
log_futures = log(SS_oil$stitched_futures),
futures_TTM = SS_oil$stitched_TTM,
dt = SS_oil$dt,
verbose = TRUE,
debugging = TRUE)
Oil_2F_parameters <- SS_oil$two_factor[1:7]
Oil_2F_parameters["ME_1"] <- 0.01
Oil_2F_contracts <- NFCP_Kalman_filter(
parameter_values = Oil_2F_parameters,
parameter_names = names(Oil_2F_parameters),
log_futures = log(SS_oil$contracts),
futures_TTM = SS_oil$contract_maturities,
dt = SS_oil$dt,
verbose = TRUE,
debugging = TRUE)
print(SS_oil$two_factor[8:12])
Oil_1F <- NFCP_MLE(
log_futures = log(SS_oil$stitched_futures),
dt = SS_oil$dt,
futures_TTM= SS_oil$stitched_TTM,
N_factors = 1,
N_ME = 3,
ME_TTM = c(0.5, 1, 1.5),
print.level = 0)
print(round(rbind(`Estimated Parameter` = Oil_1F$estimated_parameters,
`Standard Error` = Oil_1F$standard_errors),4))
print(matrix(c(Oil_1F$MLE, Oil_2F$`Log-Likelihood`),
dimnames = list(c("One-Factor", "Two-Factor"), "Log-Likelihood")))
print(round(rbind("One-Factor" = Oil_1F$`Information Criteria`,
"Two-Factor" = Oil_2F$`Information Criteria`), 4))
print(round(t(Oil_2F[["Term Structure Fit"]]),4))
CN_table3 <- matrix(nrow = 2, ncol = 2, dimnames = list(c("One-Factor","Two-Factor"), c("RMSE", "Bias")))
CN_table3[,"Bias"] <- c(Oil_1F$`Filtered Error`["Bias"], Oil_2F$`Filtered Error`["Bias"])
CN_table3[,"RMSE"] <- c(Oil_1F$`Filtered Error`["RMSE"], Oil_2F$`Filtered Error`["RMSE"])
print(round(CN_table3, 4))
matplot(as.Date(rownames(Oil_1F$V)), Oil_1F$V, type = 'l',
xlab = "", ylab = "Observation Error",
main = "Contract Observation Error: One-Factor Model"); legend("bottomright",
colnames(Oil_2F$V),col=seq_len(5),cex=0.8,fill=seq_len(5))
matplot(as.Date(rownames(Oil_2F$V)), Oil_2F$V, type = 'l',
xlab = "", ylab = "Observation Error", ylim = c(-0.3, 0.2),
main = "Contract Observation Error: Two-Factor Model"); legend("bottomright",
colnames(Oil_2F$V),col=seq_len(5),cex=0.8,fill=seq_len(5))
matplot(cbind(Oil_1F$`Term Structure Fit`["RMSE",], Oil_2F$`Term Structure Fit`["RMSE",]),
type = 'l', main = "Root Mean Squared Error of Futures Contracts",
xlab = "Contract", ylab = "RMSE"); legend("right",c("One-Factor", "Two-Factor"),
col=1:2,cex=0.8,fill=1:2)
SS_figure_4 <- cbind(`Equilibrium Price` =
exp(Oil_2F$X[,1]),
`Spot Price` =
Oil_2F$Y[,"filtered Spot"])
matplot(as.Date(rownames(SS_figure_4)), SS_figure_4, type = 'l',
xlab = "", ylab = "Oil Price ($/bbl, WTI)", col = 1,
main = "Estimated Spot and Equilibrium Prices for the Futures Data")
plot(as.Date(rownames(SS_oil$contracts)), sqrt(Oil_2F_contracts$P_t[1,1,]),
type = 'l', xlab = "Date", ylab = "Std. Dev.",
main = "Time Series of the Std. Dev for State Variable 1")
Enron_values <- c(0.0300875, 0.0161, 0.014, 1.19, 0.115, 0.158, 0.189)
names(Enron_values) <- NFCP_parameters(2, TRUE, FALSE, 0, FALSE, FALSE)
SS_expected_spot <- spot_price_forecast(x_0 = c(2.857, 0.119),
parameters = Enron_values,
t = seq(0,9,1/12),
percentiles = c(0.1, 0.9))
equilibrium_theta <- Enron_values[!names(Enron_values) %in%
c("kappa_2", "lambda_2", "sigma_2", "rho_1_2")]
SS_expected_equilibrium <- spot_price_forecast(x_0 = c(2.857, 0),
equilibrium_theta,
t = seq(0,9,1/12),
percentiles = c(0.1, 0.9))
SS_figure_1 <- cbind(SS_expected_spot, SS_expected_equilibrium)
matplot(seq(0,9,1/12), SS_figure_1, type = 'l', col = 1, lty = c(rep(1,3), rep(2,3)),
xlab = "Time (Years)", ylab = "Spot Price ($/bbl, WTI)",
main = "Probabilistic Forecasts for Spot and Equilibrium Prices")
SS_expected_spot <- spot_price_forecast(x_0 = c(2.857, 0.119),
parameters = Enron_values,
t = seq(0,9,1/12),
percentiles = c(0.1, 0.9))
SS_futures_curve <- futures_price_forecast(x_0 = c(2.857, 0.119),
parameters = Enron_values,
futures_TTM = seq(0,9,1/12))
SS_figure_2 <- cbind(SS_expected_spot[,2], SS_futures_curve)
matplot(seq(0,9,1/12), log(SS_figure_2), type = 'l', col = 1,
xlab = "Time (Years)", ylab = "Log(Price)",
main = "Futures Prices and Expected Spot Prices")
max_maturity <- max(tail(SS_oil$contract_maturities,1), na.rm = TRUE)
oil_TS_1F <- futures_price_forecast(x_0 = Oil_1F$x_t,
parameters = Oil_1F$estimated_parameters,
futures_TTM = seq(0,max_maturity,1/12))
oil_TS_2F <- futures_price_forecast(x_0 = Oil_2F$x_t,
parameters = SS_oil$two_factor,
futures_TTM = seq(0,max_maturity,1/12))
matplot(seq(0,max_maturity,1/12), cbind(oil_TS_1F, oil_TS_2F), type = 'l',
xlab = "Maturity (Years)", ylab = "Futures Price ($)",
main = "Estimated and observed oil futures prices on 1995-02-14");
points(tail(SS_oil$contract_maturities,1), tail(SS_oil$contracts,1))
legend("bottomleft", c("One-factor", "Two-Factor", "Observed"),
col=2:4,cex=0.8,fill=c(1,2,0))
V_TSFit <- TSfit_volatility(
parameters = SS_oil$two_factor,
futures = SS_oil$stitched_futures,
futures_TTM = SS_oil$stitched_TTM,
dt = SS_oil$dt)
matplot(V_TSFit["Maturity",], cbind(Oil_1F$`Term Structure Volatility Fit`["Theoretical Volatility",],
V_TSFit["Theoretical Volatility",]), type = 'l',
xlab = "Maturity (Years)", ylab = "Volatility (%)",
ylim = c(0, 0.5), main = "Volatility Term Structure of Futures Returns"); points(
V_TSFit["Maturity",], V_TSFit["Empirical Volatility",]); legend("bottomleft",
c("Empirical", "One-Factor", "Two-Factor"),col=0:2,cex=0.8,fill=0:2)
simulated_spot_prices <- spot_price_simulate(
x_0 = Oil_2F$x_t,
parameters = SS_oil$two_factor,
t = 1,
dt = 1/12,
N_simulations = 1e3,
antithetic = TRUE,
verbose = TRUE)
matplot(seq(0,1,1/12), simulated_spot_prices$spot_prices, type = 'l',
xlab = "Forecasting Horizon (Years)",
ylab = "Spot Price ($/bbl, WTI)", main = "Simulated Crude Oil prices")
prediction_interval <- rbind.data.frame(apply(simulated_spot_prices$spot_prices, 1,
FUN = function(x) stats::quantile(x, probs = c(0.025, 0.975))),
Mean = rowMeans(simulated_spot_prices$spot_prices))
matplot(seq(0,1,1/12), t(prediction_interval), type = 'l', col = c(2,2,1),
lwd = 2, lty = c(2,2,1), xlab = "Forecasting Horizon (Years)",
ylab = "Spot Price ($/bbl, WTI)", main = "Simulated Crude Oil 95% Confidence Interval")
simulated_contracts <- futures_price_simulate(x_0 = c(log(SS_oil$spot[1,1]), 0),
parameters = Oil_2F_parameters,
dt = SS_oil$dt,
N_obs = nrow(SS_oil$contracts),
futures_TTM = SS_oil$contract_maturities)
matplot(as.Date(rownames(SS_oil$contracts)), simulated_contracts$futures_prices,
type = 'l', ylab = "Futures Price ($/bbl, WTI)", xlab = "Observations",
main = "Simulated Futures Contracts")
Option_prices <- matrix(rep(0,2), nrow = 2, ncol = 3, dimnames = list(c("One-Factor", "Two-Factor"), c("European", "American", "Early Exercise Value")))
strike <- 20
risk_free <- 0.05
option <- 1
future <- 2
time_step <- 1/50
monte_carlo <- 1e5
Option_prices[1,1] <- European_option_value(x_0 = Oil_1F$x_t,
parameters = Oil_1F$estimated_parameters,
futures_maturity = future, option_maturity = option, K = strike, r = risk_free)
Option_prices[2,1] <- European_option_value(x_0 = Oil_2F$x_t,
parameters = SS_oil$two_factor,
futures_maturity = future, option_maturity = option, K = strike, r = risk_free)
Option_prices[1,2] <- American_option_value(x_0 = Oil_1F$x_t,
parameters = Oil_1F$estimated_parameters,
futures_maturity = future, option_maturity = option, K = strike, r = risk_free,
N_simulations = monte_carlo, dt = time_step)
Option_prices[2,2] <- American_option_value(x_0 = Oil_2F$x_t,
parameters = SS_oil$two_factor,
futures_maturity = future, option_maturity = option, K = strike, r = risk_free,
N_simulations = monte_carlo, dt = time_step)
Option_prices[,3] <- Option_prices[,2] - Option_prices[,1]
print(round(Option_prices,3)) |
IRT.simulate <- function (object, ...) {
UseMethod("IRT.simulate")
}
simulate_mml <- function(object, iIndex=NULL, theta=NULL, nobs=NULL, ...){
nnodes <- nobs
A <- object$A
xsi <- object$xsi$xsi
B <- object$B
ndim <- dim(B)[3]
guess <- object$guess
maxK <- dim(A)[2]
if(is.null(iIndex)){
iIndex <- 1:dim(A)[1]
}
nI <- length(iIndex)
if(is.null(theta)){
if(is.null(nnodes)){
nnodes <- nrow(object$person)
}
t.mean <- object$beta
t.sigma <- object$variance
if(ndim==1){
theta <- stats::rnorm(nnodes, mean=t.mean, sd=sqrt(t.sigma))
} else {
theta <- CDM::CDM_rmvnorm(nnodes, mean=t.mean, sigma=t.sigma)
}
theta <- matrix(theta, ncol=ndim)
}
if(is.null(dim(theta)) & ndim==1){
warning("Theta points should be either NULL or a matrix of same dimensionality as the trait distribution.")
theta <- matrix(theta, ncol=ndim)
}
if(ncol(theta) !=ndim){
warning("Theta points should be either NULL or a matrix of same dimensionality as the trait distribution.")
theta <- matrix(theta, ncol=ndim)
}
nnodes <- nrow(theta)
p <- IRT.irfprob(object=class(object), A=A, B=B, xsi=xsi, theta=theta,
guess=guess, nnodes=nnodes, iIndex=iIndex, maxK=maxK, ... )
res <- matrix( stats::runif(nnodes * nI), nrow=nnodes, ncol=nI)
for(ii in 1:nI){
cat.success.ii <- (res[, ii] > t(apply(p[ii,, ], 2, cumsum)))
cat.success.ii[is.na(cat.success.ii)] <- FALSE
res[, ii] <- c(cat.success.ii %*% rep(1, maxK))
}
if ( nrow(object$resp)==nnodes ){
res[ is.na(object$resp) ] <- NA
}
class(res) <- "IRT.simulate"
return(res)
}
IRT.simulate.tam.mml <- simulate_mml
IRT.simulate.tam.mml.2pl <- simulate_mml
IRT.simulate.tam.mml.3pl <- simulate_mml
IRT.simulate.tam.mml.mfr <- simulate_mml |
cols <- c("athlete_display_name", "team_short_display_name",
"min", "fg", "fg3", "ft", "oreb", "dreb", "reb",
"ast", "stl", "blk", "to", "pf", "pts",
"starter", "ejected", "did_not_play", "active",
"athlete_jersey", "athlete_id", "athlete_short_name",
"athlete_headshot_href", "athlete_position_name",
"athlete_position_abbreviation", "team_name", "team_logo",
"team_id", "team_abbreviation", "team_color", "team_alternate_color")
test_that("ESPN - WBB Player Box", {
skip_on_cran()
x <- espn_wbb_player_box(game_id = 401276115)
expect_equal(colnames(x), cols)
expect_s3_class(x, "data.frame")
}) |
subFasID <- function(text = text){
id = list()
sum = 0
for (i in 1:length(text)) {
if(strsplit(text[i],split = "")[[1]][1] == ">"){
sum = sum + 1
id[[sum]] <- text[i]
}
}
return(unlist(id))
} |
split_vectors <- function(x, len_cuts){
if (length(x) != sum(len_cuts)) {
return(NULL)
}
cut_test <- x; dim_each_split <- len_cuts
entris <- list()
v = 1; s = 1
h <- dim_each_split[v]
for (j in 1:length(dim_each_split)) {
entris[[v]] <- cut_test[s:h]
s = s + dim_each_split[v]
v = v + 1
h <- h + dim_each_split[v]
}
return(entris)
} |
make.spaghetti = function(x, y, id, group = NULL, data,
col = NULL, pch = 16,
lty = 1, lwd = 1,
title = '', xlab = NA, ylab = NA,
legend.title = '', ylim = NULL,
cex.axis = 1, cex.title = 1,
cex.lab = 1, cex.leg = 1,
margins = NULL,
legend.inset = -0.3, legend.space = 1) {
par.init = par()
if (is.na(xlab)) xlab = deparse(substitute(x))
if (is.na(ylab)) ylab = deparse(substitute(y))
sort.x = order(data[ , deparse(substitute(x))])
data = data[sort.x, ]
na.x = which(is.na(data[ , deparse(substitute(x))]))
na.y = which(is.na(data[ , deparse(substitute(y))]))
na.either = union(na.x, na.y)
if (length(na.either) > 0) {
data = data[-na.either, ]
}
x = data[ , deparse(substitute(x))]
y = data[ , deparse(substitute(y))]
id = data[ , deparse(substitute(id))]
if (is.null(ylim)) ylim = range(y, na.rm = T)
if (length(ylim) !=2) warning('ylim should be a vector of length 2')
check = missing(group)
if (check) group = NULL
if (!check) group = data[ , deparse(substitute(group))]
par(bty = 'l')
if (is.null(group)) {
par(mar = c(4, 4, 2, 2))
if (is.null(col)) col = 'deepskyblue3'
}
if (!is.null(group)) {
par(mar = c(4, 4, 2, 7))
nlevs = length(unique(group))
if (is.null(col)) {
palette = c("
"
if (nlevs > 11) palette = rep(palette, 50)
palette = palette[1:nlevs]
}
if (!is.null(margins)) par(mar = margins)
if (!is.null(col)) palette = col
group = as.factor(group)
group.names = levels(group)
col = group
levels(col) = palette
col = as.character(col)
}
plot(y ~ x, col = col, pch = pch, main = title,
xlab = xlab, ylab = ylab, ylim = ylim,
cex.axis = cex.axis, cex.lab = cex.lab)
data.long = data.frame(x, y, id, col, stringsAsFactors = F)
seg.list = names(which(table(data.long$id) >= 2))
nsegm = length(seg.list)
for (i in 1:nsegm) {
subset = data.long[data.long$id == seg.list[i],]
for (j in 1:(nrow(subset)-1)) {
segments(x0 = subset$x[j], x1 = subset$x[j+1],
y0 = subset$y[j], y1 = subset$y[j+1],
col = subset$col[j], lwd = lwd)
}
}
if (!is.null(group)) {
par(xpd = T)
legend(x = "right", inset=c(legend.inset, 0), levels(group),
title = legend.title, pch = pch,
y.intersp = legend.space,
col = palette, bty = 'n', cex = cex.leg)
}
par(bty = par.init$bty, xpd = par.init$xpd, mar = par.init$mar)
} |
EvaluationModel.Criterion = function(criterion, ...) {
evaluationmodel = EvaluationModel()
evaluationmodel = evaluationmodel + criterion
args = list(...)
if (length(args)>0) {
for (i in 1:length(args)){
evaluationmodel = evaluationmodel + args[[i]]
}
}
return(evaluationmodel)
} |
if (FALSE) {
shiny.NormalAndTplot <- function(x=NULL, ...) {
UseMethod("shiny.NormalAndTplot")
}
shiny.NormalAndTplot.htest <- function(x=NULL, ..., NTmethod="htest") {
shiny.NormalAndTplot(NormalAndTplot.htest(x, ...), ..., NTmethod=NTmethod)
}
shiny.NormalAndTplot.default <- function(x=NULL, ...) {
distribution.name <- list(...)$distribution.name
if (is.null(distribution.name) ||
(!is.null(distribution.name) && distribution.name != "binomial"))
shiny.NormalAndTplot(NormalAndTplot.default(...))
else {
xlab <- list(...)$xlab
if (is.null(xlab))
xlab <- '"w = p = population proportion"'
shiny.NormalAndTplot(NormalAndTplot.default(..., xlab=xlab), df=1)
}
}
shiny.NormalAndTplot.NormalAndTplot <- function(x=NULL, ..., NT=attr(x, "call.list"), NTmethod="default") {
if (FALSE) {
list(mean0=ifelse(type=="hypothesis", mean0, NA),
mean1=mean1,
xbar=ifelse(type=="confidence", mean0, xbar),
sd=sd,
df=df,
n=n,
xlim=xlim,
ylim=ylim,
alpha.right=alpha.right,
alpha.left=alpha.left,
float=float,
ntcolors=ntcolors,
digits=digits,
distribution.name=distribution.name,
type=type,
zaxis=zaxis,
cex.z=cex.z,
cex.prob=cex.prob,
main=main,
xlab=xlab,
prob.labels=prob.labels,
cex.main=1,
key.axis.padding=4.5,
number.vars=1,
sub=NULL,
NTmethod=NTmethod,
power=power,
beta=beta,
...
)
}
mean0=NT$mean0
mean1=NT$mean1
xbar=NT$xbar
sd=NT$sd
logsd=log(sd, 10)
df=NT$df
n=NT$n
stderr=sd/sqrt(n)
logstderr=log(stderr, 10)
xlim.initial=NT$xlim
xlim.potential=NT$xlim + c(-1.1, 1.1)*stderr
xlim.xbar=NT$xlim + c(-1, 1)*stderr
diff.xlim=diff(NT$xlim)/100
ylim=NT$ylim
alpha.right=NT$alpha.right
alpha.left=NT$alpha.left
float=NT$float
ntcolors=NT$ntcolors
digits=NT$digits
distribution.name=NT$distribution.name
type=NT$type
zaxis=NT$zaxis
cex.z=NT$cex.z
cex.prob=NT$cex.prob
main=NT$main
xlab=NT$xlab
prob.labels=NT$prob.labels
cex.main=NT$cex.main
key.axis.padding=NT$key.axis.padding
number.vars=NT$number.vars
sub=NT$sub
power=NT$power
beta=NT$beta
x.xx=c("xbar","xbar1-xbar2")[number.vars]
list.dots <- list(...)
for (i in names(list.dots)) assign(i, list.dots[[i]])
if (type == "confidence" && is.na(mean0)) mean0 <- xbar
if (distribution.name %in% c("normal", "z", "binomial") && is.infinite(df)) df <- 0
mu1display <- (!(is.null(mean1)||is.na(mean1)))
xbardisplay <- (!(is.null(xbar)||is.na(xbar)))
mean1 <- if (mu1display) mean1 else mean0+2*stderr
xbar <- if (xbardisplay) xbar else mean0+1.8*stderr
ExpressionOrText <- function(x) {
if (is.character(x)) return(x)
xdp <-
if (length(x)>1)
deparse(x[[1]], width.cutoff=500)
else
deparse(x, width.cutoff=500)
xdp
}
numericInput10 <-
function (inputId, label, value, min = NA, max = NA, step = NA)
{
inputTag <- tags$input(id = inputId, type = "number", value = formatNoSci(value))
if (!is.na(min))
inputTag$attribs$min = min
if (!is.na(max))
inputTag$attribs$max = max
if (!is.na(step))
inputTag$attribs$step = step
tagList(label %AND% tags$label(label, `for` = inputId), inputTag)
}
formatNoSci <-
function (x)
{
if (is.null(x))
return(NULL)
format(x, scientific = FALSE, digits = 15)
}
`%AND%` <-
function (x, y)
{
if (!is.null(x) && !is.na(x))
if (!is.null(y) && !is.na(y))
return(y)
return(NULL)
}
normal.controls <-
tabsetPanel(
tabPanel("General",
shiny::column(6,
radioButtons("Binomial", NULL, c("Normal and t"="NorT", "Normal Approximation to the Binomial"="Binom"), if (distribution.name == "binomial") "Binom" else "NorT", inline=TRUE),
radioButtons("HypOrConf", NULL, c("Hypothesis"="hypothesis", "Confidence"="confidence"), type, inline=TRUE),
radioButtons("NDF", NULL, c("Ignore df slider"="idfs", "Ignore n slider"="ins", "Honor both df and n sliders"="hon2"),
switch(NTmethod,
default="hon2",
htest="ins",
power.htest="idfs",
binomial="idfs"), inline=TRUE)
),
shiny::column(3,
div(class="numericOverride", "ylim-hi",
numericInput10("ylim-hi", NULL, if (distribution.name == "binomial") 5 else ylim[2], min=.01, step=.1)),
checkboxGroupInput("mu1xbar", NULL, c("Display mu[1]", "Display xbar"),
c("Display mu[1]","Display xbar")[c(mu1display, xbardisplay)],
inline = TRUE)
),
shiny::column(3,
div(class="sliderInputOverride", "alpha/conf: left, center, right",
sliderInput("alpha", NULL, 0, 1, c(alpha.left, 1-alpha.right), .005, width="200px", sep="")),
div(class="sliderInputOverride", "n",
sliderInput("n", NULL, 1,
150,
n,
1,
animate=list(interval=2000), width="150px", sep=""))
)
),
tabPanel("Normal and t",
shiny::column(3,
div(class="sliderInputOverride", "mu[0]",
sliderInput("mu0", NULL, mean0-50*diff.xlim, mean0+50*diff.xlim, mean0, diff.xlim, width="150px", sep="")),
div(class="sliderInputOverride", "mu[a]",
sliderInput("mu1", NULL, mean1-50*diff.xlim, mean1+50*diff.xlim, mean1, diff.xlim, animate=list(interval=2000), width="150px", sep=""))
),
shiny::column(3,
div(class="sliderInputOverride", paste("w=",x.xx, sep=""),
sliderInput("xbar", NULL, xbar-50*diff.xlim, xbar+50*diff.xlim, xbar, diff.xlim, animate=list(interval=2000), width="150px", sep="")),
div(class="sliderInputOverride", "xlim", sliderInput("xlim", NULL, xlim.potential[1], xlim.potential[2], xlim.initial, 5*diff.xlim, width="150px", sep=""))
),
shiny::column(3,
div(class="sliderInputOverride", "log(sd, 10)",
sliderInput("logsd", NULL, -.5+logsd, .5+logsd, 0+logsd, .1, animate=list(interval=2000), width="150px", sep="")), br(),
paste(c("sd: lo","init","hi"), signif(10^(c(-.5+logsd, logsd, .5+logsd)), digits=3), sep="=", collapse=" "), br(), br()
),
shiny::column(3,
div(class="sliderInputOverride", "df (0=normal)",
sliderInput("df", NULL, 0, 200, df, 1, animate=list(interval=2000), width="150px", sep=""))
)
),
tabPanel("Normal approximation to the Binomial",
shiny::column(4,
div(class="sliderInputOverride", "p[0]",
sliderInput("p0", NULL, 0, 1, .5, .01, width="150px", sep="")),
div(class="sliderInputOverride", "p[1]",
sliderInput("p1", NULL, 0, 1, .8, .01, animate=list(interval=2000), width="150px", sep=""))
),
shiny::column(4,
div(class="sliderInputOverride", "p.hat",
sliderInput("p-hat", NULL, 0, 1, .75, .01, animate=list(interval=2000), width="150px", sep=""))
),
shiny::column(4,
div(class="sliderInputOverride", "xlimBinomial",
sliderInput("xlimBinomial", NULL, 0, 1, c(0,1), .1, width="150px", sep=""))
)
),
tabPanel("Display Options",
shiny::column(5,
checkboxGroupInput("displays", NULL, c("Power", "Beta", "Table", "Call", "z axes"),
c("Power"[NT$power], "Beta"[NT$beta], "Table"), inline=TRUE)
),
shiny::column(4,
checkboxGroupInput("probs", NULL, c("Prob values on Graph"="Values","Labels"), c("Values","Labels"), inline=TRUE)
),
shiny::column(3,
radioButtons("ntcolors", NULL, c("Original Colors"="original", Stoplight="stoplight"), ntcolors, inline=TRUE)
)),
tabPanel("Fonts",
shiny::column(2,
div(class="numericOverride", "digits-axis",
numericInput10("digits-axis", NULL, digits, min=1, step=1)), br(),
div(class="numericOverride", "digits-float",
numericInput10("digits-float", NULL, digits, min=1, step=1)), br()
),
shiny::column(2,
div(class="numericOverride", "cex-top-axis",
numericInput10("cex-top-axis", NULL, 1, min=.1, step=.1)), br(),
div(class="numericOverride", "cex-prob",
numericInput10("cex-prob", NULL, cex.prob, min=.1, step=.1)), br()
),
shiny::column(2,
div(class="numericOverride", "cex-z",
numericInput10("cex-z", NULL, cex.z, min=.1, step=.1)), br(),
div(class="numericOverride", "cex-table",
numericInput10("cex-table", NULL, 1.2, min=.1, step=.1)), br()
),
shiny::column(2,
div(class="numericOverride", "cex-main",
numericInput10("cex-main", NULL, 1.6, min=.1, step=.1)), br()
),
shiny::column(3,
div(class="numericOverride", "key-axis-padding",
numericInput10("key-axis-padding", NULL, 7, min=.1, step=.1)), br(),
div(class="numericOverride", "position.2",
numericInput10("position-2", NULL, .17, min=.1, step=.1)), br()
))
)
shiny::shinyApp(
ui =
shiny::fluidPage(
shiny::titlePanel(title=NULL, windowTitle="NormalAndT-12"),
sidebarLayout(mainPanel=mainPanel(
plotOutput("distPlot", width="100%", height="975px"),
textOutput("call")
),
sidebarPanel=sidebarPanel(
tags$head(tags$style(type="text/css",
".sliderInputOverride {display: inline-block; font-size: 12px; line-height: 12px}",
".jslider {display: inline-block; margin-top: 12px}")),
tags$head(tags$style(type="text/css",
".radio.inline {font-size: 11px; line-height: 10px}")),
tags$head(tags$style(type="text/css",
".checkbox.inline {font-size: 11px; line-height: 10px}")),
tags$head(tags$style(type="text/css", ".numericOverride {display: inline-block}",
"input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0;}")),
tags$head(tags$style(type="text/css", "
tags$head(tags$style(type="text/css", "
tags$head(tags$style(type="text/css", "
tags$head(tags$style(type="text/css", "
tags$head(tags$style(type="text/css", "
tags$head(tags$style(type="text/css", "
tags$head(tags$style(type="text/css", "
tags$head(tags$style(type="text/css", "
tags$head(tags$style(type="text/css", "
tags$head(tags$style(type="text/css", "
h6(
shiny::fluidRow(normal.controls))))
),
server =
function(input, output) {
NormalAndTInterface <- function(
distribution.name,
mean0,
mu1display,
mean1,
xbardisplay,
xbar,
sd,
df,
n,
xlim.lo,
xlim.hi,
ylim.lo,
ylim.hi,
alpha.right,
alpha.left,
float,
ntcolors,
digits=4,
digits.axis,
digits.float,
HypOrConf,
zaxes,
cex.z,
cex.prob,
cex.top.axis,
main,
xlab,
prob.labels,
cex.main,
key.axis.padding,
number.vars,
sub,
power=power,
beta=beta) {
NormalAndTplot(
mean0=mean0,
mean1=mean1,
xbar=xbar,
sd=sd,
df=df,
n=n,
xlim=c(xlim.lo, xlim.hi),
ylim=c(ylim.lo, ylim.hi),
alpha.right=alpha.right,
alpha.left=alpha.left,
float=float,
ntcolors=ntcolors,
digits=4,
digits.axis=digits.axis,
digits.float=digits.float,
distribution.name=distribution.name,
type=HypOrConf,
z1axis=zaxes,
zaxis=zaxes,
cex.z=cex.z,
cex.prob=cex.prob,
cex.top.axis=cex.top.axis,
main=main,
xlab=xlab,
prob.labels=prob.labels,
cex.main=cex.main,
key.axis.padding=key.axis.padding,
xhalf.multiplier=.65,
number.vars=number.vars,
sub=sub,
power=power,
beta=beta
)
}
ResultNT <- reactive({
NDF <- input$NDF
mean0.f <- if (input$HypOrConf=="hypothesis") input$mu0 else NA
mean1.f <- if ("Display mu[1]" %in% input$mu1xbar) input$mu1 else NA
xbar.f <- if ("Display xbar" %in% input$mu1xbar || input$HypOrConf=="confidence") input$xbar else NA
n.f <- switch(NDF,
idfs=input$n,
ins=NT$n,
hon2=input$n)
df.f <- switch(NDF,
idfs=number.vars*(input$n-1),
ins=input$df,
hon2=input$df)
stderr.f <- (10^input$logsd)/sqrt(n.f)
float.f <- "Values" %in% input$probs
zaxes.f <- "z axes" %in% input$displays
prob.labels.f <- "Labels" %in% input$probs
distribution.name.f <- if (df.f==0) "z" else "t"
xlim.lo.f <- input$xlim[1]
xlim.hi.f <- input$xlim[2]
xlab.f <- input$xlab
type.f <- input$HypOrConf
if (input$Binomial=="Binom") {
p0 <- input$p0
p1 <- input$p1
p.hat <- input$"p-hat"
n.f <- input$n
df.f <- Inf
sigma.p0 <- sqrt(p0*(1-p0)/n.f)
sigma.p1 <- sqrt(p1*(1-p1)/n.f)
s.p.hat <- sqrt(p.hat*(1-p.hat)/n.f)
z.calc <- (p.hat-p0)/sigma.p0
mean0.f <- if (input$HypOrConf=="hypothesis") p0 else NA
mean1.f <- if ("Display mu[1]" %in% input$mu1xbar) p1 else NA
xbar.f <- if ("Display xbar" %in% input$mu1xbar || input$HypOrConf=="confidence") p.hat else NA
stderr.f <- if (type=="hypothesis") sigma.p0 else s.p.hat
distribution.name.f <- "binomial"
xlim.lo.f <- input$xlimBinomial[1]
xlim.hi.f <- input$xlimBinomial[2]
xlab.f <- "w = p = population proportion"
}
NormalAndTInterface(
distribution.name=distribution.name.f,
mean0 =mean0.f,
mu1display ="Display mu[1]" %in% input$mu1xbar,
mean1 =mean1.f,
xbardisplay ="Display xbar" %in% input$mu1xbar,
xbar =xbar.f,
sd =stderr.f*sqrt(n.f),
df =df.f,
n =n.f,
xlim.lo =xlim.lo.f,
xlim.hi =xlim.hi.f,
ylim.lo =0,
ylim.hi =input$"ylim-hi",
alpha.right =1-input$alpha[2],
alpha.left =input$alpha[1],
float =float.f,
ntcolors =input$ntcolors,
digits =4,
digits.axis =input$"digits-axis",
digits.float =input$"digits-float",
HypOrConf =type.f,
zaxes =zaxes.f,
cex.z =input$"cex-z",
cex.prob =input$"cex-prob",
cex.top.axis =input$"cex-top-axis",
main=list(
MainSimpler(mean0.f, mean1.f, xbar.f, stderr.f, n.f, df.f, distribution.name.f,
digits=input$"digits-axis", number.vars=number.vars, type=type.f),
cex=input$"cex-main"
),
xlab =xlab.f,
prob.labels =prob.labels.f,
cex.main =input$"cex-main",
key.axis.padding =input$"key-axis-padding",
number.vars =number.vars,
sub =sub,
power ="Power" %in% input$displays,
beta ="Beta" %in% input$displays
)
})
Result <- reactive({
ResultNT()
})
output$distPlot <- renderPlot({
print(Result(), tablesOnPlot="Table" %in% input$displays,
cex.table=input$"cex-table",
scales=FALSE, prob=FALSE, position.2=input$"position-2")
})
output$call <- renderText({
if ("Call" %in% input$displays)
attr(ResultNT(), "call")
else ""
})
})
}
} |
library(sanitizers)
stackAddressSanitize(42) |
library(knotR)
filename <- "9_26.svg"
a <- reader(filename)
sym926 <- symmetry_object(a,celtic=FALSE,xver=27)
a <- symmetrize(a,sym926)
ou926 <- matrix(
c(
02,18,
20,04,
06,21,
17,07,
08,26,
15,10,
11,24,
23,13,
25,16
), byrow=TRUE,ncol=2)
jj <- knotoptim(filename,
symobj=sym926,
ou = ou926,
prob=0,
iterlim=1000,print.level=2
)
write_svg(jj,filename,safe=FALSE)
save(jj,file=sub('.svg','.S',filename)) |
mxScores <- function(x, control) {
if (OpenMx::imxHasDefinitionVariable(x)) {
return(mxScores_df(x = x, control = control))
} else {
return(mxScores_standard(x = x, control = control))
}
}
mxScores_standard <- function(x, control) {
p <- control$scores_info$p
mean_structure <- control$scores_info$mean_structure
p_star <- control$scores_info$p_star
p_star_seq <- seq_len(p_star)
p_star_means <- control$scores_info$p_star_means
exp_cov <- OpenMx::mxGetExpected(model = x, component = "covariance")
exp_cov_inv <- solve(exp_cov)
data_obs <- x$data$observed[, x$manifestVars, drop = FALSE]
N <- nrow(data_obs)
if (control$linear) {
q <- control$scores_info$q
q_seq <- control$scores_info$q_seq
p_unf <- control$scores_info$p_unf
A_deriv <- control$scores_info$A_deriv
S_deriv <- control$scores_info$S_deriv
m_deriv <- control$scores_info$m_deriv
F_RAM <- x$F$values
m <- t(x$M$values)
B <- solve(diag(x = 1, nrow = NROW(x$A$values)) - x$A$values)
E <- B %*% x$S$values %*% t(B)
FB <- F_RAM %*% B
jac <- matrix(0, nrow = p_star_means, ncol = q)
for (i in seq_len(q)) {
symm <- FB %*% A_deriv[[i]] %*% E %*% t(F_RAM)
jac[p_star_seq, i] <- lavaan::lav_matrix_vech(symm + t(symm) + FB %*% S_deriv[[i]] %*% t(FB))
}
for (i in seq_len(q)) {
jac[(p_star+1):p_star_means, i] <- FB %*% A_deriv[[i]] %*% B %*% m +
FB %*% m_deriv[[i]]
}
colnames(jac) <- names(x$output$estimate)
} else {
jac <- OpenMx::omxManifestModelByParameterJacobian(model = x)
}
if (mean_structure == FALSE) {jac <- jac[p_star_seq, , drop = FALSE]}
Dup <- lavaan::lav_matrix_duplication(n = p)
V <- 0.5 * t(Dup) %*% kronecker(X = exp_cov_inv, Y = exp_cov_inv) %*% Dup
if (mean_structure) {
V_m_cov <- matrix(data = 0, nrow = p_star_means, ncol = p_star_means)
V_m_cov[p_star_seq, p_star_seq] <- V
V_m_cov[(p_star + 1):p_star_means, (p_star + 1):p_star_means] <- exp_cov_inv
V <- V_m_cov
}
cd <- scale(x = data_obs, center = TRUE, scale = FALSE)
if (p == 1) {
mc <- matrix(apply(X = cd, MARGIN = 1,
FUN = function(x) {lavaan::lav_matrix_vech(x %*% t(x))}))
} else {
mc <- t(apply(X = cd, MARGIN = 1,
FUN = function(x) {lavaan::lav_matrix_vech(x %*% t(x))}))
}
vech_cov <- matrix(data = rep(x = lavaan::lav_matrix_vech(exp_cov), times = N),
byrow = TRUE, nrow = N, ncol = p_star)
md <- mc - vech_cov
if (mean_structure) {
exp_means <- OpenMx::mxGetExpected(model = x, component = "means")
means <- matrix(data = rep(x = exp_means, times = N), byrow = TRUE,
nrow = N, ncol = p)
mean_dev <- data_obs - means
md <- as.matrix(cbind(md, mean_dev))
}
scores <- md %*% V %*% jac
return(scores)
}
mxScores_df <- function(x, control) {
p <- control$scores_info$p
mean_structure <- control$scores_info$mean_structure
p_star <- control$scores_info$p_star
p_star_seq <- seq_len(p_star)
p_star_means <- control$scores_info$p_star_means
p_star_p_means_seq <- (p_star + 1):p_star_means
p_unf <- control$scores_info$p_unf
data_obs <- x$data$observed[, x$manifestVars, drop = FALSE]
N <- nrow(data_obs)
Ident <- diag(x = 1, nrow = p_unf)
Dup <- lavaan::lav_matrix_duplication(n = p)
scores <- matrix(NA, nrow = N, ncol = control$scores_info$q)
colnames(scores) <- names(x$output$estimate)
cd <- scale(x = data_obs, center = TRUE, scale = FALSE)
if (p == 1) {
mc <- matrix(apply(X = cd, MARGIN = 1,
FUN = function(x) {lavaan::lav_matrix_vech(x %*% t(x))}))
} else {
mc <- t(apply(X = cd, MARGIN = 1,
FUN = function(x) {lavaan::lav_matrix_vech(x %*% t(x))}))
}
if (mean_structure) {
md <- matrix(NA, nrow = N, ncol = p_star_means)
} else {
md <- matrix(NA, nrow = N, ncol = p_star)
}
df <- identify_definition_variables(x)
df_labels <- df[[1]]
df_nr <- length(df_labels)
df_data <- x$data$observed[, df[[2]], drop = FALSE]
df_indices <- seq_along(df_labels)
F_RAM <- x$F$values
A <- x$A$values
S <- x$S$values
m <- t(x$M$values)
B <- solve(Ident - A)
FB <- F_RAM %*% B
E <- B %*% S %*% t(B)
if (control$linear) {
q <- control$scores_info$q
q_seq <- control$scores_info$q_seq
A_deriv <- control$scores_info$A_deriv
S_deriv <- control$scores_info$S_deriv
m_deriv <- control$scores_info$m_deriv
jac <- matrix(0, nrow = p_star_means, ncol = q)
}
RAM_df <- rep(NA, times = df_nr)
RAM_df[which(df_labels %in% x$A$labels)] <- "A"
RAM_df[which(df_labels %in% x$S$labels)] <- "S"
RAM_df[which(df_labels %in% x$M$labels)] <- "M"
RAM_coord <- list()
for (j in df_indices) {
if (RAM_df[j] == "A") {
RAM_coord[[j]] <- which(x$A$labels == df_labels[j], arr.ind = TRUE)
}
if (RAM_df[j] == "S") {
RAM_coord[[j]] <- which(x$S$labels == df_labels[j], arr.ind = TRUE)
}
if (RAM_df[j] == "M") {
RAM_coord[[j]] <- which(t(x$M$labels) == df_labels[j], arr.ind = TRUE)
}
}
group <- transform(df_data,
group_ID = as.numeric(interaction(df_data,
drop = TRUE)))
unique_groups <- unique(group$group_ID)
for (i in unique_groups) {
group_rows <- which(group$group_ID == i)
group_n <- NROW(group_rows)
df_values <- as.numeric(group[group$group_ID == i, ][1, ])
for (j in df_indices){
if (RAM_df[j] == "A") {
A[RAM_coord[[j]]] <- df_values[j]
}
if (RAM_df[j] == "S") {
S[RAM_coord[[j]]] <- df_values[j]
}
if (RAM_df[j] == "M") {
m[RAM_coord[[j]]] <- df_values[j]
}
}
B <- solve(Ident - A)
FB <- F_RAM %*% B
E <- B %*% S %*% t(B)
exp_cov <- F_RAM %*% E %*% t(F_RAM)
exp_cov_inv <- solve(exp_cov)
if (control$linear) {
for (j in seq_len(q)) {
symm <- FB %*% A_deriv[[j]] %*% E %*% t(F_RAM)
jac[p_star_seq, j] <- lavaan::lav_matrix_vech(symm + t(symm) + FB %*% S_deriv[[j]] %*% t(FB))
}
if (mean_structure) {
for (j in seq_len(q)) {
jac[(p_star+1):p_star_means, j] <- FB %*% A_deriv[[j]] %*% B %*% m +
FB %*% m_deriv[[j]]
}
}
} else {
x <- OpenMx::omxSetParameters(model = x, labels = df$labels,
values = df_values[df_indices])
x <- suppressMessages(OpenMx::mxRun(model = x, useOptimizer = FALSE))
jac <- OpenMx::omxManifestModelByParameterJacobian(model = x)
}
if (mean_structure == FALSE) {jac <- jac[p_star_seq, , drop = FALSE]}
V <- 0.5 * t(Dup) %*% kronecker(X = exp_cov_inv, Y = exp_cov_inv) %*% Dup
if (mean_structure) {
V_m_cov <- matrix(data = 0, nrow = p_star_means, ncol = p_star_means)
V_m_cov[p_star_seq, p_star_seq] <- V
V_m_cov[p_star_p_means_seq, p_star_p_means_seq] <- exp_cov_inv
V <- V_m_cov
}
vech_cov <- matrix(data = rep(x = lavaan::lav_matrix_vech(exp_cov),
times = group_n),
byrow = TRUE, nrow = group_n, ncol = p_star)
md[group_rows, 1:p_star] <- mc[group_rows, ] - vech_cov
if (mean_structure) {
means <- matrix(data = rep(x = FB %*% m, times = group_n), byrow = TRUE,
nrow = group_n, ncol = p)
means_dev <- as.matrix(data_obs[group_rows, ]) - means
md[group_rows, (p_star+1):p_star_means] <- means_dev
}
scores[group_rows, ] <- md[group_rows, ] %*% V %*% jac
}
scores
}
identify_definition_variables <- function(x) {
definition_variables <- c()
for (i in 1:length(x@matrices)) {
definition_variables <- c(definition_variables,
sapply(x@matrices[[i]]$labels,
OpenMx::imxIsDefinitionVariable))
}
definition_variables <- names(which(definition_variables))
list(labels = definition_variables,
data = sub(".*\\.", "", definition_variables))
} |
isPositiveIntegerOrNaOrNanScalarOrNull <- function(argument, default = NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL) {
checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = TRUE, n = 1, zeroAllowed = TRUE, negativeAllowed = FALSE, positiveAllowed = TRUE, nonIntegerAllowed = FALSE, naAllowed = TRUE, nanAllowed = TRUE, infAllowed = FALSE, message = message, argumentName = argumentName)
} |
source('~/git/derivmkts/R/simprice.R')
library(testthat)
load('~/git/derivmkts/tests/testthat/option_testvalues.Rdata')
test_that(paste('simprice', 'works'), {
correct = simprice_S
unknown = do.call(simprice, simprice_params)
expect_equivalent(as.data.frame(correct), unknown[-1])
}
)
print('simprice okay') |
knitr::opts_chunk$set(echo = TRUE)
library(medfate) |
test_that("praatScriptCentreOfGravity default arguments works", {
script <- paste(
"\nselect Sound 'sampleName$'",
"\nfast$ = \"yes\"",
"\nTo Spectrum: fast$",
"\ncog_2 = Get centre of gravity: 2",
"\nprint 'cog_2:0' 'newline$'",
"\nRemove\n", sep="")
expect_equal(praatScriptCentreOfGravity(), script)
})
test_that("praatScriptCentreOfGravity with powers works", {
script <- paste(
"\nselect Sound 'sampleName$'",
"\nfast$ = \"yes\"",
"\nTo Spectrum: fast$",
"\ncog_2 = Get centre of gravity: 2",
"\nprint 'cog_2:0' 'newline$'",
"\ncog_1 = Get centre of gravity: 1",
"\nprint 'cog_1:0' 'newline$'",
"\ncog_0_666666666666667 = Get centre of gravity: 0.666666666666667",
"\nprint 'cog_0_666666666666667:0' 'newline$'",
"\nRemove\n", sep="")
expect_equal(praatScriptCentreOfGravity(powers = c(2,1,2/3)), script)
})
test_that("praatScriptCentreOfGravity without fast setting works", {
script <- paste(
"\nselect Sound 'sampleName$'",
"\nfast$ = \"no\"",
"\nTo Spectrum: fast$",
"\ncog_2 = Get centre of gravity: 2",
"\nprint 'cog_2:0' 'newline$'",
"\nRemove\n", sep="")
expect_equal(praatScriptCentreOfGravity(spectrum.fast = F), script)
}) |
stri_match_all <- function(str, ..., regex)
{
stri_match_all_regex(str, regex, ...)
}
stri_match_first <- function(str, ..., regex)
{
stri_match_first_regex(str, regex, ...)
}
stri_match_last <- function(str, ..., regex)
{
stri_match_last_regex(str, regex, ...)
}
stri_match <- function(str, ..., regex, mode = c("first", "all", "last"))
{
mode <- match.arg(mode)
switch(mode,
first = stri_match_first_regex(str, regex, ...),
last = stri_match_last_regex(str, regex, ...),
all = stri_match_all_regex(str, regex, ...))
}
stri_match_all_regex <- function(str, pattern,
omit_no_match = FALSE, cg_missing = NA_character_,
..., opts_regex = NULL)
{
if (!missing(...))
opts_regex <- do.call(stri_opts_regex, as.list(c(opts_regex, ...)))
.Call(C_stri_match_all_regex, str, pattern, omit_no_match, cg_missing, opts_regex)
}
stri_match_first_regex <- function(str, pattern, cg_missing = NA_character_, ...,
opts_regex = NULL)
{
if (!missing(...))
opts_regex <- do.call(stri_opts_regex, as.list(c(opts_regex, ...)))
.Call(C_stri_match_first_regex, str, pattern, cg_missing, opts_regex)
}
stri_match_last_regex <- function(str, pattern, cg_missing = NA_character_, ...,
opts_regex = NULL)
{
if (!missing(...))
opts_regex <- do.call(stri_opts_regex, as.list(c(opts_regex, ...)))
.Call(C_stri_match_last_regex, str, pattern, cg_missing, opts_regex)
} |
RDestimate<-function(formula, data, subset=NULL, cutpoint=NULL, bw=NULL, kernel="triangular", se.type="HC1", cluster=NULL, verbose=FALSE, model=FALSE, frame=FALSE) {
call<-match.call()
if(missing(data)) data<-environment(formula)
formula<-as.Formula(formula)
X<-model.frame(formula,rhs=1,lhs=0,data=data,na.action=na.pass)[[1]]
Y<-model.frame(formula,rhs=0,lhs=NULL,data=data,na.action=na.pass)[[1]]
if(!is.null(subset)){
X<-X[subset]
Y<-Y[subset]
if(!is.null(cluster)) cluster<-cluster[subset]
}
if (!is.null(cluster)) {
cluster<-as.character(cluster)
robust.se <- function(model, cluster){
M <- length(unique(cluster))
N <- length(cluster)
K <- model$rank
dfc <- (M/(M - 1)) * ((N - 1)/(N - K))
uj <- apply(estfun(model), 2, function(x) tapply(x, cluster, sum));
rcse.cov <- dfc * sandwich(model, meat. = crossprod(uj)/N)
rcse.se <- coeftest(model, rcse.cov)
return(rcse.se[2,2])
}
}
na.ok<-complete.cases(X)&complete.cases(Y)
if(length(all.vars(formula(formula,rhs=1,lhs=F)))>1){
type<-"fuzzy"
Z<-model.frame(formula,rhs=1,lhs=0,data=data,na.action=na.pass)[[2]]
if(!is.null(subset)) Z<-Z[subset]
na.ok<-na.ok&complete.cases(Z)
if(length(all.vars(formula(formula,rhs=1,lhs=F)))>2)
stop("Invalid formula. Read ?RDestimate for proper syntax")
} else {
type="sharp"
}
covs<-NULL
if(length(formula)[2]>1){
covs<-model.frame(formula,rhs=2,lhs=0,data=data,na.action=na.pass)
if(!is.null(subset)) covs<-subset(covs,subset)
na.ok<-na.ok&complete.cases(covs)
covs<-subset(covs,na.ok)
}
X<-X[na.ok]
Y<-Y[na.ok]
if(type=="fuzzy") Z<-as.double(Z[na.ok])
if(is.null(cutpoint)) {
cutpoint<-0
if(verbose) cat("No cutpoint provided. Using default cutpoint of zero.\n")
}
if(frame) {
if(type=="sharp") {
if (!is.null(covs))
dat.out<-data.frame(X,Y,covs)
else
dat.out<-data.frame(X,Y)
} else {
if (!is.null(covs))
dat.out<-data.frame(X,Y,Z,covs)
else
dat.out<-data.frame(X,Y,Z)
}
}
if(is.null(bw)) {
bw<-IKbandwidth(X=X,Y=Y,cutpoint=cutpoint,kernel=kernel, verbose=verbose)
bws<-c(bw,.5*bw,2*bw)
names(bws)<-c("LATE","Half-BW","Double-BW")
} else if (length(bw)==1) {
bws<-c(bw,.5*bw,2*bw)
names(bws)<-c("LATE","Half-BW","Double-BW")
} else {
bws<-bw
}
o<-list()
o$type<-type
o$call<-call
o$est<-vector(length=length(bws),mode="numeric")
names(o$est)<-names(bws)
o$bw<-as.vector(bws)
o$se<-vector(mode="numeric")
o$z<-vector(mode="numeric")
o$p<-vector(mode="numeric")
o$obs<-vector(mode="numeric")
o$ci<-matrix(NA,nrow=length(bws),ncol=2)
o$model<-list()
if(type=="fuzzy") {
o$model$firststage<-list()
o$model$iv<-list()
}
o$frame<-list()
o$na.action<-which(na.ok==FALSE)
class(o)<-"RD"
X<-X-cutpoint
Xl<-(X<0)*X
Xr<-(X>=0)*X
Tr<-as.integer(X>=0)
for(bw in bws){
ibw<-which(bw==bws)
sub<- X>=(-bw) & X<=(+bw)
if(kernel=="gaussian")
sub<-TRUE
w<-kernelwts(X,0,bw,kernel=kernel)
o$obs[ibw]<-sum(w>0)
if(type=="sharp"){
if(verbose) {
cat("Running Sharp RD\n")
cat("Running variable:",all.vars(formula(formula,rhs=1,lhs=F))[1],"\n")
cat("Outcome variable:",all.vars(formula(formula,rhs=F,lhs=1))[1],"\n")
if(!is.null(covs)) cat("Covariates:",paste(names(covs),collapse=", "),"\n")
}
if(!is.null(covs)) {
data<-data.frame(Y,Tr,Xl,Xr,covs,w)
form<-as.formula(paste("Y~Tr+Xl+Xr+",paste(names(covs),collapse="+",sep=""),sep=""))
} else {
data<-data.frame(Y,Tr,Xl,Xr,w)
form<-as.formula(Y~Tr+Xl+Xr)
}
mod<-lm(form,weights=w,data=subset(data,w>0))
if(verbose==TRUE) {
cat("Model:\n")
print(summary(mod))
}
o$est[ibw]<-coef(mod)["Tr"]
if (is.null(cluster)) {
o$se[ibw]<-coeftest(mod,vcovHC(mod,type=se.type))[2,2]
} else {
o$se[ibw]<-robust.se(mod,cluster[na.ok][w>0])
}
o$z[ibw]<-o$est[ibw]/o$se[ibw]
o$p[ibw]<-2*pnorm(abs(o$z[ibw]),lower.tail=F)
o$ci[ibw,]<-c(o$est[ibw]-qnorm(.975)*o$se[ibw],o$est[ibw]+qnorm(.975)*o$se[ibw])
if(model) o$model[[ibw]]=mod
if(frame) o$frame[[ibw]]=dat.out
} else {
if(verbose){
cat("Running Fuzzy RD\n")
cat("Running variable:",all.vars(formula(formula,rhs=1,lhs=F))[1],"\n")
cat("Outcome variable:",all.vars(formula(formula,rhs=F,lhs=1))[1],"\n")
cat("Treatment variable:",all.vars(formula(formula,rhs=1,lhs=F))[2],"\n")
if(!is.null(covs)) cat("Covariates:",paste(names(covs),collapse=", "),"\n")
}
if(!is.null(covs)) {
data<-data.frame(Y,Tr,Xl,Xr,Z,covs,w)
form<-as.Formula(paste(
"Y~Z+Xl+Xr+",paste(names(covs),collapse="+"),
"|Tr+Xl+Xr+",paste(names(covs),collapse="+"),sep=""))
form1<-as.Formula(paste("Z~Tr+Xl+Xr+",paste(names(covs),collapse="+",sep="")))
} else {
data<-data.frame(Y,Tr,Xl,Xr,Z,w)
form<-as.Formula(Y~Z+Xl+Xr|Tr+Xl+Xr)
form1<-as.formula(Z~Tr+Xl+Xr)
}
mod1<-lm(form1,weights=w,data=subset(data,w>0))
mod<-ivreg(form,weights=w,data=subset(data,w>0))
if(verbose==TRUE) {
cat("First stage:\n")
print(summary(mod1))
cat("IV-RD:\n")
print(summary(mod))
}
o$est[ibw]<-coef(mod)["Z"]
if (is.null(cluster)) {
o$se[ibw]<-coeftest(mod,vcovHC(mod,type=se.type))[2,2]
} else {
o$se[ibw]<-robust.se(mod,cluster[na.ok][w>0])
}
o$z[ibw]<-o$est[ibw]/o$se[ibw]
o$p[ibw]<-2*pnorm(abs(o$z[ibw]),lower.tail=F)
o$ci[ibw,]<-c(o$est[ibw]-qnorm(.975)*o$se[ibw],o$est[ibw]+qnorm(.975)*o$se[ibw])
if(model) {
o$model$firststage[[ibw]]<-mod1
o$model$iv[[ibw]]=mod
}
if(frame) o$frame=dat.out
}
}
return(o)
} |
plot.tune_xrnet <- function(x, p = NULL, pext = NULL, ...) {
if (is.null(x$fitted_model$alphas) || !is.null(p) || !is.null(pext)) {
if (is.null(x$fitted_model$alphas)) {
xval <- log(as.numeric(rownames(x$cv_mean)))
cverr <- x$cv_mean[, 1]
cvsd <- x$cv_sd[, 1]
xlab <- "log(Penalty)"
xopt_val <- log(x$opt_penalty)
} else {
if (!is.null(p) && !is.null(pext)) {
stop("Please only specify either penalty or penalty_ext, cannot specify both at the same time")
} else if (!is.null(p)) {
if (p == "opt") {
p <- x$opt_penalty
}
p_idx <- match(p, x$fitted_model$penalty)
if (is.na(p_idx)) {
stop("The penalty value 'p' is not in the fitted model")
}
xval <- log(as.numeric(colnames(x$cv_mean)))
cverr <- x$cv_mean[p_idx, ]
cvsd <- x$cv_sd[p_idx, ]
xlab <- "log(External Penalty)"
xopt_val <- log(x$opt_penalty_ext)
} else {
if (pext == "opt") {
pext <- x$opt_penalty_ext
}
pext_idx <- match(pext, x$fitted_model$penalty_ext)
if (is.na(pext_idx)) {
stop("The penalty value 'p' is not in the fitted model")
}
xval <- log(as.numeric(rownames(x$cv_mean)))
cverr <- x$cv_mean[, pext_idx]
cvsd <- x$cv_sd[, pext_idx]
xlab <- "log(Penalty)"
xopt_val <- log(x$opt_penalty)
}
}
graphics::plot(
x = xval,
y = cverr,
ylab = paste0("Mean CV Error (", x$loss, ")"),
xlab = xlab,
ylim=range(c(cverr - cvsd, cverr + cvsd)),
type = "n"
)
graphics::arrows(
xval,
cverr - cvsd,
xval,
cverr + cvsd,
length = 0.025,
angle = 90,
code = 3,
col = "lightgray"
)
graphics::points(
x = xval,
y = cverr,
col = "dodgerblue4",
pch = 16,
)
graphics::abline(v = xopt_val, col = "firebrick")
} else {
cvgrid <- x$cv_mean
cvgrid <- cvgrid[rev(seq_len(nrow(cvgrid))), ]
cvgrid <- cvgrid[ , rev(seq_len(ncol(cvgrid)))]
minx <- log(x$opt_penalty_ext)
miny <- log(x$opt_penalty)
contour_colors <- c("
"
graphics::filled.contour(
x = log(as.numeric(colnames(cvgrid))),
y = log(as.numeric(rownames(cvgrid))),
z = t(cvgrid),
col = colorRampPalette(contour_colors)(25),
xlab = "log(External Penalty)",
ylab = "log(Penalty)",
plot.axes = {axis(1); axis(2); points(minx, miny, col = "red", pch = 16)}
)
}
} |
plotPotential = function(filename, main_title = NULL){
if(filename$file_type != "full"){
stop("This function will not work with a reduced data set.")
}
plot(x = filename$time, y = filename$potential, lwd = 2, col = "blue",
type = "l", xlab = "time (sec)", ylab = "potential (V)",
main = main_title)
grid()
} |
tbplots.by.var <-
function (xmat, log = FALSE, logx = FALSE, notch = FALSE, xlab = "Measured Variables",
ylab = "Reported Values", main = "", label = NULL, plot.order = NULL,
xpos = NA, las = 1, cex = 1, adj = 0.5, colr = 8, ...)
{
zz <- var2fact(xmat)
x <- zz[, 1]
y <- as.numeric(zz[, 2])
if (is.null(label))
label <- sort(unique(x))
tbplots(split(y, x), log = log, logx = logx, notch = notch,
xlab = xlab, ylab = ylab, main = main, label = label,
plot.order = plot.order, xpos = xpos, las = las, cex = cex,
adj = adj, colr = colr, ...)
invisible()
} |
`cddews` <-
function (data, filter.number = 1, family = "DaubExPhase", switch = "direction",
correct = TRUE, verbose = FALSE, smooth = TRUE, sm.filter.number = 4,
sm.family = "DaubExPhase", levels = 3:6, type = "hard", policy = "LSuniversal",
by.level = FALSE, value = 0, dev = var)
{
now <- proc.time()[1:2]
if (nrow(data) != ncol(data))
stop(paste("Sorry, but imwd has only been coded for square images!"))
data.wd <- imwd(data, filter.number = filter.number, family = family,
type = "station")
RawPer <- getdata(data.wd, switch = switch)
if (smooth == TRUE) {
cat("Now starting to smooth\n")
test <- RawPer
NS <- dim(test)[1]
for (i in 1:NS) {
tmp <- test[i, , ]
tmp.imwd <- imwd(tmp, filter.number = sm.filter.number,
family = sm.family)
tmp.imwdTH <- threshold.imwd(tmp.imwd, levels = levels,
type = type, policy = policy, value = value,
by.level = by.level, dev = dev, compression = FALSE)
tmp.imwr <- imwr(tmp.imwdTH)
test[i, , ] <- tmp.imwr
}
RawPer <- test
if (correct == FALSE) {
cat("OK, so you've chosen to use the raw (uncorrected) periodogram!\n")
l <- list(S = RawPer, datadim = dim(data), filter.number = filter.number,
family = "DaubExPhase", structure = switch, nlevels = data.wd$nlevels,
correct = correct, smooth = smooth, sm.filter.number = sm.filter.number,
sm.family = sm.family, levels = levels, type = type,
policy = policy, date = date())
}
if (correct == TRUE) {
A <- D2Amat(-data.wd$nlevels, filter.number = data.wd$filter$filter.number,
family = data.wd$filter$family, switch = switch,
verbose = verbose)
Ainv <- solve(A)
first.last.d <- data.wd$fl.dbase$first.last.d
first.last.c <- data.wd$fl.dbase$first.last.c
firstD <- first.last.d[data.wd$nlevels, 1]
lastD <- first.last.d[data.wd$nlevels, 2]
LengthD <- lastD - firstD + 1
LEVELS <- data.wd$nlevels
TMP <- matrix(aperm(RawPer), nrow = 3 * LEVELS, ncol = LengthD^2,byrow = TRUE)
TMP2 <- Ainv %*% TMP
data2 <- array(0, dim(RawPer))
for (i in (1:(3 * LEVELS))) {
data2[i, , ] <- matrix(TMP2[i, ], nrow = LengthD,
ncol = LengthD, byrow = TRUE)
}
speed <- proc.time()[1:2] - now
cat("Took ", sum(speed), "seconds \n")
l <- list(S = data2, datadim = dim(data), filter.number = filter.number,
family = "DaubExPhase", structure = switch, nlevels = data.wd$nlevels,
correct = correct, smooth = smooth, sm.filter.number = sm.filter.number,
sm.family = sm.family, levels = levels, type = type,
policy = policy, date = date())
}
class(l) <- "cddews"
return(l)
}
if (smooth == FALSE) {
if (correct == FALSE) {
cat("OK, so you've chosen to use the raw (uncorrected periodogram!\n")
l <- list(S = RawPer, datadim = dim(data), filter.number = filter.number,
family = "DaubExPhase", structure = switch, nlevels = data.wd$nlevels,
correct = correct, smooth = smooth, date = date())
}
if (correct == TRUE) {
A <- D2Amat(-data.wd$nlevels, filter.number = data.wd$filter$filter.number,
family = data.wd$filter$family, switch = switch,
verbose = verbose)
Ainv <- solve(A)
first.last.d <- data.wd$fl.dbase$first.last.d
first.last.c <- data.wd$fl.dbase$first.last.c
firstD <- first.last.d[data.wd$nlevels, 1]
lastD <- first.last.d[data.wd$nlevels, 2]
LengthD <- lastD - firstD + 1
LEVELS <- data.wd$nlevels
TMP <- matrix(aperm(RawPer), nrow = 3 * LEVELS, ncol = LengthD^2, byrow = TRUE)
TMP2 <- Ainv %*% TMP
data2 <- array(0, dim(RawPer))
for (i in (1:(3 * LEVELS))) {
data2[i, , ] <- matrix(TMP2[i, ], nrow = LengthD,
ncol = LengthD, byrow = TRUE)
}
speed <- proc.time()[1:2] - now
cat("Took ", sum(speed), "seconds \n")
l <- list(S = data2, datadim = dim(data), filter.number = filter.number,
family = "DaubExPhase", structure = switch, nlevels = data.wd$nlevels,
correct = correct, smooth = smooth, date = date())
}
class(l) <- "cddews"
return(l)
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.