code
stringlengths 1
13.8M
|
---|
source("ESEUR_config.r")
library(plyr)
library(survival)
study_start=as.Date("9-November-2004", format="%d-%B-%Y")
study_end=as.Date("1-October-2010", format="%d-%B-%Y")
every_day=seq(study_start, study_end, by=1)
version_fault=read.csv(paste0(ESEUR_dir, "faults/ff-version-fault.csv.xz"), row.names=1, as.is=TRUE)
vf_names=colnames(version_fault)
version_dates=read.csv(paste0(ESEUR_dir, "faults/ff-release-retire.csv.xz"), row.names=1, as.is=TRUE)
version_dates$release=as.Date(version_dates$release, format="%d-%B-%Y")
version_dates$retire=as.Date(version_dates$retire, format="%d-%B-%Y")
version_dates$retire[version_dates$retire > study_end]=study_end
mk_censored_release=function(censor_count, src_cluster)
{
if (censor_count == 0)
return(NULL)
rep_cluster=names(censor_count)
src_start=version_dates[src_cluster, 1]
rep_start=version_dates[rep_cluster, 1]
survive_list=data.frame(rep_date=rep(NA, censor_count))
survive_list$end=as.numeric(rep_start-study_start)
survive_list$start=as.numeric(src_start-study_start)
survive_list$src_id=src_cluster
survive_list$rep_id=rep_cluster
survive_list$event=0
return(survive_list)
}
mk_censored_faults=function(fault_count, src_cluster, rep_cluster)
{
if (src_cluster == rep_cluster)
return(NULL)
start_col= 1+which(names(src_percent) == src_cluster)
end_col= which(names(src_percent) == rep_cluster)
percent_missing=as.numeric(1-src_percent[src_cluster, start_col:end_col])
latest_missing=percent_missing[length(percent_missing)]
if (latest_missing == 0)
return(NULL)
total_cendored=fault_count/latest_missing
faults_censored=cummax(total_cendored*(percent_missing/latest_missing))
ver_cen_fault=round(diff(c(0, faults_censored)))
names(ver_cen_fault)=names(src_percent)[start_col:end_col]
t=adply(ver_cen_fault, 1,
function(X)
mk_censored_release(X, src_cluster))
return(t)
}
mk_cell_survive=function(fault_count)
{
if (is.na(fault_count))
return(NULL)
src_cluster=rownames(fault_count)
rep_cluster=colnames(fault_count)
src_start_date=version_dates[src_cluster, 1]
rep_start_date=version_dates[rep_cluster, 1]
rep_end_date=version_dates[rep_cluster, 2]
cur_fault_count=as.integer(fault_count)
if (cur_fault_count == 0)
{
return(NULL)
}
censored_faults=mk_censored_faults(cur_fault_count, src_cluster, rep_cluster)
censored_faults$X1=NULL
start_offset=as.numeric(rep_start_date)
end_offset=as.numeric(rep_end_date)
v_interval=end_offset-start_offset
f_width=v_interval / cur_fault_count
survive_list=data.frame(rep_date=rep_start_date+runif(cur_fault_count, 1, v_interval))
survive_list=data.frame(rep_date=rep_start_date+(1:cur_fault_count)*f_width)
survive_list$start=as.numeric(src_start_date-study_start)
survive_list$src_id=src_cluster
survive_list$rep_id=rep_cluster
survive_list$event=1
return(rbind(survive_list, censored_faults))
}
mk_row_survive=function(version_row)
{
t=adply(version_row, 2, mk_cell_survive)
return(t)
}
mk_survive=function(version_array)
{
t=adply(version_array, 1, mk_row_survive)
return(t)
}
src_LOC=read.csv(paste0(ESEUR_dir, "faults/ff-src-version.csv.xz"), row.names=1, as.is=TRUE)
LOC_diag=diag(src_LOC)
src_percent=src_LOC/diag(as.matrix(src_LOC))
ff_faults=mk_survive(version_fault)
ff_faults$fault_id=1:nrow(ff_faults)
ff_faults$v1.0=NULL
ff_faults$v1.5=NULL
ff_faults$v2.0=NULL
ff_faults$v3.0=NULL
ff_faults$v3.5=NULL
ff_faults$v3.6=NULL
ff_faults$X1=NULL
total_usage=function(one_fault)
{
total_usage=sum(daily_ff_usage[(one_fault$start+1):one_fault$end])
return(data.frame(total_usage))
}
browser_ms=read.csv(paste0(ESEUR_dir, "faults/w3stats_browser.csv.xz"), as.is=TRUE)
browser_ms$date=as.Date(browser_ms$date, format="%m/%d/%Y")
total_ff_ms=ddply(browser_ms, .(date),
function(df) data.frame(ms=sum(df$market_share)))
total_ff_ms$date=as.numeric(total_ff_ms$date)
l_mod=loess(ms ~ date, data=total_ff_ms, span=0.2)
daily_ff_ms=predict(l_mod, newdata=data.frame(date=as.numeric(every_day)))
i_users=read.csv(paste0(ESEUR_dir, "faults/itu-internet-users.csv.xz"), as.is=TRUE)
i_users$year=as.Date(i_users$year)
user_mod=lm(Developed ~ year, data=i_users)
daily_i_users=predict(user_mod, newdata=data.frame(year=every_day))
pop_growth=(1.09^(1/365))^(1:length(daily_i_users))
daily_i_users=daily_i_users*pop_growth
daily_ff_usage=daily_ff_ms*daily_i_users
split_start_end=function(one_fault)
{
t=seq(one_fault$start, one_fault$end, by = 7)
split_start=t[t < one_fault$end-7]
if (one_fault$end-7 < one_fault$start)
{
f_interval=one_fault
}
else
{
f_interval=one_fault[rep(1, length(split_start)), ]
f_interval$start=split_start
f_interval$end=split_start+7
f_interval$event=0
t=one_fault
t$start=f_interval$end[nrow(f_interval)]
f_interval=rbind(f_interval, t)
}
t=adply(f_interval, 1, total_usage)
return(t)
}
ff_usage=adply(ff_faults, 1, split_start_end)
f_sur=Surv(time=ff_usage$start, time2=ff_usage$end, event=ff_usage$event)
f_fit=survfit(f_sur ~ 1+cluster(ff_usage$fault_id))
plot(f_fit)
ff_cox=coxph(f_sur ~ total_usage+strata(src_id)+cluster(fault_id), data=ff_usage)
t=cox.zph(ff_cox)
t
plot(t)
ff_cox=coxph(Surv(time=start, time2=end, event=event) ~
total_usage+strata(src_id)+cluster(fault_id), data=ff_usage)
v1=subset(ff_usage, src_id == "v1.0")
v_sur=Surv(v1$start, v1$end, v1$event)
ff_cox=coxph(v_sur ~ total_usage, data=v1, ties="breslow")
v1=ff_usage[1:100, ]
v_sur=Surv(time=v1$start, time2=v1$end, event=v1$event)
ff_cox=coxph(v_sur ~ total_usage+cluster(fault_id), data=v1)
library(rms)
f_sur=Srv(time=ff_usage$start, time2=ff_usage$end, event=ff_usage$event)
ff_cox=cph(f_sur ~ total_usage+strat(src_id)+cluster(fault_id), data=ff_usage)
|
random.shortonly.test <- function( n=2, k=n, segments=NULL, x.t=1,
x.l=0, x.u=x.t, max.iter=1000 )
{
if ( x.l >= x.u )
stop( "Argument 'x.l' is greater than or equal to argument 'x.u'" )
if ( x.l < 0 )
stop( "Argument 'x.l' is less than zero" )
if ( x.u < 0 )
stop( "Argument 'x.u' is less than zero" )
thisResult <- random.longonly.test( n, k, segments, x.t, x.l, x.u,
max.iter )
x <- -thisResult$x
iter <- thisResult$iter
newResult <- list( x=x, iter=iter )
return( newResult )
}
|
tbl_format_header <- function(x, setup, ...) {
check_dots_empty()
UseMethod("tbl_format_header")
}
tbl_format_header.tbl <- function(x, setup, ...) {
named_header <- setup$tbl_sum
if (all(names2(named_header) == "")) {
header <- named_header
} else {
header <- paste0(
align(paste0(names2(named_header), ":"), space = NBSP),
" ",
named_header
)
}
style_subtle(format_comment(header, width = setup$width))
}
tbl_format_header.pillar_tbl_format_setup <- function(x, ...) {
as_glue(c(
cli::style_bold("<tbl_format_header(setup)>"),
tbl_format_header(x$x, setup = x)
))
}
|
split.data.byext.comb <- function(dat,ext.mat=ext.mat,
clstr0.vec=NULL){
printcheck <- TRUE
H <- ncol(ext.mat)
if(is.null(H)){
ext.mat=as.matrix(ext.mat,ncol=1)
H=1
}
J=ncol(dat) ; N=nrow(dat)
extcate.vec<-sapply(seq(1,H),function(x){length(unique(ext.mat[,x]))})
extcate.list=rep(list(NA),H)
for(hh in 1:H){
extcate.list[[hh]]=unique(ext.mat[,hh])
if(all(is.numeric(extcate.list[[hh]])))extcate.list[[hh]]=sort(extcate.list[[hh]])
extcate.vec[hh]=length(extcate.list[[hh]])
}
C<-prod(extcate.vec)
extcomb <- expand.grid(lapply(c(1:H),function(x){extcate.list[[x]]}))
if(nrow(extcomb)!=C){
stop("something is wrong.")
}
classlab.mat=matrix(NA,C,H+1)
rownames(classlab.mat)=paste0(c(1:C),"th class")
colnames(classlab.mat)=c(paste0("extvari",c(1:H)),"classlabel")
classlab.mat[,c(1:H)]=as.matrix(extcomb)
classlab.mat[,(H+1)]=apply(extcomb,1,function(x){paste(x,collapse="&")})
X.list<-clstr0.list <- clstr.list <- oriindex.list <-rep(list(NA),C)
names(X.list)<-names(clstr0.list) <- names(clstr.list) <- names(oriindex.list) <-classlab.mat[,(H+1)]
class.n.vec <- clstr.vec<-rep(NA,N)
names(class.n.vec)=rownames(dat)
Ktrue.vec<-N.vec <- rep(NA,C)
names(Ktrue.vec)<-names(N.vec) <-classlab.mat[,(H+1)]
emptyclass=rep(FALSE,C)
cc <- emp<-1
for(cc in 1:C){
comb <- as.vector(extcomb[cc,])
as.character(extcomb[cc,])
pickupsub <- apply(ext.mat,1,function(x){all(x==comb)})
N.vec[cc] <- Nc <-sum(pickupsub)
if(printcheck) cat(cc,"th class:","(",paste(as.matrix(comb),collapse=","),") data, n=",Nc,"\n")
if(Nc==0){
cat("the
emptyclass[cc]=TRUE
Ktrue.vec[cc]=0
}else{
X.list[[cc]]<-dat[pickupsub,]
class.n.vec[pickupsub]=cc
oriindex.list[[cc]]=which(pickupsub)
if(!is.null(clstr0.vec)){
clstr0.list[[cc]] <- clstr0.vec[pickupsub]
Ktrue.vec[cc]=length(unique(clstr0.list[[cc]]))
}
}
}
ded=1 ; class.n.vec.old=class.n.vec
for(emp in which(emptyclass)){
whichlist=(which(names(X.list)==classlab.mat[emp,H+1]))
X.list[[whichlist]]<-clstr0.list[[whichlist]] <- oriindex.list[[whichlist]]<-NULL
class.n.vec[emp<class.n.vec.old]=class.n.vec.old[emp<class.n.vec.old]-ded
ded=ded+1
}
if(any(emptyclass)){
classlab.mat=classlab.mat[-which(emptyclass),]
N.vec<-N.vec[-which(emptyclass)] ; Ktrue.vec<-Ktrue.vec[-which(emptyclass)]
}
C2=nrow(classlab.mat)
rownames(classlab.mat)<-paste0(c(1:C2),"th class")
names(N.vec)<-names(Ktrue.vec)<-mapply(function(x,y){paste(x,y,sep=":")},c(1:C2),classlab.mat[,(H+1)])
names(oriindex.list)=mapply(function(x,y){paste(x,y,sep=":")},c(1:C2),names(oriindex.list))
names(X.list)=mapply(function(x,y){paste(x,y,sep=":")},c(1:C2),names(X.list))
classname.n.vec=classlab.mat[class.n.vec,(H+1)]
classname.n.vec=mapply(function(x,y){paste(x,y,sep=":")},class.n.vec,classname.n.vec)
if(is.null(clstr0.vec)){
clstr0.list <- Ktrue.vec<-NULL
}
list(data.list=X.list,clstr0.list=clstr0.list,Ktrue.vec=Ktrue.vec
,N.vec=N.vec,classlab.mat=classlab.mat,class.n.vec=class.n.vec,classname.n.vec=classname.n.vec,
oriindex.list=oriindex.list)
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
required <- c("tidyverse", "MortalityLaws", "reshape2")
if (!all(sapply(required,
function(pkg) requireNamespace(pkg, quietly = TRUE)))) {
message(paste("This vignette needs the followig packages:\n\t",
paste(required, collapse = " "),
"\nSince not all are installed, code will not be executed: "))
knitr::opts_chunk$set(eval = FALSE)
}
|
options("repos" = c(CRAN = "http://cran.ma.imperial.ac.uk/"))
\dontrun{
install.packages("fortunes")
}
library("fortunes")
library(help=fortunes)
\dontrun{
vignette("fortunes")
}
\dontrun{
update.packages()
}
search()
detach(package:fortunes, unload=TRUE)
\dontrun{
install.packages("data.table", repos="http://R-Forge.R-project.org")
}
\dontrun{
source("http://bioconductor.org/biocLite.R")
}
|
get_comptab <- function(pdat, var1="ZC", var2="nH2O", plot.it=FALSE, mfun="median", oldstyle = FALSE, basis = getOption("basis")) {
ZC <- function() ZCAA(pdat$pcomp$aa)
nH2O <- function() H2OAA(pdat$pcomp$aa, basis = basis)
nO2 <- function() O2AA(pdat$pcomp$aa, basis = basis)
AA3 <- c("Ala", "Cys", "Asp", "Glu", "Phe", "Gly", "His", "Ile", "Lys", "Leu",
"Met", "Asn", "Pro", "Gln", "Arg", "Ser", "Thr", "Val", "Trp", "Tyr")
icol <- match(AA3, colnames(pdat$pcomp$aa))
nAA <- function() rowSums(pdat$pcomp$aa[, icol])
V0 <- function() {
volumes <- c(26.864, 39.913, 41.116, 56.621, 88.545, 9.606, 65.753, 72.204,
75.048, 74.2, 71.832, 43.826, 49.049, 60.078, 105.825, 27.042,
44.03, 57.279, 110.045, 90.904, 26.296, 33.585)
vAA <- volumes[1:20]
vUPBB <- volumes[21]
vAABB <- volumes[22]
VAA <- rowSums(t(t(pdat$pcomp$aa[, icol]) * vAA))
chains <- pdat$pcomp$aa$chains
plength <- nAA()
VUPBB <- (plength - chains) * vUPBB
VAABB <- chains * vAABB
(VAA + VUPBB + VAABB) / plength
}
GRAVY <- function() canprot::GRAVY(pdat$pcomp$aa)
pI <- function() canprot::pI(pdat$pcomp$aa)
MW <- function() MWAA(pdat$pcomp$aa)
val1 <- get(var1)()
val2 <- get(var2)()
if(plot.it) {
col <- ifelse(pdat$up2, 2, 4)
pch <- ifelse(pdat$up2, 0, 19)
cex <- ifelse(pdat$up2, 1, 0.8)
i <- sample(1:length(val1))
plot(val1[i], val2[i], xlab=cplab[[var1]], ylab=cplab[[var2]], col=col[i], pch=pch[i], cex=cex[i])
title(pdat$description)
mtext(pdat$dataset, side=4, cex=0.85, las=0, adj=0, line=-0.1)
}
val1_dn <- val1[!pdat$up2]
val1_up <- val1[pdat$up2]
val2_dn <- val2[!pdat$up2]
val2_up <- val2[pdat$up2]
message(paste0(pdat$dataset, " (", pdat$description ,"): n1 ", length(val1_dn), ", n2 ", length(val1_up)))
mfun1_dn <- get(mfun)(val1_dn)
mfun1_up <- get(mfun)(val1_up)
mfun2_dn <- get(mfun)(val2_dn)
mfun2_up <- get(mfun)(val2_up)
val1.diff <- mfun1_up - mfun1_dn
val2.diff <- mfun2_up - mfun2_dn
out <- data.frame(dataset=pdat$dataset, description=pdat$description,
n1=length(val1_dn), n2=length(val1_up),
val1.median1=mfun1_dn, val1.median2=mfun1_up, val1.diff,
val2.median1=mfun2_dn, val2.median2=mfun2_up, val2.diff, stringsAsFactors=FALSE)
if(oldstyle) {
val1.CLES <- 100*CLES(val1_dn, val1_up, distribution = NA)
val2.CLES <- 100*CLES(val2_dn, val2_up, distribution = NA)
val1.p.value <- val2.p.value <- NA
if(!any(is.na(val1_dn)) & !any(is.na(val1_up))) val1.p.value <- stats::wilcox.test(val1_dn, val1_up)$p.value
if(!any(is.na(val2_dn)) & !any(is.na(val2_up))) val2.p.value <- stats::wilcox.test(val2_dn, val2_up)$p.value
nchar1 <- nchar(var1)
nchar2 <- nchar(var2)
start1 <- paste0(var1, substr(" MD ", nchar1, 10))
start2 <- paste0(var2, substr(" MD ", nchar2, 10))
message(paste0(start1, format(round(val1.diff, 3), nsmall=3, width=6),
", CLES ", round(val1.CLES), "%",
", p-value ", format(round(val1.p.value, 3), nsmall=3)))
message(paste0(start2, format(round(val2.diff, 3), nsmall=3, width=6),
", CLES ", round(val2.CLES), "%",
", p-value ", format(round(val2.p.value, 3), nsmall=3), "\n"))
out <- data.frame(dataset=pdat$dataset, description=pdat$description,
n1=length(val1_dn), n2=length(val1_up),
val1.median1=mfun1_dn, val1.median2=mfun1_up, val1.diff, val1.CLES, val1.p.value,
val2.median1=mfun2_dn, val2.median2=mfun2_up, val2.diff, val2.CLES, val2.p.value, stringsAsFactors=FALSE)
}
colnames(out) <- gsub("val1", var1, colnames(out))
colnames(out) <- gsub("val2", var2, colnames(out))
if(mfun == "mean") colnames(out) <- gsub("median", "mean", colnames(out))
return(invisible(out))
}
|
context("dockerignore")
test_that("parse_dockerignore: empty", {
expect_null(parse_dockerignore(character()))
expect_null(parse_dockerignore(NULL))
expect_null(parse_dockerignore("
expect_null(parse_dockerignore(" "))
expect_null(parse_dockerignore(c("
})
test_that("parse_dockerignore: empty", {
expect_null(parse_dockerignore(character()))
expect_null(parse_dockerignore(NULL))
expect_null(parse_dockerignore("
expect_null(parse_dockerignore(" "))
expect_null(parse_dockerignore(c("
})
test_that("parse_dockerignore: simple", {
expect_equal(parse_dockerignore("hello"),
list(patterns = "hello", is_exception = FALSE))
})
test_that("parse_dockerignore: exceptions", {
expect_equal(parse_dockerignore(c("*.md", "!README.md")),
list(patterns = c("*.md", "README.md"),
is_exception = c(FALSE, TRUE)))
})
test_that("parse_dockerignore: cleanup", {
parse_dockerignore("//a///b\\c")$patterns
expect_equal(parse_dockerignore("a/b/c")$patterns, "a/b/c")
expect_equal(parse_dockerignore("a//b/c")$patterns, "a/b/c")
expect_equal(parse_dockerignore("a//b\\c")$patterns, "a/b/c")
expect_equal(parse_dockerignore("/a//b\\c")$patterns, "a/b/c")
expect_equal(parse_dockerignore("////a/////b///c\\\\\\d")$patterns, "a/b/c/d")
})
test_that("simple cases", {
paths <- c(paste0("dir1/", c("a.txt", "b.md", "c.c")),
paste0("dir2/", c("file.txt", "foo.md", "secret.json")),
paste0("dir3/", c("bar.md", "bar.c")),
"README.md",
"Dockerfile")
root <- make_fake_files(paths)
on.exit(unlink(root, recursive = TRUE), add = TRUE)
dockerfile <- "Dockerfile"
expect_equal(build_file_list(root, NULL), ".")
dockerignore <- parse_dockerignore(c("*/*.md", "dir2"))
expect_equal(
build_file_list(root, dockerignore),
sort(c("Dockerfile", "README.md", "dir1/a.txt", "dir1/c.c",
"dir3/bar.c")))
dockerignore <- parse_dockerignore(c("*/*.md", "dir2", "!dir2/foo.md"))
expect_equal(
build_file_list(root, dockerignore),
sort(c("Dockerfile", "README.md", "dir1/a.txt", "dir1/c.c",
"dir2/foo.md", "dir3/bar.c")))
dockerignore <- parse_dockerignore(c("**/*.md", "dir2"))
expect_equal(
build_file_list(root, dockerignore),
sort(c("Dockerfile", "dir1/a.txt", "dir1/c.c",
"dir3/bar.c")))
dockerignore <- parse_dockerignore(c("**/*.md", "dir2", "!dir2/foo.md"))
expect_equal(
build_file_list(root, dockerignore),
sort(c("Dockerfile", "dir1/a.txt", "dir1/c.c",
"dir2/foo.md", "dir3/bar.c")))
})
test_that("build file list with excluded dockerignore", {
paths <- c(paste0("dir1/", c("a.txt", "Dockerfile")),
paste0("dir2/", c("file.txt", "foo.md", "secret.json")),
"README.md")
root <- make_fake_files(paths)
on.exit(unlink(root, recursive = TRUE), add = TRUE)
dockerfile <- "dir1/Dockerfile"
writeLines("dir1", file.path(root, ".dockerignore"))
ignore1 <- parse_dockerignore("dir1")
ignore2 <- include_dockerfile(ignore1, root, dockerfile)
ignore3 <- read_dockerignore(root, dockerfile)
expect_equal(ignore2, ignore3)
expect_equal(build_file_list(root, ignore1),
sort(c(".dockerignore", "dir2", "README.md")))
expect_equal(build_file_list(root, ignore2),
sort(c(".dockerignore", "dir1/Dockerfile", "dir2", "README.md")))
expect_equal(build_file_list(root, ignore3),
sort(c(".dockerignore", "dir1/Dockerfile", "dir2", "README.md")))
})
test_that("build_tar", {
skip_if_external_tar_unsupported()
paths <- c(paste0("dir1/", c("a.txt", "Dockerfile")),
paste0("dir2/", c("file.txt", "foo.md", "secret.json")),
"README.md")
root <- make_fake_files(paths)
dockerfile <- "dir1/Dockerfile"
x <- build_tar(root, dockerfile)
expect_is(x, "raw")
tmp <- untar_bin(x)
expect_equal(dir(tmp, all.files = TRUE, recursive = TRUE),
dir(root, all.files = TRUE, recursive = TRUE))
unlink(tmp, recursive = TRUE)
writeLines("dir2", file.path(root, ".dockerignore"))
x <- build_tar(root, dockerfile)
tmp2 <- untar_bin(x)
f1 <- dir(tmp2, all.files = TRUE, recursive = TRUE)
f2 <- dir(root, all.files = TRUE, recursive = TRUE)
expect_equal(sort(f1), sort(grep("^dir2", f2, invert = TRUE, value = TRUE)))
unlink(root, recursive = TRUE)
unlink(tmp2, recursive = TRUE)
})
test_that("validate_tar_directory", {
skip_if_external_tar_unsupported()
paths <- c(paste0("dir1/", c("a.txt", "Dockerfile")),
paste0("dir2/", c("file.txt", "foo.md", "secret.json")),
"README.md")
root <- make_fake_files(paths)
on.exit(unlink(root, recursive = TRUE), add = TRUE)
dockerfile <- "dir1/Dockerfile"
bin <- validate_tar_directory(root, dockerfile)
expect_is(bin, "raw")
expect_identical(validate_tar_directory(bin), bin)
})
|
pwr.1way<-function(k=k, n=n,alpha=alpha, f=NULL, delta=delta, sigma=sigma){
if (is.null(f)) {f<-sqrt(((1/k)*(delta/2)^2*2)/sigma^2)
lambda<-n*k*f^2
q<- qf(alpha, k - 1, (n - 1) * k, lower.tail = FALSE)
pwr<-pf(q, k - 1, (n - 1) * k, lambda, lower.tail = FALSE)
NOTE <- paste("n is number in each group, total sample =", k*n, "power =", pwr)
METHOD <- "Balanced one-way analysis of variance power calculation"
structure(list(k=k, n=n, delta=delta, sigma=sigma, effect.size=f, sig.level=alpha, power = pwr, note = NOTE, method = METHOD), class = "power.htest")
} else {f<-f
lambda<-n*k*f^2
q<- qf(alpha, k - 1, (n - 1) * k, lower.tail = FALSE)
pwr<-pf(q, k - 1, (n - 1) * k, lambda, lower.tail = FALSE)
NOTE <- paste("n is number in each group, total sample =", k*n, "power =", pwr)
METHOD <- "Balanced one-way analysis of variance power calculation"
structure(list(k=k, n=n, effect.size=f, sig.level=alpha, power = pwr, note = NOTE, method = METHOD), class = "power.htest")
}
}
|
KO_evaluation=function(W,reg_coef,fdr_range=0.2,offset=1){
fdp = function(selected,reg_coef) {sum(reg_coef[selected] == 0) / max(1, length(selected))}
fpr = function(selected,reg_coef) {sum(reg_coef[selected] == 0) / max(1, sum(reg_coef==0))}
tpr = function(selected,reg_coef) {sum(reg_coef[selected] != 0) / max(1, sum(reg_coef!=0))}
perf=c()
for (i_fdr in fdr_range){
thres = knockoff.threshold(W, fdr=i_fdr, offset=offset)
selected = which(W >= thres)
perf=c(perf,fdp(selected,reg_coef),fpr(selected,reg_coef),tpr(selected,reg_coef))
}
perf=t(perf)
colnames(perf)=paste(rep(c("FDP","FPR","TPR"),length(fdr_range)),"_",rep(fdr_range,each=3),sep="")
return(perf)
}
|
context("earth")
test_that("parsnip + earth + axe_() works", {
skip_on_cran()
skip_if_not_installed("parsnip")
skip_if_not_installed("earth")
library(parsnip)
library(earth)
earth_fit <- mars(mode = "regression") %>%
set_engine("earth") %>%
fit(Volume ~ ., data = trees)
x <- axe_call(earth_fit)
expect_equal(x$fit$call, rlang::expr(dummy_call()))
expect_error(update(x))
x <- axe_fitted(earth_fit)
expect_equal(x$fit$residuals, numeric(0))
x <- axe_data(earth_fit)
expect_equal(x$fit$data, data.frame(NA))
expect_equal(residuals(x$fit), residuals(earth_fit$fit))
x <- butcher(earth_fit)
expect_equal(format(x$fit), format(earth_fit$fit))
expected_output <- predict(earth_fit, trees[1:3,])
new_output <- predict(x, trees[1:3,])
expect_equal(new_output, expected_output)
})
test_that("earth + axe_() works", {
skip_on_cran()
skip_if_not_installed("earth")
library(earth)
earth_mod <- earth(Volume ~ ., data = trees)
x <- axe_call(earth_mod)
expect_equal(x$call, rlang::expr(dummy_call()))
expect_error(update(x))
x <- axe_fitted(earth_mod)
expect_equal(x$residuals, numeric(0))
expect_warning(expect_error(residuals(x)))
x <- axe_data(earth_mod)
expect_equal(x, earth_mod)
expect_equal(class(x), class(earth_mod))
x <- butcher(earth_mod)
expect_equal(format(x), format(earth_mod))
expected_output <- predict(earth_mod, trees[1:3,])
new_output <- predict(x, trees[1:3,])
expect_equal(new_output, expected_output)
})
|
context("util.list")
test_that("which.pmax() properly applies attributes, and also works for lists of length 1", {
x <- list(a = matrix(c(1, 2, 3, 4)), b = matrix(c(4, 3, 2, 1)))
xattr <- attributes(x[[1]])
expect_equal(attributes(which.pmax(x)), xattr)
expect_equal(as.numeric(which.pmax(x[1])), c(1, 1, 1, 1))
})
test_that("which.pmax() can handle NA values", {
x <- list(a = matrix(c(1, 2, NA, 4)), b = matrix(c(4, 3, 2, 1)))
expect_equal(as.numeric(which.pmax(x)), c(2, 2, NA, 1))
})
|
output$Bullet0 <- rAmCharts::renderAmCharts({
rates <- data.frame(name = c('excelent', 'good', 'average', 'poor', 'bad'),
min = c(0, 20, 40, 60, 80),
max = c(20, 40, 60, 80, 100),
color = c('
'
stringsAsFactors = FALSE)
dataProvider <- data.frame(category = '', t(rates$max - rates$min), stringsAsFactors = FALSE)
colnames(dataProvider)[-1] <- as.character(rates$name)
dataProvider$limit <- 90
dataProvider$full <- 100
dataProvider$bullet <- 85
chart <- sapply(1:nrow(rates), FUN = function(rt) {
amGraph(type = 'column', valueField = as.character(rates$name[rt]), fillAlphas = 0.8,
lineColor = rates$color[rt], showBalloon = FALSE, columnWidth = 1)
})
chart <- c(chart,amGraph(type = 'step', valueField = 'limit', columnWidth = 0.5,
lineThickness = 3, noStepRisers = TRUE, stackable = FALSE))
chart <- c(chart,amGraph(type = 'column', valueField = 'bullet', columnWidth = 0.3, fillAlphas = 1, clustered = FALSE, stackable = FALSE))
pipeR::pipeline(
amSerialChart(dataProvider = dataProvider , categoryField = 'category',
columnWidth = 1) ,
addValueAxes(stackType = 'regular', gridAlpha = 0),
setGraphs(chart)
)
})
output$code_Bullet0 <- renderText({
"
rates <- data.frame(name = c('excelent', 'good', 'average', 'poor', 'bad'),
min = c(0, 20, 40, 60, 80),
max = c(20, 40, 60, 80, 100),
color = c('
'
stringsAsFactors = FALSE)
dataProvider <- data.frame(category = '', t(rates$max - rates$min), stringsAsFactors = FALSE)
colnames(dataProvider)[-1] <- as.character(rates$name)
dataProvider$limit <- 90
dataProvider$full <- 100
dataProvider$bullet <- 85
chart <- sapply(1:nrow(rates), FUN = function(rt) {
amGraph(type = 'column', valueField = as.character(rates$name[rt]), fillAlphas = 0.8,
lineColor = rates$color[rt], showBalloon = FALSE, columnWidth = 1)
})
chart <- c(chart,amGraph(type = 'step', valueField = 'limit', columnWidth = 0.5,
lineThickness = 3, noStepRisers = TRUE, stackable = FALSE))
chart <- c(chart,amGraph(type = 'column', valueField = 'bullet', columnWidth = 0.3, fillAlphas = 1, clustered = FALSE, stackable = FALSE))
pipeR::pipeline(
amSerialChart(dataProvider = dataProvider , categoryField = 'category',
columnWidth = 1) ,
addValueAxes(stackType = 'regular', gridAlpha = 0),
setGraphs(chart)
)
"
})
|
library(shiny.fluent)
people <- tibble::tribble(
~key, ~imageUrl, ~imageInitials, ~text, ~secondaryText, ~tertiaryText, ~optionalText, ~isValid, ~presence, ~canExpand,
1, "https://static2.sharepointonline.com/files/fabric/office-ui-fabric-react-assets/persona-female.png", "PV", "Annie Lindqvist", "Designer", "In a meeting", "Available at 4:00pm", TRUE, 2, NA,
2, "https://static2.sharepointonline.com/files/fabric/office-ui-fabric-react-assets/persona-male.png", "AR", "Aaron Reid", "Designer", "In a meeting", "Available at 4:00pm", TRUE, 6, NA,
3, "https://static2.sharepointonline.com/files/fabric/office-ui-fabric-react-assets/persona-male.png", "AL", "Alex Lundberg", "Software Developer", "In a meeting", "Available at 4:00pm", TRUE, 4, NA,
4, "https://static2.sharepointonline.com/files/fabric/office-ui-fabric-react-assets/persona-male.png", "RK", "Roko Kolar", "Financial Analyst", "In a meeting", "Available at 4:00pm", TRUE, 1, NA,
5, "https://static2.sharepointonline.com/files/fabric/office-ui-fabric-react-assets/persona-male.png", "CB", "Christian Bergqvist", "Sr. Designer", "In a meeting", "Available at 4:00pm", TRUE, 2, NA,
6, "https://static2.sharepointonline.com/files/fabric/office-ui-fabric-react-assets/persona-female.png", "VL", "Valentina Lovric", "Design Developer", "In a meeting", "Available at 4:00pm", TRUE, 2, NA,
7, "https://static2.sharepointonline.com/files/fabric/office-ui-fabric-react-assets/persona-male.png", "MS", "Maor Sharett", "UX Designer", "In a meeting", "Available at 4:00pm", TRUE, 3, NA
)
if (interactive()) {
shinyApp(
ui = tagList(
textOutput("selectedPeople"),
NormalPeoplePicker.shinyInput(
"selectedPeople",
options = people,
pickerSuggestionsProps = list(
suggestionsHeaderText = 'Matching people',
mostRecentlyUsedHeaderText = 'Sales reps',
noResultsFoundText = 'No results found',
showRemoveButtons = TRUE
)
)
),
server = function(input, output) {
output$selectedPeople <- renderText({
if (length(input$selectedPeople) == 0) {
"Select recipients below:"
} else {
selectedPeople <- dplyr::filter(people, key %in% input$selectedPeople)
paste("You have selected:", paste(selectedPeople$text, collapse=", "))
}
})
}
)
}
|
qrsgld = function(p,lambda){
out = .Fortran(.F_RGldx,
y=as.double(p), as.double(lambda),n=as.integer(length(p)))
if(out$n<0) stop("Invalid RS-GLD parameters.")
out$y
}
prsgld = function(x,lambda){
out = .Fortran(.F_RGldFx,
y=as.double(x), as.double(lambda),n=as.integer(length(x)))
if(out$n<0) stop("Invalid RS-GLD parameters.")
out$y
}
drsgld = function(x,lambda){
out = .Fortran(.F_RGldfx,
y=as.double(x), as.double(lambda),n=as.integer(length(x)))
if(out$n<0) stop("Invalid RS-GLD parameters.")
out$y
}
rrsgld = function(n, lambda){
qrsgld(runif(n),lambda)
}
.lecount <- function(x,y) sum(y<=x)
.bincount <- function(x){
x=x[!is.na(x)]; s = sd(x); mu = mean(x);
n=length(x)
x0 = seq(mu-5.7*s,mu+6*s,by=0.3*s)
ps = apply(matrix(x0,ncol=1),1,FUN=.lecount,y=x)
cts = diff(ps)
bounds = NULL; counts=NULL;
k = length(cts)
for(i in 1:(k-1)){
if(cts[i]>=5){
bounds = c(bounds,x0[i])
counts = c(counts,cts[i])
ul = x0[i+1]
}else{
cts[i+1] = cts[i+1]+cts[i]
}
}
m = n - sum(counts)
if(m>5){
bounds = c(bounds,ul)
counts = c(counts,m)
}else{
counts[length(counts)] = counts[length(counts)]+m
}
list(x=bounds,y=counts);
}
.mom <- function(x){
x = x[!is.na(x)]
s = sd(x);
m1 = mean(x);
m2 = mean((x-m1)^2)
m3 = mean((x-m1)^3)/s^3
m4 = mean((x-m1)^4)/s^4
c(m1,m2,m3,m4)
}
.mop <- function(x){
pctls = quantile(x,c(.10,.25,.50,.75,.90))
mp1 = pctls[3];
mp2 = pctls[5]-pctls[1];
mp3 = (pctls[3]-pctls[1])/(pctls[5]-pctls[3]);
mp4 = (pctls[4]-pctls[2])/mp2;
as.numeric(c(mp1,mp2,mp3,mp4))
}
.lmom = function(x){
x = sort(x);
n = length(x);
b0 = mean(x);
w1 = (0:(n-1))/(n-1);
b1 = mean(w1*x);
s2 = 2:n;
w2 = c(0,(s2-1)*(s2-2)/(n-1)/(n-2))
b2 = mean(w2*x);
s3 = 3:n;
w3 = c(0,0,(s3-1)*(s3-2)*(s3-3)/(n-1)/(n-2)/(n-3));
b3 = mean(w3*x);
s4 = 4:n;
w4 = c(0,0,0,(s4-1)*(s4-2)*(s4-3)*(s4-4)/(n-1)/(n-2)/(n-3)/(n-4));
b4 = mean(w4*x);
p10=1;p20=-1;p30=1;p40=-1;p50=1;
p21=2; p31=-6;p41=12;p51=-20;
p32=6;p42=-30;p52=90;
p43 = 20;p53=-140;p54=70;
l1=p10*b0;
l2=p20*b0+p21*b1;
l3=p30*b0+p31*b1+p32*b2;
l4=p40*b0+p41*b1+p42*b2+p43*b3;
return(c(l1,l2,l3,l4));
}
fit.gld <- function(x,method='LMoM'){
name <- deparse(substitute(x))
if(!is.numeric(x)) stop("\n\n\t 'x' must be numeric values!\n\n\n");
x = x[!is.na(x)]; n = length(x);
if(n < 6) stop("\n\n\t Sample size is too small!\n\n\n");
if(n < 30) warning("\n Sample size might be too small to fit moment matching GLD!\n");
s = sd(x); gpoints = seq(min(x)-s,max(x)+s,length=100);
out = .bincount(x); os = out$y; nbins = length(out$y); xbin = out$x
if(nbins<3) stop("Data has less than 3 bins. Double-check the raw data.")
method = match.arg(tolower(method), c("mom","mop","lmom"))
out = switch(method,
mom = .Fortran(.F_GLDMoM, b=as.double(.mom(x)), chisq = as.double(0.),
as.integer(c(n,nbins)),as.double(os),as.double(xbin)),
mop = .Fortran(.F_GLDMoP, b=as.double(.mop(x)), chisq = as.double(0.),
as.integer(c(n,nbins)),as.double(os),as.double(xbin)),
lmom = .Fortran(.F_GLDLMoM, b=as.double(.lmom(x)), chisq = as.double(0.),
as.integer(c(n,nbins)),as.double(os),as.double(xbin))
)
DF = nbins - 5
D2 = out$chisq
pv = ifelse(DF>0,pchisq(D2,DF,lower.tail=FALSE),NA)
y = drsgld(gpoints,out$b)
sele = y>0
return(structure(list(x = gpoints[sele],y = y[sele],n = n,para=out$b,
chisq = out$chisq, p.value=pv,method=method,
call = match.call(), data.name = name),
class = "gld"))
}
print.gld <- function (x, digits = NULL, ...)
{
tmp=NULL;k=length(x$para)
for(i in 1:(k-1))
tmp = paste(tmp,formatC(x$para[i]),",",sep='')
tmp = paste(tmp,formatC(x$para[k]),sep='')
cat("\nCall:\n\t", deparse(x$call), "\n\nData: ", x$data.name,
" (", x$n, " obs.);", "\tMethod: = ", x$method,"\n",
"Parameters: \t'para' = (",tmp,
")", sep = "")
cat("\nGoodness-of-fit: \n\tChi-Square = ",x$chisq,
",\tp-value = ", format(x$p.value,6), "\n",sep = "")
print(summary(as.data.frame(x[c("x", "y")])), digits = digits,
...)
invisible(x)
}
plot.gld <-
function (x, main = NULL, xlab = NULL, ylab = "Density", type = "l",
zero.line = TRUE, ...)
{
tmp=NULL;k=length(x$para)
for(i in 1:(k-1))
tmp = paste(tmp,formatC(x$para[i]),",",sep='')
tmp = paste(tmp,formatC(x$para[k]),sep='')
if (is.null(xlab))
xlab <- paste("N =", x$n, " Parameters =(",tmp,")")
if (is.null(main))
main <- deparse(x$call)
sele = x$y>0
plot.default(x$x[sele],x$y[sele], type = type,
main = main, xlab = xlab, ylab = ylab, ...)
if (zero.line)
abline(h = 0, lwd = 0.1, col = "gray")
invisible(NULL)
}
lines.gld <-
function (x, zero.line = TRUE, ...)
{
sele = x$y>0
lines.default(x$x[sele],x$y[sele], ...)
invisible(NULL)
}
|
koyckDlm <- function(x , y , intercept) UseMethod("koyckDlm")
|
library("matrixStats")
rowDiffs_R <- function(x, lag = 1L, differences = 1L, ..., useNames = NA) {
ncol2 <- ncol(x) - lag * differences
if (ncol2 <= 0) {
y <- matrix(x[integer(0L)], nrow = nrow(x), ncol = 0L)
if (isTRUE(useNames) && !is.null(rownames(x))) rownames(y) <- rownames(x)
return(y)
}
suppressWarnings({
y <- apply(x, MARGIN = 1L, FUN = diff, lag = lag, differences = differences)
})
y <- t(y)
dim(y) <- c(nrow(x), ncol2)
if (isTRUE(useNames) && !is.null(dimnames(x))) {
colnames <- colnames(x)
if (!is.null(colnames)) {
len <- length(colnames)
colnames <- colnames[(len - ncol2 + 1):len]
}
dimnames(y) <- list(rownames(x), colnames)
}
else dimnames(y) <- NULL
y
}
source("utils/validateIndicesFramework.R")
x <- matrix(runif(6 * 6, min = -6, max = 6), nrow = 6, ncol = 6)
storage.mode(x) <- "integer"
dimnames <- list(letters[1:6], LETTERS[1:6])
for (setDimnames in c(TRUE, FALSE)) {
if (setDimnames) dimnames(x) <- dimnames
else dimnames(x) <- NULL
for (rows in index_cases) {
for (cols in index_cases) {
for (lag in 1:2) {
for (differences in 1:3) {
for (useNames in c(NA, TRUE, FALSE)) {
validateIndicesTestMatrix(x, rows, cols,
ftest = rowDiffs, fsure = rowDiffs_R,
lag = lag, differences = differences, useNames = useNames)
validateIndicesTestMatrix(x, rows, cols,
ftest = function(x, rows, cols, ..., useNames) {
t(colDiffs(t(x), rows = cols, cols = rows, ..., useNames = useNames))
}, fsure = rowDiffs_R,
lag = lag, differences = differences, useNames = useNames)
}
}
}
}
}
}
|
NULL
"-.ggplot" <- function(e1, e2) {
if (should_autowrap(e2)) e2 <- wrap_elements(full = e2)
if (!is.ggplot(e2)) stop("Only knows how to fold ggplot objects together", call. = FALSE)
patchwork <- new_patchwork()
if (is_patchwork(e2)) {
plot <- plot_filler()
patchwork$plots <- list(e1, e2)
} else {
plot <- e2
patchwork$plots <- list(e1)
}
add_patches(plot, patchwork)
}
"/.ggplot" <- function(e1, e2) {
if (should_autowrap(e2)) e2 <- wrap_elements(full = e2)
if (!is_patchwork(e1)) {
e1 + e2 + plot_layout(ncol = 1)
} else if (!is.null(e1$patches$layout$ncol) && e1$patches$layout$ncol == 1) {
e1 + e2
} else {
e1 - e2 + plot_layout(ncol = 1)
}
}
"|.ggplot" <- function(e1, e2) {
if (should_autowrap(e2)) e2 <- wrap_elements(full = e2)
if (!is_patchwork(e1)) {
e1 + e2 + plot_layout(nrow = 1)
} else if (!is.null(e1$patches$layout$nrow) && e1$patches$layout$nrow == 1) {
e1 + e2
} else {
e1 - e2 + plot_layout(nrow = 1)
}
}
"*.gg" <- function(e1, e2) {
if (is_patchwork(e1)) {
e1$patches$plots <- lapply(e1$patches$plots, function(p) {
if (!is_patchwork(p)) p <- p + e2
p
})
}
e1 + e2
}
"&.gg" <- function(e1, e2) {
if (is_patchwork(e1)) {
if (is.theme(e2)) {
e1$patches$annotation$theme <- e1$patches$annotation$theme + e2
}
e1$patches$plots <- lapply(e1$patches$plots, function(p) {
if (is_patchwork(p)) {
p <- p & e2
} else {
p <- p + e2
}
p
})
}
e1 + e2
}
|
enforce_form = function(file, ...) {
file = checkimg(file)
stopifnot(length(file) == 1)
form = getForms(file = file, ...)
both_zero = form$qform_code == 0 & form$sform_code == 0
if (any(both_zero)) {
us = !any(form$ssor == "UU")
fs = !any(form$sqor == "UU")
if (fs && us) {
stop("both qform and sform are set")
}
if (!fs && !us) {
stop("neither qform or sform has orientation")
}
if (fs && !us) {
if (all(form$qform == 0)) {
stop("qform selected but all zero")
}
code = "qform_code"
}
if (!fs && us) {
if (all(form$sform == 0)) {
stop("sform selected but all zero")
}
code = "sform_code"
}
stopifnot(all(code %in% c("qform_code", "sform_code")))
img = readnii(file)
slot(img, code) = 1
pixdim(img)[1] = 1
file = tempimg(img)
}
return(file)
}
|
context("Test ug_delta")
library(hBayesDM)
test_that("Test ug_delta", {
skip_on_cran()
expect_output(ug_delta(
data = "example", niter = 10, nwarmup = 5, nchain = 1, ncore = 1))
})
|
test_that("acc_multivariate_outlier works with 3 args", {
skip_if_translated()
load(system.file("extdata/meta_data.RData", package = "dataquieR"), envir =
environment())
load(system.file("extdata/study_data.RData", package = "dataquieR"), envir =
environment())
expect_error(
res1 <-
acc_multivariate_outlier(
study_data = study_data, meta_data = meta_data),
regexp =
"argument .+resp_vars.+ is missing, with no default",
perl = TRUE
)
expect_error(
res1 <-
acc_multivariate_outlier(
resp_vars = "v00014",
study_data = study_data, meta_data = meta_data),
regexp =
"Need at least two variables for multivariate outliers.",
perl = TRUE
)
expect_warning(
res1 <-
acc_multivariate_outlier(resp_vars = c("v00014", "v00006"),
study_data = study_data, meta_data = meta_data),
regexp =
sprintf(
"(%s|%s)",
paste("As no ID-var has been specified the rownumbers will be used."),
paste("Due to missing values in v00014, v00006 or dq_id N=602",
"observations were excluded.")
),
perl = TRUE,
all = TRUE
)
expect_true(all(c("FlaggedStudyData",
"SummaryTable",
"SummaryPlot") %in% names(res1)))
expect_lt(
suppressWarnings(abs(sum(as.numeric(
as.matrix(res1$FlaggedStudyData)),
na.rm = TRUE) - 4493047)), 0.5
)
expect_equal(
suppressWarnings(abs(sum(as.numeric(
as.matrix(res1$SummaryTable)),
na.rm = TRUE))), 182
)
})
test_that("acc_multivariate_outlier works with label_col", {
load(system.file("extdata/meta_data.RData", package = "dataquieR"), envir =
environment())
load(system.file("extdata/study_data.RData", package = "dataquieR"), envir =
environment())
expect_error(
res1 <-
acc_multivariate_outlier(
label_col = LABEL,
study_data = study_data, meta_data = meta_data),
regexp =
"argument .+resp_vars.+ is missing, with no default",
perl = TRUE
)
expect_error(
res1 <-
acc_multivariate_outlier(
label_col = LABEL,
resp_vars = "CRP_0",
study_data = study_data, meta_data = meta_data),
regexp =
"Need at least two variables for multivariate outliers.",
perl = TRUE
)
expect_warning(
res1 <-
acc_multivariate_outlier(resp_vars = c("CRP_0", "GLOBAL_HEALTH_VAS_0"),
label_col = LABEL,
study_data = study_data, meta_data = meta_data),
regexp =
sprintf(
"(%s|%s)",
paste("As no ID-var has been specified the rownumbers will be used."),
paste("Due to missing values in CRP_0, GLOBAL_HEALTH_VAS_0 or",
"dq_id N=602 observations were excluded.")
),
perl = TRUE,
all = TRUE
)
expect_true(all(c("FlaggedStudyData",
"SummaryTable",
"SummaryPlot") %in% names(res1)))
expect_lt(
suppressWarnings(abs(sum(as.numeric(
as.matrix(res1$FlaggedStudyData)),
na.rm = TRUE) - 4493047)), 0.5
)
expect_equal(
suppressWarnings(abs(sum(as.numeric(
as.matrix(res1$SummaryTable)),
na.rm = TRUE))), 182
)
skip_on_cran()
skip_if_not_installed("vdiffr")
skip_if_not(capabilities()["long.double"])
vdiffr::expect_doppelganger(
"acc_mv_outlierCRP0GLOBHEAVA0",
res1$SummaryPlot)
})
|
xsecmanyfoc <-
function(MEK, theta=NULL, focsiz=0.5, foccol=NULL, UP=TRUE, focstyle=1, LEG = FALSE, DOBAR=FALSE)
{
if(missing(theta)) { theta = NULL }
if(missing(UP)) UP = TRUE
if(missing(foccol)) foccol=NULL
if(missing(LEG)) LEG = FALSE
if(missing(DOBAR)) DOBAR=FALSE
if(missing(focsiz)) { focsiz = 0.04 }
if(length(MEK$Elat)<1 | (length(MEK$Elon)<1))
{
MEK$Elat = rep(NA, length(MEK$lat))
MEK$Elon = rep(NA, length(MEK$lat))
}
XYplode = list(x=MEK$Elat, y=MEK$Elon)
tem1 = list(x=MEK$x, y=MEK$y)
tem2 = tem1
ww = which(!is.na(MEK$x))
if( length(ww) < 1 ) { return() }
for(IW in 1:length(ww))
{
i = ww[IW]
lind= foc.icolor(MEK$rake1[i])
focal.col = foc.color(lind, pal=1)
a1 = SDRfoc(MEK$str1[i], MEK$dip1[i],MEK$rake1[i] , u=UP, ALIM=c(-1,-1, +1, +1), PLOT=FALSE)
if(!is.null(theta))
{
b1 = Rotfocphi(theta, a1$M$uaz, a1$M$ud, a1$M$vaz,
a1$M$vd, a1$M$az1, a1$M$d1, a1$M$az2, a1$M$d2,
a1$M$paz, a1$M$pd, a1$M$taz, a1$M$td)
FMEC=list(UP=a1$UP, LIM=a1$LIM, P=b1$P, az1=b1$A2$az-90 ,
dip1=b1$A2$dip , az2=b1$A1$az-90, dip2=b1$A1$dip )
FMEC$sense = 0
pax = focpoint(FMEC$P$az, FMEC$P$dip, lab="P", UP=FMEC$UP, PLOT=FALSE)
PLS = polyfoc(FMEC$az1, FMEC$dip1, FMEC$az2, FMEC$dip2, UP=FMEC$UP, PLOT = FALSE)
kin = splancs::inout(cbind(pax$x, pax$y) ,cbind(PLS$Px, y =PLS$Py), bound=TRUE)
if(kin==0) FMEC$sense = 1
ang2 = GetRakeSense(b1$U$az, b1$U$dip, b1$V$az, b1$V$dip ,b1$P$az, b1$P$dip , b1$T$az, b1$T$dip )
MEC = GetRake(FMEC$az1, FMEC$dip1, FMEC$az2, FMEC$dip2, ang2)
MEC$sense = ang2
MEC$UP = TRUE
MEC = c(MEC, b1)
}
else
{
MEC = a1
}
if(focstyle==1)
{
justfocXY(MEC, x=tem1$x[i], y= tem1$y[i], focsiz=focsiz,
fcol =focal.col , fcolback = "white", xpd = TRUE)
}
if(focstyle==2)
{
nipXY(MEC, x=tem1$x[i], y= tem1$y[i], focsiz =focsiz,
fcol =focal.col, nipcol="black", cex=.4)
}
if(focstyle==4)
{
PTXY2( tem1$x[i], tem1$y[i] , MEC ,focsiz, col=focal.col, pt=0, lwd=2 )
}
if(focstyle==5)
{
PTXY2( tem1$x[i], tem1$y[i] , MEC ,focsiz, col=focal.col, pt=1, lwd=2 )
}
if(focstyle==6)
{
PTXY2( tem1$x[i], tem1$y[i] , MEC ,focsiz, col=focal.col, pt=2, lwd=2 )
}
}
if(LEG)
{
fleg = 1:7
flegc = foc.color(fleg, pal=1)
flab = focleg(fleg)
legend("topleft", legend=flab, col=flegc, pch=19, bg="white" )
}
}
|
bq_test_project <- function() {
if (is_testing() && !bq_authable()) {
testthat::skip("No BigQuery access credentials available")
}
env <- Sys.getenv("BIGQUERY_TEST_PROJECT")
if (!identical(env, "")) {
return(env)
}
if (is_testing()) {
testthat::skip("BIGQUERY_TEST_PROJECT not set")
}
stop(
"To run bigrquery tests you must have BIGQUERY_TEST_PROJECT envvar set ",
"to name of project which has billing set up and to which you have ",
"write access",
call. = FALSE
)
}
bq_test_init <- function(name = "basedata") {
proj <- bq_test_project()
basedata <- bq_dataset(proj, name)
if (!bq_dataset_exists(basedata)) {
bq_dataset_create(basedata)
}
bq_mtcars <- bq_table(basedata, "mtcars")
if (!bq_table_exists(bq_mtcars)) {
bq_table_upload(bq_mtcars, values = datasets::mtcars)
}
}
bq_test_dataset <- function(name = random_name(), location = "US") {
ds <- bq_dataset(bq_test_project(), name)
bq_dataset_create(ds, location = location)
env <- new.env()
reg.finalizer(
env,
function(e) bq_dataset_delete(ds, delete_contents = TRUE),
onexit = TRUE
)
attr(ds, "env") <- env
ds
}
bq_testable <- function() {
bq_authable() && !identical(Sys.getenv("BIGQUERY_TEST_PROJECT"), "")
}
bq_authable <- function() {
bq_has_token() || (interactive() && !is_testing())
}
gs_test_bucket <- function() {
env <- Sys.getenv("BIGQUERY_TEST_BUCKET")
if (!identical(env, "")) {
return(env)
}
if (is_testing()) {
testthat::skip("BIGQUERY_TEST_BUCKET not set")
}
stop(
"To run bigrquery extract/load tests you must have BIGQUERY_TEST_BUCKET set ",
"to name of the bucket where `bq_test_project()` has write acess",
call. = FALSE
)
}
gs_test_object <- function(name = random_name()) {
gs_object(gs_test_bucket(), name)
}
random_name <- function(n = 10) {
paste0("TESTING_", paste(sample(letters, n, replace = TRUE), collapse = ""))
}
is_testing <- function() identical(Sys.getenv("TESTTHAT"), "true")
skip_if_no_auth <- function() {
testthat::skip_if_not(bq_has_token(), "Authentication not available")
}
|
aoplot <- function(x, ...) UseMethod("aoplot")
|
lrtestm <- function(x, mu, lam, cvar, vare, th0, th1, vari, nfac){
nume0 <- 0
nume1 <- 0
deno0 <- 0
deno1 <- 0
ni <- size(x)[2]
for (j in 1:ni){
if (nfac == 2){
lamtmp <- c(lam[j,1],lam[j,2])
term01 <- (x[j] - mu[j] - (lam[j,1] * th0[1]) - (lam[j,2] * th0[2]))^2
term11 <- (x[j] - mu[j] - (lam[j,1] * th1[1]) - (lam[j,2] * th1[2]))^2
}
if (nfac == 3){
lamtmp <- c(lam[j,1],lam[j,2],lam[j,3])
term01 <- (x[j] - mu[j] - (lam[j,1] * th0[1]) - (lam[j,2] * th0[2]) - (lam[j,3] * th0[3]))^2
term11 <- (x[j] - mu[j] - (lam[j,1] * th1[1]) - (lam[j,2] * th1[2]) - (lam[j,3] * th1[3]))^2
}
if (nfac == 4){
lamtmp <- c(lam[j,1],lam[j,2],lam[j,3],lam[j,4])
term01 <- (x[j] - mu[j] - (lam[j,1] * th0[1]) - (lam[j,2] * th0[2]) - (lam[j,3] * th0[3]) - (lam[j,4] * th0[4]))^2
term11 <- (x[j] - mu[j] - (lam[j,1] * th1[1]) - (lam[j,2] * th1[2]) - (lam[j,3] * th1[3]) - (lam[j,4] * th1[4]))^2
}
rlamtmp <- lamtmp %*% transpose(lamtmp)
term02 <- rlamtmp * (cvar + vare[j])
term12 <- rlamtmp * (vari + vare[j])
t0 <- term01 / term02
t1 <- term11 / term12
nume0 <- nume0 + t0
nume1 <- nume1 + t1
term03 <- log(cvar + vare[j])
term13 <- log(vari + vare[j])
deno0 <- deno0 + term03
deno1 <- deno1 + term13
}
provi <- nume0 + deno0 - nume1 - deno1
if (provi < 0){
chi <- 0.01
}
else if (provi > 15){
chi <- 15
}
else {
chi <- provi
}
LR <- exp(-2 * chi)
OUT <- list("LR"=LR, "chi"=chi)
return(OUT)
}
|
"thyroids"
|
class_summary<-function(data){
classes_url <- RCurl::getURL("https://gitlab.com/Algorithm379/databases/-/raw/main/HS_protein_classes_curated.csv")
classes <- utils::read.csv(text = classes_url)
data$"Class"<-ifelse(data$"Symbol"%in%classes$"Gene",classes$"Class","NA")
df<-table(data$"Class")
df<-as.data.frame(sort(df,decreasing = TRUE))
colnames(df)<-c("Class","Freq")
print(df)
Class<-df$"Class"
Freq<-df$"Freq"
p1<-ggplot2::ggplot(df)+ggplot2::geom_col(ggplot2::aes(x=Class,y=Freq, fill=Class))+ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90, vjust = 0.5, hjust=1))
methods::show(p1)
}
|
ConfidenceInterval <- function (n, mean_azimuth, mean_module, von_mises)
{
z = 1.96
vm = 1/(sqrt(n * von_mises * mean_module))
ci1 = mean_azimuth + ToSexagesimal(asin(z * vm))
ci2 = mean_azimuth - ToSexagesimal(asin(z * vm))
return(c(ci1, ci2))
}
|
rmodel<-function(formula,weights,X)
{
cl <- match.call()
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "weights"), names(mf), 0)
mf <- mf[c(1, m)]
mf$drop.unused.levels <- TRUE
mf[[1]] <- as.name("model.frame")
mf <- eval(mf, parent.frame())
mt <- attr(mf, "terms")
y <- model.response(mf, "numeric")
w <- as.vector(model.weights(mf))
x <- model.matrix(mt, mf, contrasts)
prob<-glm(y~x,family="binomial",weights=w)$fitted.values
result<-cbind.data.frame(X,prob)
names(result)<-c(names(X),"prob_resp")
result
}
|
mbeta <- function(order, shape1, shape2)
.External(C_actuar_do_dpq, "mbeta", order, shape1, shape2, FALSE)
levbeta <- function(limit, shape1, shape2, order = 1)
.External(C_actuar_do_dpq, "levbeta", limit, shape1, shape2, order, FALSE)
|
splineDesign <-
function(knots, x, ord = 4, derivs = 0L, outer.ok = FALSE,
sparse = FALSE)
{
if((nk <- length(knots <- as.numeric(knots))) <= 0)
stop("must have at least 'ord' knots")
if(is.unsorted(knots)) knots <- sort.int(knots)
x <- as.numeric(x)
nx <- length(x)
if(length(derivs) > nx)
stop("length of 'derivs' is larger than length of 'x'")
if(length(derivs) < 1L) stop("empty 'derivs'")
ord <- as.integer(ord)
if(ord > nk || ord < 1)
stop("'ord' must be positive integer, at most the number of knots")
if(!outer.ok && nk < 2*ord-1)
stop(gettextf("need at least %s (=%d) knots",
"2*ord -1", 2*ord -1),
domain = NA)
o1 <- ord - 1L
if(need.outer <- any(x < knots[ord] | knots[nk - o1] < x)) {
if(outer.ok) {
in.x <- knots[1L] <= x & x <= knots[nk]
if((x.out <- !all(in.x))) {
x <- x[in.x]
nnx <- length(x)
}
dkn <- diff(knots)[(nk-1L):1]
knots <- knots[c(rep.int(1L, o1), seq_len(nk),
rep.int(nk, max(0L, ord - match(TRUE, dkn > 0))))]
} else
stop(gettextf("the 'x' data must be in the range %g to %g unless you set '%s'",
knots[ord], knots[nk - o1], "outer.ok = TRUE"),
domain = NA)
}
temp <- .Call(C_spline_basis, knots, ord, x, derivs)
ncoef <- nk - ord
ii <- if(need.outer && x.out) {
rep.int((1L:nx)[in.x], rep.int(ord, nnx))
} else rep.int(1L:nx, rep.int(ord, nx))
jj <- c(outer(1L:ord, attr(temp, "Offsets"), "+"))
if(sparse) {
if(is.null(tryCatch(loadNamespace("Matrix"), error = function(e)NULL)))
stop(gettextf("%s needs package 'Matrix' correctly installed",
"splineDesign(*, sparse=TRUE)"),
domain = NA)
if(need.outer) {
jj <- jj - o1 - 1L
ok <- 0 <= jj & jj < ncoef
methods::as(methods::new("dgTMatrix", i = ii[ok] - 1L, j = jj[ok],
x = as.double(temp[ok]),
Dim = c(nx, ncoef)), "CsparseMatrix")
}
else
methods::as(methods::new("dgTMatrix", i = ii - 1L, j = jj - 1L,
x = as.double(temp),
Dim = c(nx, ncoef)), "CsparseMatrix")
} else {
design <- matrix(double(nx * ncoef), nx, ncoef)
if(need.outer) {
jj <- jj - o1
ok <- 1 <= jj & jj <= ncoef
design[cbind(ii, jj)[ok , , drop=FALSE]] <- temp[ok]
}
else
design[cbind(ii, jj)] <- temp
design
}
}
interpSpline <-
function(obj1, obj2, bSpline = FALSE, period = NULL, na.action = na.fail, sparse = FALSE)
UseMethod("interpSpline")
interpSpline.default <-
function(obj1, obj2, bSpline = FALSE, period = NULL, na.action = na.fail, sparse = FALSE)
{
ord <- 4L
deg <- ord - 1L
frm <- na.action(data.frame(x = as.numeric(obj1), y = as.numeric(obj2)))
frm <- frm[order(frm$x), ]
ndat <- nrow(frm)
x <- frm$x
if(anyDuplicated(x))
stop("values of 'x' must be distinct")
knots <- c(x[1L:deg] + x[1L] - x[ord], x,
x[ndat + (1L:deg) - deg] + x[ndat] - x[ndat - deg])
derivs <- c(2, integer(ndat), 2)
x <- c(x[1L], x, x[ndat])
des <- splineDesign(knots, x, ord, derivs, sparse=sparse)
y <- c(0, frm$y, 0)
coeff <- if(sparse) Matrix::solve(des, Matrix::..2dge(y), sparse=TRUE)
else solve(des, y)
value <- structure(list(knots = knots, coefficients = coeff, order = ord),
formula = do.call(`~`, list(substitute(obj2), substitute(obj1))),
class = c("nbSpline", "bSpline", "spline"))
if (bSpline) return(value)
value <- polySpline(value)
coeff <- coef(value)
coeff[ , 1] <- frm$y
coeff[1, deg] <- coeff[nrow(coeff), deg] <- 0
value$coefficients <- coeff
value
}
interpSpline.formula <-
function(obj1, obj2, bSpline = FALSE, period = NULL, na.action = na.fail, sparse = FALSE)
{
form <- as.formula(obj1)
if (length(form) != 3)
stop("'formula' must be of the form \"y ~ x\"")
local <- if (missing(obj2)) sys.parent(1) else as.data.frame(obj2)
value <- interpSpline(as.numeric(eval(form[[3L]], local)),
as.numeric(eval(form[[2L]], local)),
bSpline = bSpline, period = period,
na.action = na.action, sparse = sparse)
attr(value, "formula") <- form
value
}
periodicSpline <-
function(obj1, obj2, knots, period = 2 * pi, ord = 4)
UseMethod("periodicSpline")
periodicSpline.default <-
function(obj1, obj2, knots, period = 2 * pi, ord = 4)
{
x <- as.numeric(obj1)
y <- as.numeric(obj2)
lenx <- length(x)
if(lenx != length(y))
stop("lengths of 'x' and 'y' must match")
ind <- order(x)
x <- x[ind]
if(length(unique(x)) != lenx)
stop("values of 'x' must be distinct")
if(any((x[-1L] - x[ - lenx]) <= 0))
stop("values of 'x' must be strictly increasing")
if(ord < 2) stop("'ord' must be >= 2")
o1 <- ord - 1
if(!missing(knots)) {
period <- knots[length(knots) - o1] - knots[1L]
}
else {
knots <- c(x[(lenx - (ord - 2)):lenx] - period, x, x[1L:ord] + period)
}
if((x[lenx] - x[1L]) >= period)
stop("the range of 'x' values exceeds one period")
y <- y[ind]
coeff.mat <- splineDesign(knots, x, ord)
i1 <- seq_len(o1)
sys.mat <- coeff.mat[, (1L:lenx)]
sys.mat[, i1] <- sys.mat[, i1] + coeff.mat[, lenx + i1]
coeff <- qr.coef(qr(sys.mat), y)
coeff <- c(coeff, coeff[i1])
structure(list(knots = knots, coefficients = coeff,
order = ord, period = period),
formula = do.call("~", as.list(sys.call())[3:2]),
class = c("pbSpline", "bSpline", "spline"))
}
periodicSpline.formula <- function(obj1, obj2, knots, period = 2 * pi, ord = 4)
{
form <- as.formula(obj1)
if (length(form) != 3)
stop("'formula' must be of the form \"y ~ x\"")
local <- if (missing(obj2)) sys.parent(1) else as.data.frame(obj2)
structure(periodicSpline.default(as.numeric(eval(form[[3L]], local)),
as.numeric(eval(form[[2L]], local)),
knots = knots, period = period, ord = ord),
formula = form)
}
polySpline <-
function(object, ...) UseMethod("polySpline")
polySpline.polySpline <- function(object, ...) object
as.polySpline <-
function(object, ...) polySpline(object, ...)
polySpline.bSpline <- function(object, ...)
{
ord <- splineOrder(object)
knots <- splineKnots(object)
if(is.unsorted(knots))
stop("knot positions must be non-decreasing")
knots <- knots[ord:(length(knots) + 1L - ord)]
coeff <- array(0, c(length(knots), ord))
coeff[, 1] <- asVector(predict(object, knots))
if(ord > 1) {
for(i in 2:ord) {
coeff[, i] <- asVector(predict(object, knots, deriv = i - 1))/
prod(1L:(i - 1))
}
}
structure(list(knots = knots, coefficients = coeff),
formula = attr(object, "formula"),
class = c("polySpline", "spline"))
}
polySpline.nbSpline <- function(object, ...)
{
structure(NextMethod("polySpline"),
class = c("npolySpline", "polySpline", "spline"))
}
polySpline.pbSpline <- function(object, ...)
{
value <- NextMethod("polySpline")
value[["period"]] <- object$period
class(value) <- c("ppolySpline", "polySpline", "spline")
value
}
splineKnots <-
function(object) UseMethod("splineKnots")
splineKnots.spline <- function(object) object$knots
splineOrder <-
function(object) UseMethod("splineOrder")
splineOrder.bSpline <- function(object) object$order
splineOrder.polySpline <- function(object) ncol(coef(object))
xyVector <-
function(x, y)
{
x <- as.vector(x)
y <- as.vector(y)
if(length(x) != length(y))
stop("lengths of 'x' and 'y' must be the same")
structure(list(x = x, y = y), class = "xyVector")
}
asVector <-
function(object) UseMethod("asVector")
asVector.xyVector <- function(object) object$y
as.data.frame.xyVector <- function(x, ...) data.frame(x = x$x, y = x$y)
plot.xyVector <- function(x, ...)
{
plot(x = x$x, y = x$y, ...)
}
predict.polySpline <- function(object, x, nseg = 50, deriv = 0, ...)
{
knots <- splineKnots(object)
coeff <- coef(object)
cdim <- dim(coeff)
ord <- cdim[2L]
if(missing(x))
x <- seq.int(knots[1L], knots[cdim[1L]], length.out = nseg + 1)
i <- as.numeric(cut(x, knots))
i[x == knots[1L]] <- 1
delx <- x - knots[i]
deriv <- as.integer(deriv)[1L]
if(deriv < 0 || deriv >= ord)
stop(gettextf("'deriv' must be between 0 and %d", ord - 1),
domain = NA)
while(deriv > 0) {
ord <- ord - 1
coeff <- t(t(coeff[, -1]) * (1L:ord))
deriv <- deriv - 1
}
y <- coeff[i, ord]
if(ord > 1) {
for(j in (ord - 1):1)
y <- y * delx + coeff[i, j]
}
xyVector(x = x, y = y)
}
predict.bSpline <- function(object, x, nseg = 50, deriv = 0, ...)
{
knots <- splineKnots(object)
if(is.unsorted(knots))
stop("knot positions must be non-decreasing")
ord <- splineOrder(object)
if(deriv < 0 || deriv >= ord)
stop(gettextf("'deriv' must be between 0 and %d", ord - 1),
domain = NA)
ncoeff <- length(coeff <- coef(object))
if(missing(x)) {
x <- seq.int(knots[ord], knots[ncoeff + 1], length.out = nseg + 1)
accept <- TRUE
} else accept <- knots[ord] <= x & x <= knots[ncoeff + 1]
y <- x
y[!accept] <- NA
y[accept] <- .Call(C_spline_value, knots, coeff, ord, x[accept], deriv)
xyVector(x = x, y = y)
}
predict.nbSpline <- function(object, x, nseg = 50, deriv = 0, ...)
{
value <- NextMethod("predict")
if(!any(is.na(value$y)))
return(value)
x <- value$x
y <- value$y
knots <- splineKnots(object)
ord <- splineOrder(object)
ncoeff <- length(coef(object))
bKn <- knots[c(ord,ncoeff + 1)]
coeff <- array(0, c(2L, ord))
coeff[,1] <- asVector(predict(object, bKn))
coeff[,2] <- asVector(predict(object, bKn, deriv = 1))
deriv <- as.integer(deriv)
while(deriv) {
ord <- ord - 1
coeff <- t(t(coeff[, -1]) * (1L:ord))
deriv <- deriv - 1
}
nc <- ncol(coeff)
if(any(which <- (x < bKn[1L]) & is.na(y)))
y[which] <- if(nc==0) 0 else if(nc==1) coeff[1, 1]
else coeff[1, 1] + coeff[1, 2] * (x[which] - bKn[1L])
if(any(which <- (x > bKn[2L]) & is.na(y)))
y[which] <- if(nc==0) 0 else if(nc==1) coeff[1, 1]
else coeff[2, 1] + coeff[2, 2] * (x[which] - bKn[2L])
xyVector(x = x, y = y)
}
predict.pbSpline <- function(object, x, nseg = 50, deriv = 0, ...)
{
knots <- splineKnots(object)
ord <- splineOrder(object)
period <- object$period
ncoeff <- length(coef(object))
if(missing(x))
x <- seq.int(knots[ord], knots[ord] + period, length.out = nseg + 1)
x.original <- x
if(any(ind <- x < knots[ord]))
x[ind] <- x[ind] + period * (1 + (knots[ord] - x[ind]) %/% period)
if(any(ind <- x > knots[ncoeff + 1]))
x[ind] <- x[ind] - period * (1 + (x[ind] - knots[ncoeff +1]) %/% period)
xyVector(x = x.original,
y = .Call(C_spline_value, knots, coef(object), ord, x, deriv))
}
predict.npolySpline <- function(object, x, nseg = 50, deriv = 0, ...)
{
value <- NextMethod()
if(!any(is.na(value$y)))
return(value)
x <- value$x
y <- value$y
nk <- length(knots <- splineKnots(object))
coeff <- coef(object)[ - (2:(nk - 1)), ]
ord <- dim(coeff)[2L]
if(ord >= 3) coeff[, 3:ord] <- 0
deriv <- as.integer(deriv)
while(deriv) {
ord <- ord - 1
coeff <- t(t(coeff[, -1]) * (1L:ord))
deriv <- deriv - 1
}
nc <- ncol(coeff)
if(any(which <- (x < knots[1L]) & is.na(y)))
y[which] <- if(nc==0) 0 else if(nc==1) coeff[1, 1]
else coeff[1, 1] + coeff[1, 2] * (x[which] - knots[1L])
if(any(which <- (x > knots[nk]) & is.na(y)))
y[which] <- if(nc==0) 0 else if(nc==1) coeff[1, 1]
else coeff[2, 1] + coeff[2, 2] * (x[which] - knots[nk])
xyVector(x = x, y = y)
}
predict.ppolySpline <- function(object, x, nseg = 50, deriv = 0, ...)
{
knots <- splineKnots(object)
nknot <- length(knots)
period <- object$period
if(missing(x))
x <- seq.int(knots[1L], knots[1L] + period, length.out = nseg + 1)
x.original <- x
if(any(ind <- x < knots[1L]))
x[ind] <- x[ind] + period * (1 + (knots[1L] - x[ind]) %/% period)
if(any(ind <- x > knots[nknot]))
x[ind] <- x[ind] - period * (1 + (x[ind] - knots[nknot]) %/% period)
value <- NextMethod("predict")
value$x <- x.original
value
}
plot.spline <- function(x, ...)
{
args <- list(x = as.data.frame(predict(x)), type = "l")
if(length(form <- attr(x, "formula")) == 3) {
args <- c(args, list(xlab = deparse(form[[3L]]), ylab = deparse(form[[2L]])))
}
args <- c(list(...), args)
do.call("plot", args[unique(names(args))])
}
print.polySpline <- function(x, ...)
{
coeff <- coef(x)
dnames <- dimnames(coeff)
if (is.null(dnames[[2L]]))
dimnames(coeff) <-
list(format(splineKnots(x)),
c("constant", "linear", "quadratic", "cubic",
paste0(4:29, "th"))[1L:(dim(coeff)[2L])])
cat("polynomial representation of spline")
if (!is.null(form <- attr(x, "formula")))
cat(" for", deparse(as.vector(form)))
cat("\n")
print(coeff, ...)
invisible(x)
}
print.ppolySpline <- function(x, ...)
{
cat("periodic ")
value <- NextMethod("print")
cat("\nPeriod:", format(x[["period"]]), "\n")
value
}
print.bSpline <- function(x, ...)
{
value <- c(rep(NA, splineOrder(x)), coef(x))
names(value) <- format(splineKnots(x), digits = 5)
cat("bSpline representation of spline")
if (!is.null(form <- attr(x, "formula")))
cat(" for", deparse(as.vector(form)))
cat("\n")
print(value, ...)
invisible(x)
}
backSpline <- function(object) UseMethod("backSpline")
backSpline.npolySpline <- function(object)
{
knots <- splineKnots(object)
nk <- length(knots)
nkm1 <- nk - 1
kdiff <- diff(knots)
if(any(kdiff <= 0))
stop("knot positions must be strictly increasing")
coeff <- coef(object)
bknots <- coeff[, 1]
adiff <- diff(bknots)
if(all(adiff < 0))
revKnots <- TRUE
else if(all(adiff > 0))
revKnots <- FALSE
else
stop("spline must be monotone")
bcoeff <- array(0, dim(coeff))
bcoeff[, 1] <- knots
bcoeff[, 2] <- 1/coeff[, 2]
a <- array(c(adiff^2, 2 * adiff, adiff^3, 3 * adiff^2),
c(nkm1, 2L, 2L))
b <- array(c(kdiff - adiff * bcoeff[ - nk, 2L],
bcoeff[-1L, 2L] - bcoeff[ - nk, 2L]), c(nkm1, 2))
for(i in 1L:(nkm1))
bcoeff[i, 3L:4L] <- solve(a[i,, ], b[i, ])
bcoeff[nk, 2L:4L] <- NA
if(nk > 2L) {
bcoeff[1L, 4L] <- bcoeff[nkm1, 4L] <- 0
bcoeff[1L, 2L:3L] <- solve(array(c(adiff[1L], 1, adiff[1L]^2,
2 * adiff[1L]), c(2L, 2L)),
c(kdiff[1L], 1/coeff[2L, 2L]))
bcoeff[nkm1, 3L] <- (kdiff[nkm1] - adiff[nkm1] *
bcoeff[nkm1, 2L])/adiff[nkm1]^2
}
if(bcoeff[1L, 3L] > 0) {
bcoeff[1L, 3L] <- 0
bcoeff[1L, 2L] <- kdiff[1L]/adiff[1L]
}
if(bcoeff[nkm1, 3L] < 0) {
bcoeff[nkm1, 3L] <- 0
bcoeff[nkm1, 2L] <- kdiff[nkm1]/adiff[nkm1]
}
value <- if(!revKnots) list(knots = bknots, coefficients = bcoeff)
else {
ikn <- length(bknots):1L
list(knots = bknots[ikn], coefficients = bcoeff[ikn,])
}
attr(value, "formula") <- do.call("~", as.list(attr(object, "formula"))[3L:2L])
class(value) <- c("polySpline", "spline")
value
}
backSpline.nbSpline <- function(object) backSpline(polySpline(object))
|
modify_column_alignment <- function(x, columns, align = c("left", "right", "center")) {
updated_call_list <- c(x$call_list, list(modify_column_hide = match.call()))
align <- match.arg(align)
x <-
modify_table_styling(
x = x,
columns = {{ columns }},
align = align
)
x$call_list <- updated_call_list
x
}
|
NULL
SPCModellogregLikRatio <- function(formula,Delta=1){
SPCModelNonpar(
updates=function(xi,data){
xbeta <- predict.glm(xi,newdata=data)
response <- model.response( model.frame( formula,data=data))
Delta*response + log(1+exp(xbeta)) - log(1+exp(Delta+xbeta))
},
xiofP=function(P)
glm(formula,data=P,family=binomial("logit"))
)
}
SPCModellogregOE <- function(formula,Delta=0){
SPCModelNonpar(
updates=function(xi,data){
response <- model.response( model.frame( formula,data=data))
response - predict.glm(xi,newdata=data,type="response")-Delta/2
},
xiofP=function(P)
glm(formula,data=P,family=binomial("logit"))
)
}
|
defaultTimeseries <-
function(N,AC,Years,PD){
Psi=rnorm(Years)
PDcond1=pnorm((qnorm(PD)-sqrt(AC)*Psi)/sqrt(1-AC))
size_p=rep(N,Years)
D1=rbinom(Years,size_p,PDcond1)
return(D1)
}
|
"abweich.nair.fun" <-
function(matrix,c)
{
kap.mei <- matrix[,2]
sigma <- matrix[,3]
result1 <- c*sqrt(sigma)*kap.mei
result2 <- exp((c*sqrt(sigma))/log(kap.mei))
return(list(lin.dev=result1,log.dev=result2))
}
|
fem.mstep.par <- function(Y,U,T,model,method){
Y = as.matrix(Y)
n = nrow(Y)
p = ncol(Y)
K = ncol(T)
d = min(p-1,(K-1))
U = as.matrix(U)
mu = matrix(NA,K,d)
m = matrix(NA,K,p)
prop = rep(c(NA),1,K)
D = array(0,c(K,d,d))
b = rep(NA,K)
X = as.matrix(Y) %*% as.matrix(U)
test = 0
fun <- function(k){
nk = sum(T[,k])
if (nk ==0) stop("some classes become empty\n",call.=FALSE)
prop[k] = nk / n
mu[k,] = colSums((T[,k]*matrix(1,n,d))* X) / nk
m[k,] = colSums(T[,k]*matrix(1,n,p)* Y) / nk
YY = as.matrix(Y - t(m[k,]*matrix(1,p,n)))
if (nk < 1) denk = 1 else denk = (nk-1)
YYk = T[,k] * matrix(1,n,p) * YY
if (model %in% c('DkB','DB','AkjB','AkB','AjB','AB')){
TT = t(apply(T,1,"/",sqrt(colSums(T))))
W = (crossprod(YY) - crossprod(t(TT)%*%YY)) / n
}
if (model=='DkBk'){
D[k,(1:d),(1:d)] = crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk
bk = (sum(YYk*YY)/denk - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='DkB'){
D[k,(1:d),(1:d)] = crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk
bk = (sum(diag(W)) - sum(diag(crossprod(W%*%U,U)))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='DBk'){
D[k,(1:d),(1:d)] = crossprod(YY%*%U,YY%*%U)/n
bk = (sum(YYk*YY)/denk - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='DB'){
D[k,(1:d),(1:d)] = crossprod(YY%*%U,YY%*%U)/n
bk = (sum(YY*YY)/n - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AkjBk'){
if (d==1){D[k,1,1] = diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk)} else {
D[k,(1:d),(1:d)] = diag(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))}
bk = (sum(YYk*YY)/denk - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AkjB'){
if (d==1){D[k,1,1] = diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk)} else {
D[k,(1:d),(1:d)] = diag(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))}
bk = (sum(YY*YY)/n - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AkBk'){
if (d==1){D[k,1,1] = sum(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))/d} else{
D[k,(1:d),(1:d)] = diag(rep(sum(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))/d,d))}
bk = (sum(YYk*YY)/denk - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AkB'){
if (d==1){D[k,1,1] = sum(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))/d} else{
D[k,(1:d),(1:d)] = diag(rep(sum(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))/d,d))}
bk = (sum(YY*YY)/n - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AjBk'){
if (d==1){D[k,1,1] = diag(crossprod(YY%*%U,YY%*%U)/n)} else {
D[k,(1:d),(1:d)] = diag(diag(crossprod(YY%*%U,YY%*%U)/n))}
bk = (sum(YYk*YY)/denk - sum(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AjB'){
if (d==1){D[k,1,1] = diag(crossprod(YY%*%U,YY%*%U)/n)} else{
D[k,(1:d),(1:d)] = diag(diag(crossprod(YY%*%U,YY%*%U)/n))}
bk = (sum(YY*YY)/n - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='ABk'){
if (d==1){D[k,1,1] = sum(diag(crossprod(YY%*%U,YY%*%U)/n))} else {
D[k,(1:d),(1:d)] = diag(rep(sum(diag(crossprod(YY%*%U,YY%*%U)/n))/d,d))}
bk = (sum(YYk*YY)/denk - sum(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AB'){
if (d==1){D[k,1,1] = sum(diag(crossprod(YY%*%U,YY%*%U)/n))} else {
D[k,(1:d),(1:d)] = diag(rep(sum(diag(crossprod(YY%*%U,YY%*%U)/n))/d,d))}
bk = (sum(YY*YY)/n - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
}
prms = list(K=K,p=p,mean=mu,my=m,prop=prop,D=D,b=b,model=model,method=method,V=U,test=test)
}
|
var_boot_fis <- function(ri, n, r, dv = 10, reps = 1000)
{
r_thetai <- mean(ri)
cov <- r
Sigma <- matrix(cov, nrow = dv+1, ncol = dv+1)
Sigma[1, ] <- r_thetai
Sigma[ ,1] <- r_thetai
diag(Sigma) <- 1
boot_var <- get_var_boot_fis(Sigma, n, dv, reps)
return(boot_var)
}
|
get_predict <- function(model, newdata, type, ...) {
UseMethod("get_predict", model)
}
get_predict.default <- function(model,
newdata = insight::get_data(model),
type = "response",
conf.level = NULL,
...) {
type <- sanity_type(model, type)
type_base <- unname(type)
type_insight <- names(type)
dots <- list(...)
unused <- c("normalize_dydx", "step_size", "numDeriv_method")
dots <- dots[setdiff(names(dots), unused)]
if (!is.na(type_insight) && (!is.null(conf.level) || "include_random" %in% names(dots))) {
if ("include_random" %in% names(dots)) {
if (any(c("re.form", "re_formula") %in% names(dots))) {
stop("The `include_random` and `re.form` (or `re_formula`) arguments cannot be used together.")
}
}
if ("re_formula" %in% names(dots)) {
dots[["re.form"]] <- dots[["re_formula"]]
}
if ("re.form" %in% names(dots)) {
if (isTRUE(checkmate::check_formula(dots[["re.form"]]))) {
dots[["include_random"]] <- dots[["re.form"]]
} else if (is.na(dots[["re.form"]])) {
dots[["include_random"]] <- FALSE
} else {
dots[["include_random"]] <- TRUE
}
dots[["re.form"]] <- NULL
}
args <- list(
x = model,
data = newdata,
predict = type_insight,
ci = conf.level)
args <- c(args, dots)
f <- insight::get_predicted
pred <- try(do.call("f", args), silent = TRUE)
if (inherits(pred, "get_predicted")) {
out <- data.frame(pred)
colnames(out)[colnames(out) == "Row"] <- "rowid"
colnames(out)[colnames(out) == "Response"] <- "group"
return(out)
}
}
dots[["newdata"]] <- newdata
dots[["type"]] <- type_base
args <- c(list(model), dots)
fun <- stats::predict
pred <- do.call("fun", args)
if (is.array(pred) && length(dim(pred)) == 1) {
pred <- as.vector(pred)
}
if (is.array(pred) &&
length(dim(pred)) == 3 &&
dim(pred)[1] == 1 &&
dim(pred)[2] == 1 &&
dim(pred)[3] > 1) {
pred <- as.vector(pred)
}
if (isTRUE(checkmate::check_atomic_vector(pred))) {
out <- data.frame(
rowid = 1:nrow(newdata),
predicted = as.numeric(pred))
} else if (is.matrix(pred)) {
out <- data.frame(
rowid = rep(1:nrow(pred), times = ncol(pred)),
group = rep(colnames(pred), each = nrow(pred)),
predicted = c(pred))
} else {
stop(sprintf("Unable to extract predictions of type %s from a model of class %s. Please report this problem, along with reproducible code and data on Github: https://github.com/vincentarelbundock/marginaleffects/issues", type, class(model)[1]))
}
return(out)
}
|
NULL
NULL
NULL
NULL
NULL
|
UtilIntrinsic2PhysicalRSM <- function(mu, lambda, nu) {
lambdaP <- lambda / mu
nuP <- 1 - exp(-nu * mu)
return (list(
lambdaP = lambdaP,
nuP = nuP))
}
|
triple_ins = function(x, path_start, path_end){
inserts = c(path_start:path_end)[x[path_start:path_end] == 0]
triples = c()
if(length(inserts) > 2){
for(i in 1:(length(inserts)-2)){
potential = inserts[i]:(inserts[i]+2)
observed = inserts[i:(i+2)]
if(isTRUE(all.equal(potential, observed))){
triples = c(triples, observed)
}
}
return(triples)
}else{
return(c())
}
}
triple_dels = function(x, path_start, path_end){
deletes = c(path_start:path_end)[x[path_start:path_end] == 2]
triples = c()
if(length(deletes) > 2){
for(i in 1:(length(deletes)-2)){
potential = deletes[i]:(deletes[i]+2)
observed = deletes[i:(i+2)]
if(isTRUE(all.equal(potential, observed))){
triples = c(triples, observed)
}
}
return(triples)
}else{
return(c())
}
}
adj_seq = function(frame_dat, path_out, censor_length = 3, added_phred = "*"){
org_seq_vec = frame_dat$trimmed_seq
new_seq = c()
org_seq_pos = 1
path_pos = frame_dat$path_start
path_end = frame_dat$path_end
new_pos = 1
censor_0s = c()
censor_2s = c()
match_seen = FALSE
first_0 = TRUE
triple_inserts = triple_ins(path_out, path_pos, path_end)
triple_deletes = triple_dels(path_out, path_pos, path_end)
for(i in path_pos:path_end){
if(org_seq_pos > length(org_seq_vec)){
break
}
if(path_out[i] == 0){
if(paste(path_out[i:(i+4)], collapse='') == "00000"){
break
}
if(match_seen == TRUE){
if(!i %in% triple_inserts){
if(first_0 == TRUE){
new_seq = c(new_seq, org_seq_vec[org_seq_pos])
org_seq_pos = org_seq_pos + 1
new_pos = new_pos + 1
match_seen = TRUE
first_0 = FALSE
}
add_char = '-'
if(!is.null(names(org_seq_vec))){
names(add_char) = added_phred
}
new_seq = c(new_seq, add_char)
new_pos = new_pos + 1
censor_0s = c(censor_0s, new_pos)
if(i < path_end){
if(path_out[(i+1)] != 0){
first_0 = TRUE
}
}
}
}
}else if(path_out[i] == 1){
new_seq = c(new_seq, org_seq_vec[org_seq_pos])
org_seq_pos = org_seq_pos + 1
new_pos = new_pos + 1
match_seen = TRUE
}else if(path_out[i] == 2){
if(match_seen == TRUE){
if(paste(path_out[i:(i+4)], collapse='') == "22222"){
break
}
if(!i %in% triple_deletes){
org_seq_pos = org_seq_pos + 1
censor_2s = c(censor_2s, new_pos)
}
}
}
}
if(org_seq_pos < length(org_seq_vec)){
trimmed_end = org_seq_vec[org_seq_pos:length(org_seq_vec)]
}else{
trimmed_end = c()
}
if(censor_length != 0){
if(!is.null(censor_0s)){
censor_0s_masks = unlist(lapply(censor_0s, function(pos){
(pos-censor_length-1):(pos+censor_length-1)
}))
censor_0s_masks = unique(censor_0s_masks)
censor_0s_masks = censor_0s_masks[censor_0s_masks>0]
censor_0s_masks = censor_0s_masks[censor_0s_masks<=length(new_seq)]
new_seq[censor_0s_masks] = "-"
}
if(!is.null(censor_2s)){
censor_2s_masks = unlist(lapply(censor_2s, function(pos){
(pos-(censor_length)):(pos+censor_length-1)
}))
censor_2s_masks = unique(censor_2s_masks)
censor_2s_masks = censor_2s_masks[censor_2s_masks>0]
censor_2s_masks = censor_2s_masks[censor_2s_masks<=length(new_seq)]
new_seq[censor_2s_masks] = "-"
}
}
adj_count = length(c(censor_0s,censor_2s))
return(list(c(frame_dat$front, new_seq), adj_count, trimmed_end, censor_0s, censor_2s))
}
adjust = function(x, ...){
UseMethod("adjust")
}
adjust.DNAseq = function(x, ..., censor_length = 7, added_phred = "*"){
adj_out = adj_seq(x$frame_dat, x$data$path, censor_length = censor_length, added_phred = added_phred)
x$adjusted_sequence = adj_out[[1]]
x$adjustment_count = adj_out[[2]]
x$data$adjusted_trimmed = adj_out[[3]]
x$data$deletes_changed = adj_out[[4]]
x$data$inserts_changed = adj_out[[5]]
return(x)
}
|
job_formats_zh_tw <- c(
"BIOS\u5de5\u7a0b\u5e2b",
"CAD\uff0fCAM\u5de5\u7a0b\u5e2b",
"CNC\u6a5f\u53f0\u64cd\u4f5c\u4eba\u54e1",
"CNC\u96fb\u8166\u7a0b\u5f0f\u7de8\u6392\u4eba\u54e1",
"EMC\uff0f\u96fb\u5b50\u5b89\u898f\u5de5\u7a0b\u5e2b",
"FAE\u5de5\u7a0b\u5e2b",
"IC\u4f48\u5c40\u5de5\u7a0b\u5e2b",
"IC\u5c01\u88dd\uff0f\u6e2c\u8a66\u5de5\u7a0b\u5e2b",
"ISO\uff0f\u54c1\u4fdd\u4eba\u54e1",
"Internet\u7a0b\u5f0f\u8a2d\u8a08\u5e2b",
"LCD\u88fd\u7a0b\u5de5\u7a0b\u5e2b",
"LCD\u8a2d\u5099\u5de5\u7a0b\u5e2b",
"MES\u5de5\u7a0b\u5e2b",
"MIS\u7a0b\u5f0f\u8a2d\u8a08\u5e2b",
"MIS\uff0f\u7db2\u7ba1\u4e3b\u7ba1",
"OP\uff0f\u65c5\u884c\u793e\u4eba\u54e1",
"PCB\u4f48\u7dda\u5de5\u7a0b\u5e2b",
"PCB\u6280\u8853\u4eba\u54e1",
"RF\u901a\u8a0a\u5de5\u7a0b\u5e2b",
"SMT\u5de5\u7a0b\u5e2b",
"\u4e00\u822c\u52d5\u7269\u98fc\u80b2\u5de5\u4f5c\u8005",
"\u4e0d\u52d5\u7522\u7522\u6b0a\u5be9\u6838\uff0f\u4f30\u50f9\u5e2b",
"\u4e0d\u52d5\u7522\u7d93\u7d00\u4eba",
"\u4e0d\u52d5\u7522\uff0f\u5546\u5834\u958b\u767c\u4eba\u54e1",
"\u4e2d\u7b49\u5b78\u6821\u6559\u5e2b",
"\u4e2d\u91ab\u5e2b",
"\u4e2d\u9910\u5eda\u5e2b",
"\u4e3b\u6301\u4eba",
"\u4e3b\u7ba1\u7279\u5225\u52a9\u7406",
"\u4e3b\u8fa6\u6703\u8a08",
"\u4eba\u529b\u8cc7\u6e90\u4e3b\u7ba1",
"\u4eba\u529b\u8cc7\u6e90\u4eba\u54e1",
"\u4eba\u529b\u8cc7\u6e90\u52a9\u7406",
"\u4eba\u529b\uff0f\u5916\u52de\u4ef2\u4ecb",
"\u4ee3\u66f8\uff0f\u5730\u653f\u58eb",
"\u4f30\u7b97\u4eba\u54e1",
"\u4f5c\u66f2\u5bb6",
"\u4f5c\u696d\u54e1\uff0f\u5305\u88dd\u54e1",
"\u4fdd\u5168\u4eba\u54e1\uff0f\u8b66\u885b",
"\u4fdd\u5168\u6280\u8853\u4eba\u54e1",
"\u4fdd\u5b89\u670d\u52d9\u5de5\u4f5c",
"\u4fdd\u7a05\u4eba\u54e1",
"\u4fdd\u96aa\u696d\u52d9\uff0f\u7d93\u7d00\u4eba",
"\u5009\u5132\u7269\u6d41\u4eba\u54e1",
"\u5009\u7ba1",
"\u50ac\u6536\u4eba\u54e1",
"\u50b3\u64ad\u5a92\u9ad4\u4f01\u5283\u4eba\u54e1",
"\u50b3\u92b7\u4eba\u54e1",
"\u5132\u5099\u5e79\u90e8",
"\u5149\u5b78\u5de5\u7a0b\u5e2b",
"\u5149\u96fb\u5de5\u7a0b\u5e2b",
"\u5149\u96fb\u5de5\u7a0b\u7814\u767c\u4e3b\u7ba1",
"\u5167\u696d\u5de5\u7a0b\u5e2b",
"\u516c\u5171\u885b\u751f\u4eba\u54e1",
"\u516c\u5171\u885b\u751f\u91ab\u5e2b",
"\u516c\u5bb6\u6a5f\u95dc\u4eba\u54e1",
"\u5238\u5546\u5f8c\u7dda\u4eba\u54e1",
"\u526f\u6559\u6388",
"\u52a0\u6cb9\u54e1",
"\u52a9\u6559",
"\u52a9\u7406\u5de5\u7a0b\u5e2b",
"\u52a9\u7406\u6559\u6388",
"\u52de\u5de5\u5b89\u5168\u885b\u751f\u7ba1\u7406\u4eba\u54e1",
"\u52de\u5de5\u5b89\u5168\u885b\u751f\u7ba1\u7406\u5e2b",
"\u5305\u88dd\u8a2d\u8a08",
"\u5316\u5b78\u5de5\u7a0b\u7814\u767c\u4eba\u54e1",
"\u5316\u5b78\u7814\u7a76\u54e1",
"\u5316\u5de5\u5316\u5b78\u5de5\u7a0b\u5e2b",
"\u5347\u5b78\u88dc\u7fd2\u73ed\u8001\u5e2b",
"\u534a\u5c0e\u9ad4\u5de5\u7a0b\u5e2b",
"\u534a\u5c0e\u9ad4\u88fd\u7a0b\u5de5\u7a0b\u5e2b",
"\u534a\u5c0e\u9ad4\u8a2d\u5099\u5de5\u7a0b\u5e2b",
"\u5370\u524d\u88fd\u4f5c\uff0f\u5370\u5237\u6280\u8853\u4eba\u54e1",
"\u53ef\u9760\u5ea6\u5de5\u7a0b\u5e2b",
"\u540a\u8eca\uff0f\u8d77\u91cd\u6a5f\u8a2d\u5099\u64cd\u4f5c\u54e1",
"\u547c\u5438\u6cbb\u7642\u5e2b",
"\u54c1\u724c\u5ba3\u50b3\u53ca\u5a92\u9ad4\u516c\u95dc",
"\u54c1\u7ba1\uff0f\u54c1\u4fdd\u4e3b\u7ba1",
"\u54c1\u7ba1\uff0f\u54c1\u4fdd\u5de5\u7a0b\u5e2b",
"\u54c1\u7ba1\uff0f\u6aa2\u9a57\u4eba\u54e1",
"\u54f2\u5b78\uff0f\u6b77\u53f2\uff0f\u653f\u6cbb\u7814\u7a76\u4eba\u54e1",
"\u552e\u7968\uff0f\u6536\u9280\u4eba\u54e1",
"\u5546\u696d\u8a2d\u8a08",
"\u5546\u6a19\uff0f\u5c08\u5229\u4eba\u54e1",
"\u5674\u6f06\u4eba\u54e1",
"\u570b\u5167\u696d\u52d9\u4e3b\u7ba1",
"\u570b\u5167\u696d\u52d9\u4eba\u54e1",
"\u570b\u5916\u696d\u52d9\u4e3b\u7ba1",
"\u570b\u5916\u696d\u52d9\u4eba\u54e1",
"\u570b\u5c0f\u5b78\u6821\u6559\u5e2b",
"\u570b\u8cbf\u4eba\u54e1",
"\u5716\u66f8\u8cc7\u6599\u7ba1\u7406\u4eba\u54e1",
"\u571f\u5730\u958b\u767c\u4eba\u54e1",
"\u571f\u6728\u6280\u5e2b\uff0f\u571f\u6728\u5de5\u7a0b\u5e2b",
"\u5730\u52e4\u4eba\u54e1",
"\u5730\u8cea\u8207\u5730\u7403\u79d1\u5b78\u7814\u7a76\u54e1",
"\u5851\u81a0\u5c04\u51fa\u6280\u8853\u4eba\u54e1",
"\u5851\u81a0\u6a21\u5177\u6280\u8853\u4eba\u54e1",
"\u5857\u88dd\u6280\u8853\u4eba\u54e1",
"\u58d3\u9444\u6a21\u5177\u6280\u8853\u4eba\u54e1",
"\u5916\u52d9\uff0f\u5feb\u905e\uff0f\u9001\u8ca8",
"\u591a\u5a92\u9ad4\u52d5\u756b\u8a2d\u8a08\u5e2b",
"\u591a\u5a92\u9ad4\u958b\u767c\u4e3b\u7ba1",
"\u5927\u6a13\u7ba1\u7406\u54e1",
"\u5927\u8ca8\u8eca\u53f8\u6a5f",
"\u5929\u6587\u7814\u7a76\u54e1",
"\u592a\u967d\u80fd\u6280\u8853\u5de5\u7a0b\u5e2b",
"\u5a1b\u6a02\u4e8b\u696d\u4eba\u54e1",
"\u5a92\u9ad4\u516c\u95dc\uff0f\u5ba3\u50b3\u63a1\u8cb7",
"\u5b89\u5168\uff0f\u885b\u751f\u6aa2\u9a57\u4eba\u54e1",
"\u5b89\u5fc3\u670d\u52d9\u54e1",
"\u5b89\u89aa\u73ed\u8001\u5e2b",
"\u5ba2\u6236\u670d\u52d9\u4e3b\u7ba1",
"\u5ba2\u6236\u670d\u52d9\u4eba\u54e1",
"\u5ba4\u5167\u8a2d\u8a08\uff0f\u88dd\u6f62\u4eba\u54e1",
"\u5bb6\u4e8b\u670d\u52d9\u4eba\u54e1",
"\u5bb6\u5ead\u4ee3\u5de5",
"\u5be6\u9a57\u5316\u9a57\u4eba\u54e1",
"\u5bf5\u7269\u7f8e\u5bb9\u5c08\u696d\u4eba\u54e1",
"\u5c08\u6848\u696d\u52d9\u4e3b\u7ba1",
"\u5c08\u6848\u7ba1\u7406\u4e3b\u7ba1",
"\u5c08\u6848\u7ba1\u7406\u5e2b",
"\u5c08\u79d1\u8b77\u7406\u5e2b",
"\u5c0e\u64ad",
"\u5c0e\u6f14",
"\u5c0e\u904a",
"\u5c0f\u5ba2\u8eca\u53f8\u6a5f",
"\u5c0f\u8ca8\u8eca\u53f8\u6a5f",
"\u5c45\u5bb6\u670d\u52d9\u7763\u5c0e\u54e1",
"\u5c55\u5834\uff0f\u6ae5\u7a97\u4f48\u7f6e\u4eba\u54e1",
"\u5de5\u52d9\u4eba\u54e1\uff0f\u52a9\u7406",
"\u5de5\u5546\u767b\u8a18\u670d\u52d9\u4eba\u54e1",
"\u5de5\u5730\u76e3\u5de5\uff0f\u4e3b\u4efb",
"\u5de5\u5ee0\u4e3b\u7ba1",
"\u5de5\u696d\u5de5\u7a0b\u5e2b\uff0f\u751f\u7522\u7dda\u898f\u5283",
"\u5de5\u696d\u8a2d\u8a08",
"\u5de5\u7a0b\u52a9\u7406",
"\u5de5\u7a0b\u7814\u767c\u4e3b\u7ba1",
"\u5de5\u7a0b\u914d\u7ba1\u7e6a\u5716",
"\u5de5\u8b80\u751f",
"\u5e02\u5834\u8abf\u67e5\uff0f\u5e02\u5834\u5206\u6790",
"\u5e73\u9762\u8a2d\u8a08\uff0f\u7f8e\u7de8\u4eba\u54e1",
"\u5e7c\u6559\u73ed\u8001\u5e2b",
"\u5e97\u9577\uff0f\u8ce3\u5834\u7ba1\u7406\u4eba\u54e1",
"\u5ee0\u52d9",
"\u5ee0\u52d9\u52a9\u7406",
"\u5ee3\u544aAE\u696d\u52d9\u4eba\u54e1",
"\u5ee3\u544a\u4f01\u5283\u4e3b\u7ba1",
"\u5ee3\u544a\u6587\u6848\uff0f\u4f01\u5283",
"\u5ee3\u544a\u8a2d\u8a08",
"\u5efa\u7bc9\u5e2b",
"\u5efa\u7bc9\u7269\u6e05\u6f54\u5de5",
"\u5efa\u7bc9\u7269\u96fb\u529b\u7cfb\u7d71\u7dad\u4fee\u5de5",
"\u5efa\u7bc9\u8a2d\u8a08\uff0f\u7e6a\u5716\u4eba\u54e1",
"\u5f71\u7247\u88fd\u4f5c\u6280\u8853\u4eba\u54e1",
"\u5f8b\u5e2b",
"\u5fa9\u5efa\u6280\u8853\u5e2b",
"\u5fae\u6a5f\u96fb\u5de5\u7a0b\u5e2b",
"\u5fc3\u7406\u5b78\u7814\u7a76\u4eba\u54e1",
"\u5fd7\u5de5\u4eba\u54e1",
"\u5fd7\u9858\u5f79\u8ecd\u5b98\uff0f\u58eb\u5b98\uff0f\u58eb\u5175",
"\u61c9\u7528\u79d1\u5b78\u7814\u7a76\u54e1",
"\u6210\u672c\u6703\u8a08",
"\u624b\u5de5\u5305\u88dd\u5de5",
"\u624d\u85dd\u985e\u8001\u5e2b",
"\u6253\u7248\u4eba\u54e1",
"\u6280\u8853\u6587\u4ef6\uff0f\u8aaa\u660e\u66f8\u7de8\u8b6f",
"\u6309\u6469\uff0f\u63a8\u62ff\u5e2b",
"\u6392\u7248\u4eba\u54e1",
"\u63a1\u8cfc\u4e3b\u7ba1",
"\u63a1\u8cfc\u4eba\u54e1",
"\u63a1\u8cfc\u52a9\u7406",
"\u63a8\u571f\u6a5f\u8a2d\u5099\u64cd\u4f5c\u54e1",
"\u64ad\u97f3\uff0f\u914d\u97f3\u4eba\u54e1",
"\u651d\u5f71\u52a9\u7406",
"\u651d\u5f71\u5e2b",
"\u653e\u5c04\u6027\u8a2d\u5099\u4f7f\u7528\u6280\u8853\u54e1",
"\u6551\u751f\u54e1",
"\u6559\u4fdd\u54e1",
"\u6559\u6388",
"\u6559\u80b2\u8a13\u7df4\u4eba\u54e1",
"\u6574\u9ad4\u9020\u578b\u5e2b",
"\u6578\u4f4dIC\u8a2d\u8a08\u5de5\u7a0b\u5e2b",
"\u6578\u5b78\u7814\u7a76\u54e1",
"\u6578\u7406\u88dc\u7fd2\u73ed\u8001\u5e2b",
"\u6587\u4ef6\u7ba1\u7406\u5e2b",
"\u6587\u7de8\uff0f\u6821\u5c0d\uff0f\u6587\u5b57\u5de5\u4f5c\u8005",
"\u65c5\u904a\u4f11\u9592\u985e\u4e3b\u7ba1",
"\u65e5\u5f0f\u5eda\u5e2b",
"\u65e5\u6587\u7ffb\u8b6f\uff0f\u53e3\u8b6f\u4eba\u54e1",
"\u661f\u8c61\u5360\u535c\u4eba\u54e1",
"\u666f\u89c0\u8a2d\u8a08\u5e2b",
"\u6703\u8a08\u5e2b",
"\u670d\u88dd\uff0f\u76ae\u5305\uff0f\u978b\u985e\u8a2d\u8a08",
"\u6728\u5de5",
"\u6750\u6599\u7814\u767c\u4eba\u54e1",
"\u677f\u91d1\u6280\u8853\u54e1",
"\u6797\u6728\u4f10\u904b\u5de5\u4f5c\u8005",
"\u67d3\u6574\u6280\u8853\u4eba\u54e1",
"\u67e5\u5e33\uff0f\u5be9\u8a08\u4eba\u54e1",
"\u6838\u4fdd\uff0f\u4fdd\u96aa\u5167\u52e4\u4eba\u54e1",
"\u696d\u52d9\u52a9\u7406",
"\u696d\u52d9\u652f\u63f4\u5de5\u7a0b\u5e2b",
"\u6a02\u5668\u88fd\u9020\u54e1",
"\u6a21\u7279\u5152",
"\u6a5f\u68b0\u52a0\u5de5\u6280\u8853\u4eba\u54e1",
"\u6a5f\u68b0\u5de5\u7a0b\u5e2b",
"\u6a5f\u68b0\u64cd\u4f5c\u54e1",
"\u6a5f\u68b0\u88dd\u914d\u54e1",
"\u6a5f\u68b0\u8a2d\u8a08\uff0f\u7e6a\u5716\u4eba\u54e1",
"\u6a5f\u69cb\u5de5\u7a0b\u5e2b",
"\u6a5f\u96fb\u6280\u5e2b\uff0f\u5de5\u7a0b\u5e2b",
"\u6ac3\u6aaf\u63a5\u5f85\u4eba\u54e1",
"\u6c23\u8c61\u7814\u7a76\u54e1",
"\u6c34\u4fdd\u5de5\u7a0b\u5e2b",
"\u6c34\u4fdd\u6280\u5e2b",
"\u6c34\u5229\u5de5\u7a0b\u5e2b",
"\u6c34\u7522\u990a\u6b96\u5de5\u4f5c\u8005",
"\u6c34\u96fb\u5de5",
"\u6c34\u96fb\u5de5\u7a0b\u5e2b",
"\u6c34\u96fb\u5de5\u7a0b\u7e6a\u5716\u4eba\u54e1",
"\u6c7d\u8eca\u7f8e\u5bb9\u4eba\u54e1",
"\u6c7d\u8eca\u92b7\u552e\u4eba\u54e1",
"\u6c7d\u8eca\uff0f\u6a5f\u8eca\u5f15\u64ce\u6280\u8853\u4eba\u54e1",
"\u6c7d\u8eca\uff0f\u6a5f\u8eca\u6280\u8853\u7dad\u4fee\u4eba\u54e1",
"\u6c96\u58d3\u6a21\u5177\u6280\u8853\u4eba\u54e1",
"\u6cb9\u6f06\u5de5",
"\u6cbb\u7642\u5e2b",
"\u6cd5\u52d9\u4eba\u54e1",
"\u6cd5\u52d9\u52a9\u7406",
"\u6cd5\u52d9\uff0f\u667a\u8ca1\u4e3b\u7ba1",
"\u6cd5\u5f8b\u5c08\u696d\u4eba\u54e1",
"\u6ce5\u6c34\u5c0f\u5de5",
"\u6ce5\u6c34\u5de5",
"\u6d17\u7897\u4eba\u54e1",
"\u6d3b\u52d5\u4f01\u5283\u4eba\u54e1",
"\u6d3e\u5831\u751f\uff0f\u50b3\u55ae\u6d3e\u9001",
"\u6d88\u9632\u54e1",
"\u6d88\u9632\u5c08\u696d\u4eba\u54e1",
"\u6df7\u51dd\u571f\u5de5",
"\u6e05\u6f54\u5de5",
"\u6e2c\u8a66\u4eba\u54e1",
"\u6f14\u54e1",
"\u6f14\u594f\u5bb6",
"\u6f14\u7b97\u6cd5\u958b\u767c\u5de5\u7a0b\u5e2b",
"\u710a\u63a5\u53ca\u5207\u5272\u6280\u8853\u54e1",
"\u7167\u9867\u6307\u5c0e\u54e1",
"\u7167\u9867\u670d\u52d9\u54e1",
"\u71b1\u50b3\u5de5\u7a0b\u5e2b",
"\u71c8\u5149\uff0f\u97f3\u97ff\u5e2b",
"\u71df\u5efa\u4e3b\u7ba1",
"\u71df\u5efa\u69cb\u9020\u5de5",
"\u71df\u9020\u5de5\u7a0b\u5e2b",
"\u71df\u904b\u7ba1\u7406\u5e2b",
"\u71df\u990a\u5e2b",
"\u7259\u91ab\u52a9\u7406",
"\u7259\u91ab\u5e2b",
"\u7269\u7406\u6cbb\u7642\u5e2b",
"\u7269\u7406\u7814\u7a76\u54e1",
"\u7269\u7ba1\uff0f\u8cc7\u6750",
"\u7279\u6b8a\u5de5\u7a0b\u5e2b",
"\u7279\u6b8a\u6559\u80b2\u6559\u5e2b",
"\u7279\u7528\u5316\u5b78\u5de5\u7a0b\u5e2b",
"\u7378\u91ab\u5e2b",
"\u73e0\u5bf6\u53ca\u8cb4\u91d1\u5c6c\u6280\u8853\u54e1",
"\u73e0\u5fc3\u7b97\u8001\u5e2b",
"\u7406\u8ce0\u4eba\u54e1",
"\u74b0\u5883\u5de5\u7a0b\u5e2b",
"\u751f\u547d\u79ae\u5100\u5e2b",
"\u751f\u7269\u5b78\u5c08\u696d\u8207\u7814\u7a76",
"\u751f\u7269\u79d1\u6280\u7814\u767c\u4eba\u54e1",
"\u751f\u7522\u6280\u8853\uff0f\u88fd\u7a0b\u5de5\u7a0b\u5e2b",
"\u751f\u7522\u7ba1\u7406\u4e3b\u7ba1",
"\u751f\u7522\u8a2d\u5099\u5de5\u7a0b\u5e2b",
"\u751f\u7ba1",
"\u751f\u7ba1\u52a9\u7406",
"\u751f\u9bae\u4eba\u54e1",
"\u7522\u54c1\u4e8b\u696d\u8655\u4e3b\u7ba1",
"\u7522\u54c1\u4f01\u5283\u4e3b\u7ba1",
"\u7522\u54c1\u4f01\u5283\u958b\u767c\u4eba\u54e1",
"\u7522\u54c1\u552e\u5f8c\u6280\u8853\u670d\u52d9",
"\u7522\u54c1\u7ba1\u7406\u5e2b",
"\u7522\u54c1\u7dad\u4fee\u4eba\u54e1",
"\u7522\u54c1\u884c\u92b7\u4eba\u54e1",
"\u75c5\u7406\u85e5\u7406\u7814\u7a76\u4eba\u54e1",
"\u767c\u5305\u4eba\u54e1",
"\u767c\u884c\u4f01\u5283\uff0f\u51fa\u7248\u4eba\u54e1",
"\u780c\u78da\u5de5",
"\u7814\u7a76\u4eba\u54e1",
"\u7814\u7a76\u52a9\u7406",
"\u786c\u9ad4\u5de5\u7a0b\u7814\u767c\u4e3b\u7ba1",
"\u786c\u9ad4\u6e2c\u8a66\u5de5\u7a0b\u5e2b",
"\u786c\u9ad4\u7814\u767c\u5de5\u7a0b\u5e2b",
"\u793e\u5de5\u4eba\u54e1",
"\u793e\u6703\uff0f\u4eba\u985e\u5b78\u7814\u7a76\u4eba\u54e1",
"\u79d8\u66f8",
"\u7a05\u52d9\u4eba\u54e1",
"\u7a3d\u6838\u4eba\u54e1",
"\u7a7a\u670d\u54e1",
"\u7a7a\u8abf\u51b7\u51cd\u6280\u8853\u4eba\u54e1",
"\u7bc0\u76ee\u52a9\u7406",
"\u7bc0\u76ee\u88fd\u4f5c\u4eba\u54e1",
"\u7c89\u672b\u51b6\u91d1\u6a21\u5177\u6280\u8853\u4eba\u54e1",
"\u7cbe\u5bc6\u5100\u5668\u88fd\u9020\u5de5",
"\u7cbe\u5bc6\u62cb\u5149\u6280\u8853\u4eba\u54e1",
"\u7cfb\u7d71\u6574\u5408\uff0fERP\u5c08\u6848\u5e2b",
"\u7cfb\u7d71\u7dad\u8b77\uff0f\u64cd\u4f5c\u4eba\u54e1",
"\u7d21\u7e54\u5316\u5b78\u5de5\u7a0b\u5e2b",
"\u7d21\u7e54\u5de5\u52d9",
"\u7d50\u69cb\u6280\u5e2b",
"\u7d71\u8a08\u5b78\u7814\u7a76\u54e1",
"\u7d71\u8a08\u7cbe\u7b97\u4eba\u54e1",
"\u7d93\u71df\u7ba1\u7406\u4e3b\u7ba1",
"\u7db2\u7ad9\u884c\u92b7\u4f01\u5283",
"\u7db2\u8def\u5b89\u5168\u5206\u6790\u5e2b",
"\u7db2\u8def\u7ba1\u7406\u5de5\u7a0b\u5e2b",
"\u7db2\u9801\u8a2d\u8a08\u5e2b",
"\u7dda\u5207\u5272\u6280\u8853\u54e1",
"\u7e3d\u52d9\u4e3b\u7ba1",
"\u7e3d\u52d9\u4eba\u54e1",
"\u7e3d\u5e79\u4e8b",
"\u7e3d\u6a5f\u4eba\u54e1",
"\u7e54\u54c1\u8a2d\u8a08",
"\u7f8e\u59ff\u7f8e\u5100\u4eba\u54e1",
"\u7f8e\u5bb9\u5de5\u4f5c\u8005",
"\u7f8e\u5bb9\u985e\u52a9\u7406",
"\u7f8e\u7532\u5f69\u7e6a\u5e2b",
"\u7f8e\u7642\uff0f\u82b3\u7642\u5e2b",
"\u7f8e\u8853\u8001\u5e2b",
"\u7f8e\u8853\u8a2d\u8a08",
"\u7f8e\u9aee\u5de5\u4f5c\u8005",
"\u7f8e\u9aee\u985e\u52a9\u7406",
"\u7ffb\u8b6f\uff0f\u53e3\u8b6f\u4eba\u54e1",
"\u8072\u5b78\uff0f\u566a\u97f3\u5de5\u7a0b\u5e2b",
"\u8072\u6a02\u5bb6",
"\u8077\u80fd\u6cbb\u7642\u5e2b",
"\u80a1\u52d9\u4eba\u54e1",
"\u81ea\u52d5\u63a7\u5236\u5de5\u7a0b\u5e2b",
"\u821e\u8e48\u6307\u5c0e\u8207\u821e\u8e48\u5bb6",
"\u8239\u52d9\uff0f\u62bc\u532f\uff0f\u5831\u95dc\u4eba\u54e1",
"\u8239\u9577\uff0f\u5927\u526f\uff0f\u8239\u54e1",
"\u82b1\u85dd\uff0f\u5712\u85dd\u4eba\u54e1",
"\u82f1\u6587\u7ffb\u8b6f\uff0f\u53e3\u8b6f\u4eba\u54e1",
"\u85dd\u8853\u54c1\uff0f\u73e0\u5bf6\u9451\u50f9\uff0f\u62cd\u8ce3\u9867\u554f",
"\u85dd\u8853\u6307\u5c0e\uff0f\u7e3d\u76e3",
"\u85e5\u5b78\u52a9\u7406",
"\u85e5\u5e2b",
"\u878d\u8cc7\uff0f\u4fe1\u7528\u696d\u52d9\u4eba\u54e1",
"\u884c\u653f\u4e3b\u7ba1",
"\u884c\u653f\u4eba\u54e1",
"\u884c\u653f\u52a9\u7406",
"\u884c\u92b7\u4f01\u5283\u4e3b\u7ba1",
"\u884c\u92b7\u4f01\u5283\u4eba\u54e1",
"\u884c\u92b7\u4f01\u5283\u52a9\u7406",
"\u88dc\u7fd2\u73ed\u5c0e\u5e2b\uff0f\u7ba1\u7406\u4eba\u54e1",
"\u88dc\u7fd2\u73ed\u8001\u5e2b",
"\u88fd\u978b\u985e\u4eba\u54e1",
"\u897f\u9910\u5eda\u5e2b",
"\u897f\u9ede\uff0f\u86cb\u7cd5\u5e2b",
"\u8996\u807d\u5de5\u7a0b\u985e\u4eba\u54e1",
"\u8a08\u7a0b\u8eca\u53f8\u6a5f",
"\u8a18\u5e33\uff0f\u51fa\u7d0d\uff0f\u4e00\u822c\u6703\u8a08",
"\u8a18\u8005\uff0f\u63a1\u7de8",
"\u8a2d\u8a08\u52a9\u7406",
"\u8a3a\u6240\u52a9\u7406",
"\u8a9e\u6587\u88dc\u7fd2\u73ed\u8001\u5e2b",
"\u8a9e\u8a00\u6cbb\u7642\u5e2b",
"\u8abf\u9152\u5e2b\uff0f\u5427\u53f0\u4eba\u54e1",
"\u8abf\u97f3\u6280\u8853\u54e1",
"\u8b1b\u5e2b",
"\u8b77\u7406\u5e2b",
"\u8ca1\u52d9\u5206\u6790\u4eba\u54e1",
"\u8ca1\u52d9\u6216\u6703\u8a08\u4e3b\u7ba1",
"\u8ca1\u52d9\u6703\u8a08\u52a9\u7406",
"\u8cc7\u6599\u5eab\u7ba1\u7406\u4eba\u54e1",
"\u8cc7\u6599\u8f38\u5165\u4eba\u54e1",
"\u8cc7\u6750\u4e3b\u7ba1",
"\u8cc7\u6e90\u56de\u6536\u4eba\u54e1",
"\u8cc7\u8a0a\u52a9\u7406\u4eba\u54e1",
"\u8cc7\u8a0a\u5c08\u696d\u4eba\u54e1",
"\u8cc7\u8a0a\u8a2d\u5099\u7ba1\u5236\u4eba\u54e1",
"\u8eca\u5e8a\u4eba\u54e1",
"\u8eca\u7e2b\uff0f\u88c1\u7e2b\u985e\u4eba\u54e1",
"\u8edf\u97cc\u9ad4\u6e2c\u8a66\u5de5\u7a0b\u5e2b",
"\u8edf\u9ad4\u5c08\u6848\u4e3b\u7ba1",
"\u8edf\u9ad4\u5c08\u6848\u7ba1\u7406\u5e2b",
"\u8edf\u9ad4\u8a2d\u8a08\u5de5\u7a0b\u5e2b",
"\u8fb2\u5de5\u696d\u7528\u6a5f\u5668\u88dd\u4fee\u5de5",
"\u8fb2\u6797\u696d\u8a2d\u5099\u64cd\u4f5c\u54e1",
"\u8fb2\u85dd\u4f5c\u7269\u683d\u57f9\u5de5\u4f5c\u8005",
"\u8fb2\u85dd\uff0f\u755c\u7522\u7814\u7a76\u4eba\u54e1",
"\u901a\u4fe1\u6e2c\u8a66\u7dad\u4fee\u4eba\u54e1",
"\u901a\u8a0a\u5de5\u7a0b\u7814\u767c\u4e3b\u7ba1",
"\u901a\u8a0a\u8edf\u9ad4\u5de5\u7a0b\u5e2b",
"\u901a\u8def\u958b\u767c\u4eba\u54e1",
"\u9023\u9396\u5e97\u7ba1\u7406\u4eba\u54e1",
"\u904a\u6232\u4f01\u5283\u4eba\u54e1",
"\u904b\u52d5\u6559\u7df4",
"\u904b\u8f38\u4ea4\u901a\u5c08\u696d\u4eba\u54e1",
"\u904b\u8f38\u7269\u6d41\u985e\u4e3b\u7ba1",
"\u90fd\u5e02\uff0f\u4ea4\u901a\u898f\u5283\u4eba\u54e1",
"\u91ab\u4e8b\u653e\u5c04\u5e2b",
"\u91ab\u4e8b\u6aa2\u9a57\u5e2b",
"\u91ab\u5e2b",
"\u91ab\u7642\u4eba\u54e1",
"\u91ab\u7642\u5668\u6750\u7814\u767c\u5de5\u7a0b\u5e2b",
"\u91ab\u7642\u5f9e\u696d\u4eba\u54e1",
"\u91ab\u7642\u8a2d\u5099\u63a7\u5236\u4eba\u54e1",
"\u91ab\u85e5\u696d\u52d9\u4ee3\u8868",
"\u91ab\u85e5\u7814\u767c\u4eba\u54e1",
"\u91ab\u9662\u884c\u653f\u7ba1\u7406\u4eba\u54e1",
"\u91cf\u6e2c\uff0f\u5100\u6821\u4eba\u54e1",
"\u91d1\u5c6c\u5efa\u6750\u67b6\u69cb\u4eba\u54e1",
"\u91d1\u878d\u4ea4\u6613\u54e1",
"\u91d1\u878d\u5c08\u696d\u4e3b\u7ba1",
"\u91d1\u878d\u627f\u92b7\u54e1",
"\u91d1\u878d\u71df\u696d\u54e1",
"\u91d1\u878d\u7406\u8ca1\u5c08\u54e1",
"\u91d1\u878d\u7814\u7a76\u54e1",
"\u9280\u884c\u8fa6\u4e8b\u54e1",
"\u9291\u5e8a\u4eba\u54e1",
"\u934b\u7210\u64cd\u4f5c\u6280\u8853\u4eba\u54e1",
"\u9435\u8def\u8eca\u8f1b\u99d5\u99db\u54e1",
"\u9444\u9020\uff0f\u935b\u9020\u6a21\u5177\u6280\u8853\u4eba\u54e1",
"\u9580\u5e02\uff0f\u5e97\u54e1\uff0f\u5c08\u6ac3\u4eba\u54e1",
"\u9632\u6c34\u65bd\u5de5\u4eba\u54e1",
"\u9632\u706b\u53ca\u5efa\u7bc9\u6aa2\u9a57\u4eba\u54e1",
"\u96f6\u4ef6\u5de5\u7a0b\u5e2b",
"\u96f7\u5c04\u64cd\u4f5c\u6280\u8853\u54e1",
"\u96fb\u4fe1\u53ca\u96fb\u529b\u7dda\u8def\u67b6\u8a2d\u5de5",
"\u96fb\u4fe1\uff0f\u901a\u8a0a\u7cfb\u7d71\u5de5\u7a0b\u5e2b",
"\u96fb\u53f0\u5de5\u4f5c\u4eba\u54e1",
"\u96fb\u5b50\u5546\u52d9\u6280\u8853\u4e3b\u7ba1",
"\u96fb\u5b50\u5de5\u7a0b\u5e2b",
"\u96fb\u5b50\u7522\u54c1\u7cfb\u7d71\u5de5\u7a0b\u5e2b",
"\u96fb\u5b50\u8a2d\u5099\u88dd\u4fee\u5de5",
"\u96fb\u6a5f\u5de5\u7a0b\u6280\u8853\u54e1",
"\u96fb\u6a5f\u6280\u5e2b\uff0f\u5de5\u7a0b\u5e2b",
"\u96fb\u6a5f\u88dd\u4fee\u5de5",
"\u96fb\u6a5f\u8a2d\u5099\u88dd\u914d\u54e1",
"\u96fb\u6e90\u5de5\u7a0b\u5e2b",
"\u96fb\u73a9\u7a0b\u5f0f\u8a2d\u8a08\u5e2b",
"\u96fb\u8166\u7cfb\u7d71\u5206\u6790\u5e2b",
"\u96fb\u8166\u7d44\u88dd\uff0f\u6e2c\u8a66",
"\u96fb\u8166\u7e6a\u5716\u4eba\u54e1",
"\u96fb\u8166\u88dc\u7fd2\u73ed\u8001\u5e2b",
"\u96fb\u8a71\u53ca\u96fb\u5831\u6a5f\u88dd\u4fee\u5de5",
"\u96fb\u8a71\u5ba2\u670d\u985e\u4eba\u54e1",
"\u96fb\u8a71\u884c\u92b7\u4eba\u54e1",
"\u96fb\u934d\uff0f\u8868\u9762\u8655\u7406\u6280\u8853\u4eba\u54e1",
"\u97cc\u9ad4\u8a2d\u8a08\u5de5\u7a0b\u5e2b",
"\u97f3\u6a02\u5bb6",
"\u97f3\u6a02\u8001\u5e2b",
"\u9818\u73ed",
"\u9818\u968a",
"\u985e\u5eda\u5e2b",
"\u985e\u6bd4IC\u8a2d\u8a08\u5de5\u7a0b\u5e2b",
"\u985e\u8b1b\u5e2b",
"\u9867\u554f\u4eba\u54e1",
"\u98db\u5b89\u4eba\u54e1",
"\u98db\u6a5f\u88dd\u4fee\u5de5",
"\u98db\u884c\u6a5f\u5e2b",
"\u98df\u54c1\u7814\u767c\u4eba\u54e1",
"\u98df\u54c1\u885b\u751f\u7ba1\u7406\u5e2b",
"\u98ef\u5e97\u5de5\u4f5c\u4eba\u54e1",
"\u98ef\u5e97\u9910\u5ef3\u4e3b\u7ba1",
"\u9910\u5eda\u52a9\u624b",
"\u9910\u98f2\u670d\u52d9\u751f",
"\u99d0\u6821\u4ee3\u8868",
"\u9a57\u5149\u5e2b",
"\u9eb5\u5305\u5e2b",
"\u9ebb\u9189\u91ab\u5e2b"
)
|
is_character <- function(f) {
function(..., msg = '[\u2713] function output is character') {
c <- f(...)
if (is.character(c))
cat(msg, '\n')
else
stop('found object of class', class(c), call. = FALSE)
c
}
}
hello <- function(world = 'world!') {
paste('hello,', world)
}
|
CreateInputsCrit <- function(FUN_CRIT,
InputsModel,
RunOptions,
Qobs,
Obs,
VarObs = "Q",
BoolCrit = NULL,
transfo = "",
Weights = NULL,
Ind_zeroes = NULL,
epsilon = NULL,
warnings = TRUE,
verbose = TRUE) {
ObjectClass <- NULL
if (!missing(Qobs)) {
if (missing(Obs)) {
if (warnings) {
warning("argument 'Qobs' is deprecated. Please use 'Obs' and 'VarObs' instead")
}
Obs <- Qobs
} else {
warning("argument 'Qobs' is deprecated. The values set in 'Obs' will be used instead")
}
}
if (!missing(Ind_zeroes) & warnings) {
warning("deprecated 'Ind_zeroes' argument")
}
if (!missing(verbose)) {
warning("deprecated 'verbose' argument. Use 'warnings', instead")
}
if (!inherits(InputsModel, "InputsModel")) {
stop("'InputsModel' must be of class 'InputsModel'")
}
LLL <- length(InputsModel$DatesR[RunOptions$IndPeriod_Run])
vecObs <- unlist(Obs)
if (length(vecObs) %% LLL != 0 | !is.numeric(vecObs)) {
stop(sprintf("'Obs' must be a (list of) vector(s) of numeric values of length %i", LLL), call. = FALSE)
}
if (!is.list(Obs)) {
idLayer <- list(1L)
Obs <- list(Obs)
} else {
idLayer <- lapply(Obs, function(i) {
if (is.list(i)) {
length(i)
} else {
1L
}
})
Obs <- lapply(Obs, function(x) rowMeans(as.data.frame(x)))
}
listArgs <- list(FUN_CRIT = FUN_CRIT,
Obs = Obs,
VarObs = VarObs,
BoolCrit = BoolCrit,
idLayer = idLayer,
transfo = as.character(transfo),
Weights = Weights,
epsilon = epsilon)
for (iArgs in names(listArgs)) {
if (iArgs %in% c("Weights", "BoolCrit", "epsilon")) {
if (any(is.null(listArgs[[iArgs]]))) {
listArgs[[iArgs]] <- lapply(seq_along(listArgs$FUN_CRIT), function(x) NULL)
}
}
if (iArgs %in% c("FUN_CRIT", "VarObs", "transfo", "Weights") & length(listArgs[[iArgs]]) > 1L) {
listArgs[[iArgs]] <- as.list(listArgs[[iArgs]])
}
if (!is.list(listArgs[[iArgs]])) {
listArgs[[iArgs]] <- list(listArgs[[iArgs]])
}
}
listArgs$FUN_CRIT <- lapply(listArgs$FUN_CRIT, FUN = match.fun)
if (missing(VarObs)) {
listArgs$VarObs <- as.list(rep("Q", times = length(listArgs$Obs)))
}
if ("Q" %in% VarObs & !inherits(RunOptions, "GR")) {
stop("'VarObs' cannot contain Q if a GR rainfall-runoff model is not used")
}
if (any(c("SCA", "SWE") %in% VarObs) & !inherits(RunOptions, "CemaNeige")) {
stop("'VarObs' cannot contain SCA or SWE if CemaNeige is not used")
}
if ("SCA" %in% VarObs & inherits(RunOptions, "CemaNeige") & !"Gratio" %in% RunOptions$Outputs_Sim) {
stop("'Gratio' is missing in 'Outputs_Sim' of 'RunOptions', which is necessary to output SCA with CemaNeige")
}
if ("SWE" %in% VarObs & inherits(RunOptions, "CemaNeige") & !"SnowPack" %in% RunOptions$Outputs_Sim) {
stop("'SnowPack' is missing in 'Outputs_Sim' of 'RunOptions', which is necessary to output SWE with CemaNeige")
}
if (missing(transfo)) {
listArgs$transfo <- as.list(rep("", times = length(listArgs$Obs)))
}
if (length(unique(sapply(listArgs, FUN = length))) != 1) {
stopListArgs <- paste(sapply(names(listArgs), shQuote), collapse = ", ")
stop(sprintf("arguments %s must have the same length", stopListArgs))
}
if (!inherits(RunOptions , "RunOptions")) {
stop("'RunOptions' must be of class 'RunOptions'")
}
if (length(listArgs$Weights) > 1 & sum(unlist(listArgs$Weights)) == 0 & !any(sapply(listArgs$Weights, is.null))) {
stop("sum of 'Weights' cannot be equal to zero")
}
listArgs2 <- lapply(seq_along(listArgs$FUN_CRIT), function(i) lapply(listArgs, "[[", i))
inVarObs <- c("Q", "SCA", "SWE")
msgVarObs <- "'VarObs' must be a (list of) character vector(s) and one of %s"
msgVarObs <- sprintf(msgVarObs, paste(sapply(inVarObs, shQuote), collapse = ", "))
inTransfo <- c("", "sqrt", "log", "inv", "sort", "boxcox")
msgTransfo <- "'transfo' must be a (list of) character vector(s) and one of %s, or numeric value for power transformation"
msgTransfo <- sprintf(msgTransfo, paste(sapply(inTransfo, shQuote), collapse = ", "))
InputsCrit <- lapply(listArgs2, function(iListArgs2) {
if (!(identical(iListArgs2$FUN_CRIT, ErrorCrit_NSE ) | identical(iListArgs2$FUN_CRIT, ErrorCrit_KGE ) |
identical(iListArgs2$FUN_CRIT, ErrorCrit_KGE2) | identical(iListArgs2$FUN_CRIT, ErrorCrit_RMSE))) {
stop("incorrect 'FUN_CRIT' for use in 'CreateInputsCrit'", call. = FALSE)
}
if (identical(iListArgs2$FUN_CRIT, ErrorCrit_RMSE) & length(listArgs$Weights) > 1 & all(!is.null(unlist(listArgs$Weights)))) {
stop("calculating a composite criterion with the RMSE is not allowed since RMSE is not a dimensionless metric", call. = FALSE)
}
if (!is.vector(iListArgs2$Obs) | length(iListArgs2$Obs) != LLL | !is.numeric(iListArgs2$Obs)) {
stop(sprintf("'Obs' must be a (list of) vector(s) of numeric values of length %i", LLL), call. = FALSE)
}
if (is.null(iListArgs2$BoolCrit)) {
iListArgs2$BoolCrit <- rep(TRUE, length(iListArgs2$Obs))
}
if (!is.logical(iListArgs2$BoolCrit)) {
stop("'BoolCrit' must be a (list of) vector(s) of boolean", call. = FALSE)
}
if (length(iListArgs2$BoolCrit) != LLL) {
stop("'BoolCrit' and the period defined in 'RunOptions' must have the same length", call. = FALSE)
}
if (!is.vector(iListArgs2$VarObs) | length(iListArgs2$VarObs) != 1 | !is.character(iListArgs2$VarObs) | !all(iListArgs2$VarObs %in% inVarObs)) {
stop(msgVarObs, call. = FALSE)
}
if (any(iListArgs2$VarObs %in% "SCA")) {
idSCA <- which(iListArgs2$VarObs == "SCA")
if (length(idSCA) == 1L) {
vecSCA <- iListArgs2$Obs
} else {
vecSCA <- unlist(iListArgs2$Obs[idSCA])
}
if (min(vecSCA, na.rm = TRUE) < 0 | max(vecSCA, na.rm = TRUE) > 1) {
stop("'Obs' outside [0,1] for \"SCA\"", call. = FALSE)
}
}
inPosVarObs <- c("Q", "SWE")
if (any(iListArgs2$VarObs %in% inPosVarObs)) {
idQSS <- which(iListArgs2$VarObs %in% inPosVarObs)
if (length(idQSS) == 1L) {
vecQSS <- iListArgs2$Obs
} else {
vecQSS <- unlist(iListArgs2$Obs[idQSS])
}
if (all(is.na(vecQSS))) {
stop("'Obs' contains only missing values", call. = FALSE)
}
if (min(vecQSS, na.rm = TRUE) < 0) {
stop(sprintf("'Obs' outside [0,Inf[ for \"%s\"", iListArgs2$VarObs), call. = FALSE)
}
}
if (is.null(iListArgs2$transfo) | !is.vector(iListArgs2$transfo) | length(iListArgs2$transfo) != 1 | !is.character(iListArgs2$transfo)) {
stop(msgTransfo, call. = FALSE)
}
isNotInTransfo <- !(iListArgs2$transfo %in% inTransfo)
if (any(isNotInTransfo)) {
powTransfo <- iListArgs2$transfo[isNotInTransfo]
powTransfo <- gsub("\\^|[[:alpha:]]", "", powTransfo)
numExpTransfo <- suppressWarnings(as.numeric(powTransfo))
if (any(is.na(numExpTransfo))) {
stop(msgTransfo, call. = FALSE)
}
iListArgs2$transfo <- paste0("^", iListArgs2$transfo)
}
if (!is.null(iListArgs2$Weights)) {
if (!is.vector(iListArgs2$Weights) | length(iListArgs2$Weights) != 1 | !is.numeric(iListArgs2$Weights) | any(iListArgs2$Weights < 0)) {
stop("'Weights' must be a single (list of) positive or equal to zero value(s)", call. = FALSE)
}
}
if (!is.null(iListArgs2$epsilon)) {
if (!is.vector(iListArgs2$epsilon) | length(iListArgs2$epsilon) != 1 | !is.numeric(iListArgs2$epsilon) | any(iListArgs2$epsilon <= 0)) {
stop("'epsilon' must be a single (list of) positive value(s)", call. = FALSE)
}
} else if (iListArgs2$transfo %in% c("log", "inv") & any(iListArgs2$Obs %in% 0) & warnings) {
warning("zeroes detected in Obs: the corresponding time-steps will be excluded by the 'ErrorCrit*' functions as the epsilon argument was set to NULL", call. = FALSE)
}
if (iListArgs2$transfo == "log" & warnings) {
warn_log_kge <- "we do not advise using the %s with a log transformation on Obs (see the details section in the 'CreateInputsCrit' help)"
if (identical(iListArgs2$FUN_CRIT, ErrorCrit_KGE)) {
warning(sprintf(warn_log_kge, "KGE"), call. = FALSE)
}
if (identical(iListArgs2$FUN_CRIT, ErrorCrit_KGE2)) {
warning(sprintf(warn_log_kge, "KGE'"), call. = FALSE)
}
}
iInputsCrit <- list(FUN_CRIT = iListArgs2$FUN_CRIT,
Obs = iListArgs2$Obs,
VarObs = iListArgs2$VarObs,
BoolCrit = iListArgs2$BoolCrit,
idLayer = iListArgs2$idLayer,
transfo = iListArgs2$transfo,
epsilon = iListArgs2$epsilon,
Weights = iListArgs2$Weights)
class(iInputsCrit) <- c("Single", "InputsCrit", ObjectClass)
return(iInputsCrit)
})
names(InputsCrit) <- paste0("IC", seq_along(InputsCrit))
listErrorCrit <- c("ErrorCrit_KGE", "ErrorCrit_KGE2", "ErrorCrit_NSE", "ErrorCrit_RMSE")
InputsCrit <- lapply(InputsCrit, function(i) {
i$FUN_CRIT <- listErrorCrit[sapply(listErrorCrit, function(j) identical(i$FUN_CRIT, get(j)))]
i
})
listVarObs <- sapply(InputsCrit, FUN = "[[", "VarObs")
inCnVarObs <- c("SCA", "SWE")
if (!"ZLayers" %in% names(InputsModel)) {
if(any(listVarObs %in% inCnVarObs)) {
stop(sprintf("'VarObs' can not be equal to %i if CemaNeige is not used",
paste(sapply(inCnVarObs, shQuote), collapse = " or ")))
}
} else {
listGroupLayer0 <- sapply(InputsCrit, FUN = "[[", "idLayer")
listGroupLayer <- rep(listVarObs, times = listGroupLayer0)
tabGroupLayer <- as.data.frame(table(listGroupLayer))
colnames(tabGroupLayer) <- c("VarObs", "freq")
nLayers <- length(InputsModel$ZLayers)
for (iInCnVarObs in inCnVarObs) {
if (any(listVarObs %in% iInCnVarObs)) {
if (tabGroupLayer[tabGroupLayer$VarObs %in% iInCnVarObs, "freq"] != nLayers) {
stop(sprintf("'Obs' must contain %i vector(s) about %s", nLayers, iInCnVarObs))
}
}
}
}
for (iInCnVarObs in unique(listVarObs)) {
if (iInCnVarObs == "Q") {
for (i in which(listVarObs == iInCnVarObs)) {
InputsCrit[[i]]$idLayer <- NA
}
} else {
aa <- listGroupLayer0[listVarObs == iInCnVarObs]
aa <- unname(aa)
bb <- cumsum(c(0, aa[-length(aa)]))
cc <- lapply(seq_along(aa), function(x) seq_len(aa[x]) + bb[x])
k <- 1
for (i in which(listVarObs == iInCnVarObs)) {
InputsCrit[[i]]$idLayer <- cc[[k]]
k <- k + 1
}
}
}
if (length(InputsCrit) < 2) {
InputsCrit <- InputsCrit[[1L]]
InputsCrit["Weights"] <- list(Weights = NULL)
} else {
if (any(sapply(listArgs$Weights, is.null))) {
for (iListArgs in InputsCrit) {
iListArgs$Weights <- NULL
}
class(InputsCrit) <- c("Multi", "InputsCrit", ObjectClass)
} else {
class(InputsCrit) <- c("Compo", "InputsCrit", ObjectClass)
}
combInputsCrit <- combn(x = length(InputsCrit), m = 2)
apply(combInputsCrit, MARGIN = 2, function(i) {
equalInputsCrit <- identical(InputsCrit[[i[1]]], InputsCrit[[i[2]]])
if(equalInputsCrit) {
warning(sprintf("elements %i and %i of the criteria list are identical. This might not be necessary", i[1], i[2]), call. = FALSE)
}
})
}
return(InputsCrit)
}
|
lslx <-
R6::R6Class(
classname = "lslx",
inherit = prelslx,
private = list(
model = "lslxModel",
data = "lslxData",
fitting = "lslxFitting"
)
)
|
tenant <- Sys.getenv("AZ_TEST_TENANT_ID")
app <- Sys.getenv("AZ_TEST_NATIVE_APP_ID")
team_name <- Sys.getenv("AZ_TEST_TEAM_NAME")
team_id <- Sys.getenv("AZ_TEST_TEAM_ID")
channel_name <- Sys.getenv("AZ_TEST_CHANNEL_NAME")
channel_id <- Sys.getenv("AZ_TEST_CHANNEL_ID")
if(tenant == "" || app == "" || team_name == "" || team_id == "" || channel_name == "" || channel_id == "")
skip("Teams tests skipped: Microsoft Graph credentials not set")
if(!interactive())
skip("Teams tests skipped: must be in interactive session")
tok <- get_test_token(tenant, app, c("Group.ReadWrite.All", "Directory.Read.All"))
if(is.null(tok))
skip("Teams tests skipped: no access to tenant")
team <- try(call_graph_endpoint(tok, file.path("teams", team_id)), silent=TRUE)
if(inherits(team, "try-error"))
skip("Teams tests skipped: service not available")
team <- ms_team$new(tok, tenant, team)
test_that("Teams client works",
{
expect_error(get_team(team_name=team_name, team_id=team_id, token=tok))
team1 <- get_team(team_name=team_name, token=tok)
expect_is(team1, "ms_team")
expect_identical(team1$properties$displayName, team_name)
team2 <- get_team(team_id=team_id, token=tok)
expect_is(team2, "ms_team")
expect_identical(team1$properties$id, team_id)
teams <- list_teams(token=tok)
expect_is(teams, "list")
expect_true(all(sapply(teams, inherits, "ms_team")))
})
test_that("Teams methods work",
{
expect_is(team, "ms_team")
drives <- team$list_drives()
expect_is(drives, "list")
expect_true(all(sapply(drives, inherits, "ms_drive")))
drv <- team$get_drive()
expect_is(drv, "ms_drive")
drv2 <- team$get_drive("Documents")
expect_is(drv2, "ms_drive")
grp <- team$get_group()
expect_is(grp, "az_group")
drv3 <- grp$get_drive("Documents")
expect_is(drv3, "ms_drive")
site <- team$get_sharepoint_site()
expect_is(site, "ms_site")
chans <- team$list_channels()
expect_is(chans, "list")
expect_true(all(sapply(chans, inherits, "ms_channel")))
chanpager <- team$list_channels(filter=sprintf("displayName eq '%s'", channel_name), n=NULL)
expect_is(chanpager, "ms_graph_pager")
chans0 <- chanpager$value
expect_true(length(chans0) == 1 && inherits(chans0[[1]], "ms_channel"))
expect_error(team$get_channel(channel_name, channel_id))
chan0 <- team$get_channel()
expect_is(chan0, "ms_channel")
f0 <- chan0$get_folder()
expect_is(f0, "ms_drive_item")
expect_is(f0$list_files(), "data.frame")
chan1 <- team$get_channel(channel_name=channel_name)
expect_is(chan1, "ms_channel")
f1 <- chan1$get_folder()
expect_is(f1, "ms_drive_item")
expect_is(f1$list_files(), "data.frame")
src <- write_file()
it <- chan1$upload_file(src)
expect_is(it, "ms_drive_item")
expect_silent(it$delete(confirm=FALSE))
chan2 <- team$get_channel(channel_id=channel_id)
expect_is(chan2, "ms_channel")
})
test_that("Team member methods work",
{
mlst <- team$list_members()
expect_is(mlst, "list")
expect_true(all(sapply(mlst, inherits, "ms_team_member")))
expect_true(all(sapply(mlst, function(obj) obj$type == "team member")))
mpager <- team$list_members(filter=sprintf("displayName eq '%s'", mlst[[1]]$properties$displayName), n=NULL)
expect_is(mpager, "ms_graph_pager")
mlst0 <- mpager$value
expect_true(length(mlst0) == 1 && inherits(mlst0[[1]], "ms_team_member"))
usr <- mlst[[1]]
usrname <- usr$properties$displayName
usremail <- usr$properties$email
usrid <- usr$properties$id
expect_false(is.null(usrname))
expect_false(is.null(usremail))
expect_false(is.null(usrid))
usr1 <- team$get_member(usrname)
expect_is(usr1, "ms_team_member")
expect_identical(usr$properties$id, usr1$properties$id)
usr2 <- team$get_member(email=usremail)
expect_is(usr2, "ms_team_member")
expect_identical(usr$properties$id, usr2$properties$id)
usr3 <- team$get_member(id=usrid)
expect_is(usr3, "ms_team_member")
expect_identical(usr$properties$id, usr3$properties$id)
aaduser <- usr$get_aaduser()
expect_is(aaduser, "az_user")
aaduser1 <- usr1$get_aaduser()
expect_is(aaduser1, "az_user")
})
|
context("gradient and Hessian")
library(uGMAR)
foo1 <- function(x) x^2
foo2 <- function(x, a=1, b=1) a*x[1]^2 - b*x[2]^2
foo3 <- function(x) x[1]^2 + log(x[2]) - x[3]^3
test_that("calc_gradient works correctly", {
expect_equal(calc_gradient(x=0, fn=foo1), 0, tolerance=1e-4)
expect_equal(calc_gradient(x=1, fn=foo1), 2, tolerance=1e-4)
expect_equal(calc_gradient(x=-2, fn=foo1), -4, tolerance=1e-4)
expect_equal(calc_gradient(x=c(0, 0), fn=foo2), c(0, 0), tolerance=1e-4)
expect_equal(calc_gradient(x=c(0, 0), fn=foo2, a=2, b=3), c(0, 0), tolerance=1e-4)
expect_equal(calc_gradient(x=c(1, 2), fn=foo2), c(2, -4), tolerance=1e-4)
expect_equal(calc_gradient(x=c(1, 2), fn=foo2, a=2, b=3), c(4, -12), tolerance=1e-4)
expect_equal(calc_gradient(x=c(1, 2, 3), fn=foo3), c(2.0, 0.5, -27.0), tolerance=1e-4)
expect_equal(calc_gradient(x=c(1, 2, 3), fn=foo3, varying_h=c(0.1, 0.2, 0.5)), c(2.0000000, 0.5016767, -27.2500000), tolerance=1e-4)
})
test_that("calc_hessian works correctly", {
expect_equal(calc_hessian(x=0, fn=foo1), as.matrix(2), tolerance=1e-4)
expect_equal(calc_hessian(x=1, fn=foo1), as.matrix(2), tolerance=1e-4)
expect_equal(calc_hessian(x=-2, fn=foo1), as.matrix(2), tolerance=1e-4)
expect_equal(calc_hessian(x=-2, fn=foo1, varying_h=1), as.matrix(2), tolerance=1e-4)
expect_equal(calc_hessian(x=c(0, 0), fn=foo2), diag(c(2, -2)), tolerance=1e-4)
expect_equal(calc_hessian(x=c(0, 0), fn=foo2, a=2, b=3), diag(c(4, -6)), tolerance=1e-4)
expect_equal(calc_hessian(x=c(1, 2), fn=foo2), diag(c(2, -2)), tolerance=1e-4)
expect_equal(calc_hessian(x=c(1, 2), fn=foo2, a=2, b=3), diag(c(4, -6)), tolerance=1e-4)
expect_equal(calc_hessian(x=c(1, 2), fn=foo2, varying_h=c(1, 2), a=2, b=3), diag(c(4, -6)), tolerance=1e-4)
expect_equal(calc_hessian(x=c(1, 2, 3), fn=foo3), diag(c(1.99998, -0.2500222, -18.00002)), tolerance=1e-4)
expect_equal(calc_hessian(x=c(1, 2, 3), fn=foo3, varying_h=c(0.1, 0.2, 0.3)), diag(c(2.000000, -0.2551375, -18.00000)), tolerance=1e-4)
})
|
sen2r <- function(param_list = NULL,
gui = NA,
preprocess = TRUE,
s2_levels = "l2a",
sel_sensor = c("s2a","s2b"),
online = TRUE,
server = "scihub",
order_lta = TRUE,
apihub = NA,
downloader = "builtin",
overwrite_safe = FALSE,
rm_safe = "no",
step_atmcorr = "auto",
sen2cor_use_dem = NA,
sen2cor_gipp = NA,
max_cloud_safe = 100,
timewindow = NA,
timeperiod = "full",
extent = NA,
extent_name = "sen2r",
s2tiles_selected = NA,
s2orbits_selected = NA,
list_prods = NA,
list_rgb = NA,
list_indices = NA,
index_source = "BOA",
rgb_ranges = NA,
mask_type = NA,
max_mask = 100,
mask_smooth = 0,
mask_buffer = 0,
clip_on_extent = TRUE,
extent_as_mask = FALSE,
reference_path = NA,
res = NA,
res_s2 = "10m",
unit = "Meter",
proj = NA,
resampling = "near",
resampling_scl = "near",
outformat = "GTiff",
rgb_outformat = "GTiff",
index_datatype = "Int16",
compression = "DEFLATE",
rgb_compression = "90",
overwrite = FALSE,
path_l1c = NA,
path_l2a = NA,
path_tiles = NA,
path_merged = NA,
path_out = NA,
path_rgb = NA,
path_indices = NA,
path_subdirs = TRUE,
thumbnails = TRUE,
parallel = FALSE,
processing_order = "by_groups",
use_python = NA,
tmpdir = NA,
rmtmp = TRUE,
log = NA) {
if (!is.na(log[2])) {
dir.create(dirname(log[2]), showWarnings=FALSE)
sink(log[2], split = TRUE, type = "output", append = TRUE)
}
if (!is.na(log[1])) {
dir.create(dirname(log[1]), showWarnings=FALSE)
logfile_message = file(log[1], open = "a")
sink(logfile_message, type="message")
}
sen2r_args <- formalArgs(.sen2r)
sen2r_args <- sen2r_args[!sen2r_args %in% c(".only_list_names", "globenv")]
pm_arg_passed <- logical(0)
for (i in seq_along(sen2r_args)) {
pm_arg_passed[i] <- !do.call(missing, list(sen2r_args[i]))
}
sen2r_env <- new.env()
names_out_created <- .sen2r(
param_list = param_list,
pm_arg_passed = pm_arg_passed,
gui = gui,
preprocess = preprocess,
s2_levels = s2_levels,
sel_sensor = sel_sensor,
online = online,
server = server,
order_lta = order_lta,
apihub = apihub,
downloader = downloader,
overwrite_safe = overwrite_safe,
rm_safe = rm_safe,
step_atmcorr = step_atmcorr,
sen2cor_use_dem = sen2cor_use_dem,
sen2cor_gipp = sen2cor_gipp,
max_cloud_safe = max_cloud_safe,
timewindow = timewindow,
timeperiod = timeperiod,
extent = extent,
extent_name = extent_name,
s2tiles_selected = s2tiles_selected,
s2orbits_selected = s2orbits_selected,
list_prods = list_prods,
list_rgb = list_rgb,
list_indices = list_indices,
index_source = index_source,
rgb_ranges = rgb_ranges,
mask_type = mask_type,
max_mask = max_mask,
mask_smooth = mask_smooth,
mask_buffer = mask_buffer,
clip_on_extent = clip_on_extent,
extent_as_mask = extent_as_mask,
reference_path = reference_path,
res = res,
res_s2 = res_s2,
unit = unit,
proj = proj,
resampling = resampling,
resampling_scl = resampling_scl,
outformat = outformat,
rgb_outformat = rgb_outformat,
index_datatype = index_datatype,
compression = compression,
rgb_compression = rgb_compression,
overwrite = overwrite,
path_l1c = path_l1c,
path_l2a = path_l2a,
path_tiles = path_tiles,
path_merged = path_merged,
path_out = path_out,
path_rgb = path_rgb,
path_indices = path_indices,
path_subdirs = path_subdirs,
thumbnails = thumbnails,
parallel = parallel,
processing_order = processing_order,
use_python = use_python,
tmpdir = tmpdir,
rmtmp = rmtmp,
log = log,
globenv = sen2r_env,
.only_list_names = FALSE
)
if (!is.na(log[2])) {
sink(type = "output")
}
if (!is.na(log[1])) {
sink(type = "message"); close(logfile_message)
}
if (!is.null(sen2r_env$internal_log)) {
sink(type = "message")
sen2r_env$internal_log <- NULL
}
return(invisible(names_out_created))
}
.sen2r <- function(param_list,
pm_arg_passed,
gui,
preprocess,
s2_levels,
sel_sensor,
online,
server,
order_lta,
apihub,
downloader,
overwrite_safe,
rm_safe,
step_atmcorr,
sen2cor_use_dem,
sen2cor_gipp,
max_cloud_safe,
timewindow,
timeperiod,
extent,
extent_name,
s2tiles_selected,
s2orbits_selected,
list_prods,
list_rgb,
list_indices,
index_source,
rgb_ranges,
mask_type,
max_mask,
mask_smooth,
mask_buffer,
clip_on_extent,
extent_as_mask,
reference_path,
res,
res_s2,
unit,
proj,
resampling,
resampling_scl,
outformat,
rgb_outformat,
index_datatype,
compression,
rgb_compression,
overwrite,
path_l1c,
path_l2a,
path_tiles,
path_merged,
path_out,
path_rgb,
path_indices,
path_subdirs,
thumbnails,
parallel,
processing_order,
use_python = NA,
tmpdir,
rmtmp,
log,
globenv,
.only_list_names = FALSE) {
. <- sensing_datetime <- creation_datetime <- mission <- level <- id_orbit <-
id_tile <- name <- id_baseline <- prod_type <- name <- sel_group_A <-
i_group_A <- sel_apihub_path <- i_group_B <- sensing_date <- lta <-
centroid_x <- centroid_y <- res_type <-path <- footprint <- sel_out <-
NULL
print_message(
type = "message",
date = TRUE,
"
)
if (requireNamespace("sf", quietly = TRUE)) {
try({
invisible(capture.output(sf_use_s2_prev <- sf::sf_use_s2(FALSE)))
on.exit(invisible(capture.output(sf::sf_use_s2(sf_use_s2_prev))))
}, silent = TRUE)
}
pm_def <- formals(sen2r::sen2r)
pm_def <- sapply(pm_def[!names(pm_def) %in% c("param_list","gui","use_python","tmpdir","rmtmp")], eval)
sen2r_args <- formalArgs(.sen2r)
pm_arg <- sapply(sen2r_args[pm_arg_passed], function(x){
do.call(get, list(x))
}, simplify=FALSE)
pm_arg <- pm_arg[!names(pm_arg) %in% c("param_list","gui","use_python","tmpdir","rmtmp")]
pm_list <- if (is(param_list, "character")) {
jsonlite::fromJSON(param_list)
} else if (is(param_list, "list")) {
param_list
} else {
list("pkg_version" = packageVersion("sen2r"))
}
pm <- pm_def
pm[names(pm_list)] <- pm_list
pm[names(pm_arg)] <- pm_arg
if (is.na(gui)) {
gui <- if (is.null(param_list)) {TRUE} else {FALSE}
}
suppressWarnings(suppressMessages({
pm <- check_param_list(
pm,
type = if (gui) {"message"} else {"error"},
check_paths = FALSE, correct = TRUE
)
}))
if (is.null(pm_list$pkg_version)) {
if (!is.null(pm_list$fidolasen_version)) {
pm_list$pkg_version <- pm_list$fidolasen_version
} else {
pm_list$pkg_version <- package_version("0.2.0")
}
}
if (packageVersion("sen2r") > package_version(pm_list$pkg_version)) {
if (interactive() & !gui) {
open_gui <- NA
while(is.na(open_gui)) {
open_gui_prompt <- print_message(
type="waiting",
"\nThe parameter file was created with an old version of the package: ",
"would you like to open a GUI and check that the input parameters are correct? (y/n)\n",
"Alternatively, press ESC to interrupt and check the parameter file manually."
)
open_gui <- if (grepl("^[Yy]",open_gui_prompt)) {
gui <- TRUE
TRUE
} else if (grepl("^[Nn]",open_gui_prompt)) {
FALSE
} else {
NA
}
}
} else {
print_message(
type="warning",
"The parameter file was created with an old version of the package ",
"(this could lead to errors)."
)
}
}
pm_prev <- pm
if (gui==TRUE) {
print_message(
type = "message",
date = TRUE,
"Launching GUI..."
)
pm <- .s2_gui(pm, par_fun = "sen2r")
if (is.null(pm)) {
print_message(
type = "message",
date = TRUE,
"Program interrupted by the user (GUI closed)."
)
sen2r_output <- character(0)
attr(sen2r_output, "status") <- data.frame(completed = FALSE)
return(invisible(sen2r_output))
}
print_message(
type = "message",
date = TRUE,
"Gui closed by the user. Starting processing."
)
}
pm <- check_param_list(pm, type = "error", check_paths = TRUE, correct = TRUE)
if (pm$online == TRUE & "gcloud" %in% pm$server) {
if (!check_gcloud_connection()) {
print_message(
type = "error",
"Impossible to reach the Sentinel-2 bucket on Google Cloud ",
"(internet connection may be down)."
)
}
}
if (pm$online == TRUE & "scihub" %in% pm$server) {
if (!check_scihub_connection()) {
print_message(
type = "error",
"Impossible to reach the SciHub server ",
"(internet connection or SciHub may be down)."
)
}
}
outpm_dir <- file.path(dirname(attr(load_binpaths(), "path")), "proc_par")
dir.create(outpm_dir, showWarnings = FALSE)
outpm_path <- file.path(
outpm_dir,
strftime(Sys.time(), format = "s2proc_%Y%m%d_%H%M%S.json")
)
pm_exported <- pm[!names(pm) %in% c(".only_list_names", "globenv")]
if (inherits(pm$extent, "sf") | inherits(pm$extent, "sfc")) {
pm_exported$extent <- geojson_json(
st_transform(pm$extent, 4326),
pretty = TRUE
)
}
if (inherits(pm$pkg_version, "numeric_version")) {
pm_exported$pkg_version <- as.character(pm$pkg_version)
}
writeLines(toJSON(pm_exported, pretty = TRUE), outpm_path)
attr(pm, "outpath") <- outpm_path
out_attributes <- list()
out_attributes[["procpath"]] <- attr(pm, "outpath")
if (all(is.na(pm_prev$log), length(nn(pm$log))>0, !is.na(pm$log))) {
if (!is.na(pm$log[1]) & is.na(pm_prev$log[1])) {
print_message(
type = "message",
"Output messages are redirected to log file \"",pm$log[1],"\"."
)
dir.create(dirname(pm$log[1]), showWarnings=FALSE)
logfile_message = file(pm$log[1], open = "a")
sink(logfile_message, type="message")
assign("internal_log", pm$log[1], envir = globenv)
}
}
rm(pm_prev)
.log_message <- pm$log[1]
.log_output <- pm$log[2]
if (grepl("^[0-9A-Z]{5}$",extent_name)) {
print_message(
type = "error",
"\"extent_name\" cannot have the same structure of a tile ID ",
"(two numeric and by three uppercase character values)."
)
} else if (grepl("^[0-9A-Z]{5}[a-z]$",extent_name)) {
print_message(
type = "error",
"\"extent_name\" cannot have the same structure of a tile ID ",
"(two numeric and by three uppercase character values)",
"followed by a lowercase letter."
)
} else if (grepl("[\\.\\_]",extent_name)) {
print_message(
type = "error",
"\"extent_name\" cannot contain points nor underscores."
)
}
if (is.null(pm$parallel)) {pm$parallel <- parallel}
if (is.null(pm$processing_order)) {pm$processing_order <- processing_order}
if (pm$preprocess == FALSE & !pm$processing_order %in% c(1,"by_step")) {
print_message(
type = "warning",
"Only processing_order = \"by_step\" is accepted if preprocess = FALSE."
)
pm$processing_order <- "by_step"
}
if (!pm$processing_order %in% c(
1,"by_step",
2,"by_date",
3,"mixed",
4,"by_groups"
)) {
print_message(
type = "warning",
"processing_order = \"",pm$processing_order,"\"not recognised, ",
"using default \"by_step\"."
)
pm$processing_order <- "by_step"
}
if (pm$parallel == TRUE | is.numeric(pm$parallel)) {
if (pm$processing_order %in% c(1,"by_step", 2,"by_date")) {
parallel_groups_A <- FALSE
parallel_groups_B <- FALSE
parallel_steps <- pm$parallel
} else if (pm$processing_order %in% c(3,"mixed", 4,"by_groups")) {
parallel_groups_A <- FALSE
parallel_groups_B <- pm$parallel
parallel_steps <- FALSE
}
} else {
parallel_groups_A <- FALSE
parallel_groups_B <- FALSE
parallel_steps <- FALSE
}
if (is.na(tmpdir)) {
tmpdir <- if (
pm$outformat == "VRT" &
!all(is.na(pm[c("path_out","path_rgb","path_indices","path_tiles","path_merged")]))
) {
main_dir <- unlist(pm[c("path_out","path_rgb","path_indices","path_tiles","path_merged")])[
!is.na(pm[c("path_out","path_rgb","path_indices","path_tiles","path_merged")])
][1]
dir.create(main_dir, showWarnings=FALSE)
file.path(main_dir, ".vrt")
} else {
tempfile(pattern="sen2r_")
}
}
if (pm$outformat == "VRT") {
rmtmp <- FALSE
}
dir.create(tmpdir, showWarnings=FALSE)
l1c_prods <- c("TOA")
l2a_prods <- c("BOA","SCL","TCI","AOT","WVP","CLD","SNW")
nomsk <- c("SCL", "CLD", "SNW", "AOT")
list_prods <- if (!is.na(pm$mask_type)) {
unique(c(pm$list_prods, "SCL"))
} else {
pm$list_prods
}
if (any(!is.na(pm$list_rgb))) {
list_prods <- unique(c(
list_prods,
paste0(unique(substr(pm$list_rgb,7,7)),"OA")
))
}
if (any(!is.na(pm$list_indices))) {
list_prods <- unique(c(list_prods, pm$index_source))
}
list_prods <- list_prods[!is.na(list_prods)]
if (pm$preprocess == TRUE && length(list_prods) == 0) {
print_message(
type ="message",
"No output products selected. Use \"preprocess = FALSE\" if you only want to download S2 images.\n"
)
print_message(
type = "message",
date = TRUE,
"
)
return(invisible(character(0)))
}
if (pm$preprocess==TRUE) {
pm$s2_levels <- c(
if (any(list_prods %in% l1c_prods)) {"l1c"},
if (any(list_prods %in% l2a_prods)) {"l2a"}
)
}
parent_paths <- sapply(
pm[c("path_l1c","path_l2a","path_tiles","path_merged","path_out","path_rgb","path_indices")],
function(x){if(is.na(nn(x))){NA}else{dirname(x)}}
)
parent_paths <- as.character(na.omit(unique(parent_paths)))
paths_exist <- sapply(parent_paths, file.exists)
if (any(!paths_exist)) {
print_message(
type="error",
"The following output ",
if (sum(!paths_exist)==1) {"directory does "} else {"directories do "},
"not exist:\n",
paste(names(paths_exist[!paths_exist]),collapse="\n"),
".\nPlease create ",
if (sum(!paths_exist)==1) {"it "} else {"them "},
"before continuing."
)
}
sapply(
pm[c("path_l1c","path_l2a","path_tiles","path_merged","path_out","path_rgb","path_indices")],
function(x) {if(is.na(nn(x))){NA}else{dir.create(x, recursive = FALSE, showWarnings = FALSE)}}
)
if (pm$outformat == "BigTIFF") {
pm$outformat <- "GTiff"
bigtiff <- TRUE
} else {
bigtiff <- FALSE
}
suppressWarnings(gdal_formats <- fromJSON(
system.file("extdata/settings/gdal_formats.json",package="sen2r")
)$drivers)
sel_driver <- gdal_formats[gdal_formats$name==pm$outformat,]
sel_rgb_driver <- gdal_formats[gdal_formats$name==pm$rgb_outformat,]
s2_lists <- s2_lists_islta <- s2_lists_footprints <- list()
if (pm$online == TRUE) {
print_message(
type = "message",
date = TRUE,
"Searching for available SAFE products..."
)
if ("l1c" %in% pm$s2_levels) {
s2_lists[["l1c"]] <- s2_list(
spatial_extent = pm$extent,
time_interval = pm$timewindow,
time_period = pm$timeperiod,
tile = if (any(length(nn(pm$s2tiles_selected))==0, all(is.na(pm$s2tiles_selected)))) {
tiles_intersects(pm$extent)
} else {
pm$s2tiles_selected
},
orbit = pm$s2orbits_selected,
level = "L1C",
server = pm$server,
max_cloud = pm$max_cloud_safe,
availability = "check",
apihub = pm$apihub
)
s2_lists_footprints[["l1c"]] <- nn(attr(s2_lists[["l1c"]], "footprint"))
s2_lists_islta[["l1c"]] <- !nn(attr(s2_lists[["l1c"]], "online"))
names(s2_lists_islta[["l1c"]]) <- names(s2_lists[["l1c"]])
}
if ("l2a" %in% pm$s2_levels) {
s2_lists[["l2a"]] <- s2_list(
spatial_extent = pm$extent,
time_interval = pm$timewindow,
time_period = pm$timeperiod,
tile = if (any(length(nn(pm$s2tiles_selected))==0, all(is.na(pm$s2tiles_selected)))) {
tiles_intersects(pm$extent)
} else {
pm$s2tiles_selected
},
orbit = pm$s2orbits_selected,
level = if (pm$step_atmcorr=="auto") {
"auto"
} else if (pm$step_atmcorr=="l2a") {
"L2A"
} else if (pm$step_atmcorr %in% c("scihub")) {
"L1C"
},
server = pm$server,
max_cloud = pm$max_cloud_safe,
availability = "check",
apihub = pm$apihub
)
s2_lists_footprints[["l2a"]] <- nn(attr(s2_lists[["l2a"]], "footprint"))
s2_lists_islta[["l2a"]] <- !nn(attr(s2_lists[["l2a"]], "online"))
names(s2_lists_islta[["l2a"]]) <- names(s2_lists[["l2a"]])
}
} else {
if ("l1c" %in% pm$s2_levels) {
s2_lists[["l1c"]] <- list.files(pm$path_l1c, "\\.SAFE$")
suppressWarnings({
s2_lists_footprints[["l1c"]] <- safe_getMetadata(
file.path(pm$path_l1c, s2_lists[["l1c"]]),
"footprint", abort = FALSE, format = "vector", simplify = TRUE
)
})
}
if ("l2a" %in% pm$s2_levels) {
s2_lists[["l2a"]] <- if (pm$step_atmcorr=="l2a") {
list.files(pm$path_l2a, "\\.SAFE$", full.names = TRUE)
} else if (pm$step_atmcorr %in% c("scihub")) {
list.files(pm$path_l1c, "\\.SAFE$", full.names = TRUE)
} else if (pm$step_atmcorr=="auto") {
all_l1c <- list.files(pm$path_l1c, "\\.SAFE$", full.names = TRUE)
all_l2a <- list.files(pm$path_l2a, "\\.SAFE$", full.names = TRUE)
c(
all_l2a,
all_l1c[
!gsub(
"\\_OPER\\_","_USER_",
gsub(
"S2([AB])\\_((?:OPER\\_PRD\\_)?)MSIL1C\\_","S2\\1\\_\\2MSIL2A\\_",
all_l1c
)
) %in% all_l2a
]
)
}
suppressWarnings({
s2_lists_footprints[["l2a"]] <- safe_getMetadata(
s2_lists[["l2a"]], "footprint",
abort = FALSE, format = "vector", simplify = TRUE
)
})
s2_lists[["l2a"]] <- basename(s2_lists[["l2a"]])
}
s2_lists <- lapply(s2_lists, function(l) {
safe_getMetadata(l, "level", abort = FALSE, format = "vector", simplify = TRUE)
})
s2_lists_whichna <- lapply(s2_lists, function(l) {is.na(l)})
s2_lists <- lapply(seq_along(s2_lists), function(i) {
s2_lists[[i]][!s2_lists_whichna[[i]]]
})
s2_lists_footprints <- lapply(seq_along(s2_lists_footprints), function(i) {
s2_lists_footprints[[i]][!s2_lists_whichna[[i]]]
})
}
s2_list <- unlist(s2_lists)[!duplicated(unlist(lapply(s2_lists, names)))]
s2_list_footprints <- unlist(s2_lists_footprints)[!duplicated(unlist(lapply(s2_lists, names)))]
s2_list_islta <- unlist(s2_lists_islta)[!duplicated(unlist(lapply(s2_lists_islta, names)))]
rm(s2_lists, s2_lists_islta, s2_lists_footprints)
if (length(s2_list)==0) {
print_message(
type = "message",
date = TRUE,
if (pm$online == FALSE) {
"No SAFE products which match the settings were found locally."
} else {
"No SAFE products matching the settings were found."
}
)
}
if (length(nn(s2_list))>0) {
names(s2_list) <- gsub("^l[12][ac]\\.","",names(s2_list))
}
s2_dt <- safe_getMetadata(
names(s2_list),
info = c("nameinfo"), format = "data.table"
)
s2_dt$footprint <- s2_list_footprints
if (nrow(s2_dt)==0) {
s2_dt <- safe_getMetadata(
"S2A_MSIL2A_20000101T000000_N0200_R001_T01TAA_20000101T000000.SAFE",
info = "nameinfo", format = "data.table"
)[-1,]
s2_dt$footprint <- character(0)
}
s2_dt[,"lta":=if (is.null(s2_list_islta)) {FALSE} else {s2_list_islta}]
s2_dt[,c("name","url"):=list(nn(names(s2_list)),nn(s2_list))]
if (nrow(s2_dt) > 0) {
s2_footprint_sf_l <- lapply(s2_dt$footprint, function(f) {
tryCatch(
st_as_sfc(f, crs = 4326),
error = function(e) {st_sfc(st_polygon(), crs = 4326)}
)
})
s2_dt_centroid <- suppressMessages(round(st_coordinates(
st_centroid(st_transform(do.call("c",s2_footprint_sf_l), 3857))
), -3))
s2_dt[,c("centroid_x", "centroid_y") := list(s2_dt_centroid[,"X"], s2_dt_centroid[,"Y"])]
} else {
s2_dt[,c("centroid_x", "centroid_y") := list(numeric(), numeric())]
}
s2_existing_list <- list.files(unique(c(pm$path_l1c,pm$path_l2a)), "\\.SAFE$", full.names = TRUE)
if (length(s2_existing_list) > 0 & pm$online == TRUE) {
s2_isvalid <- safe_isvalid(s2_existing_list, check_file = FALSE)
s2_existing_list <- s2_existing_list[s2_isvalid]
s2_existing_dt <- safe_getMetadata(
s2_existing_list,
info = c("name", "mission", "level", "sensing_datetime", "id_orbit",
"id_tile", "creation_datetime", "footprint"),
format = "data.table"
)
s2_existing_dt_centroid <- suppressMessages(round(st_coordinates(
st_centroid(st_transform(st_as_sfc(s2_existing_dt$footprint, crs = 4326), 3857))
), -3))
s2_existing_dt[,c("centroid_x", "centroid_y") := list(s2_existing_dt_centroid[,"X"], s2_existing_dt_centroid[,"Y"])]
s2_meta_pasted <- s2_dt[,list("V1" = paste(
mission,
level,
strftime(sensing_datetime,"%y%m%d"),
id_orbit,
centroid_x, centroid_y
))]$V1
s2_existing_meta_pasted <- s2_existing_dt[,list("V1" = paste(
mission,
level,
strftime(sensing_datetime,"%y%m%d"),
id_orbit,
centroid_x, centroid_y
))]$V1
s2_existing_list_touse <- s2_existing_dt[s2_existing_meta_pasted %in% s2_meta_pasted,]$name
if (!pm$overwrite_safe) {
s2_dt[
!is.na(match(s2_meta_pasted, s2_existing_meta_pasted)),
name := basename(s2_existing_list)[na.omit(match(s2_meta_pasted, s2_existing_meta_pasted))]
]
s2_dt[!is.na(match(s2_meta_pasted, s2_existing_meta_pasted)), c("url","lta"):=list("",FALSE)]
}
}
s2_dt <- if (!is.null(s2_dt$id_baseline)) {
s2_dt[order(-sensing_datetime, lta, -creation_datetime, -id_baseline),]
} else {
s2_dt[order(-sensing_datetime, lta, -creation_datetime),]
}
s2_dt <- s2_dt[!duplicated(paste(
prod_type, version, mission, level,
sensing_datetime, id_orbit,
centroid_x, centroid_y
)),]
if (is.null(s2_dt$id_tile)) {
s2_dt$id_tile <- as.character(NA)
}
s2_dt <- s2_dt[mission %in% toupper(substr(pm$sel_sensor,2,3)),]
if (!anyNA(pm$timewindow)) {
s2_dt <- s2_dt[as.Date(sensing_datetime) >= pm$timewindow[1] &
as.Date(sensing_datetime) <= pm$timewindow[2],]
}
if (
pm$online == FALSE &&
identical(pm$extent, NA) &&
identical(pm$s2tiles_selected, NA)
) {
pm$s2tiles_selected <- unique(s2_dt$id_tile)
}
if (pm$online == FALSE && nrow(s2_dt) == 0) {
print_message(
type = "error",
"There are no images on your machine acquired ",
"in the specified time period."
)
}
if (!any(length(nn(pm$s2tiles_selected))==0, all(is.na(pm$s2tiles_selected)))) {
s2_dt <- s2_dt[id_tile %in% c(as.character(pm$s2tiles_selected),NA),]
} else if (all(is.na(pm$extent)) && all(st_is_valid(pm$extent))) {
s2tiles_sel_id <- tiles_intersects(pm$extent)
s2_dt <- s2_dt[id_tile %in% s2tiles_sel_id,]
}
if (all(!is.na(pm$s2orbits_selected))) {
s2_dt <- s2_dt[id_orbit %in% pm$s2orbits_selected,]
}
if (all(!is(pm$extent, "logical"), !anyNA(pm$extent), !is.na(s2_dt$footprint))) {
extent_dissolved <- suppressMessages(st_union(pm$extent))
if (any(!st_is_valid(extent_dissolved))) {
extent_dissolved <- st_make_valid(extent_dissolved)
}
s2_dt <- s2_dt[suppressMessages(st_intersects(
extent_dissolved,
st_transform(st_as_sfc(s2_dt$footprint, crs = 4326), st_crs2(pm$extent))
))[[1]],]
}
s2_lta_dates <- s2_dt[
,list(lta = any(lta)),
by = list(sensing_date = as.Date(sensing_datetime))
][lta==TRUE, sensing_date]
s2_list_lta <- s2_dt[lta==TRUE, url]
s2_list_ign <- s2_dt[lta==FALSE & as.Date(sensing_datetime) %in% s2_lta_dates, url]
s2_list_l1c <- s2_dt[lta==FALSE & !as.Date(sensing_datetime) %in% s2_lta_dates & level=="1C", url]
s2_list_l2a <- s2_dt[lta==FALSE & !as.Date(sensing_datetime) %in% s2_lta_dates & level=="2A", url]
names(s2_list_lta) <- s2_dt[lta==TRUE, name]
names(s2_list_ign) <- s2_dt[lta==FALSE & as.Date(sensing_datetime) %in% s2_lta_dates, name]
names(s2_list_l1c) <- s2_dt[lta==FALSE & !as.Date(sensing_datetime) %in% s2_lta_dates & level=="1C", name]
names(s2_list_l2a) <- s2_dt[lta==FALSE & !as.Date(sensing_datetime) %in% s2_lta_dates & level=="2A", name]
s2_list_ordered <- if (pm$online == TRUE & pm$order_lta == TRUE) {
.s2_order(
s2_list_lta,
.s2_availability = rep(FALSE, length(s2_list_lta)),
apihub = pm$apihub,
.log_path = FALSE
)
} else {
character(0)
}
out_attributes[["ltapath"]] <- attr(s2_list_ordered, "path")
if (pm$step_atmcorr %in% c("auto","scihub")) {
s2_list_l1c_tocorrect <- if (pm$overwrite_safe==FALSE) {
s2_list_l1c[
!gsub(
"\\_OPER\\_","_USER_",
gsub(
"^S2([AB])\\_((?:OPER\\_PRD\\_)?)MSIL1C\\_([0-9T]{15})\\_N[0-9]{4}\\_",
"S2\\1\\_\\2MSIL2A\\_\\3\\_NXXXX\\_",
names(s2_list_l1c)
)
) %in% gsub("\\_N[0-9]{4}\\_", "_NXXXX_", names(s2_list_l2a))
]
} else {
s2_list_l1c
}
if (length(s2_list_l1c_tocorrect)>0) {
s2_list_l2a_tobecorrected <- gsub(
"\\_OPER\\_","_USER_",
gsub(
"^S2([AB])\\_((?:OPER\\_PRD\\_)?)MSIL1C\\_","S2\\1\\_\\2MSIL2A\\_",
names(s2_list_l1c_tocorrect)
)
)
names(s2_list_l2a_tobecorrected) <- basename(s2_list_l2a_tobecorrected)
s2_list_l2a_exp <- c(s2_list_l2a,s2_list_l2a_tobecorrected)
} else {
s2_list_l2a_exp <- s2_list_l2a
}
} else {
s2_list_l1c_tocorrect <- character()
s2_list_l2a_exp <- s2_list_l2a
}
if (length(s2_list_lta) == dim(s2_dt)[1]) {
status <- sen2r_process_report(
s2_list_ordered = s2_list_ordered,
pm = pm,
download_only = !pm$preprocess
)
sen2r_output <- character(0)
attr(sen2r_output, "status") <- status
attr(sen2r_output, "ltapath") <- attr(s2_list_ordered, "path")
return(invisible(sen2r_output))
}
if (pm$preprocess == TRUE) {
ignorelist <- read_ignorelist(pm = pm, param_list = param_list)
if (all(c("l1c", "l2a") %in% pm$s2_levels)) {
s2_meta_l2a <- apply(
safe_getMetadata(
names(s2_list_l2a_exp),
info = c("nameinfo"), format = "data.table"
)[,list(mission, sensing_datetime, id_orbit, id_tile)],
1, paste, collapse = "_"
)
s2_meta_l1c <- apply(
safe_getMetadata(
names(s2_list_l1c),
info = c("nameinfo"), format = "data.table"
)[,list(mission, sensing_datetime, id_orbit, id_tile)],
1, paste, collapse = "_"
)
s2_l2a_orphan <- !s2_meta_l2a %in% s2_meta_l1c
s2_l1c_orphan <- !s2_meta_l1c %in% s2_meta_l2a
if (any(s2_l2a_orphan, s2_l1c_orphan)) {
print_message(
type = "warning",
"Some SAFE archive is present only as Level-1C or Level-2A, ",
"while both are required. ",
"To prevent errors, only coupled products will be used. ",
if (any(s2_l1c_orphan)) {paste0(
"This issue can be avoided by setting argument \"step_atmcorr\" ",
"to 'auto' or 'scihub', or \"online\" to TRUE, ",
"or re-launching the processing when products ordered from the ",
"Long Term Archive will be made available, ",
"so that missing Level-2A can be produced or downloaded."
)}
)
s2_list_l2a_exp <- s2_list_l2a_exp[!s2_l2a_orphan]
s2_list_l1c <- s2_list_l1c[!s2_l1c_orphan]
}
}
print_message(type = "message", date = TRUE, "Computing output names...")
s2names <- compute_s2_paths(
pm=pm,
s2_list_l1c=s2_list_l1c, s2_list_l2a=s2_list_l2a_exp,
tmpdir=tmpdir,
list_prods=list_prods,
force_tiles = TRUE,
ignorelist = ignorelist
)
out_ext <- attr(s2names, "out_ext")
out_format <- attr(s2names, "out_format")
s2_tiles <- names(sort(table(tile_utmzone(s2_dt$id_tile)), decreasing = TRUE))
out_proj <- if (!is.na(pm$proj)) {st_crs2(pm$proj)} else {
if (is.null(s2_tiles)) {NA} else {st_crs2(s2_tiles[1])}
}
gdal_tap <- any(
length(s2_tiles) > 2,
!is.null(out_proj$epsg) && !is.na(out_proj$epsg) &&
out_proj$epsg > 32601 && out_proj$epsg < 32799
)
s2_mask_extent <- if (is(pm$extent, "vector") && is.na(pm$extent)) {
NULL
} else if (anyNA(pm$extent$geometry)) {
NULL
} else if (pm$extent_as_mask==TRUE) {
st_combine(pm$extent)
} else {
st_combine(
suppressWarnings(st_cast(st_cast(pm$extent,"POLYGON"), "LINESTRING"))
)
}
if (inherits(s2_mask_extent, c("sf", "sfc")) && any(!st_is_valid(s2_mask_extent))) {
s2_mask_extent <- st_make_valid(s2_mask_extent)
}
if (all(unlist(sapply(s2names$new, sapply, length)) == 0)) {
if (all(unlist(sapply(s2names$exp, sapply, length)) == 0)) {
if (length(ignorelist$dates_cloudcovered) + length(ignorelist$names_missing) == 0) {
print_message(
type = "message",
date = TRUE,
"No S2 products matching the query settings were found; please ",
if (pm$online == FALSE) {"try in online mode, or "},
"specify less restrictive settings."
)
} else {
print_message(
type = "message",
date = TRUE,
"All S2 products matching the query settings were ignored because ",
"they are included in the list of files with cloudiness above the ",
"\"max_mask\" threshold ",
"or in the list of files for which previous processing failed",
" (see the \"Details\" section of sen2r() documentation)."
)
}
} else {
print_message(
type = "message",
date = TRUE,
"All the required output files for dates not on lta already exist; nothing to do. ",
"To reprocess, run sen2r() with the argument overwrite = TRUE, or ",
if (pm$online == FALSE) {"try running sen2r() in online mode, or "},
"specify a different output directory."
)
}
ignorelist_path <- write_ignorelist(
pm = pm,
dates_cloudcovered = ignorelist$dates_cloudcovered,
names_missing = ignorelist$names_missing,
param_list = param_list
)
clean_ignorelist(pm = pm, param_list = param_list)
sen2r_output <- character(0)
attributes(sen2r_output) <- c(attributes(sen2r_output), out_attributes)
status <- sen2r_process_report(
s2_list_ordered = s2_list_ordered,
s2names = s2names,
pm =pm,
ignorelist = ignorelist
)
attr(sen2r_output, "status") <- status
return(invisible(sen2r_output))
}
}
if (pm$preprocess == TRUE & .only_list_names == TRUE) {
sen2r_output <- s2names
attributes(sen2r_output) <- c(attributes(sen2r_output), out_attributes)
return(sen2r_output)
}
if (pm$preprocess==TRUE) {
exi_meta <- cbind(
sen2r_getElements(unlist(s2names$exi[c("indices","rgb","masked","warped_nomsk","warped")])),
data.frame(path=unlist(s2names$exi[c("indices","rgb","masked","warped_nomsk","warped")]))
)
exi_meta[,res_type:=ifelse(prod_type %in% c("SCL","CLD","SNW"), "res20", "res10")]
reference_exi_paths <- if (nrow(exi_meta)>0) {
exi_meta[!duplicated(res_type),list(res_type,path)]
} else {
data.table(res_type = character(0), path = character(0))
}
}
if (pm$preprocess==TRUE) {
s2_list_l2a_req <- s2_list_l2a[
names(s2_list_l2a) %in% basename(nn(s2names$req$tiles$L2A))
]
safe_names_l2a_reqout <- s2names$req$tiles$L2A[
!gsub("\\_N[0-9]{4}\\_", "_NXXXX_", basename(nn(s2names$req$tiles$L2A))) %in%
gsub("\\_N[0-9]{4}\\_", "_NXXXX_", names(s2_list_l2a))
]
safe_names_l1c_tocorrect <- gsub(
"\\_USER\\_","_OPER_",
gsub(
"^S2([AB])\\_((?:USER\\_PRD\\_)?)MSIL2A\\_","S2\\1\\_\\2MSIL1C\\_",
basename(nn(safe_names_l2a_reqout))
)
)
s2_list_l1c_req <- s2_list_l1c[
gsub("\\_N[0-9]{4}\\_", "_NXXXX_", names(s2_list_l1c)) %in%
gsub("\\_N[0-9]{4}\\_", "_NXXXX_", c(safe_names_l1c_tocorrect,basename(nn(s2names$req$tiles$L1C))))
]
s2_dt <- s2_dt[name %in% c(names(s2_list_l1c_req),names(s2_list_l2a_req)),]
s2_list_l1c <- s2_list_l1c_req
s2_list_l2a <- s2_list_l2a_req
} else {
safe_names_l1c_tocorrect <- names(s2_list_l1c_tocorrect)
}
max_n_cores <- if (is.numeric(pm$parallel)) {
as.integer(pm$parallel)
} else if (pm$parallel == FALSE) {
1
} else {
min(parallel::detectCores()-1, 8)
}
if (pm$processing_order %in% c(2,"by_date", 4,"by_groups")) {
sen2r_dates_A <- if (pm$preprocess == TRUE) {
sort(unique(sen2r_getElements(
unlist(s2names$new)
)$sensing_date))
} else {
s2names <- list()
sort(unique(as.Date(s2_dt$sensing_datetime)))
}
sen2r_groups_A <- if (pm$processing_order %in% c(2,"by_date")) {
setNames(as.list(sen2r_dates_A), sen2r_dates_A)
} else if (pm$processing_order %in% c(4,"by_groups")) {
suppressWarnings(split(
sen2r_dates_A,
seq_len(ceiling(length(sen2r_dates_A)/max_n_cores))
))
}
s2names_groups_A <- lapply(sen2r_groups_A, function(d) {
d_string <- strftime(d, "%Y%m%d")
sapply(s2names, function(v1) {
sapply(v1, function(v2) {
sapply(v2, function(v3) {
v3[grepl(paste0("[12][ABC]\\_((",paste(d_string,collapse=")|("),"))"), basename(nn(v3)))]
}, simplify = FALSE, USE.NAMES = TRUE)
}, simplify = FALSE, USE.NAMES = TRUE)
}, simplify = FALSE, USE.NAMES = TRUE)
})
s2_list_l1c_groups_A <- lapply(sen2r_groups_A, function(d) {
d_string <- strftime(d, "%Y%m%d")
s2_list_l1c[grepl(paste0("[12][ABC]\\_((",paste(d_string,collapse=")|("),"))"), names(s2_list_l1c))]
})
s2_list_l2a_groups_A <- lapply(sen2r_groups_A, function(d) {
d_string <- strftime(d, "%Y%m%d")
s2_list_l2a[grepl(paste0("[12][ABC]\\_((",paste(d_string,collapse=")|("),"))"), names(s2_list_l2a))]
})
s2_dt_groups_A <- lapply(sen2r_groups_A, function(d) {
s2_dt[
as.Date(
gsub("^S2[AB]\\_MSIL[12][AC]\\_([0-9]{8})T.+$", "\\1", name),
"%Y%m%d"
) %in% d,
]
})
names(s2names_groups_A) <- names(s2_list_l1c_groups_A) <-
names(s2_list_l2a_groups_A) <- names(s2_dt_groups_A) <- names(sen2r_groups_A)
} else if (pm$processing_order %in% c(1,"by_step", 3,"mixed")) {
s2names_groups_A <- if (pm$preprocess == TRUE) {list(s2names)} else {"dummy"}
s2_list_l1c_groups_A <- list(s2_list_l1c)
s2_list_l2a_groups_A <- list(s2_list_l2a)
s2_dt_groups_A <- list(s2_dt)
names(s2names_groups_A) <- names(s2_list_l1c_groups_A) <-
names(s2_list_l2a_groups_A) <- names(s2_dt_groups_A) <- "unique"
}
if (all(pm$online == TRUE, "scihub" %in% pm$server)) {
apihubs <- read_scihub_login(if (length(nn(pm$apihub) > 0)) {pm$apihub} else {NA})
n_apihubs <- min(nrow(apihubs), length(s2names_groups_A))
if (n_apihubs > 1 & pm$processing_order %in% c(2,"by_date")) {
pm$apihub <- file.path(tmpdir,paste0("apihub_",seq_len(n_apihubs),".txt"))
for (i in seq_len(n_apihubs)) {
write_scihub_login(apihubs[i,1], apihubs[i,2], pm$apihub[i], append = FALSE, check = FALSE)
}
if (pm$parallel == TRUE | is.numeric(pm$parallel)) {
parallel_groups_A <- pm$parallel
parallel_groups_B <- FALSE
parallel_steps <- FALSE
}
}
} else {
n_apihubs <- length(s2names_groups_A)
}
n_cores_A <- if (is.numeric(parallel_groups_A)) {
min(as.integer(parallel_groups_A), length(s2names_groups_A))
} else if (parallel_groups_A == FALSE) {
1
} else {
min(max_n_cores, length(s2names_groups_A), n_apihubs)
}
if (n_cores_A<=1) {
`%DO_A%` <- `%do%`
n_cores_A <- 1
} else {
`%DO_A%` <- `%dopar%`
cl <- makeCluster(
n_cores_A,
type = if (Sys.info()["sysname"] == "Windows") {"PSOCK"} else {"FORK"}
)
registerDoParallel(cl)
}
outnames_list_A1 <- foreach(
sel_group_A = suppressWarnings(split(
seq_len(length(s2names_groups_A)),
seq_len(ceiling(length(s2names_groups_A)/n_apihubs))
))
) %do% {
outnames_list_A2 <- foreach(
sel_s2names = s2names_groups_A[sel_group_A],
sel_s2_list_l1c = s2_list_l1c_groups_A[sel_group_A],
sel_s2_list_l2a = s2_list_l2a_groups_A[sel_group_A],
sel_s2_dt = s2_dt_groups_A[sel_group_A],
i_group_A = match(names(s2names_groups_A[sel_group_A]), names(s2names_groups_A)),
sel_apihub_path = pm$apihub,
.packages = c("sf", "sen2r")
) %DO_A% {
if (n_cores_A > 1) {
if (!is.na(.log_output)) {
sink(.log_output, split = TRUE, type = "output", append = TRUE)
}
if (!is.na(.log_message)) {
logfile_message = file(.log_message, open = "a")
sink(logfile_message, type="message")
}
}
if (length(s2names_groups_A) > 1) {
print_message(
type="message",
date=TRUE,
"Processing group ",i_group_A," of ",length(s2names_groups_A),"..."
)
}
tmpdir_groupA <- file.path(tmpdir, basename(tempfile(pattern="group")))
dir.create(tmpdir_groupA, recursive = FALSE, showWarnings = FALSE)
path_l1c <- if (!is.na(pm$path_l1c)) {pm$path_l1c} else {file.path(tmpdir_groupA,"SAFE")}
path_l2a <- if (!is.na(pm$path_l2a)) {pm$path_l2a} else {file.path(tmpdir_groupA,"SAFE")}
if (pm$online == TRUE) {
print_message(
type = "message",
date = TRUE,
"Starting to download the required level-2A SAFE products."
)
if (all(safe_getMetadata(
names(sel_s2_list_l2a), info = "version",
format = "vector", simplify = TRUE
) == "compact")) {
if (pm$overwrite_safe) {
s2_to_download_l2a <- sel_s2_list_l2a
} else {
s2_to_download_l2a <- sel_s2_list_l2a[!names(sel_s2_list_l2a) %in% list.files(path_l2a, "\\.SAFE$")]
s2_to_skip_l2a <- names(sel_s2_list_l2a[names(sel_s2_list_l2a) %in% list.files(path_l2a, "\\.SAFE$")])
if (length(s2_to_skip_l2a) != 0) {
print_message(
type = "message",
"Images ", paste(s2_to_skip_l2a, collapse = ", "),
" are already on your system and will be skipped. ",
"Set \"overwrite_safe\" to TRUE to re-download them."
)
}
if (length(s2_to_download_l2a) == 0) {
print_message(type = "message", "No L2A images are needed.")
}
}
s2_to_download_l2a <- as(data.table(
as.data.table(as(s2_to_download_l2a, "safelist")),
footprint = s2_dt[match(names(s2_to_download_l2a), name), footprint]
), "safelist")
s2_downloaded_l2a <- s2_download(
s2_to_download_l2a,
outdir = path_l2a,
downloader = pm$downloader,
apihub = sel_apihub_path,
overwrite = pm$overwrite_safe
)
} else {
print_message(
type = "error",
"Old name SAFE products are no longer supported."
)
}
print_message(
type = "message",
date = TRUE,
"Download of level-2A SAFE products terminated."
)
print_message(
type = "message",
date = TRUE,
"Starting to download the required level-1C SAFE products."
)
if (all(safe_getMetadata(
names(sel_s2_list_l1c), info = "version",
format = "vector", simplify = TRUE
) == "compact")) {
if (pm$overwrite_safe) {
s2_to_download_l1c <- sel_s2_list_l1c
} else {
s2_to_download_l1c <- sel_s2_list_l1c[!names(sel_s2_list_l1c) %in% list.files(path_l1c, "\\.SAFE$")]
s2_to_skip_l1c <- sel_s2_list_l1c[names(sel_s2_list_l1c) %in% list.files(path_l1c, "\\.SAFE$")]
if (length(s2_to_skip_l1c) != 0) {
print_message(
type = "message",
"Images ", paste(names(s2_to_skip_l1c), collapse = ", "),
" are already on your system and will be skipped. ",
"Set \"overwrite_safe\" to TRUE to re-download them."
)
}
if (length(s2_to_download_l1c) == 0) {
print_message(type = "message", "No L1C images are needed.")
}
}
s2_to_download_l1c <- as(data.table(
as.data.table(as(s2_to_download_l1c, "safelist")),
footprint = s2_dt[match(names(s2_to_download_l1c), name), footprint]
), "safelist")
s2_downloaded_l1c <- s2_download(
s2_to_download_l1c,
outdir = path_l1c,
downloader = pm$downloader,
overwrite = pm$overwrite_safe
)
} else {
print_message(
type = "error",
"Old name SAFE products are no longer supported."
)
}
print_message(
type = "message",
date = TRUE,
"Download of level-1C SAFE products terminated."
)
}
sel_s2_dt <- sel_s2_dt[order(-creation_datetime),]
sel_s2_dt <- sel_s2_dt[
!duplicated(
sel_s2_dt[, list(
mission,
level,
id_orbit,
centroid_x, centroid_y,
as.Date(sensing_datetime)
)]
),
]
if (pm$online == TRUE) {
sel_s2_dt_id <- sel_s2_dt[
,paste(mission, level, sensing_datetime, id_orbit, centroid_x, centroid_y)
]
s2_downloaded_dt <- rbind(
safe_getMetadata(
file.path(path_l1c, names(s2_downloaded_l1c)),
info = c("name", "mission", "level", "sensing_datetime", "id_orbit",
"id_tile", "creation_datetime", "footprint"),
format = "data.table"
),
safe_getMetadata(
file.path(path_l2a, names(s2_downloaded_l2a)),
info = c("name", "mission", "level", "sensing_datetime", "id_orbit",
"id_tile", "creation_datetime", "footprint"),
format = "data.table"
),
fill = TRUE
)
if (nrow(s2_downloaded_dt)>0) {
s2_downloaded_dt_centroid <- suppressMessages(round(st_coordinates(
st_centroid(st_transform(st_as_sfc(s2_downloaded_dt$footprint, crs = 4326), 3857))
), -3))
s2_downloaded_dt[,c("centroid_x", "centroid_y") := list(
s2_downloaded_dt_centroid[,"X"],
s2_downloaded_dt_centroid[,"Y"]
)]
s2_downloaded_id <- s2_downloaded_dt[
,paste(mission, level, sensing_datetime, id_orbit, centroid_x, centroid_y)
]
sel_s2_dt[
match(s2_downloaded_id, sel_s2_dt_id),
name:=names(c(s2_downloaded_l1c,s2_downloaded_l2a))
]
}
}
sel_s2_list_l1c <- sel_s2_dt[level=="1C",url]
sel_s2_list_l2a <- sel_s2_dt[level=="2A",url]
names(sel_s2_list_l1c) <- sel_s2_dt[level=="1C",name]
names(sel_s2_list_l2a) <- sel_s2_dt[level=="2A",name]
if (all(
pm$step_atmcorr %in% c("auto","scihub"),
"l2a" %in% pm$s2_levels
)) {
sel_s2_list_l1c_tocorrect <- if (pm$overwrite_safe==FALSE) {
sel_s2_list_l1c[
!gsub(
"\\_OPER\\_","_USER_",
gsub(
"^S2([AB])\\_((?:OPER\\_PRD\\_)?)MSIL1C\\_","S2\\1\\_\\2MSIL2A\\_",
names(sel_s2_list_l1c)
)
) %in% names(sel_s2_list_l2a) &
names(sel_s2_list_l1c) %in% safe_names_l1c_tocorrect
]
} else {
sel_s2_list_l1c[names(sel_s2_list_l1c) %in% safe_names_l1c_tocorrect]
}
if (length(sel_s2_list_l1c_tocorrect)>0) {
if (sum(file.exists(file.path(path_l1c,names(sel_s2_list_l1c_tocorrect)))) > 0) {
print_message(
type = "message",
date = TRUE,
"Starting to correct level-1C SAFE products with Sen2Cor. ",
"This operation could take very long time."
)
}
sel_s2_list_l2a_corrected <- sen2cor(
names(sel_s2_list_l1c_tocorrect),
l1c_dir = path_l1c,
outdir = path_l2a,
tiles = pm$s2tiles_selected,
parallel = pm$parallel,
use_dem = pm$sen2cor_use_dem,
gipp = if (all(is.na(pm$sen2cor_gipp))) {list()} else {pm$sen2cor_gipp},
tmpdir = if (Sys.info()["sysname"] == "Windows") {
file.path(tmpdir_groupA, "sen2cor")
} else if (any(attr(mountpoint(tmpdir_groupA), "protocol") %in% c("cifs", "nsfs"))) {
NA
} else {
file.path(tmpdir_groupA, "sen2cor")
},
.log_message = .log_message, .log_output = .log_output,
rmtmp = TRUE
)
names(sel_s2_list_l2a_corrected) <- basename(sel_s2_list_l2a_corrected)
sel_s2_list_l2a <- c(sel_s2_list_l2a,sel_s2_list_l2a_corrected)
}
if (!("l1c" %in% pm$s2_levels) & pm$rm_safe %in% c("all","l1c")) {
unlink(file.path(path_l1c,names(sel_s2_list_l1c_tocorrect)), recursive=TRUE)
}
}
if (pm$preprocess == FALSE) {
sen2r_output <- c(file.path(path_l1c,names(sel_s2_list_l1c)),
file.path(path_l2a,names(sel_s2_list_l2a)))
status <- sen2r_process_report(
s2_list_ordered = s2_list_ordered,
download_only = TRUE,
s2_downloaded = c(
if (exists("s2_downloaded_l1c")) s2_downloaded_l1c else NA,
if (exists("s2_downloaded_l2a")) s2_downloaded_l2a else NA
),
s2_skipped = c(
if (exists("s2_to_skip_l1c")) s2_to_skip_l1c else NA,
if (exists("s2_to_skip_l2a")) s2_to_skip_l2a else NA
),
s2_corrected = if (all("l1c" %in% pm$s2_levels, length(pm$s2_levels) == 1)) {
NA
} else {
s2_list_l1c_tocorrect
}
)
out_attributes[["status"]] <- status
attributes(sen2r_output) <- c(attributes(sen2r_output), out_attributes)
return(invisible(sen2r_output))
}
print_message(type = "message", date = TRUE, "Updating output names...")
sel_s2names <- compute_s2_paths(
pm=pm,
s2_list_l1c = if (exists("sel_s2_list_l1c")) {sel_s2_list_l1c} else {character(0)},
s2_list_l2a = if (exists("sel_s2_list_l2a")) {sel_s2_list_l2a} else {character(0)},
tmpdir=tmpdir_groupA,
list_prods=list_prods,
force_tiles = FALSE,
ignorelist = ignorelist
)
paths <- attr(sel_s2names, "paths")
paths_istemp <- attr(sel_s2names, "paths_istemp")
if (pm$processing_order %in% c(2,"by_date", 3,"mixed", 4,"by_groups")) {
sen2r_dates_B <- sort(unique(nn(sen2r_getElements(
unlist(sel_s2names$new)
)$sensing_date)))
s2names_groups_B <- lapply(sen2r_dates_B, function(d) {
d_string <- strftime(d, "%Y%m%d")
sapply(sel_s2names, function(v1) {
sapply(v1, function(v2) {
sapply(v2, function(v3) {
v3[grepl(paste0("[12][ABC]\\_((",paste(d_string,collapse=")|("),"))"), basename(nn(v3)))]
}, simplify = FALSE, USE.NAMES = TRUE)
}, simplify = FALSE, USE.NAMES = TRUE)
}, simplify = FALSE, USE.NAMES = TRUE)
})
names(s2names_groups_B) <- sen2r_dates_B
} else if (pm$processing_order %in% c(1,"by_step")) {
s2names_groups_B <- list(sel_s2names)
}
n_cores_B <- if (is.numeric(parallel_groups_B)) {
min(as.integer(parallel_groups_B), length(s2names_groups_B))
} else if (parallel_groups_B == FALSE) {
1
} else {
min(max_n_cores, length(s2names_groups_B))
}
if (n_cores_B<=1) {
`%DO_B%` <- `%do%`
n_cores_B <- 1
} else {
`%DO_B%` <- `%dopar%`
cl <- makeCluster(
n_cores_B,
type = if (Sys.info()["sysname"] == "Windows") {"PSOCK"} else {"FORK"}
)
registerDoParallel(cl)
print_message(
type="message",
date=TRUE,
"Starting running processing operations on multiple (",n_cores_B,
") parallel cores..."
)
if (is.na(.log_message) & i_group_A == 1) {
print_message(
type="message",
"Note: logging messages are not shown during this phase, ",
"since it is not possible to send it to standard output. ",
"To see them, send messages to an external log file ",
"or use a different processing order (by_date or by_steps)."
)
}
}
outnames_list_B <- foreach(
sel_s2names = s2names_groups_B,
i_group_B = seq_along(s2names_groups_B),
.packages = c("sf", "sen2r")
) %DO_B% {
if (n_cores_B > 1) {
if (!is.na(.log_output)) {
sink(.log_output, split = TRUE, type = "output", append = TRUE)
}
if (!is.na(.log_message)) {
logfile_message = file(.log_message, open = "a")
sink(logfile_message, type="message")
}
}
if (length(s2names_groups_B) > 1) {
print_message(
type="message",
date=TRUE,
"Processing date ",i_group_B," of ",length(s2names_groups_B),
" in group ",i_group_A," of ",length(s2names_groups_A),"..."
)
}
if (length(unlist(sel_s2names$req$tiles))>0) {
print_message(
type = "message",
date = TRUE,
"Starting to translate SAFE products in custom format."
)
dir.create(paths["tiles"], recursive=FALSE, showWarnings=FALSE)
if ("l1c" %in% pm$s2_levels) {
list_l1c_prods <- list_prods[list_prods %in% l1c_prods]
tiles_l1c_names_out <- foreach(
sel_prod = sel_s2names$req$tiles$L1C,
sel_out = lapply(
seq_len(max(sapply(sel_s2names$exp$tiles, length))),
function(i) {sapply(sel_s2names$exp$tiles, function(p) {p[i]})}
),
.combine = c
) %do% {
sel_tiles_l1c_names_out0 <- trace_function(
s2_translate,
infile = sel_prod,
outdir = paths["tiles"],
tmpdir = file.path(tmpdir_groupA, "s2_translate_l1c"),
rmtmp = FALSE,
prod_type = list_l1c_prods,
format = out_format["tiles"],
compress = pm$compression,
bigtiff = bigtiff,
tiles = pm$s2tiles_selected,
res = pm$res_s2,
subdirs = pm$path_subdirs,
overwrite = pm$overwrite,
trace_files = remove_tile_suffix(sel_out)
)
sel_tiles_l1c_names_out <- add_tile_suffix(
sel_tiles_l1c_names_out0,
extract_tile_suffix(sel_out)[1]
)
file.rename(sel_tiles_l1c_names_out0, sel_tiles_l1c_names_out)
sel_tiles_l1c_names_out
}
}
list_l2a_prods <- list_prods[list_prods %in% l2a_prods]
tiles_l2a_names_out <- foreach(
sel_prod = sel_s2names$req$tiles$L2A,
sel_out = lapply(
seq_len(max(sapply(sel_s2names$exp$tiles, length))),
function(i) {sapply(sel_s2names$exp$tiles, function(p) {p[i]})}
),
.combine = c
) %do% {
sel_tiles_l2a_names_out0 <- trace_function(
s2_translate,
infile = sel_prod,
tmpdir = file.path(tmpdir_groupA, "s2_translate_l2a"),
rmtmp = FALSE,
outdir = paths["tiles"],
prod_type = list_l2a_prods,
format = out_format["tiles"],
compress = pm$compression,
bigtiff = bigtiff,
tiles = pm$s2tiles_selected,
res = pm$res_s2,
subdirs = pm$path_subdirs,
overwrite = pm$overwrite,
trace_files = remove_tile_suffix(sel_out)
)
sel_tiles_l2a_names_out <- add_tile_suffix(
sel_tiles_l2a_names_out0,
extract_tile_suffix(sel_out)[1]
)
file.rename(sel_tiles_l2a_names_out0, sel_tiles_l2a_names_out)
sel_tiles_l2a_names_out
}
tiles_names_out <- c(if("l1c" %in% pm$s2_levels) {tiles_l1c_names_out},
if("l2a" %in% pm$s2_levels) {tiles_l2a_names_out})
}
if (sum(file.exists(nn(unlist(sel_s2names$req$merged))))>0) {
print_message(
type = "message",
date = TRUE,
"Starting to merge tiles by orbit."
)
dir.create(paths["merged"], recursive=FALSE, showWarnings=FALSE)
merged_names_out <- trace_function(
s2_merge,
infiles = unlist(sel_s2names$req$merged)[file.exists(unlist(sel_s2names$req$merged))],
outdir = paths["merged"],
subdirs = pm$path_subdirs,
tmpdir = file.path(tmpdir_groupA, "s2_merge"),
rmtmp = FALSE,
format = out_format["merged"],
compress = pm$compression,
bigtiff = bigtiff,
out_crs = out_proj,
parallel = if (out_format["merged"]=="VRT") {FALSE} else {parallel_steps},
overwrite = pm$overwrite,
.log_message = .log_message, .log_output = .log_output,
trace_files = unlist(sel_s2names$new$merged)
)
}
if (sum(file.exists(nn(unlist(c(sel_s2names$req$warped,sel_s2names$req$warped_nomsk)))))>0) {
print_message(
type = "message",
date = TRUE,
"Starting to edit geometry (clip, reproject, rescale)."
)
warped_tomsk_reqout <- sapply(names(sel_s2names$req$warped), function(prod) {
sel_s2names$exp$warped[[prod]][
sel_s2names$exp$merged[[prod]] %in% sel_s2names$req$warped[[prod]]
]
}, simplify = FALSE, USE.NAMES = TRUE)
warped_nomsk_reqout <- sapply(names(sel_s2names$req$warped_nomsk), function(prod) {
sel_s2names$exp$warped_nomsk[[prod]][
sel_s2names$exp$merged[[prod]] %in% sel_s2names$req$warped_nomsk[[prod]]
]
}, simplify = FALSE, USE.NAMES = TRUE)
dir.create(paths["warped"], recursive=FALSE, showWarnings=FALSE)
if(pm$path_subdirs==TRUE){
sapply(unique(dirname(unlist(c(warped_tomsk_reqout,warped_nomsk_reqout)))),dir.create,showWarnings=FALSE)
}
if (any(!file.exists(nn(unlist(warped_tomsk_reqout)))) | pm$overwrite==TRUE) {
for (sel_prod in names(sel_s2names$req$warped)) {
tracename_gdalwarp <- start_trace(warped_tomsk_reqout[[sel_prod]], "gdal_warp")
trace_gdalwarp <- tryCatch({
gdal_warp(
sel_s2names$req$warped[[sel_prod]],
warped_tomsk_reqout[[sel_prod]],
of = out_format["warped"],
ref = if (!is.na(pm$reference_path)) {
pm$reference_path
} else {
reference_exi_paths[
res_type == ifelse(
sel_prod %in% c("SCL","CLD","SNW"),
"res20", "res10"
),
path
]
},
mask = s2_mask_extent,
tr = if (!anyNA(pm$res)) {pm$res} else {NULL},
t_srs = out_proj,
r = pm$resampling,
dstnodata = s2_defNA(sel_prod),
co = if (out_format["warped"]=="GTiff") {c(
paste0("COMPRESS=",pm$compression),
"TILED=YES",
if (bigtiff) {"BIGTIFF=YES"}
)},
tap = gdal_tap,
overwrite = pm$overwrite,
tmpdir = file.path(tmpdir_groupA, "gdal_warp"),
rmtmp = FALSE
)
if (out_format["warped"]=="ENVI") {fix_envi_format(
unlist(warped_tomsk_reqout)[file.exists(unlist(warped_tomsk_reqout))]
)}
}, error = print)
if (is(trace_gdalwarp, "error")) {
clean_trace(tracename_gdalwarp)
stop(trace_gdalwarp)
} else {
end_trace(tracename_gdalwarp)
}
}
}
if (any(!file.exists(nn(unlist(warped_nomsk_reqout)))) | pm$overwrite==TRUE) {
for (sel_prod in names(sel_s2names$req$warped_nomsk)) {
tracename_gdalwarp <- start_trace(warped_nomsk_reqout[[sel_prod]], "gdal_warp")
trace_gdalwarp <- tryCatch({
gdal_warp(
sel_s2names$req$warped_nomsk[[sel_prod]],
warped_nomsk_reqout[[sel_prod]],
of = out_format["warped_nomsk"],
ref = if (!is.na(pm$reference_path)) {
pm$reference_path
} else {
reference_exi_paths[
res_type == ifelse(
sel_prod %in% c("SCL","CLD","SNW"),
"res20", "res10"
),
path
]
},
mask = s2_mask_extent,
tr = if (!anyNA(pm$res)) {pm$res} else {NULL},
t_srs = out_proj,
r = if (sel_prod == "SCL") {pm$resampling_scl} else {pm$resampling},
dstnodata = s2_defNA(sel_prod),
co = if (out_format["warped_nomsk"]=="GTiff") {c(
paste0("COMPRESS=",pm$compression),
"TILED=YES",
if (bigtiff) {"BIGTIFF=YES"}
)},
tap = gdal_tap,
overwrite = pm$overwrite,
tmpdir = file.path(tmpdir_groupA, "gdal_warp"),
rmtmp = FALSE
)
if (out_format["warped_nomsk"]=="ENVI") {fix_envi_format(
unlist(warped_nomsk_reqout)[file.exists(unlist(warped_nomsk_reqout))]
)}
}, error = print)
if (is(trace_gdalwarp, "error")) {
clean_trace(tracename_gdalwarp)
stop(trace_gdalwarp)
} else {
end_trace(tracename_gdalwarp)
}
}
}
}
if (sum(file.exists(nn(unlist(sel_s2names$req$masked))))>0) {
if (!is.na(pm$mask_type) & length(unlist(sel_s2names$new$masked))>0) {
print_message(
type = "message",
date = TRUE,
"Starting to apply cloud masks."
)
masked_names_out <- if (length(unlist(sel_s2names$req$masked))>0) {
trace_function(
s2_mask,
infiles = unlist(sel_s2names$req$masked[names(sel_s2names$req$masked)!="SCL"]),
maskfiles = sel_s2names$req$masked[["SCL"]],
mask_type = pm$mask_type,
smooth = pm$mask_smooth,
buffer = pm$mask_buffer,
max_mask = pm$max_mask,
outdir = paths["masked"],
tmpdir = file.path(tmpdir_groupA, "s2_mask"),
rmtmp = FALSE,
format = out_format["masked"],
compress = pm$compression,
bigtiff = bigtiff,
subdirs = pm$path_subdirs,
overwrite = pm$overwrite,
parallel = parallel_steps,
.log_message = .log_message, .log_output = .log_output,
trace_files = unlist(sel_s2names$new$masked)
)
} else {character(0)}
masked_names_notcreated <- c(
attr(masked_names_out, "toomasked")
)
}
}
if (sum(file.exists(nn(unlist(sel_s2names$req$rgb))))>0) {
print_message(
type = "message",
date = TRUE,
"Producing required RGB images."
)
dir.create(paths["rgb"], recursive=FALSE, showWarnings=FALSE)
if (sum(file.exists(nn(sel_s2names$req$rgb[["TOA"]])))>0) {
rgb_names <- trace_function(
s2_rgb,
infiles = sel_s2names$req$rgb[["TOA"]][file.exists(sel_s2names$req$rgb[["TOA"]])],
rgb_bands = lapply(
strsplit(unique(gsub("^RGB([0-9a-f]{3})T$","\\1",pm$list_rgb[grepl("T$",pm$list_rgb)])),""),
function(x) {strtoi(paste0("0x",x))}
),
scaleRange = pm$rgb_ranges[grepl("T$",pm$list_rgb)],
outdir = paths["rgb"],
subdirs = pm$path_subdirs,
format = out_format["rgb"],
compress = pm$rgb_compression,
bigtiff = bigtiff,
tmpdir = file.path(tmpdir_groupA, "s2_rgb"),
rmtmp = FALSE,
parallel = parallel_steps,
overwrite = pm$overwrite,
.log_message = .log_message, .log_output = .log_output,
trace_files = unlist(sel_s2names$new$rgb)[grepl("T$",names(unlist(sel_s2names$new$rgb)))]
)
}
if (sum(file.exists(nn(sel_s2names$req$rgb[["BOA"]])))>0) {
rgb_names <- trace_function(
s2_rgb,
infiles = sel_s2names$req$rgb[["BOA"]][file.exists(sel_s2names$req$rgb[["BOA"]])],
rgb_bands = lapply(
strsplit(unique(gsub("^RGB([0-9a-f]{3})B$","\\1",pm$list_rgb[grepl("B$",pm$list_rgb)])),""),
function(x) {strtoi(paste0("0x",x))}
),
scaleRange = pm$rgb_ranges[grepl("B$",pm$list_rgb)],
outdir = paths["rgb"],
subdirs = pm$path_subdirs,
format = out_format["rgb"],
compress = pm$rgb_compression,
bigtiff = bigtiff,
tmpdir = file.path(tmpdir_groupA, "s2_rgb"),
rmtmp = FALSE,
parallel = parallel_steps,
overwrite = pm$overwrite,
.log_message = .log_message, .log_output = .log_output,
trace_files = unlist(sel_s2names$new$rgb)[grepl("B$",names(unlist(sel_s2names$new$rgb)))]
)
}
}
if (sum(file.exists(nn(sel_s2names$req$indices[[pm$index_source]])))>0) {
print_message(
type = "message",
date = TRUE,
"Computing required spectral indices."
)
dir.create(paths["indices"], recursive=FALSE, showWarnings=FALSE)
indices_names <- trace_function(
s2_calcindices,
infiles = sel_s2names$req$indices[[pm$index_source]][file.exists(sel_s2names$req$indices[[pm$index_source]])],
indices = pm$list_indices,
outdir = paths["indices"],
subdirs = pm$path_subdirs,
tmpdir = file.path(tmpdir_groupA, "s2_calcindices"),
source = pm$index_source,
format = out_format["indices"],
dataType = pm$index_datatype,
compress = pm$compression,
bigtiff = bigtiff,
overwrite = pm$overwrite,
parallel = parallel_steps,
.log_message = .log_message, .log_output = .log_output,
trace_files = unlist(sel_s2names$new$indices)
)
}
if (exists("masked_names_notcreated")) {
if (length(masked_names_notcreated)>0 & length(unlist(sel_s2names$req$indices))>0) {
indices_names_notcreated_raw <- sen2r_getElements(
masked_names_notcreated, format="data.table"
)[prod_type == pm$index_source,
paste0("S2",
mission,
level,"_",
strftime(sensing_date,"%Y%m%d"),"_",
id_orbit,"_",
if (pm$clip_on_extent) {pm$extent_name},"_",
"<index>_",
substr(res,1,2),".",
out_ext["masked"])]
indices_names_notcreated <- file.path(
paths["indices"],
apply(
expand.grid(indices_names_notcreated_raw, pm$list_indices),
1, function(x) {
file.path(
if(pm$path_subdirs==TRUE){x[2]}else{""},
gsub("<index>",x[2],x[1])
)
}
)
)
indices_names_notcreated <- gsub(
paste0(out_ext["merged"],"$"), out_ext["masked"],
indices_names_notcreated
)
}
}
names_out <- unique(unlist(
sel_s2names$new[!paths_istemp[names(sel_s2names$new)]]
))
names_out_created <- names_out[file.exists(nn(names_out))]
if (pm$thumbnails==TRUE) {
thumb_names_req <- names_out_created
if (length(thumb_names_req)>0) {
print_message(
type = "message",
date = TRUE,
"Generating thumbnails."
)
thumb_names_new <- file.path(
dirname(thumb_names_req),
"thumbnails",
sapply(
basename(thumb_names_req),
function(x) {
gsub(
"\\..+$",
if (sen2r_getElements(x)$prod_type %in% c("SCL")) {".png"} else {".jpg"},
x
)
}
)
)
thumb_names_out <- trace_function(
s2_thumbnails,
infiles = thumb_names_req,
tmpdir = file.path(tmpdir_groupA, "s2_thumbnails"),
rmtmp = FALSE,
trace_files = c(thumb_names_new,paste0(thumb_names_new,".aux.xml")),
overwrite = pm$overwrite
)
}
}
if (n_cores_B > 1) {
if (!is.na(.log_output)) {
sink(type = "output")
}
if (!is.na(.log_message)) {
sink(type = "message"); close(logfile_message)
}
}
gc()
list(
"out" = names_out,
"out_created" = names_out_created,
"cloudcovered" = nn(c(
if(exists("masked_names_notcreated")) {masked_names_notcreated},
if(exists("indices_names_notcreated")) {indices_names_notcreated}
))
)
}
if (n_cores_B > 1) {
stopCluster(cl)
print_message(
type="message",
date=TRUE,
"Processing operations on multiple parallel cores was done."
)
}
if (rmtmp == TRUE) {
unlink(tmpdir_groupA, recursive=TRUE)
}
if (pm$rm_safe %in% c("all", "yes")) {
unlink(file.path(path_l1c,names(sel_s2_list_l1c)), recursive=TRUE)
unlink(file.path(path_l2a,names(sel_s2_list_l2a)), recursive=TRUE)
} else if (pm$rm_safe == "l1c") {
unlink(file.path(path_l1c,names(sel_s2_list_l1c)), recursive=TRUE)
}
gc()
list(
"out" = as.vector(unlist(lapply(outnames_list_B, function(x){x$out}))),
"out_created" = as.vector(unlist(lapply(outnames_list_B, function(x){x$out_created}))),
"cloudcovered" = as.vector(unlist(lapply(outnames_list_B, function(x){x$cloudcovered})))
)
}
gc()
if (n_cores_A > 1) {
stopCluster(cl)
}
if (pm$preprocess == FALSE | .only_list_names == TRUE) {
outnames_list_A2
} else {
list(
"out" = as.vector(unlist(lapply(outnames_list_A2, function(x){x$out}))),
"out_created" = as.vector(unlist(lapply(outnames_list_A2, function(x){x$out_created}))),
"cloudcovered" = as.vector(unlist(lapply(outnames_list_A2, function(x){x$cloudcovered})))
)
}
}
if (pm$preprocess == FALSE | .only_list_names == TRUE) {
sen2r_output <- unlist(outnames_list_A1)
attributes(sen2r_output) <- c(attributes(sen2r_output), out_attributes)
return(sen2r_output)
}
names_out <- as.vector(unlist(lapply(outnames_list_A1, function(x){x$out})))
names_out_created <- as.vector(unlist(lapply(outnames_list_A1, function(x){x$out_created})))
names_cloudcovered <- as.vector(unlist(lapply(outnames_list_A1, function(x){x$cloudcovered})))
names_missing <- names_out[!file.exists(nn(names_out))]
names_missing <- names_missing[!names_missing %in% names_cloudcovered]
ignorelist_path <- write_ignorelist(
pm = pm,
names_cloudcovered = names_cloudcovered,
names_missing = names_missing,
param_list = param_list
)
clean_ignorelist(pm = pm, param_list = param_list)
if (length(names_missing)>0) {
print_message(
type="warning",
"Some files were not created:\n\"",
paste(names_missing,collapse="\"\n\""),"\"",
"\"\nThese files will be skipped during next executions ",
"from the current parameter file (\"",param_list,"\"). ",
"To try again to build them, remove their file name in the text file \"",
ignorelist_path,"\"."
)
}
status <- sen2r_process_report(
s2_list_ordered = s2_list_ordered,
s2names = s2names,
pm = pm,
ignorelist = ignorelist,
s2_list_cloudcovered = if (length(names_cloudcovered) != 0) names_cloudcovered else NA,
s2_list_failed = if (length(names_missing) != 0) names_missing else NA,
s2_downloaded = c(
if (exists("s2_downloaded_l1c")) s2_downloaded_l1c else NA,
if (exists("s2_downloaded_l2a")) s2_downloaded_l2a else NA
),
s2_skipped = c(
if (exists("s2_to_skip_l1c")) s2_to_skip_l1c else NA,
if (exists("s2_to_skip_l2a")) s2_to_skip_l2a else NA
),
s2_corrected = if (all("l1c" %in% pm$s2_levels, length(pm$s2_levels) == 1)) {
NA
} else {
s2_list_l1c_tocorrect
}
)
sen2r_output <- names_out_created
attributes(sen2r_output) <- c(attributes(sen2r_output), out_attributes)
new_ignorelist <- read_ignorelist(pm)
attr(sen2r_output, "clouddates") <- new_ignorelist$dates_cloudcovered
attr(sen2r_output, "missing") <- new_ignorelist$names_missing
attr(sen2r_output, "status") <- status
gc()
return(invisible(sen2r_output))
}
|
mediancenter <- function(x)
{
if (is.data.frame(x))
x <- as.matrix(x)
else if (!is.matrix(x))
stop("'x' must be a matrix or a data frame")
if (!all(is.finite(x)))
stop("'x' must contain finite values only")
n <- nrow(x)
p <- ncol(x)
storage.mode(x) <- "double"
z <- .Fortran("median_center",
x = x,
ldx = as.integer(n),
n = as.integer(n),
p = as.integer(p),
median = double(p),
iter = as.integer(0),
info = as.integer(0))[c("median","iter")]
z
}
|
test_that("datapack library loads", {
expect_true(library(datapack, logical.return = TRUE))
})
test_that("DataObject constructors work", {
library(datapack)
library(digest)
identifier <- "id1"
user <- "matt"
data <- charToRaw("1,2,3\n4,5,6\n")
format <- "text/csv"
node <- "urn:node:KNB"
do <- new("DataObject", identifier, data, filename="test.cvs", format=format, user=user, mnNodeId=node)
expect_equal(class(do)[[1]], "DataObject")
expect_equal(do@sysmeta@serialVersion, 1)
expect_equal(do@sysmeta@identifier, identifier)
expect_equal(do@sysmeta@submitter, user)
expect_equal(do@sysmeta@size, length(data))
expect_equal(length(do@data), length(data))
expect_equal(getIdentifier(do), identifier)
expect_equal(getFormatId(do), format)
sha <- digest(data, algo="sha256", serialize=FALSE, file=FALSE)
sm <- new("SystemMetadata", identifier=identifier, formatId=format, size=length(data), submitter=user, rightsHolder=user, checksum=sha, originMemberNode=node, authoritativeMemberNode=node)
expect_equal(sm@identifier, identifier)
do <- new("DataObject", sm, data, filename="test.csv")
expect_equal(do@sysmeta@serialVersion, 1)
expect_equal(do@sysmeta@identifier, identifier)
expect_equal(do@sysmeta@submitter, user)
expect_equal(do@sysmeta@checksumAlgorithm, "SHA-256")
expect_equal(do@sysmeta@checksum, sha)
expect_equal(do@sysmeta@size, length(data))
expect_equal(do@sysmeta@size, length(data))
expect_equal(length(do@data), length(data))
expect_equal(getIdentifier(do), identifier)
expect_equal(getFormatId(do), format)
tf <- tempfile()
con <- file(tf, "wb")
writeBin(data, con)
close(con)
sha_file <- digest(tf, algo="sha256", serialize=FALSE, file=TRUE)
do <- new("DataObject", sm, filename=tf, checksumAlgorith="SHA-256")
expect_equal(do@sysmeta@serialVersion, 1)
expect_equal(do@sysmeta@identifier, identifier)
expect_equal(do@sysmeta@submitter, user)
expect_equal(do@sysmeta@checksumAlgorithm, "SHA-256")
expect_equal(do@sysmeta@checksum, sha)
expect_equal(do@sysmeta@size, length(data))
expect_equal(file.info(tf)$size, length(data))
expect_equal(getIdentifier(do), identifier)
expect_equal(getFormatId(do), format)
data2 <- getData(do)
sha_get_data <- digest(data2, algo="sha256", serialize=FALSE, file=FALSE)
expect_match(sha_get_data, sha)
expect_match(sha_file, do@sysmeta@checksum)
expect_match(sha_get_data, do@sysmeta@checksum)
sha_file <- digest(tf, algo="sha1", serialize=FALSE, file=TRUE)
do <- new("DataObject", identifier, filename=tf, checksumAlgorith="SHA1")
expect_equal(do@sysmeta@checksum, sha_file)
expect_equal(do@sysmeta@checksumAlgorithm, "SHA1")
sha_file <- digest(tf, algo="md5", serialize=FALSE, file=TRUE)
do <- new("DataObject", identifier, filename=tf, checksumAlgorith="MD5")
expect_equal(do@sysmeta@checksum, sha_file)
expect_equal(do@sysmeta@checksumAlgorithm, "MD5")
unlink(tf)
targetPath="./data/rasters/test.csv"
do <- new("DataObject", sm, data, filename="test.csv", targetPath=targetPath)
expect_equal(do@targetPath, targetPath)
targetPath="data/rasters/test.csv"
do <- new("DataObject", sm, data, filename="test.csv", targetPath=targetPath)
expect_equal(do@targetPath, targetPath)
})
test_that("DataObject accessPolicy methods", {
library(datapack)
library(digest)
identifier <- "id1"
user <- "matt"
data <- charToRaw("1,2,3\n4,5,6")
format <- "text/csv"
node <- "urn:node:KNB"
do <- new("DataObject", identifier, data, format, user, node, filename="test.csv")
expect_equal(class(do)[[1]], "DataObject")
canRead <- canRead(do, "uid=anybody,DC=somedomain,DC=org")
expect_false(canRead)
do <- setPublicAccess(do)
isPublic <- hasAccessRule(do@sysmeta, "public", "read")
expect_true(isPublic)
accessRules <- data.frame(subject=c("uid=smith,ou=Account,dc=example,dc=com",
"uid=wiggens,o=unaffiliated,dc=example,dc=org"),
permission=c("write", "changePermission"), stringsAsFactors=FALSE)
do <- addAccessRule(do, accessRules)
expect_true(hasAccessRule(do@sysmeta, "uid=smith,ou=Account,dc=example,dc=com", "write"))
expect_true(hasAccessRule(do@sysmeta, "uid=wiggens,o=unaffiliated,dc=example,dc=org", "changePermission"))
expect_false(hasAccessRule(do@sysmeta, "uid=smith,ou=Account,dc=example,dc=com", "changePermission"))
canRead <- canRead(do, "uid=anybody,DC=somedomain,DC=org")
expect_true(canRead)
do <- clearAccessPolicy(do)
expect_true(nrow(do@sysmeta@accessPolicy) == 0)
expect_false(hasAccessRule(do@sysmeta, "uid=smith,ou=Account,dc=example,dc=com", "write"))
expect_false(hasAccessRule(do@sysmeta, "uid=wiggens,o=unaffiliated,dc=example,dc=org", "changePermission"))
expect_false(hasAccessRule(do@sysmeta, "uid=smith,ou=Account,dc=example,dc=com", "changePermission"))
do <- new("DataObject", identifier, data, format, user, node, filename="test.csv")
do <- addAccessRule(do, "uid=smith,ou=Account,dc=example,dc=com", "write")
do <- addAccessRule(do, "uid=smith,ou=Account,dc=example,dc=com", "changePermission")
expect_true(hasAccessRule(do, "uid=smith,ou=Account,dc=example,dc=com", "write"))
expect_true(hasAccessRule(do, "uid=smith,ou=Account,dc=example,dc=com", "changePermission"))
do <- removeAccessRule(do, "uid=smith,ou=Account,dc=example,dc=com", "changePermission")
expect_false(hasAccessRule(do, "uid=smith,ou=Account,dc=example,dc=com", "changePermission"))
do <- removeAccessRule(do, "uid=smith,ou=Account,dc=example,dc=com", "write")
expect_false(hasAccessRule(do, "uid=smith,ou=Account,dc=example,dc=com", "write"))
do <- addAccessRule(do, "uid=jones,ou=Account,dc=example,dc=com", "write")
do <- addAccessRule(do, "uid=jones,ou=Account,dc=example,dc=com", "changePermission")
expect_true(hasAccessRule(do, "uid=jones,ou=Account,dc=example,dc=com", "write"))
expect_true(hasAccessRule(do, "uid=jones,ou=Account,dc=example,dc=com", "changePermission"))
accessRules <- data.frame(subject=c("uid=jones,ou=Account,dc=example,dc=com",
"uid=jones,ou=Account,dc=example,dc=com"),
permission=c("write", "changePermission"))
do <- removeAccessRule(do, accessRules)
expect_false(hasAccessRule(do, "uid=jones,ou=Account,dc=example,dc=com", "write"))
expect_false(hasAccessRule(do, "uid=jones,ou=Account,dc=example,dc=com", "changePermission"))
})
test_that("DataObject updateXML method", {
library(datapack)
library(XML)
resolveURL <- "https://cn.dataone.org/cn/v2/resolve"
sampleMeta <- system.file("./extdata/sample-eml.xml", package="datapack")
metaObj <- new("DataObject", format="eml://ecoinformatics.org/eml-2.1.1", file=sampleMeta)
sampleData <- system.file("./extdata/sample-data.csv", package="datapack")
dataObj <- new("DataObject", format="text/csv", file=sampleData)
xp <- sprintf("//dataTable/physical/distribution[../objectName/text()=\"%s\"]/online/url", "sample-data.csv")
newURL <- sprintf("%s/%s", resolveURL, getIdentifier(dataObj))
metaObj <- updateXML(metaObj, xpath=xp, replacement=newURL)
metadataDoc <- xmlInternalTreeParse(rawToChar(getData(metaObj)))
nodeSet = xpathApply(metadataDoc,xp)
URL <- xmlValue(nodeSet[[1]])
expect_match(newURL, URL)
})
|
create.ascii <- function(file_genotype=NULL, type="text", AA=NULL, AB=NULL, BB=NULL,
availmemGb=8, dim_of_M=NULL, quiet=TRUE, missing=NULL){
if(.Platform$OS.type == "unix") {
asciiMfile <- paste(tempdir() , "/", "M.ascii", sep="")
asciiMtfile <- paste(tempdir() , "/", "Mt.ascii", sep="")
} else {
asciiMfile <- paste(tempdir() , "\\", "M.ascii", sep="")
asciiMtfile <- paste(tempdir() , "\\", "Mt.ascii", sep="")
}
if (type=="text"){
if(!is.null(missing)) {
missing <- as.character(missing)
} else {
missing <- "NA"
}
it_worked <- createM_ASCII_rcpp(f_name = file_genotype, type=type , f_name_ascii = asciiMfile, AA = AA, AB = AB, BB = BB,
max_memory_in_Gbytes=availmemGb, dims = dim_of_M ,
quiet = quiet, message=message, missing=missing)
if(!it_worked)
return(FALSE)
message(" \n Taking transpose of marker data and writing untransposed and transposed data to disc ... \n")
createMt_ASCII_rcpp(f_name = asciiMfile, f_name_ascii = asciiMtfile, type=type,
max_memory_in_Gbytes=availmemGb, dims = dim_of_M, quiet = quiet, message=message )
message("\n Writing of marker data to disc is complete ... \n")
} else {
ncol <- dim_of_M[2]
dim_of_M[2] <- 2*dim_of_M[2] + 6
it_worked <- createM_ASCII_rcpp(f_name = file_genotype, type=type, f_name_ascii = asciiMfile, AA ="-9", AB = "-9", BB = "-9",
max_memory_in_Gbytes=availmemGb, dims = dim_of_M , quiet = quiet,
message=message, missing="NA")
if(!it_worked)
return(FALSE)
dim_of_M[2] <- ncol
message(" \n Taking transpose of marker data and writing untransposed and transposed data to disc ... \n")
createMt_ASCII_rcpp(f_name = asciiMfile, f_name_ascii = asciiMtfile, type=type,
max_memory_in_Gbytes=availmemGb, dims = dim_of_M, quiet = quiet, message=message )
message(" \n Writing of marker data to disc is complete ... \n")
}
return(TRUE)
}
|
aqs_credentials <- function(username = NA_character_, key = NA_character_)
{
if (!is.na(username) ||
!is.na(key) ||
!is_character(username) ||
!is_character(key)
)
{
options(aqs_username = username)
options(aqs_key = key)
} else {cat("Please enter a valid username and key \n") }
}
aqs_sign_up <- function(email)
{
url <- glue("https://aqs.epa.gov/data/api/signup?email={email}")
httr::GET(url)
glue("A verification email will be sent to {email} \n") %>%
message()
}
|
context("diagnose design")
test_that("error when you send other objects to diagnose", {
expect_error(diagnose_design(rep(3, 2)), "Please only send design objects or functions with no arguments.")
})
test_that("default diagnosands work", {
my_designer <- function(N = 10) {
my_population <- declare_population(N = N, noise = rnorm(N))
my_potential_outcomes <-
declare_potential_outcomes(Y_Z_0 = noise, Y_Z_1 = noise + rnorm(N, mean = 2, sd = 2))
my_assignment <- declare_assignment(Z = complete_ra(N, m = 25))
my_inquiry <- declare_inquiry(ATE = mean(Y_Z_1 - Y_Z_0))
my_estimator <- declare_estimator(Y ~ Z, inquiry = my_inquiry)
my_measurement <- declare_measurement(Y = reveal_outcomes(Y ~ Z))
design <- my_population +
my_potential_outcomes +
my_inquiry +
declare_step(dplyr::mutate, q = 5) +
my_assignment +
my_measurement +
my_estimator
diagnosands <- declare_diagnosands(med_bias = median(estimate - estimand))
set_diagnosands(design, diagnosands)
}
design_1 <- my_designer(N = 100)
design_2 <- my_designer(N = 200)
diag <- diagnose_design(
design_2 = design_2,
design_1 = design_1,
sims = 2
)
expect_equal(dim(tidy(diag)), c(2, 9))
expect_equal(names(tidy(diag)), c("design", "inquiry", "estimator", "term", "diagnosand", "estimate",
"std.error", "conf.low", "conf.high"))
expect_equal(names(diag$diagnosands_df),
c("design", "inquiry", "estimator", "term",
"med_bias", "se(med_bias)", "n_sims"
))
design_1 <- set_diagnosands(my_designer(N = 100), NULL)
design_2 <- set_diagnosands(my_designer(N = 200), NULL)
diagnosand_1 <- declare_diagnosands(my_bias = median(estimate - estimand))
diagnosand_2 <- declare_diagnosands(my_power = mean(p.value <= .5))
diag <- diagnose_design(
design_2 = set_diagnosands(design_2, diagnosand_2),
design_1 = set_diagnosands(design_1, diagnosand_1),
sims = 2
)
expect_equal(dim(tidy(diag)), c(4, 9))
expect_equal(names(tidy(diag)), c("design", "inquiry", "estimator", "term", "diagnosand", "estimate",
"std.error", "conf.low", "conf.high"))
expect_equal(names(diag$diagnosands_df), c("design", "inquiry", "estimator", "term",
"my_bias", "se(my_bias)", "my_power",
"se(my_power)", "n_sims"))
diag <- diagnose_design(
design_2 = design_2,
design_1 = design_1,
sims = 2
)
expect_equal(names(diag$diagnosands_df),
c("design", "inquiry", "estimator", "term", "mean_estimand",
"se(mean_estimand)", "mean_estimate", "se(mean_estimate)", "bias",
"se(bias)", "sd_estimate", "se(sd_estimate)", "rmse", "se(rmse)",
"power", "se(power)", "coverage", "se(coverage)", "n_sims"))
expect_equal(dim(tidy(diag)), c(14, 9))
expect_equal(names(tidy(diag)), c("design", "inquiry", "estimator", "term", "diagnosand", "estimate",
"std.error", "conf.low", "conf.high"))
diag <- diagnose_design(
design_2 = design_2,
design_1 = design_1,
diagnosands = declare_diagnosands(med_bias = median(estimate - estimand)),
sims = 2
)
expect_equal(names(diag$diagnosands_df),
c("design", "inquiry", "estimator", "term",
"med_bias", "se(med_bias)", "n_sims"
))
expect_equal(dim(tidy(diag)), c(2, 9))
expect_equal(names(tidy(diag)), c("design", "inquiry", "estimator", "term", "diagnosand", "estimate",
"std.error", "conf.low", "conf.high"))
designs <- expand_design(my_designer, N = c(100, 200))
diag <- diagnose_design(designs, sims = 5, bootstrap_sims = FALSE)
expect_equal(names(diag$diagnosands_df),
c("design", "N", "inquiry", "estimator", "term",
"med_bias", "n_sims"))
expect_equal(dim(tidy(diag)), c(2, 7))
expect_equal(names(tidy(diag)), c("design", "inquiry", "estimator", "term", "N", "diagnosand", "estimate"))
attr(designs[[1]], "diagnosands") <- NULL
diag <- diagnose_design(designs, sims = 5, bootstrap_sims = FALSE)
expect_equal(ncol(diag$diagnosands_df), 14)
expect_equal(dim(tidy(diag)), c(16, 7))
expect_equal(names(tidy(diag)), c("design", "inquiry", "estimator", "term", "N", "diagnosand", "estimate"))
sims <- set_diagnosands(simulate_design(designs, sims = 5), declare_diagnosands(med_bias = median(estimate - estimand)))
diag <- diagnose_design(sims, sims = 5, bootstrap_sims = FALSE)
expect_equal(dim(tidy(diag)), c(2, 7))
expect_equal(names(tidy(diag)), c("design", "inquiry", "estimator", "term", "N", "diagnosand", "estimate"))
})
test_that("more term",{
population <-
declare_model(N = 100,
Z = rep(0:1, 50),
Y = rnorm(N))
inquiries_regression <- declare_inquiry(
`(Intercept)` = 0,
`Z` = 1,
term = TRUE,
label = "Regression_Inquiries"
)
estimators_regression <- declare_estimator(Y ~ Z,
inquiry = inquiries_regression,
model = lm_robust,
term = TRUE)
inquiry_2 <- declare_inquiry(ATE = 2, label = "2")
estimator_2 <-
declare_estimator(Y ~ Z, inquiry = inquiry_2, label = "dim")
design <-
population + inquiries_regression + estimators_regression + inquiry_2 + estimator_2
sims_df <- simulate_design(design, sims = 1)
expect_equal(nrow(sims_df), 3)
expect_equal(sims_df[, 1:6],
structure(
list(
design = c("design", "design", "design"),
sim_ID = c(1L, 1L, 1L),
inquiry = c("ATE", "Regression_Inquiries",
"Regression_Inquiries"),
estimand = c(2, 0, 1),
estimator = c("dim",
"estimator", "estimator"),
term = c("Z", "(Intercept)", "Z")
),
class = "data.frame",
row.names = c(NA,-3L)
))
})
test_that("diagnose_design does not reclass the variable N", {
skip_if(compareVersion("3.5", paste(R.Version()$major, R.Version()$minor, sep = ".")) == 1)
design <-
declare_model(N = 5, noise = rnorm(N)) +
declare_inquiry(mean_noise = mean(noise))
designs <- redesign(design, N = 5:10)
dx <- diagnose_design(designs, sims = 50, bootstrap_sims = FALSE)
expect_equal(class(dx$simulations_df$N), "integer")
expect_equal(class(dx$diagnosands_df$N), "integer")
expect_equal(class(tidy(dx)$N), "integer")
designer <- function(N = 5) {
declare_model(N = N, noise = rnorm(N)) +
declare_inquiry(mean_noise = mean(noise))
}
designs <- expand_design(designer, N = 5:10)
dx <- diagnose_design(designs, sims = 50, bootstrap_sims = FALSE)
expect_equal(class(dx$simulations_df$N), "integer")
expect_equal(class(dx$diagnosands_df$N), "integer")
expect_equal(class(tidy(dx)$N), "integer")
})
test_that("diagnose_design works when simulations_df lacking parameters attr", {
design <- declare_model(N = 100, X = rnorm(N), Y = rnorm(N, X)) +
declare_inquiry(true_effect = 1) +
declare_estimator(Y ~ X, model=lm_robust, inquiry = "true_effect", label = "Y on X")
simulations <- simulate_design(design, sims = 20)
simulations_no_attr <- simulations
attributes(simulations_no_attr)["parameters"] <- NULL
d1 <- diagnose_design(simulations, bootstrap_sims = FALSE)
d2 <- diagnose_design(simulations_no_attr, bootstrap_sims = FALSE)
attributes(d1$simulations_df)["parameters"] <- NULL
d1$simulations_df$design <- as.character(d1$simulations_df$design)
d1$diagnosands_df$design <- as.character(d1$diagnosands_df$design)
d1["parameters_df"] <- list(NULL)
d1$duration <- NULL
d2$duration <- NULL
expect_identical(d1,d2)
expect_identical(tidy(d1), tidy(d2))
})
test_that("diagnose_design stops when a zero-row simulations_df is sent", {
expect_error(diagnose_design(data.frame(estimator = rep(1, 0))), "which has zero rows")
})
test_that("diagnose_design can generate and use grouping variables", {
set.seed(5)
design <-
declare_model(N = 100, u = rnorm(N),
Y_Z_0 = 0,
Y_Z_1 = ifelse(rbinom(N, 1, prob = 0.5), 0.1, -0.1) + u
) +
declare_assignment(Z = complete_ra(N)) +
declare_inquiry(ATE_positive = mean(Y_Z_1 - Y_Z_0) > 0) +
declare_measurement(Y = reveal_outcomes(Y ~ Z)) +
declare_estimator(Y ~ Z, inquiry = "ATE_positive")
diagnosis <- diagnose_design(design,
make_groups = vars(estimand, significant = p.value <= 0.05),
sims = 5
)
expect_equivalent(diagnosis$diagnosands_df$significant, c(FALSE, FALSE))
expect_equivalent(diagnosis$diagnosands_df$estimand, c(FALSE, TRUE))
expect_equal(dim(tidy(diagnosis)), c(14, 11))
expect_equal(names(tidy(diagnosis)), c("design", "inquiry", "estimator", "term", "estimand", "significant", "diagnosand", "estimate",
"std.error", "conf.low", "conf.high"))
design <-
declare_model(N = 100, u = rnorm(N),
Y_Z_0 = 0,
Y_Z_1 = ifelse(rbinom(N, 1, prob = 0.5), 0.1, -0.1) + u
) +
declare_assignment(Z = complete_ra(N)) +
declare_inquiry(ATE = mean(Y_Z_1 - Y_Z_0)) +
declare_measurement(Y = reveal_outcomes(Y ~ Z)) +
declare_estimator(Y ~ Z, inquiry = "ATE")
diagnosis <- diagnose_design(
design,
make_groups = vars(effect_size = cut(
estimand, quantile(estimand, (0:4) / 4), include.lowest = TRUE
)),
sims = 5
)
expect_equivalent(nrow(diagnosis$diagnosands_df), 4)
expect_equal(dim(tidy(diagnosis)), c(28, 10))
expect_equal(names(tidy(diagnosis)), c("design", "inquiry", "estimator", "term", "effect_size", "diagnosand",
"estimate", "std.error", "conf.low", "conf.high"))
design <-
declare_model(N = 100, u = rnorm(N),
Y_Z_0 = 0,
Y_Z_1 = ifelse(rbinom(N, 1, prob = 0.5), 0.1, -0.1) + u
) +
declare_assignment(Z = complete_ra(N)) +
declare_inquiry(ATE_positive = mean(Y_Z_1 - Y_Z_0) > 0) +
declare_measurement(Y = reveal_outcomes(Y ~ Z)) +
declare_estimator(Y ~ Z, inquiry = "ATE_positive")
diagnosis <- diagnose_design(design,
make_groups = vars(significant = ifelse(p.value > 0.1, NA, p.value <= 0.05)),
sims = 5
)
expect_equal(dim(tidy(diagnosis)), c(14, 10))
expect_equal(names(tidy(diagnosis)), c("design", "inquiry", "estimator", "term", "significant", "diagnosand",
"estimate", "std.error", "conf.low", "conf.high"))
print(diagnosis, digits = 5, select = "Bias")
diagnosis <- diagnose_design(design,
make_groups = vars(significant = factor(ifelse(p.value > 0.1, NA, p.value <= 0.05))),
sims = 100
)
expect_equal(dim(tidy(diagnosis)), c(21, 10))
expect_equal(names(tidy(diagnosis)), c("design", "inquiry", "estimator", "term", "significant", "diagnosand",
"estimate", "std.error", "conf.low", "conf.high"))
})
test_that("tidy.diagnosis handles NAs", {
design <-
declare_model(N = 10, Y = rnorm(N)) +
declare_estimator(Y ~ 1, label = "normal") +
declare_estimator(handler = function(data){data.frame(estimate = 5)})
dx <- diagnose_design(design, sims = 5)
expect_equal(dim(tidy(dx)), c(14, 8))
set.seed(343)
portola <-
fabricate(
N = 2100,
Y_star = rnorm(N)
)
design <-
declare_model(data = portola) +
declare_measurement(Y = as.numeric(cut(Y_star, 7))) +
declare_inquiry(Y_bar = mean(Y)) +
declare_sampling(S = complete_rs(N, n = 100)) +
declare_measurement(
R = rbinom(n = N, size = 1, prob = pnorm(Y_star + effort)),
Y = ifelse(R == 1, Y, NA_real_)
) +
declare_estimator(Y ~ 1, inquiry = "Y_bar") +
declare_estimator(R ~ 1, label = "Response Rate")
designs <- redesign(design, effort = seq(0, 5, by = 1))
diagnosis <-
diagnose_designs(
designs,
sims = 20,
bootstrap_sims = 20
)
expect_equal(sum(is.na(tidy(diagnosis) %>% dplyr::filter(diagnosand == "mean_estimate", estimator == "estimator") %>% dplyr::pull(estimate))), 0)
})
|
shifted_gamma <- function(shape = 1, scale = 1, shift = 0, autoscale = TRUE) {
validate_parameter_value(scale)
nlist(dist = "gamma", df = NA, shape, scale, shift, autoscale)
}
hexp <- function(prior_aux = rstanarm::exponential(0.03)) {
check_prior(prior_aux)
check_in_set(prior_aux$dist, ok_aux_dists)
out <- nlist(dist = "hexp", prior_aux)
out$df <- NA
out$location <- NA
out$scale <- 1
out$autoscale <- FALSE
return(out)
}
|
xport.dateFMT <- function(when, fill=16)
{
if(missing(when)) when <- Sys.time()
date.format <- sprintf("%%-%d.%ds", fill, fill)
toupper(sprintf(date.format, format(when, "%d%b%y:%H:%M:%S")))
}
|
setMethod("pemix",
signature(x = "REBMIX"),
function(x,
pos,
variables,
lower.tail,
log.p, ...)
{
digits <- getOption("digits"); options(digits = 15)
if (missing(x)) {
stop(sQuote("x"), " object of class REBMIX is requested!", call. = FALSE)
}
if (!is.wholenumber(pos)) {
stop(sQuote("pos"), " integer is requested!", call. = FALSE)
}
length(pos) <- 1
if ((pos < 1) || (pos > nrow(x@summary))) {
stop(sQuote("pos"), " must be greater than 0 and less or equal than ", nrow(x@summary), "!", call. = FALSE)
}
Dataset <- x@Dataset[[which(names(x@Dataset) == x@summary[pos, "Dataset"])]]
d <- ncol(Dataset); dini <- d; variables <- eval(variables)
n <- nrow(Dataset)
if (length(variables) != 0) {
if (!is.wholenumber(variables)) {
stop(sQuote("variables"), " integer is requested!", call. = FALSE)
}
if ((min(variables) < 1) || (max(variables) > d)) {
stop(sQuote("variables"), " must be greater than 0 and less or equal than ", d, "!", call. = FALSE)
}
variables <- unique(variables); d <- length(variables)
}
else {
variables <- 1:d
}
if (!is.logical(lower.tail)) {
stop(sQuote("lower.tail"), " logical is requested!", call. = FALSE)
}
if (!is.logical(log.p)) {
stop(sQuote("log.p"), " logical is requested!", call. = FALSE)
}
Dataset <- as.matrix(Dataset[, variables])
F <- array(data = 0.0, dim = n, dimnames = NULL)
if (lower.tail == TRUE) {
for (i in 1:n) {
F[i] <- sum(apply(Dataset <= Dataset[i,], 1, all))
}
}
else {
for (i in 1:n) {
F[i] <- sum(apply(Dataset > Dataset[i,], 1, all))
}
}
F <- F / n
if (log.p == TRUE) {
F <- log(F)
}
output <- as.data.frame(cbind(Dataset, F), stringsAsFactors = FALSE)
colnames(output) <- c(paste("x", if (dini > 1) variables else "", sep = ""), "F")
options(digits = digits)
rm(list = ls()[!(ls() %in% c("output"))])
output
})
setMethod("pemix",
signature(x = "REBMVNORM"),
function(x,
pos,
variables,
lower.tail,
log.p, ...)
{
digits <- getOption("digits"); options(digits = 15)
if (missing(x)) {
stop(sQuote("x"), " object of class REBMVNORM is requested!", call. = FALSE)
}
if (!is.wholenumber(pos)) {
stop(sQuote("pos"), " integer is requested!", call. = FALSE)
}
length(pos) <- 1
if ((pos < 1) || (pos > nrow(x@summary))) {
stop(sQuote("pos"), " must be greater than 0 and less or equal than ", nrow(x@summary), "!", call. = FALSE)
}
Dataset <- x@Dataset[[which(names(x@Dataset) == x@summary[pos, "Dataset"])]]
d <- ncol(Dataset); dini <- d; variables <- eval(variables)
n <- nrow(Dataset)
if (length(variables) != 0) {
if (!is.wholenumber(variables)) {
stop(sQuote("variables"), " integer is requested!", call. = FALSE)
}
if ((min(variables) < 1) || (max(variables) > d)) {
stop(sQuote("variables"), " must be greater than 0 and less or equal than ", d, "!", call. = FALSE)
}
variables <- unique(variables); d <- length(variables)
}
else {
variables <- 1:d
}
if (!is.logical(lower.tail)) {
stop(sQuote("lower.tail"), " logical is requested!", call. = FALSE)
}
if (!is.logical(log.p)) {
stop(sQuote("log.p"), " logical is requested!", call. = FALSE)
}
Dataset <- as.matrix(Dataset[, variables])
F <- array(data = 0.0, dim = n, dimnames = NULL)
if (lower.tail == TRUE) {
for (i in 1:n) {
F[i] <- sum(apply(Dataset <= Dataset[i,], 1, all))
}
}
else {
for (i in 1:n) {
F[i] <- sum(apply(Dataset > Dataset[i,], 1, all))
}
}
F <- F / n
if (log.p == TRUE) {
F <- log(F)
}
output <- as.data.frame(cbind(Dataset, F), stringsAsFactors = FALSE)
colnames(output) <- c(paste("x", if (dini > 1) variables else "", sep = ""), "F")
options(digits = digits)
rm(list = ls()[!(ls() %in% c("output"))])
output
})
|
source(here::here('dictionary/utilities.R'))
url <- 'http://geonames.nga.mil/gns/html/Docs/GEOPOLITICAL_CODES.xls'
filename <- tempfile(fileext = '.xls')
httr::GET(url, write_disk(filename, overwrite=TRUE))
bad <- c('AKROTIRI SOVEREIGN BASE AREA', 'ASHMORE AND CARTIER ISLANDS', 'BAKER ISLAND',
'CLIPPERTON ISLAND', 'CORAL SEA ISLANDS', 'DHEKELIA SOVEREIGN BASE AREA',
'ETOROFU, HABOMAI, KUNASHIRI, AND SHIKOTAN ISLANDS', 'EUROPA ISLAND',
'GLORIOSO ISLANDS', 'HOWLAND ISLAND', 'JAN MAYEN', 'JARVIS ISLAND',
'JOHNSTON ATOLL', 'JUAN DE NOVA ISLAND', 'KINGMAN REEF', 'MIDWAY ISLANDS',
'NAVASSA ISLAND', 'PALMYRA ATOLL', 'PARACEL ISLANDS', 'SAINT MARTIN',
'SPRATLY ISLANDS', 'TROMELIN ISLAND', 'WAKE ISLAND', 'BASSAS DA INDIA', 'GAZA STRIP')
out <- readxl::read_excel(filename, sheet = 'TABLE 1', skip = 2) %>%
select(fips = Code, country = Name) %>%
filter(!country %in% bad)
out %>% write_csv('dictionary/data_fips.csv', na = "")
|
get.360matchFree <- function(Match){
print("Whilst we are keen to share data and facilitate research, we also urge you to be responsible with the data. Please register your details on https://www.statsbomb.com/resource-centre and read our User Agreement carefully.")
Events.url <- paste0("https://raw.githubusercontent.com/statsbomb/open-data/master/data/three-sixty/",
Match$match_id[1], ".json")
raw.events.api <- GET(url = Events.url)
events.string <- rawToChar(raw.events.api$content)
Encoding(events.string) <- "UTF-8"
events <- fromJSON(events.string, flatten = T)
events <- events %>% mutate(match_id = Match$match_id[1],
competition_id = Match$competition.competition_id[1],
season_id = Match$season.season_id[1])
return(events)
}
|
print_dust_html <- function(x, ..., asis=TRUE,
linebreak_at_end = getOption("pixie_html_linebreak", 2),
interactive = getOption("pixie_interactive"))
{
if (is.null(interactive)) interactive <- interactive()
if (!is.null(x$caption) & x$caption_number) increment_pixie_count()
caption_number_prefix <-
if (x$caption_number) sprintf("Table %s: ", get_pixie_count())
else ""
label <-
if (is.null(x[["label"]]))
{
chunk_label <- knitr::opts_current$get("label")
if (is.null(chunk_label))
sprintf("tab:pixie-%s", getOption("pixie_count"))
else
sprintf("tab:%s", chunk_label)
}
else
{
sprintf("tab:%s", x[["label"]])
}
label <-
if (x[["bookdown"]])
{
sprintf("(\\
}
else
{
caption_number_prefix
}
if (!is.numeric(x$longtable) & x$longtable) longtable_rows <- 25L
else if (!is.numeric(x$longtable) & !x$longtable) longtable_rows <- as.integer(max(x$body$row))
else longtable_rows <- as.integer(x$longtable)
Divisions <- data.frame(div_num = rep(1:ceiling(max(x$body$row) / longtable_rows),
each = longtable_rows)[1:max(x$body$row)],
row_num = 1:max(x$body$row))
total_div <- max(Divisions$div_num)
head <- part_prep_html(x$head, head = TRUE,
fixed_header = x[["fixed_header"]],
fixed_header_class_name = x[["fixed_header_param"]][["fixed_header_class_name"]])
body <- part_prep_html(x$body)
foot <- if (!is.null(x$foot)) part_prep_html(x$foot) else NULL
interfoot <- if (!is.null(x$interfoot)) part_prep_html(x$interfoot) else NULL
tmpfile <- tempfile(fileext=".html")
non_interactive <- ""
for (i in 1:total_div){
tbl <- dplyr::bind_rows(head,
body[Divisions$row_num[Divisions$div_num == i], , drop=FALSE],
if (i == total_div) foot else interfoot)
rows <- apply(tbl, 1, paste0, collapse = "\n")
rows <- sprintf("<tr>\n%s\n</tr>", rows)
justify <-
if (x[["justify"]] == "center") "margin:auto"
else sprintf("float:%s", x[["justify"]])
float_guard <-
if (x[["justify"]] == "center") ""
else "<div style = 'clear:both'></div>"
fixed_head_css <-
if (x[["fixed_header"]] & x[["include_fixed_header_css"]])
do.call(fixed_header_css,
c(x[["fixed_header_param"]],
list(pretty = FALSE)))
else ""
if (x[["fixed_header"]]){
fixed_head_open_tag <-
sprintf("<div style = 'text-align:%s'><section class='%s-section'><div class='%s-container'><div>",
x[["justify"]],
x[["fixed_header_param"]][["fixed_header_class_name"]],
x[["fixed_header_param"]][["fixed_header_class_name"]])
fixed_head_close_tag <- "</div></section></div>"
}
else{
fixed_head_open_tag <- fixed_head_close_tag <- ""
}
html_code <- sprintf("%s%s%s<table style = '%s;border-collapse:%s;'>\n%s\n</table>%s%s%s",
float_guard,
fixed_head_css,
fixed_head_open_tag,
justify,
x$border_collapse,
paste0(rows, collapse = "\n"),
fixed_head_close_tag,
float_guard,
paste0(rep("</br>", linebreak_at_end), collapse = ""))
if (!is.null(x$caption))
html_code <- sub(">",
sprintf(">\n<caption>%s %s</caption>",
label, x$caption),
html_code)
if (interactive & asis){
write(html_code, tmpfile, append = i > 1)
}
else non_interactive <- paste0(non_interactive, html_code)
}
if (interactive & asis){
getOption("viewer")(tmpfile)
}
else if (asis){
if (x$html_preserve) knitr::asis_output(htmltools::htmlPreserve(non_interactive))
else knitr::asis_output(non_interactive)
}
else {
if (x$html_preserve) htmltools::htmlPreserve(non_interactive)
else non_interactive
}
}
part_prep_html <- function(part, head=FALSE,
fixed_header = FALSE, fixed_header_class_name = "")
{
numeric_classes <- c("double", "numeric")
dh <-
if (head)
{
if (fixed_header){
sprintf("th class = 'th-%s'", fixed_header_class_name)
}
else
{
"th"
}
}
else
{
"td"
}
part <- perform_function(part)
logic <- part$round == "" & part$col_class %in% numeric_classes
part$round[logic] <- getOption("digits")
logic <- part$col_class %in% numeric_classes
if (any(logic))
part$value[logic] <-
as.character(roundSafe(part$value[logic], as.numeric(part$round[logic])))
logic <- !is.na(part[["replace"]])
part[["value"]][logic] <- part[["replace"]][logic]
boldify <- part$bold
part$bold[boldify] <- "font-weight:bold;"
part$bold[!boldify] <- ""
italicize <- part$italic
part$italic[italicize] <- "font-style:italic;"
part$italic[!italicize] <- ""
logic <- part$halign == ""
part$halign[logic] <- vapply(X = part$col_class[logic],
FUN = default_halign,
FUN.VALUE = character(1),
print_method = "html")
part$halign <-
with(part, sprintf("text-align:%s;", halign))
logic <- part$valign != ""
part$valign[logic] <-
with(part, sprintf("vertical-align:%s;", valign[logic]))
logic <- part$bg != ""
part$bg[logic] <-
with(part, sprintf("background-color:%s;", bg[logic]))
logic <- part$font_family != ""
part$font_family[logic] <-
with(part, sprintf("font-family:%s;", font_family[logic]))
logic <- part$font_color != ""
part$font_color[logic] <-
with(part, sprintf("color:%s;", font_color[logic]))
logic <- part$font_size != ""
part$font_size[logic] <-
with(part, sprintf("font-size:%s%s;",
font_size[logic],
font_size_units[logic]))
logic <- part$height != ""
part$height[logic] <-
with(part, sprintf("height:%s%s;", height[logic], height_units[logic]))
logic <- part$width != ""
part$width[logic] <-
with(part, sprintf("width:%s%s;", width[logic], width_units[logic]))
logic <- part$top_border != ""
part$top_border[logic] <-
with(part, sprintf("border-top:%s;", top_border[logic]))
logic <- part$bottom_border != ""
part$bottom_border[logic] <-
with(part, sprintf("border-bottom:%s;", bottom_border[logic]))
logic <- part$left_border != ""
part$left_border[logic] <-
with(part, sprintf("border-left:%s;", left_border[logic]))
logic <- part$right_border != ""
part$right_border[logic] <-
with(part, sprintf("border-right:%s;", right_border[logic]))
logic <- is.na(part$value) & !is.na(part$na_string)
part$value[logic] <-
part$na_string[logic]
logic <- part$pad != ""
part$pad[logic] <-
with(part, sprintf("padding:%spx;", pad[logic]))
logic <- part$rotate_degree != ""
part$rotate_degree[logic] <-
with(part, rotate_tag(rotate_degree[logic]))
part$value <-
with(part, sprintf("<%s colspan = '%s'; rowspan = '%s'; style='%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s'>%s %s</%s>",
dh, colspan, rowspan,
bold, italic, halign, valign, bg, font_family,
font_color, font_size, height, width,
top_border, bottom_border, left_border, right_border,
rotate_degree, pad,
value,
if (fixed_header) paste0("<div>", value, "</div>") else "",
substr(dh, 1, 2)))
ncol <- max(part$col)
part <- dplyr::filter_(part, "!(rowspan == 0 | colspan == 0)")
logic <-
part[["row"]] == part[["html_row"]] &
part[["col"]] == part[["html_col"]] &
part[["colspan"]] > 1
if ("html_row_pos" %in% names(part))
part[["html_row"]][logic] <- part[["html_row_pos"]][logic]
if ("html_col_pos" %in% names(part))
part[["html_col"]][logic] <- part[["html_col_pos"]][logic]
part <- dplyr::select_(part, "html_row", "html_col", "value") %>%
tidyr::spread_("html_col", "value", fill = "") %>%
dplyr::select_("-html_row")
if (ncol(part) != ncol){
part <- dplyr::bind_cols(part,
do.call("cbind",
lapply(1:(ncol - ncol(part)),
function(i) dplyr::data_frame(value = ""))))
names(part) <- 1:ncol
}
part
}
rotate_tag <- function(degree)
{
sprintf(
paste0("-webkit-transform:rotate(%sdeg);",
"-moz-transform:rotate(%sdeg);",
"-ms-transform:rotate(%sdeg);",
"-o-transform:rotate(%sdeg);",
"transform:rotate(%sdeg);"),
degree, degree, degree, degree, degree)
}
|
compCDF <- function(data, weights,
x=seq(min(data, na.rm=TRUE), max(data, na.rm=TRUE), len=250),
comp=1:NCOL(weights), makeplot=TRUE, ...) {
if (NROW(weights) != NROW(data)) {
stop("data and weights arguments must have same number of rows")
}
weights <- t(t(weights) / (NCOL(data) * colSums(weights)))
f <- function(row, cutpt) colSums(outer(row, cutpt, "<="), na.rm = TRUE)
bc <- apply(data, 1, f, x)
cdfs <- bc %*% weights[,comp,drop=FALSE]
if(makeplot) {
plot(range(x), 0:1, type="n", ...)
for (i in 1:length(comp)) {
lines(x, cdfs[,comp[i]], lty=i, ...)
}
}
t(cdfs)
}
|
doPermimp <- function(object, input, inp, y, OOB, threshold, conditional,
whichxnames, ntree, nperm, scaled,
progressBar, thresholdDiagnostics,
w, AUC, pre1.0_0, mincriterion, asParty)
{
if (conditional) {
if(!all(complete.cases(input)))
stop("cannot compute variable importance measure with missing values")
if (conditional && threshold == 1) {
warning(sQuote("permimp"),
paste0(": Unable to permute conditionally. \n",
"The chosen threshold is too high, no variables to condition on were selected. \n",
"Instead the unconditional permimp values are computed. "),
call. = FALSE, immediate. = TRUE)
doPermimpCall <- match.call()
doPermimpCall$conditional <- FALSE
return(eval(doPermimpCall))
}
}
xnames <- colnames(input)
if(is.null(whichxnames)) {
whichxnames <- xnames
whichVarIDs <- seq_along(xnames)
}
else {
whichVarIDs <- match(whichxnames, table = xnames)
if(length(whichVarIDs) < 1){
stop("Error: whichxnames is not a subset of the predictor variable names in the forest.")
}
whichVarIDs <- whichVarIDs[order(whichVarIDs)]
}
type <- getOutcomeType(object)
error <- selectError(type, AUC)
nullError <- selectNullError(type)
pred <- selectPred(object, type, w, inp, y)
if (conditional && asParty) {
cond_list <- create_cond_list(binnedVars = NULL, threshold,
input, seq_along(xnames), asParty = TRUE)
}
perror <- array(0, dim = c(ntree, length(xnames), nperm),
dimnames = list(NULL, xnames, NULL))
changeThres <- array(NA, dim = c(ntree, length(xnames), nperm),
dimnames = list(NULL, xnames, NULL))
if(progressBar) pBar <- txtProgressBar(min = 0, max = ntree,
style = 3, char = "|")
for (treeNr in seq_len(ntree)){
tree <- getTree(object, treeNr)
if(OOB){oob <- getOOB(object, treeNr)} else {oob <- rep(TRUE, length(y))}
p <- pred(tree, inp, mincriterion, -1L, input)
eoob <- error(p, oob, y)
varsInTree <- intersect(unique(varIDs(tree)), whichVarIDs)
if(conditional) {
binnedVars <- makeBinnedVars(varsInTree, tree, oob, input)
if (!asParty) {
cond_list <- create_cond_list(binnedVars, threshold, input, varsInTree, asParty = FALSE)
}
}
for(j in varsInTree){
for (per in 1:nperm){
if (!conditional && !pre1.0_0){
p <- pred(tree, inp, mincriterion, as.integer(j))
}
else {
if(conditional){
changeThres[treeNr, j, per] <- 0
if(asParty)
varsToCondOn <- intersect(cond_list[[as.character(j)]], varsInTree)
else varsToCondOn <- cond_list[[as.character(j)]]
if(length(varsToCondOn) < 1){
changeThres[treeNr, j, per] <- -1
perm <- sample(which(oob))
} else {
perm <- conditional_perm(varID = j, varsToCondOn,
binnedVars, oob, asParty)
}
}
else{
perm <- sample(which(oob))
}
if(is.null(perm)) {
changeThres[treeNr, j, per] <- 1
break}
tmp <- replacePermVar(input, inp, permVarNr = j, oob, perm)
p <- pred(tree, tmp, mincriterion, -1L, input = tmp)
}
perror[treeNr, j, per] <- (error(p, oob, y) - eoob)
}
}
if(scaled){
perror[treeNr, , per] <- perror[treeNr, , per]/nullError(y, oob)
}
if(progressBar) setTxtProgressBar(pBar , treeNr)
}
perror <- apply(perror[ , whichVarIDs, , drop = FALSE], c(1, 2), mean)
perror <- as.data.frame(perror)
if(thresholdDiagnostics){
changeThres <- apply(changeThres[ , whichVarIDs, , drop = FALSE], 2, mean, na.rm = TRUE)
increaseThres <- changeThres > .5
decreaseThres <- changeThres < -.5
if(any(increaseThres[!is.na(increaseThres)])){
warning(sQuote("permimp"),
paste0(" Unable to permute conditionally for ",
sum(increaseThres),
" variable(s) in 50 percent of the cases.\n",
"Increasing the threshold may help. \n",
"The variables for which conditionally permuting (often) was impossible are: ",
ifelse(sum(increaseThres) > 6,
paste0("(showing only six) \n - ",
paste0(whichxnames[increaseThres][1:6], collapse = "\n - ")),
paste0("\n - ",
paste0(whichxnames[increaseThres], collapse = "\n - ")))),
call. = FALSE, immediate. = TRUE)
}
if(any(decreaseThres[!is.na(decreaseThres)])){
warning(sQuote("permimp"),
paste0(" Conditionally permuting the predictor values of ",
sum(decreaseThres),
" variable(s) had no impact in 50 percent of the cases.\n",
"Decreasing the threshold may help. \n",
"The variables for which conditionally permuting (often) had no impact are: ",
ifelse(sum(decreaseThres) > 6,
paste0("(showing only six) \n - ",
paste0(whichxnames[decreaseThres][1:6], collapse = "\n - ")),
paste0("\n - ",
paste0(whichxnames[decreaseThres], collapse = "\n - ")))),
call. = FALSE, immediate. = TRUE)
}
}
info <- list()
if(conditional){
info$threshold = threshold
if (asParty) info$conditioning = "as party"
else info$conditioning = "permimp implementation"
}
info$outcomeType = type
if (info$outcomeType == "nominal2") info$outcomeType <- "binary"
if (type == "survival") info$errorType <- "Brier score"
else if (type == "regression") info$errorType <- "MSE"
else info$errorType <- "accuracy"
if(AUC && type == "nominal2") info$errorType <- "AUC"
out <- as.VarImp(perror,
FUN = mean,
type = 'if'(conditional, "Conditional Permutation", "Permutation"),
info = info)
if(progressBar) close(pBar)
return(out)
}
|
classify_milestone_network <- function(milestone_network) {
is_directed <- any(milestone_network$directed)
gr <- milestone_network %>%
mutate(weight = length) %>%
igraph::graph_from_data_frame(directed = is_directed) %>%
simplify_igraph_network()
props <- determine_milenet_props(gr)
network_type <- determine_network_type(props)
lst(network_type, directed = props$is_directed, properties = props)
}
determine_network_type <- function(props) {
with(props, {
if (is_directed) {
if (num_components > 1) {
"disconnected_graph"
} else {
if (!has_cycles) {
if (num_branch_nodes == 0) {
"linear"
} else if (num_branch_nodes == 1) {
if (num_convergences == 0) {
if (max_degree <= 3 && max_degree_out < 3) {
"bifurcation"
} else {
"multifurcation"
}
} else if (num_divergences == 0) {
"convergence"
} else {
"acyclic_graph"
}
} else {
if (num_convergences == 0) {
"tree"
} else {
"acyclic_graph"
}
}
} else {
if (num_branch_nodes == 0) {
"cycle"
} else
"graph"
}
}
} else {
if (num_components > 1) {
"disconnected_graph"
} else {
if (!has_cycles) {
if (num_branch_nodes == 0) {
"linear"
} else if (num_branch_nodes == 1) {
if (max_degree == 3) {
"bifurcation"
} else {
"multifurcation"
}
} else {
"tree"
}
} else {
if (num_branch_nodes == 0) {
"cycle"
} else {
"graph"
}
}
}
}
})
}
determine_milenet_props <- function(gr) {
requireNamespace("igraph")
is_directed <- igraph::is_directed(gr)
is_self_loop <- sapply(igraph::V(gr), function(n) igraph::are_adjacent(gr, n, n))
num_components <- igraph::components(gr)$no
if (is_directed) {
degr_in <- igraph::degree(gr, mode = "in")
degr_out <- igraph::degree(gr, mode = "out")
degr_tot <- degr_in + degr_out
max_degree_in <- max(degr_in)
max_degree_out <- max(degr_out)
is_begin <- degr_in == is_self_loop & degr_out != 0
is_end <- degr_in != 0 & degr_out == 0
is_branch <- degr_out > 1 | degr_in > 1
is_outer <- is_begin | is_end
num_begin_nodes <- sum(is_begin)
num_end_nodes <- sum(is_end)
num_branch_nodes <- sum(is_branch)
num_outer_nodes <- sum(is_outer)
num_divergences <- sum(degr_out > 1)
num_convergences <- sum(degr_in > 1)
} else {
degr_tot <- igraph::degree(gr)
is_outer <- degr_tot == 1 + is_self_loop
is_branch <- !is_outer
num_outer_nodes <- sum(is_outer)
num_branch_nodes <- sum(is_branch)
}
max_degree <- max(degr_tot)
has_cycles <- any(is_self_loop) || has_cycle_function(gr)
out <- lst(
is_directed,
max_degree,
degr_tot,
is_branch,
is_outer,
num_branch_nodes,
num_outer_nodes,
is_self_loop,
has_cycles,
num_components
)
if (is_directed) {
c(out, lst(
degr_in,
degr_out,
max_degree_in,
max_degree_out,
num_divergences,
num_convergences,
is_begin,
is_end,
num_begin_nodes,
num_end_nodes
))
} else {
out
}
}
has_cycle_function <- function(gr) {
if (igraph::is_directed(gr)) {
for (from in igraph::V(gr)) {
for (to in igraph::V(gr)) {
if (from != to) {
one <- igraph::distances(gr, from, to, mode = "out")
two <- igraph::distances(gr, to, from, mode = "out")
if (is.finite(one) && is.finite(two)) {
return(TRUE)
}
}
}
}
return(FALSE)
} else {
for (from in names(igraph::V(gr))) {
if (any(duplicated(igraph::neighbors(gr, from) %>% names))) {
return(TRUE)
}
for (to in names(igraph::V(gr))) {
if (from != to && igraph::are_adjacent(gr, from, to) && length(igraph::E(gr)) > 1) {
newgr <- gr - igraph::edge(paste0(from, "|", to))
if (is.finite(igraph::distances(newgr, from, to))) {
return(TRUE)
}
}
}
}
return(FALSE)
}
}
|
yates <- function(fit, method=c("ATT", "STT", "NSTT")) {
method <- match.arg(method)
X <- model.matrix(fit)
ax <- attr(X, "assign")
xcon <- attr(X, "contrasts")
Terms <- terms(fit)
dfac <- attr(Terms, "factors")
nacoef <- is.na(coef(fit))
if (any(nacoef)) {
ax[nacoef] <- 0
X[,nacoef] <- 0
}
ux <- unique(ax)
ux <- ux[ux!=0]
if (length(ux)==0) return(NULL)
clist <- vector("list", length(ux))
names(clist) <- dimnames(dfac)[[2]]
dtemp <- diag(length(ax))
dimnames(dtemp) <- list(NULL, dimnames(X)[[2]])
for (i in 1:length(ux))
clist[[i]] <- dtemp[ax== ux[i],]
forder <- attr(Terms, "order")
fvar <- dimnames(dfac)[[1]] %in% names(xcon)
fterm <- colSums(dfac[!fvar,, drop=FALSE]) ==0
included <- diag(ncol(dfac))
for (i in which(fterm)) {
temp <- dfac[,i] * dfac
keep <- (colSums(temp) >0 & forder >=forder[i] & fterm)
included[i,keep] <- 1
}
adjust <- which(rowSums(included) >1)
if (length(adjust) >0 && method != "NSTT") {
if (method=="ATT") {
for (i in adjust) {
icol <- ax %in% which(included[i,] >0)
xfac <- unique(X[, icol, drop=FALSE])
afac <- ax[icol]
xtemp <- xfac[,afac==i, drop=FALSE]
index <- xmatch(xtemp)
dtemp <- matrix(0., max(index), ncol(X),
dimnames=list(NULL, dimnames(X)[[2]]))
for (j in 1:max(index))
dtemp[j, icol] <- colMeans(xfac[index==j,, drop=FALSE])
clist[[i]] <- dtemp[-1,] - rep(dtemp[1,], each=nrow(dtemp)-1)
}
} else {
}
}
temp <- lapply(clist, contrast, fit)
list(ss = sapply(temp, function(x) x$ss),
df = sapply(temp, function(x) x$df),
detail = temp)
}
xmatch <- function(x) {
ux <- unique(x)
result <- integer(nrow(x))
for (i in 1:nrow(x)){
for (j in 1:nrow(ux)) if (all(x[i,] == ux[j,])) result[i] <- j
}
result
}
qform <- function(beta, var)
sum(beta * solve(var, beta))
contrast <- function(cmat, fit) {
varmat <- vcov(fit)
if (class(fit) == "lm") sigma2 <- summary(fit)$sigma^2
else sigma2 <- 1
beta <- coef(fit)
if (!is.matrix(cmat)) cmat <- matrix(cmat, nrow=1)
if (ncol(cmat) != length(beta)) stop("wrong dimension for contrast")
estimate <- drop(cmat %*% beta)
ss <- qform(estimate, cmat %*% varmat %*% t(cmat)) *sigma2
list(contrast=cmat, estimate=estimate, ss=ss, df=qr(cmat)$rank,
var=drop(cmat %*% varmat %*% t(cmat)))
}
|
resampLmer <-
function(resamp,dam,sire,response,start,end,ml=F) {
if (missing(resamp)) stop("Need the resampled data frame")
if (missing(dam)) stop("Need the dam column name")
if (missing(sire)) stop("Need the sire column name")
if (missing(response)) stop("Need the response column name")
if (missing(start)) stop("Need the starting model number")
if (missing(end)) stop("Need the ending model number")
print(time1<- Sys.time())
response2<- colnames(resamp)[grep(paste(response), colnames(resamp))]
dam2<- colnames(resamp)[grep(paste(dam), colnames(resamp))]
sire2<- colnames(resamp)[grep(paste(sire), colnames(resamp))]
mod<- matrix(0,ncol=4,nrow=length(response2))
for (j in start:end) {
print(paste("Working on model: ", j, sep=""))
if (ml == F) {
m<- lmer(formula= noquote(paste(response2[j],"~ (1|",dam2[j],") + (1|",sire2[j],") + (1|",dam2[j],":",sire2[j],")",sep="")),
data=resamp) }
if (ml == T) {
m<- lmer(formula= noquote(paste(response2[j],"~ (1|",dam2[j],") + (1|",sire2[j],") + (1|",dam2[j],":",sire2[j],")",sep="")),
data=resamp, REML=F) }
mod[j,]<- c(colSums(diag(VarCorr(m))),attr(VarCorr(m),"sc")^2)
col_names<- as.data.frame(VarCorr(m))$grp; rm(m) }
comp<- as.data.frame(mod)
colnames(comp)<- col_names
comp$Total<- rowSums(comp)
colnames(comp)<- gsub(end,'', colnames(comp))
temp<- comp
colnames(temp)[which(colnames(temp)==dam)]<- "dam"
colnames(temp)[which(colnames(temp)==sire)]<- "sire"
colnames(temp)[which(colnames(temp)==noquote(paste(dam,":",sire,sep="")))]<- "dam:sire"
comp$additive<- 4*temp$sire
comp$nonadd<- 4*temp$'dam:sire'
comp$maternal<- temp$dam- temp$sire
print(Sys.time()- time1)
invisible(comp)
}
|
set.seed(320)
par(mfrow = c(1, 2))
x = matrix(rnorm(200), ncol = 2)
plot(x, pch = c(4, 19)[kmeans(x, centers = 2)$cluster],
xlab = "$x_1$", ylab = "$x_2$")
library(alphahull)
plot(ahull(x, alpha = 0.4), xlab = "$x_1$", ylab = "$x_2$")
box()
|
read_gbk <- function(file, sources=NULL, types=NULL, infer_cds_parents=TRUE){
gb2gff <- base::system.file("exec/gb2gff", package="gggenomes")
if(file_is_zip(file) && file_suffix(file, ignore_zip = FALSE) != "gz")
abort(str_glue("Decompressing for genbank only works with gzipped files, not `{suf}`"))
if(file_is_url(file) && file_is_zip(file)){
file <- pipe(str_glue("curl {file} | gzip -cd | {gb2gff} -S"))
}else if(file_is_url(file)){
file <- pipe(str_glue("curl {file} | {gb2gff} -S"))
}else if(file_is_zip(file)){
suf <- file_suffix(file, ignore_zip = FALSE)
if(suf != "gz")
abort(str_glue("Decompressing for genbank only works with gzipped files, not `{suf}`"))
file <- pipe(str_glue("gzip -cd {file} | {gb2gff} -S"))
}else{
file <- pipe(str_glue("{gb2gff} -S {file}"))
}
read_gff3(file, sources=sources, types=types,
infer_cds_parents=infer_cds_parents)
}
|
a.estimate <-
function (data, to = 1, min_points, alpha = 0.05, g = 1, r = 1)
{
cl <- match.call()
if (round(max(data), 1) == round(2 * pi, 1))
data<-unique(data/(2*pi))
data<-sort(unique(data))
data <- c(data - 1, data, data + 1)
close_to_min_index <- unique(findInterval(min_points, data) + 1)
CVM_rejectionpnt <- numeric(length(close_to_min_index))
AD_rejectionpnt <- numeric(length(close_to_min_index))
KS_rejectionpnt <- numeric(length(close_to_min_index))
rayleigh_rejectionpnt <- numeric(length(close_to_min_index))
for (k in 1 : length(close_to_min_index))
{
end <- close_to_min_index[k]
begin <- close_to_min_index[k] - (length(data) / 3)
start <- begin
endpoint <- end
lengte <- endpoint-start-1
ks <- numeric(trunc(lengte / g))
ks_p <- numeric(trunc(lengte / g))
c <- numeric(trunc(lengte / g))
d <- numeric(trunc(lengte / g))
asq <- numeric(trunc(lengte / g))
asq_p <- numeric(trunc(lengte / g))
CVM_pvalue <- numeric(trunc(lengte / g))
rayleigh_p <- numeric(trunc(lengte / g))
tol <- 1e-20
j <- 1
CVM_rejection <- FALSE
KS_rejection <- FALSE
AD_rejection <- FALSE
rayleigh_rejection <- FALSE
rejected <- (CVM_rejection & KS_rejection & AD_rejection & rayleigh_rejection)
while (!rejected & (j <= trunc(lengte / g)))
{
sn<-0
n<-0
sn_star<-0
star_pval<-0
start <- endpoint - (j * g) - 1
n <- endpoint - start - 1
d[j] <- n
if (n < 8)
{
asq[j] <- 0
asq_p[j] <-0.999
}
else
{
sn <- ad.test(data[(start + 1) : (endpoint - 1)],punif, data[start]-tol, data[endpoint]+tol)
asq[j] <-sn$statistic
asq_p[j] <-sn$p.value
}
sn <- ((data[(start + 1) : (endpoint - 1)] - data[start]) / (data[endpoint] - data[start]) - (1 : n - 0.5)/(n))^2
c[j] <- sum(sn) + (1 / (12 * n))
CVM_pvalue[j] <- CVM_pvall(c[j], n)
ks[j] <- ks.test(data[(start + 1) : (endpoint - 1)], punif, data[start], data[endpoint])$statistic
ks_p[j] <- ks.test(data[(start + 1) : (endpoint - 1)], punif, data[start], data[endpoint])$p.value
rayleigh_p[j] <- rayleigh.test(circular(((data[(start + 1) : (endpoint - 1)]) - data[(start + 1)]) / (data[(endpoint - 1)] - data[(start + 1)]) * 2 * pi))$p.value
if (rayleigh_p[j] == "NaN")
rayleigh_p[j] <- 1
if (j >= r)
{
if (CVM_rejection == FALSE)
{
if (max(CVM_pvalue[(j - r + 1) : j]) < alpha)
{
CVM_rejection <- TRUE
if (endpoint - 1 - ((j - r + 1) * g) >= ((length(data) / 3) + 1))
CVM_rejectionpnt[k] <- (data[endpoint - 1 - ((j - r + 1) * g)]) / 1
else CVM_rejectionpnt[k] <- (data[endpoint - 1- ((j - r + 1) * g) + (length(data) / 3)])/1
}
}
if (KS_rejection == FALSE)
{
if (max(ks_p[(j - r + 1) : j]) < alpha)
{
KS_rejection <- TRUE
if (endpoint - 1 - ((j - r + 1) * g) >= ((length(data) / 3) + 1))
KS_rejectionpnt[k] <- (data[endpoint - 1 - ((j - r + 1) * g)]) / 1
else KS_rejectionpnt[k] <- (data[endpoint - 1 - ((j - r + 1) * g)+(length(data) / 3)]) / 1
}
}
if (AD_rejection == FALSE)
{
if (max(asq_p[(j - r + 1) : j]) < alpha)
{
AD_rejection <- TRUE
if (endpoint - 1 - ((j - r + 1) * g) >= ((length(data) / 3) + 1))
AD_rejectionpnt[k] <- (data[endpoint - 1 - ((j - r + 1) * g)]) / 1
else AD_rejectionpnt[k] <- (data[endpoint - 1 - ((j - r + 1) * g) + (length(data) / 3)]) / 1
}
}
if (rayleigh_rejection == FALSE)
{
if (max(rayleigh_p[(j - r + 1) : j]) < alpha)
{
rayleigh_rejection <- TRUE
if (endpoint - 1 - ((j - r + 1) * g) >= ((length(data) / 3) + 1))
rayleigh_rejectionpnt[k] <- (data[endpoint - 1 - ((j - r + 1) * g)]) / 1
else rayleigh_rejectionpnt[k] <- (data[endpoint - 1 - ((j - r + 1) * g) + (length(data) / 3)]) / 1
}
}
}
rejected <- (CVM_rejection & KS_rejection & AD_rejection & rayleigh_rejection)
j <- j + 1
}
if (!(is.na(which(c == 0)[1])))
CVM_pvalue <- CVM_pvalue[1 : ((which(CVM_pvalue == 0)[1]) - 1)]
if (!(is.na(which(ks == 0)[1])))
ks <- ks[1 : ((which(ks == 0)[1] - 1))]
if (!(is.na(which(ks_p == 0)[1])))
ks_p <- ks_p[1 : ((which(ks_p == 0)[1] - 1))]
if (!(is.na(which(asq == 0)[1])))
asq <- asq[1 : ((which(asq == 0)[1] - 1))]
if (!(is.na(which(asq_p == 0)[1])))
asq_p <- asq_p[1 : ((which(asq_p == 0)[1] - 1))]
if (!(is.na(which(rayleigh_p == 0)[1])))
rayleigh_p<-rayleigh_p[1 : ((which(rayleigh_p == 0)[1] - 1))]
}
vec <- c(mean(CVM_rejectionpnt), mean(KS_rejectionpnt), mean(AD_rejectionpnt), mean(rayleigh_rejectionpnt))
sum <- matrix(c(mean(CVM_rejectionpnt), mean(KS_rejectionpnt), mean(AD_rejectionpnt), mean(rayleigh_rejectionpnt), median(vec)), ncol=5, dimnames=list(c("a-hat"),
c("Cramer von Mises", "Kolmogorov-Smirnoff", "Anderson-Darling", "Rayleigh", "MEDIAN")))
CVM <- list(rejection = CVM_rejectionpnt, mean = mean(CVM_rejectionpnt))
KS <- list(rejection = KS_rejectionpnt, mean = mean(KS_rejectionpnt))
AD <- list(rejection = AD_rejectionpnt, mean = mean(AD_rejectionpnt))
rayleigh <- list(rejection = rayleigh_rejectionpnt, mean = mean(rayleigh_rejectionpnt))
general<-list(call = cl, Minimums = data[close_to_min_index], alpha = alpha, grow = g, nr_reject = r, kernel_function = "Epanechnikov")
comb<-list(summary = sum, General = general)
return(comb)
}
|
blockNorm <- function(X, targetnorm = 1) {
if (!any(class(X) %in% c("matrix", "data.frame"))) {
stop("X should be a matrix or optionally a data.frame")
}
if (is.data.frame(X)) {
X <- as.matrix(X)
}
if (targetnorm == 1) {
f <- sum(X^2, na.rm = TRUE)^0.5
} else {
fmax <- sum(X^2, na.rm = TRUE)
fmaxn <- sum((X / fmax)^2, na.rm = TRUE)
if (fmaxn > targetnorm) {
fmin <- fmax
fminn <- fmaxn
while (fminn > targetnorm) {
fmin <- fmin * 10
fminn <- sum((X / fmin)^2, na.rm = TRUE)
}
} else {
fmin <- fmax
fminn <- fmaxn
while (fmaxn < targetnorm) {
fmax <- fmax / 10
fmaxn <- sum((X / fmax)^2, na.rm = TRUE)
}
}
n <- fmaxn
while ((targetnorm - n)^2 > 1e-12) {
f <- (fmin + fmax) / 2
n <- sum((X / f)^2, na.rm = TRUE)
if (n > targetnorm) {
fmax <- f
} else {
fmin <- f
}
}
}
Xn <- X / f
return(list(Xscaled = Xn, f = f))
}
|
rvmatrix <- function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL) {
data <- as.vector(data)
if (missing(nrow))
nrow <- ceiling(length(data)/ncol)
else if (missing(ncol))
ncol <- ceiling(length(data)/nrow)
if (byrow) {
X <- t(rvarray(data, c(ncol, nrow), dimnames=dimnames))
} else {
X <- rvarray(data, c(nrow, ncol), dimnames=dimnames)
}
return(X)
}
rvarray <- function (data = NA, dim = length(data), dimnames = NULL) {
as.rv(array(data = data, dim = dim, dimnames = dimnames))
}
is.matrix.rv <- function (x) {
dx <- dim(x)
return((!is.null(dx)) && length(dx)==2)
}
as.matrix.rv <- function (x, ...) {
if (is.matrix(x)) {
return(x)
}
dn <- if (!is.null(names(x))) list(names(x), NULL) else NULL
rvarray(x, dim=c(length(x), 1), dimnames=dn)
}
|
r_versions <- function(dots = TRUE) {
df <- r_versions_fetch()
dotver <- gsub('-', '.', df$version)
if (dots) df$version <- dotver
nicks <- cached_nicks()
nonick <- setdiff(dotver, names(nicks))
if (length(nonick)) nicks <- c(nicks, get_nicknames(nonick))
df$date <- as.POSIXct(
strptime(df$date, "%Y-%m-%dT%H:%M:%S", tz = "UTC")
)
df$nickname <- rep(NA_character_, nrow(df))
df$nickname[match(names(nicks), dotver)] <- nicks
df
}
r_release <- function(dots = TRUE) {
tail(r_versions(dots), 1)
}
r_oldrel <- function(dots = TRUE) {
versions <- r_versions(dots)
version_strs <- package_version(versions$version)
major <- version_strs$major
minor <- version_strs$minor
major_minor <- paste(major, sep = ".", minor)
latest <- tail(major_minor, 1)
tail(versions[ major_minor != latest, ], 1)
}
cache <- new.env(parent = emptyenv())
r_versions_fetch <- function() {
if (is.null(cache$versions)) {
h <- handle_setheaders(new_handle(customrequest = "PROPFIND"), Depth="1")
req <- curl_fetch_memory(r_svn_url(), handle = h)
doc <- read_xml(rawToChar(req$content))
prop <- xml_find_all(doc, ".//D:propstat/D:prop", xml_ns(doc))
dates <- xml_text(xml_find_first(prop, ".//D:creationdate", xml_ns(doc)))
tags <- xml_text(xml_find_first(prop, ".//D:getetag", xml_ns(doc)))
tags <- sub("^.*/tags/R-([-0-9]+).*$", "\\1", tags)
is_release <- grepl("^[0-9]+-[0-9]+(-[0-9]+|)$", tags)
tags <- tags[is_release]
dates <- dates[is_release]
versions <- data.frame(
stringsAsFactors = FALSE,
version = tags,
date = dates
)
df <- versions[order(package_version(tags)), ]
rownames(df) <- NULL
cache$versions <- df
}
cache$versions
}
|
expected <- eval(parse(text="FALSE"));
test(id=0, code={
argv <- eval(parse(text="list(structure(list(B = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L), .Label = c(\"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\"), class = \"factor\"), V = structure(c(3L, 3L, 3L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c(\"Golden.rain\", \"Marvellous\", \"Victory\"), class = \"factor\"), N = structure(c(2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c(\"0.0cwt\", \"0.2cwt\", \"0.4cwt\", \"0.6cwt\"), class = \"factor\"), Y = c(130L, 157L, 174L, 117L, 114L, 161L, 141L, 105L, 140L, 118L, 156L, 61L, 91L, 97L, 100L, 70L, 108L, 126L, 149L, 96L, 124L, 121L, 144L, 68L, 64L, 112L, 86L, 60L, 102L, 89L, 96L, 89L, 129L, 132L, 124L, 74L, 89L, 81L, 122L, 64L, 103L, 132L, 133L, 70L, 89L, 104L, 117L, 62L, 90L, 100L, 116L, 80L, 82L, 94L, 126L, 63L, 70L, 109L, 99L, 53L, 74L, 118L, 113L, 89L, 82L, 86L, 104L, 97L, 99L, 119L, 121L)), .Names = c(\"B\", \"V\", \"N\", \"Y\"), row.names = 2:72, class = \"data.frame\"))"));
do.call(`is.environment`, argv);
}, o=expected);
|
mutate_other <- function(.data,
var,
n = 5,
count,
by = NULL,
var.weight = NULL,
mass = NULL,
copy = TRUE,
other.category = "Other"){
stopifnot(is.data.table(.data),
is.character(other.category),
identical(length(other.category), 1L))
if (is.character(.data[[var]])){
had.key <- haskey(.data)
if (!isTRUE(copy)){
stop("`copy` was ", copy, ", but must be TRUE.")
}
out <- copy(.data)
has_null_nom_attr <- is.null(attr(names(out), ".match.hash"))
if (had.key){
orig_key <- key(out)
} else {
orig_key <- "_order"
out[, "_order" := seq_len(.N)]
setkeyv(out, "_order")
}
stopifnot(!("nvar" %in% names(out)),
var %in% names(out))
N <- .rank <- NULL
if ("N" %chin% names(out)) {
if ("_temp" %chin% names(out)) {
`_temp` <- NULL
new_nom <- paste0(names(out), collapse = "x")
n_by_var <-
out %>%
.[, stats::setNames(list(`_temp` = .N), nm = new_nom), keyby = c(var, by)] %>%
setorderv(c(by, new_nom)) %>%
.[, .rank := seq_len(.N), by = by]
} else {
n_by_var <-
out %>%
.[, .(`_temp` = .N), keyby = c(var, by)] %>%
.[, .rank := rank(-`_temp`), by = by]
}
} else {
n_by_var <-
out %>%
.[, .N, keyby = c(var, by)] %>%
.[, .rank := rank(-N), by = by]
}
if (!is.null(var.weight)) {
stopifnot(var.weight %chin% names(out))
if ("wEiGhT" %in% names(out)) {
stop("`data` contained column `wEiGhT`, but this is not allowed ",
"as it conflicts with `mutate_other` internals. ",
"Rename this column (temporarily at least) to use `mutate_other`.")
}
if (".rank" %in% names(out)) {
stop("`data` contained column `.rank`, but this is not allowed ",
"as it conflicts with `mutate_other` internals. ",
"Rename this column (temporarily at least) to use `mutate_other`.")
}
setnames(out, var.weight, "wEiGhT")
wEiGhT <- NULL
wt_by_var <- out[, .(wEiGhT = sum(wEiGhT)), keyby = c(var, by)]
setorderv(wt_by_var, "wEiGhT", order = -1L)
wt_by_var[, .rank := seq_len(.N), by = by]
if (!missing(mass) && !is.null(n)) {
warning("`mass` was provided, yet `n` was not set to NULL. ",
"As a result, `mass` may be misinterpreted. ",
"If you intended to use `mass` to create the other category, ",
"set `n = NULL`. Otherwise, do not provide `mass`.")
}
if (is.null(n)) {
if (is.null(mass)) {
warning("Setting mass to negative infinity. Choose a better value.")
mass <- -Inf
}
wt_by_var[, .rank := NULL]
out <- wt_by_var[out, on = c(var, by)]
out[wEiGhT < mass, (var) := other.category]
out[, wEiGhT := NULL]
setnames(out, "i.wEiGhT", var.weight)
} else {
wt_by_var[, wEiGhT := NULL]
out <- wt_by_var[out, on = c(var, by)]
out[.rank > n, (var) := other.category]
out[, .rank := NULL]
setnames(out, "wEiGhT", var.weight)
}
} else {
out <- n_by_var[out, on = c(var, by)]
if (missing(count) || is.null(count)) {
out[.rank > n, (var) := other.category]
} else {
out[N < count, (var) := other.category]
}
out[, N := NULL]
out[, .rank := NULL]
}
setkeyv(out, orig_key)
if (!had.key){
out[, (orig_key) := NULL]
setkey(out, NULL)
}
out
} else {
warning("`by` was not a character vector, so `mutate_other()` will have no effect.")
return(.data)
}
}
|
powernoise <- function(k, N) {
N2 = floor(N/2)-1;
f = (2:(N2+1))
A2 = 1/(f^(k/2))
p2 = complex(real=matrix(stats::rnorm(N2*1,0,1),N2,1), imaginary=matrix(stats::rnorm(N2*1,0,1),N2,1))
d2 = A2*p2;
d = c(1,d2,1/((N2+2)^k),rev(Conj(d2)))
x = Re(stats::fft(d, inverse=T))
xdft = stats::fft(x)
xdft = xdft[1:(N/2+1)]
psd_fft = (1/(2*pi*N))*abs(xdft)^2
psd_fft[2:(length(psd_fft)-1)] = 2*psd_fft[2:(length(psd_fft)-1)]
f_fft = seq(from=0, to=pi, by=(2*pi)/N)
psp=psd_fft/stats::var(x);
x_scaled = (x - mean(x))/stats::sd(x)
ret.list = list(x_scaled,psp,f_fft)
names(ret.list) = c("x", "psp", "f_fft")
return(ret.list)
}
|
find_dependencies <- function(function_name, envir = .GlobalEnv, in_envir = TRUE, add_info = FALSE) {
purrr::map_dfr(function_name, ~ {
func <- tryCatch(
get(.x, envir = envir),
error = function(e) NULL
)
if (is.null(func)) {
message("No ", .x, " in given environment")
return(NULL)
}
f_body <- deparse(body(func), width.cutoff = 500L)
calls <- unlist(stringr::str_extract_all(
f_body,
"[[:alnum:]\\.\\_]+\\(|[[:alnum:]\\.\\_]+::[[:alnum:]\\.\\_]+\\("
))
calls <- stringr::str_remove_all(calls, "\\(")
arguments <- unlist(stringr::str_extract_all(f_body, "\\((.*?)\\)"))
arguments <- unlist(stringr::str_remove_all(arguments, "^\\(|\\)$"))
arguments <- unlist(stringr::str_extract_all(
arguments,
"[[:alnum:]\\.\\_]+|[[:alnum:]\\.\\_]+::[[:alnum:]\\.\\_]+"
))
functions <- tibble::tibble(
Source = c(calls, arguments)
) %>%
dplyr::group_by(Source) %>%
dplyr::tally(name = "SourceRep")
if (in_envir) {
functions <- dplyr::filter(functions, Source %in% ls(envir))
}
is_fun <- vapply(functions$Source, function(x) {
tryCatch(
{
f_name <- stringr::str_split(x, "::")[[1]]
func <- if (length(f_name) == 2) {
getExportedValue(f_name[1], f_name[2])
} else {
get(x, envir = envir)
}
is.function(func)
},
error = function(e) FALSE
)},
logical(1)
)
functions <- dplyr::filter(functions, is_fun[names(is_fun) %in% functions$Source])
functions <- functions %>%
dplyr::bind_cols(tibble::as_tibble(stringr::str_locate(functions$Source, "::"))) %>%
dplyr::mutate(
SourceNamespace = ifelse(
is.na(start),
Vectorize(find, "what")(Source, mode = "function"),
stringr::str_sub(Source, 1, start - 1)
),
SourceNamespace = gsub("package:", "", SourceNamespace),
SourceNamespace = ifelse(SourceNamespace == "character(0)", NA, SourceNamespace),
SourceNamespace = ifelse(Source %in% ls(envir), "user-defined", SourceNamespace),
Source = ifelse(
is.na(start),
Source,
stringr::str_sub(Source, end + 1)
)
) %>%
dplyr::select(-c(start, end))
if (nrow(functions) == 0) {
functions <- tibble::tibble(
Source = NA,
SourceRep = 0,
SourceNamespace = "user-defined",
Target = .x,
TargetInDegree = 0
)
}
if (add_info) {
functions <- functions %>%
dplyr::rowwise() %>%
dplyr::mutate(
SourcePosition = list(grep(paste0("\\b", Source, "\\b"), f_body) - 1),
SourceContext = list(f_body[SourcePosition + 1])
) %>%
dplyr::ungroup()
}
functions %>%
dplyr::mutate(
Target = .x,
TargetInDegree = ifelse(is.na(Source), 0, nrow(.))
)
})
}
|
library(shiny)
library(shinydashboard)
source("../R/function.R")
source("../R/colorPicker.R")
source("../R/transformation.R")
source("../R/geneView.R")
source("../R/columnSelector.R")
source("../R/label.R")
source("../R/limit.R")
source("../R/global.R")
source("../R/clarion.R")
data <- data.table::as.data.table(mtcars, keep.rowname = "id")
metadata <- data.table::data.table(names(data), level = c("feature", rep("sample", 7), rep("condition", 4)), factor1 = c(rep("a", 5), rep("b", 7)), factor2 = c(rep("1", 7), rep("2", 5)), factor3 = c(rep("", 4), rep("test", 5), rep("test2", 3)))
names(metadata)[1] <- "key"
clarion <- Clarion$new(data = data, metadata = metadata)
ui <- dashboardPage(header = dashboardHeader(), sidebar = dashboardSidebar(
numericInput(inputId = "width", label = "width in cm", value = 0, min = 0),
numericInput(inputId = "height", label = "height in cm", value = 0, min = 0),
sliderInput(inputId = "scale", label = "scale plot", value = 1, min = 1, max = 10)
), dashboardBody(fluidPage(
geneViewUI("id")
)))
server <- function(input, output) {
gene <- callModule(geneView, "id", clarion = clarion, plot.method = "static", width = reactive(input$width), height = reactive(input$height), scale = reactive(input$scale))
observe({
print(gene())
})
}
shinyApp(ui = ui, server = server)
|
pal_tron <- function(palette = c("legacy"), alpha = 1) {
palette <- match.arg(palette)
if (alpha > 1L | alpha <= 0L) stop("alpha must be in (0, 1]")
raw_cols <- ggsci_db$"tron"[[palette]]
raw_cols_rgb <- col2rgb(raw_cols)
alpha_cols <- rgb(
raw_cols_rgb[1L, ], raw_cols_rgb[2L, ], raw_cols_rgb[3L, ],
alpha = alpha * 255L, names = names(raw_cols),
maxColorValue = 255L
)
manual_pal(unname(alpha_cols))
}
scale_color_tron <- function(palette = c("legacy"), alpha = 1, ...) {
palette <- match.arg(palette)
discrete_scale("colour", "tron", pal_tron(palette, alpha), ...)
}
scale_colour_tron <- scale_color_tron
scale_fill_tron <- function(palette = c("legacy"), alpha = 1, ...) {
palette <- match.arg(palette)
discrete_scale("fill", "tron", pal_tron(palette, alpha), ...)
}
|
choose.target <- function(x,lower,upper,n,tvectors=tvectors,
breakdown=FALSE){
if(is.data.frame(tvectors)){
tvectors <- as.matrix(tvectors)
}else if("textmatrix" %in% class(tvectors)){
tvectors <- matrix(tvectors,
nrow=nrow(tvectors),ncol=ncol(tvectors),
dimnames=list(rownames(tvectors),colnames(tvectors)))
}
if(is.matrix(tvectors)){
if(class(x) != "character"){
x <- as.character(x)
message("Note: x converted to character")
}
allwords <- vector(length=nrow(tvectors))
if(breakdown==TRUE){satz1 <- breakdown(x)}
if(breakdown==FALSE){satz1 <- x}
satz1split <- strsplit(satz1,split=" ")[[1]]
used1 <- satz1split[satz1split %in% rownames(tvectors)]
if(length(used1)==0){(warning("no element of x found in rownames(tvectors)"))
return(NA)}
if(length(used1) >1){satz1vec <- colSums(tvectors[used1,])}
if(length(used1)==1){satz1vec <- tvectors[used1,]}
for(i in 1:nrow(tvectors)){
allwords[i] <- cosine(satz1vec,tvectors[i,])
}
names(allwords) <- rownames(tvectors)
a <- sample(allwords[allwords >= lower & allwords <= upper])[1:n]
return(a)
}else{warning("tvectors must be a matrix!")}
}
|
setMethodS3("clearCalls", "AbstractCBS", function(fit, ...) {
segs <- fit$output
params <- fit$params
excl <- grep("Call$", colnames(segs))
if (length(excl) > 0L) {
segs <- segs[,-excl]
}
for (ff in c("deltaROH", "deltaAB", "deltaLOH")) {
params[[ff]] <- NULL
}
fit$output <- segs
fit$params <- params
invisible(fit)
}, protected=TRUE)
|
test_df <- rbind(
data.frame(
date = as.Date(c("2015-01-01", "2015-10-01", "2016-02-04", "2016-12-31", "2017-01-01", "2017-02-01", "2017-02-05", "2020-01-01")),
patient_id = "A"
),
data.frame(
date = as.Date(c("2015-01-01", "2016-02-01", "2016-12-31", "2017-01-01", "2017-02-03")),
patient_id = "B"
))
expect_equal(get_episode(test_df$date, 365),
c(1, 1, 2, 2, 2, 3, 3, 4, 1, 2, 2, 2, 3))
expect_equal(get_episode(test_df$date[which(test_df$patient_id == "A")], 365),
c(1, 1, 2, 2, 2, 2, 3, 4))
expect_equal(get_episode(test_df$date[which(test_df$patient_id == "B")], 365),
c(1, 2, 2, 2, 3))
if (AMR:::pkg_is_available("dplyr", min_version = "1.0.0")) {
expect_identical(test_df %>% group_by(patient_id) %>% mutate(f = is_new_episode(date, 365)) %>% pull(f),
c(TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE))
suppressMessages(
x <- example_isolates %>%
mutate(out = first_isolate(., include_unknown = TRUE, method = "episode-based", info = FALSE))
)
y <- example_isolates %>%
group_by(patient_id, mo) %>%
mutate(out = is_new_episode(date, 365))
expect_identical(which(x$out), which(y$out))
}
|
implicIndep <- function (expression, n.samples = 1, size.sample = 100, corr = "0") {
if (missing(expression)) {
errmsg <- paste0("The expression is missing.")
cat("\n")
stop(paste(strwrap(errmsg, exdent = 7), collapse = "\n"), call. = FALSE)
}
expression <- gsub(" ", "", expression)
antec <- substr(expression, 2, regexpr("<", expression)[1] - 1)
out.f <- substr(expression, regexpr(">", expression)[1] + 1, regexpr(")", expression)[1] - 1)
pos.irr.f <- as.vector(gregexpr("[+)]", expression)[[1]])
pos.irr.f <- tail(pos.irr.f, 2)
irr.f <- toupper(substr(expression, pos.irr.f[1] + 1, pos.irr.f[2] - 1))
pos.last.lower <- tail(as.vector(gregexpr("[a-z]", expression)[[1]]), 1)
pos.last.upper <- tail(as.vector(gregexpr("[A-Z]", expression)[[1]]), 1)
if (tail(pos.last.lower, 1) < tail(pos.last.upper, 1)) {
substr(expression, pos.last.lower, pos.last.lower) <- irr.f
substr(expression, pos.last.upper, pos.last.upper) <- tolower(irr.f)
}
disj.list <- as.list(unlist(strsplit(antec, "[+]")))
conj.list <- lapply(disj.list, function (x) {
if (grepl("[*]", antec)) {
sort(unlist(strsplit(x, "[*]")))
}
else if (!grepl("[0-9]", antec)) {
strs <- substring(x, 1:nchar(x), 1:nchar(x))
sort(strs[strs != ""])
}
else {sst <- strsplit(x, "")[[1]]
sort(paste0(sst[c(TRUE, FALSE)], sst[c(FALSE, TRUE)]))
}
}
)
if (any(sapply(conj.list, function (x) any(duplicated(toupper(x)))))) {
errmsg <- paste0("Check the expression. At least one disjunct contains a
contradiction or the same conjunct more than once.")
cat("\n")
stop(paste(strwrap(errmsg, exdent = 7), collapse = "\n"), call. = FALSE)
}
conj.sorted <- sort(unlist(lapply(conj.list, paste, collapse = "*")))
f.names <- c(unique(toupper(unlist(conj.list))), out.f, irr.f)
tt <- data.frame(mintermMatrix(rep(2, length(f.names))))
dimnames(tt) <- list(as.character(seq(2^length(f.names))), f.names)
antec.sorted <- paste(conj.sorted, sep = "", collapse = "+")
conj.repl <- gsub(
"[*]", ",", paste0("pmin(", unlist(strsplit(antec.sorted, "[+]")), ")")
)
subs <- paste0("pmax(", paste0(conj.repl, collapse = ","), ")", "==", out.f)
taut <- sub("[+]", ",", paste0(", pmax", substr(
expression, regexpr(irr.f, expression)[1] - 1, nchar(expression)))
)
coll <- paste0(gsub("([A-Z]+)", "tt$\\U\\1",
gsub("(\\b[a-oq-z][a-z0-9]*)", "1-\\U\\1",
paste0("pmin(", paste0(subs, taut), ")"), perl = TRUE),
perl = TRUE), "==TRUE"
)
tt <- tt[eval(parse(text = coll)), ]
out.col <- match(out.f, names(tt))
irr.col <- match(irr.f, names(tt))
if (identical(mean(tt[, out.col]), 1)) {
errmsg <- paste0("Check the expression. The endogenous factor is a constant.")
cat("\n")
stop(paste(strwrap(errmsg, exdent = 7), collapse = "\n"), call. = FALSE)
}
if (size.sample < nrow(tt)) {
errmsg <- paste0("The sample size must be at least ", nrow(tt), ".")
cat("\n")
stop(paste(strwrap(errmsg, exdent = 7), collapse = "\n"), call. = FALSE)
}
ded <- 2^(length(f.names) - 1)
dat.list <- sol.list <- vector("list", n.samples)
if (corr == "0") {
for (i in seq(length(dat.list))) {
set.seed(i)
dat.list[[i]] <- rbind(tt, head(tt[sample.int(nrow(tt), size.sample,
replace = TRUE), ], -ded))[order(sample.int(size.sample, size.sample)), ]
rownames(dat.list[[i]]) <- as.character(seq(size.sample))
sol.list[[i]] <- eQMC(dat.list[[i]], outcome = out.f)$solution
}
}
else {
if (corr == "+") {
add.to <- tt[tt[, out.col] == tt[, irr.col], ]
}
else {
add.to <- tt[tt[, out.col] != tt[, irr.col], ]
}
for (i in seq_along(dat.list)) {
set.seed(i)
dat.list[[i]] <- rbind(tt, head(add.to[sample.int(nrow(add.to), size.sample,
replace = TRUE), ], -ded))[order(sample.int(size.sample, size.sample)), ]
rownames(dat.list[[i]]) <- as.character(seq(size.sample))
sol.list[[i]] <- eQMC(dat.list[[i]], outcome = out.f)$solution
}
}
for (i in seq_along(sol.list)) {
for (j in seq_along(sol.list[[i]])) {
sol.list[[i]][[j]] <- lapply(sol.list[[i]][[j]], function (x) {
paste0(sort(unlist(
if (grepl("[*]", x)) {
strsplit(x, "[*]")
}
else {
strsplit(x, "")
}
)), collapse = "*")}
)
}
}
for (i in seq_along(sol.list)) {
for (j in seq_along(sol.list[[i]])) {
sol.list[[i]][[j]] <- gsub(
"[*]", "", paste0(sort(unlist(sol.list[[i]][[j]], recursive = FALSE)),
collapse = "+")
)
}
}
cor.list <- sapply(dat.list, function (x) round(cor(x[, out.col], x[, irr.col]), 4))
sols.obj <- list(tt = tt, dat.list = dat.list, sol.list = sol.list, cor.list = cor.list,
test = if ((any(sapply(sol.list, function (x) {
grepl(irr.f, x, ignore.case = TRUE)})) == FALSE) &
(gsub("[*]", "", antec.sorted) %in% unique(unlist(sol.list)) == FALSE)) {
paste(irr.f, "has been eliminated (expression was not a causal structure).")
}
else if (any(sapply(sol.list, function (x) {
grepl(irr.f, x, ignore.case = TRUE)}
)) == FALSE) {
paste(irr.f, "has been eliminated.")
}
else {
paste(irr.f, "has not been eliminated.")
}
)
return(sols.obj)
}
|
"Finnish_Lakes"
|
context("solr_group")
test_that("solr_group works", {
skip_on_cran()
a <- conn_plos$group(params = list(q='ecology', group.field='journal',
group.limit=3, fl=c('id','score')))
Sys.sleep(2)
b <- conn_plos$group(params = list(q='ecology', group.field='journal',
group.limit=3, fl=c('id','score','alm_twitterCount'),
group.sort='alm_twitterCount desc'))
Sys.sleep(2)
out <- conn_plos$group(params = list(q='ecology',
group.field=c('journal','article_type'), group.limit=3, fl='id'),
raw=TRUE)
Sys.sleep(2)
c <- out
d <- solr_parse(out, 'df')
e <- conn_plos$group(params = list(q='ecology', group.field='journal', group.limit=3, fl=c('id','score'),
group.format='grouped', group.main='true'))
suppressPackageStartupMessages(library('jsonlite', quietly = TRUE))
f <- jsonlite::fromJSON(out, FALSE)
expect_equal(NCOL(a), 5)
expect_equal(NCOL(b), 6)
expect_that(length(c), equals(1))
expect_that(length(d), equals(2))
expect_equal(NCOL(d$article_type), 4)
expect_equal(NCOL(e), 4)
expect_that(length(f), equals(1))
expect_that(length(f$grouped), equals(2))
expect_is(a, "data.frame")
expect_is(b, "data.frame")
expect_is(c, "sr_group")
expect_is(d, "list")
expect_is(d$journal, "data.frame")
expect_is(e, "data.frame")
})
test_that("solr_group old style works", {
skip_on_cran()
expect_is(solr_group(conn_plos,
params = list(q='ecology', group.field='journal',
group.limit=3, fl=c('id','score'))),
"data.frame"
)
expect_is(solr_group(conn_plos,
params = list(q='ecology', group.field='journal', group.limit=3, fl=c('id','score'),
group.format='grouped', group.main='true')),
"data.frame"
)
})
test_that("solr_group works when no group results and responseHeader exists", {
skip_on_cran()
x <- SolrClient$new(host = "services.itis.gov", scheme = "https",
port = NULL, errors = "complete")
args <- list(q = "nameWOInd:/[A-Za-z0-9]*[%20]{1,1}[A-Za-z0-9]*/",
group.field = 'rank', group.limit = 3)
expect_null(x$group(params = args))
})
|
lba.formula <- function(formula,
data,
A = NULL,
B = NULL,
K = 1L,
cA = NULL,
cB = NULL,
logitA = NULL,
logitB = NULL,
omsk = NULL,
psitk = NULL,
S = NULL,
T = NULL,
row.weights = NULL,
col.weights = NULL,
tolG = 1e-10,
tolA = 1e-05,
tolB = 1e-05,
itmax.unide = 1e3,
itmax.ide = 1e3,
trace.lba = TRUE,
toltype = 'all',
method = c("ls",
"mle"),
what = c('inner',
'outer'),
...)
{
data <- as.data.frame(apply(data,
2,
factor))
aux.form <- strsplit(as.character(formula),
'~')
var.col <- aux.form[[2]]
var.row <- aux.form[[3]]
var.row1 <- unlist(strsplit(var.row,
' \\+ '))
var.col1 <- unlist(strsplit(var.col,
' \\+ '))
aux.tables <- rep(list(list()),
length(var.row1))
aux.tables1 <- list()
for(i in 1:length(var.row1)){
for(j in 1:length(var.col1)){
aux.tables[[i]][[j]] <- table(data[[var.row1[i]]],
data[[var.col1[j]]])
}
aux.tables1[[i]] <- do.call('cbind',
aux.tables[[i]])
}
tabs <- do.call('rbind',
aux.tables1)
aux.namesR <- sapply(var.row1,
function(x)levels(data[[x]]),
simplify=F)
aux.namesR1 <- sapply(aux.namesR,
length)
aux.namesR2 <- rep(var.row1,
aux.namesR1)
rownames(tabs) <- paste(aux.namesR2,
dimnames(tabs)[[1]],
sep='')
aux.namesC <- sapply(var.col1,
function(x)levels(data[[x]]),
simplify=F)
aux.namesC1 <- sapply(aux.namesC,
length)
aux.namesC2 <- rep(var.col1,
aux.namesC1)
colnames(tabs) <- paste(aux.namesC2,
dimnames(tabs)[[2]],
sep='')
switch(match.arg(what),
inner = what <- 'inner',
outer = what <- 'outer')
switch(match.arg(method),
ls = method <- 'ls',
mle = method <- 'mle')
if(is.null(cA) & is.null(cB) & is.null(logitA) & is.null(logitB)){
class(tabs) <- method
result <- lba(tabs,
A = A,
B = B,
K = K,
row.weights = row.weights,
col.weights = col.weights,
tolG = tolG,
tolA = tolA,
tolB = tolB,
itmax.unide = itmax.unide,
itmax.ide = itmax.ide,
trace.lba = trace.lba,
toltype = toltype,
what = what,
...)
} else
if((!is.null(cA) | !is.null(cB)) & is.null(logitA) & is.null(logitB)){
class(tabs) <- paste(method,
'fe',
sep='.')
result <- lba(tabs,
A = A,
B = B,
K = K,
cA = cA,
cB = cB,
row.weights = row.weights,
col.weights = col.weights,
tolG = tolG,
tolA = tolA,
tolB = tolB,
itmax.unide = itmax.unide,
itmax.ide = itmax.ide,
trace.lba = trace.lba,
toltype = toltype,
what = what,
...)
} else {
class(tabs) <- paste(method,
'logit',
sep='.')
result <- lba(tabs,
A = A,
B = B,
K = K,
cA = cA,
cB = cB,
logitA = logitA,
logitB = logitB,
omsk = omsk,
psitk = psitk,
S = S,
T = T,
row.weights = row.weights,
col.weights = col.weights,
tolG = tolG,
tolA = tolA,
tolB = tolB,
itmax.unide = itmax.unide,
itmax.ide = itmax.ide,
trace.lba = trace.lba,
toltype = toltype,
what = what,
...)
}
n_dim <- length(result$pk)-1
if(n_dim == 1){
class(result) <- c('lba.1d',
class(result),
'lba.formula',
'lba')
}
if(n_dim == 2){
class(result) <- c('lba.2d',
class(result),
'lba.formula',
'lba')
}
if(n_dim >= 3){
class(result) <- c('lba.3d',
class(result),
'lba.formula',
'lba')
}
cl <- match.call()
result$call <- cl
result$what <- what
result$tab <- tabs
result
}
|
mnis_lords_type <- function(date = Sys.Date(), tidy = TRUE,
tidy_style = "snake_case") {
query <- paste0(base_url, "LordsByType/", as.Date(date), "/")
got <- mnis_query(query)
x <- tibble::as_tibble(as.data.frame(got$LordsByType))
if (tidy == TRUE) {
x <- mnis::mnis_tidy(x, tidy_style)
}
x
}
|
dser <- function(x,ser_weight,cost=costBAR, ...)
UseMethod("dser")
dser.data.frame <- function(x,ser_weight,cost=costBAR,...) {
dser.matrix(as.matrix(x),ser_weight,cost=cost,...)
}
dser.matrix <-function(x,ser_weight,cost=costBAR,scale=TRUE,dmethod="euclidean",...) {
if (!is.matrix(x) || !is.numeric(x))
stop("'x' must be 2d numeric matrix")
if (scale) x <- scale(x)
d <- dist(x,method=dmethod)
if (missing(ser_weight))
if (isTRUE(all.equal(cost, costLS)))
ser_weight <- x[,1]
else ser_weight <- as.matrix(d)
dser.dist(d,ser_weight,cost=cost,...)
}
dser.dist <- function(x,ser_weight,cost=costBAR,hmethod="average",...) {
h <- hclust(x,method=hmethod)
if (missing(ser_weight) && !isTRUE(all.equal(cost, costLS)))
ser_weight <- as.matrix(x)
DendSer(h,ser_weight,cost=cost,...)
}
dser.hclust <- function(x,ser_weight,cost=costBAR,...) {
DendSer(x,ser_weight,cost=cost,...)
}
|
with_groups <- function(.data, .groups, .f, ...) {
loc <- tidyselect::eval_select(enquo(.groups), data = tbl_ptype(.data))
val <- syms(names(.data)[loc])
out <- group_by(.data, !!!val)
.f <- as_function(.f)
out <- .f(out, ...)
dplyr_reconstruct(out, .data)
}
|
"gaussd" <-
function(kode=1,x) {
if (missing(x)) messagena("x")
p <- double(1)
f.res <- .Fortran("gausszd",
kode=to.integer(kode),
x=as.double(x),
p=as.double(p))
list(p=f.res$p)
}
|
mappingDE <- function(data, var = NULL, colID = NULL,
type = c("static", "interactive"),
typeStatic = c("tmap", "choro.cart", "typo", "bar"),
unit = c("state","district", "municipal", "municipality"),
matchWith = c("name", "code", "code_full"), dir = NULL,
add_text = NULL, subset = NULL,
facets = NULL, aggregation_fun = sum, aggregation_unit = NULL,
options = mapping.options())
{
check.unit.names = options$check.unit.names
use_cache = options$use_cache
use_internet = options$use_internet
type <- match.arg(type, choices = eval(formals(mappingUK)$type))
typeStatic <- match.arg(typeStatic, choices = eval(formals(mappingUK)$typeStatic))
if(!is.null(var))
{
if(is.numeric(var))
{
var <- colnames(data)[var]
}else{
if(!any(sapply(var, function(x) x == colnames(data))))
{
stop("Column names var does not exist.", call. = FALSE)
}
}
}
if(!inherits(data, "DE"))
{
data <- data.frame(data, check.names = FALSE)
unit <- match.arg(unit, choices = eval(formals(mappingDE)$unit))
matchWith <- match.arg(matchWith, choices = eval(formals(mappingDE)$matchWith))
data <- DE(data = data, colID = colID, unit = unit, matchWith = matchWith, subset = subset,
check.unit.names = check.unit.names, use_cache = use_cache, use_internet = use_internet, crs = options$crs,
aggregation_fun = aggregation_fun, aggregation_unit = aggregation_unit, aggregation_var = var, dir = dir)
colID <- attributes(data)$colID
}else
{
unit <- attributes(data)$unit
colID <- attributes(data)$colID
if(!is.null(subset))
{
if(!inherits(subset, "formula"))
{
stop("subset must be a formula.")
}
data <- subset_formula(data = data, formula = subset)
}
if(!is.null(aggregation_unit))
{
if(is.null(aggregation_fun))
{
stop("aggregation_fun must be provided to aggregate data")
}
if(any(aggregation_unit%in%c("state","district", "municipal", "municipality")))
{
unit <- aggregation_unit
nm <- getNamesDE(unit = unit, all_levels = TRUE)
if(attributes(data)$unit == aggregation_unit)
{
colnames(nm)[which(colnames(nm) == aggregation_unit)] <- attributes(data)$colID
aggregation_unit <- attributes(data)$colID
}
if(is.null(facets)| isTRUE(facets == aggregation_unit))
{
data <- aggregate(x = data[,var],
by = list(var = data[, aggregation_unit, drop = TRUE]), FUN = aggregation_fun)
colnames(data)[1] <- aggregation_unit
facets_join <- NULL
}else{
if(!any(facets %in% colnames(data)))
{
stop("facets name does not exit.")
}
dt <- lapply(levels(factor(data[,facets, drop = TRUE])), function(x) aggregate(x = data[data[,facets, drop = TRUE]==x, var],
by = list(var = data[data[,facets, drop = TRUE]==x,aggregation_unit, drop = TRUE],
var2 = data[data[,facets, drop = TRUE]==x,facets, drop = TRUE]),
FUN = aggregation_fun))
data <- do.call("rbind", dt)
class(data) <- c(class(data),"DE")
colnames(data)[1] <- aggregation_unit
if(any(facets %in% colnames(nm)))
{
facets <- paste(facets,"_facets", sep = "")
}
colnames(data)[2] <- facets
facets_join <- facets
}
data[,aggregation_unit] <- stri_trans_tolower(data[,aggregation_unit, drop = TRUE])
nm[,aggregation_unit] <- as.character(stri_trans_tolower(nm[,aggregation_unit, drop = TRUE]))
data[,aggregation_unit] = as.character(data[,aggregation_unit, drop = TRUE])
data <- suppressWarnings(left_join(data, nm,c(aggregation_unit)))
}else{
if(is.null(facets)| isTRUE(facets == aggregation_unit))
{
data <- aggregate(x = data[,var],
by = list(var = data[, aggregation_unit, drop = TRUE]), FUN = aggregation_fun)
colnames(data)[1] <- aggregation_unit
}else{
dt <- lapply(levels(factor(data[,facets, drop = TRUE])), function(x) aggregate(x = data[data[,facets, drop = TRUE]==x, var],
by = list(var = data[data[,facets, drop = TRUE]==x,aggregation_unit, drop = TRUE],
var2 = data[data[,facets, drop = TRUE]==x,facets, drop = TRUE]),
FUN = aggregation_fun))
data <- do.call("rbind", dt)
colnames(data)[1] <- aggregation_unit
colnames(data)[2] <- facets
}
}
colID <- aggregation_unit
}
}
if(type == "static")
{
if(typeStatic == "tmap")
{
mapping_tmap(data, var = var,
facets = facets, add_text = add_text,
options = options)
}else if(typeStatic == "choro.cart")
{
mapping_choro(data = data, var = var, options = options)
}else if(typeStatic == "typo")
{
mapping_typo(data = data, var = var, options = options)
}else if(typeStatic == "bar")
{
mapping_bar(data = data, var = var, options = options)
}
}else if(type == "interactive"){
if(!is.null(facets))
{
if(isFALSE(options$facets.free.scale))
{
plot_interactive_choro_facetes(data = data,
var = var,
colID = colID,
facets = facets,
options = options)
}else{
plot_interactive_choro_facetes_freeScale(data = data,
var = var,
colID = colID,
facets = facets,
options = options)
}
}else{
plot_interactive_choro(data = data,
var = var,
colID = colID,
options = options)
}
}
}
|
list.join <- function(x, y, xkey, ykey, ..., keep.order = TRUE) {
if (missing(xkey) && missing(ykey))
stop("At least one key should be specified")
sxkey <- substitute(xkey)
sykey <- substitute(ykey)
dfsxkey <- substitute(data.frame(xkey))
if (missing(sykey)) {
sykey <- sxkey
dfsykey <- substitute(data.frame(xkey))
} else {
dfsykey <- substitute(data.frame(ykey))
}
xkeys.list <- list.map.internal(x, dfsxkey, parent.frame())
ykeys.list <- list.map.internal(y, dfsykey, parent.frame())
xkeys.df <- list.rbind(xkeys.list)
ykeys.df <- list.rbind(ykeys.list)
if (is.name(sxkey))
colnames(xkeys.df) <- as.character(sxkey)
if (is.name(sykey))
colnames(ykeys.df) <- as.character(sykey)
if (!identical(colnames(xkeys.df), colnames(ykeys.df))) {
stop("Inconsistent keys")
}
xkeys <- cbind(.xi = seq_along(xkeys.list), xkeys.df)
ykeys <- cbind(.yi = seq_along(ykeys.list), ykeys.df)
df <- merge.data.frame(xkeys, ykeys, by = colnames(xkeys)[-1L], ...)
if (keep.order)
df <- df[order(df$.xi), ]
map(modifyList, list(x[df$.xi], y[df$.yi]))
}
|
kpPlotCoverage <- function(karyoplot, data, show.0.cov=TRUE, data.panel=1, r0=NULL, r1=NULL, col="
if(missing(karyoplot)) stop("The parameter 'karyoplot' is required")
if(!methods::is(karyoplot, "KaryoPlot")) stop("'karyoplot' must be a valid 'KaryoPlot' object")
if(missing(data)) stop("The parameter 'data' is required")
if(!methods::is(data, "GRanges") && !methods::is(data, "SimpleRleList")) {
data <- tryCatch(toGRanges(data), error=function(e) {stop("'data' must be a GRanges object or a SimpleRleList")})
}
if(!methods::is(data, "SimpleRleList")) {
data <- data[as.character(GenomeInfoDb::seqnames(data)) %in% karyoplot$chromosomes,]
GenomeInfoDb::seqlevels(data) <- karyoplot$chromosomes
data <- GenomicRanges::coverage(data, width=karyoplot$chromosome.lengths[GenomeInfoDb::seqlevels(data)])
}
coverage.gr <- toGRanges(data)
if(show.0.cov==FALSE) {
coverage.gr <- coverage.gr[coverage.gr$coverage!=0]
}
if(is.null(ymax)) ymax <- max(max(coverage.gr$coverage))
if(is.null(border)) border <- col
cov.start <- coverage.gr
end(cov.start) <- start(cov.start)
cov.end <- coverage.gr
start(cov.end) <- end(cov.end)
cov.to.plot <- sort(c(cov.start, cov.end))
kpArea(karyoplot=karyoplot, data=cov.to.plot, y=cov.to.plot$coverage,
base.y = 0, ymin=0, ymax=ymax,
r0=r0, r1=r1, data.panel=data.panel,
col=col, border=border, clipping=clipping, ...)
karyoplot$latest.plot <- list(funct="kpPlotCoverage", computed.values=list(max.coverage=max(max(coverage.gr$coverage)),
coverage=coverage.gr,
ymax=ymax))
invisible(karyoplot)
}
|
overglm <- function(formula,family,weights,data,subset,start=NULL,...){
if (missingArg(data)) data <- environment(eval(formula))
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "weights", "data", "subset"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf[[1L]] <- quote(stats::model.frame)
mf <- eval(mf, parent.frame())
mt <- attr(mf, "terms")
y <- as.matrix(model.response(mf, "any"))
temp <- strsplit(gsub(" |link|=|'|'","",tolower(family)),"[()]")[[1]]
family <- temp[1]
if(is.na(temp[2])){
if(family=="bb") link <- "logit" else link="log"
}else link <- temp[2]
yres <- y
colnames(yres) <- rep(" ",ncol(yres))
if(family=="bb"){
m <- as.matrix(y[,1]+y[,2])
y <- as.matrix(y[,1])
}
weights <- as.vector(model.weights(mf))
offset <- as.vector(model.offset(mf))
X <- model.matrix(mt, mf)
p <- ncol(X)
n <- nrow(X)
if(is.null(offset)) offs <- matrix(0,n,1) else offs <- as.matrix(offset)
if(is.null(weights)) weights <- matrix(1,n,1) else weights <- as.matrix(weights)
if(any(weights <= 0)) stop("Only positive weights are allowed!!",call.=FALSE)
if(family=="bb") familyf <- binomial(link) else familyf <- poisson(link)
if(family=="nb1"){
escore <- function(theta){
eta <- tcrossprod(X,t(theta[1:p])) + offs
mu <- familyf$linkinv(eta)
phi <- exp(theta[p+1])
u1 <- -crossprod(X,weights*(y-mu)*familyf$mu.eta(eta)/(mu + phi*mu^2))
u2 <- -sum(weights*(Digamma(1/phi)-Digamma(y+1/phi)+phi*(y-mu)/(phi*mu+1)+log(mu*phi+1))/phi)
return(rbind(u1,u2))
}
objetive <- function(theta){
mu <- familyf$linkinv(tcrossprod(X,t(theta[1:p])) + offs)
phi <- exp(theta[p+1])
-sum(weights*(Lgamma(y+1/phi)-Lgamma(1/phi)+y*log(mu*phi)-(y+1/phi)*log(mu*phi+1)))
}
theta0 <- function(fits){
mus <- fitted(fits)
fik <- lm((fit0$y - mus)^2 ~ -1 + I(mus^2) + offset(mus), weights=1/(mus + 2*mus^2))
c(coef(fits),log(abs(coef(fik))))
}
}
if(family=="nb2"){
escore <- function(theta){
eta <- tcrossprod(X,t(theta[1:p])) + offs
mu <- familyf$linkinv(eta)
phi <- exp(theta[p+1])
const <- Digamma(y+mu/phi)-Digamma(mu/phi)-log(1+phi)
u1 <- -crossprod(X,weights*familyf$mu.eta(eta)*const/phi)
u2 <- -sum(weights*(-const*mu/phi+y-phi*(y+mu/phi)/(1+phi)))
return(rbind(u1,u2))
}
objetive <- function(theta){
mu <- familyf$linkinv(tcrossprod(X,t(theta[1:p])) + offs)
phi <- exp(theta[p+1])
result <- -sum(weights*(Lgamma(y+mu/phi)-Lgamma(mu/phi)+y*log(phi)-(y+mu/phi)*log(1+phi)))
}
theta0 <- function(fits){
mus <- fitted(fits)
fik <- lm((fit0$y - mus)^2 ~ -1 + mus, weights=1/(mus + 2*mus^2))
c(coef(fits),log(abs(coef(fik)-1)))
}
}
if(family=="nb3"){
escore <- function(theta){
eta <- tcrossprod(X,t(theta[1:p])) + offs
mu <- familyf$linkinv(eta)
phi <- exp(theta[p+1])
const1 <- Digamma(1/(phi*mu))-Digamma(y+1/(phi*mu))+log(phi*mu^2+1)
const2 <- phi*y*mu-(phi*y*mu+1)*phi*mu^2/(phi*mu^2+1)
u1 <- -crossprod(X,weights*familyf$mu.eta(eta)*(const1+2*const2)/(phi*mu^2))
u2 <- -sum(weights*((const1+const2)/(phi*mu)))
return(rbind(u1,u2))
}
objetive <- function(theta){
mu <- familyf$linkinv(tcrossprod(X,t(theta[1:p])) + offs)
phi <- exp(theta[p+1])
-sum(weights*(Lgamma(y+1/(phi*mu))-Lgamma(1/(phi*mu))+y*log(mu^2*phi)-(y+1/(phi*mu))*log(mu^2*phi+1)))
}
theta0 <- function(fits){
mus <- fitted(fits)
fik <- lm((fit0$y - mus)^2 ~ -1 + I(mus^3) + offset(mus), weights=1/(mus + 2*mus^2))
c(coef(fits),log(abs(coef(fik))))
}
}
if(family=="bb"){
escore <- function(theta){
eta <- tcrossprod(X,t(theta[1:p])) + offs
mu <- familyf$linkinv(eta)
phi <- exp(theta[p+1])
const1 <- Digamma(y+mu/phi)-Digamma(mu/phi)
const2 <- Digamma((1-mu)/phi)-Digamma(m-y+(1-mu)/phi)
u1 <- -crossprod(X,as.matrix(weights*familyf$mu.eta(eta)*(const1+const2)/phi))
const3 <- -const1*mu+const2*(1-mu)-Digamma(1/phi)+Digamma(m+1/phi)
u2 <- -sum(weights*const3/phi)
return(rbind(u1,u2))
}
objetive <- function(theta){
mu <- familyf$linkinv(tcrossprod(X,t(theta[1:p])) + offs)
phi <- exp(theta[p+1])
-sum(weights*(Lgamma(1/phi)+Lgamma(y+mu/phi)+Lgamma(m-y+(1-mu)/phi)-Lgamma(m+1/phi)-Lgamma(mu/phi)-Lgamma((1-mu)/phi)))
}
theta0 <- function(fits){
mus <- fitted(fits)
l0 <- mean(abs((y - m*mus)^2/(m*mus*(1-mus)) - 1)/ifelse(m==1,1,m-1))
c(coef(fits),log(l0/(1-l0)))
}
}
if(is.null(start))
fit0 <- glm.fit(y=yres,x=X,offset=offset,weights=weights,family=familyf)
else
fit0 <- glm.fit(y=yres,x=X,offset=offset,weights=weights,family=familyf,start=start)
start <- theta0(fit0)
salida <- optim(start,fn=objetive,gr=escore,method="BFGS",control=list(reltol=1e-15))
theta_hat <- as.matrix(salida$par,nrow=length(theta_hat),1)
eta <- tcrossprod(X,t(theta_hat[1:p])) + offs
mu <- familyf$linkinv(eta)
colnames(mu) <- ""
rownames(theta_hat) <- c(colnames(X),"log(dispersion)")
colnames(theta_hat) <- ""
estfun <- -escore(theta_hat)
if(salida$convergence != 0) stop("Convergence not achieved!!",call.=FALSE)
rownames(estfun) <- c(colnames(X),"log(dispersion)")
colnames(estfun) <- ""
logLik <- switch(family,
"nb1"=-salida$value-sum(weights*lgamma(y+1)),
"nb2"=-salida$value-sum(weights*lgamma(y+1)),
"nb3"=-salida$value-sum(weights*lgamma(y+1)),
"bb"=-salida$value + sum(weights*(Lgamma(m+1)-Lgamma(y+1)-Lgamma(m-y+1))))
out_ <- list(coefficients=theta_hat,fitted.values=mu,linear.predictors=eta,
prior.weights=weights,y=yres,formula=formula,call=match.call(),offset=offs,model=mf,data=data,
df.residual=n-p-1,logLik=logLik,converged=ifelse(salida$convergence==0,TRUE,FALSE),
estfun=estfun,terms=mt,escore=escore,objetive=objetive)
class(out_) <- "overglm"
nano <- list(...)
if(is.null(nano$si.mu.la.ti.on)){
hess <- -chol(jacobian(escore,theta_hat))
colnames(hess) <- rownames(theta_hat)
rownames(hess) <- rownames(theta_hat)
out_$R <- hess
}
familyf <- list(family=family,link=link)
class(familyf) <- "family"
out_$family <- familyf
return(out_)
}
print.overglm <- function(x,...){
cat(" Family: ",switch(x$family$family,"nb1"="Negative Binomial I",
"nb2"="Negative Binomial II",
"nb3"="Negative Binomial III",
"bb"="Beta-Binomial"))
cat("\n Link: ",x$family$link)
p <- length(x$coefficients)
cat("\n********************************************************")
cat("\n -2*log-likelihood: ",round(-2*x$logLik,digits=3),"\n")
cat("degrees of freedom: ",length(x$coefficients),"\n")
cat(" AIC: ",round(-2*x$logLik + 2*(p),digits=3),"\n")
cat(" BIC: ",round(-2*x$logLik + log(nrow(x$y))*(p),digits=3),"\n")
}
confint.overglm <- function(object,parm,level=0.95,digits=4,verbose=TRUE,...){
ee <- sqrt(diag(vcov(object)))
results <- matrix(0,length(ee),2)
results[,1] <- coef(object) - qnorm(1-level/2)*ee
results[,2] <- coef(object) + qnorm(1-level/2)*ee
rownames(results) <- rownames(object$coefficients)
colnames(results) <- c("Lower limit","Upper limit")
if(verbose){
cat("\n Approximate",round(100*(1-level),digits=1),"percent confidence intervals based on the Wald test \n\n")
print(round(results,digits=digits))
}
return(invisible(results))
}
estequa.overglm <- function(model,...){
salida <- model$estfun
colnames(salida) <- " "
return(salida)
}
anova.overglm <- function(object,...,test=c("wald","lr","score","gradient"),verbose=TRUE){
test <- match.arg(test)
x <- list(object,...)
if(any(lapply(x,function(xx) class(xx)[1])!="overglm"))
stop("Only glm-type objects are supported!!",call.=FALSE)
if(length(x)==1){
terminos <- attr(object$terms,"term.labels")
x[[1]] <- update(object,paste(". ~ . -",paste(terminos,collapse="-")))
for(i in 1:length(terminos)) x[[i+1]] <- update(x[[i]],paste(". ~ . + ",terminos[i]))
}
hast <- length(x)
out_ <- matrix(0,hast-1,3)
for(i in 2:hast){
vars0 <- rownames(coef(x[[i-1]]))
vars1 <- rownames(coef(x[[i]]))
nest <- vars0 %in% vars1
ids <- is.na(match(vars1,vars0))
if(test=="wald") sc <- crossprod(coef(x[[i]])[ids],solve(vcov(x[[i]])[ids,ids]))%*%coef(x[[i]])[ids]
if(test=="lr") sc <- 2*(logLik(x[[i]])-logLik(x[[i-1]]))
if(test=="score" | test=="gradient"){
envir <- environment(x[[i]]$escore)
envir$weights <- x[[i]]$prior.weights
n <- length(x[[i]]$prior.weights)
if(is.null(x[[i]]$offset)) envir$offs <- matrix(0,n,1)
else envir$offs <- as.matrix(x[[i]]$offset)
if(ncol(x[[i]]$y)==2){
envir$m <- x[[i]]$y[,1] + x[[i]]$y[,2]
envir$y <- x[[i]]$y[,1]
}else envir$y <- x[[i]]$y
envir$X <- model.matrix(as.formula(x[[i]]$formula),x[[i]]$data)
envir$p <- ncol(envir$X)
if(x[[i]]$family$family=="bb") familyf <- binomial(x[[i]]$family$link)
else familyf <- poisson(x[[i]]$family$link)
envir$familyf <- familyf
theta0 <- coef(x[[i]])
theta0[ids] <- rep(0,sum(ids))
theta0[!ids] <- coef(x[[i-1]])
u0 <- x[[i]]$escore(theta0)[ids]
if(test=="score"){
v0 <- solve(jacobian(x[[i]]$escore,theta0))[ids,ids]
sc <- abs(crossprod(u0,v0)%*%u0)
}else sc <- abs(crossprod(u0,coef(x[[i]])[ids]))
}
df <- sum(ids)
out_[i-1,] <- cbind(sc,df,1-pchisq(sc,df))
}
colnames(out_) <- c(" Chi ", " Df", " Pr(>Chi)")
rownames(out_) <- paste(1:(hast-1),"vs",2:hast)
if(verbose){
test <- switch(test,"lr"="Likelihood-ratio test",
"wald"="Wald test",
"score"="Rao's score test",
"gradient"="Gradient test")
cat("\n ",test,"\n\n")
for(i in 1:hast) cat(paste("Model", i,": ",x[[i]]$formula[2],x[[i]]$formula[1],x[[i]]$formula[3:length(x[[i]]$formula)],collapse=""),"\n")
cat("\n")
printCoefmat(out_, P.values=TRUE, has.Pvalue=TRUE, digits=5, signif.legend=TRUE, cs.ind=2)
}
return(invisible(out_))
}
dfbeta.overglm <- function(model, coefs, identify,...){
envir <- environment(model$escore)
weights <- model$prior.weights
envir$weights <- weights
n <- length(weights)
if(is.null(model$offset)) envir$offs <- matrix(0,n,1) else envir$offs <- as.matrix(model$offset)
if(ncol(model$y)==2){
envir$m <- model$y[,1] + model$y[,2]
envir$y <- model$y[,1]
}else envir$y <- model$y
envir$X <- model.matrix(model)
envir$p <- ncol(envir$X)
if(model$family$family=="bb") familyf <- binomial(model$family$link) else familyf <- poisson(model$family$link)
envir$familyf <- familyf
dfbetas <- matrix(0,n,envir$p+1)
temp <- data.frame(y=model$y,X=envir$X,offs=envir$offs,weights=weights,ids=1:n)
d <- ncol(temp)
colnames(temp) <- c(paste("var",1:(d-1),sep=""),"ids")
orden <- eval(parse(text=paste("with(temp,order(",paste(colnames(temp)[-d],collapse=","),"))",sep="")))
temp2 <- temp[orden,]
envir$weights[temp2$ids[1]] <- 0
dfbetas[1,] <- -solve(jacobian(model$escore,model$coefficients))%*%model$escore(model$coefficients)
for(i in 2:n){
if(all(temp2[i,-d]==temp2[i-1,-d])) dfbetas[i,] <- dfbetas[i-1,]
else{envir$weights <- weights
envir$weights[temp2$ids[i]] <- 0
dfbetas[i,] <- solve(jacobian(model$escore,model$coefficients))%*%model$escore(model$coefficients)
}
}
dfbetas <- dfbetas[order(temp2$ids),]
colnames(dfbetas) <- c(colnames(envir$X),"log(dispersion)")
if(!missingArg(coefs)){
ids <- grep(coefs,colnames(dfbetas),ignore.case=TRUE)
if(length(ids) > 0){
nano <- list(...)
if(is.null(nano$labels)) labels <- 1:nrow(dfbetas) else{
labels <- nano$labels
nano$labels <-NULL
}
nano$x <- 1:nrow(dfbetas)
if(is.null(nano$xlab)) nano$xlab <- "Cluster Index (i)"
if(is.null(nano$type)) nano$type <- "h"
if(is.null(nano$ylab)) nano$ylab <- expression(hat(beta)-hat(beta)[("- i")])
oldpar <- par(no.readonly=TRUE)
on.exit(par(oldpar))
par(mfrow=c(1,length(ids)))
for(i in 1:length(ids)){
nano$y <- dfbetas[,ids[i]]
nano$main <- colnames(dfbetas)[ids[i]]
do.call("plot",nano)
if(!missingArg(identify)){
identify(nano$x,nano$y,n=max(1,floor(abs(identify))),labels=model$ids)
}
}
}
}
return(invisible(dfbetas))
}
cooks.distance.overglm <- function(model, plot.it=TRUE, coefs, identify,...){
dfbetas <- dfbeta(model)
met <- vcov(model)
met <- met[-ncol(dfbetas),-ncol(dfbetas)]
dfbetas <- dfbetas[,-ncol(dfbetas)]
subst <- NULL
if(!missingArg(coefs)){
ids <- grepl(coefs,colnames(dfbetas),ignore.case=TRUE)
if(sum(ids) > 0){
subst <- colnames(dfbetas)[ids]
dfbetas <- as.matrix(dfbetas[,ids])
met <- as.matrix(met[ids,ids])
}
}
CD <- as.matrix(apply((dfbetas%*%solve(met))*dfbetas,1,sum))
colnames(CD) <- "Cook's distance"
if(plot.it){
nano <- list(...)
if(is.null(nano$labels)) labels <- 1:nrow(dfbetas) else{
labels <- nano$labels
nano$labels <- NULL
}
nano$x <- 1:nrow(dfbetas)
nano$y <- CD
if(is.null(nano$xlab)) nano$xlab <- "Index (i)"
if(is.null(nano$type)) nano$type <- "h"
if(is.null(nano$ylab)) nano$ylab <- expression((hat(beta)-hat(beta)[{(-~~i)}])^{T}~(Var(hat(beta)))^{-1}~(hat(beta)-hat(beta)[{(-~~i)}]))
do.call("plot",nano)
if(!missingArg(identify)){
identify(nano$x,nano$y,n=max(1,floor(abs(identify))),labels=model$ids)
}
}
if(!is.null(subst)){
message("The coefficients included in the Cook's distance are:\n")
message(subst)
}
return(invisible(CD))
}
summary.overglm <- function(object,...){
cat("\nSample size: ",nrow(object$y),"\n")
cat(" Family: ",switch(object$family$family,"nb1"="Negative Binomial I",
"nb2"="Negative Binomial II",
"nb3"="Negative Binomial III",
"bb"="Beta-Binomial"))
cat("\n Link: ",object$family$link)
cat("\n *************************************************************\n")
p <- length(object$coefficients) - 1
rownamu <- rownames(object$coefficients)[1:p]
rownaphi <- "Dispersion"
delta <- max(nchar(rownamu)) - nchar(rownaphi)
falta <- paste(replicate(max(abs(delta)-1,0)," "),collapse="")
if(delta > 0) rownaphi[1] <- paste(rownaphi[1],falta,collapse="")
if(delta < 0) rownamu[1] <- paste(rownamu[1],falta,collapse="")
TAB <- cbind(Estimate <- object$coefficients[1:p],
StdErr <- sqrt(diag(chol2inv(object$R)))[1:p],
tval <- Estimate/StdErr,
p.value <- 2*pnorm(-abs(tval)))
colnames(TAB) <- c("Estimate", "Std.Error", "z-value", "Pr(>|z|)")
rownames(TAB) <- rownamu
printCoefmat(TAB, P.values=TRUE, signif.stars=FALSE, has.Pvalue=TRUE, digits=5, dig.tst=5, signif.legend=FALSE, tst.ind=c(1,2,3))
hess <- crossprod(object$R)
hess[,p+1] <- hess[,p+1]/exp(object$coefficients[p+1])
hess[p+1,] <- hess[p+1,]/exp(object$coefficients[p+1])
TAB <- cbind(Estimate <- exp(object$coefficients[p+1]),
StdErr <- sqrt(diag(solve(hess)))[p+1])
colnames(TAB) <- c("Estimate", "Std.Error")
rownames(TAB) <- rownaphi
cat("\n")
printCoefmat(TAB, digits=5, dig.tst=5, signif.legend=FALSE, tst.ind=c(1,2))
cat(" *************************************************************\n")
cat(" -2*log-likelihood: ",round(-2*object$logLik,digits=3),"\n")
cat(" AIC: ",round(-2*object$logLik + 2*(p+1),digits=3),"\n")
cat(" BIC: ",round(-2*object$logLik + log(nrow(object$y))*(p+1),digits=3),"\n")
}
coef.overglm <- function(object,...){
out_ <- object$coefficients
colnames(out_) <- ""
return(out_)
}
vcov.overglm <- function(object,...){
out_ <- chol2inv(object$R)
rownames(out_) <- rownames(object$R)
colnames(out_) <- rownames(object$R)
return(out_)
}
model.matrix.overglm <- function(object,...){
if(is.null(object$call$data)) m <- get_all_vars(eval(object$call$formula))
else m <- get_all_vars(eval(object$call$formula),eval(object$call$data))
modelframe <- model.frame(object$call,m)
X <- model.matrix(modelframe,m)
return(X)
}
logLik.overglm <- function(object,...){
out_ <- object$logLik
attr(out_,"df") <- length(object$coefficients)
class(out_) <- "logLik"
return(out_)
}
fitted.overglm <- function(object,...) return(object$fitted.values)
predict.overglm <- function(object, ...,newdata, se.fit=FALSE, type=c("link","response")){
type <- match.arg(type)
if(object$family$family=="bb") familyf <- binomial(object$family$link) else familyf <- poisson(object$family$link)
type <- match.arg(type)
if(missingArg(newdata)){
predicts <- object$linear.predictors
X <- model.matrix(object)
}
else{
newdata <- data.frame(newdata)
mf <- model.frame(delete.response(object$terms),newdata)
X <- model.matrix(delete.response(object$terms),mf)
predicts <- tcrossprod(X,t(object$coefficients[1:ncol(X)]))
offs <- model.offset(mf)
if(!is.null(offs)) predicts <- predicts + offs
}
if(type=="response") predicts <- familyf$linkinv(predicts)
if(se.fit){
se <- sqrt(apply((X%*%chol2inv(object$R)[1:ncol(X),1:ncol(X)])*X,1,sum))
if(type=="response") se <- se*abs(familyf$mu.eta(familyf$linkfun(predicts)))
predicts <- cbind(predicts,se)
colnames(predicts) <- c("fit","se.fit")
}else colnames(predicts) <- c("fit")
rownames(predicts) <- rep(" ",nrow(predicts))
return(predicts)
}
residuals.overglm <- function(object, ...,type=c("quantile","standardized","response"), plot.it=TRUE, identify){
type <- match.arg(type)
mu <- object$fitted.values
phi <- exp(object$coefficients[length(object$coefficients)])
y <- object$y
n <- length(mu)
if(object$family$family=="bb"){
m <- as.matrix(y[,1]+y[,2])
y <- as.matrix(y[,1])
res <- y/m - mu
if(type=="quantile"){
alpha <- mu/phi
lambda <- (1-mu)/phi
temp2 <- matrix(NA,length(alpha),1)
temp1 <- choose(m,y)*beta(alpha+y,m-y+lambda)
const <- beta(alpha,lambda)
for(i in 1:length(alpha)){
if(y[i]==0) temp2[i] <- 0
if(y[i]==1) temp2[i] <- beta(alpha[i],m[i]+lambda[i])
if(y[i]>=2){
ys <- 1:(y[i]-1)
temp2[i] <- beta(alpha[i],m[i]+lambda[i]) + sum(exp(cumsum(log(alpha[i]+ys-1)-log(ys) +
log(m[i]+1-ys)-log(m[i]+lambda[i]-ys))-lgamma(m[i]+alpha[i]+lambda[i]) +
lgamma(m[i]+lambda[i])+lgamma(alpha[i])))
}
}
res <- (temp2/const) + (temp1/const)*runif(n)
res <- qnorm(ifelse(ifelse(res<1e-16,1e-16,res)>1-(1e-16),1-(1e-16),res))
}
if(type=="standardized") res <- (y - m*mu)/sqrt(m*mu*(1-mu)*(1 + (m-1)*phi/(phi+1)))
}
if(object$family$family=="nb3"){
res <- y - mu
if(type=="quantile"){
res <- pnbinom(y-1,mu=mu,size=mu/phi) + dnbinom(y,mu=mu,size=1/(phi*mu))*runif(n)
res <- qnorm(ifelse(ifelse(res<1e-16,1e-16,res)>1-(1e-16),1-(1e-16),res))
}
if(type=="standardized") res <- (y-mu)/sqrt((phi+1)*mu)
}
if(object$family$family=="nb2"){
res <- y - mu
if(type=="quantile"){
res <- pnbinom(y-1,mu=mu,size=mu/phi) + dnbinom(y,mu=mu,size=mu/phi)*runif(n)
res <- qnorm(ifelse(ifelse(res<1e-16,1e-16,res)>1-(1e-16),1-(1e-16),res))
}
if(type=="standardized") res <- (y-mu)/sqrt((phi+1)*mu)
}
if(object$family$family=="nb1"){
res <- y - mu
if(type=="quantile"){
res <- pnbinom(y-1,mu=mu,size=1/phi) + dnbinom(y,mu=mu,size=1/phi)*runif(n)
res <- qnorm(ifelse(ifelse(res<1e-16,1e-16,res)>1-(1e-16),1-(1e-16),res))
}
if(type=="standardized") res <- (y-mu)/sqrt(mu + phi*mu^2)
}
if(plot.it){
nano <- list(...)
nano$x <- object$fitted.values
nano$y <- res
if(is.null(nano$ylim)) nano$ylim <- c(min(-3.5,min(res)),max(+3.5,max(res)))
if(is.null(nano$xlab)) nano$xlab <- "Fitted values"
if(is.null(nano$ylab)) nano$ylab <- paste(type," - type residuals",sep="")
if(is.null(nano$pch)) nano$pch <- 20
if(is.null(nano$labels)) labels <- 1:length(res)
else{
labels <- nano$labels
nano$labels <- NULL
}
do.call("plot",nano)
abline(h=-3,lty=3)
abline(h=+3,lty=3)
if(!missingArg(identify)) identify(object$fitted.values,res,n=max(1,floor(abs(identify))),labels=labels)
}
res <- as.matrix(res)
colnames(res) <- "Residuals"
return(invisible(res))
}
AIC.overglm <- function(object,...,k=2,verbose=TRUE){
x <- list(object,...)
if(!all(unlist(lapply(x,function(a) return(class(a)[1]=="overglm" | class(a)[1]=="glm")))))
stop("Only glm- and overglm-type objects are supported!!",call.=FALSE)
results <- matrix(NA,length(x),3)
results2 <- matrix(NA,length(x),4)
rows <- matrix(NA,length(x),1)
call. <- match.call()
for(i in 1:length(x)){
results[i,1] <- -2*sum(logLik(x[[i]]))
results[i,2] <- attr(logLik(x[[i]]),"df")
results[i,3] <- -2*sum(logLik(x[[i]])) + k*attr(logLik(x[[i]]),"df")
results2[i,1] <- as.character(call.[i+1])
results2[i,2] <- switch(x[[i]]$family$family,"nb1"="Negative Binomial I",
"nb2"="Negative Binomial II",
"nb3"="Negative Binomial III",
"bb"="Beta-Binomial",
"poisson"="Poisson",
"binomial"="Binomial",
"Gamma"="Gamma",
"gaussian"="Gaussian",
"inverse.gaussian"="Inverse Gaussian")
results2[i,3] <- x[[i]]$family$link
results2[i,4] <- paste(c(ifelse(is.null(attr(x[[i]]$terms,"offset")),attr(x[[i]]$terms,"intercept"),
paste(c(attr(x[[i]]$terms,"intercept"),as.character(attr(x[[i]]$terms,"variables"))[[attr(x[[i]]$terms,"offset")+1]]),collapse=" + ")),
attr(x[[i]]$terms,"term.labels")),collapse=" + ")
}
if(nrow(results) > 1){
if(verbose){
cat("\n")
if(all(results2[,2]==results2[1,2]))
cat("\n Family: ",results2[1,2],"\n")
if(all(results2[,3]==results2[1,3]))
cat(" Link: ",results2[1,3],"\n")
if(all(results2[,4]==results2[1,4]))
cat("Predictor: ",results2[1,4],"\n")
cat("\n")
ids <- c(TRUE,!all(results2[,2]==results2[1,2]),!all(results2[,3]==results2[1,3]),!all(results2[,4]==results2[1,4]))
temp <- as.matrix(results2[,ids])
out_ <- data.frame(temp,results)
colnames(out_) <- c(c("Object","Family","Link","Predictor")[ids],"-2*log-likelihood","df","AIC ")
print(out_,row.names=FALSE)
return(invisible(out_))
}
}else return(invisible(round(results[,3],digits=3)))
}
BIC.overglm <- function(object,...,verbose=TRUE){
x <- list(object,...)
if(!all(unlist(lapply(x,function(a) return(class(a)[1]=="overglm" | class(a)[1]=="glm")))))
stop("Only glm- and overglm-type objects are supported!!",call.=FALSE)
results <- matrix(NA,length(x),3)
results2 <- matrix(NA,length(x),4)
rows <- matrix(NA,length(x),1)
call. <- match.call()
for(i in 1:length(x)){
results[i,1] <- -2*sum(logLik(x[[i]]))
results[i,2] <- attr(logLik(x[[i]]),"df")
results[i,3] <- -2*sum(logLik(x[[i]])) + log(nrow(model.matrix(x[[i]])))*attr(logLik(x[[i]]),"df")
results2[i,1] <- as.character(call.[i+1])
results2[i,2] <- switch(x[[i]]$family$family,"nb1"="Negative Binomial I",
"nb2"="Negative Binomial II",
"nb3"="Negative Binomial III",
"bb"="Beta-Binomial",
"poisson"="Poisson",
"binomial"="Binomial",
"Gamma"="Gamma",
"gaussian"="Gaussian",
"inverse.gaussian"="Inverse Gaussian")
results2[i,3] <- x[[i]]$family$link
results2[i,4] <- paste(c(ifelse(is.null(attr(x[[i]]$terms,"offset")),attr(x[[i]]$terms,"intercept"),
paste(c(attr(x[[i]]$terms,"intercept"),as.character(attr(x[[i]]$terms,"variables"))[[attr(x[[i]]$terms,"offset")+1]]),collapse=" + ")),
attr(x[[i]]$terms,"term.labels")),collapse=" + ")
}
if(nrow(results) > 1){
if(verbose){
cat("\n")
if(all(results2[,2]==results2[1,2]))
cat("\n Family: ",results2[1,2],"\n")
if(all(results2[,3]==results2[1,3]))
cat(" Link: ",results2[1,3],"\n")
if(all(results2[,4]==results2[1,4]))
cat("Predictor: ",results2[1,4],"\n")
cat("\n")
ids <- c(TRUE,!all(results2[,2]==results2[1,2]),!all(results2[,3]==results2[1,3]),!all(results2[,4]==results2[1,4]))
temp <- as.matrix(results2[,ids])
out_ <- data.frame(temp,results)
colnames(out_) <- c(c("Object","Family","Link","Predictor")[ids],"-2*log-likelihood","df","BIC ")
print(out_,row.names=FALSE)
return(invisible(out_))
}
}else return(invisible(round(results[,3],digits=3)))
}
envelope.overglm <- function(object, rep=100, conf=0.95, type=c("quantile","response","standardized"), plot.it=TRUE, identify, ...){
type <- match.arg(type)
p <- length(coef(object))
X <- model.matrix(object)
mu <- fitted(object)
n <- length(mu)
rep <- max(1,floor(abs(rep)))
e <- matrix(0,n,rep)
bar <- txtProgressBar(min=0, max=rep, initial=0, width=min(50,rep), char="+", style=3)
i <- 1
while(i <= rep){
if(object$family$family=="bb"){
phi <- exp(coef(object)[p])
size <- apply(object$y,1,sum)
prob <- rbeta(n,shape1=mu*((phi+1)/phi-1),shape2=(1-mu)*((phi+1)/phi-1))
resp <- rbinom(n,size=size,prob=prob)
resp <- cbind(resp,size-resp)
}else{
lambda <- switch(object$family$family,
nb1 = rgamma(n,scale=mu*exp(coef(object)[p]),shape=1/exp(coef(object)[p])),
nb2 = rgamma(n,scale=exp(coef(object)[p]),shape=mu/exp(coef(object)[p])),
nb3 = rgamma(n,scale=mu^2*exp(coef(object)[p]),shape=1/(mu*exp(coef(object)[p]))))
resp <- rpois(n,lambda=lambda)
}
fits <- try(overglm(resp ~ 0 + X + offset(object$offset),weights=object$weights,family=object$family$family,start=c(coef(object)[-p]),si.mu.la.ti.on=TRUE),silent=TRUE)
rs <- try(residuals(fits,type=type,plot.it=FALSE),silent=TRUE)
if(is.list(fits)){
if(fits$converged==TRUE){
e[,i] <- sort(rs)
setTxtProgressBar(bar,i)
i <- i + 1
}
}
}
close(bar)
alpha <- 1 - max(min(abs(conf),1),0)
e <- as.matrix(e[,1:(i-1)])
es <- apply(e,1,function(x) return(quantile(x,probs=c(alpha/2,0.5,1-alpha/2))))
rd <- residuals(object,type=type,plot.it=FALSE)
if(plot.it){
rango <- 1.1*range(rd)
oldpar <- par(no.readonly=TRUE)
on.exit(par(oldpar))
par(pty="s")
qqnorm(es[2,],axes=FALSE,xlab="",ylab="",main="", type="l",ylim=rango,lty=3)
par(new=TRUE)
qqnorm(es[1,],axes=FALSE,xlab="",ylab="",main="", type="l",ylim=rango,lty=1)
par(new=TRUE)
qqnorm(es[3,],axes=FALSE,xlab="",ylab="", main="", type="l",ylim=rango,lty=1)
par(new=TRUE)
nano <- list(...)
nano$y <- rd
nano$type <- "p"
nano$ylim <- rango
if(is.null(nano$labels)) labels <- 1:nrow(X)
else labels <- nano$labels
if(is.null(nano$pch)) nano$pch <- 20
if(is.null(nano$col)) nano$col <- "black"
if(is.null(nano$xlab)) nano$xlab <- "Expected quantiles"
if(is.null(nano$ylab)) nano$ylab <- "Observed quantiles"
if(is.null(nano$main)) nano$main <- paste0("Normal QQ plot with simulated envelope\n of ",type,"-type residuals")
if(is.null(nano$labels)) labels <- 1:length(rd)
else{
labels <- nano$labels
nano$labels <- NULL
}
outm <- do.call("qqnorm",nano)
if(!missingArg(identify)){
identify(outm$x,outm$y,labels=labels,n=max(1,floor(abs(identify))),labels=labels)
}
}
out_ <- cbind(t(es),rd)
colnames(out_) <- c("Lower limit","Median","Upper limit","Residuals")
return(invisible(out_))
}
stepCriterion.overglm <- function(model, criterion=c("bic","aic","p-value"), test=c("wald","score","lr","gradient"), direction=c("forward","backward"), levels=c(0.05,0.05), trace=TRUE, scope, ...){
xxx <- list(...)
if(is.null(xxx$k)) k <- 2 else k <- xxx$k
criterion <- match.arg(criterion)
direction <- match.arg(direction)
test <- match.arg(test)
if(test=="wald") test2 <- "Wald test"
if(test=="score") test2 <- "Rao's score test"
if(test=="lr") test2 <- "likelihood-ratio test"
if(test=="gradient") test2 <- "Gradient test"
criters <- c("aic","bic","adjr2","p-value")
criters2 <- c("AIC","BIC","adj.R-squared","P(Chisq>)(*)")
sentido <- c(1,1,-1,1)
if(missingArg(scope)){
upper <- formula(eval(model$call$formula))
lower <- formula(eval(model$call$formula))
lower <- formula(paste(deparse(lower[[2]]),"~",attr(terms(lower),"intercept")))
}else{
lower <- scope$lower
upper <- scope$upper
}
U <- attr(terms(upper),"term.labels")
fs <- attr(terms(upper),"factors")
long <- max(nchar(U)) + 2
nonename <- paste("<none>",paste(replicate(max(long-6,0)," "),collapse=""),collapse="")
cambio <- ""
paso <- 1
tol <- TRUE
if(trace){
cat("\n Family: ",model$family$family,"\n")
cat("Link function: ",model$family$link,"\n")
}
if(direction=="forward"){
oldformula <- lower
if(trace){
cat("\nInitial model:\n")
cat(paste("~",as.character(oldformula)[length(oldformula)],sep=" "),"\n\n")
cat("\nStep",0,":\n")
}
out_ <- list(initial=paste("~",as.character(oldformula)[length(oldformula)],sep=" "),direction=direction,criterion=criters2[criters==criterion])
while(tol){
oldformula <- update(oldformula,paste(as.character(eval(model$call$formula))[2],"~ ."))
fit.x <- update(model,formula=oldformula,start=NULL)
S <- attr(terms(oldformula),"term.labels")
entran <- seq(1:length(U))[is.na(match(U,S))]
salen <- seq(1:length(U))[!is.na(match(U,S))]
mas <- TRUE
fsalen <- matrix(NA,length(salen),5)
if(length(salen) > 0){
nombres <- matrix("",length(salen),1)
for(i in 1:length(salen)){
salida <- apply(as.matrix(fs[,salen[i]]*fs[,-c(entran,salen[i])]),2,sum)
if(all(salida < sum(fs[,salen[i]])) & U[salen[i]]!=cambio){
newformula <- update(oldformula, paste("~ . -",U[salen[i]]))
fit.0 <- update(model,formula=newformula,start=NULL)
fsalen[i,1] <- fit.0$df.residual - fit.x$df.residual
fsalen[i,5] <- anova(fit.0,fit.x,test=test,verbose=FALSE)[1,1]
fsalen[i,5] <- sqrt(9*fsalen[i,1]/2)*((fsalen[i,5]/fsalen[i,1])^(1/3) - 1 + 2/(9*fsalen[i,1]))
fsalen[i,2] <- AIC(fit.0,k=k)
fsalen[i,3] <- BIC(fit.0)
fsalen[i,4] <- 0
nombres[i] <- U[salen[i]]
}
}
rownames(fsalen) <- paste("-",nombres)
if(criterion=="p-value" & any(!is.na(fsalen))){
colnames(fsalen) <- c("df",criters2)
if(nrow(fsalen) > 1){
fsalen <- fsalen[order(fsalen[,5]),]
fsalen <- na.omit(fsalen)
attr(fsalen,"na.action") <- attr(fsalen,"class") <- NULL
}
fsalen[,5] <- 1-pchisq((sqrt(2/(9*fsalen[,1]))*fsalen[,5] + 1 - 2/(9*fsalen[,1]))^3*fsalen[,1],fsalen[,1])
if(fsalen[1,5] > levels[2]){
fsalen <- rbind(fsalen,c(NA,AIC(fit.x,k=k),BIC(fit.x),NA,NA))
rownames(fsalen)[nrow(fsalen)] <- nonename
fsalen <- fsalen[,-4]
if(trace){
printCoefmat(fsalen,P.values=TRUE,has.Pvalue=TRUE,na.print="",cs.ind=2:(ncol(fsalen)-2),
signif.stars=FALSE,tst.ind=ncol(fsalen)-1,dig.tst=4,digits=5)
cat("\nStep",paso,":",rownames(fsalen)[1],"\n\n")
}
mas <- FALSE
oldformula <- update(oldformula, paste("~ .",rownames(fsalen)[1]))
paso <- paso + 1
cambio <- substring(rownames(fsalen)[1],3)
}
}
}
if(length(entran) > 0 & mas){
fentran <- matrix(NA,length(entran),5)
nombres <- matrix("",length(entran),1)
for(i in 1:length(entran)){
salida <- apply(as.matrix(fs[,-c(salen,entran[i])]),2,function(x) sum(fs[,entran[i]]*x)!=sum(x))
if(all(salida) & U[entran[i]]!=cambio){
newformula <- update(oldformula, paste("~ . +",U[entran[i]]))
fit.0 <- update(model,formula=newformula,adjr2=FALSE,start=NULL)
fentran[i,1] <- fit.x$df.residual - fit.0$df.residual
fentran[i,5] <- anova(fit.x,fit.0,test=test,verbose=FALSE)[1,1]
fentran[i,5] <- sqrt(9*fentran[i,1]/2)*((fentran[i,5]/fentran[i,1])^(1/3) - 1 + 2/(9*fentran[i,1]))
fentran[i,2] <- AIC(fit.0,k=k)
fentran[i,3] <- BIC(fit.0)
fentran[i,4] <- 0
nombres[i] <- U[entran[i]]
}
}
rownames(fentran) <- paste("+",nombres)
if(criterion=="p-value"){
colnames(fentran) <- c("df",criters2)
if(nrow(fentran) > 1){
fentran <- fentran[order(-fentran[,5]),]
fentran <- na.omit(fentran)
attr(fentran,"na.action") <- attr(fentran,"class") <- NULL
}
fentran[,5] <- 1-pchisq((sqrt(2/(9*fentran[,1]))*fentran[,5] + 1 - 2/(9*fentran[,1]))^3*fentran[,1],fentran[,1])
fentran <- rbind(fentran,c(NA,AIC(fit.x,k=k),BIC(fit.x),NA,NA))
rownames(fentran)[nrow(fentran)] <- nonename
fentran <- fentran[,-4]
if(trace) printCoefmat(fentran,P.values=TRUE,has.Pvalue=TRUE,na.print="",cs.ind=2:(ncol(fentran)-2),
signif.stars=FALSE,tst.ind=ncol(fentran)-1,dig.tst=4,digits=5)
if(fentran[1,ncol(fentran)] < levels[1]){
if(trace) cat("\nStep",paso,":",rownames(fentran)[1],"\n\n")
paso <- paso + 1
cambio <- substring(rownames(fentran)[1],3)
oldformula <- update(oldformula, paste("~ .",rownames(fentran)[1]))
}else tol <- FALSE
}
}
if(length(entran) > 0 & criterion!="p-value"){
if(any(!is.na(fsalen))) fentran <- rbind(fentran,fsalen)
fentran[,5] <- 1-pchisq((sqrt(2/(9*fentran[,1]))*fentran[,5] + 1 - 2/(9*fentran[,1]))^3*fentran[,1],fentran[,1])
fentran <- rbind(fentran,c(0,AIC(fit.x,k=k),BIC(fit.x),0,0))
rownames(fentran)[nrow(fentran)] <- nonename
ids <- criters == criterion
colnames(fentran) <- c("df",criters2)
fentran <- na.omit(fentran)
attr(fentran,"na.action") <- attr(fentran,"class") <- NULL
fentran[nrow(fentran),c(1,5)] <- NA
fentran <- fentran[order(sentido[ids]*fentran[,c(FALSE,ids)]),]
if(rownames(fentran)[1]!=nonename){
fentran <- fentran[,-4]
if(trace){
printCoefmat(fentran,P.values=TRUE,has.Pvalue=TRUE,na.print="",cs.ind=2:(ncol(fentran)-2),
signif.stars=FALSE,tst.ind=ncol(fentran)-1,dig.tst=4,digits=5)
cat("\nStep",paso,":",rownames(fentran)[1],"\n\n")
}
paso <- paso + 1
cambio <- substring(rownames(fentran)[1],3)
oldformula <- update(oldformula, paste("~ .",rownames(fentran)[1]))
}else{
tol <- FALSE
fentran <- fentran[,-4]
if(trace) printCoefmat(fentran,P.values=TRUE,has.Pvalue=TRUE,na.print="",cs.ind=2:(ncol(fentran)-2),
signif.stars=FALSE,tst.ind=ncol(fentran)-1,dig.tst=4,digits=5)
}
}
if(length(entran) == 0 & mas) tol <- FALSE
}
}
if(direction=="backward"){
oldformula <- upper
if(trace){
cat("\nInitial model:\n")
cat(paste("~",as.character(oldformula)[length(oldformula)],sep=" "),"\n\n")
cat("\nStep",0,":\n")
}
out_ <- list(initial=paste("~",as.character(oldformula)[length(oldformula)],sep=" "),direction=direction,criterion=criters2[criters==criterion])
while(tol){
oldformula <- update(oldformula,paste(as.character(eval(model$call$formula))[2],"~ ."))
fit.x <- update(model,formula=oldformula,start=NULL)
S <- attr(terms(oldformula),"term.labels")
entran <- seq(1:length(U))[is.na(match(U,S))]
salen <- seq(1:length(U))[!is.na(match(U,S))]
menos <- TRUE
fentran <- matrix(NA,length(entran),5)
if(length(entran) > 0){
nombres <- matrix("",length(entran),1)
for(i in 1:length(entran)){
salida <- apply(as.matrix(fs[,-c(salen,entran[i])]),2,function(x) sum(fs[,entran[i]]*x)!=sum(x))
if(all(salida) & U[entran[i]]!=cambio){
newformula <- update(oldformula, paste("~ . +",U[entran[i]]))
fit.0 <- update(model,formula=newformula,adjr2=FALSE,start=NULL)
fentran[i,1] <- fit.x$df.residual - fit.0$df.residual
fentran[i,5] <- anova(fit.x,fit.0,test=test,verbose=FALSE)[1,1]
fentran[i,5] <- sqrt(9*fentran[i,1]/2)*((fentran[i,5]/fentran[i,1])^(1/3) - 1 + 2/(9*fentran[i,1]))
fentran[i,2] <- AIC(fit.0,k=k)
fentran[i,3] <- BIC(fit.0)
fentran[i,4] <- 0
nombres[i] <- U[entran[i]]
}
}
rownames(fentran) <- paste("+",nombres)
if(criterion=="p-value" & any(!is.na(fentran))){
colnames(fentran) <- c("df",criters2)
if(nrow(fentran) > 1){
fentran <- fentran[order(-fentran[,5]),]
fentran <- na.omit(fentran)
attr(fentran,"na.action") <- attr(fentran,"class") <- NULL
}
fentran[,5] <- 1-pchisq((sqrt(2/(9*fentran[,1]))*fentran[,5] + 1 - 2/(9*fentran[,1]))^3*fentran[,1],fentran[,1])
if(fentran[1,5] < levels[1]){
fentran <- rbind(fentran,c(NA,AIC(fit.x,k=k),BIC(fit.x),NA,NA))
rownames(fentran)[nrow(fentran)] <- nonename
fentran <- fentran[,-4]
if(trace){
printCoefmat(fentran,P.values=TRUE,has.Pvalue=TRUE,na.print="",cs.ind=2:(ncol(fentran)-2),
signif.stars=FALSE,tst.ind=ncol(fentran)-1,dig.tst=4,digits=5)
cat("\nStep",paso,":",rownames(fentran)[1],"\n\n")
}
menos <- FALSE
oldformula <- update(oldformula, paste("~ .",rownames(fentran)[1]))
paso <- paso + 1
cambio <- substring(rownames(fentran)[1],3)
}
}
}
if(length(salen) > 0 & menos){
fsalen <- matrix(NA,length(salen),5)
nombres <- matrix("",length(salen),1)
for(i in 1:length(salen)){
salida <- apply(as.matrix(fs[,salen[i]]*fs[,-c(entran,salen[i])]),2,sum)
if(all(salida < sum(fs[,salen[i]]))){
newformula <- update(oldformula, paste("~ . -",U[salen[i]]))
fit.0 <- update(model,formula=newformula,start=NULL)
fsalen[i,1] <- fit.0$df.residual - fit.x$df.residual
fsalen[i,5] <- anova(fit.0,fit.x,test=test,verbose=FALSE)[1,1]
fsalen[i,5] <- sqrt(9*fsalen[i,1]/2)*((fsalen[i,5]/fsalen[i,1])^(1/3) - 1 + 2/(9*fsalen[i,1]))
fsalen[i,2] <- AIC(fit.0,k=k)
fsalen[i,3] <- BIC(fit.0)
fsalen[i,4] <- 0
nombres[i] <- U[salen[i]]
}
}
rownames(fsalen) <- paste("-",nombres)
if(criterion=="p-value"){
colnames(fsalen) <- c("df",criters2)
if(nrow(fsalen) > 1){
fsalen <- fsalen[order(fsalen[,5]),]
fsalen <- na.omit(fsalen)
attr(fsalen,"na.action") <- attr(fsalen,"class") <- NULL
}
fsalen[,5] <- 1-pchisq((sqrt(2/(9*fsalen[,1]))*fsalen[,5] + 1 - 2/(9*fsalen[,1]))^3*fsalen[,1],fsalen[,1])
fsalen <- rbind(fsalen,c(NA,AIC(fit.x,k=k),BIC(fit.x),NA,NA))
rownames(fsalen)[nrow(fsalen)] <- nonename
fsalen <- fsalen[,-4]
if(trace) printCoefmat(fsalen,P.values=TRUE,has.Pvalue=TRUE,na.print="",cs.ind=2:(ncol(fsalen)-2),
signif.stars=FALSE,tst.ind=ncol(fsalen)-1,dig.tst=4,digits=5)
if(fsalen[1,ncol(fsalen)] > levels[2]){
if(trace) cat("\nStep",paso,":",rownames(fsalen)[1],"\n\n")
paso <- paso + 1
cambio <- substring(rownames(fsalen)[1],3)
oldformula <- update(oldformula, paste("~ .",rownames(fsalen)[1]))
}else tol <- FALSE
}
}
if(criterion!="p-value"){
if(any(!is.na(fentran))) fsalen <- rbind(fsalen,fentran)
fsalen[,5] <- 1-pchisq((sqrt(2/(9*fsalen[,1]))*fsalen[,5] + 1 - 2/(9*fsalen[,1]))^3*fsalen[,1],fsalen[,1])
fsalen <- rbind(fsalen,c(0,AIC(fit.x,k=k),BIC(fit.x),0,0))
rownames(fsalen)[nrow(fsalen)] <- nonename
ids <- criters == criterion
colnames(fsalen) <- c("df",criters2)
fsalen <- na.omit(fsalen)
attr(fsalen,"na.action") <- attr(fsalen,"class") <- NULL
fsalen[nrow(fsalen),c(1,5)] <- NA
fsalen <- fsalen[order(sentido[ids]*fsalen[,c(FALSE,ids)]),]
if(rownames(fsalen)[1]!=nonename){
fsalen <- fsalen[,-4]
if(trace){
printCoefmat(fsalen,P.values=TRUE,has.Pvalue=TRUE,na.print="",cs.ind=2:(ncol(fsalen)-2),
signif.stars=FALSE,tst.ind=ncol(fsalen)-1,dig.tst=4,digits=5)
cat("\nStep",paso,":",rownames(fsalen)[1],"\n\n")
}
paso <- paso + 1
cambio <- substring(rownames(fsalen)[1],3)
oldformula <- update(oldformula, paste("~ .",rownames(fsalen)[1]))
}else{
tol <- FALSE
fsalen <- fsalen[,-4]
if(trace) printCoefmat(fsalen,P.values=TRUE,has.Pvalue=TRUE,na.print="",cs.ind=2:(ncol(fsalen)-2),
signif.stars=FALSE,tst.ind=ncol(fsalen)-1,dig.tst=4,digits=5)
}
}
if(length(salen) == 0 & menos) tol <- FALSE
}
}
if(trace){
cat("\n\nFinal model:\n")
cat(paste("~",as.character(oldformula)[length(oldformula)],sep=" "),"\n\n")
cat("****************************************************************************")
cat("\n(*) p-values of the",test2)
if(criterion=="p-value"){
cat("\n Effects are included when their p-values are lower than",levels[1])
cat("\n Effects are dropped when their p-values are higher than",levels[2])
}
if(!is.null(xxx$k)) cat("The magnitude of the penalty in the AIC was set to be ",xxx$k)
cat("\n")
}
out_$final <- paste("~",as.character(oldformula)[length(oldformula)],sep=" ")
return(invisible(out_))
}
|
testthat::context("test-reconstruct_pattern_cluster")
pattern_recon <- reconstruct_pattern_cluster(pattern = species_b, n_random = 3,
max_runs = 1, verbose = FALSE)
pattern_recon_ni <- reconstruct_pattern_cluster(pattern = species_b, n_random = 2,
max_runs = 1, return_input = FALSE,
verbose = FALSE)
pattern_recon_comp_fast <- reconstruct_pattern_cluster(pattern = species_b,
n_random = 1, max_runs = 1,
comp_fast = 0, verbose = FALSE)
pattern_recon_energy <- reconstruct_pattern_cluster(pattern = species_b,
e_threshold = 0.1, n_random = 3,
verbose = FALSE)
pattern_recon_simple <- reconstruct_pattern_cluster(pattern = species_b,
n_random = 1, max_runs = 1,
return_input = FALSE, simplify = TRUE,
verbose = FALSE)
testthat::test_that("Output is a long as n_random for reconstruct_pattern_cluster", {
testthat::expect_is(pattern_recon, class = "rd_pat")
testthat::expect_type(pattern_recon$randomized, type = "list")
testthat::expect_length(pattern_recon$randomized, n = 3)
})
testthat::test_that("Output includes randomizations and original pattern for reconstruct_pattern_cluster", {
testthat::expect_named(pattern_recon$randomized,
expected = paste0("randomized_", c(1:3)))
testthat::expect_equal(pattern_recon$observed,
expected = spatstat.geom::unmark(species_b))
})
testthat::test_that("Reconstructed patterns have same number of points", {
testthat::expect_true(all(vapply(pattern_recon$randomized,
FUN.VALUE = logical(1),
function(x) x$n == species_b$n)))
})
testthat::test_that("Input pattern can not be returned for reconstruct_pattern_cluster", {
testthat::expect_equal(object = pattern_recon_ni$observed,
expected = "NA")
})
testthat::test_that("Argument comp_fast = TRUE is working", {
testthat::expect_is(pattern_recon_comp_fast, "rd_pat")
})
testthat::test_that("Reconstruction stops if e_threshold is reached", {
energy <- calculate_energy(pattern_recon_energy, verbose = FALSE)
testthat::expect_true(object = all(energy < 0.1))
})
testthat::test_that("simplify works for reconstruct_pattern_cluster", {
testthat::expect_is(pattern_recon_simple, "ppp")
})
testthat::test_that("reconstruct_pattern_cluster returns error if n_random < 1", {
testthat::expect_error(reconstruct_pattern_cluster(pattern = species_b,
n_random = -5, verbose = FALSE),
regexp = "n_random must be >= 1.",
fixed = TRUE)
})
testthat::test_that("reconstruct_pattern_cluster returns error if weights are wrong ", {
testthat::expect_error(reconstruct_pattern_cluster(pattern = species_b,
weights = c(0, 0), verbose = FALSE),
regexp = "The sum of 'weights' must be 0 < sum(weights) <= 1.",
fixed = TRUE)
testthat::expect_error(reconstruct_pattern_cluster(pattern = species_b,
weights = c(1, 1), verbose = FALSE),
regexp = "The sum of 'weights' must be 0 < sum(weights) <= 1.",
fixed = TRUE)
})
testthat::test_that("reconstruct_pattern_cluster returns warnings", {
testthat::expect_warning(reconstruct_pattern_cluster(pattern = species_b,
n_random = 2, max_runs = 1,
return_input = FALSE, simplify = TRUE),
regexp = "'simplify = TRUE' not possible for 'n_random > 1'.",
fixed = TRUE)
testthat::expect_warning(reconstruct_pattern_cluster(pattern = species_b,
n_random = 1, max_runs = 1,
simplify = TRUE),
regexp = "'simplify = TRUE' not possible for 'return_input = TRUE'.",
fixed = TRUE)
})
|
isolate({
visFun <- renderPrint({ "foo" })
visFun()
invisFun <- renderPrint({ invisible("foo") })
invisFun()
multiprintFun <- renderPrint({
print("foo");
"bar"
})
multiprintFun()
nullFun <- renderPrint({ NULL })
nullFun()
invisNullFun <- renderPrint({ invisible(NULL) })
invisNullFun()
vecFun <- renderPrint({ 1:5 })
vecFun()
visFun <- renderText({ "foo" })
visFun()
invisFun <- renderText({ invisible("foo") })
invisFun()
multiprintFun <- renderText({
print("foo");
"bar"
})
multiprintFun()
nullFun <- renderText({ NULL })
nullFun()
invisNullFun <- renderText({ invisible(NULL) })
invisNullFun()
vecFun <- renderText({ 1:5 })
vecFun()
})
|
makeNamespace <- function(name, version = NULL, lib = NULL) {
impenv <- new.env(parent = .BaseNamespaceEnv, hash = TRUE)
attr(impenv, "name") <- paste("imports", name, sep=":")
env <- new.env(parent = impenv, hash = TRUE)
name <- as.character(as.name(name))
version <- as.character(version)
info <- new.env(hash = TRUE, parent = baseenv())
assign(".__NAMESPACE__.", info, envir = env)
assign("spec", c(name = name,version = version), envir = info)
setNamespaceInfo(env, "exports", new.env(hash = TRUE, parent = baseenv()))
dimpenv <- new.env(parent = baseenv(), hash = TRUE)
attr(dimpenv, "name") <- paste("lazydata", name, sep=":")
setNamespaceInfo(env, "lazydata", dimpenv)
setNamespaceInfo(env, "imports", list("base" = TRUE))
setNamespaceInfo(env, "path",
normalizePath(file.path(lib, name), "/", TRUE))
setNamespaceInfo(env, "dynlibs", NULL)
setNamespaceInfo(env, "S3methods", matrix(NA_character_, 0L, 3L))
assign(".__S3MethodsTable__.",
new.env(hash = TRUE, parent = baseenv()),
envir = env)
registerNamespace(name, env)
env
}
|
.crit_cataXj=function(Xj, index, Stot){
n=nrow(Xj[[1]])
nblo=length(Xj)
nvar=ncol(Xj[[1]])
S=Stot[index, index]
if (length(index)>1)
{
ressvd=svd(S)
u=ressvd$u[,1]
u=u*sign(u[1])
lambda=ressvd$d[1]
}else{
u=1
lambda=1
}
C=matrix(0,n,nvar)
for (j in 1:nblo) { C=C+(u[j]*Xj[[j]]) }
Q=nblo-lambda
return(list(S=S,C=C,alpha=u,lambda=lambda,Q=Q))
}
|
gibbs_mult_fpca = function(formula, Kt=5, Kp = 2, data=NULL, verbose = TRUE, N.iter = 5000, N.burn = 1000,
sig2.me = .01, alpha = .1, SEED = NULL){
call <- match.call()
tf <- terms.formula(formula, specials = "re")
trmstrings <- attr(tf, "term.labels")
specials <- attr(tf, "specials")
where.re <-specials$re - 1
if (length(where.re) != 0) {
mf_fixed <- model.frame(tf[-where.re], data = data)
formula = tf[-where.re]
responsename <- attr(tf, "variables")[2][[1]]
REs = list(NA, NA)
REs[[1]] = names(eval(parse(text=attr(tf[where.re], "term.labels")), envir=data)$data)
REs[[2]]=paste0("(1|",REs[[1]],")")
formula2 <- paste(responsename, "~", REs[[1]], sep = "")
newfrml <- paste(responsename, "~", REs[[2]], sep = "")
newtrmstrings <- attr(tf[-where.re], "term.labels")
formula2 <- formula(paste(c(formula2, newtrmstrings),
collapse = "+"))
newfrml <- formula(paste(c(newfrml, newtrmstrings), collapse = "+"))
mf <- model.frame(formula2, data = data)
if (length(data) == 0) {
Z = lme4::mkReTrms(lme4::findbars(newfrml), fr = mf)$Zt
}
else {
Z = lme4::mkReTrms(lme4::findbars(newfrml), fr = data)$Zt
}
}
else {
mf_fixed <- model.frame(tf, data = data)
}
mt_fixed <- attr(mf_fixed, "terms")
Y <- model.response(mf_fixed, "numeric")
X <- model.matrix(mt_fixed, mf_fixed, contrasts)
if(!is.null(SEED)) { set.seed(SEED) }
W.des = X
Z.des = t(as.matrix(Z))
I = dim(Z.des)[2]
D = dim(Y)[2]
Ji = as.numeric(apply(Z.des, 2, sum))
IJ = sum(Ji)
SUBJ = factor(apply(Z.des %*% 1:dim(Z.des)[2], 1, sum))
firstobs = rep(NA, length(unique(SUBJ)))
for(i in 1:length(unique(SUBJ))){
firstobs[i] = which(SUBJ %in% unique(SUBJ)[i])[1]
}
Wi = W.des[firstobs,]
Theta = bs(1:D, df = Kt, intercept=TRUE, degree=3)
diff0 = diag(1, D, D)
diff2 = matrix(rep(c(1,-2,1, rep(0, D-2)), D-2)[1:((D-2)*D)], D-2, D, byrow = TRUE)
P0 = t(Theta) %*% t(diff0) %*% diff0 %*% Theta
P2 = t(Theta) %*% t(diff2) %*% diff2 %*% Theta
P.mat = alpha * P0 + (1-alpha) * P2
A = .01
B = .01
p = dim(W.des)[2]
BW = array(NA, c(Kt, p, N.iter))
BW[,,1] = matrix(0, Kt, p)
bw = BW[,,1]
BZ = array(NA, c(Kt, I, N.iter))
BZ[,,1] = matrix(0, Kt, I)
bz = BZ[,,1]
Bpsi = array(NA, c(Kt, Kp, N.iter))
Bpsi[,,1] = matrix(0, Kt, Kp)
bpsi = Bpsi[,,1]
C = array(NA, c(IJ, Kp, N.iter))
C[,,1] = matrix(rnorm(IJ*Kp, 0, .01), IJ, Kp)
c.mat = C[,,1]
SIGMA = rep(NA, N.iter)
SIGMA[1] = sig2.me
sig2.me = SIGMA[1]
LAMBDA.BW = matrix(NA, nrow = N.iter, ncol = p)
LAMBDA.BW[1,] = rep(1, p)
lambda.bw = LAMBDA.BW[1,]
LAMBDA.BZ = rep(NA, N.iter)
LAMBDA.BZ[1] = 1
lambda.ranef = LAMBDA.BZ[1]
LAMBDA.PSI = matrix(NA, nrow = N.iter, ncol = Kp)
LAMBDA.PSI[1,] = rep(1,Kp)
lambda.psi = LAMBDA.PSI[1,]
Y.vec = as.vector(t(Y))
t.designmat.W = t(kronecker(W.des, Theta))
sig.W = kronecker(t(W.des) %*% W.des, t(Theta)%*% Theta)
beta.cur = t(bw) %*% t(Theta)
fixef.cur = W.des %*% beta.cur
ranef.cur = Z.des %*% t(bz) %*% t(Theta)
psi.cur = t(bpsi) %*% t(Theta)
pcaef.cur = c.mat %*% psi.cur
if(verbose) { cat("Beginning Sampler \n") }
for(i in 1:N.iter){
mean.cur = as.vector(t(ranef.cur + pcaef.cur))
sigma = solve( (1/sig2.me) * sig.W + kronecker(diag(1/lambda.bw), P.mat) )
mu = (1/sig2.me) * sigma %*% (t.designmat.W %*% (Y.vec - mean.cur))
bw = matrix(mvrnorm(1, mu = mu, Sigma = sigma), nrow = Kt, ncol = p)
beta.cur = t(bw) %*% t(Theta)
fixef.cur = W.des %*% beta.cur
for(subj in 1:length(unique(SUBJ))){
t.designmat.Z = t(kronecker(Theta, rep(1, Ji[subj])))
sig.Z = kronecker(Ji[subj], t(Theta)%*% Theta)
mean.cur = as.vector((fixef.cur[which(SUBJ == unique(SUBJ)[subj]), ] +
pcaef.cur[which(SUBJ == unique(SUBJ)[subj]), ]))
sigma = solve( (1/sig2.me) * sig.Z + (1/lambda.ranef) * P.mat )
mu = (1/sig2.me) * sigma %*% (t.designmat.Z %*% (as.vector(Y[which(SUBJ == unique(SUBJ)[subj]),]) - mean.cur))
bz[,subj] = mvrnorm(1, mu = mu, Sigma = sigma)
}
ranef.cur = Z.des %*% t(bz) %*% t(Theta)
mean.cur = as.vector(t(fixef.cur + ranef.cur))
sigma = solve( (1/sig2.me) * kronecker(t(c.mat) %*% c.mat, t(Theta)%*% Theta) + kronecker(diag(1/lambda.psi), P.mat ))
mu = (1/sig2.me) * sigma %*% t(kronecker(c.mat, Theta)) %*% (Y.vec - mean.cur)
bpsi = matrix(mvrnorm(1, mu = mu, Sigma = sigma), nrow = Kt, ncol = Kp)
psi.cur = t(bpsi) %*% t(Theta)
ppT = psi.cur %*% t(psi.cur)
for(subj.vis in 1:(IJ)){
sigma = solve( (1/sig2.me)* ppT + diag(1, Kp, Kp) )
mu = (1/sig2.me) * sigma %*% psi.cur %*% (Y[subj.vis,] - fixef.cur[subj.vis,] - ranef.cur[subj.vis,] )
c.mat[subj.vis,] = mvrnorm(1, mu = mu, Sigma = sigma)
}
pcaef.cur = c.mat %*% psi.cur
Y.cur = fixef.cur + ranef.cur + pcaef.cur
a.post = A + IJ*D/2
b.post = B + 1/2*crossprod(as.vector(Y - Y.cur))
sig2.me = 1/rgamma(1, a.post, b.post)
for(term in 1:p){
a.post = A + Kt/2
b.post = B + 1/2*bw[,term] %*% P.mat %*% bw[,term]
lambda.bw[term] = 1/rgamma(1, a.post, b.post)
}
a.post = A + I*Kt/2
b.post = B + 1/2*sum(diag(t(bz) %*% P.mat %*% bz))
lambda.ranef = 1/rgamma(1, a.post, b.post)
for(K in 1:Kp){
a.post = A + Kt/2
b.post = B + 1/2*bpsi[,K] %*% P.mat %*% bpsi[,K]
lambda.psi[K] = 1/rgamma(1, a.post, b.post)
}
BW[,,i] = as.matrix(bw)
BZ[,,i] = as.matrix(bz)
Bpsi[,,i] = as.matrix(bpsi)
C[,,i] = as.matrix(c.mat)
SIGMA[i] = sig2.me
LAMBDA.BW[i,] = lambda.bw
LAMBDA.BZ[i] = lambda.ranef
LAMBDA.PSI[i,] = lambda.psi
if(verbose) { if(round(i %% (N.iter/10)) == 0) {cat(".")} }
}
beta.pm = beta.LB = beta.UB = matrix(NA, nrow = p, ncol = D)
for(i in 1:p){
beta.post = matrix(NA, nrow = (N.iter - N.burn), ncol = D)
for(n in 1:(N.iter - N.burn)){
beta.post[n,] = BW[,i, n + N.burn] %*% t(Theta)
}
beta.pm[i,] = apply(beta.post, 2, mean)
beta.LB[i,] = apply(beta.post, 2, quantile, c(.025))
beta.UB[i,] = apply(beta.post, 2, quantile, c(.975))
}
b.pm = matrix(NA, nrow = I, ncol = D)
for(i in 1:I){
b.post = matrix(NA, nrow = (N.iter - N.burn), ncol = D)
for(n in 1:(N.iter - N.burn)){
b.post[n,] = BZ[,i, n + N.burn] %*% t(Theta)
}
b.pm[i,] = apply(b.post, 2, mean)
}
psi.pm = matrix(NA, nrow = Kp, ncol = D)
for(i in 1:Kp){
psi.post = matrix(NA, nrow = (N.iter - N.burn), ncol = D)
for(n in 1:(N.iter - N.burn)){
psi.post[n,] = Bpsi[,i, n + N.burn] %*% t(Theta)
}
psi.pm[i,] = apply(psi.post, 2, mean)
}
fixef.pm = W.des %*% beta.pm
ranef.pm = Z.des %*% b.pm
Yhat = matrix(NA, nrow = IJ, ncol = D)
psi.pm = t(svd(t(psi.pm))$u)
data = if(is.null(data)) { mf_fixed } else { data }
ret = list(beta.pm, beta.UB, beta.LB, fixef.pm + ranef.pm, ranef.pm, mt_fixed, data, psi.pm)
names(ret) = c("beta.hat", "beta.UB", "beta.LB", "Yhat", "ranef", "terms", "data", "psi.pm")
class(ret) = "fosr"
ret
}
|
SELECTVERB <-
function(speakerID, situation, actor=NULL, undergoer=NULL){
roleNoise=world$roleNoise; distinctiveness=world$distinctiveness
speaker=population[[speakerID]]
target=situation[situation$target==1,]
verbTarget=target[,grep('^V\\d',names(target))]
targetTransitivity=ifelse(is.na(target$personU), 'onePlace', 'twoPlace')
verbs=speaker$verbs[speaker$verbs$type==targetTransitivity,]
verbs=verbs[sample(nrow(verbs)),]
verbs$match=VMATCH(verbTarget, verbs[,grep('^D\\d',names(verbs))])
verbs$collostruction=0
if(!is.null(actor) & is.null(undergoer)){
collostructions=speaker$collostructions$SV[speaker$collostructions$SV$S==actor$ID,]
verbs[verbs$ID%in%collostructions$V,]$collostruction=collostructions[na.omit(match(verbs$ID, collostructions$V)),]$frequency
}
if(!is.null(undergoer)){
collostructions=speaker$collostructions$OV[speaker$collostructions$OV$O==undergoer$ID,]
verbs[verbs$ID%in%collostructions$V,]$collostruction=collostructions[na.omit(match(verbs$ID, collostructions$V)),]$frequency
}
verbOrder=order(CANDIDATESCORE(verbs), decreasing=TRUE)
verb=''
if(nrow(situation) > 1){
verbDistractors=situation[situation$target==0,]
verbDistractors=unique(verbDistractors[,grep('^V\\d',names(verbDistractors))])
verbDistractors=verbDistractors[!VMATCH(verbTarget, verbDistractors)==1,]
if(nrow(verbDistractors)!=0){
for (i in verbOrder){
distractorMatch=MAX(VMATCH(verbs[i,grep('^D\\d',names(verbs))], verbDistractors), value=TRUE, forceChoice=TRUE)
if(verbs[i,]$match > (distractorMatch + distinctiveness)){
verb=verbs[i,]
break()
} } } }
if(nrow(situation)==1){
for (i in verbOrder){
if(verbs[i,]$match > max(verbs[i,]$match)-distinctiveness){
verb=verbs[i,]
break()
} } }
if(!is.data.frame(verb)){verb=verbs[MAX(verbs$match, forceChoice=TRUE),]}
verb$topic=ifelse(target$topic=='verb', 1, 0)
verb
}
|
suppressGraphics <- function(expr, envir = parent.frame()) {
toNullDev({
value <- expr
}, envir = envir)
value
}
|
plot.mctp.rm <-
function(x,...)
{
nc <- length(x$connames)
text.Ci <- paste(x$input$conf.level*100, "%", "Simultaneous Confidence Intervals")
Lowerp <- "|"
asy.method <- x$input$asy.method
alternative <- x$input$alternative
if(asy.method!="log.odds") {
plot(x$Analysis.Inf$Estimator,1:nc,xlim=c(-1,1), pch=15,axes=FALSE,xlab="",ylab="")
points(x$Analysis.Inf$Lower,1:nc, pch=Lowerp,font=2,cex=2)
points(x$Analysis.Inf$Upper,1:nc, pch=Lowerp,font=2,cex=2)
abline(v=0, lty=3,lwd=2)
for (ss in 1:nc){
polygon(x=c(x$Analysis.Inf$Lower[ss],x$Analysis.Inf$Upper[ss]),y=c(ss,ss),lwd=2)
}
axis(1, at = seq(-1, 1, 0.1))
}
else {
if(alternative=="two.sided") {
LowerPlot <- x$Analysis.Inf$Lower
UpperPlot <- x$Analysis.Inf$Upper
}
else if(alternative=="less") {
LowerPlot <- x$Analysis.Inf$Estimator - (x$Analysis.Inf$Upper - x$Analysis.Inf$Estimator)
UpperPlot <- x$Analysis.Inf$Upper
}
else {
LowerPlot <- x$Analysis.Inf$Lower
UpperPlot <- x$Analysis.Inf$Estimator + (x$Analysis.Inf$Estimator - x$Analysis.Inf$Lower)
}
plot(x$Analysis.Inf$Estimator, 1:nc, xlim = c(floor(min(LowerPlot)), ceiling(max(UpperPlot))),
pch = 15, axes = FALSE, xlab = "", ylab = "")
axis(1, at = seq(floor(min(LowerPlot)), ceiling(max(UpperPlot)),
0.05*(ceiling(max(UpperPlot))-floor(min(LowerPlot)))))
hugenumber<-10000000
if(alternative=="two.sided") {
points(LowerPlot, 1:nc, pch = Lowerp, font = 2, cex = 2)
points(UpperPlot, 1:nc, pch = Lowerp, font = 2, cex = 2)
for (ss in 1:nc) {
polygon(x = c(LowerPlot[ss], UpperPlot[ss]), y = c(ss, ss), lwd = 2)
}
}
else if(alternative=="less") {
points(UpperPlot, 1:nc, pch = Lowerp, font = 2, cex = 2)
for (ss in 1:nc) {
polygon(x = c(-hugenumber, UpperPlot[ss]), y = c(ss, ss), lwd = 2)
}
}
else{
points(LowerPlot, 1:nc, pch = Lowerp, font = 2, cex = 2)
for (ss in 1:nc) {
polygon(x = c(LowerPlot[ss], hugenumber), y = c(ss, ss), lwd = 2)
}
}
abline(v = 0, lty = 3, lwd = 2)
}
axis(2,at=1:nc,labels=x$connames)
box()
title(main=c(text.Ci, paste("Type of Contrast:",x$input$type), paste("Method:", x$AsyMethod)))
}
|
gbm.perspec <- function(gbm.object,
x = 1,
y = 2,
pred.means = NULL,
x.label = NULL,
x.range = NULL,
y.label = NULL,
z.label = "fitted value",
y.range = NULL,
z.range = NULL,
leg.coords = NULL,
ticktype = "detailed",
theta = 55,
phi=40,
smooth = "none",
mask = FALSE,
perspective = TRUE,
...)
{
if (! requireNamespace('gbm') ) { stop('you need to install the gbm package to use this function') }
requireNamespace('splines')
gbm.call <- gbm.object$gbm.call
gbm.x <- gbm.call$gbm.x
n.preds <- length(gbm.x)
gbm.y <- gbm.call$gbm.y
pred.names <- gbm.call$predictor.names
family = gbm.call$family
have.factor <- FALSE
x.name <- gbm.call$predictor.names[x]
if (is.null(x.label)) {
x.label <- gbm.call$predictor.names[x]
}
y.name <- gbm.call$predictor.names[y]
if (is.null(y.label)) {
y.label <- gbm.call$predictor.names[y]
}
data <- gbm.call$dataframe[ , gbm.x, drop=FALSE]
n.trees <- gbm.call$best.trees
if (is.vector(data[,x])) {
if (is.null(x.range)) {
x.var <- seq(min(data[,x],na.rm=T),max(data[,x],na.rm=T),length = 50)
} else {
x.var <- seq(x.range[1],x.range[2],length = 50)
}
} else {
x.var <- names(table(data[,x]))
have.factor <- TRUE
}
if (is.vector(data[,y])) {
if (is.null(y.range)) {
y.var <- seq(min(data[,y],na.rm=T),max(data[,y],na.rm=T),length = 50)
} else {y.var <- seq(y.range[1],y.range[2],length = 50)}
} else {
y.var <- names(table(data[,y]))
if (have.factor) {
stop("at least one marginal predictor must be a vector!")
} else {have.factor <- TRUE}
}
pred.frame <- expand.grid(list(x.var,y.var))
names(pred.frame) <- c(x.name,y.name)
pred.rows <- nrow(pred.frame)
if (have.factor) {
if (is.factor(pred.frame[,2])) {
pred.frame <- pred.frame[,c(2,1)]
x.var <- y.var
}
}
j <- 3
for (i in 1:n.preds) {
if (i != x & i != y) {
if (is.vector(data[,i])) {
m <- match(pred.names[i],names(pred.means))
if (is.na(m)) {
pred.frame[,j] <- mean(data[,i],na.rm=T)
} else pred.frame[,j] <- pred.means[m]
}
if (is.factor(data[,i])) {
m <- match(pred.names[i],names(pred.means))
temp.table <- table(data[,i])
if (is.na(m)) {
pred.frame[,j] <- rep(names(temp.table)[2],pred.rows)
} else {
pred.frame[,j] <- pred.means[m]
}
pred.frame[,j] <- factor(pred.frame[,j],levels=names(temp.table))
}
names(pred.frame)[j] <- pred.names[i]
j <- j + 1
}
}
prediction <- gbm::predict.gbm(gbm.object,pred.frame,n.trees = n.trees, type="response")
if (smooth == "model") {
pred.glm <- glm(prediction ~ ns(pred.frame[,1], df = 8) * ns(pred.frame[,2], df = 8), data=pred.frame,family=poisson)
prediction <- fitted(pred.glm)
}
max.pred <- max(prediction)
message("maximum value = ",round(max.pred,2),"\n")
if (is.null(z.range)) {
if (family == "bernoulli") {
z.range <- c(0,1)
} else if (family == "poisson") {
z.range <- c(0,max.pred * 1.1)
} else {
z.min <- min(data[,y],na.rm=T)
z.max <- max(data[,y],na.rm=T)
z.delta <- z.max - z.min
z.range <- c(z.min - (1.1 * z.delta), z.max + (1.1 * z.delta))
}
}
if (have.factor == FALSE) {
pred.matrix <- matrix(prediction,ncol=50,nrow=50)
if (smooth == "average") {
pred.matrix.smooth <- pred.matrix
for (i in 2:49) {
for (j in 2:49) {
pred.matrix.smooth[i,j] <- mean(pred.matrix[c((i-1):(i+1)),c((j-1):(j+1))])
}
}
pred.matrix <- pred.matrix.smooth
}
if (mask) {
mask.trees <- gbm.object$gbm.call$best.trees
point.prob <- gbm::predict.gbm(gbm.object[[1]],pred.frame, n.trees = mask.trees, type="response")
point.prob <- matrix(point.prob,ncol=50,nrow=50)
pred.matrix[point.prob < 0.5] <- 0.0
}
if (!perspective) {
image(x = x.var, y = y.var, z = pred.matrix, zlim = z.range)
} else {
persp(x=x.var, y=y.var, z=pred.matrix, zlim= z.range,
xlab = x.label, ylab = y.label, zlab = z.label,
theta=theta, phi=phi, r = sqrt(10), d = 3,
ticktype = ticktype, mgp = c(4,1,0), ...)
}
}
if (have.factor) {
factor.list <- names(table(pred.frame[,1]))
n <- 1
if (is.null(z.range)) {
vert.limits <- c(0, max.pred * 1.1)
} else {
vert.limits <- z.range
}
plot(pred.frame[pred.frame[,1]==factor.list[1],2],
prediction[pred.frame[,1]==factor.list[1]],
type = 'l',
ylim = vert.limits,
xlab = y.label,
ylab = z.label, ...)
for (i in 2:length(factor.list)) {
factor.level <- factor.list[i]
lines(pred.frame[pred.frame[,1]==factor.level,2],
prediction[pred.frame[,1]==factor.level], lty = i)
}
if(is.null(leg.coords)){
x.max <- max(pred.frame[,2])
x.min <- min(pred.frame[,2])
x.range <- x.max - x.min
x.pos <- c(x.min + (0.02 * x.range),x.min + (0.3 * x.range))
y.max <- max(prediction)
y.min <- min(prediction)
y.range <- y.max - y.min
y.pos <- c(y.min + (0.8 * y.range),y.min + (0.95 * y.range))
legend(x = x.pos, y = y.pos, factor.list, lty = c(1:length(factor.list)), bty = "n")
} else {
legend(x = leg.coords[1], y = leg.coords[2], factor.list, lty = c(1:length(factor.list)), bty = "n")
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.