code
stringlengths 1
13.8M
|
---|
test_that("continuous ranges expand as expected", {
r <- continuous_range()
r$train(1)
expect_equal(r$range, c(1, 1))
r$train(10)
expect_equal(r$range, c(1, 10))
})
test_that("discrete ranges expand as expected", {
r <- discrete_range()
r$train("a")
expect_equal(r$range, "a")
r$train("b")
expect_equal(r$range, c("a", "b"))
r$train(letters)
expect_equal(r$range, letters)
}) |
downloadCivEDICCS <- function(years=c(1999, 2009, 2016)) {
if(is.null(years)){
stop(paste0("The argument ", sQuote("years"), " must not be null."))
}
if(any(!(years %in% c(1999, 2009, 2016)))){
stop(paste0("The argument ", sQuote("years"), " must have values of only ", sQuote("1999"), ", ", sQuote("2009"), ", or ", sQuote("2016"), "."))
}
linkURL <- "https://www.iea.nl/data-tools/repository"
txt <- c()
txt <- c(txt, paste0("Please manually download and extract the SPSS (*.sav) formatted CivED 1999, ICCS 2009, or ICCS 2016 study data files from the IEA Data Repository to a folder on your local system or network. ",
"After the following steps are completed, the ", dQuote("readCivEDICCS"), " function can be used to read in the data. ",
"See help page (?readCivEDICCS) for more details."))
txt <- c(txt, "\n")
txt <- c(txt, paste0("\t", "1) Launch the IEA Data Repository web URL (", linkURL ,") in your web browser."))
txt <- c(txt, paste0("\t", "2) Find your study (CivED or ICCS) and click the appropriate studies ", dQuote("year"), " link you wish to download."))
txt <- c(txt, paste0("\t", "3) Next, click on the link ", dQuote("SPSS Data & Documentation"), " to download the SPSS (*.sav) files, which are compatible with the ", dQuote("readCivEDICCS()"), " function in EdSurvey. ",
"Follow your web browser's prompts to download the resulting *.zip file to a folder location you can find later."))
txt <- c(txt, paste0("\t", "4) Locate your downloaded zip file (*.zip) container and use an extraction program to extract the folder's file contents. ",
"It is recommended to extract the SPSS (*.sav) files to an easy-to-remember folder path based on the study and year (e.g., for Microsoft Windows OS, ", pasteItems(sQuote(c("C:/EdSurveyData/CivED/1999/", "C:/EdSurveyData/ICCS/2009/"), "C:/EdSurveyData/ICCS/2016/")), ")."))
txt <- c(txt, "\n")
txt <- paste0(paste(paste(txt, collapse = "\n\n"),collapse="\n"),"\n\n")
eout(txt)
nav <- readline(prompt = paste0("Please enter 'Y' if you wish to launch this URL (", linkURL ,") in your browser: "))
if(tolower(trimws(nav))=="y"){
browseURL(linkURL)
}
return(invisible(NULL))
} |
modulationSpectrum = function(
x,
samplingRate = NULL,
scale = NULL,
from = NULL,
to = NULL,
amRes = 5,
maxDur = 5,
logSpec = FALSE,
windowLength = 15,
step = NULL,
overlap = 80,
wn = 'hanning',
zp = 0,
power = 1,
roughRange = c(30, 150),
amRange = c(10, 200),
returnMS = TRUE,
returnComplex = FALSE,
summaryFun = c('mean', 'median', 'sd'),
averageMS = FALSE,
reportEvery = NULL,
cores = 1,
plot = TRUE,
savePlots = NULL,
logWarp = NA,
quantiles = c(.5, .8, .9),
kernelSize = 5,
kernelSD = .5,
colorTheme = c('bw', 'seewave', 'heat.colors', '...')[1],
main = NULL,
xlab = 'Hz',
ylab = '1/KHz',
xlim = NULL,
ylim = NULL,
width = 900,
height = 500,
units = 'px',
res = NA,
...
) {
myPars = c(as.list(environment()), list(...))
myPars = myPars[!names(myPars) %in% c(
'x', 'samplingRate', 'scale', 'from', 'to', 'savePlots',
'reportEvery', 'cores', 'summaryFun', 'averageMS')]
pa = processAudio(
x,
samplingRate = samplingRate,
scale = scale,
from = from,
to = to,
funToCall = '.modulationSpectrum',
myPars = myPars,
reportEvery = reportEvery,
cores = cores,
savePlots = savePlots
)
if (!is.null(pa$input$savePlots) && pa$input$n > 1) {
try(htmlPlots(pa$input, savePlots = savePlots, changesAudio = FALSE,
suffix = "MS", width = paste0(width, units)))
}
if (!is.null(summaryFun) && any(!is.na(summaryFun))) {
temp = vector('list', pa$input$n)
for (i in 1:pa$input$n) {
if (!pa$input$failed[i]) {
temp[[i]] = summarizeAnalyze(
data.frame(roughness = pa$result[[i]]$roughness,
amFreq = pa$result[[i]]$amFreq,
amDep = pa$result[[i]]$amDep),
summaryFun = summaryFun,
var_noSummary = NULL)
}
}
idx_failed = which(pa$input$failed)
idx_ok = which(!pa$input$failed)
if (length(idx_failed) > 0) {
idx_ok = which(!pa$input$failed)
if (length(idx_ok) > 0) {
filler = temp[[idx_ok[1]]] [1, ]
filler[1, ] = NA
} else {
stop('Failed to analyze any input')
}
for (i in idx_failed) temp[[i]] = filler
}
mysum_all = cbind(data.frame(file = pa$input$filenames_base),
do.call('rbind', temp))
} else {
mysum_all = NULL
}
for (i in idx_failed) pa$result[[i]] = list(
original = NULL, processed = NULL, complex = NULL,
roughness = NULL, amFreq = NULL, amDep = NULL
)
original = processed = complex = roughness = amFreq = amDep = NULL
out_prep = c('original', 'processed', 'complex', 'roughness', 'amFreq', 'amDep')
if (pa$input$n == 1) {
for (op in out_prep) assign(noquote(op), pa$result[[1]] [[op]])
} else {
for (op in out_prep) assign(noquote(op), lapply(pa$result, function(x) x[[op]]))
}
op_prep2 = c('original', 'processed')
if (returnComplex) {
op_prep2 = c(op_prep2, 'complex')
} else {
complex = NULL
}
if (averageMS & pa$input$n > 1) {
for (op in op_prep2) {
assign(
noquote(op),
averageMatrices(
get(op) [idx_ok],
rFun = 'max',
cFun = 'median',
reduceFun = '+')
)
}
}
invisible(list(original = original,
processed = processed,
complex = complex,
roughness = roughness,
amFreq = amFreq,
amDep = amDep,
summary = mysum_all))
}
.modulationSpectrum = function(
audio,
amRes = 5,
maxDur = 5,
logSpec = FALSE,
windowLength = 15,
step = NULL,
overlap = 80,
wn = 'hanning',
zp = 0,
power = 1,
roughRange = c(30, 150),
amRange = c(10, 200),
returnMS = TRUE,
returnComplex = FALSE,
plot = TRUE,
savePlots = NULL,
logWarp = NA,
quantiles = c(.5, .8, .9),
kernelSize = 5,
kernelSD = .5,
colorTheme = c('bw', 'seewave', 'heat.colors', '...')[1],
main = NULL,
xlab = 'Hz',
ylab = '1/KHz',
xlim = NULL,
ylim = NULL,
width = 900,
height = 500,
units = 'px',
res = NA,
...
) {
if (is.null(step)) step = windowLength * (1 - overlap / 100)
step_points = round(step / 1000 * audio$samplingRate)
step = step_points / audio$samplingRate * 1000
windowLength_points = round(windowLength / 1000 * audio$samplingRate)
windowLength = windowLength_points / audio$samplingRate * 1000
overlap = 100 * (1 - step_points / windowLength_points)
max_am = 1000 / step / 2
if (max_am < roughRange[1]) {
warning(paste(
'roughRange outside the analyzed range of temporal modulation frequencies;',
'increase overlap / decrease step to improve temporal resolution,',
'or else look for roughness in a lower range'))
}
if (is.numeric(amRes)) {
nFrames = max(3, ceiling(max_am / amRes * 2))
} else {
nFrames = NULL
}
if (is.numeric(nFrames)) {
chunk_ms = windowLength + step * (nFrames - 1)
splitInto = max(1, ceiling(audio$duration * 1000 / chunk_ms))
if (chunk_ms > (audio$duration * 1000)) {
message(paste('The sound is too short to be analyzed with amRes =', amRes,
'Hz. Roughness is probably not measured correctly'))
chunk_ms = audio$duration
}
} else {
splitInto = max(1, ceiling(audio$duration / maxDur))
}
if (splitInto > 1) {
myseq = floor(seq(1, length(audio$sound), length.out = splitInto + 1))
myInput = vector('list', splitInto)
for (i in 1:splitInto) {
idx = myseq[i]:(myseq[i + 1])
myInput[[i]] = audio$sound[idx]
}
} else {
myInput = list(audio$sound)
}
out = vector('list', splitInto)
if (returnComplex) {
out_complex = out
} else {
out_aggreg_complex = NULL
}
for (i in 1:splitInto) {
ms_i = modulationSpectrumFragment(
myInput[[i]],
samplingRate = audio$samplingRate,
windowLength = windowLength,
windowLength_points = windowLength_points,
step = step,
step_points = step_points,
wn = wn,
zp = zp,
logSpec = logSpec,
power = power)
out[[i]] = ms_i$ms_half
if (returnComplex) {
out_complex[[i]] = ms_i$ms_complex
}
}
keep = which(unlist(lapply(out, function(x) !is.null(x))))
out = out[keep]
if (length(out) < 1) {
warning('The sound is too short or windowLength too long. Need at least 3 frames')
return(list('original' = NA,
'processed' = NA,
'complex' = NA,
'roughness' = NA,
'amFreq' = NA,
'amDep' = NA))
}
roughness = unlist(lapply(out, function(x)
getRough(x, roughRange, colNames = as.numeric(colnames(out[[1]])))))
am_list = lapply(out, function(x)
getAM(x, amRange = amRange, amRes = amRes))
amFreq = unlist(lapply(am_list, function(x) x$amFreq))
amDep = unlist(lapply(am_list, function(x) x$amDep))
if (!returnMS) {
result = list('original' = NULL,
'processed' = NULL,
'complex' = NULL,
'roughness' = roughness,
'amFreq' = amFreq,
'amDep' = amDep)
} else {
out_aggreg = averageMatrices(
out,
rFun = 'max',
cFun = 'median',
reduceFun = '+')
X = as.numeric(colnames(out_aggreg))
Y = as.numeric(rownames(out_aggreg))
if (returnComplex) {
out_aggreg_complex = averageMatrices(
out_complex,
rFun = 'max',
cFun = 'median',
reduceFun = '+')
}
if (is.numeric(logWarp)) {
neg_col = which(X < 0)
zero_col = which(X == 0)
pos_col = which(X > 0)
m_left = logMatrix(out_aggreg[, rev(neg_col)], base = logWarp)
m_right = logMatrix(out_aggreg[, pos_col], base = logWarp)
out_transf = cbind(m_left[, ncol(m_left):1],
out_aggreg[, zero_col, drop = FALSE], m_right)
X1 = as.numeric(colnames(out_transf))
Y1 = as.numeric(rownames(out_transf))
} else {
out_transf = out_aggreg
}
out_transf = gaussianSmooth2D(out_transf,
kernelSize = kernelSize,
kernelSD = kernelSD)
result = list('original' = out_aggreg,
'processed' = out_transf,
'complex' = out_aggreg_complex,
'roughness' = roughness,
'amFreq' = amFreq,
'amDep' = amDep)
}
if (is.character(audio$savePlots)) {
plot = TRUE
png(filename = paste0(audio$savePlots, audio$filename_noExt, "_MS.png"),
width = width, height = height, units = units, res = res)
}
if (plot) {
color.palette = switchColorTheme(colorTheme)
if (is.null(xlim)) xlim = c(X[1], -X[1])
if (is.null(ylim)) ylim = range(Y)
if (is.null(main)) {
if (audio$filename_noExt == 'sound') {
main = ''
} else {
main = audio$filename_noExt
}
}
if (is.numeric(logWarp)) {
filled.contour.mod(
x = X, y = Y, z = t(out_transf),
levels = seq(0, 1, length = 30),
color.palette = color.palette,
xlab = xlab, ylab = ylab,
bty = 'n', axisX = FALSE, axisY = FALSE,
main = main,
xlim = xlim, ylim = ylim,
...
)
max_tm = log(-X[1], logWarp)
xl = unique(round(logWarp ^ pretty(c(1, max_tm), n = 4)))
xl = c(-rev(xl), 0, xl)
xl = xl[abs(xl) < -X1[1]]
pos = apply(matrix(xl), 1, function(x) which.min(abs(x - X1)))
axis(side = 1,
at = X[pos],
labels = xl)
yseq = seq(1, length(Y), length.out = 7)
digits = 0
ry = round(Y1[yseq], digits = digits)
while (length(ry) > length(unique(ry))) {
digits = digits + 1
ry = round(Y1[yseq], digits = digits)
}
axis(side = 2,
at = round(Y[yseq]),
labels = ry)
} else {
filled.contour.mod(
x = X, y = Y, z = t(out_transf),
levels = seq(0, 1, length = 30),
color.palette = color.palette,
xlab = xlab, ylab = ylab, main = main,
bty = 'n', xlim = xlim, ylim = ylim, ...
)
}
abline(v = 0, lty = 3)
qntls = pDistr(as.numeric(out_transf), quantiles = quantiles)
par(new = TRUE)
contour(x = X, y = Y, z = t(out_transf),
levels = qntls, labels = quantiles * 100,
xaxs = 'i', yaxs = 'i',
axes = FALSE, frame.plot = FALSE,
xlim = xlim, ylim = ylim, ...)
par(new = FALSE)
if (is.character(audio$savePlots)) dev.off()
}
invisible(result)
}
modulationSpectrumFragment = function(sound,
samplingRate,
windowLength,
windowLength_points,
step,
step_points,
wn = 'hanning',
zp = 0,
logSpec = FALSE,
power = 1) {
step_seq = seq(1, length(sound) + 1 - windowLength_points, step_points)
if (length(step_seq) < 3) return(NULL)
s1 = seewave::stdft(
wave = as.matrix(sound),
wn = wn,
wl = windowLength_points,
f = samplingRate,
zp = zp,
step = step_seq,
scale = FALSE,
norm = FALSE,
complex = FALSE
)
if (logSpec) {
positives = which(s1 > 0)
nonpositives = which(s1 <= 0)
s1[positives] = log(s1[positives])
if (length(positives) > 0 & length(nonpositives) > 0) {
s1[nonpositives] = min(s1[positives])
}
s1 = s1 - min(s1) + 1e-16
}
ms_complex = specToMS(s1, windowLength = windowLength, step = step)
ms = abs(ms_complex)
symAxis = floor(nrow(ms) / 2) + 1
ms_half = ms[symAxis:nrow(ms),, drop = FALSE]
if (is.numeric(power) && power != 1) ms_half = ms_half ^ power
if (any(s1 != 0)) {
ms_half = ms_half - min(ms_half)
ms_half = ms_half / max(ms_half)
}
return(list(
ms_half = ms_half,
ms_complex = ms_complex
))
}
getRough = function(m, roughRange, colNames = NULL) {
if (is.null(colNames)) colNames = abs(as.numeric(colnames(m)))
rough_cols = which(colNames > roughRange[1] &
colNames < roughRange[2])
if (length(rough_cols) > 0) {
roughness = sum(m[, rough_cols]) / sum(m) * 100
} else {
roughness = 0
}
return(roughness)
}
averageMatrices = function(mat_list,
rFun = 'max',
cFun = 'median',
reduceFun = '+') {
nr = round(do.call(rFun, list(unlist(lapply(mat_list, nrow)))))
nc = round(do.call(cFun, list(unlist(lapply(mat_list, ncol)))))
mat_list_sameDim = lapply(mat_list, function(x) interpolMatrix(x, nr = nr, nc = nc))
agg = Reduce(reduceFun, mat_list_sameDim) / length(mat_list)
return(agg)
}
getAM = function(m,
amRange = c(10, 100),
amRes = NULL) {
if (is.null(amRes)) amRes = 0
colNames = abs(as.numeric(colnames(m)))
out = list(amFreq = NA, amDep = NA)
am = data.frame(freq = abs(colNames), amp = colSums(m))
am = am[order(am$freq), ]
am_sm = am
i = 1
while(i < nrow(am_sm)) {
if (abs(am_sm$freq[i] - am_sm$freq[i + 1]) < .1) {
am_sm$amp[i] = (am_sm$amp[i] + am_sm$amp[i + 1]) / 2
am_sm$amp[i + 1] = NA
i = i + 2
} else {
i = i + 1
}
}
am_sm = na.omit(am_sm)
am_smRan = am_sm[am_sm$freq >= amRange[1] & am_sm$freq <= amRange[2], ]
wl = max(3, round(amRes / (colNames[2] - colNames[1])))
temp = zoo::rollapply(
zoo::as.zoo(am_smRan$amp),
width = wl,
align = 'center',
function(x) {
middle = ceiling(length(x) / 2)
return(which.max(x) == middle)
})
idx = zoo::index(temp)[zoo::coredata(temp)]
if (length(idx) > 0) {
peaks = am_smRan[idx, ]
peaks = peaks[which.max(peaks$amp), ]
if (nrow(peaks) > 0) {
out$amFreq = peaks$freq
out$amDep = log10(peaks$amp / max(am_sm$amp)) * 20
}
}
return(out)
} |
summary_DD_TMB <- function(Assessment, state_space = FALSE) {
assign_Assessment_slots()
if(conv) current_status <- c(F_FMSY[length(F_FMSY)], B_BMSY[length(B_BMSY)], B_B0[length(B_B0)])
else current_status <- c(NA, NA, B_B0[length(B_B0)])
current_status <- data.frame(Value = current_status)
rownames(current_status) <- c("F/FMSY", "B/BMSY", "B/B0")
Value <- c(unlist(info$data[c(2,3,5,6)]))
Description <- c("alpha = Winf * (1-rho)",
"rho = (W_k+2 - Winf)/(W_k+1 - Winf)",
"Age of knife-edge selectivity",
"Weight at age k")
rownam <- c("alpha", "rho", "k", "w_k")
if(Assessment@obj$env$data$condition == "effort" && "log_omega" %in% names(obj$env$map)) {
Value <- c(Value, TMB_report$omega)
Description <- c(Description, "Catch SD (log-space)")
rownam <- c(rownam, "omega")
}
if(state_space && "log_tau" %in% names(obj$env$map)) {
Value <- c(Value, TMB_report$tau)
Description <- c(Description, "log-Recruitment deviation SD")
rownam <- c(rownam, "tau")
}
if("transformed_h" %in% names(obj$env$map)) {
Value <- c(Value, h)
Description <- c(Description, "Stock-recruit steepness")
rownam <- c(rownam, "h")
}
if("log_M" %in% names(obj$env$map)) {
Value <- c(Value, TMB_report$M)
Description <- c(Description, "Natural mortality")
rownam <- c(rownam, "M")
}
if(any(info$data$MW_hist > 0, na.rm = TRUE) && "log_sigma_W" %in% names(obj$env$map)) {
Value <- c(Value, TMB_report$sigma_W)
Description <- c(Description, "Mean weight SD")
rownam <- c(rownam, "sigma_W")
}
input_parameters <- data.frame(Value = Value, Description = Description, stringsAsFactors = FALSE)
rownames(input_parameters) <- rownam
if(conv) derived <- c(B0, N0, MSY, FMSY, BMSY, BMSY/B0)
else derived <- rep(NA, 6)
derived <- data.frame(Value = derived,
Description = c("Unfished biomass", "Unfished abundance", "Maximum sustainable yield (MSY)",
"Fishing mortality at MSY", "Biomass at MSY", "Depletion at MSY"),
stringsAsFactors = FALSE)
rownames(derived) <- c("B0", "N0", "MSY", "FMSY", "BMSY", "BMSY/B0")
model_estimates <- sdreport_int(SD)
if(!is.character(model_estimates)) {
rownames(model_estimates)[rownames(model_estimates) == "log_rec_dev"] <- paste0("log_rec_dev_", names(Dev))
}
model_name <- "Delay-Difference"
if(state_space) model_name <- paste(model_name, "(State-Space)")
output <- list(model = model_name,
current_status = current_status, input_parameters = input_parameters,
derived_quantities = derived, model_estimates = model_estimates,
log_likelihood = matrix(NLL, ncol = 1, dimnames = list(names(NLL), "Neg.LL")))
return(output)
}
rmd_DD_TMB <- function(Assessment, state_space = FALSE, ...) {
if(state_space) {
ss <- rmd_summary("Delay-Difference (State-Space)")
} else ss <- rmd_summary("Delay-Difference")
LH_section <- c(rmd_LAA(age = "1:info$LH$maxage", header = "
rmd_WAA(age = "1:info$LH$maxage"), rmd_LW(),
rmd_mat(age = "1:info$LH$maxage", mat = "ifelse(1:info$LH$maxage < info$data$k, 0, 1)",
fig.cap = "Assumed knife-edge maturity at age corresponding to length of 50% maturity."))
if(any(Assessment@obj$env$data$MW_hist > 0, na.rm = TRUE)) {
data_MW <- rmd_data_MW()
} else {
data_MW <- ""
}
data_section <- c(rmd_data_timeseries("Catch", header = "
rmd_data_timeseries("Index", is_matrix = is.matrix(Assessment@Obs_Index), nsets = ncol(Assessment@Obs_Index)),
data_MW)
assess_all <- c(rmd_R0(header = "
rmd_sel(age = "1:info$LH$maxage", sel = "ifelse(1:info$LH$maxage < info$data$k, 0, 1)",
fig.cap = "Knife-edge selectivity set to the age corresponding to the length of 50% maturity."))
if(Assessment@obj$env$data$condition == "effort") {
assess_data <- c(rmd_assess_fit("Catch", "catch"), rmd_assess_resid("Catch"), rmd_assess_qq("Catch", "catch"))
} else {
assess_data <- c(rmd_assess_fit("Catch", "catch", match = TRUE),
rmd_assess_fit_series(nsets = ncol(Assessment@Index)))
}
if(any(Assessment@obj$env$data$MW_hist > 0, na.rm = TRUE)) {
fit_MW <- rmd_assess_fit_MW()
} else {
fit_MW <- ""
}
assess_fit <- c(assess_all, assess_data, fit_MW)
if(state_space) {
assess_fit2 <- c(rmd_residual("Dev", fig.cap = "Time series of recruitment deviations.", label = Assessment@Dev_type),
rmd_residual("Dev", "SE_Dev", fig.cap = "Time series of recruitment deviations with 95% confidence intervals.",
label = Assessment@Dev_type, conv_check = TRUE))
assess_fit <- c(assess_fit, assess_fit2)
}
ts_output <- c(rmd_F(header = "
rmd_SSB_SSB0(), rmd_dynamic_SSB0("TMB_report$dynamic_SSB0"),
rmd_Kobe(), rmd_R(), rmd_N())
SR_calc <- c("SSB_SR <- SSB[1:info$data$ny]",
"if(info$data$SR_type == \"BH\") {",
" R_SR <- TMB_report$Arec * SSB_SR / (1 + TMB_report$Brec * SSB_SR)",
"} else {",
" R_SR <- TMB_report$Arec * SSB_SR * exp(-TMB_report$Brec * SSB_SR)",
"}",
"Rest <- R[1:info$data$ny + info$data$k]")
productivity <- c(rmd_SR(header = "
rmd_SR(fig.cap = "Stock-recruit relationship (trajectory plot).", trajectory = TRUE),
rmd_yield_F("DD"), rmd_yield_depletion("DD"), rmd_sp(), rmd_SPR(), rmd_YPR())
return(c(ss, LH_section, data_section, assess_fit, ts_output, productivity))
}
profile_likelihood_DD_TMB <- function(Assessment, ...) {
dots <- list(...)
if(!"R0" %in% names(dots) && !"h" %in% names(dots)) stop("Sequence of neither R0 nor h was not found. See help file.")
if(!is.null(dots$R0)) R0 <- dots$R0 else {
R0 <- Assessment@R0
profile_par <- "h"
}
if(!is.null(dots$h)) h <- dots$h else {
h <- Assessment@h
profile_par <- "R0"
}
map <- Assessment@obj$env$map
params <- Assessment@info$params
profile_grid <- expand.grid(R0 = R0, h = h)
joint_profile <- !exists("profile_par")
profile_fn <- function(i, Assessment, params, map) {
params$R0x <- log(profile_grid[i, 1] * Assessment@obj$env$data$rescale)
if(Assessment@info$data$SR_type == "BH") {
params$transformed_h <- logit((profile_grid[i, 2] - 0.2)/0.8)
} else {
params$transformed_h <- log(profile_grid[i, 2] - 0.2)
}
if(joint_profile) {
map$R0x <- map$transformed_h <- factor(NA)
} else {
if(profile_par == "R0") map$R0x <- factor(NA) else map$transformed_h <- factor(NA)
}
obj2 <- MakeADFun(data = Assessment@info$data, parameters = params, map = map, random = Assessment@obj$env$random,
DLL = "SAMtool", silent = TRUE)
opt2 <- optimize_TMB_model(obj2, Assessment@info$control)[[1]]
if(!is.character(opt2)) nll <- opt2$objective else nll <- NA
return(nll)
}
nll <- vapply(1:nrow(profile_grid), profile_fn, numeric(1), Assessment = Assessment, params = params, map = map) - Assessment@opt$objective
profile_grid$nll <- nll
if(joint_profile) {
pars <- c("R0", "h")
MLE <- vapply(pars, function(x, y) slot(y, x), y = Assessment, numeric(1))
} else {
pars <- profile_par
MLE <- slot(Assessment, pars)
}
output <- new("prof", Model = Assessment@Model, Name = Assessment@Name, Par = pars, MLE = MLE, grid = profile_grid)
return(output)
}
retrospective_DD_TMB <- function(Assessment, nyr, state_space = FALSE) {
assign_Assessment_slots(Assessment)
ny <- info$data$ny
k <- info$data$k
Year <- info$Year
moreRecruitYears <- max(Year) + 1:k
Year <- c(Year, moreRecruitYears)
retro_ts <- array(NA, dim = c(nyr+1, ny+k, 7))
TS_var <- c("F", "F_FMSY", "B", "B_BMSY", "B_B0", "R", "VB")
dimnames(retro_ts) <- list(Peel = 0:nyr, Year = Year, Var = TS_var)
retro_est <- array(NA, dim = c(nyr+1, length(SD$par.fixed[names(SD$par.fixed) != "log_rec_dev"]), 2))
dimnames(retro_est) <- list(Peel = 0:nyr, Var = names(SD$par.fixed)[names(SD$par.fixed) != "log_rec_dev"],
Value = c("Estimate", "Std. Error"))
lapply_fn <- function(i, info, obj, state_space) {
ny_ret <- ny - i
info$data$ny <- ny_ret
info$data$C_hist <- info$data$C_hist[1:ny_ret]
info$data$E_hist <- info$data$E_hist[1:ny_ret]
info$data$I_hist <- info$data$I_hist[1:ny_ret, , drop = FALSE]
info$data$I_sd <- info$data$I_sd[1:ny_ret, , drop = FALSE]
info$data$MW_hist <- info$data$MW_hist[1:ny_ret]
if(state_space) info$params$log_rec_dev <- rep(0, ny_ret)
obj2 <- MakeADFun(data = info$data, parameters = info$params, random = obj$env$random, map = obj$env$map,
inner.control = info$inner.control, DLL = "SAMtool", silent = TRUE)
mod <- optimize_TMB_model(obj2, info$control)
opt2 <- mod[[1]]
SD <- mod[[2]]
if(!is.character(opt2)) {
report <- obj2$report(obj2$env$last.par.best)
ref_pt <- ref_pt_DD(info$data, report$Arec, report$Brec, report$M)
report <- c(report, ref_pt)
FF <- c(report$F, rep(NA, k + i))
F_FMSY <- FF/report$FMSY
B <- c(report$B, rep(NA, k - 1 + i))
B_BMSY <- B/report$BMSY
B_B0 <- B/B0
R <- c(report$R, rep(NA, i))
VB <- B
retro_ts[i+1, , ] <<- cbind(FF, F_FMSY, B, B_BMSY, B_B0, R, VB)
sumry <- summary(SD, "fixed")
sumry <- sumry[rownames(sumry) != "log_rec_dev", drop = FALSE]
retro_est[i+1, , ] <<- sumry
return(SD$pdHess)
}
return(FALSE)
}
conv <- vapply(0:nyr, lapply_fn, logical(1), info = info, obj = obj, state_space = state_space)
if(any(!conv)) warning("Peels that did not converge: ", paste0(which(!conv) - 1, collapse = " "))
retro <- new("retro", Model = Assessment@Model, Name = Assessment@Name, TS_var = TS_var, TS = retro_ts,
Est_var = dimnames(retro_est)[[2]], Est = retro_est)
attr(retro, "TS_lab") <- c("Fishing mortality", expression(F/F[MSY]), "Biomass", expression(B/B[MSY]), expression(B/B[0]),
"Recruitment", "Vulnerable biomass")
return(retro)
}
summary_DD_SS <- function(Assessment) summary_DD_TMB(Assessment, TRUE)
rmd_DD_SS <- function(Assessment, ...) rmd_DD_TMB(Assessment, TRUE, ...)
profile_likelihood_DD_SS <- profile_likelihood_DD_TMB
retrospective_DD_SS <- function(Assessment, nyr) retrospective_DD_TMB(Assessment, nyr, TRUE)
plot_yield_DD <- function(data, report, fmsy, msy, xaxis = c("F", "Biomass", "Depletion")) {
xaxis <- match.arg(xaxis)
F.vector <- seq(0, 2.5 * fmsy, length.out = 1e2)
yield <- lapply(F.vector,
yield_fn_DD, M = report$M, Alpha = data$Alpha,
Rho = data$Rho, wk = data$wk, SR = data$SR_type,
Arec = report$Arec, Brec = report$Brec, opt = FALSE)
Biomass <- vapply(yield, getElement, numeric(1), "B")
Yield <- vapply(yield, getElement, numeric(1), "Yield")
R <- vapply(yield, getElement, numeric(1), "R")
ind <- R >= 0
if(xaxis == "F") {
plot(F.vector[ind], Yield[ind], typ = 'l', xlab = "Fishing mortality",
ylab = "Equilibrium yield")
segments(x0 = fmsy, y0 = 0, y1 = msy, lty = 2)
segments(x0 = 0, y0 = msy, x1 = fmsy, lty = 2)
abline(h = 0, col = 'grey')
}
if(xaxis == "Biomass") {
plot(Biomass[ind], Yield[ind], typ = 'l', xlab = "Biomass",
ylab = "Equilibrium yield")
segments(x0 = report$BMSY, y0 = 0, y1 = msy, lty = 2)
segments(x0 = 0, y0 = msy, x1 = report$BMSY, lty = 2)
abline(h = 0, col = 'grey')
}
if(xaxis == "Depletion") {
plot(Biomass[ind]/report$B0, Yield[ind], typ = 'l',
xlab = expression(B/B[0]), ylab = "Equilibrium yield")
segments(x0 = report$BMSY/report$B0, y0 = 0, y1 = msy, lty = 2)
segments(x0 = 0, y0 = msy, x1 = report$BMSY/report$B0, lty = 2)
abline(h = 0, col = 'grey')
}
invisible(data.frame(F = F.vector[ind], Yield = Yield[ind], B = Biomass[ind], B_B0 = Biomass[ind]/report$B0))
} |
options(continue=" ", width=60)
options(SweaveHooks=list(fig=function() par(mar=c(4.1, 4.1, .3, 1.1))))
pdf.options(pointsize=8)
library(survival, quietly=TRUE)
getOption("SweaveHooks")[["fig"]]()
ksurv <- survfit(Surv(time, status) ~1, data=kidney)
plot(ksurv, fun="cumhaz", conf.int=FALSE, lwd=2,
xlab="Time since catheter insertion", ylab="Cumulative Hazard")
lines(c(0, 45, 500, 560), c(0, .55, 2.7, 4), col=2, lwd=2)
kdata2 <- survSplit(Surv(time, status) ~., data=kidney, cut=c(45, 500),
episode="interval")
kfit1 <- coxph(Surv(time, status) ~ age + sex, kidney, ties='breslow')
kfit2 <- glm(status ~ age + sex + factor(interval) -1 +
offset(log(time-tstart)), family=poisson, data=kdata2)
cbind(Cox= summary(kfit1)$coefficients[,c(1,3)],
poisson = summary(kfit2)$coefficients[1:2, 1:2])
utime <- sort(unique(kidney$time[kidney$status==1]))
kdata3 <- survSplit(Surv(time, status) ~., data=kidney, cut=utime,
episode="interval")
kdata3 <- subset(kdata3, time == c(utime,0)[interval])
kfit3 <- glm(status ~ age + sex + factor(interval) -1,
family=poisson, data=kdata3)
kfit4 <- glm(status ~ age + sex + factor(interval) -1,
family=binomial, data=kdata3)
rbind(poisson= coef(kfit3)[1:2], binomial = coef(kfit4)[1:2])
getOption("SweaveHooks")[["fig"]]()
counts <- c(table(kdata3$interval))
xmat <- as.matrix(kdata3[,c('age', 'sex')])
centers <- rowsum(xmat, kdata3$interval) / counts
xmat2 <- xmat - centers[kdata3$interval,]
kfit4a <- glm(status ~ xmat2 + factor(interval) -1, poisson, kdata3)
temp <- coef(kfit4a)[-(1:2)]
phat <- with(kdata3, tapply(status, interval, sum)) /counts
matplot(1:length(counts), cbind(phat, exp(temp)), log='y',
xlab="Interval", ylab="Simple event rate")
legend(5, .5, c("Rate", "Poisson intercept"), pch="12", col=1:2)
kdata3$phat <- phat[kdata3$interval]
logit <- function(x) log(x/(1-x))
kfit4b <- glm(status ~ xmat2 + offset(log(phat)), poisson, kdata3)
kfit4c <- glm(status ~ xmat2, poisson, kdata3)
kfit4d <- glm(status ~ xmat2 + offset(logit(phat)), binomial, kdata3,
subset=(phat<1))
kfit4e <- glm(status ~ xmat2, binomial, kdata3,
subset=(phat<1))
rbind(Cox= coef(kfit1), poisson=coef(kfit4a)[1:2],
poisson2 = coef(kfit4b)[2:3], poisson3 = coef(kfit4c)[2:3],
binomial2 = coef(kfit4d)[2:3], binomial3 = coef(kfit4e)[2:3]) |
financial_cof_hv_switchgear_distribution <- function(hv_asset_category,
access_factor_criteria){
`Asset Register Category` = `Health Index Asset Category` = `Asset Category` = NULL
asset_category <- gb_ref$categorisation_of_assets %>%
dplyr::filter(`Asset Register Category` == hv_asset_category) %>%
dplyr::select(`Health Index Asset Category`) %>% dplyr::pull()
reference_costs_of_failure_tf <- dplyr::filter(gb_ref$reference_costs_of_failure,
`Asset Register Category` ==
hv_asset_category)
fcost <- reference_costs_of_failure_tf$`Financial - (GBP)`
type_financial_factor <- 1
access_financial_factors <- gb_ref$access_factor_swg_tf_asset
access_financial_factors_tf <- dplyr::filter(access_financial_factors,
`Asset Category` ==
"HV Switchgear (GM) - Distribution")
if (access_factor_criteria == "Type A") {
access_finacial_factor <-
access_financial_factors_tf$
`Access Factor: Type A Criteria - Normal Access ( & Default Value)`
}
else if (access_factor_criteria == "Type B") {
access_finacial_factor <-
access_financial_factors_tf$
`Access Factor: Type B Criteria - Constrained Access or Confined Working Space`
}
else if (access_factor_criteria == "Type C") {
access_finacial_factor <-
access_financial_factors_tf$
`Access Factor: Type C Criteria - Underground substation`
}
fc_factor <- type_financial_factor * access_finacial_factor
return(fc_factor * fcost)
}
safety_cof_hv_switchgear_distribution <- function(hv_asset_category,
location_risk,
type_risk){
`Asset Register Category` = `Health Index Asset Category` = `Asset Category` = NULL
asset_category <- gb_ref$categorisation_of_assets %>%
dplyr::filter(`Asset Register Category` == hv_asset_category) %>%
dplyr::select(`Health Index Asset Category`) %>% dplyr::pull()
reference_costs_of_failure_tf <- dplyr::filter(gb_ref$reference_costs_of_failure,
`Asset Register Category` ==
hv_asset_category)
scost <- reference_costs_of_failure_tf$`Safety - (GBP)`
if (location_risk == "Default") location_risk <- "Medium (Default)"
if (location_risk == "Medium") location_risk <- "Medium (Default)"
if (type_risk == "Default") type_risk <- "Medium"
safety_conseq_factor_sg_tf_oh <- gb_ref$safety_conseq_factor_sg_tf_oh
row_no <- which(safety_conseq_factor_sg_tf_oh$
`Safety Consequence Factor - Switchgear, Transformers & Overhead Lines...2` ==
location_risk)
col_no <- grep(type_risk, colnames(safety_conseq_factor_sg_tf_oh))
safety_consequence_factor <- safety_conseq_factor_sg_tf_oh[row_no, col_no]
safety_cof <- safety_consequence_factor * scost
return(safety_cof)
}
environmental_cof_hv_switchgear_distribution <- function(hv_asset_category,
type_env_factor,
prox_water,
bunded){
`Asset Register Category` = `Health Index Asset Category` = `Asset Category` =
`Type environment factor` = NULL
asset_category <- gb_ref$categorisation_of_assets %>%
dplyr::filter(`Asset Register Category` == hv_asset_category) %>%
dplyr::select(`Health Index Asset Category`) %>% dplyr::pull()
reference_costs_of_failure_tf <- dplyr::filter(gb_ref$reference_costs_of_failure,
`Asset Register Category` ==
hv_asset_category)
ecost <- reference_costs_of_failure_tf$`Environmental - (GBP)`
asset_type_env_factor <- gb_ref$type_enviromental_factor %>%
dplyr::filter(`Type environment factor` == asset_category)
type_environmental_factor <- asset_type_env_factor[[type_env_factor]]
size_environmental_factor <- 1
location_environ_al_factor <- gb_ref$location_environ_al_factor
location_environ_al_factor_tf <- dplyr::filter(location_environ_al_factor,
`Asset Register Category` ==
asset_category)
if (bunded == "Default") {
bunding_factor <- 1
} else if (bunded == "Yes") {
bunding_factor <-
location_environ_al_factor_tf$`Bunding Factor: Bunded`
} else if (bunded == "No") {
bunding_factor <-
location_environ_al_factor_tf$`Bunding Factor: Not bunded`
}
if(prox_water == "Default") {
prox_factor <- 1
} else if (prox_water >= 40 && prox_water < 80) {
prox_factor <- location_environ_al_factor_tf$
`Proximity Factor: Close to Water Course (between 40m and 80m)`
} else if (prox_water >= 80 && prox_water < 120) {
prox_factor <- location_environ_al_factor_tf$
`Proximity Factor: Moderately Close to Water Course (between 80m and 120m)`
} else if (prox_water > 120) {
prox_factor <- location_environ_al_factor_tf$
`Proximity Factor: Not Close to Water Course (>120m) or No Oil`
} else if (prox_water < 40) {
prox_factor <- location_environ_al_factor_tf$
`Proximity Factor: Very Close to Water Course (<40m)`
}
location_environmental_factor <- prox_factor * bunding_factor
environmental_consequences_factor <- (type_environmental_factor *
size_environmental_factor *
location_environmental_factor)
environmental_cof <- environmental_consequences_factor * ecost
return(environmental_cof)
}
network_cof_hv_switchgear_distribution <- function(hv_asset_category,
no_customers,
kva_per_customer = "Default") {
`Asset Register Category` = `Health Index Asset Category` = `Asset Category` = NULL
asset_category <- gb_ref$categorisation_of_assets %>%
dplyr::filter(`Asset Register Category` == hv_asset_category) %>%
dplyr::select(`Health Index Asset Category`) %>% dplyr::pull()
reference_costs_of_failure_tf <- dplyr::filter(gb_ref$reference_costs_of_failure,
`Asset Register Category` ==
hv_asset_category)
ncost <- reference_costs_of_failure_tf$`Network Performance - (GBP)`
ref_nw_perf_cost_fail_lv_hv <- gb_ref$ref_nw_perf_cost_fail_lv_hv
ref_nw_perf_cost_fail_lv_hv_tf <- dplyr::filter(ref_nw_perf_cost_fail_lv_hv,
`Asset Category` ==
asset_category)
ref_no_cust <-
ref_nw_perf_cost_fail_lv_hv_tf$`Reference Number of Connected Customers`
customer_no_adjust_lv_hv_asset <- gb_ref$customer_no_adjust_lv_hv_asset
for (n in 1:nrow(customer_no_adjust_lv_hv_asset)){
if (kva_per_customer == 'Default'){
adj_cust_no <- 1
break
} else if (kva_per_customer >= as.numeric(
customer_no_adjust_lv_hv_asset$Lower[n]) &
kva_per_customer < as.numeric(
customer_no_adjust_lv_hv_asset$Upper[n])){
adj_cust_no <-
customer_no_adjust_lv_hv_asset$
`No. of Customers to be used in the derivation of Customer Factor`[n]
break
}
}
adj_cust_no <-
adj_cust_no %>% stringr::str_match_all("[0-9]+") %>% unlist %>% as.numeric
customer_factor <- (adj_cust_no * no_customers) / ref_no_cust
customer_sensitivity_factor <- 1
network_performance_consequence_factor <- customer_factor *
customer_sensitivity_factor
network_cof <- network_performance_consequence_factor * ncost
return(network_cof)
} |
ScaleKernel <- function(x, X, h=NULL, K='epan',supp=NULL){
N <- length(x)
n <- length(X)
if (K!='epan') {
message('Epanechnikov kernel is only supported currently. It uses Epanechnikov kernel automatically')
}
if (is.null(supp)==TRUE) {
supp <- c(0,1)
}
if (is.null(h)==TRUE) {
h <- 0.25*n^(-1/5)*(supp[2]-supp[1])
}
xTmp <- matrix(rep(x,n),nrow=N)
XTmp <- matrix(rep(X,N),ncol=n,byrow=TRUE)
Tmp <- xTmp-XTmp
KhTmp <- (3/4)*(1-(Tmp/h)^2)*dunif(Tmp/h,-1,1)*2/h
return(KhTmp)
} |
"bisection.search" <- function(x1, x2, f, tol = 1e-07,
niter = 25, f.extra = NA, upcross.level = 0) {
f1 <- f(x1, f.extra) - upcross.level
f2 <- f(x2, f.extra) - upcross.level
if (f1 > f2)
stop(" f1 must be < f2 ")
iter <- niter
for (k in 1:niter) {
xm <- (x1 + x2)/2
fm <- f(xm, f.extra) - upcross.level
if (fm < 0) {
x1 <- xm
f1 <- fm
}
else {
x2 <- xm
f2 <- fm
}
if (abs(fm) < tol) {
iter <- k
break
}
}
xm <- (x1 + x2)/2
fm <- f(xm, f.extra) - upcross.level
list(x = xm, fm = fm, iter = iter)
} |
NULL
option <- function(arg) {
if (missing(arg)) return(none)
if (is.null(arg)) return(none)
if (class(arg) == "optional") {
if (attr(arg, "option_none")) return(FALSE)
else return(arg)
}
attr(arg, "option_class") <- attr(arg, "class")
attr(arg, "option_none") <- FALSE
attr(arg, "class") <- "optional"
return(arg)
}
some <- function(arg) {
if (class(arg) == "optional") {
return(!attr(arg, "option_none"))
}
return(FALSE)
}
none <- option(TRUE)
attr(none, "option_none") <- TRUE
opt_unwrap <- function(opt) {
if (class(opt) != "optional")
return(opt)
if (attr(opt, "option_none"))
return(NULL)
attr(opt, "class") <- attr(opt, "option_class")
attr(opt, "option_class") <- NULL
attr(opt, "option_none") <- NULL
return(opt)
}
`==.optional` <- function(e1, e2) {
if (class(e1) == "optional" && attr(e1, "option_none"))
return(class(e2) == "optional" && attr(e2, "option_none"))
if (class(e2) == "optional" && attr(e2, "option_none"))
return(class(e1) == "optional" && attr(e1, "option_none"))
return(opt_unwrap(e1) == opt_unwrap(e2))
}
make_opt <- function(fun, stop_if_none = FALSE, fun_if_none = NULL) {
return(function(...) {
args <- list(...)
to_null <- c()
if (length(args) != 0) {
for (i in 1:length(args)) {
if (class(args[[i]]) != "optional") next
if (args[[i]] == none) {
if (!is.null(fun_if_none))
fun_if_none()
if (stop_if_none) return(none)
to_null <- c(to_null, i)
}
else {
attr(args[[i]], "class") <- attr(args[[i]], "option_class")
attr(args[[i]], "option_class") <- NULL
attr(args[[i]], "option_none") <- NULL
}
}
}
args[to_null] <- NULL
tryCatch(ret <- do.call(fun, args),
error = function(e) {
ret <- NULL
}
)
if (is.null(ret))
return(none)
else
return(option(ret))
})
}
print.optional <- function(x, ...) {
if (attr(x, "option_none")) {
print("None", ...)
} else {
attr(x, "class") <- attr(x, "option_class")
attr(x, "option_class") <- NULL
attr(x, "option_none") <- NULL
print(x, ...)
}
}
opt_call_match_ <- function(fun, x) {
if (length(formalArgs(fun)) != 0) {
return(fun(x))
}
else {
return(fun())
}
}
match_with <- function(x, ...) {
args <- list(...)
n <- length(args)
if (n < 3 || n %% 2 != 0) {
write("match_with: Wrong number of parameters", stderr())
return(none)
}
c_opt <- make_opt(c)
res_ret <- none
for (i in seq(1, n, 2)) {
pattern <- args[[i]]
res_function <- args[[i + 1]]
if ("fseq" %in% class(pattern)) {
ret <- pattern(x)
if (!is.null(ret) && x == ret) {
res_ret <- c_opt(res_ret, opt_call_match_(res_function, x))
if (is.null(attr(res_function, "option_fallthrough"))) {
break
}
}
}
else if ("list" %in% class(pattern)) {
if (x %in% pattern) {
res_ret <- c_opt(res_ret, opt_call_match_(res_function, x))
if (is.null(attr(res_function, "option_fallthrough"))) {
break
}
}
}
else if (x == pattern) {
res_ret <- c_opt(res_ret, opt_call_match_(res_function, x))
if (is.null(attr(res_function, "option_fallthrough"))) {
break
}
}
}
return(res_ret)
}
fallthrough <- function(fun) {
if (class(fun) == "function")
attr(fun, "option_fallthrough") <- TRUE
return(fun)
} |
if(getRversion() >= "2.15.1") utils::globalVariables(c("ts","status"))
plotErrorRateByHour <-function (dataFrame)
{
nhoursperbreak = 1
nhours = difftime(max(dataFrame$ts,na.rm=TRUE), min(dataFrame$ts, na.rm=TRUE), units = "hours")
if(nhours > 24)
{
nhoursperbreak = as.integer(nhours/24)+1
}
p = ggplot(dataFrame,aes(as.POSIXct(cut(ts,breaks="hour")),fill=status))
p = p + geom_histogram(binwidth=3600)
p = p + scale_x_datetime(breaks = date_breaks(paste(nhoursperbreak,"hour")))
p = p + theme(axis.text.x = element_text(angle=60,vjust = 1.1, hjust=1.1))
p = p + ylab("Request Rate and Status by Hour")
p = p + xlab("Hour of day")
p = p + ggtitle("Count")
return(p)
} |
drop_term <-
function(curr.index,data,maximal.mod){
big.X<-maximal.mod$x
full.terms<-attributes(big.X)$assign
uni<-unique(full.terms[curr.index==1])
uni<-uni[uni>0]
term.labels<-attr(summary(maximal.mod)$terms,"term.labels")[uni]
term.order<-attr(summary(maximal.mod)$terms,"order")[uni]
term.factors<-attr(summary(maximal.mod)$terms,"factors")[,uni]
K<-length(term.labels[term.order==1])
can_drop<-c()
if(max(term.order)>1){
can_drop<-term.labels[term.order==max(term.order)]
candos<-(1:length(term.labels[term.order<max(term.order)]))[-(1:K)]
for(ttt in candos){
tls<-(1:K)[term.factors[-1,ttt]==1]
ntls<-(1:K)[term.factors[-1,ttt]==0]
ok<-c()
for(q in 1:length(ntls)){
TLS<-c(tls,ntls[q])
int<-rep(0,K)
int[TLS]<-1
run<-as.numeric(apply(matrix(rep(int,dim(term.factors)[2]),nrow=K,byrow=FALSE)==term.factors[-1,],2,all))
ok[q]<-ifelse(sum(run)==0,1,0)}
if(all(ok==1)){
can_drop<-c(can_drop,term.labels[ttt])}}}
can_drop} |
"meapsingle"
|
context("Message Composition")
test_that("composing a simple message is possible", {
email <- compose_email()
expect_is(
object = email,
class = "email_message"
)
expect_equal(
length(email), 4
)
expect_equal(
names(email),
c("html_str", "html_html", "attachments", "images")
)
expect_is(
object = email$html_str,
class = "character"
)
expect_is(
object = email$html_html,
class = "character"
)
expect_is(
object = email$attachments,
class = "list"
)
})
test_that("email components appear in the HTML message", {
email <- compose_email(body = "test_text_in_body")
expect_true(
grepl("test_text_in_body", email$html_str)
)
email <- compose_email(header = "test_text_in_header")
expect_true(
grepl("test_text_in_header", email$html_str)
)
email <- compose_email(header = "test_text_in_footer")
expect_true(
grepl("test_text_in_footer", email$html_str)
)
email <-
compose_email(
body = "test_text_in_body",
header = "test_text_in_header",
footer = "test_text_in_footer"
)
expect_true(
all(
c(
grepl("test_text_in_body", email$html_str),
grepl("test_text_in_header", email$html_str),
grepl("test_text_in_footer", email$html_str)
)
)
)
email <-
compose_email(
body = "test_text_in_body",
title = "email_title"
)
expect_true(
grepl("<title>email_title</title>", email$html_str)
)
email <-
compose_email(
body = blocks(block_text("test_text_in_body_block")),
header = blocks(block_text("test_text_in_header_block")),
footer = blocks(block_text("test_text_in_footer_block"))
)
expect_true(
all(
c(
grepl("test_text_in_body_block", email$html_str),
grepl("test_text_in_header_block", email$html_str),
grepl("test_text_in_footer_block", email$html_str)
)
)
)
})
test_that("composing a message with local inline images is possible", {
library(ggplot2)
plot <-
ggplot(data = mtcars, aes(x = disp, y = hp, color = wt, size = mpg)) +
geom_point()
plot_html <-
add_ggplot(
plot,
height = 5, width = 7
)
body_input <-
glue::glue(
"
Here is a plot:
{plot_html}
"
) %>% as.character()
email <- compose_email(body = md(body_input))
expect_is(
object = email,
class = "email_message"
)
expect_equal(
length(email), 4
)
expect_equal(
names(email),
c("html_str", "html_html", "attachments", "images")
)
expect_is(
object = email$html_str,
class = "character"
)
expect_is(
object = email$html_html,
class = "character"
)
expect_is(
object = email$attachments,
class = "list"
)
expect_is(
object = email$images,
class = "list"
)
expect_is(
object = email$images[[1]],
class = "character"
)
}) |
getIncludeColumns <- function() {
c("id", "sex", "age", "birth", "exit", "population", "condition", "origin",
"first_name", "second_name")
} |
plot.fpcad <-
function(x, nscore=c(1, 2), main = "PCA of probability density functions", sub.title=NULL, color = NULL, fontsize.points = 1.5, ...)
{
if (length(nscore) > 2)
warning(paste("Since dad-4, nscore must be a length 2 numeric vector. The scores number", nscore[1], "and", nscore[2], "are plotted."))
nscore <- nscore[1:2]
inertia=x$inertia$inertia
coor=x$scores[-1]
if (length(nscore) > 2)
nscore <- nscore[1:2]
if (max(nscore)>ncol(coor))
stop("The components of nscore must be smaller than the number of score columns in the x$scores data frame")
if (!is.null(color))
coor <- data.frame(coor, color = color, stringsAsFactors = FALSE)
group=x$scores[, 1]
i1=nscore[1]; i2=nscore[2]
graph <- ggplot(coor)
graph <- graph + aes_q(as.name(names(coor)[i1]), as.name(names(coor)[i2]),
label = as.character(group))
if (!is.null(color)) {
graph <- graph + aes(colour = I(color))
}
graph <- graph + geom_text(fontface = "bold", size = 4.2*fontsize.points)
graph <- graph + labs(title = main, subtitle = sub.title,
x = paste0(names(coor)[i1], " (", inertia[i1], "%)"),
y = paste0(names(coor)[i2], " (", inertia[i2], "%)"))
print(graph)
return(invisible(NULL))
} |
library(parsnip)
library(dplyr)
library(rlang)
library(testthat)
context("model registration")
test_by_col <- function(a, b) {
for (i in union(names(a), names(b))) {
expect_equal(a[[i]], b[[i]])
}
}
test_that('adding a new model', {
set_new_model("sponge")
mod_items <- get_model_env() %>% env_names()
sponges <- grep("sponge", mod_items, value = TRUE)
exp_obj <- c('sponge_modes', 'sponge_fit', 'sponge_args',
'sponge_predict', 'sponge_pkgs', 'sponge')
expect_equal(sort(sponges), sort(exp_obj))
expect_equal(
get_from_env("sponge"),
tibble(engine = character(0), mode = character(0))
)
test_by_col(
get_from_env("sponge_pkgs"),
tibble(engine = character(0), pkg = list(), mode = character(0))
)
expect_equal(
get_from_env("sponge_modes"), "unknown"
)
test_by_col(
get_from_env("sponge_args"),
dplyr::tibble(engine = character(0), parsnip = character(0),
original = character(0), func = vector("list"),
has_submodel = logical(0))
)
test_by_col(
get_from_env("sponge_fit"),
tibble(engine = character(0), mode = character(0), value = vector("list"))
)
test_by_col(
get_from_env("sponge_predict"),
tibble(engine = character(0), mode = character(0),
type = character(0), value = vector("list"))
)
expect_error(set_new_model())
expect_error(set_new_model(2))
expect_error(set_new_model(letters[1:2]))
})
test_that('adding a new mode', {
set_model_mode("sponge", "classification")
expect_equal(get_from_env("sponge_modes"), c("unknown", "classification"))
expect_error(set_model_mode("sponge"))
})
test_that('adding a new engine', {
set_model_engine("sponge", mode = "classification", eng = "gum")
test_by_col(
get_from_env("sponge"),
tibble(engine = "gum", mode = "classification")
)
expect_equal(get_from_env("sponge_modes"), c("unknown", "classification"))
expect_error(set_model_engine("sponge", eng = "gum"))
expect_error(set_model_engine("sponge", mode = "classification"))
expect_error(
set_model_engine("sponge", mode = "regression", eng = "gum"),
"'regression' is not a known mode"
)
})
test_that('adding a new package', {
set_dependency("sponge", "gum", "trident")
expect_error(set_dependency("sponge", "gum", letters[1:2]))
expect_error(set_dependency("sponge", "gummies", "trident"))
expect_error(set_dependency("sponge", "gum", "trident", mode = "regression"))
test_by_col(
get_from_env("sponge_pkgs"),
tibble(engine = "gum", pkg = list("trident"), mode = "classification")
)
set_dependency("sponge", "gum", "juicy-fruit", mode = "classification")
test_by_col(
get_from_env("sponge_pkgs"),
tibble(engine = "gum",
pkg = list(c("trident", "juicy-fruit")),
mode = "classification")
)
test_by_col(
get_dependency("sponge"),
tibble(engine = "gum",
pkg = list(c("trident", "juicy-fruit")),
mode = "classification")
)
})
test_that('adding a new argument', {
set_model_arg(
model = "sponge",
eng = "gum",
parsnip = "modeling",
original = "modelling",
func = list(pkg = "foo", fun = "bar"),
has_submodel = FALSE
)
set_model_arg(
model = "sponge",
eng = "gum",
parsnip = "modeling",
original = "modelling",
func = list(pkg = "foo", fun = "bar"),
has_submodel = FALSE
)
args <- get_from_env("sponge_args")
expect_equal(sum(args$parsnip == "modeling"), 1)
test_by_col(
get_from_env("sponge_args"),
tibble(engine = "gum", parsnip = "modeling", original = "modelling",
func = list(list(pkg = "foo", fun = "bar")),
has_submodel = FALSE)
)
expect_error(
set_model_arg(
model = "lunchroom",
eng = "gum",
parsnip = "modeling",
original = "modelling",
func = list(pkg = "foo", fun = "bar"),
has_submodel = FALSE
)
)
expect_error(
set_model_arg(
model = "sponge",
eng = "gum",
parsnip = "modeling",
func = list(pkg = "foo", fun = "bar"),
has_submodel = FALSE
)
)
expect_error(
set_model_arg(
model = "sponge",
eng = "gum",
original = "modelling",
func = list(pkg = "foo", fun = "bar"),
has_submodel = FALSE
)
)
expect_error(
set_model_arg(
model = "sponge",
eng = "gum",
parsnip = "modeling",
original = "modelling",
func = "foo::bar",
has_submodel = FALSE
)
)
expect_error(
set_model_arg(
model = "sponge",
eng = "gum",
parsnip = "modeling",
original = "modelling",
func = list(pkg = "foo", fun = "bar"),
has_submodel = 2
)
)
expect_error(
set_model_arg(
model = "sponge",
eng = "gum",
parsnip = "modeling",
original = "modelling",
func = list(pkg = "foo", fun = "bar")
)
)
expect_error(
set_model_arg(
model = "sponge",
eng = "gum",
parsnip = "yodeling",
original = "yodelling",
func = c(foo = "a", bar = "b"),
has_submodel = FALSE
)
)
expect_error(
set_model_arg(
model = "sponge",
eng = "gum",
parsnip = "yodeling",
original = "yodelling",
func = c(foo = "a"),
has_submodel = FALSE
)
)
expect_error(
set_model_arg(
model = "sponge",
eng = "gum",
parsnip = "yodeling",
original = "yodelling",
func = c(fun = 2, pkg = 1),
has_submodel = FALSE
)
)
})
test_that('adding a new fit', {
fit_vals <-
list(
interface = "formula",
protect = c("formula", "data"),
func = c(pkg = "foo", fun = "bar"),
defaults = list()
)
set_fit(
model = "sponge",
eng = "gum",
mode = "classification",
value = fit_vals
)
expect_error(
set_fit(
model = "sponge",
eng = "gum",
mode = "classification",
value = fit_vals
)
)
fit_env_data <- get_from_env("sponge_fit")
test_by_col(
fit_env_data[ 1:2],
tibble(engine = "gum", mode = "classification")
)
expect_equal(
fit_env_data$value[[1]],
fit_vals
)
expect_error(
set_fit(
model = "cactus",
eng = "gum",
mode = "classification",
value = fit_vals
)
)
expect_error(
set_fit(
model = "sponge",
eng = "nose",
mode = "classification",
value = fit_vals
)
)
expect_error(
set_fit(
model = "sponge",
eng = "gum",
mode = "frog",
value = fit_vals
)
)
for (i in 1:length(fit_vals)) {
expect_error(
set_fit(
model = "sponge",
eng = "gum",
mode = "classification",
value = fit_vals[-i]
)
)
}
fit_vals_0 <- fit_vals
fit_vals_0$interface <- "loaf"
expect_error(
set_fit(
model = "sponge",
eng = "gum",
mode = "classification",
value = fit_vals_0
)
)
fit_vals_1 <- fit_vals
fit_vals_1$defaults <- 2
expect_error(
set_fit(
model = "sponge",
eng = "gum",
mode = "classification",
value = fit_vals_1
)
)
fit_vals_2 <- fit_vals
fit_vals_2$func <- "foo:bar"
expect_error(
set_fit(
model = "sponge",
eng = "gum",
mode = "classification",
value = fit_vals_2
)
)
fit_vals_3 <- fit_vals
fit_vals_3$interface <- letters
expect_error(
set_fit(
model = "sponge",
eng = "gum",
mode = "classification",
value = fit_vals_3
)
)
test_by_col(
get_fit("sponge")[, 1:2],
tibble(engine = "gum", mode = "classification")
)
expect_equal(
get_fit("sponge")$value[[1]],
fit_vals
)
})
test_that('adding a new predict method', {
class_vals <-
list(
pre = I,
post = NULL,
func = c(fun = "predict"),
args = list(x = quote(2))
)
set_pred(
model = "sponge",
eng = "gum",
mode = "classification",
type = "class",
value = class_vals
)
pred_env_data <- get_from_env("sponge_predict")
test_by_col(
pred_env_data[ 1:3],
tibble(engine = "gum", mode = "classification", type = "class")
)
expect_equal(
pred_env_data$value[[1]],
class_vals
)
test_by_col(
get_pred_type("sponge", "class")[ 1:3],
tibble(engine = "gum", mode = "classification", type = "class")
)
expect_equal(
get_pred_type("sponge", "class")$value[[1]],
class_vals
)
expect_error(
set_pred(
model = "cactus",
eng = "gum",
mode = "classification",
type = "class",
value = class_vals
)
)
expect_error(
set_pred(
model = "sponge",
eng = "nose",
mode = "classification",
type = "class",
value = class_vals
)
)
expect_error(
set_pred(
model = "sponge",
eng = "gum",
mode = "classification",
type = "eggs",
value = class_vals
)
)
expect_error(
set_pred(
model = "sponge",
eng = "gum",
mode = "frog",
type = "class",
value = class_vals
)
)
for (i in 1:length(class_vals)) {
expect_error(
set_pred(
model = "sponge",
eng = "gum",
mode = "classification",
type = "class",
value = class_vals[-i]
)
)
}
class_vals_0 <- class_vals
class_vals_0$pre <- "I"
expect_error(
set_pred(
model = "sponge",
eng = "gum",
mode = "classification",
type = "class",
value = class_vals_0
)
)
class_vals_1 <- class_vals
class_vals_1$post <- "I"
expect_error(
set_pred(
model = "sponge",
eng = "gum",
mode = "classification",
type = "class",
value = class_vals_1
)
)
class_vals_2 <- class_vals
class_vals_2$func <- "foo:bar"
expect_error(
set_pred(
model = "sponge",
eng = "gum",
mode = "classification",
type = "class",
value = class_vals_2
)
)
})
test_that('showing model info', {
expect_output(
show_model_info("rand_forest"),
"Information for `rand_forest`"
)
expect_output(
show_model_info("rand_forest"),
"trees --> ntree"
)
expect_output(
show_model_info("rand_forest"),
"fit modules:"
)
expect_output(
show_model_info("rand_forest"),
"prediction modules:"
)
}) |
geo_pretty <- function(x) {
UseMethod("geo_pretty")
}
geo_pretty.default <- function(x) {
stop("no 'geo_pretty' method for ", class(x), call. = FALSE)
}
geo_pretty.geojson <- function(x) {
jsonlite::prettify(x)
} |
context("as.RollingLDA and Getter")
data("economy_texts")
data("economy_dates")
roll_lda = RollingLDA(economy_texts, economy_dates, "quarter", "6 month",
init = 20, K = 5, type = "lda")
test_that("various messages", {
a = 12
class(a) = "RollingLDA"
expect_false(is.RollingLDA(a))
expect_message(is.RollingLDA(a, verbose = TRUE), "object is not a list")
tmp = roll_lda
names(tmp) = ""
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "Must have names")
tmp = roll_lda
tmp$id = 2L
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE),
"May only contain the following types: \\{character,LDA,list,Date,character,data.table,list\\},")
tmp = roll_lda
names(tmp)[names(tmp) == "id"] = "ID"
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE),
"set \\{'id','lda','docs','dates','vocab','chunks','param'\\}")
tmp = roll_lda
tmp$lda = NULL
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE),
"\\{'id','lda','docs','dates','vocab','chunks','param'\\}")
tmp = roll_lda
tmp$id = c("id1", "id2")
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "not a character of length 1")
tmp = roll_lda
class(tmp$lda) = "not LDA"
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "not an \"LDA\" object")
tmp = roll_lda
tmp$docs = "not list"
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "Must be of type 'list', not 'character'")
tmp = roll_lda
names(tmp$docs)[2] = names(tmp$docs)[1]
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "not same names as \"docs\"")
tmp = roll_lda
tmp$docs[[2]] = "not matrix"
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE),
"May only contain the following types: \\{matrix\\}")
tmp = roll_lda
tmp$docs[[2]] = matrix(0, ncol = 1, nrow = 5)
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE),
"not all elements have two rows")
tmp = roll_lda
tmp$docs[[2]] = matrix(0, ncol = 1, nrow = 2)
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE),
"not all values in the second row equal 1")
tmp = roll_lda
tmp$dates[1] = NA_Date_
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "Contains missing values")
tmp = roll_lda
tmp$dates = as.character(tmp$dates)
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "Must be of class 'Date'")
tmp = roll_lda
names(tmp$dates)[2] = names(tmp$dates)[1]
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "Must have unique names")
tmp = roll_lda
tmp$docs = append(tmp$docs, list(matrix(c(1,1), nrow = 2)))
expect_true(is.RollingLDA(tmp))
tmp = roll_lda
tmp$dates = append(tmp$dates, Sys.Date())
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "not same names as \"docs\"")
tmp = roll_lda
tmp$vocab = c(getVocab(tmp), getVocab(tmp)[1])
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "Contains duplicated values")
tmp = roll_lda
tmp$vocab = c(getVocab(tmp), NA_character_)
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "Contains missing values")
tmp = roll_lda
tmp$vocab = list(12)
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "Must be of type 'character'")
tmp = roll_lda
tmp$chunks = list()
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "not a data.table with standard parameters")
tmp = roll_lda
tmp$chunks = getChunks(tmp)[, -"chunk.id"]
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "not a data.table with standard parameters")
tmp = roll_lda
tmp$chunks$chunk.id[2] = tmp$chunks$chunk.id[1]
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "duplicated \"chunk.id\"")
tmp = roll_lda
tmp$chunks$chunk.id[1] = 0
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "\"chunk.id\" is not an integer")
tmp = roll_lda
tmp$chunks$chunk.id[1] = NA_integer_
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "NA\\(s\\) in \"chunk.id\"")
tmp = roll_lda
tmp$chunks$n[1] = 0
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "\"n\" is not an integer")
tmp = roll_lda
tmp$chunks$n[1] = NA_integer_
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "NA\\(s\\) in \"n\"")
tmp = roll_lda
tmp$chunks$n.discarded[1] = 0
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "\"n.discarded\" is not an integer")
tmp = roll_lda
tmp$chunks$n.memory[1] = 0
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "\"n.memory\" is not an integer")
tmp = roll_lda
tmp$chunks$n.vocab[1] = 0
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "\"n.vocab\" is not an integer")
tmp = roll_lda
tmp$chunks$n.vocab[1] = NA_integer_
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "NA\\(s\\) in \"n.vocab\"")
tmp = roll_lda
tmp$vocab = c(getVocab(roll_lda), "ABC")
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE),
"max of \"n.vocab\" does not match number of vocabularies")
tmp = roll_lda
tmp$chunks$n.vocab = rev(tmp$chunks$n.vocab)
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE),
"\"n.vocab\" is not monotonously increasing")
tmp = roll_lda
tmp$chunks$start.date = as.character(tmp$chunks$start.date)
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "\"start.date\" is not a Date object")
tmp = roll_lda
tmp$chunks$start.date[1] = NA_Date_
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "NA\\(s\\) in \"start.date\"")
tmp = roll_lda
tmp$chunks$start.date[1] = as.character(Sys.Date())
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE),
"minimum of \"start.date\" is larger than minimum of text's dates")
tmp = roll_lda
tmp$chunks$end.date = as.character(tmp$chunks$end.date)
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "\"end.date\" is not a Date object")
tmp = roll_lda
tmp$chunks$end.date[1] = NA_Date_
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "NA\\(s\\) in \"end.date\"")
tmp = roll_lda
tmp$chunks$end.date[nrow(getChunks(tmp))] = tmp$chunks$end.date[nrow(getChunks(tmp))]-1
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE),
"maximum of \"end.date\" is smaller than maximum of text's dates")
tmp = roll_lda
tmp$chunks$memory = as.character(tmp$chunks$memory)
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "\"memory\" is not a Date object")
tmp = roll_lda
tmp$param = getParam(roll_lda)[-1]
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE),
"\\{'vocab.abs','vocab.rel','vocab.fallback','doc.abs'\\}")
tmp = roll_lda
tmp$param$vocab.abs = -1
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "\"vocab.abs\" is smaller than 0")
tmp = roll_lda
tmp$param$vocab.rel = -1
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "\"vocab.rel\" is smaller than 0")
tmp = roll_lda
tmp$param$vocab.fallback = -1
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "\"vocab.fallback\" is smaller than 0")
tmp = roll_lda
tmp$param$doc.abs = -1
expect_false(is.RollingLDA(tmp))
expect_message(is.RollingLDA(tmp, verbose = TRUE), "\"doc.abs\" is smaller than 0")
}) |
library(devtools)
library(dplyr)
library(sf)
library(tigris)
stLouis <- tracts(state = "MO", county = 510)
stLouis <- st_as_sf(stLouis)
stLouis <- select(stLouis, STATEFP, COUNTYFP, TRACTCE, GEOID, NAME, NAMELSAD)
use_data(stLouis, overwrite = TRUE) |
ProjSepD <- function(design) {
.C(ProjSep, PACKAGE="LatticeDesign",
as.double(design), as.integer(dim(design)[2]), as.integer(dim(design)[1]), as.double(rep(0,dim(design)[2])) )[[4]]
}
DPMPD <- function(p=2, n, rotation="magic", w=100){
if(!p>=2|!p<=8|!p==round(p)) stop("p must be an integer greater than one and no greater than eight.")
if(!n>=2|!n==round(n)) stop("n must be an integer greater than one.")
if(!w>=1|!w==round(w)|!w<=10000) stop("w must be a positive integer greater no greater than 10000.")
detG <- 2
if(p==2) detG <- 2*sqrt(3)
if(p==6) detG <- sqrt(3)
if(p==7) detG <- sqrt(2)
if(p==8) detG <- 1
r <- (n*detG)^(1/p)/2*sqrt(p)+1
ss <- floor( r )
FE <- matrix(0,ss+1,2)
FE[,2] = 0:ss
FE[,1] = FE[,2]^2
for(j in 2:p) {
nFE <- matrix(0,0,j+1)
for(k in 0:ss) { oFE = cbind(FE,rep(k,dim(FE)[1])); oFE[,1] = oFE[,1]+k^2; nFE <- rbind(nFE,oFE); }
FE <- nFE[nFE[,1]<= floor( r^2 ), ]
}
FE[,1]=0; for(j in 2:(p+1)) FE[,1]=FE[,1]+FE[,j]; FE = FE[ floor(FE[,1]/2)*2==FE[,1] ,];
if(p>=6) {
FE1 = FE[ FE[,2]>0, ]
FE1[,2] = -FE1[,2]
FE2 = FE[ FE[,2]==1, ]
FE2[,2] = -FE2[,2]
FE3 = rbind(FE,FE2)
FE4 = FE3 +0.5
FE5 = FE +0.5
FE5[,2] = -FE5[,2]-1
FE <- rbind(FE,FE1,FE4,FE5)
}
if(p<6) {
nFE = FE[FE[,2]>0,]
nFE[,2] <- -nFE[,2]
FE <- rbind(FE,nFE)
}
if(p==2) { FE[,3] <- FE[,3]*sqrt(3); }
if(p==6) { FE[,7] <- FE[,7]*sqrt(3); }
if(p==7) { FE[,8] <- FE[,8]*sqrt(2); }
FE[,1] <- 0;
for(j in 2:(p+1)) FE[,1] <- FE[,1] +FE[,j]^2
FE <- FE[FE[,1]<=r^2,]
FE <- FE[,-1]
for(j in 2:p) {
nFE = FE[FE[,j]>0,]
nFE[,j] <- -nFE[,j]
nFE[,1] <- -nFE[,1]
FE <- rbind(FE,nFE)
}
mv = 25
if(w>100) mv = 55
vlist <- matrix(0,0,3)
for(v1 in 1:mv) for(v2 in v1:mv) {
vlist = rbind(vlist,c(v1,v2,v1^2+v2^2))
}
vvlist <- matrix(0,0,6)
for(i in 1:dim(vlist)[1]) for(j in 1:dim(vlist)[1]) {
ratio = vlist[j,3]/vlist[i,3]
if(ratio>1) if(floor(sqrt(ratio))!=sqrt(ratio)) if(floor(ratio)*vlist[i,3]==vlist[j,3]) vvlist = rbind(vvlist,c(vlist[i,1:2],vlist[j,1:2],ratio,0))
}
vvlist[,6] = abs( (vvlist[,3]-vvlist[,1]*sqrt(vvlist[,5])) / sqrt( (vvlist[,3]-vvlist[,1]*sqrt(vvlist[,5]))^2 + (vvlist[,4]-vvlist[,2]*sqrt(vvlist[,5]))^2 ) )
j=2
while(j<=dim(vvlist)[1]) {
for(k in 1:j) {
if(k<j) if(abs(vvlist[j,6]-vvlist[k,6])<10^-10) { vvlist = vvlist[-j,]; break; }
}
if(k==j) j=j+1
}
for(i in 1:dim(vvlist)[1]) vvlist[i,6] = max(vvlist[i,1:4])
vvlist1 = vvlist[vvlist[,5]==2,]
vvlist2 = vvlist[vvlist[,5]==5,]
vvlist3 = vvlist[vvlist[,5]==13,]
if(w<=100) {
vvlist1 = vvlist1[ order(vvlist1[,6])[1:10], ]
vvlist2 = vvlist2[ order(vvlist2[,6])[1:10], ]
vvlist3 = vvlist3[ order(vvlist3[,6])[1:10], ]
}
set.seed(1)
ress = matrix(0,w,p+1)
l <- (n*detG)^(1/p)
maxscore <- -10^10
for(ll in 1:w) {
set.seed(ll)
if(rotation!="magic"|p==5|p==7) {
CPair <- matrix(0,p*(p-1)/2,2)
row <- 1
for(i in 1:(p-1)) for(j in (i+1):p) { CPair[row,1] <- i; CPair[row,2] <- j; row <- row+1; }
R <- diag(p)
for(a in 1:((p*(p-1)/2))) {
alpha <- runif(1,0,2*pi)
thepair <- CPair[a,]
W <- diag(p)
W[thepair[1],thepair[1]] <- cos(alpha); W[thepair[2],thepair[2]] <- cos(alpha);
W[thepair[1],thepair[2]] <- sin(alpha); W[thepair[2],thepair[1]] <- -sin(alpha);
R <- R%*%W
}
}
if(rotation=="magic"&p==2) {
q1 <- 3
bb1 <- 20; bb2 <- 4;
if(w>100) { bb1 <- floor(w^(2/3)); bb2 <- floor(w^(1/3)); }
u1 = ceiling(ll/bb1)
u2 = ceiling( ( ll - (u1-1)*bb1 ) / bb2 )
u3 = ll - (u1-1)*bb1 - (u2-1)*bb2 -floor(bb2/2)
if(u3^2==3*u1^2+u2^2) u3 = bb2 -floor(bb2/2)+1
R = rbind( c(u1*sqrt(q1)+u3,-u2), c(u2,u1*sqrt(q1)+u3) )
for(j in 1:2) R[,j] = R[,j]/sqrt(sum(R[,j]^2))
R1 = rbind( c(sqrt(3)+1,sqrt(3)-1), c(-sqrt(3)+1,sqrt(3)+1) ) /2/sqrt(2)
R = R1 %*% R
}
if(rotation=="magic"&p==3) {
qlist = 2:(w+10)
for(k in 2:20) qlist = qlist[ floor(qlist/k^3)*k^3!=qlist ]
bb1 <- 10; bb2 <- 55;
if(w>100) bb2 <- floor((w+10)/2)
q1 = qlist[ll];
if(ll>bb1) q1 = qlist[ll-bb1]/8
if(ll>bb2) q1 = qlist[ll-bb2]/27
R3=matrix(0,3,3)
R3[1,1]=R3[3,2]=R3[2,3] = 1-q1
R3[2,1]=R3[1,2]=R3[3,3] = q1-q1^(1/3)
R3[3,1]=R3[2,2]=R3[1,3] = (1-q1)*(q1^(1/3)+q1^(2/3))
R <- R3 / sqrt(sum(R3[,3]*R3[,3]))
}
if(rotation=="magic"&p==4) {
bb1 <- 10;
if(w>100) bb1 <- floor(sqrt(w))
if(w>bb1*76) bb1 <- ceiling(w/76)
rot1 = vvlist1[ceiling(ll/bb1),]
GRR1 = rbind( rot1[c(3,1)], rot1[c(4,2)] )
q1 = rot1[5]
R1 <- GRR1 %*% rbind( c(1,1), c(-sqrt(q1),sqrt(q1)) )
for(j in 1:2) R1[,j] = R1[,j]/sqrt(sum(R1[,j]^2))
rot2 = vvlist2[ll-ceiling(ll/bb1)*bb1+bb1,]
GRR2 = rbind( rot2[c(3,1)], rot2[c(4,2)] )
q2 = rot2[5]
R2 <- GRR2 %*% rbind( c(1,1), c(-sqrt(q2),sqrt(q2)) )
for(j in 1:2) R2[,j] = R2[,j]/sqrt(sum(R2[,j]^2))
R <- rbind( cbind(R2[1,1]*R1,R2[1,2]*R1), cbind(R2[2,1]*R1,R2[2,2]*R1) )
}
if(rotation=="magic"&p==6) {
bb1 <- 50; bb2 <- 25;
if(w>100) { bb2 <- floor((w/5)^(1/3)*5); bb1 <- floor((w/5)^(2/3)*5); }
q1 <- 3
u1 = ceiling(ll/bb1)
u2 = ceiling( ( ll - (ceiling(ll/bb1)-1)*bb1 ) / bb2 )
u3 = ceiling( ( ll - (ceiling(ll/bb2)-1)*bb2 ) / 5 ) - ceiling(bb2/10)
if(u3==0) u3 = ceiling(bb2/5) - ceiling(bb2/10) + 1
if(w<=100) if(u1==2&u2==2&abs(u3)==2) u1 = 3
R2 = rbind( c(u1*sqrt(q1)+u3,-u2), c(u2,u1*sqrt(q1)+u3) )
for(j in 1:2) R2[,j] = R2[,j]/sqrt(sum(R2[,j]^2))
qlist = 2:100
for(k in 2:4) qlist = qlist[ floor(qlist/k^3)*k^3!=qlist ]
q1 = qlist[ ll-(ceiling(ll/5)-1)*5 ];
R3=matrix(0,3,3)
R3[1,1]=R3[3,2]=R3[2,3] = 1-q1
R3[2,1]=R3[1,2]=R3[3,3] = q1-q1^(1/3)
R3[3,1]=R3[2,2]=R3[1,3] = (1-q1)*(q1^(1/3)+q1^(2/3))
R3 <- R3 / sqrt(sum(R3[,3]*R3[,3]))
R <- rbind( cbind(R3[1,1]*R2,R3[1,2]*R2,R3[1,3]*R2), cbind(R3[2,1]*R2,R3[2,2]*R2,R3[2,3]*R2), cbind(R3[3,1]*R2,R3[3,2]*R2,R3[3,3]*R2) )
}
if(rotation=="magic"&p==8) {
bb2 <- floor(w^(1/3)); bb1 <- floor(w^(2/3));
rot1 = vvlist1[ ceiling(ll/bb1) ,]
GRR1 = rbind( rot1[c(3,1)], rot1[c(4,2)] )
q1 = rot1[5]
R1 <- GRR1 %*% rbind( c(1,1), c(-sqrt(q1),sqrt(q1)) )
for(j in 1:2) R1[,j] = R1[,j]/sqrt(sum(R1[,j]^2))
rot2 = vvlist2[ ceiling( (ll-ceiling(ll/bb1)*bb1+bb1) / bb2 ) ,]
GRR2 = rbind( rot2[c(3,1)], rot2[c(4,2)] )
q2 = rot2[5]
R2 <- GRR2 %*% rbind( c(1,1), c(-sqrt(q2),sqrt(q2)) )
for(j in 1:2) R2[,j] = R2[,j]/sqrt(sum(R2[,j]^2))
rot3 = vvlist3[ ll-ceiling(ll/bb2)*bb2+bb2 ,]
GRR3 = rbind( rot3[c(3,1)], rot3[c(4,2)] )
q3 = rot3[5]
R3 <- GRR3 %*% rbind( c(1,1), c(-sqrt(q3),sqrt(q3)) )
for(j in 1:2) R3[,j] = R3[,j]/sqrt(sum(R3[,j]^2))
R <- rbind( cbind(R2[1,1]*R1,R2[1,2]*R1), cbind(R2[2,1]*R1,R2[2,2]*R1) )
R <- rbind( cbind(R3[1,1]*R,R3[1,2]*R), cbind(R3[2,1]*R,R3[2,2]*R) )
}
E <- FE %*% R
isE <- FALSE
isB <- FALSE
isL <- FALSE
epsilonV <- matrix(0,3,p)
for(i in 1:100) {
while(1) {
delta <- runif(p,-1,1)
if( sum( sort(abs(delta))[(p-1):p] ) > 1) next
if(p==2) delta[p] <- delta[p]*sqrt(3)
if(p==6) delta[p] <- delta[p]*sqrt(3)
if(p==7) delta[p] <- delta[p]*sqrt(2)
if( sum( (abs(delta)+l/2)^2 ) <= r^2) break
}
epsilon <- delta %*% R
design <- E
for(j in 1:p) { if(length(design)<=p) break; design <- design[ abs(design[,j]-epsilon[j])<l/2 ,]; }
if(length(design)<=p) next;
if(dim(design)[1]==n) { isE <- TRUE; epsilonV[1,] <- epsilon; break; }
if(isL==FALSE & dim(design)[1]<n) { isL <- TRUE; epsilonV[2,] <- epsilon; }
if(isB==FALSE & dim(design)[1]>n) { isB <- TRUE; epsilonV[3,] <- epsilon; }
if(isL==TRUE & isB==TRUE) break;
}
if(isE==FALSE) for(j in 1:(p-1)) {
epsilon <- c(epsilonV[2,1:j],epsilonV[3,(j+1):p])
design <- E
for(j in 1:p) { if(length(design)<=p) break; design <- design[ abs(design[,j]-epsilon[j])<l/2 ,]; }
if(length(design)<=p) next;
if(dim(design)[1]==n) { isE <- TRUE; epsilonV[1,] <- epsilon; break; }
if(dim(design)[1]<n) { epsilonV[2,] <- epsilon; break; }
if(dim(design)[1]>n) { epsilonV[3,] <- epsilon; }
}
if(isE==FALSE) for(k in 1:100) {
epsilon <- (epsilonV[2,]+epsilonV[3,])/2
design <- E
for(j in 1:p) { if(length(design)<=p) break; design <- design[ abs(design[,j]-epsilon[j])<l/2 ,]; }
if(length(design)<=p) next;
if(dim(design)[1]==n) { isE <- TRUE; epsilonV[1,] <- epsilon; break; }
if(dim(design)[1]<n) { epsilonV[2,] <- epsilon; }
if(dim(design)[1]>n) { epsilonV[3,] <- epsilon; }
}
for(j in 1:p) design[,j] <- (design[,j]-epsilon[j]) / l + .5
ress[ll,1:p] = ProjSepD(design)
ress[ll,p+1] = sum( log(ress[ll,1:p]*n^(1/(1:p))) * c(1/2,2:p) )
if(ll==1|ress[ll,p+1]>maxscore) {
maxscore <- ress[ll,p+1]
designBest <- design
}
}
for(j in 1:p) designBest[,j] = designBest[,j]-(min(designBest[,j])+max(designBest[,j])-1)/2
return(list(Design=designBest,ProjectiveSeparationDistance=sqrt(ProjSepD(designBest))))
} |
art1 <- function(x, ...) UseMethod("art1")
art1.default <- function(x, dimX, dimY, f2Units=nrow(x), maxit=100,
initFunc="ART1_Weights", initFuncParams=c(1.0, 1.0),
learnFunc="ART1", learnFuncParams=c(0.9, 0.0, 0.0),
updateFunc="ART1_Stable", updateFuncParams=c(0.0),
shufflePatterns=TRUE, ...) {
x <- as.matrix(x)
nInputs <- dim(x)[2L]
snns <- rsnnsObjectFactory(subclass=c("art1"), nInputs=nInputs, maxit=maxit,
initFunc=initFunc, initFuncParams=initFuncParams,
learnFunc=learnFunc, learnFuncParams=learnFuncParams,
updateFunc=updateFunc,
updateFuncParams=updateFuncParams,
shufflePatterns=shufflePatterns, computeIterativeError=FALSE)
snns$archParams <- list(f2Units=f2Units, dimX=dimX, dimY=dimY)
snns$snnsObject$art1_createNet(dimX*dimY,dimX,f2Units,dimX)
snns <- train(snns, inputsTrain=x)
snns
} |
library(testthat)
library(goxygen)
context("goxygen")
skip_if_not(check_pandoc(error=FALSE))
test_that("extract documentation from modular dummy model", {
docfolder <- paste0(tempdir(),"/doc_modular")
out <- try(goxygen(path = system.file("dummymodel",package="gms"),
docfolder = docfolder, includeCore = TRUE, cff = "HOWTOCITE.cff"))
expect_null(out)
expect_true(file.exists(paste0(docfolder,"/html/index.htm")))
expect_true(file.exists(paste0(docfolder,"/html/core.htm")))
expect_true(file.exists(paste0(docfolder,"/html/01_fancymodule.htm")))
expect_true(file.exists(paste0(docfolder,"/html/02_crazymodule.htm")))
expect_true(file.exists(paste0(docfolder,"/documentation.tex")))
})
test_that("extract HTML documentation from modular dummy model with classic style", {
docfolder <- paste0(tempdir(),"/doc_modular_classic")
out <- try(goxygen(path = system.file("dummymodel",package="gms"),
htmlStyle = "classic", output="html",
docfolder = docfolder, includeCore = TRUE, cff = "HOWTOCITE.cff"))
expect_null(out)
expect_true(file.exists(paste0(docfolder,"/html/index.htm")))
expect_true(file.exists(paste0(docfolder,"/html/core.htm")))
expect_true(file.exists(paste0(docfolder,"/html/01_fancymodule.htm")))
expect_true(file.exists(paste0(docfolder,"/html/02_crazymodule.htm")))
})
test_that("cache and unknown output", {
docfolder <- paste0(tempdir(),"/doc_modular")
expect_warning(out <- try(goxygen(path = system.file("dummymodel",package="gms"),
docfolder = docfolder, includeCore = TRUE, cache = TRUE, output="bla")))
expect_null(out)
})
test_that("extract documentation from simple dummy model", {
docfolder <- paste0(tempdir(),"/doc_simple")
out <- try(goxygen(path = system.file("dummymodel",package="gms"),
docfolder = docfolder, modularCode = FALSE,
cff = "HOWTOCITE.cff"))
expect_null(out)
expect_true(file.exists(paste0(docfolder,"/html/index.htm")))
expect_true(file.exists(paste0(docfolder,"/html/modules_01_fancymodule_default_calculations.htm")))
expect_true(file.exists(paste0(docfolder,"/html/modules_02_crazymodule_module.htm")))
expect_true(file.exists(paste0(docfolder,"/documentation.tex")))
}) |
compute_F_test_with_limma <-
function( x,
p.adj.threshold = 0.05,
print.table = FALSE ) {
if ( any( x$"parameters"$"contrasts" != "contr.sum" ) ) {
stop( "Call compute_models_with_limma() first with F.test = TRUE." )
return( NULL )
} else {
idx.target <-
grep(
x = colnames( x$"model"$"coefficients" ),
pattern = paste0("^", x$"parameters"$"independent.variables"[ 1 ] )
)
names.target <- colnames( x$"model"$"coefficients" )[ idx.target ]
y <-
limma::topTable(
fit = x$"model",
coef = names.target,
confint = TRUE,
number = Inf,
p.value = 1,
adjust.method = "BH"
)
if ( print.table ) {
tmp <- which( y$"adj.P.Val" < p.adj.threshold )
if ( length( tmp ) > 0 ) {
y.printed <- y[ tmp, , drop = FALSE ]
y.printed <-
signif(
x = y.printed,
digits = 3
)
y.printed$"Name" <- rownames( y.printed )
y.printed$"Name" <-
stringr::str_sub(
string = y.printed$"Name",
start = 1,
end = 25
)
y.printed <-
y.printed[ , c( "Name", "AveExpr", "F", "P.Value", "adj.P.Val" ) ]
y.printed <-
knitr::kable(
x = y.printed,
caption =
paste(
"F-test for",
paste(
names.target,
collapse = ", "
)
),
row.names = FALSE )
print( y.printed )
} else {
message(
paste(
"No significant F-tests at p.adj <",
p.adj.threshold
)
)
}
}
y.out <- x
y.out$"result.F.test" <- y
y.out$"parameters"$"p.adj.threshold" <- p.adj.threshold
return( y.out )
}
} |
agree_nest <- function(x,
y,
id,
data,
delta,
agree.level = .95,
conf.level = .95){
agreeq = qnorm(1 - (1 - agree.level) / 2)
agree.l = 1 - (1 - agree.level) / 2
agree.u = (1 - agree.level) / 2
confq = qnorm(1 - (1 - conf.level) / 2)
alpha.l = 1 - (1 - conf.level) / 2
alpha.u = (1 - conf.level) / 2
df = data %>%
select(all_of(id),all_of(x),all_of(y)) %>%
rename(id = all_of(id),
x = all_of(x),
y = all_of(y)) %>%
select(id,x,y) %>%
drop_na()
df_long = df %>%
pivot_longer(!id,
names_to = "method",
values_to = "measure")
ccc_nest = cccUst(dataset = df_long,
ry = "measure",
rmet = "method",
cl = conf.level)
ccc.xy = data.frame(est.ccc = ccc_nest[1],
lower.ci = ccc_nest[2],
upper.ci = ccc_nest[3],
SE = ccc_nest[4])
df2 = df %>%
group_by(id) %>%
summarize(m = n(),
x_bar = mean(x, na.rm=TRUE),
x_var = var(x, na.rm=TRUE),
y_bar = mean(y, na.rm=TRUE),
y_var = var(y, na.rm=TRUE),
d = mean(x-y),
d_var = var(x-y),
.groups = "drop") %>%
mutate(both_avg = (x_bar+y_bar)/2)
d_bar = mean(df2$d)
d_var = var(df2$d)
sdw2 = sum((df2$m-1)/(nrow(df)-nrow(df2))*df2$d_var)
mh = nrow(df2)/sum(1/df2$m)
d_lo = d_bar - confq*sqrt(d_var)/sqrt(nrow(df2))
d_hi = d_bar + confq*sqrt(d_var)/sqrt(nrow(df2))
var_tot = d_var + (1-1/mh) * sdw2
loa_l = d_bar - agreeq*sqrt(var_tot)
loa_u = d_bar + agreeq*sqrt(var_tot)
move.l.1 = (d_var*(1-(nrow(df2)-1)/(qchisq(alpha.l,nrow(df2)-1))))^2
move.l.2 = ((1-1/mh)*sdw2*(1-(nrow(df)-nrow(df2))/(qchisq(alpha.l,nrow(df)-nrow(df2)))))^2
move.l = var_tot - sqrt(move.l.1+move.l.2)
move.u.1 = (d_var*((nrow(df2)-1)/(qchisq(alpha.u,nrow(df2)-1))-1))^2
move.u.2 = ((1-1/mh)*sdw2*((nrow(df)-nrow(df2))/(qchisq(alpha.u,nrow(df)-nrow(df2)))-1))^2
move.u = var_tot + sqrt(move.u.1+move.u.2)
LME = sqrt(confq^2*(d_var/nrow(df2))+agreeq^2*(sqrt(move.u)-sqrt(var_tot))^2)
RME = sqrt(confq^2*(d_var/nrow(df2))+agreeq^2*(sqrt(var_tot)-sqrt(move.l))^2)
loa_l.l = loa_l - LME
loa_l.u = loa_l + RME
loa_u.l = loa_u - RME
loa_u.u = loa_u + LME
df_loa = data.frame(
estimate = c(d_bar, loa_l, loa_u),
lower.ci = c(d_lo, loa_l.l, loa_u.l),
upper.ci = c(d_hi, loa_l.u, loa_u.u),
row.names = c("Difference","Lower LoA","Upper LoA")
)
if (!missing(delta)) {
rej <- (-delta < loa_l.l) * (loa_u.l < delta)
rej_text = "don't reject h0"
if (rej == 1) {
rej_text = "reject h0"
}} else {
rej_text = "No Hypothesis Test"
}
z <- lm(y_bar ~ x_bar, df2)
the_int <- summary(z)$coefficients[1,1]
the_slope <- summary(z)$coefficients[2,1]
tmp.lm <- data.frame(the_int, the_slope)
scalemin = min(c(min(df$x),min(df$y)))
scalemax = max(c(max(df$x),max(df$y)))
df = df %>%
mutate(id = as.factor(id))
identity.plot = ggplot(df,
aes(x = x, y = y,color=id)) +
geom_point() +
geom_abline(intercept = 0, slope = 1) +
geom_abline(
data = tmp.lm,
aes(intercept = the_int, slope = the_slope),
linetype = "dashed",
color = "red"
) +
xlab("Method: x") +
xlim(scalemin,scalemax) +
ylim(scalemin,scalemax) +
ylab("Method: y") +
coord_fixed(ratio = 1 / 1) +
theme_bw() +
scale_color_viridis_d()
df = df %>%
mutate(d = x-y,
avg_both = (x+y)/2)
bland_alt.plot = ggplot(df,
aes(x = avg_both, y = d)) +
geom_point(na.rm = TRUE) +
annotate("rect",
xmin = -Inf, xmax = Inf,
ymin = df_loa$lower.ci[2],
ymax = df_loa$upper.ci[2],
alpha = .5,
fill = "
annotate("rect",
xmin = -Inf, xmax = Inf,
ymin = df_loa$lower.ci[3],
ymax = df_loa$upper.ci[3],
alpha = .5,
fill = "
geom_hline(aes(yintercept = d_bar),
linetype = 1) +
annotate("rect",
xmin = -Inf, xmax = Inf,
ymin = df_loa$lower.ci[1],
ymax = df_loa$upper.ci[1],
alpha = .5,
fill = "gray") +
xlab("Average of Method x and Method y") +
ylab("Average Difference between Methods") +
theme_bw() +
theme(legend.position = "none")
structure(list(loa = df_loa,
h0_test = rej_text,
bland_alt.plot = bland_alt.plot,
identity.plot = identity.plot,
conf.level = conf.level,
agree.level = agree.level,
ccc.xy = ccc.xy,
class = "nested"),
class = "simple_agree")
} |
rwyxz <- function(mw,mx,my,mz,sw,sx,sy,sz,rwx=0,rwy=0,rwz=0,rxy=0,rxz=0,ryz=0){
out <- (
rwx*(sw/mw)*(sx/mx) - rwz*(sw/mw)*(sz/mz) -
rxy*(sx/mx)*(sy/my) + ryz*(sy/my)*(sz/mz)
)/(
sqrt((sw/mw)^2+(sy/my)^2-2*rwy*(sw/mw)*(sy/my)) *
sqrt((sx/mx)^2+(sz/mz)^2-2*rxz*(sx/mx)*(sz/mz))
)
out
}
ryxy <- function(mx,my,sx,sy,rxy=0){
rwyxz(mw=my,mx=mx,my=1,mz=my,sw=sy,sx=sx,sy=0,sz=sy,
rwx=rxy,rwy=0,rwz=1,rxy=0,rxz=rxy,ryz=0)
}
rxzyz <- function(mx,my,mz,sx,sy,sz,rxy=0,rxz=0,ryz=0){
rwyxz(mw=my,mx=mx,my=my,mz=mz,sw=sy,sx=sx,sy=sz,sz=sz,
rwx=rxy,rwy=ryz,rwz=ryz,rxy=rxz,rxz=rxz,ryz=1)
} |
test_that("format_glimpse() output test", {
expect_snapshot({
"
format_glimpse(1)
format_glimpse(1:3)
format_glimpse(NA)
format_glimpse(TRUE)
format_glimpse(logical())
"
format_glimpse("1")
format_glimpse(letters)
format_glimpse(NA_character_)
format_glimpse(character())
"
format_glimpse(factor(c("1", "a")))
format_glimpse(factor(c("foo", '"bar"')))
format_glimpse(factor())
"Add quotes around factor levels with comma"
"so they don't appear as if they were two observations (
format_glimpse(factor(c("foo, bar", "foo", '"bar"')))
"
format_glimpse(list(1:3))
format_glimpse(as.list(1:3))
format_glimpse(list(1:3, 4))
format_glimpse(list(1:3, 4:5))
format_glimpse(list())
format_glimpse(list(list()))
format_glimpse(list(character()))
format_glimpse(list(1:3, list(4)))
format_glimpse(list(1:3, list(4:5)))
})
})
test_that("glimpse(width = Inf) raises legible error", {
expect_error(
glimpse(mtcars, width = Inf)
)
})
test_that("glimpse calls tbl_sum() (
skip_if(!l10n_info()$`UTF-8`)
local_override_tbl_sum()
trees2 <- as_override_tbl_sum(trees)
expect_output(
glimpse(trees2),
"Overridden: tbl_sum",
fixed = TRUE
)
})
test_that("output test for glimpse()", {
local_unknown_rows()
expect_snapshot({
glimpse(as_tbl(mtcars), width = 70L)
glimpse(as_tbl(trees), width = 70L)
"No columns"
glimpse(as_tbl(trees[integer()]), width = 70L)
"Non-syntactic names"
df <- tibble::tibble(!!!set_names(c(5, 3), c("mean(x)", "var(x)")))
glimpse(df, width = 28)
glimpse(as_tbl(df_all), width = 70L)
"options(tibble.width = 50)"
withr::with_options(
list(tibble.width = 50),
glimpse(as_tbl(df_all))
)
"options(tibble.width = 35)"
withr::with_options(
list(tibble.width = 35),
glimpse(as_tbl(df_all))
)
"non-tibble"
glimpse(5)
trees2 <- as_unknown_rows(trees)
glimpse(trees2, width = 70L)
cyl <- unique(mtcars$cyl)
data <- unname(split(mtcars, mtcars$cyl))
nested_mtcars_df <- tibble::tibble(cyl, data)
glimpse(nested_mtcars_df, width = 70L)
data <- map(data, as_tbl)
nested_mtcars_tbl <- tibble::tibble(cyl, data)
glimpse(nested_mtcars_tbl, width = 70L)
})
}) |
double.exp <- function(x) {
0.5 * exp(-abs(x))
} |
ls_fun_args <- function (x) {
if (is.function(x)) {
c(ls_fun_args(formals(x)), ls_fun_args(body(x)))
}
else if (is.call(x)) {
args <- as.list(x[-1])
c(list(args), unlist(lapply(x[-1], ls_fun_args), use.names = FALSE, recursive = FALSE))
}
} |
execute_field <- function(object_type, object_value, field_type, fields, ..., oh) {
field <- fields[[1]]
if (identical(format(field$name), "__typename")) {
completed_value <- resolve__typename(object_type, object_value, oh = oh)
return(completed_value)
}
argument_values <- coerce_argument_values(object_type, field, ..., oh = oh)
resolved_value <- resolve_field_value(
object_type,
object_value,
field_obj = field,
argument_values,
oh = oh
)
completed_value <- complete_value(field_type, fields, resolved_value, oh = oh)
completed_value
}
resolve__typename <- function(object_type, object_value, ..., oh) {
if (oh$schema$is_object(object_type)) {
ret <- format(object_type)
return(ret)
}
obj <- ifnull(oh$schema$get_interface(object_type), oh$schema$get_union(object_type))
ret <- obj$.resolve_type(object_value, oh$schema)
ret
}
coerce_argument_values <- function(object_type, field, ..., oh) {
coerced_values <- list()
argument_values <- field$arguments
if (is.null(argument_values)) return(coerced_values)
if (length(argument_values) == 0) return(coerced_values)
field_parent_obj <- oh$schema$get_object(object_type)
matching_field_obj <- field_parent_obj$.get_field(field)
argument_definitions <- matching_field_obj$arguments
for (argument_definition in argument_definitions) {
argument_name <- argument_definition$.get_name()
argument_type <- argument_definition$type
type_obj <- oh$schema$get_type(argument_type)
default_value <- argument_definition$defaultValue
matching_arg <- field$.get_matching_argument(argument_definition)
value <- matching_arg$value
if (is.null(value) || inherits(value, "NullValue")) {
if (!is.null(default_value)) {
value <- default_value
} else if (inherits(argument_type, "NonNullType")) {
oh$error_list$add(
"6.4.1",
"Received null value for non nullable type argument definition",
loc = value$loc
)
next
} else {
next
}
}
if (inherits(value, "Variable")) {
if (oh$has_variable_value(value)) {
variable_value <- oh$get_variable_value(value)
coerced_value <- type_obj$.resolve(variable_value, oh$schema)
if (!is.null(variable_value) && is.null(coerced_value)) {
oh$error_list$add(
"6.4.1",
"Variable value cannot be coerced according to the input coercion rules",
loc = value$loc
)
next
}
coerced_values[[argument_name]] <- coerced_value
next
} else if (!is.null(default_value)) {
value <- default_value
} else if (inherits(argument_type, "NonNullType")) {
oh$error_list$add(
"6.4.1",
"non nullable type argument did not find variable definition",
loc = value$loc
)
next
} else {
next
}
}
coerced_value <- type_obj$.parse_ast(value, oh$schema)
if (!is.null(value) && is.null(coerced_value)) {
oh$error_list$add(
"6.4.1",
"Value cannot be coerced according to the input coercion rules",
loc = value$loc
)
next
}
coerced_values[[argument_name]] <- coerced_value
}
coerced_values
}
resolve_field_value <- function(object_type, object_value, field_obj, argument_values, ..., oh) {
field_name_txt <- format(field_obj$name)
if (! (field_name_txt %in% names(object_value))) {
return(NULL)
}
val <- object_value[[field_name_txt]]
if (is.function(val)) {
val_fn <- val
ans <- val_fn(object_value, argument_values, oh$schema)
return(ans)
}
return(val)
}
complete_value <- function(field_type, fields, result, ..., oh) {
if (inherits(field_type, "NonNullType")) {
inner_type <- field_type$type
completed_result <- complete_value(inner_type, fields, result, oh = oh)
if (is.null(completed_result)) {
oh$error_list$add(
"6.4.3",
"non null type: ", format(field_type), " returned a null value",
loc = fields[[1]]$loc
)
return(NULL)
}
return(completed_result)
}
if (is_nullish(result)) {
return(NULL)
}
if (inherits(field_type, "ListType")) {
if (is.vector(result)) {
result <- as.list(result)
}
if (!is.list(result)) {
oh$error_list$add(
"6.4.3",
"list type returned a non list type"
)
return(NULL)
}
inner_type <- field_type$type
completed_result <- lapply(result, function(result_item) {
complete_value(inner_type, fields, result_item, oh = oh)
})
completed_result <- unname(completed_result)
return(completed_result)
}
if (
oh$schema$is_scalar(field_type) ||
oh$schema$is_enum(field_type)
) {
type_obj <- ifnull(
oh$schema$get_scalar(field_type),
oh$schema$get_enum(field_type)
)
resolved_result <- type_obj$.resolve(result, oh$schema)
if (length(resolved_result) == 0) {
return(NULL)
}
return(resolved_result)
}
if (
is_object_interface_or_union(field_type, oh$schema)
) {
if (oh$schema$is_object(field_type)) {
object_type <- field_type
} else {
field_obj <- ifnull(
oh$schema$get_interface(field_type),
oh$schema$get_union(field_type)
)
object_type <- resolve_abstract_type(field_type, result, field_obj, oh = oh)
}
object_obj <- oh$schema$get_object(object_type)
if (is.function(object_obj$.resolve)) {
result <- object_obj$.resolve(result, schema = oh$schema)
if (is_nullish(result)) {
return(NULL)
}
}
sub_selection_set <- merge_selection_sets(fields, oh = oh)
ret <- execute_selection_set(sub_selection_set, object_type, result, oh = oh)
return(ret)
}
stop("this should not be reached")
}
resolve_abstract_type <- function(abstract_type, object_value, abstract_obj, ..., oh) {
if (inherits(abstract_obj, "InterfaceTypeDefinition")) {
type <- abstract_obj$.resolve_type(object_value, oh$schema)
type <- as_type(type)
return(type)
} else if (inherits(abstract_obj, "UnionTypeDefinition")) {
type <- abstract_obj$.resolve_type(object_value, oh$schema)
type <- as_type(type)
return(type)
}
stop("Interface or Union objects can only resolve an abstract type")
}
merge_selection_sets <- function(fields, ..., oh) {
selections <- list()
for (field in fields) {
field_selection_set <- field$selectionSet
if (is.null(field_selection_set)) next
if (length(field_selection_set) == 0) next
selections <- append(selections, field_selection_set$selections)
}
ret <- SelectionSet$new(selections = selections)
return(ret)
}
is_nullish <- function(x) {
if (is.null(x)) {
return(TRUE)
}
if (
is.logical(x) ||
is.numeric(x) ||
is.character(x)
) {
if (length(x) == 0) {
return(TRUE)
} else if (length(x) > 1) {
return(FALSE)
} else {
return(
is.na(x) | is.nan(x)
)
}
}
return(FALSE)
} |
readBTLS <- function(dat_FilePath,
spss_FilePath,
verbose=TRUE) {
userOp <- options(OutDec = ".")
on.exit(options(userOp), add = TRUE)
dat_FilePath <- suppressWarnings(normalizePath(unique(dat_FilePath), winslash = "/"))
spss_FilePath <- suppressWarnings(normalizePath(unique(spss_FilePath), winslash = "/"))
if(!file.exists(dat_FilePath)){
stop(paste0("Cannot find specified data file ", sQuote("dat_FilePath"), " in path ", sQuote(file.path(dat_FilePath)), "."))
}
if(!file.exists(spss_FilePath)){
stop(paste0("Cannot find specified data file ", sQuote("spss_FilePath"), " in path ", sQuote(file.path(spss_FilePath)), "."))
}
if(verbose){
cat(paste0("Parsing SPSS syntax file.\n"))
}
fileFormat <- parseSPSSFileFormat(spss_FilePath)
lafObj <- laf_open_fwf(dat_FilePath, fileFormat$dataType, fileFormat$Width, fileFormat$variableName)
for(coli in 1:nrow(fileFormat)){
if(verbose && ((coli %% 500)==0) || coli==1 || coli==nrow(fileFormat)){
cat(paste0("Processing column ", coli, " of ", ncol(lafObj), "\n"))
}
colData <- lafObj[,coli]
colData <- colData[,1, drop=TRUE]
if(is.numeric(colData)){
if(any(grepl(".", colData, fixed = TRUE), na.rm = TRUE)){
decTestLen <- num.decimals(colData)
decTestLen[is.na(decTestLen)] <- 0
fileFormat$dataType[coli] <- "numeric"
fileFormat$Decimal[coli] <- max(decTestLen)
}else{
if(fileFormat$Width[coli]<9){
fileFormat$dataType[coli] <- "integer"
fileFormat$Decimal[coli] <- 0
}
}
}
}
close(lafObj)
lafObj <- laf_open_fwf(dat_FilePath, fileFormat$dataType, fileFormat$Width, fileFormat$variableName)
fileFormat <- identifyBTLSWeights(fileFormat)
weights <- buildBTLSWeightList(fileFormat)
if(!is.null(weights)){
attributes(weights)$default <- ""
}
pvs <- list()
omittedLevels <- c("Deceased", "Nonrespondent", "suppressed due to limited number of respondents", "Respondent, valid skip",
"Valid Skip", "Valid skip", "Missing", "Respondent, missing data",
"(Missing)", NA)
edsurvey.data.frame(userConditions = list(),
defaultConditions = NULL,
dataList = buildBTLSDataList(lafObj, fileFormat),
weights = weights,
pvvars = pvs,
subject = "",
year = "2007-2012",
assessmentCode = "Longitudinal",
dataType = "Longitudinal Data",
gradeLevel = "",
achievementLevels = NULL,
omittedLevels = omittedLevels,
survey = "BTLS",
country = "USA",
psuVar = NULL,
stratumVar = NULL,
jkSumMultiplier = 0.0113636363636364,
validateFactorLabels = TRUE,
reqDecimalConversion = FALSE)
}
identifyBTLSWeights <- function(fileFormat){
varNames <- fileFormat$variableName
wgtVars <- grep("^(w1|w2|w3|w4|w5).*(wt|wgt)$", fileFormat$variableName, ignore.case = TRUE, value = TRUE)
fileFormat$weights <- fileFormat$variableName %in% wgtVars
return(fileFormat)
}
buildBTLSWeightList <- function(fileFormat){
wgtVars <- fileFormat[fileFormat$weights==TRUE, "variableName"]
if(length(wgtVars)==0){
return(NULL)
}
weights <- list()
wgtLookupDF <- data.frame(wgt=wgtVars,
repVar=rep("", times=length(wgtVars)),
stringsAsFactors = FALSE)
wgtLookupDF[wgtLookupDF$wgt=="w1tfnlwgt", "repVar"] <- "w1trepwt"
wgtLookupDF[wgtLookupDF$wgt=="w2afwt", "repVar"] <- "w2arwt"
wgtLookupDF[wgtLookupDF$wgt=="w2rafwt", "repVar"] <- "w2rarwt"
wgtLookupDF[wgtLookupDF$wgt=="w3afwt", "repVar"] <- "w3arwt"
wgtLookupDF[wgtLookupDF$wgt=="w3lwgt", "repVar"] <- "w3lrwgt"
wgtLookupDF[wgtLookupDF$wgt=="w3rafwt", "repVar"] <- "w3rarwt"
wgtLookupDF[wgtLookupDF$wgt=="w3rlwgt", "repVar"] <- "w3rlrwgt"
wgtLookupDF[wgtLookupDF$wgt=="w4afwt", "repVar"] <- "w4arwt"
wgtLookupDF[wgtLookupDF$wgt=="w4lwgt", "repVar"] <- "w4lrwgt"
wgtLookupDF[wgtLookupDF$wgt=="w4rlwgt", "repVar"] <- "w4rlrwgt"
wgtLookupDF[wgtLookupDF$wgt=="w4rafwt", "repVar"] <- "w4rarwt"
wgtLookupDF[wgtLookupDF$wgt=="w5afwt", "repVar"] <- "w5arwt"
wgtLookupDF[wgtLookupDF$wgt=="w5lwgt", "repVar"] <- "w5lrwgt"
wgtLookupDF[wgtLookupDF$wgt=="w5rlwgt", "repVar"] <- "w5rlrwgt"
for(i in 1:length(wgtVars)){
tempVar <- wgtVars[i]
repVar <- wgtLookupDF$repVar[wgtLookupDF$wgt==tempVar]
wgtPattern = paste0("^", repVar,"\\d+$")
ujkz <- unique(tolower(grep(wgtPattern, fileFormat$variableName, value = TRUE, ignore.case = TRUE)))
ujkz <- sub(repVar, "", ujkz, ignore.case = TRUE)
if(length(ujkz)>0){
tmpWgt <- list()
tmpWgt[[1]] <- list(jkbase=repVar, jksuffixes=as.character(ujkz))
names(tmpWgt)[[1]] <- tempVar
weights <- c(weights,tmpWgt)
}
}
return(weights)
}
buildBTLSDataList <- function(lafObj, fileFormat){
dataList <- list()
dataList[["Data"]] <- dataListItem(lafObject = lafObj,
fileFormat = fileFormat,
levelLabel = "Data",
forceMerge = TRUE,
parentMergeLevels = NULL,
parentMergeVars = NULL,
mergeVars = NULL,
ignoreVars = NULL,
isDimLevel = TRUE)
return(dataList)
} |
as_tibble.pkg_ref <- function(x, ...) {
as_tibble(vctrs::new_list_of(list(x),
ptype = pkg_ref(),
class = "list_of_pkg_ref"))
}
as_tibble.list_of_pkg_ref <- function(x, ...) {
package_names <- vapply(x, "[[", character(1L), "name")
versions <- vapply(x, function(xi) as.character(xi$version), character(1L))
tibble::tibble(
package = package_names,
version = versions,
pkg_ref = x)
} |
MeanA.SGB <-
function(shape1,scale,shape2){
pdig <- digamma(shape2)/shape1
np <- length(shape2)
EAu <- scale%*%diag(exp(pdig),nrow=np,ncol=np)
EAu <- EAu/rowSums(EAu)
colnames(EAu) <- colnames(scale)
return(EAu)
} |
gradient_cloud <- function(text.var, bigroup.var, rev.binary = FALSE, X = "red",
Y = "blue", stem = FALSE, stopwords = NULL, caps = TRUE, caps.list = NULL,
I.list = TRUE, random.order = FALSE, rot.per = 0.0, min.freq = 1,
max.word.size = NULL, min.word.size = 0.5, breaks = 10, cloud.font = NULL,
title = NULL, title.font = NULL, title.color = "black", title.padj = .25,
title.location = 3, title.cex = NULL, legend.cex = .8,
legend.location = c(.025, .025, .25, .04), char2space = "~~") {
text.var <- as.character(text.var)
bigroup.var <- drop.levels(bigroup.var)
if (length(unique(bigroup.var)) != 2) {
stop("bigroup.var must contain exactly 2 levels")
}
if (rev.binary) {
bigroup.var <- factor(bigroup.var, levels = rev(levels(bigroup.var)))
}
if (stem) {
text.var <- stemmer(text.var)
}
word.freq <- wfdf(text.var, bigroup.var)
nms <- colnames(word.freq)[-1]
colnames(word.freq)[-1] <- utils::tail(LETTERS, 2)
wf2 <- word.freq[, -1]/colSums(word.freq[, -1])
colnames(wf2) <- paste0("prop_", colnames(wf2))
WF <- data.frame(word.freq, wf2, check.names = FALSE)
WF[, "total"] <- rowSums(word.freq[, -1])
WF[, "diff"] <- wf2[, 1] - wf2[, 2]
low <- WF[, "diff"][WF[, "diff"] < 0]
high <- WF[, "diff"][WF[, "diff"] > 0]
lcuts <- stats::quantile(low, seq(0, 1, length.out = round(breaks/2)))
hcuts <- stats::quantile(high, seq(0, 1, length.out = round(breaks/2)))
cts <- as.numeric(unique(sort(c(-1, lcuts, 0, hcuts, 1))))
WF[, "trans"] <- cut(WF[, "diff"], breaks=cts)
if (!is.null(stopwords)) {
WF <- WF[!WF[, 1] %in% tolower(stopwords),]
}
if (caps) {
WF[, 1] <- capitalizer(WF[, 1], caps.list = caps.list,
I.list = I.list, apostrophe.remove = TRUE)
}
if(is.null(max.word.size )) {
max.word.size <- mean(WF[, "total"] + 1)
}
colfunc <- grDevices::colorRampPalette(c(X, Y))
WF[, "colors"] <- lookup(WF[, "trans"], levels(WF[, "trans"]),
rev(colfunc(length(levels(WF[, "trans"])))))
OP <- graphics::par()[["mar"]]
on.exit(graphics::par(mar = OP))
graphics::par(mar=c(7,1,1,1))
wordcloud(WF[, 1], WF[, "total"], min.freq = min.freq,
colors = WF[, "colors"], rot.per = rot.per, random.order = random.order,
ordered.colors = TRUE, vfont = cloud.font,
scale = c(max.word.size , min.word.size))
if (!is.null(title)) {
graphics::mtext(title, side = title.location, padj = title.padj,
col = title.color, family = title.font, cex = title.cex)
}
COLS <- colfunc(length(levels(WF[, "trans"])))
LL <- legend.location
color.legend(LL[1], LL[2], LL[3], LL[4], nms, COLS, cex = legend.cex)
colnames(WF)[1:5] <- c("words", nms, paste0("prop.", nms))
WF <- WF[, c(1:3, 6, 4:5, 7:9)]
return(invisible(WF))
}
drop.levels <- function(x, reorder=TRUE, ...){
x <- x[, drop=TRUE]
if(reorder) x <- reorder(x, ...)
x
} |
Token2S <- R6Class("token2s",
public = list(initialize = function(shape = pp_shape(),
whd = list(width = 1, height = 1, depth = 1),
center = Point3D$new(),
R = diag(3)) {
xy_npc <- Point2D$new(shape$npc_coords)
xyz_scaled <- Point3D$new(xy_npc)$translate(-0.5, -0.5, 0.5)$dilate(whd)
xyz_f <- xyz_scaled$rotate(R)$translate(center)
xy_npc <- Point2D$new(shape$npc_coords)
xyz_scaled <- Point3D$new(xy_npc)$translate(-0.5, -0.5, -0.5)$dilate(whd)
xyz_b <- xyz_scaled$rotate(R)$translate(center)
self$xyz <- Point3D$new(x = c(xyz_f$x, xyz_b$x),
y = c(xyz_f$y, xyz_b$y),
z = c(xyz_f$z, xyz_b$z))
edge_partition <- partition_edges(shape)
n_points <- length(xyz_f)
n_edges <- length(edge_partition$type)
edges <- vector("list", n_edges)
for (i in seq(n_edges)) {
vertices <- self$xyz[edge_indices(edge_partition$indices[[i]], n_points)]
type <- edge_partition$type[i]
edges[[i]] <- edge_class(type, vertices)
}
self$edges <- edges
},
op_edge_order = function(angle) {
r <- 10 * self$xyz$width
op_diff <- Point2D$new(0, 0)$translate_polar(angle, r)
op_diff <- Point3D$new(op_diff, z = r / sqrt(2))
op_ref <- self$xyz$c$translate(op_diff)
dists <- sapply(self$edges, function(x) op_ref$distance_to(x$vertices$c))
order(dists)
},
op_edges = function(angle) {
self$edges[self$op_edge_order(angle)]
},
xyz = NULL, edges = NULL
),
private = list(),
active = list(xyz_face = function() {
n <- length(self$xyz$x) / 2
self$xyz[seq(n)]
}, xyz_back = function() {
n <- length(self$xyz$x) / 2
self$xyz[seq(n + 1, 2 * n)]
})
)
edge_indices <- function(indices, n_points) {
c(indices, n_points + rev(indices))
}
edge_class <- function(type, vertices) {
switch(type,
curved = CurvedEdge$new(vertices),
flat = FlatEdge$new(vertices),
ring = RingEdge$new(vertices))
}
partition_edges <- function(shape) {
classes <- shape$npc_coords$c
n <- length(classes)
if (all(classes == "C0")) {
list(type = rep("flat", n),
indices = lapply(seq_along(classes), function(x) c(x, x %% n + 1)))
} else if (all(classes == "C1")) {
list(type = "ring", indices = list(seq_along(classes)))
} else {
if (!(classes[n] == "C0")) stop("Can only handle case when last class is 'C0'")
type <- vector("character")
indices <- vector("list")
index <- 1
prev <- classes[n]
curve_start <- NULL
for (i in seq_along(classes)) {
class <- classes[i]
if (all(c(prev, class) == "C0")) {
type[index] <- "flat"
i_prev <- ifelse(i == 1, n, i - 1)
indices[[index]] <- c(i_prev, i)
index <- index + 1
} else if (prev == "C1" && class == "C0") {
type[index] <- "curved"
if (curve_start == 0) {
indices[[index]] <- c(n, seq(i))
} else {
indices[[index]] <- seq(curve_start, i)
}
index <- index + 1
} else if (prev == "C0" && class == "C1") {
curve_start <- i - 1
}
prev <- class
}
list(type = type, indices = indices)
}
}
FlatEdge <- R6Class("edge_flat",
public = list(vertices = NULL,
initialize = function(vertices = NULL) self$vertices <- vertices,
op_grob = function(angle, scale, ...) {
xy <- self$vertices$project_op(angle, scale)
polygonGrob(xy$x, xy$y, default.units = "in", ...)
}),
private = list(),
active = list()
)
RingEdge <- R6Class("edge_ring",
public = list(vertices = NULL,
initialize = function(vertices = NULL) self$vertices <- vertices,
op_grob = function(angle, scale, ...) {
n <- length(self$vertices) / 2
xy_f <- self$vertices[seq(n)]$project_op(angle, scale)
projections <- numeric(n)
proj_vec <- Vector$new(to_x(angle - 90, 1), to_y(angle - 90, 1))
for (ii in seq(n)) {
projections[ii] <- proj_vec$dot(xy_f[ii])
}
i_min <- which.min(projections)
i_max <- which.max(projections)
if (i_min < i_max) {
indices1 <- seq(i_min, i_max)
if (i_max < n) {
indices2 <- c(seq(i_max + 1, n), seq_len(i_min - 1))
} else {
indices2 <- seq(1, i_min - 1)
}
} else {
indices1 <- c(seq(i_min, n), seq(1, i_max))
indices2 <- seq(i_max + 1, i_min - 1)
}
r <- 10 * self$vertices$width
op_diff <- Point2D$new(0, 0)$translate_polar(angle, r)
op_diff <- Point3D$new(op_diff, z = r / sqrt(2))
op_ref <- self$vertices$c$translate(op_diff)
d1 <- op_ref$distance_to(self$vertices[indices1]$c)
d2 <- op_ref$distance_to(self$vertices[indices2]$c)
if (d1 > d2) {
indices_obscured <- indices2
indices_visible <- indices1
} else {
indices_obscured <- indices1
indices_visible <- indices2
}
xy <- self$vertices$project_op(angle, scale)
x_obscured <- xy$x[full_indices(indices_obscured, n)]
y_obscured <- xy$y[full_indices(indices_obscured, n)]
x_visible <- xy$x[full_indices(indices_visible, n)]
y_visible <- xy$y[full_indices(indices_visible, n)]
polygonGrob(x=c(x_obscured, x_visible),
y=c(y_obscured, y_visible),
id.lengths = c(length(x_obscured), length(x_visible)),
default.units="in", ...)
}),
private = list(),
active = list()
)
full_indices <- function(indices, n) c(indices, rev(2 * n + 1 - indices))
CurvedEdge <- R6Class("edge_curved",
public = list(vertices = NULL,
initialize = function(vertices = NULL) self$vertices <- vertices,
op_grob = function(angle, scale, ...) {
n <- length(self$vertices) / 2
xy_f <- self$vertices[seq(n)]$project_op(angle, scale)
projections <- numeric(n)
proj_vec <- Vector$new(to_x(angle - 90, 1), to_y(angle - 90, 1))
for (ii in seq(n)) {
projections[ii] <- proj_vec$dot(xy_f[ii])
}
i_min <- which.min(projections)
i_max <- which.max(projections)
l_indices <- list()
i_l <- min(i_min, i_max)
i_u <- max(i_min, i_max)
if (i_l == 1 && i_u == n) {
l_indices[[1]] <- seq(n)
} else if (i_l == 1) {
l_indices[[1]] <- seq(i_u + 1, n)
l_indices[[2]] <- seq(1, i_u)
} else if (i_u == n) {
l_indices[[1]] <- seq(1, i_l - 1)
l_indices[[2]] <- seq(i_l, n)
} else {
l_indices[[1]] <- seq(1, i_l - 1)
l_indices[[2]] <- seq(i_u + 1, n)
l_indices[[3]] <- seq(i_l, i_u)
}
xy <- self$vertices$project_op(angle, scale)
x <- numeric(0)
y <- numeric(0)
id <- numeric(0)
r <- 10 * self$vertices$width
op_diff <- Point2D$new(0, 0)$translate_polar(angle, r)
op_diff <- Point3D$new(op_diff, z = r / sqrt(2))
op_ref <- self$vertices$c$translate(op_diff)
dists <- sapply(l_indices,
function(x) {
indices <- full_indices(x, n)
op_ref$distance_to(self$vertices[indices]$c)
})
l_indices <- l_indices[order(dists)]
for (i in seq_along(l_indices)) {
indices <- full_indices(l_indices[[i]], n)
x <- append(x, xy$x[indices])
y <- append(y, xy$y[indices])
id <- append(id, rep(i, length(indices)))
}
polygonGrob(x=x, y=y, id=id, default.units="in", ...)
}),
private = list(),
active = list()
) |
.brent <- function(brac, f, mObj, bObj, wb, init, pMat, qu, ctrl, varHat, cluster, t = .Machine$double.eps^0.25, aTol = 0, ...)
{
brac <- sort(brac)
a <- brac[1]
b <- brac[2]
epsi = sqrt(.Machine$double.eps)
cc = 0.5 * ( 3.0 - sqrt(5.0) )
sa = a
sb = b
x = sa + cc * ( b - a )
w = x
v = w
e = 0.0
feval = f(lsig = x, mObj = mObj, bObj = bObj, wb = wb, initM = init[["initM"]], initB = init[["initB"]],
pMat = pMat, qu = qu, ctrl = ctrl, varHat = varHat, cluster = cluster, ...)
fx = feval$outLoss
fw = fx
fv = fw
jj <- 1
store <- list()
store[[jj]] <- list("x" = x, "f" = fx, "initM" = feval[["initM"]], "initB" = feval[["initB"]])
jj <- jj + 1
while( TRUE ) {
m = 0.5 * ( sa + sb )
tol = epsi * abs ( x ) + t
t2 = 2.0 * tol
if( (abs(x-m) <= (t2 - 0.5 * (sb-sa))) || any(abs(x-c(a, b)) < aTol * abs(b-a)) ) { break }
r = 0.0
q = r
p = q
if ( tol < abs(e) ) {
r = ( x - w ) * ( fx - fv )
q = ( x - v ) * ( fx - fw )
p = ( x - v ) * q - ( x - w ) * r
q = 2.0 * ( q - r )
if( 0.0 < q ) { p = - p }
q = abs ( q )
r = e
e = d
}
if ( (abs(p) < abs(0.5 * q * r)) &&
(q * ( sa - x )) < p &&
(p < q * ( sb - x )) ) {
d = p / q
u = x + d
if ( ( u - sa ) < t2 || ( sb - u ) < t2 ) {
if ( x < m ) { d = tol } else { d = - tol }
}
} else {
if ( x < m ){ e = sb - x } else { e = sa - x }
d = cc * e
}
if ( tol <= abs( d ) ){
u = x + d
} else {
if ( 0.0 < d ) { u = x + tol } else { u = x - tol }
}
init <- store[[ which.min(abs(u - sapply(store, "[[", "x"))) ]]
feval = f(lsig = u, mObj = mObj, bObj = bObj, wb = wb, initM = init[["initM"]], initB = init[["initB"]],
pMat = pMat, qu = qu, ctrl = ctrl, varHat = varHat, cluster = cluster, ...)
fu = feval$outLoss
store[[jj]] <- list("x" = u, "f" = fu, "initM" = feval[["initM"]], "initB" = feval[["initB"]])
jj <- jj + 1
if ( fu <= fx ){
if ( u < x ) { sb = x } else { sa = x }
v = w
fv = fw
w = x
fw = fx
x = u
fx = fu
} else {
if ( u < x ) { sa = u } else { sb = u }
if ( (fu <= fw) || (w == x) ) {
v = w
fv = fw
w = u
fw = fu
} else {
if ( (fu <= fv) || (v == x) || (v == w) ){
v = u
fv = fu
}
}
}
}
store <- rbind( sapply(store, "[[", "x"), sapply(store, "[[", "f") )
return( list("minimum" = x, "objective" = fx, "store" = store) )
} |
LRTTBoot <- function(X, mu0, B){
n <- nrow(X)
p <- ncol(X)
if (length(mu0)!= p) stop("The test cannot be performed.")
Xsrb <- apply(X, 2, mean)
Ssrb <- var(X)
H <- (Xsrb - mu0) %*% t(Xsrb - mu0)
LRTTo <- n * (log(sum(diag(Ssrb + H))) - log(sum(diag(Ssrb))))
LRTTv <- LRTTo
for (i in 1:B)
{
Xbb <- mvrnorm(n, mu0, Ssrb)
Xsbb <- apply(Xbb, 2, mean)
Ssbb <- var(Xbb)
H <- (Xsbb - mu0) %*% t(Xsbb - mu0)
LRTTb <- n * (log(sum(diag(Ssbb + H))) - log(sum(diag(Ssbb))))
LRTTv <- c(LRTTv, LRTTb)
}
p.value <- length(LRTTv[as.numeric(LRTTo) <= LRTTv]) / (B + 1)
return(list(LRTT = LRTTo, valor.p = p.value))
} |
"simts_3node" |
bootstrapVarElimination_Bin <- function (object,pvalue=0.05,Outcome="Class",data,startOffset=0, type = c("LOGIT", "LM","COX"),selectionType=c("zIDI","zNRI"),loops=64,print=TRUE,plots=TRUE)
{
seltype <- match.arg(selectionType)
pvalue <- as.vector(pvalue);
boot.var.IDISelection <- function (object,pvalue=0.05,Outcome="Class",startOffset=0, type = c("LOGIT", "LM","COX"),selectionType=c("zIDI","zNRI"),loops,best.formula=NULL)
{
seltype <- match.arg(selectionType)
type <- match.arg(type);
varsList <- unlist(as.list(attr(terms(object),"variables")))
termList <- str_replace_all(attr(terms(object),"term.labels"),":","\\*")
if (pvalue[1]<0.5)
{
cthr <- abs(qnorm(pvalue));
}
else
{
cthr <- pvalue;
}
removeID <- 0;
outCome <- paste(varsList[2]," ~ 1");
frm1 <- outCome;
testAUC <- 0.5;
removedTerm <- NULL;
who <- 0;
idiCV <- NULL;
modsize <- length(termList);
if (modsize>0)
{
for ( i in 1:modsize)
{
frm1 <- paste(frm1,"+",termList[i]);
}
ftmp <- formula(frm1);
idiCV <- bootstrapValidation_Bin(1.0,loops,ftmp,Outcome,data,type,plots =plots,best.model.formula=best.formula)
testAUC <- (idiCV$sensitivity + idiCV$specificity)/2;
testAUC <- median(testAUC,na.rm = TRUE);
resuBin <- getVar.Bin(object,data,Outcome,type);
startSearch <- 1 + startOffset;
frm1 <- outCome;
if (startSearch > 1)
{
for ( i in 1:(startSearch-1))
{
frm1 <- paste(frm1,"+",termList[i]);
}
}
if (startSearch <= modsize)
{
ploc <- 1+modsize-startSearch;
if (ploc>length(cthr)) ploc <- length(cthr);
minlcl <- cthr[ploc];
idlist <- startOffset+1;
for ( i in startSearch:modsize )
{
{
if (seltype=="zIDI")
{
c0 <- resuBin$z.IDIs[idlist];
ci <- median(idiCV$z.IDIs[,idlist], na.rm = TRUE);
ci2 <- median(idiCV$test.z.IDIs[,idlist], na.rm = TRUE);
}
else
{
c0 <- resuBin$z.NRIs[idlist];
ci <- median(idiCV$z.NRIs[,idlist], na.rm = TRUE);
ci2 <- median(idiCV$test.z.NRIs[,idlist], na.rm = TRUE);
}
if (is.nan(ci) || is.na(ci) ) ci <- c0;
if (is.nan(ci2) || is.na(ci2) ) ci2 <- ci;
minz <- min(c(c0,ci,ci2));
if (minz < minlcl)
{
minlcl = minz;
who = i;
}
}
idlist=idlist+1;
}
}
for ( i in startSearch:modsize)
{
if (who != i)
{
if (who != -1)
{
frm1 <- paste(frm1,"+",termList[i]);
}
}
else
{
removeID=i;
removedTerm=termList[i];
}
}
if ((modsize == startSearch) && (who == startSearch))
{
removeID = -removeID;
}
}
ftmp <- formula(frm1);
if ((who>0) && (modsize>1)) idiCV <- bootstrapValidation_Bin(1.0,loops,ftmp,Outcome,data,type,plots=plots)
afterTestAUC <- (idiCV$sensitivity + idiCV$specificity)/2;
afterTestAUC <- median(afterTestAUC,na.rm = TRUE);
if (is.null(afterTestAUC)) afterTestAUC=0.0;
if (is.null(testAUC)) testAUC=0.5;
if (is.na(afterTestAUC)) afterTestAUC=0.0;
if (is.na(testAUC)) testAUC=0.5;
result <- list(Removed=removeID,BootModelAUC=idiCV$blind.ROCAUC$auc,backfrm=frm1,bootval=idiCV,afterTestAUC=afterTestAUC,beforeTestAUC=testAUC,removedTerm=removedTerm);
return (result)
}
bkobj <- NULL;
bestAccuracy <- c(0.5,0.5,0.5);
best.formula=NULL;
startAccuracy = bestAccuracy;
maxAccuracy <- startAccuracy[2];
changes=1;
loopsAux=0;
model <- object;
modelReclas <- NULL;
myOutcome <- Outcome;
varsList <- unlist(as.list(attr(terms(object),"variables")))
termList <- str_replace_all(attr(terms(object),"term.labels"),":","\\*")
outCome = paste(varsList[2]," ~ 1");
frm1 = outCome;
if (length(termList) > 0)
{
for ( i in 1:length(termList))
{
frm1 <- paste(frm1,paste("+",termList[i]));
}
}
beforeFSCmodel.formula <- frm1;
model.formula <- frm1;
if (is.null(best.formula))
{
best.formula <- frm1;
}
min.formula <- best.formula;
beforeFSCmodel <- object;
beforeFormula <- frm1;
bk <- NULL;
changes2 <- 0;
while ((changes>0) && (loopsAux<100))
{
bk <- boot.var.IDISelection(model,pvalue,Outcome=myOutcome,startOffset,type,seltype,loops,best.formula);
beforeFormula <- bk$backfrm;
nmodel = modelFitting(formula(bk$backfrm),data,type,TRUE);
if (!is.null(bk$bootval))
{
testAccuracy <-as.vector(quantile(bk$bootval$accuracy, probs = c(0.05, 0.5, 0.95), na.rm = TRUE,names = FALSE, type = 7));
if (loopsAux == 0) startAccuracy <- bk$beforeTestAUC;
}
if ((bk$Removed>0) && (!inherits(nmodel, "try-error")))
{
if (!is.null(bk$bootval))
{
if (!is.na(testAccuracy) && !is.null(testAccuracy))
{
if (testAccuracy[2] >= bestAccuracy[1])
{
best.formula <- bk$backfrm;
if (testAccuracy[2] >= maxAccuracy)
{
min.formula <- bk$backfrm;
maxAccuracy <- testAccuracy[2];
}
bestAccuracy <- testAccuracy;
}
}
}
if (changes>0)
{
changes2<- attr(terms(model),"term.labels")[which(!(attr(terms(model),"term.labels") %in% attr(terms(nmodel),"term.labels")))]
if (length(changes2)>1)
{
changes2<-changes2[2]
}
}
}
changes = as.integer(bk$Removed);
model <- nmodel;
model.formula <- bk$backfrm;
loopsAux = loopsAux + 1
}
idiCV <- NULL;
if (length(all.vars(formula(model.formula))) > 1)
{
modelReclas <- getVar.Bin(model,data=data,Outcome=myOutcome,type);
idiCV <- bootstrapValidation_Bin(1.0000,2*loops,formula(model.formula),myOutcome,data,type,plots=plots);
}
else
{
model.formula <- outCome;
idiCV <- bootstrapValidation_Bin(1.0000,loops,formula(model.formula),myOutcome,data,type,plots=plots);
}
testAccuracy <-as.vector(quantile(idiCV$accuracy, probs = c(0.05, 0.5, 0.95), na.rm = TRUE,names = FALSE, type = 7));
if (print == TRUE)
{
cat("Before FSC Mod:",beforeFSCmodel.formula,"\n")
cat("At Acc Model :",min.formula,"\n")
cat("Reduced Model :",model.formula,"\n")
cat("Start AUC:",startAccuracy,"last AUC:",idiCV$blind.ROCAUC$auc,"Accuracy:",testAccuracy[2],"\n")
}
back.model<-modelFitting(formula(model.formula),data,type,TRUE);
environment(back.model$formula) <- globalenv()
environment(back.model$terms) <- globalenv()
at.opt.model<-modelFitting(formula(min.formula),data,type,TRUE);
environment(at.opt.model$formula) <- NULL
environment(at.opt.model$terms) <- NULL
result <- list(back.model=back.model,
loops=loopsAux,
reclas.info=modelReclas,
bootCV=idiCV,
back.formula=model.formula,
lastRemoved=changes2,
at.opt.model=at.opt.model,
beforeFSC.formula=beforeFSCmodel.formula,
at.Accuracy.formula=best.formula);
return (result);
} |
get_Rcpp_module_def_code <- function(model_name) {
RCPP_MODULE <-
'
struct stan_model_holder {
stan_model_holder(rstan::io::rlist_ref_var_context rcontext,
unsigned int random_seed)
: rcontext_(rcontext), random_seed_(random_seed)
{
}
//stan::math::ChainableStack ad_stack;
rstan::io::rlist_ref_var_context rcontext_;
unsigned int random_seed_;
};
Rcpp::XPtr<stan::model::model_base> model_ptr(stan_model_holder* smh) {
Rcpp::XPtr<stan::model::model_base> model_instance(new stan_model(smh->rcontext_, smh->random_seed_), true);
return model_instance;
}
Rcpp::XPtr<rstan::stan_fit_base> fit_ptr(stan_model_holder* smh) {
return Rcpp::XPtr<rstan::stan_fit_base>(new rstan::stan_fit(model_ptr(smh), smh->random_seed_), true);
}
std::string model_name(stan_model_holder* smh) {
return model_ptr(smh).get()->model_name();
}
RCPP_MODULE(stan_fit4%model_name%_mod){
Rcpp::class_<stan_model_holder>("stan_fit4%model_name%")
.constructor<rstan::io::rlist_ref_var_context, unsigned int>()
.method("model_ptr", &model_ptr)
.method("fit_ptr", &fit_ptr)
.method("model_name", &model_name)
;
}
'
gsub("%model_name%", model_name, RCPP_MODULE)
} |
node.sons <-
function(phy, node)
{
if (!("phylo" %in% class(phy))) stop("Object \"phy\" is not of class \"phylo\"")
E <- phy$edge
n <- dim(E)[1]
sons <- numeric(0)
count <- 1
for(i in 1:n) {
if(E[i,1] == node) {
sons[count] <- E[i,2];
count <- count + 1
}
}
return(sons)
} |
convert.graph <- function(graph) {
if (is.matrix(graph))
t(graph)
else if (is.data.frame(graph))
t(data.matrix(graph))
else if (inherits(graph, "graph") && requireNamespace("graph", quietly=TRUE)) {
graph::edgeMatrix(graph)
}
else stop("unrecognized graph type")
}
name.orbits <- function(orbits) {
orb.names = NULL
for (i in 0:(ncol(orbits)-1)) {
orb.names <- c(orb.names, paste("O", i, sep=""))
}
colnames(orbits) <- orb.names
orbits
}
count4 <- function(graph) {
edges <- convert.graph(graph)
result <- .C("count4",
edges, dim(edges),
orbits=matrix(0, nrow=max(edges), ncol=15))$orbits
name.orbits(result)
}
count5 <- function(graph) {
edges <- convert.graph(graph)
result <- .C("count5",
edges, dim(edges),
orbits=matrix(0, nrow=max(edges), ncol=73))$orbits
name.orbits(result)
}
ecount4 <- function(graph) {
edges <- convert.graph(graph)
result <- .C("ecount4",
edges, dim(edges),
orbits=matrix(0, nrow=ncol(edges), ncol=12))$orbits
name.orbits(result)
}
ecount5 <- function(graph) {
edges <- convert.graph(graph)
result <- .C("ecount5",
edges, dim(edges),
orbits=matrix(0, nrow=ncol(edges), ncol=68))$orbits
name.orbits(result)
} |
l2dpar <-
function(mean1,var1,mean2,var2,check=FALSE)
{
p=length(mean1);
d=mean1-mean2;
vars=var1+var2;
if (p == 1)
{
if(check)
{if(abs(var1)<.Machine$double.eps | abs(var2)<.Machine$double.eps)
{stop("At least one variance is zero")
}
}
return((1/sqrt(2*pi))*(1/sqrt(vars))*exp(-(1/2)*(d^2)/vars))
} else
{
if(check)
{if(abs(det(var1))<.Machine$double.eps | abs(det(var2))<.Machine$double.eps)
{stop("One of the sample variances is degenerate")
}
}
return(as.numeric((1/(2*pi)^(p/2))*(1/det(vars)^(1/2))*exp((-1/2)*t(d)%*%solve(vars)%*%d)))
}
} |
plot_layout_vis.plotly <- function(
p_obj,
x,
distribution = c(
"weibull", "lognormal", "loglogistic", "normal", "logistic", "sev"
),
title_main = "Probability Plot",
title_x = "Characteristic",
title_y = "Unreliability"
) {
distribution <- match.arg(distribution)
layout_helper <- plot_layout_helper(x, distribution, "plotly")
x_axis_type <- if (distribution %in% c("sev", "normal", "logistic")) "-" else "log"
x_config <- list(
title = list(
text = title_x
),
type = x_axis_type,
autorange = TRUE,
rangemode = "nonnegative",
ticks = "inside",
tickwidth = 1,
tickfont = list(family = 'Arial', size = 10),
tickangle = 90,
showticklabels = TRUE,
zeroline = FALSE,
showgrid = TRUE,
gridwidth = 1,
exponentformat = "none",
showline = TRUE,
linecolor = "
)
if (distribution %in% c("weibull", "lognormal", "loglogistic")) {
x_config <- c(
x_config,
list(
tickvals = layout_helper$x_ticks,
ticktext = layout_helper$x_labels
)
)
}
y_config <- list(
title = list(
text = title_y
),
autorange = TRUE,
tickvals = layout_helper$y_ticks,
ticktext = layout_helper$y_labels,
ticks = "inside",
tickwidth = 1,
tickfont = list(family = 'Arial', size = 10),
showticklabels = TRUE,
zeroline = FALSE,
showgrid = TRUE,
gridwidth = 1,
exponentformat = "none",
showline = TRUE,
linecolor = "
)
l <- list(
title = list(
font = list(
family = "Arial",
size = 10,
color = "
)
)
)
m <- list(
l = 55,
r = 10,
b = 55,
t = 25,
pad = 4
)
title <- list(
text = title_main,
font = list(
family = "Arial",
size = 16,
color = "
)
)
p_obj <- p_obj %>%
plotly::layout(
title = title,
separators = ".",
legend = l,
xaxis = x_config,
yaxis = y_config,
margin = m
)
return(p_obj)
}
plot_prob_vis.plotly <- function(
p_obj, tbl_prob,
distribution = c(
"weibull", "lognormal", "loglogistic", "normal", "logistic", "sev"
),
title_main = "Probability Plot",
title_x = "Characteristic",
title_y = "Unreliability",
title_trace = "Sample"
) {
distribution <- match.arg(distribution)
mark_x <- unlist(strsplit(title_x, " "))[1]
mark_y <- unlist(strsplit(title_y, " "))[1]
n_group <- length(unique(tbl_prob[["group"]]))
n_method <- length(unique(tbl_prob$cdf_estimation_method))
color <- if (n_method == 1) I("
symbol <- if (n_group == 0) NULL else ~group
name <- to_name(tbl_prob, n_method, n_group, title_trace)
p_prob <- p_obj %>%
plotly::add_trace(
data = tbl_prob,
x = ~x,
y = ~q,
type = "scatter",
mode = "markers",
hoverinfo = "text",
name = name,
color = color,
colors = "Set2",
symbol = symbol,
legendgroup = ~cdf_estimation_method,
text = paste(
"ID:", tbl_prob$id,
paste("<br>", paste0(mark_x, ":")), format(tbl_prob$x, digits = 3),
paste("<br>", paste0(mark_y, ":")), format(tbl_prob$prob, digits = 6)
)
) %>%
plotly::layout(showlegend = TRUE)
return(p_prob)
}
plot_mod_vis.plotly <- function(
p_obj, tbl_pred, title_trace = "Fit"
) {
x_mark <- unlist(strsplit(p_obj$x$layoutAttrs[[2]]$xaxis$title$text, " "))[1]
y_mark <- unlist(strsplit(p_obj$x$layoutAttrs[[2]]$yaxis$title$text, " "))[1]
tbl_pred <- tbl_pred %>%
dplyr::rowwise() %>%
dplyr::mutate(hovertext = to_hovertext(
.data$x_p, .data$y_p, .data$param_val, .data$param_label, x_mark, y_mark
)) %>%
dplyr::ungroup()
n_method <- length(unique(tbl_pred$cdf_estimation_method))
n_group <- length(unique(tbl_pred$group))
color <- if (n_method == 1) I("
name <- to_name(tbl_pred, n_method, n_group, title_trace)
p_mod <- plotly::add_lines(
p = p_obj,
data = tbl_pred,
x = ~x_p,
y = ~q,
type = "scatter",
mode = "lines",
hoverinfo = "text",
name = name,
color = color,
colors = "Set2",
legendgroup = ~cdf_estimation_method,
text = ~hovertext
)
return(p_mod)
}
plot_conf_vis.plotly <- function(p_obj, tbl_p, title_trace) {
x_mark <- unlist(strsplit(p_obj$x$layoutAttrs[[2]]$xaxis$title$text, " "))[1]
y_mark <- unlist(strsplit(p_obj$x$layoutAttrs[[2]]$yaxis$title$text, " "))[1]
n_method <- length(unique(tbl_p$cdf_estimation_method))
color <- if (n_method == 1) I("
name <- to_name(tbl_p, n_method, n_group = 0, title_trace)
p_conf <- plotly::add_lines(
p = p_obj,
data = tbl_p,
x = ~x, y = ~q,
type = "scatter", mode = "lines",
hoverinfo = "text",
line = list(dash = "dash", width = 1),
color = color,
colors = "Set2",
name = name,
legendgroup = ~cdf_estimation_method,
text = paste(
paste0(x_mark, ":"),
format(tbl_p$x, digits = 3),
paste("<br>", paste0(y_mark, ":")),
format(tbl_p$y, digits = 6)
)
)
return(p_conf)
}
plot_pop_vis.plotly <- function(
p_obj, tbl_pop, title_trace
) {
x_mark <- unlist(strsplit(p_obj$x$layoutAttrs[[2]]$xaxis$title$text, " "))[1]
y_mark <- unlist(strsplit(p_obj$x$layoutAttrs[[2]]$yaxis$title$text, " "))[1]
tbl_pop <- tbl_pop %>%
dplyr::rowwise() %>%
dplyr::mutate(
hovertext = to_hovertext(
.data$x_s, .data$y_s, .data$param_val, .data$param_label, x_mark, y_mark
),
name = to_name_pop(
.data$param_val, .data$param_label
)
) %>%
dplyr::ungroup()
p_pop <- plotly::add_lines(
p = p_obj, data = tbl_pop,
x = ~x_s, y = ~q,
type = "scatter",
mode = "lines",
hoverinfo = "text",
colors = "Set2",
name = ~name,
line = list(width = 1),
text = ~hovertext
) %>%
plotly::layout(showlegend = TRUE)
return(p_pop)
}
to_hovertext <- function(x, y, param_val, param_label, x_mark, y_mark) {
param_val <- unlist(param_val)
param_label <- unlist(param_label)
text <- paste(
paste0(x_mark, ":"),
format(x, digits = 3),
paste("<br>", paste0(y_mark, ":")),
format(y, digits = 6),
"<br>",
paste(param_label[1], param_val[1]),
"<br>",
paste(param_label[2], param_val[2])
)
if (!is.na(param_val[3])) {
text <- paste(
text,
"<br>",
paste(param_label[3], param_val[3])
)
}
text
}
to_name_pop <- function(param_val, param_label) {
param_val <- unlist(param_val)
param_label <- unlist(param_label)
text <- paste0(
param_label[1], " ",
param_val[1], ", ",
param_label[2], " ",
param_val[2]
)
if (!is.na(param_val[3])) {
text <- paste0(
text, ", ",
param_label[3], " ",
param_val[3]
)
}
text
}
to_name <- function(tbl, n_method, n_group, title_trace) {
if (n_method <= 1) {
if (n_group <= 1) {
title_trace
} else {
paste0(title_trace, ": ", tbl$group)
}
} else {
if (n_group <= 1) {
paste0(title_trace, ": ", tbl$cdf_estimation_method)
} else {
paste0(title_trace, ": ", tbl$cdf_estimation_method, ", ", tbl$group)
}
}
} |
EMMax.p <-
function(Z, w, p, ptype) {
switch(ptype,
p.free = apply(Z,2,weighted.mean, w),
p.fixed = p,
p.HW = EMMax.p.HW(Z,w),
p.part = apply(Z,2,weighted.mean, w) )
} |
test_that("stops on failure", {
withr::local_envvar(TESTTHAT_PARALLEL = "FALSE")
expect_error(
test_dir(test_path("test_dir"), reporter = "silent")
)
})
test_that("runs all tests and records output", {
withr::local_envvar(TESTTHAT_PARALLEL = "FALSE")
res <- test_dir(test_path("test_dir"), reporter = "silent", stop_on_failure = FALSE)
df <- as.data.frame(res)
df$user <- df$system <- df$real <- df$result <- NULL
local_reproducible_output(width = 200)
local_edition(3)
expect_snapshot_output(print(df))
})
test_that("complains if no files", {
withr::local_envvar(TESTTHAT_PARALLEL = "FALSE")
path <- tempfile()
dir.create(path)
expect_error(test_dir(path), "test files")
})
test_that("can control if failures generate errors", {
withr::local_envvar(TESTTHAT_PARALLEL = "FALSE")
test_error <- function(...) {
test_dir(test_path("test-error"), reporter = "silent", ...)
}
expect_error(test_error(stop_on_failure = TRUE), "Test failures")
expect_error(test_error(stop_on_failure = FALSE), NA)
})
test_that("can control if warnings errors", {
withr::local_envvar(TESTTHAT_PARALLEL = "FALSE")
test_warning <- function(...) {
test_dir(test_path("test-warning"), reporter = "silent", ...)
}
expect_error(test_warning(stop_on_warning = TRUE), "Tests generated warnings")
expect_error(test_warning(stop_on_warning = FALSE), NA)
})
test_that("can test single file", {
out <- test_file(test_path("test_dir/test-basic.R"), reporter = "silent")
expect_length(out, 5)
})
test_that("complains if file doesn't exist", {
expect_error(test_file("DOESNTEXIST"), "does not exist")
})
test_that("files created by setup still exist", {
expect_true(file.exists("DELETE-ME"))
expect_true(file.exists("DELETE-ME-2"))
})
test_that("can filter test scripts", {
x <- c("test-a.R", "test-b.R", "test-c.R")
expect_equal(filter_test_scripts(x), x)
expect_equal(filter_test_scripts(x, "a"), x[1])
expect_equal(filter_test_scripts(x, "a", invert = TRUE), x[-1])
expect_equal(filter_test_scripts(x, "test"), character())
expect_equal(filter_test_scripts(x, ".R"), character())
}) |
source("ex4.01.R")
source("ex4.02.R")
source("ex4.03.R")
source("ex4.04.R")
source("ex4.05.R")
source("ex4.06.R")
source("ex4.07.R") |
mt <- mtcars[c("mpg", "hp", "wt", "am")]
head(mt)
mt <- mtcars[c("mpg", "hp", "wt", "am")]
summary(mt)
mystats <- function(x, na.omit=FALSE){
if (na.omit)
x <- x[!is.na(x)]
m <- mean(x)
n <- length(x)
s <- sd(x)
skew <- sum((x-m)^3/s^3)/n
kurt <- sum((x-m)^4/s^4)/n - 3
return(c(n=n, mean=m, stdev=s, skew=skew, kurtosis=kurt))
}
myvars <- c("mpg", "hp", "wt")
sapply(mtcars[myvars], mystats)
library(Hmisc)
myvars <- c("mpg", "hp", "wt")
describe(mtcars[myvars])
library(pastecs)
myvars <- c("mpg", "hp", "wt")
stat.desc(mtcars[myvars])
library(psych)
myvars <- c("mpg", "hp", "wt")
describe(mtcars[myvars])
myvars <- c("mpg", "hp", "wt")
aggregate(mtcars[myvars], by=list(am=mtcars$am), mean)
aggregate(mtcars[myvars], by=list(am=mtcars$am), sd)
dstats <- function(x)sapply(x, mystats)
myvars <- c("mpg", "hp", "wt")
by(mtcars[myvars], mtcars$am, dstats)
library(doBy)
summaryBy(mpg+hp+wt~am, data=mtcars, FUN=mystats)
library(psych)
myvars <- c("mpg", "hp", "wt")
describeBy(mtcars[myvars], list(am=mtcars$am))
library(reshape)
dstats <- function(x)(c(n=length(x), mean=mean(x), sd=sd(x)))
dfm <- melt(mtcars, measure.vars=c("mpg", "hp", "wt"),
id.vars=c("am", "cyl"))
cast(dfm, am + cyl + variable ~ ., dstats)
library(vcd)
head(Arthritis)
mytable <- with(Arthritis, table(Improved))
mytable
prop.table(mytable)
prop.table(mytable)*100
mytable <- xtabs(~ Treatment+Improved, data=Arthritis)
mytable
margin.table(mytable,1)
margin.table(mytable, 2)
prop.table(mytable)
prop.table(mytable, 1)
prop.table(mytable, 2)
addmargins(mytable)
addmargins(prop.table(mytable))
addmargins(prop.table(mytable, 1), 2)
addmargins(prop.table(mytable, 2), 1)
library(gmodels)
CrossTable(Arthritis$Treatment, Arthritis$Improved)
mytable <- xtabs(~ Treatment+Sex+Improved, data=Arthritis)
mytable
ftable(mytable)
margin.table(mytable, 1)
margin.table(mytable, 2)
margin.table(mytable, 2)
margin.table(mytable, c(1,3))
ftable(prop.table(mytable, c(1,2)))
ftable(addmargins(prop.table(mytable, c(1, 2)), 3))
library(vcd)
mytable <- xtabs(~Treatment+Improved, data=Arthritis)
chisq.test(mytable)
mytable <- xtabs(~Improved+Sex, data=Arthritis)
chisq.test(mytable)
mytable <- xtabs(~Treatment+Improved, data=Arthritis)
fisher.test(mytable)
mytable <- xtabs(~Treatment+Improved+Sex, data=Arthritis)
mantelhaen.test(mytable)
library(vcd)
mytable <- xtabs(~Treatment+Improved, data=Arthritis)
assocstats(mytable)
states<- state.x77[,1:6]
cov(states)
cor(states)
cor(states, method="spearman")
x <- states[,c("Population", "Income", "Illiteracy", "HS Grad")]
y <- states[,c("Life Exp", "Murder")]
cor(x,y)
library(ggm)
pcor(c(1,5,2,3,6), cov(states))
cor.test(states[,3], states[,5])
library(psych)
corr.test(states, use="complete")
library(MASS)
t.test(Prob ~ So, data=UScrime)
sapply(UScrime[c("U1","U2")], function(x)(c(mean=mean(x),sd=sd(x))))
with(UScrime, t.test(U1, U2, paired=TRUE))
with(UScrime, by(Prob, So, median))
wilcox.test(Prob ~ So, data=UScrime)
sapply(UScrime[c("U1", "U2")], median)
with(UScrime, wilcox.test(U1, U2, paired=TRUE))
states <- data.frame(state.region, state.x77)
kruskal.test(Illiteracy ~ state.region, data=states)
source("http://www.statmethods.net/RiA/wmc.txt")
states <- data.frame(state.region, state.x77)
wmc(Illiteracy ~ state.region, data=states, method="holm") |
funOptimizeSim <- function(x, conf, data, ...) {
para <- mapXToPara(x)
res <- modelResultHospital(para = para, conf = conf, data = data)
err <- getError(res = res, conf = conf)
if (conf$verbosity > 1000){
print(x)
str(para)
str(res)
}
if (conf$verbosity > 10) {
print(paste0("Err:", err))
}
return(err)
} |
plotExpSpace <- function(expSpace,
y = expSpace[["attPerturb"]][1],
x = expSpace[["attPerturb"]][2]
){
targetMat <- expSpace[["targetMat"]]
targetAtts <- colnames(expSpace[["targetMat"]])
x.no <- which(targetAtts == x)
y.no <- which(targetAtts == y)
xUnits <- getVarUnits(strsplit(x, "_")[[1]][1])
yUnits <- getVarUnits(strsplit(y, "_")[[1]][1])
xyFullNames <- mapply(tagBlender_noUnits, c(x,y))
y.lab <- paste0(xyFullNames[2], " (", yUnits, ")")
x.lab <- paste0(xyFullNames[1], " (", xUnits, ")")
out <- expSpace2dViz(targetMat[ ,x.no], targetMat[ ,y.no], x.lab = x.lab, y.lab = y.lab)
} |
reject<- function(sorted, criticals){
m<- length(sorted)
stopifnot( length(criticals) == m )
indicators<- sorted<criticals
if(!any(indicators)) {
return(list(cutoff=0,cut.index=0))
}
cut.index<- max((1:m)[indicators])
cutoff<- sorted[cut.index]
return( list(cutoff=cutoff,cut.index=cut.index) )
}
bh.adjust<- function(sorted, m, m0, constant=1){
adjusted<- rep(NA,m)
temp.min<- sorted[m]
min.ind<- rep(0,m)
for (i in m:1) {
temp<- min(m0*sorted[i]*constant / i, 1)
if ( temp <= temp.min ) {
temp.min <- temp
min.ind[i]<- 1
}
adjusted[i]<- temp.min
}
return(adjusted)
}
linearStepUp<- function(sorted, q, m, adjust=FALSE, m0=m, pi0, constant=1){
if(missing(m0) & !missing(pi0)) {
m0=pi0*m
}
else{
criticals<- (1:m)*q/(m0*constant)
cutoff<- reject(sorted,criticals)
rejected<- sorted<=cutoff$cutoff
adjusted=rep(NA,m)
if(adjust) {
adjusted<-bh.adjust(sorted,m=m,m0=m0,constant=constant)
}
multiple.pvals<- data.frame(
original.pvals=sorted,
criticals=criticals,
rejected=rejected,
adjusted.pvals=adjusted)
output<- list(Cutoff=cutoff,Pvals=multiple.pvals)
return(output)
}
}
solve.q<- function(sorted, m, j, r){
a<- sorted*(m-r)/(1:m)
adjusted<- ifelse(a>0.5, 1 , a/(1-a) )
temp.min<- adjusted[m]
for(i in m:j){
if(adjusted[i]<=temp.min) temp.min<- adjusted[i]
else adjusted[i]<- temp.min
}
return(adjusted)
}
two.stage.adjust<- function(sorted, r=0, patience=4, m){
adjusted<- rep(0,m)
adjusted.q<- solve.q(sorted=sorted,m=m,j=1,r=0)
checking<- adjusted.q
if(sum(linearStepUp(sorted,adjusted.q[1]/(1+adjusted.q[1]),m=m)$Pvals[['rejected']])==m){
adjusted.q<- rep(adjusted.q[1],m)
return(adjusted.q)
}
else{
for (j in 1:m) {
delta.r<- 1
delta.q<- 1
new.q<- adjusted.q[j]
r.new<- sum(linearStepUp(sorted,new.q/(1+new.q),m=m)$Pvals[['rejected']])
counter<- 0
max.q<- 0
while(delta.r>0 & delta.q>0){
old.q<- new.q
r.old<- r.new
new.q<- solve.q(sorted=sorted,m=m,j=j,r=r.old)[j]
r.new<- sum(linearStepUp(sorted,new.q/(1+new.q),m=m)$Pvals[['rejected']])
delta.r<- abs(r.new-r.old)
delta.q<- abs(new.q-old.q)
counter<- counter+1
if(counter>patience & max.q!=new.q) max.q<- max(max.q,new.q)
else if(counter>patience & max.q==new.q ) break
}
adjusted.q[j]<- min(new.q,1)
adjusted.q[min(j+1,m)]<- adjusted.q[j]
stopifnot(any(adjusted.q[j]<=checking[j]))
}
temp.min<- adjusted.q[m]
for(i in m:1){
if(adjusted.q[i]<=temp.min) temp.min<- adjusted.q[i]
else adjusted.q[i]<- temp.min
}
return(adjusted.q)
}
}
two.stage<- function(pValues, alpha){
ranks<- rank(pValues)
sorted<-sort(pValues)
m<- length(sorted)
q1<- alpha/(1+alpha)
stage.one<- linearStepUp(sorted, q1, adjust=TRUE, m=m)
r<- sum(stage.one$Pvals[['rejected']])
if (r==0) {
stage.one$Pvals[['adjusted.pvals']]<- 1
return(stage.one)
}
else if (r==m) {
stage.one$Pvals[['adjusted.pvals']]<- stage.one$Pvals[['adjusted.pvals']][1]
return(stage.one)
}
else {
m0<- m-r
output<- linearStepUp(sorted=sorted,q=q1,m0=m0,m=m)
output$Pvals[['adjusted.pvals']]<- two.stage.adjust(sorted, alpha, m=m)
output<-output$Pvals[ranks,]
output.2<- list(
criticalValues=output$criticals,
rejected=output$rejected,
adjPValues=output$adjusted.pvals,
errorControl=new(Class='ErrorControl',type="FDR",alpha=alpha),
pi0= m0/m
)
return(output.2)
}
}
mutoss.two.stage<- function() { return(new(Class="MutossMethod",
label="B.K.Y. (2006) Two-Stage Step-Up",
errorControl="FDR",
callFunction="two.stage",
output=c("adjPValues", "criticalValues", "rejected", "pi0", "errorControl"),
assumptions=c("Independent test statistics"),
info="<h2>Benjamini-Krieger-Yekutieli (2006) Two-Stage Step-Up Procedure</h2>\n\n
<p>A p-value procedure which controls the FDR at level <i>α</i> for independent test statistics, in which case it is more powerful then non adaptive procedures such as the Linear Step-Up (BH). On the other hand, when this is not the case, no error control is guaranteed.
The linear step-up procedure is used in he first stage to estimate the number of true null hypotheses (mo) which is plugged in a linear step-up
procedure at the second stage.
<h3>Reference:</h3>
<ul>
<li>Benjamini, Y., Krieger, A. and Yekutieli, D. \"<i> Adaptive linear step-up procedures that control the false
discovery rate. </i>\" Biometrika, 93(3):491-507, 2006. </li>\n
</ul>",
parameters=list(pValues=list(type="numeric"), alpha=list(type="numeric"))
)) }
multiple.down.adjust<- function(sorted, m){
adjusted<- rep(NA,m)
temp.max<- sorted[1]
max.ind<- rep(0,m)
for (i in 1:m) {
temp<- min(sorted[i]*(m+1-i)/(i*(1-sorted[i])),1)
if ( temp >= temp.max ) {
temp.max <- temp
max.ind[i] <- 1
}
adjusted[i]<- temp.max
}
return(adjusted)
}
multiple.down=function(pValues, alpha){
sorted<- sort(pValues)
ranks<- rank(pValues)
m<- length(pValues)
if(alpha>0.5) warning('FDR is not controlled when q>0.5')
criticals<- sapply(1:m,function(i) alpha*i/(m-i*(1-alpha)+1))
indicators<- sorted<criticals
if(!indicators[1]) cutoff<-list(cutoff=0,cut.index=0)
else if(all(indicators)) cutoff<- list(cutoff=sorted[m],cut.index=m)
else{
cut.index<- min((1:m)[!indicators])-1
cutoff<- list(cutoff=sorted[cut.index],cut.index=cut.index)
}
rejected<- sorted<=cutoff$cutoff
adjusted<-multiple.down.adjust(sorted,m)
output<- data.frame(
criticals=criticals,
rejected=rejected,
adjusted.pvals=adjusted)
output<- output[ranks,]
output.2<-list(
criticalValues=output$criticals,
rejected=output$rejected,
adjPValues=output$adjusted.pvals,
errorControl=new(Class='ErrorControl',type="FDR",alpha=alpha)
)
return(output.2)
}
mutoss.multiple.down <- function() { return(new(Class="MutossMethod",
label="B.K.Y. (2006) Multi-Stage Step-down",
errorControl="FDR",
callFunction="multiple.down",
output=c("adjPValues", "criticalValues", "rejected", "errorControl"),
assumptions=c("Independent test statistics"),
info="<h2>Benjamini-Krieger-Yekutieli (2006) multi-stage step-down procedure</h2>\n\n\
<p>A non-linear step-down p-value procedure which control the FDR for independent test statistics and enjoys more power then other non-adaptive procedure such as the linear step-up (BH).
For the case of non-independent test statistics, non-adaptive procedures such as the linear step-up (BH) or the all-purpose conservative Benjamini-Yekutieli (2001) are recommended.</p>\n
<h3>Reference:</h3>
<ul>
<li>Benjamini, Y., Krieger, A. and Yekutieli, D. \"<i> Adaptive linear step-up procedures that control the false
discovery rate. </i>\" Biometrika, 93(3):491-507, 2006. </li>\n
</ul>",
parameters=list(pValues=list(type="numeric"), alpha=list(type="numeric"))
)) } |
install_keras <- function(method = c("auto", "virtualenv", "conda"),
conda = "auto",
version = "default",
tensorflow = version,
extra_packages = NULL,
...,
pip_ignore_installed = TRUE) {
method <- match.arg(method)
if(is_mac_arm64()) {
return(tensorflow::install_tensorflow(
method = method,
conda = conda,
version = version,
extra_packages = c("pandas", "Pillow",
"tensorflow-hub",
"tensorflow-datasets",
extra_packages),
...))
}
pkgs <- default_extra_packages(tensorflow)
if(!is.null(extra_packages))
pkgs[gsub("[=<>~]{1,2}[0-9.]+$", "", extra_packages)] <- extra_packages
if(tensorflow %in% c("cpu", "gpu"))
tensorflow <- paste0("default-", tensorflow)
if(grepl("^default", tensorflow))
tensorflow <- sub("^default", as.character(default_version), tensorflow)
tensorflow::install_tensorflow(
method = match.arg(method),
conda = conda,
version = tensorflow,
extra_packages = pkgs,
pip_ignore_installed = pip_ignore_installed,
...
)
}
default_version <- numeric_version("2.8")
default_extra_packages <- function(tensorflow_version) {
pkgs <- c("tensorflow-hub", "scipy", "requests", "pyyaml", "Pillow", "h5py", "pandas")
names(pkgs) <- pkgs
v <- tensorflow_version
if(grepl("nightly", v))
return(pkgs)
v <- sub("-?(gpu|cpu)$", "", v)
v <- sub("rc[0-9]+", "", v)
constraint <- sub("^([><=~]{,2}).*", "\\1", v)
v <- substr(v, nchar(constraint)+1, nchar(v))
if(v %in% c("default", ""))
v <- default_version
v <- numeric_version(v)
if(nzchar(constraint)) {
l <- length(unclass(v)[[1]])
switch(constraint,
">" = v[[1, l + 1]] <- 1,
"<" = {
v <- unclass(v)[[1]]
if(v[l] == 0) l <- l-1
v[c(l, l+1)] <- c(v[l] - 1, 9999)
v <- numeric_version(paste0(v, collapse = "."))
},
"~=" = v[[1, l]] <- 9999)
}
if (v >= "2.6") {
pkgs <- pkgs[names(pkgs) != "pyyaml"]
return(pkgs)
}
if (v >= "2.4") {
pkgs["Pillow"] <- "Pillow<8.3"
return(pkgs)
}
if (v >= "2.1") {
pkgs["pyyaml"] <- "pyyaml==3.12"
pkgs["h5py"] <- "h5py==2.10.0"
return(pkgs)
}
pkgs
} |
library(ggvis)
data(diamonds, package = "ggplot2")
shinyServer(function(input, output, session) {
values <- reactiveValues(selected = rep(TRUE, nrow(diamonds)))
diamonds %>% ggvis(~carat) %>%
layer_histograms(fill.hover := "red", width = 0.1) %>%
handle_hover(function(data, ...) {
values$selected <- diamonds$carat >= data$xmin_ &
diamonds$carat < data$xmax_
}) %>%
set_options(width = 400, height = 200) %>%
bind_shiny("plot1")
reactive(diamonds[values$selected, , drop = FALSE]) %>%
ggvis(~carat) %>%
layer_histograms(width = 0.01) %>%
set_options(width = 400, height = 200) %>%
bind_shiny("plot2")
}) |
set_serialAxes_scales_grob <- function(loon.grob, pointsTreeName,
glyphNames, showAxes,
swap, whichIsDeactive) {
newGrob <- grid::getGrob(loon.grob, pointsTreeName)
serialaxes_and_active <- setdiff(which(grepl(glyphNames, pattern = "serialaxes")), whichIsDeactive)
if(length(serialaxes_and_active) > 0) {
lapply(serialaxes_and_active,
function(i) {
serialaxes_tree <- newGrob$children[[i]]
axesGrob <- grid::getGrob(serialaxes_tree, "axes")
if(is.null(axesGrob)) {
axesGrob <- grid::getGrob(serialaxes_tree, "axes: polylineGrob arguments")
axesGrob_name <- "axes: polylineGrob arguments"
} else {
axesGrob_name <- "axes"
}
newGrob$children[[i]] <<- if(showAxes) {
grid::setGrob(
gTree = newGrob$children[[i]],
gPath = axesGrob_name,
newGrob = do.call(
grid::polylineGrob,
args = getGrobArgs(axesGrob)
)
)
} else {
grid::setGrob(
gTree = newGrob$children[[i]],
gPath = axesGrob_name,
newGrob = do.call(
grob,
args = getGrobArgs(axesGrob)
)
)
}
if(swap & showAxes) {
newGrob$children[[i]] <<- grid::setGrob(
gTree = newGrob$children[[i]],
gPath = axesGrob_name,
newGrob = grid::editGrob(
grob = grid::getGrob(newGrob$children[[i]], axesGrob_name),
y = get_unit(axesGrob$x, as.numeric = FALSE) +
get_unit(axesGrob$y, is.unit = FALSE, as.numeric = FALSE),
x = get_unit(axesGrob$y, as.numeric = FALSE) +
get_unit(axesGrob$x, is.unit = FALSE, as.numeric = FALSE)
)
)
}
}
)
} else NULL
grid::setGrob(
gTree = loon.grob,
gPath = pointsTreeName,
newGrob = newGrob
)
} |
setBlur <- function(intensity = 2) {
css <- paste0(
"* {
margin: 0;
padding: 0;
overflow: hidden;
}
.blur {
-webkit-transition: all .25s ease;
-moz-transition: all .25s ease;
-o-transition: all .25s ease;
-ms-transition: all .25s ease;
transition: all .25s ease;
}
.blur:hover {
-webkit-filter: blur(15px);
-moz-filter: all .25s ease;
-o-filter: all .25s ease;
-ms-filter: all .25s ease;
filter: blur(", intensity, "px);
}
"
)
htmltools::tags$head(
htmltools::tags$style(css)
)
}
blurContainer <- function(tag) {
if (length(tag) == 2) {
tag[[2]]$attribs$class <- paste0(tag[[2]]$attribs$class, " blur")
return(tag)
} else {
tag$attribs$class <- paste0(tag$attribs$class, " blur")
return(tag)
}
} |
library("Mercator")
data("CML500")
CML500 <- removeDuplicateFeatures(CML500)
vis1 <- Mercator(CML500, "jacc", "mds", K=8)
vis2 <- Mercator(CML500, "sokal", "mds", K=8)
vis3 <- remapColors(vis1, vis2)
plot(vis1)
plot(vis2)
plot(vis3)
A <- getClusters(vis2)
B <- getClusters(vis3)
table(A, B)
X <- getClusters(vis1)
table(A, X)
table(B, X)
library(cluster)
clus <- pam(vis1@distance, k = 12, diss=TRUE, cluster.only=TRUE)
vis4 <- setClusters(vis1, clus)
plot(vis4)
slot(vis4, "palette") <- c("red", "green", "blue",
"cyan", "purple", "black")
table(Mercator:::symv(vis4)) |
extract_mod <- function(result, dim = 1:2){
coord.mod <- result$coord.mod[, dim]
rownames(coord.mod) <- result$names.mod
coord.mod <- coord.mod[,]
colnames(coord.mod) <- c("X", "Y")
md <- coord.mod %>% data.frame() %>% tibble::rownames_to_column(var = "Modality")
ctr <- result$ctr.mod[, dim]
md$ctr.x <- ctr[, 1]
md$ctr.y <- ctr[, 2]
md$ctr <- rowSums(ctr) / 2
md$ctr.set <- (apply(ctr, 2, function(x) x >= mean(x)) %>% rowSums()) > 0
md$Frequency <- result$freq.mod
md$Variable <- result$variable
md
}
extract_sup <- function(result, dim = 1:2){
coord.sup <- result$coord.sup[, dim]
rownames(coord.sup) <- result$names.sup
coord.sup <- coord.sup[,]
colnames(coord.sup) <- c("X", "Y")
md <- coord.sup %>% data.frame() %>% rownames_to_column(var = "Modality")
md$Frequency <- result$freq.sup
md$Variable <- result$variable.sup
md
}
extract_ind <- function(result, dim = 1:2){
coord.ind <- result$coord.ind[, dim]
rownames(coord.ind) <- result$names.ind
coord.ind <- coord.ind[,]
colnames(coord.ind) <- c("X", "Y")
md <- coord.ind %>% data.frame() %>% rownames_to_column(var = "Individual")
ctr <- result$ctr.ind[, dim]
md$ctr.x <- ctr[, 1]
md$ctr.y <- ctr[, 2]
md$ctr <- rowSums(ctr) / 2
md$ctr.set <- (apply(ctr, 2, function(x) x >= mean(x)) %>% rowSums()) > 0
md
}
map.ca.base <- function(up = NULL, down = NULL, right = NULL, left = NULL, ...){
breaks.major <- seq(-100, 100, by = 0.25)
labels <- breaks.major
labels[c(FALSE, TRUE)] <- ""
p <- ggplot(...) + geom_vline(xintercept = 0, size = 0.2) + geom_hline(yintercept = 0, size = 0.2)
p <- p + scale_x_continuous(sec.axis = sec_axis(~.*1, name = up, breaks = breaks.major, labels = labels),
name = down, breaks = breaks.major, labels = labels)
p <- p + scale_y_continuous(sec.axis = sec_axis(~.*1, name = right, breaks = breaks.major, labels = labels),
name = left, breaks = breaks.major, labels = labels)
p <- p + theme(axis.title.y.left = element_text(size = 16), axis.title.y.right = element_text(size = 16))
p <- p + theme(axis.title.x.top = element_text(size = 16), axis.title.x.bottom = element_text(size = 16))
theme_ca_base <- function (base_size = 15, base_family = "serif", ticks = TRUE)
{
ret <- theme_bw(base_family = base_family, base_size = base_size) +
theme(legend.background = element_blank(), legend.key = element_blank(),
panel.background = element_blank(), panel.border = element_blank(),
strip.background = element_blank(), plot.background = element_blank(),
axis.line = element_blank(), panel.grid = element_blank())
if (!ticks) {
ret <- ret + theme(axis.ticks = element_blank())
}
ret
}
p <- p + theme_ca_base()
p <- p + scale_size_continuous(range = c(0.1, 2))
p <- p + theme(legend.position = "bottom")
p
} |
appendGen <- function(ped, M, AF=c(), mut.rate=0) {
if(!identical(as.integer(ped[,1]), 1:nrow(ped))) stop("!identical(as.integer(ped[,1]), 1:nrow(ped)); Please consider renumberring the pedigree: ped[,1:3] <- ggroups::renum(ped[,1:3])$newped")
stopifnot(nrow(M) < nrow(ped))
if(nrow(M)==0) stop("The genotype matrix is empty. Please use function simulateGen.")
colnames(ped) = c("ID","SIRE","DAM")
if(length(AF)==0) {
AF = colMeans(M)
} else {
stopifnot(min(AF)>=0.01)
stopifnot(max(AF)<=0.99)
}
if(!identical(mut.rate, 0)) {
stopifnot(length(AF)==length(mut.rate))
stopifnot(min(mut.rate)>=0)
if(length(mut.rate[mut.rate > 10^-6])) {
warning("Found ", length(mut.rate[mut.rate > 10^-6]), " markers with mutation rate > 10^-6")
warning("Maximum mutation rate = ", max(mut.rate))
}
} else {
message("No mutation was simulated.")
}
tmp = c()
SNPs = 1:length(AF)
for(i in (nrow(M)+1):nrow(ped))
{
s = ped$SIRE[i]
d = ped$DAM[i]
tmp = c()
if(s==0 & d==0) {
for(j in SNPs) tmp = c(tmp, sample(0:2, 1, prob=c((1-AF[j])^2, 2*(1-AF[j])*AF[j], AF[j]^2)))
} else if(s>0 & d==0) {
for(j in SNPs) tmp = c(tmp, sample(0:1, 1, prob=c(1-AF[j], AF[j])))
tmp = tmp+makegamete(M[s,])
} else if(s==0 & d>0) {
for(j in SNPs) tmp = c(tmp, sample(0:1, 1, prob=c(1-AF[j], AF[j])))
tmp = tmp+makegamete(M[d,])
} else {
tmp = makegamete(M[s,])+makegamete(M[d,])
}
if(!identical(mut.rate, 0)) tmp = mutate(tmp, mut.rate)
M = rbind(M, tmp)
rownames(M) = NULL
}
return(M)
} |
test_that("get_outcome_type works", {
expect_equal(get_outcome_type(c(1, 2, 1)), "continuous")
expect_equal(get_outcome_type(c("a", "b", "b")), "binary")
expect_equal(get_outcome_type(c("a", "b", "c")), "multiclass")
})
test_that("get_outcome_type errors when num_outcomes < 2", {
error_msg <- "A continuous, binary, or multi-class outcome variable is required, but this dataset has "
expect_error(
get_outcome_type(c(1, 1)),
error_msg
)
expect_error(
get_outcome_type(c("a", "a", "a")),
error_msg
)
expect_error(
get_outcome_type(c()),
error_msg
)
})
test_that("get_perf_metric_fn works", {
expect_equal(get_perf_metric_fn("continuous"), caret::defaultSummary)
expect_equal(get_perf_metric_fn("binary"), caret::multiClassSummary)
expect_equal(get_perf_metric_fn("multiclass"), caret::multiClassSummary)
expect_error(get_perf_metric_fn("asdf"), "Outcome type of outcome must be one of:")
})
test_that("get_perf_metric_name works", {
expect_equal(get_perf_metric_name("continuous"), "RMSE")
expect_equal(get_perf_metric_name("binary"), "AUC")
expect_equal(get_perf_metric_name("multiclass"), "logLoss")
expect_error(get_perf_metric_name("asdf"), "Outcome type of outcome must be one of:")
})
test_that("calc_perf_metrics works", {
expect_equal(
calc_perf_metrics(otu_mini_bin_results_glmnet$test_data,
otu_mini_bin_results_glmnet$trained_model,
"dx",
caret::multiClassSummary,
class_probs = TRUE
),
unlist(c(otu_mini_bin_results_glmnet$performance[, !(colnames(otu_mini_bin_results_glmnet$performance) %in% c("cv_metric_AUC", "method", "seed"))]))
)
})
test_that("get_performance_tbl works", {
set.seed(2019)
expect_equal(
get_performance_tbl(
otu_mini_bin_results_glmnet$trained_model,
otu_mini_bin_results_glmnet$test_data,
"dx",
caret::multiClassSummary,
"AUC",
TRUE,
"glmnet",
seed = 2019
),
otu_mini_bin_results_glmnet$performance
)
expect_warning(get_performance_tbl(
otu_mini_bin_results_glmnet$trained_model,
otu_mini_bin_results_glmnet$test_data,
"dx",
caret::multiClassSummary,
"not_a_perf_metric",
TRUE,
"glmnet",
seed = 2019
), "The performance metric provided does not match the metric used to train the data.")
}) |
library(knotR)
filename <- "reefknot.svg"
a <- reader(filename)
Mhor <- matrix(c(
17,1,
16,2,
18,32,
15,3,
19,31,
24,26,
23,27,
14,4,
22,28,
13,5,
22,28,
12,6,
21,29,
11,7,
20,30,
10,8,
19,31,
18,32
),ncol=2,byrow=TRUE)
Mver <- matrix(c(
16,18,
23,11,
22,12,
24,10,
15,19,
3,31,
14,20,
13,21,
3,31,
25,9,
4,30,
5,29,
26,8,
27,7,
28,6,
2,32
),ncol=2,byrow=TRUE)
xver <- c(1,17)
xhor <- c(25,9)
symobjreef <- symmetry_object(a, Mver=Mver,Mhor=Mhor,xver=xver, xhor=xhor,reefknot=TRUE)
a <- symmetrize(a,symobjreef)
oureef <- matrix(c(
20, 10,
13, 22,
25, 15,
26, 04,
06, 29,
31, 09
),ncol=2,byrow=TRUE)
jj <- knotoptim(filename,
symobj = symobjreef,
ou = oureef,
prob = 0,
iterlim=1000, print.level=2
)
write_svg(jj,filename,safe=FALSE)
dput(jj,file=sub('.svg','.S',filename)) |
rxodeTest({
test_that("Parallel solve vs single vs for", {
TV_CLr <- 6.54
TV_CLnr <- 2.39
TV_Vc <- 95.1
TV_alag <- 0.145
TV_D <- 0.512
TV_Q <- 2.1
TV_Vp <- 23.3
OM_D_normal <- log((128/100)^2+1)
D_trans <- 0.0819
OM_CLr <- log((36.2/100)^2+1)
OM_CLnr <- log((43.6/100)^2+1)
OM_Vc <- log((14.4/100)^2+1)
OM_Q <- log((15.1/100)^2+1)
OM_Vp <- log((37.6/100)^2+1)
OM_CLr_CLnr <- 0.101
OM_CLr_Vc <- 0.0066
rwishart <- function(df, p = nrow(SqrtSigma), Sigma, SqrtSigma = diag(p)) {
if (!missing(Sigma)) {
tmp <- svd(Sigma)
SqrtSigma <- sqrt(tmp$d) * t(tmp$u)
}
if ((Ident <- missing(SqrtSigma)) && missing(p))
stop("either p, Sigma or SqrtSigma must be specified")
Z <- matrix(0, p, p)
diag(Z) <- sqrt(rchisq(p, df:(df - p + 1)))
if (p > 1) {
pseq <- 1:(p - 1)
Z[rep(p * pseq, pseq) + unlist(lapply(pseq, seq))] <- rnorm(p *
(p - 1)/2)
}
if (Ident)
crossprod(Z)
else crossprod(Z %*% SqrtSigma)
}
sample.etas <- function(df, R, n) {
R.inv = solve(df*R)
R0 = chol(.5*(R.inv+t(R.inv)))
R1 = solve(rwishart(df, SqrtSigma=R0))
eta = rxRmvn(n = n, mu= rep(0, nrow(R)), sigma= .5*(R1+t(R1)))
eta
}
set.seed(100)
nsubj <- 200
n.pts.pk <- 300
eta_CLr_CLnr_Vc <- as.data.frame(sample.etas(df = n.pts.pk,
R = lotri({eta_CLr + eta_CLnr + eta_Vc ~
c(OM_CLr,
OM_CLr_CLnr, OM_CLnr,
OM_CLr_Vc, 0, OM_Vc)
}),
n = nsubj))
eta_D_trans <- data.frame(eta_D_normal = rnorm(mean=0,sd=sqrt(OM_D_normal),n=nsubj)) %>%
dplyr::mutate(eta_D = ((exp(eta_D_normal))^D_trans-1)/D_trans)
par.pk <- data.frame(sim.id = seq(nsubj),
D = TV_D * exp(eta_D_trans$eta_D),
CLr = TV_CLr * exp(eta_CLr_CLnr_Vc$eta_CLr),
CLnr = TV_CLnr * exp(eta_CLr_CLnr_Vc$eta_CLnr),
Vc = TV_Vc * exp(eta_CLr_CLnr_Vc$eta_Vc),
Vp = TV_Vp * exp(rnorm(nsubj, 0, sqrt(OM_Vp))),
Q = TV_Q * exp(rnorm(nsubj, 0, sqrt(OM_Q))),
alag = TV_alag)
mod <- RxODE({
CL <- CLr+CLnr
C2 <- central/Vc*1000
all<- central+periph+output
d/dt(central) <- - CL/Vc*central - Q/Vc*central + Q/Vp*periph
d/dt(periph) <- Q/Vc*central - Q/Vp*periph
d/dt(output) <- CL/Vc*central
alag(central) <- alag
dur(central) <- D
})
ev <- et(amt=2,cmt="central",rate=-2,ii=24,addl=4) %>%
et(seq(0,120,0.1))
bar2x <- rxSolve(mod, ev, params=par.pk, cores=2L, returnType="data.frame")
bar1x <- rxSolve(mod, ev, params=par.pk, cores=1L, returnType="data.frame")
expect_equal(bar1x, bar2x)
bar3x <- rxSolve(mod, ev, params=par.pk)
res.all = NULL
for (id in seq(nsubj)) {
ev.new <- eventTable() %>%
add.dosing(dose = 2, nbr.doses = 5, dosing.interval = 24, dur = par.pk$D[par.pk$sim.id == id]) %>%
add.sampling(seq(0,120,0.1))
theta <- c(CLr = par.pk$CLr[par.pk$sim.id == id],
CLnr = par.pk$CLnr[par.pk$sim.id == id],
Vc = par.pk$Vc[par.pk$sim.id == id],
Q = par.pk$Q[par.pk$sim.id == id],
Vp = par.pk$Vp[par.pk$sim.id == id],
alag = par.pk$alag[par.pk$sim.id == id],
D = par.pk$D[par.pk$sim.id == id])
res.id = data.frame(sim.id=id, rxSolve(mod, theta, ev.new, returnType="data.frame"))
expect_equal(theta, unlist(bar3x$params[bar3x$params$sim.id == id, -1]))
row.names(res.id) <- NULL
res2 <- as.data.frame(bar3x[bar3x$sim.id == id,])
row.names(res2) <- NULL
expect_equal(res.id, res2)
res.all = rbind(res.all, res.id)
}
expect_equal(bar2x, res.all)
})
}, test="lvl2") |
IRT.data <- function(object, ...)
{
UseMethod("IRT.data")
}
IRT.data.din <- function( object, ... ){
dat <- object$dat
attr(dat,"weights") <- object$control$weights
attr(dat,"group") <- object$control$group
return(dat)
}
IRT.data.gdina <- IRT.data.din
IRT.data.gdm <- IRT.data.din
IRT.data.mcdina <- IRT.data.din
IRT.data.slca <- IRT.data.din
IRT.data.reglca <- function( object, ... )
{
dat <- object$dat0
attr(dat,"weights") <- object$weights
attr(dat,"group") <- NULL
return(dat)
} |
NULL
iot <- function(config = list()) {
svc <- .iot$operations
svc <- set_config(svc, config)
return(svc)
}
.iot <- list()
.iot$operations <- list()
.iot$metadata <- list(
service_name = "iot",
endpoints = list("*" = list(endpoint = "iot.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "iot.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "iot.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "iot.{region}.sc2s.sgov.gov", global = FALSE)),
service_id = "IoT",
api_version = "2015-05-28",
signing_name = "execute-api",
json_version = "",
target_prefix = ""
)
.iot$service <- function(config = list()) {
handlers <- new_handlers("restjson", "v4")
new_service(.iot$metadata, handlers, config)
} |
cat(switch(Sys.info()[['sysname']], Windows='.win', Linux='', Darwin='.macos')) |
NPtest<-function(obj, n=NULL, method="T1", ...){
dots<-as.list(substitute(list(...)))[-1]
nn<-names(dots)
for (i in seq(along=dots)) assign(nn[i],dots[[i]])
if(!exists("burn_in", inherits = FALSE)) burn_in <- 256
if(!("step" %in% nn)) step<-32
if(!exists("seed", inherits = FALSE)) seed<-0
if(is.null(n)) n <- 500
if(is.matrix(obj) || is.data.frame(obj)){
if (!all(obj %in% 0:1)) stop("Data matrix must be binary, NAs not allowed")
itscor<-colSums(obj)
itcol<-(itscor==0|itscor==nrow(obj))
if (any(itcol)){
cat("The following columns in the data show complete 0/full responses: \n")
cat((1:ncol(obj))[itcol],sep=", ")
cat("\n")
stop("NPtest using these items is meaningless. Delete them first!")
}
obj<-rsampler(obj,rsctrl(burn_in=burn_in, n_eff=n, step=step, seed=seed))
} else if(class(obj)!="RSmpl"){
stop("Input object must be data matrix/data frame or output from RaschSampler")
}
if(exists("RSinfo", inherits = FALSE)) if(get("RSinfo")) summary(obj)
switch(method,
"T1" = T1(obj, ...),
"T1l" = T1l(obj, ...),
"T1m" = T1m(obj, ...),
"Tmd" = Tmd(obj, ...),
"T2" = T2(obj, ...),
"T2m" = T2m(obj, ...),
"T4" = T4(obj, ...),
"T10" = T10(obj, ...),
"T11" = T11(obj, ...),
"Tpbis" = Tpbis(obj, ...),
"MLoef" = MLoef.x(obj, ...),
"Q3h" = Q3h(obj, ...),
"Q3l" = Q3l(obj, ...)
)
}
MLoef.x<-function(rsobj, splitcr=NULL, ...){
MLexact<-function(X,splitcr){
rmod<-RM(X)
LR<-MLoef(rmod,splitcr)$LR
LR
}
if(is.null(splitcr)) splitcr="median"
res <- rstats(rsextrobj(rsobj, 2), MLexact, splitcr)
rmod<-RM(rsextrmat(rsobj,1))
MLres<-MLoef(rmod,splitcr)
class(MLres)<-c(class(MLres),"MLx")
res1<-MLres$LR
n_eff<-rsobj$n_eff
res<-unlist(res)
prop<-sum((res[1:n_eff]>=res1)/n_eff)
result<-list(MLres=MLres, n_eff=n_eff, prop=prop, MLoefvec=res)
class(result)<-"MLobj"
result
}
Tpbis <- function(rsobj, idxt=NULL, idxs=NULL, ...){
Tpbis.stat <- function(x){
rb <- rowSums(x[, idxs, drop = FALSE])
t <- x[, idxt]
r <- tapply(rb, t, sum, simplify = FALSE)
n1 <- sum(t)
n0 <- sum(1 - t)
return(n0 * r[[2L]][1L] - n1*r[[1L]][1L])
}
if(is.null(idxs)) stop("No item(s) for subscale specified (use idxs!)")
if(is.null(idxt)) stop("No test item for testing against subscale specified (use idx!)")
li1 <- length(idxt)
li2 <- length(idxs)
k <- rsobj$k
if(li1 > 1L ||li2 >= k || (li1 + li2) > k || any(idxt %in% idxs) || any(c(idxt,idxs) > k)){
stop("Subscale and/or test item incorrectly specified.")
}
n_eff <- rsobj$n_eff
n_tot <- rsobj$n_tot
res <- rstats(rsobj, Tpbis.stat)
corrvec <- do.call(cbind, lapply(res, as.vector))
prop <- sum(corrvec[2L:(n_tot)] <= corrvec[1L]) / n_eff
result <- list("n_eff" = n_eff,
"prop" = prop,
"idxt" = idxt,
"idxs" = idxs,
"Tpbisvec" = corrvec)
class(result)<-"Tpbisobj"
return(result)
}
Tmd<-function(rsobj, idx1=NULL, idx2=NULL, ...){
Tmd.stat<-function(x){
r1<-rowSums(x[,idx1, drop=FALSE])
r2<-rowSums(x[,idx2, drop=FALSE])
corr<-cor(r1,r2)
corr
}
if(is.null(idx1))
stop("No item(s) for subscale 1 specified (use idx1!)")
if(is.null(idx2))
stop("No item(s) for subscale 2 specified (use idx2!)")
li1<-length(idx1)
li2<-length(idx2)
k<-rsobj$k
if(li1>=k ||li2>=k || li1+li2>k || any(idx1 %in% idx2))
stop("Subscale(s) incorrectly specified.")
n_eff<-rsobj$n_eff
n_tot<-rsobj$n_tot
res<-rstats(rsobj,Tmd.stat)
corrvec<-do.call(cbind, lapply(res,as.vector))
prop<-sum(corrvec[2:(n_tot)]<=corrvec[1])/n_eff
result<-list(n_eff=n_eff, prop=prop, idx1=idx1, idx2=idx2, Tmdvec=corrvec)
class(result)<-"Tmdobj"
result
}
T1m<-function(rsobj, ...){
T1mstat<-function(x){
unlist(lapply(1:(k-1),function(i) lapply((i+1):k, function(j) sum(x[,i]==x[,j]))))
}
n_eff<-rsobj$n_eff
n_tot<-rsobj$n_tot
k<-rsobj$k
res<-rstats(rsobj,T1mstat)
res<-do.call(cbind, lapply(res,as.vector))
T1mvec<-apply(res, 1, function(x) sum(x[2:(n_tot)]<=x[1])/n_eff)
T1mmat<-matrix(,k,k)
T1mmat[lower.tri(T1mmat)] <- T1mvec
result<-list(n_eff=n_eff, prop=T1mvec, T1mmat=T1mmat)
class(result)<-"T1mobj"
result
}
T1<-function(rsobj, ...){
T1stat<-function(x){
unlist(lapply(1:(k-1),function(i) lapply((i+1):k, function(j) sum(x[,i]==x[,j]))))
}
n_eff<-rsobj$n_eff
n_tot<-rsobj$n_tot
k<-rsobj$k
res<-rstats(rsobj,T1stat)
res<-do.call(cbind, lapply(res,as.vector))
T1vec<-apply(res, 1, function(x) sum(x[2:(n_tot)]>=x[1])/n_eff)
T1mat<-matrix(,k,k)
T1mat[lower.tri(T1mat)] <- T1vec
result<-list(n_eff=n_eff, prop=T1vec, T1mat=T1mat)
class(result)<-"T1obj"
result
}
T1l<-function(rsobj, ...){
T1lstat<-function(x){
unlist(lapply(1:(k-1),function(i) lapply((i+1):k, function(j) sum(x[,i] & x[,j]))))
}
n_eff<-rsobj$n_eff
n_tot<-rsobj$n_tot
k<-rsobj$k
res<-rstats(rsobj,T1lstat)
res<-do.call(cbind, lapply(res,as.vector))
T1lvec<-apply(res, 1, function(x) sum(x[2:(n_tot)]>=x[1])/n_eff)
T1lmat<-matrix(,k,k)
T1lmat[lower.tri(T1lmat)] <- T1lvec
result<-list(n_eff=n_eff, prop=T1lvec, T1lmat=T1lmat)
class(result)<-"T1lobj"
result
}
T2<-function(rsobj,idx=NULL,stat="var", ...){
T2.Var.stat<-function(x){
var(rowSums(x[,idx, drop=FALSE]))
}
T2.MAD1.stat<-function(x){
y<-rowSums(x[,idx, drop=FALSE])
mean(abs(y-mean(y)))
}
T2.MAD2.stat<-function(x){
mad(rowSums(x[,idx, drop=FALSE]),constant=1)
}
T2.Range.stat<-function(x){
diff(range(rowSums(x[,idx, drop=FALSE])))
}
n<-rsobj$n
n_eff<-rsobj$n_eff
k<-rsobj$k
if(is.null(idx))
stop("No item(s) for subscale specified (use idx!)")
res<-switch(stat,
"var"=rstats(rsobj,T2.Var.stat),
"mad1"=rstats(rsobj,T2.MAD1.stat),
"mad2"=rstats(rsobj,T2.MAD2.stat),
"range"=rstats(rsobj,T2.Range.stat),
stop("stat must be one of \"var\", \"mad1\", \"mad2\", \"range\"")
)
res<-unlist(res)
prop<-sum(res[2:(n_eff+1)]>=res[1])/n_eff
result<-list(n_eff=n_eff, prop=prop, idx=idx, stat=stat, T2vec=res)
class(result)<-"T2obj"
result
}
T2m<-function(rsobj,idx=NULL,stat="var", ...){
T2m.Var.stat<-function(x){
var(rowSums(x[,idx, drop=FALSE]))
}
T2m.MAD1.stat<-function(x){
y<-rowSums(x[,idx, drop=FALSE])
mean(abs(y-mean(y)))
}
T2m.MAD2.stat<-function(x){
mad(rowSums(x[,idx, drop=FALSE]),constant=1)
}
T2m.Range.stat<-function(x){
diff(range(rowSums(x[,idx, drop=FALSE])))
}
n<-rsobj$n
n_eff<-rsobj$n_eff
k<-rsobj$k
if(is.null(idx))
stop("No item(s) for subscale specified (use idx!)")
res<-switch(stat,
"var"=rstats(rsobj,T2m.Var.stat),
"mad1"=rstats(rsobj,T2m.MAD1.stat),
"mad2"=rstats(rsobj,T2m.MAD2.stat),
"range"=rstats(rsobj,T2m.Range.stat),
stop("stat must be one of \"var\", \"mad1\", \"mad2\", \"range\"")
)
res<-unlist(res)
prop<-sum(res[2:(n_eff+1)]<=res[1])/n_eff
result<-list(n_eff=n_eff, prop=prop, idx=idx, stat=stat, T2mvec=res)
class(result)<-"T2mobj"
result
}
T4<-function(rsobj,idx=NULL,group=NULL,alternative="high", ...){
T4.stat<-function(x){
sign*sum(rowSums(x[gr,idx,drop=FALSE]))
}
n_eff<-rsobj$n_eff
n_tot<-rsobj$n_tot
k<-rsobj$k
if(is.null(idx))
stop("No item(s) for subscale specified (use idx!)")
if(length(idx)==k)
stop("Subscale containing all items gives meaningless results for T4.")
if(is.null(group))
stop("No group specified (use group!)")
if(!is.logical(group))
stop("group must be of type \"logical\" (e.g., group = (age==1) )")
if(alternative=="high")
sign <- 1
else if(alternative=="low")
sign <- -1
else
stop("alternative incorrectly specified! (use either \"high\" or \"low\")")
gr<-as.logical(group)
res<-rstats(rsobj,T4.stat)
res<-unlist(res)
prop<-sum(res[2:(n_tot)]>=res[1])/n_eff
gr.nam <- deparse(substitute(group))
gr.n <- sum(group)
result<-list(n_eff=n_eff, prop=prop, idx=idx, gr.nam=gr.nam, gr.n=gr.n, T4vec=res, alternative=alternative)
class(result)<-"T4obj"
result
}
T10<-function(rsobj, splitcr="median", ...){
calc.groups<-function(x,splitcr){
if (length(splitcr) > 1) {
if (length(splitcr) != nrow(x)) {
stop("Mismatch between length of split vector and number of persons!")
}
splitcr <- as.factor(splitcr)
if (length(levels(splitcr))>2) {
stop("Split vector defines more than 2 groups (only two allowed)!")
}
spl.lev <- levels(splitcr)
hi <- splitcr==spl.lev[1]
} else if (!is.numeric(splitcr)) {
spl.nam <- splitcr
if (splitcr == "median") {
spl.gr <- c("Raw Scores <= Median", "Raw Scores > Median")
rv <- rowSums(x)
rvsplit <- median(rv)
hi <- rv > rvsplit
}
if (splitcr == "mean") {
spl.gr <- c("Raw Scores < Mean", "Raw Scores >= Mean")
rv <- rowSums(x)
rvsplit <- mean(rv)
hi <- rv > rvsplit
}
}
list(hi=hi,spl.nam=spl.nam)
}
T10.stat<-function(x){
nij.hi<-unlist(lapply(1:k,function(i) lapply(1:k, function(j) sum(x[hi,i]>x[hi,j]))))
nij.low<-unlist(lapply(1:k,function(i) lapply(1:k, function(j) sum(x[!hi,i]>x[!hi,j]))))
nji.hi<- unlist(lapply(1:k,function(i) lapply(1:k, function(j) sum(x[hi,i]<x[hi,j]))))
nji.low<- unlist(lapply(1:k,function(i) lapply(1:k, function(j) sum(x[!hi,i]<x[!hi,j]))))
RET<-sum(abs(nij.hi*nji.low-nij.low*nji.hi))
RET
}
spl.nam <- deparse(substitute(splitcr))
n_eff<-rsobj$n_eff
n_tot<-rsobj$n_tot
k<-rsobj$k
obj<-rsextrobj(rsobj,1,1)
x<-matrix(obj$inpmat,obj$n,obj$k)
ans <- calc.groups(x,splitcr)
hi<-ans$hi
hi.n<-sum(hi)
low.n<-sum(!hi)
res<-rstats(rsobj,T10.stat)
res<-unlist(res)
prop<-sum(res[2:(n_eff+1)]>=res[1])/n_eff
result<-list(n_eff=n_eff, prop=prop,spl.nam=ans$spl.nam,hi.n=hi.n,low.n=low.n,T10vec=res)
class(result)<-"T10obj"
result
}
T11<-function(rsobj, ...){
T11.stat<-function(x){
as.vector(cor(x))
}
calc.T11<-function(x){
sum(abs(x-rho))
}
n_eff<-rsobj$n_eff
n_tot<-rsobj$n_tot
k<-rsobj$k
res<-rstats(rsobj,T11.stat)
cormats <- matrix(unlist(res),nrow=k*k)
rho<-apply(cormats[,2:n_tot],1,mean)
T11obs<-calc.T11(cormats[,1])
prop<-sum(apply(cormats[, 2:n_tot],2,calc.T11)>=T11obs)/n_eff
result<-list(n_eff=n_eff, prop=prop, T11r=cormats[,1], T11rho=rho)
class(result)<-"T11obj"
result
}
Q3h<-function(rsobj, ...){
Q3h.stat <- function(x){
as.vector(x)
}
calcQ3h.stat <- function(x, exp=exp) {
i <- ncol(x)
mat <- x - exp
res <- matrix(nrow=i,ncol=i)
for(a in 1:(i-1)) {
for(b in (a+1):i) {
res[b,a] <- res[a,b] <- -cor(mat[,a],mat[,b])
}
}
return(res)
}
n_eff<-rsobj$n_eff
n_tot<-rsobj$n_tot
k <- rsobj$k
n <- rsobj$n
res <- rstats(rsobj,Q3h.stat)
datmat <- matrix(unlist(res),nrow=k*n)
exp <- matrix(apply(datmat, 1, mean), nrow=n, ncol=k)
res <- rstats(rsobj, calcQ3h.stat, exp=exp)
res<-do.call(cbind, lapply(res,as.vector))
Q3hvec<-apply(res, 1, function(x) sum(x[2:(n_tot)]<x[1])/n_eff)
Q3hmat<- matrix(Q3hvec, ncol=k)
Q3hmat[upper.tri(Q3hmat)] <- NA
Q3hvec <- as.vector(Q3hmat)
Q3hvec <- Q3hvec[!is.na(Q3hvec)]
result<-list(n_eff=n_eff, prop=Q3hvec, Q3hmat=Q3hmat)
class(result)<-"Q3hobj"
return(result)
}
Q3l<-function(rsobj, ...){
Q3l.stat <- function(x){
as.vector(x)
}
calcQ3l.stat <- function(x, exp=exp) {
i <- ncol(x)
mat <- x - exp
res <- matrix(nrow=i,ncol=i)
for(a in 1:(i-1)) {
for(b in (a+1):i) {
res[b,a] <- res[a,b] <- cor(mat[,a],mat[,b])
}
}
return(res)
}
n_eff<-rsobj$n_eff
n_tot<-rsobj$n_tot
k <- rsobj$k
n <- rsobj$n
res <- rstats(rsobj,Q3l.stat)
datmat <- matrix(unlist(res),nrow=k*n)
exp <- matrix(apply(datmat, 1, mean), nrow=n, ncol=k)
res <- rstats(rsobj, calcQ3l.stat, exp=exp)
res<-do.call(cbind, lapply(res,as.vector))
Q3lvec<-apply(res, 1, function(x) sum(x[2:(n_tot)]<x[1])/n_eff)
Q3lmat<- matrix(Q3lvec, ncol=k)
Q3lmat[upper.tri(Q3lmat)] <- NA
Q3lvec <- as.vector(Q3lmat)
Q3lvec <- Q3lvec[!is.na(Q3lvec)]
result<-list(n_eff=n_eff, prop=Q3lvec, Q3lmat=Q3lmat)
class(result)<-"Q3lobj"
return(result)
}
print.MLobj<-function(x,...){
print(x$MLres)
cat("'exact' p-value =", x$prop, " (based on", x$n_eff, "sampled matrices)\n\n")
}
print.Tmdobj<-function(x,...){
txt1<-"\nNonparametric RM model test: Tmd (Multidimensionality)"
writeLines(strwrap(txt1, exdent=4))
cat(" (correlation of subscale person scores)\n")
cat("Number of sampled matrices:", x$n_eff,"\n")
cat("Subscale 1 - Items:", x$idx1,"\n")
cat("Subscale 2 - Items:", x$idx2,"\n")
cat("Observed correlation:", x$Tmdvec[1],"\n")
cat("one-sided p-value:",x$prop,"\n\n")
}
print.Tpbisobj<-function(x,...){
txt1<-"\nNonparametric RM model test: Tpbis (discrimination)"
writeLines(strwrap(txt1, exdent=4))
cat(" (pointbiserial correlation of test item vs. subscale)\n")
cat("Number of sampled matrices:", x$n_eff,"\n")
cat("Test Item:", x$idxt,"\n")
cat("Subscale - Items:", x$idxs,"\n")
cat("one-sided p-value (rpbis too low):",x$prop,"\n\n")
}
print.T1obj<-function(x,alpha=0.05,...){
txt1<-"\nNonparametric RM model test: T1 (local dependence - increased inter-item correlations)\n"
writeLines(strwrap(txt1, exdent=4))
cat(" (counting cases with equal responses on both items)\n")
cat("Number of sampled matrices:", x$n_eff,"\n")
cat("Number of Item-Pairs tested:", length(x$prop),"\n")
cat("Item-Pairs with one-sided p <", alpha,"\n")
T1mat<-x$T1mat
idx<-which(T1mat<alpha,arr.ind=TRUE)
val<-T1mat[which(T1mat<alpha)]
names(val)<-apply(idx,1,function(x) paste("(",x[2],",",x[1],")",sep="",collapse=""))
if (length(val)>0)
print(round(val,digits=3))
else
cat("none\n\n")
}
print.T1mobj<-function(x,alpha=0.05,...){
txT1m<-"\nNonparametric RM model test: T1m (multidimensionality - reduced inter-item correlations)\n"
writeLines(strwrap(txT1m, exdent=4))
cat(" (counting cases with equal responses on both items)\n")
cat("Number of sampled matrices:", x$n_eff,"\n")
cat("Number of Item-Pairs tested:", length(x$prop),"\n")
cat("Item-Pairs with one-sided p <", alpha,"\n")
T1mmat<-x$T1mmat
idx<-which(T1mmat<alpha,arr.ind=TRUE)
val<-T1mmat[which(T1mmat<alpha)]
names(val)<-apply(idx,1,function(x) paste("(",x[2],",",x[1],")",sep="",collapse=""))
if (length(val)>0)
print(round(val,digits=3))
else
cat("none\n\n")
}
print.T1lobj<-function(x,alpha=0.05,...){
txt1<-"\nNonparametric RM model test: T1 (learning - based on item pairs)\n"
writeLines(strwrap(txt1, exdent=4))
cat(" (counting cases with reponsepattern (1,1) for item pair)\n")
cat("Number of sampled matrices:", x$n_eff,"\n")
cat("Number of sampled matrices:", x$n_eff,"\n")
cat("Number of Item-Pairs tested:", length(x$prop),"\n")
cat("Item-Pairs with one-sided p <", alpha,"\n")
T1lmat<-x$T1lmat
idx<-which(T1lmat<alpha,arr.ind=TRUE)
val<-T1lmat[which(T1lmat<alpha)]
names(val)<-apply(idx,1,function(x) paste("(",x[2],",",x[1],")",sep="",collapse=""))
if (length(val)>0)
print(round(val,digits=3))
else
cat("none\n\n")
}
print.T2obj<-function(x,...){
prop<-x$prop
idx<-x$idx
stat<-x$stat
statnam<-switch(stat,
"var"="variance",
"mad1"="mean absolute deviation",
"mad2"="median absolute deviation",
"range"="range"
)
txt<-"\nNonparametric RM model test: T2 (local dependence - model deviating subscales)\n"
writeLines(strwrap(txt, exdent=4))
cat(" (increased dispersion of subscale person rawscores)\n")
cat("Number of sampled matrices:", x$n_eff,"\n")
cat("Items in subscale:", idx,"\n")
cat("Statistic:", statnam,"\n")
cat("one-sided p-value:",prop,"\n\n")
}
print.T2mobj<-function(x,...){
prop<-x$prop
idx<-x$idx
stat<-x$stat
statnam<-switch(stat,
"var"="variance",
"mad1"="mean absolute deviation",
"mad2"="median absolute deviation",
"range"="range"
)
txt<-"\nNonparametric RM model test: T2m (multidimensionality - model deviating subscales)\n"
writeLines(strwrap(txt, exdent=4))
cat(" (decreased dispersion of subscale person rawscores)\n")
cat("Number of sampled matrices:", x$n_eff,"\n")
cat("Items in subscale:", idx,"\n")
cat("Statistic:", statnam,"\n")
cat("one-sided p-value:",prop,"\n\n")
}
print.T4obj<-function(x,...){
prop<-x$prop
idx<-x$idx
gr.nam<-x$gr.nam
gr.n<-x$gr.n
alternative<-x$alternative
cat("\nNonparametric RM model test: T4 (Group anomalies - DIF)\n")
txt<-paste(" (counting", alternative, "raw scores on item(s) for specified group)\n", collapse="")
writeLines(strwrap(txt, exdent=4))
cat("Number of sampled matrices:", x$n_eff,"\n")
cat("Items in Subscale:", idx,"\n")
cat("Group:",gr.nam," n =",gr.n,"\n")
cat("one-sided p-value:",prop,"\n\n")
}
print.T10obj<-function(x,...){
spl.nam<-x$spl.nam
prop<-x$prop
hi.n<-x$hi.n
low.n<-x$low.n
txt<-"\nNonparametric RM model test: T10 (global test - subgroup-invariance)\n"
writeLines(strwrap(txt, exdent=4))
cat("Number of sampled matrices:", x$n_eff,"\n")
cat("Split:",spl.nam,"\n")
cat("Group 1: n = ",hi.n," Group 2: n =",low.n,"\n")
cat("one-sided p-value:",prop,"\n\n")
}
print.T11obj<-function(x,...){
prop<-x$prop
txt<-"\nNonparametric RM model test: T11 (global test - local dependence)\n"
writeLines(strwrap(txt, exdent=4))
txt<-" (sum of deviations between observed and expected inter-item correlations)\n"
writeLines(strwrap(txt, exdent=4))
cat("Number of sampled matrices:", x$n_eff,"\n")
cat("one-sided p-value:",prop,"\n\n")
}
print.Q3hobj<-function(x,alpha=0.05,...){
txt1<-"\nNonparametric RM model test: Q3h (local dependence - increased correlation of inter-item residuals)\n"
writeLines(strwrap(txt1, exdent=4))
cat("Number of sampled matrices:", x$n_eff,"\n")
cat("Number of Item-Pairs tested:", length(x$prop),"\n")
cat("Item-Pairs with one-sided p <", alpha,"\n")
Q3hmat<-x$Q3hmat
idx<-which(Q3hmat<alpha,arr.ind=TRUE)
val<-Q3hmat[which(Q3hmat<alpha)]
names(val)<-apply(idx,1,function(x) paste("(",x[2],",",x[1],")",sep="",collapse=""))
if (length(val)>0)
print(round(val,digits=3))
else
cat("none\n\n")
}
print.Q3lobj<-function(x,alpha=0.05,...){
txt1<-"\nNonparametric RM model test: Q3l (local dependence - decreased correlation of inter-item residuals)\n"
writeLines(strwrap(txt1, exdent=4))
cat("Number of sampled matrices:", x$n_eff,"\n")
cat("Number of Item-Pairs tested:", length(x$prop),"\n")
cat("Item-Pairs with one-sided p <", alpha,"\n")
Q3lmat<-x$Q3lmat
idx<-which(Q3lmat<alpha,arr.ind=TRUE)
val<-Q3lmat[which(Q3lmat<alpha)]
names(val)<-apply(idx,1,function(x) paste("(",x[2],",",x[1],")",sep="",collapse=""))
if (length(val)>0)
print(round(val,digits=3))
else
cat("none\n\n")
} |
ifelse_pipe = function(.x, .p, .f1, .f2 = NULL) {
switch(.p %>% not%>% sum(1),
as_mapper(.f1)(.x),
if (.f2 %>% is.null %>% not)
as_mapper(.f2)(.x)
else
.x)
}
ifelse2_pipe = function(.x, .p1, .p2, .f1, .f2, .f3 = NULL) {
switch(
.p1 %>% not%>% sum(1),
as_mapper(.f1)(.x),
switch(
.p2 %>% not %>% sum(1),
as_mapper(.f2)(.x),
if (.f3 %>% is.null %>% not)
as_mapper(.f3)(.x)
else
.x
))
}
as_matrix <- function(tbl,
rownames = NULL,
do_check = TRUE) {
variable = NULL
rownames = enquo(rownames)
tbl %>%
ifelse_pipe(
do_check &&
tbl %>%
ifelse_pipe(!quo_is_null(rownames), ~ .x[, -1], ~ .x) %>%
dplyr::summarise_all(class) %>%
tidyr::gather(variable, class) %>%
pull(class) %>%
unique() %>%
`%in%`(c("numeric", "integer")) %>% not() %>% any(),
~ {
warning("to_matrix says: there are NON-numerical columns, the matrix will NOT be numerical")
.x
}
) %>%
as.data.frame() %>%
ifelse_pipe(
!quo_is_null(rownames),
~ .x %>%
magrittr::set_rownames(tbl %>% pull(!!rownames)) %>%
select(-1)
) %>%
as.matrix()
}
error_if_log_transformed <- function(x, .abundance) {
m = NULL
.abundance = enquo(.abundance)
if (x %>% nrow %>% gt(0))
if (x %>% summarise(m = !!.abundance %>% max) %>% pull(m) < 50)
stop(
"tidyHeatmap says: The input was log transformed, this algorithm requires raw (un-normalised) read counts"
)
}
parse_formula <- function(fm) {
if (attr(terms(fm), "response") == 1)
stop("tidyHeatmap says: The .formula must be of the kind \"~ covariates\" ")
else
as.character(attr(terms(fm), "variables"))[-1]
}
scale_design = function(df, .formula) {
value = sample_idx = `(Intercept)` = NULL
df %>%
setNames(c("sample_idx", "(Intercept)", parse_formula(.formula))) %>%
gather(cov, value,-sample_idx) %>%
group_by(cov) %>%
mutate(value = ifelse(
!grepl("Intercept", cov) &
length(union(c(0, 1), value)) != 2,
scale(value),
value
)) %>%
ungroup() %>%
spread(cov, value) %>%
arrange(as.integer(sample_idx)) %>%
select(`(Intercept)`, one_of(parse_formula(.formula)))
}
add_attr = function(var, attribute, name) {
attr(var, name) <- attribute
var
}
drop_class = function(var, name) {
class(var) <- class(var)[!class(var)%in%name]
var
}
prepend = function (x, values, before = 1)
{
n <- length(x)
stopifnot(before > 0 && before <= n)
if (before == 1) {
c(values, x)
}
else {
c(x[1:(before - 1)], values, x[before:n])
}
}
add_class = function(var, name) {
class(var) <- prepend(class(var),name)
var
}
get_sample_transcript_counts = function(.data, .sample, .transcript, .abundance){
my_stop = function() {
stop("
tidyHeatmap says: The function does not know what your sample, transcript and counts columns are.\n
You have to either enter those as symbols (e.g., `sample`), \n
or use the funtion create_tt_from_tibble() to pass your column names that will be remembered.
")
}
if( .sample %>% quo_is_symbol() ) .sample = .sample
else if(".sample" %in% (.data %>% attr("parameters") %>% names))
.sample = attr(.data, "parameters")$.sample
else my_stop()
if( .transcript %>% quo_is_symbol() ) .transcript = .transcript
else if(".transcript" %in% (.data %>% attr("parameters") %>% names))
.transcript = attr(.data, "parameters")$.transcript
else my_stop()
if( .abundance %>% quo_is_symbol() ) .abundance = .abundance
else if(".abundance" %in% (.data %>% attr("parameters") %>% names))
.abundance = attr(.data, "parameters")$.abundance
else my_stop()
list(.sample = .sample, .transcript = .transcript, .abundance = .abundance)
}
get_sample_counts = function(.data, .sample, .abundance){
my_stop = function() {
stop("
tidyHeatmap says: The function does not know what your sample, transcript and counts columns are.\n
You have to either enter those as symbols (e.g., `sample`), \n
or use the funtion create_tt_from_tibble() to pass your column names that will be remembered.
")
}
if( .sample %>% quo_is_symbol() ) .sample = .sample
else if(".sample" %in% (.data %>% attr("parameters") %>% names))
.sample = attr(.data, "parameters")$.sample
else my_stop()
if( .abundance %>% quo_is_symbol() ) .abundance = .abundance
else if(".abundance" %in% (.data %>% attr("parameters") %>% names))
.abundance = attr(.data, "parameters")$.abundance
else my_stop()
list(.sample = .sample, .abundance = .abundance)
}
get_sample_transcript = function(.data, .sample, .transcript){
my_stop = function() {
stop("
tidyHeatmap says: The function does not know what your sample, transcript and counts columns are.\n
You have to either enter those as symbols (e.g., `sample`), \n
or use the funtion create_tt_from_tibble() to pass your column names that will be remembered.
")
}
if( .sample %>% quo_is_symbol() ) .sample = .sample
else if(".sample" %in% (.data %>% attr("parameters") %>% names))
.sample = attr(.data, "parameters")$.sample
else my_stop()
if( .transcript %>% quo_is_symbol() ) .transcript = .transcript
else if(".transcript" %in% (.data %>% attr("parameters") %>% names))
.transcript = attr(.data, "parameters")$.transcript
else my_stop()
list(.sample = .sample, .transcript = .transcript)
}
get_elements_features = function(.data, .element, .feature, of_samples = TRUE){
if(
.element %>% quo_is_symbol() &
.feature %>% quo_is_symbol()
)
return(list(
.element = .element,
.feature = .feature
))
else {
if(.data %>% attr("parameters") %>% is.null %>% not)
return(list(
.element = switch(
of_samples %>% not %>% sum(1),
attr(.data, "parameters")$.sample,
attr(.data, "parameters")$.transcript
),
.feature = switch(
of_samples %>% not %>% sum(1),
attr(.data, "parameters")$.transcript,
attr(.data, "parameters")$.sample
)
))
else
stop("
tidyHeatmap says: The function does not know what your elements (e.g., sample) and features (e.g., transcripts) are.\n
You have to either enter those as symbols (e.g., `sample`), \n
or use the funtion create_tt_from_tibble() to pass your column names that will be remembered.
")
}
}
get_elements_features_abundance = function(.data, .element, .feature, .abundance, of_samples = TRUE){
my_stop = function() {
stop("
tidyHeatmap says: The function does not know what your elements (e.g., sample) and features (e.g., transcripts) are.\n
You have to either enter those as symbols (e.g., `sample`), \n
or use the funtion create_tt_from_tibble() to pass your column names that will be remembered.
")
}
if( .element %>% quo_is_symbol() ) .element = .element
else if(of_samples & ".sample" %in% (.data %>% attr("parameters") %>% names))
.element = attr(.data, "parameters")$.sample
else if((!of_samples) & ".transcript" %in% (.data %>% attr("parameters") %>% names))
.element = attr(.data, "parameters")$.transcript
else my_stop()
if( .feature %>% quo_is_symbol() ) .feature = .feature
else if(of_samples & ".transcript" %in% (.data %>% attr("parameters") %>% names))
.feature = attr(.data, "parameters")$.transcript
else if((!of_samples) & ".sample" %in% (.data %>% attr("parameters") %>% names))
.feature = attr(.data, "parameters")$.sample
else my_stop()
if( .abundance %>% quo_is_symbol() ) .abundance = .abundance
else if(".abundance" %in% (.data %>% attr("parameters") %>% names))
.abundance = attr(.data, "parameters")$.abundance
else my_stop()
list(.element = .element, .feature = .feature, .abundance = .abundance)
}
get_elements = function(.data, .element, of_samples = TRUE){
if(
.element %>% quo_is_symbol()
)
return(list(
.element = .element
))
else {
if(.data %>% attr("parameters") %>% is.null %>% not)
return(list(
.element = switch(
of_samples %>% not %>% sum(1),
attr(.data, "parameters")$.sample,
attr(.data, "parameters")$.transcript
)
))
else
stop("
tidyHeatmap says: The function does not know what your elements (e.g., sample) are.\n
You have to either enter those as symbols (e.g., `sample`), \n
or use the funtion create_tt_from_tibble() to pass your column names that will be remembered.
")
}
}
get_abundance_norm_if_exists = function(.data, .abundance){
.abundance_norm = NULL
if(
.abundance %>% quo_is_symbol()
)
return(list(
.abundance = .abundance
))
else {
if(.data %>% attr("parameters") %>% is.null %>% not)
return(list(
.abundance = switch(
(".abundance_norm" %in% (.data %>% attr("parameters") %>% names) &
quo_name(.data %>% attr("parameters") %$% .abundance_norm) %in% (.data %>% colnames)
) %>% not %>% sum(1),
attr(.data, "parameters")$.abundance_norm,
attr(.data, "parameters")$.abundance
)
))
else
stop("
tidyHeatmap says: The function does not know what your elements (e.g., sample) are.\n
You have to either enter those as symbols (e.g., `sample`), \n
or use the funtion create_tt_from_tibble() to pass your column names that will be remembered.
")
}
}
select_closest_pairs = function(df) {
`sample 1` = `sample 2` = NULL
couples <- df %>% head(n = 0)
while (df %>% nrow() > 0) {
pair <- df %>%
arrange(dist) %>%
head(n = 1)
couples <- couples %>% bind_rows(pair)
df <- df %>%
filter(
!`sample 1` %in% (pair %>% select(1:2) %>% as.character()) &
!`sample 2` %in% (pair %>% select(1:2) %>% as.character())
)
}
couples
}
get_x_y_annotation_columns = function(.data, .column, .row, .abundance){
. = NULL
value = NULL
orientation = NULL
col_name = NULL
.column = enquo(.column)
.row = enquo(.row)
.abundance = enquo(.abundance)
.data %>%
select_if(negate(is.list)) %>%
ungroup() %>%
{
bind_rows(
(.) %>% subset(!!.column) %>% colnames %>% as_tibble %>% rename(column = value) %>% gather(orientation, col_name),
(.) %>% subset(!!.row) %>% colnames %>% as_tibble %>% rename(row = value) %>% gather(orientation, col_name)
)
}
}
ct_colors = function(ct)
ct %>%
as.character() %>%
map_chr(
~ switch(
.x,
"E" = "
"F" = "
"M" = "
"T" = "
)
)
type_to_annot_function = list(
"tile" = NULL,
"point" = anno_points,
"bar" = anno_barplot,
"line" = anno_lines
)
get_top_left_annotation = function(.data_, .column, .row, .abundance, annotation, palette_annotation, type, x_y_annot_cols, size, ...){
data = NULL
fx = NULL
annot = NULL
annot_type = NULL
idx = NULL
value = NULL
orientation = NULL
col_name = NULL
col_orientation = NULL
.column = enquo(.column)
.row = enquo(.row)
.abundance = enquo(.abundance)
annotation = enquo(annotation)
dots_args = rlang::dots_list(...)
annotation_function = type_to_annot_function[type]
quo_names(annotation) %>%
as_tibble %>%
rename(col_name = value) %>%
when(quo_is_null(annotation) ~ slice(., 0), ~ (.)) %>%
left_join(x_y_annot_cols, by = "col_name") %>%
mutate(col_orientation = map_chr(orientation, ~ .x %>% when((.) == "column" ~ quo_name(.column), (.) == "row" ~ quo_name(.row)))) %>%
mutate(
data = map2(
col_name,
col_orientation,
~
.data_ %>%
ungroup() %>%
select(.y, .x) %>%
distinct() %>%
arrange_at(vars(.y)) %>%
pull(.x)
)
) %>%
mutate(fx = annotation_function) %>%
mutate(annot = pmap(list(data, fx, orientation), ~ {
fx = ..2
if(is_function(fx) & ..3 == "column") fx(..1, which=..3, height = size)
else if(is_function(fx) & ..3 == "row") fx(..1, which=..3, width = size)
else .x
})) %>%
mutate(annot_type = map_chr(annot, ~ .x %>% when(class(.) %in% c("factor", "character", "logical") ~ "discrete",
class(.) %in% c("integer", "numerical", "numeric", "double") ~ "continuous",
~ "other"
) )) %>%
group_by(annot_type) %>%
mutate(idx = row_number()) %>%
ungroup() %>%
mutate(color = map2(annot, idx, ~ {
if(.x %>% class %in% c("factor", "character", "logical"))
colorRampPalette(palette_annotation$discrete[[.y]])(length(unique(.x))) %>% setNames(unique(.x))
else if (.x %>% class %in% c("integer", "numerical", "numeric", "double"))
colorRampPalette(palette_annotation$continuous[[.y]])(length(.x)) %>% colorRamp2(seq(min(.x), max(.x), length.out = length(.x)), .)
else NULL
})) %>%
mutate(further_arguments = map2(
col_name, fx,
~ dots_args %>%
when(!is_function(.y) ~ c(., list(simple_anno_size = size)), ~ (.))
)) %>%
when(
(.) %>% pull(data) %>% map_chr(~ .x %>% class) %in%
c("factor", "character") %>% which %>% length %>%
gt(palette_annotation$discrete %>% length) ~
stop("tidyHeatmap says: Your discrete annotaton columns are bigger than the palette available"),
~ (.)
) %>%
when(
(.) %>% pull(data) %>% map_chr(~ .x %>% class) %in%
c("int", "dbl", "numeric") %>% which %>% length %>%
gt( palette_annotation$continuous %>% length) ~
stop("tidyHeatmap says: Your continuous annotaton columns are bigger than the palette available"),
~ (.)
)
}
get_group_annotation = function(.data, .column, .row, .abundance, palette_annotation){
data = NULL
. = NULL
orientation = NULL
.column = enquo(.column)
.row = enquo(.row)
.abundance = enquo(.abundance)
top_annotation = list()
left_annotation = list()
row_split = NULL
col_split = NULL
col_group = get_grouping_columns(.data)
x_y_annot_cols = .data %>% get_x_y_annotation_columns(!!.column,!!.row,!!.abundance)
x_y_annotation_cols =
x_y_annot_cols %>%
nest(data = -orientation) %>%
mutate(data = map(data, ~ .x %>% pull(1))) %>%
{
df = (.)
pull(df, data) %>% setNames(pull(df, orientation))
} %>%
map(
~ .x %>% intersect(col_group)
)
if(x_y_annotation_cols %>% lapply(length) %>% unlist %>% max %>% gt(1))
stop("tidyHeatmap says: At the moment just one grouping per dimension (max 1 row and 1 column) is supported.")
if(x_y_annotation_cols %>% unlist() %>% duplicated() %>% any())
stop(sprintf("tidyHeatmap says: the grouping %s is not specific to row or columns. Maybe you just have one grouping.", x_y_annotation_cols %>% unlist() %>% .[x_y_annotation_cols %>% unlist() %>% duplicated()]))
if(length(x_y_annotation_cols$row) > 0){
row_split =
.data %>%
ungroup() %>%
distinct(!!.row, !!as.symbol(x_y_annotation_cols$row)) %>%
arrange(!!.row) %>%
pull(!!as.symbol(x_y_annotation_cols$row))
palette_fill_row =
colorRampPalette(
palette_annotation[[1]][
1:min(length(unique(row_split)), length(palette_annotation[[1]]))
])(
length(unique(row_split))
) %>%
setNames(unique(row_split))
palette_text_row = if_else(palette_fill_row %in% c("
left_annotation_args =
list(
ct = anno_block(
gp = gpar(fill = palette_fill_row ),
labels = row_split %>% unique %>% sort,
labels_gp = gpar(col = palette_text_row, fontsize = 8),
which = "row",
width = unit(9, "pt")
)
)
left_annotation = as.list(left_annotation_args)
palette_annotation = palette_annotation[-1]
}
if(length(x_y_annotation_cols$column) > 0){
col_split =
.data %>%
ungroup() %>%
distinct(!!.column, !!as.symbol(x_y_annotation_cols$column)) %>%
arrange(!!.column) %>%
pull(!!as.symbol(x_y_annotation_cols$column))
palette_fill_column =
colorRampPalette(
palette_annotation[[1]][
1:min(length(unique(col_split)), length(palette_annotation[[1]]))
])(
length(unique(col_split))
) %>%
setNames(unique(col_split))
palette_text_column = if_else(palette_fill_column %in% c("
top_annotation_args =
list(
ct = anno_block(
gp = gpar(fill = palette_fill_column ),
labels = col_split %>% unique %>% sort,
labels_gp = gpar(col = palette_text_column, fontsize = 8),
which = "column",
height = unit(9, "pt")
)
)
top_annotation = as.list(top_annotation_args)
}
list( left_annotation = left_annotation, row_split = row_split, top_annotation = top_annotation, col_split = col_split )
}
get_group_annotation_OPTIMISED_NOT_FINISHED = function(.data, .column, .row, .abundance, palette_annotation){
value = NULL
col_name = NULL
col_orientation = NULL
annotation_function = NULL
data = NULL
. = NULL
orientation = NULL
.column = enquo(.column)
.row = enquo(.row)
.abundance = enquo(.abundance)
top_annotation = NULL
left_annotation = NULL
row_split = NULL
col_split = NULL
col_group = get_grouping_columns(.data)
x_y_annot_cols = .data %>% get_x_y_annotation_columns(!!.column,!!.row,!!.abundance)
x_y_annotation_cols =
x_y_annot_cols %>%
nest(data = -orientation) %>%
mutate(data = map(data, ~ .x %>% pull(1))) %>%
{
df = (.)
pull(df, data) %>% setNames(pull(df, orientation))
} %>%
map(
~ .x %>% intersect(col_group)
)
if(x_y_annotation_cols %>% lapply(length) %>% unlist %>% max %>% gt(1))
stop("tidyHeatmap says: At the moment just one grouping per dimension (max 1 row and 1 column) is supported.")
col_group %>%
as_tibble %>%
rename(col_name = value) %>%
when(length(col_group)==0 ~ slice(., 0), ~ (.)) %>%
left_join(x_y_annot_cols, by = "col_name") %>%
mutate(col_orientation = map_chr(orientation, ~ .x %>% when((.) == "column" ~ quo_name(.column), (.) == "row" ~ quo_name(.row)))) %>%
mutate(
data = map2(
col_name,
col_orientation,
~
.data_ %>%
ungroup() %>%
select(.y, .x) %>%
distinct() %>%
arrange_at(vars(.y)) %>%
pull(.x)
)
) %>%
mutate(fx = annotation_function)
if(length(x_y_annotation_cols$row) > 0){
row_split =
.data %>%
ungroup() %>%
distinct(!!.row, !!as.symbol(x_y_annotation_cols$row)) %>%
arrange(!!.row) %>%
pull(!!as.symbol(x_y_annotation_cols$row))
palette_fill_row = palette_annotation[[1]][1:length(unique(row_split))] %>% setNames(unique(row_split))
left_annotation_args =
list(
ct = anno_block(
gp = gpar(fill = palette_fill_row ),
labels = row_split %>% unique %>% sort,
labels_gp = gpar(col = "white"),
which = "row"
)
)
left_annotation = as.list(left_annotation_args)
palette_annotation = palette_annotation[-1]
}
if(length(x_y_annotation_cols$column) > 0){
col_split =
.data %>%
ungroup() %>%
distinct(!!.column, !!as.symbol(x_y_annotation_cols$column)) %>%
arrange(!!.column) %>%
pull(!!as.symbol(x_y_annotation_cols$column))
palette_fill_column = palette_annotation[[1]][1:length(unique(col_split))] %>% setNames(unique(col_split))
top_annotation_args =
list(
ct = anno_block(
gp = gpar(fill = palette_fill_column ),
labels = col_split %>% unique %>% sort,
labels_gp = gpar(col = "white"),
which = "column"
)
)
top_annotation = as.list(top_annotation_args)
}
list( left_annotation = left_annotation, row_split = row_split, top_annotation = top_annotation, col_split = col_split )
}
get_grouping_columns = function(.data){
.rows = NULL
if("groups" %in% (.data %>% attributes %>% names))
.data %>% attr("groups") %>% select(-.rows) %>% colnames()
else c()
}
list_drop_null = function(.data){
.data[!sapply(.data, is.null)]
}
scale_robust = function(y){
do_consider_df = !is.na(sd(y, na.rm=T)) && as.logical(sd(y, na.rm=T) )
(y - mean(y, na.rm=T)) / ( sd(y, na.rm=T) ^ do_consider_df )
}
quo_names <- function(v) {
v = quo_name(quo_squash(v))
gsub('^c\\(|`|\\)$', '', v) %>%
strsplit(', ') %>%
unlist
}
annot_to_list = function(.data){
col_name = NULL
annot = NULL
value = NULL
my_cells = NULL
name = NULL
data = NULL
.data %>%
pull(annot) %>%
setNames(.data %>% pull(col_name)) %>%
when(length(.) > 0 ~ (.) %>% c(
col = list(.data %>%
filter(map_lgl(color, ~ .x %>% is.null %>% not)) %>%
{ setNames( pull(., color), pull(., col_name)) })
) %>%
c(
.data %>%
pull(further_arguments) %>%
combine_elements_with_the_same_name()
),
~ (.))
}
list_append = function(.list1, .list2){ .list1 %>% c(.list2) }
reduce_to_tbl_if_in_class_chain = function(.obj){
.obj %>%
when(
"tbl" %in% class(.) ~ drop_class(., class(.)[1:which(class(.) == "tbl")-1] ),
~ (.)
)
}
gt = function(a, b){ a > b }
st = function(a, b){ a < b }
not = function(is){ !is }
pow = function(a,b){ a^b }
combine_elements_with_the_same_name = function(x){
my_class = NULL
value = NULL
name = NULL
data = NULL
if(length(unlist(x))==0) return(unlist(x))
else {
list_df =
map_dfr(x, ~ enframe(.x)) %>%
mutate(my_class = map_chr(value, ~class(.x)[[1]]))
if(
list_df %>%
filter(my_class == "simpleUnit") %>%
nrow() %>%
gt(1) &&
list_df %>%
filter(my_class == "simpleUnit") %>%
pull(value) %>%
reduce(identical) %>%
not()
)
warning("tidyHeatmap says: the current backend only allows for one tail annotation size. The latter one will be selected.")
list_df =
bind_rows(
list_df %>%
filter(my_class == "simpleUnit") %>%
tail(1),
list_df %>%
filter(my_class != "simpleUnit")
) %>%
nest(data = -c(name, my_class)) %>%
mutate(vector = map2(
data, my_class,
~ {
if(.y == "simpleUnit") reduce(.x$value, unit.c)
else if(.y == "gpar") combine_lists_with_the_same_name(.x$value) %>% as.list() %>% do.call(gpar, .)
else reduce(.x$value, c)
}
))
list_df %>%
pull(vector) %>%
setNames(list_df$name)
}
}
combine_lists_with_the_same_name = function(x){
if(length(unlist(x))==0) return(unlist(x))
else {
x = unlist(x)
tapply(unlist(x, use.names = FALSE), rep(names(x), lengths(x)), FUN = c)
}
} |
relmse <- function(forecast, forecastbench, true)
{
if (length(forecast) != length(true))
stop("RelMAE: the lengths of input vectors must be the same.")
ferror = mean((true - forecast)^2)
ferrorbench = mean((true - forecastbench)^2)
relativerror = ferror / ferrorbench
return(round(relativerror, 6))
} |
library(paletteer)
i <- 1
pal_viz <- function() {
name <- paste(palettes_d_names[i, ]$package, palettes_d_names[i, ]$palette, sep = "::")
plot(
paletteer_d(
name
)
)
title(name)
i <<- i + 1
}
palettes_d_names <- tibble::tribble(
~package, ~palette, ~length, ~type, ~novelty,
"awtools", "a_palette", 8L, "sequential", TRUE,
"awtools", "ppalette", 8L, "qualitative", TRUE,
"awtools", "bpalette", 16L, "qualitative", TRUE,
"awtools", "gpalette", 4L, "sequential", TRUE,
"awtools", "mpalette", 9L, "qualitative", TRUE,
"awtools", "spalette", 6L, "qualitative", TRUE,
"basetheme", "brutal", 10L, "qualitative", TRUE,
"basetheme", "clean", 10L, "qualitative", TRUE,
"basetheme", "dark", 10L, "qualitative", TRUE,
"basetheme", "deepblue", 10L, "qualitative", TRUE,
"basetheme", "ink", 10L, "qualitative", TRUE,
"basetheme", "minimal", 10L, "qualitative", TRUE,
"basetheme", "royal", 10L, "qualitative", TRUE,
"basetheme", "void", 10L, "qualitative", TRUE,
"beyonce", "X1", 6L, "divergent", TRUE,
"beyonce", "X2", 6L, "sequential", TRUE,
"beyonce", "X3", 6L, "sequential", TRUE,
"beyonce", "X4", 6L, "qualitative", TRUE,
"beyonce", "X5", 6L, "qualitative", TRUE,
"beyonce", "X6", 6L, "divergent", TRUE,
"beyonce", "X7", 6L, "sequential", TRUE,
"beyonce", "X8", 6L, "sequential", TRUE,
"beyonce", "X9", 6L, "qualitative", TRUE,
"beyonce", "X10", 6L, "divergent", TRUE,
"beyonce", "X11", 6L, "qualitative", TRUE,
"beyonce", "X12", 6L, "qualitative", TRUE,
"beyonce", "X13", 6L, "qualitative", TRUE,
"beyonce", "X14", 6L, "qualitative", TRUE,
"beyonce", "X15", 6L, "qualitative", TRUE,
"beyonce", "X16", 6L, "sequential", TRUE,
"beyonce", "X17", 6L, "qualitative", TRUE,
"beyonce", "X18", 6L, "qualitative", TRUE,
"beyonce", "X19", 6L, "qualitative", TRUE,
"beyonce", "X20", 6L, "qualitative", TRUE,
"beyonce", "X21", 6L, "qualitative", TRUE,
"beyonce", "X22", 6L, "qualitative", TRUE,
"beyonce", "X23", 6L, "sequential", TRUE,
"beyonce", "X24", 4L, "sequential", TRUE,
"beyonce", "X25", 6L, "qualitative", TRUE,
"beyonce", "X26", 6L, "sequential", TRUE,
"beyonce", "X27", 6L, "qualitative", TRUE,
"beyonce", "X28", 6L, "sequential", TRUE,
"beyonce", "X29", 6L, "qualitative", TRUE,
"beyonce", "X30", 6L, "qualitative", TRUE,
"beyonce", "X31", 6L, "qualitative", TRUE,
"beyonce", "X32", 6L, "qualitative", TRUE,
"beyonce", "X33", 6L, "qualitative", TRUE,
"beyonce", "X34", 6L, "divergent", TRUE,
"beyonce", "X35", 6L, "qualitative", TRUE,
"beyonce", "X36", 6L, "qualitative", TRUE,
"beyonce", "X37", 6L, "qualitative", TRUE,
"beyonce", "X38", 6L, "qualitative", TRUE,
"beyonce", "X39", 6L, "divergent", TRUE,
"beyonce", "X40", 8L, "qualitative", TRUE,
"beyonce", "X41", 5L, "sequential", TRUE,
"beyonce", "X42", 6L, "qualitative", TRUE,
"beyonce", "X43", 6L, "qualitative", TRUE,
"beyonce", "X44", 6L, "qualitative", TRUE,
"beyonce", "X45", 6L, "qualitative", TRUE,
"beyonce", "X46", 6L, "divergent", TRUE,
"beyonce", "X47", 6L, "divergent", TRUE,
"beyonce", "X48", 6L, "qualitative", TRUE,
"beyonce", "X49", 6L, "qualitative", TRUE,
"beyonce", "X50", 6L, "sequential", TRUE,
"beyonce", "X51", 6L, "divergent", TRUE,
"beyonce", "X52", 6L, "sequential", TRUE,
"beyonce", "X53", 6L, "qualitative", TRUE,
"beyonce", "X54", 6L, "sequential", TRUE,
"beyonce", "X55", 7L, "sequential", TRUE,
"beyonce", "X56", 6L, "qualitative", TRUE,
"beyonce", "X57", 9L, "qualitative", TRUE,
"beyonce", "X58", 6L, "sequential", TRUE,
"beyonce", "X59", 9L, "sequential", TRUE,
"beyonce", "X60", 9L, "qualitative", TRUE,
"beyonce", "X61", 15L, "qualitative", TRUE,
"beyonce", "X62", 23L, "qualitative", TRUE,
"beyonce", "X63", 11L, "qualitative", TRUE,
"beyonce", "X64", 11L, "qualitative", TRUE,
"beyonce", "X65", 13L, "qualitative", TRUE,
"beyonce", "X66", 11L, "qualitative", TRUE,
"beyonce", "X67", 11L, "qualitative", TRUE,
"beyonce", "X68", 11L, "qualitative", TRUE,
"beyonce", "X69", 11L, "qualitative", TRUE,
"beyonce", "X70", 11L, "qualitative", TRUE,
"beyonce", "X71", 17L, "qualitative", TRUE,
"beyonce", "X72", 12L, "qualitative", TRUE,
"beyonce", "X73", 14L, "qualitative", TRUE,
"beyonce", "X74", 11L, "qualitative", TRUE,
"beyonce", "X75", 11L, "qualitative", TRUE,
"beyonce", "X76", 20L, "qualitative", TRUE,
"beyonce", "X77", 11L, "qualitative", TRUE,
"beyonce", "X78", 4L, "qualitative", TRUE,
"beyonce", "X79", 11L, "qualitative", TRUE,
"beyonce", "X80", 11L, "qualitative", TRUE,
"beyonce", "X81", 10L, "qualitative", TRUE,
"beyonce", "X82", 11L, "qualitative", TRUE,
"beyonce", "X83", 11L, "qualitative", TRUE,
"beyonce", "X84", 11L, "qualitative", TRUE,
"beyonce", "X85", 11L, "sequential", TRUE,
"beyonce", "X86", 11L, "sequential", TRUE,
"beyonce", "X87", 14L, "sequential", TRUE,
"beyonce", "X88", 12L, "qualitative", TRUE,
"beyonce", "X89", 11L, "qualitative", TRUE,
"beyonce", "X90", 11L, "qualitative", TRUE,
"beyonce", "X91", 6L, "qualitative", TRUE,
"beyonce", "X92", 8L, "qualitative", TRUE,
"beyonce", "X93", 31L, "qualitative", TRUE,
"beyonce", "X94", 14L, "qualitative", TRUE,
"beyonce", "X95", 20L, "qualitative", TRUE,
"beyonce", "X96", 20L, "qualitative", TRUE,
"beyonce", "X97", 19L, "qualitative", TRUE,
"beyonce", "X98", 16L, "qualitative", TRUE,
"beyonce", "X99", 19L, "qualitative", TRUE,
"beyonce", "X100", 14L, "qualitative", TRUE,
"beyonce", "X101", 6L, "qualitative", TRUE,
"beyonce", "X102", 6L, "qualitative", TRUE,
"beyonce", "X103", 5L, "sequential", TRUE,
"beyonce", "X104", 5L, "qualitative", TRUE,
"beyonce", "X105", 6L, "qualitative", TRUE,
"beyonce", "X106", 5L, "qualitative", TRUE,
"beyonce", "X107", 5L, "qualitative", TRUE,
"beyonce", "X108", 7L, "qualitative", TRUE,
"beyonce", "X109", 6L, "qualitative", TRUE,
"beyonce", "X110", 16L, "qualitative", TRUE,
"beyonce", "X111", 15L, "qualitative", TRUE,
"beyonce", "X112", 17L, "qualitative", TRUE,
"beyonce", "X113", 14L, "qualitative", TRUE,
"beyonce", "X114", 18L, "qualitative", TRUE,
"beyonce", "X115", 5L, "sequential", TRUE,
"beyonce", "X116", 21L, "qualitative", TRUE,
"beyonce", "X117", 16L, "qualitative", TRUE,
"beyonce", "X118", 10L, "qualitative", TRUE,
"beyonce", "X119", 7L, "qualitative", TRUE,
"beyonce", "X120", 10L, "qualitative", TRUE,
"beyonce", "X121", 6L, "qualitative", TRUE,
"beyonce", "X122", 6L, "qualitative", TRUE,
"beyonce", "X123", 6L, "qualitative", TRUE,
"beyonce", "X124", 6L, "divergent", TRUE,
"beyonce", "X125", 7L, "qualitative", TRUE,
"beyonce", "X126", 6L, "qualitative", TRUE,
"beyonce", "X127", 6L, "qualitative", TRUE,
"beyonce", "X128", 6L, "qualitative", TRUE,
"beyonce", "X129", 6L, "qualitative", TRUE,
"beyonce", "X130", 5L, "qualitative", TRUE,
"calecopal", "sierra1", 6L, "qualitative", TRUE,
"calecopal", "sierra2", 6L, "qualitative", TRUE,
"calecopal", "chaparral1", 6L, "qualitative", TRUE,
"calecopal", "chaparral2", 6L, "qualitative", TRUE,
"calecopal", "chaparral3", 5L, "sequential", TRUE,
"calecopal", "conifer", 5L, "qualitative", TRUE,
"calecopal", "desert", 5L, "sequential", TRUE,
"calecopal", "wetland", 5L, "qualitative", TRUE,
"calecopal", "oak", 5L, "qualitative", TRUE,
"calecopal", "kelp1", 6L, "qualitative", TRUE,
"calecopal", "kelp2", 5L, "qualitative", TRUE,
"calecopal", "coastaldune1", 5L, "qualitative", TRUE,
"calecopal", "coastaldune2", 5L, "qualitative", TRUE,
"calecopal", "superbloom1", 5L, "qualitative", TRUE,
"calecopal", "superbloom2", 5L, "qualitative", TRUE,
"calecopal", "superbloom3", 6L, "qualitative", TRUE,
"calecopal", "sbchannel", 5L, "sequential", TRUE,
"calecopal", "lake", 5L, "qualitative", TRUE,
"calecopal", "fire", 5L, "qualitative", TRUE,
"calecopal", "agriculture", 5L, "qualitative", TRUE,
"calecopal", "bigsur", 6L, "qualitative", TRUE,
"calecopal", "figmtn", 9L, "qualitative", TRUE,
"calecopal", "caqu", 5L, "qualitative", TRUE,
"calecopal", "eschscholzia", 5L, "sequential", TRUE,
"calecopal", "arbutus", 5L, "qualitative", TRUE,
"calecopal", "calochortus", 5L, "qualitative", TRUE,
"calecopal", "grassdry", 5L, "qualitative", TRUE,
"calecopal", "grasswet", 6L, "qualitative", TRUE,
"calecopal", "sage", 5L, "qualitative", TRUE,
"calecopal", "tidepool", 6L, "qualitative", TRUE,
"calecopal", "seagrass", 6L, "qualitative", TRUE,
"calecopal", "bigsur2", 6L, "qualitative", TRUE,
"calecopal", "bixby", 5L, "qualitative", TRUE,
"calecopal", "redwood1", 5L, "qualitative", TRUE,
"calecopal", "redwood2", 5L, "qualitative", TRUE,
"calecopal", "halfdome", 5L, "qualitative", TRUE,
"calecopal", "creek", 6L, "qualitative", TRUE,
"calecopal", "vermillion", 5L, "qualitative", TRUE,
"calecopal", "canary", 5L, "qualitative", TRUE,
"calecopal", "casj", 5L, "qualitative", TRUE,
"calecopal", "lupinus", 5L, "divergent", TRUE,
"calecopal", "dudleya", 5L, "qualitative", TRUE,
"calecopal", "gayophytum", 5L, "qualitative", TRUE,
"calecopal", "collinsia", 5L, "qualitative", TRUE,
"calecopal", "buow", 5L, "qualitative", TRUE,
"colorBlindness", "paletteMartin", 15L, "qualitative", FALSE,
"colorBlindness", "Blue2DarkOrange12Steps", 12L, "divergent", FALSE,
"colorBlindness", "Blue2DarkOrange18Steps", 18L, "divergent", FALSE,
"colorBlindness", "Blue2DarkRed12Steps", 12L, "divergent", FALSE,
"colorBlindness", "Blue2DarkRed18Steps", 18L, "divergent", FALSE,
"colorBlindness", "Blue2Gray8Steps", 8L, "divergent", FALSE,
"colorBlindness", "Blue2Green14Steps", 14L, "divergent", FALSE,
"colorBlindness", "Blue2Orange10Steps", 10L, "divergent", FALSE,
"colorBlindness", "Blue2Orange12Steps", 12L, "divergent", FALSE,
"colorBlindness", "Blue2Orange8Steps", 8L, "divergent", FALSE,
"colorBlindness", "Blue2OrangeRed14Steps", 14L, "divergent", FALSE,
"colorBlindness", "Brown2Blue10Steps", 10L, "divergent", FALSE,
"colorBlindness", "Brown2Blue12Steps", 12L, "divergent", FALSE,
"colorBlindness", "Green2Magenta16Steps", 16L, "divergent", FALSE,
"colorBlindness", "LightBlue2DarkBlue10Steps", 10L, "sequential", FALSE,
"colorBlindness", "LightBlue2DarkBlue7Steps", 7L, "sequential", FALSE,
"colorBlindness", "ModifiedSpectralScheme11Steps", 11L, "divergent", FALSE,
"colorBlindness", "PairedColor12Steps", 12L, "qualitative", FALSE,
"colorBlindness", "SteppedSequential5Steps", 25L, "qualitative", FALSE,
"colorblindr", "OkabeIto", 8L, "qualitative", FALSE,
"colorblindr", "OkabeIto_black", 8L, "qualitative", FALSE,
"colRoz", "grandis", 6L, "qualitative", TRUE,
"colRoz", "flavolineata", 6L, "qualitative", TRUE,
"colRoz", "whitei", 6L, "qualitative", TRUE,
"colRoz", "picta", 6L, "qualitative", TRUE,
"colRoz", "virgo", 6L, "qualitative", TRUE,
"colRoz", "ngadju", 6L, "qualitative", TRUE,
"colRoz", "c_decresii", 6L, "qualitative", TRUE,
"colRoz", "c_kingii", 5L, "qualitative", TRUE,
"colRoz", "e_leuraensis", 5L, "qualitative", TRUE,
"colRoz", "i_lesueurii", 5L, "qualitative", TRUE,
"colRoz", "l_boydii", 5L, "qualitative", TRUE,
"colRoz", "m_horridus", 5L, "qualitative", TRUE,
"colRoz", "m_horridus2", 5L, "qualitative", TRUE,
"colRoz", "t_nigrolutea", 6L, "qualitative", TRUE,
"colRoz", "v_acanthurus", 5L, "sequential", TRUE,
"colRoz", "v_pilbarensis", 5L, "qualitative", TRUE,
"colRoz", "n_levis", 6L, "qualitative", TRUE,
"colRoz", "s_spinigerus", 6L, "qualitative", TRUE,
"colRoz", "e_kingii", 6L, "qualitative", TRUE,
"colRoz", "uluru", 7L, "qualitative", TRUE,
"colRoz", "shark_bay", 6L, "qualitative", TRUE,
"colRoz", "sky", 6L, "sequential", TRUE,
"colRoz", "desert_sunset", 6L, "qualitative", TRUE,
"colRoz", "desert_dusk", 6L, "qualitative", TRUE,
"colRoz", "desert_flood", 6L, "qualitative", TRUE,
"colRoz", "salt_lake", 6L, "qualitative", TRUE,
"colRoz", "daintree", 5L, "qualitative", TRUE,
"colRoz", "spinifex", 6L, "qualitative", TRUE,
"colRoz", "nq_stream", 5L, "qualitative", TRUE,
"colRoz", "kimberley", 5L, "qualitative", TRUE,
"colRoz", "capricorn", 6L, "qualitative", TRUE,
"colRoz", "p_cincta", 6L, "qualitative", TRUE,
"colRoz", "c_azureus", 6L, "qualitative", TRUE,
"colRoz", "m_cyaneus", 5L, "qualitative", TRUE,
"colRoz", "d_novae", 6L, "qualitative", TRUE,
"colRoz", "a_ramsayi", 6L, "qualitative", TRUE,
"colRoz", "n_violacea", 6L, "divergent", TRUE,
"colRoz", "xantho", 6L, "qualitative", TRUE,
"colRoz", "r_aculeatus", 6L, "qualitative", TRUE,
"colRoz", "p_mitchelli", 5L, "qualitative", TRUE,
"colRoz", "k_tristis", 7L, "qualitative", TRUE,
"colRoz", "m_oscellata", 6L, "qualitative", TRUE,
"colRoz", "a_conica", 6L, "qualitative", TRUE,
"colRoz", "v_viatica", 5L, "qualitative", TRUE,
"colRoz", "c_brevi", 7L, "qualitative", TRUE,
"colRoz", "a_westwoodi", 6L, "qualitative", TRUE,
"colRoz", "a_plagiata", 6L, "sequential", TRUE,
"colRoz", "physalia", 6L, "qualitative", TRUE,
"colRoz", "c_australasiae", 6L, "qualitative", TRUE,
"colRoz", "k_scurra", 6L, "qualitative", TRUE,
"colRoz", "l_vestiens", 6L, "qualitative", TRUE,
"colRoz", "t_australis", 6L, "qualitative", TRUE,
"colRoz", "p_breviceps", 6L, "qualitative", TRUE,
"colRoz", "thylacine", 5L, "qualitative", TRUE,
"dichromat", "BrowntoBlue_10", 10L, "divergent", FALSE,
"dichromat", "BrowntoBlue_12", 12L, "divergent", FALSE,
"dichromat", "BluetoDarkOrange_12", 12L, "divergent", FALSE,
"dichromat", "BluetoDarkOrange_18", 18L, "divergent", FALSE,
"dichromat", "DarkRedtoBlue_12", 12L, "divergent", FALSE,
"dichromat", "DarkRedtoBlue_18", 18L, "divergent", FALSE,
"dichromat", "BluetoGreen_14", 14L, "divergent", FALSE,
"dichromat", "BluetoGray_8", 8L, "divergent", FALSE,
"dichromat", "BluetoOrangeRed_14", 14L, "divergent", FALSE,
"dichromat", "BluetoOrange_10", 10L, "divergent", FALSE,
"dichromat", "BluetoOrange_12", 12L, "divergent", FALSE,
"dichromat", "BluetoOrange_8", 8L, "divergent", FALSE,
"dichromat", "LightBluetoDarkBlue_10", 10L, "sequential", FALSE,
"dichromat", "LightBluetoDarkBlue_7", 7L, "sequential", FALSE,
"dichromat", "Categorical_12", 12L, "qualitative", FALSE,
"dichromat", "GreentoMagenta_16", 16L, "divergent", FALSE,
"dichromat", "SteppedSequential_5", 25L, "qualitative", FALSE,
"dutchmasters", "milkmaid", 13L, "qualitative", TRUE,
"dutchmasters", "pearl_earring", 11L, "qualitative", TRUE,
"dutchmasters", "view_of_Delft", 12L, "qualitative", TRUE,
"dutchmasters", "little_street", 11L, "qualitative", TRUE,
"dutchmasters", "anatomy", 7L, "qualitative", TRUE,
"dutchmasters", "staalmeesters", 7L, "qualitative", TRUE,
"DresdenColor", "stormfront", 6L, "qualitative", TRUE,
"DresdenColor", "foolmoon", 6L, "qualitative", TRUE,
"DresdenColor", "graveperil", 6L, "qualitative", TRUE,
"DresdenColor", "summerknight", 6L, "qualitative", TRUE,
"DresdenColor", "deathmasks", 6L, "qualitative", TRUE,
"DresdenColor", "bloodrites", 6L, "qualitative", TRUE,
"DresdenColor", "deadbeat", 6L, "qualitative", TRUE,
"DresdenColor", "provenguilty", 6L, "qualitative", TRUE,
"DresdenColor", "whitenight", 6L, "qualitative", TRUE,
"DresdenColor", "smallfavor", 6L, "qualitative", TRUE,
"DresdenColor", "turncoat", 6L, "qualitative", TRUE,
"DresdenColor", "changes", 6L, "qualitative", TRUE,
"DresdenColor", "ghoststory", 6L, "qualitative", TRUE,
"DresdenColor", "colddays", 6L, "qualitative", TRUE,
"DresdenColor", "skingame", 6L, "qualitative", TRUE,
"DresdenColor", "sidejobs", 6L, "qualitative", TRUE,
"DresdenColor", "briefcases", 6L, "qualitative", TRUE,
"DresdenColor", "paired", 12L, "qualitative", TRUE,
"fishualize", "Acanthisthius_brasilianus", 5L, "qualitative", TRUE,
"fishualize", "Acanthostracion_polygonius", 5L, "sequential", TRUE,
"fishualize", "Acanthostracion_polygonius_y", 5L, "qualitative", TRUE,
"fishualize", "Acanthurus_chirurgus", 5L, "qualitative", TRUE,
"fishualize", "Acanthurus_coeruleus", 5L, "qualitative", TRUE,
"fishualize", "Acanthurus_leucosternon", 5L, "qualitative", TRUE,
"fishualize", "Acanthurus_olivaceus", 5L, "qualitative", TRUE,
"fishualize", "Acanthurus_sohal", 5L, "qualitative", TRUE,
"fishualize", "Acanthurus_triostegus", 5L, "sequential", TRUE,
"fishualize", "Alosa_fallax", 5L, "qualitative", TRUE,
"fishualize", "Aluterus_scriptus", 5L, "sequential", TRUE,
"fishualize", "Anchoviella_lepidentostole", 5L, "qualitative", TRUE,
"fishualize", "Anisotremus_virginicus", 5L, "qualitative", TRUE,
"fishualize", "Antennarius_commerson", 5L, "qualitative", TRUE,
"fishualize", "Antennarius_multiocellatus", 5L, "sequential", TRUE,
"fishualize", "Atherinella_brasiliensis", 5L, "qualitative", TRUE,
"fishualize", "Aulostomus_chinensis", 5L, "qualitative", TRUE,
"fishualize", "Balistapus_undulatus", 5L, "qualitative", TRUE,
"fishualize", "Balistes_vetula", 5L, "qualitative", TRUE,
"fishualize", "Balistoides_conspicillum", 5L, "qualitative", TRUE,
"fishualize", "Barbus_barbus", 5L, "qualitative", TRUE,
"fishualize", "Bodianus_pulchellus", 5L, "qualitative", TRUE,
"fishualize", "Bodianus_rufus", 5L, "qualitative", TRUE,
"fishualize", "Bryaninops_natans", 5L, "qualitative", TRUE,
"fishualize", "Callanthias_australis", 5L, "qualitative", TRUE,
"fishualize", "Cantherhines_macrocerus", 5L, "qualitative", TRUE,
"fishualize", "Centropyge_loricula", 5L, "qualitative", TRUE,
"fishualize", "Cephalopholis_argus", 5L, "qualitative", TRUE,
"fishualize", "Cephalopholis_fulva", 5L, "qualitative", TRUE,
"fishualize", "Cetengraulis_edentulus", 5L, "qualitative", TRUE,
"fishualize", "Chaetodon_ephippium", 5L, "qualitative", TRUE,
"fishualize", "Chaetodon_larvatus", 5L, "qualitative", TRUE,
"fishualize", "Chaetodon_pelewensis", 5L, "qualitative", TRUE,
"fishualize", "Chaetodon_sedentarius", 5L, "qualitative", TRUE,
"fishualize", "Chaetodontoplus_conspicillatus", 5L, "qualitative", TRUE,
"fishualize", "Chlorurus_microrhinos", 5L, "qualitative", TRUE,
"fishualize", "Chlorurus_spilurus", 5L, "qualitative", TRUE,
"fishualize", "Chormis_multilineata", 5L, "qualitative", TRUE,
"fishualize", "Chromis_vanderbilti", 5L, "qualitative", TRUE,
"fishualize", "Cirrhilabrus_solorensis", 5L, "qualitative", TRUE,
"fishualize", "Cirrhilabrus_tonozukai", 5L, "qualitative", TRUE,
"fishualize", "Clepticus_brasiliensis", 5L, "qualitative", TRUE,
"fishualize", "Clepticus_parrae", 5L, "qualitative", TRUE,
"fishualize", "Coris_gaimard", 5L, "qualitative", TRUE,
"fishualize", "Coryphaena_hippurus", 5L, "qualitative", TRUE,
"fishualize", "Dermatolepis_inermis", 5L, "qualitative", TRUE,
"fishualize", "Elacatinus_figaro", 5L, "qualitative", TRUE,
"fishualize", "Elagatis_bipinnulata", 5L, "qualitative", TRUE,
"fishualize", "Epibulus_insidiator", 5L, "qualitative", TRUE,
"fishualize", "Epinephelus_fasciatus", 5L, "qualitative", TRUE,
"fishualize", "Epinephelus_lanceolatus", 5L, "qualitative", TRUE,
"fishualize", "Epinephelus_marginatus", 5L, "qualitative", TRUE,
"fishualize", "Epinephelus_striatus", 5L, "sequential", TRUE,
"fishualize", "Esox_lucius", 5L, "sequential", TRUE,
"fishualize", "Etheostoma_barrenense", 5L, "qualitative", TRUE,
"fishualize", "Etheostoma_spectabile", 5L, "qualitative", TRUE,
"fishualize", "Exallias_brevis", 5L, "qualitative", TRUE,
"fishualize", "Forcipiger_longirostris", 5L, "qualitative", TRUE,
"fishualize", "Gadus_morhua", 5L, "qualitative", TRUE,
"fishualize", "Ginglymostoma_cirratum", 5L, "qualitative", TRUE,
"fishualize", "Gomphosus_varius", 5L, "qualitative", TRUE,
"fishualize", "Gramma_brasiliensis", 5L, "qualitative", TRUE,
"fishualize", "Gramma_loreto", 5L, "qualitative", TRUE,
"fishualize", "Gymnothorax_funebris", 5L, "qualitative", TRUE,
"fishualize", "Haemulon_squamipinna", 5L, "qualitative", TRUE,
"fishualize", "Halichoeres_bivittatus", 5L, "qualitative", TRUE,
"fishualize", "Halichoeres_brasiliensis", 5L, "sequential", TRUE,
"fishualize", "Halichoeres_dimidiatus", 5L, "qualitative", TRUE,
"fishualize", "Halichoeres_garnoti", 5L, "qualitative", TRUE,
"fishualize", "Halichoeres_radiatus", 5L, "qualitative", TRUE,
"fishualize", "Hamulon_plumieri", 5L, "qualitative", TRUE,
"fishualize", "Harengula_jaguana", 5L, "qualitative", TRUE,
"fishualize", "Hemitaurichthys_polylepis", 5L, "qualitative", TRUE,
"fishualize", "Heretopriacanthus_cruentatus", 5L, "qualitative", TRUE,
"fishualize", "Hexagrammos_lagocephalus", 5L, "qualitative", TRUE,
"fishualize", "Hippocampus_reidi", 5L, "qualitative", TRUE,
"fishualize", "Histiophryne_psychedelica", 5L, "qualitative", TRUE,
"fishualize", "Holacanthus_ciliaris", 5L, "qualitative", TRUE,
"fishualize", "Holocentrus_adscensionis", 5L, "qualitative", TRUE,
"fishualize", "Hypleurochilus_fissicornis", 5L, "qualitative", TRUE,
"fishualize", "Hypoplectrus_puella", 5L, "qualitative", TRUE,
"fishualize", "Hypsoblennius_invemar", 5L, "qualitative", TRUE,
"fishualize", "Hypsypops_rubicundus", 5L, "qualitative", TRUE,
"fishualize", "Koumansetta_rainfordi", 5L, "qualitative", TRUE,
"fishualize", "Labrisomus_cricota", 5L, "qualitative", TRUE,
"fishualize", "Labrisomus_nuchipinnis", 5L, "qualitative", TRUE,
"fishualize", "Lampris_guttatus", 5L, "qualitative", TRUE,
"fishualize", "Lepomis_megalotis", 5L, "qualitative", TRUE,
"fishualize", "Lile_piquitinga", 5L, "qualitative", TRUE,
"fishualize", "Lutjanus_jocu", 5L, "qualitative", TRUE,
"fishualize", "Lutjanus_sebae", 5L, "qualitative", TRUE,
"fishualize", "Lycengraulis_grossidens", 5L, "qualitative", TRUE,
"fishualize", "Melichthys_vidua", 5L, "qualitative", TRUE,
"fishualize", "Micropterus_punctulatus", 5L, "qualitative", TRUE,
"fishualize", "Minilabrus_striatus", 5L, "qualitative", TRUE,
"fishualize", "Mugil_liza", 5L, "qualitative", TRUE,
"fishualize", "Mycteroperca_bonaci", 5L, "qualitative", TRUE,
"fishualize", "Myrichthys_ocellatus", 5L, "qualitative", TRUE,
"fishualize", "Naso_lituratus", 5L, "qualitative", TRUE,
"fishualize", "Nemateleotris_magnifica", 5L, "qualitative", TRUE,
"fishualize", "Neogobius_melanostomus", 5L, "qualitative", TRUE,
"fishualize", "Odonus_niger", 5L, "qualitative", TRUE,
"fishualize", "Oncorhynchus_gorbuscha", 5L, "qualitative", TRUE,
"fishualize", "Oncorhynchus_keta", 5L, "qualitative", TRUE,
"fishualize", "Oncorhynchus_kisutch", 5L, "qualitative", TRUE,
"fishualize", "Oncorhynchus_mykiss", 5L, "qualitative", TRUE,
"fishualize", "Oncorhynchus_nerka", 5L, "qualitative", TRUE,
"fishualize", "Oncorhynchus_tshawytscha", 5L, "qualitative", TRUE,
"fishualize", "Opisthonema_oglinum", 5L, "qualitative", TRUE,
"fishualize", "Ostorhinchus_angustatus", 5L, "qualitative", TRUE,
"fishualize", "Ostracion_cubicus", 5L, "sequential", TRUE,
"fishualize", "Ostracion_whitleyi", 5L, "sequential", TRUE,
"fishualize", "Oxymonacanthus_longirostris", 5L, "qualitative", TRUE,
"fishualize", "Parablennius_marmoreus", 5L, "qualitative", TRUE,
"fishualize", "Parablennius_pilicornis", 5L, "qualitative", TRUE,
"fishualize", "Paracanthurus_hepatus", 5L, "qualitative", TRUE,
"fishualize", "Paralabrax_clathratus", 5L, "sequential", TRUE,
"fishualize", "Paranthias_furcifer", 5L, "qualitative", TRUE,
"fishualize", "Pareiorhaphis_garbei", 5L, "qualitative", TRUE,
"fishualize", "Parupeneus_insularis", 5L, "qualitative", TRUE,
"fishualize", "Petromyzon_marinus", 5L, "sequential", TRUE,
"fishualize", "Phractocephalus_hemioliopterus", 5L, "qualitative", TRUE,
"fishualize", "Pleuronectes_platessa", 5L, "qualitative", TRUE,
"fishualize", "Pomacanthus_imperator", 5L, "qualitative", TRUE,
"fishualize", "Pomacanthus_paru", 5L, "qualitative", TRUE,
"fishualize", "Pomacanthus_xanthometopon", 5L, "qualitative", TRUE,
"fishualize", "Prionace_glauca", 5L, "qualitative", TRUE,
"fishualize", "Prognathodes_brasiliensis", 5L, "qualitative", TRUE,
"fishualize", "Prognathodes_guyanensis", 5L, "qualitative", TRUE,
"fishualize", "Pronotogrammus_martinicensis", 5L, "qualitative", TRUE,
"fishualize", "Pseudocheilinus_tetrataenia", 5L, "qualitative", TRUE,
"fishualize", "Pseudochromis_aldabraensis", 5L, "qualitative", TRUE,
"fishualize", "Pseudupeneus_maculatus", 5L, "qualitative", TRUE,
"fishualize", "Pterois_volitans", 5L, "qualitative", TRUE,
"fishualize", "Rhinecanthus_aculeatus", 5L, "qualitative", TRUE,
"fishualize", "Rhinecanthus_assasi", 5L, "qualitative", TRUE,
"fishualize", "Salmo_salar", 5L, "qualitative", TRUE,
"fishualize", "Salmo_trutta", 5L, "qualitative", TRUE,
"fishualize", "Salvelinus_fontinalis", 5L, "qualitative", TRUE,
"fishualize", "Sander_lucioperca", 5L, "qualitative", TRUE,
"fishualize", "Sardinella_brasiliensis", 5L, "qualitative", TRUE,
"fishualize", "Sargocentron_bullisi", 5L, "qualitative", TRUE,
"fishualize", "Scarus_ghobban", 5L, "qualitative", TRUE,
"fishualize", "Scarus_globiceps", 5L, "qualitative", TRUE,
"fishualize", "Scarus_hoefleri", 5L, "qualitative", TRUE,
"fishualize", "Scarus_quoyi", 5L, "qualitative", TRUE,
"fishualize", "Scarus_tricolor", 5L, "qualitative", TRUE,
"fishualize", "Scarus_zelindae", 5L, "qualitative", TRUE,
"fishualize", "Semicossyphus_pulcher", 5L, "sequential", TRUE,
"fishualize", "Serranus_baldwini", 5L, "qualitative", TRUE,
"fishualize", "Serranus_scriba", 5L, "qualitative", TRUE,
"fishualize", "Sparisoma_frondosum_m", 5L, "qualitative", TRUE,
"fishualize", "Sparisoma_tuyupiranga_f", 5L, "qualitative", TRUE,
"fishualize", "Sparisoma_tuyupiranga_m", 5L, "qualitative", TRUE,
"fishualize", "Sparisoma_viride", 5L, "qualitative", TRUE,
"fishualize", "Stegastes_nigricans", 5L, "qualitative", TRUE,
"fishualize", "Stegastes_partitus", 5L, "qualitative", TRUE,
"fishualize", "Stegastes_variabilis", 5L, "qualitative", TRUE,
"fishualize", "Stethojulis_bandanensis", 5L, "qualitative", TRUE,
"fishualize", "Synchiropus_splendidus", 5L, "qualitative", TRUE,
"fishualize", "Taeniura_lymma", 5L, "qualitative", TRUE,
"fishualize", "Thalassoma_bifasciatum", 5L, "qualitative", TRUE,
"fishualize", "Thalassoma_hardwicke", 5L, "qualitative", TRUE,
"fishualize", "Thalassoma_noronhanum", 5L, "qualitative", TRUE,
"fishualize", "Thalassoma_pavo", 5L, "qualitative", TRUE,
"fishualize", "Thunnus_obesus", 5L, "qualitative", TRUE,
"fishualize", "Trimma_lantana", 5L, "qualitative", TRUE,
"fishualize", "Valenciennea_strigata", 5L, "qualitative", TRUE,
"fishualize", "Variola_louti", 5L, "qualitative", TRUE,
"fishualize", "Xyrichthys_novacula", 5L, "qualitative", TRUE,
"fishualize", "Zanclus_cornutus", 5L, "qualitative", TRUE,
"fishualize", "Zapteryx_brevirostris", 5L, "qualitative", TRUE,
"fishualize", "Zebrasoma_velifer", 5L, "qualitative", TRUE,
"fishualize", "Zebrasoma_xanthurum", 5L, "qualitative", TRUE,
"futurevisions", "venus", 5L, "qualitative", TRUE,
"futurevisions", "earth", 7L, "qualitative", TRUE,
"futurevisions", "mars", 6L, "qualitative", TRUE,
"futurevisions", "jupiter", 6L, "qualitative", TRUE,
"futurevisions", "ceres", 4L, "sequential", TRUE,
"futurevisions", "enceladus", 5L, "qualitative", TRUE,
"futurevisions", "europa", 5L, "sequential", TRUE,
"futurevisions", "titan", 6L, "sequential", TRUE,
"futurevisions", "cancri", 6L, "sequential", TRUE,
"futurevisions", "hd", 6L, "qualitative", TRUE,
"futurevisions", "kepler186", 9L, "divergent", TRUE,
"futurevisions", "kepler16b", 7L, "qualitative", TRUE,
"futurevisions", "pegasi", 8L, "qualitative", TRUE,
"futurevisions", "pso", 5L, "sequential", TRUE,
"futurevisions", "trappest", 8L, "qualitative", TRUE,
"futurevisions", "grand_tour", 7L, "qualitative", TRUE,
"futurevisions", "atomic_clock", 5L, "qualitative", TRUE,
"futurevisions", "atomic_red", 3L, "qualitative", TRUE,
"futurevisions", "atomic_blue", 3L, "qualitative", TRUE,
"futurevisions", "atomic_orange", 3L, "qualitative", TRUE,
"ggsci", "nrc_npg", 10L, "qualitative", TRUE,
"ggsci", "default_aaas", 10L, "qualitative", TRUE,
"ggsci", "default_nejm", 8L, "qualitative", TRUE,
"ggsci", "lanonc_lancet", 9L, "qualitative", TRUE,
"ggsci", "default_jama", 7L, "qualitative", TRUE,
"ggsci", "default_jco", 10L, "qualitative", TRUE,
"ggsci", "default_ucscgb", 26L, "qualitative", FALSE,
"ggsci", "category10_d3", 10L, "qualitative", FALSE,
"ggsci", "category20_d3", 20L, "qualitative", FALSE,
"ggsci", "category20b_d3", 20L, "qualitative", FALSE,
"ggsci", "category20c_d3", 20L, "qualitative", FALSE,
"ggsci", "default_igv", 51L, "qualitative", FALSE,
"ggsci", "alternating_igv", 2L, "qualitative", FALSE,
"ggsci", "default_locuszoom", 7L, "qualitative", TRUE,
"ggsci", "default_uchicago", 9L, "qualitative", TRUE,
"ggsci", "light_uchicago", 9L, "qualitative", TRUE,
"ggsci", "dark_uchicago", 9L, "qualitative", TRUE,
"ggsci", "hallmarks_dark_cosmic", 10L, "qualitative", TRUE,
"ggsci", "hallmarks_light_cosmic", 10L, "qualitative", TRUE,
"ggsci", "signature_substitutions_cosmic", 6L, "qualitative", TRUE,
"ggsci", "springfield_simpsons", 16L, "qualitative", TRUE,
"ggsci", "planetexpress_futurama", 12L, "qualitative", TRUE,
"ggsci", "schwifty_rickandmorty", 12L, "qualitative", TRUE,
"ggsci", "uniform_startrek", 7L, "qualitative", TRUE,
"ggsci", "legacy_tron", 7L, "qualitative", TRUE,
"ggsci", "default_gsea", 12L, "divergent", FALSE,
"ggsci", "red_material", 10L, "sequential", FALSE,
"ggsci", "pink_material", 10L, "sequential", FALSE,
"ggsci", "purple_material", 10L, "sequential", FALSE,
"ggsci", "deep_purple_material", 10L, "sequential", FALSE,
"ggsci", "indigo_material", 10L, "sequential", FALSE,
"ggsci", "blue_material", 10L, "sequential", FALSE,
"ggsci", "light_blue_material", 10L, "sequential", FALSE,
"ggsci", "cyan_material", 10L, "sequential", FALSE,
"ggsci", "teal_material", 10L, "sequential", FALSE,
"ggsci", "green_material", 10L, "sequential", FALSE,
"ggsci", "light_green_material", 10L, "sequential", FALSE,
"ggsci", "lime_material", 10L, "sequential", FALSE,
"ggsci", "yellow_material", 10L, "sequential", FALSE,
"ggsci", "amber_material", 10L, "sequential", FALSE,
"ggsci", "orange_material", 10L, "sequential", FALSE,
"ggsci", "deep_orange_material", 10L, "sequential", FALSE,
"ggsci", "brown_material", 10L, "sequential", FALSE,
"ggsci", "grey_material", 10L, "sequential", FALSE,
"ggsci", "blue_grey_material", 10L, "sequential", FALSE,
"ggpomological", "pomological_base", 7L, "qualitative", TRUE,
"ggpomological", "pomological_palette", 9L, "qualitative", TRUE,
"ggprism", "autumn_leaves", 9L, "qualitative", TRUE,
"ggprism", "beer_and_ales", 9L, "qualitative", TRUE,
"ggprism", "black_and_white", 9L, "qualitative", TRUE,
"ggprism", "blueprint", 9L, "qualitative", TRUE,
"ggprism", "blueprint2", 9L, "qualitative", TRUE,
"ggprism", "blueprint3", 9L, "qualitative", TRUE,
"ggprism", "candy_bright", 9L, "qualitative", TRUE,
"ggprism", "candy_soft", 9L, "qualitative", TRUE,
"ggprism", "colorblind_safe", 6L, "qualitative", TRUE,
"ggprism", "colors", 20L, "qualitative", TRUE,
"ggprism", "diazo", 9L, "qualitative", TRUE,
"ggprism", "earth_tones", 10L, "qualitative", TRUE,
"ggprism", "evergreen", 9L, "qualitative", TRUE,
"ggprism", "fir", 9L, "qualitative", TRUE,
"ggprism", "fir2", 9L, "qualitative", TRUE,
"ggprism", "fir3", 9L, "qualitative", TRUE,
"ggprism", "flames", 9L, "qualitative", TRUE,
"ggprism", "flames2", 9L, "qualitative", TRUE,
"ggprism", "floral", 12L, "qualitative", TRUE,
"ggprism", "floral2", 12L, "qualitative", TRUE,
"ggprism", "greenwash", 10L, "qualitative", TRUE,
"ggprism", "inferno", 6L, "sequential", TRUE,
"ggprism", "magma", 6L, "sequential", TRUE,
"ggprism", "mustard_field", 9L, "qualitative", TRUE,
"ggprism", "mustard_field2", 9L, "qualitative", TRUE,
"ggprism", "muted_rainbow", 10L, "qualitative", TRUE,
"ggprism", "neon", 9L, "qualitative", TRUE,
"ggprism", "ocean", 9L, "qualitative", TRUE,
"ggprism", "ocean2", 9L, "qualitative", TRUE,
"ggprism", "ocean3", 9L, "qualitative", TRUE,
"ggprism", "office", 9L, "qualitative", TRUE,
"ggprism", "pastels", 9L, "qualitative", TRUE,
"ggprism", "pearl", 6L, "qualitative", TRUE,
"ggprism", "pearl2", 6L, "qualitative", TRUE,
"ggprism", "plasma", 6L, "sequential", TRUE,
"ggprism", "prism_dark", 10L, "qualitative", TRUE,
"ggprism", "prism_dark2", 10L, "qualitative", TRUE,
"ggprism", "prism_light", 10L, "qualitative", TRUE,
"ggprism", "prism_light2", 10L, "qualitative", TRUE,
"ggprism", "purple_passion", 9L, "qualitative", TRUE,
"ggprism", "quiet", 9L, "qualitative", TRUE,
"ggprism", "quiet2", 9L, "qualitative", TRUE,
"ggprism", "shades_of_gray", 9L, "qualitative", TRUE,
"ggprism", "spring", 9L, "qualitative", TRUE,
"ggprism", "spring2", 9L, "qualitative", TRUE,
"ggprism", "stained_glass", 9L, "qualitative", TRUE,
"ggprism", "stained_glass2", 9L, "qualitative", TRUE,
"ggprism", "starry", 5L, "qualitative", TRUE,
"ggprism", "starry2", 5L, "qualitative", TRUE,
"ggprism", "summer", 10L, "qualitative", TRUE,
"ggprism", "sunny_garden", 9L, "qualitative", TRUE,
"ggprism", "sunny_garden2", 9L, "qualitative", TRUE,
"ggprism", "sunny_garden3", 9L, "qualitative", TRUE,
"ggprism", "the_blues", 9L, "qualitative", TRUE,
"ggprism", "viridis", 6L, "sequential", TRUE,
"ggprism", "warm_and_sunny", 9L, "qualitative", TRUE,
"ggprism", "warm_pastels", 9L, "qualitative", TRUE,
"ggprism", "warm_pastels2", 9L, "qualitative", TRUE,
"ggprism", "waves", 5L, "qualitative", TRUE,
"ggprism", "waves2", 5L, "qualitative", TRUE,
"ggprism", "winter_bright", 9L, "qualitative", TRUE,
"ggprism", "winter_soft", 9L, "qualitative", TRUE,
"ggprism", "wool_muffler", 9L, "qualitative", TRUE,
"ggprism", "wool_muffler2", 9L, "qualitative", TRUE,
"ggprism", "wool_muffler3", 9L, "qualitative", TRUE,
"ggthemes", "calc", 12L, "qualitative", TRUE,
"ggthemes", "manyeys", 19L, "qualitative", TRUE,
"ggthemes", "gdoc", 10L, "qualitative", TRUE,
"ggthemes", "fivethirtyeight", 6L, "qualitative", TRUE,
"ggthemes", "colorblind", 8L, "qualitative", FALSE,
"ggthemes", "Tableau_10", 10L, "qualitative", FALSE,
"ggthemes", "Tableau_20", 20L, "qualitative", FALSE,
"ggthemes", "Color_Blind", 10L, "qualitative", FALSE,
"ggthemes", "Seattle_Grays", 5L, "qualitative", TRUE,
"ggthemes", "Traffic", 9L, "qualitative", TRUE,
"ggthemes", "Miller_Stone", 11L, "qualitative", TRUE,
"ggthemes", "Superfishel_Stone", 10L, "qualitative", TRUE,
"ggthemes", "Nuriel_Stone", 9L, "qualitative", TRUE,
"ggthemes", "Jewel_Bright", 9L, "qualitative", TRUE,
"ggthemes", "Summer", 8L, "qualitative", TRUE,
"ggthemes", "Winter", 10L, "qualitative", TRUE,
"ggthemes", "Green_Orange_Teal", 12L, "qualitative", TRUE,
"ggthemes", "Red_Blue_Brown", 12L, "qualitative", TRUE,
"ggthemes", "Purple_Pink_Gray", 12L, "qualitative", TRUE,
"ggthemes", "Hue_Circle", 19L, "qualitative", TRUE,
"ggthemes", "Classic_10", 10L, "qualitative", FALSE,
"ggthemes", "Classic_10_Medium", 10L, "qualitative", FALSE,
"ggthemes", "Classic_10_Light", 10L, "qualitative", FALSE,
"ggthemes", "Classic_20", 20L, "qualitative", FALSE,
"ggthemes", "Classic_Gray_5", 5L, "qualitative", FALSE,
"ggthemes", "Classic_Color_Blind", 10L, "qualitative", FALSE,
"ggthemes", "Classic_Traffic_Light", 9L, "qualitative", FALSE,
"ggthemes", "Classic_Purple_Gray_6", 6L, "qualitative", FALSE,
"ggthemes", "Classic_Purple_Gray_12", 12L, "qualitative", FALSE,
"ggthemes", "Classic_Green_Orange_6", 6L, "qualitative", FALSE,
"ggthemes", "Classic_Green_Orange_12", 12L, "qualitative", FALSE,
"ggthemes", "Classic_Blue_Red_6", 6L, "qualitative", FALSE,
"ggthemes", "Classic_Blue_Red_12", 12L, "qualitative", FALSE,
"ggthemes", "Classic_Cyclic", 13L, "qualitative", FALSE,
"ggthemes", "few_Light", 9L, "qualitative", FALSE,
"ggthemes", "few_Medium", 9L, "qualitative", FALSE,
"ggthemes", "few_Dark", 9L, "qualitative", FALSE,
"ggthemes", "excel_Atlas", 6L, "qualitative", FALSE,
"ggthemes", "excel_Badge", 6L, "qualitative", FALSE,
"ggthemes", "excel_Berlin", 6L, "qualitative", FALSE,
"ggthemes", "excel_Celestial", 6L, "qualitative", FALSE,
"ggthemes", "excel_Crop", 6L, "qualitative", FALSE,
"ggthemes", "excel_Depth", 6L, "qualitative", FALSE,
"ggthemes", "excel_Droplet", 6L, "qualitative", FALSE,
"ggthemes", "excel_Facet", 6L, "qualitative", FALSE,
"ggthemes", "excel_Feathered", 6L, "qualitative", FALSE,
"ggthemes", "excel_Gallery", 6L, "qualitative", FALSE,
"ggthemes", "excel_Headlines", 6L, "qualitative", TRUE,
"ggthemes", "excel_Integral", 6L, "qualitative", TRUE,
"ggthemes", "excel_Ion_Boardroom", 6L, "qualitative", TRUE,
"ggthemes", "excel_Ion", 6L, "qualitative", TRUE,
"ggthemes", "excel_Madison", 6L, "qualitative", TRUE,
"ggthemes", "excel_Main_Event", 6L, "qualitative", TRUE,
"ggthemes", "excel_Mesh", 6L, "qualitative", TRUE,
"ggthemes", "excel_Office_Theme", 6L, "qualitative", TRUE,
"ggthemes", "excel_Organic", 6L, "qualitative", TRUE,
"ggthemes", "excel_Parallax", 6L, "qualitative", TRUE,
"ggthemes", "excel_Parcel", 6L, "qualitative", TRUE,
"ggthemes", "excel_Retrospect", 6L, "qualitative", TRUE,
"ggthemes", "excel_Savon", 6L, "qualitative", TRUE,
"ggthemes", "excel_Slice", 6L, "qualitative", TRUE,
"ggthemes", "excel_Vapor_Trail", 6L, "qualitative", TRUE,
"ggthemes", "excel_View", 6L, "qualitative", TRUE,
"ggthemes", "excel_Wisp", 6L, "qualitative", TRUE,
"ggthemes", "excel_Wood_Type", 6L, "qualitative", TRUE,
"ggthemes", "excel_Aspect", 6L, "qualitative", TRUE,
"ggthemes", "excel_Blue_Green", 6L, "qualitative", TRUE,
"ggthemes", "excel_Blue_II", 6L, "qualitative", TRUE,
"ggthemes", "excel_Blue_Warm", 6L, "qualitative", TRUE,
"ggthemes", "excel_Blue", 6L, "qualitative", TRUE,
"ggthemes", "excel_Grayscale", 6L, "sequential", FALSE,
"ggthemes", "excel_Green_Yellow", 6L, "qualitative", TRUE,
"ggthemes", "excel_Green", 6L, "qualitative", TRUE,
"ggthemes", "excel_Marquee", 6L, "qualitative", TRUE,
"ggthemes", "excel_Median", 6L, "qualitative", TRUE,
"ggthemes", "excel_Office_2007_2010", 6L, "qualitative", TRUE,
"ggthemes", "excel_Orange_Red", 6L, "qualitative", TRUE,
"ggthemes", "excel_Orange", 6L, "qualitative", TRUE,
"ggthemes", "excel_Paper", 6L, "qualitative", TRUE,
"ggthemes", "excel_Red_Orange", 6L, "qualitative", TRUE,
"ggthemes", "excel_Red_Violet", 6L, "qualitative", TRUE,
"ggthemes", "excel_Red", 6L, "qualitative", TRUE,
"ggthemes", "excel_Slipstream", 6L, "qualitative", TRUE,
"ggthemes", "excel_Violet_II", 6L, "qualitative", TRUE,
"ggthemes", "excel_Violet", 6L, "qualitative", TRUE,
"ggthemes", "excel_Yellow_Orange", 6L, "qualitative", TRUE,
"ggthemes", "excel_Yellow", 6L, "qualitative", TRUE,
"ggthemes", "wsj_rgby", 4L, "qualitative", TRUE,
"ggthemes", "wsj_red_green", 2L, "qualitative", TRUE,
"ggthemes", "wsj_black_green", 4L, "qualitative", TRUE,
"ggthemes", "wsj_dem_rep", 3L, "qualitative", TRUE,
"ggthemes", "wsj_colors6", 6L, "qualitative", TRUE,
"ggthemes", "stata_s2color", 15L, "qualitative", TRUE,
"ggthemes", "stata_s1rcolor", 15L, "qualitative", TRUE,
"ggthemes", "stata_s1color", 15L, "qualitative", TRUE,
"ggthemes", "stata_mono", 15L, "qualitative", TRUE,
"ggthemes", "stata_economist", 15L, "qualitative", TRUE,
"ggthemes", "hc_default", 10L, "qualitative", TRUE,
"ggthemes", "hc_darkunica", 11L, "qualitative", TRUE,
"ggthemes", "hc_bg", 5L, "qualitative", TRUE,
"ggthemes", "hc_fg", 12L, "qualitative", TRUE,
"ggthemr", "flat", 9L, "qualitative", TRUE,
"ggthemr", "flat_dark", 9L, "qualitative", TRUE,
"ggthemr", "dust", 9L, "qualitative", TRUE,
"ggthemr", "light", 9L, "qualitative", TRUE,
"ggthemr", "earth", 9L, "qualitative", TRUE,
"ggthemr", "fresh", 9L, "qualitative", TRUE,
"ggthemr", "chalk", 7L, "qualitative", TRUE,
"ggthemr", "lilac", 11L, "qualitative", TRUE,
"ggthemr", "carrot", 9L, "qualitative", TRUE,
"ggthemr", "pale", 10L, "qualitative", TRUE,
"ggthemr", "copper", 11L, "qualitative", TRUE,
"ggthemr", "grape", 9L, "qualitative", TRUE,
"ggthemr", "greyscale", 9L, "qualitative", TRUE,
"ggthemr", "sky", 6L, "qualitative", TRUE,
"ggthemr", "solarized", 7L, "qualitative", TRUE,
"ggthemr", "grass", 7L, "qualitative", TRUE,
"ggthemr", "sea", 11L, "qualitative", TRUE,
"ggthemr", "camouflage", 7L, "qualitative", TRUE,
"ghibli", "MarnieLight1", 7L, "qualitative", TRUE,
"ghibli", "MarnieMedium1", 7L, "qualitative", TRUE,
"ghibli", "MarnieDark1", 7L, "qualitative", TRUE,
"ghibli", "MarnieLight2", 7L, "qualitative", TRUE,
"ghibli", "MarnieMedium2", 7L, "qualitative", TRUE,
"ghibli", "MarnieDark2", 7L, "qualitative", TRUE,
"ghibli", "PonyoLight", 7L, "qualitative", TRUE,
"ghibli", "PonyoMedium", 7L, "qualitative", TRUE,
"ghibli", "PonyoDark", 7L, "qualitative", TRUE,
"ghibli", "LaputaLight", 7L, "qualitative", TRUE,
"ghibli", "LaputaMedium", 7L, "qualitative", TRUE,
"ghibli", "LaputaDark", 7L, "qualitative", TRUE,
"ghibli", "MononokeLight", 7L, "qualitative", TRUE,
"ghibli", "MononokeMedium", 7L, "qualitative", TRUE,
"ghibli", "MononokeDark", 7L, "qualitative", TRUE,
"ghibli", "SpiritedLight", 7L, "qualitative", TRUE,
"ghibli", "SpiritedMedium", 7L, "qualitative", TRUE,
"ghibli", "SpiritedDark", 7L, "qualitative", TRUE,
"ghibli", "YesterdayLight", 7L, "qualitative", TRUE,
"ghibli", "YesterdayMedium", 7L, "qualitative", TRUE,
"ghibli", "YesterdayDark", 7L, "qualitative", TRUE,
"ghibli", "KikiLight", 7L, "qualitative", TRUE,
"ghibli", "KikiMedium", 7L, "qualitative", TRUE,
"ghibli", "KikiDark", 7L, "qualitative", TRUE,
"ghibli", "TotoroLight", 7L, "qualitative", TRUE,
"ghibli", "TotoroMedium", 7L, "qualitative", TRUE,
"ghibli", "TotoroDark", 7L, "qualitative", TRUE,
"grDevices", "blues9", 9L, "sequential", FALSE,
"IslamicArt", "shiraz", 12L, "qualitative", TRUE,
"IslamicArt", "samarqand", 12L, "qualitative", TRUE,
"IslamicArt", "samarqand2", 4L, "qualitative", TRUE,
"IslamicArt", "shiraz2", 12L, "qualitative", TRUE,
"IslamicArt", "abu_dhabi", 13L, "qualitative", TRUE,
"IslamicArt", "istanbul", 8L, "qualitative", TRUE,
"IslamicArt", "istanbul2", 11L, "qualitative", TRUE,
"IslamicArt", "istanbul3", 8L, "qualitative", TRUE,
"IslamicArt", "konya", 8L, "qualitative", TRUE,
"IslamicArt", "jerusalem", 9L, "qualitative", TRUE,
"IslamicArt", "fes", 8L, "qualitative", TRUE,
"IslamicArt", "fes2", 9L, "qualitative", TRUE,
"IslamicArt", "alhambra", 6L, "qualitative", TRUE,
"IslamicArt", "cordoba", 8L, "qualitative", TRUE,
"IslamicArt", "damascus", 9L, "qualitative", TRUE,
"IslamicArt", "ottoman", 5L, "qualitative", TRUE,
"khroma", "broc", 256L, "divergent", FALSE,
"khroma", "cork", 256L, "divergent", FALSE,
"khroma", "vik", 256L, "divergent", FALSE,
"khroma", "lisbon", 256L, "divergent", FALSE,
"khroma", "tofino", 256L, "divergent", FALSE,
"khroma", "berlin", 256L, "divergent", FALSE,
"khroma", "roma", 256L, "divergent", FALSE,
"khroma", "bam", 256L, "divergent", FALSE,
"khroma", "vanimo", 256L, "divergent", FALSE,
"khroma", "oleron", 256L, "divergent", FALSE,
"khroma", "bukavu", 256L, "divergent", FALSE,
"khroma", "fes", 256L, "divergent", FALSE,
"khroma", "devon", 256L, "sequential", FALSE,
"khroma", "lajolla", 256L, "sequential", FALSE,
"khroma", "bamako", 256L, "sequential", FALSE,
"khroma", "davos", 256L, "sequential", FALSE,
"khroma", "bilbao", 256L, "sequential", FALSE,
"khroma", "nuuk", 256L, "sequential", FALSE,
"khroma", "oslo", 256L, "sequential", FALSE,
"khroma", "grayC", 256L, "sequential", FALSE,
"khroma", "hawaii", 256L, "sequential", FALSE,
"khroma", "lapaz", 256L, "sequential", FALSE,
"khroma", "tokyo", 256L, "sequential", FALSE,
"khroma", "buda", 256L, "sequential", FALSE,
"khroma", "acton", 256L, "sequential", FALSE,
"khroma", "turku", 256L, "sequential", FALSE,
"khroma", "imola", 256L, "sequential", FALSE,
"khroma", "batlow", 256L, "sequential", FALSE,
"khroma", "batlowW", 256L, "sequential", FALSE,
"khroma", "batlowK", 256L, "sequential", FALSE,
"khroma", "brocO", 256L, "divergent", FALSE,
"khroma", "corkO", 256L, "divergent", FALSE,
"khroma", "vikO", 256L, "divergent", FALSE,
"khroma", "romaO", 256L, "divergent", FALSE,
"khroma", "bamO", 256L, "divergent", FALSE,
"khroma", "bright", 7L, "qualitative", FALSE,
"khroma", "contrast", 3L, "qualitative", FALSE,
"khroma", "vibrant", 7L, "qualitative", FALSE,
"khroma", "muted", 9L, "qualitative", FALSE,
"khroma", "pale", 6L, "qualitative", FALSE,
"khroma", "dark", 6L, "qualitative", FALSE,
"khroma", "light", 9L, "qualitative", FALSE,
"khroma", "sunset", 11L, "divergent", FALSE,
"khroma", "BuRd", 9L, "divergent", FALSE,
"khroma", "PRGn", 9L, "divergent", FALSE,
"khroma", "YlOrBr", 9L, "sequential", FALSE,
"khroma", "iridescent", 23L, "sequential", FALSE,
"khroma", "discrete_rainbow", 29L, "qualitative", FALSE,
"khroma", "smooth_rainbow", 34L, "sequential", FALSE,
"khroma", "okabe_ito", 8L, "qualitative", FALSE,
"khroma", "stratigraphy", 175L, "qualitative", FALSE,
"khroma", "soil", 24L, "qualitative", FALSE,
"khroma", "land", 14L, "qualitative", FALSE,
"jcolors", "default", 5L, "qualitative", TRUE,
"jcolors", "pal2", 5L, "qualitative", TRUE,
"jcolors", "pal3", 5L, "qualitative", TRUE,
"jcolors", "pal4", 6L, "qualitative", TRUE,
"jcolors", "pal5", 6L, "qualitative", TRUE,
"jcolors", "pal6", 8L, "qualitative", TRUE,
"jcolors", "pal7", 8L, "qualitative", TRUE,
"jcolors", "pal8", 12L, "qualitative", TRUE,
"jcolors", "pal9", 6L, "qualitative", TRUE,
"jcolors", "pal10", 10L, "sequential", TRUE,
"jcolors", "pal11", 12L, "sequential", TRUE,
"jcolors", "pal12", 13L, "sequential", TRUE,
"jcolors", "rainbow", 9L, "qualitative", TRUE,
"LaCroixColoR", "PassionFruit", 6L, "qualitative", TRUE,
"LaCroixColoR", "Mango", 6L, "qualitative", TRUE,
"LaCroixColoR", "Pure", 6L, "qualitative", TRUE,
"LaCroixColoR", "Lime", 6L, "divergent", TRUE,
"LaCroixColoR", "Lemon", 6L, "divergent", TRUE,
"LaCroixColoR", "Orange", 6L, "divergent", TRUE,
"LaCroixColoR", "Berry", 6L, "divergent", TRUE,
"LaCroixColoR", "CranRaspberry", 6L, "divergent", TRUE,
"LaCroixColoR", "Pamplemousse", 6L, "divergent", TRUE,
"LaCroixColoR", "PeachPear", 6L, "divergent", TRUE,
"LaCroixColoR", "Coconut", 6L, "divergent", TRUE,
"LaCroixColoR", "Apricot", 6L, "qualitative", TRUE,
"LaCroixColoR", "Tangerine", 7L, "qualitative", TRUE,
"LaCroixColoR", "KeyLime", 5L, "qualitative", TRUE,
"LaCroixColoR", "PommeBaya", 5L, "qualitative", TRUE,
"LaCroixColoR", "CeriseLimon", 6L, "qualitative", TRUE,
"LaCroixColoR", "PinaFraise", 6L, "qualitative", TRUE,
"LaCroixColoR", "KiwiSandia", 7L, "qualitative", TRUE,
"LaCroixColoR", "MelonPomelo", 6L, "qualitative", TRUE,
"LaCroixColoR", "MurePepino", 6L, "qualitative", TRUE,
"LaCroixColoR", "paired", 14L, "qualitative", TRUE,
"lisa", "JosefAlbers", 5L, "qualitative", TRUE,
"lisa", "JosefAlbers_1", 5L, "qualitative", TRUE,
"lisa", "GretchenAlbrecht", 5L, "qualitative", TRUE,
"lisa", "BillyApple", 5L, "qualitative", TRUE,
"lisa", "PerArnoldi", 5L, "qualitative", TRUE,
"lisa", "MiltonAvery", 5L, "qualitative", TRUE,
"lisa", "MiltonAvery_1", 5L, "qualitative", TRUE,
"lisa", "HilmaafKlint", 5L, "qualitative", TRUE,
"lisa", "Jean_MichelBasquiat", 5L, "qualitative", TRUE,
"lisa", "Jean_MichelBasquiat_1", 5L, "qualitative", TRUE,
"lisa", "MaxBeckmann", 5L, "qualitative", TRUE,
"lisa", "FernandoBotero", 5L, "qualitative", TRUE,
"lisa", "SandroBotticelli", 5L, "qualitative", TRUE,
"lisa", "SandroBotticelli_1", 5L, "qualitative", TRUE,
"lisa", "PieterBruegel", 5L, "qualitative", TRUE,
"lisa", "JackBush", 5L, "qualitative", TRUE,
"lisa", "JackBush_1", 5L, "qualitative", TRUE,
"lisa", "MaryCassatt", 5L, "qualitative", TRUE,
"lisa", "PaulCezanne", 5L, "qualitative", TRUE,
"lisa", "MarcChagall", 5L, "qualitative", TRUE,
"lisa", "C_M_Coolidge", 5L, "divergent", TRUE,
"lisa", "SalvadorDali", 5L, "qualitative", TRUE,
"lisa", "SalvadorDali_1", 5L, "qualitative", TRUE,
"lisa", "LeonardodaVinci", 5L, "qualitative", TRUE,
"lisa", "GeneDavis", 5L, "qualitative", TRUE,
"lisa", "GiorgiodeChirico", 5L, "qualitative", TRUE,
"lisa", "GiorgiodeChirico_1", 5L, "qualitative", TRUE,
"lisa", "EdgarDegas", 5L, "qualitative", TRUE,
"lisa", "RobertDelaunay", 5L, "qualitative", TRUE,
"lisa", "RobertDelaunay_1", 5L, "qualitative", TRUE,
"lisa", "CharlesDemuth", 5L, "qualitative", TRUE,
"lisa", "RichardDiebenkorn", 5L, "qualitative", TRUE,
"lisa", "OttoDix", 5L, "qualitative", TRUE,
"lisa", "OttoDix_1", 5L, "qualitative", TRUE,
"lisa", "MarcelDuchamp", 5L, "qualitative", TRUE,
"lisa", "AlbrechtDurer", 5L, "qualitative", TRUE,
"lisa", "MaxErnst", 5L, "qualitative", TRUE,
"lisa", "M_C_Escher", 5L, "qualitative", TRUE,
"lisa", "PaulFeeley", 5L, "qualitative", TRUE,
"lisa", "LorserFeitelson", 5L, "qualitative", TRUE,
"lisa", "HelenFrankenthaler", 5L, "qualitative", TRUE,
"lisa", "LucianFreud", 5L, "qualitative", TRUE,
"lisa", "TerryFrost", 5L, "qualitative", TRUE,
"lisa", "PaulGauguin", 5L, "qualitative", TRUE,
"lisa", "RupprechtGeiger", 5L, "qualitative", TRUE,
"lisa", "HansHofmann", 5L, "qualitative", TRUE,
"lisa", "KatsushikaHokusai", 5L, "qualitative", TRUE,
"lisa", "WinslowHomer", 5L, "qualitative", TRUE,
"lisa", "EdwardHopper", 5L, "qualitative", TRUE,
"lisa", "RobertIndiana", 5L, "qualitative", TRUE,
"lisa", "JamesJean", 5L, "qualitative", TRUE,
"lisa", "JasperJohns", 5L, "qualitative", TRUE,
"lisa", "FridaKahlo", 5L, "divergent", TRUE,
"lisa", "WassilyKandinsky", 5L, "qualitative", TRUE,
"lisa", "WassilyKandinsky_1", 5L, "qualitative", TRUE,
"lisa", "WassilyKandinsky_2", 5L, "qualitative", TRUE,
"lisa", "PaulKlee", 5L, "qualitative", TRUE,
"lisa", "PaulKlee_1", 5L, "qualitative", TRUE,
"lisa", "YvesKlein", 5L, "qualitative", TRUE,
"lisa", "GustavKlimt", 5L, "qualitative", TRUE,
"lisa", "JeffKoons", 5L, "qualitative", TRUE,
"lisa", "LeeKrasner", 5L, "qualitative", TRUE,
"lisa", "JacobLawrence", 5L, "qualitative", TRUE,
"lisa", "JacobLawrence_1", 5L, "qualitative", TRUE,
"lisa", "SolLeWitt", 5L, "qualitative", TRUE,
"lisa", "RoyLichtenstein", 5L, "qualitative", TRUE,
"lisa", "RoyLichtenstein_1", 5L, "qualitative", TRUE,
"lisa", "RoyLichtenstein_2", 5L, "qualitative", TRUE,
"lisa", "KazimirMalevich", 5L, "qualitative", TRUE,
"lisa", "EdouardManet", 5L, "qualitative", TRUE,
"lisa", "ReneMagritte", 5L, "qualitative", TRUE,
"lisa", "ReneMagritte_1", 5L, "qualitative", TRUE,
"lisa", "Masaccio", 5L, "qualitative", TRUE,
"lisa", "Michelangelo", 5L, "qualitative", TRUE,
"lisa", "JoanMiro", 5L, "qualitative", TRUE,
"lisa", "AmedeoModigliani", 5L, "qualitative", TRUE,
"lisa", "PietMondrian", 5L, "qualitative", TRUE,
"lisa", "ClaudeMonet", 5L, "qualitative", TRUE,
"lisa", "ClaudeMonet_1", 5L, "qualitative", TRUE,
"lisa", "ClaudeMonet_2", 5L, "qualitative", TRUE,
"lisa", "EdvardMunch", 5L, "qualitative", TRUE,
"lisa", "EdvardMunch_1", 5L, "qualitative", TRUE,
"lisa", "BarnettNewman", 5L, "qualitative", TRUE,
"lisa", "KennethNoland", 5L, "qualitative", TRUE,
"lisa", "GeorgiaOKeeffe", 5L, "sequential", TRUE,
"lisa", "ClaesOldenburg", 5L, "qualitative", TRUE,
"lisa", "PabloPicasso", 5L, "qualitative", TRUE,
"lisa", "PabloPicasso_1", 5L, "qualitative", TRUE,
"lisa", "JacksonPollock", 5L, "qualitative", TRUE,
"lisa", "Prince", 5L, "sequential", TRUE,
"lisa", "JohnQuidor", 5L, "qualitative", TRUE,
"lisa", "MelRamos", 5L, "qualitative", TRUE,
"lisa", "OdilonRedon", 5L, "qualitative", TRUE,
"lisa", "Rembrandt", 5L, "qualitative", TRUE,
"lisa", "Pierre_AugusteRenoir", 5L, "qualitative", TRUE,
"lisa", "Pierre_AugusteRenoir_1", 5L, "qualitative", TRUE,
"lisa", "BridgetRiley", 5L, "qualitative", TRUE,
"lisa", "JamesRosenquist", 5L, "qualitative", TRUE,
"lisa", "MarkRothko", 5L, "sequential", TRUE,
"lisa", "MarkRothko_1", 5L, "qualitative", TRUE,
"lisa", "JohnSingerSargent", 5L, "qualitative", TRUE,
"lisa", "JohnSingerSargent_1", 5L, "qualitative", TRUE,
"lisa", "JohnSingerSargent_2", 5L, "qualitative", TRUE,
"lisa", "OskarSchlemmer", 5L, "divergent", TRUE,
"lisa", "GeorgesSeurat", 5L, "qualitative", TRUE,
"lisa", "SandySkoglund", 5L, "qualitative", TRUE,
"lisa", "PavelTchelitchew", 5L, "qualitative", TRUE,
"lisa", "J_M_W_Turner", 5L, "qualitative", TRUE,
"lisa", "CyTwombly", 5L, "qualitative", TRUE,
"lisa", "JohannJacobUlrich", 5L, "sequential", TRUE,
"lisa", "TheovanDoesburg", 5L, "qualitative", TRUE,
"lisa", "TheovanDoesburg_1", 5L, "qualitative", TRUE,
"lisa", "JanvanEyck", 5L, "qualitative", TRUE,
"lisa", "VincentvanGogh", 5L, "qualitative", TRUE,
"lisa", "VincentvanGogh_1", 5L, "qualitative", TRUE,
"lisa", "VincentvanGogh_2", 5L, "qualitative", TRUE,
"lisa", "RemediosVaro", 5L, "qualitative", TRUE,
"lisa", "DiegoVelazquez", 5L, "qualitative", TRUE,
"lisa", "JohannesVermeer", 5L, "qualitative", TRUE,
"lisa", "JohannesVermeer_1", 5L, "qualitative", TRUE,
"lisa", "AndyWarhol", 5L, "qualitative", TRUE,
"lisa", "AndyWarhol_1", 5L, "qualitative", TRUE,
"lisa", "AndyWarhol_2", 5L, "qualitative", TRUE,
"lisa", "AndyWarhol_3", 5L, "qualitative", TRUE,
"lisa", "GrantWood", 5L, "qualitative", TRUE,
"lisa", "FrancescoXanto", 5L, "qualitative", TRUE,
"lisa", "JackYoungerman", 5L, "qualitative", TRUE,
"lisa", "KarlZerbe", 5L, "qualitative", TRUE,
"nationalparkcolors", "SmokyMountains", 6L, "qualitative", TRUE,
"nationalparkcolors", "RockyMountains", 5L, "qualitative", TRUE,
"nationalparkcolors", "Yellowstone", 6L, "qualitative", TRUE,
"nationalparkcolors", "Arches", 6L, "qualitative", TRUE,
"nationalparkcolors", "ArcticGates", 6L, "qualitative", TRUE,
"nationalparkcolors", "MtMckinley", 6L, "qualitative", TRUE,
"nationalparkcolors", "GeneralGrant", 8L, "qualitative", TRUE,
"nationalparkcolors", "Hawaii", 5L, "qualitative", TRUE,
"nationalparkcolors", "CraterLake", 7L, "qualitative", TRUE,
"nationalparkcolors", "Saguaro", 6L, "qualitative", TRUE,
"nationalparkcolors", "GrandTeton", 5L, "qualitative", TRUE,
"nationalparkcolors", "BryceCanyon", 5L, "qualitative", TRUE,
"nationalparkcolors", "MtRainier", 5L, "qualitative", TRUE,
"nationalparkcolors", "Badlands", 5L, "qualitative", TRUE,
"nationalparkcolors", "Redwoods", 5L, "qualitative", TRUE,
"nationalparkcolors", "Everglades", 5L, "qualitative", TRUE,
"nationalparkcolors", "Voyageurs", 5L, "qualitative", TRUE,
"nationalparkcolors", "BlueRidgePkwy", 6L, "qualitative", TRUE,
"nationalparkcolors", "Denali", 5L, "qualitative", TRUE,
"nationalparkcolors", "GreatBasin", 6L, "qualitative", TRUE,
"nationalparkcolors", "ChannelIslands", 6L, "qualitative", TRUE,
"nationalparkcolors", "Yosemite", 5L, "qualitative", TRUE,
"nationalparkcolors", "Acadia", 6L, "qualitative", TRUE,
"nationalparkcolors", "DeathValley", 6L, "qualitative", TRUE,
"nationalparkcolors", "Zion", 5L, "qualitative", TRUE,
"nbapalettes", "bobcats", 5L, "qualitative", TRUE,
"nbapalettes", "bobcats_original", 4L, "qualitative", TRUE,
"nbapalettes", "blazers", 3L, "qualitative", TRUE,
"nbapalettes", "blazers_statement", 3L, "qualitative", TRUE,
"nbapalettes", "blazers_city", 5L, "qualitative", TRUE,
"nbapalettes", "blazers_city2", 4L, "qualitative", TRUE,
"nbapalettes", "bucks", 4L, "qualitative", TRUE,
"nbapalettes", "bucks_earned", 6L, "qualitative", TRUE,
"nbapalettes", "bucks_00s", 3L, "qualitative", TRUE,
"nbapalettes", "bucks_retro", 5L, "qualitative", TRUE,
"nbapalettes", "bucks_city", 4L, "qualitative", TRUE,
"nbapalettes", "bucks_city2", 6L, "qualitative", TRUE,
"nbapalettes", "bulls", 2L, "qualitative", TRUE,
"nbapalettes", "bulls_city", 3L, "qualitative", TRUE,
"nbapalettes", "bulls_city2", 3L, "qualitative", TRUE,
"nbapalettes", "bulls_holiday", 3L, "qualitative", TRUE,
"nbapalettes", "cavaliers", 4L, "qualitative", TRUE,
"nbapalettes", "cavaliers_90s", 3L, "qualitative", TRUE,
"nbapalettes", "cavaliers_retro", 2L, "qualitative", TRUE,
"nbapalettes", "celtics", 3L, "qualitative", TRUE,
"nbapalettes", "celtics2", 5L, "qualitative", TRUE,
"nbapalettes", "celtics_europe", 3L, "qualitative", TRUE,
"nbapalettes", "celtics_champ", 4L, "qualitative", TRUE,
"nbapalettes", "clippers", 4L, "qualitative", TRUE,
"nbapalettes", "clippers_city", 5L, "qualitative", TRUE,
"nbapalettes", "clippers_retro", 3L, "qualitative", TRUE,
"nbapalettes", "clippers_original", 4L, "qualitative", TRUE,
"nbapalettes", "grizzlies", 5L, "qualitative", TRUE,
"nbapalettes", "grizzlies_00s", 4L, "qualitative", TRUE,
"nbapalettes", "grizzlies_retro", 4L, "qualitative", TRUE,
"nbapalettes", "grizzlies_europe", 5L, "qualitative", TRUE,
"nbapalettes", "hawks", 4L, "qualitative", TRUE,
"nbapalettes", "hawks_statement", 3L, "qualitative", TRUE,
"nbapalettes", "hawks_90s", 4L, "qualitative", TRUE,
"nbapalettes", "hawks_retro", 3L, "qualitative", TRUE,
"nbapalettes", "heat", 3L, "qualitative", TRUE,
"nbapalettes", "heat_90s", 3L, "qualitative", TRUE,
"nbapalettes", "heat_vice", 3L, "qualitative", TRUE,
"nbapalettes", "heat_dark", 4L, "qualitative", TRUE,
"nbapalettes", "heat_0506", 3L, "qualitative", TRUE,
"nbapalettes", "heat_military", 5L, "qualitative", TRUE,
"nbapalettes", "hornets", 3L, "qualitative", TRUE,
"nbapalettes", "hornets2", 4L, "qualitative", TRUE,
"nbapalettes", "hornets_classic", 6L, "qualitative", TRUE,
"nbapalettes", "hornets_city", 3L, "qualitative", TRUE,
"nbapalettes", "hornets_city2", 4L, "qualitative", TRUE,
"nbapalettes", "huskies", 2L, "qualitative", TRUE,
"nbapalettes", "jazz", 3L, "qualitative", TRUE,
"nbapalettes", "jazz_city", 9L, "sequential", TRUE,
"nbapalettes", "jazz_classic", 5L, "qualitative", TRUE,
"nbapalettes", "jazz_retro", 5L, "qualitative", TRUE,
"nbapalettes", "kings", 3L, "qualitative", TRUE,
"nbapalettes", "kings_city", 4L, "qualitative", TRUE,
"nbapalettes", "kings_alt", 5L, "qualitative", TRUE,
"nbapalettes", "kings_alt2", 3L, "qualitative", TRUE,
"nbapalettes", "knicks", 3L, "qualitative", TRUE,
"nbapalettes", "knicks_retro", 3L, "qualitative", TRUE,
"nbapalettes", "knicks_city", 4L, "qualitative", TRUE,
"nbapalettes", "knicks_city2", 4L, "qualitative", TRUE,
"nbapalettes", "knicks_holiday", 5L, "qualitative", TRUE,
"nbapalettes", "lakers", 3L, "qualitative", TRUE,
"nbapalettes", "lakers_city", 4L, "qualitative", TRUE,
"nbapalettes", "lakers_alt", 3L, "qualitative", TRUE,
"nbapalettes", "magic", 3L, "qualitative", TRUE,
"nbapalettes", "magic_city", 3L, "qualitative", TRUE,
"nbapalettes", "magic_city2", 5L, "qualitative", TRUE,
"nbapalettes", "mavericks", 4L, "qualitative", TRUE,
"nbapalettes", "mavericks_alt", 5L, "qualitative", TRUE,
"nbapalettes", "mavericks_city", 4L, "qualitative", TRUE,
"nbapalettes", "mavericks_retro", 3L, "qualitative", TRUE,
"nbapalettes", "mavericks_banner", 5L, "qualitative", TRUE,
"nbapalettes", "nets", 2L, "qualitative", TRUE,
"nbapalettes", "nets_city", 5L, "qualitative", TRUE,
"nbapalettes", "hornets_believe", 6L, "qualitative", TRUE,
"nbapalettes", "nuggets", 4L, "qualitative", TRUE,
"nbapalettes", "nuggets_80s", 7L, "qualitative", TRUE,
"nbapalettes", "nuggets_statement", 4L, "qualitative", TRUE,
"nbapalettes", "nuggets_city", 5L, "qualitative", TRUE,
"nbapalettes", "nuggets_city2", 7L, "qualitative", TRUE,
"nbapalettes", "pacers", 3L, "qualitative", TRUE,
"nbapalettes", "pacers_classic", 2L, "qualitative", TRUE,
"nbapalettes", "pacers_venue", 4L, "qualitative", TRUE,
"nbapalettes", "pacers_foundation", 4L, "qualitative", TRUE,
"nbapalettes", "pelicans", 3L, "qualitative", TRUE,
"nbapalettes", "pelicans_city", 4L, "qualitative", TRUE,
"nbapalettes", "pelicans_pride", 4L, "qualitative", TRUE,
"nbapalettes", "pistons", 4L, "qualitative", TRUE,
"nbapalettes", "pistons_90s", 5L, "qualitative", TRUE,
"nbapalettes", "pistons_city", 4L, "qualitative", TRUE,
"nbapalettes", "raptors", 5L, "qualitative", TRUE,
"nbapalettes", "raptors_statement", 3L, "qualitative", TRUE,
"nbapalettes", "raptors_city", 4L, "qualitative", TRUE,
"nbapalettes", "raptors_original", 4L, "qualitative", TRUE,
"nbapalettes", "raptors_europe", 4L, "qualitative", TRUE,
"nbapalettes", "raptors_military", 5L, "qualitative", TRUE,
"nbapalettes", "rockets", 4L, "qualitative", TRUE,
"nbapalettes", "rockets_90s", 4L, "qualitative", TRUE,
"nbapalettes", "rockets_city", 3L, "qualitative", TRUE,
"nbapalettes", "rockets_original", 3L, "qualitative", TRUE,
"nbapalettes", "sixers", 5L, "qualitative", TRUE,
"nbapalettes", "sixers_retro", 2L, "qualitative", TRUE,
"nbapalettes", "sixers_90s", 4L, "qualitative", TRUE,
"nbapalettes", "sixers_city", 4L, "qualitative", TRUE,
"nbapalettes", "spurs", 5L, "qualitative", TRUE,
"nbapalettes", "suns", 7L, "qualitative", TRUE,
"nbapalettes", "suns_00s", 6L, "qualitative", TRUE,
"nbapalettes", "suns_retro", 3L, "qualitative", TRUE,
"nbapalettes", "suns_statement", 5L, "qualitative", TRUE,
"nbapalettes", "suns_city", 13L, "qualitative", TRUE,
"nbapalettes", "supersonics", 3L, "qualitative", TRUE,
"nbapalettes", "supersonics_90s", 5L, "qualitative", TRUE,
"nbapalettes", "supersonics_holiday", 4L, "qualitative", TRUE,
"nbapalettes", "thunder", 4L, "qualitative", TRUE,
"nbapalettes", "thunder_statement", 3L, "qualitative", TRUE,
"nbapalettes", "thunder_city", 6L, "qualitative", TRUE,
"nbapalettes", "thunder_city2", 5L, "qualitative", TRUE,
"nbapalettes", "thunder_tribute", 9L, "qualitative", TRUE,
"nbapalettes", "timberwolves", 4L, "qualitative", TRUE,
"nbapalettes", "timberwolves_00s", 6L, "qualitative", TRUE,
"nbapalettes", "timberwolves_classic", 6L, "qualitative", TRUE,
"nbapalettes", "timberwolves_statement", 4L, "qualitative", TRUE,
"nbapalettes", "warriors", 3L, "qualitative", TRUE,
"nbapalettes", "warriors_00s", 4L, "qualitative", TRUE,
"nbapalettes", "warriors_city", 3L, "qualitative", TRUE,
"nbapalettes", "warriors_city2", 4L, "qualitative", TRUE,
"nbapalettes", "warriors_cny", 3L, "qualitative", TRUE,
"nbapalettes", "wizards", 3L, "qualitative", TRUE,
"nbapalettes", "wizards_city", 3L, "qualitative", TRUE,
"nbapalettes", "wizards_earned", 4L, "qualitative", TRUE,
"NineteenEightyR", "cobra", 6L, "qualitative", TRUE,
"NineteenEightyR", "electronic_night", 5L, "qualitative", TRUE,
"NineteenEightyR", "hotpink", 5L, "sequential", TRUE,
"NineteenEightyR", "malibu", 5L, "qualitative", TRUE,
"NineteenEightyR", "miami1", 5L, "divergent", TRUE,
"NineteenEightyR", "miami2", 5L, "divergent", TRUE,
"NineteenEightyR", "seventies_aint_done_yet", 5L, "qualitative", TRUE,
"NineteenEightyR", "sonny", 5L, "qualitative", TRUE,
"NineteenEightyR", "sunset1", 5L, "qualitative", TRUE,
"NineteenEightyR", "sunset2", 5L, "sequential", TRUE,
"NineteenEightyR", "sunset3", 5L, "sequential", TRUE,
"NineteenEightyR", "youngturqs", 12L, "qualitative", TRUE,
"nord", "polarnight", 4L, "sequential", TRUE,
"nord", "snowstorm", 3L, "sequential", TRUE,
"nord", "frost", 4L, "qualitative", TRUE,
"nord", "aurora", 5L, "qualitative", TRUE,
"nord", "lumina", 5L, "qualitative", TRUE,
"nord", "mountain_forms", 5L, "divergent", TRUE,
"nord", "silver_mine", 5L, "divergent", TRUE,
"nord", "lake_superior", 6L, "qualitative", TRUE,
"nord", "victory_bonds", 5L, "qualitative", TRUE,
"nord", "halifax_harbor", 6L, "sequential", TRUE,
"nord", "moose_pond", 8L, "qualitative", TRUE,
"nord", "algoma_forest", 7L, "qualitative", TRUE,
"nord", "rocky_mountain", 6L, "qualitative", TRUE,
"nord", "red_mountain", 8L, "qualitative", TRUE,
"nord", "baie_mouton", 7L, "qualitative", TRUE,
"nord", "afternoon_prarie", 9L, "qualitative", TRUE,
"ochRe", "namatjira_qual", 8L, "qualitative", TRUE,
"ochRe", "namatjira_div", 8L, "qualitative", TRUE,
"ochRe", "mccrea", 11L, "qualitative", TRUE,
"ochRe", "parliament", 8L, "qualitative", TRUE,
"ochRe", "tasmania", 7L, "qualitative", TRUE,
"ochRe", "nolan_ned", 5L, "qualitative", TRUE,
"ochRe", "winmar", 7L, "qualitative", TRUE,
"ochRe", "olsen_qual", 6L, "qualitative", TRUE,
"ochRe", "olsen_seq", 14L, "qualitative", TRUE,
"ochRe", "williams_pilbara", 7L, "qualitative", TRUE,
"ochRe", "healthy_reef", 9L, "qualitative", TRUE,
"ochRe", "emu_woman_paired", 18L, "qualitative", TRUE,
"ochRe", "galah", 6L, "divergent", TRUE,
"ochRe", "lorikeet", 6L, "qualitative", TRUE,
"ochRe", "dead_reef", 6L, "qualitative", TRUE,
"ochRe", "jumping_frog", 5L, "qualitative", TRUE,
"palettetown", "bulbasaur", 13L, "qualitative", TRUE,
"palettetown", "ivysaur", 13L, "qualitative", TRUE,
"palettetown", "venusaur", 14L, "qualitative", TRUE,
"palettetown", "charmander", 13L, "qualitative", TRUE,
"palettetown", "charmeleon", 12L, "qualitative", TRUE,
"palettetown", "charizard", 14L, "qualitative", TRUE,
"palettetown", "squirtle", 14L, "qualitative", TRUE,
"palettetown", "wartortle", 13L, "qualitative", TRUE,
"palettetown", "blastoise", 14L, "qualitative", TRUE,
"palettetown", "caterpie", 12L, "qualitative", TRUE,
"palettetown", "metapod", 5L, "qualitative", TRUE,
"palettetown", "butterfree", 13L, "qualitative", TRUE,
"palettetown", "weedle", 11L, "qualitative", TRUE,
"palettetown", "kakuna", 8L, "qualitative", TRUE,
"palettetown", "beedrill", 14L, "qualitative", TRUE,
"palettetown", "pidgey", 12L, "qualitative", TRUE,
"palettetown", "pidgeotto", 13L, "qualitative", TRUE,
"palettetown", "pidgeot", 14L, "qualitative", TRUE,
"palettetown", "rattata", 13L, "qualitative", TRUE,
"palettetown", "raticate", 13L, "qualitative", TRUE,
"palettetown", "spearow", 15L, "qualitative", TRUE,
"palettetown", "fearow", 12L, "qualitative", TRUE,
"palettetown", "ekans", 12L, "qualitative", TRUE,
"palettetown", "arbok", 10L, "qualitative", TRUE,
"palettetown", "pikachu", 10L, "qualitative", TRUE,
"palettetown", "raichu", 14L, "qualitative", TRUE,
"palettetown", "sandshrew", 10L, "qualitative", TRUE,
"palettetown", "sandslash", 13L, "qualitative", TRUE,
"palettetown", "nidoranf", 11L, "qualitative", TRUE,
"palettetown", "nidorina", 13L, "qualitative", TRUE,
"palettetown", "nidoqueen", 13L, "qualitative", TRUE,
"palettetown", "nidoranm", 10L, "qualitative", TRUE,
"palettetown", "nidorino", 12L, "qualitative", TRUE,
"palettetown", "nidoking", 11L, "qualitative", TRUE,
"palettetown", "clefairy", 13L, "qualitative", TRUE,
"palettetown", "clefable", 12L, "qualitative", TRUE,
"palettetown", "vulpix", 13L, "qualitative", TRUE,
"palettetown", "ninetales", 7L, "qualitative", TRUE,
"palettetown", "jigglypuff", 11L, "qualitative", TRUE,
"palettetown", "wigglytuff", 12L, "qualitative", TRUE,
"palettetown", "zubat", 11L, "qualitative", TRUE,
"palettetown", "golbat", 11L, "qualitative", TRUE,
"palettetown", "oddish", 10L, "qualitative", TRUE,
"palettetown", "gloom", 14L, "qualitative", TRUE,
"palettetown", "vileplume", 13L, "qualitative", TRUE,
"palettetown", "paras", 12L, "qualitative", TRUE,
"palettetown", "parasect", 11L, "qualitative", TRUE,
"palettetown", "venonat", 14L, "qualitative", TRUE,
"palettetown", "venomoth", 11L, "qualitative", TRUE,
"palettetown", "diglett", 4L, "qualitative", TRUE,
"palettetown", "dugtrio", 12L, "qualitative", TRUE,
"palettetown", "meowth", 13L, "qualitative", TRUE,
"palettetown", "persian", 12L, "qualitative", TRUE,
"palettetown", "psyduck", 10L, "qualitative", TRUE,
"palettetown", "golduck", 13L, "qualitative", TRUE,
"palettetown", "mankey", 14L, "qualitative", TRUE,
"palettetown", "primeape", 15L, "qualitative", TRUE,
"palettetown", "growlithe", 11L, "qualitative", TRUE,
"palettetown", "arcanine", 14L, "qualitative", TRUE,
"palettetown", "poliwag", 11L, "qualitative", TRUE,
"palettetown", "poliwhirl", 9L, "qualitative", TRUE,
"palettetown", "poliwrath", 9L, "qualitative", TRUE,
"palettetown", "abra", 8L, "qualitative", TRUE,
"palettetown", "kadabra", 14L, "qualitative", TRUE,
"palettetown", "alakazam", 12L, "qualitative", TRUE,
"palettetown", "machop", 13L, "qualitative", TRUE,
"palettetown", "machoke", 13L, "qualitative", TRUE,
"palettetown", "machamp", 13L, "qualitative", TRUE,
"palettetown", "bellsprout", 13L, "qualitative", TRUE,
"palettetown", "weepinbell", 14L, "qualitative", TRUE,
"palettetown", "victreebel", 14L, "qualitative", TRUE,
"palettetown", "tentacool", 14L, "qualitative", TRUE,
"palettetown", "tentacruel", 14L, "qualitative", TRUE,
"palettetown", "geodude", 6L, "qualitative", TRUE,
"palettetown", "graveler", 6L, "qualitative", TRUE,
"palettetown", "golem", 12L, "qualitative", TRUE,
"palettetown", "ponyta", 11L, "qualitative", TRUE,
"palettetown", "rapidash", 11L, "qualitative", TRUE,
"palettetown", "slowpoke", 12L, "qualitative", TRUE,
"palettetown", "slowbro", 13L, "qualitative", TRUE,
"palettetown", "magnemite", 14L, "qualitative", TRUE,
"palettetown", "magneton", 14L, "qualitative", TRUE,
"palettetown", "farfetchd", 14L, "qualitative", TRUE,
"palettetown", "doduo", 9L, "qualitative", TRUE,
"palettetown", "dodrio", 15L, "qualitative", TRUE,
"palettetown", "seel", 11L, "qualitative", TRUE,
"palettetown", "dewgong", 7L, "qualitative", TRUE,
"palettetown", "grimer", 9L, "qualitative", TRUE,
"palettetown", "muk", 8L, "qualitative", TRUE,
"palettetown", "shellder", 9L, "qualitative", TRUE,
"palettetown", "cloyster", 9L, "qualitative", TRUE,
"palettetown", "gastly", 8L, "qualitative", TRUE,
"palettetown", "haunter", 10L, "qualitative", TRUE,
"palettetown", "gengar", 10L, "qualitative", TRUE,
"palettetown", "onix", 6L, "qualitative", TRUE,
"palettetown", "drowzee", 9L, "qualitative", TRUE,
"palettetown", "hypno", 9L, "qualitative", TRUE,
"palettetown", "krabby", 10L, "qualitative", TRUE,
"palettetown", "kingler", 10L, "qualitative", TRUE,
"palettetown", "voltorb", 9L, "qualitative", TRUE,
"palettetown", "electrode", 10L, "qualitative", TRUE,
"palettetown", "exeggcute", 9L, "qualitative", TRUE,
"palettetown", "exeggutor", 14L, "qualitative", TRUE,
"palettetown", "cubone", 13L, "qualitative", TRUE,
"palettetown", "marowak", 14L, "qualitative", TRUE,
"palettetown", "hitmonlee", 12L, "qualitative", TRUE,
"palettetown", "hitmonchan", 13L, "qualitative", TRUE,
"palettetown", "lickitung", 9L, "qualitative", TRUE,
"palettetown", "koffing", 12L, "qualitative", TRUE,
"palettetown", "weezing", 13L, "qualitative", TRUE,
"palettetown", "rhyhorn", 8L, "qualitative", TRUE,
"palettetown", "rhydon", 11L, "qualitative", TRUE,
"palettetown", "chansey", 9L, "qualitative", TRUE,
"palettetown", "tangela", 9L, "qualitative", TRUE,
"palettetown", "kangaskhan", 14L, "qualitative", TRUE,
"palettetown", "horsea", 10L, "qualitative", TRUE,
"palettetown", "seadra", 10L, "qualitative", TRUE,
"palettetown", "goldeen", 11L, "qualitative", TRUE,
"palettetown", "seaking", 12L, "qualitative", TRUE,
"palettetown", "staryu", 12L, "qualitative", TRUE,
"palettetown", "starmie", 12L, "qualitative", TRUE,
"palettetown", "mr_mime", 12L, "qualitative", TRUE,
"palettetown", "scyther", 12L, "qualitative", TRUE,
"palettetown", "jynx", 15L, "qualitative", TRUE,
"palettetown", "electabuzz", 10L, "qualitative", TRUE,
"palettetown", "magmar", 12L, "qualitative", TRUE,
"palettetown", "pinsir", 9L, "qualitative", TRUE,
"palettetown", "tauros", 13L, "qualitative", TRUE,
"palettetown", "magikarp", 13L, "qualitative", TRUE,
"palettetown", "gyarados", 15L, "qualitative", TRUE,
"palettetown", "lapras", 15L, "qualitative", TRUE,
"palettetown", "ditto", 6L, "qualitative", TRUE,
"palettetown", "eevee", 9L, "qualitative", TRUE,
"palettetown", "vaporeon", 15L, "qualitative", TRUE,
"palettetown", "jolteon", 11L, "qualitative", TRUE,
"palettetown", "flareon", 10L, "qualitative", TRUE,
"palettetown", "porygon", 11L, "qualitative", TRUE,
"palettetown", "omanyte", 12L, "qualitative", TRUE,
"palettetown", "omastar", 12L, "qualitative", TRUE,
"palettetown", "kabuto", 11L, "qualitative", TRUE,
"palettetown", "kabutops", 9L, "qualitative", TRUE,
"palettetown", "aerodactyl", 7L, "qualitative", TRUE,
"palettetown", "snorlax", 14L, "qualitative", TRUE,
"palettetown", "articuno", 12L, "qualitative", TRUE,
"palettetown", "zapdos", 10L, "qualitative", TRUE,
"palettetown", "moltres", 14L, "qualitative", TRUE,
"palettetown", "dratini", 9L, "qualitative", TRUE,
"palettetown", "dragonair", 12L, "qualitative", TRUE,
"palettetown", "dragonite", 13L, "qualitative", TRUE,
"palettetown", "mewtwo", 9L, "qualitative", TRUE,
"palettetown", "mew", 6L, "qualitative", TRUE,
"palettetown", "chikorita", 11L, "qualitative", TRUE,
"palettetown", "bayleef", 14L, "qualitative", TRUE,
"palettetown", "meganium", 14L, "qualitative", TRUE,
"palettetown", "cyndaquil", 13L, "qualitative", TRUE,
"palettetown", "quilava", 14L, "qualitative", TRUE,
"palettetown", "typhlosion", 14L, "qualitative", TRUE,
"palettetown", "totodile", 11L, "qualitative", TRUE,
"palettetown", "croconaw", 13L, "qualitative", TRUE,
"palettetown", "feraligatr", 14L, "qualitative", TRUE,
"palettetown", "sentret", 12L, "qualitative", TRUE,
"palettetown", "furret", 11L, "qualitative", TRUE,
"palettetown", "hoothoot", 13L, "qualitative", TRUE,
"palettetown", "noctowl", 13L, "qualitative", TRUE,
"palettetown", "ledyba", 12L, "qualitative", TRUE,
"palettetown", "ledian", 14L, "qualitative", TRUE,
"palettetown", "spinarak", 14L, "qualitative", TRUE,
"palettetown", "ariados", 14L, "qualitative", TRUE,
"palettetown", "crobat", 9L, "qualitative", TRUE,
"palettetown", "chinchou", 13L, "qualitative", TRUE,
"palettetown", "lanturn", 14L, "qualitative", TRUE,
"palettetown", "pichu", 11L, "qualitative", TRUE,
"palettetown", "cleffa", 11L, "qualitative", TRUE,
"palettetown", "igglybuff", 9L, "qualitative", TRUE,
"palettetown", "togepi", 12L, "qualitative", TRUE,
"palettetown", "togetic", 11L, "qualitative", TRUE,
"palettetown", "natu", 14L, "qualitative", TRUE,
"palettetown", "xatu", 15L, "qualitative", TRUE,
"palettetown", "mareep", 14L, "qualitative", TRUE,
"palettetown", "flaaffy", 13L, "qualitative", TRUE,
"palettetown", "ampharos", 12L, "qualitative", TRUE,
"palettetown", "bellossom", 13L, "qualitative", TRUE,
"palettetown", "marill", 10L, "qualitative", TRUE,
"palettetown", "azumarill", 10L, "qualitative", TRUE,
"palettetown", "sudowoodo", 11L, "qualitative", TRUE,
"palettetown", "politoed", 14L, "qualitative", TRUE,
"palettetown", "hoppip", 10L, "qualitative", TRUE,
"palettetown", "skiploom", 11L, "qualitative", TRUE,
"palettetown", "jumpluff", 13L, "qualitative", TRUE,
"palettetown", "aipom", 12L, "qualitative", TRUE,
"palettetown", "sunkern", 13L, "qualitative", TRUE,
"palettetown", "sunflora", 12L, "qualitative", TRUE,
"palettetown", "yanma", 11L, "qualitative", TRUE,
"palettetown", "wooper", 9L, "qualitative", TRUE,
"palettetown", "quagsire", 9L, "qualitative", TRUE,
"palettetown", "espeon", 9L, "qualitative", TRUE,
"palettetown", "umbreon", 10L, "qualitative", TRUE,
"palettetown", "murkrow", 12L, "qualitative", TRUE,
"palettetown", "slowking", 13L, "qualitative", TRUE,
"palettetown", "misdreavus", 13L, "qualitative", TRUE,
"palettetown", "unown", 5L, "qualitative", TRUE,
"palettetown", "wobbuffet", 8L, "qualitative", TRUE,
"palettetown", "girafarig", 13L, "qualitative", TRUE,
"palettetown", "pineco", 5L, "qualitative", TRUE,
"palettetown", "forretress", 10L, "qualitative", TRUE,
"palettetown", "dunsparce", 13L, "qualitative", TRUE,
"palettetown", "gligar", 12L, "qualitative", TRUE,
"palettetown", "steelix", 7L, "qualitative", TRUE,
"palettetown", "snubbull", 12L, "qualitative", TRUE,
"palettetown", "granbull", 11L, "qualitative", TRUE,
"palettetown", "qwilfish", 12L, "qualitative", TRUE,
"palettetown", "scizor", 11L, "qualitative", TRUE,
"palettetown", "shuckle", 12L, "qualitative", TRUE,
"palettetown", "heracross", 11L, "qualitative", TRUE,
"palettetown", "sneasel", 14L, "qualitative", TRUE,
"palettetown", "teddiursa", 12L, "qualitative", TRUE,
"palettetown", "ursaring", 13L, "qualitative", TRUE,
"palettetown", "slugma", 9L, "qualitative", TRUE,
"palettetown", "magcargo", 12L, "qualitative", TRUE,
"palettetown", "swinub", 9L, "qualitative", TRUE,
"palettetown", "piloswine", 12L, "qualitative", TRUE,
"palettetown", "corsola", 9L, "qualitative", TRUE,
"palettetown", "remoraid", 9L, "qualitative", TRUE,
"palettetown", "octillery", 12L, "qualitative", TRUE,
"palettetown", "delibird", 13L, "qualitative", TRUE,
"palettetown", "mantine", 13L, "qualitative", TRUE,
"palettetown", "skarmory", 12L, "qualitative", TRUE,
"palettetown", "houndour", 11L, "qualitative", TRUE,
"palettetown", "houndoom", 12L, "qualitative", TRUE,
"palettetown", "kingdra", 12L, "qualitative", TRUE,
"palettetown", "phanpy", 9L, "qualitative", TRUE,
"palettetown", "donphan", 13L, "qualitative", TRUE,
"palettetown", "porygon2", 12L, "qualitative", TRUE,
"palettetown", "stantler", 12L, "qualitative", TRUE,
"palettetown", "smeargle", 12L, "qualitative", TRUE,
"palettetown", "tyrogue", 12L, "qualitative", TRUE,
"palettetown", "hitmontop", 12L, "qualitative", TRUE,
"palettetown", "smoochum", 12L, "qualitative", TRUE,
"palettetown", "elekid", 9L, "qualitative", TRUE,
"palettetown", "magby", 10L, "qualitative", TRUE,
"palettetown", "miltank", 15L, "qualitative", TRUE,
"palettetown", "blissey", 9L, "qualitative", TRUE,
"palettetown", "raikou", 13L, "qualitative", TRUE,
"palettetown", "entei", 14L, "qualitative", TRUE,
"palettetown", "suicune", 14L, "qualitative", TRUE,
"palettetown", "larvitar", 9L, "qualitative", TRUE,
"palettetown", "pupitar", 9L, "qualitative", TRUE,
"palettetown", "tyranitar", 11L, "qualitative", TRUE,
"palettetown", "lugia", 9L, "qualitative", TRUE,
"palettetown", "ho_oh", 13L, "qualitative", TRUE,
"palettetown", "celebi", 11L, "qualitative", TRUE,
"palettetown", "treecko", 14L, "qualitative", TRUE,
"palettetown", "grovyle", 14L, "qualitative", TRUE,
"palettetown", "sceptile", 13L, "qualitative", TRUE,
"palettetown", "torchic", 12L, "qualitative", TRUE,
"palettetown", "combusken", 14L, "qualitative", TRUE,
"palettetown", "blaziken", 14L, "qualitative", TRUE,
"palettetown", "mudkip", 14L, "qualitative", TRUE,
"palettetown", "marshtomp", 14L, "qualitative", TRUE,
"palettetown", "swampert", 14L, "qualitative", TRUE,
"palettetown", "poochyena", 14L, "qualitative", TRUE,
"palettetown", "mightyena", 11L, "qualitative", TRUE,
"palettetown", "zigzagoon", 14L, "qualitative", TRUE,
"palettetown", "linoone", 11L, "qualitative", TRUE,
"palettetown", "wurmple", 13L, "qualitative", TRUE,
"palettetown", "silcoon", 9L, "qualitative", TRUE,
"palettetown", "beautifly", 13L, "qualitative", TRUE,
"palettetown", "cascoon", 8L, "qualitative", TRUE,
"palettetown", "dustox", 14L, "qualitative", TRUE,
"palettetown", "lotad", 13L, "qualitative", TRUE,
"palettetown", "lombre", 12L, "qualitative", TRUE,
"palettetown", "ludicolo", 15L, "qualitative", TRUE,
"palettetown", "seedot", 11L, "qualitative", TRUE,
"palettetown", "nuzleaf", 14L, "qualitative", TRUE,
"palettetown", "shiftry", 13L, "qualitative", TRUE,
"palettetown", "taillow", 15L, "qualitative", TRUE,
"palettetown", "swellow", 15L, "qualitative", TRUE,
"palettetown", "wingull", 14L, "qualitative", TRUE,
"palettetown", "pelipper", 15L, "qualitative", TRUE,
"palettetown", "ralts", 11L, "qualitative", TRUE,
"palettetown", "kirlia", 13L, "qualitative", TRUE,
"palettetown", "gardevoir", 12L, "qualitative", TRUE,
"palettetown", "surskit", 12L, "qualitative", TRUE,
"palettetown", "masquerain", 14L, "qualitative", TRUE,
"palettetown", "shroomish", 11L, "qualitative", TRUE,
"palettetown", "breloom", 15L, "qualitative", TRUE,
"palettetown", "slakoth", 14L, "qualitative", TRUE,
"palettetown", "vigoroth", 15L, "qualitative", TRUE,
"palettetown", "slaking", 14L, "qualitative", TRUE,
"palettetown", "nincada", 15L, "qualitative", TRUE,
"palettetown", "ninjask", 13L, "qualitative", TRUE,
"palettetown", "shedinja", 10L, "qualitative", TRUE,
"palettetown", "whismur", 12L, "qualitative", TRUE,
"palettetown", "loudred", 14L, "qualitative", TRUE,
"palettetown", "exploud", 15L, "qualitative", TRUE,
"palettetown", "makuhita", 12L, "qualitative", TRUE,
"palettetown", "hariyama", 15L, "qualitative", TRUE,
"palettetown", "azurill", 11L, "qualitative", TRUE,
"palettetown", "nosepass", 11L, "qualitative", TRUE,
"palettetown", "skitty", 11L, "qualitative", TRUE,
"palettetown", "delcatty", 15L, "qualitative", TRUE,
"palettetown", "sableye", 13L, "qualitative", TRUE,
"palettetown", "mawile", 14L, "qualitative", TRUE,
"palettetown", "aron", 9L, "qualitative", TRUE,
"palettetown", "lairon", 12L, "qualitative", TRUE,
"palettetown", "aggron", 12L, "qualitative", TRUE,
"palettetown", "meditite", 13L, "qualitative", TRUE,
"palettetown", "medicham", 13L, "qualitative", TRUE,
"palettetown", "electrike", 10L, "qualitative", TRUE,
"palettetown", "manectric", 13L, "qualitative", TRUE,
"palettetown", "plusle", 10L, "qualitative", TRUE,
"palettetown", "minun", 13L, "qualitative", TRUE,
"palettetown", "volbeat", 15L, "qualitative", TRUE,
"palettetown", "illumise", 15L, "qualitative", TRUE,
"palettetown", "roselia", 15L, "qualitative", TRUE,
"palettetown", "gulpin", 11L, "qualitative", TRUE,
"palettetown", "swalot", 14L, "qualitative", TRUE,
"palettetown", "carvanha", 13L, "qualitative", TRUE,
"palettetown", "sharpedo", 14L, "qualitative", TRUE,
"palettetown", "wailmer", 15L, "qualitative", TRUE,
"palettetown", "wailord", 13L, "qualitative", TRUE,
"palettetown", "numel", 15L, "qualitative", TRUE,
"palettetown", "camerupt", 13L, "qualitative", TRUE,
"palettetown", "torkoal", 12L, "qualitative", TRUE,
"palettetown", "spoink", 13L, "qualitative", TRUE,
"palettetown", "grumpig", 15L, "qualitative", TRUE,
"palettetown", "spinda", 10L, "qualitative", TRUE,
"palettetown", "trapinch", 10L, "qualitative", TRUE,
"palettetown", "vibrava", 14L, "qualitative", TRUE,
"palettetown", "flygon", 15L, "qualitative", TRUE,
"palettetown", "cacnea", 14L, "qualitative", TRUE,
"palettetown", "cacturne", 12L, "qualitative", TRUE,
"palettetown", "swablu", 12L, "qualitative", TRUE,
"palettetown", "altaria", 12L, "qualitative", TRUE,
"palettetown", "zangoose", 15L, "qualitative", TRUE,
"palettetown", "seviper", 14L, "qualitative", TRUE,
"palettetown", "lunatone", 14L, "qualitative", TRUE,
"palettetown", "solrock", 14L, "qualitative", TRUE,
"palettetown", "barboach", 12L, "qualitative", TRUE,
"palettetown", "whiscash", 15L, "qualitative", TRUE,
"palettetown", "corphish", 13L, "qualitative", TRUE,
"palettetown", "crawdaunt", 15L, "qualitative", TRUE,
"palettetown", "baltoy", 7L, "qualitative", TRUE,
"palettetown", "claydol", 12L, "qualitative", TRUE,
"palettetown", "lileep", 12L, "qualitative", TRUE,
"palettetown", "cradily", 12L, "qualitative", TRUE,
"palettetown", "anorith", 14L, "qualitative", TRUE,
"palettetown", "armaldo", 14L, "qualitative", TRUE,
"palettetown", "feebas", 13L, "qualitative", TRUE,
"palettetown", "milotic", 14L, "qualitative", TRUE,
"palettetown", "castform", 9L, "qualitative", TRUE,
"palettetown", "kecleon", 15L, "qualitative", TRUE,
"palettetown", "shuppet", 12L, "qualitative", TRUE,
"palettetown", "banette", 12L, "qualitative", TRUE,
"palettetown", "duskull", 13L, "qualitative", TRUE,
"palettetown", "dusclops", 11L, "qualitative", TRUE,
"palettetown", "tropius", 15L, "qualitative", TRUE,
"palettetown", "chimecho", 13L, "qualitative", TRUE,
"palettetown", "absol", 11L, "qualitative", TRUE,
"palettetown", "wynaut", 11L, "qualitative", TRUE,
"palettetown", "snorunt", 15L, "qualitative", TRUE,
"palettetown", "glalie", 13L, "qualitative", TRUE,
"palettetown", "spheal", 12L, "qualitative", TRUE,
"palettetown", "sealeo", 15L, "qualitative", TRUE,
"palettetown", "walrein", 12L, "qualitative", TRUE,
"palettetown", "clamperl", 14L, "qualitative", TRUE,
"palettetown", "huntail", 14L, "qualitative", TRUE,
"palettetown", "gorebyss", 12L, "qualitative", TRUE,
"palettetown", "relicanth", 13L, "qualitative", TRUE,
"palettetown", "luvdisc", 9L, "qualitative", TRUE,
"palettetown", "bagon", 11L, "qualitative", TRUE,
"palettetown", "shelgon", 12L, "qualitative", TRUE,
"palettetown", "salamence", 13L, "qualitative", TRUE,
"palettetown", "beldum", 10L, "qualitative", TRUE,
"palettetown", "metang", 13L, "qualitative", TRUE,
"palettetown", "metagross", 13L, "qualitative", TRUE,
"palettetown", "regirock", 13L, "qualitative", TRUE,
"palettetown", "regice", 10L, "qualitative", TRUE,
"palettetown", "registeel", 13L, "qualitative", TRUE,
"palettetown", "latias", 14L, "qualitative", TRUE,
"palettetown", "latios", 14L, "qualitative", TRUE,
"palettetown", "kyogre", 14L, "qualitative", TRUE,
"palettetown", "groudon", 14L, "qualitative", TRUE,
"palettetown", "rayquaza", 12L, "qualitative", TRUE,
"palettetown", "jirachi", 12L, "qualitative", TRUE,
"palettetown", "deoxys", 14L, "qualitative", TRUE,
"palettetown", "teamrocket", 6L, "qualitative", TRUE,
"palettetown", "starterspairs", 6L, "qualitative", TRUE,
"palettetown", "startersDark", 6L, "qualitative", TRUE,
"pals", "alphabet", 26L, "qualitative", FALSE,
"pals", "alphabet2", 26L, "qualitative", FALSE,
"pals", "glasbey", 32L, "qualitative", FALSE,
"pals", "kelly", 22L, "qualitative", FALSE,
"pals", "polychrome", 36L, "qualitative", FALSE,
"pals", "stepped", 24L, "qualitative", FALSE,
"pals", "tol", 12L, "qualitative", FALSE,
"pals", "watlington", 16L, "qualitative", FALSE,
"Polychrome", "alphabet", 26L, "qualitative", FALSE,
"Polychrome", "dark", 24L, "qualitative", FALSE,
"Polychrome", "glasbey", 32L, "qualitative", FALSE,
"Polychrome", "green_armytage", 26L, "qualitative", FALSE,
"Polychrome", "kelly", 22L, "qualitative", FALSE,
"Polychrome", "light", 24L, "qualitative", FALSE,
"Polychrome", "palette36", 36L, "qualitative", FALSE,
"Manu", "Hihi", 5L, "qualitative", TRUE,
"Manu", "Hoiho", 6L, "qualitative", TRUE,
"Manu", "Kaka", 5L, "qualitative", TRUE,
"Manu", "Kakapo", 6L, "qualitative", TRUE,
"Manu", "Kakariki", 5L, "qualitative", TRUE,
"Manu", "Kea", 7L, "qualitative", TRUE,
"Manu", "Kereru", 6L, "qualitative", TRUE,
"Manu", "Kereru_orig", 5L, "qualitative", TRUE,
"Manu", "Korimako", 6L, "qualitative", TRUE,
"Manu", "Korora", 5L, "qualitative", TRUE,
"Manu", "Kotare", 6L, "qualitative", TRUE,
"Manu", "Putangitangi", 6L, "qualitative", TRUE,
"Manu", "Takahe", 5L, "qualitative", TRUE,
"Manu", "Takapu", 5L, "qualitative", TRUE,
"Manu", "Titipounamu", 6L, "qualitative", TRUE,
"Manu", "Tui", 6L, "qualitative", TRUE,
"Manu", "Pepetuna", 5L, "qualitative", TRUE,
"Manu", "Pohutukawa", 6L, "qualitative", TRUE,
"Manu", "Gloomy_Nudi", 5L, "qualitative", TRUE,
"MapPalettes", "green_machine", 5L, "sequential", FALSE,
"MapPalettes", "bruiser", 5L, "sequential", FALSE,
"MapPalettes", "tealberry_pie", 5L, "divergent", FALSE,
"MapPalettes", "the_joker", 5L, "divergent", FALSE,
"MapPalettes", "sunset", 5L, "divergent", FALSE,
"MapPalettes", "irish_flag", 5L, "divergent", FALSE,
"miscpalettes", "dreaming", 8L, "qualitative", TRUE,
"miscpalettes", "jojo", 8L, "qualitative", TRUE,
"miscpalettes", "beach", 8L, "qualitative", TRUE,
"miscpalettes", "waterfall", 8L, "qualitative", TRUE,
"miscpalettes", "sunset", 8L, "qualitative", TRUE,
"miscpalettes", "bright", 16L, "qualitative", TRUE,
"miscpalettes", "grayscale", 16L, "sequential", TRUE,
"miscpalettes", "excel", 16L, "qualitative", TRUE,
"miscpalettes", "light", 10L, "qualitative", TRUE,
"miscpalettes", "pastel", 16L, "qualitative", TRUE,
"miscpalettes", "earthTones", 16L, "qualitative", TRUE,
"miscpalettes", "semiTransparent", 16L, "qualitative", TRUE,
"miscpalettes", "berry", 11L, "qualitative", TRUE,
"miscpalettes", "chocolate", 10L, "qualitative", TRUE,
"miscpalettes", "fire", 10L, "qualitative", TRUE,
"miscpalettes", "seaGreen", 10L, "qualitative", TRUE,
"miscpalettes", "brightPastel", 15L, "qualitative", TRUE,
"palettesForR", "Android", 15L, "qualitative", TRUE,
"palettesForR", "Bears", 256L, "qualitative", TRUE,
"palettesForR", "Bgold", 256L, "qualitative", TRUE,
"palettesForR", "Blues", 256L, "qualitative", TRUE,
"palettesForR", "Borders", 256L, "qualitative", TRUE,
"palettesForR", "Browns", 22L, "qualitative", TRUE,
"palettesForR", "Caramel", 256L, "qualitative", TRUE,
"palettesForR", "Cascade", 256L, "qualitative", TRUE,
"palettesForR", "China", 256L, "qualitative", TRUE,
"palettesForR", "Coldfire", 256L, "qualitative", TRUE,
"palettesForR", "Cool", 8L, "qualitative", TRUE,
"palettesForR", "Cranes", 256L, "qualitative", TRUE,
"palettesForR", "Dark", 256L, "qualitative", TRUE,
"palettesForR", "Default", 23L, "qualitative", TRUE,
"palettesForR", "Echo", 27L, "qualitative", TRUE,
"palettesForR", "Ega", 240L, "qualitative", TRUE,
"palettesForR", "Firecode", 256L, "sequential", TRUE,
"palettesForR", "Gold", 102L, "sequential", TRUE,
"palettesForR", "Gray", 256L, "sequential", TRUE,
"palettesForR", "Grayblue", 256L, "divergent", TRUE,
"palettesForR", "Grays", 31L, "sequential", TRUE,
"palettesForR", "GrayViolet", 256L, "divergent", TRUE,
"palettesForR", "Greens", 256L, "qualitative", TRUE,
"palettesForR", "Hilite", 170L, "qualitative", TRUE,
"palettesForR", "Inkscape", 431L, "qualitative", TRUE,
"palettesForR", "Khaki", 156L, "qualitative", TRUE,
"palettesForR", "LaTeX", 136L, "qualitative", TRUE,
"palettesForR", "Lights", 25L, "qualitative", TRUE,
"palettesForR", "MATLAB", 73L, "qualitative", TRUE,
"palettesForR", "Muted", 78L, "qualitative", TRUE,
"palettesForR", "Named", 448L, "qualitative", TRUE,
"palettesForR", "News3", 256L, "qualitative", TRUE,
"palettesForR", "Op2", 256L, "qualitative", TRUE,
"palettesForR", "Paintjet", 16L, "qualitative", TRUE,
"palettesForR", "Pastels", 18L, "qualitative", TRUE,
"palettesForR", "Plasma", 256L, "qualitative", TRUE,
"palettesForR", "Reds", 177L, "qualitative", TRUE,
"palettesForR", "Royal", 222L, "qualitative", TRUE,
"palettesForR", "SVG", 139L, "qualitative", TRUE,
"palettesForR", "Tango", 29L, "qualitative", TRUE,
"palettesForR", "Topographic", 191L, "qualitative", TRUE,
"palettesForR", "Visibone", 336L, "qualitative", TRUE,
"palettesForR", "Volcano", 256L, "qualitative", TRUE,
"palettesForR", "Warm", 7L, "qualitative", TRUE,
"palettesForR", "Web", 216L, "qualitative", TRUE,
"palettesForR", "WebHex", 216L, "qualitative", TRUE,
"palettesForR", "WebSafe22", 22L, "qualitative", TRUE,
"palettesForR", "Windows", 31L, "qualitative", TRUE,
"PNWColors", "Starfish", 7L, "sequential", TRUE,
"PNWColors", "Shuksan", 8L, "sequential", TRUE,
"PNWColors", "Bay", 5L, "qualitative", TRUE,
"PNWColors", "Winter", 5L, "sequential", TRUE,
"PNWColors", "Lake", 8L, "sequential", TRUE,
"PNWColors", "Sunset", 7L, "sequential", TRUE,
"PNWColors", "Shuksan2", 5L, "divergent", TRUE,
"PNWColors", "Cascades", 6L, "qualitative", TRUE,
"PNWColors", "Sailboat", 6L, "qualitative", TRUE,
"PNWColors", "Moth", 5L, "qualitative", TRUE,
"PNWColors", "Spring", 6L, "divergent", TRUE,
"PNWColors", "Mushroom", 6L, "sequential", TRUE,
"PNWColors", "Sunset2", 5L, "sequential", TRUE,
"PNWColors", "Anemone", 7L, "divergent", TRUE,
"rcartocolor", "ag_Sunset", 7L, "sequential", FALSE,
"rcartocolor", "ag_GrnYl", 7L, "sequential", FALSE,
"rcartocolor", "Tropic", 7L, "divergent", FALSE,
"rcartocolor", "Temps", 7L, "divergent", FALSE,
"rcartocolor", "TealRose", 7L, "divergent", FALSE,
"rcartocolor", "Geyser", 7L, "divergent", FALSE,
"rcartocolor", "Fall", 7L, "divergent", FALSE,
"rcartocolor", "Earth", 7L, "divergent", FALSE,
"rcartocolor", "ArmyRose", 7L, "divergent", FALSE,
"rcartocolor", "Vivid", 12L, "qualitative", FALSE,
"rcartocolor", "Safe", 12L, "qualitative", FALSE,
"rcartocolor", "Prism", 12L, "qualitative", FALSE,
"rcartocolor", "Pastel", 12L, "qualitative", FALSE,
"rcartocolor", "Bold", 12L, "qualitative", FALSE,
"rcartocolor", "Antique", 12L, "qualitative", FALSE,
"rcartocolor", "TealGrn", 7L, "sequential", FALSE,
"rcartocolor", "Teal", 7L, "sequential", FALSE,
"rcartocolor", "SunsetDark", 7L, "sequential", FALSE,
"rcartocolor", "Sunset", 7L, "sequential", FALSE,
"rcartocolor", "RedOr", 7L, "sequential", FALSE,
"rcartocolor", "PurpOr", 7L, "sequential", FALSE,
"rcartocolor", "Purp", 7L, "sequential", FALSE,
"rcartocolor", "PinkYl", 7L, "sequential", FALSE,
"rcartocolor", "Peach", 7L, "sequential", FALSE,
"rcartocolor", "OrYel", 7L, "sequential", FALSE,
"rcartocolor", "Mint", 7L, "sequential", FALSE,
"rcartocolor", "Magenta", 7L, "sequential", FALSE,
"rcartocolor", "Emrld", 7L, "sequential", FALSE,
"rcartocolor", "DarkMint", 7L, "sequential", FALSE,
"rcartocolor", "BurgYl", 7L, "sequential", FALSE,
"rcartocolor", "Burg", 7L, "sequential", FALSE,
"rcartocolor", "BrwnYl", 7L, "sequential", FALSE,
"rcartocolor", "BluYl", 7L, "sequential", FALSE,
"rcartocolor", "BluGrn", 7L, "sequential", FALSE,
"RColorBrewer", "BrBG", 11L, "divergent", FALSE,
"RColorBrewer", "PiYG", 11L, "divergent", FALSE,
"RColorBrewer", "PRGn", 11L, "divergent", FALSE,
"RColorBrewer", "PuOr", 11L, "divergent", FALSE,
"RColorBrewer", "RdBu", 11L, "divergent", FALSE,
"RColorBrewer", "RdGy", 11L, "divergent", FALSE,
"RColorBrewer", "RdYlBu", 11L, "divergent", FALSE,
"RColorBrewer", "RdYlGn", 11L, "divergent", FALSE,
"RColorBrewer", "Spectral", 11L, "sequential", FALSE,
"RColorBrewer", "Accent", 8L, "qualitative", FALSE,
"RColorBrewer", "Dark2", 8L, "qualitative", FALSE,
"RColorBrewer", "Paired", 12L, "qualitative", FALSE,
"RColorBrewer", "Pastel1", 9L, "qualitative", FALSE,
"RColorBrewer", "Pastel2", 8L, "qualitative", FALSE,
"RColorBrewer", "Set1", 9L, "qualitative", FALSE,
"RColorBrewer", "Set2", 8L, "qualitative", FALSE,
"RColorBrewer", "Set3", 12L, "qualitative", FALSE,
"RColorBrewer", "Blues", 9L, "sequential", FALSE,
"RColorBrewer", "BuGn", 9L, "sequential", FALSE,
"RColorBrewer", "BuPu", 9L, "sequential", FALSE,
"RColorBrewer", "GnBu", 9L, "sequential", FALSE,
"RColorBrewer", "Greens", 9L, "sequential", FALSE,
"RColorBrewer", "Greys", 9L, "sequential", FALSE,
"RColorBrewer", "Oranges", 9L, "sequential", FALSE,
"RColorBrewer", "OrRd", 9L, "sequential", FALSE,
"RColorBrewer", "PuBu", 9L, "sequential", FALSE,
"RColorBrewer", "PuBuGn", 9L, "sequential", FALSE,
"RColorBrewer", "PuRd", 9L, "sequential", FALSE,
"RColorBrewer", "Purples", 9L, "sequential", FALSE,
"RColorBrewer", "RdPu", 9L, "sequential", FALSE,
"RColorBrewer", "Reds", 9L, "sequential", FALSE,
"RColorBrewer", "YlGn", 9L, "sequential", FALSE,
"RColorBrewer", "YlGnBu", 9L, "sequential", FALSE,
"RColorBrewer", "YlOrBr", 9L, "sequential", FALSE,
"RColorBrewer", "YlOrRd", 9L, "sequential", FALSE,
"Redmonder", "dPBIYlBu", 11L, "divergent", TRUE,
"Redmonder", "dPBIYlPu", 11L, "divergent", TRUE,
"Redmonder", "dPBIPuGn", 11L, "divergent", TRUE,
"Redmonder", "dPBIPuOr", 11L, "divergent", TRUE,
"Redmonder", "dPBIRdBu", 11L, "divergent", TRUE,
"Redmonder", "dPBIRdGy", 11L, "divergent", TRUE,
"Redmonder", "dPBIRdGn", 11L, "divergent", TRUE,
"Redmonder", "qMSOStd", 10L, "qualitative", TRUE,
"Redmonder", "qMSO12", 8L, "qualitative", TRUE,
"Redmonder", "qMSO15", 8L, "qualitative", TRUE,
"Redmonder", "qMSOBuWarm", 8L, "qualitative", TRUE,
"Redmonder", "qMSOBu", 8L, "qualitative", TRUE,
"Redmonder", "qMSOBu2", 8L, "qualitative", TRUE,
"Redmonder", "qMSOBuGn", 8L, "qualitative", TRUE,
"Redmonder", "qMSOGn", 8L, "qualitative", TRUE,
"Redmonder", "qMSOGnYl", 8L, "qualitative", TRUE,
"Redmonder", "qMSOYl", 8L, "qualitative", TRUE,
"Redmonder", "qMSOYlOr", 8L, "qualitative", TRUE,
"Redmonder", "qMSOOr", 8L, "qualitative", TRUE,
"Redmonder", "qMSOOrRd", 8L, "qualitative", TRUE,
"Redmonder", "qMSORdOr", 8L, "qualitative", TRUE,
"Redmonder", "qMSORd", 8L, "qualitative", TRUE,
"Redmonder", "qMSORdPu", 8L, "qualitative", TRUE,
"Redmonder", "qMSOPu", 8L, "qualitative", TRUE,
"Redmonder", "qMSOPu2", 8L, "qualitative", TRUE,
"Redmonder", "qMSOMed", 8L, "qualitative", TRUE,
"Redmonder", "qMSOPap", 8L, "qualitative", TRUE,
"Redmonder", "qMSOMrq", 8L, "qualitative", TRUE,
"Redmonder", "qMSOSlp", 8L, "qualitative", TRUE,
"Redmonder", "qMSOAsp", 8L, "qualitative", TRUE,
"Redmonder", "qPBI", 8L, "qualitative", TRUE,
"Redmonder", "sPBIGn", 9L, "sequential", TRUE,
"Redmonder", "sPBIGy1", 9L, "sequential", TRUE,
"Redmonder", "sPBIRd", 9L, "sequential", TRUE,
"Redmonder", "sPBIYl", 9L, "sequential", TRUE,
"Redmonder", "sPBIGy2", 9L, "sequential", TRUE,
"Redmonder", "sPBIBu", 9L, "sequential", TRUE,
"Redmonder", "sPBIOr", 9L, "sequential", TRUE,
"Redmonder", "sPBIPu", 9L, "sequential", TRUE,
"Redmonder", "sPBIYlGn", 9L, "sequential", TRUE,
"Redmonder", "sPBIRdPu", 9L, "sequential", TRUE,
"rockthemes", "alice", 4L, "qualitative", TRUE,
"rockthemes", "californication", 4L, "qualitative", TRUE,
"rockthemes", "coltrane", 4L, "qualitative", TRUE,
"rockthemes", "deelite", 4L, "qualitative", TRUE,
"rockthemes", "electric", 4L, "qualitative", TRUE,
"rockthemes", "facelift", 4L, "qualitative", TRUE,
"rockthemes", "faithnomore", 4L, "qualitative", TRUE,
"rockthemes", "harvey", 4L, "qualitative", TRUE,
"rockthemes", "heep", 4L, "qualitative", TRUE,
"rockthemes", "hellawaits", 4L, "qualitative", TRUE,
"rockthemes", "husker", 4L, "qualitative", TRUE,
"rockthemes", "janelle", 4L, "qualitative", TRUE,
"rockthemes", "melloncollie", 4L, "qualitative", TRUE,
"rockthemes", "miles", 4L, "qualitative", TRUE,
"rockthemes", "muse", 4L, "qualitative", TRUE,
"rockthemes", "nodoubt", 4L, "qualitative", TRUE,
"rockthemes", "peacesells", 4L, "qualitative", TRUE,
"rockthemes", "secondlaw", 4L, "qualitative", TRUE,
"rockthemes", "siamesedream", 4L, "qualitative", TRUE,
"rockthemes", "swift", 4L, "qualitative", TRUE,
"rockthemes", "zeppelin", 4L, "qualitative", TRUE,
"RSkittleBrewer", "original", 5L, "qualitative", TRUE,
"RSkittleBrewer", "tropical", 5L, "qualitative", TRUE,
"RSkittleBrewer", "wildberry", 5L, "qualitative", TRUE,
"RSkittleBrewer", "M_M", 6L, "qualitative", TRUE,
"RSkittleBrewer", "smarties", 8L, "qualitative", TRUE,
"rtist", "raphael", 5L, "qualitative", TRUE,
"rtist", "hokusai", 5L, "qualitative", TRUE,
"rtist", "vermeer", 5L, "qualitative", TRUE,
"rtist", "degas", 5L, "qualitative", TRUE,
"rtist", "davinci", 5L, "qualitative", TRUE,
"rtist", "vangogh", 5L, "qualitative", TRUE,
"rtist", "hopper", 5L, "qualitative", TRUE,
"rtist", "klimt", 5L, "qualitative", TRUE,
"rtist", "rembrandt", 5L, "qualitative", TRUE,
"rtist", "munch", 5L, "qualitative", TRUE,
"rtist", "warhol", 5L, "qualitative", TRUE,
"rtist", "okeeffe", 5L, "qualitative", TRUE,
"rtist", "oldenburg", 5L, "qualitative", TRUE,
"rtist", "picasso", 5L, "qualitative", TRUE,
"rtist", "pollock", 5L, "qualitative", TRUE,
"soilpalettes", "alaquod", 5L, "qualitative", TRUE,
"soilpalettes", "bangor", 5L, "qualitative", TRUE,
"soilpalettes", "durorthod", 5L, "sequential", TRUE,
"soilpalettes", "paleustalf", 5L, "qualitative", TRUE,
"soilpalettes", "rendoll", 5L, "qualitative", TRUE,
"soilpalettes", "redox", 5L, "qualitative", TRUE,
"soilpalettes", "podzol", 5L, "sequential", TRUE,
"soilpalettes", "eutrostox", 5L, "sequential", TRUE,
"soilpalettes", "pywell", 5L, "qualitative", TRUE,
"soilpalettes", "natrudoll", 5L, "sequential", TRUE,
"soilpalettes", "vitrixerand", 5L, "sequential", TRUE,
"soilpalettes", "crait", 5L, "sequential", TRUE,
"soilpalettes", "gley", 5L, "sequential", TRUE,
"soilpalettes", "redox2", 5L, "qualitative", TRUE,
"suffrager", "london", 4L, "qualitative", TRUE,
"suffrager", "oxon", 5L, "qualitative", TRUE,
"suffrager", "CarolMan", 4L, "qualitative", TRUE,
"suffrager", "hanwell", 5L, "qualitative", TRUE,
"suffrager", "chelsea", 5L, "qualitative", TRUE,
"suffrager", "classic", 2L, "qualitative", TRUE,
"tayloRswift", "taylorSwift", 6L, "qualitative", TRUE,
"tayloRswift", "fearless", 5L, "qualitative", TRUE,
"tayloRswift", "speakNow", 5L, "qualitative", TRUE,
"tayloRswift", "speakNowLive", 5L, "qualitative", TRUE,
"tayloRswift", "taylorRed", 5L, "qualitative", TRUE,
"tayloRswift", "taylor1989", 6L, "qualitative", TRUE,
"tayloRswift", "reputation", 6L, "qualitative", TRUE,
"tayloRswift", "lover", 6L, "qualitative", TRUE,
"tayloRswift", "folklore", 4L, "sequential", TRUE,
"tayloRswift", "evermore", 5L, "qualitative", TRUE,
"tidyquant", "tq_light", 12L, "qualitative", FALSE,
"tidyquant", "tq_dark", 12L, "qualitative", FALSE,
"tidyquant", "tq_green", 12L, "qualitative", FALSE,
"trekcolors", "andorian", 9L, "sequential", TRUE,
"trekcolors", "bajoran", 6L, "qualitative", TRUE,
"trekcolors", "borg", 9L, "sequential", TRUE,
"trekcolors", "breen", 8L, "qualitative", TRUE,
"trekcolors", "breen2", 9L, "sequential", TRUE,
"trekcolors", "dominion", 7L, "qualitative", TRUE,
"trekcolors", "enara", 9L, "sequential", TRUE,
"trekcolors", "enara2", 4L, "qualitative", TRUE,
"trekcolors", "ferengi", 9L, "divergent", TRUE,
"trekcolors", "gorn", 9L, "qualitative", TRUE,
"trekcolors", "iconian", 9L, "sequential", TRUE,
"trekcolors", "klingon", 9L, "sequential", TRUE,
"trekcolors", "lcars_series", 31L, "qualitative", TRUE,
"trekcolors", "lcars_2357", 9L, "qualitative", TRUE,
"trekcolors", "lcars_2369", 8L, "qualitative", TRUE,
"trekcolors", "lcars_2375", 8L, "qualitative", TRUE,
"trekcolors", "lcars_2379", 8L, "qualitative", TRUE,
"trekcolors", "lcars_alt", 17L, "qualitative", TRUE,
"trekcolors", "lcars_first_contact", 8L, "qualitative", TRUE,
"trekcolors", "lcars_nemesis", 10L, "qualitative", TRUE,
"trekcolors", "lcars_nx01", 6L, "qualitative", TRUE,
"trekcolors", "lcars_29c", 8L, "qualitative", TRUE,
"trekcolors", "lcars_23c", 7L, "qualitative", TRUE,
"trekcolors", "lcars_red_alert", 8L, "qualitative", TRUE,
"trekcolors", "lcars_cardassian", 21L, "qualitative", TRUE,
"trekcolors", "romulan", 9L, "divergent", TRUE,
"trekcolors", "romulan2", 9L, "divergent", TRUE,
"trekcolors", "starfleet", 3L, "qualitative", TRUE,
"trekcolors", "starfleet2", 6L, "qualitative", TRUE,
"trekcolors", "tholian", 9L, "divergent", TRUE,
"trekcolors", "terran", 9L, "sequential", TRUE,
"trekcolors", "ufp", 9L, "sequential", TRUE,
"trekcolors", "red_alert", 6L, "qualitative", TRUE,
"trekcolors", "yellow_alert", 6L, "qualitative", TRUE,
"trekcolors", "black_alert", 5L, "qualitative", TRUE,
"tvthemes", "attackOnTitan", 8L, "qualitative", TRUE,
"tvthemes", "FireNation", 8L, "qualitative", TRUE,
"tvthemes", "AirNomads", 7L, "qualitative", TRUE,
"tvthemes", "EarthKingdom", 9L, "qualitative", TRUE,
"tvthemes", "WaterTribe", 8L, "qualitative", TRUE,
"tvthemes", "bigHero6", 8L, "qualitative", TRUE,
"tvthemes", "Regular", 10L, "qualitative", TRUE,
"tvthemes", "Dark", 9L, "qualitative", TRUE,
"tvthemes", "gravityFalls", 14L, "qualitative", TRUE,
"tvthemes", "Day", 8L, "qualitative", TRUE,
"tvthemes", "Dusk", 8L, "qualitative", TRUE,
"tvthemes", "Night", 8L, "qualitative", TRUE,
"tvthemes", "kimPossible", 12L, "qualitative", TRUE,
"tvthemes", "parksAndRec", 10L, "qualitative", TRUE,
"tvthemes", "rickAndMorty", 9L, "qualitative", TRUE,
"tvthemes", "simpsons", 10L, "qualitative", TRUE,
"tvthemes", "spongeBob", 9L, "qualitative", TRUE,
"tvthemes", "Stark", 9L, "qualitative", TRUE,
"tvthemes", "Stannis", 7L, "qualitative", TRUE,
"tvthemes", "Lannister", 6L, "qualitative", TRUE,
"tvthemes", "Tyrell", 9L, "qualitative", TRUE,
"tvthemes", "Targaryen", 5L, "qualitative", TRUE,
"tvthemes", "Martell", 8L, "qualitative", TRUE,
"tvthemes", "Tully", 6L, "qualitative", TRUE,
"tvthemes", "Greyjoy", 6L, "qualitative", TRUE,
"tvthemes", "Manderly", 7L, "qualitative", TRUE,
"tvthemes", "Arryn", 7L, "qualitative", TRUE,
"unikn", "pal_unikn", 11L, "divergent", TRUE,
"unikn", "pal_unikn_web", 10L, "divergent", TRUE,
"unikn", "pal_unikn_ppt", 10L, "divergent", TRUE,
"unikn", "pal_unikn_light", 10L, "qualitative", TRUE,
"unikn", "pal_unikn_dark", 10L, "qualitative", TRUE,
"unikn", "pal_unikn_pair", 16L, "qualitative", TRUE,
"unikn", "pal_unikn_pref", 9L, "qualitative", TRUE,
"unikn", "pal_seeblau", 5L, "sequential", TRUE,
"unikn", "pal_peach", 5L, "sequential", TRUE,
"unikn", "pal_grau", 5L, "sequential", TRUE,
"unikn", "pal_petrol", 5L, "sequential", TRUE,
"unikn", "pal_seegruen", 5L, "sequential", TRUE,
"unikn", "pal_karpfenblau", 5L, "sequential", TRUE,
"unikn", "pal_pinky", 5L, "sequential", TRUE,
"unikn", "pal_bordeaux", 5L, "sequential", TRUE,
"unikn", "pal_signal", 3L, "qualitative", TRUE,
"vapeplot", "vaporwave", 14L, "qualitative", TRUE,
"vapeplot", "cool", 5L, "qualitative", TRUE,
"vapeplot", "crystal_pepsi", 4L, "qualitative", TRUE,
"vapeplot", "mallsoft", 6L, "qualitative", TRUE,
"vapeplot", "jazzcup", 5L, "qualitative", TRUE,
"vapeplot", "sunset", 5L, "qualitative", TRUE,
"vapeplot", "macplus", 6L, "qualitative", TRUE,
"vapeplot", "seapunk", 5L, "qualitative", TRUE,
"vapoRwave", "avanti", 5L, "qualitative", TRUE,
"vapoRwave", "cool", 5L, "sequential", TRUE,
"vapoRwave", "crystalPepsi", 4L, "sequential", TRUE,
"vapoRwave", "floralShoppe", 8L, "qualitative", TRUE,
"vapoRwave", "hotlineBling", 8L, "qualitative", TRUE,
"vapoRwave", "hyperBubble", 7L, "qualitative", TRUE,
"vapoRwave", "jazzCup", 5L, "qualitative", TRUE,
"vapoRwave", "jwz", 8L, "qualitative", TRUE,
"vapoRwave", "macPlus", 6L, "divergent", TRUE,
"vapoRwave", "mallSoft", 6L, "qualitative", TRUE,
"vapoRwave", "newRetro", 9L, "qualitative", TRUE,
"vapoRwave", "seaPunk", 5L, "qualitative", TRUE,
"vapoRwave", "sunSet", 5L, "qualitative", TRUE,
"vapoRwave", "vapoRwave", 11L, "qualitative", TRUE,
"werpals", "cinderella", 5L, "qualitative", TRUE,
"werpals", "monet", 6L, "sequential", TRUE,
"werpals", "small_world", 6L, "qualitative", TRUE,
"werpals", "alice", 6L, "qualitative", TRUE,
"werpals", "pan", 6L, "qualitative", TRUE,
"werpals", "when_i_was_your_age", 6L, "qualitative", TRUE,
"werpals", "firefly", 7L, "qualitative", TRUE,
"werpals", "uyuni", 10L, "qualitative", TRUE,
"werpals", "okavango", 10L, "qualitative", TRUE,
"werpals", "lakelouise", 10L, "qualitative", TRUE,
"werpals", "provence", 10L, "qualitative", TRUE,
"werpals", "halong", 10L, "qualitative", TRUE,
"werpals", "vatnajokull", 10L, "qualitative", TRUE,
"werpals", "arashiyama", 10L, "qualitative", TRUE,
"werpals", "mountcook", 10L, "qualitative", TRUE,
"werpals", "benagil", 10L, "qualitative", TRUE,
"werpals", "bryce", 10L, "qualitative", TRUE,
"werpals", "jozi", 10L, "qualitative", TRUE,
"wesanderson", "BottleRocket1", 7L, "qualitative", TRUE,
"wesanderson", "BottleRocket2", 5L, "qualitative", TRUE,
"wesanderson", "Rushmore1", 5L, "qualitative", TRUE,
"wesanderson", "Rushmore", 5L, "qualitative", TRUE,
"wesanderson", "Royal1", 4L, "qualitative", TRUE,
"wesanderson", "Royal2", 5L, "qualitative", TRUE,
"wesanderson", "Zissou1", 5L, "qualitative", TRUE,
"wesanderson", "Darjeeling1", 5L, "qualitative", TRUE,
"wesanderson", "Darjeeling2", 5L, "qualitative", TRUE,
"wesanderson", "Chevalier1", 4L, "qualitative", TRUE,
"wesanderson", "FantasticFox1", 5L, "qualitative", TRUE,
"wesanderson", "Moonrise1", 4L, "qualitative", TRUE,
"wesanderson", "Moonrise2", 4L, "qualitative", TRUE,
"wesanderson", "Moonrise3", 5L, "qualitative", TRUE,
"wesanderson", "Cavalcanti1", 5L, "qualitative", TRUE,
"wesanderson", "GrandBudapest1", 4L, "qualitative", TRUE,
"wesanderson", "GrandBudapest2", 4L, "qualitative", TRUE,
"wesanderson", "IsleofDogs1", 6L, "qualitative", TRUE,
"wesanderson", "IsleofDogs2", 5L, "qualitative", TRUE,
"yarrr", "basel", 10L, "qualitative", TRUE,
"yarrr", "pony", 9L, "qualitative", TRUE,
"yarrr", "xmen", 8L, "qualitative", TRUE,
"yarrr", "decision", 6L, "qualitative", TRUE,
"yarrr", "southpark", 6L, "qualitative", TRUE,
"yarrr", "google", 4L, "qualitative", TRUE,
"yarrr", "eternal", 7L, "qualitative", TRUE,
"yarrr", "evildead", 6L, "qualitative", TRUE,
"yarrr", "usualsuspects", 7L, "qualitative", TRUE,
"yarrr", "ohbrother", 7L, "qualitative", TRUE,
"yarrr", "appletv", 6L, "qualitative", TRUE,
"yarrr", "brave", 5L, "qualitative", TRUE,
"yarrr", "bugs", 5L, "qualitative", TRUE,
"yarrr", "cars", 5L, "qualitative", TRUE,
"yarrr", "nemo", 5L, "qualitative", TRUE,
"yarrr", "rat", 5L, "qualitative", TRUE,
"yarrr", "up", 5L, "qualitative", TRUE,
"yarrr", "espresso", 5L, "qualitative", TRUE,
"yarrr", "ipod", 7L, "qualitative", TRUE,
"yarrr", "info", 9L, "qualitative", TRUE,
"yarrr", "info2", 14L, "qualitative", TRUE,
)
usethis::use_data(palettes_d_names, overwrite = TRUE) |
pandterm=function(message) { stop(message,call.=FALSE) } |
layer.density <- function(top, bottom, wtr, depths, bthA, bthD, sal = wtr*0){
force(sal)
if(top>bottom){
stop('bottom depth must be greater than top')
}else if(length(wtr)!=length(depths)){
stop('water temperature vector must be same length as depth vector')
}else if(length(as.list(match.call()))<4){
stop('not enough input arguments')
}else if(any(is.na(wtr),is.na(depths),is.na(bthA),is.na(bthD))){
stop('input arguments must be numbers')
}
if(min(bthD)<0){
useI <- bthD>=0
if(!any(bthD==0)){
depT <- c(0,bthD[useI])
}else{
depT <- bthD[useI]
}
bthA <- stats::approx(bthD,bthA,depT)$y
bthD <- depT
}
dz <- 0.1
numD <- length(wtr)
if(max(bthD)>depths[numD]){
wtr[numD+1] <- wtr[numD]
sal[numD+1] <- sal[numD]
depths[numD+1] <- max(bthD)
}else if(max(bthD)<depths[numD]){
bthD <- c(bthD,depths[numD])
bthA <- c(bthA,0)
}
if(min(bthD)<depths[1]){
wtr <- c(wtr[1],wtr)
sal <- c(sal[1],sal)
depths <- c(min(bthD),depths)
}
Io <- grep(min(depths),depths)
Ao <- bthA[Io]
if(Ao[1]==0){
stop('surface area cannot be zero, check bathymetry file')
}
layerD <- seq(top,bottom,dz)
layerT <- stats::approx(depths,wtr,layerD)$y
layerS <- stats::approx(depths,sal,layerD)$y
layerA <- stats::approx(bthD,bthA,layerD)$y
layerP <- water.density(layerT,layerS)
mass <- layerA*layerP*dz
aveDensity <- sum(mass)/(sum(layerA))/dz
return(aveDensity)
} |
context("Build map")
test_that("Default map", {
default_map <- getSpMaps()
expect_is(default_map, "SpatialPolygonsDataFrame")
})
test_that("Subset and combine", {
combine_map <- getSpMaps(countries = c("ITA", "ESP", "FRA"), states = "FRA")
expect_is(combine_map, "SpatialPolygonsDataFrame")
all_map <- getSpMaps(countries = "all", states = "all")
expect_is(all_map, "SpatialPolygonsDataFrame")
all_map_2 <- getSpMaps(countries = "all", states = NULL)
expect_is(all_map, "SpatialPolygonsDataFrame")
all_map_3 <- getSpMaps(countries = NULL, states = "all")
expect_is(all_map, "SpatialPolygonsDataFrame")
all_map_4 <- getSpMaps(countries = "all", states = "FRA")
expect_is(all_map, "SpatialPolygonsDataFrame")
all_map_5 <- getSpMaps(countries = "FRA", states = "all")
expect_is(all_map, "SpatialPolygonsDataFrame")
})
test_that("NULL map", {
null_map <- suppressMessages(getSpMaps(countries = NULL, states = NULL))
expect_null(null_map)
})
test_that("Invalid countries and states", {
expect_error(getSpMaps(countries = "invalid"))
expect_error(getSpMaps(states = "invalid"))
}) |
test_that('3+3 enforcer errors when it should.', {
expect_error(enforce_three_plus_three(outcomes = '1NNN 1N'))
expect_error(enforce_three_plus_three(outcomes = '1NNN 1NNN'))
expect_error(enforce_three_plus_three(outcomes = '1NNN 2NNT 2NNN 4N'))
expect_error(enforce_three_plus_three(outcomes = '1NNN 2TTT 1N'))
})
test_that('3+3 enforcer acquiesces when it should.', {
expect_null(enforce_three_plus_three(outcomes = ''))
expect_null(enforce_three_plus_three(outcomes = '1N'))
expect_null(enforce_three_plus_three(outcomes = '1T'))
expect_null(enforce_three_plus_three(outcomes = '1NN'))
expect_null(enforce_three_plus_three(outcomes = '1NT'))
expect_null(enforce_three_plus_three(outcomes = '1TT'))
expect_null(enforce_three_plus_three(outcomes = '1NNN'))
expect_null(enforce_three_plus_three(outcomes = '1NNT'))
expect_null(enforce_three_plus_three(outcomes = '1NTT'))
expect_null(enforce_three_plus_three(outcomes = '1TTT'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2N'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2T'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NN'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NT'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2TT'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNN'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNT'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NTT'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2TTT'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNT 2N'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNT 2T'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNT 2NN'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNT 2NT'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNT 2TT'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNT 2NNN'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNT 2NNT'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNT 2NTT'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNT 2NNN'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNN 3NNN 4NNN 5N'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNN 3NNN 4NNN 5NN'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNN 3NNN 4NNN 5NNN'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNN 3NNN 4NNN 5NNT'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNN 3NNN 4NNN 5NTT'))
expect_null(enforce_three_plus_three(outcomes = '1NNN 2NNN 3NNN 4NNN 5TTT'))
expect_null(enforce_three_plus_three(
outcomes = '1NNN 2NNN 3NNN 4NNN 5NNT 5N'))
expect_null(enforce_three_plus_three(
outcomes = '1NNN 2NNN 3NNN 4NNN 5NNT 5NN'))
expect_null(enforce_three_plus_three(
outcomes = '1NNN 2NNN 3NNN 4NNN 5NNT 5NT'))
expect_null(enforce_three_plus_three(
outcomes = '1NNN 2NNN 3NNN 4NNN 5NNT 5TT'))
expect_null(enforce_three_plus_three(
outcomes = '1NNN 2NNN 3NNN 4NNN 5NNT 5NNN'))
expect_null(enforce_three_plus_three(
outcomes = '1NNN 2NNN 3NNN 4NNN 5NNT 5NNT'))
expect_null(enforce_three_plus_three(
outcomes = '1NNN 2NNN 3NNN 4NNN 5NNT 5NTT'))
expect_null(enforce_three_plus_three(
outcomes = '1NNN 2NNN 3NNN 4NNN 5NNT 5TTT'))
}) |
test_that("load_sharpe_games works", {
g <- load_sharpe_games()
skip_if_not(nrow(g) > 0, message = NULL)
expect_true(is_tibble(g))
}) |
packageVersion("plantecophys")
library(plantecophys)
f <- fitaci(acidata1, gmeso=0.2)
acidata1$Cc <- with(acidata1, Ci - Photo/0.2)
f <- fitaci(acidata1, varnames=list(ALEAF="Photo", Ci="Cc", Tleaf="Tleaf", PPFD="PARi")) |
France <- R6::R6Class("France",
inherit = DataClass,
public = list(
origin = "France",
supported_levels = list("1", "2"),
supported_region_names = list("1" = "region", "2" = "department"),
supported_region_codes = list("1" = "iso_3166_2", "2" = "ons_region_code"),
level_data_urls = list(
"1" = list("cases" = "https://www.data.gouv.fr/fr/datasets/r/001aca18-df6a-45c8-89e6-f82d689e6c01"),
"2" = list(
"cases" = "https://www.data.gouv.fr/fr/datasets/r/406c6a23-e283-4300-9484-54e78c8ae675",
"hosp" = "https://www.data.gouv.fr/fr/datasets/r/6fadff46-9efd-4c53-942a-54aca783c30c"
)
),
source_data_cols = c("cases_new", "tested_new"),
source_text = "French Public Open Data Platform",
source_url = "https://www.data.gouv.fr/fr/pages/donnees-coronavirus",
set_region_codes = function() {
self$codes_lookup$`1` <- france_codes %>%
select(
.data$level_1_region_code,
.data$level_1_region,
.data$insee_code
)
self$codes_lookup$`2` <- france_codes
},
clean_level_1 = function() {
self$data$clean <- self$data$raw$cases %>%
filter(.data$cl_age90 == 0) %>%
select(
date = .data$jour,
insee_code = .data$reg,
cases_new = .data$P,
tested_new = .data$`T`
) %>%
mutate(date = as_date(ymd(date))) %>%
left_join(
self$codes_lookup$`1`,
insee_code = reg,
by = c("insee_code")
)
},
clean_level_2 = function() {
cases_data <- self$data$raw$cases %>%
filter(.data$cl_age90 == 0) %>%
select(
date = .data$jour,
level_2_region_code = .data$dep,
cases_new = .data$P,
tested_new = .data$`T`
) %>%
mutate(date = as_date(ymd(date)))
if (!is.null(self$data$raw$hosp)) {
hosp_data <- self$data$raw$hosp %>%
select(
date = jour,
level_2_region_code = dep,
hosp_new = incid_hosp,
deaths_new = incid_dc
) %>%
mutate(date = as_date(ymd(date)))
combined_data <- full_join(cases_data, hosp_data,
by = c("date", "level_2_region_code")
)
} else {
combined_data <- cases_data
}
self$data$clean <- combined_data %>%
mutate(
level_2_region_code =
paste0("FR-", level_2_region_code)
) %>%
left_join(self$codes_lookup$`2`, by = "level_2_region_code")
}
)
) |
context("ml feature - ngram")
skip_databricks_connect()
test_that("ft_ngram() default params", {
test_requires_latest_spark()
sc <- testthat_spark_connection()
test_default_args(sc, ft_ngram)
})
test_that("ft_ngram() param setting", {
test_requires_latest_spark()
sc <- testthat_spark_connection()
test_args <- list(
input_col = "foo",
output_col = "bar",
n = 3
)
test_param_setting(sc, ft_ngram, test_args)
})
test_that("ft_ngram() works properly", {
sc <- testthat_spark_connection()
sentence_df <- data.frame(sentence = "The purrrers on the bus go map map map")
sentence_tbl <- copy_to(sc, sentence_df, overwrite = TRUE)
bigrams <- sentence_tbl %>%
ft_tokenizer("sentence", "words") %>%
ft_ngram("words", "bigrams", n = 2) %>%
pull(bigrams) %>%
unlist()
expect_identical(
bigrams,
c(
"the purrrers", "purrrers on", "on the", "the bus", "bus go",
"go map", "map map", "map map"
)
)
trigrams <- sentence_tbl %>%
ft_tokenizer("sentence", "words") %>%
ft_ngram("words", "trigrams", n = 3) %>%
pull(trigrams) %>%
unlist()
expect_identical(
trigrams,
c(
"the purrrers on", "purrrers on the", "on the bus", "the bus go",
"bus go map", "go map map", "map map map"
)
)
}) |
RACDPAL_fun <- function(RAC_1, RAC_2A, RAC_2B, RAC_2C){
if_else2((RAC_1 %in% 1:3) & (RAC_2A %in% 1:3) & (RAC_2B %in% 1:4) &
(RAC_2C %in% 1:3),
if_else2(RAC_1 == 2 | RAC_2A == 2 | RAC_2B == 2 | RAC_2C == 2, 2,
if_else2(RAC_1 == 1 | RAC_2A == 1 | RAC_2B == 1 |
RAC_2C == 1, 1,
if_else2(RAC_1 == 3 & RAC_2A == 3 &
(RAC_2B %in% 3:4) &
RAC_2C == 3, 3, "NA(b)"))), "NA(b)"
)
} |
setup <- function(){
print("Setting up for loa")
print("(this should run without errors, warnings)")
} |
Ralpha <- function(x, n, alpha) {
if (n==1) stop('We are not able to provide sensible results for n=1')
I2n <- function(x, n, lower=NULL, upper=NULL) {
if (is.null(lower))
lower <- 0
if (is.null(upper)) {
if (n < 1500)
upper <- 100+10000/n
else
upper <- 50+10000/n
}
temp <- function(x, n, lower, upper) {
f1 <- integrate(function(x, R, n) besselJ(x, 0)^n*besselJ(R*x, 0)*x, lower=lower, upper=upper-2*0.99*log(n), R=x, n=n, subdivisions=4000, stop.on.error=FALSE)$value
f2 <- integrate(function(x, R, n) besselJ(x, 0)^n*besselJ(R*x, 0)*x, lower=lower, upper=upper-0.99*log(n), R=x, n=n, subdivisions=4000, stop.on.error=FALSE)$value
f3 <- integrate(function(x, R, n) besselJ(x, 0)^n*besselJ(R*x, 0)*x, lower=lower, upper=upper, R=x, n=n, subdivisions=4000, stop.on.error=FALSE)$value
f4 <- integrate(function(x, R, n) besselJ(x, 0)^n*besselJ(R*x, 0)*x, lower=lower, upper=upper+0.99*log(n), R=x, n=n, subdivisions=4000, stop.on.error=FALSE)$value
f5 <- integrate(function(x, R, n) besselJ(x, 0)^n*besselJ(R*x, 0)*x, lower=lower, upper=upper+2*0.99*log(n), R=x, n=n, subdivisions=4000, stop.on.error=FALSE)$value
median(c(f1,f2,f3,f4,f5))
}
sapply(X=x, FUN=temp, n=n, lower=lower, upper=upper)
}
I3n <- function(x, n, lower=NULL, upper=NULL) {
if (is.null(lower))
lower <- 0
if (is.null(upper)) {
if (n < 1500)
upper <- 100+10000/n
else
upper <- 50+10000/n
}
temp <- function(x, n, lower, upper) {
f1 <- integrate(function(x, C, n) besselJ(x, 0)^n*cos(C*x), lower=lower, upper=upper-2*0.99*log(n+1), C=x, n=n, subdivisions=4000, stop.on.error=FALSE)$value
f2 <- integrate(function(x, C, n) besselJ(x, 0)^n*cos(C*x), lower=lower, upper=upper-0.99*log(n+1), C=x, n=n, subdivisions=4000, stop.on.error=FALSE)$value
f3 <- integrate(function(x, C, n) besselJ(x, 0)^n*cos(C*x), lower=lower, upper=upper, C=x, n=n, subdivisions=4000, stop.on.error=FALSE)$value
f4 <- integrate(function(x, C, n) besselJ(x, 0)^n*cos(C*x), lower=lower, upper=upper+0.99*log(n+1), C=x, n=n, subdivisions=4000, stop.on.error=FALSE)$value
f5 <- integrate(function(x, C, n) besselJ(x, 0)^n*cos(C*x), lower=lower, upper=upper+2*0.99*log(n+1), C=x, n=n, subdivisions=4000, stop.on.error=FALSE)$value
median(c(f1,f2,f3,f4,f5))
}
sapply(X=x, temp, n=n, lower=lower, upper=upper)
}
lhs <- function(x, C, n) {
temp <- function(x, C, n) integrate(function(x, C, n) x/sqrt(x^2-C^2)*I2n(x, n), lower=x, upper=n, C=C, n=n, subdivisions=4000, stop.on.error=FALSE)$value
sapply(X=x, FUN=temp, C=C, n=n)
}
equat <- function(x, C, n, alphaI3n) {
lhs(x=x, C=C, n=n) - alphaI3n
}
temp <- function(x, n, alpha) {
alphaI3n <- alpha*I3n(x=x, n=n)
uniroot(equat, lower=x, upper=n, C=x, n=n, alphaI3n=alphaI3n)$root
}
sapply(X=x, FUN=temp, n=n, alpha=alpha)
}
Ralphaapprox <- function(x, n, alpha) {
if (n<3) stop('We are not able to provide sensible results for n<3')
temp <- function(x, n, alpha) {
if (n >=15 & x > 0 & x < n/3) {
y <- sqrt(x^2+qchisq(alpha, df=1, lower.tail=FALSE)*0.5*n)
} else if (x > n/2 & x < 3*n/4) {
ff <- qf(alpha, df1=2, df2=2*n-2, lower.tail=FALSE)
y <- (ff*n+(n-1)*x)/(n+ff-1)
} else if (x > 5/6*n) {
ff <- qf(alpha, df1=1, df2=n-1, lower.tail=FALSE)
y <- (ff*n+(n-1)*x)/(n+ff-1)
} else {
y <- NA
}
return(y)
}
sapply(X=x, FUN=temp, n=n, alpha=alpha)
} |
optimsimplex.gradcenter <- function(this=NULL,fun=NULL,data=NULL){
g1 <- optimsimplex.gradforward(this)
tmp <- optimsimplex.reflect(this=this,fun=fun,data=data)
r <- tmp$r
if (!is.null(data)) data <- tmp$data
g2 <- optimsimplex.gradforward(r)
g <- (g1 + g2)/2
varargout <- list(g=g,data=data)
return(varargout)
} |
`mantel_pertables` <-
function (pertab, env, dist.method = "bray", binary = FALSE,
cor.method = "pearson", permutations = 100)
{
mantel.test <- function(z, env) {
mantel.st <- mantel(vegdist(z, method = dist.method,
binary = binary), dist(env), method = cor.method,
permutations = permutations)
mantel.r <- -mantel.st$statistic
mantel.p <- mantel.st$signif
return(c(mantel.r, mantel.p))
}
results <- sapply(pertab$pertables, function(x) mantel.test(x,
env))
row.names(results) <- c("r", "p-value")
mantel.quant <- apply(results, 1, quantile, c(0, 0.005, 0.025,
0.5, 0.975, 0.995, 1))
vdper <- lapply(pertab$pertables, function(x) 1 - vegdist(x,
method = dist.method, binary = binary))
z <- pertab$raw
mantel.raw <- mantel(vegdist(z, method = dist.method, binary = binary),
dist(env), method = cor.method, permutations = permutations)
mantel.r <- -mantel.raw$statistic
ptax <- ((rank(c(mantel.r, results[1, ])))/(length(results[1,
]) + 1))[1]
ptax <- ifelse(ptax <= 0.5, ptax, 1 - ptax)
vd <- 1 - vegdist(pertab$raw, method = dist.method, binary = binary)
env.dist <- as.vector(dist(env))
mantel.output <- list(mantel = list(mantel.raw = mantel.raw,
ptax = ptax), simulation = list(results = results, mantel.quant = mantel.quant,
vegdist = vdper), raw = list(vegdist = vd, env.dist = env.dist))
class(mantel.output) <- c("mantel_pertables", class(mantel.output))
return(mantel.output)
} |
print.DTR <- function(x, ...) {
if (!is.null(x$Call)) {
cat("Call: ")
dput(x$Call)
cat("\n")
}
temp <- data.frame(
DTR=x$DTR,
records=x$records,
events=x$events,
median=c(min(x$time[which(abs(x$SURV11-0.5)==min(abs(x$SURV11-0.5)[which(x$SURV11<=0.5)]))]),
min(x$time[which(abs(x$SURV12-0.5)==min(abs(x$SURV12-0.5)[which(x$SURV12<=0.5)]))]),
min(x$time[which(abs(x$SURV21-0.5)==min(abs(x$SURV21-0.5)[which(x$SURV21<=0.5)]))]),
min(x$time[which(abs(x$SURV22-0.5)==min(abs(x$SURV22-0.5)[which(x$SURV22<=0.5)]))])),
LCL95=c(min(x$time[which(abs(x$SURV11-1.96*x$SE11-0.5)==min(abs(x$SURV11-1.96*x$SE11-0.5)[which((x$SURV11-1.96*x$SE11)<=0.5)]))]),
min(x$time[which(abs(x$SURV12-1.96*x$SE12-0.5)==min(abs(x$SURV12-1.96*x$SE12-0.5)[which((x$SURV12-1.96*x$SE12)<=0.5)]))]),
min(x$time[which(abs(x$SURV21-1.96*x$SE21-0.5)==min(abs(x$SURV21-1.96*x$SE21-0.5)[which((x$SURV21-1.96*x$SE21)<=0.5)]))]),
min(x$time[which(abs(x$SURV22-1.96*x$SE22-0.5)==min(abs(x$SURV22-1.96*x$SE22-0.5)[which((x$SURV22-1.96*x$SE22)<=0.5)]))])),
UCL95=c(min(x$time[which(abs(x$SURV11+1.96*x$SE11-0.5)==min(abs(x$SURV11+1.96*x$SE11-0.5)[which((x$SURV11+1.96*x$SE11)<=0.5)]))]),
min(x$time[which(abs(x$SURV12+1.96*x$SE12-0.5)==min(abs(x$SURV12+1.96*x$SE12-0.5)[which((x$SURV12+1.96*x$SE12)<=0.5)]))]),
min(x$time[which(abs(x$SURV21+1.96*x$SE21-0.5)==min(abs(x$SURV21+1.96*x$SE21-0.5)[which((x$SURV21+1.96*x$SE21)<=0.5)]))]),
min(x$time[which(abs(x$SURV22+1.96*x$SE22-0.5)==min(abs(x$SURV22+1.96*x$SE22-0.5)[which((x$SURV22+1.96*x$SE22)<=0.5)]))]))
)
print(temp, row.names = FALSE)
} |
tidy_name2 <- function(x) {
new_spec_names <- unlist(lapply(x, function(y) {
split_str <- unlist(stringr::str_split(y, " "))
return(paste0(
stringr::str_to_upper(stringr::str_sub(split_str[1], 1, 1)),
stringr::str_sub(split_str[1], 2, nchar(split_str[1])),
stringr::str_to_upper(stringr::str_sub(split_str[2],1,1)),
stringr::str_sub(split_str[2], 2, nchar(split_str[2])),
collapse = ""
))
}))
return(new_spec_names)
} |
boot.penv <- function(X1, X2, Y, u, B) {
X1 <- as.matrix(X1)
X2 <- as.matrix(X2)
a <- dim(Y)
n <- a[1]
r <- a[2]
p1 <- ncol(X1)
p2 <- ncol(X2)
fit <- penv(X1, X2, Y, u, asy = F)
Yfit <- matrix(1, n, 1) %*% t(fit$mu) + X1 %*% t(fit$beta1) + X2 %*% t(fit$beta2)
res <- Y - Yfit
bootenv <- function(i) {
res.boot <- res[sample(1:n, n, replace = T), ]
Y.boot <- Yfit + res.boot
return(c(penv(X1, X2, Y.boot, u, asy = F)$beta1))
}
bootbeta <- lapply(1:B, function(i) bootenv(i))
bootbeta <- matrix(unlist(bootbeta), nrow = B, byrow = TRUE)
bootse <- matrix(apply(bootbeta, 2, stats::sd), nrow = r)
return(bootse)
} |
plotseis24<-function(JJ, dy=1/18, FIX=24, SCALE=0, FILT=list(ON=FALSE, fl=0.05 , fh=20.0, type="BP", proto="BU"), RCOLS=c(rgb(0.2, .2, 1), rgb(.2, .2, .2)) , add=FALSE )
{
if(missing(FIX)) { FIX=24 }
if(missing(dy)) { dy = 1/18 }
if(missing(RCOLS)) { RCOLS = c(rgb(0.2, .2, 1), rgb(.2, .2, .2),"tomato3","royalblue","forestgreen","blueviolet","tan3","lightseagreen","deeppink","cyan3","bisque3","magenta1","lightsalmon3","darkcyan") }
if(missing(SCALE )) { SCALE = 0 }
if(missing(FILT)) { FILT = list(ON=FALSE, fl=0.05 , fh=20.0, type="BP", proto="BU") }
h = FIX
m1 = 0
ry = range(c(m1, m1+23.999/24) )
adt=min(JJ$gdt)
xa = seq(from=0, length=3600/adt, by=adt)
mx1 = min(xa)
mx2 = max(xa)
bcol = rgb(1, .8, .8)
gcol = rgb(.8, 1, .8)
rcol = RCOLS
par(mar=c(5, 4, 4, 4)+0.1, xaxs='i', yaxs='i', lwd=0.5, bty="u")
if(!add)
{
plot( c(0, 3600), -ry , type='n', xpd=TRUE, axes=FALSE, xlab="Time,s", ylab="")
box(col=grey(0.7) )
}
tix = rep(NA, length=h)
altcol = length(RCOLS)
cols = rep(1:altcol, length=24)
miny = rep(NA, length(24))
maxy = rep(NA, length(24))
for(i in 1:24 )
{
zed = JJ$sigs[[i]]
fy = zed
if(FILT$ON==TRUE)
{
L = length(zed)
ipad = ceiling(L*0.02)
if(ipad>10)
{
ibeg = zed[1:ipad]
iend = zed[(L-ipad+1):L]
ked = c(rev(ibeg), zed, rev(iend))
if(!any(is.na(ked)))
{
fy = butfilt(ked,fl=FILT$fl, fh=FILT$fh , deltat = adt, type=FILT$type , proto=FILT$proto , RM=FILT$RM, zp=FILT$zp )
}
else
{
fy = ked
}
jed = fy[(ipad+1):(ipad+L) ]
fy = jed
}
}
fy = fy-mean(fy, na.rm=TRUE)
miny[i] = min(fy, na.rm=TRUE)
maxy[i] = max(fy, na.rm=TRUE)
JJ$sigs[[i]] = fy
}
bigmax = max(maxy, na.rm=TRUE)
bigmin = min(miny, na.rm=TRUE)
if(SCALE>0) rat = abs(bigmax-bigmin)/SCALE
for(i in 1:24 )
{
a1 = m1 + (i-1)/24
a2 = m1 + (i)/24
y1 = -a1
fy = JJ$sigs[[i]]
zna = JJ$zna[[i]]
icol = RCOLS[cols[i]]
if(length(fy)>2)
{
if(SCALE==0)
{
zee = RPMG::RESCALE(fy, -1, 1, miny[i], maxy[i])
}
else
{
zee = RPMG::RESCALE(fy, -1 , 1, bigmin, bigmax)
}
tmean = mean(zee, na.rm=TRUE)
zee = dy*(zee-tmean)
zee[ zna ] = NA
tix[i] = y1
lines(c(mx1, 50) , c(y1, y1) , col=bcol )
lines(xa,y1+zee, col=icol, xpd=TRUE)
}
else
{
y1 = -a1
lines(c(mx1, 50) , c(y1, y1) , col=bcol )
}
}
axis(1)
days = JJ$jd
modays = getmoday(days, JJ$yr[1])
tlocs = abs(tix[!is.na(tix)])
labs4 = format.default(1+round(24*(tlocs - floor(tlocs))), digits=2)
labs2 = format.default(round(24*(tlocs - floor(tlocs))), digits=2)
axis(4, at=tix[!is.na(tix)], labels=labs4, las=1)
axis(2, at=tix[!is.na(tix)], labels=labs2, las=1)
modays = getmoday(JJ$jd[1], JJ$yr[1])
idate = ISOdate(JJ$yr[1], modays$mo, modays$dom, hour = 0, min = 0, sec = 0, tz = "GMT")
adate = format(idate, format = "%Y-%b-%d GMT", tz = "GMT" )
mtext(adate, 3, line=1, at=0, adj=0)
if(FILT$ON==TRUE)
{
fl = FILT$fl
unitlow = "Hz"
fh = FILT$fh
unithi = "Hz"
ftype= FILT$type
if(fl<1)
{
fl = 1/fl
unitlow = "s"
}
if(fh<1)
{
fh = 1/fh
unithi = "s"
}
filttag = paste(sep= " ", ftype,fl, unitlow, fh, unithi )
mtext(filttag, 3, line=1, at=mx2, adj=1)
}
if(SCALE>0)
{
mtext("Scaled by window", 1, line=3, at=0, adj=0)
}
invisible(list( x=xa, y=tix, yr=JJ$yr[1], jd=JJ$jd[1] ))
} |
bbc_style <- function() {
font <- "Helvetica"
ggplot2::theme(
plot.title = ggplot2::element_text(family=font,
size=28,
face="bold",
color="
plot.subtitle = ggplot2::element_text(family=font,
size=22,
margin=ggplot2::margin(9,0,9,0)),
plot.caption = ggplot2::element_blank(),
legend.position = "top",
legend.text.align = 0,
legend.background = ggplot2::element_blank(),
legend.title = ggplot2::element_blank(),
legend.key = ggplot2::element_blank(),
legend.text = ggplot2::element_text(family=font,
size=18,
color="
axis.title = ggplot2::element_blank(),
axis.text = ggplot2::element_text(family=font,
size=18,
color="
axis.text.x = ggplot2::element_text(margin=ggplot2::margin(5, b = 10)),
axis.ticks = ggplot2::element_blank(),
axis.line = ggplot2::element_blank(),
panel.grid.minor = ggplot2::element_blank(),
panel.grid.major.y = ggplot2::element_line(color="
panel.grid.major.x = ggplot2::element_blank(),
panel.background = ggplot2::element_blank(),
strip.background = ggplot2::element_rect(fill="white"),
strip.text = ggplot2::element_text(size = 22, hjust = 0)
)
} |
initialize_simulation_object <- function(options, net_list, edge_loc, mutual_loc) {
sim_obj <- list(burnin = options$sim_param$burnin,
interval = options$sim_param$interval,
net_list = net_list,
edge_loc = edge_loc,
mutual_loc = mutual_loc,
par_n_cores = options$est_param$par_n_cores)
return(sim_obj)
} |
snr_signal2baseline <- function(int, baseline) {
SNR <- -Inf
x_apex <- which.max(int)[1]
Max_sig <- int[x_apex]
if (Max_sig > 0) {
Median_baseline <- baseline[x_apex]
if (Median_baseline == 0) {
Median_baseline <- 1
Max_sig <- Max_sig/length(int)
}
SNR <- Max_sig/Median_baseline
}
return(SNR)
} |
cm_df.fill <-
function(dataframe, ranges, value = 1, text.var = NULL, code.vars = NULL,
transform = FALSE) {
if (transform) {
dataframe <- cm_df.transform(dataframe = dataframe,
text.var = text.var, code.vars = code.vars)
}
if (!is.null(text.var) && !is.numeric(text.var)) {
text.var <- which(colnames(DF) == text.var)
}
if (!is.null(code.vars) && !is.numeric(code.vars)) {
code.vars <- which(colnames(DF) %in% c(code.vars))
}
if (is.null(text.var)) {
text.var <- which(colnames(dataframe) == "text")
}
if (is.null(code.vars)) {
code.vars <- (text.var + 2):ncol(dataframe)
}
left.overs <- which(!1:ncol(dataframe) %in% c(code.vars, text.var))
dataframe[, text.var] <- as.character(dataframe[, text.var])
if (length(value) == 1) {
value <- rep(value, length(code.vars))
}
CV <- dataframe[, code.vars]
inds <- which(colnames(CV) %in% names(ranges))
lapply(inds, function(i) {
CV[ ranges[[colnames(CV)[i]]], colnames(CV)[i]] <<- value[i]
return(CV)
}
)
DF <- data.frame(dataframe[, 1:(text.var + 1)], CV, stringsAsFactors = FALSE)
return(DF)
} |
filtSizeUniq <- function(lst,ref=NULL,minSize=6,maxSize=36,filtUnique=TRUE,byProt=TRUE,inclEmpty=TRUE,silent=FALSE,callFrom=NULL) {
fxNa <- .composeCallName(callFrom,newNa="filtSizeUniq")
chNa <- grep("\\.$", names(utils::head(lst)))
if(!is.list(lst)) {byProt <- FALSE; inclEmpty <- FALSE}
if(length(chNa) <= min(2,length(lst))) names(lst) <- paste(names(lst),".",sep="")
pep <- unlist(lst)
chNa <- max(sapply(lst,length),na.rm=TRUE)
if(chNa >1) names(pep) <- sub("\\.$","",names(pep))
nPep <- length(pep)
nAA <- nchar(pep)
if(length(minSize) <1) minSize <- 0
if(length(maxSize) <1) {maxSize <- 40
if(!silent) message(fxNa," can't understant 'maxSize', setting to default=40")}
chAA <- nAA >= minSize & nAA <= maxSize
if(any(!chAA)) {pep <- if(all(!chAA)) NULL else pep[which(chAA)]
if(!silent) message(fxNa,nPep - length(pep)," out of ",nPep," peptides beyond range (",minSize,"-",maxSize,")")}
if(filtUnique) {
nPe2 <- length(pep)
if(length(ref) >0) {pep0 <- pep; pep <- c(pep,unique(unlist(ref))) } else pep0 <- NULL
chDup <- duplicated(pep,fromLast=FALSE)
if(any(chDup)) {
chDu2 <- duplicated(pep,fromLast=TRUE)
if(length(ref) >0) {pep <- pep0; chDup <- chDup[1:nPe2]; chDu2 <- chDu2[1:nPe2]}
pep <- list(unique=pep[which(!chDu2 & !chDup)],allRedund=pep[which(!(!chDu2 & !chDup))], firstOfRed=pep[which(chDu2 & !chDup)])
if(!silent) message(fxNa,length(pep$allRedund)," out of ",nPe2," peptides redundant")
} else {if(length(ref) >0) {pep <- pep0; chDup <- chDup[1:nPe2]}}
}
if(byProt) { fac <- sub("\\.[[:digit:]]+$","",names(if(filtUnique) pep$unique else pep))
pep <- tapply(if(filtUnique) pep$unique else pep,fac,function(x) x)
if(length(pep) <1) pep <- character()
if(inclEmpty) { iniPro <- sub("\\.$","",names(lst))
curPro <- names(pep)
newNo <- sum(!iniPro %in% curPro)
if(newNo >0){ pep[length(curPro)+(1:newNo)] <- lapply(1:newNo,function(x) character())
names(pep)[length(curPro)+(1:newNo)] <- iniPro[which(!iniPro %in% curPro)]}
}
}
pep }
.filtSize <- function(x,minSize=5,maxSize=36) {nCha <- nchar(x); x[which(nCha >= minSize & nCha <= maxSize)]}
|
test_that("getTaskFormula", {
expect_equal(binaryclass.formula, getTaskFormula(binaryclass.task),
ignore_formula_env = TRUE)
my.binaryclass.formula = paste(
binaryclass.target, "~",
collapse(colnames(binaryclass.df[, -binaryclass.class.col]), sep = " + "))
expect_equal(
as.formula(my.binaryclass.formula),
getTaskFormula(binaryclass.task, explicit.features = TRUE),
ignore_formula_env = TRUE)
expect_equal(multiclass.formula, getTaskFormula(multiclass.task),
ignore_formula_env = TRUE)
my.multiclass.formula = paste(
multiclass.target, "~",
collapse(colnames(multiclass.df[, -multiclass.class.col]), sep = " + "))
expect_equal(
as.formula(my.multiclass.formula),
getTaskFormula(multiclass.task, explicit.features = TRUE))
expect_equal(regr.formula, getTaskFormula(regr.task),
ignore_formula_env = TRUE)
my.regr.formula = paste(
regr.target, "~",
collapse(colnames(regr.df[, -regr.class.col]), sep = " + "))
expect_equal(
as.formula(my.regr.formula),
getTaskFormula(regr.task, explicit.features = TRUE))
expect_equal(regr.num.formula, getTaskFormula(regr.num.task),
ignore_formula_env = TRUE)
my.regr.num.formula = paste(
regr.num.target, "~",
collapse(colnames(regr.num.df[, -regr.num.class.col]), sep = " + "))
expect_equal(
as.formula(my.regr.num.formula),
getTaskFormula(regr.num.task, explicit.features = TRUE))
})
test_that("issue
expect_error(getTaskFormula(unclass(iris.task)), "no applicable method")
}) |
x_train <- input_variables_values_training_datasets
y_train <- target_variables_values_training_datasets
x_test <- input_variables_values_test_datasets
x <- cbind(x_train,y_train)
linear <- lm(y_train ~ ., data = x)
summary(linear)
predicted= predict(linear,x_test) |
suvC <-
function(u,v,irow,pcol){
dd=dim(u)
nnrow=as.integer(dd[1])
nncol=as.integer(nrow(v))
nrank=dd[2]
storage.mode(u)="double"
storage.mode(v)="double"
storage.mode(irow)="integer"
storage.mode(pcol)="integer"
nomega=as.integer(length(irow))
.Fortran("suvC",
nnrow,nncol,nrank,u,v,irow,pcol,nomega,
r=double(nomega),
PACKAGE="softImpute"
)$r
} |
getSimOutput <- function(simAnnealList, num){
costs_all <- unlist(do.call(rbind, lapply(simAnnealList, function(x)x$Cb)))
best_cost_index <- which.min(costs_all)
allRankOrder <- lapply(simAnnealList, function(x) x$Ordb)
names(allRankOrder) <- paste0("SimAnneal", 1:num)
allRankOrder_df <- data.frame(allRankOrder)
bestRankOrderIndex <- allRankOrder[[best_cost_index]]
return(list(
costs_all = costs_all,
bestRankOrder = bestRankOrderIndex,
allRankOrder = allRankOrder_df
))
}
getAllCosts <- function(costs_all, num){
CostOutput <- data.frame(simAnnealRun = c(1:num), Cost = costs_all)
return(CostOutput)
}
getBestRankOrder <- function(ID_index, bestRankOrder) {
bestRankOrder <- data.frame(ID = ID_index[bestRankOrder, "ID"],
ranking = 1:nrow(ID_index))
return(bestRankOrder)
}
getAllRankOrder <- function(ID_index, allRankOrder){
allRankOrder_df <- data.frame(apply(allRankOrder,
2,
function(x) ID_index[x, "ID"]),
stringsAsFactors = FALSE)
return(allRankOrder_df)
} |
context("kgram_freqs_fast")
test_that("return value has the correct structure", {
f <- kgram_freqs_fast(corpus = "some text",
N = 3,
dict = c("some", "text"),
erase = "",
lower_case = FALSE,
EOS = "")
expect_true(is.list(f))
expect_true(length(f) == 3)
expect_true(all(
c("N", "dict", ".preprocess", "EOS") %in% names(attributes(f))
))
expect_true(is.integer(attr(f, "N")))
expect_true(is.character(attr(f, "dict")))
expect_true(is.character(attr(f, "EOS")))
expect_true( is.function(attr(f, ".preprocess")) )
expect_identical(f[[1]], as_tibble(f[[1]]))
})
test_that("input `N <= 0` produces error", {
expect_error(kgram_freqs_fast(corpus = "some text",
N = 0,
dict = c("some", "text"),
erase = "",
lower_case = FALSE,
EOS = "")
)
expect_error(kgram_freqs_fast(corpus = "some text",
N = -1,
dict = c("some", "text"),
erase = "",
lower_case = FALSE,
EOS = "")
)
})
expected_1grams <- tibble(w2 = c(1L, 2L, 3L, 4L),
n = c(8L, 6L, 4L, 2L)
) %>% arrange(w2)
expected_2grams <- tibble(
w1 = c(0L, 0L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 4L, 4L),
w2 = c(1L, 2L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L),
n = c(3L, 1L, 2L, 3L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L)
) %>% arrange(w1, w2)
test_that("correct 1-gram and 2-gram counts on simple input", {
input <- c("a a b a", "a b b a", "a c b", "b c a a b")
dict <- c("a", "b")
freqs <- kgram_freqs_fast(corpus = input, N = 2, dict = dict,
erase = "", lower_case = FALSE, EOS = "")
actual_1grams <- arrange(freqs[[1]], w2)
actual_2grams <- arrange(freqs[[2]], w1, w2)
expect_identical(expected_1grams, actual_1grams)
expect_identical(expected_2grams, actual_2grams)
})
test_that("correct 1-gram and 2-gram with some preprocessing", {
input <- c("a A b A", "a B b a", "a C B", "b c A a b")
dict <- c("a", "b")
freqs <- kgram_freqs_fast(corpus = input, N = 2, dict = dict,
erase = "", lower_case = TRUE, EOS = "")
actual_1grams <- arrange(freqs[[1]], w2)
actual_2grams <- arrange(freqs[[2]], w1, w2)
expect_identical(expected_1grams, actual_1grams)
expect_identical(expected_2grams, actual_2grams)
})
test_that("correct 1-gram and 2-gram counts with EOS token", {
input <- c("/ a a b a / a b b a / a c b / b c a a b /")
dict <- c("a", "b")
freqs <- kgram_freqs_fast(corpus = input, N = 2, dict = dict,
erase = "", lower_case = FALSE, EOS = "/")
actual_1grams <- arrange(freqs[[1]], w2)
actual_2grams <- arrange(freqs[[2]], w1, w2)
expect_identical(expected_1grams, actual_1grams)
expect_identical(expected_2grams, actual_2grams)
})
test_that("build dictionary on the fly", {
input <- c("a a b a", "a b b a", "a c b", "b c a a b")
freqs <- kgram_freqs_fast(corpus = input, N = 2, dict = max_size ~ 2,
erase = "", lower_case = FALSE, EOS = "")
actual_1grams <- arrange(freqs[[1]], w2)
actual_2grams <- arrange(freqs[[2]], w1, w2)
expect_identical(expected_1grams, actual_1grams)
expect_identical(expected_2grams, actual_2grams)
})
test_that("Argument dict = Inf works", {
input <- c("a a b a", "a b b a", "a c b", "b c a a b")
freqsInf <- kgram_freqs_fast(corpus = input, N = 2, dict = max_size ~ Inf,
erase = "", lower_case = FALSE, EOS = "")
freqs3 <- kgram_freqs_fast(corpus = input, N = 2, dict = max_size ~ 3,
erase = "", lower_case = FALSE, EOS = "")
attr(freqs3, ".preprocess") <- attr(freqsInf, ".preprocess")
expect_equal(freqs3, freqsInf)
})
rm(expected_1grams, expected_2grams)
test_that("Error on 'dict' argument not character or numeric", {
input <- c("a a b a", "a b b a", "a c b", "b c a a b")
expect_error(kgram_freqs_fast(corpus = input, N = 2, dict = TRUE))
})
test_that("Error on 'dict' argument negative numeric", {
input <- c("a a b a", "a b b a", "a c b", "b c a a b")
expect_error(kgram_freqs_fast(corpus = input, N = 2, dict = max_size ~ -1))
}) |
is.Date <- function(x) {
inherits(x, "Date")
}
KM <- function(x) {
if (!survival::is.Surv(x))
stop("x must be a Surv object")
x <- x[!is.na(x)]
obs <- x[, 1]
ev <- x[, 2]
ce <- 1 - ev
if (length(obs) == 0)
stop("No data to estimate survival curve")
N <- length(obs)
if (!any(obs == 0)) {
obs <- c(0, obs)
ev <- c(0, ev)
ce <- c(0, ce)
}
i <- order(obs, 1 - ev)
obs <- obs[i]
ev <- ev[i]
ce <- ce[i]
ev <- rev(cumsum(rev(ev)))
ce <- rev(cumsum(rev(ce)))
n <- ce + ev
i <- !duplicated(obs)
obs <- obs[i]
n <- n[i]
ev <- ev[i]
ev <- ev - c(ev[-1], 0)
ce <- ce[i]
ce <- ce - c(ce[-1], 0)
v <- N * cumsum(ev/(n - ev)/n)
S <- exp(cumsum(log(1 - ev/n)))
if (is.na(S[length(S)]))
S[length(S)] <- 0
rslt <- data.frame(t = obs, atrisk = n, events = ev,
censored = ce, S = S, v = v)
class(rslt) <- c("KM", "data.frame")
rslt
}
sum_KM <- function(x, times, rightCtsCDF = TRUE) {
if (!inherits(x, "KM"))
stop("x must be a KM object")
if (rightCtsCDF) {
rslt <- as.vector(apply(matrix(rep(times, each = length(x$t)),
length(x$t)) >= x$t, 2, sum)) + 1
}
else rslt <- as.vector(apply(matrix(rep(times, each = length(x$t)),
length(x$t)) > x$t, 2, sum)) + 1
if (x$S[length(x$S)] > 0)
rslt[times > x$t[length(x$t)]] <- NA
c(1, x$S)[rslt]
}
quantile_KM <- function(x, probs) {
rslt <- length(probs)
for (i in 1:length(probs)) {
p <- 1 - probs[i]
j <- abs(x$S - p) < 1e-15 & x$events > 0
if (any(j)) {
if (abs(p - min(x$S)) < 1e-15) {
rslt[i] <- (x$t[j] + max(x$t))/2
}
else {
rslt[i] <- (x$t[j] + min(x$t[x$t > x$t[j] & x$events > 0]))/2
}
}
else {
j <- sum(x$S > p)
if (j == length(x$S) | p == 1) {
rslt[i] <- NA
}
else rslt[i] <- x$t[j + 1]
}
}
rslt
}
mean_KM <- function(x, restriction = Inf) {
if (length(restriction) == 1)
restriction <- c(x$t[1] - 1, restriction)
if (restriction[2] == Inf)
restriction[2] <- x$t[length(x$t)]
tms <- c(restriction[1], x$t[x$t > restriction[1] & x$t < restriction[2]],
restriction[2])
s <- sum_KM(x, restriction)
s <- c(s[1], x$S[x$t > restriction[1] & x$t < restriction[2]], s[2])
ne <- tms <= 0
po <- tms >= 0
neS <- 1 - s[ne]
neX <- abs(c(diff(tms[ne]), 0))
neI <- neS != 0 & neX != 0
if (sum(neI) > 0)
rslt <- -sum(neS[neI] * neX[neI])
else rslt <- 0
poS <- s[po]
poX <- c(diff(tms[po]), 0)
poI <- poS != 0 & poX != 0
if (sum(poI) > 0)
rslt <- rslt + sum(poS[poI] * poX[poI])
attr(rslt, "restriction") <- restriction
rslt
}
describe_vector <- function(x, probs = c(0.25, 0.5, 0.75), thresholds = NULL,
geometricMean = FALSE, geomInclude = FALSE,
replaceZeroes = FALSE) {
if (is.character(x)) {
x <- as.factor(x)
}
if (is.factor(x) | is.logical(x)) {
x <- as.numeric(x)
}
if (!geomInclude) {
geometricMean <- geomInclude
}
ntholds <- ifelse(is.null(thresholds), 0, dim(thresholds)[1])
probs <- sort(unique(c(probs, 0, 1)))
rslt <- length(x)
if (rslt == 0) {
rslt <- c(rslt, rep(NaN, 7 + length(probs) + ntholds))
}
else {
u <- is.na(x)
rslt <- c(rslt, sum(u))
x <- x[!u]
if (length(x) == 0 | is.character(x)) {
if (!geomInclude) {
rslt <- c(rslt, rep(NA, 6 + length(probs) + ntholds))
} else {
rslt <- c(rslt, rep(NA, 7 + length(probs) + ntholds))
}
} else {
if (geomInclude) {
rslt <- c(rslt, mean(x), stats::sd(x), ifelse1(
geometricMean,
exp(mean(log(ifelse(x == 0, replaceZeroes, x)))),
NA
), stats::quantile(x, probs))
} else {
rslt <- c(rslt, mean(x), stats::sd(x), stats::quantile(x, probs))
}
if (ntholds > 0) {
for (j in 1:ntholds) {
u <- ifelse1(
thresholds[j, 1] == 0, x > thresholds[j, 2], x >= thresholds[j, 2]
) & ifelse1(
thresholds[j, 3] == 0, x < thresholds[j, 4], x <= thresholds[j, 4]
)
rslt <- c(rslt, mean(u))
}
}
rslt <- c(rslt, Inf, NA, NA)
}
}
if (length(x) > 0) {
rslt <- matrix(c(rslt, 0), 1)
}
else {
rslt <- matrix(rslt, 1)
}
qnames <- paste(format(100 * probs), "%", sep = "")
qnames[probs == 0.5] <- " Mdn"
qnames[probs == 0] <- " Min"
qnames[probs == 1] <- " Max"
tnames <- NULL
if (ntholds > 0) {
tholds <- thresholds
tholds[tholds == Inf | tholds == -Inf] <- 0
tnames <- paste(
sep = "", "Pr", ifelse(
thresholds[, 2] == -Inf,
paste(sep = "", ifelse(thresholds[, 3] == 0, "<", "<="), format(tholds[, 4])),
ifelse(
thresholds[, 4] == Inf,
paste(sep = "", ifelse(thresholds[, 1] == 0, ">", ">="), format(tholds[, 2])),
paste(
sep = "", ifelse(thresholds[, 1] == 0, "(", "["),
format(tholds[, 2]), ",", format(tholds[, 4]),
ifelse(thresholds[, 3] == 0, ")", "]")
)
)
)
)
}
if (geomInclude) {
dimnames(rslt) <- list("", c("N", "Msng", "Mean",
"Std Dev", "Geom Mn", qnames, tnames, "restriction",
"firstEvent", "lastEvent", "isDate"))
}
else {
dimnames(rslt) <- list("", c("N", "Msng", "Mean",
"Std Dev", qnames, tnames, "restriction", "firstEvent",
"lastEvent", "isDate"))
}
rslt
}
describe_surv <- function(x, probs = c(0.25, 0.5, 0.75), thresholds = NULL,
geometricMean = FALSE, geomInclude = FALSE,
replaceZeroes = FALSE, restriction = Inf) {
if (!survival::is.Surv(x))
stop("x must be a Surv object")
ntholds <- if (is.null(thresholds))
0
else dim(thresholds)[1]
probs <- sort(unique(c(probs, 0, 1)))
rslt <- dim(x)[1]
if (rslt == 0) {
rslt <- c(rslt, rep(NaN, 7 + length(probs) + ntholds))
}
else {
u <- is.na(x)
rslt <- c(rslt, sum(u))
x <- x[!u]
if (dim(x)[1] == 0) {
rslt <- c(rslt, rep(NA, 6 + length(probs) + ntholds))
}
else {
z <- KM(x)
tmp1 <- mean_KM(z, restriction)
x2 <- x
x2[, 1] <- x2[, 1]^2
z2 <- KM(x2)
tmp2 <- sqrt(mean_KM(z2, restriction^2) - tmp1^2)
if (geometricMean) {
x2 <- x
x2[, 1] <- ifelse(x2[, 1] == 0, log(replaceZeroes),
log(x2[, 1]))
z2 <- KM(x2)
tmp3 <- exp(mean_KM(z2, log(restriction)))
}
else tmp3 <- NA
if (any(x[, 2] == 1)) {
firstEvent <- min(x[x[, 2] == 1, 1])
lastEvent <- max(x[x[, 2] == 1, 1])
}
else {
firstEvent <- Inf
lastEvent <- -Inf
}
if (geomInclude) {
rslt <- c(rslt, tmp1, tmp2, tmp3, min(x[, 1]),
quantile_KM(z, probs[-c(1, length(probs))]), max(x[,
1]))
}
else {
rslt <- c(rslt, tmp1, tmp2, min(x[, 1]), quantile_KM(z,
probs[-c(1, length(probs))]), max(x[, 1]))
}
if (ntholds > 0) {
for (j in 1:ntholds) {
rslt <- c(rslt, ifelse1(thresholds[j, 1] ==
0, sum_KM(z, thresholds[j, 2]), sum_KM(z, thresholds[j,
2], FALSE)) - ifelse1(thresholds[j, 4] == Inf,
0, ifelse1(thresholds[j, 3] == 0, sum_KM(z,
thresholds[j, 4], FALSE), sum_KM(z, thresholds[j,
4]))))
}
}
rslt <- c(rslt, attr(tmp1, "restriction")[2],
firstEvent, lastEvent)
}
}
rslt <- matrix(c(rslt, 0), 1)
qnames <- paste(format(100 * probs), "%", sep = "")
qnames[probs == 0.5] <- " Mdn"
qnames[probs == 0] <- " Min"
qnames[probs == 1] <- " Max"
tnames <- NULL
if (ntholds > 0) {
tholds <- thresholds
tholds[tholds == Inf | tholds == -Inf] <- 0
tnames <- paste(sep = "", "Pr", ifelse(thresholds[,
2] == -Inf, paste(sep = "", ifelse(thresholds[,
3] == 0, "<", "<="), format(tholds[, 4])), ifelse(thresholds[,
4] == Inf, paste(sep = "", ifelse(thresholds[,
1] == 0, ">", ">="), format(tholds[, 2])), paste(sep = "",
ifelse(thresholds[, 1] == 0, "(", "["), format(tholds[,
2]), ",", format(tholds[, 4]), ifelse(thresholds[,
3] == 0, ")", "]")))))
}
if (geomInclude) {
dimnames(rslt) <- list("", c("N", "Msng", "Mean",
"Std Dev", "Geom Mn", qnames, tnames, "restriction",
"firstEvent", "lastEvent", "isDate"))
}
else {
dimnames(rslt) <- list("", c("N", "Msng", "Mean",
"Std Dev", qnames, tnames, "restriction", "firstEvent",
"lastEvent", "isDate"))
}
rslt
}
describe_stratified_vector <- function(x, strata, subset,
probs = c(0.25, 0.5, 0.75),
thresholds = NULL, geomInclude = FALSE,
replaceZeroes = FALSE) {
if (is.null(subset))
subset <- rep(TRUE, length(x))
if (length(x) != length(subset))
stop("length of variables must match length of subset")
if (is.null(strata))
strata <- rep(1, length(x))
if (length(x) != length(strata))
stop("length of variables must match length of strata")
x <- x[subset]
if (is.factor(x) | all(x[!is.na(x)] %in% c(0, 1))) {
geometricMean <- FALSE
} else {
geometricMean <- !any(x[!is.na(x)] < 0)
}
if (is.logical(replaceZeroes)) {
if (!replaceZeroes | is.factor(x) | all(x[!is.na(x)] %in%
c(0, 1))) {
replaceZeroes <- NA
} else {
replaceZeroes <- min(x[!is.na(x) & x > 0])/2
}
}
strata <- strata[subset]
s <- sort(unique(strata))
rslt <- describe_vector(x, probs, thresholds, geometricMean,
geomInclude, replaceZeroes)
if (length(s) > 1) {
for (i in s) rslt <- rbind(rslt, describe_vector(x[strata ==
i & !is.na(strata)], probs, thresholds, geometricMean,
geomInclude, replaceZeroes))
if (any(is.na(strata))) {
rslt <- rbind(rslt, describe_vector(x[is.na(strata)],
probs, thresholds, geometricMean, geomInclude,
replaceZeroes))
dimnames(rslt)[[1]] <- format(c("All", paste(" Str",
format(c(format(s), "NA")))))
}
else dimnames(rslt)[[1]] <- format(c("All", paste(" Str",
format(s))))
}
rslt
}
describe_stratified_date <- function(x, strata, subset,
probs = c(0.25, 0.5, 0.75),
thresholds = NULL, geomInclude = FALSE,
replaceZeroes = FALSE) {
if (!is.Date(x))
stop("x must be a Date object")
xi <- as.integer(x)
rslt <- describe_stratified_vector(xi, strata, subset, probs, thresholds,
geomInclude, replaceZeroes)
rslt[, "isDate"] <- 1
rslt
}
describe_stratified_surv <- function(x, strata, subset,
probs = c(0.25, 0.5, 0.75),
thresholds = NULL, geomInclude = FALSE,
replaceZeroes = FALSE, restriction = Inf) {
if (!survival::is.Surv(x))
stop("x must be a Surv object")
n <- dim(x)[1]
if (is.null(subset))
subset <- rep(TRUE, n)
if (n != length(subset))
stop("length of variables must match length of subset")
if (is.null(strata))
strata <- rep(1, n)
if (n != length(strata))
stop("length of variables must match length of strata")
x <- x[subset]
if (geomInclude) {
geometricMean <- !any(x[!is.na(x), 1] < 0)
}
else {
geometricMean <- FALSE
}
if (is.logical(replaceZeroes)) {
if (replaceZeroes) {
replaceZeroes <- min(x[!is.na(x) & x[, 1] > 0, 1])/2
} else {
replaceZeroes <- NA
}
}
strata <- strata[subset]
s <- sort(unique(strata))
rslt <- describe_surv(x, probs, thresholds, geomInclude, geometricMean,
replaceZeroes, restriction)
if (length(s) > 1) {
for (i in s) {
rslt <- rbind(rslt, describe_surv(x[strata == i & !is.na(strata)],
probs, thresholds, geomInclude,
geometricMean, replaceZeroes, restriction))
}
if (any(is.na(strata))) {
rslt <- rbind(rslt, describe_surv(x[is.na(strata)], probs,
thresholds, geomInclude, geometricMean,
replaceZeroes, restriction))
dimnames(rslt)[[1]] <- format(c("All",
paste(" Str", format(c(format(s), "NA")))))
} else {
dimnames(rslt)[[1]] <- format(c("All", paste(" Str", format(s))))
}
}
rslt
}
describe_stratified_matrix <- function(x, strata, subset,
probs = c(0.25, 0.5, 0.75),
thresholds = NULL, geomInclude = FALSE,
replaceZeroes = FALSE) {
if (!is.matrix(x)) {
stop("x must be a matrix")
}
p <- dim(x)[2]
nms <- dimnames(x)[[2]]
if (is.null(nms)) {
nms <- paste("V", 1:p, sep = "")
}
rslt <- NULL
for (i in 1:p) {
rslt <- rbind(
rslt,
describe_stratified_vector(x[, i], strata, subset, probs,
thresholds, geomInclude, replaceZeroes)
)
}
dimnames(rslt)[[1]] <- paste(format(rep(nms, each = (dim(rslt)[1])/p)), dimnames(rslt)[[1]])
rslt
}
describe_stratified_list <- function(x, strata, subset,
probs = c(0.25, 0.5, 0.75),
thresholds = NULL, geomInclude = FALSE,
replaceZeroes = FALSE, restriction = Inf) {
if (!is.list(x)) {
stop("x must be a list")
}
p <- length(x)
nms <- names(x)
if (is.null(nms)) {
nms <- paste("V", 1:p, sep = "")
}
rslt <- NULL
for (i in 1:p) {
if (survival::is.Surv(x[[i]])) {
rslt <- rbind(rslt, describe_stratified_surv(x[[i]], strata,
subset, probs, thresholds,
geomInclude, replaceZeroes,
restriction))
} else if (is.Date(x[[i]])) {
rslt <- rbind(rslt, describe_stratified_date(x[[i]], strata, subset,
probs, thresholds,
geomInclude, replaceZeroes))
} else {
rslt <- rbind(rslt, describe_stratified_vector(x[[i]], strata, subset,
probs, thresholds,
geomInclude, replaceZeroes))
}
}
dimnames(rslt)[[1]] <- paste(format(rep(nms, each = (dim(rslt)[1])/p)), dimnames(rslt)[[1]])
rslt
}
print.uDescriptives <- function (x, ..., sigfigs=max(3,getOption("digits")-3),width=9,nonsci.limit=5, print.it= TRUE) {
cmptRoundDigits <- function (x, sf) {
y <- max(abs(x),na.rm=TRUE)
if (y==0) {
sf
} else {
y <- trunc(log(y) / log(10)) - (y < 1)
max(0,sf - y - (y < sf))
}
}
frmtCol <- function (x, sf, nonsci.limit, colwidth=9, append="") {
rslt <- NULL
for (i in 1:length(x)) {
if (is.na(x[i])) {
tmp <- "NA"
} else {
rd <- cmptRoundDigits (x[i], sf)
if (rd <= nonsci.limit & abs(x[i]) < 10^nonsci.limit) {
tmp <- format(round(x[i],rd),nsmall=rd,width=1)
} else {
tmp <- format(round(x[i],rd), digits=sf, scientific=TRUE, width=1)
}
}
rslt <- c(rslt,ifelse(x[i]<0,tmp,paste(" ",tmp,sep="")))
}
rslt <- paste(rslt,append,sep="")
format(rslt, justify="centre", width=colwidth)
}
ncol <- dim(x)[2]
meancol <- (1:ncol)[dimnames(x)[[2]]=="Mean"]
mincol <- (1:ncol)[dimnames(x)[[2]]==" Min"]
maxcol <- (1:ncol)[dimnames(x)[[2]]==" Max"]
censMin <- x[,"firstEvent"] > x[,mincol]
censMin[is.na(censMin)] <- FALSE
censMax <- x[,"lastEvent"] < x[,maxcol]
censMax[is.na(censMax)] <- FALSE
if (!any(censMax)) {
restriction <- NULL
} else {
restriction <- frmtCol(x[,"restriction"],sigfigs,nonsci.limit,1,")")
restriction <- paste("(R",restriction,sep="")
restriction[!censMax] <- ""
restriction <- format(restriction, justify="left")
}
frmtCoefficients <- format(x[,1:(ncol-4),drop=FALSE])
for (j in 1:2) frmtCoefficients[,j] <- format (x[,j],justify="right",width=5)
frmtCoefficients[,mincol] <- frmtCol (x[,mincol],sigfigs,nonsci.limit,width,ifelse(censMin,"+",""))
for (j in 3:5) frmtCoefficients[,j] <- frmtCol (x[,j],sigfigs,nonsci.limit,width,ifelse(censMax,"+",""))
if(any(dimnames(x)[[2]] == "Geom Mn")){
indx <- 7:(ncol-4)
} else {
indx <- 6:(ncol-4)
}
indx <- indx[indx != maxcol]
for (j in indx) frmtCoefficients[,j] <- frmtCol (x[,j],sigfigs,nonsci.limit,width)
frmtCoefficients[,maxcol] <- frmtCol (x[,maxcol],sigfigs,nonsci.limit,width,ifelse(censMax,"+",""))
dateBool <- any(is.na(x[,"isDate"]))
if(dateBool){
} else {
if (any(x[,"isDate"]==1)) {
xformCol <- c(3,5:(dim(x)[2]-4))
for (j in 1:length(xformCol)) {
if (substring(dimnames(x)[[2]][xformCol[j]],1,2)=="Pr") xformCol[j] <- NA
}
xformCol <- xformCol[!is.na(xformCol)]
orgn <- "1970-01-01"
frmtCoefficients[x[,"isDate"]==1,xformCol] <- format(as.Date(x[x[,"isDate"]==1,xformCol],orgn))
}
}
if (!is.null(restriction)) frmtCoefficients <- cbind(frmtCoefficients[,1:2,drop=FALSE],
"Restrict"=restriction,frmtCoefficients[,-(1:2),drop=FALSE])
if(print.it) print(frmtCoefficients,quote=FALSE)
invisible(frmtCoefficients)
} |
regtemplate <- function(x) {
get_templatebrain(attr(x, 'regtemplate'))
}
`regtemplate<-` <- function(x, value) {
attr(x, 'regtemplate') <- get_templatebrain(value)
x
}
get_templatebrain <- function(x, strict=FALSE) {
if(is.templatebrain(x) || is.null(x)) return(x)
b = try(get(x, mode = 'list'), silent = T)
if (!is.templatebrain(b) && strict)
stop("Unable to find template brain: ", b)
if(inherits(b, 'try-error')) NULL else b
}
brain_details <- function(x, pos) {
obj=get(x, pos = pos)
if(!is.templatebrain(obj))
return(NULL)
env.name=attr(as.environment(pos), 'name')
if(is.null(env.name)) env.name=NA_character_
env.name=sub("package:","", env.name)
dims=obj[['dims']]
if(is.null(dims))
dims=rep(NA_integer_, 3)
name=as.character(obj)
md5=digest::digest(obj, algo = 'md5')
data.frame(package=env.name, name=name, md5=md5,
W=dims[1],H=dims[2],D=dims[3], stringsAsFactors = FALSE)
}
all_templatebrains_tomemo <- function() {
ll=utils::apropos(what='.*', mode='list', where=TRUE)
df=data.frame(object=ll, pos=as.integer(names(ll)),
stringsAsFactors = FALSE)
reslist=mapply(brain_details, df$object, df$pos, SIMPLIFY = FALSE)
goodvals=sapply(reslist, is.data.frame)
details <- do.call(rbind, reslist[goodvals])
df=cbind(df[goodvals,,drop=FALSE], details)
rownames(df)=NULL
df
}
all_templatebrains_m <- memoise::memoise(all_templatebrains_tomemo)
all_templatebrains <- function(cached=TRUE, remove.duplicates=FALSE) {
if(isFALSE(cached))
memoise::forget(all_templatebrains_m)
res=all_templatebrains_m()
if(remove.duplicates)
res[!duplicated(res[['md5']]),,drop=FALSE]
else res
}
guess_templatebrain <- function(x, rval=c("templatebrain", "name"),
cached=TRUE, mustWork=FALSE) {
dims <- if(is.numeric(x) && length(x)%in%2:3) {
paste(x, collapse="x")
} else {
tx=as.templatebrain(x, regName='dummy')
paste(tx$dims, collapse="x")
}
rval=match.arg(rval)
df=all_templatebrains(cached = cached, remove.duplicates = TRUE)
if(nrow(df)==0) {
candidates=data.frame()
} else {
df$dims=apply(df[c("W","H","D")],1,paste, collapse="x")
candidates=df[pmatch(dims, df$dims, duplicates.ok = TRUE),,drop=FALSE]
if(nrow(candidates)>1) {
if(mustWork) {
print(candidates)
stop("Multiple candidates!")
}
}
}
if(nrow(candidates)==0)
if(mustWork) stop("No candidates found!")
if(rval=='name') {
unique(candidates$name)
} else {
if(nrow(candidates)==0) return(NULL)
if(nrow(candidates)>1)
mapply(get, x=candidates$object, pos=candidates$pos, SIMPLIFY = FALSE)
else get(candidates$object, pos = candidates$pos)
}
} |
test.basic<-function(DF, at, display_under, tag) {
if(!test.ftree(DF)) stop("first argument must be a fault tree")
parent<-which(DF$ID== at)
if(length(parent)==0) {stop("connection reference not valid")}
thisID<-max(DF$ID)+1
if(DF$Type[parent]<10) {stop("non-gate connection requested")}
if(!DF$MOE[parent]==0) {
stop("connection cannot be made to duplicate nor source of duplication")
}
if(tag!="") {
if (length(which(DF$Tag == tag) != 0)) {
stop("tag is not unique")
}
prefix<-substr(tag,1,2)
if(prefix=="E_" || prefix=="G_" || prefix=="H_") {
stop("Prefixes 'E_', 'G_', and 'H_' are reserved for auto-generated tags.")
}
}
if(DF$Type[parent]==15) {
if(length(which(DF$CParent==at))>0) {
stop("connection slot not available")
}
}
if(DF$Type[parent]==11 && length(which(DF$Parent==at))>2) {
warning("More than 3 connections to AND gate.")
}
condition=0
if(DF$Type[parent]>11 && DF$Type[parent]<15 ) {
if(length(which(DF$CParent==at))>1) {
stop("connection slot not available")
}
if( length(which(DF$CParent==at))==0) {
if(DF$Cond_Code[parent]<10) {
condition=1
}
}else{
if(DF$Cond_Code[parent]>9) {
condition=1
}
}
}
gp<-at
if(length(display_under)!=0) {
if(DF$Type[parent]!=10) {stop("Component stacking only permitted under OR gate")}
if (is.character(display_under) & length(display_under) == 1) {
siblingDF<-DF[which(DF$CParent==DF$ID[parent]),]
display_under<-siblingDF$ID[which(siblingDF$Tag==display_under)]
}
if(!is.numeric(display_under)) {
stop("display under request not found")
}
if(DF$CParent[which(DF$ID==display_under)]!=at) {stop("Must stack at component under same parent")}
if(length(which(DF$GParent==display_under))>0 ) {
stop("display under connection not available")
}else{
gp<-display_under
}
}
info_vec<-c(thisID, parent, gp, condition)
info_vec
} |
.joda.times <- matrix(c(
'^[0-9]{4}[0-9]{2}([-]|[ ]|[/])?[0-9]{2}$', '^yyyy([-]|[ ]|[/])?MM([-]|[ ]|[/])?dd$', '1988-03-02',
'^[0-9]{2}([-]|[ ]|[/])[0-9]{2}([-]|[ ]|[/])?[0-9]{4}$', '^dd([-]|[ ]|[/])?MM([-]|[ ]|[/])?yyyy$', '02-03-1988',
'^[0-9]{4}([-]|[ ]|[/])[A-Za-z]{3}([-]|[ ]|[/])?[0-9]{2}$', '^yyyy([-]|[ ]|[/])?MMM([-]|[ ]|[/])?dd$', '1988-Mar-02',
'^[0-9]{2}([-]|[ ]|[/])[A-Za-z]{3}([-]|[ ]|[/])?[0-9]{4}$', '^dd([-]|[ ]|[/])?MMM([-]|[ ]|[/])?yyyy$', '02-Mar-1988',
'^[0-9]{4}([-]|[ ]|[/])?[0-9]{2}$', '^yyyy([-]|[ ]|[/])?MM$', '1988-03',
'^[0-9]{4}([-]|[ ]|[/])?[A-Za-z]{3}$', '^yyyy([-]|[ ]|[/])?MMM$', '1988-Mar',
'^[A-Za-z]{3}([-]|[ ]|[/])?[0-9]{4}$', '^MMM([-]|[ ]|[/])?yyyy$', 'Mar-1988',
'^[0-9]{2}([-]|[ ]|[/])?[0-9]{4}$', '^MM([-]|[ ]|[/])?yyyy$', '03-1988',
'^[0-9]{4}$', '^yyyy$', '1998'
), ncol=3, byrow=T
)
colnames(.joda.times) <- c('regex','format','example')
.joda.times <- as.data.frame(.joda.times, stringsAsFactors=F)
checkTimeFormat <- function(fmt) {
result <- lapply(
.joda.times[,2],
function(X,Y) {grep(pattern=X,x=Y)},
Y=fmt
)
result <- sum(unlist(result)) == 1
return(result)
} |
make_lines = function(heightmap,basedepth=0,linecolor="grey20",zscale=1,alpha=1,linewidth = 2,solid=TRUE) {
heightmap = heightmap/zscale
heightval3 = heightmap[1,1]
heightval4 = heightmap[nrow(heightmap),1]
heightval1 = heightmap[1,ncol(heightmap)]
heightval2 = heightmap[nrow(heightmap),ncol(heightmap)]
heightlist = list()
if(all(!is.na(heightmap))) {
if(solid) {
heightlist[[1]] = matrix(c(1,1,basedepth,heightval3,-1,-1),2,3)
heightlist[[2]] = matrix(c(nrow(heightmap),nrow(heightmap),basedepth,heightval4,-1,-1),2,3)
heightlist[[3]] = matrix(c(1,1,basedepth,heightval1,-ncol(heightmap),-ncol(heightmap)),2,3)
heightlist[[4]] = matrix(c(nrow(heightmap),nrow(heightmap),basedepth,heightval2,-ncol(heightmap),-ncol(heightmap)),2,3)
heightlist[[5]] = matrix(c(1,1,basedepth,basedepth,-1,-ncol(heightmap)),2,3)
heightlist[[6]] = matrix(c(1,nrow(heightmap),basedepth,basedepth,-ncol(heightmap),-ncol(heightmap)),2,3)
heightlist[[7]] = matrix(c(nrow(heightmap),nrow(heightmap),basedepth,basedepth,-ncol(heightmap),-1),2,3)
heightlist[[8]] = matrix(c(nrow(heightmap),1,basedepth,basedepth,-1,-1),2,3)
} else {
basedepth = basedepth/zscale
counter = 1
if(basedepth > heightval1) {
heightlist[[counter]] = matrix(c(1,1,basedepth,heightval1,-1,-1),2,3)
counter = counter + 1
}
if(basedepth > heightval2) {
heightlist[[counter]] = matrix(c(nrow(heightmap),nrow(heightmap),basedepth,heightval2,-1,-1),2,3)
counter = counter + 1
}
if(basedepth > heightval3) {
heightlist[[counter]] = matrix(c(1,1,basedepth,heightval3,-ncol(heightmap),-ncol(heightmap)),2,3)
counter = counter + 1
}
if(basedepth > heightval4) {
heightlist[[counter]] = matrix(c(nrow(heightmap),nrow(heightmap),basedepth,heightval4,-ncol(heightmap),-ncol(heightmap)),2,3)
counter = counter + 1
}
}
} else {
heightlist = make_baselines_cpp(heightmap,is.na(heightmap),basedepth)
}
if(length(heightlist) > 0) {
segmentlist = do.call(rbind,heightlist)
segmentlist[,1] = segmentlist[,1] - nrow(heightmap)/2
segmentlist[,3] = -segmentlist[,3] - ncol(heightmap)/2
rgl::segments3d(segmentlist,color=linecolor,lwd=linewidth,alpha=alpha,depth_mask=TRUE,
line_antialias=FALSE, depth_test="lequal",ambient = ifelse(solid,"
}
} |
SS_read_summary <- function(file="ss_summary.sso"){
if(is.na(file.info(file)$size) || file.info(file)$size == 0){
warning("file is missing or empty: ", file)
return(NULL)
}
read_summary_section <- function(start, end, ncol, nonnumeric=NULL, names){
if(start >= end){
return(NULL)
}
df <- all_lines[start:end]
comment_lines <- grep("^
if(length(comment_lines) > 0){
df <- df[-comment_lines]
}
df <- strsplit(df, "[[:blank:]]+")
df <- as.list(df)
df <- do.call("rbind", df)
df <- as.data.frame(df[, -1], stringsAsFactors = FALSE, row.names=df[, 1])
if(ncol > 1){
numeric.cols <- which(!(1:ncol) %in% nonnumeric)
df[, numeric.cols] <- lapply(df[, numeric.cols], as.numeric)
}else{
df[, 1] <- as.numeric(df[, 1])
}
names(df) <- names
return(df)
}
all_lines <- readLines(file)
like_start <- grep("
param_start <- grep("
derived_quants_start <- grep("
survey_stdev_start <- grep("
biomass_start <- grep("
header <- all_lines[1:(like_start-1)]
likelihoods <- read_summary_section(start = like_start+2,
end = param_start - 1,
ncol = 1,
names="logL*Lambda")
parameters <- read_summary_section(start = param_start+2,
end = derived_quants_start - 1,
ncol = 4,
nonnumeric = 3,
names=c("Value", "SE", "Active?", "Range"))
derived_quants <- read_summary_section(start = derived_quants_start+2,
end = survey_stdev_start - 1,
ncol = 2,
names=c("Value", "SE"))
survey_stdev <- read_summary_section(start = survey_stdev_start+1,
end = biomass_start-1,
ncol = 6,
nonnumeric = c(3,5),
names=c("Value", "SE", "XX", "Exp", "XX", "Q"))
survey_stdev <- survey_stdev[names(survey_stdev) != "XX"]
biomass <- read_summary_section(start = biomass_start+2,
end = length(all_lines),
ncol = 2,
names=c("Value", "SE"))
return(list(header = header,
likelihoods = likelihoods,
parameters = parameters,
derived_quants = derived_quants,
survey_stdev = survey_stdev,
biomass = biomass))
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.