code
stringlengths 1
13.8M
|
---|
FDist<-function(X,gen=1,Cont=TRUE,inputNA,plot=FALSE,p.val_min=.05,crit=2,DPQR=TRUE){
if(missing(inputNA)){X<-na.omit(X)}
else{X<-ifelse(is.na(X),inputNA,X)}
if(length(X)==0){
return(NULL)
}
X<-X[X!=(-Inf) & X!=Inf]
if (length(unique(X))<2) {
fun_g<-function(n=gen){return(rep(X[1],n))}
return(list(paste0("norm(",X[1],",0)"),fun_g,rep(X[1],gen),data.frame(Dist="norm",AD_p.v=1,KS_p.v=1,estimate1=X[1],estimate2=0,estimateLL1=0,estimateLL2=1,PV_S=2),NULL))
}
if (length(unique(X))==2) {
X<-sort(X)
p<-length(X[X==unique(X)[2]])/length(X)
gene<-stats::rbinom
formals(gene)[1]<-length(X)
formals(gene)[2]<-1
formals(gene)[3]<-p
distribu<-paste0("binom(",p,")")
MA=gene(n = gen)
if(plot){
DF<-rbind(data.frame(A="Fit",DT=MA),
data.frame(A="Real",DT=X))
pl <- ggplot2::ggplot(DF,ggplot2::aes(x=DF$DT,fill=DF$A)) + ggplot2::geom_density(alpha=0.4) +ggplot2::ggtitle(distribu)
}else{
pl<-NULL
}
return(list(distribu,gene,MA[1:gen],data.frame(Dist="binom",AD_p.v=1,KS_p.v=1,estimate1=1,estimate2=p,estimateLL1=0,estimateLL2=1,PV_S=2),pl))
}
DIS<-list(Nombres=c("exp","pois","beta","gamma","lnorm","norm","weibull","nbinom","hyper","cauchy","binom"),
p=c(stats::pexp,stats::ppois,stats::pbeta,stats::pgamma,stats::plnorm,stats::pnorm,stats::pweibull,stats::pnbinom,stats::phyper,stats::pcauchy,stats::pbinom),
d=c(stats::dexp,stats::dpois,stats::dbeta,stats::dgamma,stats::dlnorm,stats::dnorm,stats::dweibull,stats::dnbinom,stats::dhyper,stats::dcauchy,stats::dbinom),
q=c(stats::qexp,stats::qpois,stats::qbeta,stats::qgamma,stats::qlnorm,stats::qnorm,stats::qweibull,stats::qnbinom,stats::qhyper,stats::qcauchy,stats::qbinom),
r=c(stats::rexp,stats::rpois,stats::rbeta,stats::rgamma,stats::rlnorm,stats::rnorm,stats::rweibull,stats::rnbinom,stats::rhyper,stats::rcauchy,stats::rbinom),
d_c=c(1,0,1,1,1,1,1,0,0,1,0),
indicadora=c("0","0","01","0","0","R","0","0","0","R","0")
)
DIS<-purrr::map(DIS,~subset(.x, DIS$d_c==as.numeric(Cont)))
DIS_0<-purrr::map(DIS,~subset(.x, DIS$indicadora=="0"))
DIS_R<-purrr::map(DIS,~subset(.x, DIS$indicadora=="R"))
DIS_01<-purrr::map(DIS,~subset(.x, DIS$indicadora=="01"))
if(sum(purrr::map_dbl(DIS_0,~length(.x)))==0){DIS_0<-NULL}
if(sum(purrr::map_dbl(DIS_R,~length(.x)))==0){DIS_R<-NULL}
if(sum(purrr::map_dbl(DIS_01,~length(.x)))==0){DIS_01<-NULL}
bt<-X
despl<-0
escala<-1
eps<-1E-15
if (sum(X<0)>0){
if (sum(X<0)/length(X)<0.03){
bt<-ifelse(X<0,eps,X)
b_0<-bt
}else{
b_0<-bt-min(bt)+eps
despl<- min(bt)
}
}else{
b_0<-bt
}
if(max(X)>1){
escala<-max(bt)
b_01<-(bt-despl)/(escala-despl)
}else{
b_01<-bt
}
fit_b<-function(bt,dist="",Cont.=Cont){
if(is.null(dist)){return(NULL)}
Disc<-!Cont
aju<-list()
if(!dist %in% DIS_01$Nombres){
suppressWarnings(aju[[1]]<-try(fitdistrplus::fitdist(bt,dist,method = "mle",discrete = Disc),silent = TRUE))
}
suppressWarnings(aju[[2]]<-try(fitdistrplus::fitdist(bt,dist,method = "mme",discrete = Disc),silent = TRUE))
suppressWarnings(aju[[3]]<-try(fitdistrplus::fitdist(bt,dist,method = c("mge"),discrete = Disc),silent = TRUE))
suppressWarnings(aju[[4]]<-try(MASS::fitdistr(bt,dist),silent = TRUE))
if(!assertthat::is.error(aju[[4]])){aju[[4]]$distname<-dist}
if(assertthat::is.error(aju[[1]]) & assertthat::is.error(aju[[2]]) &
assertthat::is.error(aju[[3]]) & assertthat::is.error(aju[[4]])){
return(list())
}
funcionales<-!purrr::map_lgl(aju,~assertthat::is.error(.x))
names(aju)<-c("mle","mme","mge","mlg2")
aju<-aju[funcionales]
return(aju)
}
suppressWarnings(try(aju_0<-purrr::map(DIS_0$Nombres,~fit_b(b_0,.x)),silent = TRUE))
suppressWarnings(try(aju_R<-purrr::map(DIS_R$Nombres,~fit_b(bt,.x)),silent = TRUE))
suppressWarnings(try(aju_01<-purrr::map(DIS_01$Nombres,~fit_b(b_01,.x)),silent = TRUE))
AAA<-list(aju_0,aju_R,aju_01)
descate<-purrr::map(AAA,~length(.x))!=0
AAA<-AAA[descate]
bts<-list(b_0,bt,b_01)[descate]
num<-0
Compe<-data.frame()
for (aju_ls in 1:length(AAA)) {
aju<-AAA[[aju_ls]]
aju<-aju[purrr::map_lgl(aju,~length(.x)>0)]
bs<-bts[[aju_ls]]
for (comp in 1:length(aju)) {
if(length(aju)==0 ||length(aju[[comp]])==0){next()}
for (ress in 1:length(aju[[comp]])) {
num<-num+1
if(length(aju[[comp]])!=0){evaluar<-aju[[comp]][[ress]]
}else{evaluar<-NULL}
if (is.null(evaluar) | length(evaluar)==0 |
c(NA) %in% evaluar$estimate | c(NaN) %in% evaluar$estimate) {next()}
distname<-evaluar$distname
method<-names(aju[[comp]])[[ress]]
dist_pfun<-try(get(paste0("p",distname)),silent = TRUE)
dist_rfun<-try(get(paste0("r",distname)),silent = TRUE)
if(assertthat::is.error(dist_rfun)){next()}
argumentos<-formalArgs(dist_pfun)
argumentos<-argumentos[argumentos %in% names(evaluar$estimate)]
num_param<-length(argumentos)
evaluar$estimate<-evaluar$estimate[names(evaluar$estimate) %in% argumentos]
if(num_param==1){
EAD<-try(AD<-ADGofTest::ad.test(bs,dist_pfun,evaluar$estimate[1]),silent = TRUE)
KS<-try(stats::ks.test(bs,dist_pfun,evaluar$estimate[1]),silent = TRUE)
if(assertthat::is.error(KS)){KS<-data.frame(p.value=NA)}
if(assertthat::is.error(EAD)){next()}
if(is.na(KS$p.value)){next()}
Chs<-data.frame(p.value=0)
}
if(num_param==2){
suppressWarnings(
Err_pl<-try(AD<-ADGofTest::ad.test(bs,dist_pfun,evaluar$estimate[1],evaluar$estimate[2]),silent = TRUE))
if (assertthat::is.error(Err_pl)) {
Err_pl<-try(AD<-ADGofTest::ad.test(bs,dist_pfun,evaluar$estimate[1],,evaluar$estimate[2]),silent = TRUE)
}
KS<-try(stats::ks.test(bs,dist_pfun,evaluar$estimate[1],evaluar$estimate[2]),silent = TRUE)
if(assertthat::is.error(KS)){KS<-data.frame(p.value=NA)}
if(assertthat::is.error(Err_pl)){next()}
if(is.na(KS$p.value)){next()}
suppressWarnings(
EE_Chs<-try(dst_chsq<-dist_rfun(length(bs),evaluar$estimate[1],evaluar$estimate[2]))
)
if(assertthat::is.error(EE_Chs) | prod(is.na(EE_Chs))==1){
dst_chsq<-dist_rfun(length(bs),evaluar$estimate[1],,evaluar$estimate[2])
}
Chs<-data.frame(p.value=0)
}
pvvv<-p.val_min
if(all(is.na(KS$p.value))){
crit<-AD$p.value>pvvv
}else{
if(crit==1){
crit<-AD$p.value>pvvv | KS$p.value>pvvv
}else{
crit<-AD$p.value>(pvvv) & KS$p.value>(pvvv)
}
}
if(crit){
if(aju_ls %in% 3){
estimate3=despl
estimate4=escala
}else if(aju_ls==1){
estimate3=despl
estimate4=1
}else{
estimate3=0
estimate4=1
}
Compe<-rbind(Compe,data.frame(Dist=distname,AD_p.v=AD$p.value,KS_p.v=KS$p.value,
Chs_p.v=Chs$p.value,
estimate1=evaluar$estimate[1],estimate2=evaluar$estimate[2],
estimateLL1=estimate3,estimateLL2=estimate4,method=method
))
}else{
next()
}
}
}
}
if (nrow(Compe)==0) {
warning("No fit")
return(NULL)
}
Compe$PV_S<-rowSums(Compe[,2:4])
WNR<-Compe[Compe$PV_S %in% max(Compe$PV_S),][1,]
distW<-WNR$Dist
paramsW<-WNR[1,names(Compe)[startsWith(names(Compe),"estim")]]
paramsW<-paramsW[,!is.na(paramsW)]
if(gen<=0){gen<-1}
generadora_r<-function(n=gen,dist=distW,params=paramsW){
fn<-get(paste0("r",dist))
formals(fn)[1]<-n
for (pr in 1:(length(params)-2)) {
formals(fn)[pr+1]<-as.numeric(params[pr])
}
fn()*params[,length(params)]+params[,length(params)-1]
}
if(DPQR){
generadoras<-function(x,tipo,dist=distW,params=paramsW){
fn<-get(paste0(tipo,dist))
formals(fn)[1]<-x
for (pr in 1:(length(params)-2)) {
formals(fn)[pr+1]<-as.numeric(params[pr])
}
class(fn)<-"gl_fun"
fn
}
rfit<-generadora_r
class(rfit)<-"gl_fun"
pfit<-generadoras(1,"p")
qfit<-generadoras(1,"q")
dfit<-generadoras(1,"d")
}
MA<-generadora_r()
paramsAUX<-c()
paramsW2<-data.frame()
for(cl in 1:nrow(paramsW)){
paramsW2<-rbind(paramsW2,round(paramsW[1,],3))
}
if(paramsW2[,length(paramsW2)]!=1 | paramsW2[,length(paramsW2)-1]!=0){
distribu<-paste0(WNR$Dist,"(",paste0(paramsW2[,1:(length(paramsW2)-2)],collapse = ", "),")*",paramsW2[,length(paramsW2)],"+",paramsW2[,length(paramsW2)-1])
}else{
distribu<-paste0(WNR$Dist,"(",paste0(paramsW2[,1:(length(paramsW2)-2)],collapse = ", "),")")
}
p<-c()
if(plot){
DF<-rbind(data.frame(A="Fit",DT=MA),
data.frame(A="Real",DT=X))
p <- ggplot2::ggplot(DF,ggplot2::aes(x=DF$DT,fill=DF$A)) + ggplot2::geom_density(alpha=0.4) +ggplot2::ggtitle(distribu)
}
return(list(distribu,generadora_r,MA,WNR[,-4],p,list(rfit,pfit,dfit,qfit),Compe))
}
|
glance.data.frame <- function(x, ...) {
stop(
"There is no glance method for data frames. ",
"Did you mean `tibble::glimpse()`?",
call. = FALSE
)
}
glance.tbl_df <- function(x, ...) {
stop(
"There is no glance method for tibbles. ",
"Did you mean `tibble::glimpse()`?",
call. = FALSE
)
}
|
perIndividualQC <- function(indir, name, qcdir=indir,
dont.check_sex=FALSE,
do.run_check_sex=TRUE, do.evaluate_check_sex=TRUE,
maleTh=0.8, femaleTh=0.2,
externalSex=NULL, externalMale="M",
externalSexSex="Sex", externalSexID="IID",
externalFemale="F", fixMixup=FALSE,
dont.check_het_and_miss=FALSE,
do.run_check_het_and_miss=TRUE,
do.evaluate_check_het_and_miss=TRUE,
imissTh=0.03, hetTh=3,
dont.check_relatedness=FALSE,
do.run_check_relatedness=TRUE,
do.evaluate_check_relatedness=TRUE,
highIBDTh=0.1875,
mafThRelatedness=0.1,
filter_high_ldregion=TRUE,
high_ldregion_file=NULL,
genomebuild='hg19',
dont.check_ancestry=FALSE,
do.run_check_ancestry=TRUE,
do.evaluate_check_ancestry=TRUE,
prefixMergedDataset, europeanTh=1.5,
defaultRefSamples = c("HapMap", "1000Genomes"),
refSamples=NULL, refColors=NULL,
refSamplesFile=NULL, refColorsFile=NULL,
refSamplesIID="IID", refSamplesPop="Pop",
refColorsColor="Color", refColorsPop="Pop",
studyColor="
highlight_samples = NULL,
highlight_type =
c("text", "label", "color", "shape"),
highlight_text_size = 3,
highlight_color = "
highlight_shape = 17,
highlight_legend = FALSE,
interactive=FALSE, verbose=TRUE,
keep_individuals=NULL,
remove_individuals=NULL,
exclude_markers=NULL,
extract_markers=NULL,
legend_text_size = 5,
legend_title_size = 7,
axis_text_size = 5,
axis_title_size = 7,
subplot_label_size = 9,
title_size = 9,
path2plink=NULL, showPlinkOutput=TRUE) {
missing_genotype <- NULL
highIBD <- NULL
outlying_heterozygosity <- NULL
mismatched_sex <- NULL
ancestry <- NULL
p_sexcheck <- NULL
p_het_imiss <- NULL
p_relatedness <- NULL
p_ancestry <- NULL
out <- makepath(qcdir, name)
if (!dont.check_sex) {
if (do.run_check_sex) {
run <- run_check_sex(indir=indir, qcdir=qcdir, name=name,
path2plink=path2plink,
showPlinkOutput=showPlinkOutput,
keep_individuals=keep_individuals,
remove_individuals=remove_individuals,
exclude_markers=exclude_markers,
extract_markers=extract_markers,
verbose=verbose)
}
if (do.evaluate_check_sex) {
if (verbose) {
message("Identification of individuals with discordant sex ",
"information")
}
fail_sex <- evaluate_check_sex(qcdir=qcdir, indir=indir, name=name,
maleTh=maleTh, femaleTh=femaleTh,
externalSex=externalSex,
externalMale=externalMale,
externalFemale=externalFemale,
externalSexSex=externalSexSex,
externalSexID=externalSexID,
verbose=verbose,
path2plink=path2plink,
showPlinkOutput=showPlinkOutput,
fixMixup=fixMixup,
label_fail=label_fail,
highlight_samples =
highlight_samples,
highlight_type = highlight_type,
highlight_text_size =
highlight_text_size,
highlight_color = highlight_color,
highlight_shape = highlight_shape,
highlight_legend = highlight_legend,
legend_text_size = legend_text_size,
legend_title_size =
legend_title_size,
axis_text_size = axis_text_size,
axis_title_size = axis_title_size,
title_size = title_size,
interactive=FALSE)
write.table(fail_sex$fail_sex[,1:2],
file=paste(out, ".fail-sexcheck.IDs",
sep=""),
quote=FALSE, row.names=FALSE, col.names=FALSE)
if (!is.null(fail_sex$fail_sex) &&
nrow(fail_sex$fail_sex) != 0) {
mismatched_sex<- select(fail_sex$fail_sex,
.data$FID, .data$IID)
}
if (!is.null(fail_sex$mixup)) {
write.table(fail_sex$mixup[,1:2],
file=paste(out, ".sexcheck_mixup.IDs",
sep=""),
quote=FALSE, row.names=FALSE, col.names=FALSE)
}
p_sexcheck <- fail_sex$p_sexcheck
}
}
if (!dont.check_het_and_miss) {
if (do.run_check_het_and_miss) {
run_miss <- run_check_missingness(qcdir=qcdir, indir=indir,
name=name,
path2plink=path2plink,
showPlinkOutput=showPlinkOutput,
keep_individuals=keep_individuals,
remove_individuals=remove_individuals,
exclude_markers=exclude_markers,
extract_markers=extract_markers,
verbose=verbose)
run_het <- run_check_heterozygosity(qcdir=qcdir, indir=indir,
name=name,
path2plink=path2plink,
showPlinkOutput=showPlinkOutput,
keep_individuals=keep_individuals,
remove_individuals=remove_individuals,
exclude_markers=exclude_markers,
extract_markers=extract_markers,
verbose=verbose)
}
if (do.evaluate_check_het_and_miss) {
if (verbose) {
message("Identification of individuals with outlying missing ",
"genotype or heterozygosity rates")
}
fail_het_imiss <-
evaluate_check_het_and_miss(qcdir=qcdir, name=name,
imissTh=imissTh,
hetTh=hetTh, label_fail=label_fail,
highlight_samples =
highlight_samples,
highlight_type = highlight_type,
highlight_text_size =
highlight_text_size,
highlight_color = highlight_color,
highlight_shape = highlight_shape,
highlight_legend = highlight_legend,
legend_text_size = legend_text_size,
legend_title_size =
legend_title_size,
axis_text_size = axis_text_size,
axis_title_size = axis_title_size,
title_size = title_size,
interactive=FALSE)
write.table(fail_het_imiss$fail_imiss[,1:2],
file=paste(out, ".fail-imiss.IDs",
sep=""),
quote=FALSE, row.names=FALSE, col.names=FALSE)
if (!is.null(fail_het_imiss$fail_imiss) &&
nrow(fail_het_imiss$fail_imiss) != 0) {
missing_genotype <- select(fail_het_imiss$fail_imiss,
.data$FID, .data$IID)
}
write.table(fail_het_imiss$fail_het[,1:2],
file=paste(out, ".fail-het.IDs",
sep=""),
quote=FALSE, row.names=FALSE, col.names=FALSE)
if (!is.null(fail_het_imiss$fail_het) &&
nrow(fail_het_imiss$fail_het) != 0) {
outlying_heterozygosity <- select(fail_het_imiss$fail_het,
.data$FID, .data$IID)
} else {
outlying_heterozygosity <- NULL
}
p_het_imiss <- fail_het_imiss$p_het_imiss
}
}
if (!dont.check_relatedness) {
if (do.run_check_relatedness) {
run <- run_check_relatedness(qcdir=qcdir, indir=indir, name=name,
path2plink=path2plink,
mafThRelatedness=mafThRelatedness,
filter_high_ldregion=
filter_high_ldregion,
high_ldregion_file=high_ldregion_file,
genomebuild=genomebuild,
showPlinkOutput=showPlinkOutput,
keep_individuals=keep_individuals,
remove_individuals=remove_individuals,
exclude_markers=exclude_markers,
extract_markers=extract_markers,
verbose=verbose)
}
if (do.evaluate_check_relatedness) {
if (verbose) message("Identification of related individuals")
fail_relatedness <- evaluate_check_relatedness(qcdir=qcdir,
name=name,
imissTh=imissTh,
highIBDTh=highIBDTh,
legend_text_size =
legend_text_size,
legend_title_size =
legend_title_size,
axis_text_size =
axis_text_size,
axis_title_size =
axis_title_size,
title_size =
title_size,
interactive=FALSE)
write.table(fail_relatedness$failIDs,
file=paste(out, ".fail-IBD.IDs", sep=""),
row.names=FALSE, quote=FALSE, col.names=FALSE,
sep="\t")
if (!is.null(fail_relatedness$failIDs) &&
nrow(fail_relatedness$failIDs) != 0) {
highIBD <- select(fail_relatedness$failIDs,
.data$FID, .data$IID)
}
p_relatedness <- fail_relatedness$p_IBD
}
}
if (!dont.check_ancestry) {
if (do.run_check_ancestry) {
run <- run_check_ancestry(qcdir=qcdir, indir=indir,
prefixMergedDataset=prefixMergedDataset,
path2plink=path2plink,
showPlinkOutput=showPlinkOutput,
keep_individuals=keep_individuals,
remove_individuals=remove_individuals,
exclude_markers=exclude_markers,
extract_markers=extract_markers,
verbose=verbose)
}
if (do.evaluate_check_ancestry) {
if (verbose) {
message("Identification of individuals of divergent ancestry")
}
fail_ancestry <- evaluate_check_ancestry(qcdir=qcdir, indir=indir,
name=name,
prefixMergedDataset=
prefixMergedDataset,
europeanTh=europeanTh,
defaultRefSamples =
defaultRefSamples,
refSamples=refSamples,
refColors=refColors,
refSamplesFile=
refSamplesFile,
refColorsFile=
refColorsFile,
refSamplesIID=
refSamplesIID,
refSamplesPop=
refSamplesPop,
refColorsColor=
refColorsColor,
refColorsPop=
refColorsPop,
studyColor=studyColor,
highlight_samples =
highlight_samples,
highlight_type =
highlight_type,
highlight_text_size =
highlight_text_size,
highlight_color =
highlight_color,
highlight_shape =
highlight_shape,
highlight_legend =
highlight_legend,
legend_text_size =
legend_text_size,
legend_title_size =
legend_title_size,
axis_text_size =
axis_text_size,
axis_title_size =
axis_title_size,
title_size = title_size,
interactive=FALSE)
write.table(fail_ancestry$fail_ancestry,
file=paste(out, ".fail-ancestry.IDs",
sep=""),
quote=FALSE, row.names=FALSE, col.names=FALSE)
if (!is.null(fail_ancestry$fail_ancestry) &&
nrow(fail_ancestry$fail_ancestry) != 0) {
ancestry <- select(fail_ancestry$fail_ancestry,
.data$FID, .data$IID)
}
p_ancestry <- fail_ancestry$p_ancestry
}
}
fail_list <- list(missing_genotype=missing_genotype,
highIBD=highIBD,
outlying_heterozygosity=outlying_heterozygosity,
mismatched_sex=mismatched_sex,
ancestry=ancestry)
if(verbose) message(paste("Combine fail IDs into ", out, ".fail.IDs",
sep=""))
uniqueFails <- do.call(rbind, fail_list)
uniqueFails <- uniqueFails[!duplicated(uniqueFails$IID),]
write.table(uniqueFails, file=paste(out, ".fail.IDs",sep=""),
quote=FALSE, row.names=FALSE, col.names=FALSE)
plots_sampleQC <- list(p_sexcheck=p_sexcheck,
p_het_imiss=p_het_imiss,
p_relatedness=p_relatedness,
p_ancestry=p_ancestry)
plots_sampleQC <- plots_sampleQC[sapply(plots_sampleQC,
function(x) !is.null(x))]
subplotLabels <- LETTERS[1:length(plots_sampleQC)]
if (!is.null(p_ancestry)) {
ancestry_legend <- cowplot::get_legend(p_ancestry)
plots_sampleQC$p_ancestry <- plots_sampleQC$p_ancestry +
theme(legend.position = "None")
plots_sampleQC$ancestry_legend <- ancestry_legend
subplotLabels <- c(subplotLabels, "")
}
if (!is.null(p_sexcheck) && !is.null(p_het_imiss)) {
first_plots <- cowplot::plot_grid(plotlist=plots_sampleQC[1:2],
nrow=2,
align = "v",
axis = "lr",
labels=subplotLabels[1:2],
label_size = subplot_label_size
)
if (!is.null(p_ancestry)) {
if (!is.null(p_relatedness)) {
rel_heights <- c(2, 1, 1, 0.3)
plots_sampleQC <- list(first_plots,
plots_sampleQC[[3]],
plots_sampleQC[[4]],
plots_sampleQC[[5]]
)
subplotLabels <- c("", subplotLabels[3:5])
} else {
rel_heights <- c(2, 1, 0.3)
plots_sampleQC <- list(first_plots,
plots_sampleQC[[3]],
plots_sampleQC[[4]]
)
subplotLabels <- c("", subplotLabels[3:4])
}
} else {
if (!is.null(p_relatedness)) {
rel_heights <- c(2, 1)
plots_sampleQC <- list(first_plots, plots_sampleQC[[3]])
subplotLabels <- c("", subplotLabels[3])
} else {
rel_heights <- 1
plots_sampleQC <- first_plots
subplotLabels <- ""
}
}
} else {
if (!is.null(p_ancestry)) {
rel_heights <- c(rep(1, length(plots_sampleQC) -1), 0.3)
} else {
rel_heights <- c(rep(1, length(plots_sampleQC)))
}
}
p_sampleQC <- cowplot::plot_grid(plotlist=plots_sampleQC,
nrow=length(plots_sampleQC),
labels=subplotLabels,
label_size = subplot_label_size,
rel_heights=rel_heights)
if (interactive) {
print(p_sampleQC)
}
return(list(fail_list=fail_list, p_sampleQC=p_sampleQC))
}
overviewPerIndividualQC <- function(results_perIndividualQC,
interactive=FALSE) {
if (length(perIndividualQC) == 2 &&
!all(names(results_perIndividualQC) == c("fail_list", "p_sampleQC"))) {
stop("results_perIndividualQC not direct output of perIndividualQC")
}
fail_list <- results_perIndividualQC$fail_list
samples_fail_all <- do.call(rbind, fail_list)
fail_list_wo_ancestry <- fail_list[!names(fail_list) == "ancestry"]
id_list_wo_ancestry <- sapply(fail_list_wo_ancestry, function(x) x$IID)
unique_samples_fail_wo_ancestry <- unique(unlist(id_list_wo_ancestry))
fail_counts_wo_ancestry <- UpSetR::fromList(id_list_wo_ancestry)
rownames(fail_counts_wo_ancestry) <- unique_samples_fail_wo_ancestry
p <- UpSetR::upset(fail_counts_wo_ancestry,
order.by = "freq",
empty.intersections = "on", text.scale=1.2,
mainbar.y.label="Samples failing multiple QC checks",
sets.x.label="Sample fails per QC check",
main.bar.color="
sets.bar.color="
p_qc <- cowplot::plot_grid(NULL, p$Main_bar, p$Sizes, p$Matrix,
nrow=2, align='v', rel_heights = c(3,1),
rel_widths = c(2,3))
if (interactive) {
print(p_qc)
}
fail_counts_wo_ancestry <- merge(samples_fail_all, fail_counts_wo_ancestry,
by.x=2, by.y=0)
if ("ancestry" %in% names(fail_list) && !is.null(fail_list$ancestry)) {
fail_all <- list(QC_fail=unique_samples_fail_wo_ancestry,
Ancestry_fail=fail_list$ancestry$IID)
unique_samples_fail_all <- unique(unlist(fail_all))
fail_counts_all <- UpSetR::fromList(fail_all)
rownames(fail_counts_all) <- unique_samples_fail_all
m <- UpSetR::upset(fail_counts_all,
order.by = "freq",
mainbar.y.label=
"Samples failing QC and ancestry checks",
sets.x.label="Sample fails per QC check",
empty.intersections = "on", text.scale=1.2,
main.bar.color="
sets.bar.color="
p_all <- cowplot::plot_grid(NULL, m$Main_bar, m$Sizes, m$Matrix,
nrow=2, align='v', rel_heights = c(3,1),
rel_widths = c(2,3))
if (interactive) {
print(p_all)
}
fail_counts_all <- merge(samples_fail_all, fail_counts_all,
by.x=2, by.y=0)
p_overview <- cowplot::plot_grid(NULL, p$Main_bar, p$Sizes, p$Matrix,
NULL, m$Main_bar, m$Sizes, m$Matrix,
nrow=4, align='v',
rel_heights = c(3,1,3,1),
rel_widths = c(2,3))
} else {
p_overview <- p_qc
fail_counts_all <- NULL
}
nr_fail_samples <- length(unique(samples_fail_all$IID))
return(list(nr_fail_samples=nr_fail_samples,
fail_QC=fail_counts_wo_ancestry,
fail_QC_and_ancestry=fail_counts_all,
p_overview=p_overview))
}
check_sex <- function(indir, name, qcdir=indir, maleTh=0.8, femaleTh=0.2,
run.check_sex=TRUE,
externalSex=NULL,
externalFemale="F", externalMale="M",
externalSexSex="Sex", externalSexID="IID",
fixMixup=FALSE,
interactive=FALSE, verbose=FALSE,
label_fail=TRUE,
highlight_samples = NULL,
highlight_type =
c("text", "label", "color", "shape"),
highlight_text_size = 3,
highlight_color = "
highlight_shape = 17,
highlight_legend = FALSE,
path2plink=NULL,
keep_individuals=NULL,
remove_individuals=NULL,
exclude_markers=NULL,
extract_markers=NULL,
legend_text_size = 5,
legend_title_size = 7,
axis_text_size = 5,
axis_title_size = 7,
title_size = 9,
showPlinkOutput=TRUE) {
if (run.check_sex) {
run_sex <- run_check_sex(indir=indir, qcdir=qcdir, name=name,
verbose=verbose,
path2plink=path2plink,
keep_individuals=keep_individuals,
remove_individuals=remove_individuals,
exclude_markers=exclude_markers,
extract_markers=extract_markers,
showPlinkOutput=showPlinkOutput)
}
fail <- evaluate_check_sex(qcdir=qcdir, name=name, externalSex=externalSex,
maleTh=maleTh, femaleTh=femaleTh,
interactive=interactive, fixMixup=fixMixup,
indir=indir,
label_fail=label_fail,
externalFemale=externalFemale,
externalMale=externalMale,
externalSexSex=externalSexSex,
externalSexID=externalSexID,
verbose=verbose, path2plink=path2plink,
highlight_samples = highlight_samples,
highlight_type = highlight_type,
highlight_text_size = highlight_text_size,
highlight_color = highlight_color,
highlight_shape = highlight_shape,
highlight_legend = highlight_legend,
keep_individuals=keep_individuals,
remove_individuals=remove_individuals,
exclude_markers=exclude_markers,
extract_markers=extract_markers,
legend_text_size = legend_text_size,
legend_title_size = legend_title_size,
axis_text_size = axis_text_size,
axis_title_size = axis_title_size,
title_size = title_size,
showPlinkOutput=showPlinkOutput)
return(fail)
}
check_het_and_miss <- function(indir, name, qcdir=indir, imissTh=0.03, hetTh=3,
run.check_het_and_miss=TRUE,
label_fail=TRUE,
highlight_samples = NULL,
highlight_type =
c("text", "label", "color", "shape"),
highlight_text_size = 3,
highlight_color = "
highlight_shape = 17,
highlight_legend = FALSE,
interactive=FALSE, verbose=FALSE,
keep_individuals=NULL,
remove_individuals=NULL,
exclude_markers=NULL,
extract_markers=NULL,
legend_text_size = 5,
legend_title_size = 7,
axis_text_size = 5,
axis_title_size = 7,
title_size = 9,
path2plink=NULL, showPlinkOutput=TRUE) {
if (run.check_het_and_miss) {
run_het <- run_check_heterozygosity(indir=indir,qcdir=qcdir, name=name,
verbose=verbose,
path2plink=path2plink,
keep_individuals=keep_individuals,
remove_individuals=remove_individuals,
exclude_markers=exclude_markers,
extract_markers=extract_markers,
showPlinkOutput=showPlinkOutput)
run_miss <- run_check_missingness(indir=indir, qcdir=qcdir, name=name,
verbose=verbose,
path2plink=path2plink,
keep_individuals=keep_individuals,
remove_individuals=remove_individuals,
exclude_markers=exclude_markers,
extract_markers=extract_markers,
showPlinkOutput=showPlinkOutput)
}
fail <- evaluate_check_het_and_miss(qcdir=qcdir, name=name, hetTh=hetTh,
imissTh=imissTh, interactive=interactive,
label_fail=label_fail,
highlight_samples = highlight_samples,
highlight_type = highlight_type,
highlight_text_size = highlight_text_size,
highlight_color = highlight_color,
highlight_shape = highlight_shape,
highlight_legend = highlight_legend,
legend_text_size = legend_text_size,
legend_title_size = legend_title_size,
title_size = title_size,
axis_text_size = axis_text_size,
axis_title_size = axis_title_size)
return(fail)
}
check_relatedness <- function(indir, name, qcdir=indir, highIBDTh=0.1875,
filter_high_ldregion=TRUE,
high_ldregion_file=NULL,
genomebuild='hg19', imissTh=0.03,
run.check_relatedness=TRUE,
interactive=FALSE, verbose=FALSE,
mafThRelatedness=0.1, path2plink=NULL,
keep_individuals=NULL,
remove_individuals=NULL,
exclude_markers=NULL,
extract_markers=NULL,
legend_text_size = 5,
legend_title_size = 7,
axis_text_size = 5,
axis_title_size = 7,
title_size = 9,
showPlinkOutput=TRUE) {
if (run.check_relatedness) {
run <- run_check_relatedness(indir=indir, qcdir=qcdir, name=name,
verbose=verbose,
mafThRelatedness=mafThRelatedness,
path2plink=path2plink,
highIBDTh=highIBDTh,
genomebuild=genomebuild,
keep_individuals=keep_individuals,
remove_individuals=remove_individuals,
exclude_markers=exclude_markers,
extract_markers=extract_markers,
showPlinkOutput=showPlinkOutput)
}
fail <- evaluate_check_relatedness(qcdir=qcdir, name=name,
highIBDTh=highIBDTh,
imissTh=imissTh, interactive=interactive,
legend_text_size = legend_text_size,
legend_title_size = legend_title_size,
axis_text_size = axis_text_size,
axis_title_size = axis_title_size,
title_size = title_size,
verbose=verbose)
return(fail)
}
check_ancestry <- function(indir, name, qcdir=indir, prefixMergedDataset,
europeanTh=1.5,
defaultRefSamples =
c("HapMap","1000Genomes"),
refPopulation=c("CEU", "TSI"),
refSamples=NULL, refColors=NULL,
refSamplesFile=NULL, refColorsFile=NULL,
refSamplesIID="IID", refSamplesPop="Pop",
refColorsColor="Color", refColorsPop="Pop",
studyColor="
legend_labels_per_row=6,
run.check_ancestry=TRUE,
interactive=FALSE, verbose=verbose,
highlight_samples = NULL,
highlight_type =
c("text", "label", "color", "shape"),
highlight_text_size = 3,
highlight_color = "
highlight_shape = 17,
highlight_legend = FALSE,
legend_text_size = 5,
legend_title_size = 7,
axis_text_size = 5,
axis_title_size = 7,
title_size = 9,
keep_individuals=NULL,
remove_individuals=NULL,
exclude_markers=NULL,
extract_markers=NULL,
path2plink=NULL, showPlinkOutput=TRUE) {
if (run.check_ancestry) {
run <- run_check_ancestry(indir=indir, qcdir=qcdir,
prefixMergedDataset=prefixMergedDataset,
verbose=verbose,
path2plink=path2plink,
keep_individuals=keep_individuals,
remove_individuals=remove_individuals,
exclude_markers=exclude_markers,
extract_markers=extract_markers,
showPlinkOutput=showPlinkOutput)
}
fail <- evaluate_check_ancestry(qcdir=qcdir, indir=indir, name=name,
prefixMergedDataset=prefixMergedDataset,
europeanTh=europeanTh,
refPopulation=refPopulation,
refSamples=refSamples,
refColors=refColors,
refSamplesFile=refSamplesFile,
refColorsFile=refColorsFile,
refSamplesIID=refSamplesIID,
refSamplesPop=refSamplesPop,
refColorsColor=refColorsColor,
refColorsPop=refColorsPop,
studyColor=studyColor,
legend_labels_per_row=
legend_labels_per_row,
highlight_samples = highlight_samples,
highlight_type = highlight_type,
highlight_text_size =
highlight_text_size,
highlight_color = highlight_color,
highlight_shape = highlight_shape,
highlight_legend = highlight_legend,
defaultRefSamples = defaultRefSamples,
legend_text_size = legend_text_size,
legend_title_size = legend_title_size,
title_size = title_size,
axis_text_size = axis_text_size,
axis_title_size = axis_title_size,
interactive=interactive)
return(fail)
}
run_check_sex <- function(indir, name, qcdir=indir, verbose=FALSE,
path2plink=NULL,
keep_individuals=NULL,
remove_individuals=NULL,
exclude_markers=NULL,
extract_markers=NULL,
showPlinkOutput=TRUE) {
prefix <- makepath(indir, name)
out <- makepath(qcdir, name)
checkFormat(prefix)
path2plink <- checkPlink(path2plink)
args_filter <- checkFiltering(keep_individuals, remove_individuals,
extract_markers, exclude_markers)
if (verbose) message("Run check_sex via plink --check-sex")
sys::exec_wait(path2plink,
args=c("--bfile", prefix, "--check-sex", "--out", out,
args_filter),
std_out=showPlinkOutput, std_err=showPlinkOutput)
}
evaluate_check_sex <- function(qcdir, name, maleTh=0.8,
femaleTh=0.2, externalSex=NULL,
fixMixup=FALSE, indir=qcdir,
externalFemale="F", externalMale="M",
externalSexSex="Sex", externalSexID="IID",
verbose=FALSE, label_fail=TRUE,
highlight_samples = NULL,
highlight_type =
c("text", "label", "color", "shape"),
highlight_text_size = 3,
highlight_color = "
highlight_shape = 17,
highlight_legend = FALSE,
legend_text_size = 5,
legend_title_size = 7,
axis_text_size = 5,
axis_title_size = 7,
title_size = 9,
path2plink=NULL,
keep_individuals=NULL,
remove_individuals=NULL,
exclude_markers=NULL,
extract_markers=NULL,
showPlinkOutput=TRUE,
interactive=FALSE) {
prefix <- makepath(indir, name)
out <- makepath(qcdir, name)
if (!file.exists(paste(out, ".sexcheck", sep=""))){
stop("plink --check-sex results file: ", out,
".sexcheck does not exist.")
}
testNumerics(numbers=c(maleTh, femaleTh), positives=c(maleTh, femaleTh),
proportions=c(maleTh, femaleTh))
sexcheck <- read.table(paste(out, ".sexcheck",sep=""),
header=TRUE, stringsAsFactors=FALSE)
names_sexcheck <- c("FID", "IID", "PEDSEX", "SNPSEX", "STATUS", "F")
if (!all(names_sexcheck == names(sexcheck))) {
stop("Header of", out, ".sexcheck is not correct. Was your
file generated with plink --check-sex?")
}
if (is.null(externalSex)) {
fail_sex <- sexcheck[sexcheck$STATUS == "PROBLEM",]
if (nrow(fail_sex) == 0) fail_sex <- NULL
mixup_geno_pheno <- NULL
} else {
if (!(externalSexSex %in% names(externalSex))) {
stop("Column ", externalSexSex, " not found in externalSex!")
}
if (!(externalSexID %in% names(externalSex))) {
stop("Column ", externalSexID, " not found in externalSex!")
}
names(externalSex)[names(externalSex) == externalSexSex] <- "Sex"
names(externalSex)[names(externalSex) == externalSexID] <- "IID"
sexcheck_fuse <- merge(sexcheck, externalSex, by="IID")
sex_mismatch <-
apply(dplyr::select(sexcheck_fuse, .data$Sex, .data$PEDSEX,
.data$SNPSEX), 1,
function(ind) {
if (ind[1] == externalFemale && ind[2] %in% c(0, 1)) {
return(ifelse(ind[3] == 2, FALSE, TRUE))
}
if (ind[1] == externalMale && ind[2] %in% c(0, 2)) {
return(ifelse(ind[3] == 1, FALSE, TRUE))
}
if (ind[1] == externalFemale && ind[2] == 2) {
return(ifelse(ind[3] == 1, TRUE, NA))
}
if (ind[1] == externalMale && ind[2] == 1) {
return(ifelse(ind[3] == 2, TRUE, NA))
}
})
fail_sex <-
dplyr::select(sexcheck_fuse, .data$FID, .data$IID, .data$Sex,
.data$PEDSEX, .data$SNPSEX, .data$F)[which(sex_mismatch),]
if (nrow(fail_sex) == 0) {
fail_sex <- NULL
mixup_geno_pheno <- NULL
} else {
mixup_geno_pheno <-
dplyr::select(sexcheck_fuse, .data$FID, .data$IID, .data$Sex,
.data$PEDSEX, .data$SNPSEX, .data$F)[which(!sex_mismatch),]
if (fixMixup) {
checkFormat(prefix)
path2plink <- checkPlink(path2plink)
args_filter <- checkFiltering(keep_individuals,
remove_individuals,
extract_markers, exclude_markers)
if (nrow(mixup_geno_pheno) != 0) {
file_mixup <- paste(out, ".mismatched_sex_geno_pheno",
sep="")
write.table(dplyr::select(mixup_geno_pheno, .data$FID,
.data$IID, .data$SNPSEX),
file=file_mixup,
row.names=FALSE, quote=FALSE, col.names=FALSE)
sys::exec_wait(path2plink, args=c("--bfile", prefix,
"--update-sex", file_mixup,
"--make-bed",
"--out", prefix,
args_filter),
std_out=showPlinkOutput, std_err=showPlinkOutput)
} else {
if (verbose) {
message("All assigned genotype sexes (PEDSEX) match",
" external sex assignment (Sex)")
}
mixup_geno_pheno <- NULL
}
} else {
if (nrow(mixup_geno_pheno) != 0) {
fail_sex <- rbind(fail_sex, mixup_geno_pheno)
} else {
mixup_geno_pheno <- NULL
}
}
}
}
sexcheck$LABELSEX <- "Unassigned"
sexcheck$LABELSEX[sexcheck$PEDSEX == 1] <- "Male"
sexcheck$LABELSEX[sexcheck$PEDSEX == 2] <- "Female"
colors <- c("
names(colors) <- c("Unassigned", "Male", "Female")
sexcheck$shape <- "general"
shape_guide <- FALSE
if(!is.null(highlight_samples)) {
if (!all(highlight_samples %in% sexcheck$IID)) {
stop("Not all samples to be highlighted are present in the",
"name.fam file")
}
highlight_type <- match.arg(highlight_type, several.ok = TRUE)
if (all(c("text", "label") %in% highlight_type)) {
stop("Only one of text or label highlighting possible; either ",
"can be combined with shape and color highlighting")
}
if ("shape" %in% highlight_type) {
sexcheck$shape[sexcheck$IID %in% highlight_samples] <- "highlight"
shape_guide <- highlight_legend
}
if ("color" %in% highlight_type && highlight_legend) {
sexcheck$LABELSEX[sexcheck$IID %in% highlight_samples] <- "highlight"
colors <- c(colors, highlight_color)
names(colors)[length(colors)] <- "highlight"
}
}
sexcheck$LABELSEX <- factor(sexcheck$LABELSEX, levels=names(colors))
sexcheck$PEDSEX <- as.factor(sexcheck$PEDSEX)
sexcheck$shape <- as.factor(sexcheck$shape)
p_sexcheck <- ggplot()
p_sexcheck <- p_sexcheck + geom_point(data=sexcheck,
aes_string(x='PEDSEX', y='F',
color='LABELSEX',
shape='shape')) +
scale_shape_manual(values=c(16, highlight_shape), guide="none") +
scale_color_manual(values=colors, name="Sex") +
labs(title="Check assigned sex versus SNP sex",
x="Reported Sex (PEDSEX)",
y="ChrX heterozygosity") +
geom_segment(data=data.frame(x=0.8, xend=1.2, y=maleTh,
yend=maleTh),
aes_string(x='x', xend='xend', y='y', yend='yend'), lty=2,
color="
geom_segment(data=data.frame(x=1.8, xend=2.2, y=femaleTh,
yend=femaleTh), lty=2,
aes_string(x='x', xend='xend', y='y', yend='yend'),
color="
if (!is.null(fail_sex) && label_fail) {
p_sexcheck <- p_sexcheck +
ggrepel::geom_label_repel(
data=dplyr::filter(sexcheck, .data$IID %in% fail_sex$IID),
aes_string(x='PEDSEX',
y='F',
label='IID'),
size=highlight_text_size)
}
if (!is.null(highlight_samples)) {
highlight_data <- dplyr::filter(sexcheck, .data$IID %in% highlight_samples)
if ("text" %in% highlight_type) {
p_sexcheck <- p_sexcheck +
ggrepel::geom_text_repel(data=highlight_data,
aes_string(x='PEDSEX', y='F',
label="IID"),
size=highlight_text_size)
}
if ("label" %in% highlight_type) {
p_sexcheck <- p_sexcheck +
ggrepel::geom_label_repel(data=highlight_data,
aes_string(x='PEDSEX', y='F',
label='IID'),
size=highlight_text_size)
}
if ("color" %in% highlight_type && !highlight_legend) {
p_sexcheck <- p_sexcheck +
geom_point(data=highlight_data,
aes_string(x='PEDSEX', y='F', shape='shape'),
color=highlight_color)
}
if ("shape" %in% highlight_type && highlight_legend) {
p_sexcheck <- p_sexcheck +
guides(shape = "legend") +
labs(shape = "Individual")
}
}
p_sexcheck <- p_sexcheck +
theme_bw() +
theme(legend.text = element_text(size = legend_text_size),
legend.title = element_text(size = legend_title_size),
title = element_text(size = title_size),
axis.text = element_text(size = axis_text_size),
axis.title = element_text(size = axis_title_size))
if (interactive) print(p_sexcheck)
return(list(fail_sex=fail_sex, mixup=mixup_geno_pheno,
p_sexcheck=p_sexcheck, plot_data=sexcheck))
}
run_check_heterozygosity <- function(indir, name, qcdir=indir, verbose=FALSE,
path2plink=NULL,
keep_individuals=NULL,
remove_individuals=NULL,
exclude_markers=NULL,
extract_markers=NULL,
showPlinkOutput=TRUE) {
prefix <- makepath(indir, name)
out <- makepath(qcdir, name)
checkFormat(prefix)
path2plink <- checkPlink(path2plink)
args_filter <- checkFiltering(keep_individuals, remove_individuals,
extract_markers, exclude_markers)
if (verbose) message("Run check_heterozygosity via plink --het")
sys::exec_wait(path2plink,
args=c("--bfile", prefix, "--het", "--out", out,
args_filter),
std_out=showPlinkOutput, std_err=showPlinkOutput)
}
run_check_missingness <- function(indir, name, qcdir=indir, verbose=FALSE,
path2plink=NULL,
keep_individuals=NULL,
remove_individuals=NULL,
exclude_markers=NULL,
extract_markers=NULL,
showPlinkOutput=TRUE) {
prefix <- makepath(indir, name)
out <- makepath(qcdir, name)
checkFormat(prefix)
path2plink <- checkPlink(path2plink)
args_filter <- checkFiltering(keep_individuals, remove_individuals,
extract_markers, exclude_markers)
if (verbose) message("Run check_missingness via plink --missing")
sys::exec_wait(path2plink,
args=c("--bfile", prefix, "--missing", "--out", out,
args_filter),
std_out=showPlinkOutput, std_err=showPlinkOutput)
}
evaluate_check_het_and_miss <- function(qcdir, name, imissTh=0.03,
hetTh=3, label_fail=TRUE,
highlight_samples = NULL,
highlight_type =
c("text", "label", "color", "shape"),
highlight_text_size = 3,
highlight_color = "
highlight_shape = 17,
legend_text_size = 5,
legend_title_size = 7,
axis_text_size = 5,
axis_title_size = 7,
title_size = 9,
highlight_legend = FALSE,
interactive=FALSE) {
prefix <- makepath(qcdir, name)
if (!file.exists(paste(prefix, ".imiss",sep=""))){
stop("plink --missing output file: ", prefix,
".imiss does not exist.")
}
if (!file.exists(paste(prefix, ".het",sep=""))){
stop("plink --het output file: ", prefix,
".het does not exist.")
}
testNumerics(numbers=c(imissTh, hetTh), positives=c(imissTh, hetTh),
proportions=imissTh)
names_imiss <- c("FID", "IID", "MISS_PHENO", "N_MISS", "N_GENO", "F_MISS")
imiss <- read.table(paste(prefix, ".imiss", sep=""), header=TRUE,
as.is=TRUE)
if (!all(names_imiss == names(imiss))) {
stop("Header of ", prefix, ".imiss is not correct. Was your
file generated with plink --imiss?")
}
fail_imiss <- imiss[imiss$F_MISS > imissTh,]
names_het <- c("FID", "IID", "O.HOM.", "E.HOM.", "N.NM.", "F")
het <- read.table(paste(prefix, ".het", sep=""), header=TRUE, as.is=TRUE)
if (!all(names_het == names(het))) {
stop("Header of ", prefix, ".het is not correct. Was your
file generated with plink --het?")
}
fail_het <- het[het$F < (mean(het$F) - hetTh*sd(het$F)) |
het$F > (mean(het$F) + hetTh*sd(het$F)),]
nr_samples <- nrow(imiss)
imiss$logF_MISS <- log10(imiss$F_MISS)
het_imiss <- merge(imiss, het, by="IID")
fail_het_imiss <- het_imiss[which(het_imiss$IID %in%
union(fail_het$IID, fail_imiss$IID)),]
if (nrow(fail_het_imiss) == 0) {
fail_het_imiss <- NULL
}
het_imiss$type <- "pass"
het_imiss$type[het_imiss$IID %in% fail_het$IID] <- "fail het"
het_imiss$type[het_imiss$IID %in% fail_imiss$IID] <- "fail miss"
het_imiss$type[het_imiss$IID %in%
intersect(fail_het$IID, fail_imiss$IID)] <- "fail het + miss"
minus_sd <- mean(het_imiss$F) - 1:5*(sd(het_imiss$F))
plus_sd <- mean(het_imiss$F) + 1:5*(sd(het_imiss$F))
colors <- c("
names(colors) <- c("pass", "fail het", "fail miss", "fail het + miss" )
het_imiss$shape <- "general"
shape_guide <- FALSE
if(!is.null(highlight_samples)) {
if (!all(highlight_samples %in% het_imiss$IID)) {
stop("Not all samples to be highlighted are present in the",
"prefixMergedDataset")
}
highlight_type <- match.arg(highlight_type, several.ok = TRUE)
if (all(c("text", "label") %in% highlight_type)) {
stop("Only one of text or label highlighting possible; either ",
"can be combined with shape and color highlighting")
}
if ("shape" %in% highlight_type) {
het_imiss$shape[het_imiss$IID %in% highlight_samples] <- "highlight"
shape_guide <- highlight_legend
}
if ("color" %in% highlight_type && highlight_legend) {
het_imiss$type[het_imiss$IID %in% highlight_samples] <- "highlight"
colors <- c(colors, highlight_color)
names(colors)[length(colors)] <- "highlight"
}
}
het_imiss$type <- factor(het_imiss$type, levels=names(colors))
het_imiss$shape <- as.factor(het_imiss$shape)
p_het_imiss <- ggplot()
p_het_imiss <- p_het_imiss + geom_point(data=het_imiss,
aes_string(x='logF_MISS', y='F',
color='type',
shape="shape")) +
scale_shape_manual(values=c(16, highlight_shape), guide="none") +
scale_color_manual(values=colors) +
labs(x = "Proportion of missing SNPs",
y = "heterozygosity rate (and sd)",
color = "Marker",
title = "heterozygosity by Missingness across samples") +
geom_hline(yintercept=c(minus_sd[1:3], plus_sd[1:3]), lty=2,
col="azure4") +
scale_y_continuous(labels=c("-5", "-4", "-3" ,"+3", "+4", "+5"),
breaks=c(minus_sd[3:5], plus_sd[3:5])) +
scale_x_continuous(labels=c(0.0001, 0.001, 0.01, 0.03, 0.05, 0.01, 1),
breaks=c(-4,-3,-2, log10(0.03), log10(0.05),-1,0)) +
geom_hline(yintercept=mean(het_imiss$F) - (hetTh*sd(het_imiss$F)),
col="
geom_hline(yintercept=mean(het_imiss$F) + (hetTh*sd(het_imiss$F)),
col="
geom_vline(xintercept=log10(imissTh), col="
if (!is.null(fail_het_imiss) && label_fail) {
p_het_imiss <-
p_het_imiss + ggrepel::geom_label_repel(
data=data.frame(x=fail_het_imiss$logF_MISS,
y=fail_het_imiss$F,
label=fail_het_imiss$IID),
aes_string(x='x', y='y', label='label'),
size=highlight_text_size)
}
highlight_data <- dplyr::filter(het_imiss, .data$IID %in% highlight_samples)
if (!is.null(highlight_samples)) {
if ("text" %in% highlight_type) {
p_het_imiss <- p_het_imiss +
ggrepel::geom_text_repel(data=highlight_data,
aes_string(x='logF_MISS', y='F',
label="IID"),
size=highlight_text_size)
}
if ("label" %in% highlight_type) {
p_het_imiss <- p_het_imiss +
ggrepel::geom_label_repel(data=highlight_data,
aes_string(x='logF_MISS', y='F',
label="IID"),
size=highlight_text_size)
}
if ("color" %in% highlight_type && !highlight_legend) {
p_het_imiss <- p_het_imiss +
geom_point(data=highlight_data,
aes_string(x='logF_MISS', y='F', shape='shape'),
color=highlight_color,
show.legend=highlight_legend)
}
if ("shape" %in% highlight_type && highlight_legend) {
p_het_imiss <- p_het_imiss +
guides(shape = "legend")
}
}
p_het_imiss <- p_het_imiss +
theme_bw() +
theme(legend.text = element_text(size = legend_text_size),
legend.title = element_text(size = legend_title_size),
axis.text = element_text(size = axis_text_size),
title = element_text(size = title_size),
axis.title = element_text(size = axis_title_size))
if (interactive) print(p_het_imiss)
return(list(fail_imiss=fail_imiss, fail_het=fail_het,
p_het_imiss=p_het_imiss,
plot_data = het_imiss))
}
run_check_relatedness <- function(indir, name, qcdir=indir, highIBDTh=0.185,
mafThRelatedness=0.1,
path2plink=NULL,
filter_high_ldregion=TRUE,
high_ldregion_file=NULL,
genomebuild='hg19',
showPlinkOutput=TRUE,
keep_individuals=NULL,
remove_individuals=NULL,
exclude_markers=NULL,
extract_markers=NULL,
verbose=FALSE) {
prefix <- makepath(indir, name)
out <- makepath(qcdir, name)
checkFormat(prefix)
path2plink <- checkPlink(path2plink)
args_filter <- checkFiltering(keep_individuals, remove_individuals,
extract_markers, exclude_markers)
if (filter_high_ldregion) {
if (!is.null(high_ldregion_file)) {
if (!file.exists(high_ldregion_file)) {
stop("high_ldregion_file (", high_ldregion_file ,
") cannot be read")
}
highld <- data.table::fread(high_ldregion_file, sep=" ",
header=FALSE, data.table=FALSE)
if(ncol(highld) != 4) {
stop("high_ldregion_file (", high_ldregion_file ,
") is incorrectly formated: ",
"contains more/less than 4 columns")
}
if(any(grepl("chr", highld[,1]))) {
stop("high_ldregion_file (", high_ldregion_file ,
") is incorrectly formated: ",
"chromosome specification in first column",
"cannot contain 'chr'")
}
if (verbose) message(paste("Using", high_ldregion_file, "coordinates for pruning of",
"high-ld regions"))
} else {
if (tolower(genomebuild) == 'hg18' || tolower(genomebuild) == 'NCBI36') {
high_ldregion_file <- system.file("extdata", 'high-LD-regions-hg18-NCBI36.txt',
package="plinkQC")
} else if (tolower(genomebuild) == 'hg19' ||
tolower(genomebuild) == 'grch37') {
high_ldregion_file <- system.file("extdata", 'high-LD-regions-hg19-GRCh37.txt',
package="plinkQC")
} else if (tolower(genomebuild) == 'hg38' ||
tolower(genomebuild) == 'grch38') {
high_ldregion_file <- system.file("extdata", 'high-LD-regions-hg38-GRCh38.txt',
package="plinkQC")
} else {
stop(genomebuild, "is not a known/provided human genome build.",
"Options are: hg18, hg19, and hg38")
}
if (verbose) message(paste("Use", genomebuild, "coordinates for pruning of",
"high-ld regions"))
}
if (verbose) message(paste("Prune", prefix, "for relatedness estimation"))
sys::exec_wait(path2plink,
args=c("--bfile", prefix,
"--exclude", "range", high_ldregion_file,
"--indep-pairwise", 50, 5, 0.2,
"--out", out,
args_filter),
std_out=showPlinkOutput, std_err=showPlinkOutput)
} else {
if (verbose) message("No pruning of high-ld regions")
if (verbose) message(paste("Prune", prefix,
"for relatedness estimation"))
sys::exec_wait(path2plink,
args=c("--bfile", prefix,
"--indep-pairwise", 50, 5, 0.2, "--out", out,
args_filter),
std_out=showPlinkOutput, std_err=showPlinkOutput)
}
if (verbose) message("Run check_relatedness via plink --genome")
if (!is.null(mafThRelatedness)) {
maf <- c("--maf", mafThRelatedness)
} else {
maf <- NULL
}
sys::exec_wait(path2plink,
args=c("--bfile", prefix, "--extract",
paste(out, ".prune.in", sep=""),
maf, "--genome",
"--out", out,
args_filter),
std_out=showPlinkOutput, std_err=showPlinkOutput)
if (!file.exists(paste(prefix, ".imiss", sep=""))) {
sys::exec_wait(path2plink,
args=c("--bfile", prefix, "--missing", "--out", out,
args_filter
),
std_out=showPlinkOutput, std_err=showPlinkOutput)
}
}
evaluate_check_relatedness <- function(qcdir, name, highIBDTh=0.1875,
imissTh=0.03, interactive=FALSE,
legend_text_size = 5,
legend_title_size = 7,
axis_text_size = 5,
axis_title_size = 7,
title_size = 9,
verbose=FALSE) {
prefix <- makepath(qcdir, name)
if (!file.exists(paste(prefix, ".imiss", sep=""))){
stop("plink --missing output file: ", prefix,
".imiss does not exist.")
}
if (!file.exists(paste(prefix, ".genome",sep=""))){
stop("plink --genome output file: ", prefix,
".genome does not exist.")
}
testNumerics(numbers=highIBDTh, positives=highIBDTh, proportions=highIBDTh)
names_imiss <- c("FID", "IID", "MISS_PHENO", "N_MISS", "N_GENO", "F_MISS")
imiss <- read.table(paste(prefix, ".imiss", sep=""), header=TRUE,
as.is=TRUE, stringsAsFactors=FALSE)
if (!all(names_imiss == names(imiss))) {
stop("Header of ", prefix, ".imiss is not correct. Was your
file generated with plink --imiss?")
}
names_genome <- c("FID1", "IID1", "FID2", "IID2", "RT", "EZ", "Z0", "Z1",
"Z2", "PI_HAT", "PHE", "DST", "PPC", "RATIO")
genome <- read.table(paste(prefix, ".genome", sep=""), header=TRUE,
as.is=TRUE, stringsAsFactors=FALSE)
if (!all(names_genome == names(genome))) {
stop("Header of ", prefix, ".genome is not correct. Was your
file generated with plink --genome?")
}
fail_highIBD <- relatednessFilter(relatedness=genome, otherCriterion=imiss,
relatednessTh=highIBDTh,
relatednessFID1="FID1",
relatednessFID2="FID2",
otherCriterionTh=imissTh,
otherCriterionThDirection="gt",
otherCriterionMeasure="F_MISS" )
genome$PI_HAT_bin <- ifelse(genome$PI_HAT > 0.05, 0, 1)
p_allPI_HAT <- ggplot(genome, aes_string('PI_HAT'))
p_allPI_HAT <- p_allPI_HAT + geom_histogram(binwidth = 0.005,
fill="
ylab("Number of pairs") +
xlab("Estimated pairwise IBD (PI_HAT)") +
ggtitle("IBD for all sample pairs") +
geom_vline(xintercept=highIBDTh, lty=2, col="
theme_bw() +
theme(legend.text = element_text(size = legend_text_size),
legend.title = element_text(size = legend_title_size),
title = element_text(size = legend_text_size),
axis.text = element_text(size = axis_text_size),
axis.title = element_text(size = axis_title_size))
p_highPI_HAT <- ggplot(dplyr::filter(genome, .data$PI_HAT_bin == 0),
aes_string('PI_HAT'))
p_highPI_HAT <- p_highPI_HAT + geom_histogram(binwidth = 0.005,
fill="
ylab("Number of pairs") +
xlab("Estimated pairwise IBD (PI_HAT)") +
ggtitle("IBD for sample pairs with PI_HAT >0.1") +
geom_vline(xintercept=highIBDTh, lty=2, col="
theme_bw() +
theme(legend.text = element_text(size = legend_text_size),
legend.title = element_text(size = legend_title_size),
title = element_text(size = legend_text_size),
axis.text = element_text(size = axis_text_size),
axis.title = element_text(size = axis_title_size))
p_histo <- cowplot::plot_grid(p_allPI_HAT, p_highPI_HAT)
title <- cowplot::ggdraw() +
cowplot::draw_label("Relatedness estimated as pairwise IBD (PI_HAT)",
size=title_size)
p_IBD <- cowplot::plot_grid(title, p_histo, ncol = 1,
rel_heights = c(0.1, 1))
if (interactive) print(p_IBD)
return(list(fail_highIBD=fail_highIBD$relatednessFails,
failIDs=fail_highIBD$failIDs, p_IBD=p_IBD,
plot_data = genome))
}
run_check_ancestry <- function(indir, prefixMergedDataset,
qcdir=indir,
verbose=FALSE, path2plink=NULL,
keep_individuals=NULL,
remove_individuals=NULL,
exclude_markers=NULL,
extract_markers=NULL,
showPlinkOutput=TRUE) {
prefix <- makepath(indir, prefixMergedDataset)
out <- makepath(qcdir, prefixMergedDataset)
checkFormat(prefix)
path2plink <- checkPlink(path2plink)
args_filter <- checkFiltering(keep_individuals, remove_individuals,
extract_markers, exclude_markers)
if (verbose) message("Run check_ancestry via plink --pca")
sys::exec_wait(path2plink,
args=c("--bfile", prefix, "--pca", "--out", out,
args_filter),
std_out=showPlinkOutput, std_err=showPlinkOutput)
}
evaluate_check_ancestry <- function(indir, name, prefixMergedDataset,
qcdir=indir,
europeanTh=1.5,
defaultRefSamples =
c("HapMap","1000Genomes"),
refSamples=NULL, refColors=NULL,
refSamplesFile=NULL, refColorsFile=NULL,
refSamplesIID="IID", refSamplesPop="Pop",
refColorsColor="Color", refColorsPop="Pop",
studyColor="
refPopulation=c("CEU", "TSI"),
legend_labels_per_row=6,
legend_text_size = 5,
legend_title_size = 7,
axis_text_size = 5,
axis_title_size = 7,
title_size = 9,
highlight_samples = NULL,
highlight_type =
c("text", "label", "color", "shape"),
highlight_text_size = 3,
highlight_color = "
highlight_shape = 17,
highlight_legend = FALSE,
interactive=FALSE,
verbose=FALSE) {
prefix <- makepath(indir, name)
out <- makepath(qcdir, prefixMergedDataset)
if (!file.exists(paste(prefix, ".fam", sep=""))){
stop("plink family file: ", prefix, ".fam does not exist.")
}
samples <- data.table::fread(paste(prefix, ".fam", sep=""),
header=FALSE, stringsAsFactors=FALSE,
data.table=FALSE)[,1:2]
colnames(samples) <- c("FID", "IID")
if (!file.exists(paste(out, ".eigenvec", sep=""))){
stop("plink --pca output file: ", out, ".eigenvec does not exist.")
}
testNumerics(numbers=c(europeanTh, legend_labels_per_row),
positives=c(europeanTh, legend_labels_per_row))
pca_data <- data.table::fread(paste(out, ".eigenvec", sep=""),
stringsAsFactors=FALSE, data.table=FALSE)
colnames(pca_data) <- c("FID", "IID", paste("PC",1:(ncol(pca_data)-2),
sep=""))
if (!any(samples$IID %in% pca_data$IID)) {
stop("There are no ", prefix, ".fam samples in the prefixMergedDataset")
}
if (!all(samples$IID %in% pca_data$IID)) {
stop("Not all ", prefix, ".fam samples are present in the",
"prefixMergedDataset")
}
if (is.null(refSamples) && is.null(refSamplesFile)) {
if (any(!defaultRefSamples %in% c("1000Genomes", "HapMap"))){
stop("defaultRefSamples should be one of 'HapMap' or '1000Genomes'",
" but ", defaultRefSamples," provided")
}
defaultRefSamples <- match.arg(defaultRefSamples)
if (defaultRefSamples == "HapMap") {
refSamplesFile <- system.file("extdata", "HapMap_ID2Pop.txt",
package="plinkQC")
if(is.null(refColorsFile) && is.null(refColors)) {
refColorsFile <- system.file("extdata", "HapMap_PopColors.txt",
package="plinkQC")
}
} else {
refSamplesFile <- system.file("extdata", "Genomes1000_ID2Pop.txt",
package="plinkQC")
if(is.null(refColorsFile) && is.null(refColors)) {
refColorsFile <- system.file("extdata",
"Genomes1000_PopColors.txt",
package="plinkQC")
}
}
if (verbose) {
message("Using ", defaultRefSamples, " as reference samples.")
}
}
if (!is.null(refSamplesFile) && !file.exists(refSamplesFile)) {
stop("refSamplesFile file", refSamplesFile, "does not exist.")
}
if (!is.null(refSamplesFile)) {
refSamples <- read.table(refSamplesFile, header=TRUE,
stringsAsFactors=FALSE)
}
if (!(refSamplesIID %in% names(refSamples))) {
stop(paste("Column", refSamplesIID, "not found in refSamples."))
}
if (!(refSamplesPop %in% names(refSamples))) {
stop(paste("Column", refSamplesPop, "not found in refSamples."))
}
names(refSamples)[names(refSamples) == refSamplesIID] <- "IID"
names(refSamples)[names(refSamples) == refSamplesPop] <- "Pop"
refSamples <- dplyr::select(refSamples, .data$IID, .data$Pop)
refSamples$IID <- as.character(refSamples$IID)
refSamples$Pop <- as.character(refSamples$Pop)
if (!is.null(refColorsFile) && !file.exists(refColorsFile)) {
stop("refColorsFile file", refColorsFile, "does not exist.")
}
if (!is.null(refColorsFile)) {
refColors <- read.table(refColorsFile, header=TRUE,
stringsAsFactors=FALSE)
}
if (!is.null(refColors)) {
if (!(refColorsColor %in% names(refColors))) {
stop(paste("Column", refColorsColor, "not found in refColors."))
}
if (!(refColorsPop %in% names(refColors))) {
stop(paste("Column", refColorsPop, "not found in refColors."))
}
names(refColors)[names(refColors) == refColorsColor] <- "Color"
names(refColors)[names(refColors) == refColorsPop] <- "Pop"
refColors <- dplyr::select(refColors, .data$Pop, .data$Color)
refColors$Color <- as.character(refColors$Color)
refColors$Pop <- as.character(refColors$Pop)
} else {
refColors <- data.frame(Pop=unique(as.character(refSamples$Pop)),
stringsAsFactors=FALSE)
refColors$Color <- 1:nrow(refColors)
}
if (!all(refSamples$Pop %in% refColors$Pop)) {
missing <- refSamples$Pop[!refSamples$Pop %in% refColors$Pop]
stop("Not all refSamples populations found in population code of
refColors; missing population codes: ", paste(missing,
collapse=","))
}
if (!all(refPopulation %in% refColors$Pop)) {
missing <- refPopulation[!refPopulation %in% refColors$Pop]
stop("Not all refPopulation populations found in population code of
refColors; missing population codes: ", paste(missing,
collapse=","))
}
refSamples <- merge(refSamples, refColors, by="Pop", all.X=TRUE)
data_all <- merge(pca_data, refSamples, by="IID", all.x=TRUE)
data_all$Pop[data_all$IID %in% samples$IID] <- name
data_all$Color[data_all$IID %in% samples$IID] <- studyColor
if (any(is.na(data_all))) {
stop("There are samples in the prefixMergedDataset that cannot be found
in refSamples or ", prefix, ".fam")
}
colors <- dplyr::select(data_all, .data$Pop, .data$Color)
colors <- colors[!duplicated(colors$Pop),]
colors <- colors[order(colors$Color),]
all_european <- dplyr::filter(data_all, .data$Pop %in% refPopulation)
euro_pc1_mean <- mean(all_european$PC1)
euro_pc2_mean <- mean(all_european$PC2)
all_european$euclid_dist <- sqrt((all_european$PC1 - euro_pc1_mean)^2 +
(all_european$PC2 - euro_pc2_mean)^2)
max_euclid_dist <- max(all_european$euclid_dist)
data_name <- dplyr::filter(data_all, .data$Pop == name)
data_name$euclid_dist <- sqrt((data_name$PC1 - euro_pc1_mean)^2 +
(data_name$PC2 - euro_pc2_mean)^2)
non_europeans <- dplyr::filter(data_name, .data$euclid_dist >
(max_euclid_dist * europeanTh))
fail_ancestry <- dplyr::select(non_europeans, .data$FID, .data$IID)
legend_rows <- round(nrow(colors)/legend_labels_per_row)
data_all$shape <- "general"
shape_guide <- FALSE
if(!is.null(highlight_samples)) {
if (!all(highlight_samples %in% pca_data$IID)) {
stop("Not all samples to be highlighted are present in the",
"prefixMergedDataset")
}
highlight_type <- match.arg(highlight_type, several.ok = TRUE)
if (all(c("text", "label") %in% highlight_type)) {
stop("Only one of text or label highlighting possible; either ",
"can be combined with shape and color highlighting")
}
if ("shape" %in% highlight_type) {
data_all$shape[data_all$IID %in% highlight_samples] <- "highlight"
shape_guide <- highlight_legend
}
if ("color" %in% highlight_type && highlight_legend) {
data_all$Pop[data_all$IID %in% highlight_samples] <- "highlight"
colors <- rbind(colors, c("highlight", highlight_color))
}
}
colors$Pop <- factor(colors$Pop, levels=unique(colors$Pop))
data_all$Pop <- factor(data_all$Pop, levels=levels(colors$Pop))
p_ancestry <- ggplot()
p_ancestry <- p_ancestry +
geom_point(data=data_all,
aes_string(x='PC1', y='PC2', color='Pop', shape="shape")) +
geom_point(data=dplyr::filter(data_all, .data$Pop != name),
aes_string(x='PC1', y='PC2', color='Pop', shape="shape"),
size=1) +
scale_color_manual(values=colors$Color,
name="Population") +
scale_shape_manual(values=c(16, highlight_shape), guide="none") +
guides(color=guide_legend(nrow=legend_rows, byrow=TRUE)) +
ggforce::geom_circle(aes(x0=euro_pc1_mean, y0=euro_pc2_mean,
r=(max_euclid_dist * europeanTh))) +
ggtitle("PCA on combined reference and study genotypes") +
theme_bw() +
theme(legend.position='bottom',
legend.direction = 'vertical',
legend.box = "vertical",
legend.text = element_text(size = legend_text_size),
legend.title = element_text(size = legend_title_size),
title = element_text(size = title_size),
axis.text = element_text(size = axis_text_size),
axis.title = element_text(size = axis_title_size))
if (!is.null(highlight_samples)) {
highlight_data <- dplyr::filter(data_all, .data$IID %in% highlight_samples)
if ("text" %in% highlight_type) {
p_ancestry <- p_ancestry +
ggrepel::geom_text_repel(data=highlight_data,
aes_string(x='PC1', y='PC2',
label="IID"),
size=highlight_text_size)
}
if ("label" %in% highlight_type) {
p_ancestry <- p_ancestry +
ggrepel::geom_label_repel(data=highlight_data,
aes_string(x='PC1', y='PC2',
label="IID"),
size=highlight_text_size)
}
if ("color" %in% highlight_type && !highlight_legend) {
p_ancestry <- p_ancestry +
geom_point(data=highlight_data,
aes_string(x='PC1', y='PC2', shape='shape'),
color=highlight_color,
show.legend=highlight_legend)
}
if ("shape" %in% highlight_type && highlight_legend) {
p_ancestry <- p_ancestry +
labs(shape = "Individual") +
guides(shape = "legend")
}
}
if (interactive) print(p_ancestry)
return(list(fail_ancestry=fail_ancestry, p_ancestry=p_ancestry,
plot_data=data_all))
}
|
test_that("known corner cases are correct", {
truth <- factor("a", levels = c("a", "b"))
estimate <- .9
df <- data.frame(truth, estimate)
expect_equal(
average_precision(df, truth, estimate)$.estimate,
1
)
expect_equal(
average_precision(df, truth, estimate)$.estimate,
pr_auc(df, truth, estimate)$.estimate
)
truth <- factor("b", levels = c("a", "b"))
estimate <- .9
df <- data.frame(truth, estimate)
expect_snapshot(out <- average_precision(df, truth, estimate)$.estimate)
expect_identical(out, NA_real_)
expect_snapshot(out <- average_precision(df, truth, estimate)$.estimate)
expect_snapshot(expect <- pr_auc(df, truth, estimate)$.estimate)
expect_identical(out, expect)
})
test_that("`event_level = 'second'` works", {
df <- two_class_example
df_rev <- df
df_rev$truth <- relevel(df_rev$truth, "Class2")
expect_equal(
average_precision_vec(df$truth, df$Class1),
average_precision_vec(df_rev$truth, df_rev$Class1, event_level = "second")
)
})
|
context("5-parameter logistic - core functions")
test_that("Constructor", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
)
n <- length(y)
w <- rep(1, n)
max_iter <- 10000
stats <- matrix(
c(
-6.908, -4.605, -2.303, 0, 2.303, 4.605, 6.908, 3, 2, 2, 5, 3, 4, 1,
0.932, 0.902, 0.89, 0.5542, 0.2556666667, 0.16425, 0.092, 0.0014186667,
0.002116, 0.000049, 0.00160656, 0.0000862222, 0.0014676875, 0
),
nrow = 7,
ncol = 4
)
colnames(stats) <- c("x", "n", "m", "v")
start <- c(0, 1, -1, 0, 1)
lower_bound <- c(0, -1, -Inf, -10, 0)
upper_bound <- c(3, 2, 0, 5, 2)
object <- logistic5_new(x, y, w, NULL, max_iter, NULL, NULL)
expect_true(inherits(object, "logistic5"))
expect_equal(object$x, x)
expect_equal(object$y, y)
expect_equal(object$w, w)
expect_equal(object$n, n)
expect_equal(object$m, 7)
expect_equal(object$stats, stats)
expect_false(object$constrained)
expect_equal(object$max_iter, max_iter)
expect_null(object$start)
expect_null(object$lower_bound)
expect_null(object$upper_bound)
object <- logistic5_new(x, y, w, start, max_iter, lower_bound, upper_bound)
expect_true(inherits(object, "logistic5"))
expect_equal(object$x, x)
expect_equal(object$y, y)
expect_equal(object$w, w)
expect_equal(object$n, n)
expect_equal(object$m, 7)
expect_equal(object$stats, stats)
expect_true(object$constrained)
expect_equal(object$max_iter, max_iter)
expect_equal(object$start, c(0, 1, -1, 0, 0))
expect_equal(object$lower_bound, c(0, 0, -Inf, -10, -Inf))
expect_equal(object$upper_bound, c(2, 2, 0, 5, log(2)))
w <- c(
1.46, 1.385, 1.704, 0.96, 0, 0.055, 1.071, 0.134, 1.825, 0, 1.169, 0.628,
0.327, 1.201, 0.269, 0, 1.294, 0.038, 1.278, 0.157
)
stats <- matrix(
c(
-6.908, -4.605, -2.303, 0.0, 2.303, 4.605, 6.908, 4.549, 0.96, 1.126,
3.756, 1.797, 2.61, 0.157, 0.9353000659, 0.948, 0.8836838366, 0.55221459,
0.2606149137, 0.1807233716, 0.092, 0.0014467345, 0, 0.0000091061,
0.0007707846, 0.0000597738, 0.0014230308, 0
),
nrow = 7,
ncol = 4
)
colnames(stats) <- c("x", "n", "m", "v")
object <- logistic5_new(x, y, w, NULL, max_iter, NULL, NULL)
expect_true(inherits(object, "logistic5"))
expect_equal(object$x, x)
expect_equal(object$y, y)
expect_equal(object$w, w)
expect_equal(object$n, n)
expect_equal(object$m, 7)
expect_equal(object$stats, stats)
expect_false(object$constrained)
expect_equal(object$max_iter, max_iter)
expect_null(object$start)
expect_null(object$lower_bound)
expect_null(object$upper_bound)
object <- logistic5_new(x, y, w, start, max_iter, lower_bound, upper_bound)
expect_true(inherits(object, "logistic5"))
expect_equal(object$x, x)
expect_equal(object$y, y)
expect_equal(object$w, w)
expect_equal(object$n, n)
expect_equal(object$m, 7)
expect_equal(object$stats, stats)
expect_true(object$constrained)
expect_equal(object$max_iter, max_iter)
expect_equal(object$start, c(0, 1, -1, 0, 0))
expect_equal(object$lower_bound, c(0, 0, -Inf, -10, -Inf))
expect_equal(object$upper_bound, c(2, 2, 0, 5, log(2)))
})
test_that("Constructor: errors", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
)
w <- c(
1.46, 1.385, 1.704, 0.96, 0, 0.055, 1.071, 0.134, 1.825, 0, 1.169, 0.628,
0.327, 1.201, 0.269, 0, 1.294, 0.038, 1.278, 0.157
)
max_iter <- 10000
expect_error(
logistic5_new(x, y, w, c(0, 1, -1, 0), max_iter, NULL, NULL),
"'start' must be of length 5"
)
expect_error(
logistic5_new(x, y, w, c(0, -1, -1, 0, 1), max_iter, NULL, NULL),
"parameter 'beta' cannot be smaller than 'alpha'"
)
expect_error(
logistic5_new(x, y, w, c(0, 0, -1, 0, 1), max_iter, NULL, NULL),
"parameter 'beta' cannot be smaller than 'alpha'"
)
expect_error(
logistic5_new(x, y, w, c(0, 1, 0, 0, 1), max_iter, NULL, NULL),
"parameter 'eta' cannot be initialized to zero"
)
expect_error(
logistic5_new(x, y, w, c(0, 1, -1, 0, 0), max_iter, NULL, NULL),
"parameter 'nu' cannot be negative nor zero"
)
expect_error(
logistic5_new(x, y, w, c(0, 1, -1, 0, -1), max_iter, NULL, NULL),
"parameter 'nu' cannot be negative nor zero"
)
expect_error(
logistic5_new(x, y, w, NULL, max_iter, rep(-Inf, 4), rep(Inf, 4)),
"'lower_bound' must be of length 5"
)
expect_error(
logistic5_new(x, y, w, NULL, max_iter, rep(-Inf, 4), rep(Inf, 5)),
"'lower_bound' must be of length 5"
)
expect_error(
logistic5_new(x, y, w, NULL, max_iter, rep(-Inf, 5), rep(Inf, 4)),
"'upper_bound' must be of length 5"
)
expect_error(
logistic5_new(x, y, w, NULL, max_iter, rep(-Inf, 5), c(1, rep(Inf, 3), 0)),
"'upper_bound[5]' cannot be negative nor zero",
fixed = TRUE
)
expect_error(
logistic5_new(x, y, w, NULL, max_iter, rep(-Inf, 5), c(1, rep(Inf, 3), -1)),
"'upper_bound[5]' cannot be negative nor zero",
fixed = TRUE
)
})
test_that("Function value", {
x <- -log(c(1000, 100, 10, 1, 0.1, 0.01))
theta <- c(4 / 100, 9 / 10, -2, -3 / 2, 1 / 2)
true_value <- c(
0.89998272669845415, 0.89827524246036657, 0.75019144346736942,
0.047052490645792413, 0.040000850995162837, 0.040000000085267377
)
value <- logistic5_fn(x, theta)
expect_type(value, "double")
expect_length(value, 6)
expect_equal(value, true_value)
object <- structure(
list(stats = matrix(x, nrow = 6, ncol = 1)),
class = "logistic5"
)
value <- fn(object, object$stats[, 1], theta)
expect_type(value, "double")
expect_length(value, 6)
expect_equal(value, true_value)
object <- structure(
list(stats = matrix(x, nrow = 6, ncol = 1)),
class = "logistic5_fit"
)
value <- fn(object, object$stats[, 1], theta)
expect_type(value, "double")
expect_length(value, 6)
expect_equal(value, true_value)
})
test_that("Gradient and Hessian", {
x <- -log(c(1000, 100, 10, 1, 0.1, 0.01))
theta <- c(4 / 100, 9 / 10, -2, -3 / 2, 1 / 2)
true_gradient <- matrix(
c(
0.000020085234355644039, 0.0020055320228295701, 0.17419599596817509,
0.99179942948163673, 0.99999901047074089, 0.99999999990085189,
0.99997991476564436, 0.99799446797717043, 0.82580400403182491,
0.0082005705183632714, 9.8952925911240417e-07, 9.9148112539280778e-11,
-0.000093408380497224582, -0.0053476072761497761, -0.10403715378083063,
0.019241514719677547, 6.4655250500714644e-06, 1.0411333261602936e-09,
0.000034546082682501184, 0.0034443247589330582, 0.25925513615688965,
0.025655352959570063, 3.4005945386908866e-06, 3.4106611099876862e-10,
8.6734287058557399e-11, 8.6447455933317324e-7, 0.0063015237621949961,
0.021049325905316226, 0.000010065592915696157, 1.7935503452654302e-09
),
nrow = 6,
ncol = 5
)
true_hessian <- array(
c(
rep(0, 6),
rep(0, 6),
0.00010861439592700533, 0.0062181479955229955, 0.12097343462887282,
-0.022373854325206450, -7.5180523838040284e-06, -1.2106201466980158e-09,
-0.000040169863584303702, -0.0040050287894570444, -0.30145946064754610,
-0.029831805766941934, -3.9541796961521937e-06, -3.9658850116135887e-10,
-1.0085382216111325e-10, -1.0052029759688061e-06, -0.0073273532118546466,
-0.024475960355018867, -0.000011704177808949019, -2.0855236572853840e-09,
rep(0, 6),
rep(0, 6),
-0.00010861439592700533, -0.0062181479955229955, -0.12097343462887282,
0.022373854325206450, 7.5180523838040284e-06, 1.2106201466980158e-09,
0.000040169863584303702, 0.0040050287894570444, 0.30145946064754610,
0.029831805766941934, 3.9541796961521937e-06, 3.9658850116135887e-10,
1.0085382216111325e-10, 1.0052029759688061e-06, 0.0073273532118546466,
0.024475960355018867, 0.000011704177808949019, 2.0855236572853840e-09,
0.00010861439592700533, 0.0062181479955229955, 0.12097343462887282,
-0.022373854325206450, -7.5180523838040284e-06, -1.2106201466980158e-09,
-0.00010861439592700533, -0.0062181479955229955, -0.12097343462887282,
0.022373854325206450, 7.5180523838040284e-06, 1.2106201466980158e-09,
-0.00050511444418713689, -0.016555252126485643, -0.060637799043344759,
0.049883501712141417, 0.000049098048382061985, 1.2712402410105175e-08,
0.00016953809123729721, 0.0089408616320290739, 0.021478649997785072,
0.053683659136403524, 0.000024123213411596926, 3.9939380477898473e-09,
9.3805989611171948e-10, 5.3597039009804577e-06, 0.0085715606355158565,
0.039930425361417561, 0.000070015304961175913, 2.0858519166902048e-08,
-0.000040169863584303702, -0.0040050287894570444, -0.30145946064754610,
-0.029831805766941934, -3.9541796961521937e-06, -3.9658850116135887e-10,
0.000040169863584303702, 0.0040050287894570444, 0.30145946064754610,
0.029831805766941934, 3.9541796961521937e-06, 3.9658850116135887e-10,
0.00016953809123729721, 0.0089408616320290739, 0.021478649997785072,
0.053683659136403524, 0.000024123213411596926, 3.9939380477898473e-09,
-0.000069090083756049672, -0.0068679160064153061, -0.37654877818008748,
0.088681780821584741, 0.000013582081688859556, 1.3642440673798294e-09,
-3.4693134127485286e-10, -3.4521160387059138e-06, -0.021359879993633144,
0.053240567148556747, 0.000036825108839864453, 6.8330672303858801e-09,
-1.0085382216111325e-10, -1.0052029759688061e-06, -0.0073273532118546466,
-0.024475960355018867, -0.000011704177808949019, -2.0855236572853840e-09,
1.0085382216111325e-10, 1.0052029759688061e-06, 0.0073273532118546466,
0.024475960355018867, 0.000011704177808949019, 2.0855236572853840e-09,
9.3805989611171948e-10, 5.3597039009804577e-06, 0.0085715606355158565,
0.039930425361417561, 0.000070015304961175913, 2.0858519166902048e-08,
-3.4693134127485286e-10, -3.4521160387059138e-06, -0.021359879993633144,
0.053240567148556747, 0.000036825108839864453, 6.8330672303858801e-09,
8.6733125674846536e-11, 8.6331893228632990e-07, 0.0055845141256710526,
0.053441912635589904, 0.00011068910773858665, 3.6103283407515775e-08
),
dim = c(6, 5, 5)
)
object <- structure(
list(stats = matrix(x, nrow = 6, ncol = 1)),
class = "logistic5"
)
gradient_hessian <- gradient_hessian(object, theta)
expect_type(gradient_hessian, "list")
expect_type(gradient_hessian$G, "double")
expect_type(gradient_hessian$H, "double")
expect_length(gradient_hessian$G, 6 * 5)
expect_length(gradient_hessian$H, 6 * 5 * 5)
expect_equal(gradient_hessian$G, true_gradient)
expect_equal(gradient_hessian$H, true_hessian)
})
context("5-parameter logistic - RSS functions")
test_that("Value of the RSS", {
x <- -log(c(1000, 100, 10, 1, 0.1))
n <- c(3, 3, 2, 4, 3)
m <- c(376 / 375, 3091 / 3750, 8989 / 10000, 1447 / 10000, 11 / 120)
v <- c(
643663 / 450000000, 31087 / 112500000, 961 / 160000,
177363 / 25000000, 560629 / 112500000
)
theta <- c(4 / 100, 9 / 10, -2, -3 / 2, -log(2))
true_value <- 0.13844046588658472
object <- structure(
list(stats = cbind(x, n, m, v), m = 5),
class = "logistic5"
)
rss_fn <- rss(object)
expect_type(rss_fn, "closure")
value <- rss_fn(theta)
expect_type(value, "double")
expect_length(value, 1)
expect_equal(value, true_value)
known_param <- c(4 / 100, NA, NA, -3 / 2, -log(2))
rss_fn <- rss_fixed(object, known_param)
expect_type(rss_fn, "closure")
value <- rss_fn(c(9 / 10, -2))
expect_type(value, "double")
expect_length(value, 1)
expect_equal(value, true_value)
})
test_that("Gradient and Hessian of the RSS", {
x <- -log(c(1000, 100, 10, 1, 0.1))
n <- c(3, 3, 2, 4, 3)
m <- c(376 / 375, 3091 / 3750, 8989 / 10000, 1447 / 10000, 11 / 120)
v <- c(
643663 / 450000000, 31087 / 112500000, 961 / 160000,
177363 / 25000000, 560629 / 112500000
)
theta <- c(4 / 100, 9 / 10, -2, -3 / 2, -log(2))
true_gradient <- c(
-0.59375404772645021, -0.33527664229369063, 0.022267352061200450,
-0.086374079772717690, -0.010097206230551137
)
true_hessian <- matrix(
c(
6.9953590538168059, 0.32630453922986950, 0.014184128740313277,
0.29256817446506200, 0.097473377538659030,
0.32630453922986950, 7.3520318677234551, -0.16159602781805513,
0.33901032399546030, -0.00064023593037618698,
0.014184128740313277, -0.16159602781805513, 0.018237239090142242,
-0.077452292586773564, -0.017846532854813774,
0.29256817446506200, 0.33901032399546030, -0.077452292586773564,
0.21294298805991181, -0.0090213900412146364,
0.097473377538659030, -0.00064023593037618698, -0.017846532854813774,
-0.0090213900412146364, -0.020700058407993170
),
nrow = 5,
ncol = 5
)
object <- structure(
list(stats = cbind(x, n, m, v), m = 5),
class = "logistic5"
)
rss_gh <- rss_gradient_hessian(object)
expect_type(rss_gh, "closure")
gradient_hessian <- rss_gh(theta)
expect_type(gradient_hessian$G, "double")
expect_type(gradient_hessian$H, "double")
expect_length(gradient_hessian$G, 5)
expect_length(gradient_hessian$H, 5 * 5)
expect_equal(gradient_hessian$G, true_gradient)
expect_equal(gradient_hessian$H, true_hessian)
known_param <- c(4 / 100, NA, NA, -3 / 2, -log(2))
rss_gh <- rss_gradient_hessian_fixed(object, known_param)
expect_type(rss_gh, "closure")
gradient_hessian <- rss_gh(c(9 / 10, -2))
expect_type(gradient_hessian$G, "double")
expect_type(gradient_hessian$H, "double")
expect_length(gradient_hessian$G, 2)
expect_length(gradient_hessian$H, 2 * 2)
expect_equal(gradient_hessian$G, true_gradient[2:3])
expect_equal(gradient_hessian$H, true_hessian[2:3, 2:3])
})
context("5-parameter logistic - support functions")
test_that("mle_asy", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
)
n <- length(y)
w <- rep(1, n)
theta <- c(
0, 1, -1.7617462932355768, -0.47836972294568214, 1.3765334489390748
)
true_value <- c(
0.093212121358460102, 0.92029387542791528, -1.7617462932355768,
-0.47836972294568214, 1.3765334489390748
)
object <- logistic5_new(x, y, w, NULL, 10000, NULL, NULL)
result <- mle_asy(object, theta)
expect_type(result, "double")
expect_length(result, 5)
expect_equal(result, true_value)
})
context("5-parameter logistic - fit")
test_that("fit", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
)
n <- length(y)
w <- rep(1, n)
estimated <- c(alpha = TRUE, beta = TRUE, eta = TRUE, phi = TRUE, nu = TRUE)
theta <- c(
alpha = 0.093212121358460102,
beta = 0.92029387542791528,
eta = -1.7617462932355768,
phi = -0.47836972294568214,
nu = 3.96114628361664067
)
rss_value <- 0.024883087882351184
fitted_values <- c(
rep(0.9202839186685335, 3), rep(0.9197191693822362, 2),
rep(0.8900274208207810, 2), rep(0.5533792934125556, 5),
rep(0.26271803120343568, 3), rep(0.15412982230606348, 4),
0.11508521369102612
)
residuals <- c(
0.0077160813314665, -0.0322839186685335, 0.0597160813314665,
0.0282808306177638, -0.0637191693822362, 0.0069725791792190,
-0.0070274208207810, -0.0653792934125556, -0.0213792934125556,
0.0326207065874444, 0.0126207065874444, 0.0456207065874444,
-0.00371803120343568, 0.00228196879656432, -0.01971803120343568,
-0.03712982230606348, -0.01112982230606348, 0.02387017769393652,
0.06487017769393652, -0.02308521369102612
)
object <- logistic5_new(x, y, w, NULL, 10000, NULL, NULL)
result <- fit(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_false(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, object$n - 5)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(x, y, w, c(0, 1, -1, 0, 1), 10000, NULL, NULL)
result <- fit(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_false(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, object$n - 5)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
})
test_that("fit_constrained: inequalities", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
)
n <- length(y)
w <- rep(1, n)
estimated <- c(alpha = TRUE, beta = TRUE, eta = TRUE, phi = TRUE, nu = TRUE)
theta <- c(
alpha = 0.093212121358460102,
beta = 0.92029387542791528,
eta = -1.7617462932355768,
phi = -0.47836972294568214,
nu = 3.96114628361664067
)
rss_value <- 0.024883087882351184
fitted_values <- c(
rep(0.9202839186685335, 3), rep(0.9197191693822362, 2),
rep(0.8900274208207810, 2), rep(0.5533792934125556, 5),
rep(0.26271803120343568, 3), rep(0.15412982230606348, 4),
0.11508521369102612
)
residuals <- c(
0.0077160813314665, -0.0322839186685335, 0.0597160813314665,
0.0282808306177638, -0.0637191693822362, 0.0069725791792190,
-0.0070274208207810, -0.0653792934125556, -0.0213792934125556,
0.0326207065874444, 0.0126207065874444, 0.0456207065874444,
-0.00371803120343568, 0.00228196879656432, -0.01971803120343568,
-0.03712982230606348, -0.01112982230606348, 0.02387017769393652,
0.06487017769393652, -0.02308521369102612
)
object <- logistic5_new(
x, y, w, NULL, 10000,
c(-0.5, 0.9, -2, -1, 0.5), c(0.5, 1.5, 0, 1, 5)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_true(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-6)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, object$n - 5)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(
x, y, w, c(-0.1, 1.2, -1.3, 0.3, 2), 10000,
c(-0.5, 0.9, -2, -1, 0.5), c(0.5, 1.5, 0, 1, 5)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_true(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-6)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, object$n - 5)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(
x, y, w, c(-1, 2, 1, -2, 0.1), 10000,
c(-0.5, 0.9, -2, -1, 0.5), c(0.5, 1.5, 0, 1, 5)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_true(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-6)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, object$n - 5)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
})
test_that("fit_constrained: equalities", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
)
n <- length(y)
w <- rep(1, n)
estimated <- c(
alpha = FALSE, beta = FALSE, eta = TRUE, phi = TRUE, nu = TRUE
)
theta <- c(
alpha = 0,
beta = 1,
eta = -0.75885255907605610,
phi = -0.30897155961772727,
nu = 2.34190488025700727
)
rss_value <- 0.053861132351488352
fitted_values <- c(
rep(0.993387436096706232, 3), rep(0.96390948874813840, 2),
rep(0.83729075842125321, 2), rep(0.55558345438725121, 5),
rep(0.29108572543250870, 3), rep(0.14085756611083843, 4),
0.06702715257129726
)
residuals <- c(
-0.065387436096706232, -0.105387436096706232, -0.013387436096706232,
-0.01590948874813840, -0.10790948874813840, 0.05970924157874679,
0.04570924157874679, -0.06758345438725121, -0.02358345438725121,
0.03041654561274879, 0.01041654561274879, 0.04341654561274879,
-0.03208572543250870, -0.02608572543250870, -0.04808572543250870,
-0.02385756611083843, 0.00214243388916157, 0.03714243388916157,
0.07814243388916157, 0.02497284742870274
)
object <- logistic5_new(
x, y, w, NULL, 10000, c(0, 1, -Inf, -Inf, -Inf), c(0, 1, Inf, Inf, Inf)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_false(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, object$n - 3)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(
x, y, w, c(0, 1, -1, 0, 1), 10000,
c(0, 1, -Inf, -Inf, -Inf), c(0, 1, Inf, Inf, Inf)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_false(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, object$n - 3)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(
x, y, w, c(1, 3, -1, 0, 1), 10000,
c(0, 1, -Inf, -Inf, -Inf), c(0, 1, Inf, Inf, Inf)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_false(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, object$n - 3)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
})
test_that("fit_constrained: equalities and inequalities", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
)
n <- length(y)
w <- rep(1, n)
estimated <- c(
alpha = FALSE, beta = FALSE, eta = TRUE, phi = TRUE, nu = TRUE
)
theta <- c(
alpha = 0,
beta = 1,
eta = -0.75885255907605610,
phi = -0.30897155961772727,
nu = 2.34190488025700727
)
rss_value <- 0.053861132351488352
fitted_values <- c(
rep(0.993387436096706232, 3), rep(0.96390948874813840, 2),
rep(0.83729075842125321, 2), rep(0.55558345438725121, 5),
rep(0.29108572543250870, 3), rep(0.14085756611083843, 4),
0.06702715257129726
)
residuals <- c(
-0.065387436096706232, -0.105387436096706232, -0.013387436096706232,
-0.01590948874813840, -0.10790948874813840, 0.05970924157874679,
0.04570924157874679, -0.06758345438725121, -0.02358345438725121,
0.03041654561274879, 0.01041654561274879, 0.04341654561274879,
-0.03208572543250870, -0.02608572543250870, -0.04808572543250870,
-0.02385756611083843, 0.00214243388916157, 0.03714243388916157,
0.07814243388916157, 0.02497284742870274
)
object <- logistic5_new(
x, y, w, NULL, 10000, c(0, 1, -2, -2, 1), c(0, 1, 0, 2, 3)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_true(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-7)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, object$n - 3)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(
x, y, w, c(0, 1, -1.2, -0.3, 2), 10000,
c(0, 1, -2, -2, 1), c(0, 1, 0, 2, 3)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_true(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-7)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, object$n - 3)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(
x, y, w, c(-1, 2, 1, 3, 5), 10000,
c(0, 1, -2, -2, 1), c(0, 1, 0, 2, 3)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_true(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-7)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, object$n - 3)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
})
context("5-parameter logistic - weighted fit")
test_that("fit (weighted)", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 1, 2, 4, 3, 3, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.897, 0.883, 0.488, 0.532, 0.566, 0.599, 0.259,
0.265, 0.243, 0.143, 0.178, 0.219, 0.092
)
w <- c(
1.46, 1.385, 1.704, 0.96, 0.055, 1.071, 0.134, 1.825, 1.169, 0.628, 0.327,
1.201, 0.269, 1.294, 0.038, 1.278, 0.157
)
estimated <- c(alpha = TRUE, beta = TRUE, eta = TRUE, phi = TRUE, nu = TRUE)
theta <- c(
alpha = 0.14021510699415424,
beta = 0.93769951379161088,
eta = -1.3532016035342649,
phi = -0.36746911119363776,
nu = 2.43088291720838878
)
rss_value <- 0.014141550871844299
fitted_values <- c(
rep(0.9375852722593340, 3), rep(0.9351351725701264, 1),
rep(0.8859559720192794, 2), rep(0.5516453155354000, 4),
rep(0.26479534106274689, 3), rep(0.17495286982311317, 3),
0.14985594300774278
)
residuals <- c(
-0.0095852722593340, -0.0495852722593340, 0.0424147277406660,
0.0128648274298736, 0.0110440279807206, -0.0029559720192794,
-0.0636453155354000, -0.0196453155354000, 0.0143546844646000,
0.0473546844646000, -0.00579534106274689, 0.00020465893725311,
-0.02179534106274689, -0.03195286982311317, 0.00304713017688683,
0.04404713017688683, -0.05785594300774278
)
object <- logistic5_new(x, y, w, NULL, 10000, NULL, NULL)
result <- fit(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_false(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-6)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, length(y) - 5)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(x, y, w, c(0, 1, -1, 0, 1), 10000, NULL, NULL)
result <- fit(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_false(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-6)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, length(y) - 5)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
})
test_that("fit_constrained (weighted): inequalities", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 1, 2, 4, 3, 3, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.897, 0.883, 0.488, 0.532, 0.566, 0.599, 0.259,
0.265, 0.243, 0.143, 0.178, 0.219, 0.092
)
w <- c(
1.46, 1.385, 1.704, 0.96, 0.055, 1.071, 0.134, 1.825, 1.169, 0.628, 0.327,
1.201, 0.269, 1.294, 0.038, 1.278, 0.157
)
estimated <- c(alpha = TRUE, beta = TRUE, eta = TRUE, phi = TRUE, nu = TRUE)
theta <- c(
alpha = 0.14021510699415424,
beta = 0.93769951379161088,
eta = -1.3532016035342649,
phi = -0.36746911119363776,
nu = 2.43088291720838878
)
rss_value <- 0.014141550871844299
fitted_values <- c(
rep(0.9375852722593340, 3), rep(0.9351351725701264, 1),
rep(0.8859559720192794, 2), rep(0.5516453155354000, 4),
rep(0.26479534106274689, 3), rep(0.17495286982311317, 3),
0.14985594300774278
)
residuals <- c(
-0.0095852722593340, -0.0495852722593340, 0.0424147277406660,
0.0128648274298736, 0.0110440279807206, -0.0029559720192794,
-0.0636453155354000, -0.0196453155354000, 0.0143546844646000,
0.0473546844646000, -0.00579534106274689, 0.00020465893725311,
-0.02179534106274689, -0.03195286982311317, 0.00304713017688683,
0.04404713017688683, -0.05785594300774278
)
object <- logistic5_new(
x, y, w, NULL, 10000, c(-0.5, 0.9, -2, -1, 0.5), c(0.5, 1.5, 0, 1, 5)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_true(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-6)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, length(y) - 5)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(
x, y, w, c(0.1, 1.2, -0.5, 0.5, 2), 10000,
c(-0.5, 0.9, -2, -1, 0.5), c(0.5, 1.5, 0, 1, 5)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_true(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-6)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, length(y) - 5)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(
x, y, w, c(2, 3, -3, 2, 6), 10000,
c(-0.5, 0.9, -2, -1, 0.5), c(0.5, 1.5, 0, 1, 5)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_true(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-6)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, length(y) - 5)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
})
test_that("fit_constrained (weighted): equalities", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 1, 2, 4, 3, 3, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.897, 0.883, 0.488, 0.532, 0.566, 0.599, 0.259,
0.265, 0.243, 0.143, 0.178, 0.219, 0.092
)
w <- c(
1.46, 1.385, 1.704, 0.96, 0.055, 1.071, 0.134, 1.825, 1.169, 0.628, 0.327,
1.201, 0.269, 1.294, 0.038, 1.278, 0.157
)
estimated <- c(
alpha = FALSE, beta = FALSE, eta = TRUE, phi = TRUE, nu = TRUE
)
theta <- c(
alpha = 0,
beta = 1,
eta = -0.72502089617011087,
phi = -0.33982624766042181,
nu = 2.36465699101360594
)
rss_value <- 0.036717820758155562
fitted_values <- c(
rep(0.991572996129829225, 3), rep(0.95779593343449193, 1),
rep(0.82640795793649317, 2), rep(0.55492427795777899, 4),
rep(0.30125409492277104, 3), rep(0.15182795902080912, 3),
0.07523599271751825
)
residuals <- c(
-0.063572996129829225, -0.103572996129829225, -0.011572996129829225,
-0.00979593343449193, 0.07059204206350683, 0.05659204206350683,
-0.06692427795777899, -0.02292427795777899, 0.01107572204222101,
0.04407572204222101, -0.04225409492277104, -0.03625409492277104,
-0.05825409492277104, -0.00882795902080912, 0.02617204097919088,
0.06717204097919088, 0.01676400728248175
)
object <- logistic5_new(
x, y, w, NULL, 10000, c(0, 1, rep(-Inf, 3)), c(0, 1, rep(Inf, 3))
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_false(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, length(y) - 3)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(
x, y, w, c(0, 1, -1, 0, 1), 10000,
c(0, 1, rep(-Inf, 3)), c(0, 1, rep(Inf, 3))
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_false(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, length(y) - 3)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(
x, y, w, c(1, 2, -1, 0, 1), 10000,
c(0, 1, rep(-Inf, 3)), c(0, 1, rep(Inf, 3))
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_false(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, length(y) - 3)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
})
test_that("fit_constrained (weighted): equalities and inequalities", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 1, 2, 4, 3, 3, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.897, 0.883, 0.488, 0.532, 0.566, 0.599, 0.259,
0.265, 0.243, 0.143, 0.178, 0.219, 0.092
)
w <- c(
1.46, 1.385, 1.704, 0.96, 0.055, 1.071, 0.134, 1.825, 1.169, 0.628, 0.327,
1.201, 0.269, 1.294, 0.038, 1.278, 0.157
)
estimated <- c(
alpha = FALSE, beta = FALSE, eta = TRUE, phi = TRUE, nu = TRUE
)
theta <- c(
alpha = 0,
beta = 1,
eta = -0.72502089617011087,
phi = -0.33982624766042181,
nu = 2.36465699101360594
)
rss_value <- 0.036717820758155562
fitted_values <- c(
rep(0.991572996129829225, 3), rep(0.95779593343449193, 1),
rep(0.82640795793649317, 2), rep(0.55492427795777899, 4),
rep(0.30125409492277104, 3), rep(0.15182795902080912, 3),
0.07523599271751825
)
residuals <- c(
-0.063572996129829225, -0.103572996129829225, -0.011572996129829225,
-0.00979593343449193, 0.07059204206350683, 0.05659204206350683,
-0.06692427795777899, -0.02292427795777899, 0.01107572204222101,
0.04407572204222101, -0.04225409492277104, -0.03625409492277104,
-0.05825409492277104, -0.00882795902080912, 0.02617204097919088,
0.06717204097919088, 0.01676400728248175
)
object <- logistic5_new(
x, y, w, NULL, 10000, c(0, 1, -2, -2, 1), c(0, 1, 0, 2, 3)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_true(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-6)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, length(y) - 3)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(
x, y, w, c(0, 1, -1, 0.1, 2), 10000,
c(0, 1, -2, -2, 1), c(0, 1, 0, 2, 3)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_true(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-6)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, length(y) - 3)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
object <- logistic5_new(
x, y, w, c(1, 2, -5, 2, 5), 10000,
c(0, 1, -2, -2, 1), c(0, 1, 0, 2, 3)
)
result <- fit_constrained(object)
expect_true(inherits(result, "logistic5_fit"))
expect_true(result$converged)
expect_true(result$constrained)
expect_equal(result$estimated, estimated)
expect_equal(result$coefficients, theta, tolerance = 1.0e-6)
expect_equal(result$rss, rss_value)
expect_equal(result$df.residual, length(y) - 3)
expect_equal(result$fitted.values, fitted_values)
expect_equal(result$residuals, residuals)
expect_equal(result$weights, w)
})
context("5-parameter logistic - general functions")
test_that("fisher_info", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 1, 2, 4, 3, 3, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.897, 0.883, 0.488, 0.532, 0.566, 0.599, 0.259,
0.265, 0.243, 0.143, 0.178, 0.219, 0.092
)
w <- c(
1.46, 1.385, 1.704, 0.96, 0.055, 1.071, 0.134, 1.825, 1.169, 0.628, 0.327,
1.201, 0.269, 1.294, 0.038, 1.278, 0.157
)
theta <- c(
alpha = 4 / 100,
beta = 9 / 10,
eta = -2,
phi = -3 / 2,
nu = 1 / 2
)
sigma <- 0.05
true_value <- matrix(c(
3317.1075212912263, 77.779705234498998, 30.105094962347675,
99.367820533674209, 101.76674312410457, 42879.475233843036,
77.779705234498998, 2509.3330682397757, -50.270268072025062,
57.263278623851573, -32.834177409666645, 5566.4533586419151,
30.105094962347675, -50.270268072025062, -28.431570455178267,
-53.631172444195592, -61.035018201080491, 329.86733099061305,
99.367820533674209, 57.263278623851573, -53.631172444195592,
-13.327710758643254, -75.171417594972841, 1404.2234763310936,
101.76674312410457, -32.834177409666645, -61.035018201080491,
-75.171417594972841, -95.495915267527460, 1308.4123739466697,
42879.475233843036, 5566.4533586419151, 329.86733099061305,
1404.2234763310936, 1308.4123739466697, 540135.75988991146
),
nrow = 6,
ncol = 6
)
rownames(true_value) <- colnames(true_value) <- c(
"alpha", "beta", "eta", "phi", "nu", "sigma"
)
object <- logistic5_new(x, y, w, NULL, 10000, NULL, NULL)
fim <- fisher_info(object, theta, sigma)
expect_type(fim, "double")
expect_length(fim, 6 * 6)
expect_equal(fim, true_value)
})
context("5-parameter logistic - drda fit")
test_that("drda: 'lower_bound' argument errors", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
lower_bound = c("a", "b", "c", "d", "e")
),
"'lower_bound' must be a numeric vector"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
lower_bound = matrix(-Inf, nrow = 5, ncol = 2),
upper_bound = rep(Inf, 5)
),
"'lower_bound' must be a numeric vector"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
lower_bound = rep(-Inf, 6),
upper_bound = rep(Inf, 5)
),
"'lower_bound' and 'upper_bound' must have the same length"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
lower_bound = c( 0, -Inf, -Inf, -Inf, -Inf),
upper_bound = c(-1, Inf, Inf, Inf, Inf)
),
"'lower_bound' cannot be larger than 'upper_bound'"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
lower_bound = c(Inf, -Inf, -Inf, -Inf, -Inf),
upper_bound = c(Inf, Inf, Inf, Inf, Inf)
),
"'lower_bound' cannot be equal to infinity"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
lower_bound = rep(-Inf, 6),
upper_bound = rep(Inf, 6)
),
"'lower_bound' must be of length 5"
)
})
test_that("drda: 'upper_bound' argument errors", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
upper_bound = c("a", "b", "c", "d", "e")
),
"'upper_bound' must be a numeric vector"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
lower_bound = rep(-Inf, 5),
upper_bound = matrix(Inf, nrow = 5, ncol = 2)
),
"'upper_bound' must be a numeric vector"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
lower_bound = c(-Inf, -Inf, -Inf, -Inf, -Inf),
upper_bound = c(-Inf, Inf, Inf, Inf, Inf)
),
"'upper_bound' cannot be equal to -infinity"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
lower_bound = rep(-Inf, 6),
upper_bound = rep(Inf, 6)
),
"'lower_bound' must be of length 5"
)
})
test_that("drda: 'start' argument errors", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
start = c("a", "b", "c", "d", "e")
),
"'start' must be a numeric vector"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
start = c(0, Inf, -1, 0, 1)
),
"'start' must be finite"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
start = c(-Inf, 0, -1, 0, 1)
),
"'start' must be finite"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
start = c(0, 0, -1, 0, 1, 1)
),
"'start' must be of length 5"
)
expect_error(
drda(
y ~ x, mean_function = "logistic6",
start = c(0, -1, -1, 0, 1, 1)
),
"parameter 'beta' cannot be smaller than 'alpha'"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
start = c(0, 1, 0, 0, 1)
),
"parameter 'eta' cannot be initialized to zero"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
start = c(0, 1, -1, 0, 0)
),
"parameter 'nu' cannot be negative nor zero"
)
expect_error(
drda(
y ~ x, mean_function = "logistic5",
start = c(0, 1, -1, 0, -1)
),
"parameter 'nu' cannot be negative nor zero"
)
})
context("5-parameter logistic - Area under and above the curve")
test_that("nauc: decreasing", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
)
result <- drda(y ~ x, mean_function = "logistic5")
expect_equal(nauc(result), 0.53873944885547561)
expect_equal(nauc(result, xlim = c(-1, 2)), 0.48525519463583185)
expect_equal(nauc(result, ylim = c(0.2, 0.8)), 0.52493778668672264)
expect_equal(
nauc(result, xlim = c(-1, 2), ylim = c(0.2, 0.8)), 0.47542532439305309
)
})
test_that("naac: decreasing", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
)
result <- drda(y ~ x, mean_function = "logistic5")
expect_equal(naac(result), 1 - 0.53873944885547561)
expect_equal(naac(result, xlim = c(-1, 2)), 1 - 0.48525519463583185)
expect_equal(naac(result, ylim = c(0.2, 0.8)), 1 - 0.52493778668672264)
expect_equal(
naac(result, xlim = c(-1, 2), ylim = c(0.2, 0.8)), 1 - 0.47542532439305309
)
})
test_that("nauc: increasing", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- rev(c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
))
result <- drda(y ~ x, mean_function = "logistic5")
expect_equal(nauc(result), 0.53465218185475628)
expect_equal(nauc(result, xlim = c(-1, 2)), 0.56806493427090424)
expect_equal(nauc(result, ylim = c(0.2, 0.8)), 0.50308844614941488)
expect_equal(
nauc(result, xlim = c(-1, 2), ylim = c(0.2, 0.8)), 0.61344155711817374
)
})
test_that("naac: increasing", {
x <- round(
rep(
-log(c(1000, 100, 10, 1, 0.1, 0.01, 0.001)),
times = c(3, 2, 2, 5, 3, 4, 1)
),
digits = 3
)
y <- rev(c(
0.928, 0.888, 0.98, 0.948, 0.856, 0.897, 0.883, 0.488, 0.532, 0.586, 0.566,
0.599, 0.259, 0.265, 0.243, 0.117, 0.143, 0.178, 0.219, 0.092
))
result <- drda(y ~ x, mean_function = "logistic5")
expect_equal(naac(result), 1 - 0.53465218185475628)
expect_equal(naac(result, xlim = c(-1, 2)), 1 - 0.56806493427090424)
expect_equal(naac(result, ylim = c(0.2, 0.8)), 1 - 0.50308844614941488)
expect_equal(
naac(result, xlim = c(-1, 2), ylim = c(0.2, 0.8)), 1 - 0.61344155711817374
)
})
|
dshimko <-
function(r, te, s0, k, y, a0, a1, a2)
{
sigma = a0 + a1*k + a2*k^2
v = sigma * sqrt(te)
d1 = (log(s0/k) + (r - y + (sigma^2)/2) * te) / v
d2 = d1 - v
d1x = -1/(k * v) + (1 - d1/v)*(a1 + 2 * a2 * k)
d2x = d1x - (a1 + 2 * a2 * k)
out = -1 * dnorm(d2)*(d2x - (a1 + 2 * a2* k)*(1 - d2*d2x) - 2 * a2 * k)
out
}
|
TimeStudy<-data.frame(Exposure_Time=NULL, Prob_of_Failure=NULL)
for(power in seq(0,7, by=.1)) {
mission_time<-10^power
arm2<-ftree.make(type="or", name="Warhead Armed", name2="Inadvertently")
arm2<-addLogic(arm2, at= 1, type="and", name="Arm Circuit", name2="Relays Closed")
arm2<-addExposed(arm2, at= 2, mttf=1/1.1e-6, tag="E1",
name="Relay 1", name2="Fails Closed")
arm2<-addExposed(arm2, at= 2, mttf=1/1.1e-6, tag="E2",
name="Relay 2", name2="Fails Closed")
arm2<-addLogic(arm2, at= 1, type="inhibit", name="Arm Power", name2="Is Present")
arm2<-addProbability(arm2, at= 5, prob=1, tag="W1", name="Battery Power", name2="Is Available")
arm2<-addLogic(arm2, at= 5, type="or", name="Arm Circuit Closed", name2="By Computer")
arm2<-addExposed(arm2, at= 7, mttf=1/1.1e-6, tag="E3",
name="CPU", name2="Failure")
arm2<-addExposed(arm2, at= 7, mttf=1/1.1e-6, tag="E4", name="Software", name2="Failure")
arm2<-ftree.calc(arm2)
study_row<-data.frame(Exposure_Time=mission_time, Prob_of_Failure=arm2$PBF[1])
TimeStudy<-rbind(TimeStudy, study_row)
}
plot(TimeStudy, log="x", type="l")
rm(mission_time)
|
toTernary <- function(abc){
sqrt3 <- 1.732050807568877293527446341505872366942805253810380628055806979
return(cbind(
x = (abc[, 1L] + 2.0*abc[, 3L]) / sqrt3,
y = abc[, 1L]
))
}
toTernaryVectors <- function(c1, c2, c3){ return(toTernary(cbind(c1, c2, c3))) }
toQuaternary <- function(abcd){
sqrt3 <- 1.732050807568877293527446341505872366942805253810380628055806979
return(cbind(
x = (abcd[, 1L] + 2.0*abcd[, 3L] + abcd[, 4L]) / sqrt3,
y = abcd[, 1L] + abcd[, 4L]/3.0,
z = abcd[, 4L]
))
}
toQuaternaryVectors <- function(c1, c2, c3, c4){ return(toQuaternary(cbind(c1, c2, c3, c4))) }
toSimplex <- function(x){
if(is.null(dim(x))) stop('"x" must be a matrix-like object.')
if((ncol(x) < 3L) || (ncol(x) > 4L)) stop('"x" must have 3 or 4 columns.')
if(!isTRUE(all.equal(rowSums(x), rep(1.0, nrow(x)), check.attributes = FALSE))) stop('all values in "x" must be in [0, 1].')
if(any((x < 0) | (x > 1))) stop('all values in "x" must be in [0, 1].')
if(ncol(x) == 3L){
return(toTernary(x))
} else if(ncol(x) == 4L){
return(toQuaternary(x))
} else {
stop("unexpected error")
}
}
|
source("incl/start.R")
usedNodes <- function(future) {
workers <- future$workers
reg <- sprintf("workers-%s", attr(workers, "name"))
c(used = length(future:::FutureRegistry(reg, action = "list")), total = length(workers))
}
plan(multisession, workers = 2L)
message("*** future() - invalid ownership ...")
session_uuid <- future:::session_uuid(attributes = TRUE)
cat(sprintf("Main R process: %s\n", session_uuid))
message("- Asserting ownership ...")
message("Creating future
f1 <- future({ future:::session_uuid(attributes = TRUE) })
stopifnot(inherits(f1, "MultisessionFuture"))
cat(sprintf("Future
v1 <- value(f1)
cat(sprintf("Future
stopifnot(v1 != session_uuid)
message("Creating future
f2 <- future({ future:::session_uuid(attributes = TRUE) })
stopifnot(inherits(f2, "MultisessionFuture"))
cat(sprintf("Future
v2 <- value(f2)
cat(sprintf("Future
stopifnot(v2 != session_uuid)
message("Creating future
f3 <- future({ f1$owner })
stopifnot(inherits(f3, "MultisessionFuture"))
cat(sprintf("Future
v3 <- value(f3)
cat(sprintf("Future
stopifnot(v3 == session_uuid)
message("Creating future
f4 <- future({ f1$owner })
stopifnot(inherits(f4, "MultisessionFuture"))
cat(sprintf("Future
v4 <- value(f4)
cat(sprintf("Future
stopifnot(v4 == session_uuid)
message("Creating future
f5 <- future({ stopifnot(f1$owner != future:::session_uuid(attributes = TRUE)); "not-owner" })
stopifnot(inherits(f5, "MultisessionFuture"))
v5 <- value(f5)
stopifnot(v5 == "not-owner")
message("- Asserting ownership ... DONE")
message("- Trying with invalid ownership ...")
message("Creating future
f1 <- future({ 42L })
cat(sprintf("Future
stopifnot(identical(f1$owner, session_uuid))
print(usedNodes(f1))
message("Creating future
f2 <- future({ value(f1) })
print(f2)
cat(sprintf("Future
stopifnot(identical(f2$owner, session_uuid))
print(usedNodes(f2))
message("Getting value of future
res <- tryCatch(value(f2), error = identity)
print(res)
stopifnot(inherits(res, "error"))
v1 <- value(f1)
print(v1)
stopifnot(v1 == 42L)
message("- Trying with invalid ownership ... DONE")
message("*** future() - invalid ownership ... DONE")
source("incl/end.R")
|
library(shiny)
if (interactive()) {
ui <- fluidPage(
orderInput("foo", "foo",
items = month.abb[1:3],
item_class = 'info'),
verbatimTextOutput("order"),
actionButton("update", "update")
)
server <- function(input, output, session) {
output$order <- renderPrint({input$foo})
observeEvent(input$update, {
updateOrderInput(session, "foo",
items = month.abb[1:6],
item_class = "success")
})
}
shinyApp(ui, server)
}
|
formatGhcn <- function(data, dataColumn = 7){
colSelect <- c(1,3,dataColumn)
data <- data[,colSelect]
Ids <- unique(data$Id)
CHCN <- matrix(ncol = 14)
firstStation <- Ids[1]
for(stationId in Ids){
stationData <- data[which(data$Id == stationId),]
keep <- which(!is.na(stationData[,2]))
stationData <- stationData[keep,]
years <- unique(stationData[,2])
startYear <- min(years)
endYear <- max(years)
cat(stationId, startYear, endYear, "\n")
if (sum(diff(years)) != length(years) -1 ) {
warning("gaps in years")
print(stationId)
} else {
temps <- rep(NA,((endYear-startYear)+1)*12)
temps[1:nrow(stationData)] <- stationData[,3]
tempMat <- matrix(temps,ncol = 12, byrow = TRUE)
thisStation <- cbind(stationId,startYear:endYear,tempMat)
if (stationId == firstStation) {
CHCN <- thisStation
} else {
CHCN <-rbind(CHCN,thisStation)
}
}
}
colnames(CHCN) <- c("Id","Year", month.abb)
return(CHCN)
}
|
npcdistbw <-
function(...){
args = list(...)
if (is(args[[1]],"formula"))
UseMethod("npcdistbw",args[[1]])
else if (!is.null(args$formula))
UseMethod("npcdistbw",args$formula)
else
UseMethod("npcdistbw",args[[which(names(args)=="bws")[1]]])
}
npcdistbw.formula <-
function(formula, data, subset, na.action, call, gdata = NULL, ...){
orig.class <- if (missing(data))
sapply(eval(attr(terms(formula), "variables"), environment(formula)),class)
else sapply(eval(attr(terms(formula), "variables"), data, environment(formula)),class)
has.gval <- !is.null(gdata)
gmf <- mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data", "subset", "na.action"),
names(mf), nomatch = 0)
gm <- match(c("formula", "gdata"),
names(gmf), nomatch = 0)
mf <- mf[c(1,m)]
gmf <- gmf[c(1,gm)]
if(!missing(call) && is.call(call)){
for(i in 1:length(call)){
if(tryCatch(class(eval(call[[i]])) == "formula",
error = function(e) FALSE))
break;
}
mf[[2]] <- call[[i]]
gmf[[2]] <- call[[i]]
}
mf[[1]] <- as.name("model.frame")
gmf[[1]] <- as.name("model.frame")
if (m[2] > 0) {
mf[["formula"]] = eval(mf[[m[1]]], environment(mf[[m[2]]]))
} else {
mf[["formula"]] = eval(mf[[m[1]]], parent.frame())
}
variableNames <- explodeFormula(mf[["formula"]])
varsPlus <- lapply(variableNames, paste, collapse=" + ")
mf[["formula"]] <- as.formula(paste(" ~ ", varsPlus[[1]]," + ",
varsPlus[[2]]),
env = environment(formula))
gmf[["formula"]] <- mf[["formula"]]
mf[["formula"]] <- terms(mf[["formula"]])
if(all(orig.class == "ts")){
args <- (as.list(attr(mf[["formula"]], "variables"))[-1])
attr(mf[["formula"]], "predvars") <- as.call(c(quote(as.data.frame),as.call(c(quote(ts.intersect), args))))
}else if(any(orig.class == "ts")){
arguments <- (as.list(attr(mf[["formula"]], "variables"))[-1])
arguments.normal <- arguments[which(orig.class != "ts")]
arguments.timeseries <- arguments[which(orig.class == "ts")]
ix <- sort(c(which(orig.class == "ts"),which(orig.class != "ts")),index.return = TRUE)$ix
attr(mf[["formula"]], "predvars") <- bquote(.(as.call(c(quote(cbind),as.call(c(quote(as.data.frame),as.call(c(quote(ts.intersect), arguments.timeseries)))),arguments.normal,check.rows = TRUE)))[,.(ix)])
}
mf <- eval(mf, parent.frame())
ydat <- mf[, variableNames[[1]], drop = FALSE]
xdat <- mf[, variableNames[[2]], drop = FALSE]
if (has.gval) {
names(gmf)[3] <- "data"
gmf <- eval(gmf, parent.frame())
gydat <- gmf[, variableNames[[1]], drop = FALSE]
}
tbw = eval(parse(text=paste("npcdistbw(xdat = xdat, ydat = ydat,",
ifelse(has.gval, "gydat = gydat",""), "...)")))
tbw$call <- match.call(expand.dots = FALSE)
environment(tbw$call) <- parent.frame()
tbw$formula <- formula
tbw$rows.omit <- as.vector(attr(mf,"na.action"))
tbw$nobs.omit <- length(tbw$rows.omit)
tbw$terms <- attr(mf,"terms")
tbw$variableNames <- variableNames
tbw
}
npcdistbw.condbandwidth <-
function(xdat = stop("data 'xdat' missing"),
ydat = stop("data 'ydat' missing"),
gydat = NULL,
bws, bandwidth.compute = TRUE,
nmulti, remin = TRUE, itmax = 10000,
do.full.integral = FALSE, ngrid = 100,
ftol = 1.490116e-07, tol = 1.490116e-04, small = 1.490116e-05,
memfac = 500.0, lbc.dir = 0.5, dfc.dir = 3, cfac.dir = 2.5*(3.0-sqrt(5)),initc.dir = 1.0,
lbd.dir = 0.1, hbd.dir = 1, dfac.dir = 0.25*(3.0-sqrt(5)), initd.dir = 1.0,
lbc.init = 0.1, hbc.init = 2.0, cfac.init = 0.5,
lbd.init = 0.1, hbd.init = 0.9, dfac.init = 0.375,
scale.init.categorical.sample=FALSE,
...){
ydat = toFrame(ydat)
xdat = toFrame(xdat)
if (missing(nmulti)){
nmulti <- min(5,(dim(ydat)[2]+dim(xdat)[2]))
}
if (length(bws$ybw) != dim(ydat)[2])
stop(paste("length of bandwidth vector does not match number of columns of", "'ydat'"))
if (length(bws$xbw) != dim(xdat)[2])
stop(paste("length of bandwidth vector does not match number of columns of", "'xdat'"))
if (dim(ydat)[1] != dim(xdat)[1])
stop(paste("number of rows of", "'ydat'", "does not match", "'xdat'"))
yccon = unlist(lapply(as.data.frame(ydat[,bws$iycon]),class))
if ((any(bws$iycon) && !all((yccon == class(integer(0))) | (yccon == class(numeric(0))))) ||
(any(bws$iyord) && !all(unlist(lapply(as.data.frame(ydat[,bws$iyord]),class)) ==
class(ordered(0)))) ||
(any(bws$iyuno) && !all(unlist(lapply(as.data.frame(ydat[,bws$iyuno]),class)) ==
class(factor(0)))))
stop(paste("supplied bandwidths do not match", "'ydat'", "in type"))
xccon = unlist(lapply(as.data.frame(xdat[,bws$ixcon]),class))
if ((any(bws$ixcon) && !all((xccon == class(integer(0))) | (xccon == class(numeric(0))))) ||
(any(bws$ixord) && !all(unlist(lapply(as.data.frame(xdat[,bws$ixord]),class)) ==
class(ordered(0)))) ||
(any(bws$ixuno) && !all(unlist(lapply(as.data.frame(xdat[,bws$ixuno]),class)) ==
class(factor(0)))))
stop(paste("supplied bandwidths do not match", "'xdat'", "in type"))
goodrows <- 1:dim(xdat)[1]
rows.omit <- unclass(na.action(na.omit(data.frame(xdat,ydat))))
goodrows[rows.omit] <- 0
if (all(goodrows==0))
stop("Data has no rows without NAs")
xdat = xdat[goodrows,,drop = FALSE]
ydat = ydat[goodrows,,drop = FALSE]
nrow = nrow(ydat)
yncol = ncol(ydat)
xncol = ncol(xdat)
oydat <- ydat
ydat = toMatrix(ydat)
yuno = ydat[, bws$iyuno, drop = FALSE]
ycon = ydat[, bws$iycon, drop = FALSE]
yord = ydat[, bws$iyord, drop = FALSE]
xdat = toMatrix(xdat)
xuno = xdat[, bws$ixuno, drop = FALSE]
xcon = xdat[, bws$ixcon, drop = FALSE]
xord = xdat[, bws$ixord, drop = FALSE]
tbw <- bws
if(!is.null(gydat)){
gydat <- toFrame(gydat)
if(any(is.na(gydat)))
stop("na's not allowed to be present in cdf gdata")
gydat <- toMatrix(gydat)
gyuno = gydat[, bws$iyuno, drop = FALSE]
gyord = gydat[, bws$iyord, drop = FALSE]
gycon = gydat[, bws$iycon, drop = FALSE]
cdf_on_train = FALSE
nog = nrow(gydat)
} else {
if(do.full.integral) {
cdf_on_train = TRUE
nog = 0
gyuno = data.frame()
gyord = data.frame()
gycon = data.frame()
} else {
cdf_on_train = FALSE
nog = ngrid
probs <- seq(0,1,length.out = nog)
evy <- oydat[1:nog,,drop = FALSE]
for(i in 1:ncol(evy)){
evy[,i] <- uocquantile(oydat[,i], probs)
}
evy <- toMatrix(evy)
gyuno = evy[, bws$iyuno, drop = FALSE]
gyord = evy[, bws$iyord, drop = FALSE]
gycon = evy[, bws$iycon, drop = FALSE]
}
}
mysd <- EssDee(data.frame(xcon,ycon))
nconfac <- nrow^(-1.0/(2.0*bws$cxkerorder+bws$ncon))
ncatfac <- nrow^(-2.0/(2.0*bws$cxkerorder+bws$ncon))
if (bandwidth.compute){
myopti = list(num_obs_train = nrow,
num_obs_grid = nog,
iMultistart = ifelse(nmulti==0,IMULTI_FALSE,IMULTI_TRUE),
iNum_Multistart = nmulti,
int_use_starting_values = ifelse(all(bws$ybw==0) && all(bws$xbw==0),
USE_START_NO, USE_START_YES),
int_LARGE_SF = ifelse(bws$scaling, SF_NORMAL, SF_ARB),
BANDWIDTH_den_extern = switch(bws$type,
fixed = BW_FIXED,
generalized_nn = BW_GEN_NN,
adaptive_nn = BW_ADAP_NN),
itmax=itmax, int_RESTART_FROM_MIN=ifelse(remin,RE_MIN_TRUE,RE_MIN_FALSE),
int_MINIMIZE_IO=ifelse(options('np.messages'), IO_MIN_FALSE, IO_MIN_TRUE),
bwmethod = switch(bws$method,
cv.ls = CDBWM_CVLS),
xkerneval = switch(bws$cxkertype,
gaussian = CKER_GAUSS + bws$cxkerorder/2 - 1,
epanechnikov = CKER_EPAN + bws$cxkerorder/2 - 1,
uniform = CKER_UNI,
"truncated gaussian" = CKER_TGAUSS),
ykerneval = switch(bws$cykertype,
gaussian = CKER_GAUSS + bws$cykerorder/2 - 1,
epanechnikov = CKER_EPAN + bws$cykerorder/2 - 1,
uniform = CKER_UNI,
"truncated gaussian" = CKER_TGAUSS),
uxkerneval = switch(bws$uxkertype,
aitchisonaitken = UKER_AIT,
liracine = UKER_LR),
uykerneval = switch(bws$uykertype,
aitchisonaitken = UKER_AIT,
liracine = UKER_LR),
oxkerneval = switch(bws$oxkertype,
wangvanryzin = OKER_WANG,
liracine = OKER_LR),
oykerneval = switch(bws$oykertype,
wangvanryzin = OKER_WANG,
liracine = OKER_NLR),
ynuno = dim(yuno)[2],
ynord = dim(yord)[2],
yncon = dim(ycon)[2],
xnuno = dim(xuno)[2],
xnord = dim(xord)[2],
xncon = dim(xcon)[2],
cdf_on_train = cdf_on_train,
int_do_tree = ifelse(options('np.tree'), DO_TREE_YES, DO_TREE_NO),
scale.init.categorical.sample=scale.init.categorical.sample,
dfc.dir = dfc.dir)
myoptd = list(ftol=ftol, tol=tol, small=small, memfac = memfac,
lbc.dir = lbc.dir, cfac.dir = cfac.dir, initc.dir = initc.dir,
lbd.dir = lbd.dir, hbd.dir = hbd.dir, dfac.dir = dfac.dir, initd.dir = initd.dir,
lbc.init = lbc.init, hbc.init = hbc.init, cfac.init = cfac.init,
lbd.init = lbd.init, hbd.init = hbd.init, dfac.init = dfac.init,
nconfac = nconfac, ncatfac = ncatfac)
if (bws$method != "normal-reference"){
total.time <-
system.time(myout <-
.C("np_distribution_conditional_bw", as.double(yuno), as.double(yord), as.double(ycon),
as.double(xuno), as.double(xord), as.double(xcon),
as.double(gyuno), as.double(gyord), as.double(gycon),
as.double(mysd),
as.integer(myopti), as.double(myoptd),
bw = c(bws$xbw[bws$ixcon],bws$ybw[bws$iycon],
bws$ybw[bws$iyuno],bws$ybw[bws$iyord],
bws$xbw[bws$ixuno],bws$xbw[bws$ixord]),
fval = double(2),fval.history = double(max(1,nmulti)),
timing = double(1),
PACKAGE="np" )[c("bw","fval","fval.history","timing")])[1]
} else {
nbw = double(yncol+xncol)
gbw = bws$yncon+bws$xncon
if (gbw > 0){
nbw[1:bws$xncon] <- 1.06
nbw[(bws$xncon+1):gbw] <- 1.587
if(!bws$scaling)
nbw[1:gbw]=nbw[1:gbw]*mysd*nconfac
}
myout= list( bw = nbw, fval = c(NA,NA) )
total.time <- NA
}
yr = 1:yncol
xr = 1:xncol
rorder = numeric(yncol + xncol)
rxcon = xr[bws$ixcon]
rxuno = xr[bws$ixuno]
rxord = xr[bws$ixord]
rycon = yr[bws$iycon]
ryuno = yr[bws$iyuno]
ryord = yr[bws$iyord]
tbw <- bws
tbw$ybw[c(rycon,ryuno,ryord)] <- myout$bw[yr+bws$xncon]
tbw$xbw[c(rxcon,rxuno,rxord)] <- myout$bw[setdiff(1:(yncol+xncol),yr+bws$xncon)]
tbw$fval = myout$fval[1]
tbw$ifval = myout$fval[2]
tbw$fval.history <- myout$fval.history
tbw$timing <- myout$timing
tbw$total.time <- total.time
}
tbw$sfactor <- tbw$bandwidth <- list(x = tbw$xbw, y = tbw$ybw)
bwf <- function(i){
tbw$bandwidth[[i]][tl[[i]]] <<- (tbw$bandwidth[[i]])[tl[[i]]]*dfactor[[i]]
}
sff <- function(i){
tbw$sfactor[[i]][tl[[i]]] <<- (tbw$sfactor[[i]])[tl[[i]]]/dfactor[[i]]
}
myf <- if(tbw$scaling) bwf else sff
if ((tbw$xnuno+tbw$ynuno) > 0){
dfactor <- ncatfac
dfactor <- list(x = dfactor, y = dfactor)
tl <- list(x = tbw$xdati$iuno, y = tbw$ydati$iuno)
lapply(1:length(tl), myf)
}
if ((tbw$xnord+tbw$ynord) > 0){
dfactor <- ncatfac
dfactor <- list(x = dfactor, y = dfactor)
tl <- list(x = tbw$xdati$iord, y = tbw$ydati$iord)
lapply(1:length(tl), myf)
}
if (tbw$ncon > 0){
dfactor <- nconfac
dfactor <- list(x = EssDee(xcon)*dfactor, y = EssDee(ycon)*dfactor)
tl <- list(x = tbw$xdati$icon, y = tbw$ydati$icon)
lapply(1:length(tl), myf)
}
tbw <- condbandwidth(xbw = tbw$xbw,
ybw = tbw$ybw,
bwmethod = tbw$method,
bwscaling = tbw$scaling,
bwtype = tbw$type,
cxkertype = tbw$cxkertype,
cxkerorder = tbw$cxkerorder,
uxkertype = tbw$uxkertype,
oxkertype = tbw$oxkertype,
cykertype = tbw$cykertype,
cykerorder = tbw$cykerorder,
uykertype = tbw$uykertype,
oykertype = tbw$oykertype,
fval = tbw$fval,
ifval = tbw$ifval,
fval.history = tbw$fval.history,
nobs = tbw$nobs,
xdati = tbw$xdati,
ydati = tbw$ydati,
xnames = tbw$xnames,
ynames = tbw$ynames,
sfactor = tbw$sfactor,
bandwidth = tbw$bandwidth,
rows.omit = rows.omit,
nconfac = nconfac,
ncatfac = ncatfac,
sdev = mysd,
bandwidth.compute = bandwidth.compute,
timing = tbw$timing,
total.time = tbw$total.time)
tbw
}
npcdistbw.NULL <-
function(xdat = stop("data 'xdat' missing"),
ydat = stop("data 'ydat' missing"),
bws, ...){
xdat <- toFrame(xdat)
ydat <- toFrame(ydat)
bws = double(ncol(ydat)+ncol(xdat))
tbw <- npcdistbw.default(xdat = xdat, ydat = ydat, bws = bws, ...)
mc <- match.call(expand.dots = FALSE)
environment(mc) <- parent.frame()
tbw$call <- mc
tbw
}
npcdistbw.default <-
function(xdat = stop("data 'xdat' missing"),
ydat = stop("data 'ydat' missing"),
gydat,
bws,
bandwidth.compute = TRUE,
nmulti, remin, itmax,
do.full.integral, ngrid,
ftol, tol, small, memfac,
lbc.dir, dfc.dir, cfac.dir,initc.dir,
lbd.dir, hbd.dir, dfac.dir, initd.dir,
lbc.init, hbc.init, cfac.init,
lbd.init, hbd.init, dfac.init,
scale.init.categorical.sample,
bwmethod, bwscaling, bwtype,
cxkertype, cxkerorder,
cykertype, cykerorder,
uxkertype,
oxkertype, oykertype,
...){
xdat <- toFrame(xdat)
ydat <- toFrame(ydat)
mc.names <- names(match.call(expand.dots = FALSE))
margs <- c("bwmethod", "bwscaling", "bwtype", "cxkertype", "cxkerorder",
"cykertype", "cykerorder", "uxkertype", "oxkertype",
"oykertype")
m <- match(margs, mc.names, nomatch = 0)
any.m <- any(m != 0)
tbw <- eval(parse(text=paste("condbandwidth(",
"xbw = bws[length(ydat)+1:length(xdat)],",
"ybw = bws[1:length(ydat)],",
paste(mc.names[m], ifelse(any.m,"=",""), mc.names[m], collapse=", "),
ifelse(any.m, ",",""),
"uykertype = 'aitchisonaitken',",
"nobs = nrow(xdat),",
"xdati = untangle(xdat),",
"ydati = untangle(ydat),",
"xnames = names(xdat),",
"ynames = names(ydat),",
"bandwidth.compute = bandwidth.compute)")))
mc.names <- names(match.call(expand.dots = FALSE))
margs <- c("gydat", "bandwidth.compute", "nmulti", "remin", "itmax", "do.full.integral", "ngrid", "ftol",
"tol", "small", "memfac",
"lbc.dir", "dfc.dir", "cfac.dir","initc.dir",
"lbd.dir", "hbd.dir", "dfac.dir", "initd.dir",
"lbc.init", "hbc.init", "cfac.init",
"lbd.init", "hbd.init", "dfac.init",
"scale.init.categorical.sample")
m <- match(margs, mc.names, nomatch = 0)
any.m <- any(m != 0)
tbw <- eval(parse(text=paste("npcdistbw.condbandwidth(xdat=xdat, ydat=ydat, bws=tbw",
ifelse(any.m, ",",""),
paste(mc.names[m], ifelse(any.m,"=",""), mc.names[m], collapse=", "),
")")))
mc <- match.call(expand.dots = FALSE)
environment(mc) <- parent.frame()
tbw$call <- mc
return(tbw)
}
|
bb_mods <- function(micro_set, table, ..., CI_method = c("wald", "profile"),
SS_type = c(2, 3, "II", "III"), trace = FALSE){
if(table %nin% unique(micro_set$Table)) stop("Specified table is not in supplied micro_set")
micro_set %<>% dplyr::filter(.data$Table == table) %>%
dplyr::mutate(Taxa = factor(.data$Taxa, levels = unique(.data$Taxa)))
f <- suppressWarnings(formula_fun_bb(...))
if(missing(CI_method)) CI_method <- "wald"
if(grepl("[profi]", CI_method)) warning("Profile likelihood confidence intervals greatly increase computation time.\n")
if(missing(SS_type)) SS_type <- 2
if(SS_type %nin% c(2,3,"II","III")) stop("SS_type must be either 2, 3, 'II', or 'III' \n")
Convergent_Models <- micro_set %>%
plyr::ddply(~ .data$Taxa, FE_bb, f. = f, trace = trace,
method. = CI_method, SS_type. = SS_type, ...)
if(nrow(Convergent_Models) == 0) stop("No taxa models converged.\n")
Cov <- micro_set %>% dplyr::select(cov_str(...))
Convergent_Models %<>%
dplyr::mutate(FDR_Pval = stats::p.adjust(.data$P_val, method = "BH") %>%
round(4))
RA_Summary <- micro_set %>% N.con(.data$ra,...) %>%
dplyr::left_join(Convergent_Models %>%
dplyr::select(.data$Taxa, .data$FE_Converged), by = "Taxa") %>%
dplyr::arrange(.data$FE_Converged, .data$Taxa) %>% unique
con_mod <- RA_Summary %>%
dplyr::ungroup() %>%
dplyr::distinct(.data$Taxa, .keep_all = T) %>%
dplyr::pull(.data$FE_Converged)
message("\n", sum(con_mod), " taxa converged.")
message(sum(!con_mod), " taxa did not converge.")
result <- list(Convergent_Summary=Convergent_Models %>%
dplyr::filter(.data$FE_Converged) %>%
dplyr::select(.data$Taxa, .data$Coef, .data$Beta,
.data$CI, .data$LRT, .data$P_val, .data$FDR_Pval),
Estimate_Summary=Convergent_Models %>%
dplyr::filter(.data$FE_Converged) %>%
dplyr::select(.data$Taxa, .data$Coef, .data$OR,
.data$CI_95, .data$LRT, .data$FDR_Pval) %>%
dplyr::filter(!grepl("(Intercept)", .data$Coef)),
RA_Summary=RA_Summary,
formula=f,
Model_Coef = Convergent_Models %>%
dplyr::filter(.data$FE_Converged) %>%
dplyr::select(.data$Taxa, .data$Coef, .data$Intercept,
Estimate = .data$Beta, .data$Cov_Type),
Model_Covs = Cov,
Model_Type = "bb_mod"
)
result
}
|
context("function mHMM and S3 print and summary methods")
n_t <- 100
n <- 10
m <- 3
J = 11
burn_in = 5
n_dep2 <- 2
q_emiss2 <- c(4,2)
gamma <- matrix(c(0.8, 0.1, 0.1,
0.2, 0.6, 0.2,
0.1, 0.2, 0.7), ncol = m, byrow = TRUE)
emiss_distr1 <- matrix(c(0.5, 0.5, 0.0, 0.0,
0.1, 0.1, 0.8, 0.0,
0.1, 0.1, 0.2, 0.6), nrow = m, ncol = q_emiss2[1], byrow = TRUE)
emiss_distr2 <- matrix(c(0.7, 0.3,
0.9, 0.1,
0.8, 0.2), nrow = m, ncol = q_emiss2[2], byrow = TRUE)
set.seed(4231)
data1 <- sim_mHMM(n_t = n_t, n = n, m = m, q_emiss = q_emiss2[1], gamma = gamma,
emiss_distr = emiss_distr1, var_gamma = .5, var_emiss = .5)
set.seed(4231)
data2 <- sim_mHMM(n_t = n_t, n = n, m = m, q_emiss = q_emiss2[2], gamma = gamma,
emiss_distr = emiss_distr2, var_gamma = .5, var_emiss = .5)
data3 <- list(states = data1$states, obs = cbind(data1$obs, data2$obs[,2]))
colnames(data3$obs) <- c("subj", "output_1", "output_2")
set.seed(3523)
out_2st_simb <- mHMM(s_data = data3$obs,
gen = list(m = m, n_dep = n_dep2, q_emiss = q_emiss2),
start_val = list(gamma, emiss_distr1, emiss_distr2),
mcmc = list(J = J, burn_in = burn_in))
xx <- rep(list(matrix(1, ncol = 1, nrow = n)), (n_dep2 + 1))
for(i in 2:(n_dep2 + 1)){
xx[[i]] <- cbind(xx[[i]], nonverbal_cov$std_CDI_change)
}
set.seed(3523)
out_2st_sim_cov1 <- mHMM(s_data = data3$obs, xx = xx,
gen = list(m = m, n_dep = n_dep2, q_emiss = q_emiss2),
start_val = list(gamma, emiss_distr1, emiss_distr2),
mcmc = list(J = J, burn_in = burn_in))
xx_gamma_only <- rep(list(matrix(1, ncol = 1, nrow = n)), (n_dep2 + 1))
xx_gamma_only[[1]] <- cbind(xx_gamma_only[[i]], nonverbal_cov$std_CDI_change)
set.seed(3523)
out_2st_sim_cov2 <- mHMM(s_data = data3$obs, xx = xx_gamma_only,
gen = list(m = m, n_dep = n_dep2, q_emiss = q_emiss2),
start_val = list(gamma, emiss_distr1, emiss_distr2),
mcmc = list(J = J, burn_in = burn_in))
xx_gamma_only_V2 <- rep(list(NULL), (n_dep2 + 1))
xx_gamma_only_V2[[1]] <- cbind(rep(1,n), nonverbal_cov$std_CDI_change)
set.seed(3523)
out_2st_sim_cov3 <- mHMM(s_data = data3$obs, xx = xx_gamma_only_V2,
gen = list(m = m, n_dep = n_dep2, q_emiss = q_emiss2),
start_val = list(gamma, emiss_distr1, emiss_distr2),
mcmc = list(J = J, burn_in = burn_in))
xx_dep1_only <- rep(list(matrix(1, ncol = 1, nrow = n)), (n_dep2 + 1))
xx_dep1_only[[2]] <- cbind(xx_dep1_only[[i]], nonverbal_cov$std_CDI_change)
set.seed(3523)
out_2st_sim_cov4 <- mHMM(s_data = data3$obs, xx = xx_dep1_only,
gen = list(m = m, n_dep = n_dep2, q_emiss = q_emiss2),
start_val = list(gamma, emiss_distr1, emiss_distr2),
mcmc = list(J = J, burn_in = burn_in))
xx_wrong1 <- rep(list(NULL), (n_dep2 + 1))
for(i in 2:(n_dep2 + 1)){
xx_wrong1[[i]] <- matrix(nonverbal_cov$std_CDI_change, ncol = 1)
}
xx_wrong2 <- rep(list(NULL), (n_dep2 + 1))
xx_wrong2[[1]] <- matrix(nonverbal_cov$std_CDI_change, ncol = 1)
xx_wrong3 <- list(cbind(rep(1,n), nonverbal_cov$std_CDI_change))
xx_wrong4 <- cbind(rep(1,n), nonverbal_cov$std_CDI_change)
xx_wrong5 <- rep(list(NULL), (n_dep2 + 1))
xx_wrong5[[1]] <- cbind(rep(1,n), c(rep(2,n/2), rep(1, n/2)))
xx_wrong6 <- rep(list(NULL), (n_dep2 + 1))
xx_wrong6[[1]] <- data.frame(rep(1,n), as.factor(c(rep(2,n/2), rep(1, n/2))))
test_that("errors mHMM input", {
expect_error(mHMM(s_data = data3$obs,
gen = list(m = m, n_dep = n_dep2, q_emiss = q_emiss2),
start_val = list(gamma, list(emiss_distr1, emiss_distr2)),
mcmc = list(J = J, burn_in = burn_in)), "number of elements in the list start_val")
expect_error(mHMM(s_data = data.frame(data3$obs[,1], as.factor(data3$obs[,2]), data3$obs[,3]),
gen = list(m = m, n_dep = n_dep2, q_emiss = q_emiss2),
start_val = list(gamma, emiss_distr1, emiss_distr2),
mcmc = list(J = J, burn_in = burn_in)), "factorial variables")
expect_error(mHMM(s_data = data3$obs, xx = xx_wrong1,
gen = list(m = m, n_dep = n_dep2, q_emiss = q_emiss2),
start_val = list(gamma, emiss_distr1, emiss_distr2),
mcmc = list(J = J, burn_in = burn_in)), "first column in each element of xx has to represent the intercept")
expect_error(mHMM(s_data = data3$obs, xx = xx_wrong2,
gen = list(m = m, n_dep = n_dep2, q_emiss = q_emiss2),
start_val = list(gamma, emiss_distr1, emiss_distr2),
mcmc = list(J = J, burn_in = burn_in)), "first column in each element of xx has to represent the intercept")
expect_error(mHMM(s_data = data3$obs, xx = xx_wrong3,
gen = list(m = m, n_dep = n_dep2, q_emiss = q_emiss2),
start_val = list(gamma, emiss_distr1, emiss_distr2),
mcmc = list(J = J, burn_in = burn_in)), "xx should be a list, with the number of elements")
expect_error(mHMM(s_data = data3$obs, xx = xx_wrong4,
gen = list(m = m, n_dep = n_dep2, q_emiss = q_emiss2),
start_val = list(gamma, emiss_distr1, emiss_distr2),
mcmc = list(J = J, burn_in = burn_in)), "xx should be a list, with the number of elements")
expect_error(mHMM(s_data = data3$obs, xx = xx_wrong5,
gen = list(m = m, n_dep = n_dep2, q_emiss = q_emiss2),
start_val = list(gamma, emiss_distr1, emiss_distr2),
mcmc = list(J = J, burn_in = burn_in)), "Dichotomous covariates")
expect_error(mHMM(s_data = data3$obs, xx = xx_wrong6,
gen = list(m = m, n_dep = n_dep2, q_emiss = q_emiss2),
start_val = list(gamma, emiss_distr1, emiss_distr2),
mcmc = list(J = J, burn_in = burn_in)), "Factors currently cannot be used as covariates")
})
test_that("class inherit", {
expect_s3_class(out_2st_simb, "mHMM")
expect_s3_class(out_2st_sim_cov2, "mHMM")
})
test_that("print mHMM", {
expect_output(print(out_2st_simb), paste("Number of subjects:", n))
expect_output(print(out_2st_simb), paste(J, "iterations"))
expect_output(print(out_2st_simb), paste("likelihood over all subjects:", -174))
expect_output(print(out_2st_simb), paste("AIC over all subjects:", 384))
expect_output(print(out_2st_simb), paste("states used:", m))
expect_output(print(out_2st_simb), paste("dependent variables used:", n_dep2))
})
test_that("summary mHMM", {
expect_output(summary(out_2st_simb), "From state 1 0.714 0.152 0.124")
expect_output(summary(out_2st_simb), "From state 3 0.214 0.224 0.553")
expect_output(summary(out_2st_simb), "output_1")
expect_output(summary(out_2st_simb), "output_2")
})
test_that("output PD_subj", {
expect_equal(length(out_2st_simb$PD_subj), n)
expect_equal(dim(out_2st_simb$PD_subj[[1]]), c(J, m*q_emiss2[1] + m*q_emiss2[2] + m * m + 1))
expect_equal(dim(out_2st_simb$PD_subj[[1]]), dim(out_2st_simb$PD_subj[[n]]))
expect_equal(as.vector(out_2st_simb$PD_subj[[2]][1,]), c(as.vector(t(emiss_distr1)),
as.vector(t(emiss_distr2)),as.vector(t(gamma)), NA))
expect_equal(as.numeric(out_2st_simb$PD_subj[[2]][10,(m*q_emiss2[1] + 2)]), 0.1865, tolerance=1e-4)
expect_equal(as.numeric(out_2st_simb$PD_subj[[2]][10,( m*q_emiss2[1] + m*q_emiss2[2] + m * m + 1)]), -159.1328, tolerance=1e-4)
})
test_that("output emis_cov_bar", {
expect_match(out_2st_simb$emiss_cov_bar, "predict the emission probabilities")
expect_equal(dim(out_2st_sim_cov1$emiss_cov_bar[[1]]), c(J, m * (q_emiss2[1] - 1)))
expect_equal(dim(out_2st_sim_cov1$emiss_cov_bar[[2]]), c(J, m * (q_emiss2[2] - 1)))
expect_match(out_2st_sim_cov2$emiss_cov_bar, "predict the emission probabilities")
expect_match(out_2st_sim_cov3$emiss_cov_bar, "predict the emission probabilities")
expect_match(out_2st_sim_cov3$emiss_cov_bar, "predict the emission probabilities")
expect_equal(dim(out_2st_sim_cov4$emiss_cov_bar[[1]]), c(J, m * (q_emiss2[1] - 1)))
expect_match(out_2st_sim_cov4$emiss_cov_bar[[2]], "predict the emission probabilities")
expect_equal(as.numeric(out_2st_sim_cov1$emiss_cov_bar[[1]][11, m * (q_emiss2[1] - 1)]), 0.50680380, tolerance=1e-4)
expect_equal(as.numeric(out_2st_sim_cov1$emiss_cov_bar[[2]][11, m * (q_emiss2[2] - 1)]), -0.1283152, tolerance=1e-4)
})
test_that("output emiss_int_bar", {
expect_equal(dim(out_2st_simb$emiss_int_bar[[1]]), c(J, m * (q_emiss2[1] - 1)))
expect_equal(dim(out_2st_simb$emiss_int_bar[[2]]), c(J, m * (q_emiss2[2] - 1)))
expect_equal(dim(out_2st_sim_cov1$emiss_int_bar[[1]]), c(J, m * (q_emiss2[1] - 1)))
expect_equal(as.numeric(out_2st_simb$emiss_int_bar[[1]][10,m * (q_emiss2[1] - 1)]), 0.82748937, tolerance=1e-4)
expect_equal(as.numeric(out_2st_simb$emiss_int_bar[[2]][11,m * (q_emiss2[2] - 1) - 1]), -1.31348525, tolerance=1e-4)
})
test_that("output emiss_int_subj", {
expect_equal(length(out_2st_simb$emiss_int_subj), n)
expect_equal(dim(out_2st_simb$emiss_int_subj[[1]][[1]]), dim(out_2st_simb$emiss_int_subj[[n]][[1]]))
expect_equal(dim(out_2st_simb$emiss_int_subj[[1]][[2]]), c(J, m * (q_emiss2[2] - 1)))
expect_equal(as.numeric(out_2st_simb$emiss_int_subj[[1]][[1]][2,1]), -1.131407, tolerance = 1e-4)
})
test_that("output emiss_naccept", {
expect_equal(length(out_2st_simb$emiss_naccept), n_dep2)
expect_equal(dim(out_2st_simb$emiss_naccept[[1]]), c(J-1, m))
expect_equal(dim(out_2st_simb$emiss_naccept[[2]]), c(J-1, m))
expect_equal(out_2st_simb$emiss_naccept[[1]][9,2], 3)
expect_equal(out_2st_simb$emiss_naccept[[2]][10,3], 2)
})
test_that("output emiss_prob_bar", {
expect_equal(dim(out_2st_simb$emiss_prob_bar[[1]]),c(J, m * q_emiss2[1]))
expect_equal(dim(out_2st_simb$emiss_prob_bar[[2]]),c(J, m * q_emiss2[2]))
expect_equal(as.vector(out_2st_simb$emiss_prob_bar[[1]][1,]), as.vector(t(emiss_distr1)))
expect_equal(as.vector(out_2st_simb$emiss_prob_bar[[2]][1,]), as.vector(t(emiss_distr2)))
expect_equal(as.numeric(out_2st_simb$emiss_prob_bar[[1]][11, q_emiss2[1]]), 0.05639170, tolerance = 1e-4)
expect_equal(as.numeric(out_2st_sim_cov1$emiss_prob_bar[[2]][10, q_emiss2[2]]),0.2541740, tolerance = 1e-4)
})
test_that("output gamma_cov_bar", {
expect_match(out_2st_simb$gamma_cov_bar, "predict the transition probability")
expect_match(out_2st_sim_cov1$gamma_cov_bar, "predict the transition probability")
expect_equal(dim(out_2st_sim_cov2$gamma_cov_bar), c(J, m * (m-1)))
expect_equal(dim(out_2st_sim_cov3$gamma_cov_bar), c(J, m * (m-1)))
expect_match(out_2st_sim_cov4$gamma_cov_bar, "predict the transition probability")
expect_equal(as.numeric(out_2st_sim_cov2$gamma_cov_bar[10, m * (m-1) - 1]), 0.53588195, tolerance = 1e-4)
})
test_that("output gamma_int_bar", {
expect_equal(dim(out_2st_simb$gamma_int_bar), c(J, m * (m - 1)))
expect_equal(dim(out_2st_sim_cov2$gamma_int_bar), c(J, m * (m - 1)))
expect_equal(as.numeric(out_2st_sim_cov2$gamma_int_bar[11, m - 1]), -1.422921, tolerance = 1e-4)
})
test_that("output gamma_int_subj", {
expect_equal(length(out_2st_simb$gamma_int_subj), n)
expect_equal(dim(out_2st_simb$gamma_int_subj[[1]]), dim(out_2st_simb$gamma_int_subj[[n]]))
expect_equal(dim(out_2st_simb$gamma_int_subj[[1]]), c(J, m * (m - 1)))
expect_equal(as.numeric(out_2st_simb$gamma_int_subj[[1]][11, 2 * (m-1)]), 0.03240422, tolerance = 1e-4)
})
test_that("output gamma_naccept", {
expect_equal(dim(out_2st_simb$gamma_naccept), c((J-1), m))
expect_equal(out_2st_simb$gamma_naccept[8,3], 1)
})
test_that("output gamma_prob_bar", {
expect_equal(dim(out_2st_simb$gamma_prob_bar),c(J, m * m))
expect_equal(as.vector(out_2st_simb$gamma_prob_bar[1,]), as.vector(t(gamma)))
expect_equal(as.numeric(out_2st_simb$gamma_prob_bar[11,1]),0.729715, tolerance = 1e-4)
expect_equal(as.numeric(out_2st_simb$gamma_prob_bar[10,8]), 0.2629192, tolerance = 1e-4)
})
test_that("output input", {
expect_equal(length(out_2st_simb$input), 8)
expect_equal(out_2st_simb$input[[1]], m)
expect_equal(out_2st_simb$input[[2]], n_dep2)
expect_equal(out_2st_simb$input[[3]], q_emiss2)
expect_equal(out_2st_simb$input[[4]], J)
expect_equal(out_2st_simb$input[[5]], burn_in)
expect_equal(out_2st_simb$input[[6]], n)
expect_equal(out_2st_simb$input[[7]], rep(n_t, n))
expect_equal(out_2st_simb$input[[8]], c("output_1", "output_2"))
})
|
OPF_7bit_T1<-function(seqs,label=c(),outFormat="mat",outputFileDist=""){
if(length(seqs)==1&&file.exists(seqs)){
seqs<-fa.read(seqs,alphabet="aa")
seqs_Lab<-alphabetCheck(seqs,alphabet = "aa",label)
seqs<-seqs_Lab[[1]]
label<-seqs_Lab[[2]]
}
else if(is.vector(seqs)){
seqs<-sapply(seqs,toupper)
seqs_Lab<-alphabetCheck(seqs,alphabet = "aa",label)
seqs<-seqs_Lab[[1]]
label<-seqs_Lab[[2]]
}else {
stop("ERROR: Input sequence is not in the correct format. It should be a FASTA file or a string vector.")
}
numSeqs<-length(seqs)
lenSeqs<-sapply(seqs, nchar)
group<-list("Hydrophobicity"= c('A','C','F','G','H','I','L','M','N','P','Q','S','T','V','W','Y'),
"Normalized Vander Waals volume"= c('C','F', 'I','L','M','V','W'),
"Polarity"= c('A','C','D','G','P','S','T'),
"Polarizibility"= c('C','F','I','L','M','V','W','Y'),
"Charge"= c('A','D','G','S','T'),
"Secondary structures"= c('D','G','N','P','S'),
"Solvent accessibility"= c('A','C','F','G','I','L','V','W'))
properties<-c("Hydrophobicity", "Normalized Vander Waals volume",
"Polarity", "Polarizibility", "Charge", "Secondary structures", "Solvent accessibility")
if(outFormat=="mat"){
if(length(unique(lenSeqs))>1){
stop("ERROR: All sequences should have the same length in 'mat' mode. For sequences with different lengths, please use 'txt' for outFormat parameter")
}
featureMatrix<-matrix(0, nrow = numSeqs, ncol = (lenSeqs[1]*7))
tempN1<-rep(properties,lenSeqs[1])
tempN2<-rep(1:lenSeqs[1],each=7)
colnames(featureMatrix)<-paste0("pos",tempN2,"_",tempN1)
for(n in 1:numSeqs){
seq=seqs[n]
aa=unlist(strsplit(seq,split = ""))
vect<-c()
for(a in aa)
{
g1 <- lapply(group, function(g) which(a %in% g))
b=lapply(g1, function(x) length(x)>0)
vect<-c(vect,as.numeric(b))
}
featureMatrix[n,]<-vect
}
row.names(featureMatrix)<-names(seqs)
return(featureMatrix)
}
else{
nameSeq<-names(seqs)
for(n in 1:numSeqs){
seq<-seqs[n]
chars<-unlist(strsplit(seq,split = ""))
vect<-c()
for(a in aa)
{
g1 <- lapply(group, function(g) which(a %in% g))
b=lapply(g1, function(x) length(x)>0)
vect<-c(vect,as.numeric(b))
}
temp<-c(nameSeq[n],vect)
temp<-paste(temp,collapse = "\t")
write(temp,outputFileDist,append = TRUE)
}
}
}
|
getMimeType <- function(filename) {
assertthat::assert_that(is.character(filename))
allowedFiles <- c(".png", ".tif", ".jpeg", ".jpg", ".pdf", ".kml")
assertthat::assert_that(!all(!endsWith(filename, allowedFiles)))
if (endsWith(filename, ".png")) {
return("image/png")
} else if (endsWith(filename, ".tif")) {
return("image/tiff")
} else if (endsWith(filename, ".jpeg") || endsWith(filename, ".jpg")) {
return("image/jpeg")
} else if (endsWith(filename, ".pdf")) {
return("application/pdf")
} else if (endsWith(filename, ".kml")) {
return("application/vnd.google-earth.kml+xml")
}
}
|
require(rgdal)
library(proj4)
library(raster)
library(sp)
library(spatstat)
library(maptools)
scn_metadata <- read.table(file="/home/bhardima/pecan/modules/data.remote/output/metadata/output_metadata.csv", header=T, sep="\t")
setwd("/home/bhardima/pecan/modules/data.remote/palsar_scenes/UNDERC/")
filelist <- as.vector(list.dirs(path=getwd() ,recursive=F))
for (i in 1:length(filelist)){
inpath <-filelist[i]
scnHH <- Sys.glob(file.path(inpath,"*_HH.tif"))
scnHV <- Sys.glob(file.path(inpath,"*_HV.tif"))
rasterHH <- raster(scnHH)
rasterHV <- raster(scnHV)
par(mfrow=(c(1,1)))
image(rasterHV)
decdeg_coords <-rbind(c(46.25113458880, -89.55009302960), c(46.25338996770, -89.55042213000),c(46.25345157750, -89.54913190390), c(46.25120674830, -89.54882422370), c(46.25113458880, -89.55009302960))
swN <-decdeg_coords[1,1]
nwN <-decdeg_coords[2,1]
neN <-decdeg_coords[3,1]
seN <-decdeg_coords[4,1]
swE <-decdeg_coords[1,2]
nwE <-decdeg_coords[2,2]
neE <-decdeg_coords[3,2]
seE <-decdeg_coords[4,2]
a0 <- scn_metadata$scn_coord2pix_a0[scn_metadata$scnid==scn_metadata$scnid[i]]
a1 <- scn_metadata$scn_coord2pix_a1[scn_metadata$scnid==scn_metadata$scnid[i]]
a2 <- scn_metadata$scn_coord2pix_a2[scn_metadata$scnid==scn_metadata$scnid[i]]
a3 <- scn_metadata$scn_coord2pix_a3[scn_metadata$scnid==scn_metadata$scnid[i]]
a4 <- scn_metadata$scn_coord2pix_a4[scn_metadata$scnid==scn_metadata$scnid[i]]
a5 <- scn_metadata$scn_coord2pix_a5[scn_metadata$scnid==scn_metadata$scnid[i]]
a6 <- scn_metadata$scn_coord2pix_a6[scn_metadata$scnid==scn_metadata$scnid[i]]
a7 <- scn_metadata$scn_coord2pix_a7[scn_metadata$scnid==scn_metadata$scnid[i]]
a8 <- scn_metadata$scn_coord2pix_a8[scn_metadata$scnid==scn_metadata$scnid[i]]
a9 <- scn_metadata$scn_coord2pix_a9[scn_metadata$scnid==scn_metadata$scnid[i]]
b0 <- scn_metadata$scn_coord2pix_b0[scn_metadata$scnid==scn_metadata$scnid[i]]
b1 <- scn_metadata$scn_coord2pix_b1[scn_metadata$scnid==scn_metadata$scnid[i]]
b2 <- scn_metadata$scn_coord2pix_b2[scn_metadata$scnid==scn_metadata$scnid[i]]
b3 <- scn_metadata$scn_coord2pix_b3[scn_metadata$scnid==scn_metadata$scnid[i]]
b4 <- scn_metadata$scn_coord2pix_b4[scn_metadata$scnid==scn_metadata$scnid[i]]
b5 <- scn_metadata$scn_coord2pix_b5[scn_metadata$scnid==scn_metadata$scnid[i]]
b6 <- scn_metadata$scn_coord2pix_b6[scn_metadata$scnid==scn_metadata$scnid[i]]
b7 <- scn_metadata$scn_coord2pix_b7[scn_metadata$scnid==scn_metadata$scnid[i]]
b8 <- scn_metadata$scn_coord2pix_b8[scn_metadata$scnid==scn_metadata$scnid[i]]
b9 <- scn_metadata$scn_coord2pix_b9[scn_metadata$scnid==scn_metadata$scnid[i]]
sw_p <- a0 + a1*swN + a2*swE + a3*swN*swE + a4*swN^2 + a5*swE^2 + a6*swN^2*swE + a7*swN*swE^2 + a8*swN^3 + a9*swE^3
nw_p <- a0 + a1*nwN + a2*nwE + a3*nwN*nwE + a4*nwN^2 + a5*nwE^2 + a6*nwN^2*nwE + a7*nwN*nwE^2 + a8*nwN^3 + a9*nwE^3
ne_p <- a0 + a1*neN + a2*neE + a3*neN*neE + a4*neN^2 + a5*neE^2 + a6*neN^2*neE + a7*neN*neE^2 + a8*neN^3 + a9*neE^3
se_p <- a0 + a1*seN + a2*seE + a3*seN*seE + a4*seN^2 + a5*seE^2 + a6*seN^2*seE + a7*seN*seE^2 + a8*seN^3 + a9*seE^3
sw_l <- b0 + b1*swN + b2*swE + b3*swN*swE + b4*swN^2 + b5*swE^2 + b6*swN^2*swE + b7*swN*swE^2 + b8*swN^3 + b9*swE^3
nw_l <- b0 + b1*nwN + b2*nwE + b3*nwN*nwE + b4*nwN^2 + b5*nwE^2 + b6*nwN^2*nwE + b7*nwN*nwE^2 + b8*nwN^3 + b9*nwE^3
ne_l <- b0 + b1*neN + b2*neE + b3*neN*neE + b4*neN^2 + b5*neE^2 + b6*neN^2*neE + b7*neN*neE^2 + b8*neN^3 + b9*neE^3
se_l <- b0 + b1*seN + b2*seE + b3*seN*seE + b4*seN^2 + b5*seE^2 + b6*seN^2*seE + b7*seN*seE^2 + b8*seN^3 + b9*seE^3
lpcoords <-rbind(c(sw_l, sw_p), c(nw_l, nw_p),c(ne_l, ne_p), c(se_l, se_p), c(sw_l, sw_p))
Sr1<- Polygon(lpcoords)
Srs1<- Polygons(list(Sr1),"sr1")
SpP<-SpatialPolygons(list(Srs1))
plotarea<-SpP@polygons[[1]]@area
HHcells<-as.data.frame(extract(rasterHH, SpP, method='simple',cellnumbers=T)[[1]])
HVcells<-as.data.frame(extract(rasterHV, SpP, method='simple',cellnumbers=T)[[1]])
HHcells$cell==HVcells$cell
cells <- HHcells$cell
rows<-unique(rowFromCell(rasterHH,cells))
cols<-unique(colFromCell(rasterHH,cells))
HH<-matrix(NA,length(rows),length(cols))
HV<-matrix(NA,length(rows),length(cols))
for(j in 1:length(rows)){
for(k in 1:length(cols)){
HH[j,k]<-rasterHH[rows[j],cols[k]]
HV[j,k]<-rasterHV[rows[j],cols[k]]
}
print(c("j=",100-(100*(j/length(cols)))))
}
image(HH, col=gray(1:255/255))
dates<-as.date(as.character(substr(output[2:nrow(output),2],1,8)),order='ymd')
par(mfrow=c(1,3))
image(HH, col=gray(1:255/255))
title(main=c(as.character(dates[i]),'HH'))
image(HV, col=gray(1:255/255))
title(main=c(as.character(dates[i]),'HV'))
image(HH-HV, col=gray(1:255/255))
title(main=c(as.character(dates[i]),'HH-HV'))
scn_metadata$scnid[i]
}
|
tar_test("tar_load_globals", {
tar_script({
tar_option_set(packages = "callr")
analyze_data <- function(data) {
summary(data)
}
list(
tar_target(x, 1 + 1),
tar_target(y, 1 + 1)
)
}, ask = FALSE)
envir <- new.env(parent = globalenv())
tar_load_globals(envir = envir)
expect_true(is.function(envir$analyze_data))
expect_true("callr" %in% (.packages()))
})
|
loo_moment_match <- function(x, ...) {
UseMethod("loo_moment_match")
}
loo_moment_match.default <- function(x, loo, post_draws, log_lik_i,
unconstrain_pars, log_prob_upars,
log_lik_i_upars, max_iters = 30L,
k_threshold = 0.7, split = TRUE,
cov = TRUE, cores = getOption("mc.cores", 1),
...) {
checkmate::assertClass(loo,classes = "loo")
checkmate::assertFunction(post_draws)
checkmate::assertFunction(log_lik_i)
checkmate::assertFunction(unconstrain_pars)
checkmate::assertFunction(log_prob_upars)
checkmate::assertFunction(log_lik_i_upars)
checkmate::assertNumber(max_iters)
checkmate::assertNumber(k_threshold)
checkmate::assertLogical(split)
checkmate::assertLogical(cov)
checkmate::assertNumber(cores)
if ("psis_loo" %in% class(loo)) {
is_method <- "psis"
} else {
stop("loo_moment_match currently supports only the \"psis\" importance sampling class.")
}
S <- dim(loo)[1]
N <- dim(loo)[2]
pars <- post_draws(x, ...)
upars <- unconstrain_pars(x, pars = pars, ...)
npars <- dim(upars)[2]
cov <- cov && S >= 10 * npars
orig_log_prob <- log_prob_upars(x, upars = upars, ...)
ks <- loo$diagnostics$pareto_k
kfs <- rep(0,N)
I <- which(ks > k_threshold)
loo_moment_match_i_fun <- function(i) {
loo_moment_match_i(i = i, x = x, log_lik_i = log_lik_i,
unconstrain_pars = unconstrain_pars,
log_prob_upars = log_prob_upars,
log_lik_i_upars = log_lik_i_upars,
max_iters = max_iters, k_threshold = k_threshold,
split = split, cov = cov, N = N, S = S, upars = upars,
orig_log_prob = orig_log_prob, k = ks[i],
is_method = is_method, npars = npars, ...)
}
if (cores == 1) {
mm_list <- lapply(X = I, FUN = function(i) loo_moment_match_i_fun(i))
}
else {
if (!os_is_windows()) {
mm_list <- parallel::mclapply(X = I, mc.cores = cores,
FUN = function(i) loo_moment_match_i_fun(i))
}
else {
cl <- parallel::makePSOCKcluster(cores)
on.exit(parallel::stopCluster(cl))
mm_list <- parallel::parLapply(cl = cl, X = I,
fun = function(i) loo_moment_match_i_fun(i))
}
}
for (ii in seq_along(I)) {
i <- mm_list[[ii]]$i
loo$pointwise[i, "elpd_loo"] <- mm_list[[ii]]$elpd_loo_i
loo$pointwise[i, "p_loo"] <- mm_list[[ii]]$p_loo
loo$pointwise[i, "mcse_elpd_loo"] <- mm_list[[ii]]$mcse_elpd_loo
loo$pointwise[i, "looic"] <- mm_list[[ii]]$looic
loo$diagnostics$pareto_k[i] <- mm_list[[ii]]$k
loo$diagnostics$n_eff[i] <- mm_list[[ii]]$n_eff
kfs[i] <- mm_list[[ii]]$kf
if (!is.null(loo$psis_object)) {
loo$psis_object$log_weights[, i] <- mm_list[[ii]]$lwi
}
}
if (!is.null(loo$psis_object)) {
loo$psis_object$diagnostics <- loo$diagnostics
}
cols_to_summarize <- !(colnames(loo$pointwise) %in% c("mcse_elpd_loo",
"influence_pareto_k"))
loo$estimates <- table_of_estimates(loo$pointwise[, cols_to_summarize,
drop = FALSE])
loo$elpd_loo <- loo$estimates["elpd_loo","Estimate"]
loo$p_loo <- loo$estimates["p_loo","Estimate"]
loo$looic <- loo$estimates["looic","Estimate"]
loo$se_elpd_loo <- loo$estimates["elpd_loo","SE"]
loo$se_p_loo <- loo$estimates["p_loo","SE"]
loo$se_looic <- loo$estimates["looic","SE"]
psislw_warnings(loo$diagnostics$pareto_k)
if (!split) {
throw_large_kf_warning(kfs)
}
loo
}
loo_moment_match_i <- function(i,
x,
log_lik_i,
unconstrain_pars,
log_prob_upars,
log_lik_i_upars,
max_iters,
k_threshold,
split,
cov,
N,
S,
upars,
orig_log_prob,
k,
is_method,
npars,
...) {
uparsi <- upars
ki <- k
kfi <- 0
log_liki <- log_lik_i(x, i, ...)
S_per_chain <- NROW(log_liki)
N_chains <- NCOL(log_liki)
dim(log_liki) <- c(S_per_chain, N_chains, 1)
r_eff_i <- loo::relative_eff(exp(log_liki), cores = 1)
dim(log_liki) <- NULL
is_obj <- suppressWarnings(importance_sampling.default(-log_liki,
method = is_method,
r_eff = r_eff_i,
cores = 1))
lwi <- as.vector(weights(is_obj))
lwfi <- rep(-matrixStats::logSumExp(rep(0, S)),S)
total_shift <- rep(0, npars)
total_scaling <- rep(1, npars)
total_mapping <- diag(npars)
iterind <- 1
while (iterind <= max_iters && ki > k_threshold) {
if (iterind == max_iters) {
throw_moment_match_max_iters_warning()
}
trans <- shift(x, uparsi, lwi)
quantities_i <- update_quantities_i(x, trans$upars, i = i,
orig_log_prob = orig_log_prob,
log_prob_upars = log_prob_upars,
log_lik_i_upars = log_lik_i_upars,
r_eff_i = r_eff_i,
cores = 1,
is_method = is_method,
...)
if (quantities_i$ki < ki) {
uparsi <- trans$upars
total_shift <- total_shift + trans$shift
lwi <- quantities_i$lwi
lwfi <- quantities_i$lwfi
ki <- quantities_i$ki
kfi <- quantities_i$kfi
log_liki <- quantities_i$log_liki
iterind <- iterind + 1
next
}
trans <- shift_and_scale(x, uparsi, lwi)
quantities_i <- update_quantities_i(x, trans$upars, i = i,
orig_log_prob = orig_log_prob,
log_prob_upars = log_prob_upars,
log_lik_i_upars = log_lik_i_upars,
r_eff_i = r_eff_i,
cores = 1,
is_method = is_method,
...)
if (quantities_i$ki < ki) {
uparsi <- trans$upars
total_shift <- total_shift + trans$shift
total_scaling <- total_scaling * trans$scaling
lwi <- quantities_i$lwi
lwfi <- quantities_i$lwfi
ki <- quantities_i$ki
kfi <- quantities_i$kfi
log_liki <- quantities_i$log_liki
iterind <- iterind + 1
next
}
if (cov) {
trans <- shift_and_cov(x, uparsi, lwi)
quantities_i <- update_quantities_i(x, trans$upars, i = i,
orig_log_prob = orig_log_prob,
log_prob_upars = log_prob_upars,
log_lik_i_upars = log_lik_i_upars,
r_eff_i = r_eff_i,
cores = 1,
is_method = is_method,
...)
if (quantities_i$ki < ki) {
uparsi <- trans$upars
total_shift <- total_shift + trans$shift
total_mapping <- trans$mapping %*% total_mapping
lwi <- quantities_i$lwi
lwfi <- quantities_i$lwfi
ki <- quantities_i$ki
kfi <- quantities_i$kfi
log_liki <- quantities_i$log_liki
iterind <- iterind + 1
next
}
}
break
}
if (split && (iterind > 1)) {
split_obj <- loo_moment_match_split(
x, upars, cov, total_shift, total_scaling, total_mapping, i,
log_prob_upars = log_prob_upars, log_lik_i_upars = log_lik_i_upars,
cores = 1, r_eff_i = r_eff_i, is_method = is_method, ...
)
log_liki <- split_obj$log_liki
lwi <- split_obj$lwi
lwfi <- split_obj$lwfi
r_eff_i <- split_obj$r_eff_i
}
else {
dim(log_liki) <- c(S_per_chain, N_chains, 1)
r_eff_i <- loo::relative_eff(exp(log_liki), cores = 1)
dim(log_liki) <- NULL
}
elpd_loo_i <- matrixStats::logSumExp(log_liki + lwi)
lpd <- matrixStats::logSumExp(log_liki) - log(length(log_liki))
mcse_elpd_loo <- mcse_elpd(
ll = as.matrix(log_liki), lw = as.matrix(lwi),
E_elpd = exp(elpd_loo_i), r_eff = r_eff_i
)
list(elpd_loo_i = elpd_loo_i,
p_loo = lpd - elpd_loo_i,
mcse_elpd_loo = mcse_elpd_loo,
looic = -2 * elpd_loo_i,
k = ki,
kf = kfi,
n_eff = min(1.0 / sum(exp(2 * lwi)),
1.0 / sum(exp(2 * lwfi))) * r_eff_i,
lwi = lwi,
i = i)
}
update_quantities_i <- function(x, upars, i, orig_log_prob,
log_prob_upars, log_lik_i_upars,
r_eff_i, is_method, ...) {
log_prob_new <- log_prob_upars(x, upars = upars, ...)
log_liki_new <- log_lik_i_upars(x, upars = upars, i = i, ...)
is_obj_new <- suppressWarnings(importance_sampling.default(-log_liki_new +
log_prob_new -
orig_log_prob,
method = is_method,
r_eff = r_eff_i,
cores = 1))
lwi_new <- as.vector(weights(is_obj_new))
ki_new <- is_obj_new$diagnostics$pareto_k
is_obj_f_new <- suppressWarnings(importance_sampling.default(log_prob_new -
orig_log_prob,
method = is_method,
r_eff = r_eff_i,
cores = 1))
lwfi_new <- as.vector(weights(is_obj_f_new))
kfi_new <- is_obj_f_new$diagnostics$pareto_k
list(
lwi = lwi_new,
lwfi = lwfi_new,
ki = ki_new,
kfi = kfi_new,
log_liki = log_liki_new
)
}
shift <- function(x, upars, lwi) {
mean_original <- colMeans(upars)
mean_weighted <- colSums(exp(lwi) * upars)
shift <- mean_weighted - mean_original
upars_new <- sweep(upars, 2, shift, "+")
list(
upars = upars_new,
shift = shift
)
}
shift_and_scale <- function(x, upars, lwi) {
S <- dim(upars)[1]
mean_original <- colMeans(upars)
mean_weighted <- colSums(exp(lwi) * upars)
shift <- mean_weighted - mean_original
mii <- exp(lwi)* upars^2
mii <- colSums(mii) - mean_weighted^2
mii <- mii*S/(S-1)
scaling <- sqrt(mii / matrixStats::colVars(upars))
upars_new <- sweep(upars, 2, mean_original, "-")
upars_new <- sweep(upars_new, 2, scaling, "*")
upars_new <- sweep(upars_new, 2, mean_weighted, "+")
list(
upars = upars_new,
shift = shift,
scaling = scaling
)
}
shift_and_cov <- function(x, upars, lwi, ...) {
mean_original <- colMeans(upars)
mean_weighted <- colSums(exp(lwi) * upars)
shift <- mean_weighted - mean_original
covv <- stats::cov(upars)
wcovv <- stats::cov.wt(upars, wt = exp(lwi))$cov
chol1 <- tryCatch(
{
chol(wcovv)
},
error = function(cond)
{
return(NULL)
}
)
if (is.null(chol1)) {
mapping <- diag(length(mean_original))
}
else {
chol2 <- chol(covv)
mapping <- t(chol1) %*% solve(t(chol2))
}
upars_new <- sweep(upars, 2, mean_original, "-")
upars_new <- tcrossprod(upars_new, mapping)
upars_new <- sweep(upars_new, 2, mean_weighted, "+")
colnames(upars_new) <- colnames(upars)
list(
upars = upars_new,
shift = shift,
mapping = mapping
)
}
throw_moment_match_max_iters_warning <- function() {
warning(
"The maximum number of moment matching iterations ('max_iters' argument)
was reached.\n",
"Increasing the value may improve accuracy.",
call. = FALSE
)
}
throw_large_kf_warning <- function(kf, k_threshold = 0.5) {
if (any(kf > k_threshold)) {
warning(
"The accuracy of self-normalized importance sampling may be bad.\n",
"Setting the argument 'split' to 'TRUE' will likely improve accuracy.",
call. = FALSE
)
}
}
psislw_warnings <- function(k) {
if (any(k > 0.7)) {
.warn(
"Some Pareto k diagnostic values are too high. ",
.k_help()
)
} else if (any(k > 0.5)) {
.warn(
"Some Pareto k diagnostic values are slightly high. ",
.k_help()
)
}
}
|
setClass("hash_big.matrix",
slots = c(md5 = "character"),
contains = "big.matrix"
)
as.hash_big.matrix <- function(x, backingpath = "bp", silence = TRUE, ...) {
if (!dir.exists(backingpath)) dir.create(backingpath)
temp <- methods::new("hash_big.matrix")
temp@md5 <- digest::digest(x)
if (file.exists(file.path(backingpath, paste0(temp@md5, ".desc")))) {
temp@address <- bigmemory::attach.big.matrix(paste0(temp@md5, ".desc"), path = backingpath)@address
if (!silence) message("Old backing file attached.")
} else {
temp@address <- bigmemory::as.big.matrix(x,
backingpath = backingpath,
backingfile = paste0(temp@md5, ".bin"),
descriptorfile = paste0(temp@md5, ".desc")
)@address
}
methods::validObject(temp)
return(temp)
}
attach.hash_big.matrix <- function(x, backingpath = "bp") {
if (!methods::is(x, "hash_big.matrix")) stop("Wrong input class. x should be a `hash_big.matrix`.")
if (!bigmemory::is.nil(x@address)) {
return(x)
}
x@address <- bigmemory::attach.big.matrix(paste0(x@md5, ".desc"), path = backingpath)@address
return(x)
}
|
PARETO2 <- function (mu.link = "log", sigma.link = "log")
{
mstats <- checklink("mu.link", "Pareto Type 2", substitute(mu.link),
c("inverse", "log", "identity", "own"))
dstats <- checklink("sigma.link", "Pareto Type 2", substitute(sigma.link),
c("inverse", "log", "identity", "own"))
structure(
list(family = c("PARETO2", "Pareto Type 2"),
parameters = list(mu = TRUE, sigma = TRUE),
nopar = 2,
type = "Continuous",
mu.link = as.character(substitute(mu.link)),
sigma.link = as.character(substitute(sigma.link)),
mu.linkfun = mstats$linkfun,
sigma.linkfun = dstats$linkfun,
mu.linkinv = mstats$linkinv,
sigma.linkinv = dstats$linkinv,
mu.dr = mstats$mu.eta,
sigma.dr = dstats$mu.eta,
dldm = function(y, mu, sigma)
{
dldm <- (1/(mu*sigma))-(1+(1/sigma))*(1/(y+mu))
dldm
},
d2ldm2 = function(y, mu, sigma)
{
d2ldm2 <- -(1/(mu^2*(1+2*sigma)))
d2ldm2
},
dldd = function(y, mu, sigma)
{
dldd2 <- -(1/sigma)+(log(y+mu)/(sigma^2))-(log(mu)/sigma^2)
dldd2
},
d2ldd2 = function(y, mu, sigma)
{
d2ldd22 <- -(1/sigma^2)
d2ldd22
},
d2ldmdd = function(y, mu, sigma)
{
d2ldmdd <- -(1/(mu*sigma+mu*sigma^2))
d2ldmdd
},
G.dev.incr = function(y, mu, sigma, ...) -2 *
dPARETO2(y, mu, sigma, log = TRUE),
rqres = expression(rqres(pfun = "pPARETO2",
type = "Continuous", y = y, mu = mu, sigma = sigma)),
mu.initial = expression({mu <- (y + mean(y))/2}),
sigma.initial = expression({sigma <- rep(1, length(y))}),
mu.valid = function(mu) all(mu > 0),
sigma.valid = function(sigma) all(sigma > 0),
y.valid = function(y) TRUE,
mean = function(mu, sigma) ifelse(sigma < 1, (mu*sigma) / (1-sigma), Inf),
variance = function(mu, sigma) ifelse(sigma < 0.5, (sigma^2 * mu^2) / ((1-sigma)^2 * (1-2*sigma)), Inf)
),
class = c("gamlss.family", "family"))
}
dPARETO2 <- function(x, mu = 1, sigma = 0.5, log = FALSE)
{
if (any(mu < 0)) stop(paste("mu must be positive", "\n", ""))
if (any(sigma <= 0)) stop(paste("sigma must be positive", "\n", ""))
if (any(x < 0)) stop(paste("x must be greater than 0", "\n", ""))
lfy <- -log(sigma) + (1/sigma)*log(mu) - ((1/sigma)+1)*log(x+mu)
if (log == FALSE) fy <- exp(lfy) else fy <- lfy
fy
}
pPARETO2 <- function(q, mu = 1, sigma = 0.5, lower.tail = TRUE, log.p = FALSE)
{
if (any(mu <= 0)) stop(paste("mu must be positive", "\n", ""))
if (any(sigma <= 0)) stop(paste("tau must be positive", "\n", ""))
if (any(q < 0)) stop(paste("q must be be greater than 0", "\n", ""))
cdf <- 1 - ((mu/(mu+q))^(1/sigma))
if (lower.tail == TRUE) cdf <- cdf
else cdf <- 1 - cdf
if (log.p == FALSE) cdf <- cdf
else cdf < - log(cdf)
cdf
}
qPARETO2 <- function(p, mu = 1, sigma = 0.5, lower.tail = TRUE, log.p = FALSE)
{
if (any(mu < 0)) stop(paste("mu must be positive", "\n", ""))
if (any(sigma < 0)) stop(paste("sigma must be positive", "\n", ""))
if (log.p==TRUE) p <- exp(p) else p <- p
if (any(p <= 0)|any(p >= 1)) stop(paste("p must be between 0 and 1", "\n", ""))
if (lower.tail==TRUE) p <- p else p <- 1-p
q <- mu*((1-p)^(-sigma)-1)
q
}
rPARETO2 <- function(n, mu = 1, sigma = 0.5)
{
if (any(mu <= 0)) stop(paste("mu must be positive", "\n", ""))
if (any(sigma <= 0)) stop(paste("sigma must be positive", "\n", ""))
if (any(n <= 0)) stop(paste("n must be a positive integer", "\n", ""))
n <- ceiling(n)
p <- runif(n)
r <- qPARETO2(p, mu = mu, sigma = sigma)
r
}
|
geom_blurry <- function(mapping = NULL, data = NULL,
stat = "identity", position = "identity",
...,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE) {
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomBlurry,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
na.rm = na.rm,
...
)
)
}
GeomBlurry <- ggproto(
"GeomBlurry", Geom,
required_aes = c("x", "y"),
non_missing_aes = c("size", "shape", "colour"),
default_aes = aes(
shape = 19, colour = "black", size = 1.5, fill = NA,
alpha = NA, stroke = 0.5
),
draw_panel = function(data, panel_params, coord, na.rm = FALSE) {
if (is.character(data$shape)) {
data$shape <- translate_shape_string(data$shape)
}
coords <- coord$transform(data, panel_params)
my_alpha <- coords$alpha
my_alpha[is.na(my_alpha)] <- 1.0
ggplot2:::ggname(
"geom_blurry",
grid::grobTree(
grid::pointsGrob(
coords$x, coords$y,
pch = coords$shape,
gp = grid::gpar(
col = alpha(coords$colour, my_alpha * 0.1),
fill = alpha(coords$fill , my_alpha * 0.1),
fontsize = (coords$size + 3) * .pt + coords$stroke * .stroke / 2,
lwd = coords$stroke * .stroke / 2
)
),
grid::pointsGrob(
coords$x, coords$y,
pch = coords$shape,
gp = grid::gpar(
col = alpha(coords$colour, my_alpha * 0.3),
fill = alpha(coords$fill , my_alpha * 0.3),
fontsize = (coords$size + 2) * .pt + coords$stroke * .stroke / 2,
lwd = coords$stroke * .stroke / 2
)
),
grid::pointsGrob(
coords$x, coords$y,
pch = coords$shape,
gp = grid::gpar(
col = alpha(coords$colour, my_alpha * 0.5),
fill = alpha(coords$fill , my_alpha * 0.5),
fontsize = (coords$size + 1) * .pt + coords$stroke * .stroke / 2,
lwd = coords$stroke * .stroke / 2
)
),
grid::pointsGrob(
coords$x, coords$y,
pch = coords$shape,
gp = grid::gpar(
col = alpha(coords$colour, coords$alpha),
fill = alpha(coords$fill , coords$alpha),
fontsize = coords$size * .pt + coords$stroke * .stroke / 2,
lwd = coords$stroke * .stroke / 2
)
)
)
)
},
draw_key = draw_key_point
)
translate_shape_string <- function(shape_string) {
if (nchar(shape_string[1]) <= 1) {
return(shape_string)
}
pch_table <- c(
"square open" = 0,
"circle open" = 1,
"triangle open" = 2,
"plus" = 3,
"cross" = 4,
"diamond open" = 5,
"triangle down open" = 6,
"square cross" = 7,
"asterisk" = 8,
"diamond plus" = 9,
"circle plus" = 10,
"star" = 11,
"square plus" = 12,
"circle cross" = 13,
"square triangle" = 14,
"triangle square" = 14,
"square" = 15,
"circle small" = 16,
"triangle" = 17,
"diamond" = 18,
"circle" = 19,
"bullet" = 20,
"circle filled" = 21,
"square filled" = 22,
"diamond filled" = 23,
"triangle filled" = 24,
"triangle down filled" = 25
)
shape_match <- charmatch(shape_string, names(pch_table))
invalid_strings <- is.na(shape_match)
nonunique_strings <- shape_match == 0
if (any(invalid_strings)) {
bad_string <- unique(shape_string[invalid_strings])
n_bad <- length(bad_string)
collapsed_names <- sprintf("\n* '%s'", bad_string[1:min(5, n_bad)])
more_problems <- if (n_bad > 5) {
sprintf("\n* ... and %d more problem%s", n_bad - 5, ifelse(n_bad > 6, "s", ""))
}
stop(
"Can't find shape name:",
collapsed_names,
more_problems,
call. = FALSE
)
}
if (any(nonunique_strings)) {
bad_string <- unique(shape_string[nonunique_strings])
n_bad <- length(bad_string)
n_matches <- vapply(
bad_string[1:min(5, n_bad)],
function(shape_string) sum(grepl(paste0("^", shape_string), names(pch_table))),
integer(1)
)
collapsed_names <- sprintf(
"\n* '%s' partially matches %d shape names",
bad_string[1:min(5, n_bad)], n_matches
)
more_problems <- if (n_bad > 5) {
sprintf("\n* ... and %d more problem%s", n_bad - 5, ifelse(n_bad > 6, "s", ""))
}
stop(
"Shape names must be unambiguous:",
collapsed_names,
more_problems,
call. = FALSE
)
}
unname(pch_table[shape_match])
}
|
"mslp"
|
collect_highlight_terms_1 <- function() {
terms <- c(
shiny::isolate(input$search_text),
shiny::isolate(input$area_2),
shiny::isolate(input$area_3),
shiny::isolate(input$area_4),
shiny::isolate(input$area_5),
shiny::isolate(input$area_6)
)[seq_len(shiny::isolate(input$antall_linjer))] %>%
(function(x)
x <- x[x != ""]) %>%
unique
if(length(terms) == 0){
terms <- ""
}
if (search_arguments$case_sensitive == FALSE) {
terms <- stringr::str_to_lower(terms)
}
return(terms)
}
collect_highlight_terms <- function() {
if (is.null(isolate(input$more_terms_button))) {
terms_highlight <- collect_highlight_terms_1()
} else if (isolate(input$more_terms_button == 'Yes')) {
terms_highlight <- isolate(input$area) %>%
stringr::str_split("\n") %>%
unlist %>%
.[length(.) > 0] %>%
unique
terms_highlight <-
c(collect_highlight_terms_1(), terms_highlight[terms_highlight != ""])
}
terms_highlight <-
terms_highlight[terms_highlight != ""]
return(terms_highlight)
}
collect_threshold_values <- function() {
thresholds <- stringr::str_extract(search_arguments$search_terms, "--\\d*$") %>%
stringr::str_replace("--", "") %>%
as.numeric()
return(thresholds)
}
clean_terms <- function(terms) {
if (search_arguments$case_sensitive == FALSE) {
terms <- stringr::str_to_lower(terms)
}
return(stringr::str_replace(terms, "--.*$", ""))
}
contains_argument <- function(chr_vector) {
return(any(stringr::str_detect(chr_vector, "--")))
}
contains_only_valid_thresholds <- function(chr_vector) {
chr_vector <- stringr::str_extract(chr_vector, "--\\d.*($|--)")
chr_vector <- chr_vector[!is.na(chr_vector)]
return(all(stringr::str_detect(chr_vector, "[^\\d-]") == FALSE))
}
check_valid_column_names <- function(chr_vector, df) {
chr_vector <- chr_vector %>%
.[!is.na(.)]
return(all(chr_vector %in% colnames(df)))
}
check_regexes <- function(patterns) {
patterns[is.null(patterns)] <-
"OK"
tryCatch(
is.integer(stringr::str_count("esel", patterns)),
error = function(e)
FALSE
)
}
collect_subset_terms <- function() {
terms_subset <- input$filter_text %>%
stringr::str_split("\n") %>%
unlist %>%
.[length(.) > 0] %>%
(function(x)
x <- x[x != ""]) %>%
unique
if (search_arguments$case_sensitive == FALSE) {
terms_subset <- stringr::str_to_lower(terms_subset)
}
return(terms_subset)
}
highlight_terms_exist <- function() {
if (length(search_arguments$highlight_terms) > 0) {
if (!is.na(search_arguments$highlight_terms)) {
return(TRUE)
}
}
return(FALSE)
}
|
result.extract.sub <- function(mask.grid, values, gk4.x, gk4.y,
outliers, silent=FALSE, withOutliers=FALSE){
if (!silent){ msg <- "" }
extracted.values <- rep(NA, times=length(mask.grid$alt))
for (i in 1:length(values)){
gridcellnumber <- data.coordinates2gridcellnumber(grid=mask.grid,
x=gk4.x[i], y=gk4.y[i])
if ((withOutliers)||(outliers[i]==0)){
extracted.values[gridcellnumber] <- values[i]
}
if (!silent){
cat(rep("\b", nchar(msg)),sep="")
msg <- paste(i," of ",
length(values), " Datasets done!",sep="")
cat(msg,sep="")
}
}
if (!silent){ cat("\n") }
result.values <- data.frame(values=extracted.values,
x=mask.grid$x, y=mask.grid$y)
return(result.values)
}
|
{}
.Samples <-
setClass(Class="Samples",
representation(data="list",
options="McmcOptions"),
prototype(data=
list(alpha=matrix(0, nrow=1, ncol=1),
beta=matrix(0, nrow=1, ncol=1)),
options=
McmcOptions(burnin=1,
step=1,
samples=1)),
validity=
function(object){
o <- Validate()
o$check(all(sapply(object@data,
NROW) == sampleSize(object@options)),
"all data elements must have as many rows as the sample size was")
o$result()
})
validObject(.Samples())
Samples <- function(data,
options)
{
.Samples(data=data,
options=options)
}
|
NULL
optimum_batches <- function(size_data, size_subset) {
check_number(size_data, "size_data")
check_number(size_subset, "size_subset")
ceiling(size_data/size_subset)
}
optimum_subset <- function(size_data, batches) {
check_number(size_data, "size_data")
check_number(batches, "batches")
ceiling(size_data/batches)
}
sizes_batches <- function(size_data, size_subset, batches) {
check_number(size_data, "size_data")
check_number(size_subset, "size_subset")
check_number(batches, "batches")
if (batches == 1) {
stop("There should be more than one batch.", call. = FALSE)
}
if (size_subset*batches < size_data) {
stop("batches or size_subset is too small to fit all the samples.",
call. = FALSE)
}
if (sum(size_subset*seq_len(batches) > size_data) > 1) {
stop("batches or size_subset could be reduced.",
call. = FALSE)
}
if (!valid_sizes(size_data, size_subset, batches)) {
stop("Please provide a higher number of batches or more samples per batch.",
call. = FALSE)
}
out <- internal_batches(size_data, size_subset, batches)
out <- unname(out)
stopifnot(sum(out) == size_data)
stopifnot(length(out) == batches)
stopifnot(all(out <= size_subset))
out
}
internal_batches <- function(size_data, size_subset, batches) {
if (size_subset*batches == size_data) {
return(rep(size_subset, times = batches))
}
if (batches == 1) {
return(size_subset)
}
if (size_subset*batches == size_data) {
return(rep(size_subset, times = batches))
}
max_batch_size <- optimum_subset(size_data, batches)
if (max_batch_size > size_subset) {
return(rep(size_subset, times = batches))
}
remaining <- size_data - max_batch_size*batches
out <- rep(max_batch_size, batches)
if (remaining == 0) {
return(out)
}
samples_to_remove_per_batch <- ceiling(abs(remaining)/batches)
batches_to_remove_samples <- abs(remaining)/samples_to_remove_per_batch
out[1:batches_to_remove_samples] <- out[1:batches_to_remove_samples] - samples_to_remove_per_batch
sort(out, decreasing = TRUE)
}
check_number <- function(x, name) {
if (length(x) != 1 || !is.numeric(x)) {
stop(name, " must be a single number.", call. = FALSE)
}
}
|
source(system.file(file.path('tests', 'testthat', 'test_utils.R'), package = 'nimble'))
context("Testing of old vs. new generated C++ during refactoring steps")
RwarnLevel <- options('warn')$warn
options(warn = -1)
nimbleVerboseSetting <- nimbleOptions('verbose')
nimbleOptions(verbose = FALSE)
compareOldAndNewCompilationRC <- function(input) {
name <- paste0('math: ', input$name, ': compiles')
test_that(name, {
wrap_if_matches(input$knownFailure, name, expect_error, {
run <- input$run
name <- input$name
foo <- nimbleFunction(run = run, name = 'foo')
nimbleOptions(useRefactoredSizeProcessing = FALSE)
nimble:::resetLabelFunctionCreators()
testProject <- nimble:::nimbleProjectClass(name = 'for_comparison')
compileNimble(foo, project = testProject, control = list(writeFiles = TRUE, compileCpp = FALSE, loadSO = FALSE))
filename <- testProject$RCfunInfos[['foo']][['cppClass']]$filename
newfilename <- paste0(filename,'_original')
pathedfilename <- file.path(tempdir(), 'nimble_generatedCode', filename)
original_pathedfilename <- file.path(tempdir(), 'nimble_generatedCode', newfilename)
for(ext in c('.h', '.cpp')) {
file.copy(paste0(pathedfilename, ext), paste0(original_pathedfilename, ext), overwrite = TRUE)
}
nimbleOptions(useRefactoredSizeProcessing = TRUE)
nimble:::resetLabelFunctionCreators()
testProject <- nimble:::nimbleProjectClass(name = 'for_comparison')
compileNimble(foo, project = testProject, control = list(writeFiles = TRUE, compileCpp = FALSE, loadSO = FALSE))
filename <- testProject$RCfunInfos[['foo']][['cppClass']]$filename
refactored_pathedfilename <- file.path(tempdir(), 'nimble_generatedCode', filename)
for(ext in c('.h','.cpp')) {
compareFilesUsingDiff(paste0(refactored_pathedfilename, ext), paste0(original_pathedfilename, ext),
main = paste0(ext, ' files do not match for: ', name))
}
})
})
}
testCases <- list(
list(name = 'Y <- x',
run = function(x = double(1)) {
Y <- x
}))
ans <- lapply(testCases, compareOldAndNewCompilationRC)
compareOldAndNewMathTest <- function(input) {
runFun <- gen_runFun(input, logicalArgs = input$logicalArgs,
returnType = ifelse(is.null(input$returnType), "double", input$returnType))
input$run <- runFun
if('knownFailureReport' %in% names(input) && input$knownFailureReport)
cat("\nBegin expected error message:\n")
compareOldAndNewCompilationRC(input)
if('knownFailureReport' %in% names(input) && input$knownFailureReport)
cat("End expected error message.\n")
}
source(system.file(file.path('tests', 'testthat', 'mathTestLists.R'), package = 'nimble'))
testsBasicMathModified <- lapply(testsBasicMath, function(x) {
if(x$name %in% c('modulo of vectors', 'modulo of vector and scalar'))
x$knownFailure <- NULL
x
})
ans2 <- lapply(testsBasicMathModified, compareOldAndNewMathTest)
options(warn = RwarnLevel)
nimbleOptions(verbose = nimbleVerboseSetting)
|
library(XML)
tt = xmlTree(namespaces = c(w = "http://schemas.microsoft.com/office/word/2003/wordml"))
tt$addPI("mso-application", "progid='Word.Document'")
tt$addTag("wordDocument", namespace = "w", close = FALSE)
v = tt$addTag("w:body",
tt$addTag("w:p",
tt$addTag("w:r",
tt$addTag("w:t", "Hello World!"))))
tt$closeTag()
cat(saveXML(tt))
|
multmixOpen <- function(lambdaformula, gammaformula, omegaformula, pformula,
data, mixture=c("P", "NB", "ZIP"), K,
dynamics=c("constant", "autoreg", "notrend", "trend", "ricker", "gompertz"),
fix=c("none", "gamma", "omega"), immigration=FALSE, iotaformula = ~1,
starts, method="BFGS", se=TRUE, ...)
{
if(!is(data, "unmarkedFrameMMO"))
stop("Data is not of class unmarkedFrameMMO.")
piFun <- data@piFun
mixture <- match.arg(mixture)
dynamics <- match.arg(dynamics)
if((identical(dynamics, "constant") || identical(dynamics, "notrend")) & immigration)
stop("You can not include immigration in the constant or notrend models")
if(identical(dynamics, "notrend") &
!identical(lambdaformula, omegaformula))
stop("lambdaformula and omegaformula must be identical for notrend model")
fix <- match.arg(fix)
formlist <- mget(c("lambdaformula", "gammaformula", "omegaformula",
"pformula", "iotaformula"))
check_no_support(formlist)
formula <- as.formula(paste(unlist(formlist), collapse=" "))
D <- getDesign(data, formula)
y <- D$y
M <- nrow(y)
T <- data@numPrimary
J <- ncol(getY(data)) / T
y <- array(y, c(M, J, T))
yt <- apply(y, c(1,3), function(x) {
if(all(is.na(x)))
return(NA)
else return(sum(x, na.rm=TRUE))
})
ytna <- apply(is.na(y), c(1,3), all)
ytna <- matrix(ytna, nrow=M)
ytna[] <- as.integer(ytna)
first <- apply(!ytna, 1, function(x) min(which(x)))
last <- apply(!ytna, 1, function(x) max(which(x)))
first1 <- which(first==1)[1]
Xlam.offset <- D$Xlam.offset
Xgam.offset <- D$Xgam.offset
Xom.offset <- D$Xom.offset
Xp.offset <- D$Xp.offset
Xiota.offset <- D$Xiota.offset
if(is.null(Xlam.offset)) Xlam.offset <- rep(0, M)
if(is.null(Xgam.offset)) Xgam.offset <- rep(0, M*(T-1))
if(is.null(Xom.offset)) Xom.offset <- rep(0, M*(T-1))
if(is.null(Xp.offset)) Xp.offset <- rep(0, M*T*J)
if(is.null(Xiota.offset)) Xiota.offset <- rep(0, M*(T-1))
if(missing(K)) {
K <- max(y, na.rm=T) + 20
warning("K was not specified and was set to ", K, ".")
}
if(K <= max(y, na.rm = TRUE))
stop("specified K is too small. Try a value larger than any observation")
k <- 0:K
lk <- length(k)
lfac.k <- lgamma(k+1)
kmyt <- array(0, c(lk, T, M))
lfac.kmyt <- array(0, c(M, T, lk))
fin <- array(NA, c(M, T, lk))
for(i in 1:M) {
for(t in 1:T) {
fin[i,t,] <- k - yt[i,t] >= 0
if(sum(ytna[i,t])==0) {
kmyt[,t,i] <- k - yt[i,t]
lfac.kmyt[i,t, ] <- lgamma(kmyt[,t,i] + 1)
}
}
}
lamParms <- colnames(D$Xlam)
gamParms <- colnames(D$Xgam)
omParms <- colnames(D$Xom)
detParms <- colnames(D$Xp)
nAP <- ncol(D$Xlam)
nGP <- ncol(D$Xgam)
nOP <- ncol(D$Xom)
nDP <- ncol(D$Xp)
nIP <- ifelse(immigration, ncol(D$Xiota), 0)
iotaParms <- character(0)
if(immigration) iotaParms <- colnames(D$Xiota)
if(identical(fix, "gamma")) {
if(!identical(dynamics, "constant"))
stop("dynamics must be constant when fixing gamma or omega")
if(nGP > 1){
stop("gamma covariates not allowed when fix==gamma")
}else {
nGP <- 0
gamParms <- character(0)
}
} else if(identical(dynamics, "notrend")) {
if(nGP > 1){
stop("gamma covariates not allowed when dyamics==notrend")
} else {
nGP <- 0
gamParms <- character(0)
}
}
if(identical(fix, "omega")) {
if(!identical(dynamics, "constant"))
stop("dynamics must be constant when fixing gamma or omega")
if(nOP > 1)
stop("omega covariates not allowed when fix==omega")
else {
nOP <- 0
omParms <- character(0)
}
} else if(identical(dynamics, "trend")) {
if(nOP > 1)
stop("omega covariates not allowed when dynamics='trend'")
else {
nOP <- 0
omParms <- character(0)
}
}
nP <- nAP + nGP + nOP + nDP + nIP + (mixture!="P")
if(!missing(starts) && length(starts) != nP)
stop(paste("The number of starting values should be", nP))
nbParm <- character(0)
if(identical(mixture,"NB"))
nbParm <- "alpha"
else if(identical(mixture, "ZIP"))
nbParm <- "psi"
paramNames <- c(lamParms, gamParms, omParms, detParms,
iotaParms, nbParm)
I <- cbind(rep(k, times=lk), rep(k, each=lk))
I1 <- I[I[,1] <= I[,2],]
lik_trans <- .Call("get_lik_trans", I, I1, PACKAGE="unmarked")
beta_ind <- matrix(NA, 6, 2)
beta_ind[1,] <- c(1, nAP)
beta_ind[2,] <- c(1, nGP) + nAP
beta_ind[3,] <- c(1, nOP) + nAP + nGP
beta_ind[4,] <- c(1, nDP) + nAP + nGP + nOP
beta_ind[5,] <- c(1, nIP) + nAP + nGP + nOP + nDP
beta_ind[6,] <- c(1, 1) + nAP + nGP + nOP + nDP + nIP
fin <- fin*1
yperm <- aperm(y, c(1,3,2))
yna <- is.na(yperm)*1
yna <- aperm(yna, c(3,2,1))
yperm <- aperm(yperm, c(3,2,1))
nll <- function(parms) {
.Call("nll_multmixOpen",
yperm, yt,
D$Xlam, D$Xgam, D$Xom, D$Xp, D$Xiota,
parms, beta_ind - 1,
Xlam.offset, Xgam.offset, Xom.offset, Xp.offset, Xiota.offset,
ytna, yna,
lk, mixture, first - 1, last - 1, first1 - 1, M, T, J,
D$delta, dynamics, fix, D$go.dims, immigration,
I, I1, lik_trans$Ib, lik_trans$Ip,
piFun, lfac.k, kmyt, lfac.kmyt, fin,
PACKAGE = "unmarked")
}
if(missing(starts)){
starts <- rep(0, nP)
}
fm <- optim(starts, nll, method=method, hessian=se, ...)
ests <- fm$par
names(ests) <- paramNames
covMat <- invertHessian(fm, nP, se)
fmAIC <- 2*fm$value + 2*nP
lamEstimates <- unmarkedEstimate(name = "Abundance", short.name = "lam",
estimates = ests[1:nAP], covMat = as.matrix(covMat[1:nAP,1:nAP]),
invlink = "exp", invlinkGrad = "exp")
estimateList <- unmarkedEstimateList(list(lambda=lamEstimates))
gamName <- switch(dynamics, constant = "gamConst", autoreg = "gamAR",
notrend = "", trend = "gamTrend",
ricker="gamRicker", gompertz = "gamGomp")
if(!(identical(fix, "gamma") | identical(dynamics, "notrend"))){
estimateList@estimates$gamma <- unmarkedEstimate(name =
ifelse(identical(dynamics, "constant") | identical(dynamics, "autoreg"),
"Recruitment", "Growth Rate"), short.name = gamName,
estimates = ests[(nAP+1) : (nAP+nGP)], covMat = as.matrix(covMat[(nAP+1) :
(nAP+nGP), (nAP+1) : (nAP+nGP)]),
invlink = "exp", invlinkGrad = "exp")
}
if(!(identical(fix, "omega") | identical(dynamics, "trend"))) {
if(identical(dynamics, "constant") | identical(dynamics, "autoreg") |
identical(dynamics, "notrend")){
estimateList@estimates$omega <- unmarkedEstimate( name="Apparent Survival",
short.name = "omega", estimates = ests[(nAP+nGP+1) :(nAP+nGP+nOP)],
covMat = as.matrix(covMat[(nAP+nGP+1) : (nAP+nGP+nOP),
(nAP+nGP+1) : (nAP+nGP+nOP)]),
invlink = "logistic", invlinkGrad = "logistic.grad")
} else if(identical(dynamics, "ricker")){
estimateList@estimates$omega <- unmarkedEstimate(name="Carrying Capacity",
short.name = "omCarCap", estimates = ests[(nAP+nGP+1) :(nAP+nGP+nOP)],
covMat = as.matrix(covMat[(nAP+nGP+1) : (nAP+nGP+nOP),
(nAP+nGP+1) : (nAP+nGP+nOP)]),
invlink = "exp", invlinkGrad = "exp")
} else{
estimateList@estimates$omega <- unmarkedEstimate(name="Carrying Capacity",
short.name = "omCarCap", estimates = ests[(nAP+nGP+1) :(nAP+nGP+nOP)],
covMat = as.matrix(covMat[(nAP+nGP+1) : (nAP+nGP+nOP),
(nAP+nGP+1) : (nAP+nGP+nOP)]),
invlink = "exp", invlinkGrad = "exp")
}
}
estimateList@estimates$det <- unmarkedEstimate(
name = "Detection", short.name = "p",
estimates = ests[(nAP+nGP+nOP+1) : (nAP+nGP+nOP+nDP)],
covMat = as.matrix(covMat[(nAP+nGP+nOP+1) : (nAP+nGP+nOP+nDP),
(nAP+nGP+nOP+1) : (nAP+nGP+nOP+nDP)]),
invlink = "logistic", invlinkGrad = "logistic.grad")
if(immigration) {
estimateList@estimates$iota <- unmarkedEstimate(
name="Immigration", short.name = "iota",
estimates = ests[(nAP+nGP+nOP+nDP+1) :(nAP+nGP+nOP+nDP+nIP)],
covMat = as.matrix(covMat[(nAP+nGP+nOP+nDP+1) : (nAP+nGP+nOP+nDP+nIP),
(nAP+nGP+nOP+nDP+1) : (nAP+nGP+nOP+nDP+nIP)]),
invlink = "exp", invlinkGrad = "exp")
}
if(identical(mixture, "NB")) {
estimateList@estimates$alpha <- unmarkedEstimate(name = "Dispersion",
short.name = "alpha", estimates = ests[nP],
covMat = as.matrix(covMat[nP, nP]), invlink = "exp",
invlinkGrad = "exp")
}
if(identical(mixture, "ZIP")) {
estimateList@estimates$psi <- unmarkedEstimate(name = "Zero-inflation",
short.name = "psi", estimates = ests[nP],
covMat = as.matrix(covMat[nP, nP]), invlink = "logistic",
invlinkGrad = "logistic.grad")
}
umfit <- new("unmarkedFitMMO", fitType = "multmixOpen",
call = match.call(), formula = formula, formlist = formlist, data = data,
sitesRemoved=D$removed.sites, estimates = estimateList, AIC = fmAIC,
opt = fm, negLogLike = fm$value, nllFun = nll, K = K, mixture = mixture,
dynamics = dynamics, fix = fix, immigration=immigration)
return(umfit)
}
|
expected <- eval(parse(text="c(2.06019871693154-0.97236279736125i, 1.38966747567603-0.89308479200721i, 1.74477849158514-0.89217080785487i, 1.81523768768554-0.90287292275869i, 2.20913948714243-1.04459069848176i, 1.60263304392934-0.88173204641486i, 2.10776763442223-0.99258373995851i, 2.5380296111574-1.33177066138762i, 1.83792574762849-0.90713748654542i, 0.95167219314953-1.03372343363615i, 1.97115981017201-0.940809478923i, 1.14864149179823-0.9478159925318i, 2.52084254505265-1.31054487269306i, 1.61007950812446-0.88191942508125i, 1.20816857163099-0.92971161728178i, 1.35868857560486-0.8974910350038i, 1.49610693236178-0.88334910031388i, 2.01465147478476-0.95524421064323i, 2.14806988970708-1.01173036858466i, 2.25066651078344-1.06983602959499i, 1.48765591796887-0.88382239981613i, 2.20671601896538-1.04319273288422i, 1.91380178921757-0.92444247548778i, 1.75137033621791-0.89301246696347i, 0.54901015708049-1.40555758406813i, 2.02206077002631-0.95788602315598i, 1.40474744046887-0.89120080287719i, 1.51568368331281-0.88244842343019i, 2.21510417542065-1.04806593419354i, 1.6212080486594-0.88227275342459i, 0.68659437082566-1.23700772602298i, 1.2545077861783-0.91780201569415i, 1.54164231516619-0.88167416649732i, 1.8671364540176-0.9132355492085i, 2.64716760753218-1.49064594698513i, 0.83275223108544-1.1096090644475i, 2.46154314736853-1.24380506401514i, 1.06238393475755-0.98014668087382i, 0.53089285385325-1.43244403873718i, 2.45472879430902-1.23673011585732i, 1.08697693875905-0.97014975400808i, 1.75564923963954-0.89357620129453i, 2.50444377143645-1.29111486671099i, 2.48285928286931-1.26669863184365i, 2.51505930226871-1.30360310302078i, 1.94121615992608-0.93189805963656i, 2.46199354083604-1.24427675964869i, 1.09598785117287-0.96664660265816i, 0.48353317246709-1.50917513375676i, 2.38599272957818-1.17141281294956i, 1.03204027934864-0.99339141904072i, 1.04384831135097-0.98811495960226i, 1.33703098122139-0.90100631664327i, 2.24178949069067-1.06422955325057i, 1.65521150816549-0.8838982271986i, 1.76839163576082-0.8953365000496i, 1.17873102109643-0.93825792450717i, 1.83252734835527-0.90608576667087i, 0.91774134184438-1.05325217158387i, 1.83401272112857-0.90637283063358i, 0.87502981371111-1.08017250683592i, 2.26461206945042-1.07888319465557i, 2.37331090399735-1.16047433677904i, 0.31221417819914-1.89630688813059i, 1.86324878916868-0.91238391489524i, 1.36073251658084-0.89717788657767i, 1.12967250507139-0.95428402228972i, 1.90917797809015-0.92324959236406i, 1.20989551220349-0.92923433018444i, 1.31147517885395-0.90562376711956i, 1.72279235941004-0.88959702916893i, 1.52463539820123-0.88212741812883i, 1.59488434738021-0.88157876499314i, 0.47715740224864-1.52028317388427i, 2.08009766680446-0.9805202035075i, 2.2901049191676-1.09620500808125i, 1.54407748442208-0.88162604012553i, 1.35217597933995-0.89851014050068i, 1.26479953626603-0.91540482044197i, 1.89179085389467-0.91892771491411i, 2.27239579346697-1.08406296973435i, 0.76683865083424-1.1617027515241i, 1.81670329981108-0.90313612992273i, 2.15773593551216-1.01661316076046i, 1.73747207096121-0.89127574734901i, 1.70999062255743-0.88826260835802i, 0.84405334773776-1.1014538505892i, 1.51089600213742-0.88264348268232i, 1.05337324593324-0.98397287363741i, 1.91975338258785-0.9260051285683i, 1.41945761915969-0.88952557986273i, 1.79932440652189-0.90012306157287i, 1.50394071111703-0.88295591770301i, 2.17579962867022-1.02605215090402i, 2.39698753635608-1.18116280419683i, 0.50804991930984-1.46823049931261i, 1.15347435427867-0.94622340979008i, 2.36906014015905-1.15687993185943i, 1.99508101918656-0.94852492497881i, 2.33667576456328-1.13063614489832i)"));
test(id=0, code={
argv <- eval(parse(text="list(c(-0.7104065636993+1i, 0.25688370915653+1i, -0.24669187846237+1i, -0.34754259939773+1i, -0.95161856726502+1i, -0.04502772480892+1i, -0.78490446945708+1i, -1.66794193658814+1i, -0.38022652028776+1i, 0.91899660906077+1i, -0.57534696260839+1i, 0.60796432222503+1i, -1.61788270828916+1i, -0.05556196552454+1i, 0.51940720394346+1i, 0.30115336216671+1i, 0.10567619414894+1i, -0.64070600830538+1i, -0.84970434603358+1i, -1.02412879060491+1i, 0.11764659710013+1i, -0.9474746141848+1i, -0.49055744370067+1i, -0.25609219219825+1i, 1.84386200523221+1i, -0.65194990169546+1i, 0.23538657228486+1i, 0.07796084956371+1i, -0.96185663413013+1i, -0.0713080861236+1i, 1.44455085842335+1i, 0.45150405307921+1i, 0.04123292199294+1i, -0.42249683233962+1i, -2.05324722154052+1i, 1.13133721341418+1i, -1.46064007092482+1i, 0.73994751087733+1i, 1.90910356921748+1i, -1.4438931609718+1i, 0.70178433537471+1i, -0.26219748940247+1i, -1.57214415914549+1i, -1.51466765378175+1i, -1.60153617357459+1i, -0.5309065221703+1i, -1.4617555849959+1i, 0.68791677297583+1i, 2.10010894052567+1i, -1.28703047603518+1i, 0.78773884747518+1i, 0.76904224100091+1i, 0.33220257895012+1i, -1.00837660827701+1i, -0.11945260663066+1i, -0.28039533517025+1i, 0.56298953322048+1i, -0.37243875610383+1i, 0.97697338668562+1i, -0.37458085776701+1i, 1.05271146557933+1i, -1.04917700666607+1i, -1.26015524475811+1i, 3.2410399349424+1i, -0.41685758816043+1i, 0.29822759154072+1i, 0.63656967403385+1i, -0.48378062570874+1i, 0.51686204431361+1i, 0.36896452738509+1i, -0.21538050764169+1i, 0.06529303352532+1i, -0.03406725373846+1i, 2.12845189901618+1i, -0.74133609627283+1i, -1.09599626707466+1i, 0.03778839917108+1i, 0.31048074944314+1i, 0.43652347891018+1i, -0.45836533271111+1i, -1.06332613397119+1i, 1.26318517608949+1i, -0.34965038795355+1i, -0.86551286265337+1i, -0.2362795689411+1i, -0.19717589434855+1i, 1.10992028971364+1i, 0.0847372921972+1i, 0.75405378518452+1i, -0.49929201717226+1i, 0.2144453095816+1i, -0.32468591149083+1i, 0.09458352817357+1i, -0.89536335797754+1i, -1.31080153332797+1i, 1.99721338474797+1i, 0.60070882367242+1i, -1.25127136162494+1i, -0.61116591668042+1i, -1.18548008459731+1i))"));
do.call(`acos`, argv);
}, o=expected);
|
pcaBootPlot <- function(data=NULL, groups=NULL,
min.value=1, all.min.value=FALSE,
num.boot.samples=100, log2.transform=TRUE,
pdf.filename=NULL,
pdf.width=6,
pdf.height=6,
draw.legend=FALSE, legend.names=NULL,
legend.x=NULL, legend.y=NULL,
transparency=77,
min.x=NULL, max.x=NULL, min.y=NULL, max.y=NULL,
correct.inversions=TRUE,
confidence.regions=FALSE,
confidence.size=0.95,
step.size=0.1,
trim.proportion=0,
return.samples=FALSE,
use.prcomp=FALSE) {
if(is.null(data)) {
return("You must provide a data.frame for the data parameter")
}
num.samples <- (ncol(data)-1)
cat("Performing PCA on", num.samples, "samples\n")
use.facto <- TRUE
if (use.prcomp == TRUE) {
use.facto <- FALSE
} else if (num.samples < 50) {
cat("\nUsing FactoMineR for analysis. However you may be able to speed up\n")
cat(" computation by setting use.prcomp to TRUE\n\n")
}
dup.indices <- duplicated(data$ID)
dup.IDs <- data[dup.indices,]$ID
avg.fpkms <- data.frame()
cat(paste("There are ", length(dup.IDs), " duplicated entries", sep=""), "\n")
if (length(dup.IDs) > 0) {
cat("Averaging duplicated entries...\n")
for (ID in levels(as.ordered(dup.IDs))) {
avg.ID <- data.frame(ID=ID,
t(data.frame(colMeans(data[data$ID == ID,2:ncol(data)]))))
row.names(avg.ID) <- 1
avg.fpkms <- rbind(avg.fpkms, avg.ID)
data <- data[data$ID != ID,]
}
data <- rbind(data, avg.fpkms)
}
IDs <- data[,1]
data <- as.matrix(data[,2:ncol(data)])
row.names(data) <- IDs
cat("Filtering entries based on min.val and groups...\n")
if (!is.null(groups)) {
data.factors <- as.data.frame(table(factor(groups)))
}
if (is.null(groups) || all.min.value) {
if (all.min.value) {
keep <- (apply(data, 1, min) > min.value)
} else {
keep <- (rowSums(data[,1:ncol(data)]) > min.value)
}
} else {
all.keeps <- list()
list.index <- 1
for(group.id in data.factors[,1]) {
group.keep <- which(rowSums(data[,which(groups==group.id)]) > min.value)
all.keeps[[list.index]] <- group.keep
list.index = list.index+1
}
keep <- Reduce(intersect, all.keeps)
}
data <- data[keep,]
num.genes <- nrow(data)
if (is.null(groups)) {
if (all.min.value) {
cat(" ", paste(num.genes, "entries had all samples with values >", min.value), "\n")
} else {
cat(" ", paste(num.genes, "entries had at least one sample with value >", min.value), "\n")
}
} else {
cat(" ", paste(num.genes, "entries had at least one sample per group with values >", min.value), "\n")
}
if(log2.transform) {
cat("Adding pseudo-counts and log2 transforming the data...", "\n")
cat(" You can turn this off by setting log2.transform to FALSE.", "\n")
data <- log2(data+1)
}
pca.data <- data.frame()
pc1 <- vector()
pc2 <- vector()
pc1.names <- vector()
pc2.names <- vector()
pca.var.per <- vector()
if (use.facto) {
cat("Using FactoMineR for analysis\n")
pca <- FactoMineR::PCA(t(data), ncp=5, graph=FALSE, scale.unit=TRUE)
pca.data <- list(x=pca$ind$coord[,c(1,2)])
pc1 <- pca$var$coord[,1]/sqrt(pca$eig[1,1])
pc2 <- pca$var$coord[,2]/sqrt(pca$eig[2,1])
pc1.names <- names(pc1)
pc2.names <- names(pc2)
pca.var.per <- round(pca$eig[,2], digits=1)
} else {
cat("Using prcomp for analysis\n")
pca <- prcomp(t(data), center=TRUE, scale. = TRUE, retx=TRUE)
pca.data <- list(x=pca$x[,c(1,2)])
pc1 <- pca$rotation[,1]
pc1.names <- names(pc1)
pc2 <- pca$rotation[,2]
pc2.names <- names(pc2)
pca.var <- pca$sdev^2
pca.var.per <- round(pca.var/sum(pca.var)*100, 1)
pca.var.cum <- cumsum(pca.var.per)
}
boot.points <- data.frame()
if (num.boot.samples > 0) {
cat("Bootstrapping the PCA at the entry level...\n")
gene.names <- rownames(data)
for (i in 1:num.boot.samples) {
cat("Bootstrap iteration:", i, "\n")
boot.indices <- sample(x=c(1:num.genes), size=num.genes, replace=TRUE)
boot.data <- data[boot.indices,]
boot.pc1 <- vector()
boot.pc2 <- vector()
if (use.facto) {
rownames(boot.data) <- c(1:nrow(boot.data))
pca.boot <- FactoMineR::PCA(t(boot.data), ncp=5, graph=FALSE, scale.unit=TRUE)
rownames(pca.boot$var$coord) <- gene.names[boot.indices]
pca.boot.data <- list(x=pca.boot$ind$coord[,c(1,2)])
boot.pc1 <- pca.boot$var$coord[,1]/sqrt(pca.boot$eig[1,1])
boot.pc2 <- pca.boot$var$coord[,2]/sqrt(pca.boot$eig[2,1])
} else {
pca.boot <- prcomp(t(boot.data), center=TRUE, scale. = TRUE, retx=TRUE)
pca.boot.data <- list(x=pca.boot$x[,c(1,2)])
boot.pc1 <- pca.boot$rotation[,1]
boot.pc2 <- pca.boot$rotation[,2]
}
if (correct.inversions) {
boot.pc1.names <- levels(factor(names(boot.pc1)))
pc1.cor <- cor(pc1[boot.pc1.names], boot.pc1[boot.pc1.names])
if (pc1.cor < 0) {
pca.boot.data$x[,1] <- pca.boot.data$x[,1] * -1
}
boot.pc2.names <- levels(factor(names(boot.pc2)))
pc2.cor <- cor(pc2[boot.pc1.names], boot.pc2[boot.pc1.names])
if (pc2.cor < 0) {
pca.boot.data$x[,2] <- pca.boot.data$x[,2] * -1
}
}
boot.points <- rbind(boot.points, pca.boot.data$x[,c(1,2)])
}
}
if (exists("data.factors")) {
if (length(data.factors[,1]) == 2) {
hex.colors <- RColorBrewer::brewer.pal(n=3, name="Set1")[1:2]
plot.col <- paste(rep(hex.colors, data.factors[,2]), transparency, sep="")
} else {
hex.colors <- RColorBrewer::brewer.pal(n=length(data.factors[,1]), name="Set1")
plot.col <- paste(rep(hex.colors, data.factors[,2]), transparency, sep="")
}
} else {
hex.colors <- RColorBrewer::brewer.pal(n=3, name="Set1")[1]
plot.col <- paste(hex.colors, transparency, sep="")
}
plot.pch <- 1
if (!is.null(groups)) {
plot.pch <- (groups)[1:ncol(data)]
}
radii <- NULL
return.samples.vector <- NULL
num.cells <- nrow(pca.data$x)
if (num.boot.samples > 0) {
if (confidence.regions | (trim.proportion > 0)) {
cat("Calculating ", round(confidence.size * 100, digits=2), "% confidence regions\n", sep="")
boot.points.by.cell <- cbind(boot.points, cell=c(1:num.cells))
min.points <- round(num.boot.samples * confidence.size)
radii <- vector(length=num.cells)
for (i in 1:num.cells) {
circle.center.x <- pca.data$x[i,1]
circle.center.y <- pca.data$x[i,2]
radius <- step.size
cell.points <- boot.points.by.cell[boot.points.by.cell$cell == i,c(1,2)]
done <- FALSE
while(!done) {
contained.points <- sum(((cell.points[,1] - circle.center.x)^2 +
(cell.points[,2] - circle.center.y)^2) <=
(radius^2))
if (contained.points >= min.points) {
done <- TRUE
} else {
radius <- radius + step.size
}
}
radii[i] <- radius
}
if (trim.proportion > 0) {
cat("Trimming samples with the most variation\n")
cat("\tThe top ", round(trim.proportion * 100, digits=2), "% will be removed\n", sep="")
radius.cutoff <- quantile(radii, (1-trim.proportion))
cutoff.indices <- which(radii >= radius.cutoff)
cat("\t", length(cutoff.indices), " samples were removed\n", sep="")
return.samples.vector <- c(1:num.samples)
return.samples.vector <- return.samples.vector[-cutoff.indices]
pca.data$x <- pca.data$x[-cutoff.indices,]
rownames(boot.points) <- c(1:nrow(boot.points))
for (i in 0:(num.boot.samples-1)) {
offset <- i * num.samples
boot.points[cutoff.indices + offset,] <- NA
}
na.indices <- which(is.na(boot.points[,1]))
boot.points <- boot.points[-na.indices,]
}
}
}
if (!confidence.regions) {
radii <- NULL
}
if (nrow(pca.data$x) > 0) {
draw.pcaBootPlot(pca=pca.data, boot.points=boot.points,
pca.var.per=pca.var.per,
num.boot.samples=num.boot.samples,
plot.col=plot.col,
plot.pch=plot.pch,
data.factors=data.factors,
draw.legend=draw.legend,
legend.names=legend.names,
legend.x=legend.x,
legend.y=legend.y,
hex.colors=hex.colors,
transparency=transparency,
min.x=min.x, max.x=max.x, min.y=min.y, max.y=max.y,
radii=radii)
if (!is.null(pdf.filename)) {
pdf(file=pdf.filename, width=pdf.width, height=pdf.height)
draw.pcaBootPlot(pca=pca.data, boot.points=boot.points,
pca.var.per=pca.var.per,
num.boot.samples=num.boot.samples,
plot.col=plot.col,
plot.pch=plot.pch,
data.factors=data.factors,
draw.legend=draw.legend,
legend.names=legend.names,
legend.x=legend.x,
legend.y=legend.y,
hex.colors=hex.colors,
transparency=transparency,
min.x=min.x, max.x=max.x, min.y=min.y, max.y=max.y,
radii=radii)
dev.off()
}
} else {
cat("\nThere were no points to plot! Bummer\n")
return()
}
cat("\nDone! Hooray!")
if (return.samples) {
return(return.samples.vector)
}
}
draw.pcaBootPlot <- function(pca=NULL, boot.points=NULL, pca.var.per=NULL,
num.boot.samples=100,
plot.col=NULL,
plot.pch=NULL,
data.factors=NULL,
draw.legend=FALSE, legend.names=NULL,
legend.x=NULL, legend.y=NULL,
hex.colors=NULL,
transparency=77,
min.x=NULL, max.x=NULL, min.y=NULL, max.y=NULL,
radii=NULL) {
if (num.boot.samples > 0 && (nrow(boot.points) > 0)) {
if (is.null(max.x)) {
max.x <- max(boot.points[,1], pca$x[,1], na.rm=TRUE)
}
if (is.null(min.x)) {
min.x <- min(boot.points[,1], pca$x[,1], na.rm=TRUE)
}
if (is.null(max.y)) {
max.y <- max(boot.points[,2], pca$x[,2], na.rm=TRUE)
}
if (is.null(min.y)) {
min.y <- min(boot.points[,2], pca$x[,2], na.rm=TRUE)
}
plot(boot.points, type="n", xlim=c(min.x, max.x), ylim=c(min.y, max.y), xlab=paste("PC1 (", pca.var.per[1], "%)", sep=""),
ylab=paste("PC2 (", pca.var.per[2], "%)", sep=""))
grid()
points(boot.points, pch=plot.pch, col=plot.col)
} else {
if (is.null(legend.x)) {
legend.x <- 0
}
if (is.null(legend.y)) {
legend.y <- 0
}
if ((!is.null(min.x)) & (!is.null(max.x))) {
x.lims <- c(min.x, max.x)
}
if ((!is.null(min.y)) & (!is.null(max.y))) {
y.lims <- c(min.y, max.y)
}
if (exists("x.lims") & exists("y.lims")) {
plot(pca$x[,c(1,2)], type="n",
xlab=paste("PC1 (", pca.var.per[1], "%)", sep=""),
ylab=paste("PC2 (", pca.var.per[2], "%)", sep=""),
xlim=x.lims, ylim=y.lims)
} else {
plot(pca$x[,c(1,2)], type="n",
xlab=paste("PC1 (", pca.var.per[1], "%)", sep=""),
ylab=paste("PC2 (", pca.var.per[2], "%)", sep=""))
}
grid()
}
if(!is.null(radii)) {
symbols(pca$x[,c(1,2)], circles=radii, add=TRUE, inches=FALSE, lty=2, col="
}
points(pca$x[,c(1,2)], pch=plot.pch)
if (draw.legend) {
if (is.null(legend.names)) {
legend.names <- c(1:length(data.factors[,1]))
}
legend(legend.x, legend.y, legend.names, pch=1:length(data.factors[,1]), pt.cex=1, cex=0.8, col=hex.colors[1:nrow(data.factors)])
}
}
|
lpridge <- function(x,y,bandwidth,
deriv = 0, n.out = 200,x.out = NULL, order = NULL,
ridge = NULL, weight = "epa", mnew = 100, var = FALSE)
{
n <- length(x)
if (length(y) != n) stop("Input grid and data must have the same length.")
sorvec <- sort.list(x)
x <- x[sorvec]
y <- y[sorvec]
if (is.null(x.out)) {
n.out <- as.integer(n.out)
x.out <- seq(min(x),max(x),length = n.out)
}
else {
n.out <- length(x.out)
}
if (length(bandwidth) == 1)
bandwidth <- rep(bandwidth,n.out)
else if (length(bandwidth) != n.out)
stop("Length of bandwith is not equal to length of output grid.")
sorvec <- sort.list(x.out)
x.out <- x.out[sorvec]
bandwidth <- bandwidth[sorvec]
if (is.null(order)) order <- deriv+1
if (order < 0) stop("Polynomial order is negative.")
if (deriv < 0) stop("Order of derivative is negative.")
if (deriv > order)
stop("Order of derivative is larger than polynomial order.")
if (is.null(ridge)) {
ridge <- 5*sqrt(length(x)*mean(bandwidth)/diff(range(x)))*
mean(bandwidth)^(2*deriv)/((2*deriv+3)*(2*deriv+5))
if (order == deriv) ridge <- 0
}
if (order == deriv & ridge > 0)
stop("ridging is impossible for order==deriv.")
if (weight == "epa") {
kord <- 2
wk <- c(1,0,-1)
}
else if (weight == "bi") {
kord <- 4
wk <- c(1,0,-2,0,1)
}
else if (weight == "tri") {
kord <- 6
wk <- c(1,0,-3,0,3,0,-1)
}
else if (is.numeric(weight)) {
kord <- length(weight)-1
wk <- weight
}
else stop("Error in weight.")
var <- as.logical(var)
leng <- 10
nmoms <- as.integer(length(x)/leng+1)
imoms <- integer(nmoms)
moms <- double(nmoms*4*(order+max(2,kord)+as.integer(var)))
if (order > 10)
stop("polynomial order exceeds 10.")
if ((kord+order) > 12)
stop("Order of kernel weights + polynomial order exceeds 12.")
res <- .Fortran(lpridge_s,
x = as.double(x),
y = as.double(y),
as.integer(n),
bandwidth = as.double(bandwidth),
deriv = as.integer(deriv),
order = as.integer(order),
kord = as.integer(kord),
wk = as.double(wk),
x.out = as.double(x.out),
as.integer(n.out),
mnew = as.integer(mnew),
as.integer(imoms),
as.double(moms),
est = double(n.out),
as.integer(leng),
as.integer(nmoms),
var = as.integer(var),
est.var = double(n.out),
ridge = as.double(ridge),
nsins = integer(1))[c("bandwidth", "est","est.var", "nsins")]
if (res$nsins > 0)
warning(res$nsins,
" singularity exceptions. Corresponding estimators set zero.")
list(x = x, y = y, bandwidth = res$bandwidth, deriv = deriv, x.out = x.out,
order = order, ridge = ridge, weight = wk, mnew = mnew,
var = var, est = res$est, est.var = res$est.var)
}
|
util_is_integer <- function(x, tol = .Machine$double.eps^0.5) {
if (is.numeric(x)) {
r <- abs(x - round(x)) < tol
} else {
r <- rep(FALSE, length(x))
}
r[is.na(r)] <- TRUE
r
}
|
frair_compare <- function(frfit1, frfit2, start=NULL){
if(!inherits(frfit1, 'frfit') | !inherits(frfit2, 'frfit')){
stop('Both inputs must be of class frfit')
}
if(frfit1$response!=frfit2$response){
stop('Both inputs must be fitted using the same response.')
}
fr_nll_difffunc <- get(paste0(frfit1$response,'_nll_diff'), pos = "package:frair")
if(any(frfit1$optimvars!=frfit2$optimvars)){
stop('Both inputs must have the same optimised variables.')
}
if(is.null(start)){
start <- list()
for(a in 1:length(frfit1$optimvars)){
cname <- frfit1$optimvars[a]
start[cname] <- mean(frfit1$coefficients[cname], frfit2$coefficients[cname])
}
} else {
fr_checkstart(start, deparse(substitute(start)))
}
varnames <- unlist(frair_responses(show=FALSE)[[frfit1$response]][4])
deltavarnames <- NULL
for(a in 1:length(varnames)){
deltavarname <- paste0('D',varnames[a])
start[deltavarname] <- 0
deltavarnames <- c(deltavarnames,deltavarname)
}
if(any(frfit1$fixedvars!=frfit2$fixedvars)){
stop('Both inputs must have the same fixed variables.')
}
fixed=list()
for(a in 1:length(frfit1$fixedvars)){
fname <- frfit1$fixedvars[a]
if(frfit1$coefficients[fname]!=frfit2$coefficients[fname]){
stop('Fixed variables must have the same numerical value')
}
fixed[fname] <- frfit1$coefficients[fname]
}
Xin <- c(frfit1$x,frfit2$x)
Yin <- c(frfit1$y,frfit2$y)
grp <- c(rep(0,times=length(frfit1$x)), rep(1,times=length(frfit2$x)))
if(length(unlist(start))>1){
try_test <- try(bbmle::mle2(minuslogl=fr_nll_difffunc, start=start, fixed=fixed,
data=list('X'=Xin, 'Y'=Yin, grp=grp), optimizer='optim',
method='Nelder-Mead', control=list(maxit=5000)),
silent=TRUE)
} else {
try_test <- try(bbmle::mle2(minuslogl=fr_nll_difffunc, start=start, fixed=fixed,
data=list('X'=Xin, 'Y'=Yin, grp=grp), optimizer='optim',
control=list(maxit=5000)),
silent=TRUE)
}
if(inherits(try_test, 'try-error')){
stop(paste0('Refitting the model for the test failed with the error: \n', try_test[1], '\nNo fallback exists, please contact the package author.'))
}
cmatall <- cbind(Estimate = try_test@coef, 'Std. Error' = sqrt(diag(try_test@vcov)))
zval <- cmatall[,'Estimate']/cmatall[,'Std. Error']
pval <- 2*pnorm(-abs(zval))
cmatall <- cbind(cmatall,'z value'=zval,'Pr(z)'=pval)
coefmatDeltas <- cmatall[deltavarnames,]
if(is.null(dim(coefmatDeltas))){
dim(coefmatDeltas) <- c(1,length(coefmatDeltas))
dimnames(coefmatDeltas) <- list(deltavarnames, c('Estimate', 'Std. Error', 'z value', 'Pr(z)'))
}
origcoef <- rbind(coef(frfit1)[frfit1$optimvars],coef(frfit2)[frfit1$optimvars])
row.names(origcoef) <- c(deparse(substitute(frfit1)), deparse(substitute(frfit2)))
cat('FUNCTIONAL RESPONSE COEFFICIENT TEST\n\n')
cat('Response: ', frfit1$response, '\n', sep='')
cat('Optimised variables: ', paste(frfit1$optimvars, collapse=','), '\n', sep='')
cat('Fixed variables: ', paste(frfit1$fixedvars, collapse=','), '\n\n', sep='')
cat('Original coefficients: \n')
print(round(origcoef,5))
cat('\n')
cat('Test: ', deparse(substitute(frfit1)), ' - ', deparse(substitute(frfit2)), '\n\n', sep='')
printCoefmat(round(coefmatDeltas,5))
output <- list(frfit1=frfit1, frfit2=frfit2, test_fit=try_test, result=coefmatDeltas)
class(output) <- c('frcompare', class(output))
invisible(output)
}
|
catconttable <- function(data, vars, byVar, vars.cat=NULL, fisher=NULL, fisher.arg=NULL,
cmh=NULL, row.score=NULL, col.score=NULL,
normal = NULL, var.equal = NULL,
median=NULL, odds=NULL, odds.scale=NULL, odds.unit=NULL,
none=NULL,
row.p=TRUE, alpha=0.05, B=1000, seed=NULL){
if (missing(byVar)){
byVar <- "PlAcE_hOlDeR_fOr_CaTcOnTtAbLe"
data[, byVar] <- factor("")
}
if (!all(vars %in% names(data))){
bad.vars <- vars[!vars %in% names(data)]
bad.vars.msg <- paste("The following variables are not found in 'data':", paste(bad.vars, collapse=", "))
stop(bad.vars.msg)
}
all.missing <- sapply(data[, c(vars, byVar)], function(x) all(is.na(x)))
if (any(all.missing)){
miss.vars <- c(vars, byVar)[all.missing]
miss.vars.msg <- paste("The following variables contain only missing values:", paste(miss.vars, collapse=", "))
stop(miss.vars.msg)
}
if ("tbl_df" %in% class(data)) data <- as.data.frame(data)
var.info <- function(v, ...){
if (!is.numeric(data[, v]) | v %in% vars.cat)
cattable(data=data, vars=v, byVar=byVar, fisher=fisher, fisher.arg=fisher.arg,
cmh=cmh, row.score=row.score, col.score=col.score,
odds=odds,
none=none, row.p=row.p, alpha=0.05)
else conttable(data=data, vars=v, byVar=byVar,
normal = normal, var.equal = var.equal, median=median,
odds = odds, odds.scale=odds.scale, odds.unit=odds.unit,
alpha = alpha, B=B, seed=seed)
}
ctable <- do.call("rbind", lapply(vars, var.info))
ctable$type <- factor(ctable$type)
data[[byVar]] <- labelVector::set_label(data[[byVar]],
labelVector::get_label(data, byVar))
attributes(ctable)$byVar <- data[, byVar]
attributes(ctable)$vars <- vars
return(ctable)
}
|
test_that("output are length one characters for some inputs", {
inputs <- list(
1, 1:10, list("a", TRUE, 3i), list(list(list()))
)
for (input in inputs) {
output <- default_hash_fn(input)
expect_vector(output, ptype = character(), size = 1L)
}
})
test_that("is equivalent to as.character() for atomic length-one input", {
inputs <- list(1L, 1, "1", 1i, TRUE, raw(1L))
for (input in inputs)
expect_identical(default_hash_fn(input), as.character(input))
})
test_that("Utility for collision handling works as expected", {
env <- new.env(); env[["1"]] <- "1"
key <- 1
hash <- as.character
compare <- identical
expect_identical(get_env_key(env, key, hash, compare), "10")
})
|
source("settings.r")
context("Checking plots example: forest plot with subgroups")
test_that("plot can be drawn.", {
expect_equivalent(TRUE, TRUE)
skip_on_cran()
opar <- par(no.readonly=TRUE)
par(mar=c(4,4,1,2))
res <- rma(ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat.bcg, measure="RR",
slab=paste(author, year, sep=", "), method="REML")
forest(res, xlim=c(-16, 6), at=log(c(.05, .25, 1, 4)), atransf=exp,
ilab=cbind(dat.bcg$tpos, dat.bcg$tneg, dat.bcg$cpos, dat.bcg$cneg),
ilab.xpos=c(-9.5,-8,-6,-4.5), cex=.75, ylim=c(-1, 27),
order=dat.bcg$alloc, rows=c(3:4,9:15,20:23),
xlab="Risk Ratio", mlab="", psize=1, header="Author(s) and Year")
text(-16, -1, pos=4, cex=0.75, bquote(paste("RE Model for All Studies (Q = ",
.(formatC(res$QE, digits=2, format="f")), ", df = ", .(res$k - res$p),
", p = ", .(formatC(res$QEp, digits=2, format="f")), "; ", I^2, " = ",
.(formatC(res$I2, digits=1, format="f")), "%)")))
op <- par(cex=.75, font=4)
text(-16, c(24,16,5), pos=4, c("Systematic Allocation",
"Random Allocation",
"Alternate Allocation"))
par(font=2)
text(c(-9.5,-8,-6,-4.5), 26, c("TB+", "TB-", "TB+", "TB-"))
text(c(-8.75,-5.25), 27, c("Vaccinated", "Control"))
par(op)
res.s <- rma(ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat.bcg, measure="RR",
subset=(alloc=="systematic"), method="REML")
res.r <- rma(ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat.bcg, measure="RR",
subset=(alloc=="random"), method="REML")
res.a <- rma(ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat.bcg, measure="RR",
subset=(alloc=="alternate"), method="REML")
addpoly(res.s, row=18.5, mlab="")
addpoly(res.r, row= 7.5, mlab="")
addpoly(res.a, row= 1.5, mlab="")
text(-16, 18.5, pos=4, cex=0.75, bquote(paste("RE Model for Subgroup (Q = ",
.(formatC(res.s$QE, digits=2, format="f")), ", df = ", .(res.s$k - res.s$p),
", p = ", .(formatC(res.s$QEp, digits=2, format="f")), "; ", I^2, " = ",
.(formatC(res.s$I2, digits=1, format="f")), "%)")))
text(-16, 7.5, pos=4, cex=0.75, bquote(paste("RE Model for Subgroup (Q = ",
.(formatC(res.r$QE, digits=2, format="f")), ", df = ", .(res.r$k - res.r$p),
", p = ", .(formatC(res.r$QEp, digits=2, format="f")), "; ", I^2, " = ",
.(formatC(res.r$I2, digits=1, format="f")), "%)")))
text(-16, 1.5, pos=4, cex=0.75, bquote(paste("RE Model for Subgroup (Q = ",
.(formatC(res.a$QE, digits=2, format="f")), ", df = ", .(res.a$k - res.a$p),
", p = ", .(formatC(res.a$QEp, digits=2, format="f")), "; ", I^2, " = ",
.(formatC(res.a$I2, digits=1, format="f")), "%)")))
par(opar)
})
rm(list=ls())
|
py_set_seed <- function(seed, disable_hash_randomization = TRUE) {
seed <- as.integer(seed)
if (disable_hash_randomization) {
os <- import("os")
Sys.setenv(PYTHONHASHSEED = "0")
os$environ[["PYTHONHASHSEED"]] <- "0"
}
random <- import("random")
random$seed(seed)
if (py_numpy_available()) {
np <- import("numpy")
np$random$seed(seed)
}
invisible(NULL)
}
|
m <- mean(life01); m
n <- length(life01); n
v <- var(life01) * (n-1) / n; v
m^2 / v
m / v
|
rrfNews <- function() {
newsfile <- file.path(system.file(package="RRF"), "NEWS")
file.show(newsfile)
}
|
cste_bin <- function(x, y, z, beta_ini = NULL, lam = 0, nknots = 1, max.iter = 200, eps = 1e-3) {
x <- as.matrix(x)
n <- dim(x)[1]
p <- dim(x)[2]
if(p==1) {
B1 <- B2 <- bs(x, df = nknots+4, intercept = TRUE)
B <- cbind(z * B1, B2)
fit <- glm.fit(B, y, family=binomial(link = 'logit'))
delta1 <- coef(fit)[1:(nknots+4)]
delta2 <- coef(fit)[(nknots+5):(2*nknots+8)]
geta <- z * B1 %*% delta1 + B2 %*% delta2
g1 <- B1 %*% delta1
g2 <- B2 %*% delta2
loss <- -sum(log(1 + exp(geta))) + sum(y * geta)
bic <- -2 * loss + (nknots+4) * log(n)
aic <- -2 * loss + 2 * (nknots+4)
out <- list(beta1 = 1, beta2 = 1, B1 = B1, B2 = B2, delta2 = delta2, delta1 = delta1, g = geta, x = x, y = y, z = z, nknots = nknots, p=p, g1=g1, g2=g2, bic=bic, aic=aic)
class(out) <- "cste"
return(out)
} else {
flag <- FALSE
truth <- rep(p,2)
if(is.null(beta_ini)) beta_ini <- c(normalize(rep(1, truth[1])), normalize(rep(1, truth[2])))
else beta_ini <- c(beta_ini[1:truth[1]], beta_ini[(truth[1]+1):sum(truth)])
beta_curr <- beta_ini
conv <- FALSE
iter <- 0
knots <- seq(0, 1, length = nknots + 2)
len.delta <- length(knots) + 2
while(conv == FALSE & iter < max.iter) {
iter <- iter + 1
beta1 <- beta_curr[1:truth[1]]
beta2 <- beta_curr[(truth[1]+1):length(beta_curr)]
u1 <- pu(x[,1:truth[1]], beta1)
u2 <- pu(x[,1:truth[2]], beta2)
eta1 <- u1$u
eta2 <- u2$u
B1 <- bsplineS(eta1, breaks = quantile(eta1, knots))
B2 <- bsplineS(eta2, breaks = quantile(eta2, knots))
B <- cbind(z*B1, B2)
fit.delta <- glm.fit(B, y, family=binomial(link = 'logit'))
delta <- drop(coef(fit.delta))
delta[is.na(delta)] <- 0
delta1 <- delta[1 : len.delta]
delta2 <- delta[(len.delta + 1) : (2*len.delta)]
B_deriv_1 <- bsplineS(eta1, breaks = quantile(eta1, knots), nderiv = 1)
B_deriv_2 <- bsplineS(eta2, breaks = quantile(eta2, knots), nderiv = 1)
newx_1 <- z * drop((B_deriv_1*(u1$deriv))%*%delta1)*x[,1:truth[1]]
newx_2 <- drop((B_deriv_2*(u2$deriv))%*%delta2)*x[,1:truth[2]]
newx <- cbind(newx_1, newx_2)
off_1 <- z * B1%*%delta1 - newx_1 %*% beta1
off_2 <- B2%*%delta2 - newx_2 %*% beta2
off <- off_1 + off_2
beta <- my_logit(newx, y, off, lam = lam)
if(sum(is.na(beta)) > 1){
break
stop("only 1 variable in betas; decrease lambda")
}
beta1 <- beta[1:truth[1]]
beta2 <- beta[(truth[1]+1):length(beta_curr)]
check <- c(sum(beta1!=0),sum(beta2!=0))
if(min(check) <= 1) {
stop("0 beta occurs; decrease lambda")
flag <- TRUE
if(check[1] != 0) beta[1:truth[1]] <- normalize(beta1)
if(check[2] !=0) beta[(truth[1]+1):length(beta_curr)] <- normalize(beta2)
break
}
beta <- c(normalize(beta1), normalize(beta2))
conv <- (max(abs(beta - beta_curr)) < eps)
beta_curr <- beta
}
geta <- z * B1 %*% delta1 + B2 %*% delta2
g1 <- B1 %*% delta1
g2 <- B2 %*% delta2
loss <- -sum(log(1 + exp(geta))) + sum(y * geta)
df1 <- sum(beta1!=0)
df2 <- sum(beta2!=0)
df <- df1 + df2 + 2*length(delta1)
bic <- -2 * loss + df * log(n) * log(p)
aic <- -2 * loss + 2 * df
out <- list(beta1 = beta[1:truth[1]], beta2 = beta[(truth[1]+1):length(beta_curr)], B1 = B1, B2 = B2, delta1 = delta1, delta2 = delta2, iter = iter, g = geta, g1 = g1, g2 = g2, loss = loss, df = df, df1 = df1, df2 = df2, bic = bic, aic = aic, x = x, y = y, z = z, knots = knots, flag = flag, p=p, conv=conv, final.x = newx, final.off = off)
class(out) <- "cste"
return(out)
}
}
|
brainGraph_mediate <- function(g.list, covars, mediator, treat,
outcome, covar.names, level=c('graph', 'vertex'),
control.value=0, treat.value=1, int=FALSE,
boot=TRUE, boot.ci.type=c('perc', 'bca'), N=1e3,
conf.level=0.95, long=FALSE, ...) {
region <- NULL
if (!is.brainGraphList(g.list)) try(g.list <- as_brainGraphList(g.list))
g.list <- g.list[]
stopifnot(all(hasName(covars, c(treat, outcome, covar.names))))
sID <- getOption('bg.subject_id')
if (!hasName(covars, sID)) covars[, eval(sID) := seq_len(dim(covars)[1L])]
covars[, eval(sID) := check_sID(get(sID))]
covars <- droplevels(covars[, c(sID, treat, covar.names, outcome), with=FALSE])
incomp <- covars[!complete.cases(covars), which=TRUE]
names(incomp) <- covars[incomp, get(sID)]
level <- match.arg(level)
dt.graph <- glm_data_table(g.list, level, mediator)
DT <- covars[dt.graph, on=sID]
if (length(incomp) > 0L) DT <- DT[-incomp]
DT[, eval(treat) := as.factor(get(treat))]
t.levels <- DT[, levels(get(treat))]
if (all(c(treat.value, control.value) %in% t.levels)) {
cat.0 <- control.value
cat.1 <- treat.value
} else {
stopifnot(is.numeric(c(control.value, treat.value)))
cat.0 <- t.levels[control.value + 1L]
cat.1 <- t.levels[treat.value + 1L]
}
cols <- c(sID, treat, covar.names)
X.m <- brainGraph_GLM_design(DT[, cols, with=FALSE], ...)
y.y <- DT[, get(outcome)]
treatstr <- paste0(treat, cat.1)
DT.m <- melt(DT, id.vars=names(covars), variable.name='region', value.name=mediator)
regions <- names(dt.graph)[-1L]
y.m <- as.matrix(DT[, c(sID, regions), with=FALSE], rownames=sID)
des_args <- list(...)
if (isTRUE(int)) des_args <- c(des_args, list(int=c(treat, mediator)))
cols <- append(cols, mediator, after=1L)
X.y <- lapply(regions, function(r)
do.call(brainGraph_GLM_design,
c(list(covars=DT.m[region == r, cols, with=FALSE]), des_args)))
names(X.y) <- regions
attrs <- attributes(X.y[[1L]])[-c(1L, 2L)]
X.y <- abind::abind(X.y, along=3L)
attributes(X.y) <- c(attributes(X.y), attrs)
if (!getDoParRegistered()) {
cl <- makeCluster(getOption('bg.ncpus'))
registerDoParallel(cl)
}
res_boot <- boot_mediate(X.m, y.m, X.y, y.y, mediator, treat, treatstr, int, N)
res_p <- as.data.table(pvalArray(res_boot, N, dim(y.m)[2L]), keep.rownames='region')
res_boot <- rbindlist(apply(res_boot, 3L, as.data.table), idcol='region')
res_obs <- res_boot[, .SD[.N], by=region]
res_boot <- res_boot[, .SD[-.N], by=region]
conf.limits <- (1 + c(-1, 1) * conf.level) / 2
if (isTRUE(boot)) {
boot.ci.type <- match.arg(boot.ci.type)
bootFun <- switch(boot.ci.type, perc=fastquant, bca=BC.CI2)
if (boot.ci.type == 'bca') conf.limits <- qnorm(conf.limits)
res_ci <- res_boot[, lapply(.SD, bootFun, conf.limits, N), by=region]
}
if (isFALSE(long)) res_boot <- NULL
out <- list(level=level, removed.subs=incomp, X.m=X.m, X.y=X.y, y.m=y.m, y.y=y.y,
res.obs=res_obs, res.ci=res_ci, res.p=res_p,
boot=boot, boot.ci.type=boot.ci.type, res.boot=res_boot,
treat=treat, mediator=mediator, outcome=outcome, covariates=NULL, INT=int,
conf.level=conf.level, control.value=cat.0, treat.value=cat.1,
nobs=dim(X.m)[1L], sims=N, covar.names=covar.names)
out$atlas <- guess_atlas(g.list[[1L]])
class(out) <- c('bg_mediate', class(out))
return(out)
}
boot_mediate <- function(X.m, y.m, X.y, y.y, mediator, treat, treatstr, int, N) {
b <- NULL
regions <- dimnames(y.m)[[2L]]
dimXm <- dim(X.m)
n <- dimXm[1L]
pm <- dimXm[2L]
dfRm <- n - pm
py <- dim(X.y)[2L]
ny <- dim(y.m)[2L]
index <- t(replicate(N, sample.int(n, replace=TRUE)))
index <- rbind(index, seq_len(n))
if (ny == 1L) {
Xyperm <- function(X, porder) X[porder, , , drop=FALSE]
Xyfun <- f_beta_3d_g
} else {
Xyperm <- function(X, porder) X[porder, , ]
Xyfun <- f_beta_3d
}
diagIndsY <- diag(1, n, py)
diagIndsM <- diag(1, n, pm)
ttMat <- matrix(c(1, 1, 1, 0, 0, 1,
0, 0, 1, 0, 0, 1,
1, 0, 1, 1, 0, 0,
1, 0, 0, 0, 1, 1),
nrow=6L)
effects.tmp <- array(NA, dim=c(n, 4L, ny))
vnames <- dimnames(X.y)[[2L]]
treatstrOther <- setdiff(grep(treat, dimnames(X.m)[[2L]], value=TRUE), treatstr)
Xcols <- c(mediator, treatstr)
if (isTRUE(int)) {
treatintstr <- paste0(treatstr, ':', mediator)
Xcols <- c(Xcols, treatintstr)
ecols <- 1L:4L
} else {
ecols <- c(1L, 3L)
}
bcols <- which(vnames %in% Xcols)
fun_effects <- function(Xy.diff, beta.y, Xcols, bcols, regions) {
X <- Xy.diff[, Xcols, ]
b <- beta.y[bcols, ]
vapply(regions, function(r) X[, , r] %*% b[, r], numeric(n))
}
res <- foreach(b=seq_len(N + 1L), .combine=rbind) %dopar% {
neworder <- index[b, ]
fits.m <- f_beta_m(X.m[neworder, ], y.m[neworder, ], diagIndsM, n, pm, ny, dfRm)
error <- vapply(fits.m$sigma, function(r) rnorm(n, mean=0, sd=r), numeric(n))
X.m.t <- X.m.c <- X.m
X.m.t[, treatstr] <- 1
X.m.c[, treatstr] <- 0
X.m.t[, treatstrOther] <- X.m.c[, treatstrOther] <- 0
PredictM1 <- X.m.t %*% fits.m$coefficients + error
PredictM0 <- X.m.c %*% fits.m$coefficients + error
beta.y <- Xyfun(Xyperm(X.y, neworder), y.y[neworder], regions, diagIndsY, n, py, ny)
for (e in ecols) {
X.y.t <- X.y.c <- X.y
X.y.t[, treatstr, ] <- ttMat[1L, e]
X.y.c[, treatstr, ] <- ttMat[2L, e]
X.y.t[, mediator, ] <- PredictM1 * ttMat[3L, e] + PredictM0 * ttMat[5L, e]
X.y.c[, mediator, ] <- PredictM1 * ttMat[4L, e] + PredictM0 * ttMat[6L, e]
if (isTRUE(int)) {
X.y.t[, treatintstr, ] <- X.y.t[, treatstr, ] * X.y.t[, mediator, ]
X.y.c[, treatintstr, ] <- X.y.c[, treatstr, ] * X.y.c[, mediator, ]
}
Xy.diff <- X.y.t - X.y.c
effects.tmp[, e, ] <- fun_effects(Xy.diff, beta.y, Xcols, bcols, regions)
}
return(colMeans(effects.tmp))
}
res <- array(res, dim=c(4L, N + 1L, ny))
if (isFALSE(int)) res[c(2L, 4L), , ] <- res[ecols, , ]
res2 <- array(dim=c(10L, N + 1L, ny))
res2[1L:4L, , ] <- res
res2 <- aperm(res2, c(2L, 1L, 3L))
dimnames(res2)[2L:3L] <- list(c('d1', 'd0', 'z1', 'z0', 'tau', 'n0', 'n1', 'd.avg', 'z.avg', 'n.avg'), regions)
res2[, 'd.avg', ] <- (res2[, 'd1', ] + res2[, 'd0', ]) / 2
res2[, 'z.avg', ] <- (res2[, 'z1', ] + res2[, 'z0', ]) / 2
res2[, 'tau', ] <- res2[, 'd.avg', ] + res2[, 'z.avg', ]
res2[, 'n0', ] <- res2[, 'd0', ] / res2[, 'tau', ]
res2[, 'n1', ] <- res2[, 'd1', ] / res2[, 'tau', ]
res2[, 'n.avg', ] <- (res2[, 'n1', ] + res2[, 'n0', ]) / 2
return(res2)
}
f_beta_m <- function(X, Y, diagMat, n, p, ny, dfR) {
QR <- qr.default(X, LAPACK=TRUE)
Q <- qr_Q2(QR, diagMat, n, p)
R <- qr_R2(QR, p)
beta <- backsolve(R, crossprod(Q, Y), p)
beta[QR$pivot, ] <- beta
ehat <- Y - X %*% beta
s <- if (ny == 1L) sum(ehat^2) else .colSums(ehat^2, n, ny)
list(coefficients=beta, sigma=sqrt(s / dfR))
}
f_beta_3d <- function(X, Y, regions, diagMat, n, p, ny) {
QR <- qr(X, LAPACK=TRUE)
Q <- lapply(QR, qr_Q2, diagMat, n, p)
R <- lapply(QR, qr_R2, p)
beta <- matrix(NaN, p, ny, dimnames=list(NULL, regions))
for (r in regions) {
beta[QR[[r]]$pivot, r] <- backsolve(R[[r]], crossprod(Q[[r]], Y), p)
}
beta
}
f_beta_3d_g <- function(X, Y, regions, diagMat, n, p, ny=1L) {
QR <- qr.default(X[, , 1L], LAPACK=TRUE)
Q <- qr_Q2(QR, diagMat, n, p)
R <- qr_R2(QR, p)
beta <- backsolve(R, crossprod(Q, Y), p)
beta[QR$pivot, ] <- beta
dimnames(beta) <- list(NULL, 'graph')
beta
}
pvalArray <- function(res_boot, N=dim(res_boot)[1L] - 1L, ny=dim(res_boot)[3L]) {
seqN <- seq_len(N)
gt0 <- colSums(res_boot[seqN, , ] > 0)
lt0 <- N - gt0
pMat <- 2 * pmin.int(gt0, lt0) / N
zeros <- which(res_boot[N + 1L, , ] == 0)
if (length(zeros) > 0L) pMat[zeros] <- 1
dim(pMat) <- c(10L, ny)
dimnames(pMat) <- dimnames(res_boot)[2L:3L]
t(pMat)
}
BC.CI2 <- function(theta, quants, N) {
avg <- sum(theta) / N
z.inv <- sum(theta < avg) / N
z <- qnorm(z.inv)
U <- (N - 1L) * (avg - theta)
U2 <- U^2
top <- sum(U * U2)
under <- 6 * (sum(U2))^1.5
a <- top / under
lower.upper <- pnorm(z + (z + quants) / (1 - a * (z + quants)))
fastquant(theta, lower.upper, N)
}
fastquant <- function(x, probs, N) {
index <- 1 + (N - 1) * probs
lo <- floor(index)
hi <- ceiling(index)
x <- sort(x, partial=unique(c(lo, hi)))
qs <- x[lo]
i <- which(index > lo & x[hi] != qs)
h <- (index - lo)[i]
qs[i] <- (1 - h) * qs[i] + h * x[hi[i]]
qs
}
summary.bg_mediate <- function(object, mediate=FALSE, region=NULL, digits=max(3L, getOption('digits') - 2L), ...) {
stopifnot(inherits(object, 'bg_mediate'))
Mediator <- treat <- Outcome <- NULL
DT.obs <- copy(object$res.obs)
DT.ci <- copy(object$res.ci)
DT.p <- copy(object$res.p)
setnames(DT.ci, c('region', paste0(names(DT.ci)[-1L], '.ci')))
setnames(DT.p, c('region', paste0(names(DT.p)[-1L], '.p')))
DT.all <- merge(merge(DT.obs, DT.p, by='region'), DT.ci, by='region')
DT.all[, c('Mediator', 'treat', 'Outcome') := with(object, mediator, treat, outcome)]
change <- matrix(c('d0', 'd0.p', 'z0', 'z0.p', 'tau', 'tau.p', 'n0', 'n0.p',
'b0.acme', 'p0.acme', 'b0.ade', 'p0.ade', 'b.tot', 'p.tot', 'b0.prop', 'p0.prop'),
ncol=2L)
setnames(DT.all, change[, 1L], change[, 2L])
change_ci <- change[seq.int(1L, 7L, 2L), ]
change_ci <- cbind(paste0(change_ci[, 1L], '.ci'),
sub('[bdnz]([01]?)\\.', 'ci.low\\1.', change_ci[, 2L]))
change_ci <- cbind(change_ci, sub('low', 'high', change_ci[, 2L]))
DT.all[, eval(change_ci[, 2L]) := lapply(.SD, function(x) x[1L]), by=region, .SDcols=change_ci[, 1L]]
DT.all[, eval(change_ci[, 3L]) := lapply(.SD, function(x) x[2L]), by=region, .SDcols=change_ci[, 1L]]
mainnames <- c('Mediator', 'treat', 'Outcome', 'region')
acme <- c('b0.acme', 'ci.low0.acme', 'ci.high0.acme', 'p0.acme')
total <- sub('0.acme', '.tot', acme)
if (isTRUE(object$INT)) {
change1 <- sub('0', '1', change)[-c(5L, 6L), ]
change1 <- rbind(change1, sub('1', '.avg', change1))
setnames(DT.all, change1[, 1L], change1[, 2L])
change_ci1 <- sub('0', '1', change_ci)[-3L, ]
change_ci1 <- rbind(change_ci1, sub('1', '.avg', change_ci1))
DT.all[, eval(change_ci1[, 2L]) := lapply(.SD, function(x) x[1L]), by=region, .SDcols=change_ci1[, 1L]]
DT.all[, eval(change_ci1[, 3L]) := lapply(.SD, function(x) x[2L]), by=region, .SDcols=change_ci1[, 1L]]
acme <- c(acme, sub('0', '1', acme), sub('0', '.avg', acme))
} else {
DT.all[, grep('1|avg', names(DT.all)) := NULL]
}
DT.all[, grep('.*.ci', names(DT.all)) := NULL]
setcolorder(DT.all, c(mainnames, acme, sub('acme', 'ade', acme), total, sub('acme', 'prop', acme)))
DT.all <- DT.all[, .SD[1L], keyby=region]
DT.all[, region := as.factor(region)]
object <- c(object, list(DT.sum=DT.all, region=region, digits=digits, mediate=mediate))
class(object) <- c('summary.bg_mediate', class(object))
return(object)
}
print.summary.bg_mediate <- function(x, ...) {
region <- NULL
width <- getOption('width') / 4
dashes <- rep.int('-', width)
print_title_summary(simpleCap(x$level), '-level mediation results')
cat('
message('\n', 'Variables', '\n', dashes)
df <- data.frame(A=c(' Mediator:', ' Treatment:', ' Control condition:',
' Treatment condition:', ' Outcome:'),
B=c(x$mediator, x$treat, x$control.value, x$treat.value, x$outcome))
cov.df <- data.frame(A=c('', 'Covariates:', rep.int('', length(x$covar.names) - 1L)),
B=c('', x$covar.names))
df <- rbind(df, cov.df)
dimnames(df)[[2L]] <- rep.int('', 2L)
print(df, right=FALSE, row.names=FALSE)
cat('\nTreatment-mediator interaction? ', x$INT, '\n\n')
print_subs_summary(x)
if (isTRUE(x$boot)) {
low <- (1 - x$conf.level) / 2
high <- 1 - low
message('\n', 'Bootstrapping', '\n', dashes)
ci <- switch(x$boot.ci.type,
perc='Percentile bootstrap',
bca='Bias-corrected accelerated')
cat('Bootstrap CI type: ', ci, '\n')
cat('
cat('Bootstrap CI level: ',
sprintf('[%s]', paste(paste0(100 * c(low, high), '%'), collapse=' ')), '\n\n')
}
if (isTRUE(x$mediate)) {
if (!requireNamespace('mediation', quietly=TRUE)) stop('Must install the "mediation" package.')
region <- if (is.null(x$region)) x$DT.sum[, levels(region)[1L]] else x$region
message('Mediation summary for: ', region, '\n', dashes)
print(summary(bg_to_mediate(x, region)))
} else {
if (is.null(x$region)) {
regions <- x$DT.sum[, levels(region)]
} else {
regions <- x$region
}
message('Mediation statistics', '\n', dashes)
print(x$DT.sum[region %in% regions])
}
invisible(x)
}
bg_to_mediate <- function(x, region=NULL) {
if (!inherits(x, c('bg_mediate', 'summary.bg_mediate'))) {
stop('Use only with \'bg_mediate\' objects!')
}
if (x$level == 'graph') {
res.obs <- x$res.obs
res.ci <- x$res.ci
res.p <- x$res.p
} else {
regions <- x$res.obs[, unique(region)]
if (is.null(region)) {
i <- 1L
} else {
i <- which(region == regions)
}
res.obs <- x$res.obs[region == regions[i]]
res.ci <- x$res.ci[region == regions[i]]
res.p <- x$res.p[region == regions[i]]
}
out <- list(d0=res.obs$d0, d1=res.obs$d1, d0.ci=res.ci$d0, d1.ci=res.ci$d1, d0.p=res.p$d0, d1.p=res.p$d1,
z0=res.obs$z0, z1=res.obs$z1, z0.ci=res.ci$z0, z1.ci=res.ci$z1, z0.p=res.p$z0, z1.p=res.p$z1,
n0=res.obs$n0, n1=res.obs$n1, n0.ci=res.ci$n0, n1.ci=res.ci$n1, n0.p=res.p$n0, n1.p=res.p$n1,
tau.coef=res.obs$tau, tau.ci=res.ci$tau, tau.p=res.p$tau,
d.avg=res.obs$d.avg, d.avg.ci=res.ci$d.avg, d.avg.p=res.p$d.avg,
z.avg=res.obs$z.avg, z.avg.ci=res.ci$z.avg, z.avg.p=res.p$z.avg,
n.avg=res.obs$n.avg, n.avg.ci=res.ci$n.avg, n.avg.p=res.p$n.avg,
boot=x$boot, boot.ci.type=x$boot.ci.type, treat=x$treat, mediator=x$mediator, covariates=x$covariates,
INT=x$INT, control.value=x$control.value, treat.value=x$treat.value, nobs=x$nobs, sims=x$sims,
robustSE=FALSE, cluster=NULL)
class(out) <- 'mediate'
return(out)
}
|
inferTTree = function(ptree, w.shape=2, w.scale=1, ws.shape=NA, ws.scale=NA,
w.mean=NA,w.std=NA,ws.mean=NA,ws.std=NA,mcmcIterations=1000,
thinning=1, startNeg=100/365, startOff.r=1, startOff.p=0.5, startPi=0.5, updateNeg=TRUE,
updateOff.r=TRUE, updateOff.p=FALSE, updatePi=TRUE, startCTree=NA, updateTTree=TRUE,
optiStart=2, dateT=Inf,verbose=F) {
ptree$ptree[,1]=ptree$ptree[,1]+runif(nrow(ptree$ptree))*1e-10
if (dateT<dateLastSample(ptree)) stop('The parameter dateT cannot be smaller than the date of last sample')
for (i in (ceiling(nrow(ptree$ptree)/2)+1):nrow(ptree$ptree)) for (j in 2:3)
if (ptree$ptree[ptree$ptree[i,j],1]-ptree$ptree[i,1]<0)
stop("The phylogenetic tree contains negative branch lengths!")
if (!is.na( w.mean)&&!is.na( w.std)) { w.shape= w.mean^2/ w.std^2; w.scale= w.std^2/ w.mean}
if (!is.na(ws.mean)&&!is.na(ws.std)) {ws.shape=ws.mean^2/ws.std^2;ws.scale=ws.std^2/ws.mean}
if (is.na(ws.shape)) ws.shape=w.shape
if (is.na(ws.scale)) ws.scale=w.scale
neg <- startNeg
off.r <- startOff.r
off.p <- startOff.p
pi <- startPi
if (is.na(sum(startCTree))) ctree <- makeCTreeFromPTree(ptree,off.r,off.p,neg,pi,w.shape,w.scale,ws.shape,ws.scale,dateT,optiStart)
else ctree<-startCTree
ttree <- extractTTree(ctree)
record <- vector('list',mcmcIterations/thinning)
pTTree <- probTTree(ttree$ttree,off.r,off.p,pi,w.shape,w.scale,ws.shape,ws.scale,dateT)
pPTree <- probPTreeGivenTTree(ctree$ctree,neg)
if (verbose==F) pb <- utils::txtProgressBar(min=0,max=mcmcIterations,style = 3)
for (i in 1:mcmcIterations) {
if (i%%thinning == 0) {
if (verbose==F) utils::setTxtProgressBar(pb, i)
if (verbose==T) message(sprintf('it=%d,neg=%f,off.r=%f,off.p=%f,pi=%f,Prior=%e,Likelihood=%e,nind=%d',i,neg,off.r,off.p,pi,pTTree,pPTree,nrow(ttree$ttree)))
record[[i/thinning]]$ctree <- ctree
record[[i/thinning]]$pTTree <- pTTree
record[[i/thinning]]$pPTree <- pPTree
record[[i/thinning]]$neg <- neg
record[[i/thinning]]$off.r <- off.r
record[[i/thinning]]$off.p <- off.p
record[[i/thinning]]$pi <- pi
record[[i/thinning]]$w.shape <- w.shape
record[[i/thinning]]$w.scale <- w.scale
record[[i/thinning]]$ws.shape <- ws.shape
record[[i/thinning]]$ws.scale <- ws.scale
record[[i/thinning]]$source <- ctree$ctree[ctree$ctree[which(ctree$ctree[,4]==0),2],4]
if (record[[i/thinning]]$source<=length(ctree$nam)) record[[i/thinning]]$source=ctree$nam[record[[i/thinning]]$source] else record[[i/thinning]]$source='Unsampled'
}
if (updateTTree) {
if (verbose) message("Proposing ttree update")
prop <- proposal(ctree$ctree)
ctree2 <- list(ctree=prop$tree,nam=ctree$nam)
class(ctree2)<-'ctree'
ttree2 <- extractTTree(ctree2)
pTTree2 <- probTTree(ttree2$ttree,off.r,off.p,pi,w.shape,w.scale,ws.shape,ws.scale,dateT)
pPTreeDiff <- probPTreeGivenTTree(ctree2$ctree,neg,prop$new)-probPTreeGivenTTree(ctree$ctree,neg,prop$old)
if (log(runif(1)) < log(prop$qr)+pTTree2+pPTreeDiff-pTTree) {
ctree <- ctree2
ttree <- ttree2
pTTree <- pTTree2
pPTree <- pPTree+pPTreeDiff
}
}
if (updateNeg) {
neg2 <- abs(neg + (runif(1)-0.5)*0.5)
if (verbose) message(sprintf("Proposing Ne*g update %f->%f",neg,neg2))
pPTree2 <- probPTreeGivenTTree(ctree$ctree,neg2)
if (log(runif(1)) < pPTree2-pPTree-neg2+neg) {neg <- neg2;pPTree <- pPTree2}
}
if (updateOff.r) {
off.r2 <- abs(off.r + (runif(1)-0.5)*0.5)
if (verbose) message(sprintf("Proposing off.r update %f->%f",off.r,off.r2))
pTTree2 <- probTTree(ttree$ttree,off.r2,off.p,pi,w.shape,w.scale,ws.shape,ws.scale,dateT)
if (log(runif(1)) < pTTree2-pTTree-off.r2+off.r) {off.r <- off.r2;pTTree <- pTTree2}
}
if (updateOff.p) {
off.p2 <- abs(off.p + (runif(1)-0.5)*0.1)
if (off.p2>1) off.p2=2-off.p2
if (verbose) message(sprintf("Proposing off.p update %f->%f",off.p,off.p2))
pTTree2 <- probTTree(ttree$ttree,off.r,off.p2,pi,w.shape,w.scale,ws.shape,ws.scale,dateT)
if (log(runif(1)) < pTTree2-pTTree) {off.p <- off.p2;pTTree <- pTTree2}
}
if (updatePi) {
pi2 <- pi + (runif(1)-0.5)*0.1
if (pi2<0.01) pi2=0.02-pi2
if (pi2>1) pi2=2-pi2
if (verbose) message(sprintf("Proposing pi update %f->%f",pi,pi2))
pTTree2 <- probTTree(ttree$ttree,off.r,off.p,pi2,w.shape,w.scale,ws.shape,ws.scale,dateT)
if (log(runif(1)) < pTTree2-pTTree) {pi <- pi2;pTTree <- pTTree2}
}
}
class(record)<-'resTransPhylo'
return(record)
}
|
context("db")
test_that("invalid db type", {
expect_error(orderly_db("xxx", "example"),
"Invalid db type 'xxx'")
})
test_that("custom fields", {
path <- tempfile()
orderly_init(path)
file_copy("example_config.yml", file.path(path, "orderly_config.yml"),
overwrite = TRUE)
con <- orderly_db("destination", path)
on.exit(DBI::dbDisconnect(con))
expect_true(DBI::dbExistsTable(con, "orderly_schema"))
config <- orderly_config(path)
expect_error(report_db_init(con, config, TRUE),
"Table 'orderly_schema' already exists")
DBI::dbExecute(con, "DELETE FROM custom_fields WHERE id = 'author'")
expect_error(report_db_init(con, config, FALSE),
"custom fields 'author' not present in existing database")
unlockBinding(quote(fields), config)
config$fields <- NULL
expect_error(report_db_init(con, config, FALSE),
"custom fields 'requester', 'comments' in database")
})
test_that("rebuild empty database", {
skip_on_cran_windows()
path <- tempfile()
orderly_init(path)
file_copy("example_config.yml", file.path(path, "orderly_config.yml"),
overwrite = TRUE)
orderly_rebuild(path)
con <- orderly_db("destination", path)
on.exit(DBI::dbDisconnect(con))
expect_true(DBI::dbExistsTable(con, "orderly_schema"))
})
test_that("rebuild nonempty database", {
skip_on_cran_windows()
path <- test_prepare_orderly_example("minimal")
id <- orderly_run("example", root = path, echo = FALSE)
orderly_commit(id, root = path)
file.remove(file.path(path, "orderly.sqlite"))
orderly_rebuild(path)
orderly_rebuild(path)
con <- orderly_db("destination", path)
on.exit(DBI::dbDisconnect(con))
expect_equal(nrow(DBI::dbReadTable(con, "report_version")), 1)
})
test_that("no transient db", {
config <- list(destination = list(
driver = c("RSQLite", "SQLite"),
args = list(dbname = ":memory:")),
root = tempdir())
expect_error(orderly_db_args(config$destination, config = config),
"Cannot use a transient SQLite database with orderly")
})
test_that("db includes parameters", {
skip_on_cran_windows()
path <- test_prepare_orderly_example("demo")
id <- orderly_run("other", parameters = list(nmin = 0.1), root = path,
echo = FALSE)
orderly_commit(id, root = path)
con <- orderly_db("destination", root = path)
d <- DBI::dbReadTable(con, "parameters")
DBI::dbDisconnect(con)
expect_equal(d, data_frame(id = 1,
report_version = id,
name = "nmin",
type = "number",
value = "0.1"))
})
test_that("different parameter types are stored correctly", {
skip_on_cran_windows()
path <- test_prepare_orderly_example("parameters", testing = TRUE)
id <- orderly_run("example", parameters = list(a = 1, b = TRUE, c = "one"),
root = path, echo = FALSE)
orderly_commit(id, root = path)
con <- orderly_db("destination", root = path)
d <- DBI::dbReadTable(con, "parameters")
DBI::dbDisconnect(con)
expect_equal(d, data_frame(id = 1:3,
report_version = id,
name = c("a", "b", "c"),
type = c("number", "boolean", "text"),
value = c("1", "true", "one")))
})
test_that("avoid unserialisable parameters", {
t <- Sys.Date()
expect_error(report_db_parameter_type(t), "Unsupported parameter type")
expect_error(report_db_parameter_serialise(t), "Unsupported parameter type")
})
test_that("dialects", {
skip_on_cran()
s <- report_db_schema_read(NULL, "sqlite")
p <- report_db_schema_read(NULL, "postgres")
expect_false(isTRUE(all.equal(s, p)))
path <- test_prepare_orderly_example("minimal")
config <- orderly_config_$new(path)
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
on.exit(DBI::dbDisconnect(con))
expect_error(report_db_init_create(con, config, "postgres"),
"syntax error")
expect_silent(report_db_init_create(con, config, "sqlite"))
expect_equal(report_db_dialect(con), "sqlite")
expect_equal(report_db_dialect(structure(TRUE, class = "PqConnection")),
"postgres")
expect_error(report_db_dialect(structure(TRUE, class = "other")),
"Can't determine SQL dialect")
})
test_that("sources are listed in db", {
skip_on_cran_windows()
path <- test_prepare_orderly_example("demo")
id <- orderly_run("other", root = path, parameters = list(nmin = 0),
echo = FALSE)
orderly_commit(id, root = path)
con <- orderly_db("destination", root = path)
on.exit(DBI::dbDisconnect(con))
p <- path_orderly_run_rds(file.path(path, "archive", "other", id))
info <- readRDS(p)$meta$file_info_inputs
h <- hash_files(file.path(path, "archive", "other", id, "functions.R"), FALSE)
expect_equal(info$filename[info$file_purpose == "source"], "functions.R")
expect_equal(info$file_hash[info$file_purpose == "source"], h)
d <- DBI::dbGetQuery(
con, "SELECT * from file_input WHERE report_version = $1", id)
expect_false("resource" %in% d$file_purpose)
expect_true("source" %in% d$file_purpose)
})
test_that("backup", {
skip_on_cran_windows()
path <- create_orderly_demo()
expect_message(
orderly_backup(path),
"orderly.sqlite => backup/db/orderly.sqlite",
fixed = TRUE)
dest <- path_db_backup(path, "orderly.sqlite")
expect_true(file.exists(dest))
dat_orig <- with_sqlite(file.path(path, "orderly.sqlite"), function(con)
DBI::dbReadTable(con, "report_version"))
dat_backup <- with_sqlite(dest, function(con)
DBI::dbReadTable(con, "report_version"))
expect_equal(dat_orig, dat_backup)
})
test_that("db includes custom fields", {
skip_on_cran_windows()
path <- test_prepare_orderly_example("demo")
id <- orderly_run("minimal", root = path, echo = FALSE)
orderly_commit(id, root = path)
con <- orderly_db("destination", root = path)
on.exit(DBI::dbDisconnect(con))
d <- DBI::dbReadTable(con, "report_version_custom_fields")
expect_equal(d$report_version, rep(id, 3))
v <- c("requester", "author", "comment")
expect_setequal(d$key, v)
expect_equal(d$value[match(v, d$key)],
c("Funder McFunderface",
"Researcher McResearcherface",
"This is a comment"))
})
test_that("db includes file information", {
skip_on_cran_windows()
path <- test_prepare_orderly_example("demo")
id <- orderly_run("multifile-artefact", root = path, echo = FALSE)
p <- orderly_commit(id, root = path)
h1 <- hash_files(
file.path(path, "src", "multifile-artefact", "orderly.yml"), FALSE)
h2 <- hash_files(
file.path(path, "src", "multifile-artefact", "script.R"), FALSE)
con <- orderly_db("destination", root = path)
on.exit(DBI::dbDisconnect(con))
file_input <- DBI::dbReadTable(con, "file_input")
expect_equal(
file_input,
data_frame(id = 1:2,
report_version = id,
file_hash = c(h1, h2),
filename = c("orderly.yml", "script.R"),
file_purpose = c("orderly_yml", "script")))
info <- readRDS(path_orderly_run_rds(p))$meta$file_info_artefacts
artefact_hash <- info$file_hash
file_artefact <- DBI::dbReadTable(con, "file_artefact")
expect_equal(
file_artefact,
data_frame(id = 1:2,
artefact = 1,
file_hash = artefact_hash,
filename = c("mygraph.png", "mygraph.pdf")))
report_version_artefact <- DBI::dbReadTable(con, "report_version_artefact")
expect_equal(
report_version_artefact,
data_frame(id = 1,
report_version = id,
format = "staticgraph",
description = "A graph of things",
order = 1))
filenames <- c("orderly.yml", "script.R", "mygraph.png", "mygraph.pdf")
file <- DBI::dbReadTable(con, "file")
expect_equal(file,
data_frame(hash = c(h1, h2,
artefact_hash),
size = file_size(file.path(p, filenames))))
})
test_that("connect to database instances", {
path <- test_prepare_orderly_example("minimal")
p <- file.path(path, "orderly_config.yml")
writeLines(c(
"database:",
" source:",
" driver: RSQLite::SQLite",
" args:",
" dbname: source.sqlite",
" instances:",
" staging:",
" dbname: staging.sqlite",
" production:",
" dbname: production.sqlite"),
p)
f <- function(x) {
basename(x$source@dbname)
}
expect_equal(
f(orderly_db("source", root = path)),
"staging.sqlite")
expect_equal(
f(orderly_db("source", root = path, instance = "staging")),
"staging.sqlite")
expect_equal(
f(orderly_db("source", root = path, instance = "production")),
"production.sqlite")
})
test_that("db instance select", {
config_db <- list(
x = list(
driver = c("RSQLite", "SQLite"),
args = list(name = "a"),
instances = list(
a = list(name = "a"),
b = list(name = "b"))),
y = list(
driver = c("RSQLite", "SQLite"),
args = list(name = "y")))
config_db_a <- modifyList(config_db, list(x = list(instance = "a")))
config_db_b <- modifyList(config_db, list(x = list(args = list(name = "b"),
instance = "b")))
expect_identical(db_instance_select(NULL, config_db), config_db_a)
expect_equal(db_instance_select("a", config_db), config_db_a)
expect_equal(db_instance_select("b", config_db), config_db_b)
expect_equal(db_instance_select(c(x = "a"), config_db), config_db_a)
expect_equal(db_instance_select(c(x = "b"), config_db), config_db_b)
expect_error(db_instance_select("c", config_db),
"Invalid instance 'c' for database 'x'")
expect_error(db_instance_select(c(x = "c"), config_db),
"Invalid instance: 'c' for 'x'")
expect_error(db_instance_select(c(z = "a"), config_db),
"Invalid database name 'z' in provided instance")
})
test_that("db instance select with two instanced databases", {
config_db <- list(
x = list(
driver = c("RSQLite", "SQLite"),
args = list(name = "b"),
instances = list(
b = list(name = "b"),
a = list(name = "a"))),
y = list(
driver = c("RSQLite", "SQLite"),
args = list(name = "c"),
instances = list(
c = list(name = "c"),
a = list(name = "a"))))
config_db_aa <- modifyList(config_db,
list(x = list(args = list(name = "a"),
instance = "a"),
y = list(args = list(name = "a"),
instance = "a")))
config_db_bc <- modifyList(config_db, list(x = list(instance = "b"),
y = list(instance = "c")))
config_db_ac <- modifyList(config_db,
list(x = list(args = list(name = "a"),
instance = "a"),
y = list(args = list(name = "c"),
instance = "c")))
expect_identical(db_instance_select(NULL, config_db), config_db_bc)
expect_equal(db_instance_select("a", config_db), config_db_aa)
expect_equal(db_instance_select(c(x = "a", y = "a"), config_db),
config_db_aa)
expect_equal(db_instance_select(c(x = "b", y = "c"), config_db),
config_db_bc)
expect_equal(db_instance_select(c(x = "a"), config_db), config_db_ac)
expect_error(db_instance_select("f", config_db),
"Invalid instance 'f' for databases 'x', 'y'")
expect_error(db_instance_select(c(x = "f", y = "g"), config_db),
"Invalid instances: 'f' for 'x', 'g' for 'y'")
expect_error(db_instance_select(c(z = "a"), config_db),
"Invalid database name 'z' in provided instance")
})
test_that("db instance select rejects instance when no dbs support it", {
config_db <- list(
x = list(
driver = c("RSQLite", "SQLite"),
args = list(name = "a")),
y = list(
driver = c("RSQLite", "SQLite"),
args = list(name = "b")))
expect_identical(db_instance_select(NULL, config_db), config_db)
expect_error(db_instance_select("a", config_db),
"Can't specify 'instance' with no databases supporting it")
})
test_that("Create and verify tags on startup", {
root <- test_prepare_orderly_example("minimal")
append_lines(c("tags:", " - tag1", " - tag2"),
file.path(root, "orderly_config.yml"))
con <- orderly_db("destination", root = root)
expect_equal(DBI::dbReadTable(con, "tag"),
data_frame(id = c("tag1", "tag2")))
DBI::dbDisconnect(con)
append_lines(" - tag3", file.path(root, "orderly_config.yml"))
expect_error(
orderly_db("destination", root = root),
"tags have changed: rebuild with orderly::orderly_rebuild()",
fixed = TRUE)
orderly_rebuild(root)
con <- orderly_db("destination", root = root)
expect_equal(DBI::dbReadTable(con, "tag"),
data_frame(id = c("tag1", "tag2", "tag3")))
DBI::dbDisconnect(con)
})
test_that("Add tags to db", {
root <- test_prepare_orderly_example("minimal")
append_lines(c("tags:", " - tag1", " - tag2"),
file.path(root, "orderly_config.yml"))
append_lines(c("tags:", " - tag1"),
file.path(root, "src", "example", "orderly.yml"))
id <- orderly_run("example", root = root, echo = FALSE)
p <- orderly_commit(id, root = root)
con <- orderly_db("destination", root)
on.exit(DBI::dbDisconnect(con))
expect_equal(
DBI::dbReadTable(con, "report_version_tag"),
data_frame(id = 1, report_version = id, tag = "tag1"))
})
test_that("add batch info to db", {
path <- test_prepare_orderly_example("parameters", testing = TRUE)
params <- data_frame(
a = c("one", "two", "three"),
b = c(1, 2, 3)
)
batch_id <- ids::random_id()
mockery::stub(orderly_batch, "ids::random_id", batch_id)
ids <- orderly_batch("example", parameters = params,
root = path, echo = FALSE)
p <- lapply(ids, function(id) {
orderly_commit(id, root = path)
})
con <- orderly_db("destination", path)
on.exit(DBI::dbDisconnect(con))
expect_equal(
DBI::dbReadTable(con, "report_batch"),
data_frame(id = batch_id))
expect_equal(
DBI::dbReadTable(con, "report_version_batch"),
data_frame(report_version = ids, report_batch = rep(batch_id, 3)))
})
test_that("trailing slash in report name is tolerated", {
path <- test_prepare_orderly_example("minimal")
id <- orderly_run("src/example/", root = path, echo = FALSE)
expect_error(orderly_commit(id, root = path), NA)
})
test_that("db includes elapsed time", {
skip_on_cran_windows()
path <- test_prepare_orderly_example("minimal")
id <- orderly_run("example", root = path, echo = FALSE)
p <- orderly_commit(id, root = path)
con <- orderly_db("destination", root = path)
on.exit(DBI::dbDisconnect(con))
d <- DBI::dbReadTable(con, "report_version")
expect_true(d$elapsed > 0)
expect_equal(d$elapsed,
readRDS(path_orderly_run_rds(p))$meta$elapsed)
})
test_that("rebuild nonempty database with backup", {
skip_on_cran_windows()
path <- test_prepare_orderly_example("minimal")
id <- orderly_run("example", root = path, echo = FALSE)
orderly_commit(id, root = path)
con <- orderly_db("destination", path)
DBI::dbExecute(con, "UPDATE report_version SET published = 1")
DBI::dbDisconnect(con)
orderly_rebuild(path)
files <- dir(file.path(path, "backup/db"))
expect_equal(length(files), 1)
expect_match(files, "^orderly\\.sqlite\\.[0-9]{8}-[0-9]{6}$")
con1 <- orderly_db("destination", path)
con2 <- DBI::dbConnect(RSQLite::SQLite(),
dbname = file.path(path, "backup/db", files))
expect_equal(
DBI::dbReadTable(con1, "report_version")$published, 0)
expect_equal(
DBI::dbReadTable(con2, "report_version")$published, 1)
DBI::dbDisconnect(con1)
DBI::dbDisconnect(con2)
})
test_that("db write collision", {
skip_on_cran()
path <- test_prepare_orderly_example("minimal")
id1 <- orderly_run("example", root = path, echo = FALSE)
id2 <- orderly_run("example", root = path, echo = FALSE)
orderly_commit(id1, root = path)
con <- orderly_db("destination", root = path)
on.exit(DBI::dbDisconnect(con))
DBI::dbExecute(con, "BEGIN IMMEDIATE")
DBI::dbExecute(con, "DELETE FROM file_artefact")
elapsed <- system.time(
testthat::expect_error(
orderly_commit(id2, root = path, timeout = 5),
"database is locked"))
expect_true(elapsed["elapsed"] > 5)
DBI::dbRollback(con)
p <- orderly_commit(id2, root = path)
ids <- DBI::dbGetQuery(con, "SELECT id from report_version")$id
expect_equal(length(ids), 2)
expect_setequal(ids, c(id1, id2))
})
test_that("db includes instance", {
skip_on_cran_windows()
path <- test_prepare_orderly_example("minimal")
p <- file.path(path, "orderly_config.yml")
writeLines(c(
"database:",
" source:",
" driver: RSQLite::SQLite",
" instances:",
" default:",
" dbname: source.sqlite",
" alternative:",
" dbname: alternative.sqlite"),
p)
file.copy(file.path(path, "source.sqlite"),
file.path(path, "alternative.sqlite"))
id1 <- orderly_run("example", root = path, echo = FALSE)
id2 <- orderly_run("example", root = path, echo = FALSE,
instance = "default")
id3 <- orderly_run("example", root = path, echo = FALSE,
instance = "alternative")
orderly_commit(id1, root = path)
orderly_commit(id2, root = path)
orderly_commit(id3, root = path)
con <- orderly_db("destination", root = path)
d <- DBI::dbReadTable(con, "report_version_instance")
DBI::dbDisconnect(con)
expect_equal(d,
data_frame(id = c(1, 2, 3),
report_version = c(id1, id2, id3),
type = rep("source", 3),
instance = c("default", "default", "alternative")))
})
test_that("Can cope when all fields are optional", {
path <- test_prepare_orderly_example("minimal")
append_lines(
c("fields:",
" requester:",
" required: false",
" author:",
" required: false"),
file.path(path, "orderly_config.yml"))
id <- orderly_run("example", root = path, echo = FALSE)
orderly_commit(id, root = path)
db <- orderly_db("destination", root = path)
expect_equal(nrow(DBI::dbReadTable(db, "report_version_custom_fields")), 0)
})
|
ceRNA.enrich <-
function(data,GOterms,background,threshold=2,correction="BH"){
goname<-names(GOterms)
index<-numeric()
for(i in 1:length(goname)){
comm<-intersect(GOterms[[goname[i]]],background)
if(length(comm)!=0){
assign(goname[i],comm)
index<-c(index,i)
}
}
goname<-goname[index]
goterm_num<-as.data.frame(matrix(nrow=length(goname),ncol=2))
colnames(goterm_num)<-c("goterm","go_num")
goterm_num[,1]<-goname
for(j in 1:length(goname)){goterm_num[j,2]<-length(get(goname[j]))}
tar<-sort(as.character(unique(data[,1])))
tar_num<-as.data.frame(matrix(ncol=2,nrow=length(tar)))
tar_num[,1]<-tar
colnames(tar_num)<-c("tar","tarnum")
inter<-list()
for(j in 1:length(tar)){
tmptar<-unique(data[data[,1]==tar[j],2])
tmptar_num<-length(tmptar)
tmpinter<-numeric()
for(k in goname){
tmpinter<-append(tmpinter,length(intersect(tmptar,get(k))))
}
inter[[j]]<-tmpinter
tar_num[j,2]<-length(tmptar)
}
interd<-unlist(inter)
tard<-sort(rep(tar,length(goname)))
gotermd<-rep(goname,length(tar))
result<-as.data.frame(cbind(tard,gotermd))
result<-cbind(result,interd)
colnames(result)<-c("tar","goterm","internum")
result<-result[result[,"internum"]>=threshold,]
result<-merge(result,goterm_num)
result<-merge(result,tar_num)
backnum<-length(background)
pvalue<-apply(result[,c("tarnum","go_num","internum")],1,function(x){return(1-phyper(x[3],x[1],backnum-x[1],x[2]))})
result<-result[,c("tar","goterm","tarnum","go_num","internum")]
result<-cbind(result,pvalue)
fdr<-p.adjust(result[,"pvalue"],method=correction)
result<-cbind(result,fdr)
colnames(result)<-c("target","GOterm","target_num","GOtermnum","term_tar","P_value","fdr")
return(result)
}
|
use_circle_yml <- function(type = "linux-matrix-deploy",
write = TRUE,
quiet = FALSE) {
if (type == "linux") {
template <- readLines(system.file("templates/circle.yml", package = "tic"))
} else if (type == "linux-matrix") {
template <- readLines(system.file("templates/circle-matrix.yml",
package = "tic"
))
} else if (type == "linux-deploy") {
template <- readLines(system.file("templates/circle-deploy.yml",
package = "tic"
))
} else if (type == "linux-deploy-matrix" || type == "linux-matrix-deploy") {
template <- readLines(system.file("templates/circle-deploy-matrix.yml",
package = "tic"
))
}
dir.create(".circleci", showWarnings = FALSE)
if (!write) {
return(template)
} else {
writeLines(template, ".circleci/config.yml")
}
if (!quiet) {
cat_bullet(
"Below is the file structure of the new/changed files:",
bullet = "arrow_down", bullet_col = "blue"
)
data <- data.frame(
stringsAsFactors = FALSE,
package = c(
basename(getwd()), ".circleci", "config.yml"
),
dependencies = I(list(
".circleci", "config.yml", character(0)
))
)
print(tree(data, root = basename(getwd())))
}
}
use_ghactions_yml <- function(type = "linux-macos-windows-deploy",
write = TRUE,
quiet = FALSE) {
usethis::use_build_ignore(c(".ccache", ".github"))
if (type == "linux-matrix" || type == "linux") {
meta <- readLines(system.file("templates/ghactions-meta-linux.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
template <- c(meta, env, core)
} else if (type == "linux-matrix-deploy" || type == "linux-deploy-matrix" || type == "linux-deploy") {
meta <- readLines(system.file("templates/ghactions-meta-linux-deploy.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
deploy <- readLines(system.file("templates/ghactions-deploy.yml", package = "tic"))
template <- c(meta, env, core, deploy)
} else if (type == "macos-matrix" || type == "macos") {
meta <- readLines(system.file("templates/ghactions-meta-macos.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
template <- c(meta, env, core)
} else if (type == "macos-matrix-deploy" || type == "macos-deploy-matrix" || type == "macos-deploy") {
meta <- readLines(system.file("templates/ghactions-meta-macos-deploy.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
deploy <- readLines(system.file("templates/ghactions-deploy.yml", package = "tic"))
template <- c(meta, env, core, deploy)
} else if (type == "windows-matrix" || type == "windows") {
meta <- readLines(system.file("templates/ghactions-meta-windows.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
template <- c(meta, env, core)
} else if (type == "windows-matrix-deploy" || type == "windows-deploy-matrix" || type == "windows-deploy") {
meta <- readLines(system.file("templates/ghactions-meta-windows-deploy.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
deploy <- readLines(system.file("templates/ghactions-deploy.yml", package = "tic"))
template <- c(meta, env, core, deploy)
} else if (type == "linux-macos" || type == "linux-macos-matrix") {
meta <- readLines(system.file("templates/ghactions-meta-linux-macos.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
template <- c(meta, env, core)
} else if (type == "linux-macos-deploy" || type == "linux-macos-deploy-matrix") {
meta <- readLines(system.file("templates/ghactions-meta-linux-macos.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
deploy <- readLines(system.file("templates/ghactions-deploy.yml", package = "tic"))
template <- c(meta, env, core, deploy)
} else if (type == "linux-windows" || type == "linux-windows-matrix") {
meta <- readLines(system.file("templates/ghactions-meta-linux-windows.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
template <- c(meta, env, core)
} else if (type == "linux-windows-deploy" || type == "linux-windows-deploy-matrix") {
meta <- readLines(system.file("templates/ghactions-meta-linux-windows.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
deploy <- readLines(system.file("templates/ghactions-deploy.yml", package = "tic"))
template <- c(meta, env, core, deploy)
} else if (type == "macos-windows" || type == "macos-windows-matrix") {
meta <- readLines(system.file("templates/ghactions-meta-macos-windows.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
template <- c(meta, env, core)
} else if (type == "macos-windows-deploy" || type == "macos-windows-deploy-matrix") {
meta <- readLines(system.file("templates/ghactions-meta-macos-windows.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
deploy <- readLines(system.file("templates/ghactions-deploy.yml", package = "tic"))
template <- c(meta, env, core, deploy)
} else if (type == "linux-macos-windows") {
meta <- readLines(system.file("templates/ghactions-meta.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
template <- c(meta, env, core)
} else if (type == "linux-macos-windows-deploy" || type == "all") {
meta <- readLines(system.file("templates/ghactions-meta.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
deploy <- readLines(system.file("templates/ghactions-deploy.yml", package = "tic"))
template <- c(meta, env, core, deploy)
} else if (type == "custom") {
meta <- readLines(system.file("templates/ghactions-meta-custom.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
template <- c(meta, env, core)
} else if (type == "custom-deploy") {
meta <- readLines(system.file("templates/ghactions-meta-custom-deploy.yml", package = "tic"))
env <- readLines(system.file("templates/ghactions-env.yml", package = "tic"))
core <- readLines(system.file("templates/ghactions-core.yml", package = "tic"))
deploy <- readLines(system.file("templates/ghactions-deploy.yml", package = "tic"))
template <- c(meta, env, core, deploy)
}
dir.create(".github/workflows", showWarnings = FALSE, recursive = TRUE)
if (!quiet) {
cli::cli_alert_info("Please comment in/out the platforms you want to use
in {.file .github/workflows/tic.yml}.", wrap = TRUE)
cli::cli_text("Call {.code usethis::edit_file('.github/workflows/tic.yml')}
to open the YAML file.")
}
if (!write) {
return(template)
}
cli::cli_alert_info("Writing {.file .github/workflows/tic.yml}.")
writeLines(template, con = ".github/workflows/tic.yml")
if (!quiet) {
cat_bullet(
"Below is the file structure of the new/changed files:",
bullet = "arrow_down", bullet_col = "blue"
)
data <- data.frame(
stringsAsFactors = FALSE,
package = c(
basename(getwd()), ".github", "workflows", "tic.yml"
),
dependencies = I(list(
".github", "workflows", "tic.yml", character(0)
))
)
print(tree(data, root = basename(getwd())))
}
}
use_tic_template <- function(template, save_as = template, open = FALSE,
ignore = TRUE, data = NULL) {
usethis::use_template(
template, save_as,
package = "tic", open = open, ignore = ignore, data = data
)
}
|
legend <-
function(x, y = NULL, legend, fill = NULL, col = par("col"), border="black",
lty, lwd, pch, angle = 45, density = NULL, bty = "o", bg = par("bg"),
box.lwd = par("lwd"), box.lty = par("lty"), box.col = par("fg"),
pt.bg = NA, cex = 1, pt.cex = cex, pt.lwd = lwd,
xjust = 0, yjust = 1, x.intersp = 1, y.intersp = 1, adj = c(0, 0.5),
text.width = NULL, text.col = par("col"), text.font = NULL,
merge = do.lines && has.pch, trace = FALSE,
plot = TRUE, ncol = 1, horiz = FALSE, title = NULL,
inset = 0, xpd, title.col = text.col, title.adj = 0.5,
seg.len = 2)
{
if(missing(legend) && !missing(y) &&
(is.character(y) || is.expression(y))) {
legend <- y
y <- NULL
}
mfill <- !missing(fill) || !missing(density)
if(!missing(xpd)) {
op <- par("xpd")
on.exit(par(xpd=op))
par(xpd=xpd)
}
title <- as.graphicsAnnot(title)
if(length(title) > 1) stop("invalid 'title'")
legend <- as.graphicsAnnot(legend)
n.leg <- if(is.call(legend)) 1 else length(legend)
if(n.leg == 0) stop("'legend' is of length 0")
auto <-
if (is.character(x))
match.arg(x, c("bottomright", "bottom", "bottomleft", "left",
"topleft", "top", "topright", "right", "center"))
else NA
if (is.na(auto)) {
xy <- xy.coords(x, y, setLab = FALSE); x <- xy$x; y <- xy$y
nx <- length(x)
if (nx < 1 || nx > 2) stop("invalid coordinate lengths")
} else nx <- 0
xlog <- par("xlog")
ylog <- par("ylog")
rect2 <- function(left, top, dx, dy, density = NULL, angle, ...) {
r <- left + dx; if(xlog) { left <- 10^left; r <- 10^r }
b <- top - dy; if(ylog) { top <- 10^top; b <- 10^b }
rect(left, top, r, b, angle = angle, density = density, ...)
}
segments2 <- function(x1, y1, dx, dy, ...) {
x2 <- x1 + dx; if(xlog) { x1 <- 10^x1; x2 <- 10^x2 }
y2 <- y1 + dy; if(ylog) { y1 <- 10^y1; y2 <- 10^y2 }
segments(x1, y1, x2, y2, ...)
}
points2 <- function(x, y, ...) {
if(xlog) x <- 10^x
if(ylog) y <- 10^y
points(x, y, ...)
}
text2 <- function(x, y, ...) {
if(xlog) x <- 10^x
if(ylog) y <- 10^y
text(x, y, ...)
}
if(trace)
catn <- function(...)
do.call("cat", c(lapply(list(...),formatC), list("\n")))
cin <- par("cin")
Cex <- cex * par("cex")
if(is.null(text.width))
text.width <- max(abs(strwidth(legend, units="user",
cex=cex, font = text.font)))
else if(!is.numeric(text.width) || text.width < 0)
stop("'text.width' must be numeric, >= 0")
xc <- Cex * xinch(cin[1L], warn.log=FALSE)
yc <- Cex * yinch(cin[2L], warn.log=FALSE)
if(xc < 0) text.width <- -text.width
xchar <- xc
xextra <- 0
yextra <- yc * (y.intersp - 1)
ymax <- yc * max(1, strheight(legend, units="user", cex=cex)/yc)
ychar <- yextra + ymax
if(trace) catn(" xchar=", xchar, "; (yextra,ychar)=", c(yextra,ychar))
if(mfill) {
xbox <- xc * 0.8
ybox <- yc * 0.5
dx.fill <- xbox
}
do.lines <- (!missing(lty) && (is.character(lty) || any(lty > 0))
) || !missing(lwd)
n.legpercol <-
if(horiz) {
if(ncol != 1)
warning(gettextf("horizontal specification overrides: Number of columns := %d",
n.leg), domain = NA)
ncol <- n.leg
1
} else ceiling(n.leg / ncol)
has.pch <- !missing(pch) && length(pch) > 0
if(do.lines) {
x.off <- if(merge) -0.7 else 0
} else if(merge)
warning("'merge = TRUE' has no effect when no line segments are drawn")
if(has.pch) {
if(is.character(pch) && !is.na(pch[1L]) &&
nchar(pch[1L], type = "c") > 1) {
if(length(pch) > 1)
warning("not using pch[2..] since pch[1L] has multiple chars")
np <- nchar(pch[1L], type = "c")
pch <- substr(rep.int(pch[1L], np), 1L:np, 1L:np)
}
if(!is.character(pch)) pch <- as.integer(pch)
}
if (is.na(auto)) {
if (xlog) x <- log10(x)
if (ylog) y <- log10(y)
}
if(nx == 2) {
x <- sort(x)
y <- sort(y)
left <- x[1L]
top <- y[2L]
w <- diff(x)
h <- diff(y)
w0 <- w/ncol
x <- mean(x)
y <- mean(y)
if(missing(xjust)) xjust <- 0.5
if(missing(yjust)) yjust <- 0.5
}
else {
h <- (n.legpercol + !is.null(title)) * ychar + yc
w0 <- text.width + (x.intersp + 1) * xchar
if(mfill) w0 <- w0 + dx.fill
if(do.lines) w0 <- w0 + (seg.len + x.off)*xchar
w <- ncol*w0 + .5* xchar
if (!is.null(title)
&& (abs(tw <- strwidth(title, units="user", cex=cex) + 0.5*xchar)) > abs(w)) {
xextra <- (tw - w)/2
w <- tw
}
if (is.na(auto)) {
left <- x - xjust * w
top <- y + (1 - yjust) * h
} else {
usr <- par("usr")
inset <- rep_len(inset, 2)
insetx <- inset[1L]*(usr[2L] - usr[1L])
left <- switch(auto, "bottomright" =,
"topright" =, "right" = usr[2L] - w - insetx,
"bottomleft" =, "left" =, "topleft" = usr[1L] + insetx,
"bottom" =, "top" =, "center" = (usr[1L] + usr[2L] - w)/2)
insety <- inset[2L]*(usr[4L] - usr[3L])
top <- switch(auto, "bottomright" =,
"bottom" =, "bottomleft" = usr[3L] + h + insety,
"topleft" =, "top" =, "topright" = usr[4L] - insety,
"left" =, "right" =, "center" = (usr[3L] + usr[4L] + h)/2)
}
}
if (plot && bty != "n") {
if(trace)
catn(" rect2(", left, ",", top,", w=", w, ", h=", h, ", ...)",
sep = "")
rect2(left, top, dx = w, dy = h, col = bg, density = NULL,
lwd = box.lwd, lty = box.lty, border = box.col)
}
xt <- left + xchar + xextra +
(w0 * rep.int(0:(ncol-1), rep.int(n.legpercol,ncol)))[1L:n.leg]
yt <- top - 0.5 * yextra - ymax -
(rep.int(1L:n.legpercol,ncol)[1L:n.leg] - 1 + !is.null(title)) * ychar
if (mfill) {
if(plot) {
if(!is.null(fill)) fill <- rep_len(fill, n.leg)
rect2(left = xt, top=yt+ybox/2, dx = xbox, dy = ybox,
col = fill,
density = density, angle = angle, border = border)
}
xt <- xt + dx.fill
}
if(plot && (has.pch || do.lines))
col <- rep_len(col, n.leg)
if(missing(lwd) || is.null(lwd))
lwd <- par("lwd")
if (do.lines) {
if(missing(lty) || is.null(lty)) lty <- 1
lty <- rep_len(lty, n.leg)
lwd <- rep_len(lwd, n.leg)
ok.l <- !is.na(lty) & (is.character(lty) | lty > 0) & !is.na(lwd)
if(trace)
catn(" segments2(",xt[ok.l] + x.off*xchar, ",", yt[ok.l],
", dx=", seg.len*xchar, ", dy=0, ...)")
if(plot)
segments2(xt[ok.l] + x.off*xchar, yt[ok.l],
dx = seg.len*xchar, dy = 0,
lty = lty[ok.l], lwd = lwd[ok.l], col = col[ok.l])
xt <- xt + (seg.len+x.off) * xchar
}
if (has.pch) {
pch <- rep_len(pch, n.leg)
pt.bg <- rep_len(pt.bg, n.leg)
pt.cex <- rep_len(pt.cex, n.leg)
pt.lwd <- rep_len(pt.lwd, n.leg)
ok <- !is.na(pch)
if (!is.character(pch)) {
ok <- ok & (pch >= 0 | pch <= -32)
} else {
ok <- ok & nzchar(pch)
}
x1 <- (if(merge && do.lines) xt-(seg.len/2)*xchar else xt)[ok]
y1 <- yt[ok]
if(trace)
catn(" points2(", x1,",", y1,", pch=", pch[ok],", ...)")
if(plot)
points2(x1, y1, pch = pch[ok], col = col[ok],
cex = pt.cex[ok], bg = pt.bg[ok], lwd = pt.lwd[ok])
}
xt <- xt + x.intersp * xchar
if(plot) {
if (!is.null(title))
text2(left + w*title.adj, top - ymax, labels = title,
adj = c(title.adj, 0), cex = cex, col = title.col)
text2(xt, yt, labels = legend, adj = adj, cex = cex,
col = text.col, font = text.font)
}
invisible(list(rect = list(w = w, h = h, left = left, top = top),
text = list(x = xt, y = yt)))
}
|
kegg_enrichment <- function(...) {
lifecycle::deprecate_warn("0.2.0",
"kegg_enrichment()",
"calculate_kegg_enrichment()",
details = "This function has been renamed."
)
calculate_kegg_enrichment(...)
}
calculate_kegg_enrichment <- function(data,
protein_id,
is_significant,
pathway_id = pathway_id,
pathway_name = pathway_name,
plot = TRUE,
plot_cutoff = "adj_pval top10") {
. <- NULL
n_sig <- NULL
kegg_term <- NULL
data <- data %>%
dplyr::ungroup() %>%
dplyr::distinct({{ protein_id }}, {{ is_significant }}, {{ pathway_id }}, {{ pathway_name }}) %>%
tidyr::drop_na() %>%
dplyr::mutate({{ pathway_name }} := stringr::str_extract({{ pathway_name }}, ".*(?=\\s\\-\\s)")) %>%
tidyr::unite(col = "kegg_term", {{ pathway_id }}, {{ pathway_name }}, sep = ";") %>%
dplyr::group_by({{ protein_id }}) %>%
tidyr::nest(kegg_term = .data$kegg_term) %>%
dplyr::distinct({{ protein_id }}, {{ is_significant }}, .data$kegg_term) %>%
dplyr::group_by({{ protein_id }}) %>%
dplyr::mutate({{ is_significant }} := ifelse(sum({{ is_significant }}, na.rm = TRUE) > 0,
TRUE,
FALSE
)) %>%
dplyr::distinct()
if (sum(dplyr::pull(data, {{ is_significant }})) == 0) {
stop(strwrap("None of the significant proteins has any associated pathway
in the KEGG database. No pathway enrichment could be computed.",
prefix = "\n", initial = ""
))
}
if (length(unique(pull(data, {{ protein_id }}))) != nrow(data)) {
stop(strwrap("The data frame contains more rows than unique proteins. Make sure that
there are no double annotations.\nThere could be for example proteins annotated as significant
and not significant.", prefix = "\n", initial = ""))
}
cont_table <- data %>%
dplyr::group_by({{ is_significant }}) %>%
dplyr::mutate(n_sig = dplyr::n()) %>%
tidyr::unnest(.data$kegg_term) %>%
dplyr::mutate(kegg_term = stringr::str_trim(.data$kegg_term)) %>%
dplyr::group_by(.data$kegg_term, {{ is_significant }}) %>%
dplyr::mutate(n_has_pathway = dplyr::n()) %>%
dplyr::distinct(.data$kegg_term, {{ is_significant }}, .data$n_sig, .data$n_has_pathway) %>%
dplyr::ungroup() %>%
tidyr::complete(kegg_term, tidyr::nesting(!!rlang::ensym(is_significant), n_sig), fill = list(n_has_pathway = 0))
fisher_test <- cont_table %>%
split(dplyr::pull(., kegg_term)) %>%
purrr::map(.f = ~ dplyr::select(.x, -kegg_term) %>%
tibble::column_to_rownames(var = rlang::as_name(enquo(is_significant))) %>%
as.matrix() %>%
fisher.test()) %>%
purrr::map2_df(
.y = names(.),
.f = ~ tibble::tibble(
pval = .x$p.value,
kegg_term = .y
)
)
result_table <- cont_table %>%
dplyr::left_join(fisher_test, by = "kegg_term") %>%
dplyr::mutate(adj_pval = stats::p.adjust(.data$pval, method = "BH")) %>%
dplyr::group_by(.data$kegg_term) %>%
dplyr::mutate(
n_detected_proteins = sum(.data$n_sig),
n_detected_proteins_in_pathway = sum(.data$n_has_pathway),
n_significant_proteins = ifelse({{ is_significant }} == TRUE, .data$n_sig, NA),
n_significant_proteins_in_pathway = ifelse({{ is_significant }} == TRUE, .data$n_has_pathway, NA)
) %>%
tidyr::drop_na() %>%
dplyr::select(-c({{ is_significant }}, .data$n_sig, .data$n_has_pathway)) %>%
dplyr::mutate(n_proteins_expected = round(
.data$n_significant_proteins / .data$n_detected_proteins * .data$n_detected_proteins_in_pathway,
digits = 2
)) %>%
dplyr::mutate(direction = ifelse(.data$n_proteins_expected < .data$n_significant_proteins_in_pathway, "Up", "Down")) %>%
tidyr::separate(.data$kegg_term, c("pathway_id", "pathway_name"), ";") %>%
dplyr::arrange(.data$pval)
if (plot == FALSE) {
return(result_table)
}
if (stringr::str_detect(plot_cutoff, pattern = "top10")) {
split_cutoff <- stringr::str_split(plot_cutoff, pattern = " ", simplify = TRUE)
type <- split_cutoff[1]
plot_input <- result_table %>%
dplyr::ungroup() %>%
dplyr::mutate(neg_log_sig = -log10(!!rlang::ensym(type))) %>%
dplyr::slice(1:10)
} else {
split_cutoff <- stringr::str_split(plot_cutoff, pattern = " ", simplify = TRUE)
type <- split_cutoff[1]
threshold <- as.numeric(split_cutoff[2])
plot_input <- result_table %>%
dplyr::ungroup() %>%
dplyr::mutate(neg_log_sig = -log10(!!rlang::ensym(type))) %>%
dplyr::filter(!!rlang::ensym(type) <= threshold)
}
enrichment_plot <- plot_input %>%
ggplot2::ggplot(ggplot2::aes(stats::reorder(.data$pathway_name, .data$neg_log_sig), .data$neg_log_sig, fill = .data$direction)) +
ggplot2::geom_col(col = "black", size = 1.5) +
ggplot2::scale_fill_manual(values = c(Down = "
ggplot2::scale_y_continuous(breaks = seq(0, 100, 2)) +
ggplot2::coord_flip() +
ggplot2::labs(title = "KEGG pathway enrichment of significant proteins", y = "-log10 adjusted p-value") +
ggplot2::theme_bw() +
ggplot2::theme(
plot.title = ggplot2::element_text(
size = 20
),
axis.text.x = ggplot2::element_text(
size = 15
),
axis.text.y = ggplot2::element_text(
size = 15
),
axis.title.x = ggplot2::element_text(
size = 15
),
axis.title.y = ggplot2::element_blank()
)
return(enrichment_plot)
}
|
tb1simpleUI <- function(id) {
ns <- NS(id)
tagList(
uiOutput(ns("base")),
uiOutput(ns("sub2"))
)
}
tb1simple <- function(input, output, session, data, matdata, data_label, data_varStruct = NULL, group_var, showAllLevels = T){
variable <- NULL
if (is.null(data_varStruct)){
data_varStruct = list(variable = names(data))
}
if (!("data.table" %in% class(data))) {data = data.table(data)}
if (!("data.table" %in% class(data_label))) {data_label = data.table(data_label)}
factor_vars <- names(data)[data[, lapply(.SD, class) %in% c("factor", "character")]]
factor_list <- mklist(data_varStruct, factor_vars)
conti_vars <- setdiff(names(data), c(factor_vars, "pscore", "iptw"))
conti_list <- mklist(data_varStruct, conti_vars)
nclass_factor <- unlist(data[, lapply(.SD, function(x){length(unique(x)[!is.na(unique(x))])}), .SDcols = factor_vars])
group_vars <- factor_vars[nclass_factor >=2 & nclass_factor <=10 & nclass_factor < nrow(data)]
group_list <- mklist(data_varStruct, group_vars)
except_vars <- factor_vars[nclass_factor > 10 | nclass_factor == 1 | nclass_factor == nrow(data)]
f <- function(x) {
if (diff(range(x, na.rm = T)) == 0) return(F) else return(shapiro.test(x)$p.value <= 0.05)
}
non_normal <- ifelse(nrow(data) <=3 | nrow(data) >= 5000,
rep(F, length(conti_vars)),
sapply(conti_vars, function(x){f(data[[x]])})
)
output$base <- renderUI({
tagList(
selectInput(session$ns("nonnormal_vars"), "Non-normal variable (continuous)",
choices = conti_list, multiple = T,
selected = conti_vars[non_normal]
),
sliderInput(session$ns("decimal_tb1_con"), "Digits (continuous)",
min = 1, max = 3, value = 1
),
sliderInput(session$ns("decimal_tb1_cat"), "Digits (categorical, %)",
min = 1, max = 3, value = 1
),
sliderInput(session$ns("decimal_tb1_p"), "Digits (p)",
min = 3, max = 5, value = 3
),
checkboxInput(session$ns("smd"), "Show SMD", T),
selectInput(session$ns("group2_vars"), "Stratified by (optional)",
choices = c("None", mksetdiff(group_list, group_var)), multiple = F,
selected = "None")
)
})
output$sub2 <- renderUI({
req(!is.null(input$group2_vars))
if (input$group2_vars == 'None') return(NULL)
tagList(
checkboxInput(session$ns("psub"), "Subgroup p-values", T)
)
})
labelled::var_label(data) = sapply(names(data), function(v){data_label[variable == v, var_label][1]}, simplify = F)
out <- reactive({
vars <- setdiff(setdiff(names(data),except_vars), group_var)
Svydesign <- survey::svydesign(ids = ~ 1, data = data, weights = ~ iptw)
if (input$group2_vars == "None"){
vars.tb1 = setdiff(vars, c(group_var, "pscore", "iptw"))
res = jstable::CreateTableOneJS(data = data,
vars = vars.tb1, strata = group_var, includeNA = F, test = T,
testApprox = chisq.test, argsApprox = list(correct = TRUE),
testExact = fisher.test, argsExact = list(workspace = 2 * 10^7),
testNormal = oneway.test, argsNormal = list(var.equal = F),
testNonNormal = kruskal.test, argsNonNormal = list(NULL),
showAllLevels = showAllLevels, printToggle = F, quote = F, smd = input$smd, Labels = T, exact = NULL, nonnormal = input$nonnormal_vars,
catDigits = input$decimal_tb1_cat, contDigits = input$decimal_tb1_con, pDigits = input$decimal_tb1_p, labeldata = data_label)
res.ps = jstable::CreateTableOneJS(data = matdata,
vars = vars.tb1, strata = group_var, includeNA = F, test = T,
testApprox = chisq.test, argsApprox = list(correct = TRUE),
testExact = fisher.test, argsExact = list(workspace = 2 * 10^7),
testNormal = oneway.test, argsNormal = list(var.equal = F),
testNonNormal = kruskal.test, argsNonNormal = list(NULL),
showAllLevels = showAllLevels, printToggle = F, quote = F, smd = input$smd, Labels = T, exact = NULL, nonnormal = input$nonnormal_vars,
catDigits = input$decimal_tb1_cat, contDigits = input$decimal_tb1_con, pDigits = input$decimal_tb1_p, labeldata = data_label)
res.iptw <- jstable::svyCreateTableOneJS(data = Svydesign, vars = vars.tb1, strata = group_var, includeNA = F, test = T,
showAllLevels = showAllLevels, printToggle = F, quote = F, smd = input$smd, Labels = T, nonnormal = input$nonnormal_vars,
catDigits = input$decimal_tb1_cat, contDigits = input$decimal_tb1_con, pDigits = input$decimal_tb1_p, labeldata = data_label)
} else{
vars.tb1 = setdiff(vars, c(group_var, input$group2_vars, "pscore", "iptw"))
res = jstable::CreateTableOneJS(data = data,
vars = vars.tb1, strata = input$group2_vars, strata2 = group_var, includeNA = F, test = T,
testApprox = chisq.test, argsApprox = list(correct = TRUE),
testExact = fisher.test, argsExact = list(workspace = 2 * 10^7),
testNormal = oneway.test, argsNormal = list(var.equal = F),
testNonNormal = kruskal.test, argsNonNormal = list(NULL),
showAllLevels = showAllLevels, printToggle = F, quote = F, smd = input$smd, Labels = T, exact = NULL, nonnormal = input$nonnormal_vars,
catDigits = input$decimal_tb1_cat, contDigits = input$decimal_tb1_con, pDigits = input$decimal_tb1_p, labeldata = data_label, psub = input$psub)
res.ps = jstable::CreateTableOneJS(data = matdata,
vars = vars.tb1, strata = input$group2_vars, strata2 = group_var, includeNA = F, test = T,
testApprox = chisq.test, argsApprox = list(correct = TRUE),
testExact = fisher.test, argsExact = list(workspace = 2 * 10^7),
testNormal = oneway.test, argsNormal = list(var.equal = F),
testNonNormal = kruskal.test, argsNonNormal = list(NULL),
showAllLevels = showAllLevels, printToggle = F, quote = F, smd = input$smd, Labels = T, exact = NULL, nonnormal = input$nonnormal_vars,
catDigits = input$decimal_tb1_cat, contDigits = input$decimal_tb1_con, pDigits = input$decimal_tb1_p, labeldata = data_label, psub = input$psub)
res.iptw <- jstable::svyCreateTableOneJS(data = Svydesign, vars = vars.tb1, strata = input$group2_vars, strata2 = group_var, includeNA = F, test = T,
showAllLevels = showAllLevels, printToggle = F, quote = F, smd = input$smd, Labels = T, nonnormal = input$nonnormal_vars,
catDigits = input$decimal_tb1_cat, contDigits = input$decimal_tb1_con, pDigits = input$decimal_tb1_p, labeldata = data_label, psub = input$psub)
}
return(list(original = res, ps = res.ps, iptw = res.iptw))
})
return(out)
}
tb1simple2 <- function(input, output, session, data, matdata, data_label, data_varStruct = NULL, vlist, group_var, showAllLevels = T){
if (is.null(data_varStruct)){
data_varStruct = reactive(list(variable = names(data())))
}
output$base <- renderUI({
tagList(
selectInput(session$ns("nonnormal_vars"), "Non-normal variable (continuous)",
choices = vlist()$conti_list, multiple = T,
selected = vlist()$conti_vars[vlist()$non_normal]
),
sliderInput(session$ns("decimal_tb1_con"), "Digits (continuous)",
min = 1, max = 3, value = 1
),
sliderInput(session$ns("decimal_tb1_cat"), "Digits (categorical, %)",
min = 1, max = 3, value = 1
),
sliderInput(session$ns("decimal_tb1_p"), "Digits (p)",
min = 3, max = 5, value = 3
),
checkboxInput(session$ns("smd"), "Show SMD", T)
,
selectInput(session$ns("group2_vars"), "Stratified by (optional)",
choices = c("None", mksetdiff(vlist()$group_list, group_var())), multiple = F,
selected = "None")
)
})
output$sub2 <- renderUI({
req(!is.null(input$group2_vars))
if (input$group2_vars == 'None') return(NULL)
tagList(
checkboxInput(session$ns("psub"), "Subgroup p-values", T)
)
})
out <- reactive({
req(!is.null(group_var()))
vars = setdiff(setdiff(names(data()),vlist()$except_vars), group_var())
Svydesign <- survey::svydesign(ids = ~ 1, data = data(), weights = ~ iptw)
if (input$group2_vars == "None"){
vars.tb1 = setdiff(vars, c(group_var(), "pscore", "iptw"))
res = jstable::CreateTableOneJS(data = data(),
vars = vars.tb1, strata = group_var(), includeNA = F, test = T,
testApprox = chisq.test, argsApprox = list(correct = TRUE),
testExact = fisher.test, argsExact = list(workspace = 2 * 10^7),
testNormal = oneway.test, argsNormal = list(var.equal = F),
testNonNormal = kruskal.test, argsNonNormal = list(NULL),
showAllLevels = showAllLevels, printToggle = F, quote = F, smd = input$smd, Labels = T, exact = NULL, nonnormal = input$nonnormal_vars,
catDigits = input$decimal_tb1_cat, contDigits = input$decimal_tb1_con, pDigits = input$decimal_tb1_p, labeldata = data_label())
res.ps = jstable::CreateTableOneJS(data = matdata(),
vars = vars.tb1, strata = group_var(), includeNA = F, test = T,
testApprox = chisq.test, argsApprox = list(correct = TRUE),
testExact = fisher.test, argsExact = list(workspace = 2 * 10^7),
testNormal = oneway.test, argsNormal = list(var.equal = F),
testNonNormal = kruskal.test, argsNonNormal = list(NULL),
showAllLevels = showAllLevels, printToggle = F, quote = F, smd = input$smd, Labels = T, exact = NULL, nonnormal = input$nonnormal_vars,
catDigits = input$decimal_tb1_cat, contDigits = input$decimal_tb1_con, pDigits = input$decimal_tb1_p, labeldata = data_label())
res.iptw <- jstable::svyCreateTableOneJS(data = Svydesign, vars = vars.tb1, strata = group_var(), includeNA = F, test = T,
showAllLevels = showAllLevels, printToggle = F, quote = F, smd = input$smd, Labels = T, nonnormal = input$nonnormal_vars,
catDigits = input$decimal_tb1_cat, contDigits = input$decimal_tb1_con, pDigits = input$decimal_tb1_p, labeldata = data_label())
} else{
vars.tb1 = setdiff(vars, c(group_var(), input$group2_vars, "pscore", "iptw"))
res = jstable::CreateTableOneJS(data = data(),
vars = vars.tb1, strata = input$group2_vars, strata2 = group_var(), includeNA = F, test = T,
testApprox = chisq.test, argsApprox = list(correct = TRUE),
testExact = fisher.test, argsExact = list(workspace = 2 * 10^7),
testNormal = oneway.test, argsNormal = list(var.equal = F),
testNonNormal = kruskal.test, argsNonNormal = list(NULL),
showAllLevels = showAllLevels, printToggle = F, quote = F, smd = input$smd, Labels = T, exact = NULL, nonnormal = input$nonnormal_vars,
catDigits = input$decimal_tb1_cat, contDigits = input$decimal_tb1_con, pDigits = input$decimal_tb1_p, labeldata = data_label(), psub = input$psub)
res.ps = jstable::CreateTableOneJS(data = matdata(),
vars = vars.tb1, strata = input$group2_vars, strata2 = group_var(), includeNA = F, test = T,
testApprox = chisq.test, argsApprox = list(correct = TRUE),
testExact = fisher.test, argsExact = list(workspace = 2 * 10^7),
testNormal = oneway.test, argsNormal = list(var.equal = F),
testNonNormal = kruskal.test, argsNonNormal = list(NULL),
showAllLevels = showAllLevels, printToggle = F, quote = F, smd = input$smd, Labels = T, exact = NULL, nonnormal = input$nonnormal_vars,
catDigits = input$decimal_tb1_cat, contDigits = input$decimal_tb1_con, pDigits = input$decimal_tb1_p, labeldata = data_label(), psub = input$psub)
res.iptw <- jstable::svyCreateTableOneJS(data = Svydesign, vars = vars.tb1, strata = input$group2_vars, strata2 = group_var(), includeNA = F, test = T,
showAllLevels = showAllLevels, printToggle = F, quote = F, smd = input$smd, Labels = T, nonnormal = input$nonnormal_vars,
catDigits = input$decimal_tb1_cat, contDigits = input$decimal_tb1_con, pDigits = input$decimal_tb1_p, labeldata = data_label(), psub = input$psub)
}
return(list(original = res, ps = res.ps, iptw = res.iptw))
})
return(out)
}
|
context("test-get_n")
test_that("Checking that get_n works for T-test", {
data("ToothGrowth")
stat.test <- ToothGrowth %>% t_test(len ~ dose)
expect_equal(get_n(stat.test), c(40, 40, 40))
})
test_that("Checking that get_n works for grouped T-test", {
data("ToothGrowth")
stat.test <- ToothGrowth %>%
group_by(dose) %>%
t_test(len ~ supp)
expect_equal(get_n(stat.test), c(20, 20, 20))
})
test_that("Checking that get_n works for grouped ANOVA", {
data("ToothGrowth")
res.aov <- ToothGrowth %>%
group_by(supp) %>%
anova_test(len ~ dose)
expect_equal(get_n(res.aov), c(30, 30))
})
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(chronochrt)
library(ggplot2)
library(knitr)
chrons <- add_chron(
region = c("region = A", "region = A", "region = A", "region = A", "region = A", "region = A", "region = A", "region = A", "region = A", "region = A", "region = A", "region = A", "region = B", "region = B", "region = B"),
name = c("level = 1\nadd =\nFALSE", "level = 2\nadd =\nFALSE", "level = 3\nadd =\nFALSE", "level = 4\nadd =\nFALSE", "level = 5\nadd =\nFALSE","level = 1\nadd =\nTRUE","level = 2\nadd =\nTRUE","level = 2\nadd =\nTRUE", "add =\nTRUE", "level = 3", "add = TRUE", "level = 4", "level = 1\nadd = FALSE", "level = 2\nadd = FALSE", "level = 3\nadd = FALSE"),
start = c(-500, -500, -500, -500, -500, -400, -400, 0, 0, "200/200", "200/200", "275_325", -500, -500, -500),
end = c(500, 500, 500, 500, 500, 400, -50, 400, "200/200", 400, "275_325", 400, 500, 500, 500),
level = c(1, 2, 3, 4, 5, 1, 2, 2, 3, 3, 4, 4, 1, 2, 3),
add = c(FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE),
new_table = TRUE)
print(chrons)
plot_chronochrt(chrons, size_text = 4, line_break = 20) +
ggplot2::scale_x_continuous(name = NULL, breaks = seq(0, 2, 0.1), minor_breaks = NULL, expand = c(0,0)) +
ggplot2::theme(axis.text.x = ggplot2::element_text(),
axis.ticks.x = ggplot2::element_line())
data <- add_chron(region = "earlier/later",
name = c("1", "2", "1a", "1b"),
start = c(-100, "50/100", -100, "-25_25"),
end = c("50/100", 200, "-25_25", "50/100"),
level = c(1, 1, 2, 2),
add = FALSE,
new_table = TRUE) %>%
add_chron(region = "later/earlier",
name = c("1", "2", "1a", "1b"),
start = c(-100, "100/50", -100, "25_-25"),
end = c("100/50", 200, "25_-25", "100/50"),
level = c(1, 1, 2, 2),
add = FALSE,
new_table = FALSE) %>%
add_chron(region = "mixed",
name = c("1", "2", "1a", "1b"),
start = c(-100, "50/100", -100, "-25_25"),
end = c("50/100", 200, "25_-25", "100/50"),
level = c(1, 1, 2, 2),
add = FALSE,
new_table = FALSE) %>%
add_chron(region = "same",
name = c("1", "2", "1a", "1b"),
start = c(-100, "100/100", -100, "25_25"),
end = c("100/100", 200, "25_25", "100/100"),
level = c(1, 1, 2, 2),
add = FALSE,
new_table = FALSE) %>%
arrange_regions(order = c("earlier/later", "later/earlier", "same", "mixed"))
plot_chronochrt(data)
text <- add_label_text(region = "earlier/later",
year = 50,
position = 0.95,
label = "This date in front of the /.",
new = TRUE)
text <- add_label_text(data = text,
region = "later/earlier",
year = 100,
position = 0.9,
label = "This date in\nfront of the /.",
new = FALSE) %>%
add_label_text(region = "mixed",
year = 75,
position = 0.75,
label = "Both dates are\nin front of the /.",
new = FALSE)
text <- add_label_text(data = text,
region = "same",
year = 100,
position = c(0.4, 0.9),
label = "same", new = FALSE)
plot_chronochrt(data, labels_text = text)
image <- add_label_image(region = "earlier/later",
year = 50,
position = 0.5,
image_path = "https://www.r-project.org/logo/Rlogo.png",
new = TRUE) %>%
add_label_image(region = "same",
year = 0,
position = 0.5,
image_path = "https://www.r-project.org/logo/Rlogo.svg",
new = FALSE)
plot_chronochrt(data, labels_image = image)
plot <- ggplot() +
geom_chronochRt(data = data, mapping = aes(region = region, name = name, start = start, end = end, level = level, add = add)) +
geom_text(data = text, aes(x = position, y = year, label = label)) +
geom_chronochRtImage(data = image, aes(x = position, y = year, image_path = image_path)) +
facet_grid(cols = vars(region))
plot
plot + theme_chronochrt()
ggplot() +
geom_chronochRt(data = chrons, mapping = aes(region = region, name = name, start = start, end = end, level = level, add = add)) +
facet_grid(cols = vars(region)) +
theme_chronochrt()
ggplot() +
geom_chronochRt(data = chrons, mapping = aes(region = region, name = name, start = start, end = end, level = level, add = add)) +
scale_x_continuous(expand = c(0,0)) +
scale_y_continuous(name = "Year", expand = c(0,0)) +
facet_grid(cols = vars(region), scales = "free_x", space = "free_x") +
theme_chronochrt()
ggplot() +
geom_chronochRt(data = data, mapping = aes(region = region, name = name, start = start, end = end, level = level, add = add)) +
geom_text(data = text, aes(x = position, y = year, label = label)) +
geom_chronochRtImage(data = image, aes(x = position, y = year, image_path = image_path)) +
scale_x_continuous(expand = c(0,0)) +
scale_y_continuous(name = "Year", expand = c(0,0)) +
facet_grid(cols = vars(region), scales = "free_x", space = "free_x") +
theme_chronochrt()
points <- data.frame(x = seq(0, 2, 0.5),
y = seq(-500,-100, 100))
ggplot() +
geom_chronochRt(data = chrons, aes(region = region, name = NULL, start = start, end = end, level = level, add = add)) +
geom_point(data = points, aes(x = x, y = y), size = 5, colour = "red") +
facet_grid(cols = vars(region), scales = "free_x", space = "free_x") +
theme_void()
|
context("Base assertions")
test_that("any message is useful", {
expect_equal(validate_that(any(TRUE, FALSE)), TRUE)
x <- c(FALSE, FALSE)
expect_equal(validate_that(any(x)), "No elements of x are true")
})
test_that("all message is useful", {
expect_equal(validate_that(all(TRUE, TRUE)), TRUE)
x <- c(FALSE, TRUE)
expect_match(validate_that(all(x)), "Elements .* of x are not true")
})
test_that("custom message is printed", {
expect_equal(validate_that(FALSE, msg = "Custom message"), "Custom message")
})
|
data <- c(18.0, 6.3, 7.5, 8.1, 3.1, 0.8, 2.4, 3.5, 9.5, 39.7,
3.4, 14.6, 5.1, 6.8, 2.6, 8.0, 8.5, 3.7, 21.2, 3.1,
10.2, 8.3, 6.4, 3.0, 5.7, 5.6, 7.4, 3.9, 9.1, 4.0)
weiblik <-
function(theta, x) { sum(dweibull(x, theta[1], theta[2], log = TRUE)) }
pweib <- function(x, theta){ pweibull(x, theta[1], theta[2]) }
GOF(data, weiblik, pweib, start = c(1, 1), cutpts = c(0, 3, 6, 12, Inf))$table
GOF(data, weiblik, pweib, start = c(1, 1), cutpts = c(0, 3, 6, 12, Inf))
GOF(data, weiblik, pweib, start = c(1, 1), cutpts = c(0, 3, 6, 12, Inf),
pearson = TRUE)
|
temperature_curve <- function(T_par,
years = 1,
t_int = 1
){
T_amp <- T_par[1]
T_per <- T_par[2]
T_pha <- T_par[3]
T_av <- T_par[4]
t <- seq(0, years * T_per, t_int)
SST <- T_av + T_amp/2 * sin((2 * pi * (t - T_pha + T_per/4)) / T_per)
res <- cbind(t, SST)
return(res)
}
|
stat.tpm <- function(p,tau1){
return(stat.tfisher(p,tau1,1))
}
|
source("ESEUR_config.r")
library("diagram")
plot_layout(1, 1, default_width=ESEUR_default_width+2,
default_height=ESEUR_default_height+2)
pal_col=rainbow(3)
names=c("A2-0",
"1", "2",
"13", "12", "14",
"123", "124", "125", "134",
"1235", "1234",
"12345")
M=matrix(data=0, nrow=length(names), ncol=length(names))
colnames(M)=names
rownames(M)=names
M["A2-0", "1"]=37
M["A2-0", "2"]=2
M["A2-0", "12"]=10
M["A2-0", "14"]=1
M["1", "13"]=1
M["1", "124"]=1
M["1", "12"]=34
M["1", "14"]=1
M["2", "12"]=2
M["13", "123"]=1
M["12", "123"]=17
M["12", "124"]=28
M["12", "125"]=1
M["12", "124"]=28
M["12", "134"]=1
M["14", "124"]=1
M["14", "134"]=1
M["123", "1235"]=1
M["123", "1234"]=17
M["124", "1234"]=30
M["134", "1234"]=1
M["1234", "12345"]=22
par(col=pal_col[3])
plotmat(t(M), pos=c(1, 2, 3, 4, 2, 1), lwd=1, lcol="grey", txt.col=pal_col[1],
arr.col=pal_col[3], arr.lcol=pal_col[2], arr.pos=0.4, arr.width=0.1,
box.prop=0.5, box.size=0.05, box.cex=1.2, box.lcol="white",
cex=1.2, shadow.size=0)
|
create.dotmap <- function(x, bg.data = NULL, filename = NULL, main = NULL, main.just = 'center',
main.x = 0.5, main.y = 0.5, pch = 19, pch.border.col = 'black', add.grid = TRUE, xaxis.lab = colnames(x),
yaxis.lab = rownames(x), xaxis.rot = 0, yaxis.rot = 0, main.cex = 3, xlab.cex = 2, ylab.cex = 2,
xlab.label = NULL, ylab.label = NULL, xlab.col = 'black', ylab.col = 'black', xlab.top.label = NULL,
xlab.top.cex = 2, xlab.top.col = 'black', xlab.top.just = 'center', xlab.top.x = 0.5, xlab.top.y = 0,
xaxis.cex = 1.5, yaxis.cex = 1.5, xaxis.col = 'black', yaxis.col = 'black', xaxis.tck = 1, yaxis.tck = 1,
axis.top = 1, axis.bottom = 1, axis.left = 1, axis.right = 1, top.padding = 0.1, bottom.padding = 0.7,
right.padding = 0.1, left.padding = 0.5, key.ylab.padding = 0.1, key = list(text = list(lab = c(''))), legend = NULL, col.lwd = 1.5,
row.lwd = 1.5, spot.size.function = 'default', spot.colour.function = 'default', na.spot.size = 7,
na.pch = 4, na.spot.size.colour = 'black', grid.colour = NULL, colour.scheme = 'white', total.colours = 99,
at = NULL, colour.centering.value = 0, colourkey = FALSE, colourkey.labels.at = NULL,
colourkey.labels = NULL, colourkey.cex = 1, colour.alpha = 1, bg.alpha = 0.5, fill.colour = 'white',
key.top = 0.1, height = 6, width = 6, size.units = 'in', resolution = 1600, enable.warnings = FALSE,
col.colour = 'black', row.colour = 'black', description = 'Created with BoutrosLab.plotting.general',
add.rectangle = FALSE, xleft.rectangle = NULL, ybottom.rectangle = NULL, xright.rectangle = NULL,
ytop.rectangle = NULL, col.rectangle = 'transparent', border.rectangle=NULL, lwd.rectangle = NULL,
alpha.rectangle = 1, xaxis.fontface = 'bold', yaxis.fontface = 'bold', dot.colour.scheme = NULL,
style = 'BoutrosLab', preload.default = 'custom', use.legacy.settings = FALSE, remove.symmetric = FALSE, lwd = 2) {
tryCatch({
dir.name <- '/.mounts/labs/boutroslab/private/BPGRecords/Objects';
if( !dir.exists(dir.name) ) {
dir.create(dir.name);
}
funcname <- 'create.dotmap';
print.to.file(dir.name, funcname, x, filename);
},
warning = function(w) {
},
error = function(e) {
});
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
data.subset <- TRUE;
if (remove.symmetric == TRUE) {
if (ncol(x) != nrow(x)) {
stop('can only use remove.symmetric with matrices of same length and width');
}
data.subset <- c();
for (i in c(1:nrow(x))) {
for (j in c(1:nrow(x))) {
if(j > i) {
data.subset <- c(data.subset, T);
}
else {
data.subset <- c(data.subset, F);
}
}
}
}
x <- as.data.frame(x);
temp <- x;
if (class(spot.size.function) == 'character' && spot.size.function == 'default') {
spot.size.function <- function(x) { 0.1 + (2 * abs(x)); }
}
else if (class(spot.size.function) == 'numeric') {
returnval <- spot.size.function;
spot.size.function <- function(x) { returnval; }
}
if (class(spot.colour.function) == 'character' && spot.colour.function == 'default') {
spot.colour.function <- function(x) {
colours <- rep('white', length(x));
colours[sign(x) == -1] <- BoutrosLab.plotting.general::default.colours(2, palette.type = 'dotmap')[1];
colours[sign(x) == 1] <- BoutrosLab.plotting.general::default.colours(2, palette.type = 'dotmap')[2];
return(colours);
}
}
else if (class(spot.colour.function) == 'character' && spot.colour.function == 'discrete') {
if (length(unique(unlist(x))) > length(dot.colour.scheme)) {
stop(paste('Not enough colours specified to use discrete function: need at least', length(unique(unlist(x))), 'colours'));
}
spot.colour.function <- function(x) {
unique.values <- unique(x);
colours <- rep('white', length(x));
for (i in c(1:length(unique.values))) {
colours[x == unique.values[i]] <- dot.colour.scheme[i];
}
return(colours);
}
}
else if (class(spot.colour.function) == 'character' && spot.colour.function == 'columns') {
spot.colour.function <- function(x) {
no.unique.columns <- length(unique(colnames(temp)));
no.rows <- length(rownames(temp));
if (no.unique.columns != length(colnames(temp))) {
stop(paste('Remove repeated column names'));
}
new.colnames <- seq(1, no.unique.columns, 1);
colnames(temp) <- new.colnames;
temp <- stack(temp);
temp$values <- temp$ind;
temp$ind <- NULL;
index <- 1;
colours <- rep('white', no.unique.columns * no.rows);
for (i in c(1:no.unique.columns)) {
for (j in c(1:no.rows)) {
colours[index] <- default.colours(12)[(i %% 12) + 1];
index <- index + 1;
}
}
return(colours);
}
}
else if (class(spot.colour.function) == 'character' && spot.colour.function == 'rows') {
spot.colour.function <- function(x) {
no.columns <- length(colnames(temp));
no.unique.rows <- length(unique(rownames(temp)));
if (no.unique.rows != length(rownames(temp))) {
stop(paste('Remove repeated row names'));
}
colour.per.column <- c(1:no.unique.rows);
for (i in 0:no.unique.rows) {
colour.per.column[i + 1] <- default.colours(12)[(i %% 12) + 1];
}
temp <- stack(temp);
temp$ind <- NULL;
index <- 1;
for (i in c(1:no.columns)) {
for (j in c(1:no.unique.rows)) {
temp$values[index] <- colour.per.column[j];
index <- index + 1;
}
}
return(temp);
}
}
spot.sizes <- spot.size.function(stack(x)$values);
spot.colours <- spot.colour.function(stack(x)$values);
spot.border <- pch.border.col;
if (!is.null(bg.data)) {
if (length(colour.scheme) == 1 && colour.scheme == 'white') {
warning("bg.data is set, but colour.scheme is set to default 'white'. No background colours will be displayed. Changing bg.data to NULL");
bg.data <- NULL;
}
}
if (is.null(bg.data)) {
bg.data <- x;
if (colourkey) {
warning('No bg.data set, but colourkey is set to TRUE. Changing colourkey to FALSE');
colourkey <- FALSE;
}
if (length(colour.scheme) != 1 || colour.scheme != 'white') {
warning("No bg.data set, but colour.scheme is set to non-default value. Changing colour.scheme to 'white'.");
colour.scheme <- 'white';
}
}
if (is.null(at)) {
min.value <- min(bg.data - colour.centering.value, na.rm = TRUE);
max.value <- max(bg.data - colour.centering.value, na.rm = TRUE);
at <- seq(from = min.value, to = max.value, length.out = total.colours);
}
else {
min.value <- min(at - colour.centering.value, na.rm = TRUE);
max.value <- max(at - colour.centering.value, na.rm = TRUE);
min.at <- min(at);
max.at <- max(at);
if (min(bg.data, na.rm = TRUE) < min.at) {
warning(
paste(
'min(bg.data) = ',
min(bg.data, na.rm = TRUE),
'is smaller than min(at) = ',
min.at,
'Clipped data will be plotted'
)
);
bg.data[bg.data < min.at] <- min(at);
}
if (max(bg.data, na.rm = TRUE) > max.at) {
warning(
paste(
'max(bg.data) = ',
max(bg.data, na.rm = TRUE),
'is greater than max(at) = ',
max.at,
'Clipped data will be plotted'
)
);
bg.data[bg.data > max.at] <- max(at);
}
total.colours <- max(length(at), total.colours);
}
if (bg.alpha <= 1 && bg.alpha >= 0) {
bg.alpha <- bg.alpha * 255;
}
if (1 == length(colour.scheme)) {
if (colour.scheme == 'RedWhiteBlue') { colour.scheme <- c('red', 'white', 'blue'); }
else if (colour.scheme == 'WhiteBlack') { colour.scheme <- c('white', 'black'); }
else if (colour.scheme == 'BlueWhiteYellow') { colour.scheme <- c('blue', 'white', 'yellow'); }
else if (colour.scheme == 'white') { colour.scheme <- c('white', 'white'); }
else {
warning(paste('Unknown colour scheme:', colour.scheme));
return(0);
}
}
if (2 == length(colour.scheme)) {
colour.function <- colorRamp(colour.scheme, space = 'Lab');
my.palette <- rgb(colour.function(seq(0, 1, 1 / total.colours) ^ colour.alpha), alpha = bg.alpha, maxColorValue = 255);
}
else if (3 == length(colour.scheme)) {
is.twosided <- sign(min.value) != sign(max.value);
if (!is.twosided) {
warning('Using a three-colour scheme with one-sided data is not advised!');
}
colour.function.low <- colorRamp(colour.scheme[1:2], space = 'Lab');
colour.function.high <- colorRamp(colour.scheme[2:3], space = 'Lab');
neg.colours <- min.value / (max.value - min.value) * (total.colours - 1);
neg.colours <- ceiling(abs(neg.colours));
pos.colours <- total.colours - neg.colours - 1;
if (neg.colours < 1 | pos.colours < 1) {
warning('Colour allocation scheme failed, moving to a default method');
neg.colours <- round(total.colours / 2);
pos.colours <- round(total.colours / 2);
}
my.palette <- c(
rgb(colour.function.low(seq(0, 1, 1 / neg.colours) ^ colour.alpha), alpha = bg.alpha, maxColorValue = 255),
colour.scheme[2],
rgb(colour.function.high(seq(0, 1, 1 / pos.colours) ^ (1 / colour.alpha)), alpha = bg.alpha, maxColorValue = 255)
);
}
else {
my.palette <- c();
for (n in 1:length(colour.scheme)) {
colour.function <- colorRamp(c('white', colour.scheme[n]), space = 'Lab');
my.palette <- c(my.palette, rgb(colour.function(1 ^ colour.alpha), alpha = bg.alpha, maxColorValue = 255));
}
}
bg.data <- as.data.frame(bg.data);
y.coords <- rep(nrow(x):1, ncol(x));
x.coords <- c();
for (i in 1:ncol(x)) { x.coords <- c(x.coords, rep(i, nrow(x))); }
bg.data <- data.frame(
x = x.coords,
y = y.coords,
freq = stack(bg.data)$values
);
if (colourkey) {
colourkey <- list(
size = 1,
space = 'bottom',
width = 1.25,
height = 1.0,
labels = list(
cex = colourkey.cex,
at = colourkey.labels.at,
labels = colourkey.labels
),
tick.number = 3
);
}
if (!is.null(grid.colour)) {
row.colour <- grid.colour;
col.colour <- grid.colour;
cat(paste0('CAUTION: grid.colour is DEPRECATED! Use row.colour/col.colour. Using: ', grid.colour, '\n'));
}
if (any(is.na(x))) {
tmp.pch <- pch;
pch[is.na(x)] <- na.pch;
pch[!is.na(x)] <- tmp.pch;
spot.colours[is.na(x)] <- na.spot.size.colour;
spot.sizes[is.na(x)] <- na.spot.size;
rm(tmp.pch);
}
if (is.null(lwd.rectangle) & !is.null(border.rectangle)) {
lwd.rectangle <- 1;
}
trellis.object <- lattice::levelplot(
freq ~ x * y,
bg.data,
subset = data.subset,
panel = function(...) {
panel.fill(col = fill.colour);
panel.levelplot(...);
if (add.grid) {
if(remove.symmetric == TRUE) {
for(i in c(1:max(bg.data$y))) {
panel.lines(x = c(0,max(bg.data$x) - (i)) + 0.5, y = i + 0.5, col=col.colour, lwd = col.lwd);
}
for(i in c(1:max(bg.data$x))) {
panel.lines(x = i + 0.5, y = c(0,max(bg.data$y) - (i)) + 0.5, col=row.colour, lwd = row.lwd);
}
}
else {
panel.abline(
h = min(bg.data$y):max(bg.data$y) - 0.5,
v = 0,
col.line = row.colour,
lwd = row.lwd
);
panel.abline(
v = min(bg.data$x):max(bg.data$x) - 0.5,
h = 0,
col.line = col.colour,
lwd = col.lwd
);
}
}
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = ifelse(is.null(border.rectangle), NA, border.rectangle),
lwd = lwd.rectangle
);
}
panel.xyplot(
type = 'p',
cex = spot.sizes,
pch = pch,
col = mapply(
function(pch, spot.colours, spot.border) {
if (pch %in% 0:20) { return(spot.colours); } else
if (pch %in% 21:25) { return(spot.border); }
},
pch, spot.colours = spot.colours, spot.border = spot.border
),
fill = mapply(
function(pch, spot.colours) {
if (pch %in% 0:20) { NA; } else
if (pch %in% 21:25) { return(spot.colours); }
},
pch, spot.colours = spot.colours
),
key = key,
legend = legend,
...
);
},
at = at,
key = key,
legend = legend,
col.regions = my.palette,
colorkey = colourkey,
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) {'plain'} else ('bold'),
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
fontface = if ('Nature' == style) {'plain'} else ('bold'),
cex = xlab.cex,
col = xlab.col
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) {'plain'} else {'bold'},
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
fontface = if ('Nature' == style) {'plain'} else ('bold'),
cex = ylab.cex,
col = ylab.col
)
),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = xaxis.lab,
cex = xaxis.cex,
rot = xaxis.rot,
col = xaxis.col,
tck = xaxis.tck,
limits = c( min(bg.data$x, na.rm = TRUE) - 0.5, max(bg.data$x, na.rm = TRUE) + 0.5 ),
at = min(bg.data$x, na.rm = TRUE):max(bg.data$x, na.rm = TRUE),
fontface = if ('Nature' == style) {'plain'} else (xaxis.fontface)
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = rev(yaxis.lab),
cex = yaxis.cex,
rot = yaxis.rot,
col = yaxis.col,
tck = yaxis.tck,
limits = c( min(bg.data$y, na.rm = TRUE) - 0.5, max(bg.data$y, na.rm = TRUE) + 0.5 ),
at = min(bg.data$y, na.rm = TRUE):max(bg.data$y, na.rm = TRUE),
fontface = if ('Nature' == style) {'plain'} else (yaxis.fontface)
)
)
),
par.settings = list(
axis.line = list(
lwd = lwd,
col = if(remove.symmetric == TRUE) { 'transparent'; } else { 'black'; }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3} else { 1 },
main.key.padding = 0.1,
key.top = key.top,
key.axis.padding = 0.1,
axis.top = axis.top,
axis.bottom = axis.bottom,
axis.xlab.padding = 1,
xlab = if (is.null(xaxis.lab)) {0.1} else {1},
xlab.key.padding = 0.5,
key.bottom = 1,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 1,
key.ylab.padding = key.ylab.padding,
ylab = if (is.null(yaxis.lab)) {0.1} else {1},
ylab.axis.padding = 1,
axis.left = axis.left,
axis.right = axis.right,
axis.key.padding = 0.1,
key.right = 1,
right.padding = right.padding
)
)
);
if (remove.symmetric == TRUE) {
trellis.object$axis <- function(side, line.col = 'black', ...) {
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1], lwd = lwd);
}
}
}
if ('Nature' == style) {
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
warning('Nature also requires italicized single-letter variables and en-dashes
for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend');
}
else if ('BoutrosLab' == style) {
}
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
}
|
publish.htest <- function(object,
title,
...){
pynt <- getPyntDefaults(list(...),names=list("digits"=c(2,3),"handler"="sprintf",nsmall=NULL))
digits <- pynt$digits
if (length(digits)==1) digits <- rep(digits,2)
handler <- pynt$handler
if (length(pynt$nsmall)>0) nsmall <- pynt$nsmall else nsmall <- pynt$digits
Lower <- object$conf.int[[1]]
Upper <- object$conf.int[[2]]
ci.defaults <- list(format="[l;u]",
digits=digits[[1]],
nsmall=digits[[1]],
degenerated="asis")
pvalue.defaults <- list(digits=digits[[2]],
eps=10^{-digits[[2]]},
stars=FALSE)
smartF <- prodlim::SmartControl(call=list(...),
keys=c("ci","pvalue"),
ignore=c("x","print","handler","digits","nsmall"),
defaults=list("ci"=ci.defaults,"pvalue"=pvalue.defaults),
forced=list("ci"=list(lower=Lower,upper=Upper,handler=handler,digits=digits[[1]],nsmall=nsmall[[1]]),
"pvalue"=list(object$p.value)),
verbose=FALSE)
printmethod=object$method
printmethod[grep("Wilcoxon rank sum test",printmethod)]="Wilcoxon rank sum test"
printmethod[grep("Wilcoxon signed rank test",printmethod)]="Wilcoxon signed rank test"
printmethod[grep("Two Sample t-test",printmethod)]="Two Sample t-test"
if (!is.null(object$conf.int)){
if (printmethod=="Exact binomial test"){
cistring=paste(" (CI-",
100*attr(object$conf.int,"conf.level"),
"% = ",
do.call("formatCI",smartF$ci),
").",sep="")
}else{
cistring=paste(" (CI-",
100*attr(object$conf.int,"conf.level"),
"% = ",
do.call("formatCI",smartF$ci),
"; ",
"p-value = ",
do.call("format.pval",smartF$pvalue),
").",sep="")
}
} else{
cistring=""
}
switch(printmethod,
"Exact binomial test"={
outstring <- paste("The ",
object$method,
" to estimate the ",
names(object$null.value),
" based on ", object$statistic,
" events ",
" in ", object$parameter,
" trials yields a probability estimate of ",
pubformat(object$estimate,handler=handler, digits=digits[[1]], nsmall=nsmall[[1]]),
cistring,
sep="")
},
"Two Sample t-test"={
outstring <- paste("The ",
object$method,
" to compare the ",
names(object$null.value),
" for ",
object$data.name,
" yields a mean difference of ",
pubformat(diff(object$estimate),handler=handler, digits=digits[[1]], nsmall=nsmall[[1]]),
cistring,
sep="")
},
"Wilcoxon rank sum test"={
if (is.null(object$conf.int))
outstring <- paste("The ",
object$method,
" to compare the ",
names(object$null.value),
" for ",
object$data.name,
" yields a p-value of ",
do.call("format.pval",smartF$pvalue),
".",
sep="")
else
outstring <- paste("The ",
object$method,
" to compare the ",
names(object$null.value),
" for ",
object$data.name,
" yields a ",
names(object$estimate),
" of ",
pubformat(object$estimate,handler=handler, digits=digits[[1]], nsmall=nsmall[[1]]),
cistring,
sep="")
},
"Paired t-test"={
outstring <- paste("The ",
object$method,
" to compare the ",
names(object$null.value),
" for ",
object$data.name,
" yields a mean of the differences of ",
pubformat(object$estimate,handler=handler, digits=digits[[1]], nsmall=nsmall[[1]]),
cistring,
sep="")
},
"Wilcoxon signed rank test"={
if (is.null(object$conf.int))
outstring <- paste("The ",
object$method,
" to compare the ",
names(object$null.value),
" for ",
object$data.name,
" yields a p-value of ",
do.call("format.pval",smartF$pvalue),
".",
sep="")
else
outstring <- paste("The ",
object$method,
" to compare the ",
names(object$null.value),
" for ",
object$data.name,
" yields a ",
names(object$estimate),
" of ",
pubformat(object$estimate,handler=handler, digits=digits[[1]], nsmall=nsmall[[1]]),
cistring,
sep="")
})
outstring=gsub('[[:space:]]+',' ',gsub('[[:space:]]$','',outstring))
if (missing(title))
cat("\n",outstring,"\n")
else{
names(outstring) <- title
print(outstring,quote=F)
}
}
|
readland.shapes <- function(Shapes, nCurvePts = NULL, continuous.curve = NULL, scaled = TRUE){
if(is.null(nCurvePts)) out <- GMfromShapes0(Shapes) else{
nCurvePts[nCurvePts < 3] = 0
if(!is.null(continuous.curve)) {
continuous.curve <- unlist(continuous.curve)
check <- which(nCurvePts[continuous.curve] < 4)
nCurvePts[check] = 0
}
out <- GMfromShapes1(Shapes, nCurvePts = nCurvePts, continuous.curve = continuous.curve)
}
out
}
|
setMethod("get_neighbors", signature(x = "Quadtree", y = "numeric"),
function(x, y) {
return(x@ptr$getNeighbors(y))
}
)
|
context("valuate of one portfolio of guaratee contracts")
library(vamc)
fundScen <- genFundScen(fundMap, indexScen)[1:5, , ]
test_that("test for the correctness of valuation", {
skip_on_cran()
tmp <- tempfile()
expect_equal_to_reference(valuatePortfolio(VAPort, mortTable, fundScen,
1 / 12, cForwardCurve), tmp)
})
|
pkg_env = environment()
restriction_names = list(
's' = 'sym',
'l' = 'logspd',
'c' = 'spd',
'd' = 'diag',
'e' = 'logdiag',
'k' = '+++PLACEHOLDER+++',
'0' = 'zero',
'f' = 'fixed'
)
avail_restrict_cmds = list(
M=c('s','l','c','d','e','k','0','f'),
V=c('0','k','f'),
L=c('k','d','f')
)
special_cases = list(brn=list(M='0',V='0'))
npar2k = function(y,a,b,c,d) {
if (2L*a+c!=0)
-(2L*b+c-as.integer(sqrt(16L*a*(y-d)+4L*b*(b+c)+c*c+8L*c*(y-d))))%/%(2L*(2L*a+c))
else
-(2L*(d-y))%/%(2L*b+c)
}
get_name_stub = function (pat) {
if ((pat[['M']] == '0' && pat[['V']] != '0')||(pat[['M']] != '0' && pat[['V']] == '0')) {
return(NULL)
}
if (pat[['M']] == 'f' && pat[['V']] == 'f' && pat[['L']] == 'f') {
return(NULL)
}
match = NULL
for (i in seq_along(special_cases)) {
matched = T
names_matched = list()
for (n in c('M','V','L'))
if (n %in% names(special_cases[[i]])) {
if (special_cases[[i]][[n]] != pat[[n]]) {
matched = F
} else {
names_matched = c(names_matched, list(n))
}
}
if (matched) {
match = i
for (n in names_matched)
pat[[n]] = NULL
break;
}
}
done_part = if (!is.null(match)) names(special_cases)[match]
else done_part = 'ou'
pat[which(pat=='k')] = NULL
for (i in seq_along(pat)) {
if (names(pat)[i] == 'M') {
done_part = paste0(done_part, '_', restriction_names[[pat[[i]]]], 'H')
} else if (names(pat)[i] == 'V') {
done_part = paste0(done_part, '_', restriction_names[[pat[[i]]]], 'theta')
} else if (names(pat)[i] == 'L') {
done_part = paste0(done_part, '_', restriction_names[[pat[[i]]]], 'Sig')
} else {
stop('Error compiling the names of restriction functions')
}
}
if (done_part == 'ou') return(NULL)
else return(list(par = done_part,
jac = paste0('d', done_part),
hess = paste0('h', done_part),
nparams= paste0('nparams_',done_part)))
}
mkcmd = function (pat) {
s = ''
for (i in seq_along(pat)) s = paste0(s, names(pat)[i], pat[[i]])
return(s)
}
cmd2abcd = function (cmd) {
cmd_s = strsplit(cmd, '')[[1]]
curstate = 1L
i = 1L
res = list(a=0L,b=0L,c=0L,d=0L)
repeat{
if (curstate == 1L) {
switch(cmd_s[[i]],
M={curstate = 2L},
V={curstate = 3L},
L={curstate = 4L})
} else if (curstate == 2L) {
switch(cmd_s[[i]],
s= {res[['c']]=res[['c']]+1L},
l= {res[['c']]=res[['c']]+1L},
c= {res[['c']]=res[['c']]+1L},
d= {res[['b']]=res[['b']]+1L},
e= {res[['b']]=res[['b']]+1L},
k= {res[['a']]=res[['a']]+1L},
'0'= {NULL;},
f= {NULL;})
curstate = 1L
} else if (curstate == 3L) {
switch(cmd_s[[i]],
k= {res[['b']]=res[['b']]+1L},
'0'= {NULL;},
f= {NULL;})
curstate = 1L
} else if (curstate == 4L) {
switch(cmd_s[[i]],
d= {res[['b']]=res[['b']]+1L},
k= {res[['c']]=res[['c']]+1L},
'0'= {NULL;},
f= {NULL;})
curstate = 1L
} else stop("Error pasing command line in cmd2abcd")
i=i+1
if (i > length(cmd_s)) break;
}
res
}
build_par = function (pat) {
cmd = mkcmd(pat)
body = quote({
parfn
BUILD_FIXED__;
f=function (par, ...) {
mode(par) = 'double'
parfn(.Call(Rparamrestrict, s, par, npar2k(length(par),a,b,c,d), FIXEDPART__), ...)
}
attr(f,'srcref') = NULL
f
})
outerargs = alist(parfn=)
tosub = c(list('s'=cmd),
cmd2abcd(cmd),
list('FIXEDPART__' =quote(NULL),
'BUILD_FIXED__'=quote(NULL)))
outerargs = c(outerargs, fixed_arg <- mk_fixed_arg(pat))
if (0L != length(fixed_arg)) {
tosub_f = alist(SUB_H__ =NULL,
SUB_THETA__=NULL,
SUB_SIG__ =NULL)
cnt = 1L
for (i in seq_along(names(fixed_arg))) {
if (names(fixed_arg)[i] == 'H')
tosub_f[['SUB_H__']] = substitute({
fixedpart[[j]] = {
if (!is.numeric(H)) stop('The argument `H` must be numeric')
mode(H)='double';
H
}
}, list(j=cnt))
else if (names(fixed_arg)[i] == 'theta')
tosub_f[['SUB_THETA__']] = substitute({
fixedpart[[j]] = {
if (!is.numeric(theta)) stop('The argument `theta` must be numeric')
mode(theta)='double';
theta
}
}, list(j=cnt))
else if (names(fixed_arg)[i] == 'Sig')
tosub_f[['SUB_SIG__']] = substitute({
fixedpart[[j]] = {
if (!is.numeric(Sig)) stop('The argument `Sig` must be numeric')
mode(Sig)='double';
Sig
}
}, list(j=cnt))
else stop('Error building fixed-parameter restriction functions')
cnt = cnt+1L
}
tosub[['BUILD_FIXED__']] = substitute({
fixedpart = list()
SUB_H__
SUB_THETA__
SUB_SIG__
}, tosub_f)
tosub[['FIXEDPART__']] = quote(fixedpart)
}
body = substituteDirect(body, tosub)
substitute(
`function`(A, B),
list(A=as.pairlist(outerargs), B=body))
}
build_jac = function (pat) {
cmd = mkcmd(pat)
body = quote({
jacfn
BUILD_FIXED__;
f=function (par, ...) {
mode(par) = 'double'
k = npar2k(length(par),a,b,c,d)
.Call(Rpostjacrestrict, s, par,
jacfn(.Call(Rparamrestrict, s, par, k, FIXEDPART__), ...), k)
}
attr(f,'srcref') = NULL
f
})
outerargs = alist(jacfn=)
tosub = c(list('s'=cmd),
cmd2abcd(cmd),
list('FIXEDPART__' =quote(NULL),
'BUILD_FIXED__'=quote(NULL)))
outerargs = c(outerargs, fixed_arg <- mk_fixed_arg(pat))
if (0L != length(fixed_arg)) {
tosub_f = alist(SUB_H__ =NULL,
SUB_THETA__=NULL,
SUB_SIG__ =NULL)
cnt = 1L
for (i in seq_along(names(fixed_arg))) {
if (names(fixed_arg)[i] == 'H')
tosub_f[['SUB_H__']] = substitute({
fixedpart[[j]] = {
if (!is.numeric(H)) stop('The argument `H` must be numeric')
mode(H)='double';
H
}
}, list(j=cnt))
else if (names(fixed_arg)[i] == 'theta')
tosub_f[['SUB_THETA__']] = substitute({
fixedpart[[j]] = {
if (!is.numeric(theta)) stop('The argument `theta` must be numeric')
mode(theta)='double';
theta
}
}, list(j=cnt))
else if (names(fixed_arg)[i] == 'Sig')
tosub_f[['SUB_SIG__']] = substitute({
fixedpart[[j]] = {
if (!is.numeric(Sig)) stop('The argument `Sig` must be numeric')
mode(Sig)='double';
Sig
}
}, list(j=cnt))
else stop('Error building fixed-parameter restriction functions')
cnt = cnt+1L
}
tosub[['BUILD_FIXED__']] = substitute({
fixedpart = list()
SUB_H__
SUB_THETA__
SUB_SIG__
}, tosub_f)
tosub[['FIXEDPART__']] = quote(fixedpart)
}
body = substituteDirect(body, tosub)
substitute(
`function`(A, B),
list(A=as.pairlist(outerargs), B=body))
}
mk_fixed_arg = function (pat) {
stopifnot(names(pat)[1] == 'M')
stopifnot(names(pat)[2] == 'V')
stopifnot(names(pat)[3] == 'L')
A = alist()
if (pat[[1]]=='f') A = c(A, alist(H=))
if (pat[[2]]=='f') A = c(A, alist(theta=))
if (pat[[3]]=='f') A = c(A, alist(Sig=))
return(A)
}
build_hess = function (pat) {
outerargs = alist(hessfn=)
body = quote({
hessfn;
JAC_GUARD_EVAL__;
BUILD_FIXED__;
f= function (par, ...) {
mode(par) = 'double';
k = npar2k(length(par), A__, B__, C__, D__)
par_orig = .Call(Rparamrestrict, CMD__, par, k, FIXEDPART__);
Hes = hessfn(par_orig, ...);
MAKE_JACTHIS__;
MAKE_JACLOWER__;
list(V = .Call(Rposthessrestrict, CMD__, par, Hes[['V']], k,
RJACLOWER__, RJLOWEROFFSET_V__, RJACTHIS__, RJTHISOFFSET_R_V__, RJTHISOFFSET_C__),
w = .Call(Rposthessrestrict, CMD__, par, Hes[['w']], k,
RJACLOWER__, RJLOWEROFFSET_W__, RJACTHIS__, RJTHISOFFSET_R_W__, RJTHISOFFSET_C__),
Phi = .Call(Rposthessrestrict, CMD__, par, Hes[['Phi']], k,
RJACLOWER__, RJLOWEROFFSET_PHI__, RJACTHIS__, RJTHISOFFSET_R_PHI__, RJTHISOFFSET_C__))
}
attr(f, 'srcref') = NULL
f
})
cmd = mkcmd(pat)
to_sub = list(
BUILD_FIXED__ = quote(NULL),
FIXEDPART__ = quote(NULL),
JAC_GUARD_EVAL__ = quote(NULL),
MAKE_JACTHIS__ = quote(NULL),
MAKE_JACLOWER__ = quote(NULL),
CMD__ = cmd,
RJACLOWER__ = quote(NULL),
RJLOWEROFFSET_V__ = quote(NULL),
RJLOWEROFFSET_W__ = quote(NULL),
RJLOWEROFFSET_PHI__ = quote(NULL),
RJACTHIS__ = quote(NULL),
RJTHISOFFSET_R_V__ = quote(NULL),
RJTHISOFFSET_R_W__ = quote(NULL),
RJTHISOFFSET_R_PHI__ = quote(NULL),
RJTHISOFFSET_C__ = quote(NULL)
)
if (grepl('Ml', cmd, fixed = TRUE) || grepl('Mc', cmd, fixed = TRUE)) {
outerargs = c(outerargs, alist(jacfn=))
to_sub[['JAC_GUARD_EVAL__']] = quote(jacfn)
to_sub[['MAKE_JACLOWER__']] = quote(
{
J = jacfn(par_orig, ...);
ku = INFO__$mod$rawmod$dimtab[INFO__$node_id];
kv = INFO__$mod$rawmod$dimtab[INFO__$parent_id];
})
to_sub[['RJACLOWER__']] = quote(J)
to_sub[['RJLOWEROFFSET_V__']] = quote(ku*kv+ku)
to_sub[['RJLOWEROFFSET_W__']] = quote(ku*kv)
to_sub[['RJLOWEROFFSET_PHI__']] = quote(0L)
}
if (grepl('Me', cmd, fixed = TRUE)) {
to_sub[['MAKE_JACTHIS__']] = quote(
{
Jthis = INFO__[['reparametrisation_jacobian']];
gstart = INFO__$mod$gausssegments[INFO__$node_id,'start'];
gend = INFO__$mod$gausssegments[INFO__$node_id,'end'];
pstart = INFO__$mod$parsegments[INFO__$parfn_id,'start'];
phid = dim(Hes[['Phi']])[1];
wd = dim(Hes[['w']])[1];
})
to_sub[['RJACTHIS__']] = quote(Jthis)
to_sub[['RJTHISOFFSET_R_V__']] = quote(gstart+phid+wd-1L)
to_sub[['RJTHISOFFSET_R_W__']] = quote(gstart+phid-1L)
to_sub[['RJTHISOFFSET_R_PHI__']] = quote(gstart-1L)
to_sub[['RJTHISOFFSET_C__']] = quote(pstart-1L)
}
outerargs = c(outerargs, fixed_arg <- mk_fixed_arg(pat))
if (0L != length(fixed_arg)) {
tosub_f = alist(SUB_H__ =NULL,
SUB_THETA__=NULL,
SUB_SIG__ =NULL)
cnt = 1L
for (i in seq_along(names(fixed_arg))) {
if (names(fixed_arg)[i] == 'H')
tosub_f[['SUB_H__']] = substitute({
fixedpart[[j]] = {
if (!is.numeric(H)) stop('The argument `H` must be numeric')
mode(H)='double';
H
}
}, list(j=cnt))
else if (names(fixed_arg)[i] == 'theta')
tosub_f[['SUB_THETA__']] = substitute({
fixedpart[[j]] = {
if (!is.numeric(theta)) stop('The argument `theta` must be numeric')
mode(theta)='double';
theta
}
}, list(j=cnt))
else if (names(fixed_arg)[i] == 'Sig')
tosub_f[['SUB_SIG__']] = substitute({
fixedpart[[j]] = {
if (!is.numeric(Sig)) stop('The argument `Sig` must be numeric')
mode(Sig)='double';
Sig
}
}, list(j=cnt))
else stop('Error building fixed-parameter restriction functions')
cnt = cnt+1L
}
to_sub[['BUILD_FIXED__']] = substitute({
fixedpart = list()
SUB_H__
SUB_THETA__
SUB_SIG__
}, tosub_f)
to_sub[['FIXEDPART__']] = quote(fixedpart)
}
abcd = cmd2abcd(cmd)
to_sub[['A__']] = abcd$a
to_sub[['B__']] = abcd$b
to_sub[['C__']] = abcd$c
to_sub[['D__']] = abcd$d
body = substituteDirect(body, to_sub)
substitute(`function`(args, body), list(args=as.pairlist(outerargs), body=body))
}
build_nparams = function (pat) {
cmd = mkcmd(pat)
abcd = cmd2abcd(cmd)
substitute(function (k) { a*k*k+b*k+c*(k*(k+1L))%/%2L+d }, abcd)
}
avail_restrictions = list(nparams=character(0),
par =character(0),
jac =character(0),
hess =character(0))
for (m in avail_restrict_cmds[['M']]) {
for (v in avail_restrict_cmds[['V']]) {
for (l in avail_restrict_cmds[['L']]) {
pat = list('M'=m,'V'=v,'L'=l)
name_stub = get_name_stub(pat)
if (is.null(name_stub)) next
assign(name_stub[['nparams']], eval(build_nparams(pat)))
assign(name_stub[['par']], eval(build_par(pat)))
assign(name_stub[['jac']], eval(build_jac(pat)))
assign(name_stub[['hess']], eval(build_hess(pat)))
eval(substitute({environment(f) = pkg_env}, list(f = as.name(name_stub[['nparams']]))))
eval(substitute({environment(f) = pkg_env}, list(f = as.name(name_stub[['par']]))))
eval(substitute({environment(f) = pkg_env}, list(f = as.name(name_stub[['jac']]))))
eval(substitute({environment(f) = pkg_env}, list(f = as.name(name_stub[['hess']]))))
eval(substitute({attr(f, "srcref") = NULL}), list(f= as.name(name_stub[['nparams']])))
eval(substitute({attr(f, "srcref") = NULL}), list(f= as.name(name_stub[['par']])))
eval(substitute({attr(f, "srcref") = NULL}), list(f= as.name(name_stub[['jac']])))
eval(substitute({attr(f, "srcref") = NULL}), list(f= as.name(name_stub[['hess']])))
avail_restrictions$nparams = c(avail_restrictions$nparams, name_stub[['nparams']])
avail_restrictions$par = c(avail_restrictions$par, name_stub[['par']])
avail_restrictions$jac = c(avail_restrictions$jac, name_stub[['jac']])
avail_restrictions$hess = c(avail_restrictions$hess, name_stub[['hess']])
}
}
}
human_name_to_cmdchr = list(
'symmetric' = 's',
'logspd' = 'l',
'spd' = 'c',
'diag' = 'd',
'logdiag' = 'e',
'zero' = '0'
)
get_restricted_ou = function (H=NULL, theta=NULL, Sig=NULL, lossmiss = 'halt') {
pat = list(M='k', V='k', L='k')
fixed_args = list()
if (!is.null(H)) {
if (is.character(H)) {
s = human_name_to_cmdchr[[H]]
if (is.null(s) || !(s %in% avail_restrict_cmds[[1]]))
stop(sprintf('`%s` restriction for H is not supported', H))
pat[[1]] = s
} else if (is.numeric(H)) {
fixed_args[['H']] = as.double(H)
pat[[1]] = 'f'
} else {
stop('`H` must be either a string or a numeric vector to be fixed.')
}
} else {
pat[[1]] = 'k'
}
if (!is.null(theta)) {
if (is.character(theta)) {
s = human_name_to_cmdchr[[theta]]
if (is.null(s) || !(s %in% avail_restrict_cmds[[2]]))
stop(sprintf('`%s` restriction for theta is not supported', theta))
pat[[2]] = s
} else if (is.numeric(theta)) {
fixed_args[['theta']] = as.double(theta)
pat[[2]] = 'f'
} else {
stop('`theta` must be either a string or a numeric vector to be fixed.')
}
} else {
pat[[2]] = 'k'
}
if (!is.null(Sig)) {
if (is.character(Sig)) {
s = human_name_to_cmdchr[[Sig]]
if (is.null(s) || !(s %in% avail_restrict_cmds[[3]]))
stop(sprintf('`%s` restriction for Sig is not supported', Sig))
pat[[3]] = s
} else if (is.numeric(Sig)) {
fixed_args[['Sig']] = as.double(Sig)
pat[[3]] = 'f'
} else {
stop('`Sig` must be either a string or a numeric vector to be fixed.')
}
} else {
pat[[3]] = 'k'
}
if ((pat[[1]] == '0' && pat[[2]] != '0') || (pat[[1]] != '0' && pat[[2]] == '0'))
stop('zero H but non-zero theta, or non-zero H but zero theta is not supported. The former does not make statistical sense and the latter can be done by using fixed theta instead of zero theta.')
if (is.null(lossmiss)) {
ouparfn = oupar
oujacfn = oujac
ouhessfn = ouhess
} else if (lossmiss == 'halt') {
ouparfn = ou_haltlost(oupar)
oujacfn = dou_haltlost(oujac)
ouhessfn = hou_haltlost(ouhess)
} else if (lossmiss == 'zap') {
ouparfn = ou_zaplost(oupar)
oujacfn = dou_zaplost(oujac)
ouhessfn = hou_zaplost(ouhess)
} else {
stop('`lossmiss` is invalid')
}
if (pat[[1]] == 'k' && pat[[2]] == 'k' && pat[[3]] == 'k')
return(list(par=oupar, jac=oujac, hess=ouhess, nparams=nparams_ou))
cmd = mkcmd(pat)
namestub = get_name_stub(pat)
par_re = get(namestub[['par']])
jac_re = get(namestub[['jac']])
hess_re = get(namestub[['hess']])
nparams = get(namestub[['nparams']])
if (all(sapply(fixed_args, is.null)))
fixed_args = list()
if (grepl('Ml', cmd, fixed = TRUE) || grepl('Mc', cmd, fixed = TRUE)) {
ouparfn = do.call(par_re, c(list(parfn=ouparfn), fixed_args))
ouhessfn = do.call(hess_re, c(list(hessfn=ouhessfn, jacfn=oujacfn), fixed_args))
oujacfn = do.call(jac_re, c(list(jacfn=oujacfn), fixed_args))
} else {
ouparfn = do.call(par_re, c(list(parfn=ouparfn), fixed_args))
ouhessfn = do.call(hess_re, c(list(hessfn=ouhessfn), fixed_args))
oujacfn = do.call(jac_re, c(list(jacfn=oujacfn), fixed_args))
}
list(par=ouparfn, jac=oujacfn, hess=ouhessfn, nparams=nparams)
}
rm('mk_fixed_arg')
rm('m')
rm('v')
rm('l')
rm('pat')
rm('name_stub')
rm('pkg_env')
rm('cmd2abcd')
rm('build_par')
rm('build_jac')
rm('build_hess')
rm('build_nparams')
NULL
NULL
|
metadata2SLD.Spatial <- function(obj, ...){
if(xmlValue(obj@xml[["//formcont"]]) == "SpatialPixelsDataFrame"){
metadata2SLD.SpatialPixels(obj, ...)
}
else {
stop("Format_Information_Content field in 'obj@xml' must specify an applicable sp class.")
}
}
metadata2SLD.SpatialPixels <- function(
obj,
Format_Information_Content = xmlValue(obj@xml[["//formcont"]]),
obj.name = normalizeFilename(deparse(substitute(obj))),
sld.file = .set.file.extension(obj.name, ".sld"),
Citation_title = xmlValue(obj@xml[["//title"]]),
ColorMap_type = "intervals",
opacity = 1,
brw.trg = 'Greys',
target.var,
...
){
l1 = newXMLNode("StyledLayerDescriptor", attrs=c("xsi:schemaLocation" = "http://www.opengis.net/sld StyledLayerDescriptor.xsd", version="1.0.0"), namespaceDefinitions=c("http://www.opengis.net/sld", "xsi" = "http://www.w3.org/2001/XMLSchema-instance", "ogc" = "http://www.opengis.net/ogc", "gml" = "http://www.opengis.net/gml"))
l2 <- newXMLNode("NamedLayer", parent = l1)
l3 <- newXMLNode("Name", paste(Citation_title, "(", Format_Information_Content, ")"), parent = l2)
l3b <- newXMLNode("UserStyle", parent = l2)
l4 <- newXMLNode("Title", paste(obj.name, "style", sep="_"), parent = l3b)
l4b <- newXMLNode("FeatureTypeStyle", parent = l3b)
l5 <- newXMLNode("Rule", parent = l4b)
l6 <- newXMLNode("RasterSymbolizer", parent = l5)
l7 <- newXMLNode("ColorMap", attrs=c(type=ColorMap_type), parent = l6)
if(missing(target.var)) {
txt <- sprintf('<ColorMapEntry color="%s" quantity="%.2f" label="%s" opacity="%.1f"/>', obj@palette@color, obj@palette@bounds[-1], obj@palette@names, rep(opacity, length(obj@palette@color)))
} else {
mm <- classIntervals(target.var, ...)
brew.p <- RColorBrewer::brewer.pal(n = length(mm$brks) - 1, name = brw.trg)
op <- findColours(mm, pal = brew.p, under = 'under', over = 'over', between = '-', cutlabels = F)
txt <- sprintf('<ColorMapEntry color="%s" quantity="%.2f" label="%s" opacity="%.1f"/>', attr(op, 'palette'), mm$brks[-1], attr(attr(op, 'table'), 'dimnames')[[1]], rep(opacity, length(mm$brks[-1])))
}
parseXMLAndAdd(txt, l7)
saveXML(l1, sld.file)
}
setMethod("metadata2SLD", "SpatialMetadata", metadata2SLD.Spatial)
|
df <- data.frame(a = 0:9, b = as.numeric(9:0))
test_that("scoped na_if_* errors when dplyr not installed", {
withr::local_options(list(lifecycle_verbosity = "quiet"))
with_mock(
requireNamespace = function(...) FALSE,
expect_error(na_if_all(df, 0), "Package `dplyr`"),
expect_error(na_if_at(df, "a", 0), "Package `dplyr`"),
expect_error(na_if_if(df, is.integer, 0), "Package `dplyr`"),
expect_error(na_if_not_all(df, 0), "Package `dplyr`"),
expect_error(na_if_not_at(df, "a", 0), "Package `dplyr`"),
expect_error(na_if_not_if(df, is.integer, 0), "Package `dplyr`")
)
})
test_that("scalar argument replaces all matching x", {
withr::local_options(list(lifecycle_verbosity = "quiet"))
expect_equal(
na_if_all(df, 0),
data.frame(a = c(NA, 1:9), b = c(9:1, NA))
)
expect_equal(
na_if_at(df, "a", 0),
data.frame(a = c(NA, 1:9), b = 9:0)
)
expect_equal(
na_if_if(df, is.integer, 0),
data.frame(a = c(NA, 1:9), b = 9:0)
)
expect_equal(
na_if_not_all(df, 0),
data.frame(a = c(0, rep(NA, 9)), b = c(rep(NA, 9), 0))
)
expect_equal(
na_if_not_at(df, "a", 0),
data.frame(a = c(0, rep(NA, 9)), b = 9:0)
)
expect_equal(
na_if_not_if(df, is.integer, 0),
data.frame(a = c(0, rep(NA, 9)), b = 9:0)
)
})
test_that("multiple scalar arguments replaces all matching x", {
withr::local_options(list(lifecycle_verbosity = "quiet"))
df <- data.frame(a = 0:9, b = as.numeric(0:9))
target <- c(NA, NA, 2:9)
expect_equal(na_if_all(df, 0, 1), data.frame(a = target, b = target))
expect_equal(na_if_at(df, "a", 0, 1), data.frame(a = target, b = 0:9))
expect_equal(na_if_if(df, is.integer, 0, 1), data.frame(a = target, b = 0:9))
target <- c(NA, 1:8, NA)
expect_equal(na_if_all(df, 0, 9), data.frame(a = target, b = target))
expect_equal(na_if_at(df, "a", 0, 9), data.frame(a = target, b = 0:9))
expect_equal(na_if_if(df, is.integer, 0, 9), data.frame(a = target, b = 0:9))
target <- c(0, 1, rep(NA, 8))
expect_equal(na_if_not_all(df, 0, 1), data.frame(a = target, b = target))
expect_equal(na_if_not_at(df, "a", 0, 1), data.frame(a = target, b = 0:9))
expect_equal(
na_if_not_if(df, is.integer, 0, 1), data.frame(a = target, b = 0:9)
)
target <- c(0, rep(NA, 8), 9)
expect_equal(na_if_not_all(df, 0, 9), data.frame(a = target, b = target))
expect_equal(na_if_not_at(df, "a", 0, 9), data.frame(a = target, b = 0:9))
expect_equal(
na_if_not_if(df, is.integer, 0, 9), data.frame(a = target, b = 0:9)
)
})
test_that("two-sided formula produces warning", {
withr::local_options(list(lifecycle_verbosity = "quiet"))
expect_warning(na_if_all(df, x ~ . < 1), "must be one-sided")
expect_warning(na_if_at(df, "a", x ~ . < 1), "must be one-sided")
expect_warning(na_if_if(df, is.integer, x ~ . < 1), "must be one-sided")
expect_warning(na_if_not_all(df, x ~ . < 1), "must be one-sided")
expect_warning(na_if_not_at(df, "a", x ~ . < 1), "must be one-sided")
expect_warning(na_if_not_if(df, is.integer, x ~ . < 1), "must be one-sided")
})
test_that("non-coercible argument produces warning", {
withr::local_options(list(lifecycle_verbosity = "quiet"))
expect_warning(na_if_all(df, lm(1 ~ 1)), "Argument.*lm")
expect_warning(na_if_at(df, "a", lm(1 ~ 1)), "Argument.*lm")
expect_warning(na_if_if(df, is.integer, lm(1 ~ 1)), "Argument.*lm")
expect_warning(na_if_not_all(df, lm(1 ~ 1)), "Argument.*lm")
expect_warning(na_if_not_at(df, "a", lm(1 ~ 1)), "Argument.*lm")
expect_warning(na_if_not_if(df, is.integer, lm(1 ~ 1)), "Argument.*lm")
})
test_that("multiple non-coercible arguments produce multiple warnings", {
withr::local_options(list(lifecycle_verbosity = "quiet"))
expect_warning(na_if_all(df, NULL, lm(1 ~ 1)), "NULL.*lm")
expect_warning(na_if_at(df, "a", NULL, lm(1 ~ 1)), "NULL.*lm")
expect_warning(na_if_if(df, is.integer, NULL, lm(1 ~ 1)), "NULL.*lm")
expect_warning(na_if_not_all(df, NULL, lm(1 ~ 1)), "NULL.*lm")
expect_warning(na_if_not_at(df, "a", NULL, lm(1 ~ 1)), "NULL.*lm")
expect_warning(na_if_not_if(df, is.integer, NULL, lm(1 ~ 1)), "NULL.*lm")
})
test_that("no ... produces warning", {
withr::local_options(list(lifecycle_verbosity = "quiet"))
expect_warning(na_if_all(df), "No values")
expect_warning(na_if_at(df, "a"), "No values")
expect_warning(na_if_if(df, is.integer), "No values")
expect_warning(na_if_not_all(df), "No values")
expect_warning(na_if_not_at(df, "a"), "No values")
expect_warning(na_if_not_if(df, is.integer), "No values")
})
test_that("deprecated scoped na_if_*()", {
lifecycle::expect_deprecated(na_if_all(df, 0))
lifecycle::expect_deprecated(na_if_at(df, "a", 0))
lifecycle::expect_deprecated(na_if_if(df, is.integer, 0))
lifecycle::expect_deprecated(na_if_not_all(df, 0))
lifecycle::expect_deprecated(na_if_not_at(df, "a", 0))
lifecycle::expect_deprecated(na_if_not_if(df, is.integer, 0))
})
|
test_that("layout IDs must be unique", {
app <- Dash$new()
expect_error(
app$layout(html$div(list(html$a(id = "a"), html$a(id = "a"), html$p(id="b"), html$p(id="c"), html$a(id="c")))),
"layout ids must be unique -- please check the following list of duplicated ids: 'a, c'"
)
})
test_that("app$layout() only accepts components, or functions that return components", {
app <- Dash$new()
expect_error(
app$layout(html$a(id = "a"), html$a(id = "a")),
'unused argument (html$a(id = "a"))',
fixed = TRUE)
})
test_app <- dash_app()
set_get_layout_new <- function(..., app = test_app) set_layout(app, ...)$layout_get()
set_get_layout_old <- function(..., app = test_app) { app$layout(...); app$layout_get() }
test_that("Can set empty layout, couldn't before", {
expect_error(set_get_layout_new(), NA)
expect_error(set_get_layout_old())
})
test_that("Layout errors", {
expect_error(set_get_layout_new("test", app = "not a dash app"))
expect_error(set_get_layout_new(foo = "test"))
expect_error(set_get_layout_new(div("one"), h2("two"), id = "test"))
})
test_that("Layout basics", {
expect_identical(
set_get_layout_new(div("one"), h2("two")),
set_get_layout_old(html$div(list(
html$div("one"), html$h2("two")
)))
)
expect_identical(set_get_layout_new("one", "two"), set_get_layout_new(list("one", "two")))
expect_identical(
set_get_layout_new(function() div("one", "two")),
set_get_layout_old(function() html$div(list("one", "two")))
)
})
test_that("set_layout replaces previous layout", {
expect_identical(
(dash_app() %>% set_layout("foo") %>% set_layout("bar"))$layout_get(),
(dash_app() %>% set_layout("bar"))$layout_get()
)
})
test_that("NULL layout elements", {
expect_identical(
set_get_layout_new("one", if (TRUE) "two", "three"),
set_get_layout_new("one", "two", "three")
)
expect_identical(
set_get_layout_new("one", if (FALSE) "two", "three"),
set_get_layout_new("one", "three")
)
})
test_that("No need to place everything in containers and lists", {
expect_error(set_get_layout_new("test"), NA)
expect_error(set_get_layout_old("test"))
expect_identical(
set_get_layout_new(div("one", "two")),
set_get_layout_old(html$div(list("one", "two")))
)
expect_identical(set_get_layout_new("test"), set_get_layout_old(html$span("test")))
expect_identical(
set_get_layout_new("one", 5, TRUE),
set_get_layout_old(html$div(list(
html$span("one"),
html$span(5),
html$span(TRUE)
)))
)
})
test_that("Function as layout works", {
app1 <- Dash$new()
set.seed(1000)
runif(1)
set_layout(app1, div(runif(1)))
app1_layout1 <- app1$layout_get()
app1_layout2 <- app1$layout_get()
expect_identical(app1_layout1, app1_layout2)
app2 <- Dash$new()
set.seed(1000)
runif(1)
app2$layout(html$div(runif(1)))
app2_layout <- app2$layout_get()
expect_identical(app1_layout1, app2_layout)
app1_fx <- Dash$new()
set.seed(1000)
set_layout(app1_fx, function() div(runif(1)))
app1_fx_layout1 <- app1_fx$layout_get()
app1_fx_layout2 <- app1_fx$layout_get()
expect_identical(app1_layout1, app1_fx_layout1)
expect_false(identical(app1_fx_layout1, app1_fx_layout2))
app2_fx <- Dash$new()
set.seed(1000)
app2_fx$layout(function() html$div(runif(1)))
app2_fx_layout1 <- app2_fx$layout_get()
app2_fx_layout2 <- app2_fx$layout_get()
expect_identical(app1_fx_layout1, app2_fx_layout1)
expect_identical(app1_fx_layout2, app2_fx_layout2)
})
test_that("Sample apps layout are identical with the compact syntax", {
expect_identical(
set_get_layout_old(
html$div(list(
html$div('Dash To-Do List'),
dccInput(id = 'new-item'),
html$button("Add", id = "add"),
html$button("Clear Done", id = "clear-done"),
html$div(id = "list-container"),
html$div(id = "totals")
))
),
set_get_layout_new(
div('Dash To-Do List'),
dccInput(id = 'new-item'),
button("Add", id = "add"),
button("Clear Done", id = "clear-done"),
div(id = "list-container"),
div(id = "totals")
)
)
expect_identical(
set_get_layout_old(
dash:::htmlDiv(
list(
dash:::htmlH1('Hello Dash'),
dash:::htmlDiv(children = "Dash: A web application framework for R."),
dccGraph(
figure=list(
data=list(
list(
x=list(1, 2, 3),
y=list(4, 1, 2),
type='bar',
name='SF'
),
list(
x=list(1, 2, 3),
y=list(2, 4, 5),
type='bar',
name='Montreal'
)
),
layout = list(title='Dash Data Visualization')
)
)
)
)
),
set_get_layout_new(
h1('Hello Dash'),
div("Dash: A web application framework for R."),
dccGraph(
figure=list(
data=list(
list(
x=list(1, 2, 3),
y=list(4, 1, 2),
type='bar',
name='SF'
),
list(
x=list(1, 2, 3),
y=list(2, 4, 5),
type='bar',
name='Montreal'
)
),
layout = list(title='Dash Data Visualization')
)
)
)
)
})
|
library(EcoNetGen)
set.seed(2222)
replicate(1000,
netgen(net_size = 50,
ave_module_size = 10,
min_module_size = 4,
min_submod_size = 2,
net_type = "bi-partite nested",
ave_degree = 10,
rewire_prob_global = 0.3,
rewire_prob_local = 0.1,
mixing_probs = c(0.2, 0.2, 0.2, 0.2, 0.2, 0.2 ,0.2),
verbose = FALSE)
)
set.seed(1234)
netgen(net_size = 30,
ave_module_size = 10,
min_module_size = 1,
min_submod_size = 1,
net_type = "bn",
ave_degree = 10,
rewire_prob_global = 0.2,
rewire_prob_local = 0.0,
mixing_probs = c(0.2, 0.2, 0.2, 0.2, 0.2, 0.0 ,0.0),
verbose = FALSE)
set.seed(2222)
replicate(1000,
netgen(net_size = 50,
ave_module_size = 25,
min_module_size = 10,
min_submod_size = 1,
net_type = "mixed",
ave_degree = 9,
rewire_prob_global = 0.0,
rewire_prob_local = 0.0,
mixing_probs = c(1,1,1,0.1,0.1,0.1,0.1),
verbose = FALSE)
)
|
NAME <- "diffPrint"
source(file.path('_helper', 'init.R'))
mx.2 <- matrix(1:100, ncol=2)
mx.4 <- mx.3 <- mx.2
mx.3[31, 2] <- 111L
mx.3a <- mx.3[-31, ]
set.seed(2)
mx.4[cbind(sample(1:50, 6), sample(1:2, 6, replace=TRUE))] <-
sample(-(1:50), 6)
mx.5 <- matrix(1:9, 3)
mx.6 <- matrix(12:1, 4)
mx.6[4,] <- c(3L, 6L, 9L)
all.equal(as.character(diffPrint(mx.2, mx.3)), rdsf(100))
all.equal(as.character(diffPrint(mx.2, mx.3, mode="unified")), rdsf(150))
all.equal(as.character(diffPrint(mx.2, mx.3, mode="context")), rdsf(175))
all.equal(as.character(diffPrint(mx.2, mx.3a)), rdsf(200))
all.equal(as.character(diffPrint(mx.2, mx.3a, mode="unified")), rdsf(300))
all.equal(as.character(diffPrint(mx.2, mx.4)), rdsf(400))
all.equal(as.character(diffPrint(mx.2, mx.4, mode="unified")), rdsf(500))
all.equal(as.character(diffPrint(mx.5, mx.6)), rdsf(600))
all.equal(as.character(diffPrint(mx.5, mx.6, mode="unified")), rdsf(700))
all.equal(as.character(diffPrint(mx.5, mx.6, mode="context")), rdsf(800))
set.seed(2)
A <- B <- matrix(sample(1:80), nrow=16)
B[cbind(sample(5:16, 4), sample(1:5, 4))] <- sample(30:80, 4)
all.equal(as.character(diffPrint(A, B)), rdsf(900))
all.equal(as.character(diffPrint(A, B, mode="unified")), rdsf(1000))
all.equal(as.character(diffPrint(A, B, mode="context")), rdsf(1100))
all.equal(as.character(diffPrint(diffobj:::.mx1, diffobj:::.mx2)), rdsf(1200))
all.equal(as.character(diffPrint(lst.1, lst.3)), rdsf(1300))
all.equal(as.character(diffPrint(lst.1, lst.3, mode="unified")), rdsf(1400))
all.equal(as.character(diffPrint(lst.4, lst.5)), rdsf(1500))
all.equal(as.character(diffPrint(lst.4, lst.5, mode="context")), rdsf(1600))
all.equal(
as.character(diffPrint(list(1, list(2, list(1:3))), list(list(list(1:3))))),
rdsf(1650)
)
all.equal(as.character(diffPrint(iris.s, iris.2)), rdsf(1700))
all.equal(
as.character(diffPrint(iris.s, iris.2, mode="sidebyside")), rdsf(1800)
)
all.equal(as.character(diffPrint(iris.s, iris.c)), rdsf(1900))
all.equal(as.character(diffPrint(iris.s, iris.3)), rdsf(2000))
all.equal(
as.character(diffPrint(iris.s, iris.3, mode="sidebyside")), rdsf(2100)
)
all.equal(as.character(diffPrint(iris.s, iris.4, mode="unified")), rdsf(2150))
all.equal(
as.character(diffPrint(iris.s, iris.4, mode="sidebyside")), rdsf(2200)
)
all.equal(
as.character(diffPrint(iris.5, iris.4, mode="sidebyside")), rdsf(2250)
)
all.equal(as.character(diffPrint(iris.3a, iris.4a)), rdsf(2300))
all.equal(
as.character(diffPrint(iris.s, iris.3, mode="sidebyside")), rdsf(2350)
)
all.equal(as.character(diffPrint(iris.s, iris.s[-2])), rdsf(2370))
all.equal(
as.character(diffPrint(iris.s, iris.s[-2], mode="sidebyside")), rdsf(2383)
)
all.equal(
as.character(diffPrint(cars[1:5,], mtcars[1:5,], mode="sidebyside")),
rdsf(2380)
)
all.equal(
as.character(
diffPrint(
iris.s, iris.4, mode="sidebyside", guides=function(x, y) integer()
) ),
rdsf(2400)
)
all.equal(
as.character(diffPrint(iris.s, iris.4, mode="sidebyside", guides=FALSE)),
rdsf(2500)
)
arr.1 <- arr.2 <- array(1:24, c(4, 2, 3))
arr.2[c(3, 20)] <- 99L
all.equal(as.character(diffPrint(arr.1, arr.2)), rdsf(2600))
all.equal(
as.character(diffPrint(list(1, 2, 3), matrix(1:9, 3))),
rdsf(2700)
)
all.equal(
as.character(diffPrint(list(25, 2, 3), matrix(1:9, 3))),
rdsf(2800)
)
all.equal(
as.character(
diffPrint(list(c(1, 4, 7), c(2, 5, 8), c(3, 6, 9)), matrix(1:9, 3))
),
rdsf(2900)
)
res1 <- structure(
c(-1717, 101, 0.938678984853783),
.Names = c("intercept", "slope", "rsq"), class = "fastlm"
)
res2 <- structure(
c(-3.541306e+13, 701248600000, 0.938679),
.Names = c("intercept", "slope", "rsq"), class = "fastlm"
)
all.equal(as.character(diffPrint(res1, res2)), rdsf(3000))
all.equal(
as.character(diffPrint(unname(res1), unname(res2))), rdsf(3100)
)
all.equal(
as.character(diffPrint(factor(1:100), factor(c(1:99, 101)))), rdsf(3200)
)
f1 <- factor(1:100)
f2 <- factor(c(1:20, 22:99, 101))
all.equal(capture.output(diffPrint(f1, f2)), txtf(100))
f3 <- factor(letters[1:10])
f4 <- factor(letters[1:10], levels=letters[1:11])
all.equal(capture.output(diffPrint(f3, f4)), txtf(150))
nhtemp2 <- nhtemp
nhtemp2[c(5, 30)] <- -999
all.equal(capture.output(diffPrint(nhtemp, nhtemp2)), txtf(175))
print.diffobj_test_c1 <- function(x, ...) {
writeLines(c("Header row 1", "header row 2"))
print(c(x))
writeLines(c("", "Footer row 1", "", "footer row2"))
}
m1 <- structure(1:30, class='diffobj_test_c1')
m2 <- structure(2:51, class='diffobj_test_c1')
all.equal(capture.output(diffPrint(m1, m2)), txtf(200), print=TRUE)
all.equal(
as.character(diffPrint(letters, LETTERS, format="raw", pager="off")),
rdsf(3300)
)
all.equal(
as.character(diffPrint(letters, LETTERS, format="raw", disp.width=40)),
rdsf(3400)
)
try(diffPrint(letters, LETTERS, disp.width=5))
invisible(diffobj:::make_diff_fun())
a <- "G\xc3\xa1bor Cs\xc3\xa1rdi"
b <- sprintf("%s wow", a)
Encoding(a) <- 'UTF-8'
Encoding(b) <- 'UTF-8'
new <- (as.character(diffPrint(list(hell=a, b=NULL), list(hell=b, b=list()))))
ref <- structure(
c("\033[33m<\033[39m \033[33mlist(hell = a, b = N..\033[39m \033[34m>\033[39m \033[34mlist(hell = b, b = l..\033[39m",
"\033[36m@@ 1,6 @@ \033[39m \033[36m@@ 1,6 @@ \033[39m",
" \033[90m\033[39m$hell\033[90m\033[39m \033[90m\033[39m$hell\033[90m\033[39m ",
"\033[33m<\033[39m \033[90m[1] \033[39m\033[33m\"G\xc3\xa1bor Cs\xc3\xa1rdi\"\033[39m\033[90m\033[39m \033[34m>\033[39m \033[90m[1] \033[39m\033[34m\"G\xc3\xa1bor Cs\xc3\xa1rdi wow\"\033[39m\033[90m\033[39m",
" ", " \033[90m\033[39m$b\033[90m\033[39m \033[90m\033[39m$b\033[90m\033[39m ",
"\033[33m<\033[39m \033[90m\033[39m\033[33mNULL\033[39m\033[90m\033[39m \033[34m>\033[39m \033[90m\033[39m\033[34mlist\033[39m\033[34m()\033[39m\033[90m\033[39m ",
" "
),
len = 8L
)
Encoding(ref) <- 'UTF-8'
all.equal(new, ref)
bytes <- "\x81"
Encoding(bytes) <- "bytes"
isTRUE(!any(diffPrint(bytes, bytes)))
all.equal(
as.character(diffPrint(quote(zz + 1), quote(zz + 3))),
structure(
c("\033[33m<\033[39m \033[33mquote(..\033[39m \033[34m>\033[39m \033[34mquote(..\033[39m", "\033[36m@@ 1 @@ \033[39m \033[36m@@ 1 @@ \033[39m", "\033[33m<\033[39m \033[90m\033[39mzz + \033[33m1\033[39m\033[90m\033[39m \033[34m>\033[39m \033[90m\033[39mzz + \033[34m3\033[39m\033[90m\033[39m "
), len = 3L
)
)
all.equal(
as.character(diffPrint(quote(x), quote(y))),
structure(
c("\033[33m<\033[39m \033[33mquote(x)\033[39m \033[34m>\033[39m \033[34mquote(y)\033[39m", "\033[36m@@ 1 @@ \033[39m \033[36m@@ 1 @@ \033[39m", "\033[33m<\033[39m \033[90m\033[39m\033[33mx\033[39m\033[90m\033[39m \033[34m>\033[39m \033[90m\033[39m\033[34my\033[39m\033[90m\033[39m "),
len = 3L
)
)
env <- new.env()
env$print <- function(x, ...) stop('boom')
try(evalq(diffPrint(1:3, 1:4), env))
f <- function(a, b, ...) {
print <- function(x, ...) stop('boom2')
diffPrint(a, b, ...)
}
try(f(1:3, 1:4, format='raw'))
|
od_AQUA <- function(Fx, b1=NULL, A1=NULL, b2=NULL, A2=NULL, b3=NULL, A3=NULL,
w0=NULL, bin=FALSE, crit="D", h=NULL, M.anchor=NULL,
ver.qa="+", conic=TRUE, t.max=120, echo=TRUE) {
cl <- match.call()
verify(cl, Fx = Fx, b1 = b1, A1 = A1, b2 = b2, A2 = A2, b3 = b3, A3 = A3,
w0 = w0, bin = bin, crit = crit, h = h, M.anchor = M.anchor,
ver.qa = ver.qa, conic = conic, t.max = t.max, echo = echo)
n <- nrow(Fx); m <- ncol(Fx)
if (!is.null(b1) && is.null(A1)) A1 <- matrix(1, nrow = length(b1), ncol = n)
if (!is.null(b2) && is.null(A2)) A2 <- matrix(1, nrow = length(b2), ncol = n)
if (!is.null(b3) && is.null(A3)) A3 <- matrix(1, nrow = length(b3), ncol = n)
if (is.null(w0)) w0 <- rep(0, n)
if (crit == "C" && is.null(h)) h <- c(rep(0, m - 1), 1)
if (crit == "c")
stop("The pure c-optimality is not implemented for AQUA. Try its regularized version: the C-optimality.")
if (!is.null(w0) && sum(w0) > 0) {
A2 <- rbind(A2, diag(n)[w0 > 0, ])
b2 <- c(b2, w0[w0 > 0])
}
info <- paste("Running od_AQUA for cca", t.max, "seconds")
info <- paste(info, " starting at ", Sys.time(), ".", sep = "")
print(info, quote = FALSE)
info <- paste("The problem size is n=", n, sep = "")
info <- paste(info, ", m=", m, sep = "")
info <- paste(info, ", k=", length(c(b1, b2, b3)), ".", sep = "")
print(info, quote = FALSE)
start <- as.numeric(proc.time()[3])
if (crit == "D") res <- od_D_AQUA(Fx, b1, A1, b2, A2, b3, A3, bin,
M.anchor = M.anchor, ver.qa, conic, t.max)
if (crit == "A") res <- od_A_AQUA(Fx, b1, A1, b2, A2, b3, A3, bin,
M.anchor = M.anchor, ver.qa, conic, t.max)
if (crit == "I") {
M.anchor.A <- NULL
if (!is.null(M.anchor)) {
L <- m*infmat(Fx, rep(1, n), echo = FALSE)/sum(Fx^2)
M.anchor.A <- t(solve(chol(L))) %*% M.anchor %*% solve(chol(L))
}
res <- od_A_AQUA(Fx_ItoA(Fx, echo = FALSE),
b1, A1, b2, A2, b3, A3, bin,
M.anchor = M.anchor.A, ver.qa, conic, t.max)
}
if (crit == "C") {
M.anchor.A <- NULL
if (!is.null(M.anchor)) {
alpha <- 0.05
L <- alpha*diag(m) + (1 - alpha)*m*h %*% t(h)/sum(h^2)
M.anchor.A <- t(solve(chol(L))) %*% M.anchor %*% solve(chol(L))
}
res <- od_A_AQUA(Fx_CtoA(Fx, h, echo = FALSE),
b1, A1, b2, A2, b3, A3, bin,
M.anchor = M.anchor.A, ver.qa, conic, t.max)
}
w <- res$w.best
if (!is.null(w)) {
supp <- (1:n)[w > 0.5]; w.supp <- w[supp]
M.best <- infmat(Fx, w, echo = FALSE)
Phi.best <- optcrit(Fx, w, crit = crit, h = h, echo = FALSE)
} else {
supp <- NULL; w.supp <- NULL
M.best <- NULL; Phi.best <- 0
}
w <- res$w.best
if (!is.null(w)) {
supp <- (1:n)[w > 0.5]; w.supp <- w[supp]
M.best <- infmat(Fx, w, echo = FALSE)
Phi.best <- optcrit(Fx, w, crit = crit, h = h, echo = FALSE)
err <- c()
if (!is.null(b1)) err <- c(err, pmin(A1 %*% w - b1, 0))
if (!is.null(b2)) err <- c(err, pmin(b2 - A2 %*% w, 0))
if (!is.null(b3)) err <- c(err, abs(A3 %*% w - b3))
if (max(err) > 1e-05)
warning(cat("Some constraints are significantly violated:", round(err, 6)))
} else {
supp <- NULL; w.supp <- NULL
M.best <- NULL; Phi.best <- 0
warning("AQUA was not able to find any meaningful solution within the alloted time.")
}
t.act <- round(as.numeric(proc.time()[3]) - start, 2)
return(list(call = cl, w.best = w, supp = supp, w.supp = w.supp, M.best = M.best,
Phi.best = Phi.best, status = res$status, t.act = t.act))
}
|
test_that("as_vegaspec translates", {
spec_ref <- spec_mtcars %>% vw_as_json() %>% as_vegaspec()
spec_json <- vw_as_json(spec_ref)
expect_identical(as_vegaspec(spec_ref), spec_ref)
expect_identical(as_vegaspec(spec_json), spec_ref)
})
test_that("class is correct", {
expect_type(as_vegaspec(unclass(spec_mtcars)), "list")
expect_s3_class(as_vegaspec(unclass(spec_mtcars)), "vegaspec")
expect_s3_class(as_vegaspec(unclass(spec_mtcars)), "vegaspec_vega_lite")
spec_mtcars_vega <- vw_to_vega(spec_mtcars)
expect_type(spec_mtcars_vega, "list")
expect_s3_class(spec_mtcars_vega, "vegaspec")
expect_s3_class(spec_mtcars_vega, "vegaspec_vega")
})
test_that("vw_as_json handles NULLS", {
spec_test <- list(
`$schema` = "https://vega.github.io/schema/vega-lite/v2.json",
width = NULL,
height = NULL
)
spec_test_json <- vw_as_json(spec_test)
expect_match(spec_test_json, '"width": null')
expect_match(spec_test_json, '"height": null')
})
test_that("vegaspec without $schema warns and adds element", {
spec_test <- list()
expect_warning(
spec_ref <- as_vegaspec(spec_test)
)
expect_identical(
spec_ref,
as_vegaspec(list(`$schema` = vega_schema()))
)
})
test_that("as_vegaspec reads UTF-8 correctly", {
filename <- "test_encoding_utf8.vl4.json"
description <- "ceci une version allégée d'une spécification vega-lite"
withr::local_file(filename)
fileConn <- file(filename, encoding = "UTF-8")
writeLines(
glue_js(
"{",
" \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.json\",",
" \"description\": \"${description}\"",
"}"
),
fileConn
)
close(fileConn)
myspec <- vegawidget::as_vegaspec(filename)
expect_identical(myspec$description, description)
})
test_that("as_vegaspec reads urls correctly", {
skip_on_cran()
myspec <- as_vegaspec("https://raw.githubusercontent.com/vega/vega-lite/master/examples/specs/bar.vl.json")
expect_s3_class(myspec, "vegaspec_vega_lite")
})
|
SummaryMarginals <- function(marginals) {
margs <- marginals$marginals
nms0 <- names(margs)
types <- marginals$types
nms <- mu <- sd <- n <-c()
for (i in 1:length(types)) {
if(!types[i]) {
msd <- MeanSD(margs[[i]])
nms <- c(nms, nms0[i])
mu <- c(mu, msd[1])
sd <- c(sd, msd[2])
n <- c(n, nrow(margs[[i]]))
}
}
df <- data.frame(Mean=mu, SD=sd, n=n)
rownames(df) <- nms
return(df)
}
|
LS.kalman <- function(series, start, order = c(p = 0, q = 0), ar.order = NULL,
ma.order = NULL, sd.order = NULL, d.order = NULL,
include.d = FALSE, m = NULL) {
x <- start
T. <- length(series)
if (is.null(ar.order)) {
ar.order <- rep(0, order[1])
}
if (is.null(ma.order)) {
ma.order <- rep(0, order[2])
}
if (is.null(sd.order)) {
sd.order <- 0
}
if (is.null(d.order)) {
d.order <- 0
}
if (is.null(m)) {
m <- trunc(0.25 * T.^0.8)
}
M <- m + 1
u <- (1:T.) / T.
p <- na.omit(c(ar.order, ma.order, sd.order))
if (include.d == TRUE) {
p <- na.omit(c(ar.order, ma.order, d.order, sd.order))
}
phi. <- numeric()
theta. <- numeric()
sigma. <- numeric()
d. <- numeric()
for (j in 1:length(u)) {
X <- numeric()
k <- 1
for (i in 1:length(p)) {
X[i] <- sum(x[k:(k + p[i])] * u[j]^(0:p[i]))
k <- k + p[i] + 1
}
phi <- numeric()
k <- 1
if (order[1] > 0) {
phi[is.na(ar.order) == 1] <- 0
phi[is.na(ar.order) == 0] <- X[k:(length(na.omit(ar.order)))]
k <- length(na.omit(ar.order)) + 1
phi. <- rbind(phi., phi)
}
theta <- numeric()
if (order[2] > 0) {
theta[is.na(ma.order) == 1] <- 0
theta[is.na(ma.order) == 0] <- X[k:(length(na.omit(ma.order)) + k - 1)]
k <- length(na.omit(ma.order)) + k
theta. <- rbind(theta., theta)
}
d <- 0
if (include.d == TRUE) {
d <- X[k]
k <- k + 1
d. <- c(d., d)
}
sigma <- X[k]
sigma. <- c(sigma., sigma)
}
sigma <- sigma.
Omega <- matrix(0, nrow = M, ncol = M)
diag(Omega) <- 1
X <- rep(0, M)
delta <- vector("numeric")
hat.y <- vector("numeric")
for (i in 1:T.) {
if (is.null(dim(phi.)) == 1 & is.null(dim(theta.)) == 1) {
psi <- c(1, ARMAtoMA(ar = numeric(), ma = numeric(), lag.max = m))
}
if (is.null(dim(phi.)) == 1 & is.null(dim(theta.)) == 0) {
psi <- c(1, ARMAtoMA(ar = numeric(), ma = theta.[i, ], lag.max = m))
}
if (is.null(dim(phi.)) == 0 & is.null(dim(theta.)) == 1) {
psi <- c(1, ARMAtoMA(ar = phi.[i, ], ma = numeric(), lag.max = m))
}
if (is.null(dim(phi.)) == 0 & is.null(dim(theta.)) == 0) {
psi <- c(1, ARMAtoMA(ar = phi.[i, ], ma = theta.[i, ], lag.max = m))
}
psi. <- numeric()
if (include.d == TRUE) {
eta <- gamma(0:m + d.[i]) / (gamma(0:m + 1) * gamma(d.[i]))
for (k in 0:m) {
psi.[k + 1] <- sum(psi[1:(k + 1)] * rev(eta[1:(k + 1)]))
}
psi <- psi.
}
g <- sigma[i] * rev(psi)
aux <- Omega %*% g
delta[i] <- g %*% aux
F. <- matrix(0, M - 1, M - 1)
diag(F.) <- 1
F. <- cbind(0, F.)
F. <- rbind(F., 0)
Theta <- c(F. %*% aux)
Q <- matrix(0, M, M)
Q[M, M] <- 1
if (is.na(series[i])) {
Omega <- F. %*% Omega %*% t(F.) + Q
hat.y[i] <- t(g) %*% X
X <- F. %*% X
}
else {
Omega <- F. %*% Omega %*% t(F.) + Q - Theta %*% solve(delta[i]) %*% Theta
hat.y[i] <- t(g) %*% X
X <- F. %*% X + Theta %*% solve(delta[i]) %*% (series[i] - hat.y[i])
}
}
residuals <- (series - hat.y) / sqrt(delta[1:T.])
fitted.values <- hat.y
return(list(residuals = residuals, fitted.values = fitted.values, delta = delta))
}
|
getDist <- function(n, dist, mu, sigma,
par.location = 0, par.scale = 1, par.shape = 1, dist.par = NULL,
rounding.factor = NULL) {
if(rounding.factor == 0 || is.null(rounding.factor)){rounding.factor = NULL}
switch(dist,
Uniform = {
a <- 0
b <- 1
EX <- (a+b)/2
VarX <- (b-a)^2/12
xtemp <- runif(n, min = a, max = b)
},
Normal = {
a <- par.location
b <- par.scale
if(!is.null(dist.par)){
a <- dist.par[1]
b <- dist.par[2]
}
EX <- a
VarX <- b^2
xtemp <- rnorm(n, mean = a, sd = b)
},
Normal2 = {
a <- par.location
b <- par.scale
if(!is.null(dist.par)){
a <- dist.par[1]
b <- dist.par[2]
}
EX <- a^2 + b^2
VarX <- 4 * a^2 * b^2 + 2 * b^4
xtemp <- (rnorm(n, mean = a, sd = b))^2
},
DoubleExp = {
a <- par.location
b <- par.scale
if(!is.null(dist.par)){
a <- dist.par[1]
b <- dist.par[2]
}
EX <- a
VarX <- 2 * b^2
xtemp <- log(runif(n) / runif(n)) / 2^(0.5)
},
DoubleExp2 = {
a <- par.location
b <- par.scale
if(!is.null(dist.par)){
a <- dist.par[1]
b <- dist.par[2]
}
EX <- 2 * b^2 + a^2
EY3 <- 6 * b^3 + 6 * a * b^2 + 5 * a^3
EY4 <- 24 * b^4 + 4 * a * EY3 - 6 * a^2 * (2 * b^2 + a^2) + 5 * a^4
VarX <- EY4 - EX^2
xtemp <- (log(runif(n) / runif(n)))^2
},
LogNormal = {
a <- par.location
b <- par.scale
if(!is.null(dist.par)){
a <- dist.par[1]
b <- dist.par[2]
}
EX <- exp(a + b^2 / 2)
VarX <- exp(2 * (a + b^2)) - exp(2 * a + b^2)
xtemp <- rlnorm(n, meanlog = a, sdlog = b)
},
Gamma = {
k <- par.scale
o <- par.shape
if(!is.null(dist.par)){
k <- dist.par[1]
o <- dist.par[2]
}
EX <- k * o
VarX <- o * k^2
xtemp <- rgamma(n, shape = o, scale = k)
},
Weibull = {
k <- par.shape
l <- par.scale
if(!is.null(dist.par)){
k <- dist.par[1]
l <- dist.par[2]
}
EX <- l * gamma(1 + 1 / k)
VarX <- l^2 * (gamma(1 + 2 / k) - (gamma(1 + 1 / k))^2)
xtemp <- rweibull(n, shape = k, scale = l)
},
t = {
v <- par.shape
if(!is.null(dist.par)){
v <- dist.par[1]
}
EX <- 0
VarX <- v/(v-2)
xtemp <- rt(n, v)
},
{
a <- par.location
b <- par.scale
if(!is.null(dist.par)){
a <- dist.par[1]
b <- dist.par[2]
}
EX <- a
VarX <- b^2
xtemp <- rnorm(n, mean = a, sd = b)
}
)
z <- (xtemp - EX) / VarX^(0.5)
x <- mu + sigma * z
if(!is.null(rounding.factor)){
x <- round(x/rounding.factor) * rounding.factor
}
return(x)
}
|
library(RNeo4j)
context("Properties")
skip_on_cran()
neo4j = startTestGraph()
test_that("string properties are added correctly", {
n = createNode(neo4j, "Person", name="Alice")
expect_equal(n$name, "Alice")
})
test_that("string properties are retrieved with correct encoding", {
n = createNode(neo4j, "Bar", location="México")
expect_equal(n$location, "México")
})
test_that("numeric properties are added correctly", {
n = createNode(neo4j, "Person", age=23)
expect_equal(n$age, 23)
})
test_that("boolean properties are added correctly", {
n = createNode(neo4j, "Person", awesome=TRUE)
expect_true(n$awesome)
})
test_that("arrays of strings are added correctly", {
n = createNode(neo4j, "Person", names=c("Alice", "Bob"))
expect_equal(n$names, c("Alice", "Bob"))
})
test_that("arrays of numerics are added correctly", {
n = createNode(neo4j, "Person", ages=c(1, 2, 3))
expect_equal(n$ages, c(1, 2, 3))
})
test_that("arrays of booleans are added correctly", {
n = createNode(neo4j, "Person", awesome=c(TRUE, FALSE))
expect_equal(n$awesome, c(TRUE, FALSE))
})
test_that("updateProp works with strings", {
n = createNode(neo4j, "Person")
n = updateProp(n, name="Nicole")
expect_equal(n$name, "Nicole")
nicole = getSingleNode(neo4j, "MATCH (n) WHERE n.name = 'Nicole' RETURN n")
expect_true(!is.null(nicole))
})
test_that("updateProp works with numerics", {
n = createNode(neo4j, "Person")
n = updateProp(n, age=24)
expect_equal(n$age, 24)
twentyfour = getSingleNode(neo4j, "MATCH (n) WHERE n.age = 24 RETURN n")
expect_true(!is.null(twentyfour))
})
test_that("updateProp works with booleans", {
n = createNode(neo4j, "Person")
n = updateProp(n, awesome=TRUE)
expect_true(n$awesome)
awesome = getSingleNode(neo4j, "MATCH (n) WHERE n.awesome = true RETURN n")
expect_true(!is.null(awesome))
})
test_that("updateProp both replaces and creates new properties", {
n = createNode(neo4j, "Person", name="Nicole")
n = updateProp(n, name="Julian", age=100)
expect_equal(n$name, "Julian")
expect_equal(n$age, 100)
})
test_that("updateProp works with array properties", {
n = createNode(neo4j, "Person", name="Nicole")
n = updateProp(n, ages=c(1, 2, 3))
expect_equal(n$name, "Nicole")
expect_equal(n$ages, c(1, 2, 3))
})
test_that("deleteProp works with given property", {
n = createNode(neo4j, "Person", name="Nicole", age=24)
n = deleteProp(n, "age", "name")
expect_null(n$age)
expect_null(n$name)
})
test_that("deleteProp works with all=TRUE", {
n = createNode(neo4j, "Person", name="Nicole", age=24)
n = deleteProp(n, all=TRUE)
expect_null(n$age)
expect_null(n$name)
})
test_that("deleteProp works with a list of properties", {
n = createNode(neo4j, "Person", name="Nicole", age=24)
n = deleteProp(n, list("age"))
expect_null(n$age)
expect_equal(n$name, "Nicole")
})
test_that("updateProp works with a list of properties", {
n = createNode(neo4j, "Person", name="Nicole")
n = updateProp(n, list(name="Julian", age=100))
expect_equal(n$name, "Julian")
expect_equal(n$age, 100)
})
|
ICA.Sample.ContCont <- function(T0S0, T1S1, T0T0=1, T1T1=1, S0S0=1, S1S1=1,
T0T1=seq(-1, 1, by=.001), T0S1=seq(-1, 1, by=.001), T1S0=seq(-1, 1, by=.001),
S0S1=seq(-1, 1, by=.001), M=50000) {
T0S0_val <- T0S0
T1S1_val <- T1S1
T0T1_val <- T0T1
T0S1_val <- T0S1
T1S0_val <- T1S0
S0S1_val <- S0S1
Results <- na.exclude(matrix(NA, 1, 9))
colnames(Results) <- c("T0T1", "T0S0", "T0S1", "T1S0", "T1S1", "S0S1", "ICA", "Sigma.Delta.T", "delta")
for (i in 1: M) {
T0T1 <- runif(n = 1, min = min(T0T1_val), max = max(T0T1_val))
T0S0 <- runif(n = 1, min = min(T0S0_val), max = max(T0S0_val))
T0S1 <- runif(n = 1, min = min(T0S1_val), max = max(T0S1_val))
T1S0 <- runif(n = 1, min = min(T1S0_val), max = max(T1S0_val))
T1S1 <- runif(n = 1, min = min(T1S1_val), max = max(T1S1_val))
S0S1 <- runif(n = 1, min = min(S0S1_val), max = max(S0S1_val))
Sigma_c <- diag(4)
Sigma_c[2,1] <- Sigma_c[1,2] <- T0T1 * (sqrt(T0T0)*sqrt(T1T1))
Sigma_c[3,1] <- Sigma_c[1,3] <- T0S0 * (sqrt(T0T0)*sqrt(S0S0))
Sigma_c[4,1] <- Sigma_c[1,4] <- T0S1 * (sqrt(T0T0)*sqrt(S1S1))
Sigma_c[3,2] <- Sigma_c[2,3] <- T1S0 * (sqrt(T1T1)*sqrt(S0S0))
Sigma_c[4,2] <- Sigma_c[2,4] <- T1S1 * (sqrt(T1T1)*sqrt(S1S1))
Sigma_c[4,3] <- Sigma_c[3,4] <- S0S1 * (sqrt(S0S0)*sqrt(S1S1))
Sigma_c[1,1] <- T0T0
Sigma_c[2,2] <- T1T1
Sigma_c[3,3] <- S0S0
Sigma_c[4,4] <- S1S1
Cor_c <- cov2cor(Sigma_c)
Min.Eigen.Cor <- try(min(eigen(Cor_c)$values), TRUE)
if (Min.Eigen.Cor > 0) {
ICA <- ((sqrt(S0S0*T0T0)*Cor_c[3,1])+(sqrt(S1S1*T1T1)*Cor_c[4,2])-(sqrt(S0S0*T1T1)*Cor_c[3,2])-(sqrt(S1S1*T0T0)*Cor_c[4,1]))/(sqrt((T0T0+T1T1-(2*sqrt(T0T0*T1T1)*Cor_c[2,1]))*(S0S0+S1S1-(2*sqrt(S0S0*S1S1)*Cor_c[4,3]))))
if ((is.finite(ICA))==TRUE){
sigma.delta.T <- T0T0 + T1T1 - (2 * sqrt(T0T0*T1T1) * Cor_c[2,1])
delta <- sigma.delta.T * (1-(ICA**2))
results.part <- as.vector(cbind(T0T1, T0S0, T0S1, T1S0, T1S1, S0S1, ICA, sigma.delta.T, delta))
Results <- rbind(Results, results.part)
rownames(Results) <- NULL}
}
}
Results <- data.frame(Results, stringsAsFactors = TRUE)
rownames(Results) <- NULL
Total.Num.Matrices <- dim(Results)[1]
fit <-
list(Total.Num.Matrices=Total.Num.Matrices, Pos.Def=Results[,1:6], ICA=Results$ICA, GoodSurr=Results[,7:9], Call=match.call())
class(fit) <- "ICA.ContCont"
fit
}
plot.ICA.ContCont <- function(x, Xlab.ICA, Main.ICA, Type="Percent", Labels=FALSE, ICA=TRUE, Good.Surr=FALSE, Main.Good.Surr,
Par=par(oma=c(0, 0, 0, 0), mar=c(5.1, 4.1, 4.1, 2.1)), col, ...){
Object <- x
if (missing(Xlab.ICA)) {Xlab.ICA <- expression(rho[Delta])}
if (missing(Main.ICA)) {Main.ICA="ICA"}
if (missing(col)) {col <- c(8)}
if (ICA==TRUE){
dev.new()
par=Par
if (Type=="Freq"){
h <- hist(Object$ICA, ...)
h$density <- h$counts/sum(h$counts)
cumulMidPoint <- ecdf(x=Object$ICA)(h$mids)
labs <- paste(round((1-cumulMidPoint), digits=4)*100, "%", sep="")
if (Labels==FALSE){
plot(h,freq=T, xlab=Xlab.ICA, ylab="Frequency", col=col, main=Main.ICA)
}
if (Labels==TRUE){
plot(h,freq=T, xlab=Xlab.ICA, ylab="Frequency", col=col, main=Main.ICA, labels=labs)
}
}
if (Type=="Percent"){
h <- hist(Object$ICA, ...)
h$density <- h$counts/sum(h$counts)
cumulMidPoint <- ecdf(x=Object$ICA)(h$mids)
labs <- paste(round((1-cumulMidPoint), digits=4)*100, "%", sep="")
if (Labels==FALSE){
plot(h,freq=F, xlab=Xlab.ICA, ylab="Percentage", col=col, main=Main.ICA)
}
if (Labels==TRUE){
plot(h,freq=F, xlab=Xlab.ICA, ylab="Percentage", col=col, main=Main.ICA, labels=labs)
}
}
if (Type=="CumPerc"){
h <- hist(Object$ICA, breaks=length(Object$ICA), ...)
h$density <- h$counts/sum(h$counts)
cumulative <- cumsum(h$density)
plot(x=h$mids, y=cumulative, xlab=Xlab.ICA, ylab="Cumulative percentage", col=0, main=Main.ICA)
lines(x=h$mids, y=cumulative)
}
}
if (Good.Surr==TRUE){
if (missing(Main.Good.Surr)) {Main.Good.Surr = " "}
par=Par
if (Type=="Freq"){
h <- hist(Object$GoodSurr$delta, ...)
h$density <- h$counts/sum(h$counts)
cumulMidPoint <- ecdf(x=Object$GoodSurr$delta)(h$mids)
labs <- paste(round((1-cumulMidPoint), digits=4)*100, "%", sep="")
if (Labels==FALSE){
plot(h,freq=T, xlab=expression(delta), ylab="Frequency", main=Main.Good.Surr, col=col)
}
if (Labels==TRUE){
plot(h,freq=T, xlab=expression(delta), ylab="Frequency", col=col, labels=labs, main=Main.Good.Surr)
}
}
if (Type=="Percent"){
h <- hist(Object$GoodSurr$delta, ...)
h$density <- h$counts/sum(h$counts)
cumulMidPoint <- ecdf(x=Object$GoodSurr$delta)(h$mids)
labs <- paste(round((1-cumulMidPoint), digits=4)*100, "%", sep="")
if (Labels==FALSE){
plot(h,freq=F, xlab=expression(delta), ylab="Percentage", col=col, main=Main.Good.Surr)
}
if (Labels==TRUE){
plot(h,freq=F, xlab=expression(delta), ylab="Percentage", col=col, labels=labs, main=Main.Good.Surr)
}
}
if (Type=="CumPerc"){
h <- hist(Object$GoodSurr$delta, breaks=length(Object$GoodSurr$delta), ...)
h$density <- h$counts/sum(h$counts)
cumulative <- cumsum(h$density)
plot(x=h$mids, y=cumulative, xlab=expression(delta), ylab="Cumulative percentage", col=0, main=Main.Good.Surr)
lines(x=h$mids, y=cumulative)
}
}
}
summary.ICA.ContCont <- function(object, ..., Object){
if (missing(Object)){Object <- object}
mode <- function(data) {
x <- data
z <- density(x)
mode_val <- z$x[which.max(z$y)]
fit <- list(mode_val= mode_val)
}
cat("\nFunction call:\n\n")
print(Object$Call)
cat("\n\n
cat("\n
cat("\n
cat(Object$Total.Num.Matrices)
cat("\n\n
cat("\n
cat(nrow(Object$Pos.Def))
cat("\n\n\n
cat("\n
cat("Mean (SD) ICA: ", format(round(mean(Object$ICA), 4), nsmall = 4), " (", format(round(sd(Object$ICA), 4), nsmall = 4), ")",
" [min: ", format(round(min(Object$ICA), 4), nsmall = 4), "; max: ", format(round(max(Object$ICA), 4), nsmall = 4), "]", sep="")
cat("\nMode ICA: ", format(round(mode(Object$ICA)$mode_val, 4), nsmall = 4))
cat("\n\nQuantiles of the ICA distribution: \n\n")
quant <- quantile(Object$ICA, probs = c(.05, .10, .20, .50, .80, .90, .95))
print(quant)
}
|
Rd2list <- function(Rd) {
names(Rd) <- substring(sapply(Rd, attr, "Rd_tag"), 2)
temp_args <- Rd$arguments
Rd$arguments <- NULL
myrd <- lapply(Rd, unlist)
myrd <- lapply(myrd, paste, collapse = "")
temp_args <-
temp_args[sapply(temp_args , attr, "Rd_tag") == "\\item"]
temp_args <- lapply(temp_args, lapply, paste, collapse = "")
temp_args <- lapply(temp_args, "names<-", c("arg", "description"))
myrd$arguments <- temp_args
myrd
}
getHelpList <- function(...) {
thefile <- help(...)
myrd <- utils:::.getHelpFile(thefile)
Rd2list(myrd)
}
makeExamplePage <- function(name, ui) {
help <- getHelpList(name)
makePage(name,
"Fluent UI component",
div(
makeCard("Description", Text(nowrap = FALSE, help$description)),
makeCard("Usage", pre(help$usage)),
makeCard("Live example", div(style = "padding: 20px", ui)),
makeCard("Live example code", pre(help$example))
))
}
|
plot.pec <- function(x,
what,
models,
xlim=c(x$start,x$minmaxtime),
ylim=c(0,0.3),
xlab="Time",
ylab,
axes=TRUE,
col,
lty,
lwd,
type,
smooth=FALSE,
add.refline=FALSE,
add=FALSE,
legend=ifelse(add,FALSE,TRUE),
special=FALSE,
...){
allArgs <- match.call()
allArgs
if (missing(what)){
if (match("what",names(allArgs),nomatch=0)){
what <- eval(allArgs$what)
}
else{
if (match("PredErr",names(x),nomatch=0))
what <- "PredErr"
else{
what <- switch(x$splitMethod$internal.name,
"noPlan"="AppErr",
paste(x$splitMethod$internal.name,"Err",sep=""))
}
}
}
if (0==(match(what,names(x),nomatch=0)))
stop("Estimate \"",what,"\" not found in object")
if (missing(models))
if (match("who",names(allArgs),nomatch=0))
models <- eval(allArgs$who)
else
models <- 1:length(x$models)
if(!is.numeric(models))
models <- names(x$model)[match(models,names(x$models))]
a <- x$time >= xlim[1]
b <- x$time <= xlim[2]
at <- (a & b)
X <- x$time[at]
y <- do.call("cbind",x[[what]][models])[at,,drop=FALSE]
if (length(y)==0) stop("No plotting values: check if x[[what]][models] is a list of numeric vectors.")
uyps <- unlist(y)
uyps <- uyps[!is.infinite(uyps)]
max.y <- max(uyps,na.rm=T)
ymax <- max(max.y,ylim[2])
if (max.y>ylim[2])
ylim <- if (what=="PredErr")
c(0,ceiling(ymax*10)/10)
else
c(0,ceiling(max(unlist(y),na.rm=T)*10))/10
nfit <- ncol(y)
if (missing(ylab)) ylab <- "Prediction error"
if (missing(xlab)) xlab <- "Time"
if (missing(col)) col <- 1:nfit
if (missing(lty)) lty <- rep(1, nfit)
if (missing(lwd)) lwd <- rep(2, nfit)
if (length(col)< nfit) col <- rep(col, nfit)
if (length(lty) < nfit) lty <- rep(lty, nfit)
if (length(lwd) < nfit) lwd <- rep(lwd, nfit)
if (missing(type))
if (!x$exact || smooth) type <- "l" else type <- "s"
axis1.DefaultArgs <- list()
axis2.DefaultArgs <- list()
plot.DefaultArgs <- list(x=0,
y=0,
type = "n",
ylim = ylim,
xlim = xlim,
xlab = xlab,
ylab = ylab)
special.DefaultArgs <- list(x=x,
y=x[[what]],
addprederr=NULL,
models=models,
bench=FALSE,
benchcol=1,
times=X,
maxboot=NULL,
bootcol="gray77",
col=rep(1,4),
lty=1:4,
lwd=rep(2,4))
if (special)
legend.DefaultArgs <- list(legend=NULL,lwd=NULL,col=NULL,lty=NULL,cex=1.5,bty="n",y.intersp=1,x=xlim[1],xjust=0,y=(ylim+.1*ylim)[2],yjust=1)
else
legend.DefaultArgs <- list(legend=if(is.numeric(models)) names(x$models)[models] else models,
lwd=lwd,
col=col,
lty=lty,
cex=1.5,
bty="n",
y.intersp=1,
x=xlim[1],
xjust=0,
y=(ylim+.1*ylim)[2],
yjust=1)
if (match("legend.args",names(args),nomatch=FALSE)){
legend.DefaultArgs <- c(args[[match("legend.args",names(args),nomatch=FALSE)]],legend.DefaultArgs)
legend.DefaultArgs <- legend.DefaultArgs[!duplicated(names(legend.DefaultArgs))]
}
if (match("special.args",names(args),nomatch=FALSE)){
special.DefaultArgs <- c(args[[match("special.args",names(args),nomatch=FALSE)]],special.DefaultArgs)
special.DefaultArgs <- special.DefaultArgs[!duplicated(names(special.DefaultArgs))]
}
smartA <- prodlim::SmartControl(call=list(...),
keys=c("plot","special","legend","axis1","axis2"),
defaults=list("plot"=plot.DefaultArgs,
"special"=special.DefaultArgs,
"legend"= legend.DefaultArgs,
"axis1"=axis1.DefaultArgs,
"axis2"=axis2.DefaultArgs),
forced=list("plot"=list(axes=FALSE),
"axis1"=list(side=1),
"axis2"=list(side=2)),
ignore.case=TRUE,
ignore=c("what","who"),
verbose=TRUE)
if (!add) {
do.call("plot",smartA$plot)
if (axes){
do.call("axis",smartA$axis1)
do.call("axis",smartA$axis2)
}
}
if (special==TRUE){
if (!(x$splitMethod$internal.name=="Boot632plus"||x$splitMethod$internal.name=="Boot632"))
stop("Plotting method 'special' requires prediction error method 'Boot632plus' or 'Boot632'")
if (is.null(x$call$keep.matrix))
stop("Need keep.matrix")
do.call("Special", smartA$special)
}
else{
nlines <- ncol(y)
nix <- lapply(1:nlines, function(s) {
lines(x = X, y = y[,s], type = type, col = col[s], lty = lty[s], lwd = lwd[s])
})
}
if (add.refline) abline(h=.25,lty=3,lwd=2,col=1)
if(legend==TRUE && !add && !is.null(names(x$models)[models])){
save.xpd <- par()$xpd
par(xpd=TRUE)
if (special==TRUE){
if(is.numeric(models)) nameModels <- names(x$models)[smartA$special$models] else nameModels <- smartA$special$models
if (is.null(smartA$legend$legend))
if (smartA$special$bench == FALSE)
smartA$legend$legend <- c(paste(x$method$internal.name,"-",nameModels), paste(smartA$special$addprederr, "-", nameModels))
else{
if (is.numeric(smartA$special$bench))
benchName <- names(x$models)[smartA$special$bench] else benchName <- smartA$special$bench
if (is.null(smartA$special$addprederr))
smartA$legend$legend <- c(paste(x$splitMethod$internal.name,"-",c(benchName, nameModels)))
else
smartA$legend$legend <- c(paste(x$splitMethod$internal.name,"-",c(benchName, nameModels)), paste(smartA$special$addprederr, "-", nameModels))
}
if (is.null(smartA$legend$col))
if (smartA$special$bench == FALSE)
smartA$legend$col <- smartA$special$col
else
smartA$legend$col <- c(smartA$special$benchcol,smartA$special$col)
if (is.null(smartA$legend$lty))
if (smartA$special$bench == FALSE)
smartA$legend$lty <- smartA$special$lty
else
smartA$legend$lty <- c(1,smartA$special$lty)
if (is.null(smartA$legend$lwd))
if (smartA$special$bench == FALSE)
smartA$legend$lwd <- smartA$special$lwd
else
smartA$legend$lwd <- c(smartA$special$lwd[1],smartA$special$lwd)
do.call("legend",smartA$legend)
}
else
do.call("legend",smartA$legend)
par(xpd=save.xpd)
}
invisible(x)
}
|
EventRenaming <- function(EventVec, Censored_Annot){
CensoredInd <- which(EventVec == Censored_Annot)
EventVec_Renamed <- EventVec
EventVec_Renamed[CensoredInd] <- 0
EventVec_Renamed[-CensoredInd] <- 1
return(EventVec_Renamed)
}
|
itsframe <- function(dates, a, b)
UseMethod("itsframe")
itsframe.default <- function(dates, a, b) {
n <- length(a)
if (length(a) != length(b))
stop('a and b must be of the same length')
if(inherits(dates, "Date")==T){dates = as.Date(dates)} else {dates = dates}
outputs <- list(dates = dates, a = a, b = b, n=n, D=1, call = match.call())
class(outputs) <- "itsframe"
return(outputs)
}
plot.itsframe <- function(x, time.format="%m-%y", col = NULL, lty = NULL, main = NULL, type = NULL, pch = NULL, lwd = NULL,
tick = TRUE, ylab = NULL,xlab = NULL, ylim = NULL, xlim = NULL,cex.lab=NULL, cex.axis=NULL,cex.main=NULL, ...) {
plot(x$dates, x$a,
main = if(is.null(main)){''} else {main},
col = if(is.null(col)){'black'} else {col},
lty = if(is.null(lty)){1} else {lty},
pch = if(is.null(pch)){1} else {pch},
type = if(is.null(type)){'l'} else {type},
xlab = if(is.null(xlab)){'Time'} else {xlab},
lwd = if(is.null(lwd)){1} else {lwd},
ylab = if(is.null(ylab)){''} else {ylab},
ylim = if(is.null(ylim)){c(min(x$a, x$b),max(x$a, x$b))} else {ylim},
xlim = if(is.null(xlim)){c(min(x$dates),max(x$dates))} else {xlim},
cex.lab = if(is.null(cex.lab)){1} else {cex.lab},
cex.axis = if(is.null(cex.axis)){1} else {cex.axis},
cex.main = if(is.null(cex.main)){1} else {cex.main},
xaxt="n")
if(inherits(x$dates, "Date")==T){ timelabels<-format(x$dates,time.format) ;
axis(1,at=x$dates, tick =tick, labels=timelabels,cex.axis = if(is.null(cex.axis)){1} else {cex.axis})} else { axis(1,at=x$dates, tick =tick, cex.axis = if(is.null(cex.axis)){1} else {cex.axis}) }
lines(x$dates, x$b,
col = if(is.null(col)){'black'} else {col},
lty = if(is.null(lty)){1} else {lty},
pch = if(is.null(pch)){1} else {pch},
type = if(is.null(type)){'l'} else {type},
lwd = if(is.null(lwd)){1} else {lwd})
polygon(c(rev(x$dates), x$dates), c(rev(x$a), x$b),
border = NA, col = if(is.null(col)){'lightgray'} else {col})
}
|
SnnsR__resetRSNNS <- function(snnsObject) {
res <- list()
res$err <- 0
while (res$err == 0) {
res <- snnsObject$deletePatSet(0)
};
snnsObject$deleteNet()
}
SnnsR__deserialize <- function(snnsObject, str) {
filename <- tempfile(pattern = "rsnns")
file <- file(filename, "w")
writeLines(str, con=file)
close(file)
snnsObject$loadNet(filename)
unlink(filename)
}
|
cyclocomp_linter <- function(complexity_limit = 25) {
function(source_file) {
if (!is.null(source_file[["file_lines"]])) {
return(NULL)
}
complexity <- try_silently(
cyclocomp::cyclocomp(parse(text = source_file$content))
)
if (inherits(complexity, "try-error")) return(NULL)
if (complexity <= complexity_limit) return(NULL)
Lint(
filename = source_file[["filename"]],
line_number = source_file[["line"]][1],
column_number = source_file[["column"]][1],
type = "style",
message = paste0(
"functions should have cyclomatic complexity of less than ",
complexity_limit, ", this has ", complexity,"."
),
ranges = list(c(source_file[["column"]][1], source_file[["column"]][1])),
line = source_file$lines[1],
linter = "cyclocomp_linter"
)
}
}
|
dbRunScript <- function(conn, script, echo = FALSE, ...) {
if (file.exists(script)) {
message(paste0("Initializing DB using SQL script ", basename(script)))
sql <- readChar(script, file.info(script)$size, useBytes = TRUE)
} else {
sql <- script
}
sql_lines <- unlist(strsplit(sql, "\n"))
sql_lines <- sql_lines[grepl("[A-Za-z0-9);]+", sql_lines)]
sql_lines <- sql_lines[!grepl("^--", sql_lines)]
sql_lines <- sql_lines[!grepl("^/\\*", sql_lines)]
sql_rebuild <- paste(sql_lines, collapse = " ")
sql_cmds <- unlist(strsplit(sql_rebuild, ";"))
good <- DBI::SQL(sql_cmds)
if (echo) {
print(good)
}
lapply(good, DBI::dbExecute, conn = conn, ... = ...)
}
|
context("selenium")
normalizePath <- function(...) base::normalizePath(...)
list.files <- function(...) base::list.files(...)
Sys.info <- function(...) base::Sys.info(...)
Sys.which <- function(...) base::Sys.which(...)
test_that("canCallSelenium", {
with_mock(
`binman::process_yaml` = function(...){},
`binman::list_versions` = mock_binman_list_versions_selenium,
`binman::app_dir` = mock_binman_app_dir,
normalizePath = mock_base_normalizePath,
list.files = mock_base_list.files,
`subprocess::spawn_process` = mock_subprocess_spawn_process,
`subprocess::process_return_code` =
mock_subprocess_process_return_code,
`subprocess::process_read` =
mock_subprocess_process_read_selenium,
`subprocess::process_kill` = mock_subprocess_process_kill,
`wdman:::generic_start_log` = mock_generic_start_log,
`wdman:::infun_read` = function(...){"infun"},
Sys.info = function(...){
structure("Windows", .Names = "sysname")
},
`wdman:::chrome_check` = function(...){
list(platform = "some.plat")
},
`wdman:::chrome_ver` = function(...){
list(path = "some.path")
},
`wdman:::gecko_check` = function(...){
list(platform = "some.plat")
},
`wdman:::gecko_ver` = function(...){
list(path = "some.path")
},
`wdman:::phantom_check` = function(...){
list(platform = "some.plat")
},
`wdman:::phantom_ver` = function(...){
list(path = "some.path")
},
`wdman:::ie_check` = function(...){
list(platform = "some.plat")
},
`wdman:::ie_ver` = function(...){
list(path = "some.path")
},
{
selServ <- selenium(iedrver = "latest")
retCommand <- selenium(iedrver = "latest", retcommand = TRUE)
expect_identical(selServ$output(), "infun")
expect_identical(selServ$error(), "infun")
logOut <- selServ$log()[["stdout"]]
logErr <- selServ$log()[["stderr"]]
expect_identical(logOut, "super duper")
expect_identical(logErr, "no error here")
expect_identical(selServ$stop(), "stopped")
}
)
expect_identical(selServ$process, "hello")
exRet <- "-Dwebdriver.chrome.driver='some.path' " %+%
"-Dwebdriver.gecko.driver='some.path' " %+%
"-Dphantomjs.binary.path='some.path' " %+%
"-Dwebdriver.ie.driver='some.path' " %+%
"-jar 'some.path' -port 4567"
if(identical(.Platform[["OS.type"]], "unix")){
expect_true(grepl(exRet, retCommand))
}else{
expect_true(grepl(gsub("'", "\"", exRet), retCommand))
}
})
test_that("errorIfJavaNotFound", {
with_mock(
Sys.which= function(...){""},
expect_error(selenium(), "PATH to JAVA not found")
)
})
test_that("errorIfVersionNotFound", {
with_mock(
Sys.which= function(...){"im here"},
`binman::process_yaml` = function(...){},
`binman::list_versions` = mock_binman_list_versions_selenium,
expect_error(selenium(version = "nothere"),
"version requested doesnt match versions available")
)
})
test_that("pickUpErrorFromReturnCode", {
with_mock(
`binman::process_yaml` = function(...){},
`binman::list_versions` = mock_binman_list_versions_selenium,
`binman::app_dir` = mock_binman_app_dir,
normalizePath = mock_base_normalizePath,
list.files = mock_base_list.files,
`subprocess::spawn_process` = mock_subprocess_spawn_process,
`subprocess::process_return_code` = function(...){"some error"},
`subprocess::process_read` =
mock_subprocess_process_read_selenium,
`wdman:::generic_start_log` = mock_generic_start_log,
Sys.info = function(...){
structure("Windows", .Names = "sysname")
},
`wdman:::chrome_check` = function(...){
list(platform = "some.plat")
},
`wdman:::chrome_ver` = function(...){
list(path = "some.path")
},
`wdman:::gecko_check` = function(...){
list(platform = "some.plat")
},
`wdman:::gecko_ver` = function(...){
list(path = "some.path")
},
`wdman:::phantom_check` = function(...){
list(platform = "some.plat")
},
`wdman:::phantom_ver` = function(...){
list(path = "some.path")
},
`wdman:::ie_check` = function(...){
list(platform = "some.plat")
},
`wdman:::ie_ver` = function(...){
list(path = "some.path")
},
expect_error(selenium(version = "3.0.1", iedrver = "latest"),
"Selenium server couldn't be started")
)
})
test_that("pickUpErrorFromPortInUse", {
with_mock(
`binman::process_yaml` = function(...){},
`binman::list_versions` = mock_binman_list_versions_selenium,
`binman::app_dir` = mock_binman_app_dir,
normalizePath = mock_base_normalizePath,
list.files = mock_base_list.files,
`subprocess::spawn_process` = mock_subprocess_spawn_process,
`subprocess::process_return_code` =
mock_subprocess_process_return_code,
`subprocess::process_read` =
mock_subprocess_process_read_selenium,
`subprocess::process_kill` = mock_subprocess_process_kill,
`wdman:::generic_start_log` = function(...){
list(stderr = "Address already in use")
},
Sys.info = function(...){
structure("Windows", .Names = "sysname")
},
`wdman:::chrome_check` = function(...){
list(platform = "some.plat")
},
`wdman:::chrome_ver` = function(...){
list(path = "some.path")
},
`wdman:::gecko_check` = function(...){
list(platform = "some.plat")
},
`wdman:::gecko_ver` = function(...){
list(path = "some.path")
},
`wdman:::phantom_check` = function(...){
list(platform = "some.plat")
},
`wdman:::phantom_ver` = function(...){
list(path = "some.path")
},
`wdman:::ie_check` = function(...){
list(platform = "some.plat")
},
`wdman:::ie_ver` = function(...){
list(path = "some.path")
},
expect_error(selenium(), "Selenium server signals port")
)
})
test_that("pickUpWarningOnNoStderr", {
with_mock(
`binman::process_yaml` = function(...){},
`binman::list_versions` = mock_binman_list_versions_selenium,
`binman::app_dir` = mock_binman_app_dir,
normalizePath = mock_base_normalizePath,
list.files = mock_base_list.files,
`subprocess::spawn_process` = mock_subprocess_spawn_process,
`subprocess::process_return_code` =
mock_subprocess_process_return_code,
`subprocess::process_read` =
mock_subprocess_process_read_selenium,
`wdman:::generic_start_log` =
function(...){list(stdout = character(), stderr = character())},
Sys.info = function(...){
structure("Windows", .Names = "sysname")
},
`wdman:::chrome_check` = function(...){
list(platform = "some.plat")
},
`wdman:::chrome_ver` = function(...){
list(path = "some.path")
},
`wdman:::gecko_check` = function(...){
list(platform = "some.plat")
},
`wdman:::gecko_ver` = function(...){
list(path = "some.path")
},
`wdman:::phantom_check` = function(...){
list(platform = "some.plat")
},
`wdman:::phantom_ver` = function(...){
list(path = "some.path")
},
`wdman:::ie_check` = function(...){
list(platform = "some.plat")
},
`wdman:::ie_ver` = function(...){
list(path = "some.path")
},
expect_warning(selenium(), "No output to stderr yet detected")
)
})
|
get_object <-
function(object,
bucket,
headers = list(),
parse_response = FALSE,
as = "raw",
...) {
if (missing(bucket)) {
bucket <- get_bucketname(object)
}
object <- get_objectkey(object)
r <- s3HTTP(verb = "GET",
bucket = bucket,
path = paste0("/", object),
headers = headers,
parse_response = parse_response,
...)
cont <- httr::content(r, as = as)
return(cont)
}
save_object <-
function(object,
bucket,
file = basename(object),
headers = list(),
overwrite = TRUE,
...) {
if (missing(bucket)) {
bucket <- get_bucketname(object)
}
object <- get_objectkey(object)
d <- dirname(file)
if (!file.exists(d)) {
dir.create(d, recursive = TRUE)
}
r <- s3HTTP(verb = "GET",
bucket = bucket,
path = paste0("/", object),
headers = headers,
write_disk = httr::write_disk(path = file, overwrite = overwrite),
...)
return(file)
}
select_object <-
function(
object,
bucket,
request_body,
headers = list(),
parse_response = FALSE,
...
) {
if (missing(bucket)) {
bucket <- get_bucketname(object)
}
object <- get_objectkey(object)
r <- s3HTTP(verb = "POST",
bucket = bucket,
path = paste0("/", object),
headers = headers,
query = list(select = "", "select-type" = "2"),
request_body = request_body,
parse_response = parse_response,
...)
cont <- httr::content(r, as = "raw")
return(cont)
}
get_torrent <- function(object, bucket, ...) {
if (missing(bucket)) {
bucket <- get_bucketname(object)
}
object <- get_objectkey(object)
r <- s3HTTP(verb = "GET",
bucket = bucket,
path = paste0("/", object),
query = list(torrent =""),
...)
return(content(r, "raw"))
}
s3connection <-
function(object,
bucket,
headers = list(),
...) {
if (missing(bucket)) {
bucket <- get_bucketname(object)
}
object <- get_objectkey(object)
r <- s3HTTP(verb = "connection",
bucket = bucket,
path = paste0("/", object),
headers = headers,
...)
return(r)
}
|
print.designMatrices <-
function( X, ... ){
x <- X
BB <- x$flatB
colnames(BB) <- paste("B_", colnames(BB), sep="")
out <- cbind( x$flatA, BB )
NAs <- apply( x$flatA, 1, function(fA) all(is.na(fA)) )
out <- out[!NAs, ]
print(out)
invisible( out )
}
rownames.design <- function(X){
Y <- apply(X, 2, as.numeric )
Y <- sapply(1:ncol(Y), function(vv)
paste( colnames(Y)[vv], add.lead(Y[,vv], ceiling(log( max(as.numeric(Y[,vv])), 10)) ), sep="" )
)
rownames(X) <- apply(Y, 1, paste, collapse="-")
return(X)
}
rownames.design2 <- function(X){
Y <- apply(X, 2, as.numeric )
Y <- sapply(1:ncol(Y), function(vv)
paste( colnames(Y)[vv], add.lead(Y[,vv], 1), sep="" )
)
rownames(X) <- apply(Y, 1, paste, collapse="-")
return(X)
}
.A.matrix <- function( resp, formulaA=~ item + item*step, facets=NULL,
constraint=c("cases", "items"), progress=FALSE,
maxKi=NULL )
{
z0 <- Sys.time()
facets0 <- facets
NF <- length(facets)
facet.list <- as.list( 1:NF )
names(facet.list) <- colnames(facets)
if (NF==0){ facet.list <- NULL }
if (NF>0){
for (ff in 1:NF){
uff <- sort( unique( facets[,ff] ) )
facets[,ff] <- match( facets[,ff], uff )
facet.list[[ff]] <- data.frame(
"facet.label"=paste0( colnames(facets)[ff], uff ),
"facet.index"=paste0( colnames(facets)[ff], seq(1,length(uff) ) ) )
}
}
constraint <- match.arg(constraint)
if ( is.null(maxKi) ){
maxKi <- apply( resp, 2, max, na.rm=TRUE )
}
maxK <- max( maxKi )
nI <- ncol( resp )
i11 <- names(maxKi)[ maxKi==0 ]
if ( length(i11) > 0 ){
stop( cat( "Items with maximum score of 0:", paste(i11, collapse=" " ) ) )
}
tf <- terms( formulaA )
fvars <- as.vector( attr(tf,"variables"), mode="character" )[-1]
otherFacets <- setdiff( fvars, c("item", "step") )
contr.list <- as.list( rep( "contr.sum", length(fvars) ) )
names( contr.list ) <- fvars
nitems <- ncol(resp)
expand.list <- vector(mode="list", length=0)
if( "item" %in% fvars ) expand.list <- c(expand.list, if("item" %in% names(facet.list)) list(as.factor(sort(unique(facets[,"item"])))) else list(factor(1:nI)) )
if( "step" %in% fvars ) expand.list <- c(expand.list, if("step" %in% names(facet.list)) list(as.factor(sort(unique(facets[,"step"])))) else list(factor(1:maxK)) )
if( length( otherFacets )==1) expand.list <- c(expand.list, list(factor(1:max(facets[, otherFacets]))) )
if( length( otherFacets ) > 1 ) expand.list <- c(expand.list, sapply( otherFacets, FUN=function(ff) as.factor(1:max(facets[, ff])), simplify=FALSE ))
names( expand.list ) <- fvars
for (vv in seq(1, length(expand.list) ) ){
expand.list[[vv]] <- paste( expand.list[[vv]] )
}
X <- rownames.design2( expand.grid(expand.list) )
if( constraint=="cases" ) formulaA <- update.formula(formulaA, ~0+.)
NX <- ncol(X)
for (ff in 1:NX){
uff <- length( unique(X[,ff] ) )
if (uff==1){ cat(paste0(" - facet ",
colnames(X)[ff], " does only have one level!" ), "\n") }
}
mm <- - stats::model.matrix(formulaA, X, contrasts=contr.list)
if( constraint=="items" ) mm <- mm[,-1]
xsi.constr <- .generate.interactions(X, facets, formulaA, mm )
if( "step" %in% fvars ){
if( ncol( attr(tf, "factors") )==1 ){
return( warning("Can't proceed the estimation:
Factor of order 1 other than step must be specified.") )
}
if( all( attr(tf, "factors")["step",] !=1 ) ){
return( warning("Can't proceed the estimation:
Lower-order term is missing.") )
}
A <- NULL
stepgroups <- unique( gsub( "(^|-)+step([[:digit:]])*", "\\1step([[:digit:]])*", rownames(X) ) )
X.out <- data.frame(as.matrix(X), stringsAsFactors=FALSE)
if (progress){
cat(" o Create design matrix A\n")
ip <- length(stepgroups)
VP <- min( ip, 10 )
cat(paste0(" |",paste0( rep("*", VP), collapse=""), "|\n"))
cat(" |") ; flush.console()
if (VP<10){ disp_progress <- 1:ip } else {
disp_progress <- 100* ( 1:ip ) / (ip+1)
disp_progress <- sapply( seq(5,95,10), FUN=function(pp){
which.min( abs( disp_progress - pp ) )[1] }
)
}
}
ii <- 0 ; vv <- 1
NRX <- length( rownames(X) )
rownames_X_matr <- strsplit( rownames(X), split="-")
rownames_X_matr <- matrix( unlist( rownames_X_matr ), nrow=NRX, byrow=TRUE )
step_col <- 0
for (ff in 1:( ncol( rownames_X_matr ) ) ){
if ( length( grep( "step1", rownames_X_matr[,ff] ) ) > 0 ){
step_col <- ff
}
}
rownames_X_matr2 <- rownames_X_matr[, - step_col, drop=FALSE ]
N2 <- ncol( rownames_X_matr2 )
rownames_X_matr2_collapse <- rownames_X_matr2[,1]
if (N2>1){
for (nn in 2:N2){
rownames_X_matr2_collapse <- paste0( rownames_X_matr2_collapse, "-",
rownames_X_matr2[,nn] )
}
}
stepgroups2 <- unique(rownames_X_matr2_collapse)
match_stepgroups <- match( rownames_X_matr2_collapse, stepgroups2 )
index_matr <- cbind( match_stepgroups, 1:NRX)
index_matr <- index_matr[ order( index_matr[, 1] ), ]
SG <- length(stepgroups2)
res <- tam_rcpp_mml_mfr_a_matrix_cumsum( index_matr=as.matrix(index_matr)-1,
mm=as.matrix(mm), SG=SG )
mm.sg.temp <- res$cumsum_mm
rownames(mm.sg.temp) <- paste0("I", seq(1,nrow(mm.sg.temp) ) )
ind2 <- seq( 1, NRX+SG, maxK+1 )
rownames(mm.sg.temp)[ind2] <- gsub("step([[:digit:]])*", "step0", stepgroups, fixed=T)
rownames(mm.sg.temp)[setdiff( seq(1,NRX+SG), ind2) ] <- rownames(mm)[ index_matr[,2] ]
colnames(mm.sg.temp) <- colnames(mm)
A1 <- rbind(A, mm.sg.temp)
index_matr2 <- index_matr
index_matr2 <- index_matr2[ index_matr2[,1] !=c(0, index_matr2[ -NRX, 1] ), ]
x.sg.temp <- X.out[ index_matr2[,2], ]
x.sg.temp[,"step"] <- 0
rownames(x.sg.temp) <- gsub("step([[:digit:]])*", "step0", stepgroups, fixed=T)
X.out1 <- rbind( X.out, x.sg.temp )
if (TRUE){
X.out <- X.out1
A <- A1
}
if (FALSE){
for( sg in stepgroups ){
ind.mm <- grep(sg, rownames(mm))
mm.sg.temp <- rbind( 0, apply( mm[ ind.mm,], 2, cumsum ) )
rownames(mm.sg.temp)[1] <- gsub("step([[:digit:]])*", "step0", sg, fixed=T)
A <- rbind(A, mm.sg.temp)
isg <- grep(sg, rownames(X.out))[1]
x.sg.temp <- X.out[ isg, ]
x.sg.temp[,"step"] <- 0
rownames(x.sg.temp) <- gsub("step([[:digit:]])*", "step0", sg, fixed=TRUE)
X.out <- rbind(X.out, x.sg.temp)
if ( progress ){
ii <- ii+1
if (( ii==disp_progress[vv] ) & (vv<=10) ){
cat("-") ; flush.console()
vv <- vv+1
}
}
}
}
if ( progress ){
cat("|\n") ; flush.console()
}
} else {
rownames(mm) <- paste( rownames(X), "-step1", sep="")
A <- mm
for( kk in setdiff(0:maxK, 1) ){
mm.k.temp <- mm*kk
rownames(mm.k.temp) <- paste( rownames(X), "-step", kk, sep="")
A <- rbind(A, mm.k.temp)
}
X.out <- expand.grid( c( expand.list, list("step"=factor(0:maxK)) ) )
X.out <- rownames.design2( data.frame(as.matrix(X.out), stringsAsFactors=FALSE) )
}
facet.design <- list( "facets"=facets, "facets.orig"=facets0,
"facet.list"=facet.list[otherFacets])
A <- A[ ! duplicated( rownames(A) ), ]
A <- A[order(rownames(A)),,drop=FALSE]
X.out <- X.out[order(rownames(X.out)),,drop=FALSE]
xsi1 <- xsi.constr$xsi.constraints
xsi.constr$intercept_included <- FALSE
ind <- grep("(Intercept", rownames(xsi1), fixed=TRUE)
if ( length(ind) > 0 ){
xsi1 <- xsi1[ - ind, ]
xsi.constr$xsi.constraints <- xsi1
xsi.constr$intercept_included <- TRUE
}
xsi1 <- xsi.constr$xsi.table
ind <- grep("(Intercept", paste(xsi1$parameter), fixed=TRUE)
if ( length(ind) > 0 ){
xsi1 <- xsi1[ - ind, ]
xsi.constr$xsi.table <- xsi1
}
return(list( "A"=A, "X"=X.out, "otherFacets"=otherFacets, "xsi.constr"=xsi.constr,
"facet.design"=facet.design ) )
}
.A.PCM2 <- function( resp, Kitem=NULL, constraint="cases", Q=NULL ){
if ( is.null(Kitem) ){
Kitem <- apply( resp, 2, max, na.rm=T ) + 1
}
maxK <- max(Kitem)
I <- ncol(resp)
Nxsi <- sum(Kitem) - I
A <- array( 0, dim=c( I, maxK, Nxsi ) )
vv <- 1
for (ii in 1:I){
A[ ii, 2:Kitem[ii], vv ] <- - ( 2:Kitem[ii] - 1 )
if ( Kitem[ii] < maxK ){
A[ ii, ( Kitem[ii] + 1 ):maxK, ] <- NA
}
vv <- vv+1
}
for (ii in 1:I){
if ( Kitem[ii] > 2 ){
for (kk in 2:(Kitem[ii] - 1) ){
A[ ii, kk:(Kitem[ii]-1), vv ] <- - 1
vv <- vv + 1
}
}
}
dimnames(A)[[1]] <- colnames(resp)
vars <- colnames(resp)
unidim <- TRUE
if ( ! is.null(Q) ){
unidim <- ncol(Q)==1
}
if ( constraint=="items" ){
if ( unidim ){
I <- ncol(resp)
x1 <- matrix( - A[I,,I], nrow=dim(A)[2], ncol=I-1, byrow=FALSE )
A[ I,, seq(1,I-1) ] <- x1
A <- A[,,-I]
vars <- vars[ - I ]
}
if (!unidim){
rem.pars <- NULL
D <- ncol(Q)
for (dd in 1:D){
ind.dd <- which( Q[,dd] !=0 )
I <- ind.dd[ length(ind.dd) ]
x1 <- matrix( - A[I,,I], nrow=dim(A)[2], ncol=length(ind.dd)-1, byrow=FALSE )
A[ I,, ind.dd[ - length(ind.dd) ] ] <- x1
rem.pars <- c(rem.pars, I )
}
vars <- vars[ - rem.pars ]
A <- A[,, - rem.pars ]
}
}
vars <- c(vars, unlist( sapply( (1:I)[Kitem>2], FUN=function(ii){
paste0( colnames(resp)[ii], "_step", 1:(Kitem[ii] - 2) ) } ) ) )
dimnames(A)[[3]] <- vars
return(A)
}
.A.PCM3 <- function( resp, Kitem=NULL ){
if ( is.null(Kitem) ){
Kitem <- apply( resp, 2, max, na.rm=T ) + 1
}
maxK <- max(Kitem)
I <- ncol(resp)
Nxsi <- I + sum( Kitem > 2 )
A <- array( 0, dim=c( I, maxK, Nxsi ) )
vv <- 1
for (ii in 1:I){
A[ ii, 2:Kitem[ii], vv ] <- - ( 2:Kitem[ii] - 1 )
if ( Kitem[ii] < maxK ){
A[ ii, ( Kitem[ii] + 1 ):maxK, ] <- NA
}
vv <- vv+1
}
for (ii in 1:I){
if ( Kitem[ii] > 2 ){
Kii <- Kitem[ii]-1
A[ ii, 1:(Kii+1), vv ] <- ( 0:Kii ) * ( Kii - ( 0:Kii) )
vv <- vv + 1
}
}
dimnames(A)[[1]] <- colnames(resp)
vars <- colnames(resp)
vars1 <- paste0( vars[ Kitem > 2 ], "_disp" )
vars <- c( vars, vars1 )
dimnames(A)[[3]] <- vars
return(A)
}
|
buildFreqdist<-
function(freq.distr, freq.param){
freqdist = list()
freqdist[[1]] = freq.distr
freqdist[[2]] = freq.param
class(freqdist)="freqdist"
return(freqdist)
}
|
expected <- eval(parse(text="structure(list(size = NA_real_, isdir = NA, mode = structure(NA_integer_, class = \"octmode\"), mtime = NA_real_, ctime = NA_real_, atime = NA_real_, uid = NA_integer_, gid = NA_integer_, uname = NA_character_, grname = NA_character_), .Names = c(\"size\", \"isdir\", \"mode\", \"mtime\", \"ctime\", \"atime\", \"uid\", \"gid\", \"uname\", \"grname\"))"));
test(id=0, code={
argv <- eval(parse(text="list(\"/home/lzhao/hg/r-instrumented/library/codetools/data\")"));
.Internal(file.info(argv[[1]]));
}, o=expected);
|
gbm_call <- function(gbm_data_obj, gbm_dist_obj, train_params, var_container, par_details, is_verbose) {
check_if_gbm_data(gbm_data_obj)
check_if_gbm_dist(gbm_dist_obj)
check_if_gbm_train_params(train_params)
check_if_gbm_var_container(var_container)
y_levels <- nlevels(gbm_data_obj$y)
if(y_levels > 0) {
y_input <- as.integer(gbm_data_obj$y)
} else {
y_input <- gbm_data_obj$y
}
if(!is.null(dim(gbm_data_obj$y))) {
y_levels <- nlevels(gbm_data_obj$y[,1])
if(y_levels > 0)
y_input <- as.integer(gbm_data_obj$y[,1])
}
fit <- .Call("gbm",
Y=as.matrix(as.data.frame(y_input)),
intResponse = as.matrix(cbind(gbm_dist_obj$strata, gbm_dist_obj$sorted)),
Offset=as.double(gbm_data_obj$offset),
X=as.matrix(as.data.frame(gbm_data_obj$x)),
X.order=as.integer(gbm_data_obj$x_order),
weights=as.double(gbm_data_obj$weights),
Misc=get_misc(gbm_dist_obj),
prior.node.coeff.var = ifelse(is.null(gbm_dist_obj$prior_node_coeff_var), as.double(0),
as.double(gbm_dist_obj$prior_node_coeff_var)),
id = as.integer(train_params$id),
var.type=as.integer(var_container$var_type),
var.monotone=as.integer(var_container$var_monotone),
distribution=gbm_call_dist_name(gbm_dist_obj),
n.trees=as.integer(train_params$num_trees),
interaction.depth=as.integer(train_params$interaction_depth),
n.minobsinnode=as.integer(train_params$min_num_obs_in_node),
shrinkage=as.double(train_params$shrinkage),
bag.fraction=as.double(train_params$bag_fraction),
nTrainRows=as.integer(train_params$num_train_rows),
nTrainObs = as.integer(train_params$num_train),
mFeatures=as.integer(train_params$num_features),
fit.old=as.double(NA),
n.cat.splits.old=as.integer(0),
n.trees.old=as.integer(0),
par_details,
verbose=as.integer(is_verbose),
PACKAGE = "gbm3")
fit$distribution <- gbm_dist_obj
fit$params <- train_params
fit$variables <- var_container
class(fit) <- "GBMFit"
return(fit)
}
gbm_call_dist_name <- function(obj) {
UseMethod("gbm_call_dist_name")
}
gbm_call_dist_name.default <- function(obj) {
tolower(distribution_name(obj))
}
gbm_call_dist_name.PairwiseGBMDist <- function(obj) {
paste(tolower(distribution_name(obj)), tolower(obj$metric), sep="_")
}
|
library(ggplot2)
this_base <- "fig03-01_angle-judgments"
my_data <- data.frame(
variable = c("A", "B","C","D","E"),
value = c(25, 55, 55, 90, 135) / 360)
p <- ggplot(my_data, aes(x = factor(1), y = value)) +
geom_bar(width = 1, colour = "black", fill = "white", stat = "identity") +
coord_polar(theta = "y", start = (1/2)*pi) +
ggtitle("Fig 3.1 Angle Judgments") +
theme_bw() +
theme(panel.grid.major = element_blank(),
plot.title = element_text(size = rel(1.5), face = "bold"),
panel.border = element_blank(),
axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank())
p
ggsave(paste0(this_base, ".png"),
p, width = 6, height = 5)
|
Qstat.sb.opt = function(DATA, vecA, Psize, Bsize, sigLev)
{
Tsize = nrow(DATA)
vecQ.BP = matrix(0,Psize,1)
vecQ.LB = matrix(0,Psize,1)
vecCRQ = crossq.max(DATA, vecA, Psize)
for (k in 1:Psize){
RES = Qstat(vecCRQ[1:k], Tsize)
vecQ.BP[k] = RES$Q.BP
vecQ.LB[k] = RES$Q.LB
}
Nsize = Tsize - Psize
matD = matrix(0,Nsize,Psize+1)
bigA = matrix(0,(Psize+1), 1)
matD[,1] = as.matrix(DATA[(Psize+1):Tsize,1,drop=F])
bigA[,1] = vecA[1]
for (k in 1:Psize){
matD[,(k+1)] = as.matrix(DATA[(Psize-k+1):(Tsize-k),2, drop=F])
bigA[ (k+1)] = vecA[2]
}
matB = b.star(matD)
gamma = mean( (1/matB[,1, drop=FALSE]) )
matQ.BP = matrix(0,Bsize,Psize)
matQ.LB = matrix(0,Bsize,Psize)
for (b in 1:Bsize){
vecI = sb.index(Nsize, gamma)
matD.SB = matD[vecI,]
vecCRQ.B = matrix(0,Psize, 1)
matQhit.SB = q.hit(matD.SB, bigA)
vecD1 = matD.SB[,1, drop=FALSE]
for (k in 1:Psize){
matH.SB = cbind(matQhit.SB[,1], matQhit.SB[,(1+k)])
matHH.SB = t(matH.SB) %*% matH.SB
vecCRQ.B[k] = matHH.SB[1,2] / sqrt( matHH.SB[1,1] * matHH.SB[2,2] )
}
vecTest = vecCRQ.B - vecCRQ
for (k in 1:Psize){
Res1 = Qstat(vecTest[1:k], Tsize)
matQ.BP[b,k] = Res1$Q.BP
matQ.LB[b,k] = Res1$Q.LB
}
}
vecCV.BP = matrix(0, Psize, 1)
vecCV.LB = matrix(0, Psize, 1)
for (k in 1:Psize){
vecCV.BP[k] = quantile(matQ.BP[,k], probs = (1 - sigLev) )
vecCV.LB[k] = quantile(matQ.LB[,k], probs = (1 - sigLev) )
}
list(vecQ.BP = vecQ.BP, vecCV.BP=vecCV.BP, vecQ.LB=vecQ.LB, vecCV.LB=vecCV.LB)
}
|
library(systemicrisk)
l <- c(714,745,246, 51,847)
a <- c(872, 412, 65, 46,1208)
mod <- Model.additivelink.exponential.fitness(n=5,alpha=-2.5,beta=0.3,gamma=1.0,
lambdaprior=Model.fitness.genlambdaparprior(ratescale=500))
thin <- choosethin(l=l,a=a,model=mod,silent=TRUE)
thin
res <- sample_HierarchicalModel(l=l,a=a,model=mod,nsamples=1e3,thin=thin,silent=TRUE)
res$L[[1]]
res$L[[2]]
plot(ecdf(sapply(res$L,function(x)x[1,2])))
diagnose(res)
plot(sapply(res$L,function(x)x[1,2]),type="b")
plot(res$theta[1,],type="b")
acf(sapply(res$L,function(x)x[1,2]))
|
xxyy.to.array <- function (M, p, k = 2) {
if (!is.matrix(M) && !is.data.frame(M))
stop("M must be a data frame or matrix")
if (k < 2)
stop("One-dimensional data cannot be used")
if (ncol(M) != p * k)
stop("Matrix dimensions do not match input")
n <- nrow(M)
A <- array(NA, dim = c(p, k, n))
for (i in 1:k) {
A[, i, ] <- t(M[, p*(i-1) + 1:p])
}
dimnames(A)[[3]] <- dimnames(M)[[1]]
return(A)
}
|
library(testthat)
library(visR)
library(vdiffr)
library(survival)
test_check("visR")
|
"incr_matrix1"
|
context("read_sistec")
test_that("read_sistec works", {
skip_on_cran()
sistec <- read_sistec(system.file("extdata/examples/sistec",
package = "sistec"))
check_sistec_table(sistec, expect_nrow = 200)
expect_true(inherits(sistec, "sistec_data_frame"))
})
test_that("encoding and sep work", {
skip_on_cran()
sistec <- read_sistec(system.file("extdata/test_datasets/sistec_encoding/latin1",
package = "sistec"))
expect_true(any(stringr::str_detect(sistec$S_NO_CURSO,
"\xc9|\xc7|\xd5|\xca|\xda|\xc2|\xc1|\xcd")))
sistec <- read_sistec(system.file("extdata/test_datasets/sistec_encoding/utf8",
package = "sistec"))
expect_true(any(stringi::stri_enc_isutf8(sistec$S_NO_CURSO)))
})
|
CADFtest.default <- function(model, X=NULL, type=c("trend", "drift", "none"),
data=list(), max.lag.y=1, min.lag.X=0, max.lag.X=0, dname=NULL,
criterion=c("none", "BIC", "AIC", "HQC", "MAIC"), ...)
{
if (is.null(dname)){dname <- deparse(substitute(model))}
method <- "CADF test"
y <- model
if (is.null(X)) method <- "ADF test"
type <- match.arg(type)
switch(type,
"trend" = urtype <- "ct",
"drift" = urtype <- "c",
"none" = urtype <- "nc")
criterion <- match.arg(criterion)
rho2 <- NULL
nX <- 0
if (is.ts(y)==FALSE) y <- ts(y)
trnd <- ts(1:length(y), start=start(y), frequency=frequency(y))
if (criterion=="none")
{
test.results <- estmodel(y=y, X=X, trnd=trnd, type=type,
max.lag.y=max.lag.y, min.lag.X=min.lag.X, max.lag.X=max.lag.X,
dname=dname, criterion=criterion, obs.1=NULL, obs.T=NULL, ...)
}
if (criterion!="none")
{
all.models <- expand.grid(max.lag.y:0, min.lag.X:0, max.lag.X:0)
models.num <- dim(all.models)[1]
ICmatrix <- matrix(NA, models.num, 7)
max.lag.y <- all.models[1, 1]
min.lag.X <- all.models[1, 2]
max.lag.X <- all.models[1, 3]
interm.res <- estmodel(y=y, X=X, trnd=trnd, type=type,
max.lag.y=max.lag.y, min.lag.X=min.lag.X, max.lag.X=max.lag.X,
dname=dname, criterion=criterion, obs.1=NULL, obs.T=NULL, ...)
ICmatrix[1, ] <- c(max.lag.y, min.lag.X, max.lag.X, interm.res$AIC, interm.res$BIC, interm.res$HQC, interm.res$MAIC)
t.1 <- interm.res$est.model$index[1]
t.T <- interm.res$est.model$index[length(interm.res$est.model$index)]
for (modeln in 2:models.num)
{
max.lag.y <- all.models[modeln, 1]
min.lag.X <- all.models[modeln, 2]
max.lag.X <- all.models[modeln, 3]
interm.res <- estmodel(y=y, X=X, trnd=trnd, type=type,
max.lag.y=max.lag.y, min.lag.X=min.lag.X, max.lag.X=max.lag.X,
dname=dname, criterion=criterion, obs.1=t.1, obs.T=t.T, ...)
ICmatrix[modeln, ] <- c(max.lag.y, min.lag.X, max.lag.X, interm.res$AIC, interm.res$BIC,
interm.res$HQC, interm.res$MAIC)
}
if (criterion=="AIC") selected.model <- which(ICmatrix[,4]==min(ICmatrix[,4]))
if (criterion=="BIC") selected.model <- which(ICmatrix[,5]==min(ICmatrix[,5]))
if (criterion=="HQC") selected.model <- which(ICmatrix[,6]==min(ICmatrix[,6]))
if (criterion=="MAIC") selected.model <- which(ICmatrix[,7]==min(ICmatrix[,7]))
if (length(selected.model) > 1) selected.model <- selected.model[length(selected.model)]
max.lag.y <- ICmatrix[selected.model, 1]
min.lag.X <- ICmatrix[selected.model, 2]
max.lag.X <- ICmatrix[selected.model, 3]
test.results <- estmodel(y=y, X=X, trnd=trnd, type=type,
max.lag.y=max.lag.y, min.lag.X=min.lag.X, max.lag.X=max.lag.X,
dname=dname, criterion=criterion, obs.1=t.1, obs.T=t.T, ...)
}
class(test.results) <- c("CADFtest", "htest")
if (is.null(X)){names(test.results$statistic) <- paste("ADF(",max.lag.y,")",sep="")}
else{names(test.results$statistic) <- paste("CADF(",max.lag.y,",",max.lag.X,",",min.lag.X,")",sep="")}
test.results$estimate <- c("delta" = as.vector(test.results$est.model$coefficients[(2 - as.numeric(type=="none") +
as.numeric(type=="trend"))]))
test.results$null.value <- c("delta" = 0)
test.results$alternative <- "less"
test.results$type <- type
return(test.results)
}
estmodel <- function(y, X, trnd, type, max.lag.y, min.lag.X, max.lag.X, dname, criterion, obs.1, obs.T, ...)
{
method <- "CADF test"
if (is.null(X)) method <- "ADF test"
rho2 <- NULL
model <- "d(y) ~ "
if (type=="trend") model <- paste(model, "trnd +", sep="")
model <- paste(model, " L(y, 1)", sep="")
if (max.lag.y > 0)
{
for (i in 1:max.lag.y) model <- paste(model, " + L(d(y), ",i,")", sep="")
}
if (is.null(X)==FALSE)
{
if (is.ts(X)==FALSE) X <- ts(X, start=start(y), frequency=frequency(y))
nX <- 1; if (is.null(dim(X))==FALSE) nX <- dim(X)[2]
nX <- (max.lag.X - min.lag.X + 1)*nX
if ((min.lag.X==0) & (max.lag.X==0)) model <- paste(model, " + L(X, 0)", sep="")
if ((min.lag.X!=0) | (max.lag.X!=0))
{
for (i in min.lag.X:max.lag.X) model <- paste(model, " + L(X, ",i,")", sep="")
}
}
if (type=="none") model <- paste(model, " -1", sep="")
est.model <- dynlm(formula=formula(model), start=obs.1, end=obs.T)
summ.est.model <- summary(est.model)
q <- summ.est.model$df[1]
TT <- q + summ.est.model$df[2]
sig2 <- sum(est.model$residuals^2)/TT
lsig2 <- log(sig2)
model.AIC <- lsig2 + 2*q/TT
model.BIC <- lsig2 + q*log(TT)/TT
model.HQC <- lsig2 + 2*q*log(log(TT))/TT
ytm1 <- est.model$model[, (2 + as.numeric(type=="trend"))]
if (type=="drift") ytm1 <- ytm1 - mean(ytm1)
if (type=="trend")
{
dtrmod <- lsfit((1:TT), ytm1)
ytm1 <- dtrmod$residuals
}
b0 <- est.model$coefficient[1 + as.numeric(type=="drift") + as.numeric(type=="trend")*2]
sy2 <- sum(ytm1^2)
tau <- b0^2 * sy2 / sig2
model.MAIC <- lsig2 + 2*(tau + q)/TT
t.value <- summ.est.model$coefficients[(2 - as.numeric(type=="none") + as.numeric(type=="trend")),3]
if (is.null(X))
{
switch(type,
"trend" = urtype <- "ct",
"drift" = urtype <- "c",
"none" = urtype <- "nc")
p.value <- punitroot(t.value, N=TT, trend=urtype, statistic = "t")
}
if (is.null(X)==FALSE)
{
k <- length(est.model$coefficients)
series <- as.matrix(est.model$model)
nseries <- dim(series)[2]
Xseries <- series[,(nseries-nX+1):nseries]
if (nX==1) Xseries <- Xseries - mean(Xseries)
if (nX>1) Xseries <- Xseries - apply(Xseries,2,mean)
e <- as.matrix(est.model$residuals)
if (nX==1) v <- Xseries * est.model$coefficients[k] + e
if (nX>1) v <- Xseries%*%est.model$coefficients[(k-nX+1):k] + e
V <- cbind(e,v)
mod <- lm(V~1)
LRCM <- (kernHAC(mod, ...))*nrow(V)
rho2 <- LRCM[1,2]^2/(LRCM[1,1]*LRCM[2,2])
p.value <- CADFpvalues(t.value, rho2, type)
}
return(list(statistic=t.value,
parameter=c("rho2" = rho2),
method=method,
p.value=as.vector(p.value),
data.name=dname,
max.lag.y=max.lag.y,
min.lag.X=min.lag.X,
max.lag.X=max.lag.X,
AIC=model.AIC,
BIC=model.BIC,
HQC=model.HQC,
MAIC=model.MAIC,
est.model=est.model,
call=match.call(CADFtest)))
}
|
bayesx_prgfile <- function(x, model = 1L)
{
x <- get.model(x, model)
bayesx.prg <- NULL
if(inherits(x, "bayesx")) {
bayesx.prg <- x[[model]]$bayesx.prg$prg
if(!is.null(bayesx.prg))
cat(bayesx.prg)
}
if(is.null(bayesx.prg))
warning("program file is not available!")
return(invisible(bayesx.prg))
}
|
Jeffreys_CI_1x2 <- function(X, n, alpha=0.05, printresults=TRUE) {
estimate <- X / n
L <- qbeta(alpha / 2, X + 0.5, n - X + 0.5)
U <- qbeta(1 - alpha / 2, X + 0.5, n - X + 0.5)
if (printresults) {
print(
sprintf(
'The Jeffreys CI: estimate = %6.4f (%g%% CI %6.4f to %6.4f)',
estimate, 100 * (1 - alpha), L, U
)
)
}
res <- c(L, U, estimate)
names(res) <- c("lower", "upper", "estimate")
invisible(res)
}
|
.Tcl <- function(...)
structure(.External(.C_dotTcl, ...), class = "tclObj")
.Tcl.objv <- function(objv)
structure(.External(.C_dotTclObjv, objv), class = "tclObj")
.Tcl.callback <- function(...)
.External(.C_dotTclcallback, ...)
.Tcl.args <- function(...) {
pframe <- parent.frame(3)
name2opt <- function(x) if ( x != "") paste0("-", x) else ""
isCallback <- function(x)
is.function(x) || is.call(x) || is.expression(x)
makeAtomicCallback <- function(x, e) {
if (is.name(x))
x <- eval(x, e)
if (is.call(x)){
if(identical(x[[1L]], as.name("break")))
return("break")
if(identical(x[[1L]], as.name("function")))
x <- eval(x, e)
}
.Tcl.callback(x, e)
}
makeCallback <- function(x, e) {
if (is.expression(x))
paste(lapply(x, makeAtomicCallback, e), collapse = ";")
else
makeAtomicCallback(x, e)
}
val2string <- function(x) {
if (is.null(x)) return("")
if (is.tkwin(x)){ current.win <<- x ; return (.Tk.ID(x)) }
if (inherits(x,"tclVar")) return(names(unclass(x)$env))
if (isCallback(x)){
ref <- local({value <- x; envir <- pframe; environment()})
callback <- makeCallback(get("value", envir = ref),
get("envir", envir = ref))
callback <- paste("{", callback, "}")
assign(callback, ref, envir = current.win$env)
return(callback)
}
x <- gsub("\\\\", "\\\\\\\\", as.character(x))
x <- gsub("\"","\\\\\"", as.character(x))
x <- gsub("\\[","\\\\[", as.character(x))
x <- gsub("\\$","\\\\$", as.character(x))
paste0("\"", x, "\"", collapse = " ")
}
val <- list(...)
nm <- names(val)
if (!length(val)) return("")
nm <- if (is.null(nm)) rep("", length(val)) else sapply(nm, name2opt)
current.win <-
if (exists("win", envir = parent.frame()))
get("win", envir = parent.frame())
else .TkRoot
val <- sapply(val, val2string)
paste(as.vector(rbind(nm, val)), collapse = " ")
}
.Tcl.args.objv <- function(...) {
pframe <- parent.frame(3)
isCallback <- function(x)
is.function(x) || is.call(x) || is.expression(x)
makeAtomicCallback <- function(x, e) {
if (is.name(x))
x <- eval(x, e)
if (is.call(x)){
if(identical(x[[1L]], as.name("break")))
return("break")
if(identical(x[[1L]], as.name("function")))
x <- eval(x, e)
}
.Tcl.callback(x, e)
}
makeCallback <- function(x, e) {
if (is.expression(x))
paste(lapply(x, makeAtomicCallback, e), collapse = ";")
else
makeAtomicCallback(x, e)
}
val2obj <- function(x) {
if (is.null(x)) return(NULL)
if (is.tkwin(x)){current.win <<- x ; return(as.tclObj(.Tk.ID(x)))}
if (inherits(x,"tclVar")) return(as.tclObj(names(unclass(x)$env)))
if (isCallback(x)){
ref <- local({value <- x; envir <- pframe; environment()})
callback <- makeCallback(get("value", envir = ref),
get("envir", envir = ref))
assign(callback, ref, envir = current.win$env)
return(as.tclObj(callback, drop = TRUE))
}
as.tclObj(x, drop = TRUE)
}
val <- list(...)
current.win <- .TkRoot
lapply(val, val2obj)
}
.Tk.ID <- function(win) win$ID
.Tk.newwin <- function(ID) {
win <- list(ID = ID, env = new.env(parent = emptyenv()))
win$env$num.subwin <- 0
class(win) <- "tkwin"
win
}
.Tk.subwin <- function(parent) {
ID <- paste(parent$ID, parent$env$num.subwin <- parent$env$num.subwin + 1,
sep = ".")
win <- .Tk.newwin(ID)
assign(ID, win, envir = parent$env)
assign("parent", parent, envir = win$env)
win
}
tkdestroy <- function(win) {
tcl("destroy", win)
ID <- .Tk.ID(win)
env <- get("parent", envir = win$env)$env
if (exists(ID, envir = env, inherits = FALSE))
rm(list = ID, envir = env)
}
is.tkwin <- function(x) inherits(x, "tkwin")
tclVar <- function(init = "") {
n <- .TkRoot$env$TclVarCount <- .TkRoot$env$TclVarCount + 1L
name <- paste0("::RTcl", n)
l <- list(env = new.env())
assign(name, NULL, envir = l$env)
reg.finalizer(l$env, function(env) tcl("unset", names(env)))
class(l) <- "tclVar"
tclvalue(l) <- init
l
}
tclObj <- function(x) UseMethod("tclObj")
"tclObj<-" <- function(x, value) UseMethod("tclObj<-")
tclObj.tclVar <- function(x){
z <- .External(.C_RTcl_ObjFromVar, names(x$env))
class(z) <- "tclObj"
z
}
"tclObj<-.tclVar" <- function(x, value){
value <- as.tclObj(value)
.External(.C_RTcl_AssignObjToVar, names(x$env), value)
x
}
tclvalue <- function(x) UseMethod("tclvalue")
"tclvalue<-" <- function(x, value) UseMethod("tclvalue<-")
tclvalue.tclVar <- function(x) tclvalue(tclObj(x))
tclvalue.tclObj <- function(x) .External(.C_RTcl_StringFromObj, x)
print.tclObj <- function(x,...) {
z <- tclvalue(x)
if (length(z)) cat("<Tcl>", z, "\n")
invisible(x)
}
"tclvalue<-.tclVar" <- function(x, value) {
name <- names(unclass(x)$env)
tcl("set", name, value)
x
}
tclvalue.default <- function(x) tclvalue(tcl("set", as.character(x)))
"tclvalue<-.default" <- function(x, value) {
name <- as.character(x)
tcl("set", name, value)
x
}
as.character.tclVar <- function(x, ...) names(unclass(x)$env)
as.character.tclObj <- function(x, ...)
.External(.C_RTcl_ObjAsCharVector, x)
as.double.tclObj <- function(x, ...)
.External(.C_RTcl_ObjAsDoubleVector, x)
as.integer.tclObj <- function(x, ...)
.External(.C_RTcl_ObjAsIntVector, x)
as.logical.tclObj <- function(x, ...)
as.logical(.External(.C_RTcl_ObjAsIntVector, x))
as.raw.tclObj <- function(x, ...)
.External(.C_RTcl_ObjAsRawVector, x)
is.tclObj <- function(x) inherits(x, "tclObj")
as.tclObj <- function(x, drop = FALSE) {
if (is.tclObj(x)) return(x)
z <- switch(storage.mode(x),
character = .External(.C_RTcl_ObjFromCharVector, x, drop),
double = .External(.C_RTcl_ObjFromDoubleVector, x,drop),
integer = .External(.C_RTcl_ObjFromIntVector, x, drop),
logical = .External(.C_RTcl_ObjFromIntVector, as.integer(x), drop),
raw = .External(.C_RTcl_ObjFromRawVector, x),
stop(gettextf("cannot handle object of mode '%s'",
storage.mode(x)), domain = NA)
)
class(z) <- "tclObj"
z
}
tclServiceMode <- function(on = NULL)
.External(.C_RTcl_ServiceMode, as.logical(on))
.TkRoot <- .Tk.newwin("")
tclvar <- structure(NULL, class = "tclvar")
.TkRoot$env$TclVarCount <- 0
tkwidget <- function (parent, type, ...)
{
win <- .Tk.subwin(parent)
tcl(type, win, ...)
win
}
tkbutton <- function(parent, ...) tkwidget(parent, "button", ...)
tkcanvas <- function(parent, ...) tkwidget(parent, "canvas", ...)
tkcheckbutton <- function(parent, ...) tkwidget(parent, "checkbutton", ...)
tkentry <- function(parent, ...) tkwidget(parent, "entry", ...)
tkframe <- function(parent, ...) tkwidget(parent, "frame", ...)
tklabel <- function(parent, ...) tkwidget(parent, "label", ...)
tklistbox <- function(parent, ...) tkwidget(parent, "listbox", ...)
tkmenu <- function(parent, ...) tkwidget(parent, "menu", ...)
tkmenubutton <- function(parent, ...) tkwidget(parent, "menubutton", ...)
tkmessage <- function(parent, ...) tkwidget(parent, "message", ...)
tkradiobutton <- function(parent, ...) tkwidget(parent, "radiobutton", ...)
tkscale <- function(parent, ...) tkwidget(parent, "scale", ...)
tkscrollbar <- function(parent, ...) tkwidget(parent, "scrollbar", ...)
tktext <- function(parent, ...) tkwidget(parent, "text", ...)
ttkbutton <- function(parent, ...) tkwidget(parent, "ttk::button", ...)
ttkcheckbutton <- function(parent, ...) tkwidget(parent, "ttk::checkbutton", ...)
ttkcombobox <- function(parent, ...) tkwidget(parent, "ttk::combobox", ...)
ttkentry <- function(parent, ...) tkwidget(parent, "ttk::entry", ...)
ttkframe <- function(parent, ...) tkwidget(parent, "ttk::frame", ...)
ttklabel <- function(parent, ...) tkwidget(parent, "ttk::label", ...)
ttklabelframe <- function(parent, ...) tkwidget(parent, "ttk::labelframe", ...)
ttkmenubutton <- function(parent, ...) tkwidget(parent, "ttk::menubutton", ...)
ttknotebook <- function(parent, ...) tkwidget(parent, "ttk::notebook", ...)
ttkpanedwindow <- function(parent, ...) tkwidget(parent, "ttk::panedwindow", ...)
ttkprogressbar <- function(parent, ...) tkwidget(parent, "ttk::progressbar", ...)
ttkradiobutton <- function(parent, ...) tkwidget(parent, "ttk::radiobutton", ...)
ttkscale <- function(parent, ...) tkwidget(parent, "ttk::scale", ...)
ttkscrollbar <- function(parent, ...) tkwidget(parent, "ttk::scrollbar", ...)
ttkseparator <- function(parent, ...) tkwidget(parent, "ttk::separator", ...)
ttksizegrip <- function(parent, ...) tkwidget(parent, "ttk::sizegrip", ...)
ttkspinbox <- function(parent, ...) tkwidget(parent, "ttk::spinbox", ...)
ttktreeview <- function(parent, ...) tkwidget(parent, "ttk::treeview", ...)
tktoplevel <- function(parent = .TkRoot,...) {
w <- tkwidget(parent,"toplevel",...)
ID <- .Tk.ID(w)
tkbind(w, "<Destroy>",
function() {
if (exists(ID, envir = parent$env, inherits = FALSE))
rm(list = ID, envir = parent$env)
tkbind(w, "<Destroy>","")
})
utils::process.events()
w
}
tcl <- function(...) .Tcl.objv(.Tcl.args.objv(...))
tktitle <- function(x) tcl("wm", "title", x)
"tktitle<-" <- function(x, value) {
tcl("wm", "title", x, value)
x
}
tkbell <- function(...) tcl("bell", ...)
tkbind <- function(...) tcl("bind", ...)
tkbindtags <- function(...) tcl("bindtags", ...)
tkfocus <- function(...) tcl("focus", ...)
tklower <- function(...) tcl("lower", ...)
tkraise <- function(...) tcl("raise", ...)
tkclipboard.append <- function(...) tcl("clipboard", "append", ...)
tkclipboard.clear <- function(...) tcl("clipboard", "clear", ...)
tkevent.add <- function(...) tcl("event", "add", ...)
tkevent.delete <- function(...) tcl("event", "delete", ...)
tkevent.generate <- function(...) tcl("event", "generate", ...)
tkevent.info <- function(...) tcl("event", "info", ...)
tkfont.actual <- function(...) tcl("font", "actual", ...)
tkfont.configure <- function(...) tcl("font", "configure", ...)
tkfont.create <- function(...) tcl("font", "create", ...)
tkfont.delete <- function(...) tcl("font", "delete", ...)
tkfont.families <- function(...) tcl("font", "families", ...)
tkfont.measure <- function(...) tcl("font", "measure", ...)
tkfont.metrics <- function(...) tcl("font", "metrics", ...)
tkfont.names <- function(...) tcl("font", "names", ...)
tkgrab <- function(...) tcl("grab", ...)
tkgrab.current <- function(...) tcl("grab", "current", ...)
tkgrab.release <- function(...) tcl("grab", "release", ...)
tkgrab.set <- function(...) tcl("grab", "set", ...)
tkgrab.status <- function(...) tcl("grab", "status", ...)
tkimage.create <- function(...) tcl("image", "create", ...)
tkimage.delete <- function(...) tcl("image", "delete", ...)
tkimage.height <- function(...) tcl("image", "height", ...)
tkimage.inuse <- function(...) tcl("image", "inuse", ...)
tkimage.names <- function(...) tcl("image", "names", ...)
tkimage.type <- function(...) tcl("image", "type", ...)
tkimage.types <- function(...) tcl("image", "types", ...)
tkimage.width <- function(...) tcl("image", "width", ...)
tkXselection.clear <- function(...) tcl("selection", "clear", ...)
tkXselection.get <- function(...) tcl("selection", "get", ...)
tkXselection.handle <- function(...) tcl("selection", "handle", ...)
tkXselection.own <- function(...) tcl("selection", "own", ...)
tkwait.variable <- function(...) tcl("tkwait", "variable", ...)
tkwait.visibility <- function(...) tcl("tkwait", "visibility", ...)
tkwait.window <- function(...) tcl("tkwait", "window", ...)
tkgetOpenFile <- function(...) tcl("tk_getOpenFile", ...)
tkgetSaveFile <- function(...) tcl("tk_getSaveFile", ...)
tkchooseDirectory <- function(...) tcl("tk_chooseDirectory", ...)
tkmessageBox <- function(...) tcl("tk_messageBox", ...)
tkdialog <- function(...) tcl("tk_dialog", ...)
tkpopup <- function(...) tcl("tk_popup", ...)
tclfile.tail <- function(...) tcl("file", "tail", ...)
tclfile.dir <- function(...) tcl("file", "dir", ...)
tclopen <- function(...) tcl("open", ...)
tclclose <- function(...) tcl("close", ...)
tclputs <- function(...) tcl("puts", ...)
tclread <- function(...) tcl("read", ...)
tkwinfo <- function(...) tcl("winfo", ...)
tkwm.aspect <- function(...) tcl("wm", "aspect", ...)
tkwm.client <- function(...) tcl("wm", "client", ...)
tkwm.colormapwindows <- function(...) tcl("wm", "colormapwindows", ...)
tkwm.command <- function(...) tcl("wm", "command", ...)
tkwm.deiconify <- function(...) tcl("wm", "deiconify", ...)
tkwm.focusmodel <- function(...) tcl("wm", "focusmodel", ...)
tkwm.frame <- function(...) tcl("wm", "frame", ...)
tkwm.geometry <- function(...) tcl("wm", "geometry", ...)
tkwm.grid <- function(...) tcl("wm", "grid", ...)
tkwm.group <- function(...) tcl("wm", "group", ...)
tkwm.iconbitmap <- function(...) tcl("wm", "iconbitmap", ...)
tkwm.iconify <- function(...) tcl("wm", "iconify", ...)
tkwm.iconmask <- function(...) tcl("wm", "iconmask", ...)
tkwm.iconname <- function(...) tcl("wm", "iconname ", ...)
tkwm.iconposition <- function(...) tcl("wm", "iconposition", ...)
tkwm.iconwindow <- function(...) tcl("wm", "iconwindow ", ...)
tkwm.maxsize <- function(...) tcl("wm", "maxsize", ...)
tkwm.minsize <- function(...) tcl("wm", "minsize", ...)
tkwm.overrideredirect <- function(...) tcl("wm", "overrideredirect", ...)
tkwm.positionfrom <- function(...) tcl("wm", "positionfrom", ...)
tkwm.protocol <- function(...) tcl("wm", "protocol", ...)
tkwm.resizable <- function(...) tcl("wm", "resizable", ...)
tkwm.sizefrom <- function(...) tcl("wm", "sizefrom", ...)
tkwm.state <- function(...) tcl("wm", "state", ...)
tkwm.title <- function(...) tcl("wm", "title", ...)
tkwm.transient <- function(...) tcl("wm", "transient", ...)
tkwm.withdraw <- function(...) tcl("wm", "withdraw", ...)
tkgrid <- function(...) tcl("grid", ...)
tkgrid.bbox <- function(...) tcl("grid", "bbox", ...)
tkgrid.columnconfigure <- function(...) tcl("grid", "columnconfigure", ...)
tkgrid.configure <- function(...) tcl("grid", "configure", ...)
tkgrid.forget <- function(...) tcl("grid", "forget", ...)
tkgrid.info <- function(...) tcl("grid", "info", ...)
tkgrid.location <- function(...) tcl("grid", "location", ...)
tkgrid.propagate <- function(...) tcl("grid", "propagate", ...)
tkgrid.rowconfigure <- function(...) tcl("grid", "rowconfigure", ...)
tkgrid.remove <- function(...) tcl("grid", "remove", ...)
tkgrid.size <- function(...) tcl("grid", "size", ...)
tkgrid.slaves <- function(...) tcl("grid", "slaves", ...)
tkpack <- function(...) tcl("pack", ...)
tkpack.configure <- function(...) tcl("pack", "configure", ...)
tkpack.forget <- function(...) tcl("pack", "forget", ...)
tkpack.info <- function(...) tcl("pack", "info", ...)
tkpack.propagate <- function(...) tcl("pack", "propagate", ...)
tkpack.slaves <- function(...) tcl("pack", "slaves", ...)
tkplace <- function(...) tcl("place", ...)
tkplace.configure <- function(...) tcl("place", "configure", ...)
tkplace.forget <- function(...) tcl("place", "forget", ...)
tkplace.info <- function(...) tcl("place", "info", ...)
tkplace.slaves <- function(...) tcl("place", "slaves", ...)
tkactivate <- function(widget, ...) tcl(widget, "activate", ...)
tkadd <- function(widget, ...) tcl(widget, "add", ...)
tkaddtag <- function(widget, ...) tcl(widget, "addtag", ...)
tkbbox <- function(widget, ...) tcl(widget, "bbox", ...)
tkcanvasx <- function(widget, ...) tcl(widget, "canvasx", ...)
tkcanvasy <- function(widget, ...) tcl(widget, "canvasy", ...)
tkcget <- function(widget, ...) tcl(widget, "cget", ...)
tkcompare <- function(widget, ...) tcl(widget, "compare", ...)
tkconfigure <- function(widget, ...) tcl(widget, "configure", ...)
tkcoords <- function(widget, ...) tcl(widget, "coords", ...)
tkcreate <- function(widget, ...) tcl(widget, "create", ...)
tkcurselection <- function(widget, ...) tcl(widget, "curselection", ...)
tkdchars <- function(widget, ...) tcl(widget, "dchars", ...)
tkdebug <- function(widget, ...) tcl(widget, "debug", ...)
tkdelete <- function(widget, ...) tcl(widget, "delete", ...)
tkdelta <- function(widget, ...) tcl(widget, "delta", ...)
tkdeselect <- function(widget, ...) tcl(widget, "deselect", ...)
tkdlineinfo <- function(widget, ...) tcl(widget, "dlineinfo", ...)
tkdtag <- function(widget, ...) tcl(widget, "dtag", ...)
tkdump <- function(widget, ...) tcl(widget, "dump", ...)
tkentrycget <- function(widget, ...) tcl(widget, "entrycget", ...)
tkentryconfigure <- function(widget, ...) tcl(widget, "entryconfigure", ...)
tkfind <- function(widget, ...) tcl(widget, "find", ...)
tkflash <- function(widget, ...) tcl(widget, "flash", ...)
tkfraction <- function(widget, ...) tcl(widget, "fraction", ...)
tkget <- function(widget, ...) tcl(widget, "get", ...)
tkgettags <- function(widget, ...) tcl(widget, "gettags", ...)
tkicursor <- function(widget, ...) tcl(widget, "icursor", ...)
tkidentify <- function(widget, ...) tcl(widget, "identify", ...)
tkindex <- function(widget, ...) tcl(widget, "index", ...)
tkinsert <- function(widget, ...) tcl(widget, "insert", ...)
tkinvoke <- function(widget, ...) tcl(widget, "invoke", ...)
tkitembind <- function(widget, ...) tcl(widget, "bind", ...)
tkitemcget <- function(widget, ...) tcl(widget, "itemcget", ...)
tkitemconfigure <- function(widget, ...) tcl(widget, "itemconfigure", ...)
tkitemfocus <- function(widget, ...) tcl(widget, "focus", ...)
tkitemlower <- function(widget, ...) tcl(widget, "lower", ...)
tkitemraise <- function(widget, ...) tcl(widget, "raise", ...)
tkitemscale <- function(widget, ...) tcl(widget, "scale", ...)
tkmark.gravity <- function(widget, ...) tcl(widget, "mark", "gravity", ...)
tkmark.names <- function(widget, ...) tcl(widget, "mark", "names", ...)
tkmark.next <- function(widget, ...) tcl(widget, "mark", "next", ...)
tkmark.previous <- function(widget, ...) tcl(widget, "mark", "previous", ...)
tkmark.set <- function(widget, ...) tcl(widget, "mark", "set", ...)
tkmark.unset <- function(widget, ...) tcl(widget, "mark", "unset", ...)
tkmove <- function(widget, ...) tcl(widget, "move", ...)
tknearest <- function(widget, ...) tcl(widget, "nearest", ...)
tkpost <- function(widget, ...) tcl(widget, "post", ...)
tkpostcascade <- function(widget, ...) tcl(widget, "postcascade", ...)
tkpostscript <- function(widget, ...) tcl(widget, "postscript", ...)
tkscan.dragto <- function(widget, ...) tcl(widget, "scan", "dragto", ...)
tkscan.mark <- function(widget, ...) tcl(widget, "scan", "mark", ...)
tksearch <- function(widget, ...) tcl(widget, "search", ...)
tksee <- function(widget, ...) tcl(widget, "see", ...)
tkselect <- function(widget, ...) tcl(widget, "select", ...)
tkselection.adjust <- function(widget, ...)
tcl(widget, "selection", "adjust", ...)
tkselection.anchor <- function(widget, ...)
tcl(widget, "selection", "anchor", ...)
tkselection.clear <- function(widget, ...)
tcl(widget, "selection", "clear", ...)
tkselection.from <- function(widget, ...)
tcl(widget, "selection", "from", ...)
tkselection.includes <- function(widget, ...)
tcl(widget, "selection", "includes", ...)
tkselection.present <- function(widget, ...)
tcl(widget, "selection", "present", ...)
tkselection.range <- function(widget, ...)
tcl(widget, "selection", "range", ...)
tkselection.set <- function(widget, ...)
tcl(widget, "selection", "set", ...)
tkselection.to <- function(widget,...)
tcl(widget, "selection", "to", ...)
tkset <- function(widget, ...) tcl(widget, "set", ...)
tksize <- function(widget, ...) tcl(widget, "size", ...)
tktoggle <- function(widget, ...) tcl(widget, "toggle", ...)
tktag.add <- function(widget, ...) tcl(widget, "tag", "add", ...)
tktag.bind <- function(widget, ...) tcl(widget, "tag", "bind", ...)
tktag.cget <- function(widget, ...) tcl(widget, "tag", "cget", ...)
tktag.configure <- function(widget, ...) tcl(widget, "tag", "configure", ...)
tktag.delete <- function(widget, ...) tcl(widget, "tag", "delete", ...)
tktag.lower <- function(widget, ...) tcl(widget, "tag", "lower", ...)
tktag.names <- function(widget, ...) tcl(widget, "tag", "names", ...)
tktag.nextrange <- function(widget, ...) tcl(widget, "tag", "nextrange", ...)
tktag.prevrange <- function(widget, ...) tcl(widget, "tag", "prevrange", ...)
tktag.raise <- function(widget, ...) tcl(widget, "tag", "raise", ...)
tktag.ranges <- function(widget, ...) tcl(widget, "tag", "ranges", ...)
tktag.remove <- function(widget, ...) tcl(widget, "tag", "remove", ...)
tktype <- function(widget, ...) tcl(widget, "type", ...)
tkunpost <- function(widget, ...) tcl(widget, "unpost", ...)
tkwindow.cget <- function(widget, ...) tcl(widget, "window", "cget", ...)
tkwindow.configure <- function(widget, ...) tcl(widget,"window","configure",...)
tkwindow.create <- function(widget, ...) tcl(widget, "window", "create", ...)
tkwindow.names <- function(widget, ...) tcl(widget, "window", "names", ...)
tkxview <- function(widget, ...) tcl(widget, "xview", ...)
tkxview.moveto <- function(widget, ...) tcl(widget, "xview", "moveto", ...)
tkxview.scroll <- function(widget, ...) tcl(widget, "xview", "scroll", ...)
tkyposition <- function(widget, ...) tcl(widget, "ypositions", ...)
tkyview <- function(widget, ...) tcl(widget, "yview", ...)
tkyview.moveto <- function(widget, ...) tcl(widget, "yview", "moveto", ...)
tkyview.scroll <- function(widget, ...) tcl(widget, "yview", "scroll", ...)
tkpager <- function(file, header, title, delete.file)
{
title <- paste(title, header)
for ( i in seq_along(file) ) {
zfile <- file[[i]]
tt <- tktoplevel()
tkwm.title(tt,
if (length(title)) title[(i-1L) %% length(title)+1L] else "")
txt <- tktext(tt, bg = "grey90")
scr <- tkscrollbar(tt, repeatinterval = 5,
command = function(...) tkyview(txt,...))
tkconfigure(txt, yscrollcommand = function(...) tkset(scr,...))
tkpack(txt, side = "left", fill = "both", expand = TRUE)
tkpack(scr, side = "right", fill = "y")
chn <- tcl("open", zfile)
tkinsert(txt, "end", gsub("_\b","",tclvalue(tcl("read", chn))))
tcl("close", chn)
tkconfigure(txt, state = "disabled")
tkmark.set(txt, "insert", "0.0")
tkfocus(txt)
if (delete.file) tcl("file", "delete", zfile)
}
}
|
plotautocor <- function(data, ask = TRUE, lag.max = 100, ...) {
if (!is.data.frame(data))
data <- read.table(data, header = TRUE)
data <- data[, -1]
data.mcmc <- coda::as.mcmc(data)
coda::autocorr.plot(data.mcmc, ask = ask, lag.max = lag.max, ...)
return(invisible())
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.