code
stringlengths 1
13.8M
|
---|
NULL
axe_call.multnet <- function(x, verbose = FALSE, ...) {
old <- x
x <- exchange(x, "call", call("dummy_call"))
add_butcher_attributes(
x,
old,
disabled = c("print()", "summary()"),
verbose = verbose
)
}
|
library(PopED)
fg.PK.1.comp.oral.md.param.2 <- function(x,a,bpop,b,bocc){
parameters=c( V=bpop[1]*exp(b[1]),
KA=bpop[2]*exp(b[2]),
KE=bpop[3]*exp(b[3]),
Favail=bpop[4],
DOSE=a[1],
TAU=a[2])
return( parameters )
}
poped.db <- create.poped.database(ff_file="ff.PK.1.comp.oral.md.KE",
fg_file="fg.PK.1.comp.oral.md.param.2",
fError_file="feps.add.prop",
groupsize=20,
m=2,
sigma=c(0.04,5e-6),
bpop=c(V=72.8,KA=0.25,KE=3.75/72.8,Favail=0.9),
d=c(V=0.09,KA=0.09,KE=0.25^2),
notfixed_bpop=c(1,1,1,0),
notfixed_sigma=c(0,0),
xt=c( 1,2,8,240,245),
minxt=c(0,0,0,240,240),
maxxt=c(10,10,10,248,248),
bUseGrouped_xt=1,
a=list(c(DOSE=20,TAU=24),c(DOSE=40, TAU=24)),
maxa=c(DOSE=200,TAU=40),
mina=c(DOSE=0,TAU=2))
plot_model_prediction(poped.db)
plot_model_prediction(poped.db,IPRED=T,DV=T,separate.groups=T)
evaluate_design(poped.db)
shrinkage(poped.db)
output <- poped_optim(poped.db, opt_xt =TRUE, parallel=TRUE)
summary(output)
get_rse(output$FIM,output$poped.db)
plot_model_prediction(output$poped.db)
output_2 <- poped_optim(output$poped.db, opt_xt =TRUE, opt_a = TRUE, parallel = TRUE)
summary(output_2)
get_rse(output_2$FIM,output_2$poped.db)
plot_model_prediction(output_2$poped.db)
poped.db.discrete <- create.poped.database(poped.db,discrete_xt = list(0:248))
output_discrete <- poped_optim(poped.db.discrete, opt_xt=T, parallel = TRUE)
summary(output_discrete)
get_rse(output_discrete$FIM,output_discrete$poped.db)
plot_model_prediction(output_discrete$poped.db)
plot_efficiency_of_windows(output_discrete$poped.db, xt_windows=1)
|
data("colonDC")
set.seed(2)
colonDC <- colonDC[sample(1:nrow(colonDC), 500), ]
colonDC$bhaz <- general.haz(time = "FU", age = "agedays", sex = "sex", year = "dx",
data = colonDC, ratetable = survexp.dk)
fit.wei <- fit.cure.model(Surv(FUyear, status) ~ 1, data = colonDC, bhazard = "bhaz",
type = "mixture", dist = "weibull", link = "logit")
plot(fit.wei)
plot(fit.wei, time = seq(0, 40, length.out = 100))
plot(fit.wei, type = "hazard")
plot(fit.wei, type = "survuncured")
plot(fit.wei, type = "probcure")
fit.weiwei <- fit.cure.model(Surv(FUyear, status) ~ 1, data = colonDC, bhazard = "bhaz",
type = "mixture", dist = "weiwei", link = "logit")
plot(fit.wei, ci = FALSE)
plot(fit.weiwei, add = TRUE, col = 2, ci = FALSE)
fit <- fit.cure.model(Surv(FUyear, status) ~ age, data = colonDC, bhazard = "bhaz",
formula.surv = list(~ age, ~ age),
type = "mixture", dist = "weibull", link = "logit")
plot(fit, newdata = data.frame(age = 60),
time = seq(0, 15, length.out = 100), ci = FALSE)
plot(fit, newdata = data.frame(age = 50),
time = seq(0, 15, length.out = 100), ci = FALSE, add = TRUE, col = 2)
plot(fit, newdata = data.frame(age = 60),
time = seq(0, 15, length.out = 100), ci = FALSE, type = "hazard")
plot(fit, newdata = data.frame(age = 50),
time = seq(0, 15, length.out = 100), ci = FALSE, type = "hazard", add = TRUE, col = 2)
|
weighted.geomean <- function(x, w, ...) exp(weighted.mean(log(x), w, ...))
geomean <- function(x, ...) exp(mean(log(x), ...))
|
g.analyse.perfile = function(ID, fname, deviceSerialNumber, BodyLocation, startt, I, LC2, LD, dcomplscore,
LMp, LWp, C, lookat, AveAccAve24hr, colnames_to_lookat, QUAN, ML5AD,
ML5AD_names, igfullr, igfullr_names,
daysummary, ds_names, includedaycrit, strategy, hrs.del.start,
hrs.del.end, maxdur, windowsizes, idloc, snloc, wdayname, doquan,
qlevels_names, doiglevels, tooshort, InterdailyStability, IntradailyVariability,
IVIS_windowsize_minutes, qwindow, longitudinal_axis_id) {
filesummary = matrix(" ",1,100)
s_names = rep(" ",ncol(filesummary))
vi = 1
filesummary[vi] = ID
g_variables_lookat = lookat[grep(x = colnames_to_lookat, pattern = "BrondCounts|ZCX|ZCY", invert = TRUE)]
if (snloc == 1) {
filesummary[(vi+1)] = deviceSerialNumber
} else if (snloc == 2) {
filesummary[(vi+1)] = unlist(strsplit(fname,"_"))[2]
}
s_names[vi:(vi+1)] = c("ID","device_sn")
vi = vi+2
filesummary[vi] = BodyLocation
filesummary[(vi+1)] = fname
filesummary[(vi+2)] = startt
s_names[vi:(vi+2)] = c("bodylocation","filename","start_time")
vi = vi+3
filesummary[vi] = wdayname
filesummary[(vi+1)] = I$sf
filesummary[(vi+2)] = I$monn
s_names[vi:(vi+2)] = c("startday","samplefreq","device")
vi = vi+3
filesummary[vi] = LC2 / ((LD/1440)*96)
filesummary[(vi+1)] = LD/1440
s_names[vi:(vi+1)] = c("clipping_score",
"meas_dur_dys")
vi = vi+2
filesummary[vi] = dcomplscore
filesummary[(vi+1)] = LMp/1440
filesummary[(vi+2)] = LWp/1440
s_names[vi:(vi+2)] = c("complete_24hcycle",
"meas_dur_def_proto_day","wear_dur_def_proto_day")
vi = vi+3
if (length(C$cal.error.end) == 0) C$cal.error.end = c(" ")
filesummary[vi] = C$cal.error.end
filesummary[vi+1] = C$QCmessage
for (la in 1:length(lookat)) {
AveAccAve24hr[la] = AveAccAve24hr[la] * ifelse(test = lookat[la] %in% g_variables_lookat, yes = 1000, no = 1)
}
q0 = length(AveAccAve24hr) + 1
filesummary[(vi+2):(vi+q0)] = AveAccAve24hr
colnames_to_lookat = paste0(colnames_to_lookat,"_fullRecordingMean")
s_names[vi:(vi+q0)] = c("calib_err",
"calib_status",colnames_to_lookat)
vi = vi+q0+2
if (doquan == TRUE) {
q1 = length(QUAN)
filesummary[vi:((vi-1)+q1)] = QUAN * ifelse(test = lookat[la] %in% g_variables_lookat, yes = 1000, no = 1)
s_names[vi:((vi-1)+q1)] = paste0(qlevels_names,"_fullRecording")
vi = vi + q1
q1 = length(ML5AD)
filesummary[vi:((vi-1)+q1)] = as.numeric(ML5AD)
s_names[vi:((vi-1)+q1)] = paste0(ML5AD_names,"_fullRecording")
vi = vi + q1
}
if (doiglevels == TRUE) {
q1 = length(igfullr)
filesummary[vi:((vi-1)+q1)] = igfullr
s_names[vi:((vi-1)+q1)] = paste0(igfullr_names,"_fullRecording")
vi = vi + q1
}
if (tooshort == 0) {
wkend = which(daysummary[,which(ds_names == "weekday")] == "Saturday" | daysummary[,which(ds_names == "weekday")] == "Sunday")
columnWithAlwaysData = which(ds_names == "N hours" | ds_names == "N_hours")
NVHcolumn = which(ds_names == "N valid hours" | ds_names == "N_valid_hours" )
v1 = which(is.na(as.numeric(daysummary[wkend,columnWithAlwaysData])) == F &
as.numeric(daysummary[wkend,NVHcolumn]) >= includedaycrit)
wkend = wkend[v1]
wkday = which(daysummary[,which(ds_names == "weekday")] != "Saturday" & daysummary[,which(ds_names == "weekday")] != "Sunday")
v2 = which(is.na(as.numeric(daysummary[wkday,columnWithAlwaysData])) == F &
as.numeric(daysummary[wkday,NVHcolumn]) >= includedaycrit)
wkday = wkday[v2]
filesummary[vi:(vi+1)] = c(length(wkend), length(wkday))
iNA = which(is.na(filesummary[vi:(vi+1)]) == TRUE)
if (length(iNA) > 0) filesummary[(vi:(vi+1))[iNA]] = 0
s_names[vi:(vi+1)] = c("N valid WEdays","N valid WKdays")
vi = vi + 2
filesummary[vi:(vi+2)] = c(InterdailyStability, IntradailyVariability,
IVIS_windowsize_minutes)
iNA = which(is.na(filesummary[vi:(vi+3)]) == TRUE)
if (length(iNA) > 0) filesummary[(vi:(vi+3))[iNA]] = " "
s_names[vi:(vi+2)] = c("IS_interdailystability","IV_intradailyvariability",
"IVIS_windowsize_minutes")
vi = vi + 4
daytoweekvar = c(5:length(ds_names))
md = unique(which(ds_names[daytoweekvar] %in% c("measurementday", "weekday") == TRUE), grep(x = ds_names, pattern="qwindow_timestamps|qwindow_names"))
if (length(md) > 0) daytoweekvar = daytoweekvar[-md]
dtwtel = 0
if (length(daytoweekvar) >= 1) {
sp = length(daytoweekvar) + 1
for (dtwi in daytoweekvar) {
uncona = unique(daysummary[,dtwi])
storevalue = !(length(uncona) == 1 & length(qwindow) > 2 & uncona[1] == "")
if (is.na(storevalue) == TRUE) storevalue = FALSE
if (storevalue == TRUE) {
v4 = mean(suppressWarnings(as.numeric(daysummary[,dtwi])),na.rm=TRUE)
filesummary[(vi+1+(dtwtel*sp))] = v4
s_names[(vi+1+(dtwtel*sp))] = paste("AD_",ds_names[dtwi],sep="")
dtw_wkend = suppressWarnings(as.numeric(daysummary[wkend,dtwi]))
dtw_wkday = suppressWarnings(as.numeric(daysummary[wkday,dtwi]))
filesummary[(vi+2+(dtwtel*sp))] = suppressWarnings(mean(dtw_wkend,na.rm=TRUE))
filesummary[(vi+3+(dtwtel*sp))] = suppressWarnings(mean(dtw_wkday,na.rm=TRUE))
s_names[(vi+2+(dtwtel*sp))] = paste0("WE_",ds_names[dtwi])
s_names[(vi+3+(dtwtel*sp))] = paste0("WD_",ds_names[dtwi])
if (length(dtw_wkend) > 2) {
dtw_wkend = c((dtw_wkend[1]+dtw_wkend[3])/2,dtw_wkend[2])
}
if (length(dtw_wkday) > 5) {
dtw_wkday = c((dtw_wkday[1]+dtw_wkday[6])/2,dtw_wkday[2:5])
}
filesummary[(vi+4+(dtwtel*sp))] = suppressWarnings(mean(dtw_wkend,na.rm=TRUE))
filesummary[(vi+5+(dtwtel*sp))] = suppressWarnings(mean(dtw_wkday,na.rm=TRUE))
s_names[(vi+4+(dtwtel*sp))] = paste("WWE_",ds_names[dtwi],sep="")
s_names[(vi+5+(dtwtel*sp))] = paste("WWD_",ds_names[dtwi],sep="")
dtwtel = dtwtel + 1
}
v4 = mean(suppressWarnings(as.numeric(daysummary[,dtwi])),na.rm=TRUE)
filesummary[(vi+1+(dtwtel*sp))] = v4
s_names[(vi+1+(dtwtel*sp))] = paste("AD_",ds_names[dtwi],sep="")
dtw_wkend = suppressWarnings(as.numeric(daysummary[wkend,dtwi]))
dtw_wkday = suppressWarnings(as.numeric(daysummary[wkday,dtwi]))
if (storevalue == TRUE) {
filesummary[(vi+2+(dtwtel*sp))] = mean(dtw_wkend,na.rm=TRUE)
filesummary[(vi+3+(dtwtel*sp))] = mean(dtw_wkday,na.rm=TRUE)
}
s_names[(vi+2+(dtwtel*sp))] = paste("WE_",ds_names[dtwi],sep="")
s_names[(vi+3+(dtwtel*sp))] = paste("WD_",ds_names[dtwi],sep="")
if (length(dtw_wkend) > 2) {
dtw_wkend = c((dtw_wkend[1]+dtw_wkend[3])/2,dtw_wkend[2])
}
if (length(dtw_wkday) > 5) {
dtw_wkday = c((dtw_wkday[1]+dtw_wkday[6])/2,dtw_wkday[2:5])
}
if (storevalue == TRUE) {
filesummary[(vi+4+(dtwtel*sp))] = mean(dtw_wkend,na.rm=TRUE)
filesummary[(vi+5+(dtwtel*sp))] = mean(dtw_wkday,na.rm=TRUE)
}
s_names[(vi+4+(dtwtel*sp))] = paste("WWE_",ds_names[dtwi],sep="")
s_names[(vi+5+(dtwtel*sp))] = paste("WWD_",ds_names[dtwi],sep="")
dtwtel = dtwtel + 1
}
vi = vi+6+((dtwtel*sp)-1)
}
filesummary[vi] = strategy
filesummary[(vi+1)] = hrs.del.start
filesummary[(vi+2)] = hrs.del.end
filesummary[(vi+3)] = maxdur
filesummary[(vi+4)] = windowsizes[1]
filesummary[(vi+5)] = longitudinal_axis_id
SI = sessionInfo()
GGIRversion = c()
try(expr = {GGIRversion = SI$loadedOnly$GGIR$Version},silent=TRUE)
if (length(GGIRversion) == 0) {
try(expr = {GGIRversion = SI$otherPkgs$GGIR$Version},silent=TRUE)
}
if (length(GGIRversion) == 0) GGIRversion = "GGIR not used"
filesummary[(vi+6)] = GGIRversion
s_names[vi:(vi+6)] = as.character(c(paste0("data exclusion stategy (value=1, ignore specific hours;",
" value=2, ignore all data before the first midnight and",
" after the last midnight)"),
"n hours ignored at start of meas (if strategy=1)",
"n hours ignored at end of meas (if strategy=1)",
"n days of measurement after which all data is ignored (if strategy=1)",
"epoch size to which acceleration was averaged (seconds)",
"if_hip_long_axis_id", "GGIR version"))
vi = vi + 6
}
rm(LD); rm(ID)
mw = which(is.na(daysummary)==T)
if (length(mw) > 0) {
daysummary[which(is.na(daysummary)==T)] = " "
}
cut = which(ds_names == " " | ds_names == "" | is.na(ds_names)==T)
if (length(cut > 0)) {
ds_names = ds_names[-cut]
daysummary = daysummary[,-cut]
}
if(min(dim(as.matrix(daysummary))) == 1) {
if (nrow(as.matrix(daysummary)) != 1) {
daysummary = t(daysummary)
}
}
daysummary = data.frame(value=daysummary,stringsAsFactors=FALSE)
names(daysummary) = ds_names
columnswith16am = grep("1-6am",x=colnames(daysummary))
if (length(columnswith16am) > 1) {
daysummary = daysummary[,-columnswith16am[2:length(columnswith16am)]]
}
mw = which(is.na(filesummary)==T)
if (length(mw) > 0) {
filesummary[which(is.na(filesummary)==T)] = " "
}
cut = which(as.character(s_names) == " " | as.character(s_names) == "" | is.na(s_names)==T |
s_names %in% c("AD_", "WE_", "WD_", "WWD_", "WWE_",
"AD_N hours", "WE_N hours", "WD_N hours", "WWD_N hours", "WWE_N hours",
"AD_N valid hours", "WE_N valid hours", "WD_N valid hours", "WWD_N valid hours", "WWE_N valid hours"))
if (length(cut) > 0) {
s_names = s_names[-cut]
filesummary = filesummary[-cut]
}
filesummary = data.frame(value=t(filesummary),stringsAsFactors=FALSE)
names(filesummary) = s_names
columns2order = c()
if (ncol(filesummary) > 37) {
columns2order = 30:(ncol(filesummary)-6)
}
options(encoding = "UTF-8")
if (length(columns2order) > 0) {
selectcolumns = c(names(filesummary)[1:29],
sort(names(filesummary[,columns2order])),
names(filesummary)[(ncol(filesummary)-5):ncol(filesummary)])
} else {
selectcolumns = names(filesummary)
}
selectcolumns = selectcolumns[which(selectcolumns %in% colnames(filesummary) == TRUE)]
filesummary = filesummary[,selectcolumns]
filesummary = filesummary[,!duplicated(filesummary)]
invisible(list(filesummary=filesummary, daysummary=daysummary))
}
|
overallRunsSRPlotT20 <- function(dir=".",minMatches, dateRange,type="IPL",plot=1) {
quantile=quadrant=ggplotly=NULL
currDir= getwd()
cat("T20batmandir=",currDir,"\n")
battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=year=NULL
setwd(dir)
battingDF<-NULL
battingDetails <- paste(type,"-BattingDetails.RData",sep="")
print(battingDetails)
load(battingDetails)
print(dim(battingDF))
print(dim(battingDF))
print(names(battingDF))
tryCatch({
df=battingDF %>% filter(date >= dateRange[1] & date <= dateRange[2])
},
warning=function(war)
{
print(paste("NULL values: ", war))
},
error=function(err)
{
setwd(currDir)
cat("Back to root",getwd(),"\n")
})
df1 <- select(df,batsman,runs,strikeRate)
df1 <- distinct(df1)
b=summarise(group_by(df1,batsman),matches=n(), meanRuns=mean(runs),meanSR=mean(strikeRate))
print(dim(b))
b[is.na(b)] <- 0
c <- filter(b,matches >= minMatches)
setwd(currDir)
x_lower <- quantile(c$meanRuns,p=0.66,na.rm = TRUE)
y_lower <- quantile(c$meanSR,p=0.66,na.rm = TRUE)
print("!!!!!!!!!!!!!!!!!!!!!!!!!")
print(plot)
print("!!!!!!!!!!!!!!!!!!!!!!!!!")
plot.title <- paste("Overall Runs vs SR in ",type,sep="")
if(plot == 1){
c %>%
mutate(quadrant = case_when(meanRuns > x_lower & meanSR > y_lower ~ "Q1",
meanRuns <= x_lower & meanSR > y_lower ~ "Q2",
meanRuns <= x_lower & meanSR <= y_lower ~ "Q3",
TRUE ~ "Q4")) %>%
ggplot(aes(meanRuns,meanSR,color=quadrant)) +
geom_text(aes(meanRuns,meanSR,label=batsman,color=quadrant)) + geom_point() +
xlab("Runs") + ylab("Strike rate") +
geom_vline(xintercept = x_lower,linetype="dashed") +
geom_hline(yintercept = y_lower,linetype="dashed") +
ggtitle(plot.title)
} else if(plot == 2){
g <- c %>%
mutate(quadrant = case_when(meanRuns > x_lower & meanSR > y_lower ~ "Q1",
meanRuns <= x_lower & meanSR > y_lower ~ "Q2",
meanRuns <= x_lower & meanSR <= y_lower ~ "Q3",
TRUE ~ "Q4")) %>%
ggplot(aes(meanRuns,meanSR,color=quadrant)) +
geom_text(aes(meanRuns,meanSR,label=batsman,color=quadrant)) + geom_point() +
xlab("Runs") + ylab("Strike rate") +
geom_vline(xintercept = x_lower,linetype="dashed") +
geom_hline(yintercept = y_lower,linetype="dashed") +
ggtitle(plot.title)
ggplotly(g)
}
}
|
simple <- function(x) {
.Call(simple_, x)
}
simple3 <- function(x) {
.Call(simple3_, x)
}
simple4 <- function(x) {
.Call(simple4_, x)
}
|
context("Cutoff score calculation")
test_that("upper_inner_fence calculates UIF as with sample data", {
d <- c(1,2,3,4,5,6,7,8,9)
expect_equal(13, upper_inner_fence(d))
})
test_that("fake data for cutoff testing is as expected", {
expect_equal(mean(unlist(fake_DVR)), 1.310381, tol=0.00001)
})
test_that("cutoff_aiz() produces accurate error and messages", {
expect_error(cutoff_aiz(fake_DVR, c("ROI1_DVR")))
expect_message(cutoff_aiz(fake_DVR, c("ROI1_DVR", "ROI2_DVR", "ROI3_DVR")),
"Iteration: 1 Removed: 10")
expect_message(cutoff_aiz(fake_DVR, c("ROI1_DVR", "ROI2_DVR", "ROI3_DVR")),
"Iteration: 2 Removed: 0")
expect_message(cutoff_aiz(fake_DVR, c("ROI1_DVR", "ROI2_DVR", "ROI3_DVR",
"ROI4_DVR")),
"Iteration: 3 Removed: 0")
})
test_that("cutoff_aiz() calculates ROI-based cutoffs accurately", {
clean <- c(11:33, 35:50)
expect_equal(cutoff_aiz(fake_DVR, c("ROI1_DVR", "ROI2_DVR", "ROI3_DVR",
"ROI4_DVR"))[[1]],
upper_inner_fence(fake_DVR[clean,]$ROI1_DVR))
expect_equal(cutoff_aiz(fake_DVR, c("ROI1_DVR", "ROI2_DVR", "ROI3_DVR",
"ROI4_DVR"))[[2]],
upper_inner_fence(fake_DVR[clean,]$ROI2_DVR))
expect_equal(cutoff_aiz(fake_DVR, c("ROI1_DVR", "ROI2_DVR", "ROI3_DVR",
"ROI4_DVR"))[[3]],
1.330504, tol=0.00001)
expect_equal(cutoff_aiz(fake_DVR, c("ROI1_DVR", "ROI2_DVR", "ROI3_DVR",
"ROI4_DVR"))[[4]],
1.27347, tol=0.00001)
})
test_that("pos_anyroi() dichotomizes participants accurately", {
cutoffs <- cutoff_aiz(fake_DVR, c("ROI1_DVR", "ROI2_DVR", "ROI3_DVR",
"ROI4_DVR"))
pos_table <- pos_anyroi(fake_DVR, cutoffs)
expect_type(pos_table, "logical")
expect_equal(sum(pos_table), 11)
expect_equal(sum(pos_table[c(1:10, 34)]), 11)
expect_equal(sum(pos_table[!c(1:10, 34)]), 0)
})
|
library(quantmod)
getFin("LNKD")
head(viewFin(LNKD.f, type= 'BS', period = 'Q' ))
fin <- c('GOOGL','AAPL','AMZN','EBAY','CRM','FB','LNKD','ALBIY')
|
ui.createMap <- function() {
tabItem(
tabName = "createmap",
fluidRow(
box(
status = "primary", width = 6,
conditionalPanel("input.tabset1 == 'Range'", plotOutput("plot1", height = "auto", brush = "map_brush")),
conditionalPanel("input.tabset1 != 'Range'", plotOutput("plot1b", height = "auto"))
),
tabBox(
title = "Map", width = 6, id = "tabset1",
tabPanel(
title = "Range",
fluidRow(
box(
title = "Map range", status = "warning", solidHeader = FALSE, width = 12, collapsible = TRUE,
helpText("For longitude values, please use the range -180 to 180.",
"For instance, use left and right longitudes of 130 and -110, respectively,",
"for a map of the northern Pacific.", tags$br(),
"Click the 'Replot map' button after changing map range values,",
"or if the map isn't properly sized in the window.", tags$br(),
"In addition, users can automatically change the map range input values",
"by clicking and holding to draw a box on map, although users still must click 'Replot map'.",
"To clear the box, click within the plot outside of the box."),
fluidRow(
column(3, tags$h5("Left longitude")),
column(3, tags$h5("Right longitude")),
column(3, tags$h5("Bottom latitude")),
column(3, tags$h5("Top latitude"))
),
fluidRow(
column(3, numericInput("lon_left", NULL, value = start.ll$X[1])),
column(3, numericInput("lon_right", NULL, value = start.ll$X[2])),
column(3, numericInput("lat_bot", NULL, value = start.ll$X[3])),
column(3, numericInput("lat_top", NULL, value = start.ll$X[4]))
),
fluidRow(
column(3, selectInput("resolution", label = tags$h5("Resolution"),
choices = list("Low" = 1, "High" = 2), selected = start.ll$X[5])),
column(3, tags$br(), tags$br(), actionButton("map_replot", "Replot map"))
),
tags$span(htmlOutput("map_range_message"), style = "color: red;"),
tags$h5("Set the map range to a default study area and replot:"),
actionButton("map_replot_cce", "CCE"),
actionButton("map_replot_cce2", "Extended CCE"),
actionButton("map_replot_etp", "ETP"),
actionButton("map_replot_hawaii", "Hawaii"),
actionButton("map_replot_hawaiimain", "Main Hawaiian Islands"),
actionButton("map_replot_marianas", "Marianas")
),
box(
title = "Scale bar", status = "warning", solidHeader = FALSE, width = 12, collapsible = TRUE,
checkboxInput("bar", "Plot scale bar", value = FALSE),
conditionalPanel(
condition = "input.bar",
helpText("Provide the coordinates for the left edge of the scale bar.",
"The coordinates must have the same range as the map range coordinates."),
fluidRow(
column(4, uiOutput("scale_lon_uiOut_numeric")),
column(4, uiOutput("scale_lat_uiOut_numeric")),
column(4, numericInput("scale_width", tags$h5("Width of bar"), value = 2, min = 1, max = 6, step = 1)),
),
fluidRow(
column(4, radioButtons("scale_units", tags$h5("Scale bar units"),
choices = list("Kilometers" = 1, "Nautical miles" = 2),
selected = 2)),
column(4, uiOutput("out_scale_len"))
)
)
),
box(
title = "Coastline", status = "warning", solidHeader = FALSE, width = 12, collapsible = TRUE,
checkboxInput("coast", label = "Use coastline file", value = FALSE),
conditionalPanel(
condition = "input.coast",
helpText("Map limits will automatically be updated to the extent of the",
"coastline file. Note: CruzPlot can only process coastline files",
"with points are between -180 and 0"),
fileInput("coast_file", label = tags$h5("Coastline file"), width = "50%")
)
)
)
),
tabPanel(
title = "Planned Transects", value = "planned_transects",
fluidRow(
box(
title = "Planned transects", status = "warning", solidHeader = FALSE, width = 12, collapsible = FALSE,
fluidRow(
box(
width = 12,
tags$strong("Load planned transects"),
helpText(paste("Longitudes must be in -180 to 180 range. See the manual for the required CSV file format")),
fileInput("planned_transects_file", tags$h5("Load planned transects CSV file"), accept = ".csv"),
fluidRow(
column(3, uiOutput("planned_transects_lon_uiOut_select")),
column(3, uiOutput("planned_transects_lat_uiOut_select")),
column(3, uiOutput("planned_transects_num_uiOut_select")),
column(3, uiOutput("planned_transects_class1_uiOut_select"))
),
fluidRow(
column(3, uiOutput("planned_transects_class2_uiOut_select")),
column(3, offset = 1, tags$br(), tags$br(), uiOutput("planned_transects_execute_uiOut_button")),
column(5, tags$br(), tags$br(), textOutput("planned_transects_text"))
),
tags$span(textOutput("planned_transects_message"), style = "color: blue;")
),
conditionalPanel(
condition = "output.cruzMapPlannedTransects_Conditional",
box(
width = 12,
tags$strong("Plot loaded planned transects"),
checkboxInput("planned_transects_plot", "Plot planned transect lines", value = FALSE),
conditionalPanel(
condition = "input.planned_transects_plot",
column(12, helpText("For the color(s) and (if a class 2 column is specified) the line type(s),",
"select either one or the same number as transect classes or class 2s, respectively.",
"When multiple colors or line types are selected,",
"the order in which transect classes and class 2s are selected to be plotted",
"corresponds to order of specified colors and line types, respectively.")),
box(
width = 12,
ui.select.instructions(),
fluidRow(
column(6, uiOutput("planned_transects_toplot_uiOut_select")),
column(6, uiOutput("planned_transects_color_uiOut_select"))
),
fluidRow(
column(4, uiOutput("planned_transects_toplot2_uiOut_select")),
column(4, uiOutput("planned_transects_lty_uiOut_select")),
column(4, numericInput("planned_transects_lwd", tags$h5("Line width"),
value = 1, min = 0, step = 1))
)
)
)
)
)
)
)
)
),
tabPanel(
title = "Ticks & Labels",
fluidRow(
box(
title = NULL, status = "warning", solidHeader = FALSE, width = 12, collapsible = TRUE,
checkboxInput("tick", label = "Plot tick marks and/or their labels", value = TRUE)
)
),
fluidRow(
conditionalPanel(
condition = "input.tick",
box(
title = "Tick marks", status = "warning", solidHeader = FALSE, width = 6, collapsible = TRUE, height = 437,
fluidRow(
column(
width = 6,
checkboxInput("tick_left", label = "Left", value = TRUE),
checkboxInput("tick_bot", label = "Bottom", value = TRUE),
numericInput("tick_interval_major", label = tags$h5("Degrees between each major tick"),
value = start.tick$interval, min = 0, max = 45, step = 5),
selectInput("tick_style", label = tags$h5("Tick label style"),
choices = list("120" = 1, "120W" = 2, "120\u00B0" = 3, "120\u00B0W" = 4),
selected = 4)
),
column(
width = 6,
checkboxInput("tick_right", label = "Right", value = TRUE),
checkboxInput("tick_top", label = "Top", value = TRUE),
numericInput("tick_interval_minor", label = tags$h5("Minor ticks between each major tick"),
value = 4, min = 0, max = 45, step = 1),
numericInput("tick_length", label = tags$h5("Tick length"), value = 1.0, min = 0, max = 2.5, step = 0.1)
)
)
),
box(
title = "Tick labels", status = "warning", solidHeader = FALSE, width = 6, collapsible = TRUE, height = 437,
fluidRow(
column(
width = 6,
checkboxInput("tick_left_lab", label = "Left", value = TRUE),
checkboxInput("tick_bot_lab", label = "Bottom", value = TRUE),
numericInput("label_lon_start", tags$h5("Start longitude tick labels at"), value = as.character(start.tick$lon)),
selectInput("label_tick_font", label = tags$h5("Tick label font"), choices = font.family, selected = 1)
),
column(
width = 6,
checkboxInput("tick_right_lab", label = "Right", value = TRUE),
checkboxInput("tick_top_lab", label = "Top", value = TRUE),
numericInput("label_lat_start", tags$h5("Start latitude tick labels at"), value = as.character(start.tick$lat)),
numericInput("label_tick_size", label = tags$h5("Tick label size"), value = 1.0, min = 0.1, max = 3, step = 0.1)
)
)
)
)
)
),
tabPanel(
title = "Map Labels",
fluidRow(
box(
title = "Title", status = "warning", solidHeader = FALSE, width = 6, collapsible = TRUE, height = 315,
textInput("label_title", tags$h5("Map title"), value = ""),
fluidRow(
column(6, selectInput("label_title_font", label = tags$h5("Title font"), choices = font.family, selected = 1)),
column(6, numericInput("label_title_size", label = tags$h5("Title size"), value = 1.5, min = 0.1, max = 3, step = 0.1))
)
),
box(
title = "Axis labels", status = "warning", solidHeader = FALSE, width = 6, collapsible = TRUE, height = 402,
textInput("label_axis_lon", tags$h5("Longitude axis label"), value = ""),
textInput("label_axis_lat", tags$h5("Latitude axis label"), value = ""),
fluidRow(
column(6, selectInput("label_axis_font", label = tags$h5("Axis label font"), choices = font.family, selected = 1)),
column(6, numericInput("label_axis_size", label = tags$h5("Axis label size"), value = 1.2, min = 0.1, max = 3, step = 0.1))
)
)
)
),
tabPanel(
title = "Color",
fluidRow(
box(
title = "Color style", status = "warning", solidHeader = FALSE, collapsible = TRUE, width = 6,
helpText("This color style selection will affect the palette options for all color selections in CruzPlot"),
tags$br(),
radioButtons("color_style", label = NULL, choices = list("Color" = 1, "Gray scale" = 2),
selected = 1)
),
box(
title = "Land", status = "warning", solidHeader = FALSE, collapsible = TRUE, width = 6,
fluidRow(
column(6, checkboxInput("color_land_all", label = "Color all land", value = TRUE)),
column(
width = 6,
conditionalPanel(
condition = "input.color_land_all",
selectInput("color_land", label = tags$h5("Land color"), choices = cruz.palette.color, selected = "bisque1")
)
)
)
)
),
fluidRow(
box(
title = "Water", status = "warning", solidHeader = FALSE, collapsible = TRUE, width = 6,
checkboxInput("color_lakes_rivers", label = "Color lakes and rivers", value = FALSE),
selectInput("color_water", label = tags$h5("Water (background) color"),
choices = cruz.palette.color, selected = "white"),
radioButtons("color_water_style", label = tags$h5("Ocean color style"),
choices = list("Single color" = 1, "Depth (bathymetric) shading" = 2),
selected = 1),
conditionalPanel(
condition = "input.color_water_style==2",
helpText("Load a CSV file with exactly 3 columns: latitude, longitude, and depth"),
fileInput("depth_file", tags$h5("Bathymetric CSV file"), accept = ".csv"),
textOutput("bathy_load_text"),
tags$span(textOutput("bathy_message_text"), style = "color: blue;")
)
),
box(
title = "Download bathymetric data", status = "warning", solidHeader = FALSE, collapsible = TRUE, width = 6,
helpText("Download bathymetric data from NOAA website (see the documentation for",
tags$a(href = "https://CRAN.R-project.org/package=marmap",
"marmap function 'getNOAA.bathy'"),
"for more details).",
"The coordinates of the downloaded data will be the same as the current map range.",
"After downloading, you must load the CSV file into CruzPlot in the 'Water: Ocean color style' section"),
numericInput("depth_res", tags$h5("Bathymetric data resolution, in minutes (range: 0-60)"),
value = 10, min = 0, max = 60, step = 5),
uiOutput("depth_download_button"),
uiOutput("depth_download_message")
)
)
),
tabPanel(
title = "Grid",
fluidRow(
box(
title = "Grid", status = "warning", solidHeader = FALSE, width = 12, collapsible = TRUE, height = 385,
checkboxInput("grid", label = "Include grid lines at major tick marks", value = FALSE),
conditionalPanel(
condition = "input.grid",
fluidRow(
column(3, selectInput("grid_line_color", label = tags$h5("Line color"), choices = cruz.palette.color, selected = "black")),
column(3, numericInput("grid_line_width", label = tags$h5("Line width"), value = 1, min = 1, max = 6, step = 1)),
column(3, selectInput("grid_line_type", label = tags$h5("Line type"), choices = cruz.line.type, selected = 1))
)
)
)
)
),
tabPanel(
title = "Save",
fluidRow(
box(
title = "Save map", status = "warning", solidHeader = FALSE, width = 12,
fluidRow(
column(3, radioButtons("download_format", label = tags$h5("File format"),
choices = list("JPEG" = 1, "PDF" = 2, "PNG" = 3),
selected = 3)),
column(
width = 8,
fluidRow(
column(6, radioButtons("download_dim", tags$h5("File dimensions"),
choices = list("Use dimensions of plot window" = 1, "Specify dimensions" = 2),
selected = 1)),
column(6, numericInput("download_res", tags$h5("Resolution (ppi)"), value = 300, step = 50, min = 0))
),
conditionalPanel("input.download_dim == 1", helpText("Downloaded map should look exactly like displayed map")),
conditionalPanel(
condition = "input.download_dim == 2",
fluidRow(
column(6, numericInput("download_width", tags$h5("File width (inches)"), value = 10, step = 1, min = 0)),
column(6, numericInput("download_height", tags$h5("File height (inches)"), value = 10, step = 1, min = 0))
)
)
)
),
uiOutput("downloadMap_button")
)
)
)
)
)
)
}
|
ts_makeframes <- function(x_list,r_type = NULL,minq = 0.02,maxq = 0.98,samplesize = 1000,blacken_NA=FALSE,l_indices=NULL,alpha=NULL,hillshade=NULL,...){
if(is.null(r_type)){
r_type <- .ts_guess_raster_type(x_list[[1]])
}
if(is.null(l_indices)){
print("No layer indices were given. Assuming and selecting layers by r_type.")
if(r_type == "RGB"){
l_indices <- c(1:3)
}else if (r_type == "gradient" | r_type == "discrete"){
l_indices <- 1
}
}
x_list <- .ts_subset_ts_util(x_list,l_indices)
if(r_type=="RGB"){
r_list_out_stretched <- ts_stretch_list(x_list = x_list,minq = minq,maxq = maxq,samplesize = samplesize)
}else{
r_list_out_stretched <- x_list
}
if(blacken_NA){
r_list_out_stretched <- .blacken_NA_util(r_list_out_stretched)
}
if(!is.null(hillshade)){
if(is.null(alpha)){
alpha=0.5
}
if(!compareCRS(hillshade,x_list[[1]])){
print("Reprojecting Hillshade")
hillshade <- projectRaster(from = hillshade,(x_list[[1]]))
}
hillshade <- crop(hillshade,x_list[[1]])
hillshade_layer <- RStoolbox::ggR(hillshade,ggLayer = TRUE)
r_ggplots <- .ts_makeframes(x_list = r_list_out_stretched,r_type = r_type,gglayer=TRUE,alpha=alpha,hillshade_layer=hillshade_layer,...)
}else{
if(is.null(alpha)){
alpha=1
}
r_ggplots <- .ts_makeframes(x_list = r_list_out_stretched,r_type = r_type,gglayer=FALSE,alpha=alpha,...)
}
r_ggplots <- .ts_set_frametimes(r_ggplots , .ts_get_frametimes(x_list))
return(r_ggplots)
}
|
calc_full_extent <- function(x, aggregate = TRUE) {
stopifnot(inherits(x, "Raster"))
stopifnot(is.logical(aggregate), length(aggregate) == 1)
e_input <- raster::extent(x)
if (isTRUE(aggregate)) {
x <- raster::aggregate(x, fact = 3)
}
x[x == 0] <- NA
e <- c(NA_real_, NA_real_, NA_real_, NA_real_)
for (i in seq_len(raster::nlayers(x))) {
e_trim <- raster::extent(raster::trim(x[[i]]))
e[1] <- min(e[1], e_trim[1], na.rm = TRUE)
e[2] <- max(e[2], e_trim[2], na.rm = TRUE)
e[3] <- min(e[3], e_trim[3], na.rm = TRUE)
e[4] <- max(e[4], e_trim[4], na.rm = TRUE)
}
e <- raster::extent(e)
e[1] <- max(e[1], e_input[1], na.rm = TRUE)
e[2] <- min(e[2], e_input[2], na.rm = TRUE)
e[3] <- max(e[3], e_input[3], na.rm = TRUE)
e[4] <- min(e[4], e_input[4], na.rm = TRUE)
return(e)
}
calc_bins <- function(abundance, count) {
stopifnot(inherits(abundance, "Raster"))
stopifnot(inherits(count, "Raster"))
if (all(is.na(suppressWarnings(raster::maxValue(abundance)))) &&
all(is.na(suppressWarnings(raster::minValue(abundance)))) &&
all(is.na(suppressWarnings(raster::maxValue(count)))) &&
all(is.na(suppressWarnings(raster::minValue(count))))) {
stop("Input Raster* objects must have non-NA values.")
}
if (all(raster::maxValue(abundance) == 0) &&
all(raster::maxValue(count) == 0)) {
stop("Raster must have at least 2 non-zero values to calculate bins")
}
v <- as.vector(raster::getValues(abundance))
v <- as.numeric(stats::na.omit(v))
v <- v[v > 0]
if (length(v) <= 1) {
stop("Raster must have at least 2 non-zero values to calculate bins")
}
abd_rng <- range(v, na.rm = TRUE)
abd_5th <- stats::quantile(v, 0.05)
rm(v)
v <- as.vector(raster::getValues(count))
v <- as.numeric(stats::na.omit(v))
v <- v[v > 0]
b <- stats::quantile(v, probs = seq(0, 1, by = 0.05), na.rm = TRUE)
b[1] <- abd_rng[1]
b <- b[b <= abd_rng[2]]
b <- c(b, abd_rng[2])
if (b[2] > abd_5th) {
b <- sort(c(b, abd_5th))
}
b <- unname(b)
attr(b, "labels") <- c(b[2], stats::median(b), b[length(b) - 1])
return(b)
}
abundance_palette <- function(n, season = c("weekly",
"breeding", "nonbreeding",
"migration",
"prebreeding_migration",
"postbreeding_migration",
"year_round")) {
stopifnot(is.numeric(n), length(n) == 1, n >= 1)
season <- match.arg(season)
col_zero <- "
if (season == "weekly") {
plsm <- rev(viridisLite::plasma(n - 1, end = 0.9))
plsm <- stringr::str_remove(plsm, "FF$")
gry <- grDevices::colorRampPalette(c(col_zero, plsm[1]))
return(c(gry(4)[2], plsm))
} else if (season == "breeding") {
base_col <- "
} else if (season == "nonbreeding") {
base_col <- "
} else if (season %in% c("migration", "postbreeding_migration")) {
base_col <- "
} else if (season == "prebreeding_migration") {
base_col <- "
} else if (season == "year_round") {
base_col <- "
} else {
stop("Invalid season.")
}
gry <- grDevices::colorRampPalette(c(col_zero, base_col))
mid <- grDevices::colorRampPalette(c(gry(5)[2], base_col))
black <- grDevices::colorRampPalette(c(base_col, "
pal <- grDevices::colorRampPalette(c(gry(5)[2], mid(9)[5], base_col,
black(5)[2]))
return(pal(n))
}
|
cd_grips <- CD(GRiPS_raw)
test_that("output class and dimensions are correct", {
expect_is(cd_grips, "CD")
expect_named(cd_grips, c("n_factors", "eigenvalues", "RMSE_eigenvalues",
"settings"))
expect_is(cd_grips$RMSE_eigenvalues, "matrix")
})
test_that("CD returns the correct values", {
expect_equal(cd_grips$n_factors, 1)
expect_equal(sum(cd_grips$eigenvalues), 8)
})
test_that("errors etc. are thrown correctly", {
expect_error(CD(1:10), " 'x' is neither a matrix nor a dataframe. Provide a dataframe or matrix with raw data.\n")
expect_error(CD(test_models$baseline$cormat), " 'x' is a correlation matrix, but CD only works with raw data.\n")
expect_warning(CD(GRiPS_raw, n_factors_max = 5), " n_factors_max was set to 5 but maximum possible factors to extract is 4 . Setting n_factors_max to 4 .\n")
})
rm(cd_grips)
|
procD.lm <- function(f1, iter = 999, seed=NULL, RRPP = TRUE,
SS.type = c("I", "II", "III"),
effect.type = c("F", "cohenf", "SS", "MS", "Rsq"),
int.first = FALSE, Cov = NULL,
turbo = TRUE, Parallel = FALSE,
data=NULL, print.progress = FALSE, ...){
if(is.null(data)) {
vars <- rownames(attr(terms(f1), "factors"))
if(!is.null(vars)) {
data <- list()
data <- data[vars]
names(data) <- vars
for(i in 1:length(vars)) {
f <- as.formula(paste("~", vars[i]))
temp <- try(eval(f[[2]]), silent = TRUE)
if(inherits(temp, "try-error")) stop("Cannot find data in global environment.\n",
call. = FALSE) else
data[[i]] <- temp
}
}
}
if(inherits(f1, "formula")){
Y <- try(eval(f1[[2]], envir = data , enclos = parent.frame()), silent = TRUE)
if(inherits(Y, "try-error"))
Y <- try(eval(f1[[2]], envir = parent.frame), silent = TRUE)
if(inherits(Y, "try-error")) stop("Cannot find data in data frame or global environment.\n",
call. = FALSE)
nms <- if(is.vector(Y)) names(Y) else if(inherits(Y, "matrix")) attr(Y, "Labels") else
if(is.matrix(Y)) rownames(Y) else dimnames(Y)[[3]]
dims.Y <- dim(Y)
f <- update(f1, Y ~ .)
if(length(dims.Y) == 3) {
GM <- TRUE
Y <- two.d.array(Y)
rownames(Y) <- nms
p <- dims.Y[[1]]
k <- dims.Y[[2]]
n <- dims.Y[[3]]
} else {
GM <- FALSE
Y <- as.matrix(Y)
rownames(Y) <- nms
if(isSymmetric(Y)) colnames(Y) <- nms
}
data$Y <- Y
} else {
f <- f1
GM <- FALSE
}
out <- lm.rrpp(f, data = data, turbo = turbo,
seed = seed, RRPP = RRPP,
SS.type = SS.type,
int.first = int.first,
Cov = Cov, iter = iter,
print.progress = print.progress,
Parallel = Parallel, ...)
n <- out$LM$n
out$ANOVA$effect.type <- match.arg(effect.type)
out$GM <- NULL
if(!out$LM$gls) {
out$fitted <- out$LM$fitted
out$residuals <- out$LM$residuals
out$coefficients <- out$LM$coefficients
if(GM) {
out$GM$p <- p
out$GM$k <- k
out$GM$n <- n
kk <- NROW(out$LM$coefficients)
out$GM$fitted <- arrayspecs(out$LM$fitted, p, k)
out$GM$residuals <- arrayspecs(out$LM$residuals, p, k)
if(kk > 1) out$GM$coefficients <- arrayspecs(out$LM$coefficients, p, k) else {
out$GM$coefficients <- array(matrix(out$LM$coefficients, p, k, byrow = TRUE), c(p,k,1))
}
}
}
if(out$LM$gls) {
out$gls.fitted <- out$LM$gls.fitted
out$gls.residuals <- out$LM$gls.residuals
out$gls.coefficients <- out$LM$gls.coefficients
out$gls.mean <- out$LM$gls.mean
if(GM) {
out$GM$p <- p
out$GM$k <- k
out$GM$n <- n
kk <- NROW(out$LM$gls.coefficients)
out$GM$gls.fitted <- arrayspecs(out$LM$gls.fitted, p, k)
out$GM$gls.residuals <- arrayspecs(out$LM$gls.residuals, p, k)
out$GM$gls.mean <- matrix(out$LM$gls.mean, out$GM$p, out$GM$k, byrow = TRUE)
if(kk > 1) out$GM$gls.coefficients <- arrayspecs(out$LM$gls.coefficients, p, k) else {
out$GM$coefficients <- array(matrix(out$LM$gls.coefficients, p, k, byrow = TRUE), c(p,k,1))
}
}
}
o.class <- class(out)
out2 <- list()
out2$aov.table <- anova.lm.rrpp(out)$table
out2$call <- match.call()
out$call <- out2$call
if(out$LM$gls) out2$gls.coefficients <- out$LM$gls.coefficients else
out2$coefficients <- out$LM$coefficients
out2$Y <- out$LM$Y
out2$X <- out$LM$X
out2$QR <- out$LM$QR
if(out$LM$gls) out2$gls.fitted <- out$LM$gls.fitted else
out2$fitted <- out$LM$fitted
if(out$LM$gls) out2$gls.residuals <- out$LM$gls.residuals else
out2$residuals <- out$LM$residuals
out2$weights <- if(!is.null(out$LM$weights)) out$LM$weights else NULL
out2$Terms <- out$LM$Terms
out2$term.labels <- out$LM$term.labels
out2$data <- out$LM$data
out2$random.SS <- out2$ANOVA$SS
out <- c(out2, out)
class(out) <- c("procD.lm", o.class)
out
}
|
context("is_too_many")
test_that("is_too_many gives reasonable info", {
skip_on_cran()
old_delay <- getOption("aRxiv_delay")
on.exit(options(aRxiv_delay=old_delay))
options(aRxiv_delay=0.5)
suppressMessages(expect_true(is_too_many("au:A", start=0, limit=NULL) > 170000))
expect_equal(is_too_many("au:A", start=0, limit=10), 0)
})
test_that("arxiv_search throws error with huge result", {
skip_on_cran()
old_delay <- getOption("aRxiv_delay")
on.exit(options(aRxiv_delay=old_delay))
options(aRxiv_delay=0.5)
suppressMessages(expect_error(arxiv_search("au:A", limit=NULL)))
})
|
exact_segments <- function(
data,
max_segments,
likelihood,
initial_position,
allow_parallel) {
num_variables <- ncol(data)
if (num_variables < max_segments) {
max_segments <- num_variables
}
if (num_variables == 0 || nrow(data) == 0) {
return(NULL)
}
segment_likelihoods <- matrix(nrow = max_segments, ncol = num_variables)
max_likehood_pos <- matrix(nrow = max_segments, ncol = num_variables)
for (seg_start in 1:max_segments) {
results <- chuncked_foreach(seg_start:num_variables, allow_parallel, function(seg_end) {
if (seg_start > 1) {
segment_likelihood <- function(preceding_likelihood, index) {
segment <- slice_segment(data, index, seg_end)
likelihood_value <- likelihood(segment)
handle_nan(likelihood_value, index + initial_position - 1, seg_end + initial_position - 1)
preceding_likelihood + likelihood_value
}
indices <- seg_start:seg_end
previous_likelihoods <- segment_likelihoods[seg_start - 1, indices - 1]
segment_tries <- mapply(segment_likelihood, previous_likelihoods, indices)
list(max_likelihood = max(segment_tries), max_likelihood_pos = which.max(segment_tries) + seg_start - 1)
} else {
segment <- slice_segment(data, seg_start, seg_end)
list(max_likelihood = likelihood(segment), max_likelihood_pos = 0)
}
})
segment_likelihoods[seg_start, seg_start:num_variables] <- sapply(results, "[[", "max_likelihood")
max_likehood_pos[seg_start, seg_start:num_variables] <- sapply(results, "[[", "max_likelihood_pos")
}
last_break_pos <- which.max(segment_likelihoods[, num_variables])
if (last_break_pos <= 1) {
return(NULL)
}
break_positions <- num_variables + 1
for (break_pos in last_break_pos:2) {
break_positions <- c(max_likehood_pos[break_pos, break_positions[1] - 1], break_positions)
}
changepoints <- head(break_positions, n = -1)
previous_changepoints <- c(1, head(changepoints, n = -1))
changepoints <- changepoints + initial_position - 1
foreach(changepoint = changepoints) %do% {
list(changepoint = changepoint)
}
}
|
init_state <- function(raster){
if(raster::nlayers(raster) == 2){
In_storage <- raster::raster(raster[[1]])
In_ground <- raster::raster(raster[[2]])
} else{
if(raster::nlayers(raster) != 2){
warning("Strange number of initial state files\n Review files of initial states \n Creation by default from first raster")
}
In_storage <- raster[[1]] / 2
In_ground <- raster[[1]] / 2
}
g_v <- raster::rasterToPoints(In_ground)[ ,-c(1,2)]
s_v <- raster::rasterToPoints(In_storage)[ ,-c(1,2)]
init <- list(In_storage = s_v, In_ground = g_v)
return(init)
}
|
plugincvc <- function(xi,
obswin = NULL,
setcov_boundarythresh = NULL) {
if (is.im(xi)) {
if (!is.null(obswin)) {
winim <- as.im(obswin, xy = xi)
xi <- eval.im(xi * winim)
}
isbinarymap(xi, requiretrue = TRUE)
obswin <- as.owin(xi)
xi[is.na(as.matrix(xi))] <- 0
setcovxi <- imcov(xi)
setcovwindow <- setcov(obswin, eps = c(setcovxi$xstep, setcovxi$ystep))
} else if (is.owin(xi)) {
stopifnot(is.owin(obswin))
xi <- intersect.owin(xi, obswin)
Frame(xi) <- Frame(obswin)
unitname(xi) <- unitname(obswin)
setcovxi <- setcov(xi)
setcovwindow <- setcov(obswin, eps = c(setcovxi$xstep, setcovxi$ystep))
} else {
stop("Input xi is not an image or owin object")
}
if (is.null(setcov_boundarythresh)){
setcov_boundarythresh <- 0.1 * area.owin(obswin)
} else if (setcov_boundarythresh < setcovwindow$xstep * setcovwindow$ystep * 1E-8){
warning("setcov_boundarythresh is smaller than A*1E-8 where A is the size of a pixel.
This might be smaller than the precision of the set covariance computations.
Consider setting setcov_boundarythresh higher.")
}
setcovwindow[setcovwindow < setcov_boundarythresh] <- NA
harmims <- harmonise.im(setcovxi, setcovwindow)
covar <- harmims[[1]]/harmims[[2]]
return(covar)
}
|
library(quint)
data(bcrp)
head(bcrp)
bcrp2arm<-subset(bcrp,bcrp$cond<3)
head(bcrp2arm)
summary(bcrp2arm)
control1 <- quint.control(crit="dm",maxl = 5,B = 10)
formula1<- I(cesdt1-cesdt3) ~ cond | nationality+marital+wcht1+ age+trext+comorbid+disopt1+uncomt1+negsoct1
set.seed(2)
quint1<-quint(formula1, data= bcrp2arm, control=control1 )
quint1pr <- prune(quint1)
quint1pr_bootCI <- quint.bootstrapCI(quint1pr,n_boot = 5)
summary(quint1pr)
summary(quint1pr_bootCI$tree)
plot(quint1pr)
plot(quint1pr_bootCI$tree)
|
plot.subgroupAnalysis <- function(x,...)
{
if (class(x)[1]!="subgroupAnalysis") stop("Object not of class subgroupAnalysis")
num <- length(names(x))
plotcols<-x[,(num-4):(num-2)]
tabcols <-x[,1:2]
Publish::plotConfidence(x=plotcols, labels=tabcols)
}
|
library(hamcrest)
expected <- c(0x1.fbd5cb696cc6p+9 + 0x0p+0i, -0x1.71ff938ddea3p+1 + 0x1.4ae09f2dd74aep+7i,
-0x1.2f570fe0895aap+4 + -0x1.e16f6b53ea1fp+5i, 0x1.69984475fe663p+6 + -0x1.da2f4795c907cp+5i,
0x1.ba16fa21c7f2dp+7 + -0x1.272dc12699e9cp+6i, 0x1.27fe11662f3b2p+5 + 0x1.3d9c0fa6ffa0ep+6i,
-0x1.7f83fcdb74ac6p+5 + -0x1.81886739a6283p+7i, 0x1.dcdfd4823604p+4 + -0x1.b0e19b9841f36p+5i,
0x1.a20efc5d1248cp+7 + 0x1.b09bd2dec195p+4i, -0x1.3a0e23a526833p+5 + -0x1.d64fb153b4bacp+6i,
-0x1.4913857c20fdcp+4 + -0x1.5456c7b7a0cc6p+5i, -0x1.922df046af502p+7 + -0x1.9ee5f0b134373p+6i,
0x1.5594fb2083dfp+6 + -0x1.c12a357ab25eap+6i, -0x1.611bbcfaa0fb1p+5 + 0x1.bb6ef346f9151p+5i,
-0x1.707815233206dp+6 + -0x1.c8053c772dc27p+7i, -0x1.62955da2f9f22p+6 + 0x1.250a849c50853p+5i,
-0x1.ceef56d28c7a6p+5 + -0x1.2f97cc2861892p+5i, -0x1.5bbf2314c2f4ap+3 + -0x1.b3373d0cfc0aap+3i,
0x1.fb9664f6e7p+0 + -0x1.866a32487f4bap+6i, 0x1.fec44787c986ap+5 + -0x1.93297b084a94p+3i,
-0x1.0bc71fcb6cea8p+6 + 0x1.c92cd3b3dfd25p+6i, -0x1.59f353a4c3b6cp+4 + 0x1.000f60cdabbbbp+7i,
0x1.d998eaa6228p+6 + 0x1.4332253c22c7bp+5i, -0x1.ddbf771d57d22p+5 + 0x1.14960d50b9118p+5i,
-0x1.055e90b30c329p+4 + 0x1.7c4d8622132c1p+5i, 0x1.b1c300a76ed67p+5 + 0x1.64f1bed03ea4ep+6i,
0x1.2015cd17685a9p+4 + -0x1.d644f0b97d07p+4i, 0x1.0da89c3d09a9ap+5 + 0x1.5a71c6c7ff532p+5i,
-0x1.37f5d015ca726p+2 + 0x1.a7691ff4cfab8p+0i, -0x1.53a43ed485ea8p+4 + 0x1.12261a030f86ap+6i,
-0x1.102fd011d036ap+4 + 0x1.2d79a845ca2a4p+6i, 0x1.9ed28df367cbfp+5 + -0x1.1825e1d3b4b38p+4i,
0x1.dafbf99b0dc8cp+4 + -0x1.eac87238bc75cp+2i, -0x1.9564826dc979ep+6 + 0x1.0194fe4953ef8p+5i,
0x1.71e8bb36427eap+5 + -0x1.c01cbe8c24c52p+4i, 0x1.04dec220d9694p+5 + 0x1.e1ed205e9d7a8p+2i,
-0x1.a5dbe0c85ebeap+4 + -0x1.62fad467550c8p+3i, -0x1.4ddbcf44f287ep+6 + 0x1.46e88fe8404ddp+4i,
0x1.5799b61ed431ep+5 + 0x1.59f5a10f013bp+2i, 0x1.216aa633312c6p+7 + 0x1.8decdb91202cep+6i,
-0x1.a8b525de615f8p+1 + 0x1.f4360ba556148p+2i, -0x1.acd94dc0af898p+5 + -0x1.491b5b6f854cep+4i,
0x1.d5984fca042bcp+3 + 0x1.fd5859e74ab37p+4i, 0x1.09195c9f202c4p+6 + 0x1.5bea2618443a1p+6i,
-0x1.8ea7139ccdc7p+3 + 0x1.0545d573cece6p+5i, -0x1.1ec92afc81ef8p+5 + -0x1.4eba5c27a0398p+3i,
-0x1.2cc718d796b91p+5 + 0x1.1b6a616c01248p+5i, 0x1.a2a298e5c61dap+6 + 0x1.fdaf9218b6625p+5i,
0x1.7fe49a4aa059p+1 + -0x1.b297bcddd28p-3i, -0x1.e808027dbb7bp+3 + 0x1.be31877613cep+3i,
-0x1.e898038744418p+3 + -0x1.22135f895e0f4p+5i, 0x1.a214eb7ae790fp+5 + 0x1.07d7711f4acb8p+5i,
0x1.5612fafaa1ce4p+2 + 0x1.7b59d94a51519p+5i, 0x1.5d16c0f546fa5p+4 + -0x1.ce43b1d1b473p+5i,
-0x1.e54345d4a7d36p+5 + -0x1.784fab15862dap+4i, 0x1.30a472fd3a12p+3 + 0x1.397bf31f9a512p+5i,
0x1.80a45360df264p+2 + -0x1.97fb1aac9f3f8p+4i, 0x1.a4705bf38c29ep+3 + -0x1.829109abf9acdp+4i,
0x1.e75a6994dcap+1 + 0x1.8115abe45007p+3i, 0x1.561ee6fa6af72p+4 + 0x1.b2c863906ce84p+4i,
0x1.3e89916b3c26p+3 + -0x1.7a26344eb677p+2i, 0x1.b6d64b9a15fe8p+4 + -0x1.118da4b7f87ep+2i,
-0x1.5361555bb8aa4p+3 + -0x1.58e5624cab026p+4i, -0x1.b289eca1da747p+4 + 0x1.5e4ff25a3f4p+1i,
-0x1.8ab1f21de2e6cp+3 + 0x1.a756713601c92p+4i, 0x1.a247c91febe7p+1 + 0x1.ef829b913cddp+1i,
0x1.7c6d386164a78p+1 + -0x1.18635de33a7b8p+4i, -0x1.c238973f82dp-4 + 0x1.75beb10603b9p+2i,
-0x1.fcd7b8c86755p+2 + 0x1.51a550e7bc1b8p+2i, -0x1.ee193b30d4046p+2 + 0x1.4f0be139890f4p+4i,
-0x1.af6fa6af3c7c1p+4 + -0x1.ac494b1f0fd7p+4i, -0x1.a28a19a4d2489p+3 + 0x1.55f16cfa314a4p+3i,
-0x1.6466028bbe2edp+5 + -0x1.49a11a7f6a86p+4i, 0x1.d364484d1433cp+3 + 0x1.4dfe98fa7bb6ep+5i,
-0x1.0f3341949dc68p+5 + -0x1.f1aa4b6b05644p+2i, 0x1.4b7e2d2e81104p+4 + -0x1.28fd792c9d2a5p+3i,
-0x1.67982b09d8454p+4 + 0x1.352b453f684dep+4i, 0x1.897d15d8919fbp+5 + 0x1.7af662e392b02p+4i,
0x1.f31fe0a112c46p+3 + 0x1.e32205a32c181p+4i, 0x1.507479d98be72p+3 + 0x1.416861ee77d16p+4i,
0x1.343393ef3b35p-1 + -0x1.3c619bd1148a8p+2i, 0x1.cfe87d6a1fe16p+4 + 0x1.7e25a229594d6p+4i,
-0x1.59ac5d4242eep+1 + 0x1.011403974070ep+6i, 0x1.af74bec58c72fp+5 + 0x1.2c6de411310c7p+5i,
-0x1.607104155f3c8p+3 + 0x1.1292d83bc3128p+4i, 0x1.46c4735766966p+3 + 0x1.07cb7691b1b2ep+5i,
0x1.6ccb33749764cp+4 + 0x1.5b790b22901ap+4i, 0x1.ce7996d122819p+5 + -0x1.b316344c9e369p+3i,
0x1.5c30a25f502a4p+2 + 0x1.bf8db8cbc307p+3i, -0x1.1f0f03ecd0c72p+4 + -0x1.e91e1566b0e27p+3i,
0x1.4db4276062116p+4 + -0x1.218be4dffac78p+2i, 0x1.53e668a4bc19p+5 + 0x1.751e7b14e1b88p+2i,
0x1.05e32ff07d868p+6 + -0x1.c202c92d5ee1p+4i, -0x1.18ee82f074d2ep+4 + -0x1.1089b34077b2bp+6i,
-0x1.718b57f32982dp+5 + -0x1.46d2d094f5581p+4i, 0x1.7eecc1d30ffafp+4 + 0x1.e0cb9363b75e8p+3i,
0x1.137ef9bc208ep+6 + -0x1.c70ab51e7e748p+3i, 0x1.026a8095c0967p+5 + 0x1.d08f125ee471cp+3i,
0x1.0be3b2465cbbdp+5 + -0x1.8563c7c4e784ap+4i, 0x1.495048ad151d3p+4 + -0x1.40b4d745a273ap+4i,
0x1.7339501ecfe43p+5 + 0x1.21857cad0a0a2p+5i, -0x1.cab56703b95e8p+4 + -0x1.d58317d041d7ep+5i,
-0x1.b0f626543e544p+4 + -0x1.1292718004728p+4i, -0x1.65b3e8f6d47aep+4 + 0x1.c8f22261a8687p+6i,
-0x1.631f0d15c9a16p+4 + 0x1.245c38c686b75p+5i, 0x1.92fea3acb705fp+5 + -0x1.6eafe30aad6p-3i,
0x1.31e5a5c2cabcbp+5 + 0x1.03acf5c5f6831p+3i, -0x1.08de9a7ef2f18p+3 + 0x1.0fce8e7209494p+5i,
-0x1.fef1b5179c967p+3 + 0x1.bd7dedc62087dp+4i, 0x1.b58b6a0c5af95p+5 + -0x1.a983b62e9f431p+4i,
-0x1.2a9c01936874dp+5 + -0x1.2a4916ab529aep+3i, -0x1.1463c9bea61dp+4 + -0x1.306b85530071p+3i,
-0x1.65dcbb0330a3ap+4 + 0x1.187194aa9ee65p+6i, -0x1.92e531bc1fa45p+6 + 0x1.08ca7328a250bp+5i,
0x1.c22d0646301a2p+3 + -0x1.0eb1d24151adp+6i, 0x1.958507d8a2a5p+2 + -0x1.2423f84ec580cp+5i,
-0x1.87d2d87e70e99p+5 + 0x1.1e9d16df0a0ap+6i, 0x1.0a818882c67cp+3 + 0x1.0efc991905f35p+5i,
0x1.ef24bfc91c602p+5 + 0x1.19aaf1e900e88p+5i, 0x1.559dcbbc7a541p+4 + 0x1.b0d62fde0ba74p+6i,
-0x1.f56d2ad43bbdp+5 + 0x1.5a25df63b0897p+4i, 0x1.b6cc5623ae65p+4 + 0x1.9d65b2091589cp+5i,
0x1.78feb00bb34fp+6 + 0x1.81868536ef06cp+6i, -0x1.6269a8af2ef4fp+6 + -0x1.6d67289ecd1a4p+5i,
0x1.a0ca6ac9a8346p+4 + 0x1.0fc827689769ep+4i, 0x1.0f0b83f4162b6p+6 + 0x1.89a720bac503bp+6i,
0x1.b3adb91832b32p+5 + 0x1.c8f19978828a4p+4i, -0x1.0e437447746c4p+4 + 0x1.a24105c6a2abcp+6i,
-0x1.5beb873b34ec7p+3 + -0x1.5ba0ac3d9234p+6i, 0x1.d0ebf1c63ec02p+4 + 0x1.238b190b94b9cp+6i,
0x1.86424d7ebec87p+6 + 0x1.b4a4eda5a3e08p+5i, 0x1.ae502fcd85c5ep+6 + 0x1.942b22c734fedp+5i,
-0x1.dbb712c1aff7bp+5 + -0x1.5cb3bf8a98536p+7i, -0x1.2b68de011cadp+4 + -0x1.3f84de3b7c2f5p+6i,
0x1.99ec38b9aa89ap+6 + 0x1.f9663a1458adfp+5i, 0x1.3a4ac025dc2ap+3 + 0x1.4d56fd0898e7p+6i,
0x1.d699455ee92d2p+5 + -0x1.27cafdae25a7bp+7i, 0x1.017bd17af3f91p+6 + 0x1.54d36906390b4p+5i,
0x1.c48cd30cd9adcp+5 + 0x1.36c386301fc1ap+6i, 0x1.4500b0d505fc2p+2 + 0x1.62969f482591bp+7i,
-0x1.6d3de4eee919p+5 + -0x1.9b2702268765ap+7i, 0x1.03ebcd8e4e642p+4 + 0x1.8dab784b5a22p+3i,
-0x1.8bbf1b79ae995p+7 + 0x1.17eeddf0db3a5p+7i, 0x1.497f191934418p+6 + 0x1.0d1ec776fb6ep+5i,
-0x1.2af783452dc8p+1 + -0x1.19a699d39cc3ep+4i, -0x1.064c0b3f0d19ap+5 + -0x1.bcb3c34439eb8p+3i,
-0x1.7253559c56b9ap+6 + 0x1.70a955f9ca1eep+6i, -0x1.06d1792ea59d6p+2 + 0x1.df363df179735p+4i,
0x1.ceea8e018441fp+4 + -0x1.0d48d144cf972p+7i, -0x1.f30f4480118fdp+5 + -0x1.1ffecbdfb58f9p+5i,
0x1.d0e3338968abp+3 + -0x1.4f84b840e5de2p+6i, -0x1.58b7e8bbe6156p+6 + 0x1.0cca2372ef592p+7i,
-0x1.d204d5e0178b4p+7 + -0x1.f1c5bf0b39d9bp+6i, 0x1.526d25b45ca16p+7 + -0x1.04f1895b87929p+7i,
-0x1.6c0fcb7282371p+6 + -0x1.5240753363e4cp+6i, -0x1.16981dd0df563p+7 + 0x1.690ebe2be3bfbp+5i,
0x1.bf821658be7cp+5 + -0x1.6b26c6fefc966p+2i, -0x1.d8d211bdfe4d8p+3 + -0x1.05ec78a07c9a2p+3i,
-0x1.a946fb136461p+6 + 0x1.84b35dfd94247p+7i, -0x1.6cc9c77314408p+7 + 0x1.c9730739eca74p+5i,
-0x1.5844d278c89a7p+7 + -0x1.3d9e7752a89ep+2i, -0x1.29b2fe4327df9p+7 + 0x1.c8d2d8840c655p+7i,
-0x1.34ac883b034ap+6 + -0x1.63d586f92bd9bp+7i, -0x1.066871621de1ep+7 + 0x1.1cb153427cb17p+7i,
-0x1.2d2fb1665a42p+7 + 0x1.26e5d2d93f468p+7i, 0x1.90911d8361b3bp+4 + 0x1.5c42e448f60d8p+6i,
-0x1.27ff480c08121p+8 + 0x1.216e66d073fa8p+8i, -0x1.40d36ff72f687p+6 + -0x1.5d80d174d6cabp+7i,
0x1.ba505bcd7812ap+6 + 0x1.76c5da847fdc7p+7i, 0x1.d309ecda94f89p+6 + 0x1.024fa3216fcf9p+8i,
-0x1.fd76d50ec4298p+5 + 0x1.4053c1efd38aap+7i, 0x1.476feb8837972p+6 + -0x1.5a68600efc808p+7i,
0x1.4139327d8a941p+8 + -0x1.2518bcd7353bap+6i, 0x1.7560d2c808b1ep+5 + 0x1.bf5a33bbe4695p+7i,
-0x1.1a55cb2e9e986p+7 + 0x1.50d9c17170fe8p+3i, 0x1.bd5005bf4515ep+8 + -0x1.e2fae4649817fp+8i,
0x1.df9481d1ea563p+6 + 0x1.7d98468c19984p+7i, 0x1.be09d3abe2a4dp+7 + 0x1.f1e49dccc06c4p+7i,
-0x1.2ba77db2ea156p+7 + 0x1.85cb8621d93bap+7i, 0x1.ad95eb9776745p+4 + -0x1.9d517a3f3e608p+8i,
0x1.89e303a24b0f3p+6 + 0x1.4af99c04e2176p+6i, -0x1.f2695e71d9d22p+6 + -0x1.3e2f23f36aae4p+6i,
-0x1.a7b0846b7d96cp+6 + -0x1.01901079190acp+3i, 0x1.479316b8dfd1ep+5 + -0x1.17ac310914b68p+8i,
0x1.d85936e3a9622p+5 + -0x1.f55b325767765p+5i, -0x1.c070bec0c2d5ap+7 + -0x1.c569e9faa1079p+5i,
-0x1.3c2c114247646p+7 + 0x1.46e9df89669ep+7i, -0x1.0ad6bbecc2db2p+7 + -0x1.39ef122d1e26p+7i,
-0x1.78cb97f1e9e38p+7 + -0x1.8b3a1273a2fafp+3i, -0x1.c02c43778a9d4p+7 + -0x1.80a8cb4c30692p+6i,
0x1.36d61ff0bed8cp+3 + 0x1.2ac10ced91d1dp+6i, -0x1.7cdb6b503a3e6p+6 + -0x1.1f12f02c77b0ap+7i,
0x1.026f7585fb24cp+4 + -0x1.b6d03b39d103ap+5i, 0x1.a55922e665df2p+6 + 0x1.30faf83f61c8ap+4i,
0x1.82c43d3fd5463p+6 + 0x1.4fc124b71a2fbp+8i, 0x1.80185d7d61ea3p+3 + 0x1.04e0bd8a2c015p+6i,
0x1.84644ce4be688p+6 + 0x1.1ceafc1e236bcp+5i, 0x1.330ab725dc1f9p+5 + -0x1.9e086560c9448p+6i,
0x1.2affb776b079cp+6 + 0x1.9fc549bf515b2p+5i, 0x1.493f2288f1a53p+7 + -0x1.b9d4401dd8cc9p+4i,
0x1.978c74723b42dp+7 + -0x1.04041116a6668p+6i, -0x1.ccb7d58d77586p+4 + 0x1.0b8a1e51d27f8p+7i,
0x1.0b2d823b969e6p+7 + -0x1.81adf2c92ac21p+2i, 0x1.88f5557ff7433p+5 + 0x1.4b43d1d9d5687p+5i,
-0x1.6520587503494p+5 + -0x1.4520097fa4999p+5i, 0x1.4ee40310afcddp+7 + -0x1.7878eec8c332p+7i,
-0x1.4446e198219acp+7 + 0x1.24642e883f595p+5i, 0x1.024dbf1d837fp+6 + -0x1.8f86b84c53909p+7i,
-0x1.398dfc2722316p+6 + -0x1.126abcfd9a007p+5i, -0x1.a40e3c8b2766ap+5 + -0x1.c95225680fb6cp+7i,
-0x1.5340bec5a4871p+7 + -0x1.2f04e41c269a8p+6i, 0x1.488e065a79b42p+3 + -0x1.0fce271623103p+7i,
-0x1.027aa1d01cd08p+2 + 0x1.a07fc09efdbe8p+5i, -0x1.d5edcd97ef864p+2 + -0x1.083a73cde98bcp+7i,
-0x1.92c8d62726d4cp+7 + -0x1.0aa3e42112978p+3i, 0x1.6104ba1832334p+7 + -0x1.1ebae79836f6ap+6i,
-0x1.60228b300acd2p+7 + 0x1.4d18cfa95b45p+4i, 0x1.3ce5b6416b93fp+4 + -0x1.2a7edd86fe7e9p+7i,
-0x1.6b59b63288c4p+4 + 0x1.6a7c6ad0291b4p+6i, -0x1.f05e7e59b1a16p+5 + 0x1.b711ae4833962p+6i,
0x1.11f598e588f5bp+6 + 0x1.6dc2049367fc4p+7i, 0x1.3b7928790c099p+6 + -0x1.1c8638d894e95p+6i,
0x1.5332df353aac3p+4 + 0x1.0f5caaed86223p+7i, -0x1.eab267bae9bd7p+4 + 0x1.098ac9fa8eb6p+6i,
0x1.7d397adf453dp+6 + 0x1.d465a4885cc0ap+6i, -0x1.2f3f02c0240f1p+6 + -0x1.bd950f8f5d72bp+5i,
0x1.bcd74027e0dcdp+5 + 0x1.edcdcc0a2195cp+6i, -0x1.d69a00aec9653p+5 + -0x1.81dbb50742ba4p+6i,
0x1.d30ba09c9626ep+6 + 0x1.c901ef2bb6d0bp+6i, -0x1.956a7cf8b180dp+6 + -0x1.071c3ab07a613p+7i,
0x1.977a2b9249462p+6 + 0x1.8b7daf00f9821p+6i, -0x1.1d407386903edp+5 + -0x1.1adc0dc578f39p+3i,
0x1.c79a2e623de4fp+5 + 0x1.73c88661c093bp+5i, 0x1.00e279e2cc988p+3 + -0x1.03ba6d4e74d66p+3i,
0x1.d4c29f6b13808p+5 + 0x1p-48i, 0x1.00e279e2cc95p+3 + 0x1.03ba6d4e74d77p+3i,
0x1.c79a2e623de37p+5 + -0x1.73c88661c093p+5i, -0x1.1d407386903eep+5 + 0x1.1adc0dc578f43p+3i,
0x1.977a2b924945ap+6 + -0x1.8b7daf00f981ep+6i, -0x1.956a7cf8b180fp+6 + 0x1.071c3ab07a614p+7i,
0x1.d30ba09c9626ap+6 + -0x1.c901ef2bb6d0ep+6i, -0x1.d69a00aec9653p+5 + 0x1.81dbb50742ba8p+6i,
0x1.bcd74027e0dbcp+5 + -0x1.edcdcc0a21954p+6i, -0x1.2f3f02c0240ecp+6 + 0x1.bd950f8f5d72cp+5i,
0x1.7d397adf453cp+6 + -0x1.d465a4885cc02p+6i, -0x1.eab267bae9bd6p+4 + -0x1.098ac9fa8eb64p+6i,
0x1.5332df353aaccp+4 + -0x1.0f5caaed8621dp+7i, 0x1.3b7928790c0ap+6 + 0x1.1c8638d894e9ep+6i,
0x1.11f598e588f53p+6 + -0x1.6dc2049367fbep+7i, -0x1.f05e7e59b1a0bp+5 + -0x1.b711ae4833963p+6i,
-0x1.6b59b63288c0bp+4 + -0x1.6a7c6ad0291aep+6i, 0x1.3ce5b6416b94dp+4 + 0x1.2a7edd86fe7e9p+7i,
-0x1.60228b300acdp+7 + -0x1.4d18cfa95b447p+4i, 0x1.6104ba1832338p+7 + 0x1.1ebae79836f59p+6i,
-0x1.92c8d62726d4bp+7 + 0x1.0aa3e421129bdp+3i, -0x1.d5edcd97ef874p+2 + 0x1.083a73cde98bdp+7i,
-0x1.027aa1d01cda1p+2 + -0x1.a07fc09efdbdep+5i, 0x1.488e065a79b3ap+3 + 0x1.0fce2716230fep+7i,
-0x1.5340bec5a486fp+7 + 0x1.2f04e41c269aap+6i, -0x1.a40e3c8b2765cp+5 + 0x1.c95225680fb6cp+7i,
-0x1.398dfc272231ap+6 + 0x1.126abcfd9a008p+5i, 0x1.024dbf1d837f3p+6 + 0x1.8f86b84c53904p+7i,
-0x1.4446e198219aap+7 + -0x1.24642e883f595p+5i, 0x1.4ee40310afcdap+7 + 0x1.7878eec8c331dp+7i,
-0x1.652058750349ep+5 + 0x1.4520097fa49ap+5i, 0x1.88f5557ff7426p+5 + -0x1.4b43d1d9d5688p+5i,
0x1.0b2d823b969e6p+7 + 0x1.81adf2c92abcp+2i, -0x1.ccb7d58d77599p+4 + -0x1.0b8a1e51d27fap+7i,
0x1.978c74723b42ep+7 + 0x1.04041116a6664p+6i, 0x1.493f2288f1a51p+7 + 0x1.b9d4401dd8cc8p+4i,
0x1.2affb776b079cp+6 + -0x1.9fc549bf515b5p+5i, 0x1.330ab725dc208p+5 + 0x1.9e086560c944dp+6i,
0x1.84644ce4be687p+6 + -0x1.1ceafc1e236a8p+5i, 0x1.80185d7d61e9p+3 + -0x1.04e0bd8a2c00dp+6i,
0x1.82c43d3fd545ap+6 + -0x1.4fc124b71a2fap+8i, 0x1.a55922e665dfdp+6 + -0x1.30faf83f61c96p+4i,
0x1.026f7585fb252p+4 + 0x1.b6d03b39d103bp+5i, -0x1.7cdb6b503a3ep+6 + 0x1.1f12f02c77b0fp+7i,
0x1.36d61ff0bed76p+3 + -0x1.2ac10ced91d23p+6i, -0x1.c02c43778a9d6p+7 + 0x1.80a8cb4c30697p+6i,
-0x1.78cb97f1e9e36p+7 + 0x1.8b3a1273a2f9ep+3i, -0x1.0ad6bbecc2db1p+7 + 0x1.39ef122d1e264p+7i,
-0x1.3c2c114247648p+7 + -0x1.46e9df89669ep+7i, -0x1.c070bec0c2d5ep+7 + 0x1.c569e9faa108dp+5i,
0x1.d85936e3a9628p+5 + 0x1.f55b325767766p+5i, 0x1.479316b8dfd2p+5 + 0x1.17ac310914b6ap+8i,
-0x1.a7b0846b7d973p+6 + 0x1.019010791908ep+3i, -0x1.f2695e71d9d1fp+6 + 0x1.3e2f23f36aae8p+6i,
0x1.89e303a24b0f2p+6 + -0x1.4af99c04e217ap+6i, 0x1.ad95eb9776762p+4 + 0x1.9d517a3f3e60ap+8i,
-0x1.2ba77db2ea16p+7 + -0x1.85cb8621d93b7p+7i, 0x1.be09d3abe2a5p+7 + -0x1.f1e49dccc06c3p+7i,
0x1.df9481d1ea556p+6 + -0x1.7d98468c19988p+7i, 0x1.bd5005bf45162p+8 + 0x1.e2fae4649818p+8i,
-0x1.1a55cb2e9e988p+7 + -0x1.50d9c17170fd4p+3i, 0x1.7560d2c808b14p+5 + -0x1.bf5a33bbe4699p+7i,
0x1.4139327d8a947p+8 + 0x1.2518bcd7353bap+6i, 0x1.476feb8837978p+6 + 0x1.5a68600efc80ap+7i,
-0x1.fd76d50ec42a8p+5 + -0x1.4053c1efd38bp+7i, 0x1.d309ecda94f8cp+6 + -0x1.024fa3216fcfbp+8i,
0x1.ba505bcd7812cp+6 + -0x1.76c5da847fdccp+7i, -0x1.40d36ff72f685p+6 + 0x1.5d80d174d6cacp+7i,
-0x1.27ff480c08124p+8 + -0x1.216e66d073faap+8i, 0x1.90911d8361b4ep+4 + -0x1.5c42e448f60d3p+6i,
-0x1.2d2fb1665a427p+7 + -0x1.26e5d2d93f468p+7i, -0x1.066871621de26p+7 + -0x1.1cb153427cb2p+7i,
-0x1.34ac883b0349fp+6 + 0x1.63d586f92bd9dp+7i, -0x1.29b2fe4327dfep+7 + -0x1.c8d2d8840c658p+7i,
-0x1.5844d278c89aep+7 + 0x1.3d9e7752a89fp+2i, -0x1.6cc9c7731440ep+7 + -0x1.c9730739eca75p+5i,
-0x1.a946fb136461ap+6 + -0x1.84b35dfd9424ep+7i, -0x1.d8d211bdfe4eap+3 + 0x1.05ec78a07c9dp+3i,
0x1.bf821658be7cp+5 + 0x1.6b26c6fefc966p+2i, -0x1.16981dd0df55ep+7 + -0x1.690ebe2be3cp+5i,
-0x1.6c0fcb7282366p+6 + 0x1.5240753363e52p+6i, 0x1.526d25b45ca1p+7 + 0x1.04f1895b87925p+7i,
-0x1.d204d5e0178abp+7 + 0x1.f1c5bf0b39d94p+6i, -0x1.58b7e8bbe615fp+6 + -0x1.0cca2372ef589p+7i,
0x1.d0e3338968ac8p+3 + 0x1.4f84b840e5ddap+6i, -0x1.f30f4480118fbp+5 + 0x1.1ffecbdfb5903p+5i,
0x1.ceea8e0184424p+4 + 0x1.0d48d144cf96ep+7i, -0x1.06d1792ea59d8p+2 + -0x1.df363df17972ap+4i,
-0x1.7253559c56b9dp+6 + -0x1.70a955f9ca1eap+6i, -0x1.064c0b3f0d19ap+5 + 0x1.bcb3c34439eap+3i,
-0x1.2af783452dc3p+1 + 0x1.19a699d39cc38p+4i, 0x1.497f19193441bp+6 + -0x1.0d1ec776fb6e2p+5i,
-0x1.8bbf1b79ae99p+7 + -0x1.17eeddf0db3a2p+7i, 0x1.03ebcd8e4e642p+4 + -0x1.8dab784b5a24p+3i,
-0x1.6d3de4eee9178p+5 + 0x1.9b27022687655p+7i, 0x1.4500b0d505f9cp+2 + -0x1.62969f4825911p+7i,
0x1.c48cd30cd9accp+5 + -0x1.36c386301fc19p+6i, 0x1.017bd17af3f96p+6 + -0x1.54d36906390b8p+5i,
0x1.d699455ee92cep+5 + 0x1.27cafdae25a78p+7i, 0x1.3a4ac025dc2cp+3 + -0x1.4d56fd0898e67p+6i,
0x1.99ec38b9aa89p+6 + -0x1.f9663a1458ad8p+5i, -0x1.2b68de011cab5p+4 + 0x1.3f84de3b7c2f6p+6i,
-0x1.dbb712c1aff7ap+5 + 0x1.5cb3bf8a98535p+7i, 0x1.ae502fcd85c56p+6 + -0x1.942b22c734ffp+5i,
0x1.86424d7ebec8p+6 + -0x1.b4a4eda5a3e09p+5i, 0x1.d0ebf1c63ebfbp+4 + -0x1.238b190b94b9ap+6i,
-0x1.5beb873b34eb8p+3 + 0x1.5ba0ac3d92341p+6i, -0x1.0e437447746bp+4 + -0x1.a24105c6a2ab8p+6i,
0x1.b3adb91832b2ap+5 + -0x1.c8f19978828a4p+4i, 0x1.0f0b83f4162bp+6 + -0x1.89a720bac5039p+6i,
0x1.a0ca6ac9a834cp+4 + -0x1.0fc8276897692p+4i, -0x1.6269a8af2ef4cp+6 + 0x1.6d67289ecd19dp+5i,
0x1.78feb00bb34fp+6 + -0x1.81868536ef067p+6i, 0x1.b6cc5623ae65p+4 + -0x1.9d65b209158ap+5i,
-0x1.f56d2ad43bbccp+5 + -0x1.5a25df63b0895p+4i, 0x1.559dcbbc7a55ap+4 + -0x1.b0d62fde0ba72p+6i,
0x1.ef24bfc91c60ap+5 + -0x1.19aaf1e900e88p+5i, 0x1.0a818882c67b5p+3 + -0x1.0efc991905f3ap+5i,
-0x1.87d2d87e70e8dp+5 + -0x1.1e9d16df0a0a4p+6i, 0x1.958507d8a2a58p+2 + 0x1.2423f84ec580cp+5i,
0x1.c22d0646301b2p+3 + 0x1.0eb1d24151adp+6i, -0x1.92e531bc1fa46p+6 + -0x1.08ca7328a2506p+5i,
-0x1.65dcbb0330a48p+4 + -0x1.187194aa9ee66p+6i, -0x1.1463c9bea61d2p+4 + 0x1.306b855300718p+3i,
-0x1.2a9c019368743p+5 + 0x1.2a4916ab529c2p+3i, 0x1.b58b6a0c5af8dp+5 + 0x1.a983b62e9f43ap+4i,
-0x1.fef1b5179c98ap+3 + -0x1.bd7dedc62087ep+4i, -0x1.08de9a7ef2f4p+3 + -0x1.0fce8e72094a6p+5i,
0x1.31e5a5c2cabd2p+5 + -0x1.03acf5c5f6825p+3i, 0x1.92fea3acb7062p+5 + 0x1.6eafe30aad8p-3i,
-0x1.631f0d15c9a29p+4 + -0x1.245c38c686b71p+5i, -0x1.65b3e8f6d47cdp+4 + -0x1.c8f22261a8687p+6i,
-0x1.b0f626543e538p+4 + 0x1.129271800473p+4i, -0x1.cab56703b95e1p+4 + 0x1.d58317d041d8p+5i,
0x1.7339501ecfe3bp+5 + -0x1.21857cad0a0ap+5i, 0x1.495048ad151e1p+4 + 0x1.40b4d745a2736p+4i,
0x1.0be3b2465cbc4p+5 + 0x1.8563c7c4e7858p+4i, 0x1.026a8095c096ap+5 + -0x1.d08f125ee472ap+3i,
0x1.137ef9bc208dep+6 + 0x1.c70ab51e7e72bp+3i, 0x1.7eecc1d30ffa1p+4 + -0x1.e0cb9363b75fp+3i,
-0x1.718b57f329824p+5 + 0x1.46d2d094f558ap+4i, -0x1.18ee82f074d25p+4 + 0x1.1089b34077b2ep+6i,
0x1.05e32ff07d86bp+6 + 0x1.c202c92d5edecp+4i, 0x1.53e668a4bc18ep+5 + -0x1.751e7b14e1bbp+2i,
0x1.4db4276062107p+4 + 0x1.218be4dffac6p+2i, -0x1.1f0f03ecd0c5dp+4 + 0x1.e91e1566b0e22p+3i,
0x1.5c30a25f502dp+2 + -0x1.bf8db8cbc3074p+3i, 0x1.ce7996d12281ep+5 + 0x1.b316344c9e34cp+3i,
0x1.6ccb33749763ep+4 + -0x1.5b790b229017ap+4i, 0x1.46c4735766954p+3 + -0x1.07cb7691b1b31p+5i,
-0x1.607104155f3ap+3 + -0x1.1292d83bc313cp+4i, 0x1.af74bec58c72ep+5 + -0x1.2c6de411310c7p+5i,
-0x1.59ac5d4242f1p+1 + -0x1.0114039740713p+6i, 0x1.cfe87d6a1fe12p+4 + -0x1.7e25a229594ccp+4i,
0x1.343393ef3b38p-1 + 0x1.3c619bd1148b8p+2i, 0x1.507479d98be9ap+3 + -0x1.416861ee77d05p+4i,
0x1.f31fe0a112c4ap+3 + -0x1.e32205a32c182p+4i, 0x1.897d15d8919eep+5 + -0x1.7af662e392afep+4i,
-0x1.67982b09d846ap+4 + -0x1.352b453f684d4p+4i, 0x1.4b7e2d2e8110ap+4 + 0x1.28fd792c9d2b9p+3i,
-0x1.0f3341949dc6fp+5 + 0x1.f1aa4b6b0562p+2i, 0x1.d364484d142fp+3 + -0x1.4dfe98fa7bb7ap+5i,
-0x1.6466028bbe2e7p+5 + 0x1.49a11a7f6a85ap+4i, -0x1.a28a19a4d24a4p+3 + -0x1.55f16cfa314a4p+3i,
-0x1.af6fa6af3c7b9p+4 + 0x1.ac494b1f0fd72p+4i, -0x1.ee193b30d406p+2 + -0x1.4f0be139890ecp+4i,
-0x1.fcd7b8c867588p+2 + -0x1.51a550e7bc1e8p+2i, -0x1.c238973f83cp-4 + -0x1.75beb10603b94p+2i,
0x1.7c6d386164a34p+1 + 0x1.18635de33a7b2p+4i, 0x1.a247c91febf1p+1 + -0x1.ef829b913cd4p+1i,
-0x1.8ab1f21de2eb2p+3 + -0x1.a756713601cb4p+4i, -0x1.b289eca1da742p+4 + -0x1.5e4ff25a3f3ep+1i,
-0x1.5361555bb8a8ap+3 + 0x1.58e5624cab03ep+4i, 0x1.b6d64b9a15fe1p+4 + 0x1.118da4b7f876p+2i,
0x1.3e89916b3c258p+3 + 0x1.7a26344eb673cp+2i, 0x1.561ee6fa6af9cp+4 + -0x1.b2c863906ce81p+4i,
0x1.e75a6994dcap+1 + -0x1.8115abe450041p+3i, 0x1.a4705bf38c286p+3 + 0x1.829109abf9ad8p+4i,
0x1.80a45360df251p+2 + 0x1.97fb1aac9f3fp+4i, 0x1.30a472fd3a11ep+3 + -0x1.397bf31f9a502p+5i,
-0x1.e54345d4a7d3bp+5 + 0x1.784fab15862f2p+4i, 0x1.5d16c0f546fabp+4 + 0x1.ce43b1d1b472ep+5i,
0x1.5612fafaa1d1p+2 + -0x1.7b59d94a51518p+5i, 0x1.a214eb7ae7913p+5 + -0x1.07d7711f4acbap+5i,
-0x1.e898038744418p+3 + 0x1.22135f895e0f7p+5i, -0x1.e808027dbb7b8p+3 + -0x1.be31877613dp+3i,
0x1.7fe49a4aa0548p+1 + 0x1.b297bcddd24p-3i, 0x1.a2a298e5c61d9p+6 + -0x1.fdaf9218b663p+5i,
-0x1.2cc718d796b92p+5 + -0x1.1b6a616c01249p+5i, -0x1.1ec92afc81efep+5 + 0x1.4eba5c27a0374p+3i,
-0x1.8ea7139ccdc58p+3 + -0x1.0545d573cece3p+5i, 0x1.09195c9f202c4p+6 + -0x1.5bea2618443a2p+6i,
0x1.d5984fca042bep+3 + -0x1.fd5859e74ab36p+4i, -0x1.acd94dc0af892p+5 + 0x1.491b5b6f854ccp+4i,
-0x1.a8b525de6166p+1 + -0x1.f4360ba55619cp+2i, 0x1.216aa633312c5p+7 + -0x1.8decdb91202cfp+6i,
0x1.5799b61ed4324p+5 + -0x1.59f5a10f0142p+2i, -0x1.4ddbcf44f287fp+6 + -0x1.46e88fe8404cep+4i,
-0x1.a5dbe0c85ebeap+4 + 0x1.62fad467550d4p+3i, 0x1.04dec220d9685p+5 + -0x1.e1ed205e9d7cp+2i,
0x1.71e8bb36427ecp+5 + 0x1.c01cbe8c24c49p+4i, -0x1.9564826dc97a1p+6 + -0x1.0194fe4953ef2p+5i,
0x1.dafbf99b0dc94p+4 + 0x1.eac87238bc7a8p+2i, 0x1.9ed28df367cbdp+5 + 0x1.1825e1d3b4b44p+4i,
-0x1.102fd011d0374p+4 + -0x1.2d79a845ca2a7p+6i, -0x1.53a43ed485ebcp+4 + -0x1.12261a030f866p+6i,
-0x1.37f5d015ca72cp+2 + -0x1.a7691ff4cfacp+0i, 0x1.0da89c3d09a9ap+5 + -0x1.5a71c6c7ff532p+5i,
0x1.2015cd17685b4p+4 + 0x1.d644f0b97d071p+4i, 0x1.b1c300a76ed5ep+5 + -0x1.64f1bed03ea4ep+6i,
-0x1.055e90b30c31cp+4 + -0x1.7c4d8622132c3p+5i, -0x1.ddbf771d57d29p+5 + -0x1.14960d50b9104p+5i,
0x1.d998eaa622801p+6 + -0x1.4332253c22c8cp+5i, -0x1.59f353a4c3b6p+4 + -0x1.000f60cdabbbdp+7i,
-0x1.0bc71fcb6cea8p+6 + -0x1.c92cd3b3dfd2bp+6i, 0x1.fec44787c9874p+5 + 0x1.93297b084a96p+3i,
0x1.fb9664f6e6fcp+0 + 0x1.866a32487f4bap+6i, -0x1.5bbf2314c2f48p+3 + 0x1.b3373d0cfc07p+3i,
-0x1.ceef56d28c7ap+5 + 0x1.2f97cc286189ep+5i, -0x1.62955da2f9f24p+6 + -0x1.250a849c50856p+5i,
-0x1.7078152332068p+6 + 0x1.c8053c772dc28p+7i, -0x1.611bbcfaa0fbdp+5 + -0x1.bb6ef346f9158p+5i,
0x1.5594fb2083df4p+6 + 0x1.c12a357ab25ecp+6i, -0x1.922df046af508p+7 + 0x1.9ee5f0b134384p+6i,
-0x1.4913857c21008p+4 + 0x1.5456c7b7a0cccp+5i, -0x1.3a0e23a526831p+5 + 0x1.d64fb153b4bafp+6i,
0x1.a20efc5d12491p+7 + -0x1.b09bd2dec195ap+4i, 0x1.dcdfd48236048p+4 + 0x1.b0e19b9841f3cp+5i,
-0x1.7f83fcdb74acap+5 + 0x1.81886739a6289p+7i, 0x1.27fe11662f3b2p+5 + -0x1.3d9c0fa6ffa1bp+6i,
0x1.ba16fa21c7f36p+7 + 0x1.272dc12699e9fp+6i, 0x1.69984475fe664p+6 + 0x1.da2f4795c9089p+5i,
-0x1.2f570fe08959ap+4 + 0x1.e16f6b53ea1f6p+5i, -0x1.71ff938ddea58p+1 + -0x1.4ae09f2dd74bp+7i
)
assertThat(stats:::fft(z=c(2.5012040421033, -0.852703320982114, 2.44035192628976, -0.315539723699655,
0.451149432296798, 8.39986904159832, -3.71189679906669, 7.27036106167732,
11.8151029135936, -6.38040750224049, 16.140696299544, 17.9377191077876,
-0.247416729234539, 0.509985690750293, 23.6568924680204, -14.3283522003003,
29.0960018063503, -0.515351440037323, 0.461417080193512, 24.4359854141647,
-15.9259485863116, 15.4066080101472, 4.39832443156715, -1.41276362948581,
0.10961423258584, 0.0485058172165162, -0.0506172814824217, 0.0800726431664566,
-0.971775810107449, -0.159327244450868, 0.176100543237969, 1.46681536662943,
-0.901994696172206, 0.177783920515548, 0.0781994358807019, 0.853771169012253,
4.06682106624248, -3.92626957121147, 4.45823618847641, 3.27847565292114,
-1.6003497166291, 2.42141340354962, -0.0564822721187989, 0.0450168316948576,
6.88934765948805, -4.32479649009797, 1.37222564023403, 2.75602044212694,
4.78084372056581, -1.2345938300935, 1.88994314666231, -2.54359571283588,
1.20600975255887, 0.110839547015589, -0.341579208618709, 5.61577604097341,
-4.22187717519161, 7.61120688676179, 4.16373131699246, -0.637266653937873,
0.629403727561432, 5.2713292035987, 4.06379201996547, -0.831247338546666,
1.05325205496696, -1.94149165628752, 1.26186841020846, -0.310646853209618,
1.01401679421515, -1.36690229893332, 0.516399945583213, 3.01166167208335,
5.98914817193362, -3.82003096140539, 2.96219376784357, -1.30568356049955,
1.71711211450703, 1.28709171787915, -0.565617025105025, 3.06288842776523,
-2.04342579408792, 1.28284608054908, 2.86231996565247, 1.43583145583119,
-1.00086734440029, 1.61178008920269, 2.45550406803161, 1.77896648213551,
-2.28490088064518, 2.55562665533308, -1.49665453685557, 0.00295904003007553,
-0.00120431376366571, -0.400856846650015, 0.322155013391105,
-0.925637418559187, -1.31332548196304, 1.42564220079983, 1.88493708230512,
-1.80825312904525, -0.590217617428646, 0.460239317779972, 1.40891960238598,
-1.69617688707413, 6.03011384325574, 3.05171301947801, -2.65252190174016,
16.0473152937269, 26.7700662436687, -9.05900954943811, 10.7513836108143,
10.8872606657361, -4.90047945822155, 6.24267343128678, -7.63519358224046,
9.85572197072743, -5.51538039199178, 4.92901497644546, 8.00921890911801,
-0.874457006746495, 1.49985313774802, 6.57391386208709, -2.5333318482676,
2.36405268999242, -0.541006858312492, 1.18083200735623, 0.217567807144298,
-0.207936708158817, 5.26230910118677, -1.92562116948667, 1.77248431442931,
3.90784011215136, 2.55054445419399, -2.42936466416995, 5.34368241959385,
1.14097032586022, -1.02908294589034, 0.825445145253103, -0.820705216020013,
-1.39477643847076, 1.42758723696605, -2.60844283655719, 2.34473549675069,
-0.266522317050162, 0.324694717223095, 0.00550709286075549, -0.00206891492054926,
2.3143033607981, 5.66683824991409, -6.53189934993799, 12.1696626147129,
3.03432183829145, -3.46610435603563, 14.4242308095015, -5.32838109793059,
-1.14455267644162, 0.324940325593892, -0.293247282343827, 1.12484150676126,
0.902197765258794, -1.03415890744551, 0.095757225968718, -0.0743925757821109,
1.36036788896361, -2.0047266490236, 4.95794813262346, 0.116094137219661,
-0.148167117267199, 11.441457227158, 5.85450776913955, -2.35413642755203,
6.81994019164135, 7.10148400969307, -5.27948321319351, 11.6044733261157,
-6.04560180155941, 6.35291128087907, 9.3794478361337, -0.680976468673371,
1.1880741812413, 7.80664942847109, 1.47060031445332, -1.83478118029851,
7.45981893203329, -6.14139584761569, 6.82202878944333, -0.171544210759257,
0.197191292709193, 6.54781795657122, -1.73189339437818, 1.54147878042684,
2.69176962546982, 0.232430264608403, -0.0163441439067955, -0.0431195067204222,
0.00784356881264786, 0.0182396250627736, 2.44000434064976, -2.67313080055508,
1.59017064884522, -0.746172106486337, -0.36527366171441, -0.29788857314782,
0.359569858591856, 0.572512908874245, 0.0538651090663797, -0.19805653886491,
3.30512959166409, -4.40861521100242, 6.45936814126974, -4.59510486724164,
7.34753588160399, -5.75945837686849, 3.97799412278568, -1.0158351635041,
0.66198678652632, -2.58319413202051, 4.77632187923232, -2.37249620701901,
2.15552699300767, 5.80210548272318, -3.06105082506442, 3.78437428334951,
0.0191069700045594, -0.0177215171350846, 1.78965091920213, 1.76286983630135,
-4.49684285756558, 5.46833018649636, 4.39789126723243, -5.88588433415689,
14.7971574900745, -7.13718455636349, 7.72190520995131, -2.14676414894422,
2.99038339602131, 19.4400771491541, -11.9657398318215, 26.1007809012763,
2.22625453343337, -0.356941069781394, 6.93518380362381, 11.5445525630654,
-8.94635692154641, 18.9174874793086, -12.4556903609694, 17.4610180804415,
-7.05045206962605, 5.40391141048492, 11.5442968616627, -1.65346204464609,
1.16935947602525, 0.167512338209973, 0.0103446359672158, -0.0471980052583276,
0.331084965400175, 0.680755577558796, 0.0555929926605876, -0.0400505517334367,
0.835908472349696, 1.53779174700996, -2.15821663662979, 5.69718268234453,
-0.365948010845236, 0.431204217897756, 4.51148556117302, -4.43658496129472,
8.33688118108401, -3.89333538373651, 7.26779737018077, 6.20628119782736,
-5.37850810019446, 18.0768666874588, 2.42523827817873, -2.07589614496951,
20.0132710811781, 13.7305528853174, -8.20404795933263, 16.2757489613215,
7.12231734522343, -6.62448942954927, 16.3016852659439, -7.31491549524687,
7.23756128375191, -0.86740852549099, 0.15645313718035, 1.70205867109388,
0.642937128917955, -0.288573860767142, 2.16062038403456, 0.635433272499144,
-1.0087799229265, 2.70678837939585, -1.33288521576567, 2.17609644047186,
1.14908019692451, -1.98117798106868, 0.0797906418462385, -0.0251239621730992,
1.01620032422546, -1.54808665816047, 2.83053804467082, -1.09218949297695,
0.632038855434266, 1.52389812175052, -1.40539882348273, 2.23146728831447,
1.89303794221421, -2.31374797734432, 5.05231556507842, 2.14730052100349,
-0.592720081850207, 1.83156688414441, 12.2410664115702, -5.26024384123263,
5.9804240533475, 1.36907282331545, -1.1380872476593, 15.7025566112197,
-1.93476962390521, 1.07635371681567, 9.14668223144001, 14.6840327799302,
-6.86888186492203, 6.44741530205466, 5.3451975679566, -1.85258780540552,
1.52811075716002, -0.905439511722959, 1.5868973822548, 2.95727301085742,
-2.07395122965949, 7.02692258322975, -0.607550991428778, 0.66596450196185,
17.8566358948004, -9.28680123208382, 13.2356069431331, 9.53989202921055,
-6.65052536826735, 15.1146585135973, -1.00237341450106, 0.882580049011146,
12.5949157095993, -7.71191295207103, 13.5919867790231, 23.9861184897859,
-13.8412602161988, 21.5781516122271, 17.7604253401961, -8.23321133367405,
14.7731418413822, 0.770051912445922, -0.722732423493026, 10.614744514212,
-8.31177932951141, 17.0488461456286, 1.94365739831651, -2.42791346912146,
23.9513544622624, -6.7594727193773, 4.11248373104701, 11.713231261678,
-7.55353208807729, 9.42938236479106, 0.413879412796547, -0.207678880064357,
10.9269709438967, -2.06769561087957, 1.68997622955887, 8.31579915959058,
4.83978725111278, -1.40100774401766, -0.182999302645208, -0.122504690898673,
0.662831489459104, 0.887082233707843, 0.798954936814531, -0.240652153897319,
0.138724993302157, 0.340993109892967, 0.239911316386162, -0.418380193084653,
1.49593978874958, 0.220038319672763, -0.346290762334036, 3.34869119231549,
-2.82425434587945, 6.3737269912336, -3.27627072207272, 4.10028449495215,
2.19024082438953, -2.12167510798474, 11.0730169215, -2.67847826095838,
3.05427674536037, 8.98939760388754, 1.611112563661, -1.53963982164349,
8.57018909477986, 2.37506451839262, -2.6502470247708, 8.64013631563968,
-4.68347650171519, 4.2448040412097, 5.07061000911227, -6.188275230053,
7.44286345184308, -3.67210851942231, 2.505251766006, 2.13601539846353,
-2.90120414441156, 9.86038848975323, -4.0690389277474, 4.26401675735639,
3.25992070521575, -3.08851308300356, 13.3452182214933, -7.78770117430249,
6.92490512394041, 9.03571711218963, -2.14166229520116, 2.03111955112523,
2.52099358848683, -0.515404199925128, 0.0839303100054819, 0.112472172798764,
-0.858027849326813, 0.170138760087768, 0.00432855150466349, 0.00234526751704238,
-0.0275204612657056, 0.331452037725083, 1.2020973912655, 0.56598461917252,
-0.60379466554742, 0.208929900608138, -0.389178206676026, 3.7590232181887,
-1.35179108707322, 1.97347568442672, 4.70391627742326, 1.69923024894145,
-3.75412357444561, 21.7197800493308, -3.89574387168473, 4.23044664362416,
8.64750601740092, -6.2146890569807, 10.89055543874, -2.93353561240448,
4.09994083987669, -1.41288940315791, 0.878944150987665, 3.05932116921148,
0.941815299235979, -2.14210730233434, 2.57993260862339, -0.084904175750199,
-0.100940226410693, -1.41528772859382, 2.9170468908322, -1.22823168645884,
1.74839533583815, 12.1470619176815, -5.81476260324132, 5.1244133525054,
11.3884019084128))
, identicalTo( expected, tol = 1e-6 ) )
|
tuneRandom = function(learner, task, resampling, measures, par.set, control, opt.path, show.info, resample.fun) {
vals = sampleValues(n = control$extra.args$maxit, par = par.set, trafo = FALSE)
evalOptimizationStatesTune(learner, task, resampling, measures, par.set, control, opt.path,
show.info, vals, dobs = seq_along(vals), eols = NA_integer_, remove.nas = TRUE, resample.fun)
makeTuneResultFromOptPath(learner, par.set, measures, resampling, control, opt.path)
}
|
head(Corn, 3)
require(tidyr)
Corn2 <- Corn %>% gather(key = "treatment", value = "yield")
Corn2 %>% group_by(treatment) %>% do(head(., 3))
|
genDWD = function(X,y,C,expon, tol = 1e-5, maxIter = 2000, method = 1, printDetails = 0,
rmzeroFea = 1, scaleFea = 1){
tau = 1.618
dim = nrow(X)
n = ncol(X)
idxpos = which(y>0)
idxneg = which(y<0)
np = length(idxpos)
nn = length(idxneg)
tstart = proc.time()
nnz = sum(X@ra!=0)
if (nnz > 0.4*dim*n && dim <= 5000){
X = as.matrix(X)
}
if (rmzeroFea!=0){
normX = sqrt(rowSums(as(X*X,"dgCMatrix")))
nzrow = which(normX>0)
if (length(nzrow) < length(normX)){
if (is.matrix.csr(X)){
X = rbind(X[nzrow,1:n], 0*as.matrix.csr(1,1,n))
}
else{
X = rbind(X[nzrow,1:n], 0*rep(0,n))
}
dim = nrow(X)
}
}
if (scaleFea!=0){
DD = 1
if(dim > 0.5*n){
normX = sqrt(rowSums(as(X*X,"dgCMatrix")))
if (max(normX) > 2*min(normX)){
if (dim > 3*n){
DD = new("matrix.csr", ra = 1/pmax(1,sqrt(normX)), ja = 1:dim, ia = 1:(dim+1), dimension = c(dim,dim))
}
else{
DD = new("matrix.csr", ra = 1/pmax(1,normX), ja = 1:dim, ia = 1:(dim+1), dimension = c(dim,dim))
}
if (is.matrix.csr(X)){
X = DD %*% X
} else{
X = as.matrix(DD) %*% X
}
}
}
}
use_balanced = TRUE;
if (use_balanced){
K = n/log(n);
tmpvec = matrix(1,n,1);
tmpvec[idxpos] = matrix(nn/K,np,1)
tmpvec[idxneg] = matrix(np/K,nn,1)
weightoptions = 2
if(weightoptions == 0){
resweight = 1
penweight = 1
}
else if(weightoptions == 1){
resweight = tmpvec^(1/(2+expon))
penweight = tmpvec^(1/(2+expon))
}
else if(weightoptions == 2){
resweight = tmpvec^(1/(1+expon))
penweight = 1
}
else if(weightoptions == 3){
resweight = 1
penweight = tmpvec^(1/(2+expon))
}
resweight = resweight/max(resweight)
y = y/resweight
Cvec = C*(penweight*resweight)
}
else{
Cvec = C*matrix(1,n,1)
}
maxC = max(Cvec);
if(is.matrix.csr(X)){
Z = X %*% new("matrix.csr", ra = as.numeric(y), ja = 1:n, ia = 1:(n+1), dimension = c(n,n))
}else{
Z = X %*% diag(as.vector(y))
}
scale_data = 1
if (scale_data==1){
Zscale = sqrt(fnorm(X))
Z = Z/Zscale
sigma = min(10*C,1*n)
} else {
Zscale = 1
sigma = max(1,log(n/dim)*fnorm(X))
}
sigma = sigma^expon
sigmastart = sigma
normZ = 1+sqrt(max(colSums(as(Z*Z,"dgCMatrix"))))
r = matrix(1,n,1)
wbeta = matrix(0,dim+1,1)
u = matrix(0,dim,1)
xi = matrix(0,n,1)
alpha = matrix(0,n,1)
p = matrix(0,dim,1)
const = 1
if (dim>5000){
if (n<0.2*dim && n<=2500){
Solver = 'SMW'
} else{
Solver = 'iterative'
}
} else{
Solver = 'direct'
}
ZT = t(Z)
if (Solver == 'direct'){
if (is.matrix.csr(X)){
M1 = Z %*% ZT + const*new("matrix.csr", ra = rep(1,dim), ja = 1:dim, ia = 1:(dim+1), dimension = c(dim,dim))
M4 = as.matrix.csr(t(y) %*% y)
} else{
M1 = Z %*% ZT + const*diag(dim)
M4 = t(y) %*% y
}
M2 = Z %*% y
M3 = t(M2)
M = rbind(cbind(M1,M2),cbind(M3,M4))
if (dim > 4000){
R = chol(M,tmpmax = 1000*dim)
}else{
R = chol(M)
}
}
else if (Solver == 'SMW'){
normy = fnorm(y)
yunit = y/normy
H11 = new("matrix.csr", ra = rep(1,n), ja = 1:n, ia = 1:(n+1), dimension = c(n,n)) + (1/const)*(ZT %*% Z)
R = chol(H11)
invH11yunit = linsysolve(R,yunit)
schurmat = t(yunit) %*% invH11yunit
schurvec = c(invH11yunit, -1)
}
else if (Solver == 'iterative'){
ff = list("Z"=Z,"ZT"=ZT,"y"=y,"const"=const)
diagM = rowSums(as(Z*Z,"dgCMatrix")) + const
L = list()
L[["invdiagM"]] = 1/c(diagM,1)
L[["precond"]] = 1
}
if (printDetails!=0){
cat('\n------------------------------------------------------')
cat('--------------------------------------------------------')
cat('\n iter time sigma primfeas dualfeas')
cat(' relcomp primobj dualobj relgap');
cat(' errNewton min-r dc_meas dcmpute psqmriter trainerr')
cat('\n------------------------------------------------------')
cat('---------------------------------------------------------')
cat(sprintf('\n sample size = %3.0f, feature dimension = %3.0f',n,dim))
cat(sprintf('\n expon = %2.1f, penalty constant C = %4.2e',expon,C))
cat(sprintf('\n initial sigma = %3.2e',sigma))
cat(sprintf('\n Zscale = %3.2e',Zscale))
cat(sprintf('\n norm(scaled Z) = %3.2e',fnorm(Z)))
cat(sprintf('\n Linear system solver = %s',Solver))
cat('\n------------------------------------------------------')
cat('--------------------------------------------------------')
}
primfeas_his = c(); dualfeas_his = c()
relcomp_his = c(); trainerr_his = c()
primobj_his = c(); dualobj_his = c()
relgap_his = c(); psqmr_his = c()
Newton_his = c(); doublecompute_his = c()
breakyes = FALSE
doublecompute = 0
psqmriter = 0
rhs = matrix(0,dim+1,1)
rhsnew = matrix(0,dim+1,1)
for (iter in 1:maxIter){
rold = r; wbetaold = wbeta; uold = u
xiold = xi; alphaold = alpha; pold = p
tmp = rold - xiold + alphaold/sigma
rhs1 = as.matrix(Z %*% tmp) + const*uold + pold/sigma
rhs = rbind(rhs1,t(y) %*% tmp)
if (Solver == 'iterative'){
psqmrTol = max(min(5e-2,1/(iter^2)),1e-8)*max(1,sqrt(fnorm(rhs)))
psqmrMaxiter = 100
runpsqmr = psqmr(ff,rhs,L,wbetaold,psqmrTol,psqmrMaxiter)
wbeta = runpsqmr$x
resnrm = runpsqmr$resnrm
solve_ok = runpsqmr$solve_ok
psqmriter = psqmriter + length(resnrm) - 1
if (solve_ok != 1 && printDetails!=0){
cat(sprintf('\n iter=%2.0f: PSQMR not successful,num iter=%3.0f,residual=%3.2e',iter,length(resnrm)-1,resnrm[length(resnrm)]/fnorm(rhs)))
}
}
else if (Solver == 'direct'){
wbeta = linsysolve(R,rhs)
}
else if (Solver == 'SMW'){
wbeta = smw(R,Z,ZT,yunit,schurmat,schurvec,normy,const,rhs)
}
w = wbeta[1:dim]
beta = wbeta[dim+1]
ZTwpbetay = as.matrix(ZT %*% w) + beta*y
cc = ZTwpbetay + xiold - alphaold/sigma;
runNewton = polyRootsNewton(cc,expon,sigma,rold)
r = runNewton[1:n]
errNewton = runNewton[n+1]
iterNewton = runNewton[n+2]
r = pmax(r,0)
if(method==1){
doublecompute_measure = normZ*fnorm(r-rold)*iter^1.5
if ((doublecompute_measure > 10) || (iter < 50)){
doublecompute = doublecompute + 1
tmpnew = r - xiold + alphaold/sigma
rhsnew1 = as.matrix(Z %*% tmpnew) + const*uold + pold/sigma
rhsnew = rbind(rhsnew1,t(y) %*% tmpnew)
if (Solver == 'iterative'){
runpsqmr = psqmr(ff,rhsnew,L,wbeta,psqmrTol,psqmrMaxiter)
wbeta = runpsqmr$x
resnrm = runpsqmr$resnrm
solve_ok = runpsqmr$solve_ok
psqmriter = psqmriter + length(resnrm) - 1
if (solve_ok != 1 && printDetails!=0){
cat(sprintf('\n iter=%2.0f: PSQMR not successful,num iter=%3.0f,residual=%3.2e',iter,length(resnrm)-1,resnrm[length(resnrm)]/fnorm(rhs)))
}
}
else if (Solver == 'direct'){
wbeta = linsysolve(R,rhsnew)
}
else if (Solver == 'SMW'){
wbeta = smw(R,Z,ZT,yunit,schurmat,schurvec,normy,const,rhsnew)
}
w = wbeta[1:dim]
beta = wbeta[dim+1]
ZTwpbetay = as.matrix(ZT %*% w) + beta*y
}
}
else{
doublecompute_measure = 0;
doublecompute = 0;
}
uinput = w -pold/(const*sigma);
u = Zscale*uinput/max(Zscale,fnorm(uinput));
xiinput = r - ZTwpbetay + (alphaold-Cvec)/sigma;
xi = pmax(as.vector(xiinput),0);
Rp = ZTwpbetay +xi-r;
alpha = alphaold -tau*sigma*Rp;
p = pold -(tau*sigma*const)*(w-u);
rexpon1 = r^(expon+1);
comp1 = abs(t(y) %*% alpha)
comp2 = abs(t(xi) %*% (Cvec-alpha));
comp3 = min(fnorm(alpha*rexpon1-expon),fnorm(alpha-expon/rexpon1)^2);
relcomp = max(comp1,comp2,comp3)/(1+maxC);
primfeas = max(fnorm(Rp),fnorm(w-u),max(fnorm(w)-Zscale,0))/(1+maxC);
dualfeas = max(fnorm(pmin(0,alpha)),fnorm(pmax(alpha-Cvec,0)))/(1+maxC);
trainerr = length(which(ZTwpbetay<=0))/n*100;
if (((max(primfeas,dualfeas) < tol) && (iter%%20==1)) || (iter%%100==1)){
primobj1 = sum(r/rexpon1)
primobj2 = sum(Cvec*xi)+1e-8
primobj = primobj1 + primobj2
kappa = ((expon+1)/expon)*expon^(1/(expon+1));
dualobj = kappa*sum(pmax(0,alpha)^(expon/(expon+1)))-Zscale*fnorm(as.matrix(Z %*% alpha))
relgap = abs(primobj-dualobj)/(1+abs(primobj)+abs(dualobj))
}
tol2 = 0.1/2
if ((iter > 50) && (max(primfeas,dualfeas) < tol) && (min(relcomp,relgap) < sqrt(tol)) && (((relcomp < tol2) && (relgap < sqrt(tol))) || (((relcomp < sqrt(tol)) && (relgap < tol2))))){
KKTerr = max(max(primfeas,dualfeas),min(relcomp,relgap))
breakyes = 1
cat(sprintf('\n Algorithm stopped with error %3.2e',KKTerr))
}
if ((iter > 50) && (max(primfeas,dualfeas) < 5*tol) && (min(relcomp,relgap) < 10*tol) && (((relcomp < tol2) && (relgap < sqrt(tol))) || (((relcomp < sqrt(tol)) && (relgap < tol2))))){
KKTerr = max(max(primfeas,dualfeas),min(relcomp,relgap))
breakyes = 2
cat(sprintf('\n Algorithm stopped with error %3.2e',KKTerr))
}
if ((iter > 50) && (max(primfeas,dualfeas) < tol) && (fnorm(alpha)/(1+maxC) < 1e-3)){
KKTerr = max(max(primfeas,dualfeas),min(relcomp,relgap))
breakyes = 3
cat(sprintf('\n Algorithm stopped with error %3.2e',KKTerr))
}
if (iter <= 100){
print_iter = 20
}else{
print_iter = 100
}
if ((iter%%print_iter==1) || (breakyes>0)){
ttime = as.numeric((proc.time()-tstart)[3])
if (printDetails!=0){
cat(sprintf('\n%4.0f| %6.2f| %3.2e| %3.2e %3.2e %3.2e| %5.4e %5.4e %3.2e| %3.2e %3.2e| %3.2e %3.0f| %5.0f %4.2f|',iter,ttime,sigma,primfeas,dualfeas,relcomp,primobj,dualobj,relgap,errNewton,min(r),doublecompute_measure,doublecompute,psqmriter,trainerr));
cat(sprintf(' %3.2e',fnorm(alpha)/(1+maxC)))
}
}
primfeas_his = c(primfeas_his,primfeas)
dualfeas_his = c(dualfeas_his,dualfeas)
relcomp_his = c(relcomp_his,relcomp)
trainerr_his = c(trainerr_his,trainerr)
primobj_his = c(primobj_his,primobj)
dualobj_his = c(dualobj_his,dualobj)
relgap_his = c(relgap_his,relgap)
psqmr_his = c(psqmr_his,psqmr)
Newton_his = c(Newton_his,iterNewton)
doublecompute_his = c(doublecompute_his,doublecompute)
sigma_update_iter = sigma_update(iter);
if (iter%%sigma_update_iter==0){
primfeas2 = max(primfeas,0.2*tol);
dualfeas2 = max(dualfeas,0.2*tol);
ratio = primfeas2/dualfeas2;
const2 = 1.1;
if (max(ratio,1/ratio) > 500){
const2 = const2*2;
}
else if (max(ratio,1/ratio) > 50){
const2 = const2*1.5;
}
if (ratio > 5){
sigma = min(sigma*const2,1e6);
}
else if (1/ratio > 5){
sigma = max(sigma/const2,1e-3);
}
}
if (breakyes){
cat('\n')
break;
}
}
Zalpha = as.matrix(Z %*% alpha)
w = w/Zscale;
res = t(X) %*% w + beta*as.matrix.csr(1,n,1)
error = length(which(y*sign(res@ra)<=0))/n*100
cat(sprintf('\n sample size = %3.0f, feature dimension = %3.0f',n,dim));
cat(sprintf('\n positve sample = %3.0f, negative sample = %3.0f',np,nn));
cat(sprintf('\n number of iterations = %3.0f',iter));
cat(sprintf('\n time taken = %3.2f',ttime));
cat(sprintf('\n error of classification (training) = %3.2f (%%)',error))
cat(sprintf('\n primfeas = %3.2e',primfeas));
cat(sprintf('\n dualfeas = %3.2e',dualfeas));
cat(sprintf('\n relative gap = %3.2e\n',relgap));
runhist = list("primfeas"=primfeas_his, "dualfeas"=dualfeas_his, "relcomp" = relcomp_his, "trainerr"=trainerr_his, "primobj"=primobj_his, "dualobj"=dualobj_his, "relgap"=relgap_his, "Newton"=Newton_his, "doublecompute"=doublecompute_his)
info = list("iter"=iter,"time"=ttime,"penaltyParameter"=C,"sampsize"=n,"np" = np, "nn"=nn, "dimension"=dim, "sigmastart"=sigmastart, "primfeas"=primfeas, "dualfeas"=dualfeas, "relcomp"=relcomp, "relgap"=relgap, "primobj"=primobj, "dualobj"=dualobj, "trainerr"=trainerr, "psqmr"=psqmriter,"doublecompute"=doublecompute);
return(list("w"=w,"beta"=beta,"xi"=xi,"r"=r,"alpha"=alpha,"info"=info,"runhist"=runhist))
}
sigma_update = function(iter){
const = 0.5
if (iter <= 25){
sigma_update_iter = 10*const
}
else if (iter <= 50){
sigma_update_iter = 20*const
}
else if (iter <= 100){
sigma_update_iter = 40*const
}
else if (iter <= 500){
sigma_update_iter = 60*const
}
else if (iter <= 1000){
sigma_update_iter = 80*const
}
else{
sigma_update_iter = 100
}
return(sigma_update_iter)
}
linsysolve = function(R,r){
if(is.matrix(R)){
x = backsolve(R,forwardsolve(t(R),r))
}else{
x = backsolve(R,r)
}
return(x)
}
smw = function(R,Z,ZT,yunit,schurmat,schurvec,normy,const,r){
n = length(yunit)
dim = length(r) - 1
b1 = (1/const)*as.matrix(ZT %*% r[1:dim]) + (r[dim+1]/normy)*yunit
b2 = r[dim+1]/normy
b = rbind(b1,b2)
tmpvec = (t(schurvec) %*% b/schurmat) %*% schurvec
a1 = backsolve(R,b1) - tmpvec[1:n]
a2 = -b2 - tmpvec[n+1]
q = matrix(0,dim+1,1)
q[1:dim] = (1/const)*(as.matrix(Z %*% (-a1)) + r[1:dim])
q[dim+1] = (1/normy)*(r[dim+1]/normy - t(yunit)%*%a1 - a2)
return (q)
}
fnorm = function(x){
if (typeof(x) == "S4"){
xentry = x@ra
return (sqrt(sum(xentry * xentry)))
}else{
return (sqrt(sum(x*x)))
}
}
polyRootsNewton = function(c,q,sigma,x0){
tol = 1e-12
x = x0
d = q/sigma; cq1 = c*(q+1); q2 = q+2;
maxiter = 50
if (q == 1){
for (iter in 1:maxiter){
idx = which(x<=0);
if (length(idx)!=0){
x[idx]=max(0,0.5+c[idx])
}
xq1 = x*x
xq = x
grad = xq1*(x-c)-d
hess = xq*(q2*x - cq1)
x = x-grad/hess
err = max(abs(grad))
if (err<tol){
break
}
}
}
else if (q == 2){
for (iter in 1:maxiter){
idx = which(x<=0);
if (length(idx)!=0){
x[idx]=max(0,0.5+c[idx])
}
xq = x*x
xq1 = xq*x
grad = xq1*(x-c)-d
hess = xq*(q2*x-cq1)
x = x - grad/hess
err = max(abs(grad))
if (err<tol){
break
}
}
}
else if (q == 3){
for (iter in 1:maxiter){
idx = which(x<=0);
if (length(idx)!=0){
x[idx]=max(0,0.5+c[idx])
}
x2 = x*x
xq = x2*x
xq1 = x2*x2
grad = xq1*(x-c)-d
hess = xq*(q2*x-cq1)
x = x - grad/hess
err = max(abs(grad))
if (err<tol){
break
}
}
}
else if (q == 4){
for (iter in 1:maxiter){
idx = which(x<=0);
if (length(idx)!=0){
x[idx]=max(0,0.5+c[idx])
}
x2 = x*x
xq = x2*x2
xq1 = xq*x
grad = xq1*(x-c)-d
hess = xq*(q2*x-cq1)
x = x - grad/hess
err = max(abs(grad))
if (err<tol){
break
}
}
}
return(rbind(x,err,iter))
}
psqmr = function(ff,b,L,x0,tol,maxit){
N = length(b)
if (!exists('maxit')) maxit = max(1000,sqrt(length(b)))
if (!exists('tol')) tol = 1e-8*fnorm(b)
if (!exists('L')) L[["precond"]] = 0
if (!exists('x0')) x0 = matrix(0,N,1)
solve_ok = 1
stagnate_check = 20*1
miniter = 0
printlevel = FALSE
x = x0
if (fnorm(x) > 0){
Aq = vecMultiply(ff,x)
}else{
Aq = matrix(0,N,1)
}
r = b - Aq
err = fnorm(r)
resnrm = err
minres = err
q = precondfun(L,r)
tau_old = fnorm(q)
rho_old = as.numeric(t(r) %*% q)
theta_old = 0
d = matrix(0,N,1)
res = r
Ad = matrix(0,N,1)
tiny = 1e-30
for (iter in 1:maxit){
Aq = vecMultiply(ff,q)
sigma = as.numeric(t(q) %*% Aq)
if (abs(sigma) < tiny){
solve_ok = 2
if (printlevel) cat('s1')
break
}else{
alpha = rho_old/sigma
r = r - alpha*Aq
}
u = precondfun(L,r)
theta = fnorm(u)/tau_old
c = 1/sqrt(1+theta^2)
tau = tau_old*theta*c
gam = (c^2*theta_old^2)
eta = c^2*alpha
d = gam*d + eta*q
x = x + d
Ad = gam*Ad + eta*Aq
res = res - Ad
err = fnorm(res)
resnrm = c(resnrm,err)
if (err < minres) minres = err
if ((err < tol) && (iter > miniter) && (t(b) %*% x > 0)) break
if ((iter > stagnate_check) && (iter > 10)){
ratio = resnrm[(iter-9):(iter+1)]/resnrm[(iter-10):iter]
if ((min(ratio) > 0.997) && (max(ratio) < 1.003)){
if (printlevel) cat('s')
solve_ok = -1
break
}
}
if (abs(rho_old) < tiny){
solve_ok = 2
cat('s2')
break
}else{
rho = as.numeric(t(r) %*% u)
beta = rho/rho_old
q = u + beta*q
}
rho_old = rho
tau_old = tau
theta_old = theta
}
if (iter == maxit) solve_ok = -2
if (solve_ok != -1){
if (printlevel) cat(' ')
}
return (list("x"=x,"resnrm"=resnrm,"solve_ok"=solve_ok))
}
precondfun = function(L,r){
precond = L$precond
if (precond == 0){
q = r
}
else if (precond == 1){
q = L$invdiagM * r
}
else if (precond == 2){
q = backsolve(L$R,r)
}
return(q)
}
vecMultiply = function(ff,x){
Z = ff$Z
ZT = ff$ZT
y = ff$y
const = ff$const
d = length(x) - 1
w = x[1:d]; beta = x[d+1]
tmp = as.matrix(ZT %*% w) + beta*y
Aq = matrix(0,d+1,1)
Aq[1:d] = as.matrix(Z %*% tmp) + const*w
Aq[d+1] = t(y) %*% tmp
return (Aq)
}
|
nb.theta<-function (par, a, w, x, y, offset, beta) {
b<- par
if (!is.null(offset)) {
Xb <- cbind(offset, w, x) %*% c(1, b, beta)
} else {
Xb <- cbind(w, x) %*% c(b, beta)
}
contri.LL<- y*log((a*exp(Xb))/(1+ (a*exp(Xb)))) -(1/a)*log(1+ (a*exp(Xb))) + lgamma(y+ (1/a)) - lgamma(y+1) - lgamma(1/a)
loglik <- sum(contri.LL)
-loglik
}
|
library(tidymodels)
library(lubridate)
get_date <- function(x) {
x <- basename(x)
x <- strsplit(x, "_")
x <- map(x, ~ .x[3:8])
x <- map(x, ~ gsub("\\.RData", "", .x))
x <- map_chr(x, paste0, collapse = "-")
ymd_hms(x)
}
get_times <- function(x) {
load(x)
res <-
times %>%
mutate(date = get_date(x))
res
}
rdata <-
list.files(path = "extras/parallel_times/",
pattern = "\\.RData",
full.names = TRUE)
rdata <- rdata[!grepl("xgb_times", rdata)]
rdata <- rdata[!grepl("logging_data", rdata)]
all_times <- map_dfr(rdata, get_times)
seq <-
all_times %>%
filter(num_cores == 1) %>%
dplyr::rename(seq_time = elapsed) %>%
select(-num_cores, -date)
times <-
full_join(all_times, seq,
by = c("num_resamples", "num_grid", "preproc", "par_method")) %>%
mutate(
time_per_fit = elapsed/(num_grid * num_resamples),
speed_up = seq_time/elapsed,
preprocessing = gsub(" preprocessing", "", preproc),
preprocessing = ifelse(preprocessing == "no", "none", preprocessing),
preprocessing = factor(preprocessing, levels = c("none", "light", "expensive")),
parallel_over = par_method
)
if (interactive()) {
ggplot(times, aes(x = num_cores, y = elapsed, col = parallel_over, shape = parallel_over)) +
geom_point() +
geom_line() +
facet_wrap(~ preprocessing) +
labs(x = "Number of Workers", y = "Execution Time (s)") +
scale_y_log10() +
theme_bw() +
theme(legend.position = "top")
times %>%
filter(preprocessing == "none") %>%
ggplot(aes(x = num_cores, y = speed_up, col = preprocessing, shape = preprocessing)) +
geom_abline(lty = 1) +
geom_point() +
geom_line() +
facet_wrap(~ par_method) +
coord_obs_pred() +
labs(x = "Number of Workers", y = "Speed-up",
title = "5 resamples, 10 grid points") +
theme_bw() +
theme(legend.position = "top")
times %>%
filter(preprocessing != "expensive") %>%
ggplot(aes(x = num_cores, y = speed_up, col = preprocessing, shape = preprocessing)) +
geom_abline(lty = 1) +
geom_point() +
geom_line() +
facet_wrap(~ par_method) +
coord_obs_pred() +
labs(x = "Number of Workers", y = "Speed-up",
title = "5 resamples, 10 grid points") +
theme_bw() +
theme(legend.position = "top")
ggplot(times, aes(x = num_cores, y = speed_up, col = parallel_over, shape = parallel_over)) +
geom_abline(lty = 1) +
geom_point() +
geom_line() +
facet_wrap(~ preprocessing) +
coord_obs_pred() +
labs(x = "Number of Workers", y = "Speed-up",
title = "5 resamples, 10 grid points") +
theme_bw() +
theme(legend.position = "top")
}
save(times, file = "extras/parallel_times/xgb_times.RData")
q("no")
|
confint.expectreg <-
function(object, parm=NULL, level=0.95,...)
{
if(is.null(object$covmat))
stop("No covariance matrix calculated.")
res = list()
if(any(object$design[,1] != 1))
center = FALSE
else
center = TRUE
if(is.null(parm))
for(i in 1:length(object$asymmetries))
{
res[[i]] = matrix(NA,nrow=nrow(object$design),ncol=2)
colnames(res[[i]]) = c(paste(eval((1-level)/2),"%"),paste(eval((1+level)/2),"%"))
for(j in 1:nrow(object$design))
{
deviation = qnorm((1+level)/2) * sqrt(t(object$design[j,]) %*% object$covmat[[i]] %*% object$design[j,])
res[[i]][j,] = c(fitted(object)[j,i] - deviation, fitted(object)[j,i] + deviation)
}
}
else
{
nb = NULL
for(i in 1:length(object$coefficients))
nb = c(nb,nrow(object$coefficients[[i]]))
PB = NULL
Koff = NULL
for(k in 1:length(parm))
{
co = which(names(object$covariates) == parm[k])
partbasis = (sum(nb[0:(co-1)])+1):(sum(nb[0:co]))
if(center)
partbasis = partbasis+1
PB = c(PB,partbasis)
Koff = rbind(Koff,object$coefficients[[co]])
}
if(center)
{
PB = c(1,PB)
Koff = rbind(object$intercept,Koff)
}
B = object$design[,PB,drop=FALSE]
fitti = B %*% Koff
for(i in 1:length(object$asymmetries))
{
res[[i]] = matrix(NA,nrow=nrow(B),ncol=2)
colnames(res[[i]]) = c(paste(eval((1-level)/2),"%"),paste(eval((1+level)/2),"%"))
for(j in 1:nrow(B))
{
deviation = qnorm((1+level)/2) * sqrt(t(B[j,]) %*% object$covmat[[i]][PB,PB] %*% B[j,])
res[[i]][j,] = c(fitti[j,i] - deviation, fitti[j,i] + deviation)
}
}
}
res
}
|
test_that("bq_perform_upload creates job that succeeds", {
ds <- bq_test_dataset()
bq_mtcars <- bq_table(ds, "mtcars")
job <- bq_perform_upload(bq_mtcars, mtcars)
expect_s3_class(job, "bq_job")
expect_message(bq_job_wait(job, quiet = FALSE), "Input")
expect_message(bq_job_wait(job, quiet = FALSE), "Output")
expect_true(bq_table_exists(bq_mtcars))
})
test_that("bq_perform_copy creates job that succeeds", {
ds <- bq_test_dataset()
src <- as_bq_table("bigquery-public-data.moon_phases.moon_phases")
dst <- bq_table(ds, "my_moon")
job <- bq_perform_copy(src, dst)
expect_s3_class(job, "bq_job")
expect_message(bq_job_wait(job, quiet = FALSE), "Complete")
expect_true(bq_table_exists(dst))
})
test_that("can round trip extract + load", {
ds_public <- bq_dataset("bigquery-public-data", "moon_phases")
ds_mine <- bq_test_dataset()
tb <- bq_dataset_query(ds_public,
query = "SELECT COUNT(*) as count FROM moon_phases",
billing = bq_test_project()
)
tmp <- gs_test_object()
job <- bq_perform_extract(tb, tmp)
bq_job_wait(job)
tb_ks <- bq_table(ds_mine, "natality_ks")
job <- bq_perform_load(tb_ks, tmp)
bq_job_wait(job)
df <- bq_table_download(tb_ks)
expect_equal(nrow(df), 1)
expect_named(df, "count")
})
test_that("bq_perform_query creates job that succeeds", {
ds <- as_bq_dataset("bigquery-public-data.moon_phases")
job <- bq_perform_query(
"SELECT count(*) FROM moon_phases",
billing = bq_test_project(),
default_dataset = ds
)
expect_s3_class(job, "bq_job")
expect_message(bq_job_wait(job, quiet = FALSE), "Billed")
job_tb <- bq_job_table(job)
expect_true(bq_table_exists(job_tb))
})
test_that("can supply scalar parameters", {
job <- bq_project_query(
bq_test_project(),
"SELECT 1 + @x",
parameters = list(x = bq_param_scalar(1))
)
df <- bq_table_download(job)
expect_setequal(df[[1]], 2)
})
test_that("can supply array parameters", {
job <- bq_project_query(
bq_test_project(),
"SELECT values FROM UNNEST(@x) values",
parameters = list(x = bq_param_array(c("a", "b")))
)
df <- bq_table_download(job)
expect_setequal(df$values, c("a", "b"))
})
test_that("can estimate cost", {
cost <- bq_perform_query_dry_run(
"SELECT count(*) FROM bigquery-public-data.moon_phases.moon_phases",
billing = bq_test_project()
)
expect_equal(cost, structure(0, class = "bq_bytes"))
})
|
summary.tegarch <-
function(object, verbose=FALSE, ...)
{
if(verbose){
out <- object[-1]
}else{
if(is.null(object$hessian)){
out <- object[-c(1,3:7)]
}else{
out <- object[-c(1,3:8)]
}
}
return(out)
}
|
install.packages("devtools");install.packages("RJSONIO")
library(devtools);library(RJSONIO)
install_github(repo = "CTSgetR", username = "dgrapov")
library(CTSgetR)
install_github(repo = "CIRgetR", username = "dgrapov")
library(CIRgetR)
id<-c("ZKHQWZAMYRWXGA-KQYNXXCUSA-N", "BAWFJGJZGIEFAR-NNYOXOHSSA-O","QNAYBMKLOCPYGJ-REOHCLBHSA-N")
write.csv(data.frame(InchiKey=id),file="InchIKeys.csv",row.names=FALSE)
id<-read.csv(file="InchIKeys.csv",header=TRUE)
results<-CIRgetR(id,to= "chemspider_id",return.all=FALSE)
results2<-CTSgetR(id,from="InChIKey",to="ChemSpider",parallel=FALSE)
miss.match<-!as.matrix(results2)%in%as.matrix(results)|!as.matrix(results)%in%as.matrix(results2)
paste(sum(miss.match),"difference(s) between results",sep=" ")
data.frame(CIR= results[,1], CTS = results2[,1])[miss.match,]
CSid<-results[miss.match,]
results3<-CTSgetR(CSid,from="ChemSpider",to="InChIKey",parallel=FALSE)
<<<<<<< HEAD
if(as.matrix(results3)==as.matrix(id[miss.match,,drop=FALSE]))cat("codes match!","\n") else cat("codes DO NOT match!","\n")
=======
if(results3==id[miss.match])cat("codes match!","\n") else cat("codes DO NOT match!","\n")
>>>>>>> 527fe4c248ad2040b68cecee54e55a80e05bade5
CIR.options<-c("smiles", "names", "iupac_name", "cas", "inchi", "stdinchi", "inchikey", "stdinchikey",
"ficts", "ficus", "uuuuu", "image", "file", "mw", "monoisotopic_mass","chemspider_id",
"pubchem_sid", "chemnavigator_sid", "formula", "chemnavigator_sid")
all.results.CIR<-sapply(1:length(CIR.options), function(i)
{
cat(CIR.options[i],"\n")
CIRgetR(id=id,to=CIR.options[i],return.all=FALSE)
})
names(all.results.CIR)<-CIR.options
all.results.CIR<-data.frame(all.results.CIR )
CTS.options<-CTS.options()
CTS.options
id<-results2
all.results.CTS<-sapply(1:length(CTS.options), function(i)
{
cat(CTS.options[i],"\n")
CTSgetR(id=id,to=CTS.options[i],from="ChemSpider")
})
names(all.results.CTS)<-CTS.options
all.results.CTS<-data.frame(all.results.CTS)
CIR.error<-round(((sum(unlist(all.results.CIR)=="<h1>Page not found (404)</h1>")/length(unlist(id))))/length(CIR.options)*100,0)
CTS.error<-round((sum(unlist(all.results.CTS)=="error")/length(unlist(id)))/length(CTS.options)*100,0)
data.frame(CIR.error=CIR.error,CTS.error=CTS.error)
<<<<<<< HEAD
best<-c("all.results.CIR","all.results.CTS")[which.min(c(CIR.error,CTS.error))[1]]
cat("Best results: ",best, "\n")
=======
best<-c("all.results.CIR","all.results.CTS")[which.min(c(CIR.error,CST.error))[1]]
>>>>>>> 527fe4c248ad2040b68cecee54e55a80e05bade5
write.csv(get(best),file="best translation.csv")
<<<<<<< HEAD
id<-"ZKHQWZAMYRWXGA-KQYNXXCUSA-N"
image.url<-as.character(unlist(CIRgetR(id,to= "image",return.all=FALSE) ))
download.file(image.url,"image.gif")
install.packages("caTools")
library(caTools)
gif <- read.gif(image.url, verbose = TRUE, flip = TRUE)
par(pin=c(2,2))
=======
download.file("http://cactus.nci.nih.gov/chemical/structure/ZKHQWZAMYRWXGA-KQYNXXCUSA-N/image","image.gif")
install.packages("caTools")
library(caTools)
gif <- read.gif(image.url, verbose = TRUE, flip = TRUE)
par(pin=c(2,2))
>>>>>>> 527fe4c248ad2040b68cecee54e55a80e05bade5
image(gif$image, col = gif$col, main = gif$comment, frame.plot=FALSE,xaxt="n", yaxt="n")
|
"beta"
|
msl.fileplot <- function(x, resol = 1800, wdir = " ", file_name = " ", type = 1,
ci = 1, header = TRUE) {
object <- x
summ <- object$Summary
graphics.off()
if (class(object) == "msl.trend" | class(object) == "custom.trend") {
class(object) <- class(object)
} else {
stop("object is not an msl.trend or custom.trend object: plotting terminated")
}
if (wdir == " ") {
stop("User must input a directory to send plot file: plotting terminated")
} else {
wdir <- wdir
}
if (header == TRUE | header == FALSE) {
header <- header
} else {
print("default header setting applied")
header <- TRUE
}
if (any(is.na(summ$MSL)) == TRUE) {
p <- 0
} else {
p <- 1
}
n <- length(summ[, 1])
n2 <- n - 3
summ2 <- summ[4:n2, ]
if (type == 1 | type == 2 | type == 3 | type == 4 | type == 5) {
type <- type
} else {
print("default type (3 Panel) setting applied")
type <- 1
}
if (ci == 1 | ci == 2) {
ci <- ci
} else {
print("default 95% CONFIDENCE INTERVAL setting applied")
ci <- 1
}
if (ci == 2) {
ci = 2.575
lab1 <- paste("99% Confidence Interval")
} else {
ci = 1.96
lab1 <- paste("95% Confidence Interval")
}
if (resol >= 300 && resol <= 1800) {
resol <- resol
} else {
print("default resolution setting (1800 dpi) applied")
resol <- 1800
}
if (file_name == " ") {
file_name <- "Plot1.jpeg"
print("output can be found in defined directory as Plot1.jpeg")
} else {
file_name <- paste0(file_name,".jpeg")
}
if (object$Vertical.Land.Motion$mm.yr == "NA") {
p2 <- 0
} else {
p2 <- 1
labe <- paste0("Vertical Land Motion = ",
object$Vertical.Land.Motion$mm.yr, " mm/year")
}
if (summ$Trend[n] - summ$Trend[1] < 0) {
laba = paste("topright")
labb = paste("bottomleft")
} else {
laba = paste("topleft")
labb = paste("bottomright")
}
if (requireNamespace("plyr", quietly = TRUE)) {
plyr::round_any
}
if (n < 100) {
xtic = 10
xlo <- plyr::round_any(min(summ[, 1]), 10, floor)
xhi <- plyr::round_any(max(summ[, 1]), 10, ceiling)
} else {
xtic = 20
xlo <- plyr::round_any(min(summ[, 1]), 20, floor)
xhi <- plyr::round_any(max(summ[, 1]), 20, ceiling)
}
xlim = c(xlo, xhi)
if (type == 1) {
if (header == TRUE) {
out <- c(4.1, 5.5, 2.1, 0.2)
} else {
out <- c(4.1, 5.5, 0.2, 0.2)
}
grDevices::jpeg(file.path(wdir, file_name), width = 160, height = 210, units = "mm",
res = resol)
opar <- par(no.readonly = TRUE)
on.exit(par(opar))
par(mfrow = c(3, 1), las = 1)
par(oma = out)
par(mar = c(0,0,0,0), las = 1)
ylen <- max(summ[, 2], na.rm = TRUE) - min(summ[, 2], na.rm = TRUE)
if (ylen < 200) {
ytic = 20
ylo <- plyr::round_any(min(summ[, 2], na.rm = TRUE), 20, floor)
yhi <- plyr::round_any(max(summ[, 2], na.rm = TRUE), 20, ceiling)
} else {
ytic = 50
ylo <- plyr::round_any(min(summ[, 2], na.rm = TRUE), 50, floor)
yhi <- plyr::round_any(max(summ[, 2], na.rm = TRUE), 50, ceiling)
}
ylim = c(ylo, yhi)
plot(summ[, 1], summ[, 2], type = "n", axes = F, lty = 0, xlim = xlim,
ylim = ylim, xlab = NA, ylab = NA)
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4],
col = "lightcyan1")
graphics::box()
polygon(c(summ[, 1], rev(summ[, 1])),
c((summ[, 3] + ci * summ[, 4]), rev((summ[, 3] - ci * summ[, 4]))),
col = "azure3", border = NA)
title(ylab = "Millimetres", outer = TRUE, font.lab = 2, cex.lab = 1.3,
line = 3.9, adj = 0.87)
axis(side = 2, tck = -0.025, at = seq(ylo, yhi, by = ytic), outer = TRUE,
labels = NA)
axis(side = 2, at = seq(ylo, yhi, by = ytic), cex.axis = 1.1)
if (p == 0) {
lines(summ[, 1], summ[, 10], col = "red")
lines(summ[, 1], summ[, 2])
lines(summ[, 1], summ[, 3], lwd = 2)
legend(laba, legend = "Relative Mean Sea Level (MSL)",
inset = c(-0.02, -0.01), bty = "n", text.font = 2, cex = 1.4)
legend(labb, bg = "white",
legend = c("KEY", "Annual Average Data", "Gap Filling",
"MSL Trend", lab1, "Peak Rate"),
text.font = c(2, 1, 1, 1, 1, 1), lty = c(0, 1, 1, 1, 1, 3),
lwd = c(1, 1, 1, 3, 8, 2),
col = c("black", "black", "red", "black", "azure3", "blue"),
cex = c(0.9, 0.9, 0.9, 0.9, 0.9, 0.9))
}
if (p == 1) {
lines(summ[, 1], summ[, 2])
lines(summ[, 1], summ[, 3], lwd = 2)
legend(laba, legend = "Relative Mean Sea Level (MSL)", inset = c(-0.02, -0.01),
bty = "n", text.font = 2, cex = 1.4)
legend(labb, bg = "white",
legend = c("KEY", "Annual Average Data", "MSL Trend", lab1,
"Peak Rate"), text.font = c(2, 1, 1, 1, 1),
lty = c(0, 1, 1, 1, 3), lwd = c(1, 1, 3, 8, 3),
col = c("black", "black", "black", "azure3", "blue"),
cex = c(0.9, 0.9, 0.9, 0.9, 0.9))
}
par(mar = c(0, 0, 0, 0), las = 1)
minV <- min((summ[, 5] - ci * summ[, 6]), summ$VelGeo, na.rm = TRUE)
maxV <- max((summ[, 5] + ci * summ[, 6]), summ$VelGeo, na.rm = TRUE)
ylen <- maxV - minV
if (ylen <= 1) {
ytic = 0.1
ylo <- plyr::round_any(minV - ylen * 0.15, 0.1, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 0.1, ceiling)
}
if (ylen > 1 & ylen <= 2) {
ytic = 0.2
ylo <- plyr::round_any(minV - ylen * 0.15, 0.2, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 0.2, ceiling)
}
if (ylen > 2 & ylen <= 5) {
ytic = 0.5
ylo <- plyr::round_any(minV - ylen * 0.15, 0.5, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 0.5, ceiling)
}
if (ylen > 5 & ylen <= 10) {
ytic = 1
ylo <- plyr::round_any(minV - ylen * 0.15, 1, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 1, ceiling)
}
if (ylen > 10) {
ytic = 2
ylo <- plyr::round_any(minV - ylen * 0.15, 2, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 2, ceiling)
}
ylim = c(ylo, yhi)
plot(summ[, 1], summ[, 5], type = "n", axes = F, lty = 0, xlim = xlim,
ylim = ylim, xlab = NA, ylab = NA)
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4],
col = "lightcyan1")
graphics::box()
polygon(c(summ[, 1], rev(summ[, 1])), c((summ[, 5] + ci * summ[, 6]),
rev((summ[, 5] - ci * summ[, 6]))),
col = "azure3", border = NA)
lines(summ[, 1], summ[, 5], lwd = 2)
abline(h = 0, lty = 2)
abline(h = max(summ[, 5]), lty = 3, col = "blue", lwd = 2)
if (p2 == 0) {
legend("topleft", legend = "Relative Velocity (MSL)", inset = c(-0.02, -0.01),
bty = "n", text.font = 2, cex = 1.4)
} else {
legend("topleft", legend = "Velocity (MSL)", inset = c(-0.02, -0.01),
bty = "n", text.font = 2, cex = 1.4)
legend("bottomleft", legend = labe, inset = c(-0.005, -0.005),
bty = "n", text.font = 1, cex = 1.0)
legend("bottomright", bg = "white",
legend = c("KEY", "Relative Velocity", "Geocentric Velocity"),
text.font = c(2, 1, 1),
lty = c(0, 1, 1),
lwd = c(1, 3, 3),
col = c("black", "black", "red"),
cex = c(0.9, 0.9, 0.9))
lines(summ[, 1], summ$VelGeo, lwd = 2, col = "red")
}
title(ylab = "Millimetres/yr", outer = TRUE, font.lab = 2, cex.lab = 1.3,
line = 3.9, adj = 0.5)
axis(side = 2, tck = -0.025, at = seq(ylo, yhi, by = ytic), outer = TRUE,
labels = NA)
axis(side = 2, at = seq(ylo, yhi, by = ytic), cex.axis = 1.1)
par(mar = c(0, 0, 0, 0), las = 1)
ylen <- max(summ2[, 7] + ci * summ2[, 8]) - min(summ2[, 7] - ci * summ2[, 8])
if (ylen <= 0.1) {
ytic = 0.01
ylo <- plyr::round_any(min(summ2[, 7] - ci * summ2[, 8]) - ylen * 0.15,
0.01, floor)
yhi <- plyr::round_any(max(summ2[, 7] + ci * summ2[, 8]) + ylen * 0.15,
0.01, ceiling)
}
if (ylen > 0.1 & ylen <= 0.2) {
ytic = 0.02
ylo <- plyr::round_any(min(summ2[, 7] - ci * summ2[, 8]) - ylen * 0.15,
0.02, floor)
yhi <- plyr::round_any(max(summ2[, 7] + ci * summ2[, 8]) + ylen * 0.15,
0.02, ceiling)
}
if (ylen > 0.2 & ylen <= 0.5) {
ytic = 0.05
ylo <- plyr::round_any(min(summ2[, 7] - ci * summ2[, 8]) - ylen * 0.15,
0.05, floor)
yhi <- plyr::round_any(max(summ2[, 7] + ci * summ2[, 8]) + ylen * 0.15,
0.05, ceiling)
}
if (ylen > 0.5 & ylen <= 1) {
ytic = 0.1
ylo <- plyr::round_any(min(summ2[, 7] - ci * summ2[, 8]) - ylen * 0.15,
0.1, floor)
yhi <- plyr::round_any(max(summ2[, 7] + ci * summ2[, 8]) + ylen * 0.15,
0.1, ceiling)
}
if (ylen > 1) {
ytic = 0.2
ylo <- plyr::round_any(min(summ2[, 7] - ci * summ2[, 8]) - ylen * 0.15,
0.2, floor)
yhi <- plyr::round_any(max(summ2[, 7] + ci * summ2[, 8]) + ylen * 0.15,
0.2, ceiling)
}
ylim = c(ylo, yhi)
plot(summ2[, 1], summ2[, 7], type = "n", axes = F, lty = 0, xlim = xlim,
ylim = ylim, xlab = NA, ylab = NA)
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4],
col = "lightcyan1")
graphics::box()
polygon(c(summ2[, 1],
rev(summ2[, 1])), c((summ2[, 7] + ci * summ2[, 8]),
rev((summ2[, 7] - ci * summ2[, 8]))),
col = "azure3", border = NA)
lines(summ2[, 1], summ2[, 7], lwd = 2)
abline(h = 0, lty = 2)
abline(h = max(summ2[, 7]), lty = 3, col = "blue", lwd = 2)
legend("topleft", legend = "Acceleration (MSL)",
inset = c(-0.02, -0.01), bty = "n", text.font = 2, cex = 1.4)
title(ylab = expression(paste(bold("Millimetres/yr" ^ "2"))), outer = TRUE,
font.lab = 2, cex.lab = 1.3, line = 3.9, adj = 0.12)
title(xlab = "Year", outer = TRUE, font.lab = 2, cex.lab = 1.3, line = 2.6)
axis(side = 1, tck = -0.030, at = seq(xlo, xhi, by = xtic), outer = TRUE,
labels = NA)
axis(side = 1, at = seq(xlo, xhi, by = xtic), outer = TRUE, lwd = 0, line = 0.1,
cex.axis = 1.1)
axis(side = 2, tck = -0.025, at = seq(ylo, yhi, by = ytic), outer = TRUE,
labels = NA)
axis(side = 2, at = seq(ylo, yhi, by = ytic), cex.axis = 1.1)
graphics::mtext(object$Station.Name, side = 3, outer = TRUE, font = 2,
line = 0.35, cex = 1.2, adj = 0.5)
graphics::par(opar)
grDevices::dev.off()
}
if (type == 2) {
if (header == TRUE) {
out <- c(2.6, 4.0, 1.5, 0.2)
} else {
out <- c(2.6, 4.0, 0.2, 0.2)
}
grDevices::jpeg(file.path(wdir, file_name), width = 160, height = 80, units = "mm", res = resol)
opar <- par(no.readonly = TRUE)
on.exit(par(opar))
par(oma = out)
par(mar = c(0,0,0,0), las = 1)
ylen <- max(summ[, 2], na.rm = TRUE) - min(summ[, 2], na.rm = TRUE)
if (ylen < 200) {
ytic = 20
ylo <- plyr::round_any(min(summ[, 2], na.rm = TRUE), 20, floor)
yhi <- plyr::round_any(max(summ[, 2], na.rm = TRUE), 20, ceiling)
} else {
ytic = 50
ylo <- plyr::round_any(min(summ[, 2], na.rm = TRUE), 50, floor)
yhi <- plyr::round_any(max(summ[, 2], na.rm = TRUE), 50, ceiling)
}
ylim = c(ylo, yhi)
plot(summ[, 1], summ[, 2], type = "n", axes = F, lty = 0, xlim = xlim,
ylim = ylim, xlab = NA, ylab = NA)
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4],
col = "lightcyan1")
graphics::box()
polygon(c(summ[, 1], rev(summ[, 1])), c((summ[, 3] + ci * summ[, 4]),
rev((summ[, 3] - ci * summ[, 4]))),
col = "azure3", border = NA)
title(ylab = "Millimetres", outer = TRUE, font.lab = 2, cex.lab = 0.9, line = 2.8)
title(xlab = "Year", outer = TRUE, font.lab = 2, cex.lab = 0.9, line = 1.5)
axis(side = 1, tck = -0.030, at = seq(xlo, xhi, by = xtic), outer = TRUE,
labels = NA)
axis(side = 1, at = seq(xlo, xhi, by = xtic), outer = TRUE, lwd = 0, line = -0.5,
cex.axis = 0.75)
axis(side = 2, tck = -0.025, at = seq(ylo, yhi, by = ytic), outer = TRUE,
labels = NA)
axis(side = 2, at = seq(ylo, yhi, by = ytic), cex.axis = 0.75)
graphics::mtext(object$Station.Name, side = 3, outer = TRUE, font = 2,
line = 0.20, cex = 1.1, adj = 0.5)
if (p == 0) {
lines(summ[, 1], summ[, 10], col = "red")
lines(summ[, 1], summ[, 2])
lines(summ[, 1], summ[, 3], lwd = 2)
legend(laba, legend = "Relative Mean Sea Level (MSL)", inset = c(-0.03, -0.01),
bty = "n", text.font = 2, cex = 0.85)
legend(labb, bg = "white", legend = c("KEY", "Annual Average Data",
"Gap Filling", "MSL Trend", lab1),
text.font = c(2, 1, 1, 1, 1), lty = c(0, 1, 1, 1, 1),
lwd = c(1, 1, 1, 3, 8),
col = c("black", "black", "red", "black", "azure3"),
cex = c(0.5, 0.5, 0.5, 0.5, 0.5))
}
if (p == 1) {
lines(summ[, 1], summ[, 2])
lines(summ[, 1], summ[, 3], lwd = 2)
legend(laba, legend = "Relative Mean Sea Level (MSL)",
inset = c(-0.03, -0.01), bty = "n", text.font = 2, cex = 0.85)
legend(labb, bg = "white", legend = c("KEY", "Annual Average Data",
"MSL Trend", lab1),
text.font = c(2, 1, 1, 1), lty = c(0, 1, 1, 1),
lwd = c(1, 1, 3, 8), col = c("black", "black", "black", "azure3"),
cex = c(0.5, 0.5, 0.5, 0.5))
}
par(opar)
grDevices::dev.off()
}
if (type == 3) {
if (header == TRUE) {
out <- c(2.6, 4.0, 1.5, 0.2)
} else {
out <- c(2.6, 4.0, 0.2, 0.2)
}
grDevices::jpeg(file.path(wdir, file_name), width = 160, height = 80, units = "mm", res = resol)
opar <- par(no.readonly = TRUE)
on.exit(par(opar))
par(oma = out)
par(mar = c(0,0,0,0), las = 1)
minV <- min((summ[, 5] - ci * summ[, 6]), summ$VelGeo, na.rm = TRUE)
maxV <- max((summ[, 5] + ci * summ[, 6]), summ$VelGeo, na.rm = TRUE)
ylen <- maxV - minV
if (ylen <= 1) {
ytic = 0.1
ylo <- plyr::round_any(minV - ylen * 0.15, 0.1, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 0.1, ceiling)
}
if (ylen > 1 & ylen <= 2) {
ytic = 0.2
ylo <- plyr::round_any(minV - ylen * 0.15, 0.2, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 0.2, ceiling)
}
if (ylen > 2 & ylen <= 5) {
ytic = 0.5
ylo <- plyr::round_any(minV - ylen * 0.15, 0.5, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 0.5, ceiling)
}
if (ylen > 5 & ylen <= 10) {
ytic = 1
ylo <- plyr::round_any(minV - ylen * 0.15, 1, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 1, ceiling)
}
if (ylen > 10) {
ytic = 2
ylo <- plyr::round_any(minV - ylen * 0.15, 2, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 2, ceiling)
}
ylim = c(ylo, yhi)
plot(summ[, 1], summ[, 5], type = "n", axes = F, lty = 0, xlim = xlim,
ylim = ylim, xlab = NA, ylab = NA)
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4],
col = "lightcyan1")
graphics::box()
polygon(c(summ[, 1], rev(summ[, 1])), c((summ[, 5] + ci * summ[, 6]),
rev((summ[, 5] - ci * summ[, 6]))),
col = "azure3", border = NA)
lines(summ[, 1], summ[, 5], lwd = 2)
abline(h = 0, lty = 2)
abline(h = max(summ[, 5]), lty = 3, col = "blue", lwd = 2)
if (p2 == 0) {
legend("topleft", legend = "Relative Velocity (MSL)", inset = c(-0.03, -0.01),
bty = "n", text.font = 2, cex = 0.85)
legend("bottomright", bg = "white",
legend = c("KEY", "MSL Velocity", "Peak Rate", lab1),
text.font = c(2, 1, 1, 1),
lty = c(0, 1, 3, 1),
lwd = c(1, 2, 2, 8),
col = c("black", "black", "blue", "azure3"),
cex = c(0.5, 0.5, 0.5, 0.5))
} else {
legend("topleft", legend = "Velocity (MSL)", inset = c(-0.03, -0.01),
bty = "n", text.font = 2, cex = 0.85)
legend("bottomleft", legend = labe, inset = c(-0.005, -0.005),
bty = "n", text.font = 1, cex = 0.6)
legend("bottomright", bg = "white",
legend = c("KEY", "Relative Velocity", "Peak Rate", lab1, "Geocentric Velocity"),
text.font = c(2, 1, 1, 1, 1),
lty = c(0, 1, 3, 1, 1),
lwd = c(1, 2, 2, 8, 2),
col = c("black", "black", "blue", "azure3", "red"),
cex = c(0.5, 0.5, 0.5, 0.5, 0.5))
lines(summ[, 1], summ$VelGeo, lwd = 2, col = "red")
}
title(ylab = "Millimetres/yr", outer = TRUE, font.lab = 2, cex.lab = 0.9,
line = 2.8)
title(xlab = "Year", outer = TRUE, font.lab = 2, cex.lab = 0.9, line = 1.5)
axis(side = 1, tck = -0.030, at = seq(xlo, xhi, by = xtic), outer = TRUE,
labels = NA)
axis(side = 1, at = seq(xlo, xhi, by = xtic), outer = TRUE, lwd = 0, line = -0.5,
cex.axis = 0.75)
axis(side = 2, tck = -0.025, at = seq(ylo, yhi, by = ytic), outer = TRUE,
labels = NA)
axis(side = 2, at = seq(ylo, yhi, by = ytic), cex.axis = 0.75)
graphics::mtext(object$Station.Name, side = 3, outer = TRUE, font = 2,
line = 0.20, cex = 1.1, adj = 0.5)
par(opar)
grDevices::dev.off()
}
if (type == 4) {
if (header == TRUE) {
out <- c(2.6, 4.0, 1.5, 0.2)
} else {
out <- c(2.6, 4.0, 0.2, 0.2)
}
grDevices::jpeg(file.path(wdir, file_name), width = 160, height = 80, units = "mm", res = resol)
opar <- par(no.readonly = TRUE)
on.exit(par(opar))
par(oma = out)
par(mar = c(0,0,0,0), las = 1)
ylen <- max(summ2[, 7] + ci * summ2[, 8]) - min(summ2[, 7] - ci * summ2[, 8])
if (ylen <= 0.1) {
ytic = 0.01
ylo <- plyr::round_any(min(summ2[, 7] - ci * summ2[, 8]) - ylen * 0.15,
0.01, floor)
yhi <- plyr::round_any(max(summ2[, 7] + ci * summ2[, 8]) + ylen * 0.15,
0.01, ceiling)
}
if (ylen > 0.1 & ylen <= 0.2) {
ytic = 0.02
ylo <- plyr::round_any(min(summ2[, 7] - ci * summ2[, 8]) - ylen * 0.15,
0.02, floor)
yhi <- plyr::round_any(max(summ2[, 7] + ci * summ2[, 8]) + ylen * 0.15,
0.02, ceiling)
}
if (ylen > 0.2 & ylen <= 0.5) {
ytic = 0.05
ylo <- plyr::round_any(min(summ2[, 7] - ci * summ2[, 8]) - ylen * 0.15,
0.05, floor)
yhi <- plyr::round_any(max(summ2[, 7] + ci * summ2[, 8]) + ylen * 0.15,
0.05, ceiling)
}
if (ylen > 0.5 & ylen <= 1) {
ytic = 0.1
ylo <- plyr::round_any(min(summ2[, 7] - ci * summ2[, 8]) - ylen * 0.15,
0.1, floor)
yhi <- plyr::round_any(max(summ2[, 7] + ci * summ2[, 8]) + ylen * 0.15,
0.1, ceiling)
}
if (ylen > 1) {
ytic = 0.2
ylo <- plyr::round_any(min(summ2[, 7] - ci * summ2[, 8]) - ylen * 0.15,
0.2, floor)
yhi <- plyr::round_any(max(summ2[, 7] + ci * summ2[, 8]) + ylen * 0.15,
0.2, ceiling)
}
ylim = c(ylo, yhi)
plot(summ2[, 1], summ2[, 7], type = "n", axes = F, lty = 0, xlim = xlim,
ylim = ylim, xlab = NA, ylab = NA)
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4],
col = "lightcyan1")
graphics::box()
polygon(c(summ2[, 1], rev(summ2[, 1])),
c((summ2[, 7] + ci * summ2[, 8]), rev((summ2[, 7] - ci * summ2[, 8]))),
col = "azure3", border = NA)
lines(summ2[, 1], summ2[, 7], lwd = 2)
abline(h = 0, lty = 2)
abline(h = max(summ2[, 7]), lty = 3, col = "blue", lwd = 2)
legend("topleft", legend = "Acceleration (MSL)",
inset = c(-0.03, -0.01), bty = "n", text.font = 2, cex = 0.85)
legend("bottomright", bg = "white", legend = c("KEY", "MSL Acceleration",
"Peak Acceleration", lab1),
text.font = c(2, 1, 1, 1), lty = c(0, 1, 3, 1), lwd = c(1, 2, 2, 8),
col = c("black", "black", "blue", "azure3"),
cex = c(0.5, 0.5, 0.5, 0.5))
title(ylab = expression(paste(bold("Millimetres/yr" ^ "2"))), outer = TRUE,
font.lab = 2, cex.lab = 0.9, line = 2.8)
title(xlab = "Year", outer = TRUE, font.lab = 2, cex.lab = 0.9, line = 1.5)
axis(side = 1, tck = -0.030, at = seq(xlo, xhi, by = xtic), outer = TRUE,
labels = NA)
axis(side = 1, at = seq(xlo, xhi, by = xtic), outer = TRUE, lwd = 0, line = -0.5,
cex.axis = 0.75)
axis(side = 2, tck = -0.025, at = seq(ylo, yhi, by = ytic), outer = TRUE,
labels = NA)
axis(side = 2, at = seq(ylo, yhi, by = ytic), cex.axis = 0.75)
graphics::mtext(object$Station.Name, side = 3, outer = TRUE, font = 2,
line = 0.20, cex = 1.1, adj = 0.5)
par(opar)
grDevices::dev.off()
}
if (type == 5) {
if (header == TRUE) {
out <- c(2.6, 4.0, 1.5, 0.2)
} else {
out <- c(2.6, 4.0, 0.2, 0.2)
}
grDevices::jpeg(file.path(wdir, file_name), width = 160, height = 150, units = "mm", res = resol)
opar <- par(no.readonly = TRUE)
on.exit(par(opar))
par(mfrow = c(2, 1), las = 1)
par(oma = out)
par(mar = c(0,0,0,0), las = 1)
ylen <- max(summ[, 2], na.rm = TRUE) - min(summ[, 2], na.rm = TRUE)
if (ylen < 200) {
ytic = 20
ylo <- plyr::round_any(min(summ[, 2], na.rm = TRUE), 20, floor)
yhi <- plyr::round_any(max(summ[, 2], na.rm = TRUE), 20, ceiling)
} else {
ytic = 50
ylo <- plyr::round_any(min(summ[, 2], na.rm = TRUE), 50, floor)
yhi <- plyr::round_any(max(summ[, 2], na.rm = TRUE), 50, ceiling)
}
ylim = c(ylo, yhi)
plot(summ[, 1], summ[, 2], type = "n", axes = F, lty = 0, xlim = xlim,
ylim = ylim, xlab = NA, ylab = NA)
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4],
col = "lightcyan1")
graphics::box()
polygon(c(summ[, 1], rev(summ[, 1])),
c((summ[, 3] + ci * summ[, 4]), rev((summ[, 3] - ci * summ[, 4]))),
col = "azure3", border = NA)
title(ylab = "Millimetres", outer = TRUE, font.lab = 2, cex.lab = 0.9,
line = 3.0, adj = 0.8)
axis(side = 2, tck = -0.025, at = seq(ylo, yhi, by = ytic), outer = TRUE,
labels = NA)
axis(side = 2, at = seq(ylo, yhi, by = ytic), cex.axis = 0.75)
if (p == 0) {
lines(summ[, 1], summ[, 10], col = "red")
lines(summ[, 1], summ[, 2])
lines(summ[, 1], summ[, 3], lwd = 2)
legend(laba, legend = "Relative Mean Sea Level (MSL)",
inset = c(-0.02, -0.01), bty = "n", text.font = 2, cex = 0.85)
legend(labb, bg = "white",
legend = c("KEY", "Annual Average Data", "Gap Filling",
"MSL Trend", lab1, "Peak Rate"),
text.font = c(2, 1, 1, 1, 1, 1), lty = c(0, 1, 1, 1, 1, 3),
lwd = c(1, 1, 1, 2, 8, 2),
col = c("black", "black", "red", "black", "azure3", "blue"),
cex = c(0.5, 0.5, 0.5, 0.5, 0.5, 0.5))
}
if (p == 1) {
lines(summ[, 1], summ[, 2])
lines(summ[, 1], summ[, 3], lwd = 2)
legend(laba, legend = "Relative Mean Sea Level (MSL)", inset = c(-0.02, -0.01),
bty = "n", text.font = 2, cex = 0.85)
legend(labb, bg = "white",
legend = c("KEY", "Annual Average Data", "MSL Trend", lab1,
"Peak Rate"), text.font = c(2, 1, 1, 1, 1),
lty = c(0, 1, 1, 1, 3), lwd = c(1, 1, 2, 8, 2),
col = c("black", "black", "black", "azure3", "blue"),
cex = c(0.5, 0.5, 0.5, 0.5, 0.5, 0.5))
}
par(mar = c(0,0,0,0), las = 1)
minV <- min((summ[, 5] - ci * summ[, 6]), summ$VelGeo, na.rm = TRUE)
maxV <- max((summ[, 5] + ci * summ[, 6]), summ$VelGeo, na.rm = TRUE)
ylen <- maxV - minV
if (ylen <= 1) {
ytic = 0.1
ylo <- plyr::round_any(minV - ylen * 0.15, 0.1, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 0.1, ceiling)
}
if (ylen > 1 & ylen <= 2) {
ytic = 0.2
ylo <- plyr::round_any(minV - ylen * 0.15, 0.2, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 0.2, ceiling)
}
if (ylen > 2 & ylen <= 5) {
ytic = 0.5
ylo <- plyr::round_any(minV - ylen * 0.15, 0.5, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 0.5, ceiling)
}
if (ylen > 5 & ylen <= 10) {
ytic = 1
ylo <- plyr::round_any(minV - ylen * 0.15, 1, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 1, ceiling)
}
if (ylen > 10) {
ytic = 2
ylo <- plyr::round_any(minV - ylen * 0.15, 2, floor)
yhi <- plyr::round_any(maxV + ylen * 0.15, 2, ceiling)
}
ylim = c(ylo, yhi)
plot(summ[, 1], summ[, 5], type = "n", axes = F, lty = 0, xlim = xlim,
ylim = ylim, xlab = NA, ylab = NA)
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4],
col = "lightcyan1")
graphics::box()
polygon(c(summ[, 1], rev(summ[, 1])), c((summ[, 5] + ci * summ[, 6]),
rev((summ[, 5] - ci * summ[, 6]))),
col = "azure3", border = NA)
lines(summ[, 1], summ[, 5], lwd = 2)
abline(h = 0, lty = 2)
abline(h = max(summ[, 5]), lty = 3, col = "blue", lwd = 2)
if (p2 == 0) {
legend("topleft", legend = "Relative Velocity (MSL)", inset = c(-0.02, -0.01),
bty = "n", text.font = 2, cex = 0.9)
}
if (p2 == 1) {
legend("topleft", legend = "Velocity (MSL)", inset = c(-0.02, -0.01),
bty = "n", text.font = 2, cex = 0.85)
legend("topright", legend = labe, inset = c(0.03, 0.01),
bty = "n", text.font = 1, cex = 0.6)
legend("bottomright", bg = "white",
legend = c("KEY", "Relative Velocity", "Geocentric Velocity"),
text.font = c(2, 1, 1),
lty = c(0, 1, 1),
lwd = c(1, 3, 3),
col = c("black", "black", "red"),
cex = c(0.5, 0.5, 0.5))
lines(summ[, 1], summ$VelGeo, lwd = 2, col = "red")
}
title(ylab = "Millimetres/yr", outer = TRUE, font.lab = 2, cex.lab = 0.9,
line = 3.0, adj = 0.2)
title(xlab = "Year", outer = TRUE, font.lab = 2, cex.lab = 0.9, line = 1.5)
axis(side = 1, tck = -0.030, at = seq(xlo, xhi, by = xtic), outer = TRUE,
labels = NA)
axis(side = 1, at = seq(xlo, xhi, by = xtic), outer = TRUE, lwd = 0, line = -0.5,
cex.axis = 0.75)
axis(side = 2, tck = -0.025, at = seq(ylo, yhi, by = ytic), outer = TRUE,
labels = NA)
axis(side = 2, at = seq(ylo, yhi, by = ytic), cex.axis = 0.75)
graphics::mtext(object$Station.Name, side = 3, outer = TRUE, font = 2,
line = 0.20, cex = 1.1, adj = 0.5)
graphics::par(opar)
grDevices::dev.off()
}
}
|
det_range<-function(data,
model,
times=50,
...){
nsize<-dim(data)[1]
lam=rep(NA,times)
for(i in 1:times){
ids = sample(1:nsize,nsize,replace=T)
datasub.boot <- data[ids,]
est_model_boot <- sem(model, data = datasub.boot)
try(cv.out.boot <- cv_regsem(est_model_boot,...))
try(lam[i]<-cv.out.boot$fit[which.min(cv.out.boot$fits[cv.out.boot$fit[,2]==0,4])])
}
if (sum(lam!=0,na.rm=T)==0){
warning("0 penalty is selected by all runs.")
lb=0;ub=0;
}else{
lb<-min(lam[lam!=0],na.rm=T)
ub<-max(lam[lam!=0],na.rm=T)
}
Lam<-c(lb,ub)
result<-list()
result$lambdas<-lam
result$lb<-lb
result$ub<-ub
result$zero_removed<-min(lam,na.rm=T)==0
return(result)
}
|
geom_text_z <- function(mapping = NULL, data = NULL,
stat = "identity", position = "identity",
...,
parse = FALSE,
nudge_x = 0,
nudge_y = 0,
check_overlap = FALSE,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE,
material = list(),
keep2d = FALSE)
{
if (!missing(nudge_x) || !missing(nudge_y)) {
if (!missing(position)) {
abort("You must specify either `position` or `nudge_x`/`nudge_y`.")
}
position <- position_nudge(nudge_x, nudge_y)
}
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomTextZ,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
parse = parse,
check_overlap = check_overlap,
na.rm = na.rm,
material = material,
keep2d = keep2d,
...
)
)
}
GeomTextZ <- ggproto(
"GeomTextZ",
Geom,
required_aes = c("x", "y", "z", "label"),
default_aes = aes(
colour = "black", size = 3.88, angle = 0, hjust = 0.5,
vjust = 0.5, alpha = NA, family = "", fontface = 1, lineheight = 1.2
),
draw_panel = function(data, panel_params, coord, parse = FALSE,
na.rm = FALSE, check_overlap = FALSE, orientation = 'xy',
material = list(), keep2d = FALSE) {
if (isTRUE(keep2d)) {
grob2d <- GeomText$draw_panel(data, panel_params, coord, parse = parse,
na.rm = na.rm, check_overlap = check_overlap)
} else {
grob2d <- ggplot2::zeroGrob()
}
lab <- data$label
if (parse) {
lab <- parse_safe(as.character(lab))
}
data <- coord$transform(data, panel_params)
if (is.character(data$vjust)) {
data$vjust <- compute_just(data$vjust, data$y)
}
if (is.character(data$hjust)) {
data$hjust <- compute_just(data$hjust, data$x)
}
rgl_call <- cryogenic::capture_call(
spheres3d(
x = data$x,
y = data$y,
z = 10,
color = 'red',
radius = 5,
alpha = 0.3
))
spheres_grob <- snowcrash::encode_robj_to_rasterGrob(rgl_call)
text3d_rgl_calls <- lapply(seq(nrow(data)), function(i) {
cryogenic::capture_call(
rgl_text_helper(
str = lab[i],
x = data$x[i],
y = data$y[i],
z = data$z[i],
rot = 0,
state = NULL,
manual = TRUE,
colour = data$colour[i],
orientation = orientation
),
defaults = material
)
})
text3d_grob <- snowcrash::encode_robj_to_rasterGrob(text3d_rgl_calls)
grid::grobTree(
grob2d,
text3d_grob
)
},
draw_key = draw_key_text
)
compute_just <- function(just, x) {
inward <- just == "inward"
just[inward] <- c("left", "middle", "right")[just_dir(x[inward])]
outward <- just == "outward"
just[outward] <- c("right", "middle", "left")[just_dir(x[outward])]
unname(c(left = 0, center = 0.5, right = 1,
bottom = 0, middle = 0.5, top = 1)[just])
}
just_dir <- function(x, tol = 0.001) {
out <- rep(2L, length(x))
out[x < 0.5 - tol] <- 1L
out[x > 0.5 + tol] <- 3L
out
}
|
create_beast2_continue_cmd_from_options <- function(beast2_options) {
beastier::check_beast2_options(beast2_options)
testit::assert(file.exists(beast2_options$beast2_path))
testit::assert(file.exists(beastier::get_default_java_path()))
cmds <- NULL
if (beastier::is_jar_path(beast2_options$beast2_path)) {
cmds <- c(
beastier::get_default_java_path(),
"-cp",
beastier::add_quotes_if_has_spaces(beast2_options$beast2_path),
beastier::get_beast2_main_class_name()
)
testit::assert(file.exists(cmds[1]))
} else {
testit::assert(beastier::is_bin_path(beast2_options$beast2_path))
testit::assert(file.exists(beast2_options$beast2_path))
cmds <- beastier::add_quotes_if_has_spaces(beast2_options$beast2_path)
}
if (!beautier::is_one_na(beast2_options$rng_seed)) {
cmds <- c(cmds, "-seed")
cmds <- c(cmds, beast2_options$rng_seed)
}
if (!beautier::is_one_na(beast2_options$n_threads)) {
cmds <- c(cmds, "-threads")
cmds <- c(cmds, beast2_options$n_threads)
}
if (beast2_options$use_beagle == TRUE) {
cmds <- c(cmds, "-beagle")
}
cmds <- c(cmds, "-statefile")
cmds <- c(
cmds,
beastier::add_quotes_if_has_spaces(beast2_options$output_state_filename)
)
cmds <- c(cmds, "-resume")
if (beast2_options$overwrite == TRUE) {
cmds <- c(cmds, "-overwrite")
}
cmds <- c(
cmds,
beastier::add_quotes_if_has_spaces(beast2_options$input_filename)
)
cmds
}
|
showMatrix3D <- function(Matrix = NULL, BestMatches=NULL, Cls=NULL,Imx=NULL, Toroid=TRUE, HeightScale=NULL,
BmSize=0.5, RemoveOcean=T, ColorStyle = "Umatrix",
ShowAxis=F, SmoothSlope=F, ClsColors = NULL, FileName = NULL){
if(is.null(ClsColors)) ClsColors = DefaultColorSequence()
if(!requireNamespace("rgl", quietly = T)) stop("Package Rgl could not be loaded.")
if(is.null(Matrix))
stop("Matrix needs to be given")
quants=quantile(as.vector(Matrix),c(0.01,0.5,0.99))
minU=quants[1]
maxU=quants[3]
Matrix=(Matrix-minU)/(maxU-minU)
quants2=quantile(as.vector(Matrix),c(0.01,0.5,0.99))
minU2=quants2[1]
maxU2=quants2[3]
if(is.null(HeightScale)){
HeightScale=round(maxU2/(2*max(minU2,0.05)),0)
stretchFactor = sqrt(nrow(Matrix)^2 + ncol(Matrix)^2) / sqrt(50^2 + 80^2)
}
stretchFactor = sqrt(nrow(Matrix)^2 + ncol(Matrix)^2) / sqrt(50^2 + 80^2)
indMax=which(Matrix>1,arr.ind=T)
indMin=which(Matrix<0,arr.ind=T)
if(length(indMax)>0)
Matrix[indMax]=1
if(length(indMin)>0)
Matrix[indMin]=0
if(!is.null(BestMatches)) if(is.null(Cls)) Cls = rep(1, nrow(BestMatches))
BestMatches = CheckBestMatches(BestMatches, Cls, shiny=F)
CheckUmatrix(Matrix, shiny=F)
CheckImx(Imx, shiny=F)
if(Toroid){
tU <- ToroidUmatrix(Matrix,BestMatches,Cls)
Matrix <- tU$Umatrix
BestMatches <- tU$BestMatches
Cls <- tU$Cls
}
bigImx = Imx
if(SmoothSlope){
for(i in 1:10){
if(!is.null(Imx)){
tmpImx = bigImx
for(x in 2:(nrow(Matrix)-1)){
for(y in 2:(ncol(Matrix)-1)){
if((Matrix[x-1,y] >= 0.3)&(tmpImx[x-1,y]==0)) bigImx[x,y] = 0
if((Matrix[x+1,y] >= 0.3)&(tmpImx[x+1,y]==0)) bigImx[x,y] = 0
if((Matrix[x,y-1] >= 0.3)&(tmpImx[x,y-1]==0)) bigImx[x,y] = 0
if((Matrix[x,y+1] >= 0.3)&(tmpImx[x,y+1]==0)) bigImx[x,y] = 0
}
}
}
}
}
zcol = cut(Matrix,128)
lines = seq(1, nrow(Matrix), len = nrow(Matrix))
columns = seq(1, ncol(Matrix), len = ncol(Matrix))
if(ColorStyle == "Umatrix") Colormap = c("
else if(ColorStyle == "Pmatrix") Colormap = c("
else stop("ColorStyle not found.")
Nrlevels2 = 2*HeightScale*stretchFactor
levelBreaks <- seq(0,1.000001,length.out=(Nrlevels2+1))
if(!is.null(Imx)){
Matrix[which(bigImx == 1)] = 0
if(!is.null(BestMatches)){
BestMatchesFilter = rep(T,nrow(BestMatches))
for(i in 1:nrow(Imx)){
for(j in 1:ncol(Imx)){
if(Imx[i,j] == 1){
if(!is.null(BestMatches))
BestMatchesFilter[(BestMatches[,2] == i) & (BestMatches[,3] == j)] = F
}
}
}
BestMatches = BestMatches[BestMatchesFilter,]
if(!is.null(Cls)) Cls = Cls[BestMatchesFilter]
}
if(RemoveOcean){
oceanLine = apply(Matrix, 1, function(x) all(x==0))
startLine = min(which(!oceanLine),na.rm=T)
endLine = length(oceanLine) - min(which(rev(!oceanLine)),na.rm=T) + 1
oceanCol = apply(Matrix, 2, function(x) all(x==0))
startCol = min(which(!oceanCol),na.rm=T)
endCol = length(oceanCol) - min(which(rev(!oceanCol)),na.rm=T) + 1
if(!is.null(BestMatches)){
BestMatches <- BestMatches - cbind(rep(0,nrow(BestMatches)),startLine-1,startCol-1)
}
Matrix <- Matrix[startLine:endLine,startCol:endCol]
Imx <- Imx[startLine:endLine,startCol:endCol]
bigImx <- bigImx[startLine:endLine,startCol:endCol]
}
}
splittedMatrix = Matrix
for(i in 1:Nrlevels2){
splittedMatrix[ (Matrix >= levelBreaks[i]) & (Matrix <= levelBreaks[i+1]) ] = levelBreaks[i]
}
splittedMatrix=(floor(splittedMatrix * length(Colormap)))+1
color = Colormap[splittedMatrix]
if(!is.null(Imx)) color[which(bigImx == 1)] = NA
z<-Matrix*HeightScale*stretchFactor
lines = seq(1, nrow(z), len = nrow(z))
columns = seq(1, ncol(z), len = ncol(z))
rgl::open3d()
if(ShowAxis){
rgl::material3d(col = "black")
rgl::persp3d(x=lines, y=columns, z=z, color=color, aspect=FALSE, lit=F,box=F, texmagfilter="nearest", texminfilter="nearest", texenvmap=TRUE)
}
else{
rgl::surface3d(x=lines, y=columns, z=z, color=color, aspect=FALSE, lit=F)
}
if(!is.null(FileName)){
rgl::writeSTL(FileName)
}
if(!is.null(BestMatches)){
if(length(ClsColors) < length(DefaultColorSequence()))
ClsColors = c(ClsColors, DefaultColorSequence()[(length(ClsColors)+1):(length(DefaultColorSequence()))])
ColorClass = c()
for(i in 1:length(unique(Cls))) ColorClass[Cls == sort(unique(Cls))[i]] = i
BestMatchesHeights <- sapply(1:nrow(BestMatches), function(x) z[BestMatches[x,2],BestMatches[x,3]])
if(is.list(BestMatchesHeights))
BestMatchesHeights = unlist(BestMatchesHeights)
bmuIds = rgl::spheres3d(x=BestMatches[,2],BestMatches[,3], BestMatchesHeights, col = ClsColors[ColorClass], radius = BmSize)
}
lines = contourLines(lines,columns,z, nlevels = 35)
for (i in seq_along(lines)) {
x <- lines[[i]]$x
y <- lines[[i]]$y
z <- rep(lines[[i]]$level, length(x))
rgl::lines3d(x, y, z)
}
}
|
lda_thomaz <- function(x, ...) {
UseMethod("lda_thomaz")
}
lda_thomaz.default <- function(x, y, prior = NULL, ...) {
x <- pred_to_matrix(x)
y <- outcome_to_factor(y)
complete <- complete.cases(x) & complete.cases(y)
x <- x[complete,,drop = FALSE]
y <- y[complete]
obj <- regdiscrim_estimates(x = x, y = y, prior = prior, cov = TRUE)
cov_eigen <- eigen(obj$cov_pool, symmetric = TRUE)
evals <- cov_eigen$values
mean_eval <- mean(evals)
evals[evals < mean_eval] <- mean_eval
if (obj$p > 1) {
obj$cov_pool <- with(cov_eigen,
tcrossprod(vectors %*% diag(evals), vectors))
obj$cov_inv <- with(cov_eigen,
tcrossprod(vectors %*% diag(1 / evals), vectors))
} else {
obj$cov_pool <- with(cov_eigen,
tcrossprod(vectors %*% as.matrix(evals), vectors))
obj$cov_inv <- with(cov_eigen,
tcrossprod(vectors %*% as.matrix(1 / evals), vectors))
}
obj$col_names <- colnames(x)
obj <- new_discrim_object(obj, "lda_thomaz")
obj
}
lda_thomaz.formula <- function(formula, data, prior = NULL, ...) {
formula <- no_intercept(formula, data)
mf <- model.frame(formula = formula, data = data)
.terms <- attr(mf, "terms")
x <- model.matrix(.terms, data = mf)
y <- model.response(mf)
est <- lda_thomaz.default(x = x, y = y, prior = prior)
est$.terms <- .terms
est <- new_discrim_object(est, class(est))
est
}
print.lda_thomaz <- function(x, ...) {
cat("LDA using the Thomaz-Kitani-Gillies Covariance Matrix Estimator\n\n")
print_basics(x, ...)
invisible(x)
}
predict.lda_thomaz <- function(object, newdata, type = c("class", "prob", "score"), ...) {
type <- rlang::arg_match0(type, c("class", "prob", "score"), arg_nm = "type")
newdata <- process_newdata(object, newdata)
scores <- apply(newdata, 1, function(obs) {
sapply(object$est, function(class_est) {
with(class_est, quadform(object$cov_inv, obs - xbar) + log(prior))
})
})
if (type == "prob") {
means <- lapply(object$est, "[[", "xbar")
covs <- replicate(n=object$num_groups, object$cov_pool, simplify=FALSE)
priors <- lapply(object$est, "[[", "prior")
res <- posterior_probs(x = newdata, means = means, covs = covs, priors = priors)
res <- as.data.frame(res)
} else if (type == "class") {
res <- score_to_class(scores, object)
} else {
res <- t(scores)
res <- as.data.frame(res)
}
res
}
|
.multi.rtt <-
function (t, tip.dates, topx=1, ncpu = 1, objective = "correlation", opt.tol = .Machine$double.eps^0.25)
{
topx <- max( 1, topx)
if (objective == "correlation")
objective <- function(x, y) cor.test(y, x)$estimate
else if (objective == "rsquared")
objective <- function(x, y) summary(lm(y ~ x))$r.squared
else if (objective == "rms")
objective <- function(x, y) -summary(lm(y ~ x))$sigma^2
else stop("objective must be one of \"correlation\", \"rsquared\", or \"rms\"")
ut <- unroot(t)
dist <- dist.nodes(ut)[, 1:(ut$Nnode + 2)]
f <- function(x, parent, child) {
edge.dist <- x * dist[parent, ] + (1 - x) * dist[child,
]
objective(tip.dates, edge.dist)
}
obj.edge <- if (ncpu > 1)
unlist(parallel::mclapply(1:nrow(ut$edge), function(e) {
opt.fun <- function(x) f(x, ut$edge[e, 1], ut$edge[e,
2])
optimize(opt.fun, c(0, 1), maximum = TRUE, tol = opt.tol)$objective
}, mc.cores = ncpu))
else apply(ut$edge, 1, function(e) {
opt.fun <- function(x) f(x, e[1], e[2])
optimize(opt.fun, c(0, 1), maximum = TRUE, tol = opt.tol)$objective
})
best.edges <- order( obj.edge, decreasing=TRUE)[1:topx]
lapply(best.edges , function(best.edge){
best.edge.parent <- ut$edge[best.edge, 1]
best.edge.child <- ut$edge[best.edge, 2]
best.edge.length <- ut$edge.length[best.edge]
opt.fun <- function(x) f(x, best.edge.parent, best.edge.child)
best.pos <- optimize(opt.fun, c(0, 1), maximum = TRUE, tol = opt.tol)$maximum
new.root <- list(edge = matrix(c(2L, 1L), 1, 2), tip.label = "new.root",
edge.length = 1, Nnode = 1L, root.edge = 1)
class(new.root) <- "phylo"
ut <- bind.tree(ut, new.root, where = best.edge.child, position = best.pos *
best.edge.length)
ut <- collapse.singles(ut)
ut <- root(ut, "new.root")
x <- drop.tip(ut, "new.root")
if (!is.rooted(x)) return(NULL)
x
})-> tres
tres[ !sapply( tres, is.null) ]
}
|
psymbolic <- function(pdata, vertices){
if(class(pdata) != 'paggregated'){
stop('Insert an object of the class paggregated')
}
if(vertices <= 2){
stop("Insert the number of vertices greater than 2!")
}
if(is.matrix(pdata$center) | is.data.frame(pdata$center)){
m <- nrow(pdata$center)
p <- ncol(pdata$center)
initial <- vector('list', m)
psdata <- new.env()
variables <- paste('X', 1 : p, sep = '')
for(j in 1 : p){
for(i in 1 : m){
initial[[i]] <- spolygon(pdata$center[i, j], pdata$radius[i, j], vertices)
}
psdata[[variables[j]]] <- initial
}
variables_names <- names(pdata$center)
objs = mget(ls(psdata), psdata)
rm(list = ls(psdata), envir = psdata)
list2env(setNames(objs, variables_names), psdata)
}
else if(is.vector(pdata$center)){
m <- length(pdata$center)
initial <- vector('list', m)
psdata <- new.env()
for(i in 1 : m){
initial[[i]] <- spolygon(pdata$center[i], pdata$radius[i], vertices)
}
names(initial) <- names(pdata$center)
psdata[['X1']] <- initial
}
else{
stop('Insert a matrix, data.frame or vector for center and radius!')
}
class(psdata) <- 'polygonal-variables'
psdata
}
|
if(isTRUE(getOption("covr"))) {
context("custom tables")
suppressWarnings(RNGversion("3.5.0"))
data(mtcars)
mtcars = apply_labels(mtcars,
mpg = "Miles/(US) gallon",
cyl = "Number of cylinders",
disp = "Displacement (cu.in.)",
carb = NULL,
qsec = "1/4 mile time",
hp = "Gross horsepower",
vs = "Engine",
vs = num_lab("
0 V-engine
1 Straight engine
"),
am = "Transmission",
am = num_lab("
0 Automatic
1 Manual
")
)
res = mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(vs) %>%
tab_rows(am) %>%
tab_stat_fun(w_mean) %>%
tab_pivot()
expect_known_value(res, "rds/ctable0.rds", update = FALSE)
expect_error(mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(vs) %>%
tab_rows(am) %>%
tab_stat_fun(w_mean) %>%
tab_caption("my table") %>%
tab_pivot()
)
expect_identical(
mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(vs) %>%
tab_rows(am) %>%
tab_stat_fun(w_mean) %>%
tab_pivot() %>%
tab_caption("my ", "table"),
mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(vs) %>%
tab_rows(am) %>%
tab_stat_fun(w_mean) %>%
tab_pivot() %>%
set_caption("my table")
)
res = mtcars %>%
tab_cols(vs) %>%
tab_cells(mpg, disp) %>%
tab_rows(am) %>%
tab_stat_fun(w_mean) %>%
tab_pivot
expect_known_value(res, "rds/ctable0.rds", update = FALSE)
res = mtcars %>%
tab_rows(am) %>%
tab_cols(vs) %>%
tab_cells(mpg, disp) %>%
tab_stat_fun(w_mean) %>%
tab_pivot
expect_known_value(res, "rds/ctable0.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(vs) %>%
tab_rows(am) %>%
tab_stat_fun(w_mean = w_mean) %>%
tab_pivot
expect_known_value(res, "rds/ctable1.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(vs) %>%
tab_rows(am) %>%
tab_stat_fun("|" = w_mean) %>%
tab_pivot
expect_known_value(res, "rds/ctable2.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(vs) %>%
tab_rows(am) %>%
tab_stat_fun("|" = w_mean, label = "Mean value") %>%
tab_pivot
expect_known_value(res, "rds/ctable3.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(vs) %>%
tab_rows(am) %>%
tab_stat_fun("|" = w_mean, label = "Mean value") %>%
tab_pivot(stat_position = "inside_rows")
expect_known_value(res, "rds/ctable3.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(vs) %>%
tab_rows(am) %>%
tab_stat_fun("|" = w_mean, label = "Mean value") %>%
tab_pivot(stat_position = "inside_columns")
expect_known_value(res, "rds/ctable4.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(vs) %>%
tab_rows(am) %>%
tab_stat_mean(label = "Mean value") %>%
tab_pivot()
expect_known_value(res, "rds/ctable3.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(vs) %>%
tab_rows(am) %>%
tab_stat_mean(label = "Mean value") %>%
tab_pivot(stat_position = "inside_columns")
expect_known_value(res, "rds/ctable4.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(vs) %>%
tab_rows(am) %>%
tab_stat_mean() %>%
tab_stat_sd() %>%
tab_stat_valid_n() %>%
tab_pivot(stat_position = "inside_rows")
expect_known_value(res, "rds/ctable5.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(vs) %>%
tab_rows(am) %>%
tab_stat_mean() %>%
tab_stat_sd() %>%
tab_stat_valid_n() %>%
tab_pivot(stat_position = "inside_columns")
expect_known_value(res, "rds/ctable6.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, disp) %>%
tab_cols(total(), vs) %>%
tab_rows(am) %>%
tab_stat_fun(summary) %>%
tab_pivot()
if(as.numeric(version$major) ==3 && as.numeric(version$minor)<4){
expect_known_value(res, "rds/ctable7.rds", update = FALSE)
} else {
expect_known_value(res, "rds/ctable7_R3.4.rds", update = FALSE)
}
res = mtcars %>%
tab_cells(vs) %>%
tab_cols(total(), am) %>%
tab_stat_cpct(total_row_position = "none", label = "col %") %>%
tab_stat_rpct(total_row_position = "none", label = "row %") %>%
tab_stat_tpct(total_row_position = "none", label = "table %") %>%
tab_cells(total(vs, label = "
tab_stat_cases(total_row_position = "none") %>%
tab_pivot(stat_position = "inside_rows")
expect_known_value(res, "rds/ctable8.rds", update = FALSE)
res = mtcars %>%
tab_total_row_position("none") %>%
tab_cells(vs) %>%
tab_cols(total(), am) %>%
tab_stat_cpct(label = "col %") %>%
tab_stat_rpct(label = "row %") %>%
tab_stat_tpct(label = "table %") %>%
tab_cells(total(vs, label = "
tab_stat_cases() %>%
tab_pivot(stat_position = "inside_rows")
expect_known_value(res, "rds/ctable8.rds", update = FALSE)
res = mtcars %>%
tab_subgroup(vs == 0) %>%
tab_cells(vs) %>%
tab_cols(total(), am) %>%
tab_subgroup() %>%
tab_stat_cpct(total_row_position = "none", label = "col %") %>%
tab_stat_rpct(total_row_position = "none", label = "row %") %>%
tab_stat_tpct(total_row_position = "none", label = "table %") %>%
tab_cells(total(vs, label = "
tab_stat_cases(total_row_position = "none") %>%
tab_pivot(stat_position = "inside_rows")
expect_known_value(res, "rds/ctable8.rds", update = FALSE)
res = mtcars %>%
tab_subgroup(vs == 0) %>%
tab_cells(vs) %>%
tab_cols(total(), am) %>%
tab_stat_cpct(total_row_position = "none", label = "col %") %>%
tab_stat_rpct(total_row_position = "none", label = "row %") %>%
tab_stat_tpct(total_row_position = "none", label = "table %") %>%
tab_cells(total(vs, label = "
tab_stat_cases(total_row_position = "none") %>%
tab_pivot(stat_position = "inside_rows")
expect_known_value(res, "rds/ctable9.rds", update = FALSE)
res = mtcars %>%
tab_cells(cyl) %>%
tab_cols(total(), am) %>%
tab_stat_rpct(total_row_position = "none") %>%
tab_pivot() %>%
tab_transpose() %>%
tab_sort_desc()
expect_known_value(res, "rds/ctable10.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, disp, hp) %>%
tab_cols(total(label = "
tab_stat_fun(Mean = w_mean, "Std. dev" = w_sd, "Valid N" = w_n, method = list) %>%
tab_sort_asc() %>%
tab_transpose() %>%
tab_pivot() %>%
split_columns()
expect_known_value(res, "rds/ctable11.rds", update = FALSE)
set.seed(1)
df = data.frame(area=rep(c('Area 1','Area 2'), each=6),
var_orange=sample(0:1, 12, T),
var_banana=sample(0:1, 12, T),
var_melon=sample(0:1, 12, T),
var_mango=sample(0:1, 12, T))
res = df %>%
tab_cells(mdset(var_orange, var_banana, var_melon, var_mango)) %>%
tab_cols(total(), list(area)) %>%
tab_stat_cpct_responses(total_row_position = "below", total_statistic = "u_responses") %>%
tab_pivot()
expect_known_value(res, "rds/ctable12.rds", update = FALSE)
res = mtcars %>%
tab_cells(cyl, carb) %>%
tab_cols(total(), am %nest% vs) %>%
tab_stat_fun(Mean = w_mean, "Std. dev" = w_sd, "Valid N" = w_n) %>%
tab_stat_cpct() %>%
tab_pivot()
expect_known_value(res, "rds/ctable13.rds", update = FALSE)
res = mtcars %>%
tab_cols(total(), am %nest% vs) %>%
tab_cells(cyl) %>%
tab_stat_fun(Mean = w_mean, "Std. dev" = w_sd, "Valid N" = w_n) %>%
tab_stat_cpct() %>%
tab_cells(carb) %>%
tab_stat_fun(Mean = w_mean, "Std. dev" = w_sd, "Valid N" = w_n) %>%
tab_stat_cpct() %>%
tab_pivot()
expect_known_value(res, "rds/ctable14.rds", update = FALSE)
res = mtcars %>%
tab_cols(total(), am %nest% vs)
for(each in qc(cyl, carb, hp)){
res = res %>% tab_cells(vars(each)) %>%
tab_stat_fun(Mean = w_mean, "Std. dev" = w_sd, "Valid N" = w_n) %>%
tab_stat_cpct()
}
res = res %>% tab_pivot()
expect_known_value(res, "rds/ctable15.rds", update = FALSE)
res = mtcars %>%
tab_cells(cyl, carb) %>%
tab_cols(total(), am %nest% vs) %>%
tab_stat_fun(w_mean, w_sd, w_n, method = list) %>%
tab_pivot()
expect_known_value(res, "rds/ctable16.rds", update = FALSE)
res = mtcars %>%
tab_cells(cyl) %>%
tab_cols(total(), am) %>%
tab_stat_cpct(total_row_position = "none", label = "col %") %>%
tab_stat_rpct(total_row_position = "none", label = "row %") %>%
tab_stat_tpct(total_row_position = "none", label = "table %") %>%
tab_pivot(stat_position = "inside_columns")
expect_known_value(res, "rds/ctable17.rds", update = FALSE)
res = mtcars %>%
tab_cells(cyl) %>%
tab_cols(total(), am) %>%
tab_total_row_position("none") %>%
tab_stat_cpct(label = "col %") %>%
tab_stat_rpct(label = "row %") %>%
tab_stat_tpct(label = "table %") %>%
tab_pivot(stat_position = "inside_columns")
expect_known_value(res, "rds/ctable17.rds", update = FALSE)
res = mtcars %>%
tab_cells(cyl) %>%
tab_cols(total(), am) %>%
tab_rows(vs) %>%
tab_stat_cpct(total_row_position = "none", label = "col %") %>%
tab_stat_rpct(total_row_position = "none", label = "row %") %>%
tab_stat_tpct(total_row_position = "none", label = "table %") %>%
tab_pivot(stat_position = "inside_rows")
expect_known_value(res, "rds/ctable18.rds", update = FALSE)
context("custom tables summary stats")
mtcars$mpg[1:2] = NA
mtcars$wt[4:5] = NA
mtcars$wt[6] = -1
mtcars$wt[15] = -1
mtcars$wt[16] = 0
mtcars$wt[20] = NA
res = mtcars %>% tab_cells(mpg, qsec, hp, disp) %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "inside_columns")
expect_known_value(res, "rds/ctable19.rds", update = FALSE)
res = mtcars %>%
tab_weight(wt) %>%
tab_cells(mpg, qsec, hp, disp) %>%
tab_weight() %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "inside_columns")
expect_known_value(res, "rds/ctable19.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, qsec, hp, disp) %>%
tab_weight(wt) %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "inside_columns")
expect_known_value(res, "rds/ctable20.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, qsec, hp, disp) %>%
tab_subgroup(!is.na(wt) & wt>0) %>%
tab_weight(wt) %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "inside_columns")
expect_known_value(res, "rds/ctable20.rds", update = FALSE)
res = mtcars %>%
tab_subgroup(!is.na(wt) & wt>0) %>%
tab_cells(mpg, qsec, hp, disp) %>%
tab_weight(wt) %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "inside_columns")
expect_known_value(res, "rds/ctable20.rds", update = FALSE)
res1 = sheet(a = c(1, 2, 3, 4, 5), b = c(5, 5, 1, 2, NA)) %>%
tab_cells(a, b) %>%
tab_mis_val(3:5) %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "inside_columns")
res2 = sheet(a = c(1, 2, 3, 4, 5), b = c(5, 5, 1, 2, NA)) %>%
tab_cells(a, b) %>%
tab_mis_val(gt(2)) %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "inside_columns")
res4 = sheet(a = c(1, 2, 3, 4, 5), b = c(5, 5, 1, 2, NA)) %>%
tab_cells(a, b) %>%
tab_mis_val(3 | gt(3)) %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "inside_columns")
res3 = sheet(a = c(1, 2, NA, NA, NA), b = c(NA, NA, 1, 2, NA)) %>%
tab_mis_val(1:2) %>%
tab_cells(a, b) %>%
tab_mis_val() %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "inside_columns")
expect_identical(res1, res2)
expect_identical(res1, res3)
expect_identical(res1, res4)
data("product_test")
codeframe_likes = num_lab("
1 Liked everything
2 Disliked everything
3 Chocolate
4 Appearance
5 Taste
6 Stuffing
7 Nuts
8 Consistency
98 Other
99 Hard to answer
")
set.seed(1)
pr_t = product_test %>%
let(
age_cat = if_val(s2a, lo %thru% 25 ~ 1, lo %thru% hi ~ 2),
wgt = runif(.N, 0.25, 4)
) %>%
apply_labels(
c1 = "Preferences",
c1 = num_lab("
1 VSX123
2 SDF456
3 Hard to say
"),
age_cat = "Age",
age_cat = c("18 - 25" = 1, "26 - 35" = 2),
a1_1 = "Likes. VSX123",
b1_1 = "Likes. SDF456",
a1_1 = codeframe_likes,
b1_1 = codeframe_likes,
a22 = "Overall quality. VSX123",
b22 = "Overall quality. SDF456",
a22 = num_lab("
1 Extremely poor
2 Very poor
3 Quite poor
4 Neither good, nor poor
5 Quite good
6 Very good
7 Excellent
"),
b22 = val_lab(a22)
)
expect_error(
pr_t %>%
tab_cells(mrset(a1_1 %to% a1_6), a22) %>%
tab_cols(mrset(b1_1 %to% b1_6), b22) %>%
tab_stat_cases(
total_statistic = c("u_cases", "u_repsonses", "u_cpct", "u_cpct_repsonses", "u_rpct", "u_tpct",
"w_cases", "w_repsonses", "w_cpct", "w_cpct_repsonses", "w_rpct", "w_tpct"
)) %>%
tab_pivot()
)
res = pr_t %>%
tab_cells(mrset(a1_1 %to% a1_6), a22) %>%
tab_cols(mrset(b1_1 %to% b1_6), b22) %>%
tab_stat_cases(
total_statistic = c("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct",
"w_cases", "w_responses", "w_cpct", "w_rpct", "w_tpct"
)) %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable20_1.rds", update = FALSE
)
res = pr_t %>% cross_cases(list(mrset(a1_1 %to% a1_6), a22),
list(mrset(b1_1 %to% b1_6), b22),
total_statistic = c("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct",
"w_cases", "w_responses", "w_cpct", "w_rpct", "w_tpct")
)
expect_known_value(
res,
"rds/ctable20_1.rds", update = FALSE
)
res = pr_t %>% cross_cases(list(mrset(a1_1 %to% a1_6), a22),
list(mrset(b1_1 %to% b1_6), b22),
weight = 1,
total_statistic = c("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct")
)
expect_known_value(
res,
"rds/ctable20_1a.rds", update = FALSE
)
res = pr_t %>%
tab_total_statistic("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct",
"w_cases", "w_responses", "w_cpct", "w_rpct", "w_tpct") %>%
tab_cells(mrset(a1_1 %to% a1_6), a22) %>%
tab_cols(mrset(b1_1 %to% b1_6), b22) %>%
tab_stat_cases() %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable20_1.rds", update = FALSE
)
res = pr_t %>%
tab_weight(wgt) %>%
tab_cells(mrset(a1_1 %to% a1_6), a22) %>%
tab_cols(mrset(b1_1 %to% b1_6), b22) %>%
tab_stat_cases(
total_statistic = c("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct",
"w_cases", "w_responses", "w_cpct", "w_rpct", "w_tpct"
)) %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable21.rds", update = FALSE
)
res = pr_t %>%
tab_weight(wgt) %>%
tab_cells(mrset(a1_1 %to% a1_6), a22) %>%
tab_cols(mrset(b1_1 %to% b1_6), b22) %>%
tab_stat_cpct(
total_statistic = c("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct",
"w_cases", "w_responses", "w_cpct", "w_rpct", "w_tpct"
)) %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable22.rds", update = FALSE
)
res = pr_t %>%
tab_weight(wgt) %>%
tab_cells(mrset(a1_1 %to% a1_6), a22) %>%
tab_cols(mrset(b1_1 %to% b1_6), b22) %>%
tab_stat_rpct(
total_statistic = c("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct",
"w_cases", "w_responses", "w_cpct", "w_rpct", "w_tpct"
)) %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable23.rds", update = FALSE
)
res = pr_t %>%
tab_weight(wgt) %>%
tab_cells(mrset(a1_1 %to% a1_6), a22) %>%
tab_cols(mrset(b1_1 %to% b1_6), b22) %>%
tab_stat_tpct(
total_statistic = c("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct",
"w_cases", "w_responses", "w_cpct", "w_rpct", "w_tpct"
)) %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable24.rds", update = FALSE
)
res = pr_t %>%
tab_weight(wgt) %>%
tab_cells(mrset(a1_1 %to% a1_6), a22) %>%
tab_cols(mrset(b1_1 %to% b1_6), b22) %>%
tab_stat_cpct_responses(
total_statistic = c("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct",
"w_cases", "w_responses", "w_cpct", "w_rpct", "w_tpct"
)) %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable25.rds", update = FALSE
)
res = pr_t %>%
tab_weight(wgt) %>%
tab_cols(drop_unused_labels(a22), drop_unused_labels(b22)) %>%
tab_cells(mrset(a1_1 %to% a1_6)) %>%
tab_stat_cpct_responses(
total_statistic = c("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct",
"w_cases", "w_responses", "w_cpct", "w_rpct", "w_tpct"
)) %>%
tab_sort_desc() %>%
tab_cells(mrset(b1_1 %to% b1_6)) %>%
tab_stat_cpct_responses(
total_statistic = c("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct",
"w_cases", "w_responses", "w_cpct", "w_rpct", "w_tpct"
)) %>%
tab_sort_asc() %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable25_sorting.rds", update = FALSE
)
res = pr_t %>%
tab_weight(wgt) %>%
tab_cols(drop_unused_labels(a22), drop_unused_labels(b22)) %>%
tab_cells(mrset(a1_1 %to% a1_6)) %>%
tab_total_statistic("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct",
"w_cases", "w_responses", "w_cpct", "w_rpct", "w_tpct") %>%
tab_stat_cpct_responses() %>%
tab_sort_desc() %>%
tab_cells(mrset(b1_1 %to% b1_6)) %>%
tab_stat_cpct_responses() %>%
tab_sort_asc() %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable25_sorting.rds", update = FALSE
)
res = pr_t %>%
tab_weight(wgt) %>%
tab_cols(drop_unused_labels(a22), drop_unused_labels(b22)) %>%
tab_cells(mrset(a1_1 %to% a1_6)) %>%
tab_total_statistic("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct",
"w_cases", "w_responses", "w_cpct", "w_rpct", "w_tpct") %>%
tab_stat_cpct_responses() %>%
tab_sort_desc() %>%
tab_cells(mrset(b1_1 %to% b1_6)) %>%
tab_total_label("Wow! responses") %>%
tab_stat_cpct_responses(total_statistic = "u_cases") %>%
tab_sort_asc() %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable25_different_total.rds", update = FALSE
)
res = pr_t %>%
tab_weight(wgt) %>%
tab_cols(drop_unused_labels(a22), drop_unused_labels(b22)) %>%
tab_cells(mrset(a1_1 %to% a1_6)) %>%
tab_total_statistic("u_cases", "u_responses", "u_cpct", "u_rpct", "u_tpct",
"w_cases", "w_responses", "w_cpct", "w_rpct", "w_tpct") %>%
tab_stat_cpct_responses() %>%
tab_sort_desc() %>%
tab_cells(mrset(b1_1 %to% b1_6)) %>%
tab_total_label(paste0("Wow! responses ", var_lab(a22))) %>%
tab_stat_cpct_responses(total_statistic = "u_cases") %>%
tab_sort_asc() %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable25_different_total2.rds", update = FALSE
)
res = mtcars %>%
tab_cells(qsec, mpg) %>%
tab_stat_fun(my_fun = w_mean, w_median) %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable26.rds", update = FALSE
)
res = mtcars %>%
tab_cells(vars(qc(mpg, qsec, hp, disp))) %>%
tab_rows(am) %>%
tab_cols(vs) %>%
tab_stat_fun_df(w_cor) %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable27.rds", update = FALSE
)
res = mtcars %>%
tab_cells(vars(qc(mpg, qsec, hp, disp))) %>%
tab_rows(am %nest% vs) %>%
tab_stat_fun_df(w_cor) %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable28.rds", update = FALSE
)
res = mtcars %>% tab_cells() %>%
tab_rows() %>%
tab_cols() %>%
tab_stat_cases() %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable29.rds", update = FALSE
)
res = mtcars %>%
tab_cells(vars(qc(mpg, qsec, hp, disp))) %>%
tab_rows(am %nest% vs) %>%
tab_stat_fun_df(sum = colSums, mean = colMeans, method = list) %>%
tab_pivot()
expect_known_value(
res,
"rds/ctable30.rds", update = FALSE
)
res = mtcars %>%
tab_cells(mpg, qsec, hp, disp) %>%
tab_weight(wt) %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "inside_columns", stat_label = "outside")
expect_known_value(res, "rds/ctable31.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, qsec, hp, disp) %>%
tab_weight(wt) %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "inside_rows", stat_label = "outside")
expect_known_value(res, "rds/ctable32.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, qsec, hp, disp) %>%
tab_weight(wt) %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "outside_rows", stat_label = "outside")
expect_known_value(res, "rds/ctable33.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, qsec, hp, disp) %>%
tab_cols(total(), am, vs) %>%
tab_weight(wt) %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "outside_columns", stat_label = "outside")
expect_known_value(res, "rds/ctable34.rds", update = FALSE)
mtcars2 = mtcars
mtcars2$am = unvr(mtcars2$am)
res = mtcars2 %>%
tab_cells(mpg, qsec, hp, disp) %>%
tab_cols(total(), "My am" = am) %>%
tab_weight(wt) %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max() %>%
tab_pivot(stat_position = "outside_columns", stat_label = "outside")
expect_known_value(res, "rds/ctable35.rds", update = FALSE)
mtcars2$vs = unvr(mtcars2$vs)
res = mtcars2 %>%
tab_cells("My vs" = vs) %>%
tab_cols(total(), "My am" = am) %>%
tab_stat_cpct() %>%
tab_pivot()
expect_known_value(res, "rds/ctable36.rds", update = FALSE)
res = mtcars %>%
tab_cells(mpg, qsec, hp, disp) %>%
tab_weight(wt) %>%
tab_stat_mean() %>%
tab_stat_median() %>%
tab_stat_sd() %>%
tab_stat_sum() %>%
tab_stat_se() %>%
tab_stat_unweighted_valid_n() %>%
tab_stat_valid_n() %>%
tab_stat_min() %>%
tab_stat_max()
expect_output_file(print(res), "rds/print_intermediate_table.txt")
context("custom tables error")
expect_error(
mtcars %>% tab_stat_cases()
)
expect_error(
mtcars %>% tab_stat_cpct()
)
expect_error(
mtcars %>% tab_stat_cpct_responses()
)
expect_error(
mtcars %>% tab_stat_rpct()
)
expect_error(
mtcars %>% tab_stat_tpct()
)
expect_error(
mtcars %>% tab_stat_fun()
)
expect_error(
mtcars %>% tab_stat_fun_df()
)
expect_error(
mtcars %>% tab_cells(am) %>% tab_pivot()
)
expect_error(
mtcars %>% tab_pivot()
)
expect_error(
1:5 %>% tab_cells(42)
)
context("custom table long expression as argument")
res = mtcars %>%
tab_cells(list(am, am, am, am, am, am, am, am, am, am, am, am, am, am, am, am)) %>%
tab_stat_mean() %>%
tab_pivot()
expect_known_value(res, "rds/ctable37.rds", update = FALSE)
res = mtcars %>%
tab_total_row_position("above") %>%
tab_total_statistic("u_cases", "u_rpct") %>%
tab_total_label(paste(var_lab(mpg), c("unw. cases", "unw. row pct."))) %>%
tab_cells(am) %>%
tab_cols(vs) %>%
tab_stat_cases() %>%
tab_pivot()
res2 = mtcars %>%
tab_cells(am) %>%
tab_cols(vs) %>%
tab_stat_cases(total_row_position = "above",
total_statistic = c("u_cases", "u_rpct"),
total_label = paste(var_lab(mtcars$mpg), c("unw. cases", "unw. row pct."))) %>%
tab_pivot()
expect_identical(res, res2)
res = mtcars %>%
tab_total_statistic("u_cases", "u_rpct") %>%
tab_total_row_position("above") %>%
tab_total_label(paste(var_lab(mpg), c("unw. cases", "unw. row pct."))) %>%
tab_cells(am) %>%
tab_cols(vs) %>%
tab_stat_cpct() %>%
tab_pivot()
res2 = mtcars %>%
tab_cells(am) %>%
tab_cols(vs) %>%
tab_stat_cpct(total_row_position = "above",
total_statistic = c("u_cases", "u_rpct"),
total_label = paste(var_lab(mtcars$mpg), c("unw. cases", "unw. row pct."))) %>%
tab_pivot()
expect_identical(res, res2)
res = mtcars %>%
tab_total_label(paste(var_lab(mpg), c("unw. cases", "unw. row pct."))) %>%
tab_total_statistic("u_cases", "u_rpct") %>%
tab_total_row_position("above") %>%
tab_cells(am) %>%
tab_cols(vs) %>%
tab_stat_tpct() %>%
tab_pivot()
res2 = mtcars %>%
tab_cells(am) %>%
tab_cols(vs) %>%
tab_stat_tpct(total_row_position = "above",
total_statistic = c("u_cases", "u_rpct"),
total_label = paste(var_lab(mtcars$mpg), c("unw. cases", "unw. row pct."))) %>%
tab_pivot()
expect_identical(res, res2)
res = mtcars %>%
tab_total_label(paste(var_lab(mpg), c("unw. cases", "unw. row pct."))) %>%
tab_total_statistic("u_cases", "u_rpct") %>%
tab_total_row_position("above") %>%
tab_cells(am) %>%
tab_cols(vs) %>%
tab_stat_rpct() %>%
tab_pivot()
res2 = mtcars %>%
tab_cells(am) %>%
tab_cols(vs) %>%
tab_stat_rpct(total_row_position = "above",
total_statistic = c("u_cases", "u_rpct"),
total_label = paste(var_lab(mtcars$mpg), c("unw. cases", "unw. row pct."))) %>%
tab_pivot()
expect_identical(res, res2)
res = mtcars %>%
tab_total_label(paste(var_lab(mpg), c("unw. cases", "unw. row pct."))) %>%
tab_total_statistic("u_cases", "u_rpct") %>%
tab_total_row_position("above") %>%
tab_cells(am) %>%
tab_cols(vs) %>%
tab_stat_cpct_responses() %>%
tab_pivot()
res2 = mtcars %>%
tab_cells(am) %>%
tab_cols(vs) %>%
tab_stat_cpct_responses(total_row_position = "above",
total_statistic = c("u_cases", "u_rpct"),
total_label = paste(var_lab(mtcars$mpg), c("unw. cases", "unw. row pct."))) %>%
tab_pivot()
expect_identical(res, res2)
for(each_stat in c(tab_stat_cases, tab_stat_cpct,
tab_stat_cpct_responses, tab_stat_rpct, tab_stat_tpct)){
res = mtcars %>%
tab_total_label(paste(var_lab(mpg), c("unw. cases", "unw. row pct."))) %>%
tab_total_statistic("u_cases", "u_rpct") %>%
tab_total_row_position("above") %>%
tab_cells(am) %>%
tab_cols(vs) %>%
tab_total_label() %>%
tab_total_statistic() %>%
tab_total_row_position() %>%
each_stat() %>%
tab_pivot()
res2 = mtcars %>%
tab_cells(am) %>%
tab_cols(vs) %>%
each_stat() %>%
tab_pivot()
expect_identical(res, res2)
}
res = mtcars %>%
tab_row_label("Table!", "Start!") %>%
tab_cells(vs) %>%
tab_cols(total(), am) %>%
tab_stat_mean() %>%
tab_row_label("Wow! Percent! %%%", label = var_lab(vs)) %>%
tab_stat_cpct(total_row_position = "none") %>%
tab_row_label(var_lab(am), var_lab(mpg)) %>%
tab_row_label("
tab_pivot()
expect_known_value(res, "rds/ctable38.rds", update = FALSE)
res = mtcars %>%
tab_cells(vs) %>%
tab_cols(total(), am) %>%
tab_stat_mean() %>%
tab_row_label("Wow! Percent! %%%") %>%
tab_stat_cpct() %>%
tab_pivot()
context("tab_last_vstack/tab_last_hstack")
res = pr_t %>% tab_cols(total(), age_cat) %>%
tab_cells("Mean" = unlab(a22)) %>%
tab_stat_mean(label = var_lab(a22)) %>%
tab_cells("Mean" = unlab(b22)) %>%
tab_stat_mean(label = var_lab(b22)) %>%
tab_last_hstack(stat_position = "inside_columns") %>%
tab_cells("Column %" = unlab(a22)) %>%
tab_stat_cpct(label = var_lab(a22)) %>%
tab_cells("Column %" = unlab(b22)) %>%
tab_stat_cpct(label = var_lab(b22)) %>%
tab_last_hstack(stat_position = "inside_columns") %>%
tab_pivot() %>%
make_subheadings()
expect_known_value(
res,
"rds/ctable40.rds", update = FALSE
)
res = pr_t %>% tab_cols(total(), age_cat) %>%
tab_cells("Mean" = unlab(a22)) %>%
tab_stat_mean(label = var_lab(a22)) %>%
tab_cells("Mean" = unlab(b22)) %>%
tab_stat_mean(label = var_lab(b22)) %>%
tab_last_hstack(stat_position = "outside_columns",
stat_label = "outside") %>%
tab_cells("Column %" = unlab(a22)) %>%
tab_stat_cpct(label = var_lab(a22)) %>%
tab_cells("Column %" = unlab(b22)) %>%
tab_stat_cpct(label = var_lab(b22)) %>%
tab_last_hstack(stat_position = "outside_columns",
stat_label = "outside") %>%
tab_pivot() %>%
make_subheadings()
expect_known_value(
res,
"rds/ctable41.rds", update = FALSE
)
}
|
(M = matrix( 1:12, ncol=3))
prop.table(M)
round(prop.table(M),2)
round(prop.table(M,1),2)
round(prop.table(M,2),2)
addmargins(prop.table(M))
addmargins(round(prop.table(M),2))
addmargins(round(prop.table(M),2),1)
addmargins(round(prop.table(M),2),2)
addmargins(round(prop.table(M),2),3)
margin.table(round(prop.table(M),2))
margin.table(round(prop.table(M),2),1)
margin.table(round(prop.table(M),2),2)
|
predictor <- function(prep, ...) {
UseMethod("predictor")
}
predictor.bprepl <- function(prep, i = NULL, fprep = NULL, ...) {
nobs <- ifelse(!is.null(i), length(i), prep$nobs)
eta <- matrix(0, nrow = prep$ndraws, ncol = nobs) +
predictor_fe(prep, i) +
predictor_re(prep, i) +
predictor_sp(prep, i) +
predictor_sm(prep, i) +
predictor_gp(prep, i) +
predictor_offset(prep, i, nobs)
eta <- predictor_ac(eta, prep, i, fprep = fprep)
eta <- predictor_cs(eta, prep, i)
unname(eta)
}
predictor.bprepnl <- function(prep, i = NULL, fprep = NULL, ...) {
stopifnot(!is.null(fprep))
nlpars <- prep$used_nlpars
covars <- names(prep$C)
args <- named_list(c(nlpars, covars))
for (nlp in nlpars) {
args[[nlp]] <- get_nlpar(fprep, nlpar = nlp, i = i, ...)
}
for (cov in covars) {
args[[cov]] <- p(prep$C[[cov]], i, row = FALSE)
}
dim_eta <- dim(rmNULL(args)[[1]])
if (!prep$loop) {
for (i in seq_along(args)) {
args[[i]] <- split(args[[i]], row(args[[i]]))
}
.fun <- function(...) eval(prep$nlform, list(...))
eta <- try(
t(do_call(mapply, c(list(FUN = .fun, SIMPLIFY = "array"), args))),
silent = TRUE
)
} else {
eta <- try(eval(prep$nlform, args), silent = TRUE)
}
if (is(eta, "try-error")) {
if (grepl("could not find function", eta)) {
eta <- rename(eta, "Error in eval(expr, envir, enclos) : ", "")
vectorize <- str_if(prep$loop, ", vectorize = TRUE")
message(
eta, " Most likely this is because you used a Stan ",
"function in the non-linear model formula that ",
"is not defined in R. If this is a user-defined function, ",
"please run 'expose_functions(.", vectorize, ")' ",
"on your fitted model and try again."
)
} else {
eta <- rename(eta, "^Error :", "", fixed = FALSE)
stop2(eta)
}
}
dim(eta) <- dim_eta
unname(eta)
}
predictor_fe <- function(prep, i) {
fe <- prep[["fe"]]
if (!isTRUE(ncol(fe[["X"]]) > 0)) {
return(0)
}
eta <- try(.predictor_fe(X = p(fe[["X"]], i), b = fe[["b"]]))
if (is(eta, "try-error")) {
stop2(
"Something went wrong (see the error message above). ",
"Perhaps you transformed numeric variables ",
"to factors or vice versa within the model formula? ",
"If yes, please convert your variables beforehand. ",
"Or did you set a predictor variable to NA?"
)
}
eta
}
.predictor_fe <- function(X, b) {
stopifnot(is.matrix(X))
stopifnot(is.matrix(b))
tcrossprod(b, X)
}
predictor_re <- function(prep, i) {
eta <- 0
re <- prep[["re"]]
group <- names(re[["r"]])
for (g in group) {
eta_g <- try(.predictor_re(Z = p(re[["Z"]][[g]], i), r = re[["r"]][[g]]))
if (is(eta_g, "try-error")) {
stop2(
"Something went wrong (see the error message above). ",
"Perhaps you transformed numeric variables ",
"to factors or vice versa within the model formula? ",
"If yes, please convert your variables beforehand. ",
"Or did you use a grouping factor also for a different purpose? ",
"If yes, please make sure that its factor levels are correct ",
"also in the new data you may have provided."
)
}
eta <- eta + eta_g
}
eta
}
.predictor_re <- function(Z, r) {
Matrix::as.matrix(Matrix::tcrossprod(r, Z))
}
predictor_sp <- function(prep, i) {
eta <- 0
sp <- prep[["sp"]]
if (!length(sp)) {
return(eta)
}
eval_list <- list()
for (j in seq_along(sp[["simo"]])) {
eval_list[[paste0("Xmo_", j)]] <- p(sp[["Xmo"]][[j]], i)
eval_list[[paste0("simo_", j)]] <- sp[["simo"]][[j]]
}
for (j in seq_along(sp[["Xme"]])) {
eval_list[[paste0("Xme_", j)]] <- p(sp[["Xme"]][[j]], i, row = FALSE)
}
for (j in seq_along(sp[["Yl"]])) {
eval_list[[names(sp[["Yl"]])[j]]] <- p(sp[["Yl"]][[j]], i, row = FALSE)
}
for (j in seq_along(sp[["idxl"]])) {
eval_list[[names(sp[["idxl"]])[j]]] <- p(sp[["idxl"]][[j]], i, row = FALSE)
}
for (j in seq_along(sp[["Csp"]])) {
eval_list[[paste0("Csp_", j)]] <- p(sp[["Csp"]][[j]], i, row = FALSE)
}
re <- prep[["re"]]
coef <- colnames(sp[["bsp"]])
for (j in seq_along(coef)) {
rsp <- named_list(names(re[["rsp"]][[coef[j]]]))
for (g in names(rsp)) {
rsp[[g]] <- .predictor_re(
Z = p(re[["Zsp"]][[g]], i),
r = re[["rsp"]][[coef[j]]][[g]]
)
}
eta <- eta + .predictor_sp(
eval_list, call = sp[["calls"]][[j]],
b = sp[["bsp"]][, j],
r = Reduce("+", rsp)
)
}
eta
}
.predictor_sp <- function(eval_list, call, b, r = NULL) {
b <- as.vector(b)
if (is.null(r)) r <- 0
(b + r) * eval(call, eval_list)
}
.mo <- function(simplex, X) {
stopifnot(is.matrix(simplex), is.atomic(X))
D <- NCOL(simplex)
simplex <- cbind(0, simplex)
for (i in seq_cols(simplex)[-1]) {
simplex[, i] <- simplex[, i] + simplex[, i - 1]
}
D * simplex[, X + 1]
}
predictor_sm <- function(prep, i) {
eta <- 0
if (!length(prep[["sm"]])) {
return(eta)
}
fe <- prep[["sm"]]$fe
if (length(fe)) {
eta <- eta + .predictor_fe(X = p(fe$Xs, i), b = fe$bs)
}
re <- prep[["sm"]]$re
for (k in seq_along(re)) {
for (j in seq_along(re[[k]]$s)) {
Zs <- p(re[[k]]$Zs[[j]], i)
s <- re[[k]]$s[[j]]
eta <- eta + .predictor_fe(X = Zs, b = s)
}
}
eta
}
predictor_gp <- function(prep, i) {
if (!length(prep[["gp"]])) {
return(0)
}
if (!is.null(i)) {
stop2("Pointwise evaluation is not supported for Gaussian processes.")
}
eta <- matrix(0, nrow = prep$ndraws, ncol = prep$nobs)
for (k in seq_along(prep[["gp"]])) {
gp <- prep[["gp"]][[k]]
if (isTRUE(attr(gp, "byfac"))) {
for (j in seq_along(gp)) {
if (length(gp[[j]][["Igp"]])) {
eta[, gp[[j]][["Igp"]]] <- .predictor_gp(gp[[j]])
}
}
} else {
eta <- eta + .predictor_gp(gp)
}
}
eta
}
.predictor_gp <- function(gp) {
if (is.null(gp[["slambda"]])) {
ndraws <- length(gp[["sdgp"]])
eta <- as.list(rep(NA, ndraws))
if (!is.null(gp[["x_new"]])) {
for (i in seq_along(eta)) {
eta[[i]] <- with(gp, .predictor_gp_new(
x_new = x_new, yL = yL[i, ], x = x,
sdgp = sdgp[i], lscale = lscale[i, ], nug = nug
))
}
} else {
for (i in seq_along(eta)) {
eta[[i]] <- with(gp, .predictor_gp_old(
x = x, sdgp = sdgp[i], lscale = lscale[i, ],
zgp = zgp[i, ], nug = nug
))
}
}
eta <- do_call(rbind, eta)
} else {
eta <- with(gp, .predictor_gpa(
x = x, sdgp = sdgp, lscale = lscale,
zgp = zgp, slambda = slambda
))
}
if (!is.null(gp[["Jgp"]])) {
eta <- eta[, gp[["Jgp"]], drop = FALSE]
}
if (!is.null(gp[["Cgp"]])) {
eta <- eta * data2draws(gp[["Cgp"]], dim = dim(eta))
}
eta
}
.predictor_gp_old <- function(x, sdgp, lscale, zgp, nug) {
Sigma <- cov_exp_quad(x, sdgp = sdgp, lscale = lscale)
lx <- nrow(x)
Sigma <- Sigma + diag(rep(nug, lx), lx, lx)
L_Sigma <- try_nug(t(chol(Sigma)), nug = nug)
as.numeric(L_Sigma %*% zgp)
}
.predictor_gp_new <- function(x_new, yL, x, sdgp, lscale, nug) {
Sigma <- cov_exp_quad(x, sdgp = sdgp, lscale = lscale)
lx <- nrow(x)
lx_new <- nrow(x_new)
Sigma <- Sigma + diag(rep(nug, lx), lx, lx)
L_Sigma <- try_nug(t(chol(Sigma)), nug = nug)
L_Sigma_inverse <- solve(L_Sigma)
K_div_yL <- L_Sigma_inverse %*% yL
K_div_yL <- t(t(K_div_yL) %*% L_Sigma_inverse)
k_x_x_new <- cov_exp_quad(x, x_new, sdgp = sdgp, lscale = lscale)
mu_yL_new <- as.numeric(t(k_x_x_new) %*% K_div_yL)
v_new <- L_Sigma_inverse %*% k_x_x_new
cov_yL_new <- cov_exp_quad(x_new, sdgp = sdgp, lscale = lscale) -
t(v_new) %*% v_new + diag(rep(nug, lx_new), lx_new, lx_new)
yL_new <- try_nug(
rmulti_normal(1, mu = mu_yL_new, Sigma = cov_yL_new),
nug = nug
)
return(yL_new)
}
.predictor_gpa <- function(x, sdgp, lscale, zgp, slambda) {
spd <- sqrt(spd_cov_exp_quad(slambda, sdgp, lscale))
(spd * zgp) %*% t(x)
}
predictor_cs <- function(eta, prep, i) {
cs <- prep[["cs"]]
re <- prep[["re"]]
if (!length(cs[["bcs"]]) && !length(re[["rcs"]])) {
return(eta)
}
nthres <- cs[["nthres"]]
rcs <- NULL
if (!is.null(re[["rcs"]])) {
groups <- names(re[["rcs"]])
rcs <- vector("list", nthres)
for (k in seq_along(rcs)) {
rcs[[k]] <- named_list(groups)
for (g in groups) {
rcs[[k]][[g]] <- .predictor_re(
Z = p(re[["Zcs"]][[g]], i),
r = re[["rcs"]][[g]][[k]]
)
}
rcs[[k]] <- Reduce("+", rcs[[k]])
}
}
.predictor_cs(
eta, X = p(cs[["Xcs"]], i),
b = cs[["bcs"]], nthres = nthres, r = rcs
)
}
.predictor_cs <- function(eta, X, b, nthres, r = NULL) {
stopifnot(is.null(X) && is.null(b) || is.matrix(X) && is.matrix(b))
nthres <- max(nthres)
eta <- predictor_expand(eta, nthres)
if (!is.null(X)) {
I <- seq(1, (nthres) * ncol(X), nthres) - 1
X <- t(X)
}
for (k in seq_len(nthres)) {
if (!is.null(X)) {
eta[, , k] <- eta[, , k] + b[, I + k, drop = FALSE] %*% X
}
if (!is.null(r[[k]])) {
eta[, , k] <- eta[, , k] + r[[k]]
}
}
eta
}
predictor_expand <- function(eta, nthres) {
if (length(dim(eta)) == 2L) {
eta <- array(eta, dim = c(dim(eta), nthres))
}
eta
}
predictor_offset <- function(prep, i, nobs) {
if (is.null(prep$offset)) {
return(0)
}
eta <- rep(p(prep$offset, i), prep$ndraws)
matrix(eta, ncol = nobs, byrow = TRUE)
}
predictor_ac <- function(eta, prep, i, fprep = NULL) {
if (has_ac_class(prep$ac$acef, "arma")) {
if (!is.null(prep$ac$err)) {
eta <- eta + p(prep$ac$err, i, row = FALSE)
} else {
if (!is.null(i)) {
stop2("Pointwise evaluation is not possible for ARMA models.")
}
eta <- .predictor_arma(
eta, ar = prep$ac$ar, ma = prep$ac$ma,
Y = prep$ac$Y, J_lag = prep$ac$J_lag,
fprep = fprep
)
}
}
if (has_ac_class(prep$ac$acef, "car")) {
eta <- eta + .predictor_re(Z = p(prep$ac$Zcar, i), r = prep$ac$rcar)
}
eta
}
.predictor_arma <- function(eta, ar = NULL, ma = NULL, Y = NULL, J_lag = NULL,
fprep = NULL) {
if (is.null(ar) && is.null(ma)) {
return(eta)
}
if (anyNA(Y)) {
stopifnot(is.brmsprep(fprep) || is.mvbrmsprep(fprep))
pp_fun <- paste0("posterior_predict_", fprep$family$fun)
pp_fun <- get(pp_fun, asNamespace("brms"))
}
S <- nrow(eta)
N <- length(Y)
max_lag <- max(J_lag, 1)
Kar <- ifelse(is.null(ar), 0, ncol(ar))
Kma <- ifelse(is.null(ma), 0, ncol(ma))
take_ar <- seq_len(min(Kar, max_lag))
take_ma <- seq_len(min(Kma, max_lag))
ar <- ar[, take_ar, drop = FALSE]
ma <- ma[, take_ma, drop = FALSE]
Err <- array(0, dim = c(S, max_lag, max_lag + 1))
err <- zero_mat <- matrix(0, nrow = S, ncol = max_lag)
zero_vec <- rep(0, S)
for (n in seq_len(N)) {
if (Kma) {
eta[, n] <- eta[, n] + rowSums(ma * Err[, take_ma, max_lag])
}
eta_before_ar <- eta[, n]
if (Kar) {
eta[, n] <- eta[, n] + rowSums(ar * Err[, take_ar, max_lag])
}
y <- Y[n]
if (is.na(y)) {
fprep$dpars$mu <- eta
y <- pp_fun(n, fprep)
}
err[, max_lag] <- y - eta_before_ar
if (J_lag[n] > 0) {
I <- seq_len(J_lag[n])
Err[, I, max_lag + 1] <- err[, max_lag + 1 - I]
}
Err <- abind(Err[, , -1, drop = FALSE], zero_mat)
err <- cbind(err[, -1, drop = FALSE], zero_vec)
}
eta
}
|
mtabulate <- function(m, code=FALSE){
data.frame(
code = get_code(m) %>% vapply(FUN.VALUE=character(1), paste0, collapse="\n"),
id = get_id(m) %>% as.numeric,
OK = get_OK(m),
cached = has_value(m),
time = get_time(m) %>% vapply(FUN.VALUE=numeric(1), function(x) { signif(.[1], 2) }),
space = get_mem(m),
is_nested = get_nest(m) %>% vapply(FUN.VALUE=integer(1), length),
ndependents = get_dependents(m) %>% vapply(FUN.VALUE=integer(1), length),
nnotes = get_notes(m) %>% vapply(FUN.VALUE=integer(1), length),
nwarnings = get_warnings(m) %>% vapply(FUN.VALUE=integer(1), length),
error = get_error(m) %>% vapply(FUN.VALUE=integer(1), length),
doc = get_doc(m) %>% vapply(FUN.VALUE=integer(1), length)
) %>% {
if(!code)
.$code <- NULL
.
}
}
missues <- function(m){
error_len <- get_error(m) %>% vapply(FUN.VALUE=integer(1), length)
warning_len <- get_warnings(m) %>% vapply(FUN.VALUE=integer(1), length)
note_len <- get_notes(m) %>% vapply(FUN.VALUE=integer(1), length)
ids <- get_id(m) %>% {c(
rep(., times=error_len),
rep(., times=warning_len),
rep(., times=note_len)
)}
error <- get_error(m) %>% unlist %>% as.character
warnings <- get_warnings(m) %>% unlist %>% as.character
notes <- get_notes(m) %>% unlist %>% as.character
data.frame(
id = ids,
type = c(
rep("error", length(error)),
rep("warning", length(warnings)),
rep("note", length(notes))
),
issue = c(error, warnings, notes)
)
}
esc <- function(m, quiet=FALSE){
.quiet_warning <- function(code, msg) warning(msg, call.=FALSE)
.quiet_note <- function(code, msg) message(msg)
.quiet_error <- function(code, msg) stop(msg, call.=FALSE)
.unquiet_warning <- function(code, msg) {
warning("in '", code, "': ", msg, call.=FALSE)
}
.unquiet_note <- function(code, msg) {
message(msg)
}
.unquiet_error <- function(code, msg) {
stop(paste0('in "', code, '":\n ', msg), call.=FALSE)
}
mtab <- mtabulate(m, code=TRUE)
issues <- missues(m) %>%
{ merge(mtab, .)[, c("code", "type", "issue")] }
if(quiet){
fw <- .quiet_warning
fn <- .quiet_note
fe <- .quiet_error
} else {
fw <- .unquiet_warning
fn <- .unquiet_note
fe <- .unquiet_error
}
for(i in seq_len(nrow(issues))){
if(issues[i, "type"] == "warning"){
fw(issues[i, "code"], issues[i, "issue"])
}
if(issues[i, "type"] == "note"){
fn(issues[i, "code"], issues[i, "issue"])
}
}
if(! .single_OK(m)){
fe(.single_code(m), .single_error(m))
}
.single_value(m)
}
report <- function(
m,
prefix='report'
){
dir <- tempdir()
m_path <- file.path(dir, 'rmonad.Rd')
r_path <- file.path(dir, 'report.Rmd')
md_path <- file.path(dir, paste0(prefix, ".md"))
saveRDS(m, m_path)
tostr <- function(x, prefix){
if(.is_not_empty_string(x)){
paste0(prefix, x, "\n", collapse="\n")
} else {
""
}
}
strsummary <- function(m, i){
summaries <- .single_summary(m, index=i)
headers <- if(!is.null(names(summaries))){
names(summaries)
} else {
paste('summary', letters[seq_along(summaries)])
}
vapply(FUN.VALUE=character(1),
seq_along(summaries),
function(j)
glue::glue(.open='{{', .close='}}',
"
```{r, echo=FALSE}
get_summary(m)[[{{i}}]][[{{j}}]]
```
"
)
) %>% paste(collapse="\n")
}
entries <- get_id(m) %>% vapply(FUN.VALUE=character(1), function(i)
glue::glue(.open='{{', .close='}}',
"
OK={{ok}} | parents={{parents}} | cached={{cached}} | time={{time}} | memory={{mem}}
{{doc}}
```{r, eval=FALSE}
{{code}}
```
{{error}}
{{warnings}}
{{notes}}
{{summary}}
",
id = i,
ok = .single_OK(m, index=i),
parents = paste0("[", paste(.single_parents(m, index=i), collapse=", "), "]"),
cached = has_value(m, index=i),
time = .single_time(m, index=i),
mem = .single_mem(m, index=i),
doc = tostr(.single_doc(m, index=i)),
code = paste0(.single_code(m, index=i), collapse="\n"),
error = tostr(.single_error(m, index=i), "ERROR: "),
warnings = tostr(.single_warnings(m, index=i), "WARNING: "),
notes = tostr(.single_notes(m, index=i), "NOTE: "),
summary = strsummary(m, i)
)) %>% paste0(collapse="\n")
rmd_str <- glue::glue(.open='{{', .close='}}',
"
```{r, echo=FALSE}
m <- readRDS('rmonad.Rd')
```
```{r, echo=FALSE}
library(rmonad)
library(knitr)
```
```{r, echo=FALSE}
plot(m)
```
```{r, results='asis', echo=FALSE}
kable(mtabulate(m))
```
```{r, results='asis', echo=FALSE}
kable(missues(m))
```
```{r, echo=FALSE}
print(m)
```
{{entries}}
",
entries=entries
)
write(rmd_str, file=r_path)
knitr::knit(input=r_path, output=md_path)
out_path <- knitr::pandoc(input=md_path, format='latex', ext='pdf')
file.copy(out_path, getwd(), overwrite=TRUE)
}
|
weightTSA <- function(Y, c, upper = TRUE, type="indicTh", param=1) {
if(is.data.frame(Y) == TRUE){
Y <- as.matrix(Y)
}
if (upper){
if (type == "indicTh") wY <- as.numeric(Y>c)
if (type == "zeroTh") wY <- Y * (Y>c)
if (type == "logistic") wY <- 1 / (1 + exp(-param * (Y-c) / abs(c)) )
if (type == "exp1side") wY <- exp( - (c-Y)*((c-Y)>0) / (param * sd(Y)/5) )
} else{
if (type == "indicTh") wY <- as.numeric(Y<c)
if (type == "zeroTh") wY <- Y * (Y<c)
if (type == "logistic") wY <- 1 / (1 + exp(-param * (c-Y) / abs(c)) )
if (type == "exp1side") wY <- exp( - (Y-c)*((Y-c)>0) / (param * sd(Y)/5) )
}
return(as.vector(wY))
}
|
Bird <- function(massTotal,wingSpan,wingArea,...) UseMethod('Bird')
Bird.data.frame <- function(massTotal,wingSpan,wingArea,...) {
df <- massTotal
massTotal <- .setDefault(df,'massTotal',NULL)
wingSpan <- df$wingSpan
wingArea <- .setDefault(df,'wingArea',NULL)
bird <- Bird.default(massTotal,wingSpan,wingArea,df)
}
Bird.default <- function(massTotal,wingSpan,wingArea=NULL,...) {
opts <- list(...)
if (length(opts)>0) if (class(opts[[1]])=='data.frame') opts <- opts[[1]];
bird <- data.frame(
wingSpan = wingSpan
)
if(!is.null(wingArea)) {
bird$wingArea <- wingArea
} else if (.hasField(opts,'wingAspect')) {
bird$wingArea <- .aspect2area(wingSpan,opts$wingAspect)
} else {
stop("I can't figure out the wing area... please provide wingArea or wingAspect")
}
bird$name <- .setDefault(opts,'name',NA)
bird$name.scientific <- .setDefault(opts,'name.scientific',NA)
bird$source <- .setDefault(opts,'source',NA)
if (!missing(massTotal)) {
bird$massTotal <- massTotal
}
bird <- .massComposition(bird,opts)
bird$muscleFraction <- .setDefault(opts,'muscleFraction',0.17)
bird$type <- .setDefault(opts,'type','other')
bird$bodyFrontalArea <- .setDefault(
opts,'bodyFrontalArea',
computeBodyFrontalArea( bird$massEmpty, bird$type )
)
bird$wingbeatFrequency <- .setDefault(opts,'wingbeatFrequency',
.estimateFrequency(bird)
)
bird$coef.profileDragLiftFactor <- .setDefault(opts,'coef.profileDragLiftFactor',0.03)
bird$coef.bodyDragCoefficient <- .setDefault(opts,'coef.bodyDragCoefficient',0.2)
bird$coef.conversionEfficiency <- .setDefault(opts,'coef.conversionEfficiency',0.23)
bird$coef.respirationFactor <- .setDefault(opts,'coef.respirationFactor',1.1)
bird$coef.activeStrain <- .setDefault(opts,'coef.activeStrain',0.26)
bird$coef.isometricStress <- .setDefault(opts,'coef.isometricStress',400E3)
bird$basalMetabolicRate <- .setDefault(opts,'basalMetabolicRate',.estimateBasalMetabolicRate(bird))
class(bird) <- append(class(bird),'bird')
return(bird)
}
.estimateFrequency <- function (bird,...) {
opts <- list(...)
rho <- .setDefault(opts,'density',1.225)
g <- .setDefault(opts,'gravity',9.81)
b <- bird$wingSpan
m <- bird$massEmpty
S <- bird$wingArea
m^(3/8)*sqrt(g)*b^(-23/24)*S^(-1/3)*rho^(-3/8)
}
.estimateBasalMetabolicRate <- function(bird,...) {
opts <- list(...)
type <- .setDefault(bird,'type','other')
massEmpty <- bird$massEmpty
isPasserine <- type == 'passerine'
isSeaBird <- type == 'seabird'
isBat <- type == 'bat'
isOther <- !(isPasserine | isSeaBird | isBat)
bmr <- 6.25*massEmpty^0.724 * isPasserine +
5.43*massEmpty^0.72 * isSeaBird +
3.14*massEmpty^0.744 * isBat +
3.79*massEmpty^0.723 * isOther
return(bmr)
}
.aspect2area <- function(wingSpan,wingAspect) wingSpan^2/wingAspect
.massComposition <- function(bird,opts) {
has.massTotal <- .hasField(bird,'massTotal')
has.massEmpty <- .hasField(opts,'massEmpty')
has.massFat <- .hasField(opts,'massFat')
has.massLoad <- .hasField(opts,'massLoad')
has.mass.count <- has.massTotal + has.massEmpty + has.massFat + has.massLoad
if ( has.mass.count == 4) {
bird$massEmpty <- opts$massEmpty
bird$massFat <- opts$massFat
bird$massLoad <- opts$massLoad
massSum = with(bird, massEmpty + massFat + massLoad )
if (bird$massTotal != massSum) {
bird$massTotal <- massSum
warning('Mismatch in mass composition. Recomputed total mass.')
}
} else if (has.mass.count == 3) {
if (!has.massTotal) {
bird$massEmpty <- opts$massEmpty
bird$massFat <- opts$massFat
bird$massLoad <- opts$massLoad
bird$massTotal <- with(bird, massEmpty + massFat + massLoad )
} else if (!has.massEmpty) {
bird$massFat <- opts$massFat
bird$massLoad <- opts$massLoad
bird$massEmpty <- with(bird, massTotal - massFat - massLoad )
} else if (!has.massLoad) {
bird$massFat <- opts$massFat
bird$massEmpty <- opts$massEmpty
bird$massLoad <- with(bird, massTotal - massFat - massEmpty )
} else if (!has.massFat) {
bird$massLoad <- opts$massLoad
bird$massEmpty <- opts$massEmpty
bird$massFat <- with(bird, massTotal - massEmpty - massLoad )
}
} else if (has.mass.count <= 2) {
has.massTotal
has.massEmpty
if (has.massTotal & has.massEmpty) {
bird$massLoad <- 0
bird$massEmpty <- opts$massEmpty
bird$massFat <- bird$massTotal - bird$massEmpty
} else if (has.massTotal | has.massEmpty) {
bird$massLoad <- .setDefault(opts,'massLoad',0)
bird$massFat <- .setDefault(opts,'massFat',0)
bird$massEmpty <- .setDefault(opts,'massEmpty',bird$massTotal)
bird$massTotal <- with(bird,massEmpty+massFat+massLoad)
} else {
stop("Can't resolve mass composition. Define at least massTotal or massEmpty.")
}
}
return(bird)
}
|
context("environment")
test_that("setting environment variables", {
set.sylly.env(lang="xy", hyph.cache.file="test", hyph.max.token.length=30)
expect_match(
get.sylly.env(lang=TRUE),
"xy"
)
expect_match(
get.sylly.env(hyph.cache.file=TRUE),
"test"
)
expect_identical(
get.sylly.env(hyph.max.token.length=TRUE),
30
)
})
context("pattern import")
test_that("import pattern file", {
samplePatternFile <- normalizePath("hyph-xy.pat.txt")
samplePatternStandard <- dget("hyph_xy_dput.txt")
hyph.xy <- read.hyph.pat(file=samplePatternFile, lang="xy")
expect_identical(
hyph.xy,
samplePatternStandard
)
})
context("pattern object handling")
test_that("debugging hyphenation", {
samplePatternStandard <- dget("hyph_xy_dput.txt")
sampleSplitStandard <- dget("mhp_split_dput.txt")
mhp_split <- manage.hyph.pat(hyph.pattern=samplePatternStandard, word="incomprehensibilities")
expect_identical(
mhp_split,
sampleSplitStandard
)
})
test_that("debugging hyphenation patterns", {
samplePatternStandard <- dget("hyph_xy_dput.txt")
sampleGetSetStandard <- dget("mhp_get_set_dput.txt")
mhp_get_old <- manage.hyph.pat(hyph.pattern=samplePatternStandard, get="xyz")
expect_is(
mhp_get_old,
"matrix"
)
expect_equal(
colnames(mhp_get_old),
c("orig", "char", "nums")
)
expect_equal(
nrow(mhp_get_old),
0
)
mhp_set <- manage.hyph.pat(hyph.pattern=samplePatternStandard, set="x3yz2")
mhp_get_new <- manage.hyph.pat(hyph.pattern=mhp_set, get="xyz")
expect_identical(
mhp_get_new,
sampleGetSetStandard
)
mhp_rm <- manage.hyph.pat(hyph.pattern=mhp_set, rm="xyz")
expect_identical(
mhp_rm,
samplePatternStandard
)
})
context("hyphenation")
test_that("hyphenation", {
samplePatternStandard <- dget("hyph_xy_dput.txt")
sampleHyphenStandard <- dget("hyphen_dput.txt")
sampleHyphenStandard_df <- hyphenText(sampleHyphenStandard)
sampleHyphenStandard_c <- sampleHyphenStandard[["syll"]]
hyph_result <- hyphen(
"incomprehensibilities",
hyph.pattern=samplePatternStandard,
cache=FALSE,
quiet=TRUE
)
hyph_result_df <- hyphen_df(
"incomprehensibilities",
hyph.pattern=samplePatternStandard,
cache=FALSE,
quiet=TRUE
)
hyph_result_c <- hyphen_c(
"incomprehensibilities",
hyph.pattern=samplePatternStandard,
cache=FALSE,
quiet=TRUE
)
expect_identical(
hyph_result,
sampleHyphenStandard
)
expect_identical(
hyph_result_df,
sampleHyphenStandard_df
)
expect_identical(
hyph_result_c,
sampleHyphenStandard_c
)
})
test_that("helper methods", {
sampleHyphenStandard <- dget("hyphen_dput.txt")
expect_identical(
language(sampleHyphenStandard),
"xy"
)
expect_identical(
describe(sampleHyphenStandard)[["num.syll"]],
8
)
})
test_that("fixing wrong hyphenation", {
sampleHyphenStandard <- dget("hyphen_dput.txt")
hyph_fixed <- correct.hyph(sampleHyphenStandard, "in-com-pre-hens-ib-il-it-ies", "in-co-mp-re-he-ns-ib-il-it-ie-s", cache=FALSE)
expect_equal(
hyphenText(hyph_fixed)[["syll"]],
11
)
})
|
date_stamp <- function(n, random = FALSE, x = NULL, start = Sys.Date(), k = 12,
by = "-1 months", prob = NULL, name = "Date"){
if (is.null(x)){
x <- seq(start, length = k, by = by)
}
if (!inherits(x, c("Date", "POSIXct", "POSIXt"))) warning("`x`may not a date vector")
out <- sample(x = x, size = n, replace = TRUE, prob = prob)
if (!random) out <- sort(out)
varname(out, name)
}
|
sim.snp.expsurv.power <-
function(GHR,B,n,raf,erate,pilm,lm,model,test,alpha,exactvar=FALSE,interval=c(0,10),rootint=c(0.1,200)) {
if(model=="additive") {
zmod=c(0,1,2)
}
else if(model=="recessive") {
zmod=c(0,0,1)
}
else if (model=="dominant") {
zmod=c(0,1,1)
}
else {
stop("Model not defined")
}
if(test=="additive") {
ztest=c(0,1,2)
}
else if(test=="recessive") {
ztest=c(0,0,1)
}
else if (test=="dominant") {
ztest=c(0,1,1)
}
else {
stop("Test not defined")
}
if(model!="additive") message('Note: For asymptotic calculations, only the "additive" model should be used.')
gtprev=hwe(raf)
lam=surv.exp.gt.model(pilm,lm,gtprev,GHR,zmod,interval)
b=censbnd(lam,gtprev,1-erate,rootint)$root
asypval=asypow(n,log(GHR),a=0,b,lam[1],raf,gtprev,alpha,zmod,exactvar)
if(B>0) {
pvals=replicate(B,sim.snp.expsurv.sctest(n,gtprev,lam,0,b,ztest))
powB=mean(pvals[2,]<alpha)
erateB=mean(pvals[1,])
}
else {
powB=NA
erateB=NA
}
if( all(zmod==ztest) ) {
data.frame(B=B,raf,q0=gtprev[1],q1=gtprev[2],q2=gtprev[3],lam0=lam[1],lam1=lam[2],lam2=lam[3],
GHR,pilm=gtprev[1]*exp(-lm*lam[1])+gtprev[2]*exp(-lm*lam[2])+gtprev[3]*exp(-lm*lam[3]),
lm,alpha,a=0,b,erate,erateB=erateB,n,powB=powB,pow=asypval[1],pow0=asypval[2],
v1=asypval[3],v2=asypval[4],v12=asypval[5])
}
else {
data.frame(B=B,raf,q0=gtprev[1],q1=gtprev[2],q2=gtprev[3],lam0=lam[1],lam1=lam[2],lam2=lam[3],
GHR,pilm=gtprev[1]*exp(-lm*lam[1])+gtprev[2]*exp(-lm*lam[2])+gtprev[3]*exp(-lm*lam[3]),
lm,alpha,a=0,b,erate,erateB=erateB,n,powB=powB,
v1=asypval[3],v2=asypval[4],v12=asypval[5])
}
}
|
create.prepared_list = function(assembled, x, Ytilde, sum_ysq, n) {
structure(list(
Ytilde = Ytilde,
sum_ysq = sum_ysq,
n = n,
s = lapply(assembled, getElement, name = "s"),
B = lapply(assembled, getElement, name = "B"),
Q = lapply(assembled, getElement, name = "Q"),
A = lapply(assembled, getElement, name = "A"),
U = lapply(assembled, getElement, name = "U"),
loglambda = rep(0, length(n)),
x = x
), class = "prepared_list")
}
|
spConsistency <- function(object, nblistw = NULL, window = NULL, nrep = 999, adj = FALSE) {
if(class(object)[[1]] == "FCMres"){
belongmat <- as.matrix(object$Belongings)
if(object$isRaster & is.null(window)){
window <- object$window
if(is.null(window)){
stop("impossible to find a window in the given object, please
specify one by hand.")
}
}
if(object$isRaster == FALSE & is.null(nblistw)){
nblistw <- object$nblistw
}
}else{
belongmat <- as.matrix(object)
}
if(is.null(window)){
if(is.null(nblistw)){
stop("The nblistw must be provided if spatial vector data is used")
}
weights <- nblistw$weights
neighbours <- nblistw$neighbours
obsdev <- sapply(1:nrow(belongmat), function(i) {
row <- belongmat[i, ]
idneighbour <- neighbours[[i]]
neighbour <- belongmat[idneighbour, ]
if (length(idneighbour) == 1){
neighbour <- t(as.matrix(neighbour))
}
W <- weights[[i]]
diff <- (neighbour-row[col(neighbour)])**2
tot <- sum(rowSums(diff) * W)
return(tot)
})
totalcons <- sum(obsdev)
belongmat <- t(belongmat)
n <- ncol(belongmat)
simulated <- vapply(1:nrep, function(d) {
belong2 <- belongmat[,sample(n)]
simvalues <- vapply(1:ncol(belong2), function(i) {
row <- belong2[,i]
idneighbour <- neighbours[[i]]
neighbour <- belong2[,neighbours[[i]]]
if (length(idneighbour) == 1){
neighbour <- t(as.matrix(neighbour))
}
W <- weights[[i]]
diff <- (neighbour-row)
tot <- sum(diff^2 * W)
return(tot)
}, FUN.VALUE = 1)
return(sum(simvalues))
},FUN.VALUE = 1)
ratio <- totalcons / simulated
}else{
rastnames <- names(object$rasters)
ok_names <- rastnames[grepl("group",rastnames, fixed = TRUE)]
rasters <- object$rasters[ok_names]
matrices <- lapply(rasters, raster::as.matrix)
mat_dim <- dim(matrices[[1]])
if(adj){
dataset <- lapply(1:ncol(object$Data), function(ic){
vec1 <- object$Data[,ic]
vec2 <- rep(NA,length(object$missing))
vec2[object$missing] <- vec1
rast <- object$rasters[[1]]
raster::values(rast) <- vec2
mat <- as.matrix(rast)
return(mat)
})
totalcons <- calc_raster_spinconsistency(matrices, window, adj, dataset)
}else{
totalcons <- calc_raster_spinconsistency(matrices,window)
}
warning("Calculating the permutation for the spatial inconsistency
when using raster can be long, depending on the raster size.
Note that the high number of cell in a raster reduces the need of
a great number of replications.")
all_ids <- 1:raster::ncell(rasters[[1]])
mem_vecs <- lapply(rasters, function(rast){
mat <- raster::as.matrix(rast)
dim(mat) <- NULL
return(mat)
})
if(adj){
data_vecs <- lapply(dataset, function(mat){
vec <- mat
dim(vec) <- NULL
return(vec)
})
}
simulated <- sapply(1:nrep, function(i){
Ids <- sample(all_ids)
new_matrices <- lapply(mem_vecs, function(vec){
new_vec <- vec[Ids]
val_na <- new_vec[!object$missing]
loc_na <- is.na(new_vec)
new_vec[!object$missing] <- NA
new_vec[loc_na] <- val_na
dim(new_vec) <- mat_dim
return(new_vec)
})
if(adj){
new_dataset <- lapply(data_vecs, function(vec){
new_vec <- vec[Ids];
val_na <- new_vec[!object$missing]
loc_na <- is.na(new_vec)
new_vec[!object$missing] <- NA
new_vec[loc_na] <- val_na
dim(new_vec) <- mat_dim
return(new_vec)
})
inconsist <- calc_raster_spinconsistency(new_matrices, window, adj, new_dataset)
}else{
inconsist <- calc_raster_spinconsistency(new_matrices, window)
}
return(inconsist)
})
ratio <- totalcons / simulated
}
return(list(Mean = mean(ratio), Median = quantile(ratio, probs = c(0.5)),
prt05 = quantile(ratio, probs = c(0.05)),
prt95 = quantile(ratio, probs = c(0.95)),
samples = ratio))
}
calc_raster_spinconsistency <- function(matrices, window, adj = FALSE, dataset = NULL){
if(adj & is.null(dataset)){
stop("When the adjusted version of spinconsistency is required, dataset must be given")
}
arr <- array(do.call(c,matrices), c(nrow(matrices[[1]]), ncol(matrices[[1]]), length(matrices)))
if(adj){
arr2 <- array(do.call(c,dataset), c(nrow(dataset[[1]]), ncol(dataset[[1]]), length(dataset)))
totalcons <- adj_spconsist_arr_window_globstd(arr2, arr, window)
}else{
totalcons <- sum(focal_euclidean_arr_window(arr,window), na.rm = TRUE)
}
return(totalcons)
}
check_matdist <- function(matdist){
if(!isSymmetric(matdist)){
stop("matdist must be a symetric matrix")
}
if(sum(diag(matdist)) != 0){
stop("matdist must have a diagonal filled with zeros")
}
}
calcELSA <- function(object, nblistw = NULL, window = NULL, matdist = NULL){
if(class(object)[[1]] != "FCMres"){
if(class(object) != "numeric"){
stop("if object is not a FCMres object, it must be a numeric vector")
}
vec <- object[object != -1]
if(min(vec) != 1){
stop("if object is a numeric vector, its lower value must be 1")
}
if(length(unique(vec)) != length(1:max(vec))){
stop("if object is a numeric vector, its values must be like 1,2,3,4,...m, -1 can be used to indicate missing values")
}
if(is.null(matdist)){
stop("if object is not a FCMres object, matdist must be provided")
}else{
check_matdist(matdist)
}
if(nrow(matdist) != length(unique(vec))){
stop("the dimension of matdist must equal the number of categories in object.")
}
if(is.null(nblistw)){
stop("if object is not a FCMres object, nblistw must be provided.")
}
}else{
if(object$isRaster){
if(is.null(object$window) & is.null(window)){
stop("impossible to extract window from object, window must be given.")
}
}else{
if(is.null(object$nblistw) & is.null(nblistw)){
stop("impossible to extract nblistw from object, nblistw must be given.")
}
}
}
if(class(object)[[1]] != "FCMres"){
vals <- elsa_vector(object, nblistw, matdist)
}else{
if(is.null(matdist)){
matdist <- as.matrix(stats::dist(object$Centers))
}
if(object$isRaster){
if(is.null(window)){
window <- object$window
}
vals <- elsa_raster(object$rasters$Groups, window, matdist)
}else{
vec <- as.numeric(gsub("V","",object$Groups,fixed = TRUE))
if(is.null(nblistw)){
vals <- elsa_vector(vec, object$nblistw, matdist)
}else{
vals <- elsa_vector(vec, nblistw, matdist)
}
}
}
return(vals)
}
elsa_vector <- function(categories, nblistw, dist){
d <- max(dist)
m <- length(unique(categories))
values <- sapply(1:length(categories), function(i){
xi <- categories[[i]]
if(xi == -1){
return(-1)
}else{
neighbours <- nblistw$neighbours[[i]]
w <- nblistw$weights[[i]]
xjs <- categories[neighbours]
Eai <- sum(dist[xi,xjs] * w) / (d * sum(w))
nn <- length(w)
if(nn > m){
mi <- m
}else{
mi <- nn
}
probs <- table(c(xjs,xi)) / (length(xjs)+1)
probs <- probs[probs > 0]
if(mi == 1){
return(0)
}else{
Eci <- -1 * (sum(probs * log2(probs)) / log2(mi))
return(Eai * Eci)
}
}
})
return(values)
}
elsa_raster <- function(rast, window, matdist){
if(class(window)[[1]] == "matrix"){
u <- unique(window)
if(length(union(c(0,1),u)) > 2){
stop("The provided matrix to calculate ELSA is not a binary matrix (0,1)")
}
fun <- Elsa_categorical_matrix_window
}else{
stop("for calculating ELSA on raster, window must be a binary matrix")
}
isRaster <- class(rast)[[1]] == "RasterLayer"
if(isRaster){
mat <- raster::as.matrix(rast)
}else{
mat <- rast
}
mat <- ifelse(is.na(mat),-1,mat)
vec <- c(mat)
m <- min(vec[vec!=-1])
if(m > 0){
mat<- ifelse(mat > 0, mat-1,mat)
}
cats <- unique(c(mat))
refcats <- 0:max(cats)
cats <- cats[cats != -1]
cats <- cats[order(cats)]
if(sum(refcats - cats)!=0){
stop(paste("the values of the raster used for ELSA calculation must be integers starting from 0 (or 1).
There must be no jumps between categories. The categories in the actual raster are : ", paste(cats,collapse = ","),sep=""))
}
mat2 <- fun(mat, window, matdist)
mat2 <- ifelse(mat2 == -1, NA, mat2)
if(isRaster){
raster::values(rast) <- mat2
return(rast)
}else{
return(mat2)
}
}
calcFuzzyELSA <- function(object, nblistw = NULL, window = NULL, matdist = NULL){
cls <- class(object)[[1]]
if(cls %in% c("FCMres","matrix","list") == FALSE){
stop("object must be a FCMres object, a matrix or a list of rasters")
}
if(cls == "matrix"){
sums <- sum(rowSums(object)) != 1
if(any(sums)){
stop("if object is a matrix, the sum of each row must be 1")
}
}
if(cls != "FCMres" & is.null(matdist)){
stop("if object is not a FCMre, matdist must be specified")
}
if(cls == "matrix" & is.null(nblistw)){
stop("if object is a matrix, nblistw must be specified")
}
if(cls == "list" & is.null(window)){
stop("if object is a list, window must be specified")
}
if(is.null(matdist)==FALSE){
if(!isSymmetric(matdist)){
stop("matdist must be a symetric matrix")
}
}
if(cls == "matrix"){
if(nrow(matdist) != ncol(object)){
stop("the number of columns in object (matrix) must match the number of rows in matdist")
}
if(is.null(nblistw)){
stop("if object is a matrix, nblistw must be provided")
}
}
if(cls == "list"){
if(nrow(matdist) != length(object)){
stop("the number of rasters in object (list) must match the number of rows in matdist")
}
if(is.null(window)){
stop("if object is a list of rasters, window must be provided")
}
}
if(cls == "FCMres"){
if(object$isRaster){
if(is.null(object$window) & is.null(window)){
stop("impossible to extract window from object, window must be provided")
}
}else{
if(is.null(object$nblistw) & is.null(nblistw)){
stop("impossible to extract nblistw from object, nblistw must be provided")
}
}
}
if(cls == "FCMres"){
if(object$isRaster==FALSE){
mat <- object$Belongings
if(is.null(matdist)){
matdist <- as.matrix(stats::dist(object$Centers))
}
if(is.null(nblistw)){
nblistw <- object$nblistw
}
return(elsa_fuzzy_vector(mat, nblistw, matdist))
}else{
if(is.null(matdist)){
matdist <- as.matrix(stats::dist(object$Centers))
}
if(is.null(window)){
window <- object$window
}
mats <- lapply(object$rasters[1:object$k], raster::as.matrix)
arr <- do.call(c,mats)
arr <- array(arr, dim = c(nrow(mats[[1]]), ncol(mats[[1]]),object$k))
values <- Elsa_fuzzy_matrix_window(arr, window, matdist)
rast <- object$rasters[[1]]
raster::values(rast) <- values
return(rast)
}
}else if (cls == "matrix"){
values <- elsa_fuzzy_vector(object, nblistw, matdist)
return(values)
}else if (cls == "list"){
mats <- lapply(object, raster::as.matrix)
arr <- do.call(c,mats)
arr <- array(arr, dim = c(nrow(mats[[1]]), ncol(mats[[1]]),object$k))
values <- Elsa_fuzzy_matrix_window(arr, window, matdist)
rast <- object[[1]]
raster::values(rast) <- values
return(rast)
}else{
stop("invalid arguments passed to calcFuzzyELSA")
}
return(values)
}
elsa_fuzzy_vector <- function(memberships, nblistw, matdist){
d <- max(matdist)
m <- ncol(memberships)
values <- sapply(1:nrow(memberships), function(i){
xi <- memberships[i,]
neighbours <- nblistw$neighbours[[i]]
xj <- memberships[neighbours,]
diffs <- abs(xi - t(xj))
sis <- apply(diffs, 2, function(x){
out <- outer(x,x)
return(sum(out * matdist))
})
s1 <- sum(sis)/2.0
nn <- length(neighbours)
eai <- s1 / (d*nn)
pks <- (colSums2(xj) + xi) / (nn+1)
pks <- pks[pks>0]
if(nn > m){
mi <- m
}else{
mi <- nn
}
eci <- -1 * (sum(pks * log2(pks)) / log2(mi))
return(eai * eci)
})
return(values)
}
calcFuzzyElsa_raster <- function(rasters,window,matdist){
if(class(rasters[[1]]) == "matrix"){
mats <- rasters
isRaster <- FALSE
vals <- do.call(c,mats)
arr <- array(vals, c(nrow(mats[[1]]),ncol(mats[[1]]),length(rasters)))
}else if (class(rasters[[1]]) == "RasterLayer"){
mats <- lapply(rasters, raster::as.matrix)
isRaster <- TRUE
vals <- do.call(c,mats)
arr <- array(vals, c(nrow(mats[[1]]),ncol(mats[[1]]),length(rasters)))
}else if (class(rasters)[[1]]=="array"){
arr <- rasters
isRaster <- FALSE
}else{
stop("rasters must be a list of matrix or a list of RasterLayer or an array")
}
elsa <- Elsa_fuzzy_matrix_window(arr, window, matdist)
if(isRaster){
rast <- rasters[[1]]
raster::values(rast) <- elsa
}else{
dims <- dim(arr)
rast <- matrix(elsa, nrow = dims[[1]], ncol = dims[[2]])
}
return(rast)
}
calc_moran_raster <- function(rast, window){
if(class(rast)[[1]] == "RasterLayer"){
mat <- raster::as.matrix(rast)
}else if (class(rast)[[1]] == "matrix"){
mat <- rast
}else{
stop("rast parameter must be on of matrix or RasterLayer")
}
if(class(window)[[1]] == "matrix"){
fun <- moranI_matrix_window
}else if (class(window)[[1]] == "numeric"){
fun <- moranI_matrix
}else{
stop("window parameter must be an integer or a matrix")
}
val <- fun(mat, window)
return(val)
}
calc_local_moran_raster <- function(rast, window){
if(class(rast)[[1]] == "RasterLayer"){
mat <- raster::as.matrix(rast)
}else if (class(rast)[[1]] == "matrix"){
mat <- rast
}else{
stop("rast parameter must be on of matrix or RasterLayer")
}
if(class(window)[[1]] == "matrix"){
window <- window
}else if (class(window)[[1]] == "numeric"){
w <- 1+2*window
window <- matrix(1, nrow = w, ncol = w)
window[ceiling(w/2),ceiling(w/2)] <- 0
}else{
stop("window parameter must be an integer or a matrix")
}
vals <- local_moranI_matrix_window(mat, window)
if(class(rast)[[1]] == "RasterLayer"){
raster::values(rast) <- vals
return(rast)
}else{
return(matrix(vals, ncol = ncol(mat), nrow = nrow(mat)))
}
}
|
print.summary_wsyn<-function(x,...)
{
for (counter in 1:length(x))
{
cat(names(x)[counter],": ",x[[counter]],"\n",sep="")
}
}
|
context("Ensuring that conditional formatting works as expected")
data_tbl <-
data.frame(
char_1 = c("saturday", "sunday", "monday", "tuesday",
"wednesday", "thursday", "friday"),
char_2 = c("june", "july", "august", "september",
"october", "november", "december"),
num_1 = c(1836.23, 2763.39, 937.29, 643.00, 212.232, 0, -23.24),
num_2 = c(34, 74, 23, NA, 35, NA, NA),
stringsAsFactors = FALSE)
tab <- gt(data_tbl)
time_tbl <-
data.frame(
date = c("2017-10-15", "2013-02-22", "2014-09-22", "2018-01-10"),
time = c("16:45", "19:23", "01:30", "08:00"),
datetime = c("2010-03-25 19:45", "2015-06-12 09:25",
"2016-01-15 14:38", "2012-08-07 12:31"),
stringsAsFactors = FALSE)
tab_time <- gt(time_tbl)
test_that("the `fmt_number()` function works with conditional `rows`", {
expect_equal(
(tab %>%
fmt_number(
columns = num_1,
decimals = 4,
rows = num_1 < 1000) %>%
render_formats_test(context = "html"))[["num_1"]],
c("1836.23", "2763.39", "937.2900", "643.0000",
"212.2320", "0.0000", "−23.2400"))
expect_equal(
(tab %>%
fmt_number(
columns = c(num_1, num_2),
decimals = 4,
rows = char_2 %in% c("june", "july") & grepl("sa.*", char_1)) %>%
render_formats_test(context = "html"))[["num_2"]],
c("34.0000", "74", "23", "NA", "35", "NA", "NA"))
})
test_that("the `fmt_scientific()` function works with conditional `rows`", {
expect_equal(
(tab %>%
fmt_scientific(
columns = num_1,
decimals = 4,
rows = num_1 < 1000) %>%
render_formats_test(context = "html"))[["num_1"]],
c("1836.23", "2763.39", "9.3729 × 10<sup class='gt_super'>2</sup>",
"6.4300 × 10<sup class='gt_super'>2</sup>",
"2.1223 × 10<sup class='gt_super'>2</sup>", "0.0000",
"−2.3240 × 10<sup class='gt_super'>1</sup>")
)
expect_equal(
(tab %>%
fmt_scientific(
columns = c(num_1, num_2),
decimals = 4,
rows = char_2 %in% c("june", "july") & grepl("sa.*", char_1)) %>%
render_formats_test(context = "html"))[["num_2"]],
c("3.4000 × 10<sup class='gt_super'>1</sup>",
"74", "23", "NA", "35", "NA", "NA")
)
})
test_that("the `fmt_percent()` function works with conditional `rows`", {
expect_equal(
(tab %>%
fmt_percent(
columns = num_1,
decimals = 2,
rows = num_1 < 1000) %>%
render_formats_test(context = "html"))[["num_1"]],
c("1836.23", "2763.39", "93,729.00%", "64,300.00%",
"21,223.20%", "0.00%", "−2,324.00%")
)
expect_equal(
(tab %>%
fmt_percent(
columns = c(num_1, num_2),
decimals = 2,
rows = char_2 %in% c("june", "july") & grepl("sa.*", char_1)) %>%
render_formats_test(context = "html"))[["num_2"]],
c("3,400.00%", "74", "23", "NA", "35", "NA", "NA")
)
})
test_that("the `fmt_currency()` function works with conditional `rows`", {
expect_equal(
(tab %>%
fmt_currency(
columns = num_1,
currency = "USD",
rows = num_1 < 1000) %>%
render_formats_test(context = "html"))[["num_1"]],
c("1836.23", "2763.39", "$937.29", "$643.00", "$212.23",
"$0.00", "−$23.24")
)
expect_equal(
(tab %>%
fmt_currency(
columns = c(num_1, num_2),
currency = "USD",
rows = char_2 %in% c("june", "july") & grepl("sa.*", char_1)) %>%
render_formats_test(context = "html"))[["num_2"]],
c("$34.00", "74", "23", "NA", "35", "NA", "NA")
)
})
test_that("the `fmt_date()` function works with conditional `rows`", {
expect_equal(
(tab_time %>%
fmt_date(
columns = date,
date_style = 2,
rows = time == "16:45") %>%
render_formats_test(context = "html"))[["date"]],
c("Sunday, October 15, 2017", "2013-02-22",
"2014-09-22", "2018-01-10")
)
expect_equal(
(tab_time %>%
fmt_date(
columns = date,
date_style = 2,
rows = date %in% c("2017-10-15", "2014-09-22") & grepl("^1", time)) %>%
render_formats_test(context = "html"))[["date"]],
c("Sunday, October 15, 2017", "2013-02-22",
"2014-09-22", "2018-01-10")
)
})
test_that("the `fmt_time()` function works with conditional `rows`", {
expect_equal(
(tab_time %>%
fmt_time(
columns = time,
time_style = 2,
rows = time == "16:45") %>%
render_formats_test(context = "html"))[["time"]],
c("16:45", "19:23", "01:30", "08:00")
)
expect_equal(
(tab_time %>%
fmt_time(
columns = time,
time_style = 2,
rows = date %in% c("2017-10-15", "2014-09-22") & grepl("^1", time)) %>%
render_formats_test(context = "html"))[["time"]],
c("16:45", "19:23", "01:30", "08:00")
)
})
test_that("the `fmt_datetime()` function works with conditional `rows`", {
expect_equal(
(tab_time %>%
fmt_datetime(
columns = datetime,
date_style = 2,
time_style = 2,
rows = time == "16:45") %>%
render_formats_test(context = "html"))[["datetime"]],
c("Thursday, March 25, 2010 19:45", "2015-06-12 09:25",
"2016-01-15 14:38", "2012-08-07 12:31")
)
expect_equal(
(tab_time %>%
fmt_datetime(
columns = datetime,
date_style = 2,
time_style = 2,
rows = date %in% c("2017-10-15", "2014-09-22") & grepl("^1", time)) %>%
render_formats_test(context = "html"))[["datetime"]],
c("Thursday, March 25, 2010 19:45", "2015-06-12 09:25",
"2016-01-15 14:38", "2012-08-07 12:31")
)
})
test_that("the `fmt_passthrough()` function works with conditional `rows`", {
expect_equal(
(tab_time %>%
fmt_passthrough(
columns = datetime,
rows = time == "16:45") %>%
render_formats_test(context = "html"))[["datetime"]],
c("2010-03-25 19:45", "2015-06-12 09:25",
"2016-01-15 14:38", "2012-08-07 12:31")
)
expect_equal(
(tab_time %>%
fmt_passthrough(
columns = datetime,
rows = date %in% c("2017-10-15", "2014-09-22") & grepl("^1", time)) %>%
render_formats_test(context = "html"))[["datetime"]],
c("2010-03-25 19:45", "2015-06-12 09:25",
"2016-01-15 14:38", "2012-08-07 12:31")
)
})
test_that("the `fmt_missing()` function works with conditional `rows`", {
expect_equal(
(tab %>%
fmt_missing(
columns = num_2,
rows = num_1 <= 0) %>%
render_formats_test(context = "html"))[["num_2"]],
c("34", "74", "23", "NA", "35", rep("—", 2))
)
})
test_that("the `fmt()` function works with conditional `rows`", {
expect_equal(
(tab %>%
fmt(
columns = num_1,
rows = num_1 > 1000,
fns = function(x){
x * 1000
}) %>%
render_formats_test(context = "html"))[["num_1"]],
c("1836230", "2763390", "937.290", "643.000",
"212.232", "0.000", "-23.240")
)
})
|
notExp <- function(x)
{ f <- x
ind <- x > 1
f[ind] <- exp(1)*(x[ind]^2+1)/2
ind <- (x <= 1)&(x > -1)
f[ind] <- exp(x[ind])
ind <- (x <= -1)
x[ind] <- -x[ind] ;f[ind] <- exp(1)*(x[ind]^2+1)/2; f[ind]<-1/f[ind]
f
}
notLog <- function(x)
{ f <- x
ind <- x> exp(1)
f[ind] <- sqrt(2*x[ind]/exp(1)-1)
ind <- !ind & x > exp(-1)
f[ind] <- log(x[ind])
ind <- x <= exp(-1)
x[ind]<- 1/x[ind]; f[ind] <- sqrt(2*x[ind]/exp(1)-1);f[ind] <- -f[ind]
f
}
notExp2 <- function (x,d=.Options$mgcv.vc.logrange,b=1/d)
{ exp(d*sin(x*b))
}
notLog2 <- function(x,d=.Options$mgcv.vc.logrange,b=1/d)
{ x <- log(x)/d
x <- pmin(1,x)
x <- pmax(-1,x)
asin(x)/b
}
pdTens <- function(value = numeric(0), form = NULL, nam = NULL, data = sys.frame(sys.parent()))
{
object <- numeric(0)
class(object) <- c("pdTens", "pdMat")
nlme::pdConstruct(object, value, form, nam, data)
}
pdConstruct.pdTens <-
function(object, value = numeric(0), form = formula(object),
nam = nlme::Names(object), data = sys.frame(sys.parent()), ...)
{
val <- NextMethod()
if (length(val) == 0) {
class(val) <- c("pdTens","pdMat")
return(val)
}
if (is.matrix(val)) {
S <- attr(form,"S")
m <- length(S)
y <- as.numeric((crossprod(val)))
lform <- "y ~ as.numeric(S[[1]])"
if (m>1) for (i in 2:m) lform <- paste(lform," + as.numeric(S[[",i,"]])",sep="")
lform <- formula(paste(lform,"-1"))
mod1 <- lm(lform)
mod1.r2 <- 1-sum(residuals(mod1)^2)/sum((y-mean(y))^2)
y <- as.numeric(solve(crossprod(val)))
mod2 <- lm(lform)
mod2.r2 <- 1-sum(residuals(mod2)^2)/sum((y-mean(y))^2)
if (mod2.r2 > mod1.r2) mod1 <- mod2
value <- coef(mod1)
value[value <=0] <- .Machine$double.eps * mean(as.numeric(lapply(S,function(x) max(abs(x)))))
value <- notLog2(value)
attributes(value) <- attributes(val)[names(attributes(val)) != "dim"]
class(value) <- c("pdTens", "pdMat")
return(value)
}
m <- length(attr(form,"S"))
if ((aux <- length(val)) > 0) {
if (aux && (aux != m)) {
stop(gettextf("An object of length %d does not match the required parameter size",aux))
}
}
class(val) <- c("pdTens","pdMat")
val
}
pdFactor.pdTens <- function(object)
{ sp <- as.vector(object)
m <- length(sp)
S <- attr(formula(object),"S")
value <- S[[1]]*notExp2(sp[1])
if (m>1) for (i in 2:m) value <- value + notExp2(sp[i])*S[[i]]
if (sum(is.na(value))>0) warning("NA's in pdTens factor")
value <- (value+t(value))/2
c(t(mroot(value,rank=nrow(value))))
}
pdMatrix.pdTens <-
function(object, factor = FALSE)
{
if (!nlme::isInitialized(object)) {
stop("Cannot extract the matrix from an uninitialized object")
}
sp <- as.vector(object)
m <- length(sp)
S <- attr(formula(object),"S")
value <- S[[1]]*notExp2(sp[1])
if (m>1) for (i in 2:m) value <- value + notExp2(sp[i])*S[[i]]
value <- (value + t(value))/2
if (sum(is.na(value))>0) warning("NA's in pdTens matrix")
if (factor) {
value <- t(mroot(value,rank=nrow(value)))
}
dimnames(value) <- attr(object, "Dimnames")
value
}
coef.pdTens <-
function(object, unconstrained = TRUE, ...)
{
if (unconstrained) NextMethod()
else {
val <- notExp2(as.vector(object))
names(val) <- paste("sp.",1:length(val), sep ="")
val
}
}
summary.pdTens <-
function(object, structName = "Tensor product smooth term", ...)
{
NextMethod(object, structName, noCorrelation=TRUE)
}
pdIdnot <-
function(value = numeric(0), form = NULL, nam = NULL, data = sys.frame(sys.parent()))
{
object <- numeric(0)
class(object) <- c("pdIdnot", "pdMat")
nlme::pdConstruct(object, value, form, nam, data)
}
corMatrix.pdIdnot <-
function(object, ...)
{
if (!nlme::isInitialized(object)) {
stop("Cannot extract the matrix from an uninitialized pdMat object")
}
if (is.null(Ncol <- attr(object, "ncol"))) {
stop(paste("Cannot extract the matrix with uninitialized dimensions"))
}
val <- diag(Ncol)
attr(val, "stdDev") <- rep(sqrt(notExp2(as.vector(object))), Ncol)
if (length(nm <- nlme::Names(object)) == 0) {
len <- length(as.vector(object))
nm <- paste("V", 1:len, sep = "")
dimnames(val) <- list(nm, nm)
}
names(attr(val, "stdDev")) <- nm
val
}
pdConstruct.pdIdnot <-
function(object, value = numeric(0), form = formula(object),
nam = nlme::Names(object), data = sys.frame(sys.parent()), ...)
{
val <- NextMethod()
if (length(val) == 0) {
if ((ncol <- length(nlme::Names(val))) > 0) {
attr(val, "ncol") <- ncol
}
return(val)
}
if (is.matrix(val)) {
value <- notLog2(mean(diag(crossprod(val))))
attributes(value) <- attributes(val)[names(attributes(val)) != "dim"]
attr(value, "ncol") <- dim(val)[2]
class(value) <- c("pdIdnot", "pdMat")
return(value)
}
if (length(val) > 1) {
stop(paste("An object of length", length(val),
"does not match the required parameter size"))
}
if (((aux <- length(nlme::Names(val))) == 0) && is.null(formula(val))) {
stop(paste("Must give names when initializing pdIdnot from parameter.",
"without a formula"))
} else {
attr(val, "ncol") <- aux
}
val
}
pdFactor.pdIdnot <-
function(object)
{
sqrt(notExp2(as.vector(object))) * diag(attr(object, "ncol"))
}
pdMatrix.pdIdnot <-
function(object, factor = FALSE)
{
if (!nlme::isInitialized(object)) {
stop("Cannot extract the matrix from an uninitialized pdMat object")
}
if (is.null(Ncol <- attr(object, "ncol"))) {
stop(paste("Cannot extract the matrix with uninitialized dimensions"))
}
value <- diag(Ncol)
if (factor) {
value <- sqrt(notExp2(as.vector(object))) * value
attr(value, "logDet") <- Ncol * log(notExp2(as.vector(object)))/2
} else {
value <- notExp2(as.vector(object)) * value
}
dimnames(value) <- attr(object, "Dimnames")
value
}
coef.pdIdnot <-
function(object, unconstrained = TRUE, ...)
{
if (unconstrained) NextMethod()
else structure(notExp2(as.vector(object)),
names = c(paste("sd(", deparse(formula(object)[[2]],backtick=TRUE),")",sep = "")))
}
Dim.pdIdnot <-
function(object, ...)
{
if (!is.null(val <- attr(object, "ncol"))) {
c(val, val)
} else {
stop("Cannot extract the dimensions")
}
}
logDet.pdIdnot <-
function(object, ...)
{
attr(object, "ncol") * log(notExp2(as.vector(object)))/2
}
solve.pdIdnot <-
function(a, b, ...)
{
if (!nlme::isInitialized(a)) {
stop("Cannot extract the inverse from an uninitialized object")
}
atr <- attributes(a)
a <- -coef(a, TRUE)
attributes(a) <- atr
a
}
summary.pdIdnot <-
function(object, structName = "Multiple of an Identity", ...)
{
NextMethod(object, structName, noCorrelation=TRUE)
}
smooth2random <- function(object,vnames,type=1) UseMethod("smooth2random")
smooth2random.fs.interaction <- function(object,vnames,type=1) {
if (object$fixed) return(list(fixed=TRUE,Xf=object$X))
if (!is.null(object$Xb)) {
object$X <- object$Xb
object$S <- object$base$S
if (!is.null(object$S.scale)&&length(object$S)>0) for (i in 1:length(object$S)) object$S[[i]] <- object$S[[i]]/object$S.scale[i]
}
colx <- ncol(object$X)
diagU <- rep(1,colx)
ind <- 1:colx
n.lev <- length(object$flev)
if (type==2) {
pen.ind <- rep(ind*0,n.lev)
} else pen.ind <- NULL
random <- list()
k <- 1
rinc <- rind <- rep(0,0)
for (i in 1:length(object$S)) {
indi <- ind[diag(object$S[[i]])!=0]
X <- object$X[,indi,drop=FALSE]
D <- diag(object$S[[i]])[indi]
diagU[indi] <- 1/sqrt(D)
X <- X%*%diag(diagU[indi],ncol=length(indi))
term.name <- new.name("Xr",vnames)
vnames <- c(vnames,term.name)
rind <- c(rind,k:(k+ncol(X)-1))
rinc <- c(rinc,rep(ncol(X),ncol(X)))
k <- k + n.lev * ncol(X)
if (type==1) {
form <- as.formula(paste("~",term.name,"-1",sep=""),env=.GlobalEnv)
fname <- new.name(object$fterm,vnames)
vnames <- c(vnames,fname)
random[[i]] <- pdIdnot(form)
names(random)[i] <- fname
attr(random[[i]],"group") <- object$fac
attr(random[[i]],"Xr.name") <- term.name
attr(random[[i]],"Xr") <- X
} else {
Xr <- as(matrix(0,nrow(X),0),"dgCMatrix")
ii <- 0
for (j in 1:n.lev) {
Xr <- cbind2(Xr,as(X*as.numeric(object$fac==object$flev[j]),"dgCMatrix"))
pen.ind[indi+ii] <- i;ii <- ii + colx
}
random[[i]] <- if (is.null(object$Xb)) Xr else as(Xr,"matrix")
names(random)[i] <- term.name
attr(random[[i]],"s.label") <- object$label
}
}
if (type==2) {
ind <- 1:length(rind)
ni <- length(ind)
rind <- rep(rind,n.lev)
if (n.lev>1) for (k in 2:n.lev) {
rind[ind+ni] <- rind[ind]+rinc
ind <- ind + ni
}
D <- rep(diagU,n.lev)
} else D <- diagU
Xf <- matrix(0,nrow(object$X),0)
list(rand=random,trans.D=D,Xf=Xf,fixed=FALSE,rind=rind,rinc=rinc,
pen.ind=pen.ind)
}
smooth2random.t2.smooth <- function(object,vnames,type=1) {
if (object$fixed) return(list(fixed=TRUE,Xf=object$X))
fixed <- rep(TRUE,ncol(object$X))
random <- list()
diagU <- rep(1,ncol(object$X))
ind <- 1:ncol(object$X)
pen.ind <- ind*0
n.para <- 0
for (i in 1:length(object$S)) {
indi <- ind[diag(object$S[[i]])!=0]
pen.ind[indi] <- i
X <- object$X[,indi,drop=FALSE]
D <- diag(object$S[[i]])[indi]
diagU[indi] <- 1/sqrt(D)
X <- X%*%diag(diagU[indi])
fixed[indi] <- FALSE
term.name <- new.name("Xr",vnames)
group.name <- new.name("g",vnames)
vnames <- c(vnames,term.name,group.name)
if (type==1) {
form <- as.formula(paste("~",term.name,"-1",sep=""),env=.GlobalEnv)
random[[i]] <- pdIdnot(form)
names(random)[i] <- group.name
attr(random[[i]],"group") <- factor(rep(1,nrow(X)))
attr(random[[i]],"Xr.name") <- term.name
attr(random[[i]],"Xr") <- X
} else {
random[[i]] <- X
names(random)[i] <- term.name
attr(random[[i]],"s.label") <- object$label
}
n.para <- n.para + ncol(X)
}
if (sum(fixed)) {
Xf <- object$X[,fixed,drop=FALSE]
} else Xf <- matrix(0,nrow(object$X),0)
list(rand=random,trans.D=diagU,Xf=Xf,fixed=FALSE,
rind=1:n.para,rinc=rep(n.para,n.para),pen.ind=pen.ind)
}
smooth2random.mgcv.smooth <- function(object,vnames,type=1) {
if (object$fixed) return(list(fixed=TRUE,Xf=object$X))
if (length(object$S)>1) stop("Can not convert this smooth class to a random effect")
ev <- eigen(object$S[[1]],symmetric=TRUE)
null.rank <- object$df - object$rank
p.rank <- object$rank
if (p.rank>ncol(object$X)) p.rank <- ncol(object$X)
U <- ev$vectors
D <- c(ev$values[1:p.rank],rep(1,null.rank))
D <- 1/sqrt(D)
UD <- t(t(U)*D)
X <- object$X%*%UD
if (p.rank<object$df) Xf <- X[,(p.rank+1):object$df,drop=FALSE] else
Xf <- matrix(0,nrow(object$X),0)
term.name <- new.name("Xr",vnames)
if (type==1) {
form <- as.formula(paste("~",term.name,"-1",sep=""),env=.GlobalEnv)
random <- list(pdIdnot(form))
group.name <- new.name("g",vnames)
names(random) <- group.name
attr(random[[1]],"group") <- factor(rep(1,nrow(X)))
attr(random[[1]],"Xr.name") <- term.name
attr(random[[1]],"Xr") <- X[,1:p.rank,drop=FALSE]
} else {
random <- list(X[,1:p.rank,drop=FALSE])
names(random)[1] <- term.name
attr(random[[1]],"s.label") <- object$label
}
rind <- 1:p.rank
pen.ind <- rep(0,ncol(object$X))
pen.ind[rind] <- 1
rinc <- rep(p.rank,p.rank)
list(rand=random,
Xf=Xf,
trans.U=U,
trans.D=D,
fixed=FALSE,rind=rind,rinc=rinc,
pen.ind=pen.ind)
}
smooth2random.tensor.smooth <- function(object,vnames,type=1) {
if (type==2) stop("te smooths not useable with gamm4: use t2 instead")
if (sum(object$fx)==length(object$fx)) return(list(fixed=TRUE,Xf=object$X)) else
if (sum(object$fx)!=0) warning("gamm can not fix only some margins of tensor product.")
sum.S <- object$S[[1]]/mean(abs(object$S[[1]]))
if (length(object$S)>1) for (l in 2:length(object$S)) {
sum.S <- sum.S + object$S[[l]]/mean(abs(object$S[[l]]))
}
null.rank <- object$null.space.dim
ev <- eigen(sum.S,symmetric=TRUE)
p.rank <- ncol(object$X) - null.rank
if (p.rank>ncol(object$X)) p.rank <- ncol(object$X)
U <- ev$vectors
D <- c(ev$values[1:p.rank],rep(1,null.rank))
if (sum(D<=0)) stop(
"Tensor product penalty rank appears to be too low: please email [email protected] with details.")
U <- U
X <- object$X%*%U
if (p.rank<ncol(X)) Xf <- X[,(p.rank+1):ncol(X),drop=FALSE] else
Xf <- matrix(0,nrow(X),0)
for (l in 1:length(object$S)) {
object$S[[l]] <- (t(U)%*%object$S[[l]]%*%U)[1:p.rank,1:p.rank]
object$S[[l]] <- (object$S[[l]]+t(object$S[[l]]))/2
}
term.name <- new.name("Xr",vnames)
form <- as.formula(paste("~",term.name,"-1",sep=""),env=.GlobalEnv)
attr(form,"S") <- object$S
random <- list(pdTens(form))
group.name <- new.name("g",vnames)
names(random) <- group.name
attr(random[[1]],"group") <- factor(rep(1,nrow(X)))
attr(random[[1]],"Xr.name") <- term.name
attr(random[[1]],"Xr") <- X[,1:p.rank,drop=FALSE]
rind <- 1:p.rank
rinc <- rep(p.rank,p.rank)
list(rand=random,
Xf=Xf,
trans.U=U,
trans.D=rep(1,ncol(U)),
fixed=FALSE,rind=rind,rinc=rinc)
}
gamm.setup <- function(formula,pterms,
data=stop("No data supplied to gamm.setup"),knots=NULL,
parametric.only=FALSE,absorb.cons=FALSE)
{
G <- gam.setup(formula,pterms,
data=data,knots=knots,sp=NULL,
min.sp=NULL,H=NULL,absorb.cons=TRUE,sparse.cons=0,gamm.call=TRUE)
if (!is.null(G$L)) stop("gamm can not handle linked smoothing parameters (probably from use of `id' or adaptive smooths)")
first.f.para <- G$nsdf+1
first.r.para <- 1
G$Xf <- G$X
random <- list()
if (G$nsdf>0) ind <- 1:G$nsdf else ind <- rep(0,0)
X <- G$X[,ind,drop=FALSE]
xlab <- rep("",0)
if (G$m>0) {
pord <- 1:G$m
done <- rep(FALSE,length(pord))
k <- 0
f.name <- NULL
for (i in 1:G$m) if (is.null(G$smooth[[i]]$fac)) {
k <- k + 1
pord[k] <- i
done[i] <- TRUE
} else {
if (is.null(f.name)) f.name <- G$smooth[[i]]$fterm
else if (f.name!=G$smooth[[i]]$fterm) stop("only one level of smooth nesting is supported by gamm")
if (!is.null(attr(G$smooth[[i]],"del.index"))) stop("side conditions not allowed for nested smooths")
}
if (k < G$m) pord[(k+1):G$m] <- (1:G$m)[!done]
}
if (G$m) for (i in 1:G$m) {
sm <- G$smooth[[pord[i]]]
sm$X <- G$X[,sm$first.para:sm$last.para,drop=FALSE]
rasm <- smooth2random(sm,names(data))
sm$fixed <- rasm$fixed
if (!is.null(sm$fac)) {
flev <- levels(sm$fac)
}
n.para <- 0
if (!sm$fixed) {
for (k in 1:length(rasm$rand)) {
group.name <- names(rasm$rand)[k]
group <- attr(rasm$rand[[k]],"group")
Xr.name <- attr(rasm$rand[[k]],"Xr.name")
Xr <- attr(rasm$rand[[k]],"Xr")
attr(rasm$rand[[k]],"group") <- attr(rasm$rand[[k]],"Xr") <-
attr(rasm$rand[[k]],"Xr.name") <- NULL
n.para <- n.para + ncol(Xr)
data[[group.name]] <- group
data[[Xr.name]] <- Xr
}
random <- c(random,rasm$rand)
sm$trans.U <- rasm$trans.U
sm$trans.D <- rasm$trans.D
}
if (ncol(rasm$Xf)) {
Xfnames <- rep("",ncol(rasm$Xf))
k <- length(xlab)+1
for (j in 1:ncol(rasm$Xf)) {
xlab[k] <- Xfnames[j] <-
new.name(paste(sm$label,"Fx",j,sep=""),xlab)
k <- k + 1
}
colnames(rasm$Xf) <- Xfnames
}
X <- cbind(X,rasm$Xf)
sm$first.f.para <- first.f.para
first.f.para <- first.f.para + ncol(rasm$Xf)
sm$last.f.para <- first.f.para - 1
sm$rind <- rasm$rind - 1 + first.r.para
sm$rinc <- rasm$rinc
first.r.para <- first.r.para+n.para
sm$n.para <- n.para
if (!is.null(sm$fac)) {
first.r.para <- first.r.para + n.para*(length(flev)-1)
}
sm$X <- NULL
if (G$m>0) G$smooth[[pord[i]]] <- sm
}
G$random <- random
G$X <- X
G$data <- data
if (G$m>0) G$pord <- pord
G
}
varWeights.dfo <- function(b,data)
{ w <- nlme::varWeights(b$modelStruct$varStruct)
group.name <- names(b$groups)
ind <- NULL
order.txt <- paste("ind<-order(data[[\"",group.name[1],"\"]]",sep="")
if (length(b$groups)>1) for (i in 2:length(b$groups))
order.txt <- paste(order.txt,",data[[\"",group.name[i],"\"]]",sep="")
order.txt <- paste(order.txt,")")
eval(parse(text=order.txt))
w[ind] <- w
w
}
extract.lme.cov2<-function(b,data=NULL,start.level=1)
{ if (!inherits(b,"lme")) stop("object does not appear to be of class lme")
if (is.null(data)) {
na.act <- na.action(b)
data <- if (is.null(na.act)) b$data else b$data[-na.act,]
}
grps <- nlme::getGroups(b)
n <- length(grps)
n.levels <- length(b$groups)
n.corlevels <- if (is.null(b$modelStruct$corStruct)) 0 else
length(all.vars(nlme::getGroupsFormula(b$modelStruct$corStruct)))
if (n.levels<n.corlevels) {
getGroupsFormula(b$modelStruct$corStruct)
vnames <- all.vars(nlme::getGroupsFormula(b$modelStruct$corStruct))
lab <- paste(eval(parse(text=vnames[1]),envir=b$data))
if (length(vnames)>1) for (i in 2:length(vnames)) {
lab <- paste(lab,"/",eval(parse(text=vnames[i]),envir=b$data),sep="")
}
grps <- factor(lab)
}
if (n.levels >= start.level||n.corlevels >= start.level) {
if (n.levels >= start.level)
Cgrps <- nlme::getGroups(b,level=start.level)
else Cgrps <- grps
Cind <- sort(as.numeric(Cgrps),index.return=TRUE)$ix
rCind <- 1:n; rCind[Cind] <- 1:n
Clevel <- levels(Cgrps)
n.cg <- length(Clevel)
size.cg <- array(0,n.cg)
for (i in 1:n.cg) size.cg[i] <- sum(Cgrps==Clevel[i])
} else { n.cg <- 1; Cind<-1:n }
if (is.null(b$modelStruct$varStruct)) w<-rep(b$sigma,n)
else {
w <- 1/nlme::varWeights(b$modelStruct$varStruct)
group.name<-names(b$groups)
order.txt <- paste("ind<-order(data[[\"",group.name[1],"\"]]",sep="")
if (length(b$groups)>1) for (i in 2:length(b$groups))
order.txt <- paste(order.txt,",data[[\"",group.name[i],"\"]]",sep="")
order.txt <- paste(order.txt,")")
eval(parse(text=order.txt))
w[ind] <- w
w <- w*b$sigma
}
w <- w[Cind]
if (is.null(b$modelStruct$corStruct)) V <- array(1,n)
else {
c.m <- nlme::corMatrix(b$modelStruct$corStruct)
if (!is.list(c.m)) {
V <- c.m;V[Cind,] -> V;V[,Cind] -> V
} else {
V<-list()
ind <- list()
for (i in 1:n.cg) {
V[[i]] <- matrix(0,size.cg[i],size.cg[i])
ind[[i]] <- 1:size.cg[i]
}
Voff <- cumsum(c(1,size.cg))
gr.name <- names(c.m)
n.g<-length(c.m)
j0<-rep(1,n.cg)
ii <- 1:n
for (i in 1:n.g)
{
Clev <- unique(Cgrps[grps==gr.name[i]])
if (length(Clev)>1) stop("inner groupings not nested in outer!!")
k <- (1:n.cg)[Clevel==Clev]
j1<-j0[k]+nrow(c.m[[i]])-1
V[[k]][j0[k]:j1,j0[k]:j1]<-c.m[[i]]
ind1 <- ii[grps==gr.name[i]]
ind2 <- rCind[ind1]
ind[[k]][j0[k]:j1] <- ind2 - Voff[k] + 1
j0[k]<-j1+1
}
for (k in 1:n.cg) {
V[[k]][ind[[k]],]<-V[[k]];V[[k]][,ind[[k]]]<-V[[k]]
}
}
}
if (is.list(V))
{ for (i in 1:n.cg)
{ wi <- w[Voff[i]:(Voff[i]+size.cg[i]-1)]
V[[i]] <- as.vector(wi)*t(as.vector(wi)*V[[i]])
}
} else
if (is.matrix(V))
{ V <- as.vector(w)*t(as.vector(w)*V)
} else
{ V <- w^2*V
}
X <- list()
grp.dims <- b$dims$ncol
Zt <- model.matrix(b$modelStruct$reStruct,data)
cov <- as.matrix(b$modelStruct$reStruct)
i.col<-1
Z <- matrix(0,n,0)
if (start.level<=n.levels)
{ for (i in 1:(n.levels-start.level+1))
{
if(length(levels(b$groups[[n.levels-i+1]]))==1) {
X[[1]] <- matrix(rep(1,nrow(b$groups))) } else {
clist <- list('b$groups[[n.levels - i + 1]]'=c("contr.treatment","contr.treatment"))
X[[1]] <- model.matrix(~b$groups[[n.levels - i + 1]]-1,
contrasts.arg=clist) }
X[[2]] <- Zt[,i.col:(i.col+grp.dims[i]-1),drop=FALSE]
i.col <- i.col+grp.dims[i]
Z <- cbind(Z,tensor.prod.model.matrix(X))
}
Vr <- matrix(0,ncol(Z),ncol(Z))
start <- 1
for (i in 1:(n.levels-start.level+1))
{ k <- n.levels-i+1
for (j in 1:b$dims$ngrps[i])
{ stop <- start+ncol(cov[[k]])-1
Vr[start:stop,start:stop]<-cov[[k]]
start <- stop+1
}
}
Vr <- Vr*b$sigma^2
Z <- Z[Cind,]
if (n.cg == 1) {
if (is.matrix(V)) {
V <- V+Z%*%Vr%*%t(Z)
} else V <- diag(V) + Z%*%Vr%*%t(Z)
} else {
j0 <- 1
Vz <- list()
for (i in 1:n.cg) {
j1 <- size.cg[i] + j0 -1
Zi <- Z[j0:j1,,drop=FALSE]
Vz[[i]] <- Zi %*% Vr %*% t(Zi)
j0 <- j1+1
}
if (is.list(V)) {
for (i in 1:n.cg) V[[i]] <- V[[i]]+Vz[[i]]
} else {
j0 <-1
for (i in 1:n.cg) {
kk <- size.cg[i]
j1 <- kk + j0 -1
Vz[[i]] <- Vz[[i]] + diag(x=V[j0:j1],nrow=kk,ncol=kk)
j0 <- j1+1
}
V <- Vz
}
}
}
list(V=V,ind=Cind)
}
extract.lme.cov<-function(b,data=NULL,start.level=1)
{ if (!inherits(b,"lme")) stop("object does not appear to be of class lme")
if (is.null(data)) {
na.act <- na.action(b)
data <- if (is.null(na.act)) b$data else b$data[-na.act,]
}
grps<-nlme::getGroups(b)
n<-length(grps)
if (is.null(b$modelStruct$varStruct)) w<-rep(b$sigma,n)
else
{ w<-1/nlme::varWeights(b$modelStruct$varStruct)
group.name<-names(b$groups)
order.txt <- paste("ind<-order(data[[\"",group.name[1],"\"]]",sep="")
if (length(b$groups)>1) for (i in 2:length(b$groups))
order.txt <- paste(order.txt,",data[[\"",group.name[i],"\"]]",sep="")
order.txt <- paste(order.txt,")")
eval(parse(text=order.txt))
w[ind] <- w
w<-w*b$sigma
}
if (is.null(b$modelStruct$corStruct)) V<-diag(n)
else
{ c.m<-nlme::corMatrix(b$modelStruct$corStruct)
if (!is.list(c.m)) V<-c.m
else
{ V<-matrix(0,n,n)
gr.name <- names(c.m)
n.g<-length(c.m)
j0<-1
ind<-ii<-1:n
for (i in 1:n.g)
{ j1<-j0+nrow(c.m[[i]])-1
V[j0:j1,j0:j1]<-c.m[[i]]
ind[j0:j1]<-ii[grps==gr.name[i]]
j0<-j1+1
}
V[ind,]<-V;V[,ind]<-V
}
}
V <- as.vector(w)*t(as.vector(w)*V)
X<-list()
grp.dims<-b$dims$ncol
Zt<-model.matrix(b$modelStruct$reStruct,data)
cov<-as.matrix(b$modelStruct$reStruct)
i.col<-1
n.levels<-length(b$groups)
Z<-matrix(0,n,0)
if (start.level<=n.levels)
{ for (i in 1:(n.levels-start.level+1))
{
if(length(levels(b$groups[[n.levels-i+1]]))==1) {
X[[1]] <- matrix(rep(1,nrow(b$groups))) } else {
clist <- list('b$groups[[n.levels - i + 1]]'=c("contr.treatment","contr.treatment"))
X[[1]] <- model.matrix(~b$groups[[n.levels - i + 1]]-1,
contrasts.arg=clist) }
X[[2]] <- Zt[,i.col:(i.col+grp.dims[i]-1),drop=FALSE]
i.col <- i.col+grp.dims[i]
Z <- cbind(Z,tensor.prod.model.matrix(X))
}
Vr <- matrix(0,ncol(Z),ncol(Z))
start <- 1
for (i in 1:(n.levels-start.level+1))
{ k <- n.levels-i+1
for (j in 1:b$dims$ngrps[i])
{ stop <- start+ncol(cov[[k]])-1
Vr[start:stop,start:stop]<-cov[[k]]
start <- stop+1
}
}
Vr <- Vr*b$sigma^2
V <- V+Z%*%Vr%*%t(Z)
}
V
}
formXtViX <- function(V,X)
{ X <- X[V$ind,,drop=FALSE]
if (is.list(V$V)) {
Z <- X
j0 <- 1
for (i in 1:length(V$V))
{ Cv <- chol(V$V[[i]])
j1 <- j0+nrow(V$V[[i]])-1
Z[j0:j1,] <- backsolve(Cv,X[j0:j1,,drop=FALSE],transpose=TRUE)
j0 <- j1 + 1
}
} else if (is.matrix(V$V)) {
Cv <- chol(V$V)
Z <- backsolve(Cv,X,transpose=TRUE)
} else {
Z <- X/sqrt(as.numeric(V$V))
}
qrz <- qr(Z,LAPACK=TRUE)
R <- qr.R(qrz);R[,qrz$pivot] <- R
colnames(R) <- colnames(X)
R
}
new.name <- function(proposed,old.names)
{ prop <- proposed
k <- 0
while (sum(old.names==prop))
{ prop<-paste(proposed,".",k,sep="")
k <- k + 1
}
prop
}
gammPQL <- function (fixed, random, family, data, correlation, weights,
control, niter = 30, verbose = TRUE, mustart=NULL, etastart=NULL, ...) {
off <- model.offset(data)
if (is.null(off)) off <- 0
y <- model.response(data)
nobs <- nrow(data)
if (is.null(weights)) weights <- rep(1, nrow(data))
start <- NULL
if (is.null(mustart)) {
eval(family$initialize)
} else {
mukeep <- mustart
eval(family$initialize)
mustart <- mukeep
}
wts <- weights
wts.name <- new.name("wts",names(data))
data[[wts.name]] <- wts
fam <- family
eta <- if (!is.null(etastart))
etastart
else fam$linkfun(mustart)
mu <- fam$linkinv(eta)
w <- wts;
mu.eta.val <- fam$mu.eta(eta)
zz <- eta + (y - mu)/mu.eta.val - off
wz <- w * mu.eta.val^2/fam$variance(mustart)
zz.name <- new.name("zz",names(data))
eval(parse(text=paste("fixed[[2]] <- quote(",zz.name,")")))
data[[zz.name]] <- zz
invwt.name <- new.name("invwt",names(data))
data[[invwt.name]] <- 1/wz
w.formula <- as.formula(paste("~",invwt.name,sep=""))
converged <- FALSE
if (family$family %in% c("poisson","binomial")) {
control$sigma <- 1
control$apVar <- FALSE
}
for (i in 1:niter) {
if (verbose) message(gettextf("iteration %d", i))
fit <- lme(fixed=fixed,random=random,data=data,correlation=correlation,
control=control,weights=varFixed(w.formula),method="ML",...)
etaold <- eta
eta <- fitted(fit) + off
if (sum((eta - etaold)^2) < 1e-06 * sum(eta^2)) {
converged <- TRUE
break
}
mu <- fam$linkinv(eta)
mu.eta.val <- fam$mu.eta(eta)
data[[zz.name]] <- eta + (y - mu)/mu.eta.val - off
wz <- w * mu.eta.val^2/fam$variance(mu)
data[[invwt.name]] <- 1/wz
}
if (!converged) warning("gamm not converged, try increasing niterPQL")
fit$y <- y
fit$w <- w
fit
}
gamm <- function(formula,random=NULL,correlation=NULL,family=gaussian(),data=list(),weights=NULL,
subset=NULL,na.action,knots=NULL,control=list(niterEM=0,optimMethod="L-BFGS-B",returnObject=TRUE),
niterPQL=20,verbosePQL=TRUE,method="ML",drop.unused.levels=TRUE,mustart=NULL, etastart=NULL,...)
{ if (inherits(family,"extended.family")) warning("family are not designed for use with gamm!")
if (inherits(family,"extended.family")) warning("gamm is not designed to use extended families")
control <- do.call("lmeControl",control)
if (!is.null(random))
{ if (is.list(random))
{ r.names<-names(random)
if (is.null(r.names)) stop("random argument must be a *named* list.")
else if (sum(r.names=="")) stop("all elements of random list must be named")
}
else stop("gamm() can only handle random effects defined as named lists")
random.vars<-c(unlist(lapply(random, function(x) all.vars(formula(x)))),r.names)
} else random.vars<-NULL
if (!is.null(correlation)) {
cor.for<-attr(correlation,"formula")
if (!is.null(cor.for)) cor.vars<-all.vars(cor.for)
} else cor.vars<-NULL
wisvf <- try(inherits(weights,"varFunc"),silent=TRUE)
if (inherits(wisvf,"try-error")) wisvf <- FALSE
if (wisvf) {
if (inherits(weights,"varComb")) {
vf.vars <- rep("",0)
for (i in 1:length(weights)) {
vf.vars <- c(vf.vars,all.vars(attr(weights[[i]],"formula")))
}
vf.vars <- unique(vf.vars)
} else {
vf.for<-attr(weights,"formula")
if (!is.null(vf.for)) vf.vars<-all.vars(vf.for)
}
} else vf.vars <- NULL
gp <- interpret.gam(formula)
mf <- match.call(expand.dots=FALSE)
mf$formula <- gp$fake.formula
if (wisvf) {
mf$correlation <- mf$random <- mf$family <- mf$control <- mf$scale <- mf$knots <- mf$sp <- mf$weights <-
mf$min.sp <- mf$H <- mf$gamma <- mf$fit <- mf$niterPQL <- mf$verbosePQL <- mf$G <- mf$method <- mf$... <- NULL
} else {
mf$correlation <- mf$random <- mf$family <- mf$control <- mf$scale <- mf$knots <- mf$sp <-
mf$min.sp <- mf$H <- mf$gamma <- mf$fit <- mf$niterPQL <- mf$verbosePQL <- mf$G <- mf$method <- mf$... <- NULL
}
mf$drop.unused.levels <- drop.unused.levels
mf[[1]] <- quote(stats::model.frame)
pmf <- mf
gmf <- eval(mf, parent.frame())
gam.terms <- attr(gmf,"terms")
if (!wisvf) weights <- gmf[["(weights)"]]
allvars <- c(cor.vars,random.vars,vf.vars)
if (length(allvars)) {
mf$formula <- as.formula(paste(paste(deparse(gp$fake.formula,backtick=TRUE),collapse=""),
"+",paste(allvars,collapse="+")))
mf <- eval(mf, parent.frame())
}
else mf <- gmf
rm(gmf)
if (nrow(mf)<2) stop("Not enough (non-NA) data to do anything meaningful")
vars <- all.vars1(gp$fake.formula[-2])
inp <- parse(text = paste("list(", paste(vars, collapse = ","),")"))
dl <- eval(inp, data, parent.frame())
names(dl) <- vars
var.summary <- variable.summary(gp$pf,dl,nrow(mf))
rm(dl)
pmf$formula <- gp$pf
pmf <- eval(pmf, parent.frame())
pTerms <- attr(pmf,"terms")
if (is.character(family)) family<-eval(parse(text=family))
if (is.function(family)) family <- family()
if (is.null(family$family)) stop("family not recognized")
G <- gamm.setup(gp,pterms=pTerms,
data=mf,knots=knots,parametric.only=FALSE,absorb.cons=TRUE)
G$var.summary <- var.summary
mf <- G$data
n.sr <- length(G$random)
if (is.null(random)&&n.sr==0)
stop("gamm models must have at least 1 smooth with unknown smoothing parameter or at least one other random effect")
offset.name <- attr(mf,"names")[attr(attr(mf,"terms"),"offset")]
yname <- new.name("y",names(mf))
eval(parse(text=paste("mf$",yname,"<-G$y",sep="")))
Xname <- new.name("X",names(mf))
eval(parse(text=paste("mf$",Xname,"<-G$X",sep="")))
fixed.formula <- paste(yname,"~",Xname,"-1")
fixed.formula <- as.formula(fixed.formula)
rand <- G$random
if (!is.null(random))
{ r.m <- length(random)
r.names <- c(names(rand),names(random))
for (i in 1:r.m) rand[[n.sr+i]]<-random[[i]]
names(rand) <- r.names
}
if (length(formula(correlation)))
{
corGroup <- paste(names(rand),collapse="/")
groupForm<-nlme::getGroupsFormula(correlation)
if (!is.null(groupForm)) {
groupFormNames <- all.vars(groupForm)
exind <- groupFormNames %in% names(rand)
groupFormNames <- groupFormNames[!exind]
if (length(groupFormNames)) corGroup <-
paste(corGroup,paste(groupFormNames,collapse="/"),sep="/")
}
corForm <- as.formula(paste(deparse(nlme::getCovariateFormula(correlation)),"|",corGroup))
attr(correlation,"formula") <- corForm
}
ret <- list()
if (family$family=="gaussian"&&family$link=="identity"&&
length(offset.name)==0) lme.used <- TRUE else lme.used <- FALSE
if (lme.used&&!is.null(weights)&&!wisvf) lme.used <- FALSE
if (lme.used) {
eval(parse(text=paste("ret$lme<-lme(",deparse(fixed.formula),
",random=rand,data=strip.offset(mf),correlation=correlation,",
"control=control,weights=weights,method=method)"
,sep="" )))
} else {
if (wisvf) stop("weights must be like glm weights for generalized case")
if (verbosePQL) cat("\n Maximum number of PQL iterations: ",niterPQL,"\n")
eval(parse(text=paste("ret$lme<-gammPQL(",deparse(fixed.formula),
",random=rand,data=strip.offset(mf),family=family,",
"correlation=correlation,control=control,",
"weights=weights,niter=niterPQL,verbose=verbosePQL,mustart=mustart,etastart=etastart,...)",sep="")))
G$y <- ret$lme$y
}
object <- list(model=mf,formula=formula,smooth=G$smooth,nsdf=G$nsdf,family=family,
df.null=nrow(G$X),y=G$y,terms=gam.terms,pterms=G$pterms,xlevels=G$xlevels,
contrasts=G$contrasts,assign=G$assign,na.action=attr(mf,"na.action"),
cmX=G$cmX,var.summary=G$var.summary,scale.estimated=TRUE)
pvars <- all.vars(delete.response(object$terms))
object$pred.formula <- if (length(pvars)>0) reformulate(pvars) else NULL
bf <- as.numeric(ret$lme$coefficients$fixed)
br <- as.numeric(unlist(lapply(ret$lme$coefficients$random,t)))
fs.present <- FALSE
if (G$nsdf) p <- bf[1:G$nsdf] else p <- array(0,0)
if (G$m>0) for (i in 1:G$m)
{ fx <- G$smooth[[i]]$fixed
first <- G$smooth[[i]]$first.f.para;last <- G$smooth[[i]]$last.f.para
if (first <=last) beta <- bf[first:last] else beta <- array(0,0)
if (fx) p <- c(p, beta) else {
ind <- G$smooth[[i]]$rind
if (!is.null(G$smooth[[i]]$fac)) {
fs.present <- TRUE
if (first<=last) stop("Nested smooths must be fully random")
flev <- levels(G$smooth[[i]]$fac)
for (j in 1:length(flev)) {
b <- br[ind]
b <- G$smooth[[i]]$trans.D*b
if (!is.null(G$smooth[[i]]$trans.U)) b <- G$smooth[[i]]$trans.U%*%b
ind <- ind + G$smooth[[i]]$rinc
p <- c(p,b)
}
} else {
b <- c(br[ind],beta)
b <- G$smooth[[i]]$trans.D*b
if (!is.null(G$smooth[[i]]$trans.U)) b <- G$smooth[[i]]$trans.U%*%b
p <- c(p,b)
}
}
}
var.param <- coef(ret$lme$modelStruct$reStruct)
n.v <- length(var.param)
spl <- list()
if (G$m>0) for (i in 1:G$m)
{ ii <- G$pord[i]
n.sp <- length(object$smooth[[ii]]$S)
if (n.sp>0) {
if (inherits(object$smooth[[ii]],"tensor.smooth"))
spl[[ii]] <- notExp2(var.param[(n.v-n.sp+1):n.v])
else
spl[[ii]] <- 1/notExp2(var.param[n.v:(n.v-n.sp+1)])
}
n.v <- n.v - n.sp
}
object$sp <- rep(0,0)
if (length(spl)) for (i in 1:length(spl)) if (!is.null(spl[[i]])) object$sp <- c(object$sp,spl[[i]])
if (length(object$sp)==0) object$sp <- NULL
object$coefficients <- p
V <- extract.lme.cov2(ret$lme,mf,n.sr+1)
first.para <- last.para <- rep(0,G$m)
if (fs.present) {
Xf <- G$Xf[,1:G$nsdf,drop=FALSE]
if (G$m>0) for (i in 1:G$m) {
ind <- object$smooth[[i]]$first.para:object$smooth[[i]]$last.para
if (is.null(object$smooth[[i]]$fac)) {
first.para[i] <- ncol(Xf)+1
Xf <- cbind(Xf,G$Xf[,ind])
last.para[i] <- ncol(Xf)
} else {
flev <- levels(object$smooth[[i]]$fac)
first.para[i] <- ncol(Xf)+1
for (k in 1:length(flev)) {
Xf <- cbind(Xf,G$Xf[,ind]*as.numeric(object$smooth[[i]]$fac==flev[k]))
}
last.para[i] <- ncol(Xf)
}
}
object$R <- formXtViX(V,Xf)
XVX <- crossprod(object$R)
nxf <- ncol(Xf)
} else {
if (G$m>0) for (i in 1:G$m) {
first.para[i] <- object$smooth[[i]]$first.para
last.para[i] <- object$smooth[[i]]$last.para
}
object$R <- formXtViX(V,G$Xf)
XVX <- crossprod(object$R)
nxf <- ncol(G$Xf)
}
object$R <- object$R*ret$lme$sigma
S <- matrix(0,nxf,nxf)
first <- G$nsdf+1
k <- 1
if (G$m>0) for (i in 1:G$m) {
if (is.null(object$smooth[[i]]$fac)) {
ind <- first.para[i]:last.para[i]
ns <-length(object$smooth[[i]]$S)
if (ns) for (l in 1:ns) {
S[ind,ind] <- S[ind,ind] +
object$smooth[[i]]$S[[l]]*object$sp[k]
k <- k+1
}
} else {
flev <- levels(object$smooth[[i]]$fac)
ind <- first.para[i]:(first.para[i]+object$smooth[[i]]$n.para-1)
ns <- length(object$smooth[[i]]$S)
for (j in 1:length(flev)) {
if (ns) for (l in 1:ns) {
S[ind,ind] <- S[ind,ind] +
object$smooth[[i]]$S[[l]]*object$sp[k]
k <- k+1
}
k <- k - ns
ind <- ind + object$smooth[[i]]$n.para
}
k <- k + ns
}
}
S <- S/ret$lme$sigma^2
if (G$m) for (i in 1:G$m) {
object$smooth[[i]]$first.para <- first.para[i]
object$smooth[[i]]$last.para <- last.para[i]
}
ev <- eigen(XVX+S,symmetric=TRUE)
ind <- ev$values != 0
iv <- ev$values;iv[ind] <- 1/ev$values[ind]
Vb <- ev$vectors%*%(iv*t(ev$vectors))
object$edf<-rowSums(Vb*t(XVX))
object$df.residual <- length(object$y) - sum(object$edf)
object$sig2 <- ret$lme$sigma^2
if (lme.used) { object$method <- paste("lme.",method,sep="")}
else { object$method <- "PQL"}
if (!lme.used||method=="ML") Vb <- Vb*length(G$y)/(length(G$y)-G$nsdf)
object$Vp <- Vb
object$Ve <- Vb%*%XVX%*%Vb
object$prior.weights <- weights
class(object) <- "gam"
if (!is.null(G$P)) {
object$coefficients <- G$P %*% object$coefficients
object$Vp <- G$P %*% object$Vp %*% t(G$P)
object$Ve <- G$P %*% object$Ve %*% t(G$P)
}
object$linear.predictors <- predict.gam(object,type="link")
object$fitted.values <- object$family$linkinv(object$linear.predictors)
object$residuals <- residuals(ret$lme)
if (G$nsdf>0) term.names<-colnames(G$X)[1:G$nsdf] else term.names<-array("",0)
n.smooth <- length(G$smooth)
if (n.smooth) {
for (i in 1:n.smooth)
{ k <- 1
for (j in object$smooth[[i]]$first.para:object$smooth[[i]]$last.para)
{ term.names[j] <- paste(object$smooth[[i]]$label,".",as.character(k),sep="")
k <- k+1
}
}
if (!is.null(object$sp)) names(object$sp) <- names(G$sp)
}
names(object$coefficients) <- term.names
names(object$edf) <- term.names
if (is.null(weights)) object$prior.weights <- object$y*0+1
else if (wisvf) object$prior.weights <- varWeights.dfo(ret$lme,mf)^2
else object$prior.weights <- ret$lme$w
object$weights <- object$prior.weights
if (!is.null(G$Xcentre)) object$Xcentre <- G$Xcentre
environment(attr(object$model,"terms")) <-
environment(object$terms) <- environment(object$pterms) <-
environment(object$formula) <- .GlobalEnv
if (!is.null(object$pred.formula)) environment(object$pred.formula) <- .GlobalEnv
ret$gam <- object
environment(attr(ret$lme$data,"terms")) <- environment(ret$lme$terms) <- .GlobalEnv
if (!is.null(ret$lme$modelStruct$varStruct)) {
environment(attr(ret$lme$modelStruct$varStruct,"formula")) <- .GlobalEnv
}
if (!is.null(ret$lme$modelStruct$corStruct)) {
environment(attr(ret$lme$modelStruct$corStruct,"formula")) <- .GlobalEnv
}
class(ret) <- c("gamm","list")
ret
}
test.gamm <- function(control=nlme::lmeControl(niterEM=3,tolerance=1e-11,msTol=1e-11))
{ test1<-function(x,z,sx=0.3,sz=0.4)
{ x<-x*20
(pi**sx*sz)*(1.2*exp(-(x-0.2)^2/sx^2-(z-0.3)^2/sz^2)+
0.8*exp(-(x-0.7)^2/sx^2-(z-0.8)^2/sz^2))
}
compare <- function(b,b1,edf.tol=.001)
{ edf.diff <- abs(sum(b$edf)-sum(b1$edf))
fit.cor <- cor(fitted(b),fitted(b1))
if (fit.cor<.999) { cat("FAILED: fit.cor = ",fit.cor,"\n");return()}
if (edf.diff>edf.tol) { cat("FAILED: edf.diff = ",edf.diff,"\n");return()}
cat("PASSED \n")
}
n<-500
x<-runif(n)/20;z<-runif(n);
f <- test1(x,z)
y <- f + rnorm(n)*0.2
control$sigma <- NULL
cat("testing covariate scale invariance ... ")
b <- gamm(y~te(x,z), control=control )
x1 <- x*100
b1 <- gamm(y~te(x1,z),control=control)
res <- compare(b$gam,b1$gam)
cat("testing invariance w.r.t. response ... ")
y1 <- y*100
b1 <- gamm(y1~te(x,z),control=control)
res <- compare(b$gam,b1$gam)
cat("testing equivalence of te(x) and s(x) ... ")
b2 <- gamm(y~te(x,k=10,bs="cr"),control=control)
b1 <- gamm(y~s(x,bs="cr",k=10),control=control)
res <- compare(b2$gam,b1$gam,edf.tol=.1)
cat("testing equivalence of gam and gamm with same sp ... ")
b1 <- gam(y~te(x,z),sp=b$gam$sp)
res <- compare(b$gam,b1)
if (FALSE) cat(res,x1,y1)
}
|
print.edr <-
function(x,...){
if (!inherits(x, "edr")) stop("use only with \"edr\" objects")
cat(paste("Reduction method performed:", x$method),"\n")
cat(" \n")
cat(paste("Number of observations:", x$n),"\n")
cat(paste("Dimension reduction K:", x$K),"\n")
cat(paste("Number of slices:", paste(x$H, collapse=", ")),"\n")
cat(" \n")
if (is.null(x$matEDR)) {
cat("Indices estimation results:\n")
tmp <- x$indices
colnames(tmp) <- 1:x$K
row.names(tmp) <- paste("estimated index", 1:x$n, sep=" ")
} else {
cat("Result of EDR directions estimation:\n" )
tmp <- matrix(x$matEDR[,1:x$K],ncol=x$K)
row.names(tmp) <- 1:dim(tmp)[1]
colnames(tmp) <- paste("estimated direction",1:x$K,sep=" ")
}
cat("\n")
prmatrix(signif(tmp,3))
cat("\n")
}
|
get.components <- function(id) {
if( length(id) > 1 ) {
stop('Function not vectorized - use apply functions');
}
components <- strsplit(id, split = ':|-')[[ 1 ]];
component.list <- list(
chr = components[1],
start = as.numeric(components[2]),
end = as.numeric(components[3])
);
return(component.list);
}
|
multi.mcp <- function(X, Y, p.fac = NULL, fold.num) {
if (is.null(p.fac)) {
p.fac <- rep(1, ncol(X))
}
mcp_cv <- ncvreg::cv.ncvreg(X = X, y = Y, penalty = "MCP", penalty.factor = p.fac,
family = "gaussian", gamma = 3, nfolds = fold.num)
n <- nrow(X)
nzero <- (colSums(mcp_cv$fit$beta != 0) - 1)
lambda.index <- which(nzero < (n - floor(n/2)))
lambda_hat <- mcp_cv$lambda[lambda.index[which.min(mcp_cv$cve[lambda.index])]]
beta.est <- coef(mcp_cv, lambda=lambda_hat)
selected.index <- which(beta.est!=0,arr.ind = T)[-1]-1
unselected.index <- which(beta.est==0,arr.ind = T)-1
return (list("selected.index"=selected.index, "unselected.index"=unselected.index))
}
|
matdistl2dnormpar <-
function(meanL, varL)
{
n <- length(meanL)
W = diag(0, nrow = n)
dimnames(W) = list(names(meanL), names(meanL))
W = matipl2dpar(meanL, varL)
norme <- sqrt(diag(W))
for (i in 2:n) for (j in 1:i)
W[i, j] <- W[j, i] <- W[i, j]/(norme[i]*norme[j])
distances = diag(0, nrow = n)
dimnames(distances) = list(names(meanL), names(meanL))
for (i in 2:n) for (j in 1:(i-1)) {
distances[i, j] = distances[j, i] = sqrt( 2 - 2 * W[i, j] )
}
as.dist(distances)
}
|
send_unsecure <- function(data, send.more=FALSE)
{
pbdZMQ::send.socket(getval(socket), data=data, send.more=send.more)
}
send_secure <- function(data, send.more=FALSE)
{
serialized <- serialize(data, NULL)
encrypted <- sodium::auth_encrypt(serialized, getkey(private), getkey(theirs))
send_unsecure(data=encrypted, send.more=send.more)
}
receive_unsecure <- function()
{
msg <- pbdZMQ::receive.socket(getval(socket))
if (identical(msg, magicmsg_first_connection))
{
first_receive()
return(magicmsg_first_connection)
}
msg
}
receive_secure <- function()
{
encrypted <- pbdZMQ::receive.socket(getval(socket))
if (identical(encrypted, magicmsg_first_connection))
{
first_receive()
return(magicmsg_first_connection)
}
raw <- sodium::auth_decrypt(encrypted, getkey(private), getkey(theirs))
unserialize(raw)
}
remoter_send <- function(data, send.more=FALSE)
{
if (getval(secure))
send_secure(data=data, send.more=send.more)
else
send_unsecure(data=data, send.more=send.more)
}
remoter_receive <- function()
{
if (getval(secure))
receive_secure()
else
receive_unsecure()
}
first_send <- function()
{
send_unsecure(magicmsg_first_connection)
security <- receive_unsecure()
if (security && !has.sodium())
stop("remoter server communications are encrypted but the 'sodium' package is not detected on the client. Please install the 'sodium' package, or start an unsecure server.")
else if (!security && has.sodium())
cat("WARNING: server not secure; communications are not encrypted.\n")
set(secure, security)
if (getval(secure))
{
send_unsecure(NULL)
setkey(theirs, receive_unsecure())
send_unsecure(getkey(public))
}
else
send_unsecure(NULL)
invisible()
}
first_receive <- function()
{
logprint(level="INIT", "Receiving first connection from client...", checkverbose=TRUE)
logprint(level="INIT", paste("alerting that server", ifelse(getval(secure), "is", "isn't"), "secure"), checkverbose=TRUE)
send_unsecure(getval(secure))
logprint(level="INIT", "receiving security acknowledgement from client", checkverbose=TRUE)
if (getval(secure))
{
receive_unsecure()
logprint(level="AUTH", "sending server public key", checkverbose=TRUE)
send_unsecure(getkey(public))
logprint(level="AUTH", "receiving client public key", checkverbose=TRUE)
setkey(theirs, receive_unsecure())
}
else
receive_unsecure()
invisible()
}
|
prodestACF <- function(Y, fX, sX, pX, idvar, timevar, R = 20, cX = NULL, opt = 'optim',
theta0 = NULL, cluster = NULL){
Start = Sys.time()
Y <- checkM(Y)
fX <- checkM(fX)
sX <- checkM(sX)
pX <- checkM(pX)
idvar <- checkM(idvar)
timevar <- checkM(timevar)
snum <- ncol(sX)
fnum <- ncol(fX)
if (!is.null(cX)) {cX <- checkM(cX); cnum <- ncol(cX)} else {cnum <- 0}
if (length(theta0) != cnum + fnum + snum & !is.null(theta0)){
stop(paste0('theta0 length (', length(theta0), ') is inconsistent with the number of parameters (', cnum + fnum + snum, ')'), sep = '')
}
polyframe <- data.frame(fX,sX,pX)
mod <- model.matrix( ~.^2-1, data = polyframe)
mod <- mod[match(rownames(polyframe),rownames(mod)),]
regvars <- cbind(mod, fX^2, sX^2, pX^2)
lag.sX = sX
for (i in 1:snum) {
lag.sX[, i] = lagPanel(sX[, i], idvar = idvar, timevar = timevar)
}
lag.fX = fX
for (i in 1:fnum) {
lag.fX[, i] = lagPanel(fX[, i], idvar = idvar, timevar = timevar)
}
if (!is.null(cX)) {
data <- as.matrix(data.frame(Y = Y, idvar = idvar, timevar = timevar, Z = data.frame(lag.fX, sX),
Xt = data.frame(fX, sX), lX = data.frame(lag.fX, lag.sX),
cX = data.frame(cX), regvars = regvars))
} else {
data <- as.matrix(data.frame(Y = Y, idvar = idvar, timevar = timevar, Z = data.frame(lag.fX, sX),
Xt = data.frame(fX, sX), lX = data.frame(lag.fX,lag.sX), regvars = regvars))
}
betas <- finalACF(ind = TRUE, data = data, fnum = fnum, snum = snum, cnum = cnum, opt = opt, theta0 = theta0)
boot.indices <- block.boot.resample(idvar, R)
if (is.null(cluster)){
nCores = NULL
boot.betas <- matrix(unlist(
lapply(boot.indices, finalACF, data = data, fnum = fnum, snum = snum, cnum = cnum, opt = opt,
theta0 = theta0, boot = TRUE)), ncol = fnum + snum + cnum, byrow = TRUE)
} else {
nCores = length(cluster)
clusterEvalQ(cl = cluster, library(prodest))
boot.betas <- matrix( unlist( parLapply(cl = cluster, boot.indices, finalACF, data = data, fnum = fnum, snum = snum,
cnum = cnum, opt = opt, theta0 = theta0, boot = TRUE) ),
ncol = fnum + snum + cnum, byrow = TRUE )
}
boot.errors <- apply(boot.betas, 2, sd, na.rm = TRUE)
res.names <- c(colnames(fX, do.NULL = FALSE, prefix = 'fX'),
colnames(sX, do.NULL = FALSE, prefix = 'sX') )
if (!is.null(cX)) {
res.names <- c(res.names, colnames(cX, do.NULL = FALSE, prefix = 'cX'))
}
names(betas$betas) <- res.names
names(boot.errors) <- res.names
elapsedTime = Sys.time() - Start
out <- new("prod",
Model = list(method = 'ACF', FSbetas = NA, boot.repetitions = R, elapsed.time = elapsedTime, theta0 = theta0,
opt = opt, opt.outcome = betas$opt.outcome, nCores = nCores),
Data = list(Y = Y, free = fX, state = sX, proxy = pX, control = cX, idvar = idvar, timevar = timevar,
FSresiduals = betas$FSresiduals),
Estimates = list(pars = betas$betas, std.errors = boot.errors))
return(out)
}
finalACF <- function(ind, data, fnum, snum, cnum, opt, theta0, boot = FALSE){
if (sum(as.numeric(ind)) == length(ind)){
newid <- data[ind, 'idvar', drop = FALSE]
} else {
newid <- as.matrix(as.numeric(rownames(ind)))
ind <- as.matrix(ind)
}
data <- data[ind,]
first.stage <- lm(data[,'Y', drop = FALSE] ~ data[, grepl('regvars', colnames(data)), drop = FALSE], na.action = na.exclude)
phi <- fitted(first.stage)
if (is.null(theta0)) {
theta0 <- coef(first.stage)[2:(1 + snum + fnum + cnum)] + rnorm((snum + fnum), 0, 0.01)
}
newtime <- data[,'timevar', drop = FALSE]
rownames(phi) <- NULL
rownames(newtime) <- NULL
lag.phi <- lagPanel(idvar = newid, timevar = newtime, value = phi)
Z <- data[, grepl('Z', colnames(data)), drop = FALSE]
X <- data[, grepl('Xt', colnames(data)), drop = FALSE]
lX <- data[, grepl('lX', colnames(data)), drop = FALSE]
tmp.data <- model.frame(Z ~ X + lX + phi + lag.phi)
W <- solve(crossprod(tmp.data$Z)) / nrow(tmp.data$Z)
if (opt == 'optim'){
try.out <- try(optim(theta0, gACF, method = "BFGS", mZ = tmp.data$Z, mW = W, mX = tmp.data$X,
mlX = tmp.data$lX,
vphi = tmp.data$phi, vlag.phi = tmp.data$lag.phi), silent = TRUE)
if (!inherits(try.out, "try-error")) {
betas <- try.out$par
opt.outcome <- try.out
} else {
betas <- matrix(NA,(snum + fnum), 1)
opt.outcome <- list(convergence = 999)
}
} else if (opt == 'DEoptim'){
try.out <- try(DEoptim(gACF, lower = theta0, upper = rep.int(1,length(theta0)), mZ = tmp.data$Z,
mW = W, mX = tmp.data$X, mlX = tmp.data$lX,
vphi = tmp.data$phi, vlag.phi = tmp.data$lag.phi,
control = DEoptim.control(trace = FALSE)), silent = TRUE)
if (!inherits(try.out, "try-error")) {
betas <- try.out$optim$bestmem
opt.outcome <- try.out
} else {
betas <- matrix(NA, (snum + fnum), 1)
opt.outcome <- list(convergence = 99)
}
} else if (opt == 'solnp'){
try.out <- try(suppressWarnings(solnp(theta0, gACF, mZ = tmp.data$Z, mW = W, mX = tmp.data$X, mlX = tmp.data$lX,
vphi = tmp.data$phi, vlag.phi = tmp.data$lag.phi,
control = list(trace = FALSE))), silent = TRUE)
if (!inherits(try.out, "try-error")) {
betas <- try.out$pars
opt.outcome <- try.out
} else {
betas <- matrix(NA,(snum + fnum), 1)
opt.outcome <- list(convergence = 999)
}
}
if (boot == FALSE){
return(list(betas = betas, opt.outcome = opt.outcome, FSresiduals = resid(first.stage)))
} else {
return(betas)
}
}
gACF <- function(theta, mZ, mW, mX, mlX, vphi, vlag.phi){
Omega <- vphi - mX %*% theta
Omega_lag <- vlag.phi - mlX %*% theta
Omega_lag_pol <- cbind(1, Omega_lag, Omega_lag^2, Omega_lag^3)
g_b <- solve(crossprod(Omega_lag_pol)) %*% t(Omega_lag_pol) %*% Omega
XI <- Omega - Omega_lag_pol %*% g_b
crit <- t(crossprod(mZ, XI)) %*% mW %*% (crossprod(mZ, XI))
return(crit)
}
|
afc.dd = function(obsv,fcst){
fcst.1 = fcst[which(obsv == 1)]
fcst.0 = fcst[which(obsv == 0)]
a = sum(fcst.1)
b = sum(fcst.0)
c = length(fcst.1)-a
d = length(fcst.0)-b
p.afc = (a*d + 0.5*(a*b + c*d))/((a+c)*(b+d))
return(p.afc)
}
|
validate_parameters <- function(response,
n_min,
n_folds,
n_trees,
min_node_impurity,
sample_size,
testSize,
sampleWithReplacement,
useIdentity,
pruning,
parallelize,
use_smote = FALSE,
useOOBEE = FALSE,
calcVarImp = FALSE,
max_features = NA){
response_choices <- c("classify", "regressor")
checkmate::assertChoice(response, response_choices)
checkmate::assertInt(n_min, lower = 1)
checkmate::assertInt(n_folds, lower = 1)
if(is.na(max_features)){
checkmate::assertInt(n_trees, lower = 1, upper = 1)
} else {
checkmate::assertInt(n_trees, lower = 1, upper = 10000)
}
if(typeof(min_node_impurity) == "character"){
checkmate::assert_character(min_node_impurity, pattern = "auto")
} else {
checkmate::assert_number(min_node_impurity, lower = 0.0, upper = 1.0)
}
checkmate::assert_number(sample_size, lower = 0.10, upper = 1.0)
checkmate::assert_number(testSize, lower = 0.0, upper = 0.75)
choices <- c(TRUE, FALSE)
checkmate::assertChoice(sampleWithReplacement, choices)
checkmate::assertChoice(useIdentity, choices)
checkmate::assertChoice(parallelize, choices)
checkmate::assertChoice(pruning, choices)
checkmate::assertChoice(use_smote, choices)
checkmate::assertChoice(useOOBEE, choices)
checkmate::assertChoice(calcVarImp, choices)
if(!is.na(max_features)){
if(is.integer(max_features)){
checkmate::assertInteger(max_features, lower = 1)
} else if(is.double(max_features)){
checkmate::assert_number(max_features, lower = 1.0)
} else {
choices <- c("sqrt", "log2", "None")
checkmate::assertChoice(max_features, choices)
}
}
}
gini_ <- function(y, length_of_y){
m <- length_of_y
num_samples_per_class <- data.frame(table(y))
G <- 1.0 - sum((num_samples_per_class$Freq/m)**2)
return (G)
}
compute_max_features <- function(max_features, n_features_){
if(max_features == "None"){
return(n_features_)
} else if(max_features == "sqrt"){
return(as.integer(sqrt(n_features_)))
} else if(is.integer(max_features)){
return(max_features)
} else if(is.double(max_features)){
return(as.integer(max_features))
} else {
if(pkg.env$show_progress){
message("compute_max_features() max_features unknown, defaulting to n_features_.")
}
return(n_features_)
}
}
find_number_valid_feature_columns <- function(X, n_features_){
debug_msg <- FALSE
initial_feature_list <- 1:n_features_
for(k in 1:n_features_){
if(length(unique(X[,k])) == 1){
initial_feature_list <- initial_feature_list[!initial_feature_list %in% k]
if(debug_msg){
msg <- "find_number_valid_feature_columns() Skipping column %s as all values are the same."
msgs <- sprintf(msg, k)
message(msgs)
}
}
}
return(initial_feature_list)
}
check_package <- function(pkgname){
package.check <- lapply(pkgname, FUN = function(x) {
if (!require(x, character.only = TRUE)) {
library(x, character.only = TRUE)
}
})
}
`%notin%` <- Negate(`%in%`)
is.not.null <- function(x) !is.null(x)
mni.control <- function(mni_trials = 1,
mni_n_folds = 10,
mni_n_trees = 1,
mni_size = 0.01,
mni_start = 0.05,
mni_numvals = 50,
...){
mni_parms <- c(as.list(environment()), list(...))
checkmate::assertInt(mni_parms$mni_trials, lower = 1)
checkmate::assertInt(mni_parms$mni_n_folds, lower = 1)
checkmate::assertInt(mni_parms$mni_n_trees, lower = 1, upper = 1)
checkmate::assert_number(mni_parms$mni_size, lower = 0.001, upper = 0.10)
checkmate::assert_number(mni_parms$mni_start, lower = 0.001, upper = 1.0)
checkmate::assertInt(mni_parms$mni_numvals, lower = 1, upper = 1000)
outp <- list(mni_parms$mni_trials,
mni_parms$mni_n_folds,
mni_parms$mni_n_trees,
mni_parms$mni_size,
mni_parms$mni_start,
mni_parms$mni_numvals)
return(outp)
}
prune.control <- function(prune_type = "ccp",
prune_stochastic_max_nodes = 10,
prune_stochastic_max_depth = 10,
prune_stochastic_samples = 100,
...){
prune_parms <- c(as.list(environment()), list(...))
choices <- c("ccp", "all")
checkmate::assertChoice(prune_parms$prune_type, choices)
checkmate::assertInt(prune_parms$prune_stochastic_max_nodes, lower = 2, upper = 24)
checkmate::assert(prune_parms$prune_stochastic_max_nodes %% 2 == 0)
checkmate::assertInt(prune_parms$prune_stochastic_max_depth, lower = 1)
checkmate::assertInt(prune_parms$prune_stochastic_samples, lower = 1, upper = 10000)
outp <- list(prune_parms$prune_type,
prune_parms$prune_stochastic_max_nodes,
prune_parms$prune_stochastic_max_depth,
prune_parms$prune_stochastic_samples)
return(outp)
}
|
preprocess.pfr <- function (subj=NULL, covariates = NULL, funcs, kz = NULL, kb = NULL, nbasis=10, funcs.new=NULL, smooth.option="fpca.sc",pve=0.99){
N_subj = length(unique(subj))
p = ifelse(is.null(covariates), 0, dim(covariates)[2])
if (is.matrix(funcs)) {
Funcs = list(length = 1)
Funcs[[1]] = funcs
}else {
Funcs = funcs
}
if (is.matrix(funcs.new)) {
Funcs.new = list(length = 1)
Funcs.new[[1]] = funcs.new
}else {
Funcs.new = funcs.new
}
N.Pred = length(Funcs)
if(!is.null(kz)){
if(length(kz)==1) kz = rep(kz,N.Pred)
if(length(kz)!=N.Pred) stop("Length of kz is not the number of predictors\n")
}
kz.adj = rep(NA, N.Pred)
if(is.null(funcs.new)){o.len <- nrow(as.matrix(Funcs[[1]]))
}else{o.len <- nrow(as.matrix(Funcs.new[[1]]))}
t <- phi <- FPCA <- psi <- C <- J <- CJ <- D <- list()
if (smooth.option=="fpca.sc"){
for(i in 1:N.Pred){
t[[i]] = seq(0, 1, length = dim(Funcs[[i]])[2])
FPCA[[i]] = fpca.sc(Y = Funcs[[i]], Y.pred = Funcs.new[[i]], pve=pve, nbasis=nbasis, npc=kz[i])
psi[[i]] = FPCA[[i]]$efunctions
C[[i]]=FPCA[[i]]$scores
kz.adj[i]=FPCA[[i]]$npc
}
}
if (smooth.option=="fpca.face"){
for(i in 1:N.Pred){
Funcs[[i]] = apply(Funcs[[i]],2,function(x){x-0*mean(x,na.rm=TRUE)})
if(!is.null(Funcs.new[[i]])) Funcs.new[[i]] = apply(Funcs.new[[i]],2,function(x){x-0*mean(x,na.rm=TRUE)})
t[[i]] = seq(0, 1, length = dim(Funcs[[i]])[2])
FPCA[[i]] = fpca.face(Y = Funcs[[i]], Y.pred = Funcs.new[[i]], knots=nbasis,pve = pve)
if (is.null(kz[i]) || kz[i]>dim(FPCA[[i]]$efunctions)[2]){
psi[[i]] = FPCA[[i]]$efunctions
C[[i]]=FPCA[[i]]$scores*sqrt(dim(Funcs[[i]])[2])
kz.adj[i] = dim(FPCA[[i]]$efunctions)[2]
cat("For the ", i, "-th functional predictor, the number of PCs changes to", kz.adj[i],"\n");
cat("For details, see the manual\n");
}
else {
psi[[i]] = FPCA[[i]]$efunctions[,1:kz[i]]
C[[i]]=FPCA[[i]]$scores[,1:kz[i]]*sqrt(dim(Funcs[[i]])[2])
kz.adj[i] = kz[i]
}
}
}
for(i in 1:N.Pred){
phi[[i]] = cbind(1, bs(t[[i]], df=kb-1, intercept=FALSE, degree=3))
J[[i]] = t(psi[[i]]) %*% phi[[i]]
CJ[[i]] = C[[i]] %*% J[[i]]
}
if(!is.null(subj)){
Z1 = matrix(0, nrow = o.len, ncol = N_subj)
for (i in 1:length(unique(subj))) {
Z1[which(subj == unique(subj)[i]), i] = 1
}
colnames(Z1)=c(paste("i",1:dim(Z1)[2], sep=""))
D[[1]] = diag(c(rep(0, 1 + p),
rep(1, N_subj),
rep(0, length = N.Pred * (kb))))
totD <- N.Pred+1
startD <- 2
}else{
Z1 <- NULL
totD <- N.Pred
startD <- 1
}
temp=matrix(0, nrow=kb-1, ncol=kb-1)
for(ii in 1:(kb-1)){
for(jj in 1:(kb-1)){
temp[ii,jj]=min(ii,jj)-1
}
}
spl.pen = matrix(1, nrow=kb-1, ncol=kb-1)+temp
Dinv=solve(spl.pen)
for (i in startD:totD) {
D[[i]] = magic::adiag( diag(c(rep(0, 1 + p + N_subj*!is.null(subj)), rep(0, kb * (i - startD)) , rep(0, 1))),
Dinv,
diag(rep(0, kb * (totD - i))))
}
X = cbind(rep(1,o.len), covariates, Z1)
for (i in 1:N.Pred) {
X = cbind(X, CJ[[i]])
}
fixed.mat = X[,1:(1+p)]
rand.mat = Z1
for (i in 1:N.Pred) {
fixed.mat = cbind(fixed.mat, CJ[[i]][,1])
rand.mat = cbind(rand.mat , CJ[[i]][,2:kb])
}
ret <- list( X, D, phi, psi, C, J, CJ,
Z1, subj,
fixed.mat, rand.mat, N_subj, p, N.Pred,
kz, kz.adj, kb, nbasis,
totD,
funcs, covariates, smooth.option)
names(ret) <- c("X", "D", "phi", "psi", "C", "J", "CJ",
"Z1", "subj",
"fixed.mat", "rand.mat", "N_subj", "p", "N.Pred",
"kz", "kz.adj", "kb", "nbasis",
"totD",
"funcs", "covariates", "smooth.option")
ret
}
|
PushGist <- function(mdFile, githubUserName = "") {
reportName <- strsplit(basename(mdFile), ".", fixed = TRUE)[[1]][1]
conf <- getConfig()
pConf <- conf$network$proxy
HTTP_PROXY <- pConf$http
USE_PROXY_URL <- pConf$ip
USE_PROXY_PORT <- pConf$port
Sys.setenv(http_proxy=HTTP_PROXY)
Sys.setenv(https_proxy=HTTP_PROXY)
PAT <- conf$github$PAT[githubUserName]
if (PAT != "") {
tryCatch({
Sys.setenv(GITHUB_PAT=PAT)
gistr::gist_auth()
}, warning = function(war) {
return(paste("Authentication warning:", war))
}, error = function(err) {
return(paste("Authentication error:", err))
})
}
gistId <- as.character(conf$github$gistId[reportName])
if (gistId == "") {
tryCatch({
g <- gistr::run(mdFile, knitopts = list(quiet=TRUE))
gistr::gist_create(g, browse=FALSE)
}, warning = function(war) {
return(paste("Create gist warning:", war))
}, error = function(err){
return(paste("Create gist error:", err))
})
} else {
tryCatch({
g <- gistr::gist(id = gistId)
g <- gistr::update_files(g, gistr::run(mdFile, knitopts = list(quiet=TRUE)))
g <- gistr::update(g)
}, warning = function(war){
return(paste("Update gist warning:", war))
}, error = function(err) {
return(paste("Update gist error:", err))
})
}
}
|
library("dbscan")
data("moons")
plot(moons, pch=20)
cl <- hdbscan(moons, minPts = 5)
cl
plot(moons, col=cl$cluster+1, pch=20)
cl$hc
plot(cl$hc, main="HDBSCAN* Hierarchy")
cl <- hdbscan(moons, minPts = 5)
check <- rep(F, nrow(moons)-1)
core_dist <- kNNdist(moons, k=5-1)
cut_tree <- function(hcl, eps, core_dist){
cuts <- unname(cutree(hcl, h=eps))
cuts[which(core_dist > eps)] <- 0
cuts
}
eps_values <- sort(cl$hc$height, decreasing = T)+.Machine$double.eps
for (i in 1:length(eps_values)) {
cut_cl <- cut_tree(cl$hc, eps_values[i], core_dist)
dbscan_cl <- dbscan(moons, eps = eps_values[i], minPts = 5, borderPoints = F)
check[i] <- (all.equal(rle(cut_cl)$lengths, rle(dbscan_cl$cluster)$lengths) == "TRUE")
}
print(all(check == T))
plot(cl)
plot(cl, gradient = c("yellow", "orange", "red", "blue"))
plot(cl, gradient = c("purple", "blue", "green", "yellow"), scale=1.5)
plot(cl, gradient = c("purple", "blue", "green", "yellow"), show_flat = T)
print(cl$cluster_scores)
head(cl$membership_prob)
plot(moons, col=cl$cluster+1, pch=21)
colors <- mapply(function(col, i) adjustcolor(col, alpha.f = cl$membership_prob[i]),
palette()[cl$cluster+1], seq_along(cl$cluster))
points(moons, col=colors, pch=20)
top_outliers <- order(cl$outlier_scores, decreasing = T)[1:10]
colors <- mapply(function(col, i) adjustcolor(col, alpha.f = cl$outlier_scores[i]),
palette()[cl$cluster+1], seq_along(cl$cluster))
plot(moons, col=colors, pch=20)
text(moons[top_outliers, ], labels = top_outliers, pos=3)
data("DS3")
plot(DS3, pch=20, cex=0.25)
cl2 <- hdbscan(DS3, minPts = 25)
cl2
plot(DS3, col=cl2$cluster+1,
pch=ifelse(cl2$cluster == 0, 8, 1),
cex=ifelse(cl2$cluster == 0, 0.5, 0.75),
xlab=NA, ylab=NA)
colors <- sapply(1:length(cl2$cluster),
function(i) adjustcolor(palette()[(cl2$cluster+1)[i]], alpha.f = cl2$membership_prob[i]))
points(DS3, col=colors, pch=20)
plot(cl2, scale = 3, gradient = c("purple", "orange", "red"), show_flat = T)
|
plot_dendocluster <-
function(spectral_count_object, target_variable, file_title,
hclust_method = "ward.D", correlation_method = "spearman", force = FALSE){
spectral_count_object <- spectral_count_object
if (!force && interactive()) {
response <- select.list(c("yes", "no"), title = "Do you allow to create a pdf file with a dendogram?")
if (response == "yes") {
if ((length(spectral_count_object) == 4) &
(spectral_count_object[[4]] == "spectral_count_object")) {
metadata <- spectral_count_object[[2]]
if(target_variable %in% colnames(metadata)){
elements_meta <- as.character(metadata[[target_variable]])
colors_condition = NULL
unique_conditions <- unique(elements_meta)
print("Indicate colors by name (ex. red) or hexadecimal code (ex.
for(i in 1:length(unique_conditions)){
color <- readline(prompt = paste0("Enter the color for ", unique_conditions[i], ": " ))
colors_condition <- rbind.data.frame(
colors_condition,
cbind.data.frame(condition = as.character(unique_conditions[i]), color = as.character(color))
)
}
colors_vector = NULL
for(i in 1:length(elements_meta)){
for(j in 1:dim(colors_condition)[1]){
if(elements_meta[i] == as.character(colors_condition[j, 1])){
colors_vector <- append(colors_vector, as.character(colors_condition[j, 2]))
}
}
}
ncols <- length(colnames(spectral_count_object[[1]]))
ncolors <- length(colors_vector)
if (ncols == ncolors) {
if (is.character(file_title) == TRUE && nchar(file_title) > 1){
SC_sampple_id <- spectral_count_object[[1]]
colnames(SC_sampple_id) <- metadata$SampleID
max_length_name <- max(nchar(colnames(SC_sampple_id)))
for (sample in 1:c(length(colnames(SC_sampple_id)))) {
sample_name <- names(SC_sampple_id[sample])
length_name <- nchar(sample_name)
length_space <- max_length_name - length_name + 7
length_space <- paste(replicate(length_space, " "), collapse = "")
sample_elements <- nrow(SC_sampple_id[SC_sampple_id[sample] > 0, ])
new_name <- paste(sample_name, length_space, sample_elements)
names(SC_sampple_id)[sample] <- new_name
}
SC_sampple_id_corr <- 1 - cor(SC_sampple_id, method = correlation_method)
SC_sampple_id_dist <- as.dist(SC_sampple_id_corr)
SC_sampple_id_hc <- hclust(SC_sampple_id_dist, method = hclust_method)
SC_sampple_id_dend <- as.dendrogram(SC_sampple_id_hc)
colors_vector <- colors_vector[order.dendrogram(SC_sampple_id_dend)]
labels_colors(SC_sampple_id_dend) <- colors_vector
if(ncolors > 15){
height = ncolors * 0.3
} else {
height = 7
}
old_par <- par(no.readonly = TRUE)
on.exit(suppressWarnings(par(old_par)))
filename <- paste(file_title, ".pdf", sep = "")
pdf(filename, width = 7, height = height)
par(cex = 1.2, mar = c(2, 2, 0, 13))
print(plot(SC_sampple_id_dend, horiz = TRUE))
dev.off()
print("Clustering file generated")
}
else {
stop("The third argument must be a character indication the title of the file")
}
}
else{
stop("Check that the number of colors are equal to the number of samples!")
}
}
else{
var_options <- paste(colnames(metadata), collapse = ", ")
stop(paste(c("The second argument must be ONE of the following options:", var_options), collapse = " "))
}
}
else{
stop("Invalid object")
}
}
else{
stop("No file was created")
}
}
}
|
data(synth)
repl.levs <- function(x, ch.lev){
for (j in 1:length(ch.lev)) x <- gsub(ch.levs[j], j, x)
return(x)
}
d <- paste(synth$data, collapse = " ")
d <- strsplit(d, " ")[[1]]
ch.levs <- levels(as.factor(d))
S <- strsplit(synth$data, " ")
S <- sapply(S, repl.levs, ch.levs)
S <- sapply(S, as.numeric)
C <- click.read(S)
set.seed(123)
N2 <- click.EM(X = C$X, K = 2)
T <- click.predict(M = 3, gamma = N2$gamma, pr = N2$z[1,])
colnames(T) <- ch.levs
T[S[[1]][length(S[[1]])],]
|
bi2ste3 <-
function(m,n,eps,alpha,sw,tolrd,tol,maxh) {
outste3 <- tempfile()
cat(" m = ",m," n = ",n," eps = ",eps," alpha = ",alpha,
"\n","sw = ",sw," tolrd = ",tolrd," tol = ",tol," maxh = ",maxh,"\n",
file=outste3,append=FALSE)
fakl <- rep(0,2000)
hyp0 <- matrix(rep(0,2000*2000),nrow=2000)
rho0l <- log(1-eps)
nn <- m+n
fakl[1+0] <- 0
for (i in 1:2000)
{ qi <- i
fakl[1+i] <- fakl[1+i-1] + log(qi) }
oom0l <- 0
for (is in 1:(nn-1))
{ ixl <- max(0,is-n)
ixu <- min(is,m)
hyp0[2+is,2+ixu] <- 0
for (j in 1:(ixu-ixl+1))
{ ix <- ixu - j
hl <- fakl[1+m] - fakl[1+ix+1] - fakl[1+m-ix-1] +
fakl[1+n] - fakl[1+is-ix-1] - fakl[1+n-is+ix+1]
hyp0[2+is,2+ix] <- exp(hl + (ix+1)*rho0l - oom0l)
hyp0[2+is,2+ix] <- hyp0[2+is,2+ix] + hyp0[2+is,2+ix+1]
}
oom0l <- oom0l + log(hyp0[2+is,2+ixl-1])
for (ix in ixl:(ixu-1))
{ hyp0[2+is,2+ix] <- hyp0[2+is,2+ix] / hyp0[2+is,2+ixl-1]
}
hyp0[2+is,2+ixl-1] <- 1 }
alph_0 <- alpha
nhst <- 0
size <- rejmax(m,n,eps,sw,tolrd,alph_0,fakl,hyp0)
cat("\n","alph_0 =",alph_0," NHST =",nhst," SIZE =",size,file=outste3,append=TRUE)
while (size <= alpha)
{ alph_0 <- alph_0 + .01
size <- rejmax(m,n,eps,sw,tolrd,alph_0,fakl,hyp0)
cat("\n","alph_0 =",alph_0," NHST =",nhst,
" SIZE =",size,file=outste3,append=TRUE) }
nhst <- 0
alph_1 <- alph_0 - .01
alph_2 <- alph_0
repeat
{ nhst <- nhst + 1
alph_0 <- (alph_1 + alph_2) / 2
size <- rejmax(m,n,eps,sw,tolrd,alph_0,fakl,hyp0)
cat("\n","alph_0 =",alph_0," NHST =",nhst," SIZE =",size,file=outste3,append=TRUE)
if (abs(size-alpha) < tol || nhst >= maxh) break
if (abs(size-alpha) >= tol && nhst < maxh)
{ if (size > alpha && size < (alpha + 0.001) ) break }
if (size > alpha) alph_2 <- alph_0
if (size < alpha) alph_1 <- alph_0 }
size <- rejmax(m,n,eps,sw,tolrd,alph_0,fakl,hyp0)
cat("\n","alph_0 =",alph_0," NHST =",nhst," SIZE =",size,file=outste3,append=TRUE)
file.show(outste3)
}
|
library(LoopRig)
ovary_loops <- system.file("extdata/loops", "ovary_hg19.bedpe", package = "LoopRig", mustWork = TRUE)
pancreas_loops <- system.file("extdata/loops", "pancreas_hg19.bedpe", package = "LoopRig", mustWork = TRUE)
spleen_loops <- system.file("extdata/loops", "spleen_hg19.bedpe", package = "LoopRig", mustWork = TRUE)
loops <- LoopsToRanges(ovary_loops, pancreas_loops, spleen_loops, custom_cols = 0)
loops_single <- LoopsToRanges(ovary_loops, custom_cols = 0)
test_that("error handling", {
expect_error(DropLoops(ovary_loops, type = "loop_size", size = c(1000, 10000)), "Please enter an object of LoopRanges class for the 'loop_ranges' parameter")
expect_error(DropLoops(loops, type = "type", size = c(1000, 20000)), "Please enter either 'loop_size' or 'anchor_size' for the 'type' parameter")
expect_error(DropLoops(loops, type = "loop_size", size = 1000), "Please enter a numerical vector of two integers for the 'size' parameter")
})
test_that("class output", {
expect_is(DropLoops(loops, type = "loop_size", size = c(100, 10000)), "LoopRanges")
expect_is(DropLoops(loops, type = "anchor_size", size = c(1000, 25000)), "LoopRanges")
})
|
print.sim.seqtest.cor <- function(x, ...) {
if (!inherits(x, "sim.seqtest.cor")) {
stop("Object is not a sim.seqtest.cor object!")
}
cat("\n Statistical Simulation for the Sequential Triangular Test\n\n")
if (x$spec$alternative == "two.sided") {
cat(" H0: rho =", x$spec$rho, " versus H1: rho !=", x$spec$rho, "\n\n")
} else {
if (x$spec$alternative == "less") {
cat(" H0: rho >=", x$spec$rho, " versus H1: rho <", x$spec$rho, "\n\n")
} else {
cat(" H0: rho <=", x$spec$rho, " versus H1: rho >", x$spec$rho, "\n\n")
}
}
if (length(x$spec$k) == 1 & length(x$spec$beta) == 1) {
cat(" Nominal type-I-risk (alpha): ", x$spec$alpha, "\n",
" Nominal type-II-risk (beta): ", x$spec$beta, "\n",
" Practical relevant effect (delta):", x$spec$delta, "\n",
" n in each sub-sample (k): ", x$spec$k, "\n\n",
" Simulated data based on rho: ", x$spec$rho.sim, "\n",
" Simulation runs: ", x$spec$runs, "\n")
if (x$spec$rho.sim == x$spec$rho) {
cat("\n Estimated empirical type-I-risk (alpha):", x$res$alpha.emp, "\n",
" Average number of steps (AVN): ", x$res$AVN, "\n",
" Average number of sample pairs (ASN): ", x$res$ASN, "\n\n")
} else {
cat("\n Estimated empirical type-II-risk (beta):", formatC(x$res$beta.emp, digits = x$spec$digits, format = "f"), "\n",
" Average number of steps (AVN): ", formatC(x$res$AVN, digits = x$spec$digits, format = "f"), "\n",
" Average number of sample pairs (ASN): ", formatC(x$res$ASN, digits = x$spec$digits, format = "f"), "\n\n")
}
} else {
if (length(x$spec$k) > 1) {
cat(" Nominal type-I-risk (alpha): ", x$spec$alpha, "\n",
" Nominal type-II-risk (beta): ", x$spec$beta, "\n",
" Practical relevant effect (delta):", x$spec$delta, "\n\n",
" Simulated data based on rho: ", x$spec$rho.sim, "\n",
" Simulation runs: ", x$spec$runs, "\n\n")
cat(" Estimated empirical type-I-risk (alpha):\n")
for (i in x$spec$k) {
cat(paste0(" k = ", i, ": ", formatC(x$res$p.H1[x$res$k == i], digits = x$spec$digits, format = "f")), "\n")
}
cat("\n Average number of steps (AVN):\n")
for (i in x$spec$k) {
cat(paste0(" k = ", i, ": ", formatC(x$res$AVN[x$res$k == i], digits = x$spec$digits, format = "f")), "\n")
}
cat("\n Average number of sample pairs (ASN):\n")
for (i in x$spec$k) {
cat(paste0(" k = ", i, ": ", formatC(x$res$ASN[x$res$k == i], digits = x$spec$digits, format = "f")), "\n")
}
} else {
cat(" Nominal type-I-risk (alpha): ", x$spec$alpha, "\n",
" Practical relevant effect (delta):", x$spec$delta, "\n",
" n in each sub-sample (k): ", x$spec$k, "\n\n",
" Simulated data based on rho: ", x$spec$rho.sim, "\n",
" Simulation runs: ", x$spec$runs, "\n\n")
cat(" Estimated empirical type-II-risk (beta):\n")
digits <- max(nchar(x$spec$beta)) - 2
for (i in x$spec$beta) {
cat(paste0(" Nominal beta = ", formatC(i, format = "f", digits = digits), ": ",
formatC(x$res$beta.emp[x$res$beta.nom == i], digits = x$spec$digits, format = "f")), "\n")
}
cat("\n Average number of steps (AVN):\n")
for (i in x$spec$beta) {
cat(paste0(" Nominal beta = ", formatC(i, format = "f", digits = digits), ": ",
formatC(x$res$AVN[x$res$beta.nom == i], digits = x$spec$digits, format = "f")), "\n")
}
cat("\n Average number of sample pairs (ASN):\n")
for (i in x$spec$beta) {
cat(paste0(" Nominal beta = ", formatC(i, format = "f", digits = digits), ": ",
formatC(x$res$ASN[x$res$beta.nom == i], digits = x$spec$digits, format = "f")), "\n")
}
}
cat("\n")
}
}
|
write_vc <- function(work_item, path_absolute, output_dir, export_as) {
if (path_absolute) {
output_path <- here::here(output_dir, paste0(work_item$BIBTEXKEY, ".html"))
} else {
output_path <- file.path(output_dir, paste0(work_item$BIBTEXKEY, ".html"))
}
if (export_as == "html_full") {
tryCatch(
expr = {
htmltools::save_html(work_item$vcs, file = here::here(output_path))
},
error = function(e) {
message("Could not save the HTML output:")
print(e)
},
warning = function(w) {
message("Having difficulties saving the HTML output:")
print(w)
}
)
} else if (export_as == "html") {
tryCatch(
expr = {
write(
as.character(htmltools::as.tags(work_item$vcs)),
file = here::here(output_path)
)
},
error = function(e) {
message("Could not save the HTML output:")
print(e)
},
warning = function(w) {
message("Having difficulties saving the HTML output:")
print(w)
}
)
} else if (export_as == "png") {
if (!webshot::is_phantomjs_installed()) {
message("You need to download and install phantomJS to save output as PNG. Try running 'webshot::install_phantomjs()' once.")
} else {
tryCatch(
expr = {
htmltools::save_html(work_item$vcs, file = here::here(output_path))
},
error = function(e) {
message("Could not save the intermediate HTML output:")
print(e)
},
warning = function(w) {
message("Having difficulties saving the intermediate HTML output:")
print(w)
}
)
tryCatch(
expr = {
webshot::webshot(output_path, paste0(output_path, ".png"), selector = ".visual-citation", zoom = 2)
},
error = function(e) {
message("Could not take a screenshot of the intermediate HTML.")
print(e)
},
warning = function(w) {
message("Having difficulties taking a screenshot of the intermediate HTML output:")
print(w)
}
)
unlink(output_path)
return(paste0(output_path, ".png"))
}
} else {
stop("Output format unknown")
}
return(as.character(output_path))
}
|
makeRLearner.classif.LiblineaRL1LogReg = function() {
makeRLearnerClassif(
cl = "classif.LiblineaRL1LogReg",
package = "LiblineaR",
par.set = makeParamSet(
makeNumericLearnerParam(id = "cost", default = 1, lower = 0),
makeNumericLearnerParam(id = "epsilon", default = 0.01, lower = 0),
makeLogicalLearnerParam(id = "bias", default = TRUE),
makeNumericVectorLearnerParam(id = "wi", len = NA_integer_),
makeIntegerLearnerParam(id = "cross", default = 0L, lower = 0L, tunable = FALSE),
makeLogicalLearnerParam(id = "verbose", default = FALSE, tunable = FALSE)
),
properties = c("twoclass", "multiclass", "numerics", "class.weights", "prob"),
class.weights.param = "wi",
name = "L1-Regularized Logistic Regression",
short.name = "liblinl1logreg",
callees = "LiblineaR"
)
}
trainLearner.classif.LiblineaRL1LogReg = function(.learner, .task, .subset, .weights = NULL, ...) {
d = getTaskData(.task, .subset, target.extra = TRUE)
LiblineaR::LiblineaR(data = d$data, target = d$target, type = 6L, ...)
}
predictLearner.classif.LiblineaRL1LogReg = function(.learner, .model, .newdata, ...) {
if (.learner$predict.type == "response") {
as.factor(predict(.model$learner.model, newx = .newdata, ...)$predictions)
} else {
predict(.model$learner.model, newx = .newdata, proba = TRUE, ...)$probabilities
}
}
|
create_barebone <- function(path){
dir.create(path, showWarnings = FALSE, recursive = TRUE)
src <- system.file("builtin-templates", "AdminLTE3-bare", package = "shidashi")
fs <- list.files(src, full.names = TRUE, recursive = FALSE, all.files = FALSE,
no.. = TRUE, include.dirs = TRUE)
file.copy(
from = fs,
to = path,
overwrite = TRUE,
recursive = TRUE,
copy.date = TRUE
)
{
writeLines(
c(
"{",
" library(shiny)",
" server <- function(input, output, session) {",
" shiny::observeEvent(session$clientData$url_search, {",
" req <- list(QUERY_STRING = session$clientData$url_search)",
" resource <- shidashi::load_module(request = req)",
" if (resource$has_module) {",
" module_table <- shidashi::module_info()",
" module_table <- module_table[module_table$id %in% ",
" resource$module$id, ]",
" if (nrow(module_table)) {",
" group_name <- as.character(module_table$group[[1]])",
" if (is.na(group_name)) {",
" group_name <- \"<no group>\"",
" }",
" if (system.file(package = \"logger\") != \"\") {",
" logger::log_info(\"Loading - { module_table$label[1] } ({group_name}/{ module_table$id })\")",
" }",
" shiny::moduleServer(resource$module$id, resource$module$server, ",
" session = session)",
" }",
" }",
" })",
" }",
"}"
), file.path(path, "server.R"))
}
dir.create(file.path(path, 'R'), showWarnings = FALSE, recursive = TRUE)
dir.create(file.path(path, 'modules', 'module_id', 'R'), showWarnings = FALSE, recursive = TRUE)
{
writeLines(
c(
"library(shiny)",
"page_title <- function(complete = TRUE){",
" if(complete){",
" \"Shiny Dashboard Template - Barebone\"",
" } else {",
" \"ShiDashi\"",
" }",
"}",
"page_logo <- function(size = c(\"normal\", \"small\", \"large\")){",
"
"
" NULL",
"}",
"page_loader <- function(){",
"
" shiny::div(",
" class = \"preloader flex-column justify-content-center align-items-center\",",
" shiny::img(",
" class = \"animation__shake\",",
" src = page_logo(\"large\"),",
" alt = \"Logo\", height=\"60\", width=\"60\"",
" )",
" )",
"}",
"body_class <- function(){",
" c(",
"
"
"",
"
"
"",
"
"
"",
"
" \"layout-fixed\",",
"",
"
"
"",
"
" \"navbar-iframe-hidden\",",
"",
"
" \"dark-mode\"",
"",
"
"
"",
" )",
"}",
"nav_class <- function(){",
" c(",
" \"main-header\",",
" \"navbar\",",
" \"navbar-expand\",",
" \"navbar-dark\",",
" \"navbar-primary\"",
" )",
"}",
"",
"module_breadcrumb <- function(){}"
),
con = file.path(path, 'R', 'common.R'))
}
{
writeLines(
c(
"library(shiny)",
"library(shidashi)",
"ui <- function(){",
"",
" fluidPage(",
" fluidRow(",
" column(",
" width = 12L,",
"",
"
" plotOutput(ns(\"plot\"))",
" )",
" )",
" )",
"",
"}",
"",
"server_chunk_1 <- function(input, output, session, ...){",
"",
" event_data <- register_session_events()",
"",
" output$plot <- renderPlot({",
" theme <- get_theme(event_data)",
" set.seed(1)",
" par(",
" bg = theme$background, fg = theme$foreground,",
" col.main = theme$foreground,",
" col.axis = theme$foreground,",
" col.lab = theme$foreground",
" )",
" hist(rnorm(1000))",
" })",
"",
"}"
),
con = file.path(path, 'modules', 'module_id', 'R', "chunk-1.R")
)
}
{
writeLines(
c(
"library(shiny)",
"library(shidashi)",
"",
"server <- function(input, output, session, ...){",
"",
" shared_data <- shidashi::register_session_id(session)",
"",
" server_chunk_1(input, output, session, ...)",
"",
"}"
),
con = file.path(path, 'modules', 'module_id', 'server.R')
)
}
invisible()
}
|
options(width = 80)
options(digits = 6)
logfO2 <- "log<i>f</i><sub>O<sub>2</sub></sub>"
zc <- "<i>Z</i><sub>C</sub>"
o2 <- "O<sub>2</sub>"
h2o <- "H<sub>2</sub>O"
sio2 <- "SiO<sub>2</sub>"
ch4 <- "CH<sub>4</sub>"
library(knitr)
opts_chunk$set(tidy = FALSE, cache.extra = packageVersion('tufte'))
options(htmltools.dir.version = FALSE)
knit_hooks$set(small.mar = function(before, options, envir) {
if (before) par(mar = c(4.2, 4.2, .1, .1))
})
knit_hooks$set(tiny.mar = function(before, options, envir) {
if (before) par(mar = c(.1, .1, .1, .1))
})
knit_hooks$set(smallish.mar = function(before, options, envir) {
if (before) par(mar = c(4.2, 4.2, 0.9, 0.9))
})
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
dpi <- 50
knit_hooks$set(custom.plot = hook_plot_custom)
hook_plot <- knit_hooks$get("plot")
knit_hooks$set(plot = function(x, options) {
x <- hook_plot(x, options)
if (!is.null(options$embed.tag) && options$embed.tag) x <- gsub("<img ", "<embed ", x)
x
})
now = Sys.time()
knit_hooks$set(timeit = function(before) {
if (before) { now <<- Sys.time() }
else {
paste("%", sprintf("Chunk rendering time: %s seconds.\n", round(Sys.time() - now, digits = 3)))
}
})
timeit <- NULL
color_block = function(color) {
function(x, options) sprintf('<pre style="color:%s">%s</pre>', color, x)
}
knit_hooks$set(warning = color_block('magenta'), error = color_block('red'), message = color_block('blue'))
library(CHNOSZ)
reset()
info("CH4")
info("CH4", "gas")
info("methane")
info("oxygen")
info("carbon dioxide")
info("S")
info("S2")
iCH4 <- info("CH4")
info(iCH4)
info(info("water"))
options(width = 180)
info("acid")
options(width = 80)
info(" ribose")
info(iCH4)$formula
makeup(iCH4)
as.chemical.formula(makeup(iCH4))
ZC(iCH4)
ZC(info(iCH4)$formula)
ZC(makeup(iCH4))
subcrt("water")
subcrt("water", T = c(400, 500, 600), P = c(200, 400, 600), grid = "P")$out$water
substuff <- subcrt("water", T=seq(0,1000,100), P=c(NA, seq(1,500,1)), grid="T")
water <- substuff$out$water
plot(water$P, water$rho, type = "l")
T.units("K")
P.units("MPa")
E.units("J")
subcrt("CH4", T = 298.15, P = 0.1)$out$CH4$G
convert(info(info("CH4"))$G, "J")
reset()
subcrt(c("CO2", "CO2"), c("gas", "aq"), c(-1, 1), T = seq(0, 250, 50))
T <- seq(0, 350, 10)
CO2 <- subcrt(c("CO2", "CO2"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
CO <- subcrt(c("CO", "CO"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
CH4 <- subcrt(c("CH4", "CH4"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
logK <- data.frame(T, CO2, CO, CH4)
matplot(logK[, 1], logK[, -1], type = "l", col = 1, lty = 1,
xlab = axis.label("T"), ylab = axis.label("logK"))
text(80, -1.7, expr.species("CO2"))
text(240, -2.37, expr.species("CO"))
text(300, -2.57, expr.species("CH4"))
subcrt(c("CO2", "CH4"), c(-1, 1))
basis(c("CO2", "H2", "H2CO2"))
basis(c("CO2", "H2", "H2O"))
basis(c("CO2", "H2", "H2O", "H+"))
subcrt(c("acetate", "CH4"), c(-1, 1))$reaction
acetate_oxidation <- subcrt("acetate", -1)
hydrogenotrophic <- subcrt("CH4", 1)
acetoclastic <- subcrt(c("acetate", "CH4"), c(-1, 1))
plot(0, 0, type = "n", axes = FALSE, ann=FALSE, xlim=c(0, 5), ylim=c(5.2, -0.2))
text(0, 0, "acetoclastic methanogenesis", adj = 0)
text(5, 1, describe.reaction(acetoclastic$reaction), adj = 1)
text(0, 2, "acetate oxidation", adj = 0)
text(5, 3, describe.reaction(acetate_oxidation$reaction), adj = 1)
text(0, 4, "hydrogenotrophic methanogenesis", adj = 0)
text(5, 5, describe.reaction(hydrogenotrophic$reaction), adj = 1)
E.units("J")
basis(c("CO2", "H2", "H2O", "H+"))
basis(c("CO2", "H2"), "gas")
basis(c("H2", "pH"), c(-3.92, 7.3))
subcrt(c("acetate", "CH4"), c(-1, 1),
c("aq", "gas"), logact = c(-3.4, -0.18), T = 55, P = 50)$out
subcrt("CH4", 1, "gas", logact = -0.18, T = 55, P = 50)$out
rxnfun <- function(coeffs) {
subcrt(c("acetate", "CH4"), coeffs,
c("aq", "gas"), logact = c(-3.4, -0.18), T = 55, P = 50)$out
}
Adat <- lapply(c(-3, 3), function(logfCO2) {
basis("CO2", logfCO2)
data.frame(logfCO2,
rxnfun(c(0, 0))$A,
rxnfun(c(-1, 0))$A,
rxnfun(c(-1, 1))$A,
rxnfun(c(0, 1))$A
)
})
Adat <- do.call(rbind, Adat)
matplot(Adat[, 1], -Adat[, -1]/1000, type = "l", lty = 1, lwd = 2,
xlab = axis.label("CO2"), ylab = axis.label("DG", prefix = "k"))
legend("topleft", c("acetate oxidation", "acetoclastic methanogenesis",
"hydrogenotrophic methanogenesis"), lty = 1, col = 2:4)
reset()
basis("CHNOSe")
species(c("H2S", "HS-", "HSO4-", "SO4-2"))
unlist(affinity()$values)
a <- affinity(pH = c(0, 12), Eh = c(-0.5, 1))
diagram(a, limit.water = TRUE)
diagram(a, fill = "terrain", lwd = 2, lty = 3,
names = c("hydrogen sulfide", "bisulfide", "bisulfate", "sulfate"),
las = 0)
water.lines(a, col = 6, lwd = 2)
retrieve("Mn", c("O", "H"), "aq")
retrieve("Mn", c("O", "H"), "cr")
logact <- -4
T <- 100
res <- 400
basis(c("Mn+2", "H2O", "H+", "e-"))
iaq <- retrieve("Mn", c("O", "H"), "aq")
species(iaq, logact)
aaq <- affinity(pH = c(4, 16, res), Eh = c(-1.5, 1.5, res), T = T)
names <- names(iaq)
names[!names(iaq) %in% c("MnOH+", "MnO", "HMnO2-")] <- ""
diagram(aaq, lty = 2, col = "
icr <- retrieve("Mn", c("O", "H"), "cr")
species(icr, add = TRUE)
acr <- affinity(aaq)
diagram(acr, add = TRUE, bold = acr$species$state=="cr", limit.water = FALSE)
legend <- c(
bquote(log * italic(a)["Mn(aq)"] == .(logact)),
bquote(italic(T) == .(T) ~ degree*C)
)
legend("topright", legend = as.expression(legend), bty = "n")
info(" CuCl")
basis(c("Cu", "H2S", "Cl-", "H2O", "H+", "e-"))
basis("H2S", -6)
basis("Cl-", -0.7)
species(c("CuCl", "CuCl2-", "CuCl3-2", "CuCl+", "CuCl2", "CuCl3-", "CuCl4-2"))
species(c("chalcocite", "tenorite", "cuprite", "copper"), add = TRUE)
info(info("chalcocite", c("cr", "cr2", "cr3")))$T
T <- 200
res <- 200
bases <- c("H2S", "HS-", "HSO4-", "SO4-2")
m1 <- mosaic(bases, pH = c(0, 12, res), Eh=c(-1.2, 0.75, res), T=T)
diagram(m1$A.species, lwd = 2)
diagram(m1$A.bases, add = TRUE, col = 4, col.names = 4, lty = 3,
italic = TRUE)
water.lines(m1$A.species, col = "blue1")
file <- system.file("extdata/cpetc/SC10_Rainbow.csv", package = "CHNOSZ")
rb <- read.csv(file, check.names = FALSE)
basis(c("CO2", "H2", "NH4+", "H2O", "H2S", "H+"))
species("CH4", -3)
species(c("adenine", "cytosine", "aspartic acid", "deoxyribose",
"CH4", "leucine", "tryptophan", "n-nonanoic acid"), -6)
a <- affinity(T = rb$T, CO2 = rb$CO2, H2 = rb$H2,
`NH4+` = rb$`NH4+`, H2S = rb$H2S, pH = rb$pH)
T <- convert(a$vals[[1]], "K")
a$values <- lapply(a$values, convert, "G", T)
a$values <- lapply(a$values, `*`, -0.001)
diagram(a, balance = 1, ylim = c(-100, 100), ylab = axis.label("A", prefix="k"),
col = rainbow(8), lwd = 2, bg = "slategray3")
abline(h = 0, lty = 2, lwd = 2)
basis(c("FeS2", "H2S", "O2", "H2O"))
species(c("pyrite", "magnetite"))
species("pyrrhotite", "cr2")
unlist(affinity(T = 300, P = 100)$values)
mod.buffer("PPM", "pyrrhotite", "cr2")
basis(c("H2S", "O2"), c("PPM", "PPM"))
unlist(affinity(T = 300, P = 100, return.buffer = TRUE)[1:3])
demo(buffer, echo = FALSE)
par(mfrow = c(3, 1))
basis("CHNOS+")
species(c("CO2", "HCO3-", "CO3-2"))
a25 <- affinity(pH = c(4, 13))
a150 <- affinity(pH = c(4, 13), T = 150)
diagram(a25, dy = 0.4)
diagram(a150, add = TRUE, names = FALSE, col = "red")
e25 <- equilibrate(a25, loga.balance = -3)
e150 <- equilibrate(a150, loga.balance = -3)
diagram(e25, ylim = c(-6, 0), dy = 0.15)
diagram(e150, add = TRUE, names = FALSE, col = "red")
diagram(e25, alpha = TRUE, dy = -0.25)
diagram(e150, alpha = TRUE, add = TRUE, names = FALSE, col = "red")
add.OBIGT("SLOP98")
basis(c("Al+3", "H2O", "H+", "O2"))
species("corundum")
iaq <- c("Al+3", "AlO2-", "AlOH+2", "AlO+", "HAlO2")
s <- solubility(iaq, pH = c(0, 10), IS = 0, in.terms.of = "Al+3")
diagram(s, type = "loga.balance", ylim = c(-10, 0), lwd = 4, col = "green3")
diagram(s, add = TRUE, adj = c(0, 1, 2.1, -0.2, -1.5), dy = c(0, 0, 4, -0.3, 0.1))
legend("topright", c("25 °C", "1 bar"), text.font = 2, bty = "n")
reset()
oldnon <- nonideal("Alberty")
subcrt(c("MgATP-2", "MgHATP-", "MgH2ATP"),
T = c(25, 100), IS = c(0, 0.25), property = "G")$out
info(" ATP")
T <- 100
par(mfrow = c(1, 4), mar = c(3.1, 3.6, 2.1, 1.6), mgp = c(1.8, 0.5, 0))
basis("MgCHNOPS+")
species(c("ATP-4", "HATP-3", "H2ATP-2", "H3ATP-", "H4ATP"))
a <- affinity(pH = c(3, 9), T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, tplot = FALSE)
title(main = describe.property("T", T))
alphas <- do.call(rbind, d$plotvals)
nH <- alphas * 0:4
Hlab <- substitute(italic(N)[H^`+`])
plot(a$vals[[1]], colSums(nH), type = "l", xlab = "pH", ylab=Hlab, lty=2, col=2)
a <- affinity(pH = c(3, 9), IS = 0.25, T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, plot.it = FALSE)
alphas <- do.call(rbind, d$plotvals)
nH <- alphas * 0:4
lines(a$vals[[1]], colSums(nH))
legend("topright", legend = c("I = 0 M", "I = 0.25 M"), lty = 2:1, col = 2:1, cex = 0.8)
ATP.H <- substitute("ATP and H"^`+`)
title(main = ATP.H)
species(c("MgATP-2", "MgHATP-", "MgH2ATP", "Mg2ATP"), add = TRUE)
Hplot <- function(pMg, IS = 0.25) {
basis("Mg+2", -pMg)
a <- affinity(pH = c(3, 9), IS = IS, T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, plot.it = FALSE)
alphas <- do.call(rbind, d$plotvals)
NH <- alphas * c(0:4, 0, 1, 2, 0)
lines(a$vals[[1]], colSums(NH), lty = 7 - pMg, col = 7 - pMg)
}
plot(c(3, 9), c(0, 2), type = "n", xlab = "pH", ylab = Hlab)
lapply(2:6, Hplot)
legend("topright", legend = paste("pMg = ", 2:6), lty = 5:1, col = 5:1, cex = 0.8)
ATP.H.Mg <- substitute("ATP and H"^`+`~"and Mg"^`+2`)
title(main = ATP.H.Mg)
Mgplot <- function(pH, IS = 0.25) {
basis("pH", pH)
a <- affinity(`Mg+2` = c(-2, -7), IS = IS, T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, plot.it = FALSE)
alphas <- do.call(rbind, d$plotvals)
NMg <- alphas * species()$`Mg+`
lines(-a$vals[[1]], colSums(NMg), lty = 10 - pH, col = 10 - pH)
}
Mglab <- substitute(italic(N)[Mg^`+2`])
plot(c(2, 7), c(0, 1.2), type = "n", xlab = "pMg", ylab = Mglab)
lapply(3:9, Mgplot)
legend("topright", legend = paste("pH = ", 3:9), lty = 7:1, col = 7:1, cex = 0.8)
title(main = ATP.H.Mg)
nonideal(oldnon)
p1 <- pinfo("LYSC_CHICK")
p2 <- pinfo(c("SHH", "OLIG2"), "HUMAN")
pinfo(c(p1, p2))
pl <- protein.length("LYSC_CHICK")
pf <- protein.formula("LYSC_CHICK")
list(length = pl, protein = pf, residue = pf / pl,
ZC_protein = ZC(pf), ZC_residue = ZC(pf / pl))
subcrt("LYSC_CHICK")$out[[1]][1:6, ]
PM90 <- read.csv(system.file("extdata/cpetc/PM90.csv", package = "CHNOSZ"))
plength <- protein.length(colnames(PM90)[2:5])
Cp_expt <- t(t(PM90[, 2:5]) / plength)
matplot(PM90[, 1], convert(Cp_expt, "cal"), type = "p", pch = 19,
xlab = axis.label("T"), ylab = axis.label("Cp0"), ylim = c(28, 65))
for(i in 1:4) {
pname <- colnames(Cp_expt)[i]
aq <- subcrt(pname, "aq", T = seq(0, 150))$out[[1]]
cr <- subcrt(pname, "cr", T = seq(0, 150))$out[[1]]
lines(aq$T, aq$Cp / plength[i], col = i)
lines(cr$T, cr$Cp / plength[i], col = i, lty = 2)
}
legend("right", legend = colnames(Cp_expt),
col = 1:4, pch = 19, lty = 1, bty = "n", cex = 0.9)
legend("bottomright", legend = c("experimental", "calculated (aq)",
"calculated (cr)"), lty = c(NA, 1, 2), pch = c(19, NA, NA), bty = "n")
ip <- pinfo(c("CYC_BOVIN", "LYSC_CHICK", "MYG_PHYCA", "RNAS1_BOVIN"))
basis("CHNOS+")
a_ion <- affinity(pH = c(0, 14), iprotein = ip)
basis("CHNOS")
a_nonion <- affinity(iprotein = ip)
plot(c(0, 14), c(50, 300), xlab = "pH", ylab = axis.label("A"), type = "n")
for(i in 1:4) {
A_ion <- as.numeric(a_ion$values[[i]])
A_nonion <- as.numeric(a_nonion$values[[i]])
lines(a_ion$vals[[1]], A_ion - A_nonion, col=i)
}
legend("topright", legend = a_ion$species$name,
col = 1:4, lty = 1, bty = "n", cex = 0.9)
basis("CHNOS")
species(c("CYC_BOVIN", "LYSC_CHICK", "MYG_PHYCA", "RNAS1_BOVIN"))
a_nonion_species <- affinity()
unlist(a_nonion_species$values)
unlist(a_nonion$values)
file.copy("rubisco.svg", fig_path(".svg"))
datfile <- system.file("extdata/cpetc/rubisco.csv", package = "CHNOSZ")
fastafile <- system.file("extdata/protein/rubisco.fasta", package = "CHNOSZ")
dat <- read.csv(datfile)
aa <- read.fasta(fastafile)
Topt <- (dat$T1 + dat$T2) / 2
idat <- match(dat$ID, substr(aa$protein, 4, 9))
aa <- aa[idat, ]
ZC <- ZC(protein.formula(aa))
pch <- match(dat$domain, c("E", "B", "A")) - 1
col <- match(dat$domain, c("A", "B", "E")) + 1
plot(Topt, ZC, pch = pch, cex = 2, col = col,
xlab = expression(list(italic(T)[opt], degree*C)),
ylab = expression(italic(Z)[C]))
text(Topt, ZC, rep(1:9, 3), cex = 0.8)
abline(v = c(36, 63), lty = 2, col = "grey")
legend("topright", legend = c("Archaea", "Bacteria", "Eukaryota"),
pch = c(2, 1, 0), col = 2:4, pt.cex = 2)
layout(matrix(1:4, nrow = 2))
par(mgp = c(1.8, 0.5, 0))
pl <- protein.length(aa)
ZClab <- axis.label("ZC")
nO2lab <- expression(bar(italic(n))[O[2]])
nH2Olab <- expression(bar(italic(n))[H[2]*O])
lapply(c("CHNOS", "QEC"), function(thisbasis) {
basis(thisbasis)
pb <- protein.basis(aa)
nO2 <- pb[, "O2"] / pl
plot(ZC, nO2, pch = pch, col = col, xlab = ZClab, ylab = nO2lab)
nH2O <- pb[, "H2O"] / pl
plot(ZC, nH2O, pch = pch, col = col, xlab = ZClab, ylab = nH2Olab)
mtext(thisbasis, font = 2)
})
protein <- c("YDL195W", "YHR098C", "YIL109C", "YLR208W", "YNL049C", "YPL085W")
abundance <- c(1840, 12200, NA, 21400, 1720, 358)
ina <- is.na(abundance)
ip <- match(protein[!ina], thermo()$protein$protein)
pl <- protein.length(ip)
logact <- unitize(numeric(5), pl)
logabundance <- unitize(log10(abundance[!ina]), pl)
par(mfrow = c(1, 3))
basis("CHNOS+")
a <- affinity(O2 = c(-80, -73), iprotein = ip, loga.protein = logact)
e <- equilibrate(a)
diagram(e, ylim = c(-5, -2), col = 1:5, lwd = 2)
e <- equilibrate(a, normalize = TRUE)
diagram(e, ylim = c(-5, -2.5), col = 1:5, lwd = 2)
abline(h = logabundance, lty = 1:5, col = 1:5)
revisit(e, "DGinf", logabundance)
file <- system.file("extdata/protein/POLG.csv", package = "CHNOSZ")
aa_POLG <- read.csv(file, as.is = TRUE, nrows = 5)
file <- system.file("extdata/protein/EF-Tu.aln", package = "CHNOSZ")
aa_Ef <- read.fasta(file, iseq = 1:2)
aa_PRIO <- seq2aa("PRIO_HUMAN", "
MANLGCWMLVLFVATWSDLGLCKKRPKPGGWNTGGSRYPGQGSPGGNRYPPQGGGGWGQP
HGGGWGQPHGGGWGQPHGGGWGQPHGGGWGQGGGTHSQWNKPSKPKTNMKHMAGAAAAGA
VVGGLGGYMLGSAMSRPIIHFGSDYEDRYYRENMHRYPNQVYYRPMDEYSNQNNFVHDCV
NITIKQHTVTTTTKGENFTETDVKMMERVVEQMCITQYERESQAYYQRGSSMVLFSSPPV
ILLISFLIFLIVG
")
aa_ALAT1 <- seq2aa("ALAT1_HUMAN", "
MASSTGDRSQAVRHGLRAKVLTLDGMNPRVRRVEYAVRGPIVQRALELEQELRQGVKKPF
TEVIRANIGDAQAMGQRPITFLRQVLALCVNPDLLSSPNFPDDAKKRAERILQACGGHSL
GAYSVSSGIQLIREDVARYIERRDGGIPADPNNVFLSTGASDAIVTVLKLLVAGEGHTRT
GVLIPIPQYPLYSATLAELGAVQVDYYLDEERAWALDVAELHRALGQARDHCRPRALCVI
NPGNPTGQVQTRECIEAVIRFAFEERLFLLADEVYQDNVYAAGSQFHSFKKVLMEMGPPY
AGQQELASFHSTSKGYMGECGFRGGYVEVVNMDAAVQQQMLKLMSVRLCPPVPGQALLDL
VVSPPAPTDPSFAQFQAEKQAVLAELAAKAKLTEQVFNEAPGISCNPVQGAMYSFPRVQL
PPRAVERAQELGLAPDMFFCLRLLEETGICVVPGSGFGQREGTYHFRMTILPPLEKLRLL
LEKLSRFHAKFTLEYS
")
aa_CO1A1 <- seq2aa("CO1A1_HUMAN", "
MFSFVDLRLLLLLAATALLTHGQEEGQVEGQDEDIPPITCVQNGLRYHDRDVWKPEPCRI
CVCDNGKVLCDDVICDETKNCPGAEVPEGECCPVCPDGSESPTDQETTGVEGPKGDTGPR
GPRGPAGPPGRDGIPGQPGLPGPPGPPGPPGPPGLGGNFAPQLSYGYDEKSTGGISVPGP
MGPSGPRGLPGPPGAPGPQGFQGPPGEPGEPGASGPMGPRGPPGPPGKNGDDGEAGKPGR
PGERGPPGPQGARGLPGTAGLPGMKGHRGFSGLDGAKGDAGPAGPKGEPGSPGENGAPGQ
MGPRGLPGERGRPGAPGPAGARGNDGATGAAGPPGPTGPAGPPGFPGAVGAKGEAGPQGP
RGSEGPQGVRGEPGPPGPAGAAGPAGNPGADGQPGAKGANGAPGIAGAPGFPGARGPSGP
QGPGGPPGPKGNSGEPGAPGSKGDTGAKGEPGPVGVQGPPGPAGEEGKRGARGEPGPTGL
PGPPGERGGPGSRGFPGADGVAGPKGPAGERGSPGPAGPKGSPGEAGRPGEAGLPGAKGL
TGSPGSPGPDGKTGPPGPAGQDGRPGPPGPPGARGQAGVMGFPGPKGAAGEPGKAGERGV
PGPPGAVGPAGKDGEAGAQGPPGPAGPAGERGEQGPAGSPGFQGLPGPAGPPGEAGKPGE
QGVPGDLGAPGPSGARGERGFPGERGVQGPPGPAGPRGANGAPGNDGAKGDAGAPGAPGS
QGAPGLQGMPGERGAAGLPGPKGDRGDAGPKGADGSPGKDGVRGLTGPIGPPGPAGAPGD
KGESGPSGPAGPTGARGAPGDRGEPGPPGPAGFAGPPGADGQPGAKGEPGDAGAKGDAGP
PGPAGPAGPPGPIGNVGAPGAKGARGSAGPPGATGFPGAAGRVGPPGPSGNAGPPGPPGP
AGKEGGKGPRGETGPAGRPGEVGPPGPPGPAGEKGSPGADGPAGAPGTPGPQGIAGQRGV
VGLPGQRGERGFPGLPGPSGEPGKQGPSGASGERGPPGPMGPPGLAGPPGESGREGAPGA
EGSPGRDGSPGAKGDRGETGPAGPPGAPGAPGAPGPVGPAGKSGDRGETGPAGPTGPVGP
VGARGPAGPQGPRGDKGETGEQGDRGIKGHRGFSGLQGPPGPPGSPGEQGPSGASGPAGP
RGPPGSAGAPGKDGLNGLPGPIGPPGPRGRTGDAGPVGPPGPPGPPGPPGPPSAGFDFSF
LPQPPQEKAHDGGRYYRADDANVVRDRDLEVDTTLKSLSQQIENIRSPEGSRKNPARTCR
DLKMCHSDWKSGEYWIDPNQGCNLDAIKVFCNMETGETCVYPTQPSVAQKNWYISKNPKD
KRHVWFGESMTDGFQFEYGGQGSDPADVAIQLTFLRLMSTEASQNITYHCKNSVAYMDQQ
TGNLKKALLLQGSNEIEIRAEGNSRFTYSVTVDGCTSHTGAWGKTVIEYKTTKTSRLPII
DVAPLDVGAPDQEFGFDVGPVCFL
")
aa_UniProt <- rbind(aa_ALAT1, aa_CO1A1)
aa_UniProt$abbrv <- c("ALAT1", "CO1A1")
aa_UniProt
myaa <- rbind(aa_Ef, aa_PRIO, aa_ALAT1)
protein.length(myaa)
options(width = 180)
iATP <- info("ATP-4")
iMgATP <- info("MgATP-2")
thermo.refs(c(iATP, iMgATP))
thermo.refs(c("HDNB78", "MGN03"))
substuff <- subcrt(c("C2H5OH", "O2", "CO2", "H2O"), c(-1, -3, 2, 3))
thermo.refs(substuff)
options(width = 80)
file <- system.file("extdata/adds/BZA10.csv", package = "CHNOSZ")
read.csv(file, as.is = TRUE)
iCd <- add.OBIGT(file)
subcrt(c("CdCl+", "Cl-", "CdCl2"), c(-1, -1, 1), T = 25, P = c(1, 2000))
reset()
thermo.refs(iCd)[, 1:3]
subcrt(c("CdCl+", "Cl-", "CdCl2"), c(-1, -1, 1), T = 25, P = c(1, 2000))
mod.OBIGT("CoCl4-2", formula = "CoCl4-2", state = "aq", ref1 = "LBT+11",
date = as.character(Sys.Date()), G = -134150, H = -171558, S = 19.55, Cp = 72.09, V = 27.74)
mod.OBIGT("CoCl4-2", a1 = 6.5467, a2 = 8.2069, a3 = 2.0130, a4 = -3.1183,
c1 = 76.3357, c2 = 11.6389, omega = 2.9159, z = -2)
T <- c(25, seq(50, 350, 50))
sres <- subcrt(c("Co+2", "Cl-", "CoCl4-2"), c(-1, -4, 1), T = T)
round(sres$out$logK, 2)
stopifnot(identical(round(sres$out$logK, 2), c(-3.2, -2.96, -2.02, -0.74, 0.77, 2.5, 4.57, 7.29)))
H <- -1762000
S <- 119.6
V <- 43.56
mod.OBIGT("magnesiochromite", formula = "MgCr2O4", state = "cr", ref1 = "KOSG00",
date = as.character(Sys.Date()), E_units = "J", H = H, S = S, V = V)
a <- 221.4
b <- -0.00102030 * 1e3
c <- -1757210 * 1e-5
d <- -1247.9
mod.OBIGT("magnesiochromite", E_units = "J", a = a, b = b, c = c, d = d,
e = 0, f = 0, lambda = 0, T = 1500)
T.units("K")
E.units("J")
subcrt("magnesiochromite", property = "Cp", T = c(250, 300, 340), P = 1)
T.units("C")
E.units("cal")
inew <- info("CoCl4-2")
info(inew)
info(info("S3-"))
file <- system.file("extdata/adds/OBIGT_check.csv", package = "CHNOSZ")
dat <- read.csv(file, as.is = TRUE)
nrow(dat)
cref <- citation("CHNOSZ")
print(cref, style = "html")
maintainer("CHNOSZ")
sessionInfo()
|
APML <- function(model='gbm',AUC_stopping=F,xcol,traindata,testdata,hyper,distribution='bernoulli',imbalance=F,sort_by='auc',
extra_data=NULL,stopping_metric='AUTO'
){
search_criteria=NULL
if(AUC_stopping==T) search_criteria = list(strategy = 'RandomDiscrete',stopping_metric = "AUC",stopping_rounds = 3)
traindata=as.h2o(traindata)
testdata=as.h2o(testdata)
if(!is.null(extra_data))extra_data=as.h2o(extra_data)
if(model=="gbm"){
grid1=NULL
grid1=h2o.grid("gbm", distribution=distribution,x=xcol, y=1, training_frame=traindata,nfolds=5,seed=666,
sample_rate=0.7,col_sample_rate=0.7,fold_assignment = "AUTO",balance_classes=isTRUE(imbalance),
hyper_params=hyper,search_criteria = search_criteria,stopping_metric=stopping_metric
)
}
if(model=="rf"){
grid1=NULL
grid1=h2o.grid("randomForest",x=xcol, y=1, training_frame=traindata,nfolds=5,seed=666,balance_classes=isTRUE(imbalance),
sample_rate=0.7,col_sample_rate_per_tree=0.7,fold_assignment = "AUTO",distribution=distribution,
hyper_params=hyper,search_criteria = search_criteria,stopping_metric=stopping_metric)
}
if(sort_by=='auc'){
gridperf1=NULL
gridperf1 <- h2o.getGrid(grid_id = grid1@grid_id,
sort_by = sort_by,
decreasing = TRUE)
best_gd <- h2o.getModel(gridperf1@model_ids[[1]])
best_perf1=h2o.performance(model = best_gd,newdata = testdata)
out=data.frame(
train_AUC=best_gd@model$training_metrics@metrics$AUC,
train_prAUC=best_gd@model$training_metrics@metrics$pr_auc,
cv_AUC=best_gd@model$cross_validation_metrics@metrics$AUC,
cv_prAUC=best_gd@model$cross_validation_metrics@metrics$pr_auc,
test_AUC=best_perf1@metrics$AUC,
test_prAUC=best_perf1@metrics$pr_auc
)
OUT=data.frame(gridperf1@summary_table)
para=list(metrics=out,grid_summary=OUT)
train_metrics <- h2o.metric(h2o.performance(model = best_gd,newdata = traindata))
test_metrics <- h2o.metric(h2o.performance(model = best_gd,newdata = testdata))
train0_metrics=NULL
if(!is.null(extra_data)) train0_metrics <- h2o.metric(h2o.performance(model = best_gd,newdata = extra_data))
result <- list(bestmodel=best_gd,train_metrics=train_metrics,test_metrics=test_metrics,summary=para,extra_metrics=train0_metrics)
}else{
gridperf1=NULL
if(sort_by=='r2'){
gridperf1 <- h2o.getGrid(grid_id = grid1@grid_id,
sort_by = sort_by,
decreasing = TRUE)
}else{
gridperf1 <- h2o.getGrid(grid_id = grid1@grid_id,
sort_by = sort_by,
decreasing = FALSE)
}
best_gd <- h2o.getModel(gridperf1@model_ids[[1]])
best_perf1=h2o.performance(model = best_gd,newdata = testdata)
out=data.frame(
train_MSE=best_gd@model$training_metrics@metrics$MSE,
train_RMSE=best_gd@model$training_metrics@metrics$RMSE,
train_R2=best_gd@model$training_metrics@metrics$r2,
cv_MSE=best_gd@model$cross_validation_metrics@metrics$MSE,
cv_RMSE=best_gd@model$cross_validation_metrics@metrics$RMSE,
cv_R2=best_gd@model$cross_validation_metrics@metrics$r2,
test_MSE=best_perf1@metrics$MSE,
test_RMSE=best_perf1@metrics$RMSE,
test_R2=best_perf1@metrics$r2
)
OUT=data.frame(gridperf1@summary_table)
para=list(metrics=out,grid_summary=OUT)
train_metrics <- h2o.performance(model = best_gd,newdata = traindata)
test_metrics <- h2o.performance(model = best_gd,newdata = testdata)
train0_metrics=NULL
if(!is.null(extra_data)) train0_metrics <- h2o.metric(h2o.performance(model = best_gd,newdata = extra_data))
result <- list(bestmodel=best_gd,train_metrics=train_metrics,test_metrics=test_metrics,summary=para,extra_metrics=train0_metrics)
}
return(result)
}
|
epcreg.baselearner.control <- function(baselearners=c("nnet","rf","svm","gbm","knn")
, baselearner.configs=make.configs(baselearners, type="regression"), npart=1, nfold=5) {
return (list(configs=baselearner.configs, npart=npart, nfold=nfold))
}
epcreg.integrator.control <- function(errfun=rmse.error, nfold=5, method=c("default")) {
return (list(errfun=rmse.error, nfold=nfold, method=method))
}
epcreg.set.filemethod <- function(formula, data, instance.list, type="regression") FALSE
epcreg <- function(formula, data
, baselearner.control=epcreg.baselearner.control()
, integrator.control=epcreg.integrator.control()
, ncores=1, filemethod=FALSE, print.level=1
, preschedule = TRUE
, schedule.method = c("random", "as.is", "task.length"), task.length) {
if (integrator.control$method!="default") stop("invalid PCR integration method")
ncores.max <- try(detectCores(),silent=T)
mycall <- match.call()
if (!inherits(ncores.max,"try-error")) ncores <- min(ncores,ncores.max)
if (print.level>=1 && ncores>1) cat("running in parallel mode, using", ncores, "cores\n")
partitions.bl <- generate.partitions(baselearner.control$npart, nrow(data), baselearner.control$nfold)
my.instance.list <- make.instances(baselearner.control$configs, partitions.bl)
if (missing(filemethod)) filemethod <- epcreg.set.filemethod(formula, data, my.instance.list)
if (print.level>=1) cat("CV training of base learners...\n")
est.baselearner.cv.batch <- Regression.CV.Batch.Fit(my.instance.list, formula, data, ncores=ncores, filemethod=filemethod, print.level=print.level, preschedule = preschedule, schedule.method = schedule.method, task.length = task.length)
if (print.level>=1) cat("finished CV training of base learners\n")
Xcv <- est.baselearner.cv.batch@pred
y <- data[,all.vars(formula)[1]]
partition.int <- generate.partition(nrow(data), integrator.control$nfold)
my.integrator.config <- Regression.Integrator.PCR.SelMin.Config(errfun=integrator.control$errfun, partition=partition.int)
est.integrator <- Regression.Integrator.Fit(my.integrator.config, X=Xcv, y=y, print.level=print.level)
pred <- est.integrator@pred
ret <- list(call=mycall, formula=formula, instance.list=my.instance.list, integrator.config=my.integrator.config, method=integrator.control$method
, est=list(baselearner.cv.batch=est.baselearner.cv.batch, integrator=est.integrator)
, y=y, pred=pred, filemethod=filemethod)
class(ret) <- "epcreg"
if (filemethod) class(ret) <- c(class(ret), "epcreg.file")
return (ret)
}
predict.epcreg <- function(object, newdata=NULL, ncores=1, preschedule = TRUE, ...) {
if (is.null(newdata)) return (object$pred)
if (object$method=="default") {
newpred.baselearner.cv.batch <- predict(object$est$baselearner.cv.batch, newdata, ncores=ncores, preschedule = preschedule, ...)
newpred <- predict(object$est$integrator, Xnew=newpred.baselearner.cv.batch, [email protected], ...)
} else {
stop("invalid PCR integration method")
}
return (as.numeric(newpred))
}
plot.epcreg <- function(x, ...) {
errfun <- x$integrator.config@errfun
error <- errfun(x$pred, x$y)
oldpar <- par(mfrow=c(1,2))
plot(x$est$baselearner.cv.batch, errfun=errfun, ylim.adj = error)
abline(h=error, lty=2)
pcr.errors <- x$est$integrator@est$select@est$error
plot(pcr.errors, type="l", xlab="Number of Principal Components", ylab="CV Error", main="Integrator Performance")
par(oldpar)
}
epcreg.save <- function (obj, file) {
if (!("epcreg" %in% class(obj)))
stop("invalid object class (must be epcreg & epcreg.file)")
if (missing(file))
stop("must provide file argument")
tmpfiles <- obj$est$baselearner.cv.batch@tmpfiles
if (is.null(tmpfiles)) {
save(obj, file = file)
} else {
tmpfile.new <- tempfile()
save(obj, file = tmpfile.new, compress = F)
all.files <- c(tmpfile.new, tmpfiles)
all.files.basename <- basename(all.files)
tmpdir <- paste0("./.", basename(tempfile("dir")), "/")
dir.create(tmpdir)
all.files.new <- paste0(tmpdir, all.files.basename)
file.copy(all.files, all.files.new)
meta <- list(filename.mainobj = all.files.basename[1], filenames.batchobj = all.files.basename[1 + 1:length(tmpfiles)])
save(meta, file = paste0(tmpdir, "meta"), compress = FALSE)
tar(file, files = tmpdir, compression = "gzip")
unlink(tmpdir, recursive = TRUE)
}
}
epcreg.load <- function (file) {
env <- new.env()
loadret <- suppressWarnings(try(load(file, envir = env), silent = TRUE))
if (class(loadret) == "try-error") {
filepaths <- untar(file, list = T)
basenames <- basename(filepaths)
dirnames <- dirname(filepaths)
if (length(unique(dirnames)) > 1)
stop("unexpected multiple directories in tar filepaths")
metafile.index <- which(basenames == "meta")
extdir <- dirnames[1]
untar(file)
meta <- NULL
load(filepaths[metafile.index])
mainfile.index <- which(basenames == meta$filename.mainobj)
load(filepaths[mainfile.index])
if (!identical(class(obj), c("epcreg", "epcreg.file")))
stop("invalid object class (must be epcreg & epcreg.file)")
basenames.ordered <- basename(obj$est$baselearner.cv.batch@tmpfiles)
filepaths.ordered <- paste(extdir, basenames.ordered, sep = "/")
tmpfiles.new <- tempfile(rep("file", length(filepaths.ordered)))
file.copy(from = filepaths.ordered, to = tmpfiles.new)
unlink(filepaths.ordered, recursive = TRUE)
unlink(extdir, recursive = TRUE)
obj$est$baselearner.cv.batch@tmpfiles <- tmpfiles.new
n.instance <- length([email protected]@instances)
for (i in 1:n.instance) {
partid <- [email protected]@instances[[1]]@partid
nfold <- length(unique([email protected]@partitions[, partid]))
for (j in 1:nfold) {
[email protected][[i]]@fitobj.list[[j]]@est <- tmpfiles.new[[email protected]$start[i] + j - 1]
}
}
return(obj)
} else {
loadedObjects <- objects(env, all.names = TRUE)
stopifnot(length(loadedObjects) == 1)
return (env[[loadedObjects]])
}
}
print.epcreg <- function(x, ...) {
cat("Call:\n")
print(x$call)
}
summary.epcreg <- function(object, ...) {
n.instance <- length(object$instance.list@instances)
maxpc <- object$est$integrator@[email protected][[1]]@config@n
index.min <- object$est$integrator@est$select@est$index.min
error.min <- object$est$integrator@est$select@est$error.min
tvec <- object$est$baselearner.cv.batch@tvec
ret <- list(n.instance=n.instance, maxpc=maxpc, index.min=index.min, error.min=error.min, tvec = tvec)
class(ret) <- "summary.epcreg"
return (ret)
}
print.summary.epcreg <- function(x, ...) {
cat("number of base learner instances:", x$n.instance, "\n")
cat("maximum number of PC's considered:", x$maxpc, "\n")
cat("optimal number of PC's:", x$index.min, "\n")
cat("minimum error:", x$error.min, "\n")
}
|
lsem_fitsem_raw_data_lavaan <- function(dat, pseudo_weights, survey.fit,
lavaan_est_fun, se, ...)
{
res <- lsem_fitsem_raw_data_define_pseudo_weights(dat=dat, pseudo_weights=pseudo_weights)
dat1 <- res$dat
sampling_weights <- res$sampling_weights
nobs_pseudo <- res$nobs_pseudo
sum_weight <- res$sum_weight
partable <- sirt_import_lavaan_parameterTable(object=survey.fit)
partable$start <- partable$est
survey.fit <- lavaan_est_fun(model=partable, data=dat1,
sampling.weights=sampling_weights, se=se, ... )
survey.fit <- lavaan_object_adjust_sample_size(object=survey.fit, n_used=sum_weight)
return(survey.fit)
}
|
rm(list=ls(all=TRUE))
cols=c("city","sex","doseg","agexg","calg","kerma","PY","adjPY","num.entering",
"age","agex","tsx","cal","sv","gam","neut","lymphoma","NHL","leukemia","AML","ALL","CML","ATL","MM")
d<-read.table("c:/data/abomb/HEMA87.dat", header=F,col.names=cols);
d=d[d$adjPY>0,]
d=d[d$kerma==1,]
d=d[d$city==1,]
d$py=10^4*d$adjPY
d$calg=as.integer(cut(d$calg,c(0,2,4,6,8,10)))
m=d[d$sex==1,]; f=d[d$sex==2,]
agem=55
agem=0
require(bbmle)
nLL<-function(c0,k,beta,L1,L2,L3,L4,L5,x,agem) with(x, {L=c(L1,L2,L3,L4,L5)
mn = (exp(c0+k*(age-agem)) + exp(-beta*abs(agex-30)/28.85)*sv*exp(L[calg]))*py
-sum(stats::dpois(CML, mn, log=TRUE))})
fit0 <- mle2(nLL,start=list(c0=-10,k=.04,L1=-10,L2=-10,L3=-10,L4=-10,L5=-10,beta=0.5),data=list(x=m,agem=agem))
fit0Fx <- mle2(nLL,start=list(c0=-10,k=.04,L1=-10,L2=-10,L3=-10,L4=-10,L5=-10),fixed = list(beta=0),data=list(x=m,agem=agem))
deviance(fit0Fx)-deviance(fit0)
fit0 <- mle2(nLL,start=list(c0=-10,k=.04,L1=-10,L2=-10,L3=-10,L4=-10,L5=-10,beta=0.5),data=list(x=f,agem=agem))
fit0Fx <- mle2(nLL,start=list(c0=-10,k=.04,L1=-10,L2=-10,L3=-10,L4=-10,L5=-10),fixed = list(beta=0),data=list(x=f,agem=agem))
deviance(fit0Fx)-deviance(fit0)
|
power.scABEL2 <- function(alpha=0.05, theta1, theta2, theta0, CV, n,
design=c("2x3x3", "2x2x4", "2x2x3"), regulator,
nsims, details=FALSE, setseed=TRUE)
{
if (missing(CV)) stop("CV must be given!")
if (missing(n)) stop("Number of subjects n must be given!")
if (missing(theta0)) theta0 <- 0.90
if (length(theta0)>1) {
theta0 <- theta0[2]
warning(paste0("theta0 has to be scalar. theta0 = ",
theta0, " used."), call. = FALSE)
}
if (missing(theta1) & missing(theta2)) theta1 <- 0.8
if (missing(theta2)) theta2 <- 1/theta1
if (missing(theta1)) theta1 <- 1/theta2
ptm <- proc.time()
CVwT <- CV[1]
if (length(CV)==2) CVwR <- CV[2] else CVwR <- CVwT
if (missing(nsims)) {
if (theta0 == scABEL(CVwR)[["lower"]] | theta0 == scABEL(CVwR)[["upper"]]) {
nsims <- 1e6
} else {
nsims <- 1e5
}
}
s2wT <- log(1.0 + CVwT^2)
s2wR <- log(1.0 + CVwR^2)
if(missing(regulator)) regulator <- "EMA"
reg <- reg_check(regulator)
CVcap <- reg$CVcap
CVswitch <- reg$CVswitch
r_const <- reg$r_const
pe_constr <- reg$pe_constr
if(is.null(pe_constr)) pe_constr <- TRUE
design <- match.arg(design)
if (design=="2x3x3") {
seqs <- 3
dfe <- parse(text="n-3", srcfile=NULL)
dfRRe <- parse(text="n-3", srcfile=NULL)
Emse <- s2wT + s2wR/2
}
if (design=="2x2x4") {
seqs <- 2
dfe <- parse(text="n-2", srcfile=NULL)
dfRRe <- parse(text="n-2", srcfile=NULL)
Emse <- (s2wT + s2wR)/2
}
if (design=="2x2x3") {
seqs <- 2
dfe <- parse(text="n-2", srcfile=NULL)
dfRRe <- parse(text="n/2-1", srcfile=NULL)
Emse <- 1.5*(s2wT + s2wR)/2
}
if (length(n)==1){
nv <- nvec(n=n, grps=seqs)
if (nv[1]!=nv[length(nv)]){
message("Unbalanced design. n(i)=", paste(nv, collapse="/"), " assumed.")
}
} else {
if (length(n)!=seqs) stop("n must be a vector of length=",seqs,"!")
nv <- n
}
C3 <- sum(1/nv)/seqs^2
n <- sum(nv)
df <- eval(dfe)
if (design=="2x2x3"){
dfTT <- nv[1]-1
dfRR <- nv[2]-1
Emse <- (dfRR*(s2wT + s2wR/2)+dfTT*(s2wT/2 + s2wR))/(dfRR+dfTT)
} else {
dfRR <- eval(dfRRe)
}
sdm <- sqrt(Emse*C3)
mlog <- log(theta0)
if(setseed) set.seed(123456)
p <- .pwr.ABEL.ISC(mlog, sdm, C3, Emse, df, s2wR, dfRR, nsims,
CVswitch=CVswitch, r_const=r_const, CVcap=CVcap,
pe_constr=pe_constr, ln_lBEL=log(theta1),ln_uBEL=log(theta2),
alpha=alpha)
if (details) {
ptm <- summary(proc.time()-ptm)
message(nsims," sims. Time elapsed (sec): ",
formatC(ptm["elapsed"], digits=2), "\n")
names(p) <- c("p(BE)", "p(BE-ABEL)", "p(BE-pe)", "p(BE-ABE)")
if (!pe_constr) p <- p[-3]
p
} else {
as.numeric(p["BE"])
}
}
|
NULL
opsworkscm <- function(config = list()) {
svc <- .opsworkscm$operations
svc <- set_config(svc, config)
return(svc)
}
.opsworkscm <- list()
.opsworkscm$operations <- list()
.opsworkscm$metadata <- list(
service_name = "opsworks-cm",
endpoints = list("*" = list(endpoint = "opsworks-cm.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "opsworks-cm.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "opsworks-cm.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "opsworks-cm.{region}.sc2s.sgov.gov", global = FALSE)),
service_id = "OpsWorksCM",
api_version = "2016-11-01",
signing_name = "opsworks-cm",
json_version = "1.1",
target_prefix = "OpsWorksCM_V2016_11_01"
)
.opsworkscm$service <- function(config = list()) {
handlers <- new_handlers("jsonrpc", "v4")
new_service(.opsworkscm$metadata, handlers, config)
}
|
phylostruct<-function(samp,tree,env=NULL,metric=c("psv","psr","pse","psc","sppregs"),null.model=c("frequency","richness","independentswap","trialswap"),runs=100,it=1000,alpha=0.05,fam="binomial"){
metric<-match.arg(metric)
null.model<-match.arg(null.model)
if(metric=="sppregs")
{
nulls<-t(replicate(runs,sppregs(randomizeMatrix(samp,null.model=null.model,iterations=it),env,tree,fam=fam)$correlations))
obs<-sppregs(samp,env,tree,fam=fam)$correlations
mean.null<-apply(nulls,2,mean)
quantiles.null<-t(apply(nulls,2,quantile,probs=c(alpha/2,1-(alpha/2))))
if((null.model!="independentswap")&&(null.model!="trialswap")){it=NA}
return(list(metric=metric,null.model=null.model,runs=runs,it=it,obs=obs,mean.null=mean.null
,quantiles.null=quantiles.null,phylo.structure=NULL,nulls=nulls))
} else {
nulls<-switch(metric,
psv = replicate(runs,mean(psv(as.matrix(randomizeMatrix(samp,null.model=null.model,iterations=it)),tree,compute.var=FALSE)[,1],na.rm=TRUE)),
psr = replicate(runs,mean(psr(as.matrix(randomizeMatrix(samp,null.model=null.model,iterations=it)),tree,compute.var=FALSE)[,1],na.rm=TRUE)),
pse = replicate(runs,mean(pse(as.matrix(randomizeMatrix(samp,null.model=null.model,iterations=it)),tree)[,1],na.rm=TRUE)),
psc = replicate(runs,mean(psc(as.matrix(randomizeMatrix(samp,null.model=null.model,iterations=it)),tree)[,1],na.rm=TRUE)))
quantiles.null<-quantile(nulls,probs=c(alpha/2,1-(alpha/2)))
mean.null<-mean(nulls)
mean.obs<-switch(metric,
psv = mean(psv(samp,tree,compute.var=FALSE)[,1],na.rm=TRUE),
psr = mean(psr(samp,tree,compute.var=FALSE)[,1],na.rm=TRUE),
pse = mean(pse(samp,tree)[,1],na.rm=TRUE),
psc = mean(psc(samp,tree)[,1],na.rm=TRUE))
if(mean.obs<=quantiles.null[1])
{phylo.structure="underdispersed"
} else {if(mean.obs>=quantiles.null[2]){
phylo.structure="overdispersed"} else {phylo.structure="random"}
}
if((null.model!="independentswap")&&(null.model!="trialswap")){it=NA}
return(list(metric=metric,null.model=null.model,runs=runs,it=it,mean.obs=mean.obs,mean.null=mean.null
,quantiles.null=quantiles.null,phylo.structure=phylo.structure,null.means=nulls))
}
}
|
runlinear=function(
x,
y,
nPredics,
fwerRate=0.25,
adjust_method="fdr",
zeroSDCut=0
){
results=list()
nBeta=ncol(x)
nObsAll=length(y)
print(paste("length of y: ",length(y)))
lm_res<-lm(as.vector(y)~as.matrix(x)-1)
full_name_coef<-names(lm_res$coefficients)
valid_coef<-summary(lm_res)$coefficients
bootResu<-matrix(nrow = length(full_name_coef),ncol = 4)
rownames(bootResu)<-full_name_coef
bootResu[rownames(bootResu)%in%rownames(valid_coef),]<-valid_coef
p_value_est<-bootResu[,4]
p_value_est_noint<-p_value_est[-seq(1,length(p_value_est),by=(nPredics+1))]
p_value_est_noint_adj<-p.adjust(p_value_est_noint,adjust_method)
p_value_est_noint_adj[is.na(p_value_est_noint_adj)]<-1
coef_est<-abs(bootResu[,1])
coef_est_noint<-coef_est[-seq(1,length(coef_est),by=(nPredics+1))]
coef_est_noint[is.na(coef_est_noint)]<-max(coef_est_noint,na.rm = T)
results$betaNoInt=p_value_est_noint_adj<fwerRate
results$betaInt=p_value_est
results$coef_est_noint=coef_est_noint
return(results)
}
|
NULL
normalizeGaussian_severalstations_prec <-
function(x,
data=x,
cpf=NULL,mean=0,
sd=1,
inverse=FALSE,
qnull=NULL,
valmin=0.5,
type=3,
extremes=TRUE,
sample=NULL,
origin_x=NULL,
origin_data=NULL
) {
out <- x*NA
if (is.null(sample)) {
for (i in 1:ncol(x)) {
out[,i] <- normalizeGaussian_prec(x=x[,i],data=data[,i],cpf=cpf,mean=mean,sd=sd,inverse=inverse,type=type,extremes=extremes,sample=sample,valmin=valmin,qnull=qnull)
}
} else if (sample=="monthly") {
months <- months_f((0.5:11.5)*365/12,abbreviate=TRUE)
for (m in 1:length(months)) {
i_months_x <- extractmonths(data=1:nrow(x),when=months[m],origin=origin_x)
i_months_data <- extractmonths(data=1:nrow(data),when=months[m],origin=origin_data)
for (i in 1:ncol(x)) {
out[i_months_x,i] <- normalizeGaussian_prec(x=x[i_months_x,i],data=data[i_months_data,i],cpf=cpf,mean=mean,sd=sd,inverse=inverse,valmin=valmin,qnull=qnull,type=type,extremes=extremes,sample=NULL)
}
}
} else if (sample=="monthly_year"){
} else {
print("Error in normalizaGaussian_sevaralStation_prec: sample option not yet implemented!!")
}
names(out) <- names(x)
return(out)
}
|
activity_names_repetitions <-
function(repetition_and_path_log,
xml_internal_doc) {
activity <- NULL
task_id <- NULL
all_tasks <- task_names(xml_internal_doc)
all_tasks$task_id <- as.character(all_tasks$task_id)
all_tasks$task_names <- as.character(all_tasks$task_names)
ids_activity <- all_tasks %>%
pull(task_id)
repetitions <- repetition_and_path_log[[2]]
repetitions <- lapply(repetitions, function(repetition) {
repetition <- sapply(1:length(repetition), function(index) {
task_name <- all_tasks %>%
filter(task_id == repetition[index]) %>%
pull(task_names)
})
repetition <- unlist(repetition)
})
return(unique(repetitions))
}
activity_multiple_times_executed <-
function(repetition_and_path_log,
xml_internal_doc,
activity,
direct_parallel) {
task_id <- NULL
structured_path_log <- NULL
first_task <- NULL
second_task <- NULL
relation <- NULL
all_tasks <- task_names(xml_internal_doc)
all_tasks$task_id <- as.character(all_tasks$task_id)
all_tasks$task_names <- as.character(all_tasks$task_names)
ids_activity <- all_tasks %>%
filter(task_names == activity) %>%
pull(task_id)
repetitions <- repetition_and_path_log[[3]]
repetitions <- unique(unlist(repetitions))
activity_part_of_rep <-
sapply(ids_activity, function(activity_id) {
return(activity_id %in% repetitions)
})
filtered_path_log <-
lapply(structured_path_log, function(path) {
indices_element_to_keep <- which(path %in% ids_activity)
return(path[indices_element_to_keep])
})
paths_contain_more_than_two_executions <-
sapply(filtered_path_log, function(path) {
if (length(path) >= 2)
return(TRUE)
else
return(FALSE)
})
parallel_with_himself <- direct_parallel %>%
select(first_task, second_task, relation) %>%
filter(first_task == activity &
second_task == activity & relation == "parallel") %>%
summarise(n = n()) %>%
pull(n)
multiple_executions <-
any(paths_contain_more_than_two_executions) |
any(activity_part_of_rep) | parallel_with_himself > 0
return(multiple_executions)
}
some_traces_without_activity <-
function(repetition_and_path_log,
xml_internal_doc,
activity) {
task_id <- NULL
all_tasks <- task_names(xml_internal_doc)
all_tasks$task_id <- as.character(all_tasks$task_id)
all_tasks$task_names <- as.character(all_tasks$task_names)
ids_activity <- all_tasks %>%
filter(task_names == activity) %>%
pull(task_id)
structured_path_log <- repetition_and_path_log[[4]]
parallel_splits <-
split_gateways(
xml_internal_doc,
"//bpmn:parallelGateway | //parallelGateway |
//bpmn:task | //bpmn:sendTask | //bpmn:receiveTask | //bpmn:manualTask |
//bpmn:businessRuleTask | //bpmn:userTask | //bpmn:scriptTask |
//bpmn:subProcess | //bpmn:callActivity | //task"
)
parallel_joins <-
join_gateways(xml_internal_doc,
"//bpmn:parallelGateway | //parallelGateway")
filtered_path_log <-
lapply(structured_path_log, function(path) {
indices_element_to_keep <- which(path %in% ids_activity)
return(path[indices_element_to_keep])
})
all_paths_contain_activity <-
sapply(filtered_path_log, function(path) {
if (length(path) > 0)
return(TRUE)
else
return(FALSE)
})
if (!all(all_paths_contain_activity)) {
parallel_splits_with_relevant_activity <-
lapply(structured_path_log, function(path) {
indices_elements_parallel_splits <- which(path %in% parallel_splits)
indices_elements_parallel_joins <-
which(path %in% parallel_joins)
indices_elements_activity <-
which(path %in% ids_activity)
parallel_splits_with_relevant_activity <-
lapply(indices_elements_parallel_splits, function(index) {
indices_elements_activity_after_split <-
indices_elements_activity[indices_elements_activity > index]
indices_elements_join_after_split <-
indices_elements_parallel_joins[indices_elements_parallel_joins > index]
if (length(indices_elements_activity_after_split) > 0 &&
length(indices_elements_join_after_split) > 0)
if (indices_elements_activity_after_split[1] < indices_elements_join_after_split[1])
return(path[index])
})
return(parallel_splits_with_relevant_activity)
})
parallel_splits_with_relevant_activity <-
unique(unlist(parallel_splits_with_relevant_activity))
filtered_path_log <-
lapply(structured_path_log, function(path) {
indices_element_to_keep <-
which(path %in% c(ids_activity, parallel_splits_with_relevant_activity))
return(path[indices_element_to_keep])
})
all_paths_contain_activity_or_parallel_gateway <-
sapply(filtered_path_log, function(path) {
if (length(path) > 0)
return(TRUE)
else
return(FALSE)
})
return(!all(all_paths_contain_activity_or_parallel_gateway))
} else {
return(FALSE)
}
}
traces_contain_relation <-
function(repetition_and_path_log,
xml_internal_doc,
activity_1,
activity_2,
always = TRUE,
filter_indirect = TRUE,
precede = FALSE,
alternate_response = FALSE,
alternate_precedence = FALSE,
chain_response = FALSE,
chain_precedence = FALSE,
negation_alternate_precedence = FALSE,
negation_alternate_response = FALSE) {
task_id <- NULL
alternate <-
alternate_response |
alternate_precedence |
negation_alternate_precedence | negation_alternate_response
chain <- chain_response | chain_precedence
all_tasks <- task_names(xml_internal_doc)
all_tasks$task_id <- as.character(all_tasks$task_id)
all_tasks$task_names <- as.character(all_tasks$task_names)
if (filter_indirect) {
indirect <- 1
} else {
indirect <- 0
}
ids_activity_1 <- all_tasks %>%
filter(task_names == activity_1) %>%
pull(task_id)
ids_activity_2 <- all_tasks %>%
filter(task_names == activity_2) %>%
pull(task_id)
structured_path_log <- repetition_and_path_log[[4]]
several_path_logs <- FALSE
if (always |
alternate_response | alternate_precedence) {
structured_path_log_1 <-
filtered_path_log_parallel(structured_path_log, xml_internal_doc, activity_1)
structured_path_log_2 <-
filtered_path_log_parallel(structured_path_log, xml_internal_doc, activity_2)
combinations_log_1_2 <-
expand.grid(1:length(structured_path_log_1),
1:length(structured_path_log_2))
number_combinations <- dim(combinations_log_1_2)[1]
structured_path_log <-
lapply(1:number_combinations, function(combination_index) {
path_log_1_index <- combinations_log_1_2$Var1[combination_index]
path_log_2_index <-
combinations_log_1_2$Var2[combination_index]
return(intersect(structured_path_log_1[[path_log_1_index]], structured_path_log_2[[path_log_2_index]]))
})
if (length(structured_path_log) > 1) {
several_path_logs <- TRUE
} else {
structured_path_log <-
unlist(structured_path_log, recursive = FALSE)
}
}
if (!several_path_logs)
structured_path_log <- list(structured_path_log)
task_ids <- all_tasks %>%
pull(task_id)
parallel_ids <-
node_ids(xml_internal_doc,
"//bpmn:parallelGateway | //parallelGateway")
exclusive_ids <-
node_ids(
xml_internal_doc,
"//bpmn:exclusiveGateway | //exclusiveGateway | //bpmn:eventBasedGateway | //eventBasedGateway"
)
inclusive_ids <-
node_ids(
xml_internal_doc,
"//bpmn:inclusiveGateway | //inclusiveGateway | //bpmn:complexGateway | //complexGateway"
)
events <-
node_ids(
xml_internal_doc,
"//bpmn:startEvent | //bpmn:messageStartEvent | //bpmn:timerStartEvent |
//bpmn:conditionalStartEvent | //bpmn:endEvent | //bpmn:messageEndEvent |
//bpmn:terminateEndEvent | //bpmn:escalationEndEvent | //bpmn:errorEndEvent |
//bpmn:compensationEndEvent | //bpmn:signalEndEvent | //bpmn:intermediateCatchEvent |
//bpmn:intermediateThrowEvent | //bpmn:boundaryEvent | //startEvent | //endEvent"
)
special_elements <-
c(
"AND-split",
"AND-join",
"OR-split",
"OR-join",
"XOR-join",
"XOR-split",
"XOR-loop-split",
"XOR-loop-join",
"Other-loop-split",
"Other-loop-join",
"start-join",
"end-split"
)
structured_path_log <-
lapply(structured_path_log, function(structured_path_log) {
structured_path_log <-
lapply(structured_path_log, function(path) {
indices_element_to_keep <- which(path %in% task_ids)
return(path[indices_element_to_keep])
})
})
if (!alternate & !chain) {
if (!precede) {
relation_in_path <-
lapply(structured_path_log, function(structured_path_log) {
relation_in_path <- sapply(structured_path_log, function(path) {
indices_activity_1 <- which(path %in% ids_activity_1)
indices_activity_2 <-
which(path %in% ids_activity_2)
if (length(indices_activity_1) > 0 &&
length(indices_activity_2) > 0) {
last_index_activity_2 <-
indices_activity_2[length(indices_activity_2)]
if (always)
return(all(
last_index_activity_2 - indices_activity_1 > indirect
))
else
return(any(
last_index_activity_2 - indices_activity_1 > indirect
))
} else if (length(indices_activity_1) == 0) {
return (NA)
} else {
return (FALSE)
}
})
})
} else {
relation_in_path <-
lapply(structured_path_log, function(structured_path_log) {
relation_in_path <- sapply(structured_path_log, function(path) {
indices_activity_1 <- which(path %in% ids_activity_1)
indices_activity_2 <-
which(path %in% ids_activity_2)
if (length(indices_activity_1) > 0 &&
length(indices_activity_2) > 0) {
last_index_activity_2 <-
indices_activity_2[length(indices_activity_2)]
if (always)
return(all(
last_index_activity_2 - indices_activity_1 > indirect
))
else
return(any(
last_index_activity_2 - indices_activity_1 > indirect
))
} else if (length(indices_activity_2) == 0) {
return (NA)
} else {
return (FALSE)
}
})
})
}
} else if (alternate_precedence | chain_precedence) {
relation_in_path <-
lapply(structured_path_log, function(structured_path_log) {
relation_in_path <- sapply(structured_path_log, function(path) {
if (alternate_precedence) {
path <- path[path %in% c(ids_activity_1, ids_activity_2)]
indices_activity_1 <- which(path %in% ids_activity_1)
indices_activity_2 <- which(path %in% ids_activity_2)
indices_activity_2_plus_one <- indices_activity_2 + 1
two_activities_2_without_activity_1_between <-
length(intersect(indices_activity_2, indices_activity_2_plus_one)) > 0
if (length(indices_activity_2) > 0) {
last_index_activity_2 <-
indices_activity_2[length(indices_activity_2)]
indices_activity_1 <-
indices_activity_1[indices_activity_1 < last_index_activity_2]
at_least_as_many_a1_as_2 <-
length(indices_activity_1) >= length(indices_activity_2)
return(
!two_activities_2_without_activity_1_between &
at_least_as_many_a1_as_2
)
} else {
if (length(indices_activity_1) > 0)
return(TRUE)
else
return(NA)
}
}
if (chain_precedence) {
indices_activity_1 <- which(path %in% ids_activity_1)
indices_activity_2 <- which(path %in% ids_activity_2)
indices_directly_before_a2 <- indices_activity_2 - 1
intersection_a1_directly_before_a2 <-
intersect(indices_activity_1, indices_directly_before_a2)
return(
length(indices_activity_2) == length(intersection_a1_directly_before_a2)
)
}
})
})
} else if (alternate_response | chain_response) {
relation_in_path <-
lapply(structured_path_log, function(structured_path_log) {
relation_in_path <- sapply(structured_path_log, function(path) {
if (alternate_response) {
path <- path[path %in% c(ids_activity_1, ids_activity_2)]
indices_activity_1 <- which(path %in% ids_activity_1)
indices_activity_2 <- which(path %in% ids_activity_2)
indices_activity_1_plus_one <- indices_activity_1 + 1
two_activities_1_without_activity_2_between <-
length(intersect(indices_activity_1, indices_activity_1_plus_one)) > 0
if (length(indices_activity_1) > 0) {
first_index_activity_1 <- indices_activity_1[1]
indices_activity_2 <-
indices_activity_2[indices_activity_2 > first_index_activity_1]
at_least_as_many_a2_as_1 <-
length(indices_activity_2) >= length(indices_activity_1)
return(
!two_activities_1_without_activity_2_between &
at_least_as_many_a2_as_1
)
} else {
if (length(indices_activity_2) > 0)
return(TRUE)
else
return(NA)
}
}
if (chain_response) {
indices_activity_1 <- which(path %in% ids_activity_1)
indices_activity_2 <- which(path %in% ids_activity_2)
indices_directly_after_a1 <- indices_activity_1 + 1
intersection_a2_directly_after_a1 <-
intersect(indices_activity_2, indices_directly_after_a1)
return(
length(indices_activity_1) == length(intersection_a2_directly_after_a1)
)
}
})
})
} else if (negation_alternate_response) {
relation_in_path <-
lapply(structured_path_log, function(structured_path_log) {
sapply(structured_path_log, function(path) {
indices_activity_1 <- which(path %in% ids_activity_1)
indices_activity_2 <- which(path %in% ids_activity_2)
if (length(indices_activity_1) > 0 &&
length(indices_activity_2) > 0) {
first_index_activity_1 <- min(indices_activity_1)
last_index_activity_1 <- max(indices_activity_1)
return(!(
any(
indices_activity_2 > first_index_activity_1 &
indices_activity_2 < last_index_activity_1
)
))
} else {
return(TRUE)
}
})
})
} else if (negation_alternate_precedence) {
relation_in_path <-
lapply(structured_path_log, function(structured_path_log) {
sapply(structured_path_log, function(path) {
indices_activity_1 <- which(path %in% ids_activity_1)
indices_activity_2 <- which(path %in% ids_activity_2)
if (length(indices_activity_1) > 0 &&
length(indices_activity_2) > 0) {
first_index_activity_2 <- min(indices_activity_2)
last_index_activity_2 <- max(indices_activity_2)
return((
!any(
indices_activity_1 > first_index_activity_2 &
indices_activity_1 < last_index_activity_2
)
))
} else {
return(TRUE)
}
})
})
}
relation_in_path <-
lapply(relation_in_path, function(relation_in_path) {
relation_in_path <- relation_in_path[!is.na(relation_in_path)]
})
if (always) {
relation_in_path <-
sapply(relation_in_path, function(relation_in_path) {
if (length(relation_in_path) > 0)
return(all(relation_in_path))
else
return(FALSE)
})
return(any(relation_in_path))
} else
relation_in_path <-
sapply(relation_in_path, function(relation_in_path) {
if (length(relation_in_path) > 0)
return(any(relation_in_path) && any(!relation_in_path))
else
return(FALSE)
})
return(any(relation_in_path))
}
filtered_path_log_parallel <-
function(structured_path_log,
xml_internal_doc,
activity_name) {
task_id <- NULL
oldw <- getOption("warn")
options(warn = -1)
parallel_splits <-
split_gateways(
xml_internal_doc,
"//bpmn:parallelGateway | //parallelGateway |
//bpmn:task | //bpmn:sendTask | //bpmn:receiveTask | //bpmn:manualTask |
//bpmn:businessRuleTask | //bpmn:userTask | //bpmn:scriptTask |
//bpmn:subProcess | //bpmn:callActivity | //task"
)
parallel_joins <-
join_gateways(xml_internal_doc,
"//bpmn:parallelGateway | //parallelGateway")
other_splits <-
split_gateways(
xml_internal_doc,
"//bpmn:exclusiveGateway | //exclusiveGateway | //bpmn:eventBasedGateway | //eventBasedGateway |
//bpmn:inclusiveGateway | //inclusiveGateway | //bpmn:complexGateway | //complexGateway"
)
other_joins <-
join_gateways(
xml_internal_doc,
"//bpmn:exclusiveGateway | //exclusiveGateway | //bpmn:eventBasedGateway | //eventBasedGateway |
//bpmn:inclusiveGateway | //inclusiveGateway | //bpmn:complexGateway | //complexGateway"
)
task_ids <- task_names(xml_internal_doc) %>%
filter(task_names == activity_name) %>%
mutate(task_id = as.character(task_id)) %>%
pull(task_id)
parallel_gateway_with_activity_filter <-
lapply(task_ids, function(task_id) {
path_log_filtered_activity_id_parallel <-
lapply(structured_path_log, function(path) {
indices_to_filter <-
which(
path %in% c(
parallel_splits,
parallel_joins,
task_id,
other_splits,
other_joins
)
)
indices_to_filter <- sort(indices_to_filter)
return(path[indices_to_filter])
})
parallel_gateway_with_task_id_filter <-
lapply(path_log_filtered_activity_id_parallel, function(path) {
sub_path_indices <-
which(path %in% c(parallel_splits, parallel_joins, task_id))
sub_path <- path[sub_path_indices]
parallel_split_indices <-
which(sub_path %in% parallel_splits)
parallel_join_indices <-
which(sub_path %in% parallel_joins)
task_indices <- which(sub_path %in% task_id)
if (length(task_indices) > 0) {
parallel_splits_before_task <-
parallel_split_indices[parallel_split_indices < task_indices[1]]
parallel_joins_before_task <-
parallel_join_indices[parallel_join_indices < task_indices[1]]
if (length(parallel_splits_before_task) > length(parallel_joins_before_task)) {
sub_path_indices <- 1:length(sub_path)
nesting_depth_path <-
sub_path[sub_path_indices < task_indices[1]]
nesting_depth_path[parallel_splits_before_task] <-
1
nesting_depth_path[parallel_joins_before_task] <-
-1
nesting_depth_path[parallel_joins_before_task < parallel_splits_before_task[1]] <-
0
nesting_depth_path <- cumsum(nesting_depth_path)
indices_nesting_depth_equal_zero <-
which(nesting_depth_path == 0)
if (length(indices_nesting_depth_equal_zero) == 0) {
index_after_last_nesting_depth_zero <- 1
parallel_split_task <-
sub_path[index_after_last_nesting_depth_zero]
} else {
index_after_last_nesting_depth_zero <-
indices_nesting_depth_equal_zero[length(indices_nesting_depth_equal_zero)] + 1
parallel_split_task <-
sub_path[index_after_last_nesting_depth_zero]
}
index_parallel_split_task <-
which(path %in% parallel_split_task)
task_indices <- which(path %in% task_id)
sub_path <-
path[index_parallel_split_task[1]:task_indices[1]]
sub_path_indices <-
which(sub_path %in% c(other_splits, other_joins))
sub_path <- sub_path[sub_path_indices]
other_split_indices <-
which(sub_path %in% other_splits)
other_join_indices <-
which(sub_path %in% other_joins)
if (length(other_split_indices) > length(other_join_indices)) {
nesting_depth_path <- sub_path
nesting_depth_path[other_split_indices] <- 1
nesting_depth_path[other_join_indices] <- -1
nesting_depth_path[other_join_indices < other_split_indices[1]] <-
0
nesting_depth_path <-
cumsum(nesting_depth_path)
indices_exclusive_nesting_depth_zero <-
which(nesting_depth_path == 0)
if (length(indices_exclusive_nesting_depth_zero) == 0) {
task_id <- sub_path[1]
} else {
task_id <-
sub_path[indices_exclusive_nesting_depth_zero[length(indices_exclusive_nesting_depth_zero)] + 1]
}
}
return(data.frame(
parallel_split = as.character(parallel_split_task),
task = as.character(task_id)
))
}
}
})
})
parallel_gateway_with_activity_filter <-
unlist(parallel_gateway_with_activity_filter, recursive = FALSE)
parallel_gateway_with_activity_filter <-
bind_rows(parallel_gateway_with_activity_filter)
parallel_gateway_with_activity_filter <-
parallel_gateway_with_activity_filter %>%
distinct()
if (length(parallel_gateway_with_activity_filter) > 0) {
paths_to_filter <-
lapply(1:length(parallel_gateway_with_activity_filter$parallel_split), function(gateway_index) {
gateway <-
parallel_gateway_with_activity_filter$parallel_split[gateway_index]
activity <-
parallel_gateway_with_activity_filter$task[gateway_index]
path_indices_to_filter <-
sapply(1:length(structured_path_log), function(path_index) {
path <- structured_path_log[[path_index]]
gateway_in_path <-
length(which(path %in% gateway)) > 0
activity_in_path <-
length(which(path %in% activity)) > 0
if (!activity_in_path & gateway_in_path)
return(path_index)
})
})
paths_to_filter <- lapply(paths_to_filter, unlist)
filtered_path_log <-
lapply(paths_to_filter, function(filter_vector) {
lapply(1:length(structured_path_log), function(index) {
if (!(index %in% filter_vector)) {
return(structured_path_log[[index]])
}
})
})
filtered_path_log <-
lapply(filtered_path_log, function(path_log) {
return(path_log[-which(sapply(path_log, is.null))])
})
options(warn = oldw)
return(filtered_path_log)
} else {
options(warn = oldw)
return(list(structured_path_log))
}
}
direct_parallel_relations <-
function(repetition_and_path_log,
xml_internal_doc) {
oldw <- getOption("warn")
options(warn = -1)
second <- NULL
number_of_occurences <- NULL
task_id <- NULL
sometimes <- NULL
relation <- NULL
first_task <- NULL
second_task <- NULL
X1 <- NULL
X2 <- NULL
exclusive <- NULL
structured_path_log <- repetition_and_path_log[[4]]
task_ids <- task_names(xml_internal_doc) %>%
pull(task_id)
parallel_ids <-
node_ids(xml_internal_doc,
"//bpmn:parallelGateway | //parallelGateway")
exclusive_ids <-
node_ids(
xml_internal_doc,
"//bpmn:exclusiveGateway | //exclusiveGateway | //bpmn:eventBasedGateway | //eventBasedGateway"
)
inclusive_ids <-
node_ids(
xml_internal_doc,
"//bpmn:inclusiveGateway | //inclusiveGateway | //bpmn:complexGateway | //complexGateway"
)
events <-
node_ids(
xml_internal_doc,
"//bpmn:startEvent | //bpmn:messageStartEvent | //bpmn:timerStartEvent |
//bpmn:conditionalStartEvent | //bpmn:endEvent | //bpmn:messageEndEvent |
//bpmn:terminateEndEvent | //bpmn:escalationEndEvent | //bpmn:errorEndEvent |
//bpmn:compensationEndEvent | //bpmn:signalEndEvent | //bpmn:intermediateCatchEvent |
//bpmn:intermediateThrowEvent | //bpmn:boundaryEvent | //startEvent | //endEvent"
)
special_elements <-
c(
"AND-split",
"AND-join",
"OR-split",
"OR-join",
"XOR-join",
"XOR-split",
"XOR-loop-split",
"XOR-loop-join",
"Other-loop-split",
"Other-loop-join",
"start-join",
"end-split"
)
structured_path_log <-
lapply(structured_path_log, function(path) {
indices_element_to_keep <- which(path %in% task_ids)
return(path[indices_element_to_keep])
})
relations <- lapply(structured_path_log, function(path) {
if (length(path) >= 2) {
path_without_end <- as.character(path[1:(length(path) - 1)])
path_without_start <- as.character(path[2:length(path)])
relations <- cbind(path_without_end, path_without_start)
relations <- as.data.frame(relations)
colnames(relations) <- c("first", "second")
relations$first <- as.character(relations$first)
relations$second <- as.character(relations$second)
return(relations)
}
})
relations <- bind_rows(relations)
direct_relations <- relations %>%
unique() %>%
mutate(relation = "d_l_t_r")
if (nrow(direct_relations) > 0) {
direct_relations_reversed <-
cbind(direct_relations$second, direct_relations$first)
direct_relations_reversed <-
as.data.frame(direct_relations_reversed)
colnames(direct_relations_reversed) <-
c("first", "second")
direct_relations_reversed$first <-
as.character(direct_relations_reversed$first)
direct_relations_reversed$second <-
as.character(direct_relations_reversed$second)
direct_relations_reversed <- direct_relations_reversed %>%
mutate(relation = "d_r_t_l")
all_direct_relations <-
rbind(direct_relations, direct_relations_reversed)
} else {
all_direct_relations <- direct_relations %>%
mutate(second = relation, first = relation)
}
structured_path_log <- repetition_and_path_log[[4]]
path_log_with_parallel_gateways <-
lapply(structured_path_log, function(path) {
indices_gateways <-
which(path %in% c(exclusive_ids, special_elements))
indices_all_elements <- 1:length(path)
indices_element_to_keep <-
setdiff(indices_all_elements, indices_gateways)
return(path[indices_element_to_keep])
})
path_log_with_exclusive_gateways <-
lapply(structured_path_log, function(path) {
indices_gateways <-
which(path %in% c(special_elements))
indices_all_elements <- 1:length(path)
indices_element_to_keep <-
setdiff(indices_all_elements, indices_gateways)
return(path[indices_element_to_keep])
})
parallel_splits <-
split_gateways(
xml_internal_doc,
"//bpmn:parallelGateway | //parallelGateway |
//bpmn:task | //bpmn:sendTask | //bpmn:receiveTask | //bpmn:manualTask |
//bpmn:businessRuleTask | //bpmn:userTask | //bpmn:scriptTask |
//bpmn:subProcess | //bpmn:callActivity | //task"
)
inclusive_splits <-
split_gateways(
xml_internal_doc,
"//bpmn:inclusiveGateway | //inclusiveGateway |
//bpmn:complexGateway | //complexGateway"
)
parallel_joins <-
join_gateways(xml_internal_doc,
"//bpmn:parallelGateway | //parallelGateway")
inclusive_joins <-
join_gateways(
xml_internal_doc,
"//bpmn:inclusiveGateway | //inclusiveGateway |
//bpmn:complexGateway | //complexGateway"
)
exclusive_splits <-
split_gateways(
xml_internal_doc,
"//bpmn:exclusiveGateway | //exclusiveGateway | //bpmn:eventBasedGateway | //eventBasedGateway"
)
exclusive_joins <-
join_gateways(
xml_internal_doc,
"//bpmn:exclusiveGateway | //exclusiveGateway | //bpmn:eventBasedGateway | //eventBasedGateway"
)
parallel_splits <- c(parallel_splits, inclusive_splits)
parallel_joins <- c(parallel_joins, inclusive_joins)
parallel_relationships <-
lapply(parallel_splits, function(parallel_split) {
relevant_paths <-
lapply(path_log_with_parallel_gateways, function(path) {
parallel_index <- which(path %in% parallel_split)
if (length(parallel_index) > 0)
return(path[parallel_index[1]:length(path)])
})
null_indices <- which(sapply(relevant_paths, is.null))
if (length(null_indices) > 0)
relevant_paths <-
relevant_paths[-null_indices]
intersection_elements <-
reduce(relevant_paths, intersect)
intersection_parallel_joins <-
which(intersection_elements %in% c(parallel_joins, inclusive_joins))
parallel_join <-
intersection_elements[intersection_parallel_joins[1]]
sub_paths_between_split_join <-
lapply(relevant_paths, function(path) {
index_after_parallel_split <-
which(path == parallel_split)[1]
index_before_parallel_join <-
which(path == parallel_join)[1]
if (is.na(index_before_parallel_join))
index_before_parallel_join <- length(path)
return (path[index_after_parallel_split:index_before_parallel_join])
})
second_elements_sub_paths <-
sapply(sub_paths_between_split_join, function(sub_path) {
if (length(sub_path) >= 3)
return(sub_path[2])
})
second_elements_sub_paths <-
unique(second_elements_sub_paths)
elements_being_part_outgoing_flow_parallel_split <-
lapply(second_elements_sub_paths, function(element) {
if (length(element) > 0) {
elements_of_path <-
sapply(sub_paths_between_split_join, function(sub_path) {
if (element %in% sub_path)
if (length(sub_path) >= 2)
return(sub_path[2:length(sub_path) - 1])
})
} else {
elements_of_path <- character()
}
elements_of_path <- unique(unlist(elements_of_path))
elements_of_path <-
elements_of_path[elements_of_path %in% task_ids]
})
if (length(elements_being_part_outgoing_flow_parallel_split) > 1) {
combinations_all_paths <-
t(combn(
1:length(elements_being_part_outgoing_flow_parallel_split),
2
))
combinations_elements_two_paths <-
lapply(1:dim(combinations_all_paths)[1], function(index) {
sub_path_1 <-
elements_being_part_outgoing_flow_parallel_split[[combinations_all_paths[index, 1]]]
sub_path_2 <-
elements_being_part_outgoing_flow_parallel_split[[combinations_all_paths[index, 2]]]
combinations_all_paths <-
expand.grid(first = sub_path_1, second = sub_path_2)
})
combinations_elements_two_paths <-
bind_rows(combinations_elements_two_paths)
combinations_elements_two_paths_reversed <-
data.frame(
first = as.character(combinations_elements_two_paths$second),
second = as.character(combinations_elements_two_paths$first)
)
combinations_elements_two_paths <-
rbind(combinations_elements_two_paths,
combinations_elements_two_paths_reversed)
combinations_elements_two_paths <-
unique(combinations_elements_two_paths)
combinations_elements_two_paths$first <-
as.character(combinations_elements_two_paths$first)
combinations_elements_two_paths$second <-
as.character(combinations_elements_two_paths$second)
combinations_elements_two_paths <-
combinations_elements_two_paths
return(combinations_elements_two_paths)
} else {
return(data.frame(
first = character(),
second = character(),
exclusive = logical()
))
}
})
parallel_relationships <- bind_rows(parallel_relationships)
direct_relations_part_parallel_gateway <-
lapply(parallel_splits, function(parallel_split) {
relevant_paths <-
lapply(path_log_with_parallel_gateways, function(path) {
parallel_index <- which(path %in% parallel_split)
if (length(parallel_index) > 0)
return(path[parallel_index[1]:length(path)])
})
null_indices <- which(sapply(relevant_paths, is.null))
if (length(null_indices) > 0)
relevant_paths <-
relevant_paths[-null_indices]
intersection_elements <-
reduce(relevant_paths, intersect)
intersection_parallel_joins <-
which(intersection_elements %in% c(parallel_joins, inclusive_joins))
parallel_join <-
intersection_elements[intersection_parallel_joins[1]]
sub_paths_between_split_join <-
lapply(relevant_paths, function(path) {
index_after_parallel_split <-
which(path == parallel_split)[1]
index_before_parallel_join <-
which(path == parallel_join)[1]
if (is.na(index_before_parallel_join))
index_before_parallel_join <- length(path)
return (path[index_after_parallel_split:index_before_parallel_join])
})
sub_paths_between_split_join <-
unique(sub_paths_between_split_join)
direct_relations_part_parallel_gateway <-
lapply(sub_paths_between_split_join, function(path) {
path <- path[path %in% task_ids]
if (length(path) > 1) {
first <- path[1:length(path) - 1]
second <- path[2:length(path)]
direct_relations <-
data.frame(first = as.character(first), second = as.character(second))
direct_relations <- direct_relations %>%
mutate(relation = "d_l_t_r")
direct_relations_reversed <-
data.frame(first = as.character(second), second = as.character(first))
direct_relations_reversed <-
direct_relations_reversed %>%
mutate(relation = "d_r_t_l")
direct_relations <-
rbind(direct_relations, direct_relations_reversed)
return(direct_relations)
} else {
return(data.frame(
first = character(),
second = character(),
relation = character()
))
}
})
direct_relations_part_parallel_gateway <-
bind_rows(direct_relations_part_parallel_gateway)
})
direct_relations_part_parallel_gateway <-
bind_rows(direct_relations_part_parallel_gateway)
direct_relations_part_parallel_gateway <-
direct_relations_part_parallel_gateway %>%
mutate(sometimes = TRUE)
exclusive_relationships <-
lapply(exclusive_splits, function(exclusive_split) {
path_indices <-
1:length(path_log_with_exclusive_gateways)
path_indices_selector <-
sapply(path_indices, function(path_index) {
return(exclusive_split %in% path_log_with_exclusive_gateways[[path_index]])
})
relevant_paths <-
path_log_with_exclusive_gateways[path_indices_selector]
intersection_elements <-
reduce(relevant_paths, intersect)
intersection_exclusive_joins <-
which(intersection_elements %in% exclusive_joins)
exclusive_join <-
intersection_elements[intersection_exclusive_joins[1]]
sub_paths_between_split_join <-
lapply(relevant_paths, function(path) {
index_after_exclusive_split <-
which(path == exclusive_split)[1]
index_before_exclusive_join <-
which(path == exclusive_join)[1]
if (is.na(index_before_exclusive_join))
index_before_exclusive_join <- length(path)
sub_path <-
as.character(path[index_after_exclusive_split:index_before_exclusive_join])
return (sub_path)
})
second_elements_sub_paths <-
sapply(sub_paths_between_split_join, function(sub_path) {
if (length(sub_path) >= 3)
return(sub_path[2])
})
second_elements_sub_paths <-
unique(second_elements_sub_paths)
elements_being_part_outgoing_flow_exclusive_split <-
lapply(second_elements_sub_paths, function(element) {
if (length(element) > 0) {
elements_of_path <-
sapply(sub_paths_between_split_join, function(sub_path) {
if (element %in% sub_path)
if (length(sub_path) >= 2)
return(sub_path[2:length(sub_path) - 1])
})
} else {
elements_of_path <- character()
}
elements_of_path <- unique(unlist(elements_of_path))
elements_of_path <-
elements_of_path[elements_of_path %in% task_ids]
})
if (length(elements_being_part_outgoing_flow_exclusive_split) > 1) {
combinations_all_paths <-
t(combn(
1:length(elements_being_part_outgoing_flow_exclusive_split),
2
))
combinations_elements_two_paths <-
lapply(1:dim(combinations_all_paths)[1], function(index) {
sub_path_1 <-
elements_being_part_outgoing_flow_exclusive_split[[combinations_all_paths[index, 1]]]
sub_path_2 <-
elements_being_part_outgoing_flow_exclusive_split[[combinations_all_paths[index, 2]]]
combinations_all_paths <-
expand.grid(first = sub_path_1, second = sub_path_2)
})
combinations_elements_two_paths <-
bind_rows(combinations_elements_two_paths)
combinations_elements_two_paths_reversed <-
data.frame(
first = as.character(combinations_elements_two_paths$second),
second = as.character(combinations_elements_two_paths$first)
)
combinations_elements_two_paths <-
rbind(combinations_elements_two_paths,
combinations_elements_two_paths_reversed)
combinations_elements_two_paths <-
unique(combinations_elements_two_paths)
combinations_elements_two_paths$first <-
as.character(combinations_elements_two_paths$first)
combinations_elements_two_paths$second <-
as.character(combinations_elements_two_paths$second)
combinations_elements_two_paths <-
combinations_elements_two_paths %>%
mutate(exclusive = TRUE)
return(combinations_elements_two_paths)
} else {
return(data.frame(
first = character(),
second = character(),
exclusive = logical()
))
}
})
exclusive_relationships <-
bind_rows(exclusive_relationships)
if (length(exclusive_relationships) != 0) {
exclusive_relationships_filter <- exclusive_relationships %>%
select(first, second)
if (length(parallel_relationships) > 0) {
interleaving_relations <-
setdiff(parallel_relationships,
exclusive_relationships_filter)
}
else {
interleaving_relations <-
data.frame(first = character(),
second = character(),
relation = character())
}
} else {
interleaving_relations <- parallel_relationships
}
interleaving_relations <- interleaving_relations %>%
mutate(relation = "parallel")
direct_parallel_relations <-
rbind(interleaving_relations, all_direct_relations)
if (nrow(direct_relations_part_parallel_gateway) > 0) {
direct_parallel_relations <-
left_join(
direct_parallel_relations,
direct_relations_part_parallel_gateway,
by = c("first", "second", "relation")
)
direct_parallel_relations$sometimes[is.na(direct_parallel_relations$sometimes)] <-
FALSE
direct_parallel_relations <- direct_parallel_relations %>%
mutate(relation = if_else(sometimes, paste("s_", relation, sep = ""), relation)) %>%
select(first, second, relation)
}
all_tasks <- task_names(xml_internal_doc)
all_tasks$task_id <- as.character(all_tasks$task_id)
all_tasks$task_names <- as.character(all_tasks$task_names)
direct_parallel_relations <-
left_join(direct_parallel_relations,
all_tasks,
by = c("first" = "task_id"))
direct_parallel_relations <-
left_join(direct_parallel_relations,
all_tasks,
by = c("second" = "task_id"))
colnames(direct_parallel_relations) <-
c("first", "second", "relation", "first_task", "second_task")
relations_parallel_join <-
relations_with_parallel_join_split(repetition_and_path_log, xml_internal_doc)
direct_parallel_relations <-
left_join(direct_parallel_relations,
relations_parallel_join,
by = c("first", "second"))
direct_parallel_relations$sometimes[is.na(direct_parallel_relations$sometimes)] <-
FALSE
direct_parallel_relations <- direct_parallel_relations %>%
mutate(
relation = if_else(
sometimes &
relation != "s_d_l_t_r" &
relation != "s_d_r_t_l",
paste("s_", relation, sep = ""),
relation
)
) %>%
select(first, second, relation, first_task, second_task) %>%
filter(!is.na(first_task) & !is.na(second_task)) %>%
distinct()
options(warn = oldw)
return(direct_parallel_relations)
}
relations_with_parallel_join_split <-
function(repetition_and_path_log,
xml_internal_doc) {
task_id <- NULL
parallel_joins <-
join_gateways(xml_internal_doc,
"//bpmn:parallelGateway | //parallelGateway")
parallel_splits <-
split_gateways(xml_internal_doc,
"//bpmn:parallelGateway | //parallelGateway")
inclusive_joins <-
join_gateways(
xml_internal_doc,
"//bpmn:inclusiveGateway | //inclusiveGateway |
//bpmn:complexGateway | //complexGateway"
)
inclusive_splits <-
split_gateways(
xml_internal_doc,
"//bpmn:inclusiveGateway | //inclusiveGateway |
//bpmn:complexGateway | //complexGateway"
)
task_ids <- task_names(xml_internal_doc) %>%
pull(task_id)
structured_path_log <- repetition_and_path_log[[4]]
relevant_relations <-
lapply(structured_path_log, function(path) {
parallel_join_indices <-
which(path %in% c(
parallel_joins,
inclusive_joins,
parallel_splits,
inclusive_splits
))
activity_indices <- which(path %in% task_ids)
activities_before_parallel_join <-
sapply(parallel_join_indices, function(index) {
activity_indices_before_join <-
activity_indices[activity_indices < index]
last_activity_before_join <-
path[activity_indices_before_join[length(activity_indices_before_join)]]
return(as.character(last_activity_before_join))
})
activities_after_parallel_join <-
sapply(parallel_join_indices, function(index) {
activity_indices_after_join <-
activity_indices[activity_indices > index]
last_activity_after_join <-
path[activity_indices_after_join[1]]
return(as.character(last_activity_after_join))
})
relations <-
as.data.frame(cbind(
first = as.character(activities_before_parallel_join),
second = as.character(activities_after_parallel_join)
))
relations$first <- as.character(relations$first)
relations$second <- as.character(relations$second)
return (relations)
})
relevant_relations <- bind_rows(relevant_relations) %>%
distinct() %>%
mutate(sometimes = TRUE)
relevant_relations_reversed <-
data_frame(
first = relevant_relations$second,
second = relevant_relations$first,
sometimes = TRUE
)
relevant_relations <-
rbind(relevant_relations, relevant_relations_reversed)
return(relevant_relations)
}
|
handlers(handler_pbcol)
with_progress({ y <- slow_sum(1:10) })
print(y)
|
PREPS$covr <- function(state, path = state$path, quiet) {
covr <- try(list(coverage = package_coverage(path, quiet = quiet)),
silent = quiet)
if (inherits(covr, "try-error")) {
warning("Prep step for test coverage failed.")
} else {
with_options(
list(covr.rstudio_source_markers = FALSE),
covr$zero <- zero_coverage(covr$coverage)
)
covr$pct_by_line <- percent_coverage(covr$coverage, by = "line")
covr$pct_by_expr <- percent_coverage(covr$coverage, by = "expression")
}
state$covr <- covr
state
}
|
local_edition(3)
local_reproducible_output()
test_that("check empty pk_model", {
expect_snapshot(check(pk_model()))
})
test_that("check complete pk_model", {
expect_snapshot(
check(
pk_model() +
pk_distribution_1cmp() +
pk_elimination_linear() +
obs_additive(conc~C["central"])
)
)
})
test_that("1cmp linear, advan", {
m <- pk_model() +
pk_distribution_1cmp() +
pk_elimination_linear() +
obs_additive(conc~C["central"])
render(m) %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("CL = THETA(2) * EXP(ETA(2))") %>%
expect_contains(" ADVAN1 ") %>%
expect_contains(" TRANS2 ") %>%
expect_contains("CONC = A(1)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
})
test_that("1cmp linear, ode", {
m <- pk_model() +
pk_distribution_1cmp() +
pk_elimination_linear() +
obs_additive(conc~C["central"])
render(m,
options = assemblerr_options(ode.use_special_advans = FALSE,
ode.use_general_linear_advans = FALSE)
) %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("CL = THETA(2) * EXP(ETA(2))") %>%
expect_contains("DADT(1) = -(CL * (A(1)/VC))") %>%
expect_contains("CONC = A(1)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
})
test_that("2cmp linear", {
m <- pk_model() +
pk_distribution_2cmp() +
pk_elimination_linear() +
obs_additive(conc~C["central"])
render(m,
options = assemblerr_options(ode.use_special_advans = FALSE,
ode.use_general_linear_advans = FALSE)
) %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("VP = THETA(2) * EXP(ETA(2))") %>%
expect_contains("Q = THETA(3) * EXP(ETA(3))") %>%
expect_contains("CL = THETA(4) * EXP(ETA(4))") %>%
expect_contains("DADT(1) = Q * (A(2)/VP) - (Q * (A(1)/VC) + CL * (A(1)/VC))") %>%
expect_contains("DADT(2) = Q * (A(1)/VC) - Q * (A(2)/VP)") %>%
expect_contains("CONC = A(1)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
render(m,
options = assemblerr_options(ode.use_special_advans = TRUE,
ode.use_general_linear_advans = FALSE)
) %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("VP = THETA(2) * EXP(ETA(2))") %>%
expect_contains("Q = THETA(3) * EXP(ETA(3))") %>%
expect_contains("CL = THETA(4) * EXP(ETA(4))") %>%
expect_contains("V1 = VC") %>%
expect_contains("V2 = VP") %>%
expect_contains("CONC = A(1)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
render(m,
options = assemblerr_options(ode.use_special_advans = FALSE,
ode.use_general_linear_advans = TRUE)
) %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("VP = THETA(2) * EXP(ETA(2))") %>%
expect_contains("Q = THETA(3) * EXP(ETA(3))") %>%
expect_contains("CL = THETA(4) * EXP(ETA(4))") %>%
expect_contains("K12 = Q * (1/VC)") %>%
expect_contains("K21 = Q * (1/VP)") %>%
expect_contains("K10 = CL * (1/VC)") %>%
expect_contains("CONC = A(1)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
})
test_that("1cmp nonlinear", {
m <- pk_model() +
pk_distribution_1cmp() +
pk_elimination_nl() +
obs_additive(conc~C["central"])
render(m,
options = assemblerr_options(ode.use_special_advans = TRUE,
ode.use_general_linear_advans = TRUE)
) %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("CLMM = THETA(2) * EXP(ETA(2))") %>%
expect_contains("KM = THETA(3) * EXP(ETA(3))") %>%
expect_contains("DADT(1) = -(CLMM * KM/(KM + A(1)/VC))") %>%
expect_contains("CONC = A(1)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
m <- pk_model() +
pk_distribution_1cmp() +
pk_elimination_nl(prm_vmax = prm_log_normal("vmax"), prm_clmm = NULL) +
obs_additive(conc~C["central"])
render(m,
options = assemblerr_options(ode.use_special_advans = TRUE,
ode.use_general_linear_advans = TRUE)
) %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("VMAX = THETA(2) * EXP(ETA(2))") %>%
expect_contains("KM = THETA(3) * EXP(ETA(3))") %>%
expect_contains("DADT(1) = -(VMAX * (A(1)/VC)/(KM + A(1)/VC))") %>%
expect_contains("CONC = A(1)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
expect_warning(pk_elimination_nl(prm_clmm = prm_log_normal("clmm"), prm_vmax = prm_log_normal("vmax")))
})
test_that("1cmp linear 1st order absorption, advan", {
m <- pk_model() +
pk_absorption_fo() +
pk_distribution_1cmp() +
pk_elimination_linear() +
obs_additive(conc~C["central"])
render(m) %>%
expect_contains(" ADVAN2 ") %>%
expect_contains(" TRANS2 ") %>%
expect_does_not_contain("$MODEL") %>%
expect_contains("MAT = THETA(1) * EXP(ETA(1))") %>%
expect_contains("VC = THETA(2) * EXP(ETA(2))") %>%
expect_contains("CL = THETA(3) * EXP(ETA(3))") %>%
expect_contains("KA = 1/MAT") %>%
expect_contains("CONC = A(2)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
})
test_that("3cmp linear", {
m <- pk_model() +
pk_distribution_3cmp() +
pk_elimination_linear() +
obs_additive(conc~C["central"])
render(m,
options = assemblerr_options(ode.use_special_advans = FALSE,
ode.use_general_linear_advans = FALSE,
ode.general_nonlinear_advan = "advan13")
) %>%
expect_contains("$SUBROUTINES ADVAN13") %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("VP1 = THETA(2) * EXP(ETA(2))") %>%
expect_contains("VP2 = THETA(3) * EXP(ETA(3))") %>%
expect_contains("Q1 = THETA(4) * EXP(ETA(4))") %>%
expect_contains("Q2 = THETA(5) * EXP(ETA(5))") %>%
expect_contains("CL = THETA(6) * EXP(ETA(6))") %>%
expect_contains("DADT(1) = Q1 * (A(2)/VP1) + Q2 * (A(3)/VP2) - (Q1 * (A(1)/VC) + Q2 * (A(1)/VC) + CL * (A(1)/VC))") %>%
expect_contains("DADT(2) = Q1 * (A(1)/VC) - Q1 * (A(2)/VP1)") %>%
expect_contains("DADT(3) = Q2 * (A(1)/VC) - Q2 * (A(3)/VP2)") %>%
expect_contains("CONC = A(1)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
render(m,
options = assemblerr_options(ode.use_special_advans = TRUE,
ode.use_general_linear_advans = FALSE)
) %>%
expect_contains("$SUBROUTINES ADVAN11") %>%
expect_does_not_contain("$MODEL") %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("VP1 = THETA(2) * EXP(ETA(2))") %>%
expect_contains("VP2 = THETA(3) * EXP(ETA(3))") %>%
expect_contains("Q1 = THETA(4) * EXP(ETA(4))") %>%
expect_contains("Q2 = THETA(5) * EXP(ETA(5))") %>%
expect_contains("CL = THETA(6) * EXP(ETA(6))") %>%
expect_contains("V1 = VC") %>%
expect_contains("V2 = VP1") %>%
expect_contains("V3 = VP2") %>%
expect_contains("CONC = A(1)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
render(m,
options = assemblerr_options(ode.use_special_advans = FALSE,
ode.use_general_linear_advans = TRUE)
) %>%
expect_contains("$SUBROUTINES ADVAN5") %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("VP1 = THETA(2) * EXP(ETA(2))") %>%
expect_contains("VP2 = THETA(3) * EXP(ETA(3))") %>%
expect_contains("Q1 = THETA(4) * EXP(ETA(4))") %>%
expect_contains("Q2 = THETA(5) * EXP(ETA(5))") %>%
expect_contains("CL = THETA(6) * EXP(ETA(6))") %>%
expect_contains("K12 = Q1 * (1/VC)") %>%
expect_contains("K21 = Q1 * (1/VP1)") %>%
expect_contains("K13 = Q2 * (1/VC)") %>%
expect_contains("K31 = Q2 * (1/VP2)") %>%
expect_contains("K10 = CL * (1/VC)") %>%
expect_contains("CONC = A(1)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
})
test_that("2cmp linear, fo", {
m <- pk_model() +
pk_distribution_2cmp() +
pk_elimination_linear() +
pk_absorption_fo() +
obs_additive(conc~C["central"])
render(m,
options = assemblerr_options(ode.use_special_advans = TRUE,
ode.use_general_linear_advans = FALSE,
ode.general_nonlinear_advan = "advan13")
) %>%
expect_contains("$SUBROUTINES ADVAN4") %>%
expect_contains("TRANS4") %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("VP = THETA(2) * EXP(ETA(2))") %>%
expect_contains("Q = THETA(3) * EXP(ETA(3))") %>%
expect_contains("CL = THETA(4) * EXP(ETA(4))") %>%
expect_contains("MAT = THETA(5) * EXP(ETA(5))") %>%
expect_contains("KA = 1/MAT") %>%
expect_contains("V2 = VC") %>%
expect_contains("V3 = VP") %>%
expect_contains("CONC = A(2)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
})
test_that("3cmp linear, fo", {
m <- pk_model() +
pk_distribution_3cmp() +
pk_elimination_linear() +
pk_absorption_fo() +
obs_additive(conc~C["central"])
render(m,
options = assemblerr_options(ode.use_special_advans = TRUE,
ode.use_general_linear_advans = FALSE,
ode.general_nonlinear_advan = "advan13")
) %>%
expect_contains("$SUBROUTINES ADVAN12") %>%
expect_contains("TRANS4") %>%
expect_does_not_contain("$MODEL") %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("VP1 = THETA(2) * EXP(ETA(2))") %>%
expect_contains("VP2 = THETA(3) * EXP(ETA(3))") %>%
expect_contains("Q1 = THETA(4) * EXP(ETA(4))") %>%
expect_contains("Q2 = THETA(5) * EXP(ETA(5))") %>%
expect_contains("CL = THETA(6) * EXP(ETA(6))") %>%
expect_contains("MAT = THETA(7) * EXP(ETA(7))") %>%
expect_contains("KA = 1/MAT") %>%
expect_contains("V2 = VC") %>%
expect_contains("V3 = VP1") %>%
expect_contains("V4 = VP2") %>%
expect_contains("CONC = A(2)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
})
test_that("1cmp linear, transit delay", {
m <- pk_model() +
pk_distribution_1cmp() +
pk_elimination_linear() +
pk_absorption_fo_transit(transit_compartments = 3) +
obs_additive(conc~C["central"])
render(m,
options = assemblerr_options(
ode.use_special_advans = TRUE,
ode.use_general_linear_advans = TRUE
)
) %>%
expect_contains(" ADVAN5 ") %>%
expect_contains(" TRANS1 ") %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("CL = THETA(2) * EXP(ETA(2))") %>%
expect_contains("MDT = THETA(3) * EXP(ETA(3))") %>%
expect_contains("MAT = THETA(4) * EXP(ETA(4))") %>%
expect_contains("KTR = 3/MDT") %>%
expect_contains("KA = 1/MAT") %>%
expect_contains("K12 = KTR") %>%
expect_contains("K23 = KTR") %>%
expect_contains("K34 = KTR") %>%
expect_contains("K45 = KA") %>%
expect_contains("K50 = CL * (1/VC)") %>%
expect_contains("CONC = A(5)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
})
test_that("1cmp linear, lagtime", {
m <- pk_model() +
pk_distribution_1cmp() +
pk_elimination_linear() +
pk_absorption_fo_lag() +
obs_additive(conc~C["central"])
render(m,
options = assemblerr_options(
ode.use_special_advans = TRUE,
ode.use_general_linear_advans = TRUE
)
) %>%
expect_contains(" ADVAN2 ") %>%
expect_contains(" TRANS2 ") %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("CL = THETA(2) * EXP(ETA(2))") %>%
expect_contains("MDT = THETA(3) * EXP(ETA(3))") %>%
expect_contains("MAT = THETA(4) * EXP(ETA(4))") %>%
expect_contains("ALAG1 = MDT") %>%
expect_contains("KA = 1/MAT") %>%
expect_contains("V = VC") %>%
expect_contains("CONC = A(2)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
})
test_that("1cmp, zo", {
m <- pk_model() +
pk_distribution_1cmp() +
pk_elimination_linear() +
pk_absorption_zo() +
obs_additive(conc~C["central"])
render(m,
options = assemblerr_options(
ode.use_special_advans = TRUE,
ode.use_general_linear_advans = TRUE
)
) %>%
expect_contains(" ADVAN1 ") %>%
expect_contains(" TRANS2 ") %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("CL = THETA(2) * EXP(ETA(2))") %>%
expect_contains("MAT = THETA(3) * EXP(ETA(3)") %>%
expect_contains("R1 = AMT/MAT/2") %>%
expect_contains("V = VC") %>%
expect_contains("CONC = A(1)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
})
test_that("1cmp, zo lag", {
m <- pk_model() +
pk_distribution_1cmp() +
pk_elimination_linear() +
pk_absorption_zo_lag() +
obs_additive(conc~C["central"])
render(m,
options = assemblerr_options(
ode.use_special_advans = TRUE,
ode.use_general_linear_advans = TRUE
)
) %>%
expect_contains(" ADVAN1 ") %>%
expect_contains(" TRANS2 ") %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("CL = THETA(2) * EXP(ETA(2))") %>%
expect_contains("MAT = THETA(3) * EXP(ETA(3)") %>%
expect_contains("R1 = AMT/MAT/2") %>%
expect_contains("V = VC") %>%
expect_contains("CONC = A(1)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
})
test_that("1cmp, fo zo", {
m <- pk_model() +
pk_distribution_1cmp() +
pk_elimination_linear() +
pk_absorption_fo_zo() +
obs_additive(conc~C["central"])
render(m,
options = assemblerr_options(
ode.use_special_advans = TRUE,
ode.use_general_linear_advans = TRUE
)
) %>%
expect_contains(" ADVAN2 ") %>%
expect_contains(" TRANS2 ") %>%
expect_contains("VC = THETA(1) * EXP(ETA(1))") %>%
expect_contains("CL = THETA(2) * EXP(ETA(2))") %>%
expect_contains("MAT = THETA(3) * EXP(ETA(3)") %>%
expect_contains("MDT = THETA(4) * EXP(ETA(4)") %>%
expect_contains("R1 = AMT/MDT/2") %>%
expect_contains("KA = 1/MAT") %>%
expect_contains("V = VC") %>%
expect_contains("CONC = A(2)/VC") %>%
expect_contains("Y = CONC + EPS(1)")
})
|
NULL
setGeneric (
name= "calcPriceDelta",
def=function(object,levels = FALSE, market = FALSE,...){standardGeneric("calcPriceDelta")}
)
setMethod(
f= "calcPriceDelta",
signature= "Antitrust",
definition=function(object, levels = FALSE, market = FALSE, index=c("paasche","laspeyres"), ... ){
index <- match.arg(index)
pricePre <- object@pricePre
pricePost <- object@pricePost
if(levels){priceDelta <- pricePost - pricePre}
else{priceDelta <- pricePost/pricePre - 1}
if(market){
sharesPre <- calcShares(object, preMerger=TRUE,revenue=FALSE,...)
sharesPre <- sharesPre/sum(sharesPre,na.rm=TRUE)
sharesPost <- calcShares(object, preMerger=FALSE,revenue=FALSE,...)
sharesPost <- sharesPost/sum(sharesPost,revenue=FALSE,na.rm=TRUE)
if(index=="paasche") priceDelta <- sum(sharesPost*pricePost)/sum(sharesPost*pricePre) - 1
else if (index=="laspeyres") priceDelta <- sum(sharesPre*pricePost)/sum(sharesPre*pricePre) - 1
}
return(priceDelta)
}
)
setMethod(
f= "calcPriceDelta",
signature= "Cournot",
definition=function(object, levels = FALSE, market=TRUE, ... ){
callNextMethod()
}
)
setMethod(
f= "calcPriceDelta",
signature= "VertBargBertLogit",
definition=function(object, levels = FALSE, market = FALSE, ... ){
up <- object@up
down <- object@down
marginsPre <- calcMargins(object,preMerger=TRUE,level=TRUE)
marginsPost <- calcMargins(object,preMerger=FALSE,level=TRUE)
sharesPre <- calcShares(object, preMerger=TRUE,revenue=FALSE)
sharesPost <- calcShares(object, preMerger=FALSE,revenue=FALSE)
upMCPre=up@mcPre
downMCPre=down@mcPre
upPricePre <- up@pricePre
upMCPost=up@mcPost
downMCPost=down@mcPost
upPricePost <- up@pricePost
if(!market){
mcDeltaUp <- upMCPost - upMCPre
mcDeltaDown <- (downMCPost+upPricePost) - (downMCPre + upPricePre)
mcDeltaUp <- ifelse(is.na(mcDeltaUp),0,mcDeltaUp)
mcDeltaDown <- ifelse(is.na(mcDeltaDown),0,mcDeltaDown)
upDelta <- marginsPost$up - marginsPre$up + mcDeltaUp
downDelta <- marginsPost$down - marginsPre$down + mcDeltaDown
upPricePre <- up@pricePre
downPricePre <- down@pricePre
}
else{
mcDeltaUp <- upMCPost *sharesPost - upMCPre*sharesPre
mcDeltaDown <- (downMCPost+upPricePost)*sharesPost - (downMCPre + upPricePre)*sharesPre
mcDeltaUp <- ifelse(is.na(mcDeltaUp),0,mcDeltaUp)
mcDeltaDown <- ifelse(is.na(mcDeltaDown),0,mcDeltaDown)
upDelta <- marginsPost$up*sharesPost - marginsPre$up*sharesPre + mcDeltaUp
downDelta <- marginsPost$down*sharesPost - marginsPre$down*sharesPre + mcDeltaDown
upPricePre <- up@pricePre*sharesPre
downPricePre <- down@pricePre*sharesPre
upDelta <- sum(upDelta,na.rm=TRUE)
downDelta <- sum(downDelta,na.rm=TRUE)
upPricePre <- sum(upPricePre,na.rm=TRUE)
downPricePre <- sum(downPricePre,na.rm=TRUE)
}
if(!levels){
upDelta <- upDelta/upPricePre
downDelta <- downDelta/downPricePre
}
priceDelta <- list(up = upDelta,
down= downDelta)
return(priceDelta)
}
)
setMethod(
f= "calcPriceDelta",
signature= "AIDS",
definition=function(object,isMax=FALSE,levels=FALSE,subset,market=FALSE, index=c("paasche","laspeyres"),...){
index <- match.arg(index)
if(market){
if(index=="paasche") shares <- calcShares(object, preMerger = FALSE)
else{shares <- calcShares(object, preMerger = TRUE)}
return(sum(object@priceDelta * shares,na.rm=TRUE))
}
ownerPost <- object@ownerPost
nprods <- length(object@shares)
if(missing(subset)){subset <- rep(TRUE,nprods)}
if(!is.logical(subset) || length(subset) != nprods ){stop("'subset' must be a logical vector the same length as 'shares'")}
FOC <- function(priceDelta){
object@priceDelta <- exp(priceDelta)-1
sharePost <- calcShares(object,FALSE)
elastPost <- t(elast(object,FALSE))
marginPost <- calcMargins(object,FALSE)
thisFOC <- sharePost*diag(ownerPost) + as.vector((elastPost*ownerPost) %*% (sharePost*marginPost))
thisFOC[!subset] <- sharePost[!subset]
return(thisFOC)
}
minResult <- BBsolve(object@priceStart,FOC,quiet=TRUE,[email protected])
if(minResult$convergence != 0){warning("'calcPrices' nonlinear solver may not have successfully converged. 'BBsolve' reports: '",minResult$message,"'")}
if(isMax){
hess <- genD(FOC,minResult$par)
hess <- hess$D[,1:hess$p]
if(any(eigen(hess)$values>0)){warning("Hessian of first-order conditions is not positive definite. Price vector may not maximize profits. Consider rerunning 'calcPrices' using different starting values")}
}
deltaPrice <- exp(minResult$par)-1
names(deltaPrice) <- object@labels
if(levels){deltaPrice <- calcPrices(object,FALSE) - calcPrices(object,TRUE)}
if(market){
sharePost <- calcShares(object,FALSE,...)
sharePost <- sharePost/sum(sharePost, na.rm=TRUE)
deltaPrice <- sum(deltaPrice*sharePost,na.rm=TRUE)
}
return(deltaPrice)
}
)
setMethod(
f= "calcPriceDelta",
signature= "Auction2ndLogit",
definition=function(object,levels=TRUE, market=FALSE,exAnte=ifelse(market,TRUE,FALSE),...){
if(!levels){
result <- callNextMethod()
return(result)
}
subset <- object@subset
mcDelta <- object@mcDelta
if(exAnte){
sharesPost <- calcShares(object, preMerger=FALSE)
mcDelta <- mcDelta*sharesPost
}
result <- calcMargins(object, preMerger=FALSE,exAnte=exAnte) + mcDelta -
calcMargins(object, preMerger=TRUE,exAnte=exAnte)
if(market) result <- sum(result,na.rm=TRUE)
if(!market) names(result) <- object@labels
return(result)
}
)
|
codename <- function(type = "any", seed) {
if (missing(seed)) {
set.seed(NULL)
} else {
if (is.numeric(seed))
{
set.seed(seed)
}
charseed <- char2seed(seed)
set.seed(charseed)
}
if (type == "any") {
all_adjs <- rbind(adjectives, xkcd_colors, wu_adjs)
all_adjs$value <- tolower(all_adjs$value)
my_adj <- sample(unique(all_adjs$value), 1)
gods$type <- NULL
all_nouns <- rbind(animals, gods, nouns, wu_nouns)
all_nouns$value <- tolower(all_nouns$value)
my_noun <- sample(unique(all_nouns$value), 1)
the_codename <- paste(my_adj, my_noun)
return(the_codename)
}
if (type == "gods") {
my_noun <- sample(gods$value, 1)
all_adjs <- rbind(adjectives, xkcd_colors)
my_adj <- sample(unique(all_adjs$value), 1)
the_codename <- paste(my_adj, my_noun)
return(the_codename)
}
if (type == "ubuntu") {
my_noun <- sample(animals$value, 1)
sw <- substring(my_noun, 1, 1)
all_adjs <- rbind(adjectives, xkcd_colors)
all_adjs <- subset(all_adjs, sapply(strsplit(all_adjs$value, " "), length) == 1)
matchingsw <- subset(all_adjs, tolower(substr(value, 1, 1)) == sw)
my_adj <- sample(matchingsw$value, 1)
the_codename <- paste(my_adj, my_noun)
return(the_codename)
}
if (type == "wu-tang") {
my_adj <- sample(wu_adjs$value, 1)
my_noun <- sample(wu_nouns$value, 1)
the_codename <- paste(my_adj, my_noun)
return(the_codename)
}
}
|
library(extraDistr)
library(ggplot2)
d_para <- data.frame(mu=c(0, 0), sigma=c(1, 3), gr=letters[1:2])
my_labs <- parse(text=sprintf('mu=="%.0f"~~sigma=="%.0f"', d_para$mu, d_para$sigma))
p <- ggplot(data.frame(X=c(-6, 6)), aes(x=X)) +
theme_bw(base_size=18) +
theme(legend.key.width=grid::unit(2.5,'line')) +
mapply(
function(mu, sigma, co) stat_function(fun=dlaplace, args=list(mu=mu, sigma=sigma), aes_q(linetype=co)),
d_para$mu, d_para$sigma, d_para$gr
) +
scale_linetype_manual('parameter', values=c('solid', '12'), labels=my_labs) +
labs(x='y', y='density') +
scale_x_continuous(limit=c(-6, 6))
ggsave(file='output/fig6-15.png', plot=p, dpi=300, w=6, h=3)
|
library(ggplot2)
library(treemapify)
G20
ggplot(G20, aes(area = gdp_mil_usd, fill = hdi)) +
geom_treemap()
ggplot(G20, aes(area = gdp_mil_usd, fill = hdi, label = country)) +
geom_treemap() +
geom_treemap_text(fontface = "italic", colour = "white", place = "centre",
grow = TRUE)
ggplot(G20, aes(area = gdp_mil_usd, fill = hdi, label = country,
subgroup = region)) +
geom_treemap() +
geom_treemap_subgroup_border() +
geom_treemap_subgroup_text(place = "centre", grow = T, alpha = 0.5, colour =
"black", fontface = "italic", min.size = 0) +
geom_treemap_text(colour = "white", place = "topleft", reflow = T)
ggplot(G20, aes(area = 1, label = country, subgroup = hemisphere,
subgroup2 = region, subgroup3 = econ_classification)) +
geom_treemap() +
geom_treemap_subgroup3_border(colour = "blue", size = 1) +
geom_treemap_subgroup2_border(colour = "white", size = 3) +
geom_treemap_subgroup_border(colour = "red", size = 5) +
geom_treemap_subgroup_text(
place = "middle",
colour = "red",
alpha = 0.5,
grow = T
) +
geom_treemap_subgroup2_text(
colour = "white",
alpha = 0.5,
fontface = "italic"
) +
geom_treemap_subgroup3_text(place = "top", colour = "blue", alpha = 0.5) +
geom_treemap_text(colour = "white", place = "middle", reflow = T)
|
[
{
"title": "BaselR meetup",
"href": "https://www.r-bloggers.com/baselr-meetup/"
},
{
"title": "Query a MySQL Database from R using RMySQL",
"href": "http://www.gettinggeneticsdone.com/2011/12/query-mysql-database-from-r-using.html"
},
{
"title": "Packrat on CRAN",
"href": "https://blog.rstudio.org/2014/09/05/packrat-on-cran/"
},
{
"title": "How to write and debug an R function",
"href": "http://rforpublichealth.blogspot.com/2014/06/how-to-write-and-debug-r-function.html"
},
{
"title": "Using iterators for sparse vectors and matrices",
"href": "http://gallery.rcpp.org/articles/sparse-iterators/"
},
{
"title": "Birth Month by Gender",
"href": "http://www.exegetic.biz/blog/2016/07/birth-month-by-gender/"
},
{
"title": "Putting a football model into JAGS",
"href": "http://wiekvoet.blogspot.com/2012/10/putting-football-model-into-jags.html"
},
{
"title": "Why [Not] Simulate?",
"href": "http://ww1.danielmarcelino.com/why-not-simulate/"
},
{
"title": "Revolution Newsletter: April 2013",
"href": "http://blog.revolutionanalytics.com/2013/04/revolution-newsletter-april-2013.html"
},
{
"title": "FII and DII turnover with effect on Nifty Downloader",
"href": "http://foss.gauravsmind.com/2011/08/download-fii-and-dii-turnover-with.html"
},
{
"title": "R Cookbook with examples",
"href": "https://rdatamining.wordpress.com/2011/10/27/r-cookbook-with-examples/"
},
{
"title": "Play 2048… using R!",
"href": "http://decisionsandr.blogspot.com/2014/04/play-2048-using-r.html"
},
{
"title": "correlation matrices on copulas",
"href": "https://xianblog.wordpress.com/2016/07/04/correlation-matrices-on-copulas/"
},
{
"title": "Risk, Return and Analyst Ratings",
"href": "https://systematicinvestor.wordpress.com/2011/10/08/risk-return-and-analyst-ratings/"
},
{
"title": "Introduction to R for Data Science :: Session 3",
"href": "http://www.exactness.net/post/144812605330/introduction-to-r-for-data-science-session-3"
},
{
"title": "Spirograph with R",
"href": "http://menugget.blogspot.com/2012/12/spirograph-with-r.html"
},
{
"title": "Artificial Intelligence: Solving the Chinese Room Argument",
"href": "https://feedproxy.google.com/~r/graphoftheweek/fzVA/~3/o-lMkg1nNV4/artificial-intelligence-solving-chinese.html"
},
{
"title": "New R User Group in Dublin, Ireland",
"href": "http://blog.revolutionanalytics.com/2011/10/new-r-user-group-in-dublin-ireland.html"
},
{
"title": "Some R User Group Highlights for November 2014",
"href": "http://blog.revolutionanalytics.com/2014/12/november-2014-r-user-group-roundup.html"
},
{
"title": "Comparing ESPN’s, CBS’s, and NFL.com’s Fantasy Football Projections using R",
"href": "http://fantasyfootballanalyticsr.blogspot.com/2013/03/comparing-espns-cbss-and-nflcoms.html"
},
{
"title": "Data from the World Health Organization API",
"href": "http://ellisp.github.io/blog/2016/02/06/world-health-organization"
},
{
"title": "The R-Files: Martyn Plummer",
"href": "http://blog.revolutionanalytics.com/2011/08/the-r-files-martyn-plummer.html"
},
{
"title": "R programming challenge: Escape the zombie horde",
"href": "http://blog.revolutionanalytics.com/2013/05/r-programming-challenge-escape-the-zombie-horde.html"
},
{
"title": "SCRIPT for NIR \"DEMO\" Tutorial – 001",
"href": "http://nir-quimiometria.blogspot.com/2012/03/script-for-nir-demo-tutorial-001.html"
},
{
"title": "An OpenBLAS-based Rblas for Windows 64: Step-by-step",
"href": "http://www.avrahamadler.com/2013/10/24/an-openblas-based-rblas-for-windows-64-step-by-step/"
},
{
"title": "Power and Sample Size Analysis: Z test",
"href": "http://www.milanor.net/blog/power-and-sample-size-analysis-z-test/"
},
{
"title": "This Is the Place, Apparently",
"href": "http://juliasilge.com/blog/This-Is-the-Place/"
},
{
"title": "The useR! 2016 Tutorials",
"href": "http://blog.revolutionanalytics.com/2016/06/the-user-2016-tutorials.html"
},
{
"title": "R/Finance 2009: Applied Finance with R",
"href": "https://feedproxy.google.com/~r/FossTrading/~3/smIn2-z7hv4/rfinance-2009-applied-finance-with-r.html"
},
{
"title": "Ideas on A Really Fast Statistics Journal",
"href": "http://yihui.name/en/2012/03/a-really-fast-statistics-journal/"
},
{
"title": "Stan 2.5, now with MATLAB, Julia, and ODEs",
"href": "http://andrewgelman.com/2014/10/22/stan-2-5-now-matlab-julia-odes/"
},
{
"title": "An epithet I can live with",
"href": "http://andrewgelman.com/2012/12/04/an-epithet-i-can-live-with/"
},
{
"title": "More Readable Code with Pipes in R",
"href": "http://www.econometricsbysimulation.com/2014/07/more-readable-code-with-pipes-in-r.html"
},
{
"title": "Tikz Nodes",
"href": "http://www.wekaleamstudios.co.uk/posts/tikz-nodes/"
},
{
"title": "scheduleR: a web interface to schedule .R & .Rmd scripts",
"href": "https://web.archive.org/web/http://fishyoperations.com/wp/scheduler-interface-schedule-r-rmd-scripts/"
},
{
"title": "KDD Cup 2015 winners announced",
"href": "http://blog.revolutionanalytics.com/2015/07/kdd-cup-2015-winners-announced.html"
},
{
"title": "Pareto plot party!",
"href": "https://4dpiecharts.com/2010/12/05/pareto-plot-party/"
},
{
"title": "Processing Data from a Statistica Worksheet Using R",
"href": "https://rforwork.info/2012/08/30/processing-statistica-data-using-r/"
},
{
"title": "NHL Statistics – Goals scored by age",
"href": "https://rocknrblog.wordpress.com/2011/06/26/nhl-goals-by-age/"
},
{
"title": "Upcoming R training by Hadley Wickham: SF Dec 3-4, DC Dec 10-11",
"href": "https://www.r-bloggers.com/upcoming-r-training-by-hadley-wickham-sf-dec-3-4-dc-dec-10-11/"
},
{
"title": "R, HDF5 Data and Lightning",
"href": "http://www.exegetic.biz/blog/2016/02/r-hdf5-and-lightning-data/"
},
{
"title": "R Helps With Employee Churn",
"href": "http://blog.revolutionanalytics.com/2014/04/r-helps-with-employee-churn.html"
},
{
"title": "Rblogger Posting Patterns Analyzed with R",
"href": "http://decisionsandr.blogspot.com/2014/04/rblogger-posting-patterns-analyzed-with.html"
},
{
"title": "R books are now showing up in the dollar bin. That’s a good…",
"href": "http://jeffreyhorner.tumblr.com/post/6286598693/r-books-are-now-showing-up-in-the-dollar-bin"
},
{
"title": "Does R have too many packages?",
"href": "http://www.econometricsbysimulation.com/2014/04/does-r-have-too-many-packages.html"
},
{
"title": "cpumemlog: Monitor CPU and RAM usage of a process (and its children)",
"href": "http://ggorjan.blogspot.com/2015/01/cpumemlog-monitor-cpu-and-ram-usage-of.html"
},
{
"title": "R script to manipulate health data",
"href": "https://web.archive.org/web/http://www.johnmarquess.com/?p=28"
},
{
"title": "htmltab: Next version and CRAN release",
"href": "http://www.r-datacollection.com/blog/htmltab-Next-version-and-CRAN-release/"
},
{
"title": "Le Monde puzzle [
"href": "https://xianblog.wordpress.com/2015/04/01/le-monde-puzzle-905/"
},
{
"title": "R’s continued growth in academia",
"href": "http://blog.revolutionanalytics.com/2012/04/rs-continued-growth-in-academia.html"
}
]
|
library(bayesplot)
context("PPC: misc. functions")
source(test_path("data-for-ppc-tests.R"))
expect_molten_yrep <- function(yrep) {
y <- rnorm(ncol(yrep))
yrep <- validate_yrep(yrep, y)
x <- melt_yrep(yrep)
expect_equal(ncol(x), 4)
expect_equal(nrow(x), prod(dim(yrep)))
rep_nums <- rep(seq_len(nrow(yrep)), length(y))
obs_nums <- sort(rep(seq_len(length(y)), nrow(yrep)))
expect_identical(colnames(x), c("y_id", "rep_id", "rep_label", "value"))
expect_equal(x$y_id, obs_nums)
expect_equal(x$rep_id, rep_nums)
expect_s3_class(x, "data.frame")
expect_s3_class(x$rep_label, "factor")
expect_type(x$rep_id, "integer")
expect_type(x$y_id, "integer")
expect_type(x$value, "double")
}
test_that("melt_yrep returns correct structure", {
expect_molten_yrep(yrep)
expect_molten_yrep(yrep2)
load(test_path("data-for-binomial.rda"))
expect_molten_yrep(Ey)
expect_molten_yrep(validate_yrep(yrep, y))
})
test_that("melt_and_stack returns correct structure", {
molten_yrep <- melt_yrep(yrep)
d <- melt_and_stack(y, yrep)
expect_s3_class(d, "data.frame")
expect_equal(nrow(d), nrow(molten_yrep) + length(y))
sorted_names <- sort(c(colnames(molten_yrep), c("is_y", "is_y_label")))
expect_equal(sort(colnames(d)), sorted_names)
})
d <- ppc_group_data(y, yrep, group)
d_stat <- ppc_group_data(y, yrep, group, stat = "mean")
test_that("ppc_group_data returns correct structure", {
expect_identical(colnames(d), c("group", "variable", "value"))
expect_s3_class(d, c("grouped_df", "tbl_df", "tbl", "data.frame"))
expect_identical(colnames(d_stat), colnames(d))
expect_s3_class(d, c("grouped_df", "tbl_df", "tbl", "data.frame"))
nr <- length(unique(d$variable)) * length(unique(group))
expect_equal(nrow(d_stat), nr)
})
test_that("ppc_group_data with stat returns correct values for y", {
for (lev in levels(group)) {
mean_y_group <- with(d_stat, value[group == lev & variable == "y"])
expect_equal(mean_y_group, mean(y[group == lev]),
info = paste("group =", lev))
}
})
test_that("ppc_group_data with stat returns correct values for yrep", {
for (lev in levels(group)) {
for (j in 1:nrow(yrep)) {
var <- paste0("yrep_", j)
mean_yrep_group <- with(d_stat, value[group == lev & variable == var])
expect_equal(mean_yrep_group, mean(yrep[j, group == lev]),
info = paste("group =", lev, "|", "rep =", j))
}
}
})
test_that("is_whole_number works correctly", {
expect_equal(is_whole_number(c(1L, 2, 3/3, 4/5)),
c(rep(TRUE, 3), FALSE))
expect_true(!is_whole_number("1"))
})
test_that("all_counts works correctly", {
expect_true(all_counts(1))
expect_true(all_counts(0:5))
expect_true(all_counts(matrix(rpois(10, 1), 2, 5)))
expect_false(all_counts(rnorm(5)))
expect_false(all_counts(c("1", "2")))
expect_false(all_counts(c(1, 1.5)))
expect_false(all_counts(c(-1, 2)))
})
|
nrow <- function(df,...) {
UseMethod("nrow")
}
nrow.default <- function(df, ...) {
base::nrow(df, ...)
}
nrow.disk.frame <- function(df, ...) {
stopifnot(is_ready(df))
path1 <- attr(df,"path", exact=TRUE)
if(dir.exists(path1)) {
path2 <- list.files(path1,full.names = TRUE)
if(length(path2) == 0) {
return(0)
}
tmpfstmeta = fst::fst.metadata(path2[1])
if("nrOfRows" %in% names(tmpfstmeta)) {
return(sum(sapply(path2, function(p2) fst::fst.metadata(p2)$nrOfRows)))
} else {
return(sum(sapply(path2, function(p2) fst::fst.metadata(p2)$NrOfRows)))
}
} else {
stop(glue::glue("nrow error: directory {} does not exist"))
}
}
ncol <- function(df) {
UseMethod("ncol")
}
ncol.disk.frame <- function(df) {
length(colnames(df))
}
ncol.default <- function(df) {
base::ncol(df)
}
|
source('../gsDesign_independent_code.R')
testthat::test_that(
desc = "Test: gridpoints validation,
source: gridpts function is borrowed from gsdmvn package",
code = {
bounds <- c(-100, 100)
sigma <- 1
mu <- 0
y <- gsDesign::normalGrid(r = 18, mu = 0, bounds = bounds, sigma = sigma)
x <- gridpts(r = 18, mu = mu, a = bounds[1], b = bounds[2])
gridpoints <- x$z * sigma
expect_equal(y$z, gridpoints)
})
testthat::test_that(
desc = "Test: gridpts() bounds",
code = {
bounds <- c(2, 1)
sigma <- 1
mu <- 0
y <- gsDesign::normalGrid(r = 6, mu = 0, bounds = bounds, sigma = sigma)
expect_error(gridpts(r = 6, mu = mu, a = bounds[1], b = bounds[2]))
}
)
testthat::test_that(desc = "Test: checking r out of range", code = {
bounds <- c(5, 10)
sigma <- 1
mu <- 0
expect_error(gsDesign::normalGrid(r = 0.5, mu = 0, bounds = bounds, sigma = sigma))
})
testthat::test_that(desc = "Test: checking sigma out of range", code = {
bounds <- c(1, 2)
sigma <- -0.000001
mu <- 0
expect_error(gsDesign::normalGrid(r = 10, mu = 0, bounds = bounds, sigma = sigma))
})
testthat::test_that(desc = "Test: checking gridpts() mu", code = {
bounds <- c(0, 0)
sigma <- 4
mu <- -1
y <- gsDesign::normalGrid(r = 80, mu = mu, bounds = bounds, sigma = sigma)
expect_error(gridpts(r = 80, mu = mu, a = bounds[1], b = bounds[2]))
})
testthat::test_that(desc = "Test: checking bounds length", code = {
bounds <- c(1)
sigma <- 4
mu <- -1
expect_error(gsDesign::normalGrid(r = 6, mu = mu, bounds = bounds, sigma = sigma))
})
|
.dfmix.x <- function(x, w, xTheta, ...)
{
n <- length(x)
f <- array(data = 0.0, dim = n, dimnames = NULL)
for (i in 1:length(w)) {
if (xTheta[[i]]$pdf == .rebmix$pdf[1]) {
fix <- dnorm(as.numeric(x), mean = as.numeric(xTheta[[i]]$theta1), sd = as.numeric(xTheta[[i]]$theta2), ...)
}
else
if (xTheta[[i]]$pdf == .rebmix$pdf[2]) {
fix <- dlnorm(as.numeric(x), meanlog = as.numeric(xTheta[[i]]$theta1), sdlog = as.numeric(xTheta[[i]]$theta2), ...)
}
else
if (xTheta[[i]]$pdf == .rebmix$pdf[3]) {
fix <- dweibull(as.numeric(x), scale = as.numeric(xTheta[[i]]$theta1), shape = as.numeric(xTheta[[i]]$theta2), ...)
}
else
if (xTheta[[i]]$pdf == .rebmix$pdf[4]) {
fix <- dbinom(as.integer(x), size = as.integer(xTheta[[i]]$theta1), prob = as.numeric(xTheta[[i]]$theta2), ...)
}
else
if (xTheta[[i]]$pdf == .rebmix$pdf[5]) {
fix <- dpois(as.integer(x), lambda = as.numeric(xTheta[[i]]$theta1), ...)
}
else
if (xTheta[[i]]$pdf == .rebmix$pdf[6]) {
fix <- ddirac(as.numeric(x), location = as.numeric(xTheta[[i]]$theta1))
}
else
if (xTheta[[i]]$pdf == .rebmix$pdf[7]) {
fix <- dgamma(as.numeric(x), scale = as.numeric(xTheta[[i]]$theta1), shape = as.numeric(xTheta[[i]]$theta2), ...)
}
else
if (xTheta[[i]]$pdf == .rebmix$pdf[8]) {
fix <- dunif(as.numeric(x), min = as.numeric(xTheta[[i]]$theta1), max = as.numeric(xTheta[[i]]$theta2), ...)
}
else
if (xTheta[[i]]$pdf == .rebmix$pdf[9]) {
output <- .C(C_RvonMisesPdf,
n = as.integer(n),
y = as.double(x),
Mean = as.double(xTheta[[i]]$theta1),
Kappa = as.double(xTheta[[i]]$theta2),
f = double(n),
PACKAGE = "rebmix")
fix <- output$f
}
else
if (xTheta[[i]]$pdf == .rebmix$pdf[10]) {
output <- .C(C_RGumbelPdf,
n = as.integer(n),
y = as.double(x),
Mean = as.double(xTheta[[i]]$theta1),
Sigma = as.double(xTheta[[i]]$theta2),
Xi = as.double(xTheta[[i]]$theta3),
f = double(n),
PACKAGE = "rebmix")
fix <- output$f
}
f <- f + w[i] * fix
}
rm(list = ls()[!(ls() %in% c("f"))])
return(f)
}
|
context("json_types")
test_that("works with simple input", {
json <- '[{"key":"value"}, [1, 2], "string", 1, true, false, null]'
expect_identical(
json %>% gather_array %>% json_types,
tbl_json(
data.frame(
document.id = rep(1L, 7),
array.index = 1L:7L,
type = factor(
c("object", "array", "string", "number", "logical", "logical",
"null"),
levels = allowed_json_types)
),
list(list(key = "value"), list(1L, 2L), "string", 1L, TRUE, FALSE, NULL)
)
)
}
)
test_that("works with varying array types", {
json <- '[[1, 2], [1, null], [{"key":"value"}], [null]]'
expect_identical(
(json %>% gather_array %>% json_types)$type,
factor(rep("array", 4), levels = allowed_json_types)
)
}
)
test_that("works with varying empty data", {
json <- '[[], {}, null]'
expect_identical(
(json %>% gather_array %>% json_types)$type,
factor(c("array", "object", "null"), levels = allowed_json_types)
)
}
)
test_that("works with character(0)", {
expect_identical(
(character(0) %>% json_types)$type,
factor(character(0), levels = allowed_json_types)
)
}
)
|
`groupLikelihoodCurves` <-
function(plotT, plotS, plotC, plotD, main=NULL, cex=0.7) {
plotT <- update(plotT, main=main, sub="d)", par.settings=list(par.ylab.text=list(cex=cex)))
plotC <- update(plotC, main=main, sub="c)",par.settings=list(par.zlab.text=list(cex=cex)))
plotD <- update(plotD, main=main, sub="a)",par.settings=list(par.zlab.text=list(cex=cex)))
plotS <- update(plotS, main=main, sub="b)",par.settings=list(par.zlab.text=list(cex=cex)))
plot(plotT, split=c(2,2,2,2), more=TRUE)
plot(plotC, split=c(2,1,2,2), more=TRUE)
plot(plotS, split=c(1,2,2,2), more=TRUE)
plot(plotD, split=c(1,1,2,2), more=FALSE)
}
|
print.dLR <-
function(x, ...){
cat("\n Call: \t Likelihood Ratio Test MPRM: dimension reduction \n\n")
cat("emp Chi2: \t", x$emp_Chi2, "\n")
cat("df: \t\t\t\t\t\t\t", x$df, "\n")
cat("p-value: \t\t", deparse(round(x$pval,3)), "\n\n")
}
|
tformshapes <- function(singletext=FALSE,transform=NA,jacobian=FALSE,driftdiag=FALSE, parname='param',stan=FALSE){
out = c('param',
'(log1p_exp(param))',
'(exp(param))',
'(1/(1+exp(-param)))',
'((param)^3)',
'log1p(param)',
'meanscale',
'1/(1+exp(-param))',
'exp(param)',
'1/(1+exp(-param))-(exp(param)^2)/(1+exp(param))^2',
'3*param^2',
'1/(1+param)')
tfvec=c(0:5,50:55)
out=gsub('param',parname,out,fixed=TRUE)
if(!is.na(transform)&&transform!=0) out = out[tfvec == transform]
if(!singletext) {
out = paste0('if(transform==', tfvec,') param = ',out,';\n',collapse='')
if(!stan) out <- paste0('param = parin * meanscale + inneroffset; \n ',out,'
param=param*multiplier;
if(transform < 49) param = param+offset;')
if(stan) out <- paste0('if(meanscale!=1.0) param *= meanscale;
if(inneroffset != 0.0) param += inneroffset; \n',out,'
if(multiplier != 1.0) param *=multiplier;
if(transform < 49 && offset != 0.0) param+=offset;')
}
if(singletext) out <- paste0('offset + multiplier*',gsub('param','(param*meanscale+inneroffset)',out))
out=gsub(' ','',out,fixed=TRUE)
return(out)
}
tform <- function(parin, transform, multiplier, meanscale, offset, inneroffset, extratforms='',singletext=FALSE,jacobian=FALSE,driftdiag=FALSE){
param=parin
if(!is.na(suppressWarnings(as.integer(transform)))) {
out <- tformshapes(singletext=singletext,transform=as.integer(transform))
if(!singletext) paste0(out,extratforms)
if(singletext) {
for(i in c('param','multiplier', 'meanscale', 'inneroffset','offset')){
irep = get(i)
out <- gsub(pattern = i,replacement = irep,out)
}
}
}
if(is.na(suppressWarnings(as.integer(transform)))) out <- transform
if(!singletext) out <- eval(parse(text=out))
return(out)
}
|
det <- function(x, ...)
{
z <- determinant(x, logarithm = TRUE, ...)
c(z$sign * exp(z$modulus))
}
determinant <- function(x, logarithm = TRUE, ...) UseMethod("determinant")
determinant.matrix <- function(x, logarithm = TRUE, ...)
{
if ((n <- ncol(x)) != nrow(x))
stop("'x' must be a square matrix")
if (n < 1L)
return(structure(list(modulus =
structure(if(logarithm) 0 else 1,
logarithm = logarithm),
sign = 1L),
class = "det"))
if (is.complex(x))
stop("'determinant' not currently defined for complex matrices")
.Internal(det_ge_real(x, logarithm))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.