code
stringlengths 1
13.8M
|
---|
"SxM_pheno" |
calc_CobbleDoseRate <- function(input,conversion = "Guerinetal2011"){
if ((max(input[,1])>input$CobbleDiameter[1]*10) ||
((max(input[,1]) + input[length(input[,1]),3]) > input$CobbleDiameter[1]*10))
stop("[calc_CobblDoseRate()] Slices outside of cobble. Please check your distances and make sure they are in mm and diameter is in cm!", call. = FALSE)
SedDoseData <- matrix(data = NA, nrow = 1, ncol = 10)
CobbleDoseData <- matrix(data = 0, nrow = 1, ncol = 10)
CobbleDoseData <- input[1,5:12]
CobbleDoseData <- cbind(CobbleDoseData,0,0)
SedDoseData <- cbind(input[1,5],input[1,15:20],input[1,12],input[1,23:24])
CobbleDoseRate <- get_RLum(convert_Concentration2DoseRate(
input = CobbleDoseData, conversion = conversion))
SedDoseRate <- get_RLum(
convert_Concentration2DoseRate(input = SedDoseData, conversion = conversion))
N <- length(input$Distance)
Diameter <- input$CobbleDiameter[1]
if (Diameter<25){
CobbleGammaAtt <-
(0.55 * exp(-0.45 * Diameter) + 0.09 * exp(-0.06 * Diameter)) * 10
}else {
CobbleGammaAtt <- 0.02
}
Scaling <- input$Density[1] / 2.7
GammaEdge <- 0.5 * (1 - exp(-0.039 * Diameter))
GammaCentre <- 2 * GammaEdge
DiameterSeq <-
seq(0, Diameter * 10, by = 0.01)
Temp <- matrix(data = NA, nrow = length(DiameterSeq), ncol = 9)
DistanceError <- matrix(data = NA, nrow = N, ncol = 8)
ThicknessError <- matrix(data = NA, nrow = N, ncol = 8)
DataIndividual <- matrix(data = NA, nrow = N, ncol = 25)
DataComponent <- matrix(data = NA, nrow = N, ncol = 9)
DoseRates <- matrix(data = NA, nrow = 1, ncol = 24)
output <- matrix(list(), nrow = 2, ncol = 1)
t <- Diameter * 10 - DiameterSeq
tGamma <- t
KBetaCobble <- function(x) (1 - 0.5 * exp(-3.77 * DiameterSeq))+(1-0.5*exp(-3.77*t))-1
ThBetaCobble_short <- function(x) (1 - 0.5 * exp(-5.36 * x * Scaling))+(1-0.5*exp(-5.36*t*Scaling))-1
ThBetaCobble_long <- function(x) (1 - 0.33 * exp(-2.36 * x * Scaling))+(1-0.33*exp(-2.36*t*Scaling))-1
UBetaCobble_short <- function(x) (1 - 0.5 * exp(-4.15 * x * Scaling))+(1-0.5*exp(-4.15*t*Scaling))-1
UBetaCobble_long <- function(x) (1 - 0.33 * exp(-2.36 * x * Scaling))+(1-0.33*exp(-2.36*t*Scaling))-1
GammaCobble <- function(x) {
(GammaCentre - GammaEdge * exp(-CobbleGammaAtt * x * Scaling)) +
(GammaCentre - GammaEdge * exp(-CobbleGammaAtt * tGamma * Scaling)) -
GammaCentre
}
KBetaSed <- function(x) 2 - (1 - 0.5 * exp(-3.77 * x * Scaling)) - (1 - 0.5 * exp(-3.77 * t * Scaling))
ThBetaSed_short <- function(x) 2 - (1 - 0.5 * exp(-5.36 * x * Scaling)) - (1 - 0.5 * exp(-5.36 * t * Scaling))
ThBetaSed_long <- function(x) 2 - (1 - 0.33 * exp(-2.36 * x * Scaling)) - (1 - 0.33 * exp(-2.36 * t * Scaling))
UBetaSed_short <- function(x) 2 - (1 - 0.5 * exp(-4.15 * x * Scaling)) - (1 - 0.5 * exp(-4.15 * t * Scaling))
UBetaSed_long <- function(x) 2 - (1 - 0.33 * exp(-2.36 * x * Scaling)) - (1 - 0.33 * exp(-2.36 * t * Scaling))
GammaSed <- function(x) 2 - (1 - 0.5 * exp(-0.02 * x * Scaling)) - (1 - 0.5 * exp(-0.02 * tGamma *
Scaling))
Temp[, 1] <- DiameterSeq
Temp[, 2] <- KBetaCobble(DiameterSeq)
Temp[, 3] <- ThBetaCobble_long(DiameterSeq)
Temp[, 4] <- UBetaCobble_long(DiameterSeq)
Temp[, 5] <- GammaCobble(DiameterSeq)
Temp[, 6] <- KBetaSed(DiameterSeq)
Temp[, 7] <- ThBetaSed_long(DiameterSeq)
Temp[, 8] <- UBetaSed_long(DiameterSeq)
Temp[, 9] <- GammaSed(DiameterSeq)
TempThCob <- ThBetaCobble_short(DiameterSeq)
TempUCob <- UBetaCobble_short(DiameterSeq)
TempThSed <- ThBetaSed_short(DiameterSeq)
TempUSed <- UBetaSed_short(DiameterSeq)
n <- which(DiameterSeq >= (max(DiameterSeq)-0.15))[1]
Max <- length(DiameterSeq)
Temp[0:16, 3] <- TempThCob[0:16]
Temp[n:Max, 3] <- TempThCob[n:Max]
Temp[0:16, 7] <- TempThSed[0:16]
Temp[n:Max, 7] <- TempThSed[n:Max]
Temp[0:16, 4] <- TempUCob[0:16]
Temp[n:Max, 4] <- TempUCob[n:Max]
Temp[0:16, 8] <- TempUSed[0:16]
Temp[n:Max, 8] <- TempUSed[n:Max]
colnames(Temp) <- c(
"Distance",
"KBetaCob",
"ThBetaCob",
"UBetaCob",
"GammaCob",
"KBetaSed",
"ThBetaSed",
"UBetaSed",
"GammaSed"
)
Distances <- input$Distance / 0.01 + 1
Thicknesses <- input$Thickness / 0.01
MinDistance <- (input$Distance - input$DistanceError) / 0.01 + 1
MaxDistance <- (input$Distance + input$DistanceError) / 0.01 + 1
MinThickness <- (input$Thickness - input$ThicknessError) / 0.01
MaxThickness <- (input$Thickness + input$ThicknessError) / 0.01
for (i in 1:N){
Start <- Distances[i]
End <- Start+Thicknesses[i]
d_min <- MinDistance[i]
d_max <- MaxDistance[i]
t_min <- MinThickness[i]
t_max <- MaxThickness[i]
if (MinDistance[i]<0){
d_min <- 0
}
j <- d_min+Thicknesses[i]
k <- d_max+Thicknesses[i]
for (l in 1:8){
m <- l + 1
if (d_min == Start){
DistanceError[i,l]<- abs(
(mean(Temp[d_max:k,m])-mean(Temp[Start:End,m]))/(2*mean(Temp[Start:End,m])))
} else if (k > Max){
DistanceError[i,l] <- abs(
(mean(Temp[Start:End,m])-mean(Temp[d_min:j,m]))/(2*mean(Temp[Start:End,m])))
} else {
DistanceError[i,l] <- abs(
mean((mean(Temp[d_max:k,m])-mean(Temp[Start:End,m])):(mean(Temp[Start:End,m])-mean(Temp[d_min:j,m])))/(2*mean(Temp[Start:End,m])))
}
j2 <- Start+t_min
k2 <- Start+t_max
if (k2 > Max){
ThicknessError[i,l] <- abs(
(mean(Temp[Start:End,m])-mean(Temp[Start:j2,m]))/(2*mean(Temp[Start:End,m])))
} else {
ThicknessError[i,l] <- abs(
mean((mean(Temp[Start:k2,m])-mean(Temp[Start:End,m])):(mean(Temp[Start:End,m])-mean(Temp[Start:j2,m])))/(2*mean(Temp[Start:End,m])))
}
}
DataIndividual[i, 1] <- input[i, 1]
DataIndividual[i, 2] <- mean(Temp[Start:End, 2]) * CobbleDoseRate[1, 1]
DataIndividual[i, 3] <-
DataIndividual[i, 2] * sqrt(DistanceError[i, 1] ^ 2 + ThicknessError[i, 1] ^
2 + (CobbleDoseRate[1, 2] / CobbleDoseRate[1, 1]) ^ 2)
DataIndividual[i, 4] <- mean(Temp[Start:End, 3]) * CobbleDoseRate[1, 3]
DataIndividual[i, 5] <-
DataIndividual[i, 4] * sqrt(DistanceError[i, 2] ^ 2 + ThicknessError[i, 2] ^
2 + (CobbleDoseRate[1, 4] / CobbleDoseRate[1, 3]) ^ 2)
DataIndividual[i, 6] <- mean(Temp[Start:End, 4]) * CobbleDoseRate[1, 5]
DataIndividual[i, 7] <- DataIndividual[i, 6] * sqrt(DistanceError[i, 3] ^ 2 + ThicknessError[i, 3] ^
2 + (CobbleDoseRate[1, 6] / CobbleDoseRate[1, 5]) ^ 2)
DataIndividual[i, 8] <- mean(Temp[Start:End, 5]) * CobbleDoseRate[2, 1]
DataIndividual[i, 9] <- DataIndividual[i, 8] * sqrt(DistanceError[i, 4] ^ 2 + ThicknessError[i, 4] ^
2 + (CobbleDoseRate[2, 2] / CobbleDoseRate[2, 1]) ^ 2)
DataIndividual[i, 10] <- mean(Temp[Start:End, 5]) * CobbleDoseRate[2, 3]
DataIndividual[i, 11] <-
DataIndividual[i, 10] * sqrt(DistanceError[i, 4] ^ 2 + ThicknessError[i, 4] ^
2 + (CobbleDoseRate[2, 4] / CobbleDoseRate[2, 3]) ^ 2)
DataIndividual[i, 12] <- mean(Temp[Start:End, 5]) * CobbleDoseRate[2, 5]
DataIndividual[i, 13] <-
DataIndividual[i, 12] * sqrt(DistanceError[i, 4] ^ 2 + ThicknessError[i, 4] ^
2 + (CobbleDoseRate[2, 6] / CobbleDoseRate[2, 5]) ^ 2)
DataIndividual[i, 14] <- mean(Temp[Start:End, 6]) * SedDoseRate[1, 1]
DataIndividual[i, 15] <-
DataIndividual[i, 14] * sqrt(DistanceError[i, 5] ^ 2 + ThicknessError[i, 5] ^
2 + (SedDoseRate[1, 2] / SedDoseRate[1, 1]) ^ 2)
DataIndividual[i, 16] <- mean(Temp[Start:End, 7]) * SedDoseRate[1, 3]
DataIndividual[i, 17] <-
DataIndividual[i, 16] * sqrt(DistanceError[i, 6] ^ 2 + ThicknessError[i, 6] ^
2 + (SedDoseRate[1, 4] / SedDoseRate[1, 3]) ^ 2)
DataIndividual[i, 18] <- mean(Temp[Start:End, 8]) * SedDoseRate[1, 5]
DataIndividual[i, 19] <-
DataIndividual[i, 18] * sqrt(DistanceError[i, 7] ^ 2 + ThicknessError[i, 7] ^
2 + (SedDoseRate[1, 6] / SedDoseRate[1, 5]) ^ 2)
DataIndividual[i, 20] <- mean(Temp[Start:End, 9]) * SedDoseRate[2, 1]
DataIndividual[i, 21] <-
DataIndividual[i, 20] * sqrt(DistanceError[i, 8] ^ 2 + ThicknessError[i, 8] ^
2 + (SedDoseRate[2, 2] / SedDoseRate[2, 1]) ^ 2)
DataIndividual[i, 22] <- mean(Temp[Start:End, 9]) * SedDoseRate[2, 3]
DataIndividual[i, 23] <-
DataIndividual[i, 22] * sqrt(DistanceError[i, 8] ^ 2 + ThicknessError[i, 8] ^
2 + (SedDoseRate[2, 4] / SedDoseRate[2, 3]) ^ 2)
DataIndividual[i, 24] <- mean(Temp[Start:End, 9]) * SedDoseRate[2, 5]
DataIndividual[i, 25] <-
DataIndividual[i, 24] * sqrt(DistanceError[i, 8] ^ 2 + ThicknessError[i, 8] ^
2 + (SedDoseRate[2, 6] / SedDoseRate[2, 5]) ^ 2)
DataComponent[i, 1] <- input[i, 1]
DataComponent[i, 2] <- DataIndividual[i, 2] + DataIndividual[i, 4] + DataIndividual[i, 6]
DataComponent[i, 3] <- DataComponent[i,2]*sqrt((DataIndividual[i,3]/DataIndividual[i,2])^2+(DataIndividual[i,5]/DataIndividual[i,4])^2+(DataIndividual[i,7]/DataIndividual[i,6])^2)
DataComponent[i, 4] <- DataIndividual[i, 8] + DataIndividual[i, 10] + DataIndividual[i, 12]
DataComponent[i, 5] <- DataComponent[i,4]*sqrt((DataIndividual[i,9]/DataIndividual[i,8])^2+(DataIndividual[i,11]/DataIndividual[i,10])^2+(DataIndividual[i,13]/DataIndividual[i,12])^2)
DataComponent[i, 6] <- DataIndividual[i, 14] + DataIndividual[i, 16] + DataIndividual[i, 18]
DataComponent[i, 7] <- DataComponent[i,6]*sqrt((DataIndividual[i,15]/DataIndividual[i,14])^2+(DataIndividual[i,17]/DataIndividual[i,16])^2+(DataIndividual[i,19]/DataIndividual[i,18])^2)
DataComponent[i, 8] <- DataIndividual[i, 20] + DataIndividual[i, 22] + DataIndividual[i, 24]
DataComponent[i, 9] <- DataComponent[i,8]*sqrt((DataIndividual[i,21]/DataIndividual[i,20])^2+(DataIndividual[i,23]/DataIndividual[i,22])^2 + (DataIndividual[i,25]/DataIndividual[i,24])^2)
}
colnames(DataIndividual) <-
c(
"Distance.",
"K Beta cobble",
"SE",
"Th Beta cobble",
"SE",
"U Beta cobble",
"SE",
"K Gamma cobble",
"SE",
"Th Gamma cobble",
"SE",
"U Gamma cobble",
"SE",
"K Beta sed.",
"SE",
"Th Beta sed.",
"SE",
"U Beta sed.",
"SE",
"K Gamma sed.",
"SE",
"Th Gamma sed.",
"SE",
"U Gamma sed.",
"SE"
)
colnames(DataComponent) <-
c(
"Distance",
"Total Cobble Beta",
"SE",
"Total Cobble Gamma",
"SE",
"Total Beta Sed.",
"SE",
"Total Gamma Sed.",
"SE"
)
DataIndividual[is.na(DataIndividual)] <- 0
DataComponent[is.na(DataComponent)] <- 0
return(
set_RLum(
class = "RLum.Results",
data = list(
DataIndividual = DataIndividual,
DataComponent = DataComponent,
input = input
),
info = list(
call = sys.call()
)))
} |
rmetalog <- function(m, n = 1, term = 3) {
UseMethod("rmetalog", m)
}
rmetalog.default <- function(m, n = 1, term = 3) {
print('Object must be of calss metalog')
}
rmetalog.metalog <- function(m, n = 1, term = 3){
valid_terms <- m$Validation$term
valid_terms_printout <- paste(valid_terms, collapse = " ")
if (class(n) != 'numeric' | n < 1 | n %% 1 != 0) {
stop('Error: n must be a positive numeric interger')
}
if (class(term) != 'numeric' |
term < 2 | term %% 1 != 0 | !(term %in% valid_terms) |
length(term) > 1) {
stop(
paste('Error: term must be a single positive numeric interger contained',
'in the metalog object. Available terms are:', valid_terms_printout)
)
}
x <- stats::runif(n)
Y <- data.frame(y1 = rep(1, n))
Y$y2 <- (log(x / (1 - x)))
if (term > 2) {
Y$y3 <- (x - 0.5) * Y$y2
}
if (term > 3) {
Y$y4 <- x - 0.5
}
if (term > 4) {
for (i in 5:(term)) {
y <- paste0('y', i)
if (i %% 2 != 0) {
Y[`y`] <- Y$y4 ^ (i %/% 2)
}
if (i %% 2 == 0) {
z <- paste0('y', (i - 1))
Y[`y`] <- Y$y2 * Y[`z`]
}
}
}
Y <- as.matrix(Y)
amat <- paste0('a', term)
a <- as.matrix(m$A[`amat`])
s <- Y %*% a[1:term]
if (m$params$boundedness == 'sl') {
s <- m$params$bounds[1] + exp(s)
}
if (m$params$boundedness == 'su') {
s <- m$params$bounds[2] - exp(-(s))
}
if (m$params$boundedness == 'b') {
s <-
(m$params$bounds[1] + (m$params$bounds[2]) * exp(s)) /
(1 + exp(s))
}
return(as.numeric(s))
}
qmetalog <- function(m, y, term = 3) {
UseMethod("qmetalog", m)
}
qmetalog.default <- function(m, y, term = 3){
print('Object must be of class metalog')
}
qmetalog.metalog <- function(m, y, term = 3){
valid_terms <- m$Validation$term
valid_terms_printout <- paste(valid_terms, collapse = " ")
if (class(y) != 'numeric' | max(y) >= 1 | min(y) <= 0) {
stop('Error: y must be a positive numeric vector between 0 and 1')
}
if (class(term) != 'numeric' |
term < 2 | term %% 1 != 0 | !(term %in% valid_terms) |
length(term) > 1) {
stop(
paste('Error: term must be a single positive numeric interger contained',
'in the metalog object. Available terms are:', valid_terms_printout)
)
}
Y <- data.frame(y1 = rep(1, length(y)))
Y$y2 <- (log(y / (1 - y)))
if (term > 2) {
Y$y3 <- (y - 0.5) * Y$y2
}
if (term > 3) {
Y$y4 <- (y - 0.5)
}
if (term > 4) {
for (i in 5:(term)) {
y <- paste0('y', i)
if (i %% 2 != 0) {
Y[`y`] <- Y$y4 ^ (i %/% 2)
}
if (i %% 2 == 0) {
z <- paste0('y', (i - 1))
Y[`y`] <- Y$y2 * Y[`z`]
}
}
}
Y <- as.matrix(Y)
amat <- paste0('a', term)
a <- as.matrix(m$A[`amat`])
s <- Y %*% a[1:term]
if (m$params$boundedness == 'sl') {
s <- m$params$bounds[1] + exp(s)
}
if (m$params$boundedness == 'su') {
s <- m$params$bounds[2] - exp(-(s))
}
if (m$params$boundedness == 'b') {
s <- (m$params$bounds[1] + (m$params$bounds[2]) * exp(s)) / (1 + exp(s))
}
return(as.numeric(s))
}
pmetalog <- function(m, q, term = 3) {
UseMethod("pmetalog", m)
}
pmetalog.default <- function(m, q, term = 3){
print('Object must be of class metalog')
}
pmetalog.metalog <- function(m, q, term = 3){
valid_terms <- m$Validation$term
if (class(q) != 'numeric') {
stop('Error: q must be a positive numeric vector between 0 and 1')
}
if (class(term) != 'numeric' |
term < 2 | term %% 1 != 0 | !(term %in% valid_terms) |
length(term) > 1) {
stop(
cat('Error: term must be a single positive numeric interger contained',
'in the metalog object. Available terms are:',
valid_terms)
)
}
qs<-sapply(q,newtons_method_metalog,m=m,t=term)
return(qs)
}
dmetalog <- function(m, q, term = 3) {
UseMethod("dmetalog", m)
}
dmetalog.default <- function(m, q, term = 3){
print('Object must be of class metalog')
}
dmetalog.metalog <- function(m, q, term = 3){
valid_terms <- m$Validation$term
if (class(q) != 'numeric') {
stop('Error: q must be a numeric vector')
}
if (class(term) != 'numeric' |
term < 2 | term %% 1 != 0 | !(term %in% valid_terms) |
length(term) > 1) {
stop(
paste('Error: term must be a single positive numeric interger contained',
'in the metalog object. Available terms are:',
valid_terms)
)
}
qs<-sapply(q,newtons_method_metalog,m=m,term=term)
ds<-sapply(qs,pdfMetalog_density, m=m,t=term)
return(ds)
}
summary.metalog <- function(object, ...) {
cat(' -----------------------------------------------\n',
'Summary of Metalog Distribution Object\n',
'-----------------------------------------------\n',
'\nParameters\n',
'Term Limit: ', object$params$term_limit, '\n',
'Term Lower Bound: ', object$params$term_lower_bound, '\n',
'Boundedness: ', object$params$boundedness, '\n',
'Bounds (only used based on boundedness): ', object$params$bounds, '\n',
'Step Length for Distribution Summary: ', object$params$step_len, '\n',
'Method Use for Fitting: ', object$params$fit_method, '\n',
'Number of Data Points Used: ', object$params$number_of_data, '\n',
'Original Data Saved: ', object$params$save_data, '\n',
'\n\n Validation and Fit Method\n'
)
print(object$Validation, row.names = FALSE)
}
plot.metalog <- function(x, ...) {
InitalResults <-
data.frame(
term = (rep(
paste0(x$params$term_lower_bound, ' Terms'), length(x$M[, 1])
)),
pdfValues = x$M[, 1],
quantileValues = x$M[, 2],
cumValue = x$M$y
)
if (ncol(x$M) > 3) {
for (i in 2:(length(x$M[1,] - 1) / 2)) {
TempResults <-
data.frame(
term = (rep(paste((x$params$term_lower_bound + (i - 1)), 'Terms'),
length(x$M[, 1]))),
pdfValues = x$M[, (i * 2 - 1)],
quantileValues = x$M[, (i * 2)],
cumValue = x$M$y
)
InitalResults <- rbind(InitalResults, TempResults)
}
}
p <-
ggplot2::ggplot(InitalResults, aes(x = quantileValues, y = pdfValues)) +
ggplot2::geom_line(colour = "blue") +
ggplot2::xlab("Quantile Values") +
ggplot2::ylab("PDF Values") +
ggplot2::facet_wrap(~ term, ncol = 4, scales = "free_y")
q <-
ggplot2::ggplot(InitalResults, aes(x = quantileValues, y = cumValue)) +
ggplot2::geom_line(colour = "blue") +
ggplot2::xlab("Quantile Values") +
ggplot2::ylab("CDF Values") +
ggplot2::facet_wrap(~ term, ncol = 4, scales = "free_y")
list(pdf = p, cdf = q)
} |
require(OpenMx)
data(latentMultipleRegExample2)
numberFactors <- 3
indicators <- names(latentMultipleRegExample2)
numberIndicators <- length(indicators)
totalVars <- numberIndicators + numberFactors
latents <- paste("F", 1:numberFactors, sep="")
loadingLabels <- paste("b_F", rep(1:numberFactors, each=numberIndicators),
rep(indicators, numberFactors), sep="")
loadingLabels
uniqueLabels <- paste("U_", indicators, sep="")
meanLabels <- paste("M_", indicators, sep="")
factorVarLabels <- paste("Var_", latents, sep="")
latents1 <- latents[1]
indicators1 <- indicators[1:4]
loadingLabels1 <- paste("b_F1", indicators[1:4], sep="")
latents2 <- latents[2]
indicators2 <- indicators[5:8]
loadingLabels2 <- paste("b_F2", indicators[5:8], sep="")
latents3 <- latents[3]
indicators3 <- indicators[9:12]
loadingLabels3 <- paste("b_F3", indicators[9:12], sep="")
threeLatentOrthoRaw1 <- mxModel("threeLatentOrthogonal",
type="RAM",
manifestVars=indicators,
latentVars=latents,
mxPath(from=latents1, to=indicators1,
arrows=1, connect="all.pairs",
free=TRUE, values=.2,
labels=loadingLabels1),
mxPath(from=latents2, to=indicators2,
arrows=1, connect="all.pairs",
free=TRUE, values=.2,
labels=loadingLabels2),
mxPath(from=latents3, to=indicators3,
arrows=1, connect="all.pairs",
free=TRUE, values=.2,
labels=loadingLabels3),
mxPath(from=latents1, to=indicators1[1],
arrows=1,
free=FALSE, values=1),
mxPath(from=latents2, to=indicators2[1],
arrows=1,
free=FALSE, values=1),
mxPath(from=latents3, to=indicators3[1],
arrows=1,
free=FALSE, values=1),
mxPath(from=indicators,
arrows=2,
free=TRUE, values=.8,
labels=uniqueLabels),
mxPath(from=latents,
arrows=2,
free=TRUE, values=.8,
labels=factorVarLabels),
mxPath(from="one", to=indicators,
arrows=1, free=TRUE, values=.1,
labels=meanLabels),
mxData(observed=latentMultipleRegExample2, type="raw")
)
threeLatentOrthoRaw1Out <- mxRun(threeLatentOrthoRaw1, suppressWarnings=TRUE)
summary(threeLatentOrthoRaw1Out)
threeLatentObliqueRaw1 <- mxModel(threeLatentOrthoRaw1,
mxPath(from=latents,to=latents,connect="unique.pairs",
arrows=2,
free=TRUE, values=.3),
mxPath(from=latents,
arrows=2,
free=TRUE, values=.8,
labels=factorVarLabels),
name="threeLatentOblique"
)
threeLatentObliqueRaw1Out <- mxRun(threeLatentObliqueRaw1, suppressWarnings=TRUE)
summary(threeLatentObliqueRaw1Out)
threeLatentMultipleReg1 <- mxModel(threeLatentOrthoRaw1,
mxPath(from="F1",to="F2",
arrows=2,
free=TRUE, values=.3),
mxPath(from=c("F1","F2"), to="F3",
arrows=1,
free=TRUE, values=.2,
labels=c("b1", "b2")),
name="threeLatentMultipleReg"
)
threeLatentMultipleReg1Out <- mxRun(threeLatentMultipleReg1, suppressWarnings=TRUE)
summary(threeLatentMultipleReg1Out)
threeLatentMultipleReg2 <- mxModel(threeLatentMultipleReg1,
mxPath(from="F1",to="F3",
arrows=1,
free=FALSE, values=0),
name="threeLatentMultipleReg2"
)
threeLatentMultipleReg2Out <- mxRun(threeLatentMultipleReg2, suppressWarnings=TRUE)
summary(threeLatentMultipleReg2Out)
threeLatentMultipleReg3 <- mxModel(threeLatentMultipleReg1,
mxPath(from="F2",to="F3",
arrows=1,
free=FALSE, values=0),
name="threeLatentMultipleReg3"
)
threeLatentMultipleReg3Out <- mxRun(threeLatentMultipleReg3, suppressWarnings=TRUE)
summary(threeLatentMultipleReg3Out)
expectVal <- c(0.899885, 1.211974, 1.447476, 0.700916, 1.295793,
1.138494, 0.90601, 0.89185, 0.847205, 1.038429, 1.038887, 0.820293,
0.945828, 0.835869, 0.973786, 0.9823, 1.049919, 1.331468, 1.038726,
0.767559, 0.965987, 1.742792, 1.095046, 1.089994, 0.828187, 0.516085,
1.139466, 0.067508, 0.121391, 0.088573, -0.034883, -0.094189,
0.012756, -0.067871, -0.059441, -0.070524, -0.049503, -0.049853,
-0.098781)
expectSE <- c(0.07695, 0.087954, 0.102656, 0.088136, 0.119946, 0.111449,
0.11528, 0.113175, 0.110252, 0.122903, 0.11859, 0.114598, 0.145985,
0.106003, 0.106815, 0.141517, 0.133942, 0.17212, 0.133215, 0.10943,
0.121737, 0.26635, 0.162563, 0.18551, 0.158593, 0.118376, 0.235046,
0.117896, 0.110676, 0.129977, 0.151584, 0.098098, 0.086849, 0.118565,
0.110935, 0.11116, 0.099326, 0.091469, 0.094438)
expectMin <- 7710.615
omxCheckCloseEnough(expectVal, threeLatentObliqueRaw1Out$output$estimate, 0.001)
omxCheckCloseEnough(expectSE,
as.vector(threeLatentObliqueRaw1Out$output[['standardErrors']]), 0.001)
omxCheckCloseEnough(expectMin, threeLatentObliqueRaw1Out$output$minimum, 0.001)
expectVal <- c(0.899885, 1.211973, 1.447476, 0.481912, 0.700916,
1.295792, 1.138493, -0.010669, 0.906009, 0.891849, 0.847204,
1.038428, 1.038887, 0.820293, 0.945828, 0.835868, 0.973786, 0.982301,
1.049919, 1.331467, 1.038726, 0.767558, 0.965987, 1.742797, 1.09505,
1.089998, 0.745861, 0.067508, 0.12139, 0.088573, -0.034883, -0.09419,
0.012755, -0.067872, -0.059441, -0.070524, -0.049503, -0.049853,
-0.098781)
expectSE <- c(0.0769, 0.087865, 0.102543, 0.127828, 0.088084, 0.119791, 0.111236,
0.152625, 0.115206, 0.113084, 0.110164, 0.122883, 0.118535, 0.114589,
0.145932, 0.10598, 0.106799, 0.141507, 0.133841, 0.171978, 0.13313,
0.109413, 0.121718, 0.26595, 0.16229, 0.185135, 0.157228, 0.11835,
0.111086, 0.13054, 0.152265, 0.098407, 0.087037, 0.119005, 0.111335,
0.11135, 0.09954, 0.091682, 0.094603)
expectMin <- 7710.615
omxCheckCloseEnough(expectVal, threeLatentMultipleReg1Out$output$estimate, 0.01)
omxCheckCloseEnough(expectSE,
as.vector(threeLatentMultipleReg1Out$output[['standardErrors']]), 0.01)
omxCheckCloseEnough(expectMin, threeLatentMultipleReg1Out$output$minimum, 0.01)
expectVal <- c(0.90026, 1.208833, 1.450523, 0.714247, 1.294955,
1.145001, 0.539993, 0.925794, 0.907651, 0.857963, 1.038481, 1.037751,
0.833617, 0.930552, 0.865281, 0.968228, 1.033987, 1.072283, 1.360517,
1.022325, 0.759087, 0.966464, 1.742743, 1.115285, 1.060584, 0.801163,
0.067507, 0.12139, 0.088573, -0.034883, -0.09419, 0.012755, -0.067872,
-0.059442, -0.070524, -0.049503, -0.049853, -0.098781)
expectSE <- c(0.07703, 0.088125, 0.103052, 0.089582, 0.121094, 0.113147,
0.102949, 0.118661, 0.116812, 0.113105, 0.123476, 0.118851, 0.116296,
0.146876, 0.106735, 0.105913, 0.142948, 0.13435, 0.17478, 0.133635,
0.110398, 0.122877, 0.266637, 0.163601, 0.183091, 0.171665, 0.11752,
0.110322, 0.129462, 0.150946, 0.097806, 0.086686, 0.118153, 0.110619,
0.111, 0.099205, 0.091341, 0.09432)
expectMin <- 7726.295
omxCheckCloseEnough(expectVal, threeLatentMultipleReg2Out$output$estimate, 0.01)
omxCheckCloseEnough(expectSE,
as.vector(threeLatentMultipleReg2Out$output[['standardErrors']]), 0.01)
omxCheckCloseEnough(expectMin, threeLatentMultipleReg2Out$output$minimum, 0.01)
expectVal <- c(0.899897, 1.211937, 1.447488, 0.474834, 0.701118,
1.296061, 1.138723, 0.905957, 0.891751, 0.8471, 1.038272, 1.03872,
0.820213, 0.945435, 0.836219, 0.973649, 0.982129, 1.049802, 1.331303,
1.038698, 0.767626, 0.96607, 1.742954, 1.094587, 1.089649, 0.746656,
0.067506, 0.121389, 0.088571, -0.034885, -0.09419, 0.012755,
-0.067873, -0.059442, -0.070525, -0.049504, -0.049854, -0.098782)
expectSE <- c(0.076951, 0.087964, 0.102685, 0.077557, 0.088124, 0.119953,
0.111436, 0.115278, 0.11316, 0.110212, 0.122951, 0.118561, 0.114641,
0.145913, 0.105921, 0.106784, 0.141498, 0.133944, 0.172141, 0.133254,
0.109461, 0.121748, 0.266409, 0.162381, 0.185465, 0.157074, 0.117716,
0.110489, 0.129714, 0.151265, 0.097968, 0.086774, 0.118361, 0.110787,
0.111027, 0.09925, 0.091375, 0.094362)
expectMin <- 7710.62
omxCheckCloseEnough(expectVal, threeLatentMultipleReg3Out$output$estimate, 0.01)
omxCheckCloseEnough(expectSE,
as.vector(threeLatentMultipleReg3Out$output[['standardErrors']]), 0.01)
omxCheckCloseEnough(expectMin, threeLatentMultipleReg3Out$output$minimum, 0.01)
expectVal <- c(0.901891, 1.20158, 1.427049, 0.692088, 1.351975,
1.149558, 0.987615, 0.966986, 0.902343, 1.013963, 1.012679, 0.828678,
0.998327, 0.86774, 1.002452, 0.878394, 1.064433, 1.459186, 0.987214,
0.727833, 0.960052, 1.767278, 1.058139, 1.01176, 0.067512, 0.121394,
0.088578, -0.034877, -0.094186, 0.012757, -0.067868, -0.059437,
-0.070521, -0.049501, -0.04985, -0.098779)
expectSE <- c(0.076528, 0.088527, 0.103665, 0.092459, 0.136218, 0.118764,
0.130232, 0.129587, 0.123389, 0.125806, 0.119984, 0.12382, 0.163071,
0.117211, 0.111291, 0.161268, 0.14648, 0.181275, 0.136797, 0.113505,
0.125792, 0.269576, 0.189346, 0.226953, 0.117883, 0.110644, 0.129952,
0.151555, 0.098128, 0.086865, 0.118584, 0.110962, 0.111143, 0.099336,
0.091474, 0.094429)
expectMin <- 7897.082
omxCheckCloseEnough(expectVal, threeLatentOrthoRaw1Out$output$estimate, 0.01)
omxCheckCloseEnough(expectSE,
as.vector(threeLatentOrthoRaw1Out$output[['standardErrors']]), 0.01)
omxCheckCloseEnough(expectMin, threeLatentOrthoRaw1Out$output$minimum, 0.01) |
rm(list=ls())
d<-read.csv("/data/abomb/lsshempy.csv",header=T)
head(d,2)
d=d[d$mar_an>=0,]
sum(d$cml)
d=within(d,{rm(distcat,agxcat, agecat, dcat, time,upyr,subjects,year,
nhl,hl,mye,all,oll,alltot,cll,hcl,clltot,atl,aml,oml,amol,amltot,
othleuk,noncll,leuktot,hldtot,mar_ag,mar_an)})
head(d,2)
d=within(d, {nic = as.numeric(gdist > 12000); over4gy = 1 - un4gy ;
tsx = (age -agex) ;
lt25 = log(tsx/25) ;
rm(gdist,un4gy)
a = log(age/70) ;
a55 = log(age/55) ;
age55=age-55
agex30=agex-30
ax30 = log(agex/30) ;
py10k = pyr/10000 ;
py = pyr;
s=sex-1
c=city-1
sv=mar_ad10/1000;
hiro = as.numeric(city == 1) ; naga = as.numeric(city ==2);
rm(sex,city,pyr,mar_ad10)
})
head(d)
bk=d[d$sv<0.05,]
library(bbmle)
summary(p1<-mle2(cml~dpois(lambda=py10k*A*exp(cs*s+ca*a+csa*a*s)),
start=list(A=.22,cs=-0.06,ca=1.38,csa=1.75),data=bk) )
summary(e1<-mle2(cml~dpois(lambda=py10k*A*exp(cs*s+k*age55)),
start=list(A=.22,cs=-0.6,k=0.04),data=bk) )
summary(e2<-mle2(cml~dpois(lambda=py10k*A*exp(cs*s+k*age55+ks*s*age55)),
start=list(A=.22,cs=-0.6,k=0.03,ks=.02),data=bk) )
AIC(p1,e1,e2)
BIC(p1,e1,e2)
summary(err<-mle2(cml~dpois(lambda=py10k*(A1*exp(c1s*s+c1a*a+c1sa*a*s+c1nic0*hiro*nic+c1nic1*naga*nic)*
(1+sv*A2*exp(c2c*c + c2t*lt25 + c2a*a55+c2o4g*over4gy) ) ) ),
start=list(A1=.22,c1s=-0.06,c1a=1.38,c1sa=1.75,c1nic0=-0.2,c1nic1=-0.86,
A2=5.24,c2c=-1.50,c2t=-1.59,c2a=-1.42,c2o4g=-0.3),data=d) )
AIC(err)
logLik(err)
deviance(err)
summary(err)
prd=predict(err)
sum(d$cml==1)
-2*sum(d$cml*log(prd))+2*length(coef(err))
-2*sum(d$cml*log(prd))
-2*sum(d$cml*log(prd)-prd-log(factorial(d$cml)))
-2*sum(d$cml*log(prd)-prd)
sum(predict(err))
summary(ear<-mle2(cml~dpois(lambda=py10k*(A1*exp(c1s*s+c1a*a+c1sa*a*s+c1nic0*hiro*nic+c1nic1*naga*nic)
+sv*A2*exp(c2c*c + c2s*s+c2t*lt25 + c2a*a55+c2sa*s*a55+c2o4g*over4gy) ) ) ,
start=list(A1=.22,c1s=-0.06,c1a=1.38,c1sa=1.75,c1nic0=-0.2,c1nic1=-0.86,
A2=5.24,c2c=-1.50,c2s=-0.18,c2t=-1.59,c2a=-1.42,c2sa=2.3,c2o4g=-0.3),data=d) )
prd=predict(ear)
-2*sum(d$cml*log(prd))
-2*sum(d$cml*log(prd))+2*length(coef(ear))
AIC(err,ear)
ICtab(err,ear)
anova(err,ear)
summary(s1<-mle2(cml~dpois(lambda=py*(exp(c10+c2c*c+c2s*s+k*age+ks*s*age)
+sv*exp(c20+c2c*c + c2s*s+c2t*tsx+c2ts*s*tsx) ) ),
start=list(c10=-12.4,k=0.025,ks=0,c20=-10.5,c2c=-1.50,c2s=-0.18,c2t=-0.4,c2ts=0.3),data=d) )
prd=predict(s1)
-2*sum(d$cml*log(prd))
-2*sum(d$cml*log(prd))+2*length(coef(s1))
ICtab(err,s1)
anova(err,s1)
summary(s1a55<-mle2(cml~dpois(lambda=py*(exp(c10+c2c*c+c2s*s+k*age+ks*s*age)
+sv*exp(c20+c2c*c + c2s*s+c2t*tsx+c2ts*s*tsx + c2a*a55+c2sa*s*a55 ) ) ),
start=list(c10=-12.4,k=0.025,ks=0,c20=-10.5,c2c=-1.50,
c2s=-0.18,c2t=-0.4,c2ts=0.3,c2a=-1.42,c2sa=2.3),data=d) )
prd=predict(s1a55)
-2*sum(d$cml*log(prd))
-2*sum(d$cml*log(prd))+2*length(coef(s1a55))
ICtab(err,s1a55)
anova(err,s1a55)
summary(s1a55f<-mle2(cml~dpois(lambda=py*(exp(c10+c2c*c+c2s*s+(k+ks*s)*age)
+sv*exp(c20+c2c*c + c2s*s+c2t*tsx+c2ts*s*tsx +c2sa*s*a55 ) ) ),
start=list(c10=-12.4,k=0.025,ks=0,c20=-10.5,c2c=-1.50,
c2s=-0.18,c2t=-0.4,c2ts=0.3,c2sa=2.3),data=d) )
prd=predict(s1a55f)
-2*sum(d$cml*log(prd))
-2*sum(d$cml*log(prd))+2*length(coef(s1a55f))
ICtab(err,s1a55f)
anova(err,s1a55f)
summary(s1a55f)
a55HMb<-mle2(cml~dpois(lambda=py*(exp(c10+c2c*c+c2s*s+k*age+ks*s*age) +
sv*exp(c20+c2c*c + c2s*s+c2t*tsx+c2ts*s*tsx +c2sa*s*a55+ c2x*(1-c)*(1-s)*abs(agex-30)) ) ),
start=list(c10=-12.4,k=0.025,ks=0,c20=-10.5,c2c=-1.50,
c2s=-0.18,c2t=-0.4,c2ts=0.3,c2x=.1,c2sa=2.3),data=d)
prd=predict(a55HMb)
-2*sum(d$cml*log(prd))
-2*sum(d$cml*log(prd))+2*length(coef(a55HMb))
summary(a55HMb)
AIC(a55HMb,s1a55f)
ICtab(a55HMb,s1a55f)
anova(a55HMb,s1a55f)
summary(best<-mle2(cml~dpois(lambda=py*(exp(c10+c2c*c+c2s*s+k*age+ks*s*age)
+sv*exp(c20+c2c*c + c2s*s-tsx/(c2t+exp(c2ts)*s) +c2sa*s*a55 ) ) ),
start=list(c10=-12.4,k=0.025,ks=0,c20=-10.5,c2c=-1.50,
c2s=-0.18,c2t=5,c2ts=log(10),c2sa=2.3),data=d) )
prd=predict(best)
-2*sum(d$cml*log(prd))
-2*sum(d$cml*log(prd))+2*length(coef(best))
AIC(s1a55f,best)
(sb=summary(best))
sd=coef(sb)["c2ts",2]
mn=coef(best)["c2ts"]
(tauDiff=c(mn,mn-1.96*sd,mn+1.96*sd))
d=transform(d,tsxf=cut(tsx,6),sex=as.factor(s))
head(d)
summary(s3<-mle2(cml~dpois(lambda=py*(exp(c10 + c2c*c + c2s*s + k*age + ks*s*age)
+sv*exp(c2c*c + f + c2sa*s*a55 ) ) ),
parameters=list(f~-1 + tsxf:sex),
start=list(c10=-12.4,k=0.025,ks=0,c2c=-1.50,
c2s=-0.18,f=-5,c2sa=2),data=d) )
prd=predict(s3)
-2*sum(d$cml*log(prd))
-2*sum(d$cml*log(prd))+2*length(coef(s3))
ss3=summary(s3)
wait=exp(coef(ss3)[6:17,1])*1e4
waitL=exp(coef(ss3)[6:17,1]-1.96*coef(ss3)[6:17,2])*1e4
waitU=exp(coef(ss3)[6:17,1]+1.96*coef(ss3)[6:17,2])*1e4
(lvls=levels(d$tsxf))
(Lvls=strsplit(lvls,","))
substring("(4.23",2)
(lows=sapply(Lvls,function(x) as.numeric(substring(x[1],2))))
(ups=sapply(Lvls,function(x) as.numeric(substring(x[2],1,4))))
(mids=round(apply(rbind(lows,ups),2,mean),2))
(dfc=data.frame(mids,wait,waitL,waitU,Sex=gl(2,6,labels=c("Male","Female") ) ) )
dfc
library(ggplot2)
pd <- position_dodge(1)
(p=ggplot(dfc, aes(x=mids, y=wait, shape=Sex,ymax=10)) +
geom_point(size=6,position=pd) )
(p=p+labs(title="IR-to-CML Latency",x="Years since exposure",
y=expression(paste("Cases per ",10^4," Person-Year-Sv") ) ) )
(p=p+geom_errorbar(aes(ymin=waitL, ymax=waitU),width=.01,position=pd))
(p=p+theme(plot.title = element_text(size = rel(2.3)),
axis.title = element_text(size = rel(2.3)),
axis.text = element_text(size = rel(2.3))) )
(p=p+theme(legend.position = c(0.8, .5),
legend.title = element_text(size = rel(2)) ,
legend.text = element_text(size = rel(2)) ) )
waitm=exp(coef(ss3)[6:11,1])
waitf=exp(coef(ss3)[12:17,1])
(MovF<-format(sum(waitm)/sum(waitf),digits=3))
pm=waitm/sum(waitm)
pf=waitf/sum(waitf)
(taum<-round(mids%*%pm,2))
(tauf<-round(mids%*%pf,2))
(p=p+annotate("text",x=25,y=10, hjust=0, label = paste("M/F =",MovF),size=9) )
(lb1=paste0("tau[m] == ",taum,"*~Yrs"))
(p=p+annotate("text",x=25,y=9, hjust=0, label = lb1,size=9,parse=T) )
(lb1=paste0("tau[f] == ",tauf,"*~Yrs"))
(p=p+annotate("text",x=25,y=8, hjust=0, label = lb1,size=9,parse=T) )
rdiscrete <- function(n, probs,values) {
cumprobs <- cumsum(probs)
singlenumber <- function() {
x <- runif(1)
N <- sum(x > cumprobs)
N
}
values[replicate(n, singlenumber())+1]
}
x=rdiscrete(1e5,pf,mids)
summary(as.factor(x))
y=rdiscrete(1e5,pm,mids)
summary(as.factor(y))
(delT=quantile(x-y,c(0.025,0.975)))
(lb1=paste0("Delta*tau == ",tauf-taum,"(",delT[1],", ",delT[2],")"))
windows(height=7,width=8,xpos=-100,ypos=-100)
(p=p+annotate("text",x=25,y=7, hjust=0, label = lb1,size=7,parse=T) )
ggsave(p,file="/users/radivot/downloads/sachs/IR2CML.wmf")
graphics.off()
windows(height=6,width=6,xpos=-100,ypos=-100)
k=0.025
Tp=22.1
Rp=1.73
Tf=-15:23
fR=function(Tf) exp(-k*(Tf-Tp))
R=fR(Tf)
par(mar=c(4.5,4.5,0,.5))
plot(Tf,R,type="l",lwd=2.5,cex.lab=1.8,cex.axis=1.8,
ylab="(male risk)/(female risk) M/F",
xlab="extra female latency time T in years",axes=F,font=2)
mtext(side=3,line=-4,"Continuum of SEER CML\n Sex Difference Interpretations",cex=1.5,font=2)
axis(1);axis(2)
points(x=c(0,Tp),y=c(Rp,1),pch=1,cex=3,lwd=3)
abline(h=1,v=0,lty=3)
fT=function(R) Tp-log(R)/k
Tx=3.86
Rx=1.26
points(x=c(fT(Rx),Tx),y=c(Rx,fR(Tx)),pch="+",cex=3)
x=seq(Tx,fT(Rx),0.1)
y=fR(x)
points(x,y,type="l",lwd=6)
rect(-1,1.13*Rp,23,1.26*Rp,lwd=2)
text(12,1.2*Rp,"interpretations by\n a single cause",cex=1.4,font=2,bty="o")
arrows(x0=0,y0=1.13*Rp,x1=0,y1=Rp+0.05,lwd=2,angle=20)
arrows(x0=Tp,y0=1.13*Rp,x1=Tp,y1=1.05,lwd=2,angle=20)
text(4,1.04*Rp,"higher\nmale\nrisk",cex=1.4,font=2)
text(10,0.96*Rp,"or",cex=1.4,font=2)
text(18,0.9*Rp,"shorter\nmale\nlatency",cex=1.4,font=2)
text(-9,1.28,
"interpretations\nconsistent with\ntime-since-\nexposure data\n(heavy line)",
cex=1.4,font=2)
arrows(x0=-2,y0=1.4,fT(1.4),y1=1.4,lwd=2,angle=20)
windows(height=7,width=8,xpos=-100,ypos=-100)
head(d)
d$Dose<-cut(d$sv,c(-1,.02,1,100),labels=c("Low","Moderate","High"))
d$agexc<-cut(d$agex,c(0,20,40,180),labels=c("10","30","50"))
d$Sex<-factor(d$s,labels=c("Male","Female"))
head(d)
library(plyr)
(d2<-ddply(subset(d,c==0), .(Dose,Sex,agexc), summarise,
PY=sum(py),cases=sum(cml),agex=weighted.mean(agex,py) ))
(d2=within(d2,{incid=1e5*cases/PY}))
library(ggplot2)
(p <- ggplot(d2,aes(x=agex,y=incid,shape=Dose,group=Dose))+geom_point(size=5) +geom_line()
+ labs(title="Hiroshima A-bomb Survivors",x="Age-at-exposure (PY-weighted)",
y=expression(paste("CML Cases per ",10^5," Person-Years")))
+ scale_y_log10(limits=c(.1,130)) +xlim(8,52) )
(p=p + facet_grid(. ~ Sex))
(p=p+theme(legend.position = c(0.67, .85),
legend.title = element_text(size = rel(2)) ,
legend.text = element_text(size = rel(1.7)) ) )
(p=p+theme(plot.title = element_text(size = rel(2.5)),
strip.text = element_text(size = rel(2)),
axis.title.y = element_text(size = rel(2.5)),
axis.title.x = element_text(size = rel(2.3)),
axis.text = element_text(size = rel(2.3))) )
dHM=subset(d,Sex=="Male"&c==0)
head(dHM)
summary(hm0<-mle2(cml~dpois(lambda=py*(exp(c10 + k*age)+sv*exp(f)) ),
parameters=list(f~-1 + tsxf),
start=list(c10=-12.4,k=0.025,f=-10),data=dHM ) )
summary(hm1<-mle2(cml~dpois(lambda=py*(exp(c10 + k*age)+
exp(-b*abs(agex-30)/28.85)*sv*exp(f)) ),
parameters=list(f~-1 + tsxf),
start=list(c10=-12.4,k=0.025,f=-10,b=0.5),data=dHM ) )
anova(hm0,hm1) |
GetTransactionEnabled <- function(reportsuite.ids) {
request.body <- c()
request.body$rsid_list <- reportsuite.ids
request.body$locale <- unbox(AdobeAnalytics$SC.Credentials$locale)
request.body$elementDataEncoding <- unbox("utf8")
response <- ApiRequest(body=toJSON(request.body),func.name="ReportSuite.GetTransactionEnabled")
if(length(response$transaction[[1]]) == 0) {
return(print("Transactions Not Defined For This Report Suite"))
}
return(response)
} |
if (Sys.info()['sysname'] != "Windows") {
set.seed(1234)
rmse <- function(theta, theta_star) { sqrt(sum((theta - theta_star)^2)/sum(theta_star^2)) }
nbNodes <- 40
nbBlocks <- 2
blockProp <- c(.5, .5)
covarParam <- c(-2,2)
dimLabels <- list(row = "rowLabel", col = "colLabel")
covar1 <- matrix(rnorm(nbNodes**2), nbNodes, nbNodes)
covar2 <- matrix(rnorm(nbNodes**2), nbNodes, nbNodes)
covarList_directed <- list(covar1 = covar1, covar2 = covar2)
covar1 <- covar1 + t(covar1)
covar2 <- covar2 + t(covar2)
covarList <- list(covar1 = covar1, covar2 = covar2)
test_that("SimpleSBM_fit 'Bernoulli' model, undirected, one covariate", {
means <- diag(.4, 2) + 0.05
connectParam <- list(mean = means)
mySampler <- SimpleSBM$new('bernoulli', nbNodes, FALSE, blockProp, connectParam, covarParam = covarParam[1], covarList = covarList[1])
mySampler$rMemberships(store = TRUE)
mySampler$rEdges(store = TRUE)
mySBM <- SimpleSBM_fit$new(mySampler$networkData, 'bernoulli', FALSE, covarList = covarList[1])
expect_error(SimpleSBM_fit$new(mySampler$networkData, 'bernouilli', FALSE, covarList = covarList[1]))
expect_error(SimpleSBM_fit$new(mySampler$networkData[1:20, 1:30], 'bernouilli', FALSE, covarList = covarList[1]))
expect_error(SimpleSBM_fit$new(mySampler$networkData, 'bernoulli', TRUE, covarList = covarList[1]))
expect_error(SimpleSBM_fit$new(mySampler$networkData, 'bernoulli', FALSE, covarList = covarList[[1]]))
expect_true(inherits(mySBM, "SBM"))
expect_true(inherits(mySBM, "SimpleSBM"))
expect_true(inherits(mySBM, "SimpleSBM_fit"))
expect_equal(mySBM$modelName, 'bernoulli')
expect_equal(unname(mySBM$nbNodes), nbNodes)
expect_equal(mySBM$dimLabels, c(node="nodeName"))
expect_equal(mySBM$nbDyads, nbNodes*(nbNodes - 1)/2)
expect_true(all(is.na(diag(mySBM$networkData))))
expect_true(isSymmetric(mySBM$networkData))
expect_true(!mySBM$directed)
expect_true(is.matrix(mySBM$connectParam$mean))
expect_true(all(dim(mySBM$covarEffect) == c(nbNodes, nbNodes)))
expect_equal(mySBM$nbCovariates, 1)
expect_equal(mySBM$covarList, covarList[1])
expect_equal(mySBM$covarParam, c(0))
expect_equal(coef(mySBM, 'connectivity'), mySBM$connectParam)
expect_equal(coef(mySBM, 'block') , mySBM$blockProp)
expect_equal(coef(mySBM, 'covariates') , mySBM$covarParam)
BM_out <- mySBM$optimize(estimOptions = list(verbosity = 0, fast = TRUE))
mySBM$setModel(2)
expect_equal(dim(mySBM$expectation), c(nbNodes, nbNodes))
expect_true(all(mySBM$expectation >= 0, na.rm = TRUE))
expect_true(all(mySBM$expectation <= 1, na.rm = TRUE))
expect_null(mySBM$connectParam$var)
expect_equal(mySBM$nbBlocks, nbBlocks)
expect_equal(dim(mySBM$probMemberships), c(nbNodes, nbBlocks))
expect_equal(sort(unique(mySBM$memberships)), 1:nbBlocks)
expect_equal(length(mySBM$memberships), nbNodes)
expect_equal(coef(mySBM, 'connectivity'), mySBM$connectParam)
expect_equal(coef(mySBM, 'block') , mySBM$blockProp)
expect_equal(coef(mySBM, 'covariates') , mySBM$covarParam)
expect_equal(mySBM$predict(), predict(mySBM))
expect_equal(predict(mySBM), fitted(mySBM))
expect_equal(predict(mySBM, covarList[1]), fitted(mySBM))
expect_error(predict(mySBM, covarList))
for (Q in mySBM$storedModels$indexModel) {
pred_bm <- BM_out$prediction(Q = Q)
mySBM$setModel(Q)
pred_sbm <- predict(mySBM)
expect_lt( rmse(pred_bm, pred_sbm), 1e-12)
}
})
test_that("SimpleSBM_fit 'Bernoulli' model, directed, one covariate", {
means <- matrix(c(0.1, 0.4, 0.6, 0.9), 2, 2)
connectParam <- list(mean = means)
mySampler <- SimpleSBM$new('bernoulli', nbNodes, TRUE, blockProp, connectParam, c(node = "nodeName"), covarParam[1], covarList_directed[1])
mySampler$rMemberships(store = TRUE)
mySampler$rEdges(store = TRUE)
mySBM <- SimpleSBM_fit$new(mySampler$networkData, 'bernoulli', TRUE, covarList = covarList_directed[1])
expect_error(SimpleSBM_fit$new(mySampler$networkData, 'bernouilli', TRUE, covarList = covarList_directed[1]))
expect_error(SimpleSBM_fit$new(mySampler$networkData, 'bernoulli', FALSE, covarList = covarList_directed[1]))
expect_error(SimpleSBM_fit$new(mySampler$networkData[1:20, 1:30], 'bernouilli', FALSE, covarList = covarList_directed[1]))
expect_true(inherits(mySBM, "SBM"))
expect_true(inherits(mySBM, "SimpleSBM"))
expect_true(inherits(mySBM, "SimpleSBM_fit"))
expect_equal(mySBM$modelName, 'bernoulli')
expect_equal(unname(mySBM$nbNodes), nbNodes)
expect_equal(mySBM$dimLabels, c(node="nodeName"))
expect_equal(mySBM$nbDyads, nbNodes*(nbNodes - 1))
expect_true(all(is.na(diag(mySBM$networkData))))
expect_true(!isSymmetric(mySBM$networkData))
expect_true(mySBM$directed)
expect_true(is.matrix(mySBM$connectParam$mean))
expect_true(all(dim(mySBM$covarEffect) == c(nbNodes, nbNodes)))
expect_equal(mySBM$nbCovariates, 1)
expect_equal(mySBM$covarList, covarList_directed[1])
expect_equal(mySBM$covarParam, c(0))
expect_equal(coef(mySBM, 'connectivity'), mySBM$connectParam)
expect_equal(coef(mySBM, 'block') , mySBM$blockProp)
expect_equal(coef(mySBM, 'covariates') , mySBM$covarParam)
BM_out <- mySBM$optimize(estimOptions = list(verbosity = 0, fast = TRUE))
mySBM$setModel(2)
expect_equal(dim(mySBM$expectation), c(nbNodes, nbNodes))
expect_true(all(mySBM$expectation >= 0, na.rm = TRUE))
expect_true(all(mySBM$expectation <= 1, na.rm = TRUE))
expect_null(mySBM$connectParam$var)
expect_equal(mySBM$nbBlocks, nbBlocks)
expect_equal(dim(mySBM$probMemberships), c(nbNodes, nbBlocks))
expect_equal(sort(unique(mySBM$memberships)), 1:nbBlocks)
expect_equal(length(mySBM$memberships), nbNodes)
expect_equal(coef(mySBM, 'connectivity'), mySBM$connectParam)
expect_equal(coef(mySBM, 'block') , mySBM$blockProp)
expect_equal(coef(mySBM, 'covariates') , mySBM$covarParam)
expect_equal(mySBM$predict(), predict(mySBM))
expect_equal(predict(mySBM), fitted(mySBM))
expect_equal(predict(mySBM, covarList[1]), fitted(mySBM))
for (Q in mySBM$storedModels$indexModel) {
pred_bm <- BM_out$prediction(Q = Q)
mySBM$setModel(Q)
pred_sbm <- predict(mySBM)
expect_lt( rmse(pred_bm, pred_sbm), 1e-12)
}
})
test_that("SimpleSBM_fit 'Poisson' model, undirected, two covariates", {
means <- diag(15, 2) + 5
connectParam <- list(mean = means)
mySampler <- SimpleSBM$new('poisson', nbNodes, FALSE, blockProp, connectParam, covarParam = covarParam[1], covarList = covarList[1])
mySampler$rMemberships(store = TRUE)
mySampler$rEdges(store = TRUE)
mySBM <- SimpleSBM_fit$new(mySampler$networkData, 'poisson', FALSE, covarList = covarList[1])
expect_error(SimpleSBM_fit$new(SamplerBernoulli$networkData, 'poison', FALSE, covarList = covarList[1]))
expect_error(SimpleSBM_fit$new(SamplerBernoulli$networkData[1:20, 1:30], 'poisson', FALSE, covarList = covarList[1]))
expect_error(SimpleSBM_fit$new(SamplerBernoulli$networkData, 'poisson', TRUE, covarList = covarList[1]))
expect_true(inherits(mySBM, "SBM"))
expect_true(inherits(mySBM, "SimpleSBM"))
expect_true(inherits(mySBM, "SimpleSBM_fit"))
expect_equal(mySBM$modelName, 'poisson')
expect_equal(unname(mySBM$nbNodes), nbNodes)
expect_equal(mySBM$dimLabels, c(node="nodeName"))
expect_equal(mySBM$nbDyads, nbNodes*(nbNodes - 1)/2)
expect_true(all(is.na(diag(mySBM$networkData))))
expect_true(isSymmetric(mySBM$networkData))
expect_true(!mySBM$directed)
expect_true(is.matrix(mySBM$connectParam$mean))
expect_true(all(dim(mySBM$covarEffect) == c(nbNodes, nbNodes)))
expect_equal(mySBM$nbCovariates, 1)
expect_equal(mySBM$covarList, covarList[1])
expect_equal(mySBM$covarParam, c(0))
expect_equal(coef(mySBM, 'connectivity'), mySBM$connectParam)
expect_equal(coef(mySBM, 'block') , mySBM$blockProp)
expect_equal(coef(mySBM, 'covariates') , mySBM$covarParam)
BM_out <- mySBM$optimize(estimOptions=list(verbosity = 0))
mySBM$setModel(2)
expect_equal(dim(mySBM$expectation), c(nbNodes, nbNodes))
expect_true(all(mySampler$expectation >= 0, na.rm = TRUE))
expect_null(mySBM$connectParam$var)
expect_equal(mySBM$nbBlocks, nbBlocks)
expect_equal(dim(mySBM$probMemberships), c(nbNodes, nbBlocks))
expect_equal(sort(unique(mySBM$memberships)), 1:nbBlocks)
expect_equal(length(mySBM$memberships), nbNodes)
expect_equal(coef(mySBM, 'connectivity'), mySBM$connectParam)
expect_equal(coef(mySBM, 'block') , mySBM$blockProp)
expect_equal(coef(mySBM, 'covariates') , mySBM$covarParam)
expect_equal(mySBM$predict(), predict(mySBM))
expect_equal(predict(mySBM), fitted(mySBM))
expect_equal(predict(mySBM, covarList[1]), fitted(mySBM))
for (Q in mySBM$storedModels$indexModel) {
pred_bm <- BM_out$prediction(Q = Q)
mySBM$setModel(Q)
pred_sbm <- predict(mySBM)
expect_lt( rmse(pred_bm, pred_sbm), 1e-12)
}
})
test_that("SimpleSBM_fit 'Poisson' model, directed, two covariates", {
means <- matrix(c(1, 4, 7, 9), 2, 2)
connectParam <- list(mean = means)
mySampler <- SimpleSBM$new('poisson', nbNodes, TRUE, blockProp, connectParam, covarParam = covarParam[1], covarList = covarList_directed[1])
mySampler$rMemberships(store = TRUE)
mySampler$rEdges(store = TRUE)
mySBM <- SimpleSBM_fit$new(mySampler$networkData, 'poisson', TRUE, covarList = covarList_directed[1])
expect_error(SimpleSBM_fit$new(SamplerBernoulli$networkData, 'poison', TRUE, covarList = covarList_directed[1]))
expect_error(SimpleSBM_fit$new(SamplerBernoulli$networkData[1:20, 1:30], 'poisson', FALSE, covarList = covarList_directed[1]))
expect_error(SimpleSBM_fit$new(SamplerBernoulli$networkData, 'poisson', FALSE, covarList = covarList_directed[1]))
expect_true(inherits(mySBM, "SBM"))
expect_true(inherits(mySBM, "SimpleSBM"))
expect_true(inherits(mySBM, "SimpleSBM_fit"))
expect_equal(mySBM$modelName, 'poisson')
expect_equal(unname(mySBM$nbNodes), nbNodes)
expect_equal(mySBM$dimLabels, c(node="nodeName"))
expect_equal(mySBM$nbDyads, nbNodes*(nbNodes - 1))
expect_true(all(is.na(diag(mySBM$networkData))))
expect_true(!isSymmetric(mySBM$networkData))
expect_true(mySBM$directed)
expect_true(is.matrix(mySBM$connectParam$mean))
expect_true(all(dim(mySBM$covarEffect) == c(nbNodes, nbNodes)))
expect_equal(mySBM$nbCovariates, 1)
expect_equal(mySBM$covarList, covarList_directed[1])
expect_equal(mySBM$covarParam, c(0))
expect_equal(coef(mySBM, 'connectivity'), mySBM$connectParam)
expect_equal(coef(mySBM, 'block') , mySBM$blockProp)
expect_equal(coef(mySBM, 'covariates') , mySBM$covarParam)
BM_out <- mySBM$optimize(estimOptions=list(verbosity = 0))
mySBM$setModel(2)
expect_equal(dim(mySBM$expectation), c(nbNodes, nbNodes))
expect_true(all(mySampler$expectation >= 0, na.rm = TRUE))
expect_null(mySBM$connectParam$var)
expect_equal(mySBM$nbBlocks, nbBlocks)
expect_equal(dim(mySBM$probMemberships), c(nbNodes, nbBlocks))
expect_equal(sort(unique(mySBM$memberships)), 1:nbBlocks)
expect_equal(length(mySBM$memberships), nbNodes)
expect_equal(coef(mySBM, 'connectivity'), mySBM$connectParam)
expect_equal(coef(mySBM, 'block') , mySBM$blockProp)
expect_equal(coef(mySBM, 'covariates') , mySBM$covarParam)
expect_equal(mySBM$predict(), predict(mySBM))
expect_equal(predict(mySBM), fitted(mySBM))
expect_equal(predict(mySBM, covarList[1]), fitted(mySBM))
for (Q in mySBM$storedModels$indexModel) {
pred_bm <- BM_out$prediction(Q = Q)
mySBM$setModel(Q)
pred_sbm <- predict(mySBM)
expect_lt( rmse(pred_bm, pred_sbm), 1e-12)
}
})
test_that("SimpleSBM_fit 'Gaussian' model, undirected, two covariates", {
means <- diag(15., 2) + 5
connectParam <- list(mean = means, var = 2)
mySampler <- SimpleSBM$new('gaussian', nbNodes, FALSE, blockProp, connectParam, covarParam = covarParam, covarList = covarList)
mySampler$rMemberships(store = TRUE)
mySampler$rEdges(store = TRUE)
mySBM <- SimpleSBM_fit$new(mySampler$networkData, 'gaussian', FALSE, covarList = covarList)
expect_error(SimpleSBM_fit$new(SamplerBernoulli$networkData, 'normal', FALSE, covarList = covarList))
expect_error(SimpleSBM_fit$new(SamplerBernoulli$networkData[1:20, 1:30], 'gaussian', FALSE, covarList = covarList))
expect_error(SimpleSBM_fit$new(SamplerBernoulli$networkData, 'gaussian', TRUE, covarList = covarList))
expect_true(inherits(mySBM, "SBM"))
expect_true(inherits(mySBM, "SimpleSBM"))
expect_true(inherits(mySBM, "SimpleSBM_fit"))
expect_equal(mySBM$modelName, 'gaussian')
expect_equal(unname(mySBM$nbNodes), nbNodes)
expect_equal(mySBM$dimLabels, c(node="nodeName"))
expect_equal(mySBM$nbDyads, nbNodes*(nbNodes - 1)/2)
expect_true(all(is.na(diag(mySBM$networkData))))
expect_true(isSymmetric(mySBM$networkData))
expect_true(!mySBM$directed)
expect_true(is.matrix(mySBM$connectParam$mean))
expect_true(all(dim(mySBM$covarEffect) == c(nbNodes, nbNodes)))
expect_equal(mySBM$nbCovariates, 2)
expect_equal(mySBM$covarList, covarList)
expect_equal(mySBM$covarParam, c(0,0))
expect_equal(coef(mySBM, 'connectivity'), mySBM$connectParam)
expect_equal(coef(mySBM, 'block') , mySBM$blockProp)
expect_equal(coef(mySBM, 'covariates') , mySBM$covarParam)
BM_out <- mySBM$optimize(estimOptions=list(verbosity = 0))
mySBM$setModel(2)
expect_equal(dim(mySBM$expectation), c(nbNodes, nbNodes))
expect_gt(mySBM$connectParam$var, 0)
expect_equal(mySBM$nbBlocks, nbBlocks)
expect_equal(dim(mySBM$probMemberships), c(nbNodes, nbBlocks))
expect_equal(sort(unique(mySBM$memberships)), 1:nbBlocks)
expect_equal(length(mySBM$memberships), nbNodes)
expect_lt(rmse(mySBM$connectParam$mean, means), 1e-1)
expect_lt(rmse(mySBM$covarParam, covarParam), 0.1)
expect_lt(1 - aricode::ARI(mySBM$memberships, mySampler$memberships), 1e-1)
expect_equal(coef(mySBM, 'connectivity'), mySBM$connectParam)
expect_equal(coef(mySBM, 'block') , mySBM$blockProp)
expect_equal(coef(mySBM, 'covariates') , mySBM$covarParam)
expect_equal(mySBM$predict(), predict(mySBM))
expect_equal(predict(mySBM), fitted(mySBM))
expect_equal(predict(mySBM, covarList), fitted(mySBM))
for (Q in mySBM$storedModels$indexModel) {
pred_bm <- BM_out$prediction(Q = Q)
mySBM$setModel(Q)
pred_sbm <- predict(mySBM)
expect_lt( rmse(pred_bm, pred_sbm), 1e-12)
}
})
test_that("SimpleSBM_fit 'Gaussian' model, undirected, two covariates", {
means <- matrix(c(1, 4, 7, 10),2,2)
connectParam <- list(mean = means, var = 2)
mySampler <- SimpleSBM$new('gaussian', nbNodes, TRUE, blockProp, connectParam, covarParam = covarParam, covarList = covarList_directed)
mySampler$rMemberships(store = TRUE)
mySampler$rEdges(store = TRUE)
mySBM <- SimpleSBM_fit$new(mySampler$networkData, 'gaussian', TRUE, covarList = covarList_directed)
expect_error(SimpleSBM_fit$new(SamplerBernoulli$networkData, 'normal', TRUE, covarList = covarList_directed))
expect_error(SimpleSBM_fit$new(SamplerBernoulli$networkData[1:20, 1:30], 'gaussian', TRUE, covarList = covarList_directed))
expect_error(SimpleSBM_fit$new(SamplerBernoulli$networkData, 'gaussian', FALSE, covarList = covarList_directed))
expect_true(inherits(mySBM, "SBM"))
expect_true(inherits(mySBM, "SimpleSBM"))
expect_true(inherits(mySBM, "SimpleSBM_fit"))
expect_equal(mySBM$modelName, 'gaussian')
expect_equal(unname(mySBM$nbNodes), nbNodes)
expect_equal(mySBM$dimLabels, c(node="nodeName"))
expect_equal(mySBM$nbDyads, nbNodes*(nbNodes - 1))
expect_true(all(is.na(diag(mySBM$networkData))))
expect_true(!isSymmetric(mySBM$networkData))
expect_true(mySBM$directed)
expect_true(is.matrix(mySBM$connectParam$mean))
expect_true(all(dim(mySBM$covarEffect) == c(nbNodes, nbNodes)))
expect_equal(mySBM$nbCovariates, 2)
expect_equal(mySBM$covarList, covarList_directed)
expect_equal(mySBM$covarParam, c(0,0))
expect_equal(coef(mySBM, 'connectivity'), mySBM$connectParam)
expect_equal(coef(mySBM, 'block') , mySBM$blockProp)
expect_equal(coef(mySBM, 'covariates') , mySBM$covarParam)
BM_out <- mySBM$optimize(estimOptions=list(verbosity = 0))
mySBM$setModel(2)
expect_equal(dim(mySBM$expectation), c(nbNodes, nbNodes))
expect_gt(mySBM$connectParam$var, 0)
expect_equal(mySBM$nbBlocks, nbBlocks)
expect_equal(dim(mySBM$probMemberships), c(nbNodes, nbBlocks))
expect_equal(sort(unique(mySBM$memberships)), 1:nbBlocks)
expect_equal(length(mySBM$memberships), nbNodes)
expect_lt(rmse(sort(mySBM$connectParam$mean), means), 1e-1)
expect_lt(rmse(mySBM$covarParam, covarParam), 0.1)
expect_lt(1 - aricode::ARI(mySBM$memberships, mySampler$memberships), 1e-1)
expect_equal(coef(mySBM, 'connectivity'), mySBM$connectParam)
expect_equal(coef(mySBM, 'block') , mySBM$blockProp)
expect_equal(coef(mySBM, 'covariates') , mySBM$covarParam)
expect_equal(mySBM$predict(), predict(mySBM))
expect_equal(predict(mySBM), fitted(mySBM))
expect_equal(predict(mySBM, covarList), fitted(mySBM))
for (Q in mySBM$storedModels$indexModel) {
pred_bm <- BM_out$prediction(Q = Q)
mySBM$setModel(Q)
pred_sbm <- predict(mySBM)
expect_lt( rmse(pred_bm, pred_sbm), 1e-12)
}
})
} |
doAmap <-
function(stas, doproj=TRUE)
{
proj = GEOmap::setPROJ(type=2, LAT0 =median(stas$lat) , LON0 = median(stas$lon) )
if(doproj)
{
XY = GEOmap::GLOB.XY(stas$lat, stas$lon, proj)
BEX = GEOmap::expandbound(range(XY$x), 0.1)
BEY = GEOmap::expandbound(range(XY$y), 0.1)
plot(BEX, BEY, type='n', xlab="km", ylab="km" )
points(XY, pch=25, bg=stas$col, cex=1.2)
text(XY, labels=stas$name, pos=3, xpd=TRUE, cex=1.1)
}
else
{
plot(stas$lon, stas$lat, pch=25, bg=stas$col, cex=1.2)
text(stas$lon, stas$lat, labels=stas$name, pos=3, xpd=TRUE, cex=1.1)
}
return(proj)
} |
"print.nestedn0" <-
function(x, ...)
{
cat("Nestedness index N0:", format(x$statistic), "\n")
invisible(x)
} |
"BivalvePBDB" |
UpdateTau.GL <-
function(survObj, priorPara, ini){
lambdaSq <- ini$lambdaSq
sigmaSq <- ini$sigmaSq
tauSq <- ini$tauSq
be.normSq <- ini$be.normSq
K <- priorPara$K
groupInd <- priorPara$groupInd
groupNo <- priorPara$groupNo
nu.ind<-NULL
nu=sqrt(lambdaSq * sigmaSq/be.normSq)
nu.ind <- which(nu == Inf)
if(length(nu.ind) > 0){nu[nu.ind] <- max(nu[-nu.ind]) + 10}
gam <- c()
for (j in 1:K){
repeat{
gam[j] <- rinvGauss(1, nu = nu[j], lambda = lambdaSq)
if (gam[j] > 0) break
}
tauSq[j] <- 1/gam[j]
}
return(tauSq)
} |
data{
n <- length(distance)
n.papers <- max(paper)
n.angles <- max(angle)
n.designs <- max(design)
}
model{
for (i in 1:n) {
distance[i] ~ dnorm(mu[i], tau)
mu[i] <- b0 + b3[design[i]]
}
for (j in 2:n.papers) {
b1[j] <- paper[j]
}
for (k in 2:n.angles) {
b2[k] <- angle[k]
}
for (m in 2:n.designs) {
b3[m] ~ dnorm(0, 1e-07)
}
b3[1] <- 0
tau ~ dgamma(0.001, 0.001)
b0 ~ dunif(0, 10000)
} |
draw_lines <- function(){
head <- dashboardHeader(disable=TRUE)
sidebar <- dashboardSidebar(disable=TRUE)
body <- dashboardBody(
fluidRow(
box(width=8, leafletOutput('map', height=800)),
box(width=4,
textInput('file_name', label='File Name', value='lines.rds'),
actionButton('make', 'Make'),
actionButton('clear', 'Clear'),
actionButton('save', 'Save'),
actionButton('load', 'Load')
)
)
)
ui <- dashboardPage(head, sidebar, body)
server <- function(input, output){
rv <- reactiveValues(
clicks = data.frame(lng = numeric(), lat = numeric()),
objects = list()
)
output$map <- {
renderLeaflet({
leaflet() %>%
addTiles() %>%
setView(lat=37.56579, lng=126.9386, zoom=5)
})
}
observeEvent(input$map_click, {
lastest.click <-
data.frame(
lng = input$map_click$lng,
lat = input$map_click$lat
)
rv$clicks <-
rbind(rv$clicks, lastest.click)
leafletProxy('map') %>%
addCircles(data=rv$clicks, lng=~lng, lat=~lat, radius=2, color='black', opacity=1, layerId='circles') %>%
addPolylines(data=rv$clicks, lng=~lng, lat=~lat, weight=2, dashArray=3, color='black', opacity=1, layerId='lines')
})
observeEvent(input$make, {
if(nrow(rv$clicks) > 0){
new.line <- rv$clicks %>% as.matrix %>% st_linestring
rv$objects[[length(rv$objects) + 1]] <- new.line
rv$clicks <- data.frame(lng = numeric(), lat = numeric())
leafletProxy('map') %>%
removeShape('circles') %>%
removeShape('lines') %>%
addPolylines(data=new.line %>% st_sfc, weight=2, color='black', fillColor='black')
}
})
observeEvent(input$clear, {
rv$clicks <- data.frame(lng = numeric(), lat = numeric())
rv$objects <- list()
leafletProxy('map') %>% clearShapes()
})
observeEvent(input$save, {
base_crs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
rv$objects %>%
st_sfc(crs=base_crs) %>%
saveRDS(file=input$file_name)
save.file.message <-
paste('lines are saved at: ', getwd(), '/', input$file_name, sep='')
print(save.file.message)
})
observeEvent(input$load, {
rv$objects <- readRDS(input$file_name) %>% st_sfc
rv$clicks <- data.frame(lng = numeric(), lat = numeric())
leafletProxy('map') %>%
clearShapes() %>%
addPolylines(data=rv$objects %>% st_sfc, weight=2, color='black', fillColor='black')
})
}
shinyApp(ui, server)
} |
globalVariables(c("..count..","..density..","ind", "values",
"Success Probability", "Expected Data Transmissions",
"Expected ACK Transmissions", "Expected Total Transmissions",
"Expected Data Receptions", "Expected ACK Receptions",
"Expected Total Receptions"))
ETE <- function(p1,p2,L,N)
{
if(p1 >= 1 | p1 <= 0) stop("p1 must be a real number in (0,1)")
if(p2 >= 1 | p2 <= 0) stop("p2 must be a real number in (0,1)")
if(L != Inf && (L%%1!=0 | L<0)) stop("L must be a positive integer")
if(N%%1!=0 | N<1) stop("N must be a positive integer")
cat(" ","\n")
cat("
cat("END TO END - THEORETICAL RESULTS","\n")
cat("
cat(" ","\n")
cat(paste("Data success probability p1 = ",p1),"\n")
cat(paste("ACK success probability p2 = ",p2),"\n")
cat(paste("Maximum number of transmissions L = ",L),"\n")
cat(paste("Number of Hops N = ",N),"\n")
cat(" ","\n")
pp = p1*p2
if(L==Inf)
{
ETData = ((1 - p1^N)/(1-p1)) * ((1)/(p1*p2)^N)
ETACK = ((p1^N)*((1 - p2^N)/(1-p2))) * ((1)/(p1*p2)^N)
ETS = ETData + ETACK
REC_ETData = p1*((1 - p1^N)/(1-p1)) * ((1)/(p1*p2)^N)
REC_ETACK = p2 * ((p1^N)*((1 - p2^N)/(1-p2))) * ((1)/(p1*p2)^N)
REC_ETS = REC_ETData + REC_ETACK
}else
{
if((p1*p2)<0.05)
{
ETData = L/(1-p1)
ETACK = 0
ETS = ETData + ETACK
REC_ETData = (p1*L)/(1-p1)
REC_ETACK = 0
REC_ETS = (p1*L)/(1-p1)
}else{
ETData = ((1 - p1^N)/(1-p1)) * ((1 - (1-(p1*p2)^N)^L)/(p1*p2)^N)
ETACK = ((p1^N)*((1 - p2^N)/(1-p2))) * ((1 - (1-(p1*p2)^N)^L)/(p1*p2)^N)
ETS = ETData + ETACK
REC_ETData = p1*((1 - p1^N)/(1-p1)) * ((1 - (1-(p1*p2)^N)^L)/(p1*p2)^N)
REC_ETACK = p2 * ((p1^N)*((1 - p2^N)/(1-p2))) * ((1 - (1-(p1*p2)^N)^L)/(p1*p2)^N)
REC_ETS = REC_ETData + REC_ETACK
}
}
PrS = 1-(1-p1^N)^L
res = round(matrix(data = c(c(PrS),c(ETData),c(ETACK),c(ETS),c(REC_ETData),c(REC_ETACK),c(REC_ETS)),nrow = 7,ncol = 1,byrow = T),4)
rownames(res)=c("Success Probability",
"Expected Data Transmissions",
"Expected ACK Transmissions",
"Expected Total Transmissions",
"Expected Data Receptions",
"Expected ACK Receptions","Expected Total Receptions")
colnames(res)= c("Total")
return(res)
}
MCETE = function(p1,p2,L,N,M=5000)
{
if(p1 >= 1 | p1 <= 0) stop("p1 must be a real number in (0,1)")
if(p2 >= 1 | p2 <= 0) stop("p2 must be a real number in (0,1)")
if(L != Inf && (L%%1!=0 | L<0)) stop("L must be a positive integer")
if(N%%1!=0 | N<1) stop("N must be a positive integer")
if(M%%1!=0 | M<1) stop("N must be a positive integer")
cat(" ","\n")
cat("
cat("END TO END - MONTE CARLO SIMULATION RESULTS","\n")
cat("
cat(" ","\n")
cat(paste("Data success probability p1 = ",p1),"\n")
cat(paste("ACK success probability p2 = ",p2),"\n")
cat(paste("Maximum number of transmissions L = ",L),"\n")
cat(paste("Number of Hops N = ",N),"\n")
cat(paste("Monte Carlo Simulations M = ",M),"\n")
cat(" ","\n")
prog2 = function(p1,p2,L,N)
{
pos = 1
trans = 0
ack = 0
maxpos = 1
ok = FALSE
okACK = FALSE
arr = 0
abj = 0
failUP = 0
failACK = 0
failT = 0
chegou = 0
while(failT < L && okACK == FALSE)
{
back = FALSE
while(pos<=N && failT < L)
{
maxpos = max(maxpos,pos)
u1 = runif(1)
trans = trans +1
if(u1<p1){arr = arr + 1;pos = pos + 1}else{pos = 1;failUP = failUP + 1;failT = failT + 1}
}
if(pos == N+1)
{
maxpos = N+1
posACK = pos
ok = TRUE
chegou=1
while(posACK >1 && back == FALSE)
{
u2 = runif(1)
ack = ack +1
if(u2<p2){abj = abj + 1;posACK = posACK - 1}else{back = TRUE;pos = 1;failACK = failACK + 1;failT = failT + 1}
if(posACK == 1){okACK = TRUE}
}
}
}
return(list(pos=pos,tDATA = trans,tACK = ack,
trans = trans+ack,RDATA = arr,
RACK = abj,Rtrans = arr+abj,ok=chegou))
cat(" ","\n")
}
resul = matrix(data = NA,nrow = M,ncol = 8)
pb <- txtProgressBar(min = 0, max = M, style = 3)
for(k in 1:M)
{
run = prog2(p1,p2,L,N)
resul[k,1]=run$pos
resul[k,2]=run$tDATA
resul[k,3]=run$tACK
resul[k,4]=run$trans
resul[k,5]=run$RDATA
resul[k,6]=run$RACK
resul[k,7]=run$Rtrans
resul[k,8]=run$ok
setTxtProgressBar(pb, k)
}
close(pb)
success = sum(resul[,8])/M
tarr = mean(resul[,2])
tabj = mean(resul[,3])
tt = tarr + tabj
rarr = mean(resul[,5])
rabj = mean(resul[,6])
rt = rarr + rabj
table = round(rbind(success,tarr,tabj,tt,rarr,rabj,rt),4)
rownames(table)=c("MC Success Probability","MC Mean Data Transmissions","MC Mean ACK Transmissions","MC Mean Total Transmissions","MC Mean Data Receptions","MC Mean ACK Receptions","MC Mean Total Receptions")
colnames(table)= c("Total")
return(table)
cat(" ","\n")
}
ETE0 = function (p1, p2, L, N){
pp = p1 * p2
if (L == Inf) {
ETData = ((1 - p1^N)/(1 - p1)) * ((1)/(p1 * p2)^N)
ETACK = ((p1^N) * ((1 - p2^N)/(1 - p2))) * ((1)/(p1 *
p2)^N)
ETS = ETData + ETACK
REC_ETData = p1 * ((1 - p1^N)/(1 - p1)) * ((1)/(p1 *
p2)^N)
REC_ETACK = p2 * ((p1^N) * ((1 - p2^N)/(1 - p2))) * ((1)/(p1 *
p2)^N)
REC_ETS = REC_ETData + REC_ETACK
}else {
if ((p1 * p2) < 0.05) {
ETData = L/(1 - p1)
ETACK = 0
ETS = ETData + ETACK
REC_ETData = (p1 * L)/(1 - p1)
REC_ETACK = 0
REC_ETS = (p1 * L)/(1 - p1)
}else {
ETData = ((1 - p1^N)/(1 - p1)) * ((1 - (1 - (p1 *
p2)^N)^L)/(p1 * p2)^N)
ETACK = ((p1^N) * ((1 - p2^N)/(1 - p2))) * ((1 -
(1 - (p1 * p2)^N)^L)/(p1 * p2)^N)
ETS = ETData + ETACK
REC_ETData = p1 * ((1 - p1^N)/(1 - p1)) * ((1 - (1 -
(p1 * p2)^N)^L)/(p1 * p2)^N)
REC_ETACK = p2 * ((p1^N) * ((1 - p2^N)/(1 - p2))) *
((1 - (1 - (p1 * p2)^N)^L)/(p1 * p2)^N)
REC_ETS = REC_ETData + REC_ETACK
}
}
PrS = 1 - (1 - p1^N)^L
res = round(matrix(data = c(c(PrS), c(ETData), c(ETACK),
c(ETS), c(REC_ETData), c(REC_ETACK), c(REC_ETS)), nrow = 7,
ncol = 1, byrow = T), 4)
return(res)
}
stochastic_ETE = function(dist1,p11,p12,dist2,p21,p22,L,N,M=10^5,printout=TRUE,plotspdf=TRUE){
if(L != Inf && (L%%1!=0 | L<0)) stop("L must be a positive integer")
if(N%%1!=0 | N<1) stop("N must be a positive integer")
if(dist1 == "uniform"){
p1 = runif(M,p11,p12)
}else{
if(dist1 == "beta"){
p1 = rbeta(M,p11,p12)
}else{
stop("p1 distribution must be either 'uniform' or 'beta'.")
}
}
if(dist2 == "uniform"){
p2 = runif(M,p21,p22)
}else{
if(dist2 == "beta"){
p2 = rbeta(M,p21,p22)
}else{
stop("p1 distribution must be either 'uniform' or 'beta'.")
}
}
out = apply(X = cbind(p1,p2),MARGIN = 1, function(x) ETE0(x[1], x[2], L, N))
outsum = matrix(apply(out,1,mean),7,1)
rownames(outsum) = c("Success Probability", "Expected Data Transmissions",
"Expected ACK Transmissions", "Expected Total Transmissions",
"Expected Data Receptions", "Expected ACK Receptions",
"Expected Total Receptions")
colnames(outsum) = c("Total")
df = data.frame(p1,p2,t(out))
colnames(df) = c("p1","p2",rownames(outsum))
stats = as.data.frame(t(stat.desc(df))[,-c(1:3)])
p1 = ggplot(df,aes(p1)) +
geom_histogram(aes(y=..density.., fill = "p1"),alpha = 0.4,color="gray40",breaks = seq(min(p1),max(p1),length.out = round(diff(range(p1))/0.0625)+1)) +
geom_histogram(aes(x = p2, y = ..density..,fill = "p2"),alpha = 0.4,color="gray40",breaks = seq(min(p2),max(p2),length.out = round(diff(range(p2))/0.0625)+1))+
theme(axis.title.x=element_blank(),
axis.ticks.x=element_blank()) +
labs(fill = "")+
xlab("probability") +
ylab("density") +
ggtitle("Data and ACK Success Probabilities") +
xlim(0,1) +
theme_classic()
p2 = ggplot(df,aes(x=`Success Probability`)) +
geom_histogram(aes(y = (..count..)/sum(..count..)),alpha = 0.2,color="gray40",fill = 1,
breaks = seq(min(df$`Success Probability`),max(df$`Success Probability`),length.out = 17)) +
theme(axis.title.x=element_blank(),
axis.ticks.x=element_blank())+
geom_vline(xintercept = outsum[1],color="gray40",lwd=1.2) +
ggtitle(paste("Success Probability (mean = ",round(outsum[1],3),")",sep = "")) +
ylab("relative frequency")+ theme_classic()
p3 = ggplot(df,aes(x=`Expected Data Transmissions`)) +
geom_histogram(aes(y = (..count..)/sum(..count..)),alpha = 0.2,color="gray40",fill = 2,
breaks = seq(min(df$`Expected Data Transmissions`),max(df$`Expected Data Transmissions`),length.out = 17)) +
theme(axis.title.x=element_blank(),
axis.ticks.x=element_blank()) +
geom_vline(xintercept = outsum[2],color="gray40",lwd=1.2) +
ggtitle(paste("Expected Data Transmissions (mean = ",round(outsum[2],3),")",sep = "")) +
ylab("relative frequency") +
theme_classic()
p4 = ggplot(df,aes(x=`Expected ACK Transmissions`)) +
geom_histogram(aes(y = (..count..)/sum(..count..)),alpha = 0.2,color="gray40",fill = 3,
breaks = seq(min(df$`Expected ACK Transmissions`),max(df$`Expected ACK Transmissions`),length.out = 17)) +
theme(axis.title.x=element_blank(),
axis.ticks.x=element_blank()) +
geom_vline(xintercept = outsum[3],color="gray40",lwd=1.2) +
ggtitle(paste("Expected ACK Transmissions (mean = ",round(outsum[3],3),")",sep = "")) +
ylab("relative frequency") +
theme_classic()
p5 = ggplot(df,aes(x=`Expected Total Transmissions`)) +
geom_histogram(aes(y = (..count..)/sum(..count..)),alpha = 0.2,color="gray40",fill = 4,
breaks = seq(min(df$`Expected Total Transmissions`),max(df$`Expected Total Transmissions`),length.out = 17)) +
theme(axis.title.x=element_blank(),
axis.ticks.x=element_blank()) +
geom_vline(xintercept = outsum[4],color="gray40",lwd=1.2) +
ggtitle(paste("Expected Total Transmissions (mean = ",round(outsum[4],3),")",sep = "")) +
ylab("relative frequency") +
theme_classic()
p6 = ggplot(df,aes(x=`Expected Data Receptions`)) +
geom_histogram(aes(y = (..count..)/sum(..count..)),alpha = 0.2,color="gray40",fill = 5,
breaks = seq(min(df$`Expected Data Receptions`),max(df$`Expected Data Receptions`),length.out = 17)) +
theme(axis.title.x=element_blank(),
axis.ticks.x=element_blank()) +
geom_vline(xintercept = outsum[5],color="gray40",lwd=1.2) +
ggtitle(paste("Expected Data Receptions (mean = ",round(outsum[5],3),")",sep = "")) +
ylab("relative frequency") +
theme_classic()
p7 = ggplot(df,aes(x=`Expected ACK Receptions`)) +
geom_histogram(aes(y = (..count..)/sum(..count..)),alpha = 0.2,color="gray40",fill = 6,
breaks = seq(min(df$`Expected ACK Receptions`),max(df$`Expected ACK Receptions`),length.out = 17)) +
theme(axis.title.x=element_blank(),
axis.ticks.x=element_blank()) +
geom_vline(xintercept = outsum[6],color="gray40",lwd=1.2) +
ggtitle(paste("Expected ACK Receptions (mean = ",round(outsum[6],3),")",sep = "")) +
ylab("relative frequency") +
theme_classic()
p8 = ggplot(df,aes(x=`Expected Total Receptions`)) +
geom_histogram(aes(y = (..count..)/sum(..count..)),alpha = 0.2,color="gray40",fill = 7,
breaks = seq(min(df$`Expected Total Receptions`),max(df$`Expected Total Receptions`),length.out = 17)) +
theme(axis.title.x=element_blank(),
axis.ticks.x=element_blank()) +
geom_vline(xintercept = outsum[7],color="gray40",lwd=1.2) +
ggtitle(paste("Expected Total Receptions (mean = ",round(outsum[7],3),")",sep = "")) +
ylab("relative frequency") +
theme_classic()
df2 = stack(df[,c(4:9)])
p9 = ggplot(df2, aes(x = ind, y = values)) +
geom_boxplot(fill = rev(2:7),alpha = 0.2,color="gray40") +
coord_flip() +
xlab("") +
scale_x_discrete(limits = rev(levels(df2$ind))) +
theme_classic()
if(isTRUE(printout)){
cat(paste("Monte Carlo simulations M = ", M), "\n")
cat(paste("Maximum number of transmissions L = ", L), "\n")
cat(paste("Number of Hops N = ", N), "\n")
print(stats)
print(p1)
print(p2)
print(p3)
print(p4)
print(p5)
print(p6)
print(p7)
print(p8)
print(p9)
}
if(isTRUE(plotspdf)){
plotsPath = paste("ETE",format(Sys.time(),"%d%m%y_%H%M%S"),".pdf",sep="")
pdf(file=plotsPath,width = 8.27,height = 5.83)
print(p1)
print(p2)
print(p3)
print(p4)
print(p5)
print(p6)
print(p7)
print(p8)
print(p9)
dev.off()
print(paste("Plots file ",plotsPath," saved in working directory ",getwd(),".",sep = ""))
}
return(list(data=df,stats = stats))
} |
qgis_sanitize_arguments <- function(algorithm, ..., .algorithm_arguments = qgis_arguments(algorithm),
.use_json_input = FALSE) {
dots <- rlang::list2(...)
if (length(dots) > 0 && !rlang::is_named(dots)) {
abort("All ... arguments to `qgis_sanitize_arguments()` must be named.")
}
arg_meta <- .algorithm_arguments
dot_names <- names(dots)
duplicated_dot_names <- unique(dot_names[duplicated(dot_names)])
regular_dot_names <- setdiff(dot_names, duplicated_dot_names)
user_args <- vector("list", length(unique(dot_names)))
names(user_args) <- unique(dot_names)
user_args[regular_dot_names] <- dots[regular_dot_names]
for (arg_name in duplicated_dot_names) {
items <- unname(dots[dot_names == arg_name])
user_args[[arg_name]] <- qgis_list_input(!!! items)
}
unknown_args <- setdiff(names(dots), c("PROJECT_PATH", "ELLIPSOID", arg_meta$name))
if (length(unknown_args) > 0){
for (arg_name in unknown_args) {
message(glue("Ignoring unknown input '{ arg_name }'"))
}
}
special_args <- user_args[c("PROJECT_PATH", "ELLIPSOID")]
special_args <- special_args[!sapply(special_args, is.null)]
args <- rep(list(qgis_default_value()), nrow(arg_meta))
names(args) <- arg_meta$name
args[intersect(names(args), names(user_args))] <- user_args[intersect(names(args), names(user_args))]
args <- c(args, special_args)
arg_spec <- Map(
qgis_argument_spec_by_name,
rep_len(list(algorithm), length(args)),
names(args),
rep_len(list(arg_meta), length(args))
)
names(arg_spec) <- names(args)
args_sanitized <- vector("list", length(args))
names(args_sanitized) <- names(args)
all_args_sanitized <- FALSE
on.exit(if (!all_args_sanitized) qgis_clean_arguments(args_sanitized))
for (name in names(args)) {
args_sanitized[[name]] <-
as_qgis_argument(args[[name]], arg_spec[[name]], use_json_input = .use_json_input)
}
all_args_sanitized <- TRUE
is_default_value <- vapply(args_sanitized, is_qgis_default_value, logical(1))
args_sanitized <- args_sanitized[!is_default_value]
args_sanitized
}
qgis_serialize_arguments <- function(arguments, use_json_input = FALSE) {
if (use_json_input) {
unclass_recursive <- function(x) {
is_list <- vapply(x, is.list, logical(1))
x[is_list] <- lapply(x[is_list], unclass_recursive)
lapply(x, unclass)
}
jsonlite::toJSON(list(inputs = unclass_recursive(arguments)), auto_unbox = TRUE)
} else {
args_dict <- vapply(arguments, inherits, logical(1), "qgis_dict_input")
if (any(args_dict)) {
labels <- names(arguments)[args_dict]
abort("`qgis_run_algorithm()` can't generate command-line arguments from `qgis_dict_input()`")
}
args_flat <- unlist(arguments)
arg_name_n <- vapply(arguments, length, integer(1))
names(args_flat) <- unlist(Map(rep, names(arguments), arg_name_n))
if (length(args_flat) > 0) {
paste0("--", names(args_flat), "=", vapply(args_flat, as.character, character(1)))
} else {
character(0)
}
}
}
qgis_clean_arguments <- function(arguments) {
lapply(arguments, qgis_clean_argument)
invisible(NULL)
}
as_qgis_argument <- function(x, spec = qgis_argument_spec(), use_json_input = FALSE) {
UseMethod("as_qgis_argument")
}
qgis_default_value <- function() {
structure(list(), class = "qgis_default_value")
}
is_qgis_default_value <- function(x) {
inherits(x, "qgis_default_value")
}
as_qgis_argument.default <- function(x, spec = qgis_argument_spec(), use_json_input = FALSE) {
abort(
glue(
paste0(
"Don't know how to convert object of type ",
"'{ paste(class(x), collapse = \" / \") }' ",
"to QGIS type '{ spec$qgis_type }'"
)
)
)
}
as_qgis_argument.list <- function(x, spec = qgis_argument_spec(), use_json_input = FALSE) {
if (use_json_input) {
return(x)
}
NextMethod()
}
as_qgis_argument.qgis_default_value <- function(x, spec = qgis_argument_spec(),
use_json_input = FALSE) {
if (isTRUE(spec$qgis_type %in% c("sink", "vectorDestination"))) {
message(glue("Using `{ spec$name } = qgis_tmp_vector()`"))
qgis_tmp_vector()
} else if (isTRUE(spec$qgis_type == "rasterDestination")) {
message(glue("Using `{ spec$name } = qgis_tmp_raster()`"))
qgis_tmp_raster()
} else if (isTRUE(spec$qgis_type == "folderDestination")) {
message(glue("Using `{ spec$name } = qgis_tmp_folder()`"))
qgis_tmp_folder()
} else if (isTRUE(spec$qgis_type == "fileDestination")) {
message(glue("Using `{ spec$name } = qgis_tmp_file(\"\")`"))
qgis_tmp_file("")
} else if (isTRUE(spec$qgis_type == "enum") && length(spec$available_values) > 0) {
default_enum_value <- rlang::as_label(spec$available_values[1])
message(glue("Using `{ spec$name } = { default_enum_value }`"))
if (use_json_input) 0 else "0"
} else {
message(glue("Argument `{ spec$name }` is unspecified (using QGIS default value)."))
qgis_default_value()
}
}
as_qgis_argument.NULL <- function(x, spec = qgis_argument_spec(),
use_json_input = FALSE) {
qgis_default_value()
}
as_qgis_argument.character <- function(x, spec = qgis_argument_spec(),
use_json_input = FALSE) {
result <- switch(
as.character(spec$qgis_type),
field = if (use_json_input) x else paste0(x, collapse = ";"),
enum = {
x_int <- match(x, spec$available_values)
invalid_values <- x[is.na(x_int)]
if (length(invalid_values) > 0) {
abort(
paste0(
glue("All values for input '{ spec$name }' must be one of the following:\n\n"),
glue::glue_collapse(
paste0('"', spec$available_values, '"'),
", ", last = " or "
)
)
)
}
x_int - 1
},
x
)
if (use_json_input) result else paste(result, collapse = ",")
}
as_qgis_argument.logical <- function(x, spec = qgis_argument_spec(),
use_json_input = FALSE) {
if (use_json_input) x else paste0(x, collapse = ",")
}
as_qgis_argument.numeric <- function(x, spec = qgis_argument_spec(),
use_json_input = FALSE) {
if (use_json_input) x else paste0(x, collapse = ",")
}
qgis_clean_argument <- function(value) {
UseMethod("qgis_clean_argument")
}
qgis_clean_argument.default <- function(value) {
}
qgis_clean_argument.qgis_tempfile_arg <- function(value) {
unlink(value)
}
qgis_argument_spec <- function(algorithm = NA_character_, name = NA_character_,
description = NA_character_, qgis_type = NA_character_,
available_values = character(0), acceptable_values = character(0)) {
list(
algorithm = algorithm,
name = name,
description = description,
qgis_type = qgis_type,
available_values = available_values,
acceptable_values = acceptable_values
)
}
qgis_argument_spec_by_name <- function(algorithm, name,
.algorithm_arguments = qgis_arguments(algorithm)) {
if (isTRUE(name %in% c("ELLIPSOID", "PROJECT_PATH"))) {
return(qgis_argument_spec(algorithm, name, name))
}
position <- match(name, .algorithm_arguments$name)
if (is.na(position)) {
abort(
glue(
paste0(
"'{ name }' is not an argument for algorithm '{ algorithm }'.",
"\nSee `qgis_show_help(\"{ algorithm }\")` for a list of supported arguments."
)
)
)
}
c(list(algorithm = algorithm), lapply(.algorithm_arguments, "[[", position))
}
qgis_list_input <- function(...) {
dots <- rlang::list2(...)
if (length(dots) > 0 && rlang::is_named(dots)) {
abort("All ... arguments to `qgis_list_input()` must be unnamed.")
}
structure(dots, class = "qgis_list_input")
}
qgis_dict_input <- function(...) {
dots <- rlang::list2(...)
if (length(dots) > 0 && !rlang::is_dictionaryish(dots)) {
abort("All ... arguments to `qgis_dict_input()` must have unique names.")
}
structure(dots, class = "qgis_dict_input")
}
as_qgis_argument.qgis_list_input <- function(x, spec = qgis_argument_spec(),
use_json_input = FALSE) {
qgis_list_input(!!! lapply(x, as_qgis_argument, spec = spec, use_json_input = use_json_input))
}
as_qgis_argument.qgis_dict_input <- function(x, spec = qgis_argument_spec(),
use_json_input = FALSE) {
qgis_dict_input(!!! lapply(x, as_qgis_argument, spec = spec, use_json_input = use_json_input))
}
qgis_clean_argument.qgis_list_input <- function(value) {
lapply(value, qgis_clean_argument)
}
qgis_clean_argument.qgis_dict_input <- function(value) {
lapply(value, qgis_clean_argument)
} |
rm(list=ls())
setwd("C:/Users/Tom/Documents/Kaggle/Santander")
library(data.table)
library(bit64)
library(xgboost)
library(stringr)
submissionDate <- "29-11-2016"
loadFile <- "xgboost weighted posFlanks 5, linear increase jun15 times6 back 13-0 no zeroing, exponential normalisation joint"
submissionFile <- "xgboost weighted posFlanks 5, less weight jun15 cno_fin linear increase jun15 times6 back 13-0 no zeroing, exponential normalisation joint"
targetDate <- "12-11-2016"
trainModelsFolder <- "trainTrainAll"
trainAll <- grepl("TrainAll", trainModelsFolder)
testFeaturesFolder <- "testOld"
loadPredictions <- FALSE
loadBaseModelPredictions <- TRUE
savePredictions <- TRUE
saveBaseModelPredictions <- TRUE
savePredictionsBeforeNormalisation <- TRUE
normalizeProdProbs <- TRUE
normalizeMode <- c("additive", "linear", "exponential")[3]
additiveNormalizeProds <- NULL
fractionPosFlankUsers <- 0.035
expectedCountPerPosFlank <- 1.25
marginalNormalisation <- c("linear", "exponential")[2]
monthsBackModels <- 0:13
monthsBackWeightDates <- rev(as.Date(paste(c(rep(2015, 9), rep(2016, 5)),
str_pad(c(4:12, 1:5), 2, pad='0'),
28, sep="-")))
monthsBackModelsWeights <- rev(c(1.2, 1.3, 13, 0.1*(15:25)))
weightSum <- sum(monthsBackModelsWeights)
monthsBackLags <- 16:3
nominaNomPensSoftAveraging <- FALSE
predictSubset <- FALSE
nbLags <- length(monthsBackModelsWeights)
if(nbLags != length(monthsBackModels) ||
nbLags != length(monthsBackLags) ||
nbLags != length(monthsBackWeightDates)) browser()
predictionsFolder <- "Predictions"
ccoNoPurchase <- FALSE
zeroTargets <- NULL
source("Common/exponentialNormaliser.R")
monthProductWeightOverride <- NULL
monthProductWeightOverride <-
rbind(monthProductWeightOverride, data.frame(product = "ind_cco_fin_ult1",
month = as.Date(c("2015-12-28"
)),
weight = 13)
)
monthProductWeightOverride <-
rbind(monthProductWeightOverride, data.frame(product = "ind_cco_fin_ult1",
month = as.Date(c("2015-04-28",
"2015-05-28",
"2015-07-28",
"2015-08-28",
"2015-09-28",
"2015-10-28",
"2015-11-28",
"2016-01-28",
"2016-02-28",
"2016-03-28",
"2016-04-28",
"2016-05-28"
)),
weight = 0)
)
predictionsPath <- file.path(getwd(), "Submission", submissionDate,
predictionsFolder)
dir.create(predictionsPath, showWarnings = FALSE)
if(saveBaseModelPredictions && !loadBaseModelPredictions){
baseModelPredictionsPath <- file.path(predictionsPath, submissionFile)
dir.create(baseModelPredictionsPath, showWarnings = FALSE)
} else{
if(loadBaseModelPredictions){
baseModelPredictionsPath <- file.path(predictionsPath, loadFile)
}
}
if(loadPredictions){
rawPredictionsPath <- file.path(predictionsPath,
paste0("prevNorm", loadFile, ".rds"))
} else{
rawPredictionsPath <- file.path(predictionsPath,
paste0("prevNorm", submissionFile, ".rds"))
}
posFlankClientsFn <- file.path(getwd(), "Feature engineering", targetDate,
"positive flank clients.rds")
posFlankClients <- readRDS(posFlankClientsFn)
modelsBasePath <- file.path(getwd(), "First level learners", targetDate,
trainModelsFolder)
modelGroups <- list.dirs(modelsBasePath)[-1]
nbModelGroups <- length(modelGroups)
baseModelInfo <- NULL
baseModels <- list()
for(i in 1:nbModelGroups){
modelGroup <- modelGroups[i]
slashPositions <- gregexpr("\\/", modelGroup)[[1]]
modelGroupExtension <- substring(modelGroup,
1 + slashPositions[length(slashPositions)])
modelGroupFiles <- list.files(modelGroup)
nbModels <- length(modelGroupFiles)
monthsBack <- as.numeric(substring(gsub("Lag.*$", "", modelGroupExtension),
5))
lag <- as.numeric(gsub("^.*Lag", "", modelGroupExtension))
relativeWeightOrig <- monthsBackModelsWeights[match(monthsBack,
monthsBackModels)]
weightDate <- monthsBackWeightDates[match(monthsBack, monthsBackModels)]
for(j in 1:nbModels){
modelInfo <- readRDS(file.path(modelGroup, modelGroupFiles[j]))
targetProduct <- modelInfo$targetVar
overrideId <- which(monthProductWeightOverride$product == targetProduct &
monthProductWeightOverride$month == weightDate)
if(length(overrideId)>0){
relativeWeight <- monthProductWeightOverride$weight[overrideId]
} else{
relativeWeight <- relativeWeightOrig
}
baseModelInfo <- rbind(baseModelInfo,
data.table(
modelGroupExtension = modelGroupExtension,
targetProduct = targetProduct,
monthsBack = monthsBack,
modelLag = lag,
relativeWeight = relativeWeight)
)
baseModels <- c(baseModels, list(modelInfo))
}
}
baseModelInfo[, modelId := 1:nrow(baseModelInfo)]
uniqueBaseModels <- sort(unique(baseModelInfo$targetProduct))
for(i in 1:length(uniqueBaseModels)){
productIds <- baseModelInfo$targetProduct==uniqueBaseModels[i]
productWeightSum <- baseModelInfo[productIds, sum(relativeWeight)]
normalizeWeightRatio <- weightSum/productWeightSum
baseModelInfo[productIds, relativeWeight := relativeWeight*
normalizeWeightRatio]
}
if(all(is.na(baseModelInfo$modelLag))){
nbGroups <- length(unique(baseModelInfo$modelGroupExtension))
baseModelInfo$monthsBack <- 0
baseModelInfo$modelLag <- 17
baseModelInfo$relativeWeight <- 1
monthsBackLags <- rep(17, nbGroups)
nbLags <- length(monthsBackLags)
monthsBackModelsWeights <- rep(1, nbGroups)
weightSum <- sum(monthsBackModelsWeights)
}
baseModelInfo <- baseModelInfo[order(monthsBack), ]
baseModelNames <- unique(baseModelInfo[monthsBack==0, targetProduct])
testDataLag <- readRDS(file.path(getwd(), "Feature engineering", targetDate,
testFeaturesFolder, "Lag17 features.rds"))
if(predictSubset){
testDataLag <- testDataLag[1:predictFirst]
}
testDataPosFlank <- testDataLag$ncodpers %in% posFlankClients
trainFn <- "train/Back13Lag3 features.rds"
colOrderData <- readRDS(file.path(getwd(), "Feature engineering", targetDate,
trainFn))
targetCols <- grep("^ind_.*_ult1$", names(colOrderData), value=TRUE)
nbBaseModels <- length(targetCols)
countContributions <- readRDS(file.path(getwd(), "Feature engineering",
targetDate,
"monthlyRelativeProductCounts.rds"))
if(!trainAll){
posFlankModelInfo <- baseModelInfo[targetProduct=="hasNewProduct"]
newProdPredictions <- rep(0, nrow(testDataLag))
if(nrow(posFlankModelInfo) != nbLags) browser()
for(i in 1:nbLags){
cat("Generating new product predictions for lag", i, "of", nbLags, "\n")
lag <- posFlankModelInfo[i, lag]
weight <- posFlankModelInfo[i, relativeWeight]
newProdModel <- baseModels[[posFlankModelInfo[i, modelId]]]
testDataLag <- readRDS(file.path(getwd(), "Feature engineering", targetDate,
testFeaturesFolder,
paste0("Lag", lag, " features.rds")))
if(predictSubset){
testDataLag <- testDataLag[1:predictFirst]
}
predictorData <- testDataLag[, newProdModel$predictors, with=FALSE]
predictorDataM <- data.matrix(predictorData)
newProdPredictionsLag <- predict(newProdModel$model, predictorDataM)
newProdPredictions <- newProdPredictions + newProdPredictionsLag*weight
}
newProdPredictions <- newProdPredictions/weightSum
meanGroupPredsMayFlag <-
c(mean(newProdPredictions[testDataLag$hasMay15Data==0]),
mean(newProdPredictions[testDataLag$hasMay15Data==1]))
meanGroupPredsPosFlank <- c(mean(newProdPredictions[!testDataPosFlank]),
mean(newProdPredictions[testDataPosFlank]))
expectedPosFlanks <- sum(newProdPredictions)
leaderboardPosFlanks <- fractionPosFlankUsers*nrow(testDataLag)
normalisedProbRatio <- leaderboardPosFlanks/expectedPosFlanks
cat("Expected/leaderboard positive flank ratio",
round(1/normalisedProbRatio, 2), "\n")
if(marginalNormalisation == "linear"){
newProdPredictions <- newProdPredictions * normalisedProbRatio
} else{
newProdPredictions <- probExponentNormaliser(newProdPredictions,
normalisedProbRatio)
}
} else{
newProdPredictions <- rep(1, nrow(testDataLag))
}
if(loadPredictions && file.exists(rawPredictionsPath)){
allPredictions <- readRDS(rawPredictionsPath)
} else{
allPredictions <- NULL
for(lagId in 1:nbLags){
cat("\nGenerating positive flank predictions for lag", lagId, "of", nbLags,
"@", as.character(Sys.time()), "\n\n")
lag <- monthsBackLags[lagId]
testDataLag <- readRDS(file.path(getwd(), "Feature engineering", targetDate,
testFeaturesFolder,
paste0("Lag", lag, " features.rds")))
if(predictSubset){
testDataLag <- testDataLag[1:predictFirst]
}
for(i in 1:nbBaseModels){
targetVar <- targetCols[i]
targetModelId <- baseModelInfo[targetProduct==targetVar &
modelLag==lag, modelId]
if(length(targetModelId)>1){
targetModelId <- targetModelId[lagId]
}
targetModel <- baseModels[[targetModelId]]
weight <- baseModelInfo[modelId == targetModelId, relativeWeight]
if(targetModel$targetVar != targetVar) browser()
cat("Generating test predictions for model", i, "of", nbBaseModels, "\n")
baseModelPredPath <- file.path(baseModelPredictionsPath,
paste0(targetVar, " Lag ", lag, ".rds"))
if(loadBaseModelPredictions && file.exists(baseModelPredPath)){
predictionsDT <- readRDS(baseModelPredPath)
} else{
if(targetVar %in% zeroTargets){
predictions <- rep(0, nrow(testDataLag))
} else{
predictorData <- testDataLag[, targetModel$predictors, with=FALSE]
predictorDataM <- data.matrix(predictorData)
predictions <- predict(targetModel$model, predictorDataM)
alreadyOwned <- is.na(testDataLag[[paste0(targetVar, "Lag1")]]) |
testDataLag[[paste0(targetVar, "Lag1")]] == 1
predictionsPrevNotOwned <- predictions[!alreadyOwned]
}
predictions[alreadyOwned] <- 0
predictionsDT <- data.table(ncodpers = testDataLag$ncodpers,
predictions = predictions,
product = targetVar)
}
predictionsDT[, weightedPrediction :=
predictionsDT$predictions*weight]
if(targetVar %in% allPredictions$product){
allPredictions[product==targetVar, weightedPrediction:=
weightedPrediction +
predictionsDT$weightedPrediction]
} else{
allPredictions <- rbind(allPredictions, predictionsDT)
}
if(saveBaseModelPredictions && !loadBaseModelPredictions){
predictionsDT[, weightedPrediction:=NULL]
saveRDS(predictionsDT, baseModelPredPath)
}
}
}
allPredictions[, prediction := weightedPrediction / weightSum]
allPredictions[, weightedPrediction := NULL]
allPredictions[, predictions := NULL]
if(savePredictionsBeforeNormalisation){
saveRDS(allPredictions, file=rawPredictionsPath)
}
}
if(nominaNomPensSoftAveraging){
nominaProb <- allPredictions[product == "ind_nomina_ult1", prediction] *
newProdPredictions
nomPensProb <- allPredictions[product == "ind_nom_pens_ult1", prediction] *
newProdPredictions
avIds <- nominaProb>0 & nomPensProb>0 & (nomPensProb-nominaProb < 0.1)
avVals <- (nominaProb[avIds] + nomPensProb[avIds])/2
ncodpers <- unique(allPredictions$ncodpers)
avNcodPers <- ncodpers[avIds]
allPredictions[ncodpers %in% avNcodPers & product == "ind_nomina_ult1",
prediction := avVals]
allPredictions[ncodpers %in% avNcodPers & product == "ind_nom_pens_ult1",
prediction := avVals]
}
probMultipliers <- rep(NA, nbBaseModels)
if(normalizeProdProbs){
for(i in 1:nbBaseModels){
cat("Normalizing product predictions", i, "of", nbBaseModels, "\n")
targetVar <- targetCols[i]
alreadyOwned <- is.na(testDataLag[[paste0(targetVar, "Lag1")]]) |
testDataLag[[paste0(targetVar, "Lag1")]] == 1
predictions <- allPredictions[product==targetVar, prediction]
predictionsPrevNotOwned <- predictions[!alreadyOwned]
if(suppressWarnings(max(predictions[alreadyOwned]))>0) browser()
predictedPosFlankCount <- sum(predictionsPrevNotOwned *
newProdPredictions[!alreadyOwned])
probMultiplier <- nrow(testDataLag) * fractionPosFlankUsers *
expectedCountPerPosFlank * countContributions[17, i] /
predictedPosFlankCount
probMultipliers[i] <- probMultiplier
if(is.finite(probMultiplier)){
if(normalizeMode == "additive" || targetVar %in% additiveNormalizeProds){
predictions[!alreadyOwned] <- predictions[!alreadyOwned] +
(probMultiplier-1)*mean(predictions[!alreadyOwned])
} else{
if(normalizeMode == "linear"){
predictions[!alreadyOwned] <- predictions[!alreadyOwned] *
probMultiplier
} else{
predictions[!alreadyOwned] <- probExponentNormaliser(
predictions[!alreadyOwned], probMultiplier)
}
}
allPredictions[product==targetVar, prediction:=predictions]
}
}
}
if(ccoNoPurchase){
allPredictions[!ncodpers %in% posFlankClients &
ncodpers %in% testDataLag[ind_cco_fin_ult1Lag1==0, ncodpers] &
product == "ind_cco_fin_ult1",
prediction := 10]
}
setkey(allPredictions, ncodpers)
allPredictions[,order_predict := match(1:length(prediction),
order(-prediction)), by=ncodpers]
allPredictions <- allPredictions[order(ncodpers, -prediction), ]
orderCount <- allPredictions[, .N, .(ncodpers, order_predict)]
if(max(orderCount$N)>1) browser()
hist(allPredictions[order_predict==1, prediction])
topPredictions <- allPredictions[order_predict==1, .N, product]
topPredictions <- topPredictions[order(-N)]
topPredictionsPosFlanks <- allPredictions[order_predict==1 &
ncodpers %in% posFlankClients,
.N, product]
topPredictionsPosFlanks <- topPredictionsPosFlanks[order(-N)]
productRankDelaFin <- allPredictions[product=="ind_dela_fin_ult1", .N,
order_predict]
productRankDelaFin <- productRankDelaFin[order(order_predict),]
productRankDecoFin <- allPredictions[product=="ind_deco_fin_ult1", .N,
order_predict]
productRankDecoFin <- productRankDecoFin[order(order_predict),]
productRankTjcrFin <- allPredictions[product=="ind_tjcr_fin_ult1", .N,
order_predict]
productRankTjcrFin <- productRankTjcrFin[order(order_predict),]
productRankRecaFin <- allPredictions[product=="ind_reca_fin_ult1", .N,
order_predict]
productRankRecaFin <- productRankRecaFin[order(order_predict),]
allPredictions[, totalProb := prediction * rep(newProdPredictions,
each = nbBaseModels)]
meanProductProbs <- allPredictions[, .(meanCondProb = mean(prediction),
meanProb = mean(totalProb)), product]
meanProductProbs <- meanProductProbs[order(-meanCondProb), ]
productString <- paste(allPredictions[order_predict==1, product],
allPredictions[order_predict==2, product],
allPredictions[order_predict==3, product],
allPredictions[order_predict==4, product],
allPredictions[order_predict==5, product],
allPredictions[order_predict==6, product],
allPredictions[order_predict==7, product])
if(length(productString) != nrow(testDataLag)) browser()
submission <- data.frame(ncodpers = testDataLag$ncodpers,
added_products = productString)
paddedSubmission <- fread("Data/sample_submission.csv")
paddedSubmission[, added_products := ""]
matchIds <- match(submission$ncodpers, paddedSubmission$ncodpers)
paddedSubmission[matchIds, added_products := submission$added_products]
write.csv(paddedSubmission, file.path(getwd(), "Submission", submissionDate,
paste0(submissionFile, ".csv")),
row.names = FALSE)
if(savePredictions){
saveRDS(allPredictions, file=file.path(predictionsPath,
paste0(submissionFile, ".rds")))
}
cat("Submission file created successfully!\n",
nrow(submission)," records were predicted (",
round(nrow(submission)/nrow(paddedSubmission)*100,2), "%)\n", sep="") |
structure(list(
url = "https://example.com/login/",
status_code = 204L, headers = structure(list(
allow = "GET, HEAD, OPTIONS, POST",
`content-type` = "application/json;charset=utf-8", date = "Thu, 14 Sep 2017 04:27:22 GMT",
server = "nginx", `set-cookie` = "token=12345; Domain=example.com; Max-Age=31536000; Path=/",
vary = "Cookie, Accept-Encoding", connection = "keep-alive"
), class = c(
"insensitive",
"list"
)), all_headers = list(list(
status = 204L, version = "HTTP/1.1",
headers = structure(list(
allow = "GET, HEAD, OPTIONS, POST",
`content-type` = "application/json;charset=utf-8",
date = "Thu, 14 Sep 2017 04:27:22 GMT", server = "nginx",
`set-cookie` = "token=12345; Domain=example.com; Max-Age=31536000; Path=/",
vary = "Cookie, Accept-Encoding", connection = "keep-alive"
), class = c(
"insensitive",
"list"
))
)), cookies = structure(list(
domain = "example.com",
flag = TRUE, path = "/", secure = FALSE, expiration = structure(1536899241, class = c(
"POSIXct",
"POSIXt"
)), name = "token", value = "12345"
), row.names = c(
NA,
-1L
), class = "data.frame"), content = raw(0), date = structure(1505363242, class = c(
"POSIXct",
"POSIXt"
), tzone = "GMT"), times = c(
redirect = 0, namelookup = 0.115726,
connect = 0.467124, pretransfer = 1.405551, starttransfer = 2.041081,
total = 2.041137
), request = structure(list(
method = "POST",
url = "https://example.com/login/", headers = c(
Accept = "application/json, text/xml, application/xml, */*",
`Content-Type` = "application/json", `user-agent` = "libcurl/7.54.0 curl/2.8.1 httr/1.3.1"
), fields = NULL, options = list(
useragent = "libcurl/7.54.0 r-curl/2.8.1 httr/1.3.1",
post = TRUE, postfieldsize = 46L, postfields = charToRaw('{"username":"password"}'), postredir = 3
), auth_token = NULL, output = structure(list(), class = c(
"write_memory",
"write_function"
))
), class = "request")
), class = "response") |
get_tweets <- function(method = 'stream',
location = c(-180, -90, 180, 90),
timeout = Inf,
keywords = "",
n_max = 100L,
file_name = NULL,
...) {
if (method == 'stream') {
stopifnot(is.double(location)|is.character(location))
if (is.double(location)) rtweet::stream_tweets(q = location,
timeout = timeout,
parse = FALSE,
file_name = file_name,
...)
if (is.character(location)) {
if (location %in% row.names(bbox_country)) {
location <- as.double(bbox_country[location, ])
rtweet::stream_tweets(q = location,
timeout = timeout,
parse = FALSE,
file_name = file_name,
...)
} else if (!location %in% row.names(bbox_country)) {
tryCatch(location <- rtweet::lookup_coords(location)$box,
error = function(e) {
e$message <- paste("Could not find coordinates for your location or a Google Maps API key.
The `location` parameter requires a valid character string or Google Maps API key.
Use Twitmo:::bbox_country and rtweet:::citycoords for a full list of supported character strings for locations or
use supply your own bounding box coordinates in the following format: c(sw.long, sw.lat, ne.long, ne.lat)", sep = " ")
stop(e)
}
)
location <- as.double(location)
rtweet::stream_tweets(q = location,
timeout = timeout,
parse = FALSE,
file_name = file_name,
...)
}
}
}
if (method == 'search') {
message("You're using the search endpoint.
For search this package includes 250 cities worldwide (type rtweet::citycoords to see a list).
If you want to use your a custom location with the search endpoint use rtweet::search_tweets()")
stopifnot(is.character(location)|NULL)
if (is.character(location)) {
location <- rtweet::lookup_coords(location)$point
location <- paste(paste(location, collapse = ",", sep = ","), "50mi", collapse = ",", sep = ",")
}
rtweet::search_tweets(q = keywords,
n = n_max,
retryonratelimit = TRUE,
geocode = location,
parse = TRUE,
...)
}
} |
CCTfromXYZ <- function( XYZ, isotherms='robertson', locus='robertson', strict=FALSE )
{
uv = uvfromXYZ( XYZ, space=1960 )
if( is.null(uv) ) return(NULL)
out = CCTfromuv( uv, isotherms=isotherms, locus=locus, strict=strict )
return( out )
}
CCTfromxy <- function( xy, isotherms='robertson', locus='robertson', strict=FALSE )
{
uv = uvfromxy( xy, space=1960 )
if( is.null(uv) ) return(NULL)
out = CCTfromuv( uv, isotherms=isotherms, locus=locus, strict=strict )
return(out)
}
CCTfromuv <- function( uv, isotherms='robertson', locus='robertson', strict=FALSE )
{
uv = prepareNxM( uv, M=2 )
if( is.null(uv) ) return(NULL)
if( length(isotherms) == 0 )
{
log.string( ERROR, "isotherms is invalid, because length(isotherms)=0." )
return( NULL )
}
isofull = c( 'native', 'Robertson', 'McCamy' )
isotherms = as.character(isotherms)
isotherms[ is.na(isotherms) ] = 'native'
idx.isotherms = pmatch( tolower(isotherms), tolower(isofull), nomatch=0, duplicates.ok=TRUE )
if( any( idx.isotherms==0 ) )
{
log.string( ERROR, "isotherms='%s' is invalid.", isotherms[idx.isotherms==0] )
return( NULL )
}
ok = is.character(locus) && length(locus)==1
if( ! ok )
{
log.string( ERROR, "Argument locus is invalid. It must be a character vector with length 1." )
return(NULL)
}
locusfull = c( 'Robertson', 'precision' )
idx.locus = pmatch( tolower(locus), tolower(locusfull), nomatch=0 )
if( idx.locus == 0 )
{
log.string( ERROR, "locus='%s' is invalid.", as.character(locus) )
return( NULL )
}
if( idx.locus == 1 )
locus.list = p.uvCubicsfromMired
else
locus.list = p.uvQuinticsfromMired
n = nrow(uv)
out = matrix( NA_real_, n, length(idx.isotherms) )
rownames(out) = rownames(uv)
colnames(out) = isofull[ idx.isotherms ]
for( j in 1:length(idx.isotherms) )
{
idx = idx.isotherms[j]
if( idx == 1 )
{
for( i in 1:n )
out[i,j] = CCTfromuv_native( uv[i, ], locus.list, strict )
}
else if( idx == 2 )
{
for( i in 1:n )
out[i,j] = CCTfromuv_Robertson( uv[i, ], locus.list, strict )
}
else if( idx == 3 )
{
for( i in 1:n )
{
denom = uv[i,1] - 4*uv[i,2] + 2
if( is.na(denom) || denom < 1.e-16 ) next
xy = c( 1.5*uv[i,1], uv[i,2] ) / denom
out[i,j] = CCTfromxy_McCamy( xy, locus.list, strict )
}
}
}
if( length(idx.isotherms) == 1 )
{
rnames = rownames(out)
dim(out) = NULL
names(out) = rnames
}
return(out)
}
CCTfromuv_native <- function( uv, locus.list, strict )
{
if( any( is.na(uv) ) ) return(NA_real_)
if( FALSE )
{
idx = which( (uv[1] == p.dataCCT$u) & (uv[2] == p.dataCCT$v) )
if( length(idx) == 1 )
return( 1.e6 / p.dataCCT$mired[idx] )
}
myfun <- function( mir, uv )
{
uv.locus = c( locus.list$ufun( mir ), locus.list$vfun( mir ) )
tangent = c( locus.list$ufun( mir, deriv=1 ), locus.list$vfun( mir, deriv=1 ) )
return( sum( tangent * (uv.locus - uv) ) )
}
miredInterval = locus.list$miredInterval
f1 = myfun( miredInterval[1], uv )
f2 = myfun( miredInterval[2], uv )
if( 0 < f1 * f2 )
{
log.string( WARN, "uv=%g,%g is in invalid region. CCT cannot be calculated.", uv[1], uv[2] )
return( NA_real_ )
}
if( f1 == 0 )
mired.end = miredInterval[1]
else if( f2 == 0 )
mired.end = miredInterval[2]
else
{
res = try( stats::uniroot( myfun, interval=miredInterval, uv=uv, tol=.Machine$double.eps^0.5 ), silent=FALSE )
if( class(res) == "try-error" )
{
cat( 'stats::uniroot() res = ', utils::str(res), '\n', file=stderr() )
return( NA_real_ )
}
mired.end = res$root
}
if( strict )
{
uv.locus = c( locus.list$ufun( mired.end ),locus.list$vfun( mired.end ) )
resid = uv - uv.locus
dist = sqrt( sum(resid^2) )
if( 0.05 < dist )
{
log.string( WARN, "uv=%g,%g is invalid, because its distance to the Planckian locus = %.7f > 0.05. (mired=%g)",
uv[1], uv[2], dist, mired.end )
return( NA_real_ )
}
}
return( 1.e6 / mired.end )
}
CCTfromuv_Robertson <- function( uv, locus.list, strict )
{
if( any( is.na(uv) ) ) return(NA_real_)
mired = miredfromuv_Robertson_nocheck( uv, extrap=FALSE )
if( is.na(mired) ) return(NA_real_)
CCT = 1.e6 / mired
if( strict )
{
res = nativeFromRobertson( CCT, locus.list )
if( is.null(res) ) return( NA_real_ )
offset = uv - res$uv
test = sqrt( sum(offset*offset) )
if( 0.05 < test )
{
log.string( WARN, "uv=%g,%g is invalid, because its distance to the Planckian locus = %g > 0.05. (mired=%g)",
uv[1], uv[2], test, mired )
return( NA_real_ )
}
}
return( CCT )
}
miredfromuv_Robertson_nocheck <- function( uv, extrap=FALSE )
{
di = (uv[2] - p.dataCCT$v) - p.dataCCT$t * (uv[1] - p.dataCCT$u)
n = length(di)
idx = which( di == 0 )
if( 0 < length(idx) )
{
if( length(idx) == 1 )
return( p.dataCCT$mired[idx] )
log.string( WARN, "uv=%g,%g lies on more than 1 isotherm. Mired cannot be calculated.", uv[1], uv[2] )
return( NA_real_ )
}
idx = which( di[1:(n-1)] * di[2:n] < 0 )
if( length(idx) == 0 )
{
if( ! extrap )
{
log.string( WARN, "uv=%g,%g is in invalid region. Found no zero-crossings. Mired cannot be calculated.", uv[1], uv[2] )
return( NA_real_ )
}
if( di[1] < 0 )
return( p.dataCCT$mired[1] + 100 * di[1] )
else
return( p.dataCCT$mired[n] + 30 * di[n] )
}
else if( 2 <= length(idx) )
{
log.string( WARN, "uv=%g,%g is in invalid region. Found multiple zero-crossings. Mired cannot be calculated.", uv[1], uv[2] )
return( NA_real_ )
}
i = idx[1] + 1
d0 = di[i] / sqrt( 1 + p.dataCCT$t[i]^2 )
dm = di[i-1] / sqrt( 1 + p.dataCCT$t[i-1]^2 )
p = dm / (dm - d0)
mired = (1-p)*p.dataCCT$mired[i-1] + p*p.dataCCT$mired[i]
return( mired )
}
nativeFromRobertson <- function( CCT, locus.list )
{
mired = 1.e6 / CCT
j = findInterval( mired, p.dataCCT$mired )
if( j == 0 )
{
log.string( WARN, "CCT=%g is out of the Robertson LUT range. mired < %g", CCT, p.dataCCT$mired[1] )
return(NULL)
}
n = length( p.dataCCT$mired )
if( j == n )
{
epsilon = 1.e-12
if( p.dataCCT$mired[n] + epsilon < mired )
{
log.string( WARN, "CCT=%g is outside the Robertson LUT range. %g < %g mired",
CCT, p.dataCCT$mired[n], mired )
return(NULL)
}
mired = p.dataCCT$mired[n]
}
out = list()
if( p.dataCCT$mired[j] == mired )
{
out$uv = c( p.dataCCT$u[j], p.dataCCT$v[j] )
out$CCT = CCT
tanj = c( 1, p.dataCCT$t[j] )
len = sqrt( sum(tanj^2) )
out$normal = -tanj / len
return(out)
}
alpha = (mired - p.dataCCT$mired[j]) / (p.dataCCT$mired[j+1] - p.dataCCT$mired[j])
pj = c( p.dataCCT$u[j], p.dataCCT$v[j] )
pj1 = c( p.dataCCT$u[j+1], p.dataCCT$v[j+1] )
tanj = c( 1, p.dataCCT$t[j] )
len = sqrt( sum(tanj^2) )
normj = c( -tanj[2], tanj[1] ) / len
tanj1 = c( 1, p.dataCCT$t[j+1] )
len = sqrt( sum(tanj1^2) )
normj1 = c( -tanj1[2], tanj1[1] ) / len
norm = (1-alpha)*normj + alpha*normj1
delta = pj1 - pj
s = alpha * sum( delta * normj1 ) / sum( delta * norm )
p = pj + s*delta
myfun <- function( mired )
{
uv = c( locus.list$ufun( mired ), locus.list$vfun( mired ) )
return( sum( (uv - p)*norm ) )
}
miredInterval = locus.list$miredInterval
f1 = myfun( miredInterval[1] )
f2 = myfun( miredInterval[2] )
if( 0 < f1 * f2 )
{
log.string( WARN, "CCT=%g mired=%g p=%g,%g. norm=%g,%g. Test function has the same sign at endpoints [%g,%g]. %g and %g CCT cannot be calculated.",
CCT, mired, p[1], p[2], norm[1], norm[2], miredInterval[1], miredInterval[2], f1, f2 )
return( NULL )
}
if( f1 == 0 )
mired.end = miredInterval[1]
else if( f2 == 0 )
mired.end = miredInterval[2]
else
{
res = try( stats::uniroot( myfun, interval=miredInterval ), silent=FALSE )
if( class(res) == "try-error" )
{
cat( 'stats::uniroot() res = ', utils::str(res), '\n', file=stderr() )
return( NULL )
}
mired.end = res$root
}
out$uv = c( locus.list$ufun( mired.end ), locus.list$vfun( mired.end ) )
out$CCT = 1.e6 / mired.end
norm = norm / sqrt( sum(norm^2) )
out$normal = c( -norm[2], norm[1] )
return( out )
}
CCTfromxy_McCamy_nocheck <- function( xy )
{
topbot = xy - c(0.3320,0.1858)
if( topbot[2] <= 0 ) return( NA_real_ )
w = topbot[1]/topbot[2]
out = ((-449*w + 3525)*w - 6823.3)*w + 5520.33
if( out <= 0 ) return( NA_real_ )
return( out )
}
CCTfromxy_McCamy <- function( xy, locus.list, strict )
{
if( any( is.na(xy) ) ) return( NA_real_ )
CCT = CCTfromxy_McCamy_nocheck( xy )
if( is.finite(CCT) && strict )
{
res = nativeFromMcCamy( CCT, locus.list )
if( is.null(res) ) return( NA_real_ )
uv = c( 4*xy[1] , 6*xy[2] ) / ( -2*xy[1] + 12*xy[2] + 3 )
offset = uv - res$uv
dist = sqrt( sum(offset^2) )
if( 0.05 < dist )
{
log.string( WARN, "uv=%g,%g is invalid, because its distance to the Planckian locus = %g > 0.05. CCT=%g",
uv[1], uv[2], dist, CCT )
return( NA_real_ )
}
}
return(CCT)
}
nativeFromMcCamy <- function( CCT, locus.list )
{
if( 34530 < CCT )
return(NULL)
if( CCT < 1621 )
return(NULL)
ifun <- function( w ) { ((-449*w + 3525)*w - 6823.3)*w + 5520.33 - CCT }
res = try( stats::uniroot( ifun, interval=c(-1.91,1.28), tol=.Machine$double.eps^0.33 ), silent=FALSE )
if( class(res) == "try-error" )
{
cat( 'stats::uniroot() res = ', utils::str(res), '\n', file=stderr() )
return( NULL )
}
alpha = res$root
meet = c(0.3320,0.1858)
C = sum( c(1,-alpha) * meet )
normal = c( 1.5 - C, 4*C - alpha )
uv0 = uvfromxy( meet, 1960 )
myfun <- function( mired )
{
uv = c( locus.list$ufun(mired), locus.list$vfun(mired) )
return( sum( (uv-uv0)*normal ) )
}
miredInterval = locus.list$miredInterval
f1 = myfun( miredInterval[1] )
f2 = myfun( miredInterval[2] )
if( 0 < f1 * f2 )
{
log.string( WARN, "CCT=%g. Test function has the same sign at endpoints [%g,%g]. %g and %g. Intersection of isotherm and locus cannot be calculated.",
CCT, miredInterval[1], miredInterval[2], f1, f2 )
return( NULL )
}
if( f1 == 0 )
mired.end = miredInterval[1]
else if( f2 == 0 )
mired.end = miredInterval[2]
else
{
res = try( stats::uniroot( myfun, interval=miredInterval, tol=.Machine$double.eps^0.33 ), silent=FALSE )
if( class(res) == "try-error" )
{
cat( 'stats::uniroot() res = ', utils::str(res), '\n', file=stderr() )
return( NULL )
}
mired.end = res$root
}
uv = c( locus.list$ufun( mired.end ), locus.list$vfun( mired.end ) )
out = list()
out$uv = uv
out$CCT = 1.e6 / mired.end
out$normal = c(-normal[2],normal[1]) / sqrt( sum(normal^2) )
return(out)
}
planckLocus <- function( temperature, locus='robertson', param='robertson', delta=0, space=1960 )
{
ok = is.numeric(temperature) && 0<length(temperature)
if( ! ok )
{
log.string( ERROR, "Argument temperature is invalid. It must be a numeric vector with positive length." )
return(NULL)
}
ok = is.character(locus) && length(locus)==1
if( ! ok )
{
log.string( ERROR, "Argument locus is invalid. It must be a character vector with length 1." )
return(NULL)
}
locusfull = c( 'Robertson', 'precision' )
idx.locus = pmatch( tolower(locus), tolower(locusfull), nomatch=0 )
if( idx.locus == 0 )
{
log.string( ERROR, "locus='%s' is invalid.", as.character(locus) )
return( NULL )
}
if( idx.locus == 1 )
locus.list = p.uvCubicsfromMired
else
locus.list = p.uvQuinticsfromMired
if( length(param) != 1 )
{
log.string( ERROR, "param is invalid, because it has length=%d != 1.", length(param) )
return( NULL )
}
param = as.character(param)
param[ is.na(param) ] = 'native'
paramfull = c( 'native', 'Robertson', 'McCamy' )
idx.param = pmatch( tolower(param), tolower(paramfull), nomatch=0 )
if( idx.param == 0 )
{
log.string( ERROR, "param='%s' is invalid.", param )
return( NULL )
}
n = length(temperature)
ok = is.numeric(delta) && length(delta) %in% c(1,n)
if( ! ok )
{
log.string( ERROR, "Argument delta is invalid. It must be a numeric vector with length 1 or %d.", n )
return(NULL)
}
if( length(delta) == 1 ) delta = rep( delta[1], n )
if( ! match(space,c(1960,1976,1931),nomatch=FALSE) )
{
log.string( ERROR, "space='%s' is invalid.", as.character(space[1]) )
return(NULL)
}
uv = matrix( NA_real_, n, 2 )
rnames = names(temperature)
if( is.null(rnames) ) rnames = sprintf( "%gK", round(temperature) )
rownames(uv) = rnames
colnames(uv) = c('u','v')
if( FALSE )
{
temperaturerange = range( 1.e6 / locus.list$miredInterval )
ok = temperaturerange[1]<=temperature & temperature<=temperaturerange[2]
temperature[ ! ok ] = NA_real_
}
if( idx.param == 1 )
{
mired = 1.e6 / temperature
uv[ ,1] = locus.list$ufun( mired )
uv[ ,2] = locus.list$vfun( mired )
if( any( delta!=0 ) )
{
for( i in 1:n )
{
if( delta[i] == 0 || is.na(mired[i]) ) next
normal = c( -locus.list$vfun( mired[i], deriv=1 ), locus.list$ufun( mired[i], deriv=1 ) )
len = sqrt( sum(normal^2) )
if( len == 0 ) next
normal = normal / len
uv[i, ] = uv[i, ] + delta[i]*normal
}
}
}
else
{
for( i in 1:n )
{
if( is.na(temperature[i]) ) next
if( idx.param == 3 )
{
res = nativeFromMcCamy( temperature[i], locus.list )
}
else
{
res = nativeFromRobertson( temperature[i], locus.list )
}
if( is.null(res) ) next
uv[i, ] = res$uv
if( is.finite(delta[i]) && delta[i]!=0 )
{
uv[i, ] = uv[i, ] + delta[i] * res$normal
}
}
}
if( space == 1931 )
{
xy = uv
colnames(xy) = c('x','y')
denom = uv[ ,1] - 4*uv[ ,2] + 2
xy[ ,1] = 1.5*uv[ ,1] / denom
xy[ ,2] = uv[ ,2] / denom
return( xy )
}
else if( space == 1976 )
{
colnames(uv) = c("u'","v'")
uv[ ,2] = 1.5 * uv[ ,2]
}
return(uv)
}
|
`%<-%` <- function(var, value) {
if (!is.character(value)) {
stop("Please enter a proper character matrix. See ?`%<-%`")
}
txt <- gsub("\\,[^0-9]*(?=\\n)", "", value, perl = TRUE)
rows <- strsplit(txt, "[\n\\\\]", perl = TRUE)[[1]]
commas <- sapply(gregexpr(",", rows, fixed = TRUE),
function(x) {
if (x[1] < 0) {
return(0)
} else {
length(x)
}
})
commasTotal <- sum(commas)
nc <- max(commas) + 1
nr <- length(rows)
nValues <- commasTotal + nr
if (nValues != nr*nc) {
isLowerTriangular <- all(commas == seq_along(commas) - 1)
isUpperTriangular <- all(commas == rev(seq_along(commas) - 1))
if (isLowerTriangular) {
for (i in seq_along(rows)) {
sRows <- strsplit(rows, ",")
rows[[i]] <- paste(sapply(sRows, function(x) x[i]), collapse = ",")
}
} else if (isUpperTriangular) {
stop("Upper triangular matrices not yet supported, use lower triangular.")
} else {
stop("(Syntax) number of values not equal to number of cells in matrix.")
}
}
d <- paste(rows, collapse = ",")
matExp <- paste0("matrix(data = c(", d, "), byrow = TRUE, nrow = ", nr,
", ncol = ", nc, ")")
pf <- parent.frame()
eval(parse(text = paste0("`__MassignMat__` <-", matExp)), envir = pf)
eval(parse(text = paste0(deparse(substitute(var)), " <- `__MassignMat__`")),
envir = pf)
evalq(rm("__MassignMat__"), envir = pf)
}
`%->%` <- function(value, var) {
eval(parse(text = paste0(deparse(substitute(var)), "<- NULL")),
envir = parent.frame())
if (is.character(value)) {
eval(parse(text = paste0("`%<-%`(",
deparse(substitute(var)),
",'", value,"')")),
envir = parent.frame())
} else {
eval(parse(text = paste0("`%<-%`(",
deparse(substitute(var)),
",",
deparse(substitute(value)),
")")),
envir = parent.frame())
}
} |
structure.stat <-
function(g,subnodes)
{
subg=induced.subgraph(g, subnodes)
CZ=sum(degree(subg))/2;CG=sum(degree(g))/2
MuZ=(sum(degree(g)[subnodes]))^2/(4*CG);MuG=CG
t.stat=CZ*log(CZ/MuZ)+(CG-CZ)*log((CG-CZ)/(MuG-MuZ))
p1=(CZ/MuZ);p10=(CG-CZ)/(MuG-MuZ)
return(c(t.stat,p10,p1))
} |
require(quantstrat)
oldtz <- Sys.getenv('TZ')
if(oldtz=='') {
Sys.setenv(TZ="UTC")
}
suppressWarnings(rm("account.faber","portfolio.faber",pos=.blotter))
suppressWarnings(rm("ltaccount", "ltportfolio", "ClosePrice", "CurrentDate", "equity",
"GSPC", "stratFaber", "startDate", "initEq", "Posn", "UnitSize", "verbose"))
suppressWarnings(rm("order_book.faber",pos=.strategy))
startDate='1997-12-31'
initEq=100000
currency("USD")
symbols = c("XLF", "XLP", "XLE", "XLY", "XLV", "XLI", "XLB", "XLK", "XLU")
for(symbol in symbols){
stock(symbol, currency="USD",multiplier=1)
}
getSymbols(symbols, src='yahoo', index.class=c("POSIXt","POSIXct"), from='1999-01-01')
for(symbol in symbols) {
x<-get(symbol)
x<-to.monthly(x,indexAt='lastof',drop.time=TRUE)
indexFormat(x)<-'%Y-%m-%d'
colnames(x)<-gsub("x",symbol,colnames(x))
assign(symbol,x)
}
initPortf('faber', symbols=symbols)
initAcct('faber', portfolios='faber', initEq=100000)
initOrders(portfolio='faber')
posval<-initEq/length(symbols)
for(symbol in symbols){
pos<-round((posval/first(getPrice(get(symbol)))[,1]),-2)
addPosLimit('faber', symbol, startDate, maxpos=pos, minpos=-pos)
}
print("setup completed")
strategy("faber", store=TRUE)
add.indicator('faber', name = "SMA", arguments = list(x = quote(Cl(mktdata)), n=10), label="SMA10")
add.signal('faber',name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="gte"),label="Cl.gt.SMA")
add.signal('faber',name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="lt"),label="Cl.lt.SMA")
add.rule('faber', name='ruleSignal', arguments = list(sigcol="Cl.gt.SMA", sigval=TRUE, orderqty=100000, osFUN='osMaxPos', ordertype='market', orderside='long', pricemethod='market',TxnFees=-5), type='enter', path.dep=TRUE)
add.rule('faber', name='ruleSignal', arguments = list(sigcol="Cl.lt.SMA", sigval=TRUE, orderqty='all', ordertype='market', orderside='long', pricemethod='market',TxnFees=-5), type='exit', path.dep=TRUE)
add.rule('faber', 'rulePctEquity',
arguments=list(rebalance_on='quarters',
trade.percent=1/length(symbols),
refprice=quote(last(getPrice(mktdata)[paste('::',as.character(curIndex),sep='')][,1])),
digits=0
),
type='rebalance',
label='rebalance'
)
start_t<-Sys.time()
out<-applyStrategy.rebalancing(strategy='faber' , portfolios='faber')
end_t<-Sys.time()
print("Strategy Loop:")
print(end_t-start_t)
Sys.setenv(TZ=oldtz)
start_t<-Sys.time()
updatePortf(Portfolio='faber',Dates=paste('::',as.Date(Sys.time()),sep=''))
updateAcct('faber')
end_t<-Sys.time()
print("trade blotter portfolio update:")
print(end_t-start_t)
themelist<-chart_theme()
themelist$col$up.col<-'lightgreen'
themelist$col$dn.col<-'pink'
dev.new()
layout(mat=matrix(1:(length(symbols)+1),ncol=2))
for(symbol in symbols){
chart.Posn(Portfolio='faber',Symbol=symbol,theme=themelist,TA="add_SMA(n=10,col='darkgreen')")
}
ret1 <- PortfReturns('faber')
ret1$total <- rowSums(ret1)
print(ret1)
if("package:PerformanceAnalytics" %in% search() || require("PerformanceAnalytics",quietly=TRUE)){
getSymbols("SPY", src='yahoo', index.class=c("POSIXt","POSIXct"), from='1999-01-01')
SPY<-to.monthly(SPY, indexAt='lastof')
SPY.ret <- Return.calculate(SPY$SPY.Close)
dev.new()
charts.PerformanceSummary(cbind(ret1$total,SPY.ret), geometric=FALSE, wealth.index=TRUE)
}
faber.stats<-tradeStats('faber')[,c('Net.Trading.PL','Max.Drawdown','Num.Trades','Profit.Factor','Std.Dev.Trade.PL','Largest.Winner','Largest.Loser','Max.Equity','Min.Equity')]
faber.stats |
source("library.R")
a_date <- ymd(c("20151201", "20160201"))
a_ct <- ymd_h(c("20151201 03", "20160201 03"))
b_date <- span(a_date, convert_interval("month"))
b_ct <- ymd_hms(c("2015-01-01 00:00:00", "2016-01-01 00:00:00",
"2017-01-01 00:00:00"))
b_ct_tz_is_NULL <- b_ct
attr(b_ct_tz_is_NULL, 'tzone') <- NULL
context("to_posix creates correct result")
test_that("to_posix sets second to posix if first is", {
date_date <- to_posix(a_date, b_date)
posix_date <- to_posix(a_ct, b_date)
date_posix <- to_posix(a_date, b_ct)
posix_posix <- to_posix(a_ct, b_ct)
date_posix_tz_null <- to_posix(a_date, b_ct_tz_is_NULL)
posix_date_tz_null <- to_posix(b_ct_tz_is_NULL, a_date)
expect_equal( date_date$a %>% class, "Date")
expect_equal( date_date$b %>% class, "Date")
expect_equal( posix_date$a %>% class, c("POSIXct", "POSIXt"))
expect_equal( posix_date$b %>% class, c("POSIXct", "POSIXt"))
expect_equal( date_posix$a %>% class, c("POSIXct", "POSIXt"))
expect_equal( date_posix$b %>% class, c("POSIXct", "POSIXt"))
expect_equal( posix_posix$a %>% class, c("POSIXct", "POSIXt"))
expect_equal( posix_posix$b %>% class, c("POSIXct", "POSIXt"))
expect_equal( date_posix_tz_null$a %>% class, c("POSIXct", "POSIXt"))
expect_equal( date_posix_tz_null$b %>% class, c("POSIXct", "POSIXt"))
})
context("round_up_core and round_down_core work as expected")
test_that("round_up_core gives correct result", {
expect_equal( round_up_core(a_date, b_date),
as.numeric (as.Date ( c("2016-01-01", "2016-03-01"))))
expect_equal( round_up_core(a_ct, b_ct),
as.numeric (ymd_hms ( c("2016-01-01 00:00:00",
"2017-01-01 00:00:00"))))
})
test_that("round_down_core gives correct result", {
expect_equal( round_down_core(a_date, b_date),
as.numeric (as.Date ( c("2015-12-01", "2016-02-01"))))
expect_equal( round_down_core(a_ct, b_ct),
as.numeric (ymd_hms ( c("2015-01-01 00:00:00",
"2016-01-01 00:00:00"))))
})
context("posix_to_date works as expected")
test_that("posix_to_date gives date when possible", {
expect_equal( posix_to_date(a_date) %>% class, "Date" )
expect_equal( posix_to_date(a_ct) %>% class, c("POSIXct", "POSIXt"))
expect_equal( posix_to_date(b_ct) %>% class, "Date" )
}) |
formatpv <- function(p, text = FALSE) {
if(p < 0.0001) {return("<0.0001")}
if(p >= 0.0001 & p < 0.00095) {
ifelse(text == FALSE,
return(sprintf("%.4f", p)),
return(paste("=", sprintf("%.4f", p), sep = ""))
)
}
if(p >= 0.00095 & p <= 0.0095) {
ifelse(text == FALSE,
return(as.character(signif(p, 1))),
return(paste("=", as.character(signif(p, 1)), sep = ""))
)
}
if(p > 0.0095 & p < 0.0995) {
ifelse(text == FALSE,
return(sprintf("%.3f", signif(p, 2))),
return(paste("=", sprintf("%.3f", signif(p, 2)), sep = ""))
)
}
if(p >= 0.0995) {
ifelse(text == FALSE,
return(sprintf("%.2f", signif(p, 2))),
return(paste("=", sprintf("%.2f", signif(p, 2)), sep = ""))
)
}
} |
context("Test that functions gracefully fail when retrieving data from \"OsloW\", which has been removed.")
library(testthat)
testthat::skip_on_cran()
test_that("fread_trips_data() produces an error when city = 'OsloW'", {
expect_error(fread_trips_data(year = 2019, month = 01, city = "OsloW"))
}
)
test_that("read_trips_data() produces an error when city = 'OsloW'", {
expect_error(read_trips_data(year = 2019, month = 01, city = "OsloW"))
}
)
test_that("dl_trips_data() produces an error when city = 'OsloW'", {
expect_error(dl_trips_data(year = 2019, month = 01, city = "OsloW"))
}
) |
setMethod("asJSON", "complex", function(x, digits = 5, collapse = TRUE, complex = c("string",
"list"), na = c("string", "null", "NA"), oldna = NULL, ...) {
na <- match.arg(na);
complex <- match.arg(complex)
if (complex == "string") {
mystring <- prettyNum(x = x, digits = digits)
if (any(missings <- which(!is.finite(x)))){
if (na %in% c("null", "NA")) {
mystring[missings] <- NA_character_;
}
}
asJSON(mystring, collapse = collapse, na = na, ...)
} else {
if(na == "NA"){
na <- oldna;
}
asJSON(list(real = Re(x), imaginary = Im(x)), na = na, digits = digits, ...)
}
}) |
.get_dtcc_name_df <-
function() {
dtcc_name_df <-
tibble(
nameDTCC = c(
"DISSEMINATION_ID",
"ORIGINAL_DISSEMINATION_ID",
"ACTION",
"EXECUTION_TIMESTAMP",
"CLEARED",
"INDICATION_OF_COLLATERALIZATION",
"INDICATION_OF_END_USER_EXCEPTION",
"INDICATION_OF_OTHER_PRICE_AFFECTING_TERM",
"BLOCK_TRADES_AND_LARGE_NOTIONAL_OFF-FACILITY_SWAPS",
"EXECUTION_VENUE",
"EFFECTIVE_DATE",
"END_DATE",
"DAY_COUNT_CONVENTION",
"SETTLEMENT_CURRENCY",
"ASSET_CLASS",
"SUB-ASSET_CLASS_FOR_OTHER_COMMODITY",
"TAXONOMY",
"PRICE_FORMING_CONTINUATION_DATA",
"UNDERLYING_ASSET_1",
"UNDERLYING_ASSET_2",
"PRICE_NOTATION_TYPE",
"PRICE_NOTATION",
"ADDITIONAL_PRICE_NOTATION_TYPE",
"ADDITIONAL_PRICE_NOTATION",
"NOTIONAL_CURRENCY_1",
"NOTIONAL_CURRENCY_2",
"ROUNDED_NOTIONAL_AMOUNT_1",
"ROUNDED_NOTIONAL_AMOUNT_2",
"PAYMENT_FREQUENCY_1",
"RESET_FREQUENCY_1",
"OPTION_STRIKE_PRICE",
"OPTION_TYPE",
"OPTION_FAMILY",
"OPTION_CURRENCY",
"OPTION_PREMIUM",
"OPTION_LOCK_PERIOD",
"OPTION_EXPIRATION_DATE",
"PRICE_NOTATION2_TYPE",
"PRICE_NOTATION2",
"PRICE_NOTATION3_TYPE",
"PRICE_NOTATION3",
"urlData",
"EMBEDED_OPTION",
"PAYMENT_FREQUENCY_2",
"RESET_FREQUENCY_2",
"Action",
"UPI/Taxonomy",
"PublicationTimestamp (UTC)",
"ExecutionTimestamp (UTC)",
"UnderlyingAsset 1",
"UnderlyingAsset 2",
"MaturityDate",
"RoundedNotionalCurrency/Quantity",
"NotionalQuantity UOM/Currency",
"Clear",
"PriceNotation",
"PriceNotationType",
"Bespoke(Y/N)",
"OptionType",
"ExerciseDate",
"OptionLevel",
"OptionPremium",
"RoundedNotional(MMs)",
"Curr",
"Addl PriceNotationExists(Y/N)",
"RoundedNotional 2/Units",
"EffectiveDate",
"RoundedNotional1(MMs)",
"Curr1",
"Curr2",
"Exotic(Y/N)",
"EmbeddedOption(Y/N)",
"OptionFamily",
"CLEARED_OR_UNCLEARED",
"COLLATERALIZATION",
"END_USER_EXCEPTION",
"BESPOKE_SWAP",
"BLOCK_TRADE",
"ASSET_ID"
),
nameActual = c(
"idDissemination",
"idDisseminationOriginal",
"typeAction",
"dateTimeExecution",
"isCleared",
"idTypeCollateralization",
"hasEndUserAccepted",
"hasOtherPriceAffectingTerm",
"hasBlockTradeLargeNotionalOffFacilitySwap",
"typeExecutionVenue",
"dateEffective",
"dateEnd",
"idDayCount",
"codeCurrencySettlement",
"idAssetClass",
"idSubAssetClass",
"descriptionTaxonomy",
"typePriceFormingContinuation",
"nameUnderylingAsset1",
"nameUnderylingAsset2",
"typePriceNotation",
"priceNotation",
"typePriceNotationAdditional",
"detailsPriceNotation",
"codeCurrencyNotional1",
"codeCurrencyNotional2",
"amountNotionalRounded1",
"amountNotionalRounded2",
"idPaymentFrequency1",
"idResetFrequency1",
"priceOptionStrike",
"typeOption",
"familyOption",
"codeCurrencyOption",
"amountOptionPremium",
"dateOptionLockPeriod",
"dateOptionExpiration",
"typePriceNotation2",
"priceNotation2",
"typePriceNotation3",
"priceNotation3",
"urlData",
"descriptionEmbeddedOption",
"idPaymentFrequency2",
"idResetFrequency2",
"typeAction",
"descriptionTaxonomy",
"dateTimePublication",
"dateTimeExecution",
"nameUnderylingAsset1",
"nameUnderylingAsset2",
"dateMaturity",
"amountNotionalRounded1",
"codeNotionalQuantity",
"isCleared",
"priceNotation",
"typePriceNotation",
"isBespoke",
"typeOption",
"dateExercise",
"amountLevelOption",
"amountOptionPremium",
"amountNotionalRounded1",
"codeCurrency",
"hasAdditionalPriceNotation",
"amountRoundedNotionalUnits",
"dateEffective",
"amountNotionalRounded2",
"codeCurrency1",
"codeCurrency2",
"isExotic",
"hasEmbeddedOption",
"codeOptionFamily",
"type",
"idTypeCollateralization",
"hasEndUserException",
"isBespokeSwap",
"isBlockTrade",
"idAssetType"
)
)
return(dtcc_name_df)
}
.resolve_dtcc_name_df <-
function(data) {
options(scipen = 9999999)
name_df <-
.get_dtcc_name_df() %>%
mutate(idRow = 1:n())
rf_names <-
data %>% names()
has_missing_names <-
rf_names[!rf_names %in% name_df$nameDTCC] %>% length() > 0
if (has_missing_names) {
df_has <-
data %>%
select(one_of(rf_names[rf_names %in% name_df$nameDTCC]))
has_names <-
names(df_has) %>%
map_chr(function(x) {
name_df %>%
filter(nameDTCC == x) %>%
filter(idRow == min(idRow)) %>%
.$nameActual
})
df_has <-
df_has %>%
purrr::set_names(has_names)
data <-
df_has %>%
bind_cols(data %>%
select(one_of(rf_names[!rf_names %in% name_df$nameDTCC])))
return(data)
}
actual_names <-
names(data) %>%
map_chr(function(x) {
name_df %>%
filter(nameDTCC == x) %>%
filter(idRow == min(idRow)) %>%
.$nameActual
})
data <-
data %>%
purrr::set_names(actual_names)
has_notional <-
data %>% select(dplyr::matches("amountNotionalRounded1")) %>% names() %>% length() > 0
if (has_notional) {
data <-
data %>%
mutate(
isNotionalEstimate = amountNotionalRounded1 %>% str_detect('\\+'),
amountNotionalRounded1 = amountNotionalRounded1 %>% as.character() %>% readr::parse_number()
)
if ('amountNotionalRounded2' %in% names(data)) {
data <-
data %>%
mutate(
isNotionalEstimate2 = amountNotionalRounded2 %>% str_detect('\\+'),
amountNotionalRounded2 = amountNotionalRounded2 %>% as.character() %>% readr::parse_number()
)
}
}
data <-
data %>%
mutate_at(data %>% select(dplyr::matches("isCleared")) %>% names(),
funs(ifelse(. == "C", TRUE, FALSE))) %>%
mutate_at(data %>% select(dplyr::matches("^has|^is")) %>% names(),
funs(ifelse(. == "Y", TRUE, FALSE))) %>%
mutate_at(data %>% select(dplyr::matches("nameUnderylingAsset|^code|^type")) %>% names(),
funs(ifelse(. == '', NA, .)))
if ('amountLevelOption' %in% names(data)) {
data <-
data %>%
mutate(amountLevelOption = amountLevelOption %>% as.character())
}
data <-
data %>%
mutate_at(data %>% select(dplyr::matches("^name|^description|^idDay|^type")) %>% names(),
funs(. %>% str_to_upper())) %>%
mutate_at(data %>% select(dplyr::matches("^price|amountOptionPremium")) %>% names(),
funs(. %>% as.character() %>% readr::parse_number())) %>%
mutate_at(
data %>% select(
dplyr::matches("^dateOptionLockPeriod|dateOptionExpiration|^date")
) %>% select(-dplyr::matches("dateTime|dateMaturity|dateExercise")) %>% names(),
funs(. %>% lubridate::ymd())
) %>%
mutate_at(data %>% select(dplyr::matches("dateMaturity|dateExercise")) %>% names(),
funs(. %>% lubridate::mdy())) %>%
mutate_at(data %>% select(dplyr::matches("^dateTime")) %>% names(),
funs(. %>% lubridate::ymd_hms())) %>%
mutate_at(data %>% select(dplyr::matches("^details|idDisseminationOriginal")) %>% names(),
funs(. %>% as.character()))
if ('amountLevelOption' %in% names(data)) {
data <-
data %>%
mutate(amountLevelOption = amountLevelOption %>% as.character())
}
return(data)
}
.parse_most_recent_dtcc_url <-
function(url = "https://kgc0418-tdw-data-0.s3.amazonaws.com/gtr/static/gtr/html/tracker.html") {
}
.generate_dtcc_dump_urls <-
function(date = "2016-01-07",
assets = NULL) {
if (length(assets) == 0) {
assets <-
c('COMMODITIES', 'credits', 'equities', 'forex', 'rates') %>%
str_to_upper()
}
if (length(assets) > 0) {
actual_assets <-
c('COMMODITIES', 'credits', 'equities', 'forex', 'rates') %>%
str_to_upper()
wrong <-
!assets %>% str_to_upper() %in% actual_assets %>% sum() == length(assets)
if (wrong) {
stop(list(
"Financial assets can only be\n",
paste0(actual_assets, collapse = '\n')
) %>% purrr::invoke(paste0, .))
}
assets <-
assets %>%
str_to_upper()
}
date_actual <-
date %>% lubridate::ymd()
date <-
date_actual %>%
str_replace_all("\\-", '\\_')
urls <-
list(
"https://kgc0418-tdw-data-0.s3.amazonaws.com/slices/CUMULATIVE_",
assets,
"_",
date,
".zip"
) %>%
purrr::invoke(paste0, .)
url_df <-
tibble(dateData = date_actual,
urlData = urls)
return(url_df)
}
.parse_for_underlying_asset <-
function(data) {
if ('nameUnderylingAsset1' %in% names(data)) {
data <-
data %>%
separate(
nameUnderylingAsset1,
into = c(
'descriptionUnderlyingAsset1',
'durationIndex',
'idSeriesUnderlyingAsset1'
),
sep = '\\:',
remove = FALSE
) %>%
mutate(
idSeriesUnderlyingAsset1 = ifelse(
idSeriesUnderlyingAsset1 %>% is.na(),
durationIndex,
idSeriesUnderlyingAsset1
),
descriptionUnderlyingAsset1 = ifelse(
descriptionUnderlyingAsset1 == durationIndex,
NA,
descriptionUnderlyingAsset1
),
durationIndex = ifelse(
durationIndex == idSeriesUnderlyingAsset1,
NA,
durationIndex
)
) %>%
suppressWarnings()
has_desc_df <-
data %>%
mutate(idRow = 1:n()) %>%
filter(!descriptionUnderlyingAsset1 %>% is.na()) %>%
select(idRow, descriptionUnderlyingAsset1) %>% nrow() > 0
if (has_desc_df) {
description_df <-
data %>%
filter(!descriptionUnderlyingAsset1 %>% is.na()) %>%
mutate(idRow = 1:n()) %>%
select(idRow, descriptionUnderlyingAsset1)
desc_df <-
1:nrow(description_df) %>%
future_map_dfr(function(x) {
row_number <-
description_df$idRow[[x]]
if (description_df$descriptionUnderlyingAsset1[[x]] %>% str_count('\\.') == 0) {
return(tibble(idRow = row_number))
}
items <-
description_df$descriptionUnderlyingAsset1[[x]] %>%
str_split('\\.') %>%
flatten_chr()
items <-
items[!items == 'NA']
count_items <-
items %>% length()
if (count_items == 2) {
df <-
tibble(
idRow = row_number,
item = c('idSubIndex', 'idSeries'),
values = items
) %>%
spread(item, values) %>%
mutate(idSeries = idSeries %>% as.numeric())
}
if (count_items == 3) {
df <-
tibble(
idRow = row_number,
item = c('idIndex', 'idSubIndex', 'idSeries'),
values = items
) %>%
spread(item, values) %>%
mutate(idSeries = idSeries %>% as.numeric())
}
if (count_items == 4) {
df <-
tibble(
idRow = row_number,
item = c('idIndex', 'idSubIndex', 'idSeries', 'idSubIndex1'),
values = items
) %>%
spread(item, values) %>%
mutate(idSeries = idSeries %>% as.numeric())
}
if (count_items == 5) {
df <-
tibble(
idRow = row_number,
item = c(
'idIndex',
'idSubIndex',
'idSeries',
'idSubIndex1',
'idRating'
),
values = items
) %>%
spread(item, values) %>%
mutate(idSeries = idSeries %>% as.numeric())
}
if (count_items == 6) {
df <-
tibble(
idRow = row_number,
item = c(
'idIndex',
'idSubIndex',
'idSeries',
'idSeries1',
'idRating',
'idOther'
),
values = items
) %>%
spread(item, values) %>%
mutate(idSeries = idSeries %>% as.numeric())
}
if (count_items == 7) {
df <-
tibble(
idRow = row_number,
item = c(
'idIndex',
'idSubIndex',
'idSeries',
'idSeries1',
'idRating',
'idOther',
'idOther1'
),
values = items
) %>%
spread(item, values) %>%
mutate(idSeries = idSeries %>% as.numeric())
}
if (count_items == 8) {
df <-
tibble(
idRow = row_number,
item = c(
'idIndex',
'idSubIndex',
'idSeries',
'idSeries1',
'idRating',
'idOther',
'idOther1',
'idOther2'
),
values = items
) %>%
spread(item, values) %>%
mutate(idSeries = idSeries %>% as.numeric())
}
return(df)
}) %>%
distinct()
data <-
data %>%
mutate(idRow = 1:n()) %>%
left_join(desc_df) %>%
select(-idRow) %>%
suppressMessages()
}
return(data)
}
}
.resolve_taxonomy <-
function(data) {
has_taxonomy <-
'descriptionTaxonomy' %in% names(data)
if (has_taxonomy) {
df_taxonomy <-
data %>%
filter(!descriptionTaxonomy %>% is.na()) %>%
select(descriptionTaxonomy) %>%
distinct() %>%
arrange(descriptionTaxonomy)
df_taxonomies <-
1:nrow(df_taxonomy) %>%
future_map_dfr(function(x) {
tax <-
df_taxonomy$descriptionTaxonomy[[x]]
levels <-
tax %>% str_count('\\:')
if (levels == 0) {
return(tibble(descriptionTaxonomy = tax))
}
tax_items <-
tax %>%
str_split('\\:') %>%
flatten_chr()
asset <-
tax_items[[1]] %>% str_to_upper()
if (asset == 'COMMODITY') {
items <-
c(
'typeFinancialProduct',
'nameProduct',
'nameSubProduct',
'typeFuture',
'methodDelivery'
)
df_long <-
tibble(value = tax_items, item = items[seq_along(tax_items)]) %>%
mutate(descriptionTaxonomy = tax)
col_order <-
c('descriptionTaxonomy', df_long$item)
df <-
df_long %>%
spread(item, value) %>%
select(one_of(col_order))
}
if (asset == "CREDIT") {
items <-
c(
'typeFinancialProduct',
'typeIndex',
'nameIndexReference',
'nameSubIndexReference'
)
df_long <-
tibble(value = tax_items, item = items[seq_along(tax_items)]) %>%
mutate(descriptionTaxonomy = tax)
col_order <-
c('descriptionTaxonomy', df_long$item)
df <-
df_long %>%
spread(item, value) %>%
select(one_of(col_order))
}
if (asset == "EQUITY") {
items <-
c(
'typeFinancialProduct',
'typeFuture',
'nameIndexReference',
'typeIndexReference'
)
df_long <-
tibble(value = tax_items, item = items[seq_along(tax_items)]) %>%
mutate(descriptionTaxonomy = tax)
col_order <-
c('descriptionTaxonomy', df_long$item)
df <-
df_long %>%
spread(item, value) %>%
select(one_of(col_order))
}
if (asset %in% c("FOREIGNEXCHANGE", "INTERESTRATE")) {
items <-
c(
'typeFinancialProduct',
'typeFuture',
'nameIndexReference',
'typeIndexReference'
)
df_long <-
tibble(value = tax_items, item = items[seq_along(tax_items)]) %>%
mutate(descriptionTaxonomy = tax)
col_order <-
c('descriptionTaxonomy', df_long$item)
df <-
df_long %>%
spread(item, value) %>%
select(one_of(col_order))
}
df <-
df %>%
mutate_all(as.character)
return(df)
})
data <-
data %>%
left_join(df_taxonomies) %>%
suppressMessages()
return(data)
}
}
.download_dtcc_url <-
function(url = "https://kgc0418-tdw-data-0.s3.amazonaws.com/slices/CUMULATIVE_CREDITS_2017_01_06.zip",
return_message = TRUE) {
tmp <-
tempfile()
date_data <-
url %>%
str_replace_all(
"https://kgc0418-tdw-data-0.s3.amazonaws.com/slices/|.zip|CUMULATIVE_|COMMODITIES|CREDITS|EQUITIES|FOREX|RATES|\\_",
''
) %>%
lubridate::ymd()
type_item <-
url %>%
str_replace_all("https://kgc0418-tdw-data-0.s3.amazonaws.com/slices/CUMULATIVE_",
'') %>%
str_split('\\_') %>%
flatten_chr() %>%
.[[1]]
url %>%
curl::curl_download(url = ., tmp)
con <-
unzip(tmp)
data <-
con %>%
readr::read_csv() %>%
suppressWarnings() %>%
suppressMessages() %>%
select(which(colMeans(is.na(.)) < 1)) %>%
as_tibble()
con %>%
unlink()
data <-
data %>%
.resolve_dtcc_name_df() %>%
mutate(nameAsset = type_item,
dateData = date_data) %>%
select(nameAsset,
dateData, everything()) %>%
select(which(colMeans(is.na(.)) < 1))
data <-
data %>%
.parse_for_underlying_asset() %>%
.resolve_taxonomy()
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(data)
}
.get_data_dtcc_assets_days <-
function(assets = NULL,
start_date = "2017-01-21",
end_date = "2017-01-22",
nest_data = TRUE,
return_message = TRUE) {
start_date <-
start_date %>%
as.character() %>%
readr::parse_date()
end_date <-
end_date %>%
as.character() %>%
readr::parse_date()
days <-
seq(start_date, end_date, by = 1)
df_date <-
days %>%
future_map_dfr(function(x) {
.generate_dtcc_dump_urls(date = x, assets = assets)
})
.download_dtcc_url_safe <-
purrr::possibly(.download_dtcc_url, tibble())
all_df <-
1:nrow(df_date) %>%
future_map_dfr(function(x) {
.download_dtcc_url_safe(url = df_date$urlData[[x]], return_message = TRUE)
})
if (return_message) {
list(
"Parsed ",
all_df %>% nrow() %>% formattable::comma(digits = 0),
' DTCC cleared trades from ',
all_df$dateData %>% min(na.rm = T),
' to ',
all_df$dateData %>% max(na.rm = T)
) %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
if (nest_data) {
all_df <-
all_df %>%
nest(-c(dateData, nameAsset), .key = dataDTCC)
}
return(all_df)
}
.get_dtcc_recent_schema_df <-
function() {
tibble(
idCSS = c(
'
'
'
'
'
'
'
'
'
),
nameAsset = c(
'commodities',
'commodities',
'credits',
'credits',
'equities',
'forex',
'forex',
'rates',
'rates'
),
urlData = c(
"https://kgc0418-tdw-data-0.s3.amazonaws.com/prices/COMMODITIES_SWAPS_PRICES.HTML",
"https://kgc0418-tdw-data-0.s3.amazonaws.com/prices/COMMODITIES_OPTIONS_PRICES.HTML",
"https://kgc0418-tdw-data-0.s3.amazonaws.com/prices/CREDITS_SWAPS_PRICES.HTML",
"https://kgc0418-tdw-data-0.s3.amazonaws.com/prices/CREDITS_OPTIONS_PRICES.HTML",
"https://kgc0418-tdw-data-0.s3.amazonaws.com/prices/EQUITIES_SWAPS_PRICES.HTML",
"https://kgc0418-tdw-data-0.s3.amazonaws.com/prices/FOREX_SWAPS_PRICES.HTML",
"https://kgc0418-tdw-data-0.s3.amazonaws.com/prices/FOREX_OPTIONS_PRICES.HTML",
"https://kgc0418-tdw-data-0.s3.amazonaws.com/prices/RATES_SWAPS_PRICES.HTML",
"https://kgc0418-tdw-data-0.s3.amazonaws.com/prices/RATES_OPTIONS_PRICES.HTML"
)
)
}
.parse_most_recent_url <-
function(url = "https://kgc0418-tdw-data-0.s3.amazonaws.com/prices/COMMODITIES_SWAPS_PRICES.HTML",
return_message = TRUE) {
css_df <-
.get_dtcc_recent_schema_df()
page <-
"https://kgc0418-tdw-data-0.s3.amazonaws.com/gtr/static/gtr/html/tracker.html" %>%
read_html()
id_css <-
css_df %>%
filter(urlData == url) %>%
.$idCSS
names_dtcc <-
page %>%
html_nodes(id_css) %>%
html_text()
page <-
url %>%
read_html()
df <-
page %>%
html_table(fill = F) %>%
flatten_df() %>%
purrr::set_names(names_dtcc)
df <-
df %>%
.resolve_dtcc_name_df() %>%
mutate(urlData = url,
datetimeData = Sys.time()) %>%
inner_join(css_df %>% select(urlData, nameAsset)) %>%
mutate(nameAsset = nameAsset %>% str_to_upper()) %>%
select(datetimeData, nameAsset, everything()) %>%
suppressMessages()
if (return_message) {
list("Parsed: ", url) %>%
purrr::invoke(paste0, .) %>% cat(fill = T)
}
return(df)
}
dtcc_recent_trades <-
function(assets = NULL,
nest_data = TRUE,
return_message = TRUE) {
assets <-
assets %>% str_to_lower()
css_df <-
.get_dtcc_recent_schema_df()
if (length(assets) > 0 ) {
assets_options <-
css_df$nameAsset %>% unique()
if (assets %>% str_to_lower() %in% assets_options %>% sum() == 0) {
stop(
list(
"Assets can only be:\n",
assets_options %>% paste0(collapse = '\n')
) %>%
purrr::invoke(paste0, .)
)
}
css_df <-
css_df %>%
filter(nameAsset %in% assets)
}
.parse_most_recent_url_safe <-
purrr::possibly(.parse_most_recent_url, tibble())
all_data <-
css_df$urlData %>%
future_map_dfr(function(x) {
.parse_most_recent_url(url = x, return_message = return_message)
}) %>%
select(which(colMeans(is.na(.)) < 1)) %>%
suppressMessages() %>%
suppressWarnings()
all_data <-
all_data %>%
.parse_for_underlying_asset() %>%
suppressWarnings() %>%
select(which(colMeans(is.na(.)) < 1))
if ('amountLevelOption' %in% names(all_data)) {
all_data <-
all_data %>%
mutate(amountLevelOption = amountLevelOption %>% as.character() %>% readr::parse_number())
}
if (return_message) {
list(
"Parsed ",
all_data %>% nrow() %>% formattable::comma(digits = 0),
' DTCC most recent cleared trades as of ',
Sys.time()
) %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
if (nest_data) {
all_data <-
all_data %>%
nest(-c(nameAsset, typeAction), .key = dataDTCC)
}
return(all_data)
}
.get_c_url_data <-
function(c_url = "curl 'https://rtdata.dtcc.com/gtr/dailySearch.do?action=dailySearchNextPage&dailySearchCurrentPage=10&dailySearchHasMore=yes&dailySearchMaxDailyNumber=49369457&displayType=c' -H 'DNT: 1' -H 'Accept-Encoding: gzip, deflate, sdch, br' -H 'Accept-Language: en-US,en;q=0.8' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.59 Safari/537.36' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Cookie: JSESSIONID_TDW01_Cluster=0000w-S0Gm-OK-9X7LvjnOgRFHE:1a9spvpvu' -H 'Connection: keep-alive' --compressed") {
clean_url <-
c_url %>%
curlconverter::straighten() %>%
suppressMessages()
res <-
clean_url %>%
make_req(add_clip = FALSE)
dtcc_df <-
res[[1]]() %>%
content(as = "parsed") %>%
as_tibble() %>%
suppressWarnings() %>%
suppressMessages()
if (dtcc_df %>% nrow() == 0) {
return(tibble())
}
dtcc_df <-
dtcc_df %>%
mutate_at(dtcc_df %>% select(
dplyr::matches(
"PRICE_NOTATION2|PRICE_NOTATION3|OPTION_EXPIRATION_DATE|OPTION_LOCK_PERIOD|OPTION_PREMIUM|ADDITIONAL_PRICE_NOTATION|ROUNDED_NOTIONAL_AMOUNT_1|ROUNDED_NOTIONAL_AMOUNT_2|OPTION_STRIKE_PRICE|ORIGINAL_DISSEMINATION_ID"
)
) %>% names(),
funs(. %>% as.character()))
return(dtcc_df)
}
.get_data_today <-
function(dtcc_url = "https://rtdata.dtcc.com/gtr/dailySearch.do?action=dailySearchNextPage&dailySearchCurrentPage=1&dailySearchHasMore=yes&dailySearchMaxDailyNumber=993694579&displayType=c") {
dtcc_url <-
list(
"curl '",
dtcc_url,
"' -H 'DNT: 1' -H 'Accept-Encoding: gzip, deflate, sdch, br' -H 'Accept-Language: en-US,en;q=0.8' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.59 Safari/537.36' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Cookie: JSESSIONID_TDW01_Cluster=0000w-S0Gm-OK-9X7LvjnOgRFHE:1a9spvpvu' -H 'Connection: keep-alive' --compressed"
) %>%
purrr::invoke(paste0, .)
.get_c_url_data_safe <-
purrr::possibly(.get_c_url_data, tibble())
data <-
dtcc_url %>%
.get_c_url_data_safe()
return(data)
}
.get_data_dtcc_today <-
function(assets = NULL,
nest_data = TRUE,
return_message = TRUE) {
date_data <-
Sys.Date() %>%
str_split('\\-') %>%
flatten_chr() %>% {
list(.[2], .[3], .[1]) %>% purrr::invoke(paste, ., sep = "%2F")
}
nameAsset <-
c('credits', 'commodities', 'equities', 'forex', 'rates')
types <-
c("CR", 'CO', 'EQ', 'FX', 'IR')
urls <-
list(
'https://rtdata.dtcc.com/gtr/dailySearch.do?action=dailySearch&disseminationDateLow=',
date_data,
'&disseminationDateHigh=',
date_data,
'&assetClassification=',
types,
'¬ionalRangeLow=0¬ionalRangeHigh=50000000000000&disseminationHourLow=0&disseminationMinuteLow=0&disseminationHourHigh=23&disseminationMinuteHigh=59¤cy=USD&displayType=c'
) %>%
purrr::invoke(paste0, .)
df_types <-
tibble(nameAsset, idAssetType = types,
urlData = urls) %>%
mutate(nameAsset = nameAsset %>% str_to_upper())
.get_data_today_safe <-
purrr::possibly(.get_data_today, tibble())
if (length(assets) == 0 | assets %>% length() > 0) {
assets <-
assets %>% str_to_upper()
assets_options <-
df_types$nameAsset %>% unique()
if (assets %>% str_to_upper() %in% assets_options %>% sum() == 0) {
stop(
list(
"Assets can only be:\n",
assets_options %>% paste0(collapse = '\n')
) %>%
purrr::invoke(paste0, .)
)
}
df_types <-
df_types %>%
filter(nameAsset %in% assets)
}
urls <-
df_types$urlData
all_data <-
urls %>%
sort(decreasing = T) %>%
future_map_dfr(function(x) {
.get_data_today(dtcc_url = x) %>%
mutate(urlData = x)
}) %>%
mutate(dateData = Sys.Date()) %>%
mutate_at(.vars = c('ORIGINAL_DISSEMINATION_ID'),
funs(. %>% as.numeric()))
if (all_data %>% nrow() == 0) {
return(all_data)
}
all_data <-
all_data %>%
.resolve_dtcc_name_df() %>%
.parse_for_underlying_asset() %>%
.resolve_taxonomy() %>%
mutate(dateData = Sys.Date()) %>%
left_join(df_types %>% select(-urlData)) %>%
suppressWarnings() %>%
mutate(nameAsset = nameAsset %>% str_to_upper()) %>%
select(idAssetType, nameAsset, everything()) %>%
suppressMessages()
all_data <-
all_data %>%
mutate_at(
all_data %>% select(dplyr::matches("^priceNotation")) %>% names(),
funs(. %>% as.character() %>% readr::parse_number())
)
if ('isCleared' %in% names(all_data)) {
all_data <-
all_data %>%
mutate(isCleared = ifelse(isCleared == "C", TRUE, FALSE))
}
if (return_message) {
list(
"Parsed ",
all_data %>% nrow() %>% formattable::comma(digits = 0),
' DTCC most recent cleared trades for ',
Sys.Date()
) %>%
purrr::invoke(paste0, .) %>%
cat(fill = T)
}
if (nest_data) {
all_data <-
all_data %>%
nest(-c(dateData, nameAsset), .key = dataDTCC)
}
return(all_data)
}
dtcc_trades <-
function(assets = NULL,
include_today = FALSE,
start_date = NULL,
end_date = NULL,
nest_data = TRUE,
return_message = TRUE) {
all_data <-
tibble()
if (length(assets) > 0) {
assets <-
assets %>% str_to_upper()
}
if (include_today) {
today <-
.get_data_dtcc_today(assets = assets,
nest_data = FALSE,
return_message = return_message)
if (today %>% nrow() > 0) {
today <-
today %>%
.resolve_dtcc_name_df() %>%
select(which(colMeans(is.na(.)) < 1))
today <-
today %>%
mutate_at(today %>% select(dplyr::matches(
"dateTime|idDisseminationOriginal|^date"
)) %>% names(),
funs(. %>% as.character())) %>%
mutate_at(today %>% select(dplyr::matches("^amount|priceOptionStrike")) %>% names(),
funs(. %>% as.numeric())) %>%
suppressWarnings()
all_data <-
all_data %>%
bind_rows(today)
}
}
if (length(start_date) > 0) {
if (length(end_date) == 0) {
end_date <-
Sys.Date()
}
data <-
.get_data_dtcc_assets_days(
assets = assets,
start_date = start_date,
end_date = end_date,
nest_data = FALSE,
return_message = return_message
)
data <-
data %>%
.resolve_dtcc_name_df() %>%
mutate_at(data %>% select(
dplyr::matches(
"^dateTime|idDisseminationOriginal|^date|^priceNotation"
)
) %>% names(),
funs(. %>% as.character()))
data <-
data %>%
mutate_at(
data %>% select(dplyr::matches("^priceNotation")) %>% names(),
funs(. %>% as.character() %>% readr::parse_number())
)
if (data %>% nrow() > 0) {
all_data <-
all_data %>%
bind_rows(data)
}
}
all_data <-
all_data %>%
mutate_at(all_data %>% select(dplyr::matches("^dateTime[A-Z]")) %>% names(),
funs(. %>% lubridate::ymd_hms())) %>%
mutate_at(
all_data %>% select(dplyr::matches("^date[A-Z]")) %>% select(-dplyr::matches("^dateTime")) %>% names(),
funs(. %>% lubridate::ymd())
) %>%
mutate_at(all_data %>% select(dplyr::matches("^idDissemination")) %>% names(),
funs(. %>% as.character() %>% as.integer())) %>%
suppressMessages() %>%
suppressWarnings()
if ('urlData' %in% names(all_data)) {
all_data <-
all_data %>%
select(-urlData)
}
if ('idAssetType' %in% names(all_data)) {
all_data <-
all_data %>%
select(-idAssetType)
}
all_data <-
all_data %>%
arrange(desc(idDissemination))
if (nest_data) {
all_data <-
all_data %>%
nest(-c(dateData, nameAsset), .key = dataDTCC)
}
return(all_data)
} |
recluster.boot <- function (tree,mat,phylo=NULL,tr=100,p=0.5,dist="simpson", method="average",boot=1000,level=1) {
mat<-as.matrix(mat)
if(length(tree$tip.label)!= nrow(mat))
stop("ERROR: different site numbers between tree and matrix")
treesb<-(as.phylo(hclust(recluster.dist(mat,phylo,dist),method=method)))
for (i in 1 : boot){
for (testNA in 1:10000){
xs<-mat[,sample(ncol(mat),ncol(mat)*level,replace=T)]
if(prod(rowSums(xs))>0){
break
}
}
treesb[[i]]<-recluster.cons(xs,phylo,tr,p,dist)$cons
}
btr2 <- .compressTipLabel(treesb)
tr2 <- recluster.check(tree, attr(btr2, "TipLabel"))
btr2 <- .uncompressTipLabel(btr2)
result <- prop.clades(tr2, btr2, rooted=T)*(100/boot)
rows<-nrow(mat)
matrix<-dist.nodes(tree)[(rows+1):(rows*2-1),(rows+1):(rows*2-1)]
for (i in 2 : (rows-1)) {
if(min(matrix[1:i-1,i])==0) {
result[i]<- NA
}
}
result<-as.matrix(result)
result
} |
gensvm.accuracy <- function(y.true, y.pred)
{
n <- length(y.true)
if (n != length(y.pred)) {
cat("Error: Can't compute accuracy if vector don't have the ",
"same length\n")
return(-1)
}
return (sum(y.true == y.pred) / n)
} |
DetMM<-function(x,y,intercept=1,alpha=0.75,h=NULL,scale_est="scaleTau2",tuning.chi=1.54764,tuning.psi=4.685061){
conv<-1
if(!is.numeric(tuning.chi)) stop("tuning.chi nust be a finite numeric or NULL.")
if(!is.finite(tuning.chi)) stop("tuning.chi nust be a finite numeric or NULL.")
if(tuning.chi<=0) stop("tuning.chi nust be a finite numeric or NULL.")
if(!is.numeric(tuning.psi)) stop("tuning.psi nust be a finite numeric or NULL.")
if(!is.finite(tuning.psi)) stop("tuning.psi nust be a finite numeric or NULL.")
if(tuning.psi<=0) stop("tuning.psi nust be a finite numeric or NULL.")
s1<-robustbase::lmrob.control()
s1$subsampling<-"simple"
s1$max.it<-1000
s1$k.max<-1000
s1$maxit.scale<-1000
niter.k<-2
S2<-DetLTS_raw(x=x,y=y,h=h,alpha=alpha,scale_est=scale_est,doCsteps=0)
S4<-S1<-vector("list",length(S2$Subset))
names(S4)<-names(S1)<-names(S2$Subset)
for(i in 1:length(which(S2$SubsetSize<nrow(x)))){
S4[[i]]<-fast.s(x=x,y=y,int=intercept,H1=S2$Raw,k=niter.k,b=1-S2$SubsetSize[i]/nrow(x),cc=tuning.chi,conv=conv)
names(S4[[i]])<-c('coef','scale')
s1$bb<-1-S2$SubsetSize[i]/nrow(x)
S1[[i]]<-robustbase::lmrob(y~x,control=s1,init=list(coefficients=S4[[i]][[1]],scale=S4[[i]][[2]]))
}
if(max(S2$SubsetSize)==nrow(x)){
i<-i+1
S4[[i]]<-S1[[i]]<-ordreg(x=x,y=y,intercept=intercept)
}
S3<-vector('list',2)
names(S3)<-c('DetS','DetMM')
S3[[1]]<-S4
S3[[2]]<-S1
return(S3)
} |
to_munich <- function (sdf, idbrin, typo, width, height, crs= 4326){
sdf <- sf::st_as_sf(sdf)
x <- sapply(sf::st_set_geometry(sdf, NULL), class)
if(any(x != "units")){
stop("All emissions must have units. Check ?units::set_units")
}
sdf$id <- NULL
if(missing(crs)) {
dft <- as.data.frame(sf::st_coordinates(sdf))
} else {
dft <- as.data.frame(sf::st_coordinates(sf::st_transform(sdf, crs)))
}
lista <- split(x = dft, f = dft$L1)
df <- do.call("rbind",(lapply(1:length(lista), function(i){
cbind(names(lista)[i], lista[[i]][1,], lista[[i]][2,])
})))
names(df) <- c("i", "xa", "ya", "borrar1", "xb", "yb", "borrar2")
if(missing(idbrin)) idbrin <- df$i
if(missing(typo)) typo <- rep(0, nrow(df))
if(missing(width)) width <- rep(0, nrow(df))
if(missing(height)) height <- rep(30, nrow(df))
dfa <- data.frame(i = df$i,
idbrin = idbrin,
typo = typo,
xa = df$xa,
ya = df$ya,
xb = df$xb,
yb = df$yb)
dfb <- sf::st_set_geometry(sdf, NULL)
dfr <- cbind(dfa, dfb)
dfr2 <- data.frame(i = dfa$i,
length = sf::st_length(sdf),
width,
height)
dfl <- list(Emissions = dfr,
Street = dfr2)
return(dfl)
} |
mnlfa_create_vector_with_names <- function( vec, val=0 )
{
NP <- length(vec)
res <- rep(val, NP)
names(res) <- vec
return(res)
} |
OLSv <-
function(data=NULL,xcol=1,ycol=2,conf.level=0.95,pred.level=0.95,npoints=1000,q=1,xpred=NULL)
{
if(length(conf.level) > 1) stop("Only one confidence level is allowed.")
if(length(pred.level) > 1) stop("Only one predictive level is allowed.")
if(conf.level <= 0 | conf.level >= 1) stop("The confidence level must be between 0 and 1 (excluded)")
if(pred.level <= 0 | pred.level >= 1) stop("The predictive level must be between 0 and 1 (excluded)")
if(length(npoints) > 1) stop("npoints must be an integer (at least 10)")
if(floor(npoints) != ceiling(npoints) | npoints < 10 | !is.numeric(npoints)) stop("npoints must be an integer (at least 10)")
if(length(q) > 1) stop("q must be an integer (at least 1)")
if(floor(q) != ceiling(q) | q < 1 | !is.numeric(q)) stop("q must be an integer (at least 1)")
if(!is.null(xpred) & !is.numeric(xpred)) stop("xpred must be numeric")
res=desc.stat(data=data,xcol=xcol,ycol=ycol)
x=res$Xi
y=res$Yi
xmean=res$statistics$Xmean
ymean=res$statistics$Ymean
Sxx=res$statistics$Sxx
Syy=res$statistics$Syy
Sxy=res$statistics$Sxy
n=res$statistics$N
slope_OLSv=Sxy/Sxx
intercept_OLSv=ymean-xmean*slope_OLSv
S2_OLSv=sum((y-intercept_OLSv-slope_OLSv*x)^2)/(n-2)
S_slope_OLSv=sqrt(S2_OLSv/Sxx)
S_intercept_OLSv=sqrt(S2_OLSv*(1/n+xmean^2/Sxx))
cov_slope_intercept_OLSv=-S2_OLSv*xmean/Sxx
cov_matrix_OLSv=matrix(nrow=2,ncol=2,c(S_slope_OLSv^2,cov_slope_intercept_OLSv,cov_slope_intercept_OLSv,S_intercept_OLSv^2))
Hotelling_correction=(2*(n-1))/(n-2)
ell_OLSv=ellipse(cov_matrix_OLSv,centre=c(slope_OLSv,intercept_OLSv),npoints=npoints, t = sqrt(qf(conf.level,2,n-2)*Hotelling_correction))
F1=matrix(nrow=1,ncol=2,c(slope_OLSv-1,intercept_OLSv))
F2=solve(cov_matrix_OLSv)
F3=t(F1)
Fell=F1%*%F2%*%F3
alpha=1-conf.level
CI_slope_OLSv_1=slope_OLSv-qt(1-alpha/2,n-2)*S_slope_OLSv
CI_slope_OLSv_2=slope_OLSv+qt(1-alpha/2,n-2)*S_slope_OLSv
CI_intercept_OLSv_1=intercept_OLSv-qt(1-alpha/2,n-2)*S_intercept_OLSv
CI_intercept_OLSv_2=intercept_OLSv+qt(1-alpha/2,n-2)*S_intercept_OLSv
pval_slope_OLSv=(1-pt(abs(slope_OLSv-1)/S_slope_OLSv,n-2))*2
pval_intercept_OLSv=(1-pt(abs(intercept_OLSv)/S_intercept_OLSv,n-2))*2
pval_ell_OLSv=1-pf(F1%*%F2%*%F3/Hotelling_correction,2,n-2)
rownames=c("Intercept","Slope","Joint")
name1=paste("Lower ",conf.level*100,"%CI",sep="")
name2=paste("Upper ",conf.level*100,"%CI",sep="")
colnames=c("H0","Estimate","Std Error",name1,name2,"pvalue")
Table.OLSv=as.data.frame(matrix(nrow=length(rownames),ncol=length(colnames),dimnames=list(rownames,colnames)))
Table.OLSv$H0=c("0","1","(0,1)")
Table.OLSv$Estimate=c(intercept_OLSv,slope_OLSv,"")
Table.OLSv$'Std Error'=c(S_intercept_OLSv,S_slope_OLSv,"")
Table.OLSv[,name1]=c(CI_intercept_OLSv_1,CI_slope_OLSv_1,"")
Table.OLSv[,name2]=c(CI_intercept_OLSv_2,CI_slope_OLSv_2,"")
Table.OLSv$pvalue=c(pval_intercept_OLSv,pval_slope_OLSv,pval_ell_OLSv)
xx=c(seq(min(x),max(x),length.out=npoints),xpred)
xx.pred=xx*slope_OLSv+intercept_OLSv
CI1=paste(conf.level*100,"% CI Lower",sep="")
CI2=paste(conf.level*100,"% CI Upper",sep="")
CB1=paste(conf.level*100,"% CB Lower",sep="")
CB2=paste(conf.level*100,"% CB Upper",sep="")
PI1=paste(pred.level*100,"% PI Lower",sep="")
PI2=paste(pred.level*100,"% PI Upper",sep="")
GI1=paste(pred.level*100,"% GI Lower",sep="")
GI2=paste(pred.level*100,"% GI Upper",sep="")
colnames=c("X0","Ypred",CI1,CI2,PI1,PI2,GI1,GI2,CB1,CB2)
if(is.null(xpred)) rownames=1:npoints else rownames=c(1:npoints,paste("xpred",1:length(xpred)))
data.pred=as.data.frame(matrix(nrow=npoints+length(xpred),ncol=length(colnames),dimnames=list(rownames,colnames)))
data.pred$X0=xx
data.pred$Ypred=xx.pred
alpha.pred=1-pred.level
data.pred[,CI1]=xx.pred-qt(1-alpha/2,n-2)*sqrt(S2_OLSv)*sqrt(1/n+(xx-xmean)^2/Sxx)
data.pred[,CI2]=xx.pred+qt(1-alpha/2,n-2)*sqrt(S2_OLSv)*sqrt(1/n+(xx-xmean)^2/Sxx)
data.pred[,PI1]=xx.pred-qt(1-alpha.pred/2,n-2)*sqrt(S2_OLSv)*sqrt(1+1/n+(xx-xmean)^2/Sxx)
data.pred[,PI2]=xx.pred+qt(1-alpha.pred/2,n-2)*sqrt(S2_OLSv)*sqrt(1+1/n+(xx-xmean)^2/Sxx)
data.pred[,GI1]=xx.pred-qt(1-alpha.pred/2,n-2)*sqrt(S2_OLSv)*sqrt(1/q+1/n+(xx-xmean)^2/Sxx)
data.pred[,GI2]=xx.pred+qt(1-alpha.pred/2,n-2)*sqrt(S2_OLSv)*sqrt(1/q+1/n+(xx-xmean)^2/Sxx)
data.pred[,CB1]=xx.pred-sqrt(qf(conf.level,2,n-2)*Hotelling_correction)*sqrt(S2_OLSv)*sqrt(1/n+(xx-xmean)^2/Sxx)
data.pred[,CB2]=xx.pred+sqrt(qf(conf.level,2,n-2)*Hotelling_correction)*sqrt(S2_OLSv)*sqrt(1/n+(xx-xmean)^2/Sxx)
results=list(ell_OLSv,Table.OLSv,data.pred[1:npoints,],data.pred[-(1:npoints),])
names(results)=c("Ellipse.OLSv","Estimate.OLSv","Pred.OLSv","xpred.OLSv")
return(results)
} |
spellTree_3 <-
function(letra = character(),
bandera = integer(),
left = integer(),
rigth = integer(),
center = integer(),
palabra = list()) {
tree <- list(ch = letra, flag = bandera, L = left, R = rigth, C = center, word = palabra)
class(tree) <- append(class(tree), "spellTree_3")
return(tree)
} |
ind.crsp <-
function(crsp, loc1, loc2)
{
nLoc <- length(crsp)
ind1 <- rep(0, length(loc1))
ind2 <- rep(0, length(loc2))
res <- .C("indCrsp",
as.integer(nLoc), as.integer(crsp), as.integer(loc1), as.integer(loc2),
as.integer(ind1), as.integer(ind2)
)
return(list(i1=res[[5]], i2=res[[6]]))
} |
gitcreds_get <- NULL
gitcreds_set <- NULL
gitcreds_delete <- NULL
gitcreds_list_helpers <- NULL
gitcreds_cache_envvar <- NULL
gitcreds_fill <- NULL
gitcreds_approve <- NULL
gitcreds_reject <- NULL
gitcreds_parse_output <- NULL
gitcreds <- local({
gitcreds_get <<- function(url = "https://github.com", use_cache = TRUE,
set_cache = TRUE) {
stopifnot(
is_string(url), has_no_newline(url),
is_flag(use_cache),
is_flag(set_cache)
)
cache_ev <- gitcreds_cache_envvar(url)
if (use_cache && !is.null(ans <- gitcreds_get_cache(cache_ev))) {
return(ans)
}
check_for_git()
out <- gitcreds_fill(list(url = url), dummy = TRUE)
creds <- gitcreds_parse_output(out, url)
if (set_cache) {
gitcreds_set_cache(cache_ev, creds)
}
creds
}
gitcreds_set <<- function(url = "https://github.com") {
if (!is_interactive()) {
throw(new_error(
"gitcreds_not_interactive_error",
message = "`gitcreds_set()` only works in interactive sessions"
))
}
stopifnot(is_string(url), has_no_newline(url))
check_for_git()
current <- tryCatch(
gitcreds_get(url, use_cache = FALSE, set_cache = FALSE),
gitcreds_no_credentials = function(e) NULL
)
if (!is.null(current)) {
gitcreds_set_replace(url, current)
} else {
gitcreds_set_new(url)
}
msg("-> Removing credentials from cache...")
gitcreds_delete_cache(gitcreds_cache_envvar(url))
msg("-> Done.")
invisible()
}
gitcreds_set_replace <- function(url, current) {
current_username <- current$username
while (!is.null(current)) {
if (!ack(url, current, "Replace")) {
throw(new_error("gitcreds_abort_replace_error"))
}
msg("\n-> Removing current credentials...")
gitcreds_reject(current)
current <- tryCatch(
gitcreds_get(url, use_cache = FALSE, set_cache = FALSE),
gitcreds_no_credentials = function(e) NULL
)
if (!is.null(current)) msg("\n!! Found more matching credentials!")
}
msg("")
pat <- readline("? Enter new password or token: ")
username <- get_url_username(url) %||%
gitcreds_username(url) %||%
current_username
msg("-> Adding new credentials...")
gitcreds_approve(list(url = url, username = username, password = pat))
invisible()
}
gitcreds_set_new <- function(url) {
msg("\n")
pat <- readline("? Enter password or token: ")
username <- get_url_username(url) %||%
gitcreds_username(url) %||%
default_username()
msg("-> Adding new credentials...")
gitcreds_approve(list(url = url, username = username, password = pat))
invisible()
}
gitcreds_delete <<- function(url = "https://github.com") {
if (!is_interactive()) {
throw(new_error(
"gitcreds_not_interactive_error",
message = "`gitcreds_delete()` only works in interactive sessions"
))
}
stopifnot(is_string(url))
check_for_git()
current <- tryCatch(
gitcreds_get(url, use_cache = FALSE, set_cache = FALSE),
gitcreds_no_credentials = function(e) NULL
)
if (is.null(current)) {
return(invisible(FALSE))
}
if (!ack(url, current, "Delete")) {
throw(new_error("gitcreds_abort_delete_error"))
}
msg("-> Removing current credentials...")
gitcreds_reject(current)
msg("-> Removing credentials from cache...")
gitcreds_delete_cache(gitcreds_cache_envvar(url))
msg("-> Done.")
invisible(TRUE)
}
gitcreds_list_helpers <<- function() {
check_for_git()
out <- git_run(c("config", "--get-all", "credential.helper"))
clear <- rev(which(out == ""))
if (length(clear)) out <- out[-(1:clear[1])]
out
}
gitcreds_cache_envvar <<- function(url) {
pcs <- parse_url(url)
bad <- is.na(pcs$protocol) | is.na(pcs$host)
if (any(bad)) {
stop("Invalid URL(s): ", paste(url[bad], collapse = ", "))
}
proto <- sub("^https?_$", "", paste0(pcs$protocol, "_"))
user <- ifelse(pcs$username != "", paste0(pcs$username, "_AT_"), "")
host0 <- sub("^api[.]github[.]com$", "github.com", pcs$host)
host1 <- gsub("[.:]+", "_", host0)
host <- gsub("[^a-zA-Z0-9_-]", "x", host1)
slug1 <- paste0(proto, user, host)
slug2 <- ifelse(grepl("^AT_", slug1), paste0("AT_", slug1), slug1)
slug3 <- ifelse(grepl("^[0-9]", slug2), paste0("AT_", slug2), slug2)
paste0("GITHUB_PAT_", toupper(slug3))
}
gitcreds_get_cache <- function(ev) {
val <- Sys.getenv(ev, NA_character_)
if (is.na(val) && ev == "GITHUB_PAT_GITHUB_COM") {
val <- Sys.getenv("GITHUB_PAT", NA_character_)
}
if (is.na(val) && ev == "GITHUB_PAT_GITHUB_COM") {
val <- Sys.getenv("GITHUB_TOKEN", NA_character_)
}
if (is.na(val) || val == "") {
return(NULL)
}
if (val == "FAIL" || grepl("^FAIL:", val)) {
class <- strsplit(val, ":", fixed = TRUE)[[1]][2]
if (is.na(class)) class <- "gitcreds_no_credentials"
throw(new_error(class))
}
unesc <- function(x) {
gsub("\\\\(.)", "\\1", x)
}
spval <- strsplit(val, "(?<!\\\\):", perl = TRUE)[[1]]
spval0 <- unesc(spval)
if (length(spval) == 1) {
return(new_gitcreds(
protocol = NA_character_,
host = NA_character_,
username = NA_character_,
password = unesc(val)
))
}
if (length(spval) == 2) {
return(new_gitcreds(
protocol = NA_character_,
host = NA_character_,
username = spval0[1],
password = spval0[2]
))
}
if (length(spval) %% 2 == 1) {
warning("Invalid gitcreds credentials in env var `", ev, "`. ",
"Maybe an unescaped ':' character?")
return(NULL)
}
creds <- structure(
spval0[seq(2, length(spval0), by = 2)],
names = spval[seq(1, length(spval0), by = 2)]
)
do.call("new_gitcreds", as.list(creds))
}
gitcreds_set_cache <- function(ev, creds) {
esc <- function(x) gsub(":", "\\:", x, fixed = TRUE)
keys <- esc(names(creds))
vals <- esc(unlist(creds, use.names = FALSE))
value <- paste0(keys, ":", vals, collapse = ":")
do.call("set_env", list(structure(value, names = ev)))
invisible(NULL)
}
gitcreds_delete_cache <- function(ev) {
Sys.unsetenv(ev)
}
gitcreds_fill <<- function(input, args = character(), dummy = TRUE) {
if (dummy) {
helper <- paste0(
"credential.helper=\"! echo protocol=dummy;",
"echo host=dummy;",
"echo username=dummy;",
"echo password=dummy\""
)
args <- c(args, "-c", helper)
}
gitcreds_run("fill", input, args)
}
gitcreds_approve <<- function(creds, args = character()) {
gitcreds_run("approve", creds, args)
}
gitcreds_reject <<- function(creds, args = character()) {
gitcreds_run("reject", creds, args)
}
gitcreds_parse_output <<- function(txt, url) {
if (is.null(txt) || txt[1] == "protocol=dummy") {
throw(new_error("gitcreds_no_credentials", url = url))
}
nms <- sub("=.*$", "", txt)
vls <- sub("^[^=]+=", "", txt)
structure(as.list(vls), names = nms, class = "gitcreds")
}
gitcreds_run <- function(command, input, args = character()) {
env <- gitcreds_env()
oenv <- set_env(env)
on.exit(set_env(oenv), add = TRUE)
stdin <- create_gitcreds_input(input)
git_run(c(args, "credential", command), input = stdin)
}
git_run <- function(args, input = NULL) {
stderr_file <- tempfile("gitcreds-stderr-")
on.exit(unlink(stderr_file, recursive = TRUE), add = TRUE)
out <- tryCatch(
suppressWarnings(system2(
"git", args, input = input, stdout = TRUE, stderr = stderr_file
)),
error = function(e) NULL
)
if (!is.null(attr(out, "status")) && attr(out, "status") != 0) {
throw(new_error(
"git_error",
args = args,
stdout = out,
status = attr(out, "status"),
stderr = read_file(stderr_file)
))
}
out
}
ack <- function(url, current, what = "Replace") {
msg("\n-> Your current credentials for ", squote(url), ":\n")
msg(paste0(format(current, header = FALSE), collapse = "\n"), "\n")
choices <- c(
"Keep these credentials",
paste(what, "these credentials"),
if (has_password(current)) "See the password / token"
)
repeat {
ch <- utils::menu(title = "-> What would you like to do?", choices)
if (ch == 1) return(FALSE)
if (ch == 2) return(TRUE)
msg("\nCurrent password: ", current$password, "\n\n")
}
}
has_password <- function(creds) {
is_string(creds$password) && creds$password != ""
}
create_gitcreds_input <- function(args) {
paste0(
paste0(names(args), "=", args, collapse = "\n"),
"\n\n"
)
}
gitcreds_env <- function() {
c(
GCM_INTERACTIVE = "Never",
GCM_MODAL_PROMPT = "false",
GCM_VALIDATE = "false"
)
}
check_for_git <- function() {
has_git <- tryCatch({
suppressWarnings(system2(
"git", "--version",
stdout = TRUE, stderr = null_file()
))
TRUE
}, error = function(e) FALSE)
if (!has_git) throw(new_error("gitcreds_nogit_error"))
}
gitcreds_username <- function(url = NULL) {
gitcreds_username_for_url(url) %||% gitcreds_username_generic()
}
gitcreds_username_for_url <- function(url) {
if (is.null(url)) return(NULL)
tryCatch(
git_run(c(
"config", "--get-urlmatch", "credential.username", shQuote(url)
)),
git_error = function(err) {
if (err$status == 1) NULL else throw(err)
}
)
}
gitcreds_username_generic <- function() {
tryCatch(
git_run(c("config", "credential.username")),
git_error = function(err) {
if (err$status == 1) NULL else throw(err)
}
)
}
default_username <- function() {
"PersonalAccessToken"
}
new_gitcreds <- function(...) {
structure(list(...), class = "gitcreds")
}
gitcred_errors <- function() {
c(
git_error = "System git failed",
gitcreds_nogit_error = "Could not find system git",
gitcreds_not_interactive_error = "gitcreds needs an interactive session",
gitcreds_abort_replace_error = "User aborted updating credentials",
gitcreds_abort_delete_error = "User aborted deleting credentials",
gitcreds_no_credentials = "Could not find any credentials",
gitcreds_no_helper = "No credential helper is set",
gitcreds_multiple_helpers =
"Multiple credential helpers, only using the first",
gitcreds_unknown_helper = "Unknown credential helper, cannot list credentials"
)
}
new_error <- function(class, ..., message = "", call. = TRUE, domain = NULL) {
if (message == "") message <- gitcred_errors()[[class]]
message <- .makeMessage(message, domain = domain)
cond <- list(message = message, ...)
if (call.) cond$call <- sys.call(-1)
class(cond) <- c(class, "gitcreds_error", "error", "condition")
cond
}
new_warning <- function(class, ..., message = "", call. = TRUE, domain = NULL) {
if (message == "") message <- gitcred_errors()[[class]]
message <- .makeMessage(message, domain = domain)
cond <- list(message = message, ...)
if (call.) cond$call <- sys.call(-1)
class(cond) <- c(class, "gitcreds_warning", "warning", "condition")
cond
}
throw <- function(cond) {
cond
if ("error" %in% class(cond)) {
stop(cond)
} else if ("warning" %in% class(cond)) {
warning(cond)
} else if ("message" %in% class(cond)) {
message(cond)
} else {
signalCondition(cond)
}
}
set_env <- function(envs) {
current <- Sys.getenv(names(envs), NA_character_, names = TRUE)
na <- is.na(envs)
if (any(na)) {
Sys.unsetenv(names(envs)[na])
}
if (any(!na)) {
do.call("Sys.setenv", as.list(envs[!na]))
}
invisible(current)
}
get_url_username <- function(url) {
nm <- parse_url(url)$username
if (nm == "") NULL else nm
}
parse_url <- function(url) {
re_url <- paste0(
"^(?<protocol>[a-zA-Z0-9]+)://",
"(?:(?<username>[^@/:]+)(?::(?<password>[^@/]+))?@)?",
"(?<host>[^/]+)",
"(?<path>.*)$"
)
mch <- re_match(url, re_url)
mch[, setdiff(colnames(mch), c(".match", ".text")), drop = FALSE]
}
is_string <- function(x) {
is.character(x) && length(x) == 1 && !is.na(x)
}
is_flag <- function(x) {
is.logical(x) && length(x) == 1 && !is.na(x)
}
has_no_newline <- function(url) {
! grepl("\n", url, fixed = TRUE)
}
re_match <- function(text, pattern, perl = TRUE, ...) {
stopifnot(is.character(pattern), length(pattern) == 1, !is.na(pattern))
text <- as.character(text)
match <- regexpr(pattern, text, perl = perl, ...)
start <- as.vector(match)
length <- attr(match, "match.length")
end <- start + length - 1L
matchstr <- substring(text, start, end)
matchstr[ start == -1 ] <- NA_character_
res <- data.frame(
stringsAsFactors = FALSE,
.text = text,
.match = matchstr
)
if (!is.null(attr(match, "capture.start"))) {
gstart <- attr(match, "capture.start")
glength <- attr(match, "capture.length")
gend <- gstart + glength - 1L
groupstr <- substring(text, gstart, gend)
groupstr[ gstart == -1 ] <- NA_character_
dim(groupstr) <- dim(gstart)
res <- cbind(groupstr, res, stringsAsFactors = FALSE)
}
names(res) <- c(attr(match, "capture.names"), ".text", ".match")
res
}
null_file <- function() {
if (get_os() == "windows") "nul:" else "/dev/null"
}
get_os <- function() {
if (.Platform$OS.type == "windows") {
"windows"
} else if (Sys.info()[["sysname"]] == "Darwin") {
"macos"
} else if (Sys.info()[["sysname"]] == "Linux") {
"linux"
} else {
"unknown"
}
}
`%||%` <- function(l, r) if (is.null(l)) r else l
msg <- function(..., domain = NULL, appendLF = TRUE) {
cnd <- .makeMessage(..., domain = domain, appendLF = appendLF)
withRestarts(muffleMessage = function() NULL, {
signalCondition(simpleMessage(cnd))
output <- default_output()
cat(cnd, file = output, sep = "")
})
invisible()
}
default_output <- function() {
if (is_interactive() && no_active_sink()) stdout() else stderr()
}
no_active_sink <- function() {
sink.number("output") == 0 && sink.number("message") == 2
}
is_interactive <- function() {
opt <- getOption("rlib_interactive")
opt2 <- getOption("rlang_interactive")
if (isTRUE(opt)) {
TRUE
} else if (identical(opt, FALSE)) {
FALSE
} else if (isTRUE(opt2)) {
TRUE
} else if (identical(opt2, FALSE)) {
FALSE
} else if (tolower(getOption("knitr.in.progress", "false")) == "true") {
FALSE
} else if (identical(Sys.getenv("TESTTHAT"), "true")) {
FALSE
} else {
base::interactive()
}
}
squote <- function(x) {
old <- options(useFancyQuotes = FALSE)
on.exit(options(old), add = TRUE)
sQuote(x)
}
read_file <- function(path, ...) {
readChar(path, nchars = file.info(path)$size, ...)
}
environment()
}) |
knitr::opts_chunk$set(message=FALSE, error=FALSE, warning=FALSE, comment=NA)
savefigs <- FALSE
library("rprojroot")
root<-has_file(".ROS-Examples-root")$make_fix_file()
library("rstanarm")
library("arm")
library("ggplot2")
library("bayesplot")
theme_set(bayesplot::theme_default(base_family = "sans"))
hibbs <- read.table(root("ElectionsEconomy/data","hibbs.dat"), header=TRUE)
head(hibbs)
if (savefigs) pdf(root("ElectionsEconomy/figs","hibbsdots.pdf"), height=4.5, width=7.5, colormodel="gray")
n <- nrow(hibbs)
par(mar=c(0,0,1.2,0))
left <- -.3
right <- -.28
center <- -.07
f <- .17
plot(c(left-.31,center+.23), c(-3.3,n+3), type="n", bty="n", xaxt="n", yaxt="n", xlab="", ylab="", xaxs="i", yaxs="i")
mtext("Forecasting elections from the economy", 3, 0, cex=1.2)
with(hibbs, {
for (i in 1:n){
ii <- order(growth)[i]
text(left-.3, i, paste (inc_party_candidate[ii], " vs. ", other_candidate[ii], " (", year[ii], ")", sep=""), adj=0, cex=.8)
points(center+f*(vote[ii]-50)/10, i, pch=20)
if (i>1){
if (floor(growth[ii]) != floor(growth[order(growth)[i-1]])){
lines(c(left-.3,center+.22), rep(i-.5,2), lwd=.5, col="darkgray")
}
}
}
})
lines(center+f*c(-.65,1.3), rep(0,2), lwd=.5)
for (tick in seq(-.5,1,.5)){
lines(center + f*rep(tick,2), c(0,-.2), lwd=.5)
text(center + f*tick, -.5, paste(50+10*tick,"%",sep=""), cex=.8)
}
lines(rep(center,2), c(0,n+.5), lty=2, lwd=.5)
text(center+.05, n+1.5, "Incumbent party's share of the popular vote", cex=.8)
lines(c(center-.088,center+.19), rep(n+1,2), lwd=.5)
text(right, n+1.5, "Income growth", adj=.5, cex=.8)
lines(c(right-.05,right+.05), rep(n+1,2), lwd=.5)
text(right, 16.15, "more than 4%", cex=.8)
text(right, 14, "3% to 4%", cex=.8)
text(right, 10.5, "2% to 3%", cex=.8)
text(right, 7, "1% to 2%", cex=.8)
text(right, 3.5, "0% to 1%", cex=.8)
text(right, .85, "negative", cex=.8)
text(left-.3, -2.3, "Above matchups are all listed as incumbent party's candidate vs.\ other party's candidate.\nIncome growth is a weighted measure over the four years preceding the election. Vote share excludes third parties.", adj=0, cex=.7)
if (savefigs) dev.off()
if (savefigs) pdf(root("ElectionsEconomy/figs","hibbsscatter.pdf"), height=4.5, width=5, colormodel="gray")
par(mar=c(3,3,2,.1), mgp=c(1.7,.5,0), tck=-.01)
plot(c(-.7, 4.5), c(43,63), type="n", xlab="Avg recent growth in personal income", ylab="Incumbent party's vote share", xaxt="n", yaxt="n", mgp=c(2,.5,0), main="Forecasting the election from the economy ", bty="l")
axis(1, 0:4, paste(0:4,"%",sep=""), mgp=c(2,.5,0))
axis(2, seq(45,60,5), paste(seq(45,60,5),"%",sep=""), mgp=c(2,.5,0))
with(hibbs, text(growth, vote, year, cex=.8))
abline(50, 0, lwd=.5, col="gray")
if (savefigs) dev.off()
M1 <- stan_glm(vote ~ growth, data = hibbs, refresh = 0)
print(M1)
prior_summary(M1)
summary(M1)
round(posterior_interval(M1),1)
if (savefigs) pdf(root("ElectionsEconomy/figs","hibbsline.pdf"), height=4.5, width=5, colormodel="gray")
par(mar=c(3,3,2,.1), mgp=c(1.7,.5,0), tck=-.01)
plot(c(-.7, 4.5), c(43,63), type="n", xlab="Average recent growth in personal income", ylab="Incumbent party's vote share", xaxt="n", yaxt="n", mgp=c(2,.5,0), main="Data and linear fit", bty="l")
axis(1, 0:4, paste(0:4,"%",sep=""), mgp=c(2,.5,0))
axis(2, seq(45,60,5), paste(seq(45,60,5),"%",sep=""), mgp=c(2,.5,0))
with(hibbs, points(growth, vote, pch=20))
abline(50, 0, lwd=.5, col="gray")
abline(coef(M1), col="gray15")
text(2.7, 53.5, paste("y =", fround(coef(M1)[1],1), "+", fround(coef(M1)[2],1), "x"), adj=0, col="gray15")
if (savefigs) dev.off()
if (savefigs) pdf(root("ElectionsEconomy/figs","hibbspredict.pdf"), height=3.5, width=6.5, colormodel="gray")
par(mar=c(3,3,3,1), mgp=c(1.7,.5,0), tck=-.01)
mu <- 52.3
sigma <- 3.9
curve (dnorm(x,mu,sigma), ylim=c(0,.103), from=35, to=70, bty="n",
xaxt="n", yaxt="n", yaxs="i",
xlab="Clinton share of the two-party vote", ylab="",
main="Probability forecast of Hillary Clinton vote share in 2016,\nbased on 2% rate of economic growth", cex.main=.9)
x <- seq (50,65,.1)
polygon(c(min(x),x,max(x)), c(0,dnorm(x,mu,sigma),0),
col="darkgray", border="black")
axis(1, seq(40,65,5), paste(seq(40,65,5),"%",sep=""))
text(50.7, .025, "Predicted\n72% chance\nof Clinton victory", adj=0)
if (savefigs) dev.off()
if (savefigs) pdf(root("ElectionsEconomy/figs","hibbsline2a.pdf"), height=4.5, width=5, colormodel="gray")
par(mar=c(3,3,2,.1), mgp=c(1.7,.5,0), tck=-.01)
plot(c(-.7, 4.5), c(43,63), type="n", xlab="x", ylab="y", xaxt="n", yaxt="n", mgp=c(2,.5,0), main="Data and linear fit", bty="l", cex.lab=1.3, cex.main=1.3)
axis(1, 0:4, cex.axis=1.3)
axis(2, seq(45, 60, 5), cex.axis=1.3)
abline(coef(M1), col="gray15")
with(hibbs, points(growth, vote, pch=20))
text(2.7, 53.5, paste("y =", fround(coef(M1)[1],1), "+", fround(coef(M1)[2],1), "x"), adj=0, col="gray15", cex=1.3)
if (savefigs) dev.off()
if (savefigs) pdf(root("ElectionsEconomy/figs","hibbsline2b.pdf"), height=4.5, width=5, colormodel="gray")
par(mar=c(3,3,2,.1), mgp=c(1.7,.5,0), tck=-.01)
plot(c(-.7, 4.5), c(43,63), type="n", xlab="x", ylab="y", xaxt="n", yaxt="n", mgp=c(2,.5,0), main="Data and range of possible linear fits", bty="l", cex.lab=1.3, cex.main=1.3)
axis(1, 0:4, cex.axis=1.3)
axis(2, seq(45, 60, 5), cex.axis=1.3)
sims <- as.matrix(M1)
n_sims <- nrow(sims)
for (s in sample(n_sims, 50))
abline(sims[s,1], sims[s,2], col="gray50", lwd=0.5)
with(hibbs, points(growth, vote, pch=20))
if (savefigs) dev.off()
sims <- as.matrix(M1)
a <- sims[,1]
b <- sims[,2]
sigma <- sims[,3]
n_sims <- nrow(sims)
Median <- apply(sims, 2, median)
MAD_SD <- apply(sims, 2, mad)
print(cbind(Median, MAD_SD))
a <- sims[,1]
b <- sims[,2]
z <- a/b
print(median(z))
print(mad(z))
new <- data.frame(growth=2.0)
y_point_pred <- predict(M1, newdata=new)
a_hat <- coef(M1)[1]
b_hat <- coef(M1)[2]
y_point_pred <- a_hat + b_hat*as.numeric(new)
y_linpred <- posterior_linpred(M1, newdata=new)
a <- sims[,1]
b <- sims[,2]
y_linpred <- a + b*as.numeric(new)
y_pred <- posterior_predict(M1, newdata=new)
sigma <- sims[,3]
n_sims <- nrow(sims)
y_pred <- a + b*as.numeric(new) + rnorm(n_sims, 0, sigma)
Median <- median(y_pred)
MAD_SD <- mad(y_pred)
win_prob <- mean(y_pred > 50)
cat("Predicted Clinton percentage of 2-party vote: ", round(Median,1),
", with s.e. ", round(MAD_SD, 1), "\nPr (Clinton win) = ", round(win_prob, 2),
sep="")
hist(y_pred)
new_grid <- data.frame(growth=seq(-2.0, 4.0, 0.5))
y_point_pred_grid <- predict(M1, newdata=new_grid)
y_linpred_grid <- posterior_linpred(M1, newdata=new_grid)
y_pred_grid <- posterior_predict(M1, newdata=new_grid)
if (savefigs) pdf(root("ElectionsEconomy/figs","hibbspredict_bayes_1.pdf"), height=4, width=10, colormodel="gray")
par(mfrow=c(1,2), mar=c(3,2,3,0), mgp=c(1.5,.5,0), tck=-.01)
hist(a, ylim=c(0,0.25*n_sims), xlab="a", ylab="", main="Posterior simulations of the intercept, a,\nand posterior median +/- 1 and 2 std err", cex.axis=.9, cex.lab=.9, yaxt="n", col="gray90")
abline(v=median(a), lwd=2)
arrows(median(a) - 1.483*median(abs(a - median(a))), 550, median(a) + 1.483*median(abs(a - median(a))), 550, length=.1, code=3, lwd=2)
arrows(median(a) - 2*1.483*median(abs(a - median(a))), 250, median(a) + 2*1.483*median(abs(a - median(a))), 250, length=.1, code=3, lwd=2)
hist(b, ylim=c(0,0.27*n_sims), xlab="b", ylab="", main="Posterior simulations of the slope, b,\nand posterior median +/- 1 and 2 std err", cex.axis=.9, cex.lab=.9, yaxt="n", col="gray90")
abline(v=median(b), lwd=2)
arrows(median(b) - 1.483*median(abs(b - median(b))), 550, median(b) + 1.483*median(abs(b - median(b))), 550, length=.1, code=3, lwd=2)
arrows(median(b) - 2*1.483*median(abs(b - median(b))), 250, median(b) + 2*1.483*median(abs(b - median(b))), 250, length=.1, code=3, lwd=2)
if (savefigs) dev.off()
if (savefigs) pdf(root("ElectionsEconomy/figs","hibbspredict_bayes_2a.pdf"), height=4.5, width=5)
par(mar=c(3,3,2,.1), mgp=c(1.7,.5,0), tck=-.01)
plot(a, b, xlab="a", ylab="b", main="Posterior draws of the regression coefficients a, b ", bty="l", pch=20, cex=.2)
if (savefigs) dev.off()
ggplot(data.frame(a = sims[, 1], b = sims[, 2]), aes(a, b)) +
geom_point(size = 1) +
labs(title = "Posterior draws of the regression coefficients a, b")
if (savefigs) pdf(root("ElectionsEconomy/figs","hibbspredict_bayes_2b.pdf"), height=4.5, width=5, colormodel="gray")
par(mar=c(3,3,2,.1), mgp=c(1.7,.5,0), tck=-.01)
plot(c(-.7, 4.5), c(43,63), type="n", xlab="Average recent growth in personal income", ylab="Incumbent party's vote share", xaxt="n", yaxt="n", mgp=c(2,.5,0), main="Data and 100 posterior draws of the line, y = a + bx ", bty="l")
axis(1, 0:4, paste(0:4,"%",sep=""), mgp=c(2,.5,0))
axis(2, seq(45,60,5), paste(seq(45,60,5),"%",sep=""), mgp=c(2,.5,0))
for (i in 1:100){
abline(a[i], b[i], lwd=.5)
}
abline(50, 0, lwd=.5, col="gray")
with(hibbs, {
points(growth, vote, pch=20, cex=1.7, col="white")
points(growth, vote, pch=20)
})
if (savefigs) dev.off()
ggplot(hibbs, aes(x = growth, y = vote)) +
geom_abline(
intercept = sims[1:100, 1],
slope = sims[1:100, 2],
size = 0.1
) +
geom_abline(
intercept = mean(sims[, 1]),
slope = mean(sims[, 2])
) +
geom_point(color = "white", size = 3) +
geom_point(color = "black", size = 2) +
labs(
x = "Avg recent growth in personal income",
y ="Incumbent party's vote share",
title = "Data and 100 posterior draws of the line, y = a + bx"
) +
scale_x_continuous(
limits = c(-.7, 4.5),
breaks = 0:4,
labels = paste(0:4, "%", sep = "")
) +
scale_y_continuous(
limits = c(43, 63),
breaks = seq(45, 60, 5),
labels = paste(seq(45, 60, 5), "%", sep = "")
)
x <- rnorm(n_sims, 2.0, 0.3)
y_hat <- a + b*x
y_pred <- rnorm(n_sims, y_hat, sigma)
Median <- median(y_pred)
MAD_SD <- 1.483*median(abs(y_pred - median(y_pred)))
win_prob <- mean(y_pred > 50)
cat("Predicted Clinton percentage of 2-party vote: ", round(Median, 1), ",
with s.e. ", round(MAD_SD, 1), "\nPr (Clinton win) = ", round(win_prob, 2), sep="", "\n")
if (savefigs) pdf(root("ElectionsEconomy/figs","hibbspredict_bayes_3.pdf"), height=3.5, width=6)
par(mar=c(3,3,3,1), mgp=c(1.7,.5,0), tck=-.01)
hist(y_pred, breaks=seq(floor(min(y_pred)), ceiling(max(y_pred)),1), xlim=c(35,70), xaxt="n", yaxt="n", yaxs="i", bty="n",
xlab="Clinton share of the two-party vote", ylab="",
main="Bayesian simulations of Hillary Clinton vote share,\nbased on 2% rate of economic growth")
axis(1, seq(40,65,5), paste(seq(40,65,5),"%",sep=""))
if (savefigs) dev.off()
qplot(y_pred, binwidth = 1) +
labs(
x ="Clinton share of the two-party vote",
title = "Simulations of Hillary Clinton vote share,\nbased on 2% rate of economic growth"
) +
theme(axis.line.y = element_blank())
theta_hat_prior <- 0.524
se_prior <- 0.041
n <- 400
y <- 190
theta_hat_data <- y/n
se_data <- sqrt((y/n)*(1-y/n)/n)
theta_hat_bayes <-
(theta_hat_prior / se_prior^2 + theta_hat_data / se_data^2) /
(1 / se_prior^2 + 1 / se_data^2)
se_bayes <- sqrt(1/(1/se_prior^2 + 1/se_data^2))
se_data <- .075
print((theta_hat_prior/se_prior^2 + theta_hat_data/se_data^2)/(1/se_prior^2 + 1/se_data^2))
M1a <- lm(vote ~ growth, data=hibbs)
print(M1a)
summary(M1a) |
isurvdiff.smax <- function(formula,...,verbose=FALSE,accuracy=0.05,smax=12) {
s <- 0
if(verbose) print(paste('Trying s=',s))
out <- isurvdiff(formula, ...,s=s, display=FALSE)
if (out$h==2) {
s=-1
return(list("s"=s,"test0"=out))
}
ds <- 3
while(out$h!=2 && s<smax) {
s <- s + ds
if(verbose) print(paste('Trying s=',s))
test0 <- out
out <- isurvdiff(formula, ...,s=s, display=FALSE)
}
if(out$h!=2) {
return(list("s"=s,"test0"=out))
}
mins <- s-ds
maxs <- s
while(mins < maxs - accuracy) {
s <- (mins+maxs)/2
if(verbose) print(paste('Trying s=',s))
out <- isurvdiff(formula, ...,s=s,display=FALSE)
if (out$h==2) maxs <- s
else {
mins <- s
test0 <- out
}
}
return(list("s"=mins, "test0"=test0))
} |
context("build_output")
describe("build_output", {
source("helper.R")
it("status available", {
output <- c("line 1", "\n", "line 2")
attr(output, "status") <- 15
script_output <- scriptexec::build_output(output, wait = TRUE)
expect_equal(script_output$status, 15)
expect_equal(script_output$output, "line 1\nline 2")
expect_true(is.null(attr(script_output, "error")))
})
it("status null wait", {
output <- c("line 1", "\n", "line 2")
script_output <- scriptexec::build_output(output, wait = TRUE)
expect_equal(script_output$status, 0)
expect_equal(script_output$output, "line 1\nline 2")
expect_true(is.null(attr(script_output, "error")))
})
it("status null nowait", {
output <- c("line 1", "\n", "line 2")
script_output <- scriptexec::build_output(output, wait = FALSE)
expect_equal(script_output$status, -1)
expect_equal(script_output$output, "line 1\nline 2")
expect_true(is.null(attr(script_output, "error")))
})
it("errmsg", {
output <- c("line 1", "\n", "line 2")
attr(output, "errmsg") <- "error message"
script_output <- scriptexec::build_output(output, wait = TRUE)
expect_equal(script_output$status, 0)
expect_equal(script_output$output, "line 1\nline 2")
expect_equal(script_output$error, "error message")
})
}) |
NULL
chisq_test <- function(x, y = NULL, correct = TRUE,
p = rep(1/length(x), length(x)), rescale.p = FALSE,
simulate.p.value = FALSE, B = 2000){
args <- as.list(environment()) %>%
add_item(method = "chisq_test")
if(is.data.frame(x)) x <- as.matrix(x)
if(inherits(x, c("matrix", "table"))) n <- sum(x)
else n <- length(x)
res.chisq <- stats::chisq.test(
x, y, correct = correct, p = p, rescale.p = rescale.p,
simulate.p.value = simulate.p.value, B = B
)
as_tidy_stat(res.chisq, stat.method = "Chi-square test") %>%
add_significance("p") %>%
add_columns(n = n, .before = 1) %>%
set_attrs(args = args, test = res.chisq) %>%
add_class(c("rstatix_test", "chisq_test"))
}
pairwise_chisq_gof_test <- function(x, p.adjust.method = "holm", ...){
if(is.null(names(x))){
names(x) <- paste0("grp", 1:length(x))
}
compare_pair <- function(levs, x, ...){
levs <- as.character(levs)
suppressWarnings(chisq_test(x[levs], ...)) %>%
add_columns(group1 = levs[1], group2 = levs[2], .before = "statistic")
}
args <- as.list(environment()) %>%
add_item(method = "chisq_test")
comparisons <- names(x) %>%
.possible_pairs()
results <- comparisons %>%
map(compare_pair, x, ...) %>%
map(keep_only_tbl_df_classes) %>%
bind_rows() %>%
adjust_pvalue("p", method = p.adjust.method) %>%
add_significance("p.adj") %>%
mutate(p.adj = signif(.data$p.adj, digits = 3)) %>%
select(-.data$p.signif, -.data$method)
results %>%
set_attrs(args = args) %>%
add_class(c("rstatix_test", "chisq_test"))
}
pairwise_chisq_test_against_p <- function(x, p = rep(1/length(x), length(x)), p.adjust.method = "holm", ...){
args <- as.list(environment()) %>%
add_item(method = "chisq_test")
if (sum(p) != 1) {
stop(
"Make sure that the `p` argument is correctly specified.",
"sum of probabilities must be 1."
)
}
if(is.null(names(x))){
names(x) <- paste0("grp", 1:length(x))
}
results <- list()
for (i in 1:length(x)) {
res.chisq <- suppressWarnings(chisq_test(c(x[i], sum(x) - x[i]), p = c(p[i], 1 - p[i]), ...))
res.desc <- chisq_descriptives(res.chisq)
res.chisq <- res.chisq %>%
add_columns(observed = res.desc$observed[1], expected = res.desc$expected[1], .before = 1)
results[[i]] <- res.chisq
}
results <- results %>%
map(keep_only_tbl_df_classes) %>%
bind_rows() %>%
add_columns(group = names(x), .before = 1) %>%
adjust_pvalue("p", method = p.adjust.method) %>%
add_significance("p.adj") %>%
mutate(p.adj = signif(.data$p.adj, digits = 3)) %>%
select(-.data$p.signif, -.data$method)
results %>%
set_attrs(args = args) %>%
add_class(c("rstatix_test", "chisq_test"))
}
chisq_descriptives <- function(res.chisq){
res <- attr(res.chisq, "test") %>% augment()
colnames(res) <- gsub(pattern = "^\\.", replacement = "", colnames(res))
res
}
expected_freq <- function(res.chisq){
attr(res.chisq, "test")$expected
}
observed_freq <- function(res.chisq){
attr(res.chisq, "test")$observed
}
pearson_residuals <- function(res.chisq){
attr(res.chisq, "test")$residuals
}
std_residuals <- function(res.chisq){
attr(res.chisq, "test")$stdres
} |
test_that("Test Data Handling", {
expect_true(all(samples_modis_4bands[1:3, ]$label %in% c("Pasture")))
expect_true(sum(sits_labels_summary(samples_modis_4bands)$prop) == 1)
expect_true(all(sits_bands(samples_modis_4bands) %in%
c("NDVI", "EVI", "MIR", "NIR")))
}) |
pnn.optmiz_logl <- function(net, lower = 0, upper, nfolds = 4, seed = 1, method = 1) {
if (class(net) != "Probabilistic Neural Net") stop("net needs to be a PNN object.", call. = F)
if (!(method %in% c(1, 2))) stop("the method is not supported.", call. = F)
fd <- folds(seq(nrow(net$x)), n = nfolds, seed = seed)
cv <- function(s) {
cls <- parallel::makeCluster(min(nfolds, parallel::detectCores() - 1), type = "PSOCK")
obj <- c("fd", "net", "pnn.fit", "pnn.predone", "pnn.predict", "dummies", "logl")
parallel::clusterExport(cls, obj, envir = environment())
rs <- Reduce(rbind,
parallel::parLapply(cls, fd,
function(f) data.frame(ya = net$y.ind[f, ],
yp = pnn.predict(pnn.fit(net$x[-f, ], net$y.raw[-f], sigma = s),
net$x[f, ]))))
parallel::stopCluster(cls)
return(logl(y_pred = as.matrix(rs[, grep("^yp", names(rs))]),
y_true = as.matrix(rs[, grep("^ya", names(rs))])))
}
if (method == 1) {
rst <- optimize(f = cv, interval = c(lower, upper))
} else if (method == 2) {
rst <- optim(par = mean(lower, upper), fn = cv, lower = lower, upper = upper, method = "Brent")
}
return(data.frame(sigma = rst[[1]], logl = rst[[2]]))
} |
makeRLearner.regr.cubist = function() {
makeRLearnerRegr(
cl = "regr.cubist",
package = "Cubist",
par.set = makeParamSet(
makeIntegerLearnerParam(id = "committees", default = 1L, lower = 1L, upper = 100L),
makeLogicalLearnerParam(id = "unbiased", default = FALSE),
makeIntegerLearnerParam(id = "rules", default = 100L, lower = 1L),
makeNumericLearnerParam(id = "extrapolation", default = 100, lower = 0, upper = 100),
makeIntegerLearnerParam(id = "sample", default = 0L, lower = 0L),
makeIntegerLearnerParam(id = "seed", default = sample.int(4096, size = 1) - 1L, tunable = FALSE),
makeUntypedLearnerParam(id = "label", default = "outcome"),
makeIntegerLearnerParam(id = "neighbors", default = 0L, lower = 0L, upper = 9L, when = "predict")
),
properties = c("missings", "numerics", "factors"),
name = "Cubist",
short.name = "cubist",
callees = c("cubist", "cubistControl", "predict.cubist")
)
}
trainLearner.regr.cubist = function(.learner, .task, .subset, .weights = NULL, unbiased, rules,
extrapolation, sample, seed, label, ...) {
ctrl = learnerArgsToControl(Cubist::cubistControl, unbiased, rules, extrapolation, sample, seed, label)
d = getTaskData(.task, .subset, target.extra = TRUE)
Cubist::cubist(x = d$data, y = d$target, control = ctrl, ...)
}
predictLearner.regr.cubist = function(.learner, .model, .newdata, ...) {
predict(.model$learner.model, newdata = .newdata, ...)
} |
test_that("label can be missing", {
case <- textpathGrob(x = c(0, 1), y = c(0, 1), id = c(1, 1), as_label = TRUE)
ctrl <- textpathGrob(x = c(0, 1), y = c(0, 1), id = c(1, 1), label = "ABC",
as_label = TRUE)
expect_null(case$textpath)
expect_type(ctrl$textpath, "list")
case <- makeContent(case)
ctrl <- makeContent(ctrl)
expect_s3_class(case, "zeroGrob")
expect_s3_class(ctrl, "gTree")
test <- textpathGrob(
x = c(0, 1), y = c(0, 1), id = c(1, 1), label = "ABC",
polar_params = list(x = 0.5, y = 0.5), as_label = TRUE
)
ppar <- test$textpath$params$polar_params
expect_equal(convertUnit(ppar$x, "npc", valueOnly = TRUE), 0.5)
expect_equal(convertUnit(ppar$y, "npc", valueOnly = TRUE), 0.5)
})
test_that("straight and curved setting produce similar boxes", {
pth <- textpathGrob(
"ABC",
x = c(0, 1),
y = c(0, 1),
id = c(1, 1),
gp_box = gpar(fill = "white"),
as_label = TRUE
)
pth <- makeContent(pth)
box1 <- pth$children[[2]]
pth <- textpathGrob(
"ABC",
x = c(0, 1),
y = c(0, 1),
id = c(1, 1),
gp_box = gpar(fill = "white"),
straight = TRUE,
as_label = TRUE
)
pth <- makeContent(pth)
box2 <- pth$children[[2]]
x1 <- as_inch(box1$x)
x2 <- as_inch(box2$x)
expect_lt(sum(abs(x1 - x2)), 2)
y1 <- as_inch(box1$y)
y2 <- as_inch(box2$y)
expect_lt(sum(abs(y1 - y2)), 2)
})
test_that("radius is shrunk when needed", {
pth <- textpathGrob(
"ABC",
x = c(2.5, 7.5),
y = c(5, 5),
id = c(1, 1),
gp_box = gpar(fill = "white"),
default.units = "in",
label.r = unit(0.1, "inch"),
label.padding = unit(0, "inch"),
as_label = TRUE
)
attr(pth$textpath$label[[1]], "metrics")$height <- 0.2
pth <- makeContent(pth)
box1 <- pth$children[[2]]
pth <- textpathGrob(
"ABC",
x = c(2.5, 7.5),
y = c(5, 5),
id = c(1, 1),
gp_box = gpar(fill = "white"),
default.units = "in",
label.r = unit(1, "inch"),
label.padding = unit(0, "inch"),
as_label = TRUE
)
attr(pth$textpath$label[[1]], "metrics")$height <- 0.2
pth <- makeContent(pth)
box2 <- pth$children[[2]]
expect_equal(as_inch(box1$x), as_inch(box2$x), tolerance = 1e-4)
expect_equal(as_inch(box1$y), as_inch(box2$y), tolerance = 1e-4)
})
test_that("straight richtext is similar to richtext on straight path", {
labels <- c(
"A<span style='color:blue'>B</span>C",
"D\nE<br>F"
)
x <- c(0, 1, 0, 1)
y <- c(0, 1, 1, 0)
id <- c(1, 1, 2, 2)
ctrl <- textpathGrob(x = x, y = y, id = id,
label = labels, rich = TRUE,
default.units = "inch", as_label = TRUE)
case <- textpathGrob(x = x, y = y, id = id,
label = labels, rich = TRUE, straight = TRUE,
default.units = "inch", as_label = TRUE)
ctrl <- makeContent(ctrl)$children[[2]]
case <- makeContent(case)$children[[2]]
expect_equal(ctrl$gp, case$gp)
expect_equal(ctrl$x, case$x, tolerance = 0.05)
expect_equal(ctrl$y, case$y, tolerance = 0.05)
expect_equal(ctrl$label, case$label)
})
test_that("We can set blank lines", {
gp <- data_to_path_gp(data.frame(linetype = NA))
expect_equal(gp$lty, 0)
})
test_that("We can remove labels too long for the path to support", {
grob <- textpathGrob(label = "A label that is too long for its path",
x = c(0.45, 0.55), y = c(0.5, 0.5), id = c(1, 1),
default.units = "npc", remove_long = TRUE,
as_label = TRUE)
grob <- makeContent(grob)
expect_equal(class(grob$children[[1]])[1], "polyline")
}) |
CIbeta <- function(m,alpha=0.95)
{
if(!is.momentuHMM(m))
stop("'m' must be a momentuHMM object (as output by fitHMM)")
if(!is.null(m$conditions$fit) && !m$conditions$fit)
stop("The given model hasn't been fitted.")
if(alpha<0 | alpha>1)
stop("alpha needs to be between 0 and 1.")
nbStates <- length(m$stateNames)
dist <- m$conditions$dist
distnames <- names(dist)
fullDM <- m$conditions$fullDM
m <- delta_bc(m)
reForm <- formatRecharge(nbStates,m$conditions$formula,m$conditions$betaRef,m$data,par=m$mle)
recharge <- reForm$recharge
covs <- reForm$covs
nbCovs <- reForm$nbCovs
if(!is.null(m$mod$hessian) && !inherits(m$mod$Sigma,"error")) Sigma <- m$mod$Sigma
else Sigma <- NULL
p <- parDef(dist,nbStates,m$conditions$estAngleMean,m$conditions$zeroInflation,m$conditions$oneInflation,m$conditions$DM,m$conditions$userBounds)
bounds <- p$bounds
ncmean <- get_ncmean(distnames,fullDM,m$conditions$circularAngleMean,nbStates)
nc <- ncmean$nc
meanind <- ncmean$meanind
tmPar <- lapply(m$mle[distnames],function(x) c(t(x)))
parCount<- lapply(fullDM,ncol)
for(i in distnames[!unlist(lapply(m$conditions$circularAngleMean,isFALSE))]){
parCount[[i]] <- length(unique(gsub("cos","",gsub("sin","",colnames(fullDM[[i]])))))
}
parindex <- c(0,cumsum(unlist(parCount))[-length(fullDM)])
names(parindex) <- distnames
quantSup <- qnorm(1-(1-alpha)/2)
wpar <- m$mod$estimate
Par <- list()
for(i in distnames){
est <- w2wn(wpar[parindex[[i]]+1:parCount[[i]]],m$conditions$workBounds[[i]])
pnames <- colnames(fullDM[[i]])
if(!isFALSE(m$conditions$circularAngleMean[[i]])) pnames <- unique(gsub("cos","",gsub("sin","",pnames)))
Par[[i]] <- get_CIwb(wpar[parindex[[i]]+1:parCount[[i]]],est,parindex[[i]]+1:parCount[[i]],Sigma,alpha,m$conditions$workBounds[[i]],cnames=pnames)
}
mixtures <- m$conditions$mixtures
if(nbStates>1){
est <- w2wn(wpar[tail(cumsum(unlist(parCount)),1)+1:((nbCovs+1)*nbStates*(nbStates-1)*mixtures)],m$conditions$workBounds$beta)
Par$beta <- get_CIwb(wpar[tail(cumsum(unlist(parCount)),1)+1:((nbCovs+1)*nbStates*(nbStates-1)*mixtures)],est,tail(cumsum(unlist(parCount)),1)+1:((nbCovs+1)*nbStates*(nbStates-1)*mixtures),Sigma,alpha,m$conditions$workBounds$beta,rnames=rownames(m$mle$beta),cnames=colnames(m$mle$beta))
Par$beta <- lapply(Par$beta,function(x) matrix(x[c(m$conditions$betaCons)],dim(x),dimnames=list(rownames(x),colnames(x))))
nbCovsDelta <- ncol(m$covsDelta)-1
}
if(mixtures>1){
nbCovsPi <- ncol(m$covsPi)-1
piInd <- tail(cumsum(unlist(parCount)),1) + ((nbCovs+1)*nbStates*(nbStates-1)*mixtures) + 1:((nbCovsPi+1)*(mixtures-1))
est <- w2wn(wpar[piInd],m$conditions$workBounds[["pi"]])
Par[["pi"]] <- get_CIwb(wpar[piInd],est,piInd,Sigma,alpha,m$conditions$workBounds[["pi"]],rnames=colnames(m$covsPi),cnames=paste0("mix",2:mixtures))
}
if(nbStates>1 & !m$conditions$stationary){
dInd <- length(wpar)-ifelse(reForm$nbRecovs,(reForm$nbRecovs+1)+(reForm$nbG0covs+1),0)
foo <- dInd -(nbCovsDelta+1)*(nbStates-1)*mixtures+1
est <- w2wn(wpar[foo:dInd],m$conditions$workBounds$delta)
rnames <- rep(colnames(m$covsDelta),mixtures)
if(mixtures>1) rnames <- paste0(rep(colnames(m$covsDelta),mixtures),"_mix",rep(1:mixtures,each=length(colnames(m$covsDelta))))
Par$delta <- get_CIwb(wpar[foo:dInd],est,foo:dInd,Sigma,alpha,m$conditions$workBounds$delta,rnames=rnames,cnames=m$stateNames[-1])
}
if(!is.null(recharge)){
ind <- tail(cumsum(unlist(parCount)),1)+(nbCovs+1)*nbStates*(nbStates-1)+(nbCovsDelta+1)*(nbStates-1)+1:(reForm$nbG0covs+1)
est <- w2wn(wpar[ind],m$conditions$workBounds$g0)
Par$g0 <- get_CIwb(wpar[ind],est,ind,Sigma,alpha,m$conditions$workBounds$g0,rnames="[1,]",cnames=colnames(reForm$g0covs))
ind <- tail(cumsum(unlist(parCount)),1)+(nbCovs+1)*nbStates*(nbStates-1)+(nbCovsDelta+1)*(nbStates-1)+reForm$nbG0covs+1+1:(reForm$nbRecovs+1)
est <- w2wn(wpar[ind],m$conditions$workBounds$theta)
Par$theta <- get_CIwb(wpar[ind],est,ind,Sigma,alpha,m$conditions$workBounds$theta,rnames="[1,]",cnames=colnames(reForm$recovs))
}
return(Par)
}
get_gradwb<-function(wpar,workBounds){
ind1<-which(is.finite(workBounds[,1]) & is.infinite(workBounds[,2]))
ind2<-which(is.finite(workBounds[,1]) & is.finite(workBounds[,2]))
ind3<-which(is.infinite(workBounds[,1]) & is.finite(workBounds[,2]))
dN <- diag(length(wpar))
dN[cbind(ind1,ind1)] <- exp(wpar[ind1])
dN[cbind(ind2,ind2)] <- (workBounds[ind2,2]-workBounds[ind2,1])*exp(wpar[ind2])/(1+exp(wpar[ind2]))^2
dN[cbind(ind3,ind3)] <- exp(-wpar[ind3])
dN
}
get_CIwb<-function(wpar,Par,ind,Sigma,alpha,workBounds,rnames="[1,]",cnames){
npar <- length(wpar)
bRow <- (rnames=="[1,]")
lower<-upper<-se<-rep(NA,npar)
if(!is.null(Sigma)){
dN <- get_gradwb(wpar,workBounds)
se <- suppressWarnings(sqrt(diag(dN%*%Sigma[ind,ind]%*%t(dN))))
lower <- Par - qnorm(1-(1-alpha)/2) * se
upper <- Par + qnorm(1-(1-alpha)/2) * se
}
est<-matrix(Par,ncol=length(cnames),byrow=bRow)
l<-matrix(lower,ncol=length(cnames),byrow=bRow)
u<-matrix(upper,ncol=length(cnames),byrow=bRow)
s<-matrix(se,ncol=length(cnames),byrow=bRow)
beta_parm_list(est,s,l,u,rnames,cnames)
}
beta_parm_list<-function(est,se,lower,upper,rnames,cnames){
Par <- list(est=est,se=se,lower=lower,upper=upper)
rownames(Par$est) <- rownames(Par$se) <- rownames(Par$lower) <- rownames(Par$upper) <- rnames
colnames(Par$est) <- cnames
colnames(Par$se) <- cnames
colnames(Par$lower) <- cnames
colnames(Par$upper) <- cnames
Par
} |
mixmat <-
function(p = 2)
{
a <- matrix(rnorm(p * p), p, p)
sa <- svd(a)
d <- sort(runif(p) + 1)
mat <- sa$u %*% (sa$v * d)
attr(mat, "condition") <- d[p]/d[1]
mat
} |
source('../gsDesign_independent_code.R')
x <- gsDesign(k = 5, test.type = 2, n.fix = 800)
pltobj <- plotgsZ(x)
test_that(
desc = "check the sample size",
code = {
nplot <- subset(pltobj$data, Bound == "Upper")$N
expect_equal(object = nplot, expected = x$n.I)
expect_lte(abs(nplot[1] - x$n.I[1]), 1e-6)
expect_lte(abs(nplot[2] - x$n.I[2]), 1e-6)
expect_lte(abs(nplot[3] - x$n.I[3]), 1e-6)
expect_lte(abs(nplot[4] - x$n.I[4]), 1e-6)
expect_lte(abs(nplot[5] - x$n.I[5]), 1e-6)
}
)
zlow <- subset(pltobj$data, Bound == "Lower")$Z
expectedlowb <- x$lower$bound
test_that(
desc = "check Z values for lower boundary",
code = {
expect_lte(abs(zlow[1] - expectedlowb[1]), 1e-6)
expect_lte(abs(zlow[2] - expectedlowb[2]), 1e-6)
expect_lte(abs(zlow[3] - expectedlowb[3]), 1e-6)
expect_lte(abs(zlow[4] - expectedlowb[4]), 1e-6)
expect_lte(abs(zlow[5] - expectedlowb[5]), 1e-6)
}
)
zup <- subset(pltobj$data, Bound == "Upper")$Z
expectedupb <- x$upper$bound
test_that(
desc = "check Z value for upper boundary",
code = {
expect_lte(abs(zup[1] - expectedupb[1]), 1e-6)
expect_lte(abs(zup[2] - expectedupb[2]), 1e-6)
expect_lte(abs(zup[3] - expectedupb[3]), 1e-6)
expect_lte(abs(zup[4] - expectedupb[4]), 1e-6)
expect_lte(abs(zup[5] - expectedupb[5]), 1e-6)
}
)
test_that("Test plotgsZ graphs are correctly rendered ", {
save_plot_obj <- save_gg_plot(plotgsZ(x))
local_edition(3)
expect_snapshot_file(save_plot_obj, "plot_plotgsz_1.png")
}) |
svg.images <- function(file, corners, name = gsub('[.][A-Za-z]+$', '', tail(strsplit(file[1], '/')[[1]], 1)),
seg = 2, opacity = 1, ontop = FALSE, times = NULL){
if('svg' == getOption("svgviewr_glo_type")) stop("Image plotting is currently only available with webgl svgViewR output.")
if('html' == getOption("svgviewr_glo_type")) stop('Image plotting is currently only available with server-based visualization.')
env <- as.environment(getOption("svgviewr_glo_env"))
input_params <- mget(names(formals()),sys.frame(sys.nframe()))
input_params$type <- gsub('svg[.]', '', input_params$fcn)
add_at <- length(svgviewr_env$svg$image)+1
if(!file.exists(file[1])) stop(paste0("File '", file[1], "' not found."))
if(file.info(file[1])$isdir) file <- paste0(file[1], '/', list.files(file[1]))
input_params$fname <- rep(NA, length(file))
for(i in 1:length(file)){
if(!file.exists(file[i])) stop(paste0('Input file "', file[i], '" not found.'))
if(!grepl('[.](jpeg|jpg)$', file[i])) stop(paste0('Input file "', file[i], '" is of unrecognized file type. Currently only jpeg files are allowed.'))
input_params$fname[i] <- tail(strsplit(file[i], '/')[[1]], 1)
}
file_norm <- normalizePath(path=file[1])
file_norm_split <- strsplit(file_norm, '/')[[1]]
input_params$src <- ''
if(length(file_norm_split) > 1) input_params$src <- paste0(paste0(file_norm_split[1:(length(file_norm_split)-1)], collapse='/'), '/')
if(length(seg) == 1) seg <- rep(seg, 2)
if(!is.null(times) && length(file) > 1){
if(is.null(svgviewr_env$svg$animate$times)) svgviewr_env$svg$animate$times <- times
}
plane_mesh <- create_plane_mesh(corners, seg, create.uvs=TRUE)
vertices <- plane_mesh$vertices
faces <- plane_mesh$faces
uvs <- plane_mesh$uvs
input_params[['opacity']] <- setNames(opacity, NULL)
input_params[['depthTest']] <- !ontop
svgviewr_env$svg$image[[add_at]] <- input_params
svgviewr_env$svg$image[[add_at]]$vertices <- t(vertices)
svgviewr_env$svg$image[[add_at]]$faces <- t(faces)
svgviewr_env$svg$image[[add_at]]$uvs <- t(uvs)
svgviewr_env$ref$names <- c(svgviewr_env$ref$names, name)
svgviewr_env$ref$num <- c(svgviewr_env$ref$num, add_at)
svgviewr_env$ref$type <- c(svgviewr_env$ref$type, 'image')
obj_ranges <- apply(corners, 2, 'range', na.rm=TRUE)
corners <- lim2corners(obj_ranges)
svgviewr_env$svg$image[[add_at]][['lim']] <- obj_ranges
svgviewr_env$svg$image[[add_at]][['corners']] <- corners
ret = NULL
} |
c(
output$Mod2Step1_plot_alligator <- renderPlot({
t <- input$Mod2Step1_temperature
prop <- ifelse(t < 30, 0,
ifelse(t > 33, 1, (t-30)/(33-30)))
dat <- data.frame("Sex" = c("Female", "Male"),
"Proportion" = c(1-prop, prop))
ggplot2::ggplot(data=dat, aes(x=Sex, y=Proportion)) +
ggplot2::geom_col(width=0.3) +
ggplot2::ylim(0,1)
}),
output$Mod2Step1_plot_coin_flip <- renderPlot({
if(input$Mod2Step1_Refresh_1 == 0){}
size <- input$Mod2Step1_n_offspring
prop <- rbinom(n=1, size=size, prob=0.5) / size
dat <- data.frame("Sex" = c("Female", "Male"),
"Proportion" = c(1-prop, prop))
ggplot2::ggplot(data=dat, aes(x=Sex, y=Proportion)) +
ggplot2::geom_col(width=0.3) +
ggplot2::ylim(0,1) +
ggplot2::geom_hline(yintercept=0.5, color="red", linetype="dashed")
}),
output$Mod2Step1_plot_female_prob <- renderPlot({
if(input$Mod2Step1_Refresh_2 == 0){}
f_prob <- input$Mod2Step1_female_probability
prop <- rbinom(n=1, size=100, prob=f_prob) / 100
dat <- data.frame("Sex" = c("Female", "Male"),
"Proportion" = c(prop, 1-prop))
ggplot2::ggplot(data=dat, aes(x=Sex, y=Proportion)) +
ggplot2::geom_col(width=0.3) +
ggplot2::ylim(0,1) +
ggplot2::geom_hline(yintercept=f_prob, color="red", linetype="dashed")
}),
output$Mod2Step1_plot_female_hist <- renderPlot({
size <- input$Mod2Step1_n_offspring_2
prob <- input$Mod2Step1_female_probability_2
prop <- rbinom(n=1000, size=size, prob=prob) / size
dat <- data.frame("Proportion" = prop)
ggplot2::ggplot(data=dat, aes(x=Proportion)) +
ggplot2::geom_histogram(binwidth=0.1) +
ggplot2::xlim(-0.1,1.1) +
ggplot2::ylim(0, 1000) +
ggplot2::xlab("Female proportion") +
ggplot2::geom_vline(xintercept=prob, color="red", linetype="dashed")
}),
output$Mod2Step1_plot_count_hist <- renderPlot({
rate <- input$Mod2Step1_poisson_rate
counts <- rpois(n=1000, lambda=rate)
dat <- data.frame("Counts" = counts)
ggplot2::ggplot(data=dat, aes(x=Counts)) +
ggplot2::geom_histogram(binwidth=0.5) +
ggplot2::geom_vline(xintercept=rate, color="red", linetype="dashed")
})
) |
getArgs <- function() {
myargs.list <- strsplit(grep("=",gsub("--","",commandArgs()),value=TRUE),"=")
myargs <- lapply(myargs.list,function(x) x[2] )
names(myargs) <- lapply(myargs.list,function(x) x[1])
return (myargs)
} |
bin.fit.Cpp <- function(resp, design, kat, epsilon = 1e-05, penalty,
lambda, max.iter = 200, start = NULL, adaptive = NULL, norm = "L1",
control = list(c = 1e-06, gama = 20, index = NULL), m, hat.matrix = FALSE,
lambda2 = 1e-04) {
N <- length(resp)
q <- kat - 1
n <- N/q
acoefs <- penalty$acoefs
if (is.null(start)) {
start <- rep(0,ncol(design))
if(any(which(rowSums(abs(acoefs)) == 0))){
start[which(rowSums(abs(acoefs)) == 0)] <- coef(glm.fit(y = resp, x = design[,which(rowSums(abs(acoefs)) == 0)], family = binomial()))
}
if (any(is.na(start))) {
start[which(is.na(start))] <- 0
}
}
if (is.null(adaptive)) {
weight <- as.vector(rep(1, ncol(acoefs)))
} else {
weight <- abs(t(acoefs) %*% adaptive)
if (any(weight == 0))
weight[which(weight == 0)] <- epsilon
weight <- as.vector(weight^(-1))
}
pen.nums <- c(penalty$numpen.order, penalty$numpen.intercepts,
penalty$numpen.X, penalty$numpen.Z1, penalty$numpen.Z2)
if (sum(pen.nums) > 0) {
if (penalty$weight.penalties) {
pen.nums.scaled <- c(penalty$numpen.order/penalty$n.order,
penalty$numpen.intercepts/(m - 1), penalty$numpen.X/penalty$p.X/(m -
1), penalty$numpen.Z1/penalty$p.Z1/m, penalty$numpen.Z2/penalty$p.Z2)
weight <- weight/rep(pen.nums.scaled, pen.nums)
}
}
beta.old <- beta.new <- start
diff <- 1
delta.new <- delta.old <- 1
rcpp.out <- binfit(matrix(beta.new, ncol = 1), epsilon, max.iter,
acoefs, lambda, matrix(weight, ncol = 1), control, design,
N, n, q, matrix(resp, ncol = 1), control$index, control$c,
control$gama, norm, as.numeric(hat.matrix), lambda2)
beta.new <- rcpp.out$beta.new
start <- rcpp.out$start
df <- rcpp.out$df
df2 <- rcpp.out$df2
rownames(beta.new) <- names(start)
if (norm == "grouped") {
beta.pen <- matrix(beta.new[rowSums(acoefs) != 0], nrow = m -
1)
norm.col <- sqrt(colSums((beta.pen)^2))/(m - 1)
beta.pen[, norm.col < epsilon] <- 0
beta.new[rowSums(acoefs) != 0] <- c(beta.pen)
}
return(list(coefficients = beta.new, start = start, df = df, weight = weight, df2 = df2))
} |
qsr <- function(dataset,
ipuc = "ipuc",
hhcsw = "DB090",
hhsize = "HX040",
ci = NULL, rep = 1000, verbose = FALSE){
dataset <- dataset[order(dataset[,ipuc]), ]
dataset$wHX040 <- dataset[,hhcsw]*dataset[,hhsize]
if(is.null(ci)){
dataset$acum.wHX040 <- cumsum(dataset$wHX040)
dataset$abscisa2 <-
dataset$acum.wHX040/dataset$acum.wHX040[length(dataset$acum.wHX040)]
A <- dataset[,ipuc]*dataset$wHX040
uc.S20 <- sum(A[which(dataset$abscisa2 < 0.2)])
uc.S80 <- sum(A[which(dataset$abscisa2 > 0.8)])
qsr <- uc.S80/uc.S20
return(qsr)
}else{
qsr3 <- function(dataset, i){
dataset.boot <- dataset[i,]
dataset.boot <- dataset.boot[order(dataset.boot[,ipuc]), ]
dataset.boot$acum.wHX040 <- cumsum(dataset.boot$wHX040)
dataset.boot$abscisa2 <-
dataset.boot$acum.wHX040/dataset.boot$acum.wHX040[length(dataset.boot$acum.wHX040)]
A <- dataset.boot[,ipuc]*dataset.boot$wHX040
uc.S20 <- sum(A[which(dataset.boot$abscisa2 < 0.2)])
uc.S80 <- sum(A[which(dataset.boot$abscisa2 > 0.8)])
uc.S80/uc.S20
}
boot.qsr <- boot::boot(dataset, statistic = qsr3, R = rep,
sim = "ordinary", stype = "i")
qsr.ci <- boot::boot.ci(boot.qsr, conf = ci, type = "basic")
if(verbose == FALSE){
return(qsr.ci)
}else{
plot(boot.qsr)
summary(qsr.ci)
return(qsr.ci)
}
}
} |
plot_hierarchy_shape <-
function(identity, rank, winners, losers, fitted=FALSE) {
winners.rank <- rank[match(winners,identity)]
losers.rank <- rank[match(losers,identity)]
xx <- winners.rank-losers.rank
x <- 1:(max(abs(xx)))
y <- rep(NA,length(x))
CI.upper <- y
CI.lower <- y
for (i in 1:length(x)) {
y[i] <- sum(xx==-x[i])/sum(abs(xx)==x[i])
CI.upper[i] <- y[i] + sqrt(y[i]*(1-y[i])/sum(abs(xx)==x[i])) + 0.5/sum(abs(xx)==x[i])
CI.upper[i] <- min(CI.upper[i],1)
CI.lower[i] <- y[i] - sqrt(y[i]*(1-y[i])/sum(abs(xx)==x[i])) - 0.5/sum(abs(xx)==x[i])
CI.lower[i] <- max(CI.lower[i],0)
}
CI.upper <- CI.upper[!is.na(y)]
CI.lower <- CI.lower[!is.na(y)]
x <- x[!is.na(y)]
y <- y[!is.na(y)]
sizes <- sapply(x,function(x) { sum(abs(xx)==x)})
plot(x,y, xlab="Difference in rank", ylab="Probability that higher rank wins", ylim=c(min(0.5,min(y)),1), pch=20, cex=3*(sizes/max(sizes)))
arrows(x,CI.lower,x,CI.upper,length=0.1,angle=90,code=3, lwd=2*(sizes/max(sizes)))
legend("bottomright", pch=c(20,20,20,20),pt.cex=3*rev(c(0.2,0.4,0.6,0.8)),legend=rev(c(round(0.2*max(sizes)),round(0.4*max(sizes)),round(0.6*max(sizes)),round(0.8*max(sizes)))),title="Interactions")
if (fitted) {
l <- loess(y~x)
lines(x,l$fitted, col="red", lwd=2)
}
invisible(data.frame(Rank.diff=x,Prob.dom.win=y,CI.upper=CI.upper,CI.lower=CI.lower))
} |
library(grid)
eikos_x_probs <- function(data, xprobs = NULL, xprobs_size = 8,
margin = unit(2, "points"), rotate = TRUE) {
if(is.null(xprobs)) {
labels <- round(as.vector(unique(data$xmax[data$xmax < 1])), 2)
} else {
labels <- round(xprobs, 2)
}
probs <- if(length(labels) > 0) {
if(rotate) {
textGrob(labels, x = labels, y = margin,
gp = gpar(fontsize = xprobs_size),
just = "left", rot = 90,
name = "x probs")
} else {
textGrob(labels, x = labels, y = unit(0.5, "npc") + 0.5*margin,
gp = gpar(fontsize = xprobs_size), just = "center",
name = "x probs")
}
} else nullGrob(name = "null: no x probs")
return(probs)
}
eikos_y_probs <- function(data, yprobs, yprobs_size = 8, margin = unit(2, "points")) {
if(is.null(yprobs)) {
labels <- round(as.vector(unique(data$ymax[data$ymax < 1])), 2)
} else {
labels <- round(yprobs, 2)
}
probs <- if(length(labels) > 0) {
textGrob(labels, y = labels, x = margin,
gp = gpar(fontsize = yprobs_size),
just = "left",
name = "y probs")
} else nullGrob(name = "null: no y probs")
return(probs)
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(shinybusy)
knitr::include_graphics(path = "figures/add_busy_spinner.png")
knitr::include_graphics(path = "figures/add_busy_bar.png")
knitr::include_graphics(path = "figures/add_busy_gif.png")
knitr::include_graphics(path = "figures/modal_spinner.png")
knitr::include_graphics(path = "figures/modal_progress.png") |
"MacroTS" |
ibd.length = function(inher.hap1, inher.hap2, startpos = NULL, endpos = NULL){
n1 = nrow(inher.hap1)
n2 = nrow(inher.hap2)
if(is.null(startpos)){
startpos = 0
}
if(is.null(endpos)){
endpos = inher.hap1[n1,2]
}
if(startpos < 0 || endpos > inher.hap1[n1,2] || startpos > endpos){
stop("Check starting and ending genetic positions.")
}
index1 = 1
index2 = 1
relatedness = 0
ibd = 0
while(index1 <= n1 && index2 <= n2){
if(inher.hap1[index1,2] < startpos){
index1 = index1 + 1
next
}else if(inher.hap2[index2,2] < startpos){
index2 = index2 + 1
next
}
if(inher.hap1[index1,1] == inher.hap2[index2,1]){
ibd = 1
}else{
ibd = 0
}
if(inher.hap1[index1,2] >= endpos && inher.hap2[index2,2] >= endpos){
relatedness = relatedness + ibd * (endpos - startpos)
break
}else{
if(inher.hap1[index1,2] < inher.hap2[index2,2]){
relatedness = relatedness + ibd * (inher.hap1[index1,2] - startpos)
startpos = inher.hap1[index1,2]
index1 = index1 + 1
}else{
relatedness = relatedness + ibd * (inher.hap2[index2,2] - startpos)
startpos = inher.hap2[index2,2]
index2 = index2 + 1
}
}
}
return(as.numeric(relatedness))
}
ibd.proportion = function(inheritance, ind1index, ind2index = NULL, startpos = NULL, endpos = NULL){
if(is.null(startpos)){
startpos = 0
}
if(is.null(endpos)){
endpos = tail(c(inheritance[[1]]), 1)
}
seglength = endpos - startpos
if(is.null(ind2index)){
proportion = ibd.length(inheritance[[2*ind1index-1]], inheritance[[2*ind1index]], startpos, endpos)/seglength
}else{
proportion = (ibd.length(inheritance[[2*ind1index-1]], inheritance[[2*ind2index-1]], startpos, endpos) + ibd.length(inheritance[[2*ind1index-1]], inheritance[[2*ind2index]], startpos, endpos) + ibd.length(inheritance[[2*ind1index]], inheritance[[2*ind2index-1]], startpos, endpos) + ibd.length(inheritance[[2*ind1index]], inheritance[[2*ind2index]], startpos, endpos)) / 2 / seglength
}
return(proportion)
}
fgl2ibd = function(fgl1p, fgl1m, fgl2p, fgl2m){
if(fgl1p == fgl1m){
if(fgl2p == fgl2m){
if(fgl1p ==fgl2p){
ibdstate = 1
}else{
ibdstate = 4
}
}else{
if(fgl1p == fgl2p){
ibdstate = 2
}else if(fgl1p == fgl2m){
ibdstate = 3
}else{
ibdstate = 5
}
}
}else{
if(fgl2p == fgl2m){
if(fgl1p == fgl2p){
ibdstate = 6
}else if(fgl1m == fgl2p){
ibdstate = 10
}else{
ibdstate = 14
}
}else{
if(fgl1p == fgl2p){
if(fgl1m == fgl2m){
ibdstate = 7
}else{
ibdstate = 8
}
}else if(fgl1p == fgl2m){
if(fgl1m == fgl2p){
ibdstate = 9
}else{
ibdstate = 12
}
}else{
if(fgl1m == fgl2p){
ibdstate = 11
}else if(fgl1m == fgl2m){
ibdstate = 13
}else{
ibdstate = 15
}
}
}
}
return(ibdstate)
}
fgl2relatedness = function(fgl1p, fgl1m, fgl2p, fgl2m){
relatedness = ((fgl1p == fgl2p) + (fgl1p == fgl2m) + (fgl1m == fgl2p) + (fgl1m == fgl2m))/2
return(relatedness)
}
ibd.segment = function(inheritance, ind1index, ind2index = NULL, relatedness = TRUE){
ibd = NULL
startpos = 0
endpos = NULL
if(is.null(ind2index)){
N = nrow(inheritance[[2*ind1index-1]]) + nrow(inheritance[[2*ind1index]])
ibd = ifelse(inheritance[[2*ind1index-1]][1, 1] == inheritance[[2*ind1index]][1, 1], 1, 0)
recomb.index = c(1, 1)
data = list(inheritance[[2*ind1index-1]], inheritance[[2*ind1index]])
while(sum(recomb.index) < N){
min.index = which.min(c(data[[1]][recomb.index[1], 2], data[[2]][recomb.index[2], 2]))
min.recomb = data[[min.index]][recomb.index[min.index], 2]
if(data[[1]][recomb.index[1],2] == min.recomb){
recomb.index[1] = recomb.index[1] + 1
}
if(data[[2]][recomb.index[2],2] == min.recomb){
recomb.index[2] = recomb.index[2] + 1
}
ibd.temp = ifelse((data[[1]][recomb.index[1], 1] == data[[2]][recomb.index[2], 1]), 1, 0)
if(ibd.temp != tail(ibd, 1)){
ibd = c(ibd, ibd.temp)
endpos = c(endpos, data[[min.index]][recomb.index[min.index]-1, 2])
startpos = c(startpos, data[[min.index]][recomb.index[min.index]-1, 2])
}
}
endpos = c(endpos, inheritance[[2*ind1index-1]][recomb.index[1], 2])
return(data.frame(ibd, startpos, endpos))
}else{
N = nrow(inheritance[[2*ind1index-1]]) + nrow(inheritance[[2*ind1index]]) + nrow(inheritance[[2*ind2index-1]]) + nrow(inheritance[[2*ind2index]])
recomb.index = rep(1, 4)
data = list(inheritance[[2*ind1index-1]], inheritance[[2*ind1index]], inheritance[[2*ind2index-1]], inheritance[[2*ind2index]])
if(relatedness){
relatedness = fgl2relatedness(data[[1]][1, 1], data[[2]][1, 1], data[[3]][1, 1], data[[4]][1, 1])
while(sum(recomb.index) < N){
min.index = which.min(c(data[[1]][recomb.index[1], 2], data[[2]][recomb.index[2], 2], data[[3]][recomb.index[3], 2], data[[4]][recomb.index[4], 2]))
min.recomb = data[[min.index]][recomb.index[min.index], 2]
recomb.index[min.index] = recomb.index[min.index] + 1
while(min(c(data[[1]][recomb.index[1], 2], data[[2]][recomb.index[2], 2], data[[3]][recomb.index[3], 2], data[[4]][recomb.index[4], 2])) == min.recomb){
min.index = which.min(c(data[[1]][recomb.index[1], 2], data[[2]][recomb.index[2], 2], data[[3]][recomb.index[3], 2], data[[4]][recomb.index[4], 2]))
recomb.index[min.index] = recomb.index[min.index] + 1
}
relatedness.temp = fgl2relatedness(inheritance[[2*ind1index-1]][recomb.index[1], 1], inheritance[[2*ind1index]][recomb.index[2], 1], inheritance[[2*ind2index-1]][recomb.index[3], 1], inheritance[[2*ind2index]][recomb.index[4], 1])
if(relatedness.temp != tail(relatedness, 1)){
relatedness = c(relatedness, relatedness.temp)
endpos = c(endpos, data[[min.index]][recomb.index[min.index]-1, 2])
startpos = c(startpos, data[[min.index]][recomb.index[min.index]-1, 2])
}
}
endpos = c(endpos, inheritance[[2*ind1index-1]][recomb.index[1], 2])
return(data.frame(relatedness, startpos, endpos))
}else{
ibd = fgl2ibd(data[[1]][1, 1], data[[2]][1, 1], data[[3]][1, 1], data[[4]][1, 1])
while(sum(recomb.index) < N){
min.index = which.min(c(data[[1]][recomb.index[1], 2], data[[2]][recomb.index[2], 2], data[[3]][recomb.index[3], 2], data[[4]][recomb.index[4], 2]))
min.recomb = data[[min.index]][recomb.index[min.index], 2]
recomb.index[min.index] = recomb.index[min.index] + 1
while(min(c(data[[1]][recomb.index[1], 2], data[[2]][recomb.index[2], 2], data[[3]][recomb.index[3], 2], data[[4]][recomb.index[4], 2])) == min.recomb){
min.index = which.min(c(data[[1]][recomb.index[1], 2], data[[2]][recomb.index[2], 2], data[[3]][recomb.index[3], 2], data[[4]][recomb.index[4], 2]))
recomb.index[min.index] = recomb.index[min.index] + 1
}
ibd.temp = fgl2ibd(inheritance[[2*ind1index-1]][recomb.index[1], 1], inheritance[[2*ind1index]][recomb.index[2], 1], inheritance[[2*ind2index-1]][recomb.index[3], 1], inheritance[[2*ind2index]][recomb.index[4], 1])
if(ibd.temp != tail(ibd, 1)){
ibd = c(ibd, ibd.temp)
endpos = c(endpos, data[[min.index]][recomb.index[min.index]-1, 2])
startpos = c(startpos, data[[min.index]][recomb.index[min.index]-1, 2])
}
}
endpos = c(endpos, inheritance[[2*ind1index-1]][recomb.index[1], 2])
return(data.frame(ibd, startpos, endpos))
}
}
}
ibd.marker = function(inheritance, marker, ind1index, ind2index = NULL, relatedness = TRUE){
L = tail(c(inheritance[[1]]),1)
if(min(marker) < 0 || max(marker) > L){
stop("Marker positon out of bounds.")
}
nsnp = length(marker)
output = rep(0, nsnp)
if(relatedness){
segment = ibd.segment(inheritance, ind1index, ind2index)
}else{
segment = ibd.segment(inheritance, ind1index, ind2index, relatedness = FALSE)
}
current.index = 1
current.ibd = segment[1, 1]
current.recomb = segment[1, 3]
start.mindex = 1
end.mindex = 1
L = segment[nrow(segment), 3]
if(current.recomb == L){
output = rep(current.ibd, nsnp)
}
while(current.recomb < L && end.mindex <= nsnp){
if(marker[end.mindex] > current.recomb){
if(start.mindex != end.mindex){
output[start.mindex:(end.mindex-1)] = rep(current.ibd, (end.mindex-start.mindex))
start.mindex = end.mindex
}
current.index = current.index + 1
current.ibd = segment[current.index, 1]
current.recomb = segment[current.index, 3]
}else{
end.mindex = end.mindex + 1
}
}
output[start.mindex:nsnp] = rep(current.ibd, (nsnp-start.mindex+1))
return(output)
} |
skip_on_cran()
tbl1 <-
lm(time ~ sex + ph.ecog, survival::lung) %>%
tbl_regression()
tbl2 <-
lm(time ~ ph.ecog + sex, survival::lung) %>%
tbl_regression(label = list(sex = "Sex", ph.ecog = "ECOG Score"))
test_that("works as expected without error", {
expect_error(
tbl1 %>%
add_significance_stars(hide_ci = FALSE, hide_p = FALSE),
NA
)
expect_error(
tbl_stars <-
tbl1 %>%
add_significance_stars(hide_ci = FALSE, hide_p = FALSE),
NA
)
expect_error(
tbl_merge(list(tbl_stars, tbl_stars)),
NA
)
expect_equal(
tbl_stack(list(tbl_stars, tbl_stars)) %>% as_tibble(col_labels = FALSE) %>% pull(estimate),
c("52", "-58**", "52", "-58**")
)
expect_error(
tbl1 %>%
add_significance_stars(
thresholds = c(0.0000001, 0.55, 0.9, 1),
hide_p = FALSE
),
NA
)
expect_equal(
tbl2 %>%
add_significance_stars(
pattern = "{estimate} ({conf.low}, {conf.high}){stars}",
hide_ci = TRUE, hide_se = TRUE
) %>%
as_tibble(col_labels = FALSE) %>% purrr::pluck("estimate", 1),
"-58 (-96, -21)**"
)
})
test_that("errors/messages with bad inputs", {
expect_error(
tbl1 %>% add_significance_stars(thresholds = c(0.0000001, 0.55, 0.9, 1.1))
)
expect_error(
add_significance_stars(trial)
)
expect_error(
add_significance_stars(trial, pattern = c("afds", "asf"))
)
expect_error(
tbl1 %>% add_significance_stars(pattern = c("afds", "asf"))
)
expect_error(
tbl1 %>% add_significance_stars(pattern = "no columns selected")
)
expect_message(
tbl1 %>% add_significance_stars(pattern = "{estimate}")
)
}) |
cdcc_estimation <- function(ini.para=c(0.05,0.93) ,ht ,residuals, method=c("COV","LS","NLS"), ts = 1){
stdresids <- residuals/sqrt(ht)
flag <- match.arg(method)
if(flag == "NLS"){
print("non-linear shrinkage Step Now...")
uncR <- nlshrink::nlshrink_cov(stdresids)
}
else if(flag == "LS"){
print("linear shrinkage Step Now...")
uncR <- nlshrink::linshrink_cov(stdresids)
}
else{
uncR <- stats::cov(stdresids)
}
print("Optimization Step Now...")
result <- cdcc_optim(param=ini.para,ht=ht, residuals=residuals, stdresids=stdresids, uncR=uncR)
print("Construction Rt Step Now...")
cdcc_Rt <- cdcc_correlations(result$par, stdresids, uncR, ts)
list(result=result,cdcc_Rt=cdcc_Rt)
} |
data_color <- function(data,
columns,
colors,
alpha = NULL,
apply_to = c("fill", "text"),
autocolor_text = TRUE) {
stop_if_not_gt(data = data)
apply_to <- match.arg(apply_to)
colors <- rlang::enquo(colors)
data_tbl <- dt_data_get(data = data)
colors <- rlang::eval_tidy(colors, data_tbl)
colnames <- names(data_tbl)
resolved_columns <-
resolve_cols_c(expr = {{ columns }}, data = data)
rows <- seq_len(nrow(data_tbl))
data_color_styles_tbl <-
dplyr::tibble(
locname = character(0), grpname = character(0), colname = character(0),
locnum = numeric(0), rownum = integer(0), colnum = integer(0), styles = list()
)
for (column in resolved_columns) {
data_vals <- data_tbl[[column]][rows]
if (inherits(colors, "character")) {
if (is.numeric(data_vals)) {
color_fn <- scales::col_numeric(palette = colors, domain = data_vals, alpha = TRUE)
} else if (is.character(data_vals) || is.factor(data_vals)) {
if (length(colors) > 1) {
nlvl <-
if (is.factor(data_vals)) {
nlevels(data_vals)
} else {
nlevels(factor(data_vals))
}
if (length(colors) > nlvl) {
colors <- colors[seq_len(nlvl)]
}
}
color_fn <- scales::col_factor(palette = colors, domain = data_vals, alpha = TRUE)
} else {
stop("Don't know how to map colors to a column of class ", class(data_vals)[1], ".",
call. = FALSE)
}
} else if (inherits(colors, "function")) {
color_fn <- colors
} else {
stop("The `colors` arg must be either a character vector of colors or a function",
call. = FALSE)
}
color_fn <- rlang::eval_tidy(color_fn, data_tbl)
color_vals <- color_fn(data_vals)
color_vals <- html_color(colors = color_vals, alpha = alpha)
color_styles <-
switch(
apply_to,
fill = lapply(color_vals, FUN = function(x) cell_fill(color = x)),
text = lapply(color_vals, FUN = function(x) cell_text(color = x))
)
data_color_styles_tbl <-
dplyr::bind_rows(
data_color_styles_tbl,
generate_data_color_styles_tbl(
column = column, rows = rows,
color_styles = color_styles
)
)
if (apply_to == "fill" && autocolor_text) {
color_vals <- ideal_fgnd_color(bgnd_color = color_vals)
color_styles <- lapply(color_vals, FUN = function(x) cell_text(color = x))
data_color_styles_tbl <-
dplyr::bind_rows(
data_color_styles_tbl,
generate_data_color_styles_tbl(
column = column, rows = rows,
color_styles = color_styles
)
)
}
}
dt_styles_set(
data = data,
styles = dplyr::bind_rows(dt_styles_get(data = data), data_color_styles_tbl)
)
}
generate_data_color_styles_tbl <- function(column, rows, color_styles) {
dplyr::tibble(
locname = "data", grpname = NA_character_,
colname = column, locnum = 5, rownum = rows,
styles = color_styles
)
}
is_rgba_col <- function(colors) {
grepl("^rgba\\(\\s*(?:[0-9]+?\\s*,\\s*){3}[0-9\\.]+?\\s*\\)$", colors)
}
is_hex_col <- function(colors) {
grepl("^
}
is_short_hex <- function(colors) {
grepl("^
}
expand_short_hex <- function(colors) {
gsub("^
}
ideal_fgnd_color <- function(bgnd_color,
light = "
dark = "
bgnd_color <- rgba_to_hex(colors = bgnd_color)
bgnd_color <- html_color(colors = bgnd_color, alpha = 1)
yiq_contrasted_threshold <- 128
colors <- grDevices::col2rgb(bgnd_color)
score <- colSums(colors * c(299, 587, 144)) / 1000
ifelse(score >= yiq_contrasted_threshold, dark, light)
}
rgba_to_hex <- function(colors) {
colors_vec <- rep(NA_character_, length(colors))
colors_rgba <- is_rgba_col(colors = colors)
colors_vec[!colors_rgba] <- colors[!colors_rgba]
color_matrix <-
colors[colors_rgba] %>%
gsub(pattern = "(rgba\\(|\\))", replacement = "", x = .) %>%
strsplit(",") %>%
unlist() %>%
as.numeric() %>%
matrix(
., ncol = 4,
dimnames = list(c(), c("r", "g", "b", "alpha")),
byrow = TRUE
)
alpha <- color_matrix[, "alpha"] %>% unname()
colors_to_hex <-
grDevices::rgb(
red = color_matrix[, "r"] / 255,
green = color_matrix[, "g"] / 255,
blue = color_matrix[, "b"] / 255,
alpha = alpha
)
colors_vec[colors_rgba] <- colors_to_hex
colors_vec
}
html_color <- function(colors, alpha = NULL) {
if (any(is.na(colors))) {
stop("No values supplied in `colors` should be NA")
}
is_rgba <- is_rgba_col(colors = colors)
is_short_hex <- is_short_hex(colors = colors)
colors[is_short_hex] <- expand_short_hex(colors = colors[is_short_hex])
is_hex <- is_hex_col(colors = colors)
is_named <- !is_rgba & !is_hex
colors[is_named] <- tolower(colors[is_named])
named_colors <- colors[is_named]
if (length(named_colors) > 0) {
check_named_colors(named_colors)
named_colors[named_colors == "transparent"] <- "
is_css_excl_named <- colors %in% names(css_exclusive_colors())
if (any(is_css_excl_named)) {
colors[is_css_excl_named] <-
unname(css_exclusive_colors()[colors[is_css_excl_named]])
}
}
colors[!is_rgba] <-
normalize_colors(
colors = colors[!is_rgba],
alpha = alpha
)
colors
}
col_matrix_to_rgba <- function(color_matrix) {
paste0(
"rgba(",
color_matrix[, "red"], ",",
color_matrix[, "green"], ",",
color_matrix[, "blue"], ",",
round(color_matrix[, "alpha"], 2),
")"
)
}
normalize_colors <- function(colors, alpha) {
color_matrix <- t(grDevices::col2rgb(col = colors, alpha = TRUE))
color_matrix[, "alpha"] <- color_matrix[, "alpha"] / 255
if (!is.null(alpha)) {
color_matrix[, "alpha"] <- alpha
}
colors_html <- rep(NA_character_, nrow(color_matrix))
colors_alpha_1 <- color_matrix[, "alpha"] == 1
colors_html[colors_alpha_1] <-
grDevices::rgb(
red = color_matrix[colors_alpha_1, "red", drop = FALSE] / 255,
green = color_matrix[colors_alpha_1, "green", drop = FALSE] / 255,
blue = color_matrix[colors_alpha_1, "blue", drop = FALSE] / 255
)
colors_html[!colors_alpha_1] <-
color_matrix[!colors_alpha_1, , drop = FALSE] %>%
col_matrix_to_rgba()
colors_html
}
css_exclusive_colors <- function() {
color_tbl_subset <- css_colors[!css_colors$is_x11_color, ]
color_values <- color_tbl_subset[["hexadecimal"]]
color_values <-
stats::setNames(
color_values,
tolower(color_tbl_subset[["color_name"]])
)
color_values
}
valid_color_names <- function() {
c(tolower(grDevices::colors()), names(css_exclusive_colors()), "transparent")
}
check_named_colors <- function(named_colors) {
named_colors <- tolower(named_colors)
if (!all(named_colors %in% valid_color_names())) {
invalid_colors <- base::setdiff(unique(named_colors), valid_color_names())
stop(
ifelse(
length(invalid_colors) > 1,
"Several invalid color names were ",
"An invalid color name was "
), "used (", str_catalog(invalid_colors, conj = "and"), "):\n",
" * Only R/X11 color names and CSS 3.0 color names can be used",
call. = FALSE
)
}
} |
cat("Checking Chapter 1 - Introduction\n\n")
setwd('01-Introduction')
source('ufo_sightings.R')
setwd('..')
cat("Checking Chapter 2 - Exploration\n\n")
setwd('02-Exploration')
source('chapter02.R')
setwd('..')
cat("Checking Chapter 3 - Classification\n\n")
setwd('03-Classification')
source('email_classify.R')
setwd('..')
cat("Checking Chapter 4 - Ranking\n\n")
setwd('04-Ranking')
source('priority_inbox.R')
setwd('..')
cat("Checking Chapter 5 - Regression\n\n")
setwd('05-Regression')
source('chapter05.R')
setwd('..')
cat("Checking Chapter 6 - Regularization\n\n")
setwd('06-Regularization')
source('chapter06.R')
setwd('..')
cat("Checking Chapter 7 - Optimization\n\n")
setwd('07-Optimization')
source('chapter07.R')
setwd('..')
cat("Checking Chapter 8 - PCA\n\n")
setwd('08-PCA')
source('chapter08.R')
setwd('..')
cat("Checking Chapter 9 - MDS\n\n")
setwd('09-MDS')
source('chapter09.R')
setwd('..')
cat("Checking Chapter 10 - Recommendations\n\n")
setwd('10-Recommendations')
source('chapter10.R')
setwd('..')
cat("Checking Chapter 12 - Model Comparison\n\n")
setwd('12-Model_Comparison')
source('chapter12.R')
setwd('..') |
fitted.gpcm <-
function (object, resp.patterns = NULL,
type = c("expected", "marginal-probabilities", "conditional-probabilities"), ...) {
if (!inherits(object, "gpcm"))
stop("Use only with 'gpcm' objects.\n")
type <- match.arg(type)
betas <- object$coefficients
p <- length(betas)
X <- if (is.null(resp.patterns)) {
object$patterns$X
} else {
if (!is.matrix(resp.patterns) && !is.data.frame(resp.patterns))
stop("'resp.patterns' should be a matrix or a data.frame.\n")
if (ncol(resp.patterns) != p)
stop("the number of items in ", deparse(substitute(object)), " and the number of columns of 'resp.patterns' do not much.\n")
rp <- resp.patterns
if (!is.data.frame(rp))
rp <- as.data.frame(rp)
for (i in 1:p) {
if (is.factor(rp[[i]])) {
if (!all(levels(rp[[i]]) %in% levels(object$X[[i]])))
stop("the levels in the ", i, "th column of 'resp.patterns' does not much with the levels of the ",
i, " item in the original data set.\n")
} else {
rp[[i]] <- factor(rp[[i]], levels = sort(unique(object$patterns$X[, i])))
}
}
rp <- sapply(rp, unclass)
if (!is.matrix(rp))
rp <- t(rp)
rp
}
if (type == "expected" || type == "marginal-probabilities") {
colnames(X) <- names(betas)
log.crf <- crf.GPCM(betas, object$GH$Z, object$IRT.param, log = TRUE)
log.p.xz <- matrix(0, nrow(X), object$control$GHk)
for (j in 1:p) {
log.pr <- log.crf[[j]]
xj <- X[, j]
na.ind <- is.na(xj)
log.pr <- log.pr[xj, , drop = FALSE]
if (any(na.ind))
log.pr[na.ind, ] <- 0
log.p.xz <- log.p.xz + log.pr
}
p.xz <- exp(log.p.xz)
out <- switch(type,
"expected" = cbind(X, Exp = nrow(object$X) * colSums(object$GH$GHw * t(p.xz))),
"marginal-probabilities" = cbind(X, "Marg-Probs" = colSums(object$GH$GHw * t(p.xz))))
rownames(out) <- if (!is.null(resp.patterns) && !is.null(nams <- rownames(resp.patterns))) nams else NULL
out
} else {
Z <- factor.scores(object, resp.patterns = resp.patterns)$score.dat$z1
names(Z) <- if (!is.null(resp.patterns) && !is.null(nams <- rownames(resp.patterns))) nams else NULL
res <- vector(mode = "list", length = p)
out <- lapply(crf.GPCM(betas, Z, object$IRT.param), t)
for (i in seq_along(out)) {
if (is.factor(object$X[[i]]))
colnames(out[[i]]) <- levels(object$X[[i]])
}
out
}
} |
change_pwd <- function(old, new, ...) {
query <- list(Action = "ChangePassword", NewPassword = new, OldPassword = old)
out <- iamHTTP(query = query, ...)
if (!inherits(out, "aws_error")) {
out <- TRUE
}
out
}
get_pwd_policy <- function(...) {
query <- list(Action = "GetAccountPasswordPolicy")
out <- iamHTTP(query = query, ...)
out[["GetAccountPasswordPolicyResponse"]][["GetAccountPasswordPolicyResult"]][["PasswordPolicy"]]
}
set_pwd_policy <-
function(allowchange,
hardexpire,
age,
length,
previous,
requirements,
...) {
query <- list(Action = "UpdateAccountPasswordPolicy")
if (!missing(allowchange)) {
query[["AllowUsersToChangePassword"]] <- tolower(as.character(allowchange))
}
if (!missing(hardexpire)) {
query[["HardExpiry"]] <- tolower(as.character(hardexpire))
}
if (!missing(age)) {
if(age > 1095 | age < 6)
stop("'age' must be between 1 and 1095")
query[["MaxPasswordAge"]] <- age
}
if (!missing(length)) {
if (length > 128 | length < 6) {
stop("'length' must be between 6 and 128")
}
query[["MinPasswordLength"]] <- length
}
if (!missing(previous)) {
if (previous > 24 | age < 0) {
stop("'age' must be between 0 and 24")
}
query[["PasswordReusePrevention"]] <- previous
}
if (!missing(requirements)){
if ("upper" %in% requirements) {
query[["RequireUppercaseCharacters"]] <- "true"
}
if ("lower" %in% requirements) {
query[["RequireLowercaseCharacters"]] <- "true"
}
if ("number" %in% requirements) {
query[["RequireNumbers"]] <- "true"
}
if ("symbol" %in% requirements) {
query[["RequireSymbols"]] <- "true"
}
}
out <- iamHTTP(query = query, ...)
if (!inherits(out, "aws_error")) {
out <- TRUE
}
out
} |
setMethod("StateIndependentInFluxList_by_PoolIndex",
signature=signature(object="list"),
definition=function(object){
makeListInstance(
object
,targetClassName='StateIndependentInFlux_by_PoolIndex'
,targetListClassName="StateIndependentInFluxList_by_PoolIndex"
,permittedValueClassName='ScalarTimeMap'
,key_value_func=function(key,val){
StateIndependentInFlux_by_PoolIndex(
destinationIndex=PoolIndex(key)
,flux=object[[key]]
)
}
)
}
) |
ms_chat_message <- R6::R6Class("ms_chat_message", inherit=ms_object,
public=list(
initialize=function(token, tenant=NULL, properties=NULL)
{
self$type <- "Teams message"
if(!is.null(properties$channelIdentity))
{
parent <- properties$channelIdentity
private$api_type <- file.path("teams", parent[[1]], "channels", parent[[2]], "messages")
}
else if(!is.null(properties$chatId))
private$api_type <- file.path("chats", properties$chatId, "messages")
else stop("Unable to get parent", call=FALSE)
if(!is.null(properties$replyToId))
private$api_type <- file.path(private$api_type, properties$replyToId, "replies")
super$initialize(token, tenant, properties)
},
send_reply=function(body, content_type=c("text", "html"), attachments=NULL, inline=NULL, mentions=NULL)
{
private$assert_not_nested_reply()
content_type <- match.arg(content_type)
call_body <- build_chatmessage_body(private$get_parent(), body, content_type, attachments, inline, mentions)
res <- self$do_operation("replies", body=call_body, http_verb="POST")
ms_chat_message$new(self$token, self$tenant, res)
},
list_replies=function(filter=NULL, n=50)
{
private$assert_not_nested_reply()
private$make_basic_list("replies", filter, n)
},
get_reply=function(message_id)
{
private$assert_not_nested_reply()
op <- file.path("replies", message_id)
ms_chat_message$new(self$token, self$tenant, self$do_operation(op))
},
delete_reply=function(message_id, confirm=TRUE)
{
private$assert_not_nested_reply()
self$get_reply(message_id)$delete(confirm=confirm)
},
delete=function(confirm=TRUE)
{
stop("Deleting Teams messages is not currently supported", call.=FALSE)
},
print=function(...)
{
cat("<Teams message>\n", sep="")
cat(" directory id:", self$properties$id, "\n")
if(!is.null(self$properties$channelIdentity))
{
parent <- self$properties$channelIdentity
cat(" team:", parent[[1]], "\n")
cat(" channel:", parent[[2]], "\n")
}
else cat(" chat:", self$properties$chatId, "\n")
if(!is_empty(self$properties$replyToId))
cat(" in-reply-to:", self$properties$replyToId, "\n")
cat("---\n")
cat(format_public_methods(self))
invisible(self)
}
),
private=list(
get_parent=function()
{
parent <- if(!is.null(self$properties$channelIdentity))
{
channel <- self$properties$channelIdentity
ms_channel$new(self$token, self$tenant, list(id=channel$channelId), team_id=channel$teamId)
}
else ms_channel$new(self$token, self$tenant, list(id=self$properties$chatId))
parent$sync_fields()
},
assert_not_nested_reply=function()
{
stopifnot("Nested replies not allowed in Teams channels"=is.null(self$properties$replyToId))
}
)) |
Scenario2 <-
function(sigmak=0.1){
g=100
m=1000
s=100
mu1=-0.65
mu2=0
mu3=0.65
mu4=1.5
mu=c(mu1,mu2,mu3,mu4)
sigma1=0.1
sigma2=0.1
sigma3=0.1
sigma4=0.2
sigma=c(sigma1,sigma2,sigma3,sigma4)
A=matrix(c(0.3,0.6,0.095,0.005,0.09,0.818,0.09,0.002,0.095,0.6,0.3,0.005,0.005,0.71,0.005,0.28),nrow=4,byrow=T)
AC=matrix(nrow=4,ncol=4)
for (i in 1:4){
AC[i,1]=A[i,1]
for (j in 2:4){
AC[i,j]=AC[i,(j-1)]+A[i,j]
}
}
A1=A
A1[1,]=c(0.7500, 0.1800, 0.0500, 0.020)
A1[2,]=c(0.4955, 0.0020, 0.4955, 0.007)
A1[3,]=c(0.0200, 0.1800, 0.7000, 0.100)
A1[4,]=c(0.0001, 0.3028, 0.1001, 0.597)
AC1=matrix(nrow=4,ncol=4)
for (i in 1:4){
AC1[i,1]=A1[i,1]
for (j in 2:4){
AC1[i,j]=AC1[i,(j-1)]+A1[i,j]
}
}
xi=matrix(2,nrow=s,ncol=m)
change=c(4:8,100:109,250:259,300,306,380,390,420:426,490:495,500:503,505,525:530,sample(531:1000,197))
change.complete=rep(0,m)
change.complete[change]=1
change.pos.two=which(change.complete==0)
change.partial=sample(change.pos.two[-1],375)
change.complete[change.partial]=2
q=10
for(j in 2:m){
if(change.complete[j]==1){
for(i in 1:s){
temp2=runif(1,0,1)
if(temp2<AC1[xi[i,j-1],1]){
xi[i,j]=1
}
if(AC1[xi[i,j-1],1]<=temp2 && temp2<AC1[xi[i,j-1],2]){
xi[i,j]=2
}
if(AC1[xi[i,j-1],2]<=temp2 && temp2<AC1[xi[i,j-1],3]){
xi[i,j]=3
}
if(AC1[xi[i,j-1],3]<=temp2){
xi[i,j]=4
}
}
}
if(change.complete[j]==2){
samples.to.change=sample(1:s,q)
for(i in 1:q){
temp2=runif(1,0,1)
if(temp2<AC1[xi[samples.to.change[i],j-1],1]){
xi[samples.to.change[i],j]=1
}
if(AC1[xi[samples.to.change[i],j-1],1]<=temp2 && temp2<AC1[xi[samples.to.change[i],j-1],2]){
xi[samples.to.change[i],j]=2
}
if(AC1[xi[samples.to.change[i],j-1],2]<=temp2 && temp2<AC1[xi[samples.to.change[i],j-1],3]){
xi[samples.to.change[i],j]=3
}
if(AC1[xi[samples.to.change[i],j-1],3]<=temp2){
xi[samples.to.change[i],j]=4
}
}
}
}
X=matrix(nrow=s,ncol=m)
for (i in 1:s){
for(j in 1:m){
X[i,j]=rnorm(1,mean=mu[xi[i,j]],sd=sigma[xi[i,j]])
}
}
beta=matrix(0,nrow=g,ncol=m)
beta[4,change[6:15]]=((-1)^(floor(runif(1,0,2))))*rnorm(10,mean=0.5,sd=0.3)
beta[10,change[16:25]]=((-1)^(floor(runif(1,0,2))))*rnorm(10,mean=0.5,sd=0.3)
epsilon=NULL
for(i in 1:s){
epsilon=rbind(epsilon,rnorm(g,mean=0,sd=sigmak))
}
mu.g=rnorm(g,0,sd=0.1)
Y=xi%*%t(beta)+mu.g+epsilon
realA=Tran(xi)
realA[1,]=realA[1,]/sum(realA[1,])
realA[2,]=realA[2,]/sum(realA[2,])
realA[3,]=realA[3,]/sum(realA[3,])
realA[4,]=realA[4,]/sum(realA[4,])
signbeta=which(beta!=0)
distance=rexp(m-1)
disfix=2*sum(distance)
return(list(Y=Y,X=X,Xi=xi,A=realA,mu=mu,Sd=sigma,coeff=beta,distance=distance,disfix=disfix))
} |
toolstartmessage <- function(argumentValues, level = NULL) {
functionAndArgs <- as.list(sys.call(-1))
theFunction <- functionAndArgs[[1]]
nonDefaultArguments <- getNonDefaultArguments(eval(theFunction), argumentValues)
argsString <- paste0(list(nonDefaultArguments))
argsString <- substr(argsString, 6, nchar(argsString) - 1)
if (nchar(argsString) <= getConfig("maxLengthLogMessage")) {
functionCallString <- paste0(theFunction, "(", argsString, ")", collapse = "")
hint <- ""
} else {
functionCallString <- paste0(deparse(sys.call(-1)), collapse = "")
hint <- paste0(" -- to print evaluated arguments: setConfig(maxLengthLogMessage = ", nchar(argsString), ")")
}
vcat(1, "Run ", functionCallString, hint, level = level, fill = 300, show_prefix = FALSE)
return(list(time1 = proc.time(), functionCallString = functionCallString))
} |
context("nonportable-inheritance")
test_that("Inheritance", {
AC <- R6Class("AC",
portable = FALSE,
public = list(
x = 0,
z = 0,
initialize = function(x) self$x <- x,
getx = function() x,
getx2 = function() x*2
),
private = list(
getz = function() z,
getz2 = function() z*2
),
active = list(
x2 = function(value) {
if (missing(value)) return(x * 2)
else x <<- value/2
},
x3 = function(value) {
if (missing(value)) return(x * 3)
else x <<- value/3
}
)
)
BC <- R6Class("BC",
portable = FALSE,
inherit = AC,
public = list(
y = 0,
z = 3,
initialize = function(x, y) {
super$initialize(x)
self$y <- y
},
getx = function() x + 10
),
private = list(
getz = function() z + 10
),
active = list(
x2 = function(value) {
if (missing(value)) return(x + 2)
else x <<- value-2
}
)
)
B <- BC$new(1, 2)
expect_identical(B, environment(B$getx))
expect_identical(B, parent.env(environment(B$getx2)))
expect_identical(B, environment(B$private$getz))
expect_identical(B, parent.env(environment(B$private$getz2)))
expect_identical(B$x, 1)
expect_identical(B$y, 2)
expect_identical(B$z, 3)
expect_identical(B$getx(), 11)
expect_identical(B$getx2(), 2)
expect_identical(B$private$getz(), 13)
expect_identical(B$private$getz2(), 6)
expect_identical(B$x2, 3)
expect_identical(B$x3, 3)
expect_identical(class(B), c("BC", "AC", "R6"))
})
test_that("Inheritance: superclass methods", {
AC <- R6Class("AC",
portable = FALSE,
public = list(
x = 0,
initialize = function() {
inc_x()
inc_self_x()
inc_y()
inc_self_y()
incz
},
inc_x = function() x <<- x + 1,
inc_self_x = function() self$x <- self$x + 10,
inc = function(val) val + 1,
pinc = function(val) priv_inc(val),
z = 0
),
private = list(
y = 0,
inc_y = function() y <<- y + 1,
inc_self_y = function() private$y <- private$y + 10,
priv_inc = function(val) val + 1
),
active = list(
incz = function(value) {
z <<- z + 1
}
)
)
BC <- R6Class("BC",
portable = FALSE,
inherit = AC,
public = list(
inc_x = function() x <<- x + 2,
inc_self_x = function() self$x <- self$x + 20,
inc = function(val) super$inc(val) + 20
),
private = list(
inc_y = function() y <<- y + 2,
inc_self_y = function() private$y <- private$y + 20,
priv_inc = function(val) super$priv_inc(val) + 20
),
active = list(
incz = function(value) {
z <<- z + 2
}
)
)
B <- BC$new()
expect_identical(parent.env(B$super), emptyenv())
expect_identical(parent.env(environment(B$super$inc_x)), B)
expect_identical(B$x, 22)
expect_identical(B$private$y, 22)
expect_identical(B$z, 2)
expect_identical(B$inc(0), 21)
expect_identical(B$pinc(0), 21)
CC <- R6Class("CC",
portable = FALSE,
inherit = BC,
public = list(
inc_x = function() x <<- x + 3,
inc_self_x = function() self$x <- self$x + 30,
inc = function(val) super$inc(val) + 300
),
private = list(
inc_y = function() y <<- y + 3,
inc_self_y = function() private$y <- private$y + 30,
priv_inc = function(val) super$priv_inc(val) + 300
),
active = list(
incz = function(value) {
z <<- z + 3
}
)
)
C <- CC$new()
expect_identical(C$x, 33)
expect_identical(C$private$y, 33)
expect_identical(C$z, 3)
expect_identical(C$inc(0), 321)
expect_identical(C$pinc(0), 321)
expect_identical(class(C), c("CC", "BC", "AC", "R6"))
})
test_that("Inheritance hierarchy for super$ methods", {
AC <- R6Class("AC",
portable = FALSE,
public = list(n = function() 0 + 1)
)
expect_identical(AC$new()$n(), 1)
BC <- R6Class("BC",
portable = FALSE,
public = list(n = function() super$n() + 10),
inherit = AC
)
expect_identical(BC$new()$n(), 11)
CC <- R6Class("CC",
portable = FALSE,
inherit = BC
)
expect_identical(CC$new()$n(), 11)
AC <- R6Class("AC",
portable = FALSE,
public = list(n = function() 0 + 1)
)
expect_identical(AC$new()$n(), 1)
BC <- R6Class("BC",
portable = FALSE,
inherit = AC
)
expect_identical(BC$new()$n(), 1)
CC <- R6Class("CC",
portable = FALSE,
public = list(n = function() super$n() + 100),
inherit = BC
)
expect_identical(CC$new()$n(), 101)
DC <- R6Class("DC",
portable = FALSE,
inherit = CC
)
expect_identical(DC$new()$n(), 101)
AC <- R6Class("AC",
portable = FALSE,
public = list(n = function() 0 + 1)
)
expect_identical(AC$new()$n(), 1)
BC <- R6Class("BC", portable = FALSE, inherit = AC)
expect_identical(BC$new()$n(), 1)
CC <- R6Class("CC", portable = FALSE, inherit = BC)
expect_identical(CC$new()$n(), 1)
})
test_that("Private env is created when all private members are inherited", {
AC <- R6Class("AC",
portable = FALSE,
public = list(
getx = function() x,
getx2 = function() private$x
),
private = list(x = 1)
)
BC <- R6Class("BC", portable = FALSE, inherit = AC)
expect_identical(BC$new()$getx(), 1)
expect_identical(BC$new()$getx2(), 1)
AC <- R6Class("AC",
portable = FALSE,
public = list(
getx = function() x(),
getx2 = function() private$x()
),
private = list(x = function() 1)
)
BC <- R6Class("BC", portable = FALSE, inherit = AC)
expect_identical(BC$new()$getx(), 1)
expect_identical(BC$new()$getx2(), 1)
}) |
selEstan<-function(emod=c('basemodel.rds','mrmodel.rds')){
emod<-match.arg(emod)
if(isTRUE(grep("64",Sys.getenv("R_ARCH"))>0)){
ebase<-'comp64'
}else ebase<-'comp32'
emod<-file.path(ebase,emod)
emod<-system.file(package="clinDR", "models", emod)
if(file.access(emod,mode=0)<0)stop(paste('The compiled rstan model',
'could not be accessed. You must',
'run compileStanModels once before using',
'the Bayesian functions'))
estan<-readRDS(emod)
if(!inherits(estan,'stanmodel'))stop('unable to create estan model')
return(estan)
}
|
library(OpenMx)
source('inst/tools/dummyFunctions.R')
dummies <- ls()
options('mxPrintUnitTests' = FALSE)
directories <- c('staging/doctest')
null <- tryCatch(suppressWarnings(file('/dev/null', 'w')),
error = function(e) { file('nul', 'w') } )
sink(null, type = 'output')
files <- list.files(directories, pattern = '^.+[.]R$',
full.names = TRUE, recursive = TRUE)
errors <- list()
errorRecover <- function(script, index) {
sink(type = 'output')
cat(paste("Running model", index, "of",
length(files), script, "...\n"))
sink(null, type = 'output')
tryCatch(source(script, chdir = TRUE),
error = function(x) {
errors[[script]] <<- x
})
rm(envir=globalenv(),
list=setdiff(ls(envir=globalenv()),
c('errors', 'errorRecover', 'null', 'files', 'directories', 'dummies', dummies)))
}
if (length(files) > 0) {
for (i in 1:length(files)) {
errorRecover(files[[i]], i)
}
}
sink(type = 'output')
close(null)
cat("Number of errors:", length(errors), '\n')
if (length(errors) > 0) {
fileName <- names(errors)
for (i in 1:length(errors)) {
cat("From model", fileName[[i]], ':\n')
print(errors[[i]]$message)
cat('\n')
}
}
cat("Finished testing models.\n") |
optimizerNlminb <- function(start, objective=objectiveML,
gradient=TRUE, maxiter, debug, par.size, model.description, warn, ...){
with(model.description, {
obj <- objective(gradient=gradient)
objective <- obj$objective
grad <- if (gradient) obj$gradient else NULL
if (!warn) save.warn <- options(warn=-1)
res <- nlminb(start, objective, gradient=grad, model.description=model.description,
control=list(trace=if(debug) 1 else 0, iter.max=maxiter, ...))
if (!warn) options(save.warn)
result <- list()
result$convergence <- res$convergence == 0
result$iterations <- res$iterations
par <- res$par
names(par) <- param.names
result$par <- par
if (!result$convergence)
warning(paste('Optimization may not have converged; nlminb return code = ',
res$convergence, '. Consult ?nlminb.\n', sep=""))
result$criterion <- res$objective
obj <- objective(par, model.description)
C <- attr(obj, "C")
rownames(C) <- colnames(C) <- var.names[observed]
result$C <- C
A <- attr(obj, "A")
rownames(A) <- colnames(A) <- var.names
result$A <- A
P <- attr(obj, "P")
rownames(P) <- colnames(P) <- var.names
result$P <- P
class(result) <- "semResult"
result
}
)
} |
TAR.coeff<-function(reg,ay,p1,p2,sig,lagd,thres,mu0,v0,lagp1,lagp2,constant=1,thresVar){
p<-max(max(lagp1),max(lagp2))+constant
n<- length(ay)
if (!missing(thresVar)){
if (length(thresVar) > n ){
zt <- thresVar[1:n]
cat("Using only first", n, "elements of threshold Variable\n")
}
else zt<-thresVar
lag.y<- zt[(p+1-lagd):(n-lagd)]
}
else lag.y<- ay[(p+1-lagd):(n-lagd)]
yt<- ay[(p+1):n]
if (reg==1){
ph<-rep(0.01,p1)
y.1<-matrix(yt[lag.y<=thres],ncol=1)
x.1<-matrix(NA,nrow=p1,ncol=n-p)
for (i in 1:p1){
x.1[i,]<-ay[(p-lagp1[i]+1):(n-lagp1[i])]}
if(p1>1){
if (constant==1){
tx<-cbind(1,t(x.1[,lag.y<=thres]))
}
else {
tx<-t(x.1[,lag.y<=thres])
}
}
if(p1 == 1){
if (constant==1){
tx<-cbind(1,t(t(x.1[,lag.y<=thres])))
}
else {
tx<-t(t(x.1[,lag.y<=thres]))
}
}
yt<- matrix(yt[lag.y<=thres],ncol=1)
sigma<- (t(tx)%*%tx)/sig+v0
mu<- solve(sigma,((t(tx)%*%tx)/sig)%*%(solve((t(tx)%*%tx),t(tx)%*%yt))+v0%*%mu0)
ph<- rmvnorm(n = 1, mu, solve(sigma),method="chol")
}
else {
ph<-rep(0.01,p2)
y.2<-matrix(yt[lag.y>thres],ncol=1)
x.2<-matrix(NA,nrow=p2,ncol=n-p)
for ( i in 1:p2){
x.2[i,]<-ay[(p-lagp2[i]+1):(n-lagp2[i])]}
if(p2 > 1) {
if (constant==1){
tx<-cbind(1,t(x.2[,lag.y>thres]))
}
else {
tx<-t(x.2[,lag.y>thres])
}
}
if(p2 == 1){
if (constant==1){
tx<-cbind(1,t(t(x.2[,lag.y>thres])))
}
else {
tx<-t(t(x.2[,lag.y>thres]))
}
}
yt<- matrix(yt[lag.y>thres],ncol=1)
sigma<- (t(tx)%*%tx)/sig+v0
mu<- solve(sigma,((t(tx)%*%tx)/sig)%*%(solve((t(tx)%*%tx),t(tx)%*%yt))+v0%*%mu0)
ph<- rmvnorm(n=1,mu,solve(sigma),method="chol")
}
return(ph)
} |
blr_test_hosmer_lemeshow <- function(model, data = NULL)
UseMethod("blr_test_hosmer_lemeshow")
blr_test_hosmer_lemeshow.default <- function(model, data = NULL) {
blr_check_model(model)
if (is.null(data)) {
resp <- model$y
data <- model$model
} else {
namu <- formula(model)[[2]]
blr_check_data(data)
resp_temp <- data[[namu]]
resp <- as.numeric(levels(resp_temp))[resp_temp]
}
hoslem_data <- hoslem_data_prep(model, data, resp)
int_limits <- hoslem_int_limits(hoslem_data)
h1 <- hoslem_data_mutate(hoslem_data, int_limits = int_limits)
hoslem_table <- hoslem_table_data(h1, resp = resp)
chisq_stat <- hoslem_chisq_stat(hoslem_table)
hoslem_df <- 8
hoslem_pval <- pchisq(chisq_stat, df = hoslem_df, lower.tail = FALSE)
result <- list(partition_table = hoslem_table,
chisq_stat = chisq_stat,
df = hoslem_df,
pvalue = hoslem_pval
)
class(result) <- "blr_test_hosmer_lemeshow"
return(result)
}
print.blr_test_hosmer_lemeshow <- function(x, ...) {
print_blr_test_hosmer_lemeshow(x)
}
hoslem_data_prep <- function(model, data, resp) {
data$prob <- predict.glm(model, newdata = data, type = "response")
data$resp <- resp
data[order(data$prob), ]
}
hoslem_int_limits <- function(hoslem_data) {
unname(quantile(hoslem_data$prob, probs = seq(0, 1, 0.1)))
}
hoslem_data_mutate <- function(hoslem_data, int_limits) {
d <- hoslem_data
d$group <- lest::case_when(
d$prob <= int_limits[2] ~ 1,
d$prob > int_limits[2] & d$prob <= int_limits[3] ~ 2,
d$prob > int_limits[3] & d$prob <= int_limits[4] ~ 3,
d$prob > int_limits[4] & d$prob <= int_limits[5] ~ 4,
d$prob > int_limits[5] & d$prob <= int_limits[6] ~ 5,
d$prob > int_limits[6] & d$prob <= int_limits[7] ~ 6,
d$prob > int_limits[7] & d$prob <= int_limits[8] ~ 7,
d$prob > int_limits[8] & d$prob <= int_limits[9] ~ 8,
d$prob > int_limits[9] & d$prob <= int_limits[10] ~ 9,
d$prob > int_limits[10] ~ 10
)
return(d)
}
hoslem_table_data <- function(data, resp) {
d <- data.table(data)
d <- d[, .(n = .N,
`1s_observed` = sum(resp),
avg_prob = mean(prob)),
by = group]
d <- setDF(d)
d$`0s_observed` <- d$n - d$`1s_observed`
d$`1s_expected` <- d$n * d$avg_prob
d$`0s_expected` <- d$n - d$`1s_expected`
d$positive <- ((d$`1s_observed` - d$`1s_expected`) ^ 2 / d$`1s_expected`)
d$negative <- ((d$`0s_observed` - d$`0s_expected`) ^ 2 / d$`0s_expected`)
return(d)
}
hoslem_chisq_stat <- function(hoslem_table) {
d <- hoslem_table[c('positive', 'negative')]
sum(unlist((lapply(d, sum))))
} |
default_style_guide_attributes <- function(pd_flat) {
initialize_newlines(pd_flat) %>%
initialize_spaces() %>%
remove_attributes(c("line1", "line2", "col1", "col2", "parent", "id")) %>%
initialize_multi_line() %>%
initialize_indention_ref_pos_id() %>%
initialize_indent() %>%
validate_parse_data()
}
NULL
initialize_newlines <- function(pd_flat) {
pd_flat$line3 <- lead(pd_flat$line1, default = tail(pd_flat$line2, 1))
pd_flat$newlines <- pd_flat$line3 - pd_flat$line2
pd_flat$lag_newlines <- lag(pd_flat$newlines, default = 0L)
pd_flat$line3 <- NULL
pd_flat
}
initialize_spaces <- function(pd_flat) {
pd_flat$col3 <- lead(pd_flat$col1, default = tail(pd_flat$col2, 1) + 1L)
pd_flat$col2_nl <- ifelse(pd_flat$newlines > 0L,
rep(0L, nrow(pd_flat)), pd_flat$col2
)
pd_flat$spaces <- pd_flat$col3 - pd_flat$col2_nl - 1L
pd_flat$col3 <- pd_flat$col2_nl <- NULL
pd_flat
}
remove_attributes <- function(pd_flat, attributes) {
pd_flat[attributes] <- rep(list(NULL), length(attributes))
pd_flat
}
initialize_multi_line <- function(pd_flat) {
nrow <- nrow(pd_flat)
pd_flat$multi_line <- ifelse(pd_flat$terminal,
rep(0L, nrow),
rep(NA, nrow)
)
pd_flat
}
initialize_indention_ref_pos_id <- function(pd_flat) {
pd_flat$indention_ref_pos_id <- NA
pd_flat
}
initialize_indent <- function(pd_flat) {
if (!("indent" %in% names(pd_flat))) {
pd_flat$indent <- 0
}
pd_flat
}
validate_parse_data <- function(pd_flat) {
if (any(pd_flat$spaces < 0L)) {
abort("Invalid parse data")
}
pd_flat
} |
context("Test models with custom objective")
data(agaricus.train, package = "lightgbm")
data(agaricus.test, package = "lightgbm")
dtrain <- lgb.Dataset(agaricus.train$data, label = agaricus.train$label)
dtest <- lgb.Dataset(agaricus.test$data, label = agaricus.test$label)
watchlist <- list(eval = dtest, train = dtrain)
TOLERANCE <- 1e-6
logregobj <- function(preds, dtrain) {
labels <- get_field(dtrain, "label")
preds <- 1.0 / (1.0 + exp(-preds))
grad <- preds - labels
hess <- preds * (1.0 - preds)
return(list(grad = grad, hess = hess))
}
evalerror <- function(preds, dtrain) {
labels <- get_field(dtrain, "label")
preds <- 1.0 / (1.0 + exp(-preds))
err <- as.numeric(sum(labels != (preds > 0.5))) / length(labels)
return(list(
name = "error"
, value = err
, higher_better = FALSE
))
}
param <- list(
num_leaves = 8L
, learning_rate = 1.0
, objective = logregobj
, metric = "auc"
)
num_round <- 10L
test_that("custom objective works", {
bst <- lgb.train(param, dtrain, num_round, watchlist, eval = evalerror)
expect_false(is.null(bst$record_evals))
})
test_that("using a custom objective, custom eval, and no other metrics works", {
set.seed(708L)
bst <- lgb.train(
params = list(
num_leaves = 8L
, learning_rate = 1.0
)
, data = dtrain
, nrounds = 4L
, valids = watchlist
, obj = logregobj
, eval = evalerror
)
expect_false(is.null(bst$record_evals))
expect_equal(bst$best_iter, 4L)
expect_true(abs(bst$best_score - 0.000621) < TOLERANCE)
eval_results <- bst$eval_valid(feval = evalerror)[[1L]]
expect_true(eval_results[["data_name"]] == "eval")
expect_true(abs(eval_results[["value"]] - 0.0006207325) < TOLERANCE)
expect_true(eval_results[["name"]] == "error")
expect_false(eval_results[["higher_better"]])
}) |
context("Test RSA formats")
sk1 <- read_key("../keys/id_rsa")
pk1 <- read_pubkey("../keys/id_rsa.pub")
test_that("reading protected keys", {
sk2 <- read_key("../keys/id_rsa.pw", password = "test")
sk3 <- read_key("../keys/id_rsa.openssh")
sk4 <- read_key("../keys/id_rsa.openssh.pw", password = "test")
expect_equal(sk1, sk2)
expect_equal(sk1, sk3)
expect_equal(sk1, sk4)
expect_error(read_key("../keys/id_rsa.pw", password = ""), "bad")
})
test_that("reading public key formats", {
pk2 <- read_pubkey("../keys/id_rsa.pem")
pk3 <- read_pubkey("../keys/id_rsa.pub")
pk4 <- read_pubkey("../keys/id_rsa.sshpub")
pk5 <- read_pubkey("../keys/id_rsa.sshpem2")
pk6 <- as.list(sk1)$pubkey
expect_equal(pk1, pk2)
expect_equal(pk1, pk3)
expect_equal(pk1, pk4)
expect_equal(pk1, pk5)
expect_equal(pk1, pk6)
})
test_that("legacy pkcs1 format", {
expect_equal(sk1, read_key(write_pkcs1(sk1)))
expect_equal(sk1, read_key(write_pkcs1(sk1, password = 'test'), password = 'test'))
expect_equal(pk1, read_pubkey(write_pkcs1(pk1)))
expect_error(read_key(write_pkcs1(sk1, password = 'test'), password = ''))
})
test_that("pubkey ssh fingerprint", {
fp <- paste(as.list(pk1)$fingerprint, collapse = "")
expect_equal(fp, "3ad46117a06192f13e55beb3cd4cfa6f")
pk7 <- read_pubkey(readLines("../keys/authorized_keys")[2])
expect_equal(pk1, pk7)
pk8 <- read_pubkey(write_ssh(pk1))
expect_equal(pk1, pk8)
})
test_that("signatures", {
msg <- readBin("../keys/message", raw(), 100)
sig <- readBin("../keys/message.sig.rsa.md5", raw(), 1000)
expect_equal(signature_create(msg, md5, sk1), sig)
expect_true(signature_verify(msg, sig, md5, pk1))
sig <- readBin("../keys/message.sig.rsa.sha1", raw(), 1000)
expect_equal(signature_create(msg, sha1, sk1), sig)
expect_true(signature_verify(msg, sig, sha1, pk1))
sig <- readBin("../keys/message.sig.rsa.sha256", raw(), 1000)
expect_equal(signature_create(msg, sha256, sk1), sig)
expect_true(signature_verify(msg, sig, sha256, pk1))
})
test_that("roundtrip pem format", {
expect_equal(pk1, read_pubkey(write_pem(pk1)))
expect_equal(sk1, read_key(write_pem(sk1, password = NULL)))
expect_equal(pk1, read_pubkey(write_pem(pk1, tempfile())))
expect_equal(sk1, read_key(write_pem(sk1, tempfile(), password = NULL)))
})
test_that("roundtrip der format", {
expect_equal(pk1, read_pubkey(write_der(pk1), der = TRUE))
expect_equal(sk1, read_key(write_der(sk1), der = TRUE))
expect_equal(pk1, read_pubkey(write_der(pk1, tempfile()), der = TRUE))
expect_equal(sk1, read_key(write_der(sk1, tempfile()), der = TRUE))
})
test_that("signature path interface", {
sig <- signature_create("../keys/message", sha256, "../keys/id_rsa")
writeBin(sig, tmp <- tempfile())
expect_true(signature_verify("../keys/message", tmp, sha256, "../keys/id_rsa.pub"))
})
test_that("rsa_keygen works", {
key <- rsa_keygen(1024)
expect_is(key, "rsa")
expect_equal(as.list(key)$size, 1024)
rm(key)
key <- rsa_keygen(2048)
expect_is(key, "rsa")
expect_equal(as.list(key)$size, 2048)
rm(key)
})
rm(sk1, pk1) |
require(Rcpp)
require(Matrix)
NAMESPACE <- environment()
.onLoad <- function(libname, pkgname){
require(methods)
loadRcppModules()
if (exists(".presto.shutdown.handle.reg", envir = .GlobalEnv) == FALSE) {
assign(".presto.shutdown.handle.reg", TRUE, envir = .GlobalEnv)
assign(".Last", lastCleanupFunc, envir = .GlobalEnv)
}
}
.onDetach <- function(libpath){
distributedR_shutdown()
remove(list=".Last", envir = .GlobalEnv)
remove(list=".presto.shutdown.handle.reg", envir = .GlobalEnv)
}
lastCleanupFunc <- function(){
pkgname <- "distributedR"
packagename <- paste("package:",pkgname,sep="")
if(packagename %in% search()){
for(pkg in search()[-1L]) {
if(grepl("^package:", pkg) &&
exists(".Depends", pkg, inherits = FALSE) &&
pkgname %in% get(".Depends", pkg, inherits = FALSE)){
detach(name=pkg, unload=TRUE, force=TRUE, character.only=TRUE)
}
}
detach(name=packagename, unload=TRUE, force=TRUE, character.only=TRUE)
}
}
get_pm_object <- function(){
pm <- mget(".PrestoMaster", envir = .GlobalEnv, ifnotfound=list(NULL))
pm <- pm[[1]]
if(is.null(pm)) {
clear_presto_r_objs(FALSE)
stop("distributedR is not running")
} else {
if (pm$running() == FALSE) {
clear_presto_r_objs(FALSE)
stop("distributedR is not running")
}
}
pm
}
stop_workers <- function(bin_name="R-worker-bin") {
pm <- get_pm_object()
if (!is.null(pm)) {
hosts <- pm$worker_hosts()
ports <- pm$worker_ports()
rm(pm)
for (i in 1:length(hosts)) {
cmd = paste("ssh -n", hosts[[i]], "'", "killall", bin_name, "'", sep=" ")
message(paste("Running ", cmd, sep=""))
system(cmd, wait=FALSE, ignore.stdout=TRUE, ignore.stderr=TRUE)
}
}
return(TRUE)
}
.pass_env_var <- function() {
env_list <- c("ODBCINI", "VERTICAINI")
ret_str <- ""
for (el in env_list) {
ev <- Sys.getenv(el)
if (nchar(ev) > 0) {
ret_str <- paste(ret_str, "-v ", el, ":", ev, " ", sep="")
}
}
return (ret_str)
}
clean_string <- function(string) {
clean <- string;
clean <- gsub(" ","", clean, fixed=TRUE)
clean <- gsub("\n","", clean, fixed=TRUE)
clean <- gsub("\r","", clean, fixed=TRUE)
clean <- gsub("\t","", clean, fixed=TRUE)
}
start_workers <- function(cluster_conf, storage,
bin_path="./bin/start_proto_worker.sh",
executors=0, mem=0, rmt_home="", rmt_uid="", log=2) {
if (rmt_home == ""){
rmt_home <- getwd()
}
if (rmt_uid==""){
rmt_uid = Sys.getenv(c("USER"))
}
library(XML)
resourcePool <- data.frame()
iscolocated <- isColocated(cluster_conf)
if(isTRUE(iscolocated)){
dsnName <- getDSN_Name(cluster_conf)
if(is.null(dsnName) | dsnName == 'NULL'){
stop("DSN Name in the config file cannot be null when Co-locating with Vertica.")
}
if(! require(vRODBC))
library(RODBC)
connect <- odbcConnect(dsnName)
resourcePool <- sqlQuery(connect, "select memory_size_kb, cpu_affinity_mask, cpu_affinity_mode from resource_pool_status where pool_name = 'distributedr' limit 1");
close(connect)
if(nrow(resourcePool)!=1){
stop("Could not locate the distritubedr resource pool. Please create a resource pool named distributedr.")
}
}
worker_conf <- conf2df(cluster_conf)
master_addr <- get_pm_object()$get_master_addr()
master_port <- get_pm_object()$get_master_port()
master_addr <- clean_string(master_addr)
master_port <- clean_string(master_port)
env_variables <- .pass_env_var()
tryCatch({
for(i in 1:nrow(worker_conf)) {
r <- worker_conf[i,]
r$Hostname <- clean_string(r$Hostname)
r$StartPortRange <- clean_string(r$StartPortRange)
r$EndPortRange <- clean_string(r$EndPortRange)
r$SharedMemory <- clean_string(r$SharedMemory)
r$Executors <- clean_string(r$Executors)
m <- ifelse(as.numeric(mem)>0, mem, ifelse(is.na(r$SharedMemory), 0, r$SharedMemory))
e <- ifelse(as.numeric(executors)>0, executors, ifelse(is.na(r$Executors), 0, r$Executors))
if (as.numeric(e)>64)
{
message(paste("Warning: distributedR only supports 64 Executors per worker.\nNumber of Executors has been truncated from ", e, " to 64 for worker ", r$Hostname, "\n", sep=""))
e <- 64
}
sp_opt <- getOption("scipen")
options("scipen"=100000)
local_cmd <- paste("cd",rmt_home,";", bin_path,
"-m", m, "-e", e, "-s", storage, "-p", r$StartPortRange, "-q", r$EndPortRange, "-l", log, "-a", master_addr, "-b", master_port,
"-w", r$Hostname, env_variables, sep=" ")
ssh_cmd <- paste("ssh -n", paste(rmt_uid,"@",r$Hostname,sep=""), "'", local_cmd,"'", sep=" ")
if(r$Hostname == "localhost" || r$Hostname == "127.0.0.1") {
cmd <- local_cmd;
}
else {
cmd <- ssh_cmd;
}
if(isTRUE(iscolocated)){
cmd <- paste(cmd, "-c", iscolocated, "-o", resourcePool[1,1], "-k", resourcePool[1,2], "-d", resourcePool[1,3], sep=" ")
}
options("scipen"=sp_opt)
system(cmd, wait=FALSE, ignore.stdout=TRUE, ignore.stderr=TRUE)
}
}, error = handle_presto_exception)
return(TRUE)
}
distributedR_start <- function(inst=0, mem=0,
cluster_conf="", executors=0,
log=2, storage="worker") {
gcinfo(FALSE)
gc()
ret<-TRUE
presto_home=""
workers=TRUE
rmt_home=""
rmt_uid=""
yarn=FALSE
if(tolower(storage) != "executor" && tolower(storage) != "worker") stop("Argument 'storage' can either be worker or executor")
if(!(is.numeric(executors) && floor(executors)==executors && executors>=0)) stop("Argument 'executors' should be a non-negative integral value")
if(!(is.numeric(inst) && floor(inst)==inst && inst>=0)) stop("Argument 'inst' should be a non-negative integral value")
if(!(is.numeric(mem) && mem>=0)) stop("Argument 'mem' should be a non-negative number")
if(executors == 0) executors <- inst
pm <- NULL
tryCatch(pm <- get_pm_object(), error=function(e){})
if (!is.null(pm)){
stop("distributedR is already running. Call distributedR_shutdown() to terminate existing session\n")
}
if(presto_home==""){
presto_home<-ifelse(Sys.getenv(c("DISTRIBUTEDR_HOME"))=="", system.file(package='distributedR'), Sys.getenv(c("DISTRIBUTEDR_HOME")))
}
if (cluster_conf==""){
cluster_conf <- ifelse(Sys.getenv(c("DR_CLUSTER_CONF")) != "", Sys.getenv(c("DR_CLUSTER_CONF")), paste(presto_home,"/conf/cluster_conf.xml",sep=""))
}
bin_path <- "./bin/start_proto_worker.sh"
normalized_config <- normalizePath(cluster_conf)
pm <- new ( PrestoMaster, normalized_config )
if (rmt_home == ""){
rmt_home <- presto_home
}
dobject_map <- new.env()
assign(".PrestoMaster", pm , envir = .GlobalEnv)
assign(".PrestoDobjectMap", dobject_map, envir = .GlobalEnv)
tryCatch({
if (workers) {
start_workers(cluster_conf=cluster_conf, storage=storage, bin_path=bin_path,
executors=executors, mem=mem, rmt_home=rmt_home, rmt_uid=rmt_uid, log=log)
}
else if (yarn){
dr_path <- system.file(package = "distributedR")
full_path <- paste(dr_path,'/yarn/yarn.R', sep='')
source(full_path)
}
pm$start(log, storage)
},error = function(excpt){
pm <- get_pm_object()
distributedR_shutdown(pm)
gcinfo(FALSE)
gc()
ret<-FALSE
stop(excpt$message)})
cat(paste("Master address:port - ", pm$get_master_addr(),":",pm$get_master_port(),"\n",sep=""))
ret<-ret && (check_dr_version_compatibility())
}
conf2df <- function(cluster_conf) {
tryCatch({
library(XML)
if(file.access(cluster_conf,mode=4)==-1) stop("Cannot read configuration file. Check file permissions.")
conf_xml <- xmlToList(cluster_conf)
conf_xml$Workers[which(names(conf_xml$Workers) %in% c("comment"))] <- NULL
for(i in 1:length(conf_xml$Workers)) {
conf_xml$Workers[[i]][which(names(conf_xml$Workers[[i]]) %in% c("comment"))] <- NULL
}
conf_df <- lapply(conf_xml$Workers, data.frame, stringsAsFactors=FALSE)
conf_df <- lapply(conf_df, function(X){
nms <- c("Hostname", "StartPortRange", "EndPortRange", "Executors", "SharedMemory")
missing <- setdiff(nms, names(X))
X[missing] <- NA
X <- X[nms]})
conf_df <- do.call(rbind.data.frame, conf_df)
row.names(conf_df) <- NULL
return(conf_df)
}, error = function(e) {
message(paste("Fail to parse cluster configuration XML file. Start with default values\n", e, "\n", sep=""))
})
tryCatch({
pm <- get_pm_object()
if (!is.null(pm)) {
hosts <- pm$worker_hosts()
port_start <- pm$worker_start_port_range()
port_end <- pm$worker_end_port_range()
conf_df <- data.frame(Hostname=hosts, StartPortRange=port_start, EndPortRange=port_end, Executors=NA, SharedMemory=NA, stringsAsFactors=FALSE)
return(conf_df)
}}, error = handle_presto_exception)
}
isColocated <- function(cluster_conf){
tryCatch({
if(file.access(cluster_conf,mode=4)==-1) stop("Cannot read configuration file. Check file permissions.")
conf_xml <- xmlToList(cluster_conf)
iscolocated <- FALSE
if(!is.null(conf_xml$ServerInfo$isColocatedWithVertica)){
iscolocated <- conf_xml$ServerInfo$isColocatedWithVertica
}
return(as.logical(iscolocated))
}, error = handle_presto_exception)
}
getDSN_Name <- function(cluster_conf){
tryCatch({
if(file.access(cluster_conf,mode=4)==-1) stop("Cannot read configuration file. Check file permissions.")
conf_xml <- xmlToList(cluster_conf)
return(conf_xml$ServerInfo$VerticaDSN)
}, error = handle_presto_exception)
}
distributedR_shutdown <- function(pm=NA, quiet=FALSE) {
ret<-TRUE
if(class(pm) != "Rcpp_PrestoMaster"){
tryCatch(pm <- get_pm_object(), error=function(e){})
if (is.null(pm)){
return(NULL)
}
}
tryCatch(pm$shutdown(),error = function(e){})
ret<-ret && clear_presto_r_objs(FALSE)
}
clear_presto_r_objs <- function(darray_only=TRUE) {
if(darray_only == FALSE) {
rm_by_name <- c(".PrestoMaster", ".PrestoDobjectMap", "pm", ".__C__Rcpp_DistributedObject", ".__C__Rcpp_PrestoMaster")
for(rl in rm_by_name){
if(exists(rl, envir=.GlobalEnv) == TRUE){
rm(list=c(rl), envir=.GlobalEnv)
}
}
rm_by_class <- c("dobject", "splits", "Rcpp_PrestoMaster")
} else {
rm_by_class <- c("dobject", "splits")
}
vars <- ls(all=TRUE, envir=.GlobalEnv)
for(v in vars){
for (c in rm_by_class) {
eval_obj <- eval(as.name(v), envir=.GlobalEnv)
if (inherits(eval_obj, "list") == TRUE) {
lsize = length(eval_obj)
if (lsize > 0) {
for (i in lsize:1) {
if (inherits(eval_obj[[i]], c) == TRUE) {
eval(parse(text = paste(as.name(v), "[[", i, "]] <- NULL", sep="")), envir=.GlobalEnv)
}
}
}
} else {
if(inherits(eval_obj, c) == TRUE){
rm(list=c(eval(v)), envir=.GlobalEnv)
break
}
}
}
}
gcinfo(FALSE)
gc()
TRUE
}
distributedR_status <- function(help=FALSE){
stat_df <- NA
tryCatch({
pm <- get_pm_object()
if (!is.null(pm)) {
stat <- pm$presto_status()
stat_df <- as.data.frame(t(data.frame(stat, check.names = FALSE)))
stat_df <- data.frame(row.names(stat_df), stat_df)
row.names(stat_df) <- NULL
names(stat_df) <- c("Workers", "Inst", "SysMem", "MemUsed", "DarrayQuota", "DarrayUsed")
}},error = handle_presto_exception)
if(help==TRUE) {
cat("\ndistributedR_status - help\nWorkers: list of workers\nInst: number of executors on a worker\n")
cat("SysMem: total available system memory (MB)\nMemUsed: memory currently used in a worker (MB)\n")
cat("DarrayQuota: memory for darrays (MB)\nDarrayUsed: memory currently used by darray (MB)\n\n")
}
stat_df
}
.distributedR_ls <- function(){
tryCatch({
pm <- get_pm_object()
if (!is.null(pm)) {
pm$presto_ls()
}
},error = handle_presto_exception)
}
distributedR_master_info <- function() {
tryCatch({
pm <- get_pm_object()
if (!is.null(pm)) {
master_addr <- pm$get_master_addr()
master_port <- as.integer(pm$get_master_port())
asc <- function(x) {strtoi(charToRaw(x),16L)}
session_id <- master_port + sum(unlist(lapply(strsplit(master_addr, "")[[1]], asc)))
list(address=master_addr, port=master_port, sessionID=session_id)
}
},error = handle_presto_exception)
}
handle_presto_exception <- function (excpt){
excpt_class <- class(excpt)[1L]
if (excpt_class=="presto::PrestoShutdownException") {
message(excpt$message)
pm <- get_pm_object()
distributedR_shutdown(pm)
gcinfo(FALSE)
gc()
stop()
} else if (excpt_class=="presto::PrestoWarningException"){
stop(excpt$message)
} else {
stop(excpt$message)
}
}
check_dr_version_compatibility<-function(){
nworkers<-get_pm_object()$get_num_workers()
temp<-dframe(c(nworkers,1),c(1,1))
foreach(i, 1:npartitions(temp), function(x=splits(temp,i)){
x=data.frame(v=packageVersion("distributedR"))
update(x)
}, progress=FALSE)
vers<-getpartition(temp)
master_version<-packageVersion("distributedR")
bad_workers<-which(master_version != vers$v)
if(length(bad_workers)>0){
message(paste("Error: Incompatible distributedR versions in the cluster (master=",master_version,", worker(s)=",vers$v[(bad_workers[1])],")\nInstall same version across cluster. Shutting down session.", sep=""))
distributedR_shutdown()
return (FALSE)
}
return (TRUE)
}
ddyn.load <- function(x, trace = FALSE){
number_of_executors <- sum(distributedR_status()$Inst)
y <- lapply(x, .loadLibrary , trace=trace, num_of_Exec = number_of_executors)
}
.loadLibrary <- function(x, trace = FALSE, num_of_Exec) {
if(!is.character(x)){
stop("x must be of type character")
}
foreach(i, 1:num_of_Exec, progress=trace, function(x=x) {
thePath = paste(find.package(x), "/libs/", x, ".so", sep="")
dyn.load(thePath)
})
}
ddyn.unload <- function(x, trace = FALSE){
number_of_executors <- sum(distributedR_status()$Inst)
y <- lapply(x, .unloadLibrary, trace=trace, num_of_Exec = number_of_executors)
}
.unloadLibrary <- function(x, trace = FALSE, num_of_Exec) {
if(!is.character(x)){
stop("x must be of type character")
}
foreach(i, 1:num_of_Exec, progress=trace, function(x=x) {
thePath = paste(find.package(x), "/libs/", x, ".so", sep="")
dyn.unload(thePath)
})
} |
lrppage <- tabItem(tabName = "lrpos",
h2("Positive likelihood ratio"),
"Calculate precision or sample size for the positive likelihood ratio based on sensitivity and specificity. Formula 10 from Simel et al is used.",
tags$br(),
"Groups here refer to e.g. the disease status.",
tags$br(),
"",
h4("Please enter the following"),
sliderInput("lrp_prev", "Prevalence",
min = 0, max = 1, value = .5),
sliderInput("lrp_sens", "Sensitivity",
min = 0, max = 1, value = .5),
sliderInput("lrp_spec", "Specificity",
min = 0, max = 1, value = .5),
h4("Please enter one of the following"),
uiOutput("lrp_resetable_input"),
actionButton("lpr_reset_input",
"Reset 'Total sample size' or 'Confidence interval width'"),
h4("Results"),
verbatimTextOutput("lrp_out"),
tableOutput("lrp_tab"),
"Code to replicate in R:",
verbatimTextOutput("lrp_code"),
h4("References"),
"Simel, DL, Samsa, GP and Matchar, DB (1991) Likelihood ratios with confidence: Sample size estimation for diagnostic test studies. ", tags$i("J Clin Epidemiol"), "44(8), 763-770, DOI 10.1016/0895-4356(91)90128-v"
)
lrp_fn <- function(input, code = FALSE){
if(is.na(input$lrp_n) & is.na(input$lrp_ciwidth)) {
cat("Awaiting 'number of observations' or 'confidence interval width'")
} else {
z <- ifelse(is.na(input$lrp_n),
paste0("conf.width = ", input$lrp_ciwidth),
paste0("n = ", input$lrp_n))
x <- paste0("prec_pos_lr(prev = ", input$lrp_prev,
", sens = ", input$lrp_sens,
", spec = ", input$lrp_spec,
", ", z,
", conf.level = ", input$conflevel,
")")
if(code){
cat(x)
} else {
eval(parse(text = x))
}
}
} |
"covid_testing" |
library(epos)
context("test_calcCosine")
test_that("Test calcCosine if it calculates the correct vector with cosine coefficients", {
expect_that(calcCosine(c(1,2,3), c(2,3,4)), equals(1-c(0.0, 0.5, 2/3)))
}) |
setMethod("cnetplot", signature(x = "enrichResult"),
function(x, showCategory = 5,
foldChange = NULL, layout = "kk", ...) {
cnetplot.enrichResult(x, showCategory = showCategory,
foldChange = foldChange, layout = layout, ...)
})
setMethod("cnetplot", signature(x = "list"),
function(x, showCategory = 5,
foldChange = NULL, layout = "kk", ...) {
cnetplot.enrichResult(x, showCategory = showCategory,
foldChange = foldChange, layout = layout, ...)
})
setMethod("cnetplot", signature(x = "gseaResult"),
function(x, showCategory = 5,
foldChange = NULL, layout = "kk", ...) {
cnetplot.enrichResult(x, showCategory = showCategory,
foldChange = foldChange, layout = layout, ...)
})
setMethod("cnetplot", signature(x = "compareClusterResult"),
function(x, showCategory = 5,
foldChange = NULL, layout = "kk", ...) {
cnetplot.compareClusterResult(x, showCategory = showCategory,
foldChange = foldChange, layout = layout, ...)
})
cnetplot.enrichResult <- function(x,
showCategory = 5,
foldChange = NULL,
layout = "kk",
colorEdge = FALSE,
circular = FALSE,
node_label = "all",
cex_category = 1,
cex_gene = 1,
cex_label_category = 1,
cex_label_gene = 1,
color_category = "
color_gene = "
shadowtext = "all",
...) {
label_size_category <- 5
label_size_gene <- 5
node_label <- match.arg(node_label, c("category", "gene", "all", "none"))
if (circular) {
layout <- "linear"
geom_edge <- geom_edge_arc
} else {
geom_edge <- geom_edge_link
}
if (is.logical(shadowtext)) {
shadowtext <- ifelse(shadowtext, "all", "none")
}
shadowtext_category <- shadowtext_gene <- FALSE
if (shadowtext == "all") shadowtext_category <- shadowtext_gene <- TRUE
if (shadowtext == "category") shadowtext_category <- TRUE
if (shadowtext == "gene") shadowtext_gene <- TRUE
geneSets <- extract_geneSets(x, showCategory)
g <- list2graph(geneSets)
if (!inherits(x, "list")) {
foldChange <- fc_readable(x, foldChange)
}
size <- sapply(geneSets, length)
V(g)$size <- min(size)/2
n <- length(geneSets)
V(g)$size[1:n] <- size
node_scales <- c(rep(cex_category, n), rep(cex_gene, (length(V(g)) - n)))
if (colorEdge) {
E(g)$category <- rep(names(geneSets), sapply(geneSets, length))
edge_layer <- geom_edge(aes_(color = ~category), alpha=.8)
} else {
edge_layer <- geom_edge(alpha=.8, colour='darkgrey')
}
if (!is.null(foldChange)) {
fc <- foldChange[V(g)$name[(n+1):length(V(g))]]
V(g)$color <- NA
V(g)$color[(n+1):length(V(g))] <- fc
show_legend <- c(TRUE, FALSE)
names(show_legend) <- c("color", "size")
p <- ggraph(g, layout=layout, circular = circular)
p <- p + edge_layer +
geom_node_point(aes_(color=~I(color_category), size=~size),
data = p$data[1:n, ]) +
scale_size(range=c(3, 8) * cex_category) +
ggnewscale::new_scale_color() +
geom_node_point(aes_(color=~as.numeric(as.character(color)), size=~I(3 * cex_gene)),
data = p$data[-(1:n), ], show.legend = show_legend) +
scale_colour_gradient2(name = "fold change", low = "blue",
mid = "white", high = "red",
guide = guide_colorbar(order = 2))
} else {
V(g)$color <- color_gene
V(g)$color[1:n] <- color_category
p <- ggraph(g, layout=layout, circular=circular)
p <- p + edge_layer +
geom_node_point(aes_(color=~I(color), size=~size), data = p$data[1:n, ]) +
scale_size(range=c(3, 8) * cex_category) +
geom_node_point(aes_(color=~I(color), size=~I(3 * cex_gene)),
data = p$data[-(1:n), ], show.legend = FALSE)
}
p <- p + theme_void()
if (node_label == "category") {
p <- add_node_label(p = p, data = p$data[1:n,], label_size_node = label_size_category,
cex_label_node = cex_label_category, shadowtext = shadowtext_category)
} else if (node_label == "gene") {
p <- add_node_label(p = p, data = p$data[-c(1:n),], label_size_node = label_size_gene,
cex_label_node = cex_label_gene, shadowtext = shadowtext_gene)
} else if (node_label == "all") {
p <- add_node_label(p = p, data = p$data[-c(1:n),], label_size_node = label_size_gene,
cex_label_node = cex_label_gene, shadowtext = shadowtext_gene)
p <- add_node_label(p = p, data = p$data[1:n,], label_size_node = label_size_category,
cex_label_node = cex_label_category, shadowtext = shadowtext_category)
}
if (!is.null(foldChange)) {
p <- p + guides(size = guide_legend(order = 1),
color = guide_colorbar(order = 2))
}
return(p)
}
cnetplot.compareClusterResult <- function(x,
showCategory = 5,
foldChange = NULL,
layout = "kk",
colorEdge = FALSE,
circular = FALSE,
node_label = "all",
split=NULL,
pie = "equal",
cex_category = 1,
cex_gene = 1,
legend_n = 5,
x_loc = NULL,
y_loc = NULL,
cex_label_category = 1,
cex_label_gene = 1,
shadowtext = "all",
...) {
label_size_category <- 2.5
label_size_gene <- 2.5
range_category_size <- c(3, 8)
range_gene_size <- c(3, 3)
if (is.logical(shadowtext)) {
shadowtext <- ifelse(shadowtext, "all", "none")
}
shadowtext_category <- shadowtext_gene <- FALSE
if (shadowtext == "all") shadowtext_category <- shadowtext_gene <- TRUE
if (shadowtext == "category") shadowtext_category <- TRUE
if (shadowtext == "gene") shadowtext_gene <- TRUE
y <- fortify(x, showCategory = showCategory,
includeAll = TRUE, split = split)
y$Cluster <- sub("\n.*", "", y$Cluster)
if ("core_enrichment" %in% colnames(y)) {
y$geneID <- y$core_enrichment
}
y_union <- merge_compareClusterResult(y)
node_label <- match.arg(node_label, c("category", "gene", "all", "none"))
if (circular) {
layout <- "linear"
geom_edge <- geom_edge_arc
} else {
geom_edge <- geom_edge_link
}
geneSets <- setNames(strsplit(as.character(y_union$geneID), "/",
fixed = TRUE), y_union$Description)
n <- length(geneSets)
g <- list2graph(geneSets)
edge_layer <- geom_edge(alpha=.8, colour='darkgrey')
if(is.null(dim(y)) | nrow(y) == 1) {
V(g)$size <- 1
V(g)$size[1] <- 3
V(g)$color <- "
V(g)$color[1] <- "
title <- y$Cluster
p <- ggraph(g, layout=layout, circular=circular)
p <- p + edge_layer + theme_void() +
geom_node_point(aes_(color=~I(color), size=~size),
data = p$data[1:n, ]) +
scale_size(range = range_category_size * cex_category) +
ggnewscale::new_scale("size") +
geom_node_point(aes_(color=~I(color), size=~size),
data = p$data[-(1:n), ], show.legend = FALSE) +
scale_size(range = range_gene_size * cex_gene) +
labs(title= title) +
theme(legend.position="none")
p <- add_node_label(p = p, data = p$data[-c(1:n),], label_size_node = label_size_gene,
cex_label_node = cex_label_gene, shadowtext = shadowtext_gene)
p <- add_node_label(p = p, data = p$data[1:n,], label_size_node = label_size_category,
cex_label_node = cex_label_category, shadowtext = shadowtext_category)
return(p)
}
if(is.null(dim(y_union)) | nrow(y_union) == 1) {
p <- ggraph(g, "tree") + edge_layer
} else {
p <- ggraph(g, layout=layout, circular=circular) + edge_layer
}
ID_Cluster_mat <- prepare_pie_category(y, pie=pie)
gene_Cluster_mat <- prepare_pie_gene(y)
if(ncol(ID_Cluster_mat) > 1) {
clusters <- match(colnames(ID_Cluster_mat),colnames(gene_Cluster_mat))
ID_Cluster_mat <- ID_Cluster_mat[,clusters]
gene_Cluster_mat <- gene_Cluster_mat[,clusters]
}
ID_Cluster_mat2 <- rbind(ID_Cluster_mat,gene_Cluster_mat)
aa <- p$data
ii <- match(rownames(ID_Cluster_mat2), aa$name)
ID_Cluster_mat2$x <- aa$x[ii]
ID_Cluster_mat2$y <- aa$y[ii]
ii <- match(rownames(ID_Cluster_mat2)[1:n], y_union$Description)
node_scales <- c(rep(cex_category, n), rep(cex_gene, (length(V(g)) - n)))
sum_yunion <- sum(y_union[ii, "Count"])
sizee <- sqrt(y_union[ii, "Count"] / sum_yunion)
ID_Cluster_mat2$radius <- min(sizee)/2 * sqrt(cex_gene)
ID_Cluster_mat2$radius[1:n] <- sizee * sqrt(cex_category)
if(is.null(x_loc)) x_loc <- min(ID_Cluster_mat2$x)
if(is.null(y_loc)) y_loc <- min(ID_Cluster_mat2$y)
if (node_label == "category") {
p$data$name[(n+1):nrow(p$data)] <- ""
} else if (node_label == "gene") {
p$data$name[1:n] <- ""
} else if (node_label == "none") {
p$data$name <- ""
}
if(ncol(ID_Cluster_mat2) > 4) {
if (!is.null(foldChange)) {
log_fc <- abs(foldChange)
genes <- rownames(ID_Cluster_mat2)[(n+1):nrow(ID_Cluster_mat2)]
gene_fc <- rep(1,length(genes))
gid <- names(log_fc)
ii <- gid %in% names(x@gene2Symbol)
gid[ii] <- x@gene2Symbol[gid[ii]]
ii <- match(genes,gid)
gene_fc <- log_fc[ii]
gene_fc[is.na(gene_fc)] <- 1
gene_fc2 <- c(rep(1,n),gene_fc)
ID_Cluster_mat2$radius <- min(sizee)/2*gene_fc2 * sqrt(cex_gene)
ID_Cluster_mat2$radius[1:n] <- sizee * sqrt(cex_category)
p <- p + geom_scatterpie(aes_(x=~x,y=~y,r=~radius),
data=ID_Cluster_mat2[1:n, ],
cols=colnames(ID_Cluster_mat2)[1:(ncol(ID_Cluster_mat2)-3)], color=NA) +
geom_scatterpie_legend(ID_Cluster_mat2$radius[1:n],
x=x_loc, y=y_loc + 3, n = legend_n, labeller=function(x) round(x^2 * sum_yunion / cex_category)) +
geom_scatterpie(aes_(x=~x,y=~y,r=~radius),
data=ID_Cluster_mat2[-(1:n), ],
cols=colnames(ID_Cluster_mat2)[1:(ncol(ID_Cluster_mat2)-3)],
color=NA, show.legend = FALSE) +
coord_equal()+
geom_scatterpie_legend(ID_Cluster_mat2$radius[(n+1):nrow(ID_Cluster_mat2)],
x=x_loc, y=y_loc, n = legend_n,
labeller=function(x) round(x*2/(min(sizee))/sqrt(cex_gene),3)) +
ggplot2::annotate("text", x = x_loc + 3, y = y_loc, label = "log2FC") +
ggplot2::annotate("text", x = x_loc + 3, y = y_loc + 3, label = "gene number")
p <- add_node_label(p = p, data = p$data[-c(1:n),], label_size_node = label_size_gene,
cex_label_node = cex_label_gene, shadowtext = shadowtext_gene)
p <- add_node_label(p = p, data = p$data[1:n,], label_size_node = label_size_category,
cex_label_node = cex_label_category, shadowtext = shadowtext_category)
p <- p + theme_void() + labs(fill = "Cluster")
return(p)
}
p <- p + geom_scatterpie(aes_(x=~x,y=~y,r=~radius),
data=ID_Cluster_mat2[1:n, ],
cols=colnames(ID_Cluster_mat2)[1:(ncol(ID_Cluster_mat2)-3)], color=NA) +
geom_scatterpie(aes_(x=~x,y=~y,r=~radius),
data=ID_Cluster_mat2[-(1:n), ],
cols=colnames(ID_Cluster_mat2)[1:(ncol(ID_Cluster_mat2)-3)],
color=NA, show.legend = FALSE) +
coord_equal() +
geom_scatterpie_legend(ID_Cluster_mat2$radius[1:n],
x=x_loc, y=y_loc, n = legend_n, labeller=function(x) round(x^2 * sum_yunion / cex_category)) +
ggplot2::annotate("text", x = x_loc + 3, y = y_loc, label = "gene number")
p <- add_node_label(p = p, data = p$data[-c(1:n),], label_size_node = label_size_gene,
cex_label_node = cex_label_gene, shadowtext = shadowtext_gene)
p <- add_node_label(p = p, data = p$data[1:n,], label_size_node = label_size_category,
cex_label_node = cex_label_category, shadowtext = shadowtext_category)
p <- p + theme_void() + labs(fill = "Cluster")
return(p)
}
title <- colnames(ID_Cluster_mat2)[1]
V(g)$size <- ID_Cluster_mat2$radius
V(g)$color <- "
V(g)$color[1:n] <- "
ggraph(g, layout=layout, circular=circular) +
edge_layer +
geom_node_point(aes_(color=~I(color), size=~size),
data = p$data[1:n, ]) +
scale_size(range = range_category_size * cex_category) +
ggnewscale::new_scale("size") +
geom_node_point(aes_(color=~I(color), size=~size),
data = p$data[-(1:n), ], show.legend = FALSE) +
scale_size(range = range_gene_size * cex_gene) +
labs(title= title)
p <- add_node_label(p = p, data = p$data[-c(1:n),], label_size_node = label_size_gene,
cex_label_node = cex_label_gene, shadowtext = shadowtext_gene)
p <- add_node_label(p = p, data = p$data[1:n,], label_size_node = label_size_category,
cex_label_node = cex_label_category, shadowtext = shadowtext_category)
p <- p + theme_void() + theme(legend.position="none")
} |
test_that("works as expected", {
ecopy( iris, showrowcolnames = "cols", show = 'show' )
ecopy( iris )
ecopy( 'hello' )
result = tryCatch({
readClipboard(format = 1, raw = FALSE)
},
error = function(e) {}
)
if(!is.null(result)){
expect_equal(result, 'hello')
expect_error( { ecopy( iris, showrowcolnames = "wrong", show = 'show' ) }, 'should be one of' )
}
}) |
fit_SKAT_NULL = function(kins = NULL,
phenoFile = "",
phenoCol = "",
traitType = "quantitative",
invNormalize = FALSE,
covarColList = NULL,
qCovarCol = NULL,
sampleIDColinphenoFile = "",
outputPrefix = "",
isCovariateTransform = FALSE,
sampleFileForDosages="",
methodforRelatedSample="EMMAX",
isDiagofKinSetAsOne = FALSE){
modelOut=paste0(outputPrefix, ".rda")
if(!file.exists(modelOut)){
file.create(modelOut, showWarnings = TRUE)
}
if(!file.exists(phenoFile)){
stop("ERROR! phenoFile ", phenoFile, " does not exsit\n")
}else{
ydat = data.table:::fread(phenoFile, header=T, stringsAsFactors=FALSE, colClasses=list(character = sampleIDColinphenoFile))
data = data.frame(ydat)
for(i in c(phenoCol, covarColList, qCovarCol, sampleIDColinphenoFile)){
if(!(i %in% colnames(data))){
stop("ERROR! column for ", i, " does not exsit in the phenoFile \n")
}
}
if(length(covarColList) > 0){
formula = paste0(phenoCol,"~", paste0(covarColList,collapse="+"))
hasCovariate = TRUE
}else{
formula = paste0(phenoCol,"~ 1")
hasCovariate = FALSE
}
cat("formula is ", formula,"\n")
formula.null = as.formula(formula)
mmat = model.frame(formula.null, data, na.action=NULL)
mmat$IID = data[,which(sampleIDColinphenoFile == colnames(data))]
mmat_nomissing = mmat[complete.cases(mmat),]
cat(nrow(mmat_nomissing), " samples have non-missing phenotypes\n")
}
if(traitType == "quantitative"){
if(invNormalize){
cat("Perform the inverse nomalization for ", phenoCol, "\n")
invPheno = qnorm((rank(mmat_nomissing[,which(colnames(mmat_nomissing) == phenoCol)], na.last="keep")-0.5)/sum(!is.na(mmat_nomissing[,which(colnames(mmat_nomissing) == phenoCol)])))
mmat_nomissing[,which(colnames(mmat_nomissing) == phenoCol)] = invPheno
}
}
if(!is.null(kins)){
if(isDiagofKinSetAsOne){
diag(kins) = 1
}
if(methodforRelatedSample == "EMMAX"){
if(traitType == "quantitative"){
out.obj = SKAT:::SKAT_NULL_emmaX(formula.null, data = mmat_nomissing, K=kins)
}else{
stop("SKAT_NULL_emmaX does not work for binary tratis \n")
}
}else if(methodforRelatedSample == "GMMAT"){
if(traitType == "quantitative"){
out.obj = GMMAT:::glmmkin(formula.null, data = mmat_nomissing, family=gaussian(link = "identity"), kins=as.matrix(kins), verbose=T)
}else{
out.obj = GMMAT:::glmmkin(formula.null, data = mmat_nomissing, family=binomial(link = "logit"), kins=as.matrix(kins), verbose=T)
}
}
}else{
if(traitType == "quantitative"){
out.obj = SKAT:::SKAT_Null_Model(formula.null, data = mmat_nomissing, out_type="C")
}else{
out.obj = SKAT:::SKAT_Null_Model(formula.null, data = mmat_nomissing, out_type="D")
}
}
out.obj$sampleID = mmat_nomissing$IID
out.obj$traitType = traitType
save(out.obj, file = modelOut)
} |
vote_mun_zone_local <- function(year, uf = "all",
ascii = FALSE,
encoding = "latin1",
export = FALSE, temp = TRUE){
test_encoding(encoding)
test_local_year(year)
uf <- test_uf(uf)
filenames <- paste0("/votacao_candidato_munzona_", year, ".zip")
dados <- paste0(file.path(tempdir()), filenames)
url <- "https://cdn.tse.jus.br/estatistica/sead/odsele/votacao_candidato_munzona%s"
download_unzip(url, dados, filenames, year)
if(temp == FALSE){
unlink(dados)
}
setwd(as.character(year))
banco <- juntaDados(uf, encoding, FALSE)
setwd("..")
unlink(as.character(year), recursive = T)
if(year <= 2012){
names(banco) <- c("DATA_GERACAO", "HORA_GERACAO", "ANO_ELEICAO", "NUM_TURNO", "DESCRICAO_ELEICAO",
"SIGLA_UF", "SIGLA_UE", "CODIGO_MUNICIPIO", "NOME_MUNICIPIO", "NUMERO_ZONA",
"CODIGO_CARGO", "NUMERO_CAND", "SQ_CANDIDATO", "NOME_CANDIDATO", "NOME_URNA_CANDIDATO",
"DESCRICAO_CARGO", "COD_SIT_CAND_SUPERIOR", "DESC_SIT_CAND_SUPERIOR", "CODIGO_SIT_CANDIDATO",
"DESC_SIT_CANDIDATO", "CODIGO_SIT_CAND_TOT", "DESC_SIT_CAND_TOT", "NUMERO_PARTIDO",
"SIGLA_PARTIDO", "NOME_PARTIDO", "SEQUENCIAL_LEGENDA", "NOME_COLIGACAO", "COMPOSICAO_LEGENDA",
"TOTAL_VOTOS")
} else {
names(banco) <- c("DATA_GERACAO", "HORA_GERACAO", "ANO_ELEICAO", "COD_TIPO_ELEICAO",
"NOME_TIPO_ELEICAO", "NUM_TURNO", "COD_ELEICAO", "DESCRICAO_ELEICAO",
"DATA_ELEICAO", "ABRANGENCIA", "SIGLA_UF", "SIGLA_UE", "NOME_UE",
"CODIGO_MUNICIPIO", "NOME_MUNICIPIO", "NUMERO_ZONA", "CODIGO_CARGO",
"DESCRICAO_CARGO", "SQ_CANDIDATO", "NUMERO_CAND", "NOME_CANDIDATO",
"NOME_URNA_CANDIDATO", "NOME_SOCIAL_CANDIDATO", "CODIGO_SIT_CANDIDATO",
"DESC_SIT_CANDIDATO", "COD_SIT_CAND_SUPERIOR", "DESC_SIT_CAND_SUPERIOR",
"TIPO_AGREMIACAO", "NUMERO_PARTIDO", "SIGLA_PARTIDO", "NOME_PARTIDO",
"SEQUENCIAL_LEGENDA", "NOME_COLIGACAO", "COMPOSICAO_LEGENDA",
"CODIGO_SIT_CAND_TOT", "DESC_SIT_CAND_TOT", "TRANSITO","TOTAL_VOTOS" )
}
if(ascii == T) banco <- to_ascii(banco, encoding)
if(export) export_data(banco)
message("Done.\n")
return(banco)
} |
context("test-function")
test_that("test-function", {
N <- 100
declaration <- randomizr::declare_ra(N = N, m = 50)
Z <- randomizr::conduct_ra(declaration)
X <- rnorm(N)
Y <- .9 * X + .2 * Z + rnorm(N)
df <- data.frame(Y, X, Z)
test_fun <- function(data) {
with(data, var(Y[Z == 1]) - var(Y[Z == 0]))
}
ri_out <-
conduct_ri(
test_function = test_fun,
declaration = declaration,
assignment = "Z",
sharp_hypothesis = 0,
data = df, sims = 100
)
plot(ri_out)
summary(ri_out)
balance_fun <- function(data) {
f_stat <- summary(lm(Z ~ X, data = data))$f[1]
names(f_stat) <- NULL
return(f_stat)
}
balance_fun(df)
ri_out <-
conduct_ri(
test_function = balance_fun,
declaration = declaration,
assignment = "Z",
sharp_hypothesis = 0,
data = df, sims = 100
)
plot(ri_out)
summary(ri_out)
summary(lm(Z ~ X, data = df))
expect_true(TRUE)
}) |
library(dplyr)
library(corrr)
knitr::opts_chunk$set(collapse = TRUE, comment = "
library(corrr)
d <- correlate(mtcars, quiet = TRUE)
d
library(dplyr)
d %>% filter(cyl > .7)
d %>% select(term, mpg, cyl, disp)
d %>%
filter(cyl > .7) %>%
select(term, mpg, cyl, disp)
library(purrr)
d %>%
select(-term) %>%
map_dbl(~ mean(., na.rm = TRUE))
d %>% focus(mpg, cyl)
d %>%
focus(mpg:drat, mirror = TRUE) %>%
shave() %>%
fashion()
d %>%
focus(mpg:drat, mirror = TRUE) %>%
shave(upper = FALSE) %>%
rplot()
d %>%
focus(mpg:drat, mirror = TRUE) %>%
rearrange(absolute = FALSE) %>%
shave() %>%
rplot() |
paths_allowed <-
function(
paths = "/",
domain = "auto",
bot = "*",
user_agent = utils::sessionInfo()$R.version$version.string,
check_method = c("spiderbar"),
warn = getOption("robotstxt_warn", TRUE),
force = FALSE,
ssl_verifypeer = c(1,0),
use_futures = TRUE,
robotstxt_list = NULL,
verbose = FALSE,
rt_request_handler = robotstxt::rt_request_handler,
rt_robotstxt_http_getter = robotstxt::get_robotstxt_http_get,
on_server_error = on_server_error_default,
on_client_error = on_client_error_default,
on_not_found = on_not_found_default,
on_redirect = on_redirect_default,
on_domain_change = on_domain_change_default,
on_file_type_mismatch = on_file_type_mismatch_default,
on_suspect_content = on_suspect_content_default
){
if( all(domain == "auto") ){
domain <- guess_domain(paths)
paths <- remove_domain(paths)
}
if( all(is.na(domain)) & !is.null(robotstxt_list) ){
domain <- "auto"
}
if( is.null(robotstxt_list) ){
robotstxt_list <-
get_robotstxts(
domain = domain,
warn = warn,
force = force,
user_agent = user_agent,
ssl_verifypeer = ssl_verifypeer,
use_futures = use_futures,
verbose = verbose,
rt_request_handler = rt_request_handler,
rt_robotstxt_http_getter = rt_robotstxt_http_getter,
on_server_error = on_server_error,
on_client_error = on_client_error,
on_not_found = on_not_found,
on_redirect = on_redirect,
on_domain_change = on_domain_change,
on_file_type_mismatch = on_file_type_mismatch,
on_suspect_content = on_suspect_content
)
names(robotstxt_list) <- domain
}
if ( check_method[1] == "robotstxt"){
warning(
"
This check method is deprecated,
please stop using it -
use 'spiderbar' instead
or do not specify check_method parameter at all.
"
)
}
res <-
paths_allowed_worker_spiderbar(
domain = domain,
bot = bot,
paths = paths,
robotstxt_list = robotstxt_list
)
return(res)
} |
row_mean_dgcmatrix <- function(matrix) {
.Call('_sctransform_row_mean_dgcmatrix', PACKAGE = 'sctransform', matrix)
}
row_mean_grouped_dgcmatrix <- function(matrix, group, shuffle) {
.Call('_sctransform_row_mean_grouped_dgcmatrix', PACKAGE = 'sctransform', matrix, group, shuffle)
}
row_gmean_dgcmatrix <- function(matrix, eps) {
.Call('_sctransform_row_gmean_dgcmatrix', PACKAGE = 'sctransform', matrix, eps)
}
row_gmean_grouped_dgcmatrix <- function(matrix, group, eps, shuffle) {
.Call('_sctransform_row_gmean_grouped_dgcmatrix', PACKAGE = 'sctransform', matrix, group, eps, shuffle)
}
row_nonzero_count_dgcmatrix <- function(matrix) {
.Call('_sctransform_row_nonzero_count_dgcmatrix', PACKAGE = 'sctransform', matrix)
}
row_nonzero_count_grouped_dgcmatrix <- function(matrix, group) {
.Call('_sctransform_row_nonzero_count_grouped_dgcmatrix', PACKAGE = 'sctransform', matrix, group)
}
row_var_dgcmatrix <- function(x, i, rows, cols) {
.Call('_sctransform_row_var_dgcmatrix', PACKAGE = 'sctransform', x, i, rows, cols)
}
grouped_mean_diff_per_row <- function(x, group, shuffle) {
.Call('_sctransform_grouped_mean_diff_per_row', PACKAGE = 'sctransform', x, group, shuffle)
}
mean_boot <- function(x, N, S) {
.Call('_sctransform_mean_boot', PACKAGE = 'sctransform', x, N, S)
}
mean_boot_grouped <- function(x, group, N, S) {
.Call('_sctransform_mean_boot_grouped', PACKAGE = 'sctransform', x, group, N, S)
}
distribution_shift <- function(x) {
.Call('_sctransform_distribution_shift', PACKAGE = 'sctransform', x)
}
qpois_reg <- function(X, Y, tol, maxiters, minphi, returnfit) {
.Call('_sctransform_qpois_reg', PACKAGE = 'sctransform', X, Y, tol, maxiters, minphi, returnfit)
} |
ia.samp<-function(n.pair,conj=0){
mat<-matrix(0,2^n.pair,n.pair)
for(i in 1:n.pair)
mat[, i]<-rep(rep(c(1,conj),e=2^(n.pair-i)),2^(i-1))
mat
} |
image_WINDOW <- function(){
initializeDialog(title = gettextRcmdr("Drawing Heatmaps"),use.tabs=TRUE,tabs=c("tab1","tab2"))
AllResults <- .makeResultList()
onOK <- function(){}
onCancel <- function() {
if (GrabFocus())
tkgrab.release(top)
tkdestroy(top)
tkfocus(CommanderWindow())
}
onDataImage <- function(){
transf <- tclvalue(trans_vars)
if(transf=="none"){
temp.data <- get(ActiveDataSet(),envir=.GlobalEnv)
if(.is.binary.matrix(as.matrix(temp.data))){
col="c('grey','blue')"
image.command <- paste0("image(c(1:dim(",ActiveDataSet(),")[2]),c(1:dim(",ActiveDataSet(),")[1]),t(as.matrix(",ActiveDataSet(),")),col=",col,",axes=FALSE,useRaster=TRUE,ylab='Genes',xlab='Samples')")
doItAndPrint(image.command)
}
else{
image.command <- paste0("image(c(1:dim(",ActiveDataSet(),")[2]),c(1:dim(",ActiveDataSet(),")[1]),t(as.matrix(",ActiveDataSet(),")),col=viridis(511),axes=FALSE,useRaster=TRUE,ylab='Genes',xlab='Samples')")
doItAndPrint(image.command)
}
}
if(transf=="bin"){
col="c('grey','blue')"
thres <- tclvalue(thres_vars)
trans.command <- paste0("x <- binarize(x=as.matrix(",ActiveDataSet(),"),threshold=",thres,")")
doItAndPrint(trans.command)
image.command <- paste0("image(c(1:dim(x)[2]),c(1:dim(x)[1]),t(x),col=",col,",axes=FALSE,useRaster=TRUE,ylab='Genes',xlab='Samples')")
doItAndPrint(image.command)
}
if(transf=="disc"){
nlvl <- tclvalue(level_vars)
quan <- ifelse(tclvalue(quantile_vars)=='1',TRUE,FALSE)
trans.command <- paste0("x <- discretize(x=as.matrix(",ActiveDataSet(),"),nof=",nlvl,",quant=",quan,")")
doItAndPrint(trans.command)
image.command <- paste0("image(c(1:dim(x)[2]),c(1:dim(x)[1]),t(x),col=viridis(511,begin=1,end=0),axes=FALSE,useRaster=TRUE,ylab='Genes',xlab='Samples')")
doItAndPrint(image.command)
}
}
onResultImage <- function(){
sel <- as.integer(tkcurselection(resultBox))+1
if(length(AllResults)==0){
justDoIt(paste0("warning('No available results',call.=FALSE)"))
}
else if(length(sel)==0){
justDoIt(paste0("warning('No result selected',call.=FALSE)"))
}
else{
SelResult <- AllResults[sel]
eval(parse(text=paste0("temp.correct <- .correctdataforresult(",SelResult,")")))
if(temp.correct){
transf <- tclvalue(trans_vars2)
bin.thres <- tclvalue(thres_vars2)
disc.nof <- tclvalue(level_vars2)
disc.quant <- ifelse(tclvalue(quantile_vars)=='1',TRUE,FALSE)
BC <- tclvalue(BC_vars)
reorder <- ifelse(tclvalue(reorder_vars)=='1',TRUE,FALSE)
background <- ifelse(tclvalue(background_vars)=='1',TRUE,FALSE)
zeroBC <- ifelse(tclvalue(zeroBC_vars)=='1',TRUE,FALSE)
thresZ <- tclvalue(thresZ_vars)
thresL <- tclvalue(thresL_vars)
BCResult <- .tobiclust_transf(SelResult,thresZ=paste0(thresZ),thresL=paste0(thresL))
BC.highlight <- tclvalue(BChighlightSel_vars)
if(length(BC.highlight)==0){BC.highlight <- NULL}
BC.highlight.opacity <- tclvalue(BChighlightOpa_vars)
image.command <- paste0("HeatmapBC.GUI(data=",ActiveDataSet(),",res=",BCResult,",BC=",BC,",reorder=",reorder,",background=",background,",zeroBC=",zeroBC,",transf='",transf,"',bin.thres=",bin.thres,",disc.nof=",disc.nof,",disc.quant=",disc.quant,",BC.highlight=",BC.highlight,",BC.highlight.opacity=",BC.highlight.opacity,")")
doItAndPrint(image.command)
}
}
}
tab1Frame <- tkframe(tab1)
transformFrame <- tkframe(tab1Frame)
radioButtons(transformFrame,name="radioTransform",buttons=c("bin","disc","none"),values=c("bin","disc","none"),labels=gettextRcmdr(c("Binarization:","Discretation:","None")),initialValue="none",title="")
trans_vars <- radioTransformVariable
tkgrid(labelRcmdr(transformFrame,fg=getRcmdr("title.color"),font="RcmdrTitleFont" ,text=gettextRcmdr("Data Manipulation")),sticky="nw")
transformEntry <- tkframe(transformFrame)
thres_entry <- tkframe(transformEntry)
thres_vars <- tclVar("NA")
thres_field <- ttkentry(thres_entry,width=3,textvariable=thres_vars)
tkgrid(labelRcmdr(thres_entry,text=gettextRcmdr("Threshold (NA=median)")),thres_field,sticky="nw")
tkgrid(thres_entry,stick="nw")
disc_pms <- tkframe(transformEntry)
level_entry <- tkframe(disc_pms)
level_vars <- tclVar("10")
level_field <- ttkentry(level_entry,width=3,textvariable=level_vars)
tkgrid(labelRcmdr(level_entry,text=gettextRcmdr("Number of Levels")),level_field,sticky="nw")
checkBoxes(disc_pms,frame="quantilesCheck",boxes=paste("quantile"),initialValues=0,labels=gettextRcmdr("Use quantiles? (else equally spaced)"))
quantile_vars <- quantileVariable
tkgrid(level_entry,quantilesCheck,sticky="nw")
tkgrid.configure(quantilesCheck,padx="10")
tkgrid(disc_pms,sticky="nw")
tkgrid(radioTransformFrame,transformEntry,stick='nw')
tkgrid(transformFrame,stick="nw",padx="6",pady="6")
drawdataButton <- buttonRcmdr(tab1Frame,command=onDataImage,text=gettextRcmdr("Heatmap"),foreground="darkgreen",default="active",width="12",borderwidth=3)
tkgrid(drawdataButton,sticky="w",pady="15",padx="10")
tab2Frame <- tkframe(tab2)
ResultTransFrame <- tkframe(tab2Frame)
resultFrame <- tkframe(ResultTransFrame)
resultBox <- tklistbox( resultFrame , height=5, exportselection="FALSE",
selectmode="single", background="white")
for (result in AllResults) tkinsert(resultBox, "end", result)
resultScroll <- ttkscrollbar(resultFrame,command=function(...) tkyview(resultBox, ...))
tkconfigure(resultBox, yscrollcommand=function(...) tkset(resultScroll, ...))
if(length(AllResults)!=0){tkselection.set(resultBox,0)}
tkgrid(labelRcmdr(resultFrame,fg=getRcmdr("title.color"),font="RcmdrTitleFont",text=gettextRcmdr("Biclustering Results:")),sticky="nw")
tkgrid(resultBox,resultScroll)
tkgrid.configure(resultScroll,sticky="ns")
transformFrame2 <- tkframe(ResultTransFrame)
radioButtons(transformFrame2,name="radioTransform2",buttons=c("bin","disc","none"),values=c("bin","disc","none"),labels=gettextRcmdr(c("Binarization:","Discretation:","None")),initialValue="none",title="")
trans_vars2 <- radioTransform2Variable
tkgrid(labelRcmdr(transformFrame2,fg=getRcmdr("title.color"),font="RcmdrTitleFont" ,text=gettextRcmdr("Data Manipulation")),sticky="nw")
transformEntry2 <- tkframe(transformFrame2)
thres_entry2 <- tkframe(transformEntry2)
thres_vars2 <- tclVar("NA")
thres_field2 <- ttkentry(thres_entry2,width=3,textvariable=thres_vars2)
tkgrid(labelRcmdr(thres_entry2,text=gettextRcmdr("Threshold (NA=median)")),thres_field2,sticky="nw")
tkgrid(thres_entry2,stick="nw")
disc_pms2 <- tkframe(transformEntry2)
level_entry2 <- tkframe(disc_pms2)
level_vars2 <- tclVar("10")
level_field2 <- ttkentry(level_entry2,width=3,textvariable=level_vars2)
tkgrid(labelRcmdr(level_entry2,text=gettextRcmdr("Number of Levels")),level_field2,sticky="nw")
checkBoxes(disc_pms2,frame="quantilesCheck2",boxes=paste("quantile2"),initialValues=0,labels=gettextRcmdr("Use quantiles? (else equally spaced)"))
quantile_vars2 <- quantile2Variable
tkgrid(level_entry2,quantilesCheck2,sticky="nw")
tkgrid.configure(quantilesCheck2,padx="10")
tkgrid(disc_pms2,sticky="nw")
tkgrid(radioTransform2Frame,transformEntry2,stick='nw')
tkgrid(resultFrame,sticky="nw",padx="6",pady="6")
tkgrid(transformFrame2,sticky="nw",padx="6",pady="6")
tkgrid(ResultTransFrame,sticky="nw")
plotOptions <- tkframe(tab2Frame)
tkgrid(labelRcmdr(plotOptions,fg=getRcmdr("title.color"),font="RcmdrTitleFont",text=gettextRcmdr("Heatmap Options")),sticky="nw")
BC_entry <- tkframe(plotOptions)
BC_vars <- tclVar("c()")
BC_field <- ttkentry(BC_entry,width=15,textvariable=BC_vars)
tkgrid(labelRcmdr(BC_entry,text=gettextRcmdr("Biclusters Selection ('c()' = All): ")),BC_field,sticky="nw")
tkgrid(BC_entry,sticky="nw")
checkBoxes(plotOptions,frame="backgroundCheck",boxes=paste("background"),initialValues=0,labels=gettextRcmdr("Add data heatmap on background?"))
background_vars <- backgroundVariable
tkgrid(backgroundCheck,sticky="nw")
checkBoxes(plotOptions,frame="reorderCheck",boxes=paste("reorder"),initialValues=0,labels=gettextRcmdr("Reorder rows and columns for Bicluster Visualization?"))
reorder_vars <- reorderVariable
tkgrid(reorderCheck,sticky="nw")
checkBoxes(plotOptions,frame="zeroBCCheck",boxes=paste("zeroBC"),initialValues=1,labels=gettextRcmdr("Also color genes of Biclusters which have '0' as response?"))
zeroBC_vars <- zeroBCVariable
tkgrid(zeroBCCheck,sticky="nw")
BChighlight <- tkframe(plotOptions)
BChighlightSel_entry <- tkframe(BChighlight)
BChighlightSel_vars <- tclVar("")
BChighlightSel_field <- ttkentry(BChighlightSel_entry,width=4,textvariable=BChighlightSel_vars)
tkgrid(labelRcmdr(BChighlightSel_entry,text=gettextRcmdr("Bicluster Highlight: ")),BChighlightSel_field,sticky="nw")
BChighlightOpa_entry <- tkframe(BChighlight)
BChighlightOpa_vars <- tclVar("0.4")
BChighlightOpa_field <- ttkentry(BChighlightOpa_entry,width=4,textvariable=BChighlightOpa_vars)
tkgrid(labelRcmdr(BChighlightOpa_entry,text=gettextRcmdr("Opacity [0;1]: ")),BChighlightOpa_field,sticky="nw")
tkgrid(BChighlightSel_entry,BChighlightOpa_entry,sticky="nw")
tkgrid(BChighlight,sticky="nw")
tkgrid(plotOptions,sticky="nw",padx="6",pady="6")
fabiaoptionsFrame <- tkframe(tab2Frame)
tkgrid(labelRcmdr(fabiaoptionsFrame,fg=getRcmdr("title.color"),font="RcmdrTitleFont",text=gettextRcmdr("Fabia Result Options")),sticky="nw")
thresZ_entry <- tkframe(fabiaoptionsFrame)
thresZ_vars <- tclVar("0.5")
thresZ_field <- ttkentry(thresZ_entry,width=6,textvariable=thresZ_vars)
tkgrid(labelRcmdr(thresZ_entry,text=gettextRcmdr("Threshold Bicluster Sample: ")),thresZ_field,sticky="nw")
tkgrid(thresZ_entry,sticky="ne")
thresL_entry <- tkframe(fabiaoptionsFrame)
thresL_vars <- tclVar("NULL")
thresL_field <- ttkentry(thresL_entry,width=6,textvariable=thresL_vars)
tkgrid(labelRcmdr(thresL_entry,text=gettextRcmdr("Threshold Bicluster Loading: ")),thresL_field,sticky="nw")
tkgrid(thresL_entry,sticky="ne")
tkgrid(fabiaoptionsFrame,padx="6",pady="6",sticky="nw")
drawresultButton <- buttonRcmdr(tab2Frame,command=onResultImage,text=gettextRcmdr("Heatmap"),foreground="darkgreen",default="active",width="12",borderwidth=3)
tkgrid(drawresultButton,sticky="w",pady="15",padx="10")
buttonsFrame <- tkframe(top)
exitButton <- buttonRcmdr(buttonsFrame,command=onCancel,text=gettextRcmdr("Exit"),foreground="darkgreen",width="8",borderwidth=3)
tkgrid(exitButton,sticky="es")
tkgrid(tab1Frame)
tkgrid(tab2Frame)
dialogSuffix(use.tabs=TRUE, grid.buttons=TRUE,onOK=onOK,tabs=c("tab1","tab2"),tab.names=c("Data","Biclustering Results"),preventGrabFocus=TRUE)
} |
pymjsDependency <- function() {
list(
htmltools::htmlDependency(
name = 'pymjs', version = '1.3.2',
src = system.file('htmlwidgets/pymjs', package = 'widgetframe'),
script = c('pym.v1.min.js')
)
)
}
addPymjsDependency <- function(widget) {
widget$dependencies <- c(pymjsDependency(), widget$dependencies)
widget
}
blazyDependency <- function() {
list(
htmltools::htmlDependency(
name = 'blazy', version = '1.8.2',
src = system.file('htmlwidgets/blazy', package = 'widgetframe'),
script = c('blazy.min.js')
)
)
}
addBlazyDependency <- function(widget) {
widget$dependencies <- c(blazyDependency(), widget$dependencies)
widget
}
frameOptions <- function(xdomain = '*', title=NULL, name=NULL,
id = NULL, allowfullscreen=FALSE,
sandbox=NULL, lazyload = FALSE) {
purrr::keep(
list(
xdomain = xdomain,
title = title,
name = name,
id = id,
allowfullscreen = allowfullscreen,
sandbox = sandbox,
lazyload = lazyload
), ~!is.null(.))
}
frameableWidget <- function(widget, renderCallback = NULL) {
if (!("htmlwidget" %in% class(widget))) {
stop ("The input widget argument is not a htmldidget.")
}
if ("widgetframe" %in% class(widget)) {
stop ("Can't make an already framed widget frameable.")
}
if ('frameablewidget' %in% class(widget)) {
return(widget)
}
numClasses <- length(class(widget))
class(widget) <- c(class(widget)[1:(numClasses-1)],
'frameablewidget', class(widget)[[numClasses]])
widget$sizingPolicy$padding <- 0
widget$sizingPolicy$viewer$padding <- 0
widget$sizingPolicy$browser$padding <- 0
initChildJsCode <- NULL
if (is.null(renderCallback)) {
initChildJsCode <- "HTMLWidgets.pymChild = new pym.Child();"
} else {
initChildJsCode <- sprintf(
"HTMLWidgets.pymChild = new pym.Child({renderCallback : %s});", renderCallback)
}
initChildJsCode <- paste0(initChildJsCode,
"HTMLWidgets.addPostRenderHandler(function(){
setTimeout(function(){HTMLWidgets.pymChild.sendHeight();},100);
});")
widget %>%
addPymjsDependency() %>%
htmlwidgets::appendContent(htmltools::tags$script(initChildJsCode))
}
frameWidget <- function(targetWidget, width = '100%', height = NULL, elementId = NULL,
options = frameOptions()) {
if ('widgetframe' %in% class(targetWidget)) {
warning("Re-framing an already framed widget with new params")
targetWidget <- attr(targetWidget$x,'widget')
}
targetWidget <- frameableWidget(targetWidget)
if (!is.null(width)) {
targetWidget$width <- width
} else {
if (!is.null(targetWidget$width)) {
width <- targetWidget$width
}
}
if (!is.null(height)) {
targetWidget$height <- height
} else {
if (!is.null(targetWidget$height)) {
height <- targetWidget$height
}
}
widgetData = structure(
list(
url = 'about:blank',
options = options
), widget = targetWidget )
widget <- htmlwidgets::createWidget(
name = 'widgetframe',
x = widgetData,
width = width,
height = height,
package = 'widgetframe',
elementId = elementId
)
if(!is.null(options) && options$lazyload) {
widget <- widget %>%
addBlazyDependency() %>%
htmlwidgets::appendContent(htmltools::tags$script("if(!window.bLazy){window.bLazy = new Blazy();}"))
}
widget
}
print.widgetframe <- function(x, ..., view = interactive()) {
viewer <- getOption("viewer", utils::browseURL)
parentDir <- tempfile('widgetframe')
dir.create(parentDir)
childWidget <- attr(x$x,'widget')
if (!is.null(childWidget)) {
childDir <- file.path(parentDir,'widget')
dir.create(childDir)
childHTML <- file.path(childDir, "index.html")
htmltools::save_html(
htmltools::as.tags(childWidget, standalone = TRUE), file = childHTML)
x$x$url <- './widget/index.html'
}
parentHTML <- file.path(parentDir,'index.html')
htmltools::save_html(
htmltools::as.tags(x, standalone = TRUE), file = parentHTML)
if (view) {
viewer(parentHTML)
}
invisible(x)
}
saveWidgetframe <- function(widget, file, selfcontained = FALSE,
libdir = NULL,
background = "white", knitrOptions = list()) {
parentWidget <- NULL
if ('widgetframe' %in% class(widget)) {
parentWidget <- widget
} else {
parentWidget <- frameWidget(widget)
}
childDir <- file.path(
dirname(file),
paste0(tools::file_path_sans_ext(basename(file)),'_widget'))
dir.create(childDir)
parentWidget$x$url <- paste0(
tools::file_path_sans_ext(basename(file)),'_widget/index.html')
childWidget <- attr(parentWidget$x,'widget')
oldwd <- setwd(childDir)
htmlwidgets::saveWidget(childWidget, 'index.html', selfcontained = selfcontained,
libdir = libdir, background = background,
knitrOptions = knitrOptions)
setwd(oldwd)
htmlwidgets::saveWidget(parentWidget, file, selfcontained = selfcontained,
libdir = libdir, background = background,
knitrOptions = knitrOptions)
}
widgetframeOutput <- function(outputId, width = '100%', height = '400px'){
htmlwidgets::shinyWidgetOutput(outputId, 'widgetframe', width, height, package = 'widgetframe')
}
renderWidgetframe <- function(expr, env = parent.frame(), quoted = FALSE) {
if (!quoted) { expr <- substitute(expr) }
htmlwidgets::shinyRenderWidget(expr, widgetframeOutput, env, quoted = TRUE)
} |
icrsf <- function(data, subject, testtimes, result, sensitivity, specificity, Xmat,
root.size, ntree, ns, node, pval=1){
getparm <- function(id, Xmat, treemat, hdidx = 1) {
stopifnot(is.numeric(id), length(id) == 1)
vec <- treemat[hdidx, ]
obs <- Xmat[id, ]
dir <- (obs[vec[3]] >= vec[4]) + 1
if (is.na(vec[dir])) {
fparm <- vec[-(1:5)]
fparm[1] <- fparm[1] + (dir-1)*vec[5]*obs[vec[3]]
return(list(fparm=fparm, id=hdidx))
} else {
getparm(id, Xmat, treemat, vec[dir])
}
}
varimp1 <- function(Dmat, Xmat, treemat, OOBid){
J <- ncol(Dmat) - 1
nOOB <- length(OOBid)
ncov <- ncol(Xmat)
newpred <- function(inc){
m <- rep(NA, inc)
m[1] <- 1
return(list(mat=m, nxt=2, inc=inc))
}
insertpred <- function(pred, newval){
newidx <- pred$nxt
if (pred$nxt == length(pred) + 1) {
pred$mat <- c(pred$mat, rep(NA, pred$inc))
}
pred$mat[newidx] <- newval
pred$nxt <- pred$nxt + 1
return(pred)
}
getparm <- function(x, treemat, hdidx = 1) {
vec <- treemat[hdidx, ]
dir <- (x[vec[3]] >= vec[4]) + 1
if (is.na(vec[dir])) {
fparm <- vec[6:(J+5)]
fparm[1] <- fparm[1] + (dir-1)*vec[5]*x[vec[3]]
return(list(fparm=fparm, id=hdidx))
} else {
getparm(x, treemat, vec[dir])
}
}
getpred <- function(x, treemat, hdidx = 1, pmat) {
vec <- treemat[hdidx, ]
dir <- (x[vec[3]] >= vec[4]) + 1
if(is.na(hdidx) == FALSE){
if(hdidx == 1){
pmat <- newpred(3)
} else
{
pmat <- insertpred(pmat, hdidx)
}
hdidx <- vec[dir]
pmat <- getpred(x, treemat, hdidx, pmat)
}
return(pmat)
}
OOBloglik <- function(Dmat, Xmat, OOBid, varid, treemat){
simdata <- cbind(Dmat, Xmat)
OOB <- simdata[OOBid, ]
OOBDmat <- OOB[, 1:(J+1)]
OOBDes <- OOB[, -(1:(J+1))]
nOOB <- nrow(OOB)
if (varid > 0) OOBDes[, varid] <- sample(OOBDes[, varid], nOOB, replace=FALSE)
p <- apply(OOBDes, 1, function(x) getparm(x, treemat))
parms <- t(sapply(p, function(x) cumsum(x$fparm)))
l <- rowSums(OOBDmat*cbind(1, exp(-exp(parms))))
freq <- unlist(sapply(1:nOOB, function(x) getpred(OOBDes[x, ], treemat, 1, 1)[[1]]))
freq <- freq[!is.na(freq)]
l1 <- ifelse(l>0, log(l), NA)
return(l1)
}
cov <- unique(treemat[, 3])
cov <- cov[!is.na(cov)]
varimp <- rep(0, ncov)
lik.org <- OOBloglik(Dmat, Xmat, OOBid, 0, treemat)
permutelik <- lapply(cov, function(x) OOBloglik(Dmat, Xmat, OOBid, x, treemat))
varimp[cov] <- sapply(permutelik, function(x) sum(lik.org - x, na.rm=T))
return(varimp)
}
treebuilder <- function(Dmat, Xmat, root.size, ns, pval=1){
hdidx <- 1
tree <- 1
thres <- stats::qchisq(1-pval, df=1)
getchisq <- function(Dmat, x) {
if(length(unique(x))==1){
chisq <- 0
parm <- rep(0, J+1)
}else{
q <- try(optim(parmD, loglikCD, gradlikCD, lower = c(rep(-Inf, 2), rep(1e-8, J-1)), Dmat = Dmat, x = x, method="L-BFGS-B"))
q0 <- try(optim(parmD0, loglikCD0, gradlikCD0, lower = c(-Inf, rep(1e-8, J-1)), Dmat = Dmat, method="L-BFGS-B"))
if (class(q)=="try-error" | class(q0)=="try-error") return(rep(0, J+2))
chisq <- 2*(q0$value - q$value)
parm <- q$par
}
return(c(chisq, parm))
}
simdata <- cbind(Dmat, Xmat)
J <- ncol(Dmat) - 1
nsub <- nrow(Dmat)
ncov <- ncol(Xmat)
parmi <- c(0, log(-log((J:1)/(J+1))))
parmD <- c(parmi[1], diff(c(0, parmi[-1])))
parmD0 <- parmD[-1]
bootid <- sample(1:nrow(simdata),nrow(simdata), replace = T)
bootdata <- simdata[bootid, ]
OOBid <- setdiff(1:nsub, unique(bootid))
OOB <- simdata[setdiff(1:nsub, unique(bootid)), ]
nOOB <- nrow(OOB)
newtree <- function(firstval, firstc, inc, parm, firstnobs) {
m <- matrix(rep(NA, inc*(J+6)), nrow = inc, ncol = J + 6)
m[1, 3] <- firstval
m[1, 4] <- firstc
m[1, 5:(J+5)] <- parm
m[1, J+6] <- firstnobs
return(list(mat=m, nxt=2, inc=inc))
}
insert <- function(hdidx, dir, tr, newval, newc, parm, nobs) {
newidx <- tr$nxt
if (tr$nxt == nrow(tr$mat) + 1) {
tr$mat <- rbind(tr$mat, matrix(rep(NA, tr$inc*(J+6)), nrow=tr$inc, ncol=J+6))
}
tr$mat[newidx, 3] <- newval
tr$mat[newidx, 4] <- newc
tr$mat[newidx, 5:(J+5)] <- parm
tr$mat[newidx, (J+6)] <- nobs
tr$mat[hdidx, dir] <- newidx
tr$nxt <- tr$nxt + 1
return(tr)
}
training <- function(bootdata, hdidx, dir, tree, root.size, ns, pval) {
if (length(unique(row.names(bootdata))) > root.size) {
Dmat <- bootdata[, 1:(J+1)]
Xmat <- bootdata[, -(1:(J+1))]
selid <- sample(1:ncov, ns, replace=FALSE)
X <- Xmat[, selid]
bsplit <- apply(X, 2, function(t) splitpointC(Dmat, t, getchisq))
if(length(selid) > 0){
id <- which.max(bsplit[2, ])
if(max(bsplit[2, ])>= thres){
bvar <- selid[id]
bcp <- bsplit[1, id]
bootdata.L <- bootdata[X[,id] <= bcp, ]
bootdata.R <- bootdata[X[, id] > bcp, ]
parm <- bsplit[-(1:2), id]
nobs <- nrow(bootdata)
if (nrow(bootdata) == nsub) {
tree <- newtree(bvar, bcp, 3, parm, nobs)
} else {
tree <- insert(hdidx, dir, tree, bvar, bcp, parm, nobs)
}
a <- tree$nxt - 1
tree <- training(bootdata.L, a, 1, tree, root.size, ns, pval)
tree <- training(bootdata.R, a, 2, tree, root.size, ns, pval)
}
}
}
return(tree)
}
tr <- training(bootdata, hdidx, dir, tree, root.size, ns, pval)
tr<- tr$mat
tr <- tr[!is.na(tr[, 3]), ]
return(list(tree=tr, OOBid=OOBid))
}
id <- eval(substitute(subject), data, parent.frame())
time <- eval(substitute(testtimes), data, parent.frame())
result <- eval(substitute(result), data, parent.frame())
ord <- order(id, time)
if (is.unsorted(ord)) {
id <- id[ord]
time <- time[ord]
result <- result[ord]
data <- data[ord, ]
}
utime <- sort(unique(time))
stopifnot(is.numeric(sensitivity), is.numeric(specificity),
is.numeric(root.size), is.numeric(node),
is.numeric(pval), is.numeric(ns))
stopifnot(length(sensitivity) == 1, sensitivity >= 0, sensitivity <= 1,
length(specificity) == 1, specificity >= 0, specificity <= 1,
length(root.size) == 1, root.size >= 1, root.size <= nrow(Xmat),
length(node) ==1, node >=1,
length(ns) ==1, ns >=1, ns<=ncol(Xmat),
all(time > 0), all(is.finite(time)))
if (!all(result %in% c(0, 1))) stop("result must be 0 or 1")
if (any(tapply(time, id, anyDuplicated)))
stop("existing duplicated visit times for some subjects")
timen0 <- (time != 0)
Dmat <- dmat(id[timen0], time[timen0], result[timen0], sensitivity,
specificity, 1)
row.names(Dmat) <- unique(id)
trees <- mclapply(1:ntree, function(x) treebuilder(Dmat, Xmat, root.size, ns, pval),
mc.cores=node)
treemats <- mclapply(trees, function(x) x[[1]], mc.cores=node)
OOBids <- mclapply(trees, function(x) x[[2]], mc.cores=node)
vimp <- mclapply(1:ntree, function(x) varimp1(Dmat, Xmat, treemats[[x]], OOBid=OOBids[[x]]))
vimp.adj <- mclapply(vimp, function(x) ifelse(x>0, x, 0))
vimp1 <- do.call("rbind", vimp.adj)
vimp2 <- colSums(vimp1, na.rm=T)
return(ensemble.vimp=vimp2)
} |
get_table_metadata <- function(table_id, variables_only = FALSE, language = c("en", "da")){
language <- match.arg(language)
call_body <- list(lang = language,
table = table_id)
result <- httr::POST(METADATA_ENDPOINT, body = call_body, encode = "json")
check_http_type(result)
full_result <- jsonlite::fromJSON(httr::content(result))
if (variables_only) return(full_result$variables)
return(full_result)
}
get_valid_variable_values <- function(table_id, variable_id){
vars <- get_table_metadata(table_id = table_id, variables_only = TRUE)
return(vars[["values"]][[which(tolower(vars$id) == tolower(variable_id))]]$id)
} |
get_ylu.default <- function(y, t) {
ylu_min <- aggregate(y, list(year = year(t)), min)$x %>% median()
ylu_max <- aggregate(y, list(year = year(t)), max)$x %>% median()
A <- ylu_max - ylu_min
listk(ylu_min, ylu_max, A)
}
get_A <- function(x, na.rm = FALSE) {
range(x, na.rm = na.rm) %>% diff()
}
default_nups <- function(nptperyear) {
ifelse(nptperyear >= 100, 2, 1)
}
default_minpeakdistance <- function(nptperyear) {
floor(nptperyear / 6)
}
guess_nyear <- function(INPUT) {
nlen = length(INPUT$y)
nptperyear = INPUT$nptperyear
nyear = nlen / nptperyear
date_year <- year(INPUT$t) + ((month(INPUT$t) >= 7) - 1) * INPUT$south
info <- table(date_year)
years <- info[info > nptperyear*0.2] %>% {as.numeric(names(.))}
listk(nyear, year = years)
}
di2dt <- function(di, t, ypred){
dt = di %>% mutate(across(.fns = ~ ypred[.x], .names = "y_{.col}")) %>%
mutate(across(beg:end, .fns = ~ t[.x]))
if (is.Date(t)) {
dt %>% mutate(len = as.integer(difftime(end, beg, units = "days") + 1), year = year(peak))
} else {
dt %>% mutate(len = end - beg + 1, year = NA_integer_)
}
}
rename_season <- function(d) {
names(d)[1:6] <- c("time_start", "time_peak", "time_end", "val_start", "val_peak", "val_end")
d
}
removeClosedExtreme <- function(pos, ypred, A = NULL, y_min, minpeakdistance)
{
if (is.null(A)) A = max(ypred) - min(ypred)
for (i in 1:2) {
if (i == 1) {
I_del <- which(diff(pos$pos) < minpeakdistance/3) + 1
} else if(i == 2) {
I_del <- which(abs(diff(pos$val)) < 0.05 * A) + 1
}
if (length(I_del) > 0) pos <- pos[-I_del, ]
pos$flag <- cumsum(c(1, diff(pos$type) != 0))
has_duplicated <- duplicated(pos$flag) %>% any()
if (has_duplicated) {
pos %<>% group_by(flag) %>%
group_modify(~merge_duplicate(.x, y = ypred, threshold = y_min)) %>%
ungroup() %>%
select(-flag)
}
pos
}
pos
}
merge_duplicate <- function(d, y, threshold, max_gap = 180){
if (nrow(d) > 1) {
type <- d$type[1]
diff_val = diff(range(d$val))
diff_gap = diff(range(d$pos))
if ( diff_gap < max_gap) {
if (diff_val < threshold) {
I <- floor(median(d$pos))
data.table(
val = y[I], pos = I,
left = min(d$left),
right = max(d$right), type = type
)
} else {
fun <- ifelse(type == 1, which.max, which.min)
d[fun(d$val), ]
}
} else {
d[1, ]
}
} else {
d
}
}
fixYearBroken <- function(di, t, ypred) {
is_date <- is(di$beg[1], "Date")
origin <- t[1]
if (is_date) {
I_beg <- match(di$beg, t)
I_end <- match(di$end, t)
I_peak <- match(di$peak, t)
} else {
I_beg <- di$beg
I_end <- di$end
I_peak <- di$peak
}
for (i in 1:nrow(di)) {
I <- I_beg[i]:I_end[i]
I_nona <- I
ti <- t[I_nona]
I_brkyear <- which(diff(ti) >= 365)
nbrk <- length(I_brkyear)
if (nbrk > 0 & nbrk <= 2) {
if (nbrk == 1) {
I_1 <- I_nona[1:I_brkyear]
I_2 <- I_nona[(I_brkyear + 1):length(I_nona)]
lst <- list(I_1, I_2)
} else if (nbrk == 2) {
I_1 <- I_nona[1:I_brkyear[1]]
I_2 <- I_nona[(I_brkyear[1] + 1):I_brkyear[2]]
I_3 <- I_nona[(I_brkyear[2] + 1):length(I_nona)]
lst <- list(I_1, I_2, I_3)
}
I_nona <- lst[[which.max(sapply(lst, length))]]
I_beg[i] <- first(I_nona)
I_end[i] <- last(I_nona)
I_peak[i] <- I_nona[which.max(ypred[I_nona])]
}
}
di <- data.table(beg = I_beg, peak = I_peak, end = I_end)
di2dt(di, t, ypred)
}
check_GS_HeadTail <- function(pos, ypred, minlen, A = NULL, ...) {
if (is.null(A)) A <- diff(range(ypred))
nlen <- length(ypred)
locals <- pos[, c("pos", "type")]
ns <- nrow(locals)
if (last(pos$type) == 1 && (nlen - nth(pos$pos, -2)) > minlen &&
abs(last(ypred) - nth(pos$val, -2)) < 0.15 * A) {
locals %<>% rbind.data.frame(., data.frame(pos = nlen, type = -1))
}
if (pos$type[1] == 1 && pos$pos[2] > minlen && abs(ypred[1] - pos$val[2]) < 0.15 * A) {
locals %<>% rbind.data.frame(data.frame(pos = 1, type = -1), .)
}
I <- which(locals$type == -1)
locals <- locals[I[1]:I[length(I)], ]
s <- locals$pos
ns <- length(s)
if (ns < 3) {
warning("Can't find a complete growing season!")
return(NULL)
}
data.table(
beg = s[seq(1, ns - 1, 2)], peak = s[seq(2, ns, 2)],
end = s[seq(3, ns, 2)]
)
} |
qm_is_cluster <- function(obj, verbose = FALSE){
if (verbose != TRUE & verbose != FALSE){
stop("The 'verbose' argument must be either 'TRUE' or 'FALSE'.")
}
if (ncol(obj) < 4){
count <- FALSE
} else {
count <- TRUE
}
if ("RID" %in% names(obj) == FALSE){
rid <- FALSE
} else {
rid <- TRUE
}
if ("CID" %in% names(obj) == FALSE){
cid <- FALSE
} else {
cid <- TRUE
}
if ("CAT" %in% names(obj) == FALSE){
cat <- FALSE
} else {
cat <- TRUE
}
output <- dplyr::tibble(
test = c("Contains at least 4 columns", "Contains RID variable", "Contains CID variable", "Contains CAT variable"),
result = c(count, rid, cid, cat)
)
if (verbose == FALSE){
output <- all(output$result)
}
return(output)
} |
ans1 <- expand_array_indexes(c("123_1", "55_[1-5]", "122_[1, 5-6]", "44_[1-3:2]"))
ans0 <- c("123_1", "55_1", "55_2", "55_3", "55_4", "55_5", "122_1", "122_5", "122_6", "44_1", "44_3")
expect_equal(ans1, ans0) |
NULL
vegtable2kml <- function(obj, ...) {
.Deprecated(msg = paste("This function is deprecated.",
"Visit the package's site for alternative mapping methods."))
} |
"locfit"<-
function(formula, data = sys.frame(sys.parent()), weights = 1, cens = 0, base = 0, subset,
geth = FALSE, ..., lfproc = locfit.raw)
{
Terms <- terms(formula, data = data)
attr(Terms, "intercept") <- 0
m <- match.call()
m[[1]] <- as.name("model.frame")
z <- pmatch(names(m), c("formula", "data", "weights", "cens", "base",
"subset"))
for(i in length(z):2)
if(is.na(z[i])) m[[i]] <- NULL
frm <- eval(m, sys.frame(sys.parent()))
if (nrow(frm) < 1) stop("fewer than one row in the data")
vnames <- as.character(attributes(Terms)$variables)[-1]
if(attr(Terms, "response")) {
y <- model.extract(frm, "response")
yname <- deparse(formula[[2]])
vnames <- vnames[-1]
}
else {
y <- yname <- NULL
}
x <- as.matrix(frm[, vnames])
if(!inherits(x, "lp")) {
if(length(vnames) == dim(x)[2]) {
dimnames(x) <- list(NULL, vnames)
}
}
if(!missing(weights))
weights <- model.extract(frm, weights)
if(!missing(cens))
cens <- model.extract(frm, cens)
if(!missing(base))
base <- model.extract(frm, base)
ret <- lfproc(x, y, weights = weights, cens = cens, base = base, geth = geth,
...)
if(geth == 0) {
ret$terms <- Terms
ret$call <- match.call()
if(!is.null(yname))
ret$yname <- yname
ret$frame <- sys.frame(sys.parent())
}
ret
}
"locfit.raw"<-
function(x, y, weights = 1, cens = 0, base = 0, scale = FALSE, alpha = 0.7,
deg = 2, kern = "tricube", kt = "sph", acri = "none",
basis = list(NULL), deriv = numeric(0), dc = FALSE, family,
link = "default", xlim, renorm = FALSE, ev = rbox(),
maxk = 100, itype = "default", mint = 20, maxit = 20, debug = 0,
geth = FALSE, sty = "none")
{
if(inherits(x, "lp")) {
alpha <- attr(x, "alpha")
deg <- attr(x, "deg")
sty <- attr(x, "style")
acri <- attr(x, "acri")
scale <- attr(x, "scale")
}
if(!is.matrix(x)) {
vnames <- deparse(substitute(x))
x <- matrix(x, ncol = 1)
d <- 1
}
else {
d <- ncol(x)
if(is.null(dimnames(x)))
vnames <- paste("x", 1:d, sep = "")
else vnames <- dimnames(x)[[2]]
}
n <- nrow(x)
if((!missing(y)) && (!is.null(y))) {
yname <- deparse(substitute(y))
if(missing(family))
family <- if(is.logical(y)) "binomial" else "qgaussian"
}
else {
if(missing(family))
family <- "density"
y <- 0
yname <- family
}
if(!missing(basis)) {
deg0 <- deg <- length(basis(matrix(0, nrow = 1, ncol = d), rep(0, d)))
}
if(length(deg) == 1)
deg = c(deg, deg)
xl <- rep(0, 2 * d)
lset <- 0
if(!missing(xlim)) {
xl <- lflim(xlim, vnames, xl)
lset <- 1
}
if(is.character(ev)) {
stop("Character ev argument no longer used.")
}
if(is.numeric(ev)) {
xev <- ev
mg <- length(xev)/d
ev <- list(type = "pres", xev = xev, mg = mg, cut = 0, ll = 0, ur = 0)
if(mg == 0)
stop("Invalid ev argument")
}
fl <- c(rep(ev$ll,length.out=d), rep(ev$ur,length.out=d))
mi <- c(n, 0, deg, d, 0, 0, 0, 0, mint, maxit, renorm, 0, 0, 0, dc, maxk,
debug, geth, 0, !missing(basis))
if(any(is.na(mi)))
print(mi)
if(is.logical(scale))
scale <- 1 - as.numeric(scale)
if(length(scale) == 1)
scale <- rep(scale, d)
if(is.character(deriv))
deriv <- match(deriv, vnames)
alpha <- c(alpha, 0, 0, 0)[1:3]
style <- pmatch(sty, c("none", "z1", "z2", "angle", "left", "right", "cpar"))
if(length(style) == 1)
style <- rep(style, d)
dp <- c(alpha, ev$cut, 0, 0, 0, 0, 0, 0)
size <- .C("guessnv",
lw = integer(7),
evt = as.character(c(ev$type, kt)),
dp = as.numeric(dp),
mi = as.integer(mi),
nvc = integer(5),
mg = as.integer(ev$mg), PACKAGE="locfit")
nvc <- size$nvc
lw <- size$lw
z <- .C("slocfit",
x = as.numeric(x),
y = as.numeric(rep(y, length.out = n)),
cens = as.numeric(rep(cens, length.out = n)),
w = as.numeric(rep(weights, length.out = n)),
base = as.numeric(rep(base, length.out = n)),
lim = as.numeric(c(xl, fl)),
mi = as.integer(size$mi),
dp = as.numeric(size$dp),
strings = c(kern, family, link, itype, acri, kt),
scale = as.numeric(scale),
xev = if(ev$type == "pres") as.numeric(xev) else numeric(d * nvc[1]),
wdes = numeric(lw[1]),
wtre = numeric(lw[2]),
wpc = numeric(lw[4]),
nvc = as.integer(size$nvc),
iwk1 = integer(lw[3]),
iwk2 = integer(lw[7]),
lw = as.integer(lw),
mg = as.integer(ev$mg),
L = numeric(lw[5]),
kap = numeric(lw[6]),
deriv = as.integer(deriv),
nd = as.integer(length(deriv)),
sty = as.integer(style),
PACKAGE="locfit")
nvc <- z$nvc
names(nvc) <- c("nvm", "ncm", "vc", "nv", "nc")
nvm <- nvc["nvm"]
ncm <- nvc["ncm"]
nv <- max(nvc["nv"], 1)
nc <- nvc["nc"]
if(geth == 1)
return(matrix(z$L[1:(nv * n)], ncol = nv))
if(geth == 2)
return(list(const = z$kap, d = d))
if(geth == 3)
return(z$kap)
dp <- z$dp
mi <- z$mi
names(mi) <- c("n", "p", "deg0", "deg", "d", "acri", "ker", "kt", "it",
"mint", "mxit", "renorm", "ev", "tg", "link", "dc", "mk", "debug", "geth",
"pc", "ubas")
names(dp) <- c("nnalph", "fixh", "adpen", "cut", "lk", "df1", "df2", "rv",
"swt", "rsc")
if(geth == 4) {
p <- mi["p"]
return(list(residuals = z$y, var = z$wdes[n * (p + 2) + p * p + (1:n)],
nl.df = dp["df1"] - 2))
}
if(geth == 6)
return(z$L)
if(length(deriv) > 0)
trans <- function(x)
x
else trans <- switch(mi["link"] - 2,
function(x)
x,
exp,
expit,
function(x)
1/x,
function(x)
pmax(x, 0)^2,
function(x)
pmax(sin(x), 0)^2)
t1 <- z$wtre
t2 <- z$iwk1
xev <- z$xev[1:(d * nv)]
if(geth == 7)
return(list(x = xev, y = trans(t1[1:nv])))
coef <- matrix(t1[1:((3 * d + 8) * nvm)], nrow = nvm)[1:nv, ]
if(nv == 1)
coef <- matrix(coef, nrow = 1)
if(geth >= 70) {
data <- list(x = x, y = y, cens = cens, base = base, w = weights)
return(list(xev = matrix(xev, ncol = d, byrow = TRUE), coef = coef[, 1], sd =
coef[, d + 2], lower = z$L[1:nv], upper = z$L[nvm + (1:nv)], trans =
trans, d = d, vnames = vnames, kap = z$kap, data = data, mi = mi))
}
eva <- list(ev = ev, xev = xev, coef = coef, scale = z$scale, pc = z$wpc)
class(eva) <- "lfeval"
if(nc == 0) {
cell <- list(sv = integer(0), ce = integer(0), s = integer(0), lo =
as.integer(rep(0, nv)), hi = as.integer(rep(0, nv)))
}
else {
mvc <- max(nv, nc)
mvcm <- max(nvm, ncm)
vc <- nvc["vc"]
cell <- list(sv = t1[nvm * (3 * d + 8) + 1:nc], ce = t2[1:(vc * nc)], s =
t2[vc * ncm + 1:mvc], lo = t2[vc * ncm + mvcm + 1:mvc], hi = t2[vc * ncm +
2 * mvcm + 1:mvc])
}
ret <- list(eva = eva, cell = cell, terms = NULL, nvc = nvc, box = z$lim[2 *
d + 1:(2 * d)], sty = style, deriv = deriv, mi = mi, dp = dp, trans = trans,
critval = crit(const = c(rep(0, d), 1), d = d), vnames = vnames, yname =
yname, call = match.call(), frame = sys.frame(sys.parent()))
class(ret) <- "locfit"
ret
}
"ang" <-
function(x, ...)
{
ret <- lp(x, ..., style = "angle")
dimnames(ret) <- list(NULL, deparse(substitute(x)))
ret
}
"gam.lf"<-
function(x, y, w, xeval, ...)
{
if(!missing(xeval)) {
fit <- locfit.raw(x, y, weights = w, geth = 5, ...)
return(predict(fit, xeval))
}
ret <- locfit.raw(x, y, weights = w, geth = 4, ...)
names(ret) <- c("residuals", "var", "nl.df")
ret
}
"gam.slist"<-
c("s", "lo", "random", "lf")
"lf"<-
function(..., alpha = 0.7, deg = 2, scale = 1, kern = "tcub", ev = rbox(), maxk
= 100)
{
if(!any(gam.slist == "lf"))
warning("gam.slist does not include \"lf\" -- fit will be incorrect")
x <- cbind(...)
scall <- deparse(sys.call())
attr(x, "alpha") <- alpha
attr(x, "deg") <- deg
attr(x, "scale") <- scale
attr(x, "kern") <- kern
attr(x, "ev") <- ev
attr(x, "maxk") <- maxk
attr(x, "call") <- substitute(gam.lf(data[[scall]], z, w, alpha = alpha, deg
= deg, scale = scale, kern = kern, ev = ev, maxk = maxk))
attr(x, "class") <- "smooth"
x
}
"left"<-
function(x, ...)
{
ret <- lp(x, ..., style = "left")
dimnames(ret) <- list(NULL, deparse(substitute(x)))
ret
}
"right"<-
function(x, ...)
{
ret <- lp(x, ..., style = "right")
dimnames(ret) <- list(NULL, deparse(substitute(x)))
ret
}
"cpar"<-
function(x, ...)
{
ret <- lp(x, ..., style = "cpar")
dimnames(ret) <- list(NULL, deparse(substitute(x)))
ret
}
"lp"<-
function(..., nn = 0, h = 0, adpen = 0, deg = 2, acri = "none", scale = FALSE,
style = "none")
{
x <- cbind(...)
z <- as.list(match.call())
z[[1]] <- z$nn <- z$h <- z$adpen <- z$deg <- z$acri <- z$scale <- z$style <-
NULL
dimnames(x) <- list(NULL, z)
if(missing(nn) & missing(h) & missing(adpen))
nn <- 0.7
attr(x, "alpha") <- c(nn, h, adpen)
attr(x, "deg") <- deg
attr(x, "acri") <- acri
attr(x, "style") <- style
attr(x, "scale") <- scale
class(x) <- c("lp", class(x))
x
}
"[.lp" <- function (x, ..., drop = FALSE) {
cl <- oldClass(x)
oldClass(x) <- NULL
ats <- attributes(x)
ats$dimnames <- NULL
ats$dim <- NULL
ats$names <- NULL
y <- x[..., drop = drop]
attributes(y) <- c(attributes(y), ats)
oldClass(y) <- cl
y
}
"fitted.locfit"<-
function(object, data = NULL, what = "coef", cv = FALSE, studentize = FALSE,
type = "fit", tr, ...)
{
if(missing(data)) {
data <- if(is.null(object$call$data)) sys.frame(sys.parent()) else eval(object$call$
data)
}
if(missing(tr))
tr <- if((what == "coef") & (type == "fit")) object$trans else function(x)
x
mm <- locfit.matrix(object, data = data)
n <- object$mi["n"]
pred <- .C("sfitted",
x = as.numeric(mm$x),
y = as.numeric(rep(mm$y, length.out = n)),
w = as.numeric(rep(mm$w, length.out = n)),
ce = as.numeric(rep(mm$ce, length.out = n)),
ba = as.numeric(rep(mm$base, length.out = n)),
fit = numeric(n),
cv = as.integer(cv),
st = as.integer(studentize),
xev = as.numeric(object$eva$xev),
coef = as.numeric(object$eva$coef),
sv = as.numeric(object$cell$sv),
ce = as.integer(c(object$cell$ce, object$cell$s, object$cell$lo, object$
cell$hi)),
wpc = as.numeric(object$eva$pc),
scale = as.numeric(object$eva$scale),
nvc = as.integer(object$nvc),
mi = as.integer(object$mi),
dp = as.numeric(object$dp),
mg = as.integer(object$eva$ev$mg),
deriv = as.integer(object$deriv),
nd = as.integer(length(object$deriv)),
sty = as.integer(object$sty),
what = as.character(c(what, type)),
basis = list(eval(object$call$basis)), PACKAGE="locfit")
tr(pred$fit)
}
"formula.locfit"<-
function(x, ...)
x$call$formula
"predict.locfit"<-
function(object, newdata = NULL, where = "fitp", se.fit = FALSE, band = "none",
what = "coef", ...)
{
if((se.fit) && (band == "none"))
band <- "global"
for(i in 1:length(what)) {
pred <- preplot.locfit(object, newdata, where = where, band = band, what =
what[i], ...)
fit <- pred$trans(pred$fit)
if(i == 1)
res <- fit
else res <- cbind(res, fit)
}
if(band == "none")
return(res)
return(list(fit = res, se.fit = pred$se.fit, residual.scale = pred$
residual.scale))
}
"lines.locfit"<-
function(x, m = 100, tr = x$trans, ...)
{
newx <- lfmarg(x, m = m)[[1]]
y <- predict(x, newx, tr = tr)
lines(newx, y, ...)
}
"points.locfit"<-
function(x, tr, ...)
{
d <- x$mi["d"]
p <- x$mi["p"]
nv <- x$nvc["nv"]
if(d == 1) {
if(missing(tr))
tr <- x$trans
x1 <- x$eva$xev
x2 <- x$eva$coef[, 1]
points(x1, tr(x2), ...)
}
if(d == 2) {
xx <- lfknots(x, what = "x")
points(xx[, 1], xx[, 2], ...)
}
}
"print.locfit"<-
function(x, ...)
{
if(!is.null(cl <- x$call)) {
cat("Call:\n")
dput(cl)
}
cat("\n")
cat("Number of observations: ", x$mi["n"], "\n")
cat("Family: ", c("Density", "PP Rate", "Hazard", "Gaussian", "Logistic",
"Poisson", "Gamma", "Geometric", "Circular", "Huber", "Robust Binomial",
"Weibull", "Cauchy")[x$mi["tg"] %% 64], "\n")
cat("Fitted Degrees of freedom: ", round(x$dp["df2"], 3), "\n")
cat("Residual scale: ", signif(sqrt(x$dp["rv"]), 3), "\n")
invisible(x)
}
"residuals.locfit"<-
function(object, data = NULL, type = "deviance", ...)
{
if(missing(data)) {
data <- if(is.null(object$call$data)) sys.frame(sys.parent()) else eval(object$call$
data)
}
fitted.locfit(object, data, ..., type = type)
}
"summary.locfit"<-
function(object, ...)
{
mi <- object$mi
fam <- c("Density Estimation", "Poisson process rate estimation",
"Hazard Rate Estimation", "Local Regression", "Local Likelihood - Binomial",
"Local Likelihood - Poisson", "Local Likelihood - Gamma",
"Local Likelihood - Geometric", "Local Robust Regression")[mi["tg"] %% 64]
estr <- c("Rectangular Tree", "Triangulation", "Data", "Rectangular Grid",
"k-d tree", "k-d centres", "Cross Validation", "User-provided")[mi["ev"]]
ret <- list(call = object$call, fam = fam, n = mi["n"], d = mi["d"], estr =
estr, nv = object$nvc["nv"], deg = mi["deg"], dp = object$dp, vnames =
object$vnames)
class(ret) <- "summary.locfit"
ret
}
"print.summary.locfit"<-
function(x, ...)
{
cat("Estimation type:", x$fam, "\n")
cat("\nCall:\n")
print(x$call)
cat("\nNumber of data points: ", x$n, "\n")
cat("Independent variables: ", x$vnames, "\n")
cat("Evaluation structure:", x$estr, "\n")
cat("Number of evaluation points: ", x$nv, "\n")
cat("Degree of fit: ", x$deg, "\n")
cat("Fitted Degrees of Freedom: ", round(x$dp["df2"], 3), "\n")
invisible(x)
}
"rbox"<-
function(cut = 0.8, type = "tree", ll = rep(0, 10), ur = rep(0, 10))
{
if(!any(type == c("tree", "kdtree", "kdcenter", "phull")))
stop("Invalid type argument")
ret <- list(type = type, xev = 0, mg = 0, cut = as.numeric(cut), ll =
as.numeric(ll), ur = as.numeric(ur))
class(ret) <- "lf_evs"
ret
}
"lfgrid"<-
function(mg = 10, ll = rep(0, 10), ur = rep(0, 10))
{
if(length(mg) == 1)
mg <- rep(mg, 10)
ret <- list(type = "grid", xev = 0, mg = as.integer(mg), cut = 0, ll =
as.numeric(ll), ur = as.numeric(ur))
class(ret) <- "lf_evs"
ret
}
"dat"<-
function(cv = FALSE)
{
type <- if(cv) "crossval" else "data"
ret <- list(type = type, xev = 0, mg = 0, cut = 0, ll = 0, ur = 0)
class(ret) <- "lf_evs"
ret
}
"xbar"<-
function()
{
ret <- list(type = "xbar", xev = 0, mg = 0, cut = 0, ll = 0, ur = 0)
class(ret) <- "lf_evs"
ret
}
"none"<-
function()
{
ret <- list(type = "none", xev = 0, mg = 0, cut = 0, ll = 0, ur = 0)
class(ret) <- "lf_evs"
ret
}
"plot.locfit"<-
function(x, xlim, pv, tv, m, mtv = 6, band = "none", tr = NULL, what = "coef",
get.data = FALSE, f3d = (d == 2) && (length(tv) > 0), ...)
{
d <- x$mi["d"]
ev <- x$mi["ev"]
where <- "grid"
if(missing(pv))
pv <- if(d == 1) 1 else c(1, 2)
if(is.character(pv))
pv <- match(pv, x$vnames)
if(missing(tv))
tv <- (1:d)[ - pv]
if(is.character(tv))
tv <- match(tv, x$vnames)
vrs <- c(pv, tv)
if(any(duplicated(vrs)))
warning("Duplicated variables in pv, tv")
if(any((vrs <= 0) | (vrs > d)))
stop("Invalid variable numbers in pv, tv")
if(missing(m))
m <- if(d == 1) 100 else 40
m <- rep(m, d)
m[tv] <- mtv
xl <- x$box
if(!missing(xlim))
xl <- lflim(xlim, x$vnames, xl)
if((d != 2) & (any(ev == c(3, 7, 8))))
pred <- preplot.locfit(x, where = "fitp", band = band, tr = tr, what = what,
get.data = get.data, f3d = f3d)
else {
marg <- lfmarg(xl, m)
pred <- preplot.locfit(x, marg, band = band, tr = tr, what = what, get.data
= get.data, f3d = f3d)
}
plot(pred, pv = pv, tv = tv, ...)
}
"preplot.locfit"<-
function(object, newdata = NULL, where, tr = NULL, what = "coef", band = "none",
get.data = FALSE, f3d = FALSE, ...)
{
mi <- object$mi
dim <- mi["d"]
ev <- mi["ev"]
nointerp <- any(ev == c(3, 7, 8))
wh <- 1
n <- 1
if(is.null(newdata)) {
if(missing(where))
where <- if(nointerp) "fitp" else "grid"
if(where == "grid")
newdata <- lfmarg(object)
if(any(where == c("fitp", "ev", "fitpoints"))) {
where <- "fitp"
newdata <- lfknots(object, what = "x", delete.pv = FALSE)
}
if(where == "data")
newdata <- locfit.matrix(object)$x
if(where == "vect")
stop("you must give the vector points")
}
else {
where <- "vect"
if(is.data.frame(newdata))
newdata <- as.matrix(model.frame(delete.response(object$terms), newdata))
else if(is.list(newdata))
where <- "grid"
else newdata <- as.matrix(newdata)
}
if(is.null(tr)) {
if(what == "coef")
tr <- object$trans
else tr <- function(x)
x
}
if((nointerp) && (where == "grid") && (dim == 2)) {
nv <- object$nvc["nv"]
x <- object$eva$xev[2 * (1:nv) - 1]
y <- object$eva$xev[2 * (1:nv)]
z <- preplot.locfit.raw(object, 0, "fitp", what, band)$y
fhat <- interp::interp(x, y, z, newdata[[1]], newdata[[2]], ncp = 2)$z
}
else {
z <- preplot.locfit.raw(object, newdata, where, what, band)
fhat <- z$y
}
fhat[fhat == 0.1278433] <- NA
band <- pmatch(band, c("none", "global", "local", "prediction"))
if(band > 1)
sse <- z$se
else sse <- numeric(0)
if(where != "grid")
newdata <- list(xev = newdata, where = where)
else newdata$where <- where
data <- if(get.data) locfit.matrix(object) else list()
if((f3d) | (dim > 3))
dim <- 3
ret <- list(xev = newdata, fit = fhat, se.fit = sse, residual.scale = sqrt(
object$dp["rv"]), critval = object$critval, trans = tr, vnames = object$
vnames, yname = object$yname, dim = as.integer(dim), data = data)
class(ret) <- "preplot.locfit"
ret
}
"preplot.locfit.raw"<-
function(object, newdata, where, what, band, ...)
{
wh <- pmatch(where, c("vect", "grid", "data", "fitp"))
switch(wh,
{
mg <- n <- nrow(newdata)
xev <- newdata
}
,
{
xev <- unlist(newdata)
mg <- sapply(newdata, length)
n <- prod(mg)
}
,
{
mg <- n <- object$mi["n"]
xev <- newdata
}
,
{
mg <- n <- object$nvc["nv"]
xev <- newdata
}
)
.C("spreplot",
xev = as.numeric(object$eva$xev),
coef = as.numeric(object$eva$coef),
sv = as.numeric(object$cell$sv),
ce = as.integer(c(object$cell$ce, object$cell$s, object$cell$lo, object$
cell$hi)),
x = as.numeric(xev),
y = numeric(n),
se = numeric(n),
wpc = as.numeric(object$eva$pc),
scale = as.numeric(object$eva$scale),
m = as.integer(mg),
nvc = as.integer(object$nvc),
mi = as.integer(object$mi),
dp = as.numeric(object$dp),
mg = as.integer(object$eva$ev$mg),
deriv = as.integer(object$deriv),
nd = as.integer(length(object$deriv)),
sty = as.integer(object$sty),
wh = as.integer(wh),
what = c(what, band),
bs = list(eval(object$call$basis)), PACKAGE="locfit")
}
"print.preplot.locfit"<-
function(x, ...)
{
print(x$trans(x$fit))
invisible(x)
}
"plot.locfit.1d"<-
function(x, add=FALSE, main="", xlab="default", ylab=x$yname, type="l",
ylim, lty = 1, col = 1, ...) {
y <- x$fit
nos <- !is.na(y)
xev <- x$xev[[1]][nos]
y <- y[nos]
ord <- order(xev)
if(xlab == "default")
xlab <- x$vnames
tr <- x$trans
yy <- tr(y)
if(length(x$se.fit) > 0) {
crit <- x$critval$crit.val
cup <- tr((y + crit * x$se.fit))[ord]
clo <- tr((y - crit * x$se.fit))[ord]
}
ndat <- 0
if(length(x$data) > 0) {
ndat <- nrow(x$data$x)
xdsc <- rep(x$data$sc, length.out = ndat)
xdyy <- rep(x$data$y, length.out = ndat)
dok <- xdsc > 0
}
if(missing(ylim)) {
if(length(x$se.fit) > 0)
ylim <- c(min(clo), max(cup))
else ylim <- range(yy)
if(ndat > 0)
ylim <- range(c(ylim, xdyy[dok]/xdsc[dok]))
}
if(!add) {
plot(xev[ord], yy[ord], type = "n", xlab = xlab, ylab = ylab, main = main,
xlim = range(x$xev[[1]]), ylim = ylim, ...)
}
lines(xev[ord], yy[ord], type = type, lty = lty, col = col)
if(length(x$se.fit) > 0) {
lines(xev[ord], cup, lty = 2)
lines(xev[ord], clo, lty = 2)
}
if(ndat > 0) {
xd <- x$data$x[dok]
yd <- xdyy[dok]/xdsc[dok]
cd <- rep(x$data$ce, length.out = ndat)[dok]
if(length(x$data$y) < 2) {
rug(xd[cd == 0])
if(any(cd == 1))
rug(xd[cd == 1], ticksize = 0.015)
}
else {
plotbyfactor(xd, yd, cd, col = col, pch = c("o", "+"), add = TRUE)
}
}
invisible(NULL)
}
"plot.locfit.2d"<-
function(x, type="contour", main, xlab, ylab, zlab=x$yname, ...)
{
if(x$xev$where != "grid")
stop("Can only plot from grids")
if(missing(xlab))
xlab <- x$vnames[1]
if(missing(ylab))
ylab <- x$vnames[2]
tr <- x$trans
m1 <- x$xev[[1]]
m2 <- x$xev[[2]]
y <- matrix(tr(x$fit))
if(type == "contour")
contour(m1, m2, matrix(y, nrow = length(m1)), ...)
if(type == "image")
image(m1, m2, matrix(y, nrow = length(m1)), ...)
if((length(x$data) > 0) && any(type == c("contour", "image"))) {
xd <- x$data$x
ce <- rep(x$data$ce, length.out = nrow(xd))
points(xd[ce == 0, 1], xd[ce == 0, 2], pch = "o")
if(any(ce == 1))
points(xd[ce == 1, 1], xd[ce == 1, 2], pch = "+")
}
if(type == "persp") {
nos <- is.na(y)
y[nos] <- min(y[!nos])
persp(m1, m2, matrix(y, nrow = length(m1)), zlab=zlab, ...)
}
if(!missing(main))
title(main = main)
invisible(NULL)
}
"plot.locfit.3d"<-
function(x, main = "", pv, tv, type = "level", pred.lab = x$vnames, resp.lab =
x$yname, crit = 1.96, ...)
{
xev <- x$xev
if(xev$where != "grid")
stop("Can only plot from grids")
xev$where <- NULL
newx <- as.matrix(expand.grid(xev))
newy <- x$trans(x$fit)
wh <- rep("f", length(newy))
if(length(x$data) > 0) {
dat <- x$data
for(i in tv) {
m <- xev[[i]]
dat$x[, i] <- m[1 + round((dat$x[, i] - m[1])/(m[2] - m[1]))]
}
newx <- rbind(newx, dat$x)
if(is.null(dat$y))
newy <- c(newy, rep(NA, nrow(dat$x)))
else {
newy <- c(newy, dat$y/dat$sc)
newy[is.na(newy)] <- 0
}
wh <- c(wh, rep("d", nrow(dat$x)))
}
if(length(tv) == 0) {
newdat <- data.frame(newy, newx[, pv])
names(newdat) <- c("y", paste("pv", 1:length(pv), sep = ""))
}
else {
newdat <- data.frame(newx[, tv], newx[, pv], newy)
names(newdat) <- c(paste("tv", 1:length(tv), sep = ""), paste("pv", 1:
length(pv), sep = ""), "y")
for(i in 1:length(tv))
newdat[, i] <- as.factor(signif(newdat[, i], 5))
}
loc.strip <- function(...)
strip.default(..., strip.names = c(TRUE, TRUE), style = 1)
if(length(pv) == 1) {
clo <- cup <- numeric(0)
if(length(x$se.fit) > 0) {
if((!is.null(class(crit))) && (class(crit) == "kappa"))
crit <- crit$crit.val
cup <- x$trans((x$fit + crit * x$se.fit))
clo <- x$trans((x$fit - crit * x$se.fit))
}
formula <- switch(1 + length(tv),
y ~ pv1,
y ~ pv1 | tv1,
y ~ pv1 | tv1 * tv2,
y ~ pv1 | tv1 * tv2 * tv3)
pl <- xyplot(formula, xlab = pred.lab[pv], ylab = resp.lab, main = main,
type = "l", cup = cup, wh = wh, panel = panel.xyplot.lf, data
= newdat, strip = loc.strip, ...)
}
if(length(pv) == 2) {
formula <- switch(1 + length(tv),
y ~ pv1 * pv2,
y ~ pv1 * pv2 | tv1,
y ~ pv1 * pv2 | tv1 * tv2,
y ~ pv1 * pv2 | tv1 * tv2 * tv3)
if(type == "contour")
pl <- contourplot(formula, xlab = pred.lab[pv[1]], ylab = pred.lab[pv[2]],
main = main, data = newdat, strip = loc.strip, ...)
if(type == "level")
pl <- levelplot(formula, xlab = pred.lab[pv[1]], ylab = pred.lab[pv[2]],
main = main, data = newdat, strip = loc.strip, ...)
if((type == "persp") | (type == "wireframe"))
pl <- wireframe(formula, xlab = pred.lab[pv[1]], ylab = pred.lab[pv[2]],
zlab = resp.lab, data = newdat, strip = loc.strip, ...)
}
if(length(tv) > 0) {
if(exists("is.R") && is.function(is.R) && is.R())
names(pl$cond) <- pred.lab[tv]
else names(attr(pl$glist, "endpts")) <- attr(pl$glist, "names") <- names(
attr(pl$glist, "index")) <- pred.lab[tv]
}
pl
}
"panel.xyplot.lf"<-
function(x, y, subscripts, clo, cup, wh, type = "l", ...)
{
wh <- wh[subscripts]
panel.xyplot(x[wh == "f"], y[wh == "f"], type = type, ...)
if(length(clo) > 0) {
panel.xyplot(x[wh == "f"], clo[subscripts][wh == "f"], type = "l", lty = 2,
...)
panel.xyplot(x[wh == "f"], cup[subscripts][wh == "f"], type = "l", lty = 2,
...)
}
if(any(wh == "d")) {
yy <- y[wh == "d"]
if(any(is.na(yy)))
rug(x[wh == "d"])
else panel.xyplot(x[wh == "d"], yy)
}
}
"plot.preplot.locfit"<-
function(x, pv, tv, ...)
{
if(x$dim == 1)
plot.locfit.1d(x, ...)
if(x$dim == 2)
plot.locfit.2d(x, ...)
if(x$dim >= 3)
print(plot.locfit.3d(x, pv=pv, tv=tv, ...))
invisible(NULL)
}
"summary.preplot.locfit"<-
function(object, ...)
object$trans(object$fit)
"panel.locfit"<-
function(x, y, subscripts, z, rot.mat, distance, shade,
light.source, xlim, ylim, zlim, xlim.scaled, ylim.scaled, zlim.scaled, region,
col, lty, lwd, alpha, col.groups, polynum, drape, at,
xlab, ylab, zlab, xlab.default, ylab.default, zlab.default, aspect, panel.aspect,
scales.3d, contour, labels, ...)
{
if(!missing(z)) {
zs <- z[subscripts]
fit <- locfit.raw(cbind(x, y), zs, ...)
marg <- lfmarg(fit, m = 10)
zp <- predict(fit, marg)
if(!missing(contour)) {
lattice::panel.contourplot(marg[[1]], marg[[2]], zp, 1:length(zp), at=at)
}
else {
lattice::panel.wireframe(marg[[1]], marg[[2]], zp,
rot.mat, distance, shade,
light.source, xlim, ylim, zlim,
xlim.scaled, ylim.scaled, zlim.scaled,
col, lty, lwd, alpha, col.groups, polynum, drape, at)
}
}
else {
panel.xyplot(x, y, ...)
args <- list(x = x, y = y, ...)
ok <- names(formals(locfit.raw))
llines.locfit(do.call("locfit.raw",
args[ok[ok %in% names(args)]]))
}
}
llines.locfit <-
function (x, m = 100, tr = x$trans, ...)
{
newx <- lfmarg(x, m = m)[[1]]
y <- predict(x, newx, tr = tr)
llines(newx, y, ...)
}
"lfmarg"<-
function(xlim, m = 40)
{
if(!is.numeric(xlim)) {
d <- xlim$mi["d"]
xlim <- xlim$box
}
else d <- length(m)
marg <- vector("list", d)
m <- rep(m, length.out = d)
for(i in 1:d)
marg[[i]] <- seq(xlim[i], xlim[i + d], length.out = m[i])
marg
}
"lfeval"<-
function(object)
object$eva
"plot.lfeval"<-
function(x, add = FALSE, txt = FALSE, ...)
{
if(class(x) == "locfit")
x <- x$eva
d <- length(x$scale)
v <- matrix(x$xev, nrow = d)
if(d == 1) {
xx <- v[1, ]
y <- x$coef[, 1]
}
if(d == 2) {
xx <- v[1, ]
y <- v[2, ]
}
if(!add) {
plot(xx, y, type = "n", ...)
}
points(xx, y, ...)
if(txt)
text(xx, y, (1:length(xx)) - 1)
invisible(x)
}
"print.lfeval"<-
function(x, ...)
{
if(class(x) == "locfit")
x <- x$eva
d <- length(x$scale)
ret <- matrix(x$xev, ncol = d, byrow = TRUE)
print(ret)
}
"lflim"<-
function(limits, nm, ret)
{
d <- length(nm)
if(is.numeric(limits))
ret <- limits
else {
z <- match(nm, names(limits))
for(i in 1:d)
if(!is.na(z[i])) ret[c(i, i + d)] <- limits[[z[i]]]
}
as.numeric(ret)
}
"plot.eval"<-
function(x, add = FALSE, text = FALSE, ...)
{
d <- x$mi["d"]
v <- matrix(x$eva$xev, nrow = d)
ev <- x$mi["ev"]
pv <- if(any(ev == c(1, 2))) as.logical(x$cell$s) else rep(FALSE, ncol(v))
if(!add) {
plot(v[1, ], v[2, ], type = "n", xlab = x$vnames[1], ylab = x$vnames[2])
}
if(text)
text(v[1, ], v[2, ], (1:x$nvc["nv"]) - 1)
else {
if(any(!pv))
points(v[1, !pv], v[2, !pv], ...)
if(any(pv))
points(v[1, pv], v[2, pv], pch = "*", ...)
}
if(any(x$mi["ev"] == c(1, 2))) {
zz <- .C("triterm",
as.numeric(v),
h = as.numeric(lfknots(x, what = "h", delete.pv = FALSE)),
as.integer(x$cell$ce),
lo = as.integer(x$cell$lo),
hi = as.integer(x$cell$hi),
as.numeric(x$eva$scale),
as.integer(x$nvc),
as.integer(x$mi),
as.numeric(x$dp),
nt = integer(1),
term = integer(600),
box = x$box, PACKAGE="locfit")
ce <- zz$term + 1
}
else ce <- x$cell$ce + 1
if(any(x$mi["ev"] == c(1, 5, 7))) {
vc <- 2^d
ce <- matrix(ce, nrow = vc)
segments(v[1, ce[1, ]], v[2, ce[1, ]], v[1, ce[2, ]], v[2, ce[2, ]],
...)
segments(v[1, ce[1, ]], v[2, ce[1, ]], v[1, ce[3, ]], v[2, ce[3, ]],
...)
segments(v[1, ce[2, ]], v[2, ce[2, ]], v[1, ce[4, ]], v[2, ce[4, ]],
...)
segments(v[1, ce[3, ]], v[2, ce[3, ]], v[1, ce[4, ]], v[2, ce[4, ]],
...)
}
if(any(x$mi["ev"] == c(2, 8))) {
vc <- d + 1
m <- matrix(ce, nrow = 3)
segments(v[1, m[1, ]], v[2, m[1, ]], v[1, m[2, ]], v[2, m[2, ]], ...)
segments(v[1, m[1, ]], v[2, m[1, ]], v[1, m[3, ]], v[2, m[3, ]], ...)
segments(v[1, m[2, ]], v[2, m[2, ]], v[1, m[3, ]], v[2, m[3, ]], ...)
}
invisible(NULL)
}
"rv"<-
function(fit)
fit$dp["rv"]
"rv<-"<-
function(fit, value)
{
fit$dp["rv"] <- value
fit
}
"regband"<-
function(formula, what = c("CP", "GCV", "GKK", "RSW"), deg = 1, ...)
{
m <- match.call()
m$geth <- 3
m$deg <- c(deg, 4)
m$what <- NULL
m$deriv <- match(what, c("CP", "GCV", "GKK", "RSW"))
m[[1]] <- as.name("locfit")
z <- eval(m, sys.frame(sys.parent()))
names(z) <- what
z[1:length(what)]
}
"kdeb"<-
function(x, h0 = 0.01 * sd, h1 = sd, meth = c("AIC", "LCV", "LSCV", "BCV",
"SJPI", "GKK"), kern = "gauss", gf = 2.5)
{
n <- length(x)
sd <- sqrt(var(x))
z <- .C("kdeb",
x = as.numeric(x),
mi = as.integer(n),
band = numeric(length(meth)),
ind = integer(n),
h0 = as.numeric(gf * h0),
h1 = as.numeric(gf * h1),
meth = as.integer(match(meth, c("AIC", "LCV", "LSCV", "BCV", "SJPI", "GKK")
)),
nmeth = as.integer(length(meth)),
kern = pmatch(kern, c("rect", "epan", "bisq", "tcub", "trwt", "gauss")),
PACKAGE="locfit")
band <- z$band
names(band) <- meth
band
}
"lfknots"<-
function(x, tr, what = c("x", "coef", "h", "nlx"), delete.pv = TRUE)
{
nv <- x$nvc["nv"]
d <- x$mi["d"]
p <- x$mi["p"]
z <- 0:(nv - 1)
ret <- matrix(0, nrow = nv, ncol = 1)
rname <- character(0)
if(missing(tr))
tr <- x$trans
coef <- x$eva$coef
for(wh in what) {
if(wh == "x") {
ret <- cbind(ret, matrix(x$eva$xev, ncol = d, byrow = TRUE))
rname <- c(rname, x$vnames)
}
if(wh == "coef") {
d0 <- coef[, 1]
d0[d0 == 0.1278433] <- NA
ret <- cbind(ret, tr(d0))
rname <- c(rname, "mu hat")
}
if(wh == "f1") {
ret <- cbind(ret, coef[, 1 + (1:d)])
rname <- c(rname, paste("d", 1:d, sep = ""))
}
if(wh == "nlx") {
ret <- cbind(ret, coef[, d + 2])
rname <- c(rname, "||l(x)||")
}
if(wh == "nlx1") {
ret <- cbind(ret, coef[, d + 2 + (1:d)])
rname <- c(rname, paste("nlx-d", 1:d, sep = ""))
}
if(wh == "se") {
ret <- cbind(ret, sqrt(x$dp["rv"]) * coef[, d + 2])
rname <- c(rname, "StdErr")
}
if(wh == "infl") {
z <- coef[, 2 * d + 3]
ret <- cbind(ret, z * z)
rname <- c(rname, "Influence")
}
if(wh == "infla") {
ret <- cbind(ret, coef[, 2 * d + 3 + (1:d)])
rname <- c(rname, paste("inf-d", 1:d, sep = ""))
}
if(wh == "lik") {
ret <- cbind(ret, coef[, 3 * d + 3 + (1:3)])
rname <- c(rname, c("LocLike", "fit.df", "res.df"))
}
if(wh == "h") {
ret <- cbind(ret, coef[, 3 * d + 7])
rname <- c(rname, "h")
}
if(wh == "deg") {
ret <- cbind(ret, coef[, 3 * d + 8])
rname <- c(rname, "deg")
}
}
ret <- as.matrix(ret[, -1])
if(nv == 1)
ret <- t(ret)
dimnames(ret) <- list(NULL, rname)
if((delete.pv) && (any(x$mi["ev"] == c(1, 2))))
ret <- ret[!as.logical(x$cell$s), ]
ret
}
"locfit.matrix"<-
function(fit, data)
{
m <- fit$call
n <- fit$mi["n"]
y <- ce <- base <- 0
w <- 1
if(m[[1]] == "locfit.raw") {
x <- as.matrix(eval(m$x, fit$frame))
if(!is.null(m$y))
y <- eval(m$y, fit$frame)
if(!is.null(m$weights))
w <- eval(m$weights, fit$frame)
if(!is.null(m$cens))
ce <- eval(m$cens, fit$frame)
if(!is.null(m$base))
base <- eval(m$base, fit$frame)
}
else {
Terms <- terms(as.formula(m$formula))
attr(Terms, "intercept") <- 0
m[[1]] <- as.name("model.frame")
z <- pmatch(names(m), c("formula", "data", "weights", "cens", "base",
"subset"))
for(i in length(z):2)
if(is.na(z[i])) m[[i]] <- NULL
frm <- eval(m, fit$frame)
vnames <- as.character(attributes(Terms)$variables)[-1]
if(attr(Terms, "response")) {
y <- model.extract(frm, "response")
vnames <- vnames[-1]
}
x <- as.matrix(frm[, vnames])
if(any(names(m) == "weights"))
w <- model.extract(frm, weights)
if(any(names(m) == "cens"))
ce <- model.extract(frm, "cens")
if(any(names(m) == "base"))
base <- model.extract(frm, base)
}
sc <- if(any((fit$mi["tg"] %% 64) == c(5:8, 11, 12))) w else 1
list(x = x, y = y, w = w, sc = sc, ce = ce, base = base)
}
"expit"<-
function(x)
{
y <- x
ix <- (x < 0)
y[ix] <- exp(x[ix])/(1 + exp(x[ix]))
y[!ix] <- 1/(1 + exp( - x[!ix]))
y
}
"plotbyfactor"<-
function(x, y, f, data, col = 1:10, pch = "O", add = FALSE, lg, xlab = deparse(
substitute(x)), ylab = deparse(substitute(y)), log = "", ...)
{
if(!missing(data)) {
x <- eval(substitute(x), data)
y <- eval(substitute(y), data)
f <- eval(substitute(f), data)
}
f <- as.factor(f)
if(!add)
plot(x, y, type = "n", xlab = xlab, ylab = ylab, log = log, ...)
lv <- levels(f)
col <- rep(col, length.out = length(lv))
pch <- rep(pch, length.out = length(lv))
for(i in 1:length(lv)) {
ss <- f == lv[i]
if(any(ss))
points(x[ss], y[ss], col = col[i], pch = pch[i])
}
if(!missing(lg))
legend(lg[1], lg[2], legend = levels(f), col = col, pch = paste(pch,
collapse = ""))
}
"hatmatrix"<-
function(formula, dc = TRUE, ...)
{
m <- match.call()
m$geth <- 1
m[[1]] <- as.name("locfit")
z <- eval(m, sys.frame(sys.parent()))
nvc <- z[[2]]
nvm <- nvc[1]
nv <- nvc[4]
matrix(z[[1]], ncol = nvm)[, 1:nv]
}
"locfit.robust"<-
function(x, y, weights, ..., iter = 3)
{
m <- match.call()
if((!is.numeric(x)) && (class(x) == "formula")) {
m1 <- m[[1]]
m[[1]] <- as.name("locfit")
m$lfproc <- m1
names(m)[[2]] <- "formula"
return(eval(m, sys.frame(sys.parent())))
}
n <- length(y)
lfr.wt <- rep(1, n)
m[[1]] <- as.name("locfit.raw")
for(i in 0:iter) {
m$weights <- lfr.wt
fit <- eval(m, sys.frame(sys.parent()))
res <- residuals(fit, type = "raw")
s <- median(abs(res))
lfr.wt <- pmax(1 - (res/(6 * s))^2, 0)^2
}
fit
}
"locfit.censor"<-
function(x, y, cens, ..., iter = 3, km = FALSE)
{
m <- match.call()
if((!is.numeric(x)) && (class(x) == "formula")) {
m1 <- m[[1]]
m[[1]] <- as.name("locfit")
m$lfproc <- m1
names(m)[[2]] <- "formula"
return(eval(m, sys.frame(sys.parent())))
}
lfc.y <- y
cens <- as.logical(cens)
m$cens <- m$iter <- m$km <- NULL
m[[1]] <- as.name("locfit.raw")
for (i in 0:iter) {
m$y <- lfc.y
fit <- eval(m, sys.frame(sys.parent()))
fh <- fitted(fit)
if(km) {
sr <- y - fh
lfc.y <- y + km.mrl(sr, cens)
}
else {
rdf <- sum(1 - cens) - 2 * fit$dp["df1"] + fit$dp["df2"]
sigma <- sqrt(sum((y - fh) * (lfc.y - fh))/rdf)
sr <- (y - fh)/sigma
lfc.y <- fh + (sigma * dnorm(sr))/pnorm( - sr)
}
lfc.y[!cens] <- y[!cens]
}
m$cens <- substitute(cens)
m$y <- substitute(y)
fit$call <- m
fit
}
"km.mrl"<-
function(times, cens)
{
n <- length(times)
if(length(cens) != length(times))
stop("times and cens must have equal length")
ord <- order(times)
times <- times[ord]
cens <- cens[ord]
n.alive <- n:1
haz.km <- (1 - cens)/n.alive
surv.km <- exp(cumsum(log(1 - haz.km[ - n])))
int.surv <- c(diff(times) * surv.km)
mrl.km <- c(rev(cumsum(rev(int.surv)))/surv.km, 0)
mrl.km[!cens] <- 0
mrl.km.ord <- numeric(n)
mrl.km.ord[ord] <- mrl.km
mrl.km.ord
}
"locfit.quasi"<-
function(x, y, weights, ..., iter = 3, var = abs)
{
m <- match.call()
if((!is.numeric(x)) && (class(x) == "formula")) {
m1 <- m[[1]]
m[[1]] <- as.name("locfit")
m$lfproc <- m1
names(m)[[2]] <- "formula"
return(eval(m, sys.frame(sys.parent())))
}
n <- length(y)
w0 <- lfq.wt <- if(missing(weights)) rep(1, n) else weights
m[[1]] <- as.name("locfit.raw")
for(i in 0:iter) {
m$weights <- lfq.wt
fit <- eval(m, sys.frame(sys.parent()))
fh <- fitted(fit)
lfq.wt <- w0/var(fh)
}
fit
}
"density.lf"<-
function(x, n=50, window="gaussian", width, from, to, cut=if(iwindow == 4)
0.75 else 0.5, ev=lfgrid(mg=n, ll=from, ur=to), deg=0,
family="density", link="ident", ...)
{
if(!exists("logb"))
logb <- log
x <- sort(x)
r <- range(x)
iwindow <- pmatch(window, c("rectangular", "triangular", "cosine", "gaussian"
), -1.)
if(iwindow < 0.)
kern <- window
else kern <- c("rect", "tria", NA, "gauss")[iwindow]
if(missing(width)) {
nbar <- logb(length(x), base = 2.) + 1.
width <- diff(r)/nbar * 0.5
}
if(missing(from))
from <- r[1.] - width * cut
if(missing(to))
to <- r[2.] + width * cut
if(to <= from)
stop("Invalid from/to values")
h <- width/2
if(kern == "gauss")
h <- h * 1.25
fit <- locfit.raw(lp(x, h = h, deg = deg), ev = ev, kern = kern, link = link,
family = family, ...)
list(x = fit$eva$xev, y = fit$eva$coef[, 1])
}
"smooth.lf"<-
function(x, y, xev = x, direct = FALSE, ...)
{
if(missing(y)) {
y <- x
x <- 1:length(y)
}
if(direct) {
fit <- locfit.raw(x, y, ev = xev, geth = 7, ...)
fv <- fit$y
xev <- fit$x
if(is.matrix(x))
xev <- matrix(xev, ncol = ncol(x), byrow = TRUE)
}
else {
fit <- locfit.raw(x, y, ...)
fv <- predict(fit, xev)
}
list(x = xev, y = fv, call = match.call())
}
"gcv"<-
function(x, ...)
{
m <- match.call()
if(is.numeric(x))
m[[1]] <- as.name("locfit.raw")
else {
m[[1]] <- as.name("locfit")
names(m)[2] <- "formula"
}
fit <- eval(m, sys.frame(sys.parent()))
z <- fit$dp[c("lk", "df1", "df2")]
n <- fit$mi["n"]
z <- c(z, (-2 * n * z[1])/(n - z[2])^2)
names(z) <- c("lik", "infl", "vari", "gcv")
z
}
"gcvplot"<-
function(..., alpha, df = 2)
{
m <- match.call()
m[[1]] <- as.name("gcv")
m$df <- NULL
if(!is.matrix(alpha))
alpha <- matrix(alpha, ncol = 1)
k <- nrow(alpha)
z <- matrix(nrow = k, ncol = 4)
for(i in 1:k) {
m$alpha <- alpha[i, ]
z[i, ] <- eval(m, sys.frame(sys.parent()))
}
ret <- list(alpha = alpha, cri = "GCV", df = z[, df], values = z[, 4])
class(ret) <- "gcvplot"
ret
}
"plot.gcvplot"<-
function(x, xlab = "Fitted DF", ylab = x$cri, ...)
{
plot(x$df, x$values, xlab = xlab, ylab = ylab, ...)
}
"print.gcvplot"<-
function(x, ...)
plot.gcvplot(x = x, ...)
"summary.gcvplot"<-
function(object, ...)
{
z <- cbind(object$df, object$values)
dimnames(z) <- list(NULL, c("df", object$cri))
z
}
"aic"<-
function(x, ..., pen = 2)
{
m <- match.call()
if(is.numeric(x))
m[[1]] <- as.name("locfit.raw")
else {
m[[1]] <- as.name("locfit")
names(m)[2] <- "formula"
}
m$pen <- NULL
fit <- eval(m, sys.frame(sys.parent()))
dp <- fit$dp
z <- dp[c("lk", "df1", "df2")]
z <- c(z, -2 * z[1] + pen * z[2])
names(z) <- c("lik", "infl", "vari", "aic")
z
}
"aicplot"<-
function(..., alpha)
{
m <- match.call()
m[[1]] <- as.name("aic")
if(!is.matrix(alpha))
alpha <- matrix(alpha, ncol = 1)
k <- nrow(alpha)
z <- matrix(nrow = k, ncol = 4)
for(i in 1:k) {
m$alpha <- alpha[i, ]
z[i, ] <- eval(m, sys.frame(sys.parent()))
}
ret <- list(alpha = alpha, cri = "AIC", df = z[, 2], values = z[, 4])
class(ret) <- "gcvplot"
ret
}
"cp"<-
function(x, ..., sig2 = 1)
{
m <- match.call()
if(is.numeric(x))
m[[1]] <- as.name("locfit.raw")
else {
m[[1]] <- as.name("locfit")
names(m)[2] <- "formula"
}
m$sig2 <- NULL
fit <- eval(m, sys.frame(sys.parent()))
z <- c(fit$dp[c("lk", "df1", "df2")], fit$mi["n"])
z <- c(z, (-2 * z[1])/sig2 - z[4] + 2 * z[2])
names(z) <- c("lik", "infl", "vari", "n", "cp")
z
}
"cpplot"<-
function(..., alpha, sig2)
{
m <- match.call()
m[[1]] <- as.name("cp")
m$sig2 <- NULL
if(!is.matrix(alpha))
alpha <- matrix(alpha, ncol = 1)
k <- nrow(alpha)
z <- matrix(nrow = k, ncol = 5)
for(i in 1:k) {
m$alpha <- alpha[i, ]
z[i, ] <- eval(m, sys.frame(sys.parent()))
}
if(missing(sig2)) {
s <- (1:k)[z[, 3] == max(z[, 3])][1]
sig2 <- (-2 * z[s, 1])/(z[s, 4] - 2 * z[s, 2] + z[s, 3])
}
ret <- list(alpha = alpha, cri = "CP", df = z[, 3], values = (-2 * z[, 1])/
sig2 - z[, 4] + 2 * z[, 2])
class(ret) <- "gcvplot"
ret
}
"lcv"<-
function(x, ...)
{
m <- match.call()
if(is.numeric(x))
m[[1]] <- as.name("locfit.raw")
else {
m[[1]] <- as.name("locfit")
names(m)[2] <- "formula"
}
fit <- eval(m, sys.frame(sys.parent()))
z <- fit$dp[c("lk", "df1", "df2")]
res <- residuals(fit, type = "d2", cv = TRUE)
z <- c(z, sum(res))
names(z) <- c("lik", "infl", "vari", "cv")
z
}
"lcvplot"<-
function(..., alpha)
{
m <- match.call()
m[[1]] <- as.name("lcv")
if(!is.matrix(alpha))
alpha <- matrix(alpha, ncol = 1)
k <- nrow(alpha)
z <- matrix(nrow = k, ncol = 4)
for(i in 1:k) {
m$alpha <- alpha[i, ]
z[i, ] <- eval(m, sys.frame(sys.parent()))
}
ret <- list(alpha = alpha, cri = "LCV", df = z[, 2], values = z[, 4])
class(ret) <- "gcvplot"
ret
}
"lscv"<-
function(x, ..., exact = FALSE)
{
if(exact) {
ret <- lscv.exact(x, ...)
}
else {
m <- match.call()
m$exact <- NULL
if(is.numeric(x))
m[[1]] <- as.name("locfit.raw")
else {
m[[1]] <- as.name("locfit")
names(m)[2] <- "formula"
}
m$geth <- 6
ret <- eval(m, sys.frame(sys.parent()))
}
ret
}
"lscv.exact"<-
function(x, h = 0)
{
if(!is.null(attr(x, "alpha")))
h <- attr(x, "alpha")[2]
if(h <= 0)
stop("lscv.exact: h must be positive.")
ret <- .C("slscv",
x = as.numeric(x),
n = as.integer(length(x)),
h = as.numeric(h),
ret = numeric(2), PACKAGE="locfit")$ret
ret
}
"lscvplot"<-
function(..., alpha)
{
m <- match.call()
m[[1]] <- as.name("lscv")
if(!is.matrix(alpha))
alpha <- matrix(alpha, ncol = 1)
k <- nrow(alpha)
z <- matrix(nrow = k, ncol = 2)
for(i in 1:k) {
m$alpha <- alpha[i, ]
z[i, ] <- eval(m, sys.frame(sys.parent()))
}
ret <- list(alpha = alpha, cri = "LSCV", df = z[, 2], values = z[, 1])
class(ret) <- "gcvplot"
ret
}
"sjpi"<-
function(x, a)
{
dnorms <- function(x, k)
{
if(k == 0)
return(dnorm(x))
if(k == 1)
return( - x * dnorm(x))
if(k == 2)
return((x * x - 1) * dnorm(x))
if(k == 3)
return(x * (3 - x * x) * dnorm(x))
if(k == 4)
return((3 - x * x * (6 - x * x)) * dnorm(x))
if(k == 6)
return((-15 + x * x * (45 - x * x * (15 - x * x))) * dnorm(x))
stop("k too large in dnorms")
}
alpha <- a * sqrt(2)
n <- length(x)
M <- outer(x, x, "-")
s <- numeric(length(alpha))
for(i in 1:length(alpha)) {
s[i] <- sum(dnorms(M/alpha[i], 4))
}
s <- s/(n * (n - 1) * alpha^5)
h <- (s * 2 * sqrt(pi) * n)^(-0.2)
lambda <- diff(summary(x)[c(2, 5)])
A <- 0.92 * lambda * n^(-1/7)
B <- 0.912 * lambda * n^(-1/9)
tb <- - sum(dnorms(M/B, 6))/(n * (n - 1) * B^7)
sa <- sum(dnorms(M/A, 4))/(n * (n - 1) * A^5)
ah <- 1.357 * (sa/tb * h^5)^(1/7)
cbind(h, a, ah/sqrt(2), s)
}
"scb"<-
function(x, ..., ev = lfgrid(20), simul = TRUE, type = 1)
{
oc <- m <- match.call()
if(is.numeric(x))
m[[1]] <- as.name("locfit.raw")
else {
m[[1]] <- as.name("locfit")
names(m)[2] <- "formula"
}
m$type <- m$simul <- NULL
m$geth <- 70 + type + 10 * simul
m$ev <- substitute(ev)
fit <- eval(m, sys.frame(sys.parent()))
fit$call <- oc
class(fit) <- "scb"
fit
}
"plot.scb"<-
function(x, add = FALSE, ...)
{
fit <- x$trans(x$coef)
lower <- x$trans(x$lower)
upper <- x$trans(x$upper)
d <- x$d
if(d == 1)
plot.scb.1d(x, fit, lower, upper, add, ...)
if(d == 2)
plot.scb.2d(x, fit = fit, lower = lower, upper = upper, ...)
if(!any(d == c(1, 2)))
stop("Can't plot this scb")
}
"plot.scb.1d"<-
function(x, fit, lower, upper, add = FALSE, style = "band", ...)
{
if(style == "test") {
lower <- lower - fit
upper <- upper - fit
}
if(!add) {
yl <- range(c(lower, fit, upper))
plot(x$xev, fit, type = "l", ylim = yl, xlab = x$vnames[1])
}
lines(x$xev, lower, lty = 2)
lines(x$xev, upper, lty = 2)
if(is.null(x$call$deriv)) {
dx <- x$data$x
sc <- if(any((x$mi["tg"] %% 64) == c(5:8, 11, 12))) x$data$w else 1
dy <- x$data$y/sc
points(dx, dy)
}
if(style == "test")
abline(h = 0, lty = 3)
}
"plot.scb.2d" <- function(x, fit, lower, upper, style = "tl", ylim, ...) {
plot.tl <- function(x, y, z, nint = c(16, 15), v1, v2,
xlab=deparse(substitute(x)),
ylab=deparse(substitute(y)),
legend=FALSE, pch="", ...) {
xl <- range(x)
if (legend) {
mar <- par()$mar
if (mar[4] < 6.1)
par(mar = c(mar[1:3], 6.1))
on.exit(par(mar = mar))
dlt <- diff(xl)
xl[2] <- xl[2] + 0.02 * dlt
}
plot(1, 1, type = "n", xlim = xl, ylim = range(y), xlab = xlab,
ylab = ylab, ...)
nx <- length(x)
ny <- length(y)
if (missing(v)) {
v <- seq(min(z) - 0.0001, max(z), length.out = nint + 1)
} else {
nint <- length(v) - 1
}
ix <- rep(1:nx, ny)
iy <- rep(1:ny, rep(nx, ny))
r1 <- range(z[, 1])
r2 <- range(z[, 2])
hue <- if (missing(v1)) {
floor((nint[1] * (z[, 1] - r1[1]))/(r1[2] - r1[1]) * 0.999999999)
} else cut(z[, 1], v1) - 1
sat <- if (missing(v2)) {
floor((nint[2] * (z[, 2] - r2[1]))/(r2[2] - r2[1]) * 0.999999999)
} else cut(z[, 2], v2) - 1
col <- hue + nint[1] * sat + 1
x <- c(2 * x[1] - x[2], x, 2 * x[nx] - x[nx - 1])
y <- c(2 * y[1] - y[2], y, 2 * y[ny] - y[ny - 1])
x <- (x[1:(nx + 1)] + x[2:(nx + 2)])/2
y <- (y[1:(ny + 1)] + y[2:(ny + 2)])/2
for (i in unique(col)) {
u <- col == i
if(pch == "") {
xx <- rbind(x[ix[u]], x[ix[u] + 1], x[ix[u] + 1], x[ix[u]], NA)
yy <- rbind(y[iy[u]], y[iy[u]], y[iy[u] + 1], y[iy[u] + 1], NA)
polygon(xx, yy, col = i, border = 0)
}
else points(x[ix[u]], y[iy[u]], col = i, pch = pch)
}
if(legend) {
yv <- seq(min(y), max(y), length = length(v))
x1 <- max(x) + 0.02 * dlt
x2 <- max(x) + 0.06 * dlt
for(i in 1:nint) {
polygon(c(x1, x2, x2, x1), rep(yv[i:(i + 1)], c(2, 2)),
col = i, border = 0)
}
axis(side = 4, at = yv, labels = v, adj = 0)
}
}
if(style == "trell") {
if(missing(ylim))
ylim <- range(c(fit, lower, upper))
loc.dat = data.frame(x1 = x$xev[, 1], x2 = x$xev[, 2], y = fit)
pl <- xyplot(y ~ x1 | as.factor(x2), data = loc.dat,
panel = panel.xyplot.lf, clo=lower, cup=upper,
wh=rep("f", nrow(loc.dat)))
plot(pl)
}
if(style == "tl") {
ux <- unique(x$xev[, 1])
uy <- unique(x$xev[, 2])
sig <- abs(x$coef/x$sd)
rv1 <- max(abs(fit)) * 1.0001
v1 <- seq( - rv1, rv1, length.out = 17)
v2 <- - c(-1e-100, crit(const = x$kap, cov = c(0.5, 0.7, 0.8, 0.85,
0.9, 0.95, 0.98, 0.99, 0.995,
0.999, 0.9999))$crit.val,
1e+300)
plot.tl(ux, uy, cbind(fit, - sig), v1 = v1, v2 = v2,
xlab = x$vnames[1], ylab = x$vnames[2])
}
}
"print.scb"<-
function(x, ...)
{
m <- cbind(x$xev, x$trans(x$coef), x$trans(x$lower), x$trans(x$upper))
dimnames(m) <- list(NULL, c(x$vnames, "fit", "lower", "upper"))
print(m)
}
"kappa0"<-
function(formula, cov=0.95, ev=lfgrid(20), ...)
{
if(class(formula) == "locfit") {
m <- formula$call
}
else {
m <- match.call()
m$cov <- NULL
}
m$dc <- TRUE
m$geth <- 2
m$ev <- substitute(ev)
m[[1]] <- as.name("locfit")
z <- eval(m, sys.frame(sys.parent()))
crit(const = z$const, d = z$d, cov = cov)
}
"crit"<-
function(fit, const = c(0, 1), d = 1, cov = 0.95, rdf = 0)
{
if(!missing(fit)) {
z <- fit$critval
if(missing(const) & missing(d) & missing(cov))
return(z)
if(!missing(const))
z$const <- const
if(!missing(d))
z$d <- d
if(!missing(cov))
z$cov <- cov
if(!missing(rdf))
z$rdf <- rdf
}
else {
z <- list(const = const, d = d, cov = cov, rdf = rdf, crit.val = 0)
class(z) <- "kappa"
}
z$crit.val <- .C("scritval",
k0 = as.numeric(z$const),
d = as.integer(z$d),
cov = as.numeric(z$cov),
m = as.integer(length(z$const)),
rdf = as.numeric(z$rdf),
x = numeric(1),
k = as.integer(1), PACKAGE="locfit")$x
z
}
"crit<-"<-
function(fit, value)
{
if(is.numeric(value))
fit$critval$crit.val <- value[1]
else {
if(class(value) != "kappa")
stop("crit<-: value must be numeric or class kappa")
fit$critval <- value
}
fit
}
"spence.15"<-
function(y)
{
n <- length(y)
y <- c(rep(y[1], 7), y, rep(y[n], 7))
n <- length(y)
k <- 3:(n - 2)
a3 <- y[k - 1] + y[k] + y[k + 1]
a2 <- y[k - 2] + y[k + 2]
y1 <- y[k] + 3 * (a3 - a2)
n <- length(y1)
k <- 1:(n - 3)
y2 <- y1[k] + y1[k + 1] + y1[k + 2] + y1[k + 3]
n <- length(y2)
k <- 1:(n - 3)
y3 <- y2[k] + y2[k + 1] + y2[k + 2] + y2[k + 3]
n <- length(y3)
k <- 1:(n - 4)
y4 <- y3[k] + y3[k + 1] + y3[k + 2] + y3[k + 3] + y3[k + 4]
y4/320
}
"spence.21"<-
function(y)
{
n <- length(y)
y <- c(rep(y[1], 10), y, rep(y[n], 10))
n <- length(y)
k <- 4:(n - 3)
y1 <- - y[k - 3] + y[k - 1] + 2 * y[k] + y[k + 1] - y[k + 3]
n <- length(y1)
k <- 4:(n - 3)
y2 <- y1[k - 3] + y1[k - 2] + y1[k - 1] + y1[k] + y1[k + 1] + y1[k + 2] + y1[
k + 3]
n <- length(y2)
k <- 3:(n - 2)
y3 <- y2[k - 2] + y2[k - 1] + y2[k] + y2[k + 1] + y2[k + 2]
n <- length(y3)
k <- 3:(n - 2)
y4 <- y3[k - 2] + y3[k - 1] + y3[k] + y3[k + 1] + y3[k + 2]
y4/350
}
"store"<-
function(data = FALSE, grand = FALSE)
{
lfmod <- c("ang", "gam.lf", "gam.slist", "lf", "left", "right",
"cpar", "lp")
lfmeth <- c("fitted.locfit", "formula.locfit", "predict.locfit",
"lines.locfit", "points.locfit", "print.locfit", "residuals.locfit",
"summary.locfit", "print.summary.locfit")
lfev <- c("rbox", "gr", "dat", "xbar", "none")
lfplo <- c("plot.locfit", "preplot.locfit", "preplot.locfit.raw",
"print.preplot.locfit", "plot.locfit.1d", "plot.locfit.2d",
"plot.locfit.3d", "panel.xyplot.lf", "plot.preplot.locfit",
"summary.preplot.locfit", "panel.locfit", "lfmarg")
lffre <- c("hatmatrix", "locfit.robust", "locfit.censor", "km.mrl",
"locfit.quasi", "density.lf", "smooth.lf")
lfscb <- c("scb", "plot.scb", "plot.scb.1d", "plot.scb.2d", "print.scb",
"kappa0", "crit", "crit<-", "plot.tl")
lfgcv <- c("gcv", "gcvplot", "plot.gcvplot", "print.gcvplot",
"summary.gcvplot", "aic", "aicplot", "cp", "cpplot", "lcv", "lcvplot",
"lscv", "lscv.exact", "lscvplot", "sjpi")
lfspen <- c("spence.15", "spence.21")
lffuns <- c("locfit", "locfit.raw", lfmod, lfmeth, lfev, lfplo, "lfeval",
"plot.lfeval", "print.lfeval", "lflim", "plot.eval", "rv", "rv<-",
"regband", "kdeb", "lfknots", "locfit.matrix", "expit", "plotbyfactor",
lffre, lfgcv, lfscb, lfspen, "store")
lfdata <- c("bad", "cltest", "cltrain", "co2", "diab", "geyser", "ethanol",
"mcyc", "morths", "border", "heart", "trimod", "insect", "iris", "spencer",
"stamp")
lfgrand <- c("locfit.raw", "crit", "predict.locfit", "preplot.locfit",
"preplot.locfit.raw", "expit", "rv", "rv<-", "knots")
dump(lffuns, "S/locfit.s")
if(data)
dump(lfdata, "S/locfit.dat")
if(grand)
dump(lfgrand, "src-gr/lfgrand.s")
dump(lffuns, "R/locfit.s")
} |
gettrainmethod <-
function (method)
{
if (method == "logistic") {
rval = function(Z, T) {
if (length(levels(T)) == 2)
return(matrix(coefficients(multinom(T ~ Z, trace = FALSE))))
else return(t(coefficients(multinom(T ~ Z, trace = FALSE))))
}
}
else if (method == "logistic2") {
rval = function(Z, T) {
if (length(levels(T)) == 2)
return(matrix(coefficients(multinom(T ~ .^2,
data = data.frame(Z), trace = FALSE))))
else return(t(coefficients(multinom(T ~ .^2, data = data.frame(Z),
trace = FALSE))))
}
}
else if (method == "lda") {
rval = function(Z, T) {
gn = length(levels(T))
return(lda(Z, T, prior = rep(1/gn, gn), tol = 1e-05))
}
}
else if (method == "forest") {
rval = function(Z, T) {
return(randomForest(Z, T))
}
}
else if (method == "glmnet") {
rval = function(Z, T) {
return(cv.glmnet(Z, T, family = "multinomial"))
}
}
else if (method == "glmnet2") {
rval = function(Z, T) {
means = apply(Z, 2, mean)
sds = apply(Z, 2, sd)
Z = scale(Z)
Z = as.matrix(model.matrix(~.^2, data = data.frame(Z))[,
-1])
return(list(means, sds, cv.glmnet(Z, T, family = "multinomial")))
}
}
return(rval)
} |
regulomeSearch <- function(query=NULL,
genomeAssembly = NULL,
limit=1000,
timeout=100) {
if(is.null(genomeAssembly)) {
genomeAssembly <- "GRCh37"
}
tryCatch({
qr <- paste("https://", "www.regulomedb.org/regulome-search/?regions=", paste(query, collapse = '%0A'), "&genome=", genomeAssembly, "&limit=", limit, "&format=json", sep="")
r <- GET(qr, timeout=timeout)
raw <- content(r, "text")
json_content <- fromJSON(raw)
guery_coordinates <- json_content$query_coordinates
features1 <- lapply(json_content$features, function(x) {
x[sapply(x, is.null)] <- NA
unlist(x)
})
features <- t(data.frame(do.call("rbind", features1), check.names = FALSE, check.rows = FALSE))
rownames(features) <- seq(1:nrow(features))
regulome_score <- lapply(json_content$regulome_score, function(x) {
x[sapply(x, is.null)] <- NA
unlist(x)
})
regulome_score <- t(data.frame(do.call("rbind", regulome_score), check.names = FALSE, check.rows = FALSE))
rownames(regulome_score) <- seq(1:nrow(regulome_score))
tryCatch({
variants <- lapply(json_content$variants, function(x) {
x[sapply(x, is.null)] <- NA
unlist(x)
})
variants <- t(data.frame(do.call("rbind", variants), check.names = FALSE, check.rows = FALSE))
rownames(variants) <- seq(1:nrow(variants))
}, error=function(e) {
print(e)
variants <- NULL
})
nearby_snps <- data.frame(do.call("rbind", json_content$nearby_snps))
assembly <- json_content$assembly
return(list(guery_coordinates=guery_coordinates,
features=features,
regulome_score=regulome_score,
variants=variants,
nearby_snps=nearby_snps,
assembly=assembly))
}, error=function(e) {
print(e)
return(NULL)
})
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.