code
stringlengths 1
13.8M
|
---|
post_medx <- function(
x,
ed,
probs,
time,
lower,
upper,
greater,
small_bound,
return_samples,
...
) {
UseMethod("post_medx", x)
}
post_medx.dreamer_bma <- function(
x,
ed,
probs = c(.025, .975),
time = NULL,
lower = min(x$doses),
upper = max(x$doses),
greater = TRUE,
small_bound = 0,
return_samples = FALSE,
...
) {
assert_no_dots("post_medx.dreamer_bma", ...)
time <- get_time(x, time)
mcmc_index <- vapply(
x,
function(y) any(grepl("mcmc_", class(y))),
logical(1)
) %>% which()
model_index <- attr(x, "model_index")
samps <- purrr::map_df(
unique(model_index),
function(i) {
index <- which(model_index == i)
post_medx(
x = x[[mcmc_index[i]]],
ed = ed,
probs = probs,
time = time,
lower = lower,
upper = upper,
greater = greater,
small_bound = small_bound,
index = index,
return_samples = TRUE
)$samps
}
)
output <- summarize_medx(samps = samps, probs = probs)
return_stats_samps(output, samps, return_samples)
}
post_medx.dreamer <- function(
x,
ed,
probs = c(.025, .975),
time = NULL,
lower = min(attr(x, "doses")),
upper = max(attr(x, "doses")),
greater = TRUE,
small_bound = 0,
return_samples = FALSE,
index = 1:(nrow(x[[1]]) * length(x)),
...
) {
assert_no_dots("post_medx.dreamer", ...)
time <- get_time(x, time)
extremes <- get_extreme(
x = x,
time = time,
greater = greater,
lower = lower,
upper = upper,
index = index
)
samps <- purrr::map_df(
ed,
calc_post_medx_samps,
effect100 = extremes$extreme_responses,
extreme_dose = extremes$doses,
x = x,
index = index,
lower = lower,
upper = upper,
greater = greater,
time = time,
small_bound = small_bound
)
output <- summarize_medx(samps = samps, probs = probs)
return_stats_samps(output, samps, return_samples)
}
calc_post_medx_samps <- function(
ed,
effect100,
extreme_dose,
small_bound,
x,
index,
lower,
upper,
greater,
time
) {
effect_x <- (ed / 100) * (effect100 - small_bound) + small_bound
post_doses <- get_dose(
x = x,
time = time,
response = effect_x,
index = index,
lower = lower,
upper = upper
)
post_doses[post_doses > extreme_dose] <- NA
return(
dplyr::tibble(
ed = ed,
dose = post_doses
)
)
}
post_medx.dreamer_mcmc_independent <- function(...) {
rlang::abort(
"post_medx() not supported for independent models.",
class = "dreamer"
)
}
post_medx.dreamer_mcmc_independent_binary <- function(...) {
rlang::abort(
"post_medx() not supported for independent models.",
class = "dreamer"
)
}
summarize_medx <- function(samps, probs) {
output <- dplyr::group_by(samps, .data$ed) %>%
dplyr::summarize(
pr_edx_exists = mean(!is.na(.data$dose)),
mean = mean(.data$dose, na.rm = TRUE)
)
output2 <- purrr::map(
probs,
function(xx, samps) {
dplyr::group_by(samps, .data$ed) %>%
dplyr::summarize(
!!(paste0(100 * xx, "%")) :=
quantile(.data$dose, probs = xx, na.rm = TRUE)
)
},
samps = samps
) %>%
{
Reduce(
function(x, y, ...) merge(x, y, by = "ed"),
.
)
}
output <- merge(output, output2, by = "ed")
return(output)
}
return_stats_samps <- function(stats, samps, return_samples) {
if (return_samples) {
return(list(stats = stats, samps = samps))
} else {
return(list(stats = stats))
}
} |
E(chartr2("aixbjyckz", "ab!", "xyz"), "xixyjyckz") |
"read.crd" <- function(file, ...) {
pos <- regexpr("\\.([[:alnum:]]+)$", file)
ext <- ifelse(pos > -1L, substring(file, pos + 1L), "")
if(ext %in% c("crd")) {
class(file)=c("character", "charmm")
}
if(ext %in% c("inpcrd", "rst")) {
class(file)=c("character", "amber")
}
UseMethod("read.crd", file)
} |
survs <- function
(y, wt, x, parms, continuous)
{
y <- data.frame(y)
if (parms$LTRC){
colnames(y)[1:4] <- c('start','end','event','biomarker')
formulay1 <- Surv(start, end, event) ~ . - biomarker
formulay2 <- Surv(start, end, event) ~ .
} else {
colnames(y)[1:3] <- c('end','event','biomarker')
formulay1 <- Surv(end, event) ~ . - biomarker
formulay2 <- Surv(end, event) ~ .
}
nevents <- sum(y[,'event'])
rootval <- get_node_val(formulay1, formulay2, y,
lrt=parms$lrt,
stable=parms$stable, cov.max=parms$cov.max)
if (nevents <= parms$min.nevents*2 || rootval < parms$stop.thre){
if (continuous){
goodness <- rep(-Inf,nrow(y)-1); direction <- goodness;
} else{
ux <- sort(unique(x))
goodness <- rep(-Inf,length(ux)-1); direction <- ux
}
return(list(goodness=goodness, direction=direction))
}
if (continuous) {
n <- nrow(y)
goodness <- rep(-Inf,n-1)
direction <- double(n-1)
for (i in 1:(n-1)) {
if (x[i] != x[i+1]) {
nel <- sum(y$event[1:i])
ner <- sum(y$event[(i+1):n])
if (nel <= parms$min.nevents || ner <= parms$min.nevents ){
result <- c(-Inf,0)
} else{
result <- tryCatch({
leftval <- get_node_val(formulay1, formulay2, y[1:i,],
lrt= parms$lrt,
stable=parms$stable, cov.max=parms$cov.max)
rightval <- get_node_val(formulay1, formulay2, y[(i+1):n,],
lrt= parms$lrt,
stable=parms$stable, cov.max=parms$cov.max)
c(rootval - (leftval + rightval), sign(leftval-rightval))
}, error = function(e){ c(-Inf, sign(1))})
}
goodness[i] <- result[1]; direction[i] <- result[2]
}
}
goodness <- goodness + parms$split.add
} else {
n <- nrow(y)
ux <- sort(unique(x))
nx <- length(ux)
goodness <- rep(-Inf, nx-1)
direction <- double(nx-1)
xorder <- order(x); xtmp <- x[xorder]; ytmp <- y[xorder,]
for (i in 1:(nx-1)){
nextstart <- min(which(xtmp == ux[i+1]))
nel <- sum(ytmp$event[1:(nextstart-1)])
ner <- sum(ytmp$event[nextstart:n])
if (nel <= parms$min.nevents | ner <= parms$min.nevents ){
result <- c(-Inf,0)
} else{
result <- tryCatch({
leftval <- get_node_val(formulay1, formulay2, ytmp[1:(nextstart-1),],
lrt=parms$lrt,
stable=parms$stable, cov.max=parms$cov.max)
rightval <- get_node_val(formulay1, formulay2, ytmp[nextstart:n,],
lrt=parms$lrt,
stable=parms$stable, cov.max=parms$cov.max)
c(rootval - (leftval + rightval), sign(leftval-rightval))
}, error = function(e){ c(-Inf, sign(1))})
}
goodness[i] <- result[1]
}
names(goodness) <- ux[1:(nx-1)]
goodness <- goodness + parms$split.add
direction <- ux
}
list(goodness=goodness, direction=direction)
} |
NULL
ssoadmin_attach_managed_policy_to_permission_set <- function(InstanceArn, PermissionSetArn, ManagedPolicyArn) {
op <- new_operation(
name = "AttachManagedPolicyToPermissionSet",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$attach_managed_policy_to_permission_set_input(InstanceArn = InstanceArn, PermissionSetArn = PermissionSetArn, ManagedPolicyArn = ManagedPolicyArn)
output <- .ssoadmin$attach_managed_policy_to_permission_set_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$attach_managed_policy_to_permission_set <- ssoadmin_attach_managed_policy_to_permission_set
ssoadmin_create_account_assignment <- function(InstanceArn, TargetId, TargetType, PermissionSetArn, PrincipalType, PrincipalId) {
op <- new_operation(
name = "CreateAccountAssignment",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$create_account_assignment_input(InstanceArn = InstanceArn, TargetId = TargetId, TargetType = TargetType, PermissionSetArn = PermissionSetArn, PrincipalType = PrincipalType, PrincipalId = PrincipalId)
output <- .ssoadmin$create_account_assignment_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$create_account_assignment <- ssoadmin_create_account_assignment
ssoadmin_create_instance_access_control_attribute_configuration <- function(InstanceArn, InstanceAccessControlAttributeConfiguration) {
op <- new_operation(
name = "CreateInstanceAccessControlAttributeConfiguration",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$create_instance_access_control_attribute_configuration_input(InstanceArn = InstanceArn, InstanceAccessControlAttributeConfiguration = InstanceAccessControlAttributeConfiguration)
output <- .ssoadmin$create_instance_access_control_attribute_configuration_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$create_instance_access_control_attribute_configuration <- ssoadmin_create_instance_access_control_attribute_configuration
ssoadmin_create_permission_set <- function(Name, Description = NULL, InstanceArn, SessionDuration = NULL, RelayState = NULL, Tags = NULL) {
op <- new_operation(
name = "CreatePermissionSet",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$create_permission_set_input(Name = Name, Description = Description, InstanceArn = InstanceArn, SessionDuration = SessionDuration, RelayState = RelayState, Tags = Tags)
output <- .ssoadmin$create_permission_set_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$create_permission_set <- ssoadmin_create_permission_set
ssoadmin_delete_account_assignment <- function(InstanceArn, TargetId, TargetType, PermissionSetArn, PrincipalType, PrincipalId) {
op <- new_operation(
name = "DeleteAccountAssignment",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$delete_account_assignment_input(InstanceArn = InstanceArn, TargetId = TargetId, TargetType = TargetType, PermissionSetArn = PermissionSetArn, PrincipalType = PrincipalType, PrincipalId = PrincipalId)
output <- .ssoadmin$delete_account_assignment_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$delete_account_assignment <- ssoadmin_delete_account_assignment
ssoadmin_delete_inline_policy_from_permission_set <- function(InstanceArn, PermissionSetArn) {
op <- new_operation(
name = "DeleteInlinePolicyFromPermissionSet",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$delete_inline_policy_from_permission_set_input(InstanceArn = InstanceArn, PermissionSetArn = PermissionSetArn)
output <- .ssoadmin$delete_inline_policy_from_permission_set_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$delete_inline_policy_from_permission_set <- ssoadmin_delete_inline_policy_from_permission_set
ssoadmin_delete_instance_access_control_attribute_configuration <- function(InstanceArn) {
op <- new_operation(
name = "DeleteInstanceAccessControlAttributeConfiguration",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$delete_instance_access_control_attribute_configuration_input(InstanceArn = InstanceArn)
output <- .ssoadmin$delete_instance_access_control_attribute_configuration_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$delete_instance_access_control_attribute_configuration <- ssoadmin_delete_instance_access_control_attribute_configuration
ssoadmin_delete_permission_set <- function(InstanceArn, PermissionSetArn) {
op <- new_operation(
name = "DeletePermissionSet",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$delete_permission_set_input(InstanceArn = InstanceArn, PermissionSetArn = PermissionSetArn)
output <- .ssoadmin$delete_permission_set_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$delete_permission_set <- ssoadmin_delete_permission_set
ssoadmin_describe_account_assignment_creation_status <- function(InstanceArn, AccountAssignmentCreationRequestId) {
op <- new_operation(
name = "DescribeAccountAssignmentCreationStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$describe_account_assignment_creation_status_input(InstanceArn = InstanceArn, AccountAssignmentCreationRequestId = AccountAssignmentCreationRequestId)
output <- .ssoadmin$describe_account_assignment_creation_status_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$describe_account_assignment_creation_status <- ssoadmin_describe_account_assignment_creation_status
ssoadmin_describe_account_assignment_deletion_status <- function(InstanceArn, AccountAssignmentDeletionRequestId) {
op <- new_operation(
name = "DescribeAccountAssignmentDeletionStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$describe_account_assignment_deletion_status_input(InstanceArn = InstanceArn, AccountAssignmentDeletionRequestId = AccountAssignmentDeletionRequestId)
output <- .ssoadmin$describe_account_assignment_deletion_status_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$describe_account_assignment_deletion_status <- ssoadmin_describe_account_assignment_deletion_status
ssoadmin_describe_instance_access_control_attribute_configuration <- function(InstanceArn) {
op <- new_operation(
name = "DescribeInstanceAccessControlAttributeConfiguration",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$describe_instance_access_control_attribute_configuration_input(InstanceArn = InstanceArn)
output <- .ssoadmin$describe_instance_access_control_attribute_configuration_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$describe_instance_access_control_attribute_configuration <- ssoadmin_describe_instance_access_control_attribute_configuration
ssoadmin_describe_permission_set <- function(InstanceArn, PermissionSetArn) {
op <- new_operation(
name = "DescribePermissionSet",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$describe_permission_set_input(InstanceArn = InstanceArn, PermissionSetArn = PermissionSetArn)
output <- .ssoadmin$describe_permission_set_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$describe_permission_set <- ssoadmin_describe_permission_set
ssoadmin_describe_permission_set_provisioning_status <- function(InstanceArn, ProvisionPermissionSetRequestId) {
op <- new_operation(
name = "DescribePermissionSetProvisioningStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$describe_permission_set_provisioning_status_input(InstanceArn = InstanceArn, ProvisionPermissionSetRequestId = ProvisionPermissionSetRequestId)
output <- .ssoadmin$describe_permission_set_provisioning_status_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$describe_permission_set_provisioning_status <- ssoadmin_describe_permission_set_provisioning_status
ssoadmin_detach_managed_policy_from_permission_set <- function(InstanceArn, PermissionSetArn, ManagedPolicyArn) {
op <- new_operation(
name = "DetachManagedPolicyFromPermissionSet",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$detach_managed_policy_from_permission_set_input(InstanceArn = InstanceArn, PermissionSetArn = PermissionSetArn, ManagedPolicyArn = ManagedPolicyArn)
output <- .ssoadmin$detach_managed_policy_from_permission_set_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$detach_managed_policy_from_permission_set <- ssoadmin_detach_managed_policy_from_permission_set
ssoadmin_get_inline_policy_for_permission_set <- function(InstanceArn, PermissionSetArn) {
op <- new_operation(
name = "GetInlinePolicyForPermissionSet",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$get_inline_policy_for_permission_set_input(InstanceArn = InstanceArn, PermissionSetArn = PermissionSetArn)
output <- .ssoadmin$get_inline_policy_for_permission_set_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$get_inline_policy_for_permission_set <- ssoadmin_get_inline_policy_for_permission_set
ssoadmin_list_account_assignment_creation_status <- function(InstanceArn, MaxResults = NULL, NextToken = NULL, Filter = NULL) {
op <- new_operation(
name = "ListAccountAssignmentCreationStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$list_account_assignment_creation_status_input(InstanceArn = InstanceArn, MaxResults = MaxResults, NextToken = NextToken, Filter = Filter)
output <- .ssoadmin$list_account_assignment_creation_status_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$list_account_assignment_creation_status <- ssoadmin_list_account_assignment_creation_status
ssoadmin_list_account_assignment_deletion_status <- function(InstanceArn, MaxResults = NULL, NextToken = NULL, Filter = NULL) {
op <- new_operation(
name = "ListAccountAssignmentDeletionStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$list_account_assignment_deletion_status_input(InstanceArn = InstanceArn, MaxResults = MaxResults, NextToken = NextToken, Filter = Filter)
output <- .ssoadmin$list_account_assignment_deletion_status_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$list_account_assignment_deletion_status <- ssoadmin_list_account_assignment_deletion_status
ssoadmin_list_account_assignments <- function(InstanceArn, AccountId, PermissionSetArn, MaxResults = NULL, NextToken = NULL) {
op <- new_operation(
name = "ListAccountAssignments",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$list_account_assignments_input(InstanceArn = InstanceArn, AccountId = AccountId, PermissionSetArn = PermissionSetArn, MaxResults = MaxResults, NextToken = NextToken)
output <- .ssoadmin$list_account_assignments_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$list_account_assignments <- ssoadmin_list_account_assignments
ssoadmin_list_accounts_for_provisioned_permission_set <- function(InstanceArn, PermissionSetArn, ProvisioningStatus = NULL, MaxResults = NULL, NextToken = NULL) {
op <- new_operation(
name = "ListAccountsForProvisionedPermissionSet",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$list_accounts_for_provisioned_permission_set_input(InstanceArn = InstanceArn, PermissionSetArn = PermissionSetArn, ProvisioningStatus = ProvisioningStatus, MaxResults = MaxResults, NextToken = NextToken)
output <- .ssoadmin$list_accounts_for_provisioned_permission_set_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$list_accounts_for_provisioned_permission_set <- ssoadmin_list_accounts_for_provisioned_permission_set
ssoadmin_list_instances <- function(MaxResults = NULL, NextToken = NULL) {
op <- new_operation(
name = "ListInstances",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$list_instances_input(MaxResults = MaxResults, NextToken = NextToken)
output <- .ssoadmin$list_instances_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$list_instances <- ssoadmin_list_instances
ssoadmin_list_managed_policies_in_permission_set <- function(InstanceArn, PermissionSetArn, MaxResults = NULL, NextToken = NULL) {
op <- new_operation(
name = "ListManagedPoliciesInPermissionSet",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$list_managed_policies_in_permission_set_input(InstanceArn = InstanceArn, PermissionSetArn = PermissionSetArn, MaxResults = MaxResults, NextToken = NextToken)
output <- .ssoadmin$list_managed_policies_in_permission_set_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$list_managed_policies_in_permission_set <- ssoadmin_list_managed_policies_in_permission_set
ssoadmin_list_permission_set_provisioning_status <- function(InstanceArn, MaxResults = NULL, NextToken = NULL, Filter = NULL) {
op <- new_operation(
name = "ListPermissionSetProvisioningStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$list_permission_set_provisioning_status_input(InstanceArn = InstanceArn, MaxResults = MaxResults, NextToken = NextToken, Filter = Filter)
output <- .ssoadmin$list_permission_set_provisioning_status_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$list_permission_set_provisioning_status <- ssoadmin_list_permission_set_provisioning_status
ssoadmin_list_permission_sets <- function(InstanceArn, NextToken = NULL, MaxResults = NULL) {
op <- new_operation(
name = "ListPermissionSets",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$list_permission_sets_input(InstanceArn = InstanceArn, NextToken = NextToken, MaxResults = MaxResults)
output <- .ssoadmin$list_permission_sets_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$list_permission_sets <- ssoadmin_list_permission_sets
ssoadmin_list_permission_sets_provisioned_to_account <- function(InstanceArn, AccountId, ProvisioningStatus = NULL, MaxResults = NULL, NextToken = NULL) {
op <- new_operation(
name = "ListPermissionSetsProvisionedToAccount",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$list_permission_sets_provisioned_to_account_input(InstanceArn = InstanceArn, AccountId = AccountId, ProvisioningStatus = ProvisioningStatus, MaxResults = MaxResults, NextToken = NextToken)
output <- .ssoadmin$list_permission_sets_provisioned_to_account_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$list_permission_sets_provisioned_to_account <- ssoadmin_list_permission_sets_provisioned_to_account
ssoadmin_list_tags_for_resource <- function(InstanceArn, ResourceArn, NextToken = NULL) {
op <- new_operation(
name = "ListTagsForResource",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$list_tags_for_resource_input(InstanceArn = InstanceArn, ResourceArn = ResourceArn, NextToken = NextToken)
output <- .ssoadmin$list_tags_for_resource_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$list_tags_for_resource <- ssoadmin_list_tags_for_resource
ssoadmin_provision_permission_set <- function(InstanceArn, PermissionSetArn, TargetId = NULL, TargetType) {
op <- new_operation(
name = "ProvisionPermissionSet",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$provision_permission_set_input(InstanceArn = InstanceArn, PermissionSetArn = PermissionSetArn, TargetId = TargetId, TargetType = TargetType)
output <- .ssoadmin$provision_permission_set_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$provision_permission_set <- ssoadmin_provision_permission_set
ssoadmin_put_inline_policy_to_permission_set <- function(InstanceArn, PermissionSetArn, InlinePolicy) {
op <- new_operation(
name = "PutInlinePolicyToPermissionSet",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$put_inline_policy_to_permission_set_input(InstanceArn = InstanceArn, PermissionSetArn = PermissionSetArn, InlinePolicy = InlinePolicy)
output <- .ssoadmin$put_inline_policy_to_permission_set_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$put_inline_policy_to_permission_set <- ssoadmin_put_inline_policy_to_permission_set
ssoadmin_tag_resource <- function(InstanceArn, ResourceArn, Tags) {
op <- new_operation(
name = "TagResource",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$tag_resource_input(InstanceArn = InstanceArn, ResourceArn = ResourceArn, Tags = Tags)
output <- .ssoadmin$tag_resource_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$tag_resource <- ssoadmin_tag_resource
ssoadmin_untag_resource <- function(InstanceArn, ResourceArn, TagKeys) {
op <- new_operation(
name = "UntagResource",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$untag_resource_input(InstanceArn = InstanceArn, ResourceArn = ResourceArn, TagKeys = TagKeys)
output <- .ssoadmin$untag_resource_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$untag_resource <- ssoadmin_untag_resource
ssoadmin_update_instance_access_control_attribute_configuration <- function(InstanceArn, InstanceAccessControlAttributeConfiguration) {
op <- new_operation(
name = "UpdateInstanceAccessControlAttributeConfiguration",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$update_instance_access_control_attribute_configuration_input(InstanceArn = InstanceArn, InstanceAccessControlAttributeConfiguration = InstanceAccessControlAttributeConfiguration)
output <- .ssoadmin$update_instance_access_control_attribute_configuration_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$update_instance_access_control_attribute_configuration <- ssoadmin_update_instance_access_control_attribute_configuration
ssoadmin_update_permission_set <- function(InstanceArn, PermissionSetArn, Description = NULL, SessionDuration = NULL, RelayState = NULL) {
op <- new_operation(
name = "UpdatePermissionSet",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .ssoadmin$update_permission_set_input(InstanceArn = InstanceArn, PermissionSetArn = PermissionSetArn, Description = Description, SessionDuration = SessionDuration, RelayState = RelayState)
output <- .ssoadmin$update_permission_set_output()
config <- get_config()
svc <- .ssoadmin$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.ssoadmin$operations$update_permission_set <- ssoadmin_update_permission_set |
takefeaturecolumns<-function(sam,feat){
featuretrain = subset(sam, select=c('classification'))
feat<-feat[feat!='classification']
for (i in 1:(length(feat))){
row=feat[i]
featuretrain[row]<-sam[row]
}
featuretrain
}
nextbestfeature<-function(model,trainingsam,testsam,featuresleft,ongoingfeatures){
training<-takefeaturecolumns(trainingsam,union(featuresleft,ongoingfeatures))
test<-takefeaturecolumns(testsam,union(featuresleft,ongoingfeatures))
maxaccuracy<-0
maxfeat<-utils::head(featuresleft,1)
for (feat in featuresleft){
feat_trainingsample<-takefeaturecolumns(trainingsam,append(ongoingfeatures,feat))
feat_testsample<-takefeaturecolumns(testsam,append(ongoingfeatures,feat))
featresults<-model(feat_trainingsample,feat_testsample)
feataccuracy<-featresults$training
if (maxaccuracy<=feataccuracy){
maxaccuracy<-feataccuracy
max_train<-featresults$training
max_test<- featresults$test
max_testsens<-featresults$testsensitivity
max_testspec<-featresults$testspecificity
max_trainsens<-featresults$trainsensitivity
max_trainspec<-featresults$trainspecificity
maxfeat<-feat
}
}
return_list <- list("feature" = maxfeat, "training_accuracy" = max_train,"test_accuracy"= max_test,"trainsens"=max_trainsens,"testsens"=max_testsens,"trainspec"=max_trainspec,"testspec"=max_testspec)
return(return_list)
}
beforeandafter<-function(vect,centre,places,threshold){
flag<-FALSE
for (i in 1:places){
if (centre+i<length(vect) & (abs(vect[centre]-vect[centre-i])>threshold || abs(vect[centre]-vect[centre+i])>threshold)){
flag<-TRUE
}
else if (centre+i>=length(vect) & abs(vect[centre]-vect[centre-i])>threshold){
flag<-TRUE
}
}
flag
}
forwardfeatureselection <-function(model=feamiR::svmlinear,training,test,featurelist,includePlot=FALSE){
ongoing<-c()
featureaccuracy<-data.frame(matrix(nrow=length(featurelist), ncol = 0))
i<-1
while (i<=length(featurelist)){
b<-nextbestfeature(model,training,test,featurelist[!featurelist %in% ongoing],ongoing)
ongoing<-c(ongoing,b$feature)
featureaccuracy[i,'training_accuracy']<-b$training_accuracy
featureaccuracy[i,'test_accuracy']<-b$test_accuracy
featureaccuracy[i,'accuracy']<-b$training_accuracy
featureaccuracy[i,'number of features']<-i
featureaccuracy[i,'test_specificity']<-b$testspec
featureaccuracy[i,'train_specificity']<-b$trainspec
featureaccuracy[i,'test_sensitivity']<-b$testsens
featureaccuracy[i,'train_sensitivity']<-b$trainsens
i<-i+1
}
x<-featureaccuracy$'number of features'
y<-featureaccuracy$accuracy
if (length(x)<=5){
loess30 = suppressWarnings(stats::loess(y ~ x, degree = 1, span = 0.5))
}
else{
loess30<-suppressWarnings(stats::loess(y ~ x,degree=1,span=0.2))}
y1 <- stats::predict(loess30,newdata=x,se=FALSE)
flag<-TRUE
i<-3
numfeat<-length(x)
while (i<=length(x) & flag==TRUE){
if (length(x)<20 & i>3){
flag<-beforeandafter(y1,i,3,0.01)
}
else {
if (i>5){
flag<-beforeandafter(y1,i,5,0.01)
}
}
if (!flag){numfeat<-x[i]}
i<-i+1
}
y2_<-featureaccuracy$test_accuracy
loess30_2<-suppressWarnings(stats::loess(y2_ ~ x,degree=1,span=0.2))
y2 <- stats::predict(loess30_2,newdata=x,se=FALSE)
y4_<-featureaccuracy$training_accuracy
loess30_4<-suppressWarnings(stats::loess(y4_ ~ x,degree=1,span=0.2))
y4 <- stats::predict(loess30_4,newdata=x,se=FALSE)
if (includePlot == TRUE){
graphics::plot(utils::head(x,numfeat),utils::head(y,numfeat),col='red',main='Number of Features Against Accuracy up to Plateau',xlab='Number of features',ylab='Accuracy',ylim=c(0:1),type='b') + graphics::text(utils::head(x,numfeat), utils::head(y1,numfeat), utils::head(ongoing,numfeat), cex=0.6, pos=4,adj=0.5, col="red",srt=90)
graphics::points(utils::head(x,numfeat),utils::head(y2_,numfeat),col='green')
graphics::lines(utils::head(x,numfeat),utils::head(y1,numfeat),col='red')
graphics::lines(utils::head(x,numfeat),utils::head(y2,numfeat),col='green')}
return_list <- list("feature_list" = utils::head(ongoing,numfeat), "accuracy" = y1[numfeat],"testacc"=featureaccuracy$test_accuracy[numfeat],"trainacc"=featureaccuracy$training_accuracy[numfeat],"trainsens"=featureaccuracy$train_sensitivity[numfeat],"trainspec"=featureaccuracy$train_specificity[numfeat],"testsens"=featureaccuracy$test_sensitivity[numfeat],"testspec"=featureaccuracy$test_specificity[numfeat])
return(return_list)
} |
checkDir <- function(dir, errors = NULL) {
if (!dir.exists(dir)) {
errors <- c(errors, "
} else {
if (length(dir) > 1) {
errors <- c(errors, "
}
}
return(errors)
}
checkReads <- function(reads, errors = NULL) {
if (!is.data.frame(reads)) {
errors <- c(errors, paste0("
}
if (dim(reads)[2] > 2) {
errors <- c(errors, paste0("
} else {
if (dim(reads)[2] == 2) {
if (sum(names(reads) == c("read_count", "barcode")) != 2) {
errors <- c(errors, "
}
}
}
return(errors)
}
checkBackbone <- function(backbone, errors = NULL) {
if (backbone != "not defined") {
if (backbone != "none") {
if (!is.character(backbone)) {
errors <- c(errors, paste0("
}
if (length(backbone) > 1) {
errors <- c(errors, "
} else {
elements <- strsplit(backbone, split = "") %>% unlist %>% table %>% as.data.frame(stringsAsFactors = TRUE)
IUPAC_nucCode <- c("A", "C", "G", "T", "U", "R", "Y", "S", "W", "K", "M", "B", "D", "H", "V", "N", ".", "-")
if (sum(!as.character(elements[, 1]) %in% IUPAC_nucCode) != 0) {
errors <- c(errors, "
}
}
}
}
return(errors)
}
checkLabel <- function(label, errors = NULL) {
if (length(label) != 1) {
errors <- c(errors, "
}
if (!is.character(label)) {
errors <- c(errors, paste0("
}
return(errors)
}
checkBarcodeData <- function(object) {
errors <- character()
errors <- checkReads(object@reads, errors)
errors <- checkBackbone(object@BC_backbone, errors)
errors <- checkDir(object@results_dir, errors)
errors <- checkLabel(object@label, errors)
if (length(errors) == 0) TRUE else errors
}
BCdat <- methods::setClass("BCdat",
slots = list(
reads = "data.frame",
results_dir = "character",
label = "character",
BC_backbone = "character"
),
prototype = list(
reads = data.frame(read_count = NA_integer_, barcode = NA_character_),
results_dir = NA_character_,
label = NA_character_,
BC_backbone = NA_character_
),
validity = checkBarcodeData
)
setMethod("show", signature = c("BCdat"),
definition = function(object){
len <- 45
cat(" class: BCdat\n\n")
cat(" number of barcode sequences:", dim(object@reads)[1], "\n")
if (sum(dim(object@reads)) > 1) {
cat(" read count distribution: min", min(object@reads$read_count),
" mean", round(mean(object@reads$read_count), digits = 2),
" median", stats::median(object@reads$read_count),
" max", max(object@reads$read_count), "\n")
l <- sort(unique(nchar(as.character(object@reads$barcode))))
if (length(l) == 1) {
cat(" barcode sequence length:", l[1], "\n")
}
if (length(l) == 2) {
cat(" barcode sequence lengths: ", l[1], ", ", l[2], "\n")
}
if (length(l) == 3) {
cat(" barcode sequence lengths: ", l[1], ", ", l[2], ", ", l[3], "\n")
}
if (length(l) > 3) {
cat(" barcode sequence lengths: ", l[1], ", ", l[2], ", ", l[3], ", ...", l[length(l)], "\n")
}
cat("\n")
cat(" barcode read counts:\n")
if (dim(object@reads)[1] > 10) {
if (sum(l > (len + 3)) > 0) {
seqs <- lapply(as.character(object@reads[1:10, 2]), function(x) {
ind <- x %>% nchar %>% -len
tmp_seq <- (strsplit(x, split = "") %>% unlist)[c(1:round(len/2), (round(len/2) + ind):nchar(x))]
paste0(paste0(tmp_seq[1:round(len/2)], collapse = ""),
"...",
paste0(tmp_seq[(round(len/2)+1):length(tmp_seq)], collapse = ""),
collapse = "")
}) %>% unlist
print(data.frame(read_count = object@reads[1:10, 1],
barcode = seqs, stringsAsFactors = TRUE), row.names = FALSE)
} else {
print(object@reads[1:10, ], row.names = FALSE)
}
cat(" ...")
} else {
if (sum(l > (len + 3)) > 0) {
seqs <- lapply(as.character(object@reads[, 2]), function(x) {
ind <- x %>% nchar %>% -len
tmp_seq <- (strsplit(x, split = "") %>% unlist)[c(1:round(len/2), (round(len/2) + ind):nchar(x))]
paste0(paste0(tmp_seq[1:round(len/2)], collapse = ""),
"...",
paste0(tmp_seq[(round(len/2)+1):length(tmp_seq)], collapse = ""), collapse = "")
}) %>% unlist
print(data.frame(read_count = object@reads[, 1],
barcode = seqs, stringsAsFactors = TRUE), row.names = FALSE)
} else {
print(object@reads[, ], row.names = FALSE)
}
}
}
cat("\n")
cat(" results dir: \n")
cat(" ", object@results_dir, "\n")
cat(" barcode backbone: \n")
cat(" ", object@BC_backbone, "\n")
cat(" label: \n")
cat(" ", object@label, "\n")
}
) |
data_simu <-
function(n,N,eta_star,q)
{
sigma_u=1
P=runif(N,0.1,0.5)
W=matrix(0,n,N)
for(j in 1:N)
{ W[,j]=rbinom(n,2,P[j])}
nb_comp_non_zero=q*N
sigma_e=sqrt(q*N*sigma_u^2*(1-eta_star)/eta_star)
b=sample(1:N,nb_comp_non_zero)
a1=sort(b)
u=rnorm(nb_comp_non_zero,0,sigma_u)
e=rnorm(n,0,sigma_e)
U=matrix(0,N)
U[a1]=u
Z=scale(W,center=TRUE,scale=TRUE)
Y=Z%*%U + e
list(W=W,Y=Y)
} |
transitiveweights <- function(m,ties.f=pmin,combine.f=max,compare.f=min) sum(unlist(sapply(1:nrow(m),function(i) sapply(1:nrow(m),function(j) if(j==i) 0 else compare.f(m[i,j],combine.f(ties.f(m[i,-c(j,i)], m[-c(i,j),j])))))))
cyclicalweights <- function(m,ties.f=pmin,combine.f=max,compare.f=min) sum(unlist(sapply(1:nrow(m),function(i) sapply(1:nrow(m),function(j) if(j==i) 0 else compare.f(m[j,i],combine.f(ties.f(m[i,-c(j,i)], m[-c(i,j),j])))))))
pgeomean <- function(x,y) sqrt(x*y)
summary.call <- function(y)
summary(y
~ transitiveweights("min","max","min")
+ transitiveweights("min","sum","min")
+ transitiveweights("geomean","sum","geomean")
+ cyclicalweights("min","max","min")
+ cyclicalweights("min","sum","min")
+ cyclicalweights("geomean","sum","geomean"),
response="w")
simulate.call <- function(y)
simulate(y
~ transitiveweights("min","max","min")
+ transitiveweights("min","sum","min")
+ transitiveweights("geomean","sum","geomean")
+ cyclicalweights("min","max","min")
+ cyclicalweights("min","sum","min")
+ cyclicalweights("geomean","sum","geomean"),
coef=rep(0,6),reference=~DiscUnif(0,4),response="w",control=control.simulate(MCMC.burnin=0,MCMC.interval=100),nsim=100,output="ergm_state")
test_that("valued triadic effects in undirected networks", {
y <- network.initialize(20, dir=FALSE)
y %ergmlhs% "response" <- "w"
y <- simulate(y~sum,coef=0,reference=~DiscUnif(0,4),control=control.simulate(MCMC.burnin=1000),nsim=1)
y.summ <- summary.call(y)
y.m <- as.matrix(y, a="w")
expect_equivalent(y.summ[1], transitiveweights(y.m, pmin, max, min)/2)
expect_equivalent(y.summ[2], transitiveweights(y.m, pmin, sum, min)/2)
expect_equivalent(y.summ[3], transitiveweights(y.m, pgeomean, sum, pgeomean)/2)
expect_equivalent(y.summ[4], cyclicalweights(y.m, pmin, max, min)/2)
expect_equivalent(y.summ[5], cyclicalweights(y.m, pmin, sum, min)/2)
expect_equivalent(y.summ[6], cyclicalweights(y.m, pgeomean, sum, pgeomean)/2)
y.sim <- simulate.call(y)
s_results <- t(sapply(y.sim, summary.call))
d_results <- attr(y.sim,"stats")
expect_equivalent(s_results,as.matrix(d_results))
})
test_that("valued triadic effects in directed networks", {
y <- network.initialize(20, dir=TRUE)
y <- simulate(y~sum,coef=0,reference=~DiscUnif(0,4),response="w",control=control.simulate(MCMC.burnin=1000),nsim=1)
y.summ <- summary.call(y)
y.m <- as.matrix(y, a="w")
expect_equivalent(y.summ[1], transitiveweights(y.m, pmin, max, min))
expect_equivalent(y.summ[2], transitiveweights(y.m, pmin, sum, min))
expect_equivalent(y.summ[3], transitiveweights(y.m, pgeomean, sum, pgeomean))
expect_equivalent(y.summ[4], cyclicalweights(y.m, pmin, max, min))
expect_equivalent(y.summ[5], cyclicalweights(y.m, pmin, sum, min))
expect_equivalent(y.summ[6], cyclicalweights(y.m, pgeomean, sum, pgeomean))
y.sim <- simulate.call(y)
s_results <- t(sapply(y.sim, summary.call))
d_results <- attr(y.sim,"stats")
expect_equivalent(s_results,as.matrix(d_results))
}) |
includeChapter <- 1:7 %in% (1:7)
includeApp <- 1:4 %in% 1:3
require(MASS)
require(Matrix)
require(fastR2)
require(mosaic)
theme_set(theme_bw())
require(knitr)
require(xtable)
options(xtable.floating = FALSE)
opts_knit$set(width=74)
opts_knit$set(self.contained=FALSE)
opts_chunk$set(
digits = 3,
dev="pdf",
dev.args=list(colormodel="cmyk"),
comment="
prompt=FALSE,
size="small",
cache=TRUE,
cache.path='cache/c-',
cache.lazy=FALSE,
tidy=FALSE,
fig.width=8*.45,
fig.height=6*.45,
fig.show="hold",
fig.align="center",
out.width=".47\\textwidth",
boxedLabel=TRUE
)
opts_template$set(fig3 = list(fig.height = 7*.40, fig.width = 8*.40, out.width=".31\\textwidth"))
opts_template$set(figtall = list(fig.height = 8*.45, fig.width = 8*.45, out.width=".47\\textwidth"))
opts_template$set(fig1 = list(fig.height = 3*0.9, fig.width = 8 * 0.9, out.width=".95\\textwidth"))
opts_template$set(figbig = list(fig.height = 9*0.9, fig.width = 12*0.9, out.width=".95\\textwidth"))
knit_hooks$set(seed = function(before, options, envir) {
if (before) set.seed(options$seed)
})
knit_hooks$set(digits = function(before, options, envir) {
if (before) {
options(digits = options$digits)
} else {
options(digits = 3)
}
})
knit_hooks$set(
document = function(x) {
sub('\\usepackage[]{color}', '\\usepackage{xcolor}', x, fixed = TRUE)
gsub(
"\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}",
"\\definecolor{shadecolor}{gray}{0.8}", x, fixed = TRUE)
}
)
knit_hooks$set(chunk = function (x, options) {
if ( !is.null(options$boxedLabel) && options$boxedLabel &&
! grepl("unnamed-chunk", options$label) &&
(is.null(options$echo) || options$echo) ) {
labeling <- paste0(
"\\endgraf\\nobreak\\null\\endgraf\\penalty-2\\kern-.5\\baselineskip",
"\n\n",
"\\hfill \\makebox[0pt][r]{\\fbox{\\tiny ",
options$label,
"}}",
"\\endgraf",
"\\kern-4.5ex\n\n")
} else {
labeling <- ""
}
ai = knitr:::output_asis(x, options)
col = if (!ai)
paste(knitr:::color_def(options$background),
if (!knitr:::is_tikz_dev(options)) "\\color{fgcolor}",
sep = "")
k1 = paste(col, "\\begin{kframe}\n", sep = "")
k2 = "\\end{kframe}"
x = knitr:::.rm.empty.envir(paste(k1, labeling, x, k2, sep = ""))
size = if (options$size == "normalsize")
""
else sprintf("\\%s", options$size)
if (!ai)
x = sprintf("\\begin{knitrout}%s\n%s\n\\end{knitrout}",
size, x)
if (options$split) {
name = knitr:::fig_path(".tex", options)
if (!file.exists(dirname(name)))
dir.create(dirname(name))
cat(x, file = name)
sprintf("\\input{%s}", name)
}
else x
}
)
blackAndWhite = TRUE
fastRlty = rep(1,20)
fastRlty = c(1,2,5,6,1,2,5,6,1,2,5,6)
trellis.par.set(theme=col.whitebg())
trellis.par.set(theme=col.fastR())
options(continue=" ")
options(str = strOptions(strict.width = "wrap"))
options(show.signif.stars=FALSE)
options(digits=3) |
makeAA <- function(pedigree)
{
A <- makeA(pedigree)
AA <- A*A
logDet <- determinant(AA, logarithm = TRUE)$modulus[1]
AAinv <- solve(AA)
AAinv@Dimnames <- list(as.character(pedigree[, 1]), NULL)
listAAinv <- sm2list(AAinv, rownames=pedigree[,1], colnames=c("row", "column", "AAinverse"))
return(list(AA = AA, logDet = logDet, AAinv = AAinv, listAAinv = listAAinv))
} |
rec_pattern <- function(from, to, width = 5, other = NULL){
rec.pat <- c()
rec.labels <- c()
values <- seq(from, to + width, by = width)
for (x in seq_len(length(values) - 1)) {
rec.pat <- paste0(rec.pat,
sprintf("%i:%i=%i", values[x], values[x + 1] - 1, x),
sep = ";")
rec.labels <- c(rec.labels, sprintf("%i-%i", values[x], values[x + 1] - 1))
}
if (!is.null(other) && !sjmisc::is_empty(other))
rec.pat <- paste0(rec.pat, "else=", other, sep = "")
names(rec.labels) <- seq_len(length(values) - 1)
list(pattern = rec.pat, labels = rec.labels)
} |
svmfs <- function (x, ...)
UseMethod ("svmfs")
`svmfs.default` <-
function(x,y,
fs.method = c("scad", "1norm", "scad+L2", "DrHSVM"),
grid.search=c("interval","discrete"),
lambda1.set=NULL,
lambda2.set=NULL,
bounds=NULL,
parms.coding= c("log2","none"),
maxevals=500,
inner.val.method = c("cv", "gacv"),
cross.inner= 5,
show= c("none", "final"),
calc.class.weights=FALSE,
class.weights=NULL,
seed=123,
maxIter=700,
verbose=TRUE,
...){
print("grid search")
print(grid.search)
print("show")
print(show)
possible.fs<-c("1norm", "scad", "scad+L2", "DrHSVM")
nn<-length(y)
nlevels.class<- nlevels(as.factor(y))
levels.class <- levels(as.factor(y))
if (!all((levels(factor(y)) == c("-1","1"))) ) stop ("labels y should be -1 and 1.")
if (fs.method == "1norm" & inner.val.method == "gacv" ) stop("gacv is not availible for 1norm SVM. Use k fold cv instead.")
if (grid.search=="interval"){
if ((fs.method %in% c("scad", "1norm" )) & is.null(bounds)){
bounds=t(data.frame(log2lambda1=c(-10, 10)))
colnames(bounds)<-c("lower", "upper")
}
if (fs.method %in% c("DrHSVM") & is.null(bounds)){
bounds=t(data.frame(log2lambda2=c(-10, 10)))
colnames(bounds)<-c("lower", "upper")
}
if (fs.method %in% c("scad+L2") & is.null(bounds)){
bounds=t(data.frame(log2lambda1=c(-10, 10), log2lambda2=c(-10,10)))
colnames(bounds)<-c("lower", "upper")
}
if (calc.class.weights){
class.weights = 100/ table(y)
}else class.weights = NULL
}
possible.inner.val.method<-c("gacv", "cv")
if (! (inner.val.method %in% possible.inner.val.method )) stop(paste("You have to use one of following (inner) validation methods:",
paste(possible.inner.val.method, collapse=", ")))
if (! (fs.method %in% possible.fs )) stop(paste("You have to use one of following fecture selection methods:",
paste(possible.fs, collapse=", ")))
print(paste("feature selection method is", fs.method))
if (!is.null(seed)) set.seed(seed)
if (grid.search=="interval") {
model<-.run.interval(x=x,y=y, fs.method=fs.method, bounds=bounds,parms.coding=parms.coding,
class.weights=class.weights, maxevals=maxevals, seed=seed,
maxIter=maxIter, show=show, inner.val.method=inner.val.method, cross.inner=cross.inner, verbose=verbose)
}
if (grid.search=="discrete") {
model<-.run.discrete(x=x,y=y, fs.method=fs.method,
lambda1.set=lambda1.set,
lambda2.set=lambda2.set,
parms.coding=parms.coding,
class.weights=class.weights,
maxevals=maxevals,
seed=seed,
maxIter=maxIter,
show=show,
inner.val.method=inner.val.method,
cross.inner=cross.inner,
verbose=verbose)
}
rv <- list(classes=as.factor(y),
sample.names = names(y),
class.method=paste("svm",fs.method ),
grid.search=grid.search,
seed = seed,
model =model,
lambda1.set=lambda1.set,
lambda2.set=lambda2.set,
bounds=bounds,
inner.val.method = inner.val.method,
cross.inner= cross.inner )
if (inner.val.method != "cv") rv$cross.inner =NULL
class(rv) <- "penSVM"
return(rv)
} |
vapoRwave_palette <- c(
"
,"
,"
,"
,"
,"
,"
,"
,"
,"
,"
)
NULL
vapoRwave_pal <- function(){
scales::manual_pal(vapoRwave_palette)
}
scale_colour_vapoRwave <- function(...) {
ggplot2::discrete_scale("colour", "vapoRwave", vapoRwave_pal(), ...)
}
scale_color_vapoRwave <- scale_colour_vapoRwave
scale_fill_vapoRwave <- function(...) {
ggplot2::discrete_scale('fill', 'vapoRwave', vapoRwave_pal(), ...)
} |
compute.fa2<-function(Y, X,verbose=F){
Xtemp <- X
Ytemp <- Y
if(length(Y)!=length(X)){stop("Input vectors are of different length !!!")}
lengthNAX <- sum(is.na(X))
if(lengthNAX > 0){warning(paste("Vector of true values contains ", lengthNAX, " NA !!! NA excluded", sep = ""))}
lengthNAY <- sum(is.na(Y))
if(lengthNAY > 0){warning(paste("Vector of imputed values contains ", lengthNAY, " NA !!! NA excluded", sep = ""))}
Xtemp <- X[which(!is.na(X)&!is.na(Y))]
Ytemp <- Y[which(!is.na(X)&!is.na(Y))]
id0XY <- which(X==0&Y==0)
Xtemp[id0XY] <- 1
Ytemp[id0XY] <- 1
ratio <- (Ytemp/Xtemp)
fraction <- ratio[ratio>=0.5 & ratio<=2]
FA2 <- length(fraction)/length(ratio)
if (verbose){
if(FA2>0.8) {print(" Good model")
}else{print("Important number of different points")}
}
out<-FA2
return(out)
} |
test_that("Coercion from other date classes into messydt works", {
date <- as.Date("2010-10-10")
POSIXct <- as.POSIXct("2010-10-20 CEST")
POSIXlt <- as.POSIXlt("2010-10-15 CEST")
character <- "2010-10-10"
messy <- as_messydate("2010-10-10..2010-10-20")
negative <- as_messydate("28 BC")
expect_equal(as.Date(messy, min), date)
expect_equal(as.POSIXct(messy, max), POSIXct)
expect_equal(as.POSIXlt(messy, median), POSIXlt)
expect_equal(as.Date(negative, min), as.Date("0028-01-01"))
}) |
context("h2o")
skip_on_cran()
library(h2o)
h2o.init()
h2o.no_progress()
test_that("H2OBinomialClassification: lime explanation only produces one entry per case and feature", {
path <- system.file("extdata", "prostate.csv", package = "h2o")
df_h2o <- h2o.importFile(path)
df_h2o$CAPSULE <- h2o::as.factor(df_h2o$CAPSULE)
df_h2o$RACE <- h2o::as.factor(df_h2o$RACE)
df_h2o$DCAPS <- h2o::as.factor(df_h2o$DCAPS)
df_h2o$DPROS <- h2o::as.factor(df_h2o$DPROS)
df_h2o$ID <- NULL
predictors <- c("AGE", "RACE", "VOL", "GLEASON")
response <- "CAPSULE"
model.rf <- h2o.randomForest(x = predictors, y = response, training_frame = df_h2o, ntrees = 50, stopping_rounds = 2)
expect_s4_class(model.rf, "H2OBinomialModel")
explainer <- lime(as.data.frame(df_h2o), model = model.rf)
expect_s3_class(explainer, "data_frame_explainer")
explanation <- lime::explain(as.data.frame(df_h2o[1,]), explainer, n_labels = 1, n_features = 1, kernel_width = 0.5)
expect_equal(nrow(explanation), 1)
})
test_that("H2OMultinomialClassification: lime explanation only produces one entry per case and feature", {
path <- system.file("extdata", "iris.csv", package = "h2o")
df_h2o <- h2o.importFile(path)
df_h2o$C5 <- h2o::as.factor(df_h2o$C5)
response <- "C5"
predictors <- base::setdiff(names(df_h2o), response)
model.rf <- h2o.randomForest(x = predictors, y = response, training_frame = df_h2o, ntrees = 50, stopping_rounds = 2)
expect_s4_class(model.rf, "H2OMultinomialModel")
explainer <- lime(as.data.frame(df_h2o), model = model.rf)
expect_s3_class(explainer, "data_frame_explainer")
explanation <- lime::explain(as.data.frame(df_h2o[1,]), explainer, n_labels = 1, n_features = 1, kernel_width = 0.5)
expect_equal(nrow(explanation), 1)
})
test_that("H2ORegression: lime explanation only produces one entry per case and feature", {
path <- system.file("extdata", "australia.csv", package = "h2o")
df_h2o <- h2o.importFile(path)
response <- "premax"
predictors <- base::setdiff(names(df_h2o), response)
model.rf <- h2o.randomForest(x = predictors, y = response, training_frame = df_h2o, ntrees = 50, stopping_rounds = 2)
expect_s4_class(model.rf, "H2ORegressionModel")
explainer <- lime(as.data.frame(df_h2o), model = model.rf)
expect_s3_class(explainer, "data_frame_explainer")
explanation <- lime::explain(as.data.frame(df_h2o[1,]), explainer, n_features = 1, kernel_width = 0.5)
expect_equal(nrow(explanation), 1)
}) |
library(hamcrest)
test.stringparams <- function() {
import(org.renjin.invocation.StringParams)
strParms <- StringParams$new()
assertThat(strParms$concatString("Hello ", "World"), equalTo("Hello World"))
}
test.charseq <- function() {
import(org.renjin.invocation.StringParams)
strParms <- StringParams$new()
assertThat(strParms$concatCharSeq("Hello ", "World2"), equalTo("Hello World2"))
} |
tr <-
function(x)
{
if (dim(x)[1] != dim(x)[2] ) {
return(NA)
} else {
return(sum(diag(x)))
}
invisible()
} |
ConstModVar <- R6::R6Class(
classname = "ConstModVar",
lock_class = TRUE,
inherit = ModVar,
private = list(
),
public = list(
initialize = function(description, units, const) {
D <- DiracDistribution$new(const)
super$initialize(description, units, D, k=as.integer(1))
return(invisible(self))
},
is_probabilistic = function() {
return(FALSE)
}
)
) |
out_1 <- poped_optimize(poped.db,opt_a=1,
bUseExchangeAlgorithm=1,
EAStepSize=25,out_file = "")
\dontrun{
out_2 <- poped_optimize(poped.db,opt_xt=1,
bUseExchangeAlgorithm=1,
EAStepSize=1)
get_rse(out_2$fmf,out_2$poped.db)
plot_model_prediction(out_2$poped.db)
dsl <- downsizing_general_design(poped.db)
output <- mfea(poped.db,
model_switch=dsl$model_switch,
ni=dsl$ni,
xt=dsl$xt,
x=dsl$x,
a=dsl$a,
bpopdescr=dsl$bpop,
ddescr=dsl$d,
maxxt=dsl$maxxt,
minxt=dsl$minxt,
maxa=dsl$maxa,
mina=dsl$mina,
fmf=0,dmf=0,
EAStepSize=1,
opt_xt=1)
} |
library(testthat)
test_that("autotest", {
autotest_sdistribution(
sdist = Loglogistic,
pars = list(shape = 2, scale = 3),
traits = list(
valueSupport = "continuous",
variateForm = "univariate",
type = PosReals$new(zero = TRUE)
),
support = PosReals$new(zero = TRUE),
symmetry = "asymmetric",
mean = (3 * pi / 2) / sin(pi / 2),
mode = 1.73205,
median = actuar::qllogis(0.5, shape = 2, scale = 3),
variance = NaN,
skewness = NaN,
exkur = NaN,
pgf = NaN,
pdf = actuar::dllogis(1:3, shape = 2, scale = 3),
cdf = actuar::pllogis(1:3, shape = 2, scale = 3),
quantile = actuar::qllogis(c(0.24, 0.42, 0.5), shape = 2, scale = 3),
)
}) |
omercProj4string = function(
lon, lat, angle,
x=0,y=0, inverseAngle=0,
scale=1,
ellps='WGS84', units='m',
datum='WGS84',
crs=TRUE) {
x = rep_len(x, length(angle))
y = rep_len(y, length(angle))
scale = rep_len(scale, length(angle))
lat = rep_len(lat, length(angle))
lon = rep_len(lon, length(angle))
whichZeros = (angle==0)
which90 = abs(angle)==90
result = paste(
"+proj=omerc",
" +lat_0=", lat,
" +lonc=", lon,
" +alpha=", angle,
" +k_0=", scale,
" +x_0=", x,
" +y_0=", y,
" +gamma=", inverseAngle,
" +ellps=", ellps,
" +units=", units,
' +datum=', datum,
sep="")
if(any(whichZeros)) {
result[whichZeros] = paste(
"+proj=tmerc",
" +lat_0=", lat[whichZeros] ,
" +lon_0=", lon[whichZeros] ,
" +k=", scale[whichZeros] ,
" +x_0=", x[whichZeros] ,
" +y_0=", y[whichZeros] ,
" +ellps=", ellps,
" +units=", units,
' +datum=', datum,
sep="")
}
if(crs) {
result = lapply(result, CRS)
}
result
}
omerc = function(
x, angle=0,
post=c('none', 'north', 'wide','tall'),
preserve=NULL
) {
digits=3
angleOrig = angle
post = post[1]
if(is.numeric(post)){
inverseAngle = rep_len(post, length(angle))
post='none'
} else {
inverseAngle=rep(0, length(angle))
post=post[seq(1,len=length(post))]
}
scale = rep(1, length(angle))
objectiveResult = NULL
southAngle = ( abs(angle)>90) & (abs(angle) < 270 )
angle[southAngle] = angle[southAngle] + 180
inverseAngle[southAngle] = inverseAngle[southAngle] + 180
angleC = exp(1i*2*pi*(angle/360))
angle = round(Arg(angleC)*360/(2*pi), digits)
if(!is.numeric(x)){
theCentre = bbox(x)
theCentre = theCentre[,'min'] +
apply(theCentre, 1, diff)/2
} else {
theCentre = x[1:2]
if(!is.null(preserve)){
x = preserve
} else {
if(post %in% c('wide', 'tall'))
post = 'none'
}
}
theCentre = round(theCentre, digits)
haveRgdal = requireNamespace('rgdal', quietly=TRUE)
if(!haveRgdal) {
rotatedCRS =
omercProj4string(
lon=theCentre[1],
lat=theCentre[2],
angle=angle,
inverseAngle = inverseAngle)
if(length(rotatedCRS)==1)
rotatedCRS = rotatedCRS[[1]]
return(rotatedCRS)
}
crs = crs(x)
if(is.na(crs)){
crs = crsLL
}
if(is.character(crs))
crs = CRS(crs)
if(!isLonLat(crs)) {
theCentre = SpatialPoints(
t(theCentre[1:2]),
proj4string=crs
)
theCentre = spTransform(theCentre, crsLL)
theCentre = as.vector(theCentre@coords)
}
rotatedCRS =
omercProj4string(
lon=theCentre[1],
lat=theCentre[2],
angle=angle)
theCentreSp = SpatialPoints(t(theCentre), proj4string=crsLL)
newxy = simplify2array(lapply(rotatedCRS, function(qq){
drop(spTransform(theCentreSp, qq)@coords)
}))
newxy = round(newxy)
rotatedCRS = omercProj4string(
lon=theCentre[1],
lat=theCentre[2],
angle=angle,
x=-newxy[1,],
y=-newxy[2,])
if(!is.null(preserve)) {
if(!isLonLat(crs(preserve))){
preserve = spTransform(preserve, crsLL)
}
distGS = spDists(preserve)*1000
theLower = lower.tri(distGS, diag=FALSE)
distGS = distGS[theLower]
distEu = unlist(lapply(rotatedCRS,
function(crs){
mean(
spDists(
spTransform(preserve, crs)
)[theLower]/distGS,
na.rm=TRUE)
}
))
rotatedCRS =
omercProj4string(
lon=theCentre[1],
lat=theCentre[2],
angle=angle,
x=-newxy[1,],
y=-newxy[2,],
scale=round(1/distEu, digits))
distEuSsq = unlist(
lapply(rotatedCRS,
function(crs){
sqrt(mean(
(spDists(spTransform(preserve, crs)
)[theLower]/distGS
-1)^2,
na.rm=TRUE))
}
)
)
minDist= which.min(distEuSsq)
objectiveResult=list(
x = angle,
y = distEuSsq
)
angle=angle[minDist]
scale=round(1/distEu[minDist], digits)
inverseAngle = inverseAngle[minDist]
newxy = newxy[,minDist,drop=FALSE]
}
if(!is.numeric(x) & (length(rotatedCRS)>1) & is.null(preserve)){
if(post=='tall')
post = 'none'
if(post=='wide'){
post='none'
inverseAngle = rep(90, length(angle))
}
xTrans = mapply(
function(CRSobj) {
abs(prod(apply(bbox(
spTransform(x, CRSobj)
), 1, diff)
))
},
CRSobj=rotatedCRS
)
objectiveResult=list(
x = angle,
y = xTrans)
minX = which.min(xTrans)
angle = angle[minX]
scale = scale[minX]
inverseAngle = inverseAngle[minX]
newxy = newxy[,minX,drop=FALSE]
}
rotatedCRS = omercProj4string(
lon=theCentre[1],
lat=theCentre[2],
angle=angle,
scale=scale,
x=-newxy[1,],
y=-newxy[2,],
inverseAngle=inverseAngle
)
if(post=='none') {
if(length(rotatedCRS)==1) {
rotatedCRS = rotatedCRS[[1]]
}
if(!is.null(objectiveResult))
attributes(rotatedCRS)$obj = objectiveResult
return(rotatedCRS)
}
if(post=='north') {
rotatedCRS = omercProj4string(
lon=theCentre[1],
lat=theCentre[2],
angle=angle,
scale=scale,
x=-newxy[1,],
y=-newxy[2,]
)
pointNorth = SpatialPoints(
rbind(
theCentre,
theCentre + c(0, 0.1)
), proj4string=crsLL
)
adjust = mapply(
function(crs){
pn2 = spTransform(
pointNorth,
crs
)
pn2@coords = round(pn2@coords)
pnDist =apply(pn2@coords,2,diff)
-atan(pnDist[1]/pnDist[2])*360/(2*pi)
},
crs=rotatedCRS
)
inverseAngle = round(adjust, digits)
}
if(post=='wide' | post=='tall' & (length(angle)==1)) {
Sgamma = seq(-90,90,)
rotatedCRS = omercProj4string(
lon=theCentre[1],
lat=theCentre[2],
angle=angle,
scale=scale,
x=-newxy[1,],
y=-newxy[2,],
inverseAngle = Sgamma
)
bbarea = mapply(
function(CRSobj) {
thebb = bbox(
spTransform(x, CRSobj)
)
thebb = apply(thebb, 1, diff)
c(area= abs(prod(thebb)),
ratio = as.numeric(abs(thebb[2]/thebb[1]))
)
},
CRSobj=rotatedCRS
)
bbarea = rbind(bbarea, inverseAngle=Sgamma)
if(post=='wide'){
bbarea = bbarea[,bbarea['ratio',]<=1]
} else {
bbarea = bbarea[,bbarea['ratio',]>=1]
}
inverseAngle = bbarea[
'inverseAngle',
which.min(bbarea['area',])]
}
rotatedCRS =
omercProj4string(
lon=theCentre[1],
lat=theCentre[2],
angle=angle,
inverseAngle=inverseAngle,
x=-newxy[1,],
y=-newxy[2,],
scale=scale)
if(length(rotatedCRS)==1) {
rotatedCRS = rotatedCRS[[1]]
}
if(!is.null(objectiveResult))
attributes(rotatedCRS)$obj = objectiveResult
rotatedCRS
} |
QLMDp <- function(
from = .05, to = .95, length.out = 15L, equidistant = c('prob', 'quantile'),
extra = c(.005, .01, .02, .03, .97, .98, .99, .995),
obs
) {
if (!is.double(from) || length(from) != 1L || is.na(from) || from <= 0) stop('`from` must be numeric >0')
if (!is.double(to) || length(to) != 1L || is.na(to) || to >= 1) stop('`to` must be numeric <1')
if (!is.integer(length.out) || length(length.out) != 1L || anyNA(length.out) || length.out < 0L) stop('N must be len-1 non-negative integer')
if (!is.double(extra) || anyNA(extra) || any(extra <= 0, extra >= 1)) stop('`extra` must be numeric between (0, 1)')
p <- if (!length.out) extra else {
c(extra, switch(match.arg(equidistant), prob = {
seq.int(from = from, to = to, length.out = length.out)
}, quantile = {
if (missing(obs)) stop('Must have `obs`')
qlim <- quantile(obs, probs = c(from, to))
ecdf(obs)(seq.int(from = qlim[1L], to = qlim[2L], length.out = length.out))
}))
}
if (!length(p)) stop('len-0 p, do not allow')
sort.int(unique_allequal(p))
} |
CombIncrease_sim = function(ndose_a1, ndose_a2, p_tox, target, target_min, target_max, prior_tox_a1, prior_tox_a2, n_cohort,
cohort, tite=FALSE, time_full=0, poisson_rate=0, nsim, c_e=0.85, c_d=0.45, c_stop=0.95, c_t=0.5,
c_over=0.25, cmin_overunder=2, cmin_mtd=3, cmin_recom=1, startup=1, alloc_rule=1, early_stop=1,
nburn=2000, niter=5000, seed=14061991){
c_d = 1-c_d
dim_ptox = dim(p_tox)
if(dim_ptox[1] != ndose_a1 || dim_ptox[2] != ndose_a2){
stop("Wrong dimension of the matrix for true toxicity probabilities.")
}
n_prior_tox_a1 = length(prior_tox_a1)
if(n_prior_tox_a1 != ndose_a1){
stop("The entered vector of initial guessed toxicity probabities for agent 1 is of wrong length.")
}
n_prior_tox_a2 = length(prior_tox_a2)
if(n_prior_tox_a2 != ndose_a2){
stop("The entered vector of initial guessed toxicity probabities for agent 2 is of wrong length.")
}
ndose_a1 = as.integer(ndose_a1)[1]
ndose_a2 = as.integer(ndose_a2)[1]
target = as.double(target)[1]
target_min = as.double(target_min)[1]
target_max = as.double(target_max)[1]
prior_tox_a1 = as.double(prior_tox_a1)
prior_tox_a2 = as.double(prior_tox_a2)
n_cohort = as.integer(n_cohort)[1]
cohort = as.integer(cohort)[1]
tite = as.logical(tite)[1]
time_full = as.double(time_full)[1]
poisson_rate = as.double(poisson_rate)[1]
nsim = as.integer(nsim)[1]
c_e = as.double(c_e)[1]
c_d = as.double(c_d)[1]
c_stop = as.double(c_stop)[1]
c_t = as.double(c_t)[1]
c_over = as.double(c_over)[1]
cmin_overunder = as.integer(cmin_overunder)[1]
cmin_mtd = as.integer(cmin_mtd)[1]
cmin_recom = as.integer(cmin_recom)[1]
startup = as.integer(startup)[1]
alloc_rule = as.integer(alloc_rule)[1]
early_stop = as.integer(early_stop)[1]
seed = as.integer(seed)[1]
nburn = as.integer(nburn)[1]
niter = as.integer(niter)[1]
if(startup < 0 || startup > 3){
stop("Unknown start-up id.")
}
if(alloc_rule != 1 && alloc_rule != 2 && alloc_rule != 3){
stop("Unknown allocation rule id.")
}
if(early_stop != 1 && early_stop != 2 && early_stop != 3){
stop("Unknown early stopping rule id.")
}
if(target < 0 || target > 1){
stop("Targeted toxicity probability is not comprised between 0 and 1.")
}
if(target_max < 0 || target_max > 1){
stop("Maximum targeted toxicity probability is not comprised between 0 and 1.")
}
if(target_min < 0 || target_min > 1){
stop("Minimum targeted toxicity probability is not comprised between 0 and 1.")
}
if(n_cohort <= 0){
stop("Number of cohorts must be positive.")
}
if(cohort <= 0){
stop("Cohort size must be positive.")
}
if(time_full < 0){
stop("Full follow-up time must be positive.")
}
if(poisson_rate < 0){
stop("Parameter for Poisson process accrual must be positive.")
}
if(nsim <= 0){
stop("Number of simulations must be positive.")
}
if(c_e < 0 || c_e > 1 || c_d < 0 || c_d > 1 || c_stop < 0 || c_stop > 1 || c_t < 0 || c_t > 1 || c_over < 0 || c_over > 1){
stop("Probability thresholds are not comprised between 0 and 1.")
}
if(cmin_overunder < 0 || cmin_mtd < 0 || cmin_recom < 0){
stop("Minimum number of cohorts for stopping or recommendation rule must be positive.")
}
if(nburn <= 0 || niter <= 0){
stop("Number of iterations and burn-in for MCMC must be positive.")
}
for(a1 in 1:ndose_a1){
if(prior_tox_a1[a1] < 0 || prior_tox_a1[a1] > 1){
stop("At least one of the initial guessed toxicity probability for agent 1 is not comprised between 0 and 1.")
}
}
for(a2 in 1:ndose_a2){
if(prior_tox_a2[a2] < 0 || prior_tox_a2[a2] > 1){
stop("At least one of the initial guessed toxicity probability for agent 2 is not comprised between 0 and 1.")
}
}
for(a1 in 1:ndose_a1){
for(a2 in 1:ndose_a2){
if(p_tox[a1,a2] < 0 || p_tox[a1,a2] > 1){
stop("At least one of the true toxicity probability is not comprised between 0 and 1.")
}
}
}
p_tox_na = matrix(NA, nrow=ndose_a1+1, ncol=ndose_a2+1)
p_tox_na[1:ndose_a1, 1:ndose_a2] = p_tox
for(a1 in 1:ndose_a1){
for(a2 in 1:ndose_a2){
if(p_tox[a1,a2] >
min(1,p_tox_na[a1+1,a2],p_tox_na[a1,a2+1],p_tox_na[a1+1,a2+1],na.rm=TRUE)){
stop("The partial ordering between true toxicity probabilities is not satisfied.")
}
}
}
p_tox = as.double(p_tox)
inconc = as.double(numeric(1))
n_pat_dose = as.double(numeric(ndose_a1*ndose_a2))
rec_dose = as.double(numeric(ndose_a1*ndose_a2))
n_tox_dose = as.double(numeric(ndose_a1*ndose_a2))
early_conc = as.double(numeric(1))
conc_max = as.double(numeric(1))
tab_pat = as.double(numeric(nsim))
logistic = .C(C_logistic_sim, tite, ndose_a1, ndose_a2, time_full, poisson_rate, p_tox, target,
target_max, target_min, prior_tox_a1, prior_tox_a2, n_cohort, cohort, nsim, c_e, c_d, c_stop,
c_t, c_over, cmin_overunder, cmin_mtd, cmin_recom, seed, startup, alloc_rule, early_stop,
nburn, niter,
rec_dose=rec_dose, n_pat_dose=n_pat_dose, n_tox_dose=n_tox_dose, inconc=inconc, early_conc=early_conc, tab_pat=tab_pat)
nsim = logistic$nsim
inconc=logistic$inconc*100
early_conc=logistic$early_conc*100
conc_max=100-early_conc-inconc
tab_pat=logistic$tab_pat
rec_dose=logistic$rec_dose*100
n_pat_dose=logistic$n_pat_dose
n_tox_dose=logistic$n_tox_dose
p_tox= matrix(p_tox,nrow=ndose_a1)
rec_dose=matrix(rec_dose,nrow=ndose_a1)
n_pat_dose=matrix(n_pat_dose,nrow=ndose_a1)
n_tox_dose=matrix(n_tox_dose,nrow=ndose_a1)
p_tox_p = t(p_tox)[ndose_a2:1,]
rec_dose_p = t(rec_dose)[ndose_a2:1,]
n_pat_dose_p = t(n_pat_dose)[ndose_a2:1,]
n_tox_dose_p = t(n_tox_dose)[ndose_a2:1,]
dimnames(p_tox_p) = list("Agent 2" = ndose_a2:1, "Agent 1" = 1:ndose_a1)
dimnames(rec_dose_p) = list("Agent 2 " = ndose_a2:1, "Agent 1" = 1:ndose_a1)
dimnames(n_pat_dose_p) = list("Agent 2"=ndose_a2:1, "Agent 1" = 1:ndose_a1)
dimnames(n_tox_dose_p) = list("Agent 2" = ndose_a2:1, "Agent 1" = 1:ndose_a1)
pat_tot = round(sum(n_pat_dose),1)
res = list(call = match.call(),
tite=tite,
ndose_a1=ndose_a1,
ndose_a2=ndose_a2,
time_full=time_full,
poisson_rate=poisson_rate,
startup=startup,
alloc_rule=alloc_rule,
early_stop=early_stop,
p_tox=p_tox,
p_tox_p=p_tox_p,
target=target,
target_min=target_min,
target_max=target_max,
prior_tox_a1=prior_tox_a1,
prior_tox_a2=prior_tox_a2,
n_cohort=n_cohort,
cohort=cohort,
pat_tot=pat_tot,
nsim=nsim,
c_e=c_e,
c_d=c_d,
c_stop=c_stop,
c_t=c_t,
c_over=c_over,
cmin_overunder=cmin_overunder,
cmin_mtd=cmin_mtd,
cmin_recom=cmin_recom,
nburn=nburn,
niter=niter,
seed=seed,
rec_dose=rec_dose,
n_pat_dose=n_pat_dose,
n_tox_dose=n_tox_dose,
rec_dose_p=rec_dose_p,
n_pat_dose_p=n_pat_dose_p,
n_tox_dose_p=n_tox_dose_p,
inconc=inconc,
early_conc=early_conc,
conc_max=conc_max,
tab_pat=tab_pat)
class(res) = "CombIncrease_sim"
return(res)
}
print.CombIncrease_sim = function(x, dgt = 2, ...) {
cat("Call:\n")
print(x$call)
cat("\n")
print_rnd= function (hd, x) {cat(hd, "\n"); print(round(x, digits = dgt)); cat("\n")}
print_rnd("True toxicities:", x$p_tox_p)
print_rnd("Percentage of Selection:", x$rec_dose_p)
print_rnd("Mean number of patients:" , x$n_pat_dose_p)
print_rnd("Mean number of toxicities:", x$n_tox_dose_p)
cat(paste("Percentage of inconclusive trials:\t",x$inconc,"\n",sep=""), sep="")
cat(paste("Percentage of trials stopping with criterion for finding MTD:\t",x$early_conc,"\n",sep=""), sep="")
cat(paste("Percentage of trials stopping with recommendation based on maximum sample size:\t",x$conc_max,"\n",sep=""), sep="")
cat("\n")
cat("Number of simulations:\t", x$nsim, "\n")
cat("Total mean number of patients accrued:\t", x$pat_tot, "\n")
cat("Quantiles for number of patients accrued:\t", "\n", quantile(x$tab_pat), "\n")
}
CombIncrease_next = function(ndose_a1, ndose_a2, target, target_min, target_max, prior_tox_a1, prior_tox_a2, cohort, final,
pat_incl, dose_adm1, dose_adm2, tite=FALSE, toxicity, time_full=0, time_tox=0, time_follow=0,
c_e=0.85, c_d=0.45, c_stop=0.95, c_t=0.5, c_over=0.25, cmin_overunder=2, cmin_mtd=3, cmin_recom=1,
early_stop=1, alloc_rule=1, nburn=2000, niter=5000){
if(tite == TRUE) {
toxicity = as.numeric(time_tox < time_follow)
}
if(pat_incl > 0) {
cdose1 = dose_adm1[pat_incl]
cdose2 = dose_adm2[pat_incl]
}
else {
cdose1 = 0
cdose2 = 0
}
n_prior_tox_a1 = length(prior_tox_a1)
if(n_prior_tox_a1 != ndose_a1){
stop("The entered vector of initial guessed toxicity probabities for agent 1 is of wrong length.")
}
n_prior_tox_a2 = length(prior_tox_a2)
if(n_prior_tox_a2 != ndose_a2){
stop("The entered vector of initial guessed toxicity probabities for agent 2 is of wrong length.")
}
n_toxicity = length(toxicity)
n_time_follow = length(time_follow)
n_time_tox = length(time_tox)
n_dose_adm1 = length(dose_adm1)
n_dose_adm2 = length(dose_adm2)
if(tite==FALSE && n_toxicity != pat_incl){
stop("The entered vector of observed toxicities is of wrong length.")
}
if(tite==TRUE && n_time_follow != pat_incl){
stop("The entered vector for patients' follow-up time is of wrong length.")
}
if(tite==TRUE && n_time_tox != pat_incl){
stop("The entered vector for patients' time-to-toxicity is of wrong length.")
}
if(n_dose_adm1 != pat_incl){
stop("The entered vector for patients' dose of agent 1 is of wrong length.")
}
if(n_dose_adm2 != pat_incl){
stop("The entered vector for patients' dose of agent 2 is of wrong length.")
}
tite = as.logical(tite)
ndose_a1 = as.integer(ndose_a1)[1]
ndose_a2 = as.integer(ndose_a2)[1]
time_full = as.double(time_full)[1]
target = as.double(target)[1]
target_max = as.double(target_max)[1]
target_min = as.double(target_min)[1]
prior_tox_a1 = as.double(prior_tox_a1)
prior_tox_a2 = as.double(prior_tox_a2)
cohort = as.integer(cohort)[1]
final = as.logical(final)
c_e = as.double(c_e)[1]
c_d = as.double(c_d)[1]
c_stop = as.double(c_stop)[1]
c_t = as.double(c_t)[1]
c_over = as.double(c_over)[1]
cmin_overunder = as.integer(cmin_overunder)[1]
cmin_mtd = as.integer(cmin_mtd)[1]
cmin_recom = as.integer(cmin_recom)[1]
pat_incl = as.integer(pat_incl)[1]
cdose1 = as.integer(cdose1-1)
cdose2 = as.integer(cdose2-1)
dose_adm1 = as.integer(dose_adm1-1)
dose_adm2 = as.integer(dose_adm2-1)
time_tox = as.double(time_tox)
time_follow = as.double(time_follow)
toxicity = as.logical(toxicity)
alloc_rule = as.integer(alloc_rule)[1]
early_stop = as.integer(early_stop)[1]
nburn = as.integer(nburn)[1]
niter = as.integer(niter)[1]
if(alloc_rule != 1 && alloc_rule != 2 && alloc_rule != 3){
stop("Unknown allocation rule id.")
}
if(early_stop != 1 && early_stop != 2 && early_stop != 3){
stop("Unknown early stopping rule id.")
}
if(cohort <= 0){
stop("Cohort size must be positive.")
}
if(time_full < 0){
stop("Full follow-up time must be positive.")
}
if(c_e < 0 || c_e > 1 || c_d < 0 || c_d > 1 || c_stop < 0 || c_stop > 1 || c_t < 0 || c_t > 1 || c_over < 0 || c_over > 1){
stop("Probability thresholds are not comprised between 0 and 1.")
}
if(cmin_overunder < 0 || cmin_mtd < 0 || cmin_recom < 0){
stop("Minimum number of cohorts for stopping or recommendation rule must be positive.")
}
if(nburn <= 0 || niter <= 0){
stop("Number of iterations and burn-in for MCMC must be positive.")
}
for(i in 1:ndose_a1){
if(prior_tox_a1[i] < 0 || prior_tox_a1[i] > 1){
stop("At least one of the initial guessed toxicity for agent 1 is not comprised between 0 and 1.")
}
}
for(i in 1:ndose_a2){
if(prior_tox_a2[i] < 0 || prior_tox_a2[i] > 1){
stop("At least one of the initial guessed toxicity for agent 2 is not comprised between 0 and 1.")
}
}
if(target < 0 || target > 1){
stop("Targeted toxicity probability is not comprised between 0 and 1.")
}
if(target_max < 0 || target_max > 1){
stop("Maximum targeted toxicity probability is not comprised between 0 and 1.")
}
if(target_min < 0 || target_min > 1){
stop("Minimum targeted toxicity probability is not comprised between 0 and 1.")
}
inconc = as.logical(numeric(1))
early_conc = as.logical(numeric(1))
pi = as.double(numeric(ndose_a1*ndose_a2))
ptox_inf = as.double(numeric(ndose_a1*ndose_a2))
ptox_inf_targ = as.double(numeric(ndose_a1*ndose_a2))
ptox_targ = as.double(numeric(ndose_a1*ndose_a2))
ptox_sup_targ = as.double(numeric(ndose_a1*ndose_a2))
logistic = .C(C_logistic_next, tite, ndose_a1, ndose_a2, time_full, target, target_max, target_min, prior_tox_a1, prior_tox_a2,
cohort, final, c_e, c_d, c_stop, c_t, c_over, cmin_overunder, cmin_mtd, cmin_recom, early_stop, alloc_rule,
nburn, niter, pat_incl, cdose1=cdose1, cdose2=cdose2, dose_adm1, dose_adm2, time_tox, time_follow, toxicity,
inconc=inconc, early_conc=early_conc, pi=pi, ptox_inf=ptox_inf, ptox_inf_targ=ptox_inf_targ, ptox_targ=ptox_targ, ptox_sup_targ=ptox_sup_targ, NAOK=TRUE)
cdose1=logistic$cdose1+1
cdose2=logistic$cdose2+1
dose_adm1=dose_adm1+1
dose_adm2=dose_adm2+1
pi=matrix(logistic$pi, nrow=ndose_a1)
ptox_inf=matrix(logistic$ptox_inf, nrow=ndose_a1)
ptox_inf_targ=matrix(logistic$ptox_inf_targ, nrow=ndose_a1)
ptox_targ=matrix(logistic$ptox_targ, nrow=ndose_a1)
ptox_sup_targ=matrix(logistic$ptox_sup_targ, nrow=ndose_a1)
n_pat_comb = matrix(0, nrow=ndose_a1, ncol=ndose_a2)
n_tox_comb = matrix(0, nrow=ndose_a1, ncol=ndose_a2)
for(i in 1:pat_incl){
n_pat_comb[dose_adm1[i],dose_adm2[i]] = n_pat_comb[dose_adm1[i],dose_adm2[i]]+1
n_tox_comb[dose_adm1[i],dose_adm2[i]] = n_tox_comb[dose_adm1[i],dose_adm2[i]]+toxicity[i]
}
n_pat_comb_p = t(n_pat_comb)[ndose_a2:1,]
n_tox_comb_p = t(n_tox_comb)[ndose_a2:1,]
pi_p = t(pi)[ndose_a2:1,]
ptox_inf_p = t(ptox_inf)[ndose_a2:1,]
ptox_inf_targ_p = t(ptox_inf_targ)[ndose_a2:1,]
ptox_targ_p = t(ptox_targ)[ndose_a2:1,]
ptox_sup_targ_p = t(ptox_sup_targ)[ndose_a2:1,]
dimnames(n_pat_comb_p) = list("Agent 2"=ndose_a2:1, "Agent 1"=1:ndose_a1)
dimnames(n_tox_comb_p) = list("Agent 2"=ndose_a2:1, "Agent 1"=1:ndose_a1)
dimnames(pi_p) = list("Agent 2"=ndose_a2:1, "Agent 1"=1:ndose_a1)
dimnames(ptox_inf_p) = list("Agent 2"=ndose_a2:1, "Agent 1"=1:ndose_a1)
dimnames(ptox_inf_targ_p) = list("Agent 2"=ndose_a2:1, "Agent 1"=1:ndose_a1)
dimnames(ptox_targ_p) = list("Agent 2"=ndose_a2:1, "Agent 1"=1:ndose_a1)
dimnames(ptox_sup_targ_p) = list("Agent 2"=ndose_a2:1, "Agent 1"=1:ndose_a1)
res = list(call = match.call(),
tite=tite,
ndose_a1=ndose_a1,
ndose_a2=ndose_a2,
time_full=time_full,
target=target,
target_max=target_max,
target_min=target_min,
prior_tox_a1=prior_tox_a1,
prior_tox_a2=prior_tox_a2,
cohort=cohort,
final=final,
c_e=c_e,
c_d=c_d,
c_stop=c_stop,
c_t=c_t,
c_over=c_over,
cmin_overunder=cmin_overunder,
cmin_mtd=cmin_mtd,
cmin_recom=cmin_recom,
early_stop=early_stop,
alloc_rule=alloc_rule,
nburn=nburn,
niter=niter,
pat_incl=pat_incl,
cdose1=cdose1,
cdose2=cdose2,
dose_adm1=dose_adm1,
dose_adm2=dose_adm2,
time_tox=time_tox,
time_follow=time_follow,
toxicity=toxicity,
inconc=logistic$inconc,
early_conc=logistic$early_conc,
n_pat_comb=n_pat_comb,
n_tox_comb=n_tox_comb,
pi=pi,
ptox_inf=ptox_inf,
ptox_inf_targ=ptox_inf_targ,
ptox_targ=ptox_targ,
ptox_sup_targ=ptox_sup_targ,
n_pat_comb_p=n_pat_comb_p,
n_tox_comb_p=n_tox_comb_p,
pi_p=pi_p,
ptox_inf_p=ptox_inf_p,
ptox_inf_targ_p=ptox_inf_targ_p,
ptox_targ_p=ptox_targ_p,
ptox_sup_targ_p=ptox_sup_targ_p)
class(res) = "CombIncrease_next"
return(res)
}
print.CombIncrease_next = function(x, dgt = 2, ...) {
cat("Call:\n")
print(x$call)
cat("\n")
print_rnd= function (hd, x) {cat(hd, "\n"); print(round(x, digits = dgt)); cat("\n")}
print_rnd("Number of patients:" , x$n_pat_comb_p)
print_rnd("Number of toxicities:", x$n_tox_comb_p)
print_rnd("Estimated toxicity probabilities:", x$pi_p)
print_rnd("P(toxicity probability < target):", x$ptox_inf_p)
print_rnd("Probabilities of underdosing:", x$ptox_inf_targ_p)
print_rnd("Probabilities being in targeted interval:", x$ptox_targ_p)
print_rnd("Probabilities of overdosing:", x$ptox_sup_targ_p)
cat("Warning: recommendation for model-based phase (start-up phase must be ended).\n")
if(!x$inconc){
if(!x$early_conc){
if(x$final){
cat(paste("The RECOMMENDED COMBINATION at the end of the trial is:\t (",x$cdose1, ",", x$cdose2, ")\n",sep=""), sep="")
}
else{
cat(paste("The next RECOMMENDED COMBINATION is:\t (",x$cdose1, ",", x$cdose2, ")\n",sep=""), sep="")
}
}
else{
cat(paste("The dose-finding process should be STOPPED (criterion for identifying MTD met) and the RECOMMENDED COMBINATION is:\t (",x$cdose1, ",", x$cdose2, ")\n",sep=""), sep="")
}
}
else{
cat(paste("The dose-finding process should be STOPPED WITHOUT COMBINATION RECOMMENDATION (criterion for over or under toxicity met)\n",sep=""), sep="")
}
} |
CheckAtm.lin = function(ATM = list()){
if(is.null(ATM$z0)){
ATM$z0 = 0
}
if(is.null(ATM$c0)){
ATM$c0 = 330
}
if(is.null(ATM$gc)){
ATM$gc = -10^-9
}else if(ATM$gc == 0){
ATM$gc = -10^-9
}
if(is.null(ATM$wx0)){
ATM$wx0 = 0
}
if(is.null(ATM$gwx)){
ATM$gwx = 0
}
if(is.null(ATM$wy0)){
ATM$wy0 = 0
}
if(is.null(ATM$gwy)){
ATM$gwy = 0
}
if(is.null(ATM$rho0)){
ATM$rho0 = 1.2929 * exp(-ATM$z0/6800)
}
if(is.null(ATM$grho)){
ATM$grho = -1.013*10^5/(287.04*273*6800) * exp(-ATM$z0/6800)
}
return(ATM)
} |
if (is_installed(pkgnm = pkgnm)) {
uninstall(pkgnm = pkgnm)
} |
majoritySingleVetoGameValue<-function(S,vetoPlayer){
paramCheckResult=getEmptyParamCheckResult()
stopOnInvalidCoalitionS(paramCheckResult,S)
stopOnInvalidVetoPlayer(paramCheckResult,vetoPlayer)
logicmajoritySingleVetoGameValue(S,vetoPlayer)
}
logicmajoritySingleVetoGameValue=function(S, vetoPlayer) {
result=0
if ( (length(S) >= 2) && (vetoPlayer %in% S) ) {
result=1
}
return(result)
}
majoritySingleVetoGameVector<-function(n,vetoPlayer){
bitMatrix = createBitMatrix(n)[,1:n];
A<-c()
i<-1
end<-((2^n)-1)
while(i<=end){
currCoal<-which(bitMatrix[i,]&1)
A[i] = majoritySingleVetoGameValue(S=currCoal, vetoPlayer=vetoPlayer)
i<-i+1
}
return(A)
}
majoritySingleVetoGame<-function(n,vetoPlayer){
v = majoritySingleVetoGameVector(n=n,vetoPlayer=vetoPlayer)
retmajoritySingleVetoGame=list(n=n,vetoPlayer=vetoPlayer,v=v)
return(retmajoritySingleVetoGame)
} |
gr_cumhaz_flexrsurv_fromto_GA0B0AB_bh<-function(GA0B0AB, var,
Y, X0, X, Z,
step, Nstep,
intTD=intTD_NC, intweightsfunc=intweights_CAV_SIM,
intTD_base=intTD_base_NC,
nT0basis,
Spline_t0=BSplineBasis(knots=NULL, degree=3, keep.duplicates=TRUE), Intercept_t0=TRUE,
ialpha0, nX0,
ibeta0, nX,
ialpha, ibeta,
nTbasis,
Spline_t =BSplineBasis(knots=NULL, degree=3, keep.duplicates=TRUE),
Intercept_t_NPH=rep(TRUE, nX),
debug=FALSE, ...){
if (debug) cat("
if(is.null(Z)){
nZ <- 0
} else {
nZ <- Z@nZ
}
if(Intercept_t0){
tmpgamma0 <- GA0B0AB[1:nT0basis]
}
else {
tmpgamma0 <- c(0, GA0B0AB[1:nT0basis])
}
if( nX0){
PHterm <-exp(X0 %*% GA0B0AB[ialpha0])
} else {
PHterm <- 1
}
if(nZ) {
tBeta <- t(ExpandAllCoefBasis(GA0B0AB[ibeta], ncol=nZ, value=1))
Zalpha <- Z@DM %*%( diag(GA0B0AB[ialpha]) %*% Z@signature )
Zalphabeta <- Zalpha %*% tBeta
if(nX) {
Zalphabeta <- Zalphabeta + X %*% t(ExpandCoefBasis(GA0B0AB[ibeta0],
ncol=nX,
splinebasis=Spline_t,
expand=!Intercept_t_NPH,
value=0))
}
} else {
if(nX) {
Zalphabeta <- X %*% t(ExpandCoefBasis(GA0B0AB[ibeta0],
ncol=nX,
splinebasis=Spline_t,
expand=!Intercept_t_NPH,
value=0))
}
}
if(nX + nZ) {
NPHterm <- intTD(rateTD_bh_alphabeta, intFrom=Y[,1], intTo=Y[,2], intToStatus=Y[,3],
step=step, Nstep=Nstep,
intweightsfunc=intweightsfunc,
gamma0=GA0B0AB[1:nT0basis], Zalphabeta=Zalphabeta,
Spline_t0=Spline_t0*tmpgamma0, Intercept_t0=Intercept_t0,
Spline_t = Spline_t, Intercept_t=TRUE)
Intb0 <- intTD_base(func=ratioTD_bh_alphabeta, intFrom=Y[,1], intTo=Y[,2], intToStatus=Y[,3],
Spline=Spline_t0,
step=step, Nstep=Nstep,
intweightsfunc=intweightsfunc,
gamma0=GA0B0AB[1:nT0basis], Zalphabeta=Zalphabeta,
Spline_t0=Spline_t0*tmpgamma0, Intercept_t0=Intercept_t0,
Spline_t = Spline_t, Intercept_t=TRUE,
debug=debug)
Intb <- intTD_base(func=rateTD_bh_alphabeta, intFrom=Y[,1], intTo=Y[,2], intToStatus=Y[,3],
Spline=Spline_t,
step=step, Nstep=Nstep,
intweightsfunc=intweightsfunc,
gamma0=GA0B0AB[1:nT0basis], Zalphabeta=Zalphabeta,
Spline_t0=Spline_t0*tmpgamma0, Intercept_t0=Intercept_t0,
Spline_t = Spline_t, Intercept_t=TRUE)
if(!Intercept_t0){
Intb0<- Intb0[,-1]
}
indx_without_intercept <- 2:getNBases(Spline_t)
}
else {
NPHterm <- predict(integrate(Spline_t0*tmpgamma0), Y[,2], intercep=Intercept_t0) -
predict(integrate(Spline_t0*tmpgamma0), Y[,1], intercep=Intercept_t0)
Intb0 <- integrate(Spline_t0, Y[,2], intercep=Intercept_t0) -
integrate(Spline_t0, Y[,1], intercep=Intercept_t0)
Intb <- NULL
}
if(nX + nZ) {
if(nX0>0) {
Intb <- Intb * c(PHterm)
}
}
Intb0 <- Intb0 * c(PHterm)
dLdgamma0 <- Intb0
if (nX0) {
dLdalpha0 <- X0 * c(PHterm * NPHterm)
}
else {
dLdalpha0 <- NULL
}
if (nX){
dLdbeta0 <- NULL
for(i in 1:nX){
if ( Intercept_t_NPH[i] ){
dLdbeta0 <- cbind(dLdbeta0, X[,i] * Intb)
}
else {
dLdbeta0 <- cbind(dLdbeta0, X[,i] * Intb[,indx_without_intercept])
}
}
}
else {
dLdbeta0 <- NULL
}
if (nZ) {
baseIntb <- Intb %*% t(tBeta)
indZ <- getIndex(Z)
dLdalpha <- NULL
dLdbeta <- NULL
for(iZ in 1:nZ){
dLdalpha <- cbind(dLdalpha, Z@DM[,indZ[iZ,1]:indZ[iZ,2]] * baseIntb[,iZ])
dLdbeta <- cbind(dLdbeta, Intb[,-1, drop=FALSE] * Zalpha[,iZ])
}
}
else {
dLdalpha <- NULL
dLdbeta <- NULL
}
rep <- cbind(dLdgamma0,
dLdalpha0,
dLdbeta0,
dLdalpha,
dLdbeta )
if(debug){
attr(rep, "intb0") <- Intb0
attr(rep, "intb") <- Intb
}
rep
} |
cumbasehaz = function(object)
{
if(class(object) != "gamlasso")
stop("Please enter a gamlasso object to print")
if(object$inherit$family != "cox")
stop("Cumulative base hazard function only makes sense for cox models")
lp <- predict.gamlasso(object, newdata=object$inherit$train.data, type="link")
event.time <- object$inherit$train.data %>%
dplyr::pull(object$inherit$fit.names$response)
status <- object$inherit$train.data %>%
dplyr::pull(object$inherit$fit.names$weights)
L0 = cbh(lp, event.time, status)
return(L0)
}
cbh = function(lp, event.time, status)
{
cox.model <- survival::coxph(survival::Surv(event.time, status) ~ offset(lp))
sf <- survival::survfit(cox.model)
H0 <- approxfun(sf$time, sf$cumhaz*exp( -mean(lp) ) )
return(H0)
} |
file_upload_button <- function(
inputId, label = "", multiple = FALSE,
accept = NULL, buttonLabel = "Load", title = "Load data",
class = "", icn = "upload", progress = FALSE
) {
if (getOption("radiant.shinyFiles", FALSE)) {
shinyFiles::shinyFileChoose(
input = input,
id = inputId,
session = session,
roots = sf_volumes,
filetype = gsub(".", "", accept, fixed = TRUE)
)
shinyFiles::shinyFilesButton(
inputId, buttonLabel, label, title = title,
multiple = FALSE, class = class, icon = icon(icn)
)
} else {
if (length(accept) > 0) {
accept <- paste(accept, collapse = ",")
} else {
accept <- ""
}
if (!radiant.data::is_empty(label)) {
label <- paste0("</br><label>", label, "</label></br>")
}
btn <- paste0(label, "
<label class='input-group-btn'>
<span class='btn btn-default btn-file-solitary ", class, "'>
<i class='fa fa-upload'></i>
", buttonLabel, "
<input id='", inputId, "' name='", inputId, "' type='file' style='display: none;' accept='", accept, "'/>
</span>
</label>
")
if (progress) {
btn <- paste0(btn, "\n<div id='uploadfile_progress' class='progress progress-striped active shiny-file-input-progress'>
<div class='progress-bar'></div>
</div>")
}
HTML(btn)
}
}
getdeps <- function() {
htmltools::attachDependencies(
htmltools::tagList(),
c(
htmlwidgets:::getDependency("DiagrammeR", "DiagrammeR"),
htmlwidgets:::getDependency("plotly", "plotly")
)
)
}
rstudio_context <- function(type = "rmd") {
rse <- rstudioapi::getSourceEditorContext()
path <- rse$path
ext <- tools::file_ext(path)
if (radiant.data::is_empty(path) || !file.exists(path) || tolower(ext) != type) {
list(path = "", rpath = "", base = "", base_name = "", ext = "", content = "")
} else {
path <- normalizePath(path, winslash = "/")
pdir <- getOption("radiant.project_dir", default = radiant.data::find_home())
sel <- rse$selection[[1]][["text"]]
if (radiant.data::is_empty(sel)) {
content <- paste0(rse$content, collapse = "\n")
} else {
content <- paste0(sel, collapse = "\n")
}
base <- basename(path)
base_name <- sub(paste0(".", ext), "", base)
rpath <- if (radiant.data::is_empty(pdir)) {
path
} else {
sub(paste0(pdir, "/"), "", path)
}
list(
path = path,
rpath = rpath,
base = base,
base_name = sub(paste0(".", ext, "$"), "", base),
ext = tolower(ext),
content = content
)
}
}
scrub <- . %>%
gsub("<!--/html_preserve-->", "", .) %>%
gsub("<!--html_preserve-->", "", .) %>%
gsub("<!–html_preserve–>", "", .) %>%
gsub("<!–/html_preserve–>", "", .)
setup_report <- function(
report, ech, add_yml = TRUE, type = "rmd",
save_type = "Notebook", lib = "radiant"
) {
report <- fix_smart(report) %>%
gsub("^```\\s*\\{", "\n\n```{", .) %>%
gsub("^```\\s*\n", "```\n\n", .) %>%
sub("^---\n(.*?)\n---", "", .) %>%
sub("<!--(.*?)-->", "", .)
sopts <- ifelse(save_type == "PDF", ",\n screenshot.opts = list(vheight = 1200)", "")
if (add_yml) {
if (save_type %in% c("PDF", "Word", "Powerpoint")) {
yml <- ""
} else if (save_type == "HTML") {
yml <- '---\npagetitle: HTML report\noutput:\n html_document:\n highlight: zenburn\n theme: cosmo\n df_print: paged\n toc: yes\n---\n\n'
} else if (save_type %in% c("Rmd", "Rmd + Data (zip)")) {
yml <- '---\npagetitle: Rmd report\noutput:\n html_document:\n highlight: zenburn\n theme: cosmo\n df_print: paged\n toc: yes\n code_folding: hide\n code_download: true\n---\n\n'
} else {
yml <- '---\npagetitle: Notebook report\noutput:\n html_notebook:\n highlight: zenburn\n theme: cosmo\n toc: yes\n code_folding: hide\n---\n\n'
}
} else {
yml = ""
}
if (missing(ech)) {
ech <- if (save_type %in% c("PDF", "Word", "Powerpoint", "HTML")) "FALSE" else "TRUE"
}
if (grepl("```{r r_setup, include = FALSE}\n", report, fixed = TRUE)) {
report
} else {
paste0(yml, "```{r r_setup, include = FALSE}
knitr::opts_chunk$set(
comment = NA,
echo = ", ech, ",
error = TRUE,
cache = FALSE,
message = FALSE,\n
dpi = 96,
warning = FALSE", sopts, "
)
options(
width = 250,
scipen = 100,
max.print = 5000,
stringsAsFactors = FALSE
)
if (is.null(shiny::getDefaultReactiveDomain())) library(", lib, ")
```
<style>
.btn, .form-control, pre, code, pre code {
border-radius: 4px;
}
.table {
width: auto;
}
ul, ol {
padding-left: 18px;
}
code, pre, pre code {
overflow: auto;
white-space: pre;
word-wrap: normal;
}
code {
color:
background-color:
}
pre {
background-color:
}
</style>\n\n", report)
}}
knit_it_save <- function(report) {
md <- knitr::knit(text = report, envir = r_data)
deps <- knitr::knit_meta()
dep_scripts <-
lapply(deps, function(x) {
lapply(x$script, function(script) file.path(x$src$file, script))
}) %>%
unlist() %>%
unique()
dep_stylesheets <-
lapply(deps, function(x) {
lapply(x$stylesheet, function(stylesheet) file.path(x$src$file, stylesheet))
}) %>%
unlist() %>%
unique()
dep_html <- c(
sapply(dep_scripts, function(script) {
sprintf(
'<script type="text/javascript" src="%s"></script>',
base64enc::dataURI(file = script)
)
}),
sapply(dep_stylesheets, function(sheet) {
sprintf(
"<style>%s</style>",
paste(sshhr(readLines(sheet)), collapse = "\n")
)
})
)
preserved <- htmltools::extractPreserveChunks(md)
markdown::markdownToHTML(
text = preserved$value,
header = dep_html,
options = c("mathjax", "base64_images"),
stylesheet = file.path(getOption("radiant.path.data"), "app/www/bootstrap.min.css")
) %>%
htmltools::restorePreserveChunks(preserved$chunks) %>%
gsub("<table>", "<table class='table table-condensed table-hover'>", .)
}
report_clean <- function(report) {
withProgress(message = "Cleaning report", value = 1, {
report <- gsub("\nr_data\\[\\[\"([^\n]+?)\"\\]\\] \\%>\\%(.*?)\\%>\\%\\s*?store\\(\"(.*?)\", (\".*?\")\\)", "\n\\3 <- \\1 %>%\\2\nregister(\"\\3\", \\4)", report) %>%
gsub("r_data\\[\\[\"([^\"]+?)\"\\]\\]", "\\1", .) %>%
gsub("r_data\\$", "", .) %>%
gsub("\"mean_rm\"", "\"mean\"", .) %>%
gsub("\"median_rm\"", "\"median\"", .) %>%
gsub("\"min_rm\"", "\"min\"", .) %>%
gsub("\"max_rm\"", "\"max\"", .) %>%
gsub("\"sd_rm\"", "\"sd\"", .) %>%
gsub("\"var_rm\"", "\"var\"", .) %>%
gsub("\"sum_rm\"", "\"sum\"", .) %>%
gsub("\"length\"", "\"n_obs\"", .) %>%
gsub("tabsort = \"desc\\(n\\)\"", "tabsort = \"desc\\(n_obs\\)\"", .) %>%
gsub("Search\\(\"(.*?)\",\\s*?.\\)", "search_data(., \"\\1\")", .) %>%
gsub("toFct\\(\\)", "to_fct()", .) %>%
gsub("rounddf\\(", "round_df(", .) %>%
gsub("formatnr\\(", "format_nr(", .) %>%
gsub("formatdf\\(", "format_df(", .) %>%
gsub("dataset\\s*=\\s*\"([^\"]+)\",", "\\1,", .) %>%
gsub("store\\(pred, data\\s*=\\s*\"([^\"]+)\"", "\\1 <- store(\\1, pred", .) %>%
gsub("pred_data\\s*=\\s*\"([^\"]+)\"", "pred_data = \\1", .) %>%
gsub("(combinedata\\(\\s*?x\\s*?=\\s*?)\"([^\"]+?)\",(\\s*?y\\s*?=\\s*?)\"([^\"]+?)\",", "\\1\\2,\\3\\4,", .) %>%
gsub("(combinedata\\((.|\n)*?),\\s*?name\\s*?=\\s*?\"([^\"`]+?)\"([^\\)]+?)\\)", "\\3 <- \\1\\4)\nregister(\"\\3\")", .) %>%
gsub("combinedata\\(", "combine_data(", .) %>%
gsub("result\\s*<-\\s*(simulater\\((.|\n)*?),\\s*name+\\s*=\\s*\"([^\"`]*?)\"([^\\)]*?)\\)", "\\3 <- \\1\\4)\nregister(\"\\3\")", .) %>%
gsub("data\\s*=\\s*\"([^\"]+)\",", "data = \\1,", .) %>%
gsub("(simulater\\((\n|.)*?)(register\\(\"(.*?)\"\\))\nsummary\\(result", "\\1\\3\nsummary(\\4", .) %>%
gsub("(simulater\\((\n|.)*?)(register\\(\"(.*?)\"\\))\n(summary.*?)\nplot\\(result", "\\1\\3\n\\5\nplot(\\4", .) %>%
gsub("result\\s*<-\\s*(repeater\\((.|\n)*?),\\s*name+\\s*=\\s*\"([^\"`]*?)\"([^\\)]*?)\\)", "\\3 <- \\1\\4)\nregister(\"\\3\")", .) %>%
gsub("(repeater\\((\n|.)*?)(register\\(\"(.*?)\"\\))\nsummary\\(result", "\\1\\3\nsummary(\\4", .) %>%
gsub("(repeater\\((\n|.)*?)(register\\(\"(.*?)\"\\))\n(summary.*?)\nplot\\(result", "\\1\\3\n\\5\nplot(\\4", .) %>%
gsub("repeater\\(((.|\n)*?),\\s*sim+\\s*=\\s*\"([^\"`]*?)\"([^\\)]*?)\\)", "repeater(\n \\3,\\1\\4)", .) %>%
gsub("(```\\{r.*?\\})(\nresult <- pivotr(\n|.)*?)(\\s*)store\\(result, name = \"(.*?)\"\\)", "\\1\\2\\4\\5 <- result$tab; register(\"\\5\")\\6", .) %>%
gsub("(```\\{r.*?\\})(\nresult <- explore(\n|.)*?)(\\s*)store\\(result, name = \"(.*?)\"\\)", "\\1\\2\\4\\5 <- result$tab; register(\"\\5\")\\6", .) %>%
gsub("store\\(result,\\s*name\\s*=\\s*\"(.*?)\",\\s*type\\s*=\\s*\"((P|I)W)\"\\)", "\\1 <- result$\\2; register(\"\\1\")", .)
})
removeModal()
fix_smart(report)
}
observeEvent(input$report_clean_r, {
shinyAce::updateAceEditor(
session, "r_edit",
value = report_clean(input$r_edit)
)
})
observeEvent(input$report_clean_rmd, {
shinyAce::updateAceEditor(
session, "rmd_edit",
value = report_clean(input$rmd_edit)
)
})
observeEvent(input$report_ignore, {
r_info[["report_ignore"]] <- TRUE
removeModal()
})
knit_it <- function(report, type = "rmd") {
report <- gsub("\r\n", "\n", report) %>%
gsub("\r", "\n", .)
if (type == "rmd") {
report <- gsub("\\\\\\\\\\s*\n", "\\\\\\\\\\\\\\\\\n", report)
}
if (
!isTRUE(r_info[["report_ignore"]]) &&
(grepl("\\s*r_data\\[\\[\".*?\"\\]\\]", report) ||
grepl("\\s*r_data\\$", report) ||
grepl("\n(\\
grepl("store\\(pred,\\s*data\\s*=\\s*\"", report) ||
grepl("\\s+data\\s*=\\s*\".*?\",", report) ||
grepl("\\s+dataset\\s*=\\s*\".*?\",", report) ||
grepl("\\s+pred_data\\s*=\\s*\"[^\"]+?\",", report) ||
grepl("result\\s*<-\\s*simulater\\(", report) ||
grepl("result\\s*<-\\s*repeater\\(", report) ||
grepl("combinedata\\(\\s*x\\s*=\\s*\"[^\"]+?\"", report) ||
grepl("formatnr\\(", report) ||
grepl("formatdf\\(", report) ||
grepl("rounddf\\(", report) ||
grepl("tabsort = \"desc\\(n\\)\"", report) ||
grepl("(mean_rm|median_rm|min_rm|max_rm|sd_rm|var_rm|sum_rm)", report))
) {
showModal(
modalDialog(
title = "The report contains deprecated code",
span("The use of, e.g., r_data[[...]]], dataset = \"...\", etc. in your report is
deprecated. Click the 'Clean report' button to remove references that are no
longer needed.", br(), br(), "Warning: It may not be possible to update all code
to the latest standard automatically. For example, the use of 'store(...)'
functions has changed and not all forms can be automatically updated. If this
applies to your report a message should be shown when you Knit the report
demonstrating how the code should be changed. You can, of course, also use the
browser interface to recreate the code you need or use the help function in R or
Rstudio for more information (e.g., ?radiant.model::store.model,
?radiant.model::store.model.predict, or ?radiant.model::simulater)", br(), br(),
"To avoid the code-cleaning step click 'Cancel' or, if you believe the code is
correct as-is, click the 'Ignore' button and continue to Knit your report"
),
footer = tagList(
modalButton("Cancel"),
actionButton("report_ignore", "Ignore", title = "Ignore cleaning popup", class = "btn-primary"),
actionButton(paste0("report_clean_", type), "Clean report", title = "Clean report", class = "btn-success")
),
size = "m",
easyClose = TRUE
)
)
return(invisible())
}
ldir <- getOption("radiant.launch_dir", default = radiant.data::find_home())
pdir <- getOption("radiant.project_dir", default = ldir)
tdir <- tempdir()
owd <- ifelse(radiant.data::is_empty(pdir), setwd(tdir), setwd(pdir))
on.exit(setwd(owd))
report <- sub("^---\n(.*?)\n---", "", report) %>%
sub("<!--(.*?)-->", "", .)
if (!grepl("```{r r_setup, include = FALSE}\n", report, fixed = TRUE)) {
report <- paste0("```{r knit_it_setup, include = FALSE}\noptions(width = 250, scipen = 100, max.print = 5000, stringsAsFactors = FALSE)\n```\n\n", report)
}
md <- knitr::knit(
text = report,
envir = r_data,
quiet = TRUE
)
md <- gsub("<p class=\"caption\">plot of chunk unnamed-chunk-[0-9]+</p>", "", md)
paste(
markdown::markdownToHTML(text = md, fragment.only = TRUE, stylesheet = ""),
paste0("<script type='text/javascript' src='", getOption("radiant.mathjax.path"), "/MathJax.js?config=TeX-AMS-MML_HTMLorMML'></script>"),
"<script>if (window.MathJax) MathJax.Hub.Typeset();</script>", sep = "\n"
) %>%
gsub("<table>", "<table class='table table-condensed table-hover'>", .) %>%
scrub() %>%
HTML()
}
sans_ext <- function(path) {
sub(
"(\\.state\\.rda|\\.rda$|\\.rds$|\\.rmd$|\\.r$|\\.rdata$|\\.html|\\.nb\\.html|\\.pdf|\\.docx|\\.pptx|\\.rmd|\\.zip)", "",
tolower(path), ignore.case = TRUE
)
}
report_name <- function(type = "rmd", out = "report", full.name = FALSE) {
ldir <- getOption("radiant.launch_dir", default = radiant.data::find_home())
pdir <- getOption("radiant.project_dir", default = ldir)
if (input[[paste0(type, "_generate")]] %in% c("To Rmd", "To R")) {
fn <- r_state[[paste0("radiant_", type, "_name")]]
} else {
fn <- ""
}
if (radiant.data::is_empty(fn)) {
fn <- state_name()
fn <- sans_ext(fn) %>%
sub("-state", paste0("-", out), .)
r_state[[paste0("radiant_", type, "_name")]] <<-
paste(fn, sep = ".", switch(
type,
rmd = "Rmd",
r = "R"
))
} else {
fn <- basename(fn) %>%
sans_ext()
}
if (full.name) {
file.path(pdir, fn)
} else {
fn
}
}
report_save_filename <- function(type = "rmd", full.name = TRUE) {
req(input[[paste0(type, "_generate")]])
if (input[[paste0(type, "_generate")]] %in% c("To Rmd", "To R")) {
cnt <- rstudio_context(type = type)
if (!radiant.data::is_empty(cnt$path)) {
if (cnt$path != cnt$rpath) {
r_state[[paste0("radiant_", type, "_name")]] <<- cnt$rpath
} else {
r_state[[paste0("radiant_", type, "_name")]] <<- cnt$path
}
if (full.name) {
fn <- cnt$path
} else {
fn <- cnt$base_name
}
} else {
fn <- report_name(type = type, full.name = full.name)
}
} else {
fn <- report_name(type = type, full.name = full.name)
}
fn <- sans_ext(fn)
paste(fn, sep = ".", switch(
input[[paste0(type, "_save_type")]],
Notebook = "nb.html",
HTML = "html",
PDF = "pdf",
Word = "docx",
Powerpoint = "pptx",
Rmd = "Rmd",
`Rmd + Data (zip)` = "zip",
R = "R",
`R + Data (zip)` = "zip"
))
}
report_save_content <- function(file, type = "rmd") {
if (isTRUE(getOption("radiant.report"))) {
isolate({
ldir <- getOption("radiant.launch_dir", default = radiant.data::find_home())
pdir <- getOption("radiant.project_dir", default = ldir)
tdir <- tempdir()
owd <- ifelse(radiant.data::is_empty(pdir), setwd(tdir), setwd(pdir))
on.exit(setwd(owd))
save_type <- input[[paste0(type, "_save_type")]]
generate <- input[[paste0(type, "_generate")]]
zip_info <- getOption("radiant.zip")
if (save_type %in% c("Rmd + Data (zip)", "R + Data (zip)")) {
if (radiant.data::is_empty(zip_info)) {
showModal(
modalDialog(
title = "ZIP attempt failed",
span(
"There is no zip utility in the path on this system. Please install a zip utility (e.g., 7-zip) and try again"
),
footer = modalButton("OK"),
size = "m",
easyClose = TRUE
)
)
return(invisible())
}
}
lib <- if ("radiant" %in% installed.packages()) "radiant" else "radiant.data"
if (generate %in% c("To Rmd", "To R")) {
cnt <- rstudio_context(type)
if (radiant.data::is_empty(cnt$path) || !cnt$ext == type) {
if (generate == "To Rmd") {
report <- "
} else {
report <- "
}
} else {
report <- cnt$content
}
} else {
report <- input[[paste0(type, "_edit")]]
}
if (save_type == "Rmd + Data (zip)") {
withProgress(message = "Preparing Rmd + Data zip file", value = 1, {
currdir <- setwd(tempdir())
save(list = ls(envir = r_data), envir = r_data, file = "r_data.rda")
setup_report(report, save_type = "Rmd", lib = lib) %>%
fix_smart() %>%
cat(file = "report.Rmd", sep = "\n")
zip(file, c("report.Rmd", "r_data.rda"),
flags = zip_info[1], zip = zip_info[2]
)
setwd(currdir)
})
} else if (save_type == "R + Data (zip)") {
withProgress(message = "Preparing R + Data zip file", value = 1, {
currdir <- setwd(tempdir())
save(list = ls(envir = r_data), envir = r_data, file = "r_data.rda")
cat(report, file = "report.R", sep = "\n")
zip(file, c("report.R", "r_data.rda"),
flags = zip_info[1], zip = zip_info[2]
)
setwd(currdir)
})
} else if (save_type == "Rmd") {
setup_report(report, save_type = "Rmd", lib = lib) %>%
fix_smart() %>%
cat(file = file, sep = "\n")
} else if (save_type == "R") {
cat(report, file = file, sep = "\n")
} else {
if (file.access(getwd(), mode = 2) == -1) {
showModal(
modalDialog(
title = "Working directory is not writable",
HTML(
paste0(
"<span>
The working directory used by radiant (\"", getwd(), "\") is not writable. This is required to save a report.
To save reports, restart radiant from a writable directory. Preferaby by setting up an Rstudio
project folder. See <a href='https://support.rstudio.com/hc/en-us/articles/200526207-Using-Projects' target='_blank'>
https://support.rstudio.com/hc/en-us/articles/200526207-Using-Projects</a> for more information
</span>"
)
),
footer = modalButton("OK"),
size = "m",
easyClose = TRUE
)
)
return(invisible())
}
options(radiant.rmarkdown = TRUE)
if (type == "r") {
report <- paste0("\n```{r echo = TRUE}\n", report, "\n```\n")
}
init <- setup_report(report, save_type = save_type, lib = lib) %>%
fix_smart()
withProgress(message = paste0("Saving report to ", save_type), value = 1, {
if (isTRUE(rmarkdown::pandoc_available())) {
tmp_fn <- tempfile(pattern = "report-", tmpdir = ".", fileext = ".Rmd")
cat(init, file = tmp_fn, sep = "\n")
if (!save_type %in% c("Notebook", "HTML")) {
oop <- knitr::opts_chunk$get()$screenshot.force
knitr::opts_chunk$set(screenshot.force = TRUE)
on.exit(knitr::opts_chunk$set(screenshot.force = oop))
}
out <- rmarkdown::render(
tmp_fn,
switch(
save_type,
Notebook = rmarkdown::html_notebook(highlight = "zenburn", theme = "cosmo", code_folding = "hide"),
HTML = rmarkdown::html_document(highlight = "zenburn", theme = "cosmo", code_download = TRUE, df_print = "paged"),
PDF = rmarkdown::pdf_document(),
Word = rmarkdown::word_document(
reference_docx = getOption("radiant.word_style", default = file.path(system.file(package = "radiant.data"), "app/www/style.docx")),
),
Powerpoint = rmarkdown::powerpoint_presentation(
reference_doc = getOption("radiant.powerpoint_style", default = file.path(system.file(package = "radiant.data"), "app/www/style.potx"))
)
),
envir = r_data, quiet = TRUE, encoding = "UTF-8",
output_options = list(pandoc_args = "--quiet")
)
file.copy(out, file, overwrite = TRUE)
file.remove(out, tmp_fn)
} else {
setup_report(report, add_yml = FALSE, type = save_type, lib = lib) %>%
fix_smart() %>%
knit_it_save() %>%
cat(file = file, sep = "\n")
}
})
options(radiant.rmarkdown = FALSE)
}
})
}
}
update_report <- function(
inp_main = "", fun_name = "", inp_out = list("", ""),
cmd = "", pre_cmd = "result <- ", post_cmd = "",
xcmd = "", outputs = c("summary", "plot"), inp = "result",
wrap, figs = TRUE, fig.width = 7, fig.height = 7
) {
if (missing(wrap)) {
lng <- nchar(pre_cmd) + nchar(fun_name) + nchar(post_cmd) + 2
if (!radiant.data::is_empty(inp_main)) {
lng <- lng + sum(nchar(inp_main)) +
sum(nchar(names(inp_main))) +
length(inp_main) * 5 - 1
}
wrap <- ifelse(lng > 70, TRUE, FALSE)
}
dctrl <- getOption("dctrl")
depr <- function(x, wrap = FALSE) {
cutoff <- ifelse (wrap, 20L, 55L)
for (i in names(x)) {
tmp <- x[[i]]
wco <- ifelse(max(nchar(tmp)) > cutoff, cutoff, 55L)
if (inherits(tmp, "fractions")) {
if (length(tmp) > 1) {
tmp <- paste0("c(", paste(tmp, collapse = ", "), ")")
} else {
tmp <- as.character(tmp)
}
} else {
tmp <- deparse(tmp, control = dctrl, width.cutoff = wco)
}
if ((nchar(i) + sum(nchar(tmp)) < 70) | (length(tmp) == 2 & tmp[2] == ")")) {
tmp <- paste0(tmp, collapse = "")
}
if (length(tmp) > 1) {
if (grepl("^c\\(", tmp[1])) {
tmp <- c("c(", sub("^c\\(", "", tmp))
} else {
tmp <- c("list(", sub("^list\\(", "", tmp))
}
if (tail(tmp, 1) != ")") {
tmp <- c(sub("\\)$", "", tmp), ")")
}
}
x[[i]] <- sub("^\\s+", "", tmp) %>%
paste0(collapse = "\n ") %>%
sub("[ ]+\\)", " \\)", .)
}
if (wrap) {
x <- paste0(paste0(paste0("\n ", names(x)), " = ", x), collapse = ", ")
x <- paste0("list(", x, "\n)")
} else {
x <- paste0(paste0(names(x), " = ", x), collapse = ", ")
x <- paste0("list(", x, ")")
}
x
}
if (inp_main[1] != "") {
cmd <- depr(inp_main, wrap = wrap) %>%
sub("list", fun_name, .) %>%
paste0(pre_cmd, .) %>%
paste0(., post_cmd) %>%
sub("dataset = \"([^\"]+)\"", "\\1", .)
}
lout <- length(outputs)
if (lout > 0) {
for (i in seq_len(lout)) {
if (inp %in% names(inp_out[[i]])) {
inp_rep <- inp
inp <- inp_out[[i]][[inp]]
inp_out[[i]][inp_rep] <- NULL
}
if (inp_out[i] != "" && length(inp_out[[i]]) > 0) {
if (sum(nchar(inp_out[[i]])) > 40L) {
cmd <- depr(inp_out[[i]], wrap = TRUE) %>%
sub("list\\(", paste0(outputs[i], "\\(\n ", inp, ", "), .) %>%
paste0(cmd, "\n", .)
} else {
cmd <- deparse(inp_out[[i]], control = dctrl, width.cutoff = 500L) %>%
sub("list\\(", paste0(outputs[i], "\\(", inp, ", "), .) %>%
paste0(cmd, "\n", .)
}
} else {
cmd <- paste0(cmd, "\n", outputs[i], "(", inp, ")")
}
}
}
if (xcmd != "") cmd <- paste0(cmd, "\n", xcmd)
if (length(input$rmd_generate) == 0) {
type <- ifelse(state_init("r_generate", "Use Rmd") == "Use Rmd", "rmd", "r")
} else {
type <- ifelse(state_init("rmd_generate", "auto") == "Use R", "r", "rmd")
}
if (type == "r") {
update_report_fun(cmd, type = "r")
} else {
if (figs) {
cmd <- paste0("\n```{r fig.width = ", round(7 * fig.width / 650, 2), ", fig.height = ", round(7 * fig.height / 650, 2), ", dpi = 96}\n", cmd, "\n```\n")
} else {
cmd <- paste0("\n```{r}\n", cmd, "\n```\n")
}
update_report_fun(cmd, type = "rmd")
}
}
update_report_fun <- function(cmd, type = "rmd", rfiles = FALSE) {
isolate({
generate <- paste0(type, "_generate")
sinit <- state_init(generate, "auto")
editor <- paste0(type, "_edit")
sel <- ifelse(type == "rmd", "Rmd", "R")
if (sinit == "manual") {
os_type <- Sys.info()["sysname"]
if (os_type == "Windows") {
withProgress(message = "Putting command in clipboard", value = 1, {
cat(cmd, file = "clipboard")
})
} else if (os_type == "Darwin") {
withProgress(message = "Putting command in clipboard", value = 1, {
out <- pipe("pbcopy")
cat(cmd, file = out)
close(out)
})
} else if (os_type == "Linux") {
showModal(
modalDialog(
title = "Copy-and-paste the code shown below",
pre(cmd),
footer = modalButton("Cancel"),
size = "m",
easyClose = TRUE
)
)
}
} else if (sinit == "To Rmd") {
withProgress(message = "Putting code chunk in Rstudio", value = 1, {
rstudioapi::insertText(Inf, fix_smart(cmd))
})
} else if (sinit == "To R") {
withProgress(message = "Putting R-code in Rstudio", value = 1, {
gsub("(```\\{.*\\}\n)|(```\n)", "", fix_smart(paste0("\n", cmd, "\n"))) %>%
rstudioapi::insertText(Inf, .)
})
} else {
if (radiant.data::is_empty(r_state[[editor]])) {
r_state[[editor]] <<- paste0("
} else {
r_state[[editor]] <<- paste0(fix_smart(r_state[[editor]]), "\n", cmd)
}
withProgress(message = paste0("Updating Report > ", sel), value = 1, {
shinyAce::updateAceEditor(
session, editor,
value = fix_smart(r_state[[editor]])
)
})
}
if (!rfiles) {
if (state_init(paste0(type, "_switch"), "switch") == "switch") {
updateTabsetPanel(session, "nav_radiant", selected = sel)
}
}
})
} |
suff.stat <-
function(ModelMatrix, Table)
{
nr <- nrow(ModelMatrix)
S <- rep(0,nr)
for( h in 1:nr)
{
S[h] <- (Table) %*% ModelMatrix[h,]
}
return(S)
} |
pick.model <- function(...) UseMethod("pick.model")
pick.model.HOF.list <- function(object, ...) {
out <- sapply(object, function(x) pick.model.HOF(object=x, ...))
return(out)
}
pick.model.HOF <- function (object, level = 0.95, test = c('AICc', 'BIC', 'AIC','Dev'), modeltypes, penal = 'df', gam = FALSE, selectMethod = c('bootselect.lower', 'bootselect.always', 'IC.weight', 'pick.model'), silent = FALSE, ...) {
selectMethod <- match.arg(selectMethod)
if(is.null(object$bootstrapmodels) & selectMethod != 'pick.model') {
if(getOption("eHOF.bootselectmessage")) {
message('Bootselect or IC.weight method only possible after bootstrapping.')
options(eHOF.bootselectmessage = FALSE)}
selectMethod <- 'pick.model'
}
test <- match.arg(test)
if(missing(modeltypes)) modeltypes <- eHOF.modelnames
if(length(penal)==1) {
penal <- switch(penal,
df= sapply(object$models, function(x) length(x$par)),
h = c(I=1, II=2, III=3, IV=4, V=5, VI=6, VII=7),
m = c(I=1, II=2, III=2, IV=3, V=4, VI=4, VII=5)
)
}
rejectedmodels <- sapply(object$models, function(x) is.na(x$deviance))
if(gam) {
gamfun <- function(x, bs = 'cr', k = -1, ...) gam(x$y ~ s(x$x, bs=bs, k=k),family = get(x$family), scale = 0, ...)
pg <- gamfun(object, ...)
object$models$GAM <- pg
modeltypes <- c(modeltypes, 'GAM')
if('GAM' %in% names(penal)) penal['GAM'] <- sum(pg$edf) else
penal <- c(penal, GAM=sum(pg$edf))
}
if (test == "AIC") {
k <- 2
p <- penal[match(names(penal), names(object$models))]
ic <- -2 * logLik(object) + k * p
ic <- ic[names(ic) %in% modeltypes]
model <- names(ic[!rejectedmodels])[which.min(ic[!rejectedmodels])]
}
if (test == "AICc") {
k <- 2
p <- penal[match(names(penal), names(object$models))]
ic <- -2 * logLik(object) + k * p + (2*k*(k + 1))/(object$nobs - k - 1)
ic <- ic[names(ic) %in% modeltypes]
model <- names(ic[!rejectedmodels])[which.min(ic[!rejectedmodels])]
}
if( test == 'BIC') {
k <- log(object$nobs)
p <- penal[match(names(penal), names(object$models))]
ic <- -2 * logLik(object) + k * p
ic <- ic[names(ic) %in% modeltypes]
model <- names(ic[!rejectedmodels])[which.min(ic[!rejectedmodels])]
}
if (test == "Dev") {
ic <- deviance(object)
ic <- ic[names(ic) %in% modeltypes]
model <- names(ic[!rejectedmodels])[which.min(ic[!rejectedmodels])]
}
if(selectMethod == 'bootselect.lower') {
modboot <- names(which.max(table(object$bootstrapmodels)))
if(eHOF.modelnames[match(modboot, eHOF.modelnames)] < eHOF.modelnames[match(model, eHOF.modelnames)] )
if(!silent) message(object$y.name, ': Most frequent bootstrap model (',modboot, ') lower than original choice (', model, ',', object$bootstraptest,') by ', test, ' test.', sep='')
if(!modboot %in% names(rejectedmodels)[rejectedmodels]) model <- modboot
}
if(selectMethod == 'bootselect.always') {
modboot <- names(which.max(table(object$bootstrapmodels)))
if(modboot != model )
if(!silent) message(object$y.name, ': Most frequent bootstrap model (',modboot, ') not equal to original choice (', model, ',', object$bootstraptest,') by ', test, ' test.', sep='')
if(!modboot %in% names(rejectedmodels)[rejectedmodels]) model <- modboot
}
if(selectMethod == 'IC.weights') {
dev <- deviance(object); ll <- logLik(object)
AICc <- -2 * ll + 2 * penal + 2 * penal *(penal + 1)/(object$nobs - penal - 1)
d.AICc <- AICc - min(AICc, na.rm=TRUE)
AICc.W <- round(exp(-0.5*AICc)/ sum(exp(-0.5*AICc), na.rm=TRUE),4)
model.weight <- names(which.max(AICc.W[!rejectedmodels]))
if(eHOF.modelnames[match(model.weight, eHOF.modelnames)] < eHOF.modelnames[match(model, eHOF.modelnames)]) {
if(!silent) message('Selection method: Highest ', test, ' weights.\n', object$y.name, ': Original model choice (', model, ') lower than the model with highest IC weight (', model.weight, ') is chosen instead.', sep='')
if(!model.weight %in% names(rejectedmodels)[rejectedmodels]) model <- model.weight
}
}
return(model)
} |
library(dynbenchmark)
library(png)
library(tidyverse)
library(GNG)
library(tidygraph)
library(ggraph)
experiment("manual_ti")
run_id <- "mds_robrechtc_1"
run <- read_rds(derived_file(paste0(run_id, ".rds")))
processed_file <- derived_file(c(run_id, '_run', '.png'))
processx::run(commandline=dynutils::pritt("inkscape -z {derived_file(c(run_id, '.svg'))} -e={processed_file} -d=100"))
png <- readPNG(processed_file)
red <- png[, , 1] - png[, , 2]
coordinates <- red %>%
reshape2::melt(varnames=c("y", "x"), value.var=value) %>%
as_tibble() %>%
filter(value > 0.5)
box_height <- dim(red)[[1]]/run$nrow
box_width <- dim(red)[[2]]/run$ncol
coordinates <- coordinates %>%
mutate(
col = floor((x-1)/box_width) + 1,
row = floor((y-1)/box_height),
box_id = (row * run$ncol) + col
)
coordinates %>% filter(y<200) %>% ggplot() + geom_point(aes(x, -y, color=factor(box_id)))
process_coordinates <- function(coordinates) {
data <- coordinates %>% select(x, y) %>% as.matrix()
result <- GNG::gng(data, max_nodes=50, assign_cluster=F)
graph <- result$edges %>% as_tbl_graph() %>%
activate(nodes) %>%
left_join(result$nodes %>% mutate(index=as.character(index)) %>% rename(id=name), by=c("name"="index")) %>%
left_join(result$node_space %>% as.data.frame() %>% tibble::rownames_to_column("id"), "id")
graph
}
coordinates_split <- coordinates %>% split(coordinates$box_id)
graphs <- tibble(graph = map(coordinates_split, process_coordinates), box_id = as.numeric(names(coordinates_split)))
graphs <- graphs %>% left_join(run$spaces, by="box_id")
map(graphs$graph[16:16], function(graph) {
ggraph(graph) +
geom_node_point() +
geom_edge_link()
}) %>% cowplot::plot_grid(plotlist=.)
merge_graph <- function(graph, max_dist) {
distances <- graph %>% activate(nodes) %>% as_tibble() %>% select(x, y) %>% as.matrix() %>% dist() %>% as.matrix()
rownames(distances) <- colnames(distances) <- graph %>% pull(name)
close <- distances < maxdist
n_close <- close %>% apply(1, sum)
close <- close[order(n_close, decreasing=T), order(n_close, decreasing=T)]
labels <- setNames(rownames(distances), rownames(distances))
for (i in rownames(close)) {
which_close <- names(which(close[i, ]))
close[which_close, ] <- FALSE
close[, which_close] <- FALSE
labels[which_close] <- i
}
nodes <- graph %>%
activate(nodes) %>%
as_tibble() %>%
mutate(new = labels) %>%
group_by(new) %>%
summarise(x = mean(x), y=mean(y)) %>%
rename(name=new)
edges <- graph %>%
activate(edges) %>%
as_tibble() %>%
mutate(from = labels[from], to = labels[to]) %>%
mutate(from = match(from, nodes$name), to = match(to, nodes$name)) %>%
filter(from!=to) %>%
mutate(fromto = map2_chr(from, to, ~paste0(sort(c(.x, .y)), collapse="
group_by(fromto) %>%
filter(row_number() == 1) %>%
ungroup()
new_graph <- tbl_graph(nodes, edges)
new_graph
}
maxdist <- box_width / 10
graphs$graph_merged <- map(graphs$graph, merge_graph, maxdist)
map(graphs$graph_merged[1:20], function(graph) {
ggraph(graph) +
geom_node_point() +
geom_edge_link()
}) %>% cowplot::plot_grid(plotlist=.)
global_x_scale <- 1.15
global_y_scale <- 1.15
scale_graph <- function(graph, box_id) {
space <- run$spaces %>% filter(box_id == !!box_id)
graph %>%
activate(nodes) %>%
mutate(
x = x - box_width * ((box_id-1) %% run$ncol),
y = y - box_height * floor((box_id-1) / run$ncol),
y = box_height - y,
x = x/box_width,
y = y/box_height
) %>%
mutate(
x = (x - 0.5) * global_x_scale + 0.5,
y = (y - 0.5) * global_y_scale + 0.5
) %>%
mutate(
x = x * space$x_scale + space$x_shift,
y = y * space$y_scale + space$y_shift
)
}
graphs$graph_scaled <- map2(graphs$graph_merged, graphs$box_id, scale_graph)
graphs[100:110, ] %>% pmap(function(graph_scaled, space, ...) {
ggraph(graph_scaled) +
geom_point(aes(Comp1, Comp2), data=space) +
geom_edge_link(edge_colour="darkred", edge_width=4)+
geom_node_point(color="red")
}) %>% cowplot::plot_grid(plotlist=.)
predictions_list <- graphs %>% pmap(function(box_id, graph_scaled, space, ...) {
print(box_id)
cluster_space <- graph_scaled %>%
activate(nodes) %>%
as_tibble() %>%
select(x, y) %>%
as.matrix()
rownames(cluster_space) <- seq_len(nrow(cluster_space))
cluster_network <- graph_scaled %>%
activate(edges) %>%
as_tibble() %>%
mutate_all(as.character) %>%
mutate(directed=F, length=1)
sample_space <- space %>% .[, c("Comp1", "Comp2")] %>% magrittr::set_colnames(c("x", "y")) %>% magrittr::set_rownames(space$cell_id)
out <- dynmethods:::project_cells_to_segments(cluster_network, cluster_space, sample_space)
wrap_prediction_model(
cell_ids = space$cell_id,
milestone_ids = out$milestone_ids,
milestone_network = out$milestone_network,
progressions = out$progressions,
space = out$space_df,
graph_scaled = graph_scaled
)
})
predictions <- tibble(prediction = predictions_list, dataset_id = graphs$id)
datasets <- read_rds(derived_file("datasets.rds", experiment_id="01-datasets/05-dataset_characterisation"))
datasets <- datasets %>% slice(match(run$spaces$id, id))
controls <- map(datasets %>% filter(dataset_group == "control" & id != "control_BA") %>% pull(id), function(dataset_id) {
print(dataset_id)
dataset <- extract_row_to_list(datasets, which(datasets$id == dataset_id))
dataset$geodesic_dist <- dynutils::compute_tented_geodesic_distances(dataset)
prediction <- extract_row_to_list(predictions, which(predictions$dataset_id == dataset_id))$prediction
prediction$geodesic_dist <- dynutils::compute_tented_geodesic_distances(prediction)
plot = dynplot::plot_default(prediction)
plot
tibble(
scores = dyneval::calculate_metrics(dataset, prediction, c("correlation", "edge_flip", "rf_mse"))$summary %>%
select(correlation, edge_flip) %>% list(),
plot = list(plot),
dataset_id = dataset_id
) %>% unnest(scores)
}) %>% bind_rows()
controls
predictions %>% write_rds(derived_file(pritt("predictions_{run$run_id}.rds")))
qsub:::rsync_remote(
remote_dest = "prism",
path_dest = derived_file() %>% gsub(dynbenchmark::get_dynbenchmark_folder(), qsub:::run_remote("echo $DYNBENCHMARK_PATH", "prism")$cmd_out, .),
remote_src = "",
path_src = derived_file()
) |
lsqnonlin <- function(fun, x0, options = list(), ...) {
stopifnot(is.numeric(x0))
opts <- list(tau = 1e-3,
tolx = 1e-8,
tolg = 1e-8,
maxeval = 700)
namedOpts <- match.arg(names(options), choices = names(opts),
several.ok = TRUE)
if (!is.null(names(options)))
opts[namedOpts] <- options
tau <- opts$tau
tolx <- opts$tolx
tolg <- opts$tolg
maxeval <- opts$maxeval
fct <- match.fun(fun)
fun <- function(x) fct(x, ...)
n <- length(x0)
m <- length(fun(x0))
x <- x0; r <- fun(x)
f <- 0.5 * sum(r^2); J <- jacobian(fun, x)
g <- t(J) %*% r; ng <- Norm(g, Inf)
A <- t(J) %*% J
mu <- tau * max(diag(A))
nu <- 2; nh <- 0
errno <- 0
k <- 1
while (k < maxeval) {
k <- k + 1
R <- chol(A + mu*eye(n))
h <- c(-t(g) %*% chol2inv(R))
nh <- Norm(h); nx <- tolx + Norm(x)
if (nh <= tolx * nx) {errno <- 1; break}
xnew <- x + h; h <- xnew - x
dL <- sum(h * (mu*h - g))/2
rn <- fun(xnew)
fn <- 0.5 * sum(rn^2); Jn <- jacobian(fun, xnew)
if (length(rn) != length(r)) {df <- f - fn
} else {df <- sum((r - rn) * (r + rn))/2}
if (dL > 0 && df > 0) {
x <- xnew; f <- fn; J <- Jn; r <- rn;
A <- t(J) %*% J; g <- t(J) %*% r; ng <- Norm(g,Inf)
mu <- mu * max(1/3, 1 - (2*df/dL - 1)^3); nu <- 2
} else {
mu <- mu*nu; nu <- 2*nu
}
if (ng <= tolg) { errno <- 2; break }
}
if (k >= maxeval) errno <- 3
errmess <- switch(errno,
"Stopped by small x-step.",
"Stopped by small gradient.",
"No. of function evaluations exceeded.")
return(list(x = c(xnew), ssq = sum(fun(xnew)^2), ng = ng, nh = nh,
mu = mu, neval = k, errno = errno, errmess = errmess))
}
lsqcurvefit <- function(fun, p0, xdata, ydata) {
stopifnot(is.function(fun), is.numeric(p0))
stopifnot(is.numeric(xdata), is.numeric(ydata))
if (length(xdata) != length(ydata))
stop("Aguments 'xdata', 'ydata' must have the same length.")
fn <- function(p, x) fun(p, xdata) - ydata
lsqnonlin(fn, p0)
} |
devtools::check_rhub(interactive = FALSE)
devtools::check_win_devel()
devtools::check_win_release()
devtools::check_win_oldrelease()
devtools::spell_check(use_wordlist = TRUE)
devtools::release_checks()
devtools::release() |
filter.variants <- function(
variants,
caller = c('vardict', 'ides', 'mutect', 'pgm', 'consensus', 'isis', 'varscan', 'lofreq'),
config.file = NULL,
verbose = FALSE
) {
caller <- match.arg(caller);
filters <- get.varitas.options(paste0('filters.', caller));
if( !in.varitas.options( paste0('filters.', caller) ) ) {
error.message <- paste('No filters found in VariTAS settings for variant caller', caller);
stop(error.message);
}
if( !is.data.frame(variants) ) {
stop('variants must be a data frame');
}
print(filters);
if( !is.null(config.file) ) {
config <- yaml::yaml.load_file(config.file);
config$pkgname <- get.varitas.options('pkgname');
options(varitas = config);
}
names(variants) <- stringr::str_replace(
names(variants),
pattern = 'TUMOR',
replacement = 'TUMOUR'
);
old.names <- names(variants);
names(variants) <- gsub('.DEPTH', '.DP', names(variants));
paired <- FALSE;
if( any(grepl('NORMAL', names(variants))) ) {
paired <- TRUE;
}
filtered.variants <- variants;
if(verbose) {
cat('\nApplying filters to', nrow(variants), 'calls from', caller, '\n');
}
if( 'min_tumour_variant_reads' %in% names(filters) ) {
tumour.af <- mean.field.value(filtered.variants, field = 'TUMOUR.AF', caller = caller);
tumour.dp <- mean.field.value(filtered.variants, field = 'TUMOUR.DP', caller = caller);
passed.filter <- (tumour.dp*tumour.af >= filters$min_tumour_variant_reads) | is.na(tumour.dp*tumour.af);
filtered.variants <- filtered.variants[passed.filter, ];
if(verbose) {
cat('Applied min_tumour_variant_reads filter, and removed', sum(!passed.filter), 'variants\n');
}
}
if( paired && 'max_normal_variant_reads' %in% names(filters) && caller != 'lofreq' ) {
normal.af <- mean.field.value(filtered.variants, field = 'NORMAL.AF', caller = caller);
normal.dp <- mean.field.value(filtered.variants, field = 'NORMAL.DP', caller = caller);
passed.filter <- (normal.dp*normal.af <= filters$max_normal_variant_reads) | is.na(normal.dp*normal.af);
filtered.variants <- filtered.variants[passed.filter, ];
if(verbose) {
cat('Applied max_normal_variant_reads filter, and removed', sum(!passed.filter), 'variants\n');
}
}
if( 'min_tumour_depth' %in% names(filters) ) {
tumour.dp <- mean.field.value(filtered.variants, field = 'TUMOUR.DP', caller = caller);
passed.filter <- (tumour.dp >= filters$min_tumour_depth) | is.na(tumour.dp);
filtered.variants <- filtered.variants[passed.filter, ];
if(verbose) {
cat('Applied min_tumour_depth filter, and removed', sum(!passed.filter), 'variants\n');
}
}
if( paired && 'min_normal_depth' %in% names(filters) ) {
normal.dp <- mean.field.value(filtered.variants, field = 'NORMAL.DP', caller = caller);
passed.filter <- (normal.dp >= filters$min_normal_depth) | is.na(normal.dp);
filtered.variants <- filtered.variants[passed.filter, ];
if(verbose) {
cat('Applied min_normal_depth filter, and removed', sum(!passed.filter), 'variants\n');
}
}
if( 'min_tumour_allele_frequency' %in% names(filters) ) {
tumour.af <- mean.field.value(filtered.variants, field = 'TUMOUR.AF', caller = caller);
passed.filter <- (tumour.af >= filters$min_tumour_allele_frequency) | is.na(tumour.af);
filtered.variants <- filtered.variants[passed.filter, ];
if(verbose) {
cat('Applied min_tumour_allele_frequency filter, and removed', sum(!passed.filter), 'variants\n');
}
}
if( paired && 'max_normal_allele_frequency' %in% names(filters) && caller != 'lofreq' ) {
normal.af <- mean.field.value(filtered.variants, field = 'NORMAL.AF', caller = caller);
passed.filter <- (normal.af <= filters$max_normal_allele_frequency) | is.na(normal.af);
filtered.variants <- filtered.variants[passed.filter, ];
if(verbose) {
cat('Applied max_normal_allele_frequency filter, and removed', sum(!passed.filter), 'variants\n');
}
}
if( 'indel_min_tumour_allele_frequency' %in% names(filters) ) {
mutation.type <- classify.variant(ref = filtered.variants$REF, alt = filtered.variants$ALT);
tumour.af <- mean.field.value(filtered.variants, field = 'TUMOUR.AF', caller = caller);
passed.filter <- ('indel' != mutation.type) | tumour.af >= filters$indel_min_tumour_allele_frequency | is.na(tumour.af);
filtered.variants <- filtered.variants[passed.filter, ];
if(verbose) {
cat('Applied indel_min_tumour_allele_frequency filter, and removed', sum(!passed.filter), 'variants\n');
}
}
if( 'min_quality' %in% names(filters) ) {
qual <- mean.field.value(filtered.variants, field = 'QUAL', caller = caller);
passed.filter <- (qual >= filters$min_quality) | is.na(qual);
filtered.variants <- filtered.variants[passed.filter, ];
if(verbose) {
cat('Applied min_quality filter, and removed', sum(!passed.filter), 'variants\n');
}
}
if( 'ct_min_tumour_allele_frequency' %in% names(filters) ) {
tumour.af <- mean.field.value(filtered.variants, field = 'TUMOUR.AF', caller = caller);
base.substitutions <- get.base.substitution(ref = filtered.variants$REF, alt = filtered.variants$ALT);
base.substitutions[ is.na(base.substitutions) ] <- '';
passed.filter <- (base.substitutions != 'C>T') | (tumour.af >= filters$ct_min_tumour_allele_frequency) | is.na(tumour.af);
filtered.variants <- filtered.variants[passed.filter, ];
if(verbose) {
cat('Applied ct_min_tumour_allele_frequency filter, and removed', sum(!passed.filter), 'variants\n');
}
}
if( 'remove_1000_genomes' %in% names(filters) && filters$remove_1000_genomes ) {
if( sum(grepl('1000g', names(variants) )) > 1 ) {
stop('More than one column matching 1000g found.');
}
passed.filter <- '.' == filtered.variants[ , grepl('1000g', names(variants))];
filtered.variants <- filtered.variants[passed.filter, ];
if(verbose) {
cat('Applied remove_1000_genomes filter, and removed', sum(!passed.filter), 'variants\n');
}
}
if( 'remove_exac' %in% names(filters) && filters$remove_exac ) {
if( sum(grepl('^ExAC', names(variants) )) > 1 ) {
stop('More than one column matching ExAC found.');
}
passed.filter <- '.' == filtered.variants[ , grepl('^ExAC', names(variants))] | as.numeric(filtered.variants[ , grepl('^ExAC', names(variants))]) < 0.01;
filtered.variants <- filtered.variants[passed.filter, ];
if(verbose) {
cat('Applied remove_exac filter, and removed', sum(!passed.filter), 'variants\n');
}
}
if( 'remove_germline_status' %in% names(filters) && filters$remove_germline_status ) {
status.columns <- grepl('STATUS$', names(filtered.variants));
if( 1 == sum(status.columns) ) {
passed.filter <- is.na(filtered.variants[, status.columns]) | filtered.variants[, status.columns] != 'Germline';
filtered.variants <- filtered.variants[passed.filter, ];
}
if(verbose) {
cat('Applied remove_germline_status filter, and removed', sum(!passed.filter), 'variants\n');
}
}
names(filtered.variants) <- old.names;
return(filtered.variants);
} |
library(tinytest)
library(ggiraph)
library(ggplot2)
library(xml2)
source("setup.R")
{
eval(test_geom_layer, envir = list(name = "geom_bar_interactive"))
} |
image_modify_rgb_v=function(x, fun_r=NULL, fun_g=NULL, fun_b=NULL,
alpha=FALSE, rescale_v=NULL, result="magick", res=144){
stopifnot(result %in% c("magick", "raster"))
if ( ! grepl("magick", class(x)[1])) stop("x must be a picture read into R by magick::image_read.")
x=as.raster(x)
nrpic=nrow(x)
ncpic=ncol(x)
x=as.character(x)
vv=farver::get_channel(x, channel="v", space="hsv")/360
if (!is.null(rescale_v)) vv=RESCALE_FUN_VEC(vv, para=rescale_v)
if ( ! is.null(fun_r)){
rr=farver::get_channel(x, channel="r", space="rgb")
if (is.function(fun_r)){
rr=rr*(1+(match.fun(fun_r)(vv)-vv))
} else if (is.list(fun_r)){
rr=rr*(1+(USE_INTERNAL_CURVE(vv, LIST=fun_r, cat_text=NULL)-vv))
}
x=farver::set_channel(x, channel="r", value=rr, space="rgb")
rr=NULL
}
if ( ! is.null(fun_g)){
gg=farver::get_channel(x, channel="g", space="rgb")
if (is.function(fun_g)){
gg=gg*(1+(match.fun(fun_g)(vv)-vv))
} else if (is.list(fun_g)){
gg=gg*(1+(USE_INTERNAL_CURVE(vv, LIST=fun_g, cat_text=NULL)-vv))
}
x=farver::set_channel(x, channel="g", value=gg, space="rgb")
gg=NULL
}
if ( ! is.null(fun_b)){
bb=farver::get_channel(x, channel="b", space="rgb")
if (is.function(fun_b)){
bb=bb*(1+(match.fun(fun_b)(vv)-vv))
} else if (is.list(fun_b)){
bb=bb*(1+(USE_INTERNAL_CURVE(vv, LIST=fun_b, cat_text=NULL)-vv))
}
x=farver::set_channel(x, channel="b", value=bb, space="rgb")
bb=NULL
}
x=matrix(x, nrow=nrpic, byrow=TRUE)
if (result=="raster"){
return(x)
} else {
magick::image_read(x)
}
} |
context("test-weigted.R")
test_that("test of frequency method", {
expect_equal(flag_weighted(1, data.frame(f=c("pe","b","p","p","u","e","d"),stringsAsFactors = F), data.frame(w=c(10,3,7,12,31,9,54))),c("d","54"))
expect_equal(flag_weighted(1, data.frame(f=c("pe","b","p","p","up","e","d"),stringsAsFactors = F), data.frame(w=c(10,3,7,12,31,9,54))),c("p","60"))
expect_equal(flag_weighted(1, data.frame(f=c(NA,NA,NA,NA),stringsAsFactors = F), data.frame(w=c(NA,NA,NA,NA))),c(NA,NA))
expect_equal(flag_weighted(1, data.frame(f=c(NA,"b",NA,NA),stringsAsFactors = F), data.frame(w=c(NA,NA,NA,NA))),c(NA,NA))
expect_equal(flag_weighted(1, data.frame(f=c(NA,"b",NA,"b"),stringsAsFactors = F), data.frame(w=c(NA,NA,NA,8))),c("b","8"))
expect_equal(flag_weighted(1, data.frame(f=c(NA,"bd",NA,NA),stringsAsFactors = F), data.frame(w=c(NA,9,NA,7))),c("b, d","9"))
expect_equal(flag_weighted(1, data.frame(f=c(NA,"bd",NA,"be"),stringsAsFactors = F), data.frame(w=c(NA,9,NA,7))),c("b","16"))
expect_equal(flag_weighted(1, data.frame(f=c(NA,"bde",NA,NA),stringsAsFactors = F), data.frame(w=c(NA,10,NA,7))),c("b, d, e","10"))
expect_equal(flag_weighted(1, data.frame(f=c(NA,"bd",NA,"d"),stringsAsFactors = F), data.frame(w=c(NA,9,NA,7))),c("d","16"))
expect_equal(flag_weighted(1, data.frame(f=c(NA,"bde","deu","peb"),stringsAsFactors = F), data.frame(w=c(NA,9,5,7))),c("e","21"))
expect_equal(flag_weighted(1, data.frame(f=c(NA,"bde","deu","peb"),stringsAsFactors = F), data.frame(w=c(NA,9,5,NA))),c("d, e","14"))
}) |
simSettNum <- 2
compileCode <- TRUE
library(rstan) ; library(HRW)
nWarm <- 10000
nKept <- 10000
nThin <- 10
if (simSettNum == 1)
{
n <- 500
fTrue <- function(x)
return(sin(4*pi*x^2))
muXTrue <- 0.5 ; sigmaXTrue <- 1/6
sigmaEpsTrue <- sqrt(0.35)
phiTrue <- c(3,-3)
}
if (simSettNum == 2)
{
n <- 1000
fTrue <- function(x)
return(3*exp(-78*(x-0.38)^2)+exp(-200*(x-0.75)^2) - x)
muXTrue <- 0.5 ; sigmaXTrue <- 1/6
sigmaEpsTrue <- 0.35
phiTrue <- c(2.95,-2.95)
}
set.seed(2)
x <- rnorm(n,muXTrue,sigmaXTrue)
probxObs <- 1/(1+exp(-(phiTrue[1]+phiTrue[2]*x)))
indicxObsTmp <- rbinom(n,1,probxObs)
xObs <- x[indicxObsTmp == 1]
nObs <- length(xObs)
yxObs <- fTrue(xObs) + sigmaEpsTrue*rnorm(nObs)
indicxObs <- rep(1,nObs)
xUnobsTrue <- x[indicxObsTmp == 0]
nUnobs <- length(xUnobsTrue)
yxUnobs <- fTrue(xUnobsTrue) + sigmaEpsTrue*rnorm(nUnobs)
indicxUnobs <- rep(0,nUnobs)
r <- c(indicxObs,indicxUnobs)
ncZ <- 30
knots <- seq(min(xObs),max(xObs),length = (ncZ+2))[-c(1,ncZ+2)]
ZxObs <- outer(xObs,knots,"-")
ZxObs <- ZxObs*(ZxObs>0)
npRegMNARModel <-
'data
{
int<lower=1> nObs; int<lower=1> nUnobs;
int<lower=1> n; int<lower=1> ncZ;
vector[nObs] yxObs; vector[nUnobs] yxUnobs;
vector[nObs] xObs;
vector[ncZ] knots; matrix[nObs,ncZ] ZxObs;
int<lower=0,upper=1> r[n];
real<lower=0> sigmaBeta; real<lower=0> sigmaMu;
real<lower=0> sigmaPhi;
real<lower=0> Ax; real<lower=0> Aeps;
real<lower=0> Au;
}
transformed data
{
vector[n] y;
for (i in 1:nObs)
y[i] = yxObs[i];
for (i in 1:nUnobs)
y[i+nObs] = yxUnobs[i];
}
parameters
{
vector[2] beta; vector[ncZ] u;
vector[2] phi;
real muX; real<lower=0> sigmaX;
real<lower=0> sigmaEps; real<lower=0> sigmaU;
real xUnobs[nUnobs];
}
transformed parameters
{
matrix[n,2] X; matrix[n,ncZ] Z;
for (i in 1:nObs)
{
X[i,1] = 1 ; X[i,2] = xObs[i] ;
Z[i] = ZxObs[i];
}
for (i in 1:nUnobs)
{
X[i+nObs,1] = 1 ; X[i+nObs,2] = xUnobs[i];
for (k in 1:ncZ)
Z[i+nObs,k] = (xUnobs[i]-knots[k])*step(xUnobs[i]-knots[k]);
}
}
model
{
y ~ normal(X*beta+Z*u,sigmaEps);
r ~ bernoulli_logit(X*phi);
col(X,2) ~ normal(muX,sigmaX);
u ~ normal(0,sigmaU) ; beta ~ normal(0,sigmaBeta);
muX ~ normal(0,sigmaMu); phi ~ normal(0,sigmaPhi);
sigmaX ~ cauchy(0,Ax);
sigmaEps ~ cauchy(0,Aeps); sigmaU ~ cauchy(0,Au);
}'
allData <- list(nObs = nObs,nUnobs = nUnobs,n = (nObs+nUnobs),
ncZ = ncZ,xObs = xObs,yxObs = yxObs,yxUnobs = yxUnobs,knots = knots,
ZxObs = ZxObs,r = r,sigmaMu = 1e5,sigmaBeta = 1e5,sigmaPhi = 1e5,
sigmaEps = 1e5,sigmaX = 1e5,Ax = 1e5,Aeps = 1e5,Au = 1e5)
if (compileCode)
stanCompilObj <- stan(model_code = npRegMNARModel,data = allData,
iter = 1,chains = 1)
stanObj <- stan(model_code = npRegMNARModel,data = allData,warmup = nWarm,
iter = (nWarm + nKept),chains = 1,thin = nThin,refresh = 25,
fit = stanCompilObj)
betaMCMC <- NULL
for (j in 1:2)
{
charVar <- paste("beta[",as.character(j),"]",sep = "")
betaMCMC <- rbind(betaMCMC,extract(stanObj,charVar,permuted = FALSE))
}
uMCMC <- NULL
for (k in 1:ncZ)
{
charVar <- paste("u[",as.character(k),"]",sep = "")
uMCMC <- rbind(uMCMC,extract(stanObj,charVar,permuted = FALSE))
}
muXMCMC <- as.vector(extract(stanObj,"muX",permuted = FALSE))
sigmaXMCMC <- as.vector(extract(stanObj,"sigmaX",permuted = FALSE))
sigmaEpsMCMC <- as.vector(extract(stanObj,"sigmaEps",permuted = FALSE))
sigmaUMCMC <- as.vector(extract(stanObj,"sigmaU",permuted = FALSE))
phiMCMC <- NULL
for (j in 1:2)
{
charVar <- paste("phi[",as.character(j),"]",sep = "")
phiMCMC <- rbind(phiMCMC,extract(stanObj,charVar,permuted = FALSE))
}
xUnobsMCMC <- NULL
for (i in 1:nUnobs)
{
charVar <- paste("xUnobs[",as.character(i),"]",sep = "")
xUnobsMCMC <- rbind(xUnobsMCMC,extract(stanObj,charVar,permuted = FALSE))
}
cexVal <- 0.3
obsCol <- "darkblue" ; misCol <- "lightskyblue"
estFunCol <- "darkgreen"; trueFunCol <- "indianred3"
varBandCol <- "palegreen"
ng <- 101
xg <- seq(min(x),max(x),length = ng)
Xg <- cbind(rep(1,ng),xg)
Zg <- outer(xg,knots,"-")
Zg <- Zg*(Zg>0)
fMCMC <- Xg%*%betaMCMC + Zg%*%uMCMC
credLower <- apply(fMCMC,1,quantile,0.025)
credUpper <- apply(fMCMC,1,quantile,0.975)
fg <- apply(fMCMC,1,mean)
par(mfrow = c(1,1),mai = c(1.02,0.82,0.82,0.42))
plot(xg,fg,type = "n",bty = "l",xlab = "x",ylab = "y",xlim = range(c(xObs,xUnobsTrue)),
ylim = range(c(yxObs,yxUnobs)))
polygon(c(xg,rev(xg)),c(credLower,rev(credUpper)),col = varBandCol,border = FALSE)
lines(xg,fg,lwd = 2,col = estFunCol)
lines(xg,fTrue(xg),lwd = 2,col = trueFunCol)
points(xObs,yxObs,col = obsCol,cex = cexVal)
points(xUnobsTrue,yxUnobs,col = misCol,cex = cexVal)
legend(0.75,1.5,c("fully observed","x value unobserved"),col = c(obsCol,misCol),
pch = rep(1,2),pt.lwd = rep(2,2))
legend(0.467,-1.2,c("true f","estimated f"),col = c(trueFunCol,estFunCol),
lwd = rep(2,2))
indQ1 <- length(xg[xg <= quantile(xObs,0.25)])
fQ1MCMC <- fMCMC[indQ1,]
indQ2 <- length(xg[xg <= quantile(xObs,0.50)])
fQ2MCMC <- fMCMC[indQ2,]
indQ3 <- length(xg[xg <= quantile(xObs,0.75)])
fQ3MCMC <- fMCMC[indQ3,]
parms <- list(cbind(muXMCMC,sigmaXMCMC,sigmaEpsMCMC,phiMCMC[1,],phiMCMC[2,],
fQ1MCMC,fQ2MCMC,fQ3MCMC))
parNamesVal <- list(c(expression(mu[x])),c(expression(sigma[x])),
c(expression(sigma[epsilon])),
c(expression(phi[0])),c(expression(phi[1])),
c("first quartile","of x"),
c("second quart.","of x"),
c("third quartile","of x"))
summMCMC(parms,parNames = parNamesVal,numerSummCex = 1,
KDEvertLine = FALSE,addTruthToKDE = c(muXTrue,sigmaXTrue,sigmaEpsTrue,
phiTrue[1],phiTrue[2],fTrue(xg[indQ1]),
fTrue(xg[indQ2]),fTrue(xg[indQ3])))
parms <- list(t(xUnobsMCMC[1:5,]))
parNamesVal <- list(c(expression(x[1]^{"unobs"})),
c(expression(x[2]^{"unobs"})),
c(expression(x[3]^{"unobs"})),
c(expression(x[4]^{"unobs"})),
c(expression(x[5]^{"unobs"})))
summMCMC(parms,parNames = parNamesVal,KDEvertLine = FALSE,addTruthToKDE = x[1:5]) |
testthat::context('check_attach')
testthat::describe('test check attach',{
testthat::skip_on_ci()
nenv <- new.env()
sinew:::check_attach('testthat::test_dir',nenv)
it('already loaded',testthat::expect_true(length(ls(nenv))==0))
unloadNamespace('ggplot2')
sinew:::check_attach('ggplot2::aes',nenv)
it('not already loaded',testthat::expect_true('package:ggplot2'%in%nenv$toUnload))
}) |
"sumpos" <-
function(v){sum(v[v>0])} |
test_that("tuneIrace", {
rdesc = makeResampleDesc("Holdout", stratify = TRUE, split = 0.1)
ps1 = makeParamSet(
makeNumericParam("cp", lower = 0.001, upper = 1),
makeIntegerParam("minsplit", lower = 1, upper = 10)
)
n = 100
ctrl = makeTuneControlIrace(
maxExperiments = n, nbIterations = 1L,
minNbSurvival = 1)
tr1 = tuneParams(makeLearner("classif.rpart"), multiclass.task, rdesc,
par.set = ps1, control = ctrl)
expect_true(getOptPathLength(tr1$opt.path) >= 10 &&
getOptPathLength(tr1$opt.path) <= n)
expect_number(tr1$y, lower = 0, upper = 0.3)
ps2 = makeParamSet(
makeNumericParam("C", lower = -5, upper = 5, trafo = function(x) 2^x),
makeNumericParam("sigma", lower = -5, upper = 5, trafo = function(x) 2^x)
)
n = 20
ctrl = makeTuneControlIrace(
maxExperiments = n, nbIterations = 1L,
minNbSurvival = 1)
tr2 = tuneParams(makeLearner("classif.ksvm"), multiclass.task, rdesc,
par.set = ps2, control = ctrl, measures = acc)
expect_true(getOptPathLength(tr2$opt.path) >= 10 &&
getOptPathLength(tr2$opt.path) <= n)
expect_number(tr2$y, lower = 0.8, upper = 1)
})
test_that("tuneIrace works with dependent params", {
ps = makeParamSet(
makeDiscreteParam("kernel", values = c("vanilladot", "rbfdot")),
makeNumericParam("sigma",
lower = 1, upper = 2,
requires = quote(kernel == "rbfdot"))
)
lrn = makeLearner("classif.ksvm")
rdesc = makeResampleDesc("Holdout")
ctrl = makeTuneControlIrace(
maxExperiments = 40, nbIterations = 2L,
minNbSurvival = 1)
tr = tuneParams(lrn, multiclass.task, rdesc, par.set = ps, control = ctrl)
expect_true(getOptPathLength(tr$opt.path) >= 20 &&
getOptPathLength(tr$opt.path) <= 100)
expect_true(!is.na(tr$y))
ps = makeParamSet(
makeNumericParam("C", lower = -12, upper = 12, trafo = function(x) 2^x),
makeDiscreteParam("kernel", values = c("vanilladot", "polydot", "rbfdot")),
makeNumericParam("sigma",
lower = -12, upper = 12, trafo = function(x) 2^x,
requires = quote(kernel == "rbfdot")),
makeIntegerParam("degree",
lower = 2L, upper = 5L,
requires = quote(kernel == "polydot"))
)
ctrl = makeTuneControlRandom(maxit = 5L)
rdesc = makeResampleDesc("Holdout")
res = tuneParams("classif.ksvm", sonar.task, rdesc,
par.set = ps,
control = ctrl)
})
test_that("tuneIrace works with logical params", {
ps = makeParamSet(
makeLogicalParam("scaled"),
makeLogicalParam("shrinking")
)
lrn = makeLearner("classif.ksvm", kernel = "vanilladot")
rdesc = makeResampleDesc("Holdout", split = 0.3, stratify = TRUE)
ctrl = makeTuneControlIrace(
maxExperiments = 20, nbIterations = 1,
minNbSurvival = 1)
task = subsetTask(multiclass.task, c(1:10, 50:60, 100:110))
tr = tuneParams(lrn, task, rdesc, par.set = ps, control = ctrl)
expect_true(getOptPathLength(tr$opt.path) >= 15 &&
getOptPathLength(tr$opt.path) <= 20)
expect_true(!is.na(tr$y))
lrn2 = makeTuneWrapper(lrn, rdesc, par.set = ps, control = ctrl)
z = holdout(lrn2, task, split = 0.5, stratify = TRUE)
expect_true(getOptPathLength(tr$opt.path) >= 15 &&
getOptPathLength(tr$opt.path) <= 20)
expect_true(!is.na(tr$y))
})
test_that("tuneIrace works with tune.threshold", {
rdesc = makeResampleDesc("Holdout", stratify = TRUE, split = 0.1)
ps = makeParamSet(makeIntegerParam("minsplit", lower = 1, upper = 3))
n = 20
ctrl = makeTuneControlIrace(
maxExperiments = n, nbIterations = 1L,
minNbSurvival = 1)
expect_silent(tuneParams("classif.rpart", multiclass.task, rdesc,
par.set = ps,
control = ctrl))
})
test_that("tuneIrace uses digits", {
rdesc = makeResampleDesc(method = "Holdout")
ctrl = makeTuneControlIrace(maxExperiments = 30L, nbIterations = 1L)
ps = makeParamSet(makeNumericParam("shrinkage",
lower = pi * 1e-20,
upper = 5.242e12))
lrn.tune = makeTuneWrapper("classif.gbm",
resampling = rdesc, par.set = ps,
control = ctrl, show.info = FALSE)
res = suppressWarnings(resample(lrn.tune, task = multiclass.task, rdesc))
lrn = makeLearner("classif.rpart")
ctrl = makeTuneControlIrace(
maxExperiments = 30L, nbIterations = 1L,
digits = 5L)
ps = makeParamSet(makeNumericParam("cp", lower = 1e-5, upper = 1e-4))
lrn.tune = makeTuneWrapper(lrn,
resampling = rdesc, par.set = ps,
control = ctrl, show.info = FALSE)
res = resample(lrn.tune, task = multiclass.task, rdesc)
ctrl = makeTuneControlIrace(maxExperiments = 60L, digits = 4)
ps = makeParamSet(makeNumericParam("cp", lower = 1e-5, upper = 1e-4))
lrn.tune = makeTuneWrapper(lrn,
resampling = rdesc, par.set = ps,
control = ctrl, show.info = FALSE)
expect_error(resample(lrn.tune, task = multiclass.task, rdesc))
ctrl = makeTuneControlIrace(maxExperiments = 60L, digits = "a")
ps = makeParamSet(makeNumericParam("cp", lower = 1e-5, upper = 1e-2))
lrn.tune = makeTuneWrapper(lrn,
resampling = rdesc, par.set = ps,
control = ctrl, show.info = FALSE)
expect_error(resample(lrn.tune, task = multiclass.task, rdesc))
ctrl = makeTuneControlIrace(maxExperiments = 60L, digits = c(6L, 7L))
ps = makeParamSet(makeNumericParam("cp", lower = 1e-5, upper = 1e-2))
lrn.tune = makeTuneWrapper(lrn,
resampling = rdesc, par.set = ps,
control = ctrl, show.info = FALSE)
expect_error(resample(lrn.tune, task = multiclass.task, rdesc))
})
test_that("makeTuneControlIrace handles budget parameter", {
rdesc = makeResampleDesc("Holdout", stratify = TRUE, split = 0.1)
ps = makeParamSet(makeIntegerParam("minsplit", lower = 1, upper = 3))
n = 20
expect_error(makeTuneControlIrace(
budget = n, nbIterations = 1L,
minNbSurvival = 1, maxExperiments = n + 2L))
expect_error(makeTuneControlIrace(
budget = n + 2L, nbIterations = 1L,
minNbSurvival = 1, maxExperiments = n))
ctrl = makeTuneControlIrace(
budget = n, nbIterations = 1L, minNbSurvival = 1,
maxExperiments = n)
tr1 = tuneParams(makeLearner("classif.rpart"), multiclass.task, rdesc,
par.set = ps, control = ctrl)
expect_true(getOptPathLength(tr1$opt.path) <= n)
})
test_that("Error in hyperparameter tuning with scientific notation for lower/upper boundaries
ps = makeParamSet(makeNumericParam("shrinkage", lower = 4e-5, upper = 1e-4))
ctrl = makeTuneControlIrace(maxExperiments = 30L, nbIterations = 1L)
rdesc = makeResampleDesc(method = "Holdout")
lrn.tune = makeTuneWrapper("classif.gbm",
resampling = rdesc, par.set = ps,
control = ctrl)
expect_silent(resample(lrn.tune, task = sonar.task, rdesc))
})
test_that("irace works with unnamed discrete values", {
lrn = makeLearner("classif.rpart")
ctrl = makeTuneControlIrace(maxExperiments = 30L, nbIterations = 1L)
ps = makeParamSet(
makeDiscreteParam("minsplit", c(2L, 7L))
)
expect_silent(tuneParams(lrn, multiclass.task, hout,
par.set = ps,
control = ctrl))
})
test_that("irace handles parameters with unsatisfiable requirement gracefully", {
skip_on_os("windows")
lrn = makeLearner("classif.J48")
ctrl = makeTuneControlIrace(
maxExperiments = 20L, nbIterations = 1L,
minNbSurvival = 1L)
ps = makeParamSet(
makeNumericParam("C", 0.1, 0.3, requires = quote(R != R)),
makeLogicalParam("R"))
res = tuneParams(lrn, pid.task, hout, par.set = ps, control = ctrl)
ps = makeParamSet(
makeNumericParam("C", 0.1, 0.3),
makeLogicalParam("R", requires = quote(C > 1)))
expect_silent(tuneParams(lrn, sonar.task, hout, par.set = ps, control = ctrl))
}) |
expected <- eval(parse(text="integer(0)"));
test(id=0, code={
argv <- eval(parse(text="list(TRUE, FALSE, structure(numeric(0), .Dim = c(0L, 0L), .Dimnames = list(NULL, NULL)))"));
.Internal(order(argv[[1]], argv[[2]], argv[[3]]));
}, o=expected); |
dic_order <- function(x, dic, type) {
if (!tibble::is_tibble(dic)) dic <- get_eurostat_dic(dic)
n_type <- match(type, c("code", "label"))
if (is.na(n_type)) stop("Invalid type.")
y <- order(match(x, dic[[n_type]]))
if (any(is.na(y))) stop("All orders were not found.")
y
} |
library(fda)
data(package='fda')
help.start()
daybasis65 = create.fourier.basis(c(0,365), 65)
coefmat = matrix(0, 65, 35, dimnames=list(
daybasis65$names, CanadianWeather$place) )
tempfd. = fd(coefmat, daybasis65)
fdnames = list("Age (years)", "Child", "Height (cm)")
fdnames = vector('list', 3)
fdnames[[1]] = "Age (years)"
fdnames[[2]] = "Child"
fdnames[[3]] = "Height (cm)"
station = vector('list', 35)
station[[ 1]]= "St. Johns"
station[[35]] = "Resolute"
station = as.list(CanadianWeather$place)
fdnames = list("Day", "Weather Station" = station,
"Mean temperature (deg C)")
unitRng = c(0,1)
bspl2 = create.bspline.basis(unitRng, norder=2)
plot(bspl2, lwd=2)
tstFn1 = fd(c(-1, 2), bspl2)
tstFn2 = fd(c( 1, 3), bspl2)
par(mfrow=c(3,1))
fdsumobj = tstFn1+tstFn2
plot(tstFn1, lwd=2, xlab="", ylab="Line 1")
plot(tstFn2, lwd=2, xlab="", ylab="Line 2")
plot(fdsumobj, lwd=2, xlab="", ylab="Line1 + Line 2")
fddifobj = tstFn2-tstFn1
plot(tstFn1, lwd=2, xlab="", ylab="Line 1")
plot(tstFn2, lwd=2, xlab="", ylab="Line 2")
plot(fddifobj, lwd=2, xlab="", ylab="Line2 - Line 1")
fdprdobj = tstFn1 * tstFn2
plot(tstFn1, lwd=2, xlab="", ylab="Line 1")
plot(tstFn2, lwd=2, xlab="", ylab="Line 2")
plot(fdprdobj, lwd=2, xlab="", ylab="Line2 * Line 1")
fdsqrobj = tstFn1^2
plot(tstFn1, lwd=2, xlab="", ylab="Line 1")
plot(tstFn2, lwd=2, xlab="", ylab="Line 2")
plot(fdsqrobj, lwd=2, xlab="", ylab="Line 1 ^2")
a = 0.5
fdrootobj = fdsqrobj^a
plot(tstFn1, lwd=2, xlab="", ylab="Line 1")
plot(tstFn2, lwd=2, xlab="", ylab="Line 2")
plot(fdrootobj, lwd=2, xlab="", ylab="sqrt(fdsqrobj)")
fdrootobj = (fdsqrobj + 1)^a
par(mfrow=c(2,1))
plot(fdsqrobj + 1, lwd=2, xlab="", ylab="fdsqrobj + 1")
plot(fdrootobj, lwd=2, xlab="", ylab="sqrt(fdsqrobj + 1)")
a = (-1)
fdinvobj = fdsqrobj^a
plot(fdsqrobj, lwd=2, xlab="", ylab="fdsqrobj")
plot(fdinvobj, lwd=2, xlab="", ylab="1/fdsqrobj")
fdinvobj = (fdsqrobj+1)^a
plot(fdsqrobj + 1, lwd=2, xlab="", ylab="fdsqrobj + 1")
plot(fdinvobj, lwd=2, xlab="", ylab="1/(fdsqrobj+1)")
a = -0.99
fdpowobj = (fdsqrobj+1)^a
plot(fdsqrobj + 1, lwd=2, xlab="", ylab="fdsqrobj + 1")
plot(fdpowobj, lwd=2, xlab="", ylab="(fdsqrobj+1)^(-0.99)")
Tempbasis = create.fourier.basis(yearRng, 65)
Tempfd = smooth.basis(day.5,
CanadianWeather$dailyAv[,,'Temperature.C'], Tempbasis)$fd
meanTempfd = mean(Tempfd)
sumTempfd = sum(Tempfd)
par(mfrow=c(1,1))
plot((meanTempfd-sumTempfd*(1/35)))
plot(Tempfd[35], lwd=1, ylim=c(-35,20))
lines(meanTempfd, lty=2)
DmeanTempVec = eval.fd(day.5, meanTempfd, 1)
plot(day.5, DmeanTempVec, type='l')
harmaccelLfd = vec2Lfd(c(0,c(2*pi/365)^2, 0), c(0, 365))
LmeanTempVec = eval.fd(day.5, meanTempfd, harmaccelLfd)
par(mfrow=c(1,1))
plot(day.5, LmeanTempVec, type="l", cex=1.2,
xlab="Day", ylab="Harmonic Acceleration")
abline(h=0)
dayOfYearShifted = c(182:365, 1:181)
tempmat = daily$tempav[dayOfYearShifted, ]
tempbasis = create.fourier.basis(yearRng,65)
temp.fd = smooth.basis(day.5, tempmat, tempbasis)$fd
temp.fd$fdnames = list("Day (July 2 to June 30)",
"Weather Station",
"Mean temperature (deg. C)")
plot(temp.fd, lwd=2, xlab='Day (July 1 to June 30)',
ylab='Mean temperature (deg. C)')
basis13 = create.bspline.basis(c(0,10), 13)
tvec = seq(0,1,len=13)
sinecoef = sin(2*pi*tvec)
sinefd = fd(sinecoef, basis13, list("t","","f(t)"))
op = par(cex=1.2)
plot(sinefd, lwd=2)
points(tvec*10, sinecoef, lwd=2)
par(op)
cat(MontrealTemp, file='MtlDaily.txt')
MtlDaily = matrix(scan("MtlDaily.txt",0),34,365)
thawdata = t(MtlDaily[,16:47])
daytime = ((16:47)+0.5)
plot(daytime, apply(thawdata,1,mean), "b", lwd=2,
xlab="Day", ylab="Temperature (deg C)", cex=1.2)
thawbasis = create.bspline.basis(c(16,48),7)
thawbasismat = eval.basis(thawbasis, daytime)
thawcoef = solve(crossprod(thawbasismat),
crossprod(thawbasismat,thawdata))
thawfd = fd(thawcoef, thawbasis,
list("Day", "Year", "Temperature (deg C)"))
plot(thawfd, lty=1, lwd=2, col=1)
plotfit.fd(thawdata[,1], daytime, thawfd[1],
lty=1, lwd=2, main='')
omega = 2*pi/365
thawconst.basis = create.constant.basis(thawbasis$rangeval)
betalist = vector("list", 3)
betalist[[1]] = fd(0, thawconst.basis)
betalist[[2]] = fd(omega^2, thawconst.basis)
betalist[[3]] = fd(0, thawconst.basis)
harmaccelLfd. = Lfd(3, betalist)
accelLfd = int2Lfd(2)
harmaccelLfd.thaw = vec2Lfd(c(0,omega^2,0), thawbasis$rangeval)
all.equal(harmaccelLfd.[-1], harmaccelLfd.thaw[-1])
class(accelLfd)
class(harmaccelLfd)
Ltempmat = eval.fd(day.5, temp.fd, harmaccelLfd)
D2tempfd = deriv.fd(temp.fd, 2)
Ltempfd = deriv.fd(temp.fd, harmaccelLfd)
Bspl2 = create.bspline.basis(nbasis=2, norder=1)
Bspl3 = create.bspline.basis(nbasis=3, norder=2)
corrmat = array(1:6/6, dim=2:3)
bBspl2.3 = bifd(corrmat, Bspl2, Bspl3)
help(fd)
help(Lfd) |
testthat::expect_equal(x, -999) |
test_that("tbl_at_vars() treats `NULL` as empty inputs", {
expect_identical(tbl_at_vars(mtcars, vars(NULL)), tbl_at_vars(mtcars, vars()))
expect_identical(
tibble::remove_rownames(mutate_at(mtcars, vars(NULL), `*`, 100)),
tibble::remove_rownames(mtcars)
)
})
test_that("lists of formulas are auto-named", {
df <- tibble(x = 1:3, y = 4:6)
out <- df %>% summarise_all(list(~ mean(.), ~sd(.x, na.rm = TRUE)))
expect_named(out, c("x_mean", "y_mean", "x_sd", "y_sd"))
out <- df %>% summarise_all(list(foobar = ~ mean(.), ~sd(.x, na.rm = TRUE)))
expect_named(out, c("x_foobar", "y_foobar", "x_sd", "y_sd"))
})
test_that("colwise utils gives meaningful error messages", {
expect_snapshot(error = TRUE, tbl_at_vars(iris, raw(3)))
expect_snapshot(error = TRUE,
tbl_if_vars(iris, list(identity, force), environment())
)
.funs <- as_fun_list(list(identity, force), caller_env())
expect_snapshot(error = TRUE,
tbl_if_vars(iris, .funs, environment())
)
}) |
makeFits_initial = function(paths,
amplitude,
intercept) {
for(i in 1:length(paths)){
if (!any(colnames(paths[[i]])==c("distance","oxygen"))) {stop('data frame does not contain columns named distance and oxygen')}
}
if (! is.atomic(amplitude) || !length(amplitude)==1) {stop('amplitude needs to be a single value')}
if (! is.atomic(intercept) || !length(intercept)==1) {stop('intercept needs to be a single value')}
for(i in 1:length(paths)){if (any(is.na(paths[[i]]))) {stop('Data has NAs')}}
fits = c()
for(i in 1:length(paths)) {
data = paths[[i]]
curve = sineFit(data,amplitude,intercept, method = "initial")
fit = convertParameters(curve)
fit$predictedMin = fit$intercept - abs(fit$amplitude)
fit$predictedMax = fit$intercept + abs(fit$amplitude)
fit$observedMin = min(data$oxygen)
fit$observedMax = max(data$oxygen)
fit$MSE = mean((predict(curve)-data$oxygen)^2)
fit$PearsonCorrelation = stats::cor(predict(curve),paths[[i]]$oxygen,method="pearson")
fits = rbind(fits, as.numeric(fit))
}
fits = data.frame(fits)
colnames(fits) = c("amplitude","intercept","x0","X","birth","predictedMin",
"predictedMax","observedMin","observedMax","MSE","Pearson")
return(fits)
} |
awsimage <- function (object, hmax=4, aws=TRUE, varmodel=NULL,
ladjust=1.25 , mask = NULL, xind = NULL,
yind = NULL, wghts=c(1,1,1,1), scorr=TRUE, lkern="Plateau",
plateau=NULL, homogen=TRUE, earlystop=TRUE, demo=FALSE, graph=FALSE, max.pixel=4.e2,clip=FALSE,compress=TRUE) {
IQRdiff <- function(data) IQR(diff(data))/1.908
if(!check.adimpro(object)) {
cat(" Consistency check for argument object failed (see warnings). object is returned.\"n")
return(invisible(object))
}
object <- switch(object$type,
"hsi" = hsi2rgb(object),
"yuv" = yuv2rgb(object),
"yiq" = yiq2rgb(object),
"xyz" = xyz2rgb(object),
object)
if(object$type=="RAW") stop("RAW-image, will be implemented in function awsraw later ")
if(!is.null(object$call)) {
warning("argument object is result of awsimage or awspimage. You should know what you do.")
}
args <- match.call()
if(!is.null(mask)) {
varmodel <- "None"
scorr <- FALSE
clip <- FALSE
homogen <- FALSE
earlystop <- FALSE
}
if(clip) object <- clip.image(object,xind,yind,compress=FALSE)
if(object$compressed) object <- decompress.image(object)
if(is.null(varmodel)) {
varmodel <- if(object$gamma) "Constant" else "Linear"
}
bcf <- c(-.4724,1.1969,.22167,.48691,.13731,-1.0648)
estvar <- toupper(varmodel) %in% c("CONSTANT","LINEAR","QUADRATIC")
hpre <- 2.
if(estvar) {
dlw<-(2*trunc(hpre)+1)
nvarpar <- switch(toupper(varmodel),CONSTANT=1,LINEAR=2,QUADRATIC=3,1)
} else {
nvarpar <- 1
}
dimg <- dimg0 <- dim(object$img)
imgtype <- object$type
dv <- switch(imgtype,rgb=dimg[3],greyscale=1)
if(length(wghts)<dv) wghts <- c(wghts,rep(1,dv-length(wghts))) else wghts <- pmin(.1,wghts)
wghts <- switch(imgtype, greyscale=1, rgb = wghts[1:dv])
spcorr <- matrix(0,2,dv)
h0 <- c(0,0)
if( valid.index(xind,dimg[1]) || valid.index(yind,dimg[2])) mask <- NULL
if(!is.null(mask)) {
if(!is.logical(mask)||dim(mask)!=dimg[1:2]) {
mask<-NULL
warning("Argument mask changed to NULL")
} else if(sum(mask)==0) mask<-NULL
}
if(!is.null(mask)){
xmask <- range((1:dimg[1])[apply(mask,1,any)])
ymask <- range((1:dimg[2])[apply(mask,2,any)])
xind <- xmask[1]:xmask[2]
yind <- ymask[1]:ymask[2]
n1 <- length(xind)
n2 <- length(yind)
n <- n1*n2
} else {
if(is.null(xind)) xind <- 1:dimg[1]
if(is.null(yind)) yind <- 1:dimg[2]
n1 <- length(xind)
n2 <- length(yind)
n <- n1*n2
}
dimg <- switch(imgtype,greyscale=c(n1,n2),rgb=c(n1,n2,dv))
mc.cores <- setCores(, reprt = FALSE)
lkern <- switch(lkern,
Triangle=1,
Quadratic=2,
Cubic=3,
Plateau=4,
1)
if (is.null(hmax)) hmax <- 4
wghts <- wghts/sum(wghts)
dgf <- sum(wghts)^2/sum(wghts^2)
if (aws) lambda <- ladjust*switch(imgtype,greyscale=16,rgb=7) else lambda <- 1e50
sigma2 <- switch(imgtype,
"greyscale" = IQRdiff(object$img)^2,
"rgb" = apply(object$img,3,IQRdiff)^2,
IQRdiff(object$img)^2)
sigma2 <- pmax(.01,sigma2)
cat("Estimated variance (assuming independence): ", signif(sigma2/65635^2,4),"\n")
if (!estvar) {
if (length(sigma2)==1) {
if(dv>1) sigma2 <- rep(sigma2,1)
} else if (length(sigma2)==dv) {
wghts <- wghts[1:dv]/sigma2
}
}
spmin <- plateau
if(is.null(spmin)) spmin <- .25
maxvol <- getvofh2(hmax,lkern)
kstar <- as.integer(log(maxvol)/log(1.25))
if(aws){
k <- if(estvar) 6 else 1
}
else {
cat("No adaptation method specified. Calculate kernel estimate with bandwidth hmax.\n")
k <- kstar
}
if (demo && !graph) graph <- TRUE
if(graph){
oldpar <- par(mfrow=c(1,3),mar=c(1,1,3,.25),mgp=c(2,1,0))
on.exit(par(oldpar))
graphobj0 <- object[-(1:length(object))[names(object)=="img"]]
graphobj0$dim <- c(n1,n2)
if(!is.null(.Options$adimpro.xsize)) max.x <- trunc(.Options$adimpro.xsize/3.2) else max.x <- 600
if(!is.null(.Options$adimpro.ysize)) max.y <- trunc(.Options$adimpro.ysize/1.2) else max.y <- 900
}
bi <- rep(1,n)
img <- theta <- switch(imgtype,greyscale=object$img[xind,yind],
rgb=aperm(object$img[xind,yind,],c(3,1,2)))
bi0 <- 1
coef <- matrix(0,nvarpar,dv)
coef[1,] <- sigma2
vobj <- list(coef=coef,meanvar=sigma2)
imgq995 <- switch(imgtype,greyscale=quantile(img[xind,yind],.995),
rgb=apply(img[,xind,yind],1,quantile,.995))
if(scorr){
twohp1 <- 2*trunc(hpre)+1
pretheta <- .Fortran(C_awsimg0,
as.integer(img),
as.integer(n1),
as.integer(n2),
as.integer(dv),
as.double(hpre),
theta=integer(prod(dimg)),
bi=double(n1*n2),
as.integer(lkern),
double(twohp1*twohp1),
double(dv*mc.cores),
PACKAGE="adimpro")$theta
dim(pretheta) <- switch(imgtype,
"greyscale" = dimg,
"rgb" = dimg[c(3,1,2)])
spchcorr <- .Fortran(C_estcorr,
as.double(switch(imgtype,
greyscale=object$img[xind,yind]-pretheta,
rgb=object$img[xind,yind,]-aperm(pretheta,c(2,3,1)))),
as.integer(n1),
as.integer(n2),
as.integer(dv),
scorr=double(2*dv),
chcorr=double(max(1,dv*(dv-1)/2)),
PACKAGE="adimpro")[c("scorr","chcorr")]
spcorr <- spchcorr$scorr
srh <- sqrt(hpre)
spcorr <- matrix(pmin(.9,spcorr+
bcf[1]/srh+bcf[2]/hpre+
bcf[3]*spcorr/srh+bcf[4]*spcorr/hpre+
bcf[5]*spcorr^2/srh+bcf[6]*spcorr^2/hpre),2,dv)
chcorr <- spchcorr$chcorr
for(i in 1:dv) cat("Estimated spatial correlation in channel ",i,":",signif(spcorr[,i],2),"\n")
if(dv>1) cat("Estimated correlation between channels (1,2):",signif(chcorr[1],2),
" (1,3):",signif(chcorr[2],2),
" (2,3):",signif(chcorr[3],2),"\n")
} else {
spcorr <- matrix(0,2,dv)
chcorr <- numeric(max(1,dv*(dv-1)/2))
}
if(!is.null(mask)) fix <- !mask[xind,yind]
lambda0 <- 1e50
if(earlystop) fix <- rep(FALSE,n) else fix <- FALSE
if(homogen) hhom <- rep(0,n) else hhom <- 0
total <- cumsum(1.25^(1:kstar))/sum(1.25^(1:kstar))
mc.cores <- setCores(,reprt=FALSE)
while (k<=kstar) {
hakt0 <- geth2(1,10,lkern,1.25^(k-1),1e-4)
hakt <- geth2(1,10,lkern,1.25^k,1e-4)
twohp1 <- 2*trunc(hakt)+1
spcorr <- pmax(apply(spcorr,1,mean),0)
if(any(spcorr>0)) {
h0<-numeric(length(spcorr))
for(i in 1:length(h0))
h0[i]<-geth.gauss(spcorr[i])
if(length(h0)<2) h0<-rep(h0[1],2)
}
if (any(spcorr>0)) {
lcorr <- Spatialvar.gauss(hakt0,h0)/
Spatialvar.gauss(h0,1e-5)/Spatialvar.gauss(hakt0,1e-5)
lambda0 <-lambda0*lcorr
if(varmodel=="None")
lambda0 <- lambda0*Varcor.gauss(h0)
}
if(is.null(mask)){
zobj <- .Fortran(C_awsvimg0,
as.integer(img),
fix=as.integer(fix),
as.integer(n1),
as.integer(n2),
as.integer(n1*n2),
as.integer(dv),
as.double(vobj$coef),
as.integer(nvarpar),
as.double(vobj$meanvar),
as.double(chcorr),
hakt=as.double(hakt),
hhom=as.double(hhom),
as.double(lambda0),
as.integer(theta),
bi=as.double(bi),
bi0=as.double(bi0),
theta=integer(prod(dimg)),
as.integer(lkern),
as.double(spmin),
as.double(sqrt(wghts)),
double(twohp1*twohp1),
as.integer(earlystop),
as.integer(homogen),
PACKAGE="adimpro")[c("bi","bi0","theta","hakt","hhom","fix")]
} else {
zobj <- .Fortran(C_mawsimg0,
as.integer(img),
as.integer(fix),
as.integer(mask[xind,yind]),
as.integer(n1),
as.integer(n2),
as.integer(dv),
hakt=as.double(hakt),
as.double(lambda0),
as.integer(theta),
bi=as.double(bi),
bi0=as.double(bi0),
theta=integer(prod(dimg)),
as.integer(lkern),
as.double(spmin),
double(twohp1*twohp1),
as.double(wghts),
PACKAGE="adimpro")[c("bi","bi0","theta","hakt","hhom","fix")]
}
theta <- as.integer(zobj$theta)
dim(theta) <- switch(imgtype,greyscale=dimg,rgb=dimg[c(3,1,2)])
bi <- zobj$bi
bi0 <- zobj$bi0
hhom <- zobj$hhom
fix <- zobj$fix
rm(zobj)
gc()
dim(bi) <- dimg[1:2]
if (graph) {
graphobj <- graphobj0
class(graphobj) <- "adimpro"
graphobj$img <- switch(imgtype,
greyscale=object$img[xind,yind],
rgb=object$img[xind,yind,])
show.image(graphobj,max.x=max.x,max.y=max.y,xaxt="n",yaxt="n")
title("Observed Image")
graphobj$img <- switch(imgtype,greyscale=theta,rgb=aperm(theta,c(2,3,1)))
show.image(graphobj,max.x=max.x,max.y=max.y,xaxt="n",yaxt="n")
title(paste("Reconstruction h=",signif(hakt,3)))
graphobj$img <- matrix(as.integer(65534*bi/bi0),n1,n2)
graphobj$type <- "greyscale"
graphobj$gamma <- FALSE
show.image(graphobj,max.x=max.x,max.y=max.y,xaxt="n",yaxt="n")
title(paste("Adaptation (rel. weights):",signif(mean(bi)/bi0,3)))
rm(graphobj)
gc()
}
cat("Bandwidth",signif(hakt,3)," Progress",signif(total[k],2)*100,"% ")
if(earlystop) cat(" pixels fixed: ",sum(fix))
if(homogen) cat(" mean radius of homog. regions ",signif(mean(hhom),3))
if(homogen) cat(" min radius of homog. regions ",signif(min(hhom),3))
cat("\n")
if (scorr) {
if(hakt > hpre){
spchcorr <- .Fortran(C_estcorr,
as.double(switch(imgtype,
greyscale=object$img[xind,yind]- theta,
rgb=object$img[xind,yind,]- aperm(theta,c(2,3,1)))),
as.integer(n1),
as.integer(n2),
as.integer(dv),
scorr=double(2*dv),
chcorr=double(max(1,dv*(dv-1)/2)),
PACKAGE="adimpro")[c("scorr","chcorr")]
spcorr <- spchcorr$scorr
srh <- sqrt(hakt)
spcorr <- matrix(pmin(.9,spcorr+
bcf[1]/srh+bcf[2]/hakt+
bcf[3]*spcorr/srh+bcf[4]*spcorr/hakt+
bcf[5]*spcorr^2/srh+bcf[6]*spcorr^2/hakt),2,dv)
chcorr <- spchcorr$chcorr
for(i in 1:dv) cat("Estimated spatial correlation in channel ",i,":",signif(spcorr[,i],2),"\n")
if(dv>1) cat("Estimated correlation between channels (1,2):",signif(chcorr[1],2),
" (1,3):",signif(chcorr[2],2),
" (2,3):",signif(chcorr[3],2),"\n")
} else {
spcorr <- matrix(pmin(.9,spchcorr$scorr+
bcf[1]/srh+bcf[2]/hpre+
bcf[3]*spchcorr$scorr/srh+bcf[4]*spchcorr$scorr/hpre+
bcf[5]*spchcorr$scorr^2/srh+bcf[6]*spchcorr$scorr^2/hpre),2,dv)
chcorr <- spchcorr$chcorr
}
} else {
spcorr <- matrix(0,2,dv)
chcorr <- numeric(max(1,dv*(dv-1)/2))
}
if (estvar) {
vobj <- switch(toupper(varmodel),
CONSTANT=.Fortran(C_esigmac,
as.integer(switch(imgtype,
greyscale=object$img[xind,yind],
rgb=object$img[xind,yind,])),
as.integer(n1*n2),
as.integer(dv),
as.integer(switch(imgtype,
greyscale=theta,
rgb=aperm(theta,c(2,3,1)))),
as.double(bi),
as.integer(imgq995),
coef=double(nvarpar*dv),
meanvar=double(dv),
PACKAGE="adimpro")[c("coef","meanvar")],
LINEAR=.Fortran(C_esigmal,
as.integer(switch(imgtype,
greyscale=object$img[xind,yind],
rgb=object$img[xind,yind,])),
as.integer(n1*n2),
as.integer(dv),
as.integer(switch(imgtype,
greyscale=theta,
rgb=aperm(theta,c(2,3,1)))),
as.double(bi),
as.integer(imgq995),
coef=double(nvarpar*dv),
meanvar=double(dv),
PACKAGE="adimpro")[c("coef","meanvar")],
QUADRATIC=.Fortran(C_esigmaq,
as.integer(switch(imgtype,
greyscale=object$img[xind,yind],
rgb=object$img[xind,yind,])),
as.integer(n1*n2),
as.integer(dv),
as.integer(switch(imgtype,
greyscale=theta,
rgb=aperm(theta,c(2,3,1)))),
as.double(bi),
as.integer(imgq995),
coef=double(nvarpar*dv),
meanvar=double(dv),
PACKAGE="adimpro")[c("coef","meanvar")]
)
dim(vobj$coef) <- c(nvarpar,dv)
for(i in 1:dv){
if(any(spcorr[,i]>.1) & vobj$meanvar[i]<sigma2[i]) {
vobj$coef[,i] <- vobj$coef[,i]*sigma2[i]/vobj$meanvar[i]
vobj$meanvar[i] <- sigma2[i]
}
}
cat("Estimated mean variance",signif(vobj$meanvar/65635^2,3),"\n")
}
if (demo) readline("Press return")
lambda0 <- lambda
k <- k+1
}
if(graph) par(oldpar)
if(imgtype=="rgb") {
object$img[xind,yind,] <- aperm(theta,c(2,3,1))
} else if(imgtype=="greyscale") {
object$img[xind,yind] <- theta
}
ni <- array(1,dimg0[1:2])
ni[xind,yind] <- bi
object$ni <- ni
object$ni0 <- bi0
object$hmax <- hakt
object$call <- args
if(estvar) {
if(varmodel=="Quadratic") {
vobj$coef[1,] <- vobj$coef[1,]/65535^2
vobj$coef[2,] <- vobj$coef[2,]/65535
vobj$coef[3,] <- vobj$coef[3,]
} else if(varmodel=="Linear") {
vobj$coef[1,] <- vobj$coef[1,]/65535^2
vobj$coef[2,] <- vobj$coef[2,]/65535
} else vobj$coef <- vobj$coef/65535^2
object$varcoef <- vobj$coef
object$wghts <- vobj$wghts
}
if(scorr) {
object$scorr <- spcorr
object$chcorr <- chcorr
}
invisible(if(compress) compress.image(object) else object)
}
awspimage <- function(object, hmax=12, aws=TRUE, degree=1, varmodel=NULL,
ladjust=1.0, xind = NULL, yind = NULL, wghts=c(1,1,1,1),
scorr=TRUE, lkern="Plateau", plateau=NULL, homogen=TRUE,
earlystop=TRUE, demo=FALSE,
graph=FALSE, max.pixel=4.e2, clip=FALSE, compress=TRUE){
IQRdiff <- function(img) IQR(diff(img))/1.908
gettheta <- function(ai,bi){
n1 <- dim(ai)[1]
n2 <- dim(ai)[2]
n <- n1*n2
dp1 <- dim(ai)[3]
dp2 <- dim(bi)[3]
dv <- dim(ai)[4]
ind <- matrix(c(1, 2, 3, 4, 5, 6,
2, 4, 5, 7, 8, 9,
3, 5, 6, 8, 9,10,
4, 7, 8,11,12,13,
5, 8, 9,12,13,14,
6, 9,10,13,14,15),6,6)[1:dp1,1:dp1]
theta <- ai
for(i in 1:dv) {
theta[,,,i] <- array(.Fortran(C_mpaws2,
as.integer(n),
as.integer(dp1),
as.integer(dp2),
as.double(ai[,,,i]),
as.double(bi),
theta=double(dp1*n),
double(dp1*dp1),
as.integer(ind),PACKAGE="adimpro")$theta,c(n1,n2,dp1))
}
theta
}
if(!check.adimpro(object)) {
cat(" Consistency check for argument object failed (see warnings). object is returned.\"n")
return(invisible(object))
}
object <- switch(object$type,
"hsi" = hsi2rgb(object),
"yuv" = yuv2rgb(object),
"yiq" = yiq2rgb(object),
"xyz" = xyz2rgb(object),
object)
if(!is.null(object$call)) {
warning("argument object is result of awsimage or awspimage. You should know what you do.\"n")
}
args <- match.call()
if(!(degree %in% c(1,2))) {
warning("only polynomial degrees 1 and 2 implemented, original image is returned")
return(object)
}
if(clip) object <- clip.image(object,xind,yind,compress=FALSE)
if(object$compressed) object <- decompress.image(object)
if(is.null(varmodel)) {
varmodel <- if(object$gamma) "Constant" else "Linear"
}
estvar <- toupper(varmodel) %in% c("CONSTANT","LINEAR")
hpre <- switch(degree,2.,3.)
bcf <- switch(degree,c(-.4724,1.1969,.22167,.48691,.13731,-1.0648),
c(-.69249,2.0552,.05379,1.6063,.28891,-1.907))
if(estvar) {
dlw<-(2*trunc(hpre)+1)
nvarpar <- switch(varmodel,Constant=1,Linear=2,1)
} else nvarpar <- 1
dimg <- dimg0 <- dim(object$img)
imgtype <- object$type
dv <- switch(imgtype,rgb=dimg[3],greyscale=1)
if(length(wghts)<dv) wghts <- c(wghts,rep(1,dv-length(wghts))) else wghts <- pmin(.1,wghts)
wghts <- switch(imgtype, greyscale=1, rgb = wghts[1:dv])
spcorr <- matrix(0,2,dv)
h0 <- c(0,0)
if(is.null(xind)) xind <- 1:dimg[1]
if(is.null(yind)) yind <- 1:dimg[2]
n1 <- length(xind)
n2 <- length(yind)
n <- n1*n2
dimg <- c(n1,n2,dv)
dp1 <- switch(degree+1,1,3,6)
dp2 <- switch(degree+1,1,6,15)
lkern <- switch(lkern,
Triangle=1,
Quadratic=2,
Cubic=3,
Plateau=4,
1)
if (is.null(hmax)) hmax <- 12
wghts <- wghts/max(wghts)
maxvol <- getvofh2(hmax,lkern)
kstar <- as.integer(log(maxvol)/log(1.25))
if(aws){
k <- if(estvar) 6 else 1
}
else {
cat("No adaptation method specified. Calculate kernel estimate with bandwidth hmax.\n")
k <- kstar
}
lambda <- if (aws) ladjust*switch(imgtype, greyscale=switch(degree,18.5,32), rgb = switch(degree,38,120)) else 1e50
sigma2 <- switch(imgtype,
"greyscale" = IQRdiff(object$img)^2,
"rgb" = apply(object$img,3,IQRdiff)^2, IQRdiff(object$img)^2)
cat("Estimated variance: ", signif(sigma2/65635^2,4),"\n")
if (!estvar) {
vobj <- list(coef= sigma2, meanvar=sigma2)
spcorr <- matrix(0,2,dv)
}
spmin <- 0
bi <- array(rep(1,n*dp2),c(dimg[1:2],dp2))
theta <- array(0,c(dimg,dp1))
theta[,,,1] <- switch(imgtype,greyscale=object$img[xind,yind],rgb=object$img[xind,yind,])
bi0 <- 1
ind <- matrix(c(1, 2, 3, 4, 5, 6,
2, 4, 5, 7, 8, 9,
3, 5, 6, 8, 9,10,
4, 7, 8,11,12,13,
5, 8, 9,12,13,14,
6, 9,10,13,14,15),6,6)[1:dp1,1:dp1]
coef <- matrix(0,nvarpar,dv)
coef[1,] <- sigma2
vobj <- list(coef=coef,meanvar=sigma2)
imgq995 <- switch(imgtype,greyscale=quantile(object$img[xind,yind],.995),
rgb=apply(object$img[xind,yind,],3,quantile,.995))
if(scorr){
twohp1 <- 2*trunc(hpre)+1
pretheta <- .Fortran(C_awsimg,
as.integer(switch(imgtype,
greyscale=object$img[xind,yind],
rgb=object$img[xind,yind,])),
as.integer(n1),
as.integer(n2),
as.integer(dv),
as.double(hpre),
theta=integer(prod(dimg)),
bi=double(n1*n2),
as.integer(lkern),
double(twohp1*twohp1),
double(dv),
PACKAGE="adimpro")[c("theta","bi")]
prebi <- pretheta$bi
pretheta <- pretheta$theta
spchcorr <- .Fortran(C_estcorr,
as.double(switch(imgtype,
greyscale=object$img[xind,yind],
rgb=object$img[xind,yind,])-pretheta),
as.integer(n1),
as.integer(n2),
as.integer(dv),
scorr=double(2*dv),
chcorr=double(max(1,dv*(dv-1)/2)),
PACKAGE="adimpro")[c("scorr","chcorr")]
spcorr <- spchcorr$scorr
srh <- sqrt(hpre)
spcorr <- matrix(pmin(.9,spcorr+
bcf[1]/srh+bcf[2]/hpre+
bcf[3]*spcorr/srh+bcf[4]*spcorr/hpre+
bcf[5]*spcorr^2/srh+bcf[6]*spcorr^2/hpre),2,dv)
chcorr <- spchcorr$chcorr
for(i in 1:dv) cat("Estimated spatial correlation in channel ",i,":",signif(spcorr[,i],2),"\n")
if(dv>1) cat("Estimated correlation between channels (1,2):",signif(chcorr[1],2),
" (1,3):",signif(chcorr[2],2),
" (2,3):",signif(chcorr[3],2),"\n")
} else {
spcorr <- matrix(0,2,dv)
chcorr <- numeric(max(1,dv*(dv-1)/2))
}
if (estvar) {
vobj <- switch(toupper(varmodel),
CONSTANT=.Fortran(C_epsigmac,
as.integer(switch(imgtype,
greyscale=object$img[xind,yind],
rgb=object$img[xind,yind,])),
as.integer(n1*n2),
as.integer(dv),
as.integer(pretheta),
as.double(prebi),
as.integer(imgq995),
coef=double(nvarpar*dv),
meanvar=double(dv),
as.integer(dp1),
PACKAGE="adimpro")[c("coef","meanvar")],
LINEAR=.Fortran(C_epsigmal,
as.integer(switch(imgtype,
greyscale=object$img[xind,yind],
rgb=object$img[xind,yind,])),
as.integer(n1*n2),
as.integer(dv),
as.integer(pretheta),
as.double(prebi),
as.integer(imgq995),
coef=double(nvarpar*dv),
meanvar=double(dv),
as.integer(dp1),
PACKAGE="adimpro")[c("coef","meanvar")]
)
if(any(is.na(vobj$coef))) vobj <- oldvobj
dim(vobj$coef) <- c(nvarpar,dv)
for(i in 1:dv){
if(any(spcorr[,i]>.1) & vobj$meanvar[i]<sigma2[i]) {
vobj$coef[,i] <- vobj$coef[,i]*sigma2[i]/vobj$meanvar[i]
vobj$meanvar[i] <- sigma2[i]
}
}
cat("Estimated mean variance",signif(vobj$meanvar/65635^2,3),"\n")
}
rm(prebi)
hincr <- sqrt(1.25)
if (demo && !graph) graph <- TRUE
if(graph){
oldpar <- par(mfrow=c(1,3),mar=c(1,1,3,.25),mgp=c(2,1,0))
on.exit(par(oldpar))
graphobj0 <- object[-(1:length(object))[names(object)=="img"]]
graphobj0$dim <- c(n1,n2)
if(!is.null(.Options$adimpro.xsize)) max.x <- trunc(.Options$adimpro.xsize/3.2) else max.x <- 600
if(!is.null(.Options$adimpro.ysize)) max.y <- trunc(.Options$adimpro.ysize/1.2) else max.y <- 900
}
hw <- degree+.1
lambda0 <- 1e50
total <- cumsum(1.25^(1:kstar))/sum(1.25^(1:kstar))
while (k<=kstar) {
hakt0 <- geth2(1,10,lkern,1.25^(k-1),1e-4)
hakt <- geth2(1,10,lkern,1.25^k,1e-4)
twohp1 <- 2*trunc(hakt)+1
twohhwp1 <- 2*trunc(hakt+hw)+1
spcorr <- pmax(apply(spcorr,1,mean),0)
if(any(spcorr>0)) {
h0<-numeric(length(spcorr))
for(i in 1:length(h0))
h0[i]<-geth.gauss(spcorr[i])
if(length(h0)<2) h0<-rep(h0[1],2)
}
if (any(spcorr>0)) {
lcorr <- Spatialvar.gauss(hakt0,h0)/
Spatialvar.gauss(h0,1e-5)/Spatialvar.gauss(hakt0,1e-5)
lambda0 <-lambda0*lcorr
if(varmodel=="None")
lambda0 <- lambda0*Varcor.gauss(h0)
}
zobj <- .Fortran(C_awspimg,
as.integer(switch(imgtype,
greyscale=object$img[xind,yind],
rgb=object$img[xind,yind,])),
as.integer(n1),
as.integer(n2),
as.integer(dv),
as.integer(degree),
as.double(hw),
as.double(vobj$coef),
as.integer(nvarpar),
as.double(vobj$meanvar),
hakt=as.double(hakt),
as.double(lambda0),
as.double(theta),
bi=as.double(bi),
bi0=double(1),
ai=double(n*dp1*dv),
as.integer(lkern),
as.double(spmin),
double(twohp1*twohp1),
double(twohp1*twohp1),
double(twohhwp1*twohhwp1),
double(twohhwp1*twohhwp1),
as.double(wghts),
as.integer(ind),
PACKAGE="adimpro")[c("bi","bi0","ai","hakt")]
dim(zobj$ai) <- c(dimg[1:2],dp1,dv)
bi <- zobj$bi
dim(bi)<-c(n1,n2,dp2)
theta <- gettheta(zobj$ai,bi)
dim(theta)<-c(dimg[1:2],dp1,dv)
bi0 <- max(zobj$bi0,bi[,,1])
rm(zobj)
gc()
if (graph) {
graphobj <- graphobj0
class(graphobj) <- "adimpro"
graphobj$img <- switch(imgtype,
greyscale=object$img[xind,yind],
rgb=object$img[xind,yind,])
show.image(graphobj,max.x=max.x,max.y=max.y,xaxt="n",yaxt="n")
title("Observed Image")
graphobj$img <- switch(imgtype,
greyscale=array(pmin(65535,pmax(0,as.integer(theta[,,1,]))),dimg[1:2]),
rgb=array(pmin(65535,pmax(0,as.integer(theta[,,1,]))),dimg))
show.image(graphobj,max.x=max.x,max.y=max.y,xaxt="n",yaxt="n")
title(paste("Reconstruction h=",signif(hakt,3)))
graphobj$img <- matrix(pmin(65535,pmax(0,as.integer(65534*bi[,,1]/bi0))),n1,n2)
graphobj$type <- "greyscale"
graphobj$gamma <- FALSE
show.image(graphobj,max.x=max.x,max.y=max.y,xaxt="n",yaxt="n")
title(paste("Adaptation (rel. weights):",signif(mean(bi[,,1])/bi0,3)))
rm(graphobj)
gc()
}
cat("Bandwidth",signif(hakt,3)," Progress",signif(total[k],2)*100,"% \n")
if (scorr) {
if(hakt > hpre){
spchcorr <- .Fortran(C_estcorr,
as.double(switch(imgtype,
greyscale=object$img[xind,yind],
rgb=object$img[xind,yind,])- theta[,,1,]),
as.integer(n1),
as.integer(n2),
as.integer(dv),
scorr=double(2*dv),
chcorr=double(max(1,dv*(dv-1)/2)),
PACKAGE="adimpro")[c("scorr","chcorr")]
spcorr <- spchcorr$scorr
srh <- sqrt(hakt)
spcorr <- matrix(pmin(.9,spcorr+
bcf[1]/srh+bcf[2]/hakt+
bcf[3]*spcorr/srh+bcf[4]*spcorr/hakt+
bcf[5]*spcorr^2/srh+bcf[6]*spcorr^2/hakt),2,dv)
chcorr <- spchcorr$chcorr
for(i in 1:dv) cat("Estimated spatial correlation in channel ",i,":",signif(spcorr[,i],2),"\n")
if(dv>1) cat("Estimated correlation between channels (1,2):",signif(chcorr[1],2),
" (1,3):",signif(chcorr[2],2),
" (2,3):",signif(chcorr[3],2),"\n")
} else {
spcorr <- matrix(pmin(.9,spcorr+
bcf[1]/srh+bcf[2]/hakt+
bcf[3]*spcorr/srh+bcf[4]*spcorr/hakt+
bcf[5]*spcorr^2/srh+bcf[6]*spcorr^2/hakt),2,dv)
chcorr <- spchcorr$chcorr
}
} else {
spcorr <- matrix(0,2,dv)
chcorr <- numeric(max(1,dv*(dv-1)/2))
}
if (estvar && hakt > hpre) {
oldvobj <- vobj
vobj <- switch(toupper(varmodel),
CONSTANT=.Fortran(C_epsigmac,
as.integer(switch(imgtype,
greyscale=object$img[xind,yind],
rgb=object$img[xind,yind,])),
as.integer(n1*n2),
as.integer(dv),
as.integer(theta[,,1,]),
as.double(bi),
as.integer(imgq995),
coef=double(nvarpar*dv),
meanvar=double(dv),
as.integer(dp1),
PACKAGE="adimpro")[c("coef","meanvar")],
LINEAR=.Fortran(C_epsigmal,
as.integer(switch(imgtype,
greyscale=object$img[xind,yind],
rgb=object$img[xind,yind,])),
as.integer(n1*n2),
as.integer(dv),
as.integer(theta[,,1,]),
as.double(bi),
as.integer(imgq995),
coef=double(nvarpar*dv),
meanvar=double(dv),
as.integer(dp1),
PACKAGE="adimpro")[c("coef","meanvar")]
)
if(any(is.na(vobj$coef))) vobj <- oldvobj
dim(vobj$coef) <- c(nvarpar,dv)
cat("Estimated mean variance",signif(vobj$meanvar/65635^2,3),"\n")
}
if (demo) readline("Press return")
lambda0 <- lambda
k <- k+1
}
if(graph) par(oldpar)
if(imgtype=="rgb") {
object$img[xind,yind,] <- as.integer(pmin(65535,pmax(0,theta[,,1,])))
} else if(imgtype=="greyscale") {
object$img[xind,yind] <- as.integer(pmin(65535,pmax(0,theta[,,1,1])))
}
ni <- array(1,dimg0[1:2])
ni[xind,yind] <- bi[,,1]
object$ni <- ni
object$ni0 <- bi0
object$hmax <- hakt
object$call <- args
if(estvar) {
if(varmodel=="Linear") {
vobj$coef[1,] <- vobj$coef[1,]/65535^2
vobj$coef[2,] <- vobj$coef[2,]/65535
} else vobj$coef <- vobj$coef/65535^2
object$varcoef <- vobj$coef
object$wghts <- vobj$wghts
}
if(scorr) {
object$scorr <- spcorr
object$chcorr <- chcorr
}
invisible(if(compress) compress.image(object) else object)
}
awsprop <- function (object, hmax=10, lambda=10, wghts=c(1,1,1,1), lkern="Plateau",
plateau=NULL, earlystop=FALSE, homogen=FALSE, graph=FALSE, max.pixel=4.e2) {
varmodel <- "Constant"
IQRdiff <- function(data) IQR(diff(data))/1.908
if(!check.adimpro(object)) {
cat(" Consistency check for argument object failed (see warnings). object is returned.\"n")
return(invisible(object))
}
object <- switch(object$type,
"hsi" = hsi2rgb(object),
"yuv" = yuv2rgb(object),
"yiq" = yiq2rgb(object),
"xyz" = xyz2rgb(object),
object)
if(!is.null(object$call)) {
warning("argument object is result of awsimage or awspimage. You should know what you do.")
}
args <- match.call()
if(object$compressed) object <- decompress.image(object)
hpre <- 2.
dlw<-(2*trunc(hpre)+1)
nvarpar <- 1
dimg <- dimg0 <- dim(object$img)
imgtype <- object$type
dv <- switch(imgtype,rgb=dimg[3],greyscale=1)
if(length(wghts)<dv) wghts <- c(wghts,rep(1,dv-length(wghts))) else wghts <- pmin(.1,wghts)
wghts <- switch(imgtype, greyscale=1, rgb = wghts[1:dv])
h0 <- c(0,0)
n1 <- dimg[1]
n2 <- dimg[2]
n <- n1*n2
dimg <- switch(imgtype,greyscale=c(n1,n2),rgb=c(n1,n2,dv))
lkern <- switch(lkern,
Triangle=1,
Quadratic=2,
Cubic=3,
Plateau=4,
1)
if (is.null(hmax)) hmax <- 4
wghts <- wghts/sum(wghts)
dgf <- sum(wghts)^2/sum(wghts^2)
sigma2 <- switch(imgtype,
"greyscale" = IQRdiff(object$img)^2,
"rgb" = apply(object$img,3,IQRdiff)^2,
IQRdiff(object$img)^2)
sigma2 <- pmax(0.01,sigma2)
cat("Estimated variance (assuming independence): ", signif(sigma2/65635^2,4),"\n")
spmin <- plateau
if(is.null(spmin)) spmin <- .25
hinit <- 1
hincr <- sqrt(1.25)
if(graph){
oldpar <- par(mfrow=c(1,3),mar=c(1,1,3,.25),mgp=c(2,1,0))
on.exit(par(oldpar))
graphobj0 <- object[-(1:length(object))[names(object)=="img"]]
graphobj0$dim <- c(n1,n2)
}
hmax <- hmax
bi <- rep(1,n)
img <- theta <- switch(imgtype,greyscale=object$img,
rgb=aperm(object$img,c(3,1,2)))
bi0 <- 1
coef <- matrix(0,nvarpar,dv)
coef[1,] <- sigma2
vobj <- list(coef=coef,meanvar=sigma2)
imgq995 <- switch(imgtype,greyscale=quantile(img,.995),
rgb=apply(img,1,quantile,.995))
steps <- as.integer(log(hmax/hinit)/log(hincr)+1)
if(length(lambda)<(steps+1)) lambda <- c(lambda,rep(lambda[length(lambda)],1+steps-length(lambda)))
hakt0 <- hakt <- hinit
hakt <- hakt*hincr
step <- 1
lambda0 <- lambda[1]
sigma2 <- pmax(0.01,rep(IQRdiff(object$img)^2,dv))
vobj <- list(coef=sigma2,meanvar=sigma2)
progress <- 0
total <- (hincr^(2*ceiling(log(hmax/hinit)/log(hincr)))-1)/(hincr^2-1)
if (total == 0) total <- hincr^(2*step)
if(earlystop) fix <- rep(FALSE,n) else fix <- FALSE
if(homogen) hhom <- rep(0,n) else hhom <- 0
chcorr <- numeric(max(1,dv*(dv-1)/2))
mc.cores <- setCores(,reprt=FALSE)
dv2 <- dv*dv
while (hakt<=hmax) {
twohp1 <- 2*trunc(hakt)+1
hakt0 <- hakt
if(lambda[step+1]<1e20){
zobj <- .Fortran(C_awsvimg0,
as.integer(img),
fix=as.integer(fix),
as.integer(n1),
as.integer(n2),
as.integer(n1*n2),
as.integer(dv),
as.double(vobj$coef),
as.integer(nvarpar),
as.double(vobj$meanvar),
as.double(chcorr),
hakt=as.double(hakt),
hhom=as.double(hhom),
as.double(lambda0),
as.integer(theta),
bi=as.double(bi),
bi0=as.double(bi0),
theta=integer(prod(dimg)),
as.integer(lkern),
as.double(spmin),
as.double(sqrt(wghts)),
double(twohp1*twohp1),
as.logical(earlystop),
as.logical(homogen),
PACKAGE="adimpro")[c("bi","bi0","theta","hakt","hhom","fix")]
theta <- zobj$theta
bi <- zobj$bi
bi0 <- zobj$bi0
hhom <- zobj$hhom
fix <- zobj$fix
dim(theta) <- switch(imgtype,greyscale=dimg,rgb=dimg[c(3,1,2)])
rm(zobj)
gc()
dim(bi) <- dimg[1:2]
if (graph) {
graphobj <- graphobj0
class(graphobj) <- "adimpro"
graphobj$img <- object$img
show.image(graphobj,max.x=max.pixel,xaxt="n",yaxt="n")
title("Observed Image")
graphobj$img <- switch(imgtype,greyscale=theta,rgb=aperm(theta,c(2,3,1)))
show.image(graphobj,max.x=max.pixel,xaxt="n",yaxt="n")
title(paste("Reconstruction h=",signif(hakt,3)))
graphobj$img <- matrix(as.integer(65534*bi/bi0),n1,n2)
graphobj$type <- "greyscale"
graphobj$gamma <- FALSE
show.image(graphobj,max.x=max.pixel,xaxt="n",yaxt="n")
title(paste("Adaptation (rel. weights):",signif(mean(bi)/bi0,3)))
rm(graphobj)
gc()
}
if(lambda0<1e20){
zobj0 <- .Fortran(C_awsimg0,
as.integer(img),
as.integer(n1),
as.integer(n2),
as.integer(dv),
as.double(hpre),
theta=integer(prod(dimg)),
bi=double(n1*n2),
as.integer(lkern),
double(twohp1*twohp1),
double(dv*mc.cores),
PACKAGE="adimpro")[c("bi","theta")]
theta0 <- zobj0$theta
bi00 <- zobj0$bi
if(dv==1) risk <- mean(sqrt(zobj0$bi*(theta-theta0)^2/vobj$coef)) else {
dim(theta0) <- switch(imgtype,greyscale=dimg,rgb=dimg[c(3,1,2)])
risk1 <- mean(sqrt(zobj0$bi*(theta[1,,]-theta0[1,,])^2/vobj$coef[1]))
risk2 <- mean(sqrt(zobj0$bi*(theta[1,,]-theta0[2,,])^2/vobj$coef[2]))
risk3 <- mean(sqrt(zobj0$bi*(theta[1,,]-theta0[3,,])^2/vobj$coef[3]))
risk <- (risk1+risk2+risk3)/3
}
} else {
risk <- 0
}
progress <- progress + hincr^(2*step)
cat("Bandwidth",signif(hakt,3),"lambda",signif(lambda0,3),"risk",signif(risk,3)," Progress",signif(progress/total,2)*100,"% \n")
vobj <- .Fortran(C_esigmac,
as.integer(object$img),
as.integer(n1*n2),
as.integer(dv),
as.integer(switch(imgtype,
greyscale=theta,
rgb=aperm(theta,c(2,3,1)))),
as.double(bi),
as.integer(imgq995),
coef=double(nvarpar*dv),
meanvar=double(dv),
PACKAGE="adimpro")[c("coef","meanvar")]
cat("Estimated mean variance",signif(vobj$meanvar/65635^2,3),"\n")
}
step <- step + 1
hakt <- hakt*hincr
lambda0 <- lambda[step]
}
if(graph) par(oldpar)
object$img <- switch(imgtype,greyscale=theta,
rgb=aperm(theta,c(2,3,1)))
ni <- array(1,dimg0[1:2])
ni <- bi
object$ni <- ni
object$ni0 <- bi0
object$hmax <- hakt/hincr
object$call <- args
vobj$coef <- vobj$coef/65535^2
object$varcoef <- vobj$coef
object$wghts <- vobj$wghts
invisible(object)
} |
summary.brma <- function(object, ...){
out <- object[na.omit(match(c("coefficients", "tau2", "I2", "H2", "R2", "k"), names(object)))]
out$method <- object$fit@stan_args[[1]]$method
out$algorithm <- object$fit@stan_args[[1]]$algorithm
class(out) <- c("brma_sum", class(out))
return(out)
}
.extract_samples <- function(sim, par, ...){
unlist(lapply(1:sim$chains, function(i) {
if (sim$warmup2[i] == 0){
sim$samples[[i]][[par]]
} else {
sim$samples[[i]][[par]][-(1:sim$warmup2[i])]
}
}))
}
print.brma <- function(x, ...){
print(summary(x))
}
print.brma_sum <- function(x, digits = 2, ...){
cat("BRMA mixed-effects model (k = ", x$k, "), method: ", x$algorithm, " ", x$method, "\n", sep = "")
cat("tau^2: ", formatC(x$tau2, digits = digits, format = "f"), " (SE = ", formatC(x$coefficients["tau2", 2], digits = digits, format = "f"),")\n\n", sep = "")
coefs <- x$coefficients
pstars <- c("*", "")[as.integer(apply(coefs[, c("2.5%", "97.5%")], 1, function(x){sum(sign(x)) == 0}))+1]
coefs <- formatC(coefs, digits = digits, format = "f")
coefs <- cbind(coefs, pstars)
colnames(coefs)[ncol(coefs)] <- ""
prmatrix(coefs, quote = FALSE, right = TRUE, na.print = "")
cat("\n*: This coefficient is significant, as the 95% credible interval excludes zero.")
} |
.is.msaenet <- function(x) "msaenet" %in% class(x)
.is.glmnet <- function(x) "glmnet" %in% class(x)
.is.ncvreg <- function(x) "ncvreg" %in% class(x)
.is.adaptive <- function(x)
any(class(x) %in% c("msaenet.aenet", "msaenet.amnet", "msaenet.asnet"))
.is.multistep <- function(x)
any(class(x) %in% c("msaenet.msaenet", "msaenet.msamnet", "msaenet.msasnet"))
.aic <- function(deviance, df)
deviance + (2L * df)
.bic <- function(deviance, df, nobs)
deviance + (log(nobs) * df)
.ebic <- function(deviance, df, nobs, nvar, gamma)
deviance + (log(nobs) * df) + (2L * gamma * lchoose(nvar, df))
.deviance <- function(model) {
if (.is.glmnet(model)) return((1L - model$"dev.ratio") * model$"nulldev")
if (.is.ncvreg(model)) return(model$"loss")
}
.df <- function(model) {
if (.is.glmnet(model)) return(model$"df")
if (.is.ncvreg(model)) {
return(unname(colSums(
as.matrix(abs(model$"beta"[-1L, ])) > .Machine$double.eps
)))
}
}
.nobs <- function(model) {
if (.is.glmnet(model)) return(model$"nobs")
if (.is.ncvreg(model)) return(model$"n")
}
.nvar <- function(model) {
if (.is.glmnet(model)) return(model$"dim"[[1L]])
if (.is.ncvreg(model)) return(length(model$"penalty.factor"))
} |
whiteKernGradient <-
function (kern, x, x2, covGrad) {
if ( nargs()==3 ) {
covGrad <- x2
g <- sum(diag(as.matrix(covGrad)))
} else {
g <- 0
}
return (g)
} |
mse.saery.boot.AR1.typeI <-
function(X, D, md, beta, sigma2edi, sigmau1, sigmau2, rho, Fsig, B){
sigmau1.gorro.ast <- sigmau2.gorro.ast <- rho.gorro.ast <- vector()
u1 <- u1d <- u1di <- mudi.ast.1 <- u2d <- u2di <- beta.gorro.ast <- beta.gorro1.ast <- mudi.gorro.ast.1 <- u1di.gorro.ast <- u1di.gorro.ast2 <- u1d.gorro.ast <- u1d.gorro.ast2 <- u2di.gorro.ast <- list()
beta.tilde.ast <- beta.tilde1.ast <- u1d.tilde.ast <- u1di.tilde.ast <- u2di.tilde.ast <- mudi.tilde.ast.1 <- mudi.tilde.ast.1 <- list()
g1g2g3 <- g123.AR1(X, D, md, sigma2edi, sigmau1, sigmau2, rho, Fsig)
mse.boot.AR1.typeI <- g1g2g3[[1]] + g1g2g3[[2]]
Badg2 <- 0
b <- BadTot2 <- 0
M <- sum(md)
mse.boot.AR <- difmud <- mse.last.boot.AR <- 0
excepcion <- vector()
while(b<B){
b <- b+1
edi <- rnorm(M,0,sqrt(sigma2edi))
u1di <- 0
u2di <- 0
for(d in 1:D){
u1 <- rnorm(1,0,sqrt(sigmau1))
u1d[[d]] <- rep(u1,md[d])
epdi <- rnorm(md[d],0,sqrt(sigmau2))
u2di <- (1/(1-rho^2)^0.5)*epdi[1]
for(i in 2:md[d])
u2di[i] <- rho*u2di[i-1]+epdi[i]
u2d[[d]] <- u2di
}
u1di <- unlist(u1d)
u2di <- unlist(u2d)
ydi.ast1 <- as.vector(X%*%beta + u1di + u2di + edi)
mudi.ast.1[[b]] <- as.vector(X%*%beta + u1di + u2di)
sigma.0 <- sigmau1
fitboot <- try(REML.saery.AR1(X, ydi.ast1, D, md, sigma2edi, sigma1.0=sigma.0,sigma2.0=sigma.0), TRUE)
if(class(fitboot)=="try-error"){
excepcion <- c(excepcion, b)
write.table(data.frame(class(fitboot),D,b), file="WARNING.txt", append=TRUE, col.names=FALSE, row.names=FALSE)
b <- b-1
}
else {
cat("Bootstrap sample no. " , b,"\n")
sigmau1.gorro.ast <- fitboot[[1]][1]
sigmau2.gorro.ast <- fitboot[[1]][2]
rho.gorro.ast <- fitboot[[1]][3]
beta.gorro.ast[[b]] <- BETA.U.saery.AR1(X, ydi.ast1, D, md, sigma2edi, sigmau1.gorro.ast, sigmau2.gorro.ast, rho.gorro.ast)
beta.gorro1.ast[[b]] <- beta.gorro.ast[[b]][[1]]
u1d.gorro.ast[[b]] <- beta.gorro.ast[[b]][[2]]
u1di.gorro.ast[[b]] <- list()
for(d in 1:D)
u1di.gorro.ast[[b]][[d]] <- rep(u1d.gorro.ast[[b]][d,1],md[d])
u1di.gorro.ast[[b]] <- unlist(u1di.gorro.ast[[b]])
u2di.gorro.ast[[b]] <- beta.gorro.ast[[b]][[3]]
mudi.gorro.ast.1[[b]] <- as.vector(X%*%beta.gorro1.ast[[b]] + u1di.gorro.ast[[b]]+ u2di.gorro.ast[[b]])
beta.tilde.ast[[b]] <- BETA.U.saery.AR1(X, ydi.ast1, D, md, sigma2edi, sigmau1, sigmau2, rho)
beta.tilde1.ast[[b]] <- beta.tilde.ast[[b]][[1]]
u1d.tilde.ast[[b]] <- beta.tilde.ast[[b]][[2]]
u1di.tilde.ast[[b]] <- list()
for(d in 1:D)
u1di.tilde.ast[[b]][[d]] <- rep(u1d.tilde.ast[[b]][d,1],md[d])
u1di.tilde.ast[[b]] <- unlist(u1di.tilde.ast[[b]])
u2di.tilde.ast[[b]] <- beta.tilde.ast[[b]][[3]]
mudi.tilde.ast.1[[b]] <- as.vector(X%*%beta.tilde1.ast[[b]] + u1di.tilde.ast[[b]]+ u2di.tilde.ast[[b]])
difmud <- difmud + (mudi.gorro.ast.1[[b]]-mudi.tilde.ast.1[[b]])^2
}
}
mse.boot.AR1.typeI <- mse.boot.AR1.typeI + difmud/B
return(mse.boot.AR1.typeI)
} |
ts_pc <- function(x) {
ts_apply(ts_regular(x), function(x) {
value <- NULL
x[, list(time, value = 100 * (value / c(NA, value[-length(value)]) - 1))]
})
}
ts_diff <- function(x) {
ts_apply(ts_regular(x), function(x) {
value <- NULL
x[, list(time, value = value - c(NA, value[-length(value)]))]
})
}
ts_pca <- function(x) {
ts_apply(ts_regular(x), function(x) {
fr <- frequency_one(x$time)$freq
value <- NULL
x[
,
list(time, value = 100 * ((value / c(NA, value[-length(value)]))^fr - 1))
]
})
}
ts_pcy <- function(x) {
ts_apply(ts_regular(x), function(x) {
value <- NULL
value_lag <- NULL
xlag <- data.table(time = time_shift(x$time, "1 year"), value_lag = x$value)
xlag[x, on = "time"][, list(time, value = (value / value_lag - 1) * 100)]
})
}
ts_diffy <- function(x) {
ts_apply(ts_regular(x), function(x) {
value <- NULL
value_lag <- NULL
xlag <- data.table(time = time_shift(x$time, "1 year"), value_lag = x$value)
xlag[x, on = "time"][, list(time, value = value - value_lag)]
})
} |
set.seed(5555)
candle_df1t3 <- data.frame(
Cycle = as.factor(rep(1:24, each=3)),
candle_width = rnorm(n = 3*24, mean = 10, sd = 1),
mold_cell = as.ordered(rep(1:3))
)
candle_df4 <- data.frame(
Cycle = as.factor(rep(1:24, each=1)),
candle_width = rnorm(n = 1*24, mean = 11, sd = 2),
mold_cell = as.ordered(rep(4, each=24))
)
candle_df <- rbind(candle_df1t3, candle_df4)
library(ggplot2)
library(ggQC)
XbarR <- ggplot(candle_df, aes(x = Cycle, y = candle_width, group = 1)) +
stat_summary(fun.y = mean, geom = "point") +
stat_summary(fun.y = mean, geom = "line") +
stat_QC()
XbarR
XbarR + stat_QC_labels()
R_Bar <- ggplot(candle_df, aes(x = Cycle, y = candle_width, group = 1)) +
stat_summary(fun.y = QCrange, geom = "point") +
stat_summary(fun.y = QCrange, geom = "line") +
stat_QC(method="rBar") +
stat_QC_labels(method="rBar") + ylab("R-Bar")
R_Bar
XbarR <- ggplot(candle_df, aes(x = Cycle, y = candle_width, group = 1)) +
stat_summary(fun.y = mean, geom = "point") +
stat_summary(fun.y = mean, geom = "line") +
stat_QC() + stat_QC_labels() +
geom_point(alpha= 1/5) +
stat_QC(n=1, color.qc_limits = "orange") +
stat_QC_labels(n=1, color.qc_limits = "orange")
XbarR
XbarR <- ggplot(candle_df, aes(x = Cycle, y = candle_width, group = 1, color=mold_cell)) +
stat_summary(fun.y = mean, geom = "point") +
stat_summary(fun.y = mean, geom = "line") +
stat_QC() + stat_QC_labels() +
geom_point(alpha= 1/2) +
stat_QC(n=1, color.qc_limits = "orange") +
stat_QC_labels(n=1, color.qc_limits = "orange")
XbarR
XmR <- ggplot(candle_df,
aes(x = Cycle, y = candle_width, group = 1, color = mold_cell)) +
geom_point() + geom_line() +
stat_QC(method="XmR") + stat_QC_labels(method="XmR") +
facet_grid(.~mold_cell)
XmR |
get_auxiliary <- function(x, type = "sigma", summary = TRUE, centrality = "mean", verbose = TRUE, ...) {
type <- match.arg(type, choices = .aux_elements())
if (inherits(x, "brmsfit")) {
return(.get_generic_aux(x, type, summary = summary, centrality = centrality))
} else if (type == "sigma") {
return(as.numeric(get_sigma(x)))
} else if (type == "dispersion") {
return(get_dispersion(x))
} else {
return(NULL)
}
}
get_dispersion <- function(x, ...) {
UseMethod("get_dispersion")
}
get_dispersion.model_fit <- function(x, ...) {
get_dispersion(x$fit, ...)
}
get_dispersion.glm <- function(x, verbose = TRUE, ...) {
info <- model_info(x, verbose = verbose)
disp <- NULL
if (info$is_poisson || info$is_binomial || info$is_negbin) {
disp <- 1
} else {
working_weights <- get_weights(x, type = "working")
working_res <- as.vector(get_residuals(x, type = "working"))^2 * working_weights
disp <- sum(working_res[working_weights > 0]) / get_df(x, type = "residual")
}
disp
}
get_dispersion.glmerMod <- function(x, verbose = TRUE, ...) {
info <- model_info(x, verbose = verbose)
disp <- NULL
if (info$is_poisson || info$is_binomial || info$is_negbin) {
disp <- 1
} else {
res_df <- get_df(x, type = "residual")
p_res <- get_residuals(x, type = "pearson")
disp <- sum(p_res^2) / res_df
}
disp
}
get_dispersion.glmmTMB <- function(x, verbose = TRUE, ...) {
info <- model_info(x, verbose = verbose)
disp <- NULL
if (info$is_poisson || info$is_binomial || info$is_negbin) {
disp <- 1
} else {
disp <- as.numeric(get_sigma(x))^2
}
disp
}
get_dispersion.brmsfit <- get_dispersion.glmmTMB
.get_generic_aux <- function(x, param, summary = TRUE, centrality = "mean", ...) {
aux <- NULL
if (inherits(x, "brmsfit")) {
aux <- as.data.frame(x)[[param]]
if (summary) {
aux <- .summary_of_posteriors(aux, centrality = centrality)
}
}
aux
} |
print.MVA.test.mult <- function(x,digits=4,...) {
cat("\n")
cat(strwrap(x$method,prefix="\t"),sep="\n")
cat("\n")
cat("data: ",x$data.name,"\n\n")
tab <- data.frame(Response=names(x$p.value),Q2=x$statistic,P=x$p.value)
print(tab,digits=digits,row.names=FALSE)
cat(paste("\nP value adjustment method: ",x$p.adjust.method,"\n",sep=""))
invisible(x)
}
MVA.test <- function(X,Y,cmv=FALSE,ncomp=8,kout=7,kinn=6,scale=TRUE,model=c("PLSR","CPPLS","PLS-DA","PPLS-DA","LDA",
"QDA","PLS-DA/LDA","PLS-DA/QDA","PPLS-DA/LDA","PPLS-DA/QDA"),Q2diff=0.05,lower=0.5,upper=0.5,Y.add=NULL,
weights=rep(1,nrow(X)),set.prior=FALSE,crit.DA=c("plug-in","predictive","debiased"),p.method="fdr",nperm=999,
progress=TRUE,...) {
model <- match.arg(model)
if (model %in% c("LDA","QDA") & cmv) {stop("LDA and QDA alone only if cmv = FALSE")}
dname <- paste0(deparse(substitute(X))," and ",deparse(substitute(Y)),"\nModel: ",model,
"\n",ncomp," components",ifelse(cmv," maximum",""),"\n",nperm," permutations")
if (!cmv) {
testname <- "Permutation test based on cross-validation"
cv.ref <- MVA.cv(X,Y,repet=20,k=kout,ncomp=ncomp,scale=scale,model=model,lower=lower,upper=upper,Y.add=Y.add,
weights=weights,set.prior=set.prior,crit.DA=crit.DA,...)
} else {
testname <- "Permutation test based on cross model validation"
cv.ref <- MVA.cmv(X,Y,repet=20,kout=kout,kinn=kinn,ncomp=ncomp,scale=scale,model=model,crit.inn=ifelse(is.factor(Y),"NMC","Q2"),
Q2diff=Q2diff,lower=lower,upper=upper,Y.add=Y.add,weights=weights,set.prior=set.prior,crit.DA=crit.DA,...)
}
if(cv.ref$type=="quant") {
ref <- colMeans(cv.ref$Q2)
names(ref) <- if (ncol(as.data.frame(Y))==1) {"Q2"} else {paste("Q2",colnames(Y),sep=".")}
} else {
ref <- mean(as.vector(cv.ref$NMC))
names(ref) <- "CER"
}
if (cv.ref$type=="quant" & ncol(as.data.frame(Y))>1) {
stat.perm <- matrix(0,nrow=nperm+1,ncol=ncol(Y))
stat.perm[1,] <- ref
} else {
stat.perm <- numeric(nperm+1)
stat.perm[1] <- ref
}
if (progress) {pb <- txtProgressBar(min=0,max=100,initial=0,style=3)}
for(i in 1:nperm) {
if (progress) {setTxtProgressBar(pb,round(i*100/nperm,0))}
if (!cmv) {
if (cv.ref$type=="quant" & ncol(as.data.frame(Y))>1) {
cv.perm <- MVA.cv(X,Y[sample(1:nrow(Y)),],repet=1,k=kout,ncomp=ncomp,scale=scale,model=model,lower=lower,upper=upper,
Y.add=Y.add,weights=weights,set.prior=set.prior,crit.DA=crit.DA,...)
} else {
cv.perm <- suppressWarnings(MVA.cv(X,sample(Y),repet=1,k=kout,ncomp=ncomp,scale=scale,model=model,lower=lower,
upper=upper,Y.add=Y.add,weights=weights,set.prior=set.prior,crit.DA=crit.DA,...))
}
} else {
if (cv.ref$type=="quant" & ncol(as.data.frame(Y))>1) {
cv.perm <- MVA.cmv(X,Y[sample(1:nrow(Y)),],repet=1,kout=kout,kinn=kinn,ncomp=ncomp,scale=scale,model=model,
crit.inn=ifelse(is.factor(Y),"NMC","Q2"),Q2diff=Q2diff,lower=lower,upper=upper,
Y.add=Y.add,weights=weights,set.prior=set.prior,crit.DA=crit.DA,...)
} else {
cv.perm <- suppressWarnings(MVA.cmv(X,sample(Y),repet=1,kout=kout,kinn=kinn,ncomp=ncomp,scale=scale,model=model,
crit.inn=ifelse(is.factor(Y),"NMC","Q2"),Q2diff=Q2diff,lower=lower,upper=upper,Y.add=Y.add,
weights=weights,set.prior=set.prior,crit.DA=crit.DA,...))
}
}
if (cv.ref$type=="quant" & ncol(as.data.frame(Y))>1) {
stat.perm[i+1,] <- cv.perm$Q2
} else {
stat.perm[i+1] <- if(cv.ref$type=="quant") {as.vector(cv.perm$Q2)} else {as.vector(cv.perm$NMC)}
}
}
if (progress) {cat("\n")}
if (cv.ref$type=="quant") {
if (ncol(as.data.frame(Y))==1) {
pvalue <- length(which((stat.perm+.Machine$double.eps/2) >= ref))/(nperm+1)
} else {
pvalue <- numeric(ncol(Y))
for (i in 1:ncol(Y)) {pvalue[i] <- length(which((stat.perm[,i]+.Machine$double.eps/2) >= ref[i]))/(nperm+1)}
pvalue <- p.adjust(pvalue,method=p.method)
names(pvalue) <- colnames(Y)
}
} else {
pvalue <- length(which((stat.perm-.Machine$double.eps/2) <= ref))/(nperm+1)
}
result <- list(method=testname,data.name=dname,statistic=ref,permutations=nperm,p.value=pvalue,
p.adjust.method=p.method)
class(result) <- ifelse(cv.ref$type=="quant" & ncol(as.data.frame(Y))>1,"MVA.test.mult","htest")
return(result)
} |
mspa <- function(dudi, lwORorthobasisSp, nblocks, scannf = TRUE, nf = 2, centring = c("param", "sim"), nperm = 999){
if (!inherits(dudi, "dudi"))
stop("object of class 'dudi' expected")
if(inherits(lwORorthobasisSp,"orthobasisSp")){
if (any((dudi$lw - attr(lwORorthobasisSp,"weights"))^2 > 1e-07))
stop("Non equal row weights")
U <- lwORorthobasisSp
}
if(inherits(lwORorthobasisSp,"listw"))
U <- scores.listw(lwORorthobasisSp, wt = dudi$lw, MEM.autocor = "all")
if(ncol(U) != (nrow(U) - 1))
stop(paste("The orthobasis contains only", ncol(U), "vectors. The decomposition of variance is thus incomplete."))
df <- dudi$tab
varweights <- dudi$cw/sum(dudi$cw)
n <- nrow(df)
p <- ncol(df)
centring <- match.arg(centring)
findname <- function(vec){
if(length(vec) == 1) return(vec)
res <- sub("[.][^.]*$","",vec[1])
return(res)
}
var.idx <- dudi$assign
if(!is.null(var.idx)){
temp <- split(colnames(df), var.idx)
newlev <- sapply(temp, findname)
levels(var.idx) <- newlev
}
X <- scalewt(df, wt = dudi$lw, center=TRUE, scale=TRUE)
R <- t(X) %*% diag(dudi$lw) %*% as.matrix(U)
R2 <- R*R
if(centring=="param"){
newdf <- R2-(1/(n-1))
} else{
tempX <- t(X)
fPerm <- function(X){
permX <- X[, sample(1:n)]
res <- permX %*% diag(dudi$lw) %*% as.matrix(U)
res <- res * res
return(res)
}
listR2sim <- lapply(1:nperm, function(i) fPerm(tempX))
meanR2sim <- listR2sim[[1]]
for(i in 2:nperm){
meanR2sim <- meanR2sim + listR2sim[[i]]
}
meanR2sim <- meanR2sim / nperm
newdf <- R2 - meanR2sim
}
newdf[newdf < 0] <- 0
if(!(missing(nblocks))){
fac <- cut(1:ncol(U), nblocks)
i.start <- tapply(1:ncol(U), fac, min)
i.stop <- tapply(1:ncol(U), fac, max)
levels(fac) <- paste("[", i.start, "-", i.stop, "]", sep="")
newdf <- t(apply(newdf, 1, function(i) tapply(i, fac, sum)))
R2 <- t(apply(R2, 1, function(i) tapply(i, fac, sum)))
}
newdf <- as.data.frame(newdf)
res <- as.dudi(newdf, scannf = scannf, nf = nf, row.w = varweights,
col.w = rep(1, ncol(newdf)), call = match.call(), type = "mspa")
res$ls <- as.data.frame(as.matrix(R2) %*% as.matrix(res$c1))
colnames(res$ls) <- colnames(res$li)
row.names(res$ls) <- row.names(res$li)
xmoy <- apply(R2, 2, function(c) weighted.mean(c,varweights))
bary <- as.vector(t(xmoy) %*% as.matrix(res$c1))
names(bary) <- colnames(res$c1)
res$R2 <- R2
res$meanPoint <- bary
res$varweights <- varweights
names(res$varweights) <- colnames(X)
if(!is.null(var.idx)) res$assign <- var.idx
if(centring=="sim") {
res$centring <- meanR2sim
if(!(missing(nblocks)))
res$centring <- tapply(meanR2sim, fac, sum)
}
return(res)
}
scatter.mspa <- function(x, xax = 1, yax = 2, posieig = "topleft", bary=TRUE,
plot = TRUE, storeData = TRUE, pos = -1, ...){
if(!inherits(x,"mspa"))
stop("Object of class 'mspa' expected")
if((xax == yax) || (x$nf == 1))
stop("One axis only : not yet implemented")
if(length(xax) > 1 | length(yax) > 1)
stop("Not implemented for multiple xax/yax")
if(xax > x$nf)
stop("Non convenient xax")
if(yax > x$nf)
stop("Non convenient yax")
position <- match.arg(posieig[1], choices = c("bottomleft", "bottomright", "topleft", "topright", "none"), several.ok = FALSE)
graphsnames <- c("mem", "var", "bary", "eig")
sortparameters <- sortparamADEgS(..., graphsnames = graphsnames)
params <- list()
params$mem <- list(plabels = list(cex = 1))
params$var <- list(plabels = list(cex = 1.5))
params$eig <- list(pbackground = list(box = TRUE), psub = list(text = "Eigenvalues"))
if(bary)
params$bary = list(ppoints = list(pch = 20, cex = 2, col = "black"))
sortparameters <- modifyList(params, sortparameters, keep.null = TRUE)
g1 <- do.call("s.arrow", c(list(dfxy = substitute(x$c1), xax = xax, yax = yax, plot = FALSE, storeData = storeData, pos = pos - 2), sortparameters$mem))
g2 <- do.call("s.label", c(list(dfxy = substitute(x$ls), xax = xax, yax = yax, plot = FALSE, storeData = storeData, pos = pos - 2), sortparameters$var))
object <- do.call("superpose", list(g1@Call, g2@Call))
if(bary){
g3 <- xyplot(x$meanPoint[yax] ~ x$meanPoint[xax], col = sortparameters$bary$ppoints$col, pch = sortparameters$bary$ppoints$pch, cex = sortparameters$bary$ppoints$cex, xlab = "", ylab = "", aspect = [email protected]$paxes$aspectratio)
object <- do.call("superpose", list(object@Call, g3))
}
if(position != "none") {
g4 <- do.call("plotEig", c(list(eigvalue = substitute(x$eig), nf = 1:x$nf, xax = xax, yax = yax, plot = FALSE), sortparameters$eig))
object <- do.call("insert", list(g4@Call, object@Call, posi = position, ratio = 0.25, plot = FALSE))
}
names(object) <- graphsnames[c(1, 2, 3 * isTRUE(bary), 4 * (position != "none"))]
object@Call <- match.call()
if(plot)
print(object)
invisible(object)
}
print.mspa <- function(x, ...){
cat("Multi-Scale Pattern Analysis\n")
cat("call: ")
print(x$call)
cat("class: ")
cat(class(x), "\n")
cat("\n$rank (rank) :", x$rank)
cat("\n$nf (axis saved) :", x$nf)
cat("\n\neigen values: ")
l0 <- length(x$eig)
cat(signif(x$eig, 4)[1:(min(5, l0))])
if (l0 > 5)
cat(" ...\n\n")
else cat("\n\n")
sumry <- array("", c(3, 4), list(1:3, c("vector", "length",
"mode", "content")))
sumry[1, ] <- c("$eig", length(x$eig), mode(x$eig), "Eigenvalues")
sumry[2, ] <- c("$cw", length(x$cw), mode(x$cw), "MEM weights")
sumry[3, ] <- c("$lw", length(x$lw), mode(x$lw), "variables weights")
print(sumry, quote = FALSE)
cat("\n")
sumryA <- array("", c(4, 4), list(1:4, c("data.frame", "nrow", "ncol", "content")))
sumryA[1, ] <- c("$R2", nrow(x$R2), ncol(x$R2), "Matrix of R2 ('S')")
sumryA[2, ] <- c("$tab", nrow(x$tab), ncol(x$tab), "Matrix of centred R2 ('Z')")
sumryA[3, ] <- c("$c1", nrow(x$c1), ncol(x$c1), "Principal axes, i.e. MEM loadings('A')")
sumryA[4, ] <- c("$ls", nrow(x$ls), ncol(x$ls), "Projection of variables (R2) on principal axes ('B')")
cat("\nMain components:\n")
print(sumryA, quote = FALSE)
sumryB <- array("", c(3, 4), list(1:3, c("data.frame", "nrow", "ncol", "content")))
sumryB[1, ] <- c("$li", nrow(x$li), ncol(x$li), "Scores for variables")
sumryB[2, ] <- c("$l1", nrow(x$l1), ncol(x$l1), "Principal components")
sumryB[3, ] <- c("$co", nrow(x$co), ncol(x$co), "Scores for MEM")
cat("\nGeneric 'dudi' components:\n")
print(sumryB, quote = FALSE)
cat("Other elements: ")
if (length(names(x)) > 14)
cat(names(x)[15:(length(x))], "\n")
else cat("NULL\n")
} |
as_r <- function(f, ...) {
UseMethod("as_r")
}
as_r.default <- function(f, support = NULL, ..., n_grid = 10001,
n_sample = 10000, args_new = list()) {
assert_as_def_args(f, support, n_grid)
assert_type(
n_sample, is_single_number,
type_name = "single number more than 1", min_val = 2
)
assert_type(args_new, is.list)
f_name <- deparse(substitute(f))
honored_distr <- as_honored_distr(
"r", f_name, f, support, ..., n_grid = n_grid
)
if (!is.null(honored_distr)) {
return(honored_distr)
}
smpl <- f(n_sample, ...)
support <- detect_support_r(smpl, format_support(support))
disable_asserting_locally()
new_call_args <- c_dedupl(list(x = smpl, type = "continuous"), args_new)
d_f <- do.call(new_d, new_call_args)
d_f <- as_d(unpdqr(d_f), support = support, n_grid = n_grid)
as_r(d_f)
}
as_r.pdqr <- function(f, ...) {
assert_pdqr_fun(f)
disable_asserting_locally()
new_r(x = meta_x_tbl(f), type = meta_type(f))
}
detect_support_r <- function(smpl, supp) {
mean_diff <- mean(diff(sort(smpl)))
smpl_support <- range(smpl) + mean_diff * c(-1, 1)
supp <- coalesce_pair(supp, smpl_support)
if (!is_support(supp) || (supp[1] == supp[2])) {
stop_collapse(
"Detected support isn't proper. Usually this is because input random ",
"generation function isn't proper."
)
}
supp
} |
setClass("SolrExpression", contains=c("Expression", "VIRTUAL"))
setClass("SolrFunctionExpression",
representation(name="ANY"),
prototype(name=""),
contains="SolrExpression")
setClass("SolrLuceneExpression", contains=c("SolrExpression", "VIRTUAL"))
setClass("SolrSymbol",
representation(missable="logical"),
prototype(missable=TRUE),
contains=c("SimpleSymbol", "SolrFunctionExpression"),
validity=function(object) {
if (!isTRUEorFALSE(object@missable)) {
"'missable' must be TRUE or FALSE"
}
})
setClassUnion("SolrSymbolORNULL", c("SolrSymbol", "NULL"))
setClass("SolrLuceneSymbol", contains="SolrSymbol")
setClass("PredicatedSolrSymbol",
representation(subject="SolrSymbol",
predicate="SolrExpression"),
contains="SolrExpression")
setClass("SolrLuceneBinaryOperator",
representation(e1="SolrLuceneExpression",
e2="SolrLuceneExpression"),
contains=c("SolrLuceneExpression", "VIRTUAL"))
setClass("SolrLuceneAND", contains="SolrLuceneBinaryOperator")
setClass("SolrLuceneOR", contains="SolrLuceneBinaryOperator")
setClass("SolrLuceneUnaryOperator",
representation(e1="SolrLuceneExpression"),
contains=c("SolrLuceneExpression", "VIRTUAL"))
setClass("SolrLuceneProhibit", contains="SolrLuceneUnaryOperator")
setClass("SolrLuceneTerm",
representation(field="SolrSymbolORNULL",
term="ANY",
inverted="logical"),
prototype(inverted=FALSE),
contains="SolrLuceneExpression",
validity=function(object) {
if (!isTRUEorFALSE(object@inverted))
"'inverted' must be TRUE or FALSE"
})
setClass("LuceneRange",
representation(from="ANY", to="ANY",
fromInclusive="logical", toInclusive="logical"),
prototype(fromInclusive=FALSE, toInclusive=FALSE),
validity=function(object) {
if (!isTRUEorFALSE(object@fromInclusive) ||
!isTRUEorFALSE(object@toInclusive))
"fromInclusive and toInclusive must be TRUE or FALSE"
})
setClass("SolrLuceneRangeTerm",
representation(term="LuceneRange"),
contains="SolrLuceneTerm")
setClass("SolrQParserExpression",
representation(query="Expression",
useValueParam="logical",
tag="character_OR_NULL"),
prototype(useValueParam=FALSE),
contains="SolrExpression",
validity=function(object) {
if (!is.null(object@tag) && !isSingleString(object@tag))
"'tag' must be a single, non-NA string, or NULL"
})
setClassUnion("SolrLuceneExpressionOrSymbol",
c("SolrLuceneExpression", "SolrQParserExpression", "SolrSymbol"))
setClass("LuceneQParserExpression",
representation(query="SolrLuceneExpression"),
contains="SolrQParserExpression")
setClassUnion("numericORNULL", c("numeric", "NULL"))
setClass("FRangeQParserExpression",
representation(l="numericORNULL",
u="numericORNULL",
incl="logical",
incu="logical",
query="SolrFunctionExpression"),
prototype(incl=TRUE,
incu=TRUE),
contains="SolrQParserExpression",
validity=function(object) {
c(if (!(is.null(object@l) || isSingleNumber(object@l)) ||
!(is.null(object@u) || isSingleNumber(object@u))) {
"'l' and 'u' each must be a single, non-NA number, or NULL"
}, if (!isTRUEorFALSE(object@incl) ||
!isTRUEorFALSE(object@incu)) {
"'incl' and 'incu' must be TRUE or FALSE"
})
})
setClass("JoinQParserExpression",
representation(from="SolrSymbol",
to="SolrSymbol",
query="SolrLuceneExpression"),
contains="SolrQParserExpression")
setClass("AbstractSolrFunctionCall")
setClass("SolrFunctionCall",
representation(name="character",
args="list",
missables="character"),
contains=c("AbstractSolrFunctionCall", "SolrFunctionExpression"),
validity=function(object) {
c(if (!isSingleString(object@name))
"'name' of a Solr function call must be a string",
if (any(is.na(object@missables)))
"'missables' must not contain NAs")
})
setClassUnion("functionORNULL", c("function", "NULL"))
setClass("SolrAggregateCall",
representation(name="character",
subject="SolrFunctionExpression",
params="list",
postprocess="functionORNULL"),
contains = c("AbstractSolrFunctionCall", "SolrExpression"),
validity=function(object) {
if (!isSingleString(object@name))
"'name' of a Solr aggregate call must be a string"
})
setClass("ParentSolrAggregateCall",
representation(child="SolrAggregateCall"),
contains="SolrAggregateCall")
setClass("SolrSortExpression",
representation(by="SolrFunctionExpression",
decreasing="logical"),
contains="SolrExpression")
setClass("SolrFilterExpression",
representation(filter="SolrQParserExpression",
tag="character"),
contains="SolrExpression",
validity=function(object) {
})
SolrLuceneOR <- function(e1, e2) {
new("SolrLuceneOR",
e1=as(e1, "SolrLuceneExpression", strict=FALSE),
e2=as(e2, "SolrLuceneExpression", strict=FALSE))
}
SolrLuceneAND <- function(e1, e2) {
new("SolrLuceneAND",
e1=as(e1, "SolrLuceneExpression", strict=FALSE),
e2=as(e2, "SolrLuceneExpression", strict=FALSE))
}
SolrLuceneProhibit <- function(e1) {
new("SolrLuceneProhibit",
e1=as(e1, "SolrLuceneExpression", strict=FALSE))
}
SolrLuceneTerm <- function(field, term) {
new("SolrLuceneTerm",
field=if (!is.null(field)) as(field, "SolrSymbol", strict=FALSE),
term=term)
}
SolrLuceneRangeTerm <- function(field, from, to, fromInclusive, toInclusive) {
new("SolrLuceneRangeTerm", field=field,
term=new("LuceneRange", from=from, to=to,
fromInclusive=fromInclusive, toInclusive=toInclusive))
}
SolrQParserExpression <- function(tag = NULL) {
if (!is.null(tag)) {
tag <- as.character(tag)
}
new("SolrQParserExpression", tag=tag)
}
FRangeQParserExpression <- function(query, l = NULL, u = NULL,
incl = TRUE, incu = TRUE)
{
new("FRangeQParserExpression",
query=as(query, "SolrFunctionExpression", strict=FALSE),
l=l, u=u, incl=incl, incu=incu)
}
LuceneQParserExpression <- function(query) {
new("LuceneQParserExpression",
query=as(query, "SolrLuceneExpression", strict=FALSE))
}
JoinQParserExpression <- function(query, from, to) {
new("JoinQParserExpression",
query=as(query, "SolrLuceneExpression", strict=FALSE),
from=as(from, "SolrSymbol", strict=FALSE),
to=as(to, "SolrSymbol", strict=FALSE))
}
SolrFunctionExpression <- function(name="") {
if (isNA(name)) {
solrNA
} else {
new("SolrFunctionExpression", name=name)
}
}
SolrFunctionCall <- function(name, args) {
new("SolrFunctionCall", name=name, args=args,
missables=missablesForArgs(name, args))
}
SolrAggregateCall <- function(name = "",
subject = SolrFunctionExpression(),
params=list(), child = NULL, postprocess = NULL)
{
obj <- new("SolrAggregateCall", name=name,
subject=as(subject, "SolrFunctionExpression", strict=FALSE),
params=params, postprocess=postprocess)
if (!is.null(child)) {
obj <- new("ParentSolrAggregateCall", obj, child=child)
}
obj
}
SolrSortExpression <- function(decreasing) {
new("SolrSortExpression", decreasing=decreasing)
}
setGeneric("SymbolFactory", function(x, ...) standardGeneric("SymbolFactory"))
setMethod("SymbolFactory", "SolrExpression", function(x) SolrSymbol)
setMethod("SymbolFactory", "SolrQParserExpression",
function(x) SolrLuceneSymbol)
SolrSymbol <- new("SymbolFactory", function(name) {
new("SolrSymbol", name=as.character(name))
})
SolrLuceneSymbol <- new("SymbolFactory", function(name) {
new("SolrLuceneSymbol", name=as.character(name))
})
PredicatedSolrSymbol <- function(subject, predicate) {
new("PredicatedSolrSymbol", subject=subject,
predicate=as(predicate, "SolrExpression", strict=FALSE))
}
setGeneric("args", function(name) standardGeneric("args"))
setMethod("args", "SolrFunctionCall", function(name) name@args)
setMethod("args", "SolrAggregateCall",
function(name) c(name@subject, name@params))
setGeneric("name", function(x) standardGeneric("name"))
setMethod("name", "ANY", function(x) x@name)
`name<-` <- function(x, value) {
x@name <- value
x
}
query <- function(x) x@query
`query<-` <- function(x, value) {
x@query <- value
x
}
setGeneric("tag", function(x, ...) standardGeneric("tag"))
setMethod("tag", "ANY", function(x) NULL)
setMethod("tag", "SolrQParserExpression", function(x) x@tag)
setGeneric("child", function(x) standardGeneric("child"))
setMethod("child", "ANY", function(x) NULL)
setMethod("child", "ParentSolrAggregateCall", function(x) x@child)
setGeneric("child<-", function(x, value) standardGeneric("child<-"))
setReplaceMethod("child", "SolrAggregateCall", function(x, value) {
if (!is.null(value)) {
new("ParentSolrAggregateCall", x, child=value)
} else {
x
}
})
setReplaceMethod("child", "ParentSolrAggregateCall", function(x, value) {
x@child <- value
x
})
resultWidth <- function(x) {
if (name(x) == "percentile")
length(params(x))
else 1L
}
setMethod("translate", c("SolrExpression", "SolrExpression"),
function(x, target, context, ...) {
as(x, class(target), strict=FALSE)
})
missable <- function(x) x@missable
`missable<-` <- function(x, value) {
x@missable <- value
x
}
setGeneric("missables", function(x, fields = NULL) standardGeneric("missables"),
signature="x")
setMethod("missables", "SolrSymbol", function(x) {
if (missable(x)) {
list(name(x))
} else {
list()
}
})
setMethod("missables", "SolrFunctionCall", function(x) x@missables)
setMethod("missables", "SolrFunctionExpression",
function(x) missables(name(x)))
setMethod("missables", "SolrQParserExpression", function(x) missables(query(x)))
setMethod("missables", "SolrLuceneBinaryOperator",
function(x) {
missables <- c(missables(x@e1), missables(x@e2))
naCheck <- if (isLuceneNACheck(x@e1)) x@e1
else if (isLuceneNACheck(x@e2)) x@e2
if (!is.null(naCheck) &&
is(x, "SolrLuceneAND") == naCheck@inverted) {
missables <- setdiff(missables, name(naCheck@field))
}
missables
})
setMethod("missables", "SolrLuceneUnaryOperator", function(x) missables(x@e1))
isLuceneNACheck <- function(x) {
is(x, "SolrLuceneTerm") && identical(x@term, I("*"))
}
setMethod("missables", "SolrLuceneTerm", function(x) {
if (isLuceneNACheck(x)) list() else missables(x@field)
})
setMethod("missables", "ANY", function(x) list())
`missables<-` <- function(x, value) {
x@missables <- value
x
}
isSolrNACheck <- function(fun, args) {
fun == "exists" &&
!(is(args[[1L]], "SolrFunctionCall") && name(args[[1L]]) == "query")
}
missablesForArgs <- function(fun, args) {
if (fun == "if") {
args <- args[1L]
}
as.character(if (!isSolrNACheck(fun, args)) {
unique(unlist(lapply(args, missables)))
})
}
setGeneric("dropMissables", function(x, which) standardGeneric("dropMissables"))
setMethod("dropMissables", "SolrFunctionCall", function(x, which) {
x@missables <- setdiff(x@missables, which)
x@args <- lapply(x@args, dropMissables, which)
x
})
setMethod("dropMissables", "SolrFunctionExpression", function(x, which) {
name(x) <- dropMissables(name(x), which)
x
})
setMethod("dropMissables", "SolrQParserExpression", function(x, which) {
query(x) <- dropMissables(query(x), which)
x
})
setMethod("dropMissables", "SolrLuceneBinaryOperator", function(x, which) {
initialize(x,
e1=dropMissables(x@e1, which),
e2=dropMissables(x@e2, which))
})
setMethod("dropMissables", "SolrLuceneUnaryOperator", function(x, which) {
initialize(x, e1=dropMissables(x@e1, which))
})
setMethod("dropMissables", "SolrLuceneTerm", function(x, which) {
x@field <- dropMissables(x@field, which)
x
})
setMethod("dropMissables", "SolrSymbol", function(x, which) {
missable(x) <- missable(x) && !(name(x) %in% which)
x
})
setMethod("dropMissables", "ANY", function(x) {
x
})
setGeneric("invert", function(x) standardGeneric("invert"))
setMethod("invert", "SolrQParserExpression", function(x) {
x@query <- invert(x@query)
x
})
setMethod("invert", "SolrLuceneAND", function(x) {
SolrLuceneOR(invert(x@e1), invert(x@e2))
})
setMethod("invert", "SolrLuceneOR", function(x) {
SolrLuceneAND(invert(x@e1), invert(x@e2))
})
setMethod("invert", "SolrLuceneProhibit", function(x) {
x@e1
})
setMethod("invert", "SolrLuceneTerm", function(x) {
x@inverted <- !x@inverted
x
})
setMethod("invert", "SolrLuceneRangeTerm", function(x) {
x@term <- invert(x@term)
x
})
setMethod("invert", "LuceneRange", function(x) {
initialize(x, from=x@to, to=x@from,
fromInclusive=!x@toInclusive,
toInclusive=!x@fromInclusive)
})
setMethod("invert", "FRangeQParserExpression", function(x) {
equals <- !is.null(x@u) && identical(x@u, x@l) && x@incl && x@incu
if (equals) {
num <- if (!is.null(x@u)) x@u else x@l
minus <- SolrFunctionCall("sub", list(query(x), num))
expr <- SolrFunctionCall("abs", list(minus))
FRangeQParserExpression(expr, l=0L, incl=FALSE)
} else if (is.null(x@u) || is.null(x@l)) {
initialize(x, l=x@u, u=x@l, incu=!x@incl, incl=!x@incu)
} else {
stop("cannot invert frange")
}
})
setMethod("invert", "SolrFunctionExpression", function(x) {
SolrFunctionCall("not", list(x))
})
wrapParens <- function(x) {
if (!is(x, "SolrLuceneUnaryOperator")) {
paste0("(", x, ")")
} else {
x
}
}
setMethod("as.character", "SolrLuceneOR", function(x) {
paste(wrapParens(x@e1), wrapParens(x@e2))
})
setMethod("as.character", "SolrLuceneAND", function(x) {
paste(wrapParens(x@e1), "AND", wrapParens(x@e2))
})
setMethod("as.character", "SolrLuceneProhibit", function(x) {
if (substring(x@e1, 1L, 1L) == "-") {
expr <- substring(x@e1, 2L)
} else {
expr <- paste0("-", wrapParens(x@e1))
}
})
setMethod("as.character", "SolrLuceneTerm", function(x) {
if (x@inverted) {
x@inverted <- FALSE
if (is.logical(x@term)) {
x@term <- !x@term
} else {
wrapped <- SolrLuceneProhibit(x)
if (!isLuceneNACheck(x)) {
wrapped <- SolrLuceneAND(wrapped,
initialize(x, term=I("*")))
}
return(as.character(wrapped))
}
}
term <- normLuceneLiteral(x@term)
if (!is.null(x@field)) {
paste0(x@field, ":", term)
} else term
})
setMethod("as.character", "LuceneRange", function(x) {
paste0(if (x@fromInclusive) "[" else "{",
normLuceneLiteral(x@from), " TO ", normLuceneLiteral(x@to),
if (x@toInclusive) "]" else "}")
})
setMethod("as.character", "SolrQParserExpression", function(x) {
params <- slotsAsList(x)
params$query <- NULL
params$useValueParam <- NULL
params <- Filter(Negate(is.null), params)
def <- mapply(identical, params,
slotsAsList(new(class(x)))[names(params)])
params <- params[!as.logical(def)]
if (x@useValueParam) {
params$v <- x@query
}
qparser <- qparserFromExpr(x)
params <- vapply(params, normLuceneLiteral, character(1L))
paste0("{!", qparser, if (length(params)) " ",
paste(names(params), params, sep="=", collapse=" "),
"}", if (!x@useValueParam) x@query)
})
setMethod("as.character", "FRangeQParserExpression", function(x) {
missables <- missables(query(x))
if (length(missables) > 0L) {
expr <- Reduce(SolrLuceneAND,
c(lapply(missables, SolrLuceneTerm, I("*")),
dropMissables(x, missables)))
as.character(as(expr, "SolrQParserExpression"))
} else {
callNextMethod()
}
})
setMethod("as.character", "JoinQParserExpression", function(x) {
if (length(x@to) == 0L) {
stop("incomplete join operation, try syntax: x %in% y[expr]")
}
callNextMethod()
})
normLuceneLiteral <- function(x) {
x <- fulfill(x)
if (is.factor(x)) {
x <- as.character(x)
} else if (is(x, "POSIXt") || is(x, "Date")) {
x <- toSolr(x, new("solr.DateField"))
} else if (is(x, "Expression")) {
x <- as.character(x)
}
if (is.character(x) && !is(x, "AsIs")) {
x <- paste0("\"", gsub("\"", "\\\"", gsub("\\", "\\\\", x, fixed=TRUE),
fixed=TRUE), "\"")
} else if (is.logical(x)) {
x <- tolower(as.character(x))
}
if (length(x) > 1L) {
x <- paste0("(", paste(x, collapse=" "), ")")
}
as.character(x)
}
setMethod("as.character", "SolrFunctionExpression", function(x) {
ans <- as.character(x@name)
if (is.logical(x@name))
ans <- tolower(ans)
ans
})
normSolrArg <- function(x) {
x <- fulfill(x)
if (is(x, "Expression")) {
x <- as.character(as(x, "SolrFunctionExpression", strict=FALSE))
} else {
x <- normLuceneLiteral(x)
}
if (anyNA(x)) {
stop("cannot represent NA as a Solr function argument")
}
x
}
setMethod("as.character", "AbstractSolrFunctionCall", function(x) {
args <- vapply(args(x), normSolrArg, character(1L))
paste0(name(x), "(", paste(args, collapse=","), ")")
})
callQuery <- function(x) {
query <- as(x, "SolrQParserExpression", strict=FALSE)
query@useValueParam <- TRUE
quoted <- SolrFunctionExpression(query)
SolrFunctionCall("query", list(quoted))
}
symbolExists <- function(x) SolrFunctionCall("exists", list(I(x)))
symbolAnd <- function(x, y) SolrFunctionCall("and", list(x, y))
noneMissing <- function(missables) {
Reduce(symbolAnd, lapply(missables, symbolExists))
}
setGeneric("propagateNAs",
function(x, na=solrNA) standardGeneric("propagateNAs"),
signature="x")
setMethod("propagateNAs", "SolrFunctionCall", function(x, na) {
missables <- missables(x)
if (length(missables) == 0L) {
return(x)
}
condition <- noneMissing(missables)
x <- dropMissables(x, missables)
SolrFunctionCall("if", list(condition, x, na))
})
setMethod("propagateNAs", "SolrSymbol", function(x, na) {
missable(x) <- FALSE
x
})
setMethod("as.character", "SolrFunctionCall", function(x) {
x <- propagateNAs(x)
callNextMethod()
})
setMethod("as.character", "SolrSortExpression", function(x) {
paste(x@by, if (x@decreasing) "desc" else "asc")
})
setAs("SolrQParserExpression", "SolrLuceneExpression", function(from) {
SolrLuceneTerm("_query_", from)
})
setAs("SolrFunctionCall", "SolrQParserExpression", function(from) {
FRangeQParserExpression(from, l=1, u=1)
})
setAs("SolrSymbol", "SolrLuceneExpression", function(from) {
SolrLuceneTerm(from, TRUE)
})
setAs("character", "SolrLuceneExpression", function(from) {
SolrLuceneTerm(NULL, from)
})
setAs("AsIs", "SolrLuceneExpression", function(from) {
SolrLuceneTerm(NULL, from)
})
setAs("logical", "SolrLuceneExpression", function(from) {
if (isNA(from)) {
from <- FALSE
}
if (!isTRUEorFALSE(from)) {
stop("'from' must be TRUE, FALSE or NA")
}
true <- SolrLuceneTerm("*", I("*"))
if (!from) {
SolrLuceneProhibit(true)
} else {
true
}
})
setAs("logical", "SolrExpression", function(from) {
as(from, "SolrLuceneExpression")
})
setAs("ANY", "SolrQParserExpression", function(from) {
LuceneQParserExpression(from)
})
setAs("ANY", "SolrLuceneExpressionOrSymbol", function(from) {
as(from, "SolrQParserExpression")
})
setAs("Expression", "SolrFunctionExpression", function(from) {
SolrFunctionCall("exists", list(callQuery(from)))
})
setAs("ANY", "SolrFunctionExpression", function(from) {
SolrFunctionExpression(from)
})
setAs("ANY", "SolrSymbol", function(from) SolrSymbol(from))
setMethod("show", "SolrExpression", function(object) {
cat(as.character(object), "\n")
})
targetFromQParser <- function(x) {
if (!isSingleString(x)) {
stop("QParser name must be a single, non-NA string")
}
cls <- supportedSolrQParsers()[x]
if (is.na(cls)) {
stop("QParser '", x, "' is not supported")
}
new(cls)
}
qparserFromExpr <- function(x) {
qparserFromClassName(class(x))
}
qparserFromClassName <- function(x) {
tolower(sub("QParserExpression$", "", x))
}
supportedSolrQParsers <- function() {
cls <- signatureClasses(translate, 2)
ans <- cls[vapply(cls, extends, logical(1), "QParserExpression")]
setNames(ans, qparserFromClassName(ans))
}
solrQueryNA <- SolrLuceneProhibit(SolrLuceneTerm("*", I("*")))
solrNA <- callQuery(solrQueryNA) |
estBetaParams <- function(mu, var) {
alpha <- ((1 - mu) / var - 1 / mu) * mu ^ 2
beta <- alpha * (1 / mu - 1)
c('alpha' = abs(alpha), 'beta' = abs(beta))
}
rbeta2 <- function(n, mu, sigma){
params <- estBetaParams(mu, sigma^2)
rbeta(n, params[1], params[2])
}
dbeta2 <- function(x, mu, sigma, log=FALSE){
params <- estBetaParams(mu, sigma^2)
dbeta(x, params[1], params[2], log=log)
}
psiPrior <- function(psi, alpha=.5, kmax=5, minim=.001){
psivec <- psi
psivec[which(psivec<minim)] <- 0
psivec <- sort(psivec/sum(psivec), decreasing=TRUE)
if(length(which(psivec>0))==1){
psivec[1] <- 1 - minim
psivec[2] <- minim
}
p <- log(ddirichlet(psivec[c(which(psivec>0))], rep(alpha, length(which(psivec>0)))))
p
}
filterCN <- function(data, threshold){
indices <- which(abs(data$X - 1) >= threshold | abs(data$Y - 1) >= threshold)
if (length(indices) < 1) {
indices <- 1
}
list('mat'=data[indices,], 'indices'=indices)
}
filterMutations <- function(mutdata, mu, threshold){
indices <- which(abs(mutdata$refCounts - mu) >= threshold | abs(mutdata$varCounts - mu) >= threshold)
ids <- mutdata$mut.id[indices]
list(mat = mutdata[indices,], ids = ids)
}
seqSeg <- function(seqsnps, len, thresh){
sigma0 <- sd(c(seqsnps$refCounts, seqsnps$varCounts))
dens <- density(seqsnps$refCounts)
mu <- dens$x[which.max(dens$y)]
chrs <- unique(seqsnps$chr)
dflist <- lapply(1:length(chrs),function(i){
seqdata.chr <- seqsnps[seqsnps$chr == chrs[i],]
meandiffs <- t(sapply(1:(nrow(seqdata.chr) - len), function(j) {
mu1.ref <- mean(seqdata.chr$refCounts[((j - 1)*len+1):(j*len)])
mu2.ref <- mean(seqdata.chr$refCounts[(j*len+1):((j+1)*len)])
mu1.var <- mean(seqdata.chr$varCounts[((j - 1)*len+1):(j*len)])
mu2.var <- mean(seqdata.chr$varCounts[(j*len + 1):((j + 1)*len)])
c(abs(mu2.ref - mu1.ref), abs(mu2.var - mu1.var))
}))
peaks.ref <- findPeaks(meandiffs[,1], thresh=.25)
peaks.var <- findPeaks(meandiffs[,2], thresh=.25)
peaks <- sort(unique(c(peaks.ref, peaks.var)), decreasing=FALSE)
if(length(peaks) > 0){
start <- c(1, 1 + len*sapply(1:length(peaks), function(j) {peaks[j]} ))
end <- c(start[-1] - 1, nrow(seqdata.chr))
}else{
start <- 1
end <- nrow(seqdata.chr)
}
markers <- end - start + 1
X <- sapply(1:length(start), function(j) {median(seqdata.chr$refCounts[start[j]:end[j]])})/mu
Y <- sapply(1:length(start), function(j) {median(seqdata.chr$varCounts[start[j]:end[j]])})/mu
LRR <- log10((X + Y)/2)
BAF <- X/(X + Y)
data.frame('chr'=rep(chrs[i],length(start)), 'start'=start, 'end'=end, 'LRR'=LRR,
'BAF'=BAF, 'X'=X, 'Y'=Y, 'markers'=markers)
})
df <- Reduce(rbind, dflist)
df$seg <- 1:nrow(df)
df
} |
.compute_without_plots = function(gene_sigs_list, mRNA_expr_matrix,names_sigs=NULL,names_datasets=NULL , covariates=NULL, thresholds=NULL, out_dir = file.path('~', "sigQC"), showResults = FALSE,origin=NULL){
if(!dir.exists(out_dir)){
dir.create(out_dir,recursive=T)
}
logfile.path = file.path(out_dir, "log.log")
log.con = file(logfile.path, open = "a")
cat(paste("LOG FILE CREATED: ",Sys.time(), sep=""), file=log.con, sep="\n")
radar_plot_values <- list();
for(i in 1:length(names_sigs)){
radar_plot_values[[names_sigs[i]]] <- list();
}
tryCatch({
tryCatch(radar_plot_values <- eval_var_loc_noplots(gene_sigs_list,names_sigs, mRNA_expr_matrix,names_datasets,out_dir,file=log.con,showResults,radar_plot_values),
error=function(err){
cat(paste0("Error occurred in eval_var_loc_noplots: ",err), file=log.con, sep="\n")
})
tryCatch(radar_plot_values <- eval_expr_loc_noplots(gene_sigs_list,names_sigs,mRNA_expr_matrix,names_datasets,thresholds, out_dir,file=log.con,showResults,radar_plot_values ),
error=function(err){
cat(paste0("Error occurred in eval_expr_loc_noplots: ",err), file=log.con, sep="\n")
})
tryCatch(radar_plot_values <- eval_compactness_loc_noplots(gene_sigs_list,names_sigs,mRNA_expr_matrix,names_datasets,out_dir,file=log.con,showResults,radar_plot_values,logged=T,origin ),
error=function(err){
cat(paste0("Error occurred during the evaluation of compactness: ",err), file=log.con, sep="\n")
})
tryCatch({radar_plot_values <- compare_metrics_loc_noplots(gene_sigs_list,names_sigs,mRNA_expr_matrix,names_datasets,out_dir,file=log.con,showResults,radar_plot_values )},
error=function(err){
cat(paste0("Error occurred, likely due to inability to calculate PCA, because of missing values: ",err), file=log.con, sep="\n")
})
tryCatch({radar_plot_values <- eval_stan_loc_noplots(gene_sigs_list,names_sigs,mRNA_expr_matrix,names_datasets,out_dir,file=log.con,showResults,radar_plot_values )},
error=function(err){
cat(paste0("Error occurred in eval_stan_loc_noplots: ",err), file=log.con, sep="\n")
})
tryCatch(make_radar_chart_loc_noplots(radar_plot_values,showResults,names_sigs, names_datasets,out_dir,file=log.con),
error=function(err){
cat(paste0("Error occurred in make_radar_chart_loc_noplots: ",err), file=log.con, sep="\n")
})
}, error = function(err) {
}, finally = {
close(log.con)
})
}
eval_var_loc_noplots <- function(gene_sigs_list,names_sigs, mRNA_expr_matrix,names_datasets, out_dir = '~',file=NULL,showResults = FALSE,radar_plot_values){
num_rows <- length(names_sigs)
num_cols <- length(names_datasets)
gene_sig_mean_sd_table <- list()
for(k in 1:length(names_sigs)){
gene_sig <- gene_sigs_list[[names_sigs[k]]]
for (i in 1:length(names_datasets)){
data.matrix = mRNA_expr_matrix[[names_datasets[i]]]
inter <- intersect(gene_sig[,1], row.names(data.matrix))
sd_genes <- as.matrix(apply(data.matrix,1,function(x){stats::sd(as.numeric(x),na.rm=T) }))
mean_genes <- as.matrix(apply(mRNA_expr_matrix[[names_datasets[i]]],1,function(x) {mean(as.numeric(x),na.rm=T)}))
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['sd_median_ratio'] = stats::median(stats::na.omit(sd_genes[inter,1]))/(stats::median(stats::na.omit(sd_genes)) +stats::median(stats::na.omit(sd_genes[inter,1])))
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['abs_skewness_ratio'] = abs(moments:: skewness(stats::na.omit(mean_genes[inter, 1])))/(abs(moments:: skewness(stats::na.omit(mean_genes))) + abs(moments:: skewness(stats::na.omit(mean_genes[inter, 1]))))
quants_sd <- stats::quantile(sd_genes*is.finite(sd_genes),probs=c(0.1,0.25,0.5,0.75,0.9),na.rm=T)
gene_sig_mean_sd_table[[names_sigs[k]]][[names_datasets[i]]] <- cbind(mean_genes[inter, 1],sd_genes[inter, 1])
colnames(gene_sig_mean_sd_table[[names_sigs[k]]][[names_datasets[i]]]) <- c("Mean","SD")
}
}
for(k in 1:length(names_sigs)){
gene_sig <- gene_sigs_list[[names_sigs[k]]]
for (i in 1:length(names_datasets)){
data.matrix = mRNA_expr_matrix[[names_datasets[i]]]
inter <- intersect(gene_sig[,1], row.names(data.matrix))
coeff_of_var <- as.matrix(apply(data.matrix,1,function(x){stats::sd(as.numeric(stats::na.omit(x)),na.rm=T) / mean(as.numeric(stats::na.omit(x)),na.rm=T)}))
coeff_of_var_gene_sig <- coeff_of_var[inter, 1]
quantiles_considered <- stats::quantile(coeff_of_var,probs=c(0.9,0.75,0.5),na.rm=T)
prop_top_10_percent <- sum(stats::na.omit(coeff_of_var_gene_sig) >= quantiles_considered[1]) / length(stats::na.omit(coeff_of_var_gene_sig))
prop_top_25_percent <- sum(stats::na.omit(coeff_of_var_gene_sig) >= quantiles_considered[2]) / length(stats::na.omit(coeff_of_var_gene_sig))
prop_top_50_percent <- sum(stats::na.omit(coeff_of_var_gene_sig) >= quantiles_considered[3]) / length(stats::na.omit(coeff_of_var_gene_sig))
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['prop_top_10_percent'] <- prop_top_10_percent
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['prop_top_25_percent'] <- prop_top_25_percent
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['prop_top_50_percent'] <- prop_top_50_percent
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['coeff_of_var_ratio'] <- abs((abs(stats::median(stats::na.omit(coeff_of_var_gene_sig))))/((abs(stats::median(stats::na.omit(coeff_of_var)))) + abs((stats::median(stats::na.omit(coeff_of_var_gene_sig))))))
}
}
radar_plot_values
}
eval_expr_loc_noplots <- function(gene_sigs_list,names_sigs, mRNA_expr_matrix,names_datasets, thresholds = NULL, out_dir = '~',file=NULL,showResults = FALSE,radar_plot_values){
num_rows <- length(names_sigs)
num_cols <- length(names_datasets)
for(k in 1:length(names_sigs)){
gene_sig <- gene_sigs_list[[names_sigs[k]]]
for (i in 1:length(names_datasets)){
data.matrix = mRNA_expr_matrix[[names_datasets[i]]]
inter <- intersect(gene_sig[,1], row.names(data.matrix))
genes_expr <- data.matrix[inter,]
gene_expr_vals <- (rowSums(is.na(genes_expr)) / dim(genes_expr)[2])
gene_expr_vals[setdiff(gene_sig[,1], row.names(data.matrix))] <- 1
gene_expr_vals <- -sort(-gene_expr_vals)
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['med_prop_na'] <- stats::median(1-gene_expr_vals)
}
}
if (length(thresholds) == 0) {
thresholds <- rep(0,length(names_datasets))
for ( i in 1:length(names_datasets)){
thresholds[i] <- stats::median(unlist(stats::na.omit(mRNA_expr_matrix[[names_datasets[i]]])))
}
}
if(length(names(thresholds))==0){
names(thresholds) <- names_datasets
}
for (k in 1:length(names_sigs)){
gene_sig <- gene_sigs_list[[names_sigs[k]]]
for (i in 1:length(names_datasets)){
data.matrix = mRNA_expr_matrix[[names_datasets[i]]]
inter <- intersect(gene_sig[,1], row.names(data.matrix))
genes_expr <- data.matrix[inter,]
gene_expr_vals <- 1 - ((rowSums(genes_expr < thresholds[i])) / (dim(genes_expr)[2]))
gene_expr_vals[setdiff(gene_sig[,1], row.names(data.matrix))] <- 0
gene_expr_vals <- sort(gene_expr_vals)
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['med_prop_above_med'] <- stats::median(gene_expr_vals)
}
}
radar_plot_values
}
eval_compactness_loc_noplots <- function(gene_sigs_list,names_sigs, mRNA_expr_matrix, names_datasets, out_dir = '~',file=NULL,showResults = FALSE,radar_plot_values,logged=T,origin=NULL){
for(k in 1:length(names_sigs)){
gene_sig <- gene_sigs_list[[names_sigs[k]]]
for (i in 1:length(names_datasets) ){
data.matrix = mRNA_expr_matrix[[names_datasets[i]]]
inter <- intersect(gene_sig[,1], row.names(data.matrix))
autocors <- stats::cor(t(stats::na.omit(data.matrix[inter,])),method='spearman')
if(dim(autocors)[1] > 1){
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['autocor_median'] <- stats::median(autocors,na.rm=T)
}else{
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['autocor_median'] <- 0
}
}
}
radar_plot_values
}
compare_metrics_loc_noplots <- function(gene_sigs_list,names_sigs, mRNA_expr_matrix, names_datasets, out_dir = '~',file=NULL,showResults = FALSE,radar_plot_values){
for(k in 1:length(names_sigs)){
gene_sig <- gene_sigs_list[[names_sigs[k]]]
for (i in 1:length(names_datasets)){
data.matrix = mRNA_expr_matrix[[names_datasets[i]]]
data.matrix[!(is.finite(as.matrix(data.matrix)))] <- NA
inter = intersect(gene_sig[,1],rownames(data.matrix))
med_scores <- apply(data.matrix[inter,],2,function(x){stats::median(stats::na.omit(x))})
mean_scores <- apply(data.matrix[inter,],2,function(x){mean(stats::na.omit(x))})
pca1_scores <- NULL
tryCatch({
pca1_scores <- stats::prcomp(stats::na.omit(t(data.matrix[inter,])),retx=T)
},error=function(e){
pca1_scores <<- NULL
cat(paste0("There was an error: ",names_datasets[i]," ", names_sigs[k]," ", e,'\n'), file=file)
})
if(length(pca1_scores) > 1){
props_of_variances <- pca1_scores$sdev^2/(sum(pca1_scores$sdev^2))
pca1_scores <- pca1_scores$x[,1]
common_score_cols <- intersect(names(med_scores),intersect(names(mean_scores),names(pca1_scores)))
}else{
common_score_cols <- intersect(names(med_scores),names(mean_scores))
}
if(length(common_score_cols) > 1){
rho <- stats::cor(med_scores[common_score_cols],mean_scores[common_score_cols],method='spearman')
rho_mean_med <- rho
}else{
rho_mean_med <- 0
}
if (length(pca1_scores) > 1){
rho <- stats::cor(mean_scores[common_score_cols],pca1_scores[common_score_cols],method='spearman')
rho_mean_pca1 <- rho
rho <- stats::cor(pca1_scores[common_score_cols],med_scores[common_score_cols],method='spearman')
rho_pca1_med <- rho
}else{
rho_mean_pca1 <- 0
rho_pca1_med <- 0
}
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['rho_mean_med'] <- rho_mean_med
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['rho_pca1_med'] <- rho_pca1_med
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['rho_mean_pca1'] <- rho_mean_pca1
if(length(pca1_scores) > 1){
bars_plot <- props_of_variances[1:min(10,length(props_of_variances))]
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['prop_pca1_var']<- bars_plot[1]
}else{
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['prop_pca1_var']<- 0
}
}
}
cat('Metrics compared successfully.\n', file=file)
radar_plot_values
}
eval_stan_loc_noplots <- function(gene_sigs_list, names_sigs,mRNA_expr_matrix, names_datasets,out_dir = '~',file=NULL,showResults = FALSE,radar_plot_values ){
for(k in 1:length(names_sigs)){
gene_sig <- gene_sigs_list[[names_sigs[k]]]
for (i in 1:length(names_datasets)){
data.matrix = mRNA_expr_matrix[[names_datasets[i]]]
inter <- intersect(gene_sig[,1], row.names(data.matrix))
z_transf_mRNA <- data.matrix[inter,]
for (gene in inter){
z_transf_mRNA[gene,] <- (as.numeric(z_transf_mRNA[gene,]) - mean(as.numeric(z_transf_mRNA[gene,]),na.rm=T)) / stats::sd(as.numeric(z_transf_mRNA[gene,]),na.rm=T)
}
z_transf_scores <- apply(z_transf_mRNA[inter,],2,function(x) {stats::median(stats::na.omit(x))})
med_scores <- apply(data.matrix[inter,],2,function(x){ stats::median(stats::na.omit(x))})
rho <- stats::cor(med_scores,z_transf_scores,method='spearman')
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['standardization_comp'] <- rho
}
}
cat('Standardisation compared successfully.\n', file=file)
radar_plot_values
}
make_radar_chart_loc_noplots <- function(radar_plot_values,showResults = FALSE,names_sigs,names_datasets, out_dir = '~',file){
radar_plot_mat <- c()
all_metrics <- c('sd_median_ratio','abs_skewness_ratio','prop_top_10_percent','prop_top_25_percent',
'prop_top_50_percent','coeff_of_var_ratio','med_prop_na','med_prop_above_med',
'autocor_median','rho_mean_med','rho_pca1_med','rho_mean_pca1',
'prop_pca1_var','standardization_comp')
for(k in 1:length(names_sigs)){
for(i in 1:length(names_datasets)){
diff_names <- base::setdiff(all_metrics,names(radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]))
if(length(diff_names)>0){
for(j in 1:length(diff_names)){
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]][diff_names[j]] <- 0
}
}
}
}
for(k in 1:length(names_sigs)){
t <- lapply(radar_plot_values[[names_sigs[k]]],function(x) radar_plot_mat <<- rbind(radar_plot_mat,x))
}
radar_plot_mat <- rbind(rep(1,length(radar_plot_values[[1]][[1]])),rep(0,length(radar_plot_values[[1]][[1]])),radar_plot_mat)
radar_plot_mat <- abs(radar_plot_mat)
legend_labels <- c()
for(k in 1:length(names_sigs) ){
for(i in 1:length(names_datasets)){
legend_labels <- c(legend_labels,paste0(names_datasets[i],' ',names_sigs[k],' (XXXX)'))
}
}
row.names(radar_plot_mat) <- c('max','min',legend_labels)
areas <- c()
for (i in 3:dim(radar_plot_mat)[1]){
areas<- c(areas,sum(sapply(1:length(radar_plot_mat[i,]),function(x) if(x < length(radar_plot_mat[i,])){radar_plot_mat[i,x] * radar_plot_mat[i,x+1]}else{radar_plot_mat[i,x]* radar_plot_mat[i,1]})))
}
areas <- areas /dim(radar_plot_mat)[2]
count <-1
legend_labels <-c()
for(k in 1:length(names_sigs) ){
for(i in 1:length(names_datasets)){
legend_labels <- c(legend_labels,paste0(names_datasets[i],' ',names_sigs[k],' (',format(areas[count],digits=2),')'))
count <- count + 1
}
}
legend_labels <- legend_labels[order(-areas)]
if(!dir.exists(file.path(out_dir,'radarchart_table'))){
dir.create(file.path(out_dir,'radarchart_table'))
}
radarplot_rownames <- c()
for(k in 1:length(names_sigs) ){
for(i in 1:length(names_datasets)){
radarplot_rownames <- c(radarplot_rownames,paste0(gsub(' ','.', names_datasets[i]),'_',gsub(' ','.', names_sigs[k])))
}
}
radar_plot_mat <- radar_plot_mat[3:(dim(radar_plot_mat)[1]),]
radar_plot_mat <- as.matrix(radar_plot_mat)
if(length(radarplot_rownames)==1){
new_colnames <- rownames(radar_plot_mat)
dim(radar_plot_mat) <- c(1,length(radar_plot_mat))
colnames(radar_plot_mat) <- new_colnames
}
row.names(radar_plot_mat) <- radarplot_rownames
utils::write.table(radar_plot_mat,file=file.path(out_dir,'radarchart_table', paste0('radarchart_table','.txt')),quote=F,sep='\t',row.names=T,col.names=T)
cat('Radar chart made successfully.\n', file=file)
} |
env <- function(x) {
environment(x$as_list)
} |
pack_layers <- function(loonPlot, ggObj, buildggObj,
panelIndex, activeInfo, modelLayers) {
lenLayers <- length(ggObj$layers)
if(lenLayers == 0) return(NULL)
ggplotPanelParams <- buildggObj$ggplotPanelParams
ggBuild <- buildggObj$ggBuild
curveLayers <- modelLayers$curveLayers
boxplotLayers <- modelLayers$boxplotLayers
activeGeomLayers <- activeInfo$activeGeomLayers
activeModel <- activeInfo$activeModel
loonLayers <- lapply(seq_len(lenLayers),
function(j){
if(j %in% activeGeomLayers)
return(NULL)
loonLayer(widget = loonPlot,
layerGeom = ggObj$layers[[j]],
data = ggBuild$data[[j]][ggBuild$data[[j]]$PANEL == panelIndex, ],
ggplotPanelParams = ggplotPanelParams[[panelIndex]],
ggObj = ggObj,
curveAdditionalArgs = list(curve = list(which_curve = j,
curveLayers = curveLayers))
)
})
if(length(activeGeomLayers) != lenLayers && length(activeGeomLayers) > 0 && all(activeGeomLayers != 0L)) {
otherLayerId <- seq(lenLayers)[-activeGeomLayers]
minOtherLayerId <- min(otherLayerId)
max_hist_points_layerId <- max(activeGeomLayers)
if(max_hist_points_layerId > minOtherLayerId){
modelLayerup <- sapply(seq_len(length(which(otherLayerId < max_hist_points_layerId) == TRUE)),
function(j){
loon::l_layer_raise(loonPlot, "model")
}
)
}
}
if (length(boxplotLayers) != 0 && activeModel == "l_plot" && length(activeGeomLayers) == 0) {
loon::l_layer_hide(loonPlot, "model")
modelLayerup <- sapply(seq_len(lenLayers),
function(j){
loon::l_layer_raise(loonPlot, "model")
})
}
loonLayers
} |
climdex2ecad<-function(homefolder='./',stationlist='stations.csv',countrycode='DE'){
ecv.ECAD <- c("rr","tx","tn")
ecv.hl15 <- c("24-28 RR : Precipitation amount in 0.1 mm", "24-28 TX : Maximum temperature in 0.1 C",
"24-28 TN : Minimum temperature in 0.1 C")
ecv.hl16 <- c("30-34 Q_RR : quality code for RR (0='valid'; 1='suspect'; 9='missing')",
"30-34 Q_TX : quality code for TX (0='valid'; 1='suspect'; 9='missing')",
"30-34 Q_TN : quality code for TN (0='valid'; 1='suspect'; 9='missing')")
ecv.hl22 <- c(" STAID, SOUID, DATE, RR, Q_RR"," STAID, SOUID, DATE, TX, Q_TX",
" STAID, SOUID, DATE, TN, Q_TN")
ecv <- data.frame(ECAD=ecv.ECAD,hl15=ecv.hl15,hl16=ecv.hl16,hl22=ecv.hl22)
lst.stn <- utils::read.table(paste0(homefolder,'raw_ClimDex/',stationlist),header = FALSE, sep = ",",na.strings='-99.9')
n.stn <- nrow(lst.stn)
if(!dir.exists(paste0(homefolder,'raw'))){dir.create(paste0(homefolder,'raw'))}
for (i in 1:n.stn) {
filename<-paste0(lst.stn[i,4],'.txt')
print(filename)
lat.angel <- lst.stn[i,1]
if(lat.angel < 0){nyu<-TRUE;lat.angel = lat.angel*(-1)}else{nyu=FALSE}
lat.angel.chr <- as.character(lat.angel)
lat.deg <- as.numeric(strsplit(lat.angel.chr, "\\.")[[1]][1])
lat.min <- as.numeric(strsplit(as.character((lat.angel-lat.deg)*60), "\\.")[[1]][1])
lat.sec <- round((((lat.angel-lat.deg)*60) - lat.min) * 60)
if (nyu) {lat.deg <- paste0("-",sprintf("%02d",lat.deg))} else {lat.deg <- paste0("+",sprintf("%02d",lat.deg))}
lat.min <- sprintf("%02d",lat.min)
lat.sec <- sprintf("%02d",lat.sec)
LAT <- paste0(lat.deg,':',lat.min,':',lat.sec)
lon.angel <- lst.stn[i,2]
if(lon.angel < 0){nyu<-TRUE;lon.angel = lon.angel*(-1)}else{nyu=FALSE}
lon.angel.chr <- as.character(lon.angel)
lon.deg <- as.numeric(strsplit(lon.angel.chr, "\\.")[[1]][1])
lon.min <- as.numeric(strsplit(as.character((lon.angel-lon.deg)*60), "\\.")[[1]][1])
lon.sec <- round((((lon.angel-lon.deg)*60) - lon.min) * 60)
if (nyu) {lon.deg <- paste0("-",sprintf("%03d",lon.deg))} else {lon.deg <- paste0("+",sprintf("%03d",lon.deg))}
lon.min <- sprintf("%02d",lon.min)
lon.sec <- sprintf("%02d",lon.sec)
LON <- paste0(lon.deg,':',lon.min,':',lon.sec)
if(file.exists(paste0(homefolder,'raw_ClimDex/',filename))){
y<-utils::read.table(paste0(homefolder,'raw_ClimDex/',filename),na.strings='-99.9')
y[,4]<-round(y[,4],1)
y[,5]<-round(y[,5],1)
y[,6]<-round(y[,6],1)
date<-as.numeric(paste0(y[,1],sprintf("%02d",y[,2]),sprintf("%02d",y[,3])))
STAID <- i
for (j in 1:3) {
SOUID <- paste0(j,sprintf("%05d",i))
file.nm <- paste0(toupper(ecv[j,1]),'_STAID',sprintf("%06d",STAID),'.txt')
file.out <- file(paste0(homefolder,'raw/',file.nm))
writeLines(c("This is INQC's formal conversion of a COST Home data file to the ECA&D format (STAID and SOUID are not real!)",
paste("EUROPEAN CLIMATE ASSESSMENT & DATASET (ECA&D), file created on:",Sys.Date(),sep=" "),
"THESE DATA CAN BE USED FOR NON-COMMERCIAL RESEARCH AND EDUCATION PROVIDED THAT THE FOLLOWING SOURCE IS ACKNOWLEDGED: ",
"",
"Klein Tank, A.M.G. and Coauthors, 2002. Daily dataset of 20th-century surface",
"air temperature and precipitation series for the European Climate Assessment.",
"Int. J. of Climatol., 22, 1441-1453.",
"Data and metadata available at http://www.ecad.eu",
"",
"FILE FORMAT (MISSING VALUE CODE = -9999):",
"",
"01-06 STAID: Station identifier",
"08-13 SOUID: Source identifier",
"15-22 DATE : Date YYYYMMDD",
ecv[j,2],
ecv[j,3],
"",
paste0("This is the blended series of station ",lst.stn[i,4],", ",countrycode," (STAID: ",STAID,")"),
paste0("Blended and updated with sources: ",SOUID),
"See files sources.txt and stations.txt for more info.",
"",
ecv[j,4]),
file.out)
close(file.out)
VALUE <- as.numeric(y[,j+3])*10
QC <- vector(mode='integer',length=length(VALUE))
QC[1:length(VALUE)] <- 0
QC[which(is.na(VALUE))] <- 9
VALUE[which(is.na(VALUE))] <- -9999
df.j <- data.frame('STAID'=format(STAID,width=6), 'SOUID'=SOUID, 'DATE'=date,
'VALUE'=format(VALUE,width=5), 'QC'=format(QC,width=5))
utils::write.table(df.j, file=paste0(homefolder,'raw/',file.nm),row.names = FALSE,col.names = FALSE,
sep = ",",append=TRUE,quote = FALSE)
}
stn.fl.ECAD.i <- data.frame(format(STAID,width=5),format(lst.stn[i,4],width=40),countrycode,
LAT,LON,format(lst.stn[i,3],width=4))
if (i==1) {
stn.fl.ECAD <- stn.fl.ECAD.i
} else {
stn.fl.ECAD <- rbind(stn.fl.ECAD, stn.fl.ECAD.i)
}
}
}
names(stn.fl.ECAD) <- c('STAID','STANAME ','CN',' LAT',' LON','HGHT')
utils::write.table(stn.fl.ECAD,file=paste0(homefolder,'raw/','stations.txt'),
col.names=TRUE,row.names=FALSE,sep=',',quote = FALSE)
} |
expected <- eval(parse(text="structure(c(-1.82608695652174, 1.17391304347826, 1.17391304347826, 4.17391304347826, -1.82608695652174, -1.82608695652174, 2.17391304347826, 0.173913043478262, 4.17391304347826, -0.826086956521738, 2.17391304347826, 2.17391304347826, 2.17391304347826, 4.17391304347826, -2.82608695652174, 2.17391304347826, 2.17391304347826, -0.826086956521738, -3.82608695652174, -1.82608695652174, -4.82608695652174, 0.173913043478262, -7.82608695652174, 1.15, 5.15, -0.85, 1.15, -2.85, -2.85, -1.85, NA, 6.15, -2.85, 0.15, 3.15, 0.15, NA, NA, 1.15, -1.85, 0.15, -0.85, -0.85, 2.15, -2.85, -2.85, -32.2608695652174, -54.2608695652174, -36.2608695652174, -45.2608695652174, 194.739130434783, 130.739130434783, -35.2608695652174, -59.2608695652174, -63.2608695652174, 25.7391304347826, -25.2608695652174, -44.2608695652174, -16.2608695652174, -63.2608695652174, -53.2608695652174, -56.2608695652174, -19.2608695652174, -35.2608695652174, -39.2608695652174, -7.26086956521739, -38.2608695652174, 213.739130434783, 158.739130434783, 8.09999999999999, -94.9, -59.9, -49.9, 176.1, 11.1, -59.9, NA, 100.1, 15.1, 21.1, 84.1, 65.1, NA, NA, -63.9, -37.9, -26.9, -128.9, 42.1, -87.9, 118.1, -30.9), .Dim = c(23L, 4L), .Dimnames = list(NULL, c(\"V1\", \"V2\", \"V3\", \"V4\")))"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(9, 12, 12, 15, 9, 9, 13, 11, 15, 10, 13, 13, 13, 15, 8, 13, 13, 10, 7, 9, 6, 11, 3, 5, 9, 3, 5, 1, 1, 2, NA, 10, 1, 4, 7, 4, NA, NA, 5, 2, 4, 3, 3, 6, 1, 1, 63, 41, 59, 50, 290, 226, 60, 36, 32, 121, 70, 51, 79, 32, 42, 39, 76, 60, 56, 88, 57, 309, 254, 146, 43, 78, 88, 314, 149, 78, NA, 238, 153, 159, 222, 203, NA, NA, 74, 100, 111, 9, 180, 50, 256, 107), .Dim = c(23L, 4L), .Dimnames = list(NULL, c(\"V1\", \"V2\", \"V3\", \"V4\"))), structure(c(10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 10.8260869565217, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 3.85, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 95.2608695652174, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9, 137.9), .Dim = c(23L, 4L)))"));
do.call(`-`, argv);
}, o=expected); |
sim2.bd.fast.single.origin <-
function(n,lambda,mu,rho,origin){
edge <- c(-1,-2)
leaves <- c(-2)
timecreation <-c(0,0)
time <-0
maxspecies <- -2
edge.length <- c(0)
index = 2
specevents = vector()
specevents <-c(specevents,origin)
for (j in 1:(n-1)){
r <- runif(1,0,1)
tor=origin
lamb1= rho * lambda
mu1 = mu - lambda *(1-rho)
if (lambda>mu) {
temp <- 1/(lamb1-mu1)*log((lamb1-mu1* exp((-lamb1+mu1)*tor) -mu1*(1-exp((-lamb1+mu1)*tor)) *r )/(lamb1-mu1* exp((-lamb1+mu1)*tor) -lamb1*(1-exp((-lamb1+mu1)*tor)) *r ) )
} else {
temp<- -((tor* r)/(-1 - lambda* rho* tor + lambda* rho* tor*r ))
}
specevents <- c(specevents,temp)
}
specevents <- sort(specevents,decreasing=TRUE)
while (index<=n) {
timestep <- specevents[(index-1)]-specevents[index]
time = time+timestep
species <- sample(leaves,1)
del <- which(leaves == species)
edgespecevent <- which(edge == species) - length(edge.length)
edge.length[edgespecevent] <- time-timecreation[- species]
edge <- rbind(edge,c(species,maxspecies-1))
edge <- rbind(edge,c(species,maxspecies-2))
edge.length <- c(edge.length,0,0)
leaves <- c(leaves,maxspecies-1,maxspecies-2)
maxspecies <- maxspecies-2
leaves <- leaves[- del]
timecreation <- c(timecreation,time,time)
index <- index+1
}
time <- specevents[1]
for (j in (1:length(leaves))){
k = which( edge == leaves[j] ) - length(edge.length)
edge.length[ k ] <- time - timecreation[- leaves[j]]
}
nodes <- (length(leaves))*2
leaf=1
interior=length(leaves)+1
edgetemp<-edge
if (nodes == 2) {
phy2 <-1
} else {
for (j in (1:nodes)){
if (sum(match(leaves,- j,0)) == 0) {
posvalue <- interior
interior <- interior +1
} else {
posvalue <- leaf
leaf <- leaf +1
}
replacel <- which(edge == - j)
for (k in 1:length(replacel)) {
if ((replacel[k]-1) < length(edge.length)) {
edge[replacel[k],1] <- posvalue
} else {
edge[(replacel[k]-length(edge.length)),2] <- posvalue
}
}
}
}
phy <- list(edge = edge)
phy$tip.label <- paste("t", sample(length(leaves)), sep = "")
phy$edge.length <- edge.length
phy$Nnode <- length(leaves)
class(phy) <- "phylo"
storage.mode(phy$edge) <- "integer"
phy
} |
context("fct_relevel")
test_that("warns about unknown levels", {
f1 <- factor(c("a", "b"))
expect_warning(f2 <- fct_relevel(f1, "d"), "Unknown levels")
expect_equal(levels(f2), levels(f1))
})
test_that("moves supplied levels to front", {
f1 <- factor(c("a", "b", "c", "d"))
f2 <- fct_relevel(f1, "c", "b")
expect_equal(levels(f2), c("c", "b", "a", "d"))
})
test_that("can moves supplied levels to end", {
f1 <- factor(c("a", "b", "c", "d"))
f2 <- fct_relevel(f1, "a", "b", after = 2)
f3 <- fct_relevel(f1, "a", "b", after = Inf)
expect_equal(levels(f2), c("c", "d", "a", "b"))
expect_equal(levels(f3), c("c", "d", "a", "b"))
})
test_that("can relevel with function ", {
f1 <- fct_rev(factor(c("a", "b")))
f2a <- fct_relevel(f1, rev)
f2b <- fct_relevel(f1, ~ rev(.))
expect_equal(levels(f2a), c("a", "b"))
expect_equal(levels(f2b), c("a", "b"))
})
test_that("function must return character vector", {
f <- factor(c("a", "b"))
expect_error(fct_relevel(f, ~ 1), "character vector")
}) |
available_hosts <- function() {
.xena_hosts <- "UCSCXenaTools" %:::% ".xena_hosts"
.xena_hosts %>% as.character()
}
get_pancan_value <- function(identifier, subtype = NULL, dataset = NULL, host = available_hosts(),
samples = NULL) {
stopifnot(length(identifier) == 1, !all(is.null(subtype), is.null(dataset)))
if (!requireNamespace("UCSCXenaTools", quietly = TRUE)) {
stop("Package 'UCSCXenaTools' is not installed.")
}
if (!"UCSCXenaTools" %in% .packages()) {
attachNamespace("UCSCXenaTools")
}
host <- match.arg(host, choices = available_hosts(), several.ok = TRUE)
data <- UCSCXenaTools::XenaData
if (!is.null(subtype)) {
data <- data %>%
dplyr::filter(XenaHostNames %in% host, grepl(subtype, DataSubtype))
}
if (!is.null(dataset)) {
data <- data %>%
dplyr::filter(XenaHostNames %in% host, grepl(dataset, XenaDatasets))
}
if (nrow(data) == 0) {
stop("No dataset is determined by input")
}
if (nrow(data) > 1) {
data <- dplyr::filter(data, .data$XenaDatasets == dataset)
}
res <- try_query_value(data[["XenaHosts"]], data[["XenaDatasets"]],
identifiers = identifier, samples = samples,
check = FALSE, use_probeMap = TRUE
)
res2 <- res[1, ]
names(res2) <- colnames(res)
res2
}
try_query_value <- function(host, dataset,
identifiers, samples,
check = FALSE, use_probeMap = TRUE,
max_try = 5L) {
Sys.sleep(0.1)
tryCatch(
{
message("Try querying data
UCSCXenaTools::fetch_dense_values(host, dataset,
identifiers = identifiers, samples = samples,
check = check, use_probeMap = use_probeMap
)
},
error = function(e) {
if (max_try == 1) {
stop("Tried 5 times but failed, please check URL or your internet connection or try it later!")
} else {
try_query_value(host, dataset,
identifiers, samples,
check = check, use_probeMap = use_probeMap,
max_try = max_try - 1L
)
}
}
)
}
get_pancan_gene_value <- function(identifier) {
host <- "toilHub"
dataset <- "TcgaTargetGtex_rsem_gene_tpm"
expression <- get_data(dataset, identifier, host)
unit <- "log2(tpm+0.001)"
report_dataset_info(dataset)
res <- list(expression = expression, unit = unit)
res
}
get_pancan_transcript_value <- function(identifier) {
id <- identifier
host <- "toilHub"
dataset <- "TcgaTargetGtex_rsem_isoform_tpm"
res_p <- check_exist_data("mp", dataset, host)
if (res_p$ok) {
ids <- res_p$data
} else {
ids <- UCSCXenaTools::fetch_dataset_identifiers("https://toil.xenahubs.net", dataset)
names(ids) <- sub("\\.[0-9]+", "", ids)
save_data(ids, "mp", dataset, host)
}
identifier <- as.character(ids[identifier])
if (is.na(identifier)) identifier <- id
expression <- get_data(dataset, identifier, host)
unit <- "log2(tpm+0.001)"
report_dataset_info(dataset)
res <- list(expression = expression, unit = unit)
res
}
get_pancan_protein_value <- function(identifier) {
host <- "pancanAtlasHub"
dataset <- "TCGA-RPPA-pancan-clean.xena"
expression <- get_data(dataset, identifier, host)
unit <- "norm_value"
report_dataset_info(dataset)
res <- list(expression = expression, unit = unit)
res
}
.all_pancan_proteins <- c(
"ACC1", "ACC_pS79", "ACETYLATUBULINLYS40", "ACVRL1", "ADAR1",
"AKT", "AKT_pS473", "AKT_pT308", "ALPHACATENIN", "AMPKALPHA",
"AMPKALPHA_pT172", "ANNEXIN1", "ANNEXINVII", "AR", "ARAF", "ARAF_pS299",
"ARID1A", "ASNS", "ATM", "AXL", "BAD_pS112", "BAK", "BAP1C4",
"BAX", "BCL2", "BCL2A1", "BCLXL", "BECLIN", "BETACATENIN", "BID",
"BIM", "BRAF", "BRAF_pS445", "BRCA2", "BRD4", "CA9", "CABL",
"CASPASE3", "CASPASE7CLEAVEDD198", "CASPASE8", "CASPASE9", "CAVEOLIN1",
"CD20", "CD26", "CD31", "CD49B", "CDK1", "CDK1_pY15", "CHK1",
"CHK1_pS296", "CHK1_pS345", "CHK2", "CHK2_pT68", "CHROMOGRANINANTERM",
"CIAP", "CJUN_pS73", "CK5", "CKIT", "CLAUDIN7", "CMET", "CMET_pY1235",
"CMYC", "COG3", "COLLAGENVI", "COMPLEXIISUBUNIT30", "CRAF", "CRAF_pS338",
"CTLA4", "CYCLINB1", "CYCLIND1", "CYCLINE1", "CYCLINE2", "DIRAS3",
"DJ1", "DUSP4", "DVL3", "E2F1", "ECADHERIN", "EEF2", "EEF2K",
"EGFR", "EGFR_pY1068", "EGFR_pY1173", "EIF4E", "EIF4G", "ENY2",
"EPPK1", "ERALPHA", "ERALPHA_pS118", "ERCC1", "ERCC5", "ERK2",
"ETS1", "EZH2", "FASN", "FIBRONECTIN", "FOXM1", "FOXO3A", "FOXO3A_pS318S321",
"G6PD", "GAB2", "GAPDH", "GATA3", "GATA6", "GCN5L2", "GSK3ALPHABETA",
"GSK3ALPHABETA_pS21S9", "GSK3_pS9", "GYGGLYCOGENIN1", "GYS",
"GYS_pS641", "HER2", "HER2_pY1248", "HER3", "HER3_pY1289", "HEREGULIN",
"HIF1ALPHA", "HSP70", "IGF1R_pY1135Y1136", "IGFBP2", "INPP4B",
"IRF1", "IRS1", "JAB1", "JAK2", "JNK2", "JNK_pT183Y185", "KEAP1",
"KU80", "LCK", "LCN2A", "LDHA", "LDHB", "LKB1", "MACC1", "MAPK_pT202Y204",
"MEK1", "MEK1_pS217S221", "MIG6", "MITOCHONDRIA", "MRE11", "MSH2",
"MSH6", "MTOR", "MTOR_pS2448", "MYH11", "MYOSINIIA", "MYOSINIIA_pS1943",
"NAPSINA", "NCADHERIN", "NDRG1_pT346", "NF2", "NFKBP65_pS536",
"NOTCH1", "NRAS", "NRF2", "OXPHOSCOMPLEXVSUBUNITB", "P16INK4A",
"P21", "P27", "P27_pT157", "P27_pT198", "P38MAPK", "P38_pT180Y182",
"P53", "P62LCKLIGAND", "P63", "P70S6K1", "P70S6K_pT389", "P90RSK",
"P90RSK_pT359S363", "PAI1", "PARP1", "PARPAB3", "PARPCLEAVED",
"PAXILLIN", "PCADHERIN", "PCNA", "PDCD1", "PDCD4", "PDK1", "PDK1_pS241",
"PDL1", "PEA15", "PEA15_pS116", "PI3KP110ALPHA", "PI3KP85", "PKCALPHA",
"PKCALPHA_pS657", "PKCDELTA_pS664", "PKCPANBETAII_pS660", "PKM2",
"PR", "PRAS40_pT246", "PRDX1", "PREX1", "PTEN", "PYGB", "PYGBAB2",
"PYGL", "PYGM", "RAB11", "RAB25", "RAD50", "RAD51", "RAPTOR",
"RB", "RBM15", "RB_pS807S811", "RET_pY905", "RICTOR", "RICTOR_pT1135",
"S6", "S6_pS235S236", "S6_pS240S244", "SCD1", "SETD2", "SF2",
"SHC_pY317", "SHP2_pY542", "SLC1A5", "SMAC", "SMAD1", "SMAD3",
"SMAD4", "SNAIL", "SRC", "SRC_pY416", "SRC_pY527", "STAT3_pY705",
"STAT5ALPHA", "STATHMIN", "SYK", "SYNAPTOPHYSIN", "TAZ", "TFRC",
"THYMIDILATESYNTHASE", "TIGAR", "TRANSGLUTAMINASE", "TSC1", "TTF1",
"TUBERIN", "TUBERIN_pT1462", "VEGFR2", "X1433BETA", "X1433EPSILON",
"X1433ZETA", "X4EBP1", "X4EBP1_pS65", "X4EBP1_pT37T46", "X4EBP1_pT70",
"X53BP1", "XBP1", "XRCC1", "YAP", "YAP_pS127", "YB1", "YB1_pS102"
)
get_pancan_mutation_status <- function(identifier) {
if (utils::packageVersion("UCSCXenaTools") < "1.3.2") {
stop("You need to update 'UCSCXenaTools' (>=1.3.2).", call. = FALSE)
}
host <- "pancanAtlasHub"
dataset <- "mc3.v0.2.8.PUBLIC.nonsilentGene.xena"
report_dataset_info(dataset)
data <- get_data(dataset, identifier, host)
return(data)
}
get_pancan_cn_value <- function(identifier, use_thresholded_data = TRUE) {
host <- "tcgaHub"
if (use_thresholded_data) {
dataset <- "TCGA.PANCAN.sampleMap/Gistic2_CopyNumber_Gistic2_all_thresholded.by_genes"
unit <- "-2,-1,0,1,2: 2 copy del,1 copy del,no change,amplification,high-amplification"
} else {
dataset <- "TCGA.PANCAN.sampleMap/Gistic2_CopyNumber_Gistic2_all_data_by_genes"
unit <- "Gistic2 copy number"
}
data <- get_data(dataset, identifier, host)
report_dataset_info(dataset)
res <- list(data = data, unit = unit)
res
}
get_pancan_methylation_value <- function(identifier, type = c("450K", "27K")) {
type <- match.arg(type)
if (type == "450K") {
host <- "pancanAtlasHub"
dataset <- "jhu-usc.edu_PANCAN_HumanMethylation450.betaValue_whitelisted.tsv.synapse_download_5096262.xena"
} else {
host <- "tcgaHub"
dataset <- "TCGA.PANCAN.sampleMap/HumanMethylation27"
}
data <- get_data(dataset, identifier, host)
unit <- "beta value"
report_dataset_info(dataset)
res <- list(data = data, unit = unit)
res
}
get_pancan_miRNA_value <- function(identifier) {
host <- "pancanAtlasHub"
dataset <- "pancanMiRs_EBadjOnProtocolPlatformWithoutRepsWithUnCorrectMiRs_08_04_16.xena"
expression <- get_data(dataset, identifier, host)
unit <- "log2(norm_value+1)"
report_dataset_info(dataset)
res <- list(expression = expression, unit = unit)
res
}
report_dataset_info <- function(dataset) {
msg <- paste0(
"More info about dataset please run following commands:\n",
" library(UCSCXenaTools)\n",
" XenaGenerate(subset = XenaDatasets == \"", dataset, "\") %>% XenaBrowse()"
)
message(msg)
}
check_file <- function(id, dataset, host) {
f <- file.path(
get_cache_dir(),
paste0(
host, "_",
gsub("[/]", "_", dataset),
"_", id, ".rds"
)
)
return(f)
}
check_exist_data <- function(id, dataset, host) {
f <- check_file(id, dataset, host)
if (file.exists(f)) {
data <- tryCatch(
readRDS(f),
error = function(e) {
message("Read cache data failed.")
return(NULL)
}
)
if (!is.null(data)) {
return(list(
ok = TRUE,
data = data
))
} else {
return(
list(
ok = FALSE,
data = NULL
)
)
}
} else {
return(
list(
ok = FALSE,
data = NULL
)
)
}
}
save_data <- function(data, id, dataset, host) {
f <- check_file(id, dataset, host)
if (!dir.exists(dirname(f))) {
dir.create(dirname(f), recursive = TRUE)
}
tryCatch(
saveRDS(data, file = f),
error = function(e) {
message("Save data to cache directory failed.")
}
)
}
get_data <- function(dataset, identifier, host = NULL) {
stopifnot(length(dataset) == 1)
if (is.null(host)) {
host <- UCSCXenaTools::XenaData %>%
dplyr::filter(.data$XenaDatasets == dataset) %>%
dplyr::pull(.data$XenaHostNames)
}
res <- check_exist_data(identifier, dataset, host)
if (res$ok) {
value <- res$data
} else {
value <- get_pancan_value(identifier, dataset = dataset, host = host)
label <- UCSCXenaTools::XenaData %>%
dplyr::filter(.data$XenaDatasets == dataset) %>%
dplyr::pull(.data$DataSubtype)
attr(value, "label") <- label
save_data(value, identifier, dataset, host)
}
value
} |
Merton <- function(L, V0, sigma, r, t){
if(!is.numeric(L)) stop("L must be a number")
if(length(L) != 1) stop("L must be a number and not a vector")
if(!is.numeric(V0)) stop("V0 must be a number")
if(length(V0) != 1) stop("V0 must be a number and not a vector")
if(!is.numeric(sigma)) stop("L must be a number")
if(length(sigma) != 1) stop("L must be a number and not a vector")
if(!is.numeric(r)) stop("r must be a number")
if(length(r) != 1) stop("r must be constant for all maturities")
if(!is.numeric(t)) stop("Time t must be a numeric vector")
d1 <- (log(V0 / L) + (r + (sigma^2 / 2) * t)) / (sigma * sqrt(t))
d2 <- d1 - sigma * sqrt(t)
Q <- stats::pnorm(-d2)
Surv <- 1 - Q
Vt <- V0 * exp(r * t)
St <- fOptions::GBSOption(TypeFlag = "c", S = Vt, X = L, Time = (t[length(t)] - t), r = r, b = r, sigma = sigma)@price
Dt <- L * exp(- r * (t[length(t)] - t)) - fOptions::GBSOption(TypeFlag = "p", S = Vt, X = L, Time = (t[length(t)] - t), r = r, b = r, sigma = sigma)@price
out <- data.frame(t, Vt, St, Dt, Surv)
names(out) <- c('Maturity', 'Vt', 'St', 'Dt', 'Survival')
return(out)
} |
test_that("simple cardinal", {
expect_equal(nom_card(2), "two")
expect_equal(
nom_card(525600), "five hundred twenty-five thousand six hundred"
)
expect_equal(nom_card(100000000), "one hundred million")
})
test_that("cardinal vector", {
expect_equal(
nom_card(c(2, 525600, 100000000)),
c(
"two",
"five hundred twenty-five thousand six hundred",
"one hundred million")
)
})
test_that("cardinal with max_n", {
expect_equal(nom_card(2, 10), "two")
expect_equal(nom_card(20, 10), "20")
expect_equal(nom_card(c(2, 20), 10), c("two", "20"))
expect_equal(nom_card(c(2, 20), -1), c("2", "20"))
expect_equal(nom_card(c(20, 20), c(10, 100)), c("20", "twenty"))
})
test_that("negative cardinal", {
expect_equal(nom_card(-2), "negative two")
expect_equal(
nom_card(-525600), "negative five hundred twenty-five thousand six hundred"
)
expect_equal(nom_card(-100000000), "negative one hundred million")
expect_equal(nom_card(-2, negative = "minus"), "minus two")
expect_equal(
nom_card(c(-2, -2), negative = c("negative", "minus")),
c("negative two", "minus two")
)
})
test_that("decimal cardinal", {
expect_equal(nom_card(2.9), "two and nine tenths")
expect_equal(nom_card(1/8), "one eighth")
expect_equal(nom_card(1/20), "one twentieth")
expect_equal(nom_card(1/1e10), "zero ten-millionths")
expect_equal(nom_card(1 - 1/1e10), "ten million ten-millionths")
expect_equal(
nom_card(3539/7079),
"three thousand five hundred thirty-nine seven-thousand-seventy-ninths"
)
expect_equal(nom_card(16/113), "sixteen hundred-thirteenths")
})
test_that("decimal cardinal with fracture ...", {
expect_equal(nom_card(1/2, base_10 = TRUE), "five tenths")
expect_equal(
nom_card(c(1/2, 3/4), common_denom = TRUE),
c("two quarters", "three quarters")
)
expect_equal(nom_card(499/1000, max_denom = 100), "one half")
expect_equal(
nom_card(1307.36, base_10 = TRUE),
"one thousand three hundred seven and thirty-six hundredths"
)
})
test_that("early return", {
expect_equal(nom_card(numeric(0)), character(0))
expect_equal(nom_numer(numeric(0)), character(0))
expect_equal(convert_hundreds(numeric(0)), character(0))
})
test_that("errors", {
expect_error(nom_card(character(1)))
expect_error(nom_card(numeric(1), negative = numeric(1)))
expect_error(nom_card(numeric(1), negative = character(0)))
expect_error(nom_card(numeric(1), negative = character(2)))
expect_error(nom_card(numeric(1), max_n = numeric(0)))
expect_error(nom_card(numeric(1), max_n = character(1)))
expect_error(nom_numer(character(1)))
expect_error(nom_numer(0.5))
}) |
b_min <- function(x, ... ){
min(x, na.rm = TRUE, ...)
}
b_max <- function(x, ... ){
max(x, na.rm = TRUE, ...)
}
b_median <- function(x, ... ){
stats::median(x, na.rm = TRUE, ...)
}
b_mean <- function(x, ... ){
mean(x, na.rm = TRUE, ...)
}
b_q25 <- function(x, ... ){
stats::quantile(x,
type = 8,
probs = 0.25,
na.rm = TRUE,
names = FALSE,
...)
}
b_q75 <- function(x, ... ){
stats::quantile(x,
type = 8,
probs = 0.75,
na.rm = TRUE,
names = FALSE,
...)
}
b_range <- function(x, ... ){
range(x, na.rm = TRUE, ...)
}
b_range_diff <- function(x, ... ) {
diff(b_range(x,
na.rm = TRUE,
...))
}
b_sd <- function(x, ... ){
stats::sd(x, na.rm = TRUE, ...)
}
b_var <- function(x, ... ){
stats::var(x, na.rm = TRUE, ...)
}
b_mad <- function(x, ... ){
stats::mad(x, na.rm = TRUE, ...)
}
b_iqr <- function(x, ... ){
stats::IQR(x, na.rm = TRUE, type = 8, ...)
}
b_diff_var <- function(x, ...){
x <- stats::na.omit(x)
if (length(x) == 1){
return(NA)
}
stats::var(diff(x, na.rm = TRUE, ...))
}
b_diff_sd <- function(x, ...){
x <- stats::na.omit(x)
if (length(x) == 1){
return(NA)
}
b_sd(diff(x, ...))
}
b_diff_mean <- function(x, ...){
x <- stats::na.omit(x)
if (length(x) == 1){
return(NA)
}
b_mean(diff(x, ...))
}
b_diff_median <- function(x, ...){
x <- stats::na.omit(x)
if (length(x) == 1){
return(NA)
}
b_median(diff(x, ...))
}
b_diff_q25 <- function(x, ...){
x <- stats::na.omit(x)
if (length(x) == 1){
return(NA)
}
b_q25(diff(x, ...))
}
b_diff_q75 <- function(x, ...){
x <- stats::na.omit(x)
if (length(x) == 1){
return(NA)
}
b_q75(diff(x, ...))
}
b_diff_max <- function(x, ...){
x <- stats::na.omit(x)
if (length(x) == 1){
return(NA)
}
b_max(diff(x, ...))
}
b_diff_min <- function(x, ...){
x <- stats::na.omit(x)
if (length(x) == 1){
return(NA)
}
b_min(diff(x, ...))
}
b_diff_iqr <- function(x, ...){
x <- stats::na.omit(x)
if (length(x) == 1){
return(NA)
}
b_iqr(diff(x, ...))
} |
mpr_request <- function(slugIDs = NULL, slugIDs_legacy = NULL, report_time = NULL, message = TRUE){
if(is.null(report_time)){
report_time = format(Sys.Date(), format="%m/%d/%Y")
}
if(is.null(slugIDs) & is.null(slugIDs_legacy))
stop('slugIDs or slugIDs_legacy must be provided.')
if(!is.null(slugIDs) & !is.null(slugIDs_legacy))
stop("Please provide slugIDs or slugIDs_legacy, not both. Hint: use data('slugInfo') to check with the ID information")
if(!is.null(slugIDs_legacy)){
ehagdhjdsdcsd <- new.env()
utils::data("slugInfo", envir = ehagdhjdsdcsd)
slugIDs <- ehagdhjdsdcsd$slugInfo$slug_id[which(ehagdhjdsdcsd$slugInfo$legacy_slugid %in% slugIDs_legacy)]
}
if(length(slugIDs) == 1){
out <- mpr_request_single(slugIDs, report_time, message = message)
}else{
out <- lapply(slugIDs, function(i) mpr_request_single(i, report_time, message = message))
names(out) <- slugIDs
}
return(out)
} |
"Case10" |
author_info<-function(authors, citations, sep,top=10,only_first_author=F){
if(length(authors)!=length(citations))stop('authors and citations must be of same length.')
if(!is.numeric(citations))stop('citations must be a numeric vector')
citations[is.na(citations)]<-0
unique_authors<-sort(table(str_trim(unlist(str_split(authors, sep)))), decreasing=T)
if(only_first_author){
auth<-str_split(authors,sep)
unique_authors<-sort(table(str_trim(sapply(auth,function(x)x[1]))),decreasing = T)
}
top<-min(top, length(unique_authors))
top_authors<-names(unique_authors)[1:top]
pat<-str_replace_all(top_authors,'\\.','\\\\.')
tp<-tc<-h<-g<-i10<-max_cit<-numeric(top)
for(i in seq_len(top)){
ind<- which(str_detect(string = authors,pattern = sprintf('%s%s|%s$',pat[i],sep,pat[i])))
tp[i]<- length(ind)
tc[i]<- sum(citations[ind])
h[i]<-h_index(citations[ind])
g[i]<-g_index(citations[ind])
i10[i]<-sum(citations[ind]>=10)
max_cit[i]<-max(citations[ind])
}
list(author_names=top_authors, total_instances=tp, total_citations=tc, h_index=h, g_index=g, i10_index=i10, max_citation=max_cit)
} |
"pepper" |
alphabetCheck<-function(sequences,alphabet="aa",label=c()){
if(length(sequences)==0){
stop("ERROR: sequence parameter is empty")
}
if(length(label)!=0&&length(label)!=length(sequences)){
stop("ERROR: The lenght of the label vector and the number of sequences do not match!")
}
if(alphabet=="rna"){
alphabet<-c("A","C","G","U")
}else if (alphabet=="dna"){
alphabet<-c("A","C","G","T")
} else if (alphabet=="aa"){
alphabet<-c("A","C","D","E","F","G","H","I","K","L","M","N","P","Q","R","S","T","V","W","Y" )
} else {
stop("ERROR: alphabet shoud be 'dna' or 'rna' or 'aa' ")
}
alphabetCheck = sapply(sequences, function(i) all(strsplit(i,
split = "")[[1]] %in% alphabet))
flag=0
if(length(label)==length(sequences)){
flag=1
label = label[alphabetCheck]
} else if(length(label)>0 && length(label)!=length(sequences)){
stop("ERROR: The number of labels is not equal to the number of sequences!")
}
if(is.null(names(sequences))){
names(sequences)<-as.character(1:length(sequences))
}
nonstanSeq<-names(sequences)[!alphabetCheck]
if(length(nonstanSeq)!=0){
nonstanSeq<-toString(nonstanSeq)
warMessage<-paste("The sequences (",nonstanSeq,") were deleted. They contained non-standard alphabets")
message(warMessage)
}
sequences = sequences[alphabetCheck]
if(length(sequences)==0){
stop("All sequences contained non-standard alphabets. No sequences remained for analysis :) ")
}
if(flag==1){
names(label)=names(sequences)
}
seq_lab<-list("sequences"=sequences,"Lab"=label)
return(seq_lab)
} |
mclapply <- function(X, FUN, ..., mc.preschedule = TRUE, mc.set.seed = TRUE,
mc.silent = FALSE, mc.cores = 1L,
mc.cleanup = TRUE, mc.allow.recursive = TRUE, affinity.list = NULL)
{
cores <- as.integer(mc.cores)
if(cores < 1L) stop("'mc.cores' must be >= 1")
if(cores > 1L) stop("'mc.cores' > 1 is not supported on Windows")
lapply(X, FUN, ...)
}
pvec <- function(v, FUN, ..., mc.set.seed = TRUE, mc.silent = FALSE,
mc.cores = 1L, mc.cleanup = TRUE)
{
if (!is.vector(v)) stop("'v' must be a vector")
cores <- as.integer(mc.cores)
if(cores < 1L) stop("'mc.cores' must be >= 1")
if(cores > 1L) stop("'mc.cores' > 1 is not supported on Windows")
FUN(v, ...)
}
mcmapply <-
function(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE,
mc.preschedule = TRUE, mc.set.seed = TRUE,
mc.silent = FALSE, mc.cores = 1L, mc.cleanup = TRUE, affinity.list = NULL)
{
cores <- as.integer(mc.cores)
if(cores < 1L) stop("'mc.cores' must be >= 1")
if(cores > 1L) stop("'mc.cores' > 1 is not supported on Windows")
mapply(FUN = FUN, ..., MoreArgs = MoreArgs, SIMPLIFY = SIMPLIFY,
USE.NAMES = USE.NAMES)
}
mcMap <- function (f, ...)
{
f <- match.fun(f)
mcmapply(f, ..., SIMPLIFY = FALSE, mc.silent = TRUE)
} |
NULL
setGeneric("ssimUpdate", function(ssimObject) standardGeneric("ssimUpdate"))
setMethod("ssimUpdate", signature(ssimObject = "character"), function(ssimObject) {
return(SyncroSimNotFound(ssimObject))
})
setMethod("ssimUpdate", signature(ssimObject = "SsimObject"), function(ssimObject) {
success <- FALSE
tt <- command(list(update = NULL, lib = .filepath(ssimObject)), .session(ssimObject))
if (!is.na(tt[1])){
if (tt == "saved"){
message("Library successfully updated")
success <- TRUE
} else{
message(tt)
}
}
return(invisible(success))
})
|
besselIs <-
function(x, nu, nterm = 800, expon.scaled = FALSE, log = FALSE,
Ceps = if(isNum) 8e-16 else 2^(- [email protected][[1]]@prec))
{
if(length(nu) > 1)
stop(" 'nu' must be scalar (length 1)!")
n <- length(x)
if(n == 0) return(x)
j <- (nterm-1):0
if(is.numeric(x) && is(nu, "mpfr")) {
x <- mpfr(x, precBits = max(64, .getPrec(nu)))
isNum <- FALSE
} else
isNum <- is.numeric(x) || is.complex(x)
l.s.j <- outer(j, (x/2), function(X,Y) X*2*log(Y))
if(is(l.s.j, "mpfr"))
j <- mpfr(j, precBits = max(sapply([email protected], slot, "prec")))
else if(!isNum) j <- as(j, class(x))
log.s.j <-
if(expon.scaled)
l.s.j - rep(abs(Re(x)), each=nterm) - lgamma(j+1) - lgamma(nu+1 + j)
else
l.s.j - lgamma(j+1) - lgamma(nu+1 + j)
if(log) {
s.j <- lsum(log.s.j)
if(any(i0 <- x == 0)) s.j[i0] <- 0
if(any(lrgS <- Re(log.s.j[1,]) > Re(log(Ceps) + s.j)))
lapply(x[lrgS], function(x)
warning(gettextf(" 'nterm=%d' may be too small for %s", nterm,
paste(format(x), collapse=", ")),
domain=NA))
nu*log(x/2) + s.j
} else {
s.j <-
exp(log.s.j)
s <- colSums(s.j)
if(any(i0 <- x == 0)) s[i0] <- 0
if(!all(iFin <- is.finite(s)))
stop(sprintf("infinite s for x=%g", x[!iFin][1]))
if(any(lrgS <- Re(s.j[1,]) > Re(Ceps * s)))
lapply(x[lrgS], function(x)
warning(gettextf(" 'nterm=%d' may be too small for %s", nterm,
paste(format(x), collapse=", ")),
domain=NA))
(x/2)^nu * s
}
}
bI <- function(x, nu, nterm = 800, expon.scaled = FALSE, log = FALSE,
Ceps = if(isNum) 8e-16 else 2^(- [email protected][[1]]@prec))
{
.Deprecated("besselIs")
isNum <- is.numeric(x) || is.complex(x)
besselIs(x, nu, nterm=nterm, expon.scaled=expon.scaled, log=log, Ceps=Ceps)
}
besselIasym <- function(x, nu, k.max = 10, expon.scaled=FALSE, log=FALSE)
{
stopifnot(k.max == round(k.max))
d <- 0
if(k.max >= 1) {
x8 <- 8*x
for(k in k.max:1) {
d <- (1 - d)*((2*(nu-k)+1)*(2*(nu+k)-1))/(k*x8)
}
}
if(expon.scaled)
sx <- x - abs(if(is.complex(x)) Re(x) else x)
pi2 <- 2* (if(inherits(x, "mpfr")) Rmpfr::Const("pi", max(.getPrec(x)))
else pi)
if(log) {
(if(expon.scaled) sx else x) + log1p(-d) - log(pi2*x) / 2
} else {
exp(if(expon.scaled) sx else x) * (1-d) / sqrt(pi2*x)
}
}
besselKasym <- function(x, nu, k.max = 10, expon.scaled=FALSE, log=FALSE)
{
stopifnot(k.max == round(k.max))
d <- 0
if(k.max >= 1) {
x8 <- 8*x
for(k in k.max:1) {
d <- (1 + d)*((2*(nu-k)+1)*(2*(nu+k)-1))/(k*x8)
}
}
pi.2 <- (if(inherits(x, "mpfr")) Rmpfr::Const("pi", max(.getPrec(x))) else pi)/2
if(log) {
(if(expon.scaled) 0 else -x ) + log1p(d) + (log(pi.2) - log(x)) / 2
} else {
(if(expon.scaled) 1 else exp(-x)) * (1+d) * sqrt(pi.2/x)
}
}
besselI.ftrms <- function(x, nu, K = 20)
{
stopifnot(length(x) == 1, x > 0, length(nu) == 1,
length(K) == 1, K == round(K), K >= 0)
kk <- seq_len(K)
mu <- 4*nu^2
x8 <- 8*x
multf <- - (mu - (2*kk-1)^2)/(kk*x8)
cumprod(multf)
}
besselI.nuAsym <- function(x, nu, k.max, expon.scaled=FALSE, log=FALSE)
{
stopifnot(k.max == round(k.max),
0 <= k.max, k.max <= 5)
z <- x/nu
sz <- sqrt(1 + z^2)
t <- 1/sz
eta <- (if(expon.scaled) {
w <- if(is.complex(z)) {
x. <- Re(z); y <- Im(z)
1-y^2 + 2i*x.*y
} else 1
w/(sz + abs(if(is.complex(z)) x. else z))
}
else sz) + log(z / (1 + sz))
if(k.max == 0)
d <- 0
else {
t2 <- t^2
u1.t <- (t*(3 - 5*t2))/24
d <-
if(k.max == 1) {
u1.t/nu
} else {
u2.t <-
t2*(81 + t2*(-462 + t2*385)) / 1152
if(k.max == 2)
(u1.t + u2.t/nu)/nu
else {
u3.t <- t*t2*(30375 +
t2*(-369603 +
t2*(765765 - t2*425425)))/ 414720
if(k.max == 3)
(u1.t + (u2.t + u3.t/nu)/nu)/nu
else {
t4 <- t2*t2
u4.t <- t4*(4465125 +
t2*(-94121676 +
t2*(349922430 +
t2*(-446185740 + t2*185910725))))/39813120
if(k.max == 4)
(u1.t + (u2.t + (u3.t + u4.t/nu)/nu)/nu)/nu
else {
u5.t <- t*t4*(1519035525 +
t2*(-49286948607 +
t2*(284499769554 +
t2*(-614135872350 +
t2*(566098157625 - t2*188699385875))
)))/6688604160
if(k.max == 5)
(u1.t + (u2.t + (u3.t + (u4.t + u5.t/nu)/nu)/nu)/nu)/nu
else
stop("k.max > 5: not yet implemented (but should NOT happen)")
}
}
}
}
}
pi2 <- 2* (if(inherits(x, "mpfr")) Rmpfr::Const("pi", max(.getPrec(x)))
else pi)
if(log) {
log1p(d) + nu*eta - (log(sz) + log(pi2*nu))/2
} else {
(1+d) * exp(nu*eta) / sqrt(pi2*nu*sz)
}
}
besselK.nuAsym <- function(x, nu, k.max, expon.scaled=FALSE, log=FALSE)
{
stopifnot(k.max == round(k.max),
0 <= k.max, k.max <= 5)
z <- x/nu
sz <- sqrt(1 + z^2)
t <- 1/sz
eta <- (if(expon.scaled)
1/(z + sz) else sz) +
log(z / (1 + sz))
if(k.max == 0)
d <- 0
else {
t2 <- t^2
u1.t <- (t*(3 - 5*t2))/24
d <-
if(k.max == 1) {
- u1.t/nu
} else {
u2.t <-
t2*(81 + t2*(-462 + t2*385)) / 1152
if(k.max == 2)
(- u1.t + u2.t/nu)/nu
else {
u3.t <- t*t2*(30375 +
t2*(-369603 +
t2*(765765 - t2*425425)))/ 414720
if(k.max == 3)
(- u1.t + (u2.t - u3.t/nu)/nu)/nu
else {
t4 <- t2*t2
u4.t <- t4*(4465125 +
t2*(-94121676 +
t2*(349922430 +
t2*(-446185740 + t2*185910725))))/39813120
if(k.max == 4)
(- u1.t + (u2.t + (-u3.t + u4.t/nu)/nu)/nu)/nu
else {
u5.t <- t*t4*(1519035525 +
t2*(-49286948607 +
t2*(284499769554 +
t2*(-614135872350 +
t2*(566098157625 - t2*188699385875))
)))/6688604160
if(k.max == 5)
(- u1.t + (u2.t + (-u3.t + (u4.t - u5.t/nu)/nu)/nu)/nu)/nu
else
stop("k.max > 5: not yet implemented (but should NOT happen)")
}
}
}
}
}
if(log) {
log1p(d) - nu*eta - (log(sz) - log(pi/(2*nu)))/2
} else {
(1+d) * exp(-nu*eta)*sqrt(pi/(2*nu * sz))
}
} |
dfbetas.manylm <-
function (model, infl = manylm.influence(model, do.coef = TRUE),
...) {
xxi <- chol2inv(model$qr$qr, model$qr$rank)
n.vars <- NCOL(model$coefficients)
dfbs <- list()
dfbetai <- dfbeta(model, infl)
sqrdigxxi <- sqrt(diag(xxi))
for(i in 1:n.vars)
dfbs[[i]] <- dfbetai[[i]] /outer(infl$sigma[,i], sqrdigxxi)
names(dfbs) <- colnames(model$coefficients)
return(dfbs)
} |
DSC_EA <- function(k, generations=2000, crossoverRate=.8, mutationRate=.001, populationSize=100) {
EA <- EA_R$new(k, generations, crossoverRate, mutationRate, populationSize)
structure(
list(
description = "EA - Reclustering using an evolutionary algorithm",
RObj = EA
), class = c("DSC_EA", "DSC_Macro", "DSC_R", "DSC")
)
}
EA_R <- setRefClass("EA",
fields = list(
crossoverRate = "numeric",
mutationRate = "numeric",
populationSize = "integer",
k = "integer",
data = "data.frame",
weights = "numeric",
generations = "integer",
C = "ANY"
),
methods = list(
initialize = function(k, generations, crossoverRate, mutationRate, populationSize) {
k <<- as.integer(k)
generations <<- as.integer(generations)
crossoverRate <<- crossoverRate
mutationRate <<- mutationRate
populationSize <<- as.integer(populationSize)
}
)
)
EA_R$methods(
cluster = function(x, weight = rep(1,nrow(x)), ...) {
data <<- x
weights <<- weight
C <<- new(EvoStream)
.self$C$reclusterInitialize(as.matrix(data), weights, .self$k, .self$crossoverRate, .self$mutationRate, .self$populationSize)
.self$C$recluster(.self$generations)
},
get_microclusters = function(...) { as.data.frame(.self$data) },
get_microweights = function(...) { .self$weights },
get_macroclusters = function(...) { as.data.frame(.self$C$get_macroclusters()) },
get_macroweights = function(...) { .self$C$get_macroweights() },
microToMacro = function(micro=NULL) {
clusterAssignment = .self$C$microToMacro()+1
if(!is.null(micro)){
return(clusterAssignment[micro])
} else{
return(clusterAssignment)
}
},
recluster = function(generations=1){.self$C$recluster(generations)}
)
DSC_registry$set_entry(name = "DSC_EA",
DSC_Micro = FALSE, DSC_Macro = TRUE,
description = "EA - Reclustering using an evolutionary algorithm") |
library(EnvNJ)
context("n-Gram")
test_that("ngram() works properly", {
s <- "MSAGARRRPR"
a <- ngram(s, k = 1)
b <- ngram(s, k = 2)
c <- ngram(s, k = 3)
d <- ngram(s, k = 4)
expect_is(a, 'data.frame')
expect_equal(length(a), 2)
expect_equal(nrow(a), 20)
expect_equal(sum(a$frequency), 10)
expect_is(b, 'data.frame')
expect_equal(length(b), 2)
expect_equal(nrow(b), 400)
expect_equal(sum(b$frequency), 9)
expect_is(c, 'data.frame')
expect_equal(length(c), 2)
expect_equal(nrow(c), 8000)
expect_equal(sum(c$frequency), 8)
expect_is(d, 'data.frame')
expect_equal(length(d), 2)
expect_equal(nrow(d), 160000)
expect_equal(sum(d$frequency), 7)
})
test_that("ngraMatrix() works properly", {
prot <- data.frame(sp1 = c("MSPGASRGPR", "MKMADRSGKI", "MACTIQKAEA"),
sp2 = c("MSAGARRRPR", "MADRGKLVPG", "MCCAIQKAEA"))
a <- ngraMatrix(prot, k = 1)
a1 <- a[[1]]
a2 <- a[[2]]
expect_is(a, 'list')
expect_is(a1, 'data.frame')
expect_is(a2, 'data.frame')
expect_equal(nrow(a1), 20)
expect_equal(length(a1), 7)
expect_equal(nrow(a2), 20)
expect_equal(length(a2), 3)
expect_equal(sum(apply(a1[-1], 2, sum) == rep(10,6)), 6)
expect_equal(sum(apply(a2[-1], 2, sum) == rep(30,2)), 2)
b <- ngraMatrix(prot, k = 2)
b1 <- b[[1]]
b2 <- b[[2]]
expect_is(b, 'list')
expect_is(b1, 'data.frame')
expect_is(b2, 'data.frame')
expect_equal(nrow(b1), 400)
expect_equal(length(b1), 7)
expect_equal(nrow(b2), 400)
expect_equal(length(b2), 3)
expect_equal(sum(apply(b1[-1], 2, sum) == rep(9,6)), 6)
expect_equal(sum(apply(b2[-1], 2, sum) == rep(27,2)), 2)
c <- ngraMatrix(prot, k = 3)
c1 <- c[[1]]
c2 <- c[[2]]
expect_is(c, 'list')
expect_is(c1, 'data.frame')
expect_is(c2, 'data.frame')
expect_equal(nrow(c1), 8000)
expect_equal(length(c1), 7)
expect_equal(nrow(c2), 8000)
expect_equal(length(c2), 3)
expect_equal(sum(apply(c1[-1], 2, sum) == rep(8,6)), 6)
expect_equal(sum(apply(c2[-1], 2, sum) == rep(24,2)), 2)
d <- ngraMatrix(prot, k = 4)
d1 <- d[[1]]
d2 <- d[[2]]
expect_is(d, 'list')
expect_is(d1, 'data.frame')
expect_is(d2, 'data.frame')
expect_equal(nrow(d1), 160000)
expect_equal(length(d1), 7)
expect_equal(nrow(d2), 160000)
expect_equal(length(d2), 3)
expect_equal(sum(apply(d1[-1], 2, sum) == rep(7,6)), 6)
expect_equal(sum(apply(d2[-1], 2, sum) == rep(21,2)), 2)
})
test_that("svdgram() works properly", {
a <- ngraMatrix(bovids, k = 2)[[1]][, -1]
b <- ngraMatrix(bovids, k = 2)[[2]][, -1]
species <- names(b)
ta <- svdgram(matrix = a, rank = c(50, 143), species = species, SVS = TRUE)
tb <- svdgram(matrix = b, rank = 11, species = species, SVS = FALSE)
expect_is(ta, "multiPhylo")
expect_equal(ta[[1]]$Nnode, 9)
expect_equal(sum(ta[[1]]$tip.label == species), 11)
expect_equal(names(ta[1]), "rank-50")
expect_is(tb, "multiPhylo")
expect_equal(tb[[1]]$Nnode, 9)
expect_equal(sum(tb[[1]]$tip.label == species), 11)
expect_equal(names(tb[1]), "rank-11")
}) |
g <- function(m,k,n,p) {
sum(dbinom(m:k,size=n,prob=p))
}
g.prime <- function(m,k,n,p) {
q <- (1-p)
out <- exp(lchoose(n-1,m-1)+(m-1)*log(p)+(n-m)*log(q))
out <- out - exp(lchoose(n-1,k)+k*log(p)+(n-k-1)*log(q))
out <- n*out
out
}
evaluate.g.maximum <- function(m,k,n) {
if(m==0 || k==n) {
max.value <- 1
} else {
a <- (lchoose(n-1,m-1)-lchoose(n-1,k))/(k-m+1)
best.p <- 1-1/(1+exp(a))
max.value <- g(m,k,n,best.p)
}
return(max.value)
}
where.g.maximum <- function(m,k,n) {
if(m==0 && k==n) {
return(NULL)
} else if(m==0) {
return(0)
} else if(k==n) {
return(1)
} else {
a <- (lchoose(n-1,m-1)-lchoose(n-1,k))/(k-m+1)
best.p <- 1-1/(1+exp(a))
return(best.p)
}
}
find.endpoints.given.confidence.level <- function(m,k,n,alpha=0.05,digits=4) {
left.endpt <- NULL
right.endpt <- NULL
interval.length <- 10^(-digits)
if(alpha==0) {
if(m!=0 || k!=n) {
return(NULL)
} else {
left.endpt <- 0
right.endpt <- 1
}
}
determine.next.x <- function(x0,a,b) {
g0 <- g(m,k,n,x0)
g.prime0 <- g.prime(m,k,n,x0)
if(is.na(g.prime0) || g.prime0==0 || is.infinite(g.prime0)) {
return((a+b)/2)
} else {
f0 <- g0-(1-alpha)
x1 <- x0-f0/g.prime0
if(x1>=a && x1<=b) {
return(x1)
} else {
return((a+b)/2)
}
}
}
search.for.right.endpoint <- function() {
while((b-a)>=interval.length) {
x1 <- determine.next.x(x0,a,b)
g1 <- g(m,k,n,x1)
if(g1<=(1-alpha)) {
b <- x1
if(a<(x1-interval.length*0.9)) {
a1 <- x1-interval.length*0.9
ga1 <- g(m,k,n,a1)
if(ga1>(1-alpha)) {
a <- a1
} else {
b <- a1
x1 <- a1
}
}
} else {
a <- x1
if(b>(x1+interval.length*0.9)) {
b1 <- x1+interval.length*0.9
gb1 <- g(m,k,n,b1)
if(gb1<=(1-alpha)) {
b <- b1
} else {
a <- b1
x1 <- b1
}
}
}
x0 <- x1
}
bb <- floor(b*10^digits)/10^digits
if(bb<=a) {
right.endpt <<- bb
} else {
gbb <- g(m,k,n,bb)
if(gbb<(1-alpha)) {
aa <- floor(a*10^digits)/10^digits
right.endpt <<- aa
} else {
right.endpt <<- bb
}
}
}
search.for.left.endpoint <- function() {
while((b-a)>=interval.length) {
x1 <- determine.next.x(x0,a,b)
g1 <- g(m,k,n,x1)
if(g1<=(1-alpha)) {
a <- x1
if(b>(x1+interval.length*0.9)) {
b1 <- x1+interval.length*0.9
gb1 <- g(m,k,n,b1)
if(gb1>(1-alpha)) {
b <- b1
} else {
a <- b1
x1 <- b1
}
}
} else {
b <- x1
if(a<(x1-interval.length*0.9)) {
a1 <- x1-interval.length*0.9
ga1 <- g(m,k,n,a1)
if(ga1<=(1-alpha)) {
a <- a1
} else {
b <- a1
x1 <- a1
}
}
}
x0 <- x1
}
aa <- ceiling(a*10^digits)/10^digits
if(aa>=b) {
left.endpt <<- aa
} else {
gaa <- g(m,k,n,aa)
if(gaa<(1-alpha)) {
bb <- ceiling(b*10^digits)/10^digits
left.endpt <<- bb
} else {
left.endpt <<- aa
}
}
}
if(m==0 && k==n) {
left.endpt <- 0
right.endpt <- 1
} else if(m==0) {
left.endpt <- 0
a <- 0
b <- 1
x0 <- 1/2
g0 <- g(m,k,n,x0)
if(g0<=(1-alpha)) {
b <- x0
} else {
a <- x0
}
search.for.right.endpoint()
} else if(k==n) {
right.endpt <- 1
a <- 0
b <- 1
x0 <- 1/2
g0 <- g(m,k,n,x0)
if(g0<=(1-alpha)) {
a <- x0
} else {
b <- x0
}
search.for.left.endpoint()
} else {
max.coverage <- evaluate.g.maximum(m,k,n)
if(max.coverage<(1-alpha)) {
return(NULL)
} else {
g.max <- where.g.maximum(m,k,n)
a <- 0
b <- g.max
x0 <- (a+b)/2
g0 <- g(m,k,n,x0)
if(g0<=(1-alpha)) {
a <- x0
} else {
b <- x0
}
search.for.left.endpoint()
a <- g.max
b <- 1
x0 <- (a+b)/2
g0 <- g(m,k,n,x0)
if(g0<=(1-alpha)) {
b <- x0
} else {
a <- x0
}
search.for.right.endpoint()
if(left.endpt>right.endpt) {
return(NULL)
}
}
}
return(c(left.endpt,right.endpt))
}
evaluate.coverage <- function(L.vec, U.vec=NULL, digits=10) {
n <- length(L.vec)-1
stopifnot(n>0)
L.vec <- round(L.vec*10^digits)/10^digits
if(is.null(U.vec)) {
U.vec <- rev(1-L.vec)
}
U.vec <- round(U.vec*10^digits)/10^digits
stopifnot(length(U.vec)==(n+1))
coverage.at.left.endpt.vec <- rep(NA, n+1)
coverage.at.right.endpt.vec <- rep(NA, n+1)
for(i in 1:length(L.vec)) {
left.endpt <- L.vec[i]
if(left.endpt==0) {
coverage.at.left.endpt.vec[i] <- ifelse(L.vec[1]==0,1,0)
} else {
X.range <- range(which(L.vec<left.endpt & left.endpt<=U.vec))
m <- X.range[1]-1
k <- X.range[2]-1
coverage.at.left.endpt.vec[i] <- g(m,k,n,p=left.endpt)
}
}
for(i in 1:length(U.vec)) {
right.endpt <- U.vec[i]
if(right.endpt==1) {
coverage.at.right.endpt.vec[i] <- ifelse(U.vec[n+1]==1,1,0)
} else {
X.range <- range(which(U.vec>right.endpt & L.vec<=right.endpt))
m <- X.range[1]-1
k <- X.range[2]-1
coverage.at.right.endpt.vec[i] <- g(m,k,n,p=right.endpt)
}
}
output <- cbind(coverage.at.left.endpt.vec,coverage.at.right.endpt.vec)
rownames(output) <- paste("X=", c(0:n))
return(output)
}
blyth.still.casella <- function(n,
X=NULL,
alpha=0.05,
digits=2,
CIs.init=NULL,
additional.info=FALSE) {
stopifnot(alpha>=0 && alpha<1)
stopifnot(n==floor(n) && n>0)
if(!is.null(X)) {
stopifnot(X==floor(X) && X>=0 && X<=n)
}
if(alpha==0) {
CI.mat <- matrix(NA, nrow=n+1, ncol=2)
CI.mat[,1] <- 0
CI.mat[,2] <- 1
rownames(CI.mat) <- paste0("X=",0:n)
colnames(CI.mat) <- c("L","U")
Endpoint.Type.mat <- matrix("NC",nrow=n+1,ncol=2)
rownames(Endpoint.Type.mat) <- paste0("X=",0:n)
colnames(Endpoint.Type.mat) <- c("L","U")
Range.mat <- matrix(NA,nrow=n+1,ncol=4)
Range.mat[,1:2] <- 0
Range.mat[,3:4] <- 1
rownames(Range.mat) <- paste0("X=",0:n)
colnames(Range.mat) <- c("L.min","L.max","U.min","U.max")
if(!is.null(X)) {
CI.mat <- CI.mat[X+1,,drop=FALSE]
Endpoint.Type.mat <- Endpoint.Type.mat[X+1,,drop=FALSE]
Range.mat <- Range.mat[X+1,,drop=FALSE]
}
if(!additional.info) {
result <- CI.mat
class(result) <- "customclass"
return(result)
} else {
result <- list(CI=CI.mat,Endpoint.Type=Endpoint.Type.mat,Range=Range.mat)
class(result) <- "customclass"
return(result)
}
}
if(n==1) {
CI.mat <- matrix(NA, nrow=2, ncol=2)
CI.mat[1,] <- c( 0,max(1-alpha,0.5))
CI.mat[2,] <- c(min(alpha,0.5), 1)
CI.mat[1,2] <- ceiling(CI.mat[1,2]*10^digits)/10^digits
CI.mat[2,1] <- floor(CI.mat[2,1]*10^digits)/10^digits
rownames(CI.mat) <- c("X=0","X=1")
colnames(CI.mat) <- c("L","U")
Endpoint.Type.mat <- matrix("NC",nrow=2,ncol=2)
rownames(Endpoint.Type.mat) <- c("X=0","X=1")
colnames(Endpoint.Type.mat) <- c("L","U")
Range.mat <- cbind(CI.mat[,1],CI.mat[,1],CI.mat[,2],CI.mat[,2])
rownames(Range.mat) <- c("X=0","X=1")
colnames(Range.mat) <- c("L.min","L.max","U.min","U.max")
if(!is.null(X)) {
CI.mat <- CI.mat[X+1,,drop=FALSE]
Endpoint.Type.mat <- Endpoint.Type.mat[X+1,,drop=FALSE]
Range.mat <- Range.mat[X+1,,drop=FALSE]
}
if(!additional.info) {
result <- CI.mat
class(result) <- "customclass"
return(result)
} else {
result <- list(CI=CI.mat,Endpoint.Type=Endpoint.Type.mat,Range=Range.mat)
class(result) <- "customclass"
return(result)
}
}
digits.save <- digits
if(!is.null(CIs.init)) {
stopifnot(ncol(CIs.init)==2 && nrow(CIs.init)==(n+1))
L.vec <- floor(CIs.init[,1]*10^digits)/10^digits
U.vec <- ceiling(CIs.init[,2]*10^digits)/10^digits
stopifnot(all(diff(L.vec)>=0))
stopifnot(all(diff(U.vec)>=0))
min.coverage <- min(evaluate.coverage(L.vec,U.vec,digits)[[1]], evaluate.coverage(L.vec,U.vec,digits)[[2]])
if(min.coverage<(1-alpha)) stop("Initial set of confidence intervals does not have sufficient coverage probability");
} else {
L.vec <- qbeta(alpha/2,0:n,(n+1):1)
U.vec <- qbeta(1-alpha/2,1:(n+1),n:0)
L.vec <- floor(L.vec*10^digits)/10^digits
U.vec <- ceiling(U.vec*10^digits)/10^digits
}
move.noncoincidental.endpoint <- function() {
L.at.i <- L.vec[i+1]
j <- which(U.vec[0:(i-1)+1]>L.at.i)
if(length(j)==0) {
i <<- i-1
return(invisible(NULL))
}
j <- j[1]-1
first.touch.vers <- rep(Inf,4)
if(i<n) {
first.touch.vers[1] <- L.vec[i+2]
}
if(i!=(n/2)) {
first.touch.vers[2] <- U.vec[i+1]
}
if((i+j)!=n) {
first.touch.vers[3] <- U.vec[j+1]
}
if(i==(n/2) || (i+j)==n) {
first.touch.vers[4] <- 0.5
}
first.touch <- min(first.touch.vers)
if(first.touch==Inf) {
i <<- i-1
return(invisible(NULL))
}
if(g(j,i-1,n,first.touch)<(1-alpha)) {
endpts <- find.endpoints.given.confidence.level(j,i-1,n,alpha,digits)
if(is.null(endpts)) {
i <<- (i-1)
} else {
right.endpt <- endpts[2]
if(L.at.i < right.endpt) {
L.vec[i+1] <<- right.endpt
U.vec[n-i+1] <<- round((1-right.endpt)*10^digits)/10^digits
coincidental.endpoint.idx[i+1] <<- NA
i <<- (i-1)
} else {
coincidental.endpoint.idx[i+1] <<- NA
i <<- (i-1)
}
}
} else {
if(L.at.i < first.touch) {
L.vec[i+1] <<- first.touch
U.vec[n-i+1] <<- round((1-first.touch)*10^digits)/10^digits
coincidental.endpoint.idx[i+1] <<- NA
} else {
i <<- i-1
}
}
}
move.coincidental.endpoint <- function() {
L.at.i <- L.vec[i+1]
j.equal <- which(U.vec[0:(i-1)+1]==L.at.i)-1
if(i<n) {
j.not.taken <- setdiff(j.equal, coincidental.endpoint.idx[(i+2):(n+1)])
if(!all(is.na(coincidental.endpoint.idx[(i+2):(n+1)]))) {
j.not.taken <- j.not.taken[j.not.taken < min(coincidental.endpoint.idx[(i+2):(n+1)], na.rm = T)]
}
}else {
j.not.taken <- j.equal
}
if(length(j.not.taken)>0) {
coincidental.endpoint.idx[i+1] <<- j.not.taken[length(j.not.taken)]
j <- j.not.taken[length(j.not.taken)]
}else{
stop("No matching j is found")
}
if(j==(n-i)) {
i <<- i-1
return(invisible(NULL))
}
if(g(j,i-1,n,L.at.i)<(1-alpha) || g(j+1,i,n,L.at.i)<(1-alpha)) {
new.j <- j
k <- length(j.not.taken)
while (g(new.j,i-1,n,L.at.i)<(1-alpha) || g(new.j+1,i,n,L.at.i)<(1-alpha)) {
if(k<1) {
stop("Error: None of the endpoints satisfy the coverage")
}
else{
k <- k-1
new.j <- j.not.taken[k]
}
}
coincidental.endpoint.idx[i+1] <<- new.j
i <<- i-1
return(invisible(NULL))
}
first.touch.vers <- rep(Inf,6)
if(i<n && (i+1)!=(n-j)) {
first.touch.vers[1] <- L.vec[i+2]
}
if(i!=(n-i)) {
first.touch.vers[2] <- U.vec[i+1]
}
if((i+j)<n) {
first.touch.vers[3] <- 0.5
}
if((j+1)!=(n-i)) {
first.touch.vers[4] <- U.vec[j+2]
}
if((i+j)<n) {
first.touch.vers[5] <- 0.5
}
if(j<(i-1)) {
endpts.sep.set <- find.endpoints.given.confidence.level(j+1,i-1,n,alpha,digits)
if(!is.null(endpts.sep.set)) {
if(endpts.sep.set[2]>L.at.i) {
g.max <- where.g.maximum(j+1,i-1,n)
first.choice <- round(g.max*10^digits)/10^digits
second.choice <- floor(endpts.sep.set[2]*10^digits)/10^digits
if(first.choice>endpts.sep.set[2] || first.choice<=L.at.i) {
first.choice <- NULL
}
if(second.choice<=L.at.i) {
second.choice <- NULL
}
if(!is.null(first.choice)) {
first.touch.vers[6] <- first.choice
} else if(!is.null(second.choice)) {
first.touch.vers[6] <- second.choice
}
}
}
}
first.touch <- min(first.touch.vers)
if(first.touch==Inf) {
i <<- i-1
return(invisible(NULL))
}
if(g(j,i-1,n,first.touch)<(1-alpha) || g(j+1,i,n,first.touch)<(1-alpha)) {
endpts.set1 <- find.endpoints.given.confidence.level(j,i-1,n,alpha,digits)
endpts.set2 <- find.endpoints.given.confidence.level(j+1,i,n,alpha,digits)
if(is.null(endpts.set1) || is.null(endpts.set2)) {
i <<- (i-1)
} else {
right.endpt <- endpts.set1[2]
if(right.endpt < endpts.set2[1] || right.endpt <= L.at.i) {
i <<- (i-1)
} else {
L.vec[i+1] <<- right.endpt
U.vec[n-i+1] <<- round((1-right.endpt)*10^digits)/10^digits
U.vec[j+1] <<- right.endpt
L.vec[n-j+1] <<- round((1-right.endpt)*10^digits)/10^digits
i <<- (i-1)
}
}
} else {
if(L.at.i < first.touch) {
L.vec[i+1] <<- first.touch
U.vec[n-i+1] <<- round((1-first.touch)*10^digits)/10^digits
U.vec[j+1] <<- first.touch
L.vec[n-j+1] <<- round((1-first.touch)*10^digits)/10^digits
} else {
i <<- (i-1)
}
}
}
L.no.longer.changes <- FALSE
iter <- 0
while(!L.no.longer.changes) {
iter <- iter + 1
L.old <- L.vec
i <- n
coincidental.endpoint.idx <- rep(NA, n+1)
while(i>0) {
L.at.i <- L.vec[i+1]
j.equal <- which(U.vec[0:(i-1)+1]==L.at.i)-1
if(i<n){
j.not.taken <- setdiff(j.equal, coincidental.endpoint.idx[(i+2):(n+1)])
if(!all(is.na(coincidental.endpoint.idx[(i+2):(n+1)]))) {
j.not.taken <- j.not.taken[j.not.taken < min(coincidental.endpoint.idx[(i+2):(n+1)], na.rm = T)]
}
}else {
j.not.taken <- j.equal
}
j <- j.not.taken
if(length(j)>0) {
j <- j[length(j)]
separable <- TRUE
if(j==(i-1)) {
separable <- FALSE
} else {
if(g(j+1,i-1,n,L.at.i)<(1-alpha)) {
separable <- FALSE
}
}
if(separable) {
move.noncoincidental.endpoint()
} else {
move.coincidental.endpoint()
}
} else {
move.noncoincidental.endpoint()
}
}
L.new <- L.vec
if(all(L.new==L.old)) L.no.longer.changes <- TRUE
}
coincidental.endpt.mat <- cbind(c(0:n), coincidental.endpoint.idx)
colnames(coincidental.endpt.mat) <- NULL
keep.ind <- which(apply(coincidental.endpt.mat,1,sum)!=n & !is.na(coincidental.endpt.mat[,2]))
if(length(keep.ind)==0) {
coincidental.endpt.mat.reduced <- c()
} else {
coincidental.endpt.mat.reduced <- coincidental.endpt.mat[keep.ind,,drop=FALSE]
}
if(!is.null(coincidental.endpt.mat.reduced)) {
colnames(coincidental.endpt.mat.reduced) <- c("L.index", "U.index")
}
Range.mat <- cbind(L.vec,L.vec,U.vec,U.vec)
if(!is.null(coincidental.endpt.mat.reduced)) {
for(k in 1:nrow(coincidental.endpt.mat.reduced)) {
i <- coincidental.endpt.mat.reduced[k,1]
j <- coincidental.endpt.mat.reduced[k,2]
endpts.set1 <- find.endpoints.given.confidence.level(j,i-1,n,alpha,digits)
endpts.set2 <- find.endpoints.given.confidence.level(j+1,i,n,alpha,digits)
if(is.null(endpts.set1) || is.null(endpts.set2)) {
stop("Error in deciding allowable range for coincidental endpoints.
Please consider increasing the argument 'digits'.")
}
allowable.range <- c(endpts.set2[1],endpts.set1[2])
Range.mat[i+1,1:2] <- allowable.range
Range.mat[j+1,3:4] <- allowable.range
Range.mat[n-i+1,3:4] <- round(rev(1-allowable.range)*10^digits)/10^digits
Range.mat[n-j+1,1:2] <- round(rev(1-allowable.range)*10^digits)/10^digits
}
}
while(TRUE) {
no.more.adjustment <- TRUE
if(!is.null(coincidental.endpt.mat.reduced)) {
for(k in 1:nrow(coincidental.endpt.mat.reduced)) {
i <- coincidental.endpt.mat.reduced[k,1]
j <- coincidental.endpt.mat.reduced[k,2]
range.lower.limit <- Range.mat[i+1,1]
range.upper.limit <- Range.mat[i+1,2]
rll <- range.lower.limit
rul <- range.upper.limit
rll.candidates.vec <- c()
rul.candidates.vec <- c()
if(i+j<n) {
rul.candidates.vec <- c(rul.candidates.vec, 0.5)
}
if(i+j>n) {
rll.candidates.vec <- c(rll.candidates.vec, 0.5)
}
if(i>0) {
rll.candidates.vec <- c(rll.candidates.vec, Range.mat[i,1])
}
if(j>0) {
rll.candidates.vec <- c(rll.candidates.vec, Range.mat[j,3])
}
if(i<n) {
rul.candidates.vec <- c(rul.candidates.vec, Range.mat[i+2,2])
}
if(j<n) {
rul.candidates.vec <- c(rul.candidates.vec, Range.mat[j+2,4])
}
if(rll<max(rll.candidates.vec)) {
no.more.adjustment <- FALSE
rll <- max(rll.candidates.vec)
Range.mat[ i+1,1] <- rll
Range.mat[ j+1,3] <- rll
Range.mat[n-i+1,4] <- 1-rll
Range.mat[n-j+1,2] <- 1-rll
}
if(rul>min(rul.candidates.vec)) {
no.more.adjustment <- FALSE
rul <- min(rul.candidates.vec)
Range.mat[ i+1,2] <- rul
Range.mat[ j+1,4] <- rul
Range.mat[n-i+1,3] <- 1-rul
Range.mat[n-j+1,1] <- 1-rul
}
}
}
if(no.more.adjustment)
break;
}
rownames(Range.mat) <- paste0("X=",0:n)
colnames(Range.mat) <- c("L.min","L.max","U.min","U.max")
L.vec <- round((Range.mat[,1]+Range.mat[,2])/2*10^digits)/10^digits
U.vec <- rev(round((1-L.vec)*10^digits)/10^digits)
if(!is.null(coincidental.endpt.mat.reduced)) {
for(k in 1:nrow(coincidental.endpt.mat.reduced)) {
i <- coincidental.endpt.mat.reduced[k,1]
j <- coincidental.endpt.mat.reduced[k,2]
realigned.endpt <- max(L.vec[i+1],U.vec[j+1])
L.vec[i+1] <- U.vec[j+1] <- realigned.endpt
}
}
CI.mat <- cbind(L.vec,U.vec)
rownames(CI.mat) <- paste0("X=",0:n)
colnames(CI.mat) <- c("L","U")
Endpoint.Type.mat <- matrix("NC",nrow=n+1,ncol=2)
half.range.mat <- matrix(NA, nrow = n + 1, ncol = 2)
if(!is.null(coincidental.endpt.mat.reduced)) {
coincidental.Ls <- coincidental.endpt.mat.reduced[,1]
coincidental.Us <- coincidental.endpt.mat.reduced[,2]
Endpoint.Type.mat[coincidental.Ls+1,1] <- "C"
Endpoint.Type.mat[coincidental.Us+1,2] <- "C"
half.range.mat[coincidental.Ls+1,1] <- (Range.mat[coincidental.Ls+1,1] + Range.mat[coincidental.Ls+1,2])/2
half.range.mat[coincidental.Us+1,2] <- (Range.mat[coincidental.Us+1,1] + Range.mat[coincidental.Us+1,2])/2
}
rownames(Endpoint.Type.mat) <- paste0("X=",0:n)
colnames(Endpoint.Type.mat) <- c("L","U")
rownames(half.range.mat) <- paste0("X=",0:n)
colnames(half.range.mat) <- c("L","U")
if(digits.save!=digits) {
digits <- digits.save
CI.mat[,1] <- floor(CI.mat[,1]*10^digits)/10^digits
CI.mat[,2] <- ceiling(CI.mat[,2]*10^digits)/10^digits
Range.mat[,1] <- pmin(ceiling(Range.mat[,1]*10^digits)/10^digits, CI.mat[,1])
Range.mat[,2] <- pmax( floor(Range.mat[,2]*10^digits)/10^digits, CI.mat[,1])
Range.mat[,3] <- pmin(ceiling(Range.mat[,3]*10^digits)/10^digits, CI.mat[,2])
Range.mat[,4] <- pmax( floor(Range.mat[,4]*10^digits)/10^digits, CI.mat[,2])
}
if(!is.null(X)) {
CI.mat <- CI.mat[X+1,,drop=FALSE]
if(length(c(which(coincidental.endpt.mat.reduced[,1] == X),
which(coincidental.endpt.mat.reduced[,2] == X))) == 0){
coincidental.endpt.mat.reduced <- NULL
}else{
coincidental.endpt.mat.reduced <- coincidental.endpt.mat.reduced[c(which(coincidental.endpt.mat.reduced[,1] == X),
which(coincidental.endpt.mat.reduced[,2] == X)),,drop=FALSE]
}
Endpoint.Type.mat <- Endpoint.Type.mat[X+1,,drop=FALSE]
Range.mat <- Range.mat[X+1,,drop=FALSE]
}
if(!additional.info) {
result <- CI.mat
class(result) <- "customclass"
return(result)
} else {
result <- list(CI=CI.mat, coinc.index = coincidental.endpt.mat.reduced, endpoint.type=Endpoint.Type.mat, range=Range.mat)
class(result) <- "customclass"
return(result)
}
}
add.sign.to.number <- function(x, digits) {
x.c <- lapply(x, function(x) {if(!is.na(x)) {x <- formatC(x, format = 'f', digits = digits)} else {x<- ""}})
x.plus.sign <- lapply(x.c, function(x) {if(x != "") x <- paste(c(bquote("\U00B1"), x), collapse = " ")})
x.plus.sign[sapply(x.plus.sign, is.null)] <- ""
x.plus.sign <- unlist(x.plus.sign)
return(x.plus.sign)
}
summary.customclass <- function(object, ...) {
arguments <- list(...)
if (!is.null(names(object))) {
ls <- object$CI[,1]
us <- object$CI[,2]
lus <- c(ls, us)
if(all(lus %in% c(0,1))){
l.for.digits <- 0
} else {
l.for.digits <- max(lus[!lus %in% c(0,1)])
}
digits <- nchar(sub("^.+[.]","",l.for.digits))
L.range <- floor(apply(object$range, 1, function(x) if(x[1] != x[2]) {1/2*(x[2] - x[1])} else NA)*10^digits)/10^digits
L.range.plus.sign <- add.sign.to.number(L.range, digits)
U.range <- floor(apply(object$range, 1, function(x) if(x[3] != x[4]) {1/2*(x[4] - x[3])} else NA)*10^digits)/10^digits
U.range.plus.sign <- add.sign.to.number(U.range, digits)
output <- data.frame(L = ls, L.range = L.range.plus.sign,
U = us, U.range = U.range.plus.sign)
return(output)
} else {
output <- object
class(output) <- "matrix"
return(summary(output))
}
} |
quantile.mcmc.list <-
function(x, ...)
{
apply(as.matrix(x), 2, quantile, ...)
} |
EnsureMatrix <- function(x, nRow = NULL, nCol = NULL) {
if (is.null(x)) {
if(!is.null(nCol))
if(nCol)
stop("nCol not allowed when x is NULL")
return(matrix(0, nRow, 0))
}
x <- as.matrix(x)
if (!is.null(nRow))
if (nrow(x) != nRow)
stop(paste("nrow is", nrow(x), "when", nRow, "expected"))
if (!is.null(nCol))
if (ncol(x) != nCol)
stop(paste("ncol is", ncol(x), "when", nCol, "expected"))
x
}
EnsureIntercept <- function(x) {
colMax <- apply(x, 2, max)
colMin <- apply(x, 2, min)
if (!any((colMax - colMin == 0) & (colMax != 0)))
return(cbind(1, x))
x
} |
AGumbel <- function(copula, w) .AGumbel(w, copula@parameters[1])
.AGumbel <- function(w, alpha) {
r <- w
w <- w[i <- which(!(bnd <- w == 0 | w == 1))]
r[i] <- (w^alpha + (1 - w)^alpha)^(1/alpha)
r[bnd] <- 1
r
}
dAduGumbel <- function(copula, w) {
alpha <- copula@parameters[1]
value <- eval(expression({
.expr2 <- 1 - w
.expr4 <- w^alpha + .expr2^alpha
.expr5 <- 1/alpha
.expr7 <- .expr5 - 1
.expr8 <- .expr4^.expr7
.expr9 <- alpha - 1
.expr14 <- w^.expr9 * alpha - .expr2^.expr9 * alpha
.expr15 <- .expr5 * .expr14
.expr22 <- .expr9 - 1
.value <- .expr4^.expr5
.grad <- array(0, c(length(.value), 1L), list(NULL, "w"))
.hessian <- array(0, c(length(.value), 1L, 1L), list(NULL, "w", "w"))
.grad[, "w"] <- .expr8 * .expr15
.hessian[, "w", "w"] <- .expr4^(.expr7 - 1) * (.expr7 * .expr14) *
.expr15 + .expr8 * (.expr5 * (w^.expr22 * .expr9 * alpha +
.expr2^.expr22 * .expr9 * alpha))
attr(.value, "gradient") <- .grad
attr(.value, "hessian") <- .hessian
.value
}), list(alpha=alpha, w=w))
der1 <- c(attr(value, "gradient"))
der2 <- c(attr(value, "hessian"))
data.frame(der1=der1, der2=der2)
}
gumbelCopula <- function(param = NA_real_, dim = 2L,
use.indepC = c("message", "TRUE", "FALSE"))
{
stopifnot(length(param) == 1)
if(!is.na(param) && param == 1) {
use.indepC <- match.arg(use.indepC)
if(!identical(use.indepC, "FALSE")) {
if(identical(use.indepC, "message"))
message("parameter at boundary ==> returning indepCopula()")
return( indepCopula(dim=dim) )
}
}
cdfExpr <- function(d) {
expr <- "( - log(u1))^alpha"
for (i in 2:d) {
cur <- paste0( "(-log(u", i, "))^alpha")
expr <- paste(expr, cur, sep=" + ")
}
expr <- paste("exp(- (", expr, ")^ (1/alpha))")
parse(text = expr)
}
pdfExpr <- function(cdf, d) {
val <- cdf
for (i in 1:d) {
val <- D(val, paste0("u", i))
}
val
}
cdf <- cdfExpr((dim <- as.integer(dim)))
pdf <- if (dim <= 6) pdfExpr(cdf, dim)
new("gumbelCopula",
dimension = dim,
parameters = param,
exprdist = c(cdf = cdf, pdf = pdf),
param.names = "alpha",
param.lowbnd = 1,
param.upbnd = Inf,
fullname = "<deprecated slot>")
}
rgumbelCopula <- function(n, copula) {
dim <- copula@dimension
alpha <- copula@parameters[1]
if(is.na(alpha <- copula@parameters[1])) stop("parameter is NA")
if (alpha - 1 < .Machine$double.eps ^(1/3) )
return(rCopula(n, indepCopula(dim=dim)))
b <- 1/alpha
fr <- if(identical(getOption("copula:rstable1"), "rPosStable"))
rPosStableS(n, b) else rstable1(n, alpha = b, beta = 1,
gamma = cospi2(b)^alpha, pm=1)
val <- matrix(runif(dim * n), nrow = n)
psi(copula, - log(val) / fr)
}
pgumbelCopula <- function(copula, u) {
dim <- copula@dimension
if(!is.matrix(u)) u <- matrix(u, ncol = dim)
for (i in 1:dim) assign(paste0("u", i), u[,i])
alpha <- copula@parameters[1]
pmax(eval(copula@exprdist$cdf), 0)
}
dgumbelCopula <- function(u, copula, log=FALSE, ...) {
if(!is.matrix(u)) u <- rbind(u, deparse.level = 0L)
dim <- copula@dimension
for (i in 1:dim) assign(paste0("u", i), u[,i])
if(log) stop("'log=TRUE' not yet implemented")
alpha <- copula@parameters[1]
eval(copula@exprdist$pdf)
}
if(FALSE)
dgumbelCopula.pdf <- function(u, copula, log=FALSE) {
dim <- copula@dimension
if (dim > 10) stop("Gumbel copula PDF not implemented for dimension > 10.")
if(!is.matrix(u)) u <- rbind(u, deparse.level = 0L)
for (i in 1:dim) assign(paste0("u", i), u[,i])
alpha <- copula@parameters[1]
if(log)
log(c(eval(gumbelCopula.pdf.algr[dim])))
else c(eval(gumbelCopula.pdf.algr[dim]))
}
iTauGumbelCopula <- function(copula, tau) {
if (any(neg <- tau < 0)) {
warning("For the Gumbel copula, tau must be >= 0. Replacing negative values by 0.")
tau[neg] <- 0
}
1/(1 - tau)
}
gumbelRhoFun <- function(alpha) {
theta <- .gumbelRho$trFuns$forwardTransf(alpha, .gumbelRho$ss)
c(.gumbelRho$assoMeasFun$valFun(theta))
}
gumbeldRho <- function(alpha) {
ss <- .gumbelRho$ss
forwardTransf <- .gumbelRho$trFuns$forwardTransf
forwardDer <- .gumbelRho$trFuns$forwardDer
valFun <- .gumbelRho$assoMeasFun$valFun
theta <- forwardTransf(alpha, ss)
c(valFun(theta, 1)) * forwardDer(alpha, ss)
}
iRhoGumbelCopula <- function(copula, rho) {
if (any(neg <- rho < 0)) {
warning("For the Gumbel copula, rho must be >= 0. Replacing negative values by 0.")
rho[neg] <- 0
}
gumbelRhoInv <- approxfun(x = .gumbelRho$assoMeasFun$fm$ysmth,
y = .gumbelRho$assoMeasFun$fm$x, rule = 2)
ss <- .gumbelRho$ss
theta <- gumbelRhoInv(rho)
.gumbelRho$trFuns$backwardTransf(theta, ss)
}
setMethod("rCopula", signature("numeric", "gumbelCopula"), rgumbelCopula)
setMethod("pCopula", signature("matrix", "gumbelCopula"),
function(u, copula, ...) .pacopula(u, copGumbel, theta=copula@parameters))
setMethod("dCopula", signature("matrix", "gumbelCopula"),
function (u, copula, log = FALSE, checkPar=TRUE, ...)
copGumbel@dacopula(u, theta=copula@parameters, log=log, checkPar=checkPar, ...))
setMethod("A", signature("gumbelCopula"), AGumbel)
setMethod("dAdu", signature("gumbelCopula"), dAduGumbel)
setMethod("iPsi", signature("gumbelCopula"),
function(copula, u) copGumbel@iPsi(u, theta=copula@parameters))
setMethod("psi", signature("gumbelCopula"),
function(copula, s) copGumbel@psi(s, theta=copula@parameters))
setMethod("diPsi", signature("gumbelCopula"),
function(copula, u, degree=1, log=FALSE, ...) {
s <- if(log || degree %% 2 == 0) 1. else -1.
s* copGumbel@absdiPsi(u, theta=copula@parameters, degree=degree, log=log, ...)
})
setMethod("tau", "gumbelCopula", function(copula) 1 - 1/copula@parameters)
setMethod("rho", "gumbelCopula", function(copula) gumbelRhoFun(copula@parameters))
setMethod("lambda", signature("gumbelCopula"), function(copula, ...)
c(lower = 0, upper = 2 - 2^(1/copula@parameters)))
setMethod("iTau", signature("gumbelCopula"), iTauGumbelCopula)
setMethod("iRho", signature("gumbelCopula"), iRhoGumbelCopula)
setMethod("dRho", "gumbelCopula", function(copula) gumbeldRho(copula@parameters))
setMethod("dTau", "gumbelCopula", function(copula) 1 / copula@parameters^2) |
sscv = function(CV, DesignNo=1, True.R=1, Alpha=0.1, Beta=0.2, ThetaL=0.8, ThetaU=1.25, nMax=999999)
{
mse = log(1 + (CV/100)^2)
return(ssmse(mse, DesignNo, True.R, Alpha, Beta, ThetaL, ThetaU, nMax))
} |
context("assertions about utils in utils.R")
just.show.error <- function(err, ...){
lapply(err, summary)
}
test_that("has_all_names works with verify", {
expect_equal(verify(mtcars, has_all_names("mpg", "wt", "qsec")), mtcars)
expect_equal(mtcars %>% verify(has_all_names("mpg", "wt", "qsec")), mtcars)
mpgg <- "something"
expect_equal(verify(mtcars, exists("mpgg")), mtcars)
expect_output(
mtcars %>% verify(has_all_names("mpgg"), error_fun = just.show.error),
"verification [has_all_names(\"mpgg\")] failed! (1 failure)",
fixed = TRUE)
mpg_var <- "mpg"
wt_var <- "wt"
expect_equal(verify(mtcars, has_all_names(mpg_var, wt_var)), mtcars)
expect_equal(mtcars %>% verify(has_all_names(mpg_var, wt_var)), mtcars)
})
test_that("has_only_names works with verify", {
test_data <- data.frame(A=1, B=2)
expect_equal(verify(test_data, has_only_names(c("B", "A"))), test_data)
expect_equal(verify(test_data, has_only_names(c("A", "B"))), test_data)
expect_equal(verify(test_data, has_only_names("A", "B")), test_data)
expect_output(
expect_error(verify(test_data, has_only_names("A"))),
regexp='verification [has_only_names("A")] failed',
fixed=TRUE
)
expect_error(
verify(test_data, has_only_names(1)),
regexp="Arguments to 'has_only_names()' must be character strings.",
fixed=TRUE
)
})
test_that("has_class works with verify", {
expect_equal(verify(mtcars, has_class("mpg", class = "numeric")), mtcars)
expect_equal(
mtcars %>% verify(has_class("mpg", "wt", class = "numeric")), mtcars)
expect_output(
mtcars %>% verify(has_class("mpg", class = "character"), error_fun = just.show.error),
"verification [has_class(\"mpg\", class = \"character\")] failed! (1 failure)",
fixed = TRUE
)
mpg_var <- "mpg"
wt_var <- "wt"
expect_equal(verify(mtcars, has_class(mpg_var, class = "numeric")), mtcars)
expect_equal(mtcars %>% verify(has_class(mpg_var, wt_var, class = "numeric")), mtcars)
}) |
print.summary.invGauss <- function(x, covariance = FALSE, ...){
cat("Call:\n")
print(x$call)
cat("\nCoefficients:\n")
print(x$coefficients)
cat("\nLog likelihood: ", x$loglik, "\n\n", sep = "")
cat("AIC: ", x$AIC, "\n\n", sep = "")
if(covariance) {
cat("Asymptotic covariance of coefficients:\n")
print(x$cov.unscaled)
}
return(invisible(x))
} |
require(httr)
require(magrittr)
require(stringr)
base_endpoint <- function(server, endpoint) paste(server, "/alfresco/api/-default-/public/", endpoint, sep="")
tickets_endpoint <- function(server) base_endpoint(server, "authentication/versions/1/tickets")
ticket_endpoint <- function(server) paste(tickets_endpoint(server), "-me-", sep="/")
alf_session <- function (server, username, password) {
response <-
tickets_endpoint(server) %>%
POST(body=list(userId = username, password = password), encode = "json")
if (http_error(response))
if (response$status_code == 403) stop("Authentication failed, please check your username and password are correct.")
else stop(http_status(response)$message)
else {
node_endpoint <- function(node_id) base_endpoint(server, "alfresco/versions/1/nodes/") %>% paste(node_id, sep="")
node_content_endpoint <- function(node_id) node_endpoint(node_id) %>% paste("/content", sep="")
node_children_endpoint <- function(node_id) node_endpoint(node_id) %>% paste("/children", sep="")
list(
server = server,
ticket = fromJSON(content(response, "text"), flatten = TRUE)$entry$id,
node_endpoint = node_endpoint,
node_content_endpoint = node_content_endpoint,
node_children_endpoint = node_children_endpoint
)
}
}
alf_session.is_valid <- function (session) {
tryCatch(
if (!is.null(alf_GET(ticket_endpoint(session$server), ticket=session$ticket, params=list(ticket=session$ticket)))) TRUE,
error = function(e) if (str_detect(string=e$message, pattern = "401")) FALSE else stop(e)
)
}
alf_session.invalidate <- function (session) {
tryCatch ({
alf_DELETE(ticket_endpoint(session$server), ticket=session$ticket, params=list(ticket=session$ticket))
TRUE
},
error = function (e) if (str_detect(string=e$message, pattern = "401")) FALSE else stop(e)
) %>%
invisible()
} |
resetJobs = function(reg, ids, force = FALSE) {
checkRegistry(reg, writeable = TRUE)
syncRegistry(reg)
if (missing(ids) || length(ids) == 0L)
return(integer(0L))
ids = checkIds(reg, ids)
assertFlag(force)
if (!force) {
if(is.null(getListJobs()) || is.null(getKillJob())) {
stop("Listing or killing of jobs not supported by your cluster functions\n",
"You need to set force = TRUE to reset jobs, but see the warning in ?resetJobs")
}
running = dbFindOnSystem(reg, ids, limit = 10L)
if (length(running) > 0L)
stopf("Can't reset jobs which are live on system. You have to kill them first!\nIds: %s",
collapse(running))
}
info("Resetting %i jobs in DB.", length(ids))
dbSendMessage(reg, dbMakeMessageKilled(reg, ids), staged = FALSE)
invisible(ids)
} |
test_that("lod() catches bad `aff` input", {
x = nuclearPed(1)
x = setMarkers(x, marker(x))
mod = diseaseModel("AD")
expect_error(lod(x, aff = 1:4, mod = mod), "Invalid `aff`")
expect_error(lod(x, aff = 0:1, mod = mod), "Unknown ID label: 0")
expect_error(lod(x, aff = list(aff = 1), mod = mod), "Invalid name of `aff`")
expect_error(lod(x, aff = list(affected = 1, unaffected = 1), mod = mod),
"Individual with multiple affection statuses")
})
test_that("lod() with liability classes", {
x = nuclearPed(3)
x = setMarkers(x, marker(x, geno = c("1/2", "1/1", "1/2","1/2","1/2")))
mod = diseaseModel("AD", pen = data.frame(f0 = 0, f1 = 1:0, f2 = 1:0))
res = lod(x, aff = c(2,1,2,2,1), mod = mod, liab = c(1,1,1,1,2))
expect_equal(round(res - log10(2), 3), 0)
expect_equal(res, lod(x, aff = c(2,1,2,2,0), mod = diseaseModel("AD")))
}) |
library("plink")
options(prompt = "R> ", continue = "+ ", width = 70,
digits = 4, show.signif.stars = FALSE, useFancyQuotes = FALSE)
x <- matrix(c(
0.844, -1.630, 0.249, NA, NA, NA, NA, NA, NA, NA,
1.222, -0.467, -0.832, 0.832, NA, NA, NA, NA, NA, NA,
1.101, -0.035, -1.404, -0.285, 0.541, 1.147, NA, NA, NA, NA,
1.076, 0.840, 0.164, NA, NA, NA, NA, NA, NA, NA,
0.972, -0.140, 0.137, NA, NA, NA, NA, NA, NA, NA,
0.905, 0.522, -0.469, -0.959, NA, 0.126, -0.206, -0.257, 0.336, NA,
0.828, 0.375, -0.357, -0.079, -0.817, 0.565, 0.865, -1.186, -1.199, 0.993,
1.134, 2.034, 0.022, NA, NA, NA, NA, NA, NA, NA,
0.871, 1.461, -0.279, 0.279, NA, NA, NA, NA, NA, NA),
9, 10, byrow = TRUE)
round(x, 2)
a <- round(matrix(c(
0.844, NA, NA, NA, NA,
1.222, NA, NA, NA, NA,
1.101, NA, NA, NA, NA,
1.076, NA, NA, NA, NA,
0.972, NA, NA, NA, NA,
0.905, 0.522, -0.469, -0.959, NA,
0.828, 0.375, -0.357, -0.079, -0.817,
1.134, NA, NA, NA, NA,
0.871, NA, NA, NA, NA),
9, 5, byrow = TRUE), 2)
b <- round(matrix(c(
-1.630, NA, NA, NA, NA,
-0.467, -0.832, 0.832, NA, NA,
-0.035, -1.404, -0.285, 0.541, 1.147,
0.840, NA, NA, NA, NA,
-0.140, NA, NA, NA, NA,
0.126, -0.206, -0.257, 0.336, NA,
0.565, 0.865, -1.186, -1.199, 0.993,
2.034, NA, NA, NA, NA,
1.461, -0.279, 0.279, NA, NA),
9, 5, byrow = TRUE), 2)
c <- round(c(0.249, NA, NA, 0.164, 0.137, NA, NA, 0.022, NA), 2)
list(a = a, b = b, c = c)
cat <- c(2, 3, 5, 2, 2, 4, 5, 2, 3)
pm <- as.poly.mod(9, c("drm", "grm", "nrm"),
list(c(1, 4, 5, 8), c(2, 3, 9), 6:7))
pm <- as.poly.mod(9, c("grm", "drm", "nrm"),
list(c(2, 3, 9), c(1, 4, 5, 8), 6:7))
pars <- as.irt.pars(x, cat = cat, poly.mod = pm, location = TRUE)
common <- matrix(c(51:60, 1:10), 10, 2)
common
cat <- rep(2, 36)
pm <- as.poly.mod(36)
x <- as.irt.pars(KB04$pars, KB04$common, cat = list(cat, cat),
poly.mod = list(pm, pm), grp.names = c("new", "old"))
out <- plink(x)
summary(out)
out <- plink(x, rescale = "SL", base.grp = 2)
summary(out)
ability <- list(group1 = -4:4, group2 = -4:4)
out <- plink(x, rescale = "SL", ability = ability, base.grp = 2,
weights.t = as.weight(30, normal.wt = TRUE), symmetric = TRUE)
summary(out)
link.ability(out)
pm1 <- as.poly.mod(55, c("drm", "gpcm", "nrm"), dgn$items$group1)
pm2 <- as.poly.mod(55, c("drm", "gpcm", "nrm"), dgn$items$group2)
x <- as.irt.pars(dgn$pars, dgn$common, dgn$cat, list(pm1, pm2))
out <- plink(x)
summary(out)
out1 <- plink(x, exclude = "nrm")
summary(out1, descrip = TRUE)
pm1 <- as.poly.mod(41, c("drm", "gpcm"), reading$items[[1]])
pm2 <- as.poly.mod(70, c("drm", "gpcm"), reading$items[[2]])
pm3 <- as.poly.mod(70, c("drm", "gpcm"), reading$items[[3]])
pm4 <- as.poly.mod(70, c("drm", "gpcm"), reading$items[[4]])
pm5 <- as.poly.mod(72, c("drm", "gpcm"), reading$items[[5]])
pm6 <- as.poly.mod(71, c("drm", "gpcm"), reading$items[[6]])
pm <- list(pm1, pm2, pm3, pm4, pm5, pm6)
grp.names <- c("Grade 3.0", "Grade 4.0", "Grade 4.1", "Grade 5.1",
"Grade 5.2", "Grade 6.2")
x <- as.irt.pars(reading$pars, reading$common, reading$cat, pm,
grp.names = grp.names)
out <- plink(x, method = c("HB", "SL"), base.grp = 4)
summary(out)
dichot <- matrix(c(1.2, -1.1, 0.19, 0.8, 2.1, 0.13), 2, 3, byrow = TRUE)
poly <- t(c(0.64, -1.8, -0.73, 0.45))
mixed.pars <- rbind(cbind(dichot, matrix(NA, 2, 1)), poly)
cat <- c(2, 2, 4)
pm <- as.poly.mod(3, c("drm", "gpcm"), list(1:2, 3))
mixed.pars <- as.irt.pars(mixed.pars, cat = cat, poly.mod = pm)
out <- mixed(mixed.pars, theta = -4:4)
round(get.prob(out), 3)
pm <- as.poly.mod(36)
x <- as.irt.pars(KB04$pars, KB04$common,
cat = list(rep(2, 36), rep(2, 36)), poly.mod = list(pm, pm))
out <- plink(x, rescale = "MS", base.grp = 2, D = 1.7,
exclude = list(27, 27), grp.names = c("new", "old"))
wt <- as.weight(theta = c(-5.21, -4.16, -3.12, -2.07, -1.03, 0.02, 1.06,
2.11, 3.15, 4.20), weight = c(0.0001, 0.0028, 0.0302, 0.1420, 0.3149,
0.3158, 0.1542, 0.0359, 0.0039, 0.0002))
eq.out <- equate(out, method = c("TSE", "OSE"), weights1 = wt,
syn.weights = c(1, 0), D = 1.7)
eq.out$tse[1:10,]
eq.out$ose$scores[1:10,]
pdf.options(family = "Times")
trellis.device(device = "pdf", file = "IRC.pdf")
tmp <- plot(pars, incorrect = TRUE, auto.key = list(space = "right"))
print(tmp)
dev.off()
plot(pars, incorrect = TRUE, auto.key = list(space = "right"))
pm1 <- as.poly.mod(41, c("drm", "gpcm"), reading$items[[1]])
pm2 <- as.poly.mod(70, c("drm", "gpcm"), reading$items[[2]])
pm3 <- as.poly.mod(70, c("drm", "gpcm"), reading$items[[3]])
pm4 <- as.poly.mod(70, c("drm", "gpcm"), reading$items[[4]])
pm5 <- as.poly.mod(72, c("drm", "gpcm"), reading$items[[5]])
pm6 <- as.poly.mod(71, c("drm", "gpcm"), reading$items[[6]])
pm <- list(pm1, pm2, pm3, pm4, pm5, pm6)
grp.names <- c("Grade 3.0", "Grade 4.0", "Grade 4.1", "Grade 5.1", "Grade 5.2", "Grade 6.2")
x <- as.irt.pars(reading$pars, reading$common, reading$cat, pm)
out <- plink(x, method = "SL",rescale = "SL", base.grp = 4, grp.names = grp.names)
pdf.options(family="Times")
pdf("drift_a.pdf", 4, 4.2)
plot(out, drift = "a", sep.mod = TRUE, groups = 4, drift.sd = 2)
dev.off()
pdf.options(family="Times")
pdf("drift_b.pdf", 4, 4.2)
plot(out, drift = "b", sep.mod = TRUE, groups = 4, drift.sd = 2)
dev.off()
pdf.options(family="Times")
pdf("drift_c.pdf", 4, 4.2)
plot(out, drift = "c", sep.mod = TRUE, groups = 4, drift.sd = 2)
dev.off()
plot(out, drift = "pars", sep.mod = TRUE, groups = 4, drift.sd = 2) |
gg_rf <- function(df, vble, fitted, res,
cen_obs = FALSE,
cen_obs_label = "Centered observed values",
cen_fit_label = "Centered fitted values",
res_label = "Residuals",
xlabel = expression(f[i]),
ylabel = quo_text(vble),
...) {
if (!is.data.frame(df)) stop("The object provided in the argument df is not a data.frame")
vble <- enquo(vble)
fitted <- enquo(fitted)
res <- enquo(res)
if (!is.numeric(eval_tidy(vble, df)))
stop(paste(quo_text(vble), "provided for the vble argument is not a numeric variable"))
if (!is.numeric(eval_tidy(fitted, df)))
stop(paste(quo_text(fitted), "provided for the fitted argument is not a numeric variable"))
if (!is.numeric(eval_tidy(res, df)))
stop(paste(quo_text(res), "provided for the res argument is not a numeric variable"))
if (!is.logical(cen_obs)) stop("Argument cen_obs must be either TRUE or FALSE")
df <-
df %>%
ungroup() %>%
mutate(
centered_observed_values = !!vble - mean(!!vble),
centered_fitted_values = !!fitted - mean(!!fitted)
) %>%
tidyr::pivot_longer(
cols = c(.data$centered_observed_values, .data$centered_fitted_values, !!res),
names_to = "tipo", values_to = "valor"
) %>%
mutate(tipo = factor(.data$tipo,
levels = c("centered_observed_values", "centered_fitted_values", quo_text(res)),
labels = c(cen_obs_label, cen_fit_label, res_label))
)
if (!cen_obs) {
df <- filter(df, .data$tipo != cen_obs_label)
}
g <- ggplot(df, aes(sample = .data$valor)) +
stat_qq(distribution = qunif, ...) +
facet_wrap(~ .data$tipo) +
xlab(xlabel) + ylab(ylabel)
return(g)
} |
"spatialSign" <- function(x, ...)
UseMethod("spatialSign")
"spatialSign.default" <- function(x, na.rm = TRUE, ...) {
if (is.character(x) | is.factor(x))
stop("spatial sign is not defined for character or factor data",
call. = FALSE)
denom <- sum(x ^ 2, na.rm = na.rm)
out <-
if (sqrt(denom) > .Machine$double.eps)
x / sqrt(denom)
else
x * 0
out
}
"spatialSign.matrix" <- function(x, na.rm = TRUE, ...) {
if (is.character(x))
stop("spatial sign is not defined for character data",
call. = FALSE)
xNames <- dimnames(x)
p <- ncol(x)
tmp <- t(apply(x, 1, spatialSign.default, na.rm = na.rm))
if (p == 1 & nrow(tmp) == 1)
tmp <- t(tmp)
dimnames(tmp) <- xNames
tmp
}
"spatialSign.data.frame" <- function(x, na.rm = TRUE, ...) {
if (any(apply(x, 2, function(data)
is.character(data) | is.factor(data))))
stop("spatial sign is not defined for character or factor data",
call. = FALSE)
xNames <- dimnames(x)
x <- as.matrix(x)
if (!is.numeric(x))
stop("a character matrix was the result of as.matrix",
call. = FALSE)
tmp <- spatialSign(x, na.rm = na.rm)
dimnames(tmp) <- xNames
tmp
} |
getSSMBowlingDetails <- function(dir='.',odir=".") {
bowlingDetails=bowler=wickets=economyRate=matches=meanWickets=meanER=totalWickets=NULL
currDir= getwd()
teams <-c("Auckland", "Canterbury", "Central Districts",
"Northern Districts", "Otago", "Wellington")
details=df=NULL
teams1 <- NULL
for(team in teams){
print(team)
tryCatch({
bowling <- getTeamBowlingDetails(team,dir=dir, save=TRUE,odir=odir)
teams1 <- c(teams1,team)
},
error = function(e) {
print("No data")
}
)
}
} |
gh_encode = function(latitude, longitude, precision = 6L) {
if (length(precision) != 1L)
stop("More than one precision value detected; precision is fixed on input (for now)")
if (precision < 1L) stop('Invalid precision. Precision is measured in ',
'number of characters, must be at least 1.')
if (precision > .global$GH_MAX_PRECISION) {
warning('Precision is limited to ', .global$GH_MAX_PRECISION,
' characters; truncating')
precision = .global$GH_MAX_PRECISION
}
.Call(Cgh_encode, latitude, longitude, as.integer(precision))
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.