code
stringlengths 1
13.8M
|
---|
modifyList <- function(x, val, keep.null = FALSE)
{
stopifnot(is.list(x), is.list(val))
xnames <- names(x)
vnames <- names(val)
vnames <- vnames[nzchar(vnames)]
if (keep.null) {
for (v in vnames) {
x[v] <-
if (v %in% xnames && is.list(x[[v]]) && is.list(val[[v]]))
list(modifyList(x[[v]], val[[v]], keep.null = keep.null))
else val[v]
}
}
else {
for (v in vnames) {
x[[v]] <-
if (v %in% xnames && is.list(x[[v]]) && is.list(val[[v]]))
modifyList(x[[v]], val[[v]], keep.null = keep.null)
else val[[v]]
}
}
x
}
warnErrList <- function(x, warn = TRUE, errValue = NULL) {
errs <- vapply(x, inherits, NA, what = "error")
if(any(errs)) {
v.err <- x[errs]
e.call <- deparse1(conditionCall(v.err[[1]]), collapse = "\n")
tt <- table(vapply(v.err, conditionMessage, ""))
msg <-
if(length(tt) == 1L)
sprintf(ngettext(tt[[1L]],
"%d error caught in %s: %s",
"%d times caught the same error in %s: %s"),
tt[[1L]], e.call, names(tt)[[1L]])
else
paste(gettextf(
"%d errors caught in %s. The error messages and their frequencies are",
sum(tt), e.call),
paste(capture.output(sort(tt)), collapse="\n"), sep="\n")
if(warn)
warning(msg, call. = FALSE, domain = NA)
x[errs] <- list(errValue)
attr(x, "warningMsg") <- msg
}
x
} |
get_sysdata <- function() {
data <- .data
return(data)
} |
CNclusterNcenter <-
function(segrat,blsize,minjoin,ntrial,bestbic,
modelNames,cweight,bstimes,chromrange,seedme){
.lec.CreateStream(segrat$stream)
.lec.SetSeed(segrat$stream,seedme)
for( j in 1:segrat$sub).lec.ResetNextSubstream(segrat$stream)
.lec.CurrentStream(segrat$stream)
startcol<-"StartProbe"
endcol<-"EndProbe"
chromcol<-"chrom"
medcol<-"segmedian"
madcol<-"segmad"
segrat$seg<-cbind(segrat$seg,t(apply(segrat$seg[,c(startcol,endcol,chromcol),
drop=F],1,smedmad,v=segrat$rat)))
dimnames(segrat$seg)[[2]]<-c(startcol,endcol,chromcol,medcol,madcol)
seguse<-segrat$seg[segrat$seg[,chromcol]%in%chromrange,,drop=F]
aux<-rep(0,length(segrat$rat))
aux[seguse[,startcol]]<-1
aux[seguse[,endcol]]<-(-1)
aux<-cumsum(aux)
aux[seguse[,endcol]]<-1
ratuse<-segrat$rat[aux==1]
for(j in 1:ntrial){
aaa<-segsample(seguse,ratuse,blocksize=blsize)
if(all(unique(aaa[,3])==0)){ aaa[,3]<-1e-10 }
emfit<-Mclust(aaa[,3],maxG=15,modelNames=modelNames)
if(emfit$bic>=bestbic){
bestaaa<-aaa
bestem<-emfit
bestbic<-emfit$bic
}
}
newem<-consolidate(bestem,minjoin)
newem<-get.center(newem,cweight)
if(length(bestem$parameters$mean)==1){ profcenter<-median(bestaaa[,3])
}else{ profcenter<-weighted.median(bestaaa[,3],newem$z[,newem$center]) }
mediandev<-segrat$seg[,medcol]-profcenter
segs<-segsample(segrat$seg,segrat$rat,times=bstimes)
if(all(unique(aaa[,3])==1e-10)){ segs[segs[,3]==0,3]<-1e-10 }
segzall<-getz(segs[,3],bestem,newem$groups,times=bstimes)
centerz<-segzall[,newem$center]
maxz<-segzall[nrow(segzall)*(max.col(segzall)-1)+(1:nrow(segzall))]
maxzcol<-max.col(segzall)
maxzmean<-newem$mu[maxzcol]-newem$mu[newem$center]
maxzsigma<-sqrt(newem$sigmasq[maxzcol])
cpb<-centerprob(segs[,3],bestem,newem$groups,times=bstimes,newem$center)
w<-t(matrix(nrow=bstimes,data=segs[,3]))
segerr<-sqrt(apply(w,1,var,na.rm=T))
.lec.CurrentStreamEnd()
.lec.DeleteStream(segrat$stream)
return(cbind(segrat$seg[,medcol],segrat$seg[,madcol],mediandev,segerr,centerz,
cpb,maxz,maxzmean,maxzsigma))
} |
catalog_apply <- function(ctg, FUN, ..., .options = NULL)
{
assert_is_all_of(ctg, "LAScatalog")
assert_is_function(FUN)
opt <- engine_parse_options(.options)
if (opt[["autoread"]] == FALSE) assert_fun_is_null_with_empty_cluster(ctg, FUN, ...)
assert_processing_constraints_are_repected(ctg, opt[["need_buffer"]], opt[["need_output_file"]])
realigment <- if (opt[["check_alignment"]]) realigment = opt[["raster_alignment"]] else FALSE
clusters <- catalog_makechunks(ctg, realigment)
oldstate <- getOption("lidR.progress")
options(lidR.progress = FALSE)
on.exit(options(lidR.progress = oldstate), add = TRUE)
output <- cluster_apply(clusters, FUN, ctg@processing_options, ctg@output_options, opt[["globals"]], opt[["autoread"]], ...)
if (isTRUE(opt[["drop_null"]]))
output <- Filter(Negate(is.null), output)
if (!isFALSE(opt[["automerge"]]) && opt_merge(ctg))
output <- catalog_merge_results(ctg, output, opt[["automerge"]], as.character(substitute(FUN)))
return(output)
}
catalog_sapply <- function(ctg, FUN, ..., .options = NULL)
{
if (is.null(.options))
.options <- list(automerge = TRUE)
else
.options$automerge <- TRUE
return(catalog_apply(ctg, FUN, ..., .options = .options))
}
assert_fun_is_null_with_empty_cluster = function(ctg, FUN, ...)
{
if (opt_wall_to_wall(ctg) == TRUE)
{
cl <- LAScluster(list(x = 0, y = 0), 0, 0, 0, LIDRRECTANGLE, system.file("extdata", "example.laz", package = "rlas"), "noname")
cl@select <- "*"
u <- tryCatch(FUN(cl, ...), error = function(e)
{
stop(paste0("The function is tested before starting processing the collection and failed with following error:\n", e), call. = FALSE)
})
if (!is.null(u))
stop("User's function does not return NULL for empty chunks. Please see the documentation of catalog_apply.", call. = FALSE)
}
}
assert_processing_constraints_are_repected <- function(ctg, need_buffer, need_output_file)
{
if (need_buffer & opt_chunk_buffer(ctg) <= 0 && opt_wall_to_wall(ctg))
stop("A buffer greater than 0 is required to process the catalog.", call. = FALSE)
if (need_output_file & opt_output_files(ctg) == "")
stop("This function requires that the LAScatalog provides an output file template.", call. = FALSE)
}
engine_parse_options = function(.option)
{
output <- list()
raster_alignment <- .option$raster_alignment
if (is.null(raster_alignment))
{
raster_alignment <- NULL
check_alignment <- FALSE
}
else if (is.numeric(raster_alignment))
{
assert_is_a_number(raster_alignment)
assert_all_are_non_negative(raster_alignment)
raster_alignment <- list(res = raster_alignment, start = c(0,0))
check_alignment <- TRUE
}
else if (is.list(raster_alignment))
{
assert_is_a_number(raster_alignment$res)
assert_all_are_non_negative(raster_alignment$res)
check_alignment <- TRUE
if (!is.null(raster_alignment$start))
assert_is_numeric(raster_alignment$start)
}
else
stop("Invalid parameter 'raster_alignment")
output$raster_alignment <- raster_alignment
output$check_alignment <- check_alignment
if (is.null(.option$need_output_file))
{
need_output_file <- FALSE
}
else
{
need_output_file <- .option$need_output_file
assert_is_a_bool(need_output_file)
}
output$need_output_file <- need_output_file
if (is.null(.option$drop_null))
{
drop_null <- TRUE
}
else
{
drop_null <- .option$drop_null
assert_is_a_bool(drop_null)
}
output$drop_null <- drop_null
if (is.null(.option$automerge))
{
automerge <- FALSE
}
else
{
automerge <- .option$automerge
if (isTRUE(automerge))
automerge <- "auto"
}
output$automerge <- automerge
if (is.null(.option$autoread))
{
autoread <- FALSE
}
else
{
autoread <- .option$autoread
if (isTRUE(autoread))
autoread <- TRUE
}
output$autoread <- autoread
if (is.null(.option$need_buffer))
{
need_buffer <- FALSE
}
else
{
need_buffer <- .option$need_buffer
assert_is_a_bool(need_buffer)
}
output$need_buffer <- need_buffer
if (is.null(.option$globals))
output$globals <- NULL
else
output$globals <- .option$globals
return(output)
} |
rba_uniprot_coordinates_search <- function(accession = NULL,
chromosome = NULL,
ensembl_id = NULL,
gene = NULL,
protein = NULL,
taxid = NULL,
location = NULL,
...) {
.rba_ext_args(...)
.rba_args(cons = list(list(arg = "accession",
class = "character",
max_len = 100),
list(arg = "chromosome",
class = c("character",
"numeric"),
max_len = 20),
list(arg = "ensembl_id",
class = "character",
max_len = 20),
list(arg = "gene",
class = "character",
max_len = 20),
list(arg = "protein",
class = "character"),
list(arg = "taxid",
class = "numeric",
max_len = 20),
list(arg = "location",
class = "character")))
.msg("Searching UniProt and retrieving Coordinates of proteins that match your supplied inputs.")
call_query <- .rba_query(init = list("size" = "-1"),
list("accession",
!is.null(accession),
paste0(accession,
collapse = ",")),
list("chromosome",
!is.null(chromosome),
paste0(chromosome,
collapse = ",")),
list("ensembl_id",
!is.null(ensembl_id),
paste0(ensembl_id,
collapse = ",")),
list("gene",
!is.null(gene),
paste0(gene,
collapse = ",")),
list("protein",
!is.null(protein),
protein),
list("taxid",
!is.null(taxid),
paste0(taxid,
collapse = ",")),
list("location",
!is.null(location),
location))
parser_input <- list("json->list",
.rba_uniprot_search_namer)
input_call <- .rba_httr(httr = "get",
url = .rba_stg("uniprot", "url"),
path = paste0(.rba_stg("uniprot", "pth"),
"coordinates"),
query = call_query,
accept = "application/json",
parser = parser_input,
save_to = .rba_file("uniprot_coordinates_search.json"))
final_output <- .rba_skeleton(input_call)
return(final_output)
}
rba_uniprot_coordinates_sequence <- function(accession,
p_position = NULL,
p_start = NULL,
p_end = NULL,
...) {
.rba_ext_args(...)
.rba_args(cons = list(list(arg = "accession",
class = "character"),
list(arg = "p_position",
class = "numeric"),
list(arg = "p_start",
class = "numeric"),
list(arg = "p_end",
class = "numeric")),
cond = list(list(quote(any(sum(!is.null(p_position), !is.null(p_start), !is.null(p_end)) == 3,
sum(!is.null(p_position), !is.null(p_start), !is.null(p_end)) == 0,
sum(!is.null(p_start), !is.null(p_end)) == 1)),
"You should supply either 'p_position' alone or 'p_start' and 'p_end' together.")
))
.msg("Retrieving genome coordinates of protein %s in sequence position %s.",
accession,
ifelse(is.null(p_position),
yes = paste(p_start, p_end, sep = " to "), no = p_position))
path_input <- sprintf("%scoordinates/location/%s:%s",
.rba_stg("uniprot", "pth"),
accession,
ifelse(!is.null(p_position),
yes = p_position,
no = paste0(p_start, "-", p_end)))
input_call <- .rba_httr(httr = "get",
url = .rba_stg("uniprot", "url"),
path = path_input,
accept = "application/json",
parser = "json->list_simp",
save_to = .rba_file("uniprot_coordinates_location.json"))
final_output <- .rba_skeleton(input_call)
return(final_output)
}
rba_uniprot_coordinates <- function(accession = NULL,
db_type = NULL,
db_id = NULL,
...) {
.rba_ext_args(...)
.rba_args(cons = list(list(arg = "accession",
class = "character"),
list(arg = "db_type",
class = "character",
val = c("Ensembl",
"CCDC",
"HGNC",
"RefSeq")),
list(arg = "db_id",
class = "character")),
cond = list(list(quote(any(sum(!is.null(accession), !is.null(db_type), !is.null(db_id)) == 3,
sum(!is.null(accession), !is.null(db_type), !is.null(db_id)) == 0,
sum(!is.null(db_type), !is.null(db_id)) == 1)),
"You should supply either 'accession' alone or 'db_type' and 'db_id' together.")
))
.msg("Retrieving genome coordinates of protein with ID: %s",
ifelse(is.null(accession),
yes = sprintf("%s in %s database", db_id, db_type),
no = accession))
call_query <- list("size" = "-1")
path_input <- sprintf("%scoordinates/%s",
.rba_stg("uniprot", "pth"),
ifelse(!is.null(accession),
yes = accession,
no = paste0(db_type, ":", db_id)))
input_call <- .rba_httr(httr = "get",
url = .rba_stg("uniprot", "url"),
path = path_input,
query = call_query,
accept = "application/json",
parser = "json->list",
save_to = .rba_file("uniprot_coordinates.json"))
final_output <- .rba_skeleton(input_call)
return(final_output)
}
rba_uniprot_coordinates_location <- function(taxid,
locations,
in_range = TRUE,
feature = FALSE,
...) {
.rba_ext_args(...)
.rba_args(cons = list(list(arg = "taxid",
class = "numeric"),
list(arg = "locations",
class = "character"),
list(arg = "in_range",
class = "logical"),
list(arg = "feature",
class = "logical"))
)
.msg("Retrieving UniProt entries in location %s of taxon %s.",
locations, taxid)
call_query <- list("size" = "-1",
"in_range" = ifelse(in_range, "true", "false"))
path_input <- sprintf("%scoordinates/%s/%s",
.rba_stg("uniprot", "pth"),
taxid,
locations)
if (isTRUE(feature)) {
path_input <- paste0(path_input, "/feature")
}
input_call <- .rba_httr(httr = "get",
url = .rba_stg("uniprot", "url"),
path = path_input,
query = call_query,
accept = "application/json",
parser = "json->list",
save_to = .rba_file("rba_uniprot_coordinates_location.json"))
final_output <- .rba_skeleton(input_call)
return(final_output)
} |
theme_ggparliament <- function(legend = TRUE,
background_colour = FALSE,
border = FALSE) {
basic_theme <- ggplot2::theme_void()
if (legend == TRUE) {
basic_theme <- basic_theme
} else {
basic_theme <- basic_theme + ggplot2::theme(legend.position = "none")
}
if (!background_colour) {
basic_theme <- basic_theme
} else {
basic_theme <- basic_theme + ggplot2::theme(panel.background = ggplot2::element_rect(fill = "
}
if (!border) {
basic_theme <- basic_theme
} else {
basic_theme <- basic_theme + ggplot2::theme(panel.border = ggplot2::element_rect(colour = "
}
basic_theme
} |
cmaSetDimension <- function(cma,i) {
rJava::.jcall(cma,,"setDimension",as.integer(i));
}
cmaGetDimension <- function(cma) {
rJava::.jcall(cma,"I","getDimension");
}
cmaSetPopulationSize <- function(cma,i) {
rJava::.jcall(cma,,"setPopulationSize",as.integer(i));
}
cmaGetPopulationSize <- function(cma) {
rJava::.jcall(cma,"I","getPopulationSize");
}
cmaSetInitialX <- function(cma,initialX) {
rJava::.jcall(cma,,"setInitialX",initialX);
}
cmaGetInitialX <- function(cma) {
rJava::.jcall(cma,"[D","getInitialX");
}
cmaSetCountEval <- function(cma,p) {
rJava::.jcall(cma,"J","setCountEval",rJava::.jlong(p));
}
cmaGetCountEval <- function(cma) {
rJava::.jcall(cma,"J","getCountEval");
}
cmaSetStopFitness <- function(cma,d) {
rJava::.jcall(cma,,"setOptionsStopFitness",as.double(d));
}
cmaSetStopMaxFunEvals <- function(cma,p) {
rJava::.jcall(cma,,"setOptionsStopMaxFunEvals",rJava::.jlong(p));
}
cmaSetStopTolFun <- function(cma,d) {
rJava::.jcall(cma,,"setOptionsStopTolFun",as.double(d));
} |
qbetabinom <- function(p, M, mu, phi) {
pdfvec <- VGAM::dbetabinom(x = 0:M, size = M, prob = mu, rho = phi)
CDF <- cumsum(pdfvec)
above <- which(CDF > p)[1]
quant <- above - 1
if (quant > 0) {
return(quant + (p - CDF[quant])/pdfvec[above])
} else {
return(p/pdfvec[1])
}
} |
PrimEff <-
function(data,plot=TRUE) {
prim=data
prim[,"gene"]=as.factor(as.character(prim[,"gene"]))
genes=levels(prim[,"gene"])
if (length(genes)>1) {
graphcols=ceiling(sqrt(length(genes)))
graphrows=ceiling(length(genes)/graphcols)
if (plot==TRUE) par(mfrow=c(graphrows,graphcols))
}
gg=c();ii=c();ee=c();eu=c();el=c()
for (g in genes)
{
s=prim[prim[,"gene"]==g,]
genlm=lm(cq~log(dna,2),s,na.action="na.omit")
inter=coef(genlm)[1]
slop=coef(summary(genlm))[2,1]
sloperr=coef(summary(genlm))[2,2]
eff=2^(-1/(slop))
efflo=round(2^(-1/(slop-sloperr)),2)
effup=round(2^(-1/(slop+sloperr)),2)
slop=round(slop,2)
gg=append(gg,g)
eff=round(eff,2)
ee=append(ee,eff)
eu=append(eu,effup)
el=append(el,efflo)
ii=append(ii,round(inter,1))
if (plot==TRUE){
plot(cq~log(dna,2),s,main=g,xlab=paste("slope =",slop," intercept =",round(inter,1)), sub=paste("E = ",eff," ( ",round(efflo,2)," - ",round(effup,2)," )",sep=""),mgp=c(2.3,1,0))
abline(genlm)
}
}
rr=cbind("gene"=gg,"E"=ee,"E.minus.se"=el,"E.plus.se"=eu,"intercept"=ii)
row.names(rr)=c()
rr=data.frame(rr)
rr$E=as.numeric(as.character(rr$E))
rr$E.minus.se=as.numeric(as.character(rr$E.minus.se))
rr$E.plus.se=as.numeric(as.character(rr$E.plus.se))
rr$intercept=as.numeric(as.character(rr$intercept))
return(rr)
} |
NULL
getWidget.tkwin <- function(obj) obj
getBlock <- function(obj) {
if(is(obj, "GComponent"))
obj$get_block()
else
obj
}
widthOfChar <- ceiling(as.numeric(tclvalue(tcl("font","measure","TkTextFont","0"))))
heightOfChar <- as.numeric(as.character(tcl("font","metrics","TkTextFont"))[6])
xyToAnchor <- function(anchor) {
m = rbind(
c("nw","n","ne"),
c("w","center","e"),
c("sw","s","se")
)
anchor = m[2 - anchor[2],2 + anchor[1]]
return(anchor)
}
is_aqua <- function() {
as.character(tcl("tk","windowingsystem")) == "aqua"
}
merge_list <- function(x, y, overwrite=TRUE) {
x <- as.list(x)
if(missing(y) || is.null(y))
return(x)
for(i in names(y))
if((is.logical(overwrite) && overwrite) || !(i %in% names(x)))
x[[i]] <- y[[i]]
x
} |
do_base <- "https://api.digitalocean.com/v2"
url <- function(...) structure(paste(do_base, ..., sep = "/"), class = "do_url")
print.do_url <- function(x, ...) {
cat("<url> ", x, "\n", sep = "")
}
as.url <- function(x, ...) UseMethod("as.url")
as.url.character <- function(x, ...) paste0(do_base, "/", x)
as.url.do_url <- function(x, ...) x
NULL
do_GET <- function(url, ...) {
do_VERB("GET", url, ...)
}
do_POST <- function(url, ..., body = NULL, encode = "json") {
body <- ascompact(body)
do_VERB("POST", url, ..., body = body, encode = encode)
}
do_PUT <- function(url, ...) {
do_VERB("PUT", url, ...)
}
do_PATCH <- function(url, ...) {
do_VERB("PATCH", url, ...)
}
do_DELETE <- function(url, ...) {
do_VERB("DELETE", url, ...)
}
do_DELETE_body <- function(url, body = NULL, ...) {
url <- as.url(url)
res <- VERB("DELETE", url, body = body, ..., do_oauth())
if (length(res$content) == 0) {
httr::stop_for_status(res)
return(invisible(TRUE))
}
text <- httr::content(res, as = "text", encoding = "UTF-8")
json <- jsonlite::fromJSON(text, simplifyVector = FALSE)
if (httr::status_code(res) >= 400) {
stop(json$message, call. = FALSE)
}
json
}
do_VERB <- function(verb, url, ...) {
url <- as.url(url)
VERB <- getExportedValue("httr", verb)
res <- VERB(url, ..., do_oauth())
if (length(res$content) == 0) {
httr::stop_for_status(res)
return(invisible(TRUE))
}
text <- httr::content(res, as = "text", encoding = "UTF-8")
json <- jsonlite::fromJSON(text, simplifyVector = FALSE)
if (httr::status_code(res) >= 400) {
stop(json$message, call. = FALSE)
}
json
} |
rankODIBatsmen <- function(dir='.',odir=".",minMatches=50) {
currDir= getwd()
battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=NULL
teams <-c("Australia","India","Pakistan","West Indies", 'Sri Lanka',
"England", "Bangladesh","Netherlands","Scotland", "Afghanistan",
"Zimbabwe","Ireland","New Zealand","South Africa","Canada",
"Bermuda","Kenya","Hong Kong","Nepal","Oman","Papua New Guinea",
"United Arab Emirates","Namibia","Cayman Islands","Singapore",
"United States of America","Bhutan","Maldives","Botswana","Nigeria",
"Denmark","Germany","Jersey","Norway","Qatar","Malaysia","Vanuatu",
"Thailand")
setwd(odir)
battingDF<-NULL
for(team in teams){
battingDetails <- NULL
val <- paste(team,"-BattingDetails.RData",sep="")
print(val)
tryCatch(load(val),
error = function(e) {
print("No data1")
setNext=TRUE
}
)
details <- battingDetails
battingDF <- rbind(battingDF,details)
}
df <- select(battingDF,batsman,runs,strikeRate)
b=summarise(group_by(df,batsman),matches=n(), meanRuns=mean(runs),meanSR=mean(strikeRate))
b[is.na(b)] <- 0
setwd(currDir)
c <- filter(b,matches >= minMatches)
ODIBatsmenRank <- arrange(c,desc(meanRuns),desc(meanSR))
ODIBatsmenRank
} |
clustCombi <- function(object = NULL, data = NULL, ...)
{
if(is.null(object) & is.null(data))
stop("An object or class 'Mclust' or data as matrix/data.frame must be provided!")
if(is.null(object))
{ object <- Mclust(data, ...) }
else
{ if(!inherits(object, "Mclust"))
stop("object not of class 'Mclust'")
data <- object$data }
combiRes <- combi(data, object)
return(combiRes)
}
combMat <- function(K,l1,l2)
{
l=c(min(l1,l2), max(l1,l2))
if(any(length(l1) == 0, length(l2) == 0)){
l1 = numeric(0)
l2 = l[2]}
else {
l1 = l[1]
l2 = l[2]}
M <- rbind(cbind(diag(l2-1),
matrix(rep(0,(K-l2+1)*(l2-1)), nrow=l2-1, ncol=K-l2+1)),
cbind(matrix(rep(0,l2*(K-l2)), nrow=K-l2, ncol=l2),
diag(K-l2)))
M[l1,l2] <- 1
return(M)
}
xlog <- function(x)
{
xlog1d <- function (xi) if (xi == 0) 0 else (xi*log(xi))
if (is.null(dim(x)))
{
return(sapply(x,xlog1d))
}
else
{
return(matrix(sapply(x,xlog1d),dim(x)))
}
}
combi <- function(data, MclustOutput, n = nrow(data), d = ncol(data))
{
combiM <- list()
combiM[[MclustOutput$G]] <- diag(MclustOutput$G)
tau <- list()
tau[[MclustOutput$G]] = MclustOutput$z
classif <- list()
classif[[MclustOutput$G]] = map(tau[[MclustOutput$G]])
for (K in MclustOutput$G:2)
{
dEnt <- matrix(0,nrow=K-1, ncol=K)
preCombiTau <- tau[[K]]
for (l1 in 1:(K-1))
{
for (l2 in (l1+1):K)
{
postCombiTau <- t(combMat(K,l1,l2) %*% t(preCombiTau))
dEnt[l1,l2] <- sum(xlog(postCombiTau[,l1])) - sum(xlog(preCombiTau[,l1])+xlog(preCombiTau[,l2]))
}
}
l1=which(dEnt==max(dEnt),arr.ind=TRUE)[1]
l2=which(dEnt==max(dEnt),arr.ind=TRUE)[2]
combiM[[K-1]] <- combMat(K,l1,l2)
tau[[K-1]] = t(combiM[[K-1]] %*% t(tau[[K]]))
classif[[K-1]] = map(tau[[K-1]])
}
output <- list(classification = classif,
combiM = combiM,
combiz = tau,
MclustOutput = MclustOutput)
class(output) <- "clustCombi"
return(output)
}
plot.clustCombi <- function(x, what = c("classification", "entropy", "tree"), ...)
{
object <- x
if(!inherits(object, "clustCombi"))
stop("object not of class 'clustCombi'")
data <- object$MclustOutput$data
what <- match.arg(what, several.ok = TRUE)
oldpar <- par(no.readonly = TRUE)
on.exit(par(oldpar))
plot.clustCombi.classification <- function(...)
{
curr <- 1:object$MclustOutput$G
i <- numeric()
j <- numeric()
for(K in (object$MclustOutput$G):2)
{ l1 <- which(!object$combiM[[K-1]] %*% rep(1,K) == 1)
l2 <- (object$combiM[[K-1]] %*% curr)[l1] - curr[l1]
i <- c(curr[l1],i)
j <- c(l2,j)
curr <- object$combiM[[K-1]] %*% curr - l2*c(rep(0,(l1-1)),1,rep(0,(K-1-l1)))
}
permutMat <- function(j,K)
{
M <- diag(K)
M[j,j] <- 0
M[K,K] <- 0
M[j,K] <- 1
M[K,j] <- 1
return(M)
}
combiM <- diag(object$MclustOutput$G)
j <- c(1,j)
i <- c(0,i)
permutz <- object$MclustOutput$z[,j]
par(ask=TRUE)
for(K in object$MclustOutput$G:1)
{
curr_title <- if(K == object$MclustOutput$G)
paste0("BIC solution (", as.character(K), " clusters)")
else paste0("Combined solution with ", as.character(K), " clusters")
if(ncol(as.matrix(data)) > 2)
{ par(oma = c(0,0,2,0),
mar = { mar <- oldpar$mar; mar[3] <- 0.1; mar }) }
else
{ par(mar = { mar <- oldpar$mar; mar[3] <- 2.1; mar }) }
combiPlot(data = data, z = permutz, combiM = combiM, ...)
if(ncol(as.matrix(data)) > 2)
{ title(curr_title, outer = TRUE, cex.main = 1) }
else
{ title(curr_title, cex.main = 1) }
combiM <- combMat(K,which(j==i[K]),K) %*% combiM
}
par(ask=FALSE)
}
if(interactive() & length(what) > 1)
{ title <- "Combined clusterings plots:"
choice <- menu(what, graphics = FALSE, title = title)
while(choice != 0)
{ if(what[choice] == "classification")
plot.clustCombi.classification(...)
if(what[choice] == "entropy")
entPlot(z = object$MclustOutput$z, combiM = object$combiM, ...)
if(what[choice] == "tree")
combiTree(object, ...)
choice <- menu(what, graphics = FALSE, title = title)
}
}
else
{ if(any(what == "classification"))
plot.clustCombi.classification(...)
if(any(what == "entropy"))
entPlot(z = object$MclustOutput$z, combiM = object$combiM, ...)
if(any(what == "tree"))
combiTree(object, ...)
}
invisible()
}
combiPlot <- function(data, z, combiM, ...)
{
p <- ncol(as.matrix(data))
if (p > 2) {
clPairs(data[,1:min(5,p)],
classification = map(t(combiM %*% t(z))), ...)
}
else if (p == 2) {
mclust2Dplot(data = data, parameters = NULL,
classification = map(t(combiM %*% t(z))),
what = "classification", ...)
}
else {
mclust1Dplot(data = as.matrix(data), parameters = NULL,
classification = map(t(combiM %*% t(z))),
what = "classification", ...)
}
}
entPlot <- function(z, combiM, abc = c("standard", "normalized"), reg = 2, ...)
{
oldpar <- par(no.readonly = TRUE)
on.exit(par(oldpar))
if(length(abc) > 1) par(ask=TRUE)
ent <- numeric()
Kmax <- ncol(z)
z0 <- z
for(K in Kmax:1)
{ z0 <- t(combiM[[K]] %*% t(z0))
ent[K] <- -sum(xlog(z0))
}
if(any(abc == "normalized"))
{
mergedn <- numeric()
z0 <- z
for(K in (Kmax-1):1)
{ z0 <- t(combiM[[K+1]] %*% t(z0))
mergedn[K] = sum(sapply(map(z0), function(x)
any(which(as.logical(combiM[[K]][rowSums(combiM[[K]])==2,]))==x)))
}
}
if(Kmax == 2) reg <- NULL
if(any(abc == "standard"))
{
par(mfrow=c(1,2), oma=c(0,0,3,0),
mar = { mar <- oldpar$mar; mar[3] <- 0.1; mar })
plot(1:Kmax, ent,
xlab = "Number of clusters",
ylab = "Entropy",
xaxt = "n", ...)
axis(side = 1, at = 1:Kmax)
if(any(reg == 2))
{
pcwsreg <- pcws2_reg(1:Kmax,ent)
lines(1:pcwsreg$c,
pcwsreg$a1*(1:pcwsreg$c) + pcwsreg$b1,
lty = 2, col = "red")
lines(pcwsreg$c:Kmax,
pcwsreg$a2*(pcwsreg$c:Kmax) + pcwsreg$b2,
lty = 2, col = "red")
}
if(any(reg == 3))
{
pcwsreg <- pcws3_reg(1:Kmax,ent)
lines(1:pcwsreg$c1,
pcwsreg$a1*(1:pcwsreg$c1) + pcwsreg$b1,
lty = 2, col = "blue")
lines(pcwsreg$c1:pcwsreg$c2,
pcwsreg$a2*(pcwsreg$c1:pcwsreg$c2) + pcwsreg$b2,
lty = 2, col = "blue")
lines(pcwsreg$c2:Kmax, pcwsreg$a3*(pcwsreg$c2:Kmax) + pcwsreg$b3,
lty = 2, col = "blue")
}
plot(1:(Kmax-1), ent[2:Kmax]-ent[1:(Kmax-1)],
xlab = "Number of clusters",
ylab = "Difference in entropy",
xaxt = "n", ...)
axis(side = 1, at = 1:(Kmax-1))
title("Entropy plot", outer=TRUE, cex.main = 1)
}
if(any(abc == "normalized"))
{
par(mfrow=c(1,2), oma=c(0,0,3,0),
mar = { mar <- oldpar$mar; mar[3] <- 0.1; mar })
plot(cumsum(c(0,mergedn)), ent,
xlab = "Cumul. count of merged obs.",
ylab = "Entropy", ...)
if(any(reg == 2))
{
X <- cumsum(c(0,mergedn))
pcwsreg <- pcws2_reg(X,ent)
lines(X[1:pcwsreg$c],
pcwsreg$a1*(X[1:pcwsreg$c]) + pcwsreg$b1,
lty = 2, col = "red")
lines(X[pcwsreg$c:Kmax],
pcwsreg$a2*(X[pcwsreg$c:Kmax]) + pcwsreg$b2,
lty = 2, col = "red")
}
if(any(reg == 3))
{
X <- cumsum(c(0,mergedn))
pcwsreg <- pcws3_reg(X,ent)
lines(X[1:pcwsreg$c1],
pcwsreg$a1*(X[1:pcwsreg$c1]) + pcwsreg$b1,
lty = 2, col = "blue")
lines(X[pcwsreg$c1:pcwsreg$c2],
pcwsreg$a2*(X[pcwsreg$c1:pcwsreg$c2]) + pcwsreg$b2,
lty = 2, col = "blue")
lines(X[pcwsreg$c2:Kmax],
pcwsreg$a3*(X[pcwsreg$c2:Kmax]) + pcwsreg$b3,
lty = 2, col = "blue")
}
plot(1:(Kmax-1), (ent[2:Kmax]-ent[1:(Kmax-1)])/mergedn,
xlab = "Number of clusters",
ylab = "Normalized difference in entropy",
xaxt = "n", ...)
axis(side = 1, at = 1:(Kmax-1))
title("Normalized entropy plot", outer=TRUE, cex.main = 1)
}
invisible()
}
combiTree <- function(object, type = c("triangle", "rectangle"),
yaxis = c("entropy", "step"),
edgePar = list(col = "darkgray", lwd = 2), ...)
{
if(!inherits(object, "clustCombi"))
stop("object not of class 'clustCombi'")
yaxis <- match.arg(yaxis, eval(formals(combiTree)$yaxis), several.ok = FALSE)
type <- match.arg(type, eval(formals(combiTree)$type), several.ok = FALSE)
G <- object$MclustOutput$G
combiM <- object$combiM
curr <- 1:G
merged <- -(1:G)
merge <- matrix(NA, G-1, 2)
for(k in 1:(G-1))
{
Kp <- G - k + 1
l1 <- which(!combiM[[Kp-1]] %*% rep(1,Kp) == 1)
l2 <- (combiM[[Kp-1]] %*% curr)[l1] - curr[l1]
curr <- setdiff(curr, max(l1, l2))
merge[k,] <- merged[c(l1,l2)]
merged[merged == merged[l1] | merged == merged[l2]] <- k
}
sel <- function(x)
{ if(x < 0) return(abs(x))
else return(c(sel(merge[x,1]), sel(merge[x,2])))
}
ord <- abs(c(sel(merge[nrow(merge),1]), sel(merge[nrow(merge),2])))
if(yaxis == "step")
{
h <- 1:(G-1)
ylab <- "Steps"
} else
{
entropy <- sapply(rev(object$combiz), function(z) -sum(xlog(z)))
h <- entropy; h <- 1 - (h - min(h))/(max(h)-min(h)); h <- h[-1]
ylab <- "1 - normalised entropy"
}
hc <- list(merge = merge,
height = h,
order = ord,
labels = 1:G)
class(hc) <- "hclust"
dendro <- as.dendrogram(hc)
plot(dendro, type = type, edgePar = edgePar, ylab = ylab, ...)
invisible(dendro)
}
pcws2_reg <- function(x, y)
{
C <- length(x)
ssBest = Inf
for (c in 2:(C-1))
{
x1 <- x[1:c]
y1 <- y[1:c]
x2 <- x[c:C]
y2 <- y[c:C]
a1 <- sum((x1-mean(x1))*(y1-mean(y1)))/sum((x1-mean(x1))^2)
b1 <- -a1 * mean(x1) + mean(y1)
a2 <- sum((x2-mean(x2))*(y2-mean(y2)))/sum((x2-mean(x2))^2)
b2 <- -a2 * mean(x2) + mean(y2)
ss <- sum((a1*x1+b1-y1)^2) + sum((a2*x2+b2-y2)^2)
if (ss < ssBest)
{
ssBest <- ss
cBest <- c
a1Best <- a1
a2Best <- a2
b1Best <- b1
b2Best <- b2
}
}
return(list(c=cBest, a1=a1Best, b1=b1Best, a2=a2Best, b2=b2Best,
residuals = c(a1*x1+b1-y1,a2*x2+b2-y2)))
}
pcws3_reg <- function(x, y)
{
C <- length(x)
ssBest = Inf
for (c1 in 2:(C-2))
{
for (c2 in (c1+1):(C-1))
{
x1 <- x[1:c1]
y1 <- y[1:c1]
x2 <- x[c1:c2]
y2 <- y[c1:c2]
x3 <- x[c2:C]
y3 <- y[c2:C]
a1 <- sum((x1-mean(x1))*(y1-mean(y1)))/sum((x1-mean(x1))^2)
b1 <- -a1 * mean(x1) + mean(y1)
a2 <- sum((x2-mean(x2))*(y2-mean(y2)))/sum((x2-mean(x2))^2)
b2 <- -a2 * mean(x2) + mean(y2)
a3 <- sum((x3-mean(x3))*(y3-mean(y3)))/sum((x3-mean(x3))^2)
b3 <- -a3 * mean(x3) + mean(y3)
ss <- sum((a1*x1+b1-y1)^2) + sum((a2*x2+b2-y2)^2) + sum((a3*x3+b3-y3)^2)
if (ss < ssBest)
{
ssBest <- ss
c1Best <- c1
c2Best <- c2
a1Best <- a1
b1Best <- b1
a2Best <- a2
b2Best <- b2
a3Best <- a3
b3Best <- b3
}
}
}
return(list(c1=c1Best, c2=c2Best, a1=a1Best, b1=b1Best,
a2=a2Best, b2=b2Best, a3=a3Best, b3=b3Best,
residuals = c(a1*x1+b1-y1,a2*x2+b2-y2,a3*x3+b3-y3)))
}
print.clustCombi <- function(x, digits = getOption("digits"), ...)
{
cat("\'", class(x)[1], "\' object:\n", sep = "")
cat(paste0(" Mclust model: (",
x$MclustOutput$modelName, ",",
x$MclustOutput$G, ")\n"))
cat(" Available object components: ")
cat(names(x), "\n")
cat(" Combining matrix (K+1 classes -> K classes): <object_name>$combiM[[K]]\n")
cat(" Classification for K classes: <object_name>$classification[[K]]\n")
invisible()
}
summary.clustCombi <- function(object, ...)
{
title <- paste("Combining Gaussian mixture components for clustering")
out <- with(object,
list(title = title,
MclustModelName = object$MclustOutput$modelName,
MclustG = object$MclustOutput$G,
combiM = object$combiM))
class(out) <- "summary.clustCombi"
return(out)
}
print.summary.clustCombi <- function(x, digits = getOption("digits"), ...)
{
cat(rep("-", nchar(x$title)),"\n",sep="")
cat(x$title, "\n")
cat(rep("-", nchar(x$title)),"\n",sep="")
cat("\nMclust model name:", x$MclustModelName, "\n")
cat("Number of components:", x$MclustG, "\n")
cat("\nCombining steps:\n\n")
cat(" Step | Classes combined at this step | Class labels after this step", "\n", sep="")
cat("-------|-------------------------------|-----------------------------", "\n", sep="")
curr <- 1:x$MclustG
cat(" 0 | --- | ", sprintf(fmt = "%d ", curr), "\n", sep="")
for(K in 1:(x$MclustG-1))
{
Kp = x$MclustG - K + 1
l1 = which(!x$combiM[[Kp-1]] %*% rep(1,Kp) == 1)
l2 = (x$combiM[[Kp-1]] %*% curr)[l1] - curr[l1]
nc1 = floor((7-nchar(as.character(K)))/2)
nc2 = (7-nchar(as.character(K))) - nc1
nc3 = floor((33-nchar(paste(as.character(c(l1)), " & ",
as.character(l2))))/2)
nc4 = 33-nchar(paste(as.character(c(l1)), " & ",
as.character(l2))) - nc3
curr <- x$combiM[[Kp-1]] %*% curr -
l2*c(rep(0,(l1-1)),1,rep(0,(Kp-1-l1)))
cat(rep(" ", nc1), as.character(K), rep(" ", nc2), "|",
rep(" ", nc3), as.character(l1), " & ", as.character(l2),
rep(" ", nc4), "| ", sprintf(fmt = "%d ", curr), "\n", sep="")
}
invisible()
}
clustCombiOptim <- function(object, reg = 2, plot = FALSE, ...)
{
z <- object$MclustOutput$z
combiM <- object$combiM
ent <- rep(as.double(NA, nrow(z)))
Kmax <- ncol(z)
z0 <- z
for(K in Kmax:1)
{
z0 <- t(combiM[[K]] %*% t(z0))
ent[K] <- -sum(xlog(z0))
}
if(Kmax == 2)
{
reg <- 1
pcwsreg <- list(K = Kmax)
}
if(reg == 2)
{ pcwsreg <- pcws2_reg(1:Kmax, ent) }
if(reg == 3)
{ pcwsreg <- pcws3_reg(1:Kmax, ent) }
if(plot)
{ plot(1:Kmax, ent,
xlab = "Number of clusters",
ylab = "Entropy",
panel.first = grid(),
xaxt = "n", ...)
axis(side = 1, at = 1:Kmax)
if(reg == 2)
{ lines(1:pcwsreg$c, pcwsreg$a1 * (1:pcwsreg$c) + pcwsreg$b1,
lty = 2, col = "red")
lines(pcwsreg$c:Kmax, pcwsreg$a2 * (pcwsreg$c:Kmax) + pcwsreg$b2,
lty = 2, col = "red") }
if(reg == 3)
{ lines(1:pcwsreg$c1, pcwsreg$a1 * (1:pcwsreg$c1) + pcwsreg$b1,
lty = 2, col = "blue")
lines(pcwsreg$c1:pcwsreg$c2, pcwsreg$a2 * (pcwsreg$c1:pcwsreg$c2) +
pcwsreg$b2, lty = 2, col = "blue")
lines(pcwsreg$c2:Kmax, pcwsreg$a3 * (pcwsreg$c2:Kmax) + pcwsreg$b3,
lty = 2, col = "blue") }
}
K <- pcwsreg[[1]]
z0 <- z
for(K in Kmax:K)
{ z0 <- t(combiM[[K]] %*% t(z0)) }
out <- list(numClusters.combi = K,
z.combi = z0,
cluster.combi = map(z0))
return(out)
} |
run_fmriqa <- function(data_file = NULL, roi_width = 21, slice_num = NULL,
skip = 2, tr = NULL, pix_dim = NULL, poly_det_ord = 3,
spike_detect = FALSE, x_pos = NULL, y_pos = NULL,
plot_title = NULL, last_vol = NULL, gen_png = TRUE,
gen_res_csv = TRUE, gen_pdf = FALSE, gen_spec_csv = FALSE,
png_fname = NULL, res_fname = NULL, pdf_fname = NULL,
spec_fname = NULL, verbose = TRUE, bg_smooth = 12,
bg_shrink = 25) {
if (is.null(data_file)) {
filters <- matrix(c("NIfTI", ".nii.gz", "NIfTI", ".nii",
"All files", "*"),
3, 2, byrow = TRUE)
data_file <- tk_choose.files(caption = "Select nifti data file for analysis",
multi = FALSE, filters = filters)
if (length(data_file) == 0) {
stop("Error : input file not given.")
}
}
basename <- sub(".nii.gz$", "", data_file)
basename <- sub(".nii$", "", basename)
if (is.null(res_fname)) {
csv_file <- paste(basename, "_qa_results.csv", sep = "")
} else {
csv_file <- res_fname
}
if (is.null(png_fname)) {
png_file <- paste(basename, "_qa_plot.png", sep = "")
} else {
png_file <- png_fname
}
if (is.null(pdf_fname)) {
pdf_file <- paste(basename, "_qa_plot.pdf", sep = "")
} else {
pdf_file <- pdf_fname
}
if (is.null(spec_fname)) {
spec_file <- paste(basename, "_qa_spec.csv", sep = "")
} else {
spec_file <- spec_fname
}
image_cols <- viridis(64)
if (verbose) cat(paste("Reading data : ", data_file, "\n\n", sep = ""))
data <- readNifti(data_file)
x_dim <- dim(data)[1]
y_dim <- dim(data)[2]
z_dim <- dim(data)[3]
if (is.null(tr)) tr <- pixdim(data)[4]
if (is.null(pix_dim)) {
x_pix_dim <- pixdim(data)[1]
y_pix_dim <- pixdim(data)[2]
z_pix_dim <- pixdim(data)[3]
} else {
x_pix_dim <- pix_dim[1]
y_pix_dim <- pix_dim[2]
z_pix_dim <- pix_dim[3]
}
if (is.null(slice_num)) slice_num <- ceiling(dim(data)[3] / 2)
if (is.null(last_vol)) {
N <- dim(data)[4]
} else {
N <- last_vol
}
dyns <- N - skip
t <- seq(from = 0, by = tr, length.out = dyns)
if (verbose) {
cat("Basic analysis parameters\n")
cat("-------------------------\n")
cat(paste("X,Y matrix : ", x_dim, "x", y_dim, "\n", sep = ""))
cat(paste("Slices : ", z_dim, "\n", sep = ""))
cat(paste("X,Y,Z pix dims : ", x_pix_dim, "x", y_pix_dim, "x", z_pix_dim, "mm\n", sep = ""))
cat(paste("TR : ", round(tr, 2), "s\n", sep = ""))
cat(paste("Slice
cat(paste("ROI width : ", roi_width, "\n", sep = ""))
cat(paste("Total vols : ", dim(data)[4], "\n", sep = ""))
cat(paste("Analysis vols : ", dyns, "\n", sep = ""))
}
data_raw <- data[,,slice_num, (skip + 1):N]
X <- poly(1:dyns, poly_det_ord)[,]
X <- cbind(1,X)
data_detrend <- apply(data_raw, c(1,2), detrend_fast, X)
data_detrend <- aperm(data_detrend, c(2,3,1))
TFN <- apply(data_detrend, c(1,2), sd)
av_image <- apply(data_raw, c(1,2), mean)
SFNR_full <- av_image / TFN
odd_dynamics <- data_raw[,,c(TRUE, FALSE)]
even_dynamics <- data_raw[,,c(FALSE, TRUE)]
if (length(odd_dynamics) > length(even_dynamics)) {
odd_dynamics <- odd_dynamics[,,-(dim(odd_dynamics)[3])]
warning("Odd number of dynamic scans, removing last one for the odd even diff calculation.")
}
DIFF <- apply(odd_dynamics, c(1, 2), sum) - apply(even_dynamics, c(1, 2), sum)
SFNR_full[is.na(SFNR_full)] <- 0
av_image_cimg <- imager::as.cimg(av_image)
obj_thr <- imager::threshold(av_image_cimg)
cog_image <- obj_thr[,]
mean_obj_inten <- mean(av_image_cimg[obj_thr])
pix_dim <- min(c(x_pix_dim, y_pix_dim))
obj_thr_bg <- imager::grow(obj_thr, round(bg_shrink/pix_dim))
bg <- av_image_cimg
bg[obj_thr_bg] <- 0
bg_blur <- imager::boxblur(bg, round(bg_smooth/pix_dim))
max_bg <- max(bg_blur)
max_bg_perc <- 100 * max_bg / mean_obj_inten
mask <- obj_thr_bg[,,1,1]
bg_dynamics <- data_raw
bg_dynamics[mask] <- NA
mean_bg_image <- apply(bg_dynamics, c(1,2), mean)
bg_sig_intensity_t <- apply(bg_dynamics, 3, mean, na.rm = TRUE)
bg_fit <- bg_sig_intensity_t - detrend_fast(bg_sig_intensity_t, X)
if (is.null(x_pos)) {
x_pos <- sum(array(1:x_dim, c(x_dim, y_dim)) * cog_image) / sum(cog_image)
x_pos <- round(x_pos)
}
if (is.null(y_pos)) {
y_pos <- sum(t(array(1:y_dim, c(y_dim, x_dim))) * cog_image) / sum(cog_image)
y_pos <- round(y_pos)
}
ROI_x <- get_pixel_range(x_pos, roi_width)
ROI_y <- get_pixel_range(y_pos, roi_width)
SFNR <- SFNR_full[ROI_x, ROI_y]
av_SFNR <- mean(SFNR)
DIFF_ROI <- DIFF[ROI_x, ROI_y]
signal_summary_value <- mean(av_image[ROI_x, ROI_y])
SNR <- signal_summary_value / sqrt((sd(DIFF_ROI) ^ 2) / dyns)
slice_data_ROI <- data_raw[ROI_x, ROI_y,]
mean_sig_intensity_t <- apply(slice_data_ROI, 3, mean)
mean_sig_intensity <- mean(mean_sig_intensity_t)
mean_sig_intensity_t_detrend <- detrend_fast(mean_sig_intensity_t, X)
y_fit <- mean_sig_intensity_t - mean_sig_intensity_t_detrend
residuals <- mean_sig_intensity_t - y_fit
sd_roi <- sd(residuals)
percent_fluc <- 100.0 * sd_roi / mean_sig_intensity
percent_drift_fit <- 100.0 * (max(y_fit) - min(y_fit)) / mean_sig_intensity
percent_drift <- 100.0 * (max(mean_sig_intensity_t) -
min(mean_sig_intensity_t)) / mean_sig_intensity
detrend_res <- mean_sig_intensity_t - y_fit
zp <- 4
spec <- Mod(fft(c(detrend_res, rep(0,(zp - 1) * dyns))))[1:(dyns * zp / 2)]
max_spec_outlier <- max(spec) / mad(spec)
t <- seq(from = 0, by = tr, length.out = dyns)
vols <- seq(from = skip + 1, by = 1, length.out = dyns)
freq <- seq(from = 0, to = (1 - 1/(zp * dyns / 2))/(tr * 2),
length.out = zp * dyns / 2)
slice_tc <- apply(data[,,,(skip + 1):N, drop = FALSE], c(3, 4), mean)
X <- poly(1:dyns, poly_det_ord)[,]
X <- cbind(1, X)
slice_tc_dt <- apply(slice_tc, 1, detrend_fast, X)
max_tc_outlier <- max(abs(slice_tc_dt)) / mad(slice_tc_dt)
CV <- vector(length = roi_width)
CV_ideal <- vector(length = roi_width)
for (n in (1:roi_width)) {
x_range <- get_pixel_range(x_pos, n)
y_range <- get_pixel_range(y_pos, n)
slice_data_ROI <- data_raw[x_range, y_range,, drop = F]
mean_sig_intensity_t <- apply(slice_data_ROI, 3, mean)
mean_sig_intensity <- mean(mean_sig_intensity_t)
X <- poly(1:dyns, poly_det_ord)[,]
X <- cbind(1,X)
mean_sig_intensity_t_dt <- detrend_fast(y = mean_sig_intensity_t, X = X)
sd_sig_intensity <- sd(mean_sig_intensity_t_dt)
CV[n] <- 100 * sd_sig_intensity / mean_sig_intensity
CV_ideal[n] <- CV[1] / n
}
RDC <- CV[1] / CV[length(CV)]
line1 <- paste("Mean signal : ", round(mean_sig_intensity, 1), "\n", sep = "")
line2 <- paste("STD : ", round(sd_roi, 2), "\n", sep = "")
line3 <- paste("Percent fluc : ", round(percent_fluc, 2), "\n", sep = "")
line4 <- paste("Drift : ", round(percent_drift, 2), "\n", sep = "")
line5 <- paste("Drift fit : ", round(percent_drift_fit, 2), "\n", sep = "")
line6 <- paste("SNR : ", round(SNR, 1), "\n", sep = "")
line7 <- paste("SFNR : ", round(av_SFNR, 1), "\n", sep = "")
line8 <- paste("RDC : ", round(RDC, 2), "\n", sep = "")
line9 <- paste("TC outlier : ", round(max_tc_outlier, 2), "\n", sep = "")
line10 <- paste("Spec outlier : ", round(max_spec_outlier, 2), "\n", sep = "")
line11 <- paste("MBG percent : ", round(max_bg_perc, 2), "\n", sep = "")
if (verbose) {
cat("\nQA metrics\n")
cat("----------\n")
cat(line1)
cat(line2)
cat(line3)
cat(line4)
cat(line5)
cat(line6)
cat(line7)
cat(line8)
cat(line9)
cat(line10)
cat(line11)
}
if (is.null(plot_title)) plot_title <- NA
results_tab <- data.frame(data_file, title = plot_title,
mean_signal = mean_sig_intensity, std = sd_roi,
percent_fluc = percent_fluc, drift = percent_drift,
drift_fit = percent_drift_fit, snr = SNR,
sfnr = av_SFNR, rdc = RDC, tc_outlier = max_tc_outlier,
spec_outlier = max_spec_outlier, max_bg_perc = max_bg_perc)
if (gen_res_csv) {
write.csv(results_tab, csv_file, row.names = FALSE)
}
if (gen_spec_csv) {
spec_out <- data.frame(t(spec))
colnames(spec_out) <- freq
spec_out <- cbind(data.frame(data_file, title = plot_title), spec_out)
write.csv(spec_out, spec_file, row.names = FALSE)
}
if (gen_pdf | gen_png) {
if (spike_detect) {
cat("\nCalculating k-space spike detection map...\n")
diff_vols <- apply(data[,,,(skip + 1):N, drop = FALSE], c(1,2,3), diff)
diff_vols <- aperm(diff_vols, c(2,3,4,1))
diff_vols_fft <- apply(diff_vols, c(3,4), fft)
dim(diff_vols_fft) <- dim(diff_vols)
max_slice_proj <- apply(abs(diff_vols_fft), c(1,2), max)
max_slice_proj <- apply(apply(max_slice_proj, 1, fftshift), 1,
fftshift)
max_z <- mad(max_slice_proj) * 8 + median(max_slice_proj)
max_slice_proj <- ifelse(max_slice_proj > max_z, max_z, max_slice_proj)
max_slice_proj_plot <- ggplot(melt(max_slice_proj), aes(Var1, Var2, fill = value)) +
geom_raster(interpolate = TRUE) +
scale_fill_gradientn(colours = image_cols) +
coord_fixed(ratio = 1) + labs(x = "",y = "", fill = "Intensity",
title = "Max. proj. of k-space slice differences") +
scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))
}
theme_set(theme_bw())
marg <- theme(plot.margin = unit(c(0.5,0.5,0.5,0.5), "cm"))
raw_text <- paste(line1, line2, line3, line4, line5, line6, line7, line8,
line9, line10, line11, sep = "")
text <- textGrob(raw_text, x = 0.2, just = 0, gp = gpar(fontfamily = "mono", fontsize = 12))
Measured <- NULL
Theoretical <- NULL
group <- NULL
roi_width_vec <- NULL
fit <- NULL
tc <- NULL
Var1 <- NULL
Var2 <- NULL
value <- NULL
rdc_df <- data.frame(roi_width_vec = 1:roi_width, Theoretical = CV_ideal, Measured = CV)
rdc_df <- gather(rdc_df, group, CV, c(Measured, Theoretical))
rdc_plot <- ggplot(rdc_df, aes(x = roi_width_vec, y = CV, colour = group)) + geom_line() +
geom_point() + scale_x_log10(limits = c(1,100)) +
scale_y_log10(limits = c(0.01,10), breaks = c(0.01,0.1,1,10)) +
labs(y = "100*CV", x = "ROI width (pixels)", title = "RDC plot") + marg +
theme(legend.position = c(0.8, 0.8)) + scale_color_manual(values = c("black","red"))
tc_fit <- data.frame(t = vols, tc = mean_sig_intensity_t, fit = y_fit)
tc_plot <- ggplot(tc_fit, aes(t)) + geom_line(aes(y = tc)) +
geom_line(aes(y = fit), color = "red") +
theme(legend.position = "none") +
labs(y = "Intensity (a.u.)", x = "Time (volumes)",
title = "ROI intensity drift plot") + marg
tc_fit_bg <- data.frame(t = vols, tc = bg_sig_intensity_t, fit = bg_fit)
tc_plot_bg <- ggplot(tc_fit_bg, aes(t)) + geom_line(aes(y = tc)) +
geom_line(aes(y = fit), color = "red") +
theme(legend.position = "none") +
labs(y = "Intensity (a.u.)", x = "Time (volumes)",
title = "BG intensity drift plot") + marg
spec_plot <- qplot(freq, spec, xlab = "Frequency (Hz)",
ylab = "Intensity (a.u.)", geom = "line",
main = "Fluctuation spectrum") + marg
x_st = ROI_x[1]
x_end = ROI_x[length(ROI_x)]
y_st = ROI_y[1]
y_end = ROI_y[length(ROI_y)]
lcol <- "white"
roi_a <- geom_segment(aes(x = x_st, xend = x_st, y = y_st, yend = y_end),
colour = lcol)
roi_b <- geom_segment(aes(x = x_end, xend = x_end, y = y_st, yend = y_end),
colour = lcol)
roi_c <- geom_segment(aes(x = x_st, xend = x_end, y = y_st, yend = y_st),
colour = lcol)
roi_d <- geom_segment(aes(x = x_st, xend = x_end, y = y_end, yend = y_end),
colour = lcol)
top_val <- quantile(SFNR_full,0.999)
SFNR_full <- ifelse(SFNR_full > top_val, top_val, SFNR_full)
sfnr_plot <- ggplot(melt(SFNR_full), aes(Var1, Var2, fill = value)) +
geom_raster(interpolate = TRUE) +
scale_fill_gradientn(colours = image_cols) +
coord_fixed(ratio = 1) + labs(x = "", y = "", fill = "Intensity",
title = "SFNR image") +
marg + roi_a + roi_b + roi_c + roi_d +
scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))
bg_plot <- ggplot(melt(mean_bg_image), aes(Var1, Var2, fill = value)) +
geom_raster(interpolate = TRUE) +
scale_fill_gradientn(colours = image_cols, na.value = "white") +
coord_fixed(ratio = 1) + labs(x = "", y = "", fill = "Intensity",
title = "Mean BG image") +
marg + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))
av_plot <- ggplot(melt(av_image), aes(Var1, Var2, fill = value)) +
geom_raster(interpolate = TRUE) +
scale_fill_gradientn(colours = image_cols) +
coord_fixed(ratio = 1) + labs(x = "",y = "", fill = "Intensity",
title = "Mean image") +
marg + roi_a + roi_b + roi_c + roi_d +
scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))
diff_plot <- ggplot(melt(DIFF), aes(Var1, Var2, fill = value)) +
geom_raster(interpolate = TRUE) +
scale_fill_gradientn(colours = image_cols) +
coord_fixed(ratio = 1) + labs(x = "",y = "", fill = "Intensity",
title = "Odd-even difference") +
marg + roi_a + roi_b + roi_c + roi_d +
scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))
tfn_plot <- ggplot(melt(TFN), aes(Var1, Var2, fill = value)) +
geom_raster(interpolate = TRUE) +
scale_fill_gradientn(colours = image_cols) +
coord_fixed(ratio = 1) +
labs(x = "", y = "", fill = "Intensity",
title = "Temporal fluctuation noise") +
marg + roi_a + roi_b + roi_c + roi_d +
scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))
slice_tc_plot <- ggplot(melt(slice_tc_dt), aes(x = Var1 + skip, y = value, group = Var2)) +
geom_line(alpha = 0.5) +
labs(x = "Time (volumes)", y = "Intensity (a.u.)",
title = "Mean slice TCs (detrended)")
if (is.na(plot_title)) {
title <- NULL
} else {
title <- textGrob(plot_title, gp = gpar(fontsize = 25))
}
if (gen_pdf) {
pdf(pdf_file, height = 10, width = 20)
if (spike_detect) {
lay <- rbind(c(1,5,9,11,11),
c(4,10,3,2,2),
c(7,6,12,8,8))
grid.arrange(text, tc_plot, spec_plot, av_plot, diff_plot, sfnr_plot, tfn_plot,
slice_tc_plot, rdc_plot, bg_plot, tc_plot_bg, max_slice_proj_plot,
layout_matrix = lay, top = title)
} else {
lay <- rbind(c(1,5,9,11,11),
c(4,10,3,2,2),
c(7,6,8,8,8))
grid.arrange(text, tc_plot, spec_plot, av_plot, diff_plot, sfnr_plot, tfn_plot,
slice_tc_plot, rdc_plot, bg_plot, tc_plot_bg, layout_matrix = lay,
top = title)
}
graphics.off()
}
if (gen_png) {
png(png_file, height = 800, width = 1500, type = "cairo")
if (spike_detect) {
lay <- rbind(c(1,5,9,11,11),
c(4,10,3,2,2),
c(7,6,12,8,8))
grid.arrange(text, tc_plot, spec_plot, av_plot, diff_plot, sfnr_plot, tfn_plot,
slice_tc_plot, rdc_plot, bg_plot, tc_plot_bg, max_slice_proj_plot,
layout_matrix = lay, top = title)
} else {
lay <- rbind(c(1,5,9,11,11),
c(4,10,3,2,2),
c(7,6,8,8,8))
grid.arrange(text, tc_plot, spec_plot, av_plot, diff_plot, sfnr_plot, tfn_plot,
slice_tc_plot, rdc_plot, bg_plot, tc_plot_bg, layout_matrix = lay,
top = title)
}
graphics.off()
}
}
if (verbose) {
if (gen_pdf) cat(paste("\nPDF report : ", pdf_file, sep = ""))
if (gen_spec_csv) cat(paste("\nCSV spec file : ", spec_file, sep = ""))
if (gen_png) cat(paste("\nPNG report : ", png_file, sep = ""))
if (gen_res_csv) cat(paste("\nCSV results : ", csv_file, "\n\n", sep = ""))
}
results_tab
}
detrend_fast <- function(y, X) {
fastLmPure(y = y, X = X)$residual
}
get_pixel_range <- function(center, width) {
ROI_half_start <- floor(width / 2)
ROI_half_end <- ceiling(width / 2)
start <- floor(center - ROI_half_start)
end <- floor(center + ROI_half_end) - 1
start:end
} |
image_detect_corners <- function(x, threshold = 50L, suppress_non_max = FALSE) {
stopifnot(is.matrix(x))
corners <- detect_corners(as.integer(x),
width=nrow(x),
height=ncol(x),
bytes_per_row = nrow(x),
suppress_non_max = as.logical(suppress_non_max),
threshold = as.integer(threshold))
names(corners) <- c("x", "y")
class(corners) <- "image.corners"
corners
}
print.image.corners <- function(x, ...){
cat("Corner Detector", sep = "\n")
cat(sprintf(" found %s corners", length(x$x)), sep = "\n")
} |
dccspec = function(uspec, VAR = FALSE, robust = FALSE, lag = 1, lag.max = NULL,
lag.criterion = c("AIC", "HQ", "SC", "FPE"), external.regressors = NULL,
robust.control = list("gamma" = 0.25, "delta" = 0.01, "nc" = 10, "ns" = 500),
dccOrder = c(1,1), model = c("DCC", "aDCC", "FDCC"), groups = rep(1, length(uspec@spec)),
distribution = c("mvnorm", "mvt", "mvlaplace"), start.pars = list(), fixed.pars = list())
{
UseMethod("dccspec")
}
.xdccspec = function(uspec, VAR = FALSE, robust = FALSE, lag = 1, lag.max = NULL,
lag.criterion = c("AIC", "HQ", "SC", "FPE"), external.regressors = NULL,
robust.control = list("gamma" = 0.25, "delta" = 0.01, "nc" = 10, "ns" = 500),
dccOrder = c(1,1), model = c("DCC", "aDCC", "FDCC"), groups = rep(1, length(uspec@spec)),
distribution = c("mvnorm", "mvt", "mvlaplace"),
start.pars = list(), fixed.pars = list())
{
if(tolower(model[1]) == "fdcc"){
spec = .fdccspec(uspec = uspec, VAR = VAR, robust = robust, lag = lag,
lag.max = lag.max, lag.criterion = lag.criterion[1],
external.regressors = external.regressors,
robust.control = robust.control, fdccOrder = dccOrder,
fdccindex = groups, distribution = distribution[1],
start.pars = start.pars, fixed.pars = fixed.pars)
} else{
if(tolower(model[1]) == "adcc") asymmetric = TRUE else asymmetric = FALSE
spec = .dccspec(uspec = uspec, VAR = VAR, robust = robust, lag = lag,
lag.max = lag.max, lag.criterion = lag.criterion[1],
external.regressors = external.regressors,
robust.control = robust.control, dccOrder = dccOrder,
asymmetric = asymmetric, distribution = distribution[1],
start.pars = start.pars, fixed.pars = fixed.pars)
}
return(spec)
}
setMethod(f = "dccspec", signature(uspec = "uGARCHmultispec"), definition = .xdccspec)
.setfixeddcc = function(object, value){
model = object@model
umodel = object@umodel
ipars = model$pars
pars = unlist(value)
names(pars) = parnames = tolower(names(pars))
modelnames = rownames(ipars[which(ipars[,4]==1 | ipars[,2]==1), ,drop=FALSE])
inc = NULL
for(i in seq_along(parnames)){
if(is.na(match(parnames[i], modelnames))){
warning( (paste("Unrecognized Parameter in Fixed Values: ", parnames[i], "...Ignored", sep = "")))
} else{
inc = c(inc, i)
}
}
fixed.pars = pars[inc]
names(fixed.pars) = tolower(names(pars[inc]))
mspec = .makemultispec(umodel$modelinc, umodel$modeldesc$vmodel, umodel$modeldesc$vsubmodel,
umodel$modeldata$mexdata, umodel$modeldata$vexdata, umodel$start.pars,
umodel$fixed.pars, umodel$vt)
if(object@model$DCC == "FDCC"){
tmp = dccspec(uspec = mspec, VAR = ifelse(model$modelinc[1]>0, TRUE, FALSE),
robust = ifelse(!is.null(model$varmodel$robust), model$varmodel$robust, FALSE),
lag = model$modelinc[1], lag.max = model$varmodel$lag.max, lag.criterion = model$varmodel$lag.criterion,
external.regressors = if(model$modelinc[2]>0) model$modeldata$mexdata else NULL,
robust.control = if(!is.null(model$varmodel$robust.control)) model$varmodel$robust.control else list(),
dccOrder = model$modelinc[4:5], model="FDCC", groups = model$fdccindex,
distribution = model$modeldesc$distribution,
start.pars = if(is.null(model$start.pars)) model$start.pars else NULL, fixed.pars = as.list(fixed.pars))
} else{
tmp = dccspec(uspec = mspec, VAR = ifelse(model$modelinc[1]>0, TRUE, FALSE),
robust = ifelse(!is.null(model$varmodel$robust), model$varmodel$robust, FALSE),
lag = model$modelinc[1], lag.max = model$varmodel$lag.max, lag.criterion = model$varmodel$lag.criterion,
external.regressors = if(model$modelinc[2]>0) model$modeldata$mexdata else NULL,
robust.control = if(!is.null(model$varmodel$robust.control)) model$varmodel$robust.control else list(),
dccOrder = model$modelinc[3:4], model = ifelse(model$modelinc[5]>0, "aDCC", "DCC"),
distribution = model$modeldesc$distribution,
start.pars = if(is.null(model$start.pars)) model$start.pars else NULL, fixed.pars = as.list(fixed.pars))
}
return(tmp)
}
setReplaceMethod(f="setfixed", signature= c(object = "DCCspec", value = "vector"), definition = .setfixeddcc)
.setstartdcc = function(object, value){
model = object@model
umodel = object@umodel
ipars = model$pars
pars = unlist(value)
names(pars) = parnames = tolower(names(pars))
modelnames = rownames(ipars[which(ipars[,4]==1 | ipars[,2]==1), ,drop=FALSE])
inc = NULL
for(i in seq_along(parnames)){
if(is.na(match(parnames[i], modelnames))){
warning( (paste("Unrecognized Parameter in Start Values: ", parnames[i], "...Ignored", sep = "")))
} else{
inc = c(inc, i)
}
}
start.pars = pars[inc]
names(start.pars) = tolower(names(pars[inc]))
uspec = .makemultispec(umodel$modelinc, umodel$modeldesc$vmodel, umodel$modeldesc$vsubmodel,
umodel$modeldata$mexdata, umodel$modeldata$vexdata, umodel$start.pars,
umodel$fixed.pars, umodel$vt)
if(object@model$DCC == "FDCC"){
tmp = dccspec(uspec, VAR = ifelse(model$modelinc[1]>0, TRUE, FALSE),
robust = ifelse(!is.null(model$varmodel$robust), model$varmodel$robust, FALSE),
lag = model$modelinc[1], lag.max = model$varmodel$lag.max, lag.criterion = model$varmodel$lag.criterion,
external.regressors = if(model$modelinc[2]>0) model$modeldata$mexdata else NULL,
robust.control = if(!is.null(model$varmodel$robust.control)) model$varmodel$robust.control else list(),
dccOrder = model$modelinc[4:5], model="FDCC", groups = model$fdccindex,
distribution = model$modeldesc$distribution,
start.pars = as.list(start.pars), fixed.pars = model$fixed.pars)
} else{
tmp = dccspec(uspec, VAR = ifelse(model$modelinc[1]>0, TRUE, FALSE),
robust = ifelse(!is.null(model$varmodel$robust), model$varmodel$robust, FALSE),
lag = model$modelinc[1], lag.max = model$varmodel$lag.max, lag.criterion = model$varmodel$lag.criterion,
external.regressors = if(model$modelinc[2]>0) model$modeldata$mexdata else NULL,
robust.control = if(!is.null(model$varmodel$robust.control)) model$varmodel$robust.control else list(),
dccOrder = model$modelinc[3:4], model = ifelse(model$modelinc[5]>0, "aDCC", "DCC"),
distribution = model$modeldesc$distribution,
start.pars = as.list(start.pars), fixed.pars = model$fixed.pars)
}
return(tmp)
}
setReplaceMethod(f="setstart", signature= c(object = "DCCspec", value = "vector"), definition = .setstartdcc)
dccfit = function(spec, data, out.sample = 0, solver = "solnp", solver.control = list(),
fit.control = list(eval.se = TRUE, stationarity = TRUE, scale = FALSE),
cluster = NULL, fit = NULL, VAR.fit = NULL, realizedVol = NULL, ...)
{
UseMethod("dccfit")
}
.xdccfit = function(spec, data, out.sample = 0, solver = "solnp", solver.control = list(),
fit.control = list(eval.se = TRUE, stationarity = TRUE, scale = FALSE),
cluster = NULL, fit = NULL, VAR.fit = NULL, realizedVol = NULL, ...)
{
if(spec@model$DCC == "FDCC"){
ans = .fdccfit(spec = spec, data = data, out.sample = out.sample,
solver = solver, solver.control = solver.control,
fit.control = fit.control, cluster = cluster, fit = fit,
VAR.fit = VAR.fit, realizedVol = realizedVol, ...)
} else{
ans = .dccfit(spec = spec, data = data, out.sample = out.sample,
solver = solver, solver.control = solver.control,
fit.control = fit.control, cluster = cluster, fit = fit,
VAR.fit = VAR.fit, realizedVol = realizedVol, ...)
}
return(ans)
}
setMethod("dccfit", signature(spec = "DCCspec"), .xdccfit)
dccfilter = function(spec, data, out.sample = 0, filter.control = list(n.old = NULL),
cluster = NULL, varcoef = NULL, realizedVol = NULL, ...)
{
UseMethod("dccfilter")
}
.xdccfilter = function(spec, data, out.sample = 0, filter.control = list(n.old = NULL),
cluster = NULL, varcoef = NULL, realizedVol = NULL, ...)
{
if(spec@model$DCC == "FDCC"){
ans = .fdccfilter(spec = spec, data = data, out.sample = out.sample,
filter.control = filter.control, cluster = cluster, varcoef = varcoef,
realizedVol = realizedVol,...)
} else{
ans = .dccfilter(spec = spec, data = data, out.sample = out.sample,
filter.control = filter.control, cluster = cluster, varcoef = varcoef,
realizedVol = realizedVol,...)
}
return(ans)
}
setMethod("dccfilter", signature(spec = "DCCspec"), .xdccfilter)
dccforecast = function(fit, n.ahead = 1, n.roll = 0,
external.forecasts = list(mregfor = NULL, vregfor = NULL), cluster = NULL, ...)
{
UseMethod("dccforecast")
}
.xdccforecast = function(fit, n.ahead = 1, n.roll = 0,
external.forecasts = list(mregfor = NULL, vregfor = NULL), cluster = NULL, ...)
{
if(fit@model$DCC == "FDCC"){
ans = .fdccforecast(fit, n.ahead = n.ahead, n.roll = n.roll,
external.forecasts = external.forecasts, cluster = cluster, ...)
} else{
ans = .dccforecast(fit, n.ahead = n.ahead, n.roll = n.roll,
external.forecasts = external.forecasts, cluster = cluster, ...)
}
return(ans)
}
setMethod("dccforecast", signature(fit = "DCCfit"), .xdccforecast)
dccroll = function(spec, data, n.ahead = 1, forecast.length = 50, refit.every = 25,
n.start = NULL, refit.window = c("recursive", "moving"), window.size = NULL,
solver = "solnp", solver.control = list(),
fit.control = list(eval.se = TRUE, stationarity = TRUE, scale = FALSE),
cluster = NULL, save.fit = FALSE, save.wdir = NULL,
realizedVol = NULL, clusterOnAssets=FALSE, ...)
{
UseMethod("dccroll")
}
.xdccroll = function(spec, data, n.ahead = 1, forecast.length = 50, refit.every = 25,
n.start = NULL, refit.window = c("recursive", "moving"), window.size = NULL,
solver = "solnp", solver.control = list(),
fit.control = list(eval.se = TRUE, stationarity = TRUE, scale = FALSE),
cluster = NULL, save.fit = FALSE, save.wdir = NULL,
realizedVol = NULL, clusterOnAssets=FALSE, ...)
{
if(!is.null(cluster)){
if(clusterOnAssets){
out=.rolldcc.assets(spec=spec, data=data, n.ahead = n.ahead, forecast.length = forecast.length,
refit.every = refit.every, n.start = n.start, refit.window = refit.window[1],
window.size = window.size, solver = solver, solver.control = solver.control,
fit.control = fit.control, cluster = cluster, save.fit = save.fit, save.wdir = save.wdir,
realizedVol = realizedVol,...)
} else{
out=.rolldcc.windows(spec=spec, data=data, n.ahead = n.ahead, forecast.length = forecast.length,
refit.every = refit.every, n.start = n.start, refit.window = refit.window[1],
window.size = window.size, solver = solver, solver.control = solver.control,
fit.control = fit.control, cluster = cluster, save.fit = save.fit, save.wdir = save.wdir,
realizedVol = realizedVol,...)
}
} else{
out=.rolldcc.assets(spec=spec, data=data, n.ahead = n.ahead, forecast.length = forecast.length,
refit.every = refit.every, n.start = n.start, refit.window = refit.window[1],
window.size = window.size, solver = solver, solver.control = solver.control,
fit.control = fit.control, cluster = cluster, save.fit = save.fit, save.wdir = save.wdir,
realizedVol = realizedVol,...)
}
return(out)
}
setMethod("dccroll", signature(spec = "DCCspec"), .xdccroll)
dccsim = function(fitORspec, n.sim = 1000, n.start = 0, m.sim = 1,
startMethod = c("unconditional", "sample"), presigma = NULL,
preresiduals = NULL, prereturns = NULL, preQ = NULL, preZ = NULL,
Qbar = NULL, Nbar = NULL, rseed = NULL, mexsimdata = NULL,
vexsimdata = NULL, cluster = NULL, VAR.fit = NULL,
prerealized = NULL, ...)
{
UseMethod("dccsim")
}
.xdccsim.fit = function(fitORspec, n.sim = 1000, n.start = 0, m.sim = 1,
startMethod = c("unconditional", "sample"), presigma = NULL,
preresiduals = NULL, prereturns = NULL, preQ = NULL, preZ = NULL,
Qbar = NULL, Nbar = NULL, rseed = NULL, mexsimdata = NULL,
vexsimdata = NULL, cluster = NULL, VAR.fit = NULL, prerealized = NULL, ...)
{
if(fitORspec@model$DCC == "FDCC"){
ans = .fdccsim.fit(fitORspec = fitORspec, n.sim = n.sim, n.start = n.start,
m.sim = m.sim, startMethod = startMethod, presigma = presigma,
preresiduals = preresiduals, prereturns = prereturns,
preQ = preQ, preZ = preZ, Qbar = Qbar, rseed = rseed,
mexsimdata = mexsimdata, vexsimdata = vexsimdata,
cluster = cluster, prerealized = prerealized, ...)
} else{
ans = .dccsim.fit(fitORspec = fitORspec, n.sim = n.sim, n.start = n.start,
m.sim = m.sim, startMethod = startMethod, presigma = presigma,
preresiduals = preresiduals, prereturns = prereturns,
preQ = preQ, preZ = preZ, Qbar = Qbar, Nbar = Nbar,
rseed = rseed, mexsimdata = mexsimdata, vexsimdata = vexsimdata,
cluster = cluster, prerealized = prerealized, ...)
}
return(ans)
}
.xdccsim.spec = function(fitORspec, n.sim = 1000, n.start = 0, m.sim = 1,
startMethod = c("unconditional", "sample"), presigma = NULL,
preresiduals = NULL, prereturns = NULL, preQ = NULL, preZ = NULL,
Qbar = NULL, Nbar = NULL, rseed = NULL, mexsimdata = NULL,
vexsimdata = NULL, cluster = NULL, VAR.fit = NULL,
prerealized = NULL, ...)
{
if(fitORspec@model$DCC == "FDCC"){
ans = .fdccsim.spec(fitORspec = fitORspec, n.sim = n.sim, n.start = n.start,
m.sim = m.sim, startMethod = startMethod, presigma = presigma,
preresiduals = preresiduals, prereturns = prereturns,
preQ = preQ, preZ = preZ, Qbar = Qbar, rseed = rseed,
mexsimdata = mexsimdata, vexsimdata = vexsimdata,
cluster = cluster, VAR.fit = VAR.fit, prerealized = prerealized, ...)
} else{
ans = .dccsim.spec(fitORspec = fitORspec, n.sim = n.sim, n.start = n.start,
m.sim = m.sim, startMethod = startMethod, presigma = presigma,
preresiduals = preresiduals, prereturns = prereturns,
preQ = preQ, preZ = preZ, Qbar = Qbar, Nbar = Nbar,
rseed = rseed, mexsimdata = mexsimdata, vexsimdata = vexsimdata,
cluster = cluster, VAR.fit = VAR.fit, prerealized = prerealized, ...)
}
return(ans)
}
setMethod("dccsim", signature(fitORspec = "DCCfit"), .xdccsim.fit)
setMethod("dccsim", signature(fitORspec = "DCCspec"), .xdccsim.spec)
.fitted.dccfit = function(object)
{
T = object@model$modeldata$T
D = object@model$modeldata$index
ans = xts(object@model$mu[1:T,], D[1:T])
colnames(ans) = object@model$modeldata$asset.names
return( ans )
}
setMethod("fitted", signature(object = "DCCfit"), .fitted.dccfit)
setMethod("fitted", signature(object = "DCCfilter"), .fitted.dccfit)
.fitted.dccforecast = function(object)
{
T = object@model$modeldata$T
m = NCOL(object@model$modeldata$data)
n.roll = object@model$n.roll
n.ahead = object@model$n.ahead
T0 = object@model$modeldata$index[T:(T+n.roll)]
ans = array(object@mforecast$mu, dim = c(n.ahead, m, n.roll+1),
dimnames = list(paste("T+", 1:n.ahead,sep=""), object@model$modeldata$asset.names, as.character(T0)))
return( ans )
}
setMethod("fitted", signature(object = "DCCforecast"), .fitted.dccforecast)
.fitted.dccsim = function(object, sim = 1)
{
n = length(object@msim$simR)
m.sim = as.integer(sim)
if( m.sim > n | m.sim < 1 ) stop("\rmgarch-->error: fitted (simulation) sim index out of bounds!")
ans = object@msim$simX[[m.sim]]
rownames(sim) = NULL
colnames(ans) = object@model$modeldata$asset.names
return( ans )
}
setMethod("fitted", signature(object = "DCCsim"), .fitted.dccsim)
.fitted.dccroll = function(object)
{
n = length(object@mforecast)
index = object@model$index
m = NCOL(object@model$data)
D = index[(object@model$n.start+1):(object@model$n.start+object@model$forecast.length)]
M = matrix(unlist(sapply(object@mforecast, function(x) fitted(x))), ncol = m, byrow = TRUE)
M = xts(M, D)
colnames(M) = object@model$modeldata$asset.names
return( M )
}
setMethod("fitted", signature(object = "DCCroll"), .fitted.dccroll)
.residuals.dccfit = function(object)
{
T = object@model$modeldata$T
D = object@model$modeldata$index
ans = xts(object@model$residuals[1:T,], D[1:T])
colnames(ans) = object@model$modeldata$asset.names
return( ans )
}
setMethod("residuals", signature(object = "DCCfit"), .residuals.dccfit)
setMethod("residuals", signature(object = "DCCfilter"), .residuals.dccfit)
.rcor.dccfit = function(object, type = "R", output=c("array","matrix"))
{
T = object@model$modeldata$T
D = object@model$modeldata$index
nam = object@model$modeldata$asset.names
if( type == "R"){
if(class(object)[1]=="DCCfit") tmp = object@mfit$R else tmp = object@mfilter$R
m = dim(tmp[[1]])[2]
R = array(NA, dim = c(m, m, T))
R[1:m,1:m, ] = sapply(tmp[1:T], FUN = function(x) x)
dimnames(R)<-list(nam, nam, as.character(D[1:T]))
if(output[1]=="matrix"){
R = array2matrix(R, date=as.Date(D[1:T]), var.names=nam, diag=FALSE)
}
return( R )
} else{
if(class(object)[1]=="DCCfit") tmp = object@mfit$Q else tmp = object@mfilter$Q
m = dim(tmp[[1]])[2]
Q = array(NA, dim = c(m, m, T))
Q[1:m,1:m, ] = sapply(tmp[1:T], FUN = function(x) x)
dimnames(Q)<-list(nam, nam, as.character(D[1:T]))
if(output[1]=="matrix"){
Q = array2matrix(Q, date=as.Date(D[1:T]), var.names=nam, diag=FALSE)
}
return( Q )
}
}
setMethod("rcor", signature(object = "DCCfit"), .rcor.dccfit)
setMethod("rcor", signature(object = "DCCfilter"), .rcor.dccfit)
.rcor.dccforecast = function(object, type = "R", output=c("array","matrix"))
{
n.roll = object@model$n.roll
n.ahead = object@model$n.ahead
T = object@model$modeldata$T
D = as.character(object@model$modeldata$index[T:(T+n.roll)])
nam = object@model$modeldata$asset.names
if( type == "R"){
tmp = object@mforecast$R
} else{
tmp = object@mforecast$Q
}
for(i in 1:(n.roll+1)){ dimnames(tmp[[i]]) = list(nam, nam, paste("T+",1:n.ahead,sep="")) }
names(tmp) = D
if(output[1]=="matrix"){
for(i in 1:(n.roll+1)) tmp[[i]] = array2matrix(tmp[[i]], date=paste("T+",1:n.ahead,sep=""), var.names=nam, diag=FALSE)
}
return( tmp )
}
setMethod("rcor", signature(object = "DCCforecast"), .rcor.dccforecast)
.rcor.dccsim = function(object, type = "R", sim = 1, output=c("array","matrix"))
{
n = object@model$m.sim
m.sim = as.integer(sim)
nam = object@model$modeldata$asset.names
n.sim = object@model$n.sim
if( m.sim > n | m.sim < 1 ) stop("\rmgarch-->error: rcor sim index out of bounds!")
if( type == "R"){
tmp = object@msim$simR[[m.sim]]
} else{
tmp = object@msim$simQ[[m.sim]]
}
dimnames(tmp) = list(nam, nam, 1:n.sim)
if(output[1]=="matrix"){
tmp = array2matrix(tmp, date=as.character(1:n.sim), var.names=nam, diag=FALSE)
}
return( tmp )
}
setMethod("rcor", signature(object = "DCCsim"), .rcor.dccsim)
.rcor.dccroll = function(object, type = "R", output=c("array","matrix"))
{
n = length(object@mforecast)
index = object@model$index
m = NCOL(object@model$data)
fl = object@model$forecast.length
nam = object@model$modeldata$asset.names
D = index[(object@model$n.start+1):(object@model$n.start+fl)]
Cf = array(unlist(sapply(object@mforecast, function(x) unlist(rcor(x, type=type)))), dim=c(m,m,fl),
dimnames = list(nam, nam, as.character(D)))
if(output[1]=="matrix"){
Cf = array2matrix(Cf, date=as.Date(D), var.names=nam, diag=FALSE)
}
return( Cf )
}
setMethod("rcor", signature(object = "DCCroll"), .rcor.dccroll)
.rcov.dccfit = function(object, output=c("array","matrix"))
{
T = object@model$modeldata$T
D = object@model$modeldata$index
nam = object@model$modeldata$asset.names
if(class(object)[1]=="DCCfit") H = object@mfit$H[,,1:T] else H = object@mfilter$H[,,1:T]
dimnames(H)<-list(nam, nam, as.character(D[1:T]))
if(output[1]=="matrix"){
H = array2matrix(H, date=as.Date(D[1:T]), var.names=nam, diag=TRUE)
}
return( H )
}
setMethod("rcov", signature(object = "DCCfit"), .rcov.dccfit)
setMethod("rcov", signature(object = "DCCfilter"), .rcov.dccfit)
.rcov.dccforecast = function(object, output=c("array","matrix"))
{
n.roll = object@model$n.roll
n.ahead = object@model$n.ahead
T = object@model$modeldata$T
D = as.character(object@model$modeldata$index[T:(T+n.roll)])
nam = object@model$modeldata$asset.names
H = object@mforecast$H
for(i in 1:(n.roll+1)){ dimnames(H[[i]]) = list(nam, nam, paste("T+",1:n.ahead,sep="")) }
names(H) = D
if(output[1]=="matrix"){
for(i in 1:(n.roll+1)) H[[i]] = array2matrix(H[[i]], date=paste("T+",1:n.ahead,sep=""), var.names=nam, diag=TRUE)
}
return( H )
}
setMethod("rcov", signature(object = "DCCforecast"), .rcov.dccforecast)
.rcov.dccsim = function(object, sim = 1, output=c("array","matrix"))
{
n = object@model$m.sim
nam = object@model$modeldata$asset.names
n.sim = object@model$n.sim
m.sim = as.integer(sim)
if( m.sim > n | m.sim < 1 ) stop("\rmgarch-->error: rcov sim index out of bounds!")
tmp = object@msim$simH[[m.sim]]
dimnames(tmp) = list(nam, nam, 1:n.sim)
if(output[1]=="matrix"){
tmp = array2matrix(tmp, date=as.character(1:n.sim), var.names=nam, diag=TRUE)
}
return( tmp )
}
setMethod("rcov", signature(object = "DCCsim"), .rcov.dccsim)
.rcov.dccroll = function(object, output=c("array","matrix"))
{
n = length(object@mforecast)
index = object@model$index
m = NCOL(object@model$data)
fl = object@model$forecast.length
nam = object@model$modeldata$asset.names
D = index[(object@model$n.start+1):(object@model$n.start+fl)]
Cf = array(unlist(sapply(object@mforecast, function(x) unlist(rcov(x)))), dim=c(m,m,fl),
dimnames = list(nam, nam, as.character(D)))
if(output[1]=="matrix"){
Cf = array2matrix(Cf, date=as.character(D), var.names=nam, diag=TRUE)
}
return( Cf )
}
setMethod("rcov", signature(object = "DCCroll"), .rcov.dccroll)
.sigma.dccfit = function(object)
{
T = object@model$modeldata$T
D = object@model$modeldata$index
nam = object@model$modeldata$asset.names
if(class(object)[1] == "DCCfit"){
H = object@mfit$H[,,1:T,drop=FALSE]
m = dim(H)[2]
sig = sqrt(.Call("ArrayDiag", H, c(m,m,T), PACKAGE="rmgarch"))
} else{
H = object@mfilter$H[,,1:T,drop=FALSE]
m = dim(H)[2]
sig = sqrt(.Call("ArrayDiag", H, c(m,m,T), PACKAGE="rmgarch"))
}
colnames(sig) = nam
sig = xts(sig, D[1:T])
return( sig )
}
setMethod("sigma", signature(object = "DCCfit"), .sigma.dccfit)
setMethod("sigma", signature(object = "DCCfilter"), .sigma.dccfit)
.sigma.dccforecast = function(object)
{
T = object@model$modeldata$T
D = object@model$modeldata$index
n.ahead = object@model$n.ahead
nam = object@model$modeldata$asset.names
n.roll = object@model$n.roll
m = dim(object@model$mpars)[2]-1
sig = array(NA, dim = c(n.ahead, m, n.roll+1))
for(i in 1:(n.roll+1)){
sig[,,i] = sqrt(.Call("ArrayDiag", object@mforecast$H[[i]], c(m,m,n.ahead), PACKAGE="rmgarch"))
}
dimnames(sig) = list(paste("T+",1:n.ahead,sep=""), nam, as.character(D[T:(T+n.roll)]))
return( sig )
}
setMethod("sigma", signature(object = "DCCforecast"), .sigma.dccforecast)
.sigma.dccsim = function(object, sim = 1)
{
H = rcov(object, sim = sim)
m = dim(H)[1]
n = dim(H)[3]
nam = object@model$modeldata$asset.names
sig = sapply(1:m, FUN = function(i) sqrt(H[i,i, ]))
colnames(sig) = nam
rownames(sig) = NULL
return( sig )
}
setMethod("sigma", signature(object = "DCCsim"), .sigma.dccsim)
.sigma.dccroll = function(object)
{
n = length(object@mforecast)
index = object@model$index
m = NCOL(object@model$data)
D = index[(object@model$n.start+1):(object@model$n.start+object@model$forecast.length)]
S = matrix(unlist(sapply(object@mforecast, function(x) sigma(x))), ncol = m, byrow = TRUE)
S = xts(S, D)
colnames(S) = object@model$modeldata$asset.names
return( S )
}
setMethod("sigma", signature(object = "DCCroll"), .sigma.dccroll)
rskew = function(object, ...)
{
UseMethod("rskew")
}
.skew.dccfit = function(object)
{
sk = NA
if( object@model$modelinc[7]>0 ){
cf = object@model$mpars[,dim(object@model$mpars)[2]]
nx = which( substr(names(cf), 1, 5) == "mskew" )
sk = cf[nx]
}
return( sk )
}
setMethod("rskew", signature(object = "DCCfit"), .skew.dccfit)
setMethod("rskew", signature(object = "DCCfilter"), .skew.dccfit)
setMethod("rskew", signature(object = "DCCforecast"), .skew.dccfit)
.skew.dccroll = function(object)
{
m = dim(object@model$modeldata$data)[1]
n = length(object@mforecast)
sk = rep(NA, n)
if( object@model$modelinc[7]>0 ){
sk = sapply(object@model$rollcoef, FUN = function(x) x["mskew",m+1])
colnames(sk) = paste("roll-", 1:n, sep = "")
}
return( sk )
}
setMethod("rskew", signature(object = "DCCroll"), .skew.dccroll)
rshape = function(object, ...)
{
UseMethod("rshape")
}
.shape.dccfit = function(object)
{
sh = NA
if( object@model$modelinc[6]>0 ){
cf = object@model$mpars[,dim(object@model$mpars)[2]]
nx = which( substr(names(cf), 1, 6) == "mshape" )
sh = cf[nx]
}
return( sh )
}
setMethod("rshape", signature(object = "DCCfit"), .shape.dccfit)
setMethod("rshape", signature(object = "DCCfilter"), .shape.dccfit)
setMethod("rshape", signature(object = "DCCforecast"), .shape.dccfit)
.shape.dccroll = function(object)
{
m = dim(object@model$modeldata$data)[1]
n = length(object@mforecast)
sh = rep(NA, n)
if( object@model$modelinc[6]>0 ){
sh = sapply(object@model$rollcoef, FUN = function(x) x["mshape",m+1])
colnames(sh) = paste("roll-", 1:n, sep = "")
}
return( sh )
}
setMethod("rshape", signature(object = "DCCroll"), .shape.dccroll)
.coef.dccfit = function(object, type = "all")
{
mpars = object@model$mpars
m = dim(mpars)[2]-1
if( type == "all" ){
if(class(object)[1]=="DCCfit") cf = object@mfit$coef else cf = object@mfilter$coef
} else if( type == "dcc"){
cf = object@model$mpars[which(object@model$eidx[,m+1]==1), m+1]
if(class(object)[1]=="DCCfit"){
names(cf) = object@mfit$dccnames
} else{
names(cf) = object@mfilter$dccnames
}
} else{
cf = object@model$mpars[which(object@model$eidx[,1:m]==1)]
if(class(object)[1]=="DCCfit"){
names(cf) = object@mfit$garchnames
} else{
names(cf) = object@mfilter$garchnames
}
}
return( cf )
}
setMethod("coef", signature(object = "DCCfit"), .coef.dccfit)
setMethod("coef", signature(object = "DCCfilter"), .coef.dccfit)
.coef.dccroll = function(object)
{
model = object@model
cnames = object@model$modeldata$asset.names
m = dim(model$umodel$modelinc)[2]
allnames = NULL
midx = .fullinc(model$modelinc, model$umodel)
for(i in 1:m){
allnames = c(allnames, paste("[",cnames[i],"].", rownames(midx[midx[,i]==1,i, drop = FALSE]), sep = ""))
}
garchnames = allnames
dccnames = rownames(midx[midx[,m+1]==1,m+1, drop = FALSE])
allnames = c(garchnames, paste("[Joint]", rownames(midx[midx[,m+1]==1,m+1, drop = FALSE]), sep = ""))
n = length(object@mforecast)
rollmat = matrix(NA, ncol = n, nrow = length(allnames))
for(i in 1:n){
rollmat[,i] = model$rollcoef[[i]][midx==1]
}
colnames(rollmat) = paste("roll-", 1:n, sep = "")
rownames(rollmat) = allnames
return( rollmat )
}
setMethod("coef", signature(object = "DCCroll"), .coef.dccroll)
.likelihood.dccfit = function(object)
{
switch(class(object)[1],
DCCfit = object@mfit$llh,
DCCfilter = object@mfilter$llh,
DCCroll = {
n = length(object@mforecast)
cf = sapply( object@model$rolllik, FUN = function(x) x )
names(cf) = paste("roll-", 1:n, sep = "")
return(cf)
})
}
setMethod("likelihood", signature(object = "DCCfit"), .likelihood.dccfit)
setMethod("likelihood", signature(object = "DCCfilter"), .likelihood.dccfit)
setMethod("likelihood", signature(object = "DCCroll"), .likelihood.dccfit)
.dccinfocriteria.fit = function(object)
{
n = object@model$modeldata$T
m = NCOL(object@model$modeldata$data)
if(object@model$modelinc[1]>0){
npvar = dim(object@model$varcoef)[1] * dim(object@model$varcoef)[2]
} else{
npvar = 0
}
estpars = NROW(object@mfit$matcoef)
np = npvar + estpars + ( (m^2 - m)/2 )
itest = rugarch:::.information.test(likelihood(object), nObs = n, nPars = np)
itestm = matrix(0, ncol = 1, nrow = 4)
itestm[1,1] = itest$AIC
itestm[2,1] = itest$BIC
itestm[3,1] = itest$SIC
itestm[4,1] = itest$HQIC
colnames(itestm) = ""
rownames(itestm) = c("Akaike", "Bayes", "Shibata", "Hannan-Quinn")
return(itestm)
}
setMethod("infocriteria", signature(object = "DCCfit"), .dccinfocriteria.fit)
dcc.symcheck = function(x, m, d = rep(1, m), tol = 1e-12)
{
n1 = dim(x)[1]
n2 = dim(x)[2]
if( n1 != n2 ) stop("\nmatrix not square!")
if( n1 != m ) stop("\nmatrix not of expected dimension!")
if( max(abs(x - t(x))) > tol ) stop("\nmatrix is not symmetric!")
if( !is.null( d ) ){
if( any( diag(x) != d ) ) stop("\nwrong values on diagonal of matrix!")
}
return( 0 )
}
setMethod("show",
signature(object = "DCCspec"),
function(object){
m = dim(object@umodel$modelinc)[2]
dccpars = sum(object@model$modelinc[3:7])
garchpars = sum( object@umodel$modelinc[1:18,] )
varpars = object@model$modelinc[1]*(m*m + m + object@model$modelinc[2])
cat(paste("\n*------------------------------*", sep = ""))
cat(paste("\n* DCC GARCH Spec *", sep = ""))
cat(paste("\n*------------------------------*", sep = ""))
if(object@model$DCC=="FDCC"){
cat("\nModel : ", paste(object@model$DCC, "(", object@model$modelinc[4], ",", object@model$modelinc[5],")", sep=""))
cat("\nNo.Groups : ", object@model$modelinc[3])
} else{
cat("\nModel : ", paste(object@model$DCC, "(", object@model$modelinc[3], ",", object@model$modelinc[4],")", sep=""))
}
cat("\nEstimation : ", object@model$modeldesc$type)
cat("\nDistribution : ", object@model$modeldesc$distribution)
cat("\nNo. Parameters : ", dccpars + garchpars + varpars + ( (m^2 - m)/2 ))
cat("\nNo. Series : ", m)
cat("\n\n")
invisible(object)
})
setMethod("show",
signature(object = "DCCfit"),
function(object){
m = dim(object@model$modeldata$data)[2]
T = object@model$modeldata$T
cat(paste("\n*---------------------------------*", sep = ""))
cat(paste("\n* DCC GARCH Fit *", sep = ""))
cat(paste("\n*---------------------------------*", sep = ""))
cat("\n\nDistribution : ", object@model$modeldesc$distribution)
if(object@model$DCC=="FDCC"){
cat("\nModel : ", paste(object@model$DCC, "(", object@model$modelinc[4], ",", object@model$modelinc[5],")", sep=""))
cat("\nNo.Groups : ", object@model$modelinc[3])
} else{
cat("\nModel : ", paste(object@model$DCC, "(", object@model$modelinc[3], ",", object@model$modelinc[4],")", sep=""))
}
if(object@model$modelinc[1]>0){
npvar = dim(object@model$varcoef)[1] * dim(object@model$varcoef)[2]
} else{
npvar = 0
}
NP = paste("[",npvar, "+", length(object@mfit$garchnames),"+",length(object@mfit$dccnames), "+",(m^2 - m)/2,"]", sep="")
cat("\nNo. Parameters : ", npvar+NROW(object@mfit$matcoef) + ( (m^2 - m)/2 ))
cat("\n[VAR GARCH DCC UncQ] :", NP)
cat("\nNo. Series : ", m)
cat("\nNo. Obs. : ", T)
cat("\nLog-Likelihood : ", object@mfit$llh)
cat("\nAv.Log-Likelihood : ", round(object@mfit$llh/T, 2), "\n")
cat("\nOptimal Parameters")
cat(paste("\n-----------------------------------\n", sep = ""))
print(round(object@mfit$matcoef,6), digits = 5)
itest = rugarch:::.information.test(object@mfit$llh, nObs = T, nPars = npvar + (m^2 - m)/2 + length(object@mfit$matcoef[,1]))
itestm = matrix(0, ncol = 1, nrow = 4)
itestm[1,1] = itest$AIC
itestm[2,1] = itest$BIC
itestm[3,1] = itest$SIC
itestm[4,1] = itest$HQIC
colnames(itestm) = ""
rownames(itestm) = c("Akaike", "Bayes", "Shibata", "Hannan-Quinn")
cat("\nInformation Criteria")
cat(paste("\n---------------------\n", sep = ""))
print(itestm,digits=5)
cat("\n")
cat("\nElapsed time :", object@mfit$timer,"\n\n")
invisible(object)
})
setMethod("show",
signature(object = "DCCfilter"),
function(object){
m = dim(object@model$modeldata$data)[2]
T = object@model$modeldata$T
cat(paste("\n*------------------------------------*", sep = ""))
cat(paste("\n* DCC GARCH Filter *", sep = ""))
cat(paste("\n*------------------------------------*", sep = ""))
cat("\n\nDistribution : ", object@model$modeldesc$distribution)
if(object@model$DCC=="FDCC"){
cat("\nModel : ", paste(object@model$DCC, "(", object@model$modelinc[4], ",", object@model$modelinc[5],")", sep=""))
cat("\nNo.Groups : ", object@model$modelinc[3])
} else{
cat("\nModel : ", paste(object@model$DCC, "(", object@model$modelinc[3], ",", object@model$modelinc[4],")", sep=""))
}
if(object@model$modelinc[1]>0){
npvar = dim(object@model$varcoef)[1] * dim(object@model$varcoef)[2]
} else{
npvar = 0
}
NP = paste("[",npvar, "+", length(object@mfilter$garchnames),"+",length(object@mfilter$dccnames), "+",(m^2 - m)/2,"]", sep="")
cat("\nNo. of Parameters : ", length(object@mfilter$matcoef[,1]) + ( (m^2 - m)/2 ))
cat("\n[VAR GARCH DCC UncQ] :", NP)
cat("\nNo. of Series : ", m)
cat("\nNo. of Obs. : ", T)
cat("\nLog-Likelihood : ", object@mfilter$llh)
cat("\nAv.Log-Likelihood : ", round(object@mfilter$llh/T, 2), "\n")
cat("\nParameters")
cat(paste("\n--------------------------------------\n", sep = ""))
print(round(object@mfilter$matcoef[,1,drop=FALSE],6), digits = 5)
cat("\n")
cat("\nElapsed time :", object@mfilter$timer,"\n\n")
invisible(object)
})
setMethod("show",
signature(object = "DCCforecast"),
function(object){
cat(paste("\n*---------------------------------*", sep = ""))
cat(paste("\n* DCC GARCH Forecast *", sep = ""))
cat(paste("\n*---------------------------------*", sep = ""))
cat("\n\nDistribution : ", object@model$modeldesc$distribution)
if(object@model$DCC=="FDCC"){
cat("\nModel : ", paste(object@model$DCC, "(", object@model$modelinc[4], ",", object@model$modelinc[5],")", sep=""))
cat("\nNo.Groups : ", object@model$modelinc[3])
} else{
cat("\nModel : ", paste(object@model$DCC, "(", object@model$modelinc[3], ",", object@model$modelinc[4],")", sep=""))
}
n.ahead = object@model$n.ahead
cat("\nHorizon : ", n.ahead)
cat("\nRoll Steps : ", object@model$n.roll)
cat("\n-----------------------------------")
cat("\n\n0-roll forecast: \n")
forc = object@mforecast$R[[1]]
if( dim(forc)[3] > 5 ){
cat("\nFirst 2 Correlation Forecasts\n")
print(forc[, , 1:2], digits = 4)
cat(paste(rep(".", dim(forc[,,1])[1], collapse = TRUE)))
cat("\n")
cat(paste(rep(".", dim(forc[,,1])[1], collapse = TRUE)))
cat("\n")
cat("\nLast 2 Correlation Forecasts\n")
print(last(forc, 2), digits = 4)
} else{
print(forc, digits = 4)
}
cat("\n\n")
invisible(object)
})
setMethod("show",
signature(object = "DCCsim"),
function(object){
cat(paste("\n*---------------------------------*", sep = ""))
cat(paste("\n* DCC GARCH Simulation *", sep = ""))
cat(paste("\n*---------------------------------*", sep = ""))
cat("\n\nDistribution\t\t:", object@msim$model$distribution)
if(object@model$DCC=="FDCC"){
cat("\nModel\t\t: ", paste(object@model$DCC, "(", object@model$modelinc[4], ",", object@model$modelinc[5],")", sep=""))
cat("\nNo.Groups\t: ", object@model$modelinc[3])
} else{
cat("\nModel\t\t: ", paste(object@model$DCC, "(", object@model$modelinc[3], ",", object@model$modelinc[4],")", sep=""))
}
cat(paste("\nSimulation Horizon\t: ", object@msim$model$n.sim, sep = ""))
cat(paste("\nBurn In\t\t\t\t: ", object@msim$model$n.start, sep = ""))
cat(paste("\nNo. of Simulations\t: ",object@msim$model$m.sim, sep = ""))
cat("\n\n")
invisible(object)
})
setMethod("show",
signature(object = "DCCroll"),
function(object){
cat(paste("\n*---------------------------------------------------*", sep = ""))
cat(paste("\n* DCC GARCH Roll *", sep = ""))
cat(paste("\n*---------------------------------------------------*", sep = ""))
cat("\n\nDistribution\t\t:", object@model$modeldesc$distribution)
cat(paste("\nSimulation Horizon\t: ", object@model$forecast.length, sep = ""))
cat(paste("\nRefits\t\t\t\t: ", object@model$n.refits, sep = ""))
cat(paste("\nWindow\t\t\t\t: ", object@model$refit.window, sep = ""))
cat(paste("\nNo.Assets\t\t\t: ", length(object@model$modeldata$asset.names), sep = ""))
cat("\n\nOptimal Parameters Across Rolls (First 2, Last 2)")
cat(paste("\n---------------------------------------------------\n", sep = ""))
tmp = coef(object)
if(dim(tmp)[2]>4){
n = dim(tmp)[2]
print(round(cbind(tmp[,1:2], tmp[,(n-1):n]), 4))
} else{
print(round(tmp, 4))
}
cat("\n")
invisible(object)
})
setMethod(f = "plot", signature(x = "DCCfit", y = "missing"), .plotdccfit)
setMethod(f = "plot", signature(x = "DCCfilter", y = "missing"), .plotdccfit)
setMethod(f = "plot", signature(x = "DCCforecast", y = "missing"), .plotdccforecast)
setMethod(f = "plot", signature(x = "DCCroll", y = "missing"), .plotdccroll)
first = function(x, index = 1, ...)
{
UseMethod("first")
}
.first.array = function(x, index = 1)
{
T = dim(x)[3]
if( index > T | index < 1 ) stop("\nindex out of bounds")
x[, , 1:index, drop = FALSE]
}
setMethod("first", signature(x = "array"), .first.array)
last = function(x, index = 1, ...)
{
UseMethod("last")
}
.last.array = function(x, index = 1)
{
T = dim(x)[3]
if( index > T | index < 1 ) stop("\nindex out of bounds")
x[, , (T - index + 1):T, drop = FALSE]
}
setMethod("last", signature(x = "array"), .last.array)
.newsimpact.dcc = function(object, type = "cov", pair = c(1,2), plot = TRUE, plot.type = c("surface", "contour"))
{
if(object@model$DCC=="FDCC"){
ans = switch(type,
cov = .newsimpact.fdcc.cov(object = object, pair = pair, plot = plot, type = plot.type),
cor = .newsimpact.fdcc.cor(object = object, pair = pair, plot = plot, type = plot.type)
)
} else{
ans = switch(type,
cov = .newsimpact.dcc.cov(object = object, pair = pair, plot = plot, type = plot.type),
cor = .newsimpact.dcc.cor(object = object, pair = pair, plot = plot, type = plot.type)
)
}
return(ans)
}
setMethod("nisurface", signature(object = "DCCfit"), .newsimpact.dcc)
setMethod("nisurface", signature(object = "DCCfilter"), .newsimpact.dcc)
.newsimpact.dcc.cor = function(object, pair = c(1,2), plot = TRUE, type = c("surface", "contour")){
if(is(object, "DCCfilter")){
Z = object@mfilter$stdresid
cnames = object@model$modeldata$asset.names
m = dim(object@model$umodel$modelinc)[2]
maxz = round(max(apply(object@mfilter$stdresid, 1, "max")) + 1, 0)
minz = round(min(apply(object@mfilter$stdresid, 1, "min")) - 1, 0)
zseq = seq(minz, maxz, length.out = 100)
idx = object@model$pidx
dcca = object@model$pars[idx["dcca",1], 1]
dccg = object@model$pars[idx["dccg",1], 1]
dccb = object@model$pars[idx["dccb",1], 1]
U = object@mfilter$Qbar*(1 - dcca - dccb) - dccg*object@mfilter$Nbar
Qbar = object@mfilter$Qbar
} else{
Z = object@mfit$stdresid
cnames = object@model$modeldata$asset.names
m = dim(object@model$umodel$modelinc)[2]
maxz = round(max(apply(object@mfit$stdresid, 1, "max")) + 1, 0)
minz = round(min(apply(object@mfit$stdresid, 1, "min")) - 1, 0)
zseq = seq(minz, maxz, length.out = 100)
idx = object@model$pidx
dcca = object@model$pars[idx["dcca",1], 1]
dccg = object@model$pars[idx["dccg",1], 1]
dccb = object@model$pars[idx["dccb",1], 1]
U = object@mfit$Qbar*(1 - dcca - dccb) - dccg*object@mfit$Nbar
Qbar = object@mfit$Qbar
}
ni = matrix(0, 100, 100)
for(i in 1:100){
for(j in 1:100){
z = za = matrix(0, ncol = m, nrow = 1)
z[1,pair[1]] = zseq[i]
z[1,pair[2]] = zseq[j]
za = z * .asymI(z)
tmp = U + dcca*t(z)%*%z + dccg*t(za)%*%za + dccb * Qbar
tmp = tmp/(sqrt(diag(tmp)) %*% t(sqrt(diag(tmp))) )
ni[i,j] = tmp[pair[1],pair[2]]
}
}
type == type[1]
if(plot){
if(tolower(type[1]) == "surface"){
x1 = shape::drapecol(ni, col = shape::femmecol(100), NAcol = "white")
persp( x = zseq,
y = zseq,
z = ni, col = x1, theta = 45, phi = 25, expand = 0.5,
ltheta = 120, shade = 0.75, ticktype = "detailed", xlab = "shock[z_1]",
ylab = "shock[z_2]", zlab = "cor",
cex.axis = 0.7, cex.main = 0.8, main = paste("DCC News Impact Correlation Surface\n",
cnames[pair[1]], "-", cnames[pair[2]], sep = ""))
} else{
tcol <- terrain.colors(12)
contour(x = zseq,
y = zseq,
z = ni, col = tcol[2], lty = "solid", cex.axis = 0.7, cex.main = 0.8,
main = paste("DCC News Impact Correlation Contour\n",
cnames[pair[1]], "-", cnames[pair[2]], sep = ""))
}
}
return(list(nisurface = ni, axis = zseq))
}
.newsimpact.dcc.cov = function(object, pair = c(1,2), plot = TRUE, type = c("surface", "contour")){
umodel = object@model$umodel
m = dim(umodel$modelinc)[2]
fpars = lapply(1:m, FUN = function(i) object@model$mpars[object@model$midx[,i]==1,i])
mspec = .makemultispec(umodel$modelinc, umodel$modeldesc$vmodel, umodel$modeldesc$vsubmodel,
umodel$modeldata$mexdata, umodel$modeldata$vexdata, umodel$start.pars,
fpars, NULL)
D = rep(0, m)
for(i in 1:m) D[i] = sqrt( as.numeric( uncvariance(mspec@spec[[i]])))
if(is(object, "DCCfilter")){
Z = object@mfilter$stdresid
cnames = object@model$modeldata$asset.names
maxz = round(max(apply(object@mfilter$stdresid, 1, "max")) + 1, 0)
minz = round(min(apply(object@mfilter$stdresid, 1, "min")) - 1, 0)
zseq = seq(minz, maxz, length.out = 100)
idx = object@model$pidx
dcca = object@model$pars[idx["dcca",1], 1]
dccg = object@model$pars[idx["dccg",1], 1]
dccb = object@model$pars[idx["dccb",1], 1]
U = object@mfilter$Qbar*(1 - dcca - dccb) - dccg*object@mfilter$Nbar
Qbar = object@mfilter$Qbar
} else{
Z = object@mfit$stdresid
cnames = object@model$modeldata$asset.names
maxz = round(max(apply(object@mfit$stdresid, 1, "max")) + 1, 0)
minz = round(min(apply(object@mfit$stdresid, 1, "min")) - 1, 0)
zseq = seq(minz, maxz, length.out = 100)
idx = object@model$pidx
dcca = object@model$pars[idx["dcca",1], 1]
dccg = object@model$pars[idx["dccg",1], 1]
dccb = object@model$pars[idx["dccb",1], 1]
U = object@mfit$Qbar*(1 - dcca - dccb) - dccg*object@mfit$Nbar
Qbar = object@mfit$Qbar
}
ni = matrix(0, 100, 100)
for(i in 1:100){
for(j in 1:100){
z = za = matrix(0, ncol = m, nrow = 1)
z[1,pair[1]] = zseq[i]
z[1,pair[2]] = zseq[j]
za = z * .asymI(z)
tmp = U + dcca*t(z)%*%z + dccg*t(za)%*%za + dccb * Qbar
tmp = tmp/(sqrt(diag(tmp)) %*% t(sqrt(diag(tmp))) )
H = diag(D)%*%tmp%*%diag(D)
ni[i,j] = H[pair[1],pair[2]]
}
}
type == type[1]
if(plot){
if(tolower(type[1]) == "surface"){
x1 = shape::drapecol(ni, col = shape::femmecol(100), NAcol = "white")
persp( x = zseq,
y = zseq,
z = ni, col = x1, theta = 45, phi = 25, expand = 0.5,
ltheta = 120, shade = 0.75, ticktype = "detailed", xlab = "shock[z_1]",
ylab = "shock[z_2]", zlab = "cov",
cex.axis = 0.7, cex.main = 0.8, main = paste("DCC News Impact Covariance Surface\n",
cnames[pair[1]], "-", cnames[pair[2]], sep = ""))
} else{
tcol <- terrain.colors(12)
contour(x = zseq,
y = zseq,
z = ni, col = tcol[2], lty = "solid", cex.axis = 0.7, cex.main = 0.8,
main = paste("DCC News Impact Covariance Contour\n",
cnames[pair[1]], "-", cnames[pair[2]], sep = ""))
}
}
return(list(nisurface = ni, axis = zseq))
}
.newsimpact.fdcc.cor = function(object, pair = c(1,2), plot = TRUE, type = c("surface", "contour"))
{
tmp = getfdccpars(object@model$pars, object@model)
fC = tmp$C
fA = tmp$A
fB = tmp$B
if(is(object, "DCCfilter")){
Z = object@mfilter$stdresid
modelinc = object@model$modelinc
cnames = object@model$modeldata$asset.names
m = dim(object@model$umodel$modelinc)[2]
maxz = round(max(apply(object@mfilter$stdresid, 1, "max")) + 1, 0)
minz = round(min(apply(object@mfilter$stdresid, 1, "min")) - 1, 0)
zseq = seq(minz, maxz, length.out = 100)
Qbar = object@mfilter$Qbar
} else{
Z = object@mfit$stdresid
cnames = object@model$modeldata$asset.names
m = dim(object@model$umodel$modelinc)[2]
maxz = round(max(apply(object@mfit$stdresid, 1, "max")) + 1, 0)
minz = round(min(apply(object@mfit$stdresid, 1, "min")) - 1, 0)
zseq = seq(minz, maxz, length.out = 100)
Qbar = object@mfit$Qbar
}
U = (fC %*% t(fC)) * Qbar
ni = matrix(0, 100, 100)
for(i in 1:100){
for(j in 1:100){
z = za = matrix(0, ncol = m, nrow = 1)
z[1,pair[1]] = zseq[i]
z[1,pair[2]] = zseq[j]
tmp = U + (fA[,1] %*% t(fA[,1]))* (t(z)%*%z) + (fB[,1]%*%t(fB[,1])) * Qbar
tmp = tmp/(sqrt(diag(tmp)) %*% t(sqrt(diag(tmp))) )
ni[i,j] = tmp[pair[1],pair[2]]
}
}
type == type[1]
if(plot){
if(tolower(type[1]) == "surface"){
x1 = shape::drapecol(ni, col = shape::femmecol(100), NAcol = "white")
persp( x = zseq,
y = zseq,
z = ni, col = x1, theta = 45, phi = 25, expand = 0.5,
ltheta = 120, shade = 0.75, ticktype = "detailed", xlab = "shock[z_1]",
ylab = "shock[z_2]", zlab = "cor",
cex.axis = 0.7, cex.main = 0.8, main = paste("DCC News Impact Correlation Surface\n",
cnames[pair[1]], "-", cnames[pair[2]], sep = ""))
} else{
tcol <- terrain.colors(12)
contour(x = zseq,
y = zseq,
z = ni, col = tcol[2], lty = "solid", cex.axis = 0.7, cex.main = 0.8,
main = paste("DCC News Impact Correlation Contour\n",
cnames[pair[1]], "-", cnames[pair[2]], sep = ""))
}
}
return(list(nisurface = ni, axis = zseq))
}
.newsimpact.fdcc.cov = function(object, pair = c(1,2), plot = TRUE, type = c("surface", "contour")){
umodel = object@model$umodel
m = dim(umodel$modelinc)[2]
fpars = lapply(1:m, FUN = function(i) object@model$mpars[object@model$midx[,i]==1,i])
mspec = .makemultispec(umodel$modelinc, umodel$modeldesc$vmodel, umodel$modeldesc$vsubmodel,
umodel$modeldata$mexdata, umodel$modeldata$vexdata, umodel$start.pars,
fpars, NULL)
D = rep(0, m)
for(i in 1:m) D[i] = sqrt( as.numeric( uncvariance(mspec@spec[[i]])))
tmp = getfdccpars(object@model$pars, object@model)
fC = tmp$C
fA = tmp$A
fB = tmp$B
if(is(object, "DCCfilter")){
Z = object@mfilter$stdresid
cnames = object@model$modeldata$asset.names
maxz = round(max(apply(object@mfilter$stdresid, 1, "max")) + 1, 0)
minz = round(min(apply(object@mfilter$stdresid, 1, "min")) - 1, 0)
zseq = seq(minz, maxz, length.out = 100)
Qbar = object@mfilter$Qbar
} else{
Z = object@mfit$stdresid
cnames = object@model$modeldata$asset.names
maxz = round(max(apply(object@mfit$stdresid, 1, "max")) + 1, 0)
minz = round(min(apply(object@mfit$stdresid, 1, "min")) - 1, 0)
zseq = seq(minz, maxz, length.out = 100)
Qbar = object@mfit$Qbar
}
U = (fC %*% t(fC)) * Qbar
ni = matrix(0, 100, 100)
for(i in 1:100){
for(j in 1:100){
z = za = matrix(0, ncol = m, nrow = 1)
z[1,pair[1]] = zseq[i]
z[1,pair[2]] = zseq[j]
tmp = U + (fA[,1] %*% t(fA[,1]))* (t(z)%*%z) + (fB[,1]%*%t(fB[,1])) * Qbar
tmp = tmp/(sqrt(diag(tmp)) %*% t(sqrt(diag(tmp))) )
H = diag(D)%*%tmp%*%diag(D)
ni[i,j] = H[pair[1],pair[2]]
}
}
type == type[1]
if(plot){
if(tolower(type[1]) == "surface"){
x1 = shape::drapecol(ni, col = shape::femmecol(100), NAcol = "white")
persp( x = zseq,
y = zseq,
z = ni, col = x1, theta = 45, phi = 25, expand = 0.5,
ltheta = 120, shade = 0.75, ticktype = "detailed", xlab = "shock[z_1]",
ylab = "shock[z_2]", zlab = "cov",
cex.axis = 0.7, cex.main = 0.8, main = paste("DCC News Impact Covariance Surface\n",
cnames[pair[1]], "-", cnames[pair[2]], sep = ""))
} else{
tcol <- terrain.colors(12)
contour(x = zseq,
y = zseq,
z = ni, col = tcol[2], lty = "solid", cex.axis = 0.7, cex.main = 0.8,
main = paste("DCC News Impact Covariance Contour\n",
cnames[pair[1]], "-", cnames[pair[2]], sep = ""))
}
}
return(list(nisurface = ni, axis = zseq))
} |
pcAxisParser <- function(streamParser) {
errorFun <- function(strmPosition,h=NULL,type="") {
if ( is.null(h) || type != "concatenation" )
print(paste("Error from line:",strmPosition$line," position:",strmPosition$linePos))
else errorFun(h$pos,h$h,h$type)
return(list(type=type,pos=strmPosition,h=h))
}
tlistParse <-
concatenation(keyword("TLIST"),
whitespace(),
charParser("("),
whitespace(),
symbolic(),
whitespace(),
alternation(
concatenation(charParser(")"),
repetition1N(
concatenation(
whitespace(),
charParser(","),
whitespace(),
string(action = function(s) s),
action = function(s) s[[4]]),
action = function(s) list(type="list",value=unlist(s))),
action = function(s) s[[2]] ),
concatenation(charParser(","),
whitespace(),
string(action = function(s) s),
whitespace(),
charParser("-"),
whitespace(),
string(action = function(s) s),
whitespace(),
charParser(")"),
action = function(s) list(type="limit",value=s[c(3,7)]) ),
action = function(s) s),
whitespace(),
charParser(";"),
action = function(s) list(type="tlist",value=s[c(5,7)]) )
rule <- concatenation(
symbolic(action = function(s) s),
option(concatenation(
whitespace(),
charParser("["),
whitespace(),
symbolic(action = function(s) s),
whitespace(),
charParser("]"),
action = function(s) s[4]),
action = function(s) if (!is.null(s$type) && s$type=="empty") NULL else s),
option(concatenation(
whitespace(),
charParser("("),
whitespace(),
string(action = function(s) s),
repetition0N(
concatenation(
whitespace(),
charParser(","),
whitespace(),
string(action = function(s) s),
action = function(s) s[4]),
action = function(s) if (!is.null(s$type) && s$type=="empty") NULL else s$value),
whitespace(),
charParser(")"),
action = function(s) if( is.null(s[[5]]) ) s[c(4)] else c(s[c(4)],unlist(s[c(5)]))),
action = function(s) if (!is.null(s$type) && s$type=="empty") NULL else s),
whitespace(),
charParser("="),
whitespace(),
alternation(
concatenation(
string(action = function(s)s), repetition1N(concatenation(
whitespace(),
string(action = function(s) s),
action = function(s) s[[2]]),
action = function(s) s ),
whitespace(),
charParser(";"),
action = function(s) list(type="stringstring",value=c(s[c(1)],unlist(s[c(2)]))) ),
concatenation( string(action = function(s) s) ,
repetition0N(
concatenation(
whitespace(),
charParser(","),
whitespace(),
string(action = function(s) s),
action = function(s) s[[4]]),
action = function(s) if (!is.null(s$type) && s$type=="empty") NULL else s$value),
whitespace(),
charParser(";"),
action = function(s) list(type="liststring",value=if( is.null( s[[2]] ) ) s[c(1)] else c(s[c(1)],unlist(s[c(2)],use.names = FALSE))) ),
concatenation(
alternation(
numberScientific(action = function(s) s),
string(action = function(s) s),
dots (action = function(s) s),
action = function(s) s) ,
repetition0N(
concatenation(
separator(),
alternation(
numberScientific( action = function(s) s),
string(action = function(s) s),
dots (action = function(s) s),
action = function(s) s) ,
action = function(s) s[[2]]),
action = function(s) if (!is.null(s$type) && s$type=="empty") NULL else s$value),
whitespace(),
alternation(
concatenation(charParser(";"),
whitespace(),
option(concatenation( charParser(";"), whitespace())),
option(concatenation( charParser("\032"), whitespace()))
),
concatenation(charParser("\032"),
whitespace()
),
eofMark()),
action = function(s) list(type="list",value=if( is.null( s[[2]] ) ) s[c(1)] else c(s[c(1)],unlist(s[c(2)], use.names = FALSE))) ),
tlistParse,
concatenation(symbolic(action = function(s) s),
whitespace(),
charParser(";"),
action = function(s) list(type="symbol",value=s[[1]])),
action = function(s) s),
whitespace(),
action = function(s) { rule <- s[c(1,2,3,7)] ; names(rule) <- c("keyword","language","parameters","ruleRight") ; rule }
)
cstream <- concatenation(repetition1N(rule,action = function(s) s) ,eofMark(error=errorFun),action = function(s) s[[1]]) (streamParser)
return(cstream)
} |
calc_LD<-function(mat,MAF,method,LD_summary,saveAt,linkage_map,interval) {
if(missing(mat)) {
stop('\n','--- Argument "mat" is missing')
}
mat<-as.matrix(mat)
if(dim(mat)[2]%%2!=0) {
stop('\n','--- Error in number of colomns in argument "mat"')
}
if(length(which(mat!=1 & mat!=2))>0){
stop('\n','--- Error in argument "mat". Wrong values in mat')
}
if(missing(MAF)) {
cat('MAF is missing, it has been set to default value of 0.05.',fill=TRUE)
MAF<-0.05
}
if(!missing(MAF)) {
if(MAF>0.49999 | MAF<0){
stop('\n','--- Error in argument "MAF". Possible range: 0<=x<=0.49999')
}
}
if(missing(method)) {
cat('Method to calculate LD is missing, LD will be calculated for all adjacent loci.',fill=TRUE)
method<-'adjacent'
}
test <- c('adjacent','pairwise')
if(method%in%test==FALSE){
stop('\n','--- Possible options in argument "method" are "adjacent" and "pairwise"')
}
if(missing(LD_summary)) {
LD_summary<-TRUE
}
if(!missing(LD_summary)) {
if(is.logical(LD_summary)==FALSE){
stop('\n','--- Argument "LD_summary" should be type "logical"')
}
}
if(!missing(saveAt)){
if(is.character(saveAt)==FALSE){
stop('Define a name for the saveAt argument as type "character"')
}
outFile<-paste(saveAt,'.txt',sep='')
}
if(missing(linkage_map) & missing(interval)) {
Ld_decay<-FALSE
}
if(!missing(linkage_map) & missing(interval)){
stop('\n','--- For calculation of LD decay, arguments "linkage_map" and "interval" should be provided in the function.')
}
if(missing(linkage_map) & !missing(interval)){
stop('\n','--- For calculation of LD decay, arguments "linkage_map" and "interval" should be provided in the function.')
}
if(!missing(linkage_map)) {
if(length(linkage_map)!=(dim(mat)[2]/2)){
stop('\n','--- Error in linkage map. Linkage map does not match number of loci')
}
if(length(linkage_map)!=length(unique(linkage_map))){
stop('\n','--- Error in linkage map. Some loci have the same position in linkage map')
}
if(length(which(linkage_map<0)>0)){
stop('\n','--- Error in linkage map. Negative value in linkage map')
}
}
if(!missing(linkage_map) & !missing(interval) & method=='pairwise'){
Ld_decay<-TRUE
chrom_length<-max(linkage_map)
intervals<-seq(0,chrom_length,interval)
if(length(intervals)==1){
stop('\n','--- Wrong input for argument "interval"')
}
}
if(!missing(linkage_map) & !missing(interval) & method!='pairwise'){
stop('\n','--- For the calculation of LD decay argument "method" should be set to "pairwise"')
}
Calc_freq<-function(Loci_Mat){
freq1<-as.numeric()
freq2<-as.numeric()
s1<-seq(1,length(Loci_Mat[1,]),2)
s2<-seq(2,length(Loci_Mat[1,]),2)
a1<-Loci_Mat[,s1]+Loci_Mat[,s2]
a1[a1==3]=1
a1[a1==4]=0
Loci_Mat2<-a1
dunkan<-function(vec){
sum(vec)/(length(vec)*2)
}
freq1<-apply(Loci_Mat2,2,dunkan)
freq2<-1-freq1
return(freq1)
}
if(Ld_decay==TRUE){
chrom_length<-max(linkage_map)
intervals<-seq(0,chrom_length,interval)
intervals
}
mat<-as.matrix(mat)
loci_mat<-mat
r_size<-dim(loci_mat)[1]
c_size<-dim(loci_mat)[2]
nloci_freq<-dim(loci_mat)[2]/2
loci_mat<-as.integer(unlist(loci_mat))
outfreq<-.Fortran("cf",r_size= as.integer(r_size),c_size = as.integer(c_size),loci_mat=loci_mat,nloci=as.integer(nloci_freq),freq1_main=double(nloci_freq))
freq1<-as.numeric(outfreq[[5]])
freq2<-1-freq1
freqmatrix<-matrix(0,ncol=2,nrow=length(freq1))
freqmatrix[,1]<-freq1
freqmatrix[,2]<-freq2
MAFv<-apply(freqmatrix,1,min)
MAFv1<-MAFv[MAFv>=MAF]
index<-which(MAFv%in%MAFv1)
if(Ld_decay==TRUE){
linkage_map1<-linkage_map[index]
}
new_index<-index*2
index<-c(new_index-1,new_index)
index<-sort(index)
mat_after_maf<-mat[,index]
r_size<-nrow(mat_after_maf)
c_size<-ncol(mat_after_maf)
outi2<-unlist(mat_after_maf)
outi2<-as.integer(mat_after_maf)
if (method=='pairwise'){
npair1<-combn(1:(ncol(mat_after_maf)/2),2)
npair<-length(npair1[1,])
arg5<-npair*12
argmet<-1
}
if (method=='adjacent'){
npair<-(ncol(mat_after_maf)/2)-1
arg5<-npair*12
argmet<-2
}
LD_Out<-.Fortran("ld",r_size= as.integer(r_size), c_size = as.integer(c_size),loci_mat=outi2,npair=as.integer(npair),method=as.integer(argmet),ld_data=double(arg5))
ld_data<-matrix(as.numeric(LD_Out[[6]]),nrow = npair,ncol = 12)
dim(ld_data)
Mean_r2<-mean(ld_data[,12])
if(Ld_decay==TRUE){
npair1<-t(npair1)
mydif<-linkage_map1[npair1[,2]]-linkage_map1[npair1[,1]]
length(mydif)
if(length(which(mydif<0))){
stop('--- Internal error in linkage map')
}
ld_data2<-matrix(ncol=2,nrow=length(mydif))
ld_data2[,1]<-ld_data[,12]
ld_data2[,2]<-mydif
r2_A<-matrix(nrow=length(intervals)-1,ncol=2)
r_breedA<-ld_data2
r_breedA<-r_breedA[order(r_breedA[,2]),]
for (i in 1:(length(intervals)-1)){
insideA<-subset(r_breedA,r_breedA[,2]>intervals[i] & r_breedA[,2]<=intervals[i+1])
insideA<-insideA[,1]
r2_A[i,1]<-mean(insideA)
r2_A[i,2]<-(intervals[i]+intervals[i+1])/2
}
if(length(which(is.nan(r2_A[,1])==TRUE))>0){
warning('\n','Mean LD is not available for one or more intervals due to lack of loci on those intervals.')
}
}
if(LD_summary==TRUE){
Mean_D<-mean(ld_data[,10])
Mean_r<-mean(ld_data[,11])
Mean_r2<-mean(ld_data[,12])
cat('\n','**** Linkage disequilibrium output **** ',fill=TRUE,'\n')
cat('Method:',method,fill = TRUE)
cat('No. marker:',(ncol(mat_after_maf)/2),fill = TRUE)
cat('No. marker pairs:',npair,fill = TRUE)
cat('\n','"D" summary:',fill=TRUE)
print(summary(ld_data[,10]))
cat('\n','"r" summary:',fill=TRUE)
print(summary(ld_data[,11]))
cat('\n','"r2" summary:',fill=TRUE)
print(summary(ld_data[,12]))
}
if(!missing(saveAt)){
colnames(ld_data) <- c("Pair No.","--p1--","--q1--","--p2--","--q2--","--Hap11--","--Hap12--","--Hap21--","--Hap22--","--D--","--r--","--r2--")
write.table(formatC(ld_data,digits=4, format="f") ,file=outFile,row.names = FALSE,quote=FALSE)
cat('\n','LD data has been written to the output file:',outFile,fill = TRUE)
}
if(Ld_decay==TRUE){
Final<-list(Mean_r2=Mean_r2,ld_data=ld_data,ld_decay=r2_A)
} else
Final<-list(Mean_r2=Mean_r2,ld_data=ld_data)
return(Final)
} |
identify_nkw <- function(data, collab_threshold = 5, return = "data_summary"){
summary_byPersonId <-
data %>%
group_by(PersonId, Organization) %>%
summarize(mean_collab = mean(Collaboration_hours), .groups = "drop")%>%
mutate(flag_nkw = case_when(mean_collab >= collab_threshold ~ "kw",
TRUE ~ "nkw"))
data_with_flag <-
left_join(data,
summary_byPersonId %>%
dplyr::select(PersonId,flag_nkw),
by = 'PersonId')
summary_byOrganization <-
summary_byPersonId %>%
group_by(Organization, flag_nkw)%>%
summarise(total = n(), .groups = "drop")%>%
group_by(Organization)%>%
mutate(perc = total/sum(total))%>%
filter(flag_nkw == "nkw")%>%
rename(n_nkw = total, perc_nkw = perc)%>%
select(-flag_nkw) %>%
ungroup()
n_nkw <- sum(summary_byPersonId$flag_nkw == "nkw")
if(n_nkw == 0){
flagMessage <- paste0("[Pass] There are no non-knowledge workers identified",
" (average collaboration hours below ",
collab_threshold,
" hours).")
} else {
flagMessage <-
paste0("[Warning] Out of a population of ", n_distinct(data$PersonId),
", there are ", n_nkw,
" employees who may be non-knowledge workers (average collaboration hours below ",
collab_threshold, " hours).")
}
if(return == "data_with_flag"){
return(data_with_flag)
} else if(return %in% c("data_clean", "data_cleaned")){
data_with_flag %>%
filter(flag_nkw == "kw")
} else if(return == "text"){
flagMessage
} else if(return =="data_summary"){
summary_byOrganization %>%
mutate(perc_nkw = scales::percent(perc_nkw, accuracy = 1)) %>%
rename(`Non-knowledge workers (count)` = "n_nkw",
`Non-knowledge workers (%)` = "perc_nkw")
} else {
stop("Error: please check inputs for `return`")
}
} |
cchart.Xbar1 <- function(x, sizes)
{
a <- rowMeans(x)
x2bar <- mean(a)
sigma <- sd.xbar(x)
qcc(x, type = "xbar", sizes)
stat <- list(c(x2bar, sigma))
return(stat)
} |
replaceColors <- function(grob, type){
if(type=="none") return(grob)
if(type=="safe" && is(grob, "text")){
if (!is.null(grob$gp$col)) {
grob$gp$col <- "
}
}
if (!is.null(grob$gp)) {
if (!is.null(grob$gp$col)) {
grob$gp$col <- cvdSimulator(grob$gp$col, type)
}
if (!is.null(grob$gp$fill)) {
grob$gp$fill <- cvdSimulator(grob$gp$fill, type)
}
}
if (length(grob$grobs)>0) {
grob$grobs <- lapply(grob$grobs, replaceColors, type=type)
}
if (length(grob$children)>0) {
grob$children <- lapply(grob$children, replaceColors, type=type)
}
if (is(grob, "rastergrob")) {
r <- cvdSimulator(grob$raster, type=type)
dim(r) <- dim(grob$raster)
class(r) <- class(grob$raster)
grob <- editGrob(grob, raster = r)
}
return(grob)
}
relativePhotometricQuantities <- function(col){
return((col2rgb(col, alpha = TRUE)/255)^2.2)
}
reduceColor <- function(col, method=c("protanope", "deuteranope")){
method <- match.arg(method)
return(switch(method,
"protanope"=.992052*col+.003974,
"deuteranope"=.957237*col+.0213814))
}
RGB2LMS <- function(col){
return(matrix(c(
17.8824, 43.5161, 4.11935,
3.45565, 27.1554, 3.86714,
.0299566, .184309, 1.46709
), nrow = 3, ncol = 3, byrow = TRUE) %*% col)
}
dichromatColor <- function(col, method=c("protanope", "deuteranope")){
prot <- matrix(c(
0, 2.02344, -2.52581,
0, 1, 0,
0, 0, 1
), nrow = 3, ncol = 3, byrow = TRUE)
deut <- matrix(c(
1, 0, 0,
.494207, 0, 1.24827,
0, 0, 1
), nrow = 3, ncol = 3, byrow = TRUE)
return(switch(method,
"protanope"= prot %*% col,
"deuteranope"= deut %*% col))
}
LMS2RGB <- function(col){
return(matrix(c(
.080944, -.130504, .116721,
-.0102485, .0540194, -.113615,
-.000365294, -.00412163, .693513
), nrow = 3, ncol = 3, byrow = TRUE) %*% col)
}
RGB2rgb <- function(col){
if("alpha" %in% rownames(col)){
alpha <- col["alpha", ]
}else{
alpha <- 255
}
col <- 255* (col[seq.int(3), , drop=FALSE]^(1/2.2))
return(rgb(col[1, ], col[2, ], col[3, ], alpha = alpha, maxColorValue = 255))
}
XYZ2LMS <- function(XYZ){
stopifnot(nrow(XYZ)==3)
return(matrix(c(
0.7328, 0.4296, -0.1624,
-0.7036, 1.6975, 0.0061,
0.0030, 0.0136, 0.9834
), nrow = 3, ncol = 3, byrow = TRUE) %*% XYZ)
}
LMS2XYZ <- function(LMS){
stopifnot(nrow(LMS)==3)
return(matrix(c(
1.096123821, -0.278869000, 0.1827452,
0.454369042, 0.473533154, 0.0720978,
-0.009627609, -0.005698031, 1.0153256
), nrow = 3, ncol = 3, byrow = TRUE) %*% LMS)
}
col2lab <- function(x){
col <- col2rgb(x, alpha = TRUE)
cbind(convertColor(t(col[seq.int(3), , drop=FALSE]), from = "sRGB",
to="Lab", scale.in = 255), alpha = col["alpha", ])
}
lab2hex <- function(x){
col <- x[, seq.int(3)]
alpha <- 255
if(ncol(x)>3){
alpha <- x[, "alpha"]
}
rgb(convertColor(col, from = "Lab", to="sRGB", scale.out = 255),
alpha = alpha, maxColorValue = 255)
}
colDistRGB <- function(.ele, sc, c){
.ele <- sc[, .ele, drop=FALSE]
rbar = (c["red", ] + .ele["red", ])/2
dR = (c["red", ] - .ele["red", ])^2
dG = (c["green", ] - .ele["green", ])^2
dB = (c["blue", ] - .ele["blue", ])^2
sqrt((2+rbar/256)*dR + 4*dG + (2+(255 - rbar)/256)*dB)
}
colDistCIE2000 <- function(.ele, sc, c){
.ele <- sc[.ele, , drop=FALSE]
L1 <- .ele[, "L"]
L2 <- c[, "L"]
a1 <- .ele[, "a.x"]
a2 <- c[, "a.x"]
b1 <- .ele[, "b"]
b2 <- c[, "b"]
Lbar_ <- (L1 + L2)/2
C1 <- sqrt(a1^2 + b1^2)
C2 <- sqrt(a2^2 + b2^2)
Cbar <- (C1 + C2)/2
G <- (1-sqrt(Cbar^7/(Cbar^7+25^7)))/2
a1_ <- a1*(1+G)
a2_ <- a2*(1+G)
C1_ <- sqrt(a1_^2 + b1^2)
C2_ <- sqrt(a2_^2 + b2^2)
Cbar_ <- (C1_ + C2_)/2
at1 <- atan2(b1, a1_)*180/pi
h1_ <- ifelse(at1<0, at1+360, at1)
at2 <- atan2(b2, a2_)*180/pi
h2_ <- ifelse(at2<0, at2+360, at2)
Hbar_ <- ifelse(abs(h1_-h2_)>180, (h1_+h2_+360)/2, (h1_+h2_)/2)
T <- 1 - 0.17 * cos(Hbar_ - 30) + 0.24 * cos(2*Hbar_) +
0.32 * cos(3*Hbar_ + 6) - 0.20 * cos(4*Hbar_ - 63)
dh_ <- ifelse(abs(h2_ - h1_)<= 180, h2_ - h1_,
ifelse(abs(h2_ - h1_) > 180 & h2_ <= h1_,
h2_ - h1_ + 360, h2_ - h1_ - 360))
dL_ <- L2 - L1
dC_ <- C2_ - C1_
dH_ <- 2*sqrt(C1_*C2_)*sin(dh_/2)
SL <- 1 + 0.015 * (Lbar_ - 50)^2/sqrt(20+(Lbar_ - 50)^2)
SC <- 1 + 0.045 * Cbar_
SH <- 1 + 0.015 * Cbar_*T
dtheta <- 30 * exp(-((Hbar_-275)/25)^2)
RC <- 2*sqrt(Cbar_^7/(Cbar_^7 + 25^7))
RT <- -RC*sin(2*dtheta)
KL <- KC <- KH <- 1
sqrt((dL_/KL/SL)^2 + (dC_/KC/SC)^2 + (dH_/KH/SH)^2 +
RT*(dC_/KC/SC)*(dH_/KH/SH))
}
safeCol <- c(safeColors,
"white"="
closestColorRGB <- function(col){
if(all(is.na(col))) return(col)
sc <- col2rgb(safeCol, alpha = TRUE)
c <- col2rgb(col, alpha = TRUE)
d <- lapply(colnames(sc), colDistRGB, sc=sc, c=c)
d <- do.call(cbind, d)
colnames(d) <- colnames(sc)
maxV <- max(d)
d1 <- d + 10^(nchar(maxV))*seq.int(nrow(d))
d1 <- order(t(d1))
d <- t(d)[d1]
d <- matrix(d, ncol = length(safeCol), byrow = TRUE)
d1 <- matrix(d1, ncol = length(safeCol), byrow = TRUE)
d1 <- d1 - length(safeCol)*(seq.int(nrow(d1))-1)
da <- col2lab(safeCol[d1[, 1]])
db <- col2lab(safeCol[d1[, 2]])
f <- d[, 1]/(d[, 1]+d[, 2])
newcol <- round(f*(db - da)) + da
newcol <- lab2hex(newcol)
dim(newcol) <- dim(col)
newcol[is.na(col)] <- NA
return(newcol)
}
closestColorCIE2000 <- function(col){
if(all(is.na(col))) return(col)
sc <- col2lab(safeCol)
c <- col2lab(col)
d <- lapply(names(safeCol), colDistCIE2000, sc=sc, c=c)
d <- do.call(cbind, d)
colnames(d) <- names(safeCol)
maxV <- max(d)
d1 <- d + 10^(nchar(maxV))*seq.int(nrow(d))
d1 <- order(t(d1))
d <- t(d)[d1]
d <- matrix(d, ncol = length(safeCol), byrow = TRUE)
d1 <- matrix(d1, ncol = length(safeCol), byrow = TRUE)
d1 <- d1 - length(safeCol)*(seq.int(nrow(d1))-1)
da <- col2lab(safeCol[d1[, 1]])
db <- col2lab(safeCol[d1[, 2]])
f <- d[, 1]/(d[, 1]+d[, 2])
newcol <- round(f*(db - da)) + da
newcol <- lab2hex(newcol)
dim(newcol) <- dim(col)
newcol[is.na(col)] <- NA
return(newcol)
}
closestColorLab <- function(col){
lab <- col2lab(col)
lab.a <- lab[, 2]
lab.b <- lab[, "b"]
lab[, "b"] <- lab[, "b"] + sign(lab.b) * lab.a
lab[lab[, "b"]>127, "b"] <- 127
lab[lab[, "b"]< -128, "b"] <- -128
lab[, "L"] <- lab[, "L"] - sign(lab.b) * lab.a/2 + lab.b/4
lab[lab[, "L"]<0, "L"] <- 0
lab[lab[, "L"]>100, "L"] <- 100
newcol <- lab2hex(lab)
dim(newcol) <- dim(col)
newcol[is.na(col)] <- NA
return(newcol)
}
closestColorLab2 <- function(col){
lab <- col2lab(col)
lab.a <- lab[, 2]
lab.b <- lab[, "b"]
lab[, "L"] <- lab[, "L"] + ifelse(lab.a<0 & lab.b>0, abs(lab.a/2), 0)
lab[, "b"] <- ifelse(lab.a<0 & lab.b>0, -lab.b, lab.b)
lab[, "L"] <- lab[, "L"] + ifelse(lab.a>0 & lab.b>0, abs(lab.a/6), 0)
lab[, "b"] <- ifelse(lab.a>0 & lab.b>0, lab[, "b"]+lab.a, lab[, "b"])
lab[lab[, 2]>127, 2] <- 127
lab[lab[, 2]< -128, 2] <- -128
lab[lab[, "b"]>127, "b"] <- 127
lab[lab[, "b"]< -128, "b"] <- -128
lab[lab[, "L"]<0, "L"] <- 0
lab[lab[, "L"]>100, "L"] <- 100
newcol <- lab2hex(lab)
dim(newcol) <- dim(col)
newcol[is.na(col)] <- NA
return(newcol)
}
closestColorRGB2 <- function(col){
rgb <- col2rgb(col, alpha = TRUE)
rgb["blue", ] <- rgb["blue", ] + rgb["red", ]/2 + rgb["green", ]/3
rgb["red", ] <- rgb["red", ] + round(rgb["green", ]/2)
rgb <- round(rgb)
rgb[rgb>255] <- 255
newcol <- rgb(t(rgb), maxColorValue=255)
dim(newcol) <- dim(col)
newcol[is.na(col)] <- NA
return(newcol)
} |
yyule0<-function ()
{
defaults <- list(initial.group = NULL, initial.variable = NULL,
initial.mean = "0")
dialog.values <- getDialog("yyule0", defaults)
initializeDialog(title = gettextRcmdr(paste("Profils de modalit",
"\U00E9", "s (Q)", sep = "")))
groupBox <- variableListBox(top, Factors(), title = gettextRcmdr("Variable explicative categorielle"),
initialSelection = varPosn(dialog.values$initial.group,
"factor"))
variableBox <- variableListBox(top, Variables(), title = gettextRcmdr("Variables (select one or more)"),
selectmode = "multiple", initialSelection = varPosn(dialog.values$initial.variable,
"all"))
checkBoxes(frame = "checkBoxFrame", boxes = c("mean"), initialValues = c(dialog.values$initial.mean),
labels = gettextRcmdr(c("Rangement en fonction de la valeur de Q")))
onOK <- function() {
group <- getSelection(groupBox)
variables <- getSelection(variableBox)
meanVar <- tclvalue(meanVariable)
putDialog("yyule0", list(initial.group = group, initial.variable = variables,
initial.mean = meanVar))
closeDialog()
if (length(variables) <2) {
errorCondition(recall = yyule0, message = gettextRcmdr("You must select at least two variables"))
return()
}
if (length(group) == 0) {
errorCondition(recall = yyule0, message = gettextRcmdr("You must select a variable"))
return()
}
.activeDataSet <- ActiveDataSet()
listvar <- paste(variables, collapse = "\",\"")
names.levels <- eval(parse(text = paste("levels(", .activeDataSet,
"$", group, ")", sep = "")), envir = .GlobalEnv)
nvalues <- length(names.levels)
for (i in 1:nvalues) {
namelevel <- names.levels[i]
command <- paste("Yule04(", .activeDataSet, "$",
group, ",", .activeDataSet, "[,c(\"", listvar,
"\")],\"", namelevel, "\",nameYY=c(\"", listvar,
"\")\n", ",tri=", meanVar, ")", sep = "")
doItAndPrint(command)
command <- paste("Yule03(", .activeDataSet, "$",
group, ",", .activeDataSet, "[,c(\"", listvar,
"\")],\"", namelevel, "\",nameYY=c(\"", listvar,
"\")\n", ",tri=", meanVar, ")", sep = "")
doItAndPrint(command)
if (i < nvalues) {
justDoIt("dev.new()")
}
}
activateMenus()
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject = "Yule03", reset = "yyule0")
tkgrid(getFrame(groupBox), getFrame(variableBox), sticky = "nw")
tkgrid(checkBoxFrame, sticky = "w")
tkgrid(buttonsFrame, sticky = "w")
dialogSuffix(rows = 2, columns = 1)
} |
context("sampleSizeSignificance")
test_that("numeric test for sampleSizeSignificance(): 1", {
za <- qnorm(p = 0.025, lower.tail = FALSE)
expect_equal(object = sampleSizeSignificance(zo = za, designPrior = "conditional",
power = 0.8, alternative = "one.sided"),
expected = 2.04, tol = 0.01)
})
test_that("numeric test for sampleSizeSignificance(): 2", {
zo <- seq(-4, 4, 2)
apply_grid <- expand.grid(priors = c("conditional", "predictive", "EB"),
h = c(0, 0.1),
shrinkage = c(0, 0.75),
alt = c("one.sided", "two.sided"),
stringsAsFactors = FALSE)
out <- lapply(X=seq_len(nrow(apply_grid)), FUN=function(i){
sampleSizeSignificance(zo = zo,
power = 0.8,
level = 0.05,
designPrior = apply_grid$priors[i],
alternative = apply_grid$alt[i],
h = apply_grid$h[i],
shrinkage = apply_grid$shrinkage[i])
})
expect_equal(out, list(
c(0.386409827001236,1.54563930800494,Inf,1.54563930800494,0.386409827001236),
c(0.440562894751761,2.64240442300288,NA,2.64240442300288,0.440562894751761),
c(0.505683996618901,5.68097835352188,NA,5.68097835352188,0.505683996618901),
c(0.386409827001236,1.54563930800494,Inf,1.54563930800494,0.386409827001236),
c(0.452332524054221,2.95871584108967,NA,2.95871584108967,0.452332524054221),
c(0.52827525176549,7.60908343838383,NA,7.60908343838383,0.52827525176549),
c(6.18255723201977,24.7302289280791,Inf,24.7302289280791,6.18255723201977),
c(113.100184785495,NA,NA,NA,113.100184785495),
c(0.505683996618901,5.68097835352188,NA,5.68097835352188,0.505683996618901),
c(6.18255723201977,24.7302289280791,Inf,24.7302289280791,6.18255723201977),
c(453.912799705814,NA,NA,NA,453.912799705814),
c(0.52827525176549,7.60908343838383,NA,7.60908343838383,0.52827525176549),
c(0.490554983396818,1.96221993358727,Inf,1.96221993358727,0.490554983396818),
c(0.567658970548963,3.51088218947353,NA,3.51088218947353,0.567658970548963),
c(0.652140069510171,7.6215454064467,NA,7.6215454064467,0.652140069510171),
c(0.490554983396818,1.96221993358727,Inf,1.96221993358727,0.490554983396818),
c(0.584343691289888,3.95487118399945,NA,3.95487118399945,0.584343691289888),
c(0.683282959536562,10.3012684887906,NA,10.3012684887906,0.683282959536562),
c(7.84887973434909,31.3955189373964,Inf,31.3955189373964,7.84887973434909),
c(158.405996395716,NA,NA,NA,158.405996395716),
c(0.652140069510171,7.6215454064467,NA,7.6215454064467,0.652140069510171),
c(7.84887973434909,31.3955189373964,Inf,31.3955189373964,7.84887973434909),
c(640.395220372103,NA,NA,NA,640.395220372103),
c(0.683282959536562,10.3012684887906,NA,10.3012684887906,0.683282959536562)
))
})
test_that("sampleSizeSignificance() vs sampleSizeSignificanceNum", {
vec01 <- c(0.001, 0.2532, 0.99)
vec01bound <- c(0, 0.0386, 0.5031, 0.99)
vec55 <- c(-5, -2.6288, 0, 4)
alternative <- c("two.sided", "one.sided")
designPrior <- c("conditional", "predictive", "EB")
powvec <- c(0.499, 0.8, 0.975)
levelvec <- c(0.001, 0.025, 0.49)
pars_grid_power <- expand.grid(zo=vec55,
power=powvec,
d=NA,
level=levelvec,
alternative=alternative,
designPrior=designPrior,
h=abs(vec55),
shrinkage=vec01bound, stringsAsFactors = FALSE)
pars_grid_d <- expand.grid(zo=vec55,
power=NA,
d=vec01,
level=.025,
alternative="one.sided",
designPrior="conditional",
h=0,
shrinkage=0, stringsAsFactors = FALSE)
pars_grid <- cbind(rbind(pars_grid_power, pars_grid_d), new=NA, legacy=NA)
sampleSizeSignificanceNum <- ReplicationSuccess:::sampleSizeSignificanceNum
for(i in seq_len(nrow(pars_grid))){
pars_grid[i,9] <- do.call("sampleSizeSignificance", args = pars_grid[i,1:8])
pars_grid[i,10] <- do.call("sampleSizeSignificanceNum", args = pars_grid[i,1:8])
}
pars_grid <- pars_grid[pars_grid$new < 1000,]
expect_equal(object=is.na(pars_grid[,9]), expected=is.na(pars_grid[,10]))
pars_grid_nonNA <- pars_grid[!is.na(pars_grid[,9]) & !is.na(pars_grid[,10]),]
expect_equal(object = pars_grid_nonNA[,9], expected = pars_grid_nonNA[,10], tol = 0.1)
}) |
getTrans <- function(object, sens = "F", NAstring = "X", ambiguous = FALSE, ...)
UseMethod("getTrans")
getTrans.default <- function(object, sens = "F", NAstring = "X", ambiguous = FALSE, ...)
stop(paste("no getTrans method for objects of class:", class(object)))
getTrans.list <- function(object, sens = "F", NAstring = "X", ambiguous = FALSE, ...)
lapply(seq_len(length(object)),
function(i) getTrans(object[[i]], sens = sens, NAstring = NAstring, ambiguous = ambiguous, ...))
getTrans.character <- function(object, sens = "F", NAstring = "X", ambiguous = FALSE, ..., frame = 0, numcode = 1)
translate(seq = object, frame = frame, sens = sens, numcode = numcode, NAstring = NAstring, ambiguous = ambiguous)
getTrans.SeqFastadna <- function(object, sens = "F", NAstring = "X", ambiguous = FALSE, ..., frame = 0, numcode = 1){
dnaseq <- getSequence(object, as.string = FALSE)
translate(seq = dnaseq, frame = frame, sens = sens, numcode = numcode, NAstring = NAstring, ambiguous = ambiguous)
}
getTrans.SeqFrag <- getTrans.SeqFastadna
getTrans.SeqAcnucWeb <- function(object, sens = "F", NAstring = "X", ambiguous = FALSE, ..., frame = "auto", numcode = "auto"){
dnaseq <- getSequence(object, as.string = FALSE)
if(numcode == "auto") numcode <- attr(object, "ncbigc")
if(frame == "auto") frame <- attr(object, "frame")
translate(seq = dnaseq, frame = frame, sens = sens, numcode = numcode, NAstring = NAstring, ambiguous = ambiguous)
}
getTrans.qaw <- function(object, sens = "F", NAstring = "X", ambiguous = FALSE, ...) getTrans(object$req, ...)
getTrans.logical <- function (object, sens = "F", NAstring = "X", ambiguous = FALSE, ...)
object |
rqb <- function(A, k=NULL, p=10, q=2, sdist="normal", rand = TRUE) UseMethod("rqb")
rqb.default <- function(A, k=NULL, p=10, q=2, sdist="normal", rand = TRUE) {
A <- as.matrix(A)
rqbObj <- list()
m <- nrow(A)
n <- ncol(A)
if(is.null(k)) k = n
if(k > n) k <- n
if(is.character(k)) stop("Target rank is not valid!")
if(k < 1) stop("Target rank is not valid!")
l <- round(k) + round(p)
if(l > n) l <- n
if(l < 1) stop("Target rank is not valid!")
if(is.complex(A)) {
isreal <- FALSE
} else {
isreal <- TRUE
}
if(rand == TRUE) {
O <- switch(sdist,
normal = matrix(stats::rnorm(l*n), n, l),
unif = matrix(stats::runif(l*n), n, l),
rademacher = matrix(sample(c(-1,1), (l*n), replace = TRUE, prob = c(0.5,0.5)), n, l),
stop("Selected sampling distribution is not supported!"))
if(isreal==FALSE) {
O <- O + switch(sdist,
normal = 1i * matrix(stats::rnorm(l*n), n, l),
unif = 1i * matrix(stats::runif(l*n), n, l),
rademacher = 1i * matrix(sample(c(-1,1), (l*n), replace = TRUE, prob = c(0.5,0.5)), n, l),
stop("Selected sampling distribution is not supported!"))
}
Y <- A %*% O
remove(O)
if( q > 0 ) {
for( i in 1:q) {
Y <- qr.Q( qr(Y, complete = FALSE) , complete = FALSE )
Z <- crossprod_help(A , Y )
Z <- qr.Q( qr(Z, complete = FALSE) , complete = FALSE )
Y <- A %*% Z
}
remove(Z)
}
rqbObj$Q <- qr.Q( qr(Y, complete = FALSE) , complete = FALSE )
}else{
rqbObj$Q <- qr.Q( qr(A, complete = FALSE) , complete = FALSE )
}
rqbObj$B <- crossprod_help(rqbObj$Q , A )
class(rqbObj) <- "rqb"
return(rqbObj)
} |
use_ghactions <- function(workflow = website()) {
checkmate::assert_list(
x = workflow,
any.missing = FALSE,
names = "named",
null.ok = FALSE
)
tryCatch(
expr = gh::gh_tree_remote(),
error = function(cnd) {
usethis::ui_stop(
c("This project does not have a GitHub remote configured as {usethis::ui_value('origin')}.",
"Do you need to run {usethis::ui_code('usethis::use_github()')}?"
)
)
}
)
usethis::use_directory(path = ".github/workflows", ignore = TRUE)
new <- usethis::write_over(
path = ".github/workflows/main.yml",
lines = r2yaml(workflow),
quiet = TRUE
)
if (new) {
usethis::ui_done(x = "GitHub actions is set up and ready to go.")
usethis::ui_todo(x = "Commit and push the changes.")
usethis::ui_todo(
x = "Visit the actions tab of your repository on github.com to check the results."
)
}
invisible(new)
}
use_ghactions_badge <- function(workflow_name = NULL,
badge_name = "Actions Status") {
workflows <- read_workflows()
checkmate::assert_choice(
x = workflow_name,
choices = purrr::map_chr(.x = workflows, "name"),
null.ok = TRUE
)
if (is.null(workflow_name)) {
workflow_name <- workflows[[1]]$name
}
workflow_name <- utils::URLencode(workflow_name)
reposlug <- glue::glue(
'{gh::gh_tree_remote()$username}/{gh::gh_tree_remote()$repo}'
)
usethis::use_badge(
href = glue::glue('https://github.com/{reposlug}/actions'),
src = glue::glue('https://github.com/{reposlug}/workflows/{workflow_name}/badge.svg'),
badge_name = badge_name
)
}
edit_workflow <- function() {
path <- usethis::proj_path(".github", "workflows", "main")
usethis::ui_todo("Commit and push for the changes to take effect.")
invisible(usethis::edit_file(path))
} |
context("errorhandling")
test_that("errors and crashes are handled and fixed",{
df <- data.frame(x = 1:5)
expect_error( sfheaders::sf_linestring(obj = df, x = "x", y = "y"), "geometries - number of columns requested is greater than those available" )
expect_error( sfheaders::sf_linestring(obj = df, x = "x", y = 2 ), "geometries - number of columns requested is greater than those available" )
expect_error( sfheaders::sf_linestring(obj = df, x = 1, y = 2 ), 'geometries - number of columns requested is greater than those available' )
df <- data.frame(x = 1:5, y = 1:5)
expect_error( sfheaders::sf_linestring(obj = df, x = 3, y = 2 ), 'geometries - invalid geometry column index' )
m <- matrix(1:2, ncol = 2)
expect_error( sfheaders::sf_linestring(obj = m, x = 3, y = 2 ), 'geometries - invalid geometry column index' )
m <- matrix(1)
expect_error( sfheaders::sf_linestring(obj = m, x = "x", y = "y"), 'geometries - number of columns requested is greater than those available' )
expect_error( sfheaders::sf_linestring(obj = m, x = "x", y = 2 ), 'geometries - number of columns requested is greater than those available' )
expect_error( sfheaders::sf_linestring(obj = m, x = 1, y = 2 ), 'geometries - number of columns requested is greater than those available' )
df <- data.frame(x = 1, y = 2 )
expect_error( sfheaders:::rcpp_sfc_multipoint(df, c(0L,1L), 2L, ""), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_linestring(df, c(0L,1L), 2L, ""), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multilinestring(df, c(0L,1L), 2L, NULL, "" ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multilinestring(df, c(0L,1L), NULL, 2L, "" ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multilinestring(df, c(0L,1L), 2L, 2L, ""), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_polygon(df, c(0L,1L), 2L, NULL, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_polygon(df, c(0L,1L), NULL, 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_polygon(df, c(0L,1L), 2L, 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(df, c(0L,1L), 2L, NULL, NULL, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(df, c(0L,1L), NULL, NULL, 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(df, c(0L,1L), NULL, 2L, NULL, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(df, c(0L,1L), 2L, 2L, NULL, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(df, c(0L,1L), NULL, 2L, 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(df, c(0L,1L), 2L, NULL, 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(df, c(0L,1L), 2L, 2L, 2L, "", FALSE ), "geometries - column index doesn't exist")
m <- matrix( 1:2, ncol = 2)
expect_error( sfheaders:::rcpp_sfc_multipoint(m, c(0L,1L), 2L, ""), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_linestring(m, c(0L,1L), 2L, ""), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multilinestring(m, c(0L,1L), 2L, NULL, "" ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multilinestring(m, c(0L,1L), NULL, 2L, "" ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multilinestring(m, c(0L,1L), 2L, 2L, "" ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_polygon(m, c(0L,1L), 2L, NULL, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_polygon(m, c(0L,1L), NULL, 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_polygon(m, c(0L,1L), 2L, 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(m, c(0L,1L), 2L, NULL, NULL, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(m, c(0L,1L), NULL, 2L, NULL, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(m, c(0L,1L), NULL, NULL, 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(m, c(0L,1L), 2L, 2L, NULL, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(m, c(0L,1L), NULL, 2L, 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(m, c(0L,1L), 2L, NULL, 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfc_multipolygon(m, c(0L,1L), 2L, 2L, 2L, "", FALSE ), "geometries - column index doesn't exist")
df <- data.frame(x = 1, y = 2 )
expect_error( sfheaders:::rcpp_sfg_multilinestring(m, c(0L,1L), 2L, "" ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfg_polygon(m, c(0L,1L), 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfg_multipolygon(m, c(0L,1L), 2L, NULL, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfg_multipolygon(m, c(0L,1L), NULL, 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfg_multipolygon(m, c(0L,1L), 2L, 2L, "", FALSE ), "geometries - column index doesn't exist")
m <- matrix( 1:2, ncol = 2)
expect_error( sfheaders:::rcpp_sfg_multilinestring(m, c(0L,1L), 2L, "" ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfg_polygon(m, c(0L,1L), 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfg_multipolygon(m, c(0L,1L), 2L, NULL, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfg_multipolygon(m, c(0L,1L), NULL, 2L, "", FALSE ), "geometries - column index doesn't exist")
expect_error( sfheaders:::rcpp_sfg_multipolygon(m, c(0L,1L), 2L, 2L, "", FALSE ), "geometries - column index doesn't exist")
})
test_that("single-row objects",{
is_sf <- function(x) "sf" %in% attr(x, "class")
df <- data.frame(x =1:3, y =2:4)
expect_true( is_sf( sfheaders::sf_point( df ) ) )
expect_true( is_sf( sfheaders::sf_multipoint( df ) ) )
expect_true( is_sf( sfheaders::sf_linestring( df ) ) )
expect_true( is_sf( sfheaders::sf_multilinestring( df ) ) )
expect_true( is_sf( sfheaders::sf_polygon( df ) ) )
expect_true( is_sf( sfheaders::sf_multipolygon( df ) ) )
m <- matrix(1:6, ncol = 2)
expect_true( is_sf( sfheaders::sf_point( m[1, ] ) ) )
expect_true( is_sf( sfheaders::sf_multipoint( m ) ) )
expect_true( is_sf( sfheaders::sf_linestring( m ) ) )
expect_true( is_sf( sfheaders::sf_multilinestring( m ) ) )
expect_true( is_sf( sfheaders::sf_polygon( m ) ) )
expect_true( is_sf( sfheaders::sf_multipolygon( m ) ) )
is_sfc <- function(x) "sfc" %in% attr( x, "class" )
df <- data.frame(x =1:3, y =2:4)
expect_true( is_sfc( sfheaders::sfc_point( df ) ) )
expect_true( is_sfc( sfheaders::sfc_multipoint( df ) ) )
expect_true( is_sfc( sfheaders::sfc_linestring( df ) ) )
expect_true( is_sfc( sfheaders::sfc_multilinestring( df ) ) )
expect_true( is_sfc( sfheaders::sfc_polygon( df ) ) )
expect_true( is_sfc( sfheaders::sfc_multipolygon( df ) ) )
m <- matrix(1:6, ncol = 2)
expect_true( is_sfc( sfheaders::sfc_point( m ) ) )
expect_true( is_sfc( sfheaders::sfc_multipoint( m ) ) )
expect_true( is_sfc( sfheaders::sfc_linestring( m ) ) )
expect_true( is_sfc( sfheaders::sfc_multilinestring( m ) ) )
expect_true( is_sfc( sfheaders::sfc_polygon( m ) ) )
expect_true( is_sfc( sfheaders::sfc_multipolygon( m ) ) )
is_sfg <- function(x) "sfg" %in% attr( x, "class" )
df <- data.frame(x =1:3, y =2:4)
expect_true( is_sfg( sfheaders::sfg_point( df[1,] ) ) )
expect_true( is_sfg( sfheaders::sfg_multipoint( df ) ) )
expect_true( is_sfg( sfheaders::sfg_linestring( df ) ) )
expect_true( is_sfg( sfheaders::sfg_multilinestring( df ) ) )
expect_true( is_sfg( sfheaders::sfg_polygon( df ) ) )
expect_true( is_sfg( sfheaders::sfg_multipolygon( df ) ) )
m <- matrix(1:6, ncol = 2)
expect_true( is_sfg( sfheaders::sfg_point( m[1,] ) ) )
expect_true( is_sfg( sfheaders::sfg_multipoint( m ) ) )
expect_true( is_sfg( sfheaders::sfg_linestring( m ) ) )
expect_true( is_sfg( sfheaders::sfg_multilinestring( m ) ) )
expect_true( is_sfg( sfheaders::sfg_polygon( m ) ) )
expect_true( is_sfg( sfheaders::sfg_multipolygon( m ) ) )
})
test_that("0-row & empty objects",{
is_sf <- function(x) "sf" %in% attr(x, "class")
df <- data.frame()
expect_error( sfheaders::sf_point( df ) )
expect_error( sfheaders::sf_multipoint( df ) )
expect_error( sfheaders::sf_linestring( df ) )
expect_error( sfheaders::sf_multilinestring( df ) )
expect_error( sfheaders::sf_polygon( df ) )
expect_error( sfheaders::sf_multipolygon( df ) )
m <- matrix()
expect_error( sfheaders::sf_point( m ) )
expect_error( sfheaders::sf_multipoint( m ) )
expect_error( sfheaders::sf_linestring( m ) )
expect_error( sfheaders::sf_multilinestring( m ) )
expect_error( sfheaders::sf_polygon( m ) )
expect_error( sfheaders::sf_multipolygon( m ) )
df <- data.frame()
expect_error( sfheaders::sfc_point( df ) )
expect_error( sfheaders::sfc_multipoint( df ) )
expect_error( sfheaders::sfc_linestring( df ) )
expect_error( sfheaders::sfc_multilinestring( df ) )
expect_error( sfheaders::sfc_polygon( df ) )
expect_error( sfheaders::sfc_multipolygon( df ) )
m <- matrix()
expect_error( sfheaders::sfc_point( m ) )
expect_error( sfheaders::sfc_multipoint( m ) )
expect_error( sfheaders::sfc_linestring( m ) )
expect_error( sfheaders::sfc_multilinestring( m ) )
expect_error( sfheaders::sfc_polygon( m ) )
expect_error( sfheaders::sfc_multipolygon( m ) )
df <- data.frame()
expect_error( sfheaders::sfg_point( df ) )
expect_error( sfheaders::sfg_multipoint( df ) )
expect_error( sfheaders::sfg_linestring( df ) )
expect_error( sfheaders::sfg_multilinestring( df ) )
expect_error( sfheaders::sfg_polygon( df ) )
expect_error( sfheaders::sfg_multipolygon( df ) )
m <- matrix()
expect_error( sfheaders::sfg_point( m ) )
expect_error( sfheaders::sfg_multipoint( m ) )
expect_error( sfheaders::sfg_linestring( m ) )
expect_error( sfheaders::sfg_multilinestring( m ) )
expect_error( sfheaders::sfg_polygon( m ) )
expect_error( sfheaders::sfg_multipolygon( m ) )
})
test_that("other misc errors are caught",{
x <- data.frame( x = c(0,0), y = c(0,0) )
expect_error( sfheaders:::rcpp_sfg_linestring( x, c(1L, 2L), "" ), "geometries - invalid column index")
}) |
NULL
setClass("udSeq", slots= c(ini = "numeric", add = "numeric"), contains = "randSeq")
setClass("rUdSeq", contains = c("rRandSeq", "udSeq"))
setMethod("getProb", signature = c(obj = "udSeq"),
function(obj) {
if(obj@K == 2) {
apply(obj@M, 1, function(randSeq, ini, add) {
conditionalProb <- numeric(length(randSeq))
conditionalProb[1] <- 1/2
sumR <- randSeq[1]
for(j in 1:(length(randSeq) - 1)) {
biasedCoin <- (ini + add*(j-sumR))/(2*ini + add*j)
if(randSeq[j+1] == 1) {
conditionalProb[j+1] <- biasedCoin
} else {
conditionalProb[j+1] <- 1 - biasedCoin
}
sumR <- sumR + randSeq[j+1]
}
return(prod(conditionalProb))
}, ini = obj@ini, add = obj@add)
}
else "Only supported for K=2."
}
)
setMethod("getDesign",
signature(obj = "udSeq"),
function(obj) {
paste("UD(", obj@ini, ",", obj@add, ")", sep = "")
}
) |
unitHydrograph <- function(
n,
k,
t,
force=FALSE
)
{
if(length(n)>1 | length(k)>1) stop("n and k can only have one single value!
For vectorization, use sapply (see documentation examples).")
UH <- t^(n-1) / k^n / gamma(n) * exp(-t/k)
if(force) UH <- UH/sum(UH)
UH
} |
check.bn = function(bn) {
if (missing(bn))
stop("an object of class 'bn' is required.")
if (!is(bn, "bn")) {
stop(sprintf("%s must be an object of class 'bn'.",
deparse(substitute(bn))))
}
}
match.bn = function(bn1, bn2) {
nodes1 = names(bn1$nodes)
nodes2 = names(bn2$nodes)
equal = setequal(nodes1, nodes2) && (length(nodes1) == length(nodes2))
if (!equal)
stop("the two networks have different node sets.")
}
check.bn.or.fit = function(bn) {
if (missing(bn))
stop("an object of class 'bn' or 'bn.fit' is required.")
if (!is(bn, "bn") && !is(bn, "bn.fit")) {
stop(sprintf("%s must be an object of class 'bn' or 'bn.fit'.",
deparse(substitute(bn))))
}
}
check.fit = function(bn) {
if (missing(bn))
stop("an object of class 'bn.fit' is required.")
if (!is(bn, "bn.fit")) {
stop(sprintf("%s must be an object of class 'bn.fit'.",
deparse(substitute(bn))))
}
}
check.bn.naive = function(bn) {
check.bn.or.fit(bn)
root = root.leaf.nodes(bn, leaf = FALSE)
if (length(root) != 1)
stop("a naive Bayes classifier can have only one root node, the training variable.")
if (is(bn, "bn"))
nodes = names(bn$nodes)
else
nodes = names(bn)
explanatory = nodes[nodes != root]
leafs = root.leaf.nodes(bn, leaf = TRUE)
if (!identical(sort(explanatory), sort(leafs)))
stop("all the explanatory variables must be leaf nodes.")
nparents = sapply(explanatory, function(node) { length(parents(bn, node)) })
if (any(nparents != 1))
stop("all the explanatory variables must be children of the training variable.")
}
check.bn.tan = function(bn) {
check.bn.or.fit(bn)
root = root.leaf.nodes(bn, leaf = FALSE)
if (length(root) != 1)
stop("a naive Bayes classifier can have only one root node, the training variable.")
if (is(bn, "bn")) {
check.nodes(bn$learning$args$training)
nodes = names(bn$nodes)
training = bn$learning$args$training
}
else {
check.nodes(attr(bn, "training"))
nodes = names(bn)
training = attr(bn, "training")
}
if (!identical(training, root))
stop("the training node is not the only root node in the graph.")
explanatory = nodes[nodes != root]
nparents = sapply(explanatory, function(node) { length(parents(bn, node)) })
if (!( (length(which(nparents == 2)) == length(explanatory) - 1) && (length(which(nparents == 1)) == 1) ))
stop("the explanatory variables must form a tree.")
} |
percentile.exact <-
function(x,p=0.95,gam=0.95,logx=TRUE,wpnt=FALSE){
kf <- function(n,p,gam){ -qt(1-gam,n-1,qnorm(1-p)*sqrt(n))/sqrt(n) }
kf2 <- function(n,p,gam){ qt(gam,n-1,qnorm(p)*sqrt(n))/sqrt(n) }
if(!wpnt)options(warn=-1)
n <- length(x)
if( logx ) {if( any(x <= 0)) stop("all data values must be positive")
y <- log(x)
}
else { y<- x }
yb <- mean(y)
sy <- sd(y)
n <- length(y)
if(p > 0.5) {ku <- kf(n,p,gam); kl <- kf(n,p,1-gam) }
else { ku <- kf2(n,p,gam) ; kl <- kf2(n,p,1-gam) }
yp <- yb + qnorm(p)*sy
lcl <- yb + kl*sy
ucl <- yb + ku*sy
if(logx){
yp<- exp(yp)
lcl<- exp( lcl )
ucl<- exp(ucl)
}
out<-list("Xp"=yp,"Xpe.LCL"=lcl,"Xpe.UCL"=ucl,"p"=p,
"gam"=gam,"Logx"= logx, "n"=n, "Ku"=ku,"Kl"=kl)
if(!wpnt)options(warn=0)
out
} |
sparcoord <- function(data, xvar=character(0), ...) {
main <- paste(deparse(substitute(data), 500), collapse = "\n")
if (is.data.frame(data)) data <- as.matrix(data[,sapply(data, is.numeric)])
stopifnot("matrix" %in% class(data))
if (is.null(colnames(data))) colnames(data) <- sprintf("%s[,%.0f]", main, 1:ncol(data))
dvar <- dimnames(data)[[2]]
if (length(xvar)) {
xvar <- xvar[xvar %in% dvar]
dvar <- setdiff(dvar, xvar)
} else {
xvar <- dvar
dvar <- NULL
}
shinyApp(
ui = dashboardPage(
dashboardHeader(title="Parallel coordinate plot"),
dashboardSidebar(
tags$style( HTML(".black-text .rank-list-item { color:
bucket_list(
header = NULL,
group_name = "bucket_var_group",
orientation = "vertical",
class = c("default-sortable", "black-text"),
add_rank_list(
text = "Variable(s)",
labels = dvar,
input_id = "dvar"
),
add_rank_list(
text = "Selected variable(s)",
labels = xvar,
input_id = "xvar"
)
)
),
dashboardBody(
fluidRow(
box(plotOutput("plot")),
box(verbatimTextOutput("command"), title="Basic R code")
))
),
server = function(input, output, session) {
output$plot <- renderPlot({
if ((length(input$xvar)>1)) {
args <- list(...)
args$x <- data[,input$xvar]
if (is.null(args$main)) args$main <- main
do.call("parcoord", args)
}
})
output$command <- renderText({
txt <- "At least two variables are required for a plot!"
if (length(input$xvar)>1) {
txt <- c(paste0(" x <- c(", paste0('"', input$xvar, '"', collapse=", "), ")\n"),
sprintf("parcoord(%s[,x])\n", main))
}
txt
})
}
)
} |
"print.envfit" <-
function(x, ...)
{
if (!is.null(x$vectors)) {
cat("\n***VECTORS\n\n")
print(x$vectors)
}
if (!is.null(x$factors)) {
cat("\n***FACTORS:\n\n")
print(x$factors)
}
if (!is.null(x$na.action))
cat("\n", naprint(x$na.action), "\n", sep="")
invisible(x)
} |
predict.customizedGlmnet <-
function(object, lambda, type = c('response', 'class'), ...)
{
type = match.arg(type)
groups = as.character(sort(unique(object$groupid)))
prediction = matrix(NA, nrow(object$x$test), length(lambda))
if (object$family == 'multinomial' & type == 'response') {
K = length(unique(object$y))
prediction = array(NA, c(nrow(object$x$test), length(lambda), K),
dimnames = list(NULL, NULL, sort(unique(object$y))))
}
for (group in groups) {
x = object$x$test[object$groupid == group, ]
if (sum(object$groupid == group) == 1) {
x = t(x)
}
if (object$family == 'multinomial' & type == 'response') {
prediction[object$groupid == group, , ] = 0
prediction[object$groupid == group, , object$fit[[group]]$classnames] =
predict(object$fit[[group]], x, s = lambda/object$fit[[group]]$nobs,
type = type, ...)[, , 1]
} else {
prediction[object$groupid == group, ] = predict(object$fit[[group]],
x, s = lambda/object$fit[[group]]$nobs, type = type, ...)
}
}
prediction
} |
listen_for_authcode <- function(remote_url, local_url)
{
local_url <- httr::parse_url(local_url)
localhost <- if(local_url$hostname == "localhost") "127.0.0.1" else local_url$hostname
localport <- local_url$port
info <- NULL
listen <- function(env)
{
query <- env$QUERY_STRING
info <<- if(is.character(query) && nchar(query) > 0)
httr::parse_url(query)$query
else list()
if(is_empty(info$code))
list(status=404L, headers=list(`Content-Type`="text/plain"), body="Not found")
else list(status=200L, headers=list(`Content-Type`="text/plain"),
body="Authenticated with Azure Active Directory. Please close this page and return to R.")
}
server <- httpuv::startServer(as.character(localhost), as.integer(localport), list(call=listen))
on.exit(httpuv::stopServer(server))
message("Waiting for authentication in browser...\nPress Esc/Ctrl + C to abort")
httr::BROWSE(remote_url)
while(is.null(info))
{
httpuv::service()
Sys.sleep(0.001)
}
httpuv::service()
if(is_empty(info$code))
{
msg <- gsub("\\+", " ", utils::URLdecode(info$error_description))
stop("Authentication failed. Message:\n", msg, call.=FALSE)
}
message("Authentication complete.")
info$code
}
poll_for_token <- function(url, body, interval, period)
{
interval <- as.numeric(interval)
ntries <- as.numeric(period) %/% interval
body$grant_type <- "urn:ietf:params:oauth:grant-type:device_code"
message("Waiting for device code in browser...\nPress Esc/Ctrl + C to abort")
for(i in seq_len(ntries))
{
Sys.sleep(interval)
res <- httr::POST(url, body=body, encode="form")
status <- httr::status_code(res)
cont <- httr::content(res)
if(status == 400 && cont$error == "authorization_pending")
{
}
else if(status >= 300)
process_aad_response(res)
else break
}
if(status >= 300)
stop("Authentication failed.", call.=FALSE)
message("Authentication complete.")
res
} |
test_that("coverage of functionality in mult.R", {
S <- spray(matrix(c(1,1,2,2,1,3,3,1,3,5),ncol=2,byrow=TRUE),1:5)
expect_silent(include_perms(kill_trivial_rows(S)))
expect_silent(cross(S,S*0))
expect_silent(cross(S*0,S))
expect_silent(cross(S*0,S*0))
expect_silent(wedge(as.kform(S)))
expect_silent(as.kform(matrix(1,0,3),lose=TRUE))
expect_silent(as.kform(matrix(1,0,3),lose=FALSE))
expect_error(as.symbolic(function(x){x^5}))
expect_silent(as.symbolic(as.ktensor(+S)))
expect_silent(as.symbolic(as.ktensor(-S)))
expect_silent(as.symbolic(as.ktensor(+S*0)))
expect_silent(as.symbolic(as.ktensor(-S*0)))
expect_silent(as.ktensor(as.ktensor(S)))
expect_silent(hodge(as.kform(S)))
expect_error(hodge(0*volume(5)))
expect_silent(hodge(volume(5)))
expect_silent(hodge(0*volume(5),n=7))
expect_error(hodge(0*volume(5),n=3))
expect_error(hodge(scalar(6)))
expect_silent(hodge(scalar(6),n=3))
expect_silent(hodge(scalar(6),n=7))
expect_silent(hodge(spray(rbind(c(1,2,4,5)))))
expect_false(issmall(volume(5)))
K <- as.kform(spray(matrix(c(1,1,2,2,1,3,3,1,3,5),ncol=2,byrow=TRUE),1:5))
expect_error(stretch(K))
expect_silent(stretch(K,1:5))
expect_silent(keep(kform_general(7,3),1:4))
expect_silent(discard(kform_general(7,3),1))
expect_silent(zerotensor(5))
expect_error(zerotensor(-5))
expect_silent(as.kform(K))
expect_silent(as.ktensor(K))
}) |
library(weyl)
d1 <- weyl(spray(rbind(c(1,1),c(0,3)),c(1,2)))
d2 <- weyl(spray(rbind(c(0,0),c(1,0),c(2,2)),c(3,7,-5)))
d1
d2
d1*d2
options(polyform=TRUE)
(d1^2 + d2) * (d2 - 3*d1)
x <- weyl(cbind(0,1))
D <- weyl(cbind(1,0))
x^2*D*x*D^2
options(polyform=FALSE)
set.seed(0)
x <- rweyl()
x
x <- rweyl(n=1,d=2)
y <- rweyl(n=2,d=2)
z <- rweyl(n=3,d=2)
options(polyform=TRUE)
x*(y*z)
(x*y)*z
x*(y*z) - (x*y)*z
f <- rweyl()
D <- as.der(f)
d1 <- rweyl()
d2 <- rweyl()
D(d1*d2) == d1*D(d2) + D(d1)*d2
weyl_prod_helper3
`weyl_e_prod` <- function(a,b,c,d){
if(c==0){return(spray(cbind(a,b+d)))}
if(b==0){return(spray(cbind(a+c,d)))}
return(
Recall(a,b-1,c,d+1) +
c*Recall(a,b-1,c,d)
)
}
options(prodfunc = weyl_e_prod)
options(weylvars = "e")
d <- weyl(spray(cbind(0,1)))
e <- weyl(spray(cbind(1,0)))
d*d*e
d^2*e
d^5*e == e*(1+d)^5
options(polyform = TRUE)
d*e*d^2*e
o1 <- weyl(spray(cbind(2,1)))
o2 <- weyl(spray(cbind(3,3)))
options(polyform = FALSE)
(1+o1)*(1-5*o2)
options(polyform = TRUE)
(1+o1)*(1-5*o2)
options(polyform = NULL) |
NULL
plate_types[['pnpp_experiment']] <- "pnpp_experiment"
define_params.pnpp_experiment <- function(plate) {
params <- NextMethod("define_params")
new_params <- list(
'GENERAL' = list(
'POSITIVE_NAME' = 'positive',
'NEGATIVE_NAME' = 'negative',
'POSITIVE_DIMENSION' = NA
),
'CLASSIFY' = list(
'CLUSTERS_BORDERS_NUM_SD' = 3,
'ADJUST_BW_MIN' = 4,
'ADJUST_BW_MAX' = 20,
'SIGNIFICANT_NEGATIVE_FREQ' = 0.01,
'SIGNIFICANT_P_VALUE' = 0.01
),
'RECLASSIFY' = list(
'MIN_WELLS_NEGATIVE_CLUSTER' = 4,
'BORDER_RATIO_QUANTILE' = 0.75
)
)
params %<>% utils::modifyList(new_params)
params
}
define_clusters.pnpp_experiment <- function(plate) {
clusters <- NextMethod("define_clusters")
c(clusters,
'RAIN',
'POSITIVE',
'NEGATIVE'
)
}
define_steps.pnpp_experiment <- function(plate) {
steps <- NextMethod("define_steps")
c(steps,
list(
'CLASSIFY' = 'classify_droplets',
'RECLASSIFY' = 'reclassify_droplets'
))
}
NULL
positive_dim <- function(plate) {
stopifnot(plate %>% inherits("pnpp_experiment"))
params(plate, 'GENERAL', 'POSITIVE_DIMENSION') %>% toupper
}
`positive_dim<-` <- function(plate, value = c("X", "Y")) {
stopifnot(plate %>% inherits("pnpp_experiment"))
value <- match.arg(value)
params(plate, 'GENERAL', 'POSITIVE_DIMENSION') <- value
plate
}
NULL
variable_dim <- function(plate) {
stopifnot(plate %>% inherits("pnpp_experiment"))
params(plate, 'GENERAL', 'POSITIVE_DIMENSION') %>% toupper %>% other_dim
}
`variable_dim<-` <- function(plate, value = c("X", "Y")) {
stopifnot(plate %>% inherits("pnpp_experiment"))
value <- match.arg(value)
params(plate, 'GENERAL', 'POSITIVE_DIMENSION') <- value %>% other_dim
plate
}
other_dim <- function(dim = c("X", "Y")) {
dim <- match.arg(dim)
if(toupper(dim) == "X") "Y" else "X"
}
positive_dim_var <- function(plate) {
stopifnot(plate %>% inherits("pnpp_experiment"))
plate %>%
positive_dim %>%
{params(plate, 'GENERAL', sprintf('%s_VAR', .))}
}
variable_dim_var <- function(plate) {
stopifnot(plate %>% inherits("pnpp_experiment"))
plate %>%
variable_dim %>%
{params(plate, 'GENERAL', sprintf('%s_VAR', .))}
}
wells_positive <- function(plate) {
stopifnot(plate %>% inherits("pnpp_experiment"))
var_name <- meta_var_name(plate, "significant_negative_cluster")
if (status(plate) < step(plate, 'CLASSIFY') ||
(!var_name %in% (plate %>% plate_meta %>% names))) {
return(c())
}
plate %>%
plate_meta %>%
dplyr::filter_(lazyeval::interp(~ !var, var = as.name(var_name))) %>%
.[['well']]
}
wells_negative <- function(plate) {
stopifnot(plate %>% inherits("pnpp_experiment"))
var_name <- meta_var_name(plate, "significant_negative_cluster")
if (status(plate) < step(plate, 'CLASSIFY') ||
(!var_name %in% (plate %>% plate_meta %>% names))) {
return(c())
}
plate %>%
plate_meta %>%
dplyr::filter_(as.name(var_name)) %>% .[['well']]
}
meta_var_name <- function(plate, var) {
if(!inherits(plate, "pnpp_experiment")) {
return(var)
}
var %>%
gsub("negative", negative_name(plate), .) %>%
gsub("positive", positive_name(plate), .)
}
NULL
positive_name <- function(plate) {
stopifnot(plate %>% inherits("pnpp_experiment"))
params(plate, 'GENERAL', 'POSITIVE_NAME')
}
`positive_name<-` <- function(plate, value) {
stopifnot(plate %>% inherits("pnpp_experiment"))
value %<>% make.names
params(plate, 'GENERAL', 'POSITIVE_NAME') <- value
plate
}
negative_name <- function(plate) {
stopifnot(plate %>% inherits("pnpp_experiment"))
params(plate, 'GENERAL', 'NEGATIVE_NAME')
}
`negative_name<-` <- function(plate, value) {
stopifnot(plate %>% inherits("pnpp_experiment"))
value %<>% make.names
params(plate, 'GENERAL', 'NEGATIVE_NAME') <- value
plate
} |
immer_cmml <- function( suff_stat, cpml_design, control=NULL )
{
time <- list( start=Sys.time() )
CALL <- match.call()
do_log_LAM <- do_log_GAM <- do_log_PHI <- do_log_PSI <- 0
eps <- 1E-6
freq <- as.vector(suff_stat[,"freq"])
item_table <- as.matrix(suff_stat[, c("item1","item2","cat1","cat2")])
item_pairs <- as.matrix(suff_stat[ (suff_stat$cat1==0) & (suff_stat$cat2==0), c("item1", "item2") ])
LAM_init <- cpml_design$LAM_init
GAM_init <- cpml_design$GAM_init
PHI_init <- cpml_design$PHI_init
PSI_init <- cpml_design$PSI_init
LAM_basispar <- cpml_design$LAM_basispar
GAM_basispar <- cpml_design$GAM_basispar
PHI_basispar <- cpml_design$PHI_basispar
PSI_basispar <- cpml_design$PSI_basispar
W_LAM <- cpml_design$W_LAM
W_GAM <- cpml_design$W_GAM
W_PHI <- cpml_design$W_PHI
W_PSI <- cpml_design$W_PSI
LAM_index <- cpml_design$LAM_index
GAM_index <- cpml_design$GAM_index
PHI_index <- cpml_design$PHI_index
PSI_index <- cpml_design$PSI_index
rho_index <- cpml_design$rho_index
tau_index <- cpml_design$tau_index
N_rho <- max(rho_index)
N_tau <- max(tau_index)
W_LAM <- immer_cmml_proc_parameter_index( W_par=W_LAM, par_index=LAM_index )
W_GAM <- immer_cmml_proc_parameter_index( W_par=W_GAM, par_index=GAM_index )
W_PHI <- immer_cmml_proc_parameter_index( W_par=W_PHI, par_index=PHI_index )
W_PSI <- immer_cmml_proc_parameter_index( W_par=W_PSI, par_index=PSI_index )
res <- immer_cmml_proc_basispar( LAM_basispar=LAM_basispar, GAM_basispar=GAM_basispar,
PHI_basispar=PHI_basispar, PSI_basispar=PSI_basispar, LAM_index=LAM_index,
GAM_index=GAM_index, PHI_index=PHI_index, PSI_index=PSI_index )
basispar <- res$basispar
basispar_design <- res$basispar_design
basispar_length <- res$basispar_length
N_LAM <- res$N_LAM
N_GAM <- res$N_GAM
N_PHI <- res$N_PHI
N_PSI <- res$N_PSI
basispar_design1 <- basispar_design - 1
LAM_index1 <- LAM_index - 1
GAM_index1 <- GAM_index - 1
PHI_index1 <- PHI_index - 1
PSI_index1 <- PSI_index - 1
rho_index1 <- rho_index - 1
tau_index1 <- tau_index - 1
opt_fct <- function(par){
res <- immer_cmml_basispar_to_probs( basispar=par, basispar_design=basispar_design1,
basispar_length=basispar_length, W_LAM=W_LAM, LAM_init=LAM_init, LAM_index=LAM_index1,
W_GAM=W_GAM, GAM_init=GAM_init, GAM_index=GAM_index1, W_PHI=W_PHI, PHI_init=PHI_init,
PHI_index=PHI_index1, W_PSI=W_PSI, PSI_init=PSI_init, PSI_index=PSI_index1,
N_LAM=N_LAM, N_GAM=N_GAM, N_PHI=N_PHI, N_PSI=N_PSI, item_pairs=item_pairs,
item_table=item_table, tau_index=tau_index1, rho_index=rho_index1, N_rho=N_rho,
N_tau=N_tau, do_log_LAM=do_log_LAM, do_log_GAM=do_log_GAM, do_log_PHI=do_log_PHI,
do_log_PSI=do_log_PSI )
probs <- res$probs + eps
val <- - sum( freq * log( probs ) )
return(val)
}
res <- immer_cmml_basispar_to_derivatives( basispar=basispar, basispar_design=basispar_design1,
basispar_length=basispar_length, W_LAM=W_LAM, LAM_init=LAM_init, LAM_index=LAM_index1,
W_GAM=W_GAM, GAM_init=GAM_init, GAM_index=GAM_index1, W_PHI=W_PHI, PHI_init=PHI_init,
PHI_index=PHI_index1, W_PSI=W_PSI, PSI_init=PSI_init, PSI_index=PSI_index1,
N_LAM=N_LAM, N_GAM=N_GAM, N_PHI=N_PHI, N_PSI=N_PSI, item_pairs=item_pairs,
item_table=item_table, tau_index=tau_index1, rho_index=rho_index1, N_rho=N_rho,
N_tau=N_tau, do_log_LAM=do_log_LAM, do_log_GAM=do_log_GAM, do_log_PHI=do_log_PHI,
do_log_PSI=do_log_PSI )
cpml_design$W_LAM <- W_LAM
cpml_design$W_GAM <- W_GAM
cpml_design$W_PHI <- W_PHI
cpml_design$W_PSI <- W_PSI
time$end <- Sys.time()
time$diff <- time$end - time$start
description <- "Composite Marginal Maximum Likelihood Estimation"
res <- list( suff_stat=suff_stat, cpml_design=cpml_design,
time=time, CALL=CALL, description=description)
class(res) <- "immer_cmml"
return(res)
} |
kmr <- function(xyt,s.region,s.lambda,ds,ks="epanech",hs,correction="none",approach="simplified"){
verifyclass(xyt,"stpp")
correc <- c("none","isotropic","border","modified.border","translate","setcovf")
id <- match(correction,correc,nomatch=NA)
if (any(nbg <- is.na(id))){
messnbg <- paste("unrecognised correction method:",paste(dQuote(correction[nbg]),collapse=","))
stop(messnbg,call.=FALSE)
}
id <- unique(id)
correc2 <- rep(0,6)
correc2[id] <- 1
appro <- c("simplified","standardised")
im <- match(approach,appro,nomatch=NA)
if (any(nbm <- is.na(im))){
messnbm <- paste("unrecognised type of estimator:",paste(dQuote(approach[nbm]),collapse=","))
stop(messnbm,call.=FALSE)
}
im <- unique(im)
appro2 <- rep(0,2)
appro2[im] <- 1
ker <- c("box","epanech","biweight")
ik <- match(ks,ker,nomatch=NA)
if (any(nbk <- is.na(ik))){
messnbk <- paste("unrecognised kernel function:",paste(dQuote(ks[nbk]),collapse=","))
stop(messnbk,call.=FALSE)
}
ik <- unique(ik)
ker2 <- rep(0,3)
ker2[ik] <- 1
dup <- duplicated(data.frame(xyt[,1],xyt[,2],xyt[,3]),fromLast = TRUE)[1]
if (dup == TRUE){
messnbd <- paste("spatio-temporal data contain duplicated points")
warning(messnbd,call.=FALSE)
}
options(warn = -1)
if (missing(s.region)) s.region <- sbox(xyt[,1:2], xfrac=0.01, yfrac=0.01)
xp <- s.region[,1]
yp <- s.region[,2]
nedges <- length(xp)
yp <- yp - min(yp)
nxt <- c(2:nedges, 1)
dx <- xp[nxt] - xp
ym <- (yp + yp[nxt])/2
Areaxy <- -sum(dx * ym)
if (Areaxy > 0){
bsw <- owin(poly = list(x = s.region[,1], y = s.region[,2]))
}else{
bsw <- owin(poly = list(x = s.region[,1][length(s.region[,1]):1], y = s.region[,2][length(s.region[,1]):1]))
}
area <- area(bsw)
pert <- perimeter(bsw)
ok <- inside.owin(xyt[,1],xyt[,2],w=bsw)
xyt.inside <- data.frame(x=xyt[,1][ok],y=xyt[,2][ok],t=xyt[,3][ok])
ptsx <- xyt.inside[,1]
ptsy <- xyt.inside[,2]
ptst <- xyt.inside[,3]
pxy <- ppp(x=ptsx,y=ptsy,window=bsw)
if (missing(hs)){
hs <- bw.stoyan(pxy)
}
if (missing(ds)){
rect <- as.rectangle(bsw)
maxd <- min(diff(rect$xrange),diff(rect$yrange))/4
ds <- seq(hs, maxd,len=100)[-1]
ds <- sort(ds)
}
if(ds[1]==0){ds <- ds[-1]
}
kernel <- c(ks=ks,hs=hs)
kmrtheo <- 1
npt <- pxy$n[1]
nds <- length(ds)
mumr <- mean(ptst)
ekmr <- rep(0,nds)
storage.mode(ekmr) <- "double"
if (appro2[1]==1){
kmrout <- .Fortran("kmrcore",as.double(ptsx),as.double(ptsy),as.double(ptst),
as.integer(npt),as.double(ds),as.integer(nds),as.integer(ker2)
,as.double(hs),(ekmr))
ekmr <- kmrout[[9]]/mumr
invisible(return(list(ekmr=ekmr,ds=ds,kernel=kernel,kmrtheo=kmrtheo)))
} else {
if(missing(s.lambda)){
misl <- 1
s.lambda <- rep(npt/area,npt)
} else {
misl <- 0
if (length(s.lambda)==1){
s.lambda <- rep(s.lambda,npt)
}
}
wrs <- array(0,dim=c(npt,npt))
wts <- array(0,dim=c(npt,npt))
wbi <- array(0,dim=c(npt,nds))
wbimod <- array(0,dim=c(npt,nds))
wss <- rep(0,nds)
if(correction=="isotropic"){
wisot <- edge.Ripley(pxy,pairdist(pxy))
wrs <- 1/wisot
}
if(correction=="translate"){
wtras <- edge.Trans(pxy)
wts <- 1/wtras
}
if(any(correction=="border")|any(correction=="modified.border")){
bi <- bdist.points(pxy)
for(i in 1:nds) {
wbi[,i] <- (bi>ds[i])/sum((bi>ds[i])/s.lambda)
wbimod[,i] <- (bi>ds[i])/eroded.areas(bsw,ds[i])
}
wbi[is.na(wbi)] <- 0
wbimod[is.na(wbimod)] <- 0
}
if(correction=="setcovf"){
for (i in 1:nds){
wss[i] <- area-((pert*ds[i])/pi)
}
wss <- 1/wss
}
options(warn = 0)
kmrout <- .Fortran("kmrcoreinh",as.double(ptsx),as.double(ptsy),as.double(ptst),
as.integer(npt),as.double(ds),as.integer(nds),as.double(s.lambda),
as.integer(ker2),as.double(hs),as.double(wrs),as.double(wts),
as.double(wbi),as.double(wbimod),as.double(wss),as.integer(correc2),
(ekmr))
ekmr <- kmrout[[16]]/mumr
invisible(return(list(ekmr=ekmr,ds=ds,kernel=kernel,kmrtheo=kmrtheo,s.lambda=s.lambda)))
}
} |
ensemble_create <- function(x, x.idx, w = NULL, x.var.idx = NULL, ...) UseMethod("ensemble_create")
ensemble_create.sf <- function(x, x.idx, w = NULL, x.var.idx = NULL, ...) {
st_sf(
ensemble_create(st_set_geometry(x, NULL), x.idx, w, x.var.idx, ...),
geometry = st_geometry(x),
agr = c(as.character(st_agr(x)), "constant", "constant")
)
}
ensemble_create.data.frame <- function(x, x.idx, w = NULL, x.var.idx = NULL, ...) {
stopifnot(inherits(x, "data.frame"), length(x.idx) <= ncol(x))
lst <- list(...)
z.lgl <- if ("na.rm" %in% names(lst)) lst$na.rm else TRUE
x.df <- x
if (inherits(x.idx, "character")) {
if (!all(x.idx %in% names(x.df)))
stop("If x.idx is a character vector, then all elements of x.idx must ",
"be the name of a column of x")
} else if (inherits(x.idx, c("integer", "numeric"))) {
if (!(max(x.idx) <= ncol(x.df)))
stop("If x.idx is a numeric vector, then all values of x must be ",
"less than or equal to ncol(x)")
x.idx <- names(x)[x.idx]
} else {
stop("x.idx must be a vector of class character, integer, or numeric")
}
if (!is.null(x.var.idx)) {
if (length(x.idx) != length(x.var.idx))
stop("If specified, x.var.idx must be the same length as x.idx")
if (inherits(x.var.idx, "character")) {
if (!all(x.var.idx %in% c(names(x.df))))
stop("If x.var.idx is a character vector, then all elements of x.var.idx must ",
"be the name of a column of x (not including the geometry list-column)")
} else if (inherits(x.var.idx, c("integer", "numeric"))) {
if (!(max(x.var.idx, na.rm = TRUE) <= ncol(x)))
stop("If x.var.idx is a numeric vector, then all values of x must be ",
"less than or equal to ncol(x)")
x.var.idx <- names(x)[x.var.idx]
} else {
stop("If it is not NULL, x.var.idx must be a vector of class ",
"character, integer, or numeric")
}
}
if (any(x.idx %in% x.var.idx))
stop("x.idx and x.var.idx cannot point to any of the same columns of x")
if (is.null(w)) {
w <- rep(1 / length(x.idx), length(x.idx))
} else if (inherits(w, "numeric")) {
if (length(x.idx) != length(w)) stop("x.idx and w must have the same length")
if (!all.equal(sum(w), 1)) stop("If w is a numeric vector, it must sum to 1")
} else if (inherits(w, "data.frame")) {
stopifnot(ncol(w) == length(x.idx), nrow(x) == nrow(w))
w <- data.frame(t(apply(w, 1, function(i, z) i / sum(i, na.rm = z), z = z.lgl)))
} else {
stop("w must be one of NULL, a data frame (or tibble), or a numeric vector")
}
x.df.idx <- x.df %>% select(!!x.idx)
if (!is.null(x.var.idx)) x.var.df.idx <- x.df %>% select(!!x.var.idx)
if (inherits(w, "numeric")) {
data.ens <- unname(apply(x.df.idx, 1, esdm_weighted_mean, w = w, ... = z.lgl))
if (is.null(x.var.idx)) {
data.ens.var <- unname(apply(
cbind(x.df.idx, data.ens), 1, function(i, j, z) {
esdm_weighted_var_amv(head(i, -1), tail(i, 1), j, na.rm = z)
}, j = w, z = z.lgl
))
} else {
data.ens.var <- unname(apply(
x.var.df.idx, 1, function(i, j, z) {
esdm_weighted_var_wmv(i, j, na.rm = z)
}, j = w, z = z.lgl
))
}
} else if (inherits(w, "data.frame")) {
data.ens <- unname(apply(cbind(x.df.idx, w), 1, function(i, k, z) {
esdm_weighted_mean(head(i, k), tail(i, k), na.rm = z)
}, k = ncol(w), z = z.lgl))
if (is.null(x.var.idx)) {
data.ens.var <- unname(apply(cbind(x.df.idx, w, data.ens), 1, function(i, k, z) {
i.mean <- tail(i, 1)
i <- head(i, -1)
esdm_weighted_var_amv(head(i, k), i.mean, tail(i, k), na.rm = z)
}, k = ncol(w), z = z.lgl))
} else {
data.ens.var <- unname(apply(
cbind(x.var.df.idx, w), 1, function(i, k, z) {
esdm_weighted_var_wmv(head(i, k), tail(i, k), na.rm = z)
}, k = ncol(w), z = z.lgl
))
}
} else {
stop("Error in ensemble_create()")
}
stopifnot(is.numeric(data.ens), is.numeric(data.ens.var))
data.ens[is.nan(data.ens)] <- NA
data.ens.var[is.nan(data.ens.var)] <- NA
data.frame(x, Pred_ens = data.ens, Var_ens = data.ens.var)
} |
poisson.exact<-function (x, T = 1, r = 1, alternative = c("two.sided", "less",
"greater"), tsmethod=c("central","minlike","blaker"), conf.level = 0.95,
control=binomControl(), plot=FALSE, midp=FALSE)
{
relErr<-control$relErr
tol<-control$tol
pRange<-control$pRange
tsmethod<-match.arg(tsmethod)
if (tsmethod!="central" & tsmethod!="minlike" & tsmethod!="blaker") stop("tsmethod must be one of 'central', 'minlike', or 'blaker' ")
DNAME <- deparse(substitute(x))
DNAME <- paste(DNAME, "time base:", deparse(substitute(T)))
if ((l <- length(x)) != length(T))
if (length(T) == 1)
T <- rep(T, l)
else stop("'x' and 'T' have incompatible length")
xr <- round(x)
if (any(!is.finite(x) | (x < 0)) || max(abs(x - xr)) > 1e-07)
stop("'x' must be finite, nonnegative, and integer")
x <- xr
if (any(is.na(T) | (T < 0)))
stop("'T' must be nonnegative")
if ((k <- length(x)) < 1)
stop("not enough data")
if (k > 2)
stop("The case k > 2 is unimplemented")
if (!missing(r) && (length(r) > 1 || is.na(r) || r < 0))
stop("'r' must be a single positive number")
alternative <- match.arg(alternative)
if (k == 2) {
RVAL <- binom.exact(x, sum(x), r * T[1]/(r * T[1] + T[2]),
alternative = alternative, tsmethod=tsmethod, conf.level=conf.level,
control=control, midp=midp)
RVAL$data.name <- DNAME
RVAL$statistic <- x[1]
RVAL$parameter <- sum(x) * r * T[1]/sum(T * c(1, r))
names(RVAL$statistic) <- c("count1")
names(RVAL$parameter) <- c("expected count1")
RVAL$estimate <- (x[1]/T[1])/(x[2]/T[2])
names(RVAL$estimate) <- "rate ratio"
pp <- RVAL$conf.int
RVAL$conf.int <- pp/(1 - pp) * T[2]/T[1]
if (tsmethod=="blaker" | tsmethod=="minlike"){
pplowerprec<- attr(RVAL$conf.int,"conf.limit.prec")$lower
rval.lower.prec<-pplowerprec/(1-pplowerprec)*T[2]/T[1]
ppupperprec<- attr(RVAL$conf.int,"conf.limit.prec")$upper
rval.upper.prec<-ppupperprec/(1-ppupperprec)*T[2]/T[1]
attr(RVAL$conf.int,"conf.limit.prec")<-list(lower=rval.lower.prec,
upper=rval.upper.prec)
}
names(r) <- "rate ratio"
RVAL$null.value <- r
methodphrase<-"Exact one-sided Comparison of Poisson rates"
if (alternative=="two.sided")
methodphrase<-switch(tsmethod,
minlike="Exact two-sided Poisson test (sum of minimum likelihood method)",
central="Exact two-sided Poisson test (central method)",
blaker="Exact two-sided Poisson test (Blaker's method)")
if (midp) methodphrase<-paste0(methodphrase,", mid-p version")
RVAL$method <- methodphrase
}
else {
m <- r * T
if (midp){
if (alternative=="two.sided" & tsmethod!="central") stop("midp=TRUE only available for tsmethod='central'")
midp.less<-ppois(x, m)-0.5*dpois(x,m)
midp.greater<-ppois(x - 1, m,
lower.tail = FALSE)-0.5*dpois(x,m)
PVAL <- switch(alternative,
less = midp.less,
greater = midp.greater,
two.sided =pmin(rep(1,length(midp.less)),
2*midp.less, 2*midp.greater))
p.L<-function(x,alpha){
if (x==0){
out<-0
} else {
rootfunc<-function(mu){
1-ppois(x,mu)+0.5*dpois(x,mu) - alpha
}
out<-uniroot(rootfunc,c(0,qgamma(alpha,x)+1))$root
}
out
}
p.U<-function(x,alpha){
if (x==0 & alpha>=0.5){
out<-0
} else {
rootfunc<-function(mu){
ppois(x,mu)-0.5*dpois(x,mu) - alpha
}
out<-uniroot(rootfunc,
c(0,qgamma(1 - alpha, x + 1)+1))$root
}
}
} else {
PVAL <- switch(alternative,
less = ppois(x, m),
greater = ppois(x - 1, m, lower.tail = FALSE),
two.sided = exactpoissonPval(x,T,r,relErr, tsmethod=tsmethod))
p.L <- function(x, alpha) {
if (x == 0)
0
else qgamma(alpha, x)
}
p.U <- function(x, alpha) qgamma(1 - alpha, x + 1)
}
if (alternative=="less"){
CINT<-c(0, p.U(x, 1 - conf.level))
} else if (alternative=="greater"){
CINT<-c(p.L(x, 1 - conf.level), Inf)
} else {
if (tsmethod=="central"){
alpha <- (1 - conf.level)/2
CINT<-c(p.L(x, alpha), p.U(x, alpha))
} else {
if (midp) stop("midp=TRUE only available for tsmethod='central'")
CINT<-exactpoissonCI(x,tsmethod=tsmethod,conf.level=conf.level)
}
}
CINT<-CINT/T
attr(CINT,"conf.level")<-conf.level
ESTIMATE <- x/T
names(x) <- "number of events"
names(T) <- "time base"
names(ESTIMATE) <- names(r) <- "event rate"
methodphrase<-"Exact one-sided Poisson rate test"
if (alternative=="two.sided")
methodphrase<-switch(tsmethod,
minlike="Exact two-sided Poisson test (sum of minimum likelihood method)",
central="Exact two-sided Poisson test (central method)",
blaker="Exact two-sided Poisson test (Blaker's method)")
if (midp) methodphrase<-paste0(methodphrase,", mid-p version")
RVAL<-structure(list(statistic = x, parameter = T, p.value = PVAL,
conf.int = CINT, estimate = ESTIMATE, null.value = r,
alternative = alternative, method = methodphrase,
data.name = DNAME), class = "htest")
}
if (plot){
lowerRange<-ifelse(RVAL$conf.int[1]==0, .8*min(r,RVAL$conf.int[2]), .8*min(RVAL$conf.int[1],r) )
upperRange<-ifelse(RVAL$conf.int[2]==Inf, 1.2*max(r,RVAL$conf.int[1]), 1.2*max(RVAL$conf.int[2],r) )
exactpoissonPlot(x,T,tsmethod=tsmethod,rRange=c(lowerRange,upperRange),alternative=alternative,conf.level=conf.level,col="gray")
points(r,RVAL$p.value,col="black")
}
return(RVAL)
} |
"dicom.dic" |
is.phyloseq <- function (x) {
length(x) == 1 && is(x) == "phyloseq"
} |
hsb2 <- read.table('https://stats.idre.ucla.edu/stat/r/faq/hsb2.csv', header=T, sep=",")
head(hsb2)
l <- reshape(hsb2,
varying = c("read", "write", "math", "science", "socst"),
v.names = "score",
timevar = "subj",
times = c("read", "write", "math", "science", "socst"),
new.row.names = 1:1000,
direction = "long")
l.sort <- l[order(l$id),]
head(l.sort)
w <- reshape(l.sort,
timevar = "subj",
idvar = c("id", "female", "race", "ses", "schtyp", "prog"),
direction = "wide")
head(w)
dim(w)
dim(hsb2) |
reports <- function(apiVersion = "201809"){
switch (apiVersion,
"201809" = reportTypes <- list.files(system.file(package="RAdwords",'extdata/api201809/')),
"201806" = reportTypes <- list.files(system.file(package="RAdwords",'extdata/api201806/')),
"201802" = reportTypes <- list.files(system.file(package="RAdwords",'extdata/api201802/'))
)
reportTypes <- sub('.csv', '', reportTypes)
reportTypes <- gsub('-', '_', reportTypes)
reportTypes <- toupper(reportTypes)
reportTypes
} |
test_that("capimun online", {
skip_on_cran()
skip_if_siane_offline()
skip_if_gisco_offline()
expect_silent(esp_get_capimun())
expect_silent(esp_get_capimun(rawcols = TRUE))
expect_message(esp_get_capimun(verbose = TRUE))
expect_message(esp_get_capimun(verbose = TRUE, update_cache = TRUE))
expect_message(esp_get_capimun(region = "Canarias", verbose = TRUE))
expect_error(esp_get_capimun(year = "2019-15-23"))
expect_error(esp_get_capimun(year = "2019-15"))
expect_warning(expect_error(expect_warning(esp_get_capimun(region = "XX"))))
expect_error(esp_get_capimun(epsg = "5689"))
expect_error(esp_get_capimun(year = "2040"))
expect_error(expect_warning(esp_get_capimun(munic = "XX")))
expect_silent(esp_get_capimun(moveCAN = FALSE))
expect_silent(esp_get_capimun(moveCAN = c(0, 10)))
expect_silent(esp_get_capimun(year = "2019-10-23"))
expect_silent(esp_get_capimun(munic = "Nieva"))
expect_silent(esp_get_capimun(region = "Alava"))
a <- mapSpain::esp_codelist
n <- a$nuts1.name
s <- esp_get_capimun(region = n)
expect_equal(length(unique(s$cpro)), 52)
}) |
tr.cont.scale <- function(sp_tr, std_method = "scale_center") {
check.sp.tr(sp_tr)
if (any(!apply(sp_tr, 2, is.numeric))) {
stop("Species x traits data frame must contain only numerical variables.")
}
std_method <- match.arg(std_method, c("range", "center", "scale",
"scale_center"))
if (std_method == "range") {
sp_tr <- apply(sp_tr, 2, function(x) (x - min(x)) / (max(x) - min(x)))
}
if (std_method == "center") {
sp_tr <- apply(sp_tr, 2, function(x) x - mean(x))
}
if (std_method == "scale") {
sp_tr <- apply(sp_tr, 2, function(x) x / stats::sd(x))
}
if (std_method == "scale_center") {
sp_tr <- apply(sp_tr, 2, function(x) (x - mean(x) / stats::sd(x)))
}
return(sp_tr)
}
tr.cont.fspace <- function(sp_tr, pca = TRUE, nb_dim = 7,
scaling = "scale_center",
compute_corr = "pearson") {
check.sp.tr(sp_tr)
if (any(!apply(sp_tr, 2, is.numeric))) {
stop("Species x traits data frame must contain only numerical variables.")
}
scaling <- match.arg(scaling, c("range", "center",
"scale", "scale_center", "no_scale"))
compute_corr <- match.arg(compute_corr, c("pearson",
"none"))
if (pca) {
if (ncol(sp_tr) < 3) {
stop("There must be at least 3 traits in 'sp_tr'.")
}
if (nrow(sp_tr) < 3) {
stop("There must be at least 3 species in 'sp_tr'.")
}
}
if (nb_dim < 2) {
stop("Number of dimensions must be higher than 1.")
}
if (nb_dim > ncol(sp_tr)) {
stop("Number of dimensions must be lower than the number of traits.")
}
compute.corr.coef <- function(sp_tr) {
if (nrow(sp_tr) <= 4) {
stop("If you want to compute correlation matrix you must have more ",
"than 4 observations.")
}
Hmisc::rcorr(as.matrix(sp_tr), type = "pearson")
}
deviation.dist <- function(sp_dist_init, sp_dist_multidim) {
deviation_dist <- sp_dist_multidim - sp_dist_init
c(mAD = mean(abs(deviation_dist), 6), mSD = mean(((deviation_dist) ^ 2),
6))
}
if (scaling != "no_scale") {
sp_tr <- tr.cont.scale(sp_tr, std_method = scaling)
}
if (pca) {
sp_dist_init <- cluster::daisy(sp_tr, metric = "euclidean")
pca_analysis <- FactoMineR::PCA(sp_tr, ncp = nb_dim,
graph = FALSE, scale.unit = FALSE)
sp_faxes_coord <- as.data.frame(pca_analysis$ind$coord)
if (ncol(sp_faxes_coord) > nb_dim) {
sp_faxes_coord <- sp_faxes_coord[, 1:nb_dim]
}
nb <- 1
for(i in (1:ncol(sp_faxes_coord))) {
colnames(sp_faxes_coord)[i] <- paste0("PC", nb)
nb <- nb + 1
}
quality_nbdim <- matrix(NA, nb_dim - 1, 2,
dimnames = list(paste0(2:nb_dim, "D"),
c("mAD", "mSD")))
sp_dist_multidim <- list()
for (i in 2:nb_dim) {
sp_dist_multidim2 <- stats::dist(sp_faxes_coord[,
1:i],
method = "euclidean")
quality_nbdim[paste0(i, "D"), c("mAD",
"mSD")] <- deviation.dist(
sp_dist_init, sp_dist_multidim2)
sp_dist_multidim[[i - 1]] <- sp_dist_multidim2
names(sp_dist_multidim)[i - 1] <- paste0(i, "D")
}
eigenv_varpercent <- pca_analysis$eig[c(1:nb_dim), ]
nb <- 1
for (e in (1:nrow(eigenv_varpercent))){
rownames(eigenv_varpercent)[e] <- paste0("PC", nb)
nb <- nb + 1
}
if (compute_corr == "pearson") {
corr_tr_coeff <- compute.corr.coef(sp_tr)
return_list1 <- list(quality_nbdim, eigenv_varpercent,
as.matrix(sp_faxes_coord),
sp_dist_multidim, sp_dist_init, corr_tr_coeff)
names(return_list1) <- c("quality_metrics",
"eigenvalues_percentage_var",
"sp_faxes_coord",
"sp_dist_multidim",
"sp_dist_init",
"tr_correl")
return(return_list1)
} else {
return_list1 <- list(quality_nbdim, eigenv_varpercent,
as.matrix(sp_faxes_coord),
sp_dist_multidim, sp_dist_init)
names(return_list1) <- c("quality_metrics",
"eigenvalues_percentage_var",
"sp_faxes_coord",
"sp_dist_multidim",
"sp_dist_init")
return(return_list1)
}
} else {
sp_dist_init <- cluster::daisy(sp_tr, metric = "euclidean")
sp_faxes_coord <- sp_tr
if (compute_corr == "pearson") {
corr_tr_coeff <- compute.corr.coef(sp_tr)
return_list2 <- list(sp_faxes_coord, sp_dist_init,
corr_tr_coeff)
names(return_list2) <- c("sp_faxes_coord",
"sp_dist",
paste("tr_correl"))
return(return_list2)
} else {
return_list2 <- list(as.matrix(sp_faxes_coord),
sp_dist_init)
names(return_list2) <- c("sp_faxes_coord",
"sp_dist")
return(return_list2)
}
}
} |
coef.srafit <-
function (object, ...)
{
object$coefficients
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(ggplot2)
library(dplyr)
library(purrr)
library(tidyr)
library(forcats)
library(sitar)
knitr::kable(optimal_design(z = -4:4*2/3, N = 10000), digits = c(2, 2, 0, 3, 0, 2, 2))
minage <- 0
maxage <- 20
N <- 1e4
map_dfr(c(1, 0.9, 0.38), ~{
tibble(age = (runif(N, minage^.x, maxage^.x))^(1/.x),
p = .x)
}) %>%
mutate(lambda = fct_reorder(factor(p), -p)) %>%
ggplot(aes(age, group = lambda)) +
geom_histogram(fill = 'gray', binwidth = 1) +
facet_wrap(. ~ lambda, labeller = label_both) +
xlab('age (years)') + ylab('frequency')
n_table <- map_dfc(-4:4*2/3, ~{
n_agegp(z = .x, N = 10000) %>%
select(!!z2cent(.x) := n_varying)
}) %>%
bind_cols(tibble(age = paste(0:19, 1:20, sep = '-')), .)
knitr::kable(n_table)
knitr::kable(n_agegp(z = 2, N = 3506, minage = 0, maxage = 5, n_groups = 5) %>%
select(age, n_varying))
tibble(age = c(1/6, 1/2, 5/6, 5/4, 7/4, 19/8, 25/8, 4:10,
c(22:29/2 - 1/4), 15:18, 77/4),
n = c(rep(12, 3), rep(10, 4), 13, rep(11, 6), rep(6, 3),
rep(11, 5), 15, rep(8, 3), 13) * 100,
span = c(rep(1/3, 3), rep(1/2, 2), rep(3/4, 2), rep(1, 7),
rep(1/2, 8), rep(1, 4), 3/2)) %>%
ggplot(aes(x = age, y = n/span, width = span-0.02)) +
xlab('age (years)') + ylab('frequency') +
geom_bar(fill = 'gray', stat = 'identity') +
geom_bar(aes(y = n_varying, width = NULL),
data = n_agegp(z = qnorm(0.03), SEz = 0.3 / 5.75) %>%
mutate(n_varying = n_varying * 1.1),
width = 0.98, fill = 'gray50', stat = 'identity') |
if(requireNamespace("dagitty")) {
library(pcalg)
(doExtras <- pcalg:::doExtras())
x <- 1; y <- 2
cpdag <- matrix(c(0,1,1,0),2,2)
dag <- matrix(c(0,1,0,0),2,2)
adjC <- adjustment(amat = cpdag, amat.type = "cpdag", x = 1, y = 2, set.type = "canonical")
adjD <- adjustment(amat = dag, amat.type = "dag", x = 1, y = 2, set.type = "canonical")
adjP <- adjustment(amat = dag, amat.type = "pdag", x = 1, y = 2, set.type = "canonical")
stopifnot(!identical(adjC, adjD), identical(adjD, adjP) )
gacVSadj <- function(amat, x, y ,z, V, type) {
typeDG <- switch(type,
dag = "dag",
cpdag = "cpdag",
mag = "mag",
pag = "pag")
gacRes <- gac(amat,x,y, z, type)$gac
adjRes <- adjustment(amat = amat, amat.type = typeDG, x = x, y = y, set.type = "all")
if (gacRes) {
res <- any(sapply(adjRes, function(xx) setequal(z, xx)))
} else {
res <- all(!sapply(adjRes, function(xx) setequal(z, xx)))
}
res
}
xx <- TRUE
mFig1 <- matrix(c(0,1,1,0,0,0, 1,0,1,1,1,0, 0,0,0,0,0,1,
0,1,1,0,1,1, 0,1,0,1,0,1, 0,0,0,0,0,0), 6,6)
type <- "cpdag"
x <- 3; y <- 6
V <- as.character(1:ncol(mFig1))
rownames(mFig1) <- colnames(mFig1) <- V
xx <- xx & gacVSadj(mFig1,x,y, z=c(2,4), V=V, type)
xx <- xx & gacVSadj(mFig1,x,y, z=c(4,5), V=V, type)
type <- "pag"
mFig3a <- matrix(c(0,1,0,0, 1,0,1,1, 0,1,0,1, 0,1,1,0), 4,4)
V <- as.character(1:ncol(mFig3a))
rownames(mFig3a) <- colnames(mFig3a) <- V
xx <- xx & gacVSadj(mFig3a, x=2, y=4, z=NULL, V=V, type)
mMMd1 <- matrix(c(0,1,0,1,0,0, 0,0,1,0,1,0, 0,0,0,0,0,1,
0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0),6,6)
V <- as.character(1:ncol(mMMd1))
rownames(mMMd1) <- colnames(mMMd1) <- V
type <- "dag"
x <- 1; y <- 3
xx <- xx & gacVSadj(mMMd1, x,y, z=NULL, V=V, type)
xx <- xx & gacVSadj(mMMd1, x,y, z= 2, V=V, type)
if (!xx) {
stop("Problem when testing function gacVSadj.")
} else {
message("OK, no issues were found.")
}
if (doExtras) {
cat("doExtras is ON\n")
x <- 1; y <- 2
cpdag <- matrix(c(0,1,1,0),2,2)
dag <- matrix(c(0,1,0,0),2,2)
adjC <- adjustment(amat = cpdag, amat.type = "cpdag", x = 1, y = 2, set.type = "canonical")
adjD <- adjustment(amat = dag, amat.type = "dag", x = 1, y = 2, set.type = "canonical")
adjP <- adjustment(amat = dag, amat.type = "pdag", x = 1, y = 2, set.type = "canonical")
stopifnot(!identical(adjC, adjD), identical(adjD, adjP) )
adjCAll <- adjustment(amat = cpdag, amat.type = "cpdag", x = 1, y = 2, set.type = "all")
adjDAll <- adjustment(amat = dag, amat.type = "dag", x = 1, y = 2, set.type = "all")
adjPAll <- adjustment(amat = dag, amat.type = "pdag", x = 1, y = 2, set.type = "all")
stopifnot( !identical(adjCAll, adjDAll), identical(adjDAll, adjPAll) )
adjCMin <- adjustment(amat = cpdag, amat.type = "cpdag", x = 1, y = 2, set.type = "minimal")
adjDMin <- adjustment(amat = dag, amat.type = "dag", x = 1, y = 2, set.type = "minimal")
adjPMin <- adjustment(amat = dag, amat.type = "pdag", x = 1, y = 2, set.type = "minimal")
stopifnot( !identical(adjCMin, adjDMin), identical(adjDMin, adjPMin) )
nreps <- 100
simRes <- data.frame(setType = rep(NA, nreps), id = rep(NA,nreps),
rtCPDAG = rep(NA,nreps), rtPDAG = rep(NA, nreps),
nSet = rep(NA, nreps), gacCheck = rep(NA, nreps))
proc.time()
for (i in 1:nreps) {
cat("i = ",i,"\n")
seed <- i
set.seed(seed)
p <- sample(x=5:10, size = 1)
prob <- sample(x=3:7/10, size = 1)
g <- pcalg:::randomDAG(p, prob)
cpdag <- dag2cpdag(g)
cpdag.mat <- t(as(cpdag,"matrix"))
amat <- cpdag.mat
x <- sample(x = 1:p, size = 1)
y <- sample(x = setdiff(1:p,x), size = 1)
set.type <- sample(x = c("all", "minimal"), size = 1)
simRes$setType[i] <- set.type
simRes$rtCPDAG[i] <- system.time(res1 <- adjustment(amat = amat, amat.type = "cpdag", x = x, y = y, set.type = set.type))[3]
simRes$rtPDAG[i] <- system.time(res2 <- adjustment(amat = amat, amat.type = "pdag", x = x, y = y, set.type = set.type))[3]
simRes$nSet[i] <- length(res1)
if (length(res1) == 0) {
res1 <- vector("list", 0)
}
if (length(res2) == 0) {
res2 <- vector("list", 0)
}
simRes$id[i] <- identical(res1,res2)
if (length(res2) > 0) {
gc <- TRUE
for (j in 1:length(res2)) {
gc <- gc & gac(amat = amat, x = x, y = y, z = res2[[j]], type = "cpdag")$gac
}
simRes$gacCheck[i] <- gc
}
}
proc.time()
summary(simRes)
table(is.na(simRes$gacCheck), simRes$nSet == 0)
gacVSadj <- function(amat, x, y ,z, V, type) {
typeDG <- switch(type,
dag = "dag",
cpdag = "cpdag",
mag = "mag",
pag = "pag")
gacRes <- gac(amat,x,y, z, type)$gac
adjRes <- adjustment(amat = amat, amat.type = typeDG, x = x, y = y, set.type = "all")
if (gacRes) {
res <- any(sapply(adjRes, function(xx) setequal(z, xx)))
} else {
res <- all(!sapply(adjRes, function(xx) setequal(z, xx)))
}
res
}
xx <- TRUE
mFig1 <- matrix(c(0,1,1,0,0,0, 1,0,1,1,1,0, 0,0,0,0,0,1,
0,1,1,0,1,1, 0,1,0,1,0,1, 0,0,0,0,0,0), 6,6)
type <- "cpdag"
x <- 3; y <- 6
V <- as.character(1:ncol(mFig1))
rownames(mFig1) <- colnames(mFig1) <- V
xx <- xx & gacVSadj(mFig1,x,y, z=c(2,4), V=V, type)
xx <- xx & gacVSadj(mFig1,x,y, z=c(4,5), V=V, type)
xx <- xx & gacVSadj(mFig1,x,y, z=c(4,2,1), V=V, type)
xx <- xx & gacVSadj(mFig1,x,y, z=c(4,5,1), V=V, type)
xx <- xx & gacVSadj(mFig1,x,y, z=c(4,2,5), V=V, type)
xx <- xx & gacVSadj(mFig1,x,y, z=c(4,2,5,1), V=V, type)
xx <- xx & gacVSadj(mFig1,x,y, z= 2, V=V, type)
xx <- xx & gacVSadj(mFig1,x,y, z= NULL, V=V, type)
mFig5a <- matrix(c(0,1,0,0,0, 1,0,1,0,0, 0,0,0,0,1, 0,0,1,0,0, 0,0,0,0,0), 5,5)
V <- as.character(1:ncol(mFig5a))
rownames(mFig5a) <- colnames(mFig5a) <- V
type <- "cpdag"
x <- c(1,5); y <- 4
xx <- xx & gacVSadj(mFig5a, x,y, z=c(2,3), V=V, type)
xx <- xx & gacVSadj(mFig5a, x,y, z= 2, V=V, type)
mMMd1 <- matrix(c(0,1,0,1,0,0, 0,0,1,0,1,0, 0,0,0,0,0,1,
0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0),6,6)
V <- as.character(1:ncol(mMMd1))
rownames(mMMd1) <- colnames(mMMd1) <- V
type <- "dag"
x <- 1; y <- 3
xx <- xx & gacVSadj(mMMd1, x,y, z=NULL, V=V, type)
xx <- xx & gacVSadj(mMMd1, x,y, z= 2, V=V, type)
xx <- xx & gacVSadj(mMMd1, x,y, z= 4, V=V, type)
xx <- xx & gacVSadj(mMMd1, x,y, z= 5, V=V, type)
xx <- xx & gacVSadj(mMMd1, x,y, z= 6, V=V, type)
xx <- xx & gacVSadj(mMMd1, x,y, z=c(4,5), V=V, type)
mMMd2 <- matrix(c(0,1,0,1,0,0, 0,0,0,0,0,0, 0,1,0,0,1,0,
0,0,0,0,1,0, 0,0,0,0,0,1, 0,0,0,0,0,0), 6,6)
V <- as.character(1:ncol(mMMd2))
rownames(mMMd2) <- colnames(mMMd2) <- V
type <- "dag"
x <- 4; y <- 6
xx <- xx & gacVSadj(mMMd2, x,y, z= 1, V=V, type)
xx <- xx & gacVSadj(mMMd2, x,y, z= 3, V=V, type)
xx <- xx & gacVSadj(mMMd2, x,y, z= 5, V=V, type)
xx <- xx & gacVSadj(mMMd2, x,y, z=c(1,5), V=V, type)
xx <- xx & gacVSadj(mMMd2, x,y, z=c(1,2), V=V, type)
xx <- xx & gacVSadj(mMMd2, x,y, z=c(1,3), V=V, type)
xx <- xx & gacVSadj(mMMd2, x,y, z= 2, V=V, type)
type <- "pag"
mFig3a <- matrix(c(0,1,0,0, 1,0,1,1, 0,1,0,1, 0,1,1,0), 4,4)
V <- as.character(1:ncol(mFig3a))
rownames(mFig3a) <- colnames(mFig3a) <- V
xx <- xx & gacVSadj(mFig3a, x=2, y=4, z=NULL, V=V, type)
mFig3b <- matrix(c(0,2,0,0, 3,0,3,3, 0,2,0,3, 0,2,2,0), 4,4)
V <- as.character(1:ncol(mFig3b))
rownames(mFig3b) <- colnames(mFig3b) <- V
xx <- xx & gacVSadj(mFig3b, x=2, y=4, z=NULL, V=V, type)
mFig3c <- matrix(c(0,3,0,0, 2,0,3,3, 0,2,0,3, 0,2,2,0), 4,4)
V <- as.character(1:ncol(mFig3c))
rownames(mFig3c) <- colnames(mFig3c) <- V
xx <- xx & gacVSadj(mFig3c, x=2, y=4, z=NULL, V=V, type)
mFig4a <- matrix(c(0,0,1,0,0,0, 0,0,1,0,0,0, 2,2,0,3,3,2,
0,0,2,0,2,2, 0,0,2,1,0,2, 0,0,1,3,3,0), 6,6)
V <- as.character(1:ncol(mFig4a))
rownames(mFig4a) <- colnames(mFig4a) <- V
xx <- xx & gacVSadj(mFig4a, x=3, y=4, z=NULL, V=V, type)
xx <- xx & gacVSadj(mFig4a, x=3, y=4, z= 6, V=V, type)
xx <- xx & gacVSadj(mFig4a, x=3, y=4, z=c(1,6), V=V, type)
xx <- xx & gacVSadj(mFig4a, x=3, y=4, z=c(2,6), V=V, type)
xx <- xx & gacVSadj(mFig4a, x=3, y=4, z=c(1,2,6), V=V, type)
mFig4b <- matrix(c(0,0,1,0,0,0, 0,0,1,0,0,0, 2,2,0,0,3,2,
0,0,0,0,2,2, 0,0,2,3,0,2, 0,0,2,3,2,0), 6,6)
V <- as.character(1:ncol(mFig4b))
rownames(mFig4b) <- colnames(mFig4b) <- V
xx <- xx & gacVSadj(mFig4b, x=3, y=4, z=NULL, V=V, type)
xx <- xx & gacVSadj(mFig4b, x=3, y=4, z= 6, V=V, type)
xx <- xx & gacVSadj(mFig4b, x=3, y=4, z=c(5,6), V=V, type)
mFig5b <- matrix(c(0,1,0,0,0,0,0, 2,0,2,3,0,3,0, 0,1,0,0,0,0,0, 0,2,0,0,3,0,0,
0,0,0,2,0,2,3, 0,2,0,0,2,0,0, 0,0,0,0,2,0,0), 7,7)
V <- as.character(1:ncol(mFig5b))
rownames(mFig5b) <- colnames(mFig5b) <- V
xx <- xx & gacVSadj(mFig5b, x=c(2,7), y=6, z=NULL, V=V, type)
xx <- xx & gacVSadj(mFig5b, x=c(2,7), y=6, z=c(4,5), V=V, type)
xx <- xx & gacVSadj(mFig5b, x=c(2,7), y=6, z=c(4,5,1), V=V, type)
xx <- xx & gacVSadj(mFig5b, x=c(2,7), y=6, z=c(4,5,3), V=V, type)
xx <- xx & gacVSadj(mFig5b, x=c(2,7), y=6, z=c(1,3,4,5), V=V, type)
mMMp <- matrix(c(0,0,0,3,2,0,0, 0,0,0,0,1,0,0, 0,0,0,0,1,0,0, 2,0,0,0,0,3,2,
3,2,2,0,0,0,3, 0,0,0,2,0,0,0, 0,0,0,2,2,0,0), 7,7)
V <- as.character(1:ncol(mMMp))
rownames(mMMp) <- colnames(mMMp) <- V
x <- c(5,6); y <- 7
xx <- xx & gacVSadj(mMMp, x,y, z=NULL, V=V, type)
xx <- xx & gacVSadj(mMMp, x,y, z= 1, V=V, type)
xx <- xx & gacVSadj(mMMp, x,y, z= 4, V=V, type)
xx <- xx & gacVSadj(mMMp, x,y, z= 2, V=V, type)
xx <- xx & gacVSadj(mMMp, x,y, z= 3, V=V, type)
xx <- xx & gacVSadj(mMMp, x,y, z=c(2,3), V=V, type)
xx <- xx & gacVSadj(mMMp, x,y, z=c(1,4), V=V, type)
xx <- xx & gacVSadj(mMMp, x,y, z=c(1,4,2), V=V, type)
xx <- xx & gacVSadj(mMMp, x,y, z=c(1,4,3), V=V, type)
xx <- xx & gacVSadj(mMMp, x,y, z=c(1,4,2,3), V=V, type)
type <- "pag"
pag.m <- readRDS(system.file(package="pcalg", "external", "gac-pags.rds"))
m1 <- pag.m[["m1"]]
V <- colnames(m1)
x <- 6; y <- 9
xx <- xx & gacVSadj(m1,x,y, z=NULL, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=1, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=2, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=3, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=4, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,3), V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,3,8), V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,3,7,8), V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,3,5,8), V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,3,5,7,8), V=V, type)
x <- c(6,8); y <- 9
xx <- xx & gacVSadj(m1,x,y, z=NULL, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=1, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=2, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=3, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=4, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,3), V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,3,4), V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,3,7), V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,3,5), V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,3,5,7), V=V, type)
x <- 3; y <- 1
xx <- xx & gacVSadj(m1,x,y, z=NULL, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=2, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=4, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=5, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=6, V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,6), V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,8), V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,7,8), V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,5,8), V=V, type)
xx <- xx & gacVSadj(m1,x,y, z=c(2,5,7,8), V=V, type)
m2 <- pag.m[["m2"]]
V <- colnames(m2)
x <- 3; y <-1
xx <- xx & gacVSadj(m2,x,y, z=NULL, V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=2, V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=4, V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=c(2,8), V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=8, V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=9, V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=c(2,8,9), V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=c(2,5), V=V, type)
x <- c(3,9); y <- 1
xx <- xx & gacVSadj(m2,x,y, z=NULL, V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=2, V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=4, V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=c(2,8), V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=8, V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=9, V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=c(2,8,9), V=V, type)
xx <- xx & gacVSadj(m2,x,y, z=c(2,5), V=V, type)
m3 <- pag.m[["m3"]]
V <- colnames(m3)
x <- 1; y <- 9
xx <- xx & gacVSadj(m3,x,y, z=NULL, V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=2, V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=3, V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=5, V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=7, V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=8, V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=c(2,3), V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=c(5,7), V=V, type)
x <- 1; y <- 8
xx <- xx & gacVSadj(m3,x,y, z=NULL, V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=2, V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=3, V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=5, V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=7, V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=9, V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=c(2,3), V=V, type)
xx <- xx & gacVSadj(m3,x,y, z=c(5,9), V=V, type)
if (!xx) {
stop("Problem when testing function gacVSadj.")
} else {
message("OK, no issues were found.")
}
m <- rbind(c(0,1,0,0,0,0),
c(1,0,1,0,0,0),
c(0,1,0,0,0,0),
c(0,0,0,0,0,0),
c(0,1,1,1,0,0),
c(1,0,1,1,1,0))
colnames(m) <- rownames(m) <- as.character(1:6)
res1 <- adjustment(m,amat.type="cpdag",2,4,set.type="canonical")
res2 <- adjustment(m,amat.type="pdag",2,4,set.type="canonical")
if (!all.equal(res1, res2)) {
stop("Canonical set is not the same for type=cpdag and type=pdag\n")
}
}
else {
cat("doExtras is OFF\n")
}
} |
get_transformation <- function(x) {
transform_fun <- find_transformation(x)
if (transform_fun == "identity") {
out <- list(transformation = function(x) x, inverse = function(x) x)
} else if (transform_fun == "log") {
out <- list(transformation = log, inverse = exp)
} else if (transform_fun %in% c("log1p", "log(x+1)")) {
out <- list(transformation = log1p, inverse = expm1)
} else if (transform_fun == "exp") {
out <- list(transformation = exp, inverse = log)
} else if (transform_fun == "sqrt") {
out <- list(transformation = sqrt, inverse = function(x) x^2)
} else if (transform_fun == "expm1") {
out <- list(transformation = expm1, inverse = log1p)
} else if (transform_fun == "log-log") {
out <- list(
transformation = function(x) log(log(x)),
inverse = function(x) exp(exp(x))
)
}
out
} |
predict_apc<-function(object, periods=0, population=NULL, quantiles=c(0.05,0.5,0.95), update=FALSE){
ksi_prognose <-
function(prepi, vdb, noa, nop, nop2, noc, zmode){
my<-prepi[1]
theta<-prepi[2:(noa+1)]
phi<-prepi[(noa+2):(noa+nop2+1)]
psi<-prepi[(noa+nop2+2):(noa+nop2+noc+1)]
delta<-prepi[noa+nop2+noc+2]
ksi<-array(0, c(nop2,noa))
for(i in 1:noa){
for(j in 1:nop2){
ksi[j,i] <- my + theta[i] + phi[j] + psi[bamp::coh(i,j,noa,vdb)]
if(zmode){
ksi[j,i] <- ksi[j,i] + (rnorm(1, mean = 0, sd = 1)/sqrt(delta))
}
}
}
return(ksi)
}
predict_rw <-
function(prepi, rw, n1, n2){
lambda<-prepi[1]
phi<-prepi[-1]
if(rw == 1){
for(i in (n1+1):n2){
phi[i] <- (rnorm(1, mean = 0, sd = 1)/sqrt(lambda)) + phi[i-1]
}
}
if(rw == 2){
for(i in (n1+1):n2){
phi[i] <- (rnorm(1, mean = 0, sd = 1)/sqrt(lambda)) + (2*phi[i-1] - phi[i-2])
}
}
if(rw == 0){
for(i in (n1+1):n2){
phi[i] <- phi[i-1]
}
}
return(phi)
}
phi<-psi<-NA
a1<-dim(object$data$cases)[1]
n1<-dim(object$data$cases)[2]
n2<-n1+periods
rwp<-rwc<-0
if (!object$model$period=="")
{
rwp<-switch(object$model$period,
rw1 = 1,
rw2 = 2
)
ch<-length(object$samples$period)
prep<-parallel::mclapply(1:ch, function(i,samples)cbind(object$samples$period_parameter[[i]],object$samples$period[[i]]), samples)
phi<-parallel::mclapply(prep, function(prepi, rw, n1, n2){t(apply(prepi, 1, predict_rw, rw, n1, n2))}, rwp, n1, n2)
}
if (!object$model$cohort=="")
{
rwc<-switch(object$model$cohort,
rw1 = 1,
rw2 = 2
)
c1<-dim(object$samples$cohort[[1]])[2]
c2<-bamp::coh(1,n2,a1,object$data$periods_per_agegroup)
ch<-length(object$samples$cohort)
prep<-parallel::mclapply(1:ch, function(i,samples)cbind(object$samples$cohort_parameter[[i]],object$samples$cohort[[i]]), samples)
psi<-parallel::mclapply(prep, function(prepi, rw, n1, n2){t(apply(prepi, 1, predict_rw, rw, n1, n2))}, rwc, c1, c2)
}
nr.samples<-length(object$samples$intercept[[1]])
theta<-if(object$model$age!=""){object$samples$age}else{NA}
delta<-if(object$model$overdispersion){object$samples$overdispersion}else{NA}
prepfx<- function(i, theta, phi, psi, my, delta, a1, n1, c1, nr){
theta=if(any(is.na(theta))){array(0, c(nr, a1))}else{theta[[i]]}
phi=if(any(is.na(phi))){array(0, c(nr, a1))}else{phi[[i]]}
psi=if(any(is.na(psi))){array(0, c(nr, a1))}else{psi[[i]]}
my=my[[i]]
delta=if(any(is.na(delta))){rep(0, nr)}else{delta[[i]]}
return(cbind(my,theta,phi,psi, delta))
}
prep<- parallel::mclapply(1:ch, prepfx, theta, phi, psi, object$samples$intercept, delta, a1, n1, c1, nr.samples)
ksi<-parallel::mclapply(prep, function(prepi, vdb, noa, nop, nop2, noc, zmode){
temp<-apply(prepi, 1, ksi_prognose, vdb, noa, nop, nop2, noc, zmode); return(array(temp,c(nop2,noa,dim(temp)[2])))}, object$data$periods_per_agegroup,
a1, n1, n2, c2, object$model$overdispersion)
ksi0<-ksi[[1]]
if (ch>1)
for (i in 2:ch)
{
ksi0<-abind::abind(ksi0,ksi[[i]], along=3)
}
pr <- exp(ksi0)/(1+exp(ksi0))
if (is.null(population))population<-object$data$population
n0<-min(dim(population)[1],n2)
predictedcases <- array(apply(pr,3,function(pr1,n,n0){
return(rbinom(n0*dim(n)[2],n[1:n0,],pr1[1:n0,]))},population,n0),c(n0,dim(pr)[2:3]))
predictperiod<-apply(predictedcases,c(1,3),sum)
qu_predicted_cases<-apply(predictedcases,1:2,quantile,quantiles)
qu_predicted_pr<-apply(pr,1:2,quantile,quantiles)
qu_predictperiod<-apply(predictperiod,1,quantile,quantiles)
period<-phi[[1]]
if (ch>1)
for (i in 2:ch)
period<-abind::abind(period,phi[[i]], along=1)
cohort<-psi[[1]]
if (ch>1)
for (i in 2:ch)
cohort<-abind::abind(cohort,psi[[i]], along=1)
samples<-list(
"pr"=pr,
"cases"=predictedcases,
"cases_period"=predictperiod,
"period"=period,
"cohort"=cohort
)
predicted<-list(
"pr"=qu_predicted_pr,
"cases"=qu_predicted_cases,
"cases_period"=qu_predictperiod,
"period"=apply(period,2,quantile,quantiles),
"cohort"=apply(cohort,2,quantile,quantiles),
"samples"=samples
)
if (!update){
return(predicted)}
else{
object$predicted=predicted
return(object)
}
} |
getResponse <- function(object, ...) UseMethod("getResponse")
getResponse.default <- function(object, ...) {
if (is.list(object)) {
return(object$x)
} else {
return(NULL)
}
}
getResponse.lm <- function(object, ...) {
if(!is.null(object[["x"]])){
object[["x"]]
}
else{
responsevar <- deparse(formula(object)[[2]])
model.frame(object$model)[, responsevar]
}
}
getResponse.Arima <- function(object, ...) {
if (is.element("x", names(object))) {
x <- object$x
} else {
series.name <- object$series
if (is.null(series.name)) {
return(NULL)
} else {
x <- try(eval.parent(parse(text = series.name)), silent = TRUE)
if (is.element("try-error", class(x))) {
x <- try(eval.parent(parse(text = series.name), 2), silent = TRUE)
}
if (is.element("try-error", class(x))) {
return(NULL)
}
}
}
return(as.ts(x))
}
getResponse.fracdiff <- function(object, ...) {
if (is.element("x", names(object))) {
x <- object$x
} else {
series.name <- as.character(object$call)[2]
if (is.null(series.name)) {
stop("missing original time series")
} else {
x <- try(eval.parent(parse(text = series.name)), silent = TRUE)
if (is.element("try-error", class(x))) {
x <- try(eval.parent(parse(text = series.name), 2), silent = TRUE)
}
if (is.element("try-error", class(x))) {
return(NULL)
}
}
}
return(as.ts(x))
}
getResponse.ar <- function(object, ...) {
getResponse.Arima(object)
}
getResponse.tbats <- function(object, ...) {
if (is.element("y", names(object))) {
y <- object$y
} else {
return(NULL)
}
return(as.ts(y))
}
getResponse.bats <- function(object, ...) {
return(getResponse.tbats(object, ...))
}
getResponse.mforecast <- function(object, ...) {
return(do.call(cbind, lapply(object$forecast, function(x) x$x)))
}
getResponse.baggedModel <- function(object, ...) {
if (is.element("y", names(object))) {
y <- object$y
} else {
return(NULL)
}
return(as.ts(y))
} |
print.med1way <-
function(x,...)
{
cat("Call:\n")
print(x$call)
cat("\nTest statistic F:", round(x$test, 4),"\n")
if (!is.na(x$crit.val)) cat("Critical value:", round(x$crit.val, 4),"\n")
cat("p-value:", round(x$p.value, 5), "\n")
cat("\n")
} |
context("stack")
test_that("stack pops first element as list", {
s <- stack()
r <- as.list(stats::rnorm(5))
s <- insert(s, r)
expect_equal(pop(s), r[[5]], tolerance = 0.1)
})
test_that("stack peeks first elemen as list", {
s <- stack()
r <- as.list(stats::rnorm(5))
s <- insert(s, r)
expect_equal(peek(s), r[[5]], tolerance = 0.1)
})
test_that("stack peeks first element vectorial", {
q <- stack()
r <- stats::rnorm(5)
q <- insert(q, r)
expect_equal(peek(q), r, tolerance = 0.1)
})
test_that("stack pops first element vectorial", {
q <- stack()
r <- stats::rnorm(5)
q <- insert(q, r)
expect_equal(pop(q), r, tolerance = 0.1)
})
test_that("stack peeks first element multiple elements in list", {
q <- stack()
r <- stats::rnorm(5)
q <- insert(q, list(r, 1))
expect_equal(peek(q), 1, tolerance = 0.1)
})
test_that("stack pop first element multiple elements in list", {
q <- stack()
r <- stats::rnorm(5)
q <- insert(q, list(r, 1))
expect_equal(pop(q), 1, tolerance = 0.1)
})
test_that("stack pop first element multiple elements in list", {
q <- stack()
r <- stats::rnorm(5)
q <- insert(q, list(r, 1))
expect_equal(pop(q), 1, tolerance = 0.1)
})
test_that("stack can handle different values", {
q <- stack()
q <- insert(q, list(2, 1))
q <- insert(q, data.frame(A = 1))
q <- insert(q, rnorm(10))
expect_equal(length(pop(q)), 10)
expect_true(is.data.frame(pop(q)))
expect_equal(pop(q), 1)
expect_equal(pop(q), 2)
}) |
rcelllpp <- local({
rcelllpp <- function(L, lambda, rnumgen=NULL, ..., saveid=FALSE) {
if(inherits(L, "lintess")) {
LT <- L
L <- as.linnet(LT)
} else if(inherits(L, "linnet")) {
ns <- nsegments(L)
df <- data.frame(seg=1:ns, t0=0, t1=1, tile=1:ns)
LT <- lintess(L, df)
} else stop("L should be a linnet or lintess")
df <- LT$df
df$len <- lengths_psp(as.psp(L))[df$seg]
st <- by(df, df$tile, addpoints, lambda=lambda, rnumgen=rnumgen, ...)
st <- Reduce(rbind, st)
X <- lpp(st, L)
if(saveid)
attr(X, "cellid") <- marks(cut(X, LT))
return(X)
}
addpoints <- function(df, lambda=1, rnumgen=NULL, ...) {
piecelengths <- df$len
tilelength <- sum(piecelengths)
mu <- tilelength * lambda
n <- if(is.null(rnumgen)) rcellnumber(1, mu=mu) else rnumgen(1, mu, ...)
if(n == 0)
return(data.frame(seg=integer(0), tp=numeric(0)))
u <- runif(n, max=tilelength)
csp <- c(0, cumsum(piecelengths))
i <- findInterval(u, csp, rightmost.closed=TRUE, all.inside=TRUE)
seg <- df$seg[i]
tp <- df$t0[i] + (df$t1 - df$t0)[i] * (u - csp[i])/piecelengths[i]
return(data.frame(seg=seg, tp=tp))
}
rcelllpp
})
rSwitzerlpp <- local({
rSwitzerlpp <- function(L, lambdacut, rintens=rexp, ...,
cuts=c("points", "lines")) {
stopifnot(inherits(L, "linnet"))
cuts <- match.arg(cuts)
switch(cuts,
points = {
X <- rpoislpp(lambdacut, L)
LT <- divide.linnet(X)
},
lines = {
X <- rpoisline(lambdacut, L)
X <- attr(X, "lines")
LT <- chop.linnet(L, X)
})
Z <- rcelllpp(LT, 1, rNswitzer, rintens=rintens, ...)
attr(Z, "breaks") <- X
return(Z)
}
rNswitzer <- function(n, mu, rintens=rexp, ...) {
rpois(n, mu * rintens(n, ...))
}
rSwitzerlpp
})
|
fuzzy.signrank.ci <- function(x,
alternative = c("two.sided", "less", "greater"),
tol = sqrt(.Machine$double.eps), conf.level = 0.95)
{
alternative <- match.arg(alternative)
if (! is.numeric(x))
stop("'x' must be numeric")
if (! all(is.finite(x)))
stop("'x' must be all finite")
if (! is.numeric(tol))
stop("'tol' must be numeric")
if (length(tol) != 1)
stop("'tol' must be a single number")
if (! is.finite(tol))
stop("'tol' must be finite")
if (tol < 0.0)
stop("'tol' must be nonnegative")
if (! is.numeric(conf.level))
stop("'conf.level' must be numeric")
if (length(conf.level) != 1)
stop("'conf.level' must be a single number")
if (! (is.finite(conf.level) & 0 <= conf.level & conf.level <= 1))
stop("'conf.level' must satisfy 0 <= conf.level <= 1")
alpha <- 1 - conf.level
dname <- deparse(substitute(x))
nx <- length(x)
N <- nx * (nx + 1) / 2
w <- outer(x, x, "+") / 2
w <- sort(w[lower.tri(w, diag = TRUE)])
if (conf.level == 0 || conf.level == 1) {
whyknots <- c(-Inf, Inf)
kvalues <- rep(NA, 2)
ivalues <- conf.level
} else {
if (alternative == "two.sided") {
m <- qsignrank(alpha / 2, nx)
while (alpha <= 2 * psignrank(m - 1, nx))
m <- m - 1
while (alpha > 2 * psignrank(m, nx))
m <- m + 1
if (m > N / 2)
m <- floor(N / 2)
if (m > 0)
whyknots <- c(w[m], w[m + 1], w[N - m], w[N - m + 1])
else
whyknots <- c(-Inf, w[m + 1], w[N - m], Inf)
gdenom <- dsignrank(m, nx)
if (m < N - m)
gdenom <- 2 * gdenom
if (m + 1 < N - m) {
gnumer <- 2 * psignrank(m, nx) - alpha
} else {
gnumer <- conf.level
}
g <- gnumer / gdenom
ivalues <- c(g, 1, g)
i <- 1
while (i <= length(ivalues)) {
if (whyknots[i] + tol >= whyknots[i + 1]) {
whyknots <- whyknots[- (i + 1)]
ivalues <- ivalues[- i]
} else {
i <- i + 1
}
}
kvalues <- rep(NA, length(whyknots))
for (i in 1:length(whyknots)) {
if (! is.finite(whyknots[i])) {
kvalues[i] <- NA
} else {
kvalues[i] <- 1 - fuzzy.signrank.test(x,
alternative = alternative,
mu = whyknots[i], tol = 0, alpha = alpha)$reject
}
}
} else {
m <- qsignrank(alpha, nx)
while (alpha <= psignrank(m - 1, nx))
m <- m - 1
while (alpha > psignrank(m, nx))
m <- m + 1
if (m > N)
m <- N
gdenom <- dsignrank(m, nx)
gnumer <- psignrank(m, nx) - alpha
g <- gnumer / gdenom
if (alternative == "less") {
if (m > 0)
whyknots <- c(-Inf, w[N - m], w[N - m + 1])
else
whyknots <- c(-Inf, w[N - m], Inf)
ivalues <- c(1, g)
} else {
if (m > 0)
whyknots <- c(w[m], w[m + 1], Inf)
else
whyknots <- c(-Inf, w[m + 1], Inf)
ivalues <- c(g, 1)
}
i <- 1
while (i <= length(ivalues)) {
if (whyknots[i] + tol >= whyknots[i + 1]) {
whyknots <- whyknots[- (i + 1)]
ivalues <- ivalues[- i]
} else {
i <- i + 1
}
}
kvalues <- rep(NA, length(whyknots))
for (i in 1:length(whyknots)) {
if (! is.finite(whyknots[i])) {
kvalues[i] <- NA
} else {
kvalues[i] <- 1 - fuzzy.signrank.test(x,
alternative = alternative,
mu = whyknots[i], tol = 0, alpha = alpha)$reject
}
}
}
}
method <- "Wilcoxon signed rank test"
foo <- list(knots = whyknots, knot.values = kvalues,
interval.values = ivalues, alternative = alternative,
method = method, data.name = dname, conf.level = conf.level,
tol = tol)
return(structure(foo, class = "fuzzyrankci"))
} |
library(gt)
library(tidyverse)
library(png)
library(webshot)
library(here)
get_package_docs <- function(pkg) {
help_dir <- system.file("help", package = pkg)
db_path <- file.path(help_dir, pkg)
tools:::fetchRdDB(db_path)
}
fn_names <- get_package_docs(pkg = "gt") %>% names()
name_exclusions <-
c(
"as.data.frame.gt_tbl",
"as_latex",
"as_raw_html",
"as_rtf",
"cells_data",
"cells_group",
"countrypops",
"escape_latex",
"gt-options",
"gt-package",
"gt_latex_dependencies",
"gt_output",
"gtcars",
"gtsave",
"pipe",
"pizzaplace",
"print.gt_tbl",
"random_id",
"reexports",
"render_gt",
"sp500",
"sza",
"test_image"
)
fn_names <- fn_names %>% base::setdiff(name_exclusions)
image_width <- 1100
temp_dir <- paste0(tempdir(), random_id())
dir.create(temp_dir, showWarnings = FALSE)
rm(list = ls(pattern = "^tab_[0-9]*?$"))
for (fn_name in fn_names) {
utils::example(topic = fn_name, package = "gt", character.only = TRUE, give.lines = FALSE, echo = FALSE)
tab_obj <- ls(pattern = "^tab_[0-9]*?$")
for (i in seq_along(tab_obj)) {
if (!inherits(get(tab_obj[i]), "gt_tbl")) stop("All `tab_
filename <- file.path(temp_dir, paste0("man_", fn_name, "_", i, ".png"))
gt:::gt_save_webshot(data = get(tab_obj[i]), filename = filename, zoom = 3) %>% webshot::resize("50%")
image_dim <- readPNG(filename) %>% dim()
if (image_dim[2] > image_width) eff_image_x <- image_dim[2] else eff_image_x <- image_width
if (image_dim[1] >= 1500) eff_image_y <- 1500 else eff_image_y <- image_dim[1]
system(glue::glue("convert {shQuote(filename)} -gravity center -extent {eff_image_x}x{eff_image_y} {shQuote(filename)}"))
}
rm(list = tab_obj)
}
png_list <- list.files(temp_dir, ".*\\.png$")
webshot::shrink(filename = file.path(temp_dir, png_list))
system(glue::glue("cd {shQuote(temp_dir)}; pngquant --force --ext=.png --skip-if-larger --nofs --speed 1 *.png"))
file.copy(file.path(temp_dir, png_list), here::here("man", "figures", png_list), overwrite = TRUE) |
build_spm12_first_level = function(
...,
outdir = NULL,
est_args = list(
write_residuals = FALSE,
method = "Classical",
bayesian = NULL),
verbose = TRUE
) {
spec_out = build_spm12_first_level_spec(
verbose = TRUE,
outdir = outdir,
...
)
spm_mat = spec_out$spm_mat
spm = spec_out$spm
est_args$spm = spm_mat
est_out = do.call(
"build_spm12_fmri_est",
args = est_args)
out_spm = list(spm,
est_out$spm)
names(out_spm) = c("{1}", "{2}")
class(out_spm) = "matlabbatch"
script = matlabbatch_to_script(
out_spm,
batch_prefix = "matlabbatch")
L = list(
spm = out_spm,
script = script
)
L$spmmat = spm_mat
L$outdir = spec_out$outdir
return(L)
}
spm12_first_level = function(
...,
outdir = NULL,
est_args = list(
write_residuals = FALSE,
method = "Classical",
bayesian = NULL),
add_spm_dir = TRUE,
spmdir = spm_dir(verbose = verbose,
install_dir = install_dir),
clean = TRUE,
verbose = TRUE,
install_dir = NULL
) {
if (is.null(outdir)) {
outdir = tempfile()
dir.create(outdir, showWarnings = FALSE)
}
L = build_spm12_first_level(
...,
outdir = outdir,
est_args = est_args,
verbose = verbose)
spm = L$spm
if (verbose) {
message("
}
res = run_matlabbatch(
spm,
add_spm_dir = add_spm_dir,
clean = clean,
verbose = verbose,
spmdir = spmdir,
batch_prefix = "matlabbatch")
L$result = res
if (res != 0) {
warning("Result was not zero!")
}
outfiles = list.files(
pattern = "beta_.*[.]nii$",
path = outdir,
full.names = TRUE
)
L$outfiles = outfiles
return(L)
} |
context("plot_pxg")
test_that("plot_pxg works", {
skip_if(isnt_karl(), "plot tests only run locally")
iron <- read_cross2(system.file("extdata", "iron.zip", package="qtl2"))
map <- insert_pseudomarkers(iron$gmap, step=1)
probs <- calc_genoprob(iron, map, error_prob=0.002)
set.seed(62610474)
geno <- maxmarg(probs, map, chr=16, pos=28.6, return_char=TRUE)
test_plot_pxg <- function() plot_pxg(geno, log10(iron$pheno[,1]), ylab="log liver")
expect_doppelganger("plot_pxg", test_plot_pxg)
test_plot_pxg_se <- function() plot_pxg(geno, log10(iron$pheno[,1]), ylab="log liver", SEmult=2)
expect_doppelganger("plot_pxg_se", test_plot_pxg_se)
}) |
context("Copulas' test")
library(volesti)
test_that("10-dimensional 2-hyp_fam copula", {
h1 = h1 = runif(n = 10, min = 1, max = 1000)
h1 = h1 / 1000
h2 = h2 = runif(n = 10, min = 1, max = 1000)
h2 = h1 / 1000
cop = copula(r1 = h1 , r2 = h2 , m = 10, n = 100000)
res = sum(cop)
expect_equal(res, 1)
})
test_that("20-dimensional 1_hyp_1_ell fam copula", {
h = h = runif(n = 20, min = 1, max = 1000)
h = h / 1000
E = replicate(20, rnorm(30))
E = cov(E)
cop = copula(r1 = h , sigma = E , m = 100, n = 100000)
res = sum(cop)
expect_equal(res, 1)
}) |
library(testthat)
library(rly)
context("Tests for absence of tokens variable")
Lexer <- R6::R6Class("Lexer",
public = list(
t_PLUS = '\\+',
t_MINUS = '-',
t_NUMBER = '\\d+',
t_ignore = " \t",
t_error = function(t) { }
)
)
test_that("comment", {
expect_output(expect_error(rly::lex(Lexer), "Can't build lexer"),
"ERROR .* No token list is defined")
}) |
library("surveillance")
message("Doing computations: ",
COMPUTE <- !file.exists("twinstim-cache.RData"))
if (!COMPUTE) load("twinstim-cache.RData", verbose = TRUE)
data("imdepi")
events <- SpatialPointsDataFrame(
coords = coordinates(imdepi$events),
data = marks(imdepi, coords=FALSE),
proj4string = imdepi$events@proj4string
)
stgrid <- imdepi$stgrid[,-1]
load(system.file("shapes", "districtsD.RData", package = "surveillance"))
summary(events)
.stgrid.excerpt <- format(rbind(head(stgrid, 3), tail(stgrid, 3)), digits=3)
rbind(.stgrid.excerpt[1:3,], "..."="...", .stgrid.excerpt[4:6,])
imdepi
(simdepi <- summary(imdepi))
par(mar = c(5, 5, 1, 1), las = 1)
plot(as.stepfun(imdepi), xlim = summary(imdepi)$timeRange, xaxs = "i",
xlab = "Time [days]", ylab = "Current number of infectives", main = "")
par(las = 1)
plot(imdepi, "time", col = c("indianred", "darkblue"), ylim = c(0, 20))
par(mar = c(0, 0, 0, 0))
plot(imdepi, "space", lwd = 2,
points.args = list(pch = c(1, 19), col = c("indianred", "darkblue")))
layout.scalebar(imdepi$W, scale = 100, labels = c("0", "100 km"), plot = TRUE)
eventDists <- dist(coordinates(imdepi$events))
minsep <- min(eventDists[eventDists > 0])
set.seed(321)
imdepi_untied <- untie(imdepi, amount = list(s = minsep / 2))
imdepi_untied_infeps <- update(imdepi_untied, eps.s = Inf)
imdsts <- epidataCS2sts(imdepi, freq = 12, start = c(2002, 1), tiles = districtsD)
par(las = 1, lab = c(7,7,7), mar = c(5,5,1,1))
plot(imdsts, type = observed ~ time)
plot(imdsts, type = observed ~ unit, population = districtsD$POPULATION / 100000)
(endemic <- addSeason2formula(~offset(log(popdensity)) + I(start / 365 - 3.5),
period = 365, timevar = "start"))
imdfit_endemic <- twinstim(endemic = endemic, epidemic = ~0,
data = imdepi_untied, subset = !is.na(agegrp))
summary(imdfit_endemic)
print(xtable(imdfit_Gaussian,
caption="Estimated rate ratios (RR) and associated Wald confidence intervals (CI) for endemic (\\code{h.}) and epidemic (\\code{e.}) terms. This table was generated by \\code{xtable(imdfit\\_Gaussian)}.",
label="tab:imdfit_Gaussian"),
sanitize.text.function=NULL, sanitize.colnames.function=NULL,
sanitize.rownames.function=function(x) paste0("\\code{", x, "}"))
R0_events <- R0(imdfit_Gaussian)
tapply(R0_events, marks(imdepi_untied)[names(R0_events), "type"], mean)
par(mar = c(5,5,1,1))
set.seed(2)
plot(imdfit_Gaussian, "siaf", xlim=c(0,42), ylim=c(0,5e-5), lty=c(1,3),
xlab = expression("Distance " * x * " from host [km]"))
plot(imdfit_exponential, "siaf", add=TRUE, col.estimate=5, lty = c(5,3))
plot(imdfit_powerlaw, "siaf", add=TRUE, col.estimate=4, lty=c(2,3))
plot(imdfit_step4, "siaf", add=TRUE, col.estimate=3, lty=c(4,3))
legend("topright", legend=c("Power law", "Exponential", "Gaussian", "Step (df=4)"),
col=c(4,5,2,3), lty=c(2,5,1,4), lwd=3, bty="n")
exp(cbind("Estimate" = coef(imdfit_Gaussian)["e.siaf.1"],
confint(imdfit_Gaussian, parm = "e.siaf.1")))
exp(cbind("Estimate" = coef(imdfit_powerlaw)[c("e.siaf.1", "e.siaf.2")],
confint(imdfit_powerlaw, parm = c("e.siaf.1", "e.siaf.2"))))
quantile(getSourceDists(imdepi_untied_infeps, "space"), c(1,2,4,8)/100)
AIC(imdfit_endemic, imdfit_Gaussian, imdfit_exponential, imdfit_powerlaw, imdfit_step4)
imdfit_endemic_sel <- stepComponent(imdfit_endemic, component = "endemic")
imdfit_powerlaw <- update(imdfit_powerlaw, model = TRUE)
par(mar = c(5,5,1,1), las = 1)
intensity_endprop <- intensityplot(imdfit_powerlaw, aggregate="time",
which="endemic proportion", plot=FALSE)
intensity_total <- intensityplot(imdfit_powerlaw, aggregate="time",
which="total", tgrid=501, lwd=2,
xlab="Time [days]", ylab="Intensity")
curve(intensity_endprop(x) * intensity_total(x), add=TRUE, col=2, lwd=2, n=501)
text(2500, 0.36, labels="total", col=1, pos=2, font=2)
text(2500, 0.08, labels="endemic", col=2, pos=2, font=2)
for (.type in 1:2) {
print(intensityplot(imdfit_powerlaw, aggregate="space", which="epidemic proportion",
types=.type, tiles=districtsD, sgrid=1000,
col.regions = grey(seq(1,0,length.out=10)), at = seq(0,1,by=0.1)))
grid::grid.text("Epidemic proportion", x=1, rot=90, vjust=-1)
}
par(mar = c(5, 5, 1, 1))
checkResidualProcess(imdfit_powerlaw)
imdsim <- simulate(imdfit_powerlaw, nsim = 1, seed = 1, t0 = 2191, T = 2555,
data = imdepi_untied_infeps, tiles = districtsD)
.t0 <- imdsim$timeRange[1]
.cumoffset <- c(table(subset(imdepi, time < .t0)$events$type))
par(mar = c(5,5,1,1), las = 1)
plot(imdepi, ylim = c(0, 20), col = c("indianred", "darkblue"),
subset = time < .t0, cumulative = list(maxat = 336),
xlab = "Time [days]")
plot(imdsim, add = TRUE, legend.types = FALSE,
col = adjustcolor(c("indianred", "darkblue"), alpha.f = 0.5),
subset = !is.na(source),
cumulative = list(offset = .cumoffset, maxat = 336, axis = FALSE),
border = NA, density = 0)
plot(imdepi, add = TRUE, legend.types = FALSE,
col = 1, subset = time >= .t0,
cumulative = list(offset = .cumoffset, maxat = 336, axis = FALSE),
border = NA, density = 0)
abline(v = .t0, lty = 2, lwd = 2)
table(imdsim$events$source > 0, exclude = NULL) |
library(MASS)
library(ISLR)
data(Boston)
names(Boston)
?Boston
plot(medv~lstat, Boston)
fit1<-lm(medv~lstat, Boston)
fit1
summary(fit1)
abline(fit1,col="red")
names(fit1)
fit1$coefficients
confint(fit1)
predict(fit1,data.frame(lstat=c(5,10,15)),interval="confidence")
fit2<-lm(medv~lstat+age,data=Boston)
summary(fit2)
plot(fit2$residuals)
plot(fitted(fit2),fit2$residuals)
hist(fit2$residuals)
fit3<-lm(medv~.,data=Boston)
summary(fit3)
par(mfrow=c(2,2))
plot(fit3)
hist(fit3$residuals)
par(mfrow=c(1,1))
plot(fitted(fit3),fit3$residuals)
fit4<- update(fit3,~.-age-indus)
summary(fit4)
fit5<-lm(medv~lstat*age, Boston)
summary(fit5)
fit6<-lm(medv~lstat+ I(lstat^2), Boston)
summary(fit6)
plot(fit6)
attach(Boston)
par(mfrow=c(1,1))
plot(medv~lstat)
points(lstat,fitted(fit6),col="red",pch=20)
fit7<-lm(medv~poly(lstat,4))
points(lstat,fitted(fit7),col="blue",pch=20)
plot(1:20,1:20,pch=1:20,cex=2)
fix(Carseats)
names(Carseats)
summary(Carseats)
fit8<-lm(Sales~.+Income*Advertising+Age:Price,data=Carseats)
summary(fit8)
contrasts(Carseats$ShelveLoc) |
testthat::context("apply_theme - T1. The `define_theme()` function returns a `visR_theme` object can contain valid input parameters for `apply_theme()`.")
testthat::test_that("T1.1 No error when no parameters are specified.", {
testthat::expect_error(visR::define_theme(), NA)
})
testthat::test_that("T1.2 Not specifying any parameters returns a list.", {
theme <- visR::define_theme()
testthat::expect_true(is.list(theme))
})
testthat::test_that("T1.3 No error when `strata` is `NULL`.", {
testthat::expect_error(visR::define_theme(strata = NULL), NA)
})
testthat::test_that("T1.4 A warning when `strata` is an empty `list`.", {
testthat::expect_warning(visR::define_theme(strata = list()))
})
testthat::test_that("T1.5 A warning when `strata` is an unnamed `list`.", {
testthat::expect_warning(visR::define_theme(strata = list("v", "i", "s", "R")))
})
testthat::test_that("T1.6 No warning when `strata` is a named `list`.", {
testthat::expect_warning(visR::define_theme(strata = list("visR" = "visR")), NA)
})
testthat::test_that("T1.7 No error when `fontsizes` is `NULL`.", {
testthat::expect_error(visR::define_theme(fontsizes = NULL), NA)
})
testthat::test_that("T1.8 A warning when `fontsizes` is an empty `list`.", {
testthat::expect_warning(visR::define_theme(fontsizes = list()))
})
testthat::test_that("T1.9 A warning when `fontsizes` is an unnamed `list`.", {
testthat::expect_warning(visR::define_theme(fontsizes = list("v", "i", "s", "R")))
})
testthat::test_that("T1.10 No warning when `fontsizes` is a named `list`.", {
testthat::expect_warning(visR::define_theme(fontsizes = list("visR" = "visR")), NA)
})
testthat::test_that("T1.11 A message when `fontsizes` is a numerical value.", {
testthat::expect_message(visR::define_theme(fontsizes = 12))
})
testthat::test_that("T1.12 A warning when `fontsizes` is neither `NULL`, a `list` or a `numeric`.", {
testthat::expect_warning(visR::define_theme(fontsizes = "visR"))
})
testthat::test_that("T1.13 No error when `fontfamily` is a string.", {
testthat::expect_error(visR::define_theme(fontfamily = "Times"), NA)
})
testthat::test_that("T1.14 A warning when `fontfamily` is an empty string.", {
testthat::expect_warning(visR::define_theme(fontfamily = ""))
testthat::expect_warning(visR::define_theme(fontfamily = c("")))
})
testthat::test_that("T1.15 A warning when `fontfamily` is a vector of strings.", {
testthat::expect_warning(visR::define_theme(fontfamily = c("Times", "Helvetica")))
})
testthat::test_that("T1.16 A warning when `fontfamily` is anything but a string.", {
testthat::expect_warning(visR::define_theme(fontfamily = NULL))
testthat::expect_warning(visR::define_theme(fontfamily = 12))
testthat::expect_warning(visR::define_theme(fontfamily = TRUE))
testthat::expect_warning(visR::define_theme(fontfamily = list()))
})
testthat::test_that("T1.17 No error when `grid` is a boolean", {
testthat::expect_error(visR::define_theme(grid = TRUE), NA)
testthat::expect_error(visR::define_theme(grid = FALSE), NA)
})
testthat::test_that("T1.18 A warning when `grid` is anything but a boolean", {
testthat::expect_warning(visR::define_theme(grid = NULL))
testthat::expect_warning(visR::define_theme(grid = 12))
testthat::expect_warning(visR::define_theme(grid = "visR"))
testthat::expect_warning(visR::define_theme(grid = c()))
})
testthat::test_that("T1.19 No error when `bg` is a character.", {
testthat::expect_error(visR::define_theme(bg = "blue"), NA)
})
testthat::test_that("T1.20 A warning when `bg` is anything but a character.", {
testthat::expect_warning(visR::define_theme(bg = NULL))
testthat::expect_warning(visR::define_theme(bg = 12))
testthat::expect_warning(visR::define_theme(bg = list()))
})
testthat::test_that("T1.21 The returned theme object is of class `visR_theme`.", {
testthat::expect_true("visR_theme" %in% class(visR::define_theme()))
})
testthat::context("apply_theme - T2. The `apply_theme` function applies the specified changes to a `ggplot` object.")
testthat::test_that("T2.1 No error when a `ggplot` plot is provided, but no theme.", {
gg <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr()
testthat::expect_error(visR::apply_theme(gg), NA)
})
testthat::test_that("T2.2 No error when a `ggplot` plot and a minimal `visR::define_theme` object are provided.", {
gg <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr()
theme <- visR::define_theme()
testthat::expect_error(visR::apply_theme(gg, theme), NA)
testthat::expect_error(gg %>% visR::apply_theme(theme), NA)
})
testthat::test_that("T2.3 No error when a `ggplot` plot and a complex `visR::define_theme` object are provided.", {
gg <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr()
theme <- visR::define_theme(strata = list("SEX" = list("F" = "red",
"M" = "blue"),
"TRTA" = list("Placebo" = "cyan",
"Xanomeline High Dose" = "purple",
"Xanomeline Low Dose" = "brown")),
fontsizes = list("axis" = 12,
"ticks" = 10),
fontfamily = "Helvetica",
grid = FALSE,
bg = "transparent")
testthat::expect_error(visR::apply_theme(gg, theme), NA)
testthat::expect_error(gg %>% visR::apply_theme(theme), NA)
})
testthat::test_that("T2.4 A message when a theme not generated through `visR::define_theme` is provided.", {
gg <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr()
theme <- list("fontfamily" = "Palatino")
testthat::expect_error(visR::apply_theme(gg, theme), NA)
testthat::expect_error(gg %>% visR::apply_theme(theme), NA)
testthat::expect_message(visR::apply_theme(gg, theme))
testthat::expect_message(gg %>% visR::apply_theme(theme))
})
testthat::test_that("T2.5 Colours applied through `visR::apply_theme()` are used in the resulting `ggplot` object.", {
gg <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr()
theme <- visR::define_theme(strata = list("SEX" = list("F" = "red",
"M" = "blue"),
"TRTA" = list("Placebo" = "cyan",
"Xanomeline High Dose" = "purple",
"Xanomeline Low Dose" = "brown")))
gg <- gg %>% visR::apply_theme(theme)
ggb <- ggplot2::ggplot_build(gg)
testthat::expect_equal(unique(unlist(theme$strata$SEX)),
unique(ggb$data[[1]]$colour))
})
testthat::test_that("T2.6 Fontsizes applied through `visR::apply_theme()` are used in the resulting `ggplot` object.", {
gg <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr()
theme <- visR::define_theme(fontsizes = list("axis" = 12,
"ticks" = 10,
"legend_title" = 10,
"legend_text" = 8))
gg <- gg %>% visR::apply_theme(theme)
ggb <- ggplot2::ggplot_build(gg)
testthat::expect_equal(theme$fontsizes$axis, ggb$plot$theme$axis.title.x$size)
testthat::expect_equal(theme$fontsizes$axis, ggb$plot$theme$axis.title.y$size)
testthat::expect_equal(theme$fontsizes$ticks, ggb$plot$theme$axis.text$size)
testthat::expect_equal(theme$fontsizes$legend_title, ggb$plot$theme$legend.title$size)
testthat::expect_equal(theme$fontsizes$legend_text, ggb$plot$theme$legend.text$size)
})
testthat::test_that("T2.7 The fontfamily applied through `visR::apply_theme()` is used in the resulting `ggplot` object.", {
gg <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr()
theme <- visR::define_theme(fontfamily = "Helvetica")
gg <- gg %>% visR::apply_theme(theme)
ggb <- ggplot2::ggplot_build(gg)
testthat::expect_equal(theme$fontfamily, ggb$plot$theme$text$family)
})
testthat::test_that("T2.8 The grid applied through `visR::apply_theme()` is used in the resulting `ggplot` object.", {
gg <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr()
theme_grid_true <- visR::define_theme(grid = TRUE)
theme_grid_false <- visR::define_theme(grid = FALSE)
theme_grid_only_minor <- visR::define_theme(grid = list("major" = FALSE,
"minor" = TRUE))
theme_grid_minor_and_major <- visR::define_theme(grid = list("major" = TRUE,
"minor" = TRUE))
gg_grid_true <- gg %>% visR::apply_theme(theme_grid_true)
gg_grid_false <- gg %>% visR::apply_theme(theme_grid_false)
gg_grid_only_minor <- gg %>% visR::apply_theme(theme_grid_only_minor)
gg_grid_minor_and_major <- gg %>% visR::apply_theme(theme_grid_minor_and_major)
ggb_grid_true <- ggplot2::ggplot_build(gg_grid_true)
ggb_grid_false <- ggplot2::ggplot_build(gg_grid_false)
ggb_grid_only_minor <- ggplot2::ggplot_build(gg_grid_only_minor)
ggb_grid_minor_and_major <- ggplot2::ggplot_build(gg_grid_minor_and_major)
testthat::expect_true(("element_line" %in% class(ggb_grid_true$plot$theme$panel.grid.major)) &
("element_blank" %in% class(ggb_grid_true$plot$theme$panel.grid.minor)))
testthat::expect_true(("element_blank" %in% class(ggb_grid_false$plot$theme$panel.grid.major)) &
("element_blank" %in% class(ggb_grid_false$plot$theme$panel.grid.minor)))
testthat::expect_true(("element_blank" %in% class(ggb_grid_only_minor$plot$theme$panel.grid.major)) &
("element_line" %in% class(ggb_grid_only_minor$plot$theme$panel.grid.minor)))
testthat::expect_true(("element_line" %in% class(ggb_grid_minor_and_major$plot$theme$panel.grid.major)) &
("element_line" %in% class(ggb_grid_minor_and_major$plot$theme$panel.grid.minor)))
})
testthat::test_that("T2.9 The background applied through `visR::apply_theme()` is used in the resulting `ggplot` object.", {
gg <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr()
theme <- visR::define_theme(bg = "transparent")
gg <- gg %>% visR::apply_theme(theme)
ggb <- ggplot2::ggplot_build(gg)
testthat::expect_equal(theme$bg, ggb$plot$theme$panel.background$fill)
})
testthat::test_that("T2.10 The legend_position applied through `visR::apply_theme()` is used in the resulting `ggplot` object.", {
gg <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr()
theme_top <- visR::define_theme(legend_position = "top")
theme_right <- visR::define_theme(legend_position = "right")
theme_bottom <- visR::define_theme(legend_position = "bottom")
theme_left <- visR::define_theme(legend_position = "left")
gg_top <- gg %>% visR::apply_theme(theme_top)
gg_right <- gg %>% visR::apply_theme(theme_right)
gg_bottom <- gg %>% visR::apply_theme(theme_bottom)
gg_left <- gg %>% visR::apply_theme(theme_left)
ggb_top <- ggplot2::ggplot_build(gg_top)
ggb_right <- ggplot2::ggplot_build(gg_right)
ggb_bottom <- ggplot2::ggplot_build(gg_bottom)
ggb_left <- ggplot2::ggplot_build(gg_left)
testthat::expect_equal(theme_top$legend_position, ggb_top$plot$theme$legend.position)
testthat::expect_equal(theme_right$legend_position, ggb_right$plot$theme$legend.position)
testthat::expect_equal(theme_bottom$legend_position, ggb_bottom$plot$theme$legend.position)
testthat::expect_equal(theme_left$legend_position, ggb_left$plot$theme$legend.position)
})
testthat::test_that("T2.11 The legend_position defined in `visR::visr()` is correctly passed through to the resulting `ggplot` object.", {
gg_top <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr(legend_position = "top")
gg_right <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr(legend_position = "right")
gg_bottom <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr(legend_position = "bottom")
gg_left <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr(legend_position = "left")
gg_top <- gg_top %>% visR::apply_theme()
gg_right <- gg_right %>% visR::apply_theme()
gg_bottom <- gg_bottom %>% visR::apply_theme()
gg_left <- gg_left %>% visR::apply_theme()
ggb_top <- ggplot2::ggplot_build(gg_top)
ggb_right <- ggplot2::ggplot_build(gg_right)
ggb_bottom <- ggplot2::ggplot_build(gg_bottom)
ggb_left <- ggplot2::ggplot_build(gg_left)
testthat::expect_true("top" %in% ggb_top$plot$theme$legend.position)
testthat::expect_true("right" %in% ggb_right$plot$theme$legend.position)
testthat::expect_true("bottom" %in% ggb_bottom$plot$theme$legend.position)
testthat::expect_true("left" %in% ggb_left$plot$theme$legend.position)
}) |
.writeHdrVRT <- function(x) {
fn <- fname <- x@file@name
if (tolower(extension(fn)) == '.vrt') {
stop('cannot (over)write a vrt header for a vrt file')
}
if (tolower(extension(fn)) == '.grd') {
extension(fn) <- '.gri'
}
extension(fname) <- 'vrt'
pixsize <- dataSize(x@file@datanotation)
nbands <- nlayers(x)
bandorder <- x@file@bandorder
if (bandorder == 'BIL') {
pixoff <- pixsize
lineoff <- pixsize * x@ncols * nbands
imgoff <- ((1:nbands)-1) * x@ncols * pixsize
} else if (bandorder == 'BSQ') {
pixoff <- pixsize
lineoff <- pixsize * x@ncols
imgoff <- ((1:nbands)-1) * ncell(x) * pixsize
} else if (bandorder == 'BIP') {
pixoff <- pixsize * nbands
lineoff <- pixsize * x@ncols * nbands
imgoff <- (1:nbands)-1
}
datatype <- .getGdalDType(x@file@datanotation)
if (x@file@byteorder == "little") {
byteorder <- "LSB"
} else {
byteorder <- "MSB"
}
if (! x@file@toptobottom) { rotation <- 180 } else { rotation <- 0 }
e <- x@extent
r <- res(x)
prj <- proj4string(x)
f <- file(fname, "w")
cat('<VRTDataset rasterXSize="', x@ncols, '" rasterYSize="', x@nrows, '">\n' , sep = "", file = f)
if (rotated(r)) {
cat('<GeoTransform>', paste(x@rotation@geotrans, collapse=', '), '</GeoTransform>\n', sep = "", file = f)
} else {
cat('<GeoTransform>', e@xmin, ', ', r[1], ', ', rotation, ', ', e@ymax, ', ', 0.0, ', ', -1*r[2], '</GeoTransform>\n', sep = "", file = f)
}
if (! is.na(prj) ) {
cat('<SRS>', prj ,'</SRS>\n', sep = "", file = f)
}
for (i in 1:nlayers(x)) {
cat('\t<VRTRasterBand dataType="', datatype, '" band="', i, '" subClass="VRTRawRasterBand">\n', sep = "" , file = f)
cat('\t\t<Description>', names(x), '</Description>\n', sep = "", file = f)
cat('\t\t<SourceFilename relativetoVRT="1">', basename(fn), '</SourceFilename>\n', sep = "", file = f)
cat('\t\t<ImageOffset>', imgoff[i], '</ImageOffset>\n', sep = "", file = f)
cat('\t\t<PixelOffset>', pixoff, '</PixelOffset>\n', sep = "", file = f)
cat('\t\t<LineOffset>', lineoff, '</LineOffset>\n', sep = "", file = f)
cat('\t\t<ByteOrder>', byteorder, '</ByteOrder>\n', sep = "", file = f)
cat('\t\t<NoDataValue>', x@file@nodatavalue, '</NoDataValue>\n', sep = "", file = f)
cat('\t\t<Offset>', x@data@offset, '</Offset>\n', sep = "", file = f)
cat('\t\t<Scale>', x@data@gain, '</Scale>\n', sep = "", file = f)
cat('\t</VRTRasterBand>\n', sep = "", file = f)
}
cat('</VRTDataset>\n', sep = "", file = f)
close(f)
return( invisible(TRUE) )
}
|
MUE <- function(prob, u, t.obs) {
f.prob <- prob[u == t.obs]
f.u <- t.obs
if (length(u) == 1) {
return(NA)
} else {
return(FINDROOT(f.prob, f.u, prob, u, rhs = 0.5))
}
} |
gdfpd.read.fca.zip.file <- function(my.zip.file,
folder.to.unzip = tempdir()) {
if (tools::file_ext(my.zip.file) != 'zip') {
stop(paste('File', my.zip.file, ' is not a zip file.') )
}
if (!file.exists(my.zip.file)) {
stop(paste('File', my.zip.file, ' does not exists.') )
}
if (file.size(my.zip.file) == 0){
stop(paste('File', my.zip.file, ' has size 0!') )
}
if (length(my.zip.file) != 1){
stop('This function only works for a single zip file... check your inputs')
}
if (!dir.exists(folder.to.unzip)) {
cat(paste('Folder', folder.to.unzip, 'does not exist. Creating it.'))
dir.create(folder.to.unzip)
}
my.basename <- tools::file_path_sans_ext(basename(my.zip.file))
rnd.folder.name <- file.path(folder.to.unzip, paste0('DIR-',my.basename))
if (!dir.exists(rnd.folder.name)) dir.create(rnd.folder.name)
utils::unzip(my.zip.file, exdir = rnd.folder.name, junkpaths = TRUE)
my.files <- list.files(rnd.folder.name)
if (length(my.files) == 0) {
file.remove(my.zip.file)
stop(paste0('Zipped file contains 0 files. ',
'This is likelly a problem with the downloaded file. ',
'Try running the code again as the corrupted zip file was deleted and will be downloaded again.',
'\n\nIf the problem persists, my suggestions is to remove the time period with problem.') )
}
my.l <- gdfpd.read.zip.file.type.fca(rnd.folder.name, folder.to.unzip)
return(my.l)
}
gdfpd.read.zip.file.type.fca <- function(rnd.folder.name, folder.to.unzip = tempdir()) {
zipped.file <- file.path(rnd.folder.name, list.files(rnd.folder.name, pattern = '*.fca')[1])
utils::unzip(zipped.file, exdir = rnd.folder.name)
company.reg.file <- file.path(rnd.folder.name,'ValorMobiliarioMercadoNegociacao.xml')
if (!file.exists(company.reg.file)) {
df.governance.listings <- data.frame(listed.segment = NA,
type.market = NA,
name.market = NA)
} else {
xml_data <- XML::xmlToList(XML::xmlParse(company.reg.file))
xml_data$ValorMobiliario$Documento$CompanhiaAberta$DataConstituicaoEmpresa
xml_data2 <- xml_data$ValorMobiliario$MercadosNegociacao$MercadoNegociacao$Segmento
listed.segment <- xml_data2$DescricaoOpcaoDominio
type.market <- xml_data$ValorMobiliario$MercadoNegociacao$DescricaoOpcaoDominio
name.market <- xml_data$ValorMobiliario$MercadosNegociacao$MercadoNegociacao$EntidadeAdministradora$SiglaOpcaoDominio
df.governance.listings <- data.frame(listed.segment = fix.fct(listed.segment),
type.market = fix.fct(type.market),
name.market = fix.fct(name.market), stringsAsFactors = FALSE)
}
company.reg.file <- file.path(rnd.folder.name,'Documento.xml')
if (!file.exists(company.reg.file)) {
df.company.info <- data.frame(cnpj = NA,
date.company.constitution = NA,
date.cvm.registration = NA)
} else {
xml_data <- XML::xmlToList(XML::xmlParse(company.reg.file))
cnpj <- xml_data$CompanhiaAberta$NumeroCnpjCompanhiaAberta
date.company.constitution <- as.Date(xml_data$CompanhiaAberta$DataConstituicaoEmpresa)
date.cvm.registration <- as.Date(xml_data$CompanhiaAberta$DataRegistroCvm)
df.company.info <- data.frame(cnpj = fix.fct(cnpj),
date.company.constitution = fix.fct(date.company.constitution),
date.cvm.registration = fix.fct(date.cvm.registration), stringsAsFactors = FALSE)
}
my.l <- list(df.governance.listings = df.governance.listings,
df.company.info = df.company.info)
return(my.l)
} |
kfamset <- function(x) {
if (!inherits(x, "relation") & !inherits(x, "set")) {
stop(sprintf("%s must be a relation or a set of subsets.",dQuote("x")))
}
if (inherits(x, "relation")) {
relmat <- relation_incidence(x)
mode(relmat) <- "logical"
x <- as.set(apply(relmat,2,function(z)as.set(names(which(z)))))
} else {
x <- as.set(lapply(lapply(x, as.character),as.set))
}
names(x) <- NULL
class(x) <- unique(c("kfamset", class(x)))
x
} |
inspect_num <- function(df1, df2 = NULL, breaks = 20, include_int = TRUE){
breakseq <- attr(df1, "breakseq")
input_type <- check_df_cols(df1, df2)
df_names <- get_df_names()
if(input_type == "single"){
df_num <- df1 %>% select_if(is.numeric)
if(!include_int) df_num <- df_num %>% select_if(is.double)
n_cols <- ncol(df_num)
if(n_cols > 0){
names_vec <- colnames(df_num)
breaks_tbl <- tibble(col_name = names_vec)
if(!is.null(breakseq)){
breaks_tbl <- left_join(breaks_tbl, breakseq, by = "col_name")
} else {
breaks_tbl$breaks <- lapply(as.list(1:nrow(breaks_tbl)), function(xc) NULL)
}
pb <- start_progress(prefix = " Column", total = n_cols)
breaks_tbl$hist <- stats_list <- vector("list", length = nrow(breaks_tbl))
for(i in 1:nrow(breaks_tbl)){
col_nm <- breaks_tbl$col_name[i]
col_i <- df_num[[col_nm]]
update_progress(bar = pb, iter = i, total = nrow(breaks_tbl),
what = names_vec[i])
if(any(!is.na(col_i))){
get_stats <- function(vec, col_nm){
tibble(col_name = col_nm,
min = min(vec, na.rm = T),
q1 = quantile(vec, 0.25, na.rm = T),
median = median(vec, na.rm = T),
mean = mean(vec, na.rm = T),
q3 = quantile(vec, 0.75, na.rm = T),
max = max(vec, na.rm = T),
sd = sd(vec, na.rm = T),
pcnt_na = 100 * mean(is.na(vec)))
}
stats_list[[i]] <- get_stats(col_i, col_nm)
brks_null <- is.null(breaks_tbl$breaks[[i]])
hist_i <- suppressWarnings(
hist(col_i, plot = FALSE, right = FALSE,
breaks = if(brks_null) breaks else {breaks_tbl$breaks[[i]]})
)
breaks_tbl$hist[[i]] <- prop_value(hist_i)
} else {
breaks_tbl$hist[[i]] <- tibble(value = NA, prop = 1)
stats_list[[i]] <- tibble(col_name = col_nm, min = NA, q1 = NA, median = NA,
mean = NA, q3 = NA, max = NA, sd = NA, pcnt_na = 100)
}
}
stats_df <- bind_rows(stats_list)
out <- left_join(stats_df, breaks_tbl, by = "col_name") %>%
select(-breaks)
names(out$hist) <- as.character(out$col_name)
} else {
out <- tibble(col_name = character(), min = numeric(),
q1 = numeric(), median = numeric(),
mean = numeric(), q3 = numeric(),
max = numeric(), sd = numeric(),
pcnt_na = numeric(), hist = list())
}
}
if(input_type == "pair"){
s1 <- inspect_num(df1, breaks = breaks, include_int = include_int) %>%
select(col_name, hist)
attr(df2, "breakseq") <- tibble(col_name = s1$col_name,
breaks = lapply(s1$hist, get_break))
s2 <- inspect_num(df2, include_int = include_int) %>% select(col_name, hist)
out <- full_join(s1, s2, by = "col_name")
out <- out %>%
mutate(jsd = js_divergence_vec(hist.x, hist.y)) %>%
mutate(pval = chisq(hist.x, hist.y, n_1 = nrow(df1), n_2 = nrow(df2))) %>%
select(col_name, hist_1 = hist.x, hist_2 = hist.y, jsd, pval)
}
if(input_type == "grouped"){
s_ug <- inspect_num(df1 %>% ungroup)
brk_tab <- tibble(col_name = s_ug$col_name, breaks = lapply(s_ug$hist, get_break))
out_nest <- df1 %>% nest()
grp_nms <- attr(df1, "groups") %>% select(-ncol(.))
out_list <- vector("list", length = length(out_nest))
for(i in 1:length(out_nest$data)){
dfi <- out_nest$data[[i]]
attr(dfi, 'breakseq') <- brk_tab
out_list[[i]] <- inspect_num(dfi, include_int = include_int)
}
grp_nms$out_list <- out_list
out <- unnest(grp_nms, cols = c('out_list'))
}
attr(out, "type") <- list(method = "num", input_type = input_type)
attr(out, "df_names") <- df_names
return(out)
} |
size_b.two_way_nested.b_random_a_fixed_a <- function(alpha, beta, delta, a, cases)
{
b <- 5
b.new <- 1000
while (abs(b -b.new)>1e-6)
{
b <- b.new
dfn <- a-1
dfd <- a*(b-1)
lambda <- ncp(dfn,dfd,alpha,beta)
if (cases == "maximin")
{
b.new <- 2*lambda/(delta*delta)
}
else if (cases == "minimin")
{
b.new <- 4*lambda/(a*delta*delta)
}
}
return(ceiling(b.new))
} |
confidenceEllipse <- function(X.mean = c(0,0),
eig,
n,
p,
xl = NULL, yl = NULL,
axes = TRUE,
center = FALSE,
lim.adj = 0.02,
alpha = 0.05,
...){
X.mean <- matrix(X.mean, ncol=1)
angle <- atan(eig$vectors[2,1] / eig$vectors[1,1])
axis1 <- sqrt(eig$values[1]) *
sqrt((p * (n - 1)) /
(n * (n - p)) *
qf(1 - alpha, p, n - p))
axis2 <- sqrt(eig$values[2]) *
sqrt((p * (n - 1)) /
(n * (n - p)) *
qf(1 - alpha, p, n - p))
lengths <- c(axis1,axis2)
eigenEllipseHelper(mu = X.mean, lengths = lengths, angle = angle,
xl = xl, yl = yl,
axes = axes, center = center,
lim.adj = lim.adj, ...)
}
bvNormalContour <- function(mu = c(0,0), Sigma=NULL, eig=NULL,
xl = NULL, yl = NULL,
axes = TRUE, center = FALSE,
lim.adj = 0.02, alpha = 0.05, ...){
mu <- matrix(mu, ncol=1)
clevel <- qchisq(1 - alpha, df = 2)
if (!is.null(Sigma)){
eig <- eigen(Sigma)
}
lengths <- c(clevel * sqrt(eig$values[1]), clevel * sqrt(eig$values[2]))
angle <- atan(eig$vectors[2,1]/eig$vectors[1,1])
eigenEllipseHelper(mu = mu, lengths = lengths, angle = angle,
xl = xl, yl = yl,
axes = axes, center = center,
lim.adj = lim.adj, ...)
}
eigenEllipseHelper <- function(mu, lengths, angle, xl, yl, lim.adj, axes, center, ...){
axis1 <- lengths[1]
axis2 <- lengths[2]
axis1.x <- cos(angle) * axis1
axis1.y <- sin(angle) * axis1
axis2.x <- cos(angle + pi / 2) * axis2
axis2.y <- sin(angle + pi / 2) * axis2
if (is.null(xl)){
xl1 <- mu[1,1] - abs(axis1.x) - abs(axis2.x)
xl2 <- mu[1,1] + abs(axis1.x) + abs(axis2.x)
xl <- c(xl1*(1-lim.adj),xl2*(1+lim.adj))
}
if (is.null(yl)){
yl1 <- mu[2,1] - abs(axis1.y) - abs(axis2.y)
yl2 <- mu[2,1] + abs(axis1.y) + abs(axis2.y)
yl <- c(yl1*(1-lim.adj),yl2*(1+lim.adj))
}
plot(0,pch='',ylab='',xlab='',xlim=xl,ylim=yl)
plotrix::draw.ellipse(x = mu[1,1], y = mu[2,1],
a = lengths[1], b = lengths[2],
angle = angle, deg = FALSE)
if (axes){
segments(x1 = mu[1,1], y1 = mu[2,1], x0 = mu[1,1] + axis1.x, y0 = mu[2,1] + axis1.y)
segments(x1 = mu[1,1], y1 = mu[2,1], x0 = mu[1,1] - axis1.x, y0 = mu[2,1] - axis1.y)
segments(x1 = mu[1,1], y1 = mu[2,1], x0 = mu[1,1] + axis2.x, y0 = mu[2,1] + axis2.y)
segments(x1 = mu[1,1], y1 = mu[2,1], x0 = mu[1,1] - axis2.x, y0 = mu[2,1] - axis2.y)
}
if (center){
segments(x1 = mu[1,1], y1 = mu[2,1], y0 = mu[2,1], x0 = 0, lty=2)
segments(x1 = mu[1,1], y1 = mu[2,1], x0 = mu[1,1], y0 = 0, lty=2)
points(x = mu[1,1], y = mu[2,1], pch = 19)
}
} |
delold <- function (a){
attr (a, "old") <- NULL
a
}
.test (delold) <- function (){
tmp <- makeNd (a, 0)
old <- attributes (tmp)
old <- old [grepl ("^old", names (old))]
checkIdentical (old,
list (old = list (list (
names = NULL,
dimnames = list(rows = c("a", "b", "c", "d"),
columns = c("A", "B", "C"),
d3 = c("1", "2")),
dim = c(4L, 3L, 2L))))
)
tmp <- delold (tmp)
checkTrue (is.null (attr (old, "old")))
} |
cluster_gen_separate <- function(
n_levels, n, N, sum_pop, calc_weights, sampling_method, cluster_labels, resp_labels, collapse, n_X, n_W, cat_prop, c_mean, sigma, cor_matrix,
rho, theta, whitelist, verbose, ...
) {
out <- list()
sample <- list()
c_mean_list <- c_mean
sigma_list <- sigma
n_quest <- sapply(n, sum)
id_combos <- label_respondents(n, cluster_labels)
missing_sigma2 <- is.null(sigma)
if (class(cor_matrix)[1] != "list") {
cor_matrix <- replicate(n_levels - 1, list(cor_matrix))
}
cor_matrix_list <- cor_matrix
cat_prop_orig <- cat_prop
for (l in seq(n_levels - 1)) {
if (class(c_mean_list) == "list") c_mean <- c_mean_list[[l]]
if (class(sigma_list) == "list") sigma <- sigma_list[[l]]
if (any(sapply(cat_prop_orig, class) == "list")) {
cat_prop <- cat_prop_orig[[l]]
}
level_label <- cluster_labels[l]
next_level_label <- ifelse(
test = l < n_levels - 1,
yes = cluster_labels[l + 1],
no = resp_labels[l]
)
previous_clusterID <- NULL
previous_sublvl <- 0
if (l > 1) {
if (class(n) != "list") n[l] <- n[l] * n[l - 1]
previous_clusterID <- as.vector(unlist(sapply(sample[[l - 1]],
function(x) x$clusterID)))
previous_sublvl <- gsub("[A-Za-z]", "", previous_clusterID)
previous_sublvl <- as.numeric(gsub("\\_.", "", previous_sublvl))
}
n_groups <- sapply(n, sum)[l]
if (!is.null(rho)) {
if (class(rho) != "list") rho <- replicate(n_levels, list(rho))
if (length(rho[[l]]) == 1) rho[[l]] <- rep(rho[[l]], n_X[[l]] + theta)
n_j <- n[[l + 1]]
M <- sum(n_j)
if (missing_sigma2) {
if (is.null(c_mean) | is.null(rho) | length(c_mean) == 1) {
sigma2 <- rchisq(n_X[[l]] + theta, 2)
} else {
n_tilde <- calc_n_tilde(M, N[[l]], n_j)
mean_j <- unlist(c_mean)
overall_mean <- sum(mean_j * n_j) / M
s2btw <- calc_var_between(n_j, mean_j, overall_mean, n_tilde, N[[l]])
tau2 <- s2btw * n_tilde
sigma2 <- tau2 * (1 - rho[[l]]) / rho[[l]]
}
} else {
if (class(sigma) == "list") {
sigma2 <- sigma[[l]] ^ 2
} else {
sigma2 <- sigma ^ 2
}
}
tau2 <- rho[[l]] * sigma2 / (1 - rho[[l]])
Nn <- length(n_j)
s2 <- sigma2 * (M - Nn) / sum(n_j - 1)
}
for (lvl in seq(n_groups)) {
n_resp <- n[[l + 1]][lvl]
if (any(sapply(cat_prop, class) == "list")) {
cat_prop_lvl <- cat_prop[[lvl]]
} else {
cat_prop_lvl <- cat_prop
}
if (!is.null(c_mean) & class(c_mean) == "list") {
mu_mu <- c_mean[[lvl]]
} else {
mu_mu <- c_mean
}
if (!is.null(cor_matrix) & class(cor_matrix)[1] == "list") {
cor_mx <- cor_matrix[[l]]
if (class(cor_mx)[1] == "list") cor_mx <- cor_matrix[[l]][[lvl]]
}
if (!is.null(rho[[l]])) {
sd_X <- sqrt(s2)
} else if (!is.null(sigma) & class(sigma) == "list") {
sd_X <- sigma[[lvl]]
} else {
sd_X <- sigma
}
if (all(!is.null(rho[[l]]))) {
sd_mu <- sqrt(tau2 + sigma2 / n_j[lvl])
mu_mu <- ifelse(is.null(mu_mu), 0, mu_mu)
mu <- sapply(sd_mu, function(s) rnorm(1, mu_mu, s))
} else {
mu <- mu_mu
}
if (any(sapply(n_W[[l]], class) == "list")) {
n_W_used <- n_W[[l]][[lvl]]
} else {
n_W_used <- n_W[[l]]
}
if (is(n_W_used, "list") & any(sapply(n_W_used, length) > 1)) {
n_W_used <- n_W_used[[l]][lvl]
}
cluster_bg <- questionnaire_gen(
n_resp, n_X = n_X[[l]], n_W = n_W_used, cat_prop = cat_prop_lvl,
c_mean = mu, verbose = FALSE, c_sd = sd_X, cor_matrix = cor_mx,
theta = theta, ...
)
if (calc_weights) {
cluster_bg <- weight_responses(
cluster_bg, n, N, l + 1, lvl, previous_sublvl[lvl], sampling_method,
cluster_labels, resp_labels, sum_pop, verbose
)
}
respID <- paste0(next_level_label, seq(cluster_bg$subject))
if (l > 1) {
previous_lvl <- as.vector(unlist(sapply(n[[l]], seq)))[lvl]
cluster_bg$clusterID <- paste0(level_label, previous_lvl, "_",
previous_clusterID[lvl])
} else {
cluster_bg$clusterID <- paste0(level_label, lvl)
}
cluster_bg$uniqueID <- paste(respID, cluster_bg$clusterID, sep = "_")
if (!is.null(whitelist)) {
if (l == 1) {
clusterID_extracted <- gsub(
pattern = "\\D",
replacement = "",
cluster_bg[, "clusterID"][1]
)
clusterID_extracted <- as.numeric(clusterID_extracted)
whitelist_extracted <- whitelist[, l]
is_whitelisted <- (lvl %in% whitelist[, 1:l])
} else {
clusterID_extracted <- gsub(
pattern = "\\D",
replacement = "",
cluster_bg[, "clusterID"][1]
)
clusterID_extracted <- as.numeric(clusterID_extracted)
whitelist_extracted <- apply(
whitelist[, rev(seq_len(l))],
1,
function(x) paste(x, collapse = "")
)
is_whitelisted <- match(clusterID_extracted, whitelist_extracted)
is_whitelisted <- !is.na(is_whitelisted)
}
if (!is_whitelisted) {
cluster_bg[, 2:(ncol(cluster_bg) - 2)] <- NA
}
if (all(!is.na(cluster_bg))) {
if (l < n_levels - 1) {
keep_rows <- whitelist[whitelist[, l] == lvl, l + 1]
blacklisted_rows <- which(
is.na(match(rownames(cluster_bg), keep_rows))
)
cluster_bg[blacklisted_rows, 2:(ncol(cluster_bg) - 2)] <- NA
} else if (l == n_levels - 1) {
rowmatched <- match(clusterID_extracted, whitelist_extracted)
limit <- whitelist[rowmatched, n_levels]
if (limit < nrow(cluster_bg))
cluster_bg <- cluster_bg[seq_len(limit), ]
}
}
}
sample[[level_label]][[lvl]] <- cluster_bg
}
if (collapse == "none") {
out[[l]] <- sample[[l]]
for (ll in seq_along(out[[l]])) {
out[[l]][[ll]]["clusterID"] <- NULL
}
names(out)[[l]] <- cluster_labels[l]
} else {
out[[level_label]] <- do.call(rbind, sample[[level_label]])
if (collapse == "full") {
if (l == 1) {
names(out[[l]]) <- paste0(names(out[[l]]), ".", resp_labels[l])
}
if (l > 1) {
non_weight_cols <- grep("weight", names(out[[l]]), invert = TRUE)
names(out[[l]])[non_weight_cols] <-
paste0(names(out[[l]])[non_weight_cols], ".", resp_labels[l])
out[[l]] <- merge(x = out[[l]], y = out[[l - 1]][-1],
by.x = paste0("clusterID", ".", resp_labels[l]),
by.y = paste0("uniqueID", ".", resp_labels[l - 1]))
out[[l]][paste0("clusterID.", level_label)] <- NULL
}
if (l == n_levels - 1) {
out <- out[[l]]
names(out[[l]]) <- paste0(names(out[[l]]), ".", resp_labels[l])
out[paste0("clusterID.", resp_labels[1])] <- NULL
out[paste0("clusterID.", resp_labels[l])] <- NULL
names(out)[1] <- "subject"
out$subject <- seq(nrow(out))
}
} else {
out[[level_label]]["clusterID"] <- NULL
out[[level_label]]$subject <- seq(nrow(out[[level_label]]))
}
}
}
return(out)
} |
drop_vars <- function(p, keep.vars = character(), guess.vars = TRUE) {
stopifnot(ggplot2::is.ggplot(p))
if (inherits(p$data, "sf")) {
message("'drop_vars()' does not yet support shape file 'sf' data.")
return(p)
}
if (guess.vars) {
mapped.vars <- mapped_vars(p)
} else {
mapped.vars <- character()
}
data.vars <- names(p$data)
unused.vars <- setdiff(data.vars, union(mapped.vars, keep.vars))
keep.idxs <- which(!data.vars %in% unused.vars)
p$data <- p$data[ , keep.idxs]
p
}
mapped_vars <- function(p, invert = FALSE) {
stopifnot(ggplot2::is.ggplot(p))
mappings <- as.character(p$mapping)
for (l in p$layers) {
mappings <- c(mappings, as.character(l$mapping))
}
mappings <- c(mappings,
names(p$facet$params$facets),
names(p$facet$params$rows),
names(p$facet$params$cols))
mapped.vars <-
gsub("[~*\\%^]", " ", mappings) %>%
stringr::str_split(pattern = stringr::boundary("word")) %>%
unlist()
if (invert) {
setdiff(names(p$data), mapped.vars)
} else {
intersect(names(p$data), mapped.vars)
}
}
data_vars <- function(p) {
stopifnot(ggplot2::is.ggplot(p))
colnames(p$data)
}
data_attributes <- function(p) {
stopifnot(ggplot2::is.ggplot(p))
attributes(p$data)
} |
linkdisequ_FAST <- function(matrix_pol,populations){
npops <- length(populations)
sitelength <- dim(matrix_pol)[2]
if(sitelength<2){return(list(res=as.matrix(NaN),Zns=NaN,ZA=NaN,ZZ=NaN))}
if(length(colnames(matrix_pol))==0){
colnames(matrix_pol) <- 1:sitelength
}
init <- vector(,npops)
names <- paste("pop",1:npops)
znsvek <- init
names(znsvek) <- names
ZA <- init
names(ZA) <- names
ZZ <- init
names(ZZ) <- names
segsites <- get_segsites_FAST(matrix_pol,populations)
for(xx in 1:npops){
popmatrix <- matrix_pol[populations[[xx]],segsites[[xx]],drop=FALSE]
n.segsites.pop <- length(segsites[[xx]])
if(n.segsites.pop<=1){next}
EINSEN <- colSums(popmatrix, na.rm = TRUE)
NULLEN <- colSums(popmatrix==0, na.rm = TRUE)
res <- .Call("R2_C", popmatrix, EINSEN, NULLEN)
Zns <- mean(res, na.rm = TRUE)
znsvek[xx] <- Zns
if(n.segsites.pop==2){
adjacent <- 1
}else{
adjacent <- rep(1,n.segsites.pop-1)
fill <- n.segsites.pop - 1
for (yy in 2:length(adjacent)) {
adjacent[yy] <- adjacent[yy-1] + fill
fill <- fill - 1
}
}
ZA[xx] <- sum(res[adjacent], na.rm = TRUE)/(n.segsites.pop-1)
ZZ[xx] <- ZA[xx] - znsvek[xx]
}
return(list(Zns=znsvek,ZA=ZA,ZZ=ZZ))
} |
make_fake_deps <- function(...) {
assert_that(all_named(list(...)))
d <- desc::desc("!new")
if (length(list(...))) d$set(...)
resolve_ref_deps(
d$get_deps(),
d$get("Remotes")[[1]],
NULL
)
}
make_fake_resolution1 <- function(ref, args = list()) {
pref <- parse_pkg_refs(ref)[[1]]
if (!is.null(args$extra)) pref[names(args$extra)] <- args$extra
mirror <- args$mirror %||% current_config()$get("cran-mirror")
repodir <- args$repodir %||% "src/contrib"
version <- args$version %||% "1.0.0"
filename <- paste0(pref$package, "_", version, ".tar.gz")
def <- list(
ref = ref,
type = pref$type,
package = pref$package,
version = version,
sources = c(
sprintf("%s/%s/%s", mirror, repodir, filename),
sprintf("%s/%s/Archive/%s/%s", mirror, repodir, pref$package,
filename)
),
dep_types = tolower(pkg_dep_types_hard())
)
modifyList(def, args)
}
make_fake_metadata <- function() {
list(
resolution_start = Sys.time(),
resolution_end = Sys.time()
)
}
make_fake_resolution <- function(...) {
pkgs <- list(...)
assert_that(all_named(pkgs))
ress <- lapply_with_names(
names(pkgs), function(n) make_fake_resolution1(n, pkgs[[n]]))
res <- res_make_empty_df()
for (r in ress) res <- res_add_df_entries(res, r)
res
}
describe_fake_error <- function(pkgs, policy = "lazy",
config = current_config()) {
lp <- pkgplan_i_create_lp_problem(pkgs, config, policy)
sol <- pkgplan_i_solve_lp_problem(lp)
expect_true(sol$objval >= solve_dummy_obj - 1)
solution <- list(status = "FAILED", data = pkgs, problem = lp,
solution = sol)
describe_solution_error(pkgs, solution)
} |
bootmex <-
function (x, R = 100, nPass = 3, trace = 10,referenceMargin=NULL) {
theCall <- match.call()
if (!inherits(x, "mex")){
stop("object must be of type 'mex'")
}
ans <- list()
ans$call <- theCall
getTran <- function(i, x, data, mod, th, qu, margins) {
param <- mod[[i]]$coefficients
revTransform(margins$q2p(c(x[, i])), data = c(data[, i]), th = th[i],
qu = qu[i], sigma = exp(param[1]), xi = param[2])
}
mar <- x$margins
dep <- x$dependence
which <- dep$which
constrain <- dep$constrain
v <- dep$v
dqu <- dep$dqu
dth <- dep$dth
margins <- dep$margins
penalty <- mar$penalty
priorParameters <- mar$priorParameters
start <- 0.75* coef(x)$dependence[1:2,]
n <- dim(mar$transformed)[[1]]
d <- dim(mar$transformed)[[2]]
dqu <- rep(dqu, d)
dependent <- (1:d)[-which]
ans$simpleDep <- dep$coefficients
ans$dqu <- dqu
ans$which <- which
ans$R <- R
ans$simpleMar <- mar
ans$margins <- margins
ans$constrain <- constrain
innerFun <- function(i, x, which, dth, dqu, margins, penalty, priorParameters, constrain, v=v, start=start,
pass = 1, trace = trace, n=n, d=d, getTran=getTran, dependent=dependent,referenceMargin=referenceMargin) {
g <- sample(1:(dim(mar$transformed)[[1]]), size = n, replace = TRUE)
g <- mar$transformed[g, ]
ok <- FALSE
while (!ok) {
for (j in 1:(dim(g)[[2]])){
u <- runif(nrow(g))
g[order(g[, j]), j] <- sort(margins$p2q(u))
}
if (sum(g[, which] > dth) > 1 & all(g[g[,which] > dth , which] > 0)){ ok <- TRUE }
}
g <- sapply(1:d, getTran, x = g, data = mar$data, margins=margins,
mod = mar$models, th = mar$mth, qu = mar$mqu)
dimnames(g)[[2]] <- names(mar$models)
ggpd <- migpd(g, mth = mar$mth,
penalty = penalty, priorParameters = priorParameters)
gd <- mexDependence(ggpd, dqu = dqu, which = which, margins=margins[[1]], constrain=constrain, v=v, start=start,referenceMargin=referenceMargin)
res <- list(GPD = coef(ggpd)[3:4, ],
dependence = gd$dependence$coefficients,
Z = gd$dependence$Z,
Y = g)
if (pass == 1) {
if (i%%trace == 0) {
message(paste(i, "replicates done\n"))
}
}
res
}
res <- lapply(1:R, innerFun, x = x, which = which, dth = dth, margins=margins,
dqu = dqu, penalty = penalty, priorParameters = priorParameters, constrain=constrain, v=v, start=start,
pass = 1, trace = trace, getTran=getTran, n=n, d=d, dependent=dependent,referenceMargin=referenceMargin)
if (nPass > 1) {
for (pass in 2:nPass) {
rerun <- sapply(res, function(x) any(sapply(x, function(x) any(is.na(x)))))
wh <- !unlist(lapply(res, function(x) dim(x$Z)[[1]] > 0))
rerun <- apply(cbind(rerun, wh), 1, any)
if (sum(rerun) > 0) {
message("Pass ", pass, " : ", sum(rerun), " samples to rerun.\n")
rerun <- (1:R)[rerun]
res[rerun] <- lapply((1:R)[rerun], innerFun,
x = x, which = which, dth = dth, dqu = dqu, margins=margins,
penalty = penalty, priorParameters = priorParameters, constrain=constrain, v=v, start=start,
pass = pass, trace = trace, getTran=getTran, n=n, d=d, dependent=dependent,referenceMargin=referenceMargin)
}
}
}
ans$boot <- res
oldClass(ans) <- c("bootmex", "mex")
ans
} |
ConfInt=function(){
appDir <- system.file("ConfIntLMApp.r", package = "lmviz")
.GlobalEnv$".wd"=getwd()
shiny::runApp(appDir)
} |
response.analysis <- function(...)
{
name <- as.character(substitute(list(...)))
name <- name[-which(name=="list")]
datalist <- list(...)
for(i in 1:length(datalist)){
if(all(apply(datalist[[i]], 2, is.character))){
datalist[[i]] <- resp2bin(datalist[[i]])$binary
}
}
res <- list()
totals <- lapply(datalist, rowSums)
totals.res <- t.test(totals[[1]], totals[[2]], var.equal = TRUE)
res.totals <- numeric(10)
names(res.totals) <- c(
paste("M", name[1]), paste("SD", name[1]),
paste("M", name[2]), paste("SD", name[2]),
"t-statistic", "df", "p-value",
paste("95%", c("Lower", "Upper")),
"Cohen's d"
)
d <- function(one, two){
num <- mean(one, na.rm = TRUE) - mean(two, na.rm = TRUE)
denom <- sqrt(
(sd(one, na.rm = TRUE)^2 + sd(two, na.rm = TRUE)^2) / 2
)
return(abs(num / denom))
}
res.totals[1] <- mean(totals[[1]], na.rm = TRUE)
res.totals[2] <- sd(totals[[1]], na.rm = TRUE)
res.totals[3] <- mean(totals[[2]], na.rm = TRUE)
res.totals[4] <- sd(totals[[2]], na.rm = TRUE)
res.totals[5] <- totals.res$statistic
res.totals[6] <- totals.res$parameter
res.totals[7] <- totals.res$p.value
res.totals[8:9] <- totals.res$conf.int
res.totals[10] <- d(totals[[1]], totals[[2]])
res$total <- round(res.totals, 3)
resplist <- lapply(datalist, function(x){colnames(x)})
named.uniq <- sort(unique(unlist(resplist)))
uniq.resp <- length(named.uniq)
uniq.mat <- matrix(0, nrow = uniq.resp, ncol = 2)
row.names(uniq.mat) <- named.uniq
colnames(uniq.mat) <- name
for(i in 1:length(resplist)){
uniq.mat[match(resplist[[i]], named.uniq),i] <- 1
}
res.uniq <- numeric(9)
names(res.uniq) <- c("Total Across Groups",
paste("Total", name),
paste("Unique", name),
"McNemar's X^2", "df", "p-value",
"Phi (effect size)")
uniq.totals <- colSums(uniq.mat)
uniq.one <- length(which(uniq.mat[,1] == 1 & uniq.mat[,2] == 0))
uniq.two <- length(which(uniq.mat[,1] == 0 & uniq.mat[,2] == 1))
cont.tab <- matrix(0, nrow = 2, ncol = 2)
diag(cont.tab) <- uniq.totals
cont.tab[1,2] <- uniq.one
cont.tab[2,1] <- uniq.two
uniq.res <- mcnemar.test(cont.tab)
res.uniq[1] <- uniq.resp
res.uniq[2:3] <- uniq.totals
res.uniq[4] <- uniq.one
res.uniq[5] <- uniq.two
res.uniq[6] <- uniq.res$statistic
res.uniq[7] <- uniq.res$parameter
res.uniq[8] <- uniq.res$p.value
res.uniq[9] <- abs(cor(uniq.mat)[1,2])
res$unique <- round(res.uniq, 3)
return(res)
} |
findFormula <-
function (generators, tools) {
if (generators[1] == 1) {
formula <- paste ("freq", " ~ ", 1, sep = "")
return(formula)
}
formula <- paste ("freq", " ~ ", sep = "")
for(i in tools$nVarSets:1) {
if(generators[i] == 1) {
first <- 1
for(j in 1:tools$n) {
if(tools$varSets[i,j] == 1) {
if (first == 1) {
first <- 0
formula <- paste (formula, tools$varNames[j], sep = "")
}
else
formula <- paste (formula, "*", tools$varNames[j], sep = "")
}
}
formula <- paste (formula, " + ", sep = "")
}
}
formula <- substr (formula, 1,nchar(formula)-3)
return(formula)
} |
Chao1 <- function(f) {
x <- f.stats(f)
s.obs <- unname(x["s.obs"])
if(length(f) == 1) f <- c(f, 0)
f0 <- if(f[2] > 0) {
f[1] ^ 2 / (2 * f[2])
} else {
term.1 <- f[1] * (f[1] - 1)
term.2 <- 2 * (f[2] + 1)
term.1 / term.2
}
f0 <- f0 * (x["n"] - 1) / x["n"]
x <- c(s.est = unname(f0 + s.obs), f0 = unname(f0), x)
x[is.nan(x)] <- NA
x
} |
powerTransform.lmerMod <- function(object, family="bcPower", ...) {
if(family=="bcnPower") estimateTransform.bcnPowerlmer(object, ...) else
estimateTransform.lmerMod(object, family=family, ...)
}
estimateTransform.lmerMod <- function(object, family="bcPower", lambda=c(-3, 3), start=NULL, method="L-BFGS-B", ...) {
data <- model.frame(object)
if(any(unlist(lapply(as.list(data), class)) == "AsIs")) stop(
"powerTransform for lmer models don't work with the 'I' function; rewrite your formula"
)
y <- (object@resp)$y
fam <- matchFun(family)
llik <- function(lambda){
data$y.lambda <- fam(y, lambda, jacobian.adjusted=TRUE)
m.lambda <- update(object, y.lambda ~ ., data=data)
logLik(m.lambda)
}
if (is.null(start)) start <- 1
res<- optimize(f = function(lambda1) llik(lambda1), lower=lambda[1], upper=lambda[2],
maximum=TRUE)
res$hessian <- optimHess(res$maximum, llik, ...)
res$invHess <- solve(-res$hessian)
res$lambda <- res$maximum
res$value <- c(res$objective)
roundlam <- res$lambda
stderr <- sqrt(diag(res$invHess))
lamL <- roundlam - 1.96 * stderr
lamU <- roundlam + 1.96 * stderr
for (val in rev(c(1, 0, -1, .5, .33, -.5, -.33, 2, -2))) {
sel <- lamL <= val & val <= lamU
roundlam[sel] <- val
}
res$model <- object
res$roundlam <- roundlam
res$family<-family
class(res) <- c("lmerModpowerTransform", "powerTransform")
res
}
testTransform.lmerModpowerTransform <- function(object, lambda=1){
fam <- matchFun(object$family)
model <- object$model
y <- (model@resp)$y
local.data <- model.frame(model)
local.data$y.lambda <- fam(y, lambda, jacobian.adjusted=TRUE)
m.lambda <- update(model, y.lambda ~ ., data=local.data)
llik <- logLik(m.lambda)
LR <- c(2 * (object$value - llik))
df <- 1
pval <- 1-pchisq(LR, df)
out <- data.frame(LRT=LR, df=df, pval=format.pval(pval))
rownames(out) <-
c(paste("LR test, lambda = (",
paste(round(lambda, 2), collapse=" "), ")", sep=""))
out} |
multRepl <-
function(X,label=NULL,dl=NULL,frac=0.65,imp.missing=FALSE,closure=NULL,z.warning=0.8,delta=NULL){
if (any(X<0, na.rm=T)) stop("X contains negative values")
if (imp.missing==FALSE){
if (is.character(dl) || is.null(dl)) stop("dl must be a numeric vector or matrix")
if (is.vector(dl)) dl <- matrix(dl,nrow=1)
dl <- as.matrix(dl)
}
if (is.character(X)) stop("X is not a valid data matrix or vector.")
if (is.null(label)) stop("A value for label must be given")
if (!is.na(label)){
if (!any(X==label,na.rm=T)) stop(paste("Label",label,"was not found in the data set"))
if (label!=0 & any(X==0,na.rm=T)) stop("Zero values not labelled as censored or missing values were found in the data set")
if (any(is.na(X))) stop(paste("NA values not labelled as censored or missing values were found in the data set"))
}
if (is.na(label)){
if (any(X==0,na.rm=T)) stop("Zero values not labelled as censored or missing values were found in the data set")
if (!any(is.na(X),na.rm=T)) stop(paste("Label",label,"was not found in the data set"))
}
if (is.vector(X)){
if (imp.missing==TRUE) stop("Data matrix required: missing values cannot be imputed in single vectors")
if (ncol(dl)!=ncol(as.data.frame(matrix(X,ncol=length(X)),stringsAsFactors=TRUE))) stop("The number of columns in X and dl do not agree")
}
if (!is.vector(X)){
if (imp.missing==FALSE){
if (ncol(dl)!=ncol(X)) stop("The number of columns in X and dl do not agree")
if ((nrow(dl)>1) & (nrow(dl)!=nrow(X))) stop("The number of rows in X and dl do not agree")
}
}
if (!missing("delta")){
warning("The delta argument is deprecated, use frac instead: frac has been set equal to delta.")
frac <- delta
}
gm <- function(x, na.rm=TRUE){
exp(sum(log(x), na.rm=na.rm) / length(x[!is.na(x)]))
}
nam <- NULL
if (!is.null(names(X))) nam <- names(X)
if (is.vector(X)) X <- as.data.frame(matrix(X,ncol=length(X)),stringsAsFactors=TRUE)
X[X==label] <- NA
X <- apply(X,2,as.numeric)
if (is.vector(X)) X <- as.data.frame(matrix(X,ncol=length(X)),stringsAsFactors=TRUE)
if (nrow(X) > 1){
checkNumZerosCol <- apply(X,2,function(x) sum(is.na(x)))
if (any(checkNumZerosCol/nrow(X) == 1)) {
stop(paste("Column(s) containing all zeros/unobserved values were found (check it out using zPatterns).",sep=""))
}
else{
if (any(checkNumZerosCol/nrow(X) > z.warning)) {
warning(paste("Column(s) containing more than ",z.warning*100,"% zeros/unobserved values were found (check it out using zPatterns).
(You can use the z.warning argument to modify the warning threshold).",sep=""))
}
}
checkNumZerosRow <- apply(X,1,function(x) sum(is.na(x)))
if (any(checkNumZerosRow/ncol(X) == 1)) {
stop(paste("Row(s) containing all zeros/unobserved values were found (check it out using zPatterns).",sep=""))
}
else{
if (any(checkNumZerosRow/ncol(X) > z.warning)) {
warning(paste("Row(s) containing more than ",z.warning*100,"% zeros/unobserved values were found (check it out using zPatterns).
(You can use the z.warning argument to modify the warning threshold).",sep=""))
}
}
}
nn <- nrow(X); D <- ncol(X)
c <- apply(X,1,sum,na.rm=TRUE)
closed <- 0
if (all(abs(c - mean(c)) < .Machine$double.eps^0.3)) closed <- 1
if (imp.missing==FALSE){
if (nrow(dl)==1) dl <- matrix(rep(1,nn),ncol=1)%*%dl
}
Y <- X
if (!is.null(closure)){
if (closed == 1) {stop("closure: The data are already closed to ",c[1])}
resid <- apply(X,1, function(x) closure-sum(x, na.rm = TRUE))
Xresid <- cbind(X,resid,stringsAsFactors=TRUE)
c <- rep(closure,nn)
Y <- Xresid
}
if (imp.missing==FALSE){
for (i in 1:nn){
if (any(is.na(X[i,]))){
z <- which(is.na(X[i,]))
Y[i,z] <- frac*dl[i,z]
if (!is.null(closure)){
Y[i,-z] <- (1-(sum(Y[i,z]))/c[i])*Xresid[i,-z]
tmp <- Y[i,-(D+1)]
X[i,z] <- as.numeric((X[i,-z][1]/tmp[-z][1]))*Y[i,z]
}
else{
Y[i,-z] <- (1-(sum(Y[i,z]))/c[i])*X[i,-z]
X[i,z] <- as.numeric((X[i,-z][1]/Y[i,-z][1]))*Y[i,z]
}
}
}
}
if (imp.missing==TRUE){
gms <- apply(X,2,gm)
for (i in 1:nn){
if (any(is.na(X[i,]))){
z <- which(is.na(X[i,]))
Y[i,z] <- gms[z]
if (!is.null(closure)){
Y[i,-z] <- ((c[i]-(sum(Y[i,z])))/sum(Xresid[i,-z]))*Xresid[i,-z]
tmp <- Y[i,-(D+1)]
X[i,z] <- as.numeric((X[i,-z][1]/tmp[-z][1]))*Y[i,z]
}
else{
Y[i,-z] <- ((c[i]-(sum(Y[i,z])))/sum(X[i,-z]))*X[i,-z]
X[i,z] <- as.numeric((X[i,-z][1]/Y[i,-z][1]))*Y[i,z]
}
}
}
}
if (!is.null(nam)) names(X) <- nam
if (closed==1){
X <- t(apply(X,1,function(x) x/sum(x)*c[1]))
}
if (any(X < 0)) warning("multRepl: negative imputed values were generated (please check out help for advice)")
return(as.data.frame(X,stringsAsFactors=TRUE))
} |
packageLog <- function(packages = "cholera", date = NULL, all.filters = FALSE,
ip.filter = FALSE, triplet.filter = FALSE, small.filter = FALSE,
sequence.filter = FALSE, size.filter = FALSE, memoization = TRUE,
check.package = TRUE, clean.output = FALSE, multi.core = TRUE) {
if (check.package) packages <- checkPackage(packages)
pkg.order <- packages
ymd <- logDate(date)
cran_log <- fetchCranLog(date = ymd, memoization = memoization)
cran_log <- cleanLog(cran_log)
cores <- multiCore(multi.core)
if (all.filters) {
ip.filter <- TRUE
triplet.filter <- TRUE
small.filter <- TRUE
sequence.filter <- TRUE
size.filter <- TRUE
}
pkg_specific_filters <- c(triplet.filter, sequence.filter, size.filter)
if (ip.filter) {
row.delete <- ipFilter(cran_log, multi.core = cores)
cran_log <- cran_log[!row.names(cran_log) %in% row.delete, ]
}
if (any(pkg_specific_filters)) {
out <- parallel::mclapply(packages, function(p) {
cran_log[cran_log$package == p, ]
}, mc.cores = cores)
if (triplet.filter) {
out <- parallel::mclapply(out, tripletFilter, mc.cores = cores)
}
if (small.filter) {
out <- parallel::mclapply(out, smallFilter, mc.cores = cores)
}
if (sequence.filter) {
arch.pkg.history <- parallel::mclapply(packages, function(x) {
tmp <- packageHistory(x)
tmp[tmp$Date <= ymd & tmp$Repository == "Archive", ]
}, mc.cores = cores)
out <- parallel::mclapply(seq_along(out), function(i) {
sequenceFilter(out[[i]], arch.pkg.history[[i]])
}, mc.cores = cores)
}
if (size.filter) out <- sizeFilter(out, packages, cores)
names(out) <- packages
} else {
if (small.filter) cran_log <- smallFilter(cran_log)
out <- lapply(packages, function(p) cran_log[cran_log$package == p, ])
names(out) <- packages
}
out <- parallel::mclapply(out, function(x) {
if (!"t2" %in% names(x)) x$date.time <- dateTime(x$date, x$time)
tmp <- x[order(x$date.time), ]
tmp$date.time <- NULL
tmp
}, mc.cores = cores)
if (length(packages) == 1) {
out[[1]]
} else {
out[pkg.order]
}
} |
sor <- function(y.formula,
w1.formula,
w2.formula = ~1,
id,
waves=NULL,
family = "binomial",
y0 = 0,
hfunc = identity,
support = c(0,1),
pi1.pi0.ratio = 1,
data = parent.frame(),
init.beta=NULL,
init.sig.2 = 1,
weights=NULL,
est.var = TRUE,
CORSTR="independence"){
call <- match.call()
fam <- as.character(charmatch(family, c("gaussian", "normal", "poisson", "binomial")))
if(fam=="2") fam <- "1"
if(typeof(data) == "environment"){
id = id
waves <- waves
weights <- weights
DAT.ods <- data.frame(model.frame(y.formula), model.frame(w1.formula), model.frame(w2.formula))
}else{
DAT.ods <- data
nn <- dim(DAT.ods)[1]
if(length(call$id) == 1){
subj.col <- which(colnames(data) == call$id)
if(length(subj.col) > 0){
id <- data[,subj.col]
}else{
id <- eval(call$id, envir=parent.frame())
}
}else if(is.null(call$id)){
id <- 1:nn
}
if(length(call$weights) == 1){
weights.col <- which(colnames(data) == call$weights)
if(length(weights.col) > 0){
weights <- data[,weights.col]
}else{
weights <- eval(call$weights, envir=parent.frame())
}
}else if(is.null(call$weights)){
weights <- rep.int(1,nn)
}
if(length(call$waves) == 1){
waves.col <- which(colnames(data) == call$waves)
if(length(waves.col) > 0){
waves <- data[,waves.col]
}else{
waves <- eval(call$waves, envir=parent.frame())
}
}else if(is.null(call$waves)){
waves <- NULL
}
}
ny <- length(support)
DAT.ods$id <- id
DAT.ods$waves <- waves
DAT.ods$weights <- weights
DAT.ods$offset.z <- log(pi1.pi0.ratio)
DAT.ods$pi.ratio <- pi1.pi0.ratio
if(!is.numeric(DAT.ods$waves) & !is.null(DAT.ods$waves)) stop("waves must be either an integer vector or NULL")
na.inds <- NULL
if(any(is.na(DAT.ods))){
na.inds <- which(is.na(DAT.ods), arr.ind=T)
}
if(!is.null(waves)){
DAT.ods <- DAT.ods[order(id, waves),]
}else{
DAT.ods <- DAT.ods[order(id),]
}
cor.vec <- c("independence", "ar1", "exchangeable", "m-dependent", "unstructured", "fixed", "userdefined")
cor.match <- charmatch(CORSTR, cor.vec)
if(is.na(cor.match)){stop("Unsupported correlation structure")}
if(!is.null(DAT.ods$waves)){
wavespl <- split(DAT.ods$waves, DAT.ods$id)
idspl <- split(DAT.ods$id, DAT.ods$id)
maxwave <- rep(0, length(wavespl))
incomp <- rep(0, length(wavespl))
for(i in 1:length(wavespl)){
maxwave[i] <- max(wavespl[[i]]) - min(wavespl[[i]]) + 1
if(maxwave[i] != length(wavespl[[i]])){
incomp[i] <- 1
}
}
if(!is.element(cor.match, c(1,3)) & (sum(incomp) > 0) ){
DAT.ods <- dummyrows(y.formula, DAT.ods, incomp, maxwave, wavespl, idspl)
id <- DAT.ods$id
waves <- DAT.ods$waves
weights <- DAT.ods$weights
}
}
if(!is.null(na.inds)){
weights[unique(na.inds[,1])] <- 0
for(i in unique(na.inds)[,2]){
if(is.factor(DAT.ods[,i])){
DAT.ods[na.inds[,1], i] <- levels(DAT.ods[,i])[1]
}else{
DAT.ods[na.inds[,1], i] <- median(DAT.ods[,i], na.rm=T)
}
}
}
includedvec <- weights>0
inclsplit <- split(includedvec, id)
dropid <- NULL
allobs <- T
if(any(!includedvec)){
allobs <- F
for(i in 1:length(unique(id))){
if(all(!inclsplit[[i]])){
dropid <- c(dropid, i)
}
}
}
if(length(dropid)>0){
dropind <- which(is.element(id, dropid))
DAT.ods <- DAT.ods[-dropind,]
includedvec <- includedvec[-dropind]
weights <- weights[-dropind]
id <- id[-dropind]
}
nn <- dim(DAT.ods)[1]
K <- length(unique(id))
yframe <- model.frame(y.formula, DAT.ods)
resp <- model.response(yframe)
w1frame <- model.frame(w1.formula, DAT.ods)
ref <- model.response(w1frame)
w2frame <- model.frame(w2.formula, DAT.ods)
if(!all( is.element(ref, c(0,1)))){stop("Response in w1.formula must be binary")}
if(!all(ref==model.response(w2frame)) && !is.null(model.response(w2frame))){stop("There should be no response for w2.formula")}
if(max(resp) > max(support) | min(resp) < min(support)) warning("Some values of response are outside support")
switch(fam,
"1"= {
results <- norm.SOR(y.formula, w1.formula, w2.formula, y0, hfunc, id, support, pi1.pi0.ratio, DAT.ods, init.beta, init.sig.2, est.var, CORSTR, weights=DAT.ods$weights)
},
"3" = {
if(!all( is.wholenumber(resp))){stop("Response in y.formula must be positive integers if family is Poisson")}
if(init.sig.2 != 1){warning("Initial variance specification ignored")}
results <- pois.SOR(y.formula, w1.formula, w2.formula, y0, hfunc, id, support, pi1.pi0.ratio, DAT.ods, init.beta, est.var=est.var, CORSTR=CORSTR, weights=DAT.ods$weights)
},
"4" = {
if(!all( is.element(resp, c(0,1)))){stop("Response in y.formula must be binary if family is binomial")}
if(y0 != 0){warning("Setting y0 to 0")}
results <- binom.SOR(y.formula, w1.formula, w2.formula, DAT.ods, init.beta, CORSTR)
}
)
class(results) <- "sor"
results$coefnames <- colnames(model.matrix(y.formula, DAT.ods))
results$call <- call
results$family <- c("normal","normal", "Poisson", "binomial")[as.numeric(fam)]
return(results)
}
print.sor <- function(x, ...){
coefdf <- data.frame(x$coefs)
rownames(coefdf) <- x$coefnames
colnames(coefdf) <- ""
print(x$call)
cat("\n", "Coefficients:", "\n")
print(t(coefdf))
cat("\n Reference Distribution: ", x$family, "\n")
}
summary.sor <- function(object, ...) {
Coefs <- matrix(0,nrow=length(object$coefs),ncol=4)
Coefs[,1] <- c(object$coefs)
Coefs[,2] <- object$se.coefs
Coefs[,3] <- Coefs[,1]/Coefs[,2]
Coefs[,4] <- round(2*pnorm(abs(Coefs[,3]), lower.tail=F), digits=8)
colnames(Coefs) <- c("Estimates","Std. Err.", "wald", "p")
summ <- list(coefs = Coefs[,1], se.coefs = Coefs[,2], wald.test = Coefs[,3], p = Coefs[,4],
coefnames = object$coefnames, family=object$family, call=object$call)
class(summ) <- 'summary.sor'
return(summ)
}
print.summary.sor <- function(x, ...){
Coefs <- matrix(0,nrow=length(x$coefnames),ncol=4)
rownames(Coefs) <- c(x$coefnames)
colnames(Coefs) <- c("Estimates","Std. Err.", "wald", "p")
Coefs[,1] <- x$coefs
Coefs[,2] <- x$se.coefs
Coefs[,3] <- x$wald.test
Coefs[,4] <- x$p
print( x$call)
cat("\n")
print(Coefs)
cat("\n Reference Distribution: ", x$family, "\n")
} |
expected <- TRUE
test(id=1, code={
argv <- structure(list(x = "`", value = TRUE), .Names = c("x", "value"
))
do.call('assign', argv);
}, o = expected);
|
context("MFAEstimate")
if (requireNamespace("mfa", quietly = TRUE)) {
library(mfa)
synth <- create_synthetic(C = 20, G = 5, zero_negative = TRUE,
model_dropout = TRUE)
}
test_that("MFAEstimate works", {
skip_if_not_installed("mfa")
params <- mfaEstimate(synth$X)
expect_true(validObject(params))
}) |
context("taxonomic map")
test_that("levelmap works correctly", {
data(dietswap)
tt <- tax_table(dietswap)
expect_equal(map_levels('Akkermansia', from = 'Genus', to = 'Phylum', tt), "Verrucomicrobia")
expect_equal(map_levels('Verrucomicrobia', from = 'Phylum', to = 'Genus', tt)$Verrucomicrobia, "Akkermansia")
}) |
context("xyzt_units attribute")
nim <- readNIfTI(system.file("nifti/mniRL.nii.gz", package = "oro.nifti"))
test_that("xyzt_units()", {
expect_equal(xyzt_units(nim), 10)
})
test_that("xyzt.units()", {
expect_equal(xyzt.units(nim), 10)
})
test_that("xyzt_units<-()", {
xyzt_units(nim) <- 11
expect_equal(xyzt_units(nim), 11)
})
test_that("xyzt.units<-()", {
xyzt.units(nim) <- 12
expect_equal(xyzt.units(nim), 12)
}) |
library(itertools)
library(foreach)
n <- 10
x <- matrix(rnorm(n * n), n)
y <-
foreach(a=iarray(x, c(1,2), chunks=2), .combine='cbind') %:%
foreach(b=a, .combine='rbind') %do% {
b
}
print(identical(x, y)) |
FDRpenalties <-
function(n, k = n - 1, m = min(n - 2, k), fdr = .1, reps = 50000, rnd = 3){
if(!isTRUE(all.equal(n%%4,0))) stop("n must be a multiple of 4")
if(!isTRUE(all.equal(k%%1,0))) stop("k must be an integer")
if(!isTRUE(all.equal(m%%1,0))) stop("m must be an integer")
if(k > n - 1) stop("k cannot be greater than n-1")
if(k < 1) stop("k cannot be less than 1")
if(m > k) stop("m cannot be greater than k")
if(m < 1) stop("m cannot be less than 1")
if(m > (n-2)) stop("m cannot be greater than n-2")
if(m > k) stop("m cannot be greater than k")
if(fdr <= 0) stop("fdr must be greater than 0")
if(fdr >= 1) stop("fdr must be less than 1")
if (fdr > 1/m) warning("fdr > 1/m which results in some penalties being equal")
cs <- NULL
startj <- m - 1
if((fdr * m) >= 1){
num <- floor(fdr * m)
cs <- rep(0, num)
startj <- m - 1 - num
}
for(j in startj:0){
sqres <- matrix(rnorm(reps * (n - 1 - j)) ^ 2, reps, n - 1 - j)
if((n - k) != (n - 1 - j)) sqres[, (n - k):(n - 1 - j)] <- t(apply(sqres[ ,(n - k):(n - 1 - j)], 1, sort))
lRSS <- log(apply(sqres, 1, cumsum)[(n - m - 1):(n - 1 - j), ])
d1<-dim(lRSS)[1]
if(d1 == 2){
out <- lRSS[2, ]- lRSS[1, ]
cs <- as.numeric(quantile(out, 1 - (fdr * m)))
}
if(d1 > 2){
out <- lRSS[d1, ] - apply((lRSS[-d1, ] + c(cs, 0)), 2, min)
wts <- d1 - apply((lRSS[-d1, ] + c(cs, 0)), 2, order)[1, ]
wts <- wts / (wts + j)
ord <- order(out, decreasing = TRUE)
oout <- out[ord]
owts <- cumsum(wts[ord])
toterrs <- reps * fdr
newc <- min(oout[owts <= toterrs])
cs <- c(cs + newc, newc)
}
}
cs <- round(c(0, cs[length(cs):1]), rnd)
attributes(cs) <- NULL
return(cs)
} |
setGeneric("fix_phylo", function(tree) standardGeneric("fix_phylo") )
setMethod("fix_phylo", "phylo", function(tree){
tree$edge.length[which(is.na(tree$edge.length))] <- 0
return(tree)
}) |
context("plotPoints.pcoadata")
morphoDataFrame = data.frame("ID" = c("id1","id2","id3","id4","id5","id6","id7","id8"),
"Population" = c("Pop1", "Pop1", "Pop2", "Pop2", "Pop3", "Pop3", "Pop4", "Pop4"),
"Taxon" = c("TaxA", "TaxA", "TaxA", "TaxA", "TaxB", "TaxB", "TaxB", "TaxB"),
"Ch1" = c(1,3,4,6,1,7,12,8),
"Ch2" = c(11, 12,42,12,32,11,22,18))
morphoMockup = .morphodataFromDataFrame(morphoDataFrame)
data(centaurea)
centaurea = suppressWarnings(naMeanSubst(centaurea))
centaurea = deletePopulation(centaurea, populationName = c("LIP", "PREL"))
test_that("ploting with error parameters", {
pcoaRes = pcoa.calc(morphoMockup)
expect_is(pcoaRes, "pcoadata")
expect_error(plotPoints(pcoaRes, axes = c(3,33)))
expect_error(plotPoints(pcoaRes, axes = c(1,1,2)))
}) |
context("Sodium Compatibility")
test_that("Signatures are compatible with sodium", {
skip_if_not(openssl_config()$x25519)
sk <- sodium::sig_keygen()
pk <- sodium::sig_pubkey(sk)
msg <- serialize(iris, NULL)
key <- read_ed25519_key(sk)
pubkey <- read_ed25519_pubkey(pk)
sig1 <- sodium::sig_sign(msg, key = sk)
expect_true(sodium::sig_verify(msg, sig1, pk))
expect_true(ed25519_verify(msg, sig1, pubkey = pubkey))
sig2 <- ed25519_sign(msg, key)
expect_true(sodium::sig_verify(msg, sig2, pk))
expect_true(ed25519_verify(msg, sig2, pubkey = pubkey))
})
test_that("Diffie Hellman is compatible with sodium", {
skip_if_not(openssl_config()$x25519)
sk1 <- sodium::keygen()
sk2 <- sodium::keygen()
dh1 <- sodium::diffie_hellman(sk1, sodium::pubkey(sk2))
key <- read_x25519_key(sk2)
pubkey <- read_x25519_pubkey(sodium::pubkey(sk1))
dh2 <- x25519_diffie_hellman(key, pubkey)
expect_equal(dh1, dh2)
}) |
pifit.internal <- function(object){
X <- object[["X"]]
mt_vek <- apply(X, 2L, max, na.rm = TRUE)
mt_ind <- rep(seq_along(mt_vek), mt_vek)
mt_seq <- sequence(mt_vek)
gmemb <- object$gmemb
pmat <- pmat(object)
Emat.cat <- t(apply(pmat, 1L, function(x) x*mt_seq))
if(object$model %in% c("RM", "LLTM")){
Emat <- Emat.cat
} else {
E.list <- tapply(seq_along(mt_ind), mt_ind, function(ind){ rowSums(cbind(Emat.cat[, ind]), na.rm = TRUE) })
Emat <- matrix(unlist(E.list),ncol=dim(X)[2],dimnames=list(rownames(pmat),colnames(X)))
}
pmat.l0 <- tapply(seq_along(mt_ind), mt_ind, function(ind){
vec0 <- 1-rowSums(as.matrix(pmat[,ind]))
cbind(vec0,pmat[,ind])
})
pmat0 <- matrix(unlist(pmat.l0),nrow=length(gmemb))
mt_vek0 <- integer(0)
for (i in mt_vek) mt_vek0 <- c(mt_vek0, 0:i)
mt_ind0 <- rep(1:length(mt_vek),mt_vek+1)
colnames(Emat) <- NULL
Emat0 <- t(apply(Emat[,mt_ind0],1,function(x) {mt_vek0 - x}))
Vmat.cat <- (Emat0)^2*pmat0
V.list <- tapply(1:length(mt_ind0),mt_ind0, function(ind) {rowSums(Vmat.cat[,ind],na.rm=TRUE)})
Vmat <- matrix(unlist(V.list),ncol=dim(X)[2],dimnames=list(rownames(pmat),colnames(X)))
Cmat.cat <- (Emat0)^4*pmat0
C.list <- tapply(1:length(mt_ind0),mt_ind0, function(ind) {rowSums(Cmat.cat[,ind],na.rm=TRUE)})
Cmat <- matrix(unlist(C.list),ncol=dim(X)[2],dimnames=list(rownames(pmat),colnames(X)))
result <- list(Emat=Emat,Vmat=Vmat,Cmat=Cmat)
} |
sim.din <- function( N=0, q.matrix, guess=rep(.2, nrow(q.matrix) ), slip=guess,
mean=rep(0, ncol(q.matrix) ), Sigma=diag( ncol(q.matrix) ), rule="DINA",
alpha=NULL)
{
if (N>0){
normsim <- CDM_rmvnorm( N, mean, Sigma)
dichsim <- 1 * ( normsim > 0 )
}
if ( ! is.null( alpha) ){
dichsim <- alpha
N <- nrow(alpha)
}
poss.attr <- dichsim %*% t( q.matrix )
ness.attr <- ( rowSums(q.matrix) )*( rule=="DINA") + 1* ( rule=="DINO" )
eta.pp <- poss.attr >=outer( rep(1,N), ness.attr )
R <- matrix( eta.pp * stats::rbinom( N*nrow(q.matrix), size=1, prob=1 - outer( rep(1,N), slip ) ) +
( 1 - eta.pp) * stats::rbinom( N*nrow(q.matrix), size=1,
prob=outer( rep(1,N), guess ) ), ncol=nrow(q.matrix) )
colnames(R) <- paste( "I", substring( 1000 + 1:( nrow(q.matrix) ), 2), sep="")
res <- list( "dat"=R, "alpha"=dichsim )
return(res)
} |
intCol <-function ()
{
dialogName<-"intCol"
def <- list(dsname="Do_Not_Save", tfVar=100, clVar= 20, lnVar=20, fiVar=0.4, iVar=0.1, peVar=0.05, animaVar= 1)
initial <- getDialog(dialogName, defaults= def)
initializeDialog(title = gettextRcmdr("Internal Colonization"))
dsname <- tclVar(initial$dsname)
tfVar <- tclVar(initial$tfVar)
clVar <- tclVar(initial$clVar)
lnVar <- tclVar(initial$lnVar)
fiVar <- tclVar(initial$fiVar)
iVar <- tclVar(initial$iVar)
peVar <- tclVar(initial$peVar)
animaVar <- tclVar(initial$animaVar)
entryDsname <- tkentry(top, width="20", textvariable=dsname)
tfEntry <- tkentry(top, width = "4", textvariable = tfVar)
clEntry <- tkentry(top, width = "4", textvariable = clVar)
lnEntry <- tkentry(top, width = "4", textvariable = lnVar)
fiVarSlider <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=fiVar, resolution=0.01, orient="horizontal")
iEntry <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=iVar, resolution=0.01, orient="horizontal")
peEntry <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=peVar, resolution=0.01, orient="horizontal")
animaBox <- tkcheckbutton(top, variable = animaVar)
onOK <- function()
{
closeDialog()
tf <- round(as.numeric(tclvalue(tfVar)))
if (is.na(tf) || tf <= 0)
{
errorCondition(message = "Number of simulations must be a positive integer")
return()
}
cl <- round(as.numeric(tclvalue(clVar)))
if (is.na(cl) || cl <= 0)
{
errorCondition(message = "Number of columns on the simulated arena must be a positive integer.")
return()
}
ln <- round(as.numeric(tclvalue(lnVar)))
if (is.na(ln) || ln <= 0)
{
errorCondition("Number of lines on the simulated arena must be a positive integer.")
return()
}
i <- as.numeric(tclvalue(iVar))
if (i<0 || i > 10)
{
errorCondition(message = "Colonization constant must be between 0 and 10")
return()
}
fi <- as.numeric(tclvalue(fiVar))
pe <- as.numeric(tclvalue(peVar))
animaVF <- as.logical(as.numeric(tclvalue(animaVar)))
dsnameValue <- trim.blanks(tclvalue(dsname))
if (dsnameValue == "Do_Not_Save" | dsnameValue=="")
{
command <- paste("metaCi(tmax = ",tf, ", cl = ", cl,", f0 = ", fi,", rw =", ln,", ci = ", i,", pe = ", pe, ", anima = ", animaVF,")", sep = "")
}
else
{
command <- paste(dsnameValue,"<- metaCi(tmax = ",tf, ", cl = ", cl,", f0 = ", fi,", rw =", ln,", ci = ", i,", pe = ", pe, ", anima = ", animaVF,")", sep = "")
}
putDialog(dialogName, values = list(dsname=dsnameValue, tfVar= round(as.numeric(tclvalue(tfVar))), clVar= round(as.numeric(tclvalue(clVar))), lnVar= round(as.numeric(tclvalue(lnVar))), fiVar= as.numeric(tclvalue(fiVar)), iVar=as.numeric(tclvalue(iVar)), peVar=as.numeric(tclvalue(peVar)), animaVar=as.logical(as.numeric(tclvalue(animaVar)))),resettable = FALSE)
doItAndPrint(command)
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject = "metapopulation", reset=dialogName, apply= dialogName)
tkgrid(tklabel(top, text="Enter name for data set: "), entryDsname, sticky="e")
tkgrid(tklabel(top, text="Simulation Arena Conditions : ", fg="blue"), sticky="w")
tkgrid(tklabel(top, text = "Maximum time "), tfEntry, sticky = "e")
tkgrid(tklabel(top, text = "Columns "), clEntry, sticky = "e")
tkgrid(tklabel(top, text = "Rows "), lnEntry, sticky = "e")
tkgrid(tklabel(top, text="Species parameters :", fg="blue"), sticky="w")
tkgrid(tklabel(top, text="Initial occupancy "), fiVarSlider, sticky="se")
tkgrid(tklabel(top, text = "Colonization coefficient "), iEntry, sticky = "e")
tkgrid(tklabel(top, text = "Extinction probability "), peEntry, sticky = "se")
tkgrid(tklabel(top, text = "Show simulation frames"), animaBox, sticky = "e")
tkgrid(buttonsFrame, sticky = "w", columnspan = 2)
tkgrid.configure(entryDsname, sticky = "w")
tkgrid.configure(tfEntry, sticky = "w")
tkgrid.configure(clEntry, sticky = "w")
tkgrid.configure(lnEntry, sticky = "w")
tkgrid.configure(fiVarSlider, sticky = "w")
tkgrid.configure(iEntry, sticky = "w")
tkgrid.configure(peEntry, sticky = "w")
tkgrid.configure(animaBox, sticky = "w")
dialogSuffix(rows = 9, columns = 2, focus = tfEntry)
}
propRain <-function()
{
dialogName<-"propRain"
def <- list(dsname="Do_Not_Save", tfVar=100, clVar= 20, lnVar=20, fiVar=0.4, piVar=0.1, peVar=0.05, animaVar=1)
initial <- getDialog(dialogName, defaults= def)
initializeDialog(title = gettextRcmdr("Propagulus Rain"))
dsname <- tclVar(initial$dsname)
tfVar <- tclVar(initial$tfVar)
clVar <- tclVar(initial$clVar)
lnVar <- tclVar(initial$lnVar)
fiVar <- tclVar(initial$fiVar)
piVar <- tclVar(initial$piVar)
peVar <- tclVar(initial$peVar)
animaVar <- tclVar(initial$animaVar)
entryDsname <- tkentry(top, width="20", textvariable=dsname)
tfEntry <- tkentry(top, width = "4", textvariable = tfVar)
clEntry <- tkentry(top, width = "4", textvariable = clVar)
lnEntry <- tkentry(top, width = "4", textvariable = lnVar)
fiEntry <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=fiVar, resolution=0.01, orient="horizontal")
piEntry <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=piVar, resolution=0.01, orient="horizontal")
peEntry <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=peVar, resolution=0.01, orient="horizontal")
animaBox <- tkcheckbutton(top, variable = animaVar)
onOK <- function()
{
closeDialog()
tf <- round(as.numeric(tclvalue(tfVar)))
if (is.na(tf) || tf <= 0)
{
errorCondition(message = "Number of simulations must be a positive integer")
return()
}
cl <- round(as.numeric(tclvalue(clVar)))
if (is.na(cl) || cl <= 0)
{
errorCondition(message = "Number of columns on the simulated arena must be a positive integer.")
return()
}
ln <- round(as.numeric(tclvalue(lnVar)))
if (is.na(ln) || ln <= 0)
{
errorCondition("Number of lines on the simulated arena must be a positive integer.")
return()
}
fi <- as.numeric(tclvalue(fiVar))
pi <- as.numeric(tclvalue(piVar))
pe <- as.numeric(tclvalue(peVar))
animaVF <- as.logical(as.numeric(tclvalue(animaVar)))
dsnameValue <- trim.blanks(tclvalue(dsname))
if (dsnameValue == "Do_Not_Save" || dsnameValue=="")
{
command <- paste("metaPop(tmax = ",tf, ", cl = ", cl,", f0 = ", fi,", rw =", ln,", pi = ", pi,", pe = ", pe, ", anima = ", animaVF,")", sep = "")
}
else
{
command <- paste(dsnameValue,"<- metaPop(tmax = ",tf, ", cl = ", cl,", f0 = ", fi,", rw =", ln,", pi = ", pi,", pe = ", pe, ", anima = ", animaVF,")", sep = "")
}
putDialog(dialogName, values = list(dsname=dsnameValue, tfVar= round(as.numeric(tclvalue(tfVar))), clVar= round(as.numeric(tclvalue(clVar))), lnVar= round(as.numeric(tclvalue(lnVar))), fiVar= as.numeric(tclvalue(fiVar)), piVar=as.numeric(tclvalue(piVar)), peVar=as.numeric(tclvalue(peVar)), animaVar=as.logical(as.numeric(tclvalue(animaVar)))),resettable = FALSE)
doItAndPrint(command)
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject = "metapopulation", reset=dialogName, apply= dialogName)
tkgrid(tklabel(top, text="Enter name for data set: "), entryDsname, sticky="e")
tkgrid(tklabel(top, text="Simulation Arena Conditions : ", fg="blue"), sticky="w")
tkgrid(tklabel(top, text = "Maximum time "), tfEntry, sticky = "e")
tkgrid(tklabel(top, text = "Columns "), clEntry, sticky = "e")
tkgrid(tklabel(top, text = "Rows "), lnEntry, sticky = "e")
tkgrid(tklabel(top, text="Species parameters : ", fg="blue"), sticky="w")
tkgrid(tklabel(top, text = "Initial occupancy "), fiEntry, sticky = "se")
tkgrid(tklabel(top, text = "Colonization probability "), piEntry, sticky = "se")
tkgrid(tklabel(top, text = "Extinction probability "), peEntry, sticky = "se")
tkgrid(tklabel(top, text = "Show simulation frames"), animaBox, sticky = "e")
tkgrid(buttonsFrame, sticky = "w", columnspan = 2)
tkgrid.configure(entryDsname, sticky = "w")
tkgrid.configure(tfEntry, sticky = "w")
tkgrid.configure(clEntry, sticky = "w")
tkgrid.configure(lnEntry, sticky = "w")
tkgrid.configure(fiEntry, sticky = "w")
tkgrid.configure(piEntry, sticky = "w")
tkgrid.configure(peEntry, sticky = "w")
tkgrid.configure(animaBox, sticky = "w")
dialogSuffix(rows = 8, columns = 2, focus = tfEntry)
}
resEff <-function ()
{
dialogName<-"resEff"
def <- list(dsname="Do_Not_Save", tfVar=100, clVar= 20, lnVar=20, fiVar=0.4, piVar=0.1, eVar = 0.05, animaVar=1)
initial <- getDialog(dialogName, defaults= def)
initializeDialog(title = gettextRcmdr("Rescue Effect"))
dsname <- tclVar(initial$dsname)
tfVar <- tclVar(initial$tfVar)
clVar <- tclVar(initial$clVar)
lnVar <- tclVar(initial$lnVar)
fiVar <- tclVar(initial$fiVar)
piVar <- tclVar(initial$piVar)
eVar <- tclVar(initial$eVar)
animaVar <- tclVar(initial$animaVar)
entryDsname <- tkentry(top, width="20", textvariable=dsname)
tfEntry <- tkentry(top, width = "4", textvariable = tfVar)
clEntry <- tkentry(top, width = "4", textvariable = clVar)
lnEntry <- tkentry(top, width = "4", textvariable = lnVar)
fiEntry <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=fiVar, resolution=0.01, orient="horizontal")
piEntry <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=piVar, resolution=0.01, orient="horizontal")
eEntry <- tkscale(top, from=0, to=1, showvalue=TRUE, variable = eVar, resolution=0.01, orient="horizontal")
animaBox <- tkcheckbutton(top, variable = animaVar)
onOK <- function()
{
closeDialog()
tf <- round(as.numeric(tclvalue(tfVar)))
if (is.na(tf) || tf <= 0)
{
errorCondition(message = "Number of simulations must be a positive integer")
return()
}
cl <- round(as.numeric(tclvalue(clVar)))
if (is.na(cl) || cl <= 0)
{
errorCondition(message = "Number of columns on the simulated arena must be a positive integer.")
return()
}
ln <- round(as.numeric(tclvalue(lnVar)))
if (is.na(ln) || ln <= 0)
{
errorCondition("Number of lines on the simulated arena must be a positive integer.")
return()
}
ce <- as.numeric(tclvalue(eVar))
fi <- as.numeric(tclvalue(fiVar))
pi <- as.numeric(tclvalue(piVar))
animaVF <- as.logical(as.numeric(tclvalue(animaVar)))
dsnameValue <- trim.blanks(tclvalue(dsname))
if (dsnameValue == "Do_Not_Save" | dsnameValue=="")
{
command <- paste("metaEr(tmax = ",tf, ", cl = ", cl,", f0 = ", fi,", rw =", ln,", pi = ", pi,", ce = ", ce,", anima =", animaVF, ")", sep = "")
}
else
{
command <- paste(dsnameValue,"<-metaEr(tmax = ",tf, ", cl = ", cl,", f0 = ", fi,", rw =", ln,", pi = ", pi,", ce = ", ce, ", anima =", animaVF, ")", sep = "")
}
putDialog(dialogName, values = list(dsname=dsnameValue, tfVar= round(as.numeric(tclvalue(tfVar))), clVar= round(as.numeric(tclvalue(clVar))), lnVar= round(as.numeric(tclvalue(lnVar))), fiVar= as.numeric(tclvalue(fiVar)), piVar=as.numeric(tclvalue(piVar)), eVar=as.numeric(tclvalue(eVar)), animaVar=as.logical(as.numeric(tclvalue(animaVar)))),resettable = FALSE)
doItAndPrint(command)
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject = "metapopulation", reset=dialogName, apply= dialogName)
tkgrid(tklabel(top, text="Enter data set name: "), entryDsname, sticky="e")
tkgrid(tklabel(top, text="Simulation Arena Conditions : ", fg="blue"), sticky="w")
tkgrid(tklabel(top, text = "Maximum time "), tfEntry, sticky = "e")
tkgrid(tklabel(top, text = "Columns "), clEntry, sticky = "e")
tkgrid(tklabel(top, text = "Rows "), lnEntry, sticky = "e")
tkgrid(tklabel(top, text="Species parameters : ", fg="blue"), sticky="w")
tkgrid(tklabel(top, text = "Initial occupancy "), fiEntry, sticky = "e")
tkgrid(tklabel(top, text = "Colonization probability "), piEntry, sticky = "e")
tkgrid(tklabel(top, text = "Extinction coefficient "), eEntry, sticky = "e")
tkgrid(tklabel(top, text = "Show simulation frames"), animaBox, sticky = "e")
tkgrid(buttonsFrame, sticky = "w", columnspan = 2)
tkgrid.configure(entryDsname, sticky = "w")
tkgrid.configure(tfEntry, sticky = "w")
tkgrid.configure(clEntry, sticky = "w")
tkgrid.configure(lnEntry, sticky = "w")
tkgrid.configure(fiEntry, sticky = "w")
tkgrid.configure(piEntry, sticky = "w")
tkgrid.configure(eEntry, sticky = "w")
tkgrid.configure(animaBox, sticky = "w")
dialogSuffix(rows = 11, columns = 2, focus = tfEntry)
}
resEffcol <-function ()
{
dialogName<-"resEffcol"
def <- list(dsname="Do_Not_Save", tfVar=100, clVar= 20, lnVar=20, fiVar=0.25, iVar=0.1, eVar = 0.05, animaVar=1)
initial <- getDialog(dialogName, defaults= def)
initializeDialog(title = gettextRcmdr("Rescue and Internal Colonization"))
dsname <- tclVar(initial$dsname)
tfVar <- tclVar(initial$tfVar)
clVar <- tclVar(initial$clVar)
lnVar <- tclVar(initial$lnVar)
fiVar <- tclVar(initial$fiVar)
iVar <- tclVar(initial$iVar)
eVar <- tclVar(initial$eVar)
animaVar <- tclVar(initial$animaVar)
entryDsname <- tkentry(top, width="20", textvariable=dsname)
tfEntry <- tkentry(top, width = "4", textvariable = tfVar)
clEntry <- tkentry(top, width = "4", textvariable = clVar)
lnEntry <- tkentry(top, width = "4", textvariable = lnVar)
fiEntry <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=fiVar, resolution=0.01, orient="horizontal")
iEntry <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=iVar, resolution=0.01, orient="horizontal")
eEntry <- tkscale(top, from=0, to=1, showvalue=TRUE, variable = eVar, resolution=0.01, orient="horizontal")
animaBox <- tkcheckbutton(top, variable = animaVar)
onOK <- function()
{
closeDialog()
tf <- round(as.numeric(tclvalue(tfVar)))
if (is.na(tf) || tf <= 0)
{
errorCondition(message = "Number of simulations must be a positive integer")
return()
}
cl <- round(as.numeric(tclvalue(clVar)))
if (is.na(cl) || cl <= 0)
{
errorCondition(message = "Number of columns on the simulated arena must be a positive integer.")
return()
}
ln <- round(as.numeric(tclvalue(lnVar)))
if (is.na(ln) || ln <= 0)
{
errorCondition("Number of lines on the simulated arena must be a positive integer.")
return()
}
e <- as.numeric(tclvalue(eVar))
if (e<0 || e > 1)
{
errorCondition(message = "Extinction coefficient must be positive between 0 to 1")
return()
}
i <- as.numeric(tclvalue(iVar))
if (i<0 || i > 1)
{
errorCondition(message = "Colonization coefficient must be positive between 0 to 1")
return()
}
fi <- as.numeric(tclvalue(fiVar))
animaVF <- as.logical(as.numeric(tclvalue(animaVar)))
dsnameValue <- trim.blanks(tclvalue(dsname))
if (dsnameValue == "Do_Not_Save" | dsnameValue=="")
{
command <- paste("metaCiEr(tmax = ",tf, ", cl = ", cl,", f0 = ", fi,", rw =", ln,", ci = ", i,", ce = ", e, ", anima =", animaVF, ")", sep = "")
}
else
{
command <- paste(dsnameValue,"<-metaCiEr(tmax = ",tf, ", cl = ", cl,", f0 = ", fi,", rw =", ln,", ci = ", i,", ce = ", e, ", anima = ", animaVF,")", sep = "")
}
putDialog(dialogName, values = list(dsname=dsnameValue, tfVar= round(as.numeric(tclvalue(tfVar))), clVar= round(as.numeric(tclvalue(clVar))), lnVar= round(as.numeric(tclvalue(lnVar))), fiVar= as.numeric(tclvalue(fiVar)), iVar=as.numeric(tclvalue(iVar)), eVar=as.numeric(tclvalue(eVar)), animaVar=as.logical(as.numeric(tclvalue(animaVar)))),resettable = FALSE)
doItAndPrint(command)
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject = "metapopulation", apply= dialogName, reset= dialogName)
tkgrid(tklabel(top, text="Enter data set name:"), entryDsname, sticky="e")
tkgrid(tklabel(top, text="Simulation Arena Conditions :", fg="blue"), sticky="w")
tkgrid(tklabel(top, text = "Maximum time "), tfEntry, sticky = "e")
tkgrid(tklabel(top, text = "Columns "), clEntry, sticky = "e")
tkgrid(tklabel(top, text = "Rows "), lnEntry, sticky = "e")
tkgrid(tklabel(top, text="Species parameters :", fg="blue"), sticky="w")
tkgrid(tklabel(top, text = "Initial occupancy "), fiEntry, sticky = "e")
tkgrid(tklabel(top, text = "Colonization coefficient "), iEntry, sticky = "e")
tkgrid(tklabel(top, text = "Extinction coefficient "), eEntry, sticky = "e")
tkgrid(tklabel(top, text = "Show simulation frames"), animaBox, sticky = "e")
tkgrid(buttonsFrame, sticky = "w", columnspan = 2)
tkgrid.configure(entryDsname, sticky = "w")
tkgrid.configure(tfEntry, sticky = "w")
tkgrid.configure(clEntry, sticky = "w")
tkgrid.configure(lnEntry, sticky = "w")
tkgrid.configure(fiEntry, sticky = "w")
tkgrid.configure(iEntry, sticky = "w")
tkgrid.configure(eEntry, sticky = "w")
tkgrid.configure(animaBox, sticky = "w")
dialogSuffix(rows = 11, columns = 2, focus = tfEntry)
}
metacompDb <-function ()
{
dialogName<-"metacompDb"
def <- list(dsname="Do_Not_Save", tmaxVar=100, clVar= 20, lnVar=20, fi1Var=0.25,fi2Var= 0.25, i1Var=0.1, i2Var=0.1, peVar = 0.05, distrVar=0.00, animaVar=1)
initial <- getDialog(dialogName, defaults= def)
initializeDialog(title = gettextRcmdr("Meta Competition"))
dsname <- tclVar(initial$dsname)
tmaxVar <- tclVar(initial$tmaxVar)
clVar <- tclVar(initial$clVar)
lnVar <- tclVar(initial$lnVar)
fi1Var <- tclVar(initial$fi1Var)
fi2Var <- tclVar(initial$fi2Var)
i1Var <- tclVar(initial$i1Var)
i2Var <- tclVar(initial$i2Var)
peVar <- tclVar(initial$peVar)
distrVar <- tclVar(initial$distrVar)
animaVar <- tclVar(initial$animaVar)
entryDsname <- tkentry(top, width="20", textvariable=dsname)
tmaxEntry <- tkentry(top, width = "4", textvariable = tmaxVar)
clEntry <- tkentry(top, width = "4", textvariable = clVar)
lnEntry <- tkentry(top, width = "4", textvariable = lnVar)
fi1VarSlider <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=fi1Var, resolution=0.01, orient="horizontal")
fi2VarSlider <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=fi2Var, resolution=0.01, orient="horizontal")
i1Entry <- tkentry(top, width = "6", textvariable = i1Var)
i2Entry <- tkentry(top, width = "6", textvariable = i2Var)
peEntry <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=peVar, resolution=0.01, orient="horizontal")
distrEntry <- tkscale(top, from=0, to=1, showvalue=TRUE, variable=distrVar, resolution=0.01, orient="horizontal")
animaBox <- tkcheckbutton(top, variable = animaVar)
onOK <- function()
{
closeDialog()
tmax <- round(as.numeric(tclvalue(tmaxVar)))
if (is.na(tmax) || tmax <= 0)
{
errorCondition(message = "Number of simulations must be a positive integer")
return()
}
cl <- round(as.numeric(tclvalue(clVar)))
if (is.na(cl) || cl <= 0)
{
errorCondition(message = "Number of columns on the simulated arena must be a positive integer.")
return()
}
ln <- round(as.numeric(tclvalue(lnVar)))
if (is.na(ln) || ln <= 0)
{
errorCondition("Number of lines on the simulated arena must be a positive integer.")
return()
}
i1 <- as.numeric(tclvalue(i1Var))
i2 <- as.numeric(tclvalue(i2Var))
fi1 <- as.numeric(tclvalue(fi1Var))
fi2 <- as.numeric(tclvalue(fi2Var))
pe <- as.numeric(tclvalue(peVar))
distr <- as.numeric(tclvalue(distrVar))
animaVF <- as.logical(as.numeric(tclvalue(animaVar)))
dsnameValue <- trim.blanks(tclvalue(dsname))
if (dsnameValue == "Do_Not_Save" | dsnameValue=="")
{
command <- paste("metaComp(tmax = ",tmax, ", cl = ", cl,", f01 = ", fi1,", f02 = ", fi2,", rw =", ln,", i1 = ", i1,", i2 = ", i2,", pe = ", pe,", D = ", distr,", anima = ", animaVF, ")", sep = "")
}
else
{
command <- paste(dsnameValue,"<- metaComp(tmax = ",tmax, ", cl = ", cl,", f01 = ", fi1,", f02 = ", fi2,", rw =", ln,", i1 = ", i1,", i2 = ", i2,", pe = ", pe,", D = ", distr,", anima = ", animaVF, ")", sep = "")
}
doItAndPrint(command)
tkfocus(CommanderWindow())
putDialog(dialogName, values = list(dsname=dsnameValue, tmaxVar= round(as.numeric(tclvalue(tmaxVar))), clVar= round(as.numeric(tclvalue(clVar))), lnVar= round(as.numeric(tclvalue(lnVar))), fi1Var= as.numeric(tclvalue(fi1Var)), fi2Var= as.numeric(tclvalue(fi2Var)), i1Var=as.numeric(tclvalue(i1Var)), i2Var=as.numeric(tclvalue(i2Var)), peVar=as.numeric(tclvalue(peVar)), distrVar=as.numeric(tclvalue(distrVar)), animaVar=as.logical(as.numeric(tclvalue(animaVar)))),resettable = FALSE)
}
OKCancelHelp(helpSubject = "metaComp", apply= dialogName, reset = dialogName)
tkgrid(tklabel(top, text="Enter name for data set:"), entryDsname, sticky="e")
tkgrid(tklabel(top, text="Simulation Arena Conditions :", fg="blue"), sticky="w")
tkgrid(tklabel(top, text = "Maximum time"), tmaxEntry, sticky = "e")
tkgrid(tklabel(top, text = "Columns"), clEntry, sticky = "e")
tkgrid(tklabel(top, text = "Rows"), lnEntry, sticky = "e")
tkgrid(tklabel(top, text="Best Competitor Species :", fg="blue"), sticky="w")
tkgrid(tklabel(top, text="Initial occupancy "), fi1VarSlider, sticky="se")
tkgrid(tklabel(top, text = "Colonization coefficient "), i1Entry, sticky = "e")
tkgrid(tklabel(top, text="Inferior Competitor Species :", fg="blue"), sticky="w")
tkgrid(tklabel(top, text="Initial occupancy "), fi2VarSlider, sticky="se")
tkgrid(tklabel(top, text = "Colonization coefficient "), i2Entry, sticky = "e")
tkgrid(tklabel(top, text="Both Species :", fg="blue"), sticky="w")
tkgrid(tklabel(top, text = "Prob. Extinction "), peEntry, sticky = "se")
tkgrid(tklabel(top, text = "Habitat Destruction "), distrEntry, sticky = "se")
tkgrid(tklabel(top, text = "Show simulation frames"), animaBox, sticky = "e")
tkgrid(buttonsFrame, sticky = "w", columnspan = 2)
tkgrid.configure(entryDsname, sticky = "w")
tkgrid.configure(tmaxEntry, sticky = "w")
tkgrid.configure(clEntry, sticky = "w")
tkgrid.configure(lnEntry, sticky = "w")
tkgrid.configure(fi1VarSlider, sticky = "w")
tkgrid.configure(i1Entry, sticky = "w")
tkgrid.configure(fi2VarSlider, sticky = "w")
tkgrid.configure(i2Entry, sticky = "w")
tkgrid.configure(peEntry, sticky = "w")
tkgrid.configure(distrEntry, sticky = "w")
tkgrid.configure(animaBox, sticky = "w")
dialogSuffix(rows = 12, columns = 2, focus = entryDsname)
} |
context("parse_time_formula testing")
obj_Date <- make_dummy_dispatch_obj("Date")
obj_POSIXct <- make_dummy_dispatch_obj("POSIXct")
obj_yearmon <- make_dummy_dispatch_obj("yearmon")
obj_yearqtr <- make_dummy_dispatch_obj("yearqtr")
obj_hms <- make_dummy_dispatch_obj("hms")
test_that("Basic parsing", {
expect_equal(parse_time_formula(obj_Date, ~'2013'),
list(list(y = 2013, m = 1, d = 1),
list(y = 2013, m = 12, d = c(Dec = 31))))
expect_equal(parse_time_formula(obj_POSIXct, ~'2013'),
list(list(y = 2013, m = 1, d = 1, h = 0, M = 0, s = 0),
list(y = 2013, m = 12, d = c(Dec = 31), h = 23, M = 59, s = 59)))
expect_equal(parse_time_formula(obj_yearmon, ~'2013'),
list(list(y = 2013, m = 1),
list(y = 2013, m = 12)))
expect_equal(parse_time_formula(obj_yearqtr, ~'2013'),
list(list(y = 2013, q = 1),
list(y = 2013, q = 4)))
expect_equal(parse_time_formula(obj_hms, ~'1'),
list(list(h = 1, M = 0, s = 0),
list(h = 1, M = 59, s = 59)))
})
test_that("Errors are thrown with incorrect specification", {
expect_error(parse_time_formula(obj_Date, ~'2013-01-01 - 1'),
"For a Date index, time_formula can only include y, m, d specifications.")
expect_error(parse_time_formula(obj_yearmon, ~'2013-01-01'),
"For a yearmon index, time_formula can only include y, m specifications.")
expect_error(parse_time_formula(obj_yearqtr, ~'2013-01-01'),
"For a yearqtr index, time_formula can only include y, q specifications.")
expect_error(parse_time_formula(obj_hms, ~'2013-01-01 / 1'),
"For a hms index, time_formula can only include h, M, s specifications.")
}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.