code
stringlengths 1
13.8M
|
---|
ELEFAN_GA <- function(lfq,
seasonalised = FALSE,
low_par = NULL,
up_par = NULL,
popSize = 50,
maxiter = 100,
run = maxiter,
parallel = FALSE,
pmutation = 0.1,
pcrossover = 0.8,
elitism = base::max(1, round(popSize*0.05)),
MA = 5,
addl.sqrt = FALSE,
agemax = NULL,
flagging.out = TRUE,
seed = NULL,
monitor = FALSE,
plot = FALSE,
plot.score = TRUE, ...){
classes <- lfq$midLengths
n_classes <- length(classes)
Linf_est <- classes[n_classes]
low_par_ALL <- list(Linf = Linf_est * 0.5,
K = 0.01,
t_anchor = 0,
C = 0,
ts = 0)
low_Linf <- ifelse("Linf" %in% names(low_par),
get("Linf", low_par),
get("Linf", low_par_ALL))
low_K <- ifelse("K" %in% names(low_par),
get("K", low_par),
get("K", low_par_ALL))
low_tanc <- ifelse("t_anchor" %in% names(low_par),
get("t_anchor", low_par),
get("t_anchor", low_par_ALL))
low_C <- ifelse("C" %in% names(low_par),
get("C", low_par),
get("C", low_par_ALL))
low_ts <- ifelse("ts" %in% names(low_par),
get("ts", low_par),
get("ts", low_par_ALL))
up_par_ALL <- list(Linf = Linf_est * 1.5,
K = 1,
t_anchor = 1,
C = 1,
ts = 1)
up_Linf <- ifelse("Linf" %in% names(up_par),
get("Linf", up_par),
get("Linf", up_par_ALL))
up_K <- ifelse("K" %in% names(up_par),
get("K", up_par),
get("K", up_par_ALL))
up_tanc <- ifelse("t_anchor" %in% names(up_par),
get("t_anchor", up_par),
get("t_anchor", up_par_ALL))
up_C <- ifelse("C" %in% names(up_par),
get("C", up_par),
get("C", up_par_ALL))
up_ts <- ifelse("ts" %in% names(up_par),
get("ts", up_par),
get("ts", up_par_ALL))
lfq <- lfqRestructure(lfq, MA = MA, addl.sqrt = addl.sqrt)
sofun <- function(lfq, par, agemax, flagging.out){
Lt <- lfqFitCurves(lfq,
par=list(Linf=par[1], K=par[2], t_anchor=par[3], C=par[4], ts=par[5]),
agemax = agemax, flagging.out = flagging.out)
return(Lt$fESP)
}
fun <- function(lfq, par, agemax, flagging.out){
Lt <- lfqFitCurves(lfq,
par=list(Linf=par[1], K=par[2], t_anchor=par[3], C = 0, ts = 0),
agemax = agemax, flagging.out = flagging.out)
return(Lt$fESP)
}
if(seasonalised){
min = c(low_Linf, low_K, low_tanc, low_C, low_ts)
max = c(up_Linf, up_K, up_tanc, up_C, up_ts)
writeLines("Genetic algorithm is running. This might take some time.")
flush.console()
fit <- GA::ga(type = "real-valued",
fitness = sofun, lfq=lfq,
lower = min,
upper = max,
agemax = agemax,
flagging.out = flagging.out,
popSize = popSize, maxiter = maxiter, run = run, parallel = parallel,
pmutation = pmutation, pcrossover = pcrossover, elitism = elitism,
seed = seed, monitor = monitor,
...)
pars <- as.list(fit@solution[1,])
names(pars) <- c("Linf", "K", "t_anchor", "C", "ts")
}else{
min = c(low_Linf, low_K, low_tanc)
max = c(up_Linf, up_K, up_tanc)
writeLines("Genetic algorithm is running. This might take some time.")
flush.console()
fit <- GA::ga(
type = "real-valued",
fitness = fun,
lfq=lfq,
lower = min,
upper = max,
agemax = agemax,
flagging.out = flagging.out,
popSize = popSize, maxiter = maxiter, run = run, parallel = parallel,
pmutation = pmutation, pcrossover = pcrossover, elitism = elitism,
seed = seed,
monitor = monitor,
...
)
pars <- as.list(fit@solution[1,])
names(pars) <- c("Linf", "K", "t_anchor")
}
if(plot.score){
GA::plot(fit)
}
final_res <- lfqFitCurves(
lfq = lfq, par=pars,
flagging.out = flagging.out,
agemax = agemax)
phiL <- log10(pars$K) + 2 * log10(pars$Linf)
pars$phiL <- phiL
lfq$ncohort <- final_res$ncohort
lfq$agemax <- final_res$agemax
lfq$par <- pars
lfq$fESP <- fit@fitnessValue
lfq$Rn_max <- fit@fitnessValue
if(plot){
plot(lfq, Fname = "rcounts")
Lt <- lfqFitCurves(lfq, par = lfq$pars, draw=TRUE)
}
return(lfq)
} |
NULL
osf_tbl <- function(x = NULL, subclass = NULL) {
if (is.list(x) && rlang::is_empty(x)) x <- NULL
x <- x %||% tibble::tibble(
name = character(),
id = character(),
meta = list()
)
new_osf_tbl(x, subclass)
}
new_osf_tbl <- function(x, subclass = NULL) {
stopifnot(inherits(x, "data.frame"))
tibble::new_tibble(x, nrow = nrow(x), subclass = c(subclass, "osf_tbl"))
}
as_osf_tbl <- function(x, subclass = NULL) UseMethod("as_osf_tbl")
as_osf_tbl.default <- function(x, subclass = NULL)
abort("No methods available to coerce this object into an osf_tbl")
as_osf_tbl.data.frame <- function(x, subclass = NULL) new_osf_tbl(x, subclass)
as_osf_tbl.list <- function(x, subclass = NULL) {
if (rlang::is_empty(x)) return(osf_tbl(subclass = subclass))
x <- unname(x)
name_field <- switch(subclass,
osf_tbl_node = "title",
osf_tbl_file = "name",
osf_tbl_user = "full_name"
)
vars <- purrr::map(x, ~ list(
name = .x$attributes[[name_field]],
id = .x$id,
meta = .x[c("attributes", "links", "relationships")]
))
out <- tibble::new_tibble(purrr::transpose(vars), nrow = length(vars))
out$id <- as.character(out$id)
out$name <- as.character(out$name)
if (subclass == "osf_tbl_node") out$name <- html_decode(out$name)
new_osf_tbl(out, subclass)
}
rebuild_osf_tbl <- function(x) {
if (is_valid_osf_tbl(x)) {
if (nrow(x) == 0) return(x)
subclass <- sprintf("osf_tbl_%s", determine_entity_type(x$meta[[1]]))
return(as_osf_tbl(x, subclass = subclass))
} else {
tibble::new_tibble(x, nrow = nrow(x))
}
} |
Mammen <-
function(n)
{
p <- (sqrt(5)+1)/(2*sqrt(5))
zmat <- rep(1,n)*(-(sqrt(5)-1)/2);
u <- runif(n,0,1)
zmat[u > p] <- (sqrt(5)+1)/2
return(zmat)
} |
PBIR1=function(t2PROGRESSION, STATUS_PROGRESSION, t2RESPONSE, STATUS_RESPONSE, time=NULL, alpha=0.95){
t2RESPONSE[STATUS_RESPONSE==0]=Inf
y1=pmin(t2PROGRESSION, t2RESPONSE)
d1=1*(STATUS_RESPONSE+STATUS_PROGRESSION>0)
y2=t2PROGRESSION
d2=STATUS_PROGRESSION
fit1=survfit(Surv(y1, d1)~1)
n1=length(fit1$time)
fit2=survfit(Surv(y2, d2)~1)
n2=length(fit2$time)
tau.grd=sort(unique(c(y1, y2)))
if(min(d1[y1==max(y1)])==0) taumax=min(max(y1), max(y2))
if(min(d1[y1==max(y1)])==1) taumax=max(y2)
tau.grd=c(tau.grd[tau.grd<taumax], taumax)
m.tau.grd=length(tau.grd)
n=length(t2PROGRESSION)
surv1.tot=surv2.tot=rep(NA, m.tau.grd)
atrisk1.tot=atrisk2.tot=rep(NA, m.tau.grd)
hazard1.tot=hazard2.tot=rep(NA, m.tau.grd)
for(i in 1:m.tau.grd)
{t0=tau.grd[i]
if(t0>=max(y1)) t0new=max(y1)
if(t0<=max(y1)) t0new=t0
id1=max((1:(n1+1))[c(0, fit1$time)<=t0new])
id2=max((1:(n2+1))[c(0, fit2$time)<=t0])
surv1.tot[i]=c(1, fit1$surv)[id1]
surv2.tot[i]=c(1, fit2$surv)[id2]
atrisk1.tot[i]=sum(y1>=t0new)
atrisk2.tot[i]=sum(y2>=t0)
hazard1.tot[i]=sum((y1==t0new)*d1)/sum(y1>=t0new)
hazard2.tot[i]=sum((y2==t0)*d2)/sum(y2>=t0)
}
dsurv.tot=surv2.tot-surv1.tot
dsd.tot=rep(NA, m.tau.grd)
for(i in 1:m.tau.grd)
{t0=tau.grd[i]
if(t0>max(y1)) t0new=max(y1)
if(t0<=max(y1)) t0new=t0
tau1=tau2=rep(0, n)
for(j in 1:n)
tau1[j]=(y1[j]<=t0new)*d1[j]/sum(y1>=y1[j])-sum((hazard1.tot/atrisk1.tot)[tau.grd<=min(t0new,y1[j])])
for(j in 1:n)
tau2[j]=(y2[j]<=t0)*d2[j]/sum(y2>=y2[j])-sum((hazard2.tot/atrisk2.tot)[tau.grd<=min(t0,y2[j])])
tau1=surv1.tot[i]*tau1
tau2=surv2.tot[i]*tau2
dsd.tot[i]=sqrt(sum((tau1-tau2)^2))
}
logd.tot=log(dsurv.tot/(1-dsurv.tot))
logsd.tot=dsd.tot/(dsurv.tot*(1-dsurv.tot))
cilogd=cbind(logd.tot-qnorm((1+alpha)/2)*logsd.tot, logd.tot+qnorm((1+alpha)/2)*logsd.tot)
cid=exp(cilogd)/(1+exp(cilogd))
cid[dsurv.tot==0,]=0
cid[dsurv.tot==1,]=1
ci1=cid[,1]
ci2=cid[,2]
if(length(time)>0)
{if(max(time)>taumax)
{message("The PBIR is not identifiable at some selected time points,
which are replaced by the maximum time point, where it is identifiable.")
time=time[time<taumax]
time=c(time, taumax)
}
dsurv.tot=approx(x=tau.grd, y=dsurv.tot, xout=time, method="constant", yleft=0, yright=0)$y
dsd.tot=approx(x=tau.grd, y=dsd.tot, xout=time, method="constant", yleft=0, yright=0)$y
ci1=approx(x=tau.grd, y=ci1, xout=time, method="constant", yleft=0, yright=0)$y
ci2=approx(x=tau.grd, y=ci2, xout=time, method="constant", yleft=0, yright=0)$y
tau.grd=time
}
res.tot=cbind(tau.grd, dsurv.tot, dsd.tot, ci1, ci2)
colnames(res.tot)=c("time", "PBIR", "std", "ci-low", "ci-up")
res.tot=data.frame(res.tot)
return(res.tot)
} |
promethee123<- function(alternatives, criteria, decision_matrix, min_max, normalization_function,
q_indifference, p_preference, s_curve_change, criteria_weights){
n_alt <- length(alternatives)
n_crit <- length(criteria)
differences <- c()
for (j in 1:n_crit) {
for (i in 1:n_alt) {
for (h in 1:n_alt) {
if (min_max[j] == "max") {
value <- (decision_matrix[j,i] - decision_matrix[j,h])
}
if (min_max[j] == "min") {
value <- (decision_matrix[j,h] - decision_matrix[j,i])
}
differences <- append(differences, value)
}
}
}
normalized <- c()
x <- 1
y <- (n_alt^2)
for (j in 1:n_crit) {
for (i in x:y) {
if (normalization_function[j] == 1){
value <- differences[i]
if (value <= 0){
degree <- 0
}else{
degree <- 1
}
}
if (normalization_function[j] == 2){
value <- differences[i]
if (value <= q_indifference[j]){
degree <- 0
}else{
degree <- 1
}
}
if (normalization_function[j] == 3){
value <- differences[i]
if (value <= 0){
degree <- 0
}
if (value > 0 && value < p_preference[j]){
degree <- value/p_preference[j]
}
if (value > p_preference[j]){
degree <- 1
}
}
if (normalization_function[j] == 4){
value <- differences[i]
if (value <= q_indifference[j]){
degree <- 0
}
if (value > q_indifference[j] && value < p_preference[j]){
degree <- 0.5
}
if (value > p_preference[j]){
degree <- 1
}
}
if (normalization_function[j] == 5){
value <- differences[i]
if (value <= q_indifference[j]){
degree <- 0
}
if (value > q_indifference[j] && value < p_preference[j]){
degree <- ((value - q_indifference[j]) / (p_preference[j] - q_indifference[j]))
}
if (value >= p_preference[j]){
degree <- 1
}
}
if (normalization_function[j] == 6){
value <- differences[i]
if (value <= 0){
degree <- 0
}else{
degree <- round((1 - (exp(1) ** ((-((x)**2))/(2*(s_curve_change[j] ** 2))))), 3)
}
}
normalized <- append(normalized, degree)
}
x <- (y+1)
y <- (y+(n_alt^2))
}
weighted <- c()
x <- 1
y <- (n_alt^2)
for (j in 1:n_crit) {
for (i in x:y) {
value <- normalized[i]*criteria_weights[j]
weighted <- append(weighted, value)
}
x <- (y+1)
y <- (y+(n_alt^2))
}
print('')
print("========== Alternative Performances in Each Criterion ==========")
print('')
x <- 1
y <- (n_alt^2)
for (j in 1:n_crit) {
weighted_crit <- weighted[x:y]
matrix_weighted <- matrix(weighted_crit, nrow = n_alt, ncol = n_alt, byrow = TRUE)
rownames(matrix_weighted) <- alternatives
colnames(matrix_weighted) <- alternatives
print('')
print(paste( 'Weighted Matrix relative to criterion', criteria[j] ))
print(matrix_weighted)
x <- (y+1)
y <- (y+(n_alt^2))
}
global_index <- c()
for (i in 1:(n_alt^2)) {
value_sum <- 0
for (h in 1:n_crit) {
value <- weighted[((n_alt^2)*(h-1))+i]
value_sum <- value_sum + value
}
value_index <- round(value_sum/n_crit, 4)
global_index <- append(global_index, value_index)
}
matrix_global_index <- matrix(global_index, nrow = n_alt, ncol = n_alt, byrow = TRUE)
colnames(matrix_global_index) <- alternatives
rownames(matrix_global_index) <- alternatives
print("==================== Global Index of Preference ====================")
print('')
print(matrix_global_index)
print('')
positive_flows <- c()
for (i in 1:n_alt) {
pos_flow <- 0
for (h in 1:n_alt) {
value <- global_index[((n_alt*(i-1))+h)]
pos_flow <- pos_flow + value
}
positive_flows <- append(positive_flows, pos_flow)
}
negative_flows <- c()
for (i in 1:n_alt) {
neg_flow <- 0
for (h in 1:n_alt) {
value <- global_index[((n_alt*(h-1))+i)]
neg_flow <- neg_flow + value
}
negative_flows <- append(negative_flows, neg_flow)
}
net_flows <- c()
for (i in 1:n_alt) {
value <- positive_flows[i] - negative_flows[i]
net_flows <- append(net_flows, value)
}
Flows <- data.frame(alternatives, positive_flows, negative_flows, net_flows)
print('')
print("==================== Outranking Flows ====================")
print('')
print(Flows)
print('')
print('')
print("==================== PROMETHEE I ====================")
print('')
for (i in 1:n_alt) {
print(paste('Partial Prefernce Relation of ', alternatives[i], ":"))
print("")
for (h in 1:n_alt) {
if (i != h){
if ((positive_flows[i] > positive_flows[h]) && (negative_flows[i] < negative_flows[h])){
print(paste(alternatives[i], " is preferable to ", alternatives[h]))
}
else if ((positive_flows[i] == positive_flows[h]) && (negative_flows[i] < negative_flows[h])){
print(paste(alternatives[i], " is preferable to ", alternatives[h]))
}
else if ((positive_flows[i] > positive_flows[h]) && (negative_flows[i] == negative_flows[h])){
print(paste(alternatives[i], " is preferable to ", alternatives[h]))
}
else if ((positive_flows[i] == positive_flows[h]) && (negative_flows[i] == negative_flows[h])){
print(paste(alternatives[i], " is indifferent to ", alternatives[h]))
}
else if ((positive_flows[i] < positive_flows[h]) && (negative_flows[i] < negative_flows[h])){
print(paste(alternatives[i], " is incompatible to ", alternatives[h]))
}
else if ((positive_flows[i] > positive_flows[h]) && (negative_flows[i] > negative_flows[h])){
print(paste(alternatives[i], " is incompatible to ", alternatives[h]))
}
else {
print(paste(alternatives[i], " is not preferable to ", alternatives[h]))
}
}
}
print("")
}
print('')
print("==================== PROMETHEE II ====================")
ordering <- sort(net_flows, decreasing = TRUE)
for(i in 1:n_alt){
print(paste(alternatives[match(ordering[i],net_flows)],'=',ordering[i]))
}
print('')
print("==================== PROMETHEE III ====================")
print('')
stand_error <- round((sd(net_flows)/sqrt(n_alt)), 3)
stand_error
x_limit <- c()
y_limit <- c()
for (i in 1:n_alt) {
x <- round((net_flows[i] - stand_error), 3)
y <- round((net_flows[i] + stand_error), 3)
x_limit <- append(x_limit, x)
y_limit <- append(y_limit, y)
}
for (i in 1:n_alt) {
print(paste('Prefernce Relations of ', alternatives[i], ":"))
print("")
for (h in 1:n_alt) {
if (i != h){
if (x_limit[i] > y_limit[h]){
print(paste(alternatives[i], " is preferable to ", alternatives[h]))
}
else if ((x_limit[i] <= y_limit[h]) && (x_limit[h] <= y_limit[i])){
print(paste(alternatives[i], " is indifferent to ", alternatives[h]))
}
else {
print(paste(alternatives[i], " is not preferable to ", alternatives[h]))
}
}
}
print("")
}
requireNamespace("ggplot2")
requireNamespace("cowplot")
coresAll <- c('blue', 'green', 'goldenrod', 'red', 'purple', 'chocolate', 'sienna',
'gold', 'olivedrab', 'royalblue', 'mediumpurple', 'grey', 'maroon',
'coral', 'yellowgreen', 'slategrey', 'darkviolet', 'pink',
'springgreen', 'aqua', 'salmon', 'darkseagreen', 'steelblue', 'linen',
'indigo', 'tomato', 'khaki', 'magenta', 'lightcoral', 'yellow','black')
cores <- coresAll[1:n_alt]
scale <- c()
scale <- append(scale, negative_flows)
scale <- append(scale, positive_flows)
min <- (min(scale) - 0.1)
max <- (max(scale) + 0.1)
f_neg <- negative_flows
f_pos <- positive_flows
lista_fluxo_liquido <- net_flows
flux_inf <- x_limit
flux_sup <- y_limit
alt <- alternatives
df <- data.frame("y" = f_neg,"y_end"=f_pos, "x"=flux_inf, "x_end"=flux_sup, "liq"=lista_fluxo_liquido, "colors"=cores, "alt"=alt)
partial = ggplot(df,aes(colour = alt))
partial <- partial + geom_segment(aes(x=1, y = min, xend=1, yend=max), color="black") +
geom_segment(aes(x=2, y = min, xend=2, yend=max), color="black")
for(i in 1:n_alt){
partial <- partial + geom_segment(aes(x=1, y=f_neg, xend=2, yend=f_pos), size = 1) +
geom_point(aes(x=1, y = f_neg), size=1.8 ) + geom_point(aes (x=2, y = f_pos), size=1.8) +
scale_colour_manual(values = cores)
}
partial <- partial +
labs(color = "Alternatives") +
ggtitle("PROMETHEE I") +
theme(axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank())
bot <- (min(ordering)-0.1)
top <- (max(ordering)+0.1)
total = ggplot(df,aes(colour = alt))
total <- total + geom_segment(aes(x=1, y = bot, xend=1, yend=top), color="black")
for(i in 1:n_alt){
total <- total + geom_point(aes(x=1, y = lista_fluxo_liquido), size=2.2) +
scale_colour_manual(values = cores)
}
total <- total +
labs(color = "Alternatives") +
ggtitle("PROMETHEE II") +
theme(axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank())
inf <- (min(flux_inf)-0.1)
sup <- (max(flux_sup)+0.1)
intervals = ggplot(df,aes(fill = alt))
intervals <- intervals + geom_segment(aes(x=inf, y = 1, xend=sup, yend=1), color="black")
for(i in 1:n_alt){
intervals <- intervals + geom_point(aes(x=flux_inf, y = 1),shape=25,colour = "transparent", size =2.5) +
geom_point(aes(x=flux_sup, y = 1),shape=24, colour = "transparent", size =2.5) +
scale_fill_manual(values = cores)
}
intervals <- intervals +
labs(fill = "Alternatives") +
ggtitle("PROMETHEE III") +
theme(axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank())
ggdraw() +
draw_plot(partial, x = 0, y = .5, width = .5, height = .5) +
draw_plot(total, x = .5, y = .5, width = .5, height = .5) +
draw_plot(intervals, x = 0, y = 0, width = 1, height = 0.5)
} |
test_that("Can use add_rank_list", {
z <- add_rank_list(text = "missing", labels = NULL, input_id = NULL)
expect_s3_class(z, "add_rank_list")
})
test_that("Can create bucket_list", {
z <- bucket_list(
header = "This is a bucket list. You can drag items between the lists.",
add_rank_list(
text = "Drag from here",
labels = c("a", "bb", "ccc")
),
add_rank_list(
text = "to here",
labels = NULL,
input_id = "input_to"
)
)
expect_s3_class(z, "bucket_list")
expect_error(
bucket_list(
add_rank_list(
text = "Drag from here",
labels = c("a", "bb", "ccc")
),
add_rank_list(
text = "to here",
labels = NULL
)
),
"must be NULL or a string"
)
z <- bucket_list(
header = NA,
add_rank_list(
text = "Drag from here",
labels = c("a", "bb", "ccc")
),
add_rank_list(
text = "to here",
labels = NULL
)
)
expect_s3_class(z, "bucket_list")
}) |
SemiparChangePoint<-function(x, alternative = c("one.change", "epidemic"),
adj.Wn = FALSE, tol=1.0e-7, maxit=50,trace=FALSE,... )
{
nc<-0; n<-0
alternative <- match.arg(alternative)
ifelse(alternative == "epidemic", nc<-2, nc<-1)
alpha.hat<-0;
if(!is.matrix(x)) x<-as.matrix(x)
if(is.matrix(x)){
n<-nrow(x)
r<-ncol(x)
}
if(is.vector(x)){
n<-length(x); r<-1
x<-matrix(x,n,1)
}
if(nc ==1 ){
ll<-NULL
ll[1]<--n*log(n); ll[n+1]<-ll[1]
}
else{
ll<-matrix(0,n+1,n+1)
ll[1,n+1]<--n*log(n)
for(i in 1:(n+1)){
ll[i,i]<--n*log(n);
}
}
Beta<-NULL; z0<-NULL
beta.hat<-NULL
BETA<-NULL
lik.temp<--n*log(n); k.hat<-n; m.hat<-n
Vn<-0; Wn<-0; it<-0
Sn<-0; ind<-NULL; cnt<-0
for(k in (nc == 1):(n-1)){
for(m in ((nc == 1)*n + (nc == 2)*(k+1)):(n-(k == 0))){
it<-it+1
k1<-k+1; m1<-m+1; nm<-n-m
mk<-m-k;
if(k > 0) z0[1:k]<-rep(0,k)
if(m < n) z0[m1:n]<-rep(0, nm)
z0[k1:m]<-rep(1, mk)
z.glm<-glm(formula = z0 ~ x, family = binomial, control = glm.control(tol, maxit, trace))
Beta<-coef(z.glm)
rho<-(k+nm)/mk
ALPHA<-Beta[1]+log(rho); BETA<-as.vector(Beta[2:(r+1)])
temp1<-sum(log(mk*exp(ALPHA+x%*%BETA)+(k+nm)))
temp2<-sum(ALPHA+as.matrix(x[k1:m,])%*%BETA)
if(nc ==1){
ll[k+1]<--temp1+temp2;
if(ll[k+1]==-Inf){
cnt<-cnt+1
ind[cnt]=k+1
}
if((ll[k+1]>lik.temp)||(ll[k+1]>=lik.temp && k<k.hat)){
lik.temp<-ll[k+1]
k.hat<-k
alpha.hat<-ALPHA
beta.hat<-Beta[2:(r+1)]
}
}
else{
ll[k+1,m+1]<--temp1+temp2; ll[m+1,k+1]<-ll[k+1,m+1]
if((ll[k+1,m+1]>lik.temp)||(ll[k+1,m+1]>=lik.temp && m-k>m.hat-k.hat)){
lik.temp<-ll[k+1,m+1]
k.hat<-k; m.hat<-m;
alpha.hat<-ALPHA
beta.hat<-Beta[2:(r+1)]
}
Lambda<-(ll[k+1,m+1]-ll[1,1])
Vn<-Vn+2*(6*(n-m+k)*(m-k)-1)*Lambda/(3*n^4)
if(Lambda==-Inf) Lambda<-0
ctemp<-max((m-k)*(n-m+k)*Lambda,(m+1-k)*(n-m+k-1)*Lambda,(m-k-1)*(n-m+k+1)*Lambda)
if(Wn<2*ctemp/(n*n)){
Wn<-2*ctemp/(n*n)
}
}
}
}
if(nc==1){
Sn<-2*(lik.temp-ll[1])
if(cnt>0) ll<-replace(ll,ind,rep(min(ll[ll!=-Inf]),cnt))
return (list(k.hat = k.hat, ll = ll, Sn = Sn, alpha.hat = alpha.hat, beta.hat = beta.hat))
}
if(nc==2) {
Sn<-2*(lik.temp-ll[1,n+1])
if(adj.Wn && r == 1) Wn <- Wn*(1+0.155/sqrt(n)+0.24/n)
list(k.hat = k.hat, m.hat = m.hat, ll = ll, Sn = Sn, Vn = Vn, Wn = Wn, alpha.hat = alpha.hat, beta.hat = beta.hat)
}
} |
library(knitr)
opts_chunk$set(fig.width = 12)
library(DCLEAR)
library(phangorn)
library(tidyverse)
library(ape)
m = 30
acell = as.integer(rep(1,m))
mu_d = 0.1
d = 3
n_s = 5
p_d = 0.05
nmstrings = c( '0', '-', LETTERS[1:n_s] )
sim_tree = list()
sim_tree[[1]] = acell
k = 2
while(k < 2^d) {
mother_cell = sim_tree[[k%/%2]]
mu_loc = runif(m) < mu_d
mutation_cites = (mother_cell == 1) & mu_loc
n_mut = sum(mutation_cites)
if (n_mut > 0) {
mother_cell[mutation_cites] = as.integer(sample(n_s, n_mut, replace = T)+2)
}
dropout_cites = runif(m) < p_d
if (sum(dropout_cites) > 2 ) {
dropout_between = sample(which(dropout_cites), 2 )
mother_cell[dropout_between[1]:dropout_between[2]] = as.integer(2)
}
sim_tree[[k]] = mother_cell
k = k+1
}
1:7 %>% map(~paste(nmstrings[sim_tree[[.]]], collapse=""))
set.seed(1)
mu_d1 = c( 30, 20, 10, 5, 5, 1, 0.01, 0.001)
mu_d1 = mu_d1/sum(mu_d1)
simn = 100
m = 200
mu_d = 0.03
d = 12
p_d = 0.005
sD = sim_seqdata(sim_n = simn, m = m, mu_d = mu_d, d = d, n_s = length(mu_d1), outcome_prob = mu_d1, p_d = p_d )
sD$seqs
class(sD$tree)
distH = dist.hamming(sD$seqs)
TreeNJ = NJ(distH)
TreeFM = fastme.ols(distH)
print( RF.dist(TreeNJ, sD$tree, normalize = TRUE) )
print( RF.dist(TreeFM, sD$tree, normalize = TRUE) )
InfoW = -log(mu_d1)
InfoW[1:2] = 1
InfoW[3:7] = 4.5
dist_wh1 = WH(sD$seqs, InfoW)
TreeNJ_wh1 = NJ(dist_wh1)
TreeFM_wh1 = fastme.ols(dist_wh1)
print( RF.dist(TreeNJ_wh1, sD$tree, normalize = TRUE) )
print( RF.dist(TreeFM_wh1, sD$tree, normalize = TRUE) )
InfoW = -log(mu_d1)
InfoW[1] = 1
InfoW[2] = 12
InfoW[3:7] = 3
dist_wh2 = WH(sD$seqs, InfoW, dropout=TRUE)
TreeNJ_wh2 = NJ(dist_wh2)
TreeFM_wh2 = fastme.ols(dist_wh2)
print( RF.dist(TreeNJ_wh2, sD$tree, normalize = TRUE) )
print( RF.dist(TreeFM_wh2, sD$tree, normalize = TRUE) ) |
library(tinytest)
library(tiledb)
isOldWindows <- Sys.info()[["sysname"]] == "Windows" && grepl('Windows Server 2008', osVersion)
if (isOldWindows) exit_file("skip this file on old Windows releases")
ctx <- tiledb_ctx(limitTileDBCores())
dim <- tiledb_dim("foo", c(1, 100))
expect_true(is(dim, "tiledb_dim"))
expect_error(tiledb_dim("foo"))
expect_error(tiledb_dim("foo", c(100L, 1L), type = "INT32"))
expect_error(tiledb_dim("foo", c(1, 100), type = "INVALID"))
dim <- tiledb_dim("foo", c(1, 100))
expect_equal(tiledb::datatype(dim), "FLOAT64")
dim <- tiledb_dim("foo", c(1.0, 100.0))
expect_equal(tiledb::datatype(dim), "FLOAT64")
dim <- tiledb_dim("foo", c(1L, 100L))
expect_equal(tiledb::datatype(dim), "INT32")
dim <- tiledb_dim("foo", c(1L, 100L))
expect_equal(tiledb::name(dim), "foo")
dim <- tiledb_dim("", c(1L, 100L))
expect_equal(tiledb::name(dim), "")
dim <- tiledb_dim("foo", c(1L, 100L), tile=10L, type="INT32")
expect_equal(tiledb::tile(dim), 10L)
dim <- tiledb_dim("foo", c(1L, 100L), type = "INT32")
expect_equal(tiledb::tile(dim), 100L)
dim <- tiledb_dim("foo", c(1L, 1L), type = "INT32")
expect_equal(tiledb::tile(dim), 1L)
dim <- tiledb_dim("foo", c(1.1, 11.9), type = "FLOAT64")
expect_equal(tiledb::tile(dim), 11.9 - 1.1)
dim <- tiledb_dim("", c(1L, 100L))
expect_true(is.anonymous(dim))
dim <- tiledb_dim("foo", c(1L, 100L))
expect_false(is.anonymous(dim))
dim <- tiledb_dim("", c(1L, 100L), type = "INT32")
expect_equal(tiledb::datatype(dim), "INT32")
dim <- tiledb_dim("", c(1, 100), type = "FLOAT64")
expect_equal(tiledb::datatype(dim), "FLOAT64")
t
d <- tiledb_dim("", c(-1L, 100L))
expect_equal(dim(d), 102L)
if (tiledb_version(TRUE) < "2.1.0") exit_file("Needs TileDB 2.1.* or later")
suppressMessages({
library(nanotime)
library(bit64)
})
atttype <- "INT32"
intmax <- .Machine$integer.max
uri <- tempfile()
dimtypes <- c("ASCII",
"INT8",
"UINT8",
"INT16",
"UINT16",
"INT32",
"UINT32",
"INT64",
"UINT64",
"FLOAT32",
"FLOAT64",
"DATETIME_YEAR",
"DATETIME_MONTH",
"DATETIME_WEEK",
"DATETIME_DAY",
"DATETIME_HR",
"DATETIME_MIN",
"DATETIME_SEC",
"DATETIME_MS",
"DATETIME_US",
"DATETIME_NS",
"DATETIME_PS",
"DATETIME_FS",
"DATETIME_AS"
)
for (dtype in dimtypes) {
if (tiledb_vfs_is_dir(uri)) {
tiledb_vfs_remove_dir(uri)
}
dom <- switch(dtype,
"ASCII" = NULL,
"INT8" =,
"UINT8" = c(1L, 100L),
"INT16" =,
"UINT16" =,
"UINT32" =,
"INT32" = c(1L, 10000L),
"INT64" =,
"UINT64" = c(as.integer64(1), as.integer64(1000)),
"FLOAT32" =,
"FLOAT64" = c(1, 1000),
"DATETIME_YEAR" =,
"DATETIME_MONTH" =,
"DATETIME_WEEK" =,
"DATETIME_DAY" = c(-intmax, intmax),
"DATETIME_HR" =,
"DATETIME_MIN" =,
"DATETIME_SEC" =,
"DATETIME_MS" =,
"DATETIME_US" =,
"DATETIME_NS" =,
"DATETIME_PS" =,
"DATETIME_FS" =,
"DATETIME_AS" = c(-5e18, 5e18)
)
tile <- switch(dtype,
"ASCII" = NULL,
"UINT8" = ,
"INT8" = 100L,
"INT32" = ,
"UINT32" = 1000L,
"UINT64" =,
"INT64" = as.integer64(1000),
1000)
domain <- tiledb_domain(tiledb_dim("row", dom, tile, dtype))
attrib <- tiledb_attr("attr", type = "INT32")
schema <- tiledb_array_schema(domain, attrib, sparse=TRUE)
tiledb_array_create(uri, schema)
arr <- tiledb_array(uri, as.data.frame=TRUE)
dvec <- switch(dtype,
"ASCII" = LETTERS[1:5],
"INT8" =,
"UINT8" =,
"INT16" =,
"UINT16" =,
"UINT32" =,
"INT32" = 1:5,
"INT64" =,
"UINT64" = as.integer64(1:5),
"FLOAT32" =,
"FLOAT64" = as.numeric(1:5),
"DATETIME_YEAR" = c(as.Date("2020-01-01"), as.Date("2021-01-01"), as.Date("2022-01-01"), as.Date("2023-01-01"), as.Date("2024-01-01")),
"DATETIME_MONTH" = c(as.Date("2020-01-01"), as.Date("2020-02-01"), as.Date("2020-03-01"), as.Date("2020-04-01"), as.Date("2020-05-01")),
"DATETIME_WEEK" = c(as.Date("2020-01-01"), as.Date("2020-01-08"), as.Date("2020-01-15"), as.Date("2020-01-22"), as.Date("2020-01-29")),
"DATETIME_DAY" = as.Date("2020-01-01") + 0:4,
"DATETIME_HR" = as.POSIXct("2020-01-01 00:00:00") + (0:4)*3600,
"DATETIME_MIN" = as.POSIXct("2020-01-01 00:00:00") + (0:4)*3600,
"DATETIME_SEC" = as.POSIXct("2020-01-01 00:00:00") + (0:4)*3600,
"DATETIME_MS" = as.POSIXct("2000-01-01 00:00:00") + (0:4)*3600 + rep(0.001,5),
"DATETIME_US" = as.POSIXct("2000-01-01 00:00:00") + (0:4)*3600 + rep(0.00001,5),
"DATETIME_NS" =,
"DATETIME_PS" =,
"DATETIME_FS" =,
"DATETIME_AS" = as.nanotime("1970-01-01T00:00:00.000000001+00:00") + (0:4)*1e9
)
avec <- 10^(1:5)
data <- data.frame(row = dvec, attr = avec, stringsAsFactors=FALSE)
arr[] <- data
arr2 <- tiledb_array(uri, as.data.frame=TRUE)
readdata <- arr2[]
if (dtype == "ASCII" && getRversion() < '4.0.0') readdata$row <- as.character(readdata$row)
if (dtype == "UINT64") readdata[,1] <- as.integer64(readdata[,1])
expect_equivalent(data, readdata)
if (grepl("^DATETIME", dtype)) {
expect_false(class(readdata) == "integer64")
expect_false(datetimes_as_int64(arr2))
datetimes_as_int64(arr2) <- TRUE
expect_true(datetimes_as_int64(arr2))
expect_true(class(arr2[][,"row"]) == "integer64")
}
arr3 <- tiledb_array(uri, as.data.frame=TRUE)
if (dtype %in% c("DATETIME_YEAR", "DATETIME_MONTH", "DATETIME_WEEK", "DATETIME_DAY")) {
scaleDate <- function(val, dtype) {
val <- switch(dtype,
"DATETIME_YEAR" = as.numeric(strftime(val, "%Y")) - 1970,
"DATETIME_MONTH" = 12*(as.numeric(strftime(val, "%Y")) - 1970) + as.numeric(strftime(val, "%m")) - 1,
"DATETIME_WEEK" = as.numeric(val)/7,
"DATETIME_DAY" = as.numeric(val))
}
selected_ranges(arr3) <- list(cbind(as.integer64(scaleDate(data[2, "row"], dtype)),
as.integer64(scaleDate(data[4, "row"], dtype))))
} else if (dtype %in% c("DATETIME_HR", "DATETIME_MIN", "DATETIME_SEC",
"DATETIME_MS", "DATETIME_US")) {
scaleDatetime <- function(val, dtype) {
val <- switch(dtype,
"DATETIME_HR" = as.numeric(val)/3600,
"DATETIME_MIN" = as.numeric(val)/60,
"DATETIME_SEC" = as.numeric(val),
"DATETIME_MS" = as.numeric(val) * 1e3,
"DATETIME_US" = as.numeric(val) * 1e6
)
}
selected_ranges(arr3) <- list(cbind(as.integer64(scaleDatetime(data[2, "row"], dtype)),
as.integer64(scaleDatetime(data[4, "row"], dtype))))
} else if (dtype %in% c("DATETIME_NS", "DATETIME_PS", "DATETIME_FS", "DATETIME_AS")) {
scaleDatetime <- function(val, dtype) {
val <- switch(dtype,
"DATETIME_NS" = as.integer64(val),
"DATETIME_PS" = as.integer64(val) * 1e3,
"DATETIME_FS" = as.integer64(val) * 1e6,
"DATETIME_AS" = as.integer64(val) * 1e9
)
}
selected_ranges(arr3) <- list(cbind(as.integer64(scaleDatetime(data[2, "row"], dtype)),
as.integer64(scaleDatetime(data[4, "row"], dtype))))
} else {
selected_ranges(arr3) <- list(cbind(data[2, "row"], data[4, "row"]))
}
readdata <- arr3[]
if (dtype == "ASCII" && getRversion() < '4.0.0') readdata$row <- as.character(readdata$row)
if (dtype == "UINT64") readdata[,1] <- as.integer64(readdata[,1])
expect_equivalent(data[2:4,], readdata, info=dtype)
expect_equal(NROW(readdata), 3L)
} |
gestMultiple <- function(data, idvar, timevar, Yn, An, Cn = NA, outcomemodels, propensitymodel, censoringmodel = NULL, type, EfmVar = NA, cutoff = NA, ...) {
if (!is.data.frame(data)) (stop("Either no data set has been given, or it is not in a data frame."))
if (is.na(EfmVar) && type %in% c(2, 4)) (stop("Type 2 or 4 is specified but argument EfmVar not specified."))
if (!is.na(EfmVar) && !is.numeric(data[, EfmVar]) && type %in% c(2, 4)) (stop("Effect modification is only supported for a continuous covariate, or binary covariate written as an as.numeric() 0,1 vector"))
if (!is.na(Cn) == TRUE && !is.numeric(data[, Cn])) (stop("A censoring indicator must be written as an as.numeric() 0,1 vector, with 1 indicating censoring."))
if (!is.null(censoringmodel)) (warning("Variables included in censoringmodel should ideally be included in propensitymodel else propensity scores may be invalid."))
if (!is.factor(data[, Yn]) && !is.numeric(data[, Yn])) (stop("Outcome Yn must be an as.numeric() continuous variable, or if binary, an as.numeric() 0 1 variable."))
if (!is.factor(data[, Yn]) && !is.numeric(data[, Yn])) (stop("Exposure An must be either an as.factor() categorical variable, or an as.numeric() variable. If Binary, it must be set either as a two category as.factor() variable or a numeric 0 1 variable."))
Ybin <- FALSE
Abin <- FALSE
Acat <- FALSE
if (setequal(unique(data[, Yn][!is.na(data[, Yn])]), c(0, 1)) && is.numeric(data[, Yn])) (Ybin <- TRUE)
if (setequal(unique(data[, An][!is.na(data[, An])]), c(0, 1)) && is.numeric(data[, An])) (Abin <- TRUE)
if (is.factor(data[, An])) (Acat <- TRUE)
if (!is.numeric(data[, timevar])) (stop("timevar must be as as.numeric() variable starting at 1"))
if (is.na(min(data[, idvar]))) (stop("idvar must not contain any missing values"))
if (min(data[, timevar]) != 1) (stop("timevar must be as as.numeric() variable starting at 1. It must also not contain any missing values"))
if (nrow(data) != (length(unique(data[, idvar])) * max(data[, timevar]))) (stop("There must a a row entry for each individual at each time period. For those with entries missing or censored at a time point, add
rows of missing values except for the time and id variable. Consider using the function FormatData."))
T <- max(data[, timevar])
if (is.na(cutoff) == TRUE) {
cutoff <- T
}
data$int <- 1
lmp <- formula(propensitymodel)
if (Acat == TRUE) {
modp <- multinom(lmp, data = data)
} else if (Abin == TRUE) {
modp <- glm(lmp, family = "binomial", data = data)
} else {
modp <- glm(lmp, family = "gaussian", data = data)
}
if (Acat == TRUE) {
props <- predict(modp, type = "probs", newdata = data)
if (nlevels(data[, An]) == 2) {
data$prs <- props
} else {
data$prs <- props[, -1]
}
} else {
props <- predict(modp, type = "response", newdata = data)
data$prs <- props
}
cps <- NA
if (is.na(Cn)) {
data$w <- 1
} else {
lmc <- formula(censoringmodel)
modc <- glm(lmc, family = "binomial", data = data)
cps <- 1 - predict(modc, type = "response", newdata = data)
data$cps <- cps
data[, paste(Cn, "0", sep = "")] <- as.integer(!data[, Cn])
data$cprod <- data$cps
data[is.na(data$cprod) == TRUE, "cprod"] <- 1
data$w <- data[, paste(Cn, "0", sep = "")] / data$cps
}
data$H <- data[, Yn]
dc <- data
dc$cntstep <- 1
dcom <- data[complete.cases(data), ]
for (i in 2:cutoff) {
d2 <- data[data[, timevar] %in% seq(1, T - (i - 1), by = 1), ]
d2$cntstep <- i
dc <- rbind(dc, d2)
}
dc <- dc[order(dc[, idvar], dc[, timevar]), ]
if (type == 1) {
z <- c("int")
timevarying <- FALSE
} else if (type == 2) {
z <- c("int", EfmVar)
timevarying <- FALSE
} else if (type == 3) {
z <- c("int")
timevarying <- TRUE
} else if (type == 4) {
z <- c("int", EfmVar)
timevarying <- TRUE
}
par1 <- paste(eval(An), eval(z), sep = ":")
par1[par1 == paste(eval(An), "int", sep = ":")] <- paste(eval(An))
par2 <- paste("prs", eval(z), sep = ":")
par2[par2 == paste("prs", "int", sep = ":")] <- paste("prs")
if (Ybin == TRUE) {
family <- Gamma(link = "log")
} else {
family <- gaussian
}
for (i in 1:length(outcomemodels)) {
outcomemodels[[i]] <- formula(outcomemodels[[i]])
termlabs <- attr(terms(outcomemodels[[i]]), which = "term.labels")
if (identical(as.numeric(length(which(termlabs == An))), 0)) {
stop("Every formula in outcomemodels must have an An term")
}
if (type %in% c(2, 4)) {
if (identical(as.numeric(length(which(termlabs == paste(An, EfmVar, sep = ":")))), 0)) {
stop("For types 2 and 4. Every formula in outcomemodels must have an An term, Efm term, and
an An:Efm term. The An term must appear before any EfmVar term in each formula in outcomemodels.
Or there must be an An*EfmVar term")
}
if (!identical(as.numeric(length(which(termlabs == EfmVar))), 0) && which(termlabs == EfmVar) < which(termlabs == An)) (stop("For types 2 and 4. Every formula in outcomemodels must have an An term, Efm term, and
an An:Efm term. The An term must appear before any EfmVar term in each formula in outcomemodels. Or there must be an An*EfmVar term"))
}
outcomemodels[[i]] <- reformulate(c(termlabs, par2), response = "H")
}
if (timevarying == FALSE) {
lmy <- outcomemodels[[1]]
out <- summary(geem(terms(lmy), family = family, id = dcom[, idvar], data = dcom, weights = dcom$w))
if (Acat == TRUE) {
nam1 <- paste(An, levels(data[, An])[-1], sep = "")
nam2 <- apply(expand.grid(nam1, z[-1]), 1, paste, collapse = ":")
Acoef <- c(nam1, nam2)
psi0 <- out$beta[match(Acoef, out$coefnames)]
names(psi0) <- Acoef
psicat <- as.list(NULL)
for (l in 2:nlevels(data[, An])) {
psicat[[l]] <- psi0[grep(levels(data[, An])[l], Acoef)]
}
psicat[[1]] <- rep(0, length(psicat[[2]]))
} else {
psi <- out$beta[match(par1, out$coefnames)]
names(psi) <- par1
}
if (Acat == TRUE) {
i <- 2
while (i <= cutoff && i <= T) {
j <- 1
dc$psiZA <- 0
while (j <= (i - 1)) {
if (length(z) == 1) {
for (l in 1:nlevels(dc[, An])) {
dc[dc$cntstep == j & dc[, An] == levels(dc[, An])[l] & !is.na(dc[, An]), "psiZA"] <- psicat[[l]]
}
} else {
for (l in 1:nlevels(dc[, An])) {
dc[dc$cntstep == j & dc[, An] == levels(dc[, An])[l] & !is.na(dc[, An]), "psiZA"] <- rowSums(
sweep(dc[dc$cntstep == j & dc[, An] == levels(dc[, An])[l] & !is.na(dc[, An]), z], 2, psicat[[l]], "*")
)
}
}
j <- j + 1
}
j <- 2
while (j <= i) {
for (k in 1:(T - (j - 1))) {
if (is.na(Cn) == FALSE) {
dc[dc$cntstep == j & dc[, timevar] == k, "cprod"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == k, "cps"] *
dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "cprod"]
dc[dc$cntstep == j & dc[, timevar] == k, "w"] <- data[data[, timevar] == (k + j - 1), paste(Cn, "0", sep = "")] / dc[dc$cntstep == j & dc[, timevar] == k, "cprod"]
}
if (Ybin == FALSE) {
dc[dc$cntstep == j & dc[, timevar] == k, "H"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "H"] -
dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "psiZA"]
}
if (Ybin == TRUE) {
dc[dc$cntstep == j & dc[, timevar] == k, "H"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "H"] *
exp(-dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "psiZA"])
}
}
j <- j + 1
}
dt <- dc[dc$cntstep %in% seq(1, i, by = 1), ]
dtcom <- dt[complete.cases(dt), ]
lmH <- outcomemodels[[i]]
out <- summary(geem(terms(lmH), family = family, id = dtcom[, idvar], data = dtcom, weights = dtcom$w))
psi0 <- out$beta[match(Acoef, out$coefnames)]
names(psi0) <- Acoef
psicat <- as.list(NULL)
for (l in 2:nlevels(data[, An])) {
psicat[[l]] <- psi0[grep(levels(data[, An])[l], Acoef)]
}
psicat[[1]] <- rep(0, length(psicat[[2]]))
i <- i + 1
}
results <- list(psi = unlist(psicat[-1]), Data = as_tibble(data[, !names(data) %in% c("H", "psiZA")]), PropensitySummary = summary(data$prs), CensoringSummary = summary(cps))
class(results) <- "Results"
return(results)
} else {
i <- 2
while (i <= cutoff && i <= T) {
j <- 2
while (j <= i) {
for (k in 1:(T - (j - 1))) {
if (is.na(Cn) == FALSE) {
dc[dc$cntstep == j & dc[, timevar] == k, "cprod"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == k, "cps"] *
dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "cprod"]
dc[dc$cntstep == j & dc[, timevar] == k, "w"] <- data[data[, timevar] == (k + j - 1), paste(Cn, "0", sep = "")] / dc[dc$cntstep == j & dc[, timevar] == k, "cprod"]
}
if (Ybin == FALSE) {
if (length(z) == 1) {
dc[dc$cntstep == j & dc[, timevar] == k, "H"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "H"] -
dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), An] * psi * data[data[, timevar] == (k + 1), z]
} else {
dc[dc$cntstep == j & dc[, timevar] == k, "H"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "H"] -
rowSums(dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), An] * sweep(dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), z], 2, psi, "*"))
}
}
if (Ybin == TRUE) {
if (length(z) == 1) {
dc[dc$cntstep == j & dc[, timevar] == k, "H"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "H"] *
exp(dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), An] * -psi * data[data[, timevar] == (k + 1), z])
} else {
dc[dc$cntstep == j & dc[, timevar] == k, "H"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "H"] *
exp(-rowSums(dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), An] * sweep(dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), z], 2, psi, "*")))
}
}
}
j <- j + 1
}
dt <- dc[dc$cntstep %in% seq(1, i, by = 1), ]
dtcom <- dt[complete.cases(dt), ]
lmH <- outcomemodels[[i]]
out <- summary(geem(terms(lmH), family = family, id = dtcom[, idvar], data = dtcom, weights = dtcom$w))
psi <- out$beta[match(par1, out$coefnames)]
names(psi) <- par1
i <- i + 1
}
results <- list(psi = psi, Data = as_tibble(data[, !names(data) %in% c("H")]), PropensitySummary = summary(data$prs), CensoringSummary = summary(cps))
class(results) <- "Results"
return(results)
}
}
else if (timevarying == TRUE) {
if (Acat == TRUE) {
lmy <- outcomemodels[[1]]
out <- summary(geem(terms(lmy), family = family, id = dcom[, idvar], data = dcom, weights = dcom$w))
nam1 <- paste(An, levels(data[, An])[-1], sep = "")
nam2 <- apply(expand.grid(nam1, z[-1]), 1, paste, collapse = ":")
Acoef <- c(nam1, nam2)
psi0 <- out$beta[match(Acoef, out$coefnames)]
names(psi0) <- Acoef
psicatlist <- as.list(NULL)
psicatresult <- as.list(NULL)
psicat <- as.list(NULL)
for (l in 2:nlevels(data[, An])) {
psicat[[l]] <- psi0[grep(levels(data[, An])[l], Acoef)]
}
psicat[[1]] <- rep(0, length(psicat[[2]]))
psicatlist[[1]] <- psicat
psicatresult[[1]] <- psicat[-1]
i <- 2
while (i <= cutoff && i <= T) {
j <- 1
dc$psiZA <- 0
while (j <= (i - 1)) {
if (length(z) == 1) {
for (l in 1:nlevels(dc[, An])) {
dc[dc$cntstep == j & dc[, An] == levels(dc[, An])[l] & !is.na(dc[, An]), "psiZA"] <- psicatlist[[j]][[l]]
}
} else {
for (l in 1:nlevels(dc[, An])) {
dc[dc$cntstep == j & dc[, An] == levels(dc[, An])[l] & !is.na(dc[, An]), "psiZA"] <- rowSums(
sweep(dc[dc$cntstep == j & dc[, An] == levels(dc[, An])[l] & !is.na(dc[, An]), z], 2, psicatlist[[j]][[l]], "*")
)
}
}
j <- j + 1
}
j <- 2
while (j <= i) {
for (k in 1:(T - (j - 1))) {
if (is.na(Cn) == FALSE) {
dc[dc$cntstep == j & dc[, timevar] == k, "cprod"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == k, "cps"] *
dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "cprod"]
dc[dc$cntstep == j & dc[, timevar] == k, "w"] <- data[data[, timevar] == (k + j - 1), paste(Cn, "0", sep = "")] / dc[dc$cntstep == j & dc[, timevar] == k, "cprod"]
}
if (Ybin == FALSE) {
dc[dc$cntstep == j & dc[, timevar] == k, "H"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "H"] -
dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "psiZA"]
}
if (Ybin == TRUE) {
dc[dc$cntstep == j & dc[, timevar] == k, "H"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "H"] *
exp(-dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "psiZA"])
}
}
j <- j + 1
}
dt <- dc[dc$cntstep %in% i, ]
dtcom <- dt[complete.cases(dt), ]
lmH <- outcomemodels[[i]]
out <- summary(geem(terms(lmH), family = family, id = dtcom[, idvar], data = dtcom, weights = dtcom$w))
psi0 <- out$beta[match(Acoef, out$coefnames)]
names(psi0) <- Acoef
psicat <- as.list(NULL)
for (l in 2:nlevels(data[, An])) {
psicat[[l]] <- psi0[grep(levels(data[, An])[l], Acoef)]
}
psicat[[1]] <- rep(0, length(psicat[[2]]))
psicatlist[[i]] <- psicat
psicatresult[[i]] <- psicat[-1]
i <- i + 1
}
nam <- as.vector(NULL)
for (p in 1:cutoff) {
nam[p] <- paste("c=", p, sep = "")
}
names(psicatresult) <- nam
results <- list(psi = unlist(psicatresult), Data = as_tibble(data[, !names(data) %in% c("H", "psiZA")]), PropensitySummary = summary(data$prs), CensoringSummary = summary(cps))
class(results) <- "Results"
return(results)
} else {
lmy <- outcomemodels[[1]]
out <- summary(geem(terms(lmy), family = family, id = dcom[, idvar], data = dcom, weights = dcom$w))
psi <- out$beta[match(par1, out$coefnames)]
names(psi) <- par1
psilist <- as.list(NULL)
psilist[[1]] <- psi
i <- 2
while (i <= cutoff && i <= T) {
j <- 2
while (j <= i) {
for (k in 1:(T - (j - 1))) {
if (is.na(Cn) == FALSE) {
dc[dc$cntstep == j & dc[, timevar] == k, "cprod"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == k, "cps"] *
dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "cprod"]
dc[dc$cntstep == j & dc[, timevar] == k, "w"] <- data[data[, timevar] == (k + j - 1), paste(Cn, "0", sep = "")] / dc[dc$cntstep == j & dc[, timevar] == k, "cprod"]
}
if (Ybin == FALSE) {
if (length(z) == 1) {
dc[dc$cntstep == j & dc[, timevar] == k, "H"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "H"] -
dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), An] * psilist[[j - 1]] * data[data[, timevar] == (k + 1), z]
} else {
dc[dc$cntstep == j & dc[, timevar] == k, "H"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "H"] -
rowSums(dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), An] * sweep(dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), z], 2, psilist[[j - 1]], "*"))
}
}
if (Ybin == TRUE) {
if (length(z) == 1) {
dc[dc$cntstep == j & dc[, timevar] == k, "H"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "H"] *
exp(dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), An] * -psilist[[j - 1]] * data[data[, timevar] == (k + 1), z])
} else {
dc[dc$cntstep == j & dc[, timevar] == k, "H"] <- dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), "H"] *
exp(-rowSums(dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), An] * sweep(dc[dc$cntstep == (j - 1) & dc[, timevar] == (k + 1), z], 2, psilist[[j - 1]], "*")))
}
}
}
j <- j + 1
}
dt <- dc[dc$cntstep %in% i, ]
dtcom <- dt[complete.cases(dt), ]
lmH <- outcomemodels[[i]]
out <- summary(geem(terms(lmH, keep.order = T), family = family, id = dtcom[, idvar], data = dtcom, weights = dtcom$w))
psi <- out$beta[match(par1, out$coefnames)]
names(psi) <- par1
psilist[[i]] <- psi
i <- i + 1
}
nam <- as.vector(NULL)
for (p in 1:cutoff) {
nam[p] <- paste("c=", p, sep = "")
}
names(psilist) <- nam
results <- list(psi = unlist(psilist), Data = as_tibble(data[, !names(data) %in% c("H")]), PropensitySummary = summary(data$prs), CensoringSummary = summary(cps))
class(results) <- "Results"
return(results)
}
}
} |
library(plm)
data("Produc", package = "plm")
fd_plm <- plm(log(gsp) ~ log(pcap) + log(pc) + log(emp) + unemp, data = Produc, model = "fd")
fd_plm2 <- plm(log(gsp) ~ 0 + log(pcap) + log(pc) + log(emp) + unemp, data = Produc, model = "fd")
fd_pggls <- pggls(log(gsp) ~ log(pcap) + log(pc) + log(emp) + unemp, data = Produc, model = "fd")
fd_pggls2 <- pggls(log(gsp) ~ 0 + log(pcap) + log(pc) + log(emp) + unemp, data = Produc, model = "fd")
summary(fd_plm)
summary(fd_plm2)
summary(fd_pggls)
summary(fd_pggls2)
vcovHC(fd_plm)
vcovHC(fd_plm2) |
library(dplyr)
context("default engines")
test_that('check default engines', {
expect_equal(boost_tree()$engine, "xgboost")
expect_equal(decision_tree()$engine, "rpart")
expect_equal(linear_reg()$engine, "lm")
expect_equal(logistic_reg()$engine, "glm")
expect_equal(mars()$engine, "earth")
expect_equal(mlp()$engine, "nnet")
expect_equal(multinom_reg()$engine, "nnet")
expect_equal(nearest_neighbor()$engine, "kknn")
expect_equal(proportional_hazards()$engine, "survival")
expect_equal(rand_forest()$engine, "ranger")
expect_equal(survival_reg()$engine, "survival")
expect_equal(svm_linear()$engine, "LiblineaR")
expect_equal(svm_poly()$engine, "kernlab")
expect_equal(svm_rbf()$engine, "kernlab")
}) |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(naijR)
map_ng()
map_ng("Nigeria")
map_ng(lgas())
map_ng(states(gpz = "sw"), show.text = TRUE, col = 4)
kk <- "Kebbi"
map_ng(kk, col = 6, fill = TRUE, title = paste(kk, "State"))
ss <- states()
numStates <- length(ss)
vv <- sample(LETTERS[1:5], numStates, TRUE)
dd <- data.frame(state = ss, var = vv, stringsAsFactors = FALSE)
head(dd)
map_ng(data = dd, x = var, show.text = FALSE)
map_ng(region = ss, x = vv, col = "red", show.text = FALSE)
map_ng(region = ss, x = var)
nn <- runif(numStates, max = 100)
bb <- c(0, 40, 60, 100)
map_ng(region = ss, x = nn, breaks = bb, col = 'YlOrRd', show.text = FALSE)
map_ng(
region = ss,
x = nn,
breaks = bb,
categories = c("Low", "Medium", "High"),
col = 3L,
show.text = FALSE
)
x <- c(3.000, 4.000, 6.000, 5.993, 5.444, 6.345, 5.744)
y <- c(8.000, 9.000, 9.300, 10.432, 8.472, 6.889, 9.654)
map_ng("Nigeria", x = x, y = y)
map_ng("Kwara", x = x, y = y) |
SPU_Var <- function(gamma, n1, n2, cov){
p <- dim(cov)[1]
if(gamma == 1){
var <- (1/n1 + 1/n2)*(t(rep(1, p)) %*% cov %*% rep(1, p))
var <- as.numeric(var)
}else{
P1 <- SPU_E(2*gamma, n1, n2, cov)
P2 <- -(SPU_E(gamma, n1, n2, cov))^2
c_d <- c_and_d(gamma, gamma)
n.case <- dim(c_d)[1]
P3 <- 0
diags <- diag(cov)
p <- length(diags)
mat1 <- matrix(rep(diags, p), p, p, byrow = FALSE)
mat2 <- matrix(rep(diags, p), p, p, byrow = TRUE)
for(i in 1:n.case){
c1 <- c_d$c1[i]
c2 <- c_d$c2[i]
c3 <- c_d$c3[i]
d1 <- c_d$d1[i]
d2 <- c_d$d2[i]
d3 <- c_d$d3[i]
mat <- mat1^(c1 + d1)*mat2^(c2 + d2)*cov^(c3 + d3)
diag(mat) <- 0
N <- (factorial(gamma))^2*sum(mat)
D <- (n1^(c1 + c2 + c3)*n2^(d1 + d2 + d3)*factorial(c1)*factorial(c2)*
factorial(d1)*factorial(d2)*factorial(c3)*factorial(d3)*
2^(c1 + c2 + d1 + d2))
P3 <- P3 + N/D
}
var <- P1 + P2 + P3
}
return(var)
} |
mnis_additional_utility <- function(query) {
got <- mnis_query(query)
mem <- purrr::discard(got$Members$Member, is.null)
names(mem) <- janitor::make_clean_names(names(mem))
mem
} |
rmultivariate_normal = function( n , mean , cov )
{
svd = base::svd(cov)
S = svd$u %*% base::diag(base::sqrt(svd$d)) %*% base::t(svd$u)
n_dim = length(mean)
X = base::matrix( stats::rnorm(n*n_dim) , nrow = n , ncol = n_dim )
X = base::t(base::apply( X , 1 , function(x) { mean + S %*% x } ))
return(X)
} |
test_that("as.multiPhylo()", {
expect_equal(structure(list(BalancedTree(8), PectinateTree(8)),
class = 'multiPhylo'),
as.multiPhylo(list(BalancedTree(8), PectinateTree(8))))
expect_equal(structure(list(BalancedTree(8)), class = 'multiPhylo'),
as.multiPhylo(BalancedTree(8)))
char <- MatrixToPhyDat(matrix(c(1,1,1,0,0,0), ncol = 1,
dimnames = list(letters[1:6], NULL)))
expect_equal(ape::read.tree(text = '((a, b, c), (d, e, f));'),
as.multiPhylo(char)[[1]])
char2 <- MatrixToPhyDat(matrix(c(1,1,1,0,0,0,
0,1,1,1,1,'?',
0,0,1,1,'-',2,
0,1,1,1,1,'?'), ncol = 4,
dimnames = list(letters[1:6], NULL)))
mpChar2 <- as.multiPhylo(char2)
expect_equal(ape::read.tree(text = '((a, b, c), (d, e, f));'),
mpChar2[[1]])
expect_equal(ape::read.tree(text = '(b, c, d, e);'),
mpChar2[[2]])
expect_equal(ape::read.tree(text = '((a, b), (c, d));'),
mpChar2[[3]])
expect_equal(mpChar2[[2]], mpChar2[[4]])
mpSplits <- as.Splits(PectinateTree(letters[1:6]))
expect_true(all.equal(structure(list(
'9' = ape::read.tree(text = '((a, b), (c, d, e, f));'),
'10' = ape::read.tree(text = '((a, b, c), (d, e, f));'),
'11' = ape::read.tree(text = '((a, b, c, d), (e, f));')),
class = 'multiPhylo'),
as.multiPhylo(mpSplits)))
}) |
source("ESEUR_config.r")
ly=read.csv(paste0(ESEUR_dir, "ecosystems/lang-year.csv.xz"), as.is=TRUE)
plot(ly$Year, ly$Languages, type="l", col=point_col,
xaxs="i", yaxs="i",
xlim=c(1949, 2000), ylim=c(0, 320),
xlab="Year", ylab="New languages\n") |
.start_menzel <- function(df, est.prev, species){
years <- unique(df$year)
Mp <- switch(species,
"Larix decidua" = list(TbCD=7, TbH=3, a=1372, b=-246),
"Picea abies (frueh)" = list(TbCD=9, TbH=4, a=1848, b=-317),
"Picea abies (spaet)" = list(TbCD=9, TbH=5, a=1616, b=-274),
"Picea abies (noerdl.)" = list(TbCD=9, TbH=4, a=2084, b=-350),
"Picea omorika" = list(TbCD=7, TbH=3, a=2833, b=-484),
"Pinus sylvestris" = list(TbCD=9, TbH=5, a=1395, b=-223),
"Betula pubescens" = list(TbCD=9, TbH=5, a=1438, b=-261),
"Quercus robur" = list(TbCD=9, TbH=4, a=1748, b=-298),
"Quercus petraea" = list(TbCD=9, TbH=3, a=1741, b=-282),
"Fagus sylvatica" = list(TbCD=9, TbH=6, a=1922, b=-348))
CDNovDec <- utils::stack(tapply(df[(df$month >= 11 & df$Tavg <= Mp$TbCD), "Tavg"],
df[(df$month >= 11 & df$Tavg <= Mp$TbCD), "year"],
FUN=length))
CDNovDec$ind <- as.integer(levels(CDNovDec$ind)) + 1
names(CDNovDec) <- c("CDprev", "year")
if(est.prev == 0){
df <- df[df$year != years[1], ]
} else {
CDNovDec <- rbind(c(mean(CDNovDec$CDprev[1:est.prev]), years[1]),
CDNovDec)
}
df$CD <- ifelse(df$Tavg <= Mp$TbCD, 1, 0)
ChillDays <- utils::stack(tapply(df$CD, df$year, FUN=cumsum))
names(ChillDays) <- c("CDcumsum", "year")
ChillDays <- merge(ChillDays, CDNovDec, by="year", all.x=TRUE)
df$CD <- ChillDays$CDprev + ChillDays$CDcumsum
rm(ChillDays, CDNovDec)
df$TCrit <- ifelse(df$CD > 0, Mp$a + Mp$b * log(df$CD), Mp$a)
df$HeatSum <- ifelse(df$month >= 2 & df$Tavg > Mp$TbH, df$Tavg - Mp$TbH, 0)
df$HeatSum <- utils::stack(tapply(df$HeatSum, df$year, FUN=cumsum))$values
df$start <- df$HeatSum >= df$TCrit
start <- utils::stack(tapply(df$DOY[df$start],
df$year[df$start], FUN=min))$values
return(start)
}
.start_std_meteo <- function(df, Tmin=5){
df$period <- ifelse(df$Tavg > Tmin, 1, 0)
start <- tapply(df$period, df$year, FUN=function(x){
sixer <- as.numeric(stats::filter(x, rep(1, 6), sides=1))
doy <- which(!is.na(sixer) & sixer == 6)
ifelse(length(doy) == 0, NA, min(doy))
})
return(as.vector(start))
}
.start_ribes <- function(df){
df[df$DOY < 49 | df$Tavg < 0, 'Tavg'] <- 0
start <- tapply(df$Tavg, df$year, FUN=function(x){
x <- cumsum(x)
min(which(x > 164))
})
return(as.vector(start))
} |
test_that("early stopping with patience = 1", {
fit_with_callback <- function(cb, epochs = 25) {
model <- get_model()
dl <- get_dl()
suppressMessages({
expect_message({
mod <- model %>%
setup(
loss = torch::nn_mse_loss(),
optimizer = torch::optim_adam,
) %>%
set_hparams(input_size = 10, output_size = 1) %>%
fit(dl, verbose = TRUE, epochs = epochs, callbacks = list(cb))
})
})
mod
}
mod <- fit_with_callback(luz_callback_early_stopping(
monitor = "train_loss",
patience = 1,
min_delta = 100
))
expect_equal(nrow(get_metrics(mod)), 2)
mod <- fit_with_callback(luz_callback_early_stopping(
monitor = "train_loss",
patience = 2,
min_delta = 100
))
expect_equal(nrow(get_metrics(mod)), 3)
mod <- fit_with_callback(epochs = c(5, 25), luz_callback_early_stopping(
monitor = "train_loss",
patience = 2,
min_delta = 100
))
expect_equal(nrow(get_metrics(mod)), 5)
mod <- fit_with_callback(epochs = c(1, 25), luz_callback_early_stopping(
monitor = "train_loss",
patience = 1,
baseline = 0
))
expect_equal(nrow(get_metrics(mod)), 1)
})
test_that("early stopping", {
torch::torch_manual_seed(1)
set.seed(1)
model <- get_model()
dl <- get_dl()
mod <- model %>%
setup(
loss = torch::nn_mse_loss(),
optimizer = torch::optim_adam,
)
expect_snapshot({
expect_message({
output <- mod %>%
set_hparams(input_size = 10, output_size = 1) %>%
fit(dl, verbose = TRUE, epochs = 25, callbacks = list(
luz_callback_early_stopping(monitor = "train_loss", patience = 1,
min_delta = 0.02)
))
})
})
expect_snapshot({
expect_message({
output <- mod %>%
set_hparams(input_size = 10, output_size = 1) %>%
fit(dl, verbose = TRUE, epochs = 25, callbacks = list(
luz_callback_early_stopping(monitor = "train_loss", patience = 5,
baseline = 0.001)
))
})
})
x <- 0
output <- mod %>%
set_hparams(input_size = 10, output_size = 1) %>%
fit(dl, verbose = FALSE, epochs = 25, callbacks = list(
luz_callback_early_stopping(monitor = "train_loss", patience = 5,
baseline = 0.001),
luz_callback(on_early_stopping = function() {
x <<- 1
})()
))
expect_equal(x, 1)
mod <- model %>%
setup(
loss = torch::nn_mse_loss(),
optimizer = torch::optim_adam,
metrics = luz_metric_mae()
)
expect_snapshot({
expect_message({
output <- mod %>%
set_hparams(input_size = 10, output_size = 1) %>%
fit(dl, verbose = TRUE, epochs = 25, callbacks = list(
luz_callback_early_stopping(monitor = "train_mae", patience = 2,
baseline = 0.91, min_delta = 0.01)
))
})
})
})
test_that("model checkpoint callback works", {
torch::torch_manual_seed(1)
set.seed(1)
model <- get_model()
dl <- get_dl()
mod <- model %>%
setup(
loss = torch::nn_mse_loss(),
optimizer = torch::optim_adam,
)
tmp <- tempfile(fileext = "/")
output <- mod %>%
set_hparams(input_size = 10, output_size = 1) %>%
fit(dl, verbose = FALSE, epochs = 5, callbacks = list(
luz_callback_model_checkpoint(path = tmp, monitor = "train_loss",
save_best_only = FALSE)
))
files <- fs::dir_ls(tmp)
expect_length(files, 5)
tmp <- tempfile(fileext = "/")
output <- mod %>%
set_hparams(input_size = 10, output_size = 1) %>%
fit(dl, verbose = FALSE, epochs = 10, callbacks = list(
luz_callback_model_checkpoint(path = tmp, monitor = "train_loss",
save_best_only = TRUE)
))
files <- fs::dir_ls(tmp)
expect_length(files, 10)
torch::torch_manual_seed(2)
set.seed(2)
model <- get_model()
dl <- get_dl()
mod <- model %>%
setup(
loss = torch::nn_mse_loss(),
optimizer = torch::optim_adam,
)
tmp <- tempfile(fileext = "/")
output <- mod %>%
set_hparams(input_size = 10, output_size = 1) %>%
fit(dl, verbose = FALSE, epochs = 5, callbacks = list(
luz_callback_model_checkpoint(path = tmp, monitor = "train_loss",
save_best_only = TRUE)
))
files <- fs::dir_ls(tmp)
expect_length(files, 5)
})
test_that("early stopping + csv logger", {
model <- get_model()
dl <- get_dl()
tmp <- tempfile(fileext = ".csv")
cb <- list(
luz_callback_early_stopping(min_delta = 100, monitor = "train_loss"),
luz_callback_csv_logger(tmp)
)
suppressMessages({
expect_message({
mod <- model %>%
setup(
loss = torch::nn_mse_loss(),
optimizer = torch::optim_adam,
) %>%
set_hparams(input_size = 10, output_size = 1) %>%
fit(dl, verbose = TRUE, epochs = 25, callbacks = cb)
})
})
expect_equal(nrow(read.csv(tmp)), nrow(get_metrics(mod)))
}) |
inzplot.lm <- function(x,
which = c(
"residual",
"scale",
"leverage",
"cooks",
"normal",
"hist"
),
show.bootstraps = TRUE,
label.id = 3L,
col.smooth = "orangered",
col.bs = "lightgreen",
cook.levels = c(0.5, 1),
col.cook = "pink",
...,
bs.fits = NULL,
env = parent.frame()
) {
if (which[1] == "marginal") {
terms <- x$terms
vars <- attr(terms, "term.labels")
vars <- vars[attr(terms, "dataClasses")[vars] == "numeric"]
f <- as.formula(paste("~", paste(vars, collapse = " + ")))
p <- car::marginalModelPlots(x, f, ...)
return(invisible(p))
}
short.title <- length(which) > 1L
if (show.bootstraps && is.null(bs.fits))
bs.fits <- generate_bootstraps(x, env)
ps <- lapply(which,
function(w) {
switch(w,
"residual" = ,
"scale" = ,
"leverage" = .inzplot_lm_scatter(x, w, show.bootstraps,
label.id, col.smooth, col.bs, cook.levels, col.cook,
short.title,
...,
bs.fits = bs.fits,
env = env
),
"cooks" = .inzplot_lm_cooks(x, label.id,
short.title,
...,
env = env),
"normal" = .inzplot_lm_normqq(x, show.bootstraps, label.id,
short.title,
...,
bs.fits = bs.fits,
env = env),
"hist" = .inzplot_lm_hist(x, show.bootstraps,
short.title,
...,
env = env)
)
}
)
p <- patchwork::wrap_plots(ps)
grDevices::dev.hold()
on.exit(grDevices::dev.flush())
suppressWarnings(print(p))
invisible(p)
}
.inzplot_lm_scatter <- function(x, which, show.bootstraps, label.id,
col.smooth, col.bs,
cook.levels, col.cook,
short.title,
...,
bs.fits,
env) {
HEX_THRESHOLD <- 1e5
d_fun <- function(x, which, label.id = 0L, is.bs = FALSE) {
if (label.id > 0L)
iid <- seq_len(label.id)
labs <- character(nrow(x$model))
switch(which,
"residual" = {
r <- residuals(x)
if (label.id > 0L) {
l <- sort.list(abs(r), decreasing = TRUE)[iid]
labs[l] <- names(r)[l]
}
data.frame(x = predict(x), y = r, lab = labs)
},
"scale" = {
r <- residuals(x)
s <- sqrt(deviance(x) / df.residual(x))
hii <- lm.influence(x, do.coef = FALSE)$hat
rs <- dropInf(r / (s * sqrt(1 - hii)), hii)
if (label.id > 0L) {
l <- sort.list(abs(r), decreasing = TRUE)[iid]
labs[l] <- names(r)[l]
}
data.frame(x = predict(x), y = sqrt(abs(rs)), lab = labs)
},
"leverage" = {
rp <- residuals(x, "pearson")
hii <- lm.influence(x, do.coef = FALSE)$hat
s <- sqrt(deviance(x) / df.residual(x))
rsp <- dropInf(rp / (s * sqrt(1 - hii)), hii)
xx <- ifelse(hii > 1, NA, hii)
cook <- cooks.distance(x, sd = s, res = residuals(x))
if (label.id > 0L) {
l <- order(-cook)[iid]
labs[l] <- names(rp)[l]
}
d <- data.frame(x = xx, y = rsp, lab = labs)
if (!is.bs && length(cook.levels)) {
r.hat <- range(hii, na.rm = TRUE)
attr(d, "r.hat") <- r.hat
}
d
}
)
}
d <- d_fun(x, which, label.id = label.id)
if (show.bootstraps && is.null(bs.fits))
bs.fits <- generate_bootstraps(x, env)
title <- switch(which,
"residual" = "Residuals vs Fitted Values",
"scale" = "Scale-location plot",
"leverage" = "Residuals vs Leverage"
)
if (short.title) {
subtitle <- waiver()
} else {
subtitle <- sprintf("Linear model: %s",
utils::capture.output(x$call$formula)
)
if (show.bootstraps) {
title <- sprintf(
"**%s** with <span style='color:%s'>fitted</span> and <span style='color:%s'>bootstrap</span> smoothers",
title,
col.smooth,
col.bs
)
} else {
title <- sprintf(
"**%s** with fitted smoother",
title
)
}
if (which == "leverage" && !is.null(attr(d, "r.hat"))) {
title <- sprintf("%s, and <span style='color:%s'>Cook's contours</span>",
title,
col.cook
)
}
}
USE_HEX <- nrow(d) > HEX_THRESHOLD
XL <- extendrange(range(d$x, na.rm = TRUE))
YL <- extendrange(range(d$y, na.rm = TRUE), f = 0.08)
p <- ggplot(d, aes_(~x, ~y))
yax2 <- NULL
if (which == "leverage" && !is.null(attr(d, "r.hat"))) {
px <- length(coef(x))
r.hat <- attr(d, "r.hat")
hh <- seq.int(min(r.hat[1L], r.hat[2L] / 100), XL[2],
length.out = 101)
yax2 <- numeric()
for (crit in cook.levels) {
cl.h <- sqrt(crit * px * (1 - hh) / hh)
yax2 <- c(yax2,
structure(cl.h[length(cl.h)] * c(1, -1), .Names = c(crit, crit))
)
dx <- data.frame(x = hh, y = cl.h)
p <- p +
geom_path(lty = 2, col = col.cook,
data = dx, na.rm = TRUE) +
geom_path(aes_(y = ~-y), lty = 2, col = col.cook,
data = dx, na.rm = TRUE) +
geom_vline(xintercept = XL[2])
}
yax2 <- yax2[dplyr::between(yax2, YL[1], YL[2])]
}
if (USE_HEX) {
p <- p + geom_hex() +
scale_fill_gradient(low = "gray80", high = "black") +
labs(fill = "Count")
} else {
p <- p + geom_point()
}
p <- p +
geom_hline(yintercept = 0, lty = 3) +
scale_x_continuous(
switch(which,
"residual" = "Fitted values",
"scale" = "Fitted values",
"leverage" = "Leverage"
)
) +
scale_y_continuous(
switch(which,
"residual" = "Residuals",
"scale" = expression(sqrt(abs("Standardized residuals"))),
"leverage" = "Residuals"
),
sec.axis =
if (!is.null(yax2) && length(yax2)) {
sec_axis(
trans = ~.,
name = NULL,
breaks = yax2,
labels = names(yax2)
)
} else waiver()
) +
ggtitle(title, subtitle = subtitle) +
theme_classic() +
theme(
plot.title.position = ifelse(short.title, "panel", "plot"),
plot.title = element_markdown(size = ifelse(short.title, 11, 12))
) +
coord_cartesian(xlim = XL, ylim = YL, expand = FALSE)
if (label.id > 0L && !is.null(d$lab)) {
p <- p +
geom_text_repel(aes_(label = ~lab),
data = d[d$lab != "", ]
)
}
if (show.bootstraps) {
bs.data <- do.call(
rbind,
lapply(seq_along(bs.fits),
function(i) {
di <- cbind(
d_fun(bs.fits[[i]], which = which, is.bs = TRUE),
bs.index = i
)
si <- loess(y ~ x, data = di)
o <- order(si$x)
data.frame(x = si$x[o], y = si$fitted[o], bs.index = i)
}
)
)
p <- p +
geom_path(
aes_(group = ~bs.index),
data = bs.data,
colour = col.bs
)
}
p <- p +
geom_smooth(
method = "loess",
formula = y ~ x,
colour = col.smooth,
se = FALSE,
na.rm = TRUE
)
p
}
.inzplot_lm_cooks <- function(x, label.id, short.title, ..., env) {
cdx <- cooks.distance(x)
show.mx <- order(-cdx)[1:3]
d <- data.frame(
obs_n = seq_along(cdx),
cooks_distance = cdx
)
co <- order(-cdx)[1:3]
d$lab <- as.character(d$obs_n)
XL <- extendrange(c(0L, nrow(d)))
YL <- c(0, max(cdx) * 1.08)
ggplot(d, aes_(~obs_n, ~cooks_distance)) +
geom_segment(aes_(xend = ~obs_n, y = 0, yend = ~cooks_distance)) +
geom_text(aes_(label = ~lab),
data = d[co, ],
nudge_y = 0.02 * YL[2]
) +
scale_x_continuous("Observation number",
limits = XL
) +
scale_y_continuous("Cook's Distance",
limits = YL
) +
ggtitle(
ifelse(short.title, "Cook's Distance",
"**Cook's Distance** of ordered observations"),
subtitle = if (short.title) waiver ()
else {
sprintf("Linear model: %s",
utils::capture.output(x$call$formula)
)
}
) +
theme_classic() +
theme(
plot.title.position = ifelse(short.title, "panel", "plot"),
plot.title = element_markdown(size = ifelse(short.title, 11, 12))
) +
coord_cartesian(expand = FALSE)
}
.inzplot_lm_normqq <- function(x, show.bootstraps, label.id,
short.title,
..., bs.fits = NULL, env = env) {
r <- residuals(x)
s <- sqrt(deviance(x) / df.residual(x))
hii <- lm.influence(x, do.coef = FALSE)$hat
rs <- dropInf(r / (s * sqrt(1 - hii)), hii)
iid <- 1:3L
labs <- character(nrow(x$model))
l <- sort.list(abs(rs), decreasing = TRUE)[iid]
labs[l] <- names(r)[l]
qq <- normCheck(rs, plot = FALSE)
d <- data.frame(x = qq$x, y = qq$y, lab = labs)
stest <- shapiro.test(rs)
sp <- stest$p.value
sres <- sprintf("Shapiro Wilk normality test: W = %s, P-value %s %s",
round(stest$statistic, 4),
ifelse(sp < 1e-4, "<", "="),
max(round(stest$p.value, 3), 1e-4)
)
p <- ggplot(d, aes_(~x, ~y)) +
geom_abline(slope = 1, intercept = 0)
if (short.title) {
title <- "Normal Q-Q"
subtitle <- waiver()
} else {
title <- "**Normal Q-Q** of residuals"
subtitle <- sprintf(
"Linear model: %s<br>%s",
utils::capture.output(x$call$formula),
sres
)
}
if (show.bootstraps) {
colz <- iNZightPlots::inzpalette("rainbow")(10L)
for (i in 1:10) {
qqx <- normCheck(rnorm(length(rs)), plot = FALSE)
dx <- data.frame(x = qqx$x, y = qqx$y)
p <- p +
geom_point(
colour = colz[i],
data = dx,
pch = 4L
)
}
if (!short.title) {
tx <- c("boo", "tst", "rap", " No", "rma", "l e", "rro", "rs")
tc <- paste0("<span style='color:", colz[1:8], "'>", tx, "</span>", collapse = "")
title <- sprintf("%s with a sample of %s", title, tc)
}
}
p <- p +
geom_point() +
geom_text_repel(aes_(label = ~lab), data = d[d$lab != "", ],
direction = "x"
) +
ggtitle(title, subtitle = subtitle) +
scale_x_continuous("Theoretical quantiles") +
scale_y_continuous("Standardized residuals") +
theme_classic() +
theme(
plot.title.position = ifelse(short.title, "panel", "plot"),
plot.title = element_markdown(size = ifelse(short.title, 11, 12)),
plot.subtitle = element_markdown(lineheight = 1.5)
)
}
.inzplot_lm_hist <- function(x, short.title, ..., env = env) {
d <- data.frame(x = residuals(x))
mx <- mean(d$x, na.rm = TRUE)
sx <- sd(d$x, na.rm = TRUE)
rx <- range(d$x, na.rm = TRUE)
h <- hist(d$x, plot = FALSE)
xmin <- min(rx[1], mx - 3.5 * sx, h$breaks[1])
xmax <- max(rx[2], mx + 3.5 * sx, h$breaks[length(h$breaks)])
ymax <- max(h$density, dnorm(mx, mx, sx)) * 1.05
d2 <- data.frame(x = seq(xmin, xmax, length.out = 1001))
d2$y <- dnorm(d2$x, mx, sx)
dd <- data.frame(x = h$mids, y = h$density)
curve.col <- "orangered"
if (short.title) {
title <- "Histogram"
subtitle <- waiver()
} else {
title <- sprintf(
"**Histogram of residuals** with <span style='color: %s'>Normal density curve</span>",
curve.col
)
subtitle <- sprintf(
"Linear model: %s",
utils::capture.output(x$call$formula)
)
}
ggplot(dd, aes_(~x, ~y)) +
geom_col(
width = diff(h$breaks),
fill = "light blue",
colour = "black"
) +
geom_path(aes_(y = ~y),
data = d2,
colour = curve.col,
linetype = 2,
size = 1.2
) +
coord_cartesian(expand = FALSE) +
scale_x_continuous("Residuals",
limits = extendrange(range(d$x))
) +
scale_y_continuous("Density",
limits = function(l) c(l[1], l[2] * 1.04)
) +
ggtitle(title, subtitle = subtitle) +
theme_classic() +
theme(
plot.title.position = ifelse(short.title, "panel", "plot"),
plot.title = element_markdown(size = ifelse(short.title, 11, 12)),
plot.subtitle = element_markdown(lineheight = 1.5)
)
}
dropInf <- function(x, h) {
if (any(isInf <- h >= 1)) {
x[isInf] <- NaN
}
x
} |
fun_convert <- function(mutation_file,
organism) {
Hugo_Symbol <- NULL
Protein_Change <- NULL
Start_Position <- NULL
End_Position <- NULL
Variant_Type <- NULL
Reference <- NULL
Tumor_Seq <- NULL
Mut_type <- NULL
Chr <- NULL
Start <- NULL
End <- NULL
Ref <- NULL
Alt <- NULL
Alt_length_1 <- NULL
Alt_length_2 <- NULL
PRE_ins <- NULL
PRE_del <- NULL
Alt_ins <- NULL
Alt_del <- NULL
Alt_snv <- NULL
Ref_ins <- NULL
Ref_del <- NULL
Ref_snv <- NULL
Neighbor_start_1 <- NULL
Neighbor_end_1 <- NULL
Neighbor_start_2 <- NULL
Neighbor_end_2 <- NULL
Pre_Neighbor <- NULL
Alt_indel <- NULL
POST_ins <- NULL
Post_Neighbor <- NULL
Alt_length <- NULL
Ref_indel <- NULL
Pos <- NULL
df_mutation <- read.xlsx(mutation_file, sheet = 1)
ref_genome <- fun_load_genome(organism)
fun_genome <- function(x, y) {
r <- NULL
for (i in seq_len(length(x))) {
r <- c(r, as.character(ref_genome[[x[i]]][y[i]]))
}
return(r)
}
fun_genome_2 <- function(x, y, z) {
r <- NULL
for (i in seq_len(length(x))) {
r <- c(r, as.character(ref_genome[[x[i]]][y[i]:z[i]]))
}
return(r)
}
df_mutation <- df_mutation %>% mutate(
Gene = Hugo_Symbol,
HGVS.p = Protein_Change,
Pos = Start_Position,
Start = Start_Position,
End = End_Position,
Mut_type = Variant_Type,
Ref = Reference,
Alt = Tumor_Seq)
df_mutation <- df_mutation %>% dplyr::mutate(
Mut_type = tolower(Mut_type))
df_mutation <- df_mutation %>% dplyr::mutate(
PRE_del = fun_genome(Chr, as.integer(Start) - 1),
PRE_ins = fun_genome(Chr, as.integer(Start)),
POST_ins = fun_genome(Chr, as.integer(End)),
Alt_length_1 = nchar(Ref),
Alt_length_2 = nchar(Alt))
df_mutation <- df_mutation %>% dplyr::mutate(
Mut_type = ifelse(Mut_type == "snp", "snv", Mut_type))
df_mutation <- df_mutation %>% dplyr::mutate(
Alt_length = (((Alt_length_1 - Alt_length_2) +
abs(Alt_length_1 - Alt_length_2)) / 2) +
Alt_length_2,
Ref_ins = ifelse(Mut_type == "ins", PRE_ins, ""),
Ref_del = ifelse(Mut_type == "del", paste(PRE_del, Ref, sep = ""), ""),
Ref_snv = ifelse(Mut_type == "snv", Ref, ""),
Alt_ins = ifelse(Mut_type == "ins", paste(PRE_ins, Alt, sep = ""), ""),
Alt_del = ifelse(Mut_type == "del", PRE_del, ""),
Alt_snv = ifelse(Mut_type == "snv", Alt, ""))
df_mutation <- df_mutation %>% dplyr::mutate(
Alt_indel = paste(Alt_ins, Alt_del, Alt_snv, sep = ""),
Ref_indel = paste(Ref_ins, Ref_del, Ref_snv, sep = ""))
df_mutation <- df_mutation %>% dplyr::mutate(
Neighbor_start_1 = as.integer(Start) - 20,
Neighbor_end_1 = as.integer(Start) - 1,
Neighbor_start_2 = as.integer(End) + 1,
Neighbor_end_2 = as.integer(End) + 20)
df_mutation <- df_mutation %>% dplyr::mutate(
Pre_Neighbor = fun_genome_2(Chr, Neighbor_start_1, Neighbor_end_1),
Post_Neighbor = fun_genome_2(Chr, Neighbor_start_2, Neighbor_end_2))
df_mutation <- df_mutation %>% dplyr::mutate(
Neighborhood_sequence =
ifelse(
Mut_type == "ins",
paste(Pre_Neighbor, Alt_indel, POST_ins,
str_sub(Post_Neighbor, 1, 19), sep = ""),
ifelse(
Mut_type == "del",
paste(Pre_Neighbor, Post_Neighbor, sep = ""),
paste(Pre_Neighbor, Alt, Post_Neighbor, sep = ""))))
df_mutation <- df_mutation %>% dplyr::mutate(
Mut_type = paste(Alt_length, "-", Mut_type, sep = ""),
Ref = Ref_indel,
Alt = Alt_indel,
Pos = ifelse(str_detect(Mut_type, pattern = "del"), Pos - 1, Pos)
)
df_mutation <- df_mutation %>% dplyr::select(
-PRE_del, -PRE_ins, -POST_ins, -Alt_length_1, -Alt_length_2,
-Alt_length, -Ref_ins, -Ref_del, -Ref_snv, -Alt_ins, -Alt_del, -Alt_snv,
-Alt_indel, -Ref_indel, -Neighbor_start_1, -Neighbor_start_2,
-Neighbor_end_1, -Neighbor_end_2,
-Pre_Neighbor, -Post_Neighbor,
-Hugo_Symbol, -Start_Position, -End_Position, -Variant_Type,
-Reference, -Tumor_Seq, -Protein_Change, -Start, -End)
return(df_mutation)
}
NULL |
if (requiet("testthat") &&
requiet("insight") &&
requiet("stats") &&
requiet("parameters")) {
.runThisTest <- Sys.getenv("RunAllinsightTests") == "yes"
if (packageVersion("parameters") >= "0.14.0") {
test_that("standardize_names works", {
set.seed(123)
lm_mod <- lm(wt ~ mpg, mtcars)
x <- as.data.frame(parameters::model_parameters(lm_mod))
expect_equal(
names(standardize_names(x, style = "broom")),
c(
"term", "estimate", "std.error", "conf.level", "conf.low", "conf.high",
"statistic", "df.error", "p.value"
)
)
expect_equal(
names(standardize_names(x, style = "easystats")),
c(
"Parameter", "Coefficient", "SE", "CI", "CI_low", "CI_high",
"Statistic", "df", "p"
)
)
aov_mod <- aov(wt ~ mpg, mtcars)
y <- as.data.frame(parameters::model_parameters(aov_mod))
expect_equal(
names(standardize_names(y, style = "broom")),
c("term", "sumsq", "df", "meansq", "statistic", "p.value")
)
})
z <- as.data.frame(parameters::model_parameters(t.test(1:10, y = c(7:20))))
chi <- as.data.frame(parameters::model_parameters(chisq.test(matrix(c(12, 5, 7, 7), ncol = 2))))
}
} |
decrypt <- function(input, output = NULL, passphrase = NULL, verbosity = 1) {
if (missing(input)) {
stop("Check the input argument, it seems to be missing. There's nothing to decrypt.")
}
if (!file.exists(input)) {
stop("Check the input argument, the file name doesn't exist. There's nothing to decrypt.")
}
if (is.null(output)) {
output <- gsub(".gpg|.asc", "", input)
}
if (file.exists(output)) {
stop("Check the output argument, the file name is already in use! The decrypted file may already exist, or you need to specify a new output file name.")
}
if (.Platform$OS.type == "unix") {
tty <- "--no-tty"
} else{
tty <- NULL
}
if (!(verbosity %in% c(0, 1, 2, 3)) ||
length(verbosity %in% c(0, 1, 2, 3)) == 0) {
stop("Check the verbosity argument. You've used an invalid value.")
}
verbosity <- switch(
as.character(verbosity),
"0" = "--quiet",
"1" = NULL,
"2" = "--verbose",
"3" = "--verbose --verbose"
)
if (is.null(passphrase)) {
command <- "gpg"
system2.args <- c("--output", output, "--decrypt", verbosity, input)
} else{
command <- "echo"
system2.args <- c(
paste(passphrase, "|", sep = ""),
"gpg",
"--passphrase-fd 0",
"--batch",
tty,
"--output",
output,
"--decrypt",
verbosity,
input
)
}
if (.Platform$OS.type == "unix") {
what <- "system2"
args <- list(command = command, args = system2.args)
} else {
what <- "shell"
args <- list(cmd = paste(command,
paste(system2.args, collapse = " "),
collapse = " "
)
)
}
do.call(what = what, args = args)
} |
x_Obj = function(D,model){
D_om = orth_D(D,model,'om')
D_test = orth_D(D_om,model,'test');
D_om_ = c2m(D_om)
df_D_om = c2df(D_om)
df_D_test = c2df(D_test)
linregEst_ =linregEst(c2m(D),D_om_)
Beta_D = linregEst_$BetaU
VmodelDivS_D = linregEst_$VmodelDivS
VextraDivS1_D = linregEst_$VextraDivS1
xObj2 = linregStart(D_om_)
xObj1 = list(df_error = nrow(xObj2$Umodel) - ncol(xObj2$Umodel),
D=D,
D_test = D_test,
D_om = D_om,
df_D_om = df_D_om,
df_D_test = df_D_test,
Beta_D = Beta_D,
VmodelDivS_D = VmodelDivS_D,
VextraDivS1_D = VextraDivS1_D,
termNames = attr(model,"dimnames")[[1]]
)
c(xObj1,xObj2)
}
orth_D = function(D,model,method){
Dorth = vector("list",nrow(model))
if(length(D)!= nrow(model))
return(Dorth)
for(i in 1:nrow(model)){
d = D[[i]]
d_adj = d[,numeric(0)]
for(j in 1:nrow(model)){
switch(method,
test = {if(min( model[j,] - model[i,]) < 0 ) d_adj = cbind(d_adj,D[[j]])},
om = {if( (min( model[j,] - model[i,]) < 0 ) & (max( model[j,] - model[i,]) <= 0) ) d_adj = cbind(d_adj,D[[j]])})
}
Dorth[[i]] = adjust(d,d_adj)
}
Dorth
} |
get_Brier_score <- function(actual, predicted){
n <- length(actual)
n_1 <- length(actual==1)
n_0 <- length(actual==0)
sum <- 0
sum_0 <- 0
sum_1 <- 0
for (i in seq(1,n,1)){
diff <- abs((predicted[i]-actual[i]))^2
sum <- sum+diff
if(actual[i]==0){
sum_0 <- sum_0+diff
}
else
if(actual[i]==1){
sum_1 <- sum_1+diff
}
}
return(list(brier=sum/n, brier_1=sum_1/n_1, brier_0=sum_0/n_0))
} |
mvTqmc <- function(l, u, Sig, df, n = 1e5){
d <- length(l)
if (length(u) != d | d != sqrt(length(Sig)) | any(l > u)) {
stop("l, u, and Sig have to match in dimension with u>l")
}
if(d == 1L){
return(list(prob = pt(q = u/sqrt(Sig[1]), df = df) - pt(q = l/sqrt(Sig[1]), df = df), err = NA, relErr = NA, upbnd = NA))
}
out <- cholperm(Sig, l, u)
D <- diag(out$L)
if (any(D < 1e-10)) {
warning("Method may fail as covariance matrix is singular!")
}
L <- out$L/D - diag(d)
u <- out$u/D
l <- out$l/D
x0 <- rep(0, 2*d)
x0[2*d] <- sqrt(df)
x0[d] <- log(x0[2*d])
solvneq <- nleqslv::nleqslv(x = x0, fn = gradpsiT, L = L, l = l, u = u, nu = df,
global = "pwldog", method = "Broyden")
soln <- solvneq$x
exitflag <- solvneq$termcd
if(!(exitflag %in% c(1,2)) || !all.equal(solvneq$fvec, rep(0, length(x0)))){
warning('Did not find a solution to the nonlinear system in `mvTqmc`!')
}
soln[d] <- exp(soln[d])
x <- soln[1:d]
mu <- soln[(d+1):length(soln)]
p <- rep(0, 12)
for(i in 1:12){
p[i] <- mvtprqmc(ceiling(n/12), L = L, l = l, u = u, nu = df, mu = mu)
}
est.prob <- mean(p)
est.relErr <- sd(p)/(sqrt(12) * est.prob)
est.upbnd <- psyT(x = x, L = L, l = l, u = u, nu = df, mu = mu)
if(est.upbnd < -743){
warning('Natural log of probability is less than -743, yielding 0 after exponentiation!')
}
est.upbnd <- exp(est.upbnd)
list(prob = est.prob, relErr = est.relErr, upbnd = est.upbnd)
} |
print.to.file <- function(dirname, funcname, data, filename) {
user <- system('whoami', intern = T);
out.filename <- 'data-df.tsv';
date <- as.character(Sys.Date());
numeric.data <- c();
num.numeric <- 0;
num.factor <- 0;
num.integer <- 0;
num.rows <- 0;
num.cols <- 0;
if (is.null(filename)) {
filename <- 'None';
}
if (class(data) == 'list') {
num.numeric <- length(data);
numeric.data <- unlist(data);
num.rows <- length(data[[1]]);
num.cols <- length(data);
}
else if (class(data) == 'numeric') {
num.numeric <- 1;
numeric.data <- data;
num.rows <- length(data);
num.cols <- 1;
}
else if (class(data) == 'data.frame' || class(data) == 'matrix') {
num.rows <- nrow(data);
num.cols <- ncol(data);
for (i in 1:num.cols) {
if (class(data[, i]) == 'numeric') {
num.numeric <- num.numeric + 1;
numeric.data <- c(numeric.data, data[, i]);
}
else if (class(data[, i]) == 'integer') {
num.integer <- num.integer + 1;
}
else if (class(data[, i]) == 'factor') {
num.factor <- num.factor + 1;
}
}
}
df.to.add <- NULL;
if (num.numeric == 0) {
df.to.add <- data.frame(user = c(user), filename = c(filename), date = date, func.name = c(funcname),
data.type = c(class(data)), nrow = num.rows, ncol = num.cols, numeric = c(num.numeric),
factor = c(num.factor), integer = c(num.integer), max = c(0), min = c(0), median = c(0));
}
else {
df.to.add <- data.frame(user = c(user), filename = c(filename), date = date, func.name = c(funcname),
data.type = c(class(data)), nrow = num.rows, ncol = num.cols, numeric = c(num.numeric),
factor = c(num.factor), integer = c(num.integer), max = c(max(numeric.data, na.rm = T)),
min = c(min(numeric.data, na.rm = T)), median = c(median(numeric.data, na.rm = T)));
}
if (!is.null(df.to.add)) {
if (!file.exists(paste(dirname, out.filename, sep = '/'))) {
write.table(df.to.add, paste(dirname, out.filename, sep = '/'), sep = '\t', row.names = F, col.names = T);
}
else {
datainfo.dataframe <- read.table(paste(dirname, out.filename, sep = '/'), header = T, fill = T);
index = -1;
for(i in 1:nrow(datainfo.dataframe)) {
if(datainfo.dataframe[i,]$user == user && datainfo.dataframe[i,]$filename == filename && datainfo.dataframe[i,]$date == date) {
index = i;
}
}
if (index != -1) {
datainfo.dataframe[index, ] <- df.to.add;
write.table(datainfo.dataframe, paste(dirname, out.filename, sep = '/'), sep = '\t', row.names = F, col.names = T);
}
else {
write.table(df.to.add, paste(dirname, out.filename, sep = '/'), sep = '\t', row.names = F, col.names = F, append = T);
}
}
}
} |
classif.gkam=function(formula,data, weights = "equal", family = binomial(),
par.metric = NULL,par.np=NULL, offset=NULL,prob=0.5,type= "1vsall",
control = NULL,...){
if (is.null(control)) control =list(maxit = 100,epsilon = 0.001, trace = FALSE, inverse="solve")
C<-match.call()
a<-list()
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula","family","data","weigths","par.metric","par.np","offset","control"), names(mf),0L)
tf <- terms.formula(formula)
terms <- attr(tf, "term.labels")
nt <- length(terms)
if (attr(tf, "response") > 0) {
response <- as.character(attr(tf, "variables")[2])
pf <- rf <- paste(response, "~", sep = "")
} else pf <- rf <- "~"
newy<-y<-data$df[[response]]
nobs <- if (is.matrix(y)) nrow(y)
else length(y)
if (!is.factor(y)) y<-as.factor(y)
n<-length(y)
newdata<-data
ny<-levels(y)
probs<-ngroup<-nlevels(y)
prob.group<-array(NA,dim=c(n,ngroup))
colnames(prob.group)<-ny
if (is.character(weights)) {
weights<-weights4class(y,type=weights)
} else {
if (length(weights)!=n)
stop("length weights != length response")
}
if (ngroup==2) {
newy<-ifelse(y==ny[1],0,1)
newdata$df[[response]]<-newy
a[[1]]<-fregre.gkam(formula,family=family,data=newdata,weights=weights,par.metric=par.metric,
par.np=par.np,offset=offset,control=control)
out2glm <- classif2groups(a,y,prob,ny)
} else {
a<-list()
if (type == "majority"){
cvot<-combn(ngroup,2)
nvot<-ncol(cvot)
votos<-matrix(0,n,ngroup)
colnames(votos) <- ny
class(data)<-c("ldata","list")
b0<-list()
for (ivot in 1:nvot) {
ind1 <- y==ny[cvot[1,ivot]]
ind2 <- y==ny[cvot[2,ivot]]
i2a2 <- ind1 | ind2
newy<-rep(NA,n)
newy[ind1 ]<- 1
newy[ind2 ]<- 0
newdata<-data
newdata$df[response] <- newy
newdata<-subset(newdata,i2a2)
class(newdata)<-c("list")
a[[ivot]]<-fregre.gkam(formula,family=family,data=newdata
, weigths=weights[i2a2], par.metric=par.metric
,par.np=par.np,offset=offset,control=control,...)
prob.log <- a[[ivot]]$fitted.values > prob
votos[i2a2, cvot[1,ivot]] <- votos[i2a2, cvot[1,ivot]] + as.numeric(prob.log)
votos[i2a2, cvot[2,ivot]] <- votos[i2a2, cvot[2,ivot]] + as.numeric(!prob.log)
}
out2glm<-classifKgroups(y,votos,ny)
}
else {
prob.group<-array(NA,dim=c(n,ngroup))
colnames(prob.group)<-ny
for (i in 1:ngroup) {
igroup <- y==ny[i]
newy<-ifelse(igroup, 1, 0)
weights0 <- weights
newdata$df[response]<-newy
a[[i]]<-fregre.gkam(formula,family=family,data=newdata,weigths=weights0
,par.metric=par.metric,par.np=par.np
,offset=offset,control=control,...)
prob.group[,i]<-a[[i]]$fitted.values
}
out2glm<-classifKgroups(y,prob.group,ny)
}
}
yest <- out2glm$yest
prob.group <- out2glm$prob.group
max.prob=mean(yest==y)
output<-list(formula=formula,data=data,group=y,group.est=yest,
prob.classification=out2glm$prob1,prob.group=prob.group,C=C,
m=m,max.prob=max.prob,fit=a,prob = prob,type=type)
class(output) <- "classif"
return(output)
} |
find_chaos <- function(data, window_length, skip_window, skip_test01 = 1, test01_thresh = 0.05, find_thresh = 20) {
test01_res = test_chaos01_mw(data, window_length, skip_window, skip_test01, test01_thresh)
chaos_borders <- find_chaotic_borders(test01_res)
chaos_borders_final <- optimize_chaos(find_thresh, test01_thresh, chaos_borders, test01_res, data, skip_window, window_length,
skip_test01)
return(do.call(cbind, chaos_borders_final))
}
find_chaotic_borders <- function(test01_res) {
test01res_ <- test01_res$test01_res
left_borders_temp <- vector(mode = "numeric", length = 0)
right_borders_temp <- vector(mode = "numeric", length = 0)
if (test01res_[1] == 1) {
left_borders_temp <- 1
}
for (a in 1:(length(test01res_) - 1)) {
if (test01res_[a] == 1 & test01res_[a + 1] < 1) {
right_borders_temp <- c(right_borders_temp, a)
} else if (test01res_[a] < 1 & test01res_[a + 1] == 1) {
left_borders_temp <- c(left_borders_temp, a + 1)
}
}
if (test01res_[length(test01res_) - 1] == 1 & test01res_[length(test01res_)] == 1) {
right_borders_temp <- c(right_borders_temp, length(test01res_))
} else if (test01res_[length(test01res_) - 1] < 1 & test01res_[length(test01res_)] == 1) {
right_borders_temp <- c(right_borders_temp, length(test01res_))
}
return(list(left_borders_temp, right_borders_temp))
}
optimize_chaos <- function(find_thresh, test01_thresh = 0.05, chaos_borders_temp, test01_res, data, skip_window, window_length,
skip_test01) {
if ((length(chaos_borders_temp[[1]]) == 0) && (length(chaos_borders_temp[[2]]) == 0)) {
chaos_borders_final <- chaos_borders_temp
} else {
if ((chaos_borders_temp[[1]][1] == 1) && (chaos_borders_temp[[2]][1] == length(test01_res$test01_res))) {
chaos_borders_final <- c(1, length(data))
} else {
chaos_borders_final <- optimize_chaos_run(find_thresh, test01_thresh, chaos_borders_temp, data,
skip_window, window_length, skip_test01)
}
}
return(chaos_borders_final)
}
optimize_chaos_run <- function(find_thresh, test01_thresh = 0.05, chaos_borders_temp, data, skip_window, window_length, skip_test01) {
right_borders_final <- vector(mode = "numeric", length = 0)
left_borders_final <- vector(mode = "numeric", length = 0)
length_of_data = length(data)
intervals_middles <- seq(1, length(data) - window_length, skip_window) + round(window_length/2)
if (chaos_borders_temp[[1]][1] == 1) {
left_borders_final <- 1
reg_int2check <- c(intervals_middles[chaos_borders_temp[[2]][1]], intervals_middles[chaos_borders_temp[[2]][1] +
1])
middle <- round((reg_int2check[2] + reg_int2check[1])/2)
interval <- c(round(middle - window_length/2), round(middle + window_length/2))
size_interval <- reg_int2check[2] - reg_int2check[1]
while (size_interval > find_thresh) {
test_series <- data[seq(interval[1], interval[2], skip_test01)]
res <- Chaos01::testChaos01(test_series, c.gen = "equal", par = "seq")
if (res > (1 - test01_thresh)) {
reg_int2check <- c(middle, reg_int2check[2])
} else {
reg_int2check <- c(reg_int2check[1], middle)
}
middle <- round((reg_int2check[2] + reg_int2check[1])/2)
interval <- c(round(middle - window_length/2), round(middle + window_length/2))
size_interval <- reg_int2check[2] - reg_int2check[1]
}
right_borders_final <- reg_int2check[2]
}
if (chaos_borders_temp[[1]][1] == 1) {
aa <- 2
} else {
aa <- 1
}
if (chaos_borders_temp[[2]][length(chaos_borders_temp[[2]])] == length(intervals_middles)) {
bb <- length(chaos_borders_temp[[2]]) - 1
} else {
bb <- length(chaos_borders_temp[[2]])
}
while (aa <= bb) {
reg_int2check <- c(intervals_middles[chaos_borders_temp[[2]][aa]], intervals_middles[chaos_borders_temp[[2]][aa] +
1])
middle <- round((reg_int2check[2] + reg_int2check[1])/2)
interval <- c(round(middle - window_length/2), round(middle + window_length/2))
size_interval <- reg_int2check[2] - reg_int2check[1]
while (size_interval > find_thresh) {
test_series <- data[seq(interval[1], interval[2], skip_test01)]
res <- Chaos01::testChaos01(test_series, c.gen = "equal", par = "seq")
if (res > (1 - test01_thresh)) {
reg_int2check <- c(middle, reg_int2check[2])
} else {
reg_int2check <- c(reg_int2check[1], middle)
}
middle <- round((reg_int2check[2] + reg_int2check[1])/2)
interval <- c(round(middle - window_length/2), round(middle + window_length/2))
size_interval <- reg_int2check[2] - reg_int2check[1]
}
right_borders_final <- c(right_borders_final, reg_int2check[2])
reg_int2check <- c(intervals_middles[chaos_borders_temp[[1]][aa] - 1], intervals_middles[chaos_borders_temp[[1]][aa]])
middle <- round((reg_int2check[2] + reg_int2check[1])/2)
interval <- c(round(middle - window_length/2), round(middle + window_length/2))
size_interval <- reg_int2check[2] - reg_int2check[1]
while (size_interval > find_thresh) {
test_series <- data[seq(interval[1], interval[2], skip_test01)]
res <- Chaos01::testChaos01(test_series, c.gen = "equal", par = "seq")
if (res < (1 - test01_thresh)) {
reg_int2check <- c(middle, reg_int2check[2])
} else {
reg_int2check <- c(reg_int2check[1], middle)
}
middle <- round((reg_int2check[2] + reg_int2check[1])/2)
interval <- c(round(middle - window_length/2), round(middle + window_length/2))
size_interval <- reg_int2check[2] - reg_int2check[1]
}
left_borders_final <- c(left_borders_final, reg_int2check[1])
aa = aa + 1
}
if (chaos_borders_temp[[2]][length(chaos_borders_temp[[2]])] == length(intervals_middles)) {
right_borders_final <- c(right_borders_final, length_of_data)
reg_int2check <- c(intervals_middles[chaos_borders_temp[[1]][length(chaos_borders_temp[[1]])] - 1], intervals_middles[chaos_borders_temp[[1]][length(chaos_borders_temp[[1]])]])
middle <- round((reg_int2check[2] + reg_int2check[1])/2)
interval <- c(round(middle - window_length/2), round(middle + window_length/2))
size_interval <- reg_int2check[2] - reg_int2check[1]
while (size_interval > find_thresh) {
test_series <- data[seq(interval[1], interval[2], skip_test01)]
res <- Chaos01::testChaos01(test_series, c.gen = "equal", par = "seq")
if (res < (1 - test01_thresh)) {
reg_int2check <- c(middle, reg_int2check[2])
} else {
reg_int2check <- c(reg_int2check[1], middle)
}
middle <- round((reg_int2check[2] + reg_int2check[1])/2)
interval <- c(round(middle - window_length/2), round(middle + window_length/2))
size_interval <- reg_int2check[2] - reg_int2check[1]
}
left_borders_final <- c(left_borders_final, reg_int2check[1])
}
return(list(left_borders_final, right_borders_final))
} |
if (requiet("testthat") &&
requiet("parameters") &&
requiet("mice")) {
data("nhanes2")
imp <- mice(nhanes2, printFlag = FALSE)
fit <- with(data = imp, exp = lm(bmi ~ age + hyp + chl))
mp1 <- model_parameters(fit)
mp2 <- summary(pool(fit))
test_that("param", {
expect_equal(mp1$Parameter, as.vector(mp2$term))
})
test_that("coef", {
expect_equal(mp1$Coefficient, mp2$estimate, tolerance = 1e-3)
})
test_that("se", {
expect_equal(mp1$SE, mp2$std.error, tolerance = 1e-3)
})
} |
context("wdpa_fetch")
test_that("country name", {
skip_on_cran()
skip_if_not(curl::has_internet())
skip_on_github_workflow("Windows")
x <- suppressWarnings(wdpa_fetch("Liechtenstein", wait = TRUE))
expect_is(x, "sf")
expect_true(all(x$ISO3 == "LIE"))
})
test_that("ISO3", {
skip_on_cran()
skip_if_not(curl::has_internet())
skip_on_github_workflow("Windows")
x <- suppressWarnings(wdpa_fetch("LIE", wait = TRUE, verbose = TRUE))
expect_is(x, "sf")
expect_true(all(x$ISO3 == "LIE"))
})
test_that("global", {
skip_on_cran()
skip_if_not(curl::has_internet())
skip_if_local_and_slow_internet()
skip_on_github_workflow("Windows")
skip_on_github_workflow("Mac OSX")
x <- suppressWarnings(wdpa_fetch(
"global", wait = TRUE, n = 5, verbose = TRUE))
expect_is(x, "sf")
})
test_that("polygon and point data", {
skip_on_cran()
skip_if_not(curl::has_internet())
skip_if_local_and_slow_internet()
skip_on_github_workflow("Windows")
skip_on_github_workflow("Mac OSX")
x <- suppressWarnings(wdpa_fetch("USA", wait = TRUE))
expect_is(x, "sf")
expect_true(any(vapply(
sf::st_geometry(x), inherits, logical(1), c("POLYGON", "MULTIPOLYGON")
)))
expect_true(any(vapply(
sf::st_geometry(x), inherits, logical(1), c("POINT", "MULTIPOINT")
)))
})
test_that("cache", {
skip_on_cran()
skip_if_not(curl::has_internet())
skip_on_github_workflow("Windows")
x <- wdpa_fetch("MHL", wait = TRUE, force = TRUE)
Sys.sleep(2)
y <- wdpa_fetch("MHL", wait = TRUE, force = FALSE)
expect_is(x, "sf")
expect_equal(x, y)
}) |
setup({
vcr_test_configuration()
})
params <- c(
"record",
"match_requests_on",
"serialize_with",
"persist_with",
"preserve_exact_body_bytes"
)
test_that("default cassette options match default config", {
on.exit({
unlink(vcr_files())
})
vcr_configure(
warn_on_empty_cassette = FALSE
)
config <- VCRConfig$new()
cas1 <- sw(use_cassette("default-use", {}))
expect_identical(
config$as_list()[params],
cas1$cassette_opts[params]
)
cas2 <- insert_cassette("default-insert")
eject_cassette()
expect_identical(
config$as_list()[params],
cas2$cassette_opts[params]
)
})
test_that("cassettes inherit configured options", {
on.exit({
unlink(vcr_files())
vcr_test_configuration()
})
vcr_configure(
record = "none",
match_requests_on = "body",
preserve_exact_body_bytes = TRUE,
warn_on_empty_cassette = FALSE
)
cas1 <- sw(use_cassette("configured-use", {}))
expect_match(cas1$record, "none")
expect_setequal(cas1$match_requests_on, "body")
expect_true(cas1$preserve_exact_body_bytes)
cas2 <- insert_cassette("configured-insert")
eject_cassette()
expect_match(cas2$record, "none")
expect_setequal(cas2$match_requests_on, "body")
expect_true(cas2$preserve_exact_body_bytes)
})
test_that("cassettes can override configured options", {
on.exit({
unlink(vcr_files())
vcr_test_configuration()
})
vcr_configure(
record = "none",
match_requests_on = "body",
preserve_exact_body_bytes = TRUE,
warn_on_empty_cassette = FALSE
)
cas1 <- sw(use_cassette("overridden-use", {},
record = "new_episodes",
match_requests_on = "query",
preserve_exact_body_bytes = FALSE
))
expect_match(cas1$record, "new_episodes")
expect_setequal(cas1$match_requests_on, "query")
expect_false(cas1$preserve_exact_body_bytes)
cas2 <- insert_cassette("overridden-insert",
record = "new_episodes",
match_requests_on = "query",
preserve_exact_body_bytes = FALSE
)
eject_cassette()
expect_match(cas2$record, "new_episodes")
expect_setequal(cas2$match_requests_on, "query")
expect_false(cas2$preserve_exact_body_bytes)
}) |
test_that("Bibliographies are correctly read ", {
empty_bib <- dplyr::tribble(
~TITLE, ~AUTHOR, ~JOURNAL, ~BIBTEXKEY, ~YEAR, ~DOI
)
expect_error(drop_name(bib = empty_bib, cite_key = "Eschrich1983"), "is empty")
bib_path <- system.file("testdata", "sample.bib", package = "namedropR")
expect_error(drop_name(bib = "wrong_file_path", cite_key = "Eschrich1983"), "file not found")
expect_error(drop_name(bib = 123), "Inappropriate type of bibliography")
expect_error(drop_name(cite_key = "Eschrich1983"), "No bibliography")
good_bib <- system.file("testdata", "good.bib", package = "namedropR")
expect_message(
expect_message(
drop_name(bib = good_bib, cite_key = "Eschrich1983"),
"Years coerced to string format."
),
"Bibliography file successfully read."
)
})
test_that("compact mode returns a correct file path", {
slim_bib <- dplyr::tribble(
~TITLE, ~AUTHOR, ~JOURNAL, ~BIBTEXKEY, ~DATE,
"Some 2022", c("Alice", "Bob", "Charlie"), "Journal of Unnecessary R Packages", "Alice2022", "2022"
)
expect_equal(
drop_name(bib = slim_bib, cite_key = "Alice2022", output_dir = tempdir(), style = "compact"),
paste0(tempdir(), "/Alice2022.html")
)
})
test_that("biblatex files produce an output", {
bib_tbl <- dplyr::tribble(
~TITLE, ~AUTHOR, ~JOURNALTITLE, ~BIBTEXKEY, ~DATE, ~URL,
"Some 2022", c("Alice", "Bob", "Charlie"), "Journal of Unnecessary R Packages", "Alice2022", "2022", "https://en.wikipedia.org"
)
expect_equal(
drop_name(bib = bib_tbl, cite_key = "Alice2022", output_dir = tempdir()),
paste0(tempdir(), "/Alice2022.html")
)
bib_tbl2 <- dplyr::tribble(
~TITLE, ~AUTHOR, ~JOURNALTITLE, ~BIBTEXKEY, ~DATE, ~YEAR, ~URL,
"Some 2022", c("Alice", "Bob", "Charlie"), "Journal of Unnecessary R Packages", "Alice2022", "2022-01-01", NA, "https://en.wikipedia.org",
"Some 2023", c("Alice", "Bob", "Charlie"), "Journal of Unnecessary R Packages", "Alice2023", NA, "2023", "https://en.wikipedia.org"
)
expect_equal(
suppressMessages(drop_name(bib = bib_tbl2, output_dir = tempdir())),
c(
paste0(tempdir(), "/Alice2022.html"),
paste0(tempdir(), "/Alice2023.html")
)
)
})
test_that("missing DOI and URL columns are properly handled", {
slim_bib <- dplyr::tribble(
~TITLE, ~AUTHOR, ~JOURNAL, ~BIBTEXKEY, ~DATE,
"Some 2022", c("Alice", "Bob", "Charlie"), "Journal of Unnecessary R Packages", "Alice2022", "2022"
)
expect_equal(
drop_name(bib = slim_bib, cite_key = "Alice2022", output_dir = tempdir()),
paste0(tempdir(), "/Alice2022.html")
)
})
test_that("all required columns are enforced", {
missing_cols <- dplyr::tribble(
~TITLE, ~JOURNAL, ~BIBTEXKEY, ~YEAR, ~DOI,
"One", "Three", "Four", "2021", "Six"
)
expect_error(drop_name(missing_cols, cite_key = "Four"))
})
test_that("bulk operations work properly", {
bulk_data <- dplyr::tribble(
~TITLE, ~AUTHOR, ~JOURNAL, ~BIBTEXKEY, ~YEAR, ~DOI,
"Title1", c("Alice1", "Bob1", "Charlie1"), "JoURP1", "Alice2021", "2021", "someDOI1",
"Title2", c("Alice2", "Bob2", "Charlie2"), "JoURP2", "Alice2022", "2022", "someDOI2",
"Title3", c("Alice3", "Bob3", "Charlie3"), "JoURP3", "Alice2023", "2023", "someDOI3",
"Title4", c("Alice4", "Bob4", "Charlie4"), "JoURP4", "Alice2024", "2024", "someDOI4"
)
bulk_res1 <- evaluate_promise(drop_name(bib = bulk_data, output_dir = tempdir()))
expect_equal(length(bulk_res1$result), 4)
expect_message(drop_name(bib = bulk_data, output_dir = tempdir()), "No cite_key specified.")
bulk_res2 <- evaluate_promise(drop_name(bib = bulk_data, cite_key = c("Alice2021", "Alice2023"), output_dir = tempdir()))
expect_equal(length(bulk_res2$result), 2)
bulk_res3 <- evaluate_promise(drop_name(bib = bulk_data, cite_key = c("Alice2022", "Alice2024", "Bob2019"), output_dir = tempdir()))
expect_equal(length(bulk_res3$result), 2)
expect_true(bulk_res3$warnings == "The following cite_key items were not found in the provided library: Bob2019")
bulk_res4 <- evaluate_promise(drop_name(bib = bulk_data, cite_key = c("Bob1", "Bob2", "Bob3"), output_dir = tempdir()))
expect_equal(bulk_res4$warnings[2], "No reference matches the given cite_keys. Please check that citation key(s) are correct.")
expect_error(drop_name(bib = bulk_data, cite_key = c(1, 1, 2, 3, 5, 8), output_dir = tempdir()), "cite_key must be of type 'caracter'")
bulk_data_dup <- dplyr::tribble(
~TITLE, ~AUTHOR, ~JOURNAL, ~BIBTEXKEY, ~YEAR, ~DOI,
"Title1", c("Alice1", "Bob1", "Charlie1"), "JoURP1", "Alice2021", "2021", "someDOI1",
"Title1", c("Alice2", "Bob2", "Charlie2"), "JoURP1", "Alice2021", "2021", "someDOI3",
)
expect_warning(drop_name(bib = bulk_data_dup, cite_key = "Alice2021", output_dir = tempdir()), "BIBTEX keys are not unique")
})
test_that("output_dir is properly checked and/or created", {
sample_data <- dplyr::tribble(
~TITLE, ~AUTHOR, ~JOURNAL, ~BIBTEXKEY, ~YEAR, ~DOI,
"Title1", c("Alice1", "Bob1", "Charlie1"), "JoURP1", "Alice2021", "2021", "someDOI1",
)
expect_error(drop_name(bib = sample_data, output_dir = TRUE))
expect_error(drop_name(bib = sample_data, output_dir = 5))
})
test_that("use_xaringan is properly checked", {
sample_data <- dplyr::tribble(
~TITLE, ~AUTHOR, ~JOURNAL, ~BIBTEXKEY, ~YEAR, ~DOI,
"Title1", c("Alice1", "Bob1", "Charlie1"), "JoURP1", "Alice2021", "2021", "someDOI1",
)
expect_error(drop_name(bib = sample_data, use_xaringan = 987))
})
test_that("use_xaringan creates the correct folders (qr/ in working dir)", {
sample_data <- dplyr::tribble(
~TITLE, ~AUTHOR, ~JOURNAL, ~BIBTEXKEY, ~YEAR, ~DOI,
"Title1", c("Alice1", "Bob1", "Charlie1"), "JoURP1", "Alice2021", "2021", "someDOI1",
)
unlink(here::here("visual_citations"), recursive = TRUE)
unlink(here::here("qr"), recursive = TRUE)
drop_name(bib = sample_data, export_as = "html", cite_key = "Alice2021", use_xaringan = TRUE)
expect_true(dir.exists(here::here("visual_citations")))
expect_true(dir.exists(here::here("qr")))
unlink(here::here("visual_citations"), recursive = TRUE)
unlink(here::here("qr"), recursive = TRUE)
drop_name(bib = sample_data, export_as = "html_full", cite_key = "Alice2021", use_xaringan = TRUE)
expect_true(dir.exists(here::here("visual_citations")))
expect_true(dir.exists(here::here("qr")))
unlink(here::here("visual_citations"), recursive = TRUE)
unlink(here::here("qr"), recursive = TRUE)
}) |
SDMXAttribute <- function(xmlObj, namespaces){
messageNs <- findNamespace(namespaces, "message")
strNs <- findNamespace(namespaces, "structure")
sdmxVersion <- version.SDMXSchema(xmlDoc(xmlObj), namespaces)
VERSION.21 <- sdmxVersion == "2.1"
conceptRef = xmlGetAttr(xmlObj, "conceptRef")
if(is.null(conceptRef)) conceptRef <- as.character(NA)
conceptVersion = xmlGetAttr(xmlObj, "conceptVersion")
if(is.null(conceptVersion)) conceptVersion <- as.character(NA)
conceptAgency = xmlGetAttr(xmlObj, "conceptAgency")
if(is.null(conceptAgency)) conceptAgency <- as.character(NA)
conceptSchemeRef = xmlGetAttr(xmlObj, "conceptSchemeRef")
if(is.null(conceptSchemeRef)) conceptSchemeRef <- as.character(NA)
conceptSchemeAgency = xmlGetAttr(xmlObj, "conceptSchemeAgency")
if(is.null(conceptSchemeAgency)) conceptSchemeAgency <- as.character(NA)
codelist = xmlGetAttr(xmlObj, "codelist")
if(is.null(codelist)) codelist <- as.character(NA)
codelistVersion = xmlGetAttr(xmlObj, "codelistVersion")
if(is.null(codelistVersion)) codelistVersion <- as.character(NA)
codelistAgency = xmlGetAttr(xmlObj, "codelistAgency")
if(is.null(codelistAgency)) codelistAgency <- as.character(NA)
attachmentLevel = xmlGetAttr(xmlObj, "attachmentLevel")
if(is.null(attachmentLevel)) attachmentLevel <- as.character(NA)
assignmentStatus = xmlGetAttr(xmlObj, "assignmentStatus")
if(is.null(assignmentStatus)) assignmentStatus <- as.character(NA)
isTimeFormat = xmlGetAttr(xmlObj, "isTimeFormat")
if(is.null(isTimeFormat)){
isTimeFormat <- FALSE
}else{
isTimeFormat <- as.logical(isTimeFormat)
}
crossSectionalAttachDataset = xmlGetAttr(xmlObj, "crossSectionalAttachDataset")
if(is.null(crossSectionalAttachDataset)){
crossSectionalAttachDataset <- NA
}else{
crossSectionalAttachDataset <- as.logical(crossSectionalAttachDataset)
}
crossSectionalAttachGroup = xmlGetAttr(xmlObj, "crossSectionalAttachGroup")
if(is.null(crossSectionalAttachGroup)){
crossSectionalAttachGroup <- NA
}else{
crossSectionalAttachGroup <- as.logical(crossSectionalAttachGroup)
}
crossSectionalAttachSection = xmlGetAttr(xmlObj, "crossSectionalAttachSection")
if(is.null(crossSectionalAttachSection)){
crossSectionalAttachSection <- NA
}else{
crossSectionalAttachSection <- as.logical(crossSectionalAttachSection)
}
crossSectionalAttachObservation = xmlGetAttr(xmlObj,
"crossSectionalAttachObservation")
if(is.null(crossSectionalAttachObservation)){
crossSectionalAttachObservation <- NA
}else{
crossSectionalAttachObservation <- as.logical(crossSectionalAttachObservation)
}
isEntityAttribute = xmlGetAttr(xmlObj, "isEntityAttribute")
if(is.null(isEntityAttribute)){
isEntityAttribute <- FALSE
}else{
isEntityAttribute <- as.logical(isEntityAttribute)
}
isNonObservationTimeAttribute = xmlGetAttr(xmlObj,
"isNonObservationTimeAttribute")
if(is.null(isNonObservationTimeAttribute)){
isNonObservationTimeAttribute <- FALSE
}else{
isNonObservationTimeAttribute <- as.logical(isNonObservationTimeAttribute)
}
isCountAttribute = xmlGetAttr(xmlObj, "isCountAttribute")
if(is.null(isCountAttribute)){
isCountAttribute <- FALSE
}else{
isCountAttribute <- as.logical(isCountAttribute)
}
isFrequencyAttribute = xmlGetAttr(xmlObj, "isFrequencyAttribute")
if(is.null(isFrequencyAttribute)){
isFrequencyAttribute <- FALSE
}else{
isFrequencyAttribute <- as.logical(isFrequencyAttribute)
}
isIdentityAttribute = xmlGetAttr(xmlObj, "isIdentityAttribute")
if(is.null(isIdentityAttribute)){
isIdentityAttribute <- FALSE
}else{
isIdentityAttribute <- as.logical(isIdentityAttribute)
}
obj<- new("SDMXAttribute",
conceptRef = conceptRef,
conceptVersion = conceptVersion,
conceptAgency = conceptAgency,
conceptSchemeRef = conceptSchemeRef,
conceptSchemeAgency = conceptSchemeAgency,
codelist = codelist,
codelistVersion = codelistVersion,
codelistAgency = codelistAgency,
attachmentLevel = attachmentLevel,
assignmentStatus = assignmentStatus,
isTimeFormat = isTimeFormat,
crossSectionalAttachDataset = crossSectionalAttachDataset,
crossSectionalAttachGroup = crossSectionalAttachGroup,
crossSectionalAttachSection = crossSectionalAttachSection,
crossSectionalAttachObservation = crossSectionalAttachObservation,
isEntityAttribute = isEntityAttribute,
isNonObservationTimeAttribute = isNonObservationTimeAttribute,
isCountAttribute = isCountAttribute,
isFrequencyAttribute = isFrequencyAttribute,
isIdentityAttribute = isIdentityAttribute
)
} |
"Interaction2wtRcmdr" <-
function() {
if (length(grep("HH", search()))==0) stop("Please attach the HH directory.")
initializeDialog(title=gettextRcmdr("Interaction twoway table"))
groupBox <- variableListBox(top, Factors(), title=gettextRcmdr("Factors (pick two or more)"), selectmode="multiple")
responseBox <- variableListBox(top, Numeric(), title=gettextRcmdr("Response Variable (pick one)"))
onOK <- function() {
groups <- getSelection(groupBox)
response <- getSelection(responseBox)
closeDialog()
if (2 > length(groups)) {
errorCondition(recall=Interaction2wtRcmdr, message=gettextRcmdr("Select at least two factors."))
return()
}
if (0 == length(response)) {
errorCondition(recall=Interaction2wtRcmdr, message=gettextRcmdr("No response variable selected."))
return()
}
.activeDataSet <- ActiveDataSet()
i2wt.command <- paste("interaction2wt(",
response, " ~ ", paste(groups, collapse=' + '),
", data=", .activeDataSet,
if ("1" == tclvalue(simpleVariable)) ", simple=TRUE",
')', sep="")
doItAndPrint(i2wt.command)
activateMenus()
tkfocus(CommanderWindow())
}
optionsFrame <- tkframe(top)
buttonsFrame <- tkframe(top)
OKCancelHelp(helpSubject="interaction2wt")
tkgrid(getFrame(groupBox), getFrame(responseBox), sticky="nw")
simpleVariable <- tclVar("0")
simpleFrame <- tkframe(top)
simpleCheckBox <- tkcheckbutton(simpleFrame, variable=simpleVariable)
tkgrid(tklabel(simpleFrame, text=gettextRcmdr("Simple Effects")),
simpleCheckBox, sticky="w")
tkgrid(simpleFrame, sticky="w")
tkgrid(optionsFrame, columnspan=2, sticky="w")
tkgrid(buttonsFrame, columnspan=2, sticky="w")
dialogSuffix(rows=3, columns=2)
} |
setClassUnion("characterOrNULL", c("character", "NULL"))
setClassUnion("sdcProblemOrNULL", c("sdcProblem", "NULL"))
setClassUnion("listOrNull", c("list", "NULL"))
tau_BatchObj <- setClass("tau_BatchObj",
slots = c(
path = "characterOrNULL",
id = "characterOrNULL",
logbook = "characterOrNULL",
microdata = "characterOrNULL",
metadata = "characterOrNULL",
table = "characterOrNULL",
safetyrules = "characterOrNULL",
readInput = "characterOrNULL",
solver = "listOrNull",
suppress = "characterOrNULL",
writetable = "characterOrNULL",
is_table = "logical",
obj = "sdcProblemOrNULL"
),
prototype = list(
path = NULL,
id = NULL,
logbook = NULL,
microdata = NULL,
metadata = NULL,
table = NULL,
safetyrules = NULL,
readInput = NULL,
solver = NULL,
suppress = NULL,
writetable = NULL,
is_table = FALSE,
obj = NULL
),
validity = function(object) {
if (length(object@is_table) != 1) {
stop("length(is_table) != 1\n")
}
if (!is.null(object@solver)) {
if (object@solver$solver == "CPLEX" &&
!file.exists(object@solver$license)) {
stop("No valid licensefile given!\n")
}
}
return(TRUE)
}
)
setGeneric(
name = "setPath",
def = function(obj, f) {
standardGeneric("setPath")
}
)
setGeneric(
name = "setId",
def = function(obj, f) {
standardGeneric("setId")
}
)
setGeneric(
name = "setLogbook",
def = function(obj, f) {
standardGeneric("setLogbook")
}
)
setGeneric(
name = "setMicrodata",
def = function(obj, f) {
standardGeneric("setMicrodata")
}
)
setGeneric(
name = "setMetadata",
def = function(obj, f) {
standardGeneric("setMetadata")
}
)
setGeneric(
name = "setTable",
def = function(obj, f) {
standardGeneric("setTable")
}
)
setGeneric(
name = "setSafetyrules",
def = function(obj, f) {
standardGeneric("setSafetyrules")
}
)
setGeneric(
name = "setReadInput",
def = function(obj, f) {
standardGeneric("setReadInput")
}
)
setGeneric(
name = "setSolver",
def = function(obj, f) {
standardGeneric("setSolver")
}
)
setGeneric(
name = "setSuppress",
def = function(obj, f) {
standardGeneric("setSuppress")
}
)
setGeneric(
name = "setWritetable",
def = function(obj, f) {
standardGeneric("setWritetable")
}
)
setGeneric(
name = "setIs_table",
def = function(obj, f) {
standardGeneric("setIs_table")
}
)
setGeneric(
name = "setObj",
def = function(obj, f) {
standardGeneric("setObj")
}
)
setMethod(
f = "setPath",
signature = "tau_BatchObj",
definition = function(obj, f) {
obj@path <- f
validObject(obj)
return(obj)
}
)
setMethod(
f = "setId",
signature = "tau_BatchObj",
definition = function(obj, f) {
obj@id <- f
validObject(obj)
return(obj)
}
)
setMethod(
f = "setLogbook",
signature = "tau_BatchObj",
definition = function(obj, f) {
obj@logbook <- f
validObject(obj)
return(obj)
}
)
setMethod(
f = "setMicrodata",
signature = "tau_BatchObj",
definition = function(obj, f) {
obj@microdata <- f
validObject(obj)
return(obj)
}
)
setMethod(
f = "setMetadata",
signature = "tau_BatchObj",
definition = function(obj, f) {
obj@metadata <- f
validObject(obj)
return(obj)
}
)
setMethod(
f = "setTable",
signature = "tau_BatchObj",
definition = function(obj, f) {
obj@table <- f
validObject(obj)
return(obj)
}
)
setMethod(
f = "setSafetyrules",
signature = "tau_BatchObj",
definition = function(obj, f) {
obj@safetyrules <- f
validObject(obj)
return(obj)
}
)
setMethod(
f = "setReadInput",
signature = "tau_BatchObj",
definition = function(obj, f) {
obj@readInput <- f
validObject(obj)
return(obj)
}
)
setMethod(
f = "setSolver",
signature = "tau_BatchObj",
definition = function(obj, f) {
obj@solver <- f
validObject(obj)
return(obj)
}
)
setMethod(
f = "setSuppress",
signature = "tau_BatchObj",
definition = function(obj, f) {
obj@suppress <- f
validObject(obj)
return(obj)
}
)
setMethod(
f = "setWritetable",
signature = "tau_BatchObj",
definition = function(obj, f) {
obj@writetable <- f
validObject(obj)
return(obj)
}
)
setMethod(
f = "setIs_table",
signature = "tau_BatchObj",
definition = function(obj, f) {
obj@is_table <- f
validObject(obj)
return(obj)
}
)
setMethod(
f = "setObj",
signature = "tau_BatchObj",
definition = function(obj, f) {
obj@obj <- f
validObject(obj)
return(obj)
}
)
setGeneric(
name = "writeBatchFile",
def = function(obj) {
standardGeneric("writeBatchFile")
}
)
setMethod(
f = "writeBatchFile",
signature = c("tau_BatchObj"),
definition = function(obj) {
is_table <- obj@is_table
path <- obj@path
cmds <- list()
cmds <- append(cmds, "//This batch file was generated by sdcTable")
cmds <- append(cmds, paste("//Date:", Sys.time()))
cmds <- append(cmds, "//")
f_log <- normalizePath(
file.path(path, obj@logbook),
winslash = "/",
mustWork = FALSE
)
f_data <- normalizePath(
file.path(path, obj@microdata),
winslash = "/",
mustWork = TRUE
)
f_metadata <- normalizePath(
file.path(path, obj@metadata),
winslash = "/",
mustWork = TRUE
)
cmds <- append(cmds, paste("<LOGBOOK>", dQuote(f_log)))
if (is_table) {
cmds <- append(cmds, paste("<OPENTABLEDATA>", dQuote(f_data)))
} else {
cmds <- append(cmds, paste("<OPENMICRODATA>", dQuote(f_data)))
}
cmds <- append(cmds, paste("<OPENMETADATA>", dQuote(f_metadata)))
cmds <- append(cmds, paste("<SPECIFYTABLE>", obj@table))
cmds <- append(cmds, paste("<SAFETYRULE>", obj@safetyrules))
cmds <- append(cmds, obj@readInput)
solver <- slot(obj, "solver")$solver
if (solver == "CPLEX") {
f_license <- normalizePath(
slot(obj, "solver")$license,
winslash = "/",
mustWork = TRUE
)
cmds <- append(cmds, paste0("<SOLVER> ", solver, ",", dQuote(f_license)))
} else {
cmds <- append(cmds, paste("<SOLVER>", solver))
}
cmds <- append(cmds, paste("<SUPPRESS>", obj@suppress))
cmds <- append(cmds, paste("<WRITETABLE>", obj@writetable))
f_batch <- generateStandardizedNames(
path = obj@path,
lab = paste0("batch_", obj@id),
ext = ".arb"
)
cmds <- unlist(cmds)
cmds[length(cmds)] <- paste0(cmds[length(cmds)], "\r")
cat(cmds, sep = "\r\n", file = f_batch)
invisible(f_batch)
}
) |
createNote <-
function(labTitle = NULL, pady = c(10, 10)) {
tcltk::tkgrid(tcltk::tklabel(KTSEnv$subPanR4C1, text = labTitle,
font = KTSEnv$KTSFonts$explain,
foreground = "blue"),
padx = c(2, 2),
pady = pady, sticky = "nw", columnspan = 2)
} |
activities <- data.frame(
id = 1:17,
name = paste("a", as.character(1:17), sep=""),
duration = c(1,2,2,4,3,3,3,2,1,1,2,1,1,1,1,2,1)
)
relations <- data.frame(
from = c(1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15),
to = c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 11, 12, 13, 14, 15, 16, 17, 16, 17, 16, 17, 16, 17, 16, 17)
)
vanhoucke2014_project_1 <- function() {
schedule <- Schedule$new(activities, relations)
schedule$title <- "Project 1: Cost Information System"
schedule$reference <- "VANHOUCKE, Mario. Integrated project management and control:
first comes the theory, then the practice.
Gent: Springer, 2014, p. 6"
schedule
}
test_that("Creating a ONE activity schedule with ZERO duration", {
activities <- data.frame(
id = 1,
name = "A",
duration = 0
)
schedule <- Schedule$new(activities)
schedule$title <- "A project"
schedule$reference <- "From criticalpath"
activities <- schedule$activities
expect_equal(schedule$duration, 0)
expect_equal(activities$ES[1], 0)
expect_equal(activities$EF[1], 0)
expect_equal(activities$LS[1], 0)
expect_equal(activities$LF[1], 0)
expect_true(activities$critical[1])
})
test_that("Creating a schedule with ONE activity", {
activities <- data.frame(
id = 1,
name = "A",
duration = 3
)
schedule <- Schedule$new(activities)
schedule$title <- "A project"
schedule$reference <- "From criticalpath"
activities <- schedule$activities
expect_equal(schedule$duration, 3)
expect_equal(activities$ES[1], 0)
expect_equal(activities$EF[1], 3)
expect_equal(activities$LS[1], 0)
expect_equal(activities$LF[1], 3)
expect_true(activities$critical[1])
})
test_that("Creating a schedule only with activities list, without relations", {
activities <- data.frame(
id = c( 1, 2, 3),
name = c("A", "B", "C"),
duration = c( 3, 2, 4)
)
schedule <- Schedule$new(activities)
schedule$title <- "A project"
schedule$reference <- "From criticalpath"
activities <- schedule$activities
expect_equal(schedule$duration, 4)
expect_equal(activities$ES[1], 0)
expect_equal(activities$EF[1], 3)
expect_equal(activities$LS[1], 1)
expect_equal(activities$LF[1], 4)
expect_false(activities$critical[1])
expect_equal(activities$ES[2], 0)
expect_equal(activities$EF[2], 2)
expect_equal(activities$LS[2], 2)
expect_equal(activities$LF[2], 4)
expect_false(activities$critical[2])
expect_equal(activities$ES[3], 0)
expect_equal(activities$EF[3], 4)
expect_equal(activities$LS[3], 0)
expect_equal(activities$LF[3], 4)
expect_true(activities$critical[3])
})
test_that("Schedule duration is 11", {
schedule <- vanhoucke2014_project_1()
expect_equal(schedule$duration, 11)
})
test_that("Schedule critical activities are identified", {
schedule <- vanhoucke2014_project_1()
activities <- schedule$activities
critical_activities <- paste0(activities$id[activities$critical], collapse=",")
expected <- paste0(c(1, 2, 4, 11, 16), collapse = ",")
expect_equal(critical_activities, expected)
})
test_that("Schedule NON critical activities are identified", {
schedule <- vanhoucke2014_project_1()
activities <- schedule$activities
non_critical_activities <- paste0(activities$id[!activities$critical], collapse=",")
expected <- paste0(c(3, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 17), collapse = ",")
expect_equal(non_critical_activities, expected)
})
test_that("Early Start and Early Finish are correct!", {
schedule <- vanhoucke2014_project_1()
act <- schedule$activities
expect_equal(act$ES[1], 0)
expect_equal(act$EF[1], 1)
expect_equal(act$ES[2], 1)
expect_equal(act$EF[2], 3)
expect_equal(act$ES[3], 1)
expect_equal(act$EF[3], 3)
expect_equal(act$ES[4], 3)
expect_equal(act$EF[4], 7)
expect_equal(act$ES[5], 3)
expect_equal(act$EF[5], 6)
expect_equal(act$ES[6], 3)
expect_equal(act$EF[6], 6)
expect_equal(act$ES[7], 3)
expect_equal(act$EF[7], 6)
expect_equal(act$ES[8], 3)
expect_equal(act$EF[8], 5)
expect_equal(act$ES[9], 3)
expect_equal(act$EF[9], 4)
expect_equal(act$ES[10], 3)
expect_equal(act$EF[10], 4)
expect_equal(act$ES[11], 7)
expect_equal(act$EF[11], 9)
expect_equal(act$ES[12], 6)
expect_equal(act$EF[12], 7)
expect_equal(act$ES[13], 5)
expect_equal(act$EF[13], 6)
expect_equal(act$ES[14], 4)
expect_equal(act$EF[14], 5)
expect_equal(act$ES[15], 4)
expect_equal(act$EF[15], 5)
expect_equal(act$ES[16], 9)
expect_equal(act$EF[16], 11)
expect_equal(act$ES[17], 9)
expect_equal(act$EF[17], 10)
})
test_that("Late Start and Late Finish are correct!", {
schedule <- vanhoucke2014_project_1()
act <- schedule$activities
expect_equal(act$LS[1], 0)
expect_equal(act$LF[1], 1)
expect_equal(act$LS[2], 1)
expect_equal(act$LF[2], 3)
expect_equal(act$LS[3], 3)
expect_equal(act$LF[3], 5)
expect_equal(act$LS[4], 3)
expect_equal(act$LF[4], 7)
expect_equal(act$LS[5], 4)
expect_equal(act$LF[5], 7)
expect_equal(act$LS[6], 4)
expect_equal(act$LF[6], 7)
expect_equal(act$LS[7], 5)
expect_equal(act$LF[7], 8)
expect_equal(act$LS[8], 6)
expect_equal(act$LF[8], 8)
expect_equal(act$LS[9], 7)
expect_equal(act$LF[9], 8)
expect_equal(act$LS[10], 7)
expect_equal(act$LF[10], 8)
expect_equal(act$LS[11], 7)
expect_equal(act$LF[11], 9)
expect_equal(act$LS[12], 8)
expect_equal(act$LF[12], 9)
expect_equal(act$LS[13], 8)
expect_equal(act$LF[13], 9)
expect_equal(act$LS[14], 8)
expect_equal(act$LF[14], 9)
expect_equal(act$LS[15], 8)
expect_equal(act$LF[15], 9)
expect_equal(act$LS[16], 9)
expect_equal(act$LF[16], 11)
expect_equal(act$LS[17], 10)
expect_equal(act$LF[17], 11)
})
test_that("Brings the activities data frame by default!", {
schedule <- vanhoucke2014_project_1()
actual <- schedule$activities
expected <- activities
expect_equal(actual$id, expected$id)
})
test_that("Brings the activities data frame!", {
schedule <- vanhoucke2014_project_1()
actual <- schedule$activities
expected <- activities
expect_equal(actual$id, expected$id)
})
test_that("Brings the relations data frame!", {
schedule <- vanhoucke2014_project_1()
actual <- schedule$relations
expected <- relations
expect_equal(actual$from, expected$from)
expect_equal(actual$to, expected$to)
}) |
mdmb_optim <- function(optimizer, par, fn, gr=NULL, method="L-BFGS-B",
lower=NULL, upper=NULL, maxiter=300, control=NULL, h=1e-5)
{
control <- mdmb_optim_control(optimizer=optimizer, control=control, maxiter=maxiter)
if (optimizer=="optim"){
mod1 <- stats::optim( par=par, fn=fn, gr=gr, method=method,
hessian=TRUE, lower=lower, upper=upper, control=control)
mod1$iter <- mod1$counts['function']
}
if (optimizer=="nlminb"){
mod1 <- stats::nlminb(start=par, objective=fn, gradient=gr, lower=lower,
upper=upper, control=control)
mod1$value <- mod1$objective
mod1$hessian <- CDM::numerical_gradient(par=mod1$par, FUN=gr, h=h)
mod1$iter <- mod1$iterations
}
if (!is.null(gr)){
mod1$grad_par <- gr(mod1$par)
}
mod1$optimizer <- optimizer
mod1$converged <- mod1$convergence==0
return(mod1)
} |
setGeneric(name = 'plot_hydroMet',
def = function(obj, slot_name, col_number, interactive = FALSE,
line_type = NULL, line_color = 'dodgerblue',
x_lab = 'Date', y_lab = 'y', title_lab = NULL,
legend_lab = NULL, double_yaxis = NULL,
list_extra = NULL, from = NULL, to = NULL, scatter = NULL)
{
standardGeneric('plot_hydroMet')
})
setMethod(f = 'plot_hydroMet',
signature = 'hydroMet_BDHI',
definition = function(obj, slot_name, col_number, interactive = FALSE,
line_type = NULL, line_color = 'dodgerblue',
x_lab = 'Date', y_lab = 'y', title_lab = NULL,
legend_lab = NULL, double_yaxis = NULL,
list_extra = NULL, from = NULL, to = NULL)
{
n_slot_name <- length(slot_name)
if( is.character(slot_name) == FALSE ){
return('slot_name argument must be of class character')
}
aux <- match(x = slot_name, table = slotNames('hydroMet_BDHI')[1:13])
if( is.na( sum(aux) ) == TRUE ){
return('Unless one of the slot_name arguments is incorrect')
}
rm(aux)
col_position <- Reduce(f = c, x = col_number)
n_col_number <- length( col_position )
if(n_slot_name == 1){
if( is.numeric(col_number) == FALSE ){
return('col_number argument must be of class numeric')
}
} else {
if( is.list(col_number) == FALSE ){
return('col_number must be of list class')
}
if( is.numeric(Reduce(f = c, x = col_number) ) == FALSE ){
return('Each list element should contain numeric vectors')
}
}
col_position <- as.integer(col_position)
if(length( which(col_position <= 1) ) >= 1){
return('col_number arguments to plot must be >= 1')
}
if( is.logical(interactive) == FALSE){
return('interactive must be either TRUE or FALSE')
}
if( length(interactive) > 1 ){
return('interactive accepts a single value')
}
n_line_type <- length(line_type)
if(n_line_type == 0) {
if(interactive == FALSE){
line_type <- rep('solid', n_col_number)
} else{
line_type <- rep('lines', n_col_number)
}
} else {
if( n_line_type != n_col_number ){
return('line_type must have the same length as col_number')
}
if(interactive == FALSE){
valid_line_type <- c('solid', 'twodash', 'longdash', 'dotted', 'dotdash', 'dashed', 'blank')
correspondencia <- match(x = line_type, table = valid_line_type)
if( is.na( sum(correspondencia) ) == TRUE ){
aux_var <- line_type[ which(is.na(correspondencia) ) ]
return( paste0(aux_var, ' ', 'is not a valid line_type for ggplot2 graph') )
}
} else {
valid_line_type <- c('lines', 'lines+markers', 'markers')
correspondencia <- match(x = line_type, table = valid_line_type)
if( is.na( sum(correspondencia) ) == TRUE ){
aux_var <- line_type[ which(is.na(correspondencia) ) ]
return( paste0(aux_var, ' ', 'is not a valid line_type for plotly graph') )
}
}
}
n_line_color <- length(line_color)
if( n_line_color != n_col_number ){
return('line_color must be of the same length as col_number')
}
if( is.character(line_color) == FALSE ){
return('line_color must be of character class')
}
if( is.character(x_lab) == FALSE ){
return('x_lab must be of class character')
}
if( length(x_lab) != 1){
return('x_lab must be of length one')
}
if( is.character(y_lab) == FALSE ){
return('y_lab must be of class character')
}
if( is.null(double_yaxis) == TRUE){
if( length(y_lab) != 1){
return('y_lab must be of length one')
}
} else {
if( length(y_lab) != 2){
return('y_lab must be of length two')
}
}
if( is.null(title_lab) == FALSE){
if( is.character(title_lab) == FALSE ){
return('title_lab argument must be of character class')
}
if( length(title_lab) != 1 ){
return('title_lab length must be one')
}
}
if( is.null(legend_lab) == FALSE ){
n_legend_lab <- length(legend_lab)
if( is.character(legend_lab) == FALSE ){
return('legend_lab must be of class character')
}
if( n_col_number != n_legend_lab){
return('You must provide as many legend_lab strings as line plots')
}
}
if( is.null(double_yaxis) == FALSE){
n_double_yaxis <- length(double_yaxis)
if( is.numeric(double_yaxis) == FALSE){
return('double_axis argument must be of numeric class')
}
if( interactive == FALSE){
if( n_double_yaxis != 2 ){
return('In interactive = FALSE double_yaxis arguments only allows a numeric vector of length two')
}
} else {
if(n_double_yaxis != n_col_number){
return('double_yaxis numeric vector argument must be of the same length as col_number')
}
}
target_nums <- c(1, 2)
match_nums <- match(x = double_yaxis, table = target_nums)
if( is.na( sum(match_nums) ) == TRUE ){
return('Only 1 and 2 are allow as arguments in double_yaxis')
}
}
if( is.null(list_extra) == FALSE ){
if( interactive == FALSE){
if( is.list(list_extra) == FALSE){
return('list_extra argument must be of list class')
}
} else {
print('list_extra argument does not make sense if interactive = TRUE')
}
}
if( is.null(from) == FALSE){
if( is.character(from) == FALSE & is.POSIXct(from) == FALSE){
return('from must be of class character or POSIXct')
}
if( length(from) != 1){
return('from must be of length one')
}
}
if( is.null(to) == FALSE){
if( is.character(to) == FALSE & is.POSIXct(from) == FALSE){
return('to must be of class character or POSIXct')
}
if( length(to) != 1){
return('to must be of length one')
}
}
Date <- value <- NULL
all_slots <- get_hydroMet(obj = obj, name = slot_name)
target_max_col <- sapply(X = all_slots, FUN = ncol)
if(n_slot_name == 1){
if(max(col_number) > target_max_col){
return('Unless one of the col_number does not exist in the slot')
}
} else {
for(i in 1:n_slot_name){
aux_col_num <- col_number[[i]]
if(max(aux_col_num) > target_max_col[i]){
return( paste0('Unless one of the col_number (', slot_name[i], ') does not exist in the slot') )
}
}
}
N_all_slots <- length(all_slots)
if(N_all_slots > 1){
unidades <- rep(NA_character_, N_all_slots)
paso_tpo <- rep(NA_character_, N_all_slots)
for(i in 1:N_all_slots){
unidades[i] <- units( diff.Date( all_slots[[i]][ , 1] ) )
paso_tpo[i] <- length(unique( diff.Date( all_slots[[i]][ , 1] ) ) )
}
if( length( unique(unidades)) != 1 ){
return('the variables must have the same temporal resolution')
}
if( unique(paso_tpo) != 1 ){
return('the variables must have the same temporal resolution')
}
}
if(N_all_slots > 1){
df_plot <- all_slots[[1]][ , c(1, col_number[[1]] )]
for(i in 2:N_all_slots){
df_aux <- all_slots[[i]][ , c(1, col_number[[i]] )]
df_plot <- merge(df_plot, df_aux, all = TRUE)
}
} else {
df_plot <- all_slots[[1]][ , c(1, col_number)]
}
if( is.null(from) == FALSE & is.null(to) == FALSE){
df_plot <- subset(df_plot, subset = Date >= from & Date <= to)
} else if( is.null(from) == FALSE ) {
df_plot <- subset(df_plot, subset = Date >= from)
} else if( is.null(to) == FALSE) {
df_plot <- subset(df_plot, subset = Date <= to)
}
if( interactive == FALSE ){
if( is.null(double_yaxis) == TRUE){
N_plot <- nrow(df_plot)
N_var <- ncol(df_plot) - 1
if( is.null(legend_lab) == FALSE ){
tipo_linea <- list()
color_linea <- list()
leyen_linea <- list()
for(i in 1:N_var){
tipo_linea[[i]] <- rep(line_type[i], N_plot)
color_linea[[i]] <- rep(line_color[i], N_plot)
leyen_linea[[i]] <- rep(legend_lab[i], N_plot)
}
linea <- c(sapply(X = tipo_linea, '['))
color <- c(sapply(X = color_linea, '['))
leyen <- c(sapply(X = leyen_linea, '['))
df_plot2 <- melt(data = df_plot, id.vars = 'Date')
df_plot2 <- cbind(df_plot2, linea, color, leyen)
} else {
tipo_linea <- list()
color_linea <- list()
for(i in 1:N_var){
tipo_linea[[i]] <- rep(line_type[i], N_plot)
color_linea[[i]] <- rep(line_color[i], N_plot)
}
linea <- c(sapply(X = tipo_linea, '['))
color <- c(sapply(X = color_linea, '['))
df_plot2 <- melt(data = df_plot, id.vars = 'Date')
leyen <- df_plot2$variable
df_plot2 <- cbind(df_plot2, linea, color, leyen)
}
ggout <-
ggplot(data = df_plot2, aes(x = Date, y = value, color = leyen) ) +
geom_line(aes(linetype = leyen) ) +
scale_color_manual(values = line_color) +
scale_linetype_manual(values = line_type) +
theme(legend.title = element_blank()) +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab)
if( is.null(list_extra) == FALSE){
ggout <- ggout +
Reduce(f = c, x = list_extra)
}
return(ggout)
} else {
main_pos <- which(double_yaxis == 1) + 1
seco_pos <- which(double_yaxis == 2) + 1
y1 <- colnames(df_plot)[main_pos[1]]
y2 <- colnames(df_plot)[seco_pos[1]]
y1_plot <- colnames(df_plot)[main_pos]
y2_plot <- colnames(df_plot)[seco_pos]
m_plot <- as.matrix(x = df_plot[ , -1])
a <- range(df_plot[[y1]], na.rm = TRUE)
b <- range(df_plot[[y2]], na.rm = TRUE)
scale_factor <- diff(a)/diff(b)
m_plot[ , (seco_pos - 1)] <- ( (m_plot[ , (seco_pos - 1)] - b[1]) * scale_factor) + a[1]
trans <- ~ ((. - a[1]) / scale_factor) + b[1]
df_plot2 <- data.frame(df_plot[ , 1], m_plot)
colnames(df_plot2) <- colnames(df_plot)
ggout <-
ggplot(df_plot2) +
geom_line(aes_string('Date', y1_plot), col = line_color[ (main_pos - 1) ], lty = line_type[ (main_pos - 1) ] ) +
geom_line(aes_string('Date', y2_plot), col = line_color[ (seco_pos - 1) ], lty = line_type[ (seco_pos - 1) ] ) +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab[1]) +
scale_y_continuous(sec.axis = sec_axis(trans = trans, name = y_lab[2]))
if( is.null(list_extra) == FALSE){
ggout <- ggout +
Reduce(f = c, x = list_extra)
}
return(ggout)
}
} else {
if( is.null(double_yaxis) == TRUE ){
ppout <- plot_ly(df_plot, x = ~Date)
N_plots <- ncol(df_plot) - 1
for(i in 1:N_plots){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]) )
}
ppout <-
ppout %>%
layout(title = title_lab,
xaxis = list(title = x_lab),
yaxis = list(title = y_lab) )
return(ppout)
} else {
ppout <- plot_ly(df_plot, x = ~Date)
N_plots <- ncol(df_plot) - 1
for(i in 1:N_plots){
if(double_yaxis[i] == 1){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]) )
} else if (double_yaxis[i] == 2){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]), yaxis = 'y2')
}
}
ppout <-
ppout %>%
layout(title = title_lab,
xaxis = list(title = x_lab),
yaxis = list(title = y_lab[1]),
yaxis2 = list(title = y_lab[2],
overlaying = 'y',
side = 'right') )
return(ppout)
}
}
}
)
setMethod(f = 'plot_hydroMet',
signature = 'hydroMet_CR2',
definition = function(obj, slot_name, col_number, interactive = FALSE,
line_type = NULL, line_color = 'dodgerblue',
x_lab = 'Date', y_lab = 'y', title_lab = NULL,
legend_lab = NULL, double_yaxis = NULL,
list_extra = NULL, from = NULL, to = NULL)
{
n_slot_name <- length(slot_name)
if( is.character(slot_name) == FALSE ){
return('slot_name argument must be of class character')
}
aux <- match(x = slot_name, table = slotNames('hydroMet_CR2')[1:4])
if( is.na( sum(aux) ) == TRUE ){
return('Unless one of the slot_name arguments is incorrect')
}
rm(aux)
col_position <- Reduce(f = c, x = col_number)
n_col_number <- length( col_position )
if(n_slot_name == 1){
if( is.numeric(col_number) == FALSE ){
return('col_number argument must be of class numeric')
}
} else {
if( is.list(col_number) == FALSE ){
return('col_number must be of list class')
}
if( is.numeric(Reduce(f = c, x = col_number) ) == FALSE ){
return('Each list element should contain numeric vectors')
}
}
col_position <- as.integer(col_position)
if(length( which(col_position <= 1) ) >= 1){
return('col_number arguments to plot must be >= 1')
}
if( is.logical(interactive) == FALSE){
return('interactive must be either TRUE or FALSE')
}
if( length(interactive) > 1 ){
return('interactive accepts a single value')
}
n_line_type <- length(line_type)
if(n_line_type == 0) {
if(interactive == FALSE){
line_type <- rep('solid', n_col_number)
} else{
line_type <- rep('lines', n_col_number)
}
} else {
if( n_line_type != n_col_number ){
return('line_type must have the same length as col_number')
}
if(interactive == FALSE){
valid_line_type <- c('solid', 'twodash', 'longdash', 'dotted', 'dotdash', 'dashed', 'blank')
correspondencia <- match(x = line_type, table = valid_line_type)
if( is.na( sum(correspondencia) ) == TRUE ){
aux_var <- line_type[ which(is.na(correspondencia) ) ]
return( paste0(aux_var, ' ', 'is not a valid line_type for ggplot2 graph') )
}
} else {
valid_line_type <- c('lines', 'lines+markers', 'markers')
correspondencia <- match(x = line_type, table = valid_line_type)
if( is.na( sum(correspondencia) ) == TRUE ){
aux_var <- line_type[ which(is.na(correspondencia) ) ]
return( paste0(aux_var, ' ', 'is not a valid line_type for plotly graph') )
}
}
}
n_line_color <- length(line_color)
if( n_line_color != n_col_number ){
return('line_color must be of the same length as col_number')
}
if( is.character(line_color) == FALSE ){
return('line_color must be of character class')
}
if( is.character(x_lab) == FALSE ){
return('x_lab must be of class character')
}
if( length(x_lab) != 1){
return('x_lab must be of length one')
}
if( is.character(y_lab) == FALSE ){
return('y_lab must be of class character')
}
if( is.null(double_yaxis) == TRUE){
if( length(y_lab) != 1){
return('y_lab must be of length one')
}
} else {
if( length(y_lab) != 2){
return('y_lab must be of length two')
}
}
if( is.null(title_lab) == FALSE){
if( is.character(title_lab) == FALSE ){
return('title_lab argument must be of character class')
}
if( length(title_lab) != 1 ){
return('title_lab length must be one')
}
}
if( is.null(legend_lab) == FALSE ){
n_legend_lab <- length(legend_lab)
if( is.character(legend_lab) == FALSE ){
return('legend_lab must be of class character')
}
if( n_col_number != n_legend_lab){
return('You must provide as many legend_lab strings as line plots')
}
}
if( is.null(double_yaxis) == FALSE){
n_double_yaxis <- length(double_yaxis)
if( is.numeric(double_yaxis) == FALSE){
return('double_axis argument must be of numeric class')
}
if( interactive == FALSE){
if( n_double_yaxis != 2 ){
return('In interactive = FALSE double_yaxis arguments only allows a numeric vector of length two')
}
} else {
if(n_double_yaxis != n_col_number){
return('double_yaxis numeric vector argument must be of the same length as col_number')
}
}
target_nums <- c(1, 2)
match_nums <- match(x = double_yaxis, table = target_nums)
if( is.na( sum(match_nums) ) == TRUE ){
return('Only 1 and 2 are allow as arguments in double_yaxis')
}
}
if( is.null(list_extra) == FALSE ){
if( interactive == FALSE){
if( is.list(list_extra) == FALSE){
return('list_extra argument must be of list class')
}
} else {
print('list_extra argument does not make sense if interactive = TRUE')
}
}
if( is.null(from) == FALSE){
if( is.character(from) == FALSE ){
return('from must be of class character')
}
if( length(from) != 1){
return('from must be of length one')
}
}
if( is.null(to) == FALSE){
if( is.character(to) == FALSE ){
return('to must be of class character')
}
if( length(to) != 1){
return('to must be of length one')
}
}
Date <- value <- NULL
all_slots <- get_hydroMet(obj = obj, name = slot_name)
target_max_col <- sapply(X = all_slots, FUN = ncol)
if(n_slot_name == 1){
if(max(col_number) > target_max_col){
return('Unless one of the col_number does not exist in the slot')
}
} else {
for(i in 1:n_slot_name){
aux_col_num <- col_number[[i]]
if(max(aux_col_num) > target_max_col[i]){
return( paste0('Unless one of the col_number (', slot_name[i], ') does not exist in the slot') )
}
}
}
N_all_slots <- length(all_slots)
if(N_all_slots > 1){
unidades <- rep(NA_character_, N_all_slots)
paso_tpo <- rep(NA_character_, N_all_slots)
for(i in 1:N_all_slots){
unidades[i] <- units( diff.Date( all_slots[[i]][ , 1] ) )
paso_tpo[i] <- length(unique( diff.Date( all_slots[[i]][ , 1] ) ) )
}
if( length( unique(unidades)) != 1 ){
return('the variables must have the same temporal resolution')
}
if( unique(paso_tpo) != 1 ){
return('the variables must have the same temporal resolution')
}
}
if(N_all_slots > 1){
df_plot <- all_slots[[1]][ , c(1, col_number[[1]] )]
for(i in 2:N_all_slots){
df_aux <- all_slots[[i]][ , c(1, col_number[[i]] )]
df_plot <- merge(df_plot, df_aux, all = TRUE)
}
} else {
df_plot <- all_slots[[1]][ , c(1, col_number)]
}
if( is.null(from) == FALSE & is.null(to) == FALSE){
df_plot <- subset(df_plot, subset = Date >= from & Date <= to)
} else if( is.null(from) == FALSE ) {
df_plot <- subset(df_plot, subset = Date >= from)
} else if( is.null(to) == FALSE) {
df_plot <- subset(df_plot, subset = Date <= to)
}
if( interactive == FALSE ){
if( is.null(double_yaxis) == TRUE){
N_plot <- nrow(df_plot)
N_var <- ncol(df_plot) - 1
if( is.null(legend_lab) == FALSE ){
tipo_linea <- list()
color_linea <- list()
leyen_linea <- list()
for(i in 1:N_var){
tipo_linea[[i]] <- rep(line_type[i], N_plot)
color_linea[[i]] <- rep(line_color[i], N_plot)
leyen_linea[[i]] <- rep(legend_lab[i], N_plot)
}
linea <- c(sapply(X = tipo_linea, '['))
color <- c(sapply(X = color_linea, '['))
leyen <- c(sapply(X = leyen_linea, '['))
df_plot2 <- melt(data = df_plot, id.vars = 'Date')
df_plot2 <- cbind(df_plot2, linea, color, leyen)
} else {
tipo_linea <- list()
color_linea <- list()
for(i in 1:N_var){
tipo_linea[[i]] <- rep(line_type[i], N_plot)
color_linea[[i]] <- rep(line_color[i], N_plot)
}
linea <- c(sapply(X = tipo_linea, '['))
color <- c(sapply(X = color_linea, '['))
df_plot2 <- melt(data = df_plot, id.vars = 'Date')
leyen <- df_plot2$variable
df_plot2 <- cbind(df_plot2, linea, color, leyen)
}
ggout <-
ggplot(data = df_plot2, aes(x = Date, y = value, color = leyen) ) +
geom_line(aes(linetype = leyen) ) +
scale_color_manual(values = line_color) +
scale_linetype_manual(values = line_type) +
theme(legend.title = element_blank()) +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab)
if( is.null(list_extra) == FALSE){
ggout <- ggout +
Reduce(f = c, x = list_extra)
}
return(ggout)
} else {
main_pos <- which(double_yaxis == 1) + 1
seco_pos <- which(double_yaxis == 2) + 1
y1 <- colnames(df_plot)[main_pos[1]]
y2 <- colnames(df_plot)[seco_pos[1]]
y1_plot <- colnames(df_plot)[main_pos]
y2_plot <- colnames(df_plot)[seco_pos]
m_plot <- as.matrix(x = df_plot[ , -1])
a <- range(df_plot[[y1]], na.rm = TRUE)
b <- range(df_plot[[y2]], na.rm = TRUE)
scale_factor <- diff(a)/diff(b)
m_plot[ , (seco_pos - 1)] <- ( (m_plot[ , (seco_pos - 1)] - b[1]) * scale_factor) + a[1]
trans <- ~ ((. - a[1]) / scale_factor) + b[1]
df_plot2 <- data.frame(df_plot[ , 1], m_plot)
colnames(df_plot2) <- colnames(df_plot)
ggout <-
ggplot(df_plot2) +
geom_line(aes_string('Date', y1_plot), col = line_color[ (main_pos - 1) ], lty = line_type[ (main_pos - 1) ] ) +
geom_line(aes_string('Date', y2_plot), col = line_color[ (seco_pos - 1) ], lty = line_type[ (seco_pos - 1) ] ) +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab[1]) +
scale_y_continuous(sec.axis = sec_axis(trans = trans, name = y_lab[2]))
if( is.null(list_extra) == FALSE){
ggout <- ggout +
Reduce(f = c, x = list_extra)
}
return(ggout)
}
} else {
if( is.null(double_yaxis) == TRUE ){
ppout <- plot_ly(df_plot, x = ~Date)
N_plots <- ncol(df_plot) - 1
for(i in 1:N_plots){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]) )
}
ppout <-
ppout %>%
layout(title = title_lab,
xaxis = list(title = x_lab),
yaxis = list(title = y_lab) )
return(ppout)
} else {
ppout <- plot_ly(df_plot, x = ~Date)
N_plots <- ncol(df_plot) - 1
for(i in 1:N_plots){
if(double_yaxis[i] == 1){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]) )
} else if (double_yaxis[i] == 2){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]), yaxis = 'y2')
}
}
ppout <-
ppout %>%
layout(title = title_lab,
xaxis = list(title = x_lab),
yaxis = list(title = y_lab[1]),
yaxis2 = list(title = y_lab[2],
overlaying = 'y',
side = 'right') )
return(ppout)
}
}
}
)
setMethod(f = 'plot_hydroMet',
signature = 'hydroMet_DGI',
definition = function(obj, slot_name, col_number, interactive = FALSE,
line_type = NULL, line_color = 'dodgerblue',
x_lab = 'Date', y_lab = 'y', title_lab = NULL,
legend_lab = NULL, double_yaxis = NULL,
list_extra = NULL, from = NULL, to = NULL)
{
n_slot_name <- length(slot_name)
if( is.character(slot_name) == FALSE ){
return('slot_name argument must be of class character')
}
aux <- match(x = slot_name, table = slotNames('hydroMet_DGI')[1:7])
if( is.na( sum(aux) ) == TRUE ){
return('Unless one of the slot_name arguments is incorrect')
}
rm(aux)
col_position <- Reduce(f = c, x = col_number)
n_col_number <- length( col_position )
if(n_slot_name == 1){
if( is.numeric(col_number) == FALSE ){
return('col_number argument must be of class numeric')
}
} else {
if( is.list(col_number) == FALSE ){
return('col_number must be of list class')
}
if( is.numeric(Reduce(f = c, x = col_number) ) == FALSE ){
return('Each list element should contain numeric vectors')
}
}
col_position <- as.integer(col_position)
if(length( which(col_position <= 1) ) >= 1){
return('col_number arguments to plot must be >= 1')
}
if( is.logical(interactive) == FALSE){
return('interactive must be either TRUE or FALSE')
}
if( length(interactive) > 1 ){
return('interactive accepts a single value')
}
n_line_type <- length(line_type)
if(n_line_type == 0) {
if(interactive == FALSE){
line_type <- rep('solid', n_col_number)
} else{
line_type <- rep('lines', n_col_number)
}
} else {
if( n_line_type != n_col_number ){
return('line_type must have the same length as col_number')
}
if(interactive == FALSE){
valid_line_type <- c('solid', 'twodash', 'longdash', 'dotted', 'dotdash', 'dashed', 'blank')
correspondencia <- match(x = line_type, table = valid_line_type)
if( is.na( sum(correspondencia) ) == TRUE ){
aux_var <- line_type[ which(is.na(correspondencia) ) ]
return( paste0(aux_var, ' ', 'is not a valid line_type for ggplot2 graph') )
}
} else {
valid_line_type <- c('lines', 'lines+markers', 'markers')
correspondencia <- match(x = line_type, table = valid_line_type)
if( is.na( sum(correspondencia) ) == TRUE ){
aux_var <- line_type[ which(is.na(correspondencia) ) ]
return( paste0(aux_var, ' ', 'is not a valid line_type for plotly graph') )
}
}
}
n_line_color <- length(line_color)
if( n_line_color != n_col_number ){
return('line_color must be of the same length as col_number')
}
if( is.character(line_color) == FALSE ){
return('line_color must be of character class')
}
if( is.character(x_lab) == FALSE ){
return('x_lab must be of class character')
}
if( length(x_lab) != 1){
return('x_lab must be of length one')
}
if( is.character(y_lab) == FALSE ){
return('y_lab must be of class character')
}
if( is.null(double_yaxis) == TRUE){
if( length(y_lab) != 1){
return('y_lab must be of length one')
}
} else {
if( length(y_lab) != 2){
return('y_lab must be of length two')
}
}
if( is.null(title_lab) == FALSE){
if( is.character(title_lab) == FALSE ){
return('title_lab argument must be of character class')
}
if( length(title_lab) != 1 ){
return('title_lab length must be one')
}
}
if( is.null(legend_lab) == FALSE ){
n_legend_lab <- length(legend_lab)
if( is.character(legend_lab) == FALSE ){
return('legend_lab must be of class character')
}
if( n_col_number != n_legend_lab){
return('You must provide as many legend_lab strings as line plots')
}
}
if( is.null(double_yaxis) == FALSE){
n_double_yaxis <- length(double_yaxis)
if( is.numeric(double_yaxis) == FALSE){
return('double_axis argument must be of numeric class')
}
if( interactive == FALSE){
if( n_double_yaxis != 2 ){
return('In interactive = FALSE double_yaxis arguments only allows a numeric vector of length two')
}
} else {
if(n_double_yaxis != n_col_number){
return('double_yaxis numeric vector argument must be of the same length as col_number')
}
}
target_nums <- c(1, 2)
match_nums <- match(x = double_yaxis, table = target_nums)
if( is.na( sum(match_nums) ) == TRUE ){
return('Only 1 and 2 are allow as arguments in double_yaxis')
}
}
if( is.null(list_extra) == FALSE ){
if( interactive == FALSE){
if( is.list(list_extra) == FALSE){
return('list_extra argument must be of list class')
}
} else {
print('list_extra argument does not make sense if interactive = TRUE')
}
}
if( is.null(from) == FALSE){
if( is.character(from) == FALSE ){
return('from must be of class character')
}
if( length(from) != 1){
return('from must be of length one')
}
}
if( is.null(to) == FALSE){
if( is.character(to) == FALSE ){
return('to must be of class character')
}
if( length(to) != 1){
return('to must be of length one')
}
}
Date <- value <- NULL
all_slots <- get_hydroMet(obj = obj, name = slot_name)
target_max_col <- sapply(X = all_slots, FUN = ncol)
if(n_slot_name == 1){
if(max(col_number) > target_max_col){
return('Unless one of the col_number does not exist in the slot')
}
} else {
for(i in 1:n_slot_name){
aux_col_num <- col_number[[i]]
if(max(aux_col_num) > target_max_col[i]){
return( paste0('Unless one of the col_number (', slot_name[i], ') does not exist in the slot') )
}
}
}
N_all_slots <- length(all_slots)
if(N_all_slots > 1){
unidades <- rep(NA_character_, N_all_slots)
paso_tpo <- rep(NA_character_, N_all_slots)
for(i in 1:N_all_slots){
unidades[i] <- units( diff.Date( all_slots[[i]][ , 1] ) )
paso_tpo[i] <- length(unique( diff.Date( all_slots[[i]][ , 1] ) ) )
}
if( length( unique(unidades)) != 1 ){
return('the variables must have the same temporal resolution')
}
if( unique(paso_tpo) != 1 ){
return('the variables must have the same temporal resolution')
}
}
if(N_all_slots > 1){
df_plot <- all_slots[[1]][ , c(1, col_number[[1]] )]
for(i in 2:N_all_slots){
df_aux <- all_slots[[i]][ , c(1, col_number[[i]] )]
df_plot <- merge(df_plot, df_aux, all = TRUE)
}
} else {
df_plot <- all_slots[[1]][ , c(1, col_number)]
}
if( is.null(from) == FALSE & is.null(to) == FALSE){
df_plot <- subset(df_plot, subset = Date >= from & Date <= to)
} else if( is.null(from) == FALSE ) {
df_plot <- subset(df_plot, subset = Date >= from)
} else if( is.null(to) == FALSE) {
df_plot <- subset(df_plot, subset = Date <= to)
}
if( interactive == FALSE ){
if( is.null(double_yaxis) == TRUE){
N_plot <- nrow(df_plot)
N_var <- ncol(df_plot) - 1
if( is.null(legend_lab) == FALSE ){
tipo_linea <- list()
color_linea <- list()
leyen_linea <- list()
for(i in 1:N_var){
tipo_linea[[i]] <- rep(line_type[i], N_plot)
color_linea[[i]] <- rep(line_color[i], N_plot)
leyen_linea[[i]] <- rep(legend_lab[i], N_plot)
}
linea <- c(sapply(X = tipo_linea, '['))
color <- c(sapply(X = color_linea, '['))
leyen <- c(sapply(X = leyen_linea, '['))
df_plot2 <- melt(data = df_plot, id.vars = 'Date')
df_plot2 <- cbind(df_plot2, linea, color, leyen)
} else {
tipo_linea <- list()
color_linea <- list()
for(i in 1:N_var){
tipo_linea[[i]] <- rep(line_type[i], N_plot)
color_linea[[i]] <- rep(line_color[i], N_plot)
}
linea <- c(sapply(X = tipo_linea, '['))
color <- c(sapply(X = color_linea, '['))
df_plot2 <- melt(data = df_plot, id.vars = 'Date')
leyen <- df_plot2$variable
df_plot2 <- cbind(df_plot2, linea, color, leyen)
}
ggout <-
ggplot(data = df_plot2, aes(x = Date, y = value, color = leyen) ) +
geom_line(aes(linetype = leyen) ) +
scale_color_manual(values = line_color) +
scale_linetype_manual(values = line_type) +
theme(legend.title = element_blank()) +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab)
if( is.null(list_extra) == FALSE){
ggout <- ggout +
Reduce(f = c, x = list_extra)
}
return(ggout)
} else {
main_pos <- which(double_yaxis == 1) + 1
seco_pos <- which(double_yaxis == 2) + 1
y1 <- colnames(df_plot)[main_pos[1]]
y2 <- colnames(df_plot)[seco_pos[1]]
y1_plot <- colnames(df_plot)[main_pos]
y2_plot <- colnames(df_plot)[seco_pos]
m_plot <- as.matrix(x = df_plot[ , -1])
a <- range(df_plot[[y1]], na.rm = TRUE)
b <- range(df_plot[[y2]], na.rm = TRUE)
scale_factor <- diff(a)/diff(b)
m_plot[ , (seco_pos - 1)] <- ( (m_plot[ , (seco_pos - 1)] - b[1]) * scale_factor) + a[1]
trans <- ~ ((. - a[1]) / scale_factor) + b[1]
df_plot2 <- data.frame(df_plot[ , 1], m_plot)
colnames(df_plot2) <- colnames(df_plot)
ggout <-
ggplot(df_plot2) +
geom_line(aes_string('Date', y1_plot), col = line_color[ (main_pos - 1) ], lty = line_type[ (main_pos - 1) ] ) +
geom_line(aes_string('Date', y2_plot), col = line_color[ (seco_pos - 1) ], lty = line_type[ (seco_pos - 1) ] ) +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab[1]) +
scale_y_continuous(sec.axis = sec_axis(trans = trans, name = y_lab[2]))
if( is.null(list_extra) == FALSE){
ggout <- ggout +
Reduce(f = c, x = list_extra)
}
return(ggout)
}
} else {
if( is.null(double_yaxis) == TRUE ){
ppout <- plot_ly(df_plot, x = ~Date)
N_plots <- ncol(df_plot) - 1
for(i in 1:N_plots){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]) )
}
ppout <-
ppout %>%
layout(title = title_lab,
xaxis = list(title = x_lab),
yaxis = list(title = y_lab) )
return(ppout)
} else {
ppout <- plot_ly(df_plot, x = ~Date)
N_plots <- ncol(df_plot) - 1
for(i in 1:N_plots){
if(double_yaxis[i] == 1){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]) )
} else if (double_yaxis[i] == 2){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]), yaxis = 'y2')
}
}
ppout <-
ppout %>%
layout(title = title_lab,
xaxis = list(title = x_lab),
yaxis = list(title = y_lab[1]),
yaxis2 = list(title = y_lab[2],
overlaying = 'y',
side = 'right') )
return(ppout)
}
}
}
)
setMethod(f = 'plot_hydroMet',
signature = 'hydroMet_IANIGLA',
definition = function(obj, slot_name, col_number, interactive = FALSE,
line_type = NULL, line_color = 'dodgerblue',
x_lab = 'Date', y_lab = 'y', title_lab = NULL,
legend_lab = NULL, double_yaxis = NULL,
list_extra = NULL, from = NULL, to = NULL)
{
n_slot_name <- length(slot_name)
if( is.character(slot_name) == FALSE ){
return('slot_name argument must be of class character')
}
aux <- match(x = slot_name, table = slotNames('hydroMet_IANIGLA')[2:11])
if( is.na( sum(aux) ) == TRUE ){
return('Unless one of the slot_name arguments is incorrect')
}
rm(aux)
col_position <- Reduce(f = c, x = col_number)
n_col_number <- length( col_position )
if(n_slot_name == 1){
if( is.numeric(col_number) == FALSE ){
return('col_number argument must be of class numeric')
}
} else {
if( is.list(col_number) == FALSE ){
return('col_number must be of list class')
}
if( is.numeric(Reduce(f = c, x = col_number) ) == FALSE ){
return('Each list element should contain numeric vectors')
}
}
col_position <- as.integer(col_position)
if(length( which(col_position < 1) ) >= 1){
return('col_number arguments to plot must be > 1')
}
if( is.logical(interactive) == FALSE){
return('interactive must be either TRUE or FALSE')
}
if( length(interactive) > 1 ){
return('interactive accepts a single value')
}
n_line_type <- length(line_type)
if(n_line_type == 0) {
if(interactive == FALSE){
line_type <- rep('solid', n_col_number)
} else{
line_type <- rep('lines', n_col_number)
}
} else {
if( n_line_type != n_col_number ){
return('line_type must have the same length as col_number')
}
if(interactive == FALSE){
valid_line_type <- c('solid', 'twodash', 'longdash', 'dotted', 'dotdash', 'dashed', 'blank')
correspondencia <- match(x = line_type, table = valid_line_type)
if( is.na( sum(correspondencia) ) == TRUE ){
aux_var <- line_type[ which(is.na(correspondencia) ) ]
return( paste0(aux_var, ' ', 'is not a valid line_type for ggplot2 graph') )
}
} else {
valid_line_type <- c('lines', 'lines+markers', 'markers')
correspondencia <- match(x = line_type, table = valid_line_type)
if( is.na( sum(correspondencia) ) == TRUE ){
aux_var <- line_type[ which(is.na(correspondencia) ) ]
return( paste0(aux_var, ' ', 'is not a valid line_type for plotly graph') )
}
}
}
n_line_color <- length(line_color)
if( n_line_color != n_col_number ){
return('line_color must be of the same length as col_number')
}
if( is.character(line_color) == FALSE ){
return('line_color must be of character class')
}
if( is.character(x_lab) == FALSE ){
return('x_lab must be of class character')
}
if( length(x_lab) != 1){
return('x_lab must be of length one')
}
if( is.character(y_lab) == FALSE ){
return('y_lab must be of class character')
}
if( is.null(double_yaxis) == TRUE){
if( length(y_lab) != 1){
return('y_lab must be of length one')
}
} else {
if( length(y_lab) != 2){
return('y_lab must be of length two')
}
}
if( is.null(title_lab) == FALSE){
if( is.character(title_lab) == FALSE ){
return('title_lab argument must be of character class')
}
if( length(title_lab) != 1 ){
return('title_lab length must be one')
}
}
if( is.null(legend_lab) == FALSE ){
n_legend_lab <- length(legend_lab)
if( is.character(legend_lab) == FALSE ){
return('legend_lab must be of class character')
}
if( n_col_number != n_legend_lab){
return('You must provide as many legend_lab strings as line plots')
}
}
if( is.null(double_yaxis) == FALSE){
n_double_yaxis <- length(double_yaxis)
if( is.numeric(double_yaxis) == FALSE){
return('double_axis argument must be of numeric class')
}
if( interactive == FALSE){
if( n_double_yaxis != 2 ){
return('In interactive = FALSE double_yaxis arguments only allows a numeric vector of length two')
}
} else {
if(n_double_yaxis != n_col_number){
return('double_yaxis numeric vector argument must be of the same length as col_number')
}
}
target_nums <- c(1, 2)
match_nums <- match(x = double_yaxis, table = target_nums)
if( is.na( sum(match_nums) ) == TRUE ){
return('Only 1 and 2 are allow as arguments in double_yaxis')
}
}
if( is.null(list_extra) == FALSE ){
if( interactive == FALSE){
if( is.list(list_extra) == FALSE){
return('list_extra argument must be of list class')
}
} else {
print('list_extra argument does not make sense if interactive = TRUE')
}
}
if( is.null(from) == FALSE){
if( is.character(from) == FALSE & is.POSIXct(from) == FALSE){
return('from must be of class character or POSIXct')
}
if( length(from) != 1){
return('from must be of length one')
}
}
if( is.null(to) == FALSE){
if( is.character(to) == FALSE & is.POSIXct(from) == FALSE){
return('to must be of class character or POSIXct')
}
if( length(to) != 1){
return('to must be of length one')
}
}
Date <- value <- NULL
all_slots <- get_hydroMet(obj = obj, name = slot_name)
target_max_col <- sapply(X = all_slots, FUN = ncol)
if(n_slot_name == 1){
if(max(col_number) > target_max_col){
return('Unless one of the col_number does not exist in the slot')
}
} else {
for(i in 1:n_slot_name){
aux_col_num <- col_number[[i]]
if(max(aux_col_num) > target_max_col[i]){
return( paste0('Unless one of the col_number (', slot_name[i], ') does not exist in the slot') )
}
}
}
N_all_slots <- length(all_slots)
date_serie <- get_hydroMet(obj = obj, name = 'date')[[1]]
if(N_all_slots > 1){
aux_nom <- colnames(all_slots[[1]])[ c( col_number[[1]] ) ]
df_plot <- data.frame(date_serie, all_slots[[1]][ , c(col_number[[1]] )] )
colnames(df_plot) <- c('Date', aux_nom)
for(i in 2:N_all_slots){
aux_nom <- c('Date', aux_nom, colnames(all_slots[[i]])[ c( col_number[[i]] ) ] )
df_aux <- data.frame(Date = date_serie, all_slots[[i]][ , c(col_number[[i]] )] )
df_plot <- merge(df_plot, df_aux, all = TRUE)
colnames(df_plot) <- aux_nom
}
} else {
aux_nom <- colnames(all_slots[[1]])[ c(col_number) ]
df_plot <- data.frame(date_serie, all_slots[[1]][ , c(col_number)] )
colnames(df_plot) <- c('Date', aux_nom)
}
if( is.null(from) == FALSE & is.null(to) == FALSE){
df_plot <- subset(df_plot, subset = Date >= from & Date <= to)
} else if( is.null(from) == FALSE ) {
df_plot <- subset(df_plot, subset = Date >= from)
} else if( is.null(to) == FALSE) {
df_plot <- subset(df_plot, subset = Date <= to)
}
if( interactive == FALSE ){
if( is.null(double_yaxis) == TRUE){
N_plot <- nrow(df_plot)
N_var <- ncol(df_plot) - 1
if( is.null(legend_lab) == FALSE ){
tipo_linea <- list()
color_linea <- list()
leyen_linea <- list()
for(i in 1:N_var){
tipo_linea[[i]] <- rep(line_type[i], N_plot)
color_linea[[i]] <- rep(line_color[i], N_plot)
leyen_linea[[i]] <- rep(legend_lab[i], N_plot)
}
linea <- c(sapply(X = tipo_linea, '['))
color <- c(sapply(X = color_linea, '['))
leyen <- c(sapply(X = leyen_linea, '['))
df_plot2 <- melt(data = df_plot, id.vars = 'Date')
df_plot2 <- cbind(df_plot2, linea, color, leyen)
} else {
tipo_linea <- list()
color_linea <- list()
for(i in 1:N_var){
tipo_linea[[i]] <- rep(line_type[i], N_plot)
color_linea[[i]] <- rep(line_color[i], N_plot)
}
linea <- c(sapply(X = tipo_linea, '['))
color <- c(sapply(X = color_linea, '['))
df_plot2 <- melt(data = df_plot, id.vars = 'Date')
leyen <- df_plot2$variable
df_plot2 <- cbind(df_plot2, linea, color, leyen)
}
ggout <-
ggplot(data = df_plot2, aes(x = Date, y = value, color = leyen) ) +
geom_line(aes(linetype = leyen) ) +
scale_color_manual(values = line_color) +
scale_linetype_manual(values = line_type) +
theme(legend.title = element_blank()) +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab)
if( is.null(list_extra) == FALSE){
ggout <- ggout +
Reduce(f = c, x = list_extra)
}
return(ggout)
} else {
main_pos <- which(double_yaxis == 1) + 1
seco_pos <- which(double_yaxis == 2) + 1
y1 <- colnames(df_plot)[main_pos[1]]
y2 <- colnames(df_plot)[seco_pos[1]]
y1_plot <- colnames(df_plot)[main_pos]
y2_plot <- colnames(df_plot)[seco_pos]
m_plot <- as.matrix(x = df_plot[ , -1])
a <- range(df_plot[[y1]], na.rm = TRUE)
b <- range(df_plot[[y2]], na.rm = TRUE)
scale_factor <- diff(a)/diff(b)
m_plot[ , (seco_pos - 1)] <- ( (m_plot[ , (seco_pos - 1)] - b[1]) * scale_factor) + a[1]
trans <- ~ ((. - a[1]) / scale_factor) + b[1]
df_plot2 <- data.frame(df_plot[ , 1], m_plot)
colnames(df_plot2) <- colnames(df_plot)
ggout <-
ggplot(df_plot2) +
geom_line(aes_string('Date', y1_plot), col = line_color[ (main_pos - 1) ], lty = line_type[ (main_pos - 1) ] ) +
geom_line(aes_string('Date', y2_plot), col = line_color[ (seco_pos - 1) ], lty = line_type[ (seco_pos - 1) ] ) +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab[1]) +
scale_y_continuous(sec.axis = sec_axis(trans = trans, name = y_lab[2]))
if( is.null(list_extra) == FALSE){
ggout <- ggout +
Reduce(f = c, x = list_extra)
}
return(ggout)
}
} else {
if( is.null(double_yaxis) == TRUE ){
ppout <- plot_ly(df_plot, x = ~Date)
N_plots <- ncol(df_plot) - 1
for(i in 1:N_plots){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]) )
}
ppout <-
ppout %>%
layout(title = title_lab,
xaxis = list(title = x_lab),
yaxis = list(title = y_lab) )
return(ppout)
} else {
ppout <- plot_ly(df_plot, x = ~Date)
N_plots <- ncol(df_plot) - 1
for(i in 1:N_plots){
if(double_yaxis[i] == 1){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]) )
} else if (double_yaxis[i] == 2){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]), yaxis = 'y2')
}
}
ppout <-
ppout %>%
layout(title = title_lab,
xaxis = list(title = x_lab),
yaxis = list(title = y_lab[1]),
yaxis2 = list(title = y_lab[2],
overlaying = 'y',
side = 'right') )
return(ppout)
}
}
}
)
setMethod(f = 'plot_hydroMet',
signature = 'hydroMet_compact',
definition = function(obj, slot_name, col_number, interactive = FALSE,
line_type = NULL, line_color = 'dodgerblue',
x_lab = 'x', y_lab = 'y', title_lab = NULL,
legend_lab = NULL, double_yaxis = NULL,
list_extra = NULL, from = NULL, to = NULL, scatter = NULL)
{
n_slot_name <- length(slot_name)
if( is.character(slot_name) == FALSE ){
return('slot_name argument must be of class character')
}
aux <- match(x = slot_name, table = slotNames('hydroMet_compact')[1])
if( is.na( sum(aux) ) == TRUE ){
return('Unless one of the slot_name arguments is incorrect')
}
rm(aux)
col_position <- Reduce(f = c, x = col_number)
n_col_number <- length( col_position )
if(n_slot_name == 1){
if( is.numeric(col_number) == FALSE ){
return('col_number argument must be of class numeric')
}
} else {
if( is.list(col_number) == FALSE ){
return('col_number must be of list class')
}
if( is.numeric(Reduce(f = c, x = col_number) ) == FALSE ){
return('Each list element should contain numeric vectors')
}
}
col_position <- as.integer(col_position)
if(length( which(col_position <= 1) ) >= 1){
return('col_number arguments to plot must be >= 1')
}
if( is.logical(interactive) == FALSE){
return('interactive must be either TRUE or FALSE')
}
if( length(interactive) > 1 ){
return('interactive accepts a single value')
}
n_line_type <- length(line_type)
if(n_line_type == 0) {
if(interactive == FALSE){
line_type <- rep('solid', n_col_number)
} else{
line_type <- rep('lines', n_col_number)
}
} else {
if( n_line_type != n_col_number ){
return('line_type must have the same length as col_number')
}
if(interactive == FALSE){
valid_line_type <- c('solid', 'twodash', 'longdash', 'dotted', 'dotdash', 'dashed', 'blank')
correspondencia <- match(x = line_type, table = valid_line_type)
if( is.na( sum(correspondencia) ) == TRUE ){
aux_var <- line_type[ which(is.na(correspondencia) ) ]
return( paste0(aux_var, ' ', 'is not a valid line_type for ggplot2 graph') )
}
} else {
valid_line_type <- c('lines', 'lines+markers', 'markers')
correspondencia <- match(x = line_type, table = valid_line_type)
if( is.na( sum(correspondencia) ) == TRUE ){
aux_var <- line_type[ which(is.na(correspondencia) ) ]
return( paste0(aux_var, ' ', 'is not a valid line_type for plotly graph') )
}
}
}
n_line_color <- length(line_color)
if( is.null(scatter) == TRUE ){
if( n_line_color != n_col_number ){
return('line_color must be of the same length as col_number')
}
if( is.character(line_color) == FALSE ){
return('line_color must be of character class')
}
}
if( is.character(x_lab) == FALSE ){
return('x_lab must be of class character')
}
if( length(x_lab) != 1){
return('x_lab must be of length one')
}
if( is.character(y_lab) == FALSE ){
return('y_lab must be of class character')
}
if( is.null(double_yaxis) == TRUE){
if( length(y_lab) != 1){
return('y_lab must be of length one')
}
} else {
if( length(y_lab) != 2){
return('y_lab must be of length two')
}
}
if( is.null(title_lab) == FALSE){
if( is.character(title_lab) == FALSE ){
return('title_lab argument must be of character class')
}
if( length(title_lab) != 1 ){
return('title_lab length must be one')
}
}
if( is.null(legend_lab) == FALSE ){
n_legend_lab <- length(legend_lab)
if( is.character(legend_lab) == FALSE ){
return('legend_lab must be of class character')
}
if( n_col_number != n_legend_lab){
return('You must provide as many legend_lab strings as line plots')
}
}
if( is.null(double_yaxis) == FALSE){
n_double_yaxis <- length(double_yaxis)
if( is.numeric(double_yaxis) == FALSE){
return('double_axis argument must be of numeric class')
}
if( interactive == FALSE){
if( n_double_yaxis != 2 ){
return('In interactive = FALSE double_yaxis arguments only allows a numeric vector of length two')
}
} else {
if(n_double_yaxis != n_col_number){
return('double_yaxis numeric vector argument must be of the same length as col_number')
}
}
target_nums <- c(1, 2)
match_nums <- match(x = double_yaxis, table = target_nums)
if( is.na( sum(match_nums) ) == TRUE ){
return('Only 1 and 2 are allow as arguments in double_yaxis')
}
}
if( is.null(list_extra) == FALSE ){
if( interactive == FALSE){
if( is.list(list_extra) == FALSE){
return('list_extra argument must be of list class')
}
}
}
if( is.null(from) == FALSE){
if( is.character(from) == FALSE ){
return('from must be of class character')
}
if( length(from) != 1){
return('from must be of length one')
}
}
if( is.null(to) == FALSE){
if( is.character(to) == FALSE ){
return('to must be of class character')
}
if( length(to) != 1){
return('to must be of length one')
}
}
if( is.null(scatter) == FALSE ){
if( is.numeric(scatter) == FALSE ){
return('scatter argument must be of class numeric')
}
if( length(scatter) != 2){
return('scatter supports just two variables. Please provide a numeric vector of length two.')
}
aux_sacatter <- match(x = scatter, table = col_number)
if( is.na( sum(aux_sacatter) ) == TRUE ){
return('scatter numbers must be included in col_number argument.')
}
}
Date <- value <- NULL
all_slots <- get_hydroMet(obj = obj, name = slot_name)
target_max_col <- sapply(X = all_slots, FUN = ncol)
if(n_slot_name == 1){
if(max(col_number) > target_max_col){
return('Unless one of the col_number does not exist in the slot')
}
} else {
for(i in 1:n_slot_name){
aux_col_num <- col_number[[i]]
if(max(aux_col_num) > target_max_col[i]){
return( paste0('Unless one of the col_number (', slot_name[i], ') does not exist in the slot') )
}
}
}
N_all_slots <- length(all_slots)
if(N_all_slots > 1){
unidades <- rep(NA_character_, N_all_slots)
paso_tpo <- rep(NA_character_, N_all_slots)
for(i in 1:N_all_slots){
unidades[i] <- units( diff.Date( all_slots[[i]][ , 1] ) )
paso_tpo[i] <- length(unique( diff.Date( all_slots[[i]][ , 1] ) ) )
}
if( length( unique(unidades)) != 1 ){
return('the variables must have the same temporal resolution')
}
if( unique(paso_tpo) != 1 ){
return('the variables must have the same temporal resolution')
}
}
if(N_all_slots > 1){
df_plot <- all_slots[[1]][ , c(1, col_number[[1]] )]
for(i in 2:N_all_slots){
df_aux <- all_slots[[i]][ , c(1, col_number[[i]] )]
df_plot <- merge(df_plot, df_aux, all = TRUE)
}
} else {
df_plot <- all_slots[[1]][ , c(1, col_number)]
}
if( is.null(from) == FALSE & is.null(to) == FALSE){
df_plot <- subset(df_plot, subset = Date >= from & Date <= to)
} else if( is.null(from) == FALSE ) {
df_plot <- subset(df_plot, subset = Date >= from)
} else if( is.null(to) == FALSE) {
df_plot <- subset(df_plot, subset = Date <= to)
}
if( is.null(scatter) == TRUE){
if( interactive == FALSE ){
if( is.null(double_yaxis) == TRUE){
N_plot <- nrow(df_plot)
N_var <- ncol(df_plot) - 1
if( is.null(legend_lab) == FALSE ){
tipo_linea <- list()
color_linea <- list()
leyen_linea <- list()
for(i in 1:N_var){
tipo_linea[[i]] <- rep(line_type[i], N_plot)
color_linea[[i]] <- rep(line_color[i], N_plot)
leyen_linea[[i]] <- rep(legend_lab[i], N_plot)
}
linea <- c(sapply(X = tipo_linea, '['))
color <- c(sapply(X = color_linea, '['))
leyen <- c(sapply(X = leyen_linea, '['))
df_plot2 <- melt(data = df_plot, id.vars = 'Date')
df_plot2 <- cbind(df_plot2, linea, color, leyen)
} else {
tipo_linea <- list()
color_linea <- list()
for(i in 1:N_var){
tipo_linea[[i]] <- rep(line_type[i], N_plot)
color_linea[[i]] <- rep(line_color[i], N_plot)
}
linea <- c(sapply(X = tipo_linea, '['))
color <- c(sapply(X = color_linea, '['))
df_plot2 <- melt(data = df_plot, id.vars = 'Date')
leyen <- df_plot2$variable
df_plot2 <- cbind(df_plot2, linea, color, leyen)
}
ggout <-
ggplot(data = df_plot2, aes(x = Date, y = value, color = leyen) ) +
geom_line(aes(linetype = leyen) ) +
scale_color_manual(values = line_color) +
scale_linetype_manual(values = line_type) +
theme(legend.title = element_blank()) +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab)
if( is.null(list_extra) == FALSE){
ggout <- ggout +
Reduce(f = c, x = list_extra)
}
return(ggout)
} else {
main_pos <- which(double_yaxis == 1) + 1
seco_pos <- which(double_yaxis == 2) + 1
y1 <- colnames(df_plot)[main_pos[1]]
y2 <- colnames(df_plot)[seco_pos[1]]
y1_plot <- colnames(df_plot)[main_pos]
y2_plot <- colnames(df_plot)[seco_pos]
m_plot <- as.matrix(x = df_plot[ , -1])
a <- range(df_plot[[y1]], na.rm = TRUE)
b <- range(df_plot[[y2]], na.rm = TRUE)
scale_factor <- diff(a)/diff(b)
m_plot[ , (seco_pos - 1)] <- ( (m_plot[ , (seco_pos - 1)] - b[1]) * scale_factor) + a[1]
trans <- ~ ((. - a[1]) / scale_factor) + b[1]
df_plot2 <- data.frame(df_plot[ , 1], m_plot)
colnames(df_plot2) <- colnames(df_plot)
ggout <-
ggplot(df_plot2) +
geom_line(aes_string('Date', y1_plot), col = line_color[ (main_pos - 1) ], lty = line_type[ (main_pos - 1) ] ) +
geom_line(aes_string('Date', y2_plot), col = line_color[ (seco_pos - 1) ], lty = line_type[ (seco_pos - 1) ] ) +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab[1]) +
scale_y_continuous(sec.axis = sec_axis(trans = trans, name = y_lab[2]))
if( is.null(list_extra) == FALSE){
ggout <- ggout +
Reduce(f = c, x = list_extra)
}
return(ggout)
}
} else {
if( is.null(double_yaxis) == TRUE ){
ppout <- plot_ly(df_plot, x = ~Date)
N_plots <- ncol(df_plot) - 1
for(i in 1:N_plots){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]) )
}
ppout <-
ppout %>%
layout(title = title_lab,
xaxis = list(title = x_lab),
yaxis = list(title = y_lab) )
return(ppout)
} else {
ppout <- plot_ly(df_plot, x = ~Date)
N_plots <- ncol(df_plot) - 1
for(i in 1:N_plots){
if(double_yaxis[i] == 1){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]) )
} else if (double_yaxis[i] == 2){
ppout <- ppout %>%
add_trace(y = df_plot[ , (i + 1)], name = legend_lab[i], type = 'scatter', mode = line_type[i], color = I(line_color[i]), yaxis = 'y2')
}
}
ppout <-
ppout %>%
layout(title = title_lab,
xaxis = list(title = x_lab),
yaxis = list(title = y_lab[1]),
yaxis2 = list(title = y_lab[2],
overlaying = 'y',
side = 'right') )
return(ppout)
}
}
} else {
if( interactive == FALSE){
df_col <- c(1, scatter)
pos_col <- match(x = scatter, table = df_col)
if( is.null(list_extra) == TRUE){
ggout <-
ggplot(data = df_plot, aes(x = df_plot[ , pos_col[1]], y = df_plot[ , pos_col[2]] ) ) +
geom_point() +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab)
} else {
ggout <-
ggplot(data = df_plot, aes(x = df_plot[ , pos_col[1]], y = df_plot[ , pos_col[2]] ) ) +
Reduce(f = c, x = list_extra) +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab)
}
return(ggout)
} else {
df_col <- c(1, scatter)
pos_col <- match(x = scatter, table = df_col)
if( is.null(list_extra) == TRUE){
ggout <-
ggplot(data = df_plot, aes(x = df_plot[ , pos_col[1]], y = df_plot[ , pos_col[2]] ) ) +
geom_point() +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab)
} else {
ggout <-
ggplot(data = df_plot, aes(x = df_plot[ , pos_col[1]], y = df_plot[ , pos_col[2]] ) ) +
Reduce(f = c, x = list_extra) +
ggtitle(label = title_lab) +
xlab(x_lab) + ylab(y_lab)
}
plotly_out <- ggplotly( p = ggout )
return(plotly_out)
}
}
}
) |
logRegOrdClass <- if (requireNamespace('jmvcore')) R6::R6Class(
"logRegOrdClass",
inherit = logRegOrdBase,
private = list(
terms = NULL,
coefTerms = list(),
thresTerms = list(),
emMeans = list(),
.init = function() {
private$.modelTerms()
private$.initModelFitTable()
private$.initModelCompTable()
private$.initModelSpec()
private$.initLrtTables()
private$.initCoefTables()
private$.initThresTables()
},
.run = function() {
ready <- TRUE
if (is.null(self$options$dep) || length(self$options$blocks) < 1 || length(self$options$blocks[[1]]) == 0)
ready <- FALSE
if (ready) {
data <- private$.cleanData()
private$.errorCheck(data)
results <- private$.compute(data)
private$.populateModelFitTable(results)
private$.populateModelCompTable(results)
private$.populateLrtTables(results)
private$.populateCoefTables(results)
private$.populateThresTables(results)
}
},
.compute = function(data) {
formulas <- private$.formulas()
globalContr <- options('contrasts')$contrasts
options('contrasts' = c('contr.treatment', 'contr.poly'))
on.exit(options('contrasts', substitute(globalContr)), add=TRUE)
suppressWarnings({
suppressMessages({
models <- list(); modelTest <- list(); lrTestTerms <- list(); dev <- list();
AIC <- list(); BIC <- list(); pseudoR <- list(); CI <- list(); CIOR <- list()
nullFormula <- as.formula(paste0(jmvcore::toB64(self$options$dep), '~ 1'))
nullModel <- MASS::polr(nullFormula, data=data, model=TRUE, Hess=TRUE)
null <- list(dev=nullModel$deviance, df=nullModel$edf)
for (i in seq_along(formulas)) {
models[[i]] <- MASS::polr(formulas[[i]], data=data, model=TRUE, Hess=TRUE)
models[[i]]$call$formula <- formulas[[i]]
lrTestTerms[[i]] <- car::Anova(models[[i]], test="LR", type=3, singular.ok=TRUE)
modelTest[[i]] <- private$.modelTest(models[[i]], null)
dev[[i]] <- models[[i]]$deviance
AIC[[i]] <- stats::AIC(models[[i]])
BIC[[i]] <- stats::BIC(models[[i]])
pseudoR[[i]] <- private$.pseudoR2(models[[i]], null)
CI[[i]] <- try(confint(models[[i]], level=self$options$ciWidth/100), silent=TRUE)
CILO <- try(confint(models[[i]], level=self$options$ciWidthOR/100), silent=TRUE)
CIOR[[i]] <- exp(CILO)
}
if (length(formulas) > 1)
lrTest <- do.call(stats::anova, c(models, test="Chisq"))
else
lrTest <- NULL
})
})
results <- list(models=models, modelTest=modelTest, lrTestTerms=lrTestTerms, dev=dev,
AIC=AIC, BIC=BIC, pseudoR=pseudoR, lrTest=lrTest, CI=CI, CIOR=CIOR)
return(results)
},
.initModelFitTable = function() {
table <- self$results$modelFit
for (i in seq_along(self$options$blocks))
table$addRow(rowKey=i, values=list(model = i))
dep <- self$options$dep
if ( ! is.null(dep) ) {
depLevels <- levels(self$data[[dep]])
} else {
return()
}
table$setNote("note", jmvcore::format("The dependent variable \'{}\' has the following order: {}", dep, paste(depLevels, collapse = ' | ')))
},
.initModelCompTable = function() {
table <- self$results$modelComp
terms <- private$terms
if (length(terms) <= 1) {
table$setVisible(visible = FALSE)
return()
}
for (i in 1:(length(terms)-1))
table$addRow(rowKey=i, values=list(model1 = i, model2 = as.integer(i+1)))
},
.initModelSpec = function() {
groups <- self$results$models
for (i in seq_along(self$options$blocks)) {
groups$addItem(key=i)
group <- groups$get(key=i)
group$setTitle(paste("Model",i))
}
},
.initLrtTables = function() {
groups <- self$results$models
termsAll <- private$terms
for (i in seq_along(termsAll)) {
table <- groups$get(key=i)$lrt
terms <- termsAll[[i]]
for (j in seq_along(terms))
table$addRow(rowKey=paste0(terms[[j]]), values=list(term = jmvcore::stringifyTerm(terms[j])))
}
},
.initCoefTables = function() {
groups <- self$results$models
termsAll <- private$terms
data <- self$data
factors <- self$options$factors
dep <- self$options$dep
if ( ! is.null(dep) ) {
depLevels <- levels(self$data[[dep]])
} else {
depLevels <- NULL
}
for (i in seq_along(termsAll)) {
table <- groups$get(key=i)$coef
ciWidth <- self$options$ciWidth
table$getColumn('lower')$setSuperTitle(jmvcore::format('{}% Confidence Interval', ciWidth))
table$getColumn('upper')$setSuperTitle(jmvcore::format('{}% Confidence Interval', ciWidth))
ciWidthOR <- self$options$ciWidthOR
table$getColumn('oddsLower')$setSuperTitle(jmvcore::format('{}% Confidence Interval', ciWidthOR))
table$getColumn('oddsUpper')$setSuperTitle(jmvcore::format('{}% Confidence Interval', ciWidthOR))
coefTerms <- list()
terms <- termsAll[[i]]
for (j in seq_along(terms)) {
if (any(terms[[j]] %in% factors)) {
table$addRow(rowKey=terms[[j]], values=list(term = paste0(jmvcore::stringifyTerm(terms[[j]]), ':'),
est='', se='', odds='', z='', p='',
lower='', upper='', oddsLower='', oddsUpper=''))
coefs <- private$.coefTerms(terms[[j]])
coefNames <- coefs$coefNames
for (k in seq_along(coefNames)) {
rowKey <- jmvcore::composeTerm(coefs$coefTerms[[k]])
table$addRow(rowKey=rowKey, values=list(term = coefNames[[k]]))
table$addFormat(rowKey=rowKey, col=1, Cell.INDENTED)
}
coefTerms <- c(coefTerms, coefs$coefTerms)
} else {
rowKey <- jmvcore::composeTerm(jmvcore::toB64(terms[[j]]))
table$addRow(rowKey=rowKey, values=list(term = jmvcore::stringifyTerm(terms[[j]])))
coefTerms[[length(coefTerms) + 1]] <- jmvcore::toB64(terms[[j]])
}
}
private$coefTerms[[i]] <- coefTerms
}
},
.initThresTables = function() {
groups <- self$results$models
termsAll <- private$terms
data <- self$data
dep <- self$options$dep
if ( ! is.null(dep) ) {
depLevels <- levels(self$data[[dep]])
} else {
return()
}
for (i in seq_along(termsAll)) {
table <- groups$get(key=i)$thres
thresTerms <- list()
for ( k in 1:(length(depLevels) - 1) ) {
rowKey <- paste0(jmvcore::toB64(depLevels[k]), '|', jmvcore::toB64(depLevels[k + 1]))
rowName <- paste0(depLevels[k], ' | ', depLevels[k + 1])
table$addRow(rowKey=rowKey, values=list(term = rowName))
thresTerms[[k]] <- rowKey
}
private$thresTerms[[i]] <- thresTerms
}
},
.populateModelFitTable = function(results) {
table <- self$results$modelFit
AIC <- results$AIC
BIC <- results$BIC
pR2 <- results$pseudoR
modelTest <- results$modelTest
dev <- results$dev
for (i in seq_along(AIC)) {
row <- list()
row[["r2mf"]] <- pR2[[i]]$r2mf
row[["r2cs"]] <- pR2[[i]]$r2cs
row[["r2n"]] <- pR2[[i]]$r2n
row[["dev"]] <- dev[[i]]
row[["aic"]] <- AIC[[i]]
row[["bic"]] <- BIC[[i]]
row[["chi"]] <- modelTest[[i]]$chi
row[["df"]] <- modelTest[[i]]$df
row[["p"]] <- modelTest[[i]]$p
table$setRow(rowNo=i, values = row)
}
},
.populateModelCompTable = function(results) {
table <- self$results$modelComp
models <- results$models
lrTest <- results$lrTest
r <- lrTest[-1,]
if (length(models) <= 1)
return()
for (i in 1:(length(models)-1)) {
row <- list()
row[["chi"]] <- r[['LR stat.']][i]
row[["df"]] <- r[[' Df']][i]
row[["p"]] <- r[['Pr(Chi)']][i]
table$setRow(rowNo=i, values = row)
}
},
.populateLrtTables = function(results) {
groups <- self$results$models
termsAll <- private$terms
lrTests <- results$lrTestTerms
for (i in seq_along(termsAll)) {
table <- groups$get(key=i)$lrt
terms <- termsAll[[i]]
termsB64 <- lapply(terms, jmvcore::toB64)
lrt <- lrTests[[i]]
rowTerms <- jmvcore::decomposeTerms(rownames(lrt))
for (j in seq_along(terms)) {
term <- termsB64[[j]]
index <- which(length(term) == sapply(rowTerms, length) &
sapply(rowTerms, function(x) all(term %in% x)))
row <- list()
row[["chi"]] <- lrt[index, 'LR Chisq']
row[["df"]] <- lrt[index, 'Df']
row[["p"]] <- lrt[index, 'Pr(>Chisq)']
table$setRow(rowKey=paste0(terms[[j]]), values = row)
}
}
},
.populateCoefTables = function(results) {
groups <- self$results$models
termsAll <- private$coefTerms
models <- results$models
for (i in seq_along(termsAll)) {
table <- groups$get(key=i)$coef
model <- summary(models[[i]])
CI <- results$CI[[i]]
CIOR <- results$CIOR[[i]]
coef<- model$coefficients[,1]
se <- model$coefficients[,2]
wald <- model$coefficients[,3]
p <- (1 - pnorm(abs(wald), 0, 1)) * 2
terms <- termsAll[[i]]
rowTerms <- jmvcore::decomposeTerms(names(coef))
for (k in seq_along(terms)) {
term <- terms[[k]]
index <- which(length(term) == sapply(rowTerms, length) &
sapply(rowTerms, function(x) all(term %in% x)))
row <- list()
row[["est"]] <- coef[index]
row[["se"]] <- se[index]
row[["odds"]] <- exp(coef[index])
row[["z"]] <- wald[index]
row[["p"]] <- p[index]
if (length(terms) == 1) {
row[["lower"]] <- CI[1]
row[["upper"]] <- CI[2]
row[["oddsLower"]] <- CIOR[1]
row[["oddsUpper"]] <- CIOR[2]
} else {
row[["lower"]] <- CI[index, 1]
row[["upper"]] <- CI[index, 2]
row[["oddsLower"]] <- CIOR[index, 1]
row[["oddsUpper"]] <- CIOR[index, 2]
}
table$setRow(rowKey=jmvcore::composeTerm(terms[[k]]), values = row)
}
}
},
.populateThresTables = function(results) {
groups <- self$results$models
termsAll <- private$thresTerms
models <- results$models
for (i in seq_along(termsAll)) {
table <- groups$get(key=i)$thres
model <- summary(models[[i]])
coef<- model$coefficients[,1]
se <- model$coefficients[,2]
wald <- model$coefficients[,3]
p <- (1 - pnorm(abs(wald), 0, 1)) * 2
terms <- termsAll[[i]]
rowTerms <- names(coef)
for (k in seq_along(terms)) {
term <- terms[[k]]
index <- which(term == rowTerms)
row <- list()
row[["est"]] <- coef[index]
row[["se"]] <- se[index]
row[["odds"]] <- exp(coef[index])
row[["z"]] <- wald[index]
row[["p"]] <- p[index]
table$setRow(rowKey=terms[[k]], values = row)
}
}
},
.modelTerms = function() {
blocks <- self$options$blocks
terms <- list()
if (is.null(blocks)) {
terms[[1]] <- c(self$options$covs, self$options$factors)
} else {
for (i in seq_along(blocks)) {
terms[[i]] <- unlist(blocks[1:i], recursive = FALSE)
}
}
private$terms <- terms
},
.coefTerms = function(terms) {
covs <- self$options$covs
factors <- self$options$factors
refLevels <- self$options$refLevels
refVars <- sapply(refLevels, function(x) x$var)
levels <- list()
for (factor in factors)
levels[[factor]] <- levels(self$data[[factor]])
contrLevels <- list(); refLevel <- list(); contr <- list(); rContr <- list()
for (term in terms) {
if (term %in% factors) {
ref <- refLevels[[which(term == refVars)]][['ref']]
refNo <- which(ref == levels[[term]])
contrLevels[[term]] <- levels[[term]][-refNo]
refLevel[[term]] <- levels[[term]][refNo]
if (length(terms) > 1)
contr[[term]] <- paste0('(', paste(contrLevels[[term]], refLevel[[term]], sep = ' \u2013 '), ')')
else
contr[[term]] <- paste(contrLevels[[term]], refLevel[[term]], sep = ' \u2013 ')
rContr[[term]] <- paste0(jmvcore::toB64(term), jmvcore::toB64(contrLevels[[term]]))
} else {
contr[[term]] <- term
rContr[[term]] <- jmvcore::toB64(term)
}
}
grid <- expand.grid(contr)
coefNames <- apply(grid, 1, jmvcore::stringifyTerm)
grid2 <- expand.grid(rContr)
coefTerms <- list()
for (i in 1:nrow(grid2))
coefTerms[[i]] <- as.character(unlist(grid2[i,]))
return(list(coefNames=coefNames, coefTerms=coefTerms))
},
.formulas = function() {
dep <- self$options$dep
depB64 <- jmvcore::toB64(dep)
terms <- private$terms
formulas <- list();
for (i in seq_along(terms)) {
termsB64 <- lapply(terms[[i]], jmvcore::toB64)
composedTerms <- jmvcore::composeTerms(termsB64)
formulas[[i]] <- as.formula(paste(depB64, paste0(composedTerms, collapse ="+"), sep="~"))
}
return(formulas)
},
.errorCheck = function(data) {
dep <- self$options$dep
column <- data[[jmvcore::toB64(dep)]]
if (length(levels(column)) == 2)
jmvcore::reject(jmvcore::format('The dependent variable \'{}\' has only two levels, consider doing a binomial logistic regression.', dep), code='')
},
.cleanData = function() {
dep <- self$options$dep
covs <- self$options$covs
factors <- self$options$factors
refLevels <- self$options$refLevels
dataRaw <- self$data
data <- list()
data[[jmvcore::toB64(dep)]] <- factor(jmvcore::toB64(as.character(dataRaw[[dep]])),
levels=jmvcore::toB64(levels(dataRaw[[dep]])))
refVars <- sapply(refLevels, function(x) x$var)
for (factor in factors) {
ref <- refLevels[[which(factor == refVars)]][['ref']]
rows <- jmvcore::toB64(as.character(dataRaw[[factor]]))
levels <- jmvcore::toB64(levels(dataRaw[[factor]]))
column <- factor(rows, levels=levels)
column <- relevel(column, ref = jmvcore::toB64(ref))
data[[jmvcore::toB64(factor)]] <- column
}
for (cov in covs)
data[[jmvcore::toB64(cov)]] <- jmvcore::toNumeric(dataRaw[[cov]])
attr(data, 'row.names') <- seq_len(length(data[[1]]))
attr(data, 'class') <- 'data.frame'
data <- jmvcore::naOmit(data)
return(data)
},
.createContrasts=function(levels) {
nLevels <- length(levels)
dummy <- contr.treatment(levels)
dimnames(dummy) <- NULL
coding <- matrix(rep(1/nLevels, prod(dim(dummy))), ncol=nLevels-1)
contrast <- (dummy - coding)
return(contrast)
},
.pseudoR2 = function(model, null) {
dev <- model$deviance
n <- length(model$fitted.values)
r2mf <- 1 - dev/null$dev
r2cs <- 1 - exp(-(null$dev - dev) / n)
r2n <- r2cs / (1 - exp(-null$dev / n))
return(list(r2mf=r2mf, r2cs=r2cs, r2n=r2n))
},
.modelTest = function(model, null) {
chi <- null$dev - model$deviance
df <- abs(null$df - model$edf)
p <- 1 - pchisq(chi, df)
return(list(chi=chi, df=df, p=p))
})
) |
library(tfestimators)
inputs <- input_fn(
iris,
response = "Species",
features = c(
"Sepal.Length",
"Sepal.Width",
"Petal.Length",
"Petal.Width"),
batch_size = 10
)
custom_model_fn <- function(features, labels, mode, params, config) {
logits <- features %>%
tf$contrib$layers$stack(
tf$contrib$layers$fully_connected, c(10L, 20L, 10L),
normalizer_fn = tf$contrib$layers$dropout,
normalizer_params = list(keep_prob = 0.9)) %>%
tf$contrib$layers$fully_connected(3L, activation_fn = NULL)
predicted_classes <- tf$argmax(logits, 1L)
if (mode == "infer") {
predictions <- list(
class = predicted_classes,
prob = tf$nn$softmax(logits))
return(estimator_spec(mode = mode, predictions = predictions))
}
onehot_labels <- tf$one_hot(labels, 3L, 1L, 0L)
loss <- tf$losses$softmax_cross_entropy(onehot_labels, logits)
if (mode == "train") {
global_step <- tf$train$get_global_step()
learning_rate <- tf$train$exponential_decay(
learning_rate = 0.1,
global_step = global_step,
decay_steps = 100L,
decay_rate = 0.001)
optimizer <- tf$train$AdagradOptimizer(learning_rate = learning_rate)
train_op <- optimizer$minimize(loss, global_step = global_step)
return(estimator_spec(mode = mode, loss = loss, train_op = train_op))
}
eval_metric_ops <- list(
accuracy = tf$metrics$accuracy(
labels = labels, predictions = predicted_classes
))
return(estimator_spec(mode = mode, loss = loss, eval_metric_ops = eval_metric_ops))
}
model_dir <- "/tmp/iris-custom-decay-cnn-model"
classifier <- estimator(
model_fn = custom_model_fn, model_dir = model_dir)
classifier %>% train(input_fn = inputs, steps = 100)
predictions <- predict(classifier, input_fn = inputs) |
test_that("List of datasets makes sense", {
expect_equivalent(unique(sp_datasets), sp_datasets)
expect_equivalent(unique(sp_datasets$id), sp_datasets$id)
expect_equivalent(unique(sp_datasets$name), sp_datasets$name)
expect_equivalent(sort(sp_datasets$id), sp_datasets$id)
expect_equivalent(dplyr::distinct(sp_datasets), sp_datasets)
})
test_that("get_dataset breaks on nonsense", {
expect_error(sp_get_dataset("blah", 2012, 10))
})
check_dataset_error <- function(dataset, year, month) {
url <- sp_get_dataset_url(dataset, year, month)
}
test_that("select downloads exist", {
skip_on_cran()
expect_type(purrr::map_chr(sp_datasets$id[sp_datasets$id != "finu"],
sp_get_dataset_url, year = 2015, month = 12),
type = "character")
expect_type(sp_get_dataset_url("finm", 2015, "12"), "character")
expect_error(sp_get_dataset_url("finu"))
expect_error(sp_get_dataset_url("x"))
}) |
test.ConstFc=function(){
obj1=ConstFc(c(0,0),"Delta14C")
obj2=ConstFc(c(0,0),"AbsoluteFractionModern")
checkException( ConstFc(c(0,0),"foo-bar"))
obj3=Delta14C(AbsoluteFractionModern(obj1))
checkEquals(getFormat(obj3),getFormat(obj1))
checkEquals(getValues(obj3),getValues(obj1))
obj4=AbsoluteFractionModern(Delta14C(obj2))
checkEquals(getFormat(obj4),getFormat(obj2))
checkEquals(getValues(obj4),getValues(obj2))
} |
sobolmara <- function(model = NULL, X1, ...) {
p <- ncol(X1)
n <- nrow(X1)
XX <- matrix(1:n,ncol=p,nrow=n)
RP <- apply(XX,2,sample)
X2 <- X1
for (j in 1:p) X2[,j] <- X1[RP[,j],j]
X <- rbind(X1, X2)
x <- list(model = model, X1 = X1, RP = RP, X = X, call = match.call())
class(x) <- "sobolmara"
if (! is.null(x$model)) {
response(x, ...)
x=tell(x, ...)
}
return(x)
}
estim.sobolmara <- function(data, i = 1 : nrow(data), RP) {
d <- as.matrix(data[i, ])
n <- nrow(d)
p <- ncol(RP)
V <- var(d[, 1])
m2 <- mean(d[,1])^2
VCE <- NULL
for (j in 1:p){
hoy <- 0
hoy <- sum(d[RP[,j],1]*d[,2])
VCE <- cbind(VCE, hoy / (n - 1) - m2)
}
c(V, VCE)
}
tell.sobolmara <- function(x, y = NULL, return.var = NULL, ...) {
id <- deparse(substitute(x))
if (! is.null(y)) {
x$y <- y
} else if (is.null(x$y)) {
stop("y not found")
}
p <- ncol(x$X1)
n <- nrow(x$X1)
data <- matrix(x$y, nrow = n)
V <- data.frame(original = estim.sobolmara(data,RP=x$RP))
rownames(V) <- c("global", colnames(x$X1))
S <- V[2:(p + 1), 1, drop = FALSE] / V[1,1]
rownames(S) <- colnames(x$X1)
x$V <- V
x$S <- S
for (i in return.var) {
x[[i]] <- get(i)
}
assign(id, x, parent.frame())
}
print.sobolmara <- function(x, ...) {
cat("\nCall:\n", deparse(x$call), "\n", sep = "")
if (! is.null(x$y)) {
cat("\nModel runs:", length(x$y), "\n")
if (! is.null(x$S)) {
cat("\nSobol indices\n")
print(x$S)
}
} else {
cat("(empty)\n")
}
}
plot.sobolmara <- function(x, ylim = c(0, 1), ...) {
if (! is.null(x$y)) {
nodeplot(x$S, ylim = ylim)
}
}
ggplot.sobolmara <- function(x, ylim = c(0, 1), ...) {
if (! is.null(x$y)) {
nodeggplot(listx = list(x$S), xname="",ylim = ylim)
}
}
plotMultOut.sobolmara <- function(x, ylim = c(0, 1), ...) {
if (!is.null(x$y)) {
p <- ncol(x$X1)
if (!x$ubiquitous){
stop("Cannot plot functional indices since ubiquitous option was not activated")
}else{
if (x$Tot == T) par(mfrow=c(2,1))
plot(0,ylim=ylim,xlim=c(1,x$q),main="First order Sobol indices",ylab="",xlab="",type="n")
for (i in 1:p) lines(x$Sfct[,i],col=i)
legend(x = "topright", legend = dimnames(x$X1)[[2]], lty=1, col=1:p, cex=0.6)
if (x$Tot == T){
plot(0,ylim=ylim,xlim=c(1,x$q),main="Total Sobol indices",ylab="",xlab="",type="n")
for (i in 1:p) lines(x$Tfct[,i],col=i)
legend(x = "topright", legend = dimnames(x$X1)[[2]], lty=1, col=1:p, cex=0.6)
}
}
}
} |
.isConnected <- function(site="https://www.google.com") {
uoc <- function(site) {
con <- url(site)
open(con)
close(con)
}
suppressWarnings(!inherits(try(uoc(site), silent=TRUE), "try-error"))
} |
InitErgmm.rsender<-function(model, var=1, var.df=3){
if (!is.directed(model[["Yg"]]))
stop("Sender effects are not allowed with an undirected network; use 'sociality'", call.=FALSE)
model[["sender"]]<-TRUE
model[["prior"]][["sender.var"]]<-var
model[["prior"]][["sender.var.df"]]<-var.df
model
}
InitErgmm.rreceiver<-function(model, var=1, var.df=3){
if (!is.directed(model[["Yg"]]))
stop("receiver effects are not allowed with an undirected network; use 'sociality'", call.=FALSE)
model[["receiver"]]<-TRUE
model[["prior"]][["receiver.var"]]<-var
model[["prior"]][["receiver.var.df"]]<-var.df
model
}
InitErgmm.rsociality<-function(model, var=1, var.df=3){
model[["sociality"]]<-TRUE
model[["prior"]][["sociality.var"]]<-var
model[["prior"]][["sociality.var.df"]]<-var.df
model
} |
expected <- eval(parse(text="TRUE"));
test(id=0, code={
argv <- eval(parse(text="list(logical(0))"));
do.call(`all`, argv);
}, o=expected); |
CalmarRatio <- function (R, scale = NA)
{
R = checkData(R)
if(is.na(scale)) {
freq = periodicity(R)
switch(freq$scale,
minute = {stop("Data periodicity too high")},
hourly = {stop("Data periodicity too high")},
daily = {scale = 252},
weekly = {scale = 52},
monthly = {scale = 12},
quarterly = {scale = 4},
yearly = {scale = 1}
)
}
annualized_return = Return.annualized(R, scale=scale)
drawdown = abs(maxDrawdown(R))
result = annualized_return/drawdown
rownames(result) = "Calmar Ratio"
return(result)
}
SterlingRatio <-
function (R, scale=NA, excess=.1)
{
R = checkData(R)
if(is.na(scale)) {
freq = periodicity(R)
switch(freq$scale,
minute = {stop("Data periodicity too high")},
hourly = {stop("Data periodicity too high")},
daily = {scale = 252},
weekly = {scale = 52},
monthly = {scale = 12},
quarterly = {scale = 4},
yearly = {scale = 1}
)
}
annualized_return = Return.annualized(R, scale=scale)
drawdown = abs(maxDrawdown(R)+excess)
result = annualized_return/drawdown
rownames(result) = paste("Sterling Ratio (Excess = ", round(excess*100,0), "%)", sep="")
return(result)
} |
"IV_step1" |
expected <- eval(parse(text="structure(c(-1e-05, 1e-05, -1e-04, 1e-04, -0.001, 0.001, -0.01, 0.01, -0.1, 0.1, -1, 1, -10, 10, -100, 100, -1000, 1000, -10000, 10000, -1e+05, 1e+05), .Dim = c(2L, 11L))"));
test(id=0, code={
argv <- eval(parse(text="list(c(-1, 1), structure(c(1e-05, 1e-04, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 10000, 1e+05), .Dim = c(1L, 11L)))"));
do.call(`%*%`, argv);
}, o=expected); |
ggplot_pca <- function(x,
choices = 1:2,
scale = 1,
pc.biplot = TRUE,
labels = NULL,
labels_textsize = 3,
labels_text_placement = 1.5,
groups = NULL,
ellipse = TRUE,
ellipse_prob = 0.68,
ellipse_size = 0.5,
ellipse_alpha = 0.5,
points_size = 2,
points_alpha = 0.25,
arrows = TRUE,
arrows_colour = "darkblue",
arrows_size = 0.5,
arrows_textsize = 3,
arrows_textangled = TRUE,
arrows_alpha = 0.75,
base_textsize = 10,
...) {
stop_ifnot_installed("ggplot2")
meet_criteria(x, allow_class = c("prcomp", "princomp", "PCA", "lda"))
meet_criteria(choices, allow_class = c("numeric", "integer"), has_length = 2, is_positive = TRUE, is_finite = TRUE)
meet_criteria(scale, allow_class = c("numeric", "integer", "logical"), has_length = 1)
meet_criteria(pc.biplot, allow_class = "logical", has_length = 1)
meet_criteria(labels, allow_class = "character", allow_NULL = TRUE)
meet_criteria(labels_textsize, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
meet_criteria(labels_text_placement, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
meet_criteria(groups, allow_class = "character", allow_NULL = TRUE)
meet_criteria(ellipse, allow_class = "logical", has_length = 1)
meet_criteria(ellipse_prob, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
meet_criteria(ellipse_size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
meet_criteria(ellipse_alpha, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
meet_criteria(points_size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
meet_criteria(points_alpha, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
meet_criteria(arrows, allow_class = "logical", has_length = 1)
meet_criteria(arrows_colour, allow_class = "character", has_length = 1)
meet_criteria(arrows_size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
meet_criteria(arrows_textsize, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
meet_criteria(arrows_textangled, allow_class = "logical", has_length = 1)
meet_criteria(arrows_alpha, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
meet_criteria(base_textsize, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
calculations <- pca_calculations(pca_model = x,
groups = groups,
groups_missing = missing(groups),
labels = labels,
labels_missing = missing(labels),
choices = choices,
scale = scale,
pc.biplot = pc.biplot,
ellipse_prob = ellipse_prob,
labels_text_placement = labels_text_placement)
choices <- calculations$choices
df.u <- calculations$df.u
df.v <- calculations$df.v
ell <- calculations$ell
groups <- calculations$groups
group_name <- calculations$group_name
labels <- calculations$labels
if ((1 - as.integer(scale)) == 0) {
u.axis.labs <- paste0("Standardised PC", choices)
} else {
u.axis.labs <- paste0("PC", choices)
}
u.axis.labs <- paste0(u.axis.labs,
paste0("\n(explained var: ",
percentage(x$sdev[choices] ^ 2 / sum(x$sdev ^ 2)),
")"))
if (!is.null(labels)) {
df.u$labels <- labels
}
if (!is.null(groups)) {
df.u$groups <- groups
}
g <- ggplot2::ggplot(data = df.u,
ggplot2::aes(x = xvar, y = yvar)) +
ggplot2::xlab(u.axis.labs[1]) +
ggplot2::ylab(u.axis.labs[2]) +
ggplot2::expand_limits(x = c(-1.15, 1.15),
y = c(-1.15, 1.15))
if (!is.null(df.u$labels)) {
if (!is.null(df.u$groups)) {
g <- g + ggplot2::geom_point(ggplot2::aes(colour = groups),
alpha = points_alpha,
size = points_size) +
ggplot2::geom_text(ggplot2::aes(label = labels, colour = groups),
nudge_y = -0.05,
size = labels_textsize) +
ggplot2::labs(colour = group_name)
} else {
g <- g + ggplot2::geom_point(alpha = points_alpha,
size = points_size) +
ggplot2::geom_text(ggplot2::aes(label = labels),
nudge_y = -0.05,
size = labels_textsize)
}
} else {
if (!is.null(df.u$groups)) {
g <- g + ggplot2::geom_point(ggplot2::aes(colour = groups),
alpha = points_alpha,
size = points_size) +
ggplot2::labs(colour = group_name)
} else {
g <- g + ggplot2::geom_point(alpha = points_alpha,
size = points_size)
}
}
if (!is.null(df.u$groups) & !is.null(ell) & isTRUE(ellipse)) {
g <- g + ggplot2::geom_path(data = ell,
ggplot2::aes(colour = groups, group = groups),
size = ellipse_size,
alpha = points_alpha)
}
if (arrows == TRUE) {
g <- g + ggplot2::geom_segment(data = df.v,
ggplot2::aes(x = 0, y = 0, xend = xvar, yend = yvar),
arrow = ggplot2::arrow(length = ggplot2::unit(0.5, "picas"),
angle = 20,
ends = "last",
type = "open"),
colour = arrows_colour,
size = arrows_size,
alpha = arrows_alpha)
if (arrows_textangled == TRUE) {
g <- g + ggplot2::geom_text(data = df.v,
ggplot2::aes(label = varname, x = xvar, y = yvar, angle = angle, hjust = hjust),
colour = arrows_colour,
size = arrows_textsize,
alpha = arrows_alpha)
} else {
g <- g + ggplot2::geom_text(data = df.v,
ggplot2::aes(label = varname, x = xvar, y = yvar, hjust = hjust),
colour = arrows_colour,
size = arrows_textsize,
alpha = arrows_alpha)
}
}
g <- g + ggplot2::labs(caption = paste0("Total explained variance: ",
percentage(sum(x$sdev[choices] ^ 2 / sum(x$sdev ^ 2)))))
g <- g + ggplot2::theme_minimal(base_size = base_textsize) +
ggplot2::theme(panel.grid.major = ggplot2::element_line(colour = "grey85"),
panel.grid.minor = ggplot2::element_blank(),
plot.title = ggplot2::element_text(hjust = 0.5),
plot.subtitle = ggplot2::element_text(hjust = 0.5))
g
}
pca_calculations <- function(pca_model,
groups = NULL,
groups_missing = TRUE,
labels = NULL,
labels_missing = TRUE,
choices = 1:2,
scale = 1,
pc.biplot = TRUE,
ellipse_prob = 0.68,
labels_text_placement = 1.5) {
non_numeric_cols <- attributes(pca_model)$non_numeric_cols
if (groups_missing) {
groups <- tryCatch(non_numeric_cols[[1]],
error = function(e) NULL)
group_name <- tryCatch(colnames(non_numeric_cols[1]),
error = function(e) NULL)
}
if (labels_missing) {
labels <- tryCatch(non_numeric_cols[[2]],
error = function(e) NULL)
}
if (!is.null(groups) & is.null(labels)) {
labels <- groups
groups <- NULL
group_name <- NULL
}
if (inherits(pca_model, "prcomp")) {
nobs.factor <- sqrt(nrow(pca_model$x) - 1)
d <- pca_model$sdev
u <- sweep(pca_model$x, 2, 1 / (d * nobs.factor), FUN = "*")
v <- pca_model$rotation
} else if (inherits(pca_model, "princomp")) {
nobs.factor <- sqrt(pca_model$n.obs)
d <- pca_model$sdev
u <- sweep(pca_model$scores, 2, 1 / (d * nobs.factor), FUN = "*")
v <- pca_model$loadings
} else if (inherits(pca_model, "PCA")) {
nobs.factor <- sqrt(nrow(pca_model$call$X))
d <- unlist(sqrt(pca_model$eig)[1])
u <- sweep(pca_model$ind$coord, 2, 1 / (d * nobs.factor), FUN = "*")
v <- sweep(pca_model$var$coord, 2, sqrt(pca_model$eig[seq_len(ncol(pca_model$var$coord)), 1]), FUN = "/")
} else if (inherits(pca_model, "lda")) {
nobs.factor <- sqrt(pca_model$N)
d <- pca_model$svd
u <- predict(pca_model)$x / nobs.factor
v <- pca_model$scaling
} else {
stop("Expected an object of class prcomp, princomp, PCA, or lda")
}
choices <- pmin(choices, ncol(u))
obs.scale <- 1 - as.integer(scale)
df.u <- as.data.frame(sweep(u[, choices], 2, d[choices] ^ obs.scale, FUN = "*"),
stringsAsFactors = FALSE)
v <- sweep(v, 2, d ^ as.integer(scale), FUN = "*")
df.v <- as.data.frame(v[, choices],
stringsAsFactors = FALSE)
names(df.u) <- c("xvar", "yvar")
names(df.v) <- names(df.u)
if (isTRUE(pc.biplot)) {
df.u <- df.u * nobs.factor
}
circle_prob <- 0.69
r <- sqrt(qchisq(circle_prob, df = 2)) * prod(colMeans(df.u ^ 2)) ^ (0.25)
v.scale <- rowSums(v ^ 2)
df.v <- r * df.v / sqrt(max(v.scale))
if (!is.null(groups)) {
df.u$groups <- groups
}
df.v$varname <- rownames(v)
df.v$angle <- with(df.v, (180 / pi) * atan(yvar / xvar))
df.v$hjust <- with(df.v, (1 - labels_text_placement * sign(xvar)) / 2)
if (!is.null(df.u$groups)) {
theta <- c(seq(-pi, pi, length = 50), seq(pi, -pi, length = 50))
circle <- cbind(cos(theta), sin(theta))
df.groups <- lapply(unique(df.u$groups), function(g, df = df.u) {
x <- df[which(df$groups == g), , drop = FALSE]
if (nrow(x) <= 2) {
return(data.frame(X1 = numeric(0),
X2 = numeric(0),
groups = character(0),
stringsAsFactors = FALSE))
}
sigma <- var(cbind(x$xvar, x$yvar))
mu <- c(mean(x$xvar), mean(x$yvar))
ed <- sqrt(qchisq(ellipse_prob, df = 2))
data.frame(sweep(circle %*% chol(sigma) * ed,
MARGIN = 2,
STATS = mu,
FUN = "+"),
groups = x$groups[1],
stringsAsFactors = FALSE)
})
ell <- do.call(rbind, df.groups)
if (NROW(ell) == 0) {
ell <- NULL
} else {
names(ell)[1:2] <- c("xvar", "yvar")
}
} else {
ell <- NULL
}
list(choices = choices,
df.u = df.u,
df.v = df.v,
ell = ell,
groups = groups,
group_name = group_name,
labels = labels
)
} |
library(testthat)
if (T){
library(gRim)
test_check("gRim")
} |
library(testthat)
library(recipes)
library(modeldata)
data(biomass)
biomass_tr <- biomass[biomass$dataset == "Training",]
biomass_te <- biomass[biomass$dataset == "Testing",]
rec <- recipe(HHV ~ carbon + hydrogen + oxygen + nitrogen + sulfur,
data = biomass_tr)
test_that('correct PCA values', {
pca_extract <- rec %>%
step_center(carbon, hydrogen, oxygen ,nitrogen, sulfur) %>%
step_scale(carbon, hydrogen, oxygen ,nitrogen, sulfur) %>%
step_pca(carbon, hydrogen, oxygen, nitrogen, sulfur,
options = list(retx = TRUE), id = "")
pca_extract_trained <- prep(pca_extract, training = biomass_tr, verbose = FALSE)
pca_pred <- bake(pca_extract_trained, new_data = biomass_te, all_predictors())
pca_pred <- as.matrix(pca_pred)
pca_exp <- prcomp(biomass_tr[, 3:7], center = TRUE, scale. = TRUE, retx = TRUE)
pca_pred_exp <- predict(pca_exp, biomass_te[, 3:7])[, 1:pca_extract$steps[[3]]$num_comp]
rownames(pca_pred) <- NULL
rownames(pca_pred_exp) <- NULL
expect_equal(pca_pred, pca_pred_exp)
tidy_exp_un <- tibble(
terms = c("carbon", "hydrogen", "oxygen" ,"nitrogen", "sulfur"),
value = rep(NA_real_, 5),
component = rep(NA_character_, 5),
id = ""
)
expect_equal(tidy_exp_un, tidy(pca_extract, number = 3))
pca_obj <- prcomp(
x = biomass_tr[, c("carbon", "hydrogen", "oxygen" ,"nitrogen", "sulfur")],
scale. = TRUE)
variances <- pca_obj$sdev^2
pca_obj <- pca_obj$rotation
pca_obj <- as.data.frame(pca_obj)
pca_obj <- utils::stack(pca_obj)
tidy_exp_tr <- tibble(
terms = rep(tidy_exp_un$terms, pca_extract_trained$steps[[3]]$num_comp),
value = pca_obj$values,
component = as.character(pca_obj$ind),
id = ""
)
expect_equal(
as.data.frame(tidy_exp_tr),
as.data.frame(tidy(pca_extract_trained, number = 3))
)
var_obj <- tidy(pca_extract_trained, number = 3, type = "variance")
expect_equal(
var_obj$value[var_obj$terms == "variance"],
variances
)
expect_equal(
var_obj$value[var_obj$terms == "cumulative variance"],
cumsum(variances)
)
expect_equal(
var_obj$value[var_obj$terms == "percent variance"],
variances / sum(variances) * 100
)
expect_equal(
var_obj$value[var_obj$terms == "cumulative percent variance"],
cumsum(variances) / sum(variances) * 100
)
expect_error(tidy(pca_extract_trained, number = 3, type = "variances"),
"variance")
})
test_that('correct PCA values with threshold', {
pca_extract <- rec %>%
step_center(carbon, hydrogen, oxygen ,nitrogen, sulfur) %>%
step_scale(carbon, hydrogen, oxygen ,nitrogen, sulfur) %>%
step_pca(carbon, hydrogen, oxygen, nitrogen, sulfur, threshold = .5)
pca_extract_trained <- prep(pca_extract, training = biomass_tr, verbose = FALSE)
pca_exp <- prcomp(biomass_tr[, 3:7], center = TRUE, scale. = TRUE, retx = TRUE)
expect_equal(pca_extract_trained$steps[[3]]$num_comp, 2)
})
test_that('Reduced rotation size', {
pca_extract <- rec %>%
step_center(carbon, hydrogen, oxygen ,nitrogen, sulfur) %>%
step_scale(carbon, hydrogen, oxygen ,nitrogen, sulfur) %>%
step_pca(carbon, hydrogen, oxygen, nitrogen, sulfur, num_comp = 3)
pca_extract_trained <- prep(pca_extract, training = biomass_tr, verbose = FALSE)
pca_pred <- bake(pca_extract_trained, new_data = biomass_te, all_predictors())
pca_pred <- as.matrix(pca_pred)
pca_exp <- prcomp(biomass_tr[, 3:7], center = TRUE, scale. = TRUE, retx = TRUE)
pca_pred_exp <- predict(pca_exp, biomass_te[, 3:7])[, 1:3]
rownames(pca_pred_exp) <- NULL
rownames(pca_pred) <- NULL
rownames(pca_pred_exp) <- NULL
expect_equal(pca_pred, pca_pred_exp)
})
test_that('printing', {
pca_extract <- rec %>%
step_pca(carbon, hydrogen, oxygen, nitrogen, sulfur)
expect_output(print(pca_extract))
expect_output(prep(pca_extract, training = biomass_tr, verbose = TRUE))
})
test_that('No PCA comps', {
pca_extract <- rec %>%
step_pca(carbon, hydrogen, oxygen, nitrogen, sulfur, num_comp = 0)
pca_extract_trained <- prep(pca_extract, training = biomass_tr)
expect_equal(
names(juice(pca_extract_trained)),
names(biomass_tr)[-(1:2)]
)
expect_true(all(is.na(pca_extract_trained$steps[[1]]$res$rotation)))
expect_output(print(pca_extract_trained),
regexp = "No PCA components were extracted")
expect_true(all(is.na(tidy(pca_extract_trained, 1)$value)))
})
test_that('tunable', {
rec <-
recipe(~ ., data = iris) %>%
step_pca(all_predictors())
rec_param <- tunable.step_pca(rec$steps[[1]])
expect_equal(rec_param$name, c("num_comp", "threshold"))
expect_true(all(rec_param$source == "recipe"))
expect_true(is.list(rec_param$call_info))
expect_equal(nrow(rec_param), 2)
expect_equal(
names(rec_param),
c('name', 'call_info', 'source', 'component', 'component_id')
)
})
test_that('keep_original_cols works', {
pca_extract <- rec %>%
step_center(carbon, hydrogen, oxygen ,nitrogen, sulfur) %>%
step_scale(carbon, hydrogen, oxygen ,nitrogen, sulfur) %>%
step_pca(carbon, hydrogen, oxygen, nitrogen, sulfur,
options = list(retx = TRUE), id = "", keep_original_cols = TRUE)
pca_extract_trained <- prep(pca_extract, training = biomass_tr, verbose = FALSE)
pca_pred <- bake(pca_extract_trained, new_data = biomass_te, all_predictors())
expect_equal(
colnames(pca_pred),
c("carbon", "hydrogen", "oxygen", "nitrogen", "sulfur",
"PC1", "PC2", "PC3", "PC4", "PC5")
)
})
test_that('can prep recipes with no keep_original_cols', {
pca_extract <- rec %>%
step_center(carbon, hydrogen, oxygen ,nitrogen, sulfur) %>%
step_scale(carbon, hydrogen, oxygen ,nitrogen, sulfur) %>%
step_pca(carbon, hydrogen, oxygen, nitrogen, sulfur, num_comp = 3)
pca_extract$steps[[3]]$keep_original_cols <- NULL
expect_warning(
pca_extract_trained <- prep(pca_extract, training = biomass_tr, verbose = FALSE),
"'keep_original_cols' was added to"
)
expect_error(
pca_pred <- bake(pca_extract_trained, new_data = biomass_te, all_predictors()),
NA
)
}) |
mvrnormBase.svd <- function (n = 1, mu, Sigma, tol = 1e-06, empirical = FALSE)
{
p <- length(mu)
if (!all(dim(Sigma) == c(p, p)))
stop("incompatible arguments")
eS <- svd(Sigma)
ev <- eS$d
if (!all(ev >= -tol * abs(ev[1L])))
stop("'Sigma' is not positive definite")
X <- matrix(rnorm(p * n), n)
if (empirical) {
X <- scale(X, TRUE, FALSE)
X <- X %*% svd(X, nu = 0)$v
X <- scale(X, FALSE, TRUE)
}
X <- drop(mu) + eS$u %*% diag(sqrt(pmax(ev, 0)), p) %*%
t(X)
nm <- names(mu)
if (is.null(nm) && !is.null(dn <- dimnames(Sigma)))
nm <- dn[[1L]]
dimnames(X) <- list(nm, NULL)
if (n == 1)
drop(X)
else t(X)
} |
expected <- eval(parse(text="\"glm\""));
test(id=0, code={
argv <- eval(parse(text="list(\"glm\", 6, TRUE)"));
.Internal(abbreviate(argv[[1]], argv[[2]], argv[[3]]));
}, o=expected); |
max_min_assoc.ma = function(target, dataset, test, threshold, statistic, max_k, selectedVars, pvalues , stats , remainingVars , univariateModels, selectedVarsOrder, hash, stat_hash, pvalue_hash)
{
selected_var = -1;
selected_pvalue = 2;
selected_stat = 0;
varsToIterate = which(remainingVars==1);
for (cvar in varsToIterate) {
mma_res = min_assoc.ma(target, dataset, test, max_k, cvar, statistic, selectedVars , pvalues , stats , univariateModels , selectedVarsOrder, hash, stat_hash, pvalue_hash);
pvalues = mma_res$pvalues;
stats = mma_res$stats;
stat_hash = mma_res$stat_hash;
pvalue_hash = mma_res$pvalue_hash;
if (mma_res$pvalue > threshold) {
remainingVars[[cvar]] = 0;
}
if ( compare_p_values(mma_res$pvalue, selected_pvalue, mma_res$stat, selected_stat) ) {
selected_var = cvar;
selected_pvalue = mma_res$pvalue;
selected_stat = mma_res$stat;
}
}
results <- list(selected_var = selected_var , selected_pvalue = selected_pvalue , remainingVars = remainingVars , pvalues = pvalues , stats = stats, stat_hash=stat_hash, pvalue_hash = pvalue_hash);
return(results);
} |
MCPModSurv <- function(model = c("coxph", "parametric"), dist = NULL,
returnS = FALSE, dose, resp, status, data = NULL, models,
placAdj = FALSE, selModel = c("AIC", "maxT", "aveAIC"),
alpha = 0.025, df = NULL, critV = NULL,
doseType = c("TD", "ED"), Delta, p, pVal = TRUE,
alternative = c("one.sided", "two.sided"),
na.action = na.fail, mvtcontrol = mvtnorm.control(),
bnds, control = NULL, ...) {
if (!is.null(data)) {
if (class(data) != "data.frame") {
stop("data must be of class \"data.frame\"")
}
if (class(dose) != "character" | class(resp) != "character" | class(status) !=
"character") {
stop("dose, resp, and status must be of class \"character\" when supplying data")
}
dose.vec <- data[, dose]
resp.vec <- data[, resp]
status.vec <- data[, status]
} else {
if (class(dose) == "character" | class(resp) == "character" | class(status) ==
"character") {
stop("Must supply data when dose and resp are of class \"character\"")
}
if ((length(dose) != length(resp)) | (length(dose) != length(status))) {
stop("dose, resp, and status must be of equal length")
}
dose.vec <- dose
resp.vec <- resp
status.vec <- status
}
dat <- data.frame(dose = dose.vec, resp = resp.vec, status = status.vec)
dat$dose <- as.factor(dat$dose)
n.doses <- length(unique(dat$dose))
doses <- sort(unique(dose.vec))
model <- match.arg(model)
if (model == "coxph") {
cox.mod <- survival::coxph(survival::Surv(resp, status) ~ dose, data = dat,
...)
mu.hat <- coef(cox.mod)
S.hat <- vcov(cox.mod)
doses <- doses[-1]
mod.out <- MCPMod(doses, mu.hat, models = models, S = S.hat, type = "general",
placAdj = TRUE, selModel = selModel, alpha = alpha, df = df, critV = critV,
doseType = doseType, Delta = Delta, p = p, pVal = pVal, alternative = alternative,
na.action = na.action, mvtcontrol = mvtcontrol, bnds = bnds, control = control,
...)
} else {
if (!(dist %in% c("weibull", "exponential", "gaussian", "logistic", "lognormal",
"loglogistic"))) {
stop("dist must be one of \"weibull\", \"exponential\", \"gaussian\",
\"logistic\", \"lognormal\", \"loglogistic\".")
}
if (placAdj == FALSE) {
surv.mod <- survival::survreg(survival::Surv(resp, status) ~ dose - 1,
data = dat, dist = dist)
mu.hat <- coef(surv.mod)
S.hat <- vcov(surv.mod)
mod.out <- MCPMod(doses, mu.hat, models = models,
S = S.hat[1:n.doses, 1:n.doses], type = "general",
placAdj = FALSE, selModel = selModel, alpha = alpha,
df = df, critV = critV, doseType = doseType, Delta = Delta,
p = p, pVal = pVal, alternative = alternative,
na.action = na.action, mvtcontrol = mvtcontrol,
bnds = bnds, ...)
} else {
surv.mod <- survival::survreg(survival::Surv(resp, status) ~ dose, data = dat,
dist = dist)
mu.hat <- coef(surv.mod)
S.hat <- vcov(surv.mod)
mod.out <- MCPMod(doses[-1], mu.hat[-1], models = models,
S = S.hat[2:n.doses, 2:n.doses], type = "general",
placAdj = FALSE, selModel = selModel, alpha = alpha,
df = df, critV = critV, doseType = doseType,
Delta = Delta, p = p,
pVal = pVal, alternative = alternative,
na.action = na.action, mvtcontrol = mvtcontrol,
bnds = bnds, ...)
}
}
if (returnS == FALSE) {
return(mod.out)
} else {
data.df <- data.frame(dose = doses, resp = mu.hat)
return.list <- list(MCPMod = mod.out, data = data.df, S = S.hat)
return(return.list)
}
} |
Genes_SimCal <- function(ExpMat_Test, ExpMat_Ref1, ExpMat_Ref2, RefIDs, TestClassIter, SampleIter){
rownames(ExpMat_Ref1) <- NULL
colnames(ExpMat_Ref1) <- NULL
if(TestClassIter == RefIDs[1]){
ExpMat_Ref1 <- ExpMat_Ref1[,-SampleIter]
}
rownames(ExpMat_Ref2) <- NULL
colnames(ExpMat_Ref2) <- NULL
if(TestClassIter == RefIDs[2]){
ExpMat_Ref2 <- ExpMat_Ref2[,-SampleIter]
}
GeneVarSortInd <- sort(apply(cbind(ExpMat_Ref1, ExpMat_Ref2), 1, function(X){
mad(na.omit(as.numeric(X)))}), decreasing = T, index.return = T)[[2]]
BubbleSort_Vec1 <- c()
BubbleSort_Vec2 <- c()
Pearson_Vec1 <- c()
Pearson_Vec2 <- c()
NameVec <- c()
for(GeneNum in c(1e3,nrow(ExpMat_Ref1))){
NameVec <- c(NameVec, paste(GeneNum,"genes", sep = "", collapse = ""))
MostVarInd <- GeneVarSortInd[1:GeneNum]
TargetGenes_RefMat1 <- ExpMat_Ref1[MostVarInd,]
TargetGenes_RefMat2 <- ExpMat_Ref2[MostVarInd,]
TargetGenes_TestMat <- ExpMat_Test[MostVarInd,]
TargetGenes_Ref1Vec <- as.numeric(apply(TargetGenes_RefMat1,1,function(X){median(na.omit(as.numeric(X)))}))
TargetGenes_Ref2Vec <- as.numeric(apply(TargetGenes_RefMat2,1,function(X){median(na.omit(as.numeric(X)))}))
TargetGenes_TesTVec <- as.numeric(apply(TargetGenes_TestMat,1,function(X){median(na.omit(as.numeric(X)))}))
BubbleSort_Vec1 <- c(BubbleSort_Vec1, as.numeric(BubbleSort(TargetGenes_Ref1Vec, TargetGenes_TesTVec)))
Pearson_Vec1 <- c(Pearson_Vec1, as.numeric(cor.test(TargetGenes_Ref1Vec, TargetGenes_TesTVec)$estimate))
BubbleSort_Vec2 <- c(BubbleSort_Vec2, as.numeric(BubbleSort(TargetGenes_Ref2Vec, TargetGenes_TesTVec)))
Pearson_Vec2 <- c(Pearson_Vec2, as.numeric(cor.test(TargetGenes_Ref2Vec, TargetGenes_TesTVec)$estimate))
}
GeneSim_Out <- c(BubbleSort_Vec1, BubbleSort_Vec2, Pearson_Vec1, Pearson_Vec2)
names(GeneSim_Out) <- c(paste(rep("BubbleSort1"), NameVec, sep = "_"),
paste(rep("BubbleSort2"), NameVec, sep = "_"),
paste(rep("Pearson1"), NameVec, sep = "_"),
paste(rep("Pearson2"), NameVec, sep = "_"))
return(GeneSim_Out)
} |
library(highcharter)
library(quantmod)
library(magrittr)
options(highcharter.debug = TRUE)
aapl <- quantmod::getSymbols("AAPL",
src = "yahoo",
from = "2020-01-01",
auto.assign = FALSE
)
plain <- function() {
hc <- highcharter::highchart(type = "stock") %>%
highcharter::hc_title(text = "yAxis test") %>%
highcharter::hc_add_series(aapl, yAxis = 0, showInLegend = FALSE)
message("yAxis title: ", hc$x$hc_opts$yAxis)
return(hc)
}
with_yaxis <- function() {
hc <- highcharter::highchart(type = "stock") %>%
highcharter::hc_title(text = "yAxis test") %>%
highcharter::hc_add_series(aapl, yAxis = 0, showInLegend = FALSE) %>%
highcharter::hc_yAxis(title = list(text = "Prices"))
message("yAxis title: ", hc$x$hc_opts$yAxis)
return(hc)
}
with_both <- function() {
hc <- try(highcharter::highchart(type = "stock") %>%
highcharter::hc_title(text = "yAxis test") %>%
highcharter::hc_add_series(aapl, yAxis = 0, showInLegend = FALSE) %>%
highcharter::hc_yAxis(title = list(text = "Prices")) %>%
highcharter::hc_add_yAxis(title = list(text = "Should stop"))
)
message("yAxis 2: ", hc$x$hc_opts$yAxis)
return(hc)
}
with_add_yaxis <- function() {
hc <- highcharter::highchart(type = "stock") %>%
highcharter::hc_title(text = "yAxis test") %>%
highcharter::hc_add_series(aapl, yAxis = 0, showInLegend = FALSE) %>%
highcharter::hc_add_yAxis(title = list(text = "Prices"))
message("yAxis one: ", hc$x$hc_opts$yAxis)
return(hc)
}
with_plotline <- function() {
hc <- highcharter::highchart(type = "stock") %>%
highcharter::hc_title(text = "yAxis test") %>%
highcharter::hc_add_series(aapl, yAxis = 0, showInLegend = FALSE) %>%
highcharter::hc_add_yAxis(title = list(text = "Prices"),
plotLines = list(list(color = '
)
message("yAxis one: ", hc$x$hc_opts$yAxis)
return(hc)
}
with_create_yaxis <- function() {
hc <- highcharter::highchart(type = "stock") %>%
highcharter::hc_title(text = "yAxis test") %>%
highcharter::hc_add_series(aapl, yAxis = 0, showInLegend = FALSE) %>%
highcharter::hc_add_series(aapl[, "AAPL.Volume"], yAxis = 1, type = "column", showInLegend = FALSE) %>%
highcharter::hc_yAxis_multiples(create_yaxis(naxis = 2, lineWidth = 2, title = list(text = NULL), heights = c(2, 1)))
message("yAxis one: ", hc$x$hc_opts$yAxis)
return(hc)
}
with_vol_relative <- function() {
hc <- highcharter::highchart(type = "stock") %>%
highcharter::hc_title(text = "yAxis test") %>%
highcharter::hc_add_series(aapl, yAxis = 0, showInLegend = FALSE) %>%
highcharter::hc_add_series(aapl[, "AAPL.Volume"], yAxis = 1, type = "column", showInLegend = FALSE) %>%
highcharter::hc_add_yAxis(nid = 1L, title = list(text = "Prices"), relative = 2,
plotLines = list(list(color = '
) %>%
highcharter::hc_add_yAxis(nid = 2L, title = list(text = "Volume"), relative = 1)
message("yAxis one: ", hc$x$hc_opts$yAxis)
return(hc)
} |
print.frag.ma <- function(x, ...){
if(!inherits(x, "frag.ma")){
stop("The input must be an object of \"frag.ma\".")
}
cat(paste0("Original meta-analysis contains\n"))
cat(paste0(" ", dim(x$data)[1], " studies;\n"))
cat(paste0(" ", format(round(sum(x$data$e0)), scientific = FALSE, big.mark = ","), " total events and ",
format(round(sum(x$data$n0)), scientific = FALSE, big.mark = ","), " total sample sizes in group 0;\n"))
cat(paste0(" ", format(round(sum(x$data$e1)), scientific = FALSE, big.mark = ","), " total events and ",
format(round(sum(x$data$n1)), scientific = FALSE, big.mark = ","), " total sample sizes in group 1\n"))
cat(paste0("Significance level = ", x$alpha, "\n"))
cat(paste0("The effect size is ", x$measure, ifelse(is.element(x$measure, c("OR", "RR")), " (on a logarithmic scale)", ""), "\n"))
cat(paste0("The null value of is ", x$null, "\n"))
cat(paste0("The estimated overall effect size is\n"))
cat(paste0(" ", format(round(x$est.ori, 3), nsmall = 3), " with CI (",
format(round(x$ci.ori[1], 3), nsmall = 3), ", ", format(round(x$ci.ori[2], 3), nsmall = 3), ") and p-value ",
format(round(x$pval.ori, 3), nsmall = 3), "\n"))
if(!is.na(x$FI)){
cat(paste0("Fragility index (FI) = ", x$FI, " and fragility quotient (FQ) = ", format(round(100*x$FQ, 1), nsmall = 1), "%\n"))
cat(paste0(" for ", x$dir, "\n"))
}else{
cat(paste0("FI = FQ = NA, i.e.,\n ", x$dir, "\n"))
}
} |
is.DotProduct <- function(stat) {
"StatDotProduct" %in% class(stat)
}
is_dotProduct <- function(plot, any = TRUE) {
layers <- plot$layers
if(length(layers) == 0) return(FALSE)
dotProduct <- vapply(layers, function(layer) is.DotProduct(layer$stat), logical(1L))
if(any) any(dotProduct) else all(dotProduct)
} |
cronbach <- function(.data, ..., .ci = 0.95){
raw_alpha <- function(items) {
total <- psych::alpha(items)$total
z <- stats::qnorm(.ci + (1 - .ci)/2)
c(alpha = total$raw_alpha,
ci_lo = total$raw_alpha - z * total$ase,
ci_hi = total$raw_alpha + z * total$ase)
}
selection_sets <- rlang::enquos(...)
purrr::map_dfr(selection_sets,
function(selection_set){
raw_alpha(select(.data, !!selection_set))
},
.id = 'scale'
)
}
total_scores <- function(.data, ..., .method = 'mean', .append = FALSE){
totalling_function <- function(.data_selection, .method){
switch(.method,
mean = rowMeans(.data_selection, na.rm = T),
sum = rowSums(.data_selection, na.rm = T),
sum_like = rowMeans(.data_selection, na.rm = T) * ncol(.data_selection)
)
}
if (!(.method %in% c('mean', 'sum', 'sum_like'))) {
stop('The function that calculates the total must be either "mean", "sum" or "sum_like".')
}
selection_sets <- rlang::enquos(...)
results_df <- purrr::map_dfc(selection_sets,
function(selection_set){
totalling_function(select(.data, !!selection_set),
.method)
}
)
if (.append) {
bind_cols(.data, results_df)
} else {
results_df
}
}
re_code <- function(x, from, to){
plyr::mapvalues(x,
from = from,
to = to,
warn_missing = F)
} |
homogen_power <- function (effect_size, study_size, k, i2, es_type, p =.05, con_table = NULL){
if(missing(effect_size))
effect_size = NULL
homogen_power_integrity(effect_size, study_size, k, i2, es_type, p, con_table)
df <- k-1
c_alpha <- qchisq(1-p,df,0, lower.tail = TRUE)
range_factor <- 5
if(es_type == "d"){
variance <- compute_variance(study_size, effect_size, es_type, con_table)
homogen_power_range_df <- data.frame(k_v = rep(seq(2,range_factor*k),times = 7),
es_v = effect_size,
n_v = study_size,
i2 = i2,
c_alpha = c_alpha) %>%
mutate(variance = mapply(compute_variance, .data$n_v, .data$es_v, es_type))
}else if(es_type == "r"){
effect_size = .5*log((1 + effect_size)/(1 - effect_size))
variance <- compute_variance(study_size, effect_size, es_type, con_table)
homogen_power_range_df <- data.frame(sd_v = rep(seq(0,6), each = (k*range_factor-1)),
k_v = rep(seq(2,range_factor*k),times = 7),
es_v = effect_size,
n_v = study_size,
i2 = i2,
c_alpha = c_alpha) %>% mutate(variance = mapply(compute_variance, .data$n_v, .data$es_v, es_type))
}else if(es_type == "or") {
effect_size <- round((con_table[1]*con_table[4])/(con_table[2]*con_table[3]),3)
effect_size <- round(log(effect_size),3)
variance <- round((1/con_table[1]) + (1/con_table[2]) + (1/con_table[3]) + (1/con_table[4]),3)
homogen_power_range_df <- data.frame(sd_v = rep(seq(0,6), each = (k*range_factor-1)),
k_v = rep(seq(2,range_factor*k),times = 7),
es_v = effect_size,
n_v = study_size,
i2 = i2,
c_alpha = c_alpha,
variance = variance)
}
power_list <- list(variance = variance,
homogen_power_range_df = homogen_power_range_df,
homogen_power = compute_homogen_power(k, effect_size, variance, i2, c_alpha),
homogen_power_range = compute_homogen_range(homogen_power_range_df),
effect_size = effect_size,
study_size = study_size,
i2 = i2,
k = k,
es_type = es_type,
p = p)
attr(power_list, "class") <- "homogen_power"
return(power_list)
} |
preprocess.octopus <-
function( octopus.file, octopus.demogr=Octopus.demogr)
{
Mfile<- unlist(strsplit(octopus.file, split=';'))
m1<-match( substring(octopus.file,1,5), octopus.demogr[,1])
id<- as.character(octopus.demogr[m1,1])
eye.side<-substring(as.character(octopus.demogr[ m1 , 2]),1,1)
Mfile<- Mfile[-(1:32)]
Mfile<- as.numeric(Mfile)
pos.outliers<- (1:length(Mfile))[ abs(Mfile) > 100]
num.outliers<- length(pos.outliers)
outliers<-Mfile[pos.outliers]
if(length(pos.outliers)>0)
{
Mfile<- Mfile[-pos.outliers]
print(paste(num.outliers,' outliers removed', outliers, collapse='',
sep=' : '),quote=FALSE)
}
Mfile<- matrix( Mfile, ncol=11, byrow=TRUE)
Mfile<- as.data.frame(Mfile)
names(Mfile)<- c('start1','start2','direction1','direction2',
'X', 'Y', 'null1','null2',
'intensity','size','speed')
labels<- c('III4e', 'I4e', 'I2e', 'blind')
n.rows<- dim( Mfile)[1]
patterns.isopters<- apply(Mfile[,7:11],1, function( x){ paste(x, collapse='')})
num.isopters<- length( unique( patterns.isopters))
s1<- 2:n.rows
pos.changes<- (1:n.rows)[ patterns.isopters[s1-1] != patterns.isopters[s1]]
pos.changes<- c(0, pos.changes, n.rows)
labels.isopters<- ifelse(patterns.isopters=='00015', 'I4e',
ifelse(patterns.isopters=='00035', 'III4e',
ifelse(patterns.isopters=='001015', 'I2e', 'blind')))
Mfile$labels.isopters<- labels.isopters
list.output<- list()
list.output[[1]]<- Mfile[,c('X','Y', 'labels.isopters')]
names(list.output)[1]<- 'Subject'
for( i in 1:num.isopters)
{
obj.name<- paste(id, eye.side, 'O',Mfile$labels.isopters[pos.changes[i]+1],sep='')
s1<- (pos.changes[i]+1) : (pos.changes[i+1])
list.output[[i+1]]<- Mfile[s1, 5:6]
names(list.output)[i+1]<- obj.name
}
invisible( list.output)
} |
scale_x_seconds <- function(name = "Time",
breaks = waiver(),
minor_breaks = waiver(),
labels = waiver(),
limits = NULL,
expand = waiver(),
oob = scales::censor,
na.value = NA_real_,
position = "bottom",
time_wrap = NULL,
unit = "s",
log = FALSE) {
name <- sprintf("%s (%s)", name, unit)
scale_x_continuous(
name = name,
breaks = breaks,
labels = labels,
minor_breaks = minor_breaks,
limits = limits,
expand = expand,
oob = oob,
na.value = na.value,
position = position,
trans = seconds_trans(time_wrap, log_tr = log)
)
}
scale_y_seconds <- function(name = "Time",
breaks = waiver(),
minor_breaks = waiver(),
labels = waiver(),
limits = NULL,
expand = waiver(),
oob = scales::censor,
na.value = NA_real_,
position = "left",
time_wrap = NULL,
unit="s",
log = FALSE) {
name <- sprintf("%s (%s)", name, unit)
scale_y_continuous(
name = name,
breaks = breaks,
labels = labels,
minor_breaks = minor_breaks,
limits = limits,
expand = expand,
oob = oob,
na.value = na.value,
position = position,
trans = seconds_trans(time_wrap, log_tr = log)
)
}
seconds_trans <- function(time_wrap = NULL, log_tr = FALSE) {
if(is.null(time_wrap))
formater <- function(x)format(as.numeric(x))
else
formater <- function(x)format((as.numeric(x) %% time_wrap))
foo <- ifelse(log_tr,log10, identity)
foo_inv <- ifelse(log_tr,function(x){10^x}, identity)
scales::trans_new(
"seconds",
transform = function(x){structure(foo(as.numeric(x)), names = names(x))},
inverse = function(x){foo_inv(as.numeric(x)) },
format = formater
)
} |
api_user <- function(RH) {
url <- api_endpoints("user")
token <- paste("Bearer", RH$tokens.access_token)
dta <- GET(url, add_headers("Accept" = "application/json", "Authorization" = token))
dta <- mod_json(dta, "fromJSON")
dta <- as.list(dta)
return(dta)
} |
tess.likelihood.rateshift <- function( times,
lambda,
mu,
rateChangeTimesLambda = c(),
rateChangeTimesMu = c(),
massExtinctionTimes = c(),
massExtinctionSurvivalProbabilities = c(),
missingSpecies = c(),
timesMissingSpecies = c(),
samplingStrategy = "uniform",
samplingProbability = 1.0,
MRCA=TRUE,
CONDITION="survival",
log=TRUE) {
if ( length(lambda) != (length(rateChangeTimesLambda)+1) || length(mu) != (length(rateChangeTimesMu)+1) ) {
stop("Number of rate-change times needs to be one less than the number of rates!")
}
if ( length(massExtinctionTimes) != length(massExtinctionSurvivalProbabilities) ) {
stop("Number of mass-extinction times needs to equal the number of mass-extinction survival probabilities!")
}
if ( length(missingSpecies) != length(timesMissingSpecies) ) {
stop("Vector holding the missing species must be of the same size as the intervals when the missing speciation events happend!")
}
if ( CONDITION != "time" && CONDITION != "survival" && CONDITION != "taxa" ) {
stop("Wrong choice of argument for \"CONDITION\". Possible option are time|survival|taxa.")
}
if ( samplingStrategy != "uniform" && samplingStrategy != "diversified") {
stop("Wrong choice of argument for \"samplingStrategy\". Possible option are uniform|diversified.")
}
if ( length(rateChangeTimesLambda) > 0 ) {
sortedRateChangeTimesLambda <- sort( rateChangeTimesLambda )
lambda <- c(lambda[1], lambda[ match(sortedRateChangeTimesLambda,rateChangeTimesLambda)+1 ] )
rateChangeTimesLambda <- sortedRateChangeTimesLambda
}
if ( length(rateChangeTimesMu) > 0 ) {
sortedRateChangeTimesMu <- sort( rateChangeTimesMu )
mu <- c(mu[1], mu[ match(sortedRateChangeTimesMu,rateChangeTimesMu)+1 ] )
rateChangeTimesMu <- sortedRateChangeTimesMu
}
if ( length(massExtinctionTimes) > 0 ) {
sortedMassExtinctionTimes <- sort( massExtinctionTimes )
massExtinctionSurvivalProbabilities <- massExtinctionSurvivalProbabilities[ match(sortedMassExtinctionTimes,massExtinctionTimes) ]
massExtinctionTimes <- sortedMassExtinctionTimes
}
if ( length( rateChangeTimesLambda ) > 0 || length( rateChangeTimesMu ) > 0 || length( massExtinctionTimes ) > 0 ) {
changeTimes <- sort( unique( c( rateChangeTimesLambda, rateChangeTimesMu, massExtinctionTimes ) ) )
} else {
changeTimes <- c()
}
speciation <- rep(NaN,length(changeTimes)+1)
extinction <- rep(NaN,length(changeTimes)+1)
mep <- rep(NaN,length(changeTimes))
speciation[1] <- lambda[1]
if ( length(lambda) > 1 ) {
speciation[ match(rateChangeTimesLambda,changeTimes)+1 ] <- lambda[ 2:length(lambda) ]
}
extinction[1] <- mu[1]
if ( length(mu) > 1 ) {
extinction[ match(rateChangeTimesMu,changeTimes)+1 ] <- mu[ 2:length(mu) ]
}
if ( length( massExtinctionSurvivalProbabilities ) > 0 ) {
mep[ match(massExtinctionTimes,changeTimes) ] <- massExtinctionSurvivalProbabilities[ 1:length(massExtinctionSurvivalProbabilities) ]
}
for ( i in seq_len(length(changeTimes)) ) {
if ( is.null(speciation[i+1]) || !is.finite(speciation[i+1]) ) {
speciation[i+1] <- speciation[i]
}
if ( is.null(extinction[i+1]) || !is.finite(extinction[i+1]) ) {
extinction[i+1] <- extinction[i]
}
if ( is.null(mep[i]) || !is.finite(mep[i]) ) {
mep[i] <- 1.0
}
}
rateChangeTimes <- changeTimes
massExtinctionTimes <- changeTimes
lambda <- speciation
mu <- extinction
massExtinctionSurvivalProbabilities <- mep
PRESENT <- max(times)
nTaxa <- length(times) + 1
times <- PRESENT - sort(times,decreasing=TRUE)
if ( MRCA == TRUE ) {
times <- times[-1]
}
if (samplingStrategy == "uniform") {
rho <- samplingProbability
} else {
rho <- 1.0
}
lnl <- 0
if ( CONDITION == "survival" || CONDITION == "taxa" ) lnl <- - tess.equations.pSurvival.rateshift(lambda,mu,rateChangeTimes,massExtinctionSurvivalProbabilities,rho,0,PRESENT,PRESENT,log=TRUE)
lnl <- lnl + tess.equations.p1.rateshift(lambda,mu,rateChangeTimes,massExtinctionSurvivalProbabilities,rho,0,PRESENT,log=TRUE)
if ( MRCA == TRUE ) {
lnl <- 2*lnl
}
if ( CONDITION == "taxa" ) lnl <- lnl + tess.equations.pN.rateshift(lambda,mu,rateChangeTimes,massExtinctionSurvivalProbabilities,rho,nTaxa,0,PRESENT,SURVIVAL=TRUE,MRCA,log=TRUE)
if ( samplingStrategy == "diversified" ) {
lastEvent <- times[length(times)]
p_0_T <- 1.0 - tess.equations.pSurvival.rateshift(lambda,mu,rateChangeTimes,massExtinctionSurvivalProbabilities,1.0,0,PRESENT,PRESENT,log=FALSE) * exp((mu-lambda)*PRESENT)
p_0_t <- 1.0 - tess.equations.pSurvival.rateshift(lambda,mu,rateChangeTimes,massExtinctionSurvivalProbabilities,1.0,lastEvent,PRESENT,PRESENT,log=FALSE)*exp((mu-lambda)*(PRESENT-lastEvent))
F_t <- p_0_t / p_0_T
m <- round(nTaxa / samplingProbability)
k <- 1
if ( MRCA == TRUE ) k <- 2
lnl <- lnl + (m-nTaxa) * log(F_t) + lchoose(m-k,nTaxa-k)
}
if ( length(missingSpecies) > 0 ) {
prev_time <- 0
rate <- 0
for (j in seq_len(length(rateChangeTimes)) ) {
rate <- rate + ifelse( PRESENT >= rateChangeTimes[j], (mu[j] - lambda[j])*(rateChangeTimes[j]-prev_time) - log(massExtinctionSurvivalProbabilities[j]), 0 )
prev_time <- ifelse( PRESENT >= rateChangeTimes[j], rateChangeTimes[j], 0)
}
rate <- rate + ifelse( PRESENT > prev_time, (mu[length(mu)] - lambda[length(lambda)])*(PRESENT-prev_time), 0 )
rate <- rate - log(samplingProbability)
p_0_T <- 1.0 - exp( tess.equations.pSurvival.rateshift(lambda,mu,rateChangeTimes,massExtinctionSurvivalProbabilities,1.0,0,PRESENT,PRESENT,log=TRUE) + rate )
lastEvent <- timesMissingSpecies
prev_time <- lastEvent
rate <- 0
for (j in seq_len(length(rateChangeTimes)) ) {
rate <- rate + ifelse( lastEvent < rateChangeTimes[j] & PRESENT >= rateChangeTimes[j], (mu[j] - lambda[j])*(rateChangeTimes[j]-prev_time) - log(massExtinctionSurvivalProbabilities[j]), 0 )
prev_time <- ifelse( lastEvent < rateChangeTimes[j] & PRESENT >= rateChangeTimes[j], rateChangeTimes[j], lastEvent)
}
rate <- rate + ifelse( PRESENT > prev_time, (mu[length(mu)] - lambda[length(lambda)])*(PRESENT-prev_time), 0 )
rate <- rate - log(samplingProbability)
p_0_t <- 1.0 - exp( tess.equations.pSurvival.rateshift(lambda,mu,rateChangeTimes,massExtinctionSurvivalProbabilities,1.0,lastEvent,PRESENT,PRESENT,log=TRUE) + rate )
log_F_t <- log(p_0_t) - log(p_0_T)
m <- missingSpecies
lnl <- lnl + sum( m * log_F_t )
}
if ( length(rateChangeTimes) > 0 ) {
speciation <- function(times) {
idx <- findInterval(times,rateChangeTimes)+1
idx[ idx > length(lambda) ] <- length(lambda)
return ( lambda[idx] )
}
} else {
speciation <- function(times) rep(lambda[1],length(times))
}
lnl <- lnl + sum( log(speciation(times) ) ) + sum(tess.equations.p1.rateshift(lambda,mu,rateChangeTimes,massExtinctionSurvivalProbabilities,rho,times,PRESENT,log=TRUE))
if (is.nan(lnl)) lnl <- -Inf
if ( log == FALSE ) {
lnl <- exp(lnl)
}
return (lnl)
} |
readTextGridFast<-function(File,Encoding){
File=file(File,encoding=Encoding)
Data=readLines(File,-1)
close(File)
names=gsub("^[[:space:]]+name\\ =\\ |\"|[\\ ]+","",Data[grep("name\ =",Data)])
numberOfTiers=length(names)
TierBorder=c(grep("IntervalTier|TextTier",Data),length(Data))
TierType=gsub("[[:space:]]+|class|\\=|\"|-","",Data[grep("IntervalTier|TextTier",Data)])
for(i in 1:numberOfTiers){
if(TierType[i]=="IntervalTier"){
Part=Data[TierBorder[i]:TierBorder[i+1]]
Part=Part[-(1:5)]
Part=gsub("^[[:space:]]+((text)|(xmin)|(xmax))\\ =\\ |\"|[\\ ]+$","",Part)
Part=gsub("[\\ ]+$","",Part)
if(length(grep("class\ =\ (IntervalTier)|(TextTier)",Part))>0){
Part=Part[-grep("class\ =\ (IntervalTier)|(TextTier)",Part)]
}
if(length(grep("item\ \\[[0-9]+\\]",Part))>0){
Part=Part[-grep("item\ \\[[0-9]+\\]",Part)]
}
PartDataFrame=data.frame(Outcomes=Part[seq(4,length(Part),4)],
start=as.numeric(Part[seq(2,length(Part),4)]),
end=as.numeric(Part[seq(3,length(Part),4)]),
stringsAsFactors=F)
}
else{
Part=Data[TierBorder[i]:TierBorder[i+1]]
Part=Part[-(1:5)]
Part=gsub("^[[:space:]]+((mark)|(number))\\ =\\ |\"|[\\ ]+$","",Part)
Part=gsub("[\\ ]+$","",Part)
if(length(grep("class\ =\ (IntervalTier)|(TextTier)",Part))>0){
Part=Part[-grep("class\ =\ (IntervalTier)|(TextTier)",Part)]
}
if(length(grep("item\ \\[[0-9]+\\]",Part))>0){
Part=Part[-grep("item\ \\[[0-9]+\\]",Part)]
}
PartDataFrame=data.frame( Outcomes=Part[seq(3,length(Part),3)],
point=as.numeric(Part[seq(2,length(Part),3)]),
stringsAsFactors=F)
}
assign(names[i],PartDataFrame)
}
NewData=vector("list",length(names)+1)
NewData[[1]]=names
for(i in 2:length(NewData)){
NewData[[i]]=get(names[i-1])
}
return(NewData)
}
readTextGridRobust<-function(File,Encoding){
Data=read.csv(file(File,encoding=Encoding),stringsAsFactors=F,header=F)$V1
names=gsub("^[[:space:]]+name\\ =\\ |\"|[\\ ]+","",Data[grep("name\ =",Data)])
numberOfTiers=length(names)
TierBorder=c(grep("IntervalTier|TextTier",Data),length(Data)+1)
TierType=gsub("[[:space:]]+|class|\\=|\"|-","",Data[grep("IntervalTier|TextTier",Data)])
for(i in 1:numberOfTiers){
if(TierType[i]=="IntervalTier"){
Part=Data[TierBorder[i]:(TierBorder[i+1]-1)]
Part=Part[-(1:5)]
Part=gsub("^[[:space:]]+((text)|(xmin)|(xmax))\\ =\\ |\"|[\\ ]+$","",Part)
Part=gsub("[\\ ]+$","",Part)
PartDataFrame=data.frame(Outcomes=character(),start=numeric(),end=numeric(),stringsAsFactors=F)
for(j in 1:(length(Part)/4)){
PartDataFrame=rbind(PartDataFrame,
data.frame(Outcomes=Part[(j*4)],
start=as.numeric(Part[(j*4)-2]),
end=as.numeric(Part[(j*4)-1]),
stringsAsFactors=F),
stringsAsFactors=F)
}
assign(names[i],PartDataFrame)
}
else{
Part=Data[TierBorder[i]:(TierBorder[i+1]-1)]
Part=Part[-(1:5)]
Part=gsub("^[[:space:]]+((mark)|(number))\\ =\\ |\"|[\\ ]+$","",Part)
Part=gsub("[\\ ]+$","",Part)
PartDataFrame=data.frame(Outcomes="",point=0,stringsAsFactors=F)
for(j in 1:(length(Part)/3)){
PartDataFrame=rbind(PartDataFrame,
data.frame(Outcomes=Part[(j*3)],
point=as.numeric(Part[(j*3)-1]),stringsAsFactors=F),
stringsAsFactors=F)
}
assign(names[i],PartDataFrame)
}
}
NewData=vector("list",length(names)+1)
NewData[[1]]=names
for(i in 2:length(NewData)){
NewData[[i]]=get(names[i-1])
}
return(NewData)
}
readESPSAnnotation<-function(File,Encoding){
File=file(File,encoding=Encoding)
Data=readLines(File,-1)
close(File)
r=grep("^
if(r>0){
Data=Data[-(1:r)]
}
Data=unlist(strsplit(Data,"\ [0-9]+\ "))
End=as.numeric(Data[seq(1,length(Data),2)])
DataFrame=data.frame( Outcomes=Data[seq(2,length(Data),2)],
start=as.numeric(c(0,End[-length(End)])),
end=as.numeric(End),
stringsAsFactors=F)
return(DataFrame)
}
readWavesurfer<-function(File,Encoding){
File=file(File,encoding=Encoding)
Data=readLines(File,-1)
close(File)
Data=gsub("^[\ ]+","",Data)
Data=unlist(strsplit(Data,"\ "))
End=as.numeric(Data[seq(1,length(Data),3)])
DataFrame=data.frame( Outcomes=Data[seq(3,length(Data),3)],
start=as.numeric(c(0,End[-length(End)])),
end=as.numeric(End),
stringsAsFactors=F)
return(DataFrame)
} |
orcid_invited_positions <- function(orcid, put_code = NULL,
format = "application/json", summary = FALSE, ...) {
pth <- path_picker(put_code, summary, "invited-position")
orcid_putcode_helper(pth, orcid, put_code, format, ...)
} |
animateCA = function(filename, out_type = c("html", "gif"), out_name = "aniCA"){
if (!requireNamespace("animation", quietly = TRUE)) {
stop("You need to install the aniimation package.")
}
if (filename$expt != "CA" & filename$file_type != "full") {
stop("This file is not from a chronoamperometry
simulation created using caSim.")
}
out_type = match.arg(out_type)
if (out_type == "html"){
old.ani = animation::ani.options(interval = 0.2, verbose = FALSE)
} else {
old.ani = animation::ani.options(interval = 0.2, loop = 1)
}
time_increment = round(length(filename$time)/40, digits = 0)
if (out_type == "html"){
animation::saveHTML({
old.par = par(mfrow = c(2, 1))
for (i in seq(1, length(filename$time), time_increment)) {
plot(x = filename$distance, y = filename$oxdata[i, ],
type = "l", lwd = 3, col = "blue",
ylim = c(0, 1050 * filename$conc.bulk),
xlab = "distance from electrode (cm)",
ylab = "concentration (mM)")
grid()
lines(x = filename$distance, y = filename$reddata[i, ],
lwd = 3, col = "red")
if (filename$mechanism != "E") {
lines(x = filename$distance,
y = filename$chemdata[i, ],
lwd = 3, col = "green")
legend(x = "right", legend = c("Ox", "Red", "Chem"),
fill = c("blue", "red", "green"),
bty = "n", inset = 0.05)
} else {
legend(x = "right", legend = c("Ox", "Red"),
fill = c("blue", "red"),
bty = "n", inset = 0.05)
}
plot(x = filename$time[1:i], y = filename$current[1:i],
col = "blue", type = "l", lwd = 3,
xlim = c(min(filename$time), max(filename$time)),
ylim = c(min(filename$current), max(filename$current)),
xlab = "time (s)",ylab = expression(paste("current (", mu, "A)")))
grid()
}
par(old.par)
},
img.name = paste0(out_name,"_plot"),
imgdir = paste0(out_name,"_dir"),
htmlfile = paste0(out_name,".html"),
navigator = FALSE
)
} else {
animation::saveGIF({
old.par = par(mfrow = c(2, 1))
for (i in seq(1, length(filename$time), time_increment)) {
plot(x = filename$distance, y = filename$oxdata[i, ],
type = "l", lwd = 3, col = "blue",
ylim = c(0, 1050 * filename$conc.bulk),
xlab = "distance from electrode (cm)",
ylab = "concentration (mM)")
grid()
lines(x = filename$distance, y = filename$reddata[i, ],
lwd = 3, col = "red")
if (filename$mechanism != "E") {
lines(x = filename$distance,
y = filename$chemdata[i, ],
lwd = 3, col = "green")
legend(x = "right", legend = c("Ox", "Red", "Chem"),
fill = c("blue", "red", "green"),
bty = "n", inset = 0.05)
} else {
legend(x = "right", legend = c("Ox", "Red"), fill = c("blue", "red"),
bty = "n", inset = 0.05)
}
plot(x = filename$time[1:i], y = filename$current[1:i],
col = "blue", type = "l", lwd = 3,
xlim = c(min(filename$time), max(filename$time)),
ylim = c(min(filename$current), max(filename$current)),
xlab = "time (s)", ylab = expression(paste("current (", mu, "A)")))
grid()
}
par(old.par)}, movie.name = paste0(out_name,".gif")
)
}
animation::ani.options(old.ani)
} |
print.dbmssEnvelope <-
function(x, ...) {
einfo <- attr(x, "einfo")
type <- ifelse(einfo$global, "Global", "Local")
cat(paste(type, "critical envelopes obtained from", einfo$nsim, "simulations of", deparse(attr(x, "ylab"))))
cat(paste(" under the null hypothesis:", einfo$H0, "\n"))
if (!is.null(attr(x, "simfuns")))
cat(paste("(All", einfo$nsim, "simulated function values are stored in attr(,", dQuote("simfuns"), ") )\n"))
cat(paste("Significance level of Monte Carlo test:", einfo$Alpha, "\n"))
cat(paste("Data:", einfo$Yname, "\n"))
print.fv(x, ...)
} |
if (Sys.getenv("RunAllRcppTests") != "yes") exit_file("Set 'RunAllRcppTests' to 'yes' to run.")
Rcpp::sourceCpp("cpp/String.cpp")
expect_equal( String_replace_all("abcdbacdab", "ab", "AB"), "ABcdbacdAB")
expect_equal( String_replace_first("abcdbacdab", "ab", "AB"), "ABcdbacdab")
expect_equal( String_replace_last("abcdbacdab", "ab", "AB"), "abcdbacdAB")
res <- test_sapply_string( "foobar", c("o", "a" ), c("*", "!" ) )
expect_equal( res, "f**b!r" )
res <- test_compare_Strings( "aaa", "aab" )
target <- list("a < b" = TRUE,
"a > b" = FALSE,
"a == b" = FALSE,
"a == a" = TRUE)
expect_equal( res, target )
v <- c("aab")
res <- test_compare_String_string_proxy( "aaa", v )
target <- list("a == b" = FALSE,
"a != b" = TRUE,
"b == a" = FALSE,
"b != a" = TRUE)
expect_equal( res, target )
v <- c("aab")
res <- test_compare_String_const_string_proxy( "aaa", v )
target <- list("a == b" = FALSE,
"a != b" = TRUE,
"b == a" = FALSE,
"b != a" = TRUE)
expect_equal( res, target )
res <- test_ctor("abc")
expect_identical(res, "abc")
res <- test_push_front("def")
expect_identical(res, "abcdef")
a <- b <- "å"
Encoding(a) <- "unknown"
Encoding(b) <- "UTF-8"
expect_equal(test_String_encoding(a), 0)
expect_equal(test_String_encoding(b), 1)
expect_equal(Encoding(test_String_set_encoding(a)), "UTF-8")
expect_equal(Encoding(test_String_ctor_encoding(a)), "UTF-8")
expect_equal(Encoding(test_String_ctor_encoding2()), "UTF-8")
expect_error(test_String_embeddedNul()) |
Mussel_pop_post<-function(userpath,output,times,Dates,N,CS) {
cat('Data post-processing\n')
cat('\n')
ti=times[1]
tf=times[2]
Wb_stat=output[[1]]
R_stat=output[[2]]
Wd_stat=output[[3]]
W_stat=output[[4]]
L_stat=output[[5]]
fecC_stat=output[[6]]
fecN_stat=output[[7]]
fecP_stat=output[[8]]
psC_stat=output[[9]]
psN_stat=output[[10]]
psP_stat=output[[11]]
Cmyt_stat=output[[12]]
Nmyt_stat=output[[13]]
Pmyt_stat=output[[14]]
A_stat=output[[15]]
C_stat=output[[16]]
O2_stat=output[[17]]
NH4_stat=output[[18]]
fgT=output[[19]]
frT=output[[20]]
WbSave=Wb_stat[,ti:tf]
RSave=R_stat[,ti:tf]
WdSave=Wd_stat[,ti:tf]
WSave=W_stat[,ti:tf]
LSave=L_stat[,ti:tf]
fecCSave=fecC_stat[,ti:tf]
fecNSave=fecN_stat[,ti:tf]
fecPSave=fecP_stat[,ti:tf]
psCSave=psC_stat[,ti:tf]
psNSave=psN_stat[,ti:tf]
psPSave=psP_stat[,ti:tf]
CmytSave=Cmyt_stat[,ti:tf]
NmytSave=Nmyt_stat[,ti:tf]
PmytSave=Pmyt_stat[,ti:tf]
ASave=A_stat[,ti:tf]
CSave=C_stat[,ti:tf]
O2Save=O2_stat[,ti:tf]
NH4Save=NH4_stat[,ti:tf]
fgT=fgT[(ti+1):tf]
frT=frT[(ti+1):tf]
tfunSave=cbind(fgT,frT)
N=N[ti:tf]
foo <- function(w,S){which(w>S)[1]}
arg=as.data.frame(LSave[1,]-LSave[2,])
days <- apply(arg,1,foo,S=CS)
days_L <- as.data.frame(days)
NonNAindex <- which(!is.na(days_L))
if (length(NonNAindex)==0) {
Lb_daysToSize="Not reaching the commercial size"
}else{ Lb_daysToSize <- min(NonNAindex)
}
foo <- function(w,S){which(w>S)[1]}
arg=as.data.frame(LSave[1,])
days <- apply(arg,1,foo,S=CS)
days_L <- as.data.frame(days)
NonNAindex <- which(!is.na(days_L))
if (length(NonNAindex)==0) {
Mean_daysToSize="Not reaching the commercial size"
}else{ Mean_daysToSize <- min(NonNAindex)
}
foo <- function(w,S){which(w>S)[1]}
arg=as.data.frame(LSave[1,]+LSave[2,])
days <- apply(arg,1,foo,S=CS)
days_L <- as.data.frame(days)
NonNAindex <- which(!is.na(days_L))
if (length(NonNAindex)==0) {
Ub_daysToSize="Not reaching the commercial size"
}else{ Ub_daysToSize <- min(NonNAindex)
}
daysToSize<-as.list(cbind(Ub_daysToSize,Mean_daysToSize,Lb_daysToSize))
output=list(WbSave,RSave,WdSave,WSave,LSave,fecCSave,fecNSave,fecPSave,psCSave,psNSave,psPSave,CmytSave,NmytSave,PmytSave,ASave,CSave,fgT,frT,N,daysToSize)
days <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), by = "days", length = tf-ti+1)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//Dry_weight.jpeg")
jpeg(filepath,800,600)
plot(days,WdSave[1,],ylab="Mean dry weight (g)", xlab=" ",xaxt = "n",type="l",lwd=2,cex.lab=1.4,col="red")
lines(days,WbSave[1,],lwd=2,col="green")
lines(days,RSave[1,],lwd=2,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
legend("topleft",c("Total","Somatic tissue","Gonadic tissue"),fill=c("red","green","blue"))
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//Length.jpeg")
jpeg(filepath,800,600)
ub=LSave[1,]+LSave[2,]
lb=as.matrix(matrix(0,nrow=length(ub),ncol=1))
for (i in 1:length(LSave[1,]-LSave[2,])){
lb[i]=max(LSave[1,i]-LSave[2,i],0)
}
maxub=max(LSave[1,]+LSave[2,])
plot(days,LSave[1,],ylab="Length (cm)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(lb,rev(ub)),col="grey90",border=FALSE)
lines(days,LSave[1,],lwd=2,col="red")
lines(days,lb,col="blue")
lines(days,ub,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//Total_weight.jpeg")
jpeg(filepath,800,600)
ub=WSave[1,]+WSave[2,]
lb=as.matrix(matrix(0,nrow=length(ub),ncol=1))
for (i in 1:length(WSave[1,]-WSave[2,])){
lb[i]=max(WSave[1,i]-WSave[2,i],0)
}
maxub=max(WSave[1,]+WSave[2,])
plot(days,WSave[1,],ylab="Total weight - with shell (g)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(lb,rev(ub)),col="grey90",border=FALSE)
lines(days,WSave[1,],lwd=2,col="red")
lines(days,lb,col="blue")
lines(days,ub,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//pseudofaeces_C.jpeg")
jpeg(filepath,800,600)
ub=psCSave[1,]+psCSave[2,]
lb=as.matrix(matrix(0,nrow=length(ub),ncol=1))
for (i in 1:length(psCSave[1,]-psCSave[2,])){
lb[i]=max(psCSave[1,i]-psCSave[2,i],0)
}
maxub=max(psCSave[1,]+psCSave[2,])
plot(days,psCSave[1,],ylab="C in pseudofaeces (kg/d)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(lb,rev(ub)),col="grey90",border=FALSE)
lines(days,psCSave[1,],lwd=2,col="red")
lines(days,lb,col="blue")
lines(days,ub,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//pseudofaeces_N.jpeg")
jpeg(filepath,800,600)
ub=psNSave[1,]+psNSave[2,]
lb=as.matrix(matrix(0,nrow=length(ub),ncol=1))
for (i in 1:length(psNSave[1,]-psNSave[2,])){
lb[i]=max(psNSave[1,i]-psNSave[2,i],0)
}
maxub=max(psNSave[1,]+psNSave[2,])
plot(days,psNSave[1,],ylab="N in pseudofaeces (kg/d)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(lb,rev(ub)),col="grey90",border=FALSE)
lines(days,psNSave[1,],lwd=2,col="red")
lines(days,lb,col="blue")
lines(days,ub,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//pseudofaeces_P.jpeg")
jpeg(filepath,800,600)
ub=psPSave[1,]+psPSave[2,]
lb=as.matrix(matrix(0,nrow=length(ub),ncol=1))
for (i in 1:length(psPSave[1,]-psPSave[2,])){
lb[i]=max(psPSave[1,i]-psPSave[2,i],0)
}
maxub=max(psPSave[1,]+psPSave[2,])
plot(days,psPSave[1,],ylab="P in pseudofaeces (kg/d)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(lb,rev(ub)),col="grey90",border=FALSE)
lines(days,psPSave[1,],lwd=2,col="red")
lines(days,lb,col="blue")
lines(days,ub,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//faeces_C.jpeg")
jpeg(filepath,800,600)
ub=fecCSave[1,]+fecCSave[2,]
lb=as.matrix(matrix(0,nrow=length(ub),ncol=1))
for (i in 1:length(fecCSave[1,]-fecCSave[2,])){
lb[i]=max(fecCSave[1,i]-fecCSave[2,i],0)
}
maxub=max(fecCSave[1,]+fecCSave[2,])
plot(days,fecCSave[1,],ylab="C in faeces (kg/d)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(lb,rev(ub)),col="grey90",border=FALSE)
lines(days,fecCSave[1,],lwd=2,col="red")
lines(days,lb,col="blue")
lines(days,ub,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//faeces_N.jpeg")
jpeg(filepath,800,600)
ub=fecNSave[1,]+fecNSave[2,]
lb=as.matrix(matrix(0,nrow=length(ub),ncol=1))
for (i in 1:length(fecNSave[1,]-fecNSave[2,])){
lb[i]=max(fecNSave[1,i]-fecNSave[2,i],0)
}
maxub=max(fecNSave[1,]+fecNSave[2,])
plot(days,fecNSave[1,],ylab="N in faeces (kg/d)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(lb,rev(ub)),col="grey90",border=FALSE)
lines(days,fecNSave[1,],lwd=2,col="red")
lines(days,lb,col="blue")
lines(days,ub,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//faeces_P.jpeg")
jpeg(filepath,800,600)
ub=fecPSave[1,]+fecPSave[2,]
lb=as.matrix(matrix(0,nrow=length(ub),ncol=1))
for (i in 1:length(fecPSave[1,]-fecPSave[2,])){
lb[i]=max(fecPSave[1,i]-fecPSave[2,i],0)
}
maxub=max(fecPSave[1,]+fecPSave[2,])
plot(days,fecPSave[1,],ylab="P in faeces (kg/d)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(lb,rev(ub)),col="grey90",border=FALSE)
lines(days,fecPSave[1,],lwd=2,col="red")
lines(days,lb,col="blue")
lines(days,ub,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//C_content.jpeg")
jpeg(filepath,800,600)
ub=CmytSave[1,]+CmytSave[2,]
lb=as.matrix(matrix(0,nrow=length(ub),ncol=1))
for (i in 1:length(CmytSave[1,]-CmytSave[2,])){
lb[i]=max(CmytSave[1,i]-CmytSave[2,i],0)
}
maxub=max(CmytSave[1,]+CmytSave[2,])
plot(days,CmytSave[1,],ylab="Mussel C content (g)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(lb,rev(ub)),col="grey90",border=FALSE)
lines(days,CmytSave[1,],lwd=2,col="red")
lines(days,lb,col="blue")
lines(days,ub,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//N_content.jpeg")
jpeg(filepath,800,600)
ub=NmytSave[1,]+NmytSave[2,]
lb=as.matrix(matrix(0,nrow=length(ub),ncol=1))
for (i in 1:length(NmytSave[1,]-NmytSave[2,])){
lb[i]=max(NmytSave[1,i]-NmytSave[2,i],0)
}
maxub=max(NmytSave[1,]+NmytSave[2,])
plot(days,NmytSave[1,],ylab="Mussel N content (g)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(lb,rev(ub)),col="grey90",border=FALSE)
lines(days,NmytSave[1,],lwd=2,col="red")
lines(days,lb,col="blue")
lines(days,ub,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//P_content.jpeg")
jpeg(filepath,800,600)
ub=PmytSave[1,]+PmytSave[2,]
lb=as.matrix(matrix(0,nrow=length(ub),ncol=1))
for (i in 1:length(PmytSave[1,]-PmytSave[2,])){
lb[i]=max(PmytSave[1,i]-PmytSave[2,i],0)
}
maxub=max(PmytSave[1,]+PmytSave[2,])
plot(days,PmytSave[1,],ylab="Mussel P content (g)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(lb,rev(ub)),col="grey90",border=FALSE)
lines(days,PmytSave[1,],lwd=2,col="red")
lines(days,lb,col="blue")
lines(days,ub,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//O2_consumption.jpeg")
jpeg(filepath,800,600)
ub=O2Save[1,]+O2Save[2,]
lb=as.matrix(matrix(0,nrow=length(ub),ncol=1))
for (i in 1:length(O2Save[1,]-O2Save[2,])){
lb[i]=max(O2Save[1,i]-O2Save[2,i],0)
}
maxub=max(O2Save[1,]+O2Save[2,])
plot(days,O2Save[1,],ylab="Oxygen consumption (kg/d)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(lb,rev(ub)),col="grey90",border=FALSE)
lines(days,O2Save[1,],lwd=2,col="red")
lines(days,lb,col="blue")
lines(days,ub,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//NH4_release.jpeg")
jpeg(filepath,800,600)
ub=NH4Save[1,]+NH4Save[2,]
lb=as.matrix(matrix(0,nrow=length(ub),ncol=1))
for (i in 1:length(NH4Save[1,]-NH4Save[2,])){
lb[i]=max(NH4Save[1,i]-NH4Save[2,i],0)
}
maxub=max(NH4Save[1,]+NH4Save[2,])
plot(days,NH4Save[1,],ylab="NH4 release (kg/d)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(lb,rev(ub)),col="grey90",border=FALSE)
lines(days,NH4Save[1,],lwd=2,col="red")
lines(days,lb,col="blue")
lines(days,ub,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
days2 <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), by = "days", length = tf-ti)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//temperature_response.jpeg")
jpeg(filepath,800,600)
ub=max(max(fgT),max(frT))
plot(days2,fgT,ylab="Temperature response function",xlab=" ",xaxt = "n",cex.lab=1.4,col="red",type="l",ylim=c(0,ub+0.05*ub))
lines(days2,frT,col="blue")
legend("topright",c("Anabolism limitation","Catabolism limitation"),fill=c("red","blue"))
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots//metabolism.jpeg")
jpeg(filepath,800,600)
Aub=ASave[1,]+ASave[2,]
Cub=CSave[1,]+CSave[2,]
Alb=as.matrix(matrix(0,nrow=length(Aub),ncol=1))
Clb=as.matrix(matrix(0,nrow=length(Cub),ncol=1))
for (i in 1:length(ASave[1,]-ASave[2,])){
Alb[i]=max(ASave[1,i]-ASave[2,i],0)
Clb[i]=max(CSave[1,i]-CSave[2,i],0)
}
maxub=max(Aub,Cub)
plot(days,ASave[1,],ylab="Metabolic rates (J/d)", xlab=" ",xaxt = "n",type="l",cex.lab=1.4,col="red",ylim=c(0,maxub+0.05*maxub))
polygon(c(days,rev(days)),c(Alb,rev(Aub)),col="grey75",border=FALSE)
lines(days,ASave[1,],lwd=2,col="red")
polygon(c(days,rev(days)),c(Clb,rev(Cub)),col="grey75",border=FALSE)
lines(days,CSave[1,],lwd=2,col="blue")
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
legend("topleft",c("Anabolic rate","Catabolic rate"),fill=c("red","blue"))
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_plots/Population.jpeg")
jpeg(filepath,800,600)
plot(days, N, ylab="Number of individuals", xlab="", xaxt = "n",type="l",cex.lab=1.4)
labDates <- seq(as.Date(Dates[1], format = "%d/%m/%Y"), tail(days, 1), by = "months")
axis.Date(side = 1, days, at = labDates, format = "%d %b %y", las = 2)
dev.off()
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//Dry_weight.csv")
write.csv(t(WdSave),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//Total_weight.csv")
write.csv(t(WSave),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//Length.csv")
write.csv(t(LSave),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//faeces_C.csv")
write.csv(t(fecCSave),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//faeces_N.csv")
write.csv(t(fecNSave),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//faeces_P.csv")
write.csv(t(fecPSave),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//pseudofaeces_C.csv")
write.csv(t(psCSave),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//pseudofaeces_N.csv")
write.csv(t(psNSave),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//pseudofaeces_P.csv")
write.csv(t(psPSave),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//C_content.csv")
write.csv(t(CmytSave),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//N_content.csv")
write.csv(t(NmytSave),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//P_content.csv")
write.csv(t(PmytSave),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//O2_consumption.csv")
write.csv(t(O2Save),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//NH4_release.csv")
write.csv(t(NH4Save),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//temperature_response.csv")
write.csv(t(tfunSave),filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//anabolic_rate.csv")
write.csv(ASave,filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//catabolic_rate.csv")
write.csv(CSave,filepath)
filepath=paste0(userpath,"/Mussel_population/Outputs/Out_csv//Days_to_commercial_size.csv")
write.csv(daysToSize,filepath)
return(output)
} |
dseries <- function(num.series, tag.group = FALSE, group = 0, ...) {
my.list <- vector('list', num.series)
for (i in 1:num.series) {
my.list[[i]] <- dtrials(data.structure = "data.table", ...)
}
results <- do.call("rbind", my.list)
if (tag.group == TRUE) {
results$GROUP <- group
}
return(results)
} |
run_spm12_script <- function(
script_name,
jobvec = NULL,
mvec = NULL,
add_spm_dir = TRUE,
spmdir = spm_dir(verbose = verbose),
clean = TRUE,
verbose = TRUE,
single_thread = FALSE,
...
){
if (on_cran()) {
single_thread = TRUE
}
scripts = build_spm12_script(
script_name = script_name,
jobvec = jobvec,
mvec = mvec,
add_spm_dir = add_spm_dir,
spmdir = spmdir,
verbose = verbose,
...)
if (verbose) {
message(paste0(
"
scripts["job"], "\n"))
}
res = run_matlab_script(
scripts["script"],
verbose = verbose,
single_thread = single_thread)
if (verbose) {
message(paste0("
}
if (clean) {
file.remove(scripts)
if (verbose) {
message(paste0("
}
}
return(res)
}
build_spm12_script <- function(
script_name,
jobvec = NULL,
mvec = NULL,
add_spm_dir = TRUE,
spmdir = spm_dir(verbose = verbose),
verbose = TRUE,
install_dir = NULL,
...
){
install_spm12(verbose = verbose,
install_dir = install_dir)
scripts = spm12_script(script_name, ...)
job = readLines(scripts["job"])
njvec = names(jobvec)
if (any(is.na(jobvec))) {
print(jobvec)
stop("There is an NA in jobvec")
}
for (ijob in seq_along(jobvec)) {
job = gsub(njvec[ijob], jobvec[ijob], job)
}
m = readLines(scripts["script"])
nmvec = names(mvec)
for (ijob in seq_along(mvec)) {
m = gsub(nmvec[ijob], mvec[ijob], job)
}
m = gsub("%jobfile%", scripts['job'], m)
if (add_spm_dir) {
if (verbose) {
message(paste0("
}
m = c(paste0("addpath(genpath('", spmdir, "'));"),
m)
}
writeLines(m, con = scripts['script'])
writeLines(job, con = scripts['job'])
return(scripts)
} |
with_debug <- function(code, CFLAGS = NULL, CXXFLAGS = NULL,
FFLAGS = NULL, FCFLAGS = NULL, debug = TRUE) {
defaults <- compiler_flags(debug = debug)
flags <- c(
CFLAGS = CFLAGS, CXXFLAGS = CXXFLAGS,
FFLAGS = FFLAGS, FCFLAGS = FCFLAGS
)
flags <- unlist(utils::modifyList(as.list(defaults), as.list(flags)))
withr::with_makevars(flags, code)
}
without_compiler <- function(code) {
flags <- c(
CC = "test",
CXX = "test",
CXX11 = "test",
FC = "test"
)
if (is_windows()) {
without_cache({
cache_set("rtools_path", "")
withr::with_makevars(flags, code)
})
} else {
without_cache({
withr::with_makevars(flags, code)
})
}
}
without_cache <- function(code) {
cache_reset()
on.exit(cache_reset())
code
}
without_latex <- function(code) {
withr::with_options(list(PKGBUILD_TEST_FIXTURE_HAS_LATEX = FALSE), code)
}
with_latex <- function(code) {
withr::with_options(list(PKGBUILD_TEST_FIXTURE_HAS_LATEX = TRUE), code)
} |
today.prizelist <- function(up_or_down) {
if (up_or_down == "up") {
link <- "https://www.bmcecapitalbourse.com/bkbbourse/lists/TK?q=AE31180F8E3BE20E762758E81EDC1204&t=list&f=1W_PERF_PR&s=false
page <- rvest::read_html(link)
page <- rvest::html_nodes(page, "table")
page <- rvest::html_table(page)
page[[7]]
} else if (up_or_down == "down") {
link <- "https://www.bmcecapitalbourse.com/bkbbourse/lists/TK?q=AE31180F8E3BE20E762758E81EDC1204&t=list&f=1W_PERF_PR&s=true
page <- rvest::read_html(link)
page <- rvest::html_nodes(page, "table")
page <- rvest::html_table(page)
page[[7]]
} else {
print("today.prizelist('up') or today.prizelist('down')")
}
} |
.stackMatList <- function( matList, way, useMatrix = FALSE ){
if( way == "diag" ){
result <- matrix( 0, 0, 0 )
for( i in 1:length( matList ) ){
result <- rbind(
cbind( result,
matrix( 0, nrow( result ), ncol( matList[[ i ]] ) ) ),
cbind( matrix( 0, nrow( matList[[ i ]] ), ncol( result ) ),
as.matrix( matList[[ i ]] ) ) )
}
} else if( way == "below" ) {
result <- NULL
for( i in 1:length( matList ) ){
result <- rbind( result, as.matrix( matList[[ i ]] ) )
}
}
if( useMatrix ){
result <- as( result, "dgCMatrix" )
}
return( result )
}
.prepareWmatrix <- function( upperleft, R.restr, useMatrix = FALSE ){
if( nrow( R.restr ) == 1 ){
lowerRows <- c( R.restr, 0 )
} else {
lowerRows <- cbind2( R.restr,
matrix( 0, nrow( R.restr ), nrow( R.restr ) ) )
}
result <- rbind2( cbind2( as.matrix( upperleft ), t(R.restr) ), lowerRows )
if( useMatrix ){
result <- as( result, "dgeMatrix" )
}
return( result )
} |
racscovariance <- function(xi, obswin = NULL,
setcov_boundarythresh = NULL,
estimators = "all",
drop = FALSE){
cvchat <- plugincvc(xi, obswin, setcov_boundarythresh = setcov_boundarythresh)
cpp1 <- cppicka(xi, obswin, setcov_boundarythresh = setcov_boundarythresh)
phat <- coverageprob(xi, obswin)
cvchats <- racscovariance.cvchat(cvchat, cpp1, phat, estimators = estimators, drop = drop)
return(cvchats)
}
racscovariance.cvchat <- function(cvchat, cpp1 = NULL, phat = NULL, estimators = "all", drop = FALSE){
harmonised <- harmonise.im(cvchat = cvchat, cpp1 = cpp1)
cvchat <- harmonised$cvchat
cpp1 <- harmonised$cpp1
fcns <- list(
plugin = function(cvchat, cpp1 = NULL, phat = NULL) cvchat,
mattfeldt = balancedracscovariance_mattfeldt_add,
pickaint = balancedracscovariance_picka_int,
pickaH = balancedracscovariance_picka_H
)
if ((estimators == "all")[[1]]) {estimators <- names(fcns)}
fcnstouse <- fcns[names(fcns) %in% estimators]
isfunction <- unlist(lapply(estimators, function(x) "function" %in% class(x)))
estimatorsnotused <- estimators[!( (estimators %in% names(fcns)) | isfunction)]
fcnstouse <- c(fcnstouse, estimators[isfunction])
if(length(estimatorsnotused) > 0){stop(
paste("The following estimators are not recognised as existing function names or as a function:", estimatorsnotused))}
balancedcvchats <- lapply(fcnstouse, function(x) do.call(x, args = list(cvchat = cvchat, cpp1 = cpp1, phat = phat)))
if (drop && (length(balancedcvchats) == 1)){ return(balancedcvchats[[1]])
} else {return(as.imlist(balancedcvchats)) }
}
balancedracscovariance_mattfeldt_add <- function(cvchat, cpp1, phat){
return(cvchat - ( (cpp1 + reflect.im(cpp1))/2 )^2 + phat^2)
}
balancedracscovariance_picka_int <- function(cvchat, cpp1, phat){
return(cvchat - cpp1*reflect.im(cpp1) + phat^2)
}
balancedracscovariance_picka_H <- function(cvchat, cpp1, phat){
return(cvchat - phat*(cpp1 + reflect.im(cpp1) - 2*phat))
} |
mcdina_est_reduced_skillspace <- function(pi.k, Z)
{
G <- ncol(pi.k)
for (gg in 1:G){
ntheta <- pi.k[,gg]
res <- gdina_reduced_skillspace( ntheta=ntheta, Z=Z,
reduced.skillspace.method=2 )
pi.k[,gg] <- res$attr.prob
}
return(pi.k)
} |
.Random.seed <-
c(403L, 617L, -1535377062L, 1048656958L, 1232636983L, 1429367169L,
1367564279L, 2011257309L, 465368733L, 2145097362L, -1688392714L,
1242461871L, 903938454L, -1655899701L, -644462143L, -989546917L,
1490781404L, -1179938597L, 2096556006L, -1669069821L, -1235003168L,
4298126L, -1373383705L, -1094933586L, -1924522578L, -2130070116L,
1153772672L, 169286314L, 913582111L, -1823841886L, 319315797L,
-512210604L, 669766238L, -629316167L, -879834542L, 53959630L,
1594997830L, -753761680L, 1202322861L, 1916245638L, 142481857L,
-216356290L, 1474078510L, -243542309L, -1620436066L, -1561408156L,
1428759011L, -1153714240L, 304657431L, 1728000675L, 1216590580L,
-1565440483L, -463280192L, 1830442404L, 67767486L, 1219697979L,
-1648271L, -725890670L, 1423420271L, 1754885030L, -442461896L,
-706649005L, 863429461L, 1488913684L, 1978534690L, 1990826630L,
723767363L, -613454991L, 1211470562L, 415604088L, 158816494L,
1820203055L, 1659553460L, -1989648371L, -3518529L, -868062475L,
2074554221L, -154628299L, 1014044586L, 1869558939L, 252432264L,
-1533529280L, -1462224799L, -1223953643L, -965573803L, -953174629L,
181185641L, -1452347612L, 1065759463L, -1096166066L, -235805317L,
938652660L, -19725959L, -240747877L, 1924528925L, -923146788L,
-1285635197L, 696524468L, -260874698L, -944173736L, -1182953536L,
1874121121L, 1265613439L, 596173114L, 1400346954L, 1157516706L,
-1625717960L, -1931910401L, -1973619053L, 943053366L, 1679198816L,
1919589130L, 729903167L, 1163832394L, -1691030448L, -1867175160L,
345903030L, 1406882885L, 1507108860L, 661347892L, 960341830L,
401245988L, -1605082257L, -1026653935L, 1585328321L, -756697125L,
-255489915L, -1213516766L, -1289212476L, -1519836608L, 1213647764L,
-1338389500L, -1501294827L, -1113906120L, 351400248L, -1533569407L,
383727618L, 1020754390L, 1400347050L, -1358941374L, -1067869458L,
188098335L, -702548354L, 710881086L, 2055264945L, 2006544056L,
892689306L, 2079718624L, 1232993257L, -22498097L, -387462852L,
1462127628L, -679969546L, 923534363L, -788077496L, -779985691L,
101173785L, -697093273L, -1133406838L, 2100454052L, -353840372L,
-410557519L, 483079703L, -924075670L, 983097212L, 1952301568L,
144895466L, -1538657072L, -65370561L, -1293604830L, 1062241736L,
911246047L, 1859856934L, -268652569L, 1131347255L, 1266330948L,
731739266L, -1181477807L, -1504478365L, 1883328231L, -1120345457L,
1946795693L, -553339244L, -1950008477L, -1445917719L, 1505133882L,
1035460554L, -469375767L, -56709339L, 1088907663L, -1078726056L,
1173374907L, -1054386700L, -1423492810L, -1815365534L, -442416936L,
260927395L, -1331731870L, 731704503L, 254622690L, 283228947L,
-494378259L, 1411576571L, 1475522660L, -1301255523L, -595867743L,
-1269971997L, -1385581520L, -1165939753L, 1888916157L, -2115289665L,
996914443L, -2019527756L, 1146421078L, 1965134172L, 307640608L,
-1083947454L, 2103200985L, -280530656L, 1483706556L, 983983941L,
-2085190021L, -1540213193L, 1334168425L, -1097665898L, 2072713262L,
-1589878278L, 367012746L, 41199998L, -1820403973L, 1750789335L,
-2003872465L, 113507878L, 650269950L, 1666820437L, 1398901920L,
1506854525L, 1739995248L, 1040507176L, -113461171L, 1419883725L,
-257466723L, 1818424700L, -1665223186L, 1645150828L, 1903379953L,
1081010930L, 1029087128L, 1827754631L, 357244927L, 437580955L,
1890811775L, -148443801L, -101908920L, 695947908L, -972609378L,
-113404462L, 951287537L, -911360099L, 433894598L, -1672061675L,
-1302142616L, -269607577L, -1204799261L, 1293020681L, -1895871595L,
1120721091L, 406439333L, 945842377L, 1225935342L, -1598512143L,
-2077800604L, 690975475L, -1310686809L, 855626915L, -1158928653L,
-864096253L, 1669509358L, -1028976595L, -355650367L, 1845605833L,
-33560273L, -1546319606L, 842454956L, -1432926241L, -1746913011L,
195691286L, -1959580477L, 78343367L, 32946669L, -1009625455L,
-1439068578L, -1166750770L, 1347989198L, 1071286L, -1656879859L,
2129934488L, 1371002397L, 2094360309L, -1435951654L, 1061028614L,
1622190978L, -1968752171L, 1787082814L, -1043708656L, 1411079524L,
-1086667995L, 1890751828L, -1145827206L, -1209111694L, 168062526L,
-1634081619L, 1642144213L, -1871761313L, 1997592664L, -2045569505L,
-1043054397L, -464836496L, 926340119L, -960779794L, -1311548065L,
271448754L, -1298105753L, 15742196L, 1223523191L, 1905599876L,
-592564194L, 1905172032L, 863212315L, -609372815L, -397840219L,
-763406687L, -730720090L, -1253771145L, 1944742507L, 2102083566L,
1242709371L, -648224406L, 666473508L, 2005432251L, 2039465297L,
-1648221954L, 1310586594L, 1872831283L, 547436788L, 1490407070L,
-2010661297L, -1170093747L, -1430247034L, -1110096644L, 26368424L,
-1643599277L, -2093549864L, -1132294976L, 1716963520L, 1765059202L,
-957594615L, 1279851940L, -1409091093L, 1754948243L, -1282006644L,
558015736L, 1783775108L, -1352703157L, -1412418181L, 1428444761L,
1788278608L, -832719795L, -1544239429L, 2009372146L, 595982736L,
226929191L, -1132345690L, 998313930L, -2016050912L, -1737636894L,
-363453338L, 1498410772L, 496000327L, -1701215850L, -907239791L,
1039781340L, -1665209798L, -1109593876L, -1159213941L, 803075543L,
1971204313L, -534177708L, -990380124L, -1383750411L, -462205498L,
1384392456L, -964112266L, -1466964462L, 115341393L, 845279145L,
996272060L, -900586017L, -1879936832L, 376359205L, -652283725L,
2025728904L, 1380008006L, -1244481025L, 375424772L, 56448370L,
19775909L, -1215524017L, 1914891222L, -750964520L, 314637231L,
1832403685L, 1150617821L, -1285420509L, -403024028L, 21294443L,
-1097765175L, 2061730362L, -1220815676L, -446219379L, -1418868197L,
-1997804799L, 687389069L, 1134781544L, -1185101972L, 2130969188L,
416686891L, -425190152L, 1058360788L, -1709096420L, 979020380L,
2018700094L, 115617012L, 1690406152L, -120745897L, 1878759148L,
-1148609190L, -116373502L, 1356281799L, -1388162865L, -1017188458L,
-974632207L, 901262193L, -166391268L, -1444268734L, 689395679L,
-214744715L, 1079626966L, 626249961L, 306852561L, -2111272080L,
1175790579L, -1952238987L, 1133045842L, 238012356L, -546654303L,
-1914432245L, 897719360L, 2145466493L, -1618662470L, 1328986925L,
-819622957L, -2114861141L, -428406757L, -597059260L, 1083860074L,
-1001362639L, -58573466L, 798221867L, 1784989447L, 1059713834L,
-511559046L, -195199812L, -1859005742L, -1433066940L, 813812312L,
607556345L, -72931799L, -636788508L, -1025926857L, 16828092L,
1128236436L, -1158994389L, 648984581L, -1883722753L, 88469849L,
-1057634625L, -1340205670L, 992060661L, -582634023L, 1292516003L,
-1180882410L, 1108234525L, 724304121L, -201717252L, -1784368911L,
-2084967766L, -2114451266L, -1336465483L, -540740309L, -1191022646L,
-974274381L, -1753027543L, 104519975L, 997135836L, -1003589431L,
1689163361L, -2088874233L, 1144591053L, -1489636804L, -1144112645L,
-1760022433L, -591769544L, 607356513L, 13625789L, 176012613L,
-1757221365L, -277625901L, 752122644L, -1926782531L, 650916386L,
451166744L, -1562666783L, 1949513791L, 1909258142L, 1277144671L,
531266904L, -518146858L, -392747796L, 1023525760L, 909674007L,
-824639842L, 34754118L, -433135716L, 720762626L, 32266839L, -993211015L,
207746153L, 1776690042L, -1947332510L, -1467980279L, 438078228L,
-2023497452L, 686456718L, -628123060L, -1179967292L, 1405065335L,
-786723338L, -265143965L, 225828781L, -1196031283L, -1990356980L,
-1486132463L, 132249676L, -828133403L, -1164877240L, -1855922573L,
-352336243L, -971403923L, -1446625482L, 1621419690L, 1146081225L,
-642309080L, 1079462342L, -307473886L, -1222820161L, 1399033680L,
1690981924L, -699167786L, -702820497L, 67055579L, -1044041019L,
-325247231L, -144760069L, -2136831154L, -1392392430L, 604531050L,
1547769407L, -2013388589L, -237238573L, 1726740914L, -345186754L,
-1355052837L, 1679797311L, -1733162625L, 1815262507L, -561029487L,
1432378845L, 727396677L, 1209824870L, 611130806L, -157624750L,
108946266L, -1951363443L, 993884829L, -359255096L, 1644264180L,
1795516182L, -1220943821L, -1443594326L, -1973823534L, 605241690L,
-1365451596L, -700471898L, 1922705476L, -1252586055L, 925361148L,
-275258531L, 35062795L, -1845868388L, 566109467L, 2116558243L,
-736748735L, -1557261421L, -2135209754L, -5667991L, -1605223666L,
-69079121L, 1576105079L, -1405868522L, -1031655305L, -1654475003L,
-2113433872L, 306426039L, -187053244L, -1647546259L) |
separateSequences <- function(in.file, filter_files, identity_threshold) {
cat('Separating sequences according to the filter files...\n')
tstart <- Sys.time()
fid.in <- file(in.file,'rb')
blockSize = 2^24
hNdx <- {}
pos <- 0
cnt <- blockSize
while(cnt == blockSize) {
aux <- readChar(fid.in, nchars=blockSize, useBytes=T)
cnt<- nchar(aux)
hNdx <- c(hNdx, pos + gregexpr(aux, pattern='>')[[1]])
pos <- seek(fid.in)
}
hNdx <- c(hNdx, pos + cnt)
seek(fid.in, where=0)
numItems <- length(hNdx)-1
headers <- rep('', numItems);
for(i in 1:numItems) {
seek(fid.in, hNdx[i]);
headers[i] = readLines(con = fid.in, n = 1)
}
label = rep(1, numItems)
if(length(filter_files) > 0) {
for(i in 1:length(filter_files)) {
d <- tryCatch(read.table(filter_files[i], sep = ',', header = F),
error = function(e) data.frame(),
finally = function(e) data.frame())
if(nrow(d) > 0) {
d <- d[d[[3]] > identity_threshold,]
d <- d[order(d[[1]]),]
label[is.element(headers, d[[1]])] <- i+1
}
}
}
tstamp = Sys.time()
out.files = {}
for(i in unique(label)) {
fid.out <- NA
if(i == 1) {
filename <- paste0(tstamp, '_filtered-unlabeled.fasta')
fid.out <- file(filename, 'wb')
cat(' - unlabeled: ', sum(label == 1), '\n')
} else {
filename <- basename(filter_files[[i]])
filename <- substr(filename, 1, nchar(filename)-4)
filename <- paste0(tstamp, '_filtered-', filename, '.fasta')
fid.out <- file(filename, 'wb')
cat(' - ', filename, ': ', sum(label==i))
}
out.files <- c(out.files, filename)
for(j in which(label == i)) {
chunkStart <- hNdx[j]-1
seek(fid.in, chunkStart)
chunk <- ""
if(j < numItems) {
chunkEnd <- hNdx[j+1]-1
chunk <- readChar(fid.in, nchars = chunkEnd - chunkStart)
} else
chunk <- readChar(fid.in, nchars = 1e6)
writeChar(chunk, con=fid.out, eos=NULL)
}
close(fid.out)
}
close(fid.in)
cat(' - Elapsed time: ', Sys.time() - tstart, ' sec\n')
return(out.files)
} |
trnd<-
function(l,u)
{
x=rnorm(length(l))
I=which(x<l|x>u);d=length(I);
while (d>0) {
ly=l[I]
uy=u[I]
y=rnorm(length(ly))
idx=(y>ly)&(y<uy)
x[I[idx]]=y[idx]
I=I[!idx]
d=length(I)
}
return(x)
} |
expected <- eval(parse(text="structure(2:3, .Label = c(\"C\", \"A\", \"B\"), class = \"factor\")"));
test(id=0, code={
argv <- eval(parse(text="list(structure(1:2, .Label = c(\"a\", \"b\"), class = \"factor\"), value = structure(list(C = \"C\", A = \"a\", B = \"b\"), .Names = c(\"C\", \"A\", \"B\")))"));
do.call(`levels<-`, argv);
}, o=expected); |
"PLcop" <-
function(u, v, para=NULL, ...) {
T <- para[1]
if(is.null(para)) {
warning("Empty para argument, need value on [0,Inf]")
return()
}
if(T < 0) {
warning("Theta < 0, invalid parameter")
return()
}
if(T == 1) return( u*v)
if(T == 0) return(W(u,v))
if(! is.finite(T)) return(M(u,v))
cop <- 1+(T-1)*(u+v)
cop <- cop - sqrt(cop^2 - 4*u*v*T*(T-1))
cop <- cop / (2*(T-1))
return(cop)
}
"PLACKETTcop" <- function(u, v, para=NULL, ...) {
PLcop(u, v, para=para, ...)
} |
unzip_all_files<-function(in_direc,out_direc){
zip_files<-list.files(path=in_direc,pattern= c("*\\.zip$" ),full.names=T)
dir.create(out_direc,showWarnings = F)
for(i in 1:length(zip_files)){
unzip(zip_files[i],exdir=out_direc)
}
message("Files Unzipped")
} |
NArray <-
function( x, cells=NA )
{
if( !is.list(x) ) stop("Argument must be a (named) list." )
array( cells, dimnames=x, dim=sapply( x, length ) )
}
ZArray <- function( x, cells=0 ) NArray( x, cells=cells )
larray <-
function( data=NA, dim, dimnames )
{
if( is.list(data) )
return( array(data=NA,dim=sapply(data,length),
dimnames=data) )
else
if( is.list(dim) )
return( array(data=data,dim=sapply(dim,length),
dimnames=dim) )
else
if( is.list(dimnames) )
return( array(data=data,dim=sapply(dimnames,length),
dimnames=dimnames) )
else
if( !missing(dimnames) )
return( array(data=data,dim=length(data),
dimnames=dimnames) )
else
return( array(data=data,dim=length(data)) )
} |
rm_sdt_create_partable_define_pargroups <- function(partable, pg1, pg2)
{
partable$pargroup <- 0
K <- max( partable$col, na.rm=TRUE)
for (kk in 1:K){
m1 <- max(partable$pargroup) + 1
ind <- ( partable$type==pg1 ) & ( partable$col==kk)
partable[ ind, "pargroup"] <- m1 * ( sum( partable[ind,"est"] ) > 0 )
}
m1 <- max(partable$pargroup) + 1
ind <- ( partable$type==pg2 )
partable[ ind, "pargroup"] <- m1 * ( sum( partable[ind,"est"] ) > 0 )
return(partable)
} |
library(tidyverse)
find_game_next_score_half <- function(pbp_dataset) {
score_plays <- which(pbp_dataset$sp == 1 & pbp_dataset$play_type != "no_play")
find_next_score <- function(play_i, score_plays_i,pbp_df) {
next_score_i <- score_plays_i[which(score_plays_i >= play_i)[1]]
if (is.na(next_score_i) |
(pbp_df$qtr[play_i] %in% c(1, 2) & pbp_df$qtr[next_score_i] %in% c(3, 4, 5)) |
(pbp_df$qtr[play_i] %in% c(3, 4) & pbp_df$qtr[next_score_i] == 5)) {
score_type <- "No_Score"
score_drive <- pbp_df$drive[play_i]
} else {
score_drive <- pbp_df$drive[next_score_i]
if (pbp_df$touchdown[next_score_i] == 1 & (pbp_df$td_team[next_score_i] != pbp_df$posteam[next_score_i])) {
if (identical(pbp_df$posteam[play_i], pbp_df$posteam[next_score_i])) {
score_type <- "Opp_Touchdown"
} else {
score_type <- "Touchdown"
}
} else if (identical(pbp_df$field_goal_result[next_score_i], "made")) {
if (identical(pbp_df$posteam[play_i], pbp_df$posteam[next_score_i])) {
score_type <- "Field_Goal"
} else {
score_type <- "Opp_Field_Goal"
}
} else if (pbp_df$touchdown[next_score_i] == 1) {
if (identical(pbp_df$posteam[play_i], pbp_df$posteam[next_score_i])) {
score_type <- "Touchdown"
} else {
score_type <- "Opp_Touchdown"
}
} else if (pbp_df$safety[next_score_i] == 1) {
if (identical(pbp_df$posteam[play_i],pbp_df$posteam[next_score_i])) {
score_type <- "Opp_Safety"
} else {
score_type <- "Safety"
}
} else if (identical(pbp_df$extra_point_result[next_score_i], "good")) {
if (identical(pbp_df$posteam[play_i], pbp_df$posteam[next_score_i])) {
score_type <- "Extra_Point"
} else {
score_type <- "Opp_Extra_Point"
}
} else if (identical(pbp_df$two_point_conv_result[next_score_i], "success")) {
if (identical(pbp_df$posteam[play_i], pbp_df$posteam[next_score_i])) {
score_type <- "Two_Point_Conversion"
} else {
score_type <- "Opp_Two_Point_Conversion"
}
} else if (identical(pbp_df$defensive_two_point_conv[next_score_i], 1)) {
if (identical(pbp_df$posteam[play_i], pbp_df$posteam[next_score_i])) {
score_type <- "Opp_Defensive_Two_Point"
} else {
score_type <- "Defensive_Two_Point"
}
} else {
score_type <- NA
}
}
return(data.frame(Next_Score_Half = score_type,
Drive_Score_Half = score_drive))
}
lapply(c(1:nrow(pbp_dataset)), find_next_score,
score_plays_i = score_plays, pbp_df = pbp_dataset) %>%
bind_rows() %>%
return
}
pbp_data <- purrr::map_df(1999 : 2019, function(x) {
readRDS(
glue::glue("data/play_by_play_{x}.rds")
) %>% filter(season_type == 'REG')
}) %>%
mutate(
Winner = if_else(home_score > away_score, home_team,
if_else(home_score < away_score, away_team, "TIE"))
)
pbp_next_score_half <- map_dfr(unique(pbp_data$game_id),
function(x) {
pbp_data %>%
filter(game_id == x) %>%
find_game_next_score_half()
})
pbp_data <- bind_cols(pbp_data, pbp_next_score_half)
pbp_data <- pbp_data %>%
filter(Next_Score_Half %in% c("Opp_Field_Goal", "Opp_Safety", "Opp_Touchdown",
"Field_Goal", "No_Score", "Safety", "Touchdown") &
play_type %in% c("field_goal", "no_play", "pass", "punt", "run",
"qb_spike") & is.na(two_point_conv_result) & is.na(extra_point_result) &
!is.na(down) & !is.na(game_seconds_remaining)) %>%
select(
game_id,
Next_Score_Half,
Drive_Score_Half,
play_type,
game_seconds_remaining,
half_seconds_remaining,
yardline_100,
roof,
posteam,
defteam,
home_team,
ydstogo,
season,
qtr,
down,
week,
drive,
ep,
score_differential,
posteam_timeouts_remaining,
defteam_timeouts_remaining,
desc,
receiver_player_name,
pass_location,
air_yards,
yards_after_catch,
complete_pass, incomplete_pass, interception,
qb_hit,
extra_point_result,
field_goal_result,
sp,
Winner,
spread_line,
total_line
)
saveRDS(pbp_data, 'models/cal_data.rds')
pbp_data <- purrr::map_df(2000 : 2019, function(x) {
readRDS(
url(
glue::glue("https://raw.githubusercontent.com/guga31bb/nflfastR-data/master/legacy-data/play_by_play_{x}.rds")
)
) %>% filter(season_type == 'REG')
})
games <- readRDS(url("http://www.habitatring.com/games.rds")) %>%
filter(!is.na(result)) %>%
mutate(
game_id = as.numeric(old_game_id),
Winner = if_else(home_score > away_score, home_team,
if_else(home_score < away_score, away_team, "TIE"))
) %>%
select(game_id, Winner, result, roof)
pbp_data <- pbp_data %>%
left_join(
games, by = c('game_id')
)
pbp_next_score_half <- map_dfr(unique(pbp_data$game_id),
function(x) {
pbp_data %>%
filter(game_id == x) %>%
find_game_next_score_half()
})
pbp_data <- bind_cols(pbp_data, pbp_next_score_half)
pbp_data <- pbp_data %>%
filter(Next_Score_Half %in% c("Opp_Field_Goal", "Opp_Safety", "Opp_Touchdown",
"Field_Goal", "No_Score", "Safety", "Touchdown") &
play_type %in% c("field_goal", "no_play", "pass", "punt", "run",
"qb_spike") & is.na(two_point_conv_result) & is.na(extra_point_result) &
!is.na(down) & !is.na(game_seconds_remaining)) %>%
select(posteam, wp, qtr, Winner, td_prob, opp_td_prob, fg_prob, opp_fg_prob, safety_prob, opp_safety_prob, no_score_prob, Next_Score_Half)
saveRDS(pbp_data, 'models/cal_data_nflscrapr.rds') |
"fitted.bsad" <- function(object, alpha = 0.05, HPD = TRUE, ...) {
smcmc <- object$mcmc$smcmc
fparg <- object$fit.draws$fpar
fsemig <- object$fit.draws$fsemi
fsemiMaxKappag <- object$fit.draws$fsemiMaxKappa
if (object$parametric != "none") {
fpar <- list()
fparm <- apply(fparg, 2, mean)
fpar$mean <- fparm
}
fsemi <- list()
fsemim <- apply(fsemig, 2, mean)
fsemi$mean <- fsemim
fsemiMaxKappa <- list()
fsemiMaxKappam <- apply(fsemiMaxKappag, 2, mean)
fsemiMaxKappa$mean <- fsemiMaxKappam
if (HPD) {
n <- object$nint
prob <- 1 - alpha
if (object$parametric != "none") {
fparg.o <- apply(fparg, 2, sort)
gap <- max(1, min(smcmc - 1, round(smcmc * prob)))
init <- 1:(smcmc - gap)
inds <- apply(fparg.o[init + gap, , drop = FALSE] - fparg.o[init, , drop = FALSE], 2, which.min)
fpar$lower <- fparg.o[cbind(inds, 1:n)]
fpar$upper <- fparg.o[cbind(inds + gap, 1:n)]
}
fsemig.o <- apply(fsemig, 2, sort)
gap <- max(1, min(smcmc - 1, round(smcmc * prob)))
init <- 1:(smcmc - gap)
inds <- apply(fsemig.o[init + gap, , drop = FALSE] - fsemig.o[init, , drop = FALSE], 2, which.min)
fsemi$lower <- fsemig.o[cbind(inds, 1:n)]
fsemi$upper <- fsemig.o[cbind(inds + gap, 1:n)]
fsemiMaxKappag.o <- apply(fsemiMaxKappag, 2, sort)
gap <- max(1, min(smcmc - 1, round(smcmc * prob)))
init <- 1:(smcmc - gap)
inds <- apply(fsemiMaxKappag.o[init + gap, , drop = FALSE] - fsemiMaxKappag.o[init, , drop = FALSE], 2, which.min)
fsemiMaxKappa$lower <- fsemiMaxKappag.o[cbind(inds, 1:n)]
fsemiMaxKappa$upper <- fsemiMaxKappag.o[cbind(inds + gap, 1:n)]
} else {
if (object$parametric != "none") {
fpar$lower <- apply(fparg, 2, function(x) quantile(x, probs = alpha/2))
fpar$upper <- apply(fparg, 2, function(x) quantile(x, probs = 1 - alpha/2))
}
fsemi$lower <- apply(fsemig, 2, function(x) quantile(x, probs = alpha/2))
fsemi$upper <- apply(fsemig, 2, function(x) quantile(x, probs = 1 - alpha/2))
fsemiMaxKappa$lower <- apply(fsemiMaxKappag, 2, function(x) quantile(x, probs = alpha/2))
fsemiMaxKappa$upper <- apply(fsemiMaxKappag, 2, function(x) quantile(x, probs = 1 - alpha/2))
}
out <- object
out$alpha <- alpha
out$HPD <- HPD
out$parametric <- object$parametric
if (object$parametric != "none")
out$fpar <- fpar
out$fsemi <- fsemi
out$fsemiMaxKappa <- fsemiMaxKappa
class(out) <- "fitted.bsad"
out
} |
kimPossible_palette <- c(
"
"
"
"
"
"
"
"
"
"
"
"
)
kimPossible_pal <- function(n, type = c("discrete", "continuous"),
reverse = FALSE){
kimPossible <- kimPossible_palette
if (reverse == TRUE) {
kimPossible <- rev(kimPossible)
}
if (missing(n)) {
n <- length(kimPossible)
}
type <- match.arg(type)
if (type == "discrete" && n > length(kimPossible)) {
stop(glue::glue("Palette does not have {n} colors, maximum is {length(kimPossible)}!"))
}
kimPossible <- switch(type,
continuous = grDevices::colorRampPalette(kimPossible)(n),
discrete = kimPossible[1:n])
kimPossible <- scales::manual_pal(kimPossible)
return(kimPossible)
}
scale_color_kimPossible <- function(n, type = "discrete",
reverse = FALSE, ...){
if (type == "discrete") {
ggplot2::discrete_scale("color", "kimPossible", kimPossible_pal(), ...)
} else {
ggplot2::scale_color_gradientn(colors = kimPossible_pal(n = n, type = type,
reverse = reverse)(8))
}
}
scale_colour_kimPossible <- scale_color_kimPossible
scale_fill_kimPossible <- function(n, type = "discrete",
reverse = FALSE, ...){
if (type == "discrete") {
ggplot2::discrete_scale("fill", "kimPossible", kimPossible_pal(), ...)
} else {
ggplot2::scale_fill_gradientn(colors = kimPossible_pal(n = n, type = type,
reverse = reverse)(8))
}
} |
label_significance_level <- function( values, levels, labels ){
ix <- sort( levels, index.return=TRUE)$ix
levels <- levels[ix]
labels <- labels[ix]
NL <- length(levels)
l1 <- ""
values[ is.na(values) ] <- 1.2
for (ll in 1:NL){
l1 <- ifelse( values < levels[NL-ll+1], labels[NL-ll+1], l1)
}
return(l1)
} |
print.naive_bayes_tables <- function(x, ...) {
symbol = ":::"
n_char <- getOption("width")
str_left_right <- paste0(rep("=", floor((n_char - 11) / 2)),
collapse = "")
str_full <- paste0(str_left_right, " Naive Bayes ",
ifelse(n_char %% 2 != 0, "=", ""), str_left_right)
len <- nchar(str_full)
l <- paste0(rep("-", len), collapse = "")
n <- length(x)
cond_dists <- get_cond_dist(x)
if (is.null(cond_dists)) {
cond_dists <- recognize_cond_dist(x)
}
for (i in 1:n) {
ith_tab <- x[[i]]
ith_name <- names(x)[i]
ith_dist <- cond_dists[i]
if (ith_dist == "KDE") {
for (ith_factor in names(ith_tab)) {
cat("\n")
cat(l, "\n")
cat(paste0(" ", symbol, " ", ith_name, "::", ith_factor,
" (", ith_dist, ")", "\n"))
cat(l, "\n")
print(ith_tab[[ith_factor]])
}
} else {
cat("\n")
cat(l, "\n")
cat(paste0(" ", symbol, " ", ith_name, " (", ith_dist, ") ", "\n"))
cat(l, "\n")
if (ith_dist == "Poisson") cat("\n")
print(ith_tab)
}
}
cat("\n")
cat(l)
}
`[.naive_bayes_tables` <- function(x, i) {
if (missing(i)) {
return(x)
}
len_i <- length(i)
len_x <- length(x)
nam_x <- names(x)
cond_dist <- attr(x, "cond_dist")
class(x) <- "list"
if (any(is.na(i))) {
stop(paste0("`[`: NAs are not allowed for indexing of \"naive_bayes\" tables."), call. = FALSE)
}
if (!is.numeric(i) & !is.character(i) & !is.factor(i) & !is.logical(i))
stop("`[`: Indexing vector can only be \"character\", \"factor\", \"numeric\" or \"logical\".")
if (is.numeric(i)) {
if (any(i < 0) | any(i %% 1 != 0))
stop("`[`: Indexing vector should contain only positive integers.", call. = FALSE)
if (any(i > len_x))
stop(paste0("`[`: There ", ifelse(len_x == 1, "is", "are"), " only ", len_x,
ifelse(len_x == 1, " table.", " \"naive_bayes\" tables.")), call. = FALSE)
}
if (is.logical(i)) {
if (length(i) > len_x)
stop(paste0("`[`: There ", ifelse(len_x == 1, "is", "are"), " only ", len_x,
ifelse(len_x == 1, " table.", " \"naive_bayes\" tables.")), call. = FALSE)
if (all(i == FALSE)) {
return(list())
}
}
if ((is.character(i) | is.factor(i)) & any(!i %in% nam_x))
stop("`[`: Undefined columns selected - indexing vector does not contain correct name(s) of feature(s).", call. = FALSE)
res <- x[i]
class(res) <- "naive_bayes_tables"
attr(res, "cond_dist") <- cond_dist
res
}
get_cond_dist <- function(object) {
if (class(object) == "naive_bayes") {
cond_dist <- attr(object$tables, "cond_dist")
} else if (class(object) == "naive_bayes_tables") {
cond_dist <- attr(object, "cond_dist")
} else if (class(object) == "bernoulli_naive_bayes") {
vars <- rownames(object$prob1)
cond_dist <- stats::setNames(rep("Bernoulli", length(vars)), vars)
} else if (class(object) == "gaussian_naive_bayes") {
vars <- colnames(object$params$mu)
cond_dist <- stats::setNames(rep("Gaussian", length(vars)), vars)
} else if (class(object) == "poisson_naive_bayes") {
vars <- rownames(object$params)
cond_dist <- stats::setNames(rep("Poisson", length(vars)), vars)
} else if (class(object) == "multinomial_naive_bayes") {
vars <- rownames(object$params)
cond_dist <- stats::setNames(rep("Multinomial", length(vars)), vars)
} else if (class(object) == "nonparametric_naive_bayes") {
cond_dist <- attr(object$dens, "cond_dist")
} else {
stop(paste0("get_cond_dist() expects ", paste0(models(), collapse = ", "),
", naive_bayes_tables objects."), call. = FALSE)
}
cond_dist
}
recognize_cond_dist <- function(tab) {
sapply(tab, function(ith_tab) {
if (class(ith_tab) == "array") {
cond_dist <- "KDE"
} else if (class(ith_tab) == "table") {
rnames <- rownames(ith_tab)
norm_par <- c("mean", "sd")
if (any(rownames(ith_tab) == "lambda") & nrow(ith_tab) == 1)
cond_dist <- "Poisson"
if (nrow(ith_tab) == 2 & all(!rnames %in% norm_par))
cond_dist <- "Bernoulli"
if (nrow(ith_tab) == 2 & all(rnames %in% norm_par))
cond_dist <- "Gaussian"
if (nrow(ith_tab) > 2)
cond_dist <- "Categorical"
} else {
cond_dist <- ""
}
cond_dist
})
} |
require(BETS)
library(BETS) |
plot_hairpin <- function(ctFile){
dot <- ct2dot(ctFile)
ct <- makeCt(dot[[1]][1],dot[[2]][1])
co <- ct2coord(ct)
loops <- hairpin_loop(ctFile)
arr_min <- c()
arr_max <- c()
if(length(loops) != 0){
for (i in 1:length(loops)) {
arr_min <- c(arr_min,loops[[i]][1])
if(length(loops[[i]]) > 1){
for (j in 2:length(loops[[i]])) {
if(loops[[i]][j-1] == loops[[i]][j] - 1){
}else{
arr_max <- c(arr_max,loops[[i]][j-1])
arr_min <- c(arr_min,loops[[i]][j])
}
}
arr_max <- c(arr_max,loops[[i]][j])
}else{
arr_max <- c(arr_max,loops[[i]][1])
}
}
ranges=data.frame(min=arr_min,max=arr_max,col=2,
desc="hairpin loop"
)
RNAPlot(co,ranges)
print("------------------------------------------------------")
print("summary of hairpin loops:")
print(paste("the number of hairpin loops is:",length(loops)))
print(paste("the bases in hairpin loops are:",paste(unlist(loops),collapse = " ", sep = "")))
loops_name <- c()
for (i in 1:length(loops)) {
loops_name <- c(loops_name,paste("bases in hairpin loop ",i))
}
names(loops) <- loops_name
return(loops)
}
} |
TaskSupervised = R6Class("TaskSupervised", inherit = Task,
public = list(
initialize = function(id, task_type, backend, target, extra_args = list()) {
super$initialize(id = id, task_type = task_type, backend = backend, extra_args = extra_args)
assert_subset(target, self$col_roles$feature)
self$col_roles$target = target
self$col_roles$feature = setdiff(self$col_roles$feature, target)
},
truth = function(rows = NULL) {
self$data(rows, cols = self$target_names)
}
)
) |
theme_hdnom <- function(base_size = 14) {
theme_bw(base_size = base_size) +
theme(
text = element_text(size = base_size),
plot.title = element_text(face = "bold", size = base_size * 1.3, hjust = 0.5),
axis.title = element_text(face = "plain"),
axis.title.x = element_text(size = base_size * 1.25, vjust = -2),
axis.title.y = element_text(size = base_size * 1.25, angle = 90, vjust = 4),
axis.text = element_text(size = base_size, color = "
axis.ticks = element_line(),
axis.ticks.length = unit(2, "mm"),
axis.line = element_line(colour = "
legend.key = element_rect(colour = NA),
legend.position = "bottom",
legend.direction = "horizontal",
legend.key.size = unit(2, "mm"),
legend.margin = margin(t = 0, r = 0, b = 0, l = 0, unit = "pt"),
legend.title = element_text(face = "plain", size = base_size),
plot.background = element_rect(colour = NA),
plot.margin = unit(c(10, 5, 5, 5), "mm"),
panel.background = element_rect(colour = NA),
panel.border = element_rect(colour = NA),
panel.grid.major = element_line(colour = "
panel.grid.minor = element_blank(),
strip.background = element_rect(colour = "
strip.text = element_text(face = "bold", size = base_size)
)
} |
`is.gp` <-
function(x) {
if (inherits(x, "gp"))
return (TRUE)
return (FALSE)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.