code
stringlengths 1
13.8M
|
---|
plot.gmci <-
function (x, mattext, col = c("grey", "red"), main, las = 1,
xlab = "To", ylab = "From", xnames, ynames, cex = 1, fig = 2,
opacity_factor, ...)
{
if (missing(main)) {
main = paste0(round(100 * (1 - x$alpha), 3), "% ", x$method)
}
n = nrow(x$par)
if (missing(mattext)) {
mattext = matrix(paste0("[", signif(x$lower, fig), "; ",
signif(x$upper, fig), "]"), n, n)
mattext[which(is.na(x$lower) & is.na(x$upper))] = ""
}
plotM(x$par, mattext, col, main, las, xlab, ylab, xnames,
ynames, cex, fig, opacity_factor)
} |
"benchmarkData"
"benchmarkResults"
"benchmarkResultsNoTransform"
MiniBenchmarkRvsCpp <- function(
data = PCMBaseCpp::benchmarkData,
includeR = TRUE,
includeTransformationTime = TRUE,
nRepsCpp = 10L,
listOptions = list(
PCMBase.Lmr.mode = 11, PCMBase.Threshold.EV = 0, PCMBase.Threshold.SV = 0),
doProf = FALSE, RprofR.out = "RprofR.out", RprofCpp.out = "RprofCpp.out") {
listCurrentOptions <- options()
do.call(options, listOptions)
modelTypes <- MGPMDefaultModelTypes()
res <- do.call(rbind, lapply(seq_len(nrow(data)), function(i) {
tree <- data$tree[[i]]
X <- data$X[[i]]
model <- data$model[[i]]
if(!includeTransformationTime) {
model <- PCMApplyTransformation(model)
}
metaIR <- PCMInfo(X, tree, model)
metaICpp <- PCMInfoCpp(X, tree, model, metaI = metaIR)
valueR <- valueCpp <- NA_real_
if(includeR) {
if(doProf) {
do.call(
Rprof,
c(list(filename = RprofR.out),
getOption("PCMBaseCpp.ArgsRprofR",
list(append = TRUE, line.profiling = TRUE))))
}
timeR <- system.time({
valueR <- PCMLik(X, tree, model, metaI = metaIR)
})[3]
if(doProf) {
Rprof(NULL)
}
} else {
timeR <- NA_real_
}
if(doProf) {
do.call(
Rprof,
c(list(filename = RprofCpp.out),
getOption("PCMBaseCpp.ArgsRprofCpp", list(append = TRUE, line.profiling = TRUE))))
}
timeCpp <- system.time(
valueCpp <-replicate(
nRepsCpp,
PCMLik(X, tree, model, metaI = metaICpp))[1])[3] / nRepsCpp
if(doProf) {
Rprof(NULL)
}
data.frame(
N = PCMTreeNumTips(tree),
R = PCMTreeNumParts(tree),
mapping = I(list(names(attr(model, "modelTypes"))[attr(model, "mapping")])),
type = I(list(class(model))),
PCMBase.Lmr.mode = PCMOptions()$PCMBase.Lmr.mode,
logLik = valueR,
logLikCpp = valueCpp,
timeR = unname(timeR),
timeCpp = unname(timeCpp))
}))
resetOptionsStatus <- try(do.call(options, listCurrentOptions), silent = TRUE)
if(inherits(resetOptionsStatus, "try-error")) {
warning(
paste0(
"Error while resetting options at the end of a call to MiniBenchmarkRvsCpp: ",
toString(resetOptionsStatus)))
}
res
}
BenchmarkRvsCpp <- function(
ks = c(1, 2, 4, 8),
includeR = TRUE,
includeTransformationTime = TRUE,
optionSets = NULL,
includeParallelMode = TRUE,
doProf = FALSE, RprofR.out = "RprofR.out", RprofCpp.out = "RprofCpp.out",
verbose = FALSE) {
benchmarkData <- PCMBaseCpp::benchmarkData
X <- tree <- model <- modelBM <- modelOU <- modelType <- N <- R <- mapping <-
PCMBase.Lmr.mode <- logLik <- logLikCpp <- timeR <- timeCpp <- NULL
resultList <- lapply(ks, function(k) {
if(is.null(optionSets)) {
optionSets <- DefaultBenchmarkOptions(k, includeParallelMode)
}
resultList <- lapply(names(optionSets), function(oset) {
if(verbose) {
cat("Performing benchmark for k: ", k, "; optionSet: ", oset, "...\n")
}
fk <- findBiggestFactor(k, 8)
ds <- seq_len(fk)
nRB <- k / fk
testData <- rbindlist(list(
benchmarkData[, list(
k = k,
modelType = "MGPM (A-F)",
options = oset,
tree,
X = lapply(X, function(x) x[rep(ds, nRB),, drop=FALSE]),
model = lapply(model, function(m) PCMExtractDimensions(m, dims = ds, nRepBlocks = nRB)))],
benchmarkData[, list(
k = k,
modelType = "BM (B)",
options = oset,
tree,
X = lapply(X, function(x) x[rep(ds, nRB),, drop=FALSE]),
model = lapply(modelBM, function(m) PCMExtractDimensions(m, dims = ds, nRepBlocks = nRB)))],
benchmarkData[, list(
k = k,
modelType = "OU (E)",
options = oset,
tree,
X = lapply(X, function(x) x[rep(ds, nRB),, drop=FALSE]),
model = lapply(modelOU, function(m) PCMExtractDimensions(m, dims = ds, nRepBlocks = nRB)))]))
resultData <- MiniBenchmarkRvsCpp(
data = testData,
includeR = includeR,
includeTransformationTime = includeTransformationTime,
listOptions = optionSets[[oset]],
doProf = doProf, RprofR.out = RprofR.out, RprofCpp.out = RprofCpp.out)
resultData <- cbind(testData[, list(k, modelType, options)], resultData)
if(verbose) {
print(resultData[, list(
k, modelType, N, R, mode = PCMBase.Lmr.mode, logLik,
logLikCpp, timeR, timeCpp)])
}
resultData
})
rbindlist(resultList, use.names = TRUE)
})
rbindlist(resultList, use.names = TRUE)
}
DefaultBenchmarkOptions <- function(k, includeParallelMode) {
if(k == 1) {
os <- list(
`serial / 1D-multiv.` = list(PCMBase.Lmr.mode = 11,
PCMBase.Threshold.EV = 0,
PCMBase.Threshold.SV = 0,
PCMBase.Use1DClasses = FALSE),
`serial / 1D-univar.` = list(PCMBase.Lmr.mode = 11,
PCMBase.Threshold.EV = 0,
PCMBase.Threshold.SV = 0,
PCMBase.Use1DClasses = TRUE))
if(includeParallelMode) {
os <- c(
os,
list(
`parallel / 1D-multiv.` = list(PCMBase.Lmr.mode = 21,
PCMBase.Threshold.EV = 0,
PCMBase.Threshold.SV = 0,
PCMBase.Use1DClasses = FALSE),
`parallel / 1D-univar.` = list(PCMBase.Lmr.mode = 21,
PCMBase.Threshold.EV = 0,
PCMBase.Threshold.SV = 0,
PCMBase.Use1DClasses = TRUE)) )
}
os
} else {
os <- list(
`serial / 1D-multiv.` = list(PCMBase.Lmr.mode = 11,
PCMBase.Threshold.EV = 0,
PCMBase.Threshold.SV = 0,
PCMBase.Use1DClasses = FALSE))
if(includeParallelMode) {
os <- c(
os,
list(`parallel / 1D-multiv.` = list(PCMBase.Lmr.mode = 21,
PCMBase.Threshold.EV = 0,
PCMBase.Threshold.SV = 0,
PCMBase.Use1DClasses = FALSE)))
}
os
}
}
findBiggestFactor <- function(k, fMax) {
f <- fMax
while(f >= 1) {
if(k %% f == 0) {
break
}
f <- f - 1
}
f
} |
ROC.s <-
function(x1=NULL,x2=NULL, by=NULL) {
args <- match.call()
if(!is.null(args$x1) & !is.null(args$x2) & !is.null(args$by))
stop("Factor interaction terms (by argument) are not allowed in surface interactions")
if(is.null(args$x1) & is.null(args$x2))
stop("x1 or x2 must be indicated")
if(!is.null(args$x1) & is.null(args$x2) & is.null(args$by)) {
cov = c("", deparse(args$x1, backtick = TRUE, width.cutoff = 500))
} else if (!is.null(args$x1) & !is.null(args$x2) & is.null(args$by)) {
cov = c(deparse(args$x1, backtick = TRUE, width.cutoff = 500),deparse(args$x2, backtick = TRUE, width.cutoff = 500))
} else if (!is.null(args$x1) & is.null(args$x2) & !is.null(args$by)) {
cov = c(deparse(args$by, backtick = TRUE, width.cutoff = 500), deparse(args$x1, backtick = TRUE, width.cutoff = 500))
} else {
stop("Invalid expression")
}
res <- list(cov=cov)
res
} |
expected <- eval(parse(text="FALSE"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(1, 0, 0, 0, NA, 6, 0, 0, 0, 14, 3, 0, 15, 0, 0, 8), .Dim = c(4L, 4L)))"));
do.call(`is.logical`, argv);
}, o=expected); |
"mlb_players_18" |
source("ESEUR_config.r")
par(mar=MAR_default+c(0.0, 0.7, 0, 0))
pal_col=rainbow(3)
points_and_smooth=function(x_vals, y_vals, col_num, pch)
{
points(x_vals, y_vals, col=pal_col[col_num], bg=2, pch=pch, cex=0.7)
}
processor=read.csv(paste0(ESEUR_dir, "ecosystems/cpudb/processor.csv.xz"), as.is=TRUE)
specint2k6=read.csv(paste0(ESEUR_dir, "ecosystems/cpudb/spec_int2006.csv.xz"), as.is=TRUE)
specint2k0=read.csv(paste0(ESEUR_dir, "ecosystems/cpudb/spec_int2000.csv.xz"), as.is=TRUE)
specint95=read.csv(paste0(ESEUR_dir, "ecosystems/cpudb/spec_int1995.csv.xz"), as.is=TRUE)
specint92=read.csv(paste0(ESEUR_dir, "ecosystems/cpudb/spec_int1992.csv.xz"), as.is=TRUE)
all=merge(processor, specint2k6, by="processor_id",
suffixes=c(".proc", ".spec_int2k6"), all=TRUE)
all=merge(all, specint2k0, by="processor_id",
suffixes=c(".spec_int2k6", ".spec_int2k0"), all=TRUE)
all=merge(all, specint95, by="processor_id",
suffixes=c(".spec_int2k0", ".spec_int95"), all=TRUE)
all=merge(all, specint92, by="processor_id",
suffixes=c(".spec_int95", ".spec_int92"), all=TRUE)
all[all[["date"]]=="","date"]=NA
dates=as.POSIXct(all[["date"]])
noturbo=is.na(all[["max_clock"]])
all[noturbo,"max_clock"]=all[noturbo, "clock"]
spec92to95=mean(all[["basemean.spec_int95"]]/all[["basemean.spec_int92"]], na.rm=TRUE)
spec95to2k0=mean(all[["basemean.spec_int2k0"]]/all[["basemean.spec_int95"]], na.rm=TRUE)
spec2k0to2k6=mean(all[["basemean.spec_int2k6"]]/all[["basemean.spec_int2k0"]], na.rm=TRUE)
no95=is.na(all[["basemean.spec_int95"]])
no2k0=is.na(all[["basemean.spec_int2k0"]])
no2k6=is.na(all[["basemean.spec_int2k6"]])
all[no95, "basemean.spec_int95"]=spec92to95 * all[no95, "basemean.spec_int92"]
all[no2k0,"basemean.spec_int2k0"]=spec95to2k0 * all[no2k0, "basemean.spec_int95"]
all[no2k6, "basemean.spec_int2k6"]=spec2k0to2k6 * all[no2k6, "basemean.spec_int2k0"]
all[["perfnorm"]]=all[["basemean.spec_int2k6"]]/all[["tdp"]]
scaleclk =min(all[["max_clock"]], na.rm=TRUE)
scaletrans=min(all[["transistors"]], na.rm=TRUE)
scaletdp =min(all[["tdp"]], na.rm=TRUE)
scaleperf =min(all[["basemean.spec_int2k6"]], na.rm=TRUE)
scaleperfnorm =min(all[["perfnorm"]], na.rm=TRUE)
plot(dates, all[["transistors"]]/scaletrans, log="y", col=pal_col[1], bg=1, pch=22,
xlab="Date of introduction", ylab="Relative frequency increase\n\n")
points_and_smooth(dates, all[["transistors"]]/scaletrans, 1, 22)
points_and_smooth(dates, all[["max_clock"]]/scaleclk, 2, 20)
points_and_smooth(dates, all[["tdp"]]/scaletdp, 3, 24)
legend("topleft",
c("Transistors", "Clock", "Power"),
bty="n", fill=pal_col, cex=1.2) |
count.function <-
function(nucleotides, spec.no, seqlength){
count <- mat.or.vec(nr = 4, nc = seqlength)
letter_vector <- c("A","C","G","T")
for(i in 1:seqlength){
count[1,i] = length(which(nucleotides[,i+2] == letter_vector[1]))
count[2,i] = length(which(nucleotides[,i+2] == letter_vector[2]))
count[3,i] = length(which(nucleotides[,i+2] == letter_vector[3]))
count[4,i] = length(which(nucleotides[,i+2] == letter_vector[4]))
}
rownames(count) <- c("A", "C", "G", "T")
return(count)
} |
gpat_create_grid = function(x, brick = FALSE){
header = gpat_header_parser(x)
x1 = header$start_x
y1 = header$start_y
x2 = header$start_x + header$res_x * header$n_cols
y2 = header$start_y + header$res_y * header$n_rows
single_cell_creator = function(x1, y1, x2, y2){
list(rbind(c(x1, y1), c(x1, y2), c(x2, y2), c(x2, y1), c(x1, y1)))
}
my_bb = single_cell_creator(x1, y1, x2, y2) %>%
st_polygon() %>%
st_sfc()
if (header$proj_4 != ""){
my_bb = my_bb %>%
st_set_crs(value = header$proj_4)
}
my_grid = gpat_st_make_grid(my_bb,
n = c(header$n_cols, header$n_rows),
brick = brick)
my_grid
}
gpat_header_parser = function(x){
x = readLines(x)
res_x = str_sub(x[5], start=6) %>% as.double()
res_y = str_sub(x[9], start=6) %>% as.double()
start_x = str_sub(x[4], start=6) %>% as.double()
start_y = str_sub(x[7], start=6) %>% as.double()
n_rows = str_sub(x[10], start=7) %>% as.integer()
n_cols = str_sub(x[11], start=7) %>% as.integer()
proj_wkt = str_sub(x[12], start=7)
desc = str_split(x[13], "\\|", simplify = TRUE)
size = as.numeric(desc[str_which(desc, "-z")+1])
if (length(size) == 0){
size = as.numeric(gsub("\\D", "", desc[str_which(desc, "--size=")]))
}
shift = as.numeric(desc[str_which(desc, "-f")+1])
if (length(shift) == 0){
shift = as.numeric(gsub("\\D", "", desc[str_which(desc, "--shift=")]))
}
if (size != shift){
stop("We don't support overlapping grids (where size != shift). Open a new issue on our github page if you want this option")
}
invisible(capture.output({proj_4 = tryCatch({st_crs(wkt = proj_wkt)$proj4string},
error = function(e) "")}))
data.frame(res_x = res_x, res_y = res_y,
start_x = start_x, start_y = start_y,
n_rows = n_rows, n_cols = n_cols,
proj_4 = proj_4, stringsAsFactors = FALSE)
}
gpat_st_make_grid = function(x,
n = c(10, 10),
brick = FALSE){
offset = st_bbox(x)[c(1, 4)]
bb = st_bbox(x)
n = rep(n, length.out = 2)
nx = n[1]
ny = n[2]
xc = seq(offset[1], bb[3], length.out = nx + 1)
yc = seq(offset[2], bb[2], length.out = ny + 1)
ret = vector("list", nx * ny)
square = function(x1, y1, x2, y2){
st_polygon(list(matrix(c(x1, x2, x2, x1, x1, y1, y1, y2, y2, y1), 5)))
}
for (i in 1:nx) {
for (j in 1:ny) {
ret[[(j - 1) * nx + i]] = square(xc[i], yc[j], xc[i + 1], yc[j + 1])
}
}
my_grid = st_sf(geometry = st_sfc(ret, crs = st_crs(x)))
if (brick){
ids_y = rep(c(1, 1, 2, 2), length.out = ny)
ids = numeric(length = nrow(my_grid))
spatial_ids = seq_len(nx %/% 2 + 1)
for (i in seq_len(ny)){
ids_y_i = ids_y[i]
if (ids_y_i == 1){
ids[seq_len(nx) + (i - 1) * nx] = rep(spatial_ids, each = 2, length.out = nx)
} else if (ids_y_i == 2){
if (ids_y[i-1] != ids_y[i]){
spatial_ids = spatial_ids + (nx %/% 2 + 1)
ids[seq_len(nx) + (i - 1) * nx] = c(spatial_ids[1], rep(spatial_ids[-1], each = 2, length.out = nx-1))
} else {
ids[seq_len(nx) + (i - 1) * nx] = c(spatial_ids[1], rep(spatial_ids[-1], each = 2, length.out = nx-1))
spatial_ids = spatial_ids + (nx %/% 2 + 1)
}
}
}
n = c(length(spatial_ids), max(ids) / length(spatial_ids))
my_grid = aggregate(my_grid, by = list(ids), mean) %>%
st_cast(to = "POLYGON", warn = FALSE)
my_grid$Group.1 = NULL
}
df_ids = create_ids(n[1], n[2])
my_grid = st_sf(data.frame(my_grid, df_ids))
return(my_grid)
}
create_ids = function(num_c, num_r){
m = 1
m_row = 1
m_col = 1
result = data.frame(col = integer(length = num_r * num_c),
row = integer(length = num_r * num_c))
for (i in seq_len(num_r)){
for (j in seq_len(num_c)){
result[m, "col"] = m_col
result[m, "row"] = m_row
m = m + 1
m_col = m_col + 1
}
m_col = 1
m_row = m_row + 1
}
return(result)
} |
polygon.svg <- function(points = NULL,
fill,
fill.opacity,
stroke,
stroke.width,
stroke.opacity,
fill.rule,
style.sheet = NULL) {
if (is.null(points)) {
stop("[ERROR] Basic line elements are required (points)!")
} else {
if (!is.matrix(points)) {
points <- as.matrix(points)
}
}
if (!is.null(style.sheet)) {
style.sheet.ele <- paste(style.sheet, collapse = ";")
} else {
style.sheet.ele <- ""
}
if (!missing(fill)) {
style.sheet.ele <- paste0(style.sheet.ele, "fill:", fill, ";")
}
if (!missing(fill.opacity)) {
style.sheet.ele <- paste0(style.sheet.ele, "fill-opacity:", fill.opacity, ";")
}
if (!missing(stroke)) {
style.sheet.ele <- paste0(style.sheet.ele, "stroke:", stroke, ";")
}
if (!missing(stroke.width)) {
style.sheet.ele <- paste0(style.sheet.ele, "stroke-width:", stroke.width, ";")
}
if (!missing(stroke.opacity)) {
style.sheet.ele <- paste0(style.sheet.ele, "stroke-opacity:", stroke.opacity, ";")
}
if (!missing(fill.rule)) {
style.sheet.ele <- paste0(style.sheet.ele, "fill-rule", fill.rule, ";")
}
if (style.sheet.ele != "") {
style.sheet.ele <- paste0('style="', style.sheet.ele, '"')
}
points.ele <- lapply(1:nrow(points), function(x) { paste(points[x, 1], points[x, 2], sep = ",") })
points.ele <- paste(points.ele, collapse = " ")
polygon.svg.ele <- sprintf('<polygon points="%s" %s />', points.ele, style.sheet.ele)
return(polygon.svg.ele)
} |
erf <- function(x) {
return(2 * pnorm(x * sqrt(2)) - 1)
}
isonormdist <- function(z, area, mu, sigma) {
u <- z[1]
v <- z[2]
return(exp(-mu * (1 / 4) *
((erf((sqrt(area) - (2 * u)) / (2 * sqrt(2) * sigma))) +
(erf((sqrt(area) + (2 * u)) / (2 * sqrt(2) * sigma)))) *
((erf((sqrt(area) - (2 * v)) / (2 * sqrt(2) * sigma))) +
(erf((sqrt(area) + (2 * v)) / (2 * sqrt(2) * sigma))))))
}
espA <- function(par, area, extent, tolerance = 1e-6) {
ext <- extent
return(ext - cubature::adaptIntegrate(isonormdist,
area = area,
mu = par$mu,
sigma = par$sigma,
tol = tolerance,
lowerLimit = rep(-sqrt(ext) / 2, 2),
upperLimit = rep(sqrt(ext) / 2, 2))[[1]])
} |
beta_AD=function(K=K,nk=nk,alpha=alpha,X=X,y=y){
n=nrow(X);p=ncol(X)
M=W=c(rep(1,K));
mr=matrix(rep(0,K*nk),ncol=nk)
R=matrix(rep(0,n*nk), ncol=n);Io=matrix(rep(0,nk*K), ncol=nk);
for (i in 1:K){
mr[i,]=sample(1:n,nk,replace=T);
r=matrix(c(1:nk,mr[i,]),ncol=nk,byrow=T);
R[t(r)]=1
Io[i,]=r[2,]
X1=R%*%X;y1=R%*%y;
ux=solve(crossprod(X1))
W[i]= sum(diag(t(ux)%*% ux))
M[i]= det(X1%*%t(X1))
}
XD= X[Io[which.max(M),],];yD= y[Io[which.max(M),]]
betaD=solve(crossprod(XD))%*%t(XD)%*% yD
XA= X[Io[which.min(W),],];yA= y[Io[which.min(W),]]
betaA=solve(crossprod(XA))%*%t(XA)%*% yA
return(list(betaA=betaA,betaD=betaD))
} |
if (is.null(argv) | length(argv) < 1) {
cat("Usage: silenceTwitterAccount.r user1 [user2 user3 ...]\n\n")
cat("Calls rtweet::post_silence() for the given users.\n")
cat("NB: Needs a modified version of rtweet and a twitter token.\n\n")
q()
}
if (!requireNamespace("rtweet", quietly=TRUE))
stop("Please install `rtweet`.", call. = FALSE)
if (Sys.getenv("TWITTER_PAT") == "")
stop("Please setup a 'TWITTER_PAT' using `rtweet`.", call. = FALSE)
library(rtweet)
if (is.na(match("post_silence", ls("package:rtweet"))))
stop("This needs a version of 'rtweet' with the post_silence() function", call. = FALSE)
for (arg in argv) rtweet::post_silence(arg) |
ginhomAverage <- function(xyt,spatial.intensity,temporal.intensity,time.window=xyt$tlim,rvals=NULL,correction="iso",suppresswarnings=FALSE,...){
time.window <- sort(as.integer(time.window))
verifyclass(spatial.intensity,"spatialAtRisk")
verifyclass(temporal.intensity,"temporalAtRisk")
density <- as.im(spatial.intensity)
approxscale <- mean(sapply(xyt$t[xyt$t>=time.window[1] & xyt$t<=time.window[2]],temporal.intensity))
den <- density
den$v <- den$v * approxscale
xyt$t <- as.integer(xyt$t)
numsamp <- min(c(200,xyt$n))
if(!suppresswarnings){
if (is.null(rvals)){
gin <- pcfinhom(xyt[sample(1:xyt$n,numsamp,replace=FALSE)],lambda=den,...)
}
else{
gin <- pcfinhom(xyt[sample(1:xyt$n,numsamp,replace=FALSE)],lambda=den,r=rvals,...)
}
}
else{
if (is.null(rvals)){
suppressWarnings(gin <- pcfinhom(xyt[sample(1:xyt$n,numsamp,replace=FALSE)],lambda=den,...))
}
else{
suppressWarnings(gin <- pcfinhom(xyt[sample(1:xyt$n,numsamp,replace=FALSE)],lambda=den,r=rvals,...))
}
}
r <- gin$r
nam <- names(gin)
nam <- nam[nam!="r"]
tls <- sapply(time.window[1]:time.window[2],function(x){sum(xyt$t==x)})
tls <- (time.window[1]:time.window[2])[tls!=0]
ntls <- length(tls)
pb <- txtProgressBar(min=tls[1],max=rev(tls)[1],style=3)
if(!suppresswarnings){
pcf <- lapply(tls,function(t){setTxtProgressBar(pb,t);den<-density;den$v<-den$v*temporal.intensity(t);try(pcfinhom(xyt[xyt$t==t],lambda=den,r=r,...))})
}
else{
suppressWarnings(pcf <- lapply(tls,function(t){setTxtProgressBar(pb,t);den<-density;den$v<-den$v*temporal.intensity(t);try(pcfinhom(xyt[xyt$t==t],lambda=den,r=r,...))}))
}
close(pb)
li <- as.list(pcf[[1]])
ct <- 1
if(ntls>1){
for(i in 2:ntls){
if ((class(pcf[[i]])[1]!="try-error")&&(npoints(xyt[xyt$t==tls[i]])>1)){
li <- add.list(li,as.list(pcf[[i]]))
ct <- ct + 1
}
}
}
li <- smultiply.list(li,1/ct)
ginhom <- gin
for (n in nam){
idx <- which(names(ginhom)==n)
ginhom[[idx]] <- li[[idx]]
}
attr(ginhom,"correction") <- correction
cat("Returning an average of",ct,"curves\n")
return(ginhom)
}
KinhomAverage <- function(xyt,spatial.intensity,temporal.intensity,time.window=xyt$tlim,rvals=NULL,correction="iso",suppresswarnings=FALSE){
time.window <- sort(as.integer(time.window))
verifyclass(spatial.intensity,"spatialAtRisk")
verifyclass(temporal.intensity,"temporalAtRisk")
density <- as.im(spatial.intensity)
approxscale <- mean(sapply(xyt$t[xyt$t>=time.window[1] & xyt$t<=time.window[2]],temporal.intensity))
den <- density
den$v <- den$v * approxscale
xyt$t <- as.integer(xyt$t)
numsamp <- min(c(200,xyt$n))
if(!suppresswarnings){
if (is.null(rvals)){
Kin <- Kinhom(xyt[sample(1:xyt$n,numsamp,replace=FALSE)],lambda=den)
}
else{
Kin <- Kinhom(xyt[sample(1:xyt$n,numsamp,replace=FALSE)],lambda=den,r=rvals)
}
}
else{
if (is.null(rvals)){
suppressWarnings(Kin <- Kinhom(xyt[sample(1:xyt$n,numsamp,replace=FALSE)],lambda=den))
}
else{
suppressWarnings(Kin <- Kinhom(xyt[sample(1:xyt$n,numsamp,replace=FALSE)],lambda=den,r=rvals))
}
}
r <- Kin$r
nam <- names(Kin)
nam <- nam[nam!="r"]
tls <- sapply(time.window[1]:time.window[2],function(x){sum(xyt$t==x)})
tls <- (time.window[1]:time.window[2])[tls!=0]
ntls <- length(tls)
pb <- txtProgressBar(min=tls[1],max=rev(tls)[1],style=3)
if(!suppresswarnings){
pcf <- lapply(tls,function(t){setTxtProgressBar(pb,t);den<-density;den$v<-den$v*temporal.intensity(t);try(Kinhom(xyt[xyt$t==t],lambda=den,r=r))})
}
else{
suppressWarnings(pcf <- lapply(tls,function(t){setTxtProgressBar(pb,t);den<-density;den$v<-den$v*temporal.intensity(t);try(Kinhom(xyt[xyt$t==t],lambda=den,r=r))}))
}
close(pb)
li <- as.list(pcf[[1]])
ct <- 1
if(ntls>1){
for(i in 2:ntls){
if ((class(pcf[[i]])[1] != "try-error")&&(npoints(xyt[xyt$t==tls[i]])>1)){
li <- add.list(li,as.list(pcf[[i]]))
ct <- ct + 1
}
}
}
li <- smultiply.list(li,1/ct)
Kinhom <- Kin
for (n in nam){
idx <- which(names(Kinhom)==n)
Kinhom[[idx]] <- li[[idx]]
}
attr(Kinhom,"correction") <- correction
cat("Returning an average of",ct,"curves\n")
return(Kinhom)
}
spatialparsEst <- function(gk,sigma.range,phi.range,spatial.covmodel,covpars=c(),guess=FALSE){
ok <- function(panel){
return(panel)
}
corchoice <- c()
sigma <- c()
phi <- c()
sigmamin <- sigma.range[1]
sigmamax <- sigma.range[2]
phimin <- phi.range[1]
phimax <- phi.range[2]
idx <- which(names(gk)==attr(gk,"correction"))
env <- NULL
if (attr(gk,"fname") == "g[inhom]"){
panfun <- function(p){
env <<- environment()
r <- gk$r
egr <- suppressWarnings(exp(sapply(r,gu,sigma=p$sigma,phi=p$phi,model=spatial.covmodel,additionalparameters=covpars))-1)
gvals <- gk[[idx]]
if (p$transform!="none"){
if (p$transform=="log"){
gvals <- log(gk[[idx]])
egr <- log(egr)
}
}
plot(NULL,main="g[inhom]",xlim=c(0,max(r,na.rm=TRUE)),ylim=c(0,max(c(gvals[!is.infinite(gvals)&!is.nan(gk[[idx]])],egr[!is.infinite(egr)&!is.nan(egr)]))),xlab="r",ylab="g_inhom(r)",sub=paste(spatial.covmodel,"covariance function"))
lines(r,gvals)
lines(r,egr,col="orange")
legend("topright",lty=c("solid","solid"),col=c("black","orange"),legend=c("Empirical","Theoretical"))
return(p)
}
}
else if (attr(gk,"fname") == "K[inhom]"){
panfun <- function(p){
env <<- environment()
r <- gk$r
egr <- suppressWarnings(exp(sapply(r,gu,sigma=p$sigma,phi=p$phi,model=spatial.covmodel,additionalparameters=covpars))-1)
rdiff <- diff(r[1:2])
kest <- rdiff * egr[1] * 2 * pi * r[1]
for(i in 2:length(r)){
kest[i] <- kest[i-1] + rdiff * egr[i] * 2 * pi * r[i]
}
gvals <- gk[[idx]]
if (p$transform!="none"){
if (p$transform=="^1/4"){
gvals <- (gk[[idx]])^(1/4)
kest <- kest^(1/4)
}
}
plot(NULL,main="K[inhom]",xlim=c(0,max(r,na.rm=TRUE)),ylim=c(0,max(c(gvals[!is.infinite(gvals)],kest[!is.infinite(kest)]))),xlab="r",ylab="K_inhom(r)",sub=paste(spatial.covmodel,"covariance function"))
lines(r,gvals)
lines(r,kest,col="orange")
legend("topleft",lty=c("solid","solid"),col=c("black","orange"),legend=c("Empirical","Theoretical"))
return(p)
}
}
else{
stop("Argument gk is not of correct class, see ?ginhomAverage, ?KinhomAverage")
}
pancontrol <- rp.control("Parameter Estimation",aschar=FALSE)
if (attr(gk,"fname") == "g[inhom]"){
rp.radiogroup(pancontrol,variable=transform,vals=c("none","log"),action=panfun,initval="none")
}
else if (attr(gk,"fname") == "K[inhom]"){
rp.radiogroup(pancontrol,variable=transform,vals=c("none","^1/4"),action=panfun,initval="^1/4")
}
r <- gk$r
if(guess){
if (attr(gk,"fname") == "g[inhom]"){
spfun <- function(sigmaphi){
egr <- suppressWarnings(exp(sapply(r,gu,sigma=sigmaphi[1],phi=sigmaphi[2],model=spatial.covmodel,additionalparameters=covpars))-1)
S <- suppressWarnings((egr-gk[[idx]])^2)
S[is.infinite(S)] <- NA
W <- 1/r^2
W[is.infinite(W)] <- NA
sidx <- !(is.na(W) | is.na(S))
ans <- sum((W*S)[sidx],na.rm=TRUE)/sum(W[sidx])
return(ans)
}
ops <- optim(c(sigmamin + (sigmamax-sigmamin)/2,phimin + (phimax-phimin)/2),spfun)
sigmainit <- ops$par[1]
phiinit <- ops$par[2]
}
else if (attr(gk,"fname") == "K[inhom]"){
sigphifun <- function(sigphi){
egr <- suppressWarnings(exp(sapply(r,gu,sigma=sigphi[1],phi=sigphi[2],model=spatial.covmodel,additionalparameters=covpars))-1)
rdiff <- diff(r[1:2])
kest <- rdiff * egr[1] * 2 * pi * r[1]
for(i in 2:length(r)){
kest[i] <- kest[i-1] + rdiff * egr[i] * 2 * pi * r[i]
}
gvals <- gk[[idx]]
gvals <- (gk[[idx]])^(1/4)
kest <- kest^(1/4)
gvals[is.infinite(gvals)] <- NA
kest[is.infinite(kest)] <- NA
S <- suppressWarnings((kest-gvals)^2)
S[is.infinite(S)] <- NA
W <- 1/r^2
W[is.infinite(W)] <- NA
sidx <- !(is.na(W) | is.na(S))
ans <- sum((W*S)[sidx],na.rm=TRUE)/sum(W[sidx])
return(ans)
}
ops <- optim(c(sigmamin + (sigmamax-sigmamin)/2,phimin + (phimax-phimin)/2),sigphifun)
sigmainit <- ops$par[1]
phiinit <- ops$par[2]
}
}
else{
sigmainit <- sigmamin + (sigmamax-sigmamin)/2
phiinit <- phimin + (phimax-phimin)/2
}
rp.slider(pancontrol,variable=sigma,from=sigmamin,to=sigmamax,initval=sigmainit,action=panfun,showvalue=TRUE)
rp.slider(pancontrol,variable=phi,from=phimin,to=phimax,initval=phiinit,action=panfun,showvalue=TRUE)
rp.button(pancontrol,action=ok,title="OK",quitbutton=TRUE)
hhh = as.numeric(tkwinfo("height",pancontrol$.handle))+50
www = 300
ggg = sprintf("%dx%d",www,hhh)
tkwm.geometry(pancontrol$.handle,ggg)
rp.block(pancontrol)
dev.off()
sigma <- get("p",envir=env)$sigma
phi <- get("p",envir=env)$phi
return(list(sigma=sigma,phi=phi))
}
Cvb <- function(xyt,spatial.intensity,N=100,spatial.covmodel,covpars){
verifyclass(spatial.intensity,"im")
sar <- spatialAtRisk(list(X=spatial.intensity$xcol,Y=spatial.intensity$yrow,Zm=t(spatial.intensity$v)))
gsx <- length(xvals(sar))
gsy <- length(yvals(sar))
xy <- cbind(rep(xvals(sar),gsy),rep(yvals(sar),each=gsx))
wt <- as.vector(zvals(sar))
wt[is.na(wt)] <- 0
sidx <- sample(1:(gsx*gsy),N,prob=wt)
xy <- xy[sidx,]
pd <- as.vector(pairdist(xy))
cvb <- function(nu,sigma,phi,theta){
return(mean(exp(exp(-nu*theta)*gu(pd,sigma=sigma,phi=phi,model=spatial.covmodel,additionalparameters=covpars))-1))
}
return(cvb)
}
thetaEst <- function(xyt,spatial.intensity=NULL,temporal.intensity=NULL,sigma,phi,theta.range=c(0,10),N=100,spatial.covmodel="exponential",covpars=c()){
ok <- function(panel){
return(panel)
}
if (inherits(spatial.intensity,"spatialAtRisk")){
spatial.intensity <- as.im(spatial.intensity)
}
if (is.null(spatial.intensity)){
spatial.intensity <- density(xyt)
}
if (is.null(temporal.intensity)){
temporal.intensity <- muEst(xyt)
}
else{
if (!inherits(temporal.intensity,"temporalAtRisk")){
temporal.intensity <- temporalAtRisk(temporal.intensity,tlim=xyt$tlim,xyt=xyt)
}
if(!all(xyt$tlim==attr(temporal.intensity,"tlim"))){
stop("Incompatible temporal.intensity, integer time limits (tlim and temporal.intensity$tlim) do not match")
}
}
thetamin <- theta.range[1]
thetamax <- theta.range[2]
tlim <- as.integer(xyt$tlim)
cvb <- Cvb(xyt=xyt,spatial.intensity=spatial.intensity,N=N,spatial.covmodel=spatial.covmodel,covpars=covpars)
xytlim <- sort(as.integer(xyt$tlim))
tvec <- xytlim[1]:xytlim[2]
if(length(tvec)==1){
stop("Insufficiently many time intervals: type as.integer(xyt$tlim) into console")
}
theta <- c()
panfun <- function(p){
sigma <- as.numeric(p$sigma)
phi <- as.numeric(p$phi)
theta <- p$theta
uqt <- as.numeric(names(table(as.integer(xyt$t))))
tfit <- sapply(uqt,temporal.intensity)
autocov <- acf(table(as.integer(xyt$t)) - tfit,type="covariance",plot=FALSE)
r <- 0:(length(autocov$acf)-1)
plot(r,autocov$acf,type="l",main="Autocovariance",xlab="lag",ylab="acov(lag)")
legend("topright",lty=c("solid","solid"),col=c("black","orange"),legend=c("Empirical","Theoretical"))
abline(h=0)
rseq <- seq(r[1],r[length(r)],length.out=100)
theo <- sapply(rseq,cvb,sigma=sigma,phi=phi,theta=theta)
lines(rseq,theo*(autocov$acf[1]/theo[1]),type="l",col="orange")
return(p)
}
pancontrol <- rp.control("Parameter Estimation",aschar=FALSE)
rp.textentry(pancontrol,variable=sigma,initval=sigma,action=panfun)
rp.textentry(pancontrol,variable=phi,initval=phi,action=panfun)
rp.slider(pancontrol,variable=theta,from=thetamin,to=thetamax,initval=(thetamax-thetamin)/2,action=panfun,showvalue=TRUE)
rp.button(pancontrol,action=ok,title="OK",quitbutton=TRUE)
rp.block(pancontrol)
dev.off()
theta <- as.numeric(tclvalue(pancontrol$theta.tcl))
return(theta)
}
lambdaEst <- function(xyt,...){
UseMethod("lambdaEst")
}
lambdaEst.stppp <- function(xyt,weights=c(),edge=TRUE,bw=NULL,...){
ok <- function(panel){
return(panel)
}
adjust <- c()
plotdata <- c()
pow <- c()
if(is.null(bw)){
bw <- resolve.2D.kernel(NULL,x = xyt,adjust = 1)$sigma
}
varlist <- list(bw=bw,adjust=1,plotdata=TRUE,pow=1)
env <- NULL
panfun <- function(p){
env <<- environment()
bw <- as.numeric(p$bw)
adjust <- as.numeric(p$adjust)
d <- density(xyt,bandwidth=bw,weights=weights,edge=edge)
plotden <- d
plotden$v <- (d$v / diff(xyt$tlim))^p$pow
plot(plotden,main="Density",...)
if(p$plotdata){
points(xyt,pch="+",cex=0.5)
}
return(p)
}
panfun(varlist)
pancontrol <- rp.control("Density Estimation")
rp.textentry(pancontrol,variable=bw,initval=bw,action=panfun,title="bandwidth")
rp.checkbox(pancontrol,variable=plotdata,action=panfun,labels = "Plot Data",initval = TRUE)
rp.slider(pancontrol,variable=pow,from=0,to=1,initval=1,action=panfun,showvalue=TRUE,title="colour adjustment")
rp.button(pancontrol,action=ok,title="OK",quitbutton=TRUE)
rp.block(pancontrol)
dev.off()
return(get("d",envir=env))
}
lambdaEst.ppp <- function(xyt,weights=c(),edge=TRUE,bw=NULL,...){
ok <- function(panel){
return(panel)
}
adjust <- c()
plotdata <- c()
pow <- c()
if(is.null(bw)){
bw <- resolve.2D.kernel(NULL,x = xyt,adjust = 1)$sigma
}
varlist <- list(bw=bw,adjust=1,plotdata=TRUE,pow=1)
env <- NULL
panfun <- function(p){
env <<- environment()
bw <- as.numeric(p$bw)
adjust <- as.numeric(p$adjust)
d <- density(xyt,sigma=bw,weights=weights,edge=edge)
plotden <- d
plotden$v <- d$v^p$pow
plot(plotden,main="Density",...)
if(p$plotdata){
points(xyt,pch="+",cex=0.5)
}
return(p)
}
panfun(varlist)
pancontrol <- rp.control("Density Estimation")
rp.textentry(pancontrol,variable=bw,initval=bw,action=panfun,title="bandwidth")
rp.checkbox(pancontrol,variable=plotdata,action=panfun,labels = "Plot Data",initval = TRUE)
rp.slider(pancontrol,variable=pow,from=0,to=1,initval=1,action=panfun,showvalue=TRUE,title="colour adjustment")
rp.button(pancontrol,action=ok,title="OK",quitbutton=TRUE)
rp.block(pancontrol)
dev.off()
return(get("d",envir=env))
}
muEst <- function(xyt,...){
verifyclass(xyt,"stppp")
t <- as.integer(xyt$t)
tlim <- as.integer(xyt$tlim)
tseq <- tlim[1]:tlim[2]
counts <- sapply(tseq,function(x){sum(t==x)})
sm <- lowess(tseq,sqrt(counts),...)
return(temporalAtRisk(sm$y^2,tlim=tlim,xyt=xyt))
}
density.stppp <- function(x,bandwidth=NULL,...){
density.ppp(x,...,sigma=bandwidth)
} |
maxsel.asymp.test<-function(x1,x2=NULL,y,type)
{
maxselcrit<-maxsel(x1=x1,x2=x2,y=y,type=type)
if (is.null(x2)&is.element(type,c("inter.ord","inter.cat","inter.ord.main")) )
{
stop("if x2 is null, type can not be inter.ord, inter.cat or main")
}
if (!is.null(x2)&!is.element(type,c("inter.ord","inter.cat","inter.ord.main")) )
{
stop("if x2 is not null, type must be inter.ord, inter.cat or main")
}
if (!is.null(x2))
{
x<-transf.inter(x1,x2)
}
else
{
x<-x1
}
dat<-cbind(x,y)
dat<- subset(dat, complete.cases(dat))
y<-dat[,2]
x<-dat[,1]
n<-length(x)
if (is.element(type,c("inter.ord","inter.cat","inter.ord.main")))
{
K<-9
}
else
{
K<-max(x)
}
a.vec<-numeric(K)
for (i in 1:K)
{
a.vec[i]<-sum(x==i)/n
}
pval<-Fasymp(maxselcrit,a.vec=a.vec,type=type)
return(list(maxselstat=maxselcrit,value=pval))
} |
`curvePredictLinear` <-
function(x,params) {
return (params[2]*x+params[1])
} |
r_sample_binary <-
function (n, x = 1:2, prob = NULL, name = "Binary") {
if (missing(n)) stop("`n` is missing")
out <- x[sample.int(n = 2, size = n, replace = TRUE, prob = prob)]
varname(out, name)
}
r_sample_binary_factor <-
function (n, x = 1:2, prob = NULL, name = "Binary") {
if (missing(n)) stop("`n` is missing")
out <- x[sample.int(n = 2, size = n, replace = TRUE, prob = prob)]
out <- factor(out, levels = x)
varname(out, name)
} |
"hcdn_conus_sites" |
frdAllPairsExactTest <-
function(y, ...) UseMethod("frdAllPairsExactTest")
frdAllPairsExactTest.default <-
function(y, groups, blocks, p.adjust.method = p.adjust.methods, ...)
{
p.adjust.method <- match.arg(p.adjust.method)
ans <- frdRanks(y, groups, blocks)
r <- ans$r
n <- nrow(r)
k <- ncol(r)
GRPNAMES <- colnames(r)
METHOD <- c("Eisinga, Heskes, Pelzer & Te Grotenhuis all-pairs test",
" with exact p-values for a two-way",
" balanced complete block design")
Ri <- colSums(r)
compareRi <- function(i, j){
d <- Ri[i] - Ri[j]
d
}
PSTAT <- pairwise.table(compareRi, GRPNAMES,
p.adjust.method="none")
pstat <- as.numeric(PSTAT)
pstat <- pstat[!is.na(pstat)]
pval <- sapply(pstat, function(pstat) {
pexactfrsd(d = abs(pstat),k = k,n = n, option="pvalue")
})
padj <- p.adjust(pval, method = p.adjust.method, n = (k * (k - 1) / 2))
PVAL <- matrix(NA, ncol = (k - 1), nrow = (k -1 ))
PVAL[!is.na(PSTAT)] <- padj
DIST <- "D"
colnames(PSTAT) <- GRPNAMES[1:(k-1)]
rownames(PSTAT) <- GRPNAMES[2:k]
colnames(PVAL) <- GRPNAMES[1:(k-1)]
rownames(PVAL) <- GRPNAMES[2:k]
ans <- list(method = METHOD,
data.name = ans$DNAME,
p.value = PVAL,
statistic = PSTAT,
p.adjust.method = p.adjust.method,
dist = DIST,
model = ans$inDF)
class(ans) <- "PMCMR"
ans
} |
"sample_sel" <-
function (data, sample = c(), sample_time = c(), sample_lambda = c(),
sel_time = c(), sel_lambda = c(), sel_time_ab = c(),
sel_lambda_ab = c(), sel_special = list() )
{
increasing_x2 <- if(data@x2[1] < data@x2[2]) TRUE else FALSE
if (length(sel_time) == 2) {
if (sel_time[2] > data@nt)
sel_time[2] <- data@nt
[email protected] <- as.matrix([email protected][sel_time[1]:sel_time[2], ])
data@x <- data@x[sel_time[1]:sel_time[2]]
if (data@simdata)
data@C2 <- data@C2[sel_time[1]:sel_time[2], ]
}
if (length(sel_time_ab) == 2) {
tmin <- which(data@x >= sel_time_ab[1])[1]
tmax <- which(data@x <= sel_time_ab[2])[length(
which(data@x <= sel_time_ab[2]))]
[email protected] <- as.matrix([email protected][tmin:tmax, ])
data@x <- data@x[tmin:tmax]
if (data@simdata)
data@C2 <- data@C2[tmin:tmax, ]
}
if (length(sel_lambda) == 2) {
lmin <- sel_lambda[1]
lmax <- sel_lambda[2]
[email protected] <- as.matrix([email protected][, lmin:lmax])
data@nl <- ncol([email protected])
data@x2 <- data@x2[lmin:lmax]
if (data@simdata)
data@E2 <- data@E2[lmin:lmax, ]
}
if (length(sel_lambda_ab) == 2) {
if(increasing_x2) {
lmin <- which(data@x2 >= sel_lambda_ab[1])[1]
lmax <- which(data@x2 <= sel_lambda_ab[2])[length(
which(data@x2 <= sel_lambda_ab[2]))]
}
else {
lmin <- which(data@x2 <= sel_lambda_ab[1])[1]
lmax <- which(data@x2 >= sel_lambda_ab[2])[length(
which(data@x2 >= sel_lambda_ab[2]))]
}
[email protected] <- as.matrix([email protected][,lmin:lmax])
data@nt <- nrow([email protected])
data@x2 <- data@x2[lmin:lmax]
if (data@simdata)
data@E2 <- data@E2[,lmin:lmax ]
}
if (length(sel_special) > 0) {
for(i in 1:length(sel_special)) {
reg <- sel_special[[i]]
if(increasing_x2) {
lmin <- which(data@x2 >= reg[1])[1]
lmax <- which(data@x2 <= reg[2])[length(which(data@x2 <= reg[2]))]
}
else {
lmin <- which(data@x2 <= reg[1])[1]
lmax <- which(data@x2 >= reg[2])[length(which(data@x2 >= reg[2]))]
}
if(i == 1)
datanew <- as.matrix([email protected][- (reg[3]:reg[4]),lmin:lmax])
else
datanew <- cbind(datanew, as.matrix([email protected][- (reg[3]:reg[4]),
lmin:lmax]))
}
[email protected] <- datanew
data@x <- data@x[-(sel_special[[1]][3]:sel_special[[1]][4])]
}
data@nl <- length(data@x2)
data@nt <- length(data@x)
if (sample != 1) {
[email protected] <- as.matrix([email protected][seq(1, data@nt, by = sample),
seq(1, data@nl, by = sample)])
data@x <- data@x[seq(1, data@nt, by = sample)]
data@x2 <- data@x2[seq(1, data@nl, by = sample)]
data@nl <- length(data@x2)
data@nt <- length(data@x)
}
else {
if (is.matrix([email protected]))
[email protected] <- as.matrix([email protected][seq(1, data@nt,
by = sample_time),
seq(1, data@nl,
by = sample_lambda)])
data@x <- data@x[seq(1, data@nt, by = sample_time)]
data@x2 <- data@x2[seq(1, data@nl, by = sample_lambda)]
data@nl <- length(data@x2)
data@nt <- length(data@x)
}
data
} |
test_that("ConvertFishbaseFood function works", {
test.food <- try(rfishbase::fooditems("Plectropomus maculatus"),silent = TRUE)
if ("try-error"%in%class(test.food)) {
skip("could not connect to remote database")
}else{
test.convert <- ConvertFishbaseFood(test.food,ExcludeStage = "recruits/juv.")
expect_length(test.convert,2)
expect_setequal(dim(test.convert$FoodItems), c(1,5))
expect_setequal(dim(test.convert$Taxonomy), c(1,1))
}
}) |
context("Evolutionary Multi-Objective Algorithms")
test_that("preimplemented EMOAs work well", {
printList = function(l) {
ns = names(l)
pairs = sapply(ns, function(n) {
paste0(n, l[[n]], sep = "=")
})
collapse(pairs, ", ")
}
expect_is_pareto_approximation = function(pf, n.obj, algo, prob, algo.pars) {
info.suffix = sprintf("Algo '%s' failed on problem '%s' with params '%s'",
algo, prob, printList(algo.pars))
expect_equal(nrow(pf), length(which.nondominated(t(pf))), info = paste0(info.suffix, "Not all returned points are nondominated."))
expect_data_frame(pf, any.missing = FALSE, all.missing = FALSE, ncols = n.obj, types = "numeric", info = paste0(info.suffix, "Not all returned points are numeric."))
expect_equal(ncol(pf), n.obj, info = paste0(info.suffix, "Number of columns is not equal to the number of objectives."))
}
fns = list(
zdt1 = smoof::makeZDT1Function(dimensions = 2L),
zdt2 = smoof::makeZDT2Function(dimensions = 3L)
)
max.evals = 200L
for (mu in c(5, 10, 15)) {
for (fn in names(fns)) {
res = nsga2(
fitness.fun = fns[[fn]],
n.population = mu,
n.offspring = 5L,
lower = getLowerBoxConstraints(fns[[fn]]),
upper = getUpperBoxConstraints(fns[[fn]]),
terminators = list(stopOnEvals(max.evals))
)
expect_is_pareto_approximation(res$pareto.front, getNumberOfObjectives(fns[[fn]]), "nsga2", fn,
list(mu = mu, lambda = 5L, max.evals = max.evals)
)
}
}
for (mu in c(5, 10, 15)) {
for (fn in names(fns)) {
res = smsemoa(
fitness.fun = fns[[fn]],
n.population = mu,
n.offspring = 5L,
ref.point = rep(11, getNumberOfObjectives(fns[[fn]])),
lower = getLowerBoxConstraints(fns[[fn]]),
upper = getUpperBoxConstraints(fns[[fn]]),
terminators = list(stopOnEvals(max.evals))
)
expect_is_pareto_approximation(res$pareto.front, getNumberOfObjectives(fns[[fn]]), "smsemoa", fn,
list(mu = mu, lambda = 5L, max.evals = max.evals)
)
}
}
fitness.fun = makeZDT3Function(dimensions = 2L)
for (mu in c(10, 20)) {
aspiration.set = matrix(
c(0.2, 0.25,
0.21, 0.2,
0.18, 0.4), ncol = 3L, byrow = FALSE
)
res = asemoa(fitness.fun, mu = mu, aspiration.set = aspiration.set,
lower = getLowerBoxConstraints(fitness.fun), upper = getUpperBoxConstraints(fitness.fun))
expect_is_pareto_approximation(res$pareto.front, 2L, "asemoa", "ZDT3",
list(mu = mu, n.archive = ncol(aspiration.set)))
}
}) |
nlmixrTest(
{
context("M2 -- all observations")
.nlmixr <- function(...) {
try(suppressWarnings(nlmixr(...)))
}
dat <- Wang2007
dat$DV <- dat$Y
f <- function() {
ini({
tvK <- 0.5
bsvK ~ 0.04
prop.sd <- sqrt(0.1)
})
model({
ke <- tvK * exp(bsvK)
v <- 1
ipre <- 10 * exp(-ke * t)
ipre ~ prop(prop.sd)
})
}
dat2 <- dat
dat2$limit <- 0
dat3 <- dat
dat3$limit <- 3
dat4 <- dat
dat4$limit <- 12
f.focei <- .nlmixr(f, dat, "posthoc")
f.focei2 <- .nlmixr(f, dat2, "posthoc")
expect_false(isTRUE(all.equal(f.focei$objf, f.focei2$objf)))
f.focei3 <- .nlmixr(f, dat3, "posthoc")
expect_false(isTRUE(all.equal(f.focei2$objf, f.focei3$objf)))
f.focei4 <- .nlmixr(f, dat4, "posthoc")
f.foce <- .nlmixr(f, dat, "posthoc", control = list(interaction = FALSE))
f.foce2 <- .nlmixr(f, dat2, "posthoc", control = list(interaction = FALSE))
expect_false(isTRUE(all.equal(f.foce$objf, f.foce2$objf)))
f.foce3 <- .nlmixr(f, dat3, "posthoc", control = list(interaction = FALSE))
expect_false(isTRUE(all.equal(f.foce2$objf, f.foce3$objf)))
test_that("M3/M4 -- Missing, assume LLOQ=3 at t=1.5", {
context("M3/M4 -- Missing, assume LLOQ=3 at t=1.5")
skip_if(Sys.getenv("R_ARCH") == "/i386", "windows32")
datL <- rbind(dat[, names(dat) != "Y"], data.frame(ID = 1:10, Time = 1.5, DV = 3))
datL$cens <- ifelse(datL$Time == 1.5, 1, 0)
datL <- datL[order(datL$ID, datL$Time), ]
datL4 <- datL
datL4$limit <- 0
f.foceiL <- .nlmixr(f, datL, "posthoc")
expect_false(isTRUE(all.equal(f.focei$objf, f.foceiL$objf)))
f.foceiL4 <- .nlmixr(f, datL4, "posthoc")
expect_false(isTRUE(all.equal(f.focei$objf, f.foceiL4$objf)))
expect_false(isTRUE(all.equal(f.foceiL$objf, f.foceiL4$objf)))
datL <- rbind(dat[, names(dat) != "Y"], data.frame(ID = 1:10, Time = 1.5, DV = 3))
datL$cens <- ifelse(datL$Time == 1.5, 1, 0)
datL <- datL[order(datL$ID, datL$Time), ]
datL4 <- datL
datL4$limit <- 0
f.foceiL <- .nlmixr(f, datL, "posthoc")
expect_false(isTRUE(all.equal(f.focei$objf, f.foceiL$objf)))
f.foceiL4 <- .nlmixr(f, datL4, "posthoc")
expect_false(isTRUE(all.equal(f.focei$objf, f.foceiL4$objf)))
expect_false(isTRUE(all.equal(f.foceiL$objf, f.foceiL4$objf)))
datL <- rbind(dat[, names(dat) != "Y"], data.frame(ID = 1:10, Time = 1.5, DV = 3))
datL$cens <- ifelse(datL$Time == 1.5, 1, 0)
datL <- datL[order(datL$ID, datL$Time), ]
datL4 <- datL
datL4$limit <- 0
f.foceL <- .nlmixr(f, datL, "posthoc", control = list(interaction = FALSE))
expect_false(isTRUE(all.equal(f.foce$objf, f.foceL$objf)))
f.foceL4 <- .nlmixr(f, datL4, "posthoc", control = list(interaction = FALSE))
expect_false(isTRUE(all.equal(f.foce$objf, f.foceL4$objf)))
expect_false(isTRUE(all.equal(f.foceL$objf, f.foceL4$objf)))
})
},
test = "focei"
) |
local_methods <- function(..., .frame = caller_env()) {
local_bindings(..., .env = global_env(), .frame = .frame)
}
local_foo_df <- function(frame = caller_env()) {
local_methods(.frame = frame,
group_by.foo_df = function(.data, ...) {
out <- NextMethod()
if (missing(...)) {
class(out) <- c("foo_df", class(out))
} else {
class(out) <- c("grouped_foo_df", class(out))
}
out
},
ungroup.grouped_foo_df = function(x, ...) {
out <- NextMethod()
class(out) <- c("foo_df", class(out))
out
}
)
}
new_ctor <- function(base_class) {
function(x = list(), ..., class = NULL) {
if (inherits(x, "tbl_df")) {
tibble::new_tibble(x, class = c(class, base_class), nrow = nrow(x))
} else if (is.data.frame(x)) {
structure(x, class = c(class, base_class, "data.frame"), ...)
} else {
structure(x, class = c(class, base_class), ...)
}
}
}
foobar <- new_ctor("dplyr_foobar")
foobaz <- new_ctor("dplyr_foobaz")
quux <- new_ctor("dplyr_quux")
new_dispatched_quux <- function(x) {
out <- quux(x)
out$dispatched <- rep(TRUE, nrow(out))
out
} |
iplotScantwo <-
function(scantwoOutput, cross=NULL, lodcolumn=1, pheno.col=1, chr=NULL,
chartOpts=NULL, digits=5)
{
if(!inherits(scantwoOutput, "scantwo"))
stop('"scantwoOutput" should have class "scantwo".')
if(!is.null(chr)) {
scantwoOutput <- subset(scantwoOutput, chr=chr)
if(!is.null(cross)) cross <- subset(cross, chr=chr)
}
if(length(lodcolumn) > 1) {
lodcolumn <- lodcolumn[1]
warning("lodcolumn should have length 1; using first value")
}
if(length(dim(scantwoOutput)) < 3) {
if(lodcolumn != 1) {
warning("scantwoOutput contains just one set of lod scores; using lodcolumn=1")
lodcolumn <- 1
}
}
else {
d <- dim(scantwoOutput)[3]
if(lodcolumn < 1 || lodcolumn > 3)
stop("lodcolumn should be between 1 and ", d)
scantwoOutput$lod <- scantwoOutput$lod[,,lodcolumn]
}
if(length(pheno.col) > 1) {
pheno.col <- pheno.col[1]
warning("pheno.col should have length 1; using first value")
}
if(!is.null(cross))
pheno <- qtl::pull.pheno(cross, pheno.col)
else cross <- pheno <- NULL
scantwo_list <- data4iplotScantwo(scantwoOutput)
phenogeno_list <- cross4iplotScantwo(scantwoOutput, cross, pheno)
defaultAspect <- 1
browsersize <- getPlotSize(defaultAspect)
x <- list(scantwo_data=scantwo_list,
phenogeno_data=phenogeno_list,
chartOpts=chartOpts)
if(!is.null(digits))
attr(x, "TOJSON_ARGS") <- list(digits=digits)
htmlwidgets::createWidget("iplotScantwo", x,
width=chartOpts$width,
height=chartOpts$height,
sizingPolicy=htmlwidgets::sizingPolicy(
browser.defaultWidth=browsersize$width,
browser.defaultHeight=browsersize$height,
knitr.defaultWidth=1000,
knitr.defaultHeight=1000/defaultAspect
),
package="qtlcharts")
}
iplotScantwo_output <- function(outputId, width="100%", height="1000") {
htmlwidgets::shinyWidgetOutput(outputId, "iplotScantwo", width, height, package="qtlcharts")
}
iplotScantwo_render <- function(expr, env=parent.frame(), quoted=FALSE) {
if(!quoted) { expr <- substitute(expr) }
htmlwidgets::shinyRenderWidget(expr, iplotScantwo_output, env, quoted=TRUE)
}
data4iplotScantwo <-
function(scantwoOutput)
{
lod <- scantwoOutput$lod
map <- scantwoOutput$map
lod <- lod[map$eq.spacing==1, map$eq.spacing==1,drop=FALSE]
map <- map[map$eq.spacing==1,,drop=FALSE]
lodv1 <- get_lodv1(lod, map, scantwoOutput$scanoneX)
chr <- as.character(map$chr)
chrnam <- unique(chr)
n.mar <- tapply(chr, chr, length)[chrnam]
names(n.mar) <- NULL
labels <- revisePmarNames(rownames(map))
dimnames(lod) <- NULL
dimnames(lodv1) <- NULL
list(lod=lod, lodv1=lodv1,
nmar=n.mar, chrname=chrnam,
marker=labels, chr=chr, pos=map$pos)
}
revisePmarNames <-
function(labels)
{
wh.pmar <- grep("^c.+\\.loc-*[0-9]+", labels)
pmar <- labels[wh.pmar]
pmar.spl <- strsplit(pmar, "\\.loc")
pmar_chr <- vapply(pmar.spl, "[", "", 1)
pmar_chr <- substr(pmar_chr, 2, nchar(pmar_chr))
pmar_pos <- vapply(pmar.spl, "[", "", 2)
labels[wh.pmar] <- paste0(pmar_chr, "@", pmar_pos)
labels
}
get_lodv1 <-
function(lod, map, scanoneX=NULL)
{
thechr <- map$chr
uchr <- unique(thechr)
thechr <- factor(as.character(thechr), levels=as.character(uchr))
uchr <- factor(as.character(uchr), levels=levels(thechr))
xchr <- tapply(map$xchr, thechr, function(a) a[1])
maxo <- tapply(diag(lod), thechr, max, na.rm=TRUE)
if(any(xchr) && !is.null(scanoneX)) {
maxox <- tapply(scanoneX, thechr, max, na.rm=TRUE)
maxo[xchr] <- maxox[xchr]
}
n.chr <- length(uchr)
for(i in 1:n.chr) {
pi <- which(thechr==uchr[i])
for(j in 1:n.chr) {
pj <- which(thechr==uchr[j])
lod[pj,pi] <- lod[pj,pi] - max(maxo[c(i,j)])
}
}
lod[is.na(lod) | lod < 0] <- 0
lod
}
cross4iplotScantwo <-
function(scantwoOutput, cross=NULL, pheno=NULL)
{
if(is.null(cross) || is.null(pheno))
return(NULL)
map <- scantwoOutput$map
map <- map[map$eq.spacing==1,,drop=FALSE]
getPmarNames <-
function(cross)
{
nam <- lapply(cross$geno, function(a) colnames(a$draws))
chrnam <- names(cross$geno)
for(i in seq(along=nam)) {
g <- grep("^loc", nam[[i]])
if(length(g) > 0)
nam[[i]][g] <- paste0("c", chrnam[i], ".", nam[[i]][g])
}
nam
}
needImp <- TRUE
if("draws" %in% names(cross$geno[[1]])) {
nam <- getPmarNames(cross)
if(all(rownames(scantwoOutput) %in% unlist(nam))) {
needImp <- FALSE
}
}
if(needImp) {
if("prob" %in% names(cross$geno[[1]])) {
cross <- qtl::sim.geno(cross,
error.prob=attr(cross$geno[[1]]$prob, "error.prob"),
step=attr(cross$geno[[1]]$prob, "step"),
off.end=attr(cross$geno[[1]]$prob, "off.end"),
map.function=attr(cross$geno[[1]]$prob, "map.function"),
stepwidth=attr(cross$geno[[1]]$prob, "stepwidth"),
n.draws=1)
nam <- getPmarNames(cross)
if(all(rownames(scantwoOutput) %in% unlist(nam))) {
needImp <- FALSE
}
}
if(needImp)
stop('cross object needs imputed genotypes at pseudomarkers\n',
'Run sim.geno with step/stepwidth as used for scantwo')
}
cross_type <- crosstype(cross)
chr_type <- sapply(cross$geno, chrtype)
sexpgm <- qtl::getsex(cross)
cross.attr <- attributes(cross)
if(cross_type %in% c("f2", "bc", "bcsft") && any(chr_type=="X")) {
for(i in which(chr_type=="X")) {
cross$geno[[i]]$draws <- qtl::reviseXdata(cross_type, "standard", sexpgm,
draws=cross$geno[[i]]$draws,
cross.attr=cross.attr)
}
}
geno <- vector("list", nrow(map))
names(geno) <- rownames(map)
for(i in seq(along=cross$geno)) {
m <- which(nam[[i]] %in% rownames(map))
for(j in m)
geno[[nam[[i]][j]]] <- cross$geno[[i]]$draws[,j,1]
}
names(geno) <- revisePmarNames(rownames(map))
genonames <- vector("list", length(cross$geno))
names(genonames) <- names(cross$geno)
for(i in seq(along=genonames))
genonames[[i]] <- qtl::getgenonames(cross_type, class(cross$geno[[i]]),
"standard", sexpgm, cross.attr)
X_geno_by_sex <- NULL
chr_type <- vapply(cross$geno, chrtype, "")
if(any(chr_type=="X")) {
f_sexpgm <- m_sexpgm <- sexpgm
f_sexpgm$sex[f_sexpgm$sex==1] <- 0
m_sexpgm$sex[m_sexpgm$sex==0] <- 1
X_geno_by_sex <- list(
qtl::getgenonames(cross_type, class(cross$geno[[i]]), "standard", f_sexpgm, cross.attr),
qtl::getgenonames(cross_type, class(cross$geno[[i]]), "standard", m_sexpgm, cross.attr)
)
}
chr <- as.character(map$chr)
names(chr) <- names(geno)
indID <- qtl::getid(cross)
if(is.null(indID)) indID <- 1:qtl::nind(cross)
indID <- as.character(indID)
list(geno=geno, chr=as.list(chr), genonames=genonames, X_geno_by_sex=X_geno_by_sex,
pheno=pheno, indID=indID, chrtype=as.list(chr_type))
} |
expected <- eval(parse(text="structure(logical(0), .Dim = c(0L, 20L))"));
test(id=0, code={
argv <- eval(parse(text="list(structure(logical(0), .Dim = c(0L, 20L)), \"dimnames\", value = NULL)"));
do.call(`attr<-`, argv);
}, o=expected); |
intraMode=function(d,n,B=0,DB=c(0,0),JC=FALSE,CI_Boot,type="bca", plot=FALSE){
if(is.numeric(d)){d=d}else{stop("d is not numeric")}
if(is.numeric(n)){n=n}else{stop("n is not numeric")}
if(B==0&& plot==TRUE){stop("please select a number of bootstrap repititions for the plot")}
if(B%%1==0){B=B}else{stop("B is not an integer")}
if(DB[1]%%1==0 && DB[2]%%1==0 ){DB=DB}else{stop("At least one entry in DB is not an integer")}
if(length(d)==length(n)){}else{stop("Input vectors do not have the same length")}
d1=d/n
estimate=function(X){
mode_empirical <- function(x) {
uniqv <- unique(x)
uniqv[which.max(tabulate(match(x, uniqv)))]
}
mode=mode_empirical(X)
if(mode==0){warning("Mode is equal to 0. The estimate may be unstalbe")}
PD=mean(X)
foo=function(rho){
mode_theoretical=pnorm(sqrt(1-rho)/(1-2*rho)*qnorm(PD))
return(abs(mode_theoretical-mode))
}
Est<-list(Original =optimise(foo, interval = c(0, 1), maximum = FALSE)$minimum)
}
Estimate_Standard<-estimate(d1)
if(B>0){
N<-length(n)
D<- matrix(ncol=1, nrow=N,d1)
BCA=function(data, indices){
d <- data[indices,]
tryCatch(estimate(d)$Original,error=function(e)NA)
}
boot1<- boot(data = D, statistic = BCA, R=B)
Estimate_Bootstrap<-list(Original = boot1$t0, Bootstrap=2*boot1$t0 - mean(boot1$t,na.rm = TRUE),bValues=boot1$t )
if(missing(CI_Boot)){Estimate_Bootstrap=Estimate_Bootstrap}else{
if(type=="norm"){Conf=(boot.ci(boot1,conf=CI_Boot,type = type)$normal[2:3])}
if(type=="basic"){Conf=(boot.ci(boot1,conf=CI_Boot,type = type)$basic[4:5])}
if(type=="perc"){Conf=(boot.ci(boot1,conf=CI_Boot,type = type))$percent[4:5]}
if(type=="bca"){Conf=(boot.ci(boot1,conf=CI_Boot,type = type))$bca[4:5]}
if(type=="all"){Conf=(boot.ci(boot1,conf=CI_Boot,type = type))}
Estimate_Bootstrap<-list(Original = boot1$t0, Bootstrap=2*boot1$t0 - mean(boot1$t,na.rm = TRUE),CI_Boot=Conf,bValues=boot1$t )
}
if(plot==TRUE){
Dens<-density(boot1$t, na.rm = TRUE)
XY<-cbind(Dens$x,Dens$y)
label<-data.frame(rep("Bootstrap density",times=length(Dens$x)))
Plot<-cbind(XY,label)
colnames(Plot)<-c("Estimate","Density","Label")
SD<-cbind(rep(boot1$t0,times=length(Dens$x)), Dens$y,rep("Standard estimate",times=length(Dens$x)))
colnames(SD)<-c("Estimate","Density","Label")
BC<-cbind(rep(Estimate_Bootstrap$Bootstrap,times=length(Dens$x)), Dens$y,rep("Bootstrap corrected estimate",times=length(Dens$x)))
colnames(BC)<-c("Estimate","Density","Label")
Plot<-rbind(Plot,SD, BC)
Plot$Estimate<-as.numeric(Plot$Estimate)
Plot$Density<- as.numeric(Plot$Density)
Estimate<-Plot$Estimate
Density<-Plot$Density
Label<-Plot$Label
P<-ggplot()
P<-P+with(Plot, aes(x=Estimate, y=Density, colour=Label)) +
geom_line()+
scale_colour_manual(values = c("black", "red", "orange"))+
theme_minimal(base_size = 15) +
ggtitle("Bootstrap Density" )+
theme(plot.title = element_text(hjust = 0.5),legend.position="bottom",legend.text = element_text(size = 12),legend.title = element_text( size = 12), legend.justification = "center",axis.text.x= element_text(face = "bold", size = 12))
print(P)
}
}
if(DB[1]!=0){
IN=DB[1]
OUT=DB[2]
theta1=NULL
theta2=matrix(ncol = OUT, nrow=IN)
for(i in 1:OUT){
N<-length(d1)
Ib<-sample(N,N,replace=TRUE)
Db<-d1[Ib]
try(theta1[i]<-estimate(Db)$Original, silent = TRUE)
for(c in 1:IN){
Ic<-sample(N,N,replace=TRUE)
Dc<-Db[Ic]
try( theta2[c,i]<-estimate(Dc)$Original, silent = TRUE)
}
}
Boot1<- mean(theta1, na.rm = TRUE)
Boot2<- mean(theta2, na.rm = TRUE)
BC<- 2*Estimate_Standard$Original -Boot1
DBC<- (3*Estimate_Standard$Original-3*Boot1+Boot2)
Estimate_DoubleBootstrap<-list(Original = Estimate_Standard$Original, Bootstrap=BC, Double_Bootstrap=DBC, oValues=theta1, iValues=theta2)
}
if(JC==TRUE){
N<-length(n)
Test=NULL
for(v in 1:N){
d2<-d1[-v]
try(Test[v]<-estimate(d2)$Original)
}
Estimate_Jackknife<-list(Original = Estimate_Standard$Original, Jackknife=(N*Estimate_Standard$Original-(N-1)*mean(Test)))
}
if(B>0){return(Estimate_Bootstrap)}
if(JC==TRUE){return(Estimate_Jackknife)}
if(DB[1]!=0){return(Estimate_DoubleBootstrap)}
if(B==0 && JC==FALSE && DB[1]==0){return(Estimate_Standard)}
} |
kpPoints <- function(karyoplot, data=NULL, chr=NULL, x=NULL, y=NULL, ymin=NULL, ymax=NULL,
data.panel=1, r0=NULL, r1=NULL,
clipping=TRUE, pch=16, cex=0.5, ...) {
if(!methods::is(karyoplot, "KaryoPlot")) stop("'karyoplot' must be a valid 'KaryoPlot' object")
karyoplot$beginKpPlot()
on.exit(karyoplot$endKpPlot())
pp <- prepareParameters2("kpPoints", karyoplot=karyoplot, data=data, chr=chr, x=x, y=y,
ymin=ymin, ymax=ymax, r0=r0, r1=r1, data.panel=data.panel, ...)
ccf <- karyoplot$coord.change.function
xplot <- ccf(chr=pp$chr, x=pp$x, data.panel=data.panel)$x
yplot <- ccf(chr=pp$chr, y=pp$y, data.panel=data.panel)$y
processClipping(karyoplot=karyoplot, clipping=clipping, data.panel=data.panel)
dots <- filterParams(list(...), pp$filter, pp$original.length)
pch <- filterParams(pch, pp$filter, pp$original.length)
cex <- filterParams(cex, pp$filter, pp$original.length)
params <- c(list(x=xplot, y=yplot, pch=pch, cex=cex), dots)
do.call(graphics::points, params)
invisible(karyoplot)
} |
mdlp <-
function(data){
p <- length(data[1,])-1
y <- data[,(p+1)]
xd <- data
cutp <- list()
for (i in 1:p){
x <- data[,i]
cuts1 <- cutPoints(x,y)
cuts <- c(min(x),cuts1,max(x))
cutp[[i]] <- cuts1
if(length(cutp[[i]])==0)cutp[[i]] <- "All"
xd[,i] <- as.integer(cut(x,cuts,include.lowest = TRUE))
}
return (list(cutp=cutp,Disc.data=xd))
} |
bfFixefLMER_t.fnc<-function (model, item = FALSE, method = c("t", "z", "llrt", "AIC", "BIC", "relLik.AIC", "relLik.BIC"), threshold = NULL, t.threshold = NULL, alphaitem = NULL, prune.ranefs = TRUE, set.REML.FALSE = TRUE, keep.single.factors = FALSE, reset.REML.TRUE = TRUE, log.file = NULL) {
if (length(item) == 0) {
stop("please supply a value to argument \"item\".\n")
}
if (length(set.REML.FALSE) == 0) {
stop("please supply a value to argumnet \"set.REML.FALSE\".\n")
}
if (length(reset.REML.TRUE) == 0) {
stop("please supply a value to argument \"reset.REML.TRUE\".\n")
}
if (!method[1] %in% c("t", "z", "llrt", "AIC", "BIC", "relLik.AIC", "relLik.BIC")) {
stop("please supply a proper method name (t, z, llrt, AIC, BIC, relLik.AIC, or relLik.BIC).\n")
}
if ("factor" %in% attributes(attributes(model@frame)$terms)$dataClasses &
max(c(0, apply(as.data.frame(model@frame[, names(attributes(attributes(model@frame)$terms)$dataClasses[attributes(attributes(model@frame)$terms)$dataClasses == "factor"])]), MARGIN = 2, FUN = function(x) length(levels(factor(x)))))) > 2) {
if(!as.vector(model@call[1]) == "glmer()"){
warning("factor variable with more than two levels in model terms, backfitting on t-values is not appropriate, please use function \"bfFixefLMER_F.fnc\" instead.\n")
}
}
if (is.null(threshold)) {
threshold <- c(2, 2, 0.05, 5, 5, 4, 4)[match(method[1], c("t", "z", "llrt", "AIC", "BIC", "relLik.AIC", "relLik.BIC"))]
}
if (is.null(t.threshold)) {
t.threshold <- 2
}
if (is.null(alphaitem)) {
if (method[1] == "llrt") {
alphaitem <- threshold
} else {
alphaitem <- 0.05
}
}
if (is.null(log.file)) {
log.file <- file.path(tempdir(), paste("bfFixefLMER_t_log_", gsub(":", "-", gsub("", "_", date())), ".txt", sep = ""))
}
if ((method[1] != "t" & set.REML.FALSE) || (method[1] != "z" & set.REML.FALSE)) {
if(!as.vector(model@call[1]) == "glmer()"){
cat("setting REML to FALSE\n")
model <- update(model, . ~ ., REML = FALSE)
}
}
data <- model@frame
statistic <- "t-value"
temp.dir <- tempdir()
tempdir()
options(warn = 1)
unlink(file.path(temp.dir, "temp.txt"))
sink(file = NULL, type = "message")
if (log.file != FALSE)
sink(file = log.file, split = TRUE)
if (item != FALSE) {
cat("checking", paste("by-", item, sep = ""), "random intercepts\n")
model.updated <- NULL
eval(parse(text = paste("model.updated=update(model,.~.+(1|", item, "))", sep = "")))
if (as.vector(anova(model, model.updated)[2, "Pr(>Chisq)"]) <= alphaitem) {
cat(" log-likelihood ratio test p-value =", as.vector(anova(model, model.updated)[2, "Pr(>Chisq)"]), "\n")
cat(" adding", paste("by-", item, sep = ""), "random intercepts to model\n")
model <- model.updated
}
else {
cat(" log-likelihood ratio test p-value =", as.vector(anova(model, model.updated)[2, "Pr(>Chisq)"]), "\n")
cat(" not adding", paste("by-", item, sep = ""), "random intercepts to model\n")
}
}
if (as.vector(model@call[1]) == "glmer()") {
statistic <- "z-value"
odv <- data[, as.character(unlist(as.list(model@call))$formula[2])]
data[, as.character(unlist(as.list(model@call))$formula[2])] = rnorm(nrow(data), 0, 1)
ow<-options()$warn
options(warn = -1)
temp.lmer <- update(model, . ~ ., family = "gaussian", data = data)
options(warn=ow)
coefs <- row.names(anova(temp.lmer))
data[, as.character(unlist(as.list(model@call))$formula[2])] <- odv
} else {
coefs <- row.names(anova(model))
}
if (is(model, "merMod")) {
model <- asS4(model)
smry <- as.data.frame(summary(model)$coefficients)
}
else {
stop("the input model is not a mer object\n")
}
smry.temp <- smry[-c(1:nrow(smry)), ]
smry <- as.data.frame(summary(model)$coefficients)
for (coef in coefs) {
intr.order <- length(unlist(strsplit(coef, ":")))
orig.coef <- coef
coef <- gsub(":", "\\.\\*:", coef)
coef <- gsub("(^.*$)", "\\1\\.\\*", coef)
coef <- gsub("\\(", "\\\\(", coef)
coef <- gsub("\\)", "\\\\)", coef)
smry.temp2 <- smry[grep(paste("^", coef, sep = ""),
row.names(smry)), ]
smry.temp3 <- smry.temp2
smry.temp3 <- smry.temp3[-c(1:nrow(smry.temp3)), ]
for (j in 1:nrow(smry.temp2)) {
if (length(unlist(strsplit(row.names(smry.temp2)[j], ":"))) == intr.order) {
smry.temp3 <- rbind(smry.temp3, smry.temp2[j, ])
}
}
smry.temp2 <- smry.temp3
smry.temp2[, 3] = abs(smry.temp2[, 3])
smry.temp2 <- smry.temp2[smry.temp2[, 3] == max(smry.temp2[, 3]), ]
row.names(smry.temp2) <- orig.coef
smry.temp <- rbind(smry.temp, smry.temp2)
}
temp <- strsplit(coefs, ":")
names(temp) <- coefs
intr.order <- list()
for (i in coefs) {
intr.order[[i]] <- length(temp[[i]])
}
intr.order <- as.data.frame(unlist(intr.order))
colnames(intr.order) <- "Order"
intr.order$Coef <- row.names(intr.order)
row.names(intr.order) <- 1:nrow(intr.order)
orders <- sort(as.numeric(unique(intr.order$Order)), decreasing = TRUE)
if (keep.single.factors) {
orders <- orders[orders != 1]
}
smry.temp$Order <- intr.order$Order
count <- 1
for (order in orders) {
cat("processing model terms of interaction level", order, "\n")
keepers <- as.character(row.names(smry.temp[smry.temp$Order == order, ]))
smry.temp2 <- smry.temp[keepers, ]
if (smry.temp2[smry.temp2[, 3] == min(smry.temp2[, 3]), 3][1] >= t.threshold) {
cat(" all terms of interaction level", order, "significant\n")
}
while (smry.temp2[smry.temp2[, 3] == min(smry.temp2[, 3]), 3][1] < t.threshold) {
cat(" iteration", count, "\n")
cat(" ", statistic, "for term", paste("\"", row.names(smry.temp2[smry.temp2[, 3] == min(smry.temp2[, 3]), ])[1], "\"", sep = ""),
"=", smry.temp2[smry.temp2[, 3] == min(smry.temp2[, 3]), 3][1], "<", t.threshold, "\n")
fac <- unlist(strsplit(gsub("\\)", "", gsub("\\(", "", as.character(row.names(smry.temp2[smry.temp2[, 3] == min(smry.temp2[, 3]), ]))[1])), ":"))
hoi <- gsub("\\)", "", gsub("\\(", "", intr.order[intr.order$Order > order, "Coef"]))
tt <- c()
for (i in 1:length(hoi)) {
tt[i] <- length(grep("FALSE", unique(fac %in% unlist(strsplit(hoi[i], ":"))))) < 1
}
if (length(grep("TRUE", tt)) != 0) {
cat(" part of higher-order interaction\n")
cat(" skipping term\n")
keepers <- row.names(smry.temp2)
keepers <- keepers[-grep(as.character(row.names(smry.temp2[smry.temp2[, 3] == min(smry.temp2[, 3]), ]))[1], keepers)]
smry.temp2 <- smry.temp2[keepers, ]
} else {
cat(" not part of higher-order interaction\n")
m.temp <- NULL
eval(parse(text = paste("m.temp=update(model,.~.-", row.names(smry.temp2[smry.temp2[, 3] == min(smry.temp2[, 3]), ])[1], ")", sep = "")))
if (method[1] == "llrt") {
if (as.vector(anova(model, m.temp)[2, "Pr(>Chisq)"]) <= threshold) {
cat(" log-likelihood ratio test p-value =", as.vector(anova(model, m.temp)[2, "Pr(>Chisq)"]), "<=", threshold, "\n")
cat(" skipping term\n")
keepers <- row.names(smry.temp2)
cat("length =", length(keepers), "\n")
keepers <- keepers[-which(keepers == as.character(row.names(smry.temp2[smry.temp2[, 3] == min(smry.temp2[, 3]), ]))[1])]
smry.temp2 <- smry.temp2[keepers, ]
reduction <- FALSE
}
else {
reduction <- TRUE
cat(" log-likelihood ratio test p.value =", as.vector(anova(model, m.temp)[2, "Pr(>Chisq)"]), ">", threshold, "\n")
}
}
if (method[1] %in% c("AIC", "BIC")) {
m.temp.ic <- summary(m.temp)$AICtab[method[1]]
model.ic <- summary(model)$AICtab[method[1]]
ic.diff <- m.temp.ic - model.ic
if (ic.diff >= threshold) {
reduction <- FALSE
}
else {
reduction <- TRUE
}
if (!reduction) {
cat(paste(" ", method[1], " simple = ", round(m.temp.ic), "; ", method[1], " complex = ", round(model.ic), "; decrease = ", round(ic.diff), " >= ", threshold, "\n", sep = ""))
cat(" skipping term\n")
keepers <- row.names(smry.temp2)
cat("length =", length(keepers), "\n")
keepers <- keepers[-which(keepers == as.character(row.names(smry.temp2[smry.temp2[, 3] == min(smry.temp2[, 3]), ]))[1])]
smry.temp2 <- smry.temp2[keepers, ]
}
else {
cat(paste(" ", method[1], " simple = ", round(m.temp.ic), "; ", method[1], " complex = ", round(model.ic), "; decrease = ", round(ic.diff), " < ", threshold, "\n", sep = ""))
}
}
if (method[1] %in% c("relLik.AIC", "relLik.BIC")) {
ic <- gsub("relLik.(.*)", "\\1", method[1])
m.temp.ic <- eval(parse(text = paste(ic, "(m.temp)", sep = "")))
model.ic <- eval(parse(text = paste(ic, "(model)", sep = "")))
my.relLik <- relLik(m.temp, model, ic)["relLik"]
reduction <- FALSE
cat(paste(" ", ic, " simple = ", round(m.temp.ic), "; ", ic, " complex = ", round(model.ic), "; relLik = ", round(my.relLik), "\n", sep = ""))
if (m.temp.ic <= model.ic) {
reduction <- TRUE
}
if (!reduction) {
if (my.relLik >= threshold) {
cat(paste(" ", "relLik of ", round(my.relLik), " >= ", threshold, "\n", sep = ""))
cat(" skipping term\n")
keepers <- row.names(smry.temp2)
cat("length =", length(keepers), "\n")
keepers <- keepers[-which(keepers == as.character(row.names(smry.temp2[smry.temp2[, 3] == min(smry.temp2[, 3]), ]))[1])]
smry.temp2 <- smry.temp2[keepers, ]
}
else {
cat(paste(" ", "relLik of ", round(my.relLik), " < ", threshold, "\n", sep = ""))
reduction <- TRUE
}
}
else {
cat(paste(" simple model more likely than complex model\n"))
}
}
if (method[1] == "t") {
reduction <- TRUE
}
if (reduction) {
cat(" removing term\n")
model <- m.temp
if (as.vector(model@call[1]) == "glmer()") {
odv <- data[, as.character(unlist(as.list(model@call))$formula[2])]
data[, as.character(unlist(as.list(model@call))$formula[2])] <- rnorm(nrow(data), 0, 1)
ow<-options()$warn
options(warn = -1)
temp.lmer <- update(model, . ~ ., family = "gaussian", data = data)
options(warn=ow)
coefs <- row.names(anova(temp.lmer))
data[, as.character(unlist(as.list(model@call))$formula[2])] <- odv
}
else {
coefs <- row.names(anova(model))
if (length(coefs) == 0) {
break
}
}
smry2 <- as.data.frame(summary(model)$coefficients)
smry.temp2 <- smry2[-c(1:nrow(smry2)), ]
for (coef in coefs) {
intr.order <- length(unlist(strsplit(coef,
":")))
orig.coef <- coef
coef <- gsub(":", "\\.\\*:", coef)
coef <- gsub("(^.*$)", "\\1\\.\\*", coef)
coef <- gsub("\\(", "\\\\(", coef)
coef <- gsub("\\)", "\\\\)", coef)
smry.temp3 <- smry2[grep(paste("^", coef,
sep = ""), row.names(smry2)), ]
smry.temp4 <- smry.temp3
smry.temp4 <- smry.temp4[-c(1:nrow(smry.temp4)),
]
for (j in 1:nrow(smry.temp3)) {
if (length(unlist(strsplit(row.names(smry.temp3)[j], ":"))) == intr.order) {
smry.temp4 <- rbind(smry.temp4, smry.temp3[j, ])
}
}
smry.temp3 <- smry.temp4
smry.temp3[, 3] <- abs(smry.temp3[, 3])
smry.temp3 <- smry.temp3[smry.temp3[, 3] == max(smry.temp3[, 3]), ]
row.names(smry.temp3) <- orig.coef
smry.temp2 <- rbind(smry.temp2, smry.temp3)
}
temp <- strsplit(coefs, ":")
names(temp) <- coefs
intr.order <- list()
for (i in coefs) {
intr.order[[i]] <- length(temp[[i]])
}
intr.order <- as.data.frame(unlist(intr.order))
colnames(intr.order) <- "Order"
intr.order$Coef <- row.names(intr.order)
row.names(intr.order) <- 1:nrow(intr.order)
smry.temp2$Order <- intr.order$Order
keepers <- as.character(row.names(smry.temp2[smry.temp2$Order == order, ]))
smry.temp = smry.temp2
smry.temp2 <- smry.temp2[keepers, ]
}
}
count <- count + 1
if (nrow(smry.temp2) == 0) {
break
}
}
}
if (reset.REML.TRUE) {
if(!as.vector(model@call[1]) == "glmer()"){
cat("resetting REML to TRUE\n")
model <- update(model, . ~ ., REML = TRUE)
}
}
if (prune.ranefs) {
cat("pruning random effects structure ...\n")
split1 <- gsub(" ", "", model@call)[2]
split2 <- unlist(strsplit(split1, "\\~"))[2]
split2 <- gsub("\\)\\+\\(", "\\)_____\\(", split2)
split2 <- gsub("\\(0\\+", "\\(0\\&\\&\\&", split2)
split2 <- gsub("\\(1\\+", "\\(0\\&\\&\\&", split2)
split3 <- unlist(strsplit(split2, "\\+"))
split4 <- grep("\\|", split3, value = TRUE)
split4 <- gsub("\\&\\&\\&", "\\+", split4)
split5 <- unlist(strsplit(split4, "_____"))
m.ranefs <- split5
if (as.vector(model@call[1]) == "glmer()") {
statistic <- "z-value"
odv <- data[, as.character(unlist(as.list(model@call))$formula[2])]
data[, as.character(unlist(as.list(model@call))$formula[2])] = rnorm(nrow(data), 0, 1)
ow<-options()$warn
options(warn = -1)
temp.lmer <- update(model, . ~ ., family = "gaussian", data = data)
options(warn=ow)
coefs <- row.names(anova(temp.lmer))
data[, as.character(unlist(as.list(model@call))$formula[2])] <- odv
}
else {
coefs <- row.names(anova(model))
}
m.ranef.variables <- gsub("\\((.*)\\|.*", "\\1", m.ranefs)
m.ranef.variables <- gsub(".\\+(.*)", "\\1", m.ranef.variables)
m.ranef.variables <- m.ranef.variables[m.ranef.variables != "1"]
m.ranef.variables <- m.ranef.variables[m.ranef.variables != "0"]
ranef.to.remove <- vector("character")
for (m.ranef.variable in m.ranef.variables) {
if (!m.ranef.variable %in% coefs) {
ranef.to.remove <- c(ranef.to.remove, m.ranef.variable)
}
}
if (length(ranef.to.remove) > 0) {
rtr <- vector("character")
rtr2 <- vector("character")
for (iii in ranef.to.remove) {
rtr <- c(rtr, grep(iii, m.ranefs, value = TRUE))
cat(paste(" ", iii, " in random effects structure but not in fixed effects structure\n", sep = ""))
cat(" removing", iii, "from model ...\n")
rtr2 <- c(rtr2, sub(iii, 1, grep(iii, m.ranefs, value = TRUE)))
}
eval(parse(text = paste("model<-update(model,.~.-", paste(rtr, collapse = "-"), "+", paste(rtr2, collapse = "+"), ",data=data)", sep = "")))
}
else {
cat(" nothing to prune\n")
}
}
options(warn = 0)
sink(file = NULL, type = "message")
if (log.file != FALSE) {
cat("log file is", log.file, "\n")
sink(file = NULL)
}
return(model = model)
} |
context("FunExternal")
test_that("test external functions (smoof/BBOB) are evaluated without errors", {
fn = makeBBOBFunction(dimension = 2L, fid = 1L, iid = 1L)
y1 <- fn(c(0,0))
x <- matrix(c(0,0), 1, 2)
y2 <- as.double(funBBOBCall(x, opt = list(dimensions = 2L, fid = 1L, iid = 1L)) )
expect_equal( y1 , y2)
}) |
td <- tempfile()
dir.create(td)
Sys.setenv("PROJ_USER_WRITABLE_DIRECTORY"=td)
library(rgdal)
data("GridsDatums")
GridsDatums[grep("Netherlands", GridsDatums$country),]
mvrun <- FALSE
knitr::include_graphics(system.file("misc/meuse.png", package="rgdal"))
odd_run <- FALSE
if (new_proj_and_gdal()) odd_run <- TRUE
ellps <- projInfo("ellps")
(clrk66 <- ellps[ellps$name=="clrk66",])
a <- 6378206.4
b <- 6356583.8
print(sqrt((a^2-b^2)/a^2), digits=10)
(shpr <- get_proj_search_paths())
if (is.null(shpr)) odd_run <- FALSE
run <- FALSE
if (require("RSQLite", quietly=TRUE)) run <- TRUE
library(RSQLite)
db <- dbConnect(SQLite(), dbname=file.path(shpr[length(shpr)], "proj.db"))
dbListTables(db)
(metadata <- dbReadTable(db, "metadata"))
cat(wkt(CRS(SRS_string="OGC:CRS84")), "\n")
b_pump <- readOGR(system.file("vectors/b_pump.gpkg", package="rgdal"))
proj4string(b_pump)
if (packageVersion("sp") > "1.4.1") {
WKT <- wkt(b_pump)
} else {
WKT <- comment(slot(b_pump, "proj4string"))
}
cat(WKT, "\n")
cov <- dbReadTable(db, "coordinate_operation_view")
cov[grep("OSGB", cov$name), c("table_name", "code", "name", "method_name", "accuracy")]
list_coordOps(paste0(proj4string(b_pump), " +type=crs"), "EPSG:4326")
set_enforce_xy(FALSE)
list_coordOps(paste0(proj4string(b_pump), " +type=crs"), "EPSG:4326")
set_enforce_xy(TRUE)
set_transform_wkt_comment(FALSE)
isballpark <- spTransform(b_pump, CRS(SRS_string="OGC:CRS84"))
get_last_coordOp()
print(coordinates(isballpark), digits=10)
helm <- dbReadTable(db, "helmert_transformation_table")
helm[helm$code == "1314", c("auth_name", "code", "name", "tx", "ty", "tz", "rx", "ry", "rz", "scale_difference")]
dbDisconnect(db)
set_transform_wkt_comment(TRUE)
is2m <- spTransform(b_pump, CRS(SRS_string="OGC:CRS84"))
get_last_coordOp()
print(coordinates(is2m), digits=10)
c(spDists(isballpark, is2m)*1000)
mrun <- FALSE
if (suppressPackageStartupMessages(require(maptools, quietly=TRUE))) mrun <- TRUE
c(maptools::gzAzimuth(coordinates(isballpark), coordinates(is2m)))
(a <- project(coordinates(b_pump), proj4string(b_pump), inv=TRUE, verbose=TRUE))
(b <- project(coordinates(b_pump), WKT, inv=TRUE))
all.equal(a, b)
c(spDists(coordinates(isballpark), a)*1000)
list_coordOps(WKT, "OGC:CRS84")
if (is.projected(b_pump)) {
o <- project(t(unclass(bbox(b_pump))), wkt(b_pump), inv=TRUE)
} else {
o <- t(unclass(bbox(b_pump)))
}
(aoi <- c(t(o + c(-0.1, +0.1))))
nrow(list_coordOps(WKT, "OGC:CRS84", area_of_interest=aoi))
nrow(list_coordOps(WKT, "OGC:CRS84", strict_containment=TRUE, area_of_interest=aoi))
run <- run && (attr(getPROJ4VersionInfo(), "short") >= 710)
is_proj_CDN_enabled()
enable_proj_CDN()
is_proj_CDN_enabled()
shpr[1]
try(file.size(file.path(shpr[1], "cache.db")))
list_coordOps(WKT, "OGC:CRS84", area_of_interest=aoi)
system.time(is1m <- spTransform(b_pump, CRS(SRS_string="OGC:CRS84")))
get_last_coordOp()
print(coordinates(is1m), digits=10)
c(spDists(is2m, is1m)*1000)
c(maptools::gzAzimuth(coordinates(is1m), coordinates(is2m)))
try(file.size(file.path(shpr[1], "cache.db")))
library(RSQLite)
db <- dbConnect(SQLite(), dbname=file.path(shpr[1], "cache.db"))
dbListTables(db)
dbReadTable(db, "chunks")
dbDisconnect(db)
disable_proj_CDN()
is_proj_CDN_enabled()
knitr::include_graphics(system.file("misc/snow.png", package="rgdal"))
library(sp)
(load(system.file("misc/GGHB.IG_CRS.rda", package="rgdal")))
orig
sp_version_ok <- length(grep("get_source_if_boundcrs", deparse(args(sp::CRS)))) > 0L
orig1 <- CRS(slot(orig, "projargs"), get_source_if_boundcrs=FALSE)
cat(wkt(orig1), "\n")
orig1a <- CRS(slot(orig, "projargs"))
cat(wkt(orig1a), "\n")
orig1b <- rebuild_CRS(orig)
cat(wkt(orig1b), "\n") |
caLogit<-function(sym,y,x)
{
options(contrasts=c("contr.sum","contr.poly"))
outdec<-options(OutDec="."); on.exit(options(outdec))
options(OutDec=",")
y<-m2v(y)
m<-length(x)
n<-nrow(x)
S<-nrow(y)/n
xnms<-names(x)
Lj<-vector("numeric",m)
for (j in 1:m) {Lj[j]<-nlevels(factor(x[[xnms[j]]]))}
p<-sum(Lj)-m+1
xtmp<-paste("factor(x$",xnms,sep="",paste(")"))
xfrm<-paste(xtmp,collapse="+")
usl<-partutils(xfrm,y,x,n,p,S)
psc<-profsimcode(sym)
Zsym<-as.matrix(psc)
Usym<-Zsym%*%t(usl)
r<-nrow(Zsym)
log<-Logit(Usym,S,r)
return(log)
} |
cau.Euclid <-
function(parsil, distance.matrix)
{
parsil/(1 + 4.4*distance.matrix^2)
} |
coverage <- function(x, level = 0.95, na.rm = TRUE) {
x <- as.numeric(x)
level <- check.level(level)
bottom = (1 - level) / 2
top = 1 - bottom
res <- quantile(x, probs = c(bottom, top),
na.rm = na.rm, type = 7, names = TRUE)
names(res) <- paste("coverage", c("lower", "upper"), sep = "_")
names(res) <- c("lower", "upper")
res
}
ci.mean <- function(x, level = 0.95, na.rm = TRUE) {
x <- as.numeric(x)
level <- check.level(level)
n <- length(x)
lowerq <- stats::qt((1 - level) / 2, df = n - 1)
res <-
base::mean(x, na.rm = na.rm) +
c(lowerq, -lowerq) *
stats::sd(x, na.rm = na.rm)/sqrt(length(x))
names(res) <- c("lower", "upper")
res
}
ci.median <- function(x, level = 0.9, na.rm = TRUE) {
x <- as.numeric(x)
level <- check.level(level)
x <- sort(x)
n <- length(x)
bottom <- (1 - level) / 2
top <- 1 - bottom
ci_index <- (n + qnorm(c(bottom, top)) * sqrt(n))/2 + c(0,1)
res <- as.numeric(x[round(ci_index)])
names(res) <- c("lower", "upper")
res
}
ci.sd <- function(x, level = 0.95, na.rm = TRUE) {
x <- as.numeric(x)
level <- check.level(level)
n <- length(x)
bottom <- (1 - level) / 2
top <- 1 - bottom
res = (n - 1) *
stats::sd(x, na.rm = TRUE)^2 /
qchisq(c(top, bottom), df = n - 1)
res <- sqrt(res)
names(res) <- c("lower", "upper")
res
}
ci.prop <- function(x, success = NULL, level = 0.95,
method = c("Clopper-Pearson",
"binom.test", "Score", "Wilson",
"prop.test", "Wald", "Agresti-Coull",
"Plus4")) {
level <- check.level(level)
if (requireNamespace("mosaic")) {
tmp <- mosaic::binom.test(~ x, conf.level = level, ci.method = method,
success = success)
res <- numeric(3)
res[c(1,3)] <- tmp$conf.int
res[2] <- tmp$estimate
names(res) <- c("lower", "center", "upper")
} else {
nm = success
if (is.null(nm)) {
nm <- if (is.logical(x)) TRUE else unique(x)[1]
}
prob <- mean(x == nm[1])
n <- length(x)
bottom <- (1 - level) / 2
top <- 1 - bottom
res <- qbinom(c(bottom, top), size = length(x), prob = prob) / n
res[3] <- res[2]
res[2] <- prob
names(res) <- c("lower", "center", "upper")
}
res
}
check.level <- function(level) {
res <- ifelse(level > 1, 1, ifelse(level < 0, 0, level))
if (level < 0 | level > 1) warning("level ", level, " is not between 0 and 1. Setting to ", res)
res
} |
Visualizer4Set <- function(A, pointsToDraw, colour, label, name){
if (requireNamespace("rgl", quietly = TRUE)) {
X <- rbind(c(0, 0, 0),
c(1, 0, 0),
c(0.5, 0.5 * sqrt(3), 0),
c(0.5, 1/6 * sqrt(3), 1/3 *sqrt(6)))
grandCoalition=A[length(A)]
beta = pointsToDraw/grandCoalition
vertices <- bary2cart(X, beta)
ConvHull <- convhulln(vertices)
ts.surf <- t(ConvHull)
rgl::rgl.triangles(vertices[ts.surf, 1], vertices[ts.surf, 2], vertices[ts.surf, 3], col = colour, alpha=0.8, smooth=FALSE, lit=FALSE)
if(label == TRUE)
{
setLabels(A, pointsToDraw, name)
}
}else
{ print("Please install the package 'rgl' in order to generate plots visualizing 4-player TU games")}
} |
test_that("functions in mixutil.R are ok", {
expect_identical(lastn(letters, 5), letters[22:26])
n <- 10
x <- 1:n
expect_identical(lastn(x, n), x)
expect_identical(lastn(x, 3), x[8:10])
expect_identical(lastn(x, -3), integer(0))
expect_identical(lastn(1:3, 0), integer(0))
expect_identical(lastn(c(1, 2, 3), 0), numeric(0))
expect_error(lastn(x, n + 1),
"argument must be coercible to non-negative integer")
}) |
residuals.survreg.penal <- function(object, ...) {
pterms <- object$pterms
if (any(pterms==2))
stop("Residualss not available for sparse models")
NextMethod('residuals')
} |
test_that("ggnetmap produces the expected fortified data frame with lookup table", {
net=network::network(matrix(c(0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0), nrow=4, byrow=TRUE))
network::set.vertex.attribute(net, "name", value=c("a", "b", "c", "d"))
wkb = structure(list("01010000204071000000000000801A064100000000AC5C1641",
"01010000204071000000000000801A084100000000AC5C1441",
"01010000204071000000000000801A044100000000AC5C1241",
"01010000204071000000000000801A024100000000AC5C1841"),
class = "WKB")
map=sf::st_sf(id=c("a1", "b2", "c3", "d4"), sf::st_as_sfc(wkb, EWKB=TRUE))
lkptbl=data.frame(id=c("a1", "b2", "c3", "d4"), name=c("a", "b", "c", "d"))
res=ggnetmap(net, map, lkptbl, "id", "name")
expect_equal(
res,
data.frame(name=c("a", "a", "a", "a", "b", "b", "b", "c", "c", "d", "d"),
x=c(181072, 181072, 181072, 181072,
197456, 197456, 197456,
164688, 164688,
148304, 148304),
y=c(366379, 366379, 366379, 366379,
333611, 333611, 333611,
300843, 300843,
399147, 399147),
vertex.names=c(1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4),
xend=c(164688, 148304, 197456, 181072,
197456, 181072, 164688,
197456, 164688,
197456, 148304),
yend=c(300843, 399147, 333611, 366379,
333611, 366379, 300843,
333611, 300843,
333611, 399147),
id=c("a1", "a1", "a1", "a1",
"b2", "b2", "b2",
"c3", "c3",
"d4", "d4")),
tolerance=0.03
)
})
test_that("ggnetmap produces the expected fortified data frame without lookup table", {
net=network::network(matrix(c(0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0), nrow=4, byrow=TRUE))
network::set.vertex.attribute(net, "name", value=c("a", "b", "c", "d"))
wkb = structure(list("01010000204071000000000000801A084100000000AC5C1441",
"01010000204071000000000000801A044100000000AC5C1241",
"01010000204071000000000000801A024100000000AC5C1841",
"01010000204071000000000000801A064100000000AC5C1641"),
class = "WKB")
map=sf::st_sf(id=c("b", "c", "d", "a"), sf::st_as_sfc(wkb, EWKB=TRUE))
res=ggnetmap(net, map, NULL, "id", "name")
expect_equal(
res,
data.frame(name=c("a", "a", "a", "a", "b", "b", "b", "c", "c", "d", "d"),
x=c(181072, 181072, 181072, 181072,
197456, 197456, 197456,
164688, 164688,
148304, 148304),
y=c(366379, 366379, 366379, 366379,
333611, 333611, 333611,
300843, 300843,
399147, 399147),
vertex.names=c(1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4),
xend=c(164688, 148304, 197456, 181072,
197456, 181072, 164688,
197456, 164688,
197456, 148304),
yend=c(300843, 399147, 333611, 366379,
333611, 366379, 300843,
333611, 300843,
333611, 399147),
id=c("a", "a", "a", "a",
"b", "b", "b",
"c", "c",
"d", "d")),
tolerance=0.03
)
}) |
fit.poisson <- function(...) {
stop("estimation of Poisson fields not programmed yet")
RFoptOld <- internal.rfoptions(...)
on.exit(RFoptions(LIST=RFoptOld[[1]]))
RFopt <- RFoptOld[[2]]
} |
herit_loci <- function(
p_anc,
causal_coeffs,
causal_indexes = NULL,
sigma_sq = 1
){
if ( missing( p_anc ) )
stop( '`p_anc` (vector of ancestral allele frequencies) is required!' )
if ( missing( causal_coeffs ) )
stop( '`causal_coeffs` vector is required!' )
if ( length( sigma_sq ) != 1 )
stop( '`sigma_sq` must have length 1 (instead has length ', length( sigma_sq ), ')!' )
if ( is.na( sigma_sq ) )
stop( '`sigma_sq` cannot be `NA`!' )
if ( sigma_sq <= 0 )
stop( '`sigma_sq` must be positive (passed ', sigma_sq ,')!' )
if ( !is.null( causal_indexes ) ) {
m_loci <- length( causal_indexes )
if ( length( p_anc ) > m_loci )
p_anc <- p_anc[ causal_indexes ]
if ( length( causal_coeffs ) > m_loci )
causal_coeffs <- causal_coeffs[ causal_indexes ]
}
if ( length( p_anc ) != length( causal_coeffs ) )
stop( 'lengths of `p_anc` (', length( p_anc ), ') and `causal_coeffs` (', length( causal_coeffs ), ') disagree!' )
herit_vec <- 2 * p_anc * ( 1 - p_anc ) * causal_coeffs^2 / sigma_sq
return( herit_vec )
} |
grnn.kfold <- function(x,y,k,fun,scale=TRUE) {
x<-as.data.frame(x)
y<-as.data.frame(y)
n_p<-ncol(y)
n_s<-nrow(y)
pred_it<-numeric(n_p)
spread.end<-NULL
cvr1<-cvTools::cvFolds(n_s, K = k)
predict_end<-NULL
for (i in 1:k) {
subcvr1<-cvr1$subsets
tv.x <- x[subcvr1[cvr1$which != i],,drop=FALSE]
test.x <- x[subcvr1[cvr1$which == i],,drop=FALSE]
tv.y <- y[subcvr1[cvr1$which != i],,drop=FALSE]
test.y <- y[subcvr1[cvr1$which == i],,drop=FALSE]
best.spread<-findSpread (tv.x,tv.y,k,fun)
spread.end<-rbind(spread.end,best.spread)
pred_it<-matrix(NA,nrow(test.y),ncol(test.y))
if (scale==TRUE){
tv.x<-scales::rescale(as.matrix(tv.x), to=c(-1,1))
test.x<-scales::rescale(as.matrix(test.x), to=c(-1,1))
}
w.input<-grnn.distance(tv.x,test.x,fun)
for (k in 1:n_p) {
b.input<-w.input*sqrt(-log(0.5))/best.spread[k]
a1<-exp(-b.input^2)
weight_all<-colSums(a1)
for (h in 1:ncol(a1)) {if (weight_all[h]==0) {weight_all[h]<-1}}
pred_it[,k]<-(t(a1) %*% as.matrix(tv.y[,k]))/weight_all
}
row.names(pred_it) <- row.names(test.y)
predict_end<-rbind(predict_end,pred_it)
}
predict_all<-predict_end[order(rownames(predict_end)),]
y_all<-y[order(rownames(y)),]
res<-predict_all-y_all
res<-as.data.frame(res)
stdev<-numeric(ncol(res))
stdae<-numeric(ncol(res))
mae<-numeric(ncol(res))
rmse<-sqrt(colSums(res^2)/nrow(res))
stdev<-sqrt(colSums(res^2)/(nrow(res)-2))
r<-numeric(ncol(res))
pvalue<-numeric(ncol(res))
for (n in 1:ncol(res)) {
mae[n]<-mean(abs(res[,n]))
stdae[n]<-stats::sd(abs(res[,n]))
r[n]<-stats::cor(y_all[,n],predict_all[,n])
corv<-stats::cor.test(y_all[,n],predict_all[,n])
pvalue[n] <- 2*stats::pt(corv$statistic, df = corv$parameter, lower.tail=FALSE)
}
spread.mean<-colMeans(spread.end)
results<-rbind(rmse,stdae,stdev,mae,r,pvalue,spread.mean)
print(results)
} |
noharm_sirt_optim_function_R <- function(gamma_val, delta, I, wgtm, pm,
b0.jk, b1.jk, b2.jk, b3.jk)
{
val <- 0
for (ii in 1:(I-1)){
for (jj in (ii+1):I){
if (wgtm[ii,jj] >0 ){
x_ij <- gamma_val[ii,jj] / sqrt( delta[ii] * delta[jj] )
pm_exp <- b0.jk[ii,jj] + b1.jk[ii,jj]*x_ij + b2.jk[ii,jj]*x_ij^2 + b3.jk[ii,jj]*x_ij^3
val <- val + wgtm[ii,jj]*(pm[ii,jj] - pm_exp)^2
}
}
}
return(val)
} |
match.dat.fun <-
function(dat1, dat2){
ids=as.matrix(unique(dat1[, 1]))
n.len=length(ids)
res=NULL
for(i in 1:n.len){
idx=(dat2[,1]==ids[i])
dat.i=dat2[idx, ]
res=rbind(res, dat.i)
}
return(res)
} |
library(checkargs)
context("isStrictlyNegativeNumberOrNanVector")
test_that("isStrictlyNegativeNumberOrNanVector works for all arguments", {
expect_identical(isStrictlyNegativeNumberOrNanVector(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyNegativeNumberOrNanVector(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyNegativeNumberOrNanVector(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyNegativeNumberOrNanVector(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_error(isStrictlyNegativeNumberOrNanVector(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(0, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isStrictlyNegativeNumberOrNanVector(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyNegativeNumberOrNanVector(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isStrictlyNegativeNumberOrNanVector(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(1, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isStrictlyNegativeNumberOrNanVector(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isStrictlyNegativeNumberOrNanVector(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector("", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector("X", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isStrictlyNegativeNumberOrNanVector(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyNegativeNumberOrNanVector(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isStrictlyNegativeNumberOrNanVector(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isStrictlyNegativeNumberOrNanVector(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isStrictlyNegativeNumberOrNanVector(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrNanVector(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
}) |
with_progress <- function(expr, handlers = progressr::handlers(), cleanup = TRUE, delay_terminal = NULL, delay_stdout = NULL, delay_conditions = NULL, interrupts = getOption("progressr.interrupts", TRUE), interval = NULL, enable = NULL) {
stop_if_not(is.logical(cleanup), length(cleanup) == 1L, !is.na(cleanup))
stop_if_not(is.logical(interrupts), length(interrupts) == 1L, !is.na(interrupts))
debug <- getOption("progressr.debug", FALSE)
if (debug) {
message("with_progress() ...")
on.exit(message("with_progress() ... done"), add = TRUE)
}
if (length(handlers) == 0L) {
if (debug) message("No progress handlers - skipping")
return(expr)
}
options <- list()
if (!is.null(enable)) {
stop_if_not(is.logical(enable), length(enable) == 1L, !is.na(enable))
if (!enable) {
if (debug) message("Progress disabled - skipping")
return(expr)
}
options[["progressr.enable"]] <- enable
}
if (!is.null(interval)) {
stop_if_not(is.numeric(interval), length(interval) == 1L, !is.na(interval))
options[["progressr.interval"]] <- interval
}
if (length(options) > 0L) {
oopts <- options(options)
on.exit(options(oopts), add = TRUE)
}
progressr_in_globalenv("allow")
on.exit(progressr_in_globalenv("disallow"), add = TRUE)
handlers <- as_progression_handler(handlers)
if (length(handlers) == 0L) {
if (debug) message("No remaining progress handlers - skipping")
return(expr)
}
delays <- use_delays(handlers,
terminal = delay_terminal,
stdout = delay_stdout,
conditions = delay_conditions
)
if (debug) {
what <- c(
if (delays$terminal) "terminal",
if (delays$stdout) "stdout",
delays$conditions
)
message("- Buffering: ", paste(sQuote(what), collapse = ", "))
}
calling_handler <- make_calling_handler(handlers)
status <- "incomplete"
if (cleanup) {
on.exit({
if (debug) message("- signaling 'shutdown' to all handlers")
withCallingHandlers({
withRestarts({
signalCondition(control_progression("shutdown", status = status))
}, muffleProgression = function(p) NULL)
}, progression = calling_handler)
}, add = TRUE)
}
stdout_file <- delay_stdout(delays, stdout_file = NULL)
on.exit(flush_stdout(stdout_file), add = TRUE)
conditions <- list()
if (length(delays$conditions) > 0) {
on.exit(flush_conditions(conditions), add = TRUE)
}
if (debug) message("- signaling 'reset' to all handlers")
withCallingHandlers({
withRestarts({
signalCondition(control_progression("reset"))
}, muffleProgression = function(p) NULL)
}, progression = calling_handler)
progression_counter <- 0
capture_conditions <- TRUE
withCallingHandlers({
res <- withVisible(expr)
}, progression = function(p) {
progression_counter <<- progression_counter + 1
if (debug) message(sprintf("- received a %s (n=%g)", sQuote(class(p)[1]), progression_counter))
capture_conditions <<- FALSE
on.exit(capture_conditions <<- TRUE)
if (isTRUE(attr(delays$terminal, "flush"))) {
if (length(conditions) > 0L || has_buffered_stdout(stdout_file)) {
calling_handler(control_progression("hide"))
stdout_file <<- flush_stdout(stdout_file, close = FALSE)
conditions <<- flush_conditions(conditions)
calling_handler(control_progression("unhide"))
}
}
calling_handler(p)
},
interrupt = function(c) {
if (!interrupts) return()
suspendInterrupts({
capture_conditions <<- FALSE
on.exit(capture_conditions <<- TRUE)
if (isTRUE(attr(delays$terminal, "flush"))) {
if (length(conditions) > 0L || has_buffered_stdout(stdout_file)) {
calling_handler(control_progression("hide"))
stdout_file <<- flush_stdout(stdout_file, close = FALSE)
conditions <<- flush_conditions(conditions)
}
}
calling_handler(control_progression("interrupt"))
})
},
condition = function(c) {
if (!capture_conditions || inherits(c, c("progression", "error"))) return()
if (debug) message("- received a ", sQuote(class(c)[1]))
if (inherits(c, delays$conditions)) {
conditions[[length(conditions) + 1L]] <<- c
if (inherits(c, "message")) {
invokeRestart("muffleMessage")
} else if (inherits(c, "warning")) {
invokeRestart("muffleWarning")
} else if (inherits(c, "condition")) {
restarts <- computeRestarts(c)
for (restart in restarts) {
name <- restart$name
if (is.null(name)) next
if (!grepl("^muffle", name)) next
invokeRestart(restart)
break
}
}
}
})
status <- "ok"
if (isTRUE(res$visible)) {
res$value
} else {
invisible(res$value)
}
} |
invisible() |
validate_milestone_level <- function(x){
stopifnot("title" %in% names(x))
nonissue_keys <- setdiff(names(x), "issue")
invalid_keys <- setdiff(nonissue_keys, c("title", help_post_milestone()) )
if(length(invalid_keys)>0){
stop(paste("The following YAML keys are invalid for milestones:",
paste(invalid_keys, collapse = ", ")))
}
}
validate_issue_level <- function(x){
stopifnot("title" %in% names(x))
keys <- names(x)
invalid_keys <- setdiff(keys, c("title", help_post_issue()))
if(length(invalid_keys)>0){
stop(paste("The following YAML keys are invalid for issues:",
paste(invalid_keys, collapse = ", ")))
}
}
validate_plan <- function(plan){
sapply(plan, validate_milestone_level)
sapply(plan, function(x) sapply(x[["issue"]], validate_issue_level))
}
validate_todo <- function(todo){
sapply(todo, validate_issue_level)
} |
as.data.frame.compareClusterResult <- getFromNamespace("as.data.frame.compareClusterResult", "enrichplot")
as.data.frame.groupGOResult <- function(x, ...) {
as.data.frame(x@result, ...)
}
`[.compareClusterResult` <- function(x, i, j, asis = FALSE, ...) {
result <- as.data.frame(x)
y <- result[i,j, ...]
if (!asis)
return(y)
x@compareClusterResult <- y
return(x)
}
`[[.compareClusterResult` <- function(x, i) {
idx <- which(i == x[, "ID"])
if (length(idx) == 0)
stop("input term not found...")
y <- x[idx, asis = TRUE]
geneInCategory(y)
}
head.compareClusterResult <- function(x, n=6L, ...) {
head(as.data.frame(x), n, ...)
}
tail.compareClusterResult <- function(x, n=6L, ...) {
tail(as.data.frame(x), n, ...)
}
dim.compareClusterResult <- function(x) {
dim(as.data.frame(x))
}
geneID.groupGOResult <- function(x) as.character(x@result$geneID)
geneInCategory.groupGOResult <- function(x)
setNames(strsplit(geneID(x), "/", fixed=TRUE), rownames(x@result)) |
fit_nor <- function(sl1, sl2, st3, st4) {
parameters <- pelnor(c(sl1, sl2, st3, st4))
return(parameters)
} |
Id <- "$Id: c212.interim.1a.hier2.lev0.convergence.R,v 1.7 2019/05/05 13:18:12 clb13102 Exp clb13102 $"
c212.interim.1a.hier2.lev0.convergence.diag <- function(raw, debug_diagnostic = FALSE)
{
if (is.null(raw)) {
print("NULL raw data")
return(NULL)
}
if (M_global$INTERIM_check_conv_name_1a_2(raw)) {
print("Missing names");
return(NULL)
}
model = attr(raw, "model")
if (is.null(model)) {
print("Simulation model attribute missing")
return(NULL)
}
monitor = raw$monitor
theta_mon = monitor[monitor$variable == "theta",]$monitor
gamma_mon = monitor[monitor$variable == "gamma",]$monitor
mu.theta_mon = monitor[monitor$variable == "mu.theta",]$monitor
mu.gamma_mon = monitor[monitor$variable == "mu.gamma",]$monitor
sigma2.theta_mon = monitor[monitor$variable == "sigma2.theta",]$monitor
sigma2.gamma_mon = monitor[monitor$variable == "sigma2.gamma",]$monitor
nchains = raw$chains
gamma_conv = data.frame(Interval = character(0), B = character(0),
AE = character(0), stat = numeric(0), upper_ci = numeric(0), stringsAsFactors=FALSE)
theta_conv = data.frame(Interval = character(0), B = character(0), AE = character(0),
stat = numeric(0), upper_ci = numeric(0), stringsAsFactors=FALSE)
mu.gamma_conv = data.frame(Interval = character(0), B = character(0),
stat = numeric(0), upper_ci = numeric(0), stringsAsFactors=FALSE)
mu.theta_conv = data.frame(Interval = character(0), B = character(0),
stat = numeric(0), upper_ci = numeric(0), stringsAsFactors=FALSE)
sigma2.gamma_conv = data.frame(Interval = character(0), B = character(0),
stat = numeric(0), upper_ci = numeric(0), stringsAsFactors=FALSE)
sigma2.theta_conv = data.frame(Interval = character(0), B = character(0),
stat = numeric(0), upper_ci = numeric(0), stringsAsFactors=FALSE)
type <- NA
if (nchains > 1) {
type = "Gelman-Rubin"
for (i in 1:raw$nIntervals) {
for (b in 1:raw$nBodySys[i]) {
for (j in 1:raw$nAE[i, b]) {
if (theta_mon == 1) {
g = M_global$GelmanRubin(raw$theta[, i, b, j, ], nchains)
row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b],
AE = raw$AE[i, b,j], stat = g$psrf[1], upper_ci = g$psrf[2], stringsAsFactors=FALSE)
theta_conv = rbind(theta_conv, row)
}
if (gamma_mon == 1) {
g = M_global$GelmanRubin(raw$gamma[, i, b, j, ], nchains)
row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b],
AE = raw$AE[i, b,j], stat = g$psrf[1], upper_ci = g$psrf[2], stringsAsFactors=FALSE)
gamma_conv = rbind(gamma_conv, row)
}
}
if (mu.gamma_mon == 1) {
g = M_global$GelmanRubin(raw$mu.gamma[, i, b, ], nchains)
row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b],
stat = g$psrf[1], upper_ci = g$psrf[2], stringsAsFactors=FALSE)
mu.gamma_conv = rbind(mu.gamma_conv, row)
}
if (mu.theta_mon == 1) {
g = M_global$GelmanRubin(raw$mu.theta[, i, b, ], nchains)
row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b],
stat = g$psrf[1], upper_ci = g$psrf[2], stringsAsFactors=FALSE)
mu.theta_conv = rbind(mu.theta_conv, row)
}
if (sigma2.theta_mon == 1) {
g = M_global$GelmanRubin(raw$sigma2.theta[, i, b, ], nchains)
row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b],
stat = g$psrf[1], upper_ci = g$psrf[2], stringsAsFactors=FALSE)
sigma2.theta_conv = rbind(sigma2.theta_conv, row)
}
if (sigma2.gamma_mon == 1) {
g = M_global$GelmanRubin(raw$sigma2.gamma[, i, b, ], nchains)
row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b],
stat = g$psrf[1], upper_ci = g$psrf[2], stringsAsFactors=FALSE)
sigma2.gamma_conv = rbind(sigma2.gamma_conv, row)
}
}
}
}
else {
type = "Geweke"
for (i in 1:raw$nIntervals) {
for (b in 1:raw$nBodySys[i]) {
for (j in 1:raw$nAE[i, b]) {
if (theta_mon == 1) {
g = M_global$Geweke(raw$theta[1, i, b, j, ])
row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b],
AE = raw$AE[i, b, j], stat = g$z, upper_ci = NA, stringsAsFactors=FALSE)
theta_conv = rbind(theta_conv, row)
}
if (gamma_mon == 1) {
g = M_global$Geweke(raw$gamma[1, i, b, j, ])
row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b],
AE = raw$AE[i, b, j], stat = g$z, upper_ci = NA, stringsAsFactors=FALSE)
gamma_conv = rbind(gamma_conv, row)
}
}
if (mu.gamma_mon == 1) {
g = M_global$Geweke(raw$mu.gamma[1, i, b, ])
row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b], stat = g$z, upper_ci = NA, stringsAsFactors=FALSE)
mu.gamma_conv = rbind(mu.gamma_conv, row)
}
if (mu.theta_mon == 1) {
g = M_global$Geweke(raw$mu.theta[1, i, b, ])
row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b], stat = g$z, upper_ci = NA, stringsAsFactors=FALSE)
mu.theta_conv = rbind(mu.theta_conv, row)
}
if (sigma2.theta_mon == 1) {
g = M_global$Geweke(raw$sigma2.theta[1, i, b, ])
row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b], stat = g$z, upper_ci = NA, stringsAsFactors=FALSE)
sigma2.theta_conv = rbind(sigma2.theta_conv, row)
}
if (sigma2.gamma_mon == 1) {
g = M_global$Geweke(raw$sigma2.gamma[1, i, b, ])
row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b], stat = g$z, upper_ci = NA, stringsAsFactors=FALSE)
sigma2.gamma_conv = rbind(sigma2.gamma_conv, row)
}
}
}
}
theta_acc = data.frame(chain = numeric(0), Interval = character(0), B = character(0),
AE = character(0), rate = numeric(0), stringsAsFactors=FALSE)
gamma_acc = data.frame(chain = numeric(0), Interval = character(0), B = character(0),
AE = character(0), rate = numeric(0), stringsAsFactors=FALSE)
if (raw$sim_type == "MH") {
for (i in 1:raw$nIntervals) {
if (theta_mon == 1) {
for (b in 1:raw$nBodySys[i]) {
for (j in 1:raw$nAE[i, b]) {
for (c in 1:nchains) {
rate <- raw$theta_acc[c, i, b, j]/raw$iter
row <- data.frame(chain = c, Interval = raw$Intervals[i], B = raw$B[i, b],
AE = raw$AE[i, b,j], rate = rate, stringsAsFactors=FALSE)
theta_acc = rbind(theta_acc, row)
}
}
}
}
if (gamma_mon == 1) {
for (b in 1:raw$nBodySys[i]) {
for (j in 1:raw$nAE[i, b]) {
for (c in 1:nchains) {
rate <- raw$gamma_acc[c, i, b, j]/raw$iter
row <- data.frame(chain = c, Interval = raw$Intervals[i], B = raw$B[i, b],
AE = raw$AE[i, b,j], rate = rate, stringsAsFactors=FALSE)
gamma_acc = rbind(gamma_acc, row)
}
}
}
}
}
}
rownames(gamma_conv) <- NULL
rownames(theta_conv) <- NULL
rownames(mu.gamma_conv) <- NULL
rownames(mu.theta_conv) <- NULL
rownames(sigma2.gamma_conv) <- NULL
rownames(sigma2.theta_conv) <- NULL
rownames(gamma_acc) <- NULL
rownames(theta_acc) <- NULL
conv.diag = list(sim_type = raw$sim_type, type = type, monitor = monitor,
gamma.conv.diag = gamma_conv,
theta.conv.diag = theta_conv,
mu.gamma.conv.diag = mu.gamma_conv,
mu.theta.conv.diag = mu.theta_conv,
sigma2.gamma.conv.diag = sigma2.gamma_conv,
sigma2.theta.conv.diag = sigma2.theta_conv,
gamma_acc = gamma_acc,
theta_acc = theta_acc)
attr(conv.diag, "model") = attr(raw, "model")
return(conv.diag)
}
c212.interim.1a.hier2.lev0.print.convergence.summary <- function(conv) {
if (is.null(conv)) {
print("NULL conv data")
return(NULL)
}
monitor = conv$monitor
theta_mon = monitor[monitor$variable == "theta",]$monitor
gamma_mon = monitor[monitor$variable == "gamma",]$monitor
mu.theta_mon = monitor[monitor$variable == "mu.theta",]$monitor
mu.gamma_mon = monitor[monitor$variable == "mu.gamma",]$monitor
sigma2.theta_mon = monitor[monitor$variable == "sigma2.theta",]$monitor
sigma2.gamma_mon = monitor[monitor$variable == "sigma2.gamma",]$monitor
model = attr(conv, "model")
if (is.null(model)) {
print("Convergence model attribute missing")
return(NULL)
}
if (gamma_mon == 1 && !("gamma.conv.diag" %in% names(conv))) {
print("Missing gamma.conv.diag data")
return(NULL)
}
if (theta_mon == 1 && !("theta.conv.diag" %in% names(conv))) {
print("Missing theta.conv.diag data")
return(NULL)
}
if (mu.gamma_mon == 1 && !("mu.gamma.conv.diag" %in% names(conv))) {
print("Missing mu.gamma.conv.diag data")
return(NULL)
}
if (mu.theta_mon == 1 && !("mu.theta.conv.diag" %in% names(conv))) {
print("Missing mu.theta.conv.diag data")
return(NULL)
}
if (sigma2.gamma_mon == 1 && !("sigma2.gamma.conv.diag" %in% names(conv))) {
print("Missing sigma2.gamma.conv.diag data")
return(NULL)
}
if (sigma2.theta_mon == 1 && !("sigma2.theta.conv.diag" %in% names(conv))) {
print("Missing sigma2.theta.conv.diag data")
return(NULL)
}
if (gamma_mon == 1 && !("gamma_acc" %in% names(conv))) {
print("Missing gamma_acc data")
return(NULL)
}
if (theta_mon == 1 && !("theta_acc" %in% names(conv))) {
print("Missing theta_acc data")
return(NULL)
}
cat(sprintf("Summary Convergence Diagnostics:\n"))
cat(sprintf("================================\n"))
if (conv$type == "Gelman-Rubin") {
if (theta_mon == 1) {
cat(sprintf("theta:\n"))
cat(sprintf("------\n"))
max_t = head(conv$theta.conv.diag[conv$theta.conv.diag$stat == max(conv$theta.conv.diag$stat),,
drop = FALSE], 1)
cat(sprintf("Max Gelman-Rubin diagnostic (%s %s %s): %0.6f\n", max_t$Interval, max_t$B, max_t$AE, max_t$stat))
min_t = head(conv$theta.conv.diag[conv$theta.conv.diag$stat == min(conv$theta.conv.diag$stat),,
drop = FALSE], 1)
cat(sprintf("Min Gelman-Rubin diagnostic (%s, %s %s): %0.6f\n", min_t$Interval, min_t$B, min_t$AE, min_t$stat))
}
if (gamma_mon == 1) {
cat(sprintf("gamma:\n"))
cat(sprintf("------\n"))
max_t = head(conv$gamma.conv.diag[conv$gamma.conv.diag$stat == max(conv$gamma.conv.diag$stat),,
drop = FALSE], 1)
cat(sprintf("Max Gelman-Rubin diagnostic (%s %s %s): %0.6f\n", max_t$Interval, max_t$B, max_t$AE, max_t$stat))
min_t = head(conv$gamma.conv.diag[conv$gamma.conv.diag$stat == min(conv$gamma.conv.diag$stat),,
drop = FALSE], 1)
cat(sprintf("Min Gelman-Rubin diagnostic (%s %s %s): %0.6f\n", min_t$Interval, min_t$B, min_t$AE, min_t$stat))
}
if (mu.gamma_mon == 1) {
cat(sprintf("mu.gamma:\n"))
cat(sprintf("---------\n"))
max_t = head(conv$mu.gamma.conv.diag[conv$mu.gamma.conv.diag$stat
== max(conv$mu.gamma.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Max Gelman-Rubin diagnostic (%s %s): %0.6f\n", max_t$Interval, max_t$B, max_t$stat))
min_t = head(conv$mu.gamma.conv.diag[conv$mu.gamma.conv.diag$stat
== min(conv$mu.gamma.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Min Gelman-Rubin diagnostic (%s %s): %0.6f\n", min_t$Interval, min_t$B, min_t$stat))
}
if (mu.theta_mon == 1) {
cat(sprintf("mu.theta:\n"))
cat(sprintf("---------\n"))
max_t = head(conv$mu.theta.conv.diag[conv$mu.theta.conv.diag$stat
== max(conv$mu.theta.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Max Gelman-Rubin diagnostic (%s %s): %0.6f\n", max_t$Interval, max_t$B, max_t$stat))
min_t = head(conv$mu.theta.conv.diag[conv$mu.theta.conv.diag$stat
== min(conv$mu.theta.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Min Gelman-Rubin diagnostic (%s %s): %0.6f\n", min_t$Interval, min_t$B, min_t$stat))
}
if (sigma2.gamma_mon == 1) {
cat(sprintf("sigma2.gamma:\n"))
cat(sprintf("-------------\n"))
max_t = head(conv$sigma2.gamma.conv.diag[conv$sigma2.gamma.conv.diag$stat
== max(conv$sigma2.gamma.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Max Gelman-Rubin diagnostic (%s %s): %0.6f\n", max_t$Interval, max_t$B, max_t$stat))
min_t = head(conv$sigma2.gamma.conv.diag[conv$sigma2.gamma.conv.diag$stat
== min(conv$sigma2.gamma.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Min Gelman-Rubin diagnostic (%s %s): %0.6f\n", min_t$Interval, min_t$B, min_t$stat))
}
if (sigma2.theta_mon == 1) {
cat(sprintf("sigma2.theta:\n"))
cat(sprintf("-------------\n"))
max_t = head(conv$sigma2.theta.conv.diag[conv$sigma2.theta.conv.diag$stat
== max(conv$sigma2.theta.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Max Gelman-Rubin diagnostic (%s %s): %0.6f\n", max_t$Interval, max_t$B, max_t$stat))
min_t = head(conv$sigma2.theta.conv.diag[conv$sigma2.theta.conv.diag$stat
== min(conv$sigma2.theta.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Min Gelman-Rubin diagnostic (%s %s): %0.6f\n", min_t$Interval, min_t$B, min_t$stat))
}
}
else {
if (theta_mon == 1) {
cat(sprintf("theta:\n"))
cat(sprintf("------\n"))
max_t = head(conv$theta.conv.diag[conv$theta.conv.diag$stat == max(conv$theta.conv.diag$stat),,
drop = FALSE], 1)
cat(sprintf("Max Geweke statistic (%s %s %s): %0.6f (%s)\n", max_t$Interval, max_t$B, max_t$AE,
max_t$stat, chk_val(max_t$stat)))
min_t = head(conv$theta.conv.diag[conv$theta.conv.diag$stat == min(conv$theta.conv.diag$stat),,
drop = FALSE], 1)
cat(sprintf("Min Geweke statistic (%s %s %s): %0.6f (%s)\n", min_t$Interval, min_t$B, min_t$AE,
min_t$stat, chk_val(min_t$stat)))
}
if (gamma_mon == 1) {
cat(sprintf("gamma:\n"))
cat(sprintf("------\n"))
max_t = head(conv$gamma.conv.diag[conv$gamma.conv.diag$stat == max(conv$gamma.conv.diag$stat),,
drop = FALSE], 1)
cat(sprintf("Max Geweke statistic (%s %s %s): %0.6f (%s)\n", max_t$Interval, max_t$B, max_t$AE,
max_t$stat, chk_val(max_t$stat)))
min_t = head(conv$gamma.conv.diag[conv$gamma.conv.diag$stat == min(conv$gamma.conv.diag$stat),,
drop = FALSE], 1)
cat(sprintf("Min Geweke statistic (%s %s %s): %0.6f (%s)\n", min_t$Interval, min_t$B, min_t$AE,
min_t$stat, chk_val(min_t$stat)))
}
if (mu.gamma_mon == 1) {
cat(sprintf("mu.gamma:\n"))
cat(sprintf("---------\n"))
max_t = head(conv$mu.gamma.conv.diag[conv$mu.gamma.conv.diag$stat
== max(conv$mu.gamma.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Max Geweke statistic (%s %s): %0.6f (%s)\n", max_t$Interval, max_t$B, max_t$stat,
chk_val(max_t$stat)))
min_t = head(conv$mu.gamma.conv.diag[conv$mu.gamma.conv.diag$stat
== min(conv$mu.gamma.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Min Geweke statistic (%s %s): %0.6f (%s)\n", min_t$Interval, min_t$B, min_t$stat,
chk_val(min_t$stat)))
}
if (mu.theta_mon == 1) {
cat(sprintf("mu.theta:\n"))
cat(sprintf("---------\n"))
max_t = head(conv$mu.theta.conv.diag[conv$mu.theta.conv.diag$stat
== max(conv$mu.theta.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Max Geweke statistic (%s %s): %0.6f (%s)\n", max_t$Interval, max_t$B, max_t$stat,
chk_val(max_t$stat)))
min_t = head(conv$mu.theta.conv.diag[conv$mu.theta.conv.diag$stat
== min(conv$mu.theta.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Min Geweke statistic (%s %s): %0.6f (%s)\n", min_t$Interval, min_t$B, min_t$stat,
chk_val(min_t$stat)))
}
if (sigma2.gamma_mon == 1) {
cat(sprintf("sigma2.gamma:\n"))
cat(sprintf("-------------\n"))
max_t = head(conv$sigma2.gamma.conv.diag[conv$sigma2.gamma.conv.diag$stat
== max(conv$sigma2.gamma.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Max Geweke statistic (%s %s): %0.6f (%s)\n", max_t$Interval, max_t$B, max_t$stat,
chk_val(max_t$stat)))
min_t = head(conv$sigma2.gamma.conv.diag[conv$sigma2.gamma.conv.diag$stat
== min(conv$sigma2.gamma.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Min Geweke statistic (%s %s): %0.6f (%s)\n", min_t$Interval, min_t$B, min_t$stat,
chk_val(min_t$stat)))
}
if (sigma2.theta_mon == 1) {
cat(sprintf("sigma2.theta:\n"))
cat(sprintf("-------------\n"))
max_t = head(conv$sigma2.theta.conv.diag[conv$sigma2.theta.conv.diag$stat
== max(conv$sigma2.theta.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Max Geweke statistic (%s %s): %0.6f (%s)\n", max_t$Interval, max_t$B, max_t$stat,
chk_val(max_t$stat)))
min_t = head(conv$sigma2.theta.conv.diag[conv$sigma2.theta.conv.diag$stat
== min(conv$sigma2.theta.conv.diag$stat),, drop = FALSE], 1)
cat(sprintf("Min Geweke statistic (%s %s): %0.6f (%s)\n", min_t$Interval, min_t$B, min_t$stat,
chk_val(min_t$stat)))
}
}
if (conv$sim_type == "MH") {
cat("\nSampling Acceptance Rates:\n")
cat("==========================\n")
if (theta_mon == 1) {
cat("theta:\n")
cat("------\n")
print(sprintf("Min: %0.6f, Max: %0.6f", min(conv$theta_acc$rate),
max(conv$theta_acc$rate)))
}
if (gamma_mon == 1) {
cat("gamma:\n")
cat("------\n")
print(sprintf("Min: %0.6f, Max: %0.6f", min(conv$gamma_acc$rate),
max(conv$gamma_acc$rate)))
}
}
} |
cmpndNoiseParamInit <-
function(noise, y) {
if (nargs() > 1) {
if (length(noise$comp) != dim(y)[2])
stop("Number of noise components must match dimensions of y.")
}
noise$nParams = 0
for (i in 1:length(noise$comp)) {
if (nargs() > 1)
noise$comp[[i]] = noiseParamInit(noise$comp[[i]], y[,i])
else {
noise$comp[[i]]$numProcess = 1
noise$comp[[i]] = noiseParamInit(noise$comp[[i]])
}
noise$nParams = noise$nParams + noise$comp[[i]]$nParams
}
noise$paramGroups = diag(1, nrow=noise$nParams, ncol=noise$nParams)
noise$missing=0
return (noise)
} |
newDataset <- function(x, name = NULL, ...) {
Call <- match.call()
if (is.character(x)) {
Call[[1]] <- as.name("newDatasetFromFile")
return(eval.parent(Call))
}
is.2D <- !is.null(dim(x)) && length(dim(x)) %in% 2
if (!is.2D) {
halt(
"Can only make a Crunch dataset from a two-dimensional data ",
"structure"
)
}
if (is.null(name)) {
name <- deparseAndFlatten(substitute(x), max_length = 40)
}
d <- prepareDataForCrunch(x, name = name, ...)
ds <- createWithPreparedData(d)
invisible(ds)
}
createDataset <- function(name, body, ...) {
if (missing(body)) {
body <- wrapEntity(name = name, ...)
}
dataset_url <- crPOST(sessionURL("datasets"), body = toJSON(body))
dropDatasetsCache()
return(invisible(loadDatasetFromURL(dataset_url)))
}
prepareDataForCrunch <- function(data, ...) {
progressMessage("Processing the data")
vars <- lapply(
names(data),
function(i) toVariable(data[[i]], name = i, alias = i)
)
names(vars) <- names(data)
cols <- data.frame(lapply(vars, vget("values")), check.names = FALSE)
vars <- lapply(vars, function(v) {
v[["values"]] <- NULL
return(v)
})
meta <- shojifyDatasetMetadata(vars, ...)
return(structure(cols, metadata = meta))
}
createWithPreparedData <- function(data, metadata = attr(data, "metadata")) {
createWithMetadataAndFile(metadata, data)
}
writePreparedData <- function(data, metadata = attr(data, "metadata"), file) {
filenames <- paste(file, c("csv.gz", "json"), sep = ".")
write.csv.gz(data, filenames[1])
cat(toJSON(metadata), file = filenames[2])
return(filenames)
}
write.csv.gz <- function(x, file, na = "", row.names = FALSE, ...) {
gf <- gzfile(file, "w")
on.exit(close(gf))
invisible(write.csv(x, file = gf, na = na, row.names = row.names, ...))
}
createWithMetadataAndFile <- function(metadata, file, strict = TRUE) {
ds <- uploadMetadata(metadata)
ds <- uploadData(ds, file, strict, first_batch = TRUE)
progressMessage("Done!")
return(ds)
}
uploadMetadata <- function(metadata) {
progressMessage("Uploading metadata")
if (is.character(metadata)) {
metadata <- fromJSON(metadata, simplifyVector = FALSE)
}
return(createDataset(body = metadata))
}
uploadData <- function(dataset, data, strict = TRUE, first_batch = TRUE) {
progressMessage("Uploading data")
if (!is.character(data)) {
f <- tempfile()
write.csv.gz(data, f)
data <- f
}
return(addBatchFile(dataset, data, strict = strict, first_batch = TRUE))
}
shojifyDatasetMetadata <- function(metadata, order = I(names(metadata)), ...) {
tbl <- list(element = "crunch:table", metadata = metadata, order = order)
return(wrapEntity(..., table = tbl))
}
newDatasetByColumn <- function(x,
name = deparseAndFlatten(
substitute(x),
max_length = 40
), ...) {
vardefs <- lapply(
names(x),
function(v) toVariable(x[[v]], name = v, alias = v)
)
ds <- createDataset(name = name, ...)
ds <- addVariables(ds, vardefs)
ds <- saveVersion(ds, "initial import")
invisible(ds)
}
newDatasetFromFile <- function(x, name = basename(x), schema, ...) {
if (!missing(schema)) {
schema_source <- createSource(schema)
body_payload <- list(name = name, table = list(source = schema_source))
ds <- createDataset(body = body_payload, ...)
ds <- addBatchFile(ds, x, first_batch = TRUE, schema = schema_source)
} else {
ds <- createDataset(name = name, ...)
ds <- addBatchFile(ds, x, first_batch = TRUE)
}
return(invisible(ds))
}
newExampleDataset <- function(name = "pets") {
name <- match.arg(name)
m <- fromJSON(
system.file("example-datasets", paste0(name, ".json"), package = "crunch"),
simplifyVector = FALSE
)
return(createWithMetadataAndFile(
m,
system.file("example-datasets", paste0(name, ".csv"), package = "crunch")
))
} |
view_plate <- function(data, well_ids_column, columns_to_display,
plate_size = 96) {
data <- as.data.frame(data)
check_well_ids_column_name(well_ids_column)
validate_column_is_in_data(data, c(well_ids_column, columns_to_display))
n_rows <- number_of_rows(plate_size)
n_columns <- number_of_columns(plate_size)
data[ , well_ids_column] <- as.character(data[[well_ids_column]])
data <- ensure_correct_well_ids(data, well_ids_column, plate_size)
result <- lapply(columns_to_display, function(x) {
display_one_layout(data, well_ids_column, x, n_rows, n_columns)
})
names(result) <- columns_to_display
result
}
display_one_layout <- function(data, well_ids_column, column_to_display,
n_rows, n_columns) {
data <- sort_by_well_ids(data, well_ids_column, n_rows * n_columns)
to_display <- as.character(data[[column_to_display]])
to_display <- ifelse(is.na(to_display), ".", to_display)
result <- data.frame(matrix(to_display, nrow = n_rows, byrow = TRUE))
rownames(result) <- MEGALETTERS(1:n_rows)
colnames(result) <- 1:n_columns
result
}
ensure_correct_well_ids <- function(data, well_ids_column, plate_size) {
wells <- data[[well_ids_column]]
true_wells <- get_well_ids(plate_size)
if (length(wells) > plate_size) {
stop(paste0("There are more rows in your data ",
"frame than wells in the plate size you specified. In other words, ",
"data$", well_ids_column, " has ", length(wells), " elements, which is ",
"longer than plate_size = ", plate_size), call. = FALSE)
}
if (are_well_ids_correct(wells, plate_size)) {
return(data)
} else {
if(!are_leading_zeroes_valid(data, well_ids_column, plate_size)) {
data <- correct_leading_zeroes(data, well_ids_column, plate_size)
}
if (length(wells) < plate_size) {
data <- fill_in_missing_well_ids(data, well_ids_column, plate_size)
}
if(are_well_ids_correct(data[[well_ids_column]], plate_size)) {
return(data)
} else {
stop("Well IDs are invalid.", call. = FALSE)
}
}
}
are_well_ids_correct <- function(wells, plate_size) {
if (length(wells) != plate_size) {
return(FALSE)
}
true_wells <- get_well_ids(plate_size)
return(all(wells %in% true_wells) & all(true_wells %in% wells))
}
fill_in_missing_well_ids <- function(data, well_ids_column, plate_size) {
if (nrow(data) >= plate_size) {
stop(paste0("data has ", nrow(data), " rows, which is >= the plate size ",
"(", plate_size, "). It should have fewer rows."), call. = FALSE)
}
if(!are_leading_zeroes_valid(data, well_ids_column, plate_size)) {
stop("Some well IDs are missing leading zeroes.", call. = FALSE)
}
wells <- as.character(data[[well_ids_column]])
complete <- get_well_ids(plate_size)
missing <- !(complete %in% wells)
wells_to_add <- complete[missing]
temp <- data[0 , -which(colnames(data) == well_ids_column), drop = FALSE]
temp[1:length(wells_to_add), ] <- NA
original_names <- colnames(temp)
temp <- cbind(temp, wells_to_add)
colnames(temp) <- c(original_names, well_ids_column)
if (is.factor(data[[well_ids_column]])) {
data[[well_ids_column]] <- factor(data[[well_ids_column]], levels = complete)
temp[[well_ids_column]] <- factor(temp[[well_ids_column]], levels = complete)
}
return(rbind(data, temp))
}
are_leading_zeroes_valid <- function(data, well_ids_column, plate_size) {
wells <- data[[well_ids_column]]
missing <- get_well_ids_without_leading_zeroes(plate_size)
missing <- missing[nchar(missing) == 2]
if (any(wells %in% missing)) {
return(FALSE)
}
return(TRUE)
}
correct_leading_zeroes <- function(data, well_ids_column, plate_size) {
was_factor <- FALSE
if(is.factor(data[[well_ids_column]])) {
was_factor <- TRUE
data[[well_ids_column]] <- as.character(data[[well_ids_column]])
}
missing <- get_well_ids_without_leading_zeroes(plate_size)
correct <- get_well_ids(plate_size)
lookup <- data.frame(correct = correct, missing = missing,
stringsAsFactors = FALSE)
matches <- match(data[ , well_ids_column], lookup$missing)
data$temp <- lookup$correct[matches]
data[ , well_ids_column] <- ifelse(is.na(data$temp),
as.character(data[ , well_ids_column]),
as.character(data$temp))
data <- data[ , !(names(data) =="temp")]
if(was_factor) {
data[ , well_ids_column] <- factor(data[ , well_ids_column])
}
return(data)
} |
context("addUIds")
library(testthat)
pedOne <- data.frame(id = c("s1", "d1", "s2", "d2", "o1", "o2", "o3", "o4"),
sire = c(NA, "s0", "s4", NA, "s1", "s1", "s2", "s2"),
dam = c(NA, "d0", "d4", NA, "d1", "d2", "d2", "d2"),
sex = c("M", "F", "M", "F", "F", "F", "F", "M"),
stringsAsFactors = FALSE)
pedTwo <- data.frame(id = c("s1", "d1", "s2", "d2", "o1", "o2", "o3", "o4"),
sire = c(NA, "s0", "s4", NA, "s1", "s1", "s2", "s2"),
dam = c("d0", "d0", "d4", NA, "d1", "d2", "d2", "d2"),
sex = c("M", "F", "M", "F", "F", "F", "F", "M"),
stringsAsFactors = FALSE)
pedThree <- data.frame(id = c("s1", "d1", "s2", "d2", "o1", "o2", "o3", "o4"),
sire = c("s0", "s0", "s4", NA, "s1", "s1", "s2", "s2"),
dam = c(NA, "d0", "d4", NA, "d1", "d2", "d2", "d2"),
sex = c("M", "F", "M", "F", "F", "F", "F", "M"),
stringsAsFactors = FALSE)
test_that("addUIds modifies the correct IDs in the right way", {
newPed <- addUIds(pedOne)
expect_equal(newPed, pedOne)
newPed <- addUIds(pedTwo)
expect_equal(newPed$sire[newPed$id == "s1"], "U0001")
newPed <- addUIds(pedThree)
expect_equal(newPed$dam[newPed$id == "s1"], "U0001")
}) |
context("tests based on ex1")
test_that("identfiability", {
data("ex1")
expect_true(isIdentified(ex1$amat.cpdag, 6, 10))
expect_true(isIdentified(ex1$amat.cpdag, c(6,7), 10))
expect_true(isIdentified(ex1$amat.cpdag, 7, 9))
expect_false(isIdentified(ex1$amat.cpdag, 5, 10))
expect_false(isIdentified(ex1$amat.cpdag, c(1,3), 9))
})
test_that("estimation", {
data("ex1")
pairs <- list(
list(x=6, y=10),
list(x=c(6,7), y=10),
list(x=7, y=9),
list(x=c(3,4,5), y=8),
list(x=c(3,4,5), y=7),
list(x=c(3,4,5,6), y=8)
)
for (i in 1:length(pairs)) {
.x <- pairs[[i]]$x
.y <- pairs[[i]]$y
truth <- getEffectsFromSEM(ex1$B, .x, .y)
est <- estimateEffect(ex1$data, .x, .y, ex1$amat.cpdag, bootstrap=FALSE)
err <- sqrt(mean((est - truth)^2))
expect_lt(err, 0.03)
}
}) |
dwt.vt <- function(data, wf, J, method, pad, boundary, cov.opt = c("auto", "pos", "neg"),
flag = "biased", detrend = FALSE) {
x <- data$x
dp <- as.matrix(data$dp)
mu.dp <- apply(dp, 2, mean)
ndim <- ncol(dp)
n <- nrow(dp)
S <- matrix(nrow = J + 1, ncol = ndim)
dp.n <- matrix(nrow = n, ncol = ndim)
idwt.dp <- vector("list", ndim)
for (i in 1:ndim) {
if (!detrend) {
dp.c <- scale(dp[, i], scale = F)
} else {
dp.c <- dp[, i] - smooth.spline(1:n, dp[, i], spar = 1)$y
}
dp.p <- padding(dp.c, pad = pad)
idwt.dp[[i]] <- waveslim::mra(dp.p, wf = wf, J = J, method = method, boundary = boundary)
B <- matrix(unlist(lapply(idwt.dp[[i]], function(z) z[1:n])), ncol = J + 1, byrow = FALSE)
Bn <- scale(B)
V <- as.numeric(apply(B, 2, sd))
dif <- sum(abs(Bn %*% V - dp.c))
if (dif > 10^-10) warning(paste0("Difference between Reconstructed and original:", dif))
cov <- cov(x, Bn[seq_len(length(x)), ])
if (flag == "unbiased") {
idwt.dp.n <- non.bdy(idwt.dp[[i]], wf = wf, method = "mra")
B.n <- matrix(unlist(lapply(idwt.dp.n, function(z) z[1:n])), ncol = J + 1, byrow = FALSE)
cov <- cov(x, scale(B.n)[seq_len(length(x)), ], use = "pairwise.complete.obs")
cov[is.na(cov)] <- cov(x, Bn[seq_len(length(x)), ])[is.na(cov)]
}
if (cov.opt == "pos") cov <- cov else if (cov.opt == "neg") cov <- -cov
S[, i] <- as.vector(cov)
Vr <- as.numeric(cov / norm(cov, type = "2") * sd(dp.c))
if (!detrend) {
dp.n[, i] <- Bn %*% Vr + mu.dp[i]
} else {
dp.n[, i] <- Bn %*% Vr + smooth.spline(1:n, dp[, i], spar = 1)$y
}
if (cov.opt == "auto") {
if (cor.test(dp.n[, i], dp[, i])$estimate < 0 & cor.test(dp.n[, i], dp[, i])$p.value < 0.05) cov <- -cov
S[, i] <- as.vector(cov)
Vr <- as.numeric(cov / norm(cov, type = "2") * sd(dp.c))
if (!detrend) {
dp.n[, i] <- Bn %*% Vr + mu.dp[i]
} else {
dp.n[, i] <- Bn %*% Vr + smooth.spline(1:n, dp[, i], spar = 1)$y
}
}
dif.var <- abs(var(dp[, i]) - var(dp.n[, i])) / var(dp[, i])
if (dif.var > 0.15) warning(paste0("Variance difference between Transformed and original(percentage):", dif.var * 100))
}
dwt <- list(
wavelet = wf,
method = method,
boundary = boundary,
pad = pad,
x = x,
dp = dp,
dp.n = dp.n,
S = S
)
class(dwt) <- "dwt"
return(dwt)
}
dwt.vt.val <- function(data, J, dwt, detrend = FALSE) {
x <- data$x
dp <- as.matrix(data$dp)
wf <- dwt$wavelet
method <- dwt$method
boundary <- dwt$boundary
pad <- dwt$pad
mu.dp <- apply(dp, 2, mean)
ndim <- ncol(dp)
n <- nrow(dp)
dp.n <- matrix(nrow = n, ncol = ndim)
idwt.dp <- vector("list", ndim)
for (i in 1:ndim) {
if (!detrend) {
dp.c <- scale(dp[, i], scale = FALSE)
} else {
dp.c <- dp[, i] - smooth.spline(1:n, dp[, i], spar = 1)$y
}
dp.p <- padding(dp.c, pad = pad)
idwt.dp[[i]] <- waveslim::mra(dp.p, wf = wf, J = J, method = method, boundary = boundary)
B <- matrix(unlist(lapply(idwt.dp[[i]], function(z) z[1:n])), ncol = J + 1, byrow = FALSE)
Bn <- scale(B)
V <- as.numeric(apply(B, 2, sd))
dif <- sum(abs(Bn %*% V - dp.c))
if (dif > 10^-10) warning(paste0("Difference between Reconstructed and original:", dif))
cov <- rep(0, J + 1)
if (length(dwt$S[, i]) > (J + 1)) {
cov <- dwt$S[, i][1:(J + 1)]
} else {
cov[seq_len(length(dwt$S[, i]))] <- dwt$S[, i]
}
Vr <- as.numeric(cov / norm(cov, type = "2") * sd(dp.c))
if (!detrend) {
dp.n[, i] <- Bn %*% Vr + mu.dp[i]
} else {
dp.n[, i] <- Bn %*% Vr + smooth.spline(1:n, dp[, i], spar = 1)$y
}
}
dwt <- list(
wavelet = wf,
method = method,
boundary = boundary,
pad = pad,
x = x,
dp = dp,
dp.n = dp.n,
S = dwt$S
)
class(dwt) <- "dwt"
return(dwt)
}
padding <- function(x, pad = c("per", "zero", "sym")) {
n <- length(x)
N <- 2^(ceiling(log(n, 2)))
if (pad == "per") {
xx <- c(x, x)[1:N]
} else if (pad == "zero") {
xx <- c(x, rep(0, N - n))
} else {
xx <- c(x, rev(x))[1:N]
}
} |
setMethod('crosstab', signature(x='Raster', y='Raster'),
function(x, y, digits=0, long=FALSE, useNA=FALSE, progress='', ...) {
x <- stack(x, y)
crosstab(x, digits=digits, long=long, useNA=useNA, progress=progress, ...)
}
)
setMethod('crosstab', signature(x='RasterStackBrick', y='missing'),
function(x, digits=0, long=FALSE, useNA=FALSE, progress='', ...) {
nl <- nlayers(x)
if (nl < 2) {
stop('crosstab needs at least 2 layers')
}
nms <- names(x)
if (canProcessInMemory(x)) {
res <- getValues(x)
res <- lapply(1:nl, function(i) round(res[, i], digits=digits))
res <- do.call(table, c(res, useNA='ifany'))
res <- as.data.frame(res)
} else {
tr <- blockSize(x)
pb <- pbCreate(tr$n, label='crosstab', progress=progress)
res <- NULL
for (i in 1:tr$n) {
d <- getValuesBlock(x, row=tr$row[i], nrows=tr$nrows[i])
d <- lapply(1:nl, function(i) round(d[, i], digits=digits))
d <- do.call(table, c(d, useNA='ifany'))
d <- as.data.frame(d)
res <- rbind(res, d)
pbStep(pb, i)
}
pbClose(pb)
res <- res[res$Freq > 0, ,drop=FALSE]
if (useNA) {
for (i in 1:(ncol(res)-1)) {
if (any(is.na(res[,i]))) {
res[,i] <- factor(res[,i], levels=c(levels(res[,i]), NA), exclude=NULL)
}
}
}
res <- aggregate(res[, ncol(res), drop=FALSE], res[, 1:(ncol(res)-1), drop=FALSE], sum)
}
for (i in 1:(ncol(res)-1)) {
res[,i] <- as.numeric(as.character(res[,i]))
}
if (nrow(res) == 0) {
res <- data.frame(matrix(nrow=0, ncol=length(nms)+1))
}
colnames(res) <- c(nms, 'Freq')
if (! useNA ) {
i <- apply(res, 1, function(x) any(is.na(x)))
res <- res[!i, ,drop=FALSE]
}
if (!long) {
f <- eval(parse(text=paste('Freq ~ ', paste(nms , collapse='+'))))
res <- stats::xtabs(f, data=res, addNA=useNA)
} else {
res <- res[res$Freq > 0, ,drop=FALSE]
res <- res[order(res[,1], res[,2]), ]
rownames(res) <- NULL
}
return(res)
}
)
.oldcrosstab <- function(x, y, digits=0, long=FALSE, progress, ...) {
compareRaster(c(x, y))
if (missing(progress)) { progress <- .progress() }
if (canProcessInMemory(x, 3) | ( inMemory(x) & inMemory(y) )) {
res <- table(first=round(getValues(x), digits=digits), second=round(getValues(y), digits=digits), ...)
} else {
res <- NULL
tr <- blockSize(x, n=2)
pb <- pbCreate(tr$n, label='crosstab', progress=progress)
for (i in 1:tr$n) {
d <- table( round(getValuesBlock(x, row=tr$row[i], nrows=tr$nrows[i]), digits=digits), round(getValuesBlock(y, row=tr$row[i], nrows=tr$nrows[i]), digits=digits), ...)
if (length(dim(d))==1) {
first = as.numeric(names(d))
second = first
d <- matrix(d)
} else {
first = as.numeric(rep(rownames(d), each=ncol(d)))
second = as.numeric(rep(colnames(d), times=nrow(d)))
}
count = as.vector(t(d))
res = rbind(res, cbind(first, second, count))
pbStep(pb, i)
}
pbClose(pb)
res <- stats::xtabs(count~first+second, data=res)
}
if (long) {
return( as.data.frame(res) )
} else {
return(res)
}
} |
"PbHeron" |
context("test model2netcdf.dvmdostem")
test_that("PLACEHOLDER", {
}) |
trans_composition <- function( x=NULL, nb=30, brk=NA, dab=NA, dgrd=NA, dgrd2=NA ){
if(is.null(x)|missing(x)){stop('x should be a numerical vector')}
xori=as.numeric(x)
if(sum(is.na(xori))>0){stop('x is should not included NAs')}
if(typeof(x)!='double'|length(xori)<2){stop('x should be a numerical vector')}
if(is.null(nb)|missing(nb)){nb=NA}
nb=as.numeric(nb)
if(is.na(nb)|length(nb)!=1){nb=30}
xb=unique(xori)
xb=xb[order(xb)]
xnb=length(nb)
if(xnb>nb){stop('x has more distinct values than nb')}
if(is.null(brk)|missing(brk)){brk=max(xori)+1}
brk=as.numeric(brk)
if(is.na(brk)|length(brk)!=1){brk=max(xori)+1}
if(is.null(dab)|missing(dab)){dab=NA}
dab=as.numeric(dab)
if(is.na(dab)|length(dab)!=1|dab<=0){dab=as.numeric(quantile(diff(xb),0.2))}
if(is.null(dgrd)|missing(dgrd)){dgrd=NA}
if(is.na(dgrd)|length(dgrd)!=1){ if(brk>min(xori)){dgrd=((min(max(xori),brk)-min(xori))/24)}else{dgrd=((max(xori)-min(xori))/24)} }
if(is.null(dgrd2)|missing(dgrd2)){dgrd2=NA}
if(is.na(dgrd2)|length(dgrd2)!=1){if(brk>min(xori)){dgrd2=((min(max(xori),brk)-min(xori))/48)}else{dgrd2=((max(xori)-min(xori))/48)}}
trans=identity_trans()
trans$name='composition'
xl1=c();xb1=c();xl2=c();xb2=c()
if(brk>=max(xb)){
xl1=xb
xb1=xb
trans$breaks=function(x,n=xnb){
x=x[is.finite(x)]
if(length(x)==0){return(numeric())}
if(sum(!missing(x))==0){return(numeric())}
fxl1=eval(xl1)
fxb1=eval(xb1)
if(sum(!is.na(fxl1))<2 | sum(!is.na(fxb1))<2){return(x)}
mingr=eval(dgrd)
for(itr0 in 1:5){
if(min(diff(fxl1))>=mingr){
break
}else{
for(itr in 2:length(fxl1)){
if(fxl1[itr]-fxl1[itr-1]<mingr){
if(round(fxl1[itr])==fxl1[itr]&round(fxl1[itr-1])!=fxl1[itr-1]){
fxl1[itr-1]=fxl1[itr]
}else{
fxl1[itr]=fxl1[itr-1]
}
}
}
}
}
fxl1=unique(fxl1)
fxl1
}
}else if(brk<=min(xb)){
xl2=xb
xb2=seq(min(xl2),min(xl2)+(length(xb)-1)*dab, by=dab)
trans$transform=function(x){
if(length(x)==0){return(x)}
if(sum(!missing(x))==0){return(x)}
if(sum(!is.na(x))==0){return(x)}
fxl2=eval(xl2)
fxb2=eval(xb2)
if(sum(!is.na(fxl2))<2 | sum(!is.na(fxb2))<2){return(x)}
ff=approx(fxl2, fxb2, x, method='linear', rule=2)$y
ff
}
trans$inverse=function(x){
if(length(x)==0){return(x)}
if(sum(!missing(x))==0){return(x)}
if(sum(!is.na(x))==0){return(x)}
fxl2=eval(xl2)
fxb2=eval(xb2)
if(sum(!is.na(fxl2))<2 | sum(!is.na(fxb2))<2){return(x)}
ff=approx(fxb2, fxl2, x, method='linear', rule=2)$y
ff
}
trans$breaks=function(x,n=xnb){
x=x[is.finite(x)]
if(length(x)==0){return(numeric())}
if(sum(!missing(x))==0){return(numeric())}
fxl2=eval(xl2)
fxb2=eval(xb2)
if(sum(!is.na(fxl2))<2 | sum(!is.na(fxb2))<2){return(x)}
fxl2=eval(xl2)
out=c(fxl2)
out
}
}else{
xl1=xb[xb<=brk]
xb1=xl1
xl2=xb[xb>brk]
xb2=max(xb1)+dab*1+seq(dab,length(xl2)*dab,by=dab)
brk=max(xb1)+dab
trans$transform=function(x){
if(length(x)==0){return(x)}
if(sum(!missing(x))==0){return(x)}
if(sum(!is.na(x))==0){return(x)}
fxl2=eval(xl2)
fxb2=eval(xb2)
fbrk=eval(brk)
if(sum(!is.na(fxl2))<2 | sum(!is.na(fxb2))<2){return(x)}
ff=approx(fxl2, fxb2, x, method='linear', rule=2)$y
x*(x<=fbrk)+(x>fbrk)*ff
}
trans$inverse=function(x){
if(length(x)==0){return(x)}
if(sum(!missing(x))==0){return(x)}
if(sum(!is.na(x))==0){return(x)}
fxl2=eval(xl2)
fxb2=eval(xb2)
fbrk=eval(brk)
if(sum(!is.na(fxl2))<2 | sum(!is.na(fxb2))<2){return(x)}
ff=approx(fxb2, fxl2, x, method='linear', rule=2)$y
x*(x<=fbrk)+(x>fbrk)*ff
}
trans$breaks=function(x,n=xnb){
x=x[is.finite(x)]
if(length(x)==0){return(numeric())}
if(sum(!missing(x))==0){return(numeric())}
x=unique(x)
fxl1=eval(xl1)
fxb1=eval(xb1)
if(sum(!is.na(fxl1))<2 | sum(!is.na(fxb1))<2){return(x)}
mingr=eval(dgrd)
for(itr0 in 1:5){
if(min(diff(fxl1))>=mingr){
break
}else{
for(itr in 2:length(fxl1)){
if(fxl1[itr]-fxl1[itr-1]<mingr){
if(round(fxl1[itr])==fxl1[itr]&round(fxl1[itr-1])!=fxl1[itr-1]){
fxl1[itr-1]=fxl1[itr]
}else{
fxl1[itr]=fxl1[itr-1]
}
}
}
}
}
fxl1=unique(fxl1)
fxl2=eval(xl2)
out=c(fxl1, fxl2)
out
}
}
trans$minor_breaks=function(b,limits=range(xb),n=xnb){
b=b[is.finite(b)]
if(length(b)<2){return(numeric())}
if(sum(!missing(b))==0){ return(numeric())}
fxl=eval(xb)
fbrk=eval(brk)
if(length(fxl)<=2){ return(numeric())}
fd=eval(dgrd2)
fxlmin=floor(min(fxl))
fxlmax=ceiling(max(fxl))
if(max(limits)>fxlmax) fxlmax=ceiling(max(limits))
if(min(limits)<fxlmax) fxlmin=floor(min(limits))
if(fbrk > fxlmin){ fxc=min(fxlmax, fbrk) }else{ fxc=fxlmax }
if(is.na(fd)|fd==0|!is.finite(fd)){fd=1}
fm=max(2,floor(1+(fxc-fxlmin)/fd))
if(is.na(fm)|fm==0|!is.finite(fm)){fm=2}
out1=labeling::extended(fxlmin, fxc, m=fm)
out1
}
trans
} |
library(mclust)
gmm_fit <- Mclust(iris[, 1:4])
summary(gmm_fit)
plot(gmm_fit, 'BIC') |
conv.check <- function(x){
est.probs <- c(x$fit$p1, x$fit$p2, x$fit$p3, x$fit$c.copula.be2, x$fit$c.copula.be1)
est.dens <- c(x$fit$pdf1, x$fit$pdf2, x$fit$pdf3, x$fit$c.copula2.be1be2)
e.v <- eigen(x$fit$hessian, symmetric = TRUE, only.values = TRUE)$values
cat("\nLargest absolute gradient value:",max(abs(x$fit$gradient)))
if(x$hess==TRUE) mv <- "Observed" else mv <- "Expected"
if (min(e.v) > 0) cat("\n",mv," information matrix is positive definite\n",sep="") else cat("\n",mv," information matrix is not positive definite\n",sep="")
cat("Eigenvalue range: [",min(e.v),",",max(e.v),"]\n", sep = "")
if( (x$l.sp1!=0 || x$l.sp2!=0 || x$l.sp3!=0 || x$l.sp4!=0 || x$l.sp5!=0 || x$l.sp6!=0 || x$l.sp7!=0 || x$l.sp8!=0 || x$l.sp9!=0) && x$fp==FALSE ){
cat("\nTrust region iterations before smoothing parameter estimation:",x$iter.if)
cat("\nLoops for smoothing parameter estimation:",x$iter.sp)
cat("\nTrust region iterations within smoothing loops:",x$iter.inner)
}else{cat("\nTrust region iterations:",x$iter.if)}
if( any( is.na(est.probs) == FALSE ) ) cat("\nEstimated overall probability range:",range(est.probs, na.rm = TRUE))
if( any( is.na(est.dens) == FALSE ) ) cat("\nEstimated overall density range:",range(est.dens, na.rm = TRUE))
cat("\n\n")
} |
NULL
axe_call.sclass <- function(x, verbose = FALSE, ...) {
old <- x
x$btree <- axe_call(x$btree, ...)
add_butcher_attributes(
x,
old,
verbose = verbose
)
}
axe_env.sclass <- function(x, verbose = FALSE, ...) {
old <- x
x$btree <- axe_env(x$btree, ...)
add_butcher_attributes(
x,
old,
verbose = verbose
)
} |
manualrotate <- function(datat1, datat2){
if(class(datat1) != c('RasterLayer')) stop('datat1 must be a raster file.')
if(class(datat2) != c('RasterLayer')) stop('datat2 must be a raster file.')
res1 <- raster::res(datat1)
res2 <- raster::res(datat2)
if(res1[1] > res2[1]){datat2 <- raster::resample(datat2, datat1, method = "ngb")}
if(res1[1] < res2[1]){datat1 <- raster::resample(datat1, datat2, method = "ngb")}
stopifnot(raster::res(datat1)[1] == raster::res(datat2)[1])
conversionfactor <- ifelse(raster::res(datat1) == 56, 0.774922, 0.222394)
datat1 <- raster::rasterToPoints(datat1)
datat2 <- raster::rasterToPoints(datat2)
datat1 <- data.table::as.data.table(datat1)
datat2 <- data.table::as.data.table(datat2)
pixelcounts <- merge(datat1, datat2, by = c('x', 'y')) %>%
as.data.frame() %>%
'colnames<-'(c('x', 'y', 'value.x', 'value.y')) %>%
dplyr::filter(value.x > 0, value.y > 0) %>%
dplyr::group_by(value.x, value.y) %>%
dplyr::summarise(Count = dplyr::n()) %>%
dplyr::left_join(., linkdata, by = c('value.x' = 'MasterCat')) %>%
dplyr::left_join(., linkdata, by = c('value.y' = 'MasterCat')) %>%
dplyr::ungroup() %>%
dplyr::select(-value.x, -value.y) %>%
dplyr::rename(From = Crop.x, To = Crop.y) %>%
dplyr::mutate(Acreage = Count*conversionfactor[1])
return(pixelcounts)
} |
libxmlFeatures =
function()
{
.Call("R_getXMLFeatures", PACKAGE = "XML")
} |
decision_curve <- function(formula,
data,
family = binomial(link = 'logit'),
policy = c('opt-in', 'opt-out'),
fitted.risk = FALSE,
thresholds = seq(0, 1, by = .01),
confidence.intervals = 0.95,
bootstraps = 500,
study.design = c('cohort', 'case-control'),
population.prevalence){
call <- match.call()
stopifnot(class(formula) == 'formula')
stopifnot(is.data.frame(data))
stopifnot(is.logical(fitted.risk))
stopifnot(is.numeric(thresholds))
stopifnot(all(thresholds >= 0)); stopifnot(all(thresholds <= 1));
if(is.numeric(confidence.intervals)) stopifnot(confidence.intervals > 0 & confidence.intervals < 1)
stopifnot(is.numeric(bootstraps))
policy <- match.arg(policy)
opt.in = policy == 'opt-in'
study.design <- match.arg(study.design)
if(!missing(population.prevalence)) {
stopifnot(is.numeric(population.prevalence))
stopifnot(population.prevalence > 0 & population.prevalence < 1)
}
if(any( names.check <- !is.element(all.vars(formula), names(data)))) stop(paste('variable(s)', paste( all.vars(formula)[names.check], collapse = ', ') , 'not found in "data"'))
data <- data[,all.vars(formula)]
cc.ind <- complete.cases(data)
if(sum(cc.ind) < nrow(data)) warning(paste(sum(1-cc.ind), 'observation(s) with missing data removed'))
data <- data[cc.ind,]
if(missing(population.prevalence)) population.prevalence <- NULL
if(study.design == 'cohort'){
if(!is.null(population.prevalence)){
warning('population.prevalence was provided, but study.design = "cohort". The value input for population.prevalence will be ignored. If you are using case-control data, please set study.design = "case-control".')
}
}else{
if(missing(population.prevalence)){
stop('Need to set population.prevalence to calculate decision curves using case-control data.')
if(family$family != 'binomial') stop('Calculations for case-control data are done assuming logistic regression (family = binomial(link = "logit"))')
}else{
stopifnot(0< population.prevalence & population.prevalence <1)
message('Calculating net benefit curves for case-control data. All calculations are done conditional on the outcome prevalence provided.')
}
}
outcome <- data[[all.vars(formula[[2]])]];
predictors <- c(Reduce(paste, deparse(formula[[3]])), 'All', 'None')
predictor.names <- c(Reduce(paste, deparse(formula)), 'All', 'None')
if(length(unique(outcome)) != 2) stop('outcome variable is not binary (it does not take two unique values).')
stopifnot(is.numeric(outcome))
if(min(outcome) != 0 | max(outcome) != 1) stop('outcome variable must be binary taking on values 0 for control and 1 for case.')
if(fitted.risk){
if(length(all.vars(formula[[3]])) > 1) stop('When fitted.risk = TRUE, there can only be one term (denoting the fitted risks) on the right hand side of the formula provided.')
provided.risks <- data[[Reduce(paste, deparse(formula[[3]]))]]
if(min(provided.risks) < 0 | max(provided.risks) > 1) stop('When fitted.risks = TRUE, all risks provided must be between 0 and 1.')
}else if(length(strsplit(predictors[[1]], "+", fixed = TRUE)[[1]]) > 1) {
message("Note: The data provided is used to both fit a prediction model and to estimate the respective decision curve. This may cause bias in decision curve estimates leading to over-confidence in model performance. ")
}
formula.ind <- c(ifelse(fitted.risk, FALSE, TRUE), FALSE, FALSE)
data[['All']] <- 1
data[['None']] <- 0
n.preds <- length(predictors)
n.out <- length(predictors)*length(thresholds)
dc.data <- data.frame('thresholds' = numeric(n.out),
'FPR' = numeric(n.out), 'FNR' = numeric(n.out),
'TPR' = numeric(n.out),'TNR' = numeric(n.out),
'NB' = numeric(n.out), 'sNB' = numeric(n.out),
'rho' = numeric(n.out),
'prob.high.risk' = numeric(n.out),
'prob.low.risk' = numeric(n.out),
'DP' = numeric(n.out),
'nonDP' = numeric(n.out),
'model'= numeric(n.out))
if(is.numeric(confidence.intervals)) {
if(bootstraps < 1 ) stop('bootstraps must be greater than 0. If no confidence intervals are needed, set `confidence.intervals = "none"`')
B.ind <- matrix(nrow = nrow(data), ncol = bootstraps)
if(study.design == 'cohort'){
for(b in 1:bootstraps) B.ind[,b] <- sample.int(nrow(data), replace = TRUE)
}else{
all.ind <- 1:nrow(data)
uu <- unique(outcome)
for(b in 1:bootstraps){
ind.1 <- sample(all.ind[outcome == uu[1] ], replace = TRUE)
ind.2 <- sample(all.ind[outcome == uu[2] ], replace = TRUE)
B.ind[,b] <- c(ind.1, ind.2)
}
}
dc.data <- add.ci.columns(dc.data)
}
index = 1
n.pred = 1
for(i in 1:n.preds){
tmpNBdata <- calculate.nb(d = outcome,
y = data[[predictors[[i]]]],
rH = thresholds,
formula = formula,
family = family,
data = data,
formula.ind = formula.ind[i],
casecontrol.rho = population.prevalence,
opt.in = opt.in)
tmpNBdata$model <- predictor.names[[i]]
if(is.numeric(confidence.intervals)){
boot.data <- apply(B.ind, 2, function(x){
calculate.nb(d = outcome[x],
y = data[[predictors[[i]] ]][x],
rH = thresholds,
formula = formula,
family = family,
data = data[x,],
formula.ind = formula.ind[i],
casecontrol.rho = population.prevalence,
opt.in = opt.in)})
alpha = 1- confidence.intervals
xx <- NULL
for(rtn in names(boot.data[[1]][-1])){
tmpdat <- sapply(boot.data, function(xx) xx[,rtn])
tmpNBdata[[paste(rtn, '_lower', sep = '')]] <- apply(tmpdat, 1, quantile, probs = alpha/2, type = 1, na.rm = TRUE)
tmpNBdata[[paste(rtn, '_upper', sep = '')]] <- apply(tmpdat, 1, quantile, probs = 1-alpha/2, type = 1, na.rm = TRUE)
}
}
dc.data[index:(length(thresholds)*n.pred),] <- tmpNBdata
index = index + length(thresholds)
n.pred = n.pred + 1
}
if(!is.numeric(confidence.intervals)){dc.data <- add.ci.columns(dc.data)}
dc.data$cost.benefit.ratio <- as.character(fractions(threshold_to_costbenefit(dc.data$thresholds, policy)))
add.dash1 <- which(!is.element(1:nrow(dc.data), grep('/', dc.data$cost.benefit.ratio)))
dc.data$cost.benefit.ratio[add.dash1] <- paste(dc.data$cost.benefit.ratio[add.dash1], '/1', sep = '')
dc.data$cost.benefit.ratio <- gsub('/', ':', dc.data$cost.benefit.ratio)
out <- list('derived.data' = dc.data,
'confidence.intervals' = confidence.intervals,
'policy' = policy,
'call' = call)
class(out) = 'decision_curve'
invisible(out)
} |
shinydashboard::tabItem(
tabName = "candlesticks",
fluidRow(
column(
width = 12,
br(),
tabBox(width=12,
tabPanel(
title = "Graphic",
fluidRow(
h2("Simple example", align="center"),
column(
width = 12,
rAmCharts::amChartsOutput("candl0"))
)),
tabPanel(
title = "Code",
fluidRow(
h2("Simple example", align="center"),
column(
width = 12,
verbatimTextOutput("code_candl0"))
)
)
)
)
)
) |
VAR.mseh <-
function(x,p,h,type) {
n <- nrow(x); k <- ncol(x)
var1 <- VAR.est(x,p,type)
b <- var1$coef[,1:(k*p+1)]
zz <- var1$zzmat[1:(k*p+1),1:(k*p+1)]
sigu <- var1$sigu
mf <- VAR.mainf(b,p,h)
if (h == 1) sigyh <- ( ((n-p)+k*p+1)/(n-p) ) * sigu
if (h > 1) {
if (p == 1) bb <- rbind(b,cbind(matrix(0,ncol=k*p),1))
if (p > 1) bb <- rbind(b, cbind(diag(k*(p-1)),matrix(0,nrow=k*(p-1),ncol=k),matrix(0,nrow=k*(p-1),ncol=1)),cbind(matrix(0,ncol=k*p),1))
b0 <- diag(k*p+1); bbq <- b0
for( i in 1:(h-1)){
b0 <- b0 %*% bb
bbq <- cbind(bbq,b0)}
index1 <- seq((h-1)*(k*p+1)+1,length.out=p*k+1); index3 <- 1:k
sum1 <- matrix(0,nrow=k,ncol=k); sigy <- sum1
for (i in 0:(h-1))
{
sigy <- sigy + mf[,index3]%*%sigu%*% t(mf[,index3])
index2 <- seq((h-1)*(k*p+1)+1,length.out=p*k+1); index4 <- 1:k
for (j in 0:(h-1)){
tem <- sum( diag( t(bbq[,index1]) %*% solve(zz) %*% bbq[,index2] %*% zz) ) * mf[,index3] %*% sigu %*% t(mf[,index4])
sum1 <- sum1 + tem
index2 <- index2 - (p*k+1); index4 <- index4 + k;}
index1 <- index1-(p*k+1); index3 <- index3+k
}
sigyh <- sigy + sum1/(n-p);
}
return(sigyh)
} |
glm_model <- function(data,
response_variable,
predictor_variable,
two_way_interaction_factor = NULL,
three_way_interaction_factor = NULL,
family,
quite = FALSE) {
glm_model_check <- function(object, method) {
if (method == "response_variableiable_check") {
if (length(object) != 1) {
stop("Response variable must be length of 1")
}
}
if (method == "three_way_interaction_factor_check") {
if (length(three_way_interaction_factor) != 3) {
stop("three_way_interaction_factor must have three factors")
}
}
}
response_variable <- data %>%
dplyr::select(!!enquo(response_variable)) %>%
names()
predictor_variable <- data %>%
dplyr::select(!!enquo(predictor_variable)) %>%
names()
two_way_interaction_factor <- data %>%
dplyr::select(!!enquo(two_way_interaction_factor)) %>%
names()
three_way_interaction_factor <- data %>%
dplyr::select(!!enquo(three_way_interaction_factor)) %>%
names()
predictor_variable <- predictor_variable[!predictor_variable %in% c(response_variable)]
data <- data_check(data)
predictor_variable <- predictor_variable[!predictor_variable %in% c(response_variable)]
two_way_interaction_factor <- two_way_interaction_factor[!two_way_interaction_factor %in% c(response_variable)]
three_way_interaction_factor <- three_way_interaction_factor[!three_way_interaction_factor %in% c(response_variable)]
if (length(two_way_interaction_factor) == 0) {
two_way_interaction_factor <- NULL
}
if (length(three_way_interaction_factor) == 0) {
three_way_interaction_factor <- NULL
} else {
glm_model_check(three_way_interaction_factor, method = "three_way_interaction_factor_check")
}
glm_model_check(response_variable, method = "response_variableiable_check")
two_way_interaction_terms <- NULL
three_way_interaction_terms <- NULL
if (!is.null(two_way_interaction_factor)) {
two_way_interaction_terms <- two_way_interaction_terms(two_way_interaction_factor)
}
if (!is.null(three_way_interaction_factor)) {
two_way_interaction_terms <- NULL
three_way_interaction_terms <- paste(three_way_interaction_factor, collapse = "*")
}
predictor_variable <- c(predictor_variable, two_way_interaction_terms, three_way_interaction_terms)
model <- paste(response_variable, "~", paste(predictor_variable, collapse = " + "))
if (quite == FALSE) {
cat(paste("Fitting Model with glm:\n Formula = ", model, "\n", sep = ""))
}
model <- stats::as.formula(model)
glm_model <- stats::glm(formula = model, data = data, family = family)
return(glm_model)
} |
exact.reject.region <-
function(n1, n2, alternative=c("two.sided", "less", "greater"), alpha=0.05,
npNumbers=100, np.interval=FALSE, beta=0.001,
method=c("z-pooled", "z-unpooled", "boschloo", "santner and snell", "csm", "fisher", "pearson chisq", "yates chisq"),
tsmethod=c("square", "central"), delta=0, convexity=TRUE, useStoredCSM=TRUE){
alternative <- match.arg(tolower(alternative), c("two.sided", "less", "greater"))
if (length(method)==1 && tolower(method)=="score") { method <- "z-pooled" }
method <- match.arg(tolower(method), c("z-pooled", "z-unpooled", "boschloo", "santner and snell", "csm",
"fisher", "pearson chisq", "yates chisq"))
tsmethod <- match.arg(tolower(tsmethod), c("square", "central"))
checkParam(n1=n1, n2=n2, alternative=alternative, alpha=alpha, npNumbers=npNumbers, np.interval=np.interval, beta=beta,
method=method, tsmethod=tsmethod, delta=delta, convexity=convexity, useStoredCSM=useStoredCSM)
if (alternative == "two.sided" && tsmethod == "central") {
rejectRegionUpper <- exact.reject.region(n1=n1, n2=n2, alternative="less", alpha=alpha/2,
npNumbers=npNumbers, np.interval=np.interval, beta=beta,
method=method, tsmethod=tsmethod, delta=delta, convexity=convexity,
useStoredCSM=useStoredCSM)
rejectRegionLower <- exact.reject.region(n1=n1, n2=n2, alternative="greater", alpha=alpha/2,
npNumbers=npNumbers, np.interval=np.interval, beta=beta,
method=method, tsmethod=tsmethod, delta=delta, convexity=convexity,
useStoredCSM=useStoredCSM)
rejectRegion <- rejectRegionUpper + rejectRegionLower
if (!all(rejectRegion %in% c(0,1))) { stop("Check rejection region logic") }
return(rejectRegion)
}
alternativeTemp <- alternative
swapFlg <- (alternative == "greater" || (alternative=="two.sided" && delta < 0))
if (swapFlg) {
n2temp <- n2
n2 <- n1; n1 <- n2temp;
delta <- -delta
if (alternative == "greater") { alternative <- "less" }
}
if (!np.interval && !(method %in% c("csm", "fisher"))) {
if (delta == 0) { int <- seq(0.00001,.99999,length=npNumbers)
} else if (delta > 0) { int <- seq(0.00001, 1 - delta - 0.00001, length=npNumbers)
} else if (delta < 0) { int <- seq(abs(delta) + 0.00001, .99999, length=npNumbers)}
lookupArray <- dbinomCalc(Ns = c(n1, n2), int, delta)
TX <- switch(method,
"z-pooled" = zpooled_TX(NULL, c(n1, n2), delta=delta),
"z-unpooled" = zunpooled_TX(NULL, c(n1, n2), delta=delta),
"boschloo" = fisher.2x2(NULL, c(n1, n2), alternative=alternative),
"santner and snell" = santner_TX(NULL, c(n1, n2), delta=delta),
"pearson chisq" = chisq_TX(NULL, c(n1, n2), yates=FALSE),
"yates chisq" = chisq_TX(NULL, c(n1, n2), yates=TRUE))
TX[is.na(TX[,3]), 3] <- 0
if ((alternative == "two.sided" && method != "boschloo") || (method %in% c("pearson chisq", "yates chisq"))) {TX[, 3] <- -abs(TX[,3])}
if (method %in% c("pearson chisq", "yates chisq") && alternative == "less") {TX[TX[,1]/n1 >= TX[,2]/n2, 3] <- -TX[TX[,1]/n1 >= TX[,2]/n2, 3]}
TX <- signif(TX[order(TX[,3]), ], 12)
TX <- cbind(TX, NA)
if (method %in% c("z-pooled", "z-unpooled", "santner and snell", "pearson chisq", "yates chisq") && delta==0) { TX[TX[,3] >= 0, 4] <- FALSE }
if (method == "boschloo" && delta==0) { TX[TX[,3] <= alpha, 4] <- TRUE }
moreExtremeTbls <- searchExtreme(TX = TX, n1 = n1, n2 = n2, alternative = alternative, method = method, int = int, delta = delta,
alpha = alpha, lookupArray = lookupArray)
rejectRegion <- matrix(0, n1+1, n2+1)
if (nrow(moreExtremeTbls) > 0) {
for (i in 1:nrow(moreExtremeTbls)) {
rejectRegion[moreExtremeTbls[i, 1] + 1, moreExtremeTbls[i, 2] + 1] <- 1
}
}
rownames(rejectRegion) <- 0:n1
colnames(rejectRegion) <- 0:n2
if (swapFlg){ rejectRegion <- t(rejectRegion) }
return(rejectRegion)
} else if (method == "csm") {
if (max(c(n1, n2)) <= 100 && delta == 0 && useStoredCSM) {
if (!requireNamespace("ExactData", quietly = TRUE)) {
stop(paste("ExactData R package must be installed when useStoredCSM=TRUE. To install ExactData R package, run:",
"`install.packages('ExactData', repos='https://pcalhoun1.github.io/drat/', type='source')`"))
}
int <- seq(0.00001, .99999, length=npNumbers)
lookupArray <- dbinomCalc(Ns = c(n1, n2), int, delta)
if (alternative == "two.sided") {
if (n1 < n2) {
orderMat <- t(ExactData::orderCSMMatTwoSided[[paste0("(",n2,",",n1,")")]])
orderMat <- orderMat[(n1+1):1, (n2+1):1]
rownames(orderMat) <- 0:n1
colnames(orderMat) <- 0:n2
} else { orderMat <- ExactData::orderCSMMatTwoSided[[paste0("(",n1,",",n2,")")]] }
} else {
if (n1 < n2) {
orderMat <- t(ExactData::orderCSMMatOneSided[[paste0("(",n2,",",n1,")")]])
orderMat <- orderMat[(n1+1):1, (n2+1):1]
rownames(orderMat) <- 0:n1
colnames(orderMat) <- 0:n2
} else { orderMat <- ExactData::orderCSMMatOneSided[[paste0("(",n1,",",n2,")")]] }
}
TX <- matrix(cbind(as.matrix(expand.grid(0:n1, 0:n2)), as.vector(orderMat)), ncol=3, dimnames = NULL)
TX <- signif(TX[order(TX[,3]), ], 12)
TX <- cbind(TX, NA)
moreExtremeTbls <- searchExtreme(TX = TX, n1 = n1, n2 = n2, alternative = alternative, method = method, int = int, delta = delta,
alpha = alpha, lookupArray = lookupArray)
rejectRegion <- matrix(0, n1+1, n2+1)
if (nrow(moreExtremeTbls) > 0) {
for (i in 1:nrow(moreExtremeTbls)) {
rejectRegion[moreExtremeTbls[i, 1] + 1, moreExtremeTbls[i, 2] + 1] <- 1
}
}
rownames(rejectRegion) <- 0:n1
colnames(rejectRegion) <- 0:n2
} else {
if (delta == 0) { int <- seq(0.00001,.99999,length=npNumbers)
} else if (delta > 0) { int <- seq(0.00001, 1 - delta - 0.00001, length=npNumbers)
} else if (delta < 0) { int <- seq(abs(delta) + 0.00001, .99999, length=npNumbers)}
rejectRegion <- moreExtremeCSM(data = NULL, Ns = c(n1, n2), alternative = alternative,
int = int, doublePvalue = FALSE, delta = delta, reject.alpha = alpha)$moreExtremeMat
}
if (swapFlg) { rejectRegion <- t(rejectRegion) }
return(rejectRegion)
} else if (method == "fisher" || np.interval) {
rejectRegion <- matrix(NA, n1+1, n2+1)
rejectRegion[round((row(rejectRegion)-1)/(nrow(rejectRegion)-1), digits=10) >= round((col(rejectRegion)-1)/(ncol(rejectRegion)-1), digits=10)] <- 0
for (i in 0:n1) {
startJ <- which(is.na(rejectRegion[i+1, ]))[1] - 1
if (!is.na(startJ)) {
for (j in startJ:n2) {
tables <- matrix(c(i, n1-i, j, n2-j), ncol=2, nrow=2)
if (method=="fisher") {
rejectRegionTemp <- (fisher.2x2(tables, alternative=alternative)[3] <= alpha)
} else {
rejectRegionTemp <- (binomialCode(tables, alternative=alternative, npNumbers=npNumbers, np.interval=np.interval,
beta=beta, method=method, tsmethod=tsmethod, to.plot=FALSE,
ref.pvalue=FALSE, delta=delta, reject.alpha=alpha, useStoredCSM=useStoredCSM))
}
if (rejectRegionTemp) {
if (method=="fisher" || convexity) {
rejectRegion[i+1, (j+1):(n2+1)] <- 1
if (alternative=="two.sided") { rejectRegion[n1-i+1, 1:(n2-j+1)] <- 1 }
break
} else {
rejectRegion[i+1, j+1] <- 1
if (alternative=="two.sided") { rejectRegion[n1-i+1, n2-j+1] <- 1 }
}
} else {
if (method=="fisher" || convexity) {
rejectRegion[is.na(rejectRegion[ , j+1]), j+1] <- 0
} else { rejectRegion[i+1, j+1] <- 0 }
}
}
}
}
rownames(rejectRegion) <- 0:n1
colnames(rejectRegion) <- 0:n2
if (swapFlg){ rejectRegion <- t(rejectRegion) }
return(rejectRegion)
}
} |
boxplot <- function(x, ...) UseMethod("boxplot")
boxplot.default <-
function(x, ..., range = 1.5, width = NULL, varwidth = FALSE,
notch = FALSE, outline = TRUE, names, plot = TRUE,
border = par("fg"), col = "lightgray", log = "",
pars = list(boxwex = 0.8, staplewex = 0.5, outwex = 0.5),
ann = !add,
horizontal = FALSE, add = FALSE, at = NULL)
{
args <- list(x, ...)
namedargs <-
if(!is.null(attributes(args)$names)) attributes(args)$names != ""
else rep_len(FALSE, length(args))
groups <- if(is.list(x)) x else args[!namedargs]
if(0L == (n <- length(groups)))
stop("invalid first argument")
if(length(class(groups)))
groups <- unclass(groups)
if(!missing(names))
attr(groups, "names") <- names
else {
if(is.null(attr(groups, "names")))
attr(groups, "names") <- 1L:n
names <- attr(groups, "names")
}
cls <- lapply(groups, class)
cl <- NULL
if(all(vapply(groups,
function(e) {
is.numeric(unclass(e)) &&
identical(names(attributes(e)), "class")
},
NA)) &&
(length(unique(cls)) == 1L))
cl <- cls[[1L]]
for(i in 1L:n)
groups[i] <- list(boxplot.stats(unclass(groups[[i]]), range))
stats <- matrix(0, nrow = 5L, ncol = n)
conf <- matrix(0, nrow = 2L, ncol = n)
ng <- out <- group <- numeric(0L)
ct <- 1
for(i in groups) {
stats[,ct] <- i$stats
conf [,ct] <- i$conf
ng <- c(ng, i$n)
if((lo <- length(i$out))) {
out <- c(out,i$out)
group <- c(group, rep.int(ct, lo))
}
ct <- ct+1
}
if(length(cl) == 1L && cl != "numeric")
oldClass(stats) <- oldClass(conf) <- oldClass(out) <- cl
z <- list(stats = stats, n = ng, conf = conf, out = out, group = group,
names = names)
if(plot) {
if(is.null(pars$boxfill) && is.null(args$boxfill)) pars$boxfill <- col
do.call(bxp,
c(list(z, notch = notch, width = width, varwidth = varwidth,
log = log, border = border, pars = pars,
outline = outline, horizontal = horizontal, add = add,
ann = ann,
at = at), args[namedargs]),
quote = TRUE)
invisible(z)
}
else z
}
boxplot.matrix <- function(x, use.cols = TRUE, ...)
{
groups <- if(use.cols) {
split(c(x), rep.int(1L:ncol(x), rep.int(nrow(x), ncol(x))))
} else split(c(x), seq(nrow(x)))
if (length(nam <- dimnames(x)[[1+use.cols]])) names(groups) <- nam
invisible(boxplot(groups, ...))
}
boxplot.formula <-
function(formula, data = NULL, ..., subset, na.action = NULL,
xlab = mklab(y_var = horizontal),
ylab = mklab(y_var =!horizontal),
add = FALSE, ann = !add, horizontal = FALSE,
drop = FALSE, sep = ".", lex.order = FALSE)
{
if(missing(formula) || (length(formula) != 3L))
stop("'formula' missing or incorrect")
if(missing(xlab) || missing(ylab))
mklab <- function(y_var)
if(y_var) names(mf)[ response]
else paste(names(mf)[-response], collapse = " : ")
m <- match.call(expand.dots = FALSE)
if(is.matrix(eval(m$data, parent.frame())))
m$data <- as.data.frame(data)
m$... <- m$drop <- m$sep <- m$lex.order <- NULL
m$xlab <- m$ylab <- m$add <- m$ann <- m$horizontal <- NULL
m$na.action <- na.action
m[[1L]] <- quote(stats::model.frame.default)
mf <- eval(m, parent.frame())
response <- attr(attr(mf, "terms"), "response")
boxplot(split(mf[[response]], mf[-response],
drop = drop, sep = sep, lex.order = lex.order),
xlab = xlab, ylab = ylab, add = add, ann = ann, horizontal = horizontal,
...)
}
bxp <- function(z, notch = FALSE, width = NULL, varwidth = FALSE,
outline = TRUE, notch.frac = 0.5, log = "", border = par("fg"),
pars = NULL, frame.plot = axes, horizontal = FALSE,
ann = TRUE,
add = FALSE, at = NULL, show.names = NULL, ...)
{
pars <- as.list(pars)
if(...length()) {
nmsA <- names(args <- list(...))
if(anyDuplicated(nmsA)) {
iD <- duplicated(nmsA)
warning(sprintf(ngettext(sum(iD),
"Duplicated argument %s is disregarded",
"Duplicated arguments %s are disregarded"),
sub("^list\\((.*)\\)", "\\1", deparse(args[iD]))),
domain = NA)
nmsA <- names(args <- args[!iD])
}
pars[nmsA] <- args
}
bplt <- function(x, wid, stats, out, conf, notch, xlog, i)
{
ok <- TRUE
if(!anyNA(stats)) {
xP <-
if(xlog) function(x,w) x * exp(w)
else function(x,w) x + w
wid <- wid/2
if (notch) {
ok <- stats[2L] <= conf[1L] && conf[2L] <= stats[4L]
xx <- xP(x, wid * c(-1, 1, 1, notch.frac, 1,
1, -1,-1,-notch.frac,-1))
yy <- c(stats[c(2, 2)], conf[1L], stats[3L], conf[2L],
stats[c(4, 4)], conf[2L], stats[3L], conf[1L])
}
else {
xx <- xP(x, wid * c(-1, 1, 1, -1))
yy <- stats[c(2, 2, 4, 4)]
}
if(!notch) notch.frac <- 1
wntch <- notch.frac*wid
xypolygon(xx, yy, lty = "blank", col = boxfill[i])
xysegments(xP(x, -wntch), stats[3L],
xP(x, +wntch), stats[3L],
lty = medlty[i], lwd = medlwd[i], col = medcol[i],
lend = 1)
xypoints(x, stats[3L],
pch = medpch[i], cex = medcex[i], col = medcol[i], bg = medbg[i])
xysegments(rep.int(x, 2), stats[c(1,5)],
rep.int(x, 2), stats[c(2,4)],
lty = whisklty[i], lwd = whisklwd[i], col = whiskcol[i])
xysegments(rep.int(xP(x, -wid * staplewex[i]), 2), stats[c(1,5)],
rep.int(xP(x, +wid * staplewex[i]), 2), stats[c(1,5)],
lty = staplelty[i], lwd = staplelwd[i], col = staplecol[i])
xypolygon(xx, yy, lty = boxlty[i], lwd = boxlwd[i], border = boxcol[i])
if ((nout <- length(out))) {
xysegments(rep(x - wid * outwex, nout), out,
rep(x + wid * outwex, nout), out,
lty = outlty[i], lwd = outlwd[i], col = outcol[i])
xypoints(rep.int(x, nout), out, pch = outpch[i],
lwd = outlwd[i],
cex = outcex[i], col = outcol[i], bg = outbg[i])
}
if(any(inf <- !is.finite(out))) {
warning(sprintf(ngettext(length(unique(out[inf])),
"Outlier (%s) in boxplot %d is not drawn",
"Outliers (%s) in boxplot %d are not drawn"),
paste(unique(out[inf]), collapse=", "), i),
domain = NA)
}
}
return(ok)
}
if(!is.list(z) || 0L == (n <- length(z$n)))
stop("invalid first argument")
if(is.null(at))
at <- 1L:n
else if(length(at) != n)
stop(gettextf("'at' must have same length as 'z$n', i.e. %d", n),
domain = NA)
if(is.null(z$out))
z$out <- numeric()
if(is.null(z$group) || !outline)
z$group <- integer()
if(is.null(pars$ylim))
ylim <- range(z$stats[is.finite(z$stats)],
if(outline) z$out[is.finite(z$out)],
if(notch) z$conf[is.finite(z$conf)])
else {
ylim <- pars$ylim
pars$ylim <- NULL
}
if(length(border) == 0L) border <- par("fg")
dev.hold(); on.exit(dev.flush())
if (!add) {
if(is.null(pars$xlim))
xlim <- range(at, finite=TRUE) + c(-0.5, 0.5)
else {
xlim <- pars$xlim
pars$xlim <- NULL
}
plot.new()
if (horizontal)
plot.window(ylim = xlim, xlim = ylim, log = log, xaxs = pars$yaxs)
else
plot.window(xlim = xlim, ylim = ylim, log = log, yaxs = pars$yaxs)
}
xlog <- (par("ylog") && horizontal) || (par("xlog") && !horizontal)
pcycle <- function(p, def1, def2 = NULL)
rep(if(length(p)) p else if(length(def1)) def1 else def2,
length.out = n)
p <- function(sym) pars[[sym, exact = TRUE]]
boxlty <- pcycle(pars$boxlty, p("lty"), par("lty"))
boxlwd <- pcycle(pars$boxlwd, p("lwd"), par("lwd"))
boxcol <- pcycle(pars$boxcol, border)
boxfill <- pcycle(pars$boxfill, par("bg"))
boxwex <- pcycle(pars$boxwex, 0.8 * {
if(n <= 1) 1 else
stats::quantile(diff(sort(if(xlog) log(at) else at)), 0.10) })
medlty <- pcycle(pars$medlty, p("lty"), par("lty"))
medlwd <- pcycle(pars$medlwd, 3*p("lwd"), 3*par("lwd"))
medpch <- pcycle(pars$medpch, NA_integer_)
medcex <- pcycle(pars$medcex, p("cex"), par("cex"))
medcol <- pcycle(pars$medcol, border)
medbg <- pcycle(pars$medbg, p("bg"), par("bg"))
whisklty <- pcycle(pars$whisklty, p("lty"), "dashed")
whisklwd <- pcycle(pars$whisklwd, p("lwd"), par("lwd"))
whiskcol <- pcycle(pars$whiskcol, border)
staplelty <- pcycle(pars$staplelty, p("lty"), par("lty"))
staplelwd <- pcycle(pars$staplelwd, p("lwd"), par("lwd"))
staplecol <- pcycle(pars$staplecol, border)
staplewex <- pcycle(pars$staplewex, 0.5)
outlty <- pcycle(pars$outlty, "blank")
outlwd <- pcycle(pars$outlwd, p("lwd"), par("lwd"))
outpch <- pcycle(pars$outpch, p("pch"), par("pch"))
outcex <- pcycle(pars$outcex, p("cex"), par("cex"))
outcol <- pcycle(pars$outcol, border)
outbg <- pcycle(pars$outbg, p("bg"), par("bg"))
outwex <- pcycle(pars$outwex, 0.5)
width <-
if(!is.null(width)) {
if(length(width) != n || anyNA(width) || any(width <= 0))
stop("invalid boxplot widths")
boxwex * width/max(width)
}
else if(varwidth) boxwex * sqrt(z$n/max(z$n))
else if(n == 1) 0.5 * boxwex
else rep.int(boxwex, n)
if(horizontal) {
xypoints <- function(x, y, ...) points(y, x, ...)
xypolygon <- function(x, y, ...) polygon(y, x, ...)
xysegments <- function(x0, y0, x1, y1, ...) segments(y0, x0, y1, x1, ...)
}
else {
xypoints <- points
xypolygon <- polygon
xysegments <- segments
}
ok <- TRUE
for(i in 1L:n)
ok <- ok & bplt(at[i], wid = width[i], stats = z$stats[,i],
out = z$out[z$group == i], conf = z$conf[,i],
notch = notch, xlog = xlog, i = i)
if(!ok)
warning("some notches went outside hinges ('box'): maybe set notch=FALSE")
axes <- is.null(pars$axes)
if(!axes) { axes <- pars$axes; pars$axes <- NULL }
if(axes) {
ax.pars <- pars[names(pars) %in% c("xaxt", "yaxt", "xaxp", "yaxp",
"gap.axis",
"las",
"cex.axis", "col.axis", "format")]
if (is.null(show.names)) show.names <- n > 1
if (show.names)
do.call("axis", c(list(side = 1 + horizontal,
at = at, labels = z$names), ax.pars),
quote = TRUE)
do.call("Axis", c(list(x = z$stats, side = 2 - horizontal), ax.pars),
quote = TRUE)
}
if(ann) do.call(title,
pars[names(pars) %in% c("main", "cex.main", "col.main",
"sub", "cex.sub", "col.sub",
"xlab", "ylab", "cex.lab", "col.lab")],
quote = TRUE)
if(frame.plot)
box()
invisible(at)
} |
FitMCMC <- function(spec, data, ctr = list()) {
UseMethod(generic = "FitMCMC", spec)
}
FitMCMC.MSGARCH_SPEC <- function(spec, data, ctr = list()) {
time.start <- Sys.time()
spec <- f_check_spec(spec)
data_ <- f_check_y(data)
ctr <- f_process_ctr(ctr)
ctr$do.plm <- TRUE
if (isTRUE(spec$fixed.pars.bool)) {
f_check_fixedpars(spec$fixed.pars, spec)
}
if (is.null(ctr$par0)) {
par0 <- f_StargingValues(data_, spec, ctr)
} else {
par0 = ctr$par0
if (isTRUE(spec$regime.const.pars.bool)) {
par0 <- f_remove_regimeconstpar(par0, spec$regime.const.pars, spec$K)
}
if (isTRUE(spec$fixed.pars.bool)) {
par0 <- f_substitute_fixedpar(par0, spec$fixed.pars)
}
par0 <- f_unmapPar(par0, spec, do.plm = TRUE)
}
par <- ctr$SamplerFUN(f_posterior = f_posterior, data = data_, spec = spec, par0 = par0, ctr = ctr)
np <- length(par0)
accept <- 1 - mean(duplicated(par))
by <- seq(from = (ctr$nburn + 1L), to = (ctr$nburn + ctr$nmcmc), by = ctr$nthin)
par <- par[by, , drop = FALSE]
vLower <- spec$lower
vUpper <- spec$upper
names(vLower) <- spec$label
names(vUpper) <- spec$label
vLower <- vLower[names(par0)]
vUpper <- vUpper[names(par0)]
par <- f_map(par, vLower, vUpper)
par0 <- f_map(par0, vLower, vUpper)
vpar_full <- par[1L, ]
if (isTRUE(spec$fixed.pars.bool)) {
vpar_full <- f_add_fixedpar(vpar_full, spec$fixed.pars)
vpar_full <- vpar_full[spec$label]
names(vpar_full) <- spec$label
}
if (isTRUE(spec$regime.const.pars.bool)) {
vpar_full <- f_add_regimeconstpar(vpar_full, spec$K, spec$label)
}
if (length(vpar_full) != ncol(par)) {
vAddedPar <- vpar_full[!names(vpar_full) %in% colnames(par)]
if (isTRUE(spec$fixed.pars.bool)) {
par <- cbind(par, matrix(rep(vAddedPar, nrow(par)), nrow = nrow(par),
byrow = TRUE, dimnames = list(NULL, names(vAddedPar))))
par <- par[, spec$label]
}
if (isTRUE(spec$regime.const.pars.bool)) {
par <- f_add_regimeconstpar_matrix(par, spec$K, spec$label)
}
}
if(isTRUE(ctr$do.sort)){
par <- f_sort_par(spec, par)
}
par <- coda::mcmc(par)
ctr$par0 <- par0
elapsed.time <- Sys.time() - time.start
out <- list(par = par, accept = accept, data = data, spec = spec, ctr = ctr)
class(out) <- "MSGARCH_MCMC_FIT"
return(out)
} |
setGeneric("format")
.list2S4 <- function(from, to) {
if (!length(from))
return (new(to))
p <- pmatch(names(from), slotNames(to))
if (any(is.na(p)))
stop(paste("invalid slot name(s) for class", to, ":",
paste(names(from)[is.na(p)], collapse = "")))
names(from) <- slotNames(to)[p]
do.call("new", c(from, Class = to))
}
.S42list <- function(object) {
object <- attributes(object)
object$class <- NULL
object
}
setClass("SPparameter",
representation(
support = "numeric",
maxsize = "integer",
maxlen = "integer",
mingap = "integer",
maxgap = "integer",
maxwin = "integer"
),
prototype(support = 0.1,
maxsize = 10L,
maxlen = 10L),
validity = function(object) {
if (object@support < 0 || object@support > 1)
return("slot support : invalid range")
if (length(object@maxsize) && object@maxsize < 1)
return("slot maxsize : invalid range")
if (length(object@maxlen) && object@maxlen < 1)
return("slot maxlen : invalid range")
if (length(object@mingap) && object@mingap < 1)
return("slot mingap : invalid range")
if (length(object@maxgap) && object@maxgap < 0)
return("slot maxgap : invalid range")
if (length(object@maxwin) && object@maxwin < 0)
return("slot maxwin : invalid range")
TRUE
}
)
setMethod("initialize", "SPparameter",
function(.Object, support, ...) {
if (!missing(support))
.Object@support <- support
args <- list(...)
for (name in names(args))
slot(.Object, name) <-
as(args[[name]], Class = class(slot(.Object, name)))
validObject(.Object)
.Object
}
)
setAs("NULL", "SPparameter",
function(from, to) new(to))
setAs("list", "SPparameter",
function(from, to) .list2S4(from , to))
setAs("SPparameter", "list",
function(from) .S42list(from))
setAs("SPparameter", "vector",
function(from) unlist(as(from, "list")))
setAs("SPparameter", "character",
function(from, to) unlist(lapply(as(from, "list"), as, class(to))))
setAs("SPparameter", "data.frame",
function(from) {
from <- as(from, "character")
data.frame(name = names(from),
value = from, row.names = seq(from))
}
)
.formatSP <-
function(x, ...) {
x <- as(x, "character")
paste(format(names(x)), format(x, justify = "right"), sep = " : ")
}
setMethod("format", "SPparameter",
.formatSP
)
setMethod("show", signature(object = "SPparameter"),
function(object) {
out <- .formatSP(object)
cat("set of", length(out), "spade parameters\n\n")
if (length(out))
cat(out, sep = "\n")
invisible(NULL)
}
)
setClass("SPcontrol",
representation(
memsize = "integer",
numpart = "integer",
bfstype = "logical",
verbose = "logical",
summary = "logical",
tidLists = "logical"
),
prototype(bfstype = FALSE, verbose = FALSE, summary = FALSE,
tidLists = FALSE),
validity = function(object) {
if (length(object@memsize) && object@memsize < 16)
return("slot memsize : invalid range")
if (length(object@numpart) && object@numpart < 1)
return("slot numpart : invalid range")
TRUE
}
)
setMethod("initialize", "SPcontrol",
function(.Object, ...) {
args <- list(...)
for (name in names(args))
slot(.Object, name) <-
as(args[[name]], Class = class(slot(.Object, name)))
validObject(.Object)
.Object
}
)
setAs("NULL", "SPcontrol",
function(from, to) new(to))
setAs("list", "SPcontrol",
function(from, to) .list2S4(from , to))
setAs("SPcontrol", "list",
function(from) .S42list(from))
setAs("SPcontrol", "vector",
function(from) unlist(as(from, "list")))
setAs("SPcontrol", "character",
function(from, to) unlist(lapply(as(from, "list"), as, class(to))))
setAs("SPcontrol", "data.frame",
function(from) {
from <- as(from, "character")
data.frame(name = names(from),
value = from, row.names = seq(from))
}
)
setMethod("format", "SPcontrol",
.formatSP
)
setMethod("show", signature(object = "SPcontrol"),
function(object) {
out <- .formatSP(object)
cat("set of", length(out), "spade control parameters\n\n")
if (length(out))
cat(out, sep = "\n")
invisible(NULL)
}
) |
NOT_CRAN <- identical(tolower(Sys.getenv("NOT_CRAN")),"true")
knitr::opts_chunk$set(purl = NOT_CRAN)
library(insee)
library(tidyverse)
embed_png <- function(path, dpi = NULL) {
meta <- attr(png::readPNG(path, native = TRUE, info = TRUE), "info")
if (!is.null(dpi)) meta$dpi <- rep(dpi, 2)
knitr::asis_output(paste0(
"<img src='", path, "'",
" width=", round(meta$dim[1] / (meta$dpi[1] / 96)),
" height=", round(meta$dim[2] / (meta$dpi[2] / 96)),
" />"
))}
library(kableExtra)
library(magrittr)
library(htmltools)
library(prettydoc)
embed_png("pop_map.png") |
"turbineSpatial" |
pentaSolve <- function(a1,a2,a3,a4,a5,b)
{
u <- b
N <- length(b)
i <- 1
while(i<=N-2)
{
auxi <- a2[i]/a3[i]
a3[i+1] <- a3[i+1]-a4[i]*auxi
a4[i+1] <- a4[i+1]-a5[i]*auxi
b[i+1] <- b[i+1]-b[i]*auxi
auxi <- a1[i]/a3[i]
a2[i+1] <- a2[i+1]-a4[i]*auxi
a3[i+2] <- a3[i+2]-a5[i]*auxi
b[i+2] <- b[i+2]-b[i]*auxi
i <- i+1
}
auxi <- a2[N-1]/a3[N-1]
a3[N] <- a3[N]-a4[N-1]*auxi
b[N] <- b[N]-b[N-1]*auxi
u[N] <- b[N]/a3[N]
u[N-1] <- (b[N-1]-a4[N-1]*u[N])/a3[N-1]
i <- N-2
while(i>=1)
{
u[i] <- (b[i]-a4[i]*u[i+1]-a5[i]*u[i+2])/a3[i]
i <- i-1
}
return(u)
} |
summary.mfp <- function(object, ...)
{
summary(object$fit, ...)
} |
slopeOP <- function(data, states, penalty = 0, constraint = "null", minAngle = 0, type = "channel", testMode = FALSE)
{
if(!is.numeric(data)){stop('data values are not all numeric')}
if(!is.numeric(states)){stop('states are not all numeric')}
if(is.unsorted(states)){stop('states must be in increasing order')}
if(length(unique(states)) < length(states)){stop('states is not a strictly increasing sequence')}
if(!is.double(penalty)){stop('penalty is not a double.')}
if(penalty < 0){stop('penalty must be non-negative')}
if(!is.double(minAngle)){stop('minAngle is not a double.')}
if(minAngle < 0 || minAngle > 180){stop('minAngle must lie between 0 and 180')}
allowed.constraints <- c("null", "isotonic", "unimodal", "smoothing")
if(!constraint %in% allowed.constraints){stop('constraint must be one of: ', paste(allowed.constraints, collapse=", "))}
allowed.types <- c("null", "channel", "pruning")
if(!type %in% allowed.types){stop('type must be one of: ', paste(allowed.types, collapse=", "))}
if(!is.logical(testMode)){stop('testMode must be a boolean')}
res <- slopeOPtransfer(data, states, penalty, constraint, minAngle, type)
if(testMode == FALSE){response <- list(changepoints = res$changepoints, parameters = res$parameters, globalCost = res$globalCost - (length(res$changepoints) - 1) * penalty)}
if(testMode == TRUE){response <- list(changepoints = res$changepoints, parameters = res$parameters, globalCost = res$globalCost - (length(res$changepoints) - 1) * penalty, pruning = res$pruningPower)}
attr(response, "class") <- "slopeOP"
return(response)
}
slopeSN <- function(data, states, nbSegments = 1, constraint = "null", testMode = FALSE)
{
if(!is.numeric(data)){stop('data values are not all numeric')}
if(!is.numeric(states)){stop('states are not all numeric')}
if(is.unsorted(states)){stop('states must be in increasing order')}
if(length(unique(states)) < length(states)){stop('states is not a strictly increasing sequence')}
if(nbSegments < 1){stop('nbSegments < 1')}
if(nbSegments%%1 > 0){stop('nbSegments is not an integer')}
allowed.constraints <- c("null", "isotonic")
if(!constraint %in% allowed.constraints){stop('constraint must be one of: ', paste(allowed.constraints, collapse=", "))}
if(!is.logical(testMode)){stop('testMode must be a boolean')}
if(nbSegments + 1 > length(data)){stop('you can not have more segments that data points')}
res <- slopeSNtransfer(data, states, nbSegments, constraint)
if(testMode == FALSE){response <- list(changepoints = res$changepoints, parameters = res$parameters, globalCost = res$globalCost )}
if(testMode == TRUE){response <- list(changepoints = res$changepoints, parameters = res$parameters, globalCost = res$globalCost, pruning = res$pruningPower)}
attr(response, "class") <- "slopeOP"
return(response)
}
slopeData <- function(index, states, noise = 0, outlierDensity = 0, outlierNoise = 50)
{
if(!is.numeric(index)){stop('data values are not all numeric')}
if(is.unsorted(index)){stop('index should be an increasing vector')}
if(length(unique(index)) < length(index)){stop('index is not a strictly increasing sequence')}
if(!is.numeric(states)){stop('states are not all numeric')}
if(length(index) != length(states)){stop('index and states vectors are of different size')}
if(!is.double(noise)){stop('noise is not a double.')}
if(noise < 0){stop('noise must be nonnegative')}
steps <- diff(states)/diff(index)
response <- rep(steps, diff(index))
response <- c(states[1], cumsum(response) + states[1])
if(outlierDensity == 0)
{
response <- response + rnorm(length(response), 0, noise)
}
else
{
S <- sample(c(0,1), size = length(response), replace = TRUE, prob = c(1 - outlierDensity, outlierDensity))
response <- response + (1-S)*rnorm(length(response), 0, noise)
response <- response + S*rnorm(length(response), 0, outlierNoise)
}
return(response)
}
plot.slopeOP <- function(x, ..., data, chpt = NULL, states = NULL)
{
n <- 1:length(data)
p <- length(x$changepoints)
xbis <- x$changepoints
y <- x$parameters
plot(1:length(data), data, pch = '+')
for(i in 1:(p-1))
{
segments(xbis[i], y[i], xbis[i+1], y[i+1], col= 2, lty = 1, lwd = 3)
}
if(length(chpt) > 0 && length(chpt) == length(states))
{
q <- length(chpt)
for(i in 1:(q-1))
{
segments(chpt[i], states[i], chpt[i+1], states[i+1], col= 4, lty = 1, lwd = 3)
}
}
} |
'mixedAn<-' <- function(he, value)
UseMethod('mixedAn<-', he) |
Fx_simplex <- function(formula, n.levels.mix=NULL, echo=TRUE) {
cl <- match.call()
verify(cl, formula = formula, n.levels.mix = n.levels.mix, echo = echo)
av <- all.vars(formula); d <- length(av)
if (is.null(n.levels.mix)) {
message("n.levels.mix is NULL; setting n.levels.mix to 2*d+1.")
n.levels.mix <- 2*d + 1
}
cmb <- t(combn(n.levels.mix + d - 2, d - 1))
data <- as.data.frame((cbind(cmb, n.levels.mix + d - 1) -
cbind(0, cmb) - 1)/(n.levels.mix - 1))
labs <- c()
for (i in 1:d)
labs <- c(labs, paste("x", as.character(i), sep = ""))
names(data) <- labs[1:d]
mf <- model.frame(formula, data)
Fx <- as.data.frame(model.matrix(attr(mf, "terms"), mf))
return(as.matrix(Fx))
} |
textInputWithValidation <- function(inputId, label, container_id = NULL, help_id = NULL) {
markup <- div(class = 'form-group selectize-fh validate-wrapper', id = container_id,
tags$label(class = 'control-label', `for` = inputId, label),
tags$input(id = inputId, type = 'text', class = 'form-control', value = '', placeholder = ''),
tags$span(class='help-block', id = help_id)
)
with_deps(markup)
}
textInputWithButtons <- function(inputId, label, ..., container_id = NULL, help_id = NULL, label_title = NULL, btn_titletips = TRUE, placeholder = '', width = NULL) {
buttons <- list(...)
buttons <- buttons[!sapply(buttons, is.null)]
button_tooltips <- NULL
if (btn_titletips) {
button_tooltips <- tags$div(
lapply(buttons, function(btn)
shinyBS::bsTooltip(id = btn$attribs$id, title = btn$attribs$title, options = list(container = 'body')))
)
}
label_tooltip <- NULL
if (!is.null(label_title)) {
label_id <- paste0(inputId, '-label-info')
label_tooltip <- shinyBS::bsTooltip(label_id, title = label_title, placement = 'top', options = list(container = 'body'))
label <- tags$span(label, span(class='hover-info', span(id = label_id, icon('info', 'fa-fw'))))
}
if (!is.null(width)) width <- paste0('width: ', width, ';')
markup <- div(class = 'form-group selectize-fh validate-wrapper', id = container_id, style = width,
tags$label(class = 'control-label', `for` = inputId, label),
div(class = 'input-group',
tags$input(id = inputId, type = 'text', class = 'form-control', value = '', placeholder = placeholder),
tags$span(class = 'input-group-btn',
lapply(buttons, function(btn) {
if (btn_titletips) btn$attribs$title <- NULL
return(btn)
}))
),
tags$span(class = 'help-block', id = help_id),
button_tooltips,
label_tooltip
)
with_deps(markup)
}
textAreaInputWithButtons <- function(inputId, label, ..., container_id = NULL, help_id = NULL, label_title = NULL, btn_titletips = TRUE, placeholder = '') {
buttons <- list(...)
buttons <- buttons[!sapply(buttons, is.null)]
button_tooltips <- NULL
if (btn_titletips) {
button_tooltips <- tags$div(
lapply(buttons, function(btn)
shinyBS::bsTooltip(id = btn$attribs$id, title = btn$attribs$title, options = list(container = 'body')))
)
}
label_tooltip <- NULL
if (!is.null(label_title)) {
label_id <- paste0(inputId, '-label-info')
label_tooltip <- shinyBS::bsTooltip(label_id, title = label_title, placement = 'top', options = list(container = 'body'))
label <- tags$span(label, span(class='hover-info', span(id = label_id, icon('info', 'fa-fw'))))
}
markup <- div(class = 'form-group selectize-fh validate-wrapper', id = container_id,
tags$label(class = 'control-label', `for` = inputId, label),
div(class = 'input-group full-height-btn',
tags$textarea(id = inputId,
class = 'form-control',
value = '',
style = 'resize: vertical; min-height: 34px;',
placeholder = placeholder),
tags$span(class = 'input-group-btn',
lapply(buttons, function(btn) {
if (btn_titletips) btn$attribs$title <- NULL
return(btn)
}))
),
tags$span(class = 'help-block', id = help_id),
button_tooltips,
label_tooltip
)
with_deps(markup)
} |
rm(list=ls())
compare <- function(a,b, xs) {
plot(xs, a(xs), type='l')
lines(xs, b(xs), type='l', col='blue')
invisible()
}
assert('taylor_series_1', {
fac(1) %as% 1
fac(n) %when% { n > 0 } %as% { n * fac(n - 1) }
seal(fac)
d(f, 1, h=10^-9) %as% function(x) { (f(x + h) - f(x - h)) / (2*h) }
d(f, 2, h=10^-9) %as% function(x) { (f(x + h) - 2*f(x) + f(x - h)) / h^2 }
taylor(f, a, step=2) %as% taylor(f, a, step, 1, function(x) f(a))
taylor(f, a, 0, k, g) %as% g
taylor(f, a, step, k, g) %as% {
df <- d(f,k)
g1 <- function(x) { g(x) + df(a) * (x - a)^k / fac(k) }
taylor(f, a, step-1, k+1, g1)
}
f <- taylor(sin, pi)
v <- f(3.1)
all.equal(v, sin(3.1), tolerance=0.01)
}) |
rowMedians <-
function (mat) {
apply(mat, 1, median, na.rm = TRUE)
} |
library("testthat")
library("recommenderlab")
data("MovieLense")
methods <- unique(sapply(recommenderRegistry$get_entries(
dataType="realRatingMatrix"), "[[", "method"))
cat("Available methods for realRatingMatrix:", paste(methods, collapse = ", "))
MovieLense100 <- MovieLense[rowCounts(MovieLense) > 100,]
MovieLense100 <- MovieLense[, colCounts(MovieLense100) > 100,]
train <- MovieLense100[1:20]
test1 <- MovieLense100[101]
test3 <- MovieLense100[101:103]
for(m in methods) {
if(m == "HYBRID") next
context(paste("Algorithm:", m))
cat("Algorithm:", m, "\n")
rec <- Recommender(train, method = m)
rec
pre <- predict(rec, test1, n = 10)
pre
l <- as(pre, "list")
expect_identical(length(l), 1L)
expect_identical(length(l[[1]]), 10L)
pre <- predict(rec, test3, n = 10)
pre
l <- as(pre, "list")
expect_identical(length(l), 3L)
expect_equal(as.integer(sapply(l, length)), c(10L, 10L, 10L))
pre <- predict(rec, test1, n = 10, type = "ratings")
pre
expect_gt(sum(is.na(as(pre, "matrix"))), 0L)
if(m != "RERECOMMEND") {
pre <- predict(rec, test1, n = 10, type = "ratingMatrix")
pre
}
pre <- predict(rec, test3, n = 10, type = "ratings")
pre
expect_gt(sum(is.na(as(pre, "matrix"))), 0L)
if(m != "RERECOMMEND") {
pre <- predict(rec, test3, n = 10, type = "ratingMatrix")
pre
}
}
recom <- HybridRecommender(
Recommender(train, method = "POPULAR"),
Recommender(train, method = "RANDOM"),
Recommender(train, method = "RERECOMMEND"),
weights = c(.6, .1, .3)
)
predict(recom, test1)
predict(recom, test3)
predict(recom, test1, type = "ratings")
predict(recom, test3, type = "ratings")
methods <- unique(sapply(recommenderRegistry$get_entries(
dataType="binaryRatingMatrix"), "[[", "method"))
cat("Available methods for binaryRatingMatrix:", paste(methods, collapse = ", "))
MovieLense100_bin <- binarize(MovieLense100, minRating = 3)
train <- MovieLense100_bin[1:50]
test1 <- MovieLense100_bin[101]
test3 <- MovieLense100_bin[101:103]
for(m in methods) {
if(m == "HYBRID") next
context(paste("Algorithm:", m))
cat("Algorithm:", m, "\n")
rec <- Recommender(train, method = m)
rec
pre <- predict(rec, test1, n = 10)
pre
l <- as(pre, "list")
expect_identical(length(l), 1L)
expect_identical(length(l[[1]]), 10L)
pre <- predict(rec, test3, n = 10)
pre
l <- as(pre, "list")
expect_identical(length(l), 3L)
expect_equal(as.integer(sapply(l, length)), c(10L, 10L, 10L))
pre <- predict(rec, test1, n = 10, type = "ratings")
cat("Prediction range (should be [0,1]):\n")
print(summary(as.vector(as(pre, "matrix"))))
if(m != "RERECOMMEND") {
pre <- predict(rec, test1, n = 10, type = "ratingMatrix")
}
}
recom <- HybridRecommender(
Recommender(train, method = "POPULAR"),
Recommender(train, method = "RANDOM"),
Recommender(train, method = "AR"),
Recommender(train, method = "RERECOMMEND"),
weights = c(.25, .25, .25, .25)
)
predict(recom, test1)
predict(recom, test3)
predict(recom, test1, type = "ratings")
predict(recom, test3, type = "ratings") |
NULL
dlfInit <- function(mCall, LHS, data, ...){
xy <- sortedXyData(mCall[["time"]], LHS, data)
if(nrow(xy) < 4){
stop("Too few distinct input values to fit a dlf.")
}
z <- xy[["y"]]
x1 <- xy[["x"]]
asym <- max(xy[,"y"])
a2 <- min(xy[,"y"])
xmid <- NLSstClosestX(xy, (asym + a2)/2)
scal <- -xmid/2
zz <- z - a2
scal2 <- try(coef(nls(zz ~ SSlogis(-x1, asym, xmid, scal)))[3], silent = TRUE)
if(class(scal2) != "try-error") scal <- -scal2
value <- c(asym, a2, xmid, scal)
names(value) <- mCall[c("asym","a2","xmid","scal")]
value
}
dlf <- function(time, asym, a2, xmid, scal){
.expr1 <- (xmid - time)/scal
.expr2 <- 1 + exp(.expr1)
.value <- (asym - a2) / .expr2 + a2
.expi1 <- 1/.expr2
.expi2 <- 1 - 1/.expr2
.expr3 <- asym - a2
.expr4 <- exp((xmid - time)/scal)
.expr5 <- 1 + .expr4
.expi3 <- -(.expr3 * (.expr4 * (1/scal))/.expr5^2)
.eexpr1 <- asym - a2
.eexpr2 <- xmid - time
.eexpr4 <- exp(.eexpr2/scal)
.eexpr5 <- 1 + .eexpr4
.expi4 <- .eexpr1 * (.eexpr4 * (.eexpr2/scal^2))/.eexpr5^2
.actualArgs <- as.list(match.call()[c("asym", "a2", "xmid", "scal")])
if (all(unlist(lapply(.actualArgs, is.name)))) {
.grad <- array(0, c(length(.value), 4L), list(NULL, c("asym", "a2", "xmid","scal")))
.grad[, "asym"] <- .expi1
.grad[, "a2"] <- .expi2
.grad[, "xmid"] <- .expi3
.grad[, "scal"] <- .expi4
dimnames(.grad) <- list(NULL, .actualArgs)
attr(.value, "gradient") <- .grad
}
.value
}
SSdlf <- selfStart(dlf, initial = dlfInit, c("asym","a2","xmid","scal")) |
setGeneric("sensor", function(this,...) standardGeneric("sensor"))
setMethod("sensor", ".MoveTrack",
function(this,...) {
this@sensor
})
setMethod("sensor", ".unUsedRecords",
function(this,...) {
this@sensorUnUsedRecords
}) |
`draw.evaluated_1d_smooth` <- function(object,
rug = NULL,
ci_level = 0.95,
constant = NULL,
fun = NULL,
xlab, ylab,
title = NULL, subtitle = NULL,
caption = NULL,
partial_residuals = NULL,
response_range = NULL,
...) {
smooth_var <- names(object)[3L]
object <- add_constant(object, constant = constant)
crit <- qnorm((1 - ci_level) / 2, lower.tail = FALSE)
object[["upper"]] <- object[["est"]] + (crit * object[["se"]])
object[["lower"]] <- object[["est"]] - (crit * object[["se"]])
object <- transform_fun(object, fun = fun)
plt <- ggplot(object, aes_(x = as.name(smooth_var), y = ~ est,
group = ~ smooth))
if (!is.null(partial_residuals)) {
plt <- plt + geom_point(data = partial_residuals,
aes_string(x = "..orig_x", y = "..p_resid"),
inherit.aes = FALSE,
colour = "steelblue3", alpha = 0.5)
}
plt <- plt + geom_ribbon(mapping = aes_string(ymin = "lower",
ymax = "upper"),
alpha = 0.3) +
geom_line()
if (missing(xlab)) {
xlab <- smooth_var
}
if (missing(ylab)) {
ylab <- "Effect"
}
if (is.null(title)) {
title <- unique(object[["smooth"]])
}
if (all(!is.na(object[["by_variable"]]))) {
spl <- strsplit(title, split = ":")
title <- spl[[1L]][[1L]]
if (is.null(subtitle)) {
by_var <- as.character(unique(object[["by_variable"]]))
subtitle <- paste0("By: ", by_var, "; ", unique(object[[by_var]]))
}
}
plt <- plt + labs(x = xlab, y = ylab, title = title, subtitle = subtitle,
caption = caption)
if (!is.null(rug)) {
plt <- plt +
geom_rug(data = data.frame(x = rug), mapping = aes_string(x = 'x'),
inherit.aes = FALSE, sides = 'b', alpha = 0.5)
}
if (!is.null(response_range)) {
plt <- plt + expand_limits(y = response_range)
}
plt
}
`draw.evaluated_2d_smooth` <- function(object, show = c("estimate","se"),
contour = TRUE,
contour_col = "black",
n_contour = NULL,
constant = NULL,
fun = NULL,
xlab, ylab,
title = NULL, subtitle = NULL,
caption = NULL,
response_range = NULL,
continuous_fill = NULL,
...) {
if (is.null(continuous_fill)) {
continuous_fill <- scale_fill_distiller(palette = "RdBu", type = "div")
}
object <- add_constant(object, constant = constant)
object <- transform_fun(object, fun = fun)
smooth_vars <- names(object)[3:4]
show <- match.arg(show)
if (isTRUE(identical(show, "estimate"))) {
guide_title <- "Effect"
plot_var <- "est"
guide_limits <- if (is.null(response_range)) {
c(-1, 1) * max(abs(object[[plot_var]]))
} else {
response_range
}
} else {
guide_title <- "Std. err."
plot_var <- "se"
guide_limits <- range(object[["se"]])
}
plt <- ggplot(object, aes_string(x = smooth_vars[1], y = smooth_vars[2])) +
geom_raster(mapping = aes_string(fill = plot_var))
if (isTRUE(contour)) {
plt <- plt + geom_contour(mapping = aes_string(z = plot_var),
colour = contour_col,
bins = n_contour)
}
if (missing(xlab)) {
xlab <- smooth_vars[1L]
}
if (missing(ylab)) {
ylab <- smooth_vars[2L]
}
if (is.null(title)) {
title <- unique(object[["smooth"]])
}
if (all(!is.na(object[["by_variable"]]))) {
spl <- strsplit(title, split = ":")
title <- spl[[1L]][[1L]]
if (is.null(subtitle)) {
by_var <- as.character(unique(object[["by_variable"]]))
subtitle <- paste0("By: ", by_var, "; ", unique(object[[by_var]]))
}
}
plt <- plt + labs(x = xlab, y = ylab, title = title, subtitle = subtitle,
caption = caption)
plt <- plt + continuous_fill
plt <- plt + expand_limits(fill = guide_limits)
plt <- plt + guides(fill = guide_colourbar(title = guide_title,
direction = "vertical",
barheight = grid::unit(0.25,
"npc")))
plt <- plt + theme(legend.position = "right")
plt
}
`draw.evaluated_re_smooth` <- function(object, qq_line = TRUE,
constant = NULL, fun = NULL,
xlab, ylab,
title = NULL, subtitle = NULL,
caption = NULL,
response_range = NULL, ...) {
smooth_var <- unique(object[["smooth"]])
object <- add_constant(object, constant = constant)
object <- transform_fun(object, fun = fun)
plt <- ggplot(object, aes_string(sample = "est")) +
geom_point(stat = "qq")
if (isTRUE(qq_line)) {
sampq <- quantile(object[["est"]], c(0.25, 0.75))
gaussq <- qnorm(c(0.25, 0.75))
slope <- diff(sampq) / diff(gaussq)
intercept <- sampq[1L] - slope * gaussq[1L]
plt <- plt + geom_abline(slope = slope, intercept = intercept)
}
if (missing(xlab)) {
xlab <- "Gaussian quantiles"
}
if (missing(ylab)) {
ylab <- "Effects"
}
if(is.null(title)) {
title <- smooth_var
}
if (all(!is.na(object[["by_variable"]]))) {
spl <- strsplit(title, split = ":")
title <- spl[[1L]][[1L]]
if (is.null(subtitle)) {
by_var <- as.character(unique(object[["by_variable"]]))
subtitle <- paste0("By: ", by_var, "; ", unique(object[[by_var]]))
}
}
plt <- plt + labs(x = xlab, y = ylab, title = title, subtitle = subtitle,
caption = caption)
if (!is.null(response_range)) {
plt <- plt + expand_limits(y = response_range)
}
plt
}
`draw.evaluated_fs_smooth` <- function(object,
rug = NULL,
constant = NULL,
fun = NULL,
xlab, ylab,
title = NULL, subtitle = NULL,
caption = NULL,
response_range = NULL,
discrete_colour = NULL,
...) {
if (is.null(discrete_colour)) {
discrete_colour <- scale_colour_discrete()
}
smooth_var <- names(object)[3L]
smooth_fac <- names(object)[4L]
object <- add_constant(object, constant = constant)
object <- transform_fun(object, fun = fun)
plt <- ggplot(object, aes_(x = as.name(smooth_var), y = ~ est,
colour = as.name(smooth_fac))) +
geom_line() +
discrete_colour +
theme(legend.position = "none")
if (missing(xlab)) {
xlab <- smooth_var
}
if (missing(ylab)) {
ylab <- "Effect"
}
if (is.null(title)) {
title <- unique(object[["smooth"]])
}
if (all(!is.na(object[["by_variable"]]))) {
spl <- strsplit(title, split = ":")
title <- spl[[1L]][[1L]]
if (is.null(subtitle)) {
by_var <- as.character(unique(object[["by_variable"]]))
subtitle <- paste0("By: ", by_var, "; ", unique(object[[by_var]]))
}
}
plt <- plt + labs(x = xlab, y = ylab, title = title, subtitle = subtitle,
caption = caption)
if (!is.null(rug)) {
plt <- plt + geom_rug(data = data.frame(x = rug),
mapping = aes_string(x = 'x'),
inherit.aes = FALSE,
sides = 'b', alpha = 0.5)
}
if (!is.null(response_range)) {
plt <- plt + expand_limits(y = response_range)
}
plt
}
`draw.evaluated_parametric_term` <- function(object,
ci_level = 0.95,
constant = NULL,
fun = NULL,
xlab, ylab,
title = NULL, subtitle = NULL,
caption = NULL,
rug = TRUE,
position = "identity",
response_range = NULL,
...) {
is_fac <- object[["type"]][1L] == "factor"
term_label <- object[["term"]][1L]
object <- add_constant(object, constant = constant)
crit <- qnorm((1 - ci_level) / 2, lower.tail = FALSE)
object <- mutate(object,
lower = .data$partial - (crit * .data$se),
upper = .data$partial + (crit * .data$se))
object <- transform_fun(object, fun = fun)
plt <- ggplot(object, aes_string(x = "value", y = "partial"))
if (is_fac) {
plt <- plt + geom_pointrange(aes_string(ymin = "lower", ymax = "upper"))
} else {
if (isTRUE(rug)) {
plt <- plt + geom_rug(sides = "b", position = position, alpha = 0.5)
}
plt <- plt + geom_ribbon(aes_string(ymin = "lower", ymax = "upper"),
alpha = 0.3) +
geom_line()
}
if (missing(xlab)) {
xlab <- term_label
}
if (missing(ylab)) {
ylab <- sprintf("Partial effect of %s", term_label)
}
plt <- plt + labs(x = xlab, y = ylab, title = title, subtitle = subtitle,
caption = caption)
if (!is.null(response_range)) {
plt <- plt + expand_limits(y = response_range)
}
plt
} |
"EMPIRsimv" <-
function(u, n=1, empgrid=NULL, kumaraswamy=FALSE, ...) {
empinv <- EMPIRgridderinv(empgrid=empgrid, kumaraswamy=kumaraswamy)
rows <- as.numeric(attributes(empinv)$rownames)
ix <- 1:length(rows)
cols <- attributes(empinv)$colnames
V <- vector(mode="numeric", length=n)
for(i in 1:n) {
t <- runif(1)
ix.needed1 <- max(ix[rows <= u])
ix.needed2 <- min(ix[rows >= u])
if(ix.needed1 == 1) ix.needed1 <- 2
if(ix.needed1 == ix.needed2) {
v.available <- empinv[ix.needed1,]
v <- approx(cols, y=v.available, xout=t, rule=2)$y
} else {
v.available1 <- empinv[ix.needed1,]
v1 <- approx(cols, y=v.available1, xout=t, rule=2)$y
v.available2 <- empinv[ix.needed2,]
v2 <- approx(cols, y=v.available2, xout=t, rule=2)$y
w1 <- u - rows[ix.needed1]
w2 <- rows[ix.needed2] - u
tw <- 1/w1 + 1/w2
v <- (v1/w1 + v2/w2)/tw
}
V[i] <- v
}
return(V)
} |
make.db.names_DBIObject_character <- function(dbObj, snames, keywords, unique, allow.keywords, ...) {
make.db.names.default(snames, keywords, unique, allow.keywords)
}
setMethod("make.db.names", signature(dbObj = "DBIObject", snames = "character"), make.db.names_DBIObject_character, valueClass = "character") |
compare.2.vectors <- function(x, y, paired = FALSE, na.rm = FALSE,
tests = c("parametric", "nonparametric"),
coin = TRUE, alternative = "two.sided",
perm.distribution,
wilcox.exact = NULL, wilcox.correct = TRUE) {
tests <- match.arg(tests, c("parametric", "nonparametric"), several.ok = TRUE)
if (na.rm) {
x <- x[!is.na(x)]
y <- y[!is.na(y)]
} else if (any(is.na(x), is.na(y)))
stop("NAs in data, use na.rm = TRUE.", call. = FALSE)
out <- list()
if (paired) if (!length(x) == length(y))
stop("length(x) needs to be equal to length(y) when paired is TRUE!",
call. = FALSE)
if ("parametric" %in% tests) {
res.t <- t.test(x, y, paired = paired, var.equal = TRUE,
alternative = alternative)
parametric <- data.frame(test = "t", test.statistic = "t",
test.value = res.t[["statistic"]],
test.df = res.t[["parameter"]],
p = res.t[["p.value"]], stringsAsFactors = FALSE)
if (!paired) {
res.welch <- t.test(x, y, paired = paired, var.equal = FALSE,
alternative = alternative)
parametric <- rbind(parametric,
data.frame(test = "Welch", test.statistic = "t",
test.value = res.welch[["statistic"]],
test.df = res.welch[["parameter"]],
p = res.welch[["p.value"]],
stringsAsFactors = FALSE))
}
rownames(parametric) <- NULL
out <- c(out, list(parametric = parametric))
}
if ("nonparametric" %in% tests) {
implemented.tests <- c("permutation", "Wilcoxon", "median")
res.wilcox <- wilcox.test(x, y, paired = paired, exact = wilcox.exact,
correct = wilcox.correct,
alternative = alternative)
nonparametric <- data.frame(test = "stats::Wilcoxon",
test.statistic = if (paired) "V" else "W",
test.value = res.wilcox[["statistic"]],
test.df = NA, p = res.wilcox[["p.value"]],
stringsAsFactors = FALSE)
if (!(coin == FALSE) && !requireNamespace("coin", quietly = TRUE)) {
warning("package coin necessary if coin != FALSE.")
coin <- FALSE
}
if (!(coin == FALSE)) {
dv <- c(x, y)
iv <- factor(rep(c("A", "B"), c(length(x), length(y))))
if (missing(perm.distribution)) {
perm.distribution <- coin::approximate(100000)
}
if (paired) {
id <- factor(rep(1:length(x), 2))
formula.coin <- as.formula(dv ~ iv | id)
} else formula.coin <- as.formula(dv ~ iv)
if (isTRUE(coin)) coin <- implemented.tests
else coin <- match.arg(coin, implemented.tests, several.ok = TRUE)
tryCatch(if ("permutation" %in% coin) {
res.perm <- coin::oneway_test(formula.coin,
distribution=perm.distribution,
alternative = alternative)
nonparametric <- rbind(nonparametric,
data.frame(test = "permutation",
test.statistic = "Z",
test.value =
coin::statistic(res.perm),
test.df = NA,
p = coin::pvalue(res.perm)[1],
stringsAsFactors = FALSE))
}, error = function(e)
warning(paste("coin::permutation test failed:", e)))
tryCatch(if ("Wilcoxon" %in% coin) {
res.coin.wilcox <- coin::wilcox_test(formula.coin,
distribution=perm.distribution,
alternative = alternative)
nonparametric <- rbind(nonparametric,
data.frame(test = "coin::Wilcoxon",
test.statistic = "Z",
test.value =
coin::statistic(res.coin.wilcox),
test.df = NA,
p = coin::pvalue(res.coin.wilcox)[1],
stringsAsFactors = FALSE))
}, error = function(e) warning(paste("coin::Wilcoxon test failed:", e)))
tryCatch(if ("median" %in% coin) {
res.median <- coin::median_test(formula.coin,
distribution=perm.distribution,
alternative = alternative)
nonparametric <- rbind(nonparametric,
data.frame(test = "median",
test.statistic = "Z",
test.value =
coin::statistic(res.median),
test.df = NA,
p = coin::pvalue(res.median)[1],
stringsAsFactors = FALSE))
}, error = function(e) warning(paste("coin::median test failed:", e)))
}
rownames(nonparametric) <- NULL
out <- c(out, nonparametric = list(nonparametric))
}
out
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(lazysf)
library(lazysf)
library(dplyr)
f <- system.file("gpkg/nc.gpkg", package = "sf", mustWork = TRUE) |
mtitle <-
function(main,ll,lc,
lr=format(Sys.time(),'%d%b%y'),
cex.m=1.75, cex.l=.5, ...)
{
out <- any(par()$oma!=0)
g <-
if(out) function(...) mtext(..., outer=TRUE)
else function(z, adj, cex, side, ...)
if(missing(side))
title(z, adj=adj, cex=cex)
else
title(sub=z, adj=adj, cex=cex)
if(!missing(main))
g(main,cex=cex.m,adj=.5)
if(!missing(lc))
g(lc,side=1,adj=.5,cex=cex.l,...)
if(!missing(ll))
g(ll,side=1,adj=0,cex=cex.l,...)
if(lr!="")
g(lr,side=1,adj=1,cex=cex.l,...)
invisible()
} |
mat_shrink <- function (K, tau){
r <- dim(K)[1]
c <- dim(K)[2]
s <- svd(K, nu=r, nv=c)
L <- pmax(s$d-tau,0)
if (r < c) {
K <- s$u %*% diag(L) %*% t(s$v[,1:r])
} else {
K <- s$u[,1:c] %*% diag(L) %*% t(s$v)
}
return(K)
} |
add.term <- function (y, xinc, xout, devi_0, type = "logistic", logged = FALSE,
tol = 1e-07, maxiters = 100, parallel = FALSE) {
.Call(Rfast2_add_term, y, cbind(1, xinc), xout, devi_0, type, tol,
logged, parallel, maxiters)
} |
context("Weighted link positions")
test_that("Check binary matrices", {
for (i in 1:10) {
W <- rbm(20,20)
lp <- link_positions(W, six_node = TRUE, weights = FALSE, normalisation = "none")
lw <- link_positions(W, six_node = TRUE, weights = TRUE, normalisation = "none")
expect(all(lw == lp), failure_message = "failed")
}
})
test_that("Check matrices with equal weights", {
for (i in 1:5) {
W <- 3 * rbm(20,20)
lp <- link_positions(W, six_node = TRUE, weights = FALSE, normalisation = "none")
lw <- link_positions(W, six_node = TRUE, weights = TRUE, normalisation = "none")
expect(all(lw == 3 * lp), failure_message = "failed")
}
for (i in 1:5) {
W <- 0.5 * rbm(20,20)
lp <- link_positions(W, six_node = TRUE, weights = FALSE, normalisation = "none")
lw <- link_positions(W, six_node = TRUE, weights = TRUE, normalisation = "none")
expect(all(lw == 0.5 * lp), failure_message = "failed")
}
})
test_that("Check matrices with one weighted link", {
for (i in 1:5) {
W <- rbm(20,20)
W[1,1] <- 10
lp <- link_positions(W, six_node = TRUE, weights = FALSE, normalisation = "none")
lw <- link_positions(W, six_node = TRUE, weights = TRUE, normalisation = "none")
expect(all(lw[1,] == 10 * lp[1,]), failure_message = "failed")
expect(all(lw[-1,] == lp[-1,]), failure_message = "failed")
}
for (i in 1:5) {
W <- rbm(20,20)
W[3,3] <- 0.5
lp <- link_positions(W, six_node = TRUE, weights = FALSE, normalisation = "none")
lw <- link_positions(W, six_node = TRUE, weights = TRUE, normalisation = "none")
ind <- which(rownames(lp) == "r3 -- c3")
expect(all(lw[ind,] == 0.5 * lp[ind,]), failure_message = "failed")
expect(all(lw[-ind,] == lp[-ind,]), failure_message = "failed")
}
})
test_that("Check matrices with several weighted links", {
for (i in 1:5) {
W <- rbm(20,20)
W[7,8] <- 1.5
W[4,6] <- 0.7
lp <- link_positions(W, six_node = TRUE, weights = FALSE, normalisation = "none")
lw <- link_positions(W, six_node = TRUE, weights = TRUE, normalisation = "none")
ind <- which(rownames(lp) == "r7 -- c8")
ind2 <- which(rownames(lp) == "r4 -- c6")
expect(all(lw[ind,] == 1.5 * lp[ind,]), failure_message = "failed")
expect(all(lw[ind2,] == 0.7 * lp[ind2,]), failure_message = "failed")
expect(all(lw[-c(ind, ind2),] == lp[-c(ind, ind2),]), failure_message = "failed")
}
}) |
convert_ket2DM <- function(v){
kronecker(v,adjoint(v))
} |
btest <- function(prices,
signal,
do.signal = TRUE,
do.rebalance = TRUE,
print.info = NULL,
b = 1L,
fraction = 1,
initial.position = 0,
initial.cash = 0,
final.position = FALSE,
cashflow = NULL,
tc = 0,
...,
add = FALSE,
lag = 1,
convert.weights = FALSE,
trade.at.open = TRUE,
tol = 1e-5,
tol.p = NA,
Globals = list(),
prices0 = NULL,
include.data = FALSE,
include.timestamp = TRUE,
timestamp, instrument,
progressBar = FALSE,
variations,
variations.settings = list(),
replications) {
if (!missing(variations)) {
x <- match.call()
all_args <- as.list(x)[-1L]
all_args <- lapply(all_args, eval)
variations <- all_args$variations
all_args$variations <- NULL
vsettings <- list(method = "loop",
load.balancing = FALSE,
cores = getOption("mc.cores", 2L),
expand.grid = TRUE)
vsettings[names(variations.settings)] <- variations.settings
all_args$variations.settings <- NULL
lens <- lengths(variations)
if (vsettings$expand.grid)
cases <- do.call(expand.grid,
lapply(lens, seq_len))
else
cases <- as.data.frame(lapply(lens, seq_len))
args <- vector("list", length = nrow(cases))
for (i in seq_along(args)) {
tmp <- mapply(`[[`, variations, cases[i, ],
SIMPLIFY = FALSE)
args[[i]] <- c(all_args, tmp)
attr(args[[i]], "variation") <- tmp
}
if (is.null(vsettings$method) ||
vsettings$method == "loop") {
ans <- vector("list", length(args))
for (i in seq_along(args)) {
ans[[i]] <- do.call(btest, args[[i]])
attr(ans[[i]], "variation") <- attr(args[[i]], "variation")
}
if (!is.null(vsettings$label))
names(ans) <- vsettings$label
return(ans)
} else if (vsettings$method == "parallel" ||
vsettings$method == "snow") {
if (!requireNamespace("parallel"))
stop("package ", sQuote("parallel"), " not available")
if (is.null(vsettings$cl) && is.numeric(vsettings$cores))
cl <- parallel::makeCluster(c(rep("localhost", vsettings$cores)),
type = "SOCK")
on.exit(parallel::stopCluster(cl))
ans <- parallel::parLapplyLB(cl, X = args,
fun = function(x) do.call("btest", x))
if (!is.null(vsettings$label))
names(ans) <- vsettings$label
return(ans)
} else if (vsettings$method == "multicore") {
if (!requireNamespace("parallel"))
stop("package ", sQuote("parallel"), " not available")
ans <- parallel::mclapply(X = args,
FUN = function(x) do.call("btest", x),
mc.cores = vsettings$cores)
if (!is.null(vsettings$label))
names(ans) <- vsettings$label
return(ans)
}
} else if (!missing(replications)) {
x <- match.call()
all_args <- as.list(x)[-1L]
all_args <- lapply(all_args, eval)
replications <- all_args$replications
all_args$replications <- NULL
vsettings <- list(method = "loop",
load.balancing = FALSE,
cores = getOption("mc.cores", 2L))
vsettings[names(variations.settings)] <- variations.settings
all_args$variations.settings <- NULL
if (is.null(vsettings$method) ||
vsettings$method == "loop") {
ans <- vector("list", replications)
for (i in seq_len(replications)) {
ans[[i]] <- do.call(btest, all_args)
attr(ans[[i]], "replication") <- i
}
if (!is.null(vsettings$label))
names(ans) <- vsettings$label
return(ans)
} else if (vsettings$method == "parallel" ||
vsettings$method == "snow") {
if (!requireNamespace("parallel"))
stop("package ", sQuote("parallel"), " not available")
if (is.null(vsettings$cl) && is.numeric(vsettings$cores))
cl <- parallel::makeCluster(
c(rep("localhost", vsettings$cores)),
type = "SOCK")
on.exit(parallel::stopCluster(cl))
clusterExport(cl, "all_args", environment())
if (vsettings$load.balancing)
ans <- parallel::parLapplyLB(cl, X = seq_len(replications),
fun = function(i) {
ans <- do.call("btest", all_args)
attr(ans, "replication") <- i
ans})
else
ans <- parallel::parLapply(cl, X = seq_len(replications),
fun = function(i) {
ans <- do.call("btest", all_args)
attr(ans, "replication") <- i
ans})
if (!is.null(vsettings$label))
names(ans) <- vsettings$label
return(ans)
} else if (vsettings$method == "multicore") {
if (!requireNamespace("parallel"))
stop("package ", sQuote("parallel"), " not available")
ans <- parallel::mclapply(X = seq_len(replications),
FUN = function(i) {
ans <- do.call("btest", all_args)
attr(ans, "replication") <- i
ans
},
mc.cores = vsettings$cores)
if (!is.null(vsettings$label))
names(ans) <- vsettings$label
return(ans)
}
}
L <- lag
tc_fun <- if (is.function(tc))
tc
if (!missing(timestamp) &&
(inherits(timestamp, "Date") || inherits(timestamp, "POSIXct")) &&
inherits(b, class(timestamp))) {
b <- if (b < min(timestamp))
0
else
.match_or_previous(b, timestamp)
}
if ("tradeOnOpen" %in% names(list(...)))
warning("Did you mean 'trade.at.open'? See ChangeLog 2017-11-14.")
if ("assignInGlobals" %in% names(list(...)))
warning("Did you mean 'Globals'? See ChangeLog 2017-11-14.")
if (convert.weights && initial.cash == 0)
warning(sQuote("convert.weights"), " is TRUE and ",
sQuote("initial.cash"), " is zero")
if (convert.weights && b == 0 && is.null(prices0) && lag > 0)
stop("to convert weights to positions, either specify ",
sQuote("prices0"), " or set ", sQuote("b"), " > 0")
if (add)
.NotYetUsed("add", FALSE)
db.signal <- if (is.function(signal) && isdebugged(signal))
TRUE else FALSE
if (is.function(do.signal) && isdebugged(do.signal))
db.do.signal <- TRUE
else
db.do.signal <- FALSE
if (is.function(do.rebalance) && isdebugged(do.rebalance))
db.do.rebalance <- TRUE
else
db.do.rebalance <- FALSE
if (is.function(print.info) && isdebugged(print.info))
db.print.info <- TRUE
else
db.print.info <- FALSE
db.cashflow <- if (is.function(cashflow) && isdebugged(cashflow))
TRUE else FALSE
db.tc_fun <- if (is.function(tc) && isdebugged(tc))
TRUE else FALSE
if (is.null(do.signal) || identical(do.signal, TRUE)) {
do.signal <- function(...)
TRUE
} else if (identical(do.signal, FALSE) && !final.position) {
do.signal <- function(...)
FALSE
warning(sQuote("do.signal"), " is FALSE: strategy will never trade")
} else if (!missing(timestamp) && inherits(do.signal, class(timestamp))) {
rebalancing_times <- matchOrNext(do.signal, timestamp)
do.signal <- function(...)
Time(0L) %in% rebalancing_times
} else if (is.numeric(do.signal)) {
rebalancing_times <- do.signal
do.signal <- function(...) {
if (Time(0L) %in% rebalancing_times)
TRUE
else
FALSE
}
} else if (is.logical(do.signal)) {
rebalancing_times <- which(do.signal)
do.signal <- function(...)
if (Time(0L) %in% rebalancing_times)
TRUE
else
FALSE
} else if (is.character(do.signal) &&
tolower(do.signal) == "firstofmonth") {
tmp <- as.Date(timestamp)
if (any(is.na(tmp)))
stop("timestamp with NAs")
ii <- if (b > 0)
-seq_len(b)
else
TRUE
i_rdays <- match(aggregate(tmp[ii],
by = list(format(tmp[ii], "%Y-%m")),
FUN = head, 1)[[2L]],
tmp)
do.signal <- function(...)
Time(0) %in% i_rdays
} else if (is.character(do.signal) &&
(tolower(do.signal) == "lastofmonth" ||
tolower(do.signal) == "endofmonth")) {
tmp <- as.Date(timestamp)
if (any(is.na(tmp)))
stop("timestamp with NAs")
ii <- if (b > 0)
-seq_len(b)
else
TRUE
i_rdays <- match(aggregate(tmp[ii],
by = list(format(tmp[ii], "%Y-%m")),
FUN = tail, 1)[[2L]],
tmp)
do.signal <- function(...)
Time(0) %in% i_rdays
} else if (is.character(do.signal) &&
tolower(do.signal) == "firstofquarter") {
tmp <- as.Date(timestamp)
if (any(is.na(tmp)))
stop("timestamp with NAs")
ii <- if (b > 0)
-seq_len(b)
else
TRUE
i_rdays <- match(aggregate(tmp[ii],
by = list(paste0(format(tmp[ii], "%Y"), "-", quarters(tmp[ii]))),
FUN = head, 1)[[2L]],
tmp)
do.signal <- function(...)
Time(0) %in% i_rdays
} else if (is.character(do.signal) &&
tolower(do.signal) == "lastofquarter") {
tmp <- as.Date(timestamp)
if (any(is.na(tmp)))
stop("timestamp with NAs")
ii <- if (b > 0)
-seq_len(b)
else
TRUE
i_rdays <- match(aggregate(tmp[ii],
by = list(paste0(format(tmp[ii], "%Y"), "-", quarters(tmp[ii]))),
FUN = tail, 1)[[2L]],
tmp)
do.signal <- function(...)
Time(0) %in% i_rdays
}
if (is.null(do.rebalance) || identical(do.rebalance, TRUE)) {
do.rebalance <- function(...)
TRUE
} else if (identical(do.rebalance, FALSE)) {
do.rebalance <- function(...)
FALSE
warning(sQuote("do.rebalance"), " is FALSE: strategy will never trade")
} else if (identical(do.rebalance, "do.signal")) {
do.rebalance <- function(...)
computeSignal
} else if (!missing(timestamp) && inherits(do.rebalance, class(timestamp))) {
rebalancing_times <- matchOrNext(do.rebalance, timestamp)
do.rebalance <- function(...)
Time(0L) %in% rebalancing_times
} else if (is.numeric(do.rebalance)) {
rebalancing_times <- do.rebalance
do.rebalance <- function(...) {
Time(0L) %in% rebalancing_times
}
} else if (is.logical(do.rebalance)) {
rebalancing_times <- which(do.rebalance)
do.rebalance <- function(...)
if (Time(0L) %in% rebalancing_times)
TRUE
else
FALSE
} else if (is.character(do.rebalance) &&
tolower(do.rebalance) == "firstofmonth") {
tmp <- as.Date(timestamp)
if (any(is.na(tmp)))
stop("timestamp with NAs")
ii <- if (b > 0)
-seq_len(b)
else
TRUE
i_rdays <- match(aggregate(tmp[ii],
by = list(format(tmp[ii], "%Y-%m")),
FUN = head, 1)[[2L]],
tmp)
do.rebalance <- function(...)
Time(0) %in% i_rdays
} else if (is.character(do.rebalance) &&
(tolower(do.rebalance) == "lastofmonth" ||
tolower(do.rebalance) == "endofmonth")) {
tmp <- as.Date(timestamp)
if (any(is.na(tmp)))
stop("timestamp with NAs")
ii <- if (b > 0)
-seq_len(b)
else
TRUE
i_rdays <- match(aggregate(tmp[ii],
by = list(format(tmp[ii], "%Y-%m")),
FUN = tail, 1)[[2L]],
tmp)
do.rebalance <- function(...)
Time(0) %in% i_rdays
} else if (is.character(do.rebalance) &&
tolower(do.rebalance) == "firstofquarter") {
tmp <- as.Date(timestamp)
if (any(is.na(tmp)))
stop("timestamp with NAs")
ii <- if (b > 0)
-seq_len(b)
else
TRUE
i_rdays <- match(aggregate(tmp[ii],
by = list(paste0(format(tmp[ii], "%Y"), "-", quarters(tmp[ii]))),
FUN = head, 1)[[2L]],
tmp)
do.rebalance <- function(...)
Time(0) %in% i_rdays
} else if (is.character(do.rebalance) &&
tolower(do.rebalance) == "lastofquarter") {
tmp <- as.Date(timestamp)
if (any(is.na(tmp)))
stop("timestamp with NAs")
ii <- if (b > 0)
-seq_len(b)
else
TRUE
i_rdays <- match(aggregate(tmp[ii],
by = list(paste0(format(tmp[ii], "%Y"), "-", quarters(tmp[ii]))),
FUN = tail, 1)[[2L]],
tmp)
do.rebalance <- function(...)
Time(0) %in% i_rdays
}
if (is.null(cashflow)) {
cashflow <- function(...)
0
} else if (is.numeric(cashflow)) {
cashflow <- function(...)
cashflow[1L]
}
doPrintInfo <- TRUE
if (is.null(print.info)) {
doPrintInfo <- FALSE
print.info <- function(...)
NULL
}
Open <- function(lag = L, n = NA) {
if (!is.na(n))
mO[t - (n:1), , drop = FALSE]
else
mO[t - lag, , drop = FALSE]
}
High <- function(lag = L, n = NA) {
if (!is.na(n))
mH[t - (n:1), , drop = FALSE]
else
mH[t - lag, , drop = FALSE]
}
Low <- function(lag = L, n = NA) {
if (!is.na(n))
mL[t - (n:1), , drop = FALSE]
else
mL[t - lag, , drop = FALSE]
}
Close <- function(lag = L, n = NA) {
if (!is.na(n))
mC[t - (n:1), , drop = FALSE]
else
mC[t - lag, , drop = FALSE]
}
Wealth <- function(lag = L, n = NA) {
if (!is.na(n))
v[t - (n:1)]
else
v[t - lag]
}
Cash <- function(lag = L, n = NA) {
if (!is.na(n))
cash[t - (n:1)]
else
cash[t - lag]
}
Time <- function(lag = L, n = NA) {
if (!is.na(n))
t - (n:1)
else
t - lag
}
Portfolio <- function(lag = L, n = NA) {
if (!is.na(n))
X[t - (n:1), , drop = FALSE]
else
X[t - lag, , drop = FALSE]
}
SuggestedPortfolio <- function(lag = L, n = NA) {
if (!is.na(n))
Xs[t - (n:1), , drop = FALSE]
else
Xs[t - lag, , drop = FALSE]
}
if (!missing(timestamp)) {
Timestamp <- function(lag = L, n = NA) {
if (!is.na(n))
timestamp[t - (n:1)]
else
timestamp[t - lag]
}
} else
Timestamp <- Time
Globals <- list2env(Globals)
reservedNames <- c("Open", "High", "Low", "Close",
"Wealth", "Cash", "Time", "Timestamp",
"Portfolio", "SuggestedPortfolio", "Globals")
funs <- c("signal", "do.signal", "do.rebalance", "print.info", "cashflow")
if (!is.null(tc_fun))
funs <- c(funs, "tc_fun")
for (thisfun in funs) {
fNames <- names(formals(get(thisfun)))
for (rname in reservedNames)
if (rname %in% fNames)
stop(sQuote(rname), " cannot be used as an argument name for ",
sQuote(thisfun))}
add.args <- alist(Open = Open,
High = High,
Low = Low,
Close = Close,
Wealth = Wealth,
Cash = Cash,
Time = Time,
Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
formals(signal) <- c(formals(signal), add.args)
if (db.signal)
debug(signal)
formals(do.signal) <- c(formals(do.signal), add.args)
if (db.do.signal)
debug(do.signal)
formals(do.rebalance) <- c(formals(do.rebalance), add.args)
if (db.do.rebalance)
debug(do.rebalance)
formals(print.info) <- c(formals(print.info), add.args)
if (db.print.info)
debug(print.info)
formals(cashflow) <- c(formals(cashflow), add.args)
if (db.cashflow)
debug(cashflow)
if (!is.null(tc_fun)) {
formals(tc_fun) <- c(formals(tc_fun), add.args)
if (db.tc_fun)
debug(tc_fun)
}
if (is.list(prices)) {
if (length(prices) == 1L) {
mC <- prices[[1L]]
if (is.null(dim(mC)))
mC <- as.matrix(mC)
trade.at.open <- FALSE
} else if (length(prices) == 4L) {
mO <- prices[[1L]]
mH <- prices[[2L]]
mL <- prices[[3L]]
mC <- prices[[4L]]
if (is.null(dim(mO)))
mO <- as.matrix(mO)
if (is.null(dim(mH)))
mH <- as.matrix(mH)
if (is.null(dim(mL)))
mL <- as.matrix(mL)
if (is.null(dim(mC)))
mC <- as.matrix(mC)
} else
stop("see documentation on ", sQuote("prices"))
} else {
if (is.null(dim(prices)))
prices <- as.matrix(prices)
if (ncol(prices) == 1L) {
mC <- prices
trade.at.open <- FALSE
} else if (ncol(prices) == 4L) {
mO <- prices[, 1L]
mH <- prices[, 2L]
mL <- prices[, 3L]
mC <- prices[, 4L]
} else
stop("see documentation on ", sQuote("prices"))
}
T <- nrow(mC)
nA <- ncol(mC)
if (!missing(timestamp) && length(timestamp) != T)
warning("length(timestamp) does not match nrow(prices)")
if (!missing(instrument) && length(instrument) != nA)
warning("length(instrument) does not match ncol(prices)")
tccum <- numeric(T)
X <- array(NA, dim = c(T, nA))
Xs <- array( 0, dim = c(T, nA))
colnames(X) <- colnames(mC)
colnames(Xs) <- colnames(mC)
v <- cash <- numeric(T)
v[] <- NA
if (b > 0L) {
Xs[b, ] <- X[b, ] <- initial.position
cash[b] <- initial.cash
v[b] <- initial.cash + if (initial.position != 0)
initial.position %*% mC[b, ] else 0
}
if (initial.position != 0 && !is.null(prices0)) {
initial.wealth <- sum(prices0 * initial.position) + initial.cash
} else if (initial.position != 0) {
warning(sQuote("initial.position"), " specified, but no ", sQuote("prices0"))
initial.wealth <- initial.cash
} else
initial.wealth <- initial.cash
if (b == 0L) {
t <- 1L
computeSignal <- do.signal(...,
Open = Open, High = High,
Low = Low, Close = Close,
Wealth = Wealth, Cash = Cash,
Time = Time, Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
if (computeSignal) {
temp <- signal(..., Open = Open, High = High, Low = Low,
Close = Close, Wealth = Wealth, Cash = Cash,
Time = Time, Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
if (!is.null(temp)) {
if (convert.weights) {
temp0 <- temp != 0
temp[temp0] <- temp[temp0] *
initial.wealth/prices0[temp0]
}
Xs[t, ] <- temp
} else
Xs[t, ] <- initial.position
computeSignal <- FALSE
} else {
Xs[t, ] <- rep.int(0, nA)
}
rebalance <- do.rebalance(...,
Open = Open, High = High,
Low = Low, Close = Close,
Wealth = Wealth, Cash = Cash,
Time = Time, Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
dXs <- Xs[t, ] - if (any(initial.position != 0))
initial.position else 0
if (max(abs(dXs)) < tol)
rebalance <- FALSE
if (rebalance) {
if (!is.null(tc_fun))
tc <- tc_fun(...,
Open = Open, High = High,
Low = Low, Close = Close,
Wealth = Wealth, Cash = Cash,
Time = Time, Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
dx <- fraction * dXs
if (trade.at.open)
open <- mO[t, , drop = TRUE]
else
open <- mC[t, , drop = TRUE]
sx <- dx %*% open
abs_sx <- (abs(dx) * tc) %*% open
tccum[t] <- abs_sx
cash[t] <- initial.cash - sx - abs_sx
X[t, ] <- if (any(initial.position != 0)) initial.position else 0 + dx
rebalance <- FALSE
} else {
tccum[t] <- 0
cash[t] <- initial.cash
X[t, ] <- ifelse(initial.position != 0, initial.position, 0)
}
cash[t] <- cash[t] +
cashflow(...,
Open = Open,
High = High,
Low = Low,
Close = Close,
Wealth = Wealth,
Cash = Cash,
Time = Time,
Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
v[t] <- X[t, ] %*% mC[t, ] + cash[t]
if (doPrintInfo)
print.info(..., Open = Open, High = High, Low = Low,
Close = Close, Wealth = Wealth, Cash = Cash,
Time = Time, Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
}
if (progressBar)
progr <- txtProgressBar(min = max(2L, b+1L), max = T,
initial = max(2L, b+1L),
char = if (.Platform$OS.type == "unix") "\u2588" else "|",
width = ceiling(getOption("width")*0.8),
style = 3, file = "")
for (t in max(2L, b+1L):T) {
if (progressBar)
setTxtProgressBar(progr, t)
t1 <- t - 1L
computeSignal <- do.signal(...,
Open = Open, High = High,
Low = Low, Close = Close,
Wealth = Wealth,
Cash = Cash,
Time = Time,
Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
if (computeSignal) {
temp <- signal(..., Open = Open, High = High,
Low = Low, Close = Close, Wealth = Wealth,
Cash = Cash, Time = Time,
Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
if (!is.null(temp)) {
if (convert.weights) {
temp0 <- temp != 0
temp[temp0] <- temp[temp0] * v[t1] / mC[t1, temp0]
}
Xs[t, ] <- temp
} else
Xs[t, ] <- Xs[t1, ]
computeSignal <- FALSE
} else {
Xs[t, ] <- Xs[t1, ]
}
rebalance <- do.rebalance(..., Open = Open, High = High,
Low = Low, Close = Close,
Wealth = Wealth, Cash = Cash,
Time = Time, Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
dXs <- Xs[t, ] - X[t1, ]
if (max(abs(dXs)) < tol)
rebalance <- FALSE
else if (!is.na(tol.p) && initial.wealth > 0 && v[t1] > 0 ) {
dXs.p <- dXs * mC[t1, ]/v[t1]
small <- abs(dXs.p) < tol.p
dXs[small] <- 0
if (all(small))
rebalance <- FALSE
}
if (rebalance) {
dx <- fraction * dXs
if (!is.null(tc_fun))
tc <- tc_fun(...,
Open = Open, High = High,
Low = Low, Close = Close,
Wealth = Wealth, Cash = Cash,
Time = Time, Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
if (trade.at.open)
open <- mO[t, ]
else
open <- mC[t, ]
nzero <- dx != 0
sx <- dx[nzero] %*% open[nzero]
abs_sx <- (abs(dx[nzero]) * tc) %*% open[nzero]
tccum[t] <- tccum[t1] + abs_sx
cash[t] <- cash[t1] - sx - abs_sx
X[t, ] <- X[t1, ] + dx
rebalance <- FALSE
} else {
tccum[t] <- tccum[t1]
cash[t] <- cash[t1]
X[t, ] <- X[t1, ]
}
cash[t] <- cash[t] + cashflow(...,
Open = Open, High = High,
Low = Low, Close = Close,
Wealth = Wealth,
Cash = Cash,
Time = Time, Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
nzero <- X[t, ] != 0
v[t] <- X[t, nzero] %*% mC[t, nzero] + cash[t]
if (doPrintInfo)
print.info(..., Open = Open,
High = High,
Low = Low,
Close = Close,
Wealth = Wealth,
Cash = Cash,
Time = Time, Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
}
if (progressBar)
close(progr)
if (final.position) {
message("Compute final position ... ", appendLF = FALSE)
t <- t + 1L
t1 <- t - 1L
final.pos <- signal(..., Open = Open, High = High,
Low = Low, Close = Close, Wealth = Wealth,
Cash = Cash, Time = Time,
Timestamp = Timestamp,
Portfolio = Portfolio,
SuggestedPortfolio = SuggestedPortfolio,
Globals = Globals)
if (convert.weights)
final.pos <- final.pos * v[t1] / mC[t1, ]
if (!missing(instrument))
names(final.pos) <- instrument
message("done")
}
if (!missing(instrument))
colnames(Xs) <- colnames(X) <- instrument
if (is.null(colnames(X)))
colnames(Xs) <- colnames(X) <- paste("asset", seq_len(ncol(X)))
if (missing(timestamp))
timestamp <- seq_len(nrow(X))
trades <- diff(rbind(initial.position, X))
keep <- abs(trades) > sqrt(.Machine$double.eps) & !is.na(trades)
if (any(keep)) {
j.timestamp <- list()
j.amount <- list()
j.price <- list()
j.instrument <- list()
for (cc in seq_len(ncol(X))) {
ic <- keep[, cc]
if (!any(ic))
next
ccc <- as.character(cc)
j.timestamp[[ccc]] <- timestamp[ic]
j.amount[[ccc]] <- trades[ic, cc]
j.price[[ccc]] <- mC[ic, cc]
j.instrument[[ccc]] <- rep(colnames(X)[cc], sum(ic))
}
j.timestamp <- do.call(c, j.timestamp)
j.amount <- do.call(c, j.amount)
j.price <- do.call(c, j.price)
j.instrument <- do.call(c, j.instrument)
jnl <- journal(timestamp = unname(j.timestamp),
amount = unname(j.amount),
price = unname(j.price),
instrument = unname(j.instrument))
jnl <- sort(jnl)
} else
jnl <- journal()
ans <- list(position = X,
suggested.position = Xs,
cash = cash,
wealth = v,
cum.tc = tccum,
journal = jnl,
initial.wealth = initial.wealth,
b = b,
final.position = if (final.position) final.pos else NA,
Globals = Globals)
if (include.timestamp)
ans <- c(ans,
timestamp = list(timestamp))
if (include.data)
ans <- c(ans,
prices = prices,
signal = signal,
do.signal = do.signal,
instrument = if (missing(instrument)) NULL else list(instrument),
call = match.call())
class(ans) <- "btest"
ans
}
print.btest <- function(x, ...) {
cat("initial wealth",
tmp0 <- x$wealth[min(which(!is.na(x$wealth)))], " => ")
cat("final wealth ",
tmp1 <- round(x$wealth[max(which(!is.na(x$wealth)))], 2), "\n")
if (tmp0 > 0)
cat("Total return ", round(100*(tmp1/tmp0 - 1), 1), "%\n", sep = "")
invisible(x)
}
plot.btest <- function(x, y = NULL, type = "l",
xlab = "", ylab = "", ...) {
if (!is.null(x$timestamp))
plot(x$timestamp[-seq_len(x$b)], x$wealth[-seq_len(x$b)],
type = type, xlab = xlab, ylab = ylab, ...)
else
plot(x$wealth[-seq_len(x$b)], y,
type = type, xlab = xlab, ylab = ylab, ...)
invisible()
}
lines.btest <- function(x, y = NULL, type = "l",
...) {
if (!is.null(x$timestamp))
lines(x$timestamp[-seq_len(x$b)], x$wealth[-seq_len(x$b)],
type = type, ...)
else
lines(x$wealth[-seq_len(x$b)], y,
type = type, ...)
invisible()
}
atest <- btest
formals(atest)$do.signal <- FALSE
formals(atest)$do.rebalance <- FALSE
formals(atest)$final.position <- TRUE |
nigFit <-
function(x, alpha = 1, beta = 0, delta = 1, mu = 0,
method = c("mle", "gmm", "mps", "vmps"),
scale = TRUE, doplot = TRUE, span = "auto", trace = TRUE,
title = NULL, description = NULL, ...)
{
method = match.arg(method)
if (method == "mle") {
fit = .nigFit.mle(x = x, alpha = alpha, beta = beta, delta = delta,
mu = mu , scale = scale, doplot = doplot, span = span,
trace = trace, title = title, description = description, ...)
} else if (method == "gmm") {
fit = .nigFit.gmm(x = x, alpha = alpha, beta = beta, delta = delta,
mu = mu , scale = scale, doplot = doplot, span = span,
trace = trace, title = title, description = description, ...)
} else if (method == "mps") {
fit = .nigFit.mps(x = x, alpha = alpha, beta = beta, delta = delta,
mu = mu , scale = scale, doplot = doplot, span = span,
trace = trace, title = title, description = description, ...)
} else if (method == "vmps") {
fit = .nigFit.vmps(x = x, alpha = alpha, beta = beta, delta = delta,
mu = mu , scale = scale, doplot = doplot, span = span,
trace = trace, title = title, description = description, ...)
}
fit
}
.nigFit.mle <-
function(x, alpha = 1, beta = 0, delta = 1, mu = 0,
scale = TRUE, doplot = TRUE, add = FALSE, span = "auto", trace = TRUE,
title = NULL, description = NULL, ...)
{
x.orig = x
x = as.vector(x)
if (scale) {
SD = sd(x)
x = x / SD }
obj = function(x, y = x, trace) {
if (abs(x[2]) >= x[1]) return(1e9)
f = -sum(dnig(y, x[1], x[2], x[3], x[4], log = TRUE))
if (trace) {
cat("\n Objective Function Value: ", -f)
cat("\n Parameter Estimates: ", x, "\n")
}
f }
eps = 1e-10
BIG = 1000
fit = nlminb(
start = c(alpha, beta, delta, mu),
objective = obj,
lower = c(eps, -BIG, eps, -BIG),
upper = BIG,
y = x,
trace = trace)
names(fit$par) <- c("alpha", "beta", "delta", "mu")
if (scale) {
fit$scaleParams = c(SD, SD, 1/SD, 1/SD)
fit$par = fit$par / fit$scaleParams
fit$objective = obj(fit$par, y = as.vector(x.orig), trace = trace)
} else {
fit$scaleParams = rep(1, time = length(fit$par))
}
fit$scale = scale
fit$estimate = fit$par
fit$minimum = -fit$objective
fit$code = fit$convergence
fit = .distStandardErrors(fit, obj, x)
if (is.null(title)) title = "Normal Inverse Gaussian Parameter Estimation"
if (is.null(description)) description = description()
if (doplot) .distFitPlot(
fit,
x = x.orig,
FUN = "dnig",
main = "NIG Parameter Estimation",
span = span, add = add, ...)
new("fDISTFIT",
call = match.call(),
model = "Normal Inverse Gaussian Distribution",
data = as.data.frame(x.orig),
fit = fit,
title = as.character(title),
description = description() )
}
.nigFit.gmm <-
function(x,
scale = TRUE, doplot = TRUE, add = FALSE, span = "auto", trace = TRUE,
title = NULL, description = NULL, ...)
{
x.orig = x
x = as.vector(x)
if (scale) {
SD = sd(x)
x = x / SD }
CALL = match.call()
obj <- function(Theta, x) {
alpha = Theta[1]
beta = Theta[2]
delta = Theta[3]
mu = Theta[4]
names(Theta) <- c("alpha", "beta", "delta", "mu")
if (TRUE) print(Theta)
m1 <- x - .ghMuMoments(1, alpha, beta, delta, mu, lambda = -0.5)
m2 <- x^2 - .ghMuMoments(2, alpha, beta, delta, mu, lambda = -0.5)
m3 <- x^3 - .ghMuMoments(3, alpha, beta, delta, mu, lambda = -0.5)
m4 <- x^4 - .ghMuMoments(4, alpha, beta, delta, mu, lambda = -0.5)
f <- cbind(m1, m2, m3, m4)
return(f)
}
r <- .gmm(g = obj, x = x, t0 = c(1, 0, 1, 0))
names(r$par) <- c("alpha", "beta", "delta", "mu")
if (is.null(title)) title = "Normal Inverse Gaussian Parameter Estimation"
if (is.null(description)) description = description()
if (scale) {
r$par = r$par / c(SD, SD, 1/SD, 1/SD)
r$objective = NA
}
fit = list(estimate = r$par)
if (doplot) {
x = as.vector(x.orig)
if (span == "auto") span = seq(min(x), max(x), length = 51)
z = density(x, n = 100, ...)
x = z$x[z$y > 0]
y = z$y[z$y > 0]
y.points = dnig(span, r$par[1], r$par[2], r$par[3], r$par[4])
ylim = log(c(min(y.points), max(y.points)))
if (add) {
lines(x = span, y = log(y.points), col = "steelblue")
} else {
plot(x, log(y), xlim = c(span[1], span[length(span)]),
ylim = ylim, type = "p", xlab = "x", ylab = "log f(x)", ...)
title("NIG GMM Parameter Estimation")
lines(x = span, y = log(y.points), col = "steelblue")
}
}
new("fDISTFIT",
call = as.call(CALL),
model = "Normal Inverse Gaussian Distribution",
data = as.data.frame(x.orig),
fit = fit,
title = as.character(title),
description = description() )
}
.nigFit.mps <-
function(x, alpha = 1, beta = 0, delta = 1, mu = 0,
scale = TRUE, doplot = TRUE, add = FALSE, span = "auto", trace = TRUE,
title = NULL, description = NULL, ...)
{
x.orig = x
x = as.vector(x)
if (scale) {
SD = sd(x)
x = x / SD }
CALL = match.call()
obj <- function(x, y = x, trace) {
if (abs(x[2]) >= x[1]) return(1e9)
DH = diff(c(0, na.omit(.pnigC(sort(y), x[1], x[2], x[3], x[4])), 1))
f = -mean(log(DH[DH > 0]))*length(y)
if (trace) {
cat("\n Objective Function Value: ", -f)
cat("\n Parameter Estimates: ", x[1], x[2], x[3], x[4], "\n")
}
f }
eps = 1e-10
BIG = 1000
r = nlminb(start = c(alpha, beta, delta, mu), objective = obj,
lower = c(eps, -BIG, eps, -BIG), upper = BIG, y = x, trace = trace)
names(r$par) <- c("alpha", "beta", "delta", "mu")
hessian = tsHessian(x = r$par, fun = obj, y = x, trace = FALSE)
colnames(hessian) = rownames(hessian) = names(r$par)
varcov = solve(hessian)
par.ses = sqrt(diag(varcov))
if (scale) par.ses = par.ses / c(SD, SD, 1/SD, 1/SD)
if (is.null(title)) title = "NIG mps Parameter Estimation"
if (is.null(description)) description = description()
if (scale) {
r$par = r$par / c(SD, SD, 1/SD, 1/SD)
r$objective = obj(r$par, y = as.vector(x.orig), trace = trace)
}
fit = list(
estimate = r$par,
minimum = -r$objective,
error = par.ses,
code = r$convergence)
if (doplot) {
x = as.vector(x.orig)
if (span == "auto") span = seq(min(x), max(x), length = 501)
z = density(x, n = 100, ...)
x = z$x[z$y > 0]
y = z$y[z$y > 0]
y.points = dnig(span, r$par[1], r$par[2], r$par[3], r$par[4])
ylim = log(c(min(y.points), max(y.points)))
if (add) {
lines(x = span, y = log(y.points), col = "steelblue")
} else {
plot(x, log(y), xlim = c(span[1], span[length(span)]),
ylim = ylim, type = "p", xlab = "x", ylab = "log f(x)", ...)
title("NIG MPS Parameter Estimation")
lines(x = span, y = log(y.points), col = "steelblue")
}
}
new("fDISTFIT",
call = as.call(CALL),
model = "Normal Inverse Gaussian Distribution",
data = as.data.frame(x.orig),
fit = fit,
title = as.character(title),
description = description() )
}
.nigFit.vmps <-
function (x, alpha = 1, beta = 0, delta = 1, mu = 0,
scale = TRUE, doplot = TRUE, add = FALSE, span = "auto", trace = TRUE,
title = NULL,description = NULL, ...)
{
x.orig = x
x = as.vector(x)
if (scale) {
SD = sd(x)
x = x/SD
}
CALL = match.call()
obj <- function(x, y = x, trace) {
if (abs(x[2]) >= x[1]) return(1e+9)
DH = diff(c(0, na.omit(.pnigC(sort(y), x[1], x[2], x[3], x[4])), 1))
f = log(var(DH[DH > 0]))
if (trace) {
cat("\n Objective Function Value: ", -f)
cat("\n Parameter Estimates: ", x[1], x[2], x[3], x[4], "\n")
}
f
}
eps = 1e-10
BIG = 1000
r = nlminb(
start = c(alpha, beta, delta, mu),
objective = obj,
lower = c(eps, -BIG, eps, -BIG),
upper = BIG, y = x,
trace = trace)
names(r$par) <- c("alpha", "beta", "delta", "mu")
hessian = tsHessian(x = r$par, fun = obj, y = x, trace = FALSE)
colnames(hessian) = rownames(hessian) = names(r$par)
varcov = solve(hessian)
par.ses = sqrt(diag(varcov))
if (scale) par.ses = par.ses / c(SD, SD, 1/SD, 1/SD)
if (is.null(title)) title = "NIG varMPS Parameter Estimation"
if (is.null(description)) description = description()
if (scale) {
r$par = r$par/c(SD, SD, 1/SD, 1/SD)
r$objective = obj(r$par, y = as.vector(x.orig), trace = trace)
}
fit = list(
estimate = r$par,
minimum = -r$objective,
error = par.ses,
code = r$convergence)
if (doplot) {
x = as.vector(x.orig)
if (span == "auto") span = seq(min(x), max(x), length = 501)
z = density(x, n = 100, ...)
x = z$x[z$y > 0]
y = z$y[z$y > 0]
y.points = dnig(span, r$par[1], r$par[2], r$par[3], r$par[4])
ylim = log(c(min(y.points), max(y.points)))
if (add) {
lines(x = span, y = log(y.points), col = "steelblue")
} else {
plot(x, log(y), xlim = c(span[1], span[length(span)]),
ylim = ylim, type = "p", xlab = "x", ylab = "log f(x)", ...)
title("NIG varMPS Parameter Estimation")
lines(x = span, y = log(y.points), col = "steelblue")
}
}
new("fDISTFIT",
call = as.call(CALL),
model = "Normal Inverse Gaussian Distribution",
data = as.data.frame(x.orig),
fit = fit,
title = as.character(title),
description = description() )
} |
convert_municipality_codes <- function (ids = NULL, municipalities = NULL) {
df <- get_municipality_info_mml()
conversion.table <- df[, c("Kunta", "Kunta.FI")]
names(conversion.table) <- c("id", "name")
conversion.table$id <- as.character(conversion.table$id)
conversion.table$name <- as.character(conversion.table$name)
res <- conversion.table
if (!is.null(ids)) {
res <- conversion.table$name[match(as.character(ids), conversion.table$id)]
names(res) <- ids
} else if (!is.null(municipalities)) {
res <- conversion.table$id[match(as.character(municipalities), conversion.table$name)]
names(res) <- municipalities
}
res
} |
gamObj <- function(object,
...) {
UseMethod("gamObj")
}
gamObj.gampsth <- function(object,...) {
evalq(PoissonF, envir=environment(object$lambdaFct))
}
gamObj.gamlockedTrain <- function(object, ...) {
object$gamFit
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.