code
stringlengths 1
13.8M
|
---|
derand_RL <-
function(P,F,CR,expt){
N <- length(P[,1])
d <- length(P[1,])-1
y <- P[expt[1],1:d]
vyb <- nahvyb_expt(N,3,expt)
r123 <- P[vyb,]
fmin <- min(r123[,d+1])
indmin <- which.min(r123[,d+1])
r1 <- r123[indmin,1:d]
r123 <- r123[-indmin,]
r2 <- r123[1,1:d]
r3 <- r123[2,1:d]
v <- r1+F*(r2-r3)
change <- which(runif(d)<CR)
if (is.empty(change))
change <- 1+trunc(d*runif(1))
y[change]=v[change]
return(y)
} |
mle.getPtBSbyK=function(S, ranks, num.misses=NULL) {
if (is.null(num.misses)) { num.misses=log2(length(ranks)) }
ranks2=ranks[which(names(ranks) %in% S)]
pt.bitString=list()
for (p in seq_len(length(S))) {
miss=0
thresh=length(ranks2[[S[p]]])
for (ii in seq_len(length(ranks2[[S[p]]]))) {
ind_t=as.numeric(ranks2[[S[p]]][ii] %in% S)
if (ind_t==0) {
miss=miss + 1
if (miss >= num.misses) {
thresh=ii
break;
}
} else { miss=0 }
pt.bitString[[S[p]]][ii]=ind_t
}
pt.bitString[[S[p]]]=pt.bitString[[S[p]]][seq_len(thresh)]
names(pt.bitString[[S[p]]])=ranks2[[S[p]]][seq_len(thresh)]
ind=which(pt.bitString[[S[p]]] == 1)
pt.bitString[[S[p]]]=pt.bitString[[S[p]]][seq_len(ind[length(ind)])]
}
pt.byK=list()
for (k in seq_len(length(S))) {
pt.byK_tmp=pt.bitString
bestInd=vector("numeric", length(S))
for (p in seq_len(length(S))) {
bestInd[p]=sum(pt.bitString[[p]])
}
if (length(which(bestInd>=k))>0) {
pt.byK_tmp=pt.byK_tmp[which(bestInd>=k)]
bestInd=vector("numeric", length(pt.byK_tmp))
for (p in seq_len(length(pt.byK_tmp))) {
bestInd[p]=sum(which(pt.byK_tmp[[p]] == 1)[seq_len(k)])
}
maxInd=max(which(pt.byK_tmp[[which.min(bestInd)]]==1)[seq_len(k)])
pt.byK[[k]]=pt.byK_tmp[[which.min(bestInd)]][seq_len(maxInd)]
} else {pt.byK[[k]]=pt.byK_tmp[[which.max(bestInd)]]}
}
return(pt.byK)
} |
summary_tamaan_normal_skillspace <- function(object)
{
cat("------------------------------------------------------------\n")
cat("EAP Reliability\n")
obji <- round( object$EAP.rel, 3 )
print( obji )
cat("------------------------------------------------------------\n")
cat("Covariances and Variances\n")
if ( object$G >1){
a1 <- stats::aggregate( object$variance, list( object$group ), mean )
object$variance <- a1[,2]
}
obji <- round( object$variance, 3 )
if ( object$G >1){
names(obji) <- paste0("Group", object$groups )
}
print( obji )
cat("------------------------------------------------------------\n")
cat("Correlations and Standard Deviations (in the diagonal)\n")
if ( object$G >1){
obji <- sqrt( object$variance )
} else {
obji <- stats::cov2cor(object$variance)
diag(obji) <- sqrt( diag( object$variance) )
}
if ( object$G >1){
names(obji) <- paste0("Group", object$groups )
}
obji <- round( obji, 3 )
print( obji )
cat("------------------------------------------------------------\n")
cat("Regression Coefficients\n")
obji <- round( object$beta, 5 )
print( obji )
} |
future_worldclim2 <- function(var = "tmin",
res = 10,
gcm = "BCC-CSM2-MR",
ssp = "ssp585",
interval = "2021-2040",
bry = NULL,
path = NULL,
nm_mark = "clip",
return_stack = TRUE) {
stopifnot(res %in% c(2.5, 5, 10))
stopifnot(var %in% c('tmin', 'tmax', 'prec', 'bioc'))
stopifnot(gcm %in% c("BCC-CSM2-MR", "CNRM-CM6-1",
"CNRM-ESM2-1", "CanESM5",
"GFDL-ESM4", "IPSL-CM6A-LR",
"MIROC-ES2L", "MIROC6",
"MRI-ESM2-0"))
stopifnot(ssp %in% c("ssp126", "ssp245",
"ssp370", "ssp585"))
stopifnot(interval %in% c("2021-2040", "2041-2060",
"2061-2080", "2081-2100"))
if(gcm == "GFDL-ESM4" & ssp == "ssp245"){
stop("There is no any var to download.")}
if (gcm == "GFDL-ESM4" & ssp == "ssp585" &
var != "prec"){
stop("There is no such var to download.")}
if (is.null(bry)) {
nm_mark <- "global"
message("No bry set, download global map...")
} else{
if (!(is(bry, "sf") | is(bry, 'sfc') |
is(bry, "SpatialPolygonsDataFrame") |
is(bry, 'SpatialPolygons'))) {
stop("Only support sf or sp.")
}
}
if (is.null(path)) {
path <- getwd()
} else {
if (!dir.exists(path)) {
stop("Path does not exist!")
}
}
path <- file.path(path, "wc2.1")
dir.create(path, showWarnings = FALSE)
url_base <- "https://biogeo.ucdavis.edu/data/worldclim/v2.1/fut"
zip_name <- sprintf("%sm/wc2.1_%sm_%s_%s_%s_%s.zip",
res, res, var, gcm, ssp, interval)
url <- file.path(url_base, zip_name)
temp <- tempfile()
dl <- try(download.file(url, temp))
if (class(dl) == "try-error") {
Sys.sleep(10)
download.file(url, temp)
}
n <- ifelse(var == "bioc", 19, 12)
if (is.null(bry)) {
decompression <- system2(
"unzip",
args = c("-o", "-j", temp, sprintf("-d %s", path)),
stdout = TRUE)
if (grepl("Warning message", tail(decompression, 1))) {
print(decompression)
}; unlink(temp)
fname <- sprintf("wc2.1_%sm_%s_%s_%s_%s.tif",
res, var, gcm, ssp, interval)
fpath <- file.path(path, fname)
if (!file.exists(fpath)) stop('Fail to extract file.')
if (return_stack == TRUE) clip_imgs <- read_stars(fpath)
} else {
temp_path <- file.path(path, "global")
dir.create(temp_path, showWarnings = FALSE)
decompression <- system2(
"unzip",
args = c("-o", "-j", temp, sprintf("-d %s", temp_path)),
stdout = TRUE)
if (grepl("Warning message", tail(decompression, 1))) {
print(decompression)
}; unlink(temp)
fname <- sprintf("wc2.1_%sm_%s_%s_%s_%s.tif",
res, var, gcm, ssp, interval)
fpath <- file.path(temp_path, fname)
if (!file.exists(fpath)) stop('Fail to extract file.')
clip_imgs <- read_stars(fpath, RasterIO = list(bands = c(1:n)))
bry <- st_as_sf(bry) %>% st_make_valid()
clip_imgs <- st_crop(clip_imgs, bry)
rst_name <- paste(nm_mark, names(clip_imgs), sep = "_")
rst_path <- file.path(path, rst_name)
write_stars(clip_imgs, rst_path)
unlink(temp_path, recursive = TRUE)
if (return_stack != TRUE) rm(clip_imgs)
}
if (return_stack == TRUE) {
clip_imgs <- st_set_dimensions(
clip_imgs, 'band', values = paste0(var, 1:n))
clip_imgs
} else {
message(sprintf("Files are written to %s.", path))
}
} |
NULL
setClass("StringComparator",
slots = c(
ignore_case = "logical",
use_bytes = "logical"
),
prototype = structure(
.Data = function(x, y, ...) 0,
ignore_case = FALSE,
use_bytes = FALSE
),
contains = c("VIRTUAL", "SequenceComparator"),
validity = function(object) {
errs <- character()
if (length(object@ignore_case) != 1)
errs <- c(errs, "`ignore_case` must be a logical vector of length 1")
if (length(object@use_bytes) != 1)
errs <- c(errs, "`use_bytes` must be a logical vector of length 1")
ifelse(length(errs) == 0, TRUE, errs)
})
setMethod(elementwise, signature = c(comparator = "StringComparator", x = "vector", y = "vector"),
function(comparator, x, y, ...) {
xy = strings_to_code_vectors(x, y, ignore_case = comparator@ignore_case,
use_bytes = comparator@use_bytes)
elementwise(comparator, xy$x, xy$y, ...)
}
)
setMethod(pairwise, signature = c(comparator = "StringComparator", x = "vector", y = "vector"),
function(comparator, x, y, return_matrix, ...) {
xy = strings_to_code_vectors(x, y, ignore_case = comparator@ignore_case,
use_bytes = comparator@use_bytes)
pairwise(comparator, xy$x, xy$y, return_matrix, ...)
}
)
setMethod(pairwise, signature = c(comparator = "StringComparator", x = "vector", y = "NULL"),
function(comparator, x, y, return_matrix, ...) {
xy = strings_to_code_vectors(x, y = NULL, ignore_case = comparator@ignore_case,
use_bytes = comparator@use_bytes)
pairwise(comparator, xy$x, NULL, return_matrix, ...)
}
) |
ISOPresentationForm <- R6Class("ISOPresentationForm",
inherit = ISOCodeListValue,
private = list(
xmlElement = "CI_PresentationFormCode",
xmlNamespacePrefix = "GMD"
),
public = list(
initialize = function(xml = NULL, value, description = NULL){
super$initialize(xml = xml, id = private$xmlElement, value = value,
description = description)
}
)
)
ISOPresentationForm$values <- function(labels = FALSE){
return(ISOCodeListValue$values(ISOPresentationForm, labels))
} |
ciu.textual <- function(ciu, instance=NULL, ind.inputs=NULL, ind.output=1,
in.min.max.limits=NULL,
n.samples=100, neutral.CU=0.5,
show.input.values=TRUE, concepts.to.explain=NULL,
target.concept=NULL, target.ciu=NULL,
ciu.meta = NULL,
sort="CI", n.features = NULL,
use.text.effects = FALSE,
CI.voc = data.frame(limits=c(0.2,0.4,0.6,0.8,1.0),
texts=c("not important","slightly important",
"important","very important","extremely important")),
CU.voc = data.frame(limits=c(0.2,0.4,0.6,0.8,1.0),
texts=c("very bad","bad","average","good","very good"))) {
if ( !is.null(target.concept) ) {
if ( is.null(target.ciu) ) {
if ( inherits(ciu, "CIU") )
ciu.tmp <- ciu$as.ciu()
else
ciu.tmp <- ciu
ind.inps <- ciu.tmp$vocabulary[target.concept][[1]]
target.ciu <- ciu.explain(ciu, instance, ind.inputs.to.explain=ind.inputs, in.min.max.limits=in.min.max.limits,
n.samples=n.samples*10)
}
}
if ( is.null(ciu.meta) ) {
ciu.meta <- ciu.meta.explain(ciu, instance, ind.inputs=ind.inputs, in.min.max.limits=in.min.max.limits,
n.samples=n.samples, concepts.to.explain=concepts.to.explain,
target.concept=target.concept, target.ciu=target.ciu)
}
else {
instance <- ciu.meta$instance
}
ciu <- ciu.meta$ciu
inst.name <- rownames(instance)
ind.inputs <- ciu.meta$ind.inputs
inp.names <- ciu.meta$inp.names
ciu.text <-ciu.list.to.frame(ciu.meta$ciuvals, ind.output)
ciu.text$ind.inputs <- ind.inputs
ciu.text$inp.names <- inp.names
ciu.text$CI.text <- ciu.values.to.text(ciu.text$CI, CI.voc)
ciu.text$CU.text <- ciu.values.to.text(ciu.text$CU, CU.voc)
if ( sort == "CI")
ciu.text <- ciu.text[order(ciu.text$CI, decreasing = TRUE),]
else if ( sort == "CU" )
ciu.text <- ciu.text[order(ciu.text$CU, decreasing = TRUE),]
if ( is.null(n.features) )
n.features <- nrow(ciu.text)
else
n.features <- min(n.features, nrow(ciu.text))
if (is.null(target.concept) ) {
outval <- ciu.text$outval[ind.output]
abs.min.max <- ciu$abs.min.max;
amin <- abs.min.max[ind.output,1]; amax <- abs.min.max[ind.output,2]
out.CU <- (outval - amin)/(amax - amin)
out.CU.text <- ciu.values.to.text(out.CU, CU.voc)
}
else {
out.CU <- target.ciu[ind.output,"CU"]
out.CU.text <- ciu.values.to.text(out.CU, CU.voc)
}
if (use.text.effects) out.CU.text <- crayon::bold(out.CU.text)
if (is.null(target.concept) ) {
t <- paste0("The value of output '", ciu$output.names[ind.output], "' for instance '", inst.name)
t <- paste0(t, "' is ", round(outval,3), ", which is ", out.CU.text, " (CU=", round(out.CU,3), ").\n")
}
else {
t <- paste0("The value of intermediate concept '", target.concept, "' for output '",
ciu$output.names[ind.output], "', with instance '", inst.name,
"' is ", out.CU.text, " (CU=", round(out.CU,3), ").\n")
}
for ( i in 1:n.features ) {
ci.text <- ciu.text$CI.text[i]; if (use.text.effects) ci.text <- crayon::bold(ci.text)
cu.text <- ciu.text$CU.text[i]; if (use.text.effects) cu.text <- crayon::bold(cu.text)
fvalue <- instance[1, ciu.text$ind.inputs[i]]
if ( is.null(ciu.meta$ind.inputs) ) {
inds <- ciu$vocabulary[ciu.text$inp.names[i]][[1]]
if ( length(inds) == 1 )
fvalue <- instance[1, inds]
}
t <- paste0(t, "Feature '", ciu.text$inp.names[i], "' is ", ci.text,
" (CI=", round(ciu.text$CI[i],3), ") and value ")
if ( length(fvalue) >= 1 )
t <- paste0(t, "'", fvalue, "' ")
t <- paste0(t, "is ", cu.text, " (CU=",
round(ciu.text$CU[i],3), ").\n")
}
return(t)
}
ciu.values.to.text <- function(values, voc) {
res <- as.character(matrix(voc$texts[1], nrow = length(values)))
for ( limit.ind in 2:length(voc$limits) ) {
res[values > voc$limits[limit.ind-1] & values <= voc$limits[limit.ind]] <- voc$texts[limit.ind]
}
return(res)
} |
classify_labels <- function(df_final){
length_df <- dim(df_final)[1]
classlabel <- as.character(length_df)
for(i in 1:length_df){
if (df_final[i, "Model"] == "ARIMA") {
ar_coef <- as.numeric(as.character(df_final[i, "p"]))
num_diff <- as.numeric(as.character(df_final[i, "d"]))
ma_coef <- as.numeric(as.character(df_final[i, "q"]))
arma <- sum(ar_coef, ma_coef)
drift <- as.numeric(df_final[i, "outcome_with_drift"] == 1)
if (arma!=0 & num_diff== 0){
classlabel[i] <- "ARMA/AR/MA"
} else
classlabel[i] <- "ARIMA"
} else if(df_final[i, "Model"] == "ETS"){
error <- as.character(df_final[i, "p"])
trend <- as.character(df_final[i, "d"])
seasonality <- as.character(df_final[i, "q"])
if(error== "A" & trend== "A" & seasonality== "A") {
classlabel[i] <- "ETS-trendseasonal"
} else if (error== "A" & trend== "A" & seasonality== "N") {
classlabel[i] <- "ETS-trend"
} else if (error== "A" & trend== "Ad" & seasonality== "A"){
classlabel[i] <- "ETS-dampedtrendseasonal"
}else if (error== "A" & trend== "Ad" & seasonality== "N"){
classlabel[i] <- "ETS-dampedtrend"
}else if (error== "A" & trend== "N" & seasonality== "A"){
classlabel[i] <- "ETS-seasonal"
} else if (error== "A" & trend== "N" & seasonality== "N"){
classlabel[i] <- "ETS-notrendnoseasonal"
}else if (error== "M" & trend== "A" & seasonality== "A"){
classlabel[i] <- "ETS-trendseasonal"
} else if (error== "M" & trend== "A" & seasonality== "M"){
classlabel[i] <- "ETS-trendseasonal"
} else if (error== "M" & trend== "A" & seasonality== "N"){
classlabel[i] <- "ETS-trend"
}else if (error== "M" & trend== "Ad" & seasonality== "A"){
classlabel[i] <- "ETS-dampedtrendseasonal"
}else if (error== "M" & trend== "Ad" & seasonality== "M"){
classlabel[i] <- "ETS-dampedtrendseasonal"
}else if (error== "M" & trend== "Ad" & seasonality== "N"){
classlabel[i] <- "ETS-dampedtrend"
}else if (error== "M" & trend== "N" & seasonality== "A"){
classlabel[i] <- "ETS-seasonal"
}else if (error== "M" & trend== "N" & seasonality== "M"){
classlabel[i] <- "ETS-seasonal"
}else
classlabel[i] <- "ETS-notrendnoseasonal"
} else {
classlabel[i] <- df_final[i, "Model"]
}
}
return(classlabel)
} |
MGC_Function_refClass <- setRefClass("MGC_Function",
fields = list(
dimension = "numeric",
density = "function",
center= "function",
parameter = "function",
shape = "function"
),
methods = list(
initialize = function(den, cen, par, sha) {
dimension <<- length(cen(1))
density <<- den
center <<- cen
parameter <<- par
shape <<- sha
.self
}
),
)
MGC_Function_refClass$methods(
get_attributes = function(time, attributes=NULL) {
att <- list(density = density(time), parameter=parameter(time),
center = center(time))
if(!is.null(attributes)) att <- att[attributes]
att
},
get_points = function(time) {
shape(center=center(time), parameter=parameter(time))
}
)
MGC_Function<- function(density, center, parameter, shape = NULL) {
if(is.null(shape)) shape <- MGC_Shape_Gaussian
structure(list(description = "Functional Moving Generator Cluster",
RObj = MGC_Function_refClass$new(den = density, cen = center,
par = parameter, sha = shape)),
class = c("MGC_Function","MGC"))
} |
dataSim <- function(replicates,sites,treatment,percentage=10,effect=25,
alpha=0.4,beta=0.5,theta=10,
covariates=NULL,sample.ids=NULL,assembly="hg18",
context="CpG",add.info=FALSE){
if(length(treatment) != replicates){
stop("treatment must be of same length as requested number of replicates")}
if(!is.null(covariates)){
if(nrow(covariates)!=replicates){
stop("nrow(covariates) must be equal to replicates")}
}
if (replicates < 1) {
stop("number of replicates has to be >= 1.")
}
if(replicates == 1){
warning("single replicate methylBase cannot be used downstream.")
}
if (!is.null(sample.ids)) {
if (length(sample.ids) != replicates) {
stop("sample.ids must be of same length as requested number of replicates")
}
} else {
sample.ids <-
ifelse(treatment == 1,
paste0("test", cumsum(treatment)),
paste0("ctrl", cumsum(!treatment)))
}
raw <- matrix(ncol=replicates*3,nrow=sites)
index<-seq(1,replicates*3,by=3)
x <- rbeta(sites,alpha,beta)
treatment_indices<-sample((1:sites)[x < (1-(effect/100))],
size=sites*(percentage/100))
covariate_indices<-sample(1:sites,size=sites*0.05)
addinfo<-rep(0,sites)
effects <- if(length(effect)==1) rep(effect,length(x)) else sample(effect,
length(x),replace=TRUE)
for(i in 1:replicates){
coverage <- rnbinom(sites,1,0.01)
coverage <- ifelse(coverage<10,10,coverage)
raw[,index[i]] <- coverage
raw[,index[i]+1] <- ceiling(coverage * rbetabinom(n=sites,prob=x,
size=50,theta=theta)/50)
if(treatment[i]==1){
y<-x+(effects/100)
ifelse(y>1,1-x,effect)
addinfo<-ifelse(y>1,1-x,effect)
addinfo[-treatment_indices]<-0
y<-ifelse(y>1,1,y)
raw[treatment_indices,index[i]+1] <-
ceiling(coverage[treatment_indices] * rbetabinom(
n=length(treatment_indices),prob=y[treatment_indices],
size=50,theta=theta)/50)
}
if(!is.null(covariates[i,,drop=FALSE])){
raw[covariate_indices,index[i]+1] <-
ceiling(coverage[covariate_indices] * rbetabinom(
n=length(covariate_indices),
prob=influence(p=x[covariate_indices],
x=rep(covariates[i,],
times=length(covariate_indices))),
size=50,theta=theta)/50)
}
raw[,index[i]+2] <- coverage - raw[,index[i]+1]
}
df<-raw
df=as.data.frame(df)
info<-data.frame(chr=rep("chr1",times=sites),start=1:sites,
end=2:(sites+1),strand=rep("+",times=sites))
df<-cbind(info,df)
coverage.ind=seq(5,by=3,length.out=replicates)
numCs.ind =coverage.ind+1
numTs.ind =coverage.ind+2
names(df)[coverage.ind]=paste(c("coverage"),1:replicates,sep="" )
names(df)[numCs.ind] =paste(c("numCs"),1:replicates,sep="" )
names(df)[numTs.ind] =paste(c("numTs"),1:replicates,sep="" )
obj=new("methylBase",(df),sample.ids=sample.ids,
assembly=assembly,context=context,treatment=treatment,
coverage.index=coverage.ind,numCs.index=numCs.ind,numTs.index=numTs.ind,
destranded=FALSE,resolution="base")
if(add.info==FALSE){
obj
}
else{
addinfo=treatment_indices
list(obj,addinfo)
}
}
influence <- function(p,x=NULL,b0=0.1,b1=0.1,k=100){
if(is.null(x)){
p<-p
}
else{
y <- exp(b0 + b1*x) / (k + exp(b0 + b1*x))
p <- (p+y)/2
}
} |
FractalSegment <- function(P1, P2, angle, cut1, cut2, f, it){
if (it==0){
DrawSegmentPoints(P1, P2, "black")
}
if (it>0){
P11=P1+cut1*(P2-P1)
P12=P1+cut2*(P2-P1)
angle=(pi*angle)/180
xx=P11[1]
yy=P11[2]
x_fixed=P12[1]
y_fixed=P12[2]
xx_new=f*(xx-x_fixed)*cos(-angle)-f*(yy-y_fixed)*sin(-angle)+x_fixed
yy_new=f*(xx-x_fixed)*sin(-angle)+f*(yy-y_fixed)*cos(-angle)+y_fixed
if ((180*angle)/pi<=60 | ((180*angle)/pi>300 & (180*angle)/pi<=360)){P31=c(xx_new, yy_new)}
if ((180*angle)/pi>60 & (180*angle)/pi<=300){P32=c(xx_new, yy_new)}
xx=P12[1]
yy=P12[2]
x_fixed=P11[1]
y_fixed=P11[2]
xx_new=f*(xx-x_fixed)*cos(angle)-f*(yy-y_fixed)*sin(angle)+x_fixed
yy_new=f*(xx-x_fixed)*sin(angle)+f*(yy-y_fixed)*cos(angle)+y_fixed
if ((180*angle)/pi<=60 | ((180*angle)/pi>300 & (180*angle)/pi<=360)){P32=c(xx_new, yy_new)}
if ((180*angle)/pi>60 & (180*angle)/pi<=300){P31=c(xx_new, yy_new)}
angle=(180*angle)/pi
K1=FractalSegment(P1, P11, angle, cut1, cut2, f, it-1)
K2=FractalSegment(P11, P31, angle, cut1, cut2, f, it-1)
K3=FractalSegment(P31, P32, angle, cut1, cut2, f, it-1)
K4=FractalSegment(P32, P12, angle, cut1, cut2, f, it-1)
K5=FractalSegment(P12, P2, angle, cut1, cut2, f, it-1)
}
} |
downloadSource <- function(type,subtype=NULL,overwrite=FALSE) {
argumentValues <- as.list(environment())
startinfo <- toolstartmessage(argumentValues, "+")
on.exit(toolendmessage(startinfo,"-"))
if(!all(is.character(type)) || length(type)!=1) stop("Invalid type (must be a single character string)!")
if(!is.null(subtype) && (!all(is.character(subtype)) || length(subtype)!=1)) stop("Invalid subtype (must be a single character string)!")
functionname <- prepFunctionName(type = type,
prefix = "download",
ignore = ifelse(is.null(subtype), "subtype", NA))
if(!grepl("subtype=subtype",functionname,fixed=TRUE)) subtype <- NULL
cwd <- getwd()
on.exit(setwd(cwd), add = TRUE)
if(!file.exists(getConfig("sourcefolder"))) dir.create(getConfig("sourcefolder"), recursive = TRUE)
typesubtype <- paste(c(make.names(type),make.names(subtype)),collapse="/")
setwd(getConfig("sourcefolder"))
if(file.exists(typesubtype)) {
if(overwrite) {
unlink(typesubtype,recursive = TRUE)
} else {
stop("Source folder for source \"",typesubtype,"\" does already exist! Delete folder or activate overwrite to proceed!")
}
}
dir.create(typesubtype, recursive = TRUE)
setwd(typesubtype)
on.exit(if(length(dir())==0) unlink(getwd(), recursive = TRUE), add=TRUE, after = FALSE)
meta <- eval(parse(text=functionname))
mandatory <- c("url","author","title","license","description","unit")
if(!all(mandatory %in% names(meta))) {
vcat(0, "Missing entries in the meta data of function '", functionname[1], "': ",
toString(mandatory[!mandatory %in% names(meta)]))
}
reserved <- c("call","accessibility")
if(any(reserved %in% names(meta))) {vcat(0, "The following entries in the meta data of the function '",functionname[1],"' are reserved and will be overwritten: ",reserved[reserved %in% names(meta)])}
meta$call <- list(origin = paste0(gsub("\\s{2,}", " ", paste(deparse(match.call()),collapse="")),
" -> ", functionname, " (madrat ", unname(getNamespaceVersion("madrat")),
" | ", attr(functionname, "pkgcomment"), ")"),
type = type,
subtype = ifelse(is.null(subtype), "none",subtype),
time = format(Sys.time(),"%F %T %Z"))
meta$accessibility <- ifelse(!is.null(meta$doi),"gold","silver")
preferred_order <- c("title","description","author","doi","url","accessibility","license","version","release_date","unit","call","reference")
order <- c(intersect(preferred_order,names(meta)),setdiff(names(meta),preferred_order))
write_yaml(meta[order],"DOWNLOAD.yml")
} |
bandwidth_cross_validation<-function( r, m, x, H, link = c( "logit" ),
guessing = 0, lapsing = 0, K = 2,
p = 1, ker = c( "dnorm" ), maxiter = 50,
tol = 1e-6, method = c( "all" ) ) {
ISE <- function( f1, f2 ) {
return( sum( ( f1 - f2 )^2 ) );
}
get_ise_p <- function( h ) {
fest <- NULL;
for( i in 1:Lx ) {
fest[i] <- locglmfit( x[i], r[-i], m[-i], x[-i], h, FALSE,
link, guessing, lapsing, K, p, ker, maxiter, tol )$
pfit;
}
return( ISE( r / m, fest ) );
}
get_ise <- function( h ) {
fest <- NULL;
for( i in 1:Lx ) {
fest[i] <- locglmfit( x[i], r[-i], m[-i], x[-i], h, FALSE,
link, guessing, lapsing, K, p, ker, maxiter, tol )$
etafit;
}
fit <- ( r + .5 ) / ( m + 1 );
fit_eta <- linkfun( fit )
return( ISE( fit_eta, fest ) );
}
get_dev <- function( h ) {
fest <- NULL;
for( i in 1:Lx ) {
fest[i] <- locglmfit( x[i], r[-i], m[-i], x[-i], h, FALSE,
link, guessing, lapsing, K, p, ker, maxiter, tol )$
pfit;
}
return( deviance2( r, m, fest ) );
}
if( missing("r") || missing("m") || missing("x") || missing("H") ) {
stop("Check input. First 4 arguments are mandatory");
}
checkdata<-list();
checkdata[[1]] <- x;
checkdata[[2]] <- r;
checkdata[[3]] <- m;
checkinput( "psychometricdata", checkdata );
rm( checkdata )
checkinput( "minmaxbandwidth", H );
checkinput( "linkfunction", link );
if( length( guessing ) > 1 ) {
stop( "guessing rate must be scalar" );
}
if( length( lapsing ) > 1 ) {
stop( "lapsing rate must be scalar" );
}
checkinput( "guessingandlapsing", c( guessing, lapsing ) );
checkinput( "guessingandlapsing", c( guessing, lapsing ) );
if (link == "weibull" || link == "revweibull"){
checkinput( "exponentk", K );
}
pn <- list()
pn[[1]] <- p
pn[[2]] <- x
checkinput( "degreepolynomial", pn );
checkinput( "kernel", ker );
checkinput( "maxiter", maxiter );
checkinput( "tolerance", tol );
checkinput( "method", method );
LH = length(H);
Lx = length(x);
if( link == "logit" ||
link == "probit" ||
link == "loglog" ||
link == "comploglog" ||
link == "weibull" ||
link == "revweibull" ) {
LINK <- paste( link, "_link_private", sep = "" );
}else{
LINK <- link
}
if( LINK != "weibull_link_private" && LINK != "revweibull_link_private" ) {
linkuser <- eval( call( LINK, guessing, lapsing ) );
}
else{
linkuser <- eval( call( LINK, K, guessing, lapsing ) );
}
linkfun <- linkuser$linkfun;
warn.current <- getOption("warn")
on.exit(options(warn = warn.current));
options(warn=-1)
h <- NULL;
if( method == "ISE" ) {
h <- optimize( get_ise_p, lower = H[1], upper = H[2] )$minimum;
}
else {
if ( method == "ISEeta") {
h <- optimize( get_ise, lower = H[1], upper = H[2] )$minimum;
}
else {
if( method == "likelihood" ) {
h <- optimize( get_dev, lower = H[1], upper = H[2] )$minimum;
}
else {
h$pscale <- optimize( get_ise_p, lower = H[1], upper = H[2]
)$minimum;
h$etascale <- optimize( get_ise, lower = H[1], upper = H[2]
)$minimum;
h$deviance <- optimize( get_dev, lower = H[1], upper = H[2]
)$minimum;
}
}
}
return( h );
} |
inputBottleSim <-
function(datafile, ndigit=3)
{
input=read.delim(file=datafile, sep='\r')
noext= gsub("[.].*$","",datafile)
popcount=rbind(which(input == 'pop', arr.ind=T),which(input=='Pop',arr.ind=T),which(input=='POP',arr.ind=T))
popcount=popcount[,1]
npops=NROW(popcount)
popcount=sort(popcount)
nloci=popcount[1]-1
popsizes=vector(length=npops)
for (h in 1:npops)
{
if (h<npops) popsizes[h]=popcount[h+1]-popcount[h]-1
if (h==npops) popsizes[h]=nrow(input)-popcount[h]
}
n.individuals=sum(popsizes)
bottlesim=matrix(NA, n.individuals+3, nloci*2+1)
bottlesim[1,1]=n.individuals
bottlesim[2,1]=nloci
for (a in 1:nloci){bottlesim[3,a]=as.character(input[a,])}
input2=input[-popcount,]
input3=input2[-(1:nloci)]
for (b in 1:n.individuals)
{
inddata=input3[b]
inddata=as.vector(inddata)
indID= gsub("[ ]","",inddata)
indID= gsub("[\t]|[,].*$","",indID)
bottlesim[(3+b),1]=substr(indID,1,9)
inddata=gsub( "[^[:alnum:]]", "", inddata)
total=nchar(inddata)
diff=total-(ndigit*2*nloci)
for (x in 1:nloci)
{
bottlesim[(3+b),(1+((2*x)-1))]=substr(inddata,diff+(2*ndigit*(x-1))+(ndigit-(ndigit-1)), diff+(2*ndigit*(x-1))+ndigit)
bottlesim[(3+b),(1+(2*x))]=substr(inddata,diff+(2*ndigit*(x-1))+ndigit+1, diff+(2*ndigit*(x-1))+(2*ndigit))
}
}
if (ndigit==2) missing='00'
if (ndigit==3) missing='000'
for (r in 1:nrow(bottlesim))
{
for (c in 1:ncol(bottlesim))
{
if (is.na(bottlesim[r,c])==T) bottlesim[r,c]=''
}
}
for (x in 1:nrow(bottlesim))
{
for (y in 1:ncol(bottlesim))
{
if (bottlesim[x,y]==missing) bottlesim[x,y]='?'
}}
bottlesim2=bottlesim
alleles.bsim=c(0,1,2,3,4,5,6,7,8,9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')
final.vec=NULL
kvec=rep(NA,times=nloci)
for (i in 1:nloci)
{
alleles=bottlesim[4:(nrow(bottlesim)),(i*2):((i*2)+1)]
alleles=as.vector(alleles)
vec=unique(alleles)
if (length(which(vec[]=='?')>0)) vec=vec[-which(vec[]=='?')]
kvec[i]=length(vec)
sort.vec=sort(vec)
for (j in 1:kvec[i])
{
for (x in 4:(nrow(bottlesim)) )
{
for (y in (i*2):((i*2)+1))
{
if (bottlesim[x,y]==sort.vec[j]) bottlesim2[x,y] = alleles.bsim[j]
}}}
final.vec=c(final.vec,sort.vec)
}
filename=paste(noext,'_Bsim.txt',sep='')
write.table(bottlesim2, file=filename, quote=F, row.names=F, col.names=F, sep='\t')
save(final.vec, kvec, file='alleles')
return(list('final.vec'=final.vec, 'kvec'=kvec))
} |
ensuredim <- function (x){
if (is.null (dim (x)))
x <- structure (x, .Dim = length (x),
.Dimnames = lon (list (names (x))),
.Names = NULL)
x
}
.test (ensuredim) <- function (){
checkEquals (ensuredim (v), structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c"))))
checkEquals (ensuredim (as.numeric (v)), structure(1:3, .Dim = 3L))
checkEquals (ensuredim (m), m)
checkEquals (ensuredim (a), a)
}
drop1d <- function (x, drop = TRUE){
if (drop && ndim (x) == 1)
x <- structure (x, .Dim = NULL, .Dimnames = NULL, .Names = dimnames (x)[[1]])
x
}
.test (drop1d) <- function () {
checkEquals (drop1d (a), a)
checkEquals (drop1d (m), m)
checkEquals (drop1d (v), v)
checkEquals (drop1d (ensuredim (v)), v)
checkEquals (drop1d (ensuredim (v), drop = FALSE), ensuredim (v))
} |
context("oai")
test_that("gbif_oai_identify", {
vcr::use_cassette("gbif_oai_identify", {
tt <- gbif_oai_identify()
}, preserve_exact_body_bytes = TRUE)
expect_is(tt, "list")
expect_is(tt$repositoryName, "character")
expect_equal(tt$repositoryName, "GBIF Registry")
})
test_that("gbif_oai_list_metadataformats", {
vcr::use_cassette("gbif_oai_list_metadataformats", {
tt <- gbif_oai_list_metadataformats()
})
expect_is(tt, "data.frame")
expect_is(tt$metadataPrefix, "character")
expect_named(tt, c('metadataPrefix', 'schema', 'metadataNamespace'))
})
test_that("gbif_oai_list_sets", {
vcr::use_cassette("gbif_oai_list_sets", {
tt <- gbif_oai_list_sets()
}, preserve_exact_body_bytes = TRUE)
expect_is(tt, "data.frame")
expect_is(tt$setSpec, "character")
expect_named(tt, c('setSpec', 'setName'))
})
test_that("gbif_oai_list_identifiers", {
vcr::use_cassette("gbif_oai_list_identifiers", {
tt <- gbif_oai_list_identifiers(from = "2017-01-15", until = "2017-01-30")
})
expect_is(tt, "data.frame")
expect_is(tt$setSpec, "character")
})
test_that("gbif_oai_get_records", {
vcr::use_cassette("gbif_oai_get_records", {
tt <- gbif_oai_get_records("9c4e36c1-d3f9-49ce-8ec1-8c434fa9e6eb")
}, preserve_exact_body_bytes = TRUE)
expect_is(tt, "list")
expect_is(tt[[1]], "list")
expect_is(tt[[1]]$header, "data.frame")
expect_is(tt[[1]]$metadata, "data.frame")
expect_equal(length(tt), 1)
expect_is(tt[[1]]$header$identifier, "character")
expect_equal(tt[[1]]$header$identifier, "9c4e36c1-d3f9-49ce-8ec1-8c434fa9e6eb")
expect_is(tt[[1]]$metadata$title, "character")
expect_equal(tt[[1]]$metadata$title, "Freshwater fishes of Serbia and Montenegro")
}) |
.onLoad <- function(lib, pkg){
Rdpack::Rdpack_bibstyles(package = pkg, authors = "LongNames")
invisible(NULL)
}
multiple_breakpoints <- function(data, number_bp = "Unknown", max_bp = 80,
inf_crit = "BIC", ext_out = "TRUE") {
stopifnot("data must be a vector, matrix or data frame" =
(is.vector(data) | is.data.frame(data) |
is.matrix(data)) & !is.list(data))
stopifnot("inf_crit must be AIC, BIC or HQC" = inf_crit %in% c("AIC", "BIC",
"HQC"))
if (is.vector(data)) {
data <- cbind(seq_len(length(data)), data)
}
if (is.data.frame(data)) {
data <- as.matrix(data)
if (ncol(data) == 1) data <- cbind(seq_len(length(data)), data)
}
if (is.matrix(data)) {
stopifnot("Vector respectively second column of matrix or data frame is not
binary" = all(sort(unique(data[, 2])) == c(0, 1)))
if (dim(data)[2] == 1) {
data <- cbind(seq_len(length(data)), data)
}
data <- data[order(data[, 1]), ]
number <- nrow(data)
data2 <- data
colnames(data) <- c("V1", "V2")
data <- as.matrix(cbind(aggregate(V2 ~ V1, data = data, sum),
aggregate(V2 ~ V1, data = data, length)[, 2]))
data <- cbind(data, 1 / number *
cumsum((data[, 2] - data[, 3] *
mean(data2[, 2])) / sd(data2[, 2])))
if (ext_out == TRUE) {
dataexport <- data[, 1]
}
l <- limit <- correction <- 0
stand_dev <- 1
estimate <- safe_index <- ic <- numeric()
loglik <- sum(data[, 2]) * log(mean(data2[, 2])) +
(sum(data[, 3]) - sum(data[, 2])) * log(1 - mean(data2[, 2]))
ic <- - 2 * loglik
q <- 2
estimate[1] <- -Inf
group <- vector(mode = "list")
if (number_bp == "Unknown") {
number_bp <- max_bp
}
while (limit < number_bp) {
l <- l + 1
correction <- correction - 1
group <- group2 <- vector(mode = "list")
estimate[length(estimate) + 1] <- data[which.max(abs(data[, 4])), 1]
estimatesort <- c(sort(estimate), Inf)
border <- which(data[, 1] <=
estimatesort[which(estimate[length(estimate)] ==
estimatesort) + 1] &
data[, 1] >
estimatesort[which(estimate[length(estimate)] ==
estimatesort) - 1])
if (((quantile(abs(data[border, 4]), type = 1, probs = 0.85) >=
max(abs(data[, 4])) * 0.95) & length(data[border, 4]) >= 20) &
max(abs(data[, 4])) > 0) {
safe_index <- c(safe_index, length(estimate))
correction <- 3
} else{
if (length(safe_index) > 0) {
estimate <- estimate[-safe_index]
estimatesort <- c(sort(estimate), Inf)
safe_index <- numeric()
}
loglik <- numeric()
for (i in 2:length(estimatesort)) {
group[[i - 1]] <-
matrix(c(data[data[, 1] <= estimatesort[i] &
data[, 1] > estimatesort[i - 1], 2:3]),
ncol = 2)
if (sum(group[[i - 1]][, 1]) == 0 | sum(group[[i - 1]][, 1]) ==
sum(group[[i - 1]][, 2])) {
loglik[i - 1] <- 0
} else {
loglik[i - 1] <- sum(group[[i - 1]][, 1]) *
log(weighted.mean(group[[i - 1]][, 1] / group[[i - 1]][, 2],
group[[i - 1]][, 2])) +
(sum(group[[i - 1]][, 2]) - sum(group[[i - 1]][, 1])) *
log(1 - weighted.mean(group[[i - 1]][, 1] /
group[[i - 1]][, 2],
group[[i - 1]][, 2]))
}
}
if (inf_crit == "BIC") {
ic <- c(ic, - 2 * sum(loglik) + log(number) *
(length(estimate) - 1))
} else if (inf_crit == "HQC") {
ic <- c(ic, - 2 * sum(loglik) + 2 * (length(estimate) - 1) *
log(log(number)))
} else if (inf_crit == "AIC") {
ic <- c(ic, - 2 * sum(loglik) + 2 * (length(estimate) - 1))
}
if (number_bp >= max_bp) {
if (ic[length(ic)] > ic[length(ic) - 1] & (correction < 1)) {
limit <- Inf
} else {
limit <- limit + 1
if (ext_out == TRUE) {
dataexport <- cbind(dataexport, data[, 4])
}
}
correction <- 0
} else {
limit <- limit + 1
if (ext_out == TRUE) {
dataexport <- cbind(dataexport, data[, 4])
}
}
}
vektor <- numeric()
stand_dev <- vector(mode = "list")
for (j in 2:length(estimatesort)) {
group[[j - 1]] <-
matrix(c(data[data[, 1] <= estimatesort[j] &
data[, 1] > estimatesort[j - 1], 2:3]),
ncol = 2)
group2[[j - 1]] <- c(data2[data2[, 1] <= estimatesort[j] &
data2[, 1] > estimatesort[j - 1], 2])
if (sum(group[[j - 1]][, 2]) > 1) {
stand_dev[[j - 1]] <- sd(group2[[j - 1]])
if (stand_dev[[j - 1]] == 0) {
stand_dev[[j - 1]] <- 1
}
} else {
stand_dev[[j - 1]] <- 1
}
vektor <-
c(vektor,
1 / number * cumsum((group[[j - 1]][, 1] - group[[j - 1]][, 2] *
weighted.mean(group[[j - 1]][, 1] /
group[[j - 1]][, 2],
group[[j - 1]][, 2])) /
stand_dev[[j - 1]]))
}
data <- cbind(data[, 1:3], round(vektor, 12))
q <- q + 1
}
if (limit == Inf) {
estimate <- estimate[-length(estimate)]
}
colnames(data) <- c("X", "Y", paste("S_n", 1:(ncol(data) - 2)))
success <- numeric()
estimatesort <- c(sort(estimate), Inf)
for (i in 2:length(estimatesort)) {
group[[i - 1]] <-
matrix(c(data[data[, 1] <= estimatesort[i] &
data[, 1] > estimatesort[i - 1], 2:3]),
ncol = 2)
success[i - 1] <- sum(group[[i - 1]][, 1]) / sum(group[[i - 1]][, 2])
}
if (ext_out == TRUE) {
output <- c(list(Breakpoints = sort(estimate[-1]),
Probabilities = success,
ic = ic, S = dataexport))
names(output)[3] <- inf_crit
class(output) <- c("mBP")
print(output[1:3])
return(invisible(output))
} else {
output <- c(list(Breakpoints = sort(estimate[-1]),
Probabilities = success, ic = ic))
names(output)[3] <- inf_crit
class(output) <- c("mBP")
return(output)
}
}
}
plot.mBP <- function(x, ask = TRUE, ...) {
stopifnot("Plot cannot be drawn. Set ext_out argument to TRUE in
multiple_breakpoints command" = length(x) != 3)
devAskNewPage(ask = ask)
if (length(dim(x[[4]])) != 0) {
old_par <- par("mar")
par(mar = c(4.5, 5, 2.5, 0))
par(omd = c(0, 0.8, 0, 1))
if (dim(x[[4]])[2] >= 3) {
plot(x[[4]][, 1], x[[4]][, 2],
ylim = c(1.1 * min(x[[4]][, -1]), 1.1 * max(x[[4]][, -1])),
xlab = "x", ylab = expression(paste(S[n]^(m), "(x)", sep = "")),
type = "l")
points(c(min(x[[4]][, 1]), max(x[[4]][, 1])), c(0, 0),
type = "l", lty = "dashed")
location <- which.max(abs(x[[4]][, 2]))
segments(x[[4]][location, 1], 0, x1 = x[[4]][location, 1],
y1 = x[[4]][location, 2], lty = "dashed")
for (i in 3:ncol(x[[4]])) {
points(x[[4]][, 1], x[[4]][, i], col = i - 1, type = "l")
location <- which.max(abs(x[[4]][, i]))
segments(x[[4]][location, 1], 0, x1 = x[[4]][location, 1],
y1 = x[[4]][location, i], col = i - 1, lty = "dashed")
}
legend(par("usr")[2], par("usr")[4], xpd = NA,
legend = paste("m=", 1:(ncol(x[[4]]) - 1), sep = ""),
col = 1:(ncol(x[[4]]) - 1), lty = rep(1, (ncol(x[[4]]) - 1)),
bty = "n", title = "Step")
} else {
plot(x[[4]][, 1], x[[4]][, 2], ylim = c(1.1 * min(x[[4]][, -1]),
1.1 * max(x[[4]][, -1])),
xlab = "x", ylab = expression(paste(S[n]^m, "(x)", sep = "")),
type = "l")
points(c(min(x[[4]][, 1]), max(x[[4]][, 1])), c(0, 0),
type = "l", lty = "dashed")
location <- which.max(abs(x[[4]][, 2]))
segments(x[[4]][location, 1], 0, x1 = x[[4]][location, 1],
y1 = x[[4]][location, 2], lty = "dashed")
legend(par("usr")[2], par("usr")[4], xpd = NA,
legend = paste("m=", 1, sep = ""), col = 1, lty = 1, bty = "n",
title = "Step")
}
}
par(mar = c(4.5, 5, 2.5, 1))
if (length(x[[1]]) == 0) {
plot(0, xlab = "x", ylab = "Succes Probability",
ylim = c(0, 1.1 * x[[2]]), xlim = c(0, 1), type = "n")
points(0:1, rep(x[[2]], 2), type = "l")
} else {
if (length(x[[1]]) > 1) {
x_range <- range(x[[1]])
} else {
x_range <- c(0.95 * x[[1]], 1.05 * x[[1]])
}
add_to_x_range <- 0.05 * diff(x_range)
xvec <- c(x_range[1] - add_to_x_range, rep(x[[1]], each = 2),
x_range[2] + add_to_x_range)
yvec <- rep(x[[2]], each = 2)
par(las = 1)
plot(0, xlab = "Breakpoints", ylab = "Succes Probability",
ylim = c(0, max(1.1 * x[[2]])), xlim = c(min(xvec), max(xvec)),
type = "n", xaxt = "n", yaxt = "n")
axis(1, at = x[[1]], labels = round(x[[1]], 3))
axis(2, at = x[[2]], labels = round(x[[2]], 3))
for (i in seq(1, (length(xvec) - 1), by = 2)) {
points(xvec[i:(i + 1)], yvec[i:(i + 1)], type = "l")
}
for (i in seq(2, (length(xvec) - 1), by = 2)) {
points(xvec[i:(i + 1)], c(0, max(yvec[i:(i + 1)])),
type = "l", lty = "dotted")
}
}
par(mar = old_par, las = 0, ask = FALSE)
} |
attitude <- data.frame(
rating = c(43, 63, 71, 61, 81, 43, 58, 71, 72, 67, 64, 67,
69, 68, 77, 81, 74, 65, 65, 50, 50, 64, 53, 40, 63, 66, 78, 48, 85, 82),
complaints = c(51, 64, 70, 63, 78, 55, 67, 75, 82, 61, 53, 60, 62, 83, 77,
90, 85, 60, 70, 58, 40, 61, 66, 37, 54, 77, 75, 57, 85, 82),
privileges = c(30, 51, 68, 45, 56, 49, 42, 50, 72, 45, 53, 47, 57, 83, 54,
50, 64, 65, 46, 68, 33, 52, 52, 42, 42, 66, 58, 44, 71, 39),
learning = c(39, 54, 69, 47, 66, 44, 56, 55, 67, 47, 58, 39, 42, 45, 72,
72, 69, 75, 57, 54, 34, 62, 50, 58, 48, 63, 74, 45, 71, 59),
raises = c(61, 63, 76, 54, 71, 54, 66, 70, 71, 62, 58, 59, 55, 59, 79, 60,
79, 55, 75, 64, 43, 66, 63, 50, 66, 88, 80, 51, 77, 64),
critical = c(92, 73, 86, 84, 83, 49, 68, 66, 83, 80, 67, 74, 63, 77, 77, 54,
79, 80, 85, 78, 64, 80, 80, 57, 75, 76, 78, 83, 74, 78),
advance = c(45, 47, 48, 35, 47, 34, 35, 41, 31, 41, 34, 41, 25, 35, 46, 36,
63, 60, 46, 52, 33, 41, 37, 49, 33, 72, 49, 38, 55, 39)) |
test_that("tolower works", {
txt <- c("According to NATO", "There is G7 meeting")
expect_equal(char_tolower(txt), c("according to nato", "there is g7 meeting"))
expect_error(char_tolower(txt, logical()),
"The length of keep_acronyms must be 1")
expect_error(char_tolower(txt, c(TRUE, FALSE)),
"The length of keep_acronyms must be 1")
})
test_that("char_tolower/char_toUpper works", {
txt <- c("According to NATO", "There is G7 meeting")
expect_equal(char_tolower(txt[1]), "according to nato")
expect_equal(char_toupper(txt[1]), "ACCORDING TO NATO")
})
test_that("char_tolower keeps acronyms", {
txt <- c("According to NATO", "There is G7 meeting")
expect_equal(char_tolower(txt, keep_acronyms = TRUE),
c("according to NATO", "there is G7 meeting"))
})
test_that("tokens_tolower/tokens_toupper works", {
txt <- c("According to NATO", "There is G7 meeting")
toks <- tokens(txt)
expect_equal(as.list(tokens_tolower(toks)),
list(text1 = c("according", "to", "nato"),
text2 = c("there", "is", "g7", "meeting")))
expect_equal(as.list(tokens_tolower(toks, keep_acronyms = TRUE)),
list(text1 = c("according", "to", "NATO"),
text2 = c("there", "is", "G7", "meeting")))
expect_equal(as.list(tokens_toupper(toks)),
list(text1 = c("ACCORDING", "TO", "NATO"),
text2 = c("THERE", "IS", "G7", "MEETING")))
expect_error(tokens_tolower(toks, logical()),
"The length of keep_acronyms must be 1")
expect_error(tokens_tolower(toks, c(TRUE, FALSE)),
"The length of keep_acronyms must be 1")
})
test_that("tokens_tolower/tokens_toupper works", {
txt <- c("According to NATO", "There is G7 meeting")
dfmat <- dfm(tokens(txt), tolower = FALSE)
expect_equal(featnames(dfm_tolower(dfmat)),
c("according", "to", "nato", "there", "is", "g7", "meeting"))
expect_equal(featnames(dfm_tolower(dfmat, keep_acronyms = TRUE)),
c("according", "to", "NATO", "there", "is", "G7", "meeting"))
expect_equal(featnames(dfm_toupper(dfmat)),
c("ACCORDING", "TO", "NATO", "THERE", "IS", "G7", "MEETING"))
expect_error(dfm_tolower(dfmat, logical()),
"The length of keep_acronyms must be 1")
expect_error(dfm_tolower(dfmat, c(TRUE, FALSE)),
"The length of keep_acronyms must be 1")
})
test_that("set encoding when no gap or duplication is found,
toks <- tokens("привет tschüß bye")
toks <- tokens_tolower(toks)
expect_equal(Encoding(types(toks)),
c("UTF-8", "UTF-8", "unknown"))
})
test_that("works with empty objects (
dfmat <- as.dfm(matrix(nrow = 0, ncol = 0))
toks <- as.tokens(list())
expect_identical(types(tokens_tolower(toks)),
character())
expect_identical(types(tokens_toupper(toks)),
character())
expect_identical(featnames(dfm_tolower(dfmat)),
character())
expect_identical(featnames(dfm_toupper(dfmat)),
character())
}) |
setGeneric("resp_loglik", function(ip, resp, theta, derivative = 0)
{standardGeneric("resp_loglik")})
setMethod(
f = "resp_loglik", signature = c(ip = "Item"),
function(ip, resp, theta, derivative = 0){
if (ip$model %in% c(UNIDIM_DICHO_MODELS, UNIDIM_POLY_MODELS)) {
if (inherits(resp, 'integer')) {
if (all(is.na(resp))) return(resp)
if (!all(is.na(resp) | resp %in% 0L:length(ip$b)))
stop(paste0("\nInvalid response. Response should be ",
"either: ", paste0(0L:length(ip$b), collapse = ", "),
" or NA (i.e. missing)."))
if (length(theta) == length(resp)) {
return(resp_loglik_item_cpp(resp = resp, theta = theta, item = ip,
derivative = derivative))
} else
stop(paste0("Invalid arguments. Number of subjects (theta) ",
"should be equal to the number of responses."))
} else if (inherits(resp, c("numeric", "logical"))) {
return(resp_loglik(ip = ip, resp = as.integer(resp), theta = theta,
derivative = derivative))
} else if (inherits(resp, c("matrix"))) {
if ((ncol(resp) == 1) && (nrow(resp) == length(theta)))
{
return(resp_loglik(ip = ip, resp = as.integer(resp), theta = theta,
derivative = derivative))
} else
stop(paste0("\nInvalid arguments. Either resp has more than ",
"1 column, or number of rows in resp matrix is ",
"not equal to the length of theta vector."))
} else if (inherits(resp, c("data.frame"))) {
return(resp_loglik(ip = ip, resp = as.matrix(resp), theta = theta,
derivative = derivative))
} else
stop(paste0("Invalid response. Response cannot be a ", class(resp)[1],
" object"))
} else stop("\nThis model is not implemented in this function.")
}
)
setMethod(
f = "resp_loglik", signature = c(ip = "Itempool"),
function(ip, resp, theta, derivative = 0){
if (all(ip$model %in% c(UNIDIM_DICHO_MODELS, UNIDIM_POLY_MODELS) |
sapply(ip@item_list, is, "Testlet"))) {
num_items <- get_itempool_size(ip)["items"]
num_theta <- length(theta)
if (inherits(resp, 'integer')) {
if (num_items == 1) {
if (num_theta == length(resp)) {
item <- ip@item_list[[1]]
if (is(item, "Item")) {
result <- resp_loglik_item_cpp(resp = resp, theta = theta,
item = item,
derivative = derivative)
} else if (is(item, "Testlet")) {
result <- resp_loglik_bare_testlet_cpp(resp = resp, theta = theta,
testlet = item,
derivative = derivative)
}
} else
stop(paste0("Invalid arguments. Number of subjects (theta) ",
"should be equal to the number of responses."))
} else {
if (all(is.na(resp))) return(NA)
if ((num_theta == 1) && (num_items == length(resp))) {
result <- resp_loglik_itempool_cpp(resp = matrix(resp, nrow = 1),
theta = theta, ip = ip,
derivative = derivative)
} else
stop(paste0("Invalid arguments. Number of subjects (theta) ",
"should be equal to 1 and the number of ",
"responses should equal to the number of items."))
}
} else if (inherits(resp, c("numeric", "logical"))) {
return(resp_loglik(resp = as.integer(resp), ip = ip, theta = theta,
derivative = derivative))
} else if (inherits(resp, c("matrix"))) {
if ((ncol(resp) == num_items) && (nrow(resp) == num_theta) &&
is.numeric(resp)) {
result <- resp_loglik_itempool_cpp(resp = resp, theta = theta,
ip = ip,
derivative = derivative)
} else
stop(paste0("\nInvalid arguments. Number of columns of the resp ",
"matrix should be equal to the number of items.",
"Also number of rows of the resp matrix should be ",
"equal to the number of subjects (theta)."))
} else if (inherits(resp, c("data.frame"))) {
result <- resp_loglik(ip = ip, resp = sapply(resp, as.integer),
theta = theta, derivative = derivative)
} else stop(paste0("Invalid response. Response cannot be a ",
class(resp)[1], " object"))
if (!is.null(names(theta))) names(result) <- names(theta)
return(result)
} else stop(paste0("There is an item model in the item pool that is ",
"not implemented in this function yet."))
}
)
setMethod(
f = "resp_loglik", signature = c(ip = "Testlet"),
function(ip, resp, theta, derivative = 0){
return(resp_loglik(ip = itempool(ip), resp = resp, theta = theta,
derivative = derivative))
}
)
setMethod(
f = "resp_loglik", signature = c(ip = "numMatDfListChar"),
function(ip, resp, theta, derivative = 0){
if (inherits(ip, "numeric")) {
return(resp_loglik(resp = resp, ip = item(ip), theta = theta,
derivative = derivative))
} else if (inherits(ip, c("data.frame", "matrix", "list"))) {
return(resp_loglik(ip = itempool(ip), resp = resp, theta = theta,
derivative = derivative))
} else {
stop("Cannot convert object to an 'Item' or an 'Itempool' object. ",
"Please provide a valid 'Item' or 'Itempool' object using either ",
"'item()' or 'itempool()' function.")
}
}
)
setMethod(
f = "resp_loglik", signature = c(ip = "Itempool", resp = "Response"),
function(ip, resp, theta, derivative = 0){
resp <- response_set(lapply(1:length(theta), function(x) resp), ip = ip)
return(resp_loglik_response_set_cpp(resp, theta, ip = ip,
derivative = derivative))
}
)
setMethod(
f = "resp_loglik", signature = c(ip = "Itempool", resp = "Response_set"),
function(ip, resp, theta, derivative = 0){
return(resp_loglik_response_set_cpp(resp_set = resp, theta = theta,
ip = ip, derivative = derivative))
}
) |
library(igraph)
test_that("one vertex best solution is returned", {
solver <- rnc_solver(max_iterations = 100)
g <- igraph::make_graph(c("A", "B"), directed = FALSE)
V(g)$weight <- c(5, 5)
E(g)$weight <- -7
solution <- solve_mwcsp(solver, g)
expect_equal(solution$weight, 5)
})
test_that("sgmwcs rnc solver works on specific test", {
solver <- rnc_solver(max_iterations = 100)
g <- igraph::make_ring(5)
V(g)$weight <- 1:-3
E(g)$weight <- 1
solution <- solve_mwcsp(solver, g)
expect_equal(solution$weight, 2)
expect_equal(solution$solved_to_optimality, TRUE)
expect_true(igraph::is_connected(solution$graph))
})
test_that("sgmwcs rnc solver does not crush on GAM instances", {
solver <- rnc_solver(max_iterations = 100)
solution <- solve_mwcsp(solver, gam_example)
expect_gte(length(V(solution$graph)), 0)
expect_true(igraph::is_connected(solution$graph))
})
test_that("sgmwcs rnc solver gives good solution for a GAM instance", {
rnc <- rnc_solver(max_iterations = 100)
solution <- solve_mwcsp(rnc, gmwcs_example)
expect_gte(get_weight(solution$graph), 200)
expect_true(igraph::is_connected(solution$graph))
}) |
mice.impute.rfpred.cate <- function(
y,
ry,
x,
wy = NULL,
num.trees.cate = 10,
use.pred.prob.cate = TRUE,
forest.vote.cate = FALSE,
pre.boot = TRUE,
num.threads = NULL,
...) {
if (is.null(wy)) wy <- !ry
yMisNum <- sum(wy)
if (is.logical(y)) {
yIsLogical <- TRUE
y <- as.factor(y)
} else {
yIsLogical <- FALSE
}
if (isTRUE(pre.boot)) {
bootIdx <- sample(sum(ry), replace = TRUE)
yObs <- y[ry][bootIdx]
xObs <- x[ry, , drop = FALSE][bootIdx, , drop = FALSE]
} else {
yObs <- y[ry]
xObs <- x[ry, , drop = FALSE]
}
yobsLvDrop <- droplevels(yObs)
yObsLvNum <- nlevels(yobsLvDrop)
if (yObsLvNum == 1) return(rep_len(yObs, length.out = yMisNum))
xMis <- x[wy, , drop = FALSE]
if (isTRUE(forest.vote.cate)) {
rangerObj <- rangerCallerSafe(
x = xObs,
y = yObs,
oob.error = FALSE,
num.trees = num.trees.cate,
num.threads = num.threads,
...)
impVal <- predictions(predict(rangerObj, xMis))
} else if (isTRUE(use.pred.prob.cate)) {
rangerObjProb <- rangerCallerSafe(
x = xObs,
y = yObs,
probability = TRUE,
oob.error = FALSE,
num.trees = num.trees.cate,
num.threads = num.threads,
...)
misPredMat <- predictions(predict(rangerObjProb, xMis))
yLevels <- colnames(misPredMat)
impValChar <- apply(
X = misPredMat,
MARGIN = 1,
FUN = function(voteProb) {
sample(x = yLevels, size = 1, prob = voteProb)
})
impVal <- factor(x = impValChar, levels = levels(y))
} else {
rangerObj <- rangerCallerSafe(
x = xObs,
y = yObs,
oob.error = FALSE,
num.trees = num.trees.cate,
num.threads = num.threads,
...)
misPredMat <- predictions(predict(rangerObj, xMis, predict.all = TRUE))
impValChar <- apply(
X = misPredMat,
MARGIN = 1,
FUN = function(x) sample(x = x, size = 1))
impVal <- factor(x = levels(y)[impValChar], levels = levels(y))
}
if (yIsLogical) impVal <- as.logical(impVal == "TRUE")
return(impVal)
} |
test_that("Box.Ljung.Test works", {
blt <- Box.Ljung.Test(malleco, lag = 5)
expect_equal(blt$data$y, rep(0, 5))
}) |
ICSS <- function(data = data, demean = FALSE){
if(demean) data <- data - mean(data)
S <- rstack::stack$new()
S$push(c(1,length(data)))
potential_change_points <- rep(0, length(data))
cp_index <- 1;
while (!S$is_empty()) {
current_range <- S$pop()
change_points_sub <- ICSS_step_1_and_2(data[current_range[1]:current_range[2]])
if(length(change_points_sub)==2){
S$push(change_points_sub + current_range[1])
}
if(length(change_points_sub)>0){
potential_change_points[cp_index:(cp_index + (length(change_points_sub) -1))] <- change_points_sub + current_range[1]
}
cp_index <- cp_index + length(change_points_sub)
}
if(sum(potential_change_points, na.rm = T)==0) warning("Unable to identify structural variance breaks in the series.")
potential_change_points <- unique(c(0, sort(potential_change_points), length(data)))
converged <- FALSE
while(!converged){
new_cps_stack <- rstack::stack$new()
for(i in 2:(length(potential_change_points) -1)){
from <- potential_change_points[i-1] + 1
to <- potential_change_points[i+1]
if(is.na(to)) return(NA)
Dk <- CenteredCusumValues(data[from:to])
tmp <- check_critical_value(Dk)
if(length(tmp$position)==0) return(NA)
exceeds <- ifelse(is.na(tmp$exceeds), FALSE, tmp$exceeds)
position <- tmp$position
if(exceeds){
new_cps_stack$push(from + position)
}
}
stack_entries <- vector(mode = "numeric", length = new_cps_stack$size())
for(j in 1:new_cps_stack$size()){stack_entries[j] <- new_cps_stack$pop()}
new_cps <- unique(c(0, sort(stack_entries), length(data)))
converged <- is_converged(potential_change_points, new_cps)
if(!converged){
potential_change_points <- new_cps
}
}
change_points <- potential_change_points[2:(length(potential_change_points) -1 )]
return(change_points)
}
ICSS_step_1_and_2 <- function(x){
change_points <- vector(mode = "numeric")
if (is.null(x)) return(NA)
Dk <- CenteredCusumValues(x);
tmp <- check_critical_value(Dk);
if(length(tmp$position)==0) return(NA)
exceeds <- tmp$exceeds
position_step1 <- tmp$position
if(exceeds){
position <- position_step1
while(exceeds){
t2 <- position
Dk_step2a = CenteredCusumValues(x[1:t2])
tmp <- check_critical_value(Dk_step2a)
if(length(tmp$position)==0) return(NA)
exceeds <- ifelse(is.na(tmp$exceeds), FALSE, tmp$exceeds)
position <- tmp$position
}
k_first <- t2
position <- position_step1 + 1
exceeds <- TRUE
while(exceeds){
t1 <- position
Dk_step2b <- CenteredCusumValues(x[t1:length(x)])
tmp <- check_critical_value(Dk_step2b)
if(length(tmp$position)==0) return(NA)
exceeds <- ifelse(is.na(tmp$exceeds), FALSE, tmp$exceeds)
position2 <- tmp$position
position <- position2 + position
}
k_last <- t1 - 1
if (k_first == k_last){
change_points <- k_first
}else{
change_points = c(k_first, k_last)
}
}
return(change_points)
}
CenteredCusumValues <- function(x){
T <- length(x)
squared <- x^2
Ck <- cumsum(squared)
CT = Ck[T]
ks = 1:T
Dk <- Ck/CT - (ks/T)
return(Dk)
}
check_critical_value <- function(Dk){
value <- max(abs(Dk))
position <- which(abs(Dk)==value)
if(length(position) > 1) return(list(position = NA, exceeds = NA))
M <- sqrt(length(Dk)/2) * value
exceeds <- M > 1.358
return(list(position = position, exceeds = exceeds))
}
is_converged <- function(old, new){
if(length(old) == length(new)){
for(i in 1:length(new)){
low <- min(old[i], new[i])
high <- max(old[i], new[i])
if((high - low) > 2){
return(FALSE)
}
}
}else{
return(FALSE)
}
return(TRUE)
} |
parse_sets <- function(data) {
template <- list(
"id" = as.character,
"code" = as.character,
"name" = as.character,
"mtgo_code" = as.character,
"arena_code" = as.character,
"tcgplayer_id" = as.integer,
"uri" = as.character,
"scryfall_uri" = as.character,
"search_uri" = as.character,
"released_at" = as.Date,
"set_type" = as.character,
"card_count" = as.integer,
"parent_set_code" = as.character,
"printed_size" = as.integer,
"digital" = as.logical,
"nonfoil_only" = as.logical,
"foil_only" = as.logical,
"block_code" = as.character,
"block" = as.character,
"icon_svg_uri" = as.character
)
bind_rows(data, template)
} |
test_that("qr_version() works as expected", {
expect_type(z <- qr_version("0"), "list")
expect_identical(z[1:3], list(version = 1L, ecl = "L", mode = "Numeric"))
expect_type(z <- qr_version("0", "M"), "list")
expect_identical(z[1:3], list(version = 1L, ecl = "M", mode = "Numeric"))
expect_type(z <- qr_version("100"), "list")
expect_identical(z[1:3], list(version = 1L, ecl = "L", mode = "Numeric"))
expect_type(z <- qr_version("0.1"), "list")
expect_identical(z[1:3], list(version = 1L, ecl = "L", mode = "Alphanumeric"))
expect_type(z <- qr_version("0.1", "M"), "list")
expect_identical(z[1:3], list(version = 1L, ecl = "M", mode = "Alphanumeric"))
x <- "fa\xE7ile"
Encoding(x) <- "latin1"
expect_type(z <- qr_version(x), "list")
expect_identical(z[1:3], list(version = 1L, ecl = "L", mode = "Byte"))
expect_type(
z <- qr_version(
"This text requires version 5 with error correction level Q", ecl = "Q"
),
"list"
)
expect_identical(z[1:3], list(version = 5L, ecl = "Q", mode = "Byte"))
set.seed(20211005)
expect_type(
z <- qr_version(
paste(sample(letters, 100, replace = TRUE), collapse = ""), ecl = "Q"
),
"list"
)
expect_identical(z[1:3], list(version = 8L, ecl = "Q", mode = "Byte"))
expect_type(
z <- qr_version(
paste(sample(letters, 1600, replace = TRUE), collapse = ""), ecl = "Q"
),
"list"
)
expect_identical(z[1:3], list(version = 40L, ecl = "Q", mode = "Byte"))
expect_true(has_attr(z$bit_string, "version"))
expect_true(has_attr(z$bit_string, "ecl"))
expect_true(has_attr(z$bit_string, "dcword1"))
expect_true(has_attr(z$bit_string, "n1"))
expect_true(has_attr(z$bit_string, "dcword2"))
expect_true(has_attr(z$bit_string, "n2"))
expect_true(has_attr(z$bit_string, "ecword"))
expect_true(has_attr(z$bit_string, "remainder"))
expect_true(has_attr(z$bit_string, "alignment"))
}) |
c(
Mod4Step5updateVind <- function(input, nb.IS){
m <- matrix(rep(0,(nb.IS*2)^2),(nb.IS*2))
diag(m)[1] <- input$Mod4Step5_Vi1
diag(m)[1 + nb.IS] <- input$Mod4Step5_Vi2
m[nb.IS + 1,1] <- input$Mod4Step5_Corr_I
return(m)
},
Mod4Step5updateB <- function(input, nb.IS){
m <- matrix(rep(0,(nb.IS*2)), nrow = 1)
m[1,2] <- input$Mod4Step5_B11
m[1,nb.IS + 2] <- input$Mod4Step5_B12
return(m)
},
output$Mod4Step5_hidden <- renderUI({
list(
numericInput("Mod4Step5_Tmax", "", Modules_VAR$Tmax$max),
numericInput("Mod4Step5_NI", "", 100),
numericInput("Mod4Step5_NT", "", 2),
numericInput("Mod4Step5_NR", "", 10),
shinyMatrix::matrixInput("Mod4Step5_B", value = Mod4Step5updateB(input, nb.IS), class = "numeric"),
shinyMatrix::matrixInput("Mod4Step5_Vind", value = Mod4Step5updateVind(input, nb.IS), class = "numeric"),
shinyMatrix::matrixInput("Mod4Step5_Ve", value = matrix(c(input$Mod4Step5_Ve1, input$Mod4Step5_Corr_e,
input$Mod4Step5_Corr_e, input$Mod4Step5_Ve2), 2), class = "numeric"),
checkboxInput("Mod4Step5_X1_state", "", value = TRUE),
checkboxInput("Mod4Step5_X1_sto_state", "", value = TRUE)
)
}),
outputOptions(output, "Mod4Step5_hidden", suspendWhenHidden = FALSE),
get_data <- function(){
data <- squid::squidR(input, module = "Mod4Step5")
dt <- as.data.table(data$sampled_data)
dt <- dt[ , .(Time, Individual, Trait, Phenotype, X1)]
dt[ , Trait := paste0("Phenotype_", Trait)]
dt <- dcast(dt, Time + Individual + X1 ~ Trait, value.var = "Phenotype")
return(list("sampled" = dt, "full_data" = data$full_data))
},
Mod4Step5_output <- reactive({
if (input$Mod4Step5_Run == 0)
return(NULL)
isolate({
updateCheckboxInput(session, "isRunning", value = TRUE)
dt <- get_data()
updateCheckboxInput(session, "isRunning", value = FALSE)
return(dt)
})
}),
observe({
data <- Mod4Step5_output()
if(is.null(data)){
disableActionButton("Mod4Step5_Run_1", session, "true")
disableActionButton("Mod4Step5_Run_2", session, "true")
}else{
disableActionButton("Mod4Step5_Run_1", session, "false")
disableActionButton("Mod4Step5_Run_2", session, "false")
}
}),
Mod4Step5_output_model1 <- reactive({
if (input$Mod4Step5_Run_1 == 0)
return(NULL)
isolate({
updateCheckboxInput(session, "isRunning", value = TRUE)
data <- get_data()$sampled
library(brms)
fit1 <- readRDS("./source/server/modules/module4/stanFiles/module4_step5_brms_model1.rds")
fit1 <- update(fit1, newdata = data,
iter = 200, warmup = 100, chains = 1)
updateCheckboxInput(session, "isRunning", value = FALSE)
return(fit1)
})
}),
Mod4Step5_output_model2 <- reactive({
if (input$Mod4Step5_Run_2 == 0)
return(NULL)
isolate({
updateCheckboxInput(session, "isRunning", value = TRUE)
data <- get_data()$sampled
library(brms)
fit2 <- readRDS("./source/server/modules/module4/stanFiles/module4_step5_brms_model2.rds")
fit2 <- update(fit2, newdata = data,
iter = 200, warmup = 100, chains = 1)
updateCheckboxInput(session, "isRunning", value = FALSE)
return(fit2)
})
}),
output$Mod4Step5_correlationplot <- renderPlot({
data <- Mod4Step5_output()
if (!is.null(data)) {
dt <- copy(data[["sampled"]])
ggplot2::ggplot(dt, ggplot2::aes(x = Phenotype_1, Phenotype_2, fill = as.factor(Individual), colour = as.factor(Individual))) +
ggplot2::geom_point() +
ggplot2::xlab("Phenotype of trait y") +
ggplot2::ylab("Phenotype of trait z") +
ggplotCustomTheme()
}else{
sim_msg()
}
}),
output$Mod4Step5_correlationplot2 <- renderPlot({
data <- Mod4Step5_output()
if (!is.null(data)) {
dt <- copy(data[["sampled"]])
dt <- dt[ , .(Phenotype_1 = mean(Phenotype_1),
Phenotype_2 = mean(Phenotype_2)), by = Individual]
ggplot2::ggplot(dt, ggplot2::aes(x = Phenotype_1, Phenotype_2, fill = as.factor(Individual), colour = as.factor(Individual))) +
ggplot2::geom_point() +
ggplot2::xlab("Mean phenotype of trait y") +
ggplot2::ylab("Mean phenotype of trait z") +
ggplotCustomTheme()
}else{
defaultPlot()
}
}),
output$Mod4Step5_correlationplot3 <- renderPlot({
data <- Mod4Step5_output()
if (!is.null(data)) {
dt <- copy(data[["sampled"]])
dt[ , ':='(Phenotype_1 = Phenotype_1 - mean(Phenotype_1),
Phenotype_2 = Phenotype_2 - mean(Phenotype_2)), by = Individual]
ggplot2::ggplot(dt, ggplot2::aes(x = Phenotype_1, Phenotype_2, fill = as.factor(Individual), colour = as.factor(Individual))) +
ggplot2::geom_point() +
ggplot2::xlab("Deviation from individual phenotype mean of trait y") +
ggplot2::ylab("Deviation from individual phenotype mean of trait z") +
ggplotCustomTheme()
}else{
defaultPlot()
}
}),
output$Mod4Step5_environment <- renderPlot({
data <- Mod4Step5_output()
if (!is.null(data)) {
dt <- copy(data[["full_data"]])
dt <- dt[1:(input$Mod4Step5_Tmax),]
ggplot2::ggplot(dt, ggplot2::aes(x = Time, y = X1, fill = as.factor(Individual), colour = as.factor(Individual))) +
ggplot2::geom_point() +
ggplot2::xlab("Time") +
ggplot2::ylab("Environment value") +
ggplotCustomTheme()
}else{
defaultPlot()
}
}),
output$Mod4Step5_Phenotypic_Equation <- renderUI({
eq <- paste0("$$",
NOT$trait.1,"_{",NOT$time,NOT$ind,"} =
(0 + ",EQ$dev0.1,") +
",input$Mod4Step5_B11,NOT$env,"_{",NOT$time,NOT$ind,"} +
",NOT$error,"_{",NOT$trait.1,NOT$time,NOT$ind,"}$$
$$",
NOT$trait.2,"_{",NOT$time,NOT$ind,"} =
(0 + ",EQ$dev0.2,") +
",input$Mod4Step5_B12,NOT$env,"_{",NOT$time,NOT$ind,"} +
",NOT$error,"_{",NOT$trait.2,NOT$time,NOT$ind,"}
$$")
return(withMathJax(eq))
}),
Matrices <- reactive({
cov1 <- round(input$Mod4Step5_Corr_I * sqrt(input$Mod4Step5_Vi1 * input$Mod4Step5_Vi2),3)
eq1 <- paste0(
"$$ \\Omega_{",NOT$devI,"}=
\\begin{pmatrix}
V_{",NOT$devI,"_",NOT$trait.1,"} & Cov_{",NOT$devI,"_",NOT$trait.1,",",NOT$devI,"_",NOT$trait.2,"} \\\\
Cov_{",NOT$devI,"_",NOT$trait.1,",",NOT$devI,"_",NOT$trait.2,"} & V_{", NOT$devI,"_",NOT$trait.2,"} \\\\
\\end{pmatrix}
=
\\begin{pmatrix}
",input$Mod4Step5_Vi1," & ",cov1," \\\\
",cov1," & ",input$Mod4Step5_Vi2,"\\\\
\\end{pmatrix}
$$")
cov2 <- round(input$Mod4Step5_Corr_e * sqrt(input$Mod4Step5_Ve1 * input$Mod4Step5_Ve2),3)
eq2 <- paste0(
"$$ \\Omega_{",NOT$error,"}=
\\begin{pmatrix}
V_{",NOT$error,"_",NOT$trait.1,"} & Cov_{",NOT$error,"_",NOT$trait.1,",",NOT$error,"_",NOT$trait.2,"} \\\\
Cov_{",NOT$error,"_",NOT$trait.1,",",NOT$error,"_",NOT$trait.2,"} & V_{", NOT$error,"_",NOT$trait.2,"} \\\\
\\end{pmatrix}
=
\\begin{pmatrix}
",input$Mod4Step5_Ve1," & ",cov2," \\\\
",cov2," & ",input$Mod4Step5_Ve2,"\\\\
\\end{pmatrix}
$$")
return(withMathJax(paste0(eq1, eq2)))
}),
output$Mod4Step5_Matrices_1 <- renderUI({Matrices()}),
output$Mod4Step5_Matrices_2 <- renderUI({Matrices()}),
output$Mod4Step5_Matrices_3 <- renderUI({Matrices()}),
show_model_variance_results <- function(fit){
RanCoef <- VarCorr(fit)
varI1 <- round(RanCoef[["Individual"]][["sd"]]["Phenotype1_Intercept", "Estimate"]^2, 2)
varI2 <- round(RanCoef[["Individual"]][["sd"]]["Phenotype2_Intercept", "Estimate"]^2, 2)
covI12 <- round(RanCoef[["Individual"]][["cov"]]["Phenotype1_Intercept", "Estimate", "Phenotype2_Intercept"], 2)
varE1 <- round(RanCoef[["residual__"]][["sd"]]["Phenotype1", "Estimate"]^2, 2)
varE2 <- round(RanCoef[["residual__"]][["sd"]]["Phenotype2", "Estimate"]^2, 2)
covE12 <- round(RanCoef[["residual__"]][["cov"]]["Phenotype1", "Estimate", "Phenotype2"], 2)
cov1 <- round(input$Mod4Step5_Corr_I * sqrt(input$Mod4Step5_Vi1 * input$Mod4Step5_Vi2),3)
cov2 <- round(input$Mod4Step5_Corr_e * sqrt(input$Mod4Step5_Ve1 * input$Mod4Step5_Ve2),3)
eq1 <- paste0(
"$$\\Omega_{",NOT$devI,"'}=
\\begin{pmatrix}
",varI1,"\\,[",input$Mod4Step5_Vi1,"] & ",covI12,"\\,[",cov1,"] \\\\
",covI12,"\\,[",cov1,"] & ",varI2,"\\,[",input$Mod4Step5_Vi2,"]\\\\
\\end{pmatrix}\\quad")
eq2 <- paste0(
"\\Omega_{",NOT$error,"'}=
\\begin{pmatrix}
",varE1,"\\,[",input$Mod4Step5_Ve1,"] & ",covE12,"\\,[",cov2,"] \\\\
",covE12,"\\,[",cov2,"] & ",varE2,"\\,[",input$Mod4Step5_Ve1,"]\\\\
\\end{pmatrix}
$$")
return(paste0(eq1, eq2))
},
show_model_correlation_results <- function(fit){
RanCoef <- VarCorr(fit)
corI12 <- round(RanCoef[["Individual"]][["cor"]]["Phenotype1_Intercept", "Estimate", "Phenotype2_Intercept"],2)
corE12 <- round(RanCoef[["residual__"]][["cor"]]["Phenotype1", "Estimate", "Phenotype2"],2)
cor <- paste0("$$\\text{Among-individual correlation: }",corI12,"\\,[",input$Mod4Step5_Corr_I,"]$$
$$\\text{Residual within-individual correlation: }",corE12,"\\,[",input$Mod4Step5_Corr_e,"]$$")
return(cor)
},
output$Mod4Step5_Result_Matrices_Model1 <- renderUI({
fit1 <- Mod4Step5_output_model1()
if (!is.null(fit1)) {
isolate({res <- show_model_variance_results(fit1)})
return(withMathJax(res))
}else{return(withMathJax("$$...$$"))}
}),
output$Mod4Step5_Result_Matrices_Model1_corr <- renderUI({
fit1 <- Mod4Step5_output_model1()
if (!is.null(fit1)) {
isolate({cor <- show_model_correlation_results(fit1)})
return(withMathJax(cor))
}else{return(withMathJax("$$...$$"))}
}),
output$Mod4Step5_Result_Matrices_Model2 <- renderUI({
fit2 <- Mod4Step5_output_model2()
if (!is.null(fit2)) {
isolate({res <- show_model_variance_results(fit2)})
return(withMathJax(res))
}else{return(withMathJax("$$...$$"))}
}),
output$Mod4Step5_Result_Matrices_Model2_corr <- renderUI({
fit2 <- Mod4Step5_output_model2()
if (!is.null(fit2)) {
isolate({cor <- show_model_correlation_results(fit2)})
return(withMathJax(cor))
}else{return(withMathJax("$$...$$"))}
})
) |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(lrd)
data("cued_recall_manuscript")
head(cued_recall_manuscript)
cued_recall_manuscript$Target <- tolower(cued_recall_manuscript$Target)
cued_recall_manuscript$Answer <- tolower(cued_recall_manuscript$Answer)
cued_output <- prop_correct_cued(data = cued_recall_manuscript,
responses = "Answer",
key = "Target",
key.trial = "Trial_num",
id = "Sub.ID",
id.trial = "Trial_num",
cutoff = 1,
flag = TRUE,
group.by = NULL)
str(cued_output)
cued_output$DF_Scored
cued_output$DF_Participant |
if (interactive()) {
rank_list(
text = "You can select multiple items and drag as a group:",
labels = c("one", "two", "three", "four", "five"),
input_id = "example_2",
options = sortable_options(
multiDrag = TRUE
)
)
} |
Tune_kernel_Ridge_MM <-
function( Y_train, X_train=as.vector(rep(1,length(Y_train))), Z_train=diag(1,length(Y_train)),
Matrix_covariates_train, method="RKHS", kernel="Gaussian", rate_decay_kernel=0.1, degree_poly=2, scale_poly=1,
offset_poly=1, degree_anova=3, init_sigma2K=2, init_sigma2E=3, convergence_precision=1e-8, nb_iter=1000, display="FALSE",
rate_decay_grid=seq(0.1,1.0,length.out=10), nb_folds=5, loss="mse")
{
N=length(Y_train)
Index_whole=1:N
Folds=cvFolds(N, nb_folds, type="consecutive")
Vect_expected_loss_grid=rep(0, length(rate_decay_grid))
method_defined=method
kernel_defined=kernel
rate_decay_defined=rate_decay_kernel
degree_poly_defined=degree_poly
scale_poly_defined=scale_poly
offset_poly_defined=offset_poly
degree_anova_defined=degree_anova
init_sigma2K_defined=init_sigma2K
init_sigma2E_defined=init_sigma2E
convergence_precision_defined=convergence_precision
nb_iter_defined=nb_iter
display_defined=display
if( identical(loss, "mse") )
{
l=1
for ( h in rate_decay_grid )
{
Vect_loss_folds=rep(0,nb_folds)
for ( fold_i in 1:nb_folds )
{
Index_fold_i=which(Folds$which==fold_i)
Y_fold_i=Y_train[Index_fold_i]
Matrix_covariates_fold_i=Matrix_covariates_train[Index_fold_i, ]
Index_minus_fold_i=Index_whole[-Index_fold_i]
Y_minus_fold_i=Y_train[Index_minus_fold_i]
X_minus_fold_i=as.vector(rep(1,length(Y_minus_fold_i)))
Z_minus_fold_i=diag(1,length(Y_minus_fold_i))
Matrix_covariates_minus_fold_i=Matrix_covariates_train[Index_minus_fold_i, ]
Model_KRR_minus_fold_i = Kernel_Ridge_MM( Y_train=Y_minus_fold_i, X_train=X_minus_fold_i,
Z_train=Z_minus_fold_i, Matrix_covariates_train=Matrix_covariates_minus_fold_i,
method=method_defined, kernel=kernel_defined, rate_decay_kernel=h, degree_poly=degree_poly_defined,
scale_poly=scale_poly_defined, offset_poly=offset_poly_defined, degree_anova=degree_anova_defined,
init_sigma2K=init_sigma2K_defined, init_sigma2E=init_sigma2E_defined,
convergence_precision=convergence_precision_defined, nb_iter=nb_iter_defined, display=display_defined )
f_hat_fold_i = Predict_kernel_Ridge_MM( Model_KRR_minus_fold_i, Matrix_covariates_fold_i )
Vect_loss_folds[fold_i]= mean((f_hat_fold_i-Y_fold_i)^2)
}
Vect_expected_loss_grid[l]=mean(Vect_loss_folds)
l=l+1
}
optimal_h=rate_decay_grid[which.min(Vect_expected_loss_grid)]
tuned_model=Kernel_Ridge_MM ( Y_train, X_train, Z_train, Matrix_covariates_train, method, kernel,
rate_decay_kernel=optimal_h, degree_poly, scale_poly, offset_poly, degree_anova, init_sigma2K, init_sigma2E,
convergence_precision, nb_iter, display)
return( list( "tuned_model"=tuned_model, "optimal_h"=optimal_h, "loss"=loss,
"expected_loss_grid"=Vect_expected_loss_grid, "rate_decay_grid"=rate_decay_grid ) )
} else if ( identical( loss, "cor" ) ){
l=1
for ( h in rate_decay_grid )
{
Vect_loss_folds=rep(0,nb_folds)
for ( fold_i in 1:nb_folds )
{
Index_fold_i=which(Folds$which==fold_i)
Y_fold_i=Y_train[Index_fold_i]
Matrix_covariates_fold_i=Matrix_covariates_train[Index_fold_i, ]
Index_minus_fold_i=Index_whole[-Index_fold_i]
Y_minus_fold_i=Y_train[Index_minus_fold_i]
X_minus_fold_i=as.vector(rep(1,length(Y_minus_fold_i)))
Z_minus_fold_i=diag(1,length(Y_minus_fold_i))
Matrix_covariates_minus_fold_i=Matrix_covariates_train[Index_minus_fold_i, ]
Model_KRR_minus_fold_i = Kernel_Ridge_MM( Y_train=Y_minus_fold_i, X_train=X_minus_fold_i,
Z_train=Z_minus_fold_i, Matrix_covariates_train=Matrix_covariates_minus_fold_i,
method=method_defined, kernel=kernel_defined, rate_decay_kernel=h, degree_poly=degree_poly_defined,
scale_poly=scale_poly_defined, offset_poly=offset_poly_defined, degree_anova=degree_anova_defined,
init_sigma2K=init_sigma2K_defined, init_sigma2E=init_sigma2E_defined,
convergence_precision=convergence_precision_defined, nb_iter=nb_iter_defined, display=display_defined )
f_hat_fold_i = Predict_kernel_Ridge_MM( Model_KRR_minus_fold_i, Matrix_covariates_fold_i )
Vect_loss_folds[fold_i]= 0.5*(1-cor(f_hat_fold_i, Y_fold_i))
}
Vect_expected_loss_grid[l]=mean(Vect_loss_folds)
l=l+1
}
optimal_h=rate_decay_grid[which.min(Vect_expected_loss_grid)]
tuned_model=Kernel_Ridge_MM ( Y_train, X_train, Z_train, Matrix_covariates_train, method, kernel,
rate_decay_kernel=optimal_h, degree_poly, scale_poly, offset_poly, degree_anova, init_sigma2K, init_sigma2E,
convergence_precision, nb_iter, display)
return( list( "tuned_model"=tuned_model, "optimal_h"=optimal_h, "loss"=loss,
"expected_loss_grid"=Vect_expected_loss_grid, "rate_decay_grid"=rate_decay_grid ) )
}
} |
context("BMI operations")
test_that("BMI grouping ok", {
x <- 15:50
expect_equal(length(unique(levels(group_bmi(x, "standard")))), 7)
expect_true(group_bmi(x, "standard")[[10]] == "lean")
expect_equal(length(unique(levels(group_bmi(x, "even", 5)))), 5)
expect_true(group_bmi(18, "standard") == "underweight")
expect_true(group_bmi(18.5, "standard") == "lean")
expect_true(group_bmi(20, "standard") == "lean")
expect_true(group_bmi(22, "standard") == "lean")
expect_true(group_bmi(25, "standard") == "overweight")
expect_true(group_bmi(28, "standard") == "overweight")
expect_true(group_bmi(30, "standard") == "obese")
expect_true(group_bmi(32, "standard") == "obese")
expect_true(group_bmi(35, "standard") == "severe")
expect_true(group_bmi(37, "standard") == "severe")
expect_true(group_bmi(40, "standard") == "morbid")
expect_true(group_bmi(42, "standard") == "morbid")
expect_true(group_bmi(45, "standard") == "super")
expect_true(group_bmi(47, "standard") == "super")
expect_true(group_bmi(50, "standard") == "super")
expect_true(group_bmi(52, "standard") == "super")
expect_true(group_bmi(55, "standard") == "super")
}) |
set.seed(120)
rlap_data = geoR::grf(50, cov.pars = c(1, 1), nugget = 0.1,
messages = FALSE)
y = rlap_data$data
x = matrix(1, nrow = length(y))
coords = rlap_data$coords
d = ganiso_d(rlap_data$coords, coords2 = rlap_data$coords,
invert = TRUE)
geoR_ml = geoR::likfit(rlap_data, ini = c(1, 1),
cov.model = "matern",
nugget = 0.1, kappa = 1,
psiA = pi/8, psiR = 1.5,
fix.nug = FALSE,
fix.psiA = FALSE,
fix.psiR = TRUE,
fix.kappa = FALSE,
messages = FALSE)
geoR_reml = geoR::likfit(rlap_data, ini = c(1, 1),
cov.model = "matern",
nugget = 0.1, kappa = 1,
psiA = pi/8, psiR = 1.5,
fix.nug = FALSE,
fix.psiA = FALSE,
fix.psiR = TRUE,
fix.kappa = FALSE,
messages = FALSE,
lik.method = "REML")
aniso_coords = geoR::coords.aniso(coords, aniso.pars = geoR_reml$aniso.pars)
rlap_data_noaniso = rlap_data
rlap_data_noaniso$coords = aniso_coords
geoR_reml_noaniso = geoR::likfit(rlap_data_noaniso, ini = c(1, 1),
nugget = 0.1, fix.nug = TRUE,
fix.psiA = TRUE,
messages = FALSE,
lik.method = "REML")
geoR_ml_loglik = geoR::loglik.GRF(rlap_data, obj.model = geoR_ml)
geoR_reml_loglik = geoR::loglik.GRF(rlap_data, obj.model = geoR_reml)
geoR_reml_noaniso_loglik = geoR::loglik.GRF(rlap_data_noaniso, obj.model = geoR_reml_noaniso)
kc_ml = geoR::krige.control(obj.model = geoR_ml)
geoR_out = geoR::output.control(messages = FALSE)
geoR_ml_beta = geoR::krige.conv(rlap_data, krige = kc_ml,
locations = cbind(1, 1),
output = geoR_out)$beta.est
kc_reml = geoR::krige.control(obj.model = geoR_reml)
geoR_reml_beta = geoR::krige.conv(rlap_data, krige = kc_reml,
locations = cbind(1, 1),
output = geoR_out)$beta.est
fpath = system.file("testdata", package = "gear")
fname = paste(fpath, "/ploglik_cmodStd_r_lambda_angle_par3.rda", sep = "")
save(x, y, d, coords, geoR_ml, geoR_reml,
geoR_ml_loglik, geoR_reml_loglik,
geoR_reml_noaniso_loglik,
geoR_ml_beta, geoR_reml_beta,
compress = "bzip2",
file = fname,
version = 2) |
NULL
AUC2 <- function(pred, y) auc_cpp(pred[y == 1], pred[y == 0])
round2 <- function(x, digits = NULL) `if`(is.null(digits), x, round(x, digits))
AUC <- function(pred, target, digits = NULL) {
assert_lengths(pred, target)
y <- transform_levels(target)
round2(AUC2(pred, y), digits)
}
AUCBoot <- function(pred, target, nboot = 1e3, seed = NA, digits = NULL) {
assert_lengths(pred, target)
y <- transform_levels(target)
n <- length(y)
if (!is.na(seed)) {
old <- .Random.seed
on.exit( { .Random.seed <<- old } )
set.seed(seed)
}
repl <- replicate(nboot, {
ind <- sample(n, replace = TRUE)
AUC2(pred[ind], y[ind])
})
if (nbNA <- sum(is.na(repl)))
warning2("%d/%d bootstrap replicates were mono-class.", nbNA, nboot)
res <- c("Mean" = mean(repl, na.rm = TRUE),
stats::quantile(repl, c(0.025, 0.975), na.rm = TRUE),
"Sd" = stats::sd(repl, na.rm = TRUE))
round2(res, digits)
} |
var.used.forestRK <- function(forestRK.object = forestRK(), tree.index = c()){
x.original <- forestRK.object$X
if(is.null(forestRK.object)){
stop("'forestRK.object' has to be provided in the function call")
}
if(!(dim(x.original)[1] > 1) || !(dim(x.original)[2] >= 1) || is.null(x.original)){
stop("Invalid dimension for the dataset 'x.original'")
}
if(!(length(tree.index) >= 1) || is.null(tree.index)){
stop("Invalid length for the vector 'tree.index'")
}
forest.rk.tree.list <- forestRK.object$forest.rk.tree.list
covariate.split.vec <- c()
covariates.used.list <- list()
length(covariates.used.list) <- length(tree.index)
names(covariates.used.list) <- as.character(levels(as.factor(tree.index)))
for(i in 1:length(tree.index)){
covariate.split.vec <- c(covariate.split.vec, ((forest.rk.tree.list)[[tree.index[i]]])$covariate.split[-1,1])
covariates.used.in.bag <- c((colnames(x.original))[covariate.split.vec])
covariates.used.list[[i]] <- covariates.used.in.bag
}
covariates.used.list
} |
knitr::opts_chunk$set(collapse = TRUE, comment = "
library(ggplot2)
library(reshape2)
library(ABHgenotypeR)
genotypes <- readABHgenotypes(system.file("extdata",
"preprefall025TestData.csv",
package = "ABHgenotypeR"),
nameA = "NB", nameB = "OL")
plotGenos(genotypes)
plottedGenos <- plotGenos(genotypes)
plottedGenos <- plottedGenos + theme(axis.text = element_text(face = "bold"),
legend.position = "none")
postImpGenotypes <- imputeByFlanks(genotypes)
plotGenos(genotypes, chromToPlot = 1)
plotGenos(postImpGenotypes,chromToPlot = 1)
ErrCorr1Genotypes <- correctUndercalledHets(postImpGenotypes, maxHapLength = 3)
ErrCorr2Genotypes <- correctStretches(ErrCorr1Genotypes, maxHapLength = 3)
plotGenos(ErrCorr1Genotypes, chromToPlot = 1)
plotGenos(ErrCorr2Genotypes,chromToPlot = 1)
plotCompareGenos(genotypes, ErrCorr2Genotypes, chromToPlot = 1:3)
plotMarkerDensity(genos = ErrCorr2Genotypes)
plotAlleleFreq(genos = ErrCorr2Genotypes) |
TML.Ave2G <-
function(X,y,delta, sigma,sigma.t, mui,mui.t, wgt,cu){ cl <- -cu
n <- length(y); p <- ncol(X); ku <- kc <- 0; nc <- sum(delta==0); zero <- 1e-6
indu <- (1:n)[delta==1]; indc <- (1:n)[delta==0]
rs <- (y-mui)/sigma
if (nc < n) {
ki <- wgt[indu]*rs[indu]^2
ku <- sum(ki)}
if (nc > 0) {
muic <- mui[indc]
muit <- mui.t[indc]
rci <- rs[indc]
ai <- pmax( rci, (sigma.t*cl - muic + muit )/sigma )
bi <- (sigma.t*cu - muic + muit )/sigma
den <- 1-pnorm(rci)
ok <- den > zero
Iki <- ai*dnorm(ai) - bi*dnorm(bi) + pnorm(bi) - pnorm(ai)
eki <- rep(0, nc)
eki[bi > ai & ok] <- Iki[bi > ai & ok]/den[bi > ai & ok]
kc <- sum(eki)}
(ku + kc)/(n - p)} |
setClass("membership",
representation = representation(member="matrix",
hard.label="vector")
)
setValidity("membership",
function(object){
if(length(hard.label(object))!= nrow(member(object)))
return("hard.label Mismatch\n")
if(any(member(object)<0 ||member(object)>1))
return("Constraint of membership matrix violated\n")
rowSum.membership<-rowSums(member(object))
rowSum.membership<-round(rowSum.membership,3)
if(any(rowSum.membership!=1))
{
return("Constraint of membership matrix violated\n")
}
if(any(!is.numeric(member(object))))
return("Not Numeric")
if(anyNA(object))
return("Missing value on membership detected\n")
}) |
draw.quintuple.venn <- function(
area1,
area2,
area3,
area4,
area5,
n12,
n13,
n14,
n15,
n23,
n24,
n25,
n34,
n35,
n45,
n123,
n124,
n125,
n134,
n135,
n145,
n234,
n235,
n245,
n345,
n1234,
n1235,
n1245,
n1345,
n2345,
n12345,
category = rep('', 5),
lwd = rep(2, 5),
lty = rep('solid', 5),
col = rep('black', 5),
fill = NULL,
alpha = rep(0.5, 5),
label.col = rep('black', 31),
cex = rep(1, 31),
fontface = rep('plain', 31),
fontfamily = rep('serif', 31),
cat.pos = c(0, 287.5, 215, 145, 70),
cat.dist = rep(0.2, 5),
cat.col = rep('black', 5),
cat.cex = rep(1, 5),
cat.fontface = rep('plain', 5),
cat.fontfamily = rep('serif', 5),
cat.just = rep(list(c(0.5, 0.5)), 5),
rotation.degree = 0,
rotation.centre = c(0.5, 0.5),
ind = TRUE,
cex.prop=NULL,
print.mode = 'raw',
sigdigs=3,
direct.area=FALSE,
area.vector=0,
...
) {
if (length(category) == 1) { cat <- rep(category, 5); }
else if (length(category) != 5) { flog.error('Unexpected parameter length for "category"",name="VennDiagramLogger')
stop('Unexpected parameter length for "category"'); }
if (length(lwd) == 1) { lwd <- rep(lwd, 5); }
else if (length(lwd) != 5) { flog.error('Unexpected parameter length for "lwd"",name="VennDiagramLogger')
stop('Unexpected parameter length for "lwd"'); }
if (length(lty) == 1) { lty <- rep(lty, 5); }
else if (length(lty) != 5) { flog.error('Unexpected parameter length for "lty"",name="VennDiagramLogger')
stop('Unexpected parameter length for "lty"'); }
if (length(col) == 1) { col <- rep(col, 5); }
else if (length(col) != 5) { flog.error('Unexpected parameter length for "col"",name="VennDiagramLogger')
stop('Unexpected parameter length for "col"'); }
if (length(label.col) == 1) { label.col <- rep(label.col, 31); }
else if (length(label.col) != 31) { flog.error('Unexpected parameter length for "label.col"",name="VennDiagramLogger')
stop('Unexpected parameter length for "label.col"'); }
if (length(cex) == 1) { cex <- rep(cex, 31); }
else if (length(cex) != 31) { flog.error('Unexpected parameter length for "cex"",name="VennDiagramLogger')
stop('Unexpected parameter length for "cex"'); }
if (length(fontface) == 1) { fontface <- rep(fontface, 31); }
else if (length(fontface) != 31) { flog.error('Unexpected parameter length for "fontface"",name="VennDiagramLogger')
stop('Unexpected parameter length for "fontface"'); }
if (length(fontfamily) == 1) { fontfamily <- rep(fontfamily, 31); }
else if (length(fontfamily) != 31) { flog.error('Unexpected parameter length for "fontfamily"",name="VennDiagramLogger')
stop('Unexpected parameter length for "fontfamily"'); }
if (length(fill) == 1) { fill <- rep(fill, 5); }
else if (length(fill) != 5 & length(fill) != 0) { flog.error('Unexpected parameter length for "fill"",name="VennDiagramLogger')
stop('Unexpected parameter length for "fill"'); }
if (length(alpha) == 1) { alpha <- rep(alpha, 5); }
else if (length(alpha) != 5 & length(alpha) != 0) { flog.error('Unexpected parameter length for "alpha"",name="VennDiagramLogger')
stop('Unexpected parameter length for "alpha"'); }
if (length(cat.pos) == 1) { cat.pos <- rep(cat.pos, 5); }
else if (length(cat.pos) != 5) { flog.error('Unexpected parameter length for "cat.pos"",name="VennDiagramLogger')
stop('Unexpected parameter length for "cat.pos"'); }
if (length(cat.dist) == 1) { cat.dist <- rep(cat.dist, 5); }
else if (length(cat.dist) != 5) { flog.error('Unexpected parameter length for "cat.dist"",name="VennDiagramLogger')
stop('Unexpected parameter length for "cat.dist"'); }
if (length(cat.col) == 1) { cat.col <- rep(cat.col, 5); }
else if (length(cat.col) != 5) { flog.error('Unexpected parameter length for "cat.col"",name="VennDiagramLogger')
stop('Unexpected parameter length for "cat.col"'); }
if (length(cat.cex) == 1) { cat.cex <- rep(cat.cex, 5); }
else if (length(cat.cex) != 5) { flog.error('Unexpected parameter length for "cat.cex"",name="VennDiagramLogger')
stop('Unexpected parameter length for "cat.cex"'); }
if (length(cat.fontface) == 1) { cat.fontface <- rep(cat.fontface, 5); }
else if (length(cat.fontface) != 5) { flog.error('Unexpected parameter length for "cat.fontface"",name="VennDiagramLogger')
stop('Unexpected parameter length for "cat.fontface"'); }
if (length(cat.fontfamily) == 1) { cat.fontfamily <- rep(cat.fontfamily, 5); }
else if (length(cat.fontfamily) != 5) { flog.error('Unexpected parameter length for "cat.fontfamily"",name="VennDiagramLogger')
stop('Unexpected parameter length for "cat.fontfamily"'); }
if (!(class(cat.just) == 'list' & length(cat.just) == 5 & length(cat.just[[1]]) == 2 & length(cat.just[[2]]) == 2 & length(cat.just[[3]]) == 2 & length(cat.just[[4]]) == 2 & length(cat.just[[5]]) == 2)) { flog.error('Unexpected parameter format for "cat.just"",name="VennDiagramLogger')
stop('Unexpected parameter format for "cat.just"'); }
cat.pos <- cat.pos + rotation.degree;
if(direct.area){
areas <- area.vector;
for(i in 1:31)
{
assign(paste('a',i,sep=''),area.vector[i]);
}
}
else{
a31 <- n12345;
a30 <- n1234 - a31;
a29 <- n1235 - a31;
a28 <- n1245 - a31;
a27 <- n1345 - a31;
a26 <- n2345 - a31;
a25 <- n245 - a26 - a28 - a31;
a24 <- n234 - a26 - a30 - a31;
a23 <- n134 - a27 - a30 - a31;
a22 <- n123 - a29 - a30 - a31;
a21 <- n235 - a26 - a29 - a31;
a20 <- n125 - a28 - a29 - a31;
a19 <- n124 - a28 - a30 - a31;
a18 <- n145 - a27 - a28 - a31;
a17 <- n135 - a27 - a29 - a31;
a16 <- n345 - a26 - a27 - a31;
a15 <- n45 - a18 - a25 - a16 - a28 - a27 - a26 - a31;
a14 <- n24 - a19 - a24 - a25 - a30 - a28 - a26 - a31;
a13 <- n34 - a16 - a23 - a24 - a26 - a27 - a30 - a31;
a12 <- n13 - a17 - a22 - a23 - a27 - a29 - a30 - a31;
a11 <- n23 - a21 - a22 - a24 - a26 - a29 - a30 - a31;
a10 <- n25 - a20 - a21 - a25 - a26 - a28 - a29 - a31;
a9 <- n12 - a19 - a20 - a22 - a28 - a29 - a30 - a31;
a8 <- n14 - a18 - a19 - a23 - a27 - a28 - a30 - a31;
a7 <- n15 - a17 - a18 - a20 - a27 - a28 - a29 - a31;
a6 <- n35 - a16 - a17 - a21 - a26 - a27 - a29 - a31;
a5 <- area5 - a6 - a7 - a15 - a16 - a17 - a18 - a25 - a26 - a27 - a28 - a31 - a20 - a29 - a21 - a10;
a4 <- area4 - a13 - a14 - a15 - a16 - a23 - a24 - a25 - a26 - a27 - a28 - a31 - a18 - a19 - a8 - a30;
a3 <- area3 - a21 - a11 - a12 - a13 - a29 - a22 - a23 - a24 - a30 - a31 - a26 - a27 - a16 - a6 - a17;
a2 <- area2 - a9 - a10 - a19 - a20 - a21 - a11 - a28 - a29 - a31 - a22 - a30 - a26 - a25 - a24 - a14;
a1 <- area1 - a7 - a8 - a18 - a17 - a19 - a9 - a27 - a28 - a31 - a20 - a30 - a29 - a22 - a23 - a12;
areas <- c(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31);
}
areas.error <- c(
'a1 <- area1 - a7 - a8 - a18 - a17 - a19 - a9 - a27 - a28 - a31 - a20 - a30 - a29 - a22 - a23 - a12',
'a2 <- area2 - a9 - a10 - a19 - a20 - a21 - a11 - a28 - a29 - a31 - a22 - a30 - a26 - a25 - a24 - a14',
'a3 <- area3 - a21 - a11 - a12 - a13 - a29 - a22 - a23 - a24 - a30 - a31 - a26 - a27 - a16 - a6 - a17',
'a4 <- area4 - a13 - a14 - a15 - a16 - a23 - a24 - a25 - a26 - a27 - a28 - a31 - a18 - a19 - a8 - a30',
'a5 <- area5 - a6 - a7 - a15 - a16 - a17 - a18 - a25 - a26 - a27 - a28 - a31 - a20 - a29 - a21 - a10',
'a6 <- n35 - a16 - a17 - a21 - a26 - a27 - a29 - a31',
'a7 <- n15 - a17 - a18 - a20 - a27 - a28 - a29 - a31',
'a8 <- n14 - a18 - a19 - a23 - a27 - a28 - a30 - a31',
'a9 <- n12 - a19 - a20 - a22 - a28 - a29 - a30 - a31',
'a10 <- n25 - a20 - a21 - a25 - a26 - a28 - a29 - a31',
'a11 <- n23 - a21 - a22 - a24 - a26 - a29 - a30 - a31',
'a12 <- n13 - a17 - a22 - a23 - a27 - a29 - a30 - a31',
'a13 <- n34 - a16 - a23 - a24 - a26 - a27 - a30 - a31',
'a14 <- n24 - a19 - a24 - a25 - a30 - a28 - a26 - a31',
'a15 <- n45 - a18 - a25 - a16 - a28 - a27 - a26 - a31',
'a16 <- n345 - a26 - a27 - a31',
'a17 <- n135 - a27 - a29 - a31',
'a18 <- n145 - a27 - a28 - a31',
'a19 <- n124 - a28 - a30 - a31',
'a20 <- n125 - a28 - a29 - a31',
'a21 <- n235 - a26 - a29 - a31',
'a22 <- n123 - a29 - a30 - a31',
'a23 <- n134 - a27 - a30 - a31',
'a24 <- n234 - a26 - a30 - a31',
'a25 <- n245 - a26 - a28 - a31',
'a26 <- n2345 - a31',
'a27 <- n1345 - a31',
'a28 <- n1245 - a31',
'a29 <- n1235 - a31',
'a30 <- n1234 - a31',
'a31 <- n12345'
);
for (i in 1:length(areas)) {
if (areas[i] < 0) {
flog.error(paste('Impossible:', areas.error[i], 'produces negative area'),name='VennDiagramLogger')
stop(paste('Impossible:', areas.error[i], 'produces negative area'));
}
}
if(length(cex.prop) > 0){
if(length(cex.prop) != 1) {
flog.error('Value passed to cex.prop is not length 1',name='VennDiagramLogger')
stop('Value passed to cex.prop is not length 1')
}
func = cex.prop
if(class(cex.prop) != 'function'){
if(cex.prop == 'lin'){
func = function(x) x
}
else if(cex.prop == 'log10'){
func = log10
}
else flog.error(paste0('Unknown value passed to cex.prop: ', cex.prop),name='VennDiagramLogger')
stop(paste0('Unknown value passed to cex.prop: ', cex.prop))
}
maxArea = max(areas)
for(i in 1:length(areas)){
cex[i] = cex[i] * func(areas[i]) / func(maxArea)
if(cex[i] <= 0) stop(paste0('Error in rescaling of area labels: the label of area ',
i, ' is less than or equal to zero'))
}
}
grob.list <- gList();
dist <- 0.13;
a <- 0.24;
b <- 0.46;
init.angle <- -20;
ellipse.positions <- matrix(
nrow = 5,
ncol = 3
);
colnames(ellipse.positions) <- c('x', 'y', 'rotation');
ellipse.positions[1,] <- c(
0.5 + dist * sin(init.angle * pi / 180),
0.5 + dist * cos(init.angle * pi / 180),
0
);
ellipse.positions[2,] <- c(
0.5 - dist * cos((288 + init.angle - 270) * pi / 180),
0.5 + dist * sin((288 + init.angle - 270) * pi / 180),
-110
);
ellipse.positions[3,] <- c(
0.5 - dist * sin((216 + init.angle - 180) * pi / 180),
0.5 - dist * cos((216 + init.angle - 180) * pi / 180),
145
);
ellipse.positions[4,] <- c(
0.5 + dist * sin((180 - 144 - init.angle) * pi / 180),
0.5 - dist * cos((180 - 144 - init.angle) * pi / 180),
35
);
ellipse.positions[5,] <- c(
0.5 + dist * cos((init.angle + 72 - 90) * pi / 180),
0.5 - dist * sin((init.angle + 72 - 90) * pi / 180),
-72.5
);
for (i in 1:5) {
grob.list <- gList(
grob.list,
VennDiagram::ellipse(
x = ellipse.positions[i,'x'],
y = ellipse.positions[i,'y'],
a = a,
b = b,
rotation = ellipse.positions[i,'rotation'],
gp = gpar(
lty = 0,
fill = fill[i],
alpha = alpha[i]
)
)
);
}
for (i in 1:5) {
grob.list <- gList(
grob.list,
VennDiagram::ellipse(
x = ellipse.positions[i,'x'],
y = ellipse.positions[i,'y'],
a = a,
b = b,
rotation = ellipse.positions[i,'rotation'],
gp = gpar(
lwd = lwd[i],
lty = lty[i],
col = col[i],
fill = 'transparent'
)
)
);
}
label.matrix <- matrix(
nrow = 31,
ncol = 3
);
colnames(label.matrix) <- c('label', 'x', 'y');
label.matrix[ 1,] <- c(a1, 0.4555, 0.9322);
label.matrix[ 2,] <- c(a2, 0.0800, 0.6000);
label.matrix[ 3,] <- c(a3, 0.3000, 0.1000);
label.matrix[ 4,] <- c(a4, 0.7900, 0.1700);
label.matrix[ 5,] <- c(a5, 0.9000, 0.6800);
label.matrix[ 6,] <- c(a6, 0.7400, 0.6950);
label.matrix[ 7,] <- c(a7, 0.6300, 0.8050);
label.matrix[ 8,] <- c(a8, 0.4000, 0.7950);
label.matrix[ 9,] <- c(a9, 0.2550, 0.7150);
label.matrix[10,] <- c(a10, 0.1930, 0.4800);
label.matrix[11,] <- c(a11, 0.2250, 0.3330);
label.matrix[12,] <- c(a12, 0.4200, 0.2050);
label.matrix[13,] <- c(a13, 0.5720, 0.1800);
label.matrix[14,] <- c(a14, 0.7530, 0.3200);
label.matrix[15,] <- c(a15, 0.8230, 0.4700);
label.matrix[16,] <- c(a16, 0.7470, 0.5820);
label.matrix[17,] <- c(a17, 0.6620, 0.7500);
label.matrix[18,] <- c(a18, 0.4880, 0.7610);
label.matrix[19,] <- c(a19, 0.3230, 0.7370);
label.matrix[20,] <- c(a20, 0.2530, 0.5730);
label.matrix[21,] <- c(a21, 0.2250, 0.3950);
label.matrix[22,] <- c(a22, 0.3550, 0.2900);
label.matrix[23,] <- c(a23, 0.5150, 0.2050);
label.matrix[24,] <- c(a24, 0.6550, 0.2900);
label.matrix[25,] <- c(a25, 0.7830, 0.4200);
label.matrix[26,] <- c(a26, 0.7200, 0.4450);
label.matrix[27,] <- c(a27, 0.6050, 0.7010);
label.matrix[28,] <- c(a28, 0.3420, 0.6680);
label.matrix[29,] <- c(a29, 0.2940, 0.4100);
label.matrix[30,] <- c(a30, 0.5220, 0.2730);
label.matrix[31,] <- c(a31, 0.5000, 0.5000);
processedLabels <- rep('',length(label.matrix[,'label']));
if(print.mode[1] == 'percent'){
processedLabels <- paste(signif(label.matrix[,'label']/sum(label.matrix[,'label'])*100,digits=sigdigs),'%',sep='');
if(isTRUE(print.mode[2] == 'raw'))
{
processedLabels <- paste(processedLabels,'\n(',label.matrix[,'label'],')',sep='');
}
}
if(print.mode[1] == 'raw'){
processedLabels <- label.matrix[,'label'];
if(isTRUE(print.mode[2] == 'percent'))
{
processedLabels <- paste(processedLabels,'\n(',paste(signif(label.matrix[,'label']/sum(label.matrix[,'label'])*100,digits=sigdigs),'%)',sep=''),sep='');
}
}
for (i in 1:nrow(label.matrix)) {
tmp <- textGrob(
label = processedLabels[i],
x = label.matrix[i,'x'],
y = label.matrix[i,'y'],
gp = gpar(
col = label.col[i],
cex = cex[i],
fontface = fontface[i],
fontfamily = fontfamily[i]
)
);
grob.list <- gList(grob.list, tmp);
}
cat.pos.x <- c(0.4555, 0.08, 0.3, 0.79, 0.90);
cat.pos.y <- c(0.9322, 0.60, 0.1, 0.17, 0.68);
for (i in 1:5) {
this.cat.pos <- find.cat.pos(
x = cat.pos.x[i],
y = cat.pos.y[i],
pos = cat.pos[i],
dist = cat.dist[i]
);
grob.list <- gList(
grob.list,
textGrob(
label = category[i],
x = this.cat.pos$x,
y = this.cat.pos$y,
just = cat.just[[i]],
gp = gpar(
col = cat.col[i],
cex = cat.cex[i],
fontface = cat.fontface[i],
fontfamily = cat.fontfamily[i]
)
)
);
}
grob.list <- VennDiagram::adjust.venn(VennDiagram::rotate.venn.degrees(grob.list, rotation.degree, rotation.centre[1], rotation.centre[2]), ...);
if (ind) { grid.draw(grob.list); }
return(grob.list);
} |
test_that("decoding works", {
expect_identical(
decode_ids(c(
"32013030-2d30-3033-3338-3733fa30c4fa",
"NA",
"00-0033873",
"NA",
"32013030-2d30-3032-3739-3434d4d3846d"
)),
c("00-0033873", NA_character_, "00-0033873", NA_character_, "00-0027944")
)
}) |
NULL
"election_turnout" |
year_quarter_day <- function(year,
quarter = NULL,
day = NULL,
hour = NULL,
minute = NULL,
second = NULL,
subsecond = NULL,
...,
start = NULL,
subsecond_precision = NULL) {
check_dots_empty()
start <- quarterly_validate_start(start)
if (is_null(quarter)) {
precision <- PRECISION_YEAR
fields <- list(year = year)
} else if (is_null(day)) {
precision <- PRECISION_QUARTER
fields <- list(year = year, quarter = quarter)
} else if (is_null(hour)) {
precision <- PRECISION_DAY
fields <- list(year = year, quarter = quarter, day = day)
} else if (is_null(minute)) {
precision <- PRECISION_HOUR
fields <- list(year = year, quarter = quarter, day = day, hour = hour)
} else if (is_null(second)) {
precision <- PRECISION_MINUTE
fields <- list(year = year, quarter = quarter, day = day, hour = hour, minute = minute)
} else if (is_null(subsecond)) {
precision <- PRECISION_SECOND
fields <- list(year = year, quarter = quarter, day = day, hour = hour, minute = minute, second = second)
} else {
precision <- calendar_validate_subsecond_precision(subsecond_precision)
fields <- list(year = year, quarter = quarter, day = day, hour = hour, minute = minute, second = second, subsecond = subsecond)
}
if (is_last(fields$day)) {
fields$day <- 1L
last <- TRUE
} else {
last <- FALSE
}
fields <- vec_recycle_common(!!!fields)
fields <- vec_cast_common(!!!fields, .to = integer())
fields <- collect_year_quarter_day_fields(fields, precision, start)
names <- NULL
out <- new_year_quarter_day_from_fields(fields, precision, start, names)
if (last) {
out <- set_day(out, "last")
}
out
}
vec_proxy.clock_year_quarter_day <- function(x, ...) {
.Call(`_clock_clock_rcrd_proxy`, x)
}
vec_restore.clock_year_quarter_day <- function(x, to, ...) {
.Call(`_clock_year_quarter_day_restore`, x, to)
}
format.clock_year_quarter_day <- function(x, ...) {
out <- format_year_quarter_day_cpp(x, calendar_precision_attribute(x), quarterly_start(x))
names(out) <- names(x)
out
}
vec_ptype_full.clock_year_quarter_day <- function(x, ...) {
start <- quarterly_start(x)
start <- quarterly_start_prettify(start, abbreviate = FALSE)
class <- paste0("year_quarter_day<", start, ">")
calendar_ptype_full(x, class)
}
vec_ptype_abbr.clock_year_quarter_day <- function(x, ...) {
start <- quarterly_start(x)
start <- quarterly_start_prettify(start, abbreviate = TRUE)
class <- paste0("yqd<", start, ">")
calendar_ptype_abbr(x, class)
}
is_year_quarter_day <- function(x) {
inherits(x, "clock_year_quarter_day")
}
vec_ptype.clock_year_quarter_day <- function(x, ...) {
names <- NULL
precision <- calendar_precision_attribute(x)
start <- quarterly_start(x)
f <- integer()
fields <- switch(
precision + 1L,
list(year = f),
list(year = f, quarter = f),
abort("Internal error: Invalid precision"),
abort("Internal error: Invalid precision"),
list(year = f, quarter = f, day = f),
list(year = f, quarter = f, day = f, hour = f),
list(year = f, quarter = f, day = f, hour = f, minute = f),
list(year = f, quarter = f, day = f, hour = f, minute = f, second = f),
list(year = f, quarter = f, day = f, hour = f, minute = f, second = f, subsecond = f),
list(year = f, quarter = f, day = f, hour = f, minute = f, second = f, subsecond = f),
list(year = f, quarter = f, day = f, hour = f, minute = f, second = f, subsecond = f),
abort("Internal error: Invalid precision.")
)
new_year_quarter_day_from_fields(fields, precision, start, names)
}
vec_ptype2.clock_year_quarter_day.clock_year_quarter_day <- function(x, y, ...) {
if (quarterly_start(x) != quarterly_start(y)) {
stop_incompatible_type(x, y, ..., details = "Can't combine quarterly types with different `start`s.")
}
ptype2_calendar_and_calendar(x, y, ...)
}
vec_cast.clock_year_quarter_day.clock_year_quarter_day <- function(x, to, ...) {
if (quarterly_start(x) != quarterly_start(to)) {
stop_incompatible_cast(x, to, ..., details = "Can't cast between quarterly types with different `start`s.")
}
cast_calendar_to_calendar(x, to, ...)
}
calendar_is_valid_precision.clock_year_quarter_day <- function(x, precision) {
year_quarter_day_is_valid_precision(precision)
}
year_quarter_day_is_valid_precision <- function(precision) {
if (!is_valid_precision(precision)) {
FALSE
} else if (precision == PRECISION_YEAR || precision == PRECISION_QUARTER) {
TRUE
} else if (precision >= PRECISION_DAY && precision <= PRECISION_NANOSECOND) {
TRUE
} else {
FALSE
}
}
invalid_detect.clock_year_quarter_day <- function(x) {
invalid_detect_year_quarter_day_cpp(x, calendar_precision_attribute(x), quarterly_start(x))
}
invalid_any.clock_year_quarter_day <- function(x) {
invalid_any_year_quarter_day_cpp(x, calendar_precision_attribute(x), quarterly_start(x))
}
invalid_count.clock_year_quarter_day <- function(x) {
invalid_count_year_quarter_day_cpp(x, calendar_precision_attribute(x), quarterly_start(x))
}
invalid_resolve.clock_year_quarter_day <- function(x, ..., invalid = NULL) {
check_dots_empty()
precision <- calendar_precision_attribute(x)
start <- quarterly_start(x)
invalid <- validate_invalid(invalid)
fields <- invalid_resolve_year_quarter_day_cpp(x, precision, start, invalid)
new_year_quarter_day_from_fields(fields, precision, start, names = names(x))
}
NULL
get_year.clock_year_quarter_day <- function(x) {
field_year(x)
}
get_quarter.clock_year_quarter_day <- function(x) {
calendar_require_minimum_precision(x, PRECISION_QUARTER, "get_quarter")
field_quarter(x)
}
get_day.clock_year_quarter_day <- function(x) {
calendar_require_minimum_precision(x, PRECISION_DAY, "get_day")
field_day(x)
}
get_hour.clock_year_quarter_day <- function(x) {
calendar_require_minimum_precision(x, PRECISION_HOUR, "get_hour")
field_hour(x)
}
get_minute.clock_year_quarter_day <- function(x) {
calendar_require_minimum_precision(x, PRECISION_MINUTE, "get_minute")
field_minute(x)
}
get_second.clock_year_quarter_day <- function(x) {
calendar_require_minimum_precision(x, PRECISION_SECOND, "get_second")
field_second(x)
}
get_millisecond.clock_year_quarter_day <- function(x) {
calendar_require_precision(x, PRECISION_MILLISECOND, "get_millisecond")
field_subsecond(x)
}
get_microsecond.clock_year_quarter_day <- function(x) {
calendar_require_precision(x, PRECISION_MICROSECOND, "get_microsecond")
field_subsecond(x)
}
get_nanosecond.clock_year_quarter_day <- function(x) {
calendar_require_precision(x, PRECISION_NANOSECOND, "get_nanosecond")
field_subsecond(x)
}
NULL
set_year.clock_year_quarter_day <- function(x, value, ...) {
check_dots_empty()
set_field_year_quarter_day(x, value, "year")
}
set_quarter.clock_year_quarter_day <- function(x, value, ...) {
check_dots_empty()
calendar_require_minimum_precision(x, PRECISION_YEAR, "set_quarter")
set_field_year_quarter_day(x, value, "quarter")
}
set_day.clock_year_quarter_day <- function(x, value, ...) {
check_dots_empty()
calendar_require_minimum_precision(x, PRECISION_QUARTER, "set_day")
set_field_year_quarter_day(x, value, "day")
}
set_hour.clock_year_quarter_day <- function(x, value, ...) {
check_dots_empty()
calendar_require_minimum_precision(x, PRECISION_DAY, "set_hour")
set_field_year_quarter_day(x, value, "hour")
}
set_minute.clock_year_quarter_day <- function(x, value, ...) {
check_dots_empty()
calendar_require_minimum_precision(x, PRECISION_HOUR, "set_minute")
set_field_year_quarter_day(x, value, "minute")
}
set_second.clock_year_quarter_day <- function(x, value, ...) {
check_dots_empty()
calendar_require_minimum_precision(x, PRECISION_MINUTE, "set_second")
set_field_year_quarter_day(x, value, "second")
}
set_millisecond.clock_year_quarter_day <- function(x, value, ...) {
check_dots_empty()
calendar_require_any_of_precisions(x, c(PRECISION_SECOND, PRECISION_MILLISECOND), "set_millisecond")
set_field_year_quarter_day(x, value, "millisecond")
}
set_microsecond.clock_year_quarter_day <- function(x, value, ...) {
check_dots_empty()
calendar_require_any_of_precisions(x, c(PRECISION_SECOND, PRECISION_MICROSECOND), "set_microsecond")
set_field_year_quarter_day(x, value, "microsecond")
}
set_nanosecond.clock_year_quarter_day <- function(x, value, ...) {
check_dots_empty()
calendar_require_any_of_precisions(x, c(PRECISION_SECOND, PRECISION_NANOSECOND), "set_nanosecond")
set_field_year_quarter_day(x, value, "nanosecond")
}
set_field_year_quarter_day <- function(x, value, component) {
if (is_last(value) && identical(component, "day")) {
return(set_field_year_quarter_day_last(x))
}
start <- quarterly_start(x)
precision_fields <- calendar_precision_attribute(x)
precision_value <- year_quarter_day_component_to_precision(component)
precision_out <- precision_common2(precision_fields, precision_value)
value <- vec_cast(value, integer(), x_arg = "value")
args <- vec_recycle_common(x = x, value = value)
x <- args$x
value <- args$value
result <- set_field_year_quarter_day_cpp(x, value, precision_fields, precision_value, start)
fields <- result$fields
field <- year_quarter_day_component_to_field(component)
fields[[field]] <- result$value
new_year_quarter_day_from_fields(fields, precision_out, start, names = names(x))
}
set_field_year_quarter_day_last <- function(x) {
start <- quarterly_start(x)
precision_fields <- calendar_precision_attribute(x)
precision_out <- precision_common2(precision_fields, PRECISION_DAY)
result <- set_field_year_quarter_day_last_cpp(x, precision_fields, start)
fields <- result$fields
fields[["day"]] <- result$value
new_year_quarter_day_from_fields(fields, precision_out, start, names = names(x))
}
calendar_name.clock_year_quarter_day <- function(x) {
"year_quarter_day"
}
year_quarter_day_component_to_precision <- function(component) {
switch(
component,
year = PRECISION_YEAR,
quarter = PRECISION_QUARTER,
day = PRECISION_DAY,
hour = PRECISION_HOUR,
minute = PRECISION_MINUTE,
second = PRECISION_SECOND,
millisecond = PRECISION_MILLISECOND,
microsecond = PRECISION_MICROSECOND,
nanosecond = PRECISION_NANOSECOND,
abort("Internal error: Unknown component name.")
)
}
year_quarter_day_component_to_field <- function(component) {
switch (
component,
year = component,
quarter = component,
day = component,
hour = component,
minute = component,
second = component,
millisecond = "subsecond",
microsecond = "subsecond",
nanosecond = "subsecond",
abort("Internal error: Unknown component name.")
)
}
vec_arith.clock_year_quarter_day <- function(op, x, y, ...) {
UseMethod("vec_arith.clock_year_quarter_day", y)
}
vec_arith.clock_year_quarter_day.MISSING <- function(op, x, y, ...) {
arith_calendar_and_missing(op, x, y, ...)
}
vec_arith.clock_year_quarter_day.clock_year_quarter_day <- function(op, x, y, ...) {
arith_calendar_and_calendar(op, x, y, ..., calendar_minus_calendar_fn = year_quarter_day_minus_year_quarter_day)
}
vec_arith.clock_year_quarter_day.clock_duration <- function(op, x, y, ...) {
arith_calendar_and_duration(op, x, y, ...)
}
vec_arith.clock_duration.clock_year_quarter_day <- function(op, x, y, ...) {
arith_duration_and_calendar(op, x, y, ...)
}
vec_arith.clock_year_quarter_day.numeric <- function(op, x, y, ...) {
arith_calendar_and_numeric(op, x, y, ...)
}
vec_arith.numeric.clock_year_quarter_day <- function(op, x, y, ...) {
arith_numeric_and_calendar(op, x, y, ...)
}
year_quarter_day_minus_year_quarter_day <- function(op, x, y, ...) {
args <- vec_recycle_common(x = x, y = y)
args <- vec_cast_common(!!!args)
x <- args$x
y <- args$y
names <- names_common(x, y)
start <- quarterly_start(x)
precision <- calendar_precision_attribute(x)
if (precision > PRECISION_QUARTER) {
stop_incompatible_op(op, x, y, ...)
}
fields <- year_quarter_day_minus_year_quarter_day_cpp(x, y, precision, start)
new_duration_from_fields(fields, precision, names = names)
}
NULL
add_years.clock_year_quarter_day <- function(x, n, ...) {
year_quarter_day_plus_duration(x, n, PRECISION_YEAR)
}
add_quarters.clock_year_quarter_day <- function(x, n, ...) {
calendar_require_minimum_precision(x, PRECISION_QUARTER, "add_quarters")
year_quarter_day_plus_duration(x, n, PRECISION_QUARTER)
}
year_quarter_day_plus_duration <- function(x, n, precision_n) {
start <- quarterly_start(x)
precision_fields <- calendar_precision_attribute(x)
n <- duration_collect_n(n, precision_n)
args <- vec_recycle_common(x = x, n = n)
x <- args$x
n <- args$n
names <- names_common(x, n)
fields <- year_quarter_day_plus_duration_cpp(x, n, precision_fields, precision_n, start)
new_year_quarter_day_from_fields(fields, precision_fields, start, names = names)
}
as_year_quarter_day <- function(x, ..., start = NULL) {
UseMethod("as_year_quarter_day")
}
as_year_quarter_day.default <- function(x, ..., start = NULL) {
stop_clock_unsupported_conversion(x, "clock_year_quarter_day")
}
as_year_quarter_day.clock_year_quarter_day <- function(x, ..., start = NULL) {
check_dots_empty()
if (is_null(start)) {
return(x)
}
start <- quarterly_validate_start(start)
x_start <- quarterly_start(x)
if (x_start == start) {
return(x)
}
as_year_quarter_day(as_sys_time(x), start = start)
}
as_sys_time.clock_year_quarter_day <- function(x) {
calendar_require_all_valid(x)
start <- quarterly_start(x)
precision <- calendar_precision_attribute(x)
fields <- as_sys_time_year_quarter_day_cpp(x, precision, start)
new_sys_time_from_fields(fields, precision, clock_rcrd_names(x))
}
as_naive_time.clock_year_quarter_day <- function(x) {
as_naive_time(as_sys_time(x))
}
as.character.clock_year_quarter_day <- function(x, ...) {
format(x)
}
calendar_group.clock_year_quarter_day <- function(x, precision, ..., n = 1L) {
n <- validate_calendar_group_n(n)
x <- calendar_narrow(x, precision)
precision <- validate_precision_string(precision)
if (precision == PRECISION_YEAR) {
value <- get_year(x)
value <- group_component0(value, n)
x <- set_year(x, value)
return(x)
}
if (precision == PRECISION_QUARTER) {
value <- get_quarter(x)
value <- group_component1(value, n)
x <- set_quarter(x, value)
return(x)
}
if (precision == PRECISION_DAY) {
value <- get_day(x)
value <- group_component1(value, n)
x <- set_day(x, value)
return(x)
}
x <- calendar_group_time(x, n, precision)
x
}
calendar_narrow.clock_year_quarter_day <- function(x, precision) {
precision <- validate_precision_string(precision)
start <- quarterly_start(x)
out_fields <- list()
x_fields <- unclass(x)
if (precision >= PRECISION_YEAR) {
out_fields[["year"]] <- x_fields[["year"]]
}
if (precision >= PRECISION_QUARTER) {
out_fields[["quarter"]] <- x_fields[["quarter"]]
}
if (precision >= PRECISION_DAY) {
out_fields[["day"]] <- x_fields[["day"]]
}
out_fields <- calendar_narrow_time(out_fields, precision, x_fields)
new_year_quarter_day_from_fields(out_fields, precision, start, names = names(x))
}
calendar_widen.clock_year_quarter_day <- function(x, precision) {
x_precision <- calendar_precision_attribute(x)
precision <- validate_precision_string(precision)
if (precision >= PRECISION_QUARTER && x_precision < PRECISION_QUARTER) {
x <- set_quarter(x, 1L)
}
if (precision >= PRECISION_DAY && x_precision < PRECISION_DAY) {
x <- set_day(x, 1L)
}
x <- calendar_widen_time(x, x_precision, precision)
x
}
NULL
calendar_start.clock_year_quarter_day <- function(x, precision) {
x_precision <- calendar_precision_attribute(x)
precision <- validate_precision_string(precision)
calendar_start_end_checks(x, x_precision, precision, "start")
if (precision <= PRECISION_YEAR && x_precision > PRECISION_YEAR) {
x <- set_quarter(x, 1L)
}
if (precision <= PRECISION_QUARTER && x_precision > PRECISION_QUARTER) {
x <- set_day(x, 1L)
}
x <- calendar_start_time(x, x_precision, precision)
x
}
calendar_end.clock_year_quarter_day <- function(x, precision) {
x_precision <- calendar_precision_attribute(x)
precision <- validate_precision_string(precision)
calendar_start_end_checks(x, x_precision, precision, "end")
if (precision <= PRECISION_YEAR && x_precision > PRECISION_YEAR) {
x <- set_quarter(x, 4L)
}
if (precision <= PRECISION_QUARTER && x_precision > PRECISION_QUARTER) {
x <- set_day(x, "last")
}
x <- calendar_end_time(x, x_precision, precision)
x
}
calendar_count_between.clock_year_quarter_day <- function(start,
end,
precision,
...,
n = 1L) {
NextMethod()
}
calendar_count_between_standardize_precision_n.clock_year_quarter_day <- function(x,
precision,
n) {
precision_int <- validate_precision_string(precision)
allowed_precisions <- c(PRECISION_YEAR, PRECISION_QUARTER)
if (!(precision_int %in% allowed_precisions)) {
abort("`precision` must be one of: 'year', 'quarter'.")
}
list(precision = precision, n = n)
}
calendar_count_between_compute.clock_year_quarter_day <- function(start,
end,
precision) {
precision <- validate_precision_string(precision)
if (precision == PRECISION_YEAR) {
out <- get_year(end) - get_year(start)
return(out)
}
if (precision == PRECISION_QUARTER) {
out <- (get_year(end) - get_year(start)) * 4L
out <- out + (get_quarter(end) - get_quarter(start))
return(out)
}
abort("Internal error: `precision` should be 'year' or 'quarter' at this point.")
}
calendar_count_between_proxy_compare.clock_year_quarter_day <- function(start,
end,
precision) {
precision <- validate_precision_string(precision)
start <- vec_proxy_compare(start)
end <- vec_proxy_compare(end)
if (precision >= PRECISION_YEAR) {
start$year <- NULL
end$year <- NULL
}
if (precision >= PRECISION_QUARTER) {
start$quarter <- NULL
end$quarter <- NULL
}
list(start = start, end = end)
}
seq.clock_year_quarter_day <- function(from,
to = NULL,
by = NULL,
length.out = NULL,
along.with = NULL,
...) {
precision <- calendar_precision_attribute(from)
if (precision > PRECISION_QUARTER) {
abort("`from` must be 'year' or 'quarter' precision.")
}
seq_impl(
from = from,
to = to,
by = by,
length.out = length.out,
along.with = along.with,
precision = precision,
...
)
}
quarterly_start <- function(x) {
attr(x, "start", exact = TRUE)
}
quarterly_start_prettify <- function(start, ..., abbreviate = FALSE) {
check_dots_empty()
if (abbreviate) {
month.abb[start]
} else {
month.name[start]
}
}
quarterly_validate_start <- function(start) {
if (is_null(start)) {
return(1L)
}
start <- vec_cast(start, integer(), x_arg = "start")
if (!is_number(start)) {
abort("`start` must be a single number.")
}
if (start < 1L || start > 12L) {
abort("`start` must be a number between [1, 12].")
}
start
} |
GenerateHTMLQuestion <-
function (character = NULL, file = NULL, frame.height = 450) {
if (!is.null(character)) {
html <- paste0(character, collapse = "\n")
} else if (!is.null(file)) {
html <- paste0(readLines(file, warn = FALSE), collapse="\n")
}
string <- paste0(
"<HTMLQuestion xmlns=\"http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2011-11-11/HTMLQuestion.xsd\"><HTMLContent><![CDATA[", html, "]]></HTMLContent><FrameHeight>",frame.height,"</FrameHeight></HTMLQuestion>")
return(structure(list(xml.parsed = XML::xmlParse(string),
string = string),
class='HTMLQuestion'))
} |
context("test_get_ER2.R")
test_that("get_ER2 agrees with version 0.3", with(simulate(sparse = TRUE), {
original.res = readRDS('ER2_original_res.rds')
scaledX = set_X_attributes(X)
scaledX.sparse = set_X_attributes(X.sparse)
s$Xr = colSums(compute_MXt(s$alpha*s$mu, scaledX))
dense.res = get_ER2(scaledX, y, s)
sparse.res = get_ER2(scaledX.sparse, y, s)
expect_equal(dense.res, original.res)
expect_equal(sparse.res, original.res)
})) |
expected <- eval(parse(text="c(\"1\", \"2\", NA)"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(2L, 1L, 3L), .Label = c(\"1\", \"2\", NA), class = c(\"ordered\", \"factor\")), \"levels\")"));
do.call(`attr`, argv);
}, o=expected); |
HPDinterval.stFit = function(stFit, burn = 1, prob = .95) {
res = lapply(stFit$parameters$samples, function(s) {
r = s[-(1:burn),]
if(length(r)>1) {
HPDinterval(mcmc(as.matrix(r)))
} else {
NULL
}
})
if(!is.null(stFit$parameters$beta.names)) {
rownames(res$beta) = stFit$parameters$beta.names
}
res
} |
iterators::nextElem
itertools::hasNext
prevElem <- function(obj, ...)
{
UseMethod("prevElem")
}
hasPrev <- function(obj, ...)
{
UseMethod("hasPrev")
}
getFirst <- function(obj, ...)
{
UseMethod("getFirst")
}
getLast <- function(obj, ...)
{
UseMethod("getLast")
} |
eform <- function (object, ...)
UseMethod("eform")
eform.default <- function(object, parm, level = 0.95, method=c("Delta","Profile"), name="exp(beta)", ...) {
method <- match.arg(method)
if (missing(parm))
parm <- TRUE
if (method == "Profile") class(object) <- c(class(object),"glm")
estfun <- switch(method, Profile = confint, Delta = stats::confint.default)
val <- exp(cbind(coef = coef(object), estfun(object, level = level)))
colnames(val) <- c(name,colnames(val)[-1])
val[parm, ]
}
irr <- function(..., name = "IRR") eform(..., name = name)
or <- function(..., name = "OR") eform(..., name = name) |
get_crime_data <- function (years = NULL, cities = NULL, type = "sample",
cache = TRUE, quiet = FALSE, output = "tbl") {
stopifnot(type %in% c("core", "extended", "sample"))
stopifnot(is.character(cities) | is.null(cities))
stopifnot(is.integer(as.integer(years)) | is.null(years))
stopifnot(is.logical(quiet))
stopifnot(output %in% c("tbl", "sf"))
urls <- get_file_urls(quiet = quiet)
if (is.null(years)) {
years <- max(urls$year)
}
if (is.null(cities)) {
cities <- "all cities"
}
years <- as.integer(years)
if (!all(years %in% unique(urls$year))) {
stop("One or more of the specified years does not correspond to a year of ",
"data available in the Open Crime Database. For details of available ",
"data, see <https://osf.io/zyaqn/>. Data for the current year are ",
"not available because the database is updated annually.")
}
if (cities[1] != "all" & !all(cities %in% unique(urls$city))) {
stop("One or more of the specified cities does not correspond to a city ",
"for which data are available in the Open Crime Database. Check your ",
"spelling or for details of available data, see ",
"<https://osf.io/zyaqn/>.")
}
urls <- urls[urls$data_type == type & urls$year %in% years &
urls$city %in% cities, ]
if (nrow(urls) == 0) {
stop("The Crime Open Database does not contain data for any of the ",
"specified years for the specified cities.")
} else {
throw_away <- expand.grid(year = years, city = cities) %>%
apply(1, function (x) {
if (nrow(urls[urls$year == x[[1]] & urls$city == x[[2]], ]) == 0 &
quiet == FALSE) {
warning("Data are not available for crimes in ", x[[2]], " in ",
x[[1]], call. = FALSE, immediate. = TRUE,
noBreaks. = TRUE)
}
})
rm(throw_away)
}
hash <- digest::digest(c(type, years, cities))
cache_file <- tempfile(
pattern = paste0("crimedata_", hash, "_"),
fileext = ".Rds"
)
cache_files <- dir(tempdir(), pattern = hash, full.names = TRUE)
if (cache == FALSE & length(cache_files) > 0) {
lapply(cache_files, file.remove)
message("Deleting cached data and re-downloading from server.",
appendLF = TRUE)
}
if (cache == TRUE & length(cache_files) > 0) {
if (quiet == FALSE) {
message("Loading cached data from previous request in this session. To ",
"download data again, call get_crime_data() with cache = FALSE.",
appendLF = TRUE)
}
crime_data <- readRDS(cache_files[1])
} else {
crime_data <- urls %>%
purrr::transpose(.names = paste0(.$data_type, .$city, .$year)) %>%
purrr::map(function (x) {
if (quiet == FALSE) {
message("Downloading ", x[["data_type"]], " data for ", x[["city"]],
" in ", x[["year"]], appendLF = TRUE)
}
temp_file <- tempfile(pattern = "code_data_", fileext = ".Rds")
httr::GET(x[["file_url"]], progress(type = "down")) %>%
httr::content(as = "raw") %>%
writeBin(temp_file)
this_crime_data <- readRDS(temp_file)
file.remove(temp_file)
this_crime_data
}) %>%
dplyr::bind_rows() %>%
dplyr::arrange(.data$uid)
saveRDS(crime_data, cache_file)
}
if (output == "sf") {
crime_data <- sf::st_as_sf(crime_data, coords = c("longitude", "latitude"),
crs = 4326, remove = FALSE)
}
crime_data <- dplyr::mutate_at(
crime_data,
vars(one_of(c("city_name", "offense_code", "offense_type", "offense_group",
"offense_against", "location_type", "location_category"))),
as.factor
)
crime_data <- dplyr::mutate_at(
crime_data,
vars("date_single"),
as.POSIXct, format = "%Y-%m-%d %H:%M"
)
if ("date_start" %in% names(crime_data) | "date_end" %in% names(crime_data)) {
crime_data <- dplyr::mutate_at(
crime_data,
vars(one_of(c("date_start", "date_end"))),
as.POSIXct, format = "%Y-%m-%d %H:%M"
)
}
crime_data
} |
setClassUnion("allowedDist", c("normalDist", "logNormalDist", "gammaDist", "studentDist", "logisticDist"))
setClassUnion("allowedFitDist", c("fitNormalDist", "fitLogNormalDist", "fitGammaDist", "fitStudentDist", "fitLogisticDist", "undefined", "fitUserDefinedDist")) |
mice.impute.myfunc <- function (y, ry, x, wy = NULL, ...)
{
if (is.null(wy))
wy <- !ry
aug <- augment(y, ry, x, wy)
x <- aug$x
y <- aug$y
ry <- aug$ry
wy <- aug$wy
w <- aug$w
x <- cbind(1, as.matrix(x))
expr <- expression(glm.fit(x = x[ry, , drop = FALSE], y = y[ry],
family = quasibinomial(link = logit), weights = w[ry],
control = list(maxit=1000)))
fit <- eval(expr)
fit.sum <- summary.glm(fit)
beta <- coef(fit)
rv <- t(chol(sym(fit.sum$cov.unscaled)))
beta.star <- beta + rv %*% rnorm(ncol(rv))
p <- 1/(1 + exp(-(x[wy, , drop = FALSE] %*% beta.star)))
vec <- (runif(nrow(p)) <= p)
vec[vec] <- 1
if (is.factor(y)) {
vec <- factor(vec, c(0, 1), levels(y))
}
return(vec)
} |
getLastShortSelling=function()
{
domain="https://www.hkex.com.hk/"
webpage="eng/stat/smstat/ssturnover/ncms/ASHTMAIN.HTM"
argument=""
urlLink=paste(domain,webpage,argument,sep="")
page= RCurl::getURL(urlLink)
hp=XML::htmlParse(page)
x <- XML::xpathApply(hp,"//pre")
s=x[[1]][[1]][[1]]
xs=XML::xmlValue(s)
sDate=substr(xs, regexpr("TRADING DATE", xs)+15,regexpr("TRADING DATE", xs)+15+10)
sDate=as.Date(sDate,"%d %b %Y")
skip=function(xs,n, pattern)
{
for ( i in 1:n)
{
xs=substr(xs, regexpr(pattern, xs)+nchar(pattern), nchar(xs))
}
return (xs)
}
xs=skip(xs,7, "\r\n")
f=function(x) !is.na(as.numeric(x))
df=data.frame()
for ( i in 1:2000)
{
code=substr(xs, 1, 7)
code=gsub(" ","", code)
if (f(code)==FALSE) break
cname=substr(xs, 10, 30)
to.sh=substr(xs, 31, 41)
to.val=substr(xs, 42, 56)
df=rbind(df, data.frame(date=sDate, code,cname,to.sh, to.val))
xs=skip(xs,1, "\r\n")
}
df$to.sh=gsub(",","", df$to.sh)
df$to.val=gsub(",","", df$to.val)
return(df)
} |
implicativestat <- function(x, y, type="intensity", resid="standard") {
if (!(type %in% c("intensity", "indice"))) {
stop("type should be intensity or indice")
}
if (!(resid %in% c("standard", "deviance", "Freeman-Tukey", "adjusted"))) {
stop("resid should be one of standard, deviance, Freeman-Tukey or ajusted")
}
x <- factor(x)
if (length(levels(x)==1)) x <- factor(x, levels=c("0","1"))
y <- factor(y)
if (length(levels(y)==1)) y <- factor(y, levels=c("0","1"))
xgrp <- levels(x)
ygrp <- levels(y)
result <- matrix(0, nrow=length(xgrp), ncol=length(ygrp))
n <- length(x)
rownames(result) <- xgrp
colnames(result) <- ygrp
for (i in 1:length(xgrp)) {
condi <- x==xgrp[i]
for (j in 1:length(ygrp)) {
condj <- y==ygrp[j]
Nnbj <- sum((condi)&!condj)
Nexpnbj <- sum(condi)*sum(!condj)/n
if (resid=="standard") {
indice <- (Nnbj-Nexpnbj)/sqrt(Nexpnbj)
}
else if (resid=="deviance") {
indice <- sign(Nnbj-Nexpnbj)*sqrt(abs(2*Nnbj*log(Nnbj/Nexpnbj)))
}
else if (resid=="Freeman-Tukey") {
indice <- sqrt(Nnbj)+sqrt(1+Nnbj)-sqrt(4*Nexpnbj+1)
}
else if (resid=="adjusted") {
indice <- (Nnbj-Nexpnbj)/sqrt(Nexpnbj*(sum(condj)/n)*(1-sum(condi)/n))
}
if (type=="indice") {
result[i, j] <- indice
}
else {
result[i, j] <- pnorm(-indice)
}
}
}
return(result)
}
|
ARp <- function(margdist, margarg, acsvalue, actfpara, n, p = NULL, p0 = 0) {
transacsvalue <- actf(acsvalue,
b = actfpara$actfcoef[1],
c = actfpara$actfcoef[2])
if (any(c(is.null(p), p > 1000))) {
temp <- length(transacsvalue[transacsvalue > .01]) - 1
p <- ifelse(temp > 1000, 1000, temp)
message(paste('Order "p" limited to ', p))
}
if(length(transacsvalue) - 1 < p) {
stop(paste0('Please supply ACS of length up to order p = ', p, ', or leave argument p = NULL'))
}
P <- matrix(NA, p, p)
for (i in 1:p) {
P[i, i:p] <- transacsvalue[1:(p - i + 1)]
P[i, 1:i] <- transacsvalue[i:1]
}
rho <- matrix(transacsvalue[2:(p + 1)], p, 1)
a <- solve(P, rho)
esd <- sqrt(1 - sum(rho*a))
val <- AR1(n = p,
alpha = rho[1])
gn <- rnorm(n = (p + n),
mean = 0,
sd = esd)
a.rev <- rev(a)
for (i in (p + 1):(n + p)) {
val[i] <- sum(val[(i - p):(i - 1)]*a.rev) + gn[i]
}
uval <- (pnorm(val[-1:-p]) - p0)/(1 - p0)
uval[uval < 0] <- 0
out <- do.call(paste0('q', margdist), args = c(list(p = uval), margarg))
structure(.Data = out,
margdist = margdist,
margarg = margarg,
acsvalue = acsvalue,
p0 = p0,
a = a,
esd = esd,
gaussian = val[-1:-p],
trACS = transacsvalue)
} |
NULL
cubehelix <- function(n=25, start = 0.5, r = -1.5, hue = 1, gamma = 1) {
lambda <- seq(0, 1, length=n)
lgam <- rep(lambda^gamma, each = 3)
phi <- 2 * pi * (start/3 + r * lambda)
amp <- hue * lgam * (1 - lgam)/2
M <- matrix(c(-0.14861, -0.29227, 1.97294, 1.78277, -0.90649, 0),
byrow=FALSE, ncol = 2)
out <- lgam + amp * (M %*% rbind(cos(phi), sin(phi)))
out <- pmin(pmax(out, 0), 1)
rgb(t(out))
}
gnuplot <- function (n = 25, trim = 0.1) {
if (trim >= 1 || trim < 0)
stop("trim should be in [0, 1]")
i <- seq(0.5 * trim, 1 - 0.5 * trim, length = n)
R <- ifelse(i < 0.25, 0, ifelse(i < 0.57, i/0.32 - 0.78125, 1))
G <- ifelse(i < 0.42, 0, ifelse(i < 0.92, 2 * i - 0.84, 1))
B <- ifelse(i < 0.25, 4 * i, ifelse(i < 0.42, 1, ifelse(i < 0.92, -2 * i + 1.84, i/0.08 - 11.5)))
rgb(R, G, B)
}
tol.rainbow <- function(n=25, manual=TRUE){
if(manual & n >= 14 & n <= 21) {
banded <- matrix(c(17, 68, 119, 17, 68, 119, 17, 68, 136, 119, 170, 221, 119, 170, 221, 119, 170, 221, 119, 170, 204,
68, 119, 170, 119, 170, 204, 119, 170, 204, 119, 170, 221, 68, 119, 170, 17, 68, 119, 17, 68, 153,
119, 170, 221, 119, 170, 204, 68, 119, 170, 17, 68, 119, 17, 68, 119, 34, 85, 136, 85, 136, 187),
byrow=FALSE, ncol=3)
banded <- rgb(banded, maxColorValue=255)
ix <- list(
c(0, 1, 2, 3, 4, 5, 9, 10, 11, 12, 13, 14, 15, 16),
c(0, 1, 2, 3, 4, 5, 9, 10, 11, 12, 13, 14, 15, 16, 17),
c(20, 0, 1, 2, 3, 4, 5, 9, 10, 11, 12, 13, 14, 15, 16, 17),
c(19, 20, 0, 1, 2, 3, 4, 5, 9, 10, 11, 12, 13, 14, 15, 16, 17),
c(18, 19, 20, 0, 1, 2, 3, 4, 5, 9, 10, 11, 12, 13, 14, 15, 16, 17),
c(20, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17),
c(19, 20, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17),
c(18, 19, 20, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17))[[n-13]]
return(banded[ix+1])
}
if (manual & n <=13) {
x <- list(
c(0.137),
c(0.137, 1),
c(0.137, 0.511, 1),
c(0.137, 0.36, 0.762, 1),
c(0.137, 0.335, 0.483, 0.794, 1),
c(0.137, 0.287, 0.402, 0.651, 0.833, 1),
c(0., 0.195, 0.34, 0.436, 0.685, 0.843, 1),
c(0., 0.177, 0.301, 0.39, 0.536, 0.735, 0.861, 1),
c(0., 0.162, 0.266, 0.36, 0.437, 0.617, 0.768, 0.874, 1),
c(0., 0.149, 0.239, 0.337, 0.399, 0.508, 0.676, 0.794, 0.885, 1),
c(0., 0.137, 0.218, 0.312, 0.374, 0.44, 0.577, 0.715, 0.813, 0.894, 1),
c(0., 0.128, 0.203, 0.284, 0.351, 0.402, 0.487, 0.628, 0.742, 0.826, 0.9, 1),
c(0., 0.118, 0.188, 0.259, 0.332, 0.38, 0.437, 0.544, 0.67, 0.765, 0.839, 0.907, 1))[[n]]
} else {
x <- seq(from=0, to=1, length=n)
}
R <- (0.472-0.567*x+4.05*x^2)/(1+8.72*x-19.17*x^2+14.1*x^3)
G <- 0.108932 - 1.22635*x + 27.284*x^2 - 98.577*x^3 + 163.3*x^4 - 131.395*x^5 + 40.634*x^6
B <- 1/(1.97 + 3.54*x - 68.5*x^2 + 243*x^3-297*x^4 + 125*x^5)
return(rgb(R,G,B))
}
jet <- function(n=25) colorRampPalette(syspals$jet)(n)
parula <- function(n=25) colorRampPalette(syspals$parula)(n)
turbo <- function(n=25) colorRampPalette(syspals$turbo)(n)
coolwarm <- function(n=25) colorRampPalette(syspals$coolwarm)(n)
warmcool <- function(n=25){
rev(coolwarm(n))
}
cividis <- function(n=25) colorRampPalette(syspals$cividis)(n)
NULL
get.brewer.pal <- function(bpal, n){
rng <- as.numeric(names(bpal))
maxn <- max(rng)
if(n < 3) warning("Only accepts n>2")
if(n <= maxn) {
return(bpal[[n-2]])
} else {
return(colorRampPalette(bpal[[maxn-2]])(n))
}
}
brewer.blues <- function(n) get.brewer.pal(syspals$brewer.blues, n)
brewer.bugn <- function(n) get.brewer.pal(syspals$brewer.bugn, n)
brewer.bupu <- function(n) get.brewer.pal(syspals$brewer.bupu, n)
brewer.gnbu <- function(n) get.brewer.pal(syspals$brewer.gnbu, n)
brewer.greens <- function(n) get.brewer.pal(syspals$brewer.greens, n)
brewer.greys <- function(n) get.brewer.pal(syspals$brewer.greys, n)
brewer.oranges <- function(n) get.brewer.pal(syspals$brewer.oranges, n)
brewer.orrd <- function(n) get.brewer.pal(syspals$brewer.orrd, n)
brewer.pubu <- function(n) get.brewer.pal(syspals$brewer.pubu, n)
brewer.pubugn <- function(n) get.brewer.pal(syspals$brewer.pubugn, n)
brewer.purd <- function(n) get.brewer.pal(syspals$brewer.purd, n)
brewer.purples <- function(n) get.brewer.pal(syspals$brewer.purples, n)
brewer.rdpu <- function(n) get.brewer.pal(syspals$brewer.rdpu, n)
brewer.reds <- function(n) get.brewer.pal(syspals$brewer.reds, n)
brewer.ylgn <- function(n) get.brewer.pal(syspals$brewer.ylgn, n)
brewer.ylgnbu <- function(n) get.brewer.pal(syspals$brewer.ylgnbu, n)
brewer.ylorbr <- function(n) get.brewer.pal(syspals$brewer.ylorbr, n)
brewer.ylorrd <- function(n) get.brewer.pal(syspals$brewer.ylorrd, n)
brewer.brbg <- function(n) get.brewer.pal(syspals$brewer.brbg, n)
brewer.piyg <- function(n) get.brewer.pal(syspals$brewer.piyg, n)
brewer.prgn <- function(n) get.brewer.pal(syspals$brewer.prgn, n)
brewer.puor <- function(n) get.brewer.pal(syspals$brewer.puor, n)
brewer.rdbu <- function(n) get.brewer.pal(syspals$brewer.rdbu, n)
brewer.rdgy <- function(n) get.brewer.pal(syspals$brewer.rdgy, n)
brewer.rdylbu <- function(n) get.brewer.pal(syspals$brewer.rdylbu, n)
brewer.rdylgn <- function(n) get.brewer.pal(syspals$brewer.rdylgn, n)
brewer.spectral <- function(n) get.brewer.pal(syspals$brewer.spectral, n)
brewer.accent <- function(n) get.brewer.pal(syspals$brewer.accent, n)
brewer.dark2 <- function(n) get.brewer.pal(syspals$brewer.dark2, n)
brewer.paired <- function(n) get.brewer.pal(syspals$brewer.paired, n)
brewer.pastel1 <- function(n) get.brewer.pal(syspals$brewer.pastel1, n)
brewer.pastel2 <- function(n) get.brewer.pal(syspals$brewer.pastel2, n)
brewer.set1 <- function(n) get.brewer.pal(syspals$brewer.set1, n)
brewer.set2 <- function(n) get.brewer.pal(syspals$brewer.set2, n)
brewer.set3 <- function(n) get.brewer.pal(syspals$brewer.set3, n)
NULL
ocean.algae <- function(n) colorRampPalette(syspals$ocean.algae)(n)
ocean.deep <- function(n) colorRampPalette(syspals$ocean.deep)(n)
ocean.dense <- function(n) colorRampPalette(syspals$ocean.dense)(n)
ocean.gray <- function(n) colorRampPalette(syspals$ocean.gray)(n)
ocean.haline <- function(n) colorRampPalette(syspals$ocean.haline)(n)
ocean.ice <- function(n) colorRampPalette(syspals$ocean.ice)(n)
ocean.matter <- function(n) colorRampPalette(syspals$ocean.matter)(n)
ocean.oxy <- function(n) colorRampPalette(syspals$ocean.oxy)(n)
ocean.phase <- function(n) colorRampPalette(syspals$ocean.phase)(n)
ocean.solar <- function(n) colorRampPalette(syspals$ocean.solar)(n)
ocean.thermal <- function(n) colorRampPalette(syspals$ocean.thermal)(n)
ocean.turbid <- function(n) colorRampPalette(syspals$ocean.turbid)(n)
ocean.balance <- function(n) colorRampPalette(syspals$ocean.balance)(n)
ocean.curl <- function(n) colorRampPalette(syspals$ocean.curl)(n)
ocean.delta <- function(n) colorRampPalette(syspals$ocean.delta)(n)
ocean.amp <- function(n) colorRampPalette(syspals$ocean.amp)(n)
ocean.speed <- function(n) colorRampPalette(syspals$ocean.speed)(n)
ocean.tempo <- function(n) colorRampPalette(syspals$ocean.tempo)(n)
NULL
cubicyf <- function(n) colorRampPalette(syspals$cubicyf)(n)
isol <- function(n) colorRampPalette(syspals$isol)(n)
cubicl <- function(n) colorRampPalette(syspals$cubicl)(n)
linearl <- function(n) colorRampPalette(syspals$linearl)(n)
linearlhot <- function(n) colorRampPalette(syspals$linearlhot)(n)
NULL
magma <- function(n) colorRampPalette(syspals$magma)(n)
inferno <- function(n) colorRampPalette(syspals$inferno)(n)
plasma <- function(n) colorRampPalette(syspals$plasma)(n)
viridis <- function(n) colorRampPalette(syspals$viridis)(n)
NULL
kovesi.cyclic_grey_15_85_c0 <- function(n) colorRampPalette(syspals$kovesi.cyclic_grey_15_85_c0)(n)
kovesi.cyclic_grey_15_85_c0_s25 <- function(n) colorRampPalette(syspals$kovesi.cyclic_grey_15_85_c0_s25)(n)
kovesi.cyclic_mrybm_35_75_c68 <- function(n) colorRampPalette(syspals$kovesi.cyclic_mrybm_35_75_c68)(n)
kovesi.cyclic_mrybm_35_75_c68_s25 <- function(n) colorRampPalette(syspals$kovesi.cyclic_mrybm_35_75_c68_s25)(n)
kovesi.cyclic_mygbm_30_95_c78 <- function(n) colorRampPalette(syspals$kovesi.cyclic_mygbm_30_95_c78)(n)
kovesi.cyclic_mygbm_30_95_c78_s25 <- function(n) colorRampPalette(syspals$kovesi.cyclic_mygbm_30_95_c78_s25)(n)
kovesi.cyclic_wrwbw_40_90_c42 <- function(n) colorRampPalette(syspals$kovesi.cyclic_wrwbw_40_90_c42)(n)
kovesi.cyclic_wrwbw_40_90_c42_s25 <- function(n) colorRampPalette(syspals$kovesi.cyclic_wrwbw_40_90_c42_s25)(n)
kovesi.diverging_isoluminant_cjm_75_c23 <- function(n) colorRampPalette(syspals$kovesi.diverging_isoluminant_cjm_75_c23)(n)
kovesi.diverging_isoluminant_cjm_75_c24 <- function(n) colorRampPalette(syspals$kovesi.diverging_isoluminant_cjm_75_c24)(n)
kovesi.diverging_isoluminant_cjo_70_c25 <- function(n) colorRampPalette(syspals$kovesi.diverging_isoluminant_cjo_70_c25)(n)
kovesi.diverging_linear_bjr_30_55_c53 <- function(n) colorRampPalette(syspals$kovesi.diverging_linear_bjr_30_55_c53)(n)
kovesi.diverging_linear_bjy_30_90_c45 <- function(n) colorRampPalette(syspals$kovesi.diverging_linear_bjy_30_90_c45)(n)
kovesi.diverging_rainbow_bgymr_45_85_c67 <- function(n) colorRampPalette(syspals$kovesi.diverging_rainbow_bgymr_45_85_c67)(n)
kovesi.diverging_bkr_55_10_c35 <- function(n) colorRampPalette(syspals$kovesi.diverging_bkr_55_10_c35)(n)
kovesi.diverging_bky_60_10_c30 <- function(n) colorRampPalette(syspals$kovesi.diverging_bky_60_10_c30)(n)
kovesi.diverging_bwr_40_95_c42 <- function(n) colorRampPalette(syspals$kovesi.diverging_bwr_40_95_c42)(n)
kovesi.diverging_bwr_55_98_c37 <- function(n) colorRampPalette(syspals$kovesi.diverging_bwr_55_98_c37)(n)
kovesi.diverging_cwm_80_100_c22 <- function(n) colorRampPalette(syspals$kovesi.diverging_cwm_80_100_c22)(n)
kovesi.diverging_gkr_60_10_c40 <- function(n) colorRampPalette(syspals$kovesi.diverging_gkr_60_10_c40)(n)
kovesi.diverging_gwr_55_95_c38 <- function(n) colorRampPalette(syspals$kovesi.diverging_gwr_55_95_c38)(n)
kovesi.diverging_gwv_55_95_c39 <- function(n) colorRampPalette(syspals$kovesi.diverging_gwv_55_95_c39)(n)
kovesi.isoluminant_cgo_70_c39 <- function(n) colorRampPalette(syspals$kovesi.isoluminant_cgo_70_c39)(n)
kovesi.isoluminant_cgo_80_c38 <- function(n) colorRampPalette(syspals$kovesi.isoluminant_cgo_80_c38)(n)
kovesi.isoluminant_cm_70_c39 <- function(n) colorRampPalette(syspals$kovesi.isoluminant_cm_70_c39)(n)
kovesi.linear_bgy_10_95_c74 <- function(n) colorRampPalette(syspals$kovesi.linear_bgy_10_95_c74)(n)
kovesi.linear_bgyw_15_100_c67 <- function(n) colorRampPalette(syspals$kovesi.linear_bgyw_15_100_c67)(n)
kovesi.linear_bgyw_15_100_c68 <- function(n) colorRampPalette(syspals$kovesi.linear_bgyw_15_100_c68)(n)
kovesi.linear_blue_5_95_c73 <- function(n) colorRampPalette(syspals$kovesi.linear_blue_5_95_c73)(n)
kovesi.linear_blue_95_50_c20 <- function(n) colorRampPalette(syspals$kovesi.linear_blue_95_50_c20)(n)
kovesi.linear_bmw_5_95_c86 <- function(n) colorRampPalette(syspals$kovesi.linear_bmw_5_95_c86)(n)
kovesi.linear_bmw_5_95_c89 <- function(n) colorRampPalette(syspals$kovesi.linear_bmw_5_95_c89)(n)
kovesi.linear_bmy_10_95_c71 <- function(n) colorRampPalette(syspals$kovesi.linear_bmy_10_95_c71)(n)
kovesi.linear_bmy_10_95_c78 <- function(n) colorRampPalette(syspals$kovesi.linear_bmy_10_95_c78)(n)
kovesi.linear_gow_60_85_c27 <- function(n) colorRampPalette(syspals$kovesi.linear_gow_60_85_c27)(n)
kovesi.linear_gow_65_90_c35 <- function(n) colorRampPalette(syspals$kovesi.linear_gow_65_90_c35)(n)
kovesi.linear_green_5_95_c69 <- function(n) colorRampPalette(syspals$kovesi.linear_green_5_95_c69)(n)
kovesi.linear_grey_0_100_c0 <- function(n) colorRampPalette(syspals$kovesi.linear_grey_0_100_c0)(n)
kovesi.linear_grey_10_95_c0 <- function(n) colorRampPalette(syspals$kovesi.linear_grey_10_95_c0)(n)
kovesi.linear_kry_5_95_c72 <- function(n) colorRampPalette(syspals$kovesi.linear_kry_5_95_c72)(n)
kovesi.linear_kry_5_98_c75 <- function(n) colorRampPalette(syspals$kovesi.linear_kry_5_98_c75)(n)
kovesi.linear_kryw_5_100_c64 <- function(n) colorRampPalette(syspals$kovesi.linear_kryw_5_100_c64)(n)
kovesi.linear_kryw_5_100_c67 <- function(n) colorRampPalette(syspals$kovesi.linear_kryw_5_100_c67)(n)
kovesi.linear_ternary_blue_0_44_c57 <- function(n) colorRampPalette(syspals$kovesi.linear_ternary_blue_0_44_c57)(n)
kovesi.linear_ternary_green_0_46_c42 <- function(n) colorRampPalette(syspals$kovesi.linear_ternary_green_0_46_c42)(n)
kovesi.linear_ternary_red_0_50_c52 <- function(n) colorRampPalette(syspals$kovesi.linear_ternary_red_0_50_c52)(n)
kovesi.rainbow_bgyr_35_85_c72 <- function(n) colorRampPalette(syspals$kovesi.rainbow_bgyr_35_85_c72)(n)
kovesi.rainbow <- function(n) colorRampPalette(syspals$kovesi.rainbow_bgyr_35_85_c72)(n)
kovesi.rainbow_bgyr_35_85_c73 <- function(n) colorRampPalette(syspals$kovesi.rainbow_bgyr_35_85_c73)(n)
kovesi.rainbow_bgyrm_35_85_c69 <- function(n) colorRampPalette(syspals$kovesi.rainbow_bgyrm_35_85_c69)(n)
kovesi.rainbow_bgyrm_35_85_c71 <- function(n) colorRampPalette(syspals$kovesi.rainbow_bgyrm_35_85_c71)(n) |
options(width=65,digits=5) |
KMedoids <- function(data, k, ground.truth=NULL, distance, ...) {
if (is.character(ground.truth)) {
distance <- ground.truth
ground.truth <- NULL
}
d <- as.matrix(TSDatabaseDistances(data, distance=distance, ...))
if (distance=="lcss") {
d <- exp(-d)
}
clus <- pam(d, k=k, diss=TRUE)
if (! is.null(ground.truth)) {
f <- F(clus$clustering, ground.truth)
return(list(clustering=as.numeric(clus$clustering), F=f))
} else {
return(as.numeric(clus$clustering))
}
}
F <- function(clus, true) {
tab1 <- 2 * table(clus, true)
tab2 <- outer(rowSums(tab1), colSums(tab1), `+`)
result <- 1 / length(true) * sum(colSums(tab1) * apply((tab1 / tab2), 2, max))
return(result)
} |
absorb.dbn=function(object,node,evidence)
{
class_nodes=object$dbn_nodes
bngraph<-as.graphNEL(object$dbn)
blM<-grMAT(bngraph)
dnodes=c()
for (i in 1:dim(class_nodes)[1])
{
if(!dSep(blM,node,class_nodes[i,1],cond=NULL))
dnodes<-rbind(dnodes,class_nodes[i,])
}
for (i in 1:length(node))
{
Xnode<-which(dnodes[,1]==node[i])
if(length(Xnode)!=0)
dnodes<-dnodes[-Xnode,]
}
if(!is.matrix(evidence))
stop("In function(absorb.dbn),'evidence' must be a matrix of factors")
network<-as.grain(object$dbn)
setEvidence(network)
grn<-querygrain(network)
marginal<-.get.cpt.grn(grn,dnodes)
Y<-which(dnodes[,4]=="geno" )
Z<-which(dnodes[,4]=="pheno")
FC=matrix(nrow=length(dnodes[Z,1]),ncol=dim(evidence)[2])
pheno_state=matrix(nrow=length(dnodes[Z,1]),ncol=dim(evidence)[2])
belief_pheno_freq_list=list()
belief_pheno_freq=vector()
belief_geno_freq_list=list()
belief_geno_freq=vector()
for (i in 1:dim(evidence)[2])
{
retractEvidence(network)
grn<-setEvidence(network,node,evidence[,i])
grnstate<-querygrain(grn)
belief<-.get.cpt.grn(grnstate,dnodes)
FC_temp<-.get.FC.grn(marginal,belief,dnodes)
FC[,i]<- FC_temp[,2]
pheno_state[,i]<-FC_temp[,1]
if(length(Z)!=0)
belief_pheno_freq = cbind(belief_pheno_freq,matrix(belief[dnodes[Z,1],1:ncol(belief)],
nrow=length(dnodes[Z,1]),
ncol=as.numeric(max(dnodes[,3])),
dimnames=(list(dnodes[Z,1],
colnames(belief)))))
if(length(Y)!=0)
belief_geno_freq = cbind(belief_geno_freq,matrix(belief[dnodes[Y,1],1:ncol(belief)],
nrow=length(dnodes[Y,1]),
ncol=as.numeric(max(dnodes[,3])),
dimnames=(list(dnodes[Y,1],
colnames(belief)))))
}
rownames(FC)=dnodes[Z,1]
rownames(pheno_state)=dnodes[Z,1]
FC=list(FC=FC,pheno_state=pheno_state)
for (j in 1:as.numeric(max(dnodes[Z,3])))
{
belief_pheno_freq_temp = matrix(belief_pheno_freq[,seq(j,ncol(belief_pheno_freq),by=as.numeric(max(dnodes[,3])))],
nrow=nrow(belief_pheno_freq),
ncol=dim(evidence)[2],
dimnames=list(rownames(belief_pheno_freq),NULL))
name<-paste("state",j,sep="")
belief_pheno_freq_list[[name]]= belief_pheno_freq_temp
}
phenomarginal<- marginal[dnodes[Z,1],1:as.numeric(max(dnodes[Z,3]))]
if(length(belief_geno_freq)!=0)
{
for (j in 1:as.numeric(max(dnodes[Y,3])))
{
belief_geno_freq_temp = matrix(belief_geno_freq[,seq(j,ncol(belief_geno_freq),by=as.numeric(max(dnodes[,3])))],
nrow=nrow(belief_geno_freq),
ncol=dim(evidence)[2],
dimnames=list(rownames(belief_geno_freq),NULL))
name<-paste("state",j,sep="")
belief_geno_freq_list[[name]]= belief_geno_freq_temp
}
genomarginal<- marginal[dnodes[Y,1],1:as.numeric(max(dnodes[Y,3]))]
}else
{
belief_geno_freq_list<-NULL
genomarginal<-NULL
}
results=list(gp=grn,
gp_flag="db",
gp_nodes=class_nodes,
evidence=evidence,
node=node,
marginal=list(pheno = list(freq = phenomarginal),
geno = list(freq = genomarginal)),
belief=list(pheno = belief_pheno_freq_list,geno = belief_geno_freq_list),
FC=FC)
class(results)<-"dbn"
return(results)
}
.get.cpt.grn=function(grnstate,dnodes)
{
cpt<-matrix(NA,nrow=dim(dnodes)[1],ncol=as.numeric(max(dnodes[,3])))
rownames(cpt)=dnodes[,1]
for (j in 1:dim(dnodes)[1])
{
cpt_temp<-unlist(grnstate[dnodes[j,1]])
cpt[dnodes[j,1],1:length(cpt_temp)]<-cbind(cpt_temp)
}
if(length(cpt)!=0)
{
freqnames<-matrix(nrow=as.numeric(max(dnodes[,3])),ncol=1)
for (i in 1:max(dnodes[,3]))
freqnames[i]=paste("state",i,sep="")
colnames(cpt)=freqnames
}
return(cpt)
}
.get.FC.grn=function(marginal,belief,dnodes)
{
Z<- which(dnodes[,4]=="pheno")
FC = matrix(nrow=length(dnodes[Z,1]),ncol=2)
for (i in 1:nrow(dnodes[Z,]))
{
FC[i,1] = which.max(belief[dnodes[Z[i],1],])
FC[i,2] = belief[dnodes[Z[i],1],FC[i,1]]/marginal[dnodes[Z[i],1],FC[i,1]]
}
return(FC)
} |
dDAGroot <- function (g)
{
if(class(g)=="graphNEL"){
ig <- igraph.from.graphNEL(g)
}else{
ig <- g
}
if (class(ig) != "igraph"){
stop("The function must apply to either 'igraph' or 'graphNEL' object.\n")
}
fast <- TRUE
if(fast){
neighs.in <- igraph::neighborhood(ig, order=1, nodes=V(ig), mode="in")
num.neighs.in <- sapply(neighs.in, length)
root <- V(ig)[num.neighs.in==1]$name
}else{
e <- get.data.frame(ig, what="edges")
allnodes <- V(ig)$name
times.child <- sapply(allnodes, function(child) sum(e[,2]==child))
root <- names(which(times.child==0))
}
return(root)
} |
readXlsxBatch <- function(fileNames=NULL, path=".", fileExtension="xlsx", excludeFiles=NULL, sheetInd=1, checkFormat=TRUE,
returnArray=TRUE, columns=c("Plate","Well","StainA"), simpleNames=3, silent=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="readXlsxBatch")
packages <- c("readxl", "Rcpp")
checkPkg <- function(pkg) requireNamespace(pkg, quietly=TRUE)
checkPkgs <- sapply(packages, checkPkg)
if(!isTRUE(silent)) silent <- FALSE
if(!isFALSE(returnArray)) returnArray <- TRUE
if(any(!checkPkgs)) { out <- NULL
warning(fxNa,"package 'readxl' and/or 'Rcpp' not found ! Please install first from CRAN")
} else {
if(is.null(path)) path <- "."
chPath <- file.exists(path)
if(!chPath) {message(fxNa,"Cannot find path '",path,"' ! ... Setting to default='.'")}
if(is.null(fileNames)) {
fileNames <- dir(path=path,pattern=paste0(fileExtension,"$"))
if(length(fileNames) <1) message(fxNa,"Could not find ANY suitable files !!") else {
if(silent) message(fxNa," found ",length(fileNames)," files to extract (eg ",pasteC(utils::head(fileNames,3),quoteC="'"),")")}
useFi <- file.path(path,fileNames)
} else {
douPath <- grep(path,fileNames)
useFi <- if(length(douPath) <1) file.path(path, fileNames) else fileNames
checkFi <- file.exists(useFi)
if(sum(!checkFi) >0) {
if(silent) message(fxNa,"Could not find ",sum(!checkFi)," files out of ",length(useFi),
" (eg ",pasteC(utils::head(fileNames[which(!checkFi)],3),quoteC="'"),")")
useFi <- fileNames[which(checkFi)]
fileNames <- fileNames[which(checkFi)] }}
checkFi <- if(!is.null(excludeFiles)) grep(excludeFiles, fileNames) else NULL
if(!any("try-error" %in% checkFi)) useFi <- NULL
if(length(checkFi) >0) {
if(silent) message(fxNa,"Based on 'excludeFiles': excluding ",length(checkFi)," files (out of ",length(fileNames),")")
useFi <- useFi[-1*checkFi]
fileNames <- fileNames[-1*checkFi] }
outL <- list()
if(length(useFi) >0) {
for(i in 1:length(useFi)) {
sheets <- try(readxl::excel_sheets(useFi[i]))
if("try-error" %in% class(sheets)) { sheetInd <- NULL
warning(fxNa,"Unable to read '",fileNames[i],"' Check if you have sufficient rights to open the file !?!")
} else {
if(is.numeric(sheetInd)) { sheetInd <- as.integer(sheetInd)
if(length(sheets) < sheetInd | sheetInd <1) { sheetInd <- NULL
}} else sheetInd <- naOmit(match(sheetInd,sheets))
if(silent & length(sheetInd) <1) message(fxNa,"Unable to read '",fileNames[i],"', the sheet '",sheetInd,
"' was not found (existing: ",pasteC(sheets,quoteC="'"),")")
}
if(silent & length(sheetInd) >1) message(fxNa,"Only '",sheets[sheetInd],"', ie first match of 'sheetInd' will be read !")
tmp <- if(length(sheetInd)==1) readxl::read_excel(useFi[i], sheet=sheets[sheetInd]) else NULL
if(length(tmp) >0) {
outL[[i]] <- as.data.frame(tmp)
if(isTRUE(checkFormat)) {
silent2 <- isTRUE(silent) | i !=1
outL[[i]] <- .inspectHeader(outL[[i]], headNames=columns,silent=silent2, callFrom=fxNa)
outL[[i]] <- .removeEmptyCol(outL[[i]], fromBackOnly=FALSE,silent=silent2, callFrom=fxNa)
}
if(i ==1) {
outDim <- dim(outL[[i]])
out <- if(returnArray) array(NA, dim=c(outDim[1],length(fileNames),outDim[2]),
dimnames=list(rownames(outL[[i]]), basename(fileNames),colnames(outL[[i]]))) else NULL }
if(returnArray) outL[[i]] <- as.matrix(outL[[i]]) else {
if(identical(dim(outL[[i]]),outDim)) out[,i,] <- as.matrix(outL[[i]]) else {
message(fxNa," Omit ",i,"th file ''",fileNames[i],"': format (",dim(outL[[i]])[1]," rows & ",dim(outL[[i]])[2]," cols) NOT consistent with previous files - omitting")
} }
}
}
names(outL) <- fileNames
if(returnArray) {
chColNa <- length(unique(colnames(out)))==1
arrNames <- if(chColNa) paste(colnames(out),sub("\\.xlsx$","",if(length(simpleNames) >1) .trimFromStart(fileNames, minNchar=simpleNames, callFrom=fxNa) else fileNames),sep=".") else colnames(out)
} else { out <- outL
if(length(fileNames) !=length(out)) message(fxNa," Problem ? Got ",length(fileNames)," fileNames BUT ",length(out)," list-elements !")
names(out) <- substr(basename(fileNames), 1, nchar(basename(fileNames)) -4)
if(simpleNames) names(out) <- if(length(simpleNames) >1) .trimFromStart(fileNames, minNchar=simpleNames, callFrom=fxNa) else fileNames }
} else out <- NULL }
out }
|
fitDRMperSubject <- function(subjectData, doseID, responseID, addCovars,
funcList, bounds, EDp, addCovarsVar ){
names(subjectData)[doseID] <- "dose"
names(subjectData)[responseID] <- "response"
fittedModels <-NULL
extraCovariates <- NULL
subjectData <- as.data.frame(subjectData)
estEDp <- rep(0, length(funcList))
estAIC <- rep(0, length(funcList))
extraCovariatesNames <- all.vars(as.formula(addCovars))
if (addCovars != as.formula(~1)){
paramEst <- matrix(NA, length(funcList), length(extraCovariatesNames))
paramVar <- matrix(NA, length(funcList), length(extraCovariatesNames))
}
for (iModel in 1:length(funcList)){
tmpModel <- DoseFinding::fitMod(dose = "dose", resp = "response",
data = subjectData, model = funcList[iModel], S = NULL,
type = "normal", addCovars = addCovars, bnds = bounds[[iModel]], df = NULL,
start = NULL)
fittedModels[[iModel]] <- tmpModel
estEDp[iModel] <- DoseFinding::ED(tmpModel, p = EDp, EDtype = "continuous")
estAIC[iModel] <- AIC(tmpModel)
if (addCovars != as.formula(~1)){
idxAddedCovariate <- which(names(coefficients(tmpModel)) %in% extraCovariatesNames)
paramEst[iModel,] <- coefficients(tmpModel)[idxAddedCovariate]
if (addCovarsVar){
computedVariance <- try(vcov(tmpModel))
if (!is.character(computedVariance)){
paramVar[iModel,] <- diag(computedVariance)[idxAddedCovariate]
}else{
addCovarsVar <- FALSE
}
}
}
}
minAICEDp <- estEDp[which.min(estAIC)]
weightsAIC <- modelAveragingWeightsAIC(estAIC)
modelAveragingEDp <- sum(weightsAIC * estEDp)
if (addCovars != as.formula(~1)){
addedCovarsEst <- apply(weightsAIC * paramEst, 2, mean)
addedCovarsVar <- rep(NA, length(addedCovarsEst))
if (addCovarsVar){
paramDiff <- paramEst - matrix(rep(addedCovarsEst,length(funcList)), length(funcList), length(addedCovarsEst),
byrow = TRUE)
addedCovarsVar <- (apply(weightsAIC *sqrt(paramVar + (paramDiff^2)), 2, sum))^2
}
addedCovariatesModelAveraging <- cbind(addedCovarsEst, sqrt(addedCovarsVar))
colnames(addedCovariatesModelAveraging) <- c("Est.", "StdErr.")
addedCovariatesMinAIC <- cbind(paramEst[which.min(estAIC),], sqrt(paramVar[which.min(estAIC),]))
colnames(addedCovariatesMinAIC) <- c("Est.", "StdErr.")
extraCovariates <- list(modelAveraging = addedCovariatesModelAveraging,
minAIC = addedCovariatesMinAIC)
class(extraCovariates) <- "drmExtraCovariates"
}
estEDpFinal <- c(estEDp, minAICEDp, modelAveragingEDp)
names(estEDpFinal) <- c(funcList, "minAIC", "modelAveragingAIC")
names(estAIC) <- funcList
return(list(estEDp = estEDpFinal, fittedModels = fittedModels, estAIC = estAIC, extraCovariates = extraCovariates))
} |
ecd.rational <- function(x, pref.denominator=numeric(0), cycles=10, max.denominator=500, as.character=FALSE)
{
if (length(x) > 1) {
f <- function(x) ecd.rational(x, cycles=cycles,
pref.denominator=pref.denominator,
max.denominator=max.denominator,
as.character=as.character)
if (!as.character) return(t(sapply(x,f)))
else return(sapply(x,f))
}
if (length(x) != 1 | !is.finite(x)) {
stop("Input must be length-one finite numeric!")
}
a0 <- rep(0, length(x))
b0 <- rep(1, length(x))
A <- matrix(b0)
B <- matrix(floor(x))
r <- as.vector(x) - drop(B)
len <- 0
while(any(r > 1/max.denominator) && (len <- len + 1) <= cycles) {
a <- a0
b <- b0
a <- 1
r <- 1/r
b <- floor(r)
r <- r - b
A <- cbind(A, a)
B <- cbind(B, b)
}
pq1 <- cbind(b0, a0)
pq <- cbind(B[, 1], b0)
len <- 1
while((len <- len + 1) <= ncol(B)) {
pq0 <- pq1
pq1 <- pq
pq <- B[, len] * pq1 + A[, len] * pq0
}
R <- unname(as.vector(pq))
for (pd in pref.denominator) {
if (floor(pd/R[2]) == pd/R[2]) {
R <- R*(pd/R[2])
break
}
}
if (!as.character) return(R)
else {
if (R[1] == 0) return("0")
if (R[1] == R[2]) return("1")
return(sprintf("%d/%d", R[1], R[2]))
}
} |
require(dynr)
testthat::expect_error(
me1 <- prep.measurement(values.load=matrix(c(1, 0), 1, 1),
obs.names=c('y'),
state.names=c('x1', 'x2')),
regexp="Matrix values.load has 1 columns and 2 state.names (i.e., column names).\nHint: they should match.\nNot even the King of Soul could set these column names.",
fixed=TRUE)
testthat::expect_error(
me2 <- prep.measurement(values.load=matrix(c(1, 0), 1, 1),
obs.names=c('y1', 'y2'),
state.names=c('x1')),
regexp="Matrix values.load has 1 rows and 2 obs.names (i.e., row names).\nHint: they should match.\nNot even the King of Pop could set these row names.",
fixed=TRUE)
testthat::expect_error(
me3 <- prep.measurement(values.load=matrix(c(1, 0), 1, 1),
values.exo=matrix(c(1, 0), 1, 1),
obs.names=c('y'),
state.names=c('x1'),
exo.names=c('u1', 'u2')),
regexp="Matrix values.exo has 1 columns and 2 exo.names (i.e., column names).\nHint: they should match.\nNot even the King of Soul could set these column names.",
fixed=TRUE)
testthat::expect_error(
me4 <- prep.measurement(values.load=matrix(c(1, 0), 1, 2),
values.int=matrix(c(1, 1), 2, 1),
obs.names=c('y'),
state.names=c('x1', 'x2')),
regexp="Matrix values.int has 2 rows and 1 obs.names (i.e., row names).\nHint: they should match.\nNot even the King of Pop could set these row names.",
fixed=TRUE) |
readFam = function(famfile, useDVI = NA, Xchrom = FALSE, verbose = TRUE) {
if(!endsWith(famfile, ".fam"))
stop("Input file must end with '.fam'", call. = FALSE)
raw = readLines(famfile)
x = gsub("\\\"", "", raw)
checkInt = function(a, line, txt, value) {
if(!is.na(a)) return()
stop(sprintf('Expected line %d to be %s, but found: "%s"',
line, txt, x[line]), call. = FALSE)
}
version = x[3]
if(verbose)
message("Familias version: ", version)
if(is.na(useDVI))
useDVI = "[DVI]" %in% x
else if(useDVI && !"[DVI]" %in% x)
stop2("`useDVI` is TRUE, but no line equals '[DVI]'")
if(verbose)
message("Read DVI: ", if(useDVI) "Yes" else "No")
nid.line = if(x[4] != "") 4 else 5
nid = as.integer(x[nid.line])
checkInt(nid, nid.line, "number of individuals")
if(verbose)
message("\nNumber of individuals (excluding 'extras'): ", nid)
id = character(nid)
sex = integer(nid)
datalist = vector("list", nid)
id.line = nid.line + 1
for(i in seq_len(nid)) {
id[i] = x[id.line]
sex[i] = ifelse(x[id.line + 4] == "
nmi = as.integer(x[id.line + 5])
checkInt(nmi, id.line + 5,
sprintf('number of genotypes for "%s"', id[i]))
if(verbose)
message(sprintf(" Individual '%s': Genotypes for %d markers read", id[i], nmi))
a1.lines = seq(id.line + 6, by = 3, length = nmi)
a1.idx = as.integer(x[a1.lines]) + 1
a2.idx = as.integer(x[a1.lines + 1]) + 1
mark.idx = as.integer(x[a1.lines + 2]) + 1
datalist[[i]] = list(id = id[i], a1.idx = a1.idx,
a2.idx = a2.idx, mark.idx = mark.idx)
id.line = id.line + 6 + 3*nmi
}
twins = list()
kr.line = id.line
if(x[kr.line] != "Known relations")
stop2(sprintf('Expected line %d to be "Known relations", but found: "%s"', id.line, x[id.line]))
nFem = as.integer(x[kr.line + 1])
nMal = as.integer(x[kr.line + 2])
id = c(id, character(length = nFem + nMal))
sex = c(sex, rep.int(2:1, c(nFem, nMal)))
fidx = midx = integer(length(id))
nRel = as.integer(x[kr.line + 3])
rel.line = kr.line + 4
for(i in seq_len(nRel)) {
par.idx = as.integer(x[rel.line]) + 1
child.idx = as.integer(x[rel.line+1]) + 1
if(sex[par.idx] == 1)
fidx[child.idx] = par.idx
else
midx[child.idx] = par.idx
rel.line = rel.line + 2
}
nPed = as.integer(x[rel.line])
checkInt(nPed, "number of pedigrees")
if(verbose)
message("\nNumber of pedigrees: ", nPed)
if(nPed == 0) {
pedigrees = asFamiliasPedigree(id, fidx, midx, sex)
}
ped.line = rel.line + 1
if(nPed > 0) {
pedigrees = vector("list", nPed)
for(i in seq_len(nPed)) {
ped.idx = as.integer(x[ped.line]) + 1
ped.name = x[ped.line + 1]
nFem.i = as.integer(x[ped.line + 2])
nMal.i = as.integer(x[ped.line + 3])
id.i = c(id, character(nFem.i + nMal.i))
sex.i = c(sex, rep.int(2:1, c(nFem.i, nMal.i)))
fidx.i = c(fidx, integer(nFem.i + nMal.i))
midx.i = c(midx, integer(nFem.i + nMal.i))
if(verbose)
message(sprintf(" Pedigree '%s' (%d extra females, %d extra males)", ped.name, nFem.i, nMal.i))
nRel.i = as.integer(x[ped.line + 4])
rel.line = ped.line + 5
for(i in seq_len(nRel.i)) {
par.idx = as.integer(x[rel.line]) + 1
child.idx = as.integer(x[rel.line+1]) + 1
if(is.na(par.idx)) {
if(grepl("Direct", x[rel.line])) {
par.idx = as.integer(substring(x[rel.line], 1, 1)) + 1
twins = c(twins, list(par.idx, child.idx))
if(verbose) message(" Twins: ", toString(id[c(par.idx, child.idx)]))
stop2("File contains twins - this is not supported yet")
}
}
if(sex[par.idx] == 1)
fidx.i[child.idx] = par.idx
else
midx.i[child.idx] = par.idx
rel.line = rel.line + 2
}
pedigrees[[ped.idx]] = asFamiliasPedigree(id.i, fidx.i, midx.i, sex.i)
names(pedigrees)[ped.idx] = ped.name
ped.line = rel.line
}
}
has.probs = x[ped.line] == "
if(has.probs)
stop("\nThis file includes precomputed probabilities; this is not supported yet.")
db.line = ped.line + 1
nLoc = as.integer(x[db.line])
checkInt(nLoc, "number of loci")
has.info = x[db.line + 1] == "
if(verbose) {
if(has.info)
message("\nDatabase: ", x[db.line + 2])
else
message("")
}
if(verbose)
message("Number of loci: ", nLoc)
loci = vector("list", nLoc)
loc.line = db.line + 2 + has.info
unsupp = character()
for(i in seq_len(nLoc)) {
loc.name = x[loc.line]
mutrate.fem = as.numeric(x[loc.line + 1])
mutrate.mal = as.numeric(x[loc.line + 2])
model.idx.fem = as.integer(x[loc.line + 3])
model.idx.mal = as.integer(x[loc.line + 4])
nAll.with.silent = as.integer(x[loc.line + 5])
range.fem = as.numeric(x[loc.line + 6])
range.mal = as.numeric(x[loc.line + 7])
mutrate2.fem = as.numeric(x[loc.line + 8])
mutrate2.mal = as.numeric(x[loc.line + 9])
has.silent = x[loc.line + 10] == "
if(has.silent)
stop2("Locus ", loc.name, " has silent frequencies: this is not implemented yet")
silent.freq = as.numeric(x[loc.line + 11])
nAll = x[loc.line + 12]
nAll = as.integer(strsplit(nAll, "\t")[[1]][[1]])
checkInt(nAll, sprintf('number of alleles for marker "%s"', loc.name))
als.lines = seq(loc.line + 13, by = 2, length.out = nAll)
als = x[als.lines]
frqs = as.numeric(x[als.lines + 1])
names(frqs) = als
models = c("equal", "proportional", "stepwise", "3", "4")
maleMod = models[model.idx.mal + 1]
femaleMod = models[model.idx.fem + 1]
if(maleMod %in% models[1:3]) {
maleMutMat = mutationMatrix(model = maleMod, alleles = als, afreq = frqs,
rate = mutrate.mal, rate2 = mutrate2.mal)
}
else {
if(verbose)
message(sprintf("*** Ignoring male mutation model '%s' ***", maleMod))
maleMutMat = NULL
unsupp = c(unsupp, maleMod)
}
if(femaleMod %in% models[1:3]) {
femaleMutMat = mutationMatrix(model = femaleMod, alleles = als, afreq = frqs,
rate = mutrate.fem, rate2 = mutrate2.fem)
}
else {
if(verbose)
message(sprintf("*** Ignoring female mutation model '%s' ***", femaleMod))
femaleMutMat = NULL
unsupp = c(unsupp, femaleMod)
}
if(maleMod == femaleMod && mutrate.fem == mutrate.mal)
mut_txt = sprintf("model = %s, rate = %.2g (unisex)", maleMod, mutrate.mal)
else
mut_txt = sprintf("male model = %s, male rate = %.2g, female model = %s, female rate = %.2g",
maleMod, mutrate.mal, femaleMod, mutrate.fem)
if(verbose) message(sprintf(" %s: %d alleles, %s", loc.name, length(frqs), mut_txt))
loci[[i]] = list(locusname = loc.name, alleles = frqs,
femaleMutationType = femaleMod,
femaleMutationMatrix = femaleMutMat,
maleMutationType = maleMod,
maleMutationMatrix = maleMutMat)
loc.line = loc.line + 13 + 2*nAll
}
if(length(unsupp) > 0) {
unsupp = sort(unique.default(unsupp))
tmp ="Some mutation models were set to NULL. Model '%s' is not supported yet."
warning(paste0(sprintf(tmp, unsupp), collapse = "\n"), call. = FALSE)
}
if(useDVI) {
if(verbose)
message("\n*** Reading DVI section ***")
dvi.start = match("[DVI]", raw)
if(is.na(dvi.start))
stop2("Expected keyword '[DVI]' not found")
dvi.lines = raw[dvi.start:length(raw)]
dvi.families = readDVI(dvi.lines, verbose = verbose)
if(verbose)
message("*** Finished DVI section ***\n")
if(verbose)
message("\nConverting to `ped` format")
res = lapply(dvi.families, function(fam) {
Familias2ped(familiasped = fam$pedigrees, datamatrix = fam$datamatrix,
loci = loci, matchLoci = TRUE)
})
if(Xchrom) {
if(verbose) message("Changing all chromosome attributes to `X`")
chrom(res, seq_along(loci)) = "X"
}
if(verbose) message("")
return(res)
}
has.data = nid > 0 && any(lengths(sapply(datalist, '[[', "mark.idx")))
if(!has.data) {
datamatrix = NULL
}
else {
loc.names = vapply(loci, function(ll) ll$locusname, FUN.VALUE = "")
dm.a1.idx = dm.a2.idx = matrix(NA, nrow = nid, ncol = nLoc,
dimnames = list(id[seq_len(nid)], loc.names))
for(i in seq_len(nid)) {
g = datalist[[i]]
dm.a1.idx[i, g$mark.idx] = g$a1.idx
dm.a2.idx[i, g$mark.idx] = g$a2.idx
}
dmn = list(id[seq_len(nid)], paste(rep(loc.names, each = 2), 1:2, sep = "."))
datamatrix = matrix(NA_character_, nrow = nid, ncol = 2*nLoc, dimnames = dmn)
for(i in seq_len(nLoc)) {
als.i = names(loci[[i]]$alleles)
datamatrix[, 2*i - 1] = als.i[dm.a1.idx[, i]]
datamatrix[, 2*i] = als.i[dm.a2.idx[, i]]
}
}
if(!is.null(pedigrees)) {
if(verbose)
message("\nConverting to `ped` format")
res = Familias2ped(familiasped = pedigrees, datamatrix = datamatrix, loci = loci)
if(Xchrom) {
if(verbose) message("Changing all chromosome attributes to `X`")
chrom(res, seq_along(loci)) = "X"
}
}
else {
if(verbose)
message("\nReturning database only")
res = readFamiliasLoci(loci = loci)
}
if(verbose) message("")
res
}
asFamiliasPedigree = function(id, findex, mindex, sex) {
if(length(id) == 0)
return(NULL)
if(is.numeric(sex))
sex = ifelse(sex == 1, "male", "female")
x = list(id = id, findex = findex, mindex = mindex, sex = sex)
class(x) = "FamiliasPedigree"
x
}
readDVI = function(rawlines, verbose = TRUE) {
r = rawlines
if(r[1] != "[DVI]")
stop("Expected the first line of DVI part to be '[DVI]', but got '", r[1], "'")
dvi = list()
ivec = character()
brackets = as.integer(regexpr("[^[]", r)) - 1
splits = strsplit(r, "= ")
for(i in seq_along(r)) {
line = r[i]
if(line == "")
next
br = brackets[i]
if(br == 0) {
dvi[[ivec]] = c(dvi[[ivec]], list(splits[[i]]))
}
else {
name = gsub("[][]", "", line)
ivec = c(ivec[seq_len(br - 1)], name)
dvi[[ivec]] = list()
}
}
res = list()
un = parseUnidentified(dvi$DVI$`Unidentified persons`, verbose = verbose)
if(!is.null(un))
res$`Unidentified persons` = un
refs_raw = dvi$DVI$`Reference Families`
refs = refs_raw[-1]
stopifnot((nFam <- length(refs)) == as.integer(refs_raw[[c(1,2)]]))
if(verbose)
message("\nReference families: ", nFam)
names(refs) = sapply(refs, function(fam) fam[[1]][2])
refs = lapply(refs, parseFamily, verbose = verbose)
c(res, refs)
}
parseUnidentified = function(x, verbose = TRUE) {
if(length(x) == 0)
return(NULL)
nPers = x[[c(1,2)]]
if(verbose)
message("Unidentified persons: ", nPers)
if(nPers == "0")
return(NULL)
x = x[-1]
id = sapply(x, function(p) getValue(p[[1]], iftag = "Name", NA))
sex = sapply(x, function(p) getValue(p[[2]], iftag = "Gender", 0))
sex[sex == "Male"] = 1
sex[sex == "Female"] = 2
s = asFamiliasPedigree(as.character(id), 0, 0, as.integer(sex))
if(verbose)
for(nm in id) message(" ", nm)
vecs = lapply(x, function(p) dnaData2vec(p$`DNA data`))
vecs = vecs[!sapply(vecs, is.null)]
allnames = unique(unlist(lapply(vecs, names)))
vecs_ordered = lapply(vecs, function(v) structure(v[allnames], names = allnames))
datamatrix = do.call(rbind, vecs_ordered)
rownames(datamatrix) = id[rownames(datamatrix)]
list(pedigrees = s, datamatrix = datamatrix)
}
parseFamily = function(x, verbose = TRUE) {
famname = x[[c(1,2)]]
nPers = as.integer(x$Persons[[c(1,2)]])
nPeds = as.integer(x$Pedigrees[[c(1,2)]])
if(verbose)
message(sprintf(" %s (%d persons, %d pedigrees)", famname, nPers, nPeds))
persons_list = x$Persons[-1]
id = sapply(persons_list, function(p) getValue(p[[1]], iftag = "Name", NA))
sex = sapply(persons_list, function(p) getValue(p[[2]], iftag = "Gender", 0))
sex[sex == "Male"] = 1
sex[sex == "Female"] = 2
sex = as.integer(sex)
ped_list = x$Pedigrees[-1]
names(ped_list) = sapply(ped_list, function(pd) getValue(pd[[1]], iftag = "Name", NA))
pedigrees = lapply(ped_list, function(pd) {
if(verbose)
message(" ", pd[[1]][2])
this.id = as.character(id)
this.sex = sex
tags = sapply(pd, '[', 1)
vals = sapply(pd, '[', 2)
parent.tags = which(tags == "Parent")
po = data.frame(parent = vals[parent.tags], child = vals[parent.tags + 1],
stringsAsFactors = FALSE)
extras <- setdiff(c(po$parent, po$child), id)
if(length(extras)) {
this.id = c(this.id, extras)
this.sex = c(this.sex, rep(0L, length(extras)))
}
names(this.sex) = this.id
parent.sex = this.sex[po$parent]
if(any(parent.sex == 0)) {
par.nosex = unique(po$parent[parent.sex == 0])
for(p in par.nosex) {
chi = po$child[po$parent == p]
spou = unique(setdiff(po$parent[po$child %in% chi], p))
if(all(this.sex[spou] == 1))
this.sex[p] = 2
else if(all(this.sex[spou] == 2))
this.sex[p] = 1
else
stop2("Cannot decide sex of this parent: ", p)
}
parent.sex = this.sex[po$parent]
}
parent.idx = match(po$parent, this.id)
child.idx = match(po$child, this.id)
this.fidx = this.midx = integer(length(this.id))
this.fidx[child.idx[parent.sex == 1]] = parent.idx[parent.sex == 1]
this.midx[child.idx[parent.sex == 2]] = parent.idx[parent.sex == 2]
asFamiliasPedigree(this.id, this.fidx, this.midx, this.sex)
})
vecs = lapply(persons_list, function(p) dnaData2vec(p$`DNA data`))
vecs = vecs[!sapply(vecs, is.null)]
allnames = unique(unlist(lapply(vecs, names)))
vecs_ordered = lapply(vecs, function(v) structure(v[allnames], names = allnames))
datamatrix = do.call(rbind, vecs_ordered)
rownames(datamatrix) = id[rownames(datamatrix)]
list(pedigrees = pedigrees, datamatrix = datamatrix)
}
dnaData2vec = function(x) {
dat = do.call(rbind, x)
val = dat[, 2]
idx = which(dat[,1] == "SystemName")
nLoc = length(idx)
if(nLoc == 0)
return()
res = character(2 * nLoc)
res[2*(1:nLoc) - 1] = val[idx + 1]
res[2*(1:nLoc)] = val[idx + 2]
names(res) = paste(rep(val[idx], each = 2), 1:2, sep = ".")
res
}
getValue = function(x, iftag, default) {
if(x[1] == iftag) x[2] else default
} |
splat <- function(flat) {
function(args, ...) {
do.call(flat, c(args, list(...)))
}
} |
objfun <- function(theta, W, M, X, X_star, np, npstar, link, phi.link) {
b <- utils::head(theta, np)
b_star <- utils::tail(theta, npstar)
mu.withlink <- X %*% b
phi.withlink <- X_star %*% b_star
mu <- switch(link, "logit" = invlogit(mu.withlink))
phi <- switch(phi.link, "fishZ" = invfishZ(phi.withlink), "logit" = invlogit(phi.withlink))
val <- suppressWarnings(sum(VGAM::dbetabinom(W, M, prob = mu, rho = phi, log = TRUE)))
if (is.nan(val) || any(phi <= sqrt(.Machine$double.eps)) || any(phi >= 1 - sqrt(.Machine$double.eps))) {
return(list(value = Inf))
}
value <- -val
gam <- phi/(1 - phi)
dg1 <- digamma(1/gam)
dg2 <- digamma(M + 1/gam)
dg3 <- digamma(M - (mu + W * gam - 1)/gam)
dg4 <- digamma((1 - mu)/gam)
dg5 <- digamma(mu/gam)
dg6 <- digamma(mu/gam + W)
dldmu <- (-dg3 + dg4 - dg5 + dg6)/gam
dldgam <- (-dg1 + dg2 + (mu - 1) * (dg3 - dg4) + mu *
(dg5 - dg6))/gam^2
tmp_b <- switch(link, "logit" = mu * (1 - mu) * dldmu)
tmp_bstar <- switch(phi.link, "fishZ" = (gam + 0.5) * dldgam, "logit" = gam * dldgam)
g_b <- c(crossprod(tmp_b, X))
g_bstar <- c(crossprod(tmp_bstar, X_star))
gradient <- -c(g_b, g_bstar)
tg1 <- trigamma(M - (mu + W * gam - 1)/gam)
tg2 <- trigamma((1 - mu)/gam)
tg3 <- trigamma(mu/gam)
tg4 <- trigamma(mu/gam + W)
tg5 <- trigamma(1/gam)
tg6 <- trigamma(M + 1/gam)
dldmu2 <- (tg1 - tg2 - tg3 + tg4)/gam^2
dldgam2 <- (2 * gam * dg1 + tg5 - 2 * gam * dg2 - tg6 +
(mu - 1)^2 * tg1 - 2 * gam * (mu - 1) * dg3 - mu^2 *
tg3 + mu^2 * tg4 + (mu - 1)^2 * (-tg2) + 2 * gam * (mu -
1) * dg4 - 2 * gam * mu * dg5 + 2 * gam * mu * dg6)/gam^4
dldmdg <- (gam * (dg3 - dg4 + dg5 - dg6) + (mu - 1) * (tg2 -
tg1) + mu * (tg3 - tg4))/gam^3
dpdb <- switch(link, logit = t(X * c(mu * (1 - mu))))
dgdb <- switch(phi.link, fishZ = t(X_star * c(gam + 0.5)),
logit = t(X_star * c(gam)))
mid4 <- switch(link, logit = c(dldmu * mu * (1 - mu) * (1 - 2 * mu)))
mid5 <- switch(phi.link, fishZ = c(dldgam * (gam + 0.5)),
logit = c(dldgam * gam))
term4 <- crossprod(X, diag(mid4)) %*% X
term5 <- crossprod(X_star, diag(mid5)) %*% X_star
term1 <- dpdb %*% tcrossprod(diag(c(-dldmu2)), dpdb)
term2 <- dpdb %*% tcrossprod(diag(c(-dldmdg)), dgdb)
term3 <- dgdb %*% tcrossprod(diag(c(-dldgam2)), dgdb)
hessian <- cbind(rbind(term1 - term4, t(term2)),rbind(term2, term3 - term5))
return(list(value = value, gradient = gradient, hessian = hessian))
} |
"modeP"<-function(postP, threshold=0, marginal=FALSE, USasNA=TRUE){
post_prob2=NULL
if(is.list(postP)){
ped<-matrix(NA, length(postP), 3)
ped[,1]<-names(postP)
if(marginal){
ped[,2]<-unlist(lapply(postP, function(x){colnames(x)[which.max(colSums(x))]}))
post_prob<-unlist(lapply(postP, function(x){colSums(x)[which.max(colSums(x))]/sum(x)}))
ped[,2][which(post_prob<threshold)]<-NA
if(USasNA){
ped[,2][which(ped[,2]=="us")]<-NA
}
ped[,3]<-unlist(lapply(postP, function(x){rownames(x)[which.max(rowSums(x))]}))
post_prob2<-unlist(lapply(postP, function(x){rowSums(x)[which.max(rowSums(x))]/sum(x)}))
ped[,3][which(post_prob2<threshold)]<-NA
if(USasNA){
ped[,3][which(ped[,3]=="us")]<-NA
}
}else{
ped[,2]<-unlist(lapply(postP, function(x){colnames(x)[which(x==max(x), arr.ind=TRUE)[1,][2]]}))
ped[,3]<-unlist(lapply(postP, function(x){rownames(x)[which(x==max(x), arr.ind=TRUE)[1,][1]]}))
post_prob<-unlist(lapply(postP, function(x){x[which.max(x)]/sum(x)}))
ped[,2][which(post_prob<threshold)]<-NA
ped[,3][which(post_prob<threshold)]<-NA
if(USasNA){
ped[,2][which(ped[,2]=="us")]<-NA
ped[,3][which(ped[,3]=="us")]<-NA
}
}
}else{
ped<-matrix(NA, dim(postP)[1], 3)
lpost<-dim(postP)[2]
ped[,1]<-rownames(postP)
if(marginal){
postP1<-apply(postP, 1, function(x){table(x[seq(1,lpost,2)])/(lpost/2)})
if(is.list(postP1)==FALSE){
ped[,2]<-apply(postP, 1, function(x){x[1]})
post_prob<-rep(1, dim(ped)[1])
}else{
ped[,2]<-unlist(lapply(postP1, function(x){names(x)[which.max(x)]}))
post_prob<-unlist(lapply(postP1, function(x){max(x)}))
}
ped[,2][which(post_prob<threshold)]<-NA
if(USasNA){
ped[,2][which(ped[,2]=="us")]<-NA
}
postP2<-apply(postP, 1, function(x){table(x[seq(2,lpost,2)])/(lpost/2)})
if(is.list(postP2)==FALSE){
ped[,3]<-apply(postP, 1, function(x){x[2]})
post_prob2<-rep(1, dim(ped)[1])
}else{
ped[,3]<-unlist(lapply(postP2, function(x){names(x)[which.max(x)]}))
post_prob2<-unlist(lapply(postP2, function(x){max(x)}))
}
ped[,3][which(post_prob2<threshold)]<-NA
if(USasNA){
ped[,3][which(ped[,3]=="us")]<-NA
}
}else{
postP<-apply(postP, 1, function(x){table(paste(x[seq(1,lpost,2)], x[seq(2,lpost,2)]))})
ped[,2]<-unlist(lapply(postP, function(x){strsplit(names(x)[which.max(x)], " ")[[1]][1]}))
ped[,3]<-unlist(lapply(postP, function(x){strsplit(names(x)[which.max(x)], " ")[[1]][2]}))
post_prob<-unlist(lapply(postP, function(x){x[which.max(x)]/sum(x)}))
ped[,2:3][which(post_prob<threshold),]<-NA
if(USasNA){
ped[,2][which(ped[,2]=="us")]<-NA
ped[,3][which(ped[,3]=="us")]<-NA
}
}
}
list(P=ped, prob=as.vector(post_prob), prob.male=as.vector(post_prob2))
}
|
single_band_lomb_scargle <- function(tms, omega_seq) {
nOmega <- length(omega_seq)
B <- length(tms)
sol.names <- list(band=names(tms),
NULL,
param=c("beta0","amp","rho","rss"))
sol <- array(NA,dim=c(B,nOmega,4),dimnames=sol.names)
last_success <- c(0,1,0)
for(ii in 1:B) {
for(jj in 1:nOmega) {
tmp <- try(lomb_scargle(tms[[ii]][,1],
tms[[ii]][,2],
tms[[ii]][,3],
omega_seq[jj]),silent=TRUE)
if (!inherits(tmp, "try-error")) {
sol[ii,jj,] <- unlist(tmp)
sol[ii,jj,4] <- sol[ii,jj,4] / 2
last_success <- sol[ii,jj,1:3]
} else {
sol[ii,jj,1:3] <- last_success
sol[ii,jj,4] <- 0
}
}
}
return(sol)
} |
gvcm.cat.flex <- function(
whichCoefs,
intercept = TRUE,
data,
family = gaussian(),
method = "REML",
tuning = NULL,
indexNrCoefs,
indexPenNorm,
indexPenA,
indexPenWeight,
control = list(c=1e-05, epsilon=1e-07, gama=35, maxi=1500, nu=.5)
)
{
newton = list(
conv.tol = 1e-6,
maxNstep = 15,
maxSstep = 5,
maxHalf = 50
)
gamcontrol <- gam.control(newton=newton)
optimizer <- c("outer", "newton")
optimizer <- c("outer", "newton")
p <- length(whichCoefs)
vonBis <- matrix(nrow=2, ncol=p)
vonBis[1, ] <- c(0, cumsum(indexNrCoefs)[-p])+1
vonBis[2, ] <- cumsum(indexNrCoefs)
if(intercept) {vonBis <- vonBis+1}
L1 <- function(xi, control=control) sqrt((xi^2 + control$c) )^(-1)
control$L0.log <- TRUE
L0 <- if (control$L0.log==TRUE) {
function(xi, control=control){p <- 1+exp(-control$gama*abs(xi))
2*control$gama*(sqrt(xi^2 + control$c))^(-1)*p^(-1)*(1 - 1/p)}
} else {
function(xi, control=control){2*(xi+control$c)^(-2)}
}
L2 <- function(xi, control=control){2}
elastic <- function(xi, control=control) {control$elastic * L1(xi, control=control) +
(1-control$elastic) * L1(xi, control=control)}
grouped <- function(beta, Aj, control=control) {
dfj <- ncol(Aj)
AjtAj <- Aj%*%t(Aj)
rep(sqrt(dfj) / sqrt(t(beta)%*%AjtAj%*%beta + control$c), ncol(Aj) )
}
A <- function(beta, PenNorm, PenA, PenWeight, control)
{
if (PenNorm=="grouped") {
appro <- as.vector(PenWeight * grouped(beta, PenA, control))
} else {
appro <- as.vector(PenWeight * get(PenNorm)(t(PenA)%*%beta, control))
}
crossprod(t(PenA)*sqrt(appro))
}
start <- coefs <- coefold <- rep(1, sum(indexNrCoefs) + ifelse(intercept, 1, 0))
ff <- as.formula(paste("y ~ ", paste(whichCoefs, collapse="+"), ifelse(intercept, "+1", "-1")))
PP <- vector("list", p)
names(PP) <- whichCoefs
npen <- 0
for (j in 1:length(indexPenA)) { npen <- if (is.matrix(indexPenA[[j]])) {npen + 1} else {npen + length(indexPenA[[j]])} }
inout <- rep(0.01, npen)
conv <- FALSE
if (is.null(tuning)) {
for (i in 1L:control$maxi) {
for (j in 1:p) {
PenAjLength <- length(indexPenA[[j]])
if (!is.matrix(indexPenA[[j]])) {
l <- list()
for (k in 1:PenAjLength) {
l[[k]] <- A(start[vonBis[1,j]:vonBis[2,j]], indexPenNorm[j],
indexPenA[[j]][[k]], indexPenWeight[[j]][[k]], control)
}
PP[[j]] <- l
} else {
PP[[j]] <- list(A(start[vonBis[1,j]:vonBis[2,j]], indexPenNorm[j],
indexPenA[[j]], indexPenWeight[[j]], control))
}
}
mj <- gam(formula=ff, family=family, data=data,
na.action=na.omit, method=method,
optimizer=optimizer,
control=gamcontrol, scale=0,
select=FALSE, knots=NULL, sp=tuning,
min.sp=NULL, H=NULL, gamma=1,
fit=TRUE, paraPen=PP, in.out=list(sp=inout, scale=1)
, start = start
)
start <- (1-control$nu)*coefold + control$nu*mj$coefficients
inout <- mj$sp
if (any(is.na(start))) {
coefs <- coefold
break
}
if (sum(abs(start - coefold))/sum(abs(coefold)) <= control$epsilon) {
conv <- TRUE
coefs <- start
break
} else {
coefs <- coefold <- start
}
}
} else {
for (i in 1L:control$maxi) {
for (j in 1:p) {
PenAjLength <- length(indexPenA[[j]])
if (!is.matrix(indexPenA[[j]])) {
l <- list()
for (k in 1:PenAjLength) {
l[[k]] <- A(start[vonBis[1,j]:vonBis[2,j]], indexPenNorm[j],
indexPenA[[j]][[k]], indexPenWeight[[j]][[k]], control)
}
PP[[j]] <- l
} else {
PP[[j]] <- list(A(start[vonBis[1,j]:vonBis[2,j]], indexPenNorm[j],
indexPenA[[j]], indexPenWeight[[j]], control))
}
}
mj <- gam(formula=ff, family=family, data=data,
na.action=na.omit, method=method,
optimizer=optimizer,
control=gamcontrol, scale=0,
select=FALSE, knots=NULL, sp=tuning,
min.sp=NULL, H=NULL, gamma=1,
fit=TRUE, paraPen=PP
, start = start
)
start <- (1-control$nu)*coefold + control$nu*mj$coefficients
if (any(is.na(start))) {
coefs <- coefold
break
}
if (sum(abs(start - coefold))/sum(abs(coefold)) <= control$epsilon) {
conv <- TRUE
coefs <- start
break
} else {
coefs <- coefold <- start
}
}
}
if (conv == FALSE)
warning("The algorithm did not converge.")
mj$converged <- conv
mj$iter <- i
mj
} |
coherence = function(x, tcm, metrics = c("mean_logratio", "mean_pmi", "mean_npmi", "mean_difference", "mean_npmi_cosim", "mean_npmi_cosim2"), smooth = 1e-12, n_doc_tcm = -1) {
implemented_metrics = c("mean_logratio", "mean_pmi", "mean_npmi", "mean_difference", "mean_npmi_cosim", "mean_npmi_cosim2")
stopifnot(all(metrics %in% implemented_metrics))
n_metrics = length(metrics)
top_terms = as.vector(x)
top_terms_unique = unique(top_terms)
n_topics = ncol(x)
n_terms = nrow(x)
stopifnot( identical(colnames(tcm), rownames(tcm)))
terms_tcm = colnames(tcm)
if (length( setdiff(top_terms_unique, terms_tcm) ) > 0) {
msg = paste("Not all of the top terms 'x' are represented in 'tcm'.",
"Coherence scores for individual topics will be based on incomplete word sets and will be only partially valid.",
"Please consider a thorough check of results before further downstream analysis.")
warning(msg)
}
top_terms_tcm = intersect(top_terms_unique, terms_tcm)
tcm = as.matrix(tcm[top_terms_tcm, top_terms_tcm])
terms_tcm = colnames(tcm)
res = matrix(NA_real_, nrow = n_topics, ncol = n_metrics,
dimnames = list(paste0("topic_", 1:n_topics), metrics))
for(i in seq_len(n_topics)) {
topic_i_term_indices = match(x[, i], terms_tcm)
topic_i_term_indices = topic_i_term_indices[!is.na(topic_i_term_indices)]
for(j in seq_len(n_metrics)) {
m = metrics[j]
logger$debug("calculating coherence metric '%s' for topic %d", m, i)
res[i, j] = calc_coherence(m, topic_i_term_indices, tcm, smooth, n_doc_tcm = n_doc_tcm)
}
}
res
}
calc_coherence = function(metric, term_indices, tcm, smooth, ...) {
switch(metric,
"mean_logratio" = coherence_mean_logratio (term_indices, tcm, smooth, ...),
"mean_pmi" = coherence_mean_pmi (term_indices, tcm, smooth, ...),
"mean_npmi" = coherence_mean_npmi (term_indices, tcm, smooth, ...),
"mean_difference" = coherence_mean_difference (term_indices, tcm, smooth, ...),
"mean_npmi_cosim" = coherence_mean_npmi_cosim (term_indices, tcm, smooth, ...),
"mean_npmi_cosim2" = coherence_mean_npmi_cosim2 (term_indices, tcm, smooth, ...),
stop(sprintf("don't know how to calculate metric '%s'", metric))
)
}
coherence_mean_logratio = function(term_indices, tcm, smooth, ...) {
res = NA
if(length(term_indices) >= 2) {
term_indices = sort(term_indices, decreasing = TRUE)
res = tcm[term_indices, term_indices]
res[upper.tri(res)] = res[upper.tri(res)] + smooth
d = diag(res)
res = t(res)
res = res / d
res = res[lower.tri(res)]
res = log(res)
res = mean(res, na.rm = T)
}
return(res)
}
coherence_mean_pmi = function(term_indices, tcm, smooth, n_doc_tcm, ...) {
stopifnot(n_doc_tcm > 0L)
res = NA
if(length(term_indices) >= 2) {
res = tcm[term_indices, term_indices] / n_doc_tcm
res[upper.tri(res)] = res[upper.tri(res)] + smooth
d = diag(res)
res = res/d
res = res %*% diag(1 / d)
res = res[upper.tri(res)]
res = log2(res)
res = mean(res, na.rm = T)
}
return(res)
}
coherence_mean_difference = function(term_indices, tcm, smooth, n_doc_tcm, ...) {
stopifnot(n_doc_tcm > 0L)
res = NA
if (length(term_indices) >= 2) {
res = tcm[term_indices, term_indices] / n_doc_tcm
d = diag(res)
res = res/d
res = t(res) - d
res = res[lower.tri(res)]
res = mean(res, na.rm = T)
}
return(res)
}
coherence_mean_npmi = function(term_indices, tcm, smooth, n_doc_tcm, ...) {
stopifnot(n_doc_tcm > 0L)
res = NA
if(length(term_indices) >= 2) {
res = tcm[term_indices, term_indices] / n_doc_tcm
res[upper.tri(res)] = res[upper.tri(res)] + smooth
denominator = res[upper.tri(res)]
d = diag(res)
res = res/d
res = res %*% diag(1 / d)
res = res[upper.tri(res)]
res = log2(res) / -log2(denominator)
res = mean(res, na.rm = T)
}
return(res)
}
coherence_mean_npmi_cosim = function(term_indices, tcm, smooth, n_doc_tcm, ...) {
stopifnot(n_doc_tcm > 0L)
res = NA
if(length(term_indices) >= 2) {
res = tcm[term_indices, term_indices] / n_doc_tcm
res[lower.tri(res, diag = F)] = t(res)[lower.tri(res, diag = FALSE)]
res = res + smooth
diag(res) = diag(res) - smooth
denominator = res
d = diag(res)
res = res/d
res = res %*% diag(1 / d)
res = log2(res) / -log2(denominator)
res_compare = t(matrix(rep(colSums(res), nrow(res)), nrow = nrow(res)))
res = psim2(res, res_compare, method = "cosine", norm = "l2")
res = mean(res, na.rm = T)
}
return(res)
}
coherence_mean_npmi_cosim2 = function(term_indices, tcm, smooth, n_doc_tcm, ...) {
stopifnot(n_doc_tcm > 0L)
res = NA
if(length(term_indices) >= 2) {
res = tcm[term_indices, term_indices] / n_doc_tcm
res[lower.tri(res, diag = F)] = t(res)[lower.tri(res, diag = FALSE)]
res = res + smooth
diag(res) = diag(res) - smooth
denominator = res
d = diag(res)
res = res/d
res = res %*% diag(1 / d)
res = log2(res) / -log2(denominator)
res = sim2(res, method = "cosine", norm = "l2")
res = res[upper.tri(res)]
res = mean(res, na.rm = T)
}
return(res)
} |
sel_herb <-
function(start, result, thresh, sdrate, rate, put, max_vec_length=1e+07){
herb_check(put=put, sdrate=sdrate, thresh=thresh, rate=rate)
dfgenotype <- get0("dfgenotype", envir = parent.frame(n = 1))
n_loci <- get0("n_loci", envir = parent.frame(n = 1))
if(is.null(n_loci) | n_loci == 0){
eval(parse(text=paste("dfgenotype$",result,"<-", "dfgenotype$",start, sep="")))
assign("dfgenotype", value=dfgenotype, pos = -1, envir=parent.frame(n = 1))
return(dfgenotype)}
if(is.null(dfgenotype$resist)){
eval(parse(text=paste("dfgenotype$",result,"<-", "dfgenotype$",start,sep="")))
return(dfgenotype)
}
first_amount <- eval(parse(text=paste("dfgenotype$",start,sep="")))
return_amount <- rep(0,nrow(dfgenotype))
for(pres_GT in which(first_amount > 0)){
i1 <- first_amount[pres_GT] %/% max_vec_length
i2 <- first_amount[pres_GT] %% max_vec_length
for(i in seq_len(i1)){
return_amount[pres_GT] <- intern_herbicide(resist=dfgenotype$resist[pres_GT], n_samples=max_vec_length, put=put, rate= rate, sdrate=sdrate, thresh=thresh)
}
return_amount[pres_GT] <- intern_herbicide(resist=dfgenotype$resist[pres_GT], n_samples=i2, put=put, rate= rate, sdrate=sdrate, thresh=thresh)
}
eval(parse(text=paste("dfgenotype$",result,"<-", data.frame(return_amount),sep="")))
assign("dfgenotype", value=dfgenotype, pos = -1, envir=parent.frame(n = 1))
return(dfgenotype)
} |
rinfec <- function(npoints, s.region, t.region, nsim=1, alpha, beta, gamma,
s.distr="exponential", t.distr="uniform", maxrad, delta, h="step", g="min",
recent=1, lambda=NULL, lmax=NULL, nx=100, ny=100, nt=1000,
t0, inhibition=FALSE, ...)
{
if (missing(s.region)) s.region <- matrix(c(0,0,1,1,0,1,1,0),ncol=2)
if (missing(t.region)) t.region <- c(0,1)
if (missing(t0)) t0 <- t.region[1]
if (missing(maxrad)) maxrad <- c(0.05,0.05)
maxrads <- maxrad[1]
maxradt <- maxrad[2]
if (missing(delta)) delta <- maxrads
if (s.distr=="poisson")
{
if (is.matrix(lambda))
{
nx <- dim(lambda)[1]
ny <- dim(lambda)[2]
Lambda <- lambda
}
s.grid <- .make.grid(nx,ny,s.region)
s.grid$mask <- matrix(as.logical(s.grid$mask),nx,ny)
if (is.function(lambda))
{
Lambda <- lambda(as.vector(s.grid$X),as.vector(s.grid$Y),...)
Lambda <- matrix(Lambda,ncol=ny,byrow=T)
}
if (is.null(lambda))
{
Lambda <- matrix(npoints/areapl(s.region),ncol=ny,nrow=nx)
}
Lambda[s.grid$mask==FALSE] <- NaN
}
if (h=="step")
{
hk <- function(t,t0,alpha,beta,gamma)
{
res <- rep(0,length(t))
mask <- (t <= t0+alpha+gamma) & (t >= t0+alpha)
res[mask] <- beta
return(res)
}
}
if (h=="gaussian")
{
hk <- function(t,t0,alpha,beta,gamma)
{
t0 <- alpha+t0
d <- gamma/8
top <- beta*sqrt(2*pi)*d
res <- top*dnorm(t,mean=t0+gamma/2,sd=d)
return(res)
}
d <- gamma/8
top <- beta*sqrt(2*pi)*d
ug <- top*dnorm(0,mean=alpha+gamma/2,sd=d)
}
if (g=="min")
{
pk <- function(mu,recent)
{
if (recent=="all")
res <- min(mu)
else
{
if (is.numeric(recent))
{
if(recent<=length(ITK))
res <- min(mu[(length(ITK)-recent+1):length(ITK)])
else
res <- min(mu)
}
else
stop("'recent' must be numeric")
}
return(res)
}
}
if (g=="max")
{
pk <- function(mu,recent)
{
if (recent=="all")
res <- max(mu)
else
{
if (is.numeric(recent))
{
if(recent<=length(ITK))
res <- max(mu[(length(ITK)-recent+1):length(ITK)])
else
res <- max(mu)
}
else
stop("'recent' must be numeric")
}
return(res)
}
}
if (g=="prod")
{
pk <- function(mu,recent)
{
if (recent=="all")
res <- prod(mu)
else
{
if (is.numeric(recent))
{
if(recent<=length(ITK))
res <- prod(mu[(length(ITK)-recent+1):length(ITK)])
else
res <- prod(mu)
}
else
stop("'recent' must be numeric")
}
return(res)
}
}
t.grid <- list(times=seq(t.region[1],t.region[2],length=nt),tinc=((t.region[2]-t.region[1])/(nt-1)))
pattern <- list()
ni <- 1
while(ni<=nsim)
{
xy <- csr(npoints=1,poly=s.region)
npts <- 1
pattern.interm <- cbind(x=xy[1],y=xy[2],t=t0)
Mu <- rep(0,nt)
ti <- t0
ITK <- findInterval(vec=t.grid$times,x=ti)
continue <- FALSE
while(continue==FALSE)
{
while (npts<npoints)
{
ht <- hk(t=t.grid$times,t0=ti[npts],alpha=alpha,beta=beta,gamma=gamma)
ht <- ht/(sum(ht)*t.grid$tinc)
mu <- Mu+ht
if (sum(mu)==0)
mu2 <- mu
else
mu2 <- mu/max(mu)
if (t.distr=="uniform")
tk <- ti[npts] + runif(1,min=0,max=maxradt)
if (t.distr=="exponential")
tk <- ti[npts] + rexp(1,rate=1/maxradt)
if (tk>=t.region[2])
{
N = npts
npts <- npoints
continue <- TRUE
M = paste("only",N,"points have been generated over",npoints,". Process stopped when getting a time t greater than max(t.region): try a larger t.region or check your parameters",sep=" ")
warning(M)
}
else
{
itk <- findInterval(vec=t.grid$times,x=tk)
if ((mu[itk]==0) || ((h=="gaussian") && (mu[itk]<ug)))
{
N = npts
npts <- npoints
continue <- TRUE
M = paste("only",N,"points have been generated over",npoints,"(process stopped when getting mu(t)=0",sep=" ")
warning(M)
}
else
{
Mu <- mu
if (inhibition==FALSE)
{
cont <- FALSE
while(cont==FALSE)
{
uk <- runif(1)
xpar <- pattern.interm[npts,1]
ypar <- pattern.interm[npts,2]
out <- TRUE
while(out==TRUE)
{
if (s.distr=="uniform")
{
xp <- xpar+runif(1,min=-maxrads,max=maxrads)
yp <- ypar+runif(1,min=-maxrads,max=maxrads)
}
if (s.distr=="gaussian")
{
xp <- xpar+rnorm(1,mean=0,sd=maxrads/2)
yp <- ypar+rnorm(1,mean=0,sd=maxrads/2)
}
if (s.distr=="exponential")
{
xp <- xpar+sample(c(-1,1),1)*rexp(1,rate=1/maxrads)
yp <- ypar+sample(c(-1,1),1)*rexp(1,rate=1/maxrads)
}
if (s.distr=="poisson")
{
if (is.null(lmax))
lmax <- max(Lambda,na.rm=TRUE)
retain.eq.F <- FALSE
while(retain.eq.F==FALSE)
{
xy <- csr(poly=s.region,npoints=1)
xp <- xy[1]
yp <- xy[2]
up <- runif(1)
nix <- findInterval(vec=s.grid$x,x=xp)
niy <- findInterval(vec=s.grid$y,x=yp)
if (nix!=0 & niy!=0)
{
Up <- Lambda[nix,niy]/lmax
retain <- up <= Up
if ((retain==FALSE) || is.na(retain))
retain.eq.F <- FALSE
else
retain.eq.F <- TRUE
}
else
retain.eq.F <- FALSE
}
}
M <- inout(pts=rbind(c(xp,yp),c(xp,yp)),poly=s.region)
if ((sqrt((xp - pattern.interm[npts,1])^2 + (yp - pattern.interm[npts,2])^2) < maxrads)) M <- c(M,M)
if (sum(M)==4)
out <- FALSE
}
if (all(sqrt((xp - pattern.interm[,1])^2 + (yp - pattern.interm[,2])^2) < delta))
umax <- 1
else
umax <- pk(mu=mu2[ITK],recent=recent)
if (uk < umax)
{
npts <- npts+1
ITK <- c(ITK,itk)
ti <- c(ti,tk)
pattern.interm <- rbind(pattern.interm,c(xp,yp,tk))
cont <- TRUE
}
}
}
else
{
uk <- runif(1)
xy <- csr(npoints=1,poly=s.region)
xp <- xy[1]
yp <- xy[2]
if (all((sqrt((xp - pattern.interm[,1])^2 + (yp - pattern.interm[,2])^2)) > delta))
umax <- 1
else
umax <- pk(mu=mu2[ITK],recent=recent)
if (uk < umax)
{
npts <- npts+1
ITK <- c(ITK,itk)
ti <- c(ti,tk)
pattern.interm <- rbind(pattern.interm,c(xp,yp,tk))
}
}
}
}
}
continue <- TRUE
}
dimnames(pattern.interm) <- list(NULL,c("x","y","t"))
if (nsim==1)
{
pattern <- as.3dpoints(pattern.interm)
ni <- ni+1
}
else
{
pattern[[ni]] <- as.3dpoints(pattern.interm)
ni <- ni+1
}
}
invisible(return(list(xyt=pattern,s.region=s.region,t.region=t.region)))
}
|
devpart <-
function (null, environment, community, full) {
getdev <- function (y, z) {
p <- pnorm(z, log.p = TRUE)
for(j in 1:ncol(y)) {
ind <- which(!y[, j])
p[, ind, j] <- log(-expm1(p[, ind, j]))
}
-2 * apply(p, 1, colSums)
}
nuldev <- getdev(null$call$Y, null$trace$z)
envdev <- getdev(environment$call$Y, environment$trace$z)
comdev <- getdev(community$call$Y, community$trace$z)
fuldev <- getdev(full$call$Y, full$trace$z)
nul <- rbind(rowMeans(nuldev), apply(nuldev, 1, quantile, c(0.25, 0.975)))
env <- rbind(rowMeans(envdev), apply(envdev, 1, quantile, c(0.25, 0.975)))
com <- rbind(rowMeans(comdev), apply(comdev, 1, quantile, c(0.25, 0.975)))
ful <- rbind(rowMeans(fuldev), apply(fuldev, 1, quantile, c(0.25, 0.975)))
rownames(nul)[1] <- rownames(env)[1] <- rownames(com)[1] <- rownames(ful)[1] <- "Mean"
propR2 <- t(rbind(1 - env[1, ] / nul[1, ], 1 - com[1, ] / nul[1, ], 1 - ful[1, ] / nul[1, ], rep(1, length(env[1, ]))))
colnames(propR2) <- c("env", "com", "full", "total")
rownames(propR2) <- colnames(full$call$Y)
list(devpart = propR2, null = nul, environment = env, community = com, full = ful)
} |
grid_plot <- function(figs, width = NULL, height = NULL,
nrow = 1, ncol = 1, byrow = TRUE,
xlim = NULL, ylim = NULL, logo = NULL,
same_axes = FALSE, simplify_axes = TRUE,
y_margin = NULL, x_margin = NULL, link_data = FALSE) {
tb_pars <- list(logo = logo)
tb_pars <- handle_extra_pars(tb_pars, grid_plot_par_validator_map)
if (length(same_axes) == 1) {
same_x <- same_y <- same_axes
} else {
same_x <- same_axes[1]
same_y <- same_axes[2]
}
if (length(simplify_axes) == 1) {
simplify_x <- simplify_y <- simplify_axes
} else {
simplify_x <- simplify_axes[1]
simplify_y <- simplify_axes[2]
}
if (!is.list(figs))
stop("'figs' must be a list")
is_fig_list <- sapply(figs, function(x)
inherits(x$x$spec, "BokehFigure") || is.null(x))
if (any(is_fig_list)) {
if (!all(is_fig_list))
stop(paste("'figs' argument to makeGrid must be a list of BokehFigure objects",
"or a list of lists of BokehFigure objects"), call. = FALSE)
nn <- length(figs)
if (missing(ncol))
ncol <- ceiling(nn / nrow)
if (missing(nrow))
nrow <- ceiling(nn / ncol)
if ((nrow * ncol) < nn) {
if (byrow) {
ncol <- ceiling(nn / nrow)
} else {
nrow <- ceiling(nn / ncol)
}
}
tmp <- lapply(figs, function(fig)
fig$x$spec$model$plot[c("type", "subtype", "id")])
idx <- rep(NA, length(tmp))
cur_fig <- 1
for (ii in seq_along(idx)) {
if (!is.null(figs[[ii]])) {
idx[ii] <- cur_fig
cur_fig <- cur_fig + 1
}
}
idx <- c(idx, rep(NA, (nrow * ncol) - length(idx)))
tmp[sapply(tmp, is.null)] <- NULL
idxm <- matrix(idx, nrow = nrow, ncol = ncol, byrow = byrow)
plot_refs <- vector("list", nrow)
for (ii in seq_len(nrow(idxm))) {
plot_refs[[ii]] <- vector("list", ncol)
for (jj in seq_len(ncol(idxm)))
plot_refs[[ii]][[jj]] <- tmp[[idxm[ii, jj]]]
}
} else {
ok <- sapply(figs, function(x) {
all(sapply(x, function(y)
inherits(y$x$spec, "BokehFigure") || is.null(y)))
})
if (!all(ok))
stop(paste("'figs' argument to makeGrid must be a list of BokehFigure objects",
"or a list of lists of BokehFigure objects"), call. = FALSE)
plot_refs <- lapply(figs, function(x) {
lapply(x, function(y) {
y$x$spec$model$plot[c("type", "subtype", "id")]
})
})
nrow <- length(plot_refs)
ncol <- max(sapply(plot_refs, length))
idxm <- matrix(nrow = nrow, ncol = ncol, data = NA)
cur_fig <- 1
for (ii in seq_along(figs)) {
for (jj in seq_along(figs[[ii]])) {
if (!is.null(figs[[ii]][[jj]])) {
idxm[ii, jj] <- cur_fig
cur_fig <- cur_fig + 1
}
}
}
figs <- unlist(figs, recursive = FALSE)
}
figs[sapply(figs, is.null)] <- NULL
if (!is.null(names(figs))) {
fig_names <- names(figs)
for (ii in seq_along(figs)) {
figs[[ii]] <- add_title(figs[[ii]], fig_names[ii])
}
} else {
for (ii in seq_along(figs)) {
figs[[ii]]$x$spec$model$plot$attributes$title <- NULL
}
}
x_range <- y_range <- NULL
if (same_x) {
x_range <- get_grid_ranges(figs, "x")
for (ii in seq_along(figs)) {
figs[[ii]]$x$spec$xlim <- x_range$range
figs[[ii]]$x$spec$has_x_range <- TRUE
figs[[ii]]$x$spec$model$plot$attributes$x_range <- x_range$mod$ref
}
if (simplify_x) {
idxs <- as.vector(idxm[-nrow(idxm), ])
idxs <- idxs[!is.na(idxs)]
for (ii in idxs) {
if (figs[[ii]]$x$spec$has_x_axis) {
figs[[ii]]$x$spec$model$x_axis$attributes$visible <- FALSE
} else {
figs[[ii]] <- figs[[ii]] %>% x_axis(visible = FALSE)
}
}
if (is.null(x_margin))
x_margin <- 70
}
}
if (same_y) {
y_range <- get_grid_ranges(figs, "y")
for (ii in seq_along(figs)) {
figs[[ii]]$x$spec$ylim <- y_range$range
figs[[ii]]$x$spec$has_y_range <- TRUE
figs[[ii]]$x$spec$model$plot$attributes$y_range <- y_range$mod$ref
}
if (simplify_y) {
idxs <- as.vector(idxm[, -1])
idxs <- idxs[!is.na(idxs)]
for (ii in idxs) {
if (figs[[ii]]$x$spec$has_y_axis) {
figs[[ii]]$x$spec$model$y_axis$attributes$visible <- FALSE
} else {
figs[[ii]] <- figs[[ii]] %>% y_axis(visible = FALSE)
}
}
if (is.null(y_margin))
y_margin <- 45
}
}
if (!is.null(xlim)) {
id <- gen_id(figs[[1]], c("x", "GridRange"))
x_range <- list(range = xlim,
mod = range_model(ifelse(is.numeric(xlim), "Range1d", "FactorRange"), id, xlim))
for (ii in seq_along(figs)) {
figs[[ii]]$x$spec$xlim <- xlim
figs[[ii]]$x$spec$has_x_range <- TRUE
figs[[ii]]$x$spec$model$plot$attributes$x_range <- x_range$mod$ref
}
}
if (!is.null(ylim)) {
id <- gen_id(figs[[1]], c("y", "GridRange"))
y_range <- list(range = ylim,
mod = range_model(ifelse(is.numeric(ylim), "Range1d", "FactorRange"), id, ylim))
for (ii in seq_along(figs)) {
figs[[ii]]$x$spec$ylim <- ylim
figs[[ii]]$x$spec$has_y_range <- TRUE
figs[[ii]]$x$spec$model$plot$attributes$y_range <- y_range$mod$ref
}
}
for (ii in seq_along(figs)) {
figs[[ii]]$x$spec$model$plot$attributes["toolbar_location"] <- list(NULL)
figs[[ii]]$x$spec$model$plot$attributes$sizing_mode <- NULL
}
layoutspec <- list()
mcid <- gen_id(figs[[1]], "MasterColumn")
mcmod <- base_model_object("Column", mcid)
spacer_id_mat <- matrix(nrow = nrow(idxm), ncol = ncol(idxm), data = NA)
rrefs <- list()
for (row in seq_len(nrow(idxm))) {
refs <- list()
for (col in seq_along(idxm[row, ])) {
idx <- idxm[row, col]
if (is.na(idx)) {
spid <- gen_id(figs[[idx]], paste0("spacer", row, "_", col))
spmod <- base_model_object("Spacer", spid)
layoutspec[[spid]] <- spmod$model
refs[[col]] <- spmod$ref
spacer_id_mat[row, col] <- spmod$ref$id
} else {
refs[[col]] <- figs[[idx]]$x$spec$ref
}
}
rid <- gen_id(figs[[1]], paste0("Row", row))
rowmod <- base_model_object("Row", rid)
rowmod$model$attributes$children <- refs
rowmod$model$attributes$id <- NULL
rowmod$model$attributes$tags <- NULL
layoutspec[[rid]] <- rowmod$model
rrefs[[row]] <- rowmod$ref
}
mcmod$model$attributes$children <- rrefs
mcmod$model$attributes$id <- NULL
mcmod$model$attributes$tags <- NULL
layoutspec$mastercolumn <- mcmod$model
tbbid <- gen_id(figs[[1]], "ToolbarBox")
tbbmod <- base_model_object("ToolbarBox", tbbid)
tbbmod$model$attributes$sizing_mode <- "scale_width"
tbbmod$model$attributes$toolbar_location <- "above"
if ("logo" %in% names(tb_pars))
tbbmod$model$attributes["logo"] <- list(tb_pars$logo)
alltools <- unname(unlist(lapply(figs,
function(a) {
unname(a$x$spec$model$toolbar$attributes$tools)
}
), recursive = FALSE))
tbbmod$model$attributes$tools <- alltools
tbbmod$model$attributes$sizing_mode <- "scale_width"
layoutspec$toolbarbox <- tbbmod$model
rcid <- gen_id(list(x = list(spec = list(time = Sys.time()))), "root_column")
root_column <- base_model_object("Column", rcid)
root_column$model$attributes$children <- list(tbbmod$ref, mcmod$ref)
root_column$model$attributes$id <- NULL
root_column$model$attributes$tags <- NULL
layoutspec$root <- root_column$model
spec <- structure(list(
layout = layoutspec,
plot_refs = plot_refs,
spacer_id_mat = spacer_id_mat,
figs = figs,
x_range = x_range$mod$model,
y_range = y_range$mod$model,
link_data = link_data,
x_margin = x_margin, y_margin = y_margin,
nrow = nrow, ncol = ncol), class = "BokehGridPlot")
obj <- htmlwidgets::createWidget(
name = "rbokeh",
x = list(
spec = spec,
elementid = digest(Sys.time()),
modeltype = "GridPlot",
modelid = rcid,
docid = digest::digest(paste("rbokehgridplot", Sys.time())),
docs_json = list(list(
version = get_bokeh_version(),
title = "Bokeh GridPlot",
roots = list(
root_ids = list(rcid),
references = NULL
)))
),
sizingPolicy = htmlwidgets::sizingPolicy(defaultWidth = 800, defaultHeight = 800),
preRenderHook = rbokeh_prerender,
width = width,
height = height,
package = "rbokeh"
)
names(obj$x$docs_json) <- obj$x$docid
dims <- lapply(obj$x$spec$figs, function(x) {
list(
id = x$x$spec$model$plot$id,
width = x$x$spec$model$plot$attributes$plot_width,
height = x$x$spec$model$plot$attributes$plot_height
)
})
names(dims) <- sapply(dims, function(x) x$id)
wmat <- matrix(0, nrow = obj$x$spec$nrow, ncol = obj$x$spec$ncol)
hmat <- matrix(0, nrow = obj$x$spec$nrow, ncol = obj$x$spec$ncol)
for (ii in seq_along(obj$x$spec$plot_refs)) {
for (jj in seq_along(obj$x$spec$plot_refs[[ii]])) {
if (is.null(obj$x$spec$plot_refs[[ii]][[jj]])) {
wmat[ii, jj] <- NA
hmat[ii, jj] <- NA
} else {
ww <- dims[[obj$x$spec$plot_refs[[ii]][[jj]]$id]]$width
if (is.null(ww))
ww <- 800 / ncol(wmat)
wmat[ii, jj] <- ww
hh <- dims[[obj$x$spec$plot_refs[[ii]][[jj]]$id]]$height
if (is.null(hh))
hh <- 800 / nrow(hmat)
hmat[ii, jj] <- hh
}
}
}
cmax <- apply(wmat, 2, max, na.rm = TRUE)
rmax <- apply(hmat, 1, max, na.rm = TRUE)
wna <- which(is.na(wmat), arr.ind = TRUE)
if (length(wna) > 0) {
for (ii in seq_len(nrow(wna))) {
wmat[wna[ii, 1], wna[ii, 2]] <- cmax[wna[ii, 2]]
}
}
hna <- which(is.na(hmat), arr.ind = TRUE)
if (length(hna) > 0) {
for (ii in seq_len(nrow(hna))) {
hmat[hna[ii, 1], hna[ii, 2]] <- rmax[hna[ii, 1]]
}
}
obj$x$spec$wmat <- wmat
obj$x$spec$hmat <- hmat
obj_width <- sum(apply(wmat, 2, function(x) max(x, na.rm = TRUE)))
obj_height <- sum(apply(hmat, 1, function(x) max(x, na.rm = TRUE)))
if (is.null(obj$width))
obj$width <- obj_width
if (is.null(obj$height))
obj$height <- obj_height
names(obj$x$spec$figs) <- sapply(obj$x$spec$figs, function(x) x$x$spec$model$plot$id)
obj
}
prepare_gridplot <- function(obj) {
obj <- update_grid_sizes(obj)
figs <- lapply(obj$x$spec$figs, prepare_figure)
data_mods <- list()
if (obj$x$spec$link_data) {
sigs <- do.call(c, lapply(figs, function(x)
unique(do.call(c, lapply(x$x$spec$data_sigs, function(y) y$sig)))))
sigst <- table(sigs)
idx <- which(sigst > 1)
if (length(idx) > 0) {
for (sig in names(idx)) {
has_data <- list()
for (ii in seq_along(figs)) {
for (jj in seq_along(figs[[ii]]$x$spec$data_sigs)) {
if (!is.null(figs[[ii]]$x$spec$data_sigs[[jj]]$sig))
if (figs[[ii]]$x$spec$data_sigs[[jj]]$sig == sig)
has_data[[length(has_data) + 1]] <- list(index = c(ii, jj),
glr_id = figs[[ii]]$x$spec$data_sigs[[jj]]$glr_id)
}
}
d_id <- gen_id(NULL, sig)
new_data_ref <- list(type = "ColumnDataSource", id = d_id)
hd1 <- has_data[[1]]$index
gl1 <- has_data[[1]]$glr_id
ds1 <- figs[[hd1[1]]]$x$spec$model[[gl1]]$attributes$data_source$id
d1 <- figs[[hd1[1]]]$x$spec$model[[ds1]]$attributes$data
figs[[hd1[1]]]$x$spec$model[[gl1]]$attributes$data_source <- new_data_ref
new_data <- d1
figs[[hd1[1]]]$x$spec$model[[ds1]] <- NULL
for (ii in seq_along(has_data)[-1]) {
hd <- has_data[[ii]]$index
glr <- has_data[[ii]]$glr_id
ds <- figs[[hd[1]]]$x$spec$model[[glr]]$attributes$data_source$id
gl <- figs[[hd[1]]]$x$spec$model[[glr]]$attributes$glyph$id
nsgl <- figs[[hd[1]]]$x$spec$model[[glr]]$attributes$nonselection_glyph$id
d <- figs[[hd[1]]]$x$spec$model[[ds]]$attributes$data
merge_names <- intersect(names(d),
c("x", "y", "fill_color", "fill_alpha", "line_color",
"line_width", "line_alpha"))
new_names <- paste0(merge_names, ii)
d2 <- d[merge_names]
names(d2) <- new_names
new_data <- c(new_data, d2, d[setdiff(names(d), c(new_names, names(new_data)))])
upd <- figs[[hd[1]]]$x$spec$model[[gl]]$attributes[merge_names]
for (nm in names(upd)) {
if (!is.null(upd[[nm]]$field))
upd[[nm]]$field <- paste0(upd[[nm]]$field, ii)
}
figs[[hd[1]]]$x$spec$model[[gl]]$attributes[merge_names] <- upd
upd <- figs[[hd[1]]]$x$spec$model[[nsgl]]$attributes[merge_names]
for (nm in names(upd)) {
if (!is.null(upd[[nm]]$field))
upd[[nm]]$field <- paste0(upd[[nm]]$field, ii)
}
figs[[hd[1]]]$x$spec$model[[nsgl]]$attributes[merge_names] <- upd
figs[[hd[1]]]$x$spec$model[[glr]]$attributes$data_source <- new_data_ref
figs[[hd[1]]]$x$spec$model[[ds]] <- NULL
}
data_mods[[sig]] <- data_model(new_data, d_id)
}
} else {
message(paste("'link_data' was set to TRUE, but none of the figures",
"in the grid have the same data source."))
}
}
mod <- unlist(lapply(figs, function(fig) remove_model_names(fig$x$spec$model)), recursive = FALSE)
xxrange <- obj$x$spec$x_range
if (!is.null(xxrange)) {
xxrange <- list(xxrange)
}
yyrange <- obj$x$spec$y_range
if (!is.null(yyrange)) {
yyrange <- list(yyrange)
}
dmods <- unname(lapply(data_mods, function(x) x$model))
if (length(dmods) == 0)
dmods <- NULL
mod <- c(mod, remove_model_names(obj$x$spec$layout), xxrange, yyrange, dmods)
names(mod) <- NULL
obj$x$padding <- list(type = "gridplot")
obj$x$spec$model <- mod
obj
}
get_grid_ranges <- function(objs, which = "x") {
w1 <- paste0("glyph_", which, "_ranges")
w2 <- paste0(which, "_axis_type")
ranges <- unlist(lapply(objs, function(x) x$x$spec[[w1]]), recursive = FALSE)
rng <- get_all_glyph_range(ranges,
objs[[1]]$x$spec$padding_factor, objs[[1]]$x$spec[[w2]])
id <- gen_id(objs[[1]], c(which, "GridRange"))
list(range = rng,
mod = range_model(ifelse(is.numeric(rng), "Range1d", "FactorRange"), id, rng))
}
update_grid_sizes <- function(obj) {
width <- obj$width
height <- obj$height
hmat <- obj$x$spec$hmat
wmat <- obj$x$spec$wmat
x_margin <- obj$x$spec$x_margin
y_margin <- obj$x$spec$y_margin
if (is.null(x_margin))
x_margin <- 0
if (is.null(y_margin))
y_margin <- 0
widths <- apply(wmat, 2, function(x) max(x, na.rm = TRUE))
heights <- apply(hmat, 1, function(x) max(x, na.rm = TRUE))
full_width <- sum(widths)
full_height <- sum(heights)
new_width_factor <- (width - y_margin) / full_width
new_height_factor <- (height - x_margin - 30) / full_height
new_wmat <- wmat * new_width_factor
new_hmat <- hmat * new_height_factor
new_wmat[, 1] <- new_wmat[, 1] + y_margin
new_hmat[nrow(new_hmat), ] <- new_hmat[nrow(new_hmat), ] + x_margin
obj$width <- sum(apply(new_wmat, 2, function(x) max(x, na.rm = TRUE))) + 30
obj$height <- sum(apply(new_hmat, 1, function(x) max(x, na.rm = TRUE)))
for (ii in seq_along(obj$x$spec$plot_refs)) {
for (jj in seq_along(obj$x$spec$plot_refs[[ii]])) {
if (!is.null(obj$x$spec$plot_refs[[ii]][[jj]])) {
cur_id <- obj$x$spec$plot_refs[[ii]][[jj]]$id
obj$x$spec$figs[[cur_id]]$width <- new_wmat[ii, jj]
obj$x$spec$figs[[cur_id]]$height <- new_hmat[ii, jj]
if (jj == 1) {
obj$x$spec$figs[[cur_id]]$x$spec$model$plot$attributes$min_border_left <- y_margin
}
if (ii == length(obj$x$spec$plot_refs)) {
obj$x$spec$figs[[cur_id]]$x$spec$model$plot$attributes$min_border_bottom <- x_margin
}
} else {
spid <- obj$x$spec$spacer_id_mat[ii, jj]
obj$x$spec$layout[[spid]]$attributes$width <- new_wmat[ii, jj]
obj$x$spec$layout[[spid]]$attributes$height <- new_hmat[ii, jj]
}
}
}
obj
}
grid_plot_par_validator_map <- list(
"toolbar_location" = "toolbar_location",
"logo" = "logo"
) |
vkGetGroupStatGenderAge <-
function(
date_from = Sys.Date() - 7,
date_to = Sys.Date(),
group_id = NULL,
interval = "day",
intervals_count = NULL,
filters = NULL,
stats_groups = c("visitors", "reach", "activity"),
username = getOption("rvkstat.username"),
api_version = getOption("rvkstat.api_version"),
token_path = vkTokenPath(),
access_token = getOption("rvkstat.access_token")
)
{
if ( is.null(access_token) ) {
if ( Sys.getenv("RVK_API_TOKEN") != "" ) {
access_token <- Sys.getenv("RVK_API_TOKEN")
} else {
access_token <- vkAuth(username = username,
token_path = token_path)$access_token
}
}
if ( class(access_token) == "vk_auth" ) {
access_token <- access_token$access_token
}
answer <- GET("https://api.vk.com/method/stats.get",
query = list(
group_id = group_id,
timestamp_from = as.numeric(as.POSIXct(date_from)),
timestamp_to = as.numeric(as.POSIXct(paste0(date_to, " 23:59:59"))),
interval = interval,
intervals_count = intervals_count,
filters = filters,
stats_groups = paste0(stats_groups, collapse = ","),
access_token = access_token,
v = api_version
)
)
stop_for_status(answer)
dataRaw <- content(answer, "parsed", "application/json")
if(!is.null(dataRaw$error)){
stop(paste0("Error ", dataRaw$error$error_code," - ", dataRaw$error$error_msg))
}
result <- tibble(response = dataRaw$response) %>%
unnest_wider("response") %>%
select("period_from", "period_to", "reach") %>%
unnest_wider("reach") %>%
select("period_from", "period_to", "sex_age") %>%
unnest_longer("sex_age") %>%
unnest_wider("sex_age") %>%
separate("value",
into = c("gender", "age"),
sep = ";") %>%
rename(visitors = "count")
if ( nrow(result) > 0 ) {
result$period_from <- as.POSIXct(result$period_from, origin = '1970-01-01')
result$period_to <- as.POSIXct(result$period_to, origin = '1970-01-01')
}
return(result)
} |
dcl.boot<-function(dcl.par,sigma2,Ntriangle,boot.type=2,B=999,Tail=TRUE,
summ.by="diag",Tables=TRUE,num.dec=2,n.cal=NA)
{
if (missing(sigma2)) sigma2<-dcl.par$sigma2
if (is.na(sigma2) | sigma2<=0) stop('The variance estimate is null or negative. See the documentation for suggestions.')
Ntriangle<-as.matrix(Ntriangle)
mu.adj<-dcl.par$mu.adj
Vy<-dcl.par$Vy
Ey<-dcl.par$Ey
pj<-dcl.par$pj
adj<-dcl.par$adj
m<-length(pj);d<-m-1
Nhat<-dcl.par$Nhat
alpha.N<-dcl.par$alpha.N
beta.N<-dcl.par$beta.N
if (missing(Ntriangle)) Ntriangle<-Nhat
preds<-dcl.predict(dcl.par,Ntriangle,Model=2,Tail,Tables=FALSE)
Drbns<-preds$Drbns
Rrbns<-preds$Rrbns
Dibnr<-preds$Dibnr
Ribnr<-preds$Ribnr
Dtotal<-preds$Dtotal
Rtotal<-preds$Rtotal
BootI<-function(b,Ntriangle,Nhat,m,d,pj,Ey,Vy)
{
delta<- Ey^2 / Vy
nu<- Ey/Vy
delta_star<- delta
nu_star<- nu
Npred_star<-Nhat
pj_star<-pj
Npred_star[row(Npred_star)+col(Npred_star)<=m+1]<-NA
Nest_ext<-cbind(Npred_star,matrix(NA,nrow=m,ncol=d))
Nlist_star<-apply(Nest_ext, MARGIN=1:2, function(v) if (!is.na(v))
as.vector(rmultinom(n=1,size=v,prob=pj_star)) else NA)
Narray_star<-array(NA,dim=c(m,m+d,d+1))
for (i in 2:m)
{
for (j in (m-i+2):m)
{
Narray_star[i,j,]<-rmultinom(n=1,size=Npred_star[i,j],prob=pj_star)
}
}
Nibnr_star<-matrix(NA,nrow=m,ncol= m+d)
for (i in 2:m)
{
for (j in (m-i+2):(m+d))
{
lim2<- j:(max(m-i+2,j-d))
for (ll in lim2)
{
Nibnr_star[i,j]<- sum(c(Nibnr_star[i,j],Narray_star[i,ll,j-ll+1]),na.rm=T)
}
}
}
rm(Narray_star)
Xibnr_star<-matrix(NA,nrow=m,ncol= m+d)
for (i in 2:m)
{
for (j in (m-i+2):(m+d))
{
Xibnr_star[i,j]<-rgamma(n=1,scale=1/nu_star[i],shape=Nibnr_star[i,j]*delta_star[i])
}
}
Nlist_star<-apply(Ntriangle, MARGIN=1:2, FUN=function(v) {
if (!is.na(v)) as.vector(rmultinom(n=1,size=v,prob=pj_star)) else NA} )
Narray_star<-array(NA,dim=c(m,m,d+1))
for (i in 1:m)
{
for (j in 1:(m-i+1))
{
Narray_star[i,j,]<-rmultinom(n=1,size=Ntriangle[i,j],prob=pj_star)
}
}
Nrbns_star<-matrix(NA,nrow=m,ncol= m+d)
for (i in 1:m)
{
for (j in (m-i+2):(m+d-i+1))
{
lim2<- (max(1,j-d)):(max(m-i+1,j-d))
for (ll in lim2)
{
Nrbns_star[i,j]<- sum(c(Nrbns_star[i,j],Narray_star[i,ll,j-ll+1]),na.rm=T)
}
}
}
rm(Narray_star)
Xrbns_star<-matrix(NA,nrow=m,ncol= m+d)
for (i in 1:m)
{
for (j in (m-i+2):(m+d-i+1))
{
Xrbns_star[i,j]<-rgamma(n=1,scale=1/nu_star[i],shape=Nrbns_star[i,j]*delta_star[i])
}
}
return(list(Xibnr_star=Xibnr_star,Xrbns_star=Xrbns_star))
}
BootII<-function(b,Ntriangle,alpha.N,beta.N,m,d,pj,Ey,Vy)
{
set.triangle<-expand.grid(1:m,1:m)
Npois<-apply(set.triangle,MARGIN=1,
FUN= function(v) {
j<-as.numeric(v[1])
i<-as.numeric(v[2])
if (j<(m-i+2))
{
if (Ntriangle[i,j]>0) v.e<-rpois(n=1,lambda=round(Ntriangle[i,j])) else v.e<-0
} else v.e<-NA
return(v.e)
})
Ntriangle_star<-matrix(Npois,m,m,byrow=T)
clm.N.star<-clm(Ntriangle_star,n.cal=n.cal)
Npred_star<-clm.N.star$triangle.hat
Nlist_star<-apply(Ntriangle, MARGIN=1:2,
function(v) {
if (!is.na(v)) {
if (v>0) return(as.vector(rmultinom(n=1,size=v,prob=pj))) else return(rep(0,d))
}})
v.Npaid<-apply(set.triangle,MARGIN=1, FUN= function(v){
j<-as.numeric(v[1]);i<-as.numeric(v[2]);
if (j<(m-i+2)) {lim.m<-0:(min(d,j-1))
v.n<- sapply(lim.m, function(vv) unlist(Nlist_star[i,j-vv])[vv+1]);
v.n<-sum(v.n,na.rm=T)} else v.n<-NA
return(v.n) })
Npaid_star<-matrix(v.Npaid,m,m,byrow=T)
Npaid_star<-cbind(Npaid_star,matrix(NA,nrow=m,ncol=d))
Xtriangle_star<-matrix(NA,nrow=m,ncol= m)
delta<- Ey^2 / Vy
nu<- Ey/Vy
v.X<-apply(set.triangle,MARGIN=1,FUN= function(v) {
j<-as.numeric(v[1]);i<-as.numeric(v[2]);
if (j<(m-i+2)) v.X<-rgamma(n=1,scale=1/nu[i],shape=Npaid_star[i,j]*delta[i]) else v.X<-NA
return(v.X)})
Xtriangle_star<-matrix(v.X,m,m,byrow=T)
par.star<-dcl.estimation(Xtriangle_star,Ntriangle,adj,Tables=FALSE,n.cal=n.cal)
pj_star<-par.star$pj
Ey_star<-as.vector(par.star$Ey)
mu_star<-Ey_star[1]
Vy_star<-as.vector(par.star$Vy)
if (any(Vy_star<=0)) Vy_star<-Vy
delta_star<- Ey_star^2 / Vy_star
nu_star<- Ey_star/Vy_star
Npred_star[row(Npred_star)+col(Npred_star)<=m+1]<-NA
Nest_ext<-cbind(Npred_star,matrix(NA,nrow=m,ncol=d))
Nlist_star<-apply(Nest_ext, MARGIN=1:2, function(v) if (!is.na(v))
as.vector(rmultinom(n=1,size=v,prob=pj_star)) else NA)
Narray_star<-array(NA,dim=c(m,m+d,d+1))
for (i in 2:m)
{
for (j in (m-i+2):m)
{
Narray_star[i,j,]<-rmultinom(n=1,size=Npred_star[i,j],prob=pj_star)
}
}
Nibnr_star<-matrix(NA,nrow=m,ncol= m+d)
for (i in 2:m)
{
for (j in (m-i+2):(m+d))
{
lim2<- j:(max(m-i+2,j-d))
for (ll in lim2)
{
Nibnr_star[i,j]<- sum(c(Nibnr_star[i,j],Narray_star[i,ll,j-ll+1]),na.rm=T)
}
}
}
rm(Narray_star)
Xibnr_star<-matrix(NA,nrow=m,ncol= m+d)
for (i in 2:m)
{
for (j in (m-i+2):(m+d))
{
Xibnr_star[i,j]<-rgamma(n=1,scale=1/nu_star[i],shape=Nibnr_star[i,j]*delta_star[i])
}
}
Nlist_star<-apply(Ntriangle, MARGIN=1:2, FUN=function(v) {
if (!is.na(v)) as.vector(rmultinom(n=1,size=v,prob=pj_star)) else NA} )
Narray_star<-array(NA,dim=c(m,m,d+1))
for (i in 1:m)
{
for (j in 1:(m-i+1))
{
Narray_star[i,j,]<-rmultinom(n=1,size=Ntriangle[i,j],prob=pj_star)
}
}
Nrbns_star<-matrix(NA,nrow=m,ncol= m+d)
for (i in 1:m)
{
for (j in (m-i+2):(m+d-i+1))
{
lim2<- (max(1,j-d)):(max(m-i+1,j-d))
for (ll in lim2)
{
Nrbns_star[i,j]<- sum(c(Nrbns_star[i,j],Narray_star[i,ll,j-ll+1]),na.rm=T)
}
}
}
rm(Narray_star)
Xrbns_star<-matrix(NA,nrow=m,ncol= m+d)
for (i in 1:m)
{
for (j in (m-i+2):(m+d-i+1))
{
Xrbns_star[i,j]<-rgamma(n=1,scale=1/nu_star[i],shape=Nrbns_star[i,j]*delta_star[i])
}
}
return(list(Xibnr_star=Xibnr_star,Xrbns_star=Xrbns_star))
}
app<-logical(0)
array.rbns.boot<-array.ibnr.boot<-array(0,dim=c(m,m+d,B))
for (b in 1:B)
{
if (b==1) {app<-F;
print('Please wait, simulating the distribution...')
} else app<-T
if (boot.type==1) res.boot<-BootI(b,Ntriangle,Nhat,m,d,pj,Ey,Vy)
if (boot.type==2) res.boot<-BootII(b,Ntriangle,alpha.N,beta.N,m,d,pj,Ey,Vy)
array.rbns.boot[,,b]<-as.matrix(res.boot$Xrbns_star)
array.ibnr.boot[,,b]<-as.matrix(res.boot$Xibnr_star)
if (b==B) print('Done!')
}
if (summ.by=='diag')
{
dd<-m+d-1 +1
Mat_rbns<-Mat_ibnr<-matrix(0,B,dd)
for (b in 1:B)
{
Xrbns_star<-array.rbns.boot[,,b]
Xibnr_star<-array.ibnr.boot[,,b]
if (Tail==FALSE) {Xrbns_star[,(m+1):( 2*m-1)]<-0;Xibnr_star[,(m+1):( 2*m-1)]<-0}
Drbns_star<-sapply(split(Xrbns_star, row(Xrbns_star)+col(Xrbns_star)), sum, na.rm=T)
Drbns_star<-as.vector(Drbns_star[-(1:m)])
Mat_rbns[b,]<-c(Drbns_star,sum(Drbns_star,na.rm =T))
Dibnr_star<-sapply(split(Xibnr_star, row(Xibnr_star)+col(Xibnr_star)), sum, na.rm=T)
Dibnr_star<-as.vector(Dibnr_star[-(1:m)])
Mat_ibnr[b,]<-c(Dibnr_star,sum(Dibnr_star,na.rm =T))
}
} else {
dd<-m+1
Mat_rbns<-Mat_ibnr<-matrix(0,B,dd)
for (b in 1:B)
{
Xrbns_star<-array.rbns.boot[,,b]
Rrbns_star<-as.vector(rowSums(Xrbns_star))
Mat_rbns[b,]<-c(Rrbns_star,sum(Rrbns_star,na.rm =T))
Xibnr_star<-array.ibnr.boot[,,b]
Ribnr_star<-as.vector(rowSums(Xibnr_star))
Mat_ibnr[b,]<-c(Ribnr_star,sum(Ribnr_star,na.rm =T))
}
}
Mat_total<-Mat_rbns+Mat_ibnr
mean.Drbns<-colMeans(Mat_rbns)
mean.Drbns<-round(mean.Drbns,num.dec)
sd.Drbns<-apply(Mat_rbns,2,sd)
sd.Drbns<-round(sd.Drbns,num.dec)
quantiles.Drbns<-apply(Mat_rbns,2,quantile,c(0.01,0.05,0.5,0.95,0.99))
quantiles.Drbns<-round(quantiles.Drbns,num.dec)
mean.Dibnr<-colMeans(Mat_ibnr)
mean.Dibnr<-round(mean.Dibnr,num.dec)
sd.Dibnr<-apply(Mat_ibnr,2,sd)
sd.Dibnr<-round(sd.Dibnr,num.dec)
quantiles.Dibnr<-apply(Mat_ibnr,2,quantile,c(0.01,0.05,0.5,0.95,0.99))
quantiles.Dibnr<-round(quantiles.Dibnr,num.dec)
mean.Dtotal<-colMeans(Mat_total)
mean.Dtotal<-round(mean.Dtotal,num.dec)
sd.Dtotal<-apply(Mat_total,2,sd)
sd.Dtotal<<-round(sd.Dtotal,num.dec)
quantiles.Dtotal<-apply(Mat_total,2,quantile,c(0.01,0.05,0.5,0.95,0.99))
quantiles.Dtotal<-round(quantiles.Dtotal,num.dec)
if (Tables==TRUE)
{
period<-c(1:(dd-1),'Tot.')
resD_rbns<-data.frame(period,rbns=round(Drbns,num.dec),
mean.rbns=round(mean.Drbns,num.dec),sd.rbns=round(sd.Drbns,num.dec),
Q1.rbns=round(quantiles.Drbns[1,],num.dec),
Q5.rbns=round(quantiles.Drbns[2,],num.dec)
,Q50.rbns=round(quantiles.Drbns[3,],num.dec),
Q95.rbns=round(quantiles.Drbns[4,],num.dec),
Q99.rbns=round(quantiles.Drbns[5,],num.dec))
resD_ibnr<-data.frame(period,ibnr=round(Dibnr,num.dec),
mean.ibnr=round(mean.Dibnr,num.dec),sd.ibnr=round(sd.Dibnr,num.dec),
Q1.ibnr=round(quantiles.Dibnr[1,],num.dec),
Q5.ibnr=round(quantiles.Dibnr[2,],num.dec),
Q50.ibnr=round(quantiles.Dibnr[3,],num.dec),
Q95.ibnr=round(quantiles.Dibnr[4,],num.dec),
Q99.ibnr=round(quantiles.Dibnr[5,],num.dec))
resD_total<-data.frame(period,total=round(Dtotal,num.dec),
mean.total=round(mean.Dtotal,num.dec),sd.total=round(sd.Dtotal,num.dec),
Q1.total=round(quantiles.Dtotal[1,],num.dec),
Q5.total=round(quantiles.Dtotal[2,],num.dec),
Q50.total=round(quantiles.Dtotal[3,],num.dec),
Q95.total=round(quantiles.Dtotal[4,],num.dec),
Q99.total=round(quantiles.Dtotal[5,],num.dec))
print(resD_rbns)
print(resD_ibnr)
print(resD_total)
res<-list(array.rbns.boot=array.rbns.boot,array.ibnr.boot=array.ibnr.boot,
Mat.rbns=Mat_rbns,Mat.ibnr=Mat_ibnr,Mat.total=Mat_total,
summ.rbns=resD_rbns,summ.ibnr=resD_ibnr,summ.total=resD_total)
} else {
res<-list(array.rbns.boot=array.rbns.boot,array.ibnr.boot=array.ibnr.boot,
Mat.rbns=Mat_rbns,Mat.ibnr=Mat_ibnr,Mat.total=Mat_total)
}
return(res)
} |
library(RFLPtools)
library(MKomics)
M <- 5
N <- 10
nrB <- 3:10
checkResultsGerm <- function(newName, resData){
rownames(resData[[newName]])[1] == newName
}
dist2ref <- function(nB, newData, refData, distfun = dist, nrMissing = 0, LOD = 0){
newData$Sample <- paste("New", newData$Sample, sep = "_")
complData <- rbind(newData, refData)
if(nrMissing == 0){
res <- RFLPdist(complData, nrBands = nB, distfun = distfun, LOD = LOD)
}else{
res <- RFLPdist2(complData, nrBands = nB, distfun = distfun,
nrMissing = nrMissing)
}
res
}
checkResultsRFLP <- function(resData){
resData <- as.matrix(resData)
resData <- resData[,grepl("New", colnames(resData))]
resData <- resData[!grepl("New", rownames(resData)),]
newNam <- sapply(strsplit(colnames(resData), split = "_"), "[", 2)
refNam <- rownames(resData)[apply(resData, 2, which.min)]
sum(refNam == newNam)
}
checkResultsFragMatch <- function(resData, nrMissing = 0){
Matches <- sapply(apply(resData, 2, strsplit, split = "_"),
function(x, nrMissing){
sapply(x,
function(x, nrMissing){
as.integer(x[1]) == (as.integer(x[2])-nrMissing)
},
nrMissing = nrMissing)
}, nrMissing = nrMissing)
rowNams <- rownames(resData)
colNams <- colnames(resData)
nrMatch <- 0
for(i in 1:ncol(Matches)){
if(colNams[i] %in% rowNams[which(Matches[,i])]) nrMatch <- nrMatch + 1
}
nrMatch
}
acc.germ.joint1 <- numeric(M)
acc.germ.forward1 <- numeric(M)
acc.germ.backward1 <- numeric(M)
acc.germ.sum1 <- numeric(M)
acc.rflptools.eucl1 <- numeric(M)
acc.rflptools.cor1 <- numeric(M)
acc.rflptools.diff1 <- numeric(M)
acc.FragMatch1.5 <- numeric(M)
acc.FragMatch1.10 <- numeric(M)
acc.FragMatch1.25 <- numeric(M)
for(i in 1:M){
print(i)
refData1 <- simulateRFLPdata(N = N, bandCenters = seq(200, 800, by = 100),
nrBands = nrB, refData = TRUE)
newData1 <- refData1
newData1$MW <- newData1$MW + rnorm(nrow(newData1), mean = 0, sd = 5)
res1.germ.joint <- germ(newData = newData1, refData = refData1)
res1.germ.forward <- lapply(res1.germ.joint, function(x) x[order(x[,"Forward Max"]),])
res1.germ.backward <- lapply(res1.germ.joint, function(x) x[order(x[,"Backward Max"]),])
res1.germ.sum <- lapply(res1.germ.joint, function(x) x[order(x[,"Sum of Bands"]),])
SampleNames <- unique(refData1$Sample)
acc.germ.joint1[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res1.germ.joint))/length(SampleNames)
acc.germ.forward1[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res1.germ.forward))/length(SampleNames)
acc.germ.backward1[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res1.germ.backward))/length(SampleNames)
acc.germ.sum1[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res1.germ.sum))/length(SampleNames)
res1.rflptools.eucl <- lapply(nrB, dist2ref, newData = newData1, refData = refData1)
res1.rflptools.cor <- lapply(nrB, dist2ref, newData = newData1, refData = refData1, dist = corDist)
res1.rflptools.diff <- lapply(nrB, dist2ref, newData = newData1, refData = refData1, dist = diffDist)
acc.rflptools.eucl1[i] <- 100*sum(sapply(res1.rflptools.eucl, checkResultsRFLP))/length(SampleNames)
acc.rflptools.cor1[i] <- 100*sum(sapply(res1.rflptools.cor, checkResultsRFLP))/length(SampleNames)
acc.rflptools.diff1[i] <- 100*sum(sapply(res1.rflptools.diff, checkResultsRFLP))/length(SampleNames)
res1.FragMatch.5 <- FragMatch(newData = newData1, refData = refData1, errorBound = 5)
res1.FragMatch.10 <- FragMatch(newData = newData1, refData = refData1, errorBound = 10)
res1.FragMatch.25 <- FragMatch(newData = newData1, refData = refData1, errorBound = 25)
acc.FragMatch1.5[i] <- 100*checkResultsFragMatch(res1.FragMatch.5)/length(SampleNames)
acc.FragMatch1.10[i] <- 100*checkResultsFragMatch(res1.FragMatch.10)/length(SampleNames)
acc.FragMatch1.25[i] <- 100*checkResultsFragMatch(res1.FragMatch.25)/length(SampleNames)
}
mean(acc.germ.joint1)
mean(acc.germ.forward1)
mean(acc.germ.backward1)
mean(acc.germ.sum1)
mean(acc.rflptools.eucl1)
mean(acc.rflptools.cor1)
mean(acc.rflptools.diff1)
mean(acc.FragMatch1.5)
mean(acc.FragMatch1.10)
mean(acc.FragMatch1.25)
acc.germ.joint2 <- numeric(M)
acc.germ.forward2 <- numeric(M)
acc.germ.backward2 <- numeric(M)
acc.germ.sum2 <- numeric(M)
acc.rflptools.eucl2 <- numeric(M)
acc.rflptools.cor2 <- numeric(M)
acc.rflptools.diff2 <- numeric(M)
acc.rflptools.eucl21 <- numeric(M)
acc.rflptools.cor21 <- numeric(M)
acc.rflptools.diff21 <- numeric(M)
acc.FragMatch2.5 <- numeric(M)
acc.FragMatch2.10 <- numeric(M)
acc.FragMatch2.25 <- numeric(M)
for(i in 1:M){
print(i)
refData2 <- simulateRFLPdata(N = N, bandCenters = seq(200, 800, by = 100),
nrBands = nrB, refData = TRUE)
SampleNames <- unique(refData2$Sample)
for(j in 1:length(SampleNames)){
temp <- refData2[refData2$Sample == SampleNames[j],]
addLOD <- data.frame(Sample = SampleNames[j],
Band = 0,
MW = runif(1, min = 0, max = 100),
Enzyme = temp$Enzyme[1],
Taxonname = temp$Taxonname[1],
Accession = temp$Accession[1])
temp <- rbind(addLOD, temp)
temp$Band <- temp$Band + 1
if(j == 1)
newData2 <- temp
else
newData2 <- rbind(newData2, temp)
}
rownames(newData2) <- 1:nrow(newData2)
newData2$MW <- newData2$MW + rnorm(nrow(newData2), mean = 0, sd = 5)
res2.germ.joint <- germ(newData = newData2, refData = refData2)
res2.germ.forward <- lapply(res2.germ.joint, function(x) x[order(x[,"Forward Max"]),])
res2.germ.backward <- lapply(res2.germ.joint, function(x) x[order(x[,"Backward Max"]),])
res2.germ.sum <- lapply(res2.germ.joint, function(x) x[order(x[,"Sum of Bands"]),])
acc.germ.joint2[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res2.germ.joint))/length(SampleNames)
acc.germ.forward2[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res2.germ.forward))/length(SampleNames)
acc.germ.backward2[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res2.germ.backward))/length(SampleNames)
acc.germ.sum2[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res2.germ.sum))/length(SampleNames)
res2.rflptools.eucl <- lapply(nrB, dist2ref, newData = newData2, refData = refData2, LOD = 125)
res2.rflptools.cor <- lapply(nrB, dist2ref, newData = newData2, refData = refData2, dist = corDist, LOD = 125)
res2.rflptools.diff <- lapply(nrB, dist2ref, newData = newData2, refData = refData2, dist = diffDist, LOD = 125)
res2.rflptools.eucl1 <- lapply(nrB, dist2ref, newData = newData2, refData = refData2, nrMissing = 1)
res2.rflptools.cor1 <- lapply(nrB, dist2ref, newData = newData2, refData = refData2, dist = corDist, nrMissing = 1)
res2.rflptools.diff1 <- lapply(nrB, dist2ref, newData = newData2, refData = refData2, dist = diffDist, nrMissing = 1)
acc.rflptools.eucl2[i] <- 100*sum(sapply(res2.rflptools.eucl, checkResultsRFLP))/length(SampleNames)
acc.rflptools.cor2[i] <- 100*sum(sapply(res2.rflptools.cor, checkResultsRFLP))/length(SampleNames)
acc.rflptools.diff2[i] <- 100*sum(sapply(res2.rflptools.diff, checkResultsRFLP))/length(SampleNames)
acc.rflptools.eucl21[i] <- 100*sum(sapply(res2.rflptools.eucl1, checkResultsRFLP))/length(SampleNames)
acc.rflptools.cor21[i] <- 100*sum(sapply(res2.rflptools.cor1, checkResultsRFLP))/length(SampleNames)
acc.rflptools.diff21[i] <- 100*sum(sapply(res2.rflptools.diff1, checkResultsRFLP))/length(SampleNames)
res2.FragMatch.5 <- FragMatch(newData = newData2, refData = refData2, errorBound = 5)
res2.FragMatch.10 <- FragMatch(newData = newData2, refData = refData2, errorBound = 10)
res2.FragMatch.25 <- FragMatch(newData = newData2, refData = refData2, errorBound = 25)
acc.FragMatch2.5[i] <- 100*checkResultsFragMatch(res2.FragMatch.5)/length(SampleNames)
acc.FragMatch2.10[i] <- 100*checkResultsFragMatch(res2.FragMatch.10)/length(SampleNames)
acc.FragMatch2.25[i] <- 100*checkResultsFragMatch(res2.FragMatch.25)/length(SampleNames)
}
mean(acc.germ.joint2)
mean(acc.germ.forward2)
mean(acc.germ.backward2)
mean(acc.germ.sum2)
mean(acc.rflptools.eucl2)
mean(acc.rflptools.cor2)
mean(acc.rflptools.diff2)
mean(acc.rflptools.eucl21)
mean(acc.rflptools.cor21)
mean(acc.rflptools.diff21)
mean(acc.FragMatch2.5)
mean(acc.FragMatch2.10)
mean(acc.FragMatch2.25)
acc.germ.joint3 <- numeric(M)
acc.germ.forward3 <- numeric(M)
acc.germ.backward3 <- numeric(M)
acc.germ.sum3 <- numeric(M)
acc.rflptools.eucl3 <- numeric(M)
acc.rflptools.cor3 <- numeric(M)
acc.rflptools.diff3 <- numeric(M)
acc.FragMatch3.5 <- numeric(M)
acc.FragMatch3.10 <- numeric(M)
acc.FragMatch3.25 <- numeric(M)
for(i in 1:M){
print(i)
refData3 <- simulateRFLPdata(N = N, bandCenters = seq(200, 800, by = 100),
nrBands = nrB, refData = TRUE)
SampleNames <- unique(refData3$Sample)
for(j in 1:length(SampleNames)){
temp <- refData3[refData3$Sample == SampleNames[j],]
addBand <- data.frame(Sample = SampleNames[j],
Band = max(temp$Band)+1,
MW = -runif(1, min = 150, max = 850),
Enzyme = temp$Enzyme[1],
Taxonname = temp$Taxonname[1],
Accession = temp$Accession[1])
temp <- rbind(temp, addBand)
temp <- temp[order(abs(temp$MW)),]
temp$Band <- 1:nrow(temp)
if(j == 1)
newData3 <- temp
else
newData3 <- rbind(newData3, temp)
}
rownames(newData3) <- 1:nrow(newData3)
newData3$MW <- newData3$MW + rnorm(nrow(newData3), mean = 0, sd = 5)
res3.germ.joint <- germ(newData = newData3, refData = refData3)
res3.germ.forward <- lapply(res3.germ.joint, function(x) x[order(x[,"Forward Max"]),])
res3.germ.backward <- lapply(res3.germ.joint, function(x) x[order(x[,"Backward Max"]),])
res3.germ.sum <- lapply(res3.germ.joint, function(x) x[order(x[,"Sum of Bands"]),])
acc.germ.joint3[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res3.germ.joint))/length(SampleNames)
acc.germ.forward3[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res3.germ.forward))/length(SampleNames)
acc.germ.backward3[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res3.germ.backward))/length(SampleNames)
acc.germ.sum3[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res3.germ.sum))/length(SampleNames)
newData31 <- newData3
newData31$MW <- abs(newData31$MW)
res3.rflptools.eucl1 <- lapply(nrB, dist2ref, newData = newData31, refData = refData3, nrMissing = 1)
res3.rflptools.cor1 <- lapply(nrB, dist2ref, newData = newData31, refData = refData3, dist = corDist, nrMissing = 1)
res3.rflptools.diff1 <- lapply(nrB, dist2ref, newData = newData31, refData = refData3, dist = diffDist, nrMissing = 1)
acc.rflptools.eucl3[i] <- 100*sum(sapply(res3.rflptools.eucl1, checkResultsRFLP))/length(SampleNames)
acc.rflptools.cor3[i] <- 100*sum(sapply(res3.rflptools.cor1, checkResultsRFLP))/length(SampleNames)
acc.rflptools.diff3[i] <- 100*sum(sapply(res3.rflptools.diff1, checkResultsRFLP))/length(SampleNames)
res3.FragMatch.5 <- FragMatch(newData = newData31, refData = refData3, errorBound = 5)
res3.FragMatch.10 <- FragMatch(newData = newData31, refData = refData3, errorBound = 10)
res3.FragMatch.25 <- FragMatch(newData = newData31, refData = refData3, errorBound = 25)
acc.FragMatch3.5[i] <- 100*checkResultsFragMatch(res3.FragMatch.5)/length(SampleNames)
acc.FragMatch3.10[i] <- 100*checkResultsFragMatch(res3.FragMatch.10)/length(SampleNames)
acc.FragMatch3.25[i] <- 100*checkResultsFragMatch(res3.FragMatch.25)/length(SampleNames)
}
mean(acc.germ.joint3)
mean(acc.germ.forward3)
mean(acc.germ.backward3)
mean(acc.germ.sum3)
mean(acc.rflptools.eucl3)
mean(acc.rflptools.cor3)
mean(acc.rflptools.diff3)
mean(acc.FragMatch3.5)
mean(acc.FragMatch3.10)
mean(acc.FragMatch3.25)
acc.germ.joint4 <- numeric(M)
acc.germ.forward4 <- numeric(M)
acc.germ.backward4 <- numeric(M)
acc.germ.sum4 <- numeric(M)
acc.rflptools.eucl4 <- numeric(M)
acc.rflptools.cor4 <- numeric(M)
acc.rflptools.diff4 <- numeric(M)
acc.FragMatch4.5 <- numeric(M)
acc.FragMatch4.10 <- numeric(M)
acc.FragMatch4.25 <- numeric(M)
for(i in 1:M){
print(i)
refData4 <- simulateRFLPdata(N = N, bandCenters = seq(200, 800, by = 100),
nrBands = nrB, refData = TRUE)
SampleNames <- unique(refData4$Sample)
for(j in 1:length(SampleNames)){
temp <- refData4[refData4$Sample == SampleNames[j],]
temp <- temp[-sample(1:nrow(temp), 1),]
temp$Band <- 1:nrow(temp)
if(j == 1)
newData4 <- temp
else
newData4 <- rbind(newData4, temp)
}
rownames(newData4) <- 1:nrow(newData4)
newData4$MW <- newData4$MW + rnorm(nrow(newData4), mean = 0, sd = 5)
res4.germ.joint <- germ(newData = newData4, refData = refData4)
res4.germ.forward <- lapply(res4.germ.joint, function(x) x[order(x[,"Forward Max"]),])
res4.germ.backward <- lapply(res4.germ.joint, function(x) x[order(x[,"Backward Max"]),])
res4.germ.sum <- lapply(res4.germ.joint, function(x) x[order(x[,"Sum of Bands"]),])
acc.germ.joint4[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res4.germ.joint))/length(SampleNames)
acc.germ.forward4[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res4.germ.forward))/length(SampleNames)
acc.germ.backward4[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res4.germ.backward))/length(SampleNames)
acc.germ.sum4[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res4.germ.sum))/length(SampleNames)
res4.rflptools.eucl1 <- lapply(nrB, dist2ref, newData = newData4, refData = refData4, nrMissing = 1)
res4.rflptools.cor1 <- lapply(nrB, dist2ref, newData = newData4, refData = refData4, dist = corDist, nrMissing = 1)
res4.rflptools.diff1 <- lapply(nrB, dist2ref, newData = newData4, refData = refData4, dist = diffDist, nrMissing = 1)
acc.rflptools.eucl4[i] <- 100*sum(sapply(res4.rflptools.eucl1[-length(nrB)], checkResultsRFLP))/length(SampleNames)
acc.rflptools.cor4[i] <- 100*sum(sapply(res4.rflptools.cor1[-length(nrB)], checkResultsRFLP))/length(SampleNames)
acc.rflptools.diff4[i] <- 100*sum(sapply(res4.rflptools.diff1[-length(nrB)], checkResultsRFLP))/length(SampleNames)
res4.FragMatch.5 <- FragMatch(newData = newData4, refData = refData4, errorBound = 5)
res4.FragMatch.10 <- FragMatch(newData = newData4, refData = refData4, errorBound = 10)
res4.FragMatch.25 <- FragMatch(newData = newData4, refData = refData4, errorBound = 25)
acc.FragMatch4.5[i] <- 100*checkResultsFragMatch(res4.FragMatch.5, nrMissing = 1)/length(SampleNames)
acc.FragMatch4.10[i] <- 100*checkResultsFragMatch(res4.FragMatch.10, nrMissing = 1)/length(SampleNames)
acc.FragMatch4.25[i] <- 100*checkResultsFragMatch(res4.FragMatch.25, nrMissing = 1)/length(SampleNames)
}
mean(acc.germ.joint4)
mean(acc.germ.forward4)
mean(acc.germ.backward4)
mean(acc.germ.sum4)
mean(acc.rflptools.eucl4)
mean(acc.rflptools.cor4)
mean(acc.rflptools.diff4)
mean(acc.FragMatch4.5)
mean(acc.FragMatch4.10)
mean(acc.FragMatch4.25)
acc.germ.joint5 <- numeric(M)
acc.germ.forward5 <- numeric(M)
acc.germ.backward5 <- numeric(M)
acc.germ.sum5 <- numeric(M)
acc.rflptools.eucl5 <- numeric(M)
acc.rflptools.cor5 <- numeric(M)
acc.rflptools.diff5 <- numeric(M)
acc.FragMatch5.5 <- numeric(M)
acc.FragMatch5.10 <- numeric(M)
acc.FragMatch5.25 <- numeric(M)
for(i in 1:M){
print(i)
refData5 <- simulateRFLPdata(N = N, bandCenters = seq(200, 800, by = 100),
nrBands = nrB, refData = TRUE)
SampleNames <- unique(refData5$Sample)
for(j in 1:length(SampleNames)){
temp <- refData5[refData5$Sample == SampleNames[j],]
addBand <- temp[sample(1:nrow(temp), 1),, drop = FALSE]
temp <- rbind(temp, addBand)
temp <- temp[order(abs(temp$MW)),]
temp$Band <- 1:nrow(temp)
if(j == 1)
newData5 <- temp
else
newData5 <- rbind(newData5, temp)
}
rownames(newData5) <- 1:nrow(newData5)
newData5$MW <- newData5$MW + rnorm(nrow(newData5), mean = 0, sd = 5)
res5.germ.joint <- germ(newData = newData5, refData = refData5)
res5.germ.forward <- lapply(res5.germ.joint, function(x) x[order(x[,"Forward Max"]),])
res5.germ.backward <- lapply(res5.germ.joint, function(x) x[order(x[,"Backward Max"]),])
res5.germ.sum <- lapply(res5.germ.joint, function(x) x[order(x[,"Sum of Bands"]),])
acc.germ.joint5[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res5.germ.joint))/length(SampleNames)
acc.germ.forward5[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res5.germ.forward))/length(SampleNames)
acc.germ.backward5[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res5.germ.backward))/length(SampleNames)
acc.germ.sum5[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res5.germ.sum))/length(SampleNames)
res5.rflptools.eucl1 <- lapply(nrB, dist2ref, newData = newData5, refData = refData5, nrMissing = 1)
res5.rflptools.cor1 <- lapply(nrB, dist2ref, newData = newData5, refData = refData5, dist = corDist, nrMissing = 1)
res5.rflptools.diff1 <- lapply(nrB, dist2ref, newData = newData5, refData = refData5, dist = diffDist, nrMissing = 1)
acc.rflptools.eucl5[i] <- 100*sum(sapply(res5.rflptools.eucl1, checkResultsRFLP))/length(SampleNames)
acc.rflptools.cor5[i] <- 100*sum(sapply(res5.rflptools.cor1, checkResultsRFLP))/length(SampleNames)
acc.rflptools.diff5[i] <- 100*sum(sapply(res5.rflptools.diff1, checkResultsRFLP))/length(SampleNames)
res5.FragMatch.5 <- FragMatch(newData = newData5, refData = refData5, errorBound = 5)
res5.FragMatch.10 <- FragMatch(newData = newData5, refData = refData5, errorBound = 10)
res5.FragMatch.25 <- FragMatch(newData = newData5, refData = refData5, errorBound = 25)
acc.FragMatch5.5[i] <- 100*checkResultsFragMatch(res5.FragMatch.5)/length(SampleNames)
acc.FragMatch5.10[i] <- 100*checkResultsFragMatch(res5.FragMatch.10)/length(SampleNames)
acc.FragMatch5.25[i] <- 100*checkResultsFragMatch(res5.FragMatch.25)/length(SampleNames)
}
mean(acc.germ.joint5)
mean(acc.germ.forward5)
mean(acc.germ.backward5)
mean(acc.germ.sum5)
mean(acc.rflptools.eucl5)
mean(acc.rflptools.cor5)
mean(acc.rflptools.diff5)
mean(acc.FragMatch5.5)
mean(acc.FragMatch5.10)
mean(acc.FragMatch5.25)
shift <- 50
acc.germ.joint6 <- numeric(M)
acc.germ.forward6 <- numeric(M)
acc.germ.backward6 <- numeric(M)
acc.germ.sum6 <- numeric(M)
acc.rflptools.eucl6 <- numeric(M)
acc.rflptools.cor6 <- numeric(M)
acc.rflptools.diff6 <- numeric(M)
acc.FragMatch6.5 <- numeric(M)
acc.FragMatch6.10 <- numeric(M)
acc.FragMatch6.25 <- numeric(M)
for(i in 1:M){
print(i)
refData6 <- simulateRFLPdata(N = N, bandCenters = seq(200, 800, by = 100),
nrBands = nrB, refData = TRUE)
newData6 <- refData6
newData6$MW <- newData6$MW + shift
newData6$MW <- newData6$MW + rnorm(nrow(newData6), mean = 0, sd = 5)
res6.germ.joint <- germ(newData = newData6, refData = refData6)
res6.germ.forward <- lapply(res6.germ.joint, function(x) x[order(x[,"Forward Max"]),])
res6.germ.backward <- lapply(res6.germ.joint, function(x) x[order(x[,"Backward Max"]),])
res6.germ.sum <- lapply(res6.germ.joint, function(x) x[order(x[,"Sum of Bands"]),])
SampleNames <- unique(refData6$Sample)
acc.germ.joint6[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res6.germ.joint))/length(SampleNames)
acc.germ.forward6[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res6.germ.forward))/length(SampleNames)
acc.germ.backward6[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res6.germ.backward))/length(SampleNames)
acc.germ.sum6[i] <- 100*sum(sapply(SampleNames, checkResultsGerm, resData = res6.germ.sum))/length(SampleNames)
res6.rflptools.eucl <- lapply(nrB, dist2ref, newData = newData6, refData = refData6)
res6.rflptools.cor <- lapply(nrB, dist2ref, newData = newData6, refData = refData6, dist = corDist)
res6.rflptools.diff <- lapply(nrB, dist2ref, newData = newData6, refData = refData6, dist = diffDist)
acc.rflptools.eucl6[i] <- 100*sum(sapply(res6.rflptools.eucl, checkResultsRFLP))/length(SampleNames)
acc.rflptools.cor6[i] <- 100*sum(sapply(res6.rflptools.cor, checkResultsRFLP))/length(SampleNames)
acc.rflptools.diff6[i] <- 100*sum(sapply(res6.rflptools.diff, checkResultsRFLP))/length(SampleNames)
res6.FragMatch.5 <- FragMatch(newData = newData6, refData = refData6, errorBound = 5)
res6.FragMatch.10 <- FragMatch(newData = newData6, refData = refData6, errorBound = 10)
res6.FragMatch.25 <- FragMatch(newData = newData6, refData = refData6, errorBound = 25)
acc.FragMatch6.5[i] <- 100*checkResultsFragMatch(res6.FragMatch.5)/length(SampleNames)
acc.FragMatch6.10[i] <- 100*checkResultsFragMatch(res6.FragMatch.10)/length(SampleNames)
acc.FragMatch6.25[i] <- 100*checkResultsFragMatch(res6.FragMatch.25)/length(SampleNames)
}
mean(acc.germ.joint6)
mean(acc.germ.forward6)
mean(acc.germ.backward6)
mean(acc.germ.sum6)
mean(acc.rflptools.eucl6)
mean(acc.rflptools.cor6)
mean(acc.rflptools.diff6)
mean(acc.FragMatch6.5)
mean(acc.FragMatch6.10)
mean(acc.FragMatch6.25) |
find_neighbors2 <- function(sce, platform) {
if (platform == "Visium") {
offsets <- data.frame(x.offset=c(-2, 2, -1, 1, -1, 1),
y.offset=c( 0, 0, -1, -1, 1, 1))
} else if (platform == "ST") {
offsets <- data.frame(x.offset=c( 0, 1, 0, -1),
y.offset=c(-1, 0, 1, 0))
} else {
stop(".find_neighbors: Unsupported platform \"", platform, "\".")
}
spot.positions <- SingleCellExperiment::colData(sce)[, c("col", "row")]
spot.positions$spot.idx <- seq_len(nrow(spot.positions))
neighbor.positions <- merge(spot.positions, offsets)
neighbor.positions$x.pos <- neighbor.positions$col + neighbor.positions$x.offset
neighbor.positions$y.pos <- neighbor.positions$row + neighbor.positions$y.offset
neighbors <- merge(as.data.frame(neighbor.positions),
as.data.frame(spot.positions),
by.x=c("x.pos", "y.pos"), by.y=c("col", "row"),
suffixes=c(".primary", ".neighbor"),
all.x=TRUE)
neighbors <- neighbors[order(neighbors$spot.idx.primary,
neighbors$spot.idx.neighbor), ]
df_j <- split(neighbors$spot.idx.neighbor, neighbors$spot.idx.primary)
df_j <- unname(df_j)
df_j <- purrr::map(df_j, function(nbrs) purrr::discard(nbrs, function(x) is.na(x)))
n_with_neighbors <- length(purrr::keep(df_j, function(nbrs) length(nbrs) > 0))
message("Neighbors were identified for ", n_with_neighbors, " out of ",
ncol(sce), " spots.")
n <- length(df_j)
D <- Matrix::sparseMatrix(i = 1:n, j = 1:n, x = 0)
for (i in 1:n) {
if(length(df_j[[i]]) != 0)
D[i, df_j[[i]]] <- 1
}
D
} |
NULL
align_pander <- function(x, align_idx = NULL, caption = NULL) {
.Deprecated("kable", package = "knitr")
invisible()
} |
context("running company_information")
with_mock_api({
test_that("running ", {
expect_error(company_information("BAD"))
res <- company_information("EA")
expect_is(res, "data.frame")
expect_length(res, 19)
expect_length(rownames(res), 1)
expect_equal(res$name, "ELECTRONIC ARTS INC.")
})
}) |
.file.extensions <-
list(clustal = "aln", fasta = c("fas", "fasta", "fa"),
fastq = c("fq", "fastq"), newick = c("nwk", "newick", "tre", "tree"),
nexus = c("nex", "nexus"), phylip = "phy")
Xplorefiles <- function(from = "HOME", recursive = TRUE, ignore.case = TRUE)
{
if (from == "HOME") from <- Sys.getenv("HOME")
FILES <- list.files(path = from, recursive = recursive, full.names = TRUE)
ext <- if (exists(".file.extensions", envir = .PlotPhyloEnv))
get(".file.extensions", envir = .PlotPhyloEnv)
else .file.extensions
res <- vector("list", length(ext))
names(res) <- names(ext)
for (i in seq_along(res)) {
e <- paste0("\\.", ext[[i]], "$")
if (length(e) > 1) e <- paste(e, collapse = "|")
x <- grep(e, FILES, ignore.case = ignore.case, value = TRUE)
res[[i]] <- data.frame(File = x, Size = file.size(x),
stringsAsFactors = FALSE)
}
res
}
editFileExtensions <- function()
{
foo <- function(x) {
n <- length(x)
if (n < m) x[(n + 1):m] <- NA
x
}
res <- if (exists(".file.extensions", envir = .PlotPhyloEnv))
get(".file.extensions", envir = .PlotPhyloEnv)
else .file.extensions
m <- max(lengths(res, FALSE))
res <- lapply(res, foo)
res <- as.data.frame(res, stringsAsFactors = FALSE)
res <- edit(res)
res <- lapply(res, function(x) x[!is.na(x)])
assign(".file.extensions", res, envir = .PlotPhyloEnv)
}
bydir <- function(x)
{
nofile <- which(sapply(x, nrow) == 0)
if (length(nofile)) x <- x[-nofile]
if (!length(x)) {
cat("No file\n")
return(invisible(NULL))
}
for (i in seq_along(x)) x[[i]]$Type <- names(x)[i]
x <- do.call(rbind, x)
x <- x[order(x$File), ]
SPLIT <- strsplit(x$File, "/")
LL <- lengths(SPLIT)
foo <- function(i, PATH) {
K <- grep(paste0("^", PATH, "/"), x$File)
sel <- intersect(K, which(LL == i + 1L))
if (length(sel)) {
y <- x[sel, ]
y$File <- gsub(".*/", "", y$File)
cat("\n", PATH, "/\n", sep = "")
print(y, row.names = FALSE)
}
if (length(sel) < length(K)) {
d <- setdiff(K, sel)
subdir <- unlist(lapply(SPLIT[d], "[", i + 1L))
for (z in unique(subdir))
foo(i + 1L, paste(PATH, z, sep = "/"))
}
}
top <- unlist(lapply(SPLIT, "[", 1L))
for (z in unique(top)) foo(1L, z)
}
Xplor <- function(from = "HOME")
{
ext <- if (exists(".file.extensions", envir = .PlotPhyloEnv))
get(".file.extensions", envir = .PlotPhyloEnv)
else .file.extensions
OUT <- paste0(tempfile(), ".html")
mycat <- function(...) cat(..., sep = "", file = OUT, append = TRUE)
FILES <- Xplorefiles(from = from)
filetypes <- names(FILES)
NR <- sapply(FILES, nrow)
mycat('<html><title>Files Sorted by Type</title></head>')
mycat('<h2>File types searched:</h2>')
mycat('<TABLE border=0>')
mycat('<tr><th align="center"> Type </th><th align="center"> Number of files </th><th align="center"> Extensions* </th></tr>')
for (type in filetypes) {
mycat('<tr><td><a href=
'</td><td align="center">', paste(paste0(".", ext[[type]]), collapse = " "), '</td></tr>')
}
mycat('</TABLE>')
mycat('<br>*Case-independent<br>To change the files extensions, type in R: <font face = "courier">editFileExtensions()</font><br>')
if (all(NR == 0)) {
browseURL(OUT)
return(invisible(NULL))
}
OUTBYDIR <- paste0(tempfile(), ".html")
sink(OUTBYDIR)
cat('<html><title>Files Sorted by Directory</title></head>')
.bydir.html(FILES)
cat('</html>')
sink(NULL)
mycat('<br><a target="blank" href=', OUTBYDIR, '><h2>Files sorted by directory (in new tab)</h2></a><br>')
for (type in filetypes) {
nr <- NR[type]
mycat('<a name=', type, '></a><h1>', toupper(type), '</h1>')
if (nr == 0) {
mycat('no file of this type')
next
}
DF <- FILES[[type]]
mycat('<TABLE border=1>')
mycat('<tr><th> File name </th><th align="center"> Size (KB) </th></tr>')
for (i in 1:nr)
mycat('<tr><td><a href="file://', DF[i, 1], '">', DF[i, 1],
'</a></td><td align="right">', round(DF[i, 2]/1000, 1), '</td></tr>')
mycat('</TABLE>')
}
mycat('</html>')
browseURL(OUT)
}
.bydir.html <- function(x)
{
nofile <- which(sapply(x, nrow) == 0)
if (length(nofile)) x <- x[-nofile]
if (!length(x)) return(NULL)
for (i in seq_along(x)) x[[i]]$Type <- names(x)[i]
x <- do.call(rbind, x)
x <- x[order(x$File), ]
SPLIT <- strsplit(x$File, "/")
LL <- lengths(SPLIT)
foo <- function(i, PATH) {
K <- grep(paste0("^", PATH, "/"), x$File)
sel <- intersect(K, which(LL == i + 1L))
if (length(sel)) {
y <- x[sel, ]
y$File <- gsub(".*/", "", y$File)
cat('<h2><a href="file://', PATH, '">', PATH, '/</a></h2>', sep = "")
cat('<TABLE border=1>')
cat('<tr><th> File </th><th align="center"> Size (KB) </th><th align="center"> Type </th></tr>')
for (i in 1:nrow(y))
cat('<tr><td><a href="file://', PATH, '/', y[i, 1], '">', y[i, 1],
'</a></td><td align="right">', round(y[i, 2]/1000, 1),
'</td><td align="right">', y[i, 3], '</td></tr>', sep = "")
cat('</TABLE><br>')
}
if (length(sel) < length(K)) {
d <- setdiff(K, sel)
subdir <- unlist(lapply(SPLIT[d], "[", i + 1L))
for (z in unique(subdir))
foo(i + 1L, paste(PATH, z, sep = "/"))
}
}
top <- unlist(lapply(SPLIT, "[", 1L))
for (z in unique(top)) foo(1L, z)
} |
save.session <- function(object,folder){
curr <- getwd()
dir.create(folder)
setwd(folder)
save(object,file="GENOME")
if([email protected]){
if(length([email protected])>0){
bial <- [email protected][[1]]
ffsave(bial,file="bial_1")
}else{
for(xx in 1:length([email protected]@biallelic.matrix)){
file.name <- paste("bial_",xx,sep="")
bial <- [email protected]@biallelic.matrix[[xx]]
ffsave(bial,file=file.name)
if([email protected]){
if(is([email protected]@Coding.matrix[[xx]])[1]=="ff_matrix"){
file.name <- paste("Coding.matrix_",xx,sep="")
Coding.matrix <- [email protected]@Coding.matrix[[xx]]
ffsave(Coding.matrix,file=file.name)
}
if(is([email protected]@Gene.matrix[[xx]])[1]=="ff_matrix"){
file.name <- paste("Gene.matrix_",xx,sep="")
Gene.matrix <- [email protected]@Gene.matrix[[xx]]
ffsave(Gene.matrix,file=file.name)
}
if(is([email protected]@Exon.matrix[[xx]])[1]=="ff_matrix"){
file.name <- paste("Exon.matrix_",xx,sep="")
Exon.matrix <- [email protected]@Exon.matrix[[xx]]
ffsave(Exon.matrix,file=file.name)
}
if(is([email protected]@Intron.matrix[[xx]])[1]=="ff_matrix"){
file.name <- paste("Intron.matrix_",xx,sep="")
Intron.matrix <- [email protected]@Intron.matrix[[xx]]
ffsave(Intron.matrix,file=file.name)
}
if(is([email protected]@UTR.matrix[[xx]])[1]=="ff_matrix"){
file.name <- paste("UTR.matrix_",xx,sep="")
UTR.matrix <- [email protected]@UTR.matrix[[xx]]
ffsave(UTR.matrix,file=file.name)
}
}
}
}
}
setwd(curr)
}
load.session <- function(folder){
curr <- getwd()
setwd(folder)
name <- load("GENOME")
object <- get(name[1])
change <- [email protected]
if([email protected]){
if(length([email protected])>0){
ffload("bial_1",overwrite=TRUE)
vcv <- get("bial")
[email protected][[1]] <- vcv
}else{
for(xx in 1:length([email protected]@biallelic.matrix)){
file.name <- paste("bial_",xx,sep="")
ffload(file.name)
ff.object <- get("bial")
[email protected][[xx]] <- ff.object
open([email protected][[xx]])
if([email protected]){
file.name <- paste("Coding.matrix_",xx,sep="")
if(file.exists(paste(file.name,".RData",sep=""))){
ffload(file.name)
ff.object <- get("Coding.matrix")
[email protected][[xx]] <- ff.object
open([email protected][[xx]])
}
file.name <- paste("Gene.matrix_",xx,sep="")
if(file.exists(paste(file.name,".RData",sep=""))){
ffload(file.name)
ff.object <- get("Gene.matrix")
[email protected][[xx]] <- ff.object
open([email protected][[xx]])
}
file.name <- paste("Exon.matrix_",xx,sep="")
if(file.exists(paste(file.name,".RData",sep=""))){
ffload(file.name)
ff.object <- get("Exon.matrix")
[email protected][[xx]] <- ff.object
open([email protected][[xx]])
}
file.name <- paste("Intron.matrix_",xx,sep="")
if(file.exists(paste(file.name,".RData",sep=""))){
ffload(file.name)
ff.object <- get("Intron.matrix")
[email protected][[xx]] <- ff.object
open([email protected][[xx]])
}
file.name <- paste("UTR.matrix_",xx,sep="")
if(file.exists(paste(file.name,".RData",sep=""))){
ffload(file.name)
ff.object <- get("UTR.matrix")
[email protected][[xx]] <- ff.object
open([email protected][[xx]])
}
}
}
}
}
[email protected] <- change
setwd(curr)
assign(folder,object,envir=parent.frame())
} |
require(OpenMx)
data("myRegDataRaw", package="OpenMx")
MultipleDataRaw<-myRegData[,c("z","y","x")]
selVars <- c("x","y","z")
multiRegModel<-mxModel("Multiple Regression Matrix Specification",
mxData(MultipleDataRaw,type="raw"),
mxMatrix("Full", nrow=3, ncol=3,
values=c(0, 0, 0,
1, 0, 1,
0, 0, 0),
free= c(F, F, F,
T, F, T,
F, F, F),
labels=c(NA, NA, NA,
"betax", NA,"betaz",
NA, NA, NA),
byrow=TRUE,
name = "A" ),
mxMatrix("Symm", nrow=3, ncol=3,
values=c(1, 0, .5,
0, 1, 0,
.5, 0, 1),
free= c(T, F, T,
F, T, F,
T, F, T),
labels=c("varx", NA, "covxz",
NA, "residual", NA,
"covxz", NA, "varz"),
byrow=TRUE,
name="S" ),
mxMatrix("Iden", nrow=3, ncol=3,
dimnames = list(selVars,selVars),
name="F"
),
mxMatrix("Full", nrow=1, ncol=3, values=0, free =T,
labels=c("meanx","beta0","meanz"),
dimnames = list(NULL, selVars),
name="M"
),
mxFitFunctionML(),mxExpectationRAM("A","S","F","M")
)
multiRegFit<-mxRun(multiRegModel)
summary(multiRegFit)
omxCheckCloseEnough(multiRegFit$output$estimate[["beta0"]], 1.6332, 0.001)
omxCheckCloseEnough(multiRegFit$output$estimate[["betax"]], 0.4246, 0.001)
omxCheckCloseEnough(multiRegFit$output$estimate[["betaz"]], 0.2260, 0.001)
omxCheckCloseEnough(multiRegFit$output$estimate[["residual"]], 0.6267, 0.001)
omxCheckCloseEnough(multiRegFit$output$estimate[["varx"]], 1.1053, 0.001)
omxCheckCloseEnough(multiRegFit$output$estimate[["varz"]], 0.8275, 0.001)
omxCheckCloseEnough(multiRegFit$output$estimate[["covxz"]], 0.2862, 0.001)
omxCheckCloseEnough(multiRegFit$output$estimate[["meanx"]], 0.0542, 0.001)
omxCheckCloseEnough(multiRegFit$output$estimate[["meanz"]], 4.0611, 0.001) |
context("test-statement")
test_that("creation", {
s <- statement(quote(cl <- theta[1]*exp(eta[1])),
quote(v <- theta[2]))
expect_s3_class(s, "assemblerr_statement")
expect_length(s, 2)
})
test_that("creation from character", {
expect_equal(
statement("cl <- theta"),
statement(quote(cl <- theta))
)
index <- 5
expect_equal(
statement("cl <- theta[{index}]"),
statement(quote(cl <- theta[5]))
)
})
test_that("creation with quoting works", {
a <- 10
s <- statement(bquote(cl <- theta[.(a)]*exp(eta[.(a)])))
expect_equal(s, statement(quote(cl <- theta[10]*exp(eta[10]))))
})
test_that("conversion from declaration",{
d <- declaration(cl~theta[1]*exp(eta[1]), v ~ theta[2], ~exp(eta[1]))
s <- as_statement(d)
expect_equal(s[1], statement(quote(cl <- theta[1]*exp(eta[1]))))
expect_equal(s[2], statement(quote(v <- theta[2])))
expect_equal(s[3], statement(quote(exp(eta[1]))))
})
test_that("code rendering", {
s <- statement(
quote(cl <- theta[1]*exp(eta[1])),
quote(v <- theta[2])
)
expect_equal(render_component(s),
"CL = THETA(1) * EXP(ETA(1))\nV = THETA(2)")
}) |
changeMissings <- function(GADSdat, varName, value, missings) {
UseMethod("changeMissings")
}
changeMissings.GADSdat <- function(GADSdat, varName, value, missings) {
checkMissingsInput(varName = varName, value = value, missings = missings, labels = GADSdat$labels)
changeTable <- getChangeMeta(GADSdat, level = "value")
existing_values <- value[value %in% changeTable[changeTable$varName == varName, "value"]]
existing_missings <- missings[value %in% changeTable[changeTable$varName == varName, "value"]]
new_values <- value[!value %in% changeTable[changeTable$varName == varName, "value"]]
new_missings <- missings[!value %in% changeTable[changeTable$varName == varName, "value"]]
for(i in seq_along(existing_values)) {
changeTable[changeTable$varName == varName & changeTable$value == value[i], "value_new"] <-
changeTable[changeTable$varName == varName & changeTable$value == value[i], "value"]
changeTable[changeTable$varName == varName & changeTable$value == value[i], "valLabel_new"] <-
changeTable[changeTable$varName == varName & changeTable$value == value[i], "valLabel"]
changeTable[changeTable$varName == varName & changeTable$value == value[i], "missings_new"] <- missings[i]
}
for(i in seq_along(new_values)) {
change_row <- changeTable[changeTable$varName == varName, ][1, ]
if(i == 1 && nrow(changeTable[changeTable$varName == varName, ]) == 1) {
changeTable <- changeTable[changeTable$varName != varName, ]
}
change_row[, "value"] <- NA
change_row[, "value_new"] <- new_values[i]
change_row[, "missings_new"] <- new_missings[i]
changeTable <- rbind(changeTable, change_row)
}
applyChangeMeta(GADSdat, changeTable = changeTable)
}
changeMissings.all_GADSdat <- function(GADSdat, varName, value, missings) {
stop("This method has not been implemented yet")
}
checkMissingsInput <- function(varName, value, missings, labels) {
if(!is.character(varName) || !length(varName) == 1) stop("'varName' is not a character vector of length 1.")
if(!varName %in% labels$varName) stop("'varName' is not a variable name in the GADSdat.")
if(length(value) != length(missings)) stop("'value' and 'missings' are not of identical length.", call. = FALSE)
if(!all(missings %in% c("miss", "valid"))) stop("All values in 'missings' need to be 'miss' or 'valid'.")
return()
} |
GLMMMiRKAT <- function(y, X = NULL, Ks, id = NULL, time.pt = NULL, model, method = "perm" ,
slope = FALSE, omnibus = "perm", nperm = 5000){
om <- substring(tolower(omnibus), 1, 1)
if (is.null(time.pt) & slope) {
stop("time.pt is required for the random slope model")
}
if(model != "gaussian" & method == "davies"){
stop("Davies is only available for Gaussian traits")
}
if (model == "gaussian" & method =="davies"){
if (om == "p") {
warning("Permutation omnibus test not available with Davies P-values. Defaulting to Cauchy combination test.")
}
y <- scale(y)
if (is.null(X)) {
if (!is.null(time.pt) & slope) {
fit <- lmer(y ~ (time.pt | id))
} else {
fit <- lmer(y ~ (1 | id))
}
} else {
if (!is.null(time.pt) & slope) {
fit <- lmer(y ~ (time.pt | id) + X)
} else {
fit <- lmer(y ~ (1 | id) + X)
}
}
out <- CSKAT(fit, Ks=Ks)
return(out)
}
if (is.matrix(Ks)) {
Ks <- list(Ks)
no.omnibus <- TRUE
} else {
no.omnibus <- FALSE
}
if (is.null(time.pt)) {
id <- as.character(id)
ind <- order(id)
id <- id[ind]
y <- y[ind]
if (is.matrix(X)|is.data.frame(X)) {
X <- as.matrix(X)[ind, ]
} else {
X <- X[ind]
}
for (i in 1:length(Ks)) {
Ks[[i]] <- Ks[[i]][ind, ind]
}
} else {
ind <- order(as.character(time.pt))
id <- as.character(id)
id <- id[ind]
y <- y[ind]
if (is.matrix(X)|is.data.frame(X)) X <- as.matrix(X)[ind, ] else X <- X[ind]
time.pt <- time.pt[ind]
for (i in 1:length(Ks)) {
Ks[[i]] <- Ks[[i]][ind, ind]
}
ind <- order(id)
id <- id[ind]
y <- y[ind]
if (is.matrix(X)|is.data.frame(X)) X <- as.matrix(X)[ind, ] else X <- X[ind]
time.pt <- time.pt[ind]
for (i in 1:length(Ks)) {
Ks[[i]] <- Ks[[i]][ind, ind]
}
}
if (model == "gaussian") {
y <- scale(y)
if (is.null(X)) {
if (!is.null(time.pt) & slope) {
fit <- lmer(y ~ (time.pt | id))
} else {
fit <- lmer(y ~ (1 | id))
}
} else {
if (!is.null(time.pt) & slope) {
fit <- lmer(y ~ (time.pt | id) + X)
} else {
fit <- lmer(y ~ (1 | id) + X)
}
}
} else {
if (is.null(X)) {
if (!is.null(time.pt) & slope) {
fit <- glmer(y ~ (time.pt | id), family = model)
} else {
fit <- glmer(y ~ (1 | id), family = model)
}
} else {
if (!is.null(time.pt) & slope) {
fit <- glmer(y ~ (time.pt | id) + X, family = model)
} else {
fit <- glmer(y ~ (1 | id) + X, family = model)
}
}
}
fe <- as.numeric(getME(fit, "X") %*% getME(fit, "fixef"))
re <- as.numeric(getME(fit, "Z") %*% getME(fit, "b"))
if (model == "gaussian") {
mu <- fe + re
inv.de.mu <- diag(length(y))
}
if (model == "binomial") {
mu <- exp(fe + re)/(1 + exp(fe + re))
inv.de.mu <- diag(as.numeric(mu * (1 - mu)))
}
if (model == "poisson") {
mu <- exp(fe + re)
inv.de.mu <- diag(as.numeric(mu))
}
y.star <- as.numeric(fe + re + ginv(inv.de.mu) %*% (y - mu))
r <- y.star - fe
r.X <- as.matrix((getME(fit, "Z") %*% Matrix::crossprod(getME(fit, "Lambdat")) %*% getME(fit, "Zt")))
if (model == "gaussian") {
e.var <- diag(rep(var(mu), length(y)))
}
if (model == "binomial") {
e.var <- diag(rep(1, length(y)))
}
if (model == "poisson") {
e.var <- diag(rep(1, length(y)))
}
v.X <- r.X + e.var
inv.vX <- ginv(v.X)
r.s <- list()
if (!slope) {
id.time.pt <- id
p.ind <- as.matrix(getPermuteMatrix(nperm, length(r),
strata = id.time.pt))
clust.sizes <- as.numeric(names(table(table(id.time.pt))))
block.r.ids <- list()
for (l in 1:nperm) {
block.r.id <- list()
for (j in 1:length(clust.sizes)) {
block.r.id.clust <- list()
u.id.clust <- names(which(table(id.time.pt) == clust.sizes[j]))
r.u.id.clust <- u.id.clust[shuffle(length(u.id.clust))]
for (k in 1:length(u.id.clust)) {
block.r.id.clust[[k]] <- which(id.time.pt == r.u.id.clust[k])
}
block.r.id[[j]] <- unlist(block.r.id.clust)
}
unlist.block.r.id <- rep(NA, length(id.time.pt))
for (j in 1:length(clust.sizes)) {
unlist.block.r.id[id.time.pt %in% names(which(table(id.time.pt) ==
clust.sizes[j]))] <- block.r.id[[j]]
}
block.r.ids[[l]] <- unlist.block.r.id
}
for (l in 1:nperm) {
p.ind[l, ] <- p.ind[l, block.r.ids[[l]]]
}
for (j in 1:nperm) {
r.s[[j]] <- r[p.ind[j, ]]
}
}
if (!is.null(time.pt) & slope) {
id.names <- names(table(id))
id.time.pt <- rep(NA, length(id))
for (j in 1:length(id.names)) {
ind <- which(id == id.names[j])
id.time.pt[ind] <- paste(c(id.names[j], as.character(time.pt[ind])),
collapse = ".")
}
noid.time.pt <- rep(NA, length(id))
for (j in 1:length(id.names)) {
ind <- which(id == id.names[j])
noid.time.pt[ind] <- paste(as.character(time.pt[ind]),
collapse = ".")
}
ex.clust <- names(table(noid.time.pt))
ids <- rep(NA, length(id))
for (j in 1:length(id.names)) {
ind <- which(id == id.names[j])
ids[ind] <- id.names[j]
}
if (length(names(which(table(noid.time.pt)==1))) != 0) {
warn.ids <- unique(ids[noid.time.pt %in% names(which(table(noid.time.pt)==1))])
}
if (length(warn.ids) == 1) warning("The cluster id (", warn.ids, ") is a silent block which is not exchangeable with any other blocks. It did not contribute to the analysis.")
if (length(warn.ids) > 1) warning("The cluster ids (", paste(warn.ids, collapse=", "), ") are silent blocks which are not exchangeable with any other blocks. They did not contribute to the analysis.")
block.r.ids <- list()
for (l in 1:nperm) {
block.r.id <- list()
for (j in 1:length(ex.clust)) {
block.r.id.clust <- list()
u.id.clust <- unique(id.time.pt[which(noid.time.pt == ex.clust[j])])
r.u.id.clust <- u.id.clust[shuffle(length(u.id.clust))]
for (k in 1:length(u.id.clust)) {
block.r.id.clust[[k]] <- which(id.time.pt == r.u.id.clust[k])
}
block.r.id[[j]] <- unlist(block.r.id.clust)
}
unlist.block.r.id <- rep(NA, length(id.time.pt))
for (j in 1:length(ex.clust)) {
unlist.block.r.id[id.time.pt %in% unique(id.time.pt[which(noid.time.pt == ex.clust[j])])] <- block.r.id[[j]]
}
block.r.ids[[l]] <- unlist.block.r.id
}
for (j in 1:nperm) {
r.s[[j]] <- r[block.r.ids[[j]]]
}
}
Qs <- rep(NA, length(Ks))
for (j in 1:length(Ks)) {
Qs[j] <- (t(r) %*% inv.vX %*% Ks[[j]] %*% inv.vX %*%
r)/(t(r) %*% inv.vX %*% r)
}
Q0s <- list()
for (j in 1:length(Ks)) {
Q0s.inv <- rep(NA, nperm)
for (k in 1:nperm) {
Q0s.inv[k] <- (t(r.s[[k]]) %*% inv.vX %*% Ks[[j]] %*%
inv.vX %*% r.s[[k]])/(t(r.s[[k]]) %*% inv.vX %*%
r.s[[k]])
}
Q0s[[j]] <- Q0s.inv
}
pvs <- rep(NA, length(Ks))
for (j in 1:length(Ks)) {
pvs[j] <- (length(which(Q0s[[j]] > Qs[[j]])) + 1)/(nperm + 1)
}
if (!no.omnibus) {
if (om == "p") {
T <- min(pvs)
T0 <- rep(NA, nperm)
for (l in 1:nperm) {
T0.s.n <- list()
for (m in 1:length(Ks)) {
T0.s.n[[m]] <- Q0s[[m]][-l]
}
a.Ts <- unlist(lapply(Ks, function(x) return((t(r.s[[l]]) %*%
inv.vX %*% x %*% inv.vX %*% r.s[[l]])/(t(r.s[[l]]) %*%
inv.vX %*% r.s[[l]]))))
a.pvs <- unlist(mapply(function(x, y) (length(which(x >
y)) + 1)/nperm, T0.s.n, a.Ts))
T0[l] <- min(a.pvs)
}
pv.opt <- (length(which(T0 < T)) + 1)/(nperm + 1)
} else if (om == "c") {
cauchy.t <- sum(tan((0.5 - pvs)*pi))/length(pvs)
pv.opt <- 1 - pcauchy(cauchy.t)
} else {
stop("I don't know that omnibus option. Please choose 'permutation' or 'Cauchy'.")
}
}
names(pvs) <- names(Ks)
if (no.omnibus) {
return(list(p_values = pvs))
}
return(list(p_values = pvs, omnibus_p = pv.opt))
} |
Iteration_GMR <- function(num, full_id, G_all, M_all, R_all, evectors1, evectors2, evectors3, evals1, evals2, evals3, pskat1, pskat2, pskat3, acc, method) {
p1<-p2<-p3<-vector()
for (k in 1:num) {
r_star = rnorm(dim(full_id)[1], 0, 1)
r_star = cbind(full_id, r_star)
G_all_star = merge(r_star, G_all)
G_all_star = G_all_star[order(G_all_star$order),]
M_all_star = merge(r_star, M_all)
M_all_star = M_all_star[order(M_all_star$order),]
R_all_star = merge(r_star, R_all)
R_all_star = R_all_star[order(R_all_star$order),]
r_star1 = t(evectors1) %*% G_all_star$r_star
r_star2 = t(evectors2) %*% M_all_star$r_star
r_star3 = t(evectors3) %*% R_all_star$r_star
if (length(evals1)==1) { Q1_star = r_star1 * evals1 * r_star1
} else { Q1_star = t(r_star1) %*% diag(evals1) %*% r_star1 }
if (length(evals2)==1) { Q2_star = r_star2 * evals2 * r_star2
} else { Q2_star = t(r_star2) %*% diag(evals2) %*% r_star2 }
if (length(evals3)==1) { Q3_star = r_star3 * evals3 * r_star3
} else { Q3_star = t(r_star3) %*% diag(evals3) %*% r_star3 }
if (method=="davies"){
tmpout1_star<-davies(Q1_star, evals1, acc=acc)
tmpout2_star<-davies(Q2_star, evals2, acc=acc)
tmpout3_star<-davies(Q3_star, evals3, acc=acc)
p1[k]<-tmpout1_star$Qq
p2[k]<-tmpout2_star$Qq
p3[k]<-tmpout3_star$Qq
}
else if (method=="kuonen"){
p1[k]<-pchisqsum(Q1_star,rep(1,length(evals1)),evals1,lower.tail=F,method="sad")
p2[k]<-pchisqsum(Q2_star,rep(1,length(evals2)),evals2,lower.tail=F,method="sad")
p3[k]<-pchisqsum(Q3_star,rep(1,length(evals3)),evals3,lower.tail=F,method="sad")
}
}
p1[p1==0|p1<0] = 1e-4
p1[p1>1] = 1
p2[p2==0|p2<0] = 1e-4
p2[p2>1] = 1
p3[p3==0|p3<0] = 1e-4
p3[p3>1] = 1
p01_single = pskat1
p02_single = pskat2
p03_single = pskat3
T01 = -2*(log(pskat1) + log(pskat2))
T02 = -2*(log(pskat1) + log(pskat3))
T03 = -2*(log(pskat2) + log(pskat3))
T0tri = -2*(log(pskat1) + log(pskat2) + log(pskat3))
E_T01 = E_T02 = E_T03 = 2*2
E_T0tri = 2*3
V_T01 = 2*2*2 + 2*cov(-2*log(p1),-2*log(p2))
V_T02 = 2*2*2 + 2*cov(-2*log(p1),-2*log(p3))
V_T03 = 2*2*2 + 2*cov(-2*log(p2),-2*log(p3))
V_T0tri = 2*2*3 + 2*cov(-2*log(p1),-2*log(p2)) + 2*cov(-2*log(p1),-2*log(p3)) + 2*cov(-2*log(p2),-2*log(p3))
v01 = 2*E_T01**2/V_T01
v02 = 2*E_T02**2/V_T02
v03 = 2*E_T03**2/V_T03
v0tri = 2*E_T0tri**2/V_T0tri
c01 = v01/E_T01
c02 = v03/E_T02
c03 = v02/E_T03
c0tri = v0tri/E_T0tri
p01_dual = pchisq( c01*T01, df=v01, lower.tail=FALSE)
p02_dual = pchisq( c02*T02, df=v02, lower.tail=FALSE)
p03_dual = pchisq( c03*T03, df=v03, lower.tail=FALSE)
p0_tri = pchisq( c0tri*T0tri, df=v0tri, lower.tail=FALSE)
min0 = min(c(p01_single,p02_single,p03_single,p01_dual,p02_dual,p03_dual,p0_tri))
p1_single = p1
p2_single = p2
p3_single = p3
T1 = -2*(log(p1) + log(p2))
T2 = -2*(log(p1) + log(p3))
T3 = -2*(log(p2) + log(p3))
Ttri = -2*(log(p1) + log(p2) + log(p3))
E_T1 = E_T2 = E_T3 = 2*2
E_Ttri = 2*3
V_T1 = 2*2*2 + 2*cov(-2*log(p1),-2*log(p2))
V_T2 = 2*2*2 + 2*cov(-2*log(p1),-2*log(p3))
V_T3 = 2*2*2 + 2*cov(-2*log(p2),-2*log(p3))
V_Ttri = 2*2*3 + 2*cov(-2*log(p1),-2*log(p2)) + 2*cov(-2*log(p1),-2*log(p3)) + 2*cov(-2*log(p2),-2*log(p3))
v1 = 2*E_T1**2/V_T1
v2 = 2*E_T2**2/V_T2
v3 = 2*E_T3**2/V_T3
vtri = 2*E_Ttri**2/V_Ttri
c1 = v1/E_T1
c2 = v3/E_T2
c3 = v2/E_T3
ctri = vtri/E_Ttri
p1_dual = pchisq( c1*T1, df=v1, lower.tail=FALSE)
p2_dual = pchisq( c2*T2, df=v2, lower.tail=FALSE)
p3_dual = pchisq( c3*T3, df=v3, lower.tail=FALSE)
p_tri = pchisq( ctri*Ttri, df=vtri, lower.tail=FALSE)
min_pert = apply(cbind(p1_single,p2_single,p3_single,p1_dual,p2_dual,p3_dual,p_tri),1,min)
pval_pert = sum(min_pert<min0)/(length(min_pert)+1)
if (is.na(pval_pert)) pval_pert=1
if (is.na(p0_tri)) p0_tri=1
c(pval_pert, p0_tri, p01_single,p02_single,p03_single)
} |
GREEK <- intToUtf8(c(913:929, 931:937), multiple = TRUE)
greek <- intToUtf8(c(945:961, 963:969), multiple = TRUE)
next_label <- function(figure)
{
n <- length(figure$grobs) / 2 + 1L
panelLabelType <- attr(figure, "multipanelfigure.panelLabelType")
switch(
panelLabelType,
"upper-alpha" = LETTERS[n],
"lower-alpha" = letters[n],
"decimal" = as.character(n),
"upper-roman" = as.roman(n),
"lower-roman" = tolower(as.roman(n)),
"upper-greek" = GREEK[n],
"lower-greek" = greek[n],
"none" = "",
stop("The label type ", panelLabelType, " is not supported.")
)
} |
generate_feature_network <- function(
model
) {
model <- .add_timing(model, "3_feature_network", "checks")
if (model$verbose) cat("Sampling feature network from real network\n")
assert_that(
model %has_names% c("feature_info", "feature_network"),
msg = "Execute generate_tf_network() before executing generate_feature_network()"
)
model <- .add_timing(model, "3_feature_network", "process realnet")
realnet <- model$feature_network_params$realnet
if (is.character(realnet)) {
realnet <- .feature_network_fetch_realnet(model)
}
assert_that(
dynutils::is_sparse(realnet),
!is.null(rownames(realnet)),
!is.null(colnames(realnet))
)
assert_that(
nrow(model$feature_info) <= nrow(realnet),
msg = paste0("Number of regulators in realnet (", nrow(realnet), ") is not large enough (>= ", nrow(model$feature_info), ")")
)
sample_tfs_per <- min(model$feature_network_params$target_resampling, model$numbers$num_targets)
sample_hks_per <- min(model$feature_network_params$target_resampling, model$numbers$num_hks)
ncol_at_least <- model$numbers$num_tfs + max(sample_tfs_per, sample_hks_per)
assert_that(
ncol(realnet) >= ncol_at_least,
msg = paste0(
"Number of genes in realnet (", ncol(realnet), ") is not large enough (>= ", ncol_at_least, "). ",
"Choose a larger realnet or make use of the `feature_network_params$target_resampling` parameter."
)
)
model <- .add_timing(model, "3_feature_network", "sample target network")
if (sample_tfs_per > 0) {
num_target_start <- seq(1, model$numbers$num_targets, by = sample_tfs_per)
num_target_stop <- c((num_target_start - 1) %>% tail(-1), model$numbers$num_targets)
downstreams <-
pmap(lst(start = num_target_start, stop = num_target_stop), function(start, stop) {
.feature_network_sample_downstream(model, realnet, num_targets = stop - start + 1, target_index_offset = start - 1)
})
target_info <- map_df(downstreams, "target_info")
target_network <- map_df(downstreams, "target_network")
} else {
target_info <- NULL
target_network <- NULL
}
model <- .add_timing(model, "3_feature_network", "sample housekeeping network")
if (sample_hks_per > 0) {
num_hk_start <- seq(1, model$numbers$num_hks, by = sample_hks_per)
num_hk_stop <- c((num_hk_start - 1) %>% tail(-1), model$numbers$num_hks)
housekeepings <-
pmap(lst(start = num_hk_start, stop = num_hk_stop), function(start, stop) {
.feature_network_sample_housekeeping(model, realnet, num_hks = stop - start + 1, hk_index_offset = start - 1)
})
hk_info <- map_df(housekeepings, "hk_info")
hk_network <- map_df(housekeepings, "hk_network")
} else {
hk_info <- NULL
hk_network <- NULL
}
model <- .add_timing(model, "3_feature_network", "return output")
model$feature_info <-
bind_rows(
model$feature_info,
target_info,
hk_info
)
model$feature_network <-
bind_rows(
model$feature_network,
target_network,
hk_network
)
model %>% .add_timing("3_feature_network", "end")
}
feature_network_default <- function(
realnet = NULL,
damping = 0.01,
target_resampling = Inf,
max_in_degree = 5
) {
realnets <- NULL
if (is.null(realnet)) {
data(realnets, package = "dyngen", envir = environment())
realnet <- sample(realnets$name, 1)
}
lst(
realnet,
damping,
target_resampling,
max_in_degree
)
}
.feature_network_fetch_realnet <- function(model) {
realnets <- NULL
realnet <- model$feature_network_params$realnet
data(realnets, package = "dyngen", envir = environment())
assert_that(realnet %all_in% realnets$name)
realnet_url <- realnets$url[[match(realnet, realnets$name)]]
.download_cacheable_file(
url = realnet_url,
cache_dir = model$download_cache_dir,
verbose = model$verbose
)
}
.feature_network_sample_downstream <- function(
model,
realnet,
num_targets = model$numbers$num_targets,
target_index_offset = 0
) {
requireNamespace("igraph")
tf_info <-
model$feature_info %>%
mutate(
num_targets = .generate_partitions(
num_elements = num_targets,
num_groups = n(),
min_elements_per_group = 0
)
)
tf_names <- tf_info$feature_id
tf_mapper <- set_names(tf_names, sample(rownames(realnet), length(tf_names)))
rownames(realnet) <- ifelse(rownames(realnet) %in% names(tf_mapper), tf_mapper[rownames(realnet)], rownames(realnet))
colnames(realnet) <- ifelse(colnames(realnet) %in% names(tf_mapper), tf_mapper[colnames(realnet)], colnames(realnet))
gr <-
realnet %>%
Matrix::summary() %>%
as.data.frame() %>%
group_by(.data$j) %>%
sample_n(min(n(), sample(seq_len(model$feature_network_params$max_in_degree), 1)), weight = .data$x) %>%
ungroup() %>%
transmute(
i = rownames(realnet)[.data$i],
j = colnames(realnet)[.data$j],
weight = .data$x
) %>%
igraph::graph_from_data_frame(vertices = colnames(realnet))
personalized <- rep(0, ncol(realnet)) %>% set_names(colnames(realnet))
personalized[tf_info$feature_id] <- tf_info$num_targets
page_rank <- igraph::page_rank(
gr,
personalized = personalized,
directed = TRUE,
weights = igraph::E(gr)$weight,
damping = model$feature_network_params$damping
)
features_sel <-
enframe(page_rank$vector, "feature_id", "score") %>%
mutate(score = .data$score + runif(n(), 0, 1e-15)) %>%
filter(!.data$feature_id %in% tf_names) %>%
sample_n(num_targets, weight = .data$score) %>%
pull(.data$feature_id) %>%
unique()
subgr <-
gr %>%
igraph::induced_subgraph(c(features_sel, tf_names))
target_regnet <-
subgr %>%
igraph::as_data_frame() %>%
as_tibble() %>%
select(.data$from, .data$to) %>%
filter(!.data$to %in% tf_names)
missing_targets <- setdiff(features_sel, target_regnet$to)
if (length(missing_targets) > 0) {
deg <- igraph::degree(subgr)
new_regs <- sample(names(deg), length(missing_targets), prob = deg, replace = TRUE)
target_regnet <-
bind_rows(
target_regnet,
tibble(from = new_regs, to = missing_targets)
)
}
target_names <- unique(c(target_regnet$from, target_regnet$to)) %>% setdiff(tf_names)
target_mapper <-
set_names(
paste0("Target", seq_along(target_names) + target_index_offset),
target_names
)
target_regnet <-
target_regnet %>%
mutate_all(~ ifelse(. %in% names(target_mapper), target_mapper[.], .))
target_info <-
tibble(
feature_id = unname(target_mapper),
is_tf = FALSE,
is_hk = FALSE,
burn = TRUE
)
lst(
target_network = target_regnet,
target_info = target_info
)
}
.feature_network_sample_housekeeping <- function(
model,
realnet,
num_hks = model$numbers$num_hks,
hk_index_offset = 0
) {
requireNamespace("igraph")
gr <-
realnet %>%
Matrix::summary() %>%
as.data.frame() %>%
group_by(.data$j) %>%
sample_n(min(n(), sample(seq_len(model$feature_network_params$max_in_degree), 1)), weight = .data$x) %>%
ungroup() %>%
transmute(
i = rownames(realnet)[.data$i],
j = colnames(realnet)[.data$j],
weight = .data$x
) %>%
igraph::graph_from_data_frame(vertices = colnames(realnet))
hk_names <- gr %>%
igraph::bfs(sample.int(ncol(realnet), 1), neimode = "all") %>%
`[[`("order") %>%
`[`(seq_len(num_hks)) %>%
names()
hk_regnet <-
gr %>%
igraph::induced_subgraph(hk_names) %>%
igraph::as_data_frame() %>%
as_tibble() %>%
select(.data$from, .data$to) %>%
filter(.data$from != .data$to)
hk_mapper <-
set_names(
paste0("HK", seq_along(hk_names) + hk_index_offset),
hk_names
)
hk_regnet <-
hk_regnet %>%
mutate(from = hk_mapper[.data$from], to = hk_mapper[.data$to])
hk_info <-
tibble(
feature_id = unname(hk_mapper),
is_tf = FALSE,
is_hk = TRUE,
burn = TRUE
)
lst(
hk_network = hk_regnet,
hk_info = hk_info
)
} |
library(testthat)
library(logging)
context("Testing data interactions [test.data.interaction]")
test_that("000/getLoggerWithoutInitializingDoesNotCrash", {
root_logger <- getLogger("")
succeed()
})
test_that("001/defaultLoggingLevelIsINFO", {
basicConfig()
root_logger <- getLogger("")
expect <- logging:::loglevels["INFO"]
expect_equal(root_logger[["level"]], expect)
})
test_that("002/canInitializeTwice", {
basicConfig()
basicConfig()
root_logger <- getLogger("")
expect <- logging:::loglevels["INFO"]
expect_equal(root_logger[["level"]], expect)
})
test_that("003/sameNameMeansSameObject", {
basicConfig()
root1 <- getLogger("abc")
root2 <- getLogger("abc")
expect_identical(root1, root2)
})
test_that("004/noNameMeansRoot", {
root_logger1 <- getLogger("")
root_logger2 <- getLogger()
expect_identical(root_logger1, root_logger2)
})
test_that("500.basicConfigSetsLevelOfHandler", {
logReset()
basicConfig("DEBUG")
root_logger <- getLogger("")
expect <- logging:::loglevels["NOTSET"]
current <- root_logger$getHandler("basic.stdout")[["level"]]
expect_equal(current, expect)
logReset()
basicConfig("ERROR")
root_logger <- getLogger("")
expect <- logging:::loglevels["NOTSET"]
current <- root_logger$getHandler("basic.stdout")[["level"]]
expect_equal(current, expect)
})
test_that("canFindLoggingLevels", {
expect_equal(logging:::loglevels[["NOTSET"]], 0)
expect_equal(logging:::loglevels[["DEBUG"]], 10)
expect_equal(logging:::loglevels[["INFO"]], 20)
expect_equal(logging:::loglevels[["WARN"]], 30)
expect_equal(logging:::loglevels[["ERROR"]], 40)
expect_equal(logging:::loglevels[["FATAL"]], 50)
})
test_that("fineLevelsAreOrdered", {
expect_true(logging:::loglevels[["FINEST"]] < logging:::loglevels[["FINER"]])
expect_true(logging:::loglevels[["FINER"]] < logging:::loglevels[["FINE"]])
expect_true(logging:::loglevels[["FINE"]] < logging:::loglevels[["DEBUG"]])
})
test_that("canSetLoggerLevelByNamedValue", {
logReset()
basicConfig()
setLevel(logging:::loglevels["DEBUG"], "")
root_logger <- getLogger("")
expect <- logging:::loglevels["DEBUG"]
expect_equal(root_logger[["level"]], expect)
})
test_that("canSetLoggerLevelByName", {
logReset()
basicConfig()
setLevel("DEBUG", "")
root_logger <- getLogger("")
expect <- logging:::loglevels["DEBUG"]
expect_equal(root_logger[["level"]], expect)
})
test_setup <- function(...) {
test_env <- new.env(parent = emptyenv())
test_env$logged <- NULL
mock_action <- function(msg, handler, ...) {
if (length(list(...)) && "dry" %in% names(list(...)))
return(TRUE)
test_env$logged <- c(test_env$logged, msg)
}
mock_formatter <- function(record) {
msg <- trimws(record$msg)
paste(record$levelname, record$logger, msg, sep = ":")
}
logReset()
addHandler(mock_action, formatter = mock_formatter, ...)
return(test_env)
}
test_that("recordIsEmitted/rootToRoot", {
env <- test_setup()
logfinest("test")
logfiner("test")
logfine("test")
logdebug("test")
loginfo("test")
logerror("test")
expect_equal(length(env$logged), 2)
})
test_that("recordIsEmitted/tooDeep", {
env <- test_setup(logger = "too.deep")
logfinest("test")
logfiner("test")
logfine("test")
logdebug("test")
loginfo("test")
logerror("test")
expect_equal(length(env$logged), 0)
})
test_that("recordIsEmitted/unrelated", {
env <- test_setup(logger = "too.deep")
logdebug("test", logger = "other.branch")
loginfo("test", logger = "other.branch")
logerror("test", logger = "other.branch")
expect_equal(length(env$logged), 0)
})
test_that("recordIsEmitted/deepToRoot", {
env <- test_setup(logger = "")
logdebug("test", logger = "other.branch")
loginfo("test", logger = "other.branch")
logerror("test", logger = "other.branch")
expect_equal(length(env$logged), 2)
})
test_that("recordIsEmitted/deepToRoot.DI.dropped", {
env <- test_setup(level = "DEBUG", logger = "")
setLevel("INFO", "other.branch")
logdebug("test", logger = "other.branch")
loginfo("test", logger = "other.branch")
logerror("test", logger = "other.branch")
expect_equal(length(env$logged), 2)
})
test_that("recordIsEmitted/deepToRoot.DD.passed", {
env <- test_setup(level = "DEBUG", logger = "")
setLevel("DEBUG", "other.branch")
setLevel("DEBUG", "")
logdebug("test", logger = "other.branch")
loginfo("test", logger = "other.branch")
logerror("test", logger = "other.branch")
expect_equal(length(env$logged), 3)
})
test_that("formattingRecord/lengthZero", {
env <- test_setup(level = "DEBUG", logger = "")
loginfo("test '%s'", numeric(0))
expect_equal(env$logged, "INFO::test ''")
})
test_that("formattingRecord/lengthOne", {
env <- test_setup(level = "DEBUG", logger = "")
loginfo("test '%s'", 12)
expect_equal(env$logged, "INFO::test '12'")
})
test_that("formattingRecord/lengthMore", {
env <- test_setup(level = "DEBUG", logger = "")
loginfo("test '%s'", c(0, 1, 2))
expect_equal(env$logged, "INFO::test '0,1,2'")
})
test_that("formattingRecord/moreArguments", {
env <- test_setup(level = "DEBUG", logger = "")
loginfo("%s: %d", "name", 123)
expect_equal(env$logged, "INFO::name: 123")
env$logged <- NULL
loginfo("%s: %0.2f", "name", 123.0)
expect_equal(env$logged, "INFO::name: 123.00")
})
test_that("formattingRecord/moreArguments.lengthMore", {
env <- test_setup(level = "DEBUG", logger = "")
loginfo("%s '%s'", "name", c(0, 1, 2))
expect_equal(env$logged, "INFO::name '0,1,2'")
})
test_that("formattingRecord/strips.whitespace", {
env <- test_setup(level = "DEBUG", logger = "")
loginfo("a string with trailing whitespace \n")
expect_equal(env$logged, "INFO::a string with trailing whitespace")
env$logged <- NULL
loginfo(" this string has also leading whitespace ")
expect_equal(env$logged, "INFO::this string has also leading whitespace")
}) |
bcdc_options <- function() {
null_to_na <- function(x) {
ifelse(is.null(x), NA, as.numeric(x))
}
dplyr::tribble(
~ option, ~ value, ~default,
"bcdata.max_geom_pred_size", null_to_na(getOption("bcdata.max_geom_pred_size")), 5E5,
"bcdata.chunk_limit", null_to_na(getOption("bcdata.chunk_limit")), 1000,
"bcdata.single_download_limit",
null_to_na(getOption("bcdata.single_download_limit",
default = bcdc_single_download_limit())), 10000
)
}
check_chunk_limit <- function(){
chunk_value <- getOption("bcdata.chunk_limit")
chunk_limit <- getOption("bcdata.single_download_limit", default = bcdc_single_download_limit())
if (!is.null(chunk_value) && chunk_value >= chunk_limit) {
stop(glue::glue("Your chunk value of {chunk_value} exceed the BC Data Catalogue chunk limit of {chunk_limit}"), call. = FALSE)
}
}
bcdc_get_capabilities <- function() {
current_xml <- ._bcdataenv_$get_capabilities_xml
if (!is.null(current_xml) && inherits(current_xml, "xml_document")) {
return(current_xml)
}
if (has_internet()) {
url <- make_url(bcdc_web_service_host(https = FALSE), "geo/pub/ows")
cli <- bcdc_http_client(url, auth = FALSE)
cc <- try(cli$get(query = list(
SERVICE = "WFS",
VERSION = "2.0.0",
REQUEST = "Getcapabilities"
)))
if (inherits(cc, "try-error")) {
return(NULL)
}
cc$raise_for_status()
res <- cc$parse("UTF-8")
ret <- xml2::read_xml(res)
._bcdataenv_$get_capabilities_xml <- ret
return(ret)
}
invisible(NULL)
}
bcdc_get_wfs_records <- function() {
doc <- bcdc_get_capabilities()
if (is.null(doc)) stop("Unable to access wfs record listing", call. = FALSE)
features <- xml2::xml_find_all(doc, "./d1:FeatureTypeList/d1:FeatureType")
tibble::tibble(
whse_name = gsub("^pub:", "", xml2::xml_text(xml2::xml_find_first(features, "./d1:Name"))),
title = xml2::xml_text(xml2::xml_find_first(features, "./d1:Title")),
cat_url = xml2::xml_attr(xml2::xml_find_first(features, "./d1:MetadataURL"), "href")
)
}
bcdc_single_download_limit <- function() {
doc <- bcdc_get_capabilities()
if (is.null(doc)) {
message("Unable to access wfs record listing, using default download limit of 10000")
return(10000L)
}
count_default_xpath <- "./ows:OperationsMetadata/ows:Operation[@name='GetFeature']/ows:Constraint[@name='CountDefault']"
count_defaults <- xml2::xml_find_first(doc, count_default_xpath)
xml2::xml_integer(count_defaults)
} |
CPMCGLM<-function(formula,family,link,data,varcod,dicho,nb.dicho,categ,nb.categ,boxcox,nboxcox,FP,N=1000,cutpoint)
{
if(missing(dicho) & missing(nb.dicho) & missing(categ) & missing(nb.categ) & missing(boxcox) & missing(nboxcox) & missing(cutpoint) & missing(FP) ){stop("You need to enter at least one transformation in the function")}
if(!missing(dicho) & !missing(nb.dicho))stop("Specify only one argument for the dichotomous transformation ('dicho' or 'nb.dicho')")
if(!missing(categ) & !missing(nb.categ))stop("Specify only one argument for the categorical transformation ('categ' or 'nb.categ')")
if(!missing(boxcox) & !missing(nboxcox))stop("Specify only one argument for the boxcox transformation ('boxcox' or 'nboxcox')")
continuous<-"FALSE"
if (missing(boxcox))
{
if(!missing(nboxcox)){
if((nboxcox > 5)){stop("The nboxcox argument must not be upper than 5")}
if(nboxcox<6){
if (nboxcox==0) {boxcox<-NULL}
if (nboxcox==1) {boxcox<-1}
if (nboxcox==2) {boxcox<-c(1,0)}
if (nboxcox==3) {boxcox<-c(1,0,2)}
if (nboxcox==4) {boxcox<-c(1,0,2,0.5)}
if (nboxcox==5) {boxcox<-c(1,0,2,0.5,1.5)}
}
}
}
if(missing(dicho) & (!missing(nb.dicho))){
dicho<-c((1:nb.dicho)/(nb.dicho+1))
}
if(missing(categ) & (!missing(nb.categ))){
categ<-matrix(NA,ncol=nb.categ+1,nrow=nb.categ)
for(i in 1:nb.categ)
{
categ[i,1:(i+1)]<-c(1:(1+i))/(i+2)
}
}
if(missing(categ) & (!missing(dicho))){
quantile<-matrix(NA,ncol=1,nrow=length(dicho))
for( i in 1:length(dicho))
{
quantile[i,1]<-dicho[i]
}
}
if(missing(categ) & (missing(dicho))){quantile<-NULL}
if(!missing(categ) & (missing(dicho))){quantile<-categ}
if(!missing(categ) & (!missing(dicho))){
binc<-matrix(NA,ncol=ncol(categ),nrow=length(dicho))
for( i in 1:length(dicho))
{
binc[i,1]<-dicho[i]
}
quantile<-rbind(binc,categ)
}
call <- match.call()
if(!(family %in% c("binomial","gaussian","poisson"))) stop("This family of distribution is not taken into account in this function")
family1<- switch(family,
"binomial"=binomial,
"gaussian"=gaussian ,
"poisson"=poisson
)
if(missing(data)) stop("Missing data argument.")
if(missing(family)) stop("Missing family argument.")
if(missing(link)) stop("Missing link argument.")
if(missing(varcod)) stop("Missing varcod argument.")
if(missing(dicho) & missing(boxcox) & missing(categ) & missing(nb.dicho) & missing(nboxcox) & missing(nb.categ) & missing(cutpoint) & missing(FP)){
stop("No transformation is available")
}
if(class(formula)!="formula") stop("The argument formula must be a formula.")
if(class(data)!="data.frame") stop("The argument must be a data frame.")
if(class(varcod)!="character") stop("The argument varcod must be a character.")
if(!missing(boxcox)){
if(is.vector(boxcox)=="FALSE") stop("The argument boxcox must be a vector.")
}
m <- match.call(expand.dots=FALSE)
m$family <- m$link <- m$varcod <- m$quantile <- m$FP <- m$dicho <- m$nb.dicho<- m$nb.categ<- m$categ<- m$continuous <- m$boxcox<- m$nboxcox <-m$cutpoint <- m$N <- NULL
m[[1]] <- as.name("model.frame")
m <- eval(m)
NamesY <- all.names(update(formula,"~1"))[2]
Y <- as.vector(model.response(model.frame(formula=update(formula,"~1"),data=data)))
mat.exp <- if (!is.empty.model(attr(m,"terms")))model.matrix(attr(m,"terms"),m, contrasts)
mtt <- model.matrix(attr(m,"terms"),m, contrasts)
Nom1 <- attributes(mtt)$dimnames[[2]]
type <- paste("factor\\(",varcod,"\\)",sep="")
if(length(grep(type,Nom1))!= 0){
stop("The coding variable needs to be continuous")
}
if(ncol(mat.exp)==1)stop("the dataset must be contain the varcod variable.")
mat.exp <- mat.exp[,-1]
factor.names <- function(x){
x <- matrix(x,nrow=1)
Names <- apply(x,MARGIN=2,FUN=function(x){
if(length(grep("factor",x))!= 0){
pos1 <- grep("\\(",unlist(strsplit(x,split="")))+1
pos2 <- grep("\\)",unlist(strsplit(x,split="")))-1
compris.factor <- substr(x,start=pos1,stop=pos2)
after.factor <- substr(x,start=(pos2+2),stop=length(unlist(strsplit(x,split=""))))
paste(compris.factor,after.factor,sep=".")
}else{
x
}
}
)
return(Names)
}
if(is.matrix(mat.exp)){
colnames(mat.exp) <-factor.names(colnames(mat.exp))
}
if(is.vector(mat.exp)){
Z <- NULL
nb <- 0
namesZ <- NULL
var.cod <- as.vector(mat.exp)
ind.ajust <- 0
}
if(!is.vector(mat.exp)){
if(!(varcod %in% colnames(mat.exp)))stop("varcod argument it is not present in the dataset.")
ind.ajust <- 1
if(ncol(mat.exp)!=2){
Z <- mat.exp[,-grep(varcod,colnames(mat.exp))]
nb <- ncol(Z)
namesZ <- NULL
names1 <- unlist(colnames(Z))
for(i in 1:nb){
if(i < nb) namesZ <- paste(namesZ,names1[i],"+")
else namesZ <- paste(namesZ,colnames(Z)[i])
}
}else{
Z <- as.matrix(mat.exp[,-grep(varcod,colnames(mat.exp))])
nb <- 1
namesZ <- NULL
names1 <- as.matrix(colnames(mat.exp))
posi<-grep(varcod,names1)
namesZ <-names1[-posi,]
colnames(Z)<-namesZ
}
var.cod <- as.vector(mat.exp[,varcod])
}
n<-nrow(data)
coup<-NULL
a <- Codage(data,quantile,var.cod)
X3 <- a[[1]]
coup2<- a[[2]]
b <- Boxcox(boxcox,var.cod)
X2<- b[[1]]
coup1<- b[[2]]
d <- codcut(data,cutpoint,var.cod)
X4<- d [[1]]
coup4<-d [[2]]
e <- PF(FP,var.cod)
X5 <- e[[1]]
coup5 <- e[[2]]
if(continuous=="TRUE"){
X1<-cbind(X3,X4,var.cod,X2)
coup3<-1
}else{
X1<-cbind(X3,X4,X2)
coup3<-NULL
}
if( missing(dicho) & missing(nb.dicho) & missing(categ) & missing(nb.categ) & missing(boxcox) & missing(nboxcox) & missing(cutpoint)){
X1ter <- X5
}else{
if(missing(FP)){X1ter <- X1}else{
X1bis <- array(data=NA,c(length(var.cod),ncol(FP),ncol(X1)))
for(i in 1:ncol(X1)){X1bis[,1,i] <- X1[,i]}
X1ter <- abind(X1bis,X5)
}
}
coup<-c(coup2,coup4,coup3,coup1,coup5)
if(ind.ajust==1){
formula1 <-update(formula,paste("~",namesZ))
}else{
formula1 <-update(formula,paste("~",1))
}
data <- as.data.frame(cbind(Y,mat.exp))
colnames(data)[1] <- NamesY
t.obs<-test.score(formula=formula1,data=data,codage=X1ter,Z=Z,Y=Y,family1=family1,family=family,link1=link,ind.ajust=ind.ajust)
pval<-p.val<-NULL
if(missing(FP)){nbtransf1 <- ncol(X1ter) }else{ nbtransf1 <- dim(X1ter)[3] }
for (i in 1:nbtransf1){
pval[i]<-(1-pchisq(t.obs[i],coup[i]))
p.val[i]<- min(p.val[i-1],pval[i])
}
if(sum(is.na(p.val))!=0){stop("At least one of the coding, it isn't adapt for the model specification")}
pval.exact1<-pval.bonf1<-pval.naive1<-NULL
control<-rep(1,nbtransf1)
if(all.equal(coup,control)==TRUE){
pval.exact1<-test.liquet(formula=formula1,data=data,codage=X1ter,Z=Z,Y=Y,family=family,link1=link,family1=family1)}
else {pval.exact1<-"Correction not available for these codings"}
Y1<-matrix(ncol=N,nrow=n)
tboot1<-matrix(nrow=N,ncol=nbtransf1)
alphaboot<-NULL
alphapermut<-NULL
tpermut1<-matrix(nrow=N,ncol=nbtransf1)
link0 <- link
beta<-glm(formula1,family=family1(link0),data)$coeff
res<-glm(formula1,family=family1(link0),data)$res
design <- cbind(rep(1,n),Z)
param<- switch(link,
"logit"= exp(design%*%beta)/(1+exp(design%*%beta)),
"probit"= pnorm(design%*%beta),
"log"=exp(design%*%beta),
"identity"=(design%*%beta)
)
tboot<-matrix(ncol=nbtransf1,nrow=N)
pval.boot<-matrix(ncol=nbtransf1,nrow=N)
progress_bar_tk <- create_progress_bar (title="step 1 :Parametric Bootstrap resampling","tk")
progress_bar_tk $ init (N)
for (j in 1:N){
progress_bar_tk $ step ()
Y1[,j]<- switch(family,
"gaussian"= rnorm(n,mean=mean(param),sd=sd(res)) ,
"binomial"= rbinom(n,1,prob=param) ,
"poisson"= rpois(n,mean(param)),
)
if(ind.ajust==1){
f1<-paste("~",namesZ)
}else{
f1<-"~1"
}
tboot[j,]<-tmultboot(f1,data,Y1=Y1[,j],Z,X1ter,family1,family=family,link1=link)
for (i in 1:nbtransf1){
pval.boot[j,i]<-(1-pchisq(tboot[j,i],coup[i]))
}
}
cat("\n")
progress_bar_tk $ term ()
tpermut<-matrix(ncol=nbtransf1,nrow=N)
pval.permut<-matrix(ncol=nbtransf1,nrow=N)
progress_bar_tk <- create_progress_bar (title="step 2 : Permutation resampling","tk")
progress_bar_tk $ init (N)
for (k in 1:N){
data1<-NULL
progress_bar_tk $ step ()
ind.permut <- permut(length(Y))
if(ind.ajust==1){
if(ncol(Z)==1)
{
Z11<-as.matrix(Z[ind.permut,])
colnames(Z11)<-namesZ
formula2 <-formula(paste("Y","~",namesZ))
data.permut <- data.frame(Y=Y[ind.permut],varcod=var.cod,Z11)
tpermut[k,]<-test.score(formula=formula2,data=data.permut,codage=X1ter,Z=Z11,Y=Y[ind.permut],family1,family=family,link1=link,ind.ajust=ind.ajust)
}
else{
formula2 <-formula(paste("Y","~",namesZ))
data.permut <- data.frame(Y=Y[ind.permut],varcod=var.cod,Z[ind.permut,])
tpermut[k,]<-test.score(formula=formula2,data=data.permut,codage=X1ter,Z=Z[ind.permut,],Y=Y[ind.permut],family1,family=family,link1=link,ind.ajust=ind.ajust)
}
}else{
formula2<-formula(paste("Y","~",1))
data.permut <- data.frame(Y=Y[ind.permut],varcod=var.cod)
tpermut[k,]<-test.score(formula=formula2,data=data.permut,codage=X1ter,Z=Z,Y=Y[ind.permut],family1=family1,family=family,link1=link,ind.ajust=ind.ajust)
}
for (i in 1:nbtransf1){
pval.permut[k,i]<-(1-pchisq(tpermut[k,i],coup[i]))
}
}
cat("\n")
progress_bar_tk $ term ()
pval.boot2<-pval.permut2<-matrix(0,ncol=nbtransf1,nrow=N)
for (i in 1:nbtransf1)
{
for (j in 1:N){
pval.boot[is.na(pval.boot)] <- 9999
pval.permut[is.na(pval.permut)] <- 9999
if (i>1){
pval.boot2[j,i]<-min(pval.boot2[j,i-1],min(pval.boot[j,i]))
pval.permut2[j,i]<-min(pval.permut2[j,i-1],min(pval.permut[j,i]))
}
else{
pval.boot2[j,i]<-min(pval.boot[j,i])
pval.permut2[j,i]<-min(pval.permut[j,i])
}
}
}
cat("\n")
for (i in 1:nbtransf1){
pval.bonf<-p.val[i]*i
pval.bonf1<-c(pval.bonf1,pval.bonf)
pval.naive<-p.val[i]
pval.naive1<-c(pval.naive1,pval.naive)
for (ii in 1:N){
if(pval.boot2[ii,i]< p.val[i]){tboot1[ii,i]<-1}
}
alphaboot[i]<-(length(which(tboot1[,i]>0))/N)
for (l in 1:N){
if(pval.permut2[l,i]< p.val[i]){tpermut1[l,i]<-1}
}
alphapermut[i]<-(length(which(tpermut1[,i]>0))/N)
}
cat("\n")
trans<-transf(quantile,continuous,boxcox,cutpoint,FP)
adj<-ncol(Z)
if(continuous=="TRUE"){q<-"TRUE"}else{q<-"FALSE"}
if(class(quantile)=="NULL"){nbq=0}else{nbq=nrow(quantile)}
if(missing(cutpoint)){nbc=0}else{nbc=nrow(cutpoint)}
if(missing(boxcox)){nbb=0}else{nbb=length(boxcox)}
if(missing(FP)){nbf=0}else{nbf=nrow(FP)}
BC<-trans[which.min(pval.naive1)]
print(substr(BC,1,22))
bestcod1<-bestcod(continuous=continuous,quantile=quantile,boxcox=boxcox,cutpoint=cutpoint,PF=FP,pval.naive=pval.naive1)
print(bestcod1)
bcod<-which(is.na(bestcod1)==TRUE)
if((is.numeric(bestcod1)) & (length(bcod!=0)) ) {bestcod1<-bestcod1[-bcod]}
info<-list("link"=link,"nbt"=nbtransf1,"nbb"=nbb,"nbq"=nbq,"nbf"=nbf,"nbcont"=q,"adj"=adj,"trans"=trans,"BC"=BC,"bestcod"=bestcod1,"nbc"=nbc)
if(substr(BC,1,8)=="Quantile"){
vq<-quantile(var.cod,bestcod1)
}else{vq<-NULL}
out <- NULL
out$call <- call
out$n <- n
out$N <- N
out$family <- family
out$link <- link
out$nbt <- nbtransf1
out$nbb <- nbb
out$nbq <- nbq
out$nbf <- nbf
out$nbcont <- q
out$nbc <- nbc
out$adj <- adj
out$vq<-vq
out$trans <- trans
out$BC <- BC
out$bestcod <-bestcod1
out$naive.pvalue <- pval.naive1[nbtransf1]
if(is.numeric(pval.exact1)==TRUE)
{out$exact.pvalue <- pval.exact1[nbtransf1]}
else{out$exact.pvalue<-pval.exact1}
out$bonferroni.adjusted.pvalue <- pval.bonf1[nbtransf1]
out$parametric.bootstrap.adjusted.pvalue <- alphaboot[nbtransf1]
out$permutation.adjusted.pvalue <- alphapermut[nbtransf1]
class(out) <- c("CPMCGLM")
out
} |
individuals_defensive_actual_floor_stats <- function(df1,df2,df3){
stats <- cbind(df1[1],df1[2])
poss <- df2[1,4] - df2[1,15] / (df2[1,15] + df3[1,16]) * (df2[1,4] - df2[1,3]) * 1.07 + df2[1,21] + 0.4 * df2[1,13]
ope_poss <- df3[1,4] - df3[1,15] / (df3[1,15] + df2[1,16]) * (df3[1,4] - df3[1,3]) * 1.07 + df3[1,21] + 0.4 * df3[1,13]
team_possessions <- (poss+ope_poss)/2
dor <- df3[1,15] / (df3[1,15] + df2[1,16])
dfg <- df3[1,3] / df3[1,4]
fmwt <- (dfg * (1 - dor)) / (dfg * (1 - dor) + (1 - dfg) * dor)
dstops <- df1[7] + df1[8] + df1[10]/10 + (df1[4] + df1[5]) * fmwt * (1-dor) + df1[3] * (1-fmwt)
aux <- 0.45 * (df1[10] + df1[12]) * (1-(1- df1[12]/(df1[10]+df1[12])))^2
aux[is.na(aux)] <- 0
dscposs <- df1[11] + aux
dposs <- dstops + dscposs
stops <- dstops / (dstops + dscposs)
tmdposs <- (40/df1[2])*dposs/team_possessions
team_defensive_rating <- 100 * (df3[1,23] / team_possessions)
d_pts_per_scposs <- df3[1,23] / (df3[1,3] + (1 - (1 - (df3[1,12] / df3[1,13]))^2) * df3[1,13]*0.4)
drtg <- team_defensive_rating + tmdposs * (100 * d_pts_per_scposs * (1-stops) - team_defensive_rating)
stats <- cbind(stats,round(dstops,2),round(dscposs,2),round(dposs,2),round(stops,3),round(tmdposs,3),round(drtg,2))
names(stats) = c("Name","MP","DStops","DScPoss","DPoss","Stop%","TMDPoss%","DRtg")
stats[is.na(stats)] <- 0
return(stats)
} |
gpdTailPlot =
function(object, plottype = c("xy", "x", "y", ""), doplot = TRUE, extend = 1.5,
labels = TRUE, ...)
{
threshold = object@fit$threshold
x = as.vector(object@data$x)
data = x[x > threshold]
xi = as.numeric(object@fit$par.ests["xi"])
beta = as.numeric(object@fit$par.ests["beta"])
plotmin = threshold
plotmax = max(data) * max(1, extend)
z = qgpd(seq(from = 0, to = 1, length = 501), xi, threshold, beta)
z = pmax(pmin(z, plotmax), plotmin)
invProb = 1 - length(data)/length(x)
ypoints = invProb*(1-ppoints(sort(data)))
y = invProb*(1-pgpd(z, xi, threshold, beta))
shape = xi
scale = beta * invProb^xi
location = threshold - (scale*(invProb^(- xi)-1))/xi
if (doplot) {
plot(sort(data), ypoints, xlim = range(plotmin, plotmax),
ylim = range(ypoints, y, na.rm = TRUE), col = "steelblue",
pch = 19, xlab = "", ylab = "", log = plottype[1],
axes = TRUE, ...)
lines(z[y >= 0], y[y >= 0])
grid()
alog = plottype[1]
if (labels) {
xLab = "x"
if (alog == "x" || alog == "xy" || alog == "yx")
xLab = paste(xLab, "(on log scale)")
yLab = "1-F(x)"
if (alog == "xy" || alog == "yx" || alog == "y")
yLab = paste(yLab, "(on log scale)")
title(xlab = xLab, ylab = yLab)
title(main = "Tail Estimate Plot")
}
}
object@fit$n = length(x)
object@fit$data = object@data$exceedances
object@fit$n.exceed = length(object@fit$data)
if(object@method[2] == "mle") {
object@fit$method = "ml"
} else {
object@fit$method = ""
}
lastfit = object@fit
class(lastfit) = "gpd"
ans = list(lastfit = lastfit, type = "tail", dist = "gpd",
plotmin = plotmin, plotmax = plotmax, alog = plottype[1],
location = location, shape = shape, scale = scale)
invisible(ans)
}
gpdQPlot =
function(x, p = 0.99, ci = 0.95, type = c("likelihood", "wald"), like.num = 50)
{
par(new = TRUE)
ci.p = ci
pp = p
ci.type = type[1]
if (x$dist != "gpd")
stop("This function is used only with GPD curves")
if (length(pp) > 1)
stop("One probability at a time please")
threshold = x$lastfit$threshold
par.ests = x$lastfit$par.ests
xihat = par.ests["xi"]
betahat = par.ests["beta"]
varcov = x$lastfit$varcov
p.less.thresh = x$lastfit$p.less.thresh
lambda = 1
if (x$type == "tail") lambda = 1/(1 - p.less.thresh)
a = lambda * (1 - pp)
gfunc = function(a, xihat) (a^(-xihat) - 1)/xihat
gfunc.deriv = function(a, xihat) (-(a^(-xihat) - 1)/xihat -
a^(-xihat) * logb(a))/xihat
q = q.keep = threshold + betahat * gfunc(a, xihat)
out = as.numeric(q)
if (ci.type == "wald") {
if (class(x$lastfit) != "gpd")
stop("Wald method requires model be fitted with gpd (not pot)")
scaling = threshold
betahat = betahat/scaling
xivar = varcov[1, 1]
betavar = varcov[2, 2]/(scaling^2)
covar = varcov[1, 2]/scaling
term1 = betavar * (gfunc(a, xihat))^2
term2 = xivar * (betahat^2) * (gfunc.deriv(a, xihat))^2
term3 = 2 * covar * betavar * gfunc(a, xihat) * gfunc.deriv(a, xihat)
qvar = term1 + term2 + term3
if (qvar < 0)
stop("Negative estimate of quantile variance")
qse = scaling * sqrt(qvar)
qq = qnorm(1 - (1 - ci.p)/2)
upper = q + qse * qq
lower = q - qse * qq
abline(v = upper, lty = 2, col = 2)
abline(v = lower, lty = 2, col = 2)
out = as.numeric(c(lower, q, qse, upper))
names(out) = c("Lower CI", "Estimate", "Std.Err", "Upper CI")
}
if (ci.type == "likelihood") {
parloglik =
function(theta, tmp, a, threshold, xpi) {
beta = (theta * (xpi - threshold))/(a^(-theta) -
1)
if ((beta <= 0) || ((theta <= 0) && (max(tmp) > (-beta/theta))))
f = 1e+06
else {
y = logb(1 + (theta * tmp)/beta)
y = y/theta
f = length(tmp) * logb(beta) + (1 + theta) * sum(y)
}
if(is.na(f)) f = 1e+6
f
}
theta = xihat
parmax = NULL
xp = exp(seq(from = logb(threshold), to = logb(x$plotmax),
length = like.num))
excess = as.numeric(x$lastfit$data - threshold)
for (i in 1:length(xp)) {
fit2 = optim(theta, parloglik, method = "BFGS",
hessian = FALSE, tmp = excess, a = a, threshold = threshold,
xpi = xp[i])
parmax = rbind(parmax, fit2$value)
}
parmax = -parmax
overallmax = -parloglik(xihat, excess, a, threshold, q)
crit = overallmax - qchisq(0.999, 1)/2
cond = parmax > crit
xp = xp[cond]
parmax = parmax[cond]
par(new = TRUE)
dolog = ""
if (x$alog == "xy" || x$alog == "x") dolog = "x"
plot(xp, parmax, type = "n", xlab = "", ylab = "", axes = FALSE,
xlim = range(x$plotmin, x$plotmax),
ylim = range(overallmax, crit), log = dolog)
axis(4, at = overallmax - qchisq(c(0.95, 0.99), 1)/2,
labels = c("95", "99"), tick = TRUE)
aalpha = qchisq(ci.p, 1)
abline(h = overallmax - aalpha/2, lty = 2, col = 2)
cond = !is.na(xp) & !is.na(parmax)
smth = spline(xp[cond], parmax[cond], n = 200)
lines(smth, lty = 2, col = 2)
ci = smth$x[smth$y > overallmax - aalpha/2]
abline(v = q.keep, lty = 2)
out = c(min(ci), q, max(ci))
names(out) = c("Lower CI", "Estimate", "Upper CI")
}
out
}
gpdSfallPlot =
function(x, p = 0.99, ci = 0.95, like.num = 50)
{
par(new = TRUE)
pp = p
ci.p = ci
object = x
if(x$dist != "gpd")
stop("This function is used only with GPD curves")
if(length(pp) > 1)
stop("One probability at a time please")
threshold = x$lastfit$threshold
par.ests = x$lastfit$par.ests
xihat = par.ests["xi"]
betahat = par.ests["beta"]
varcov = x$lastfit$varcov
p.less.thresh = x$lastfit$p.less.thresh
lambda = 1
lambda = 1/(1 - p.less.thresh)
a = lambda * (1 - pp)
gfunc = function(a, xihat) (a^( - xihat) - 1) / xihat
q = threshold + betahat * gfunc(a, xihat)
s = s.keep = q + (betahat + xihat * (q - threshold))/(1 - xihat)
out = as.numeric(s)
parloglik = function(theta, tmp, a, threshold, xpi)
{
beta = ((1 - theta) * (xpi - threshold)) /
(((a^( - theta) - 1)/theta) + 1)
if((beta <= 0) || ((theta <= 0) && (max(tmp) > ( - beta/theta)))) {
f = 1e+06
} else {
y = log(1 + (theta * tmp)/beta)
y = y/theta
f = length(tmp) * log(beta) + (1 + theta) * sum(y)
}
f
}
theta = xihat
parmax = NULL
xp = exp(seq(from = log(threshold), to = log(x$plotmax),
length = like.num))
excess = as.numeric(x$lastfit$data - threshold)
for (i in 1:length(xp)) {
fit2 = optim(theta, parloglik, method = "BFGS", hessian = FALSE,
tmp = excess, a = a, threshold = threshold, xpi = xp[i])
parmax = rbind(parmax, fit2$value)
}
parmax = - parmax
overallmax = - parloglik(xihat, excess, a, threshold, s)
crit = overallmax - qchisq(0.999, 1)/2
cond = parmax > crit
xp = xp[cond]
parmax = parmax[cond]
dolog = ""
if(x$alog == "xy" || x$alog == "x") dolog = "x"
par(new = TRUE)
plot(xp, parmax, type = "n", xlab = "", ylab = "", axes = FALSE,
xlim = range(x$plotmin, x$plotmax),
ylim = range(overallmax, crit), log = dolog)
axis(4, at = overallmax - qchisq(c(0.95, 0.99), 1)/2,
labels = c("95", "99"), tick = TRUE)
aalpha = qchisq(ci.p, 1)
abline(h = overallmax - aalpha/2, lty = 2, col = 2)
cond = !is.na(xp) & !is.na(parmax)
smth = spline(xp[cond], parmax[cond], n = 200)
lines(smth, lty = 2, col = 2)
ci = smth$x[smth$y > overallmax - aalpha/2]
abline(v = s.keep, lty = 2)
out = c(min(ci), s, max(ci))
names(out) = c("Lower CI", "Estimate", "Upper CI")
out
}
gpdQuantPlot =
function(x, p = 0.99, ci = 0.95, models = 30, start = 15, end = 500,
doplot = TRUE, plottype = c("normal", "reverse"), labels = TRUE, ...)
{
data = as.vector(x)
n = length(data)
exceed = trunc(seq(from = min(end, n), to = start, length = models))
p = max(p, 1 - min(exceed)/n)
start = max(start, ceiling(length(data) * (1 - p)))
.quantFit = function(nex, data) {
prob = 1 - nex/length(as.vector(data))
fit = gpdFit(data, u = quantile(data, prob))@fit
c(fit$threshold, fit$par.ests, fit$par.ses,
as.vector(fit$varcov)[c(1,4,2)])
}
mat = apply(as.matrix(exceed), 1, .quantFit, data = data)
thresh = mat[1, ]
xihat = mat[2, ]
betahat = mat[3, ]
lambda = length(data)/exceed
a = lambda * (1 - p)
gfunc = function(a, xihat) (a^( - xihat) - 1) / xihat
qest = thresh + betahat * gfunc(a, xihat)
l = u = qest
yrange = range(qest)
if (ci) {
qq = qnorm(1 - (1 - ci)/2)
xivar = mat[4, ]
betavar = mat[5, ]
covar = mat[6, ]
scaling = thresh
betahat = betahat/scaling
betavar = betavar/(scaling^2)
covar = covar/scaling
gfunc.deriv = function(a, xihat)
(-(a^(-xihat)-1)/xihat-a^(-xihat)*log(a))/xihat
term1 = betavar * (gfunc(a, xihat))^2
term2 = xivar * (betahat^2) * (gfunc.deriv(a, xihat))^2
term3 = 2 * covar * betavar * gfunc(a, xihat) * gfunc.deriv(a, xihat)
qvar = term1 + term2 + term3
if (min(qvar) < 0)
stop(paste(
"Conditioning problems lead to estimated negative",
"quantile variance", sep = "\n"))
qse = scaling * sqrt(qvar)
u = qest + qse * qq
l = qest - qse * qq
yrange = range(qest, u, l)
}
mat = rbind(thresh, qest, exceed, l, u)
rownames(mat) = c("threshold", "qest", "exceedances", "lower", "upper")
colnames(mat) = paste(1:dim(mat)[2])
if (doplot) {
if (plottype[1] == "normal") {
index = exceed
} else if (plottype[1] == "reverse") {
index = -exceed
}
plot(index, qest, ylim = yrange, type = "l", xlab = "", ylab = "",
axes = FALSE)
axis(1, at = index, labels = paste(exceed))
axis(2)
axis(3, at = index, labels = paste(format(signif (thresh, 3))))
box()
if (ci) {
lines(index, l, lty = 2, col = "steelblue")
lines(index, u, lty = 2, col = "steelblue")
}
if (labels) {
title(xlab = "Exceedances",
ylab = paste("Quantiles:", substitute(x)))
mtext("Threshold", side = 3, line = 3)
}
p = round(p, 3)
ci = round(ci, 3)
text = paste("p =", p, "| ci =", ci, "| start =",
start, "| end =", end )
mtext(text, side = 4, adj = 0, cex = 0.7)
}
mat = t(mat)
attr(mat, "control") = data.frame(cbind(p = p, ci = ci,
start = start, end = end), row.names = "")
invisible(mat)
}
gpdShapePlot =
function(x, ci = 0.95, models = 30, start = 15, end = 500,
doplot = TRUE, plottype = c("normal", "reverse"), labels = TRUE, ...)
{
data = as.vector(x)
X = trunc(seq(from = min(end, length(data)), to = start, length = models))
.shapeFit = function(nex, data) {
prob = 1 - nex/length(as.vector(data))
fit = gpdFit(data, u = quantile(data, prob),
information = "expected")@fit
c(fit$threshold, fit$par.ests[1], fit$par.ses[1])
}
mat = apply(as.matrix(X), 1, .shapeFit, data = data)
mat = rbind(mat, X)
rownames(mat) = c("threshold", "shape", "se", "exceedances")
colnames(mat) = paste(1:dim(mat)[2])
if (doplot) {
thresh = mat[1, ]
y = mat[2, ]
yrange = range(y)
if (plottype[1] == "normal") {
index = X
} else if (plottype == "reverse") {
index = -X
}
if (ci) {
sd = mat[3, ] * qnorm(1 - (1 - ci)/2)
yrange = range(y, y + sd, y - sd)
}
plot(index, y, ylim = yrange, type = "l", xlab = "", ylab = "",
axes = FALSE)
axis(1, at = index, labels = paste(X))
axis(2)
axis(3, at = index, labels = paste(format(signif(thresh, 3))))
box()
grid()
if (ci) {
sd = mat[3, ] * qnorm(1 - (1 - ci)/2)
yrange = range(y, y + sd, y - sd)
lines(index, y + sd, lty = 2, col = "steelblue")
lines(index, y - sd, lty = 2, col = "steelblue")
}
if (labels) {
title(xlab = "Exceedances",
ylab = paste("Shape:", substitute(x)))
mtext("Threshold", side = 3, line = 3)
}
text = paste("ci =", ci, "| start =", start, "| end =", end )
mtext(text, side = 4, adj = 0, cex = 0.7)
}
attr(mat, "control") = data.frame(cbind(ci = ci,
start = start, end = end), row.names = "")
mat = t(mat)
invisible(mat)
}
gpdRiskMeasures =
function(object, prob = c(0.99, 0.995, 0.999, 0.9995, 0.9999))
{
u = object@parameter$u
par.ests = object@fit$par.ests
xi = par.ests["xi"]
beta = par.ests["beta"]
lambda = 1/(1 - object@fit$prob)
q = u + (beta * ((lambda * (1 - prob))^( - xi) - 1))/xi
es = (q * (1 + (beta - xi * u)/q)) / (1 - xi)
ans = data.frame(p = prob, quantile = q, shortfall = es)
ans
}
tailPlot <-
function(object, p = 0.99, ci = 0.95,
nLLH = 25, extend = 1.5,
grid = TRUE, labels = TRUE, ...)
{
ci.p = p
pp = p
like.num = nLLH
threshold = object@fit$threshold
x = as.vector(object@data$x)
data = x[x > threshold]
xi = as.numeric(object@fit$par.ests["xi"])
beta = as.numeric(object@fit$par.ests["beta"])
plotmin = threshold
plotmax = max(data) * max(1, extend)
z = qgpd(seq(from = 0, to = 1, length = 501), xi, threshold, beta)
z = pmax(pmin(z, plotmax), plotmin)
invProb = 1 - length(data)/length(x)
ypoints = invProb*(1-ppoints(sort(data)))
y = invProb*(1-pgpd(z, xi, threshold, beta))
shape = xi
scale = beta * invProb^xi
location = threshold - (scale*(invProb^(- xi)-1))/xi
xlim = range(plotmin, plotmax)
ylim = range(ypoints, y[y>0], na.rm = TRUE)
plot(sort(data), ypoints, xlim = xlim, ylim = ylim, col = "steelblue",
pch = 19, xlab = "", ylab = "", log = "xy", axes = TRUE, ...)
lines(z[y >= 0], y[y >= 0])
if (grid) grid()
alog = "xy"
if (labels) {
xLab = "x"
if (alog == "x" || alog == "xy" || alog == "yx")
xLab = paste(xLab, "(on log scale)")
yLab = "1-F(x)"
if (alog == "xy" || alog == "yx" || alog == "y")
yLab = paste(yLab, "(on log scale)")
title(xlab = xLab, ylab = yLab)
title(main = "Tail Estimate Plot")
}
object@fit$n = length(x)
object@fit$data = object@data$exceedances
object@fit$n.exceed = length(object@fit$data)
lastfit = object@fit
x = list(lastfit = lastfit, type = "tail", dist = "gpd",
plotmin = plotmin, plotmax = plotmax, alog = "xy",
location = location, shape = shape, scale = scale)
threshold = lastfit$threshold
par.ests = lastfit$par.ests
xihat = par.ests["xi"]
betahat = par.ests["beta"]
varcov = lastfit$varcov
p.less.thresh = lastfit$p.less.thresh
par(new = TRUE)
a = 1/(1 - p.less.thresh) * (1 - pp)
gfunc = function(a, xihat) (a^(-xihat) - 1)/xihat
gfunc.deriv = function(a, xihat)
(-(a^(-xihat)-1)/xihat - a^(-xihat)*logb(a))/xihat
q = q.keep = threshold + betahat * gfunc(a, xihat)
out1 = as.numeric(q)
parloglik = function(theta, tmp, a, threshold, xpi) {
beta = (theta * (xpi - threshold))/(a^(-theta) -
1)
if ((beta <= 0) || ((theta <= 0) && (max(tmp) > (-beta/theta))))
f = 1e+06
else {
y = logb(1 + (theta * tmp)/beta)
y = y/theta
f = length(tmp) * logb(beta) + (1 + theta) * sum(y)
}
if(is.na(f)) f = 1e+6
f
}
theta = xihat
parmax = NULL
xp = exp(seq(from = logb(threshold), to = logb(x$plotmax),
length = like.num))
excess = as.numeric(x$lastfit$data - threshold)
for (i in 1:length(xp)) {
fit2 = optim(theta, parloglik, method = "BFGS",
hessian = FALSE, tmp = excess, a = a, threshold = threshold,
xpi = xp[i])
parmax = rbind(parmax, fit2$value)
}
parmax = -parmax
overallmax = -parloglik(xihat, excess, a, threshold, q)
crit = overallmax - qchisq(0.999, 1)/2
cond = parmax > crit
xp = xp[cond]
parmax = parmax[cond]
par(new = TRUE)
plot(xp, parmax, type = "n", xlab = "", ylab = "", axes = FALSE,
xlim = range(x$plotmin, x$plotmax),
ylim = range(overallmax, crit), log = "x")
axis(4, at = overallmax - qchisq(c(0.95, 0.99), 1)/2,
labels = c("95", "99"), tick = TRUE)
aalpha = qchisq(ci.p, 1)
abline(h = overallmax - aalpha/2, lty = 2, col = 2)
cond = !is.na(xp) & !is.na(parmax)
smth = spline(xp[cond], parmax[cond], n = 200)
lines(smth, lty = 2, col = 2)
ci = smth$x[smth$y > overallmax - aalpha/2]
abline(v = q.keep, lty = 2)
out1 = c(min(ci), q, max(ci))
names(out1) = c("Lower CI", "Estimate", "Upper CI")
a = 1/(1 - p.less.thresh) * (1 - pp)
gfunc = function(a, xihat) (a^( - xihat) - 1) / xihat
q = threshold + betahat * gfunc(a, xihat)
s = s.keep = q + (betahat + xihat * (q - threshold))/(1 - xihat)
out = as.numeric(s)
parloglik = function(theta, tmp, a, threshold, xpi)
{
beta = ((1-theta)*(xpi-threshold)) / (((a^(-theta)-1)/theta)+1)
if((beta <= 0) || ((theta <= 0) && (max(tmp) > ( - beta/theta)))) {
f = 1e+06
} else {
y = log(1 + (theta * tmp)/beta)
y = y/theta
f = length(tmp) * log(beta) + (1 + theta) * sum(y)
}
f
}
theta = xihat
parmax = NULL
xp = exp(seq(from = log(threshold), to = log(x$plotmax),
length = like.num))
excess = as.numeric(x$lastfit$data - threshold)
for (i in 1:length(xp)) {
fit2 = optim(theta, parloglik, method = "BFGS", hessian = FALSE,
tmp = excess, a = a, threshold = threshold, xpi = xp[i])
parmax = rbind(parmax, fit2$value)
}
parmax = -parmax
overallmax = -parloglik(xihat, excess, a, threshold, s)
crit = overallmax - qchisq(0.999, 1)/2
cond = parmax > crit
xp = xp[cond]
parmax = parmax[cond]
par(new = TRUE)
plot(xp, parmax, type = "n", xlab = "", ylab = "", axes = FALSE,
xlim = range(x$plotmin, x$plotmax),
ylim = range(overallmax, crit), log = "x")
axis(4, at = overallmax - qchisq(c(0.95, 0.99), 1)/2,
labels = c("95", "99"), tick = TRUE)
aalpha = qchisq(ci.p, 1)
abline(h = overallmax - aalpha/2, lty = 2, col = 2)
cond = !is.na(xp) & !is.na(parmax)
smth = spline(xp[cond], parmax[cond], n = 200)
lines(smth, lty = 2, col = 2)
ci = smth$x[smth$y > overallmax - aalpha/2]
abline(v = s.keep, lty = 2)
out2 = c(min(ci), s, max(ci))
names(out2) = c("Lower CI", "Estimate", "Upper CI")
ans = list(var = out1, sfall = out2)
invisible(ans)
}
.tailSlider.last.Quantile = NA
.tailSlider.last.nThresholds = NA
.tailSlider.param = NA
.tailSlider.conf = NA
.tailSlider.counter = NA
.tailSlider.Thresholds = NA
tailSlider =
function(x)
{
x = as.vector(x)
on.exit(rm(.tailSlider.last.Quantile))
on.exit(rm(.tailSlider.last.nThresholds))
on.exit(rm(.tailSlider.param))
on.exit(rm(.tailSlider.conf))
on.exit(rm(.tailSlider.counter))
on.exit(rm(x))
refresh.code = function(...)
{
.tailSlider.counter <<- .tailSlider.counter + 1
u = thresholdStart = .sliderMenu(no = 1)
du = .sliderMenu(no = 2)
max.x = .sliderMenu(no = 3)
nThresholds = .sliderMenu(no = 4)
Quantile = .sliderMenu(no = 5)
pp = .sliderMenu(no = 6)
if (.tailSlider.counter > 5) {
par(mfrow = c(2, 2), cex = 0.7)
ans = mxfPlot(x, u = quantile(x, 1),
xlim = c(min(x), max.x), labels = FALSE)
grid()
U = min(c(u+du, max(x)))
abline(v = u, lty = 3, col = "red")
abline(v = U, lty = 3, col = "red")
X = as.vector(ans[, 1])
Y = as.vector(ans[, 2])
Y = Y[X > u & X < U]
X = X[X > u & X < U]
lineFit = lsfit(X, Y)
abline(lineFit, col = "red", lty = 2)
c = lineFit$coef[[1]]
m = lineFit$coef[[2]]
xi = c(xi = m/(1+m))
beta = c(beta = c/(1+m))
Xi = signif(xi, 3)
Beta = signif(beta, 3)
Main = paste("Fig 1: xi = ", Xi, "| beta =", Beta)
title(main = Main, xlab = "Threshold", ylab = "Mean Excess")
if (.tailSlider.last.Quantile != Quantile | .tailSlider.last.nThresholds != nThresholds) {
.tailSlider.param <<- NULL
.tailSlider.conf <<- NULL
.tailSlider.Thresholds <<- seq(quantile(x, Quantile), quantile(x, 1-Quantile),
length = nThresholds)
for (threshold in .tailSlider.Thresholds) {
ans = gpdFit(x, threshold)@fit
.tailSlider.param <<- rbind(.tailSlider.param, c(u = threshold, ans$par.ests))
.tailSlider.conf <<- rbind(.tailSlider.conf, c(u = threshold, ans$par.ses))
}
.tailSlider.last.Quantile <<- Quantile
.tailSlider.last.nThresholds <<- nThresholds
}
ymax = max(c(.tailSlider.param[, 2] + .tailSlider.conf[, 2]))
ymin = min(c(.tailSlider.param[, 2] - .tailSlider.conf[, 2]))
plot(.tailSlider.Thresholds, .tailSlider.param[, 2], xlab = "Threshold", ylab = "xi",
ylim = c(ymin, ymax), col = "steelblue", type = "l",
main = "xi Estimation")
grid()
points(.tailSlider.Thresholds, .tailSlider.param[, 2], pch = 19, col = "steelblue")
lines(.tailSlider.Thresholds, .tailSlider.param[, 2] + .tailSlider.conf[, 2], lty = 3)
lines(.tailSlider.Thresholds, .tailSlider.param[, 2] - .tailSlider.conf[, 2], lty = 3)
abline(h = xi, lty = 3, col = "red")
abline(v = u, lty = 3, col = "red")
abline(v = U, lty = 3, col = "red")
ymax = max(c(.tailSlider.param[, 3] + .tailSlider.conf[, 3]))
ymin = min(c(.tailSlider.param[, 3] - .tailSlider.conf[, 3]))
plot(.tailSlider.Thresholds, .tailSlider.param[, 3], xlab = "Threshold", ylab = "beta",
ylim = c(ymin, ymax), col = "steelblue", type = "l",
main = "beta Estimation")
grid()
points(.tailSlider.Thresholds, .tailSlider.param[, 3], pch = 19, col = "steelblue")
lines(.tailSlider.Thresholds, .tailSlider.param[, 3] + .tailSlider.conf[, 3], lty = 3)
lines(.tailSlider.Thresholds, .tailSlider.param[, 3] - .tailSlider.conf[, 3], lty = 3)
abline(h = beta, lty = 3, col = "red")
abline(v = u, lty = 3, col = "red")
abline(v = U, lty = 3, col = "red")
fit = gpdFit(x, u)
tailPlot(object = fit, p = pp)
par(mfrow = c(2, 2), cex = 0.7)
}
}
x <<- as.vector(x)
xmax = max(x)
delta.x = (max(x)-min(x))/200
start.x = par()$usr[2]
qmin = quantile(x, 0.25)
qmax = quantile(x, 0.995)
delta.q = (qmax-qmin)/200
start.q = (qmin+qmax)/2
.tailSlider.last.Quantile <<- 0.05*(1+1e-4)
.tailSlider.last.nThresholds <<- 10+1
.tailSlider.param <<- NA
.tailSlider.conf <<- NA
.tailSlider.counter <<- 0
.sliderMenu(refresh.code,
names = c("1 thresholdStart",
"1 thresholdInterval",
"1 max(x)",
"2|3 nThresholds",
"2|3 Quantile",
"pp"),
minima = c( qmin, 0, min(x), 5, 0.005, 0.900),
maxima = c( qmax, qmax, max(x), 50, 0.500, 0.999),
resolutions = c( delta.q, delta.x, delta.x, 5, 0.005, 0.001),
starts = c( start.q, start.x, max(x), 10, 0.050, 0.990))
}
tailRisk =
function(object, prob = c(0.99, 0.995, 0.999, 0.9995, 0.9999), ...)
{
u = object@parameter$u
par.ests = object@fit$par.ests
xi = par.ests["xi"]
beta = par.ests["beta"]
lambda = 1/(1 - object@fit$prob)
q = u + (beta * ((lambda * (1 - prob))^( - xi) - 1))/xi
es = (q * (1 + (beta - xi * u)/q)) / (1 - xi)
ans = data.frame(Prob = prob, VaR = q, ES = es)
ans
} |
DisjunctivePower = function(test.result, statistic.result, parameter) {
if (is.null(parameter$alpha)) stop("Evaluation model: DisjunctivePower: alpha parameter must be specified.")
alpha = parameter$alpha
if (is.numeric(test.result))
significant = (test.result <= alpha)
if (is.matrix(test.result))
significant = (rowSums(test.result <= alpha) > 0)
power = mean(significant, na.rm = TRUE)
return(power)
} |
check4SPSS <- function(GADSdat) {
UseMethod("check4SPSS")
}
check4SPSS.GADSdat <- function(GADSdat) {
check_GADSdat(GADSdat)
labels <- GADSdat$labels
spclChar_varNams <- colnames(GADSdat$dat)[grep("[^[:alnum:]_\\$@
long_varNames <- unique(namesGADS(GADSdat)[nchar_4_spss(namesGADS(GADSdat)) > 64])
long_varLabels <- unique(labels$varName[!is.na(labels$varLabel) & nchar_4_spss(labels$varLabel) > 256])
long_valLabels <- unique(labels$varName[!is.na(labels$valLabel) & nchar_4_spss(labels$valLabel) > 120])
if(length(long_valLabels) > 0 ){
names(long_valLabels) <- long_valLabels
long_valLabels <- lapply(long_valLabels, function(nam) {
single_meta <- extractMeta(GADSdat, nam)
single_long_valLabels <- single_meta[!is.na(single_meta$valLabel) & nchar_4_spss(single_meta$valLabel) > 120, "value"]
})
}
chv <- sapply(GADSdat$dat, is.character)
misInfo <- unique(labels[which(!is.na(labels$value) & labels$missings == "miss"), c("varName", "value", "valLabel", "missings")])
many_missCodes <- unlist(lapply(namesGADS(GADSdat), function(v) {
if(isTRUE(chv[v]) & length(misInfo$value[which(misInfo$varName==v)]) > 3) {
return(v)
}
character()
}))
list(varNames_special = spclChar_varNams,
varNames_length = long_varNames,
varLabels = long_varLabels,
valLabels = long_valLabels,
missings = many_missCodes)
}
nchar_4_spss <- function(x) {
long_str <- stringi::stri_escape_unicode(x)
nchar(gsub("\\\\u00", "", long_str), type = "chars")
} |
setupDataLists <- function(data, ctrlOpts = NULL, lv_model = NULL){
if (is.null(data)){
stop(paste0(
"gimme ERROR: neither a data directory nor a data list is specified. ",
"Please either specify a directory of data or a list of individual data files."
)
)
}
if (is.list(data)){
ts_list <- list()
if(is.null(names(data))){
names(data) <- paste0("subj", 1:length(data))
}
ts_list <- data
} else if (!is.list(data)){
files <- list.files(data, full.names = TRUE)
if (is.null(ctrlOpts$sep)){
stop(paste0(
"gimme ERROR: a data directory is specified but a ctrlOpts$sep argument is not. ",
"Please specify a ctrlOpts$sep argument before continuing."
))
}
if (is.null(ctrlOpts$header)){
stop(paste0(
"gimme ERROR: a data directory is specified but a ctrlOpts$header argument is not. ",
"Please specify a logical value for ctrlOpts$header before continuing."
))
}
ts_list <- list()
for (i in 1:length(files)){
ts_list[[i]] <- read.table(files[i], sep = ctrlOpts$sep, header = ctrlOpts$header)
}
names(ts_list) <- tools::file_path_sans_ext(basename(files))
} else {
stop(paste0(
"gimme ERROR: Format of data argument not recognized. "
))
}
varnames <- colnames(ts_list[[1]])
n_orig_vars <- ncol(ts_list[[1]])
if(is.null(varnames)){
varnames <- c(paste0("V", seq(1,n_orig_vars)))
ts_list <- lapply(ts_list, function(x) { colnames(x)<-varnames; x })
} else {
if(is.null(lv_model)){
ts_list <- lapply(ts_list, function(x) { x[,varnames]})
}
}
return(ts_list)
} |
girregrec <- function(siginput, gtinput, phi, nbnodes, nvoice,
freqstep, scale, epsilon = 0.5,fast = FALSE, prob= 0.8, plot = FALSE,
para = 0, hflag = FALSE, real = FALSE, check = FALSE)
{
tmp <- RidgeSampling(phi,nbnodes)
node <- tmp$node
phinode <- tmp$phinode
phi.x.min <- scale
phi.x.max <- scale
x.min <- node[1]
x.max <- node[length(node)]
x.max <- x.max + round(para * phi.x.max)
x.min <- x.min - round(para * phi.x.min)
node <- node - x.min + 1
x.inc <- 1
np <- as.integer((x.max-x.min)/x.inc)+1
cat(" (np:",np,")")
if(epsilon == 0)
Q2 <- 0
else {
if (fast == FALSE)
Q2 <- gkernel(node,phinode,freqstep,scale,x.min = x.min, x.max = x.max)
else
Q2 <- fastgkernel(node,phinode,freqstep,scale,x.min = x.min,
x.max = x.max)
}
cat(" kernel;")
if (hflag == TRUE)
one <- gsampleOne(node,scale,np)
else{
one <- numeric(np)
one[] <- 1
}
if (epsilon !=0 ){
Q <- epsilon * Q2
for(j in 1:np)
Q[j,j] <- Q[j,j] + one[j]
Qinv <- solve(Q)
}
else{
Qinv <- 1/one
}
tmp2 <- gridrec(gtinput,node,phinode,nvoice,
freqstep,scale,Qinv,epsilon,np, real = real, check = check)
tmp <- RidgeIrregSampling(phinode, node, tmp2$lam, prob)
node <- tmp$node
phinode <- tmp$phinode
phi.x.min <- scale
phi.x.max <- scale
x.min <- node[1]
x.max <- node[length(node)]
x.max <- x.max + round(para * phi.x.max)
x.min <- x.min - round(para * phi.x.min)
node <- node - x.min + 1
x.inc <- 1
np <- as.integer((x.max-x.min)/x.inc)+1
cat(" (np:",np,")")
if(epsilon == 0)
Q2 <- 0
else {
if (fast == FALSE)
Q2 <- gkernel(node,phinode,freqstep,scale,x.min = x.min, x.max = x.max)
else
Q2 <- fastgkernel(node,phinode,freqstep,scale,x.min = x.min,
x.max = x.max)
}
cat(" kernel;")
if (hflag == TRUE)
one <- gsampleOne(node,scale,np)
else{
one <- numeric(np)
one[] <- 1
}
if (epsilon !=0 ){
Q <- epsilon * Q2
for(j in 1:np)
Q[j,j] <- Q[j,j] + one[j]
Qinv <- solve(Q)
}
else{
Qinv <- 1/one
}
tmp2 <- gridrec(gtinput,node,phinode,nvoice,
freqstep,scale,Qinv,epsilon,np, real = real, check = check)
if(plot == TRUE){
par(mfrow=c(2,1))
plot.ts(Re(siginput))
title("Original signal")
plot.ts(Re(tmp2$sol))
title("Reconstructed signal")
}
list(sol=tmp2$sol,A=tmp2$A,lam=tmp2$lam,dualwave=tmp2$dualwave,
gaborets=tmp2$gaborets, solskel=tmp2$solskel,
inputskel = tmp2$inputskel, Q2 = Q2)
}
RidgeIrregSampling <- function(phinode, node, lam, prob)
{
nbnodes <- length(node)
mlam <- numeric(nbnodes)
for(j in 1:nbnodes)
mlam[j] <- Mod(lam[j] + 1i*lam[nbnodes + j])
pct <- quantile(mlam,prob)
count <- sum(mlam > pct)
newnode <- numeric(count)
newphinode <- numeric(count)
count <- 0
for(j in 1:nbnodes) {
if(mlam[j] > pct) {
newnode[count+1] <- node[j]
newphinode[count+1] <- phinode[j]
count <- count + 1
}
}
list(node = newnode,phinode = newphinode, nbnodes = count)
} |
calc.rate.weib <-
function(par)
{ rate <- par[1]/exp(lgamma(1+1/par[2]))
return(rate)
} |
l2 <- function(x){ return(sqrt(sum(x^2)))} |
options(guiToolkit="RGtk2")
readRepo <- function(dir=getwd()) {
files <- gitLsFiles(dir, "stage")
status <- gitStatus(dir, ignored=TRUE)
if ("??" %in% status$XY) {
tmp <- data.frame(tag = "", mode = NA, object = "", stage = NA,
file = with(status, file[XY == "??"]))
files <- if (nrow(files) > 0) rbind(files, tmp) else tmp
}
if ("!!" %in% status$XY) {
tmp <- data.frame(tag = "", mode = NA, object = "", stage = NA,
file = with(status, file[XY == "!!"]))
files <- if (nrow(files) > 0) rbind(files,tmp) else tmp
}
if ("D " %in% status$XY) {
tmp <- data.frame(tag = "", mode = NA, object = "", stage = NA,
file = with(status, file[XY == "D "]))
files <- if (nrow(files) > 0) rbind(files,tmp) else tmp
}
if (nrow(files) == 0) return(data.frame())
files$directory = sub("/[^/]*$", "", files$file)
files <- within(files, directory[directory == file] <- "")
dirs <- unique(files$directory)
dirs <- dirs[dirs != ""]
if (length(dirs) > 0)
files <- rbind(files,
data.frame(tag = "", mode = 040000, object = "", stage = NA,
file = dirs,
directory = sub("/?[^/]+/?$", "", dirs)))
files$was <- files$status <- ""
for (file in status$file) {
idx1 <- status$file == file
idx2 <- files$file == file
files$status[idx2] <- status$XY[idx1]
files$was[idx2] <- status$was[idx1]
}
for (dir in dirs) {
statuses <- subset(files, directory == dir)$status
if (all(statuses == "??"))
files$status[files$file == dir] <- "??"
if (all(grepl("R.", statuses)))
files$status[files$file == dir] <- "R "
}
if (nrow(files) > 1) files <- files[with(files, mixedorder(file)),]
files$filename <- sub(".*/", "", files$file)
files <- files[!grepl("^\\.
files
}
offspring <- function(path, user.data, ...) {
obj <- user.data$obj
if(length(path) > 0)
directory <- obj$absPath(path)
else {
directory <- obj$absPath()
dirty <- gitIsDirty(directory)
Branch <- gitBranch(directory)
Upstream <- gitUpstream(directory)
status <- c("dirty", "detached HEAD", "unpushed commits", "unpulled commits")
return(data.frame(Filename = obj$repo, mode=0,
Staged = FALSE, Modified = dirty,
Upstream = Upstream, Branch = Branch,
Status = paste(status[c(dirty, nchar(Branch)==0,
grepl("\\+", Upstream), grepl("\\-", Upstream))],
collapse=", "),
Mode=gitMode2Str(0)))
}
files <- readRepo(directory)
files <- files[files$directory == "", ,drop=FALSE]
Branch <- rep("", nrow(files))
idx <- !is.na(files$mode) & files$mode == 160000
if (any(idx))
Branch[idx] <- sapply(paste(directory, files$filename[idx],
sep = .Platform$file.sep), gitBranch)
Status <- gitStatus2Str(files$status)
Staged <- grepl("(from|to|in) index", Status)
Modified <- grepl("in work tree", Status)
if (any(idx))
Status[idx] <- ifelse(nchar(Branch[idx]) == 0, "detached HEAD", "")
idx <- files$mode == 160000 & substring(files$status, 2, 2) == "M"
if (any(idx)) {
Status[idx] <- paste(Status[idx],
gitStatus2Str(sprintf("%s ", substring(files$status[idx], 1, 1))),
gitSubmoduleStatus(directory, files$file[idx]), sep=", ")
}
idx <- Branch != ""
Upstream <- Branch
Upstream[idx] <- sapply(paste(directory, files$filename[idx],
sep = .Platform$file.sep), gitUpstream)
Status[idx] <- paste(Status[idx],
ifelse(grepl("\\+", Upstream[idx]), "unpushed commits", ""),
ifelse(grepl("\\-", Upstream[idx]), "unpulled commits", ""), sep=", ")
Status <- sub(", $", "", sub("^, ", "", gsub(", , ", ", ", Status)))
ret <- data.frame(Filename=files$filename, mode = as.numeric(files$mode),
Staged = Staged, Modified = Modified, Upstream = Upstream,
Branch = Branch, Status = Status, Mode=gitMode2Str(files$mode))
idx <- rep(TRUE, nrow(ret))
if (obj$preferences["hiddenFiles"] == "hide")
idx <- idx & !grepl("^\\.", ret$Filename)
if (obj$preferences["untrackedFiles"] == "hide")
idx <- idx & files$status != "??"
if (obj$preferences["ignoredFiles"] == "hide")
idx <- idx & files$status != "!!"
ret[idx, ]
}
hasOffspring <- function(children,user.data=NULL, ...) {
return(children$mode %in% c(0, 160000, 40000))
}
icon.FUN <- function(children,user.data=NULL, ...) {
x <- rep("file", length=nrow(children))
x[children$mode == 0] <- "about"
x[children$mode == 160000] <- "jump-to"
x[children$mode == 40000] <- "directory"
x[is.na(children$mode)] <- "missing-image"
x[grepl(paste("(", gitStatus2Str(c("D ", " D")), ")", collapse="|", sep=""),
children$Status)] <- "delete"
return(x)
}
contextMenu <- function(h, widget, event, action=NULL, ...) {
if(event$GetButton() == 3 ||
(event$GetState() == GdkModifierType['control-mask'] &&
event$GetButton() == 1)) {
obj <- h$action$actualobj
path <- obj$tr$getPathAtPos(event$x, event$y)$path
sel <- obj$tr$getSelection()
sel$unselectAll()
sel$selectPath(path)
menulist <- genContextMenulist(obj)
mb = gmenu(menulist, popup = TRUE)
mb = tag(mb,"mb")
gtkMenuPopup(mb,button = event$GetButton(),
activate.time=event$GetTime())
} else {
return(FALSE)
}
}
setRefClass("gitR",
fields = list(
path = "character",
repo = "character",
w = "gWindow",
m = "guiComponent",
tb = "gToolbar",
grp = "gGroup",
la = "gImage",
tr = "gTree",
s = "gStatusbar",
position = "list",
lastout = "character",
preferences = "character",
prefMenu = "list"
),
methods = list(
getWindow = function() {
'Return gtkWindow object'
w@widget@widget
},
getGTree = function() {
'Return GTree object'
tr@widget
},
getTreeView = function() {
'Return gtkTreeView object'
tr@widget@widget
},
refresh = function() {
'Refresh gTree'
update(.self$getGTree(), user.data = list(obj=.self))
},
status = function(...) {
'Set or get status bar message'
values <- list(...)
if (length(values) == 0) return(svalue(s))
svalue(s) <<- paste(values, collapse=" ")
invisible(svalue(s))
},
hide = function() {
'Hide tree view and display loading animation'
grp$Remove(tr@widget@block@widget@widget)
grp$Add(la@widget@block)
},
show = function() {
'Show tree view and hide loading animation'
grp$Remove(la@widget@block)
grp$Add(tr@widget@block@widget@widget)
},
absPath = function(...) {
'Return absolute path'
paths <- unlist(list(...))
rPath <- if (length(paths) == 0) {
rPath <- repo
} else paste(paths, collapse=.Platform$file.sep)
paste(path, rPath, sep=.Platform$file.sep)
},
quit = function(...) {
saveRDS(preferences, file="~/.gitR")
dispose(w)
}
))
createGUI <- function(path=getwd()) {
path <- try(gitToplevel(path))
if (is(path, "try-error")) {
return("This is not a git repository.")
}
w <- gwindow("gitR", visible=FALSE)
addHandlerDestroy(w, handler=function(...) {
assign(".gitR.windows",
get(".gitR.windows",
envir=.GlobalEnv,
mode="numeric") - 1,
envir=.GlobalEnv)
})
obj <- new("gitR", w=w,
path = sub("(.*)/[^/]+/?$", "\\1", path),
repo = sub(".*/([^/]+)/?$", "\\1", path))
obj$m <- gmenu(menulist <- genMenulist(obj), container=w)
obj$prefMenu <- menulist$Preferences
obj$tb <- gtoolbar(genToolbar(obj), style="both", container=w)
obj$grp <- ggroup(horizontal=FALSE, spacing=0, container=w)
obj$la <- gimage(system.file("images/loading.gif", package="traitr"),
expand = TRUE)
obj$tr <- gtree(offspring, hasOffspring = hasOffspring,
icon.FUN = icon.FUN, container=obj$grp,
offspring.data = list(obj = obj), expand=TRUE)
obj$s <- gstatusbar("Initializing...", container=w)
addHandlerDoubleclick(obj$getGTree(),
handler=doubleClickHandler,
action=list(actualobj=obj))
addHandler(obj$getGTree(), signal="button-press-event",
handler=contextMenu, action=list(actualobj=obj))
tv <- obj$getTreeView()
tv$GetColumn(2)$SetVisible(FALSE)
cellrenderer <- gtkCellRendererToggleNew()
cellrenderer$radio <- TRUE
column <- tv$GetColumn(3)
column$Clear()
column$PackStart(cellrenderer, TRUE)
column$AddAttribute(cellrenderer, "active", 3)
column <- tv$GetColumn(4)
column$Clear()
column$PackStart(cellrenderer, TRUE)
column$AddAttribute(cellrenderer, "active", 4)
obj$tr$ExpandRow(gtkTreePathNewFromString("0"), FALSE)
obj$status("Initialized.")
w$resize(1000, 600)
visible(obj$w) <- TRUE
.gitR.windows <- if (!exists(".gitR.windows", envir=.GlobalEnv)) {
0
} else {
get(".gitR.windows", envir=.GlobalEnv, mode="numeric")
}
assign(".gitR.windows", .gitR.windows + 1, envir=.GlobalEnv)
obj
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.