code
stringlengths 1
13.8M
|
---|
"makepd" <-
function(mat, eig.tol=1.0000e-06){
cor.mat <- covtocor(mat)
mat <- cor.mat$mat
eig <- eigen(mat, symmetric = TRUE)
D <- sort(eig$values)
S <- eig$vectors[,order(sort(D, decreasing=TRUE ))]
D[which(D<eig.tol)] <- eig.tol
for (i in 1:ncol(S)) S[,i] <- S[,i] * D[i]
B <- t(sumsqscale(t(S)))
A <- B %*% t(B)
return (cortocov(A, cor.mat$sd))
} |
qc_missed_cleavages <-
function(data,
sample,
grouping,
missed_cleavages,
intensity,
remove_na_intensities = TRUE,
method = "count",
plot = FALSE,
interactive = FALSE) {
protti_colours <- "placeholder"
utils::data("protti_colours", envir = environment())
if (remove_na_intensities == TRUE) {
if (missing(intensity)) {
stop(strwrap("Please provide a column containing
intensities or set remove_na_intensities to FALSE",
prefix = "\n", initial = ""
))
}
data <- data %>%
tidyr::drop_na({{ intensity }})
}
if (method == "count") {
result <- data %>%
dplyr::distinct({{ sample }}, {{ grouping }}, {{ missed_cleavages }}, {{ intensity }}) %>%
dplyr::count({{ sample }}, {{ missed_cleavages }}) %>%
dplyr::group_by({{ sample }}) %>%
dplyr::mutate(total_peptide_count = sum(n)) %>%
dplyr::group_by({{ sample }}, {{ missed_cleavages }}) %>%
dplyr::summarise(mc_percent = n / .data$total_peptide_count * 100) %>%
dplyr::ungroup() %>%
dplyr::mutate({{ missed_cleavages }} := forcats::fct_inorder(factor({{ missed_cleavages }}))) %>%
dplyr::mutate({{ sample }} := factor({{ sample }},
levels = unique(stringr::str_sort({{ sample }}, numeric = TRUE))
))
if (plot == FALSE) {
return(result)
} else {
plot <- result %>%
ggplot2::ggplot(aes(
x = {{ sample }},
y = .data$mc_percent,
fill = {{ missed_cleavages }}
)) +
geom_col(col = "black", size = 1) +
{
if (interactive == FALSE) {
geom_text(
data = result %>% dplyr::filter(.data$mc_percent > 5),
aes(label = round(.data$mc_percent, digits = 1)),
position = position_stack(vjust = 0.9)
)
}
} +
labs(
title = "Missed cleavages per .raw file",
subtitle = "By percent of total peptide count",
x = "Sample",
y = "% of total peptide count",
fill = "Missed cleavages"
) +
theme_bw() +
theme(
plot.title = ggplot2::element_text(size = 20),
axis.title.x = ggplot2::element_text(size = 15),
axis.text.y = ggplot2::element_text(size = 15),
axis.text.x = ggplot2::element_text(size = 12, angle = 75, hjust = 1),
axis.title.y = ggplot2::element_text(size = 15),
legend.title = ggplot2::element_text(size = 15),
legend.text = ggplot2::element_text(size = 15)
) +
scale_fill_manual(values = protti_colours)
}
}
if (method == "intensity") {
result <- data %>%
tidyr::drop_na({{ intensity }}) %>%
dplyr::distinct(
{{ sample }},
{{ grouping }},
{{ missed_cleavages }},
{{ intensity }}
) %>%
dplyr::group_by({{ sample }}) %>%
dplyr::mutate(total_intensity = sum({{ intensity }})) %>%
dplyr::group_by({{ sample }}, {{ missed_cleavages }}) %>%
dplyr::mutate(sum_intensity_mc = sum({{ intensity }})) %>%
dplyr::summarise(mc_percent = .data$sum_intensity_mc / .data$total_intensity * 100) %>%
dplyr::ungroup() %>%
dplyr::mutate({{ missed_cleavages }} := forcats::fct_inorder(factor({{ missed_cleavages }}))) %>%
dplyr::mutate({{ sample }} := factor({{ sample }},
levels = unique(stringr::str_sort({{ sample }}, numeric = TRUE))
)) %>%
dplyr::distinct()
if (plot == FALSE) {
return(result)
} else {
plot <- result %>%
ggplot2::ggplot(aes(
x = {{ sample }},
y = .data$mc_percent,
fill = {{ missed_cleavages }}
)) +
geom_col(col = "black", size = 1) +
{
if (interactive == FALSE) {
geom_text(
data = result %>% dplyr::filter(.data$mc_percent > 5),
aes(label = round(.data$mc_percent, digits = 1)),
position = position_stack(vjust = 0.9)
)
}
} +
labs(
title = "Missed cleavages per .raw file",
subtitle = "By percent of total intensity",
x = "",
y = "% of total intensity",
fill = "Missed cleavages"
) +
theme_bw() +
theme(
plot.title = ggplot2::element_text(size = 20),
axis.title.x = ggplot2::element_text(size = 15),
axis.text.y = ggplot2::element_text(size = 15),
axis.text.x = ggplot2::element_text(size = 12, angle = 75, hjust = 1),
axis.title.y = ggplot2::element_text(size = 15),
legend.title = ggplot2::element_text(size = 15),
legend.text = ggplot2::element_text(size = 15)
) +
scale_fill_manual(values = protti_colours)
}
}
if (interactive == TRUE) {
return(plotly::ggplotly(plot))
} else {
return(plot)
}
} |
bed_closest <- function(x, y, overlap = TRUE,
suffix = c(".x", ".y")) {
x <- check_interval(x)
y <- check_interval(y)
check_suffix(suffix)
x <- bed_sort(x)
y <- bed_sort(y)
groups_xy <- shared_groups(x, y)
groups_xy <- unique(as.character(c("chrom", groups_xy)))
groups_vars <- rlang::syms(groups_xy)
x <- convert_factors(x, groups_xy)
y <- convert_factors(y, groups_xy)
x <- group_by(x, !!! groups_vars)
y <- group_by(y, !!! groups_vars)
suffix <- list(x = suffix[1], y = suffix[2])
grp_indexes <- shared_group_indexes(x, y)
res <- closest_impl(x, y,
grp_indexes$x,
grp_indexes$y,
suffix$x,
suffix$y)
if (!overlap) {
res <- filter(res, .overlap < 1)
res <- select(res, -.overlap)
}
res
} |
dual_top <- function(alpha, beta, pair, error, numb_cells) {
number_plates <- nrow(alpha)/96
max_beta <- ncol(beta)
sample_size_well <- numb_cells[, 1]
numb_sample <- numb_cells[, 2]
small <- which(sample_size_well < 50)
if (length(small) == 0 ) return(matrix(nrow = 0, ncol = 3))
if (length(small) > 1) {
if (any(small == 1)) {
small_wells <- c(1:numb_sample[small[1]])
for (i in 2:length(small)) {
j <- small[i]
small_wells <- c(small_wells,
(sum(numb_sample[1:(j-1)]) + 1):sum(numb_sample[1:j])
)
}
} else {
small_wells <- vector()
for (i in 1:length(small)) {
j <- small[i]
small_wells <- c(small_wells,
(sum(numb_sample[1:(j-1)]) + 1):sum(numb_sample[1:j])
)
}
}
} else {
small_wells <- 1:numb_sample[small]
}
alpha <- alpha[small_wells, ]
beta <- beta[small_wells, ]
rec <- matrix(nrow = 0, ncol = 6)
colnames(rec) <- c("beta", "alpha1", "alpha2", "shared_LL",
"dual_LL", "dual_freq")
freq <- pair
freq <- freq[freq[, 9] > .8,]
freq <- freq[order(freq[, "MLE"], decreasing = TRUE), ]
freq <- freq[!is.na(freq[, "MLE"]), ]
for (clon in 1:max_beta) {
x <- freq[freq[, "beta1"] == clon, , drop = FALSE]
numb_cand <- nrow(x)
if (numb_cand > 1) {
combos <- utils::combn(numb_cand, 2)
for (ind in 1:ncol(combos)) {
ind_beta <- clon
ind_alph1 <- x[combos[1, ind], "alpha1"]
ind_alph2 <- x[combos[2, ind], "alpha1"]
f1 <- x[combos[1, ind], "MLE"]
f2 <- x[combos[2, ind], "MLE"]
exp_plates <- 0
sample_size_well <- numb_cells[, 1]
numb_sample <- numb_cells[, 2]
sample_size_well <- sample_size_well[small]
numb_sample <- numb_sample[small]
numb_distinct <- length(sample_size_well)
well_clone <- rep(0, numb_distinct)
well_clone <- matrix(ncol = 5, nrow = numb_distinct)
colnames(well_clone) <- c("ba1", "ba2", "a1a2", "ba1a2", "none")
for (size in 1:numb_distinct) {
ind1 <- cumsum(numb_sample[1:size])[size] - numb_sample[size] + 1
ind2 <- cumsum(numb_sample[1:size])[size]
well_clone[size, "ba1"] <- sum(beta[ind1:ind2, ind_beta] == 1 &
alpha[ind1:ind2, ind_alph1] == 1 &
alpha[ind1:ind2, ind_alph2] == 0)
well_clone[size, "ba2"] <- sum(beta[ind1:ind2, ind_beta] == 1 &
alpha[ind1:ind2, ind_alph1] == 0 &
alpha[ind1:ind2, ind_alph2] == 1)
well_clone[size, "a1a2"] <- sum(beta[ind1:ind2, ind_beta] == 0 &
alpha[ind1:ind2, ind_alph1] == 1 &
alpha[ind1:ind2, ind_alph2] == 1)
well_clone[size, "ba1a2"] <- sum(beta[ind1:ind2, ind_beta] == 1 &
alpha[ind1:ind2, ind_alph1] == 1 &
alpha[ind1:ind2, ind_alph2] == 1)
well_clone[size, "none"] <- numb_sample[size] - sum(well_clone[size, 1:4])
}
binomial_coeff <- list()
for (i in 1:numb_distinct) {
binomial_coeff[[i]] <- choose(sample_size_well[i], 1:sample_size_well[i])
}
multinomial_coeff <- list()
for(i in 1:numb_distinct) {
cells_per_well <- sample_size_well[i]
multi_mat <- matrix(0, nrow = cells_per_well, ncol = cells_per_well)
for (j in 1:(cells_per_well-1)) {
for (k in 1:(cells_per_well - j)) {
multi_mat[j, k] <- multicool::multinom(c(j, k, sample_size_well[i] - j - k),
counts = TRUE)
}
}
multinomial_coeff[[i]] <- multi_mat
}
shared_LL <- dual_discrim_shared_likelihood(f1, f2, .15, numb_wells = well_clone, numb_cells = sample_size_well, binomials = binomial_coeff, multinomials = multinomial_coeff)
dual_LL <- stats::optimize(dual_discrim_dual_likelihood, interval = c(0, .4), err = .15, numb_wells = well_clone,
numb_cells = sample_size_well, binomials = binomial_coeff)
dual_LL_LL <- dual_LL$objective
dual_LL_freq <- dual_LL$minimum
rec <- rbind(rec, c(clon, ind_alph1, ind_alph2, shared_LL, dual_LL_LL, dual_LL_freq))
}
}
}
rec <- as.data.frame(rec)
rec <- dplyr::mutate(rec, diff = shared_LL - dual_LL)
filt_rec <- dplyr::filter(rec, diff > 10)
filt_rec <- dplyr::filter(filt_rec, shared_LL > 40 & shared_LL < 100)
dual_cand <- filt_rec[, c(1, 1:3), drop = FALSE]
names(dual_cand) <- c("beta1", "beta2", "alpha1", "alpha2")
dual_cand
} |
screen_abstracts_ui <- function(){
header <- shinydashboard::dashboardHeader(
tag("li",
list(
class = "dropdown",
uiOutput("selector_bar")
)
),
title = plotOutput("header")
)
sidebar <- shinydashboard::dashboardSidebar(
sidebarMenu(
id = "tabs",
menuItem("Data",
icon = shiny::icon("bar-chart-o"),
startExpanded = TRUE,
fileInput(
inputId = "data_in",
label = "Import",
multiple = TRUE
),
actionButton(
inputId = "save_data",
label = "Save Data",
width = "85%"
),
actionButton(
inputId = "clear_data",
label = "Clear Data",
width = "85%"
),
actionButton(
inputId = "exit_app",
label = "Exit App",
width = "85%"
),
br()
),
menuItem("Appearance",
icon = icon("paint-brush"),
selectInput("hide_names",
label = "Hide identifying information?",
choices = c("Yes" = "TRUE", "No" = "FALSE"),
multiple = FALSE
),
selectInput(
inputId = "hide_screened",
label = "Hide screened entries?",
choices = c("Yes" = "TRUE", "No" = "FALSE"),
multiple = FALSE
),
selectInput(
inputId = "order",
label = "Order citations by:",
choices = list(
"Random" = "random",
"Input" = "initial",
"Alphabetical" = "alphabetical",
"User-defined" = "user_defined"
)
),
uiOutput("column_selector"),
actionButton(
inputId = "order_result_go",
label = "Re-order",
width = "85%"
),
br()
)
)
)
body <- shinydashboard::dashboardBody(
revtools_css(),
fluidRow(
column(width = 1),
column(
width = 10,
tableOutput("citation"),
br(),
br(),
uiOutput(outputId = "render_notes_toggle"),
uiOutput(outputId = "render_notes")
),
column(width = 1)
)
)
return(
list(
header = header,
sidebar = sidebar,
body = body
)
)
} |
"N" <- 21
"r" <-
c(10, 23, 23, 26, 17, 5, 53, 55, 32, 46, 10, 8, 10, 8, 23, 0,
3, 22, 15, 32, 3)
"n" <-
c(39, 62, 81, 51, 39, 6, 74, 72, 51, 79, 13, 16, 30, 28, 45,
4, 12, 41, 30, 51, 7)
"x1" <-
c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1)
"x2" <-
c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1,
1) |
get_new_members <- function(page = 1, myAPI_Key){
API = 'congress'
query <- sprintf("members/new.json")
pp_query(query, API, page = page, myAPI_Key = myAPI_Key)
} |
cdc_rankedpairs <-
function(x, allow_dup = TRUE, min_valid = 1) {
method <- "rankedpairs"
if (min_valid < 1)
stop("Minimux number of min_valid is 1.")
if (!class(x)[1] %in% c("vote", "matrix", "condorcet"))
stop("x must be a vote, condorcet or matrix object.")
stopifnot(allow_dup %in% c(TRUE, FALSE))
CORE_M <- fInd_cdc_mAtrIx(x, dup_ok = allow_dup, available = min_valid)
message("EXTRACTING INFO")
class1 <- CORE_M$input_object
candidate <- CORE_M$candidate
candidate_num <- CORE_M$candidate_num
ballot_num <- CORE_M$ballot_num
valid_ballot_num <- CORE_M$valid_ballot_num
cdc_matrix <- CORE_M$cdc
dif_matrix <- CORE_M$dif
binary_m <- CORE_M$binary
message("SELECTING")
summary_m <- sUmmAry_101(x = binary_m, rname = candidate)
result_ID <- 0
message("------PAIRWISE")
win_side <- c()
lose_side <- c()
win_num <- c()
lose_num <- c()
pair_have_tie <- 0
for (i in 1:nrow(cdc_matrix)) {
for (j in 1:ncol(cdc_matrix)) {
if (i > j) {
ij <- cdc_matrix[i, j]
ji <- cdc_matrix[j, i]
if (ij >= ji) {
win_side <- append(win_side, candidate[i])
lose_side <- append(lose_side, candidate[j])
win_num <- append(win_num, ij)
lose_num <- append(lose_num, ji)
if (ij == ji)
pair_have_tie <- 1
} else if (ij < ji) {
win_side <- append(win_side, candidate[j])
lose_side <- append(lose_side, candidate[i])
win_num <- append(win_num, ji)
lose_num <- append(lose_num, ij)
}
}
}
}
tally <- data.frame(win_side, lose_side, win_num, lose_num, stringsAsFactors = FALSE)
if (pair_have_tie == 0)
result_ID <- 1
if (result_ID == 1) {
message("------SORTING")
tally_o <- order((-1) * tally[, 3], tally[, 4])
tally <- tally[tally_o, ]
nr_tally <- nrow(tally)
only_num_df <- tally[, c(3, 4)]
if (nr_tally == nrow(unique(only_num_df))) {
result_ID <- 2
} else {
BI_ZERO_ONE <- binary_m
BI_ZERO_ONE[BI_ZERO_ONE == -1] <- 0
re_tally <- RP_TIE_SOLVE(x = tally, zeroone = BI_ZERO_ONE)
if (re_tally[[1]] == TRUE) result_ID <- 2
tally <- re_tally[[2]]
}
}
if (result_ID == 2) {
message("------LOCKING IN")
name_m <- as.matrix(tally[, c(1, 2)])
the_source <- lock_winner(name_m, CAND = candidate)
winner <- the_source[[2]]
LOCK_IN <- the_source[[1]]
}
message("COLLECTING RESULT")
over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = ballot_num,
valid_ballot_num = valid_ballot_num, winner = NULL, input_object = class1, cdc = cdc_matrix,
dif = dif_matrix, binary = binary_m, summary_m = summary_m, other_info = NULL)
if (result_ID == 0) {
over$other_info <- list(failure = "Pairwise comparison has ties, i. e., the number of people who prefer i than j is equal to the number of people who prefer j than i.",
tally = tally, lock_in = NULL)
}
if (result_ID == 1) {
over$other_info <- list(failure = "There are unsolved ties when sorting the tally.", tally = tally, lock_in = NULL)
}
if (result_ID == 2) {
over$winner <- winner
over$other_info <- list(failure = "", tally = tally, lock_in = LOCK_IN)
}
class(over) <- "condorcet"
message("DONE")
return(over)
} |
power.analysis.subgroup = function(TE1, TE2, seTE1, seTE2, sd1, sd2, var1, var2, two.tailed = TRUE) {
gamma = abs(TE1 - TE2)
if (missing(var1)) {
if (missing(sd1)) {
var1 = (((TE1 - 1.96 * seTE1) - TE1)/-1.96)^2
var2 = (((TE2 - 1.96 * seTE2) - TE2)/-1.96)^2
varg = var1 + var2
} else {
var1 = sd1^2
var2 = sd2^2
varg = var1 + var2
}
} else {
varg = var1 + var2
}
ca_1tail = 1.64
ca_2tail = 1.96
onetail = (1 - pnorm(ca_1tail - (gamma/sqrt(varg))))
twotail = (1 - pnorm(ca_2tail - (gamma/sqrt(varg))) + pnorm(-ca_2tail - (gamma/sqrt(varg))))
if (two.tailed == TRUE) {
if (gamma > 1) {
gammas = (1:((gamma + 3) * 1000))/1000
powervec = vector()
for (i in 1:length(gammas)) {
powervec[i] = (1 - pnorm(ca_2tail - (gammas[i]/sqrt(varg))) + pnorm(-ca_2tail - (gammas[i]/sqrt(varg))))
}
} else {
gammas = (1:1000)/1000
powervec = vector()
for (i in 1:length(gammas)) {
powervec[i] = (1 - pnorm(ca_2tail - (gammas[i]/sqrt(varg))) + pnorm(-ca_2tail - (gammas[i]/sqrt(varg))))
}
}
plotdat = as.data.frame(cbind(gammas, powervec))
plot = ggplot(data = plotdat, aes(x = gammas, y = powervec)) + geom_line(color = "blue", size = 2) +
geom_point(aes(x = gamma, y = twotail), color = "red", size = 5) + theme_minimal() + geom_hline(yintercept = 0.8,
color = "black", linetype = "dashed") + ylab("Power") + xlab("Effect size difference")
plot(plot)
if (!is.na(plotdat[plotdat$powervec >= 0.8, ][1, 1])) {
cat("Minimum effect size difference needed for sufficient power: ", plotdat[plotdat$powervec >=
0.8, ][1, 1], " (input: ", gamma, ")", "\n", sep = "")
}
cat("Power for subgroup difference test (two-tailed): \n")
return(twotail)
} else {
if (gamma > 1) {
gammas = (1:((gamma + 3) * 1000))/1000
powervec = vector()
for (i in 1:length(gammas)) {
powervec[i] = (1 - pnorm(ca_1tail - (gammas[i]/sqrt(varg))))
}
} else {
gammas = (1:1000)/1000
powervec = vector()
for (i in 1:length(gammas)) {
powervec[i] = (1 - pnorm(ca_1tail - (gammas[i]/sqrt(varg))))
}
}
plotdat = as.data.frame(cbind(gammas, powervec))
plot = ggplot(data = plotdat, aes(x = gammas, y = powervec)) + geom_line(color = "blue", size = 2) +
geom_point(aes(x = gamma, y = onetail), color = "red", size = 5) + theme_minimal() + geom_hline(yintercept = 0.8,
color = "black", linetype = "dashed") + ylab("Power") + xlab("Effect size difference")
plot(plot)
if (!is.na(plotdat[plotdat$powervec >= 0.8, ][1, 1])) {
cat("Minimum effect size difference needed for sufficient power: ", plotdat[plotdat$powervec >=
0.8, ][1, 1], " (input: ", gamma, ")", "\n", sep = "")
}
cat("Power for subgroup difference test (one-tailed): \n")
return(onetail)
}
} |
nimbleFinalize <- function(extptr) {
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$RNimble_Ptr_ManualFinalizer, extptr))
}
cGetNRow <- function(cMV, compIndex = 1)
{
nRow = eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$getNRow, cMV$componentExtptrs[[compIndex]]))
return(nRow)
}
newObjElementPtr <- function(rPtr, name, dll){
eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$getModelObjectPtr, rPtr, name))
}
getNimValues <- function(elementPtr, pointDepth = 1, dll){
if(!inherits(elementPtr, "externalptr"))
return(NULL)
eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$Nim_2_SEXP, elementPtr, as.integer(pointDepth)) )
}
setNimValues <- function(elementPtr, values, pointDepth = 1, allowResize = TRUE, dll){
ptrExp <- substitute(elementPtr)
storage.mode(values) <- 'numeric'
if(!inherits(elementPtr, "externalptr"))
return(NULL)
jnk = eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$SEXP_2_Nim, elementPtr, as.integer(pointDepth), values, allowResize))
values
}
setPtrVectorOfPtrs <- function(accessorPtr, contentsPtr, length, dll) {
if(!inherits(accessorPtr, 'externalptr')) return(NULL)
if(!inherits(contentsPtr, 'externalptr')) return(NULL)
if(!is.numeric(length)) return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$setPtrVectorOfPtrs, accessorPtr, contentsPtr, as.integer(length)))
contentsPtr
}
setOnePtrVectorOfPtrs <- function(accessorPtr, i, contentsPtr, dll) {
if(!inherits(accessorPtr, 'externalptr')) return(NULL)
if(!is.numeric(i)) return(NULL)
if(!inherits(contentsPtr, 'externalptr')) return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$setOnePtrVectorOfPtrs, accessorPtr, as.integer(i-1), contentsPtr))
contentsPtr
}
setDoublePtrFromSinglePtr <- function(elementPtr, value, dll) {
if(!inherits(elementPtr, 'externalptr')) return(NULL)
if(!inherits(value, 'externalptr')) return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$setDoublePtrFromSinglePtr, elementPtr, value))
value
}
setSmartPtrFromSinglePtr <- function(elementPtr, value, dll) {
if(!inherits(elementPtr, 'externalptr')) return(NULL)
if(!inherits(value, 'externalptr')) return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$setSmartPtrFromSinglePtr, elementPtr, value))
value
}
setSmartPtrFromDoublePtr <- function(elementPtr, value, dll) {
if(!inherits(elementPtr, 'externalptr')) return(NULL)
if(!inherits(value, 'externalptr')) return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$setSmartPtrFromDoublePtr, elementPtr, value))
value
}
getDoubleValue <- function(elementPtr, pointDepth = 1, dll){
if(!inherits(elementPtr, "externalptr") )
return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$extract_double_2_SEXP, elementPtr, as.integer(pointDepth)))
}
setDoubleValue <- function(elementPtr, value, pointDepth = 1, dll){
if(!inherits(elementPtr, "externalptr"))
return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$populate_SEXP_2_double, elementPtr, as.integer(pointDepth), value))
value
}
getIntValue <- function(elementPtr, pointDepth = 1, dll){
if(!inherits(elementPtr, "externalptr") )
return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$extract_int_2_SEXP, elementPtr, as.integer(pointDepth)))
}
setIntValue <- function(elementPtr, value, pointDepth = 1, dll){
if(!inherits(elementPtr, "externalptr"))
return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$populate_SEXP_2_int, elementPtr, as.integer(pointDepth), value))
value
}
getBoolValue <- function(elementPtr, pointDepth = 1, dll){
if(!inherits(elementPtr, "externalptr") )
return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$extract_bool_2_SEXP, elementPtr, as.integer(pointDepth)))
}
setBoolValue <- function(elementPtr, value, pointDepth = 1, dll){
if(!inherits(elementPtr, "externalptr"))
return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$populate_SEXP_2_bool, elementPtr, as.integer(pointDepth), value))
value
}
setCharacterValue <- function(elementPtr, value, dll){
if(!inherits(elementPtr, "externalptr")) return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$populate_SEXP_2_string, elementPtr, value))
value
}
getCharacterValue <- function(elementPtr, dll){
if(!inherits(elementPtr, "externalptr") )
return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$extract_string_2_SEXP, elementPtr))
}
setCharacterVectorValue <- function(elementPtr, value, dll){
if(!inherits(elementPtr, "externalptr"))
return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$populate_SEXP_2_stringVector, elementPtr, value))
value
}
getCharacterVectorValue <- function(elementPtr, dll){
if(!inherits(elementPtr, "externalptr") )
return(NULL)
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$extract_stringVector_2_SEXP, elementPtr))
} |
c("Petal.Width", "Petal.Length")
library("wrapr")
qc(Petal.Width, Petal.Length)
iris[, qc(Petal.Width, Petal.Length)] %.>%
head(.)
OTHER_SYMBOL <- "Petal.Length"
qc(Petal.Width, OTHER_SYMBOL)
qc(Petal.Width, .(OTHER_SYMBOL))
qc(Petal.Width, c(OTHER_SYMBOL))
qc(a = b)
LEFT_NAME = "a"
qc(.(LEFT_NAME) := b) |
print.seerSet.summary<-function(x, ...) {
PY=year=NULL
cat(x$title)
print(x$d)
cat("Notes:\n")
for (i in 1:length(x$notes))
cat(i,") ",x$notes[i],"\n")
N=sum(x$P$PY)
tit=paste(N,"Million",ifelse(x$sex=="male","Male","Female"),"Person-Years")
p=qplot(year,PY,ylab="Person-Years (Millions)",main=tit,data=x$P)+
theme(axis.text=element_text(size=rel(2)),axis.title=element_text(size=rel(2)))
print(p)
} |
NULL
setGenotypeMarker = function(m, id, geno) {
pedlabels = attr(m, 'pedmembers')
id_int = match(id, pedlabels)
if (anyNA(id_int))
stop2("Unknown ID label: ", setdiff(id, pedlabels))
nid = length(id)
als = alleles(m)
if(length(geno) == 2 && all(geno %in% als) && !(isXmarker.marker(m) && nid == 2 && all(attr(m, "sex")[id_int] == 1)))
geno = paste(geno, collapse = "/")
ng = length(geno)
if(nid > 1 && ng == 1)
geno = rep(geno, nid)
else if(nid != ng)
stop2("When setting the genotype of multiple individuals, `geno` must have length either 1 or `length(id)`")
genoList = strsplit(as.character(geno), "/", fixed = TRUE)
lg = lengths(genoList)
empt = lg == 0
if(any(empt))
stop2("No alleles given for individual ", id[which(empt)])
bad = lg > 2
if(any(bad)) {
idx = which(bad)[1]
stop2(sprintf("Too many alleles given for individual '%s': ", id[idx]), genoList[[idx]])
}
short = lg == 1
if(isXmarker.marker(m))
short[attr(m, "sex")[id_int] == 1] = FALSE
if(any(short))
stop2("Only one allele given for individual ", id[which(short)])
genoList[lg == 1] = lapply(genoList[lg == 1], rep_len, 2)
gAls = unlist(genoList, use.names = FALSE)
gInt = match(gAls, als, nomatch = 0)
miss = gAls[gInt == 0]
unknown = setdiff(miss, c("0", "", "-", NA))
if(length(unknown) > 0) {
nm = attr(m, "name")
stop2(sprintf("Unknown allele for %s: ", ifelse(is.na(nm), "this marker", nm)) , unknown)
}
even = seq_len(nid) * 2
m[id_int, 1] = gInt[even - 1]
m[id_int, 2] = gInt[even]
m
}
setGenotype = function(x, marker = NULL, id, geno) {
if(is.null(marker))
marker = seq_len(nMarkers(x))
nma = length(marker)
nid = length(id)
if(nma != 1 && nid != 1)
stop2("Either `marker` or `id` must have length 1")
if(nma == 1 && nid == 1) {
if(is.pedList(x)) {
comp = getComponent(x, id, checkUnique = TRUE, errorIfUnknown = TRUE)
x[[comp]] = setGenotype(x[[comp]], marker = marker, id = id, geno = geno)
return(x)
}
midx = whichMarkers(x, markers = marker)
x$MARKERS[[midx]] = setGenotypeMarker(x$MARKERS[[midx]], id = id, geno = geno)
return(x)
}
if(nma == 1 ) {
if(length(geno) == 1)
geno = rep(geno, nid)
else if(length(geno) != nid)
stop("When setting the genotype of multiple individuals, `geno` must have length either 1 or `length(id)`")
if(is.pedList(x)) {
comp = getComponent(x, id, checkUnique = TRUE, errorIfUnknown = TRUE)
x[[comp]] = lapply(x[[comp]], function(y) {
idx = match(id, y$ID, nomatch = 0)
setGenotype(y, marker = marker, id = id[idx], geno = geno[idx])
})
return(x)
}
midx = whichMarkers(x, markers = marker)
x$MARKERS[[midx]] = setGenotypeMarker(x$MARKERS[[midx]], id = id, geno = geno)
return(x)
}
if(nid == 1) {
if(length(geno) == 1)
geno = rep(geno, nma)
else if(length(geno) != nma)
stop("When setting the genotype for multiple markers, `geno` must have length either 1 or `length(marker)`")
if(is.pedList(x)) {
comp = getComponent(x, id, checkUnique = TRUE, errorIfUnknown = TRUE)
x[[comp]] = setGenotype(x[[comp]], marker = marker, id = id, geno = geno)
return(x)
}
midx = whichMarkers(x, markers = marker)
x$MARKERS[[midx]] = lapply(seq_along(midx), function(k) {
m = x$MARKERS[[midx[k]]]
setGenotypeMarker(m, id = id, geno = geno[k])
})
return(x)
}
}
setAfreq = function(x, marker, afreq) {
if(missing(marker) || length(marker) == 0)
stop2("Argument `marker` cannot be empty")
if(length(marker) > 1)
stop2("Frequency replacement can only be done for a single marker")
if(is.pedList(x)) {
y = lapply(x, setAfreq, marker = marker, afreq = afreq)
return(y)
}
idx = whichMarkers(x, markers = marker)
m = x$MARKERS[[idx]]
als = alleles(m)
freqnames = names(afreq) %||% stop2("The frequency vector must be named with allele labels")
if(anyDuplicated.default(freqnames))
stop2("Duplicated alleles in frequency vector: ", afreq[duplicated(freqnames)])
if(length(miss <- setdiff(als, freqnames)))
stop2("Alleles missing from frequency vector: ", miss)
alsOrder = match(freqnames, als)
if(anyNA(alsOrder))
stop2("Unknown allele: ", freqnames[is.na(alsOrder)])
if(round(sum(afreq), 3) != 1)
stop2("Frequencies must sum to 1")
attr(m, "afreq") = as.numeric(afreq[alsOrder])
x$MARKERS[[idx]] = m
x
}
setMarkername = function(x, marker = NULL, name) {
if(is.pedList(x)) {
y = lapply(x, setMarkername, marker = marker, name = name)
return(y)
}
marker = marker %||% seq_markers(x)
if(length(marker) == 0)
stop2("Argument `marker` cannot be empty")
if(length(name) != length(marker))
stop2("Length of `name` must equal the number of markers")
if(!is.character(name))
stop2("Argument `name` must be a character vector")
if (any(dig <- suppressWarnings(name == as.integer(name)), na.rm = TRUE))
stop2("Marker name cannot consist entirely of digits: ", name[dig])
idx = whichMarkers(x, markers = marker)
mlist = x$MARKERS[idx]
x$MARKERS[idx] = lapply(seq_along(idx), function(i) `attr<-`(mlist[[i]], "name", name[i]))
checkDupNames(x)
x
}
setChrom = function(x, marker = NULL, chrom) {
if(is.pedList(x)) {
y = lapply(x, setChrom, marker = marker, chrom = chrom)
return(y)
}
marker = marker %||% seq_markers(x)
if(length(marker) == 0)
stop2("Argument `marker` cannot be empty")
chrom = as.character(chrom)
if(length(chrom) != length(marker))
if(length(chrom) == 1)
chrom = rep(chrom, length(marker))
else
stop2("Length of `chrom` must equal the number of markers")
idx = whichMarkers(x, markers = marker)
mlist = x$MARKERS[idx]
x$MARKERS[idx] = lapply(seq_along(idx), function(i) `attr<-`(mlist[[i]], "chrom", chrom[i]))
x
}
setPosition = function(x, marker = NULL, posMb) {
if(is.pedList(x)) {
y = lapply(x, setPosition, marker = marker, posMb = posMb)
return(y)
}
marker = marker %||% seq_markers(x)
if(length(marker) == 0)
stop2("Argument `marker` cannot be empty")
if(length(posMb) != length(marker))
stop2("Length of `posMb` must equal the number of markers")
pos = suppressWarnings(as.numeric(posMb))
bad = (!is.na(posMb) & is.na(pos)) | (!is.na(pos) & pos < 0)
if(any(bad))
stop2("`posMb` must contain nonnegative numbers or NA: ", posMb[bad])
idx = whichMarkers(x, markers = marker)
mlist = x$MARKERS[idx]
x$MARKERS[idx] = lapply(seq_along(idx), function(i) `attr<-`(mlist[[i]], "posMb", pos[i]))
x
} |
context("Test distribution names")
test_that("'distr2name()' is ok", {
expect_identical(distr2name(c("norm", "dnorm", "rhyper", "ppois", "toto")),
c("Gaussian", "Gaussian", "Hypergeometric", "Poisson", "toto"))
})
test_that("'name2distr()' is ok", {
expect_identical(name2distr(c("Cauchy", "Gaussian", "Generalized Extreme Value", "Toto")),
c("cauchy", "norm", "gev", "toto"))
}) |
context("PubMed")
test_that("GetPubMedByID can process books (
skip_on_cran()
if (httr::http_error("https://eutils.ncbi.nlm.nih.gov/"))
skip("Couldn't connect to Entrez")
test <- GetPubMedByID(c("24977996", "24921111"))
if (length(test))
expect_true(length(test) == 2L)
})
test_that("GetPubMedByID uses collective name if authors missing (
skip_on_cran()
if (httr::http_error("https://eutils.ncbi.nlm.nih.gov/"))
skip("Couldn't connect to Entrez")
Sys.sleep(2)
try_again(3, test <- GetPubMedByID(c(11678951, 15373863)))
if (length(test)){
authors <- unlist(test$author)
expect_true(length(authors) == 2L)
}
})
test_that("GetPubMedByID warns if authors missing (
skip_on_cran()
if (httr::http_error("https://eutils.ncbi.nlm.nih.gov/"))
skip("Couldn't connect to Entrez")
Sys.sleep(2)
BibOptions(check.entries = FALSE)
expect_warning(try_again(3, GetPubMedByID("7936917")))
})
test_that("LookupPubMedID successfully retrieves and add ID's'", {
skip_on_cran()
file.name <- system.file("Bib", "RJC.bib", package="RefManageR")
bib <- ReadBib(file.name)
if (httr::http_error("https://eutils.ncbi.nlm.nih.gov/"))
skip("Couldn't connect to Entrez")
Sys.sleep(2)
try_again(3, out <- LookupPubMedID(bib[[101:102]]))
expect_equal(length(out), 2L)
ids <- setNames(unlist(out$eprint), NULL)
expect_equal(ids, c("19381352", "19444335"))
Sys.sleep(2)
expect_message(try_again(3, LookupPubMedID(bib, 453)), "No PubMed ID's found")
})
test_that("GetPubMedByID reading of years/months (
skip_on_cran()
if (httr::http_error("https://eutils.ncbi.nlm.nih.gov/"))
skip("Couldn't connect to Entrez")
Sys.sleep(2)
try_again(3, bib <- GetPubMedByID("23891459"))
expect_equal(bib$year, "2013")
expect_equal(bib$month, "07")
}) |
.onLoad = function(lib, pkg) {
options(demo.ask = FALSE, example.ask = FALSE)
.ani.env$.ani.opts = list(
interval = 1, nmax = 50, ani.width = 480, ani.height = 480, ani.res = NA,
imgdir = 'images', ani.type = 'png', ani.dev = 'png', imgnfmt = "%d",
title = 'Animations Using the R Language',
description = paste('Animations generated in', R.version.string,
'using the package animation'),
verbose = TRUE, loop = TRUE, autobrowse = interactive(),
autoplay = TRUE, use.dev = TRUE
)
if (.Platform$OS.type != "windows")
{
if (Sys.which('ffmpeg')==''){
if(Sys.which('avconv')!=''){
ani.options(ffmpeg = "avconv")
} else {
ani.options(ffmpeg= "ffmpeg")
}
}
}
} |
fix.tpm <- function(x,K) {
y <- matrix(x,nrow=K,byrow=TRUE)
z <- exp(cbind(y,0))
z/apply(z,1,sum)
} |
"plotMassSpec" <-
function(multimodel, t, plotoptions)
{
m <- multimodel@modellist
resultlist <- multimodel@fit@resultlist
kinspecerr <- plotoptions@kinspecerr
superimpose <- plotoptions@superimpose
if(length(superimpose) < 1 || any(superimpose > length(m)))
superimpose <- 1:length(m)
allx2 <- allx <- vector()
for(i in 1:length(m)) {
allx2 <- append(allx2, m[[i]]@x2)
allx <- append(allx, m[[i]]@x)
}
specList <- list()
maxs <- mins <- maxspecdim <- 0
specList <- getSpecList(multimodel, t)
maxA <- lapply(specList, max)
maxs <- max(unlist(maxA)[superimpose])
minA <- lapply(specList, min)
mins <- min(unlist(minA)[superimpose])
maxspecdim <- max(unlist(lapply(specList, ncol))[superimpose])
if(dev.cur() != 1)
dev.new()
par(mgp = c(2, 1, 0), mar=c(0,0,0,0), oma = c(1,0,4,0),
mfrow=c( ceiling( ncol(specList[[1]]) / 2), 2))
if(ceiling( ncol(specList[[1]]) / 2)==1) par(mfrow=c(2,1))
xlim <- c(min(allx2),max(allx2))
ylim <- vector()
if(length(plotoptions@xlimspec) == 2)
xlim <- plotoptions@xlimspec
if(length(plotoptions@ylimspec) == 2)
ylim <- plotoptions@ylimspec
if(length(ylim) == 0)
ylim <- c(mins, maxs)
if(length(plotoptions@ylimspecplus) == 2)
ylim <- ylim + plotoptions@ylimspecplus
if (plotoptions@normspec)
ylim <- c(-1,1)
if(kinspecerr)
errtList <- getSpecList(multimodel, t, getclperr=TRUE)
plotted <- FALSE
for(i in 1) {
if(i %in% superimpose) {
if(kinspecerr) {
if(plotoptions@writeclperr)
write.table(errtList[[i]],
file=paste(plotoptions@makeps,
"_std_err_clp_", i, ".txt", sep=""),
quote = FALSE, row.names = m[[i]]@x2)
}
if (plotoptions@normspec) {
sp <- normdat(specList[[i]])
}
else
sp <- specList[[i]]
for(j in 1:ncol(sp)) {
if(kinspecerr)
plotCI(m[[i]]@x2, sp[,j],
uiw=errtList[[i]][,j],
main = "", xlab = plotoptions@xlab,
ylab="amplitude",
lty = 1,
col = j, sfrac = 0, type="l", gap = 0,
add = !(i == 1), labels = "")
else {
if(plotoptions@normspec) {
mm<-max( sp[,j] )
mi <- min(sp[,j])
ylim <- c(mi, mm)
}
names.side <- 0
if(j <= 2)
names.side <- 3
if(j >= (ncol(sp) - 1)) {
names.side <- 1
par(mar=c(2,0,0,0))
}
if(names.side != 0)
barplot3(sp[,j], col = j, border = j,
ylim = ylim, names.arg = m[[i]]@x2,
names.side = names.side,
names.by = [email protected],
axes=FALSE)
else
barplot3(sp[,j], col = j, border = j,
ylim = ylim, axes=FALSE)
}
}
}
if(length(plotoptions@title) != 0){
tit <- plotoptions@title
if(plotoptions@addfilename) tit <- paste(tit,m[[i]]@datafile)
}
else {
tit <- ""
if(plotoptions@addfilename) tit <- paste(tit, m[[i]]@datafile)
}
mtext(tit, side = 3, outer = TRUE, line = 1)
par(las = 2)
}
abline(0,0)
if (dev.interactive() && length(plotoptions@makeps) != 0) {
if(plotoptions@output == "pdf")
pdev <- pdf
else pdev <- postscript
dev.print(device=pdev,
file=paste(plotoptions@makeps, "_massspec.",
plotoptions@output, sep=""))
}
} |
territories_labels <- readr::read_csv(
"county_name, state_name, county_fips, state_fips, fips_class, lat, long, state_abbv
American Samoa, American Samoa, NA, 60, NA, 19.5, -90, AS
Guam, Guam, NA, 66, NA, 20, -100, GU
Mariana Islands, Mariana Islands, NA, 69, NA, 22, -78.5, MP
Puerto Rico, Puerto Rico, NA, 43, NA, 21, -94, PR
Virgin Islands, Virgin Islands, NA, 78, NA, 18, -81, VI",
col_types = cols(county_name = col_character(),
state_name = col_character(),
county_fips = col_character(),
state_fips = col_character(),
fips_class = col_character(),
lat = col_double(),
long = col_double(),
state_abbv = col_character()))
territories_labels_sf <- territories_labels %>%
sf::st_as_sf(coords = c("long", "lat")) %>%
sf::st_set_crs(4326) %>%
sf::st_transform(crs = 2163) %>%
select(-county_name, -fips_class, -county_fips) |
as.data.frame.summary.opticut <-
function(x, row.names = NULL, optional = FALSE, cut, sort, ...)
{
if (missing(cut))
cut <- getOption("ocoptions")$cut
if (missing(sort))
sort <- getOption("ocoptions")$sort
.summary_opticut(x, cut=cut, sort=sort)
} |
aux_lapL1 <- function(A){
E<-sum(A)/2
if (E==1){
return(array(0,c(1,1)))
} else {
ES<-function(p,q){
result<-0
if (q<=p)
{result<-NA}
else if(p==1)
result<-sum(A[p,1:q])
else
{
for(i in 1:(p-1))
{result<-result+sum(A[i,(i+1):ncol(A)])}
result<-result+sum(A[p,(p+1):q])
}
return(result)
}
Al<-matrix(0,nrow=E,ncol=E)
B<-list()
for(i in 1:(ncol(A)-1))
{for(j in (i+1):ncol(A))
{if (A[i,j]==1)
{n<-ES(i,j)
B[[n]]<-c(i,j)}
}
}
for(i in 1:(E-1))
{for(j in (i+1):E)
{if((B[[i]][1]==B[[j]][1])|(B[[i]][2]==B[[j]][1])|(B[[i]][2]==B[[j]][2]))
{Al[i,j]<-1
Al[j,i]=Al[i,j]
}
}
}
A2<-A%*%A
D1<-matrix(0,nrow=E,ncol=E)
for(r in 1:(ncol(A)-1))
{for(s in (r+1):ncol(A))
{ if (A[r,s]==1)
{m<-ES(r,s)
D1[m,m]<-A2[r,s]
}
}
}
Au<-matrix(0,nrow=E,ncol=E)
for(i in 1:(E-1))
{for(j in (i+1):E)
{if(((B[[i]][1]==B[[j]][1])&(A[B[[i]][2],B[[j]][2]]==1))|((B[[i]][2]==B[[j]][1])&(A[B[[i]][1],B[[j]][2]]==1))|((B[[i]][2]==B[[j]][2])&(A[B[[i]][1],B[[j]][1]]==1)))
{Au[i,j]<-1
Au[j,i]<-1
}
}
}
L1<-D1-Au+Al+2*diag(E)
return(L1)
}
} |
options(rmarkdown.html_vignette.check_title = FALSE)
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
set.seed(987202226)
cir_data <- runif(n = 30, min = 0, max = 2 * pi)
library(sphunif)
unif_test(data = cir_data, type = "Watson")
unif_test(data = cir_data, type = "Watson", p_value = "MC")
unif_test(data = cir_data, type = "Watson", p_value = "asymp")
avail_cir_tests
unif_test(data = cir_data, type = c("PAD", "Watson"))
set.seed(987202226)
theta <- runif(n = 30, min = 0, max = 2 * pi)
phi <- runif(n = 30, min = 0, max = pi)
sph_data <- cbind(cos(theta) * sin(phi), sin(theta) * sin(phi), cos(phi))
avail_sph_tests
unif_test(data = sph_data, type = "all", p_value = "MC", M = 1e3)
unif_test(data = sph_data, type = "Rayleigh", p_value = "asymp")
hyp_data <- r_unif_sph(n = 30, p = 10)
unif_test(data = hyp_data, type = "Rayleigh", p_value = "asymp")
data(venus)
head(venus)
nrow(venus)
venus$X <- cbind(cos(venus$theta) * cos(venus$phi),
sin(venus$theta) * cos(venus$phi),
sin(venus$phi))
unif_test(data = venus$X, type = c("PCvM", "PAD"), p_value = "asymp")
require(progress)
require(progressr)
handlers(handler_progress(
format = ":spin [:bar] :percent Total: :elapsedfull End \u2248 :eta",
clear = FALSE))
with_progress(
unif_test(data = venus$X, type = c("PCvM", "PAD"),
p_value = "MC", chunks = 1e2, M = 5e2, cores = 2)
)
samps_sph <- r_unif_sph(n = 30, p = 3, M = 10)
unif_stat(data = samps_sph, type = "all")
sim <- unif_stat_MC(n = 30, type = "all", p = 3, M = 1e4, cores = 2,
chunks = 10)
sim$crit_val_MC
head(sim$stats_MC)
pow <- unif_stat_MC(n = 30, type = "all", p = 3, M = 1e4, cores = 2,
chunks = 10, r_H1 = r_alt, crit_val = sim$crit_val_MC,
alt = "vMF", kappa = 1)
pow$power_MC
r_H1 <- function(n, p, M, l = 1) {
samp <- array(dim = c(n, p, M))
for (j in 1:M) {
samp[, , j] <- mvtnorm::rmvnorm(n = n, mean = c(l, rep(0, p - 1)),
sigma = diag(rep(1, p)))
samp[, , j] <- samp[, , j] / sqrt(rowSums(samp[, , j]^2))
}
return(samp)
}
pow <- unif_stat_MC(n = 30, type = "all", p = 3, M = 1e2, cores = 2,
chunks = 5, r_H1 = r_H1, crit_val = sim$crit_val_MC)
pow$power_MC
ht1 <- unif_test(data = samps_sph[, , 1], type = "Rayleigh",
p_value = "crit_val", crit_val = sim$crit_val_MC)
ht1
ht1$reject
ht2 <- unif_test(data = samps_sph[, , 1], type = "Rayleigh",
p_value = "MC", stats_MC = sim$stats_MC)
ht2
ht2$reject
unif_test(data = samps_sph[, , 1], type = "Rayleigh", p_value = "MC") |
library(testthat)
test_that("autotest", {
autotest_sdistribution(
sdist = ChiSquaredNoncentral,
pars = list(df = 8, location = 2),
traits = list(
valueSupport = "continuous",
variateForm = "univariate",
type = PosReals$new(zero = TRUE)
),
support = PosReals$new(zero = TRUE),
symmetry = "asymmetric",
mean = 10,
median = 9.2271,
variance = 24,
skewness = 0.9526,
exkur = 1.3333,
mgf = NaN,
cf = 0.0021 - 0.0179i,
pdf = dchisq(1:3, 8, 2),
cdf = pchisq(1:3, 8, 2),
quantile = qchisq(c(0.24, 0.42, 0.5), 8, 2)
)
})
test_that("manual", {
expect_equal(ChiSquaredNoncentral$new(df = 1, location = 1)$mgf(0.1), exp(0.1 / 0.8) / (0.8^0.5))
}) |
"_PACKAGE"
if (getRversion() >= "2.15.1") {
utils::globalVariables(c(
".",
"pd", "pd_nested", "pd_flat", "flattened_pd",
"line1", "line2", "col1", "col2", "parent",
"terminal", "text", "short",
"spaces", "lag_spaces",
"newlines", "lag_newlines",
"pos_id",
NULL
))
} |
NULL
budgets <- function(config = list()) {
svc <- .budgets$operations
svc <- set_config(svc, config)
return(svc)
}
.budgets <- list()
.budgets$operations <- list()
.budgets$metadata <- list(
service_name = "budgets",
endpoints = list("*" = list(endpoint = "https://budgets.amazonaws.com", global = TRUE), "cn-*" = list(endpoint = "budgets.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "budgets.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "budgets.{region}.sc2s.sgov.gov", global = FALSE)),
service_id = "Budgets",
api_version = "2016-10-20",
signing_name = "budgets",
json_version = "1.1",
target_prefix = "AWSBudgetServiceGateway"
)
.budgets$service <- function(config = list()) {
handlers <- new_handlers("jsonrpc", "v4")
new_service(.budgets$metadata, handlers, config)
} |
ABautopacf <-
function(behavior,phaseX,v,lags){
t1<-table(phaseX)
tmax<-t1[names(t1)==v]
start<-match(v,phaseX)
end<-tmax+start-1
tsx<-behavior[start:end]
e=length(tsx)
x=1:end
x<-ts(x,start=1,end=e,deltat=1)
graphics.off()
pacf1<-pacf(tsx,lag.max=lags,plot=FALSE,na.action=na.pass,type=c("correlation"))
b1<-pacf(tsx,lag.max=lags,plot=TRUE,na.action=na.pass)
print(pacf1)
print(b1)
} |
plotAllometry <- function(fit, size, logsz = TRUE,
method = c("PredLine", "RegScore", "size.shape", "CAC"), ...){
method <- match.arg(method)
n <- length(size)
if(n != fit$LM$n)
stop("Different number of observations between model fit and size.\n", call. = FALSE)
if(!is.numeric(size))
stop("The argument, size, must be a numeric vector.\n", call. = FALSE)
if(!is.vector(size))
stop("The argument, size, must be a numeric vector.\n", call. = FALSE)
dat <- fit$LM$data
Y <- fit$LM$Y
form <- if(logsz) as.formula(Y ~ log(size)) else as.formula(Y ~ size)
dat$size <- size
GM <- fit$GM
xc <- if(logsz) log(size) else size
if(method == "PredLine") {
if(logsz) out <- plot(fit, type = "regression",
reg.type = "PredLine",
predictor = log(size), ...) else
out <- plot(fit, type = "regression",
reg.type = "PredLine",
predictor = size, ...)
} else if(method == "RegScore") {
if(logsz) out <- plot(fit, type = "regression",
reg.type = "RegScore",
predictor = log(size), ...) else
out <- plot(fit, type = "regression",
reg.type = "RegScore",
predictor = size, ...)
} else
{
if(fit$LM$gls){
if(!is.null(fit$LM$weights))
fit <- lm.rrpp(form, data = dat, weights = fit$LM$weights,
iter = 0, print.progress = FALSE)
if(!is.null(fit$LM$Cov))
fit <- lm.rrpp(form, data = dat, Cov = fit$LM$Cov,
iter = 0, print.progress = FALSE)
} else {
fit <- lm.rrpp(form, data = dat, iter = 0, print.progress = FALSE)
}
f <- if(fit$LM$gls) fit$LM$gls.fitted else fit$LM$fitted
b <- as.matrix(lm(f ~ xc)$coefficients)[2,]
y <- fit$LM$Y
a <- crossprod(center(y), xc)/sum(xc^2)
a <- a/sqrt(sum(a^2))
r <- center(y)
CAC <- r%*%a
p <- fit$LM$p
resid <- r%*%(diag(p) - tcrossprod(a))
RSC <- prcomp(resid)$x
Reg.proj <- r %*% b %*% sqrt(1/crossprod(b))
PCA <- prcomp(cbind(y, xc))
PC.points <-PCA$x
if(method == "CAC") {
par(mfcol = c(1,2))
plot.args <- list(x = xc, y = CAC,
xlab = if(logsz) "log(Size)" else "Size",
ylab = "CAC", ...)
plot2.args <- list(x = CAC, y = RSC[, 1],
xlab = "CAC", ylab = "RSC1", ...)
do.call(plot, plot.args)
do.call(plot, plot2.args)
par(mfcol = c(1,1))
out <- list(CAC = CAC, RSC = RSC, plot.args = plot.args,
all.plot.args = list(CAC=plot.args, RSC = plot2.args))
}
if(method == "size.shape") {
v <- round(PCA$sdev^2/sum(PCA$sdev^2) * 100, 2)
plot.args <- list(x = PC.points[,1], y = PC.points[,2],
xlab = paste("PC 1: ", v[1], "%", sep = ""),
ylab = paste("PC 2: ", v[2], "%", sep = ""),
...)
do.call(plot, plot.args)
title("Size-Shape PC plot")
out <- list(size.shape.PCA = PCA,
PC.points = PC.points, plot.args = plot.args)
}
}
out$size.var <- xc
out$logsz <- logsz
out$GM <- GM
class(out) <- "plotAllometry"
invisible(out)
} |
td_priceQuote = function(tickers = c('AAPL','MSFT'), output = 'df', accessToken=NULL) {
if (output != 'df') {
quotes = ram_quote_list(tickers, accessToken)
} else {
quotes = ram_quote_df(tickers, accessToken)
}
quotes
}
td_priceHistory = function(tickers=c('AAPL','MSFT'),startDate=Sys.Date()-30,endDate=Sys.Date(),
freq=c('daily','1min','5min','10min','15min','30min'),
accessToken=NULL){
if (length(tickers)>15) {
tickers = tickers[1:15]
warning('More than 15 tickers submitted. Only the first 15 tickers were pulled from the list of tickers.')
}
if (missing(freq)) freq='daily'
allTickers = dplyr::bind_rows(lapply(tickers,function(x) ram_history_single(ticker = x,
startDate,
endDate,
freq,
accessToken=accessToken)))
allTickers
}
ram_history_single = function(ticker='AAPL',startDate=Sys.Date()-30,endDate=Sys.Date(),
freq=c('daily','1min','5min','10min','15min','30min'),
accessToken=NULL){
accessToken = ram_accessToken(accessToken)
date_time <- volume <- NULL
startDate = as.Date(startDate)+lubridate::days(1)
endDate = as.Date(endDate)+lubridate::days(1)
old <- options()
on.exit(options(old))
options(scipen=999)
if (missing(freq)) freq='daily'
startDateMS = as.character(as.numeric(lubridate::as_datetime(startDate, tz='America/New_York'))*1000)
endDateMS = as.character(as.numeric(lubridate::as_datetime(endDate, tz='America/New_York'))*1000)
if (freq=='daily') {
PriceURL = paste0('https://api.tdameritrade.com/v1/marketdata/',ticker,
'/pricehistory','?periodType=month&frequencyType=daily',
'&startDate=',startDateMS,'&endDate=',endDateMS)
} else {
PriceURL = paste0('https://api.tdameritrade.com/v1/marketdata/',ticker,
'/pricehistory','?periodType=day&frequency=',
gsub('min','',freq),'&startDate=',startDateMS,'&endDate=',endDateMS)
}
tickRequest = httr::GET(PriceURL,ram_headers(accessToken))
ram_status(tickRequest)
tickHist <- httr::content(tickRequest, as = "text")
tickHist <- jsonlite::fromJSON(tickHist)
tickHist <- tickHist[["candles"]]
if (class(tickHist)=='list') return()
tickHist$ticker = ticker
tickHist$date_time = lubridate::as_datetime(tickHist$datetime/1000, tz='America/New_York')
tickHist$date = as.Date(tickHist$date_time)
tickHist = dplyr::select(tickHist,ticker,date,date_time,open:volume)
dplyr::as_tibble(tickHist)
}
ram_quote_list = function(tickers = c('AAPL','MSFT'), accessToken=NULL) {
accessToken = ram_accessToken(accessToken)
quoteURL = base::paste0('https://api.tdameritrade.com/v1/marketdata/quotes?symbol=',
paste0(tickers, collapse = '%2C'))
quotes = httr::GET(quoteURL,ram_headers(accessToken))
ram_status(quotes)
httr::content(quotes)
}
ram_quote_df = function(tickers = c('AAPL','MSFT'),accessToken=NULL) {
quoteList = ram_quote_list(tickers,accessToken)
dplyr::bind_rows(lapply(quoteList,data.frame)) %>%
dplyr::as_tibble()
} |
context("CCA Multi")
test_that("cca works for population", {
data(population)
expect_equivalent(length(table(cca(population, s=1, mode=1))), 429)
})
test_that("cca works for population mode 3", {
data(population)
expect_equivalent(length(table(cca(population, s=10, mode=3))), 15)
}) |
knitr::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE)
library(httr)
library(dplyr)
library(stringr)
getBills <- function(key,congress,branch,type,numFrom, numTo) {
get_url <- paste('https://api.propublica.org/congress/v1/',congress, '/',branch,'/bills/',type,'.json', sep="" )
listofdfs <- list()
x=c()
first_20 <- GET(get_url,
add_headers(`X-API-Key` = key))
ft_pr <- content(first_20, 'parsed')
ft_res1 <- ft_pr$results
ft_res2 <- ft_res1[[1]]
ft_res3 <- ft_res2$bills
ft_res4 <- data.frame(do.call(rbind, ft_res3), stringsAsFactors=FALSE)
for(i in numFrom:numTo) {
if ((i %% 20) ==0) {
url <- paste(get_url,'?offset=', i,sep="")
r <- GET(url,
add_headers(`X-API-Key` = key))
pr <- content(r, 'parsed')
t1 <- pr$results
t2 <- t1[[1]]
t3 <- t2$bills
listofdfs[[i]] <- t3
df_name <- paste("df", i, sep="_")
assign(df_name,listofdfs[[i]])
df1_name <- paste("df1", i, sep="_")
assign(df1_name, data.frame(do.call(rbind, listofdfs[[i]]), stringsAsFactors=FALSE))
x=append(x,df1_name)
}
}
x1 <- do.call(rbind, mget(x))
x2 <- rbind(ft_res4,x1)
x3 <- lapply(x2, function(x) ifelse(x=="NULL", NA, x))
x4 <- lapply(x3, function(x) as.character((unlist(x))))
x5 <- as.data.frame(do.call(cbind, x4))
return(x5)
} |
Sys.setenv(TZ = "GMT")
require(blotter)
require(testthat)
port = "testBreak"
acct = "testBreak"
symbol = c("IBM")
data(IBM)
startDate = first(index(IBM))
endDate = last(index(IBM))
lines = "date,shrs,price,symbol
2007-01-10,100,98.0,IBM
2007-01-16,-200,99.5,IBM
2007-01-17,150,99.45,IBM
2007-01-18,-50,99.0,IBM"
con = textConnection(lines)
tt.trades = read.csv(con, as.is = TRUE)
tt.trades[,"date"] = make.time.unique(as.POSIXct(tt.trades[,"date"]))
currency("USD")
stock(symbol,"USD")
initPortf(port,
symbol,
initDate = startDate)
initAcct(port,
portfolios = c(port),
initDate = startDate,
initEq=10^6)
for(i in 1:nrow(tt.trades)){
addTxn(port,Symbol = tt.trades[i,"symbol"],
TxnDate = tt.trades[i,"date"],
TxnPrice = tt.trades[i,"price"],
TxnQty = tt.trades[i,"shrs"])
}
updatePortf(port)
updateAcct(acct)
updateEndEq(acct) |
library(lamW)
shiehpow <- function(n, m, p, alpha=.05, dist, sides="two.sided")
{
if(!(dist %in% c("exp", "norm", "dexp")))
{
stop('dist must be equal to "exp", "norm", or "dexp."')
}
if(sides == "two.sided"){test_sides <- "Two-sided"}
if(sides == "one.sided"){test_sides <- "One-sided"}
N=m+n
np<-length(p)
nn<-length(n)
tht = vector(length=length(p))
muo=vector(length=length(n))
mu=matrix(0,nrow=length(p),ncol=length(n))
sigo=vector(length=length(n))
p2=vector(length=length(p))
p3=vector(length=length(p))
sig=matrix(0,nrow=length(p),ncol=length(n))
p1=vector(length=length(p))
power <- matrix(0,nrow=np,ncol=nn)
for(i in 1:np) {
for(j in 1:nn) {
if (dist == "exp"){
if(p[i] >= .5) {
tht[i]= -log(2*(1-p[i]))
p1[i] <- p[i]
}
else if (p[i] < .5) {
p1[i] <- 1 - p[i]
tht[i]= -log(2*(1-p1[i]))
}
p2[i]= 1-(2/3)*exp(-tht[i])
p3[i]= 1-exp(-tht[i]) + (1/3)*exp(-2*tht[i])
}
if(dist=="norm"){
if(p[i] >= .5) {
tht[i]= sqrt(2)*qnorm(p[i])
p1[i] <- p[i]
}
else if (p[i] < .5) {
p1[i] <- 1 - p[i]
tht[i]= sqrt(2)*qnorm(p1[i])
}
p2[i]= mean((pnorm(rnorm(100000)+tht[i]))^2)
p3[i]= p2[i]
}
if(dist=="dexp"){
if(p[i] >= .5) {
tht[i]= (-lamW::lambertWm1(4*(p[i]-1)/(exp(1)^2))) -2
p1[i] <- p[i]
}
else if (p[i] < .5) {
p1[i] <- 1 - p[i]
}
tht[i]= (-lamW::lambertWm1(4*(p1[i]-1)/(exp(1)^2)))-2
p2[i]= 1-(7/12 + tht[i]/2)*exp(-tht[i]) -(1/12)*exp(-2*tht[i])
p3[i]= p2[i]
}
N[j]= m[j]+n[j]
muo[j]= m[j]*n[j]/2
mu[i,j]= (m[j])*(n[j])*p1[i]
sigo[j]= sqrt(m[j]*n[j]*(m[j]+n[j]+1)/12)
sig[i,j]=sqrt(m[j]*n[j]*p1[i]*(1-p1[i]) + m[j]*n[j]*(n[j]-1)*(p2[i]-(p1[i])^2) + m[j]*n[j]*(m[j]-1)*(p3[i]-(p1[i])^2))
za1<-qnorm(alpha,lower.tail=F)
za2<-qnorm(alpha/2,lower.tail=F)
power[i,j]<-pnorm((mu[i,j]-muo[j]-za2*sigo[j])/sig[i,j]) + pnorm((-mu[i,j]+muo[j]-za2*sigo[j])/sig[i,j])
if (sides=="one.sided") {
power[i,j]<-pnorm((mu[i,j]-muo[j]-za1*sigo[j])/sig[i,j])
}
}
}
wmw_odds <- round(p/(1-p),3)
cat("Distribution: ", dist, "\n",
"Sample sizes: ", n, " and ", m, "\n",
"p: ", p, "\n",
"WMW odds: ", wmw_odds, "\n",
"sides: ", test_sides, "\n",
"alpha: ", alpha, "\n\n",
"Shieh Power: ", round(power,3),sep = "")
output_list <- list(distribution = dist,n = n, m = m, p = p, wmw_odds = wmw_odds,
alpha = alpha, test_sides = test_sides, power = round(power,3))
} |
test_that("Test whether the voxel and object function works", {
data("pc_tree")
pc <- pc_tree
to_test <- voxels(pc_tree, edge_length = c(5, 5, 5))
expect_equal(length(to_test), 3, info = "Length of the object")
expect_equal(nrow(to_test$cloud), nrow(pc), info = "Identity of the cloud")
expect_equal(length(to_test$parameter), 3, info = "Parameter of voxels")
expect_equal(ncol(to_test$voxels), 4, info = "Columns of voxels")
expect_equal(nrow(to_test$voxels), 6, info = "n of voxels")
expect_equal(min(to_test$voxels$X), (min(pc$X) + 2.5), info = "X cordinate of voxels")
expect_equal(min(to_test$voxels$Y), (min(pc$Y) + 2.5), info = "Y cordinate of voxels")
expect_equal(min(to_test$voxels$Z), (min(pc$Z) + 2.5), info = "Z cordinate of voxels")
expect_equal(sum(to_test$voxels$N), nrow(pc), info = "Total point in voxels")
})
test_that("Test whether the voxel function works", {
data("pc_tree")
pc <- pc_tree
to_test <- voxels(pc_tree, edge_length = c(5, 5, 5), obj.voxels = FALSE)
expect_equal(ncol(to_test), 4, info = "Columns of voxels")
expect_equal(nrow(to_test), 6, info = "n of voxels")
expect_equal(min(to_test$X), (min(pc$X) + 2.5), info = "X cordinate of voxels")
expect_equal(min(to_test$Y), (min(pc$Y) + 2.5), info = "Y cordinate of voxels")
expect_equal(min(to_test$Z), (min(pc$Z) + 2.5), info = "Z cordinate of voxels")
expect_equal(sum(to_test$N), nrow(pc), info = "Total point in voxels")
}) |
rowDiffs <- function(x, rows = NULL, cols = NULL,
lag = 1L, differences = 1L, dim. = dim(x), ..., useNames = NA) {
.Call(C_rowDiffs, x, dim., rows, cols, lag, differences, TRUE, useNames)
}
colDiffs <- function(x, rows = NULL, cols = NULL,
lag = 1L, differences = 1L, dim. = dim(x), ..., useNames = NA) {
.Call(C_rowDiffs, x, dim., rows, cols, lag, differences, FALSE, useNames)
} |
MakeRelationship <- function(ped, counseland.id){
iid <- ped[,"indID"]
fid <- ped[,"fatherID"]
mid <- ped[,"motherID"]
gender <- ped[,"gender"]
relationship <- rep(0,nrow(ped))
current.id <- counseland.id
indiv <- iid == current.id
relationship[indiv] <- 1
sibs <- NULL
nep <- NULL
spouse.id <- NULL
potent.spouse.id <- NULL
if (sum(indiv)!=0){
if (fid[indiv] !=0 ){
relationship[iid == fid[indiv]] <- 4
sibs <- c(sibs, which(fid == fid[indiv] & !indiv))
}
if (mid[indiv]!=0 ){
relationship[iid == mid[indiv]] <- 4
sibs <- c(sibs, which(mid == mid[indiv] & !indiv))
}
if (length(unique(sibs))!=0){
relationship[unique(sibs)] <- 2
for (i in 1:length(unique(sibs))){
nep <- c(nep,which(fid==iid[unique(sibs)[i]]|mid==iid[unique(sibs)[i]]))
}
if (sum(nep)!=0)
relationship[unique(nep)] <- 5
}
}
if(sum(indiv)!=0){
if (gender[indiv]==0){
relationship[mid==iid[indiv]] <- 3
child <- which(mid==iid[indiv])
if (sum(child)!=0){
spouse.id <- unique(fid[child])
if (sum(spouse.id)!=0){
for (i in 1:length(spouse.id)){
relationship[iid==spouse.id[i]] <- 6
}
}
}
}else {
relationship[fid==iid[indiv]] <- 3
child <- which(fid==iid[indiv])
if (sum(child)!=0){
spouse.id <- unique(mid[child])
if (sum(spouse.id)!=0){
for ( i in 1:length(spouse.id)){
relationship[iid==spouse.id[i]] <- 6
}
}
}
}
}
gcid <- is.element(fid, iid[relationship==3]) | is.element(mid, iid[relationship==3])
relationship[gcid] <- 15
if (sum(gcid)!=0) {
child.spouse.id <- unique(c(fid[gcid],mid[gcid]))
if (sum(child.spouse.id)!=0){
for ( i in 1:length(child.spouse.id)){
indiv <- iid==child.spouse.id[i]
if (sum(indiv)!=0){
if (relationship[indiv]==0) relationship[indiv] <- 14
}
}
}
}
current.fid <- fid[indiv]
current.mid <- mid[indiv]
indiv <- iid==current.fid
if(sum(indiv, na.rm=TRUE)!=0) {
if (fid[indiv]!=0){
relationship[iid==fid[indiv]] <- 8
relationship[fid==fid[indiv] & !indiv] <- 9
}
if (mid[indiv]!=0){
relationship[iid==mid[indiv]] <- 8
relationship[mid==mid[indiv] & !indiv] <- 9
}
cid <- is.element(fid, iid[relationship==9]) | is.element(mid, iid[relationship==9])
relationship[cid] <- 10
}
indiv <- iid==current.mid
if(sum(indiv, na.rm=TRUE)!=0){
if (fid[indiv] != 0){
relationship[iid==fid[indiv]] <- 11
relationship[fid==fid[indiv] & !indiv] <- 12
}
if (mid[indiv] !=0){
relationship[iid==mid[indiv]] <- 11
relationship[mid==mid[indiv] & !indiv] <- 12
}
cid <- is.element(fid, iid[relationship==12]) | is.element(mid, iid[relationship==12])
relationship[cid] <- 13
}
if (sum(nep)!=0)
potent.spouse.id <- unique(c(fid[nep],mid[nep]))
if (sum(potent.spouse.id)!=0){
for ( i in 1:length(potent.spouse.id)){
indiv <- iid==potent.spouse.id[i]
if (sum(indiv)!=0){
if (relationship[indiv]==0){
relationship[indiv] <- 7
}
}
}
}
cousin <- which(relationship==10 | relationship == 13)
if (sum(cousin)!=0) {
uncle.spouse.id <- unique(c(fid[cousin],mid[cousin]))
if (sum(uncle.spouse.id)!=0){
for ( i in 1:length(uncle.spouse.id)){
indiv <- iid==uncle.spouse.id[i]
if (sum(indiv)!=0){
if (relationship[indiv]==0){
relationship[indiv] <- 16
}
}
}
}
}
return(relationship)
}
|
complexdiv <- function(a,b) {
if( is.numeric(b) && is.complex(a) ) {
z <- complex(real=Re(a)/b, imaginary=Im(a)/b)
} else if( is.complex(b) && is.complex(a) ) {
tmp <- complex(real=1,imaginary=2)/complex(real=0,imaginary=0)
badcdiv <- is.nan(Re(tmp)) && is.nan(Im(tmp))
z <- a/b
if( badcdiv ) {
if( any(b == 0) ) {
j <- which(b==0)
z[j] <- complex(real=Re(a[j])/0, imaginary=Im(a[j])/0)
}
if( any(is.infinite(b)) ) {
j <- which(is.infinite(b))
z[j] <- complex(real=0, imaginary=0)
}
}
} else z <- a/b
z
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(blaise)
model1 = "
DATAMODEL Test
FIELDS
A : STRING[1]
B : INTEGER[1]
C : REAL[3,1]
D : REAL[3]
E : (Male, Female)
F : 1..20
G : 1.00..100.00
ENDMODEL
"
model2 = "
DATAMODEL Test
FIELDS
A : STRING[1]
B : INTEGER[1]
C : REAL[3,1]
D : REAL[3]
E : (Male (1), Female (2), Unknown (9))
F : 1..20
G : 1.00..100.00
ENDMODEL
"
data1 =
"A12.30.11 1 1.00
B23.41.2210 20.20
C34.50.0120100.00"
data2 =
"A12,30,11 1 1,00
B23,41,2210 20,20
C34,50,0920100,00"
blafile1 = tempfile('testbla1', fileext = '.bla')
datafile1 = tempfile('testdata1', fileext = '.asc')
blafile2 = tempfile('testbla2', fileext = '.bla')
datafile2 = tempfile('testdata2', fileext = '.asc')
writeLines(data1, con = datafile1)
writeLines(model1, con = blafile1)
writeLines(data2, con = datafile2)
writeLines(model2, con = blafile2)
df = read_fwf_blaise(datafile1, blafile1)
df
df_comma = read_fwf_blaise(datafile2, blafile2)
df_comma
readr::problems(df_comma)
df_comma = read_fwf_blaise(datafile2, blafile2, locale = readr::locale(decimal_mark = ","))
df_comma
df_enum = read_fwf_blaise(datafile2, blafile2, locale = readr::locale(decimal_mark = ","), numbered_enum = FALSE)
df_enum
df_laf = read_fwf_blaise(datafile1, blafile1, output = "laf")
df_laf
df_laf$E
outfile = tempfile(fileext = ".asc")
outbla = sub(".asc", ".bla", outfile)
write_fwf_blaise(df, outfile)
readr::read_lines(outfile)
readr::read_lines(outbla)
outfile_model = tempfile(fileext = ".asc")
write_fwf_blaise_with_model(df_enum, outfile_model, blafile2)
readr::read_lines(outfile_model)
model3 = "
DATAMODEL Test
FIELDS
A : (A, B, C)
B : (Male (1), Female (2), Unknown (3))
ENDMODEL
"
blafile3 = tempfile('testbla3', fileext = '.bla')
writeLines(model3, con = blafile3)
outfile_new_model = tempfile(fileext = ".asc")
write_fwf_blaise_with_model(df_enum, outfile_new_model, blafile3)
readr::read_lines(outfile_new_model)
model4 = "
DATAMODEL Test
FIELDS
A : (A, B)
B : (Male (1), Female (2))
ENDMODEL
"
blafile4 = tempfile('testbla4', fileext = '.bla')
writeLines(model4, con = blafile4)
outfile_wrong_model = tempfile(fileext = ".asc")
write_fwf_blaise_with_model(df_enum, outfile_wrong_model, blafile4) |
NULL
total_covar_matrix <- function(ci,entry,delta){
simpleci<- simple_ci(ci)
submatrix <- ci_submatrix(simpleci)
rows <- unique(c(submatrix$A,submatrix$C))
cols <- unique(c(submatrix$B,submatrix$C))
ind <- integer(0)
if(ci$order[entry[1]] %in% rows){ind <- which(cols == ci$order[entry[2]])}
if(ci$order[entry[2]] %in% rows){ind <- c(ind,which(cols == ci$order[entry[1]]))}
ind <- unique(ind)
if(identical(ind,integer(0))){return(matrix(1,nrow = nrow(ci$covariance), ncol = ncol(ci$covariance)))}else{
covar <- matrix(delta,nrow = nrow(ci$covariance), ncol = ncol(ci$covariance))
covar[entry[1],entry[2]] <- 1
covar[entry[2],entry[1]] <- 1
return(covar)}
}
col_covar_matrix <- function(ci,entry,delta){
covar <- matrix(1,nrow = nrow(ci$covariance), ncol = ncol(ci$covariance))
simpleci<- simple_ci(ci)
submatrix <- ci_submatrix(simpleci)
rows <- unique(c(submatrix$A,submatrix$C))
cols <- unique(c(submatrix$B,submatrix$C))
temp <- matrix(1,nrow = length(rows), ncol = length(cols))
ind <- integer(0)
if(ci$order[entry[1]] %in% rows){ind <- which(cols == ci$order[entry[2]])}
if(ci$order[entry[2]] %in% rows){ind <- c(ind,which(cols == ci$order[entry[1]]))}
ind <- unique(ind)
if(identical(ind,integer(0))){return(covar)}else{
while(length(ind)>0){
for(k in 1:length(ind)){
for (i in 1:length(rows)){
temp[i,ind[k]] <- delta
if(rows[i] %in% cols & cols[ind[k]] %in% rows) {temp[which(cols[ind[k]]==rows),which(cols == rows[i])] <- delta}
}
}
check <- c()
ind <- c()
for (i in 1: length(cols)){
check[i] <- sum(temp[,i]== delta)
if(check[i] > 0 & check[i] < length(rows)){ind <- c(ind,i)}
}
}
for(i in 1:nrow(covar)){
for(j in 1:ncol(covar)){
ind <- c(which(ci$order[i]==rows),which(ci$order[j]==cols))
if(length(ind) == 2){
if(temp[ind[1],ind[2]] == delta){
covar[i,j] <- delta; covar[j,i] <- delta
}
}
}
}
covar[entry[1],entry[2]] <- 1
covar[entry[2],entry[1]] <- 1
return(covar)}
}
partial_covar_matrix <- function(ci, entry, delta){
covar <- matrix(1,nrow = nrow(ci$covariance), ncol = ncol(ci$covariance))
simpleci<- simple_ci(ci)
submatrix <- ci_submatrix(simpleci)
rows <- unique(c(submatrix$A,submatrix$C))
cols <- unique(c(submatrix$B,submatrix$C))
ind <- integer(0)
if(ci$order[entry[1]] %in% rows){ind <- which(cols == ci$order[entry[2]])}
if(ci$order[entry[2]] %in% rows){ind <- c(ind,which(cols == ci$order[entry[1]]))}
ind <- unique(ind)
if(identical(ind,integer(0))){return(covar)}else{
for(i in 1:length(ci$order)){
for(j in 1:length(ci$order)){
if(ci$order[i] %in% rows & ci$order[j] %in% cols){
covar[i,j] <- delta
covar[j,i] <- delta
}
}
}
covar[entry[1],entry[2]] <- 1
covar[entry[2],entry[1]] <- 1
return(covar)}
}
row_covar_matrix <- function(ci, entry, delta){
covar <- matrix(1,nrow = nrow(ci$covariance), ncol = ncol(ci$covariance))
simpleci<- simple_ci(ci)
submatrix <- ci_submatrix(simpleci)
rows <- unique(c(submatrix$A,submatrix$C))
cols <- unique(c(submatrix$B,submatrix$C))
temp <- matrix(1,nrow = length(rows), ncol = length(cols))
ind <- integer(0)
if(ci$order[entry[1]] %in% cols){ind <- which(rows == ci$order[entry[2]])}
if(ci$order[entry[2]] %in% cols){ind <- c(ind,which(rows == ci$order[entry[1]]))}
ind <- unique(ind)
if(identical(ind,integer(0))){return(covar)}else{
while(length(ind)>0){
for(k in 1:length(ind)){
for (i in 1:length(cols)){
temp[ind[k],i] <- delta
if(cols[i] %in% rows & rows[ind[k]] %in% cols) {temp[which(rows == cols[i]),which(rows[ind[k]]==cols)] <- delta}
}
}
check <- c()
ind <- c()
for (i in 1: length(rows)){
check[i] <- sum(temp[i,]== delta)
if(check[i] > 0 & check[i] < length(cols)){ind <- c(ind,i)}
}
}
for(i in 1:nrow(covar)){
for(j in 1:ncol(covar)){
ind <- c(which(ci$order[i]==rows),which(ci$order[j]==cols))
if(length(ind) == 2){
if(temp[ind[1],ind[2]] == delta){
covar[i,j] <- delta; covar[j,i] <- delta
}
}
}
}
covar[entry[1],entry[2]] <- 1
covar[entry[2],entry[1]] <- 1
return(covar)}
} |
renv_check_unknown_source <- function(records, project = NULL) {
if (empty(records))
return(TRUE)
if (renv_tests_running())
records$renv <- NULL
unknown <- filter(records, function(record) {
source <- renv_record_source(record)
if (source != "unknown")
return(FALSE)
localpath <- tryCatch(
renv_retrieve_cellar_find(record, project),
error = function(e) ""
)
if (file.exists(localpath))
return(FALSE)
TRUE
})
if (empty(unknown))
return(TRUE)
if (!renv_tests_running())
renv_warnings_unknown_sources(unknown)
FALSE
} |
make_network <- function(physeq, type="samples", distance="jaccard", max.dist = 0.4,
keep.isolates=FALSE, ...){
if( type %in% c("taxa", "species", "OTUs", "otus", "otu")){
if( class(distance) == "dist" ){
obj.dist <- distance
if( attributes(obj.dist)$Size != ntaxa(physeq) ){
stop("ntaxa(physeq) does not match size of dist object in distance")
}
if( !setequal(attributes(obj.dist)$Labels, taxa_names(physeq)) ){
stop("taxa_names does not exactly match dist-indices")
}
} else if( class(distance) == "character" ){
obj.dist <- distance(physeq, method=distance, type=type, ...)
} else {
if( !taxa_are_rows(physeq) ){ physeq <- t(physeq) }
obj.dist <- distance(as(otu_table(physeq), "matrix"))
}
TaDiMa <- as.matrix(obj.dist)
TaDiMa <- TaDiMa + diag(Inf, ntaxa(physeq), ntaxa(physeq))
CoMa <- TaDiMa < max.dist
} else if( type == "samples" ){
if( class(distance) == "dist" ){
obj.dist <- distance
if( attributes(obj.dist)$Size != nsamples(physeq) ){
stop("nsamples(physeq) does not match size of dist object in distance")
}
if( !setequal(attributes(obj.dist)$Labels, sample_names(physeq)) ){
stop("sample_names does not exactly match dist-indices")
}
} else if( class(distance) == "character" ){
obj.dist <- distance(physeq, method=distance, type=type, ...)
} else {
if(taxa_are_rows(physeq)){ physeq <- t(physeq) }
obj.dist <- distance(as(otu_table(physeq), "matrix"))
}
SaDiMa <- as.matrix(obj.dist)
SaDiMa <- SaDiMa + diag(Inf, nsamples(physeq), nsamples(physeq))
CoMa <- SaDiMa < max.dist
} else {
stop("type argument must be one of \n (1) samples \n or \n (2) taxa")
}
ig <- graph.adjacency(CoMa, mode="lower")
if( !keep.isolates ){
isolates <- V(ig)[degree(ig) == 0]
ig = delete.vertices(ig, V(ig)[degree(ig) == 0])
}
if( vcount(ig) < 2 ){
warning("The graph you created has too few vertices. Consider changing `max.dist` argument, and check your data.")
}
return(ig)
} |
print.mixfitEM <- function(x, digits = getOption("digits"), ...) {
family <- x$family
mc <- match.call()
mc$digits <- digits
fun.name <- paste0("print", family)
mc[[1]] <- as.name(fun.name)
eval(mc, environment())
} |
expected <- eval(parse(text="structure(list(Ozone = c(41L, 36L, 12L, 18L, NA, 28L, 23L, 19L, 8L, NA, 7L, 16L, 11L, 14L, 18L, 14L, 34L, 6L, 30L, 11L, 1L, 11L, 4L, 32L, NA, NA, NA, 23L, 45L, 115L, 37L, NA, NA, NA, NA, NA, NA, 29L, NA, 71L, 39L, NA, NA, 23L, NA, NA, 21L, 37L, 20L, 12L, 13L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 135L, 49L, 32L, NA, 64L, 40L, 77L, 97L, 97L, 85L, NA, 10L, 27L, NA, 7L, 48L, 35L, 61L, 79L, 63L, 16L, NA, NA, 80L, 108L, 20L, 52L, 82L, 50L, 64L, 59L, 39L, 9L, 16L, 78L, 35L, 66L, 122L, 89L, 110L, NA, NA, 44L, 28L, 65L, NA, 22L, 59L, 23L, 31L, 44L, 21L, 9L, NA, 45L, 168L, 73L, NA, 76L, 118L, 84L, 85L, 96L, 78L, 73L, 91L, 47L, 32L, 20L, 23L, 21L, 24L, 44L, 21L, 28L, 9L, 13L, 46L, 18L, 13L, 24L, 16L, 13L, 23L, 36L, 7L, 14L, 30L, NA, 14L, 18L, 20L), Solar.R = c(190L, 118L, 149L, 313L, NA, NA, 299L, 99L, 19L, 194L, NA, 256L, 290L, 274L, 65L, 334L, 307L, 78L, 322L, 44L, 8L, 320L, 25L, 92L, 66L, 266L, NA, 13L, 252L, 223L, 279L, 286L, 287L, 242L, 186L, 220L, 264L, 127L, 273L, 291L, 323L, 259L, 250L, 148L, 332L, 322L, 191L, 284L, 37L, 120L, 137L, 150L, 59L, 91L, 250L, 135L, 127L, 47L, 98L, 31L, 138L, 269L, 248L, 236L, 101L, 175L, 314L, 276L, 267L, 272L, 175L, 139L, 264L, 175L, 291L, 48L, 260L, 274L, 285L, 187L, 220L, 7L, 258L, 295L, 294L, 223L, 81L, 82L, 213L, 275L, 253L, 254L, 83L, 24L, 77L, NA, NA, NA, 255L, 229L, 207L, 222L, 137L, 192L, 273L, 157L, 64L, 71L, 51L, 115L, 244L, 190L, 259L, 36L, 255L, 212L, 238L, 215L, 153L, 203L, 225L, 237L, 188L, 167L, 197L, 183L, 189L, 95L, 92L, 252L, 220L, 230L, 259L, 236L, 259L, 238L, 24L, 112L, 237L, 224L, 27L, 238L, 201L, 238L, 14L, 139L, 49L, 20L, 193L, 145L, 191L, 131L, 223L), Wind = c(7.4, 8, 12.6, 11.5, 14.3, 14.9, 8.6, 13.8, 20.1, 8.6, 6.9, 9.7, 9.2, 10.9, 13.2, 11.5, 12, 18.4, 11.5, 9.7, 9.7, 16.6, 9.7, 12, 16.6, 14.9, 8, 12, 14.9, 5.7, 7.4, 8.6, 9.7, 16.1, 9.2, 8.6, 14.3, 9.7, 6.9, 13.8, 11.5, 10.9, 9.2, 8, 13.8, 11.5, 14.9, 20.7, 9.2, 11.5, 10.3, 6.3, 1.7, 4.6, 6.3, 8, 8, 10.3, 11.5, 14.9, 8, 4.1, 9.2, 9.2, 10.9, 4.6, 10.9, 5.1, 6.3, 5.7, 7.4, 8.6, 14.3, 14.9, 14.9, 14.3, 6.9, 10.3, 6.3, 5.1, 11.5, 6.9, 9.7, 11.5, 8.6, 8, 8.6, 12, 7.4, 7.4, 7.4, 9.2, 6.9, 13.8, 7.4, 6.9, 7.4, 4.6, 4, 10.3, 8, 8.6, 11.5, 11.5, 11.5, 9.7, 11.5, 10.3, 6.3, 7.4, 10.9, 10.3, 15.5, 14.3, 12.6, 9.7, 3.4, 8, 5.7, 9.7, 2.3, 6.3, 6.3, 6.9, 5.1, 2.8, 4.6, 7.4, 15.5, 10.9, 10.3, 10.9, 9.7, 14.9, 15.5, 6.3, 10.9, 11.5, 6.9, 13.8, 10.3, 10.3, 8, 12.6, 9.2, 10.3, 10.3, 16.6, 6.9, 13.2, 14.3, 8, 11.5), Temp = c(67L, 72L, 74L, 62L, 56L, 66L, 65L, 59L, 61L, 69L, 74L, 69L, 66L, 68L, 58L, 64L, 66L, 57L, 68L, 62L, 59L, 73L, 61L, 61L, 57L, 58L, 57L, 67L, 81L, 79L, 76L, 78L, 74L, 67L, 84L, 85L, 79L, 82L, 87L, 90L, 87L, 93L, 92L, 82L, 80L, 79L, 77L, 72L, 65L, 73L, 76L, 77L, 76L, 76L, 76L, 75L, 78L, 73L, 80L, 77L, 83L, 84L, 85L, 81L, 84L, 83L, 83L, 88L, 92L, 92L, 89L, 82L, 73L, 81L, 91L, 80L, 81L, 82L, 84L, 87L, 85L, 74L, 81L, 82L, 86L, 85L, 82L, 86L, 88L, 86L, 83L, 81L, 81L, 81L, 82L, 86L, 85L, 87L, 89L, 90L, 90L, 92L, 86L, 86L, 82L, 80L, 79L, 77L, 79L, 76L, 78L, 78L, 77L, 72L, 75L, 79L, 81L, 86L, 88L, 97L, 94L, 96L, 94L, 91L, 92L, 93L, 93L, 87L, 84L, 80L, 78L, 75L, 73L, 81L, 76L, 77L, 71L, 71L, 78L, 67L, 76L, 68L, 82L, 64L, 71L, 81L, 69L, 63L, 70L, 77L, 75L, 76L, 68L), Month = c(5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L), Day = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L), NULL, NULL), .Names = c(\"Ozone\", \"Solar.R\", \"Wind\", \"Temp\", \"Month\", \"Day\", \"\", \"\"))"));
test(id=0, code={
argv <- eval(parse(text="list(structure(list(Ozone = c(41L, 36L, 12L, 18L, NA, 28L, 23L, 19L, 8L, NA, 7L, 16L, 11L, 14L, 18L, 14L, 34L, 6L, 30L, 11L, 1L, 11L, 4L, 32L, NA, NA, NA, 23L, 45L, 115L, 37L, NA, NA, NA, NA, NA, NA, 29L, NA, 71L, 39L, NA, NA, 23L, NA, NA, 21L, 37L, 20L, 12L, 13L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 135L, 49L, 32L, NA, 64L, 40L, 77L, 97L, 97L, 85L, NA, 10L, 27L, NA, 7L, 48L, 35L, 61L, 79L, 63L, 16L, NA, NA, 80L, 108L, 20L, 52L, 82L, 50L, 64L, 59L, 39L, 9L, 16L, 78L, 35L, 66L, 122L, 89L, 110L, NA, NA, 44L, 28L, 65L, NA, 22L, 59L, 23L, 31L, 44L, 21L, 9L, NA, 45L, 168L, 73L, NA, 76L, 118L, 84L, 85L, 96L, 78L, 73L, 91L, 47L, 32L, 20L, 23L, 21L, 24L, 44L, 21L, 28L, 9L, 13L, 46L, 18L, 13L, 24L, 16L, 13L, 23L, 36L, 7L, 14L, 30L, NA, 14L, 18L, 20L), Solar.R = c(190L, 118L, 149L, 313L, NA, NA, 299L, 99L, 19L, 194L, NA, 256L, 290L, 274L, 65L, 334L, 307L, 78L, 322L, 44L, 8L, 320L, 25L, 92L, 66L, 266L, NA, 13L, 252L, 223L, 279L, 286L, 287L, 242L, 186L, 220L, 264L, 127L, 273L, 291L, 323L, 259L, 250L, 148L, 332L, 322L, 191L, 284L, 37L, 120L, 137L, 150L, 59L, 91L, 250L, 135L, 127L, 47L, 98L, 31L, 138L, 269L, 248L, 236L, 101L, 175L, 314L, 276L, 267L, 272L, 175L, 139L, 264L, 175L, 291L, 48L, 260L, 274L, 285L, 187L, 220L, 7L, 258L, 295L, 294L, 223L, 81L, 82L, 213L, 275L, 253L, 254L, 83L, 24L, 77L, NA, NA, NA, 255L, 229L, 207L, 222L, 137L, 192L, 273L, 157L, 64L, 71L, 51L, 115L, 244L, 190L, 259L, 36L, 255L, 212L, 238L, 215L, 153L, 203L, 225L, 237L, 188L, 167L, 197L, 183L, 189L, 95L, 92L, 252L, 220L, 230L, 259L, 236L, 259L, 238L, 24L, 112L, 237L, 224L, 27L, 238L, 201L, 238L, 14L, 139L, 49L, 20L, 193L, 145L, 191L, 131L, 223L), Wind = c(7.4, 8, 12.6, 11.5, 14.3, 14.9, 8.6, 13.8, 20.1, 8.6, 6.9, 9.7, 9.2, 10.9, 13.2, 11.5, 12, 18.4, 11.5, 9.7, 9.7, 16.6, 9.7, 12, 16.6, 14.9, 8, 12, 14.9, 5.7, 7.4, 8.6, 9.7, 16.1, 9.2, 8.6, 14.3, 9.7, 6.9, 13.8, 11.5, 10.9, 9.2, 8, 13.8, 11.5, 14.9, 20.7, 9.2, 11.5, 10.3, 6.3, 1.7, 4.6, 6.3, 8, 8, 10.3, 11.5, 14.9, 8, 4.1, 9.2, 9.2, 10.9, 4.6, 10.9, 5.1, 6.3, 5.7, 7.4, 8.6, 14.3, 14.9, 14.9, 14.3, 6.9, 10.3, 6.3, 5.1, 11.5, 6.9, 9.7, 11.5, 8.6, 8, 8.6, 12, 7.4, 7.4, 7.4, 9.2, 6.9, 13.8, 7.4, 6.9, 7.4, 4.6, 4, 10.3, 8, 8.6, 11.5, 11.5, 11.5, 9.7, 11.5, 10.3, 6.3, 7.4, 10.9, 10.3, 15.5, 14.3, 12.6, 9.7, 3.4, 8, 5.7, 9.7, 2.3, 6.3, 6.3, 6.9, 5.1, 2.8, 4.6, 7.4, 15.5, 10.9, 10.3, 10.9, 9.7, 14.9, 15.5, 6.3, 10.9, 11.5, 6.9, 13.8, 10.3, 10.3, 8, 12.6, 9.2, 10.3, 10.3, 16.6, 6.9, 13.2, 14.3, 8, 11.5), Temp = c(67L, 72L, 74L, 62L, 56L, 66L, 65L, 59L, 61L, 69L, 74L, 69L, 66L, 68L, 58L, 64L, 66L, 57L, 68L, 62L, 59L, 73L, 61L, 61L, 57L, 58L, 57L, 67L, 81L, 79L, 76L, 78L, 74L, 67L, 84L, 85L, 79L, 82L, 87L, 90L, 87L, 93L, 92L, 82L, 80L, 79L, 77L, 72L, 65L, 73L, 76L, 77L, 76L, 76L, 76L, 75L, 78L, 73L, 80L, 77L, 83L, 84L, 85L, 81L, 84L, 83L, 83L, 88L, 92L, 92L, 89L, 82L, 73L, 81L, 91L, 80L, 81L, 82L, 84L, 87L, 85L, 74L, 81L, 82L, 86L, 85L, 82L, 86L, 88L, 86L, 83L, 81L, 81L, 81L, 82L, 86L, 85L, 87L, 89L, 90L, 90L, 92L, 86L, 86L, 82L, 80L, 79L, 77L, 79L, 76L, 78L, 78L, 77L, 72L, 75L, 79L, 81L, 86L, 88L, 97L, 94L, 96L, 94L, 91L, 92L, 93L, 93L, 87L, 84L, 80L, 78L, 75L, 73L, 81L, 76L, 77L, 71L, 71L, 78L, 67L, 76L, 68L, 82L, 64L, 71L, 81L, 69L, 63L, 70L, 77L, 75L, 76L, 68L), Month = c(5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L), Day = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L)), .Names = c(\"Ozone\", \"Solar.R\", \"Wind\", \"Temp\", \"Month\", \"Day\"), row.names = c(NA, -153L)), list(NULL, NULL))"));
do.call(`c`, argv);
}, o=expected); |
voxels_counting <- function(cloud, edge_sizes = NULL, min_size, length_out = 10, bootstrap = FALSE, R = NULL, progress = TRUE, parallel = FALSE, threads = NULL) {
colnames(cloud) <- c("X", "Y", "Z")
if(is.null(edge_sizes) == TRUE) {
ranges <- c(max(cloud[,1]) - min(cloud[,1]), max(cloud[,2]) - min(cloud[,2]), max(cloud[,3]) - min(cloud[,3]))
max.range <- ranges[which.max(ranges)] + 0.0001
edge_sizes <- seq(from = log10(c(max.range)), to = log10(min_size), length.out = length_out)
edge_sizes <- 10^edge_sizes
}
cloud_touse <- cloud
if(parallel == TRUE) {
cl <- makeCluster(threads, outfile="")
registerDoSNOW(cl)
if(progress == TRUE) {
print("Creating voxels in parallel")
pb <- txtProgressBar(min = 0, max = length(edge_sizes), style = 3)
progress <- function(n) setTxtProgressBar(pb, n)
opts <- list(progress=progress)
} else {
opts <- NULL
}
results <- foreach(i = 1:length(edge_sizes), .inorder = FALSE, .combine= rbind, .packages = c("data.table", "rTLS"), .options.snow = opts) %dopar% {
vox <- voxels(cloud_touse, edge_length = c(edge_sizes[i], edge_sizes[i], edge_sizes[i]), obj.voxels = FALSE)
summary <- summary_voxels(vox, edge_length = c(edge_sizes[i], edge_sizes[i], edge_sizes[i]), bootstrap = bootstrap, R = R)
return(summary)
}
results <- results[order(Edge.X)]
stopCluster(cl)
} else if(parallel == FALSE) {
if(progress == TRUE) {
print("Creating voxels")
pb <- txtProgressBar(min = 0, max = length(edge_sizes), style = 3)
}
results <- foreach(i = 1:length(edge_sizes), .inorder = FALSE, .combine= rbind) %do% {
if(progress == TRUE) {
setTxtProgressBar(pb, i)
}
vox <- voxels(cloud_touse, edge_length = c(edge_sizes[i], edge_sizes[i], edge_sizes[i]), obj.voxels = FALSE)
summary <- summary_voxels(vox, edge_length = c(edge_sizes[i], edge_sizes[i], edge_sizes[i]), bootstrap = bootstrap, R = R)
return(summary)
}
if(progress == TRUE) {
close(pb)
}
results <- results[order(Edge.X)]
}
return(results)
}
decimals <- function(x) {
n <- 0
while (!isTRUE(all.equal(floor(x),x)) & n <= 1e6) { x <- x*10; n <- n+1 }
return (n)
} |
tierChart <- function(x,
startMonth = latestJanuary(end(x)),
nMonths = 4,
nYears = 7,
offsets = 0,
padDays = 6,
pch = "year",
lty = "solid",
lwd = 1.5,
col = 1 + (n.y:1),
type = "b",
ylim = NULL,
outlier.trim = 0,
noTrimLastYear = TRUE,
extendHorizontalTicks = TRUE,
circles.ymd = NULL,
circles.col = 6,
circles.inches = 0.1,
vlines.ymd = NULL,
vlines.col = 2,
vlines.lty = 4,
vlines.lwd = 1.5,
vlines2.ymd = NULL,
vlines2.col = 3,
vlines2.lty = "solid",
vlines2.lwd = 2,
hlines = NULL,
hlines.col = 1,
hlines.lty = 1,
hlines.lwd = 1,
tiPoints.1 = NULL,
tiPoints.2 = NULL,
pch.1 = "*",
pch.2 = "+",
col.1 = 2,
col.2 = 3,
nolegend = FALSE,
main = deparse(substitute(x)),
topleft.labels = NULL,
topright.labels = NULL,
legend.ncol = length(years),
legend.bg = 0,
timestamp = TRUE,
topline = TRUE,
vlines.periodEnd = TRUE,
vlines.month = TRUE,
midperiod = FALSE,
lwdLastYear = 1.5,
cex = 1.5,
boxes = TRUE,
...){
oldpar <- par(xpd = FALSE, err = -1, mar = c(2,5,3,5)+0.1, mgp = c(1,0,0),
xaxs = "i", yaxs = "i", mex = 1, ann = FALSE)
on.exit(par(oldpar), add = TRUE)
if(par("new") == FALSE) plot.new()
main <- main
x <- as.tis(x)
xTif <- tif(x)
dim(x) <- NULL
if(!is.ti(startMonth)) stop("startMonth must be a ti")
xEndMonth <- currentMonth(end(x))
if(startMonth > xEndMonth) stop("startMonth after end(x)")
endMonth <- startMonth + nMonths - 1
if(endMonth > xEndMonth){
xExtendedEnd <- ti(endMonth, tif(x))
x[xExtendedEnd] <- NA
}
xStartMonth <- currentMonth(start(x))
years <- (year(startMonth) - nYears + 1): year(startMonth)
eyears <- (year(endMonth) - nYears + 1): year(endMonth)
eym <- 100*eyears + month(endMonth)
years <- years[eym >= (ymd(start(x)) %/% 100)]
if(midperiod) xj <- floor(jul(ti(x), offset = 0.5))
else xj <- jul(ti(x))
n.y <- length(years)
n.x <- length(x)
y.seq <- 1:n.y
x.seq <- 1:n.x
startMonths <- startMonth - 12*((nYears - 1):0)
endMonths <- startMonths + nMonths - 1
inRange <- startMonths <= xEndMonth & endMonths >= xStartMonth
startMonths <- startMonths[inRange]
endMonths <- endMonths[inRange]
offsets <- c(rev(offsets), rep(0, length(years) - length(offsets)))
starts <- jul(startMonths - 1) - (padDays - 1) + offsets
ends <- jul(endMonths) + padDays + offsets
x.ticks <- 1:(1 + ends[n.y] - starts[n.y])
x.ymd <- ymd(seq(starts[n.y], ends[n.y]))
x.periodEnds <- x.ymd == ymd(ti(x.ymd, tif = xTif))
feb28 <- match(0228, x.ymd %% 10000, nomatch = FALSE)
if(feb28 != FALSE){
feb29 <- match(0229, x.ymd %% 10000, nomatch = FALSE)
if(feb29 == FALSE){
x.ticks <- append(x.ticks, length(x.ticks) + 1)
x.ymd <- append(x.ymd, x.ymd[feb28]+1, after = feb28)
x.periodEnds <- append(x.periodEnds, FALSE, after = feb28)
}
}
xtlen <- length(x.ticks)
matrows <- ceiling(xtlen*frequency(x)/365) + 1
py <- matrix(NA, nrow = matrows, ncol = n.y,
dimnames = list(character(0), paste(years)))
pindex <- pymd <- px <- py
for(y in y.seq){
ix <- x.seq[between(xj, starts[y], ends[y])]
iRows <- 1:length(ix)
pindex[iRows, y] <- ix
py[iRows, y] <- x[ix]
pymd[iRows, y] <- ymd(xj[ix])
ymd.offset <- 10000 * (max(years) - years[y])
px[iRows, y] <- match(ymd(xj[ix] + offsets[y]) + ymd.offset, x.ymd)
}
xlim <- c(x.ticks[1], x.ticks[xtlen] + 1)
if(missing(ylim)){
bounds <- 1.1 * quantile(py, c(outlier.trim, 1-outlier.trim), na.rm=TRUE) -
0.1 * median(py, na.rm=TRUE)
ylim <- c(max(bounds[1], min(py, na.rm=TRUE)),
min(bounds[2], max(py, na.rm=TRUE)))
if(noTrimLastYear){
pyLastYear <- py[,ncol(py)]
ylim <- c(min(bounds[1], min(pyLastYear, na.rm = TRUE)),
max(bounds[2], max(pyLastYear, na.rm = TRUE)))
}
}
ylim[2] <- 1.1*ylim[2] - 0.1*ylim[1]
y.ticks <- pretty(ylim, n = 8)
ylim <- range(y.ticks)
plot.window(xlim = xlim, ylim = ylim)
if( length(pch) == 1 && is.character(pch) && pch == "year")
pch <- paste(substring(years, 4, 4), collapse = "")
if(!missing(lwdLastYear)){
lwd <- rep(lwd, length.out = length(years))
lwd[length(lwd)] <- lwdLastYear
}
if(!nolegend){
legendStrings <- format(years)
if(any(offsets != 0)){
roffStrings <- paste("[", offsets, "]", sep = "")
roffStrings[offsets == 0] <- ""
legendStrings <- paste(legendStrings, roffStrings, sep = "")
}
legend(x = 0.5*xlim[1] + 0.5*xlim[2],
y = max(ylim),
legend = legendStrings,
pch = pch,
lty = lty,
lwd = lwd,
col = col,
ncol = legend.ncol,
bg = legend.bg, bty = "o", cex = 1.3,
xjust = 0.5)
}
if(length(main))
mtext(main, side = 3, adj = 0.5, cex = 1.5, line = 0.5)
if(tl.len <- length(topleft.labels)){
for(i in 1:tl.len)
mtext(topleft.labels[i], side = 3, adj = 0, at = xlim[1],
line = tl.len - i + 0.2)
}
if(tr.len <- length(topright.labels)){
for(i in 1:tr.len)
mtext(topright.labels[i], side = 3, adj = 1, at = xlim[2],
line = tr.len - i + 0.2)
}
par(new = TRUE)
matplot(px, py, type = type, pch = pch, col = col, cex = cex,
lty = lty, lwd = lwd, axes = FALSE, bty = "n", yaxs = "i", xaxs = "i",
xlim = xlim, ylim = range(y.ticks), ...)
if(type == "b" | type == "p")
matpoints(px, py, pch = pch, lty = 1, col = col, cex = cex)
periodEnd.ticks <- x.ticks[x.periodEnds]
day15 <- (1:xtlen)[x.ymd %% 100 == 15]
eom <- (1:xtlen)[x.ymd == ymd(ti(x.ymd, tif = "monthly"))]
if(vlines.periodEnd)
axis(1, at = periodEnd.ticks, tck = 1, lty = 2, labels = FALSE)
if(vlines.month) abline(v = eom, lty = 1)
if(extendHorizontalTicks)
axis(2, at = y.ticks, tck = 1, lty = 2, labels = FALSE)
axis(2, at = y.ticks, las = 1, adj = 1, tck = 0.02, labels = TRUE)
axis(4, at = y.ticks, las = 1, adj = 0, tck = 0.02)
if(topline) abline(h = ylim[2])
axis(1, at = x.ticks, tck = 0.02, labels = FALSE)
monthLabels <- format(jul(x.ymd[day15]), "%b %Y")
if(length(monthLabels) > 8)
axis(1, at = periodEnd.ticks, tck = 0.04, labels = FALSE)
else {
periodEndLabels <- paste(x.ymd[x.periodEnds] %% 100)
axis(1, at = periodEnd.ticks, tck = 0.04, labels = periodEndLabels)
}
mtext(text = monthLabels, side = 1, line = 1, at = day15)
if(!is.null(vlines.ymd)){
i <- match(vlines.ymd, x.ymd, nomatch = 0)
if(any(i != 0))
abline(v = x.ticks[i], col = vlines.col, lty = vlines.lty, lwd = vlines.lwd)
}
if(!is.null(vlines2.ymd)){
i <- match(vlines2.ymd, x.ymd, nomatch = 0)
if(any(i != 0))
abline(v = x.ticks[i], col = vlines2.col, lty = vlines2.lty, lwd = vlines2.lwd)
}
if(!is.null(hlines)){
abline(h = hlines, col = hlines.col, lty = hlines.lty, lwd = hlines.lwd)
}
if(!is.null(tiPoints.1)){
ymd.1 <- ymd(ti(tiPoints.1))
i.1 <- match(ymd.1, x.ymd, nomatch = 0)
if(any(i.1 != 0))
matpoints(x.ticks[i.1], tiPoints.1[i.1 > 0], pch = pch.1,
cex = 1.4, col = col.1)
}
if(!is.null(tiPoints.2)){
ymd.2 <- ymd(ti(tiPoints.2))
i.2 <- match(ymd.2, x.ymd, nomatch = 0)
if(any(i.2 != 0))
matpoints(x.ticks[i.2], tiPoints.2[i.2 > 0], pch = pch.2,
cex = 1.4, col = col.2)
}
if(!is.null(circles.ymd)){
i.circles <- match(circles.ymd, pymd, nomatch = 0)
if(any(i.circles != 0)){
x <- px[i.circles]
y <- py[i.circles]
symbols(x, y, add = TRUE, circles = rep(1, length(x)),
inches = circles.inches, col = circles.col)
}
}
if(boxes){
extents <- c(diff(xlim), diff(ylim)) / (par("pin") * c(2, 4))
boxBottom <- ylim[2] - extents[2]
lBox <- c(xlim[1], boxBottom, xlim[1]+extents[1], ylim[2])
rBox <- c(xlim[2]-extents[1], boxBottom, xlim[2], ylim[2])
rect(lBox[1], lBox[2], lBox[3], lBox[4], col = "white")
rect(rBox[1], rBox[2], rBox[3], rBox[4], col = "white")
arrows(lBox[3], (lBox[2] +lBox[4])/2, lBox[1], (lBox[2]+lBox[4])/2,
angle = 30,lwd = 4, col = "black")
arrows(rBox[1], (rBox[2] +rBox[4])/2, rBox[3], (rBox[2]+rBox[4])/2,
angle = 30,lwd = 4, col = "black")
printBox <- c(lBox[3], lBox[2], lBox[3] + (lBox[3] - lBox[1]), lBox[4])
rect(printBox[1], printBox[2], printBox[3], printBox[4], col = "darkblue")
text(x = mean(printBox[c(1,3)]),
y = mean(printBox[c(2,4)]),
labels = "Print Me",
adj = c(0.5, 0.5),
cex = 1.25, col = "white")
}
else {
lBox <- rBox <- printBox <- NULL
}
if(timestamp) mtext(date(), side = 3, outer = TRUE, line = -1, adj = 1)
invisible(list(px = px, py = py, ymd = pymd, index = pindex,
lBox = lBox, rBox = rBox, printBox = printBox,
startMonth = startMonth, nMonths = nMonths,
nYears = nYears))
}
adjustableTierChart <- function(x, ..., edit = TRUE,
changes = numeric(0), verbose = FALSE){
locateOne <- function(){
options(error = NULL)
point <- try(locator(1), silent = TRUE)
if(class(point) == "try-error")
point <- NULL
options(error = quote(recover()))
point
}
arglist <- list(..., edit = edit, verbose = verbose)
if(is.null(arglist$main))
arglist$main <- deparse(substitute(x))
arglist$x <- x
arglist$changes <- changes
arglist$boxes <- TRUE
drops <- match(c("edit", "changes", "verbose"), names(arglist), nomatch = 0)
tcArgs <- arglist[-drops]
tc <- do.call("tierChart", tcArgs)
xStart <- start(x)
xEnd <- end(x)
xStartMonth <- ti(xStart, tif = "monthly")
xEndMonth <- ti(xEnd, tif = "monthly")
lastcol <- dim(tc$px)[2]
not.na <- !(is.na(tc$px[,lastcol]) | is.na(tc$py[,lastcol]))
px <- tc$px[not.na, lastcol]
py <- tc$py[not.na, lastcol]
ymd <- tc$ymd[not.na, lastcol]
index <- tc$index[not.na, lastcol]
xStep <- mean(diff(px))
lBox <- tc$lBox
rBox <- tc$rBox
pBox <- tc$printBox
startMonth <- tc$startMonth
nMonths <- tc$nMonths
scrollIncrement <- max(nMonths - 2, 1)
if(frequency(xStart) <= 12) scrollIncrement <- round(frequency(xStart))
if(length(changes) > 0){
for(i in 1:nrow(changes)){
change <- changes[i,]
j <- match(change["ymd"], ymd, nomatch = 0)
if(j > 0) arrows(px[j], py[j], px[j], change["newY"], col = 2)
}
}
if(verbose) cat("Awaiting mouse input...")
nextpoint <- locateOne()
while(length(nextpoint) != 0){
npX <- nextpoint$x
npY <- nextpoint$y
lBoxClicked <- rBoxClicked <- pBoxClicked <- FALSE
if((npY >= lBox[2]) && (npY <= lBox[4])){
lBoxClicked <- (npX >= lBox[1]) && (npX <= lBox[3])
rBoxClicked <- (npX >= rBox[1]) && (npX <= rBox[3])
pBoxClicked <- (npX >= pBox[1]) && (npX <= pBox[3])
}
if(rBoxClicked){
inc <- min(scrollIncrement, xEndMonth - startMonth)
arglist$startMonth <- startMonth + inc
return(do.call("adjustableTierChart", arglist))
}
if(lBoxClicked){
inc <- min(scrollIncrement, startMonth - xStartMonth)
arglist$startMonth <- startMonth - inc
return(do.call("adjustableTierChart", arglist))
}
if(pBoxClicked){
printer <- options()$colorPrinter
if(is.null(printer)) cat("options()$colorPrinter not set\n")
else {
postscript(file = "",
command = paste("lp -d", printer, sep = ""),
pointsize = 9)
setColors(frColors())
modArgs <- tcArgs
modArgs$legend.bg <- "grey90"
do.call("tierChart", modArgs)
dev.off()
}
}
else {
if(edit){
xDistances <- abs(px - npX)
if(min(xDistances) < xStep){
i <- order(xDistances)[1]
new.y <- npY
changes <- rbind(changes, c(ymd = ymd[i], newY = npY))
arglist$changes <- changes
arrows(px[i], py[i], px[i], new.y, col = 2)
if(verbose)
cat("Move", ymd[i], "obs from", signif(py[i], 3),
"to", signif(new.y, 3), "\nAwaiting mouse input... ")
}
}
}
nextpoint <- locateOne()
}
if(length(changes) > 0)
x[match(changes[,"ymd"], ymd(ti(x)))] <- changes[,"newY"]
retval <- x
attr(retval, "startMonth") <- arglist$startMonth
if(verbose) cat("adjustableTierChart() exiting.\n")
invisible(retval)
} |
PlotMixtures <- function(Data, Means, SDs, Weights = rep(1/length(Means),length(Means)), IsLogDistribution = rep(FALSE,length(Means)),SingleColor = 'blue', MixtureColor = 'red',DataColor='black',SingleGausses=FALSE,axes=TRUE,xlab, ylab,xlim, ylim, ParetoRad=NULL, ...){
if(missing(Data)) stop('Data is missing.')
if(!inherits(Data,'numeric')){
warning('Data is not a numerical vector. calling as.vector')
Data=as.vector(Data)
}
if(length(Data)==length(Means)) warning('Probably "Data" interchanged with "Means" ')
if(!is.null(ParetoRad)){
pareto_radius = ParetoRad
}else{
pareto_radius<-DataVisualizations::ParetoRadius(Data)
}
pdeVal <- DataVisualizations::ParetoDensityEstimation(Data,pareto_radius)
if(missing(xlab)){
xlab = ''
}
if(missing(ylab)){
ylab = 'PDE'
}
if(missing(IsLogDistribution)) IsLogDistribution = rep(FALSE,length(Means))
if(length(IsLogDistribution)!=length(Means)){
warning(paste('Length of Means',length(Means),'does not equal length of IsLogDistribution',length(IsLogDistribution),'Generating new IsLogDistribution'))
IsLogDistribution = rep(FALSE,length(Means))
}
X = sort(na.last=T,unique(Data))
AnzGaussians <- length(Means)
if(SingleColor != 0){
pdfV=Pdf4Mixtures(X, Means, SDs, Weights)
SingleGaussian=pdfV$PDF
GaussMixture=pdfV$PDFmixture
GaussMixtureInd=which(GaussMixture>0.00001)
if(missing(xlim)){
xl = max(X[GaussMixtureInd],na.rm=T)
xa = min(X[GaussMixtureInd], 0,na.rm=T)
xlim = c(xa,xl)
}
if(missing(ylim)){
yl <- max(GaussMixture,pdeVal$paretoDensity,na.rm=T)
ya <- min(GaussMixture, 0,na.rm=T)
ylim <- c(ya,yl+0.1*yl)
}
plot.new()
par(xaxs='i')
par(yaxs='i')
par(usr=c(xlim,ylim))
if(SingleGausses){
for(g in c(1:AnzGaussians)){
par(new = TRUE)
points(X, SingleGaussian[,g], col = SingleColor, type = 'l', xlim = xlim, ylim = ylim, ylab="PDE", ...)
}
}
points(X, GaussMixture, col = MixtureColor, type = 'l',xlim = xlim,...)
} else{
plot(X, GaussMixture, col = MixtureColor, type = 'l', xlim, ylim,axes=FALSE, ...)
}
if(axes){
axis(1,xlim=xlim,col="black",las=1)
axis(2,ylim=ylim,col="black",las=1)
title(xlab=xlab,ylab=ylab,...)
}
points(pdeVal$kernels,pdeVal$paretoDensity,type='l', xlim = xlim, ylim = ylim,col=DataColor,...)
} |
context("wflow_rename")
source("setup.R")
skip_on_cran_windows()
library("git2r")
cwd <- getwd()
tdir <- tempfile("test-wflow_rename-")
on.exit(setwd(cwd))
on.exit(unlink(tdir, recursive = TRUE, force = TRUE), add = TRUE)
suppressMessages(wflow_start(tdir, user.name = "Test Name",
user.email = "test@email"))
tdir <- workflowr:::absolute(tdir)
r <- repository(path = tdir)
p <- wflow_paths()
test_that("wflow_rename can rename one file", {
original <- "analysis/about.Rmd"
new <- "analysis/new.Rmd"
renamed <- wflow_rename(original, new, message = "Rename file")
expect_false(fs::file_exists(original))
expect_true(fs::file_exists(new))
expect_identical(renamed$files_git, c(original, new))
last_commit <- commits(r, n = 1)[[1]]
last_commit_mes <- last_commit$message
last_commit_sha <- last_commit$sha
expect_identical(last_commit_mes, "Rename file")
expect_output(print(renamed), sprintf("%s -> %s", original, new))
expect_output(print(renamed),
stringr::str_sub(last_commit_sha, start = 1, end = 7))
expect_output(print(renamed), "commit message:")
undo <- wflow_rename(new, original, message = "Revert to original name")
expect_true(fs::file_exists(original))
expect_false(fs::file_exists(new))
expect_identical(undo$files_git, c(new, original))
last_commit <- commits(r, n = 1)[[1]]
last_commit_mes <- last_commit$message
last_commit_sha <- last_commit$sha
expect_identical(last_commit_mes, "Revert to original name")
expect_output(print(undo), sprintf("%s -> %s", new, original))
expect_output(print(undo),
stringr::str_sub(last_commit_sha, start = 1, end = 7))
expect_output(print(renamed), "commit message:")
})
test_that("wflow_rename can rename one file when no Git repo", {
git <- ".git"
git_tmp <- ".git-tmp"
on.exit(fs::file_move(git_tmp, git))
fs::file_move(git, git_tmp)
original <- "analysis/about.Rmd"
new <- "analysis/new.Rmd"
renamed <- wflow_rename(original, new, message = "Rename file")
expect_false(fs::file_exists(original))
expect_true(fs::file_exists(new))
expect_identical(renamed$files, original, new)
expect_identical(renamed$files_git, NA_character_)
undo <- wflow_rename(new, original, message = "Revert to original name")
expect_true(fs::file_exists(original))
expect_false(fs::file_exists(new))
expect_identical(undo$files, new)
expect_identical(undo$files_git, NA_character_)
print_lines <- utils::capture.output(print(undo))
expect_true(sprintf("%s -> %s", new, original) %in% print_lines)
expect_false("commit message:" %in% print_lines)
})
test_that("wflow_rename can rename one directory", {
original <- "code"
new <- "scripts"
renamed <- wflow_rename(original, new, message = "Rename code directory")
expect_false(fs::dir_exists(original))
expect_true(fs::dir_exists(new))
expect_identical(renamed$files_git,
c(file.path(original, "README.md"),
file.path(new, "README.md")))
undo <- wflow_rename(new, original,
message = "Revert to original directory name")
expect_true(fs::dir_exists(original))
expect_false(fs::dir_exists(new))
expect_identical(undo$files_git,
c(file.path(new, "README.md"),
file.path(original, "README.md")))
})
test_that("wflow_rename can rename one directory from outside project", {
setwd(cwd)
on.exit(setwd(tdir))
original <- file.path(tdir, "code")
new <- file.path(tdir, "scripts")
renamed <- wflow_rename(original, new, message = "Rename code directory",
project = tdir)
expect_false(fs::dir_exists(original))
expect_true(fs::dir_exists(new))
expect_identical(renamed$files_git,
workflowr:::relative(c(file.path(original, "README.md"),
file.path(new, "README.md"))))
undo <- wflow_rename(new, original,
message = "Revert to original directory name",
project = tdir)
expect_true(fs::dir_exists(original))
expect_false(fs::dir_exists(new))
expect_identical(undo$files_git,
workflowr:::relative(c(file.path(new, "README.md"),
file.path(original, "README.md"))))
})
test_that("wflow_rename can handle a trailing slash in a directory name", {
original <- "code/"
new <- "scripts/"
expect_identical(workflowr:::absolute(getwd()), tdir)
expect_true(fs::dir_exists(original),
info = glue::glue("wd is {fs::path_wd()} and contains \n{paste(fs::dir_ls(), collapse = '\n')}"))
renamed <- wflow_rename(original, new, message = "Rename code directory")
expect_false(fs::dir_exists(original))
expect_true(fs::dir_exists(new))
expect_identical(renamed$files_git,
workflowr:::relative(c(file.path(original, "README.md"),
file.path(new, "README.md"))))
undo <- wflow_rename(new, original,
message = "Revert to original directory name")
expect_true(fs::dir_exists(original))
expect_false(fs::dir_exists(new))
expect_identical(undo$files_git,
workflowr:::relative(c(file.path(new, "README.md"),
file.path(original, "README.md"))))
})
test_that("wflow_rename can rename one Rmd file with HTML and figs", {
skip_on_cran()
original <- "analysis/about.Rmd"
new <- "analysis/new.Rmd"
wflow_publish(original, view = FALSE)
dir_fig <- file.path(p$docs, workflowr:::create_figure_path(original))
fs::dir_create(dir_fig)
fig <- file.path(dir_fig, "fig.png")
fs::file_create(fig)
add(r, fig)
commit(r, "Publish fake fig to accompany Rmd file to be renamed")
html <- workflowr:::to_html(original, outdir = p$docs)
html_new <- workflowr:::to_html(new, outdir = p$docs)
dir_fig_new <- file.path(p$docs, workflowr:::create_figure_path(new))
fig_new <- file.path(dir_fig_new, "fig.png")
renamed <- wflow_rename(original, new, message = "Rename file")
expect_false(fs::file_exists(original))
expect_true(fs::file_exists(new))
expect_false(fs::file_exists(html))
expect_true(fs::file_exists(html_new))
expect_false(fs::file_exists(fig))
expect_true(fs::file_exists(fig_new))
expect_identical(renamed$files_git, c(original, html, fig,
new, html_new, fig_new))
undo <- wflow_rename(new, original, message = "Revert to original name")
expect_true(fs::file_exists(original))
expect_false(fs::file_exists(new))
expect_true(fs::file_exists(html))
expect_false(fs::file_exists(html_new))
expect_true(fs::file_exists(fig))
expect_false(fs::file_exists(fig_new))
expect_identical(undo$files_git, c(new, html_new, fig_new,
original, html, fig))
})
test_that("print.wflow_rename works with dry_run", {
original <- "README.md"
new <- "new.md"
renamed <- wflow_rename(original, new, dry_run = TRUE)
expect_output(print(renamed), "The following file\\(s\\) would be renamed:")
expect_output(print(renamed), sprintf("%s -> %s", original, new))
expect_output(print(renamed),
"The following file\\(s\\) would be included in the Git commit:")
})
test_that("print.wflow_rename works with `git = FALSE`", {
original <- "README.md"
new <- "new.md"
git_true <- wflow_rename(original, new, git = TRUE, dry_run = TRUE)
git_true_print_lines <- utils::capture.output(print(git_true))
expect_true("commit message:" %in% git_true_print_lines)
git_false <- wflow_rename(original, new, git = FALSE, dry_run = TRUE)
git_false_print_lines <- utils::capture.output(print(git_false))
expect_false("commit message:" %in% git_false_print_lines)
}) |
library('Rcmdr')
gm <- function(x) {
gettext(paste0(x, '...'), domain='R-Rcmdr')
}
gt <- function(x) {
gettext(x, domain='R-Rcmdr')
} |
genwr<-function(aindex){
aindex<-as.matrix(aindex)
n1<-nrow(aindex)
n0<-ncol(aindex)
n<-n1+n0
kk<-max(abs(aindex))
tw<-tl<-xp<-rep(0,kk)
wr<-vr<-vr0<-wd<-vd0<-wp<-vp<-vp0<-0.0
vd<-rep(0,2)
abc1<-.Fortran("xgenwr",as.integer(n1),as.integer(n0),as.integer(kk), as.integer(aindex),
tw=as.integer(tw),tl=as.integer(tl),xp=as.double(xp),wr=as.double(wr),vr=as.double(vr),vr0=as.double(vr0),
wd=as.double(wd),vd=as.double(vd),vd0=as.double(vd0),
wp=as.double(wp),vp=as.double(vp),vp0=as.double(vp0))
wd<-abc1$wd;wr<-abc1$wr;wp<-abc1$wp
vd<-abc1$vd;vr<-abc1$vr;vp<-abc1$vp
vd0<-abc1$vd0;vr0<-abc1$vr0;vp0<-abc1$vp0
td<-n^(-3/2)*wd/sqrt(vd);pd<-2*(1-pnorm(abs(td)))
td0<-n^(-3/2)*wd/sqrt(vd0);pd0<-2*(1-pnorm(abs(td0)))
tr<-sqrt(n)*log(wr)*wr/sqrt(vr);pr<-2*(1-pnorm(abs(tr)))
tr0<-sqrt(n)*log(wr)/sqrt(vr0);pr0<-2*(1-pnorm(abs(tr0)))
tp<-sqrt(n)*log(wp)*wp/sqrt(vp);pp<-2*(1-pnorm(abs(tp)))
tp0<-sqrt(n)*log(wp)/sqrt(vp0);pp0<-2*(1-pnorm(abs(tp0)))
tw<-abc1$tw;tl<-abc1$tl
cwindex<-tw/sum(tw+tl)
clindex<-tl/sum(tw+tl)
xp<-abc1$xp
me<-list(n1=n1,n0=n0,n=n,totalw=sum(tw), totall=sum(tl),tw=tw,tl=tl,xp=xp,cwindex=cwindex,clindex=clindex,
wr=wr,vr=vr,vr0=vr0,tr=tr,pr=pr,tr0=tr0,pr0=pr0,
wd=wd,vd=vd,vd0=vd0,td=td,pd=pd,td0=td0,pd0=pd0,
wp=wp,vp=vp,vp0=vp0,tp=tp,pp=pp,tp0=tp0,pp0=pp0)
class(me)<-append(class(me),"WWR")
return(me)
} |
timeDateOptions <-
function(...) {
current <- if(exists(".splusTimeDateOptions", envir=.splusTimeDateEnv)) {
.splusTimeDateEnv$.splusTimeDateOptions
} else {
.defaultSplusTimeDateOptions
}
if(!nargs()) {
return(current)
}
a <- list(...)
if(length(a) == 1 && is.null(names(a)) && is.list(a[[1]])) {
a <- a[[1]]
if(is.null(names(a))) {
stop("list argument has no valid names")
}
}
r <- vector("list", length(a))
n <- names(a)
show <- FALSE
changed <- current
for(i in seq_along(a)) {
ni <- n[[i]]
if(!is.null(ni) && nchar(ni)) {
changed[[ni]] <- a[[i]]
} else {
ni = a[[i]]
if(!is.character(ni)) stop("invalid argument")
show <- TRUE
}
v <- current[[ni]]
if(!is.null(v)) {
r[[i]] <- if(is.null(a[[i]])) FALSE else v
}
names(r)[[i]] <- ni
}
assign(".splusTimeDateOptions", changed, envir=.splusTimeDateEnv)
if(show) r else invisible(r)
}
.defaultSplusTimeDateOptions <-
list(ts.eps = 1e-05,
sequence.tol = 1e-06,
time.month.name = c("January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November",
"December" ),
time.month.abb = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec"),
time.day.name = c("Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" ),
time.day.abb = c("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"),
time.am.pm = c("AM", "PM"),
time.century = 1930,
time.zone = "GMT",
time.out.format = "%02m/%02d/%04Y %02H:%02M:%02S.%03N",
time.out.format.notime = "%02m/%02d/%04Y",
time.in.format = "%m[/][.]%d[/][,]%y [%H[:%M[:%S[.%N]]][%p][[(]%3Z[)]]]",
tspan.out.format = "%dd %Hh %Mm %Ss %NMS",
tspan.in.format = "[%yy[ear[s]][,]] [%dd[ay[s]][,]] [%Hh[our[s]][,]] [%Mm[in[ute][s]][,]] [%Ss[ec[ond][s]][,]] [%NM[s][S]]"
) |
setMethod(
"plot",
signature="facelayer",
definition=function(x,projargs=NULL,col="heat",border=NA, alpha=NULL, frame=FALSE,legend=TRUE, breaks=NULL, inclusive=TRUE, discrete=FALSE, ...){
actGrid<-get(x@grid)
checkLinkedGrid(actGrid, x)
if(!is.null(breaks)){
if(!is.numeric(breaks)) stop("The 'breaks' argument has to be numeric.")
if(length(breaks)<3) stop("You need to provide at least three values to the 'breaks' argument.")
}
if(!is.null(alpha)){
if(length(alpha)>1) stop("Only one 'alpha' value is permitted.")
}
if(suppressWarnings(is.na(actGrid@sp))){
stop(paste("Slot @sp in the linked grid \'",x@grid, "\' is empty.", sep=""))
}
if(!is.null(projargs)){
if(requireNamespace("rgdal", quietly = TRUE)){
actGrid@sp<-sp::spTransform(actGrid@sp, projargs)
} else{
stop("The rgdal package is required to appropriately project this object. ")
}
}
if(sum(x@names%in%rownames(actGrid@faces))!=length(x))
stop("The facenames in the linked grid does not match the facelayer object.")
if(class(x@values)%in%c("integer","double", "numeric")){
if(length(unique(x@values[!is.na(x@values)]))==1){
x@values<-as.logical(x@values)
}
}
if(is.logical(x@values)){
x@values[x@values==FALSE]<-NA
}
boolPresent1<-rep(T,nrow(actGrid@faces))
if(length(x)!=nrow(actGrid@faces)){
boolPresent1<-rownames(actGrid@faces)%in%x@names
}
actSp<-actGrid@sp[boolPresent1]
boolPresent<-rep(T,length(x))
if(sum(is.na(x@values))>0){
boolPresent<-!is.na(x@values)
x@values<-x@values[boolPresent]
x@names<- x@names[boolPresent]
x@length <- sum(boolPresent)
}
actSp<-actSp[boolPresent]
if(class(x@values)=="logical"){
if(length(col)==1) if(col=="heat") col <- "
plot(actSp,col=col,border=border,...)
}
if(class(x@values)%in%c("integer","double", "numeric")){
if(is.null(breaks)){
minimum <- min(x@values)
maximum <- max(x@values)
steps <- length(x)+1
useBreaks <- seq(minimum, maximum,length.out=steps)
}else{
minimum <- min(breaks)
maximum <- max(breaks)
useBreaks <- breaks
}
bMax <- FALSE
bMin <- FALSE
if(inclusive){
beyondMax <- which(x@values>maximum)
if(length(beyondMax)>1){
x@values[beyondMax] <- maximum
bMax <- TRUE
}
beyondMin <- which(x@values<minimum)
if(length(beyondMin)>1){
x@values[beyondMin] <- minimum
bMin <- TRUE
}
}
if(length(col)==1){
if(col=="heat"){
cols <- rev(grDevices::heat.colors(length(useBreaks)-1))
cols<-substring(cols, 1,7)
}else{
if(length(col)==1){
stop("You specified only one color.")
}
}
} else{
ramp<-grDevices::colorRampPalette(col, bias=2, space="Lab")
cols <- ramp(length(useBreaks)-1)
}
alreadyCut <- base::cut(x@values, breaks=useBreaks, include.lowest=TRUE)
trans2 <- as.numeric(alreadyCut)
faceColors<-cols[trans2]
if(is.character(border)){
if(length(unique(border))==1){
if(substring(border[1], 1,1)=="
border=paste(border, alpha,sep="")
}
}
}
faceColors<-paste(faceColors, alpha, sep="")
if(legend){
graphics::par(mar=c(2,2,2,8))
}
addArgs<-list(...)
addArgs$tick.text<-NULL
addArgs$ticks<-NULL
addArgs$tick.cex<-NULL
addArgs$barWidth<-NULL
addArgs$barHeight<-NULL
addArgs$tickLength<-NULL
addArgs$xBot<-NULL
firstArgs<-list(
x=actSp,
col=faceColors,
border=border
)
plotArgs<-c(firstArgs, addArgs)
do.call(plot, plotArgs)
if(legend){
oldRef<-graphics::par()
oldRef$cin<-NULL
oldRef$cra<-NULL
oldRef$cxy<-NULL
oldRef$din<-NULL
oldRef$page<-NULL
oldRef$csi<-NULL
graphics::par(usr=c(0,100,0,100))
graphics::par(xpd=NA)
graphics::par(mar=c(2,2,2,2))
addArgs<-list(...)
addArgs$axes<-NULL
addArgs$add<-NULL
if(!discrete){
tickLabs <- useBreaks
}else{
tickLabs <- (useBreaks+useBreaks[2:(length(useBreaks)+1)])/2
tickLabs <- tickLabs[!is.na(tickLabs)]
}
firstArgs<-list(
cols=cols,
vals=tickLabs,
add=TRUE,
xLeft=101,
bounds=c(bMin, bMax)
)
heatArgs<-c(firstArgs, addArgs)
suppressWarnings(
do.call(heatMapLegend, heatArgs)
)
graphics::par(oldRef)
}
}
if(class(x@values)=="character" & !sum(x@values%in%grDevices::colors())==x@length){
colorAll <- grDevices::colors()[grep('gr(a|e)y', grDevices::colors(), invert = TRUE)]
active<-factor(x@values)
if(length(levels(active))>length(colorAll)){
cols<-sample(colorAll, length(levels(active)), replace=TRUE)
}else{
cols<-sample(colorAll, length(levels(active)), replace=FALSE)
}
faceColors<-cols[as.numeric(active)]
if(is.character(border)){
if(length(unique(border))==1){
if(substring(border[1], 1,1)=="
border=paste(border, alpha,sep="")
}
}
}
faceColors<-paste(faceColors, alpha, sep="")
}
if(class(x@values)=="character" & sum(x@values%in%grDevices::colors())==x@length){
faceColors<-paste(x@values, alpha, sep="")
}
if(class(x@values)=="character"){
addArgs<-list(...)
addArgs$tick.text<-NULL
addArgs$ticks<-NULL
addArgs$tick.cex<-NULL
addArgs$barWidth<-NULL
addArgs$barHeight<-NULL
addArgs$tickLength<-NULL
addArgs$xBot<-NULL
firstArgs<-list(
x=actSp,
col=faceColors,
border=border
)
plotArgs<-c(firstArgs, addArgs)
do.call(plot, plotArgs)
}
if(frame){
plot(actSp, border="black", add=TRUE)
}
}
) |
DIGITS <- 2
.onAttach <- function(libname, pkgname){
parallelism_message <- "Use plan(multisession) to set up parallel processing"
package_ver <- utils::packageDescription("spatialwarnings",
fields = "Version")
devel_message <- ""
if ( grepl("99$", package_ver, perl = TRUE) ) {
devel_message <- " (development version, use at your own risk!)"
}
packageStartupMessage({
paste0("This is spatialwarnings ",
package_ver, devel_message,
"\n", parallelism_message)
}, appendLF = TRUE)
}
theme_spwarnings <- function() {
lightgray <- "
lightgray_darker <- "
lightgray_lighter <- "
theme_bw() +
theme(panel.grid.major = element_line(color = lightgray_darker,
linetype = 2,
size = .3),
panel.grid.minor = element_blank(),
strip.background = element_rect(fill = NA, color = NA),
panel.border = element_rect(color = lightgray))
}
linescale_spwarnings <- function() {
scale_color_manual(values = c('
}
fillscale_spwarnings <- function(...) {
scale_fill_manual(..., values = c("
} |
getComments <- function(id, token, verbose=TRUE){
url <- paste0("https://api.instagram.com/v1/media/", id,
"/comments")
content <- callAPI(url, token)
l <- length(content$data)
if (verbose) message(l, " comments")
if (length(content$data)==0){
stop("Error. No comments?")
}
df <- commentsListToDF(content$data)
return(df)
} |
Yprice = c(80.13, 79.57, 79.93, 81.69, 80.82, 81.02)
Xprice = c(72.86, 72.88, 71.72, 71.54, 71, 71.78)
data = data.frame(Yprice, Xprice)
plot(y=data$Yprice, x=data$Xprice)
LinearR.lm = lm(Yprice ~ Xprice, data = data)
coef(LinearR.lm)
LinearR.lm
summary(LinearR.lm)$r.squared |
library(clifro)
takaka.df = structure(list(name = c("Takaka, Kotinga Road", "Riwaka At Takaka Hill",
"Takaka Pohara", "Takaka At Harwoods", "Takaka At Kotinga", "Takaka @ Canaan",
"Upper Takaka 2", "Takaka Ews", "Takaka Aero Raws", "Takaka, Kotinga 2",
"Upper Takaka", "Takaka,Patons Rock", "Takaka,Kotinga 1", "Takaka Aero",
"Takaka Hill", "Takaka,Bu Bu", "Takaka"), network = c("F02882",
"O12090", "F02884", "F15292", "F15291", "F0299A", "F12083", "F02885",
"O00957", "F02883", "F12082", "F02772", "F02971", "F02871", "F12081",
"F02872", "F02881"), agent = c(3788L, 44046L, 3790L, 44050L,
44051L, 44072L, 11519L, 23849L, 41196L, 3789L, 7316L, 3779L,
3794L, 3785L, 3833L, 3786L, 3787L), start = structure(c(18273600,
316263600, 520516800, 570020400, 704030400, 760014000, 805464000,
1020081600, 1439294400, 502110000, 688820400, -7992000, -255182400,
-1046692800, -704894400, -1159875000, -2082886200), class = c("POSIXct",
"POSIXt"), tzone = "NZ"), end = structure(c(1597665600, 1597665600,
1597665600, 1597665600, 1597665600, 1597665600, 1597665600, 1597665600,
1597665600, 1341057600, 720442800, 157719600, 49809600, 7732800,
-320932800, -760190400, -1333452600), class = c("POSIXct", "POSIXt"
), tzone = "NZ"), open = c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE), distance = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA), lat = c(-40.872, -41.03192, -40.845,
-41.03094, -40.87068, -40.93987, -41.01516, -40.86364, -40.81531,
-40.882, -41.051, -40.789, -40.9, -40.816, -41.017, -40.85, -40.817
), lon = c(172.809, 172.84439, 172.867, 172.79802, 172.808, 172.90821,
172.82582, 172.80568, 172.7765, 172.801, 172.833, 172.757, 172.775,
172.772, 172.867, 172.733, 172.8)), class = "data.frame", row.names = c(NA,
-17L))
new("cfStation", takaka.df)
takaka.df = structure(list(name = c("Takaka, Kotinga Road", "Riwaka At Takaka Hill",
"Takaka Pohara", "Takaka At Harwoods", "Takaka At Kotinga", "Takaka @ Canaan",
"Upper Takaka 2", "Takaka Ews", "Takaka Aero Raws"), network = c("F02882",
"O12090", "F02884", "F15292", "F15291", "F0299A", "F12083", "F02885",
"O00957"), agent = c(3788L, 44046L, 3790L, 44050L, 44051L, 44072L,
11519L, 23849L, 41196L), start = structure(c(18273600, 316263600,
520516800, 570020400, 704030400, 760014000, 805464000, 1020081600,
1439294400), class = c("POSIXct", "POSIXt"), tzone = "NZ"), end = structure(c(1597665600,
1597665600, 1597665600, 1597665600, 1597665600, 1597665600, 1597665600,
1597665600, 1597665600), class = c("POSIXct", "POSIXt"), tzone = "NZ"),
open = c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE), distance = c(NA, NA, NA, NA, NA, NA, NA, NA, NA),
lat = c(-40.872, -41.03192, -40.845, -41.03094, -40.87068,
-40.93987, -41.01516, -40.86364, -40.81531), lon = c(172.809,
172.84439, 172.867, 172.79802, 172.808, 172.90821, 172.82582,
172.80568, 172.7765)), class = "data.frame", row.names = c(NA,
-9L))
new("cfStation", takaka.df)
xx.df = structure(list(name = c("Takaka, Kotinga Road", "Takaka Pohara",
"Takaka Ews", "Aorere At Salisbury Bridge", "Takaka, Kotinga 2",
"Nelson,Mckay Hut", "Gouland Downs", "Golden Bay,Table Hl I",
"Golden Bay,Table Hl 2", "Tarakohe", "Takaka Aero", "Totaranui",
"Takaka,Bu Bu", "Takaka", "Quartz Ranges"), network = c("F02882",
"F02884", "F02885", "F02854", "F02883", "F02821", "F02831", "F02852",
"F02853", "F02891", "F02871", "F02892", "F02872", "F02881", "F02851"
), agent = c(3788L, 3790L, 23849L, 44020L, 3789L, 3780L, 3781L,
3783L, 3784L, 3791L, 3785L, 3792L, 3786L, 3787L, 3782L), start = structure(c(18273600,
520516800, 1020081600, 1311595200, 502110000, 417960000, 467982000,
233928000, 233928000, -1188819000, -1046692800, -410270400, -1159875000,
-2082886200, -2177494200), class = c("POSIXct", "POSIXt"), tzone = "NZ"),
end = structure(c(1597665600, 1597665600, 1597665600, 1597665600,
1341057600, 745416000, 745416000, 690807600, 690807600, 599569200,
7732800, -294667200, -760190400, -1333452600, -2125049400
), class = c("POSIXct", "POSIXt"), tzone = "NZ"), open = c(TRUE,
TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE), distance = c(NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), lat = c(-40.872,
-40.845, -40.86364, -40.80236, -40.882, -40.89, -40.892,
-40.807, -40.807, -40.825, -40.816, -40.823, -40.85, -40.817,
-40.867), lon = c(172.809, 172.867, 172.80568, 172.53328,
172.801, 172.213, 172.351, 172.556, 172.556, 172.898, 172.772,
173.002, 172.733, 172.8, 172.517)), class = "data.frame", row.names = c(NA,
-15L))
new("cfStation", xx.df)
open.queenstown.stations.df = dget(system.file("extdata", "queenStations", package = "clifro"))
open.queenstown.stations = new("cfStation", open.queenstown.stations.df)
takaka.town.df = structure(list(name = c("Takaka, Kotinga Road", "Takaka Pohara",
"Anatoki At Happy Sams", "Takaka At Kotinga", "Takaka Ews", "Motupiko At Reillys Bridge",
"Takaka Aero Raws"), network = c("F02882", "F02884", "F15293",
"F15291", "F02885", "F1529M", "O00957"), agent = c(3788L, 3790L,
44015L, 44051L, 23849L, 44041L, 41196L), start = structure(c(18273600,
520516800, 657284400, 704030400, 1020081600, 1164711600, 1439294400
), class = c("POSIXct", "POSIXt"), tzone = "NZ"), end = structure(c(1598788800,
1598788800, 1598788800, 1598788800, 1598788800, 1598788800, 1598788800
), class = c("POSIXct", "POSIXt"), tzone = "NZ"), open = c(TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE), distance = c(2.6, 5.7, 5.8,
2.4, 1.6, 2.7, 4.3), lat = c(-40.872, -40.845, -40.88587, -40.87068,
-40.86364, -40.85607, -40.81531), lon = c(172.809, 172.867, 172.74982,
172.808, 172.80568, 172.83162, 172.7765)), class = "data.frame", row.names = c(NA,
-7L))
takaka.town.st = new("cfStation", takaka.town.df)
takaka.town.st[, -c(8, 9)]
takaka.town.st[order(takaka.town.st$distance), -c(8, 9)]
hourly.rain.dt = new("cfDatatype"
, dt_name = "Precipitation"
, dt_type = "Rain (fixed periods)"
, dt_sel_option_names = list("Hourly")
, dt_sel_combo_name = NA_character_
, dt_param = structure("ls_ra,1,2,3,4", .Names = "dt1")
, dt_sel_option_params = list(structure("182", .Names = "prm2"))
, dt_selected_options = list(2)
, dt_option_length = 4
)
hourly.rain.dt
kaitaia.df = structure(list(name = c("Kaitaia Aero Ews", "Trounson Cws", "Russell Cws",
"Kaikohe Aws", "Purerua Aws", "Cape Reinga Aws", "Kerikeri Aerodrome Aws",
"Kaitaia Ews", "Dargaville 2 Ews", "Kerikeri Ews"), network = c("A53026",
"A53762", "A54212", "A53487", "A54101", "A42462", "A53295", "A53127",
"A53987", "A53191"), agent = c(18183L, 37131L, 41262L, 1134L,
1196L, 1002L, 37258L, 17067L, 25119L, 1056L), start = structure(c(960984000,
1244030400, 1459771200, 500727600, 788871600, 788871600, 1214395200,
913806000, 1067425200, 1025179200), class = c("POSIXct", "POSIXt"
), tzone = "NZ"), end = structure(c(1598702400, 1598702400, 1598702400,
1598616000, 1598616000, 1598616000, 1598616000, 1598443200, 1598011200,
1597924800), class = c("POSIXct", "POSIXt"), tzone = "NZ"), open = c(TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE), distance = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA), lat = c(-35.0677, -35.72035,
-35.26835, -35.4172, -35.129, -34.42963, -35.262, -35.13352,
-35.93145, -35.183), lon = c(173.2874, 173.65153, 174.136, 173.8229,
174.015, 172.68186, 173.911, 173.26294, 173.85317, 173.926)), class = "data.frame", row.names = c(NA,
-10L))
kaitaia.st = new("cfStation", kaitaia.df)
my.composite.search = takaka.town.st + kaitaia.st
my.composite.search
transform(my.composite.search, ndays = round(end - start))[, c(1, 10)] |
blockoptwrt <- function(fn,optsw,opt_xt=optsw[2],
opt_a=optsw[4],opt_x=optsw[4],
opt_samps=optsw[1],opt_inds=optsw[5]){
fprintf(fn,'==============================================================================\n')
fprintf(fn,'Optimization of design parameters\n\n')
if((opt_samps)){
fprintf(fn,'* Optimize Samples per subject\n')
}
if((opt_xt)){
fprintf(fn,'* Optimize Sampling Schedule\n')
}
if((opt_x)){
fprintf(fn,'* Optimize Discrete variables\n')
}
if((opt_a)){
fprintf(fn,'* Optimize Covariates\n')
}
if((opt_inds)){
fprintf(fn,'* Optimize Number of individuals per group\n')
}
fprintf(fn,'\n')
return( )
} |
print.clv.fitted.transactions.static.cov <- function(x, digits = max(3L, getOption("digits") - 3L), ...){
NextMethod()
cat("Constraints: ", [email protected], "\n")
cat("Regularization: ", [email protected], "\n")
invisible(x)
}
summary.clv.fitted.transactions.static.cov <- function(object, ...){
res <- NextMethod()
class(res) <- c("summary.clv.fitted.transactions.static.cov", class(res))
res$additional.options <- c(res$additional.options,
"Regularization"[email protected])
if([email protected]){
res$additional.options <- c(res$additional.options,
" lambda.life" = [email protected],
" lambda.trans" = [email protected])
}
res$additional.options <- c(res$additional.options,
"Constraint covs" = [email protected])
if([email protected]){
res$additional.options <- c(res$additional.options,
" Constraint params" = paste([email protected], collapse = ", "))
}
return(res)
}
coef.clv.fitted.transactions.static.cov <- function(object, ...){
original.scale.coef.model <- NextMethod()
last.row.optimx.coef <- tail(coef([email protected]),n=1)
if([email protected]){
names.prefixed.covs <- union([email protected],
union([email protected],
[email protected]))
}else{
names.prefixed.covs <- union([email protected],
[email protected])
}
names.prefixed.covs <- na.omit(names.prefixed.covs)
prefixed.params.cov <- last.row.optimx.coef[1, names.prefixed.covs, drop=TRUE]
prefixed.params.cov <- setNames(prefixed.params.cov, names.prefixed.covs)
original.scale.params.cov <- clv.model.backtransform.estimated.params.cov(clv.model = [email protected],
prefixed.params.cov = prefixed.params.cov)
original.scale.params.cov <- setNames(original.scale.params.cov[names.prefixed.covs],
names.prefixed.covs)
names.original.named.prefixed.all <- names(original.scale.coef.model)
if(clv.model.estimation.used.correlation(clv.model = [email protected])){
names(names.original.named.prefixed.all) <- c([email protected]@names.prefixed.params.model,
[email protected]@name.prefixed.cor.param.m)
}else{
names(names.original.named.prefixed.all) <- [email protected]@names.prefixed.params.model
}
names.original.named.prefixed.all <- c(names.original.named.prefixed.all,
setNames(names(original.scale.params.cov),
names(original.scale.params.cov)))
names.optimx.coefs <- colnames(last.row.optimx.coef)
names.original.named.prefixed.all <- names.original.named.prefixed.all[names.optimx.coefs]
params.all <- c(original.scale.coef.model, original.scale.params.cov)
return(params.all[names.original.named.prefixed.all])
}
setMethod(f = "show", signature = signature(object="clv.fitted.transactions.static.cov"), definition = function(object){
print(x=object)}) |
context("Ensuring that the `cols_label()` function works as expected")
tbl <-
dplyr::tribble(
~col_1, ~col_2, ~col_3, ~col_4,
767.6, 928.1, 382.0, 674.5,
403.3, 461.5, 15.1, 242.8,
686.4, 54.1, 282.7, 56.3,
662.6, 148.8, 984.6, 928.1,
198.5, 65.1, 127.4, 219.3,
132.1, 118.1, 91.2, 874.3,
349.7, 307.1, 566.7, 542.9,
63.7, 504.3, 152.0, 724.5,
105.4, 729.8, 962.4, 336.4,
924.2, 424.6, 740.8, 104.2)
check_suggests <- function() {
skip_if_not_installed("rvest")
skip_if_not_installed("xml2")
}
selection_value <- function(html, key) {
selection <- paste0("[", key, "]")
html %>%
rvest::html_nodes(selection) %>%
rvest::html_attr(key)
}
selection_text <- function(html, selection) {
html %>%
rvest::html_nodes(selection) %>%
rvest::html_text()
}
test_that("the function `cols_label()` works correctly", {
check_suggests()
tbl_html <-
gt(tbl) %>%
cols_label(
col_1 = "col_a",
col_2 = "col_b",
col_3 = "col_c",
col_4 = "col_d"
)
tbl_html %>%
.$`_boxh` %>%
.$column_label %>%
unlist() %>%
expect_equal(c("col_a", "col_b", "col_c", "col_d"))
tbl_html %>%
render_as_html() %>%
xml2::read_html() %>%
selection_text("[class='gt_col_heading gt_columns_bottom_border gt_right']") %>%
expect_equal(c("col_a", "col_b", "col_c", "col_d"))
tbl_html <-
gt(tbl) %>%
cols_label()
tbl_html %>%
.$`_boxh` %>%
.$var %>%
unlist() %>%
expect_equal(colnames(tbl))
tbl_html %>%
.$`_boxh` %>%
.$column_label %>%
unlist() %>%
expect_equal(colnames(tbl))
tbl_html %>%
render_as_html() %>%
xml2::read_html() %>%
selection_text("[class='gt_col_heading gt_columns_bottom_border gt_right']") %>%
expect_equal(c("col_1", "col_2", "col_3", "col_4"))
tbl_html <-
gt(tbl) %>%
cols_label(
.list = list(
col_1 = "col_a",
col_2 = "col_b",
col_3 = "col_c",
col_4 = "col_d")
)
tbl_html %>%
.$`_boxh` %>%
.$column_label %>%
unlist() %>%
expect_equal(c("col_a", "col_b", "col_c", "col_d"))
tbl_html %>%
render_as_html() %>%
xml2::read_html() %>%
selection_text("[class='gt_col_heading gt_columns_bottom_border gt_right']") %>%
expect_equal(c("col_a", "col_b", "col_c", "col_d"))
expect_error(
gt(tbl) %>%
cols_label("col_a"))
expect_error(
gt(tbl) %>%
cols_label(col_a = "col_1"))
expect_error(
regexp = NA,
dplyr::tribble(
~a , ~d,
1, 4,
5, 8
) %>%
gt() %>%
cols_label(
a = "label a",
d = "label d"
)
)
expect_error(
regexp = NA,
dplyr::tribble(
~a , ~dat,
1, 4,
5, 8
) %>%
gt() %>%
cols_label(
a = "label a",
dat = "label dat"
)
)
expect_error(
dplyr::tribble(
~a , ~.dat,
1, 4,
5, 8
) %>%
gt() %>%
cols_label(
a = "label a",
.dat = "label dat"
)
)
}) |
convolveUnitStep <- function(k, x, irfpar) {
m <- matrix(0, nrow=length(x), ncol=length(k))
step1 <- matrix(0, nrow=length(x), ncol=length(irfpar))
for(j in 1:length(irfpar))
step1[,j] <- unitstep(x-irfpar[j])
for(i in 1:length(k)) {
dec <- exp(k[i]*x)
for(j in 1:length(irfpar)) {
s1 <- if(j%%2==0) -1 else 1
s2 <- -1 * s1
decj <- exp(k[i]*irfpar[j])
m[,i] <- m[,i] +
(( s1 * dec + s2 * decj) * step1[,j]) +
((-1 + decj) * unitstep(- irfpar[j]))
}
m[,i] <- m[,i] * exp(-k[i]*x) * (1/k[i])
}
m
} |
readLandmarks.csv <- function(file, x, y=2:4, rownames=NULL, header=TRUE, dec=".", sep=";")
{
xlen <- length(x)
ylen <- length(y)
arr <- matrix(NA, xlen, ylen)
if (is.factor(x))
x <- as.character(x)
if (is.character(x)) {
data <- read.table(file, header=header,dec=dec,sep=sep)
dat <- NULL
count <- 1
if (is.null(rownames))
stop("please specify column containing Landmark names!")
rn <- data[,rownames]
for (j in 1:length(x)) {
check <- which(rn==x[j])
if (length(check) == 0) {
warning(paste("dataset misses entry for Landmark",j))
data[99999, y] <- rep(NA,ylen)
dat[count] <- 99999
}
if (length(check) > 1) {
warning(paste("dataset contains landmark
dat[count] <- check[1]
} else {
empty <- which(rn==x[j])
if (length(empty) !=0)
dat[count] <- which(rn==x[j])
}
count <- count+1
}
arr <- as.matrix(data[dat,y])
rown <- x
} else {
data <- read.table(file,header=header,dec=dec,sep=sep)
arr <- as.matrix(data[x,y])
if (is.null(rownames))
rown <- c(1:xlen)
else
rown <- data[x,rownames]
}
nas0 <- which(is.na(arr))
nas1 <- as.integer(nas0/(xlen*ylen))+1
nas <- nas1[-(which(duplicated(nas1)))]
if (length(nas) > 0) {
for (i in 1:length(nas)) {
nas2 <- nas0[which(nas1==nas[i])]%%(xlen*ylen)
nas2 <- nas2%%xlen
nas2 <- nas2[-which(duplicated(nas2))]
if (0 %in% nas2)
{nas2[which(nas2==0)] <- xlen}
if (length(nas2) > 0)
nas2 <- sort(nas2)
}
} else
nas2 <- NULL
dimnames(arr) <- list(rown,c("X","Y","Z"))
return(list(LM=arr,NAs=nas2))
} |
"qqplot.gld.bi" <-
function (data, fit, param1, param2, len = 10000, name = "",
corner = "topleft", type = "", range = c(0, 1), xlab = "",
main = "")
{
q <- seq(0, 1, length = len)
minr<-min(range)
maxr<-max(range)
first.len <- len * fit[9]
second.len <- len - first.len
first.q <- seq(0, 1, length = first.len)
second.q <- seq(0, 1, length = second.len)
theo.quantile <- sort(c(qgl(first.q, fit[1], fit[2], fit[3],
fit[4], param1), qgl(second.q, fit[5], fit[6], fit[7],
fit[8], param2)))
fitted.q <- (theo.quantile[!is.inf(theo.quantile)])
qq<-fit[9]*pgl(fitted.q,fit[1:4],param=param1)+(1-fit[9])*pgl(fitted.q,
fit[5:8],param=param2)
fitted.q<-fitted.q[qq>=minr & qq<=maxr]
qq<-qq[qq>=minr & qq<=maxr]
data.q <- quantile(data, prob = qq)
if (type == "") {
if (is.na(xlab) == TRUE) {
xlab = "Quantile"
}
if (is.na(main) == TRUE) {
main = paste("Quantile plot for", name)
}
plot(qq, data.q, xlab = xlab, ylab = "Data values", main = main,
xlim = c(minr, maxr), ylim = c(min(fitted.q, data.q), max(fitted.q,
data.q)), col = 1, type = "l")
lines(qq, fitted.q, col = 6)
legend(corner, c("Data", "Fitted Distribution"), col = c(1,
6), lty = 1)
}
if (type == "str.qqplot") {
if ((xlab) == "") {
xlab = "Data"
}
if ((main) == "") {
main = paste("Quantile plot for", name)
}
qqplot(data.q, fitted.q, xlab = xlab,
ylab = "Theoretical", main = main)
abline(0, 1, col = 2)
}
} |
pcscorebootstrapdata <- function(dat, bootrep, statistic, bootmethod = c("st", "sm", "mvn", "stiefel", "meboot"), smo)
{
dat = t(dat)
n = dim(dat)[1]
p = dim(dat)[2]
boot = matrix(, p, bootrep)
bootdataarray = array(, dim = c(p, n, bootrep))
data = scale(dat, center = TRUE, scale = FALSE)
meandata = matrix(rep(as.matrix(colMeans(dat)), n), p, n)
dummy = svd(data)
U = dummy$u
D = diag(dummy$d)
V = dummy$v
if(bootmethod == "st")
{
for(b in 1:bootrep)
{
drawU = U[sample(1:n, n, replace = TRUE), ]
bootdata = t(drawU%*%D%*%t(V)) + meandata
bootdataarray[,,b] = bootdata
boot[,b] = centre(bootdata, type = statistic)
}
}
if(bootmethod == "sm")
{
for(b in 1:bootrep)
{
drawU = U[sample(1:n, n, replace = TRUE), ] + mvrnorm(n, rep(0, min(p, n)), var(U) * smo)
bootdata = t(drawU%*%D%*%t(V)) + meandata
bootdataarray[,,b] = bootdata
boot[,b] = centre(bootdata, type = statistic)
}
}
if(bootmethod == "mvn")
{
for(b in 1:bootrep)
{
drawU <- mvrnorm(n, colMeans(U), var(U))
bootdata = t(drawU%*%D%*%t(V)) + meandata
bootdataarray[,,b] = bootdata
boot[,b] = centre(bootdata, type = statistic)
}
}
if(bootmethod == "stiefel")
{
for(b in 1:bootrep)
{
X <- mvrnorm(n, colMeans(U), var(U))
tmp <- eigen(t(X)%*%X)
drawU = (X%*%(tmp$vec%*%sqrt(diag(1/tmp$val))%*%t(tmp$vec)))[sample(1:n,n,replace=TRUE),]
bootdata = t(drawU%*%D%*%t(V)) + meandata
bootdataarray[,,b] = bootdata
boot[,b] = centre(bootdata, type = statistic)
}
}
if(bootmethod == "meboot")
{
out <- meboot::meboot(ts(as.numeric(U),start=1,end=n*(min(n,p))), reps = bootrep)
for(b in 1:bootrep)
{
drawU = matrix(out$ensemble[,b], n, min(n,p))
bootdata = t(drawU%*%D%*%t(V)) + meandata
bootdataarray[,,b] = bootdata
boot[,b] = centre(bootdata, type = statistic)
}
}
return(list(bootdata = bootdataarray, meanfunction = boot))
} |
buildPedsExtra = function(labs, sex, extra = 0, ageMat = NULL, knownPO = NULL, allKnown = FALSE,
notPO = NULL, noChildren = NULL, connected = TRUE,
maxLinearInb = Inf, sexSymmetry = TRUE, verbose = FALSE) {
st = Sys.time()
N = length(labs)
Ntot = N + extra
sex = c(sex, rep(0L, extra))
knownPO_long = lapply(1:Ntot, function(i)
unlist(lapply(knownPO, function(p) if(max(p) == i) min(p))))
notPO_long = lapply(1:Ntot, function(i)
unlist(lapply(notPO, function(p) if(max(p) == i) min(p))))
y = unname(ageMat[, "younger"])
o = unname(ageMat[, "older"])
ageList = lapply(1:N, function(i) list(younger = y[o == i], older = o[y == i]))
if(verbose) cat("\nBuilding pedigree list:\n")
a1 = adjMatrix(sex = sex[1], connected = TRUE)
attr(a1, "anc") = list(1L)
Mlist = list(a1)
addFUN = function(a, k) {
addIndividual(a, addedSex = sex[k], origN = N, final = k == Ntot,
connected = connected, knownPO = knownPO_long[[k]], notPO = notPO_long[[k]],
ageList = ageList[1:k], noChildren = noChildren, maxLinearInb = maxLinearInb)
}
for(k in 1 + seq_len(N-1)) {
Mlist = unlist(lapply(Mlist, function(a) addFUN(a, k)), recursive = FALSE)
if(verbose && k < N)
cat(sprintf(" First %d: %d candidates (%s)\n", k, length(Mlist), ftime(st)))
}
ALLSOLS = validSolutions(Mlist, connected = connected)
if(verbose)
cat(sprintf(" All %d + 0 extra: %d solutions | %d candidates (%s)\n",
N, length(ALLSOLS), length(Mlist), ftime(st)))
if(extra) {
intermediate = vector("list", length = extra)
for(ex in seq_len(extra)) {
k = N + ex
Mlist = unlist(lapply(Mlist, function(a) addFUN(a, k)), recursive = FALSE)
nCand0 = length(Mlist)
Mlist = removeDuplicates(Mlist, sexSymmetry)
intermediate[[ex]] = validSolutions(Mlist, N, connected)
if(verbose) {
nCand = length(Mlist)
cat(sprintf(" All %d + %d extra: %d solutions | %d candidates | %d duplicates removed (%s)\n",
N, ex, length(intermediate[[ex]]), nCand, nCand0 - nCand, ftime(st)))
}
}
ALLSOLS = c(ALLSOLS, unlist(intermediate, recursive = FALSE))
}
if(verbose)
cat("Total solutions:", length(ALLSOLS), "\nConverting to ped\n")
peds = lapply(ALLSOLS, function(a) adj2ped(addMissingParents1(a), labs))
if(verbose)
cat("Total time:", ftime(st))
invisible(peds)
}
addIndividual = function(a, addedSex, origN, final, connected = FALSE,
knownPO = NULL, notPO = NULL, ageList = NULL,
noChildren = NULL, maxLinearInb = Inf) {
if(addedSex == 0L) {
addedMale = addIndividual(a, 1L, origN = origN, final = final, connected = connected,
knownPO = knownPO, notPO = notPO, ageList = ageList,
noChildren = noChildren, maxLinearInb = maxLinearInb)
addedFemale = addIndividual(a, 2L, origN = origN, final = final, connected = connected,
knownPO = knownPO, notPO = notPO, ageList = ageList,
noChildren = noChildren, maxLinearInb = maxLinearInb)
return(c(addedMale, addedFemale))
}
n = dim(a)[1]
k = n + 1
extra = n >= origN
checkAge = length(ageList) > 0
thisAge = ageList[[k]]
checkInb = maxLinearInb < Inf
prev = seq_len(n)
sex = attr(a, "sex")
mal = which(sex == 1)
fem = which(sex == 2)
excludeAsParent = c(notPO, noChildren, thisAge$younger)
potentialFa = c(0, .mysetdiff(mal, excludeAsParent, makeUnique = FALSE))
potentialMo = c(0, .mysetdiff(fem, excludeAsParent, makeUnique = FALSE))
if(k %in% noChildren)
potentialCh = integer(0)
else {
excludeAsChild = c(notPO, thisAge$older)
missingParent = switch(addedSex,
which(.colSums(a[mal, , drop = F], length(mal), n) == 0),
which(.colSums(a[fem, , drop = F], length(fem), n) == 0))
potentialCh = .mysetdiff(missingParent, excludeAsChild, makeUnique = FALSE)
}
len = length(potentialFa) * length(potentialMo) * 2^length(potentialCh)
RES = vector("list", length = len)
aExt = c(rbind(a, rep(FALSE, n)), rep(FALSE, n + 1))
dim(aExt) = c(k, k)
sexExt = as.integer(c(sex, addedSex))
tmpA = newAdjMatrix(aExt, sex = sexExt)
tmpAnc = attr(a, "anc")
length(tmpAnc) = k
i = 0
for(fa in potentialFa) for(mo in potentialMo) {
par = c(fa, mo)
par = par[par > 0]
npar = length(par)
if(maxLinearInb == 0 && npar == 2 && any(a[par, par]))
next
if(npar == 0)
parAnc = integer(0)
else if(npar == 1)
parAnc = tmpAnc[[par]]
else
parAnc = unique.default(c(tmpAnc[[par[1]]], tmpAnc[[par[2]]]))
potCh = .mysetdiff(potentialCh, parAnc, makeUnique = FALSE)
known = .mysetdiff(knownPO, par, makeUnique = FALSE)
if(!all(known %in% potCh))
next
for(chs in powerset(potCh, force = known)) {
if(final && extra && (length(chs) == 0 || (length(chs) == 1 && npar == 0)))
next
if(maxLinearInb == 0 && any(a[c(par, chs), c(par, chs)]))
next
newA = tmpA
newA[par, k] = TRUE
newA[k, chs] = TRUE
if(checkInb && linearInb2(newA, minDist = maxLinearInb + 1))
next
if(extra) {
hasLonely = hasLonelyExtras(newA, origN)
if(final && hasLonely)
next
attr(newA, "hasLonely") = hasLonely
}
if(final || k >= origN) {
isConn = isConnected(newA)
if(final && connected && !isConn)
next
attr(newA, "connected") = isConn
}
if(!final || checkAge) {
newAnc = tmpAnc
newAnc[[k]] = c(k, parAnc)
isDesc = vapply(prev, function(d)
!(d %in% par) && (d %in% chs || any(chs %in% newAnc[[d]])), logical(1))
desc = which(isDesc)
if(length(parAnc))
newAnc[desc] = lapply(newAnc[desc], function(v) unique.default(c(v, k, parAnc)))
else
newAnc[desc] = lapply(newAnc[desc], function(v) c(v, k))
attr(newA, "anc") = newAnc
}
if(checkAge && ageViol(newA, newAnc, ageList))
next
if(extra && k > origN + 1)
newA = canonicalPerm(newA, origN)
RES[[i+1]] = newA
i = i+1
}
}
length(RES) = i
RES
}
hasLonelyExtras = function(a, N) {
Ntot = dim(a)[1]
Nex = Ntot - N
if(Nex == 0)
return(FALSE)
extraCh = .rowSums(a[N + seq_len(Nex), , drop = FALSE], Nex, Ntot)
if(any(extraCh == 0))
return(TRUE)
extraPar = .colSums(a[, N + seq_len(Nex), drop = FALSE], Ntot, Nex)
if(any(extraPar == 0 & extraCh == 1))
return(TRUE)
FALSE
}
canonicalPerm = function(a, N) {
n = dim(a)[1]
if(n <= N + 1)
return(a)
Nseq = seq_len(N)
exSeq = N + seq_len(n - N)
sex = attr(a, "sex")
block1 = lapply(Nseq, function(i) a[exSeq, i])
block2 = lapply(Nseq, function(i) a[i, exSeq])
args = c(block1, block2, list(sex[exSeq], decreasing = TRUE, method = "shell"))
ord = do.call(order, args)
p = c(Nseq, N + ord)
a[] = a[p, p]
attr(a, "sex") = sex[p]
if(!is.null(anc <- attr(a, "anc"))) {
pAnc = lapply(anc[p], function(v) match(v, p))
attr(a, "anc") = pAnc
}
a
}
removeDuplicates = function(DA, sexSymmetry) {
if(sexSymmetry)
dups = duplicated.default(lapply(DA, as.integer))
else
dups = duplicated.default(lapply(DA, function(da) c(as.integer(da), attr(da, "sex"))))
DA[!dups]
}
validSolutions = function(DA, checkLonely = FALSE, connected = FALSE) {
if(length(DA) == 0)
return(DA)
if(checkLonely) {
DA = DA[!sapply(DA, attr, "hasLonely")]
if(length(DA) == 0)
return(DA)
}
if(connected) {
DA = DA[sapply(DA, attr, "connected")]
if(length(DA) == 0)
return(DA)
}
DA
}
ageViol = function(a, anc, ageList) {
for(i in 1:dim(a)[1]) {
y = ageList[[i]]$younger
if(length(y) && any(y %in% anc[[i]]))
return(TRUE)
}
return(FALSE)
} |
if (requiet("emmeans") && requiet("insight") && requiet("testthat")) {
test_that("emmeans", {
m <- glm(am ~ factor(cyl),
family = binomial(), data = mtcars
)
EList <- emmeans::emmeans(m, pairwise ~ cyl, type = "resp")
E <- emmeans::emmeans(m, ~cyl, type = "resp")
C <- emmeans::contrast(E, method = "pairwise")
expect_equal(find_statistic(EList), "z-statistic")
expect_equal(get_statistic(EList)$Statistic, c(1.449, -0.377, -2.346, 1.243, 2.717, 1.393), tolerance = 0.001)
expect_equal(get_statistic(EList)$Statistic[1:3], get_statistic(E)$Statistic, tolerance = 0.001)
expect_equal(get_statistic(EList)$Statistic[4:6], get_statistic(C)$Statistic, tolerance = 0.001)
expect_equal(get_parameters(EList)$Estimate, c(0.727, 0.429, 0.143, 3.556, 16, 4.5), tolerance = 0.001)
})
} |
swap_funct_robust <- function(vect_arch_ini, rss_arch_ini, huge = 200, numArchoid, x_gvv, n, PM, prob){
vect_arch_end <- vect_arch_ini
rss <- rss_arch_ini
for (l in 1:numArchoid) {
rss1 <- c()
setpossibles <- setdiff(1:n,vect_arch_ini)
for (i in setpossibles) {
zs <- x_gvv[,c(i,vect_arch_ini[-l])]
zs <- as.matrix(zs)
alphas <- matrix(0, nrow = numArchoid, ncol = n)
for (j in 1:n) {
alphas[, j] = coef(nnls(zs, x_gvv[,j]))
}
resid <- zs[1:(nrow(zs) - 1),] %*% alphas - x_gvv[1:(nrow(x_gvv) - 1),]
rss1[i] <- frobenius_norm_funct_robust(resid, PM, prob) / n
if (rss1[i] < rss) {
rss <- rss1[i]
vect_arch_end = c(i,vect_arch_ini[-l])
}
}
}
if (numArchoid == 1) {
result <- swap2_k1_funct_robust(vect_arch_end, vect_arch_ini, rss, huge, numArchoid, x_gvv, n, PM, prob)
}else{
result <- swap2_funct_robust(vect_arch_end, vect_arch_ini, rss, huge, numArchoid, x_gvv, n, PM, prob)
}
return(result)
}
swap2_funct_robust <- function(vect_arch_end, vect_arch_ini, rss, huge = 200, numArchoid, x_gvv, n, PM, prob){
vect_arch_ini_aux <- vect_arch_ini
vect_arch_end_aux <- vect_arch_end
rss_aux <- rss
vect_arch_end2 <- c()
while (any(sort(vect_arch_end_aux) != sort(vect_arch_ini_aux))) {
se <- setdiff(vect_arch_end_aux,vect_arch_ini_aux)
se1 <- setdiff(vect_arch_end_aux,se)
for (l in 1:length(se1)) {
rss1 <- c()
comp <- c(se,se1[-l])
setpossibles <- setdiff(1:n,vect_arch_end_aux)
for (i in setpossibles) {
zs <- x_gvv[,c(i,comp)]
zs <- as.matrix(zs)
alphas <- matrix(0, nrow = numArchoid, ncol = n)
for (j in 1:n) {
alphas[, j] = coef(nnls(zs, x_gvv[,j]))
}
resid <- zs[1:(nrow(zs) - 1),] %*% alphas - x_gvv[1:(nrow(x_gvv) - 1),]
rss1[i] <- frobenius_norm_funct_robust(resid, PM, prob) / n
if (rss1[i] < rss_aux) {
rss_aux <- rss1[i]
vect_arch_end2 <- c(i,comp)
}
}
}
if (is.null(vect_arch_end2)) {
vect_arch_end_aux <- vect_arch_end_aux
vect_arch_ini_aux <- vect_arch_end_aux
}else{
vect_arch_ini_aux <- vect_arch_end_aux
vect_arch_end_aux <- vect_arch_end2
}
}
zs <- x_gvv[,vect_arch_end_aux]
zs <- as.matrix(zs)
alphas_def <- matrix(0, nrow = numArchoid, ncol = n)
for (j in 1:n) {
alphas_def[, j] = coef(nnls(zs, x_gvv[,j]))
}
resid_def <- zs[1:(nrow(zs) - 1),] %*% alphas_def - x_gvv[1:(nrow(x_gvv) - 1),]
return(list(cases = vect_arch_end_aux, rss = rss_aux, archet_ini = vect_arch_ini,
alphas = alphas_def, resid = resid_def))
}
swap2_k1_funct_robust <- function(vect_arch_end, vect_arch_ini, rss, huge=200, numArchoid, x_gvv, n, PM, prob){
vect_arch_ini_aux <- vect_arch_ini
vect_arch_end_aux <- vect_arch_end
rss_aux <- rss
vect_arch_end2 <- c()
while (vect_arch_end_aux != vect_arch_ini_aux) {
rss1 <- c()
setpossibles <- setdiff(1:n,vect_arch_end_aux)
for (i in setpossibles) {
zs <- x_gvv[,i]
zs <- as.matrix(zs)
alphas <- matrix(0, nrow = numArchoid, ncol = n)
for (j in 1:n) {
alphas[, j] = coef(nnls(zs, x_gvv[,j]))
}
resid <- zs[1:(nrow(zs) - 1),] %*% alphas - x_gvv[1:(nrow(x_gvv) - 1),]
rss1[i] <- frobenius_norm_funct_robust(resid, PM, prob) / n
if (rss1[i] < rss_aux) {
rss_aux <- rss1[i]
vect_arch_end2 = i
}
}
if (is.null(vect_arch_end2)) {
vect_arch_end_aux <- vect_arch_end_aux
vect_arch_ini_aux <- vect_arch_end_aux
}else{
vect_arch_ini_aux <- vect_arch_end_aux
vect_arch_end_aux <- vect_arch_end2
}
}
zs <- x_gvv[,vect_arch_end_aux]
zs <- as.matrix(zs)
alphas_def <- matrix(0, nrow = numArchoid, ncol = n)
for (j in 1:n) {
alphas_def[, j] = coef(nnls(zs, x_gvv[,j]))
}
resid_def <- zs[1:(nrow(zs) - 1),] %*% alphas_def - x_gvv[1:(nrow(x_gvv) - 1),]
return(list(cases = vect_arch_end_aux, rss = rss_aux, archet_ini = vect_arch_ini,
alphas = alphas_def, resid = resid_def))
} |
aggregate.escalc <- function(x, cluster, time, V, struct="CS", rho, phi, weighted=TRUE, fun, na.rm=TRUE, subset, select, digits, ...) {
mstyle <- .get.mstyle("crayon" %in% .packages())
.chkclass(class(x), must="escalc")
if (any(!is.element(struct, c("ID","CS","CAR","CS+CAR"))))
stop(mstyle$stop("Unknown 'struct' specified."))
if (length(na.rm) == 1L)
na.rm <- c(na.rm, na.rm)
k <- nrow(x)
mf <- match.call()
mf.V <- mf[[match("V", names(mf))]]
mf.cluster <- mf[[match("cluster", names(mf))]]
mf.time <- mf[[match("time", names(mf))]]
mf.subset <- mf[[match("subset", names(mf))]]
V <- eval(mf.V, x, enclos=sys.frame(sys.parent()))
cluster <- eval(mf.cluster, x, enclos=sys.frame(sys.parent()))
time <- eval(mf.time, x, enclos=sys.frame(sys.parent()))
subset <- eval(mf.subset, x, enclos=sys.frame(sys.parent()))
if (is.null(cluster))
stop(mstyle$stop("Must specify 'cluster' variable."))
if (anyNA(cluster))
stop(mstyle$stop("No missing values allowed in 'cluster' variable."))
if (length(cluster) != k)
stop(mstyle$stop(paste0("Length of variable specified via 'cluster' (", length(cluster), ") does not match length of data (", k, ").")))
ucluster <- unique(cluster)
n <- length(ucluster)
if (!is.null(attr(x, "vi.names"))) {
vi.name <- attr(x, "vi.names")[1]
} else {
if (!is.element("vi", names(x)))
stop(mstyle$stop("Cannot determine name of the 'vi' variable."))
vi.name <- "vi"
}
if (is.null(x[[vi.name]]))
stop(mstyle$stop("Cannot find 'vi' variable in data frame."))
if (is.null(V)) {
vi <- x[[vi.name]]
if (struct=="ID")
R <- diag(1, nrow=k, ncol=k)
if (is.element(struct, c("CS","CS+CAR"))) {
if (missing(rho))
stop(mstyle$stop("Must specify 'rho' for this var-cov structure."))
if (length(rho) == 1L)
rho <- rep(rho, n)
if (length(rho) != n)
stop(mstyle$stop(paste0("Length of 'rho' (", length(rho), ") does not match the number of clusters (", n, ").")))
if (any(rho > 1) || any(rho < -1))
stop(mstyle$stop("Value(s) of 'rho' must be in [-1,1]."))
}
if (is.element(struct, c("CAR","CS+CAR"))) {
if (missing(phi))
stop(mstyle$stop("Must specify 'phi' for this var-cov structure."))
if (length(phi) == 1L)
phi <- rep(phi, n)
if (length(phi) != n)
stop(mstyle$stop(paste0("Length of 'phi' (", length(phi), ") does not match the number of clusters (", n, ").")))
if (any(phi > 1) || any(phi < 0))
stop(mstyle$stop("Value(s) of 'phi' must be in [0,1]."))
if (is.null(time))
stop(mstyle$stop("Must specify 'time' variable for this var-cov structure."))
if (length(time) != k)
stop(mstyle$stop(paste0("Length of variable specified via 'time' (", length(time), ") does not match length of data (", k, ").")))
}
if (struct=="CS") {
R <- matrix(0, nrow=k, ncol=k)
for (i in 1:n) {
R[cluster == ucluster[i], cluster == ucluster[i]] <- rho[i]
}
}
if (struct == "CAR") {
R <- matrix(0, nrow=k, ncol=k)
for (i in 1:n) {
R[cluster == ucluster[i], cluster == ucluster[i]] <- outer(time[cluster == ucluster[i]], time[cluster == ucluster[i]], function(x,y) phi[i]^(abs(x-y)))
}
}
if (struct == "CS+CAR") {
R <- matrix(0, nrow=k, ncol=k)
for (i in 1:n) {
R[cluster == ucluster[i], cluster == ucluster[i]] <- rho[i] + (1 - rho[i]) * outer(time[cluster == ucluster[i]], time[cluster == ucluster[i]], function(x,y) phi[i]^(abs(x-y)))
}
}
diag(R) <- 1
S <- diag(sqrt(as.vector(vi)), nrow=k, ncol=k)
V <- S %*% R %*% S
} else {
if (.is.vector(V)) {
if (length(V) == 1L)
V <- rep(V, k)
if (length(V) != k)
stop(mstyle$stop(paste0("Length of 'V' (", length(V), ") does not match length of data frame (", k, ").")))
V <- diag(as.vector(V), nrow=k, ncol=k)
}
if (is.data.frame(V))
V <- as.matrix(V)
if (!is.null(dimnames(V)))
V <- unname(V)
if (!.is.square(V))
stop(mstyle$stop("'V' must be a square matrix."))
if (!isSymmetric(V))
stop(mstyle$stop("'V' must be a symmetric matrix."))
if (nrow(V) != k)
stop(mstyle$stop(paste0("Dimensions of 'V' (", nrow(V), "x", ncol(V), ") do not match length of data frame (", k, ").")))
for (i in 1:n) {
if (any(abs(V[cluster == ucluster[i], cluster != ucluster[i]]) >= .Machine$double.eps, na.rm=TRUE))
warning(mstyle$warning(paste0("Estimates in cluster '", ucluster[i], "' appear to have non-zero covariances with estimates belonging to a different cluster.")), call.=FALSE)
}
}
if (!is.null(attr(x, "yi.names"))) {
yi.name <- attr(x, "yi.names")[1]
} else {
if (!is.element("yi", names(x)))
stop(mstyle$stop("Cannot determine name of the 'yi' variable."))
yi.name <- "yi"
}
if (is.null(x[[yi.name]]))
stop(mstyle$stop("Cannot find 'yi' variable in data frame."))
yi <- as.vector(x[[yi.name]])
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=k)
x <- x[subset,,drop=FALSE]
yi <- yi[subset]
V <- V[subset,subset,drop=FALSE]
cluster <- cluster[subset]
k <- nrow(x)
ucluster <- unique(cluster)
n <- length(ucluster)
if (k == 0L)
stop(mstyle$stop("Processing terminated since k == 0."))
}
if (na.rm[1]) {
has.na <- is.na(yi) | .anyNAv(V)
not.na <- !has.na
if (any(has.na)) {
x <- x[not.na,]
yi <- yi[not.na]
V <- V[not.na,not.na,drop=FALSE]
cluster <- cluster[not.na]
}
k <- nrow(x)
ucluster <- unique(cluster)
n <- length(ucluster)
if (k == 0L)
stop(mstyle$stop("Processing terminated since k == 0."))
}
all.pd <- TRUE
for (i in 1:n) {
Vi <- V[cluster == ucluster[i], cluster == ucluster[i]]
if (!anyNA(Vi) && any(eigen(Vi, symmetric=TRUE, only.values=TRUE)$values <= .Machine$double.eps)) {
all.pd <- FALSE
warning(mstyle$warning(paste0("'V' appears to be not positive definite in cluster ", ucluster[i], ".")), call.=FALSE)
}
}
if (!all.pd)
stop(mstyle$stop("Cannot aggregate estimates with a non-positive-definite 'V' matrix."))
yi.agg <- rep(NA_real_, n)
vi.agg <- rep(NA_real_, n)
for (i in 1:n) {
Vi <- V[cluster == ucluster[i], cluster == ucluster[i]]
if (weighted) {
Wi <- try(chol2inv(chol(Vi)), silent=FALSE)
if (inherits(Wi, "try-error"))
stop(mstyle$stop(paste0("Cannot take inverse of 'V' in cluster ", ucluster[i], ".")))
sumWi <- sum(Wi)
yi.agg[i] <- sum(Wi %*% cbind(yi[cluster == ucluster[i]])) / sumWi
vi.agg[i] <- 1 / sumWi
} else {
ki <- sum(cluster == ucluster[i])
yi.agg[i] <- sum(yi[cluster == ucluster[i]]) / ki
vi.agg[i] <- sum(Vi) / ki^2
}
}
if (!missing(fun)) {
if (!is.list(fun) || length(fun) != 3 || any(sapply(fun, function(f) !is.function(f))))
stop(mstyle$stop("Argument 'fun' must be a list of functions of length 3."))
fun1 <- fun[[1]]
fun2 <- fun[[2]]
fun3 <- fun[[3]]
} else {
fun1 <- function(x) {
m <- mean(x, na.rm=na.rm[2])
if (is.nan(m)) NA else m
}
fun2 <- fun1
fun3 <- function(x) {
if (na.rm[2]) {
tab <- table(na.omit(x))
} else {
tab <- table(x, useNA="ifany")
}
val <- tail(names(sort(tab)), 1)
if (is.null(val)) NA else val
}
}
fcluster <- factor(cluster, levels=ucluster)
xsplit <- split(x, fcluster)
xagg <- lapply(xsplit, function(xi) {
tmp <- lapply(xi, function(xij) {
if (inherits(xij, c("numeric","integer"))) {
fun1(xij)
} else if (inherits(xij, c("logical"))) {
fun2(xij)
} else {
fun3(xij)
}
})
as.data.frame(tmp)
})
xagg <- do.call(rbind, xagg)
facs <- sapply(x, is.factor)
if (any(facs)) {
for (j in which(facs)) {
xagg[[j]] <- factor(xagg[[j]])
}
}
xagg[which(names(xagg) == yi.name)] <- yi.agg
xagg[which(names(xagg) == vi.name)] <- vi.agg
measure <- attr(x[[yi.name]], "measure")
if (is.null(measure))
measure <- "GEN"
attr(xagg[[yi.name]], "measure") <- measure
attr(xagg, "yi.names") <- yi.name
attr(xagg, "vi.names") <- vi.name
if (!missing(digits)) {
attr(xagg, "digits") <- .get.digits(digits=digits, xdigits=attr(x, "digits"), dmiss=FALSE)
} else {
attr(xagg, "digits") <- attr(x, "digits")
}
if (is.null(attr(xagg, "digits")))
attr(xagg, "digits") <- 4
class(xagg) <- c("escalc", "data.frame")
if (!missing(select)) {
nl <- as.list(seq_along(x))
names(nl) <- names(x)
sel <- eval(substitute(select), nl, parent.frame())
xagg <- xagg[,sel,drop=FALSE]
}
rownames(xagg) <- NULL
return(xagg)
} |
ISOProductionSeries <- R6Class("ISOProductionSeries",
inherit = ISOSeries,
private = list(
xmlElement = "DS_ProductionSeries",
xmlNamespacePrefix = "GMD"
),
public = list(
initialize = function(xml = NULL){
super$initialize(xml = xml)
}
)
) |
b_wincred_protocol_version <- "1.0.0"
b_wincred_i_get <- function(target) {
.Call(keyring_wincred_get, target)
}
b_wincred_i_set <- function(target, password, username = NULL,
session = FALSE) {
username <- username %||% getOption("keyring_username")
.Call(keyring_wincred_set, target, password, username, session)
}
b_wincred_i_delete <- function(target) {
.Call(keyring_wincred_delete, target)
}
b_wincred_i_exists <- function(target) {
.Call(keyring_wincred_exists, target)
}
b_wincred_i_enumerate <- function(filter) {
.Call(keyring_wincred_enumerate, filter)
}
b_wincred_i_escape <- function(x) {
if (is.null(x)) x else URLencode(x)
}
b_wincred_i_unescape <- function(x) {
URLdecode(x)
}
b_wincred_target <- function(keyring, service, username) {
username <- username %||% getOption("keyring_username")
keyring <- if (is.null(keyring)) "" else b_wincred_i_escape(keyring)
service <- b_wincred_i_escape(service)
username <- if (is.null(username)) "" else b_wincred_i_escape(username)
paste0(keyring, ":", service, ":", username)
}
b_wincred_i_parse_target <- function(target) {
parts <- lapply(strsplit(target, ":"), lapply, b_wincred_i_unescape)
extract <- function(x, i) x[i][[1]] %||% ""
res <- data.frame(
stringsAsFactors = FALSE,
keyring = vapply(parts, extract, "", 1),
service = vapply(parts, extract, "", 2),
username = vapply(parts, extract, "", 3)
)
}
b_wincred_target_keyring <- function(keyring) {
b_wincred_target(keyring, "", "")
}
b_wincred_target_lock <- function(keyring) {
b_wincred_target(keyring, "", "unlocked")
}
b_wincred_parse_keyring_credential <- function(target) {
value <- rawToChar(b_wincred_i_get(target))
con <- textConnection(value)
on.exit(close(con), add = TRUE)
as.list(read.dcf(con)[1,])
}
b_wincred_write_keyring_credential <- function(target, data) {
con <- textConnection(NULL, open = "w")
mat <- matrix(unlist(data), nrow = 1)
colnames(mat) <- names(data)
write.dcf(mat, con)
value <- paste0(paste(textConnectionValue(con), collapse = "\n"), "\n")
close(con)
b_wincred_i_set(target, password = charToRaw(value))
}
b_wincred_get_encrypted_aes <- function(str) {
r <- openssl::base64_decode(str)
structure(tail(r, -16), iv = head(r, 16))
}
b_wincred_unlock_keyring_internal <- function(keyring, password = NULL) {
target_lock <- b_wincred_target_lock(keyring)
if (b_wincred_i_exists(target_lock)) {
openssl::base64_decode(rawToChar(b_wincred_i_get(target_lock)))
} else {
target_keyring <- b_wincred_target_keyring(keyring)
keyring_data <- b_wincred_parse_keyring_credential(target_keyring)
if (is.null(password)) {
message("keyring ", sQuote(keyring), " is locked, enter password to unlock")
password <- get_pass()
if (is.null(password)) stop("Aborted unlocking keyring")
}
aes <- openssl::sha256(charToRaw(password), key = keyring_data$Salt)
verify <- b_wincred_get_encrypted_aes(keyring_data$Verify)
tryCatch(
openssl::aes_cbc_decrypt(verify, key = aes),
error = function(e) stop("Invalid password, cannot unlock keyring")
)
b_wincred_i_set(
target_lock, charToRaw(openssl::base64_encode(aes)), session = TRUE)
aes
}
}
b_wincred_is_locked_keyring_internal <- function(keyring) {
target_lock <- b_wincred_target_lock(keyring)
! b_wincred_i_exists(target_lock)
}
backend_wincred <- R6Class(
"backend_wincred",
inherit = backend_keyrings,
public = list(
name = "windows credential store",
initialize = function(keyring = NULL)
b_wincred_init(self, private, keyring),
get = function(service, username = NULL, keyring = NULL)
b_wincred_get(self, private, service, username, keyring),
get_raw = function(service, username = NULL, keyring = NULL)
b_wincred_get_raw(self, private, service, username, keyring),
set = function(service, username = NULL, keyring = NULL,
prompt = "Password: ")
b_wincred_set(self, private, service, username, keyring, prompt),
set_with_value = function(service, username = NULL, password = NULL,
keyring = NULL)
b_wincred_set_with_value(self, private, service, username, password,
keyring),
set_with_raw_value = function(service, username = NULL, password = NULL,
keyring = NULL)
b_wincred_set_with_value(self, private, service, username, password,
keyring),
delete = function(service, username = NULL, keyring = NULL)
b_wincred_delete(self, private, service, username, keyring),
list = function(service = NULL, keyring = NULL)
b_wincred_list(self, private, service, keyring),
keyring_create = function(keyring, password = NULL)
b_wincred_keyring_create(self, private, keyring, password),
keyring_list = function()
b_wincred_keyring_list(self, private),
keyring_delete = function(keyring = NULL)
b_wincred_keyring_delete(self, private, keyring),
keyring_lock = function(keyring = NULL)
b_wincred_keyring_lock(self, private, keyring),
keyring_unlock = function(keyring = NULL, password = NULL)
b_wincred_keyring_unlock(self, private, keyring, password),
keyring_is_locked = function(keyring = NULL)
b_wincred_keyring_is_locked(self, private, keyring),
keyring_default = function()
b_wincred_keyring_default(self, private),
keyring_set_default = function(keyring = NULL)
b_wincred_keyring_set_default(self, private, keyring),
docs = function() {
modifyList(super$docs(), list(
. = "Store secrets in the Windows Credential Store."
))
}
),
private = list(
keyring = NULL,
keyring_create_direct = function(keyring, password)
b_wincred_keyring_create_direct(self, private, keyring, password)
)
)
b_wincred_init <- function(self, private, keyring) {
private$keyring <- keyring
invisible(self)
}
b_wincred_get <- function(self, private, service, username, keyring) {
password <- self$get_raw(service, username, keyring)
encoding <- get_encoding_opt()
b_wincred_decode(password, encoding = encoding)
}
b_wincred_get_raw <- function(self, private, service, username, keyring) {
keyring <- keyring %||% private$keyring
target <- b_wincred_target(keyring, service, username)
password <- b_wincred_i_get(target)
if (! is.null(keyring)) {
aes <- b_wincred_unlock_keyring_internal(keyring)
enc <- b_wincred_get_encrypted_aes(rawToChar(password))
password <- openssl::aes_cbc_decrypt(enc, key = aes)
}
password
}
b_wincred_decode <- function(password, encoding = 'auto') {
if (encoding == 'auto') {
b_wincred_decode_auto(password)
} else {
password <- iconv(list(password), from = encoding, to = "")
password
}
}
b_wincred_decode_auto <- function(password) {
if (any(password == 0)) {
password <- iconv(list(password), from = "UTF-16LE", to = "")
if (is.na(password)) {
stop("Key contains embedded null bytes, use get_raw()")
}
password
} else {
rawToChar(password)
}
}
b_wincred_set <- function(self, private, service, username, keyring, prompt) {
password <- get_pass(prompt)
if (is.null(password)) stop("Aborted setting keyring key")
b_wincred_set_with_value(self, private, service, username, password,
keyring)
invisible(self)
}
b_wincred_set_with_value <- function(self, private, service,
username, password, keyring) {
encoding <- get_encoding_opt()
if (encoding != 'auto') {
password <- enc2utf8(password)
password <- iconv(x = password, from = 'UTF-8', to = encoding, toRaw = TRUE)[[1]]
} else {
password <- charToRaw(password)
}
b_wincred_set_with_raw_value(self, private, service, username, password, keyring)
}
b_wincred_set_with_raw_value <- function(self, private, service,
username, password, keyring) {
keyring <- keyring %||% private$keyring
target <- b_wincred_target(keyring, service, username)
if (is.null(keyring)) {
b_wincred_i_set(target, password, username = username)
return(invisible(self))
}
target_keyring <- b_wincred_target_keyring(keyring)
aes <- b_wincred_unlock_keyring_internal(keyring)
enc <- openssl::aes_cbc_encrypt(password, key = aes)
password <- charToRaw(openssl::base64_encode(c(attr(enc, "iv"), enc)))
b_wincred_i_set(target, password = password, username = username)
invisible(self)
}
b_wincred_delete <- function(self, private, service, username, keyring) {
keyring <- keyring %||% private$keyring
target <- b_wincred_target(keyring, service, username)
b_wincred_i_delete(target)
invisible(self)
}
b_wincred_list <- function(self, private, service, keyring) {
keyring <- keyring %||% private$keyring
filter <- if (is.null(service)) {
paste0(b_wincred_i_escape(keyring), ":*")
} else {
paste0(b_wincred_i_escape(keyring), ":",
b_wincred_i_escape(service), ":*")
}
list <- b_wincred_i_enumerate(filter)
list <- grep("(::|::unlocked)$", list, value = TRUE, invert = TRUE)
parts <- b_wincred_i_parse_target(list)
data.frame(
service = parts$service,
username = parts$username,
stringsAsFactors = FALSE
)
}
b_wincred_keyring_create <- function(self, private, keyring, password) {
password <- password %||% get_pass()
if (is.null(password)) stop("Aborted craeting keyring")
private$keyring_create_direct(keyring, password)
invisible(self)
}
b_wincred_keyring_create_direct <- function(self, private, keyring,
password) {
target_keyring <- b_wincred_target_keyring(keyring)
if (b_wincred_i_exists(target_keyring)) {
stop("keyring ", sQuote(keyring), " already exists")
}
salt <- openssl::base64_encode(openssl::rand_bytes(32))
aes <- openssl::sha256(charToRaw(password), key = salt)
verify <- openssl::aes_cbc_encrypt(openssl::rand_bytes(15), key = aes)
verify <- openssl::base64_encode(c(attr(verify, "iv"), verify))
dcf <- list(
Version = b_wincred_protocol_version,
Verify = verify,
Salt = salt
)
b_wincred_write_keyring_credential(target_keyring, dcf)
b_wincred_unlock_keyring_internal(keyring, password)
invisible(self)
}
b_wincred_keyring_list <- function(self, private) {
list <- b_wincred_i_enumerate("*")
parts <- b_wincred_i_parse_target(list)
default <- ! paste0(parts$keyring, "::") %in% list
if (length(list) > 0 && any(default)) {
parts$username[default] <-
paste0(parts$service[default], ":", parts$username[default])
parts$service[default] <- parts$keyring[default]
parts$keyring[default] <- ""
}
res <- data.frame(
stringsAsFactors = FALSE,
keyring = unname(unique(parts$keyring)),
num_secrets = as.integer(unlist(tapply(parts$keyring,
factor(parts$keyring, levels = unique(parts$keyring)), length,
simplify = FALSE))),
locked = vapply(unique(parts$keyring), FUN.VALUE = TRUE, USE.NAMES = FALSE,
function(x) {
! any(parts$username[parts$keyring == x] == "unlocked")
}
)
)
res$num_secrets <- res$num_secrets - (! res$locked) - (res$keyring != "")
if ("" %in% res$keyring) res$locked[res$keyring == ""] <- FALSE
res
}
b_wincred_keyring_delete <- function(self, private, keyring) {
self$confirm_delete_keyring(keyring)
keyring <- keyring %||% private$keyring
items <- self$list(keyring = keyring)
target_keyring <- b_wincred_target_keyring(keyring)
b_wincred_i_delete(target_keyring)
target_lock <- b_wincred_target_lock(keyring)
try(b_wincred_i_delete(target_lock), silent = TRUE)
for (i in seq_len(nrow(items))) {
target <- b_wincred_target(keyring, items$service[i],
items$username[i])
try(b_wincred_i_delete(target), silent = TRUE)
}
invisible()
}
b_wincred_keyring_lock <- function(self, private, keyring) {
keyring <- keyring %||% private$keyring
if (is.null(keyring)) {
warning("Cannot lock the default windows credential store keyring")
} else {
target_lock <- b_wincred_target_lock(keyring)
try(b_wincred_i_delete(target_lock), silent = TRUE)
invisible()
}
}
b_wincred_keyring_unlock <- function(self, private, keyring,
password = NULL) {
keyring <- keyring %||% private$keyring
if (is.null(password)) password <- get_pass()
if (is.null(password)) stop("Aborted unlocking keyring")
if (!is.null(keyring)) {
b_wincred_unlock_keyring_internal(keyring, password)
}
invisible()
}
b_wincred_keyring_is_locked <- function(self, private, keyring) {
keyring <- keyring %||% private$keyring
if (is.null(keyring)) {
FALSE
} else {
b_wincred_is_locked_keyring_internal(keyring)
}
}
b_wincred_keyring_default <- function(self, private) {
private$keyring
}
b_wincred_keyring_set_default <- function(self, private, keyring) {
private$keyring <- keyring
invisible(self)
} |
context("test-extract_row")
m <- matrix(c(TRUE, TRUE, FALSE, TRUE), nrow = 2) > 0
m <- as(m, "RsparseMatrix")
r <- extract_row_lgRMatrix(m, 1)
test_that("extract_row_lgRMatrix works", {
expect_equal(r, c(TRUE, FALSE))
})
m <- matrix(1:4, nrow = 2)
m <- as(m, "RsparseMatrix")
r <- extract_row_dgRMatrix(m, 1)
test_that("extract_row_dgRMatrix works", {
expect_equal(r, c(1, 3))
}) |
library(latticeExtra)
library(matrixTrellis)
data(apple, package="HH")
apple.aov.1 <- aov(yield ~ block + pre*treat, data=apple)
apple.aov.2 <- aov(yield ~ block + pre + treat, data=apple)
apple.aov.2b<- aov(yield ~ block + treat + pre, data=apple)
apple$yield.block.effect <- fitted(lm(yield ~ block, data=apple)) - mean(apple$yield)
apple$pre.block.effect <- fitted(lm(pre ~ block, data=apple)) - mean(apple$pre)
apple$yield.block <- apple$yield - apple$yield.block.effect
apple$pre.block <- apple$pre - apple$pre.block.effect
apple.ancova.3be<- ancovaplot(yield.block ~ treat*pre.block, data=apple,
groups=block, pch=letters[1:4], cex=1.4,
col.line=trellis.par.get()$superpose.symbol$col,
col.by.groups=TRUE)
apple.ancova.3be
apple.ancova.3bh<- ancovaplot(yield.block ~ treat*pre.block, data=apple,
col=c("red","green","purple","orange","blue","navyblue"),
pch=letters[1:6], cex=1.4,
col.line=trellis.par.get()$superpose.symbol$col,
col.by.groups=FALSE)
apple.ancova.3bh
apple.ancova.4 <- ancovaplot(yield.block ~ pre.block + treat, data=apple)
apple.aov.4 <- aov(yield.block ~ pre.block + treat, data=apple)
apple.ancova.6 <- ancovaplot(yield.block ~ treat, x=pre.block, data=apple)
apple$yield.block.pre <-
apple$yield.block -
predict.lm(apple.aov.4, type="terms", terms="pre.block")
apple.ancova.5 <- ancovaplot(yield.block.pre ~ treat, x=pre.block, data=apple)
apple.ancova.7 <- ancovaplot(yield.block ~ pre.block, groups=treat, data=apple)
apple.ancova.8b <- ancovaplot(yield ~ pre * treat, data=apple,
groups=block, pch=letters[1:4], cex=1.4,
col.line=trellis.par.get()$superpose.symbol$col,
condition=apple$treat)
apple.ancova.8b
apple7 <- do.call(c, list(a5 =apple.ancova.5,
a4 =apple.ancova.4,
a6 =apple.ancova.6,
a7 =apple.ancova.7,
a3be=apple.ancova.3be,
a8b=apple.ancova.8b,
layout=c(7, 6)))
apple7 <- update(apple7, scales=list(y=list(rot=0)))
apple7
apple7mt <- matrix.trellis(apple7, nrow=6, ncol=7, byrow=TRUE)
apple7mt$condlevels[[2]] <- c("5","4","6","7","3bd","8")
apple7mt$condlevels[[1]][7] <- "Superpose"
apple7mt
useOuterStrips(apple7mt)
combineLimits(apple7mt)
apple7uc <- useOuterStrips(combineLimits(apple7mt))
apple7uc
apple7ucr <- update(apple7uc, scales=list(
x=list(relation="same", at=7:11)))
apple7ucr
tmp <- apple7ucr$y.limits
dim(tmp) <- c(7,6)
tmp.range <- sapply(1:6, function(i) range(unlist(tmp[,i])))
for (i in 1:35) apple7ucr$y.limits[[i]] <- range(tmp.range[,-6])
for (i in 36:42) apple7ucr$y.limits[[i]] <- tmp.range[,6]
apple7ucr <- update(apple7ucr,
xlab="pre (adjusted as indicated)",
ylab="yield (adjusted as indicated)",
scales=list(
y=list(at=rep(list(c(200,250,300,350),
NULL,NULL,NULL,NULL,NULL,NULL), 6)),
x=list(alternating=1)),
xlab.top="Treatment")
apple7ucr
apple7ucrs <-
resizePanels(update(apple7ucr,
between=list(
x=c(.2,.2,.2,.2,.2,1),
y=c(.5,.2,.2,.2,1))),
h=c(rep(diff(apple7ucr$y.limits[[1]]), 5),
diff(apple7ucr$y.limits[[36]])))
apple7ucrs
apple7ucrs2 <- apple7ucrs
apple7ucrs2$condlevels[[2]] <-
c("y|bx~t","y|b~x|b+t","y|b~t","y|b~x|b","y|b~x|b*t","y~x*t")
apple7ucrs2 |
regrresidplot <- function(x, y, resid.plot=FALSE, fit.line=TRUE,
lm.object=lm(y~x),
x.name=names(lm.object$model)[2],
col=trellis.par.get()$plot.symbol$col,
col.yhat=NULL,
col.fit="gray80",
col.resid="gray40",
...) {
xyplot(y ~ x, resid.plot=resid.plot, fit.line=fit.line,
lm.object=lm.object, x.name=x.name,
col.fit=col.fit, col.resid=col.resid, ...,
panel=function(x, y, ..., resid.plot, fit.line, lm.object, x.name) {
panel.xyplot(x, y, ..., col=col, pch=19)
if (fit.line) {
newdata <- data.frame(x=cplx(101))
names(newdata)[1] <- x.name
newdata$y <- predict(lm.object, newdata=newdata)
panel.lines(newdata[[1]], newdata$y, col=col.fit, ...)
}
yhat <- fitted(lm.object)
if (!is.null(col.yhat))
panel.points(x, yhat, col=col.yhat, ..., pch=20)
panel.residSquare(x, y, yhat=yhat,
resid.plot=resid.plot, col=col.resid, ...)
})
}
panel.residSquare <- function(x, y, yhat, resid.plot=FALSE, col="black", ...) {
if (resid.plot==FALSE) return()
if (resid.plot=="square") {
xright <- x + convertUnit(unit(abs(yhat-y), "native"),
axisFrom="y", typeFrom="dimension",
unitTo="native",
axisTo="x", typeTo="dimension",
valueOnly=TRUE)
panel.rect(xleft=x, ybottom=y, xright, ytop=yhat, border=col, ...)
}
else
panel.segments(x, y, x, yhat, col=col, ...)
}
cplx <- function(length) {
xlim <- current.panel.limits()$xlim
scale(1:length, 1, (length-1)/diff(xlim)) + xlim[1]
} |
apa_print.BFBayesFactor <- function(
x
, iterations = 10000
, central_tendency = median
, hdi = 0.95
, standardized = FALSE
, ratio_subscript = "10"
, auto_invert = TRUE
, scientific = TRUE
, max = 1000
, min = 1 / max
, evidential_boost = NULL
, ...
) {
if(length(x) > 1) {
ellipsis <- list(...)
ellipsis$ratio_subscript <- ratio_subscript
ellipsis$auto_invert <- auto_invert
ellipsis$scientific <- scientific
ellipsis$max <- max
ellipsis$min <- min
bf <- c()
for(i in seq_along(x)) {
ellipsis$x <- x[i]
if(!is.null(evidential_boost)) ellipsis$evidential_boost <- evidential_boost[i]
bf[i] <- do.call("apa_print_bf", ellipsis)
}
bf <- as.list(bf)
names(bf) <- names(x)$numerator
} else bf <- apa_print_bf(x, ...)
apa_res <- apa_print_container()
apa_res$statistic <- bf
if(class(x@numerator[[1]]) %in% c("BFoneSample", "BFindepSample")) {
posterior_samples <- BayesFactor::posterior(x, index = 1, iterations = iterations)
apa_res$estimate <- bf_estimates(
x@numerator[[1]]
, posterior_samples
, central_tendency = central_tendency
, hdi = hdi
, standardized = standardized
)
}
apa_res$full_result <- paste0(apa_res$estimate, ", ", apa_res$statistic)
apa_res
}
apa_print.BFBayesFactorTop <- function(x, ...) {
x_BFBayesFactor <- BayesFactor::as.BFBayesFactor(x)
ellipsis <- list(...)
if(is.null(ellipsis$ratio_subscript)) ellipsis$ratio_subscript <- "01"
if(!is.null(ellipsis$evidential_boost)) evidential_boost <- ellipsis$evidential_boost
bf <- c()
for(i in seq_along(x_BFBayesFactor)) {
ellipsis$x <- x_BFBayesFactor[i]
if(!is.null(ellipsis$evidential_boost)) ellipsis$evidential_boost <- evidential_boost[i]
bf <- c(bf, do.call("apa_print_bf", ellipsis))
}
full_terms <- bf_term_labels(x@denominator)
full_terms <- bf_sort_terms(full_terms)
restricted_terms <- lapply(x@numerator, bf_term_labels)
restricted_terms <- lapply(restricted_terms, bf_sort_terms)
omitted_terms <- lapply(restricted_terms, function(x) full_terms[!full_terms %in% x])
names(bf) <- sanitize_terms(omitted_terms)
apa_res <- apa_print_container()
apa_res$statistic <- as.list(rev(bf))
apa_res
}
apa_print.BFBayesFactorList <- function(x, ...) {
bf <- vapply(x, apa_print_bf, as.character(as.vector(x[[1]])), ...)
names(bf) <- names(x)
apa_res <- apa_print_container()
apa_res$statistic <- as.list(bf)
apa_res
}
setMethod(f = "apa_print", signature = "BFBayesFactor", definition = apa_print.BFBayesFactor)
setMethod(f = "apa_print", signature = "BFBayesFactorTop", definition = apa_print.BFBayesFactorTop)
setMethod("apa_print", "BFBayesFactorList", apa_print.BFBayesFactorList)
apa_print_bf <- function(x, ...) {
UseMethod("apa_print_bf", x)
}
apa_print_bf.default <- function(x, ...) no_method(x)
apa_print_bf.numeric <- function(
x
, ratio_subscript = "10"
, auto_invert = TRUE
, escape = TRUE
, scientific = TRUE
, max = 1000
, min = 1 / max
, evidential_boost = NULL
, log = FALSE
, ...
) {
validate(x, check_NA = TRUE, check_infinite = FALSE)
validate(ratio_subscript, check_class = "character", check_length = 1)
validate(auto_invert, check_class = "logical", check_length = 1)
validate(scientific, check_class = "logical", check_length = 1)
validate(max, check_class = "numeric", check_length = 1)
validate(min, check_class = "numeric", check_length = 1)
if(!is.null(evidential_boost)) validate(evidential_boost, check_class = "numeric", check_length = length(x))
validate(log, check_class = "logical", check_length = 1)
ellipsis <- list(...)
ellipsis$x <- as.vector(x)
ellipsis$use_math <- FALSE
if(!is.null(evidential_boost)) {
ellipsis$x <- ellipsis$x * evidential_boost
}
if(auto_invert) {
to_invert <- ellipsis$x < 1
ellipsis$x[to_invert] <- 1 / ellipsis$x[to_invert]
ratio_subscript <- rep(ratio_subscript, length(x))
ratio_subscript[to_invert] <- invert_subscript(ratio_subscript)
}
if(escape) {
ratio_subscript <- paste0("\\textrm{", escape_latex(ratio_subscript), "}")
}
if(scientific & (ellipsis$x > max - 1 | ellipsis$x < min)) {
ellipsis$format <- "e"
if(is.null(ellipsis$digits)) ellipsis$digits <- 2
bf <- do.call("printnum", ellipsis)
bf <- typeset_scientific(bf)
} else {
if(is.null(ellipsis$zero)) ellipsis$zero <- FALSE
bf <- do.call("printnum", ellipsis)
}
bf_name <- if(!log) "BF" else "log BF"
bf <- paste0("$\\mathrm{", bf_name, "}_{", ratio_subscript, "} ", add_equals(bf), "$")
bf <- setNames(bf, names(x))
bf
}
apa_print_bf.BFBayesFactor <- function(x, ...) {
validate(as.vector(x), check_NA = TRUE)
bf <- apa_print_bf(as.vector(x))
bf <- setNames(bf, names(x@numerator))
bf
}
invert_subscript <- function(x) {
seperator <- if(nchar(x) == 2) "" else "/"
paste0(rev(unlist(strsplit(x, seperator))), collapse = seperator)
}
typeset_scientific <- function(x) {
x <- gsub("e\\+00$", "", x)
x <- gsub("e\\+0?(\\d+)$", " \\\\times 10\\^\\{\\1\\}", x)
x <- gsub("e\\-0?(\\d+)$", " \\\\times 10\\^\\{-\\1\\}", x)
x
}
bf_term_labels <- function(x) {
model_formula <- formula(x@identifier$formula)
attr(terms(model_formula), "term.labels")
}
bf_sort_terms <- function(x) {
sapply(strsplit(x, ":"), function(y) paste(sort(y), collapse = ":"))
}
setGeneric(
name = "bf_estimates"
, def = function(x, ...) standardGeneric("bf_estimates")
)
bf_estimates_ttest <- function(
x
, samples
, central_tendency = median
, hdi = 0.95
, standardized = FALSE
) {
validate(samples, check_class = "mcmc")
validate(central_tendency, check_class = "function")
validate(hdi, check_class = "numeric", check_length = 1, check_range = c(0, 1))
validate(standardized, check_class = "logical", check_length = 1)
if(standardized) {
estimate <- "delta"
est_name <- "d"
} else {
estimate <- ifelse(class(x) == "BFoneSample", "mu", "beta (x - y)")
est_name <- "M"
}
samples <- as.numeric(samples[, estimate])
est_mean <- central_tendency(samples)
est_hdi <- hd_int(samples, level = hdi)
estimate <- paste0("$", est_name, " = ", printnum(est_mean), "$ ", print_hdint(est_hdi))
estimate
}
suppressMessages(
setMethod(f = "bf_estimates", signature = "BFoneSample", definition = bf_estimates_ttest)
)
suppressMessages(
setMethod(f = "bf_estimates", signature = "BFindepSample", definition = bf_estimates_ttest)
) |
check_cqgate <- function(object) {
stopifnot(length(object@bits) == 2)
stopifnot(all(object@bits > 0))
stopifnot(length(object@bits) == length(unique(object@bits)))
}
setClass("cqgate",
representation(bits="integer",
gate="sqgate"),
prototype(bits=c(1L, 2L),
gate=Id(2L)),
validity=check_cqgate
)
cqgate <- function(bits=c(1L, 2L), gate=Id(2L)) {
return(methods::new("cqgate", bits=as.integer(bits), gate=gate))
}
setMethod("*", c("cqgate", "qstate"),
function(e1, e2) {
stopifnot(all(e1@bits > 0) && all(e1@bits <= e2@nbits))
bits <- e1@bits
nbits <- e2@nbits
res <- e2@coefs
al <- 0:(2^e2@nbits-1)
cb <- is.bitset(al, bit=bits[1])
ii <- is.bitset(al, bit=bits[2]) & cb
kk <- (!is.bitset(al, bit=bits[2])) & cb
res[kk] <- e1@gate@M[1,1]*e2@coefs[kk] + e1@gate@M[1,2]*e2@coefs[ii]
res[ii] <- e1@gate@M[2,1]*e2@coefs[kk] + e1@gate@M[2,2]*e2@coefs[ii]
circuit <- e2@circuit
ngates <- length(circuit$gatelist)
circuit$gatelist[[ngates+1]] <- list(type=e1@gate@type, bits=c(e1@bits, NA))
if(e1@gate@type == "Rx" || e1@gate@type == "Ry" || e1@gate@type == "Rz" || grepl("^R[0-9]+", e1@gate@type))
circuit$gatelist[[ngates+1]]$angle <- Arg(e1@gate@M[2,2])
circuit$gatelist[[ngates+1]]$controlled <- TRUE
return(qstate(nbits=nbits, coefs=as.complex(res), basis=e2@basis, circuit=circuit))
}
) |
plot_bars_and_hoops <- function(x,y,Name,R,colours = c('orange','darkgreen','red'),lwds = c(2,2,2),number_sites=-1,first='n'){
par(mfrow=c(1,2))
plot_bar_chart(Name,R,number_sites=number_sites,first=first,colours=c(colours[3],colours[2]))
class(x) = "hoops"
class(y) = "hoops"
plot(x,y,Name,R,colours = colours,lwds = lwds, number_sites=number_sites,first=first)
par(mfrow=c(1,1))
} |
tree_to_labels <- function(tr, remove_quotes = TRUE) {
n_right <- unlist(gregexpr("\\)", tr))
n_left <- unlist(gregexpr("\\(", tr))
if (n_right[1] == -1) n_right <- 0 else n_right <- length(n_right)
if (n_left[1] == -1) n_left <- 0 else n_left <- length(n_left)
if (!identical(n_right, n_left)) {
stop("invalid newick string, numbers of ( and ) don't match")
}
tr <- gsub("\\s+", "", tr)
tr <- gsub(":[0-9]+(\\.[0-9]+)?", "", tr)
if (n_right < 1) {
tip_lbl <- gsub(";$", "", tr)
edge_lbl <- character(0)
} else {
edge_lbl <- unlist(strsplit(tr, ")"))
edge_lbl <- grep("^[^\\(]", edge_lbl, value = T)
edge_lbl <- gsub("(,|;).*$", "", edge_lbl)
edge_lbl <- edge_lbl[nzchar(edge_lbl)]
tip_lbl <- unlist(strsplit(tr, ","))
tip_lbl <- gsub("^\\(*", "", tip_lbl)
tip_lbl <- gsub("\\).*$", "", tip_lbl)
tip_lbl <- tip_lbl[nzchar(tip_lbl)]
}
if (remove_quotes) {
tip_lbl <- gsub("^(\\\"|\\\')(.+)(\\\'|\\\")$", "\\2", tip_lbl)
}
list(tip_label = tip_lbl, edge_label = edge_lbl)
} |
properties_ <- function(deckgl) {
deckgl$x$layers[[1]]$properties
}
get_layer_props <- function(widget, idx = 1) {
widget$x$calls[[idx]]$args$properties
} |
expSBM_select <- function(K_max, N, edgelist, method = "SBM_gaussian", directed = F, trunc = T, tol = 0.001, n_iter_max = 100, init_blur_value = 1, verbose = F)
{
res <- list()
res$fitted_models <- list()
elbo_values <- icl_values <- rep(NA,K_max)
for (k in 1:K_max)
{
lambda_init <- as.numeric(rdirichlet(1, rep(1,k)))
Z_init_collapsed <- expSBM_init(edgelist = edgelist, K = k, method = method, blur_value = init_blur_value)
K_collapsed <- sum(colSums(Z_init_collapsed) > 0)
Z_init <- matrix(0,N,k)
if (k > 1) Z_init[,1:K_collapsed] = Z_init_collapsed else Z_init = Z_init_collapsed
mu_init <- matrix(rgamma(k*k,1,1),k,k)
if (!directed) for (g in 1:k) for (h in 1:k) if (g > h) mu_init[g,h] = mu_init[h,g]
nu_init <- matrix(rgamma(k*k,1,1),k,k)
if (!directed) for (g in 1:k) for (h in 1:k) if (g > h) nu_init[g,h] = nu_init[h,g]
res$fitted_models[[k]] <- output <- expSBM_EM(N, edgelist, Z_init, lambda_init, mu_init, nu_init, directed, trunc, tol, n_iter_max, verbose)
elbo_values[k] = output$elbo_values[length(output$elbo_values)]
Z_map_vec <- apply(output$Z_star, 1, which.max)
Z_map <- matrix(0,N,k)
for (i in 1:N) Z_map[i,Z_map_vec[i]] = 1
marginal_likelihood_contribution <- expSBM_ELBO(N, edgelist, Z_map, output$lambda_star, output$mu_star, output$nu_star, directed, trunc, verbose)$elbo_value
prior_contribution <- sum(Z_map %*% log(ifelse(output$lambda_star > 0, output$lambda_star, 1)))
if (directed) icl_values[k] = marginal_likelihood_contribution + prior_contribution - k^2 * log(nrow(edgelist)) - 0.5 * (k-1) * log(N)
if (!directed) icl_values[k] = marginal_likelihood_contribution + prior_contribution - (k*(k+1)/2) * log(nrow(edgelist)) - 0.5 * (k-1) * log(N)
}
res$icl_values <- icl_values
res$K_star <- which.max(icl_values)
res$best_model <- res$fitted_models[[res$K_star]]
res
} |
getHDoutliers <-
function (data, memberLists, alpha = 0.05, transform = TRUE)
{
data <- if (transform) dataTrans(data) else as.matrix(data)
if (any(is.na(data))) stop("missing values not allowed")
exemplars <- sapply(memberLists, function(x) x[[1]])
d <- knn.dist(data[exemplars, ], k = 1)
n <- length(d)
ord <- order(d)
dmin <- min(d)
dmax <- max(d)
gaps <- c(0, diff(d[ord]))
n4 <- max(min(50, floor(n/4)), 2)
J <- 1:n4
start <- max(floor(n/2), 1) + 1
ghat <- numeric(n)
for (i in start:n) ghat[i] <- sum((J/n4) * gaps[i - J + 1])
logAlpha <- log(1/alpha)
use <- start:n
bound <- Inf
for (i in start:n) {
if (gaps[i] > logAlpha * ghat[i]) {
bound <- d[ord][i - 1]
break
}
}
ex <- exemplars[which(d > bound)]
mem1 <- sapply(memberLists, function(x) x[1])
out <- unlist(memberLists[match(ex, mem1)])
names(out) <- NULL
out
} |
BlockTop <-
function(a,l,lag)
{
C <- array(dim=c(l,l,lag+3))
for(x in 1:(lag+3))
{
C[,,x] <- c(xpnd(a[((l*(l+1)/2)*(x-1)+1):(x*(l+1)*l/2)]))
}
f <- c(C)
A <- array(matrix(c(f,f[1:(l*l)],f),nrow=l,ncol=(2*(lag+4)-1)*l),dim=c(l,l,2*(lag+4)-1))
MM <- matrix(nrow=(lag+4)*(l),ncol=(lag+4)*(l))
for(i in 1:(lag+4))
{
for(j in 1:(lag+4))
{
MM[(l*i-(l-1)):(i*l),(l*j-(l-1)):(j*l)] <- A[,,j+(i-1)]
}
}
S <- MM[1:((1+lag)*l),]%*%t(MM[1:((1+lag)*l),])
return(list(S=S))
} |
phf_leaders <- function(player_type, season = 2021, season_type="Regular Season"){
league_info <- phf_league_info(season=season)
season_id <- dplyr::case_when(
season == 2022 ~ 3372,
season == 2021 ~ 2779,
season == 2020 ~ 1950,
season == 2019 ~ 2047,
season == 2018 ~ 2046,
season == 2017 ~ 2045,
season == 2016 ~ 246,
TRUE ~ NA_real_
)
team_row <- league_info$teams
player_type <- ifelse(player_type == "skaters", "players", player_type)
season_type <- gsub(" ","+", season_type)
base_url <- "https://web.api.digitalshift.ca/partials/stats/leaders/table?player_type="
full_url <- paste0(base_url,
player_type,
"&division_id=", unique(team_row$division_id),
"&game_type=", season_type,
"&season_id=", season_id,
"&limit=350&all=true"
)
res <- httr::RETRY(
"GET", full_url,
httr::add_headers(
`Authorization`='ticket="4dM1QOOKk-PQTSZxW_zfXnOgbh80dOGK6eUb_MaSl7nUN0_k4LxLMvZyeaYGXQuLyWBOQhY8Q65k6_uwMu6oojuO"'))
check_status(res)
tryCatch(
expr={
resp <- (res %>%
httr::content(as = "text", encoding="utf-8") %>%
jsonlite::parse_json() %>%
purrr::pluck("content") %>%
rvest::read_html() %>%
rvest::html_elements("table"))
resp <- unique(resp)
skaters_href <- resp[[1]] %>%
rvest::html_elements("tr") %>%
rvest::html_elements("td > a.person-inline") %>%
rvest::html_attr("href")
team_href <- resp[[1]] %>%
rvest::html_elements("tr") %>%
rvest::html_elements("td > a.team-inline") %>%
rvest::html_attr("href")
skaters <- resp[[1]] %>%
rvest::html_table()
skaters_href <- data.frame(
season_type = season_type,
player_href = skaters_href,
team_href = team_href
)
skaters <- dplyr::bind_cols(skaters, skaters_href)
if(player_type=="players"){
suppressWarnings(
skaters <- skaters %>%
tidyr::separate(.data$`FoW/L`,into = c("faceoffs_won", "faceoffs_lost"),
sep = " - ", remove = FALSE) %>%
dplyr::mutate_at(c("faceoffs_won","faceoffs_lost"), function(x){
as.integer(x)
})
)
skaters <- skaters %>%
dplyr::rename(
player_jersey = .data$`
player_name = .data$Name,
team_name = .data$Team,
position = .data$Pos,
games_played = .data$GP,
goals = .data$G,
assists = .data$A,
points = .data$Pts,
points_per_game_average = .data$PPGA,
penalty_minutes = .data$PIM,
plus_minus = .data$`+/-`,
shots_on_goal = .data$SOG,
scoring_pct = .data$`S%`,
blocks = .data$Blk,
giveaways = .data$GvA,
takeaways = .data$TkA,
faceoffs_won_lost = .data$`FoW/L`,
faceoffs_win_pct = .data$`Fo%`,
powerplay_goals = .data$`PPG`,
shorthanded_goals = .data$`SHG`,
game_winning_goals = .data$`GWG`,
shots = .data$`Sh`,
shots_blocked = .data$`ShBl`) %>%
dplyr::mutate(
player_name = stringr::str_replace(.data$player_name, pattern = "
player_id = as.integer(stringr::str_extract(.data$player_href, "\\d+")),
team_id = as.integer(stringr::str_extract(stringr::str_remove(.data$team_href,"stats
)
}else{
skaters <- skaters %>%
dplyr::rename(
player_jersey = .data$`
player_name = .data$Name,
team_name = .data$Team,
games_played = .data$GP,
wins = .data$W,
losses = .data$L,
ties = .data$T,
overtime_losses = .data$OTL,
shots_against = .data$SA,
goals_against = .data$GA,
saves = .data$Sv,
save_percent = .data$`Sv%`,
goals_against_average = .data$GAA,
shutouts = .data$SO,
minutes_played = .data$MP,
penalty_minutes = .data$PIM,
goals = .data$G,
assists = .data$A) %>%
dplyr::mutate(
player_name = stringr::str_replace(.data$player_name,pattern = "
player_id = as.integer(stringr::str_extract(.data$player_href, "\\d+")),
team_id = as.integer(stringr::str_extract(stringr::str_remove(.data$team_href,"stats
)
}
},
error = function(e) {
message(glue::glue("{Sys.time()}: Invalid parameters or no leaderboard data available!"))
},
warning = function(w) {
},
finally = {
}
)
return(skaters)
} |
cor.test <- function(x, ...) UseMethod("cor.test")
cor.test.default <-
function(x, y, alternative = c("two.sided", "less", "greater"),
method = c("pearson", "kendall", "spearman"), exact = NULL,
conf.level = 0.95, continuity = FALSE, ...)
{
alternative <- match.arg(alternative)
method <- match.arg(method)
DNAME <- paste(deparse(substitute(x)), "and", deparse(substitute(y)))
if(length(x) != length(y))
stop("'x' and 'y' must have the same length")
if(!is.numeric(x)) stop("'x' must be a numeric vector")
if(!is.numeric(y)) stop("'y' must be a numeric vector")
OK <- complete.cases(x, y)
x <- x[OK]
y <- y[OK]
n <- length(x)
NVAL <- 0
conf.int <- FALSE
if(method == "pearson") {
if(n < 3L)
stop("not enough finite observations")
method <- "Pearson's product-moment correlation"
names(NVAL) <- "correlation"
r <- cor(x, y)
df <- n - 2L
ESTIMATE <- c(cor = r)
PARAMETER <- c(df = df)
STATISTIC <- c(t = sqrt(df) * r / sqrt(1 - r^2))
if(n > 3) {
if(!missing(conf.level) &&
(length(conf.level) != 1 || !is.finite(conf.level) ||
conf.level < 0 || conf.level > 1))
stop("'conf.level' must be a single number between 0 and 1")
conf.int <- TRUE
z <- atanh(r)
sigma <- 1 / sqrt(n - 3)
cint <-
switch(alternative,
less = c(-Inf, z + sigma * qnorm(conf.level)),
greater = c(z - sigma * qnorm(conf.level), Inf),
two.sided = z +
c(-1, 1) * sigma * qnorm((1 + conf.level) / 2))
cint <- tanh(cint)
attr(cint, "conf.level") <- conf.level
}
PVAL <- switch(alternative,
"less" = pt(STATISTIC, df),
"greater" = pt(STATISTIC, df, lower.tail=FALSE),
"two.sided" = 2 * min(pt(STATISTIC, df),
pt(STATISTIC, df, lower.tail=FALSE)))
}
else {
if(n < 2)
stop("not enough finite observations")
PARAMETER <- NULL
TIES <- (min(length(unique(x)), length(unique(y))) < n)
if(method == "kendall") {
method <- "Kendall's rank correlation tau"
names(NVAL) <- "tau"
r <- cor(x,y, method = "kendall")
ESTIMATE <- c(tau = r)
if(!is.finite(ESTIMATE)) {
ESTIMATE[] <- NA
STATISTIC <- c(T = NA)
PVAL <- NA
}
else {
if(is.null(exact))
exact <- (n < 50)
if(exact && !TIES) {
q <- round((r + 1) * n * (n - 1) / 4)
STATISTIC <- c(T = q)
pkendall <- function(q, n) .Call(C_pKendall, q, n)
PVAL <-
switch(alternative,
"two.sided" = {
if(q > n * (n - 1) / 4)
p <- 1 - pkendall(q - 1, n)
else
p <- pkendall(q, n)
min(2 * p, 1)
},
"greater" = 1 - pkendall(q - 1, n),
"less" = pkendall(q, n))
} else {
xties <- table(x[duplicated(x)]) + 1
yties <- table(y[duplicated(y)]) + 1
T0 <- n * (n - 1)/2
T1 <- sum(xties * (xties - 1))/2
T2 <- sum(yties * (yties - 1))/2
S <- r * sqrt((T0 - T1) * (T0 - T2))
v0 <- n * (n - 1) * (2 * n + 5)
vt <- sum(xties * (xties - 1) * (2 * xties + 5))
vu <- sum(yties * (yties - 1) * (2 * yties + 5))
v1 <- sum(xties * (xties - 1)) * sum(yties * (yties - 1))
v2 <- sum(xties * (xties - 1) * (xties - 2)) *
sum(yties * (yties - 1) * (yties - 2))
var_S <- (v0 - vt - vu) / 18 +
v1 / (2 * n * (n - 1)) +
v2 / (9 * n * (n - 1) * (n - 2))
if(exact && TIES)
warning("Cannot compute exact p-value with ties")
if (continuity) S <- sign(S) * (abs(S) - 1)
STATISTIC <- c(z = S / sqrt(var_S))
PVAL <- switch(alternative,
"less" = pnorm(STATISTIC),
"greater" = pnorm(STATISTIC, lower.tail=FALSE),
"two.sided" = 2 * min(pnorm(STATISTIC),
pnorm(STATISTIC, lower.tail=FALSE)))
}
}
} else {
method <- "Spearman's rank correlation rho"
if (is.null(exact))
exact <- TRUE
names(NVAL) <- "rho"
r <- cor(rank(x), rank(y))
ESTIMATE <- c(rho = r)
if(!is.finite(ESTIMATE)) {
ESTIMATE[] <- NA
STATISTIC <- c(S = NA)
PVAL <- NA
}
else {
pspearman <- function(q, n, lower.tail = TRUE) {
if(n <= 1290 && exact)
.Call(C_pRho, round(q) + 2*lower.tail, n, lower.tail)
else {
den <- (n*(n^2-1))/6
if (continuity) den <- den + 1
r <- 1 - q/den
pt(r / sqrt((1 - r^2)/(n-2)), df = n-2,
lower.tail = !lower.tail)
}
}
q <- (n^3 - n) * (1 - r) / 6
STATISTIC <- c(S = q)
if(TIES && exact){
exact <- FALSE
warning("Cannot compute exact p-value with ties")
}
PVAL <-
switch(alternative,
"two.sided" = {
p <- if(q > (n^3 - n) / 6)
pspearman(q, n, lower.tail = FALSE)
else
pspearman(q, n, lower.tail = TRUE)
min(2 * p, 1)
},
"greater" = pspearman(q, n, lower.tail = TRUE),
"less" = pspearman(q, n, lower.tail = FALSE))
}
}
}
RVAL <- list(statistic = STATISTIC,
parameter = PARAMETER,
p.value = as.numeric(PVAL),
estimate = ESTIMATE,
null.value = NVAL,
alternative = alternative,
method = method,
data.name = DNAME)
if(conf.int)
RVAL <- c(RVAL, list(conf.int = cint))
class(RVAL) <- "htest"
RVAL
}
cor.test.formula <-
function(formula, data, subset, na.action, ...)
{
if(missing(formula)
|| !inherits(formula, "formula")
|| length(formula) != 2L)
stop("'formula' missing or invalid")
m <- match.call(expand.dots = FALSE)
if(is.matrix(eval(m$data, parent.frame())))
m$data <- as.data.frame(data)
m[[1L]] <- quote(stats::model.frame)
m$... <- NULL
mf <- eval(m, environment(formula))
if(length(mf) != 2L)
stop("invalid formula")
DNAME <- paste(names(mf), collapse = " and ")
names(mf) <- c("x", "y")
y <- do.call("cor.test", c(mf, list(...)))
y$data.name <- DNAME
y
} |
minnz <-
function(V) {
C <- NULL
k <- length(V)
for (i in 1:k) {
if ((V[i] == 0) == FALSE) (C[i] <- V[i]) else (C[i] <- 9999919)
}
m <- min(C)
if (max(V) == 1) (m <- 1)
if (m == 9999919) (warning("Error: Minimum calculation failed."))
return(m)
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(gh)
gitcreds::gitcreds_cache_envvar("https://github.acme.com") |
sensibo.pods <- function(key = getOption("sensibo.key")) {
url <- file.path(base_url(), "users/me/pods")
pods <- xGET(url, query=glue::glue("apiKey={key}"))
do.call(c, lapply(pods, function(pod){pod$id}))
}
sensibo.pod.info <- function(pod, key = getOption("sensibo.key")) {
if(length(pod)>1) stop("You must specify only one pod id here.")
url <- file.path(base_url(), glue::glue("pods/{pod}"))
xGET(url, query=glue::glue("apiKey={key}"))
}
sensibo.pod.states <- function(pod, n = 10, key = getOption("sensibo.key")) {
if(length(pod)>1) stop("You must specify only one pod id here.")
if(is.null(n)) n <- 10
if(n > 20) n <- 20
url <- file.path(base_url(), glue::glue("pods/{pod}/acStates"))
states <- xGET(url, query=glue::glue("limit={n}&apiKey={key}"))
return(states)
}
sensibo.pod.state <- function(pod, state, key = getOption("sensibo.key")) {
if(length(pod)>1) stop("You must specify only one pod id here.")
if(length(state)>1) stop("You must specify only one state id here.")
url <- file.path(base_url(), glue::glue("pods/{pod}/acStates/{state}"))
probe.list <- xGET(url, query=glue::glue("apiKey={key}"))
return(probe.list)
}
sensibo.pod.probe <- function(pod, key = getOption("sensibo.key")) {
if(length(pod)>1) stop("You must specify only one pod id here.")
url <- file.path(base_url(), glue::glue("pods/{pod}/measurements"))
xGET(url, query=glue::glue("apiKey={key}"))
}
sensibo.pod.historical <- function(pod, days = 1, key = getOption("sensibo.key")) {
if(length(pod)>1) stop("You must specify only one pod id here.")
if(is.null(days)) days <- 1
if(days > 7) days <- 7
url <- file.path(base_url(), glue::glue("pods/{pod}/historicalMeasurements"))
m <- xGET(url, query=glue::glue("days={days}&apiKey={key}"))
df <- merge(do.call(rbind, lapply(m$temperature, function(t){as.data.frame(t, stringsAsFactors = F)})),
do.call(rbind, lapply(m$humidity, function(t){as.data.frame(t, stringsAsFactors = F)})),
by = "time")
colnames(df) <- c("time", "temperature", "humidity")
return(df)
}
sensibo.pod.set <- function(pod, on = NULL, mode = NULL, fan = NULL, unit = NULL, temperature = NULL, swing = NULL, key = getOption("sensibo.key")) {
if(length(pod)>1) stop("You must specify only one pod id here.")
url <- file.path(base_url(), glue::glue("pods/{pod}/acStates"))
body.list <- list("on" = on,
"mode" = mode,
"fan" = fan,
"unit" = unit,
"temperature" = temperature,
"swing" = swing)
propset <- do.call(c,lapply(body.list, function(body.list){!is.null(body.list)}))
body <- jsonlite::toJSON(list("acState" = body.list[propset]), auto_unbox = T)
xPOST(url, query=glue::glue("apiKey={key}"), body = body)
}
sensibo.pod.smartmode <- function(pod, key = getOption("sensibo.key")) {
if(length(pod)>1) stop("You must specify only one pod id here.")
url <- file.path(base_url(), glue::glue("pods/{pod}/smartmode"))
react.list <- xGET(url, query=glue::glue("apiKey={key}"))
return(react.list)
}
sensibo.pod.smartmode.set <- function(pod, enable = NULL, key = getOption("sensibo.key")) {
if(length(pod)>1) stop("You must specify only one pod id here.")
url <- file.path(base_url(), glue::glue("pods/{pod}/smartmode"))
body.list <- list("enabled" = enable)
propset <- do.call(c,lapply(body.list, function(body.list){!is.null(body.list)}))
body <- jsonlite::toJSON(body.list[propset], auto_unbox = T)
xPOST(url, query=glue::glue("apiKey={key}"), body = body)
} |
orderBook <- function(events, tp=as.POSIXlt(Sys.time(), tz="UTC"),
max.levels=NULL, bps.range=0, min.bid=0, max.ask=Inf) {
pct.range <- bps.range*0.0001
activeBids <- function(active.orders) {
bids <- active.orders[active.orders$direction=="bid" &
active.orders$type != "market", ]
bids <- bids[order(-bids$price, bids$id), ]
first.price <- head(bids, 1)$price
cbind(bids, bps=((first.price-bids$price)/first.price)*10000,
liquidity=cumsum(bids$volume))
}
activeAsks <- function(active.orders) {
asks <- active.orders[active.orders$direction=="ask" &
active.orders$type != "market", ]
asks <- asks[order(asks$price, asks$id), ]
first.price <- head(asks, 1)$price
cbind(asks, bps=((asks$price-first.price)/first.price)*10000,
liquidity=cumsum(asks$volume))
}
active.orders <- (function() {
created.before <- events[events$action == "created" &
events$timestamp <= tp, "id"]
deleted.before <- events[events$action == "deleted" &
events$timestamp <= tp, "id"]
active.order.ids <- setdiff(created.before, deleted.before)
active.orders <- events[events$id %in% active.order.ids, ]
active.orders <- active.orders[active.orders$timestamp <= tp, ]
changed.orders <- active.orders$action == "changed"
changed.before <- active.orders[changed.orders, ]
changed.before <- changed.before[order(changed.before[, "volume"]), ]
changed.before <- changed.before[!duplicated(changed.before$id), ]
active.orders <- active.orders[!changed.orders, ]
active.orders <- active.orders[!(active.orders$id %in% changed.before$id), ]
active.orders <- rbind(active.orders, changed.before)
stopifnot(all(active.orders$timestamp <= tp))
stopifnot(all(!duplicated(active.orders$id)))
active.orders
})()
asks <- activeAsks(active.orders)[, c("id", "timestamp",
"exchange.timestamp", "price", "volume", "liquidity", "bps")]
asks <- asks[rev(1:nrow(asks)), ]
bids <- activeBids(active.orders)[, c("id", "timestamp",
"exchange.timestamp", "price", "volume", "liquidity", "bps")]
if(pct.range > 0) {
max.ask <- tail(asks, 1)$price*(1+pct.range)
asks <- asks[asks$price <= max.ask, ]
min.bid <- head(bids, 1)$price*(1-pct.range)
bids <- bids[bids$price >= min.bid, ]
}
if(!is.null(max.levels)) {
asks <- tail(asks, max.levels)
bids <- head(bids, max.levels)
}
rownames(asks) <- NULL
rownames(bids) <- NULL
list(timestamp=tp, asks=asks, bids=bids)
} |
ITM = function(x, y, hx, hy, h,
space = c("mean", "pdf"),
xdensity = c("normal", "kernel", "elliptic"),
out = FALSE, outden = FALSE)
{
n = NROW(x); p = NCOL(x)
if(length(y) != n)
stop("Error:\n\tThe length of the response is not equal to the
number of rows of the predictors!\n")
x = as.matrix(x)
y = scale(y)
temp = x.standardize(x)
Sinvsqrt = temp$Sinvsqrt
xstd = temp$x.std
space = match.arg(space)
xdensity = match.arg(xdensity)
if(xdensity == "normal")
{ denidx = 0; index = NULL; f0gk = NULL }
else
{
denidx = 1
f0gk = switch(xdensity,
kernel = .C("dlogden1", as.double(xstd), as.integer(n),
as.integer(p), as.double(h), as.integer(outden),
f0 = double(n), dlogf = double(n*p)),
elliptic = .C("dlogden3", as.double(xstd), as.integer(n),
as.integer(p), as.double(h), as.integer(outden),
f0 = double(n), rdlogf = double(n), dlogf = double(n*p)))
cutpoint = quantile(f0gk$f0, 0.1)
index = (f0gk$f0 >= cutpoint)
gk = matrix(f0gk$dlogf, ncol = p)[index, ]
xstd = xstd[index, ]; y = y[index]; n = sum(index)
}
Mfunindex = paste(space, denidx, sep="")
M = switch(Mfunindex,
mean0 = .C("ITM_mean_norm", as.double(xstd), as.double(y),
as.double(hx), as.integer(n), as.integer(p),
as.integer(out), M = double(p * p))$M,
mean1 = .C("ITM_mean", as.double(xstd), as.double(gk),
as.double(y), as.double(hx), as.integer(n),
as.integer(p), as.integer(out), M = double(p * p))$M,
pdf0 = .C("ITM_pdf_norm", as.double(xstd), as.double(y),
as.double(hx), as.double(hy), as.integer(n), as.integer(p),
as.integer(out), M = double(p * p))$M,
pdf1 = .C("ITM_pdf", as.double(xstd), as.double(gk),
as.double(y), as.double(hx), as.double(hy), as.integer(n),
as.integer(p), as.integer(out), M = double(p * p))$M)
M = matrix(M, nrow = p, ncol = p)
M.raw = eigen(M, symmetric = T)
M.evectors = Sinvsqrt %*% M.raw$vectors
M.evectors = apply(M.evectors, 2, function(a) {a / sqrt(sum(a^2))})
info = paste("targeted space:", space,
"\ndensity of predictors:", xdensity, "\n")
list(evalues = M.raw$values, evectors = M.evectors,
M = M, index = index, density = f0gk$f0, info = info)
}
x.standardize = function(x)
{
x.e = eigen(cov(x), symmetric = T)
Sinvsqrt = x.e$vectors %*% diag(1/sqrt(x.e$values)) %*% t(x.e$vectors)
x.std = scale(x, center = T, scale = F) %*% Sinvsqrt
list(x.std = x.std, Sinvsqrt = Sinvsqrt)
}
pm.dist = function(A, B)
{
A.orth <- qr.Q(qr(A))
B.orth <- qr.Q(qr(B))
BAAB <- t(B.orth) %*% A.orth %*% t(A.orth) %*% B.orth
BAAB.eig <- eigen(BAAB, only.values = T)$values
r = 1 - sqrt(mean(BAAB.eig))
d = max(svd(B.orth %*% t(B.orth) - A.orth %*% t(A.orth))$d)
list(r = r, d = d)
}
rmixnorm = function(n, p, percent, cvec)
{
if(length(percent) != NCOL(cvec))
stop("The length of percent and cvec are not equal!")
if(p != NROW(cvec))
stop("The dimension of cvec is not equal to p!")
ncut = c(0, n * cumsum(percent / sum(percent)))
x = matrix(rnorm(n * p), nrow = n, ncol = p)
for(i in 1:length(percent))
{
index = (ncut[i]+1):(ncut[i+1])
x[index, ] = sweep(x[index, ], 2, cvec[, i], "+")
}
x
} |
test_that("Transcript parsing yields correct records", {
tr.out = processZoomTranscript(fname=system.file('extdata', "meeting001_transcript.vtt", package = 'zoomGroupStats'), recordingStartDateTime = '2020-04-20 13:30:00',languageCode = 'en')
expect_equal(nrow(tr.out), 300)
expect_equal(length(unique(tr.out$userName)), 6)
expect_equal(lubridate::is.POSIXct(tr.out$utteranceStartTime), TRUE)
expect_equal(lubridate::is.POSIXct(tr.out$utteranceEndTime), TRUE)
expect_equal(is.numeric(tr.out$utteranceStartSeconds), TRUE)
expect_equal(is.numeric(tr.out$utteranceEndSeconds), TRUE)
}) |
peelingOneIterate = function (X, posDT, gain = TRUE, nullDist = NULL, threshold = NULL, numIters = 5)
{
output = data.frame(chr = rep(NA, numIters), peelStart = rep(NA, numIters), peelStop = rep(NA, numIters),
peakLoc = rep(NA, numIters), peakVal = rep(NA, numIters), peakPVal = rep(NA, numIters))
gainLossInd = (-1)^(1 + gain)
X1 = X * gainLossInd
for (i in 1:numIters)
{
tempK = which.max(rowMeans(X1))
tempPeakVal = gainLossInd * signif(rowMeans(X1)[tempK], 4)
tempPeakPVal = ifelse(is.null(nullDist), NA, (1 + sum(nullDist > tempPeakVal))/length(nullDist) * (gainLossInd == 1) +
(1 + sum(nullDist < tempPeakVal))/length(nullDist) * (gainLossInd == -1))
tempPeakPval = min(tempPeakPVal, 1)
tempPeel = peelingOne(X = X1, posDT = posDT, k = tempK, threshold = threshold)
output[i,] = c(posDT[tempK, 1], tempPeel[[2]][1], tempPeel[[2]][2], posDT[tempK, 2],
tempPeakVal, tempPeakPVal)
X1 = tempPeel[[1]]
}
return(output)
} |
flatsun<-function(x,maxseq,id,modonube=FALSE){
bad<-NULL
liston <- getOption("liston")
homefolder <- getOption("homefolder")
milista<-unique(liston)
if(!modonube){me<-gdata::first(which(milista$SOUID == substring(id,9,14) & substring(milista$ELEI,1,2)=='SS'))}
if(modonube){me<-gdata::first(which(milista$SOUID == substring(id,9,14) & substring(milista$ELEI,1,2)=='CC'))}
if(!modonube){cloud<-gdata::first(which(milista$STAID == milista$STAID[me] & milista$PARID == milista$PARID[me] & substring(milista$ELEI,1,2)=='CC'))}
if(modonube){cloud<-gdata::first(which(milista$STAID == milista$STAID[me] & milista$PARID == milista$PARID[me] & substring(milista$ELEI,1,2)=='SS'))}
if(length(cloud)==0){bad<-flat(x[,2],maxseq,exclude=100);return(bad)}
if(!is.null(cloud) &!(is.na(cloud))){
if(!modonube){y<-readecad(paste0(homefolder,'raw/CC_SOUID',milista$SOUID[cloud],'.txt'))[,3:4]}
if(modonube){y<-x;x<-readecad(paste0(homefolder,'raw/SS_SOUID',milista$SOUID[cloud],'.txt'))[,3:4]}
names(x)<-c('date','sun');names(y)<-c('date','cloud')
if(!modonube){z<-merge(x,y,all.x=TRUE,all.y=FALSE)}
if(modonube){z<-merge(x,y,all.x=FALSE,all.y=TRUE)}
maximo<-length(which(!is.na(z[,2])));real<-length(which(!is.na(z[,2]) & !is.na(z[,3])))
evaluation=real/maximo
if(!modonube & evaluation < 0.80){bad<-flat(x[,2],maxseq,exclude=100);return(bad)}
if(modonube & evaluation < 0.80){bad<-flat(x[,2],maxseq,exclude=c(0,8));return(bad)}
if(!modonube){bid<-flat(z[,2],maxseq)}
if(modonube){bid<-flat(z[,3],maxseq)}
if(length(bid)==0){return(bad)}
z$flat<-0;z$flat[bid]<-1
z$difs<-0;z$difs[1]<-NA;z$difs[2:nrow(z)]<-diff(z$flat)
if(z$flat[1]==1){z$difs[1]<-1}
start=which(z$difs == 1)
end=which(z$difs == -1)-1
if(z$flat[nrow(z)]==1){end<-c(end,nrow(z))}
juntos<-data.frame(start,end)
for(i in 1:nrow(juntos)){juntos$sol[i]<-mean(z$sun[juntos$start[i]:juntos$end[i]],na.rm=TRUE)}
for(i in 1:nrow(juntos)){juntos$nube[i]<-mean(z$cloud[juntos$start[i]:juntos$end[i]],na.rm=TRUE)}
if(!modonube){for(i in 1:nrow(juntos)){if(!is.na(juntos$sol[i]) & !is.na(juntos$nube[i])){if(juntos$sol[i]< 1 & juntos$nube[i] > 7){z$flat[juntos$start[i]:juntos$end[i]]<-0}}}}
juntos$date<-z$date[start]
juntos$date<-as.Date(paste(substring(juntos$date,1,4),substring(juntos$date,5,6),substring(juntos$date,7,8),sep='-'))
juntos$lat<-milista$LAT[me];juntos$lon<-milista$LON[me]
totest<-data.frame(juntos$date,juntos$lat,juntos$lon);names(totest)<-c('date','lat','lon')
juntos$maxsun<-juntos$sol/(as.numeric(suncalc::getSunlightTimes(data=totest)$night-suncalc::getSunlightTimes(data=totest)$dawn)*10)*100
juntos$maxsun[which(is.na(juntos$maxsun))]<-0
if(!modonube){for(i in 1:nrow(juntos)){if(!is.na(juntos$sol[i]) & !is.na(juntos$nube[i])){if(juntos$maxsun[i]> 90 & juntos$nube[i] < 2){z$flat[juntos$start[i]:juntos$end[i]]<-0}}}}
if(modonube){for(i in 1:nrow(juntos)){if(!is.na(juntos$sol[i]) & !is.na(juntos$nube[i])){if(juntos$maxsun[i]> 70 & juntos$nube[i] < 2){z$flat[juntos$start[i]:juntos$end[i]]<-0}}}}
if(modonube){for(i in 1:nrow(juntos)){if(!is.na(juntos$sol[i]) & !is.na(juntos$nube[i])){if(juntos$maxsun[i]< 10 & juntos$nube[i] > 7){z$flat[juntos$start[i]:juntos$end[i]]<-0}}}}
bad<-which(z$flat == 1)
return(bad)
}
} |
set.seed(123)
N = 100
k = 2
X = matrix(rnorm(N * k), ncol = k)
y = -.5 + .2*X[, 1] + .1*X[, 2] + rnorm(N, sd = .5)
dfXy = data.frame(X, y)
lm_ML = function(par, X, y) {
beta = par[-1]
sigma2 = par[1]
sigma = sqrt(sigma2)
N = nrow(X)
LP = X %*% beta
mu = LP
L = dnorm(y, mean = mu, sd = sigma, log = TRUE)
-sum(L)
}
lm_LS = function(par, X, y) {
beta = par
LP = X %*% beta
mu = LP
L = crossprod(y - mu)
}
X = cbind(1, X)
init = c(1, rep(0, ncol(X)))
names(init) = c('sigma2', 'intercept', 'b1', 'b2')
optlmML = optim(
par = init,
fn = lm_ML,
X = X,
y = y,
control = list(reltol = 1e-8)
)
optlmLS = optim(
par = init[-1],
fn = lm_LS,
X = X,
y = y,
control = list(reltol = 1e-8)
)
pars_ML = optlmML$par
pars_LS = c(sigma2 = optlmLS$value / (N - k - 1), optlmLS$par)
modlm = lm(y ~ ., dfXy)
round(
rbind(
pars_ML,
pars_LS,
modlm = c(summary(modlm)$sigma^2, coef(modlm))),
digits = 3
)
modglm = glm(y ~ ., data = dfXy)
summary(modglm)
coefs = solve(t(X) %*% X) %*% t(X) %*% y
sqrt(crossprod(y - X %*% coefs) / (N - k - 1))
summary(modlm)$sigma
sqrt(modglm$deviance / modglm$df.residual)
c(sqrt(pars_ML[1]), sqrt(pars_LS[1])) |
if (!testthat:::on_cran()) {
scrimp_res <- NULL
scrimp_res_par <- NA
test_that("Scrimp", {
set.seed(2021)
expect_silent(scrimp_res <<- scrimp(
data = motifs_discords_small, window_size = 150, exclusion_zone = 0.5,
progress = FALSE
))
expect_type(scrimp_res, "list")
expect_snapshot_value(scrimp_res, style = "serialize")
})
test_that("Scrimp Parallel", {
set.seed(2021)
expect_silent(scrimp_res_par <<- scrimp(
data = motifs_discords_small, window_size = 150, exclusion_zone = 0.5,
n_workers = 2, progress = FALSE
))
expect_type(scrimp_res_par, "list")
expect_snapshot_value(scrimp_res_par, style = "serialize")
})
test_that("Scrimps are equal", {
expect_equal(scrimp_res, scrimp_res_par)
})
} |
eh_test_subtype <- function(label, M, factors, data, digits = 2) {
if (!class(data[[label]]) %in% c("numeric", "integer")) {
stop("The argument to label must be numeric or integer. Arguments of type character and factor are not supported, please see the documentation.")
}
if (min(data[[label]] != 0)) {
stop("The argument to label should start with 0. 0 indicates control subjects and cases should be labeled 1 through M, the total number of subtypes.")
}
if (class(M) != "numeric" | M < 2) {
stop("The argument to M, the total number of subtypes, must be a numeric value >=2.")
}
if (length(levels(factor(data[[label]][data[[label]] != 0]))) != M) {
stop("M is not equal to the number of non-zero levels in the variable supplied to label. Please make sure M reflects the number of subtypes in the data.")
}
if (any(grep("^[^:]+:", factors)) == TRUE) {
stop("Risk factor names cannot include colons. Please rename the offending risk factor and try again.")
}
mform <- mlogit::mFormula(
stats::as.formula(paste0(label, " ~ 1 |", paste(factors, collapse = " + ")))
)
data2 <- mlogit::mlogit.data(data, choice = label, shape = "wide")
fit <- mlogit::mlogit(formula = mform, data = data2)
coefnames <- unique(sapply(
strsplit(rownames(summary(fit)$CoefTable), ":"),
"[[", 1
))[-1]
beta_plr <- matrix(summary(fit)$CoefTable[, 1], ncol = M, byrow = T)[-1, , drop = FALSE]
beta_se <- matrix(summary(fit)$CoefTable[, 2], ncol = M, byrow = T)[-1, , drop = FALSE]
colnames(beta_plr) <- colnames(beta_se) <- levels(as.factor(data[[label]]))[-1]
rownames(beta_plr) <- rownames(beta_se) <- coefnames
p <- nrow(beta_plr)
or <- round(exp(beta_plr), digits)
lci <- round(exp(beta_plr - stats::qnorm(0.975) * beta_se), digits)
uci <- round(exp(beta_plr + stats::qnorm(0.975) * beta_se), digits)
beta_se_p <- or_ci_p <- pval <- NULL
vcov_plr <- stats::vcov(fit)
V <- lapply(coefnames, function(x) {
vcov_plr[
which(sapply(strsplit(rownames(vcov_plr), ":"), "[[", 1) == x),
which(sapply(strsplit(rownames(vcov_plr), ":"), "[[", 1) == x)
]
})
Lmat <- matrix(0, nrow = (M - 1), ncol = M)
Lmat[row(Lmat) == col(Lmat)] <- 1
Lmat[row(Lmat) - col(Lmat) == -1] <- -1
pval <- sapply(1:p, function(i) {
aod::wald.test(
b = beta_plr[i, ],
Sigma = V[[i]],
L = Lmat
)$result$chi2["P"]
})
pval <- as.data.frame(pval)
rownames(pval) <- coefnames
colnames(pval) <- "p_het"
beta_se_p <- data.frame(matrix(paste0(
round(beta_plr, digits), " (",
round(beta_se, digits), ")"
), ncol = M),
round(pval, 3),
stringsAsFactors = FALSE
)
or_ci_p <- data.frame(matrix(paste0(or, " (", lci, "-", uci, ")"), ncol = M),
round(pval, 3),
stringsAsFactors = FALSE
)
rownames(or_ci_p) <- rownames(beta_se_p) <- coefnames
colnames(or_ci_p) <- colnames(beta_se_p) <-
c(levels(as.factor(data[[label]]))[-1], "p_het")
or_ci_p$p_het[or_ci_p$p_het == "0"] <- "<.001"
beta_se_p$p_het[beta_se_p$p_het == "0"] <- "<.001"
return(list(
beta = beta_plr,
beta_se = beta_se,
eh_pval = pval,
or_ci_p = or_ci_p,
beta_se_p = beta_se_p,
var_covar = vcov_plr
))
} |
close.bracket<-function(pattern, x){
possible.end<-nchar(x)+1
start<-gregexpr(pattern, x)[[1]]
n<-length(start)
openB<-gregexpr("\\(", x)[[1]]
closeB<-gregexpr("\\)", x)[[1]]
end<-1:n
if(n==1 & start[1]==-1){
end<--1
}else{
for(i in 1:n){
nopen<-1
pos<-openB[match(TRUE, openB>start[i])]+1
while(nopen!=0){
if(pos%in%openB){nopen<-nopen+1}
if(pos%in%closeB){nopen<-nopen-1}
pos<-pos+1
if(pos>possible.end){stop("formuala invalid")}
}
end[i]<-pos-1
}
}
cbind(start,end)
} |
blandr.display.and.plot <- function(method1, method2, method1name = "Method 1", method2name = "Method 2",
plotTitle = "Bland-Altman plot for comparison of 2 methods", sig.level = 0.95, annotate = FALSE,
ciDisplay = TRUE, ciShading = FALSE, normalLow = FALSE, normalHigh = FALSE, lowest_y_axis = FALSE,
highest_y_axis = FALSE, point_size = 0.8) {
.Deprecated("blandr.display.and.draw")
blandr.display.and.draw(method1, method2, method1name, method2name, plotTitle, sig.level,
annotate, ciDisplay, ciShading, normalLow, normalHigh, lowest_y_axis, highest_y_axis,
point_size)
} |
ggplot_add.ggplot <- function(object, plot, object_name) {
patches <- get_patches(plot)
add_patches(object, patches)
}
ggplot_add.grob <- function(object, plot, object_name) {
plot + wrap_elements(full = object)
}
ggplot_add.formula <- ggplot_add.grob
ggplot_add.raster <- ggplot_add.grob
ggplot_add.nativeRaster <- ggplot_add.grob
should_autowrap <- function(x) {
is.grob(x) || inherits(x, 'formula') || is.raster(x) || inherits(x, 'nativeRaster')
}
get_patches <- function(plot) {
empty <- is_empty(plot)
if (is_patchwork(plot)) {
patches <- plot$patches
plot$patches <- NULL
class(plot) <- setdiff(class(plot), 'patchwork')
} else {
patches <- new_patchwork()
}
if (!empty) {
patches$plots <- c(patches$plots, list(plot))
}
patches
}
is_patchwork <- function(x) inherits(x, 'patchwork')
as_patchwork <- function(x) {
UseMethod('as_patchwork')
}
as_patchwork.default <- function(x) {
stop('Don\'t know how to convert an object of class <', paste(class(x), collapse = ', '),'> to a patchwork', call. = FALSE)
}
as_patchwork.ggplot <- function(x) {
class(x) <- c('patchwork', class(x))
x$patches <- new_patchwork()
x
}
as_patchwork.patchwork <- function(x) x
add_patches <- function(plot, patches) {
UseMethod('add_patches')
}
add_patches.ggplot <- function(plot, patches) {
plot <- as_patchwork(plot)
plot$patches <- patches
plot
}
add_patches.patchwork <- function(plot, patches) {
patches$plots <- c(patches$plots, list(plot))
add_patches(plot_filler(), patches)
}
new_patchwork <- function() {
list(
plots = list(),
layout = plot_layout(),
annotation = plot_annotation()
)
}
plot_filler <- function() {
p <- ggplot()
class(p) <- c('plot_filler', class(p))
p
}
is_empty <- function(x) inherits(x, 'plot_filler')
has_tag.plot_filler <- function(x) FALSE |
sum(1,2) |
cat("Testing the calculation of the BIC score...\n")
library(pcalg)
load("test_bicscore.rda")
tol <- sqrt(.Machine$double.eps)
settings <- expand.grid(format = c("scatter", "raw"), cpp = c(FALSE, TRUE),
stringsAsFactors = FALSE)
nreps <- 5
for (m in 1:nrow(settings)) {
cat(sprintf("Setting: storage format = %s, C++ library = %s\n",
settings$format[m], settings$cpp[m]))
for (i in 1:nreps) {
perm <- 1:nrow(gauss.data)
if (i > 1) {
set.seed(i)
perm <- sample(perm)
}
score <- new("GaussL0penIntScore",
targets = gauss.targets,
target.index = gauss.target.index[perm],
data = gauss.data[perm, ],
format = settings$format[m],
use.cpp = settings$cpp[m],
intercept = FALSE)
if (any(score$pp.dat$data.count != 1000)) {
stop("The number of non-interventions are not calculated correctly.")
}
stopifnot(is.list(score$pp.dat$non.int), length(score$pp.dat$non.int) == 5)
stopifnot(all(sapply(1:5, function(j) {
isTRUE(all.equal(score$pp.dat$non.int[[j]],
setdiff(1:1200, 200*j + 1:200)))
})))
if (settings$format[m] == "scatter") {
if (!isTRUE(all.equal(score$pp.dat$scatter.index, 1:5))) {
stop("The indices of the scatter matrices are not calculated correctly.")
}
for (j in 1:5) {
if (!isTRUE(all.equal(score$pp.dat$scatter[[j]][1:5, 1:5],
gauss.scatter[[j]],
tolerance = tol))) {
stop("The scatter matrices are not calculated correctly.")
}
}
}
for (j in 1:5) {
if (!isTRUE(all.equal(gauss.loc.score[[j]],
score$local.score(j, gauss.parents[[j]]),
tolerance = tol))) {
stop("The local score is not calculated correctly.")
}
}
for (j in 1:5) {
local.mle <- score$local.fit(j, gauss.parents[[j]])
if (length(local.mle) != length(gauss.mle[[j]]) ||
!isTRUE(all.equal(gauss.mle[[j]], local.mle, tolerance = tol))) {
stop("The local MLE is not calculated correctly.")
}
}
}
}
temp.targets <- gauss.targets
temp.targets[[2]] <- rep(temp.targets[[2]], 4)
score <- new("GaussL0penIntScore",
targets = temp.targets,
target.index = gauss.target.index,
data = gauss.data,
format = "scatter",
use.cpp = FALSE,
intercept = FALSE)
stopifnot(isTRUE(all.equal(score$pp.dat$targets, gauss.targets)))
stopifnot(isTRUE(all.equal(score$pp.dat$target.index, gauss.target.index)))
stopifnot(isTRUE(
tryCatch(
score <- new("GaussL0penIntScore",
targets = gauss.targets,
target.index = gauss.target.index),
error = function(e) {
cat(paste(" Error caught:", e$message, "\n", sep = " "))
TRUE
}
)))
set.seed(307)
temp.targets <- gauss.targets
temp.targets <- c(temp.targets, temp.targets[[6]])
temp.target.index <- gauss.target.index
temp.target.index[sample(which(gauss.target.index == 6), size = 20)] <- length(temp.targets)
stopifnot(isTRUE(
tryCatch(
score <- new("GaussL0penIntScore",
targets = temp.targets,
target.index = temp.target.index,
data = gauss.data),
error = function(e) {
cat(paste(" Error caught:", e$message, "\n", sep = " "))
TRUE
}
)))
temp.targets <- gauss.targets
temp.targets[[2]] <- c(temp.targets[[2]], 9)
stopifnot(isTRUE(
tryCatch(
score <- new("GaussL0penIntScore",
targets = temp.targets,
target.index = gauss.target.index,
data = gauss.data),
error = function(e) {
cat(paste(" Error caught:", e$message, "\n", sep = " "))
TRUE
}
)))
temp.target.index <- gauss.target.index
temp.target.index[1] <- length(gauss.targets) + 1
stopifnot(isTRUE(
tryCatch(score <- new("GaussL0penIntScore",
targets = gauss.targets,
target.index = temp.target.index,
data = gauss.data),
error = function(e) {
cat(paste(" Error caught:", e$message, "\n", sep = " "))
TRUE
}
)))
cat("Done.\n") |
peek_back <- function(d, ...) {UseMethod("peek_back", d)} |
expected <- "1.235e+04"
test(id=11, code={
argv <- structure(list(fmt = "%9.4g", 12345.6789), .Names = c("fmt",
""))
do.call('sprintf', argv);
}, o = expected);
|
library("Matrix")
library("testthat")
library("L0Learn")
library("pracma")
tmp <- L0Learn::GenSynthetic(n=50, p=200, k=10, seed=1, rho=1, b0=0)
Xsmall <- tmp[[1]]
ysmall <- tmp[[2]]
tol = 1e-4
if (sum(apply(Xsmall, 2, sd) == 0)) {
stop("X needs to have non-zero std for each column")
}
Xsmall_sparse <- as(Xsmall, "dgCMatrix")
userLambda <- list()
userLambda[[1]] <- c(logspace(-1, -10, 100))
test_that("Intercepts are supported for all losses, algorithims, penalites, and matrix types", {
skip_on_cran()
for (p in c("L0", "L0L1", "L0L2")){
L0Learn.fit(Xsmall_sparse, ysmall, penalty=p, intercept = TRUE)
L0Learn.cvfit(Xsmall_sparse, ysmall, penalty=p, nFolds=2, intercept = TRUE)
}
for (a in c("CD", "CDPSI")){
L0Learn.fit(Xsmall_sparse, ysmall, algorithm=a, intercept = TRUE)
L0Learn.cvfit(Xsmall_sparse, ysmall, algorithm=a, nFolds=2, intercept = TRUE)
}
for (l in c("Logistic", "SquaredHinge")){
L0Learn.fit(Xsmall_sparse, sign(ysmall), loss=l, intercept = TRUE)
L0Learn.cvfit(Xsmall_sparse, ysmall, algorithm=a, nFolds=2, intercept = TRUE)
}
succeed()
})
test_that("Intercepts for Sparse Matricies are deterministic", {
skip_on_cran()
for (p in c("L0", "L0L1", "L0L2")){
set.seed(1)
x1 <- L0Learn.fit(Xsmall_sparse, ysmall, penalty=p)
set.seed(1)
x2 <- L0Learn.fit(Xsmall_sparse, ysmall, penalty=p)
expect_equal(x1$a0, x2$a0, info=p)
}
for (a in c("CD", "CDPSI")){
set.seed(1)
x1 <- L0Learn.fit(Xsmall_sparse, ysmall, algorithm=a)
set.seed(1)
x2 <- L0Learn.fit(Xsmall_sparse, ysmall, algorithm=a)
expect_equal(x1$a0, x2$a0, info=a)
}
for (l in c("Logistic", "SquaredHinge")){
set.seed(1)
x1 <- L0Learn.fit(Xsmall_sparse, sign(ysmall), loss=l)
set.seed(1)
x2 <- L0Learn.fit(Xsmall_sparse, sign(ysmall), loss=l)
expect_equal(x1$a0, x2$a0, info=l)
}
})
test_that("Intercepts are passed between Swap iterations", {
skip_on_cran()
})
tmp <- L0Learn::GenSynthetic(n=100, p=1000, k=10, seed=1, rho=1.5, b0=0)
X <- tmp[[1]]
y <- tmp[[2]]
tol = 1e-4
if (sum(apply(X, 2, sd) == 0)) {
stop("X needs to have non-zero std for each column")
}
X_sparse <- as(X, "dgCMatrix")
test_that("When lambda0 is large, intecepts should be found similar for both sparse and dense methods", {
skip_on_cran()
BIGuserLambda <- list()
BIGuserLambda[[1]] <- c(logspace(2, -2, 10))
for (a in c("CD", "CDPSI")){
set.seed(1)
x1 <- L0Learn.fit(X_sparse, y, penalty="L0", intercept = TRUE, algorithm = a,
autoLambda=FALSE, lambdaGrid=BIGuserLambda, maxSuppSize=100)
set.seed(1)
x2 <- L0Learn.fit(X, y, penalty="L0", intercept = TRUE, algorithm = a,
autoLambda=FALSE, lambdaGrid=BIGuserLambda, maxSuppSize=100)
for (i in 1:length(x1$a0)){
if ((x1$suppSize[[1]][i] == 0) && (x2$suppSize[[1]][i] == 0)){
expect_equal(x1$a0[[1]][i], x2$a0[[1]][i])
} else if (x1$suppSize[[1]][i] == x2$suppSize[[1]][i]){
expect_equal(x1$a0[[1]][i], x2$a0[[1]][i], tolerance=1e-6, scale=x1$a0[[1]][i])
}
}
}
})
test_that("Intercepts are learned close to real values", {
skip_on_cran()
fineuserLambda <- list()
fineuserLambda[[1]] <- c(logspace(-1, -10, 100))
k = 10
for (a in c("CD", "CDPSI")){
for (b0 in c(-100, -10, -2, 2, 10, 100)){
tmp <- L0Learn::GenSynthetic(n=500, p=200, k=k, seed=1, rho=1, b0=b0)
X2 <- tmp[[1]]
y2 <- tmp[[2]]
tol = 1e-4
if (sum(apply(X2, 2, sd) == 0)) {
stop("X needs to have non-zero std for each column")
}
X2_sparse <- as(X2, "dgCMatrix")
x1 <- L0Learn.fit(X2_sparse, y2, penalty="L0", intercept = TRUE, algorithm = a,
autoLambda=FALSE, lambdaGrid=fineuserLambda, maxSuppSize=1000)
x2 <- L0Learn.fit(X2, y2, penalty="L0", intercept = TRUE, algorithm = a,
autoLambda=FALSE, lambdaGrid=fineuserLambda, maxSuppSize=1000)
for (i in 1:length(x1$suppSize[[1]])){
if (x1$suppSize[[1]][i] == k){
expect_lt(abs(x1$a0[[1]][i] - b0), abs(.01*b0))
}
}
for (i in 1:length(x2$suppSize[[1]])){
if (x2$suppSize[[1]][i] == k){
expect_lt(abs(x2$a0[[1]][i] - b0), abs(.01*b0))
}
}
}
}
}) |
getCytobandColors <- function(color.table=NULL, color.schema=c("circos", "biovizbase", "only.centromeres")) {
color.schema <- match.arg(color.schema)
if(!is.null(color.table)) {
return(color.table)
} else {
if(color.schema %in% names(.karyoploter.colors$cytobands$schemas)) {
return(.karyoploter.colors$cytobands$schemas[[color.schema]])
} else {
stop("Unknown color.schema. Available schemas for cytobands are: ", paste0(names(.karyoploter.colors$cytobands$schemas), collapse = ", "))
}
}
stop("Error in getCytobandColors")
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.