code
stringlengths 1
13.8M
|
---|
rm(list=ls())
setwd("C:/Users/Tom/Documents/Kaggle/Santander")
library(data.table)
targetDate <- "12-11-2016"
modelGroup <- "trainTrainAll"
topNFeatures <- 10
rankImpExponent <- -0.75
K <- 5
source("Common/getModelWeights.R")
dateTargetWeights <- readRDS(file.path(getwd(), "Model weights",
targetDate, "model weights first.rds"))
jun16Counts <- c(0, 0, 9704, 9, 2505, 48, 474, 201, 119, 0, 0, 99,
2072, 114, 20, 14, 6, 3254, 4137, 290, 0, 4487, 4600, 8651)
baseProducts <- c("ahor_fin", "aval_fin", "cco_fin", "cder_fin",
"cno_fin", "ctju_fin", "ctma_fin", "ctop_fin",
"ctpp_fin", "deco_fin", "deme_fin", "dela_fin",
"ecue_fin", "fond_fin", "hip_fin", "plan_fin",
"pres_fin", "reca_fin", "tjcr_fin", "valo_fin",
"viv_fin", "nomina", "nom_pens", "recibo"
)
targetVars <- paste0("ind_", baseProducts, "_ult1")
nbTargetVars <- length(targetVars)
dropPredictors <- c(
"trainWeight"
, "hasNewProduct", "nbNewProducts", "hasAnyPosFlank"
, "ncodpers"
, "lastDate"
, "gapsFrac", "dataMonths", "monthsFrac", "nbLagRecords "
, "grossIncome"
, "seniorityDensity"
, paste0(targetVars, "MAPRatioJune15")
, paste0(targetVars, "RelMAP")
, "familyId"
, targetVars
)
featureSample <- readRDS(file.path(getwd(), "Feature engineering",
"12-11-2016", "train",
"Back0Lag16 features.rds"))
possibleFeatures <- setdiff(colnames(featureSample), dropPredictors)
modelGroupsFolder <- file.path(getwd(), "First level learners", targetDate,
modelGroup)
modelGroups <- list.dirs(modelGroupsFolder)[-1]
modelGroups <- modelGroups[!grepl("Manual tuning", modelGroups)]
modelGroups <- modelGroups[!grepl("no fold BU", modelGroups)]
nbModelGroups <- length(modelGroups)
if(nbModelGroups==0){
modelGroups <- modelGroupsFolder
nbModelGroups <- 1
}
featureImportance <- NULL
for(i in 1:nbModelGroups){
modelGroup <- modelGroups[i]
slashPositions <- gregexpr("\\/", modelGroup)[[1]]
modelGroupExtension <- substring(modelGroup,
1 + slashPositions[length(slashPositions)])
modelGroupFiles <- list.files(modelGroup)
modelGroupFiles <- modelGroupFiles[!grepl("no fold BU", modelGroupFiles)]
nbModels <- length(modelGroupFiles)
monthsBack <- as.numeric(substring(gsub("Lag.*$", "", modelGroupExtension),
5))
lag <- as.numeric(gsub("^.*Lag", "", modelGroupExtension))
if(nbModels>0){
for(j in 1:nbModels){
modelGroupFile <- modelGroupFiles[j]
isFold <- grepl("Fold", modelGroupFile)
if(isFold){
fold <- as.numeric(gsub("^.* Fold | - .*$", "", modelGroupFile))
} else{
fold <- NA
}
modelInfo <- readRDS(file.path(modelGroup, modelGroupFile))
importanceMatrix <- modelInfo$importanceMatrix
targetVar <- modelInfo$targetVar
relativeWeight <- getModelWeights(monthsBack, targetVar,
dateTargetWeights)
foldWeight <- ifelse(isFold, 1 - 1/K, 1)
if(isFold){
prodMonthFiles <- modelGroupFiles[grepl(targetVar, modelGroupFiles)]
nbFoldsProd <- sum(grepl("Fold", prodMonthFiles))
foldWeight <- foldWeight * 4 / nbFoldsProd
}
featureRankWeight <- foldWeight *
((1:nrow(importanceMatrix))^rankImpExponent)
featureWeight <- relativeWeight * featureRankWeight
jun16W <- jun16Counts[match(targetVar, targetVars)]
featureImportance <- rbind(featureImportance,
data.table(
modelGroupExtension = modelGroupExtension,
targetVar = targetVar,
relativeWeight = relativeWeight,
rank = 1:nrow(importanceMatrix),
monthsBack = monthsBack,
lag = lag,
feature = importanceMatrix$Feature,
isFold = isFold,
fold = fold,
featureRankWeight = featureRankWeight,
featureWeight = featureWeight,
jun16W = jun16W,
overallWeight = featureWeight*jun16W
)
)
}
}
}
allFeatures <- sort(unique(featureImportance$feature))
nonModeledFeatures <- setdiff(possibleFeatures, allFeatures)
allFeatures <- c(allFeatures, nonModeledFeatures)
overallProductFeatureRanks <-
featureImportance[,sum(featureWeight),
.(feature, targetVar)]
names(overallProductFeatureRanks)[3] <- "weightSum"
overallProductFeatureRanks <-
overallProductFeatureRanks[order(targetVar, -weightSum)]
overallProductFeatureRanks[,feature_rank := match(1:length(weightSum),
order(-weightSum)), by=targetVar]
generalRank <- featureImportance[, .(overallWeightSum =
sum(overallWeight)), feature]
generalRank <- generalRank[order(-overallWeightSum)]
sortedFeatures <- generalRank$feature
sortedFeatures <- c(sortedFeatures, nonModeledFeatures)
for(i in 1:nbTargetVars){
targetVarLoop <- targetVars[i]
overallFeatTargetVar <- overallProductFeatureRanks[targetVar==targetVarLoop,
feature]
missingFeatures <- setdiff(sortedFeatures, overallFeatTargetVar)
feature_ranks <- rev(rev(1:length(allFeatures))[1:length(missingFeatures)])
overallProductFeatureRanks <- rbind(overallProductFeatureRanks,
data.table(feature = missingFeatures,
targetVar = targetVarLoop,
weightSum = 0,
feature_rank = feature_ranks))
}
overallProductFeatureRanks <- overallProductFeatureRanks[order(targetVar,
feature_rank)]
productFeatureRanksMonths <-
featureImportance[,sum(featureRankWeight),
.(monthsBack, targetVar, feature)]
names(productFeatureRanksMonths)[4] <- "weightSum"
productFeatureRanksMonths <-
productFeatureRanksMonths[order(-monthsBack, targetVar, -weightSum)]
productFeatureRanksMonths[,feature_rank := match(1:length(weightSum),
order(-weightSum)),
by=.(monthsBack, targetVar)]
monthsBacks <- sort(unique(featureImportance$monthsBack))
nbMonthsBack <- length(monthsBacks)
for(i in 1:nbMonthsBack){
monthsBackLoop <- monthsBacks[i]
for(j in 1:nbTargetVars){
targetVarLoop <- targetVars[j]
overallFeatTargetVar <-
productFeatureRanksMonths[targetVar==targetVarLoop &
monthsBack == monthsBackLoop, feature]
sortedFeatures <-
overallProductFeatureRanks[targetVar==targetVarLoop, feature]
if(length(sortedFeatures) != length(allFeatures)) browser()
missingFeatures <- setdiff(sortedFeatures, overallFeatTargetVar)
feature_ranks <- rev(rev(1:length(allFeatures))[1:length(missingFeatures)])
productFeatureRanksMonths <- rbind(productFeatureRanksMonths,
data.table(monthsBack = monthsBackLoop,
targetVar = targetVarLoop,
feature = missingFeatures,
weightSum = 0,
feature_rank = feature_ranks))
}
}
productFeatureRanksMonths <- productFeatureRanksMonths[
order(-monthsBack, targetVar, feature_rank)]
saveRDS(overallProductFeatureRanks,
file.path(getwd(), "first level learners", targetDate,
"product feature order.rds"))
saveRDS(productFeatureRanksMonths,
file.path(getwd(), "first level learners", targetDate,
"product month feature order.rds"))
|
context("shinyAce")
test_that("modes", {
modes <- shinyAce::getAceModes()
expect_true(is.character(modes))
expect_true(length(modes) > 0)
expect_true(sum(nchar(modes)) > 500)
})
test_that("themes", {
themes <- shinyAce::getAceThemes()
expect_true(is.character(themes))
expect_true(length(themes) > 0)
expect_true(sum(nchar(themes)) > 300)
})
test_that("is.empty", {
expect_true(is.empty(NULL))
expect_true(is.empty(NA))
expect_true(is.empty(c()))
expect_true(is.empty(""))
expect_true(is.empty(" "))
expect_true(is.empty(c(" ", " ")))
expect_true(is.empty(list()))
expect_true(is.empty(list(a = "", b = "")))
})
|
SimulatorReference <- R6Class("SimulatorReference",
public = list(
attached = list(),
results = list()
),
)
|
pkgdown_template <- function(path = ".") {
stop_if_not_installed("pkgdown")
reference <- pkgdown::template_reference(path = path)
articles <- pkgdown::template_articles(path = path)
navbar <- pkgdown::template_navbar(path = path)
c(reference, articles, navbar) %>%
as_yml()
}
yml_pkgdown <- function(.yml, as_is = yml_blank(), extension = yml_blank()) {
.yml$pkgdown <- list(as_is = as_is, extension = extension)
.yml
}
yml_pkgdown_opts <- function(
.yml,
site_title = yml_blank(),
destination = yml_blank(),
url = yml_blank(),
toc_depth = yml_blank()
) {
pkgdown_opts <- list(
title = site_title,
destination = destination,
url = url,
toc = list(depth = toc_depth) %>% purrr::discard(is_yml_blank)
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, pkgdown_opts)
.yml[names(pkgdown_opts)] <- pkgdown_opts
.yml
}
yml_pkgdown_development <- function(
.yml,
mode = yml_blank(),
dev_destination = yml_blank(),
version_label = yml_blank(),
version_tooltip = yml_blank()
) {
pkgdown_development_opts <- list(
mode = mode,
destination = dev_destination,
version_label = version_label,
version_tooltip = version_tooltip
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, pkgdown_development_opts)
.yml[names(pkgdown_development_opts)] <- pkgdown_development_opts
.yml
}
yml_pkgdown_template <- function(
.yml,
bootswatch = yml_blank(),
ganalytics = yml_blank(),
noindex = yml_blank(),
package = yml_blank(),
path = yml_blank(),
assets = yml_blank(),
default_assets = yml_blank()
) {
pkgdown_template_opts <- list(
bootswatch = bootswatch,
ganalytics = ganalytics,
noindex = noindex,
package = package,
path = path,
assets = assets,
default_assets = default_assets
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, pkgdown_template_opts)
.yml[names(pkgdown_template_opts)] <- pkgdown_template_opts
.yml
}
yml_pkgdown_reference <- function(.yml, ...) {
warn_if_duplicate_fields(.yml, list(references = ""))
.yml$references <- c(...)
.yml
}
pkgdown_ref <- function(
title = yml_blank(),
desc = yml_blank(),
contents = yml_blank(),
exclude = yml_blank(),
...
) {
list(
title = title,
desc = desc,
contents = contents,
exclude = exclude,
...
) %>%
purrr::discard(is_yml_blank)
}
yml_pkgdown_news <- function(.yml, one_page = yml_blank()) {
warn_if_duplicate_fields(.yml, list(news = ""))
.yml$news <- list(one_page = one_page)
.yml
}
yml_pkgdown_articles <- function(.yml, ...) {
warn_if_duplicate_fields(.yml, list(articles = ""))
.yml$articles <- c(...)
.yml
}
pkgdown_article <- function(
title = yml_blank(),
desc = yml_blank(),
contents = yml_blank(),
exclude = yml_blank(),
...
) {
list(
title = title,
desc = desc,
contents = contents,
exclude = exclude,
...
) %>%
purrr::discard(is_yml_blank)
}
yml_pkgdown_tutorial <- function(.yml, ...) {
warn_if_duplicate_fields(.yml, list(references = ""))
.yml$references <- c(...)
.yml
}
pkgdown_tutorial <- function(
name = yml_blank(),
title = yml_blank(),
tutorial_url = yml_blank(),
source = yml_blank(),
...
) {
list(
name = name,
title = title,
url = tutorial_url,
source = source,
...
) %>%
purrr::discard(is_yml_blank)
}
yml_pkgdown_figures <- function(
.yml,
dev = yml_blank(),
dpi = yml_blank(),
dev.args = yml_blank(),
fig.ext = yml_blank(),
fig.width = yml_blank(),
fig.height = yml_blank(),
fig.retina = yml_blank(),
fig.asp = yml_blank(),
...
) {
warn_if_duplicate_fields(.yml, list(figures = ""))
.yml$figures <- list(
dev = dev,
dpi = dpi,
dev.args = dev.args,
fig.ext = fig.ext,
fig.width = fig.width,
fig.height = fig.height,
fig.retina = fig.retina,
fig.asp = fig.asp,
...
) %>%
purrr::discard(is_yml_blank)
.yml
}
yml_pkgdown_docsearch <- function(.yml, api_key = yml_blank(), index_name = yml_blank(), doc_url = yml_blank()) {
docsearch <- list(
template = list(
params = list(
docsearch = list(
api_key = api_key,
index_name = index_name
) %>%
purrr::discard(is_yml_blank)
)
),
url = doc_url
) %>%
purrr::discard(is_yml_blank)
warn_if_duplicate_fields(.yml, docsearch)
.yml[names(docsearch)] <- docsearch
.yml
}
|
library(testthat)
library(synthACS)
context("pull_household")
test_that("errors work", {
ca_counties <- geo.make(state= 'CA', county= '*')
diamonds <- data.frame(
carat= rexp(100),
cut= factor(sample(c("A", "B", "C"), size= 100, replace= TRUE)),
x= runif(100, min= 0, max= 10),
y= runif(100, min= 0, max= 10),
x= runif(100, min= 0, max= 10)
)
expect_error(pull_household(endyear= 2016, span=0, ca_counties))
expect_error(pull_household(endyear= 2016, span= -1, ca_counties))
expect_error(pull_household(endyear= 2016, span= 7, ca_counties))
expect_error(pull_household(endyear= 2000, span=5, ca_counties))
expect_error(pull_household(endyear= 2010.5, span=5, ca_counties))
expect_error(pull_household(endyear= "ABC", span=5, ca_counties))
ca_counties2 <- ca_counties
class(ca_counties2) <- "ABC"
expect_error(pull_household(endyear= 2010, span=5, ca_counties2))
expect_error(pull_household(endyear= 2010, span=5, diamonds))
})
test_that("returns results accurately - counties", {
ca_geo <- geo.make(state= 'CA', county= 'Los Angeles')
ca_dat <- pull_household(2014, 5, ca_geo)
synthACS:::confirm_macroACS_class(ca_dat)
})
test_that("returns results accurately - state", {
ca_geo <- geo.make(state= "CA")
ca_dat <- pull_household(2016, 5, ca_geo)
synthACS:::confirm_macroACS_class(ca_dat)
ca_geo <- geo.make(state= "CA", county= '*')
ca_dat <- pull_household(2016, 5, ca_geo)
synthACS:::confirm_macroACS_class(ca_dat)
})
|
library(shiny)
library(ggplot2)
ui <- fluidPage(
h4("Demo - brushedPoints - Interactive plots - select data points in plot - return the rows of data that are selected by brush"),
plotOutput(outputId = "boxplot", brush = "plot_brush_"),
fixedRow(
column(width= 5, tags$b(tags$i("Actual Dataset")), tableOutput("data1")),
column(width = 5, tags$b(tags$i("Updated Dataset")), tableOutput("data2"), offset = 2)
)
)
server <- function(input, output) {
mtcars1 = mtcars
mtcars1$cyl = as.factor(mtcars1$cyl)
mt <- reactiveValues(data=mtcars1)
output$boxplot <- renderPlot({
ggplot(mt$data, aes(cyl, mpg)) + geom_boxplot(outlier.colour = "red") + coord_flip()
})
output$data1 <- renderTable({
mtcars1
})
output$data2 <- renderTable({
mt$data
})
observe({
df = brushedPoints(mt$data, brush = input$plot_brush_, allRows = TRUE)
mt$data = df[df$selected_== FALSE, ]
})
}
shinyApp(ui = ui, server = server)
|
summary.xxirt <- function( object, digits=3, file=NULL, ...)
{
sirt_osink( file=file )
res <- xxirt_summary_parts(object=object, digits=digits)
sirt_csink( file=file )
}
|
"exGWAS"
|
d_ACG <- function(x, Lambda, log = FALSE) {
if (is.null(dim(x))) {
x <- rbind(x)
}
p <- ncol(x)
if (p != sqrt(length(Lambda))) {
stop("x and Lambda do not have the same dimension.")
}
if (p == 1) {
log_dens <- d_unif_sphere(x = x, log = TRUE)
} else {
x <- check_unit_norm(x = x, warnings = TRUE)
log_dens <- c_ACG(p = p, Lambda = Lambda, log = TRUE) -
0.5 * p * log(rowSums((x %*% solve(Lambda)) * x))
}
return(switch(log + 1, exp(log_dens), log_dens))
}
c_ACG <- function(p, Lambda, log = FALSE) {
if (!isSymmetric(Lambda, tol = sqrt(.Machine$double.eps),
check.attributes = FALSE)) {
stop("Lambda must be a symmetric matrix")
}
log_det <- 2 * sum(log(diag(chol(Lambda))))
log_c_ACG <- - (w_p(p = p, log = TRUE) + 0.5 * log_det)
return(switch(log + 1, exp(log_c_ACG), log_c_ACG))
}
r_ACG <- function(n, Lambda) {
p <- sqrt(length(Lambda))
x <- matrix(rnorm(n = n * p), nrow = n, ncol = p, byrow = TRUE) %*%
chol(Lambda)
return(x / sqrt(rowSums(x * x)))
}
|
ChronAmp = function(Co = 0.001, exptime = 1, Dx = 0.00001, Dm = 0.45,
Temp = 298.15, n = 1, Area = 1, DerApprox = 2, l = 100,
errCheck = FALSE, Method = "Euler") {
Par = ParCall("ChronAmp", n. = n, Temp. = Temp, Dx1. = Dx, exptime. = exptime, Dm. = Dm, l. = l)
Ox = OneMat(Par$l, Par$j)
Jox = ZeroMat(Par$l, 1)
if (Method == "Euler") {
for (i1 in 1:(Par$l-1)) {
Ox[i1,1] = 0
for (j1 in 2:(Par$j-1)) {
Ox[i1 + 1,j1] = Ox[i1,j1] + Dm*(Ox[i1, j1 -1] - 2*Ox[i1, j1] + Ox[i1, j1+1])
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "RK4") {
for (i1 in 1:(Par$l-1)) {
k1 = ZeroMat(Par$j)
k2 = ZeroMat(Par$j)
k3 = ZeroMat(Par$j)
k4 = ZeroMat(Par$j)
Ox[i1,1] = 0
Ox[i1 +1, 1] = 0
for (j1 in 2:(Par$j-1)) {
k1[j1] = Dm*(Ox[i1, j1 -1] - 2*Ox[i1, j1] + Ox[i1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k1[j1]*0.5
}
for (j1 in 2:(Par$j-1)) {
k2[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k2[j1]*0.5
}
for (j1 in 2:(Par$j-1)) {
k3[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k3[j1]
}
for (j1 in 2:(Par$j-1)) {
k4[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + (k1[j1] + 2*k2[j1] + 2*k3[j1] + k4[j1])/6
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "BI") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1/Par$dtn)/al1
a2 = al3/al1
for (i1 in 1:(Par$l-1)) {
Y = ZeroMat(Par$j-2,Par$j-2)
Y[1,1] = a1
Y[1,2] = a2
Y[Par$j-2,Par$j-3] = 1
Y[Par$j-2,Par$j-2] = a1
for (i in 2:(Par$j-3)) {
Y[i,i] = a1
Y[i,i-1] = 1
Y[i, i +1] = a2
}
Ox[i1,1] = 0
Ox[i1+1,1] = 0
b = (-Ox[i1,2:(Par$j-1)]/(al1*Par$dtn))
b[Par$j-2] = b[Par$j-2] - a2*1
b[1] = b[1] - Ox[i1+1,1]
Ox[i1+1,2:(Par$j-1)] = solve(Y) %*% b
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "CN") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 2/Par$dtn)/al1
a2 = al3/al1
a3 = (al2 + 2/Par$dtn)/al1
for (i1 in 1:(Par$l-1)) {
Y = ZeroMat(Par$j-2,Par$j-2)
Y[1,1] = a1
Y[1,2] = a2
Y[Par$j-2,Par$j-3] = 1
Y[Par$j-2,Par$j-2] = a1
for (i in 2:(Par$j-3)) {
Y[i,i] = a1
Y[i,i-1] = 1
Y[i, i +1] = a2
}
Ox[i1,1] = 0
Ox[i1+1,1] = 0
b = -a3*Ox[i1,2:(Par$j-1)] - Ox[i1,1:((Par$j-1)-1)] - a2*Ox[i1,3:((Par$j-1)+1)]
b[Par$j-2] = b[Par$j-2] - a2*1
b[1] = b[1] - Ox[i1+1,1]
Ox[i1+1,2:(Par$j-1)] = solve(Y) %*% b
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "BDF") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1.5/Par$dtn)/al1
a2 = al3/al1
for (i1 in 1:(Par$l-1)) {
Y = ZeroMat(Par$j-2,Par$j-2)
Y[1,1] = a1
Y[1,2] = a2
Y[Par$j-2,Par$j-3] = 1
Y[Par$j-2,Par$j-2] = a1
for (i in 2:(Par$j-3)) {
Y[i,i] = a1
Y[i,i-1] = 1
Y[i, i +1] = a2
}
Ox[i1,1] = 0
Ox[i1+1,1] = 0
if (i1 == 1) {
b = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[1,2:(Par$j-1)]/(2*Par$dtn*al1)
} else {
b = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1)
}
b[Par$j-2] = b[Par$j-2] - a2*1
b[1] = b[1] - Ox[i1+1,1]
Ox[i1+1,2:(Par$j-1)] = solve(Y) %*% b
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (!(Method %in% c("Euler", "BI", "RK4", "CN", "BDF"))) {
return("Available methods are Euler, BI, RK4, CN and BDF")
}
G = Jox
i = (n*Par$FA*G*Dx*Area*Co)/(sqrt(Dx*Par$tau))
graphy = ggplot(data = data.frame(i[1:(length(i)-1)],Par$t[1:(length(i)-1)]),
aes(y = i[1:(length(i)-1)], x = Par$t[1:(length(i)-1)])) +
geom_point() + xlab("t / s") +
ylab("I / A") + theme_classic()
if (errCheck == TRUE){
return(list(G,Dx,Co,Par$dtn,Par$h,Par$l,Par$j,i,n,Area))
} else {
return(graphy)
}
}
PotStep = function(Co = 0.001, exptime = 1, Dx = 0.00001, Dm = 0.45,
eta = 0, Temp = 298.15, n = 1, Area = 1, l= 100,
DerApprox = 2, errCheck = FALSE, Method = "Euler") {
Par = ParCall("PotStep", n. = n, Temp. = Temp, Dx1. = Dx, exptime. = exptime,
Dm. = Dm, eta. = eta, l. = l)
Ox = OneMat(Par$l, Par$j)
Red = ZeroMat(Par$l, Par$j)
Jox = ZeroMat(Par$l, 1)
if (Method == "Euler") {
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c(1,-exp(Par$p),Derv(npoints = DerApprox, CoefMat = T)[1],Derv(npoints = DerApprox, CoefMat = T)[1]), byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(0, -sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
Ox[i1+1,j1] = Ox[i1,j1] + Dm*(Ox[i1, j1-1] - 2*Ox[i1, j1] + Ox[i1, j1+1])
Red[i1+1, j1] = Red[i1, j1] + Dm*(Red[i1, j1-1] + Red[i1, j1+1] - 2*Red[i1,j1])
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "RK4") {
for (i1 in 1:(Par$l-1)) {
k1 = ZeroMat(Par$j)
k2 = ZeroMat(Par$j)
k3 = ZeroMat(Par$j)
k4 = ZeroMat(Par$j)
k1red = ZeroMat(Par$j)
k2red = ZeroMat(Par$j)
k3red = ZeroMat(Par$j)
k4red = ZeroMat(Par$j)
B = matrix(data = c(1,-exp(Par$p),Derv(npoints = DerApprox, CoefMat = T)[1], Derv(npoints = DerApprox, CoefMat = T)[1]), byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(0, -sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k1[j1] = Dm*(Ox[i1, j1 -1] - 2*Ox[i1, j1] + Ox[i1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k1[j1]*0.5
k1red[j1] = Dm*(Red[i1, j1 -1] - 2*Red[i1, j1] + Red[i1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + k1red[j1]*0.5
}
B = matrix(data = c(1,-exp(Par$p),Derv(npoints = DerApprox, CoefMat = T)[1], Derv(npoints = DerApprox, CoefMat = T)[1]), byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(0, -sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k2[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k2[j1]*0.5
k2red[j1] = Dm*(Red[i1 + 1, j1 -1] - 2*Red[i1 + 1, j1] + Red[i1 + 1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + k2red[j1]*0.5
}
B = matrix(data = c(1,-exp(Par$p),Derv(npoints = DerApprox, CoefMat = T)[1], Derv(npoints = DerApprox, CoefMat = T)[1]), byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(0, -sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k3[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k3[j1]
k3red[j1] = Dm*(Red[i1 + 1, j1 -1] - 2*Red[i1 + 1, j1] + Red[i1 + 1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + k3red[j1]
}
B = matrix(data = c(1,-exp(Par$p),Derv(npoints = DerApprox, CoefMat = T)[1], Derv(npoints = DerApprox, CoefMat = T)[1]), byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(0, -sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k4[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + (k1[j1] + 2*k2[j1] + 2*k3[j1] + k4[j1])/6
k4red[j1] = Dm*(Red[i1 + 1, j1 -1] - 2*Red[i1 + 1, j1] + Red[i1 + 1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + (k1red[j1] + 2*k2red[j1] + 2*k3red[j1] + k4red[j1])/6
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "BI") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1/Par$dtn)/al1
a2 = al3/al1
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c(1,-exp(Par$p),Derv(npoints = DerApprox, CoefMat = T)[1], Derv(npoints = DerApprox, CoefMat = T)[1]), byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(0, -sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
bOx = (-Ox[i1,(2:(Par$j-1))]/(al1*Par$dtn))
bRed = (-Red[i1,(2:(Par$j-1))]/(al1*Par$dtn))
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*1
bRed[Par$j-2] = bRed[Par$j-2] - A2[Par$j-2]*Red[i1,Par$j]
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2[Par$j-2]*bRed[j1+1]/A1[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1[m-1]
vRed[m] = -vRed[m-1]/A1[m-1]
}
B = matrix(data = c(1,-exp(Par$p), Derv(npoints = DerApprox, CoefMat = T)[1] + sum(vox[2:DerApprox]*Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]), Derv(npoints = DerApprox, CoefMat = T)[1] + sum(vRed[2:DerApprox]*Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox])), byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(0, -sum(uox[2:DerApprox]*Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]) - sum(uRed[2:DerApprox]*Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] -Ox[i1+1,j1])/A1[j1]
Red[i1+1,j1+1] = (bRed[j1] -Red[i1+1,j1])/A1[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "CN") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 2/Par$dtn)/al1
a2 = al3/al1
a3 = (al2 + 2/Par$dtn)/al1
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c(1,-exp(Par$p),Derv(npoints = DerApprox, CoefMat = T)[1], Derv(npoints = DerApprox, CoefMat = T)[1]), byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(0, -sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
bOx = -a3*Ox[i1,(2:(Par$j-1))] - Ox[i1,(1:(Par$j-2))] - a2*Ox[i1,(3:Par$j)]
bRed = -a3*Red[i1,(2:(Par$j-1))]- Red[i1,(1:(Par$j-2))] - a2*Red[i1,(3:Par$j)]
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*1
bRed[Par$j-2] = bRed[Par$j-2] - A2[Par$j-2]*Red[i1,Par$j]
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2[Par$j-2]*bRed[j1+1]/A1[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1[m-1]
vRed[m] = -vRed[m-1]/A1[m-1]
}
B = matrix(data = c(1,-exp(Par$p), Derv(npoints = DerApprox, CoefMat = T)[1] + sum(vox[2:DerApprox]*Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]), Derv(npoints = DerApprox, CoefMat = T)[1] + sum(vRed[2:DerApprox]*Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox])), byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(0, -sum(uox[2:DerApprox]*Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]) - sum(uRed[2:DerApprox]*Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] -Ox[i1+1,j1])/A1[j1]
Red[i1+1,j1+1] = (bRed[j1] -Red[i1+1,j1])/A1[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "BDF") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1.5/Par$dtn)/al1
a2 = al3/al1
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c(1,-exp(Par$p),Derv(npoints = DerApprox, CoefMat = T)[1], Derv(npoints = DerApprox, CoefMat = T)[1]), byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(0, -sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
if (i1 == 1) {
bOx = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[1,2:(Par$j-1)]/(2*Par$dtn*al1)
bRed = -2*Red[i1,2:(Par$j-1)]/(Par$dtn*al1) + Red[1,2:(Par$j-1)]/(2*Par$dtn*al1)
} else {
bOx = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1)
bRed = -2*Red[i1,2:(Par$j-1)]/(Par$dtn*al1) + Red[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1)
}
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*1
bRed[Par$j-2] = bRed[Par$j-2] - A2[Par$j-2]*Red[i1,Par$j]
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2[Par$j-2]*bRed[j1+1]/A1[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1[m-1]
vRed[m] = -vRed[m-1]/A1[m-1]
}
B = matrix(data = c(1,-exp(Par$p), Derv(npoints = DerApprox, CoefMat = T)[1] + sum(vox[2:DerApprox]*Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]), Derv(npoints = DerApprox, CoefMat = T)[1] + sum(vRed[2:DerApprox]*Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox])), byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(0, -sum(uox[2:DerApprox]*Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]) - sum(uRed[2:DerApprox]*Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] -Ox[i1+1,j1])/A1[j1]
Red[i1+1,j1+1] = (bRed[j1] -Red[i1+1,j1])/A1[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (!(Method %in% c("Euler", "BI", "RK4", "CN", "BDF"))) {
return("Available methods are Euler, BI, RK4, CN and BDF")
}
G = Jox
i = (n*Par$FA*G*Dx*Area*Co)/(sqrt(Dx*Par$tau))
graphy = ggplot(data = data.frame(i[1:(length(i)-1)],Par$t[1:(length(i)-1)]),
aes(y = i[1:(length(i)-1)], x = Par$t[1:(length(i)-1)])) +
geom_point() + xlab("t / s") +
ylab("I / A") + theme_classic()
if (errCheck == TRUE){
return(list(G,Dx,Co,Par$dtn,Par$h,Par$l,Par$j,i,n,Area))
} else {
return(graphy)
}
}
CottrCheck = function(Elefun) {
FA = 96485
R = 8.3145
Check = Elefun
if (length(Check) == 9){
return("ErrCheck inside the called function should be activated")
} else {
vt = c(1:Check[[6]])
if (length(Check) == 10){
Gcot = 1/sqrt(3.14*Check[[4]]*vt)
} else if (length(Check) == 12){
Gcot = (1/sqrt(3.14*Check[[4]]*vt))/(1+ (1/Check[[12]])*exp(Check[[11]]))
}
Err = (Check[[1]]/Gcot)
t = Check[[4]]*vt
ErrorGraphy = ggplot(data = data.frame(Err[1:(length(Err)-1)],t[1:(length(Err)-1)]), aes(y = Err[1:(length(Err)-1)], x = t[1:(length(Err)-1)])) + geom_point() +xlab("Time(s)") +
ylab("G/Gcott") + theme_classic()
return(ErrorGraphy)
}
}
LinSwp = function(Co = 0.001, Dx = 0.00001, Eo = 0, Dm = 0.45,
Vi = 0.3, Vf = -0.3, Vs = 0.001, ko = 0.01,
alpha = 0.5, Temp = 298.15, n = 1, Area = 1, l = 100,
DerApprox = 2, errCheck = FALSE, Method = "Euler"){
Par = ParCall("LinSwp", n. = n, Temp. = Temp, Dx1. = Dx,
Eo1. = Eo, Dm. = Dm, Vi. = Vi,
Vf. = Vf, Vs. = Vs, ko1. = ko, alpha1. = alpha, l. = l)
Ox = OneMat(Par$l+1, Par$j)
Red =ZeroMat(Par$l+1, Par$j)
Jox = ZeroMat(Par$l+1, 1)
if (Method == "Euler") {
for (i1 in 1:Par$l) {
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]), -sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
Ox[i1+1,j1] = Ox[i1,j1] + Dm*(Ox[i1, j1-1] - 2*Ox[i1, j1] + Ox[i1, j1+1])
Red[i1+1, j1] = Red[i1, j1] + Dm*(Red[i1, j1-1] + Red[i1, j1+1] - 2*Red[i1,j1])
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "RK4") {
for (i1 in 1:(Par$l-1)) {
k1 = ZeroMat(Par$j)
k2 = ZeroMat(Par$j)
k3 = ZeroMat(Par$j)
k4 = ZeroMat(Par$j)
k1red = ZeroMat(Par$j)
k2red = ZeroMat(Par$j)
k3red = ZeroMat(Par$j)
k4red = ZeroMat(Par$j)
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k1[j1] = Dm*(Ox[i1, j1 -1] - 2*Ox[i1, j1] + Ox[i1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k1[j1]*0.5
k1red[j1] = Dm*(Red[i1, j1 -1] - 2*Red[i1, j1] + Red[i1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + k1red[j1]*0.5
}
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k2[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k2[j1]*0.5
k2red[j1] = Dm*(Red[i1 + 1, j1 -1] - 2*Red[i1 + 1, j1] + Red[i1 + 1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + k2red[j1]*0.5
}
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k3[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k3[j1]
k3red[j1] = Dm*(Red[i1 + 1, j1 -1] - 2*Red[i1 + 1, j1] + Red[i1 + 1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + k3red[j1]
}
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k4[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + (k1[j1] + 2*k2[j1] + 2*k3[j1] + k4[j1])/6
k4red[j1] = Dm*(Red[i1 + 1, j1 -1] - 2*Red[i1 + 1, j1] + Red[i1 + 1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + (k1red[j1] + 2*k2red[j1] + 2*k3red[j1] + k4red[j1])/6
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "BI") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1/Par$dtn)/al1
a2 = al3/al1
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
bOx = (-Ox[i1,(2:(Par$j-1))]/(al1*Par$dtn))
bRed = (-Red[i1,(2:(Par$j-1))]/(al1*Par$dtn))
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*1
bRed[Par$j-2] = bRed[Par$j-2] - A2[Par$j-2]*Red[i1,Par$j]
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2[Par$j-2]*bRed[j1+1]/A1[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1[m-1]
vRed[m] = -vRed[m-1]/A1[m-1]
}
B = matrix(data = c((Par$Kf[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))),
-Par$Kb[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] -Ox[i1+1,j1])/A1[j1]
Red[i1+1,j1+1] = (bRed[j1] -Red[i1+1,j1])/A1[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "CN") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 2/Par$dtn)/al1
a2 = al3/al1
a3 = (al2 + 2/Par$dtn)/al1
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
bOx = -a3*Ox[i1,(2:(Par$j-1))] - Ox[i1,(1:(Par$j-2))] - a2*Ox[i1,(3:Par$j)]
bRed = -a3*Red[i1,(2:(Par$j-1))]- Red[i1,(1:(Par$j-2))] - a2*Red[i1,(3:Par$j)]
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*1
bRed[Par$j-2] = bRed[Par$j-2] - A2[Par$j-2]*Red[i1,Par$j]
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2[Par$j-2]*bRed[j1+1]/A1[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1[m-1]
vRed[m] = -vRed[m-1]/A1[m-1]
}
B = matrix(data = c((Par$Kf[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))),
-Par$Kb[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] -Ox[i1+1,j1])/A1[j1]
Red[i1+1,j1+1] = (bRed[j1] -Red[i1+1,j1])/A1[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "BDF") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1.5/Par$dtn)/al1
a2 = al3/al1
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
if (i1 == 1) {
bOx = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[1,2:(Par$j-1)]/(2*Par$dtn*al1)
bRed = -2*Red[i1,2:(Par$j-1)]/(Par$dtn*al1) + Red[1,2:(Par$j-1)]/(2*Par$dtn*al1)
} else {
bOx = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1)
bRed = -2*Red[i1,2:(Par$j-1)]/(Par$dtn*al1) + Red[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1)
}
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*1
bRed[Par$j-2] = bRed[Par$j-2] - A2[Par$j-2]*Red[i1,Par$j]
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2[Par$j-2]*bRed[j1+1]/A1[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1[m-1]
vRed[m] = -vRed[m-1]/A1[m-1]
}
B = matrix(data = c((Par$Kf[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))),
-Par$Kb[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] -Ox[i1+1,j1])/A1[j1]
Red[i1+1,j1+1] = (bRed[j1] -Red[i1+1,j1])/A1[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (!(Method %in% c("Euler", "BI", "RK4", "CN", "BDF"))) {
return("Available methods are Euler, BI, RK4, CN and BDF")
}
G = Jox
i = (n*Par$FA*G*Dx*Area*Co)/(sqrt(Dx*Par$tau))
graphy = ggplot(data = data.frame(i[1:(length(i)-1)], Par$PotentialScan[1:(length(i)-1)]), aes(y = i[1:(length(i)-1)], x = Par$PotentialScan[1:(length(i)-1)])) +
geom_point() + scale_x_continuous(trans = "reverse") +
xlab("E / V") +
ylab("I / A") +
theme_classic()
if (errCheck == TRUE){
return(list(G,Dx,Co,Par$dtn,Par$h,Par$l,Par$j,i,n,Area,Par$p,Par$Da))
} else {
return(graphy)
}
}
CV = function(Co = 0.001, Dx = 0.00001, Eo = 0, Dm = 0.45,
Vi = 0.3, Vf = -0.3, Vs = 0.001, ko = 0.01,
alpha = 0.5, Temp = 298.15, n = 1, Area = 1, l = 100,
DerApprox = 2, errCheck = FALSE, Method = "Euler"){
Par = ParCall("CV", n. = n, Temp. = Temp, Dx1. = Dx,
Eo1. = Eo, Dm. = Dm, Vi. = Vi,
Vf. = Vf, Vs. = Vs, ko1. = ko, alpha1. = alpha, l. = l)
Ox = OneMat(Par$l +1, Par$j)
Red =ZeroMat(Par$l +1, Par$j)
Jox = ZeroMat(Par$l+1, 1)
if (Method == "Euler") {
for (i1 in 1:Par$l) {
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]), -sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
Ox[i1+1,j1] = Ox[i1,j1] + Dm*(Ox[i1, j1-1] - 2*Ox[i1, j1] + Ox[i1, j1+1])
Red[i1+1, j1] = Red[i1, j1] + Dm*(Red[i1, j1-1] + Red[i1, j1+1] - 2*Red[i1,j1])
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "RK4") {
for (i1 in 1:(Par$l-1)) {
k1 = ZeroMat(Par$j)
k2 = ZeroMat(Par$j)
k3 = ZeroMat(Par$j)
k4 = ZeroMat(Par$j)
k1red = ZeroMat(Par$j)
k2red = ZeroMat(Par$j)
k3red = ZeroMat(Par$j)
k4red = ZeroMat(Par$j)
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k1[j1] = Dm*(Ox[i1, j1 -1] - 2*Ox[i1, j1] + Ox[i1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k1[j1]*0.5
k1red[j1] = Dm*(Red[i1, j1 -1] - 2*Red[i1, j1] + Red[i1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + k1red[j1]*0.5
}
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k2[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k2[j1]*0.5
k2red[j1] = Dm*(Red[i1 + 1, j1 -1] - 2*Red[i1 + 1, j1] + Red[i1 + 1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + k2red[j1]*0.5
}
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k3[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k3[j1]
k3red[j1] = Dm*(Red[i1 + 1, j1 -1] - 2*Red[i1 + 1, j1] + Red[i1 + 1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + k3red[j1]
}
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k4[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + (k1[j1] + 2*k2[j1] + 2*k3[j1] + k4[j1])/6
k4red[j1] = Dm*(Red[i1 + 1, j1 -1] - 2*Red[i1 + 1, j1] + Red[i1 + 1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + (k1red[j1] + 2*k2red[j1] + 2*k3red[j1] + k4red[j1])/6
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "BI") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1/Par$dtn)/al1
a2 = al3/al1
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
bOx = (-Ox[i1,(2:(Par$j-1))]/(al1*Par$dtn))
bRed = (-Red[i1,(2:(Par$j-1))]/(al1*Par$dtn))
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*1
bRed[Par$j-2] = bRed[Par$j-2] - A2[Par$j-2]*Red[i1,Par$j]
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2[Par$j-2]*bRed[j1+1]/A1[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1[m-1]
vRed[m] = -vRed[m-1]/A1[m-1]
}
B = matrix(data = c((Par$Kf[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))),
-Par$Kb[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] -Ox[i1+1,j1])/A1[j1]
Red[i1+1,j1+1] = (bRed[j1] -Red[i1+1,j1])/A1[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "CN") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 2/Par$dtn)/al1
a2 = al3/al1
a3 = (al2 + 2/Par$dtn)/al1
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
bOx = -a3*Ox[i1,(2:(Par$j-1))] - Ox[i1,(1:(Par$j-2))] - a2*Ox[i1,(3:Par$j)]
bRed = -a3*Red[i1,(2:(Par$j-1))]- Red[i1,(1:(Par$j-2))] - a2*Red[i1,(3:Par$j)]
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*1
bRed[Par$j-2] = bRed[Par$j-2] - A2[Par$j-2]*Red[i1,Par$j]
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2[Par$j-2]*bRed[j1+1]/A1[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1[m-1]
vRed[m] = -vRed[m-1]/A1[m-1]
}
B = matrix(data = c((Par$Kf[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))),
-Par$Kb[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] -Ox[i1+1,j1])/A1[j1]
Red[i1+1,j1+1] = (bRed[j1] -Red[i1+1,j1])/A1[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "BDF") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1.5/Par$dtn)/al1
a2 = al3/al1
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
if (i1 == 1) {
bOx = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[1,2:(Par$j-1)]/(2*Par$dtn*al1)
bRed = -2*Red[i1,2:(Par$j-1)]/(Par$dtn*al1) + Red[1,2:(Par$j-1)]/(2*Par$dtn*al1)
} else {
bOx = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1)
bRed = -2*Red[i1,2:(Par$j-1)]/(Par$dtn*al1) + Red[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1)
}
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*1
bRed[Par$j-2] = bRed[Par$j-2] - A2[Par$j-2]*Red[i1,Par$j]
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2[Par$j-2]*bRed[j1+1]/A1[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1[m-1]
vRed[m] = -vRed[m-1]/A1[m-1]
}
B = matrix(data = c((Par$Kf[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))),
-Par$Kb[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] -Ox[i1+1,j1])/A1[j1]
Red[i1+1,j1+1] = (bRed[j1] -Red[i1+1,j1])/A1[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (!(Method %in% c("Euler", "BI", "RK4", "CN", "BDF"))) {
return("Available methods are Euler, BI, RK4, CN and BDF")
}
G = Jox
i = (n*Par$FA*G*Dx*Area*Co)/(sqrt(Dx*Par$tau))
graphy = ggplot(data = data.frame(i[1:(length(i)-1)], Par$PotentialScan[1:(length(i)-1)]),
aes(y = i[1:(length(i)-1)], x = Par$PotentialScan[1:(length(i)-1)])) +
geom_point() + scale_x_continuous(trans = "reverse") +
xlab("E / V") +
ylab("I / A") +
theme_classic()
if (errCheck == TRUE){
return(list(G,Dx,Co,Par$dtn,Par$h,Par$l,Par$j,i,n,Area,Par$p,Par$Da))
} else {
return(graphy)
}
}
CVEC = function(Co = 0.001, Dx = 0.00001, Eo = 0, Dm = 0.45,
Vi = 0.3, Vf = -0.3, Vs = 0.001, ko = 0.01,
kc = 0.001, l = 100,
alpha = 0.5, Temp = 298.15, n = 1, Area = 1,
DerApprox = 2, errCheck = FALSE, Method = "Euler"){
Par = ParCall("CVEC", n. = n, Temp. = Temp, Dx1. = Dx,
Eo1. = Eo, Dm. = Dm, Vi. = Vi, kc. = kc,
Vf. = Vf, Vs. = Vs, ko1. = ko, alpha1. = alpha, l. = l)
Ox = OneMat(Par$l +1, Par$j)
Red =ZeroMat(Par$l +1, Par$j)
Jox = ZeroMat(Par$l+1, 1)
if (Method == "Euler") {
for (i1 in 1:Par$l) {
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]), -sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2] - Par$KC*Red[i1,1]
for (j1 in 2:(Par$j-1)) {
Ox[i1+1,j1] = Ox[i1,j1] + Dm*(Ox[i1, j1-1] - 2*Ox[i1, j1] + Ox[i1, j1+1])
Red[i1+1, j1] = Red[i1, j1] + Dm*(Red[i1, j1-1] + Red[i1, j1+1] - 2*Red[i1,j1]) - Par$KC*Par$dtn*Red[i1,j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "RK4") {
for (i1 in 1:(Par$l-1)) {
k1 = ZeroMat(Par$j)
k2 = ZeroMat(Par$j)
k3 = ZeroMat(Par$j)
k4 = ZeroMat(Par$j)
k1red = ZeroMat(Par$j)
k2red = ZeroMat(Par$j)
k3red = ZeroMat(Par$j)
k4red = ZeroMat(Par$j)
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k1[j1] = Dm*(Ox[i1, j1 -1] - 2*Ox[i1, j1] + Ox[i1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k1[j1]*0.5
k1red[j1] = Dm*(Red[i1, j1 -1] - 2*Red[i1, j1] + Red[i1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + k1red[j1]*0.5
}
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k2[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k2[j1]*0.5
k2red[j1] = Dm*(Red[i1 + 1, j1 -1] - 2*Red[i1 + 1, j1] + Red[i1 + 1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + k2red[j1]*0.5
}
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 2:(Par$j-1)) {
k3[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k3[j1]
k3red[j1] = Dm*(Red[i1 + 1, j1 -1] - 2*Red[i1 + 1, j1] + Red[i1 + 1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + k3red[j1]
}
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2] - Par$KC*Red[i1+1,1]
for (j1 in 2:(Par$j-1)) {
k4[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + (k1[j1] + 2*k2[j1] + 2*k3[j1] + k4[j1])/6
k4red[j1] = Dm*(Red[i1 + 1, j1 -1] - 2*Red[i1 + 1, j1] + Red[i1 + 1, j1+1])
Red[i1 + 1,j1] = Red[i1,j1] + (k1red[j1] + 2*k2red[j1] + 2*k3red[j1] + k4red[j1])/6 - Par$KC*Par$dtn*Red[i1+1,j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "BI") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1/Par$dtn)/al1
a2 = al3/al1
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2] - Par$KC*Red[i1,1]
bOx = (-Ox[i1,(2:(Par$j-1))]/(al1*Par$dtn))
bRed = (-Red[i1,(2:(Par$j-1))]/(al1*Par$dtn)) + Par$KC*Red[i1,2:(Par$j-1)]/al1
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*1
bRed[Par$j-2] = bRed[Par$j-2] - A2[Par$j-2]*(Red[i1,Par$j] - Par$KC*Red[i1,Par$j])
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2[Par$j-2]*bRed[j1+1]/A1[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1[m-1]
vRed[m] = -vRed[m-1]/A1[m-1]
}
B = matrix(data = c((Par$Kf[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))),
-Par$Kb[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] - Ox[i1+1,j1])/A1[j1]
Red[i1+1,j1+1] = (bRed[j1] - Red[i1+1,j1])/A1[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "CN") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 2/Par$dtn)/al1
a2 = al3/al1
a3 = (al2 + 2/Par$dtn)/al1
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2] - Par$KC*Red[i1,1]
bOx = -a3*Ox[i1,(2:(Par$j-1))] - Ox[i1,(1:(Par$j-2))] - a2*Ox[i1,(3:Par$j)]
bRed = -a3*Red[i1,(2:(Par$j-1))]- Red[i1,(1:(Par$j-2))] - a2*Red[i1,(3:Par$j)] + Par$KC*Red[i1,2:(Par$j-1)]/al1
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*Ox[i1,Par$j]
bRed[Par$j-2] = bRed[Par$j-2] - A2[Par$j-2]*(Red[i1,Par$j] - Par$KC*Red[i1,Par$j])
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2[Par$j-2]*bRed[j1+1]/A1[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1[m-1]
vRed[m] = -vRed[m-1]/A1[m-1]
}
B = matrix(data = c((Par$Kf[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))),
-Par$Kb[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] -Ox[i1+1,j1])/A1[j1]
Red[i1+1,j1+1] = (bRed[j1] -Red[i1+1,j1])/A1[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (Method == "BDF") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1.5/Par$dtn)/al1
a2 = al3/al1
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red[i1,1] = C[2] - Par$KC*Red[i1,1]
if (i1 == 1) {
bOx = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[1,2:(Par$j-1)]/(2*Par$dtn*al1)
bRed = -2*Red[i1,2:(Par$j-1)]/(Par$dtn*al1) + Red[1,2:(Par$j-1)]/(2*Par$dtn*al1) + Par$KC*Red[i1,2:(Par$j-1)]/al1
} else {
bOx = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1)
bRed = -2*Red[i1,2:(Par$j-1)]/(Par$dtn*al1) + Red[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1) + Par$KC*Red[i1,2:(Par$j-1)]/al1
}
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*Ox[i1,Par$j]
bRed[Par$j-2] = bRed[Par$j-2] - A2[Par$j-2]*(Red[i1,Par$j] - Par$KC*Red[i1,Par$j])
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2[Par$j-2]*bRed[j1+1]/A1[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1[m-1]
vRed[m] = -vRed[m-1]/A1[m-1]
}
B = matrix(data = c((Par$Kf[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))),
-Par$Kb[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 2, ncol = 2)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red[i1+1,1] = C[2]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] -Ox[i1+1,j1])/A1[j1]
Red[i1+1,j1+1] = (bRed[j1] -Red[i1+1,j1])/A1[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
} else if (!(Method %in% c("Euler", "BI", "RK4", "CN", "BDF"))) {
return("Available methods are Euler, BI, RK4, CN and BDF")
}
G = Jox
i = (n*Par$FA*G*Dx*Area*Co)/(sqrt(Dx*Par$tau))
graphy = ggplot(data = data.frame(i[1:(length(i)-1)], Par$PotentialScan[1:(length(i)-1)]),
aes(y = i[1:(length(i)-1)], x = Par$PotentialScan[1:(length(i)-1)])) +
geom_point() + scale_x_continuous(trans = "reverse") +
xlab("E / V") +
ylab("I / A") +
theme_classic()
if (errCheck == TRUE){
return(list(G,Dx,Co,Par$dtn,Par$h,Par$l,Par$j,i,n,Area,Par$p,Par$Da))
} else {
return(graphy)
}
}
CVEE = function(Co = 0.001, Dx1 = 0.00001, Eo1 = 0,
Vi = 0.3, Vf = -0.3, Vs = 0.001, ko1 = 0.01,
alpha1 = 0.5, Dred = 0.00001, Dred2 = 0.00001, Eo2 = 0,
ko2 = 0.01, alpha2 = 0.5, Dm = 0.45, l = 100,
Temp = 298.15, n = 1, Area = 1,
DerApprox = 2, errCheck = FALSE, Method = "Euler") {
Par = ParCall("CVEE", n. = n, Temp. = Temp, Dx1. = Dx1, Dred1. = Dred,
Eo1. = Eo1, Eo2. = Eo2, Dm. = Dm, Vi. = Vi,
Vf. = Vf, Vs. = Vs, ko1. = ko1, ko2. = ko2,
alpha1. = alpha1, alpha2. = alpha2, Dred2. = Dred2, l. = l)
Ox = OneMat(Par$l +1, Par$j)
Red1 = ZeroMat(Par$l +1, Par$j)
Jox = ZeroMat(Par$l+1, 1)
Red2 = ZeroMat(Par$l +1, Par$j)
Jred1 = ZeroMat(Par$l+1, 1)
if (Method == "Euler") {
for (i1 in 1:Par$l) {
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb1[i1]*Par$h, 0, -Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 3, ncol = 3)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red1[i1,1] = C[2]
Red2[i1,1] = C[3]
for (j1 in 2:(Par$j-1)) {
Ox[i1+1,j1] = Ox[i1,j1] + Dm*(Ox[i1, j1-1] - 2*Ox[i1, j1] + Ox[i1, j1+1])
Red1[i1+1, j1] = Red1[i1, j1] + Par$DRED*Dm*(Red1[i1, j1-1] + Red1[i1, j1+1] - 2*Red1[i1,j1])
Red2[i1+1, j1] = Red2[i1, j1] + Par$DRED2*Dm*(Red2[i1, j1-1] + Red2[i1, j1+1] - 2*Red2[i1,j1])
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
Jred1 = Derv(Ox = Red1, h = Par$h, npoints = DerApprox)
} else if (Method == "RK4") {
for (i1 in 1:(Par$l-1)) {
k1 = ZeroMat(Par$j)
k2 = ZeroMat(Par$j)
k3 = ZeroMat(Par$j)
k4 = ZeroMat(Par$j)
k1red = ZeroMat(Par$j)
k2red = ZeroMat(Par$j)
k3red = ZeroMat(Par$j)
k4red = ZeroMat(Par$j)
k1red2 = ZeroMat(Par$j)
k2red2 = ZeroMat(Par$j)
k3red2 = ZeroMat(Par$j)
k4red2 = ZeroMat(Par$j)
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb1[i1]*Par$h, 0, -Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 3, ncol = 3)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red1[i1,1] = C[2]
Red2[i1,1] = C[3]
for (j1 in 2:(Par$j-1)) {
k1[j1] = Dm*(Ox[i1, j1 -1] - 2*Ox[i1, j1] + Ox[i1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k1[j1]*0.5
k1red[j1] = Par$DRED*Dm*(Red1[i1, j1 -1] - 2*Red1[i1, j1] + Red1[i1, j1+1])
Red1[i1 + 1,j1] = Red1[i1,j1] + k1red[j1]*0.5
k1red2[j1] = Par$DRED*Dm*(Red2[i1, j1 -1] - 2*Red2[i1, j1] + Red2[i1, j1+1])
Red2[i1 + 1,j1] = Red2[i1,j1] + k1red2[j1]*0.5
}
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb1[i1]*Par$h, 0, -Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 3, ncol = 3)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1+1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red1[i1+1,1] = C[2]
Red2[i1+1,1] = C[3]
for (j1 in 2:(Par$j-1)) {
k2[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k2[j1]*0.5
k2red[j1] = Par$DRED*Dm*(Red1[i1+1, j1 -1] - 2*Red1[i1+1, j1] + Red1[i1+1, j1+1])
Red1[i1 + 1,j1] = Red1[i1,j1] + k2red[j1]*0.5
k2red2[j1] = Par$DRED*Dm*(Red2[i1+1, j1 -1] - 2*Red2[i1+1, j1] + Red2[i1+1, j1+1])
Red2[i1 + 1,j1] = Red2[i1,j1] + k2red2[j1]*0.5
}
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb1[i1]*Par$h, 0, -Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 3, ncol = 3)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1+1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red1[i1+1,1] = C[2]
Red2[i1+1,1] = C[3]
for (j1 in 2:(Par$j-1)) {
k3[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k3[j1]
k3red[j1] = Par$DRED*Dm*(Red1[i1 + 1, j1 -1] - 2*Red1[i1 + 1, j1] + Red1[i1 + 1, j1+1])
Red1[i1 + 1,j1] = Red1[i1,j1] + k3red[j1]
k3red2[j1] = Par$DRED*Dm*(Red2[i1 + 1, j1 -1] - 2*Red2[i1 + 1, j1] + Red2[i1 + 1, j1+1])
Red2[i1 + 1,j1] = Red2[i1,j1] + k3red2[j1]
}
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb1[i1]*Par$h, 0, -Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 3, ncol = 3)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1+1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red1[i1+1,1] = C[2]
Red2[i1+1,1] = C[3]
for (j1 in 2:(Par$j-1)) {
k4[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + (k1[j1] + 2*k2[j1] + 2*k3[j1] + k4[j1])/6
k4red[j1] = Par$DRED*Dm*(Red1[i1 + 1, j1 -1] - 2*Red1[i1 + 1, j1] + Red1[i1 + 1, j1+1])
Red1[i1 + 1,j1] = Red1[i1,j1] + (k1red[j1] + 2*k2red[j1] + 2*k3red[j1] + k4red[j1])/6
k4red2[j1] = Par$DRED*Dm*(Red2[i1 + 1, j1 -1] - 2*Red2[i1 + 1, j1] + Red2[i1 + 1, j1+1])
Red2[i1 + 1,j1] = Red2[i1,j1] + (k1red2[j1] + 2*k2red2[j1] + 2*k3red2[j1] + k4red2[j1])/6
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
Jred1 = Derv(Ox = Red1, h = Par$h, npoints = DerApprox)
} else if (Method == "BI") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1/Par$dtn)/al1
a2 = al3/al1
al1red = Par$DRED/(Par$h^2)
al2red = -(2*Par$DRED)/(Par$h^2)
al3red = Par$DRED/(Par$h^2)
a1red = (al2red - 1/Par$dtn)/al1red
a2red = al3red/al1red
al1red2 = Par$DRED2/(Par$h^2)
al2red2 = -(2*Par$DRED2)/(Par$h^2)
al3red2 = Par$DRED2/(Par$h^2)
a1red2 = (al2red2 - 1/Par$dtn)/al1red2
a2red2 = al3red2/al1red2
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb1[i1]*Par$h, 0, -Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 3, ncol = 3)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red1[i1,1] = C[2]
Red2[i1,1] = C[3]
bOx = (-Ox[i1,(2:(Par$j-1))]/(al1*Par$dtn))
bRed = (-Red1[i1,(2:(Par$j-1))]/(al1red*Par$dtn))
bRed2 = (-Red2[i1,(2:(Par$j-1))]/(al1red2*Par$dtn))
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
A1red = c(rep(a1red,Par$j-2))
A2red = c(rep(a2red,Par$j-2))
A1red2 = c(rep(a1red2,Par$j-2))
A2red2 = c(rep(a2red2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*1
bRed[Par$j-2] = bRed[Par$j-2] - A2red[Par$j-2]*Red1[i1,Par$j]
bRed2[Par$j-2] = bRed2[Par$j-2] - A2red2[Par$j-2]*Red2[i1,Par$j]
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
uRed2 = c(rep(0, DerApprox))
vRed2 = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2red[Par$j-2]*bRed[j1+1]/A1red[j1+1]
bRed2[j1] = bRed2[j1] - A2red2[Par$j-2]*bRed2[j1+1]/A1red2[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
A1red[j1] = A1red[j1] - A2red[Par$j-2]/A1red[j1+1]
A1red2[j1] = A1red2[j1] - A2red2[Par$j-2]/A1red2[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1red[m-1]
vRed[m] = -vRed[m-1]/A1red[m-1]
uRed2[m] = (bRed2[m-1] - uRed2[m-1])/A1red2[m-1]
vRed2[m] = -vRed2[m-1]/A1red2[m-1]
}
B = matrix(data = c((Par$Kf1[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))),
-Par$Kb1[i1]*Par$h, 0, -Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - sum(vRed*Derv(npoints = DerApprox, CoefMat = T)), -Par$Kb2[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed2*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 3, ncol = 3)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)), sum(uRed*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed2*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red1[i1+1,1] = C[2]
Red2[i1+1,1] = C[3]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] - Ox[i1+1,j1])/A1[j1]
Red1[i1+1,j1+1] = (bRed[j1] - Red1[i1+1,j1])/A1red[j1]
Red2[i1+1,j1+1] = (bRed2[j1] - Red2[i1+1,j1])/A1red2[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
Jred1 = Derv(Ox = Red1, h = Par$h, npoints = DerApprox)
} else if (Method == "CN") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 2/Par$dtn)/al1
a2 = al3/al1
a3 = (al2 + 2/Par$dtn)/al1
al1red = Par$DRED/(Par$h^2)
al2red = -(2*Par$DRED)/(Par$h^2)
al3red = Par$DRED/(Par$h^2)
a1red = (al2red - 2/Par$dtn)/al1red
a2red = al3red/al1red
a3red = (al2red + 2/Par$dtn)/al1red
al1red2 = Par$DRED2/(Par$h^2)
al2red2 = -(2*Par$DRED2)/(Par$h^2)
al3red2 = Par$DRED2/(Par$h^2)
a1red2 = (al2red2 - 2/Par$dtn)/al1red2
a2red2 = al3red2/al1red2
a3red2 = (al2red2 + 2/Par$dtn)/al1red2
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb1[i1]*Par$h, 0, -Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 3, ncol = 3)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red1[i1,1] = C[2]
Red2[i1,1] = C[3]
bOx = -a3*Ox[i1,(2:(Par$j-1))] - Ox[i1,(1:(Par$j-2))] - a2*Ox[i1,(3:Par$j)]
bRed = -a3red*Red1[i1,(2:(Par$j-1))]- Red1[i1,(1:(Par$j-2))] - a2red*Red1[i1,(3:Par$j)]
bRed2 = -a3red2*Red2[i1,(2:(Par$j-1))]- Red2[i1,(1:(Par$j-2))] - a2red2*Red2[i1,(3:Par$j)]
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
A1red = c(rep(a1red,Par$j-2))
A2red = c(rep(a2red,Par$j-2))
A1red2 = c(rep(a1red2,Par$j-2))
A2red2 = c(rep(a2red2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*1
bRed[Par$j-2] = bRed[Par$j-2] - A2red[Par$j-2]*Red1[i1,Par$j]
bRed2[Par$j-2] = bRed2[Par$j-2] - A2red2[Par$j-2]*Red2[i1,Par$j]
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
uRed2 = c(rep(0, DerApprox))
vRed2 = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2red[Par$j-2]*bRed[j1+1]/A1red[j1+1]
bRed2[j1] = bRed2[j1] - A2red2[Par$j-2]*bRed2[j1+1]/A1red2[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
A1red[j1] = A1red[j1] - A2red[Par$j-2]/A1red[j1+1]
A1red2[j1] = A1red2[j1] - A2red2[Par$j-2]/A1red2[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1red[m-1]
vRed[m] = -vRed[m-1]/A1red[m-1]
uRed2[m] = (bRed2[m-1] - uRed2[m-1])/A1red2[m-1]
vRed2[m] = -vRed2[m-1]/A1red2[m-1]
}
B = matrix(data = c((Par$Kf1[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))),
-Par$Kb1[i1]*Par$h, 0, -Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - sum(vRed*Derv(npoints = DerApprox, CoefMat = T)), -Par$Kb2[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed2*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 3, ncol = 3)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)), sum(uRed*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed2*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red1[i1+1,1] = C[2]
Red2[i1+1,1] = C[3]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] - Ox[i1+1,j1])/A1[j1]
Red1[i1+1,j1+1] = (bRed[j1] - Red1[i1+1,j1])/A1red[j1]
Red2[i1+1,j1+1] = (bRed2[j1] - Red2[i1+1,j1])/A1red2[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
Jred1 = Derv(Ox = Red1, h = Par$h, npoints = DerApprox)
} else if (Method == "BDF") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1.5/Par$dtn)/al1
a2 = al3/al1
al1red = Par$DRED/(Par$h^2)
al2red = -(2*Par$DRED)/(Par$h^2)
al3red = Par$DRED/(Par$h^2)
a1red = (al2red - 1.5/Par$dtn)/al1red
a2red = al3red/al1red
al1red2 = Par$DRED2/(Par$h^2)
al2red2 = -(2*Par$DRED2)/(Par$h^2)
al3red2 = Par$DRED2/(Par$h^2)
a1red2 = (al2red2 - 1.5/Par$dtn)/al1red2
a2red2 = al3red2/al1red2
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]),
-Par$Kb1[i1]*Par$h, 0, -Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 3, ncol = 3)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red1[i1,1] = C[2]
Red2[i1,1] = C[3]
if (i1 == 1) {
bOx = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[1,2:(Par$j-1)]/(2*Par$dtn*al1)
bRed = -2*Red1[i1,2:(Par$j-1)]/(Par$dtn*al1red) + Red1[1,2:(Par$j-1)]/(2*Par$dtn*al1red)
bRed2 = -2*Red2[i1,2:(Par$j-1)]/(Par$dtn*al1red2) + Red2[1,2:(Par$j-1)]/(2*Par$dtn*al1red2)
} else {
bOx = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1)
bRed = -2*Red1[i1,2:(Par$j-1)]/(Par$dtn*al1red) + Red1[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1red)
bRed2 = -2*Red2[i1,2:(Par$j-1)]/(Par$dtn*al1red2) + Red2[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1red2)
}
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
A1red = c(rep(a1red,Par$j-2))
A2red = c(rep(a2red,Par$j-2))
A1red2 = c(rep(a1red2,Par$j-2))
A2red2 = c(rep(a2red2,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*1
bRed[Par$j-2] = bRed[Par$j-2] - A2red[Par$j-2]*Red1[i1,Par$j]
bRed2[Par$j-2] = bRed2[Par$j-2] - A2red2[Par$j-2]*Red2[i1,Par$j]
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
uRed2 = c(rep(0, DerApprox))
vRed2 = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2red[Par$j-2]*bRed[j1+1]/A1red[j1+1]
bRed2[j1] = bRed2[j1] - A2red2[Par$j-2]*bRed2[j1+1]/A1red2[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
A1red[j1] = A1red[j1] - A2red[Par$j-2]/A1red[j1+1]
A1red2[j1] = A1red2[j1] - A2red2[Par$j-2]/A1red2[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1red[m-1]
vRed[m] = -vRed[m-1]/A1red[m-1]
uRed2[m] = (bRed2[m-1] - uRed2[m-1])/A1red2[m-1]
vRed2[m] = -vRed2[m-1]/A1red2[m-1]
}
B = matrix(data = c((Par$Kf1[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))),
-Par$Kb1[i1]*Par$h, 0, -Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - sum(vRed*Derv(npoints = DerApprox, CoefMat = T)), -Par$Kb2[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed2*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 3, ncol = 3)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)), sum(uRed*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed2*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red1[i1+1,1] = C[2]
Red2[i1+1,1] = C[3]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] - Ox[i1+1,j1])/A1[j1]
Red1[i1+1,j1+1] = (bRed[j1] - Red1[i1+1,j1])/A1red[j1]
Red2[i1+1,j1+1] = (bRed2[j1] - Red2[i1+1,j1])/A1red2[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
Jred1 = Derv(Ox = Red1, h = Par$h, npoints = DerApprox)
} else if (!(Method %in% c("Euler", "BI", "RK4", "CN", "BDF"))) {
return("Available methods are Euler, BI, RK4, CN and BDF")
}
G1 = Jox
G2 = Jox + Jred1
i = (n*Par$FA*(G1+G2)*Dx1*Area*Co)/(sqrt(Dx1*Par$tau))
graphy = ggplot(data = data.frame(i[1:(length(i)-1)],Par$PotentialScan[1:(length(i)-1)]),
aes(y = i[1:(length(i)-1)], x = Par$PotentialScan[1:(length(i)-1)])) +
geom_point() + scale_x_continuous(trans = "reverse") +
xlab("E / V") +
ylab("I / A") +
theme_classic()
if (errCheck == TRUE){
return(list((G1+G2),Dx1,Dred,Dred2,Co,Par$dtn,Par$h,i,Par$l,Par$j,n,Area,Par$DOx,Par$DRED,Par$DRED2,Par$p1,Par$p2))
} else {
return(graphy)
}
}
Gen_CV = function(Co = 0.001, Cred= 0, kco = 0, Dx1 = 0.00001, Eo1 = 0, kc1 = 0,
Vi = 0.3, Vf = -0.3, Vs = 0.001, ko1 = 0.01,
alpha1 = 0.5, Dred = 0.00001, Dred2 = 0.00001, Eo2 = 0, kc2 = 0,
ko2 = 0, alpha2 = 0.5, Dm = 0.45, Dred3 = 0.00001,
Eo3 = 0, kc3 = 0, ko3 = 0, alpha3 = 0.5, Dred4 = 0.00001,
Eo4 = 0, kc4 = 0, ko4 = 0, alpha4 = 0.5,
Temp = 298.15, n = 1, Area = 1, l = 100,
DerApprox = 2, errCheck = FALSE, Method = "Euler") {
if (kco > 0.001 | kc1 > 0.001 | kc2 > 0.001 | kc3 > 0.001 | kc4 > 0.001 ) {
warning("Chemical rate costant is too high, this will result in unstable simulation")
}
Par = ParCall("Gen_CV", n. = n, Temp. = Temp, Dx1. = Dx1, Dred1. = Dred,
Dred2. = Dred2, Dred3. = Dred3, Dred4. = Dred4,
Eo1. = Eo1, Eo2. = Eo2, Eo3. = Eo3, Eo4. = Eo4, Dm. = Dm,
Vi. = Vi, kco. = kco, kc1. = kc1, kc2. = kc2, kc3. = kc3, kc4. = kc4,
Vf. = Vf, Vs. = Vs, ko1. = ko1, ko2. = ko2, ko3. = ko3, ko4. = ko4,
alpha1. = alpha1, alpha2. = alpha2, alpha3. = alpha3, alpha4. = alpha4, l. = l)
Ox = OneMat(Par$l +1, Par$j)
if (Co == 0) {
Co = 0.0000001
}
Red1 = (Cred/Co)*OneMat(Par$l +1, Par$j)
Jox = ZeroMat(Par$l+1, 1)
Red2 = ZeroMat(Par$l +1, Par$j)
Jred1 = ZeroMat(Par$l+1, 1)
Red3 = ZeroMat(Par$l +1, Par$j)
Jred2 = ZeroMat(Par$l+1, 1)
Red4 = ZeroMat(Par$l +1, Par$j)
Jred3 = ZeroMat(Par$l+1, 1)
if (Method == "Euler") {
for (i1 in 1:Par$l) {
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]), -Par$Kb1[i1]*Par$h, 0, 0, 0,
-Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h, 0, 0,
0, -Par$Kf2[i1]*Par$h, Par$Kb2[i1]*Par$h + Par$Kf3[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb3[i1]*Par$h, 0,
0, 0, -Par$Kf3[i1]*Par$h, Par$Kb3[i1]*Par$h + Par$Kf4[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb4[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 5, ncol = 5)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]),
Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox]),
Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox]) - Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1,2:DerApprox]) - Par$DRED4*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red4[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1] - Par$KCo*Ox[i1,1]
Red1[i1,1] = C[2] - Par$KC1*Red1[i1,1]
Red2[i1,1] = C[3] - Par$KC2*Red2[i1,1]
Red3[i1,1] = C[4] - Par$KC3*Red3[i1,1]
Red4[i1,1] = C[5] - Par$KC4*Red4[i1,1]
for (j1 in 2:(Par$j-1)) {
Ox[i1+1,j1] = Ox[i1,j1] + Dm*(Ox[i1, j1-1] - 2*Ox[i1, j1] + Ox[i1, j1+1]) - Par$KCo*Par$dtn*Ox[i1,j1]
Red1[i1+1, j1] = Red1[i1, j1] + Par$DRED*Dm*(Red1[i1, j1-1] + Red1[i1, j1+1] - 2*Red1[i1,j1]) - Par$KC1*Par$dtn*Red1[i1,j1]
Red2[i1+1, j1] = Red2[i1, j1] + Par$DRED2*Dm*(Red2[i1, j1-1] + Red2[i1, j1+1] - 2*Red2[i1,j1]) - Par$KC2*Par$dtn*Red2[i1,j1]
Red3[i1+1, j1] = Red3[i1, j1] + Par$DRED3*Dm*(Red3[i1, j1-1] + Red3[i1, j1+1] - 2*Red3[i1,j1]) - Par$KC3*Par$dtn*Red3[i1,j1]
Red4[i1+1, j1] = Red4[i1, j1] + Par$DRED4*Dm*(Red4[i1, j1-1] + Red4[i1, j1+1] - 2*Red4[i1,j1]) - Par$KC4*Par$dtn*Red4[i1,j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
Jred1 = Derv(Ox = Red1, h = Par$h, npoints = DerApprox)
Jred2 = Derv(Ox = Red2, h = Par$h, npoints = DerApprox)
Jred3 = Derv(Ox = Red3, h = Par$h, npoints = DerApprox)
Jred4 = Derv(Ox = Red4, h = Par$h, npoints = DerApprox)
} else if (Method == "RK4") {
for (i1 in 1:(Par$l-1)) {
k1 = ZeroMat(Par$j)
k2 = ZeroMat(Par$j)
k3 = ZeroMat(Par$j)
k4 = ZeroMat(Par$j)
k1red1 = ZeroMat(Par$j)
k2red1 = ZeroMat(Par$j)
k3red1 = ZeroMat(Par$j)
k4red1 = ZeroMat(Par$j)
k1red2 = ZeroMat(Par$j)
k2red2 = ZeroMat(Par$j)
k3red2 = ZeroMat(Par$j)
k4red2 = ZeroMat(Par$j)
k1red3 = ZeroMat(Par$j)
k2red3 = ZeroMat(Par$j)
k3red3 = ZeroMat(Par$j)
k4red3 = ZeroMat(Par$j)
k1red4 = ZeroMat(Par$j)
k2red4 = ZeroMat(Par$j)
k3red4 = ZeroMat(Par$j)
k4red4 = ZeroMat(Par$j)
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]), -Par$Kb1[i1]*Par$h, 0, 0, 0,
-Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h, 0, 0,
0, -Par$Kf2[i1]*Par$h, Par$Kb2[i1]*Par$h + Par$Kf3[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb3[i1]*Par$h, 0,
0, 0, -Par$Kf3[i1]*Par$h, Par$Kb3[i1]*Par$h + Par$Kf4[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb4[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 5, ncol = 5)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]),
Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox]),
Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox]) - Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1,2:DerApprox]) - Par$DRED4*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red4[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1]
Red1[i1,1] = C[2]
Red2[i1,1] = C[3]
Red3[i1,1] = C[4]
Red4[i1,1] = C[5]
for (j1 in 2:(Par$j-1)) {
k1[j1] = Dm*(Ox[i1, j1 -1] - 2*Ox[i1, j1] + Ox[i1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k1[j1]*0.5
k1red1[j1] = Par$DRED*Dm*(Red1[i1, j1 -1] - 2*Red1[i1, j1] + Red1[i1, j1+1])
Red1[i1 + 1,j1] = Red1[i1,j1] + k1red1[j1]*0.5
k1red2[j1] = Par$DRED2*Dm*(Red2[i1, j1 -1] - 2*Red2[i1, j1] + Red2[i1, j1+1])
Red2[i1 + 1,j1] = Red2[i1,j1] + k1red2[j1]*0.5
k1red3[j1] = Par$DRED3*Dm*(Red3[i1, j1 -1] - 2*Red3[i1, j1] + Red3[i1, j1+1])
Red3[i1 + 1,j1] = Red3[i1,j1] + k1red3[j1]*0.5
k1red4[j1] = Par$DRED4*Dm*(Red4[i1, j1 -1] - 2*Red4[i1, j1] + Red4[i1, j1+1])
Red4[i1 + 1,j1] = Red4[i1,j1] + k1red4[j1]*0.5
}
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]), -Par$Kb1[i1]*Par$h, 0, 0, 0,
-Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h, 0, 0,
0, -Par$Kf2[i1]*Par$h, Par$Kb2[i1]*Par$h + Par$Kf3[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb3[i1]*Par$h, 0,
0, 0, -Par$Kf3[i1]*Par$h, Par$Kb3[i1]*Par$h + Par$Kf4[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb4[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 5, ncol = 5)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1+1,2:DerApprox]),
Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1+1,2:DerApprox]),
Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1+1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1+1,2:DerApprox]) - Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1+1,2:DerApprox]) - Par$DRED4*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red4[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red1[i1+1,1] = C[2]
Red2[i1+1,1] = C[3]
Red3[i1+1,1] = C[4]
Red4[i1+1,1] = C[5]
for (j1 in 2:(Par$j-1)) {
k2[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k2[j1]*0.5
k2red1[j1] = Par$DRED*Dm*(Red1[i1+1, j1 -1] - 2*Red1[i1+1, j1] + Red1[i1+1, j1+1])
Red1[i1 + 1,j1] = Red1[i1,j1] + k2red1[j1]*0.5
k2red2[j1] = Par$DRED2*Dm*(Red2[i1+1, j1 -1] - 2*Red2[i1+1, j1] + Red2[i1+1, j1+1])
Red2[i1 + 1,j1] = Red2[i1,j1] + k2red2[j1]*0.5
k2red3[j1] = Par$DRED3*Dm*(Red3[i1+1, j1 -1] - 2*Red3[i1+1, j1] + Red3[i1+1, j1+1])
Red3[i1 + 1,j1] = Red3[i1,j1] + k2red3[j1]*0.5
k2red4[j1] = Par$DRED4*Dm*(Red4[i1+1, j1 -1] - 2*Red4[i1+1, j1] + Red4[i1+1, j1+1])
Red4[i1 + 1,j1] = Red4[i1,j1] + k2red4[j1]*0.5
}
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]), -Par$Kb1[i1]*Par$h, 0, 0, 0,
-Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h, 0, 0,
0, -Par$Kf2[i1]*Par$h, Par$Kb2[i1]*Par$h + Par$Kf3[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb3[i1]*Par$h, 0,
0, 0, -Par$Kf3[i1]*Par$h, Par$Kb3[i1]*Par$h + Par$Kf4[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb4[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 5, ncol = 5)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1+1,2:DerApprox]),
Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1+1,2:DerApprox]),
Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1+1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1+1,2:DerApprox]) - Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1+1,2:DerApprox]) - Par$DRED4*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red4[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red1[i1+1,1] = C[2]
Red2[i1+1,1] = C[3]
Red3[i1+1,1] = C[4]
Red4[i1+1,1] = C[5]
for (j1 in 2:(Par$j-1)) {
k3[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + k3[j1]
k3red1[j1] = Par$DRED*Dm*(Red1[i1 + 1, j1 -1] - 2*Red1[i1 + 1, j1] + Red1[i1 + 1, j1+1])
Red1[i1 + 1,j1] = Red1[i1,j1] + k3red1[j1]
k3red2[j1] = Par$DRED2*Dm*(Red2[i1 + 1, j1 -1] - 2*Red2[i1 + 1, j1] + Red2[i1 + 1, j1+1])
Red2[i1 + 1,j1] = Red2[i1,j1] + k3red2[j1]
k3red3[j1] = Par$DRED3*Dm*(Red3[i1+1, j1 -1] - 2*Red3[i1+1, j1] + Red3[i1+1, j1+1])
Red3[i1 + 1,j1] = Red3[i1,j1] + k3red3[j1]
k3red4[j1] = Par$DRED4*Dm*(Red4[i1+1, j1 -1] - 2*Red4[i1+1, j1] + Red4[i1+1, j1+1])
Red4[i1 + 1,j1] = Red4[i1,j1] + k3red4[j1]
}
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]), -Par$Kb1[i1]*Par$h, 0, 0, 0,
-Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h, 0, 0,
0, -Par$Kf2[i1]*Par$h, Par$Kb2[i1]*Par$h + Par$Kf3[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb3[i1]*Par$h, 0,
0, 0, -Par$Kf3[i1]*Par$h, Par$Kb3[i1]*Par$h + Par$Kf4[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb4[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 5, ncol = 5)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1+1,2:DerApprox]),
Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1+1,2:DerApprox]),
Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1+1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1+1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1+1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1+1,2:DerApprox]) - Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1+1,2:DerApprox]) - Par$DRED4*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red4[i1+1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1] - Par$KCo*Ox[i1+1,1]
Red1[i1+1,1] = C[2] - Par$KC1*Red1[i1+1,1]
Red2[i1+1,1] = C[3] - Par$KC2*Red2[i1+1,1]
Red3[i1+1,1] = C[4] - Par$KC3*Red3[i1+1,1]
Red4[i1+1,1] = C[5] - Par$KC4*Red4[i1+1,1]
for (j1 in 2:(Par$j-1)) {
k4[j1] = Dm*(Ox[i1 + 1, j1 -1] - 2*Ox[i1 + 1, j1] + Ox[i1 + 1, j1+1])
Ox[i1 + 1,j1] = Ox[i1,j1] + (k1[j1] + 2*k2[j1] + 2*k3[j1] + k4[j1])/6 - Par$KCo*Par$dtn*Ox[i1+1,j1]
k4red1[j1] = Par$DRED*Dm*(Red1[i1 + 1, j1 -1] - 2*Red1[i1 + 1, j1] + Red1[i1 + 1, j1+1])
Red1[i1 + 1,j1] = Red1[i1,j1] + (k1red1[j1] + 2*k2red1[j1] + 2*k3red1[j1] + k4red1[j1])/6 - Par$KC1*Par$dtn*Red1[i1+1,j1]
k4red2[j1] = Par$DRED2*Dm*(Red2[i1 + 1, j1 -1] - 2*Red2[i1 + 1, j1] + Red2[i1 + 1, j1+1])
Red2[i1 + 1,j1] = Red2[i1,j1] + (k1red2[j1] + 2*k2red2[j1] + 2*k3red2[j1] + k4red2[j1])/6 - Par$KC2*Par$dtn*Red2[i1+1,j1]
k4red3[j1] = Par$DRED3*Dm*(Red3[i1 + 1, j1 -1] - 2*Red3[i1 + 1, j1] + Red3[i1 + 1, j1+1])
Red3[i1 + 1,j1] = Red3[i1,j1] + (k1red3[j1] + 2*k2red3[j1] + 2*k3red3[j1] + k4red3[j1])/6 - Par$KC3*Par$dtn*Red3[i1+1,j1]
k4red4[j1] = Par$DRED4*Dm*(Red4[i1 + 1, j1 -1] - 2*Red4[i1 + 1, j1] + Red4[i1 + 1, j1+1])
Red4[i1 + 1,j1] = Red4[i1,j1] + (k1red4[j1] + 2*k2red4[j1] + 2*k3red4[j1] + k4red4[j1])/6 - Par$KC4*Par$dtn*Red4[i1+1,j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
Jred1 = Derv(Ox = Red1, h = Par$h, npoints = DerApprox)
Jred2 = Derv(Ox = Red2, h = Par$h, npoints = DerApprox)
Jred3 = Derv(Ox = Red3, h = Par$h, npoints = DerApprox)
Jred4 = Derv(Ox = Red4, h = Par$h, npoints = DerApprox)
} else if (Method == "BI") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1/Par$dtn)/al1
a2 = al3/al1
al1red = Par$DRED/(Par$h^2)
al2red = -(2*Par$DRED)/(Par$h^2)
al3red = Par$DRED/(Par$h^2)
a1red = (al2red - 1/Par$dtn)/al1red
a2red = al3red/al1red
al1red2 = Par$DRED2/(Par$h^2)
al2red2 = -(2*Par$DRED2)/(Par$h^2)
al3red2 = Par$DRED2/(Par$h^2)
a1red2 = (al2red2 - 1/Par$dtn)/al1red2
a2red2 = al3red2/al1red2
al1red3 = Par$DRED3/(Par$h^2)
al2red3 = -(2*Par$DRED3)/(Par$h^2)
al3red3 = Par$DRED3/(Par$h^2)
a1red3 = (al2red3 - 1/Par$dtn)/al1red3
a2red3 = al3red3/al1red3
al1red4 = Par$DRED4/(Par$h^2)
al2red4 = -(2*Par$DRED4)/(Par$h^2)
al3red4 = Par$DRED4/(Par$h^2)
a1red4 = (al2red4 - 1/Par$dtn)/al1red4
a2red4 = al3red4/al1red4
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]), -Par$Kb1[i1]*Par$h, 0, 0, 0,
-Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h, 0, 0,
0, -Par$Kf2[i1]*Par$h, Par$Kb2[i1]*Par$h + Par$Kf3[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb3[i1]*Par$h, 0,
0, 0, -Par$Kf3[i1]*Par$h, Par$Kb3[i1]*Par$h + Par$Kf4[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb4[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 5, ncol = 5)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]),
Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox]),
Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox]) - Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1,2:DerApprox]) - Par$DRED4*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red4[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1] - Par$KCo*Ox[i1,1]
Red1[i1,1] = C[2] - Par$KC1*Red1[i1,1]
Red2[i1,1] = C[3] - Par$KC2*Red2[i1,1]
Red3[i1,1] = C[4] - Par$KC3*Red3[i1,1]
Red4[i1,1] = C[5] - Par$KC4*Red4[i1,1]
bOx = (-Ox[i1,(2:(Par$j-1))]/(al1*Par$dtn)) + Par$KCo*Ox[i1,2:(Par$j-1)]/al1
bRed = (-Red1[i1,(2:(Par$j-1))]/(al1red*Par$dtn)) + Par$KC1*Red1[i1,2:(Par$j-1)]/al1red
bRed2 = (-Red2[i1,(2:(Par$j-1))]/(al1red2*Par$dtn)) + Par$KC2*Red2[i1,2:(Par$j-1)]/al1red2
bRed3 = (-Red3[i1,(2:(Par$j-1))]/(al1red3*Par$dtn)) + Par$KC3*Red3[i1,2:(Par$j-1)]/al1red3
bRed4 = (-Red4[i1,(2:(Par$j-1))]/(al1red4*Par$dtn)) + Par$KC4*Red4[i1,2:(Par$j-1)]/al1red4
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
A1red = c(rep(a1red,Par$j-2))
A2red = c(rep(a2red,Par$j-2))
A1red2 = c(rep(a1red2,Par$j-2))
A2red2 = c(rep(a2red2,Par$j-2))
A1red3 = c(rep(a1red3,Par$j-2))
A2red3 = c(rep(a2red3,Par$j-2))
A1red4 = c(rep(a1red4,Par$j-2))
A2red4 = c(rep(a2red4,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*(1 - Par$KCo*Ox[i1,Par$j])
bRed[Par$j-2] = bRed[Par$j-2] - A2red[Par$j-2]*(Red1[i1,Par$j] - Par$KC1*Red1[i1,Par$j])
bRed2[Par$j-2] = bRed2[Par$j-2] - A2red2[Par$j-2]*(Red2[i1,Par$j] - Par$KC2*Red2[i1,Par$j])
bRed3[Par$j-2] = bRed3[Par$j-2] - A2red3[Par$j-2]*(Red3[i1,Par$j] - Par$KC3*Red3[i1,Par$j])
bRed4[Par$j-2] = bRed4[Par$j-2] - A2red4[Par$j-2]*(Red4[i1,Par$j] - Par$KC4*Red4[i1,Par$j])
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
uRed2 = c(rep(0, DerApprox))
vRed2 = c(rep(1, DerApprox))
uRed3 = c(rep(0, DerApprox))
vRed3 = c(rep(1, DerApprox))
uRed4 = c(rep(0, DerApprox))
vRed4 = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2red[Par$j-2]*bRed[j1+1]/A1red[j1+1]
bRed2[j1] = bRed2[j1] - A2red2[Par$j-2]*bRed2[j1+1]/A1red2[j1+1]
bRed3[j1] = bRed3[j1] - A2red3[Par$j-2]*bRed3[j1+1]/A1red3[j1+1]
bRed4[j1] = bRed4[j1] - A2red4[Par$j-2]*bRed4[j1+1]/A1red4[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
A1red[j1] = A1red[j1] - A2red[Par$j-2]/A1red[j1+1]
A1red2[j1] = A1red2[j1] - A2red2[Par$j-2]/A1red2[j1+1]
A1red3[j1] = A1red3[j1] - A2red3[Par$j-2]/A1red3[j1+1]
A1red4[j1] = A1red4[j1] - A2red4[Par$j-2]/A1red4[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1red[m-1]
vRed[m] = -vRed[m-1]/A1red[m-1]
uRed2[m] = (bRed2[m-1] - uRed2[m-1])/A1red2[m-1]
vRed2[m] = -vRed2[m-1]/A1red2[m-1]
uRed3[m] = (bRed3[m-1] - uRed3[m-1])/A1red3[m-1]
vRed3[m] = -vRed3[m-1]/A1red3[m-1]
uRed4[m] = (bRed4[m-1] - uRed4[m-1])/A1red4[m-1]
vRed4[m] = -vRed4[m-1]/A1red4[m-1]
}
B = matrix(data = c((Par$Kf1[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))), -Par$Kb1[i1]*Par$h, 0, 0, 0,
-Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - sum(vRed*Derv(npoints = DerApprox, CoefMat = T)), -Par$Kb2[i1]*Par$h, 0, 0,
0, -Par$Kf2[i1]*Par$h, Par$Kb2[i1]*Par$h + Par$Kf3[i1]*Par$h - sum(vRed2*Derv(npoints = DerApprox, CoefMat = T)), -Par$Kb3[i1]*Par$h, 0,
0, 0, -Par$Kf3[i1]*Par$h, Par$Kb3[i1]*Par$h + Par$Kf4[i1]*Par$h - sum(vRed3*Derv(npoints = DerApprox, CoefMat = T)), -Par$Kb4[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed2*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed3*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed4*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 5, ncol = 5)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)), sum(uRed*Derv(npoints = DerApprox, CoefMat = T)), sum(uRed2*Derv(npoints = DerApprox, CoefMat = T)), sum(uRed3*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed2*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed3*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed4*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red1[i1+1,1] = C[2]
Red2[i1+1,1] = C[3]
Red3[i1+1,1] = C[4]
Red4[i1+1,1] = C[5]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] - Ox[i1+1,j1])/A1[j1]
Red1[i1+1,j1+1] = (bRed[j1] - Red1[i1+1,j1])/A1red[j1]
Red2[i1+1,j1+1] = (bRed2[j1] - Red2[i1+1,j1])/A1red2[j1]
Red3[i1+1,j1+1] = (bRed3[j1] - Red3[i1+1,j1])/A1red3[j1]
Red4[i1+1,j1+1] = (bRed4[j1] - Red4[i1+1,j1])/A1red4[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
Jred1 = Derv(Ox = Red1, h = Par$h, npoints = DerApprox)
Jred2 = Derv(Ox = Red2, h = Par$h, npoints = DerApprox)
Jred3 = Derv(Ox = Red3, h = Par$h, npoints = DerApprox)
Jred4 = Derv(Ox = Red4, h = Par$h, npoints = DerApprox)
} else if (Method == "CN") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 2/Par$dtn)/al1
a2 = al3/al1
a3 = (al2 + 2/Par$dtn)/al1
al1red = Par$DRED/(Par$h^2)
al2red = -(2*Par$DRED)/(Par$h^2)
al3red = Par$DRED/(Par$h^2)
a1red = (al2red - 2/Par$dtn)/al1red
a2red = al3red/al1red
a3red = (al2red + 2/Par$dtn)/al1red
al1red2 = Par$DRED2/(Par$h^2)
al2red2 = -(2*Par$DRED2)/(Par$h^2)
al3red2 = Par$DRED2/(Par$h^2)
a1red2 = (al2red2 - 2/Par$dtn)/al1red2
a2red2 = al3red2/al1red2
a3red2 = (al2red2 + 2/Par$dtn)/al1red2
al1red3 = Par$DRED3/(Par$h^2)
al2red3 = -(2*Par$DRED3)/(Par$h^2)
al3red3 = Par$DRED3/(Par$h^2)
a1red3 = (al2red3 - 2/Par$dtn)/al1red3
a2red3 = al3red3/al1red3
a3red3 = (al2red3 + 2/Par$dtn)/al1red3
al1red4 = Par$DRED4/(Par$h^2)
al2red4 = -(2*Par$DRED4)/(Par$h^2)
al3red4 = Par$DRED4/(Par$h^2)
a1red4 = (al2red4 - 2/Par$dtn)/al1red4
a2red4 = al3red4/al1red4
a3red4 = (al2red4 + 2/Par$dtn)/al1red4
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]), -Par$Kb1[i1]*Par$h, 0, 0, 0,
-Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h, 0, 0,
0, -Par$Kf2[i1]*Par$h, Par$Kb2[i1]*Par$h + Par$Kf3[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb3[i1]*Par$h, 0,
0, 0, -Par$Kf3[i1]*Par$h, Par$Kb3[i1]*Par$h + Par$Kf4[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb4[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 5, ncol = 5)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]),
Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox]),
Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox]) - Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1,2:DerApprox]) - Par$DRED4*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red4[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1] - Par$KCo*Ox[i1,1]
Red1[i1,1] = C[2] - Par$KC1*Red1[i1,1]
Red2[i1,1] = C[3] - Par$KC2*Red2[i1,1]
Red3[i1,1] = C[4] - Par$KC3*Red3[i1,1]
Red4[i1,1] = C[5] - Par$KC4*Red4[i1,1]
bOx = -a3*Ox[i1,(2:(Par$j-1))] - Ox[i1,(1:(Par$j-2))] - a2*Ox[i1,(3:Par$j)] + Par$KCo*Ox[i1,2:(Par$j-1)]/al1
bRed = -a3red*Red1[i1,(2:(Par$j-1))]- Red1[i1,(1:(Par$j-2))] - a2red*Red1[i1,(3:Par$j)] + Par$KC1*Red1[i1,2:(Par$j-1)]/al1red
bRed2 = -a3red2*Red2[i1,(2:(Par$j-1))]- Red2[i1,(1:(Par$j-2))] - a2red2*Red2[i1,(3:Par$j)] + Par$KC2*Red2[i1,2:(Par$j-1)]/al1red2
bRed3 = -a3red3*Red3[i1,(2:(Par$j-1))]- Red3[i1,(1:(Par$j-2))] - a2red3*Red3[i1,(3:Par$j)] + Par$KC3*Red3[i1,2:(Par$j-1)]/al1red3
bRed4 = -a3red4*Red4[i1,(2:(Par$j-1))]- Red4[i1,(1:(Par$j-2))] - a2red4*Red4[i1,(3:Par$j)] + Par$KC4*Red4[i1,2:(Par$j-1)]/al1red4
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
A1red = c(rep(a1red,Par$j-2))
A2red = c(rep(a2red,Par$j-2))
A1red2 = c(rep(a1red2,Par$j-2))
A2red2 = c(rep(a2red2,Par$j-2))
A1red3 = c(rep(a1red3,Par$j-2))
A2red3 = c(rep(a2red3,Par$j-2))
A1red4 = c(rep(a1red4,Par$j-2))
A2red4 = c(rep(a2red4,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*(1 - Par$KCo*Ox[i1,Par$j])
bRed[Par$j-2] = bRed[Par$j-2] - A2red[Par$j-2]*(Red1[i1,Par$j] - Par$KC1*Red1[i1,Par$j])
bRed2[Par$j-2] = bRed2[Par$j-2] - A2red2[Par$j-2]*(Red2[i1,Par$j] - Par$KC2*Red2[i1,Par$j])
bRed3[Par$j-2] = bRed3[Par$j-2] - A2red3[Par$j-2]*(Red3[i1,Par$j] - Par$KC3*Red3[i1,Par$j])
bRed4[Par$j-2] = bRed4[Par$j-2] - A2red4[Par$j-2]*(Red4[i1,Par$j] - Par$KC4*Red4[i1,Par$j])
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
uRed2 = c(rep(0, DerApprox))
vRed2 = c(rep(1, DerApprox))
uRed3 = c(rep(0, DerApprox))
vRed3 = c(rep(1, DerApprox))
uRed4 = c(rep(0, DerApprox))
vRed4 = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2red[Par$j-2]*bRed[j1+1]/A1red[j1+1]
bRed2[j1] = bRed2[j1] - A2red2[Par$j-2]*bRed2[j1+1]/A1red2[j1+1]
bRed3[j1] = bRed3[j1] - A2red3[Par$j-2]*bRed3[j1+1]/A1red3[j1+1]
bRed4[j1] = bRed4[j1] - A2red4[Par$j-2]*bRed4[j1+1]/A1red4[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
A1red[j1] = A1red[j1] - A2red[Par$j-2]/A1red[j1+1]
A1red2[j1] = A1red2[j1] - A2red2[Par$j-2]/A1red2[j1+1]
A1red3[j1] = A1red3[j1] - A2red3[Par$j-2]/A1red3[j1+1]
A1red4[j1] = A1red4[j1] - A2red4[Par$j-2]/A1red4[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1red[m-1]
vRed[m] = -vRed[m-1]/A1red[m-1]
uRed2[m] = (bRed2[m-1] - uRed2[m-1])/A1red2[m-1]
vRed2[m] = -vRed2[m-1]/A1red2[m-1]
uRed3[m] = (bRed3[m-1] - uRed3[m-1])/A1red3[m-1]
vRed3[m] = -vRed3[m-1]/A1red3[m-1]
uRed4[m] = (bRed4[m-1] - uRed4[m-1])/A1red4[m-1]
vRed4[m] = -vRed4[m-1]/A1red4[m-1]
}
B = matrix(data = c((Par$Kf1[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))), -Par$Kb1[i1]*Par$h, 0, 0, 0,
-Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - sum(vRed*Derv(npoints = DerApprox, CoefMat = T)), -Par$Kb2[i1]*Par$h, 0, 0,
0, -Par$Kf2[i1]*Par$h, Par$Kb2[i1]*Par$h + Par$Kf3[i1]*Par$h - sum(vRed2*Derv(npoints = DerApprox, CoefMat = T)), -Par$Kb3[i1]*Par$h, 0,
0, 0, -Par$Kf3[i1]*Par$h, Par$Kb3[i1]*Par$h + Par$Kf4[i1]*Par$h - sum(vRed3*Derv(npoints = DerApprox, CoefMat = T)), -Par$Kb4[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed2*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed3*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed4*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 5, ncol = 5)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)), sum(uRed*Derv(npoints = DerApprox, CoefMat = T)), sum(uRed2*Derv(npoints = DerApprox, CoefMat = T)), sum(uRed3*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed2*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed3*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed4*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red1[i1+1,1] = C[2]
Red2[i1+1,1] = C[3]
Red3[i1+1,1] = C[4]
Red4[i1+1,1] = C[5]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] - Ox[i1+1,j1])/A1[j1]
Red1[i1+1,j1+1] = (bRed[j1] - Red1[i1+1,j1])/A1red[j1]
Red2[i1+1,j1+1] = (bRed2[j1] - Red2[i1+1,j1])/A1red2[j1]
Red3[i1+1,j1+1] = (bRed3[j1] - Red3[i1+1,j1])/A1red3[j1]
Red4[i1+1,j1+1] = (bRed4[j1] - Red4[i1+1,j1])/A1red4[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
Jred1 = Derv(Ox = Red1, h = Par$h, npoints = DerApprox)
Jred2 = Derv(Ox = Red2, h = Par$h, npoints = DerApprox)
Jred3 = Derv(Ox = Red3, h = Par$h, npoints = DerApprox)
Jred4 = Derv(Ox = Red4, h = Par$h, npoints = DerApprox)
} else if (Method == "BDF") {
al1 = 1/(Par$h^2)
al2 = -2/(Par$h^2)
al3 = 1/(Par$h^2)
a1 = (al2 - 1.5/Par$dtn)/al1
a2 = al3/al1
al1red = Par$DRED/(Par$h^2)
al2red = -(2*Par$DRED)/(Par$h^2)
al3red = Par$DRED/(Par$h^2)
a1red = (al2red - 1.5/Par$dtn)/al1red
a2red = al3red/al1red
al1red2 = Par$DRED2/(Par$h^2)
al2red2 = -(2*Par$DRED2)/(Par$h^2)
al3red2 = Par$DRED2/(Par$h^2)
a1red2 = (al2red2 - 1.5/Par$dtn)/al1red2
a2red2 = al3red2/al1red2
al1red3 = Par$DRED3/(Par$h^2)
al2red3 = -(2*Par$DRED3)/(Par$h^2)
al3red3 = Par$DRED3/(Par$h^2)
a1red3 = (al2red3 - 1.5/Par$dtn)/al1red3
a2red3 = al3red3/al1red3
al1red4 = Par$DRED4/(Par$h^2)
al2red4 = -(2*Par$DRED4)/(Par$h^2)
al3red4 = Par$DRED4/(Par$h^2)
a1red4 = (al2red4 - 1.5/Par$dtn)/al1red4
a2red4 = al3red4/al1red4
for (i1 in 1:(Par$l-1)) {
B = matrix(data = c((Par$Kf1[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1]), -Par$Kb1[i1]*Par$h, 0, 0, 0,
-Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb2[i1]*Par$h, 0, 0,
0, -Par$Kf2[i1]*Par$h, Par$Kb2[i1]*Par$h + Par$Kf3[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb3[i1]*Par$h, 0,
0, 0, -Par$Kf3[i1]*Par$h, Par$Kb3[i1]*Par$h + Par$Kf4[i1]*Par$h - Derv(npoints = DerApprox, CoefMat = T)[1], -Par$Kb4[i1]*Par$h,
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1],
Derv(npoints = DerApprox, CoefMat = T)[1]),
byrow = T, nrow = 5, ncol = 5)
Y = matrix(data = c(sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]),
Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]),
Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox]),
Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1,2:DerApprox]),
-sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Ox[i1,2:DerApprox]) - Par$DRED*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red1[i1,2:DerApprox]) - Par$DRED2*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red2[i1,2:DerApprox]) - Par$DRED3*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red3[i1,2:DerApprox]) - Par$DRED4*sum(Derv(npoints = DerApprox, CoefMat = T)[2:DerApprox]*Red4[i1,2:DerApprox])))
C = invMat(B) %*% Y
Ox[i1,1] = C[1] - Par$KCo*Ox[i1,1]
Red1[i1,1] = C[2] - Par$KC1*Red1[i1,1]
Red2[i1,1] = C[3] - Par$KC2*Red2[i1,1]
Red3[i1,1] = C[4] - Par$KC3*Red3[i1,1]
Red4[i1,1] = C[5] - Par$KC4*Red4[i1,1]
if (i1 == 1) {
bOx = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[1,2:(Par$j-1)]/(2*Par$dtn*al1) + Par$KCo*Ox[i1,2:(Par$j-1)]/al1
bRed = -2*Red1[i1,2:(Par$j-1)]/(Par$dtn*al1red) + Red1[1,2:(Par$j-1)]/(2*Par$dtn*al1red) + Par$KC1*Red1[i1,2:(Par$j-1)]/al1red
bRed2 = -2*Red2[i1,2:(Par$j-1)]/(Par$dtn*al1red2) + Red2[1,2:(Par$j-1)]/(2*Par$dtn*al1red2) + Par$KC2*Red2[i1,2:(Par$j-1)]/al1red2
bRed3 = -2*Red3[i1,2:(Par$j-1)]/(Par$dtn*al1red3) + Red3[1,2:(Par$j-1)]/(2*Par$dtn*al1red3) + Par$KC3*Red3[i1,2:(Par$j-1)]/al1red3
bRed4 = -2*Red4[i1,2:(Par$j-1)]/(Par$dtn*al1red4) + Red4[1,2:(Par$j-1)]/(2*Par$dtn*al1red4) + Par$KC4*Red4[i1,2:(Par$j-1)]/al1red4
} else {
bOx = -2*Ox[i1,2:(Par$j-1)]/(Par$dtn*al1) + Ox[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1) + Par$KCo*Ox[i1,2:(Par$j-1)]/al1
bRed = -2*Red1[i1,2:(Par$j-1)]/(Par$dtn*al1red) + Red1[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1red) + Par$KC1*Red1[i1,2:(Par$j-1)]/al1red
bRed2 = -2*Red2[i1,2:(Par$j-1)]/(Par$dtn*al1red2) + Red2[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1red2) + Par$KC2*Red2[i1,2:(Par$j-1)]/al1red2
bRed3 = -2*Red3[i1,2:(Par$j-1)]/(Par$dtn*al1red3) + Red3[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1red3) + Par$KC3*Red3[i1,2:(Par$j-1)]/al1red3
bRed4 = -2*Red4[i1,2:(Par$j-1)]/(Par$dtn*al1red4) + Red4[i1-1,2:(Par$j-1)]/(2*Par$dtn*al1red4) + Par$KC4*Red4[i1,2:(Par$j-1)]/al1red4
}
A = c(rep(1,Par$j-2))
A1 = c(rep(a1,Par$j-2))
A2 = c(rep(a2,Par$j-2))
A1red = c(rep(a1red,Par$j-2))
A2red = c(rep(a2red,Par$j-2))
A1red2 = c(rep(a1red2,Par$j-2))
A2red2 = c(rep(a2red2,Par$j-2))
A1red3 = c(rep(a1red3,Par$j-2))
A2red3 = c(rep(a2red3,Par$j-2))
A1red4 = c(rep(a1red4,Par$j-2))
A2red4 = c(rep(a2red4,Par$j-2))
bOx[Par$j-2] = bOx[Par$j-2] - A2[Par$j-2]*(1 - Par$KCo*Ox[i1,Par$j])
bRed[Par$j-2] = bRed[Par$j-2] - A2red[Par$j-2]*(Red1[i1,Par$j] - Par$KC1*Red1[i1,Par$j])
bRed2[Par$j-2] = bRed2[Par$j-2] - A2red2[Par$j-2]*(Red2[i1,Par$j] - Par$KC1*Red1[i1,Par$j])
bRed3[Par$j-2] = bRed3[Par$j-2] - A2red3[Par$j-2]*(Red3[i1,Par$j] - Par$KC2*Red2[i1,Par$j])
bRed4[Par$j-2] = bRed4[Par$j-2] - A2red4[Par$j-2]*(Red4[i1,Par$j] - Par$KC3*Red3[i1,Par$j])
uox = c(rep(0, DerApprox))
vox = c(rep(1, DerApprox))
uRed = c(rep(0, DerApprox))
vRed = c(rep(1, DerApprox))
uRed2 = c(rep(0, DerApprox))
vRed2 = c(rep(1, DerApprox))
uRed3 = c(rep(0, DerApprox))
vRed3 = c(rep(1, DerApprox))
uRed4 = c(rep(0, DerApprox))
vRed4 = c(rep(1, DerApprox))
for (j1 in ((Par$j-3):1)) {
bOx[j1] = bOx[j1] - A2[Par$j-2]*bOx[j1+1]/A1[j1+1]
bRed[j1] = bRed[j1] - A2red[Par$j-2]*bRed[j1+1]/A1red[j1+1]
bRed2[j1] = bRed2[j1] - A2red2[Par$j-2]*bRed2[j1+1]/A1red2[j1+1]
bRed3[j1] = bRed3[j1] - A2red3[Par$j-2]*bRed3[j1+1]/A1red3[j1+1]
bRed4[j1] = bRed4[j1] - A2red4[Par$j-2]*bRed4[j1+1]/A1red4[j1+1]
A1[j1] = A1[j1] - A2[Par$j-2]/A1[j1+1]
A1red[j1] = A1red[j1] - A2red[Par$j-2]/A1red[j1+1]
A1red2[j1] = A1red2[j1] - A2red2[Par$j-2]/A1red2[j1+1]
A1red3[j1] = A1red3[j1] - A2red3[Par$j-2]/A1red3[j1+1]
A1red4[j1] = A1red4[j1] - A2red4[Par$j-2]/A1red4[j1+1]
}
for (m in 2:DerApprox) {
uox[m] = (bOx[m-1] - uox[m-1])/A1[m-1]
vox[m] = -vox[m-1]/A1[m-1]
uRed[m] = (bRed[m-1] - uRed[m-1])/A1red[m-1]
vRed[m] = -vRed[m-1]/A1red[m-1]
uRed2[m] = (bRed2[m-1] - uRed2[m-1])/A1red2[m-1]
vRed2[m] = -vRed2[m-1]/A1red2[m-1]
uRed3[m] = (bRed3[m-1] - uRed3[m-1])/A1red3[m-1]
vRed3[m] = -vRed3[m-1]/A1red3[m-1]
uRed4[m] = (bRed4[m-1] - uRed4[m-1])/A1red4[m-1]
vRed4[m] = -vRed4[m-1]/A1red4[m-1]
}
B = matrix(data = c((Par$Kf1[i1]*Par$h - sum(vox*Derv(npoints = DerApprox, CoefMat = T))), -Par$Kb1[i1]*Par$h, 0, 0, 0,
-Par$Kf1[i1]*Par$h, Par$Kb1[i1]*Par$h + Par$Kf2[i1]*Par$h - sum(vRed*Derv(npoints = DerApprox, CoefMat = T)), -Par$Kb2[i1]*Par$h, 0, 0,
0, -Par$Kf2[i1]*Par$h, Par$Kb2[i1]*Par$h + Par$Kf3[i1]*Par$h - sum(vRed2*Derv(npoints = DerApprox, CoefMat = T)), -Par$Kb3[i1]*Par$h, 0,
0, 0, -Par$Kf3[i1]*Par$h, Par$Kb3[i1]*Par$h + Par$Kf4[i1]*Par$h - sum(vRed3*Derv(npoints = DerApprox, CoefMat = T)), -Par$Kb4[i1]*Par$h,
sum(vox*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed2*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed3*Derv(npoints = DerApprox, CoefMat = T)),
sum(vRed4*Derv(npoints = DerApprox, CoefMat = T))),
byrow = T, nrow = 5, ncol = 5)
Y = matrix(data = c(sum(uox*Derv(npoints = DerApprox, CoefMat = T)), sum(uRed*Derv(npoints = DerApprox, CoefMat = T)), sum(uRed2*Derv(npoints = DerApprox, CoefMat = T)), sum(uRed3*Derv(npoints = DerApprox, CoefMat = T)),
-sum(uox*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed2*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed3*Derv(npoints = DerApprox, CoefMat = T)) - sum(uRed4*Derv(npoints = DerApprox, CoefMat = T))))
C = invMat(B) %*% Y
Ox[i1+1,1] = C[1]
Red1[i1+1,1] = C[2]
Red2[i1+1,1] = C[3]
Red3[i1+1,1] = C[4]
Red4[i1+1,1] = C[5]
for (j1 in 1:(Par$j-2)) {
Ox[i1+1,j1+1] = (bOx[j1] - Ox[i1+1,j1])/A1[j1]
Red1[i1+1,j1+1] = (bRed[j1] - Red1[i1+1,j1])/A1red[j1]
Red2[i1+1,j1+1] = (bRed2[j1] - Red2[i1+1,j1])/A1red2[j1]
Red3[i1+1,j1+1] = (bRed3[j1] - Red3[i1+1,j1])/A1red3[j1]
Red4[i1+1,j1+1] = (bRed4[j1] - Red4[i1+1,j1])/A1red4[j1]
}
}
Jox = Derv(Ox = Ox, h = Par$h, npoints = DerApprox)
Jred1 = Derv(Ox = Red1, h = Par$h, npoints = DerApprox)
Jred2 = Derv(Ox = Red2, h = Par$h, npoints = DerApprox)
Jred3 = Derv(Ox = Red3, h = Par$h, npoints = DerApprox)
Jred4 = Derv(Ox = Red4, h = Par$h, npoints = DerApprox)
} else if (!(Method %in% c("Euler", "BI", "RK4", "CN", "BDF"))) {
return("Available methods are Euler, BI, RK4, CN and BDF")
}
G1 = Jox
G2 = Jox + Jred1
G3 = Jox + Jred1 + Jred2
G4 = Jox + Jred1 + Jred2 + Jred3
G5 = Jox + Jred1 + Jred2 + Jred3 + Jred4
i = (n*Par$FA*(G1+G2+G3+G4+G5)*Dx1*Area*Co)/(sqrt(Dx1*Par$tau))
graphy = ggplot(data = data.frame(i[1:(length(i)-1)],Par$PotentialScan[1:(length(i)-1)]),
aes(y = i[1:(length(i)-1)], x = Par$PotentialScan[1:(length(i)-1)])) +
geom_point() + scale_x_continuous(trans = "reverse") +
xlab("E / V") +
ylab("I / A") +
theme_classic()
if (errCheck == TRUE){
return(list((G1+G2),Dx1,Dred,Dred2,Co,
Par$dtn,Par$h,i,Par$l,Par$j,n,
Area,Par$DOx,Par$DRED,Par$DRED2,
Par$p1,Par$p2,Par$p3,Par$p4))
} else {
return(graphy)
}
}
|
gd_token <- function(verbose = TRUE) {
if (!token_available(verbose = verbose) || !is_legit_token(.state$token)) {
if (verbose) message("No token currently in force.")
return(invisible(NULL))
}
token <- .state$token
token_valid <- token$validate()
first_last_n <- function(x, n = 5) {
paste(substr(x, start = 1, stop = n),
substr(x, start = nchar(x) - n + 1, stop = nchar(x)), sep = "...")
}
scopes <- token$params$scope %>%
strsplit(split = "\\s+") %>%
purrr::flatten_chr()
cpf(" access token: %s",
if (token_valid) "valid" else "expired, will auto-refresh")
cpf(" peek at access token: %s",
first_last_n(token$credentials$access_token))
cpf("peek at refresh token: %s",
first_last_n(token$credentials$refresh_token))
cpf(" scopes: %s",
paste(scopes, collapse = "\n "))
cpf(" token cache_path: %s", token$cache_path)
invisible(token)
}
gs_token <- gd_token
|
library(leaflet.extras)
leaflet() %>%
setView(0, 0, 2) %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addDrawToolbar(
targetGroup = "draw",
editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions())) %>%
addLayersControl(overlayGroups = c("draw"), options =
layersControlOptions(collapsed = FALSE)) %>%
addStyleEditor()
cities <- read.csv(textConnection("
City,Lat,Long,Pop
Boston,42.3601,-71.0589,645966
Hartford,41.7627,-72.6743,125017
New York City,40.7127,-74.0059,8406000
Philadelphia,39.9500,-75.1667,1553000
Pittsburgh,40.4397,-79.9764,305841
Providence,41.8236,-71.4222,177994
"))
leaflet(cities) %>% addTiles() %>%
addCircles(lng = ~Long, lat = ~Lat, weight = 1,
radius = ~sqrt(Pop) * 30, label = ~City, group = "cities") %>%
addDrawToolbar(
targetGroup = "cities",
editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions())) %>%
addLayersControl(overlayGroups = c("cities"), options =
layersControlOptions(collapsed = FALSE)) %>%
addStyleEditor()
library(rbgm)
set.seed(2)
fs <- sample(bgmfiles::bgmfiles(), 1)
model <- boxSpatial(bgmfile(fs))
model <- spTransform(model, "+init=epsg:4326")
leaflet() %>% addTiles() %>%
addPolygons(data = model, group = "model") %>%
addDrawToolbar(targetGroup = "model",
editOptions = editToolbarOptions(
selectedPathOptions = selectedPathOptions())) %>%
addLayersControl(overlayGroups = c("model"), options =
layersControlOptions(collapsed = FALSE)) %>%
addStyleEditor()
fName <- "https://rawgit.com/benbalter/dc-maps/master/maps/ward-2012.geojson"
geoJson <- readr::read_file(fName)
geoJson2 <- rmapshaper::ms_simplify(geoJson, keep = 0.01)
leaflet() %>% addTiles() %>% setView(-77.0369, 38.9072, 12) %>%
addGeoJSONv2(geoJson2,
group = "wards", layerId = "dc-wards") %>%
addDrawToolbar(
targetLayerId = "dc-wards",
editOptions = editToolbarOptions(
selectedPathOptions = selectedPathOptions())) %>%
addLayersControl(overlayGroups = c("wards"),
options = layersControlOptions(collapsed = FALSE)) %>%
addStyleEditor()
|
graph_model <- function(model, ...) UseMethod('graph_model')
graph_model_q <- function(model, ...) UseMethod('graph_model_q')
graph_model.lm <- function(model, y, x, lines=NULL, split=NULL,
errorbars=c('CI', 'SE', 'none'), ymin=NULL, ymax=NULL, labels=NULL,
bargraph=FALSE, draw.legend=TRUE, dodge=0, exp=FALSE, ...) {
call <- as.list(match.call())[-1]
call$y <- deparse(substitute(y))
call$x <- deparse(substitute(x))
if (!is.null(call$lines)) {
call$lines <- deparse(substitute(lines))
}
if (!is.null(call$split)) {
call$split <- deparse(substitute(split))
}
return(do.call(graph_model_q.lm, call))
}
graph_model_q.lm <- function(model, y, x, lines=NULL, split=NULL,
errorbars=c('CI', 'SE', 'none'), ymin=NULL, ymax=NULL, labels=NULL,
bargraph=FALSE, draw.legend=TRUE, dodge=0, exp=FALSE, ...) {
call <- as.list(match.call())[-1]
call$type <- 'response'
return(do.call(graph_model_q.glm, call))
}
graph_model.aov <- function(model, y, x, lines=NULL, split=NULL,
errorbars=c('CI', 'SE', 'none'), ymin=NULL, ymax=NULL, labels=NULL,
bargraph=FALSE, draw.legend=TRUE, dodge=0, exp=FALSE, ...) {
call <- as.list(match.call())[-1]
call$y <- deparse(substitute(y))
call$x <- deparse(substitute(x))
if (!is.null(call$lines)) {
call$lines <- deparse(substitute(lines))
}
if (!is.null(call$split)) {
call$split <- deparse(substitute(split))
}
return(do.call(graph_model_q.aov, call))
}
graph_model_q.aov <- function(model, y, x, lines=NULL, split=NULL,
errorbars=c('CI', 'SE', 'none'), ymin=NULL, ymax=NULL, labels=NULL,
bargraph=FALSE, draw.legend=TRUE, dodge=0, exp=FALSE, ...) {
call <- as.list(match.call())[-1]
return(do.call(graph_model_q.lm, call))
}
graph_model.glm <- function(model, y, x, lines=NULL, split=NULL,
type=c('link', 'response'), errorbars=c('CI', 'SE', 'none'), ymin=NULL,
ymax=NULL, labels=NULL, bargraph=FALSE, draw.legend=TRUE, dodge=0,
exp=FALSE, ...) {
call <- as.list(match.call())[-1]
call$y <- deparse(substitute(y))
call$x <- deparse(substitute(x))
if (!is.null(call$lines)) {
call$lines <- deparse(substitute(lines))
}
if (!is.null(call$split)) {
call$split <- deparse(substitute(split))
}
return(do.call(graph_model_q.glm, call))
}
graph_model_q.glm <- function(model, y, x, lines=NULL, split=NULL,
type=c('link', 'response'), errorbars=c('CI', 'SE', 'none'), ymin=NULL,
ymax=NULL, labels=NULL, bargraph=FALSE, draw.legend=TRUE, dodge=0,
exp=FALSE, ...) {
type <- match.arg(type)
errorbars <- match.arg(errorbars)
data <- model$model
factors <- list()
i <- 1
for (term in c(x, lines, split)) {
if (!is.null(term)) {
if (is.factor(data[[term]])) {
factors[[i]] <- levels(data[[term]])
} else if (is.character(data[[term]])) {
data[[term]] <- factor(data[[term]])
factors[[i]] <- levels(data[[term]])
} else {
factors[[i]] <- c(
mean(data[[term]], na.rm=TRUE)+sd(data[[term]], na.rm=TRUE),
mean(data[[term]], na.rm=TRUE)-sd(data[[term]], na.rm=TRUE)
)
}
i <- i + 1
}
}
if (is.null(lines) && is.null(split)) {
grid <- with(data, expand.grid(
x=factors[[1]],
g=1
))
names(grid)[names(grid) == 'x'] <- x
} else if (is.null(split)) {
grid <- with(data, expand.grid(
x=factors[[1]],
lines=factors[[2]]
))
names(grid) <- c(x, lines)
} else {
grid <- with(data, expand.grid(
x=factors[[1]],
lines=factors[[2]],
split=factors[[3]]
))
names(grid) <- c(x, lines, split)
}
variables <- all.vars(formula(model))[-1]
factor_name <- NULL
for (i in 1:length(variables)) {
if (!(variables[[i]] %in% colnames(grid))) {
v <- data[[variables[[i]]]]
if (is.character(v)) {
data[[variables[[i]]]] <- factor(v)
}
if (is.factor(v)) {
temp_list <- lapply(as.list(grid), unique)
temp_list[[variables[[i]]]] <- levels(v)
grid <- expand.grid(temp_list)
factor_name <- variables[[i]]
} else {
grid[[variables[[i]]]] <- mean(v, na.rm=TRUE)
}
}
}
predicted <- predict(model, newdata=grid, type=type, se.fit=TRUE)
if (exp == TRUE) {
grid[[y]] <- exp(predicted$fit)
} else {
grid[[y]] <- predicted$fit
}
errors <- FALSE
if (errorbars == 'CI') {
grid$error_upper <- predicted$fit + 1.96 * predicted$se.fit
grid$error_lower <- predicted$fit - 1.96 * predicted$se.fit
errors <- TRUE
} else if (errorbars == 'SE') {
grid$error_upper <- predicted$fit + predicted$se.fit
grid$error_lower <- predicted$fit - predicted$se.fit
errors <- TRUE
}
if (exp == TRUE && errors == TRUE) {
grid$error_upper <- exp(grid$error_upper)
grid$error_lower <- exp(grid$error_lower)
}
if (!is.null(factor_name)) {
grid2 <- subset(grid, FALSE)
lev <- levels(data[[factor_name]])
location <- which(names(grid) == factor_name)
for (i in 1:(nrow(grid)/length(lev))) {
grid2[i, -location] <- apply(grid[seq(i, nrow(grid),
by=(nrow(grid)/length(lev))), -location], 2, mean, na.rm=TRUE)
}
grid2[[location]] <- NULL
grid <- grid2
}
for (term in c(x, lines, split)) {
if (!is.null(term) && !is.factor(data[[term]])) {
grid[[term]] <- factor(grid[[term]], labels=c('-1 SD', '+1 SD'))
}
}
if (!is.null(split)) {
if (is.null(labels$split)) {
labels$split <- paste0(split, ': ')
} else if (is.na(labels$split)) {
labels$split <- ''
} else {
labels$split <- paste0(labels$split, ': ')
}
if (!is.factor(data[[split]])) {
levels(grid[[split]]) <- c(paste0(labels$split, '-1 SD'),
paste0(labels$split, '+1 SD'))
} else {
num_levels <- length(levels(grid[[split]]))
levels(grid[[split]]) <- paste0(rep(labels$split, num_levels),
levels(grid[[split]]))
}
}
if (is.null(lines)) {
lines <- 'g'
draw.legend <- FALSE
}
graph <- .build_plot(grid, y, x, lines, split, errors, ymin, ymax,
labels, bargraph, draw.legend, dodge, exp)
return(graph)
}
graph_model.lme <- function(model, y, x, lines=NULL, split=NULL,
errorbars=c('CI', 'SE', 'none'), ymin=NULL, ymax=NULL, labels=NULL,
bargraph=FALSE, draw.legend=TRUE, dodge=0, exp=FALSE, ...) {
call <- as.list(match.call())[-1]
call$y <- deparse(substitute(y))
call$x <- deparse(substitute(x))
if (!is.null(call$lines)) {
call$lines <- deparse(substitute(lines))
}
if (!is.null(call$split)) {
call$split <- deparse(substitute(split))
}
return(do.call(graph_model_q.lme, call))
}
graph_model_q.lme <- function(model, y, x, lines=NULL, split=NULL,
errorbars=c('CI', 'SE', 'none'), ymin=NULL, ymax=NULL, labels=NULL,
bargraph=FALSE, draw.legend=TRUE, dodge=0, exp=FALSE, ...) {
errorbars <- match.arg(errorbars)
data <- model$data
factors <- list()
i <- 1
for (term in c(x, lines, split)) {
if (!is.null(term)) {
if (is.factor(data[[term]])) {
factors[[i]] <- levels(data[[term]])
} else if (is.character(data[[term]])) {
data[[term]] <- factor(data[[term]])
factors[[i]] <- levels(data[[term]])
} else {
factors[[i]] <- c(
mean(data[[term]], na.rm=TRUE)+sd(data[[term]], na.rm=TRUE),
mean(data[[term]], na.rm=TRUE)-sd(data[[term]], na.rm=TRUE)
)
}
i <- i + 1
}
}
if (is.null(lines) && is.null(split)) {
grid <- with(data, expand.grid(
x=factors[[1]],
g=1
))
names(grid)[names(grid) == 'x'] <- x
} else if (is.null(split)) {
grid <- with(data, expand.grid(
x=factors[[1]],
lines=factors[[2]]
))
names(grid) <- c(x, lines)
} else {
grid <- with(data, expand.grid(
x=factors[[1]],
lines=factors[[2]],
split=factors[[3]]
))
names(grid) <- c(x, lines, split)
}
variables <- all.vars(formula(model))[-1]
factor_name <- NULL
for (i in 1:length(variables)) {
if (!(variables[[i]] %in% colnames(grid))) {
v <- data[[variables[[i]]]]
if (is.character(v)) {
data[[variables[[i]]]] <- factor(v)
}
if (is.factor(v)) {
temp_list <- lapply(as.list(grid), unique)
temp_list[[variables[[i]]]] <- levels(v)
grid <- expand.grid(temp_list)
factor_name <- variables[[i]]
} else {
grid[[variables[[i]]]] <- mean(v, na.rm=TRUE)
}
}
}
predicted <- predict(model, newdata=grid, level=0)
if (exp == TRUE) {
grid[[y]] <- exp(predicted)
} else {
grid[[y]] <- predicted
}
errors <- FALSE
if (errorbars == 'CI' || errorbars == 'SE') {
designmat <- model.matrix(formula(model)[-2], grid)
predvar <- diag(designmat %*% vcov(model) %*% t(designmat))
se <- sqrt(predvar)
if (errorbars == 'CI') {
grid$error_upper <- predicted + 1.96 * se
grid$error_lower <- predicted - 1.96 * se
} else if (errorbars == 'SE') {
grid$error_upper <- predicted + se
grid$error_lower <- predicted - se
}
errors <- TRUE
}
if (exp == TRUE && errors == TRUE) {
grid$error_upper <- exp(grid$error_upper)
grid$error_lower <- exp(grid$error_lower)
}
if (!is.null(factor_name)) {
grid2 <- subset(grid, FALSE)
lev <- levels(data[[factor_name]])
location <- which(names(grid) == factor_name)
for (i in 1:(nrow(grid)/length(lev))) {
grid2[i, -location] <- apply(grid[seq(i, nrow(grid),
by=(nrow(grid)/length(lev))), -location], 2, mean, na.rm=TRUE)
}
grid2[[location]] <- NULL
grid <- grid2
}
for (term in c(x, lines, split)) {
if (!is.null(term) && !is.factor(data[[term]])) {
grid[[term]] <- factor(grid[[term]], labels=c('-1 SD', '+1 SD'))
}
}
if (!is.null(split)) {
if (is.null(labels$split)) {
labels$split <- paste0(split, ': ')
} else if (is.na(labels$split)) {
labels$split <- ''
} else {
labels$split <- paste0(labels$split, ': ')
}
if (!is.factor(data[[split]])) {
levels(grid[[split]]) <- c(paste0(labels$split, '-1 SD'),
paste0(labels$split, '+1 SD'))
} else {
num_levels <- length(levels(grid[[split]]))
levels(grid[[split]]) <- paste0(rep(labels$split, num_levels),
levels(grid[[split]]))
}
}
if (is.null(lines)) {
lines <- 'g'
draw.legend <- FALSE
}
graph <- .build_plot(grid, y, x, lines, split, errors, ymin, ymax,
labels, bargraph, draw.legend, dodge, exp)
return(graph)
}
graph_model.merMod <- function(model, y, x, lines=NULL, split=NULL,
errorbars=c('CI', 'SE', 'none'), ymin=NULL, ymax=NULL, labels=NULL,
bargraph=FALSE, draw.legend=TRUE, dodge=0, exp=FALSE, ...) {
call <- as.list(match.call())[-1]
call$y <- deparse(substitute(y))
call$x <- deparse(substitute(x))
if (!is.null(call$lines)) {
call$lines <- deparse(substitute(lines))
}
if (!is.null(call$split)) {
call$split <- deparse(substitute(split))
}
return(do.call(graph_model_q.merMod, call))
}
graph_model_q.merMod <- function(model, y, x, lines=NULL, split=NULL,
errorbars=c('CI', 'SE', 'none'), ymin=NULL, ymax=NULL, labels=NULL,
bargraph=FALSE, draw.legend=TRUE, dodge=0, exp=FALSE, ...) {
errorbars <- match.arg(errorbars)
data <- model@frame
factors <- list()
i <- 1
for (term in c(x, lines, split)) {
if (!is.null(term)) {
if (is.factor(data[[term]])) {
factors[[i]] <- levels(data[[term]])
} else if (is.character(data[[term]])) {
data[[term]] <- factor(data[[term]])
factors[[i]] <- levels(data[[term]])
} else {
factors[[i]] <- c(
mean(data[[term]], na.rm=TRUE)+sd(data[[term]], na.rm=TRUE),
mean(data[[term]], na.rm=TRUE)-sd(data[[term]], na.rm=TRUE)
)
}
i <- i + 1
}
}
if (is.null(lines) && is.null(split)) {
grid <- with(data, expand.grid(
x=factors[[1]],
g=1
))
names(grid)[names(grid) == 'x'] <- x
} else if (is.null(split)) {
grid <- with(data, expand.grid(
x=factors[[1]],
lines=factors[[2]]
))
names(grid) <- c(x, lines)
} else {
grid <- with(data, expand.grid(
x=factors[[1]],
lines=factors[[2]],
split=factors[[3]]
))
names(grid) <- c(x, lines, split)
}
variables <- all.vars(formula(model, fixed.only=TRUE))[-1]
factor_name <- NULL
for (i in 1:length(variables)) {
if (!(variables[[i]] %in% colnames(grid))) {
v <- data[[variables[[i]]]]
if (is.character(v)) {
data[[variables[[i]]]] <- factor(v)
}
if (is.factor(v)) {
temp_list <- lapply(as.list(grid), unique)
temp_list[[variables[[i]]]] <- levels(v)
grid <- expand.grid(temp_list)
factor_name <- variables[[i]]
} else {
grid[[variables[[i]]]] <- mean(v, na.rm=TRUE)
}
}
}
predicted <- predict(model, newdata=grid, re.form=NA)
if (exp == TRUE) {
grid[[y]] <- exp(predicted)
} else {
grid[[y]] <- predicted
}
errors <- FALSE
if (errorbars == 'CI' || errorbars == 'SE') {
designmat <- model.matrix(delete.response(terms(model)), grid)
predicted <- predict(model, grid, re.form=NA)
predvar <- diag(designmat %*% as.matrix(vcov(model)) %*% t(designmat))
se <- sqrt(predvar)
if (errorbars == 'CI') {
grid$error_upper <- predicted + 1.96 * se
grid$error_lower <- predicted - 1.96 * se
} else if (errorbars == 'SE') {
grid$error_upper <- predicted + se
grid$error_lower <- predicted - se
}
errors <- TRUE
}
if (exp == TRUE && errors == TRUE) {
grid$error_upper <- exp(grid$error_upper)
grid$error_lower <- exp(grid$error_lower)
}
if (!is.null(factor_name)) {
grid2 <- subset(grid, FALSE)
lev <- levels(data[[factor_name]])
location <- which(names(grid) == factor_name)
for (i in 1:(nrow(grid)/length(lev))) {
grid2[i, -location] <- apply(grid[seq(i, nrow(grid),
by=(nrow(grid)/length(lev))), -location], 2, mean, na.rm=TRUE)
}
grid2[[location]] <- NULL
grid <- grid2
}
for (term in c(x, lines, split)) {
if (!is.null(term) && !is.factor(data[[term]])) {
grid[[term]] <- factor(grid[[term]], labels=c('-1 SD', '+1 SD'))
}
}
if (!is.null(split)) {
if (is.null(labels$split)) {
labels$split <- paste0(split, ': ')
} else if (is.na(labels$split)) {
labels$split <- ''
} else {
labels$split <- paste0(labels$split, ': ')
}
if (!is.factor(data[[split]])) {
levels(grid[[split]]) <- c(paste0(labels$split, '-1 SD'),
paste0(labels$split, '+1 SD'))
} else {
num_levels <- length(levels(grid[[split]]))
levels(grid[[split]]) <- paste0(rep(labels$split, num_levels),
levels(grid[[split]]))
}
}
if (is.null(lines)) {
lines <- 'g'
draw.legend <- FALSE
}
graph <- .build_plot(grid, y, x, lines, split, errors, ymin, ymax,
labels, bargraph, draw.legend, dodge, exp)
return(graph)
}
.build_plot <- function(grid, y, x, lines=NULL, split=NULL, errors=TRUE,
ymin=NULL, ymax=NULL, labels=NULL, bargraph=FALSE, draw.legend=TRUE,
dodge=0, exp=FALSE) {
if (bargraph == FALSE) {
pd <- ggplot2::position_dodge(dodge)
graph <- ggplot2::ggplot(
data=grid,
ggplot2::aes_string(x=x, y=y, colour=lines, ymin=ymin, ymax=ymax))
graph <- graph + ggplot2::geom_point(position=pd) +
ggplot2::geom_line(position=pd, ggplot2::aes_string(group=lines))
} else {
pd <- ggplot2::position_dodge(dodge + .9)
graph <- ggplot2::ggplot(
data=grid,
ggplot2::aes_string(x=x, y=y, fill=lines, ymin=ymin, ymax=ymax))
graph <- graph + ggplot2::geom_bar(
position=pd,
stat='identity',
ggplot2::aes_string(group=lines))
}
if (draw.legend == FALSE) {
graph <- graph + ggplot2::theme(legend.position='none')
}
if (errors) {
graph <- graph + ggplot2::geom_errorbar(
ggplot2::aes_string(ymax='error_upper', ymin='error_lower'),
width=0.1,
position=pd)
}
if (!is.null(split)) {
graph <- graph + ggplot2::facet_grid(paste0('. ~ ', split))
}
if (!is.null(labels)) {
if (!is.null(labels$y) && is.na(labels$y)) {
labels$y <- ''
}
if (!is.null(labels$x) && is.na(labels$x)) {
labels$x <- ''
}
if (!is.null(labels$lines) && is.na(labels$lines)) {
labels$lines <- ''
}
if (!is.null(labels$title) && !is.na(labels$title)) {
graph <- graph + ggplot2::ggtitle(labels$title)
}
if (!is.null(labels$y)) {
graph <- graph + ggplot2::ylab(labels$y)
}
if (!is.null(labels$x)) {
graph <- graph + ggplot2::xlab(labels$x)
}
if (!is.null(labels$lines)) {
graph <- graph + ggplot2::labs(colour=labels$lines)
}
}
return(graph)
}
|
print.TransitionTable <- function(x, activeOnly=FALSE, ...)
{
geneCols <- setdiff(colnames(x),c("attractorAssignment","transitionsToAttractor"))
numGenes <- (length(geneCols)) / 2
colIndices <- c(1,numGenes,numGenes + 1, 2*numGenes);
if ("attractorAssignment" %in% colnames(x))
colIndices <- c(colIndices, 2*numGenes + 1)
if ("transitionsToAttractor" %in% colnames(x))
colIndices <- c(colIndices, 2*numGenes + 2)
genes <- sapply(colnames(x)[seq_len(numGenes)],function(n)strsplit(n,".",fixed=TRUE)[[1]][2])
if(activeOnly)
{
inputStates <- apply(x,1,function(row)
{
r <- paste(genes[which(row[colIndices[1]:colIndices[2]] == 1)],collapse=", ")
if (r == "")
r <- "--"
r
})
outputStates <- apply(x,1,function(row)
{
r <- paste(genes[which(row[colIndices[3]:colIndices[4]] == 1)],collapse=", ")
if (r == "")
r <- "--"
r
})
colWidth <- max(c(sapply(inputStates,nchar),sapply(outputStates,nchar)))
align <- "left"
}
else
{
inputStates <- apply(x,1,function(row)
paste(row[colIndices[1]:colIndices[2]],collapse=""))
outputStates <- apply(x,1,function(row)
paste(row[colIndices[3]:colIndices[4]],collapse=""))
colWidth <- numGenes
align <- "right"
}
binMatrix <- cbind(inputStates,outputStates)
if ("attractorAssignment" %in% colnames(x))
binMatrix <- cbind(binMatrix, x[,colIndices[5]])
if ("transitionsToAttractor" %in% colnames(x))
binMatrix <- cbind(binMatrix, x[,colIndices[6]])
binMatrix <- as.data.frame(binMatrix)
cat(format("State",width=max(7,colWidth),justify=align)," ",
format("Next state",width=max(11,colWidth + 2),justify=align),
if ("attractorAssignment" %in% colnames(x))
{
format("Attr. basin",width=13,justify="right")
}
else
"",
if ("transitionsToAttractor" %in% colnames(x))
{
format("
}
else
"",
"\n",sep="")
apply(binMatrix,1,function(row)
{
cat(format(row[1],width=max(7,colWidth),justify=align),
" => ",
format(row[2],width=max(11,colWidth + 2),justify=align),
if ("attractorAssignment" %in% colnames(x))
{
format(row[3],width=13,justify="right")
}
else
"",
if ("transitionsToAttractor" %in% colnames(x))
{
format(row[4],width=19,justify="right")
}
else
"",
"\n",sep="")
})
if (!activeOnly)
cat("\nGenes are encoded in the following order: ",
paste(genes,collapse=" "),"\n",sep="")
return(invisible(x))
}
|
afterhours_rank <- function(data,
hrvar = extract_hr(data),
mingroup = 5,
return = "table"){
data %>%
create_rank(metric = "After_hours_collaboration_hours",
hrvar = hrvar,
mingroup = mingroup,
return = return)
}
|
rtext_loadsave <-
R6::R6Class(
classname = "rtext_loadsave",
active = NULL,
inherit = rtext_base,
lock_objects = TRUE,
class = TRUE,
portable = TRUE,
lock_class = FALSE,
cloneable = TRUE,
parent_env = asNamespace('rtext'),
private = list(
prepare_save = function(id=NULL){
if( is.null(id) ){
id <- self$id
}else if( id[1] == "hash"){
tb_saved$meta$id <- self$hash()
}else{
tb_saved$meta$id <- id[1]
}
tb_saved <-
list(
meta = data.frame(
id = id,
date = as.character(Sys.time()),
text_file = self$text_file,
encoding = self$encoding,
save_file = ifelse(is.null(self$save_file), NA, self$save_file),
sourcetype = self$sourcetype,
rtext_version= as.character(packageVersion("rtext")),
r_version = paste(version$major, version$minor, sep="."),
save_format_version = 1
),
hashes = as.data.frame(private$hash()),
char = private$char,
char_data = private$char_data
)
class(tb_saved) <- c("rtext_save","list")
return(tb_saved)
},
execute_load = function(tmp){
self$id <- tmp$meta$id
self$text_file <- tmp$meta$text_file
self$encoding <- tmp$meta$encoding
self$sourcetype <- tmp$meta$sourcetype
self$save_file <- tmp$meta$save_file
private$char <- tmp$char
private$char_data <- tmp$char_data
private$hash()
invisible(self)
}
),
public = list(
save = function(file=NULL, id=NULL){
rtext_save <- as.environment(private$prepare_save(id=id))
if(
(is.na(rtext_save$meta$save_file) | is.null(rtext_save$meta$save_file)) &
is.null(file)
){
stop("rtext$save() : Neither file nor save_file given, do not know where to store file.")
}else if( !is.null(file) ){
file <- file
}else if( !is.null(rtext_save$meta$save_file) ){
file <- rtext_save$meta$save_file
}
base::save(
list = ls(rtext_save),
file = file,
envir = rtext_save
)
return(invisible(self))
},
load = function(file=NULL){
if( is.null(file) ){
stop("rtext$load() : file is not given, do not know where to load file from.")
}else{
file <- file
}
tmp <- load_into(file)
private$execute_load(tmp)
return(invisible(self))
}
)
)
|
library(hamcrest)
expected <- c(-0x1.c88d0d69dc594p-2 + 0x0p+0i, -0x1.9c02d3ab5010ep-3 + 0x1.5e65943d33391p-1i,
-0x1.2a3fdbc77b9bep+1 + -0x1.8a6cc9834e07bp-2i, 0x1.5e26f462d3552p-5 + 0x1.f0c11230fe2fp-3i,
-0x1.27a07f3e974aep-1 + -0x1.60db37940fd21p+1i, 0x1.3691753902679p+0 + 0x1.0403f5003c7acp-3i,
0x1.cbc2de62a1a6ep-1 + 0x1.66c294ccd2321p-2i, 0x1.e4353e99be1ap-5 + 0x1.d0e3b1fe69c2ep-1i,
-0x1.40eb75f058fe8p-1 + -0x1.25474452ef70bp+0i, -0x1.b11f07bf7ede5p-3 + 0x1.c6ff946f7ecbp-7i,
-0x1.0f9508285f988p-3 + 0x1.b27d8643e4f94p-2i, -0x1.2a6f19debf1e8p-1 + 0x1.0f3b41f4e8c0cp-1i,
-0x1.851a9ea109181p+0 + 0x0p+0i, -0x1.2a6f19debf1e6p-1 + -0x1.0f3b41f4e8c0bp-1i,
-0x1.0f9508285f998p-3 + -0x1.b27d8643e4f8dp-2i, -0x1.b11f07bf7edecp-3 + -0x1.c6ff946f7ed4p-7i,
-0x1.40eb75f058feep-1 + 0x1.25474452ef70ap+0i, 0x1.e4353e99be1ap-5 + -0x1.d0e3b1fe69c2dp-1i,
0x1.cbc2de62a1a7p-1 + -0x1.66c294ccd2323p-2i, 0x1.3691753902679p+0 + -0x1.0403f5003c7b2p-3i,
-0x1.27a07f3e974b4p-1 + 0x1.60db37940fd22p+1i, 0x1.5e26f462d3584p-5 + -0x1.f0c11230fe2e5p-3i,
-0x1.2a3fdbc77b9bep+1 + 0x1.8a6cc9834e076p-2i, -0x1.9c02d3ab5010bp-3 + -0x1.5e65943d33392p-1i
)
assertThat(stats:::fft(z=c(-0.286027622792142, 0.0850139363831411, -0.175844765676884,
-0.0195878168855467, 0.0547396065555839, -0.125844837790663,
0.0193917857980049, 0.326765455053088, 0.101630594070502, 0.0495244570922387,
-0.228418032116601, -0.557775319978623, -0.339272039245778, 0.193030443660542,
0.106870700470349, 0.152732595917981, 0.120980858690617, -0.0882566624696145,
-0.123121055673646, 0.708937464819026, 0.3054871538559, -0.0201214433194038,
-0.539311186803385, -0.167374841806141))
, identicalTo( expected, tol = 1e-6 ) )
|
assign.class <- function(x, emobj = NULL, pi = NULL, Mu = NULL, LTSigma = NULL,
lab = NULL, return.all = TRUE){
if(is.null(emobj)){
emobj <- list(pi = pi, Mu = Mu, LTSigma = LTSigma)
}
n <- nrow(x)
p <- ncol(x)
nclass <- length(emobj$pi)
p.LTSigma <- p * (p + 1) / 2
check.dim(emobj, p, nclass, p.LTSigma)
ss <- FALSE
if(! is.null(lab)){
labK <- max(lab)
lab <- lab - 1
if(length(unique(lab[lab != -1])) != labK) stop("lab is not correct.")
if(labK > nclass) stop("lab is not correct.")
if(any(table(lab[lab >= 0]) < (p + 1))) stop("lab is not correct.")
ss <- TRUE
}
if(!ss){
ret <- .Call("R_assign",
as.double(t(x)),
as.integer(n),
as.integer(p),
as.integer(nclass),
as.integer(p.LTSigma),
as.double(emobj$pi),
as.double(t(emobj$Mu)),
as.double(t(emobj$LTSigma)))
} else{
ret <- .Call("ss_R_assign",
as.double(t(x)),
as.integer(n),
as.integer(p),
as.integer(nclass),
as.integer(p.LTSigma),
as.double(emobj$pi),
as.double(t(emobj$Mu)),
as.double(t(emobj$LTSigma)),
as.integer(lab))
}
ret$class <- ret$class + 1
if(return.all){
emobj$nc <- ret$nc
emobj$class <- ret$class
ret <- emobj
class(ret) <- "emret"
}
ret
}
assign.class.wt <- function(x, emobj, lab = NULL, return.all = TRUE){
n <- ncol(x)
p <- nrow(x)
nclass <- length(emobj$pi)
p.LTSigma <- p * (p + 1) / 2
check.dim.wt(emobj, p, nclass, p.LTSigma)
ss <- FALSE
if(! is.null(lab)){
labK <- max(lab)
lab <- lab - 1
if(length(unique(lab[lab != -1])) != labK) stop("lab is not correct.")
if(labK > nclass) stop("lab is not correct.")
if(any(table(lab[lab >= 0]) < (p + 1))) stop("lab is not correct.")
ss <- TRUE
}
if(!ss){
ret <- .Call("R_assign",
as.double(x),
as.integer(n),
as.integer(p),
as.integer(nclass),
as.integer(p.LTSigma),
as.double(emobj$pi),
as.double(emobj$Mu),
as.double(emobj$LTSigma))
} else{
ret <- .Call("ss_R_assign",
as.double(x),
as.integer(n),
as.integer(p),
as.integer(nclass),
as.integer(p.LTSigma),
as.double(emobj$pi),
as.double(emobj$Mu),
as.double(emobj$LTSigma),
as.integer(lab))
}
ret$class <- ret$class + 1
if(return.all){
emobj$nc <- ret$nc
emobj$class <- ret$class
ret <- emobj
class(ret) <- "emret.wt"
}
ret
}
meandispersion <- function(x, type = c("MLE", "MME", "rough")){
n <- nrow(x)
p <- ncol(x)
type.index <- switch(type[1], MLE = 1, MME = 2, 0)
ret <- .Call("R_meandispersion",
as.double(t(x)),
as.integer(n),
as.integer(p),
as.integer(type.index))
ret$mu <- matrix(ret$mu, nrow = 1)
ret$ltsigma <- matrix(ret$ltsigma, nrow = 1)
ret$type <- type[1]
ret
}
|
SADEG.GC3 = function(Nucleotide_Sequence)
{
RSCU_List=NULL
Nucleotide_Sequence=toupper(Nucleotide_Sequence)
Codon=sapply(0:((nchar(Nucleotide_Sequence)/3)-1), function(x) substr(Nucleotide_Sequence,(x*3)+1,(x*3)+3))
Codon_Table=table(Codon)
Spare=c("ATG","TGG","TAG","TAA","TGA")
Codons=Codon_Table[-which(names(Codon_Table) %in% Spare)]
L=sum(Codons)
GC3=sum(Codons[which(substr(names(Codons),3,3) %in% c("C","G"))])
names(GC3)="GC3"
if (GC3>0)
return(GC3/L)
}
|
getclf<-function(data, freq)
{
nvars<-ncol(data)
pars<-double(nvars+nvars*(nvars+1)/2)
testdata<-data[cumsum(freq),]
presabs<-ifelse(is.na(testdata),0,1)
data<-t(data)
presabs<-t(presabs)
dim(presabs)<-NULL
dim(data)<-NULL
data<-data[!is.na(data)]
function(pars){
.C("evallf",as.double(data),as.integer(nvars),as.integer(freq),
as.integer(x=length(freq)),as.integer(presabs),as.double(pars),val=double(1))$val;
}
}
|
cron_rstudioaddin <- function(RscriptRepository = Sys.getenv("CRON_LIVE", unset = getwd())) {
cron_current <- function(){
x <- try(parse_crontab(), silent = TRUE)
if(inherits(x, "try-error")){
x <- list(cronR = character())
}
x
}
requireNamespace("cronR")
requireNamespace("shiny")
requireNamespace("miniUI")
requireNamespace("shinyFiles")
check <- NULL
popup <- shiny::modalDialog(title = "Request for approval",
"By using this app, you approve that you are aware that the app has access to your cron schedule and that it will add or remove elements in your crontab.",
shiny::tags$br(),
shiny::tags$br(),
shiny::modalButton("Yes, I know", icon = shiny::icon("play")),
shiny::actionButton(inputId = "ui_validate_no", label = "No I don't want this, close the app", icon = shiny::icon("stop")),
footer = NULL,
easyClose = FALSE)
ui <- miniUI::miniPage(
miniUI::gadgetTitleBar("Use cron to schedule your R script"),
miniUI::miniTabstripPanel(
miniUI::miniTabPanel(title = 'Upload and create new jobs', icon = shiny::icon("cloud-upload"),
miniUI::miniContentPanel(
shiny::h4("Choose your Rscript"),
shinyFiles::shinyFilesButton('fileSelect', label='Select file', title='Choose your Rscript', multiple=FALSE),
shiny::br(),
shiny::br(),
shiny::fillRow(flex = c(3, 3),
shiny::column(6,
shiny::div(class = "control-label", shiny::strong("Selected Rscript")),
shiny::verbatimTextOutput('currentfileselected'),
shiny::dateInput('date', label = "Launch date:", startview = "month", weekstart = 1, min = Sys.Date()),
shiny::textInput('hour', label = "Launch hour:", value = format(Sys.time() + 122, "%H:%M")),
shiny::radioButtons('task', label = "Schedule:", choices = c('ONCE', 'EVERY MINUTE', 'EVERY HOUR', 'EVERY DAY', 'EVERY WEEK', 'EVERY MONTH', 'ASIS'), selected = "ONCE"),
shiny::textInput('custom_schedule', label = "ASIS cron schedule", value = "")
),
shiny::column(6,
shiny::textInput('jobdescription', label = "Job description", value = "I execute things"),
shiny::textInput('jobtags', label = "Job tags", value = ""),
shiny::textInput('rscript_args', label = "Additional arguments to Rscript", value = ""),
shiny::textInput('jobid', label = "Job identifier", value = sprintf("job_%s", digest(runif(1)))),
shiny::textInput('rscript_repository', label = "Rscript repository path: launch & log location", value = RscriptRepository)
))
),
miniUI::miniButtonBlock(border = "bottom",
shiny::actionButton('create', "Create job", icon = shiny::icon("play-circle"))
)
),
miniUI::miniTabPanel(title = 'Manage existing jobs', icon = shiny::icon("table"),
miniUI::miniContentPanel(
shiny::fillRow(flex = c(3, 3),
shiny::column(6,
shiny::h4("Existing crontab"),
shiny::actionButton('showcrontab', "Show current crontab schedule", icon = shiny::icon("calendar")),
shiny::br(),
shiny::br(),
shiny::h4("Show/Delete 1 specific job"),
shiny::uiOutput("getFiles"),
shiny::actionButton('showjob', "Show job", icon = shiny::icon("clock-o")),
shiny::actionButton('deletejob', "Delete job", icon = shiny::icon("remove"))
),
shiny::column(6,
shiny::h4("Save crontab"),
shiny::textInput('savecrontabpath', label = "Save current crontab schedule to", value = file.path(Sys.getenv("HOME"), "my_schedule.cron")),
shiny::actionButton('savecrontab', "Save", icon = shiny::icon("save")),
shiny::br(),
shiny::br(),
shiny::h4("Load crontab"),
shinyFiles::shinyFilesButton('crontabSelect', label='Select crontab schedule', title='Select crontab schedule', multiple=FALSE),
shiny::br(),
shiny::br(),
shiny::actionButton('loadcrontab', "Load selected schedule", icon = shiny::icon("load")),
shiny::br(),
shiny::br(),
shiny::verbatimTextOutput('currentcrontabselected')
))
),
miniUI::miniButtonBlock(border = "bottom",
shiny::actionButton('deletecrontab', "Completely clear current crontab schedule", icon = shiny::icon("delete"))
)
)
)
)
server <- function(input, output, session) {
shiny::showModal(popup)
shiny::observeEvent(input$ui_validate_no, {
shiny::stopApp()
})
volumes <- c('Current working dir' = getwd(), 'HOME' = Sys.getenv('HOME'), 'R Installation' = R.home(), 'Root' = "/")
getSelectedFile <- function(inputui, default = "No R script selected yet"){
f <- shinyFiles::parseFilePaths(volumes, inputui)$datapath
f <- as.character(f)
if(length(f) == 0){
return(default)
}else{
if(length(grep(" ", f, value=TRUE))){
warning(sprintf("It is advised that the file you want to schedule (%s) does not contain spaces", f))
}
}
f
}
shinyFiles::shinyFileChoose(input, id = 'fileSelect', roots = volumes, session = session)
output$fileSelect <- shiny::renderUI({shinyFiles::parseFilePaths(volumes, input$fileSelect)})
output$currentfileselected <- shiny::renderText({getSelectedFile(inputui = input$fileSelect)})
shinyFiles::shinyFileChoose(input, id = 'crontabSelect', roots = volumes, session = session)
output$crontabSelect <- shiny::renderUI({shinyFiles::parseFilePaths(volumes, input$crontabSelect)})
output$currentcrontabselected <- shiny::renderText({basename(getSelectedFile(inputui = input$crontabSelect, default = ""))})
shiny::observeEvent(input$rscript_repository, {
RscriptRepository <<- normalizePath(input$rscript_repository, winslash = "/")
verify_rscript_path(RscriptRepository)
})
shiny::observeEvent(input$create, {
shiny::req(input$task)
if(input$task == "EVERY MONTH" ){
days <- as.integer(format(input$date, "%d"))
}
else if(input$task == "EVERY WEEK"){
days <- as.integer(format(input$date, "%w"))
}
else {
days <- NULL
}
starttime <- input$hour
rscript_args <- input$rscript_args
frequency <- factor(input$task,
levels = c('ONCE', 'EVERY MINUTE', 'EVERY HOUR', 'EVERY DAY', 'EVERY WEEK', 'EVERY MONTH', "ASIS"),
labels = c('once', 'minutely', 'hourly', 'daily', 'weekly', 'monthly', 'asis'))
frequency <- as.character(frequency)
if(length(grep(" ", RscriptRepository)) > 0){
warning(sprintf("It is advised that the RscriptRepository does not contain spaces, change argument %s to another location on your drive which contains no spaces", RscriptRepository))
}
if (!file.exists(RscriptRepository)) {
stop(sprintf("The specified Rscript repository path, at %s, does not exist. Please set it to an existing directory.", RscriptRepository))
}
runme <- getSelectedFile(inputui = input$fileSelect)
myscript <- paste0(RscriptRepository, "/", basename(runme))
if(runme != myscript){
done <- file.copy(runme, myscript, overwrite = TRUE)
if(!done){
stop(sprintf('Copying file %s to %s failed. Do you have access rights to %s?', file.path(runme, input$file$name), myscript, dirname(myscript)))
}
}
cmd <- sprintf("Rscript %s %s >> %s.log 2>&1", myscript, rscript_args, tools::file_path_sans_ext(myscript))
cmd <- sprintf('%s %s %s >> %s 2>&1', file.path(Sys.getenv("R_HOME"), "bin", "Rscript"), shQuote(myscript), rscript_args, shQuote(sprintf("%s.log", tools::file_path_sans_ext(myscript))))
if(frequency %in% c('minutely')){
cron_add(command = cmd, frequency = frequency, id = input$jobid, tags = input$jobtags, description = input$jobdescription, ask=FALSE)
}else if(frequency %in% c('hourly')){
cron_add(command = cmd, frequency = frequency, at = starttime, id = input$jobid, tags = input$jobtags, description = input$jobdescription, ask=FALSE)
}else if(frequency %in% c('daily')){
cron_add(command = cmd, frequency = 'daily', at = starttime, id = input$jobid, tags = input$jobtags, description = input$jobdescription, ask=FALSE)
}else if(frequency %in% c('weekly')){
cron_add(command = cmd, frequency = 'daily', days_of_week = days, at = starttime, id = input$jobid, tags = input$jobtags, description = input$jobdescription, ask=FALSE)
}else if(frequency %in% c('monthly')){
cron_add(command = cmd, frequency = 'monthly', days_of_month = days, days_of_week = 1:7, at = starttime, id = input$jobid, tags = input$jobtags, description = input$jobdescription, ask=FALSE)
}else if(frequency %in% c('once')){
message(sprintf("This is not a cron schedule but will launch: %s", sprintf('nohup %s &', cmd)))
system(sprintf('nohup %s &', cmd))
}else if(frequency %in% c('asis')){
cron_add(command = cmd, frequency = input$custom_schedule, id = input$jobid, tags = input$jobtags, description = input$jobdescription, ask=FALSE)
}
shiny::updateDateInput(session, inputId = 'date', value = Sys.Date())
shiny::updateTextInput(session, inputId = "hour", value = format(Sys.time() + 122, "%H:%M"))
shiny::updateRadioButtons(session, inputId = 'task', selected = "ONCE")
shiny::updateTextInput(session, inputId = "jobid", value = sprintf("job_%s", digest(runif(1))))
shiny::updateTextInput(session, inputId = "jobdescription", value = "I execute things")
shiny::updateTextInput(session, inputId = "jobtags", value = "")
shiny::updateTextInput(session, inputId = "rscript_args", value = "")
shiny::updateSelectInput(session, inputId="getFiles", choices = sapply(cron_current()$cronR, FUN=function(x) x$id))
})
output$getFiles <- shiny::renderUI({
shiny::selectInput(inputId = 'getFiles', "Select job", choices = sapply(cron_current()$cronR, FUN=function(x) x$id))
})
shiny::observeEvent(input$showcrontab, {
cron_ls()
})
shiny::observeEvent(input$showjob, {
cron_ls(input$getFiles)
})
shiny::observeEvent(input$savecrontab, {
message(input$savecrontabpath)
cron_save(file = input$savecrontabpath, overwrite = TRUE)
})
shiny::observeEvent(input$loadcrontab, {
f <- getSelectedFile(inputui = input$crontabSelect, default = "")
message(f)
if(f != ""){
cron_load(file = f, ask=FALSE)
}
output$getFiles <- shiny::renderUI({
shiny::selectInput(inputId = 'getFiles', "Select job", choices = sapply(cron_current()$cronR, FUN=function(x) x$id))
})
})
shiny::observeEvent(input$deletecrontab, {
cron_clear(ask = FALSE)
output$getFiles <- shiny::renderUI({
shiny::selectInput(inputId = 'getFiles', "Select job", choices = sapply(cron_current()$cronR, FUN=function(x) x$id))
})
})
shiny::observeEvent(input$deletejob, {
cron_rm(input$getFiles, ask=FALSE)
output$getFiles <- shiny::renderUI({
shiny::selectInput(inputId = 'getFiles', "Select job", choices = sapply(cron_current()$cronR, FUN=function(x) x$id))
})
})
shiny::observeEvent(input$done, {
shiny::stopApp()
})
}
viewer <- shiny::dialogViewer("Cron job scheduler", width = 700, height = 800)
shiny::runGadget(ui, server, viewer = viewer)
}
verify_rscript_path <- function(RscriptRepository) {
if(is.na(file.info(RscriptRepository)$isdir)){
warning(sprintf("The specified Rscript repository path %s does not exist, make sure this is an existing directory without spaces.", RscriptRepository))
} else if (as.logical(file.access(RscriptRepository, mode = 2))) {
warning(sprintf("You do not have write access to the specified Rscript repository path, %s.", RscriptRepository))
}
}
|
expected <- eval(parse(text="-29L"));
test(id=0, code={
argv <- eval(parse(text="list(structure(list(c(\"4.1-0\", \"4.1-0\", \"4.1-0\", \"4.1-0\", \"4.1-0\", \"4.1-0\", \"4.0-3\", \"4.0-3\", \"4.0-3\", \"4.0-3\", \"4.0-3\", \"4.0-2\", \"4.0-2\", \"4.0-1\", \"4.0-1\", \"4.0-1\", \"4.0-1\", \"4.0-1\", \"4.0-1\", \"4.0-1\", \"4.0-1\", \"3.1-55\", \"3.1-55\", \"3.1-55\", \"3.1-54\", \"3.1-53\", \"3.1-53\", \"3.1-52\", \"3.1-51\"), c(NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_), c(NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_), c(\"The C and R code has been reformatted for legibility.\", \"The old compatibility function rpconvert() has been removed.\", \"The cross-validation functions allow for user interrupt at the end\\nof evaluating each split.\", \"Variable Reliability in data set car90 is corrected to be an\\nordered factor, as documented.\", \"Surrogate splits are now considered only if they send two or more\\ncases _with non-zero weight_ each way. For numeric/ordinal\\nvariables the restriction to non-zero weights is new: for\\ncategorical variables this is a new restriction.\", \"Surrogate splits which improve only by rounding error over the\\ndefault split are no longer returned. Where weights and missing\\nvalues are present, the splits component for some of these was not\\nreturned correctly.\", \"A fit of class \\\"rpart\\\" now contains a component for variable\\n‘importance’, which is reported by the summary() method.\", \"The text() method gains a minlength argument, like the labels()\\nmethod. This adds finer control: the default remains pretty =\\nNULL, minlength = 1L.\", \"The handling of fits with zero and fractional weights has been\\ncorrected: the results may be slightly different (or even\\nsubstantially different when the proportion of zero weights is\\nlarge).\", \"Some memory leaks have been plugged.\", \"There is a second vignette, longintro.Rnw, a version of the\\noriginal Mayo Tecnical Report on rpart.\", \"Added dataset car90, a corrected version of the S-PLUS dataset\\ncar.all (used with permission).\", \"This version does not use paste0{} and so works with R 2.14.x.\", \"Merged in a set of Splus code changes that had accumulated at Mayo\\nover the course of a decade. The primary one is a change in how\\nindexing is done in the underlying C code, which leads to a major\\nspeed increase for large data sets. Essentially, for the lower\\nleaves all our time used to be eaten up by bookkeeping, and this\\nwas replaced by a different approach. The primary routine also\\nuses .Call{} so as to be more memory efficient.\", \"The other major change was an error for asymmetric loss matrices,\\nprompted by a user query. With L=loss asymmetric, the altered\\npriors were computed incorrectly - they were using L' instead of L.\\nUpshot - the tree would not not necessarily choose optimal splits\\nfor the given loss matrix. Once chosen, splits were evaluated\\ncorrectly. The printed “improvement” values are of course the\\nwrong ones as well. It is interesting that for my little test\\ncase, with L quite asymmetric, the early splits in the tree are\\nunchanged - a good split still looks good.\", \"Add the return.all argument to xpred.rpart().\", \"Added a set of formal tests, i.e., cases with known answers to\\nwhich we can compare.\", \"Add a usercode vignette, explaining how to add user defined\\nsplitting functions.\", \"The class method now also returns the node probability.\", \"Add the stagec data set, used in some tests.\", \"The plot.rpart routine needs to store a value that will be visible\\nto the rpartco routine at a later time. This is now done in an\\nenvironment in the namespace.\", \"Force use of registered symbols in R >= 2.16.0\", \"Update Polish translations.\", \"Work on message formats.\", \"Add Polish translations\", \"rpart, rpart.matrix: allow backticks in formulae.\", \"tests/backtick.R: regession test\", \"src/xval.c: ensure unused code is not compiled in.\", \"Change description of margin in ?plot.rpart as suggested by Bill\\nVenables.\")), row.names = c(NA, -29L), class = \"data.frame\"), 1L)"));
.Internal(shortRowNames(argv[[1]], argv[[2]]));
}, o=expected);
|
summary.immer_latent_regression <- function( object, digits=3, file=NULL, ... )
{
immer_osink( file=file )
cat("-----------------------------------------------------------------\n")
immer_summary_print_package_rsession(pack="immer")
cat( object$description, "\n\n")
immer_summary_print_call(CALL=object$CALL)
immer_summary_print_computation_time(object=object )
cat( "Number of iterations=", object$iter, "\n" )
cat("\n")
cat( "Deviance=", round( object$ic$dev, 2 ), " | " )
cat( "Log Likelihood=", round( -object$ic$dev/2, 2 ), "\n" )
cat( "Number of persons=", object$ic$n, "\n" )
cat( "Number of groups=", object$ic$G, "\n" )
cat( "Number of estimated parameters=", object$ic$np, "\n" )
cat("\n")
immer_summary_print_ic(object=object)
cat("-----------------------------------------------------------------\n")
cat( "Regression coefficients\n" )
immer_summary_print_objects(obji=object$beta_stat, from=2, digits=digits, rownames_null=TRUE)
cat("-----------------------------------------------------------------\n")
cat( "Standard deviations\n" )
immer_summary_print_objects(obji=object$gamma_stat, from=2, digits=digits, rownames_null=TRUE)
immer_csink( file=file )
}
|
testthat::test_that("Passing in weights and data arguments", {
variables = c("gender",
"age_years_interview", "education_adult")
res = cforward(nhanes_example,
event_time = "event_time_years",
event_status = "mortstat",
weight_column = "WTMEC4YR_norm",
variables = variables,
included_variables = NULL,
n_folds = 1,
seed = 1989,
max_model_size = 2,
verbose = FALSE)
testthat::expect_equal(
res[[1]]$full_concordance,
c(res[[1]]$cv_concordance)
)
testthat::expect_warning({
res = cforward(nhanes_example,
event_time = "event_time_years",
event_status = "mortstat",
weight_column = "WTMEC4YR_norm",
variables = variables,
included_variables = NULL,
n_folds = 2,
weights = 5,
seed = 1989,
max_model_size = 50,
verbose = FALSE)
}, regexp = "were specified")
testthat::expect_error({
res = cforward(nhanes_example,
event_time = "event_time_years",
event_status = "mortstat",
weight_column = "WTMEC4YR_norm",
variables = "blahblahbald",
included_variables = NULL,
n_folds = 2,
weights = 5,
seed = 1989,
max_model_size = 50,
verbose = FALSE)
}, regexp = "Independent variables")
testthat::expect_warning({
estimate_concordance(nhanes_example, nhanes_example,
data = nhanes_example,
all_variables = "1")
}, regexp = "data set in.*overridden.*")
x = nhanes_example
x$strata = rbinom(nrow(x), size = 1, prob = 0.2)
res = cforward(x,
event_time = "event_time_years",
event_status = "mortstat",
weight_column = "WTMEC4YR_norm",
variables = variables,
included_variables = NULL,
n_folds = 2,
cfit_args = list(strata_column = "strata"),
seed = 1989,
max_model_size = 50,
verbose = FALSE)
x$gender[1] = NA
testthat::expect_warning({
res = cforward(x,
event_time = "event_time_years",
event_status = "mortstat",
weight_column = "WTMEC4YR_norm",
variables = variables,
included_variables = NULL,
n_folds = 2,
seed = 1989,
max_model_size = 50,
verbose = FALSE)
}, regexp = "elements in the test")
})
|
estep.Z.cost <-
function(xx,alpha,beta,mu,a,b,d,Q,k,l,Wmat){
nbasis = ncol(xx)
Qkl = Wmat[[k]][[l]]%*%as.matrix(Q[[k]][[l]])
Pa = (as.matrix(xx - matrix(1,nrow(xx),1)%*%mu[k,l,]) %*% Qkl) %*% t(Qkl)
Pb = Pa + as.matrix(matrix(1,nrow(xx),1)%*%mu[k,l,] - xx)
A = t(1/a[k,l] * rowSums(Pa^2) + (1/b[k,l] * rowSums(Pb^2)) + d[k,l] * log(a[k,l])
+ (nbasis-d[k,l]) * log(b[k,l])) - 2 * log(beta[l])
}
|
seqtest.prop <- function(x, y = NULL, pi = NULL,
alternative = c("two.sided", "less", "greater"),
delta, alpha = 0.05, beta = 0.1,
output = TRUE, plot = FALSE) {
if (any(!x %in% c(0, 1)) || any(!y %in% c(0, 1))) {
stop("Only 0 and 1 are allowed for x and y")
}
if (is.null(pi)) {
pi <- 0.5
}
if (pi <= 0 || pi >= 1) {
stop("Argument pi out of bound, specify a value between 0 and 1")
}
if (!all(alternative %in% c("two.sided", "less", "greater"))) {
stop("Argument alternative should be \"two.sided\", \"less\" or \"greater\"")
}
if (delta <= 0) {
stop("Argument delta out of bound, specify a value > 0")
}
if (alpha <= 0 || alpha >= 1) {
stop("Argument alpha out of bound, specify a value between 0 and 1")
}
if (beta <= 0 || beta >= 1) {
stop("Argument beta out of bound, specify a value between 0 and 1")
}
sample <- ifelse(is.null(y), "one.sample", "two.sample")
alternative <- ifelse(all(c("two.sided", "less", "greater") %in% alternative), "two.sided", alternative)
if (alternative == "two.sided") {
if ((pi + delta) >= 1 || (pi - delta) <= 0) {
stop("Value pi + delta or pi - delta out of bound")
}
} else {
if (sample == "one.sample") {
if (alternative == "less") {
if ((pi - delta) <= 0) {
stop("Value (pi - delta) out of bound")
}
} else {
if ((pi + delta) >= 1) {
stop("Value (pi + delta) out of bound")
}
}
} else {
if (alternative == "less") {
if ((pi + delta) >= 1) {
stop("Value (pi + delta) out of bound")
}
} else {
if ((pi - delta) <= 0) {
stop("Value (pi - delta) out of bound")
}
}
}
}
ifelse(alternative == "two.sided", u.1a <- qnorm(1 - alpha / 2), u.1a <- qnorm(1 - alpha))
u.1b <- qnorm(1 - beta)
if (alternative == "two.sided") {
if (sample == "one.sample") {
theta1 <- log(((pi - delta) * (1 - pi)) / (pi * (1 - (pi - delta))))
theta2 <- log(((pi + delta) * (1 - pi)) / (pi * (1 - (pi + delta))))
} else {
theta1 <- -log(((pi + delta) * (1 - pi)) / (pi * (1 - (pi + delta))))
theta2 <- -log(((pi - delta) * (1 - pi)) / (pi * (1 - (pi - delta))))
}
a1 <- (1 + u.1b / u.1a) * log(1 / (2 * alpha / 2)) / theta1
a2 <- (1 + u.1b / u.1a) * log(1 / (2 * alpha / 2)) / theta2
b1 <- theta1 / (2 * (1 + u.1b / u.1a))
b2 <- theta2 / (2 * (1 + u.1b / u.1a))
V.max <- c(a1 / b1, a2 / b2)
Z.max <- c(2 * a1, 2 * a2)
f1 <- function(x1) { -a1 + 3 * b1 * x1 }
f2 <- function(x2) { -a2 + 3 * b2 * x2 }
intersec <- uniroot(function(z) f1(z) - f2(z), interval = c(0, max(V.max)))$root
} else {
if (sample == "one.sample") {
if (alternative == "less") {
theta <- log(((pi - delta) * (1 - pi)) / (pi * (1 - (pi - delta))))
} else {
theta <- log(((pi + delta) * (1 - pi)) / (pi * (1 - (pi + delta))))
}
} else {
if (alternative == "less") {
theta <- -log(((pi + delta) * (1 - pi)) / (pi * (1 - (pi + delta))))
} else {
theta <- -log(((pi - delta) * (1 - pi)) / (pi * (1 - (pi - delta))))
}
}
a <- (1 + u.1b / u.1a) * log(1 / (2 * alpha)) / theta
b <- theta / (2 * (1 + u.1b / u.1a))
V.max <- a / b
Z.max <- 2 * a
}
if (sample == "one.sample") {
if (alternative == "two.sided") {
object <- list(call = match.call(),
type = "prop",
spec = list(pi = pi, alternative = alternative, sample = sample,
delta = delta, theta1 = theta1, theta2 = theta2,
alpha = alpha, beta = beta),
tri = list(a1 = a1, a2 = a2, b1 = b1, b2 = b2,
u.1a = u.1a, u.1b = u.1b,
V.max = V.max, Z.max = Z.max,
intersec = intersec),
dat = list(x = NULL, n = NULL),
res = list(V.m = NULL, Z.m = NULL, decision = "continue", step = 0))
} else {
object <- list(call = match.call(),
type = "prop",
spec = list(pi = pi, alternative = alternative, sample = sample,
delta = delta, theta = theta,
alpha = alpha, beta = beta),
tri = list(a = a, b = b,
u.1a = u.1a, u.1b = u.1b,
V.max = V.max, Z.max = Z.max),
dat = list(x = NULL, n = NULL),
res = list(V.m = NULL, Z.m = NULL, decision = "continue", step = 0))
}
} else {
if (alternative == "two.sided") {
object <- list(call = match.call(),
type = "prop",
spec = list(pi = pi, alternative = alternative, sample = sample,
delta = delta, theta1 = theta1, theta2 = theta2,
alpha = alpha, beta = beta),
tri = list(a1 = a1, a2 = a2, b1 = b1, b2 = b2,
u.1a = u.1a, u.1b = u.1b,
V.max = V.max, Z.max = Z.max,
intersec = intersec),
dat = list(x = NULL, y = NULL, n.1 = NULL, n.2 = NULL),
res = list(V.m = NULL, Z.m = NULL, decision = "continue", step = 0))
} else {
object <- list(call = match.call(),
type = "prop",
spec = list(pi = pi, alternative = alternative, sample = sample,
delta = delta, theta = theta,
alpha = alpha, beta = beta),
tri = list(a = a, b = b,
u.1a = u.1a, u.1b = u.1b,
V.max = V.max, Z.max = Z.max),
dat = list(x = NULL, y = NULL, n.1 = NULL, n.2 = NULL),
res = list(V.m = NULL, Z.m = NULL, decision = "continue", step = 0))
}
}
class(object) <- "seqtest"
print.step <- 0
if (object$spec$sample == "one.sample") {
print.max <- length(x)
for (x.i in x) {
print.step <- print.step + 1
object <- internal.seqtest.prop(object, x = x.i, initial = TRUE,
print.step = print.step, print.max = print.max, output = output, plot = plot)
if (object$res$decision != "continue") break
}
} else {
print.max <- length(c(x, y)) - 1
print.step <- print.step + 1
object <- internal.seqtest.prop(object, x = x[1], y = y[1], initial = TRUE,
print.step = print.step, print.max = print.max, output = output, plot = plot)
x.seq <- seq_along(x)
y.seq <- seq_along(y)
if (max(x.seq, y.seq) > 1) {
xy.sum <- sum(x.seq %in% y.seq)
if (xy.sum > 1) {
for (i in 2:xy.sum) {
print.step <- print.step + 1
object <- internal.seqtest.prop(object, x = x[i], initial = TRUE,
print.step = print.step, print.max = print.max, output = output, plot = plot)
if (object$res$decision != "continue") break
print.step <- print.step + 1
object <- internal.seqtest.prop(object, y = y[i], initial = TRUE,
print.step = print.step, print.max = print.max, output = output, plot = plot)
if (object$res$decision != "continue") break
}
}
if (length(x) > length(y) & object$res$decision == "continue") {
for (i in (xy.sum + 1):length(x)) {
print.step <- print.step + 1
object <- internal.seqtest.prop(object, x = x[i], initial = TRUE,
print.step = print.step, print.max = print.max, output = output, plot = plot)
if (object$res$decision != "continue") break
}
}
if (length(x) < length(y) & object$res$decision == "continue") {
for (i in (xy.sum + 1):length(y)) {
print.step <- print.step + 1
object <- internal.seqtest.prop(object, y = y[i], initial = TRUE,
print.step = print.step, print.max = print.max, output = output, plot = plot)
if (object$res$decision != "continue") break
}
}
}
}
return(invisible(object))
}
|
"stat_locs"
"apacpnut"
"apacpwq"
"apadbwq"
"apaebmet"
|
"ICEuncrt" <-
function (df, trtm, xeffe, ycost, lambda = 1, ceunit = "cost", R = 25000, seed = 0)
{
if (missing(df) || !inherits(df, "data.frame"))
stop("The first argument to ICEuncrt must be an existing Data Frame.")
if (lambda <= 0)
stop("The lambda argument to ICEuncrt must be strictly positive.")
if (ceunit != "effe")
ceunit <- "cost"
ICEuncol <- list(df = deparse(substitute(df)), lambda = lambda, ceunit = ceunit, R = R)
if (missing(trtm))
stop("The Second argument to ICEuncrt must name the Treatment factor.")
trtm <- deparse(substitute(trtm))
if (!is.element(trtm, dimnames(df)[[2]]))
stop("Treatment factor must be an existing Data Frame variable.")
if (length(table(df[, trtm])) != 2)
stop("Treatment factor must assume exactly two different levels.")
if (missing(xeffe))
stop("The Third argument to ICEuncrt must name the Treatment Effectiveness variable.")
xeffe <- deparse(substitute(xeffe))
if (!is.element(xeffe, dimnames(df)[[2]]))
stop("Effectiveness measure must be an existing Data Frame variable.")
if (missing(ycost))
stop("The Fourth argument to ICEuncrt must name the Treatment Cost variable.")
ycost <- deparse(substitute(ycost))
if (!is.element(ycost, dimnames(df)[[2]]))
stop("Cost measure must be an existing Data Frame variable.")
effcst <- na.omit(df[, c(trtm, xeffe, ycost)])
names(effcst) <- c("trtm", "effe", "cost")
effcst <- effcst[do.call(order, effcst), ]
if (ceunit != "cost")
effcst[, 3] <- effcst[, 3]/lambda
else effcst[, 2] <- effcst[, 2] * lambda
if (R > 25000)
R <- 25000
else if (R < 50)
R <- 50
idx <- table(as.numeric(effcst$trtm))
rowstd <- 1:idx[1]
rownew <- 1:idx[2] + idx[1]
nstd <- length(rowstd)
nnew <- nstd + length(rownew)
t1 <- ICEd2m(effcst, rownew, rowstd)
t <- matrix(rep(0, R * 2), nrow = R, ncol = 2)
if (seed == 0)
seed <- 1 + floor(25000 * runif(1))
set.seed(seed)
for (i in 1:R) {
rowstd <- ICErunif(1, nstd)
rownew <- ICErunif(nstd + 1, nnew)
t[i, ] <- ICEd2m(effcst, rownew, rowstd)
}
icer.bias <- t1[1] / t1[2]
icer.boot <- mean(t[,1]) / mean(t[,2])
icer.unbi <- 2 * icer.bias - icer.boot
ICEuncol <- c(ICEuncol, list(trtm = trtm, xeffe = xeffe, ycost = ycost, effcst = effcst,
t1 = t1, t = t, icer.bias = icer.bias, icer.boot = icer.boot, icer.unbi = icer.unbi,
seed = seed))
class(ICEuncol) <- "ICEuncrt"
ICEuncol
}
"plot.ICEuncrt" <-
function (x, lfact = 1, swu = FALSE, alibi = FALSE, ...)
{
if (missing(x) || !inherits(x, "ICEuncrt"))
stop("The first argument to plot(ICEuncrt) must be an ICEuncrt object.")
if (lfact > 0)
lambda <- lfact * x$lambda
else lambda <- x$lambda
ceunit <- x$ceunit
if (ceunit != "cost")
ceunit <- "effe"
if (swu) {
if (ceunit == "cost") {
ceunit <- "effe"
if (x$lambda != 1) {
x$t1[1] <- x$t1[1] / x$lambda
x$t[, 1] <- x$t[, 1] / x$lambda
x$t1[2] <- x$t1[2] / x$lambda
x$t[, 2] <- x$t[, 2] / x$lambda
}
}
else {
ceunit <- "cost"
if (x$lambda != 1) {
x$t1[1] <- x$t1[1] * x$lambda
x$t[, 1] <- x$t[, 1] * x$lambda
x$t1[2] <- x$t1[2] * x$lambda
x$t[, 2] <- x$t[, 2] * x$lambda
}
}
}
if (lfact != 1) {
x$lambda <- lambda
if (ceunit == "cost") {
x$t1[1] <- x$t1[1] * lfact
x$t[, 1] <- x$t[, 1] * lfact
}
else {
x$t1[2] <- x$t1[2] / lfact
x$t[, 2] <- x$t[, 2] / lfact
}
}
emax <- max(abs(max(x$t[, 1])), abs(min(x$t[, 1])))
cmax <- max(abs(max(x$t[, 2])), abs(min(x$t[, 2])))
if (alibi == FALSE) {
plot(x$t[, 1], x$t[, 2], ann = FALSE, type = "p", ylim = c(-cmax,
cmax), xlim = c(-emax, emax))
par(lty = 1)
abline(v = 0, h = 0)
par(lty = 2)
abline(v = x$t1[1], h = x$t1[2])
par(lty = 3)
abline(c(0, 1))
title(main = paste("ICE Alias Uncertainty for Lambda =",
lambda), xlab = "Effectiveness Difference", ylab = "Cost Difference",
sub = paste("Units =", ceunit, ": Bootstrap Reps =", x$R))
}
else {
amax <- max(emax, cmax)
plot(x$t[, 1], x$t[, 2], ann = FALSE, type = "p", ylim = c(-amax,
amax), xlim = c(-amax, amax))
par(lty = 1)
abline(v = 0, h= 0)
par(lty = 2)
abline(v = x$t1[1], h = x$t1[2])
par(lty = 3)
abline(c(0, 1))
title(main = paste("ICE Alibi Uncertainty for Lambda =",
lambda), xlab = "Effectiveness Difference", ylab = "Cost Difference",
sub = paste("Units =", ceunit, ": Bootstrap Reps =", x$R))
}
}
"print.ICEuncrt" <-
function (x, lfact = 1, swu = FALSE, ...)
{
if (missing(x) || !inherits(x, "ICEuncrt"))
stop("The first argument to print.ICEuncrt() must be an ICEuncrt object.")
cat("\nIncremental Cost-Effectiveness (ICE) Bivariate Bootstrap Uncertainty\n")
if (lfact > 0)
lambda <- lfact * x$lambda
else lambda <- x$lambda
ceunit <- x$ceunit
if (ceunit != "cost")
ceunit <- "effe"
if (swu) {
if (ceunit == "cost") {
ceunit <- "effe"
if (x$lambda != 1) {
x$t1[1] <- x$t1[1] / x$lambda
x$t[, 1] <- x$t[, 1] / x$lambda
x$t1[2] <- x$t1[2] / x$lambda
x$t[, 2] <- x$t[, 2] / x$lambda
}
}
else {
ceunit <- "cost"
if (x$lambda != 1) {
x$t1[1] <- x$t1[1] * x$lambda
x$t[, 1] <- x$t[, 1] * x$lambda
x$t1[2] <- x$t1[2] * x$lambda
x$t[, 2] <- x$t[, 2] * x$lambda
}
}
}
cat(paste("\nShadow Price = Lambda =", lambda))
cat(paste("\nBootstrap Replications, R =", x$R))
cat(paste("\nEffectiveness variable Name =", x$xeffe))
cat(paste("\n Cost variable Name =", x$ycost))
cat(paste("\n Treatment factor Name =", x$trtm))
cat(paste("\nNew treatment level is =", names(table(x$effcst[,1]))[2],
"and Standard level is =", names(table(x$effcst[,1]))[1], "\n"))
cat(paste("\nCost and Effe Differences are both expressed in",
ceunit, "units\n"))
if (lfact != 1) {
x$lambda <- lambda
if (ceunit == "cost") {
x$t1[1] <- x$t1[1] * lfact
x$t[, 1] <- x$t[, 1] * lfact
}
else {
x$t1[2] <- x$t1[2] / lfact
x$t[, 2] <- x$t[, 2] / lfact
}
}
cat(paste("\nObserved Treatment Diff =", round(x$t1[1], digits = 3)))
cat(paste("\nMean Bootstrap Trtm Diff =", round(mean(x$t[,1]), digits = 3), "\n"))
cat(paste("\nObserved Cost Difference =", round(x$t1[2], digits = 3)))
cat(paste("\nMean Bootstrap Cost Diff =", round(mean(x$t[,2]), digits = 3), "\n"))
cat(paste("\nConsistent (Biased) ICER =", round(x$icer.bias, digits = 4), "\n"))
cat(paste("\nBootstrap Mean ICE ratio =", round(x$icer.boot, digits = 4), "\n"))
cat(paste("\nUnbiased ICER estimate =", round(x$icer.unbi, digits = 4), "\n\n"))
}
|
pointsCovarModel <- function(feature, cov.var, studyplot=NULL, oneplot=FALSE){
options(scipen=999)
if(is.null(studyplot)==TRUE){
cov.var.copy <- cov.var
cov.var.copy[na.omit(cov.var.copy)] <- 1
studyplot <-rasterToPolygons(cov.var.copy, na.rm=TRUE, dissolve=TRUE)
} else {}
feature.ppp <- unmark(as.ppp(feature))
W <- maptools::as.owin.SpatialPolygons(studyplot)
spatstat.geom::Window(feature.ppp) <- W
cov.var.im <- spatstat.geom::as.im(cov.var)
PPM0 <- ppm(feature.ppp ~ 1)
PPM1 <- ppm(feature.ppp ~ cov.var.im)
kolmsmirn <- cdf.test(feature.ppp, cov.var.im)
areaundercurve <- spatstat.core::auc(feature.ppp, cov.var.im, high=FALSE)
model.comp <- anova(PPM0, PPM1, test="LRT")
if(oneplot==TRUE){
par(mfrow=c(2,2))
} else {}
anova.p <- model.comp$"Pr(>Chi)"[2]
anova.p.to.report <- ifelse(anova.p < 0.001, "< 0.001",
ifelse(anova.p < 0.01, "< 0.01",
ifelse(anova.p < 0.05, "< 0.05",
round(anova.p, 3))))
raster::plot(cov.var, main="Point pattern against the numeric covariate data", cex.main=0.75,
sub=paste0("Null Hypothesis (H0): Homogeneous Poisson process model\nAlternative Hyphotesis (H1): Inhomogeneous Poisson process model (intensity as loglinear function of the covariate)\nH1 ", ifelse(anova.p > 0.05, "is not", "is"), " a significant improvement over H0 (Likelihood Ratio p-value: ", anova.p.to.report,"; AUC: ", round(areaundercurve,3), ")"), cex.sub=0.70)
raster::plot(feature, add=TRUE, pch=20)
raster::plot(studyplot, add=TRUE)
plot(spatstat.core::effectfun(PPM1, names(PPM1$covariates), se.fit=TRUE),
main="Fitted intensity of the point pattern \nas (loglinear) function of the covariate",
cex.main=0.8,
cex.axis=0.7,
cex.lab=0.8, legend=TRUE)
plot(kolmsmirn, cex.main=0.8)
plot(spatstat.core::roc(PPM1),
main=paste0("ROC curve of the fitted intensity of point patter \nas (loglinear) function of the cavariate \nAUC: ", round(areaundercurve,3)),
cex.main=0.8)
results <- list("H0-model"=PPM0,
"H1-model"=PPM1,
"Model comparison (LRT)"=model.comp,
"AIC-H0"=AIC(PPM0),
"AIC-H1"=AIC(PPM1),
"KS test"=kolmsmirn,
"AUC"=areaundercurve)
par(mfrow = c(1,1))
return(results)
}
|
setGeneric(name="query",def=function(.Object, field, ...){standardGeneric("query")})
setMethod(f = "query",signature("webdata",'character'),
definition = function(.Object, field, ...){
field <- match.arg(field, c('variables','times'))
args <- list(fabric = .Object, ...)
values <- do.call(paste0(field,"_query"), args)
return(values)
}
)
setMethod(f = "query",signature("webdata",'missing'),
definition = function(.Object, field, ...){
stop('specify a field to query against for webdata object')
}
)
setMethod(f = "query",signature("character",'missing'),
definition = function(.Object, field, ...){
field <- match.arg(.Object, c('webdata'))
values <- do.call(paste0(field,"_query"), list(...))
return(values)
}
)
webdata_query <- function(csw_url = 'https://www.sciencebase.gov/catalog/item/54dd2326e4b08de9379b2fb1/csw'){
request = '<csw:GetRecords xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" service="CSW" version="2.0.2" resultType="results" outputSchema="http://www.isotc211.org/2005/gmd" maxRecords="1000">
<csw:Query typeNames="csw:Record">
<csw:ElementSetName>full</csw:ElementSetName>
</csw:Query>
</csw:GetRecords>'
xpath <- '//srv:containsOperations/srv:SV_OperationMetadata/srv:connectPoint/gmd:CI_OnlineResource/gmd:linkage/gmd:URL'
parentxpath <- paste0(xpath,paste(rep('/parent::node()[1]',6), collapse=''))
response <- gcontent(gPOST(url = csw_url, body = request, content_type_xml()))
namespaces = xml2::xml_ns(response)
urls <- lapply(xml2::xml_find_all(response, xpath, ns = namespaces),
xml2::xml_text)
abstracts = xml2::xml_text(xml2::xml_find_all(response,
paste0(parentxpath,'/gmd:abstract'),
ns = namespaces))
titles = xml2::xml_text(xml2::xml_find_all(response,
paste0(parentxpath,
'/gmd:citation/gmd:CI_Citation/gmd:title/gco:CharacterString'),
ns = namespaces))
group = list()
sort.ix <- sort(titles, index.return = TRUE)$ix
for (i in 1:length(urls)){
group[[i]] <- list(title = titles[sort.ix[i]], url=urls[[sort.ix[i]]], abstract = abstracts[sort.ix[i]])
}
types = unname(xml2::xml_attrs(xml2::xml_find_all(response,
parentxpath,
ns = namespaces)))
group[which(substr(types[sort.ix],1,7) != "OPeNDAP")] <- NULL
return(datagroup(group))
}
|
unmix <- function(x, pure, alpha, shift, power=1, format="matrix", quiet=FALSE) {
format <- match.arg(format, c("matrix","list"))
if (missing(alpha)) stopifnot(!missing(shift))
if (missing(shift)) stopifnot(!missing(alpha))
stopifnot(missing(shift) | missing(alpha))
stopifnot(power %in% 1:2)
stopifnot(nrow(x) == nrow(pure))
stopifnot(ncol(pure) > 1)
if (requireNamespace("pbapply", quietly=TRUE) & !quiet) {
lapply <- pbapply::pblapply
}
cor.msg <- "some columns of 'pure' are highly correlated (>.99 after VST),
may result in instabilty of unmix(). visually inspect correlations of 'pure'"
if (missing(shift)) {
stopifnot(alpha > 0)
vst <- function(q, alpha) ( 2 * asinh(sqrt(alpha * q)) - log(alpha) - log(4) ) / log(2)
pure.cor <- cor(vst(pure, alpha)); diag(pure.cor) <- 0
if (any(pure.cor > .99)) warning(cor.msg)
sumLossVST <- function(p, i, vst, alpha, power) {
sum(abs(vst(x[,i], alpha) - vst(pure %*% p, alpha))^power)
}
res <- lapply(seq_len(ncol(x)), function(i) {
optim(par=rep(1, ncol(pure)), fn=sumLossVST, gr=NULL, i, vst, alpha, power,
method="L-BFGS-B", lower=0, upper=100)$par
})
} else {
stopifnot(shift > 0)
vstSL <- function(q, shift) log(q + shift)
pure.cor <- cor(vstSL(pure, shift)); diag(pure.cor) <- 0
if (any(pure.cor > .99)) warning(cor.msg)
sumLossSL <- function(p, i, vst, shift, power) {
sum(abs(vstSL(x[,i], shift) - vstSL(pure %*% p, shift))^power)
}
res <- lapply(seq_len(ncol(x)), function(i) {
optim(par=rep(1, ncol(pure)), fn=sumLossSL, gr=NULL, i, vstSL, shift, power,
method="L-BFGS-B", lower=0, upper=100)$par
})
}
mix <- do.call(rbind, res)
mix <- mix / rowSums(mix)
colnames(mix) <- colnames(pure)
rownames(mix) <- colnames(x)
if (format == "matrix") {
return(mix)
} else {
fitted <- pure %*% t(mix)
cor <- if (missing(shift)) {
cor(vst(x, alpha), vst(fitted, alpha))
} else {
cor(vstSL(x, shift), vstSL(fitted, shift))
}
return(list(mix=mix, cor=diag(cor), fitted=fitted))
}
}
collapseReplicates <- function(object, groupby, run, renameCols=TRUE) {
if (!is.factor(groupby)) groupby <- factor(groupby)
groupby <- droplevels(groupby)
stopifnot(length(groupby) == ncol(object))
sp <- split(seq(along=groupby), groupby)
countdata <- sapply(sp, function(i) rowSums(assay(object)[,i,drop=FALSE]))
mode(countdata) <- "integer"
colsToKeep <- sapply(sp, `[`, 1)
collapsed <- object[,colsToKeep]
dimnames(countdata) <- dimnames(collapsed)
assay(collapsed) <- countdata
if (!missing(run)) {
stopifnot(length(groupby) == length(run))
colData(collapsed)$runsCollapsed <- sapply(sp, function(i) paste(run[i],collapse=","))
}
if (renameCols) {
colnames(collapsed) <- levels(groupby)
}
stopifnot(sum(as.numeric(assay(object))) == sum(as.numeric(assay(collapsed))))
collapsed
}
fpkm <- function(object, robust=TRUE) {
fpm <- fpm(object, robust=robust)
if ("avgTxLength" %in% assayNames(object)) {
exprs <- 1e3 * fpm / assays(object)[["avgTxLength"]]
if (robust) {
sf <- estimateSizeFactorsForMatrix(exprs)
exprs <- t(t(exprs)/sf)
return(exprs)
} else {
return(exprs)
}
}
if (is.null(mcols(object)$basepairs)) {
if (is(rowRanges(object), "GRangesList")) {
ubp <- DataFrame(basepairs = sum(width(reduce(rowRanges(object)))))
} else if (is(rowRanges(object), "GRanges")) {
ubp <- DataFrame(basepairs = width(rowRanges(object)))
}
if (all(ubp$basepairs == 0)) {
stop("rowRanges(object) has all ranges of zero width.
the user should instead supply a column, mcols(object)$basepairs,
which will be used to produce FPKM values")
}
if (is.null(mcols(mcols(object)))) {
mcols(object) <- ubp
} else {
mcols(ubp) <- DataFrame(type="intermediate",
description="count of basepairs in the union of all ranges")
mcols(object) <- cbind(mcols(object), ubp)
}
}
1e3 * sweep(fpm, 1, mcols(object)$basepairs, "/")
}
fpm <- function(object, robust=TRUE) {
noAvgTxLen <- !("avgTxLength" %in% assayNames(object))
if (robust & is.null(sizeFactors(object)) & noAvgTxLen) {
object <- estimateSizeFactors(object)
}
k <- counts(object)
library.sizes <- if (robust & noAvgTxLen) {
sizeFactors(object) * exp(mean(log(colSums(k))))
} else {
colSums(k)
}
1e6 * sweep(k, 2, library.sizes, "/")
}
normalizeGeneLength <- function(...) {
.Deprecated("tximport, a separate package on Bioconductor")
}
normTransform <- function(object, f=log2, pc=1) {
if (is.null(colnames(object))) {
colnames(object) <- seq_len(ncol(object))
}
if (is.null(sizeFactors(object)) & is.null(normalizationFactors(object))) {
object <- estimateSizeFactors(object)
}
nt <- f(counts(object, normalized=TRUE) + pc)
se <- SummarizedExperiment(
assays = nt,
colData = colData(object),
rowRanges = rowRanges(object),
metadata = metadata(object))
DESeqTransform(se)
}
integrateWithSingleCell <- function(res, dds, ...) {
stopifnot(is(res, "DESeqResults"))
stopifnot(is(dds, "DESeqDataSet"))
tximetaOrg <- metadata(dds)$txomeInfo$organism
if (!is.null(tximetaOrg)) {
org <- if (tximetaOrg == "Homo sapiens") {
"human"
} else if (tximetaOrg == "Mus musculus") {
"mouse"
} else {
stop("Only human and mouse are currently supported")
}
} else {
test.gene <- rownames(res)[1]
org <- if (substr(test.gene, 1, 4) == "ENSG") {
"human"
} else if (substr(test.gene, 1, 7) == "ENSMUSG") {
"mouse"
} else {
stop("Only human and mouse are currently supported")
}
}
message(paste("Your dataset appears to be", org, "\n"))
csv.file <- system.file("extdata/singleCellTab.csv", package="DESeq2")
tab <- read.csv(csv.file)
message(paste("Choose a",org,"single-cell dataset to integrate with (0 to cancel):\n"))
tab <- tab[tab$org == org,]
tab2 <- tab[,c("pkg","func","data", "pub","nCells","desc")]
tab2$data <- ifelse(is.na(tab2$data), "", tab2$data)
rownames(tab2) <- seq_len(nrow(tab2))
print(tab2[,1:3])
print(tab2[,4:6])
cat("\n")
message(paste("Choose a",org,"single-cell dataset to integrate with (0 to cancel):"))
menuOpts <- ifelse(is.na(tab$data), tab$func, paste(tab$func, tab$data, sep="-"))
ans <- menu(menuOpts)
if (ans == 0) stop("No scRNA-seq dataset selected")
pkg <- tab$pkg[ans]
if (!requireNamespace(package=pkg, quietly=TRUE)) {
message(paste0("Package: '",pkg, "' is not installed"))
ask <- askYesNo("Would you like to install the necessary data package?")
if (ask) {
if (!requireNamespace(package="BiocManager", quietly=TRUE)) {
stop("'BiocManager' required to install packages, install from CRAN")
}
BiocManager::install(pkg)
} else {
stop("Package would need to be installed")
}
if (requireNamespace(package=pkg, quietly=TRUE)) {
message("Data package was installed successfully")
} else {
stop("Data package still needs to be installed for integrateWithSingleCell to work")
}
}
require(pkg, character.only=TRUE)
if (pkg == "scRNAseq") {
if (is.na(tab$data[ans])) {
sce <- do.call(tab$func[ans], list(ensembl=TRUE, ...))
} else {
sce <- do.call(tab$func[ans], list(which=tab$data[ans], ensembl=TRUE, ...))
}
} else {
if (is.na(tab$data[ans])) {
sce <- do.call(tab$func[ans], list(...))
} else {
sce <- do.call(tab$func[ans], list(dataset=tab$data[ans], ...))
}
}
return(list(res=res, dds=dds, sce=sce))
}
|
cpa.sw.normal <- function(alpha = 0.05, power = 0.80, nclusters = NA,
nsubjects = NA, ntimes = NA, d = NA, ICC = NA,
rho_c = NA, rho_s = NA,
vart = NA,
tol = .Machine$double.eps^0.25){
needlist <- list(alpha, power, nclusters, nsubjects, ntimes, d, ICC, rho_c, rho_s, vart)
neednames <- c("alpha", "power", "nclusters", "nsubjects", "ntimes", "d", "ICC",
"rho_c", "rho_s", "vart")
needind <- which(unlist(lapply(needlist, is.na)))
if (length(needind) != 1) {
neederror = "Exactly one of 'alpha', 'power', 'nclusters', 'nsubjects', 'ntimes', 'd', 'ICC', 'rho_c', 'rho_s', and 'vart' must be NA."
stop(neederror)
}
target <- neednames[needind]
pwr <- quote({
DEFFc <- 1 + (nsubjects - 1)*ICC
r <- (nsubjects*ICC*rho_c + (1 - ICC)*rho_s)/DEFFc
DEFFr <- 3*ntimes*(1 - r)*(1 + ntimes*r)/( (ntimes^2 - 1)*(2 + ntimes*r) )
VIF <-DEFFr*DEFFc
zcrit <- qnorm(alpha/2, lower.tail = FALSE)
zstat <- abs(d)/sqrt( 4*vart/(nclusters*nsubjects*ntimes)*VIF )
pnorm(zcrit, zstat, lower.tail = FALSE)
})
if (is.na(alpha)) {
alpha <- stats::uniroot(function(alpha) eval(pwr) - power,
interval = c(1e-10, 1 - 1e-10),
tol = tol)$root
}
if (is.na(power)) {
power <- eval(pwr)
}
if (is.na(nclusters)) {
nclusters <- stats::uniroot(function(nclusters) eval(pwr) - power,
interval = c(2 + 1e-10, 1e+07),
tol = tol, extendInt = "upX")$root
}
if (is.na(nsubjects)) {
nsubjects <- stats::uniroot(function(nsubjects) eval(pwr) - power,
interval = c(2 + 1e-10, 1e+07),
tol = tol, extendInt = "upX")$root
}
if (is.na(ntimes)) {
ntimes <- stats::uniroot(function(ntimes) eval(pwr) - power,
interval = c(1 + 1e-10, 1e+07),
tol = tol, extendInt = "upX")$root
}
if (is.na(d)) {
d <- stats::uniroot(function(d) eval(pwr) - power,
interval = c(1e-07, 1e+07),
tol = tol, extendInt = "upX")$root
}
if (is.na(ICC)){
ICC <- stats::uniroot(function(ICC) eval(pwr) - power,
interval = c(1e-07, 1 - 1e-07),
tol = tol)$root
}
if (is.na(rho_c)){
rho_c <- stats::uniroot(function(rho_c) eval(pwr) - power,
interval = c(1e-07, 1 - 1e-07),
tol = tol)$root
}
if (is.na(rho_s)){
rho_s <- stats::uniroot(function(rho_s) eval(pwr) - power,
interval = c(1e-07, 1 - 1e-07),
tol = tol)$root
}
if (is.na(vart)) {
vart <- stats::uniroot(function(vart) eval(pwr) - power,
interval = c(1e-07, 1e+07),
tol = tol, extendInt = "downX")$root
}
structure(get(target), names = target)
}
|
vis_snps <- function(output=NULL, stacks_param=NULL){
snps <- var <- snps.80 <- NULL
snp.df<-output$snp
snp.df$var<-as.factor(snp.df$var)
snp.df$snps<-as.numeric(as.character(snp.df$snps))
snp.R80.df<-output$snp.R80
snp.R80.df$var<-as.factor(snp.R80.df$var)
snp.R80.df$snps.80<-as.numeric(as.character(snp.R80.df$snps.80))
cat("Visualize how different values of", stacks_param, "affect number of SNPs retained.
Density plot shows the distribution of the number of SNPs retained in each sample,
while the asterisk denotes the total number of SNPs retained at an 80% completeness cutoff.", "\n")
return(
ggplot2::ggplot(snp.df, ggplot2::aes(x = snps, y = var)) +
ggridges::geom_density_ridges(jittered_points = FALSE, alpha = .5) +
ggplot2::geom_point(snp.R80.df, mapping=ggplot2::aes(x=snps.80, y=var), pch=8, cex=3)+
ggplot2::theme_classic() +
ggplot2::labs(x = "SNPs retained", y = paste(stacks_param, "value")) +
ggplot2::theme(legend.position = "none")
)
}
|
context("Generic comorbidity calculation")
test_that("comorbid quick test", {
testres <- icd9_comorbid(two_pts, two_map, return_df = TRUE)
testres_cat_simple <- categorize_simple(two_pts, two_map,
return_df = TRUE,
id_name = "visit_id", code_name = "icd9"
)
trueres <- data.frame(
"visit_id" = c("visit01", "visit02"),
"malady" = c(FALSE, TRUE),
"ailment" = c(TRUE, FALSE),
stringsAsFactors = FALSE
)
expect_equal(testres, trueres)
expect_equal(testres_cat_simple, trueres)
testmat <- icd9_comorbid(two_pts, two_map, return_df = FALSE)
truemat <- matrix(c(FALSE, TRUE, TRUE, FALSE),
nrow = 2,
dimnames = list(c("visit01", "visit02"), c("malady", "ailment"))
)
expect_equal(testmat, truemat)
testresfac <- icd9_comorbid(two_pts_fac, two_map_fac, return_df = TRUE)
trueresfac <- data.frame(
"visit_id" = c("visit01", "visit02"),
"malady" = c(FALSE, TRUE),
"ailment" = c(TRUE, FALSE),
stringsAsFactors = TRUE
)
expect_equal(testresfac, trueresfac)
expect_equal(icd9_comorbid(two_pts, two_map_fac, return_df = FALSE), truemat)
expect_equal(icd9_comorbid(two_pts_fac, two_map, return_df = FALSE), truemat)
expect_equal(icd9_comorbid(two_pts_fac, two_map_fac, return_df = FALSE), truemat)
})
test_that("failing example", {
mydf <- data.frame(
visit_id = c("a", "b", "c"),
icd9 = c("441", "412.93", "042")
)
cmb <- icd9_comorbid_quan_deyo(mydf, short_code = FALSE, hierarchy = TRUE)
expect_false("names" %in% names(attributes(cmb)))
charlson(mydf, short_code = FALSE)
expect_is(charlson(mydf, short_code = FALSE, return_df = TRUE), "data.frame")
charlson_from_comorbid(cmb)
})
test_that("disordered visit_ids works by default", {
set.seed(1441)
rnd_ord <- sample(seq_along(test_twenty$visit_id))
dat <- test_twenty[rnd_ord, ]
tres <- icd9_comorbid(dat, icd9_map_ahrq)
cres <- icd9_comorbid(test_twenty, icd9_map_ahrq)
expect_equal(dim(tres), dim(cres))
expect_equal(sum(tres), sum(cres))
expect_true(setequal(rownames(tres), rownames(cres)))
expect_equal(colnames(tres), colnames(cres))
})
context("ICD-9 comorbidity calculations")
test_that("ahrq all comorbidities in one patient, no abbrev, hier", {
res <- icd9_comorbid_ahrq(ahrq_test_dat,
short_code = TRUE,
abbrev_names = FALSE,
hierarchy = TRUE, return_df = TRUE
)
expect_equal(dim(res), c(1, 30))
expect_true(setequal(c("visit_id", names_ahrq), names(res)))
expect_false(all(as.logical(res[1, unlist(names_ahrq)])))
expect_false(res[1, "Diabetes, uncomplicated"])
expect_false(res[1, "Solid tumor without metastasis"])
res <- icd9_comorbid_ahrq(ahrq_test_dat,
short_code = TRUE,
abbrev_names = FALSE,
hierarchy = TRUE, return_df = FALSE
)
expect_equal(dim(res), c(1, 29))
expect_true(setequal(names_ahrq, colnames(res)))
expect_false(all(as.logical(res[1, unlist(names_ahrq)])))
expect_false(res[1, "Diabetes, uncomplicated"])
expect_false(res[1, "Solid tumor without metastasis"])
})
test_that("empty data returns empty data with or without hierarchy", {
res <- icd9_comorbid_ahrq(empty_pts, hierarchy = FALSE)
res2 <- dim(icd9_comorbid_ahrq(empty_pts, hierarchy = TRUE))
res3 <- icd9_comorbid_ahrq(empty_pts, hierarchy = TRUE)
expect_identical(res, empty_ahrq_mat)
expect_identical(res2, dim(empty_ahrq_mat_heir))
expect_identical(res3, empty_ahrq_mat_heir)
})
test_that("elix, all cmb in one patient, no abbrev, hier", {
res <- icd9_comorbid_elix(elix_test_dat,
short_code = TRUE,
abbrev_names = FALSE,
hierarchy = TRUE, return_df = TRUE
)
expect_equal(dim(res), c(1, 31))
expect_true(setequal(c("visit_id", names_elix), names(res)))
expect_false(all(as.logical(res[1, unlist(names_elix)])))
expect_false(res[1, "Diabetes, uncomplicated"])
expect_false(res[1, "Solid tumor without metastasis"])
res <- icd9_comorbid_elix(elix_test_dat,
short_code = TRUE,
abbrev_names = FALSE,
hierarchy = TRUE, return_df = FALSE
)
expect_equal(dim(res), c(1, 30))
expect_true(setequal(names_elix, colnames(res)))
expect_false(all(as.logical(res[1, unlist(names_elix)])))
expect_false(res[1, "Diabetes, uncomplicated"])
expect_false(res[1, "Solid tumor without metastasis"])
})
test_that("elix, all cmb in one patient, abbrev, hier", {
res <- icd9_comorbid_elix(elix_test_dat,
short_code = TRUE,
abbrev_names = TRUE,
hierarchy = TRUE, return_df = TRUE
)
expect_equal(dim(res), c(1, 31))
expect_true(setequal(c("visit_id", names_elix_abbrev), names(res)))
expect_false(
all(as.logical(res[1, unlist(names_elix_abbrev)]))
)
expect_false(res[1, "DM"])
expect_false(res[1, "Tumor"])
res <- icd9_comorbid_elix(elix_test_dat,
short_code = TRUE,
abbrev_names = TRUE,
hierarchy = TRUE, return_df = FALSE
)
expect_equal(dim(res), c(1, 30))
expect_true(setequal(names_elix_abbrev, colnames(res)))
expect_false(
all(as.logical(res[1, unlist(names_elix_abbrev)]))
)
expect_false(res[1, "DM"])
expect_false(res[1, "Tumor"])
})
test_that("elix, all cmb in one patient, no abbrev, no hier", {
res <- icd9_comorbid_elix(elix_test_dat,
short_code = TRUE,
abbrev_names = FALSE,
hierarchy = FALSE, return_df = TRUE
)
expect_equal(dim(res), c(1, 32))
expect_true(setequal(c("visit_id", names_elix_htn), names(res)))
expect_true(all(as.logical(res[1, unlist(names_elix_htn)])))
res <- icd9_comorbid_elix(elix_test_dat,
short_code = TRUE,
abbrev_names = FALSE,
hierarchy = FALSE, return_df = FALSE
)
expect_equal(dim(res), c(1, 31))
expect_true(setequal(names_elix_htn, colnames(res)))
expect_true(all(as.logical(res[1, unlist(names_elix_htn)])))
})
test_that("elix, all cmb in one patient, abbrev, no hier", {
res <- icd9_comorbid_elix(elix_test_dat,
short_code = TRUE,
abbrev_names = TRUE,
hierarchy = FALSE, return_df = TRUE
)
expect_equal(dim(res), c(1, 32))
expect_true(setequal(c("visit_id", names_elix_htn_abbrev), names(res)))
expect_true(
all(as.logical(res[1, unlist(names_elix_htn_abbrev)]))
)
res <- icd9_comorbid_elix(elix_test_dat,
short_code = TRUE,
abbrev_names = TRUE,
hierarchy = FALSE, return_df = FALSE
)
expect_equal(dim(res), c(1, 31))
expect_true(setequal(names_elix_htn_abbrev, colnames(res)))
expect_true(
all(as.logical(res[1, unlist(names_elix_htn_abbrev)]))
)
})
test_that("qelix, all cmb in one patient, no abbrev, hier", {
res <- icd9_comorbid_quan_elix(quan_elix_test_dat,
short_code = TRUE, abbrev_names = FALSE,
hierarchy = TRUE, return_df = TRUE
)
expect_equal(dim(res), c(1, 31))
expect_true(setequal(c("visit_id", names_quan_elix), names(res)))
expect_false(
all(as.logical(res[1, unlist(names_quan_elix)]))
)
expect_false(res[1, "Diabetes, uncomplicated"])
expect_false(res[1, "Solid tumor without metastasis"])
res <- icd9_comorbid_quan_elix(quan_elix_test_dat,
short_code = TRUE,
abbrev_names = FALSE,
hierarchy = TRUE, return_df = FALSE
)
expect_equal(dim(res), c(1, 30))
expect_true(setequal(names_quan_elix, colnames(res)))
expect_false(
all(as.logical(res[1, unlist(names_quan_elix)]))
)
expect_false(res[1, "Diabetes, uncomplicated"])
expect_false(res[1, "Solid tumor without metastasis"])
})
test_that("qelix, cmb in one patient, abbrev, hier", {
res <- icd9_comorbid_quan_elix(quan_elix_test_dat,
short_code = TRUE,
abbrev_names = TRUE,
hierarchy = TRUE, return_df = TRUE
)
expect_equal(dim(res), c(1, 31))
expect_true(setequal(c("visit_id", names_quan_elix_abbrev), colnames(res)))
expect_false(
all(as.logical(res[1, unlist(names_quan_elix_abbrev)]))
)
expect_false(res[1, "DM"])
expect_false(res[1, "Tumor"])
res <- icd9_comorbid_quan_elix(quan_elix_test_dat,
short_code = TRUE,
abbrev_names = TRUE,
hierarchy = TRUE, return_df = FALSE
)
expect_equal(dim(res), c(1, 30))
expect_equal(rownames(res)[1], quan_elix_test_dat[1, "visit_id"])
expect_true(setequal(names_quan_elix_abbrev, colnames(res)))
expect_false(
all(as.logical(res[1, unlist(names_quan_elix_abbrev)]))
)
expect_false(res[1, "DM"])
expect_false(res[1, "Tumor"])
})
test_that("qelix, all cmb in one patient, no abbrev, no hier", {
res <- icd9_comorbid_quan_elix(quan_elix_test_dat,
short_code = TRUE,
abbrev_names = FALSE,
hierarchy = FALSE, return_df = TRUE
)
expect_equal(dim(res), c(1, 32))
expect_true(setequal(c("visit_id", names_quan_elix_htn), names(res)))
expect_true(
all(as.logical(res[1, unlist(names_quan_elix_htn)]))
)
res <- icd9_comorbid_quan_elix(quan_elix_test_dat,
short_code = TRUE,
abbrev_names = FALSE,
hierarchy = FALSE, return_df = FALSE
)
expect_equal(dim(res), c(1, 31))
expect_true(setequal(names_quan_elix_htn, colnames(res)))
expect_true(
all(as.logical(res[1, unlist(names_quan_elix_htn)]))
)
})
test_that("qelix, all cmb in one patient, abbrev, no hier", {
res <- icd9_comorbid_quan_elix(quan_elix_test_dat,
short_code = TRUE,
abbrev_names = TRUE,
hierarchy = FALSE, return_df = TRUE
)
expect_equal(dim(res), c(1, 32))
expect_true(setequal(c("visit_id", names_quan_elix_htn_abbrev), names(res)))
expect_true(
all(as.logical(res[1, unlist(names_quan_elix_htn_abbrev)]))
)
res <- icd9_comorbid_quan_elix(quan_elix_test_dat,
short_code = TRUE,
abbrev_names = TRUE,
hierarchy = FALSE, return_df = FALSE
)
expect_equal(dim(res), c(1, 31))
expect_true(setequal(names_quan_elix_htn_abbrev, colnames(res)))
expect_true(
all(as.logical(res[1, unlist(names_quan_elix_htn_abbrev)]))
)
})
test_that("ahrq, all cmb in one patient, abbrev, hier", {
res <- icd9_comorbid_ahrq(ahrq_test_dat,
short_code = TRUE,
abbrev_names = TRUE,
hierarchy = TRUE, return_df = TRUE
)
expect_equal(dim(res), c(1, 30))
expect_true(setequal(c("visit_id", names_ahrq_abbrev), names(res)))
expect_false(
all(as.logical(res[1, unlist(names_ahrq_abbrev)]))
)
expect_false(res[1, "DM"])
expect_false(res[1, "Tumor"])
res <- icd9_comorbid_ahrq(ahrq_test_dat,
short_code = TRUE,
abbrev_names = TRUE,
hierarchy = TRUE, return_df = FALSE
)
expect_equal(dim(res), c(1, 29))
expect_true(setequal(names_ahrq_abbrev, colnames(res)))
expect_false(
all(as.logical(res[1, unlist(names_ahrq_abbrev)]))
)
expect_false(res[1, "DM"])
expect_false(res[1, "Tumor"])
})
test_that("ahrq, all cmb in one patient, no abbrev, no hier", {
res <- icd9_comorbid_ahrq(ahrq_test_dat,
short_code = TRUE,
abbrev_names = FALSE,
hierarchy = FALSE, return_df = TRUE
)
expect_equal(dim(res), c(1, 31))
expect_true(setequal(c("visit_id", names_ahrq_htn), names(res)))
expect_true(all(as.logical(res[1, unlist(names_ahrq_htn)])))
res <- icd9_comorbid_ahrq(ahrq_test_dat,
short_code = TRUE,
abbrev_names = FALSE,
hierarchy = FALSE, return_df = FALSE
)
expect_equal(dim(res), c(1, 30))
expect_true(setequal(names_ahrq_htn, colnames(res)))
expect_true(all(as.logical(res[1, unlist(names_ahrq_htn)])))
})
test_that("ahrq, all cmb in one patient, abbrev, no hier", {
res <- icd9_comorbid_ahrq(ahrq_test_dat,
short_code = TRUE,
abbrev_names = TRUE,
hierarchy = FALSE, return_df = TRUE
)
expect_equal(dim(res), c(1, 31))
expect_true(setequal(c("visit_id", names_ahrq_htn_abbrev), names(res)))
expect_true(
all(as.logical(res[1, unlist(names_ahrq_htn_abbrev)]))
)
res <- icd9_comorbid_ahrq(ahrq_test_dat,
short_code = TRUE,
abbrev_names = TRUE,
hierarchy = FALSE, return_df = FALSE
)
expect_equal(dim(res), c(1, 30))
expect_true(setequal(names_ahrq_htn_abbrev, colnames(res)))
expect_true(
all(as.logical(res[1, unlist(names_ahrq_htn_abbrev)]))
)
})
test_that("Charlson/Deyo comorbidities for a single patient, one icd9", {
expect_equal(
icd9_comorbid_quan_deyo(one_pt_one_icd9, short_code = FALSE, return_df = TRUE),
structure(
list(
visit_id = "a",
MI = FALSE, CHF = FALSE, PVD = FALSE, Stroke = FALSE, Dementia = FALSE,
Pulmonary = FALSE, Rheumatic = FALSE, PUD = FALSE, LiverMild = FALSE,
DM = FALSE, DMcx = FALSE, Paralysis = FALSE, Renal = FALSE,
Cancer = FALSE, LiverSevere = FALSE, Mets = FALSE, HIV = TRUE
),
.Names = c(
"visit_id",
"MI", "CHF", "PVD", "Stroke", "Dementia", "Pulmonary",
"Rheumatic", "PUD", "LiverMild", "DM", "DMcx", "Paralysis",
"Renal", "Cancer", "LiverSevere", "Mets", "HIV"
),
row.names = 1L,
class = "data.frame"
)
)
})
test_that("no error for deyo single pt w two identical (major) icd9 codes", {
expect_error(icd9_comorbid_quan_deyo(one_pt_two_icd9, short_code = FALSE, return_df = TRUE), NA)
})
test_that("no error for deyo single pt w two different decimal icd9 codes", {
mydf <- data.frame(visit_id = c("a", "a"), icd9 = c("441", "412.93"))
expect_error(icd9_comorbid_quan_deyo(mydf), NA)
expect_error(icd9_comorbid_quan_deyo(mydf, short_code = FALSE, return_df = TRUE), NA)
})
test_that("dispatch from column class when specified", {
mydf <- data.frame(
visit_id = c("a", "b", "c"),
icd9 = icd:::icd9cm(c("412.93", "441", "042"))
)
expect_warning(icd9_comorbid_quan_elix(mydf), regexp = NA)
expect_warning(icd9_comorbid_quan_deyo(mydf), regexp = NA)
expect_warning(icd9_comorbid_elix(mydf), regexp = NA)
expect_warning(icd9_comorbid_ahrq(mydf), regexp = NA)
})
test_that("dispatch from column class when not specified", {
mydf <- data.frame(
visit_id = c("a", "b", "c"),
icd9 = c("412.93", "441", "042")
)
expect_warning(icd9_comorbid_quan_elix(mydf), regexp = NA)
expect_warning(icd9_comorbid_quan_deyo(mydf), regexp = NA)
expect_warning(icd9_comorbid_elix(mydf), regexp = NA)
expect_warning(icd9_comorbid_ahrq(mydf), regexp = NA)
})
test_that("if we try to do comorbidity calc on wide data, it works!", {
expect_error(comorbid_elix(vermont_dx),
regexp = NA
)
expect_error(comorbid_charlson(long_to_wide(uranium_pathology)),
regexp = NA
)
})
test_that("code appearing in two icd9 comorbidities", {
dat <- data.frame(id = 1, icd9 = c("123"))
map <- list(a = "123", b = "123")
expect_identical(
res <- icd9_comorbid(dat, map),
matrix(c(TRUE, TRUE),
nrow = 1,
dimnames = list("1", c("a", "b"))
)
)
dat_clean <- data.frame(
id = "1",
icd9 = factor("123"),
stringsAsFactors = FALSE
)
})
test_that("calling specific functions df binary output", {
for (f in list(
"icd9_comorbid_ahrq",
"icd9_comorbid_charlson",
"icd9_comorbid_elix",
"icd9_comorbid_pccc_dx",
"icd9_comorbid_quan_deyo",
"icd9_comorbid_quan_elix"
)) {
res <- do.call(f, args = list(random_test_patients,
return_binary = TRUE,
return_df = TRUE
))
expect_true(all(vapply(res[-1],
FUN = is.integer,
FUN.VALUE = logical(1)
)),
info = f
)
}
})
test_that("comorbid for icd9 gives binary values if asked for matrices", {
for (map in list(
icd9_map_charlson,
icd9_map_ahrq,
icd9_map_elix,
icd9_map_quan_elix,
icd9_map_quan_deyo
)) {
res_bin <- comorbid(random_test_patients,
map = map,
return_binary = TRUE, return_df = FALSE
)
res_log <- comorbid(random_test_patients,
map = map,
return_binary = FALSE, return_df = FALSE
)
expect_true(is.integer(res_bin))
expect_true(is.logical(res_log))
expect_equivalent(apply(res_log, 2, as.integer), res_bin)
expect_identical(res_bin, logical_to_binary(res_log))
expect_identical(res_log, binary_to_logical(res_bin))
}
})
test_that("comorbid for icd9 gives binary values if asked for data.frames", {
for (map in list(
icd9_map_charlson,
icd9_map_ahrq,
icd9_map_elix,
icd9_map_quan_elix,
icd9_map_quan_deyo
)) {
res_bin <- comorbid(random_test_patients,
map = icd9_map_charlson,
return_binary = TRUE, return_df = TRUE
)
res_log <- comorbid(random_test_patients,
map = icd9_map_charlson,
return_binary = FALSE, return_df = TRUE
)
expect_true(all(vapply(res_bin[-1], is.integer, logical(1))))
expect_true(all(vapply(res_log[-1], is.logical, logical(1))))
expect_identical(res_bin, logical_to_binary(res_log))
expect_identical(res_log, binary_to_logical(res_bin))
}
})
test_that("binary output for CCS", {
res_bin <- comorbid_ccs(random_test_patients,
return_binary = TRUE, return_df = TRUE
)
res_log <- comorbid_ccs(random_test_patients,
return_binary = FALSE, return_df = TRUE
)
expect_true(all(vapply(res_bin[-1], is.integer, logical(1))))
expect_true(all(vapply(res_log[-1], is.logical, logical(1))))
expect_identical(res_bin, logical_to_binary(res_log))
expect_identical(res_log, binary_to_logical(res_bin))
})
test_that("integer visit IDs", {
d <- ahrq_test_dat
d$visit_id <- -1L
mat_res <- comorbid_ahrq(d)
expect_identical(rownames(mat_res), as.character(unique(d$visit_id)))
df_res <- comorbid_ahrq(d, return_df = TRUE, preserve_id_type = TRUE)
expect_identical(df_res$visit_id, d[1, "visit_id"])
})
test_that("float visit IDs", {
d <- ahrq_test_dat
d$visit_id <- -1.7
mat_res <- comorbid_ahrq(d)
expect_identical(rownames(mat_res), as.character(unique(d$visit_id)))
df_res <- comorbid_ahrq(d, return_df = TRUE, preserve_id_type = TRUE)
expect_identical(df_res$visit_id, d[1, "visit_id"])
})
test_that("plot comorbid", {
expect_error(
regexp = NA,
plot_comorbid(vermont_dx[1:1000, ])
)
expect_error(
regexp = NA,
plot_comorbid(uranium_pathology)
)
})
|
tx_vl_unsuppressed <- function(data,
ref = NULL,
states = NULL,
facilities = NULL,
status = "calculated",
n = 1000) {
ref <- lubridate::ymd(ref %||% get("Sys.Date")())
states <- states %||% unique(data$state)
facilities <- facilities %||% unique(subset(data, state %in% states)$facility)
validate_vl_unsuppressed(data, ref, states, facilities, status, n)
get_tx_vl_unsuppressed(data, ref, states, facilities, status, n)
}
validate_vl_unsuppressed <- function(data,
ref,
states,
facilities,
status,
n) {
if (!all(states %in% unique(data$state))) {
rlang::abort("state(s) is not contained in the supplied data. Check the spelling and/or case.")
}
if (!all(facilities %in% unique(subset(data, state %in% states)$facility))) {
rlang::abort("facilit(ies) is/are not found in the data or state supplied.
Check that the facility is correctly spelt and located in the state.")
}
if (is.na(ref)) {
rlang::abort("The supplied date is not in 'yyyy-mm-dd' format.")
}
if (!status %in% c("default", "calculated")) {
rlang::abort("`status` can only be one of 'default' or 'calculated'. Check that you did not mispell, include CAPS or forget to quotation marks!")
}
if (n < 0) {
rlang::abort("n cannot be less than zero")
}
}
get_tx_vl_unsuppressed <- function(data, ref, states, facilities, status, n) {
switch(status,
"calculated" = dplyr::filter(
data,
current_status == "Active",
!patient_has_died %in% TRUE,
!patient_transferred_out %in% TRUE,
lubridate::as_date(ref) - art_start_date >=
lubridate::period(6, "months"),
dplyr::if_else(
current_age < 20,
lubridate::as_date(ref) -
date_of_current_viral_load <=
lubridate::period(6, "months"),
lubridate::as_date(ref) -
date_of_current_viral_load <=
lubridate::period(1, "year")
),
current_viral_load >= n,
state %in% states,
facility %in% facilities
),
"default" = dplyr::filter(
data,
current_status_28_days == "Active",
!patient_has_died %in% TRUE,
!patient_transferred_out %in% TRUE,
lubridate::as_date(ref) - art_start_date >=
lubridate::period(6, "months"),
dplyr::if_else(
current_age < 20,
lubridate::as_date(ref) -
date_of_current_viral_load <=
lubridate::period(6, "months"),
lubridate::as_date(ref) -
date_of_current_viral_load <=
lubridate::period(1, "year")
),
current_viral_load >= n,
state %in% states,
facility %in% facilities
)
)
}
utils::globalVariables(c(
"art_start_date",
"current_age",
"current_status",
"date_of_current_viral_load",
"current_viral_load"
))
|
test_that("oanda error handling ok", {
expect_error(oanda("USD_JPY", apikey = NULL, from = "a", to = "b"), regexp = "value of 'from'")
expect_error(oanda("usd_jpy", apikey = NULL, from = "2021-01-01", to = "b"), regexp = "value of 'to'")
expect_error(oanda("USD-JPY", apikey = NULL, from = "2021-01-01", to = "2020-01-01"), regexp = "time period invalid")
expect_error(oanda("usd-jpy", apikey = NULL, from = "a"), regexp = "value of 'from'")
expect_error(oanda("USD_JPY", apikey = NULL, to = "b"), regexp = "value of 'to'")
})
test_that("oanda switch ok", {
expect_message(expect_invisible(oanda_switch()), regexp = "switched to 'live'")
expect_message(expect_invisible(oanda_switch()), regexp = "switched to 'practice'")
})
|
print.cccUst<-
function(x,...)
{
cat("CCC estimated by U-statistics: \n")
print(x[1:4])
cat("\n")
}
|
sewma.sf <- function(n, l, cl, cu, sigma, df, hs=1, sided="upper", r=40, qm=30) {
if ( n < 1 ) stop("n has to be a natural number")
if ( l <= 0 | l > 1 ) stop("l (lambda) has to be between 0 and 1")
if ( cu<=0 ) stop("cu has to be positive")
if ( cl<0 ) stop("cl has to be non-negative")
if ( sided!="upper" & cl<1e-6 ) stop("cl is too small")
if ( sigma<=0 ) stop("sigma must be positive")
if ( df<1 ) stop("df must be larger than or equal to 1")
if ( hs<cl | hs>cu ) stop("wrong headstart hs")
if ( r<10 ) stop("r is too small")
ctyp <- pmatch(sided, c("upper","Rupper","two","Rlower")) - 1
if (is.na(ctyp)) stop("invalid ewma type")
if ( qm<5 ) stop("qm is too small")
sf <- .C("sewma_sf",
as.integer(ctyp), as.double(l), as.double(cl), as.double(cu), as.double(hs), as.integer(r),
as.double(sigma), as.integer(df), as.integer(qm), as.integer(n),
ans=double(length=n),PACKAGE="spc")$ans
names(sf) <- NULL
sf
}
|
crossStat <- function(var1, var2="PM10", STxDF=DE_RB_2005, digits=NA) {
diff <- STxDF[,,var1,drop=F]@data[[1]] - STxDF[,,var2,drop=F]@data[[1]]
RMSE <- sqrt(mean(diff^2))
MAE <- mean(abs(diff))
ME <- mean(diff)
COR <- cor(STxDF[,,var1,drop=F]@data[[1]], STxDF[,,var2,drop=F]@data[[1]])
res <- c(RMSE, MAE, ME, COR)
names(res) <- c("RMSE", "MAE", "ME", "COR")
if(is.na(digits))
return(res)
else
return(round(res, digits))
}
DE_RB_2005 <- as(DE_RB_2005, "STSDF")
pureSp <- NULL
for(i in 1:365) {
pureSp <- c(pureSp, krige.cv(PM10~1,DE_RB_2005[,i,"PM10"],
model=spVgmMod, nmax=10)$var1.pred)
}
DE_RB_2005@data$pureSp10Nghbr <- pureSp
pureSp <- NULL
for(i in 1:365) {
pureSp <- c(pureSp, krige.cv(PM10~1,DE_RB_2005[,i,"PM10"],model=spVgmMod,nmax=50)$var1.pred)
}
DE_RB_2005@data$pureSp50Nghbr <- pureSp
target <- as(DE_RB_2005[,,"PM10"],"STFDF")
res <- matrix(NA, length(DE_RB_2005@sp), 365)
for(loc in 1:length(DE_RB_2005@sp)) {
cat("Location", loc, "\n")
res[loc,!is.na(target[loc,])[,"PM10"]] <- krigeST(PM10~1, data=DE_RB_2005[(1:length(DE_RB_2005@sp))[-loc],],
newdata=DE_RB_2005[loc,,drop=F],
fitSepModel, nmax=10,
stAni=fitMetricModel$stAni/24/3600)$var1.pred
}
DE_RB_2005@data$sepModel10Nghbr <- as.vector(res)[!is.na(as.vector(res))]
res <- matrix(NA, length(DE_RB_2005@sp), 365)
for(loc in 1:length(DE_RB_2005@sp)) {
cat("Location", loc, "\n")
res[loc,!is.na(target[loc,])[,"PM10"]] <- krigeST(PM10~1, data=DE_RB_2005[(1:length(DE_RB_2005@sp))[-loc],],
newdata=DE_RB_2005[loc,,drop=F],
fitSepModel, nmax=50,
stAni=fitMetricModel$stAni/24/3600)$var1.pred
}
DE_RB_2005@data$sepModel50Nghbr <- as.vector(res)[!is.na(as.vector(res))]
res <- matrix(NA, length(DE_RB_2005@sp), 365)
for(loc in 1:length(DE_RB_2005@sp)) {
cat("Location", loc, "\n")
res[loc,!is.na(target[loc,])[,"PM10"]] <- krigeST(PM10~1, data=DE_RB_2005[(1:length(DE_RB_2005@sp))[-loc],],
newdata=DE_RB_2005[loc,,drop=F],
fitProdSumModel, nmax=10,
stAni=fitMetricModel$stAni/24/3600)$var1.pred
}
DE_RB_2005@data$psModel10Nghbr <- as.vector(res)[!is.na(as.vector(res))]
res <- matrix(NA, length(DE_RB_2005@sp), 365)
for(loc in 1:length(DE_RB_2005@sp)) {
cat("Location", loc, "\n")
res[loc,!is.na(target[loc,])[,"PM10"]] <- krigeST(PM10~1, data=DE_RB_2005[(1:length(DE_RB_2005@sp))[-loc],],
newdata=DE_RB_2005[loc,,drop=F],
fitProdSumModel, nmax=50,
stAni=fitMetricModel$stAni/24/3600)$var1.pred
}
DE_RB_2005@data$psModel50Nghbr <- as.vector(res)[!is.na(as.vector(res))]
res <- matrix(NA, length(DE_RB_2005@sp), 365)
for(loc in 1:length(DE_RB_2005@sp)) {
cat("Location", loc, "\n")
res[loc,!is.na(target[loc,])[,"PM10"]] <- krigeST(PM10~1, data=DE_RB_2005[(1:length(DE_RB_2005@sp))[-loc],],
newdata=DE_RB_2005[loc,,drop=F],
fitMetricModel, nmax=10,
stAni=fitMetricModel$stAni/24/3600)$var1.pred
}
DE_RB_2005@data$metricModel10Nghbr <- as.vector(res)[!is.na(as.vector(res))]
res <- matrix(NA, length(DE_RB_2005@sp), 365)
for(loc in 1:length(DE_RB_2005@sp)) {
cat("Location", loc, "\n")
res[loc,!is.na(target[loc,])[,"PM10"]] <- krigeST(PM10~1, data=DE_RB_2005[(1:length(DE_RB_2005@sp))[-loc],],
newdata=DE_RB_2005[loc,,drop=F],
fitMetricModel, nmax=50,
stAni=fitMetricModel$stAni/24/3600)$var1.pred
}
DE_RB_2005@data$metricModel50Nghbr <- as.vector(res)[!is.na(as.vector(res))]
res <- matrix(NA, length(DE_RB_2005@sp), 365)
for(loc in 1:length(DE_RB_2005@sp)) {
cat("Location", loc, "\n")
res[loc,!is.na(target[loc,])[,"PM10"]] <- krigeST(PM10~1, data=DE_RB_2005[(1:length(DE_RB_2005@sp))[-loc],],
newdata=DE_RB_2005[loc,,drop=F],
fitSumMetricModel, nmax=10,
stAni=fitMetricModel$stAni/24/3600)$var1.pred
}
DE_RB_2005@data$sumMetricModel10Nghbr <- as.vector(res)[!is.na(as.vector(res))]
res <- array(NA, c(length(DE_RB_2005@sp), 365,2))
for(loc in 1:length(DE_RB_2005@sp)) {
cat("Location", loc, "\n")
res[loc,!is.na(target[loc,])[,"PM10"],] <- as.matrix(krigeST(PM10~1, data=DE_RB_2005[(1:length(DE_RB_2005@sp))[-loc],],
newdata=DE_RB_2005[loc,,drop=F],
fitSumMetricModel, nmax=50,
computeVar=T,
stAni=linStAni*1000/24/3600)@data[,c("var1.pred","var1.var")])
}
DE_RB_2005@data$sumMetricModel50Nghbr <- as.vector(res[,,1])[!is.na(target@data)]
DE_RB_2005@data$sumMetricModel50NghbrVar <- as.vector(res[,,2])[!is.na(target@data)]
DE_RB_2005@data$sumMetricModel50Nghbr95u <- apply(DE_RB_2005@data, 1,
function(x) {
qnorm(0.975, x["sumMetricModel50Nghbr"],
sqrt(x["sumMetricModel50NghbrVar"]))
})
DE_RB_2005@data$sumMetricModel50Nghbr95l <- apply(DE_RB_2005@data, 1,
function(x) {
qnorm(0.025, x["sumMetricModel50Nghbr"],
sqrt(x["sumMetricModel50NghbrVar"]))
})
res <- matrix(NA, length(DE_RB_2005@sp), 365)
for(loc in 1:length(DE_RB_2005@sp)) {
cat("Location", loc, "\n")
res[loc,!is.na(target[loc,])[,"PM10"]] <- krigeST(PM10~1, data=DE_RB_2005[(1:length(DE_RB_2005@sp))[-loc],],
newdata=DE_RB_2005[loc,,drop=F],
fitSimpleSumMetricModel, nmax=10,
stAni=fitMetricModel$stAni/24/3600)$var1.pred
}
DE_RB_2005@data$simpleSumMetricModel10Nghbr <- as.vector(res)[!is.na(as.vector(res))]
res <- matrix(NA, length(DE_RB_2005@sp), 365)
for(loc in 1:length(DE_RB_2005@sp)) {
cat("Location", loc, "\n")
res[loc,!is.na(target[loc,])[,"PM10"]] <- krigeST(PM10~1, data=DE_RB_2005[(1:length(DE_RB_2005@sp))[-loc],],
newdata=DE_RB_2005[loc,,drop=F],
fitSimpleSumMetricModel, nmax=50,
stAni=fitMetricModel$stAni/24/3600)$var1.pred
}
DE_RB_2005@data$simpleSumMetricModel50Nghbr <- as.vector(res)[!is.na(as.vector(res))]
rbind(
crossStat("pureSp10Nghbr", digits=2),
crossStat("pureSp50Nghbr", digits=2),
crossStat("sepModel10Nghbr", digits=2),
crossStat("sepModel50Nghbr", digits=2),
crossStat("psModel10Nghbr", digits=2),
crossStat("psModel50Nghbr", digits=2),
crossStat("metricModel10Nghbr", digits=2),
crossStat("metricModel50Nghbr", digits=2),
crossStat("sumMetricModel10Nghbr", digits=2),
crossStat("sumMetricModel50Nghbr", digits=2))
if(paper) {
texRow <- function(x) {
paste(paste(x,collapse=" & ")," \\\\ \n")
}
cat(apply(round(rbind(crossStat("pureSp10Nghbr"),
crossStat("sepModel10Nghbr"),
crossStat("psModel10Nghbr"),
crossStat("metricModel10Nghbr"),
crossStat("sumMetricModel10Nghbr"),
crossStat("simpleSumMetricModel50Nghbr"),
crossStat("pureSp50Nghbr"),
crossStat("sepModel50Nghbr"),
crossStat("psModel50Nghbr"),
crossStat("metricModel50Nghbr"),
crossStat("sumMetricModel50Nghbr"),
crossStat("simpleSumMetricModel50Nghbr")
),
2),1,texRow))
loc <- 38
tw <- "2005-01-15/2005-04-15"
png("vignettes/figures/singleStationTimeSeries.png", 9, 4, "in", bg="white", res = 149)
plot(DE_RB_2005[loc,tw][,"sumMetricModel50Nghbr"], main=paste("Location", DE_RB_2005@sp@data$station_european_code[loc]),
ylim=c(0,70))
points(DE_RB_2005[loc,tw][,"PM10"], type="l", col="darkgreen", lty=1)
points(DE_RB_2005[loc,tw][,"sumMetricModel50Nghbr95u"], type="l", col="darkgrey", lty=2)
points(DE_RB_2005[loc,tw][,"sumMetricModel50Nghbr95l"], type="l", col="darkgrey", lty=2)
legend("topright",legend = c("observed","sum-metric","95 % prediction band"), lty=c(1,1,2),
col=c("darkgreen", "black", "darkgrey") )
dev.off()
DE_RB_2005@data$diffPM10 <- DE_RB_2005@data$sumMetricModel50Nghbr - DE_RB_2005@data$PM10
stpl <- stplot(as(DE_RB_2005[,smplDays, "diffPM10"],"STFDF"),
col.regions=bpy.colors(5),
sp.layout = list("sp.polygons", DE_NUTS1), scales=list(draw=F),
key.space="right", colorkey=T, cuts=c(-25,-15,-5,5,15,25),
main=NULL)
png("vignettes/figures/diffs_daily_means_PM10.png", width=9, height=6, "in", res=150)
print(stpl)
dev.off()
}
|
rotatev <- function(mat) {
matV <- mat;
elementi <- rev(mat);
matV <- array(elementi, dim=c(nrow(mat), ncol(mat)));
for(i in 1:ncol(matV)) {
matV[,i] <- rev(matV[,i]);
}
return(matV);
}
|
tdROC <- function( X, Y, delta, tau, span = 0.1, h=NULL, type="uniform", cut.off = NULL,
nboot = 0, alpha = 0.05, n.grid = 1000,
X.min = NULL, X.max = NULL ) {
n <- length(X) ;
positive <- rep(NA, n) ;
for (i in 1:n) {
if ( Y[i] > tau ) {
positive[i] <- 0 ;
} else {
if ( delta[i] == 1 ) {
positive[i] <- 1 ;
} else {
kw <- calc.kw( X=X, x0=X[i], span=span, h=h, type=type ) ;
fm <- survfit( Surv(Y, delta) ~ 1, weights = kw ) ;
tmp <- summary(fm, times = c(Y[i], tau))$surv ;
if ( tmp[1] == 0 ) {
positive[i] <- 1 ;
} else {
positive[i] <- 1 - tmp[2]/tmp[1] ;
}
}
}
}
negative <- 1 - positive ;
if ( is.null(X.min) ) { X.min <- min(X) }
if ( is.null(X.max) ) { X.max <- max(X) }
grid <- c( -Inf, seq( X.min, X.max, length=n.grid ), Inf ) ;
sens <- spec <- NULL ;
for (this.c in grid ) {
sens <- c( sens, sum(positive*as.numeric(X > this.c))/sum(positive) ) ;
spec <- c( spec, sum(negative*as.numeric(X <= this.c))/sum(negative) ) ;
}
ROC <- data.frame( grid = grid,
sens = sens,
spec = spec ) ;
AUC <- data.frame( value = calc.AUC( sens, spec ),
sd = NA,
lower = NA,
upper = NA ) ;
W <- positive ;
numer <- denom <- 0 ;
for (i in 1:n) {
for (j in 1:n) {
numer <- numer + W[i]*(1-W[j])*( as.numeric(X[i] > X[j]) +
0.5*as.numeric(X[i] == X[j]) ) ;
denom <- denom + W[i]*(1-W[j]) ;
}
}
AUC2 <- data.frame( value = numer/denom ,
sd = NA, lower = NA, upper = NA ) ;
sens <- spec <- NULL ;
if ( !is.null(cut.off) ) {
for (this.c in cut.off ) {
sens <- c( sens, sum(positive*as.numeric(X > this.c))/sum(positive) ) ;
spec <- c( spec, sum(negative*as.numeric(X <= this.c))/sum(negative) ) ;
}
prob <- data.frame( cut.off = cut.off,
sens = sens,
spec = spec ) ;
} else {
prob <- NULL ;
}
if ( nboot > 0 ) {
boot.AUC <- boot.AUC2 <- rep(NA, nboot) ;
if ( !is.null(cut.off) ) {
boot.sens <- matrix( NA, nrow=nboot, ncol=length(cut.off) ) ;
boot.spec <- matrix( NA, nrow=nboot, ncol=length(cut.off) ) ;
}
set.seed(123) ;
for (b in 1:nboot) {
loc <- sample( x = 1:n, size = n, replace = T ) ;
X2 <- X[loc] ;
Y2 <- Y[loc] ;
delta2 <- delta[loc] ;
out <- tdROC( X2, Y2, delta2, tau, span, nboot = 0, alpha, n.grid,
cut.off = cut.off, X.min = X.min, X.max = X.max ) ;
boot.AUC[b] <- out$AUC$value ;
boot.AUC2[b] <- out$AUC2$value ;
if ( !is.null(cut.off) ) {
boot.sens[b, ] <- out$prob$sens ;
boot.spec[b, ] <- out$prob$spec ;
}
}
tmp1 <- sd(boot.AUC) ;
tmp2 <- as.numeric( quantile( boot.AUC, prob = c(alpha/2, 1-alpha/2) ) ) ;
AUC$sd <- tmp1 ;
AUC$lower <- tmp2[1] ;
AUC$upper <- tmp2[2] ;
tmp1 <- sd(boot.AUC2) ;
tmp2 <- as.numeric( quantile( boot.AUC2, prob = c(alpha/2, 1-alpha/2) ) ) ;
AUC2$sd <- tmp1 ;
AUC2$lower <- tmp2[1] ;
AUC2$upper <- tmp2[2] ;
if ( !is.null(cut.off) ) {
prob$sens.sd <- apply( boot.sens, 2, sd ) ;
prob$sens.lower <- apply( boot.sens, 2, quantile, prob = alpha/2 ) ;
prob$sens.upper <- apply( boot.sens, 2, quantile, prob = 1-alpha/2 ) ;
prob$spec.sd <- apply( boot.spec, 2, sd ) ;
prob$spec.lower <- apply( boot.spec, 2, quantile, prob = alpha/2 ) ;
prob$spec.upper <- apply( boot.spec, 2, quantile, prob = 1-alpha/2 ) ;
} else {
prob$sens.sd <- NA ;
prob$sens.lower <- NA ;
prob$sens.upper <- NA ;
prob$spec.sd <- NA ;
prob$spec.lower <- NA ;
prob$spec.upper <- NA ;
}
}
pct.ctrl <- mean( Y > tau ) ;
pct.case <- mean( Y <= tau & delta == 1 ) ;
pct.not.sure <- mean( Y <= tau & delta == 0 ) ;
return( list( ROC = ROC, AUC = AUC, AUC2 = AUC2, prob = prob ) ) ;
}
|
linrmir <- function(Y, id = NULL, age, weight = NULL,
sort = NULL, Dom = NULL, period = NULL,
dataset = NULL, order_quant = 50,
var_name = "lin_rmir", checking = TRUE) {
if (min(dim(data.table(var_name)) == 1) != 1) {
stop("'var_name' must have defined one name of the linearized variable")}
if (checking) {
order_quant <- check_var(vars = order_quant, varn = "order_quant",
varntype = "numeric0100")
Y <- check_var(vars = Y, varn = "Y", dataset = dataset,
ncols = 1, isnumeric = TRUE,
isvector = TRUE, grepls = "__")
Ynrow <- length(Y)
age <- check_var(vars = age, varn = "age",
dataset = dataset, ncols = 1,
Ynrow = Ynrow, isnumeric = TRUE,
isvector = TRUE)
weight <- check_var(vars = weight, varn = "weight",
dataset = dataset, ncols = 1,
Ynrow = Ynrow, isnumeric = TRUE,
isvector = TRUE)
sort <- check_var(vars = sort, varn = "sort",
dataset = dataset, ncols = 1,
Ynrow = Ynrow, mustbedefined = FALSE,
isnumeric = TRUE, isvector = TRUE)
period <- check_var(vars = period, varn = "period",
dataset = dataset, Ynrow = Ynrow,
ischaracter = TRUE, mustbedefined = FALSE,
duplicatednames = TRUE)
Dom <- check_var(vars = Dom, varn = "Dom", dataset = dataset,
Ynrow = Ynrow, ischaracter = TRUE,
mustbedefined = FALSE, duplicatednames = TRUE,
grepls = "__")
id <- check_var(vars = id, varn = "id", dataset = dataset,
ncols = 1, Ynrow = Ynrow, ischaracter = TRUE,
periods = period)
}
ind0 <- rep.int(1, length(Y))
period_agg <- period1 <- NULL
if (!is.null(period)) { period1 <- copy(period)
period_agg <- data.table(unique(period))
} else period1 <- data.table(ind=ind0)
period1_agg <- data.table(unique(period1))
age_under_65s <- data.table(age_under_65s = as.integer(age < 65))
if (!is.null(Dom)) age_under_65s <- data.table(age_under_65s, Dom)
quantile <- incPercentile(Y = Y,
weights = weight,
sort = sort,
Dom = age_under_65s,
period = period,
k = order_quant,
dataset = NULL,
checking = TRUE)
quantile_under_65 <- quantile[age_under_65s == 1][, age_under_65s := NULL]
quantile_over_65 <- quantile[age_under_65s == 0][, age_under_65s := NULL]
setnames(quantile_under_65, names(quantile_under_65)[ncol(quantile_under_65)], "quantile_under_65")
setnames(quantile_over_65, names(quantile_over_65)[ncol(quantile_over_65)], "quantile_over_65")
sk <- length(names(quantile_under_65)) - 1
if (sk > 0) {
setkeyv(quantile_under_65, names(quantile_under_65)[1 : sk])
setkeyv(quantile_over_65, names(quantile_over_65)[1 : sk])
quantile <- merge(quantile_under_65, quantile_over_65, all = TRUE)
} else quantile <- data.table(quantile_under_65, quantile_over_65)
rmir_id <- id
age_under_65s <- age_under_65s[["age_under_65s"]]
if (!is.null(period)) rmir_id <- data.table(rmir_id, period)
if (!is.null(Dom)) {
Dom_agg <- data.table(unique(Dom))
setkeyv(Dom_agg, names(Dom_agg))
rmir_v <- c()
rmir_m <- copy(rmir_id)
for(i in 1:nrow(Dom_agg)) {
g <- c(var_name, paste(names(Dom), as.matrix(Dom_agg[i,]), sep = "."))
var_nams <- do.call(paste, as.list(c(g, sep = "__")))
ind <- as.integer(rowSums(Dom == Dom_agg[i,][ind0,]) == ncol(Dom))
rmirl <- lapply(1 : nrow(period1_agg), function(j) {
if (!is.null(period)) {
rown <- cbind(period_agg[j], Dom_agg[i])
setkeyv(rown, names(rown))
rown2 <- copy(rown)
rown <- merge(rown, quantile, all.x = TRUE)
} else {rown <- quantile[i]
rown2 <- Dom_agg[i] }
indj <- (rowSums(period1 == period1_agg[j,][ind0,]) == ncol(period1))
rmir_l <- rmirlinCalc(Y1 = Y[indj],
ids = rmir_id[indj],
wght = weight[indj],
indicator = ind[indj],
order_quants = order_quant,
age_under_65 = age_under_65s[indj],
quant_under_65 = rown[["quantile_under_65"]],
quant_over_65 = rown[["quantile_over_65"]])
list(rmir = data.table(rown2, rmir = rmir_l$rmir_val), lin = rmir_l$lin)
})
rmirs <- rbindlist(lapply(rmirl, function(x) x[[1]]))
rmirlin <- rbindlist(lapply(rmirl, function(x) x[[2]]))
setnames(rmirlin, names(rmirlin), c(names(rmir_id), var_nams))
rmir_m <- merge(rmir_m, rmirlin, all.x = TRUE, by = names(rmir_id))
rmir_v <- rbind(rmir_v, rmirs)
}
} else { rmirl <- lapply(1:nrow(period1_agg), function(j) {
if (!is.null(period)) {
rown <- period_agg[j]
rown <- merge(rown, quantile, all.x = TRUE,
by = names(rown))
} else rown <- quantile
ind2 <- (rowSums(period1 == period1_agg[j,][ind0,]) == ncol(period1))
rmir_l <- rmirlinCalc(Y1 = Y[ind2],
ids = rmir_id[ind2],
wght = weight[ind2],
indicator = ind0[ind2],
order_quants = order_quant,
age_under_65 = age_under_65s[ind2],
quant_under_65 = rown[["quantile_under_65"]],
quant_over_65 = rown[["quantile_over_65"]])
if (!is.null(period)) {
rmirs <- data.table(period_agg[j], rmir = rmir_l$rmir_val)
} else rmirs <- data.table(rmir = rmir_l$rmir_val)
list(rmir = rmirs, lin = rmir_l$lin)
})
rmir_v <- rbindlist(lapply(rmirl, function(x) x[[1]]))
rmir_m <- rbindlist(lapply(rmirl, function(x) x[[2]]))
setnames(rmir_m, names(rmir_m), c(names(rmir_id), var_name))
}
rmir_m[is.na(rmir_m)] <- 0
setkeyv(rmir_m, names(rmir_id))
return(list(value = rmir_v, lin = rmir_m))
}
rmirlinCalc <- function(Y1, ids, wght, indicator, order_quants, age_under_65, quant_under_65, quant_over_65) {
dom1 <- (age_under_65 == 1) * indicator
dom2 <- (age_under_65 == 0) * indicator
N1 <- sum(wght * dom1)
N2 <- sum(wght * dom2)
rmir_val <- quant_over_65 / quant_under_65
h <- sqrt((sum(wght * Y1 * Y1) - sum(wght * Y1) * sum(wght * Y1) / sum(wght)) / sum(wght)) / exp(0.2 * log(sum(wght)))
u1 <- (quant_under_65 - Y1) / h
vect_f1 <- exp(-(u1^2) / 2) / sqrt(2 * pi)
f_quant1 <- sum(vect_f1 * wght * dom1) / (N1 * h)
lin_quant_under_65 <- - (1 / N1) * dom1 * ((Y1 <= quant_under_65) - order_quants / 100) / f_quant1
u2 <- (quant_over_65 - Y1) / h
vect_f2 <- exp(-(u2^2) / 2) / sqrt(2 * pi)
f_quant2 <- sum(vect_f2 * wght * dom2) / (N2 * h)
lin_quant_over_65 <- -(1 / N2) * dom2 * ((Y1 <= quant_over_65) - order_quants / 100) / f_quant2
lin <- (quant_under_65 * lin_quant_over_65 - quant_over_65 * lin_quant_under_65) / (quant_under_65 * quant_under_65)
lin_id <- data.table(ids, lin)
return(list(rmir_val = rmir_val, lin = lin_id))
}
|
subset.sim_geno <-
function(x, ind=NULL, chr=NULL, ...)
subset.calc_genoprob(x, ind, chr, ...)
`[.sim_geno` <-
function(x, ind=NULL, chr=NULL)
subset(x, ind, chr)
|
expected <- eval(parse(text="structure(list(sec = c(0, 0, 0, 0, 0), min = c(0L, 0L, 0L, 0L, 0L), hour = c(12L, 12L, 12L, 12L, 12L), mday = 22:26, mon = c(3L, 3L, 3L, 3L, 3L), year = c(108L, 108L, 108L, 108L, 108L), wday = 2:6, yday = 112:116, isdst = c(0L, 0L, 0L, 0L, 0L)), .Names = c(\"sec\", \"min\", \"hour\", \"mday\", \"mon\", \"year\", \"wday\", \"yday\", \"isdst\"), class = c(\"POSIXlt\", \"POSIXt\"), tzone = \"GMT\")"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(1208865600, 1208952000, 1209038400, 1209124800, 1209211200), tzone = \"GMT\", class = c(\"POSIXct\", \"POSIXt\")), \"GMT\")"));
.Internal(`as.POSIXlt`(argv[[1]], argv[[2]]));
}, o=expected);
|
ccacontrol <- function(algorithm="quick",full=FALSE, itercca=1, consrankitermax=10,np=15,
gl=100,ff=0.4,cr=0.9,proc=FALSE,
ps=FALSE)
{
return(list(algorithm=algorithm, full=full, itercca=itercca, consrankitermax=consrankitermax, np=np, gl=gl, ff=ff,
cr=cr, proc=proc, ps=ps))
}
|
expandEventCount <- function(count, time) {
if ( (!is.numeric(count)) || (!is.numeric(time)) ) {
stop("Require numeric input!")
}
true.count <- as.integer(count)
if (any(as.numeric(true.count) != count)) {
stop("Event counts are non-integer.")
}
if (any(true.count < 0)) {
stop("Cannot have negative event counts")
}
time <- as.numeric(time)
if (any(time <= 0)) {
stop("Cannot have non-positive followup times")
}
if (length(time) == 1) {
time <- rep.int(time, length(true.count))
}
if (length(time) != length(true.count)) {
stop("time does not match event count")
}
warning("Synthesizing fake event times from event count data.")
mapply(function(count, duration) {
duration * (seq_len(count) / count)
},
true.count, time, SIMPLIFY=FALSE)
}
|
data(ExampleData.DeValues, envir = environment())
results <- Second2Gray(ExampleData.DeValues$BT998, c(0.2,0.01))
results_alt1 <- Second2Gray(ExampleData.DeValues$BT998, c(0.2,0.01), error.propagation = "gaussian")
results_alt2 <- Second2Gray(ExampleData.DeValues$BT998, c(0.2,0.01), error.propagation = "absolute")
test_that("check class and length of output", {
testthat::skip_on_cran()
local_edition(3)
expect_s3_class(results, class = "data.frame")
})
test_that("check values from output example", {
testthat::skip_on_cran()
local_edition(3)
expect_equal(sum(results[[1]]), 14754.09)
expect_equal(sum(results[[2]]), 507.692)
expect_equal(sum(results_alt1[[2]]), 895.911)
expect_equal(sum(results_alt2[[2]]), 1245.398)
})
|
vcfR2migrate <- function(vcf, pop, in_pop, out_file = "MigrateN_infile.txt", method = c('N','H') ) {
method <- match.arg(method, c('N','H'), several.ok = FALSE)
if( class(vcf) != "vcfR"){
stop(paste("Expecting an object of class vcfR, received a", class(vcf), "instead"))
}
if( class(pop) != "factor"){
stop(paste("Expecting population vector, received a", class(pop), "instead"))
}
vcf <- extract.indels(vcf, return.indels = F)
vcf <- vcf[is.biallelic(vcf),]
gt <- extract.gt(vcf, convertNA = T)
vcf <- vcf[!rowSums((is.na(gt))),]
vcf_list <- lapply(in_pop, function(x){ vcf[,c(TRUE, x == pop)] })
names(vcf_list) <- in_pop
if(method == 'N'){
myHeader <- c('N', length(vcf_list), nrow(vcf_list[[1]]))
pop_list <- vector(mode = 'list', length=length(vcf_list))
names(pop_list) <- names(vcf_list)
for(i in 1:length(vcf_list)){
gt <- extract.gt(vcf_list[[i]], return.alleles = T)
allele1 <- apply(gt, MARGIN = 2, function(x){ substr(x, 1, 1) })
rownames(allele1) <- NULL
allele1 <- t(allele1)
rownames(allele1) <- paste(rownames(allele1), "_1", sep = "")
allele2 <- apply(gt, MARGIN = 2, function(x){ substr(x, 3, 3) })
rownames(allele2) <- NULL
allele2 <- t(allele2)
rownames(allele2) <- paste(rownames(allele2), "_2", sep = "")
pop_list[[i]][[1]] <- allele1
pop_list[[i]][[2]] <- allele2
}
write(myHeader, file = out_file, ncolumns = length(myHeader), sep = "\t")
write(rep(1, times = ncol(pop_list[[1]][[1]])), file = out_file, ncolumns = ncol(pop_list[[1]][[1]]), append = TRUE, sep = "\t")
for(i in 1:length(pop_list)){
popName <- c(2*nrow(pop_list[[i]][[1]]), names(pop_list)[i])
write(popName, file = out_file, ncolumns = length(popName), append = TRUE, sep = "\t")
for(j in 1:ncol(pop_list[[i]][[1]])){
utils::write.table(pop_list[[i]][[1]][,j], file = out_file, append = TRUE, quote = FALSE,
sep = "\t", row.names = TRUE, col.names = FALSE)
utils::write.table(pop_list[[i]][[2]][,j], file = out_file, append = TRUE, quote = FALSE,
sep = "\t", row.names = TRUE, col.names = FALSE)
}
}
} else if(method == 'H'){
myHeader <- c('H', length(vcf_list), nrow(vcf_list[[1]]))
pop_list <- vector(mode = 'list', length=length(vcf_list))
names(pop_list) <- names(vcf_list)
for(i in 1:length(vcf_list)){
myMat <- matrix(nrow = nrow(vcf_list[[i]]), ncol = 6)
var_info <- as.data.frame(vcf_list[[i]]@fix[,1:2, drop = FALSE])
var_info$mask <- TRUE
gt <- extract.gt(vcf_list[[i]])
popSum <- .gt_to_popsum(var_info = var_info, gt = gt)
myMat[,1] <- paste(vcf_list[[i]]@fix[,'CHROM'], vcf_list[[i]]@fix[,'POS'], sep = "_")
myMat[,2] <- vcf_list[[i]]@fix[,'REF']
myMat[,4] <- vcf_list[[i]]@fix[,'ALT']
myMat[,3] <- unlist(lapply(strsplit(as.character(popSum$Allele_counts), split = ",", fixed = TRUE), function(x){x[1]}))
myMat[,3][is.na(myMat[,3])] <- 0
myMat[,5] <- unlist(lapply(strsplit(as.character(popSum$Allele_counts), split = ",", fixed = TRUE), function(x){x[2]}))
myMat[,5][is.na(myMat[,5])] <- 0
myMat[,6] <- as.numeric(myMat[,3]) + as.numeric(myMat[,5])
pop_list[[i]] <- myMat
}
write(myHeader, file = out_file, ncolumns = length(myHeader), sep = "\t")
for(i in 1:length(pop_list)){
popName <- c(pop_list[[i]][1,6], names(pop_list[i]))
write(popName, file = out_file, ncolumns = length(popName), append = TRUE, sep = "\t")
utils::write.table(pop_list[[i]], file = out_file, append = TRUE, quote = FALSE,
sep = "\t", row.names = FALSE, col.names = FALSE)
}
} else {
stop("You should never get here!")
}
return( invisible(NULL) )
}
|
test_that("Singapore results, splits in parenthesis", {
file <- system.file("extdata", "s2-results.pdf", package = "SwimmeR")
df <- swim_parse(
read_results(file),
avoid = c("MR:"),
typo = c(
"Swim\\s{2,}Club",
"Performance\\s{2,}Swim",
"Swimming\\s{2,}Club",
"Stamford\\s{2,}American\\s{2,}Internationa",
"Uwcsea\\s{2,}Phoenix-ZZ",
"AquaTech\\s{2,}Swimming",
"Chinese\\s{2,}Swimming",
"Aquatic\\s{2,}Performance",
"SwimDolphia\\s{2}Aquatic School"
),
replacement = c(
"Swim Club",
"Performance Swim",
"Swimming Club",
"Stamford American International",
"Uwcsea Phoenix-ZZ",
"AquaTech Swimming",
"Chinese Swimming",
"Aquatic Performance",
"SwimDolphia Aquatic School"
),
splits = TRUE
) %>%
splits_reform()
match_sum <- sum(df$not_matching, na.rm = TRUE)
expect_equivalent(match_sum, 0)
})
test_that("NYS results, multiple lines of splits with different lengths, has parenthesis", {
skip_on_cran()
file <- "http://www.nyhsswim.com/Results/Boys/2008/NYS/Single.htm"
if(is_link_broken(file) == TRUE){
warning("Link to external data is broken")
} else {
df <- swim_parse(
read_results(file),
typo = c("-1NORTH ROCKL"),
replacement = c("1-NORTH ROCKL"),
splits = TRUE
) %>%
splits_reform()
match_sum <- sum(df$not_matching, na.rm = TRUE)
expect_equivalent(match_sum, 75)
}
})
test_that("USA Swimming results, splits don't have parenthesis, some splits longer than 59.99", {
file <- system.file("extdata", "jets08082019_067546.pdf", package = "SwimmeR")
df <- file %>%
read_results() %>%
swim_parse(splits = TRUE) %>%
splits_reform()
match_sum <- sum(df$not_matching, na.rm = TRUE)
expect_equivalent(match_sum, 11)
})
test_that("ISL results", {
skip_on_cran()
file <- "https://github.com/gpilgrim2670/Pilgrim_Data/raw/master/ISL/Season_1_2019/ISL_19102019_Lewisville_Day_1.pdf"
if(is_link_broken(file) == TRUE){
warning("Link to external data is broken")
} else {
df <- swim_parse_ISL(read_results(file), splits = TRUE) %>%
splits_reform()
match_sum <- sum(df$not_matching, na.rm = TRUE)
expect_equivalent(match_sum, 24)
}
})
test_that("multiple splits below 59.99 in parens and out", {
skip_on_cran()
file <- "https://data.ohiostatebuckeyes.com/livestats/m-swim/210302F001.htm"
if(is_link_broken(file) == TRUE){
warning("Link to external data is broken")
} else {
df <-
swim_parse(
read_results(file),
splits = TRUE,
relay_swimmers = TRUE,
split_length = 25
) %>%
dplyr::mutate(dplyr::across(Split_25:Split_200, as.numeric)) %>%
dplyr::rowwise() %>%
dplyr::mutate(
total = sum(Split_50, Split_100, Split_150, Split_200),
F_sec = sec_format(Finals_Time),
not_matching = dplyr::case_when(round(F_sec - total, 2) == 0 ~ FALSE,
round(F_sec - total, 2) != 0 ~ TRUE)
)
match_sum <- sum(df$not_matching, na.rm = TRUE)
expect_equivalent(match_sum, 0)
}
})
test_that("correct split distances", {
df_standard <-
data.frame(
Name = c("Lilly King", "Caeleb Dressel", "Mallory Comerford"),
Event = as.factor(
c(
"Women 100 Meter Breaststroke",
"Men 50 Yard Freestyle",
"Women 200 Yard Freestyle"
)
),
Split_50 = c(NA, "8.48", NA),
Split_50 = c("29.80", "9.15", "23.90"),
Split_100 = c("34.33", NA, "25.52"),
Split_150 = c(NA, NA, "25.13"),
Split_200 = c(NA, NA, "25.25"),
stringsAsFactors = FALSE
)
df_test <- data.frame(
Name = c("Lilly King", "Caeleb Dressel", "Mallory Comerford"),
Event = c(
"Women 100 Meter Breaststroke",
"Men 50 Yard Freestyle",
"Women 200 Yard Freestyle"
),
Split_50 = c("29.80", "8.48", "23.90"),
Split_100 = c("34.33", "9.15", "25.52"),
Split_150 = c(NA, NA, "25.13"),
Split_200 = c(NA, NA, "25.25"),
stringsAsFactors = FALSE
)
df_test <- df_test %>% correct_split_distance(new_split_length = 25,
events = c("Men 50 Yard Freestyle"))
expect_equivalent(df_test, df_standard)
})
|
set.seed(1)
n=500
library(clusterGeneration)
library(mnormt)
S=genPositiveDefMat("eigen",dim=15)
S
S=genPositiveDefMat("unifcorrmat",dim=15)
S
X=rmnorm(n,varcov=S$Sigma)
X
library(corrplot)
corrplot(cor(X), order = "hclust")
P=exp(Score)/(1+exp(Score))
P=exp(S)/(1+exp(S))
Y=rbinom(n,size=1,prob=P)
df=data.frame(Y,X)
allX=paste("X",1:ncol(X),sep="")
names(df)=c("Y",allX)
require(randomForest)
fit=randomForest(factor(Y)~., data=df)
(VI_F=importance(fit))
|
lineups_comparator_stats <- function(df1,m){
if(ncol(df1)==41){
adv_stats <-df1[1:6]
tm_poss <- df1[9] - (df1[23]/(df1[23] + df1[26])) * (df1[9] - df1[7]) * 1.07 + df1[35] + 0.4 * df1[21]
opp_poss <- df1[10] - (df1[24]/(df1[24] + df1[25])) * (df1[10] - df1[8]) * 1.07 + df1[36] + 0.4 * df1[22]
team <- df1[6]/cumsum(df1[6])
pace <- m * ((tm_poss + opp_poss) / (2 * df1[6]))
fg <- df1[7] - df1[8]
fga <-df1[9] - df1[10]
fg1 <- (df1[7]/df1[9])
fg2 <- (df1[8]/df1[10])
fg1[is.na(fg1)] <- 0; fg2[is.na(fg2)] <- 0
fgp <- fg1 - fg2
fgp[is.na(fgp)] <- 0
tp <- df1[11] - df1[12]
tpa <-df1[13] - df1[14]
t1 <- (df1[11]/df1[13])
t2 <- (df1[12]/df1[14])
t1[is.na(t1)] <- 0; t2[is.na(t2)] <- 0
tgp <- t1 - t2
twp <- df1[15] - df1[16]
twpa <-df1[17] - df1[18]
tw1 <- (df1[15]/df1[17])
tw2 <- (df1[16]/df1[18])
tw1[is.na(tw1)] <- 0; tw2[is.na(tw2)] <- 0
twgp <- tw1 - tw2
efg <- (df1[7] + 0.5 * df1[11]) / df1[9]
efg_opp <- (df1[8] + 0.5 * df1[12]) / df1[10]
efg[is.na(efg)] <- 0; efg_opp[is.na(efg_opp)] <- 0
efgp<- efg - efg_opp
ts <- df1[39] / (2 * (df1[9] + 0.44 * df1[21]))
ts_opp <- df1[40] / (2 * (df1[10] + 0.44 * df1[22]))
ts[is.na(ts)] <- 0; ts_opp[is.na(ts_opp)] <- 0
tsp <- ts - ts_opp
ft <- df1[19] - df1[20]
fta <-df1[21] - df1[22]
f1 <-(df1[19]/df1[21])
f2 <- (df1[20]/df1[22])
f1[is.na(f1)] <- 0; f2[is.na(f2)] <- 0
ftp <- f1 - f2
pm <- df1[41]
adv_stats <- cbind(adv_stats,round(team,3),round(pace,2),fg,fga,round(fgp,3),tp,tpa,round(tgp,3),twp,twpa,round(twgp,3),round(efgp,3),round(tsp,3),ft,fta,round(ftp,3),pm)
names(adv_stats) = c("PG","SG","SF","PF","C","MP","Team%","Pace","FG","FGA","FG%","3P","3PA","3P%",
"2P","2PA","2P%","eFG%","TS%","FT","FTA","FT%","+/-")
}else if (ncol(df1)==39){
adv_stats <-df1[1:4]
tm_poss <- df1[7] - (df1[21]/(df1[21] + df1[24])) * (df1[7] - df1[5]) * 1.07 + df1[33] + 0.4 * df1[19]
opp_poss <- df1[8] - (df1[22]/(df1[22] + df1[23])) * (df1[8] - df1[6]) * 1.07 + df1[34] + 0.4 * df1[20]
team <- df1[4]/cumsum(df1[4])
pace <- m * ((tm_poss + opp_poss) / (2 * df1[4]))
fg <- df1[5] - df1[6]
fga <-df1[7] - df1[8]
fg1 <- (df1[5]/df1[7])
fg2 <- (df1[6]/df1[8])
fg1[is.na(fg1)] <- 0; fg2[is.na(fg2)] <- 0
fgp <- fg1 - fg2
fgp[is.na(fgp)] <- 0
tp <- df1[9] - df1[10]
tpa <-df1[11] - df1[12]
t1 <- (df1[9]/df1[11])
t2 <- (df1[10]/df1[12])
t1[is.na(t1)] <- 0; t2[is.na(t2)] <- 0
tgp <- t1 - t2
twp <- df1[13] - df1[14]
twpa <-df1[15] - df1[16]
tw1 <- (df1[13]/df1[15])
tw2 <- (df1[14]/df1[16])
tw1[is.na(tw1)] <- 0; tw2[is.na(tw2)] <- 0
twgp <- tw1 - tw2
efg <- (df1[5] + 0.5 * df1[9]) / df1[7]
efg_opp <- (df1[6] + 0.5 * df1[10]) / df1[8]
efg[is.na(efg)] <- 0; efg_opp[is.na(efg_opp)] <- 0
efgp<- efg - efg_opp
ts <- df1[37] / (2 * (df1[7] + 0.44 * df1[19]))
ts_opp <- df1[38] / (2 * (df1[8] + 0.44 * df1[20]))
ts[is.na(ts)] <- 0; ts_opp[is.na(ts_opp)] <- 0
tsp <- ts - ts_opp
ft <- df1[17] - df1[18]
fta <-df1[19] - df1[20]
f1 <-(df1[17]/df1[19])
f2 <- (df1[18]/df1[20])
f1[is.na(f1)] <- 0; f2[is.na(f2)] <- 0
ftp <- f1 - f2
pm <- df1[39]
adv_stats <- cbind(adv_stats,round(team,3),round(pace,2),fg,fga,round(fgp,3),tp,tpa,round(tgp,3),twp,twpa,round(twgp,3),round(efgp,3),round(tsp,3),ft,fta,round(ftp,3),pm)
names(adv_stats) = c("PG","SG","SF","MP","Team%","Pace","FG","FGA","FG%","3P","3PA","3P%",
"2P","2PA","2P%","eFG%","TS%","FT","FTA","FT%","+/-")
}else if (ncol(df1)==38){
adv_stats <-df1[1:3]
tm_poss <- df1[6] - (df1[20]/(df1[20] + df1[23])) * (df1[6] - df1[4]) * 1.07 + df1[32] + 0.4 * df1[18]
opp_poss <- df1[7] - (df1[21]/(df1[21] + df1[22])) * (df1[7] - df1[5]) * 1.07 + df1[33] + 0.4 * df1[19]
team <- df1[3]/cumsum(df1[3])
pace <- m * ((tm_poss + opp_poss) / (2 * df1[3]))
fg <- df1[4] - df1[5]
fga <-df1[6] - df1[7]
fg1 <- (df1[4]/df1[6])
fg2 <- (df1[5]/df1[7])
fg1[is.na(fg1)] <- 0; fg2[is.na(fg2)] <- 0
fgp <- fg1 - fg2
fgp[is.na(fgp)] <- 0
tp <- df1[8] - df1[9]
tpa <-df1[10] - df1[11]
t1 <- (df1[8]/df1[10])
t2 <- (df1[9]/df1[11])
t1[is.na(t1)] <- 0; t2[is.na(t2)] <- 0
tgp <- t1 - t2
twp <- df1[12] - df1[13]
twpa <-df1[14] - df1[15]
tw1 <- (df1[12]/df1[14])
tw2 <- (df1[13]/df1[15])
tw1[is.na(tw1)] <- 0; tw2[is.na(tw2)] <- 0
twgp <- tw1 - tw2
efg <- (df1[4] + 0.5 * df1[8]) / df1[6]
efg_opp <- (df1[5] + 0.5 * df1[9]) / df1[7]
efg[is.na(efg)] <- 0; efg_opp[is.na(efg_opp)] <- 0
efgp<- efg - efg_opp
ts <- df1[36] / (2 * (df1[6] + 0.44 * df1[18]))
ts_opp <- df1[37] / (2 * (df1[7] + 0.44 * df1[19]))
ts[is.na(ts)] <- 0; ts_opp[is.na(ts_opp)] <- 0
tsp <- ts - ts_opp
ft <- df1[16] - df1[17]
fta <-df1[18] - df1[19]
f1 <-(df1[16]/df1[18])
f2 <- (df1[17]/df1[19])
f1[is.na(f1)] <- 0; f2[is.na(f2)] <- 0
ftp <- f1 - f2
pm <- df1[38]
adv_stats <- cbind(adv_stats,round(team,3),round(pace,2),fg,fga,round(fgp,3),tp,tpa,round(tgp,3),twp,twpa,round(twgp,3),round(efgp,3),round(tsp,3),ft,fta,round(ftp,3),pm)
names(adv_stats) = c("PF","C","MP","Team%","Pace","FG","FGA","FG%","3P","3PA","3P%",
"2P","2PA","2P%","eFG%","TS%","FT","FTA","FT%","+/-")
}else if (ncol(df1)==37){
adv_stats <-df1[1:2]
tm_poss <- df1[5] - (df1[19]/(df1[19] + df1[22])) * (df1[5] - df1[3]) * 1.07 + df1[31] + 0.4 * df1[17]
opp_poss <- df1[6] - (df1[20]/(df1[20] + df1[21])) * (df1[6] - df1[4]) * 1.07 + df1[32] + 0.4 * df1[18]
team <- df1[2]/cumsum(df1[2])
pace <- m * ((tm_poss + opp_poss) / (2 * df1[2]))
fg <- df1[3] - df1[4]
fga <-df1[5] - df1[6]
fg1 <- (df1[3]/df1[5])
fg2 <- (df1[4]/df1[6])
fg1[is.na(fg1)] <- 0; fg2[is.na(fg2)] <- 0
fgp <- fg1 - fg2
fgp[is.na(fgp)] <- 0
tp <- df1[7] - df1[8]
tpa <-df1[9] - df1[10]
t1 <- (df1[7]/df1[9])
t2 <- (df1[8]/df1[10])
t1[is.na(t1)] <- 0; t2[is.na(t2)] <- 0
tgp <- t1 - t2
twp <- df1[11] - df1[12]
twpa <-df1[13] - df1[14]
tw1 <- (df1[11]/df1[13])
tw2 <- (df1[12]/df1[14])
tw1[is.na(tw1)] <- 0; tw2[is.na(tw2)] <- 0
twgp <- tw1 - tw2
efg <- (df1[3] + 0.5 * df1[7]) / df1[5]
efg_opp <- (df1[4] + 0.5 * df1[8]) / df1[6]
efg[is.na(efg)] <- 0; efg_opp[is.na(efg_opp)] <- 0
efgp<- efg - efg_opp
ts <- df1[35] / (2 * (df1[5] + 0.44 * df1[17]))
ts_opp <- df1[36] / (2 * (df1[6] + 0.44 * df1[18]))
ts[is.na(ts)] <- 0; ts_opp[is.na(ts_opp)] <- 0
tsp <- ts - ts_opp
ft <- df1[15] - df1[16]
fta <-df1[17] - df1[18]
f1 <-(df1[15]/df1[17])
f2 <- (df1[16]/df1[18])
f1[is.na(f1)] <- 0; f2[is.na(f2)] <- 0
ftp <- f1 - f2
pm <- df1[37]
adv_stats <- cbind(adv_stats,round(team,3),round(pace,2),fg,fga,round(fgp,3),tp,tpa,round(tgp,3),twp,twpa,round(twgp,3),round(efgp,3),round(tsp,3),ft,fta,round(ftp,3),pm)
names(adv_stats) = c("Name","MP","Team%","Pace","FG","FGA","FG%","3P","3PA","3P%",
"2P","2PA","2P%","eFG%","TS%","FT","FTA","FT%","+/-")
}
adv_stats[is.na(adv_stats)] <- 0
return(adv_stats)
}
|
getbb <- function(obj){
bb <- bbox(obj)
pg <- matrix(NA,5,2)
pg[1,] <- c(bb[1,1],bb[2,1])
pg[2,] <- c(bb[1,1],bb[2,2])
pg[3,] <- c(bb[1,2],bb[2,2])
pg[4,] <- c(bb[1,2],bb[2,1])
pg[5,] <- pg[1,]
bound <- Polygon(pg)
bound <- Polygons(list(poly1=bound),ID=1)
bound <- SpatialPolygons(list(poly=bound))
proj4string(bound) <- CRS(proj4string(obj))
return(bound)
}
getgrd <- function(shape,cellwidth){
shape <- gBuffer(shape,width=cellwidth)
bb <- bbox(shape)
xwid <- diff(bb[1,])
ywid <- diff(bb[2,])
delx <- xwid/cellwidth
dely <- ywid/cellwidth
M <- ceiling(delx)
N <- ceiling(dely)
xg <- bb[1,1] - (M*cellwidth-xwid)/2 + cellwidth*(0:M)
yg <- bb[2,1] - (N*cellwidth-ywid)/2 + cellwidth*(0:N)
spts <- SpatialPoints(expand.grid(xg,yg),proj4string=CRS(proj4string(shape)))
ov <- over(spts,geometry(shape))
spts <- spts[!is.na(ov),]
return(as(SpatialPixels(spts),"SpatialPolygons"))
}
neighLocs <- function(coord,cellwidth,order){
M <- outer(abs(-order:order),abs(-order:order),"+")
M[M>order] <- NA
idx <- which(!is.na(M),arr.ind=TRUE)
xv <- matrix(coord[1]+cellwidth*(-order:order),nrow=2*order+1,ncol=2*order+1,byrow=TRUE)
yv <- matrix(coord[2]+cellwidth*(order:(-order)),nrow=2*order+1,ncol=2*order+1)
return(cbind(xv[idx],yv[idx]))
}
neighOrder <- function(neighlocs){
mid <- neighlocs[(nrow(neighlocs)-1)/2+1,]
del <- t(apply(neighlocs,1,function(x){x-mid}))
md <- min(del[del>0])
del <- round(del/md)
del <- del*md
dis <- apply(del,1,function(x){x[1]^2+x[2]^2})
rk <- rank(dis)
tb <- table(rk)
ds <- as.numeric(names(tb))
ord <- 0:(length(tb)-1)
return(sapply(rk,function(x){ord[which(ds==x)]}))
}
setupPrecMatStruct <- function(shape,cellwidth,no){
gr <- getgrd(shape,cellwidth)
p4s <- proj4string(shape)
ng <- neighLocs(coordinates(gr)[1,],cellwidth,no)
nord <- neighOrder(ng)
maxord <- max(nord)
nneigh <- nrow(ng)
npoly <- length(gr)
index <- c()
ng <- c()
cat("Setting up computational grid ...\n")
pb <- txtProgressBar(1,length(gr))
for (i in 1:npoly){
ng <- rbind(ng,neighLocs(coordinates(gr)[i,],cellwidth,no))
setTxtProgressBar(pb, value=i)
}
cat("Done.\n")
close(pb)
idx <- over(SpatialPoints(ng,CRS(proj4string(gr))),geometry(gr))
ind <- which(!is.na(idx))
index <- cbind(rep(1:npoly,each=nneigh),idx,rep(nord,npoly))
index <- index[ind,]
index <- index[-which(index[,2]>index[,1]),]
ord <- order(index[,3])
index <- index[ord,]
idxls <- lapply(0:maxord,function(x){which(index[,3]==x)})
f <- function(fun){
entries <- c()
for(i in 0:maxord){
entries[idxls[[i+1]]] <- fun(i)
}
return(sparseMatrix(i=index[,1],j=index[,2],x=entries,symmetric=TRUE))
}
attr(f,"order") <- no
ans <- list()
ans$f <- f
ans$grid <- gr
return(ans)
}
SPDEprec <- function(a,ord){
if(ord==1){
f <- function(i){
if(i==0){
return(a)
}
else if(i==1){
return(-1)
}
else{
stop("error in function SPDEprec")
}
}
}
else if(ord==2){
f <- function(i){
if(i==0){
return(4+a^2)
}
else if(i==1){
return(-2*a)
}
else if(i==2){
return(2)
}
else if(i==3){
return(1)
}
else{
stop("error in function SPDEprec")
}
}
}
else if(ord==3){
f <- function(i){
if(i==0){
return(a*(a^2+12))
}
else if(i==1){
return(-3*(a^2+3))
}
else if(i==2){
return(6*a)
}
else if(i==3){
return(3*a)
}
else if(i==4){
return(-3)
}
else if(i==5){
return(-1)
}
else{
stop("error in function SPDEprec")
}
}
}
else{
stop("Higher order neighbourhood structures not currently supported.")
}
return(f)
}
YFromGamma_SPDE <- function(gamma,U,mu){
return(mu+as.numeric(Matrix::solve(U,gamma)))
}
GammaFromY_SPDE <- function(Y,U,mu){
return(as.numeric(U%*%(Y-mu)))
}
|
test_that("provide_parameters provides parameters", {
x <- rnorm(1)
expect_identical(provide_parameters(x), list(x = x))
})
test_that("provide_parameters handles named and unnamed NULL arguments", {
expect_equivalent(provide_parameters(NULL), list("NULL" = NULL))
expect_identical(provide_parameters(a = NULL), list(a = NULL))
expect_identical(
provide_parameters(NULL, b = NULL, 1:3),
list("NULL" = NULL, b = NULL, "1:3" = 1:3)
)
})
test_that("provide_parameters handles internal references", {
expect_identical(provide_parameters(a = 1, b = a), list(a = 1, b = 1))
expect_identical(provide_parameters(a = NULL, b = a), list(a = NULL, b = NULL))
})
test_that("provide_parameters supports duplicate names", {
expect_identical(provide_parameters(a = 1, a = a + 1, b = a), list(a = 1, a = 2, b = 2))
expect_identical(provide_parameters(b = 1, a = b, a = b + 1, b = a), list(b = 1, a = 1, a = 2, b = 2))
})
|
setwd("/tmp")
url <- "https://dailies.rstudio.com/rstudio/latest/index.json"
js <- jsonlite::fromJSON(url)
fileurl <- js$products$desktop$platforms$bionic$link
file <- basename(fileurl)
cat("'", fileurl, "' -> '", file, "'\n", sep="")
download.file(fileurl, file)
|
setConstructorS3("DChipDcpSet", function(files=NULL, ...) {
if (is.null(files)) {
} else if (is.list(files)) {
reqFileClass <- "DChipDcpFile"
lapply(files, FUN=function(df) {
df <- Arguments$getInstanceOf(df, reqFileClass, .name="files")
})
} else if (inherits(files, "DChipDcpSet")) {
return(as.DChipDcpSet(files))
} else {
throw("Argument 'files' is of unknown type: ", mode(files))
}
extend(AffymetrixFileSet(files=files, ...), "DChipDcpSet")
})
setMethodS3("as.character", "DChipDcpSet", function(x, ...) {
this <- x
s <- sprintf("%s:", class(this)[1])
s <- c(s, sprintf("Name: %s", getName(this)))
tags <- getTags(this)
tags <- paste(tags, collapse=",")
s <- c(s, sprintf("Tags: %s", tags))
s <- c(s, sprintf("Path: %s", getPath(this)))
n <- length(this)
s <- c(s, sprintf("Number of arrays: %d", n))
names <- getNames(this)
s <- c(s, sprintf("Names: %s [%d]", hpaste(names), n))
s <- c(s, sprintf("Total file size: %s", hsize(getFileSize(this), digits = 2L, standard = "IEC")))
GenericSummary(s)
}, protected=TRUE)
setMethodS3("findByName", "DChipDcpSet", function(static, ..., paths=c("rawData(|,.*)/", "probeData(|,.*)/")) {
if (is.null(paths)) {
paths <- eval(formals(findByName.DChipDcpSet)[["paths"]])
}
NextMethod("findByName", paths=paths)
}, static=TRUE, protected=TRUE)
setMethodS3("byName", "DChipDcpSet", function(static, name, tags=NULL, chipType, paths=NULL, ...) {
chipType <- Arguments$getCharacter(chipType, length=c(1,1))
suppressWarnings({
path <- findByName(static, name, tags=tags, chipType=chipType, paths=paths, ...)
})
if (is.null(path)) {
path <- file.path(paste(c(name, tags), collapse=","), chipType)
throw("Cannot create ", class(static)[1], ". No such directory: ", path)
}
suppressWarnings({
byPath(static, path=path, ...)
})
}, static=TRUE)
setMethodS3("byPath", "DChipDcpSet", function(static, path="rawData/", pattern="[.](dcp|DCP)$", ..., fileClass="DChipDcpFile", verbose=FALSE) {
verbose <- Arguments$getVerbose(verbose)
if (verbose) {
pushState(verbose)
on.exit(popState(verbose))
}
verbose && enter(verbose, "Defining ", class(static)[1], " from files")
this <- NextMethod("byPath", pattern=pattern, fileClass=fileClass, verbose=less(verbose))
verbose && cat(verbose, "Retrieved files: ", length(this))
if (length(this) > 0) {
path <- getPath(this)
chipType <- basename(path)
verbose && cat(verbose,
"The chip type according to the path is: ", chipType)
}
verbose && exit(verbose)
this
}, static=TRUE, protected=TRUE)
setMethodS3("as.DChipDcpSet", "DChipDcpSet", function(object, ...) {
object
})
setMethodS3("as.DChipDcpSet", "list", function(object, ...) {
DChipDcpSet(object, ...)
})
setMethodS3("as.DChipDcpSet", "default", function(object, ...) {
throw("Cannot coerce object to an DChipDcpSet object: ", mode(object))
})
setMethodS3("extractTheta", "DChipDcpSet", function(this, units=NULL, ..., drop=FALSE, verbose=FALSE) {
verbose <- Arguments$getVerbose(verbose)
if (verbose) {
pushState(verbose)
on.exit(popState(verbose))
}
data <- NULL
nbrOfArrays <- length(this)
gcCount <- 0
for (kk in seq_len(nbrOfArrays)) {
df <- this[[kk]]
verbose && enter(verbose, sprintf("Array
dataKK <- extractTheta(df, units=units, ..., verbose=less(verbose, 5))
verbose && str(verbose, dataKK)
if (is.null(data)) {
dim <- c(nrow(dataKK), ncol(dataKK), nbrOfArrays)
dimnames <- list(NULL, NULL, getNames(this))
naValue <- as.double(NA)
data <- array(naValue, dim=dim, dimnames=dimnames)
}
data[,,kk] <- dataKK
dataKK <- NULL
gcCount <- gcCount + 1
if (gcCount %% 10 == 0) {
gc <- gc()
verbose && print(verbose, gc)
}
verbose && exit(verbose)
}
if (drop) {
data <- drop(data)
}
verbose && cat(verbose, "Thetas:")
verbose && str(verbose, data)
data
})
|
"mvdst" <-
function (x, variant=2, inverted=FALSE)
mvdtt(x, type="dst", variant=variant, inverted=inverted)
|
context("test-pat_aggregate")
test_that('Alternative aggregation', {
data("example_pat")
expect_true(identical(
pat_aggregate(example_pat,
FUN = function(x) mean(x,na.rm = TRUE)),
pat_aggregate(example_pat,
FUN = function(x) mean(x, na.rm = TRUE),
unit = 'minutes',
count = 60)
))
})
|
test_that("parse_query(tidy = TRUE) works on 'flights' and 'planes' left outer join example query", {
expect_equal(
{
query <- "SELECT origin, dest,
round(AVG(distance)) AS dist,
round(COUNT(*)/10) AS flights_per_year,
round(SUM(seats)/10) AS seats_per_year,
round(AVG(arr_delay)) AS avg_arr_delay
FROM fly.flights f LEFT OUTER JOIN fly.planes p
ON f.tailnum = p.tailnum
WHERE distance BETWEEN 300 AND 400
GROUP BY origin, dest
HAVING flights_per_year > 5000
ORDER BY seats_per_year DESC
LIMIT 6;"
parse_query(query, tidy = TRUE)
},
structure(list(select = structure(list(quote(origin), quote(dest),
dist = quote(round(mean(distance, na.rm = TRUE))), flights_per_year = str2lang("round(dplyr::n()/10)"),
seats_per_year = quote(round(sum(seats, na.rm = TRUE)/10)),
avg_arr_delay = quote(round(mean(arr_delay, na.rm = TRUE)))),
aggregate = c(FALSE, FALSE, dist = TRUE, flights_per_year = TRUE,
seats_per_year = TRUE, avg_arr_delay = TRUE)), from = structure(list(f = quote(fly.flights),
p = quote(fly.planes)), join_types = "left outer join", join_conditions = list(quote(f.tailnum ==
p.tailnum))), where = list(str2lang("dplyr::between(distance,300, 400)")),
group_by = list(quote(origin), quote(dest)), having = list(quote(flights_per_year > 5000)),
order_by = structure(list(str2lang("dplyr::desc(seats_per_year)")),
aggregate = FALSE), limit = list(6)), aggregate = TRUE)
)
})
test_that("parse_query() works on SQL-92-style (explicit) join with ON", {
expect_equal(
parse_query("SELECT y.w, z.x FROM y JOIN z ON y.a = z.b"),
list(select = list(quote(y.w), quote(z.x)), from = structure(list(quote(y),
quote(z)), join_types = "inner join", join_conditions = list(quote(y.a ==
z.b))))
)
})
test_that("parse_query() works on SQL-92-style (explicit) join with ON with parentheses", {
expect_equal(
parse_query("SELECT y.w, z.x FROM y JOIN z ON (y.a = z.b)"),
list(select = list(quote(y.w), quote(z.x)), from = structure(list(quote(y),
quote(z)), join_types = "inner join", join_conditions = list(quote(y.a ==
z.b))))
)
})
test_that("parse_query() works on SQL-92-style (explicit) join with USING", {
expect_equal(
parse_query("SELECT y.w, z.x FROM y JOIN z USING (a)"),
list(select = list(quote(y.w), quote(z.x)), from = structure(list(quote(y),
quote(z)), join_types = "inner join", join_conditions = list(quote(y.a ==
z.a))))
)
})
test_that("parse_query() works on join with aliases", {
expect_equal(
parse_query("SELECT y.a, z.`b`, `w`.c FROM why AS y LEFT OUTER JOIN zee 'z' ON y.a = z.b INNER JOIN dub w USING(c,d,e)"),
list(select = list(quote(y.a), quote(z.b), quote(w.c)), from = structure(list(y = quote(why),
z = quote(zee), w = quote(dub)), join_types = c("left outer join",
"inner join"), join_conditions = list(quote(y.a == z.b),
quote(z.c == w.c & z.d == w.d & z.e == w.e))))
)
})
test_that("parse_query() works on CROSS JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x CROSS JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "cross join", join_conditions = NA))
)
})
test_that("parse_query() works on NATURAL JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x NATURAL JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "natural inner join", join_conditions = NA))
)
})
test_that("parse_query() works on NATURAL INNER JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x NATURAL INNER JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "natural inner join", join_conditions = NA))
)
})
test_that("parse_query() works on INNER JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x INNER JOIN y ON x.k = y.k"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "inner join", join_conditions = list(quote(x.k ==
y.k))))
)
})
test_that("parse_query() works on NATURAL OUTER JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x NATURAL OUTER JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "natural left outer join", join_conditions = NA))
)
})
test_that("parse_query() works on NATURAL LEFT OUTER JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x NATURAL LEFT OUTER JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "natural left outer join", join_conditions = NA))
)
})
test_that("parse_query() works on LEFT OUTER JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x LEFT OUTER JOIN y ON x.k = y.k"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "left outer join", join_conditions = list(quote(x.k ==
y.k))))
)
})
test_that("parse_query() works on NATURAL RIGHT OUTER JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x NATURAL RIGHT OUTER JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "natural right outer join", join_conditions = NA))
)
})
test_that("parse_query() works on RIGHT OUTER JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x RIGHT OUTER JOIN y ON x.k = y.k"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "right outer join", join_conditions = list(quote(x.k ==
y.k))))
)
})
test_that("parse_query() works on NATURAL FULL OUTER JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x NATURAL FULL OUTER JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "natural full outer join", join_conditions = NA))
)
})
test_that("parse_query() works on FULL OUTER JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x FULL OUTER JOIN y ON x.k = y.k"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "full outer join", join_conditions = list(quote(x.k ==
y.k))))
)
})
test_that("parse_query() works on OUTER JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x OUTER JOIN y ON x.k = y.k"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "left outer join", join_conditions = list(quote(x.k ==
y.k))))
)
})
test_that("parse_query() works on NATURAL LEFT SEMI JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x NATURAL LEFT SEMI JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "natural left semi join", join_conditions = NA))
)
})
test_that("parse_query() works on LEFT SEMI JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x LEFT SEMI JOIN y ON x.k = y.k"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "left semi join", join_conditions = list(quote(x.k == y.k))))
)
})
test_that("parse_query() works on NATURAL RIGHT SEMI JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x NATURAL RIGHT SEMI JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "natural right semi join", join_conditions = NA))
)
})
test_that("parse_query() works on RIGHT SEMI JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x RIGHT SEMI JOIN y ON x.k = y.k"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "right semi join", join_conditions = list(quote(x.k == y.k))))
)
})
test_that("parse_query() stops on SEMI JOIN without RIGHT or LEFT", {
expect_error(
parse_query("SELECT a, b FROM x SEMI JOIN y ON x.k = y.k"),
"LEFT or RIGHT"
)
})
test_that("parse_query() works on NATURAL LEFT ANTI JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x NATURAL LEFT ANTI JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "natural left anti join", join_conditions = NA))
)
})
test_that("parse_query() works on LEFT ANTI JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x LEFT ANTI JOIN y ON x.k = y.k"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "left anti join", join_conditions = list(quote(x.k == y.k))))
)
})
test_that("parse_query() works on NATURAL RIGHT ANTI JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x NATURAL RIGHT ANTI JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "natural right anti join", join_conditions = NA))
)
})
test_that("parse_query() works on RIGHT ANTI JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x RIGHT ANTI JOIN y ON x.k = y.k"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "right anti join", join_conditions = list(quote(x.k == y.k))))
)
})
test_that("parse_query() stops on ANTI JOIN without RIGHT or LEFT", {
expect_error(
parse_query("SELECT a, b FROM x ANTI JOIN y ON x.k = y.k"),
"LEFT or RIGHT"
)
})
test_that("parse_query() works on NATURAL LEFT JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x NATURAL LEFT JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "natural left outer join", join_conditions = NA))
)
})
test_that("parse_query() works on LEFT JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x LEFT JOIN y ON x.k = y.k"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "left outer join", join_conditions = list(quote(x.k == y.k))))
)
})
test_that("parse_query() works on NATURAL RIGHT JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x NATURAL RIGHT JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "natural right outer join", join_conditions = NA))
)
})
test_that("parse_query() works on RIGHT JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x RIGHT JOIN y ON x.k = y.k"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "right outer join", join_conditions = list(quote(x.k == y.k))))
)
})
test_that("parse_query() works on NATURAL FULL JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x NATURAL FULL JOIN y"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "natural full outer join", join_conditions = NA))
)
})
test_that("parse_query() works on FULL JOIN", {
expect_equal(
parse_query("SELECT a, b FROM x FULL JOIN y ON x.k = y.k"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "full outer join", join_conditions = list(quote(x.k == y.k))))
)
})
test_that("parse_query() works on JOIN with no modifying keywords", {
expect_equal(
parse_query("SELECT a, b FROM x JOIN y ON x.k = y.k"),
list(select = list(quote(a), quote(b)), from = structure(list(quote(x),
quote(y)), join_types = "inner join", join_conditions = list(quote(x.k == y.k))))
)
})
test_that("parse_query() stops on LEFT INNER JOIN", {
expect_error(
parse_query("SELECT a, b FROM x LEFT INNER JOIN y ON x.k = y.k"),
"Invalid"
)
})
test_that("parse_query() stops on INNER OUTER JOIN", {
expect_error(
parse_query("SELECT a, b FROM x INNER OUTER JOIN y ON x.k = y.k"),
"Invalid"
)
})
test_that("parse_query() stops on OUTER INNER JOIN", {
expect_error(
parse_query("SELECT a, b FROM x OUTER INNER JOIN y ON x.k = y.k"),
"Invalid"
)
})
test_that("parse_query() stops on SQL-89-style (implicit) join", {
expect_error(
parse_query("SELECT y.w, z.x FROM y, z WHERE y.a = z.b"),
"implicit"
)
})
test_that("parse_query() stops on join with repeated AS in table alias", {
expect_error(
parse_query("SELECT a FROM bee AS AS b NATURAL JOIN see AS c"),
"Repeated"
)
})
test_that("parse_query() stops on join with no left table alias after AS", {
expect_error(
parse_query("SELECT a FROM bee AS NATURAL JOIN see AS c"),
"Missing table alias"
)
})
test_that("parse_query() stops on join with no right table alias after AS", {
expect_error(
parse_query("SELECT a FROM bee AS b NATURAL JOIN see AS"),
"Missing table alias"
)
})
test_that("parse_query() stops on join with missing right table reference before ON", {
expect_error(
parse_query("SELECT a FROM b JOIN ON b.x = c.y"),
"Missing table reference"
)
})
test_that("parse_query() stops on join with missing right table reference before USING", {
expect_error(
parse_query("SELECT a FROM b JOIN USING (z)"),
"Missing table reference"
)
})
test_that("parse_query() stops on join no parentheses after USING", {
expect_error(
parse_query("SELECT y.w, z.x FROM y JOIN z USING a"),
"parenthes"
)
})
test_that("parse_query() stops on join no column references in USING clause", {
expect_error(
parse_query("SELECT y.w, z.x FROM y JOIN z USING ()"),
"Missing"
)
})
test_that("parse_query() stops on join with required conditions missing", {
expect_error(
parse_query("SELECT y.w, z.x FROM y JOIN z"),
"conditions"
)
})
test_that("parse_query() stops on three-table join with required conditions missing", {
expect_error(
parse_query("SELECT a, b, c FROM x JOIN y JOIN z USING (t)"),
"conditions"
)
})
test_that("parse_query() stops on NATURAL JOIN with ON clause", {
expect_error(
parse_query("SELECT a, b FROM x NATURAL JOIN y ON x.k = y.k"),
"Unexpected ON"
)
})
test_that("parse_query() stops on NATURAL JOIN with USING clause", {
expect_error(
parse_query("SELECT a, b FROM x NATURAL JOIN y USING (k)"),
"Unexpected USING"
)
})
test_that("parse_query() stops when unexpected word or symbol in join", {
expect_error(
parse_query("SELECT a, b FROM c JOIN d USING (e) NOT f"),
"Unexpected"
)
})
test_that("parse_query() stops on incomplete join conditions", {
expect_error(
parse_query("SELECT a, b FROM x JOIN y ON x"),
"Malformed"
)
})
test_that("parse_query() stops on malformed join conditions
expect_error(
parse_query("SELECT a, b FROM x JOIN y ON x AND y"),
"Malformed"
)
})
test_that("parse_query() stops on malformed join conditions
expect_error(
parse_query("SELECT a, b FROM x JOIN y ON x AND y = q AND r"),
"Malformed"
)
})
test_that("parse_query() stops on disallowed values in USING", {
expect_error(
parse_query("SELECT a, b FROM x JOIN y USING(a = b)"),
"column"
)
})
test_that("parse_query() stops on join conditions with disallowed operators and/or functions", {
expect_error(
parse_query("SELECT a, b FROM x JOIN y ON sqrt(t) - 4 = 0"),
"equality"
)
})
test_that("parse_query() stops on self-join with no table aliases", {
expect_error(
parse_query("SELECT * FROM x JOIN x USING (z)"),
"different"
)
})
test_that("parse_query() stops on join with non-unique table aliases", {
expect_error(
parse_query("SELECT * FROM x AS y JOIN x AS y USING (z)"),
"different"
)
})
test_that("parse_query() succeeds on self-join with unique table aliases", {
expect_error(
parse_query("SELECT * FROM x AS w JOIN x AS y USING (z)"),
NA
)
})
test_that("parse_query() succeeds on self-join with unique table names/aliases", {
expect_error(
parse_query("SELECT * FROM x JOIN x AS y USING (z)"),
NA
)
})
test_that("parse_query() succeeds when parentheses enclose FROM clause with join", {
expect_error(
parse_query("SELECT * FROM (x JOIN y ON x.a = y.a)"),
NA
)
})
test_that("parse_query() succeeds when parentheses enclose FROM clause and table names in join", {
expect_error(
parse_query("SELECT * FROM ((ex) x JOIN (why) y ON x.a = y.a)"),
NA
)
})
test_that("parse_query() succeeds when two pairs of parentheses enclose FROM clause with join", {
expect_error(
parse_query("SELECT * FROM ((x JOIN y ON x.a = y.a))"),
NA
)
})
test_that("parse_query() succeeds when join in FROM clause is not enclosed in parentheses but begins with ( and ends with )", {
expect_error(
parse_query("SELECT * FROM (x) JOIN (y) USING (a)"),
NA
)
})
|
pk.tss.monoexponential <- function(...,
tss.fraction=0.9,
output=c(
"population",
"popind",
"individual",
"single"),
check=TRUE,
verbose=FALSE) {
modeldata <- pk.tss.data.prep(..., check=check)
if (is.factor(tss.fraction) |
!is.numeric(tss.fraction))
stop("tss.fraction must be a number")
if (!length(tss.fraction) == 1) {
warning("Only first value of tss.fraction is being used")
tss.fraction <- tss.fraction[1]
}
if (tss.fraction <= 0 | tss.fraction >= 1) {
stop("tss.fraction must be between 0 and 1, exclusive")
} else if (tss.fraction < 0.8) {
warning("tss.fraction is usually >= 0.8")
}
output <- match.arg(output, several.ok=TRUE)
if (!("subject" %in% names(modeldata))) {
if (any(c("population", "popind", "individual") %in% output)) {
warning("Cannot give 'population', 'popind', or 'individual' ",
"output without multiple subjects of data")
output <- setdiff(output, c("population", "popind", "individual"))
}
}
modeldata$tss.constant <- log(1-tss.fraction)
ret_population <-
if (any(c("population", "popind") %in% output)) {
pk.tss.monoexponential.population(
modeldata,
output=intersect(c("population", "popind"), output),
verbose=verbose)
} else {
NA
}
ret_individual <-
if (any(c("individual", "single") %in% output)) {
pk.tss.monoexponential.individual(
modeldata,
output=intersect(c("individual", "single"), output),
verbose=verbose)
} else {
NA
}
ret <-
if (!identical(NA, ret_population) & !identical(NA, ret_individual)) {
merge(ret_population, ret_individual)
} else if (!identical(NA, ret_population)) {
ret_population
} else if (!identical(NA, ret_individual)) {
ret_individual
} else {
stop("Error in selection of return values for pk.tss.monoexponential. This is likely a bug.")
}
ret
}
tss.monoexponential.generate.formula <- function(data) {
if ("treatment" %in% names(data)) {
ctrough.by <-
list("Ctrough.ss by treatment"=list(
formula=ctrough.ss~treatment-1,
start=dplyr::summarize_(
dplyr::group_by_(data, "treatment"),
.dots=list(conc.mean=~mean(conc)))$conc.mean))
} else {
ctrough.by <-
list("Single Ctrough.ss"=list(
formula=ctrough.ss~1,
start=mean(data$conc)))
}
tss.by <- list(
"Single value for Tss"=list(
formula=tss~1,
start=stats::median(unique(data$time))))
if ("treatment" %in% names(data))
tss.by[["Tss by treatment"]] <- list(
formula=tss~treatment,
start=rep(stats::median(unique(data$time)),
length(unique(data$treatment))))
ranef.by <-
list("Ctrough.ss and Tss"=list(formula=ctrough.ss+tss~1|subject),
"Tss"=list(formula=tss~1|subject),
"Ctrough.ss"=list(formula=ctrough.ss~1|subject))
list(
ctrough.by=ctrough.by,
tss.by=tss.by,
ranef.by=ranef.by
)
}
pk.tss.monoexponential.population <- function(data,
output=c(
"population",
"popind"),
verbose=FALSE) {
output <- match.arg(output, several.ok=TRUE)
test.formula <- tss.monoexponential.generate.formula(data)
models <- list()
for (myctrough.ss in names(test.formula$ctrough.by)) {
for (mytss in names(test.formula$tss.by)) {
for (myranef in names(test.formula$ranef.by)) {
current.desc <-
sprintf("Fixed effects of %s and %s; random effects of %s",
myctrough.ss, mytss, myranef)
if (verbose)
print(current.desc)
current.model <- NA
current.aic <- NA
current.model.summary <- "Did not converge"
try({
current.model <-
nlme::nlme(conc~ctrough.ss*(1-exp(tss.constant*time/tss)),
fixed=list(
test.formula$ctrough.by[[myctrough.ss]]$formula,
test.formula$tss.by[[mytss]]$formula),
random=test.formula$ranef.by[[myranef]]$formula,
start=c(
test.formula$ctrough.by[[myctrough.ss]]$start,
test.formula$tss.by[[mytss]]$start),
data=data,
verbose=verbose)
if (!is.null(current.model)) {
current.model.summary <- summary(current.model)
current.aic <- stats::AIC(current.model)
}
}, silent=!verbose)
models <-
append(
models,
list(
list(
desc=current.desc,
model=current.model,
summary=current.model.summary,
AIC=current.aic
)
)
)
}
}
}
all.model.summary <- AIC.list(lapply(models, function(x) x$model))
rownames(all.model.summary) <- sapply(models, function(x) x$desc)
if (verbose)
print(all.model.summary)
if (all(is.na(all.model.summary$AIC)) |
length(all.model.summary) == 0) {
warning("No population model for monoexponential Tss converged, no results given")
ret <-
data.frame(
tss.monoexponential.population=NA,
tss.monoexponential.popind=NA,
subject=unique(data[["subject"]]),
stringsAsFactors=FALSE
)
} else {
best.model <-
models[all.model.summary$AIC %in%
min(all.model.summary$AIC, na.rm=TRUE)][[1]]$model
ret <-
data.frame(
tss.monoexponential.population=nlme::fixef(best.model)[["tss"]],
stringsAsFactors=FALSE
)
best.ranef <- nlme::ranef(best.model)
if ("tss" %in% names(best.ranef)) {
ret <-
merge(
ret,
data.frame(
tss.monoexponential.popind=(best.ranef$tss +
ret$tss.monoexponential.population),
subject=factor(rownames(best.ranef)),
stringsAsFactors=FALSE
),
all=TRUE
)
} else if ("popind" %in% output) {
warning("tss.monoexponential.popind was requested, but the best model did not include a random effect for tss. Set to NA.")
ret <-
merge(
ret,
data.frame(
tss.monoexponential.popind=NA,
subject=unique(data$subject),
stringsAsFactors=FALSE
),
all=TRUE
)
}
}
ret[,intersect(c("subject", "treatment",
paste("tss.monoexponential", output, sep=".")),
names(ret)),
drop=FALSE]
}
pk.tss.monoexponential.individual <- function(data,
output=c(
"individual",
"single"),
verbose=FALSE) {
fit.tss <- function(d) {
tss <- NA_real_
try({
current.model <-
nlme::gnls(conc~ctrough.ss*(1-exp(tss.constant*time/tss)),
params=list(
ctrough.ss~1,
tss~1),
start=c(
mean(d$conc),
stats::median(unique(d$time))),
data=d,
verbose=verbose)
if (!is.null(current.model)) {
tss <- stats::coef(current.model)[["tss"]]
}
}, silent=!verbose)
if (is.null(tss)) {
tss <- NA_real_
}
tss
}
output <- match.arg(output, several.ok=TRUE)
data_maybe_grouped <-
if ("treatment" %in% names(data)) {
data %>%
dplyr::group_by_("treatment")
} else {
data
}
ret <-
data_maybe_grouped %>%
dplyr::summarize(
tss.monoexponential.single=
fit.tss(
data.frame(
time=.$time,
tss.constant=.$tss.constant,
conc=.$conc,
treatment=.$treatment,
stringsAsFactors=FALSE
)
)
)
if ("subject" %in% names(data) &
"individual" %in% output) {
data_grouped <-
if (all(c("treatment", "subject") %in% names(data))) {
data %>%
group_by_("treatment", "subject")
} else if ("subject" %in% names(data)) {
data %>%
group_by_("subject")
} else {
stop("Subject must be specified to have subject-level fitting")
}
ret.sub <-
data_grouped %>%
dplyr::summarize_(
.dots=list(
tss.monoexponential.individual=
~fit.tss(
data.frame(
time=time,
tss.constant=tss.constant,
conc=conc,
stringsAsFactors=FALSE
)
)
)
)
ret <- merge(ret, ret.sub, all=TRUE)
}
as.data.frame(
ret[,c(intersect(names(ret), c("subject", "treatment")),
paste("tss.monoexponential", output, sep=".")),
drop=FALSE],
stringsAsFactors=FALSE
)
}
|
select_threshold <- function(pairs, threshold, weight, var = "select") {
if (!methods::is(pairs, "pairs")) stop("pairs should be an object of type 'pairs'.")
UseMethod("select_threshold")
}
select_threshold.ldat <- function(pairs, threshold, weight, var = "select") {
if (missing(weight) || is.null(weight)) weight <- attr(pairs, "score")
if (is.null(weight)) stop("Missing weight")
if (is.character(weight)) weight <- pairs[[weight]]
pairs[[var]] <- weight > threshold
attr(pairs, "selection") <- var
pairs
}
select_threshold.data.frame <- function(pairs, threshold, weight,
var = "select") {
if (missing(weight) || is.null(weight)) weight <- attr(pairs, "score")
if (is.null(weight)) stop("Missing weight")
if (is.character(weight)) weight <- pairs[[weight]]
pairs[[var]] <- weight > threshold
attr(pairs, "selection") <- var
pairs
}
|
shinydashboard::tabItem(
tabName = "radar",
fluidRow(
column(
width = 12,
br(),
tabBox(width=12,height=550,
tabPanel(
title = "Graphic",
fluidRow(
h2("Simple example", align="center"),
column(
width = 12,
rAmCharts::amChartsOutput("radar1"), type = "radar")
)),
tabPanel(
title = "Code",
fluidRow(
h2("Simple example", align="center"),
column(
width = 12,
verbatimTextOutput("code_radar1"))
)
)
),
tabBox(width=12,height=550,
tabPanel(
title = "Graphic",
fluidRow(
h2("Add legend, title, font area color, bullets ....", align="center"),
column(
width = 12,
rAmCharts::amChartsOutput("radar3"), type = "radar")
)),
tabPanel(
title = "Code",
fluidRow(
h2("Add legend, title, font area color, bullets ....", align="center"),
column(
width = 12,
verbatimTextOutput("code_radar3"))
)
)
),
tabBox(width=12,height=550,
tabPanel(
title = "Graphic",
fluidRow(
h2("Wind, add guides", align="center"),
column(
width = 12,
rAmCharts::amChartsOutput("radar2"), type = "radar")
)),
tabPanel(
title = "Code",
fluidRow(
h2("Wind, add guides", align="center"),
column(
width = 12,
verbatimTextOutput("code_radar2"))
)
)
)
)
)
)
|
read.community <- function(file, grids="grids", species="species", ...){
d <- read.csv(file, stringsAsFactors = TRUE, ...)
M <- Matrix::sparseMatrix(as.integer(d[,grids]), as.integer(d[,species]),
x = rep(1L, nrow(d)),
dimnames = list(levels(d[,"grids"]), levels(d[,"species"])))
M
}
|
quickEP = function(claim, true, ids, afreq = NULL, ...) {
als = if(is.null(afreq)) NULL else seq_along(afreq)
exclusionPower(claim, true, ids, alleles = als, afreq = afreq,
plot = F, verbose = F, ...)$EPtotal
}
test_that("EP works in empty paternity case", {
claim = nuclearPed(1)
true = list(singleton(1), singleton(3))
ids = c(1, 3)
afr = c(.1, .9)
ep_aut = quickEP(claim, true, ids, afr)
expect_equal(ep_aut, 2 * afr[1]^2 * afr[2]^2)
expect_equal(quickEP(claim, true, ids, afr, Xchrom = T), 0)
claim2 = nuclearPed(1, sex = 2)
true2 = list(singleton(1), singleton(3, sex = 2))
ep_X = quickEP(claim2, true2, ids, afr, Xchrom = T)
expect_equal(ep_X, afr[1] * afr[2])
})
test_that("EP works in empty pat-case with added singletons", {
claim = list(nuclearPed(1), singleton(4))
true = list(singleton(1), singleton(3), singleton(4))
ids = c(1, 3, 4)
afr = c(.1, .9)
expect_equal(quickEP(claim, true, ids, afr), 2 * afr[1]^2 * afr[2]^2)
expect_equal(quickEP(claim, true, ids, afr, Xchrom = T), 0)
claim2 = list(nuclearPed(1, sex = 2), singleton(4))
true2 = list(singleton(1), singleton(3, sex = 2), singleton(4))
expect_equal(quickEP(claim2, true2, ids, afr, Xchrom = T), afr[1] * afr[2])
})
test_that("EP works in paternity case with child typed", {
claim = nuclearPed(1, sex = 2)
true = list(singleton(1), singleton(3))
afr = c(.5, .3, .2)
m = mX = marker(claim, `3` = 1, alleles = 1:3, afreq = afr)
chrom(mX) = 23L
claim = setMarkers(claim, list(m, mX))
ep_aut = quickEP(claim, true, ids = 1, markers = 1)
expect_equal(ep_aut, sum(afr[-1])^2)
ep_X = quickEP(claim, true, ids = 1, markers = 2)
expect_equal(ep_X, sum(afr[-1]))
})
test_that("EP works in paternity case with parents typed", {
claim = nuclearPed(1, sex = 2)
true = list(singleton(1), singleton(3, sex = 2))
afr = c(.5, .3, .2)
m = mX = marker(claim, `1` = 1, `2` = 2, alleles = 1:3, afreq = afr)
chrom(mX) = 23L
claim = setMarkers(claim, list(m, mX))
ep_aut = quickEP(claim, true, ids = 3, markers = 1)
expect_equal(ep_aut, 1 - 2*afr[1]*afr[2])
ep_X = quickEP(claim, true, ids = 3, markers = 2)
expect_equal(ep_X, 1 - 2*afr[1]*afr[2])
})
|
ml0a <- maxLik(loglik.faithful, x = geyser$duration,
start = c(0.5, m - 1, m + 1, s, s),
fixed = 1)
coef(ml0a)
logLik(ml0a)
|
poset.scores<-function(posetparenttable,scoretable,numberofparentsvec,rowmaps,n,plus1lists=NULL,
numparents,updatenodes=c(1:n)){
orderscore<-list(length=n)
revnumberofparentsvec<-lapply(numberofparentsvec,rev)
if (is.null(plus1lists)){
for (j in updatenodes){
len<-numparents[j]
binomcoefs<-choose(len,c(0:len))
nrows<-nrow(posetparenttable[[j]])
P_local<-vector("numeric",length=nrows)
P_local[nrows] <-scoretable[[j]][1,1]
maxoverall<-max(scoretable[[j]][,1])
P_local[1]<-log(sum(exp(scoretable[[j]][,1]-maxoverall)))+maxoverall
cutoff<-1
if(nrows>2){
for(level in 1:(len-1)){
cutoff<-cutoff+binomcoefs[level]
for (i in (nrows-1):cutoff) {
posetparentnodes <- posetparenttable[[j]][i,c(1:revnumberofparentsvec[[j]][i])]
maxparents<-max(P_local[posetparentnodes])
parentsum<-log(sum(exp(P_local[posetparentnodes]-maxparents)))+maxparents-log(len-revnumberofparentsvec[[j]][i]-level+1)
conjugatescore<-scoretable[[j]][rowmaps[[j]]$backwards[nrows-rowmaps[[j]]$forward[i]+1],1]
maxoverall<-max(parentsum,conjugatescore)
P_local[i]<- log(exp(parentsum-maxoverall)+exp(conjugatescore-maxoverall)) + maxoverall
}
}
}
orderscore[[j]]<-as.matrix(P_local)
}
return(orderscore)
} else {
for (j in updatenodes) {
len<-numparents[j]
binomcoefs<-choose(len,c(0:len))
ll<-length(plus1lists$parents[[j]])+1
nrows<-nrow(posetparenttable[[j]])
P_local <- matrix(nrow=nrows,ncol=ll)
for (li in 1:ll){
P_local[nrows,li] <-scoretable[[j]][[li]][1,1]
maxoverall<-max(scoretable[[j]][[li]][,1])
P_local[1,li]<-log(sum(exp(scoretable[[j]][[li]][,1]-maxoverall)))+maxoverall
cutoff<-1
if(nrows>2){
for(level in 1:(len-1)){
cutoff<-cutoff+binomcoefs[level]
for (i in (nrows-1):cutoff) {
posetparentnodes <- posetparenttable[[j]][i,c(1:revnumberofparentsvec[[j]][i])]
maxparents<-max(P_local[posetparentnodes,li])
parentsum<-log(sum(exp(P_local[posetparentnodes,li]-maxparents)))+maxparents-log(len-revnumberofparentsvec[[j]][i]-level+1)
conjugatescore<-scoretable[[j]][[li]][rowmaps[[j]]$backwards[nrows-rowmaps[[j]]$forward[i]+1],1]
maxoverall<-max(parentsum,conjugatescore)
P_local[i,li]<- log(exp(parentsum-maxoverall)+exp(conjugatescore-maxoverall)) + maxoverall
}
}
}
}
orderscore[[j]]<-P_local
}
return(orderscore)
}
}
posetscoremax<-function(posetparenttable,scoretable,numberofparentsvec,rowmaps,n,plus1lists=NULL,
updatenodes=c(1:n)) {
listy<-list()
revnumberofparentsvec<-lapply(numberofparentsvec,rev)
if (is.null(plus1lists)) {
maxmatrix<-list()
maxrows<-list()
for (j in updatenodes) {
nrows<-nrow(posetparenttable[[j]])
P_local <- numeric(nrows)
maxrow<-numeric(nrows)
P_local[nrows]<-scoretable[[j]][1,1]
maxrow[nrows]<-1
if(nrows>1) {
for (i in (nrows-1):1) {
posetparentnodes <- posetparenttable[[j]][i,c(1:revnumberofparentsvec[[j]][i])]
prevmax<- max(P_local[posetparentnodes])
candmax<-scoretable[[j]][rowmaps[[j]]$backwards[nrows-rowmaps[[j]]$forward[i]+1],1]
if (prevmax>candmax) {
P_local[i]<-prevmax
maxrow[i]<-maxrow[posetparentnodes[which.max(P_local[posetparentnodes])]]
} else {
P_local[i]<-candmax
maxrow[i]<-rowmaps[[j]]$backwards[nrows-rowmaps[[j]]$forward[i]+1]
}
}
}
maxmatrix[[j]]<-as.matrix(P_local)
maxrows[[j]]<- maxrow
}
listy$maxmatrix<-maxmatrix
listy$maxrows<-maxrows
return(listy)
} else {
maxmatrix<-list()
maxrows<-list()
for (j in updatenodes)
{
ll<-length(plus1lists$parents[[j]])+1
nrows<-nrow(posetparenttable[[j]])
P_local <- matrix(nrow=nrows,ncol=ll)
maxrow<-matrix(nrow=nrows,ncol=ll)
for (li in 1:ll)
{
P_local[nrows,li]<-scoretable[[j]][[li]][1,1]
maxrow[nrows,li]<-1
if(nrows>1) {
for (i in (nrows-1):1) {
posetparentnodes <- posetparenttable[[j]][i,c(1:revnumberofparentsvec[[j]][i])]
prevmax<- max(P_local[posetparentnodes,li])
candmax<-scoretable[[j]][[li]][rowmaps[[j]]$backwards[nrows-rowmaps[[j]]$forward[i]+1],1]
if (prevmax>candmax) {
P_local[i,li]<-prevmax
maxrow[i,li]<-maxrow[posetparentnodes[which.max(P_local[posetparentnodes,li])],li]
} else {
P_local[i,li]<-candmax
maxrow[i,li]<-rowmaps[[j]]$backwards[nrows-rowmaps[[j]]$forward[i]+1]
}
}
}
}
maxmatrix[[j]]<-P_local
maxrows[[j]]<-maxrow
}
listy$maxmatrix<-maxmatrix
listy$maxrow<-maxrows
return(listy)
}
}
parentsmapping<-function(parenttable,numberofparentsvec,n,updatenodes=c(1:n)) {
maps<-list()
mapi<-list()
for (i in updatenodes) {
nrows<-nrow(parenttable[[i]])
P_local <- numeric(nrows)
P_localinv <- numeric(nrows)
P_local[1]<-1
P_localinv[1]<-1
if (nrows>1){
for (j in 2:nrows) {
parentnodes <- parenttable[[i]][j,c(1:numberofparentsvec[[i]][j])]
P_local[j]<-sum(2^parentnodes)/2+1
P_localinv[P_local[j]]<-j
}
}
mapi$forward<-P_local
mapi$backwards<-P_localinv
maps[[i]]<- mapi
}
return(maps)
}
poset<-function(parenttable,numberofparentsvec,rowmaps,n,updatenodes=c(1:n)){
posetparenttables<-list(length=n)
for (i in updatenodes) {
nrows<-nrow(parenttable[[i]])
ncols<-ncol(parenttable[[i]])
posetparenttables[[i]]<-matrix(NA,nrow=nrows,ncol=ncols)
offsets<-rep(1,nrows)
if(nrows>1) {
for(j in nrows:2){
parentnodes<- parenttable[[i]][j,c(1:numberofparentsvec[[i]][j])]
children<-rowmaps[[i]]$backwards[rowmaps[[i]]$forward[j]-2^parentnodes/2]
posetparenttables[[i]][cbind(children,offsets[children])]<-j
offsets[children]<-offsets[children]+1
}
}
}
return(posetparenttables)
}
|
ff_scoringhistory.flea_conn <- function(conn, season = 1999:2020, ...) {
checkmate::assert_numeric(season, lower = 1999, upper = as.integer(format(Sys.Date(), "%Y")))
league_rules <-
ff_scoring(conn) %>%
dplyr::left_join(
ffscrapr::nflfastr_stat_mapping %>%
dplyr::filter(.data$platform == "fleaflicker") %>%
dplyr::mutate(ff_event = as.integer(.data$ff_event)),
by = c("event_id" = "ff_event")
)
ros <- .nflfastr_roster(season)
ps <- .nflfastr_offense_long(season)
if("K" %in% league_rules$pos){
ps <- dplyr::bind_rows(
ps,
.nflfastr_kicking_long(season))
}
ros %>%
dplyr::inner_join(ps, by = c("gsis_id"="player_id","season")) %>%
dplyr::inner_join(league_rules, by = c("metric"="nflfastr_event","pos")) %>%
dplyr::mutate(points = .data$value * .data$points) %>%
dplyr::group_by(.data$season, .data$week, .data$gsis_id, .data$sportradar_id) %>%
dplyr::mutate(points = round(sum(.data$points, na.rm = TRUE), 2)) %>%
dplyr::ungroup() %>%
tidyr::pivot_wider(
id_cols = c("season", "week", "gsis_id", "sportradar_id","fleaflicker_id",
"player_name", "pos", "team", "points"),
names_from = .data$metric,
values_from = .data$value,
values_fill = 0,
values_fn = max
)
}
|
dof.tr <- function(var.st){
var.st <- ifelse( var.st > 5.51, 5.51, var.st )
var.st <- ifelse( var.st < -10, -10, var.st )
vao <- exp(var.st) + 2
list(var.st = var.st, vao = vao )
}
|
context("test-preprocessing")
cds <- load_a549()
cds <- estimate_size_factors(cds)
test_that("preprocessing stays the same", {
cds <- preprocess_cds(cds, method = "PCA", num_dim = 20)
expect_equivalent(ncol(reducedDims(cds)$PCA), 20)
expect_equivalent(nrow(reducedDims(cds)$PCA), nrow(colData(cds)))
expect_equivalent(reducedDims(cds)$PCA[1,1], 2.4207391, tol = 1e-5)
cds <- preprocess_cds(cds, method = "LSI", num_dim = 20)
expect_equivalent(ncol(reducedDims(cds)$LSI), 20)
expect_equivalent(nrow(reducedDims(cds)$LSI), nrow(colData(cds)))
expect_equivalent(reducedDims(cds)$LSI[1,1], 13.73796, tol = 1e-5)
cds <- preprocess_cds(cds, method = "PCA", norm_method = "size_only",
num_dim = 20)
expect_equivalent(ncol(reducedDims(cds)$PCA), 20)
expect_equivalent(nrow(reducedDims(cds)$PCA), nrow(colData(cds)))
expect_equivalent(reducedDims(cds)$PCA[1,1], 2.222207, tol = 1e-5)
cds <- preprocess_cds(cds, method = "LSI", norm_method = "size_only",
num_dim = 20)
expect_equivalent(ncol(reducedDims(cds)$LSI), 20)
expect_equivalent(nrow(reducedDims(cds)$LSI), nrow(colData(cds)))
expect_equivalent(reducedDims(cds)$LSI[1,1], 13.49733, tol = 1e-5)
cds <- preprocess_cds(cds, method = "PCA", norm_method = "none",
num_dim = 20)
expect_equivalent(ncol(reducedDims(cds)$PCA), 20)
expect_equivalent(nrow(reducedDims(cds)$PCA), nrow(colData(cds)))
expect_equivalent(reducedDims(cds)$PCA[1,1], -2.42836, tol = 1e-5)
cds <- preprocess_cds(cds, method = "LSI", norm_method = "none",
num_dim = 20)
expect_equivalent(ncol(reducedDims(cds)$LSI), 20)
expect_equivalent(nrow(reducedDims(cds)$LSI), nrow(colData(cds)))
expect_equivalent(reducedDims(cds)$LSI[1,1], 13.49733, tol = 1e-5)
cds <- preprocess_cds(cds, method = "PCA", scaling=FALSE,
verbose = TRUE, norm_method = "size_only",
pseudo_count = 1.4, num_dim = 20)
expect_equal(ncol(reducedDims(cds)$PCA), 20)
expect_equal(nrow(reducedDims(cds)$PCA), nrow(colData(cds)))
expect_equal(reducedDims(cds)$PCA[1,1], -24.30544, tol = 1e-5)
cds <- preprocess_cds(cds, method = "PCA", num_dim = 20,
residual_model_formula_str = "~PCR_plate")
expect_equal(ncol(reducedDims(cds)$PCA), 20)
expect_equal(nrow(reducedDims(cds)$PCA), nrow(colData(cds)))
expect_equal(reducedDims(cds)$PCA[2,1], 1.982232, tol = 1e-5)
cds <- preprocess_cds(cds, method = "PCA", num_dim = 20,
use_genes = c(row.names(rowData(cds))[1:100]))
expect_equal(ncol(reducedDims(cds)$PCA), 20)
expect_equal(nrow(reducedDims(cds)$PCA), nrow(colData(cds)))
expect_equal(reducedDims(cds)$PCA[2,1], -0.5347819, tol = 1e-5)
})
|
chrome_exec <- function() {
exec_locate("chrome")
exec_available("chrome", error = TRUE)
.exec$chrome$exec_file
}
firefox_exec <- function() {
exec_locate("firefox")
exec_available("firefox", error = TRUE)
.exec$firefox$exec_file
}
libreoffice_exec <- function() {
exec_locate("libreoffice")
exec_available("libreoffice", error = TRUE)
.exec$libreoffice$exec_file
}
node_exec <- function() {
exec_locate("node")
.exec$node$exec_file
}
npm_exec <- function() {
exec_locate("npm")
.exec$npm$exec_file
}
python_exec <- function() {
exec_locate("python")
exec_available("python", error = TRUE)
.exec$python$exec_file
}
pip_exec <- function() {
exec_locate("pip")
exec_available("pip", error = TRUE)
.exec$pip$exec_file
}
word_exec <- function() {
exec_locate("word")
exec_available("word", error = TRUE)
.exec$word$exec_file
}
powerpoint_exec <- function() {
exec_locate("powerpoint")
exec_available("powerpoint", error = TRUE)
.exec$powerpoint$exec_file
}
excel_exec <- function() {
exec_locate("excel")
exec_available("excel", error = TRUE)
.exec$excel$exec_file
}
|
library(testthat)
library(BayesianFirstAid)
test_check("BayesianFirstAid")
|
library(testthat)
library(gluedown)
library(rvest)
library(glue)
test_that("md_convert can optionally disallow certain HTML", {
"foo" %>%
md_bold() %>%
md_convert(disallow = FALSE) %>%
read_html() %>%
html_node("strong") %>%
html_text() %>%
expect_equal("foo")
})
|
slurm_call <- function(f, params = list(), jobname = NA, global_objects = NULL, add_objects = NULL,
pkgs = rev(.packages()), libPaths = NULL, rscript_path = NULL,
r_template = NULL, sh_template = NULL, slurm_options = list(),
submit = TRUE) {
if (!is.function(f)) {
stop("first argument to slurm_call should be a function")
}
if (!missing(params)) {
if (!is.list(params)) {
stop("second argument to slurm_call should be a list")
}
if (is.null(names(params)) || (!is.primitive(f) && !"..." %in% names(formals(f)) && any(!names(params) %in% names(formals(f))))) {
stop("names of params must match arguments of f")
}
}
if (!missing("add_objects")) {
warning("Argument add_objects is deprecated; use global_objects instead.", .call = FALSE)
global_objects <- add_objects
}
if(is.null(r_template)) {
r_template <- system.file("templates/slurm_run_single_R.txt", package = "rslurm")
}
if(is.null(sh_template)) {
sh_template <- system.file("templates/submit_single_sh.txt", package = "rslurm")
}
jobname <- make_jobname(jobname)
tmpdir <- paste0("_rslurm_", jobname)
dir.create(tmpdir, showWarnings = FALSE)
saveRDS(params, file = file.path(tmpdir, "params.RDS"))
saveRDS(f, file = file.path(tmpdir, "f.RDS"))
if (!is.null(global_objects)) {
save(list = global_objects,
file = file.path(tmpdir, "add_objects.RData"),
envir = environment(f))
}
template_r <- readLines(r_template)
script_r <- whisker::whisker.render(template_r,
list(pkgs = pkgs,
add_obj = !is.null(global_objects),
libPaths = libPaths))
writeLines(script_r, file.path(tmpdir, "slurm_run.R"))
template_sh <- readLines(sh_template)
slurm_options <- format_option_list(slurm_options)
if (is.null(rscript_path)){
rscript_path <- file.path(R.home("bin"), "Rscript")
}
script_sh <- whisker::whisker.render(template_sh,
list(jobname = jobname,
flags = slurm_options$flags,
options = slurm_options$options,
rscript = rscript_path))
writeLines(script_sh, file.path(tmpdir, "submit.sh"))
if (submit && system('squeue', ignore.stdout = TRUE)) {
submit <- FALSE
cat("Cannot submit; no Slurm workload manager found\n")
}
if (submit) {
jobid <- submit_slurm_job(tmpdir)
} else {
jobid <- NA
cat(paste("Submission scripts output in directory", tmpdir,"\n"))
}
slurm_job(jobname, jobid, 1)
}
|
step_lemma <-
function(recipe,
...,
role = NA,
trained = FALSE,
columns = NULL,
skip = FALSE,
id = rand_id("lemma")) {
add_step(
recipe,
step_lemma_new(
terms = enquos(...),
role = role,
trained = trained,
columns = columns,
skip = skip,
id = id
)
)
}
step_lemma_new <-
function(terms, role, trained, columns, skip, id) {
step(
subclass = "lemma",
terms = terms,
role = role,
trained = trained,
columns = columns,
skip = skip,
id = id
)
}
prep.step_lemma <- function(x, training, info = NULL, ...) {
col_names <- recipes_eval_select(x$terms, training, info)
check_list(training[, col_names])
step_lemma_new(
terms = x$terms,
role = x$role,
trained = TRUE,
columns = col_names,
skip = x$skip,
id = x$id
)
}
bake.step_lemma <- function(object, new_data, ...) {
col_names <- object$columns
for (i in seq_along(col_names)) {
variable <- new_data[, col_names[i], drop = TRUE]
if (is.null(maybe_get_lemma(variable))) {
rlang::abort(paste0(
"`", col_names[i],
"` doesn't have a lemma attribute. ",
"Make sure the tokenization step includes ",
"lemmatization."
))
} else {
lemma_variable <- tokenlist_lemma(variable)
}
new_data[, col_names[i]] <- tibble(lemma_variable)
}
new_data <- factor_to_text(new_data, col_names)
as_tibble(new_data)
}
print.step_lemma <-
function(x, width = max(20, options()$width - 30), ...) {
cat("Lemmatization for ", sep = "")
printer(x$columns, x$terms, x$trained, width = width)
invisible(x)
}
tidy.step_lemma <- function(x, ...) {
if (is_trained(x)) {
res <- tibble(terms = unname(x$columns))
} else {
term_names <- sel2char(x$terms)
res <- tibble(terms = term_names)
}
res$id <- x$id
res
}
required_pkgs.step_lemma <- function(x, ...) {
c("textrecipes")
}
|
runExample <- function(example) {
validExamples <-
paste0(
'Valid examples are: "',
paste(list.files(system.file("examples", package = "shinyjs")),
collapse = '", "'),
'"')
if (missing(example) || !nzchar(example)) {
message(
'Please run `runExample()` with a valid example app as an argument.\n',
validExamples)
return(invisible(NULL))
}
appDir <- system.file("examples", example,
package = "shinyjs")
if (appDir == "") {
errMsg(sprintf("could not find example app `%s`\n%s",
example, validExamples))
}
shiny::runApp(appDir, display.mode = "normal")
}
|
student = read.csv('data/student1.csv')
str(student)
student$dob = as.Date(student$dob, format = "%d-%b-%y")
str(student)
student$age = round(as.numeric((Sys.Date() - student$dob)/365 ))
head(student)
smp_size <- floor(0.80 * nrow(student))
smp_size
set.seed(123)
train_ind <- sample(seq_len(nrow(student)), size = smp_size)
train_ind
train1 <- student[train_ind, ]
head(train1)
str(train1)
test1 <- student[-train_ind, ]
head(test1)
str(test1)
nrow(train1);nrow(test1)
x_train = train1[,c('age','class10','sem1')]
head(x_train)
y_train = train1$btechmarks
head(y_train)
x_test = train1[,c('age','class10','sem1')]
head(x_test)
|
select_last_nodes_created <- function(graph) {
time_function_start <- Sys.time()
fcn_name <- get_calling_fcn()
if (graph_object_valid(graph) == FALSE) {
emit_error(
fcn_name = fcn_name,
reasons = "The graph object is not valid")
}
if (graph_contains_nodes(graph) == FALSE) {
emit_error(
fcn_name = fcn_name,
reasons = "The graph contains no nodes")
}
graph_transform_steps <-
graph$graph_log %>%
dplyr::mutate(step_created_nodes = dplyr::if_else(
function_used %in% node_creation_functions(), 1, 0)) %>%
dplyr::mutate(step_deleted_nodes = dplyr::if_else(
function_used %in% node_deletion_functions(), 1, 0)) %>%
dplyr::mutate(step_init_with_nodes = dplyr::if_else(
function_used %in% graph_init_functions() &
nodes > 0, 1, 0)) %>%
dplyr::filter(
step_created_nodes == 1 | step_deleted_nodes == 1 | step_init_with_nodes) %>%
dplyr::select(-version_id, -time_modified, -duration)
if (nrow(graph_transform_steps) > 0) {
if (graph_transform_steps %>%
utils::tail(1) %>%
dplyr::pull(step_deleted_nodes) == 1) {
emit_error(
fcn_name = fcn_name,
reasons = "The previous graph transformation function resulted in a removal of nodes")
} else {
if (nrow(graph_transform_steps) > 1) {
number_of_nodes_created <-
(graph_transform_steps %>%
dplyr::select(nodes) %>%
utils::tail(2) %>%
dplyr::pull(nodes))[2] -
(graph_transform_steps %>%
dplyr::select(nodes) %>%
utils::tail(2) %>%
dplyr::pull(nodes))[1]
} else {
number_of_nodes_created <-
graph_transform_steps %>%
dplyr::pull(nodes)
}
}
node_id_values <-
graph$nodes_df %>%
dplyr::select(id) %>%
utils::tail(number_of_nodes_created) %>%
dplyr::pull(id)
} else {
node_id_values <- NA
}
if (!any(is.na(node_id_values))) {
graph <-
suppressMessages(
select_nodes(
graph = graph,
nodes = node_id_values))
graph$graph_log <-
graph$graph_log[-nrow(graph$graph_log),] %>%
add_action_to_log(
version_id = nrow(graph$graph_log) + 1,
function_used = fcn_name,
time_modified = time_function_start,
duration = graph_function_duration(time_function_start),
nodes = nrow(graph$nodes_df),
edges = nrow(graph$edges_df))
if (graph$graph_info$write_backups) {
save_graph_as_rds(graph = graph)
}
}
graph
}
|
mdbeta <- function(D=1,rangebeta,ngridbeta,a=5,b=25,r=0.00025,a0=0.5,b0=0.5,plot=FALSE,log=FALSE)
{
if(D==1)
{
mbetas = seq(rangebeta[1],rangebeta[2],length=ngridbeta)
res = rep(NA,ngridbeta)
funcintegrated0 <- function(tau,betai)
{
C = b^a*gamma(a+0.5)/((2*pi)^(D/2+0.5)*gamma(a))
ret = C*(b+0.5*tau^2/r)^(-a-0.5)/abs(tau)*exp(-betai*betai/tau^2)
return((b0/(a0+b0))*ret)
}
funcintegrated1 <- function(tau,betai)
{
C = b^a*gamma(a+0.5)/((2*pi)^(D/2+0.5)*gamma(a))
ret = C*(b+0.5*tau^2)^(-a-0.5)/abs(tau)*exp(-betai*betai/tau^2)
return((a0/(a0+b0))*ret)
}
for(betai1 in 1:ngridbeta)
{
temp1 = integrate(funcintegrated0,0,Inf,betai=mbetas[betai1])$val
temp2 = integrate(funcintegrated1,0,Inf,betai=mbetas[betai1])$val
res[betai1] = temp1+temp2
rm(temp1,temp2)
}
if(plot && !log) {
pl <- function() {plot(mbetas,res,type="l",xlab=expression(paste(beta,sep="")),ylab=expression(paste(p(beta),sep="")),
main=expression(paste("Marginal density ",p(beta),sep=""))) }
return(list(betas=mbetas,val=res,pl=pl))
} else if (plot && log) {
pl <- function() {plot(mbetas,res,type="l",xlab=expression(paste(beta,sep="")),ylab=expression(paste(p(beta),sep="")),
main=expression(paste("Marginal density ",p(beta),sep=""))) }
logpl <- function() {plot(mbetas,logres,type="l",xlab=expression(paste(beta,sep="")),ylab=expression(paste(log(p(beta)),sep="")),
main=expression(paste("Log-marginal density ",log(p(beta)),sep=""))) }
logres = log(res)
return(list(betas=mbetas,val=res,pl=pl,logval=logres,logpl=logpl))
} else if (!plot && log) {
logres = log(res)
return(list(betas=mbetas,val=res,logval=logres))
} else {
return(list(betas=mbetas,val=res))}
} else if(D==2) {
betas = seq(rangebeta[1],rangebeta[2],length=ngridbeta)
mbetas = expand.grid(betas,betas)
mbetas = matrix(as.data.frame(t(mbetas)),nrow=ngridbeta)
res = matrix(NA,nrow=dim(mbetas)[1],ncol=dim(mbetas)[2])
funcintegrated0 <- function(tau,betai)
{
C = b^a*gamma(a+0.5)/((2*pi)^(D/2+0.5)*gamma(a))
ret = C*(b+0.5*tau^2/r)^(-a-0.5)/abs(tau)*exp(-sum(betai*betai)/tau^2)
return((b0/(a0+b0))*ret)
}
funcintegrated1 <- function(tau,betai)
{
C = b^a*gamma(a+0.5)/((2*pi)^(D/2+0.5)*gamma(a))
ret = C*(b+0.5*tau^2)^(-a-0.5)/abs(tau)*exp(-sum(betai*betai)/tau^2)
return((a0/(a0+b0))*ret)
}
for(rowi in 1:ngridbeta)
{
for(coli in 1:ngridbeta)
{
temp1 = integrate(funcintegrated0,0,Inf,betai=mbetas[rowi,coli][[1]])$val
temp2 = integrate(funcintegrated1,0,Inf,betai=mbetas[rowi,coli][[1]])$val
res[rowi,coli] = temp1+temp2
rm(temp1,temp2)
}
}
if(plot && !log) {
pl <- function() {contour(betas,betas,res,xlab=expression(paste(beta[1],sep="")),ylab=expression(paste(beta[2],sep="")),
main=expression(paste("Marginal density ",p(beta[1],beta[2]),sep="")),drawlabels=FALSE) }
return(list(betas=betas,val=res,pl=pl))
} else if (plot && log) {
pl <- function() {contour(betas,betas,res,xlab=expression(paste(beta[1],sep="")),ylab=expression(paste(beta[2],sep="")),
main=expression(paste("Marginal density ",p(beta[1],beta[2]),sep="")),drawlabels=FALSE) }
logpl <- function() {contour(betas,betas,log(res),xlab=expression(paste(beta[1],sep="")),ylab=expression(paste(beta[2],sep="")),
main=expression(paste("Log-marginal density ",log(p(beta[1],beta[2])),sep="")),drawlabels=FALSE) }
logres = log(res)
return(list(betas=betas,val=res,pl=pl,logval=logres,logpl=logpl))
} else if (!plot && log) {
logres = log(res)
return(list(betas=betas,val=res,logval=logres))
} else {
return(list(betas=betas,val=res))}
} else {
stop("D has to be either 1 or 2.")
}
}
|
`propdiff.freq0` <-
function(len, c1, d1, c2, d2, level=0.95)
{
propdiff.freq(len, c1/(c1+d1), c2/(c2+d2), level)
}
|
WrapCircular <- function(x, circular = "lon", wrap = c(0, 360)) {
warningf("'WrapCircular' is deprecated, use ggperiodic::wrap instead.")
checks <- makeAssertCollection()
assertDataFrame(x, add = checks)
assertCharacter(circular, len = 1, any.missing = FALSE, add = checks)
assertNumeric(wrap, len = 2)
reportAssertions(checks)
if (nrow(x) == 0) return(x)
x <- data.table::as.data.table(x)
data.table::setorderv(x, circular)
res <- ggplot2::resolution(x[[circular]])
m <- min(x[[circular]])
M <- max(x[[circular]])
right <- trunc((max(wrap) - M)/res)
left <- trunc((min(wrap) - m)/res)
x.new <- seq(m + left*res, M + right*res, by = res)
right <- right + data.table::uniqueN(x[[circular]]) - 1
index <- seq(left, right)
index <- index %% length(unique(x[[circular]])) + 1
x.old <- unique(x[[circular]])[index]
x.new <- data.table::data.table(x.old, x.new)
colnames(x.new) <- c(circular, paste0(circular, "new"))
y <- x[x.new, on = circular, allow.cartesian = TRUE]
data.table::set(y, NULL, circular, NULL )
data.table::setnames(y, paste0(circular, "new"), circular)
return(y)
}
RepeatCircular <- function(x, circular = "lon", max = NULL) {
.Deprecated("WrapCircular")
}
|
get.2dfcom <- function(object, dfcom = NULL) {
if (rlang::is_bare_numeric(dfcom, 1) && is.finite(dfcom)) {
return(max(dfcom, 1L))
}
else dfcom <- NULL
if (!inherits(object, "mimira")) stop("The input for the object must be an object of the 'mimira' class.")
glanced <- try(summary(mice::getfit(object), type = "glance"), silent = TRUE)
if (!inherits(glanced, "try-error")) {
if ("df.residual" %in% names(glanced)) {
dfcom <- min(glanced$df.residual)
}
else {
model <- mice::getfit(object, 1L)
if (inherits(model, "coxph") && "nevent" %in% names(glanced)) {
dfcom <- min(glanced$nevent - length(coef(model)))
}
else {
if (!"nobs" %in% names(glanced)) {
glanced$nobs <- min(lengths(lapply(object$analyses, stats::residuals)), na.rm = TRUE)
}
dfcom <- min(glanced$nobs - length(coef(model)))
}
}
}
if (is.null(dfcom) || !is.finite(dfcom)) dfcom <- 999999
dfcom
}
|
"hybrid_phe"
|
tar_cue_skip <- function(
condition,
command = TRUE,
depend = TRUE,
format = TRUE,
iteration = TRUE,
file = TRUE
) {
mode <- if_any(as.logical(condition), "never", "thorough")
targets::tar_cue(
mode = mode,
command = command,
depend = depend,
format = format,
iteration = iteration,
file = file
)
}
|
setGeneric(name="BinSeg",
def=function(H, thresh="universal", q=0.99, p= 1, z=NULL,start.values=c(0.9,0.6),dampen.factor="auto",epsilon= 0.00001,LOG=TRUE,process="acd",acd_p=0,acd_q=1,do.parallel=2)
{
standardGeneric("BinSeg")
}
)
setMethod(f="BinSeg", definition = function(H, thresh="universal", q=0.99, p= 1, z=NULL,start.values=c(0.9,0.6),dampen.factor="auto",epsilon= 0.00001,LOG=TRUE,process="acd",acd_p=0,acd_q=1,do.parallel=2) {
if (thresh == "universal"){
thresh = pi_thresh(N=length(H),q=q,process=process)*log(length(H))
} else if (thresh == "boot"){
thresh = boot_thresh(H=H,q=q,r=100,p=p,start.values=start.values,process=process,do.parallel=do.parallel,dampen.factor=dampen.factor,epsilon= epsilon,LOG=LOG,acd_p=acd_p,acd_q=acd_q)
}
if (is.null(z)) z=Z_trans(H=H,start.values = start.values,dampen.factor = dampen.factor,epsilon = epsilon,LOG = LOG,process = process,acd_p = acd_p,acd_q = acd_q)
cp.est = BinSegTree(z,thresh=thresh,p=p)$breakpoints
out = list()
out[[1]] = cp.est
out[[2]] = z
return(out)
})
|
anthroplus_zscores <- function(sex,
age_in_months = NA_real_,
oedema = NA_character_,
height_in_cm = NA_real_,
weight_in_kg = NA_real_) {
stopifnot(all(tolower(sex) %in% c("1", "2", "f", "m", NA_character_)))
stopifnot(all(tolower(oedema) %in% c("1", "2", "y", "n", NA_character_)))
stopifnot(all(age_in_months >= 0, na.rm = TRUE))
stopifnot(all(height_in_cm >= 0, na.rm = TRUE))
stopifnot(all(weight_in_kg >= 0, na.rm = TRUE))
input <- data.frame(sex, age_in_months, oedema, height_in_cm, weight_in_kg)
cbmi <- compute_bmi(input$weight_in_kg, input$height_in_cm)
coedema <- anthro_api_standardize_oedema_var(input$oedema)
csex <- anthro_api_standardize_sex_var(input$sex)
zhfa <- zscore_height_for_age(
sex = csex, age_in_months = input$age_in_months,
height = input$height_in_cm
)
zwfa <- zscore_weight_for_age(
sex = csex, age_in_months = input$age_in_months,
oedema = coedema, weight = input$weight_in_kg
)
zbfa <- zscore_bmi_for_age(
sex = csex, age_in_months = input$age_in_months,
oedema = coedema, bmi = cbmi
)
zhfa <- round(zhfa, digits = 2L)
zwfa <- round(zwfa, digits = 2L)
zbfa <- round(zbfa, digits = 2L)
fhfa <- flag_scores(zhfa, !is.na(zhfa) & abs(zhfa) > 6)
fwfa <- flag_scores(zwfa, !is.na(zwfa) & (zwfa > 5 | zwfa < -6))
fbfa <- flag_scores(zbfa, !is.na(zbfa) & abs(zbfa) > 5)
data.frame(
age_in_months,
csex,
coedema,
cbmi,
zhfa,
zwfa,
zbfa,
fhfa,
fwfa,
fbfa
)
}
flag_scores <- function(zscores, condition) {
stopifnot(length(zscores) == length(condition))
flags <- rep.int(0L, length(zscores))
flags[condition] <- 1L
if (anyNA(zscores)) {
flags[is.na(zscores)] <- NA_integer_
}
flags
}
compute_bmi <- function(weight, height) {
weight / ((height / 100)^2)
}
WFA_UPPER_AGE_LIMIT <- 120
zscore_weight_for_age <- function(sex, age_in_months, oedema,
weight) {
weight[oedema == "y"] <- NA_real_
zscore_indicator(sex, age_in_months, weight,
wfa_growth_standards,
age_upper_bound = WFA_UPPER_AGE_LIMIT,
zscore_fun = anthro_api_compute_zscore_adjusted
)
}
zscore_height_for_age <- function(sex, age_in_months,
height) {
zscore_indicator(sex, age_in_months, height,
hfa_growth_standards,
age_upper_bound = 228,
zscore_fun = anthro_api_compute_zscore
)
}
zscore_bmi_for_age <- function(sex, age_in_months, oedema,
bmi) {
bmi[oedema == "y"] <- NA_real_
zscore_indicator(sex, age_in_months, bmi,
bfa_growth_standards,
age_upper_bound = 228,
zscore_fun = anthro_api_compute_zscore_adjusted
)
}
zscore_indicator <- function(sex,
age_in_months,
measure,
growth_standards,
age_upper_bound,
zscore_fun) {
low_age <- trunc(age_in_months)
upp_age <- trunc(age_in_months + 1)
diff_age <- age_in_months - low_age
data <- data.frame(
sex,
low_age,
upp_age,
ordering = seq_along(sex)
)
match_low_age <- merge(data, growth_standards,
by.x = c("sex", "low_age"),
by.y = c("sex", "age"),
all.x = TRUE, sort = FALSE
)
match_upp_age <- merge(data, growth_standards,
by.x = c("sex", "upp_age"),
by.y = c("sex", "age"),
all.x = TRUE, sort = FALSE
)
match_low_age <- match_low_age[order(match_low_age$ordering), ]
match_upp_age <- match_upp_age[order(match_upp_age$ordering), ]
m <- match_low_age[["m"]]
l <- match_low_age[["l"]]
s <- match_low_age[["s"]]
is_diff_age_pos <- !is.na(diff_age) & diff_age > 0
if (any(is_diff_age_pos)) {
adjust_param <- function(x) {
x_name <- as.character(substitute(x))
x[is_diff_age_pos] + diff_age[is_diff_age_pos] *
(match_upp_age[[x_name]][is_diff_age_pos] - x[is_diff_age_pos])
}
m[is_diff_age_pos] <- adjust_param(m)
l[is_diff_age_pos] <- adjust_param(l)
s[is_diff_age_pos] <- adjust_param(s)
}
zscores <- zscore_fun(measure, m, l, s)
has_invalid_valid_age <- is.na(age_in_months) |
!(age_in_months >= 61 & age_in_months <= age_upper_bound)
zscores[has_invalid_valid_age] <- NA_real_
zscores
}
|
oceania <- function(title = "Oceania", coords = NULL) {
select_proj <- '+proj=moll'
world <- rnaturalearth::ne_countries(continent = "Oceania",
scale = "medium",
returnclass = "sf") %>%
sf::st_transform(select_proj)
num <- nrow(world)
my_data <- data.frame(
name = world$name,
Numbers = 1 : num )
plot_data <- merge(world, my_data,
by = "name",
all.x = TRUE)
if (!is.null( coords ) ) {
d_points <- data.frame(long = coords[, 1] ,
lat = coords[, 2]) %>%
st_as_sf(coords = c("long", "lat"), crs = 4326) %>%
st_transform(crs = select_proj)
}
map_theme <- theme(
plot.title = element_text(color = "chartreuse",
size = 16,
face = "bold",
hjust = 0.5),
axis.title.x = element_text(color = "limegreen",
size = 14,
face = "bold.italic"),
axis.title.y = element_text(color = "limegreen",
size = 14,
face = "bold.italic"),
plot.background = element_rect(fill = "black"),
panel.grid.major = element_line(colour = "black",
size = 0.5,
linetype = 3),
panel.background = element_rect(fill = "honeydew2",
colour = "honeydew2",
size = 0.8,
linetype = "solid"),
axis.line = element_line(size = 1.5,
colour = "white"),
axis.ticks = element_line(size = 2,
colour = "white"),
axis.text.x = element_text( size = 14,
colour = "white"),
axis.text.y = element_text( size = 14,
colour = "white"),
legend.background = element_rect(fill = "gray",
size = 0.5,
linetype = "solid") )
ggplot() +
geom_sf(data = plot_data,
aes(fill = my_data$Numbers)) +
xlim(c(10000000, 17596910)) +
ylim(c(-6361366, 0)) +
{if (!is.null( coords ) )
geom_sf(data = d_points,
color = "black",
size = 1,
shape = 23)} +
ggtitle(title)+
labs(fill = "Number") +
map_theme +
scale_fill_gradientn(colors = heat.colors(num) )
}
|
build.lut <-
function(LEVEL=6, REPSIM=5, RAJZ=FALSE, CIM="", ENV="data") {
opar <- par(no.readonly =TRUE)
on.exit(par(opar))
DIFF <- rep(0, 110)
dim(DIFF) <- c(10, 11)
IX <- 0
IY <- 0
for(luprho in seq(0, 0.2499999, 0.0277777)) {
RHO <- luprho
IX <- IX + 1
IY <- 0
for(lupcprop in seq(0.1, 0.9, 0.1)) {
CPROP <- lupcprop
IY <- IY + 1
for(lup in 1:REPSIM) {
RESULTT <- wtest.run(REPSIM = REPSIM, LEVEL = LEVEL, RHO= RHO, CPROP = CPROP, RAJZ = RAJZ, CIM = CIM, ENV=ENV)
}
DIFF[IX, IY] <- median(RESULTT[1, ]) - median(RESULTT[2,])
}
}
return(DIFF)
}
|
to_char_uneval_matrix <- function(x) {
ex <- unlist(lapply(x, function(y) deparse(y$expr, width.cutoff = 500)))
ex[ex == "0"] <- ""
matrix(ex,
byrow = TRUE,
ncol = get_matrix_order(x),
dimnames = list(get_state_names(x),
get_state_names(x)))
}
print.uneval_matrix <- function(x, ...) {
cat(sprintf(
"A transition matrix, %i states.\n\n",
get_matrix_order(x)
))
res <- to_char_uneval_matrix(x)
print(res,
quote = FALSE,
...)
}
print.eval_matrix <- function(x, ...) {
cat(sprintf(
"An evaluated transition matrix, %i states, %i markov cycles.\n\n",
get_matrix_order(x),
length(x)
))
cat("State names:\n\n")
cat(get_state_names(x), sep = "\n")
cat("\n")
print(head(x, ...))
if (length(head(x, ...)) < length(x))
cat("...\n")
}
plot.uneval_matrix <- function(x, relsize = .75,
shadow.size = 0,
latex = TRUE, ...) {
if (! requireNamespace("diagram")) {
stop("'diagram' package required for transition plot.")
}
op <- graphics::par(mar = c(0, 0, 0, 0))
res <- to_char_uneval_matrix(x)
diagram::plotmat(
t(res[rev(seq_len(nrow(res))),
rev(seq_len(nrow(res)))]),
relsize = relsize, shadow.size = shadow.size,
absent = "",
latex = latex, ...
)
graphics::par(op)
}
reindent_transition <- function(x, print = TRUE) {
if (! requireNamespace("stringr")) {
stop("Package 'stringer' required.")
}
n_col <- get_matrix_order(x)
sn <- paste0('"', get_state_names(x), '"')
cells <- to_text_dots(x, name = FALSE)
max_char <- pmax(
nchar(sn),
apply(matrix(cells, ncol = n_col, byrow = TRUE), 2,
function (x) max(nchar(x)))
)
sn_pad <- stringr::str_pad(
string = sn,
width = max_char,
side = "right"
)
cells_pad <- stringr::str_pad(
string = cells,
width = rep(max_char, length(sn)),
side = "right"
)
res <- do.call(
stringr::str_c,
c(split(cells_pad, rep(seq_len(n_col), n_col)),
sep = ", ",
collapse = ",\n"))
res <- paste0(
"state_names = c(\n",
paste(sn_pad, collapse = ", "),
")\n",
res
)
if (print) {
cat(res)
}
invisible(res)
}
|
library(hpiR)
library(testthat)
sales <- get(data(seattle_sales))
context('rtCreateTrans()')
test_that("Can take a functional 'trans_df' object", {
sales_df <- dateToPeriod(trans_df = sales,
date = 'sale_date',
periodicity = 'monthly')
expect_is(rt_df <- rtCreateTrans(trans_df=sales_df,
prop_id='pinx',
trans_id='sale_id',
price='sale_price'),
'rtdata')
expect_true(nrow(rt_df) == 5102)
})
test_that("Can create own salesdf object", {
expect_is(rt_df <- rtCreateTrans(trans_df=sales,
prop_id='pinx',
trans_id='sale_id',
price='sale_price',
date='sale_date',
periodicity='monthly'),
'rtdata')
expect_true(nrow(rt_df) == 5102)
})
test_that("Can use min/max dates own salesdf object", {
expect_is(rt_df <- rtCreateTrans(trans_df=sales,
prop_id='pinx',
trans_id='sale_id',
price='sale_price',
date='sale_date',
periodicity='monthly',
min_date = as.Date('2012-03-21')),
'rtdata')
expect_true(nrow(rt_df) == 5102)
expect_is(rt_df <- rtCreateTrans(trans_df=sales,
prop_id='pinx',
trans_id='sale_id',
price='sale_price',
date='sale_date',
periodicity='monthly',
min_date = as.Date('2012-03-21'),
adj_type='clip'),
'rtdata')
expect_true(nrow(rt_df) == 2827)
expect_is(rt_df <- rtCreateTrans(trans_df=sales,
prop_id='pinx',
trans_id='sale_id',
price='sale_price',
date='sale_date',
periodicity='monthly',
max_date = as.Date('2015-03-21')),
'rtdata')
expect_true(nrow(rt_df) == 5102)
expect_is(rt_df <- rtCreateTrans(trans_df=sales,
prop_id='pinx',
trans_id='sale_id',
price='sale_price',
date='sale_date',
periodicity='monthly',
max_date = as.Date('2014-03-21'),
adj_type='clip'),
'rtdata')
expect_true(nrow(rt_df) == 1148)
})
test_that("Sequence only (seq_only) option works", {
expect_is(rt_df <- rtCreateTrans(trans_df=sales,
prop_id='pinx',
trans_id='sale_id',
price='sale_price',
date='sale_date',
periodicity='monthly',
seq_only = TRUE),
'rtdata')
expect_true(nrow(rt_df) == 4823)
})
test_that("min_period_dist argument works", {
expect_is(rt_df <- rtCreateTrans(trans_df=sales,
prop_id='pinx',
trans_id='sale_id',
price='sale_price',
date='sale_date',
periodicity='monthly',
seq_only = TRUE,
min_period_dist = 12),
'rtdata')
expect_true(nrow(rt_df) == 3795)
})
test_that("Fails if sales creation fails", {
expect_error(rt_df <- rtCreateTrans(trans_df=sales,
prop_id='pinx',
trans_id='sale_id',
price='sale_price',
date='sale_price',
periodicity='monthly'))
expect_error(rt_df <- rtCreateTrans(trans_df=sales,
prop_id='pinx',
trans_id='sale_id',
price='sale_price',
date='sale_date',
periodicity='mocnthly'))
})
sales_df <- dateToPeriod(trans_df = sales,
date = 'sale_date',
periodicity = 'monthly')
test_that("Fails if bad arguments fails", {
expect_error(rt_df <- rtCreateTrans(trans_df=sales_df,
prop_id='pinxx',
trans_id='sale_id',
price='sale_price'))
expect_error(rt_df <- rtCreateTrans(trans_df=sales_df,
prop_id='pinx',
trans_id='salex_id',
price='sale_price'))
expect_error(rt_df <- rtCreateTrans(trans_df=sales_df,
prop_id='pinx',
trans_id='sale_id',
price='salex_price'))
})
test_that("Returns NULL if no repeat sales", {
expect_is(rt_df <- rtCreateTrans(trans_df=sales_df[!duplicated(sales_df$prop_id),],
prop_id='pinx',
trans_id='sale_id',
price='sale_price'), "NULL")
expect_is(rt_df <- rtCreateTrans(trans_df=sales_df[1:3, ],
prop_id='pinx',
trans_id='sale_id',
price='sale_price'), "NULL")
})
context('rtTimeMatrix()')
rt_df <- rtCreateTrans(trans_df=sales_df,
prop_id='pinx',
trans_id='sale_id',
price='sale_price')
test_that('Time matrix operates properly', {
expect_is(time_matrix <- rtTimeMatrix(rt_df), 'timematrix')
expect_error(time_matrix <- rtTimeMatrix(sales_df))
expect_true(nrow(rtTimeMatrix(rt_df[1:2000,])) == 2000)
expect_true(ncol(rtTimeMatrix(rt_df[1:2000,])) ==
nrow(attr(rt_df, 'period_table')) - 1)
})
context('hpiModel.rtdata(): Prior to rtModel() call')
test_that('hpiModel.rtdata works in simplest format',{
expect_is(rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'base',
log_dep = TRUE),
'hpimodel')
})
test_that('"log_dep" argument works both ways',{
expect_true(hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'base',
log_dep = TRUE)$model_obj$fitted.values[1] < 1)
expect_true(hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'base',
log_dep = FALSE)$model_obj$fitted.values[1] > 10000)
})
test_that('Check for zero or negative prices works',{
rt_dfx <- rt_df
rt_dfx$price_1[1] <- 0
expect_error(rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_dfx,
estimator = 'base',
log_dep = TRUE))
expect_is(rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_dfx,
estimator = 'base',
log_dep = FALSE),
'hpimodel')
rt_dfx$price_1[1] <- NA_integer_
expect_error(rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_dfx,
estimator = 'base',
log_dep = TRUE))
expect_error(rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_dfx,
estimator = 'base',
log_dep = FALSE))
rt_dfx$price_1[1] <- Inf
expect_error(rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_dfx,
estimator = 'base',
log_dep = TRUE))
expect_error(rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_dfx,
estimator = 'base',
log_dep = FALSE))
})
test_that('Check for estimator type works',{
expect_true(hpiModel(model_type = 'rt',
hpi_df = rt_df)$estimator == 'base')
expect_true(hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator='xxxx')$estimator == 'base')
expect_true(hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator='robust')$estimator == 'robust')
expect_true(hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator='weighted')$estimator == 'weighted')
})
context('rtModel()')
time_matrix <- rtTimeMatrix(rt_df)
price_diff_l <- log(rt_df$price_2) - log(rt_df$price_1)
price_diff <- rt_df$price_2 - rt_df$price_1
test_that('Check for errort with bad arguments',{
expect_error(rt_model <- rtModel(rt_df = sales,
time_matrix = time_matrix,
price_diff = price_diff_l,
estimator=structure('base', class='base')))
expect_error(rt_model <- rtModel(rt_df = rt_df,
time_matrix = sales,
price_diff = price_diff_l,
estimator=structure('robust', class='robust')))
expect_error(rt_model <- rtModel(rt_df = rt_df,
time_matrix = time_matrix,
price_diff = price_diff_l[-1],
estimator=structure('weighted', class='weighted')))
expect_error(rt_model <- rtModel(rt_df = rt_df,
time_matrix = time_matrix,
price_diff = price_diff,
estimator=structure('base', class='xxx')))
})
test_that('Performance with sparse data',{
rt_df200 <- rt_df[1:200, ]
time_matrix200 <- rtTimeMatrix(rt_df200)
price_diff_l200 <- log(rt_df200$price_2) - log(rt_df200$price_1)
price_diff200 <- rt_df200$price_2 - rt_df200$price_1
expect_is(rt_model <- rtModel(rt_df = rt_df200,
time_matrix = time_matrix200,
price_diff = price_diff_l200,
estimator=structure('base', class='base')),
'rtmodel')
expect_is(rt_model <- rtModel(rt_df = rt_df200,
time_matrix = time_matrix200,
price_diff = price_diff_l200,
estimator=structure('robust', class='robust')),
'rtmodel')
expect_is(rt_model <- rtModel(rt_df = rt_df200,
time_matrix = time_matrix200,
price_diff = price_diff200,
estimator=structure('weighted', class='weighted')),
'rtmodel')
rt_df20 <- rt_df[1:20, ]
time_matrix20 <- rtTimeMatrix(rt_df20)
price_diff_l20 <- log(rt_df20$price_2) - log(rt_df20$price_1)
price_diff20 <- rt_df20$price_2 - rt_df20$price_1
expect_is(rt_model <- rtModel(rt_df = rt_df20,
time_matrix = time_matrix20,
price_diff = price_diff_l20,
estimator=structure('base', class='base')),
'rtmodel')
expect_warning(rt_model <- rtModel(rt_df = rt_df20,
time_matrix = time_matrix20,
price_diff = price_diff_l20,
estimator=structure('robust', class='robust')))
expect_is(rt_model <- rtModel(rt_df = rt_df20,
time_matrix = time_matrix20,
price_diff = price_diff20,
estimator=structure('weighted', class='weighted')),
'rtmodel')
})
context('hpiModel.rtdata(): after rtModel()')
test_that('hpiModel.rtdata works in both trim_model cases', {
expect_is(rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'base',
log_dep = TRUE,
trim_model=TRUE), 'hpimodel')
expect_is(rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'base',
log_dep = TRUE,
trim_model=FALSE), 'hpimodel')
expect_is(rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'base',
log_dep = FALSE,
trim_model=TRUE), 'hpimodel')
expect_is(rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'base',
log_dep = FALSE,
trim_model=FALSE), 'hpimodel')
expect_is(rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'weighted',
log_dep = TRUE,
trim_model=FALSE), 'hpimodel')
expect_is(rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'robust',
log_dep = FALSE,
trim_model=TRUE), 'hpimodel')
expect_true(is.null(hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'weighted',
log_dep = TRUE,
trim_model=TRUE)$model_obj$qr))
expect_true(!is.null(hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'weighted',
log_dep = TRUE,
trim_model=FALSE)$model_obj$qr))
})
test_that('hpiModel.rtdata outputs are correct', {
rt_model_base <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'base',
log_dep = TRUE,
trim_model=TRUE)
rt_model_robust <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'robust',
log_dep = TRUE,
trim_model=FALSE)
rt_model_wgt <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'weighted',
log_dep = FALSE,
trim_model=TRUE)
set.seed(123)
rt_model_wwgt <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'weighted',
log_dep = FALSE,
weights = runif(nrow(rt_df), 0, 1),
trim_model=TRUE)
expect_is(rt_model_base$estimator, 'base')
expect_is(rt_model_robust$estimator, 'robust')
expect_is(rt_model_wgt$estimator, 'weighted')
expect_is(rt_model_base$coefficients, 'data.frame')
expect_is(rt_model_robust$coefficients, 'data.frame')
expect_is(rt_model_wgt$coefficients, 'data.frame')
expect_true(nrow(rt_model_base$coefficients) == 84)
expect_true(max(rt_model_robust$coefficients$time) == 84)
expect_true(rt_model_wgt$coefficients$coefficient[1] == 0)
expect_false(identical(
rt_model_wgt$coefficients$coefficient,
rt_model_wwgt$coefficients$coefficient))
expect_is(rt_model_base$model_obj, 'rtmodel')
expect_is(rt_model_robust$model_obj, 'rtmodel')
expect_is(rt_model_wgt$model_obj, 'rtmodel')
expect_true(is.null(rt_model_base$model_spec))
expect_true(is.null(rt_model_robust$model_spec))
expect_true(is.null(rt_model_wgt$model_spec))
expect_true(round(rt_model_base$base_price, 0) == 427785)
expect_true(round(rt_model_robust$base_price, 0) == 427785)
expect_true(round(rt_model_wgt$base_price, 0) == 427785)
expect_is(rt_model_base$periods, 'data.frame')
expect_true(nrow(rt_model_base$periods) == 84)
expect_is(rt_model_robust$periods, 'data.frame')
expect_true(nrow(rt_model_robust$periods) == 84)
expect_is(rt_model_wgt$periods, 'data.frame')
expect_true(nrow(rt_model_wgt$periods) == 84)
expect_true(rt_model_base$approach == 'rt')
expect_true(rt_model_robust$approach == 'rt')
expect_true(rt_model_wgt$approach == 'rt')
})
context('modelToIndex')
rt_model <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'base',
log_dep = TRUE,
trim_model=TRUE)
test_that('modelToIndex works', {
expect_is(modelToIndex(rt_model), 'hpiindex')
})
test_that('modelToIndex works with other estimatort and options', {
expect_is(modelToIndex(hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'robust',
log_dep = TRUE,
trim_model=TRUE)), 'hpiindex')
expect_is(modelToIndex(hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'weighted',
log_dep = TRUE,
trim_model=TRUE)), 'hpiindex')
expect_is(modelToIndex(hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'robust',
log_dep = FALSE,
trim_model=TRUE)), 'hpiindex')
expect_is(modelToIndex(hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'weighted',
log_dep = TRUE,
trim_model=FALSE)), 'hpiindex')
})
test_that('modelToIndex fails with an error',{
expect_error(modelToIndex(model_obj = 'abc'))
})
test_that('modelToIndex imputes properly, BASE model, LogDEP',{
model_base <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'base',
log_dep = TRUE,
trim_model=TRUE)
model_ex <- model_base
model_ex$coefficients$coefficient[2] <- NA_real_
expect_is(modelToIndex(model_ex), 'hpiindex')
expect_true(!is.na(modelToIndex(model_ex)$value[2]))
expect_true(modelToIndex(model_ex)$value[2] == 100)
expect_true(modelToIndex(model_ex)$imputed[2] == 1)
model_ex <- model_base
model_ex$coefficients$coefficient[3:5] <- NA_real_
expect_is(modelToIndex(model_ex), 'hpiindex')
expect_true(all(!is.na(modelToIndex(model_ex)$value[3:5])))
model_ex <- model_base
model_ex$coefficients$coefficient[81:84] <- NA_real_
expect_is(modelToIndex(model_ex), 'hpiindex')
expect_true(all(!is.na(modelToIndex(model_ex)$value[81:84])))
expect_true(modelToIndex(model_ex)$value[80] ==
modelToIndex(model_ex)$value[84])
})
test_that('modelToIndex imputes properly, BASE model, LogDep=FALSE',{
model_base <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'base',
log_dep = FALSE,
trim_model=TRUE)
model_ex <- model_base
model_ex$coefficients$coefficient[2] <- NA_real_
expect_is(modelToIndex(model_ex), 'hpiindex')
expect_true(!is.na(modelToIndex(model_ex)$value[2]))
expect_true(modelToIndex(model_ex)$value[2] == 100)
expect_true(modelToIndex(model_ex)$imputed[2] == 1)
model_ex <- model_base
model_ex$coefficients$coefficient[3:5] <- NA_real_
expect_is(modelToIndex(model_ex), 'hpiindex')
expect_true(all(!is.na(modelToIndex(model_ex)$value[3:5])))
model_ex <- model_base
model_ex$coefficients$coefficient[81:84] <- NA_real_
expect_is(modelToIndex(model_ex), 'hpiindex')
expect_true(all(!is.na(modelToIndex(model_ex)$value[81:84])))
expect_true(modelToIndex(model_ex)$value[80] ==
modelToIndex(model_ex)$value[84])
})
test_that('modelToIndex imputes properly, Robust model, LogDEP = TRUE',{
model_base <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'robust',
log_dep = TRUE,
trim_model=TRUE)
model_ex <- model_base
model_ex$coefficients$coefficient[2] <- NA_real_
expect_is(modelToIndex(model_ex), 'hpiindex')
expect_true(!is.na(modelToIndex(model_ex)$value[2]))
expect_true(modelToIndex(model_ex)$value[2] == 100)
expect_true(modelToIndex(model_ex)$imputed[2] == 1)
model_ex <- model_base
model_ex$coefficients$coefficient[3:5] <- NA_real_
expect_is(modelToIndex(model_ex), 'hpiindex')
expect_true(all(!is.na(modelToIndex(model_ex)$value[3:5])))
model_ex <- model_base
model_ex$coefficients$coefficient[81:84] <- NA_real_
expect_is(modelToIndex(model_ex), 'hpiindex')
expect_true(all(!is.na(modelToIndex(model_ex)$value[81:84])))
expect_true(modelToIndex(model_ex)$value[80] ==
modelToIndex(model_ex)$value[84])
})
test_that('modelToIndex imputes properly, Weighted model, LogDep=FALSE',{
model_base <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'weighted',
log_dep = FALSE,
trim_model=TRUE)
model_ex <- model_base
model_ex$coefficients$coefficient[2] <- NA_real_
expect_is(modelToIndex(model_ex), 'hpiindex')
expect_true(!is.na(modelToIndex(model_ex)$value[2]))
expect_true(modelToIndex(model_ex)$value[2] == 100)
expect_true(modelToIndex(model_ex)$imputed[2] == 1)
model_ex <- model_base
model_ex$coefficients$coefficient[3:5] <- NA_real_
expect_is(modelToIndex(model_ex), 'hpiindex')
expect_true(all(!is.na(modelToIndex(model_ex)$value[3:5])))
model_ex <- model_base
model_ex$coefficients$coefficient[81:84] <- NA_real_
expect_is(modelToIndex(model_ex), 'hpiindex')
expect_true(all(!is.na(modelToIndex(model_ex)$value[81:84])))
expect_true(modelToIndex(model_ex)$value[80] ==
modelToIndex(model_ex)$value[84])
})
test_that('modelToIndex "max_period" cutoff works',{
model_base <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'weighted',
log_dep = FALSE,
trim_model=TRUE)
index_80 <- modelToIndex(model_base, max_period = 80)
expect_is(index_80, 'hpiindex')
expect_true(length(index_80$value) == 80)
})
context('smoothIndex()')
model_base <- hpiModel(model_type = 'rt',
hpi_df = rt_df,
estimator = 'base',
log_dep = TRUE,
trim_model=TRUE)
index_base <- modelToIndex(model_obj = model_base)
test_that('smoothing Function works with a variety of inputs',{
expect_is(index_smooth <- smoothIndex(index_obj = index_base,
order = 4),
'indexsmooth')
})
test_that('Errors are given when index is bad',{
expect_error(index_smooth <- smoothIndex(index_obj = 'abc',
order = 3))
expect_error(index_smooth <- smoothIndex(index_obj = index_base,
order = -3))
expect_error(index_smooth <- smoothIndex(index_obj = index_base,
order = 'x'))
expect_error(index_smooth <- smoothIndex(index_obj = index_base,
order = NA_integer_))
})
test_that('Returning in place works',{
expect_is(index_base <- smoothIndex(index = index_base,
order = 3,
in_place = TRUE),
'hpiindex')
expect_true('smooth' %in% names(index_base))
})
context('rtindex() wrapper')
test_that('Function works with proper inputs',{
full_1 <- rtIndex(trans_df = sales,
date = 'sale_date',
price = 'sale_price',
trans_id = 'sale_id',
prop_id = 'pinx',
estimator = 'base',
log_dep = TRUE,
periodicity = 'monthly')
expect_is(full_1, 'hpi')
expect_true(full_1$model$estimator == 'base')
full_2 <- rtIndex(trans_df = sales_df,
price = 'sale_price',
trans_id = 'sale_id',
prop_id = 'pinx',
estimator = 'robust',
log_dep = TRUE)
expect_is(full_2, 'hpi')
expect_true(full_2$model$estimator == 'robust')
full_3 <- rtIndex(trans_df = rt_df,
estimator = 'weighted',
log_dep = TRUE)
expect_is(full_3, 'hpi')
expect_true(full_3$model$estimator == 'weighted')
})
test_that('Additional arguments in rtIndex() work',{
mindate_index <- rtIndex(trans_df = sales,
date = 'sale_date',
price = 'sale_price',
trans_id = 'sale_id',
prop_id = 'pinx',
min_date = as.Date('2011-01-01'),
adj_type = 'clip')
expect_true(min(mindate_index$index$period) == 2011)
maxdate_index <- rtIndex(trans_df = sales,
date = 'sale_date',
price = 'sale_price',
trans_id = 'sale_id',
prop_id = 'pinx',
max_date = as.Date('2015-12-31'))
expect_true(max(maxdate_index$index$period) == 2016)
per_index <- rtIndex(trans_df = sales,
date = 'sale_date',
price = 'sale_price',
trans_id = 'sale_id',
prop_id = 'pinx',
periodicity = 'weekly')
expect_true(max(per_index$index$period) == 364)
seq_index <- rtIndex(trans_df = sales_df,
date = 'sale_date',
price = 'sale_price',
trans_id = 'sale_id',
prop_id = 'pinx',
seq_only = TRUE)
expect_true(nrow(seq_index$data) == 4823)
trim_index <- rtIndex(trans_df = rt_df,
trim_model=TRUE)
expect_true(is.null(trim_index$model$model_obj$qr))
ld_index <- rtIndex(trans_df = rt_df,
estimator = 'robust',
log_dep = FALSE)
expect_true(ld_index$model$log_dep == FALSE)
expect_true(ld_index$model$estimator == 'robust')
m2i_index <- rtIndex(trans_df = rt_df,
estimator = 'robust',
log_dep = FALSE,
max_period = 80)
expect_true(length(m2i_index$index$value) == 80)
})
test_that("Bad arguments generate Errors: Full Case",{
expect_error(rtIndex(trans_df = sales,
date = 'sale_price',
price = 'sale_price',
trans_id = 'sale_id',
prop_id = 'pinx',
estimator = 'base',
log_dep = TRUE,
periodicity = 'monthly'))
expect_error(rtIndex(trans_df = sales,
date = 'sale_date',
price = 'sale_price',
prop_id = 'pinx',
estimator = 'base',
log_dep = TRUE,
periodicity = 'monthly'))
expect_error(rtIndex(trans_df = sales,
date = 'sale_date',
price = 'sale_price',
trans_id = 'sale_id',
estimator = 'base',
log_dep = TRUE,
periodicity = 'monthly'))
expect_error(rtIndex(trans_df = sales,
date = 'sale_date',
trans_id = 'sale_id',
prop_id = 'pinx',
estimator = 'base',
log_dep = TRUE,
periodicity = 'monthly'))
expect_error(rtIndex(trans_df = sales,
date = 'sale_date',
price = 'sale_price',
trans_id = 'sale_id',
prop_id = 'pinx',
estimator = 'base',
log_dep = TRUE,
periodicity = 'xxx'))
expect_error(rtIndex(trans_df = sales[1, ],
date = 'sale_date',
price = 'sale_price',
trans_id = 'sale_id',
prop_id = 'pinx',
estimator = 'base',
log_dep = TRUE,
periodicity = 'monthly'), 'Converting transactions')
})
test_that("Bad arguments generate errort: trans_df Case",{
expect_error(rtIndex(trans_df = sales_df,
price = 'xx',
trans_id = 'sale_id',
prop_id = 'pinx',
estimator = 'base',
log_dep = TRUE))
expect_error(rtIndex(trans_df = sales_df,
price = 'sale_price',
trans_id = 'xx',
prop_id = 'pinx',
estimator = 'base',
log_dep = TRUE))
expect_error(rtIndex(trans_df = sales_df,
price = 'sale_price',
prop_id = 'pinx',
estimator = 'base',
log_dep = TRUE))
expect_error(rtIndex(trans_df = sales_df,
price = 'sale_price',
trans_id = 'sale_id',
prop_id = 'xx',
estimator = 'base',
log_dep = TRUE))
})
test_that("Bad arguments handling: rt_sales Case",{
expect_true(rtIndex(trans_df = rt_df,
estimator = 'basex',
log_dep = TRUE)$model$estimator == 'base')
expect_error(rtIndex(trans_df = rt_df,
estimator = 'robust',
log_dep = 'a'))
expect_error(rtIndex(trans_df = rt_df,
estimator = 'robust',
trim_model = 'a'))
expect_error(rtIndex(trans_df = rt_df,
estimator = 'robust',
max_period = 'a'))
})
test_that("Smoothing in_place for 'hpi' object works",{
full_1 <- rtIndex(trans_df = sales,
date = 'sale_date',
price = 'sale_price',
trans_id = 'sale_id',
prop_id = 'pinx',
estimator = 'base',
log_dep = TRUE,
periodicity = 'monthly',
smooth = TRUE)
expect_is(full_1$index$smooth, 'indexsmooth')
expect_is(index_smooth <- smoothIndex(index_obj = full_1,
order = 6),
'indexsmooth')
expect_is(full_1s <- smoothIndex(index = full_1,
order = 3,
in_place = TRUE),
'hpi')
expect_is(full_1s$index$smooth, 'ts')
expect_is(full_1s$index$smooth, 'indexsmooth')
})
|
draft <- function(file, cls = c("jdsart", "jds"))
{
template_path <- system.file("rmarkdown", "templates", "pdf_article",
package = "jds.rmd")
template_yaml <- file.path(template_path, "template.yaml")
if (file.exists(file))
stop("The file '", file, "' already exists.")
cls <- match.arg(cls, c("jdsart", "jds"))
sk_dir <- if (cls == "jdsart") {
"skeleton"
} else {
"skeleton-jds.cls"
}
skeleton_files <- list.files(file.path(template_path, sk_dir),
full.names = TRUE)
to <- dirname(file)
for (f in skeleton_files) {
if (file.exists(file.path(to, basename(f))))
stop("The file '", basename(f), "' already exists")
file.copy(from = f, to = to, overwrite = FALSE, recursive = TRUE)
}
file.rename(file.path(dirname(file), "skeleton.Rmd"), file)
invisible(file)
}
|
count_actions <- function(x, actions)
{
sapply(actions, function(a) sum(x==a))
}
aseq2atranseqs <- function(x) {
l <- length(x)
rbind(x[-l], x[-1])
}
action_seqs_summary <- function(action_seqs)
{
n_seq <- length(action_seqs)
seq_length <- sapply(action_seqs, length)
actions <- sort(unique(unlist(action_seqs)))
n_action <- length(actions)
action_freq_by_seq <- t(sapply(action_seqs, count_actions, actions=actions))
action_freq <- colSums(action_freq_by_seq)
action_seq_counts_by_seq <- array(as.numeric(action_freq_by_seq > 0),
dim=dim(action_freq_by_seq))
action_seq_freq <- colSums(action_seq_counts_by_seq)
names(action_seq_freq) <- actions
trans_counts <- matrix(0, n_action, n_action)
colnames(trans_counts) <- actions
rownames(trans_counts) <- actions
action_tran_seqs <- sapply(action_seqs, aseq2atranseqs)
all_pairs <- matrix(unlist(action_tran_seqs), nrow=2)
n_pair <- ncol(all_pairs)
for (i in 1:n_pair)
trans_counts[all_pairs[1,i], all_pairs[2,i]] <- trans_counts[all_pairs[1,i], all_pairs[2,i]] + 1
list(n_seq=n_seq, n_action = n_action,
actions=actions, seq_length=seq_length,
action_freq=action_freq, action_seqfreq = action_seq_freq,
trans_count = trans_counts)
}
tseq2interval <- function(x) {
c(0, diff(x))
}
time_seqs_summary <- function(time_seqs) {
total_time <- sapply(time_seqs, max)
mean_react_time <- sapply(time_seqs, max) / sapply(time_seqs, length)
list(total_time=total_time, mean_react_time=mean_react_time)
}
|
library(checkargs)
context("isPositiveIntegerScalarOrNull")
test_that("isPositiveIntegerScalarOrNull works for all arguments", {
expect_identical(isPositiveIntegerScalarOrNull(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isPositiveIntegerScalarOrNull(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isPositiveIntegerScalarOrNull(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isPositiveIntegerScalarOrNull(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isPositiveIntegerScalarOrNull(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isPositiveIntegerScalarOrNull(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isPositiveIntegerScalarOrNull(0, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isPositiveIntegerScalarOrNull(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isPositiveIntegerScalarOrNull(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isPositiveIntegerScalarOrNull(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull("", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull("X", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isPositiveIntegerScalarOrNull(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
})
|
system('R -e "pavian::runApp(port=5004)"', wait=FALSE)
DISPLAY = FALSE
setwd("~/projects/pavian/vignettes")
library(RSelenium)
remDr <- remoteDriver(remoteServerAddr = "localhost", port = 6656, browserName = "chrome")
remDr$open()
remDr$getStatus()
remDr$navigate("http://www.google.com")
remDr$navigate("http://127.0.0.1:5004")
remDr$setWindowSize(900,650)
remDr$screenshot(display = DISPLAY, useViewer = FALSE, file="main-page.png")
remDr$setWindowSize(900,1000)
btn_load_example <- remDr$findElement(using="css selector","
btn_load_example$clickElement()
remDr$screenshot(display = DISPLAY, useViewer = FALSE, file="load-data-set.png")
system("convert load-data-set.png -crop 180x230+0+180 side-bar.png")
menu_results <- remDr$findElement(using="css selector","
menu_results$clickElement()
remDr$setWindowSize(1000,650)
remDr$screenshot(display = DISPLAY, useViewer = FALSE, file="results-overview.png")
menu_comp <- remDr$findElement(using="css selector","
menu_comp$clickElement()
menu_comp1 <- remDr$findElement(using="css selector",".treeview-menu > li:nth-child(1) > a:nth-child(1)")
menu_comp1$clickElement()
remDr$setWindowSize(1200,1000)
remDr$screenshot(display = DISPLAY, file="menu-comp.png")
heatmap_tab <- remDr$findElement(using="css selector","
heatmap_tab$clickElement()
remDr$screenshot(display = DISPLAY, file="comp-heatmap.png")
system("convert comp-heatmap.png -crop 520x280+260+370 comp-heatmap1.png")
menu_sample <- remDr$findElement(using="css selector","
menu_sample$clickElement()
remDr$setWindowSize(1200,1000)
remDr$screenshot(display = DISPLAY, file="flow-pt1.png")
remDr$screenshot(display = DISPLAY, file="flow-pt5.png")
remDr$findElement(using="css selector","
remDr$findElement(using="css selector","
remDr$screenshot(display = DISPLAY, file="alignment_viewer-pt5.png")
remDr$findElement(using="css selector","div.tabbable:nth-child(2) > ul:nth-child(1) > li:nth-child(2) > a:nth-child(1)")$clickElement()
remDr$setWindowSize(1200,800)
remDr$screenshot(display = DISPLAY, file="download-genome-jcv.png")
|
expected <- eval(parse(text="NA_real_"));
test(id=0, code={
argv <- eval(parse(text="list(c(49, 61, NA, NA))"));
do.call(`sum`, argv);
}, o=expected);
|
mcsamp.default <- function (object, n.chains=3, n.iter=1000, n.burnin=floor(n.iter/2),
n.thin=max(1, floor(n.chains * (n.iter - n.burnin)/1000)),
saveb=TRUE, deviance=TRUE, make.bugs.object=TRUE)
{
cat("mcsamp() used to be a wrapper for mcmcsamp() in lme4.\nCurrently, mcmcsamp() is no longer available in lme4.\nSo in the meantime, we suggest that users use sim() to get\nsimulated estimates.\n")
}
setMethod("mcsamp", signature(object = "merMod"),
function (object, ...)
{
mcsamp.default(object, deviance=TRUE, ...)
}
)
|
test_that("IdfViewer Implemention", {
skip_on_cran()
idf <- read_idf(file.path(eplus_config(8.8)$dir, "ExampleFiles/4ZoneWithShading_Simple_1.idf"))
expect_is(geoms <- extract_geom(idf), "list")
expect_is(geoms <- align_coord_system(geoms, "absolute", "absolute", "absolute"), "list")
expect_is(geoms$vertices2 <- triangulate_geoms(geoms), "data.table")
rgl_init <- function (clear = TRUE) {
new <- FALSE
if (clear) {
if (rgl::rgl.cur() == 0) new <- TRUE else rgl::rgl.clear()
}
if (!new) {
dev <- rgl::rgl.cur()
} else {
rgl::rgl.open()
dev <- rgl::rgl.cur()
rgl::rgl.viewpoint(0, -60, 60)
cur <- rgl::par3d("mouseMode")
cur[["left"]] <- "trackball"
cur[["wheel"]] <- "push"
cur[["middle"]] <- "fov"
rgl::par3d(dev = dev, mouseMode = cur)
pan3d(2L)
}
rgl::rgl.bg(color = "white")
rgl::rgl.set(dev)
dev
}
dev <- rgl_init()
expect_is(id_axis <- rgl_view_axis(dev, geoms), "integer")
expect_is(id_ground <- rgl_view_ground(dev, geoms, alpha = 1.0), "integer")
expect_is(id_wireframe <- rgl_view_wireframe(dev, geoms), "integer")
expect_is(id_surface <- rgl_view_surface(dev, geoms, wireframe = FALSE), "integer")
expect_length(id_dayl_pnts <- rgl_view_point(dev, geoms), 0)
expect_is(rgl_pop(id = id_ground), "integer")
expect_is(rgl_pop(id = unlist(id_surface)), "integer")
expect_is(id_surface <- rgl_view_surface(dev, geoms, "boundary"), "integer")
expect_is(rgl_pop(id = unlist(id_surface)), "integer")
expect_is(id_surface <- rgl_view_surface(dev, geoms, "construction"), "integer")
expect_is(id_surface <- rgl_view_surface(dev, geoms, "zone"), "integer")
expect_is(rgl_pop(id = unlist(id_surface)), "integer")
expect_is(id_surface <- rgl_view_surface(dev, geoms, "normal"), "integer")
idf <- read_idf(file.path(eplus_config(8.8)$dir, "ExampleFiles/HospitalLowEnergy.idf"))
expect_is(geoms <- extract_geom(idf), "list")
expect_is(geoms <- align_coord_system(geoms, "relative", "relative", "relative"), "list")
expect_equal(unlist(geoms$rules[3:5], FALSE, FALSE), rep("relative", 3L))
expect_is(geoms <- align_coord_system(geoms, "absolute", "absolute", "absolute"), "list")
expect_equal(unlist(geoms$rules[3:5], FALSE, FALSE), rep("absolute", 3L))
expect_is(geoms$vertices2 <- triangulate_geoms(geoms), "data.table")
expect_is(dev <- rgl_init(), "integer")
expect_is(id_axis <- rgl_view_axis(dev, geoms), "integer")
expect_is(id_ground <- rgl_view_ground(dev, geoms, alpha = 1.0), "integer")
expect_is(id_surface <- rgl_view_surface(dev, geoms, "surface_type", wireframe = FALSE), "integer")
expect_is(id_wireframe <- rgl_view_wireframe(dev, geoms), "integer")
expect_is(id_dayl_pnts <- rgl_view_point(dev, geoms), "integer")
expect_is(rgl_pop(id = id_ground), "integer")
expect_is(rgl_pop(id = unlist(id_surface)), "integer")
expect_is(id_surface <- rgl_view_surface(dev, geoms, "boundary"), "integer")
expect_is(rgl_pop(id = unlist(id_surface)), "integer")
expect_is(id_surface <- rgl_view_surface(dev, geoms, "construction"), "integer")
expect_is(rgl_pop(id = unlist(id_surface)), "integer")
expect_is(id_surface <- rgl_view_surface(dev, geoms, "zone"), "integer")
expect_is(rgl_pop(id = unlist(id_surface)), "integer")
expect_is(id_surface <- rgl_view_surface(dev, geoms, "normal"), "integer")
rgl::rgl.close()
})
|
read_docx <- function (file, skip = 0) {
tmp <- tempfile()
if (!dir.create(tmp)) stop("Temporary directory could not be established.")
utils::unzip(file, exdir = tmp)
xmlfile <- file.path(tmp, "word", "document.xml")
doc <- XML::xmlTreeParse(xmlfile, useInternalNodes = TRUE)
unlink(tmp, recursive = TRUE)
nodeSet <- XML::getNodeSet(doc, "//w:p")
pvalues <- sapply(nodeSet, XML::xmlValue)
pvalues <- pvalues[pvalues != ""]
if (skip > 0) pvalues <- pvalues[-seq(skip)]
pvalues
}
|
numerical.derivative <- function (x, func, lb=-Inf, ub=Inf, xmin=1, delta=1.e-7) {
h <- pmax(x*delta,delta)
df <- (func(x+h)-func(x-h))/(2*h)
}
arou.new <- function (pdf, dpdf=NULL, lb, ub, islog=FALSE, ...) {
if (missing(pdf) || !is.function(pdf)) {
if (!missing(pdf) && is(pdf,"unuran.cont"))
stop ("argument 'pdf' is UNU.RAN distribution object. Did you mean 'aroud.new'?")
else
stop ("argument 'pdf' missing or invalid")
}
if (missing(lb) || missing(ub))
stop ("domain ('lb','ub') missing")
f <- function(x) pdf(x, ...)
if (is.null(dpdf)) {
df <- function(x) {
numerical.derivative(x,f)
}
}
else {
if (! is.function(dpdf) )
stop ("argument 'dpdf' invalid")
else df <- function(x) dpdf(x,...)
}
dist <- new("unuran.cont", pdf=f, dpdf=df, lb=lb, ub=ub, islog=islog)
unuran.new(dist, "arou")
}
aroud.new <- function (distr) {
if ( missing(distr) || !(isS4(distr) && is(distr,"unuran.cont")) )
stop ("argument 'distr' missing or invalid")
unuran.new(distr, "arou")
}
ars.new <- function (logpdf, dlogpdf=NULL, lb, ub, ...) {
if (missing(logpdf) || !is.function(logpdf)) {
if (!missing(logpdf) && is(logpdf,"unuran.cont"))
stop ("argument 'logpdf' is UNU.RAN distribution object. Did you mean 'arsd.new'?")
else
stop ("argument 'logpdf' missing or invalid")
}
if (missing(lb) || missing(ub))
stop ("domain ('lb','ub') missing")
f <- function(x) logpdf(x, ...)
if (is.null(dlogpdf)) {
df <- function(x) {
numerical.derivative(x,f)
}
}
else {
if (! is.function(dlogpdf) )
stop ("argument 'dlogpdf' invalid")
else df <- function(x) dlogpdf(x,...)
}
dist <- new("unuran.cont", pdf=f, dpdf=df, lb=lb, ub=ub, islog=TRUE)
unuran.new(dist, "ars")
}
arsd.new <- function (distr) {
if ( missing(distr) || !(isS4(distr) && is(distr,"unuran.cont")) )
stop ("argument 'distr' missing or invalid")
unuran.new(distr, "ars")
}
itdr.new <- function (pdf, dpdf, lb, ub, pole, islog=FALSE, ...) {
if (missing(pdf) || !is.function(pdf)) {
if (!missing(pdf) && is(pdf,"unuran.cont"))
stop ("argument 'pdf' is UNU.RAN distribution object. Did you mean 'itdrd.new'?")
else
stop ("argument 'pdf' missing or invalid")
}
if (missing(dpdf) || !is.function(dpdf))
stop ("argument 'dpdf' missing or invalid")
if (missing(pole) || !is.numeric(pole))
stop ("argument 'pole' missing or invalid")
if (missing(lb) || missing(ub))
stop ("domain ('lb','ub') missing")
f <- function(x) pdf(x, ...)
df <- function(x) dpdf(x, ...)
dist <- new("unuran.cont", pdf=f, dpdf=df, lb=lb, ub=ub, islog=islog, mode=pole)
unuran.new(dist, "itdr")
}
itdrd.new <- function (distr) {
if ( missing(distr) || !(isS4(distr) && is(distr,"unuran.cont")) )
stop ("argument 'distr' missing or invalid")
unuran.new(distr, "itdr")
}
pinv.new <- function (pdf, cdf, lb, ub, islog=FALSE, center=0,
uresolution=1.e-10, smooth=FALSE, ...) {
if (missing(pdf) && missing(cdf))
stop ("argument 'pdf' or 'cdf' required")
if (!missing(pdf) && is(pdf,"unuran.cont"))
stop ("argument 'pdf' is UNU.RAN distribution object. Did you mean 'pinvd.new'?")
if (!is.numeric(center))
stop ("argument 'center' invalid")
if (!is.numeric(uresolution))
stop ("argument 'uresolution' invalid")
if (missing(lb) || missing(ub))
stop ("domain ('lb','ub') missing")
usefunc <- if (missing(pdf)) "usecdf" else "usepdf"
if (!missing(pdf)) {
if (!is.function(pdf))
stop ("argument 'pdf' must be of class 'function'")
PDF <- function(x) pdf(x, ...)
}
else {
PDF <- NULL;
}
if (!missing(cdf)) {
if (!is.function(cdf))
stop ("argument 'cdf' must be of class 'function'")
CDF <- function(x) cdf(x, ...)
}
else {
CDF <- NULL
}
dist <- new("unuran.cont", pdf=PDF, cdf=CDF, lb=lb, ub=ub, center=center, islog=islog)
method <- paste("pinv;",usefunc,
";u_resolution=",uresolution,
";smoothness=",as.integer(smooth),
";keepcdf=on",
sep="")
unuran.new(dist, method)
}
pinvd.new <- function (distr, uresolution=1.e-10, smooth=FALSE) {
if ( missing(distr) || !(isS4(distr) && is(distr,"unuran.cont")) )
stop ("argument 'distr' missing or invalid")
method <- paste("pinv",
";u_resolution=",uresolution,
";smoothness=",as.integer(smooth),
";keepcdf=on",
sep="")
unuran.new(distr, method)
}
srou.new <- function (pdf, lb, ub, mode, area, islog=FALSE, r=1, ...) {
if (missing(pdf) || !is.function(pdf)) {
if (!missing(pdf) && is(pdf,"unuran.cont"))
stop ("argument 'pdf' is UNU.RAN distribution object. Did you mean 'sroud.new'?")
else
stop ("argument 'pdf' missing or invalid")
}
if (missing(mode) || !is.numeric(mode))
stop ("argument 'mode' missing or invalid")
if (missing(area) || !is.numeric(area))
stop ("argument 'area' missing or invalid")
if (missing(lb) || missing(ub))
stop ("domain ('lb','ub') missing")
f <- function(x) pdf(x, ...)
dist <- new("unuran.cont", pdf=f, lb=lb, ub=ub, islog=islog, mode=mode, area=area)
method <- paste("srou; r=",r, sep="")
unuran.new(dist, method)
}
sroud.new <- function (distr, r=1) {
if ( missing(distr) || !(isS4(distr) && is(distr,"unuran.cont")) )
stop ("argument 'distr' missing or invalid")
method <- paste("srou; r=",r, sep="")
unuran.new(distr, method)
}
tabl.new <- function (pdf, lb, ub, mode, islog=FALSE, ...) {
if (missing(pdf) || !is.function(pdf)) {
if (!missing(pdf) && is(pdf,"unuran.cont"))
stop ("argument 'pdf' is UNU.RAN distribution object. Did you mean 'tabld.new'?")
else
stop ("argument 'pdf' missing or invalid")
}
if (missing(mode) || !is.numeric(mode))
stop ("argument 'mode' missing or invalid")
if (missing(lb) || missing(ub))
stop ("domain ('lb','ub') missing")
f <- function(x) pdf(x, ...)
dist <- new("unuran.cont", pdf=f, lb=lb, ub=ub, islog=islog, mode=mode)
unuran.new(dist, "tabl")
}
tabld.new <- function (distr) {
if ( missing(distr) || !(isS4(distr) && is(distr,"unuran.cont")) )
stop ("argument 'distr' missing or invalid")
unuran.new(distr, "tabl")
}
tdr.new <- function (pdf, dpdf=NULL, lb, ub, islog=FALSE, ...) {
if (missing(pdf) || !is.function(pdf)) {
if (!missing(pdf) && is(pdf,"unuran.cont"))
stop ("argument 'pdf' is UNU.RAN distribution object. Did you mean 'tdrd.new'?")
else
stop ("argument 'pdf' missing or invalid")
}
if (missing(lb) || missing(ub))
stop ("domain ('lb','ub') missing")
f <- function(x) pdf(x, ...)
if (is.null(dpdf)) {
df <- function(x) {
numerical.derivative(x,f)
}
}
else {
if (! is.function(dpdf) )
stop ("argument 'dpdf' invalid")
else df <- function(x) dpdf(x,...)
}
dist <- new("unuran.cont", pdf=f, dpdf=df, lb=lb, ub=ub, islog=islog)
unuran.new(dist, "tdr")
}
tdrd.new <- function (distr) {
if ( missing(distr) || !(isS4(distr) && is(distr,"unuran.cont")) )
stop ("argument 'distr' missing or invalid")
unuran.new(distr, "tdr")
}
dari.new <- function (pmf, lb, ub, mode=NA, sum=1, ...) {
if (missing(pmf) || !is.function(pmf)) {
if (!missing(pmf) && is(pmf,"unuran.discr"))
stop ("argument 'pmf' is UNU.RAN distribution object. Did you mean 'darid.new'?")
else
stop ("argument 'pmf' missing or invalid")
}
if (missing(lb) || missing(ub))
stop ("domain ('lb','ub') missing")
f <- function(x) pmf(x, ...)
distr <- new("unuran.discr",pmf=f,lb=lb,ub=ub,mode=mode,sum=sum)
unuran.new(distr, "dari")
}
darid.new <- function (distr) {
if ( missing(distr) || !(isS4(distr) && is(distr,"unuran.discr")) )
stop ("argument 'distr' missing or invalid")
unuran.new(distr, "dari")
}
dau.new <- function (pv, from=1) {
if (missing(pv) || !is.numeric(pv)) {
if (!missing(pv) && is(pv,"unuran.discr"))
stop ("argument 'pv' is UNU.RAN distribution object. Did you mean 'daud.new'?")
else
stop ("argument 'pv' missing or invalid")
}
distr <- new("unuran.discr",pv=pv,lb=from,ub=Inf)
unuran.new(distr, "dau")
}
daud.new <- function (distr) {
if ( missing(distr) || !(isS4(distr) && is(distr,"unuran.discr")) )
stop ("argument 'distr' missing or invalid")
unuran.new(distr, "dau")
}
dgt.new <- function (pv, from=1) {
if (missing(pv) || !is.numeric(pv)) {
if (!missing(pv) && is(pv,"unuran.discr"))
stop ("argument 'pv' is UNU.RAN distribution object. Did you mean 'dgtd.new'?")
else
stop ("argument 'pv' missing or invalid")
}
distr <- new("unuran.discr",pv=pv,lb=from,ub=Inf)
unuran.new(distr, "dgt")
}
dgtd.new <- function (distr) {
if ( missing(distr) || !(isS4(distr) && is(distr,"unuran.discr")) )
stop ("argument 'distr' missing or invalid")
unuran.new(distr, "dgt")
}
hitro.new <- function (dim=1, pdf, ll=NULL, ur=NULL, mode=NULL, center=NULL, thinning=1, burnin=0, ...) {
if (missing(pdf) || !is.function(pdf))
stop ("argument 'pdf' missing or invalid")
f <- function(x) pdf(x, ...)
dist <- new("unuran.cmv", dim=dim, pdf=f, mode=mode, center=center, ll=ll, ur=ur)
method <- paste("hitro;thinning=",thinning,";burnin=",burnin, sep="")
unuran.new(dist, method)
}
vnrou.new <- function (dim=1, pdf, ll=NULL, ur=NULL, mode=NULL, center=NULL, ...) {
if (missing(pdf) || !is.function(pdf))
stop ("argument 'pdf' missing or invalid")
f <- function(x) pdf(x, ...)
dist <- new("unuran.cmv", dim=dim, pdf=f, mode=mode, center, ll=ll, ur=ur)
unuran.new(dist, "VNROU")
}
|
fPCAcapacity <- function(sftData, dimensions, acc.cutoff=.75, OR=NULL, stopping.rule=c("OR", "AND", "STST"), ratio=TRUE, register=c("median","mean","none"), plotPCs=FALSE, ...) {
subjects <- sort(unique(sftData$Subject))
subjects <- factor(subjects)
nsubjects <- length(subjects)
conditions <- sort(unique(sftData$Condition))
conditions <- factor(conditions)
nconditions <- length(conditions)
subj.out <- character()
cond.out <- character()
channels <- grep("Channel", names(sftData), value=T)
nchannels <- length(channels)
if(nchannels < 2) {
stop("Not enough channels for capacity analysis.")
}
if (!is.null(OR)) {
if (OR) {
capacity <- capacity.or
} else {
capacity <- capacity.and
}
} else {
rule <- match.arg(stopping.rule, c("OR","AND","STST"))
if(rule == "OR") {
capacity <- capacity.or
} else if (rule == "AND") {
capacity <- capacity.and
} else if (rule == "STST"){
capacity <- capacity.stst
} else {
stop("Please choose a valid stopping rule for fPCAcapacity.")
}
}
if (rule!="STST") {
for ( ch in channels ) {
if(is.factor(sftData[,ch])) {
sftData[,ch] <- as.numeric(levels(sftData[,ch]))[sftData[,ch]]
}
sftData <- subset(sftData, sftData[,ch] >=0)
}
}
if(rule=="STST") { nchannels <- 2 }
tvec <- seq(quantile(sftData$RT,.001), quantile(sftData$RT,.999),
length.out=1000)
midpoint <- floor(length(tvec)/2)
capAllMat <- numeric()
varAllMat <- numeric()
subjVec <- c()
condVec <- c()
allRT <- numeric()
registervals <- numeric()
good <- logical()
if (rule=="STST") {
RTlist <- vector("list", nchannels)
CRlist <- vector("list", nchannels)
} else {
RTlist <- vector("list", nchannels+1)
CRlist <- vector("list", nchannels+1)
}
ltyvec <- numeric()
colvec <- numeric()
condLegend <- levels(conditions)
for ( cn in 1:nconditions ) {
if (is.factor(conditions)) {cond <- levels(conditions)[cn]} else {cond <- conditions[cn] }
condsubjects <- factor(with(sftData, sort(unique(Subject[Condition==cond]))))
ncondsubjects <- length(condsubjects)
if (ncondsubjects ==0 ) { next; }
for ( sn in 1:ncondsubjects ) {
if (is.factor(condsubjects)) {subj <- levels(condsubjects)[sn]} else {subj <- condsubjects[sn] }
subjVec <- c(subjVec, subj)
condVec <- c(condVec, cond)
ds <- sftData$Subject==subj & sftData$Condition==cond
if (rule == "STST") {
usechannel <- ds & (apply(sftData[,channels]>0, 1, sum)==1) & (apply(sftData[,channels]<0, 1, sum)>0)
RTlist[[1]] <- sftData$RT[usechannel & (sftData$RT < quantile(sftData$RT[usechannel], .975)) ]
CRlist[[1]] <- sftData$Correct[usechannel & (sftData$RT < quantile(sftData$RT[usechannel], .975))]
usechannel <- ds & apply(sftData[,channels]>=0, 1, all) & (apply(sftData[,channels]!=0, 1, sum)==1)
RTlist[[2]] <- sftData$RT[usechannel & (sftData$RT < quantile(sftData$RT[usechannel], .975)) ]
CRlist[[2]] <- sftData$Correct[usechannel & (sftData$RT < quantile(sftData$RT[usechannel], .975))]
} else {
usechannel <- ds & apply(sftData[,channels]>0, 1, all)
RTlist[[1]] <- sftData$RT[usechannel & (sftData$RT < quantile(sftData$RT[usechannel], .975)) ]
CRlist[[1]] <- sftData$Correct[usechannel & (sftData$RT < quantile(sftData$RT[usechannel], .975))]
for ( ch in 1:nchannels ) {
usechannel <- ds & sftData[,channels[ch]]>0 &
apply(as.matrix(sftData[,channels[-ch]]==0), 1, all)
RTlist[[ch+1]] <- sftData$RT[usechannel & sftData$RT < quantile(sftData$RT[usechannel], .975)]
CRlist[[ch+1]] <- sftData$Correct[usechannel & sftData$RT < quantile(sftData$RT[usechannel], .975)]
}
}
if(any(lapply(CRlist, mean)<acc.cutoff) | any(lapply(RTlist, length) < 10) ) {
good <- c(good, FALSE)
capAllMat <- rbind(capAllMat, rep(NA, length(tvec)))
varAllMat <- rbind(varAllMat, rep(NA, length(tvec)))
next
} else{
good <- c(good, TRUE)
}
if (register == "median") {
registervals <- c(registervals, mean(median(RTlist[[1]], median(c(RTlist[2:nconditions],recursive=TRUE)))) )
shiftn <- midpoint - max( which(tvec < tail(registervals,1)))
} else if (register == "mean") {
registervals <- c(registervals, mean(c(RTlist,recursive=TRUE)) )
shiftn <- midpoint - max( which(tvec < tail(registervals,1)))
} else {
shiftn <- 0
}
capout <- capacity(RTlist, CRlist, ratio=ratio)
subj.out <- c(subj.out, subj)
cond.out <- c(cond.out, cond)
ltyvec <- c(ltyvec, sn)
colvec <- c(colvec, cn)
if (ratio) {
tmin <- max( c(lapply(RTlist, quantile, probs=c(.01)), recursive=TRUE), na.rm=TRUE)
tmax <- min( c(lapply(RTlist, quantile, probs=c(.99)), recursive=TRUE), na.rm=TRUE)
ct <- capout$Ct(tvec)
ct[tvec < tmin] <- NA
ct[tvec > tmax] <- NA
if (register != "none") {
capAllMat <- rbind(capAllMat, shift(ct, shiftn))
} else {
capAllMat <- rbind(capAllMat, ct)
}
} else {
if (register != "none") {
varAllMat <- rbind(varAllMat, shift(capout$Var(tvec), shiftn))
capAllMat <- rbind(capAllMat, shift(capout$Ct(tvec), shiftn))
} else {
varAllMat <- rbind(varAllMat, capout$Var(tvec))
capAllMat <- rbind(capAllMat, capout$Ct(tvec))
}
}
}
}
if(register != "none") {
tvec <- tvec - midpoint
}
tmin <- min(tvec[!apply(is.na(capAllMat[good,]), 2, all)])
tmax <- max(tvec[!apply(is.na(capAllMat[good,]), 2, all)])
tgood <- tvec[tvec >= tmin & tvec <= tmax]
capGoodMat <- capAllMat[good,tvec >= tmin & tvec <= tmax]
if (!ratio) {
varGoodMat <- varAllMat[good,tvec >= tmin & tvec <= tmax]
}
k <- dim(capGoodMat)[1]
if(plotPCs) {
dev.new()
par(mar=c(3.1, 3.1, 2.1, 1.1), mgp=c(1.75, .25,0))
matplot(tgood, t(capGoodMat), type='l', lty=ltyvec, col=colvec,
xlim=c(tmin,1300),
main="Capacity", ylab="C(t)", xlab="Time (Adjusted)")
if(nconditions <= 5) {
legend("topright", legend=condLegend, lty=1, col=1:5, cex=.9)
}
}
capGoodmn <- apply(capGoodMat, 2, mean, na.rm=TRUE)
for (i in 1:k) {
capGoodMat[i, is.na(capGoodMat[i,])] <- capGoodmn[is.na(capGoodMat[i,])]
}
if(!ratio) {
varGoodMat[i, is.na(capGoodMat[i,])] <- 0
}
capGoodmn <- apply(capGoodMat, 2, mean)
capGoodMat <- capGoodMat - matrix(capGoodmn, k, length(tgood), byrow=T)
if(plotPCs) {
dev.new()
par(mfrow=c(1,2), mar=c(3.1, 3.1, 2.1, 1.1), mgp=c(1.75, .25,0))
plot(c(tmin-1000, tmax+1000), c(0,0), type='l',
xlim=c(tmin, tmax),
main="Mean C(t)", ylab="C(t)", xlab="Time (Adjusted)")
lines(tgood, capGoodmn, lwd=2)
if (ratio) { abline(0,0, lty=1, col=grey(.4)) }
matplot(tgood, t(capGoodMat), type='l', lty=ltyvec, col=colvec,
xlim=c(tmin,tmax),
main="C(t)-Mean C(t)", ylab="C(t)", xlab="Time (Adjusted)")
if(nconditions <= 5) {
legend("topright", legend=condLegend, lty=1, col=1:5, cex=.9)
}
}
wtvec <- rep(1, length(tgood))
wtGoodMat <- t(capGoodMat)
basis <- create.bspline.basis(rangeval=c(min(tgood),max(tgood)),
nbasis=sum(good)-1, norder=4)
capGoodfd <- smooth.basis(tgood, wtGoodMat, basis)
pcastrGood <- pca.fd(capGoodfd$fd,dimensions)
if ( dimensions > 1) {
pcastrGoodVarmx <- varmx.pca.fd(pcastrGood)
} else {
pcastrGoodVarmx <- pcastrGood
}
if(plotPCs) {
values <- pcastrGood$values
dev.new()
par(mar=c(3.1, 3.1, 2.1, 1.1), mgp=c(1.75, .25,0))
plot(1:5, values[1:5]/sum(values),
xlim=c(1, 5), ylim=c(0,1), pch=19,
main="Scree Plot", xlab="Eigenfunction", ylab="Variance Accounted For")
lines(1:5, values[1:5]/sum(values))
}
harmmat <- eval.fd(tgood, pcastrGood$harmonics)
harmmat <- harmmat / (wtvec %*% matrix(1, 1, dimensions))
facmult <- apply(abs(pcastrGood$scores), 2, mean)
harmmatV <- eval.fd(tgood, pcastrGoodVarmx$harmonics)
harmmatV <- harmmatV / (wtvec %*% matrix(1, 1, dimensions))
facmultV <- apply(abs(pcastrGoodVarmx$scores), 2, mean)
scoreout <- data.frame(subjVec,condVec)
for ( i in 1:dimensions) {
scoreout[[i+2]] <- rep(NA, length(scoreout[[1]]))
scoreout[[i+2]][good] <- pcastrGood$scores[,i]
}
names(scoreout) <- c("Subject","Condition",paste("D",1:dimensions,sep=""))
scoreoutV <- data.frame(subjVec,condVec)
for ( i in 1:dimensions) {
scoreoutV[[i+2]] <- rep(NA, length(scoreoutV[[1]]))
scoreoutV[[i+2]][good] <- pcastrGoodVarmx$scores[,i]
}
names(scoreoutV) <- c("Subject","Condition",paste("D",1:dimensions,sep=""))
pflist <- vector("list", length=dimensions)
for (ifac in 1:dimensions) {
pflist[[ifac]] <- approxfun(tgood,harmmatV[,ifac])
}
if(plotPCs) {
if (ratio) { ylim<-c(0,mean(capGoodmn)+max(facmult)) } else { ylim=c(-1, mean(capGoodmn)+max(facmult)) }
dev.new()
par(mar=c(3.1, 3.1, 2.1, 1.1), mgp=c(1.75, .25,0), mfrow=c(dimensions,3))
for ( ifac in 1:dimensions) {
mainstr <- paste("PC", ifac, "-", floor(100*pcastrGood$varprop[ifac]), "%")
Wveci <- capGoodmn + facmult[ifac]* harmmat[,ifac]
plot(tgood, Wveci, type='l', lty=2, main="", xlab="Time (Adjusted)", ylab="",
ylim=ylim, xlim=c(tmin, tmax))
lines(tgood, capGoodmn)
abline(0,0, col=grey(.4))
mtext(mainstr, side=2, line=1)
if(ifac==1) {
mtext("Component Function", side=3, line=.5)
legend("topright", c("Component", "Mean"), lty=c(2,1))
}
plot(tgood, Wveci - capGoodmn, type='l', main="", xlab="Time (Adjusted)", ylab="",
ylim=ylim, xlim=c(tmin, tmax))
abline(0,0, col=grey(.4))
if(ifac==1) {mtext("Component - Mean", side=3, line=.5)}
plot(scoreout$Subject, scoreout[[ifac+2]], type="n",
xaxt='n', ylab="", xlab="Subject")
axis(1,at=1:10, labels=rep("",10), las=0, cex=.1, tck=-.02)
mtext(side=1, 1:10, at=1:10, line=.05, cex=.7)
text(scoreout$Subject, scoreout[[ifac+2]], labels=scoreout$Condition,
col=colvec)
if(ifac==1) {mtext("Score", side=3, line=.5)}
}
dev.new()
par(mar=c(3.1, 3.1, 2.1, 1.1), mgp=c(1.75, .25,0), mfrow=c(dimensions,3))
for ( ifac in 1:dimensions) {
mainstr <- paste("PC", ifac, "-", floor(100*pcastrGoodVarmx$varprop[ifac]), "%")
Wveci <- capGoodmn + facmultV[ifac]* harmmatV[,ifac]
plot(tgood, Wveci, type='l', lty=2, main="", xlab="Time (Adjusted)", ylab="",
ylim=ylim, xlim=c(tmin, tmax))
lines(tgood, capGoodmn)
abline(0,0, col=grey(.4))
mtext(mainstr, side=2, line=1)
if(ifac==1) {
mtext("Component Function", side=3, line=.5)
legend("topright", c("Component", "Mean"), lty=c(2,1))
}
plot(tgood, Wveci - capGoodmn, type='l', main="", xlab="Time (Adjusted)", ylab="",
ylim=ylim, xlim=c(tmin, tmax))
abline(0,0, col=grey(.4))
if(ifac==1) {mtext("Component - Mean", side=3, line=.5)}
plot(scoreout$Subject, scoreoutV[[ifac+2]], type="n",
xaxt='n', ylab="", xlab="Subject")
axis(1,at=1:10, labels=rep("",10), las=0, cex=.1, tck=-.02)
mtext(side=1, 1:10, at=1:10, line=.05, cex=.7)
text(scoreout$Subject, scoreoutV[[ifac+2]], labels=scoreout$Condition,
col=colvec)
if(ifac==1) {mtext("Score", side=3, line=.5)}
}
}
return(list(Scores=scoreoutV, MeanCT=approxfun(tgood,capGoodmn), PF=pflist, medianRT=registervals))
}
shift <- function(x, n, wrap=FALSE) {
if (abs(n) > length(x) ) {
if (!wrap ) { return( rep(NA, length(x))) }
n <- n %% length(x)
}
if ( n >= 0 ) {
s <- length(x)-n +1
if (wrap) {
xout <- c( x[s:length(x)], x[1:(s-1)])
} else {
xout <- c(rep(NA,n), x[1:(s-1)])
}
} else {
s <- abs(n)+1
if (wrap) {
xout <- c( x[s:length(x)], x[1:(s-1)])
} else {
xout <- c( x[s:length(x)], rep(NA, abs(n)))
}
}
return(xout)
}
|
numiMultiX = function(nVar, dMax,
Istep=1000, onestep=1/125,
KDf,
extF = extF,
v0=NULL,
method="rk4") {
pMax <- d2pMax(nVar, dMax)
if (dim(KDf)[2] != nVar) {
stop("nVar (=",nVar,") does not match with the model dimension (=",dim(KDf)[2],")")
}
if (length(v0) != nVar) {
stop("v0 length (=",length(v0),") does not match with the model dimension (=",dim(KDf)[2],")")
}
extFmemo <- extF
if (dim(extF)[1] != (Istep - 1) * 2 + 1) {
rsplextF <- matrix(0, ncol = dim(extF)[2], nrow = (Istep - 1) * 2 + 1)
for (ivar in 1:(dim(extF)[2])) {
tmp <- spline(x = extF[,1], y = extF[,ivar], xout = (0:(Istep*2-2))*onestep/2)
rsplextF[,ivar] <- tmp$y
}
extF <- rsplextF
}
if (dim(extF)[1] != (Istep - 1) * 2 + 1 ) {
stop("The forcing time length (",dim(extF)[1]," lignes) does not match with the required double time sampling (=",(Istep - 1) * 2 + 1,")")
}
if (method!="rk4") {
warning("Only 4th order Runge-Kutta method 'rk4' is supported by the numiMultiX function")
}
tvec <- (0:(Istep-1)) * onestep
reconstr <- reconstr2 <- ode(v0, tvec, derivODEwMultiX,
KDf, extF = extF, method = 'rk4')
iToUpdate <- which(is.na(colSums(KDf)))
reconstr[, iToUpdate + 1] <- extF[(1:Istep) * 2 - 1,(1:length(iToUpdate)+1)]
outNumiMultiX <- list()
outNumiMultiX$input$extF <- extFmemo
outNumiMultiX$input$v0 <- v0
outNumiMultiX$extF <- extF
outNumiMultiX$KDf <- KDf
outNumiMultiX$reconstr <- reconstr
return(outNumiMultiX)
}
|
NULL
as.rvsummary <- function (x, ...) {
UseMethod("as.rvsummary")
}
is.rvsummary <- function (x) {
inherits(x, "rvsummary")
}
print.rvsummary <- function (x, digits=3, ...)
{
s <- summary(x)
for (i in which(sapply(s, is.numeric))) {
s[[i]] <- round(s[[i]], digits=digits)
}
print(s)
}
as.rvsummary.default <- function (x, ...)
{
as.rvsummary(as.rv(x), ...)
}
as.rvsummary.rv <- function (x, quantiles=(0:200/200), ...)
{
y <- if (is.logical(x)) {
as.rvsummary.rvlogical(x, ...)
} else if (is.integer(x)) {
as.rvsummary.rvinteger(x, quantiles=quantiles, ...)
} else {
as.rvsummary.rvnumeric(x, quantiles=quantiles, ...)
}
return(y)
}
as.rvsummary.rvsummary <- function (x, ...)
{
return(x)
}
as.rvsummary.rvnumeric <- function (x, quantiles=(0:200/200), ...)
{
ms <- .rvmeansd(x, names.=c("mean", "sd", "NAS", "n.sims"))
for (name in names(ms)) {
rvattr(x, name) <- ms[[name]]
}
for (i in seq_along(x)) {
a <- attributes(x[[i]])
Q <- quantile(x[[i]], probs=quantiles, na.rm=TRUE)
attributes(Q) <- a
x[[i]] <- Q
}
structure(x, class=c("rvsummary_numeric", "rvsummary"), quantiles=quantiles)
}
as.rvsummary.rvinteger <- function (x, quantiles=(0:200/200), ...)
{
ms <- .rvmeansd(x, names.=c("mean", "sd", "NAS", "n.sims"))
for (name in names(ms)) {
rvattr(x, name) <- ms[[name]]
}
for (i in seq_along(x)) {
a <- attributes(x[[i]])
Q <- quantile(x[[i]], probs=quantiles, na.rm=TRUE)
attributes(Q) <- a
x[[i]] <- Q
}
structure(x, class=c("rvsummary_integer", "rvsummary"), quantiles=quantiles)
}
as.rvsummary.rvlogical <- function (x, ...)
{
ms <- .rvmeansd(x, names.=c("mean", "sd", "NAS", "n.sims"))
for (name in names(ms)) {
rvattr(x, name) <- ms[[name]]
}
for (i in seq_along(x)) {
a <- attributes(x[[i]])
x[[i]] <- ms[["mean"]][i]
attributes(x[[i]]) <- a
}
structure(x, class=c("rvsummary_logical", "rvsummary"))
}
as.rvsummary.rvfactor <- function (x, ...)
{
levels <- levels(x)
llev <- length(levels)
num.levels <- seq_len(llev)
S <- sims(x)
a <- apply(S, 2, function (x) table(c(x, num.levels)))
if (is.null(dim(a))) {
dim(a) <- c(ncol(S), llev)
}
a <- (a-1)
ns <- rvnsims(x)
if (any(naS <- is.na(S))) {
NAS <- (colMeans(naS)*100)
} else {
NAS <- rep.int(0, length(x))
}
nax <- if (is.null(dim(x))) NULL else names(x)
M <- a
rownames(M) <- levels
remaining <- (ns-colSums(M))
if (any(remaining>0)) {
stop("Impossible: levels won't sum up to 0")
}
P <- t(M/ns)
for (i in seq_along(x)) {
a <- attributes(x[[i]])
x[[i]] <- P[i,]
attributes(x[[i]]) <- a
}
rvattr(x, "n.sims") <- as.list(ns)
rvattr(x, "NAS") <- as.list(NAS)
structure(x, class=c("rvsummary_rvfactor", "rvsummary"))
}
as.rvsummary.data.frame <- function (x, quantiles=rvpar("summary.quantiles.numeric"), ...)
{
name <- names(x)
rnames <- rownames(x)
q.columns <- (regexpr("^([0-9.]+)%", name)>0)
q.names <- name[q.columns]
d.quantiles <- (as.numeric(gsub("^([0-9.]+)%", "\\1", name[q.columns]))/100)
lx <- nrow(x)
ms <- list()
ms$n.sims <- if ("sims" %in% name) { x[["sims"]] } else { rep(Inf, lx) }
ms$NAS <- if ("NA%" %in% name) { x[["NA%"]] } else { rep(0L, lx) }
ms$mean <- if ("mean" %in% name) { x[["mean"]] } else { rep(NA, lx) }
ms$sd <- if ("sd" %in% name) { x[["sd"]] } else { rep(NA, lx) }
if (length(d.quantiles)==0) {
if (length(quantiles)>0) {
x <- lapply(seq_along(ms$mean), function (i) qnorm(quantiles, mean=ms$mean[i], sd=ms$sd[i]))
} else {
x <- as.list(rep.int(NA, nrow(x)))
}
d.quantiles <- quantiles
} else {
x <- as.matrix(x[q.columns])
x <- split(x, row(x))
}
for (name in names(ms)) {
rvattr(x, name) <- ms[[name]]
}
structure(x, class=c("rvsummary_numeric", "rvsummary"), quantiles=d.quantiles, names=rnames)
}
as.double.rvsummary <- function (x, ...)
{
if (is.null(attr(x, "quantiles"))) {
stop("Cannot coerce to double.")
}
return(x)
}
print.rvsummary_rvfactor <- function (x, all.levels=FALSE, ...)
{
print(summary(x, all.levels=all.levels, ...))
}
as.data.frame.rvsummary <- function (x, ...) {
S <- summary(x, ...)
rownames(S) <- S[["name"]]
S[["name"]] <- NULL
return(S)
}
summary.rvsummary <- function (object, ...)
{
x <- object
xdim <- dim(x)
xdimnames <- dimnames(x)
Summary <- attr(object, "summary")
if (length(.names <- names(x))>0) {
Summary <- cbind(name=.names, Summary)
}
Col <- NULL
n.sims. <- rvnsims(x)
NAS <- unlist(rvattr(x, "NAS"))
if (all(NAS==0)) {
Col <- data.frame(sims=n.sims.)
} else {
Col <- data.frame("NA%"=NAS, sims=n.sims.)
}
if (!all(is.na(Rhats <- rvRhat(x)))) {
Col <- cbind(Col, Rhat=Rhats)
}
if (!all(is.na(n.effs <- rvneff(x)))) {
Col <- cbind(Col, n.eff=n.effs)
}
Summary <- cbind(Summary, Col)
if (!is.null(unlist(xdimnames))) {
sud <- rvpar("summary.dimnames")
if (is.null(sud) || isTRUE(sud)) {
.f <- function (i) {
X <- .dimind(dim.=xdim, MARGIN=i)
na <- xdimnames[[i]]
if (!is.null(na)) { na <- na[X] }
return(na)
}
da <- lapply(seq_along(xdim), .f)
names(da) <- names(xdimnames)
if (is.null(names(da))) {
names(da) <- if (length(xdim)==2) c("row", "col") else paste("d", seq_along(da), sep="")
}
da <- da[!sapply(da, is.null)]
if (length(da)>0) {
Summary <- cbind(as.data.frame(da), " "=':', Summary)
}
}
}
return(Summary)
}
summary.rvsummary_numeric <- function (object, ...)
{
x <- object
if (is.null(qs <- rvpar("summary.quantiles.numeric"))) {
qs <- c(0.025, 0.25, 0.5, 0.75, 0.975)
}
S <- t(sims(x))
Q <- attr(S, "quantiles")
qa <- (Q%in%qs)
q <- S[,qa,drop=FALSE]
m <- rvmean(x)
s <- rvsd(x)
S <- data.frame(mean=m, sd=s)
S <- cbind(S, as.data.frame(q))
rownames(S) <- .dim.index(x)
attr(object, "summary") <- S
NextMethod()
}
summary.rvsummary_logical <- function (object, ...)
{
x <- object
S <- data.frame(mean=rvmean(x), sd=rvsd(x))
rownames(S) <- .dim.index(x)
attr(object, "summary") <- S
NextMethod()
}
summary.rvsummary_integer <- function (object, ...)
{
x <- object
if (is.null(qs <- rvpar("summary.quantiles.integer"))) {
qs <- c(0, 0.025, 0.25, 0.5, 0.75, 0.975, 1)
}
S <- t(sims(x))
Q <- attr(S, "quantiles")
qa <- (Q%in%qs)
q <- S[,qa,drop=FALSE]
names_quantiles <- dimnames(q)[[2]]
names_quantiles[names_quantiles=="0%"] <- "min"
names_quantiles[names_quantiles=="100%"] <- "max"
dimnames(q)[[2]] <- names_quantiles
m <- rvmean(x)
s <- rvsd(x)
S <- data.frame(mean=m, sd=s)
S <- cbind(S, as.data.frame(q))
rownames(S) <- .dim.index(x)
attr(object, "summary") <- S
NextMethod()
}
summary.rvsummary_rvfactor <- function (object, all.levels=TRUE, ...)
{
x <- object
levels <- levels(x)
llev <- length(levels)
num.levels <- seq_along(levels)
maxlev <- if (is.null(maxlev <- rvpar("max.levels"))) { 10 } else maxlev
too.many.levels.to.show <- ((!all.levels) && (llev>maxlev))
last.lev.no <- llev
proportions <- t(sims(x))
if (too.many.levels.to.show) {
P1 <- proportions[,1:(maxlev-1),drop=FALSE]
P2 <- proportions[,last.lev.no,drop=FALSE]
omit_levels <- (!seq_along(levels) %in% c(1:(maxlev-1), last.lev.no))
rest <- rowSums(proportions[,omit_levels,drop=FALSE])
M <- cbind(P1, "*"=rest, P2)
colnames(M) <- c(levels[1:(maxlev-1)], "*", levels[last.lev.no])
} else {
M <- proportions
colnames(M) <- levels
}
S <- as.data.frame(M)
rownames(S) <- .dim.index(x)
attr(object, "summary") <- S
NextMethod()
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.