code
stringlengths 1
13.8M
|
---|
get_committee_leadership <- function(cycle=2018, page = 1, myAPI_Key){
API = 'campaign-finance'
if(!validate_cycle(cycle))
stop("Incorrect cycle")
query <- sprintf("%s/committees/leadership.json", cycle)
pp_query(query, API, page = page, myAPI_Key = myAPI_Key)
}
|
mapdeckScatterplotDependency <- function() {
list(
createHtmlDependency(
name = "scatterplot",
version = "1.0.0",
src = system.file("htmlwidgets/lib/scatterplot", package = "mapdeck"),
script = c("scatterplot.js"),
all_files = FALSE
)
)
}
add_scatterplot <- function(
map,
data = get_map_data(map),
lon = NULL,
lat = NULL,
polyline = NULL,
radius = NULL,
radius_min_pixels = 1,
radius_max_pixels = NULL,
fill_colour = NULL,
fill_opacity = NULL,
stroke_colour = NULL,
stroke_width = NULL,
stroke_opacity = NULL,
tooltip = NULL,
auto_highlight = FALSE,
highlight_colour = "
layer_id = NULL,
id = NULL,
palette = "viridis",
na_colour = "
legend = FALSE,
legend_options = NULL,
legend_format = NULL,
digits = 6,
update_view = TRUE,
focus_layer = FALSE,
transitions = NULL,
brush_radius = NULL
) {
if( !is.null( fill_colour ) ) {
fill_colour <- appendAlpha( fill_colour )
}
if( !is.null( stroke_colour ) ) {
stroke_colour <- appendAlpha( stroke_colour )
}
l <- list()
l[["lon"]] <- force(lon)
l[["lat"]] <- force(lat)
l[["polyline"]] <- force(polyline)
l[["radius"]] <- force(radius)
l[["fill_colour"]] <- force(fill_colour)
l[["fill_opacity"]] <- resolve_opacity(fill_opacity)
l[["stroke_colour"]] <- force( stroke_colour)
l[["stroke_opacity"]] <- force( stroke_opacity )
l[["stroke_width"]] <- force( stroke_width )
l[["tooltip"]] <- force(tooltip)
l[["id"]] <- force(id)
l[["na_colour"]] <- force(na_colour)
l <- resolve_palette( l, palette )
l <- resolve_legend( l, legend )
l <- resolve_legend_options( l, legend_options )
l <- resolve_data( data, l, c( "POINT") )
bbox <- init_bbox()
update_view <- force( update_view )
focus_layer <- force( focus_layer )
if ( !is.null(l[["data"]]) ) {
data <- l[["data"]]
l[["data"]] <- NULL
}
if( !is.null(l[["bbox"]] ) ) {
bbox <- l[["bbox"]]
l[["bbox"]] <- NULL
}
layer_id <- layerId(layer_id, "scatterplot")
checkHexAlpha(highlight_colour)
map <- addDependency(map, mapdeckScatterplotDependency())
tp <- l[["data_type"]]
l[["data_type"]] <- NULL
jsfunc <- "add_scatterplot_geo_columnar"
map <- addDependency(map, mapdeckScatterplotDependency())
if ( tp == "sf" ) {
geometry_column <- list( geometry = c("lon","lat") )
l[["geometry"]] <- NULL
shape <- rcpp_point_sf_columnar( data, l, geometry_column, digits, "scatterplot" )
} else if ( tp == "df" ) {
geometry_column <- list( geometry = c("lon", "lat") )
shape <- rcpp_point_df_columnar( data, l, geometry_column, digits, "scatterplot" )
} else if ( tp == "sfencoded" ) {
geometry_column <- c( "polyline" )
shape <- rcpp_point_polyline( data, l, geometry_column, "scatterplot" )
}
js_transitions <- resolve_transitions( transitions, "scatterplot" )
if( inherits( legend, "json" ) ) {
shape[["legend"]] <- legend
legend_format <- "hex"
} else {
shape[["legend"]] <- resolve_legend_format( shape[["legend"]], legend_format )
legend_format <- "rgb"
}
invoke_method(
map, jsfunc, map_type( map ), shape[["data"]], nrow(data) , layer_id, auto_highlight, highlight_colour,
shape[["legend"]], legend_format, bbox, update_view, focus_layer, js_transitions,
radius_min_pixels, radius_max_pixels, brush_radius
)
}
clear_scatterplot <- function( map, layer_id = NULL, update_view = TRUE ) {
layer_id <- layerId(layer_id, "scatterplot")
invoke_method(map, "md_layer_clear", map_type( map ), layer_id, "scatterplot", update_view )
}
|
NULL
NULL
NULL
NULL
add_aks_methods <- function()
{
az_resource_group$set("public", "create_aks", overwrite=TRUE,
function(name, location=self$location,
dns_prefix=name, kubernetes_version=NULL,
login_user="", login_passkey="",
enable_rbac=FALSE, agent_pools=agent_pool("pool1", 3),
cluster_service_principal=NULL,
managed_identity=TRUE, private_cluster=FALSE,
properties=list(), ..., wait=TRUE)
{
if(is_empty(kubernetes_version))
kubernetes_version <- tail(self$list_kubernetes_versions(), 1)
if(managed_identity)
{
identity <- list(type="systemAssigned")
sp_profile <- NULL
}
else
{
identity <- NULL
find_app_creds <- get("find_app_creds", getNamespace("AzureContainers"))
cluster_service_principal <- find_app_creds(cluster_service_principal, name, location, self$token)
if(is.null(cluster_service_principal[[2]]))
stop("Must provide a service principal with a secret password", call.=FALSE)
sp_profile <- list(
clientId=cluster_service_principal[[1]],
secret=cluster_service_principal[[2]]
)
}
if(inherits(agent_pools, "agent_pool"))
agent_pools <- list(unclass(agent_pools))
else if(is.list(agent_pools) && all(sapply(agent_pools, inherits, "agent_pool")))
agent_pools <- lapply(agent_pools, unclass)
agent_pools[[1]]$mode <- "System"
props <- list(
kubernetesVersion=kubernetes_version,
dnsPrefix=dns_prefix,
agentPoolProfiles=agent_pools,
enableRBAC=enable_rbac
)
if(private_cluster)
{
props$apiServerAccessProfile <- list(enablePrivateCluster=private_cluster)
props$networkProfile <- list(loadBalancerSku="standard")
}
if(!is.null(sp_profile))
props$servicePrincipalProfile <- sp_profile
if(login_user != "" && login_passkey != "")
props$linuxProfile <- list(
adminUsername=login_user,
ssh=list(publicKeys=list(list(Keydata=login_passkey)))
)
props <- utils::modifyList(props, properties)
for(i in 1:20)
{
res <- tryCatch(AzureContainers::aks$new(self$token, self$subscription, self$name,
type="Microsoft.ContainerService/managedClusters", name=name, location=location,
properties=props, identity=identity, ..., wait=wait), error=function(e) e)
if(!(inherits(res, "error") &&
grepl("Service principal|ServicePrincipal", res$message)))
break
Sys.sleep(5)
}
if(inherits(res, "error"))
{
class(res) <- c("simpleError", "error", "condition")
stop(res)
}
res
})
az_resource_group$set("public", "get_aks", overwrite=TRUE,
function(name)
{
AzureContainers::aks$new(self$token, self$subscription, self$name,
type="Microsoft.ContainerService/managedClusters", name=name)
})
az_resource_group$set("public", "delete_aks", overwrite=TRUE,
function(name, confirm=TRUE, wait=FALSE)
{
self$get_aks(name)$delete(confirm=confirm, wait=wait)
})
az_resource_group$set("public", "list_aks", overwrite=TRUE,
function()
{
provider <- "Microsoft.ContainerService"
path <- "managedClusters"
api_version <- az_subscription$
new(self$token, self$subscription)$
get_provider_api_version(provider, path)
op <- file.path("resourceGroups", self$name, "providers", provider, path)
cont <- call_azure_rm(self$token, self$subscription, op, api_version=api_version)
lst <- lapply(cont$value,
function(parms) AzureContainers::aks$new(self$token, self$subscription, deployed_properties=parms))
while(!is_empty(cont$nextLink))
{
cont <- call_azure_url(self$token, cont$nextLink)
lst <- lapply(cont$value,
function(parms) AzureContainers::aks$new(self$token, self$subscription, deployed_properties=parms))
}
named_list(lst)
})
az_resource_group$set("public", "list_kubernetes_versions", overwrite=TRUE,
function()
{
az_subscription$
new(self$token, self$subscription)$
list_kubernetes_versions(self$location)
})
az_subscription$set("public", "list_aks", overwrite=TRUE,
function()
{
provider <- "Microsoft.ContainerService"
path <- "managedClusters"
api_version <- self$get_provider_api_version(provider, path)
op <- file.path("providers", provider, path)
cont <- call_azure_rm(self$token, self$id, op, api_version=api_version)
lst <- lapply(cont$value,
function(parms) AzureContainers::aks$new(self$token, self$id, deployed_properties=parms))
while(!is_empty(cont$nextLink))
{
cont <- call_azure_url(self$token, cont$nextLink)
lst <- lapply(cont$value,
function(parms) AzureContainers::aks$new(self$token, self$id, deployed_properties=parms))
}
named_list(lst)
})
az_subscription$set("public", "list_kubernetes_versions", overwrite=TRUE,
function(location)
{
api_version <- self$get_provider_api_version("Microsoft.ContainerService", "locations/orchestrators")
op <- file.path("providers/Microsoft.ContainerService/locations", location, "orchestrators")
res <- call_azure_rm(self$token, self$id, op,
options=list(`resource-type`="managedClusters"),
api_version=api_version)
sapply(res$properties$orchestrators, `[[`, "orchestratorVersion")
})
}
find_app_creds <- function(credlist, name, location, token)
{
creds <- if(is.null(credlist))
{
gr <- graph_login(token$tenant)
message("Creating cluster service principal")
appname <- paste("RAKSapp", name, location, sep="-")
app <- gr$create_app(appname)
message("Waiting for Resource Manager to sync with Graph")
list(app$properties$appId, app$password)
}
else if(inherits(credlist, "az_app"))
list(credlist$properties$appId, credlist$password)
else if(length(credlist) == 2)
list(credlist[[1]], credlist[[2]])
if(is_empty(creds) || length(creds) < 2 || is_empty(creds[[2]]))
stop("Invalid service principal credentials: must supply app ID and password")
creds
}
|
forecast_with_cpi <- function(model, h) {
pr <- forecast(model, h)
dframe <- data.frame(
"Predicted_ts_value" = as.numeric(pr$mean),
"cpi_80_lower" = as.numeric(pr$lower[, 1]),
"cpi_80_upper" = as.numeric(pr$upper[, 1]),
"cpi_95_lower" = as.numeric(pr$lower[, 2]),
"cpi_95_upper" = as.numeric(pr$upper[, 2])
)
return(dframe)
}
expect_equal_df <- function(z_pred, r_pred) {
z_pred <- z_pred[c(
"Predicted_ts_value", "cpi_80_lower",
"cpi_80_upper", "cpi_95_lower", "cpi_95_upper"
)]
expect_equal_nn(z_pred, r_pred)
}
expect_equal_df_2 <- function(z_pred_out, r_pred) {
z_pred_out <- z_pred_out[NROW(z_pred_out), ]
z_pred_out <- z_pred_out[names(r_pred)]
z_pred_transf <- data.frame(matrix(NA,
nrow = NCOL(z_pred_out[[1]]),
ncol = NCOL(r_pred)
),
stringsAsFactors = TRUE
)
colnames(z_pred_transf) <- names(r_pred)
for (x in names(r_pred)) {
z_pred_transf[x] <- as.numeric(t(z_pred_out[[x]]))
}
expect_equal_nn(z_pred_transf, r_pred)
}
expect_equal_df_3 <- function(z_pred_out, r_pred) {
z_pred_out <- z_pred_out[names(r_pred)]
z_order <- order(as.numeric(names(z_pred_out$Predicted_ts_value)))
z_pred_transf <- data.frame(matrix(NA,
nrow = NCOL(z_pred_out[[1]]),
ncol = NCOL(r_pred)
),
stringsAsFactors = TRUE
)
colnames(z_pred_transf) <- names(r_pred)
for (x in names(r_pred)) {
z_row <- z_pred_out[[x]]
z_row <- z_row[, z_order]
z_pred_transf[x] <- as.numeric(t(z_row))
}
expect_equal_nn(z_pred_transf, r_pred)
}
expect_equal_nn <- function(...) {
expect_equal(..., check.names = FALSE)
}
expect_equal_sorted <- function(z_pred_val, r_pred) {
z_order <- order(as.numeric(names(z_pred_val)))
z_pred_val <- z_pred_val[z_order]
expect_equal_nn(as.numeric(z_pred_val), r_pred)
}
single_col_h_df <- function(h) {
dframe <- data.frame("h" = c(1:h), stringsAsFactors = TRUE)
return(dframe)
}
h_20 <- single_col_h_df(20)
h_20_one_line <- data.frame("h" = c(20))
test_that("TimeSeriesModel/forecast PMML output matches R for non-seasonal and ts_type='arima'", {
skip_on_cran()
skip_on_ci()
skip_if_not_installed("zementisr")
skip_if_not_installed("forecast")
library(zementisr)
library(forecast)
fit <- auto.arima(sunspots)
p_fit <- pmml(fit, model_name = "arima_auto_01", ts_type = "arima")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_2(z_pred$outputs, r_pred)
fit <- Arima(AirPassengers, order = c(2, 1, 2))
p_fit <- pmml(fit, model_name = "arima_212", ts_type = "arima")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_2(z_pred$outputs, r_pred)
fit <- Arima(AirPassengers, order = c(1, 1, 1))
p_fit <- pmml(fit, model_name = "arima_111", ts_type = "arima")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_2(z_pred$outputs, r_pred)
fit <- Arima(WWWusage, order = c(2, 0, 2))
p_fit <- pmml(fit, model_name = "arima_202", ts_type = "arima")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_2(z_pred$outputs, r_pred)
fit <- Arima(USAccDeaths, order = c(1, 2, 0))
p_fit <- pmml(fit,
model_name = "arima_120", ts_type = "arima",
model_version = "arima_120_v1"
)
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_2(z_pred$outputs, r_pred)
fit <- Arima(AirPassengers, order = c(2, 2, 2))
p_fit <- pmml(fit,
model_name = "arima_222", ts_type = "arima",
model_version = NULL
)
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20, up_stat$model_name)
delete_model(up_stat$model_name)
expect_failure(expect_equal_df_2(z_pred$outputs, r_pred))
fit <- Arima(USAccDeaths, order = c(1, 2, 3))
p_fit <- pmml(fit, model_name = "arima_123", ts_type = "arima")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20, up_stat$model_name)
delete_model(up_stat$model_name)
expect_failure(expect_equal_df_2(z_pred$outputs, r_pred))
})
test_that("TimeSeriesModel/forecast PMML output matches R for seasonal,ts_type='arima'", {
skip_on_cran()
skip_on_ci()
skip_if_not_installed("zementisr")
skip_if_not_installed("forecast")
library(zementisr)
library(forecast)
fit <- auto.arima(JohnsonJohnson)
p_fit <- pmml(fit, model_name = "arima_auto_02", ts_type = "arima")
r_pred <- as.numeric(forecast(fit, h = 20)$mean)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_sorted(z_pred$outputs$Predicted_ts_value, r_pred)
fit <- Arima(JohnsonJohnson, order = c(1, 1, 0), seasonal = c(0, 1, 1))
p_fit <- pmml(fit, model_name = "arima_110011", ts_type = "arima")
r_pred <- as.numeric(forecast(fit, h = 20)$mean)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_sorted(z_pred$outputs$Predicted_ts_value, r_pred)
fit <- Arima(JohnsonJohnson, order = c(0, 1, 0), seasonal = c(0, 1, 0))
p_fit <- pmml(fit, model_name = "arima_010010", ts_type = "arima")
r_pred <- as.numeric(forecast(fit, h = 20)$mean)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_sorted(z_pred$outputs$Predicted_ts_value, r_pred)
fit <- Arima(JohnsonJohnson, order = c(0, 1, 0), seasonal = c(0, 1, 2))
p_fit <- pmml(fit, model_name = "arima_010012", ts_type = "arima")
r_pred <- as.numeric(forecast(fit, h = 20)$mean)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_sorted(z_pred$outputs$Predicted_ts_value, r_pred)
fit <- Arima(AirPassengers, order = c(0, 1, 1), seasonal = c(0, 1, 1))
p_fit <- pmml(fit, model_name = "arima_011011", ts_type = "arima")
r_pred <- as.numeric(forecast(fit, h = 20)$mean)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_sorted(z_pred$outputs$Predicted_ts_value, r_pred)
fit <- Arima(JohnsonJohnson, order = c(1, 1, 1), seasonal = c(1, 1, 1))
p_fit <- pmml(fit, model_name = "arima_111111", ts_type = "arima")
r_pred <- as.numeric(forecast(fit, h = 20)$mean)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_sorted(z_pred$outputs$Predicted_ts_value, r_pred)
fit <- Arima(JohnsonJohnson, order = c(0, 0, 1), seasonal = c(0, 1, 0))
p_fit <- pmml(fit, model_name = "arima_001010", ts_type = "arima")
r_pred <- as.numeric(forecast(fit, h = 20)$mean)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_sorted(z_pred$outputs$Predicted_ts_value, r_pred)
fit <- Arima(sunspots, order = c(1, 0, 0), seasonal = c(1, 0, 0))
p_fit <- pmml(fit, model_name = "arima_100100", ts_type = "arima")
r_pred <- as.numeric(forecast(fit, h = 20)$mean)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_sorted(z_pred$outputs$Predicted_ts_value, r_pred)
fit <- Arima(JohnsonJohnson, order = c(1, 1, 0), seasonal = c(0, 0, 1))
p_fit <- pmml(fit, model_name = "arima_110001", ts_type = "arima")
r_pred <- as.numeric(forecast(fit, h = 20)$mean)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_failure(expect_equal_sorted(z_pred$outputs$Predicted_ts_value, r_pred))
})
test_that("TimeSeriesModel/forecast PMML output matches R for statespace representation", {
skip_on_cran()
skip_on_ci()
skip_if_not_installed("zementisr")
skip_if_not_installed("forecast")
library(zementisr)
library(forecast)
fit <- auto.arima(JohnsonJohnson)
p_fit <- pmml(fit, model_name = "arima_auto_02_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(AirPassengers, order = c(2, 1, 2))
p_fit <- pmml(fit, model_name = "arima_212_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(WWWusage, order = c(2, 0, 2))
p_fit <- pmml(fit, model_name = "arima_202_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(AirPassengers, order = c(2, 2, 2))
p_fit <- pmml(fit,
model_name = "arima_222_ss", ts_type = "statespace",
model_version = "arima_222_ss_0001"
)
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(USAccDeaths, order = c(1, 2, 3))
p_fit <- pmml(fit, model_name = "arima_123_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(JohnsonJohnson, order = c(1, 1, 0), seasonal = c(0, 1, 1))
p_fit <- pmml(fit, model_name = "arima_110011_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(AirPassengers, order = c(0, 1, 1), seasonal = c(0, 1, 1))
p_fit <- pmml(fit, model_name = "arima_011011_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(JohnsonJohnson, order = c(1, 1, 1), seasonal = c(1, 1, 1))
p_fit <- pmml(fit, model_name = "arima_111111_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(JohnsonJohnson, order = c(0, 0, 1), seasonal = c(0, 1, 0))
p_fit <- pmml(fit, model_name = "arima_001010_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(sunspots, order = c(1, 0, 0), seasonal = c(1, 0, 0))
p_fit <- pmml(fit, model_name = "arima_100100_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(JohnsonJohnson, order = c(1, 1, 0), seasonal = c(0, 0, 1))
p_fit <- pmml(fit, model_name = "arima_110001_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(JohnsonJohnson, order = c(1, 1, 0), seasonal = c(0, 0, 1))
p_fit <- pmml(fit, model_name = "arima_110001_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(JohnsonJohnson, order = c(4, 1, 4), seasonal = c(1, 1, 1))
p_fit <- pmml(fit, model_name = "arima_414111_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(USAccDeaths, order = c(2, 1, 1), seasonal = c(2, 1, 4))
p_fit <- pmml(fit, model_name = "arima_211214_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(USAccDeaths, order = c(2, 2, 3), seasonal = c(0, 1, 1))
p_fit <- pmml(fit, model_name = "arima_223011_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(USAccDeaths, order = c(2, 0, 0), seasonal = c(2, 0, 0))
p_fit <- pmml(fit, model_name = "arima_200200_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(WWWusage, order = c(3, 0, 3), seasonal = c(3, 0, 3))
p_fit <- pmml(fit, model_name = "arima_303303_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(JohnsonJohnson, order = c(0, 0, 4), seasonal = c(0, 2, 4))
p_fit <- pmml(fit, model_name = "arima_004024_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
fit <- Arima(JohnsonJohnson, order = c(0, 0, 0), seasonal = c(0, 2, 4))
p_fit <- pmml(fit, model_name = "arima_000024_ss", ts_type = "statespace")
r_pred <- forecast_with_cpi(fit, 20)
up_stat <- upload_model(p_fit)
z_pred <- predict_pmml_batch(h_20_one_line, up_stat$model_name)
delete_model(up_stat$model_name)
expect_equal_df_3(z_pred$outputs, r_pred)
})
|
NULL
.gwindow.guiWidgetsToolkittcltk <- function(toolkit, title, visible=visible, name, width, height, parent, handler, action, ...) {
GWindow$new(toolkit, title, visible=visible, name, width, height, parent, handler, action, ...)
}
GWindow <- setRefClass("GWindow",
contains="GContainer",
fields=list(
frame="ANY",
menubar_area="ANY",
toolbar_area="ANY",
infobar_area="ANY",
content_area="ANY",
statusbar_area="ANY",
statusbar_widget="ANY",
modal_flag="ANY"
),
methods=list(
initialize=function(toolkit=NULL, title="", visible=TRUE, name=NULL, width=NULL, height=NULL,
parent=NULL, handler, action, ...) {
tclServiceMode(FALSE)
block <<- tktoplevel()
set_value(title)
tkwm.state(block,"withdrawn")
frame <<- ttkframe(block)
if(is.null(width))
width <- 400L
if(is.null(height))
height <- as.integer(0.7 * width)
if(!is.null(parent)) {
set_location(parent)
if(is(parent, "GWindow")) {
add_handler_destroy(parent, function(h,...) {
dispose_window()
})
}
}
initFields(toolkit=toolkit,
menubar_area=ttkframe(block),
toolbar_area=ttkframe(block),
infobar_area=ttkframe(block),
content_area=ttkframe(block,
padding=ifelse(is_aqua(), c(0, 6, 14, 4), c(0,6, 0, 4))
),
statusbar_area=ttkframe(block),
modal_flag=tclVar(FALSE)
)
widget <<- content_area
tkconfigure(statusbar_area, borderwidth = 1, relief="sunken")
layout_widget()
tkbind(block, "<Unmap>", function() tkgrab.release(block))
add_handler_changed(handler, action)
set_size(c(width, height))
tclServiceMode(TRUE)
set_visible(visible)
callSuper(...)
},
layout_widget = function() {
tkgrid(toolbar_area, row=0, column = 0, sticky = "nswe")
tkgrid(menubar_area, row=1, column = 0, sticky = "nswe")
tkgrid(infobar_area, row=2, column = 0, sticky = "nswe")
tkgrid(content_area, row=3, column = 0, sticky = "nswe")
tkgrid(statusbar_area, row=4, column = 0, sticky = "we")
tkgrid.columnconfigure(block, 0, weight = 1)
tkgrid.rowconfigure(block, 3, weight = 1)
tkgrid.propagate(content_area, FALSE)
},
is_ttkwidget=function() {
FALSE
},
set_location=function(location) {
"Locate window based on other. If location is a widget, make transient. Else location can be (x,y) pair of pixel counts"
if(is(location, "GComponent"))
location <- location$get_widget()
if(is(location, "tkwin")) {
pos <- sapply(c("rootx", "rooty"), function(i) {
as.numeric(tkwinfo(i, location))
})
tkwm.geometry(block, sprintf("+%s+%s", pos[1] + 30, pos[2] + 30))
tkwm.transient(block, location)
tkbind(location, "<Destroy>",function(...) tkdestroy(block))
tkbind(location, "<Unmap>",function(...) tkdestroy(block))
} else if(is.numeric(location)) {
pos <- rep(location, 2)
tkwm.geometry(block, sprintf("+%s+%s", pos[1] + 30, pos[2] + 30))
}
},
set_modal=function(value) {
"Set or release modal"
if(value) {
tkwm.protocol(block, "WM_DELETE_WINDOW", function() {
tkgrab.release(block)
dispose_window()
})
tkwait.window(block)
} else {
tkgrab.release(block)
}
},
get_value = function(...) tclvalue(tktitle(block)),
set_value = function(value, ...) {
tktitle(block) <<- paste(value, collapse=" ")
},
set_focus = function(value) {
if(value)
tkraise(block)
},
set_visible=function(value) {
tkwm.state(block, ifelse(value, "normal", "withdrawn"))
},
set_size = function(value) {
tkwm.minsize(block, value[1], value[2])
},
update_widget=function(...) {
tkwm.geometry(block, "")
invisible()
},
set_icon=function(stock) {
icon <- getStockIconByName(stock)
if(icon != "")
tcl("wm", "iconphoto", block, default=icon)
},
add_child=function(child, ...) {
if(missing(child) || is.null(child))
return()
if(is(child, "GMenuBar")) {
add_menubar(child)
} else if(is(child, "GToolBar")) {
add_toolbar(child)
} else if(is(child, "GStatusBar")) {
add_statusbar(child)
} else {
sapply(as.character(tkwinfo("children", content_area)), tkpack.forget)
children <<- list()
if(is(child, "GComponent")) {
tkpack(child$block, expand=TRUE, fill="both")
child_bookkeeping(child)
} else {
tkpack(child, expand=TRUE, fill="both")
}
update_widget()
}
},
remove_child=function(child) {
if(is(child, "GComponent")) {
child$set_parent(NULL)
tkpack.forget(child$block)
} else {
tkpack.forget(child)
}
},
dispose_window = function() {
"close window"
tcl("after", 5, function() {
tkdestroy(block)
})
},
add_menubar=function(child, ...) {
XXX("")
},
add_toolbar=function(child, ...) {
XXX("")
},
set_infobar=function(msg, ...) {
.Tcl("ttk::style configure InfoBar.TLabel -background red")
infobar <- ttkframe(infobar_area, padding=c(0,0,0,0))
label <- ttklabel(infobar, text=paste(msg, collapse=" "), style="InfoBar.TLabel")
tkpack(label, side="left", expand=TRUE, fill="x")
tkpack(infobar, expand=TRUE, fill="x", side="left")
remove_infobar <- function() {
tkpack.forget(infobar)
tkconfigure(infobar_area, height=1)
}
tkbind(label, "<Motion>", remove_infobar)
timer <- GTimer$new(ms=4*1000,
FUN=function(...) {
remove_infobar()
},
one.shot=TRUE,
toolkit=NULL,
start=TRUE)
},
add_handler_changed=function(handler, action=NULL, ...) {
add_handler_destroy(handler, action, ...)
},
add_handler_destroy=function(handler, action=NULL, ...) {
"window manager delete event"
add_handler("<Destroy>", handler, action=action, ...)
},
add_handler_unrealize=function(handler, action, ...) {
"Intercept window manager delete event"
h <- list(obj=.self, action=action)
tkwm.protocol(block, "WM_DELETE_WINDOW",
function(...) {
val <- handler(h,...)
if(is.null(val) ||
(is.logical(val) && !val)
)
tkdestroy(block)
})
}
))
|
setClass(Class = "TreeType",
slots = c("replace" = "logical",
"randomSplit" = "numeric",
"ERT" = "logical",
"uniformSplit" = "logical",
"splitRule" = "character",
"tieMethod" = "character"))
.treeType <- function(ERT,
nSamples,
uniformSplit,
replace,
splitRule,
tieMethod,
randomSplit,
criticalValue) {
ERT <- .VerifyERT(ERT = ERT)
randomSplit <- .VerifyRandomSplit(randomSplit = randomSplit)
uniformSplit <- .VerifyUniformSplit(uniformSplit = uniformSplit, ERT = ERT)
replace <- .VerifyReplace(replace = replace, ERT = ERT)
splitRule <- .VerifySplitRule(splitRule = splitRule,
criticalValue = criticalValue)
tieMethod <- .VerifyTieMethod(tieMethod = tieMethod)
return( new(Class = "TreeType",
"replace" = replace,
"randomSplit" = randomSplit,
"ERT" = ERT,
"uniformSplit" = uniformSplit,
"splitRule" = splitRule,
"tieMethod" = tieMethod) )
}
|
dBeta_ab <-function(x, shape1=2, shape2=3, a = 0, b=1, params = list(shape1, shape2, a, b),...){
if(!missing(params)){
shape1 <- params$shape1
shape2 <- params$shape2
a <- params$a
b <- params$b
}
out <- (x>=a & x<=b) * dbeta((x-a)/(b-a),shape1,shape2)/(b-a)
return(out)
}
pBeta_ab <- function(q, shape1=2, shape2=3, a = 0, b=1, params = list(shape1=2, shape2 = 5, a = 0, b = 1),...){
if(!missing(params)){
shape1 <- params$shape1
shape2 <- params$shape2
a <- params$a
b <- params$b
}
out <- pbeta((q-a)/(b-a),shape1,shape2)
return(out)
}
qBeta_ab <- function(p, shape1=2, shape2=3, a = 0, b=1, params = list(shape1=2, shape2 = 5, a = 0, b = 1),...){
if(!missing(params)){
shape1 <- params$shape1
shape2 <- params$shape2
a <- params$a
b <- params$b
}
out <- (b-a)*qbeta(p,shape1,shape2) + a
return(out)
}
rBeta_ab <- function(n, shape1=2, shape2=3, a = 0, b = 1, params = list(shape1, shape2, a, b),...){
if(!missing(params)){
shape1 <- params$shape1
shape2 <- params$shape2
a <- params$a
b <- params$b
}
X <- rbeta(n,shape1,shape2)
out <- (b-a)*X + a
return(out)
}
eBeta_ab <- function(X,w, method ="numerical.MLE",...){
n <- length(X)
if(missing(w)){
w <- rep(1,n)
} else {
w <- n*w/sum(w)
}
{
if(method != "numerical.MLE") warning(paste("method ", method, " is not avaliable, use numerial.MLE instead."))
method = "numerical.MLE"
d <- max(X)-min(X)
est.par <- wmle(X=X, w=w, distname = "Beta_ab",
initial=list(shape1=3,shape2=3,a=min(X)-0.1*d,b=max(X)+0.1*d),
lower=list(shape1=1,shape2=1,a=-Inf,b=max(X)),
upper=list(shape1=Inf,shape2=Inf,a=min(X),b=Inf))
est.par.se <- try(sqrt(diag(solve(attributes(est.par)$nll.hessian))),silent=TRUE)
if(class(est.par.se) == "try-error") {
est.par.se <- rep(NA, length(est.par))
}
}
attributes(est.par)$ob <- X
attributes(est.par)$weights <- w
attributes(est.par)$distname <- "Beta_ab"
attributes(est.par)$method <- method
attributes(est.par)$par.name <- c("shape1","shape2","a","b")
attributes(est.par)$par.type <- c("shape","shape","boundary","boundary")
attributes(est.par)$par.vals <- c(est.par$shape1, est.par$shape2, est.par$a, est.par$b)
attributes(est.par)$par.s.e <- est.par.se
class(est.par) <- "eDist"
return(est.par)
}
lBeta_ab <- function(X, w, shape1=2, shape2 =3, a = 0, b = 1, params = list(shape1, shape2, a, b), logL = TRUE,...){
if(!missing(params)){
shape1 <- params$shape1
shape2 <- params$shape2
a <- params$a
b <- params$b
}
n <- length(X)
if(missing(w)){
w <- rep(1,n)
} else {
w <- n*w/sum(w)
}
ll <- sum(w*log(dBeta_ab(x=X,params = params)))
l <- exp(ll)
if(logL) {return(ll)} else{return(l)}
}
sBeta_ab <- function(X, w, shape1=2, shape2 =3, a = 0, b = 1, params = list(shape1, shape2, a, b),...){
if(!missing(params)){
shape1 <- params$shape1
shape2 <- params$shape2
a <- params$a
b <- params$b
}
n <- length(X)
if(missing(w)){
w <- rep(1,n)
} else {
w <- n*w/sum(w)
}
score1 <- sum(w*(digamma(shape1+shape2)-digamma(shape1)+log(X-a)-log(b-a)))
score2 <- sum(w*(digamma(shape1+shape2)-digamma(shape2)+log(b-X)-log(b-a)))
score3 <- sum(w*((shape1+shape2-1)/(b-a)-(shape1-1)/(X-a)))
score4 <- sum(w*((shape2-1)/(b-X)-(shape1+shape2-1)/(b-a)))
score <- c(score1,score2,score3,score4)
names(score) <- c("shape1","shape2","a","b")
return(score)
}
|
DownloadPrimeCode <- function(project, primeFileId, filepath) {
projectId <- ValidateProject(project)
routeString <- UrlJoin("projects", projectId, "primeFiles", primeFileId, "download")
response <- DataRobotGET(routeString, as = "file", filename = filepath)
invisible(NULL)
}
|
qmand <- function (p, N, s, v, lower.tail = TRUE, log.p = FALSE) {
if (length(N) > 1) stop("vectorization of N is not implemented")
if (N < 1 |!is.wholenumber(N)) return(rep(NaN, length(p)))
if (log.p) p <- exp(p)
if(!lower.tail) p <- 1 - p
p[p==1] <- 1+1e-12
Y <- 1:N
X <- pmand(Y, N=N, s=s, v=v)
approx(x=X, y=Y, xout=p, method="constant", rule=2)$y
}
|
benchmark(sf = read_sf(f),
v = {d <- vapour_read_attributes(f)
d$geometry <- st_as_sfc(vapour_read_geometry(f), crs = vapour:::vapour_projection_info_cpp(f))
st_as_sf(as_tibble(d))}, replications = 200)
benchmark(sf = read_sf(f)[1:10, ],
v = {d <- vapour_read_attributes(f, limit_n = 10)
d$geometry <- st_as_sfc(vapour_read_geometry(f, limit_n = 10), crs = vapour:::vapour_projection_info_cpp(f))
st_as_sf(as_tibble(d))}, replications = 200)
|
library(RMSNumpress)
data = c(100, 101, 102, 103)
data_long = c(100.0,
200.0,
300.00005,
400.00010,
450.00010,
455.00010,
700.00010)
data_slof = c(100.0,
200.0,
300.00005,
400.00010)
fp_slof = 10000
linear_result = (as.raw(as.hexmode(c("40", "f8", "6a", "00", "00", "00", "00", "00", "80", "96", "98", "00", "20", "1d", "9a", "00", "88"))))
test_that("encodeLinear encodes doubles in data", {
expect_equal( encodeLinear(data, 100000.0), linear_result )
expect_equal( length(encodeLinear(data, 100000.0)), 17)
expect_equal( encodeLinear(data, 100000.0)[1], as.raw(as.hexmode("40")))
expect_equal( length(encodeLinear(data_long, 5.0)), 22)
expect_equal( length(encodeLinear(data_long, 500.0)), 25)
expect_equal( length(encodeLinear(data_long, 5e4)), 29)
expect_equal( length(encodeLinear(data_long, 5e5)), 30)
expect_equal( length(encodeLinear(data_long, 5e6)), 31)
result = encodeLinear(data_long, 500.0)
decoded = decodeLinear(result)
expect_equal(decoded[1], 100, tolerance=3)
expect_equal(decoded[2], 200, tolerance=3)
expect_equal(decoded[3], 300, tolerance=3)
expect_equal(decoded[4], 400.00010, tolerance=3)
expect_equal(decoded[5], 450.00010, tolerance=3)
expect_equal(decoded[6], 455.00010, tolerance=3)
expect_equal(decoded[7], 700.00010, tolerance=3)
})
test_that("decodeLinear decode data encoded with encodeLinear", {
expect_equal( decodeLinear(as.raw(linear_result)), data )
expect_equal( length(decodeLinear(as.raw(linear_result))), 4 )
expect_equal( decodeLinear(as.raw(linear_result))[1], 100 )
})
test_that("encodePic encodes ion counts", {
encode = encodePic(data)
expect_equal( length(encode), 6 )
result = decodePic(encode)
expect_equal( length(result), 4 )
expect_equal( result[1], 100 )
expect_equal( result, data )
})
test_that("encodeSlof encodes ion counts", {
encode = encodeSlof(data_slof, fp_slof)
expect_equal( length(encode), 16 )
result = decodeSlof(encode)
expect_equal( length(result), 4 )
expect_true( abs(result[1] - 100) < 1)
expect_true( abs(result[2] - 200) < 1)
expect_true( abs(result[3] - 300) < 1)
expect_true( abs(result[4] - 400) < 1)
})
test_that("Compute the maximal linear fixed point that prevents integer overflow", {
pt = optimalLinearFixedPoint(data)
expect_equal(pt, 21262214.0)
})
test_that("Compute the maximal slof fixed point that prevents integer overflow", {
pt = optimalSlofFixedPoint(data)
expect_equal(pt, 14110.0)
})
test_that("optimal linear fixed point with a desired m/z accuracy", {
pt = optimalLinearFixedPointMass(data, 0.001)
expect_equal(pt, 500.0)
pt = optimalLinearFixedPointMass(data, 1e-10)
expect_equal(pt, -1)
})
|
lambda.interp=function(lambda,s){
if(length(lambda)==1){
nums=length(s)
left=rep(1,nums)
right=left
sfrac=rep(1,nums)
}
else{
s[s > max(lambda)] = max(lambda)
s[s < min(lambda)] = min(lambda)
k=length(lambda)
sfrac <- (lambda[1]-s)/(lambda[1] - lambda[k])
lambda <- (lambda[1] - lambda)/(lambda[1] - lambda[k])
coord <- approx(lambda, seq(lambda), sfrac)$y
left <- floor(coord)
right <- ceiling(coord)
sfrac=(sfrac-lambda[right])/(lambda[left] - lambda[right])
sfrac[left==right]=1
sfrac[abs(lambda[left]-lambda[right])<.Machine$double.eps]=1
}
list(left=left,right=right,frac=sfrac)
}
|
context("Fuzzy")
test_fuzzy_add_mf <- function(fuzzy) {
fuzzy$add_mf(NewMfTriangular(0, 1, 2))
expect_equal(fuzzy$mf_size(), 1)
fuzzy$add_mf(NewMfTrapezoidalInf(0, 1))
expect_equal(fuzzy$mf_size(), 2)
fuzzy$add_mf(NewMfTrapezoidalSup(0, 1))
expect_equal(fuzzy$mf_size(), 3)
fuzzy$add_mf(NewMfTrapezoidal(0, 1, 2, 3))
expect_equal(fuzzy$mf_size(), 4)
}
test_that("Fuzzy add mf", {
test_fuzzy_add_mf(NewFisIn(0, 0, 3))
test_fuzzy_add_mf(NewFisOutFuzzy(0, 0, 3))
})
test_fuzzy_get_mf <- function(fuzzy) {
mf1 <- NewMfTriangular(0, 1, 2)
mf2 <- NewMfTrapezoidalInf(0, 1)
mf3 <- NewMfTrapezoidalSup(0, 1)
mf4 <- NewMfTrapezoidal(0, 1, 2, 3)
fuzzy$add_mf(mf1)
fuzzy$add_mf(mf2)
fuzzy$add_mf(mf3)
fuzzy$add_mf(mf4)
expect_equal(fuzzy$get_mf(1), mf1)
expect_equal(fuzzy$get_mf(2), mf2)
expect_equal(fuzzy$get_mf(3), mf3)
expect_equal(fuzzy$get_mf(4), mf4)
expect_error(fuzzy$get_mf(5))
mfs <- fuzzy$get_mfs()
expect_equal(length(mfs), 4)
expect_equal(mfs[[1]], mf1)
expect_equal(mfs[[2]], mf2)
expect_equal(mfs[[3]], mf3)
expect_equal(mfs[[4]], mf4)
expect_equal(fuzzy$get_mf(1)$label, "")
mf1 <- fuzzy$get_mf(1)
mf1$label <- "foo"
expect_equal(fuzzy$get_mf(1)$label, "foo")
}
test_that("FisIn get mf", {
test_fuzzy_get_mf(NewFisIn(0, 0, 3))
test_fuzzy_get_mf(NewFisOutFuzzy(0, 0, 3))
})
test_fuzzy_standardized_partition <- function(fuzzy) {
fuzzy$add_mf(NewMfTrapezoidalInf(0, 1))
fuzzy$add_mf(NewMfTrapezoidal(0, 1, 2, 3))
fuzzy$add_mf(NewMfTriangular(2, 3, 4))
fuzzy$add_mf(NewMfTrapezoidalSup(3, 4))
expect_true(fuzzy$is_standardized())
}
test_that("Fuzzy standardized fuzzy partition", {
test_fuzzy_standardized_partition(NewFisIn(0, 0, 4))
test_fuzzy_standardized_partition(NewFisOutFuzzy(0, 0, 4))
})
test_fuzzy_not_standardized_partition <- function(fuzzy) {
fuzzy$add_mf(NewMfTrapezoidalInf(0, 1))
fuzzy$add_mf(NewMfTrapezoidalSup(1, 2))
expect_false(fuzzy$is_standardized())
}
test_that("FisIn not standardized fuzzy partition", {
test_fuzzy_not_standardized_partition(NewFisIn(0, 0, 2))
test_fuzzy_not_standardized_partition(NewFisOutFuzzy(0, 0, 2))
})
test_fuzzy_unordered_partition <- function(fuzzy) {
fuzzy$add_mf(NewMfTrapezoidalInf(0, 1))
fuzzy$add_mf(NewMfTrapezoidalSup(1, 2))
fuzzy$add_mf(NewMfTriangular(0, 1, 2))
expect_false(fuzzy$is_standardized())
}
test_that("FisIn unordered fuzzy partition", {
test_fuzzy_unordered_partition(NewFisIn(0, 0, 2))
test_fuzzy_unordered_partition(NewFisOutFuzzy(0, 0, 2))
})
|
get_platform_info = function() .Platform
|
update_news_impl <- function(messages) {
news <- collect_news(messages)
if (fledge_chatty()) {
cli_h2("Updating NEWS")
cli_alert("Adding new entries to {.file {news_path()}}.")
}
add_to_news(news)
}
collect_news <- function(messages) {
if (fledge_chatty()) {
cli_alert("Scraping {.field {length(messages)}} commit messages.")
}
messages_lf <- gsub("\r\n", "\n", messages)
messages_nonempty <- messages_lf[messages_lf != ""]
messages_before_triple_dash <- map_chr(strsplit(messages_nonempty, "\n---", fixed = TRUE), 1)
message_lines <- strsplit(messages_before_triple_dash, "\n", fixed = TRUE)
message_bullets <- map(message_lines, keep, ~ grepl("^[*-]", .))
message_items <- unlist(message_bullets)
if (length(message_items) == 0) {
if (length(range) <= 1) {
message_items <- "- Same as previous version."
} else {
message_items <- "- Internal changes only."
}
}
if (fledge_chatty()) {
cli_alert_success("Found {.field {length(message_items)}} NEWS-worthy entries.")
}
paste0(paste(message_items, collapse = "\n"), "\n\n")
}
news_path <- function() {
"NEWS.md"
}
news_comment <- function() {
"<!-- NEWS.md is maintained by https://cynkra.github.io/fledge, do not edit -->"
}
add_to_news <- function(news) {
if (!file.exists(news_path())) {
file.create(news_path())
}
enc::transform_lines_enc(news_path(), make_prepend(news))
invisible(news_path())
}
make_prepend <- function(news) {
force(news)
function(x) {
if (length(x) > 0) {
if (x[[1]] == news_comment()) {
x <- x[-1]
if (x[[1]] == "") {
x <- x[-1]
}
}
}
c(news_comment(), "", news, x)
}
}
edit_news <- function() {
local_options(usethis.quiet = TRUE)
edit_file(news_path())
}
edit_cran_comments <- function() {
local_options(usethis.quiet = TRUE)
edit_file("cran-comments.md")
}
|
modify_aprobs <- function(probs, new_probs) {
x_attr <- attributes(probs)
x_class <- class(probs)
attrs <- names(x_attr)
attrs <- attrs[!(attrs %in% c("class", "names", "dim", "dimnames", "alleles", "alleleprobs"))]
new_probs <- list(new_probs)
names(new_probs) <- names(probs)[1]
for(obj in attrs) {
attr(new_probs, obj) <- x_attr[[obj]]
}
attr(new_probs, "alleles") <- dimnames(new_probs[[1]])[[2]]
attr(new_probs, "alleleprobs") <- TRUE
class(new_probs) <- c("calc_genoprob", "list")
new_probs
}
|
library(rmarkdown)
options(continue=" ")
options(width=60)
library(knitr)
library(geoknife)
query <- geoknife::query
`values<-` <- geoknife::`values<-`
id <- geoknife::id
library(geoknife)
stencil <- simplegeom(c(-89, 46.23))
stencil <- simplegeom(data.frame(
'point1' = c(-89, 46),
'point2' = c(-88.6, 45.2)))
load(system.file('extdata', 'HUC8_stencil.RData', package = 'geoknife'))
stencil
load(system.file('extdata', 'HUC8_query.RData', package = 'geoknife'))
head(HUCs)
fabric <- webdata('prism')
fabric
times(fabric) <- c('2002-01-01','2010-01-01')
variables(fabric) <- c('tmx')
fabric
load(system.file('extdata', 'prism_job.RData', package = 'geoknife'))
plot(data[,1:2], ylab = variables(fabric))
stencil <- simplegeom(c(-89, 45.43))
stencil <- simplegeom(data.frame(
'point1' = c(-89, 46),
'point2' = c(-88.6, 45.2)))
library(sp)
Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))
Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))
Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5)))
Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)
Srs1 = Polygons(list(Sr1), "s1")
Srs2 = Polygons(list(Sr2), "s2")
Srs3 = Polygons(list(Sr3, Sr4), "s3/4")
stencil <- simplegeom(Srl = list(Srs1,Srs2,Srs3), proj4string = CRS("+proj=longlat +datum=WGS84"))
stencil <- webgeom()
stencil
fabric <- webdata()
fabric
times(fabric)
url(fabric) <- 'https://cida.usgs.gov/thredds/dodsC/prism'
variables(fabric) <- 'tmx'
times(fabric)[1] <- as.POSIXct('1990-01-01')
load(system.file('extdata', 'webdata_query.RData', package = 'geoknife'))
length(webdatasets)
webdatasets[61:65]
title(webdatasets[87])
abstract(webdatasets[87])
fabric <- webdata(webdatasets[99])
evapotran <- webdata(webdatasets['Monthly Conterminous U.S. actual evapotranspiration data'])
times(fabric) <- c('1990-01-01','2005-01-01')
fabric = webdata(url='dods://apdrc.soest.hawaii.edu/dods/public_data/satellite_product/AVHRR/avhrr_mon')
times(fabric) <- c('1990-01-01','1999-12-31')
load(system.file('extdata', 'sst_result.RData', package = 'geoknife'))
head(sst)
july.idx <- months(sst$DateTime) == 'July'
plot(sst$DateTime[july.idx], sst$caspian.sea[july.idx], type='l', lwd=2, col='dodgerblue', ylab='Sea Surface Temperature (degC)',xlab=NA)
variables(fabric) <- NA
job <- geojob()
job <- cancel(job)
id(job)
cancel()
|
endofnight <- list(
rm.incompleteperiod <- function(data){
cycs <- which(data$CycleStart == "NREMP" | data$CycleStart == "REMP")
if (data$CycleStart[cycs[length(cycs)]] == "REMP"){
REMs <- which(data$Descr3 == "REM")
stop <- REMs[length(REMs)]+1
end <- which(data$Descr3 == "NREM")
end <- end[end>=stop]
if(length(end)>10){
data$CycleStart[stop] <- "stop"
data$cycles[stop:nrow(data)] <- NA
data$REM.NREM[stop:nrow(data)] <- NA
}else{
stop <- cycs[length(cycs)]
data$CycleStart[cycs[length(cycs)]] <- "stop"
data$cycles[stop:nrow(data)] <- NA
data$REM.NREM[stop:nrow(data)] <- NA
}
}else{
NREMs <- which(data$Descr3 == "NREM")
stop <- NREMs[length(NREMs)]+1
end <- which(data$Descr3 == "REM")
end <- end[end>=stop]
if(length(end)>10){
data$CycleStart[stop] <- "stop"
data$cycles[stop:nrow(data)] <- NA
data$REM.NREM[stop:nrow(data)] <- NA
}else{
stop <- cycs[length(cycs)]
data$CycleStart[cycs[length(cycs)]] <- "stop"
data$cycles[stop:nrow(data)] <- NA
data$REM.NREM[stop:nrow(data)] <- NA
}
}
return(data)
},
clean_endofnight <- function(data){
cycs <- which(data$CycleStart == "NREMP" | data$CycleStart == "REMP")
if (data$CycleStart[cycs[length(cycs)]] == "REMP"){
REMs <- which(data$Descr3 == "REM")
if(tail(REMs, n = 1) == nrow(data)){
stop <- tail(REMs, n = 1)
data$CycleStart[stop] <- "stop"
}else{
stop <- tail(REMs, n = 1)+1
data$CycleStart[stop] <- "stop"
data$cycles[stop:nrow(data)] <- NA
data$REM.NREM[stop:nrow(data)] <- NA
}
}else{
lastNREMP <- tail(which(data$CycleStart == "NREMP"),1)
Ws <- which(data$Descr3 == "W")
Ws <- Ws[Ws > lastNREMP]
if (length(Ws) > 2){
Ws_start <- head(Ws,1)
for (kk in 2:(length(Ws))){
if (Ws[kk-1] != Ws[kk]-1){
Ws_start <- c(Ws_start, Ws[kk])
}
}
Ws_start <- tail(Ws_start,1)
}else{
Ws_start <- c()
}
NREMs <- which(data$Descr3 == "NREM")
if (length(Ws_start) > 0){
if(Ws_start < tail(NREMs,1)) Ws_start <- c()
}
if (length(Ws_start) == 0 & data$Descr3[nrow(data)] == "W") Ws_start <- nrow(data)
if (length(Ws_start) > 0){
data$CycleStart[data$CycleStart == "stop"] <- NA
stop <- Ws_start
data$CycleStart[stop] <- "stop"
}
cycs <- which(data$CycleStart == "NREMP" | data$CycleStart == "REMP")
if (data$CycleStart[cycs[length(cycs)]] == "REMP"){
REMs <- which(data$Descr3 == "REM")
if(tail(REMs, n = 1) == nrow(data)){
data$CycleStart[data$CycleStart == "stop"] <- NA
stop <- tail(REMs, n = 1)
data$CycleStart[stop] <- "stop"
}else{
data$CycleStart[data$CycleStart == "stop"] <- NA
stop <- tail(REMs, n = 1)+1
data$CycleStart[stop] <- "stop"
data$cycles[stop:nrow(data)] <- NA
data$REM.NREM[stop:nrow(data)] <- NA
}
}
check <- which(data$CycleStart == "stop")
if (length(check)>0){
if(stop - tail(which(data$CycleStart == "NREMP"),1)>=30){
data$cycles[stop:nrow(data)] <- NA
data$REM.NREM[stop:nrow(data)] <- NA
}else{
data$CycleStart[tail(which(data$CycleStart == "NREMP"),1)] <- "stop"
data$CycleStart[stop] <- NA
data$cycles[tail(which(data$CycleStart == "stop"),1):nrow(data)] <- NA
data$REM.NREM[tail(which(data$CycleStart == "stop"),1):nrow(data)] <- NA
cycs <- which(data$CycleStart == "NREMP" | data$CycleStart == "REMP")
if (data$CycleStart[cycs[length(cycs)]] == "REMP"){
REMs <- which(data$Descr3 == "REM")
stop <- REMs[length(REMs)]+1
data$CycleStart[stop] <- "stop"
data$cycles[stop:nrow(data)] <- NA
data$REM.NREM[stop:nrow(data)] <- NA
}
}
}
}
return(data)
}
)
|
dist.calc <-
function (lat1, lon1, lat2, lon2, unit = "km")
{
lat1_r <- lat1*pi/180
lon1_r <- lon1*pi/180
lat2_r <- lat2*pi/180
lon2_r <- lon2*pi/180
distance <- 6378 * (acos(sin(lat1_r) * sin(lat2_r) + cos(lat1_r) * cos(lat2_r) * cos(lon2_r-lon1_r)))
if (unit == "m") distance <- distance*1000
if (unit == "mile") distance <- distance/1.60934
return(distance)
}
|
Bsper<-function(data){
Name<-"Bsper"
data<-as.matrix(data)
n<-nrow(data)
p<-ncol(data)
R<-cor(data)
Chisq<--((n-1)-(2*p+5)/6)*log(det(R))
df<-(p*(p-1))/2
pval<-pchisq(Chisq, df=df,lower.tail = FALSE)
results <- list(Chisq=Chisq,df=df,p.value=pval,R=R,Test=Name)
class(results)<-c("MVTests","list")
return(results)
}
|
PlotPValueHist <- function(out=NULL, method="BH", xl="ANOVA P-values", yl="Number of metabolites", frac.col=NULL, ...) {
FillExpressionVector <- function(x) {
ev <- vector("expression", length(x))
for(i in 1:length(ev)) { ev[i] <- substitute(expression(10^e), list(e = x[i]))[2] }
return(ev)
}
stopifnot(all(abs(out-0.5)<=0.5, na.rm=T))
opar <- par(no.readonly = TRUE)
on.exit(par(opar))
tmp.plots <- 2*ncol(out)
tmp.layout <- rbind(cbind(tmp.plots+1, matrix(1:(tmp.plots), nrow=2, byrow=T)), tmp.plots+2)
tmp.layout[nrow(tmp.layout), 1] <- 0
layout(mat=tmp.layout, widths=c(0.025, rep(0.975/ncol(out), ncol(out))), heights=c(rep(0.475, 2), 0.05))
par(...)
if (is.null(attr(out,"p.adjust.method"))) {
out.adj <- apply(out, 2, p.adjust, method)
} else {
out.adj <- out
method <- attr(out,"p.adjust.method")
}
tmp.seq <- seq(0, 1, .05)
tmp.max <- max(apply(out.adj, 2, function(y) { hist(y, breaks=tmp.seq, plot=F)$counts }))
if (is.null(frac.col)) {
for (i in 1:ncol(out)) {
par(mar=c(1.25,3.5,1.75,0)+.25)
hist(out.adj[,i], breaks=tmp.seq, ylim=c(0,tmp.max), main=colnames(out)[i], xlab="", ylab="", las=1)
}
} else {
for (i in 1:ncol(out)) {
tmp.mat <- cbind(0, sapply(split(out.adj[,i], factor(frac.col)), function(y) { hist(y, breaks=tmp.seq, plot=F)$counts }))
par(mar=c(1.25,3.5,1.75,0)+.25)
graphics::plot(x=c(0,1), y=c(0,tmp.max), main=colnames(out)[i], xlab="", ylab="", las=1, type="n")
for (j in 2:ncol(tmp.mat)) rect(tmp.seq[-length(tmp.seq)], apply(tmp.mat[,1:(j-1),drop=F],1,sum), tmp.seq[-1], apply(tmp.mat[,1:j],1,sum), col=colnames(tmp.mat)[j])
}
}
out.adj <- log10(out.adj)
if (any(is.infinite(out.adj))) out.adj[is.infinite(out.adj)] <- min(out.adj[is.finite(out.adj)])
tmp.seq <- seq(ifelse(floor(min(out.adj, na.rm=T))<=-1, floor(min(out.adj, na.rm=T)), -1), 0)
tmp.max <- max(apply(out.adj, 2, function(y) { hist(y, breaks=tmp.seq, plot=F)$counts }))
tmp.min <- 0.9
for (i in 1:ncol(out)) {
par(mar=c(3,3.5,0.25,0)+.25)
a <- hist(out.adj[,i], breaks=tmp.seq, plot=F)$counts
filt <- a != 0
graphics::plot(x=range(tmp.seq), y=c(tmp.min, tmp.max), log="y", type="n", axes=F, ann=F)
rect(xleft=tmp.seq[-length(tmp.seq)][filt],
ybottom=rep(tmp.min, length(tmp.seq)-1)[filt],
xright=tmp.seq[-1][filt],
ytop=a[filt])
graphics::axis(1, at=axTicks(1)[seq(1,length(axTicks(1)))], tick=F, labels=FillExpressionVector(axTicks(1)[seq(1,length(axTicks(1)))]))
graphics::axis(1, at=axTicks(1), labels=FALSE); graphics::axis(2, las=2)
}
par(mar=rep(0,4)+.1)
graphics::plot(0,0,ann=F,axes=F,type="n"); graphics::text(x=0, y=0, labels=paste(yl, " (n=", sum(is.finite(out.adj[,i])), ")", sep=""), srt=90, cex=4/3)
graphics::plot(0,0,ann=F,axes=F,type="n"); graphics::text(x=0, y=0, labels=paste(xl, " (", method, ")", sep=""), cex=4/3)
invisible(NULL)
}
|
test_that("classif_plsdaCaret_binary", {
skip("until klaR pkg was updated")
requirePackagesOrSkip("caret", default.method = "load")
parset.list = list(
list(),
list(ncomp = 4),
list(probMethod = "Bayes"),
list(method = "oscorespls")
)
old.predicts.list = list()
old.probs.list = list()
for (i in seq_along(parset.list)) {
parset = parset.list[[i]]
x = binaryclass.train
y = x[, binaryclass.class.col]
x[, binaryclass.class.col] = NULL
pars = list(x = x, y = y)
pars = c(pars, parset)
m = do.call(caret::plsda, pars)
newx = binaryclass.test
newx[, binaryclass.class.col] = NULL
p = predict(m, newdata = newx, type = "class")
p2 = predict(m, newdata = newx, type = "prob")[, 1, 1]
old.predicts.list[[i]] = p
old.probs.list[[i]] = p2
}
testSimpleParsets("classif.plsdaCaret", binaryclass.df, binaryclass.target,
binaryclass.train.inds,
old.predicts.list, parset.list)
testProbParsets("classif.plsdaCaret", binaryclass.df, binaryclass.target,
binaryclass.train.inds,
old.probs.list, parset.list)
})
test_that("classif_plsdaCaret_multiclass", {
requirePackagesOrSkip("caret", default.method = "load")
parset.list = list(
list(),
list(ncomp = 4),
list(probMethod = "Bayes"),
list(method = "oscorespls")
)
old.predicts.list = list()
old.probs.list = list()
for (i in seq_along(parset.list)) {
parset = parset.list[[i]]
pars = list(x = multiclass.train[, names(multiclass.train) %nin%
multiclass.target],
y = multiclass.train[, multiclass.target])
pars = c(pars, parset)
m = do.call(caret::plsda, pars)
newx = multiclass.test
newx[, multiclass.class.col] = NULL
p = predict(m, newdata = newx, type = "class")
p2 = predict(m, newdata = newx, type = "prob")[, , 1]
old.predicts.list[[i]] = p
old.probs.list[[i]] = p2
}
testSimpleParsets("classif.plsdaCaret", multiclass.df, multiclass.target,
multiclass.train.inds, old.predicts.list, parset.list)
testProbParsets("classif.plsdaCaret", multiclass.df, multiclass.target,
multiclass.train.inds, old.probs.list, parset.list)
})
|
Tgrid=function(ne, ssigma_eps, llambda_eps, m){
grid = array(0, dim = ne)
ssigma_y = sqrt(ssigma_eps^2/(1-llambda_eps^2))
estep = 2*ssigma_y*m / (ne-1)
for(ii in 1:1:ne){
grid[ii] = -m*sqrt((ssigma_eps^2)/(1-llambda_eps^2)) + (ii-1)*estep
}
return(grid)
}
Rtauchen=function(ne, ssigma_eps, llambda_eps, m){
grid = Tgrid(ne, ssigma_eps, llambda_eps, m)
if(ne > 1){
w = grid[2] - grid[1]
P = array(0, dim = c(ne,ne))
for(jj in 1:ne){
for(kk in 1:ne){
if(kk == 1){
P[jj,kk] = pnorm((grid[kk] - llambda_eps*grid[jj]+(w/2))/ssigma_eps)
}
else if(kk == ne){
P[jj,kk] = 1- pnorm((grid[kk] - llambda_eps*grid[jj]-(w/2))/ssigma_eps)
}
else{
P[jj,kk] = pnorm((grid[kk] - llambda_eps*grid[jj]+(w/2))/ssigma_eps)-pnorm((grid[kk] - llambda_eps*grid[jj]-(w/2))/ssigma_eps)
}
}
}
} else{
P = 1
}
return(P)
}
|
setClass("Triangle",
slots=c(
triID="character",
type="character",
startDate="Date",
frequency="character",
sim="numeric",
percentile="numeric",
iRBNER="logical",
iROPEN="logical",
upper="matrix",
upperkeep="matrix",
rectangle="matrix"
),
prototype=list(
triID="XXXXXX",
type="reportedCount",
startDate=as.Date("2012-01-01"),
frequency="yearly",
sim=1,
percentile=50,
iRBNER=TRUE,
iROPEN=TRUE,
upper=matrix(),
upperkeep=matrix(),
rectangle=matrix()
)
)
setGeneric("setUpperTriangle", function(object,data,...) standardGeneric("setUpperTriangle"))
setMethod("setUpperTriangle",signature("Triangle","data.frame"), function(object,data,evaluationDate=as.Date("2016-12-31"),lob="Total",ctype="Total") {
tryCatch({
if (lob != "Total") {data <- data[data[,"LoB"]==lob,]}
if (ctype != "Total") {data <- data[data[,"Type"]==ctype,]}
startYear <- as.numeric(substr(as.character(object@startDate),1,4))
endYear <- as.numeric(substr(as.character(evaluationDate),1,4))
startMonth <- as.numeric(substr(as.character(object@startDate),6,7))
endMonth <- as.numeric(substr(as.character(evaluationDate),6,7))
startQuarter <- ceiling(startMonth/3)
endQuarter <- ceiling(endMonth/3)
if (object@frequency=="yearly") {
ncols <- endYear - startYear + 1
rowname <- c(startYear:endYear)
colname <- paste0("M",seq(12,(12*ncols),12))
} else {
ncols <- (endYear - startYear)*4 + endQuarter - startQuarter + 1
rowname <- vector()
for (i in c(startYear:endYear)){
if (i==startYear){
for (j in c(startQuarter:4)){
rowname <- c(rowname,paste0(j,"Q",i))
}
} else if (i == endYear){
for (j in c(1:endQuarter)){
rowname <- c(rowname,paste0(j,"Q",i))
}
} else {
for (j in c(1:4)){
rowname <- c(rowname,paste0(j,"Q",i))
}
}
}
colname <- paste0("M",seq(3,(3*ncols),3))
}
rec <- matrix(0,ncols,ncols,dimnames = list(rowname,colname))
if ("Sim" %in% colnames(data)) {
sim <- data$Sim[1]
data <- data[data[,"Sim"]==sim,]
}
data <- data[,colnames(data) %in% c("occurrenceDate","reportDate","settlementDate","incurredLoss","Paid")]
accidentYears <- as.numeric(substr(as.character(data$occurrenceDate),1,4))
accidentMonths <- as.numeric(substr(as.character(data$occurrenceDate),6,7))
accidentQuarters <- ceiling(accidentMonths/3)
if (object@frequency=="yearly") {
data$rowno <- (accidentYears - startYear) + 1
} else {
data$rowno <- (accidentYears - startYear) * 4 + (accidentQuarters - startQuarter) + 1
}
if (object@type == "reportedCount"){
reportYears <- as.numeric(substr(as.character(data$reportDate),1,4))
reportMonths <- as.numeric(substr(as.character(data$reportDate),6,7))
reportQuarters <- ceiling(reportMonths/3)
if (object@frequency=="yearly") {
data$colno <- (reportYears - accidentYears) + 1
} else {
data$colno <- (reportYears - accidentYears) * 4 + (reportQuarters - accidentQuarters) + 1
}
} else if (object@type == "closedCount"){
settleYears <- as.numeric(substr(as.character(data$settlementDate),1,4))
settleYears <- ifelse(is.na(settleYears), endYear+1, settleYears)
settleMonths <- as.numeric(substr(as.character(data$settlementDate),6,7))
settleMonths <- ifelse(is.na(settleMonths), endMonth, settleMonths)
settleQuarters <- ceiling(settleMonths/3)
if (object@frequency=="yearly") {
data$colno <- (settleYears - accidentYears) + 1
} else {
data$colno <- (settleYears - accidentYears) * 4 + (settleQuarters - accidentQuarters) + 1
}
}else {
settleYears <- as.numeric(substr(as.character(data$settlementDate),1,4))
settleYears <- ifelse(is.na(settleYears), endYear, settleYears)
settleMonths <- as.numeric(substr(as.character(data$settlementDate),6,7))
settleMonths <- ifelse(is.na(settleMonths), endMonth, settleMonths)
settleQuarters <- ceiling(settleMonths/3)
if (object@frequency=="yearly") {
data$colno <- (settleYears - accidentYears) + 1
} else {
data$colno <- (settleYears - accidentYears) * 4 + (settleQuarters - accidentQuarters) + 1
}
}
if (object@type == "reportedCount" | object@type == "closedCount") {
agg<-aggregate(occurrenceDate ~ rowno + colno, data = data, length)
} else if (object@type == "incurredLoss") {
agg<-aggregate(incurredLoss ~ rowno + colno, data = data, sum)
} else {
agg<-aggregate(Paid ~ rowno + colno, data = data, sum)
}
for (i in c(1:length(rowname))){
rowsum <- 0
for (j in c(1:(ncols-i+1))){
tmp <- agg[agg$rowno == i & agg$colno == j,][1,3]
if (!is.na(tmp)) {
rowsum <- rowsum + tmp
}
rec[i,j] <- rowsum
}
}
object@upper <- rec
gc()
object
}, error = function(err){
message(paste0(">>>Critical Error: ", err))
gc()
return(-1)
})
})
setGeneric("setUpperKeep", function(object,data,...) standardGeneric("setUpperKeep"))
setMethod("setUpperKeep",signature("Triangle","data.frame"), function(object,data,evaluationDate=as.Date("2016-12-31"),lob="Total",ctype="Total") {
tryCatch({
if (lob != "Total") {data <- data[data[,"LoB"]==lob,]}
if (ctype != "Total") {data <- data[data[,"Type"]==ctype,]}
startYear <- as.numeric(substr(as.character(object@startDate),1,4))
endYear <- as.numeric(substr(as.character(evaluationDate),1,4))
startMonth <- as.numeric(substr(as.character(object@startDate),6,7))
endMonth <- as.numeric(substr(as.character(evaluationDate),6,7))
startQuarter <- ceiling(startMonth/3)
endQuarter <- ceiling(endMonth/3)
if (object@frequency=="yearly") {
ncols <- endYear - startYear + 1
rowname <- c(startYear:endYear)
colname <- paste0("M",seq(12,(12*ncols),12))
} else {
ncols <- (endYear - startYear)*4 + endQuarter - startQuarter + 1
rowname <- vector()
for (i in c(startYear:endYear)){
if (i==startYear){
for (j in c(startQuarter:4)){
rowname <- c(rowname,paste0(j,"Q",i))
}
} else if (i == endYear){
for (j in c(1:endQuarter)){
rowname <- c(rowname,paste0(j,"Q",i))
}
} else {
for (j in c(1:4)){
rowname <- c(rowname,paste0(j,"Q",i))
}
}
}
colname <- paste0("M",seq(3,(3*ncols),3))
}
rec <- matrix(0,ncols,ncols,dimnames = list(rowname,colname))
if ("Sim" %in% colnames(data)) {
sim <- data$Sim[1]
data <- data[data[,"Sim"]==sim,]
}
data <- data[,colnames(data) %in% c("occurrenceDate","reportDate","settlementDate","incurredLoss","Paid")]
accidentYears <- as.numeric(substr(as.character(data$occurrenceDate),1,4))
accidentMonths <- as.numeric(substr(as.character(data$occurrenceDate),6,7))
accidentQuarters <- ceiling(accidentMonths/3)
if (object@frequency=="yearly") {
data$rowno <- (accidentYears - startYear) + 1
} else {
data$rowno <- (accidentYears - startYear) * 4 + (accidentQuarters - startQuarter) + 1
}
if (object@type == "reportedCount"){
reportYears <- as.numeric(substr(as.character(data$reportDate),1,4))
reportMonths <- as.numeric(substr(as.character(data$reportDate),6,7))
reportQuarters <- ceiling(reportMonths/3)
if (object@frequency=="yearly") {
data$colno <- (reportYears - accidentYears) + 1
} else {
data$colno <- (reportYears - accidentYears) * 4 + (reportQuarters - accidentQuarters) + 1
}
} else if (object@type == "closedCount"){
settleYears <- as.numeric(substr(as.character(data$settlementDate),1,4))
settleYears <- ifelse(is.na(settleYears), endYear+1, settleYears)
settleMonths <- as.numeric(substr(as.character(data$settlementDate),6,7))
settleMonths <- ifelse(is.na(settleMonths), endMonth, settleMonths)
settleQuarters <- ceiling(settleMonths/3)
if (object@frequency=="yearly") {
data$colno <- (settleYears - accidentYears) + 1
} else {
data$colno <- (settleYears - accidentYears) * 4 + (settleQuarters - accidentQuarters) + 1
}
} else {
settleYears <- as.numeric(substr(as.character(data$settlementDate),1,4))
settleYears <- ifelse(is.na(settleYears), endYear, settleYears)
settleMonths <- as.numeric(substr(as.character(data$settlementDate),6,7))
settleMonths <- ifelse(is.na(settleMonths), endMonth, settleMonths)
settleQuarters <- ceiling(settleMonths/3)
if (object@frequency=="yearly") {
data$colno <- (settleYears - accidentYears) + 1
} else {
data$colno <- (settleYears - accidentYears) * 4 + (settleQuarters - accidentQuarters) + 1
}
}
if (object@type == "reportedCount" | object@type == "closedCount") {
agg<-aggregate(occurrenceDate ~ rowno + colno, data = data, length)
} else if(object@type == "incurredLoss"){
agg<-aggregate(incurredLoss ~ rowno + colno, data = data, sum)
} else {
agg<-aggregate(Paid ~ rowno + colno, data = data, sum)
}
for (i in c(1:length(rowname))){
rowsum <- 0
for (j in c(1:(ncols-i+1))){
tmp <- agg[agg$rowno == i & agg$colno == j,][1,3]
if (!is.na(tmp)) {
rowsum <- rowsum + tmp
}
rec[i,j] <- rowsum
}
}
object@upperkeep <- rec
gc()
object
}, error = function(err){
message(paste0(">>>Critical Error: ", err))
gc()
return(-1)
})
})
setGeneric("setRectangle", function(object,data,...) standardGeneric("setRectangle"))
setMethod("setRectangle",signature("Triangle","data.frame"), function(object,data,evaluationDate=as.Date("2016-12-31"),futureDate=as.Date("2017-12-31"),lob="Total",ctype="Total") {
tryCatch({
if (lob != "Total") {data <- data[data[,"LoB"]==lob,]}
if (ctype != "Total") {data <- data[data[,"Type"]==ctype,]}
if (!is.nan(object@sim) & object@sim > 0) {
data <- data[data[,"Sim"]==object@sim,]
} else {
ultAgg <- aggregate(ultimateLoss ~ Sim, data = data, sum)
ultAgg <- ultAgg[order(ultAgg[,2]),]
nsim <- nrow(ultAgg)
lsim <- max(1,floor(nsim*object@percentile/100))
usim <- max(1,ceiling(nsim*object@percentile/100))
lambda <- usim - nsim*object@percentile/100
lsim <- ultAgg[lsim,1]
usim <- ultAgg[usim,1]
}
if (nrow(data)<=0){
stop("No data available for rectangle construction.")
} else {
settleYears <- as.numeric(substr(as.character(data$settlementDate),1,4))
resettleYears <- as.numeric(substr(as.character(data$resettleDate),1,4))
settleMonths <- as.numeric(substr(as.character(data$settlementDate),6,7))
resettleMonths <- as.numeric(substr(as.character(data$resettleDate),6,7))
settleYears <- ifelse(is.na(resettleYears), settleYears, resettleYears)
settleMonths <- ifelse(is.na(resettleMonths), settleMonths, resettleMonths)
settleQuarters <- ceiling(settleMonths/3)
startYear <- as.numeric(substr(as.character(object@startDate),1,4))
endYear <- max(settleYears)
evaluationYear <- as.numeric(substr(as.character(evaluationDate),1,4))
futureYear <- as.numeric(substr(as.character(futureDate),1,4))
startMonth <- as.numeric(substr(as.character(object@startDate),6,7))
endMonth <- max(settleMonths)
evaluationMonth <- as.numeric(substr(as.character(evaluationDate),6,7))
futureMonth <- as.numeric(substr(as.character(futureDate),6,7))
startQuarter <- ceiling(startMonth/3)
endQuarter <- ceiling(endMonth/3)
evaluationQuarter <- ceiling(evaluationMonth/3)
futureQuarter <- ceiling(futureMonth/3)
if (object@frequency=="yearly") {
ncols <- endYear - startYear + 1
nevals <- evaluationYear - startYear + 1
nrows <- futureYear - startYear + 1
rowname <- c(startYear:futureYear)
colname <- paste0("M",seq(12,(12*ncols),12))
} else {
ncols <- (endYear - startYear)*4 + endQuarter - startQuarter + 1
nevals <- (evaluationYear - startYear)*4 + evaluationQuarter - startQuarter + 1
nrows <- (futureYear - startYear)*4 + futureQuarter - startQuarter + 1
rowname <- vector()
for (i in c(startYear:futureYear)){
if (i==startYear){
for (j in c(startQuarter:4)){
rowname <- c(rowname,paste0(j,"Q",i))
}
} else if (i == futureYear){
for (j in c(1:futureQuarter)){
rowname <- c(rowname,paste0(j,"Q",i))
}
} else {
for (j in c(1:4)){
rowname <- c(rowname,paste0(j,"Q",i))
}
}
}
colname <- paste0("M",seq(3,(3*ncols),3))
}
rec <- matrix(0,nrows,ncols,dimnames = list(rowname,colname))
nsims <- 1
if (!is.nan(object@sim)) {
if (object@sim > 0) {
data <- data[data[,"Sim"]==object@sim,]
nsims <- 1
} else {
nsims <- length(unique(data[,"Sim"]))
}
data <- data[,colnames(data) %in% c("occurrenceDate","reportDate","settlementDate","ultimateLoss","Paid")]
accidentYears <- as.numeric(substr(as.character(data$occurrenceDate),1,4))
accidentMonths <- as.numeric(substr(as.character(data$occurrenceDate),6,7))
accidentQuarters <- ceiling(accidentMonths/3)
if (object@frequency=="yearly") {
data$rowno <- (accidentYears - startYear) + 1
} else {
data$rowno <- (accidentYears - startYear) * 4 + (accidentQuarters - startQuarter) + 1
}
if (object@type == "reportedCount"){
reportYears <- as.numeric(substr(as.character(data$reportDate),1,4))
reportMonths <- as.numeric(substr(as.character(data$reportDate),6,7))
reportQuarters <- ceiling(reportMonths/3)
if (object@frequency=="yearly") {
data$colno <- (reportYears - accidentYears) + 1
} else {
data$colno <- (reportYears - accidentYears) * 4 + (reportQuarters - accidentQuarters) + 1
}
} else {
settleYears <- as.numeric(substr(as.character(data$settlementDate),1,4))
settleYears <- ifelse(is.na(settleYears), endYear, settleYears)
settleMonths <- as.numeric(substr(as.character(data$settlementDate),6,7))
settleMonths <- ifelse(is.na(settleMonths), endMonth, settleMonths)
settleQuarters <- ceiling(settleMonths/3)
if (object@frequency=="yearly") {
data$colno <- (settleYears - accidentYears) + 1
} else {
data$colno <- (settleYears - accidentYears) * 4 + (settleQuarters - accidentQuarters) + 1
}
}
if (object@type == "reportedCount" | object@type == "closedCount") {
agg<-aggregate(occurrenceDate ~ rowno + colno, data = data, length)
} else {
agg<-aggregate(ultimateLoss ~ rowno + colno, data = data, sum)
}
for (i in c(1:length(rowname))){
rowsum <- 0
for (j in c(1:length(colname))){
tmp <- agg[agg$rowno == i & agg$colno == j,][1,3]
if (!is.na(tmp)) {
rowsum <- rowsum + tmp
}
rec[i,j] <- rowsum
}
}
for (i in c(1:length(rowname))){
for (j in c(1:length(colname))){
rec[i,j] <- rec[i,j]/nsims
}
}
if(any(is.na(object@upperkeep))==FALSE){
for (i in c(1:length(rowname))){
if(i <= nrow(object@upperkeep)){
addtmp <- object@upperkeep[i,ncol(object@upperkeep)-i+1]-rec[i,ncol(object@upperkeep)-i+1]
} else {
addtmp <- 0
}
for (j in c(1:length(colname))){
rec[i,j] <- rec[i,j] + addtmp
}
}
}
} else {
data <- data[data[,"Sim"]==lsim | data[,"Sim"]==usim,]
data <- data[,colnames(data) %in% c("occurrenceDate","reportDate","settlementDate","ultimateLoss","Sim")]
accidentYears <- as.numeric(substr(as.character(data$occurrenceDate),1,4))
accidentMonths <- as.numeric(substr(as.character(data$occurrenceDate),6,7))
accidentQuarters <- ceiling(accidentMonths/3)
if (object@frequency=="yearly") {
data$rowno <- (accidentYears - startYear) + 1
} else {
data$rowno <- (accidentYears - startYear) * 4 + (accidentQuarters - startQuarter) + 1
}
if (object@type == "reportedCount"){
reportYears <- as.numeric(substr(as.character(data$reportDate),1,4))
reportMonths <- as.numeric(substr(as.character(data$reportDate),6,7))
reportQuarters <- ceiling(reportMonths/3)
if (object@frequency=="yearly") {
data$colno <- (reportYears - accidentYears) + 1
} else {
data$colno <- (reportYears - accidentYears) * 4 + (reportQuarters - accidentQuarters) + 1
}
} else {
settleYears <- as.numeric(substr(as.character(data$settlementDate),1,4))
settleYears <- ifelse(is.na(settleYears), endYear, settleYears)
settleMonths <- as.numeric(substr(as.character(data$settlementDate),6,7))
settleMonths <- ifelse(is.na(settleMonths), endMonth, settleMonths)
settleQuarters <- ceiling(settleMonths/3)
if (object@frequency=="yearly") {
data$colno <- (settleYears - accidentYears) + 1
} else {
data$colno <- (settleYears - accidentYears) * 4 + (settleQuarters - accidentQuarters) + 1
}
}
if (object@type == "reportedCount" | object@type == "closedCount") {
lagg<-aggregate(occurrenceDate ~ rowno + colno, data = data[data[,"Sim"]==lsim,], length)
uagg<-aggregate(occurrenceDate ~ rowno + colno, data = data[data[,"Sim"]==usim,], length)
} else {
lagg<-aggregate(ultimateLoss ~ rowno + colno, data = data[data[,"Sim"]==lsim,], sum)
uagg<-aggregate(ultimateLoss ~ rowno + colno, data = data[data[,"Sim"]==usim,], sum)
}
for (i in c(1:length(rowname))){
rowsum <- 0
for (j in c(1:length(colname))){
ltmp <- lagg[lagg$rowno == i & lagg$colno == j,][1,3]
utmp <- uagg[uagg$rowno == i & uagg$colno == j,][1,3]
tmp <- 0
if(!is.na(ltmp)){tmp<-lambda*ltmp}
if(!is.na(utmp)){tmp<-tmp+(1-lambda)*utmp}
if (!is.na(tmp)) {
rowsum <- rowsum + tmp
}
rec[i,j] <- rowsum
}
}
if(any(is.na(object@upperkeep))==FALSE){
for (i in c(1:length(rowname))){
if(i <= nrow(object@upperkeep)){
addtmp <- object@upperkeep[i,ncol(object@upperkeep)-i+1]-rec[i,ncol(object@upperkeep)-i+1]
} else {
addtmp <- 0
}
for (j in c(1:length(colname))){
rec[i,j] <- rec[i,j] + addtmp
}
}
}
}
if(any(is.na(object@upperkeep))==FALSE){
for (i in c(1:min(nrows,nrow(object@upper)))){
for (j in c(1:(min(ncol(object@upper),ncols)-i+1))){
rec[i,j] <- object@upper[i,j]
}
}
}
object@rectangle <- rec
gc()
object
}
}, error = function(err){
message(paste0(">>>Critical Error: ", err))
gc()
return(-1)
})
})
setMethod("toString",signature("Triangle"), function(object) {
return(object@rectangle)
})
|
Option = setRefClass("Option",
fields = list(OptionType = 'character',
UnderlyingPrice = 'numeric',
StrikePrice = 'numeric',
del_type = 'character',
maturity = 'numeric',
exotic_opt_type = 'character'
),
methods = list(
CalcMaturity =function()
{
if(del_type=='Cash')
return(maturity)
}
))
|
whittermore.pboot<-function(...)
{
return( whittermore.stat(...) )
}
|
hsu.t.test <- function(x, ...){
UseMethod("hsu.t.test")
}
hsu.t.test.default <- function (x, y, alternative = c("two.sided", "less", "greater"),
mu = 0, conf.level = 0.95, ...){
alternative <- match.arg(alternative)
if (!missing(mu) && (length(mu) != 1 || is.na(mu)))
stop("'mu' must be a single number")
if (!missing(conf.level) && (length(conf.level) != 1 || !is.finite(conf.level) ||
conf.level < 0 || conf.level > 1))
stop("'conf.level' must be a single number between 0 and 1")
dname <- paste(deparse(substitute(x)), "and", deparse(substitute(y)))
yok <- !is.na(y)
xok <- !is.na(x)
y <- y[yok]
x <- x[xok]
nx <- length(x)
if(nx < 2) stop("not enough 'x' observations")
mx <- mean(x)
vx <- var(x)
ny <- length(y)
if(ny < 2) stop("not enough 'y' observations")
my <- mean(y)
vy <- var(y)
estimate <- c(mx, my, sqrt(vx), sqrt(vy))
names(estimate) <- c("mean of x", "mean of y", "SD of x", "SD of y")
if(nx < 6 || ny < 6)
warning("For Hsu t-test the sample size per group should be > 5.")
s <- sqrt(vx + vy)
se <- sqrt(vx/nx + vy/ny)
df <- min(nx, ny) - 1
if(se < 10 * .Machine$double.eps * max(abs(mx), abs(my)))
stop("data are essentially constant")
tstat <- (mx - my - mu)/se
if(alternative == "less") {
pval <- pt(tstat, df)
cint <- c(-Inf, tstat + qt(conf.level, df))
}
else if(alternative == "greater") {
pval <- pt(tstat, df, lower.tail = FALSE)
cint <- c(tstat - qt(conf.level, df), Inf)
}
else{
pval <- 2 * pt(-abs(tstat), df)
alpha <- 1 - conf.level
cint <- qt(1 - alpha/2, df)
cint <- tstat + c(-cint, cint)
}
cint <- mu + cint * se
names(tstat) <- "t"
names(df) <- "df"
names(mu) <- "difference in means"
attr(cint, "conf.level") <- conf.level
rval <- list(statistic = tstat, parameter = df, p.value = pval,
conf.int = cint, estimate = estimate, null.value = mu,
stderr = se, alternative = alternative,
method = "Hsu Two Sample t-test",
data.name = dname)
class(rval) <- "htest"
rval
}
hsu.t.test.formula <- function (formula, data, subset, na.action, ...)
{
if (missing(formula) || (length(formula) != 3L) || (length(attr(terms(formula[-2L]),
"term.labels")) != 1L))
stop("'formula' missing or incorrect")
m <- match.call(expand.dots = FALSE)
if (is.matrix(eval(m$data, parent.frame())))
m$data <- as.data.frame(data)
m[[1L]] <- quote(stats::model.frame)
m$... <- NULL
mf <- eval(m, parent.frame())
DNAME <- paste(names(mf), collapse = " by ")
names(mf) <- NULL
response <- attr(attr(mf, "terms"), "response")
g <- factor(mf[[-response]])
if (nlevels(g) != 2L)
stop("grouping factor must have exactly 2 levels")
DATA <- setNames(split(mf[[response]], g), c("x", "y"))
y <- do.call("hsu.t.test", c(DATA, list(...)))
y$data.name <- DNAME
if (length(y$estimate) == 2L)
names(y$estimate) <- paste("mean in group", levels(g))
y
}
|
image_comment <- function(image, comment = NULL){
assert_image(image)
comment <- as.character(comment)
magick_attr_comment(image, comment)
}
image_info <- function(image){
assert_image(image)
df <- magick_image_info(image)
df_to_tibble(df)
}
|
asymmetryCurve <- function(x, y = NULL, alpha = seq(0, 1, 0.01),
movingmedian = FALSE, name = "X", name_y = "Y",
depth_params = list(method = "Projection")) {
x <- na.omit(x)
if (nrow(x) < NCOL(x) * 10) {
stop("Too small sample!")
}
if (!is.matrix(x)) {
stop("X must be a matrix!")
}
if (!is.null(y) && !is.matrix(y)) {
stop("Y must be a matrix!")
}
uxname_list <- list(u = x, X = x)
depth_est <- do.call(depth, c(uxname_list, depth_params))
if (!movingmedian) {
x_est <- asCurve(x, depth_est = depth_est, alpha = alpha, name = name,
depth_params = depth_params)
} else {
x_est <- asCurveMM(x, alpha = alpha, name = name,
depth_params = depth_params)
}
asc <- new("AsymmetryCurve", x_est[, 2], depth = depth_est,
alpha = x_est[, 1], name = name)
if (!is.null(y)) {
name <- name_y
asc <- combineDepthCurves(
asc,
asymmetryCurve(y, y = NULL, alpha = alpha, movingmedian = movingmedian,
name = name, name_y = "Y",
depth_params = list(method = "Projection"))
)
}
return(asc)
}
asCurve <- function(X, depth_est = NULL, alpha = NULL, name = "X",
depth_params = list(method = "Projection")) {
dim_X <- dim(X)[2]
if (is.null(depth_est)) {
uxname_list <- list(u = X, X = X, name = name)
depth_est <- do.call(depth, c(uxname_list, depth_params))
}
median <- depthMedian(X, depth_params)
if ((length(median) / dim(X)[2]) != 1) {
median <- colMeans(median)
}
k <- length(alpha)
vol <- 1:k
alpha_est <- 1:k
means <- matrix(nrow = k, ncol = dim_X)
alpha_border <- ecdf(depth_est)(depth_est)
for (i in 1:k) {
tmp_X <- X[alpha_border >= alpha[i], ]
np <- dim(unique(as.matrix(tmp_X)))[1]
if ((np > ((2 * (dim_X + 2)) ^ 2)) && (np > 100)) {
vol[i] <- convhulln(tmp_X, options = "FA")$vol
alpha_est[i] <- alpha[i]
means[i, ] <- colMeans(tmp_X)
} else {
vol[i] <- NA
alpha_est[i] <- NA
}
}
k <- length(vol)
kmedian <- matrix(rep(median, k), byrow = TRUE, ncol = dim_X)
n <- (means - kmedian)
nn <- 2 * sqrt(rowSums(n ^ 2)) / (vol ^ (1 / dim_X))
matrix(c(rev(1 - alpha_est), rev(nn)), ncol = 2)
}
asCurveMM <- function(X, depth_est = NULL, alpha = NULL, name = "X",
depth_params = list(method = "Projection")) {
dim_X <- dim(X)[2]
if (is.null(depth_est)) {
uxname_list <- list(u = X, X = X)
depth_est <- do.call(depth, c(uxname_list, depth_params))
}
if (is.null(alpha)) {
alpha <- seq(0, 1, 0.01)
}
k <- length(alpha)
vol <- 1:k
alpha_est <- 1:k
means <- matrix(nrow = k, ncol = dim_X)
medians <- matrix(nrow = k, ncol = dim_X)
alpha_border <- ecdf(depth_est)(depth_est)
for (i in 1:k) {
tmp_X <- X[alpha_border >= alpha[i], ]
np <- dim(as.matrix(tmp_X))[1]
if ((np > ((2 * (dim_X + 2)) ^ 2)) && (np > 100)) {
vol[i] <- convhulln(tmp_X, options = "FA")$vol
alpha_est[i] <- alpha[i]
means[i, ] <- colMeans(tmp_X)
uxname_list_temp <- list(u = tmp_X, X = tmp_X)
tmp_depth_est <- do.call(depth, c(uxname_list_temp, depth_params))
med <- tmp_X[tmp_depth_est == max(tmp_depth_est), ]
if ((length(med) / dim(X)[2]) != 1) {
med <- colMeans(med)
}
medians[i, ] <- med
} else {
vol[i] <- NA
alpha_est[i] <- NA
}
}
vol <- vol[!is.na(vol)]
alpha_est <- alpha_est[!is.na(alpha_est)]
means <- matrix(means[!is.na(means)], ncol = dim_X)
medians <- matrix(medians[!is.na(medians)], ncol = dim_X)
k <- length(vol)
n <- (means - medians)
nn <- 2 * sqrt(rowSums(n ^ 2)) / (vol ^ (1 / dim_X))
matrix(c(rev(1 - alpha_est), rev(nn)), ncol = 2)
}
|
auto_annotate <- function(dna_seg, locus_tag_pattern=NULL, names=dna_seg$gene,
keep_genes_only=TRUE, ...){
nr <- nrow(dna_seg)
if (is.null(names) || length(names) != nr)
stop("names should be of the same length as dna_seg")
idx <- rep(TRUE, nr)
x1 <- middle(dna_seg)
x2 <- rep(NA, nr)
last_num <- numeric(nr)
last_char_idx <- numeric(nr)
prefix <- character(nr)
for (i in 1:nr){
if (names[i] == "-" || names[i] == ""){
if (keep_genes_only){
idx[i] <- FALSE
} else if (!is.null(locus_tag_pattern)
&& is.character(locus_tag_pattern)) {
names[i] <- gsub(paste("^", locus_tag_pattern, "0+(.*)", sep=""),
"\\1", dna_seg$name[i], ignore.case=TRUE)
} else {
names[i] <- dna_seg$name[i]
}
} else {
type <- NA
if (length(grep("[A-Z]$", names[i])) > 0){
last_char_idx[i] <- which(LETTERS == gsub(".*(.$)", "\\1", names[i]))
prefix[i] <- gsub("^(.*).$", "\\1", names[i])
} else if (length(grep("\\d+$", names[i])) > 0){
ln <- gsub("^\\D*(\\d+$)", "\\1", names[i])
last_num[i] <- if (ln != names[i]) ln else 0
prefix[i] <- gsub("^(\\D+)\\d+$", "\\1", names[i])
}
}
}
last_num <- as.numeric(last_num)
series_idx <- numeric(0)
series_dir <- 0
series_type <- ""
for (i in 1:(nr+1)){
break_me <- FALSE
if (i <= nr && nchar(prefix[i]) > 0 &&
(last_char_idx[i] > 0 || last_num[i] > 0)){
valid <- TRUE
curr_type <- if (last_num[i] > 0) "num" else "char"
if (length(series_idx) > 0){
if (prefix[i] == prefix[series_idx[1]] && curr_type == series_type){
if (series_dir != 0){
if ((series_type == "num" &&
last_num[i-1] + series_dir == last_num[i]) ||
(series_type == "char" &&
last_char_idx[i-1] + series_dir == last_char_idx[i])){
} else {
break_me <- TRUE
}
} else {
dif <- ifelse(series_type == "num", last_num[i] - last_num[i-1],
last_char_idx[i] - last_char_idx[i-1])
if (abs(dif) == 1){
series_dir <- dif
} else {
break_me <- TRUE
}
}
} else {
break_me <- TRUE
}
} else {
series_type <- if (last_num[i] > 0) "num" else "char"
}
} else {
break_me <- TRUE
valid <- FALSE
}
if (break_me || i > nr){
if (length(series_idx) > 1){
idx[series_idx[2:length(series_idx)]] <- FALSE
x1[series_idx[1]] <- dna_seg$start[series_idx[1]]
x2[series_idx[1]] <- dna_seg$end[series_idx[length(series_idx)]]
suffices <- if(series_type == "num") {
last_num[series_idx]
} else {
LETTERS[last_char_idx[series_idx]]
}
names[series_idx[1]] <- paste(prefix[series_idx[1]], suffices[1], "-",
suffices[length(suffices)], sep="")
} else {
}
series_dir <- 0
if (valid){
series_idx <- i
series_type <- curr_type
} else {
series_idx <- numeric(0)
series_type <- ""
}
} else {
series_idx <- c(series_idx, i)
}
}
annots <- annotation(x1=x1, x2=x2, text=names, ...)
annots[idx,]
}
|
head(england)
tail(england)
library(tidyverse)
df <- england %>% filter(Season>2014)
table(df$tier, df$Season)
year_links <- c("https://www.11v11.com/competitions/premier-league/2020/",
"https://www.11v11.com/competitions/league-championship/2020/",
"https://www.11v11.com/competitions/league-one/2020/",
"https://www.11v11.com/competitions/league-two/2020/")
league_data <- lapply(year_links[4], function(link) {
league_season <- as.numeric(gsub(".*\\/", "", gsub("\\/$", "", link))) - 1
if(grepl("premier-league", link)) {
division <- 1
}
if(grepl("championship", link)) {
division <- 2
}
if(grepl("league-one", link)) {
division <- 3
}
if(grepl("league-two", link)) {
division <- 4
}
match_links <- read_html(paste0(link, "matches/")) %>%
html_nodes(".score a") %>%
html_attr("href") %>%
paste0("https://www.11v11.com", .) %>%
unlist() %>%
unique()
data <- lapply(match_links, get_league_match_data, league_season = league_season, division = division) %>%
do.call(rbind, .)
}) %>%
do.call(rbind, .)
head(league_data)
str(league_data)
i <- sapply(league_data, is.factor)
league_data[i] <- lapply(league_data[i], as.character)
str(league_data)
league_data %>%
mutate(home = case_when(
grepl("Brighton and Hove", home) ~ "Brighton & Hove Albion",
grepl("Cheltenham Town", home) ~ "Cheltenham",
grepl("Stevenage", home) ~ "Stevenage Borough",
grepl("Macclesfield Town", home) ~ "Macclesfield",
grepl("Yeovil", home) ~ "Yeovil",
TRUE ~ home
)) %>%
mutate(visitor = case_when(
grepl("Brighton and Hove", visitor) ~ "Brighton & Hove Albion",
grepl("Cheltenham Town", visitor) ~ "Cheltenham",
grepl("Stevenage", visitor) ~ "Stevenage Borough",
grepl("Macclesfield Town", visitor) ~ "Macclesfield",
grepl("Yeovil", visitor) ~ "Yeovil",
TRUE ~ visitor
)) -> league_data
head(league_data)
tail(league_data)
str(england)
str(tier1)
str(tier2)
str(tier3)
str(tier4)
tier1$Date<-as.character(tier1$Date)
tier2$Date<-as.character(tier2$Date)
tier3$Date<-as.character(tier3$Date)
tier4$Date<-as.character(tier4$Date)
tiers <- rbind(tier1,tier2,tier3,tier4)
england <- rbind(england,tiers)
usethis::use_data(england, overwrite = T)
write.csv(england,'data-raw/england.csv',row.names=F)
devtools::load_all()
get_league_match_data <- function(link, league_season, division) {
check <<- link
read <- read_html(link)
date <- read %>%
html_nodes("h1") %>%
html_text() %>%
gsub(".*, ", "", .) %>%
as.Date(., "%d %B %Y")
season <- league_season
division <- division
tier <- division
home <- read %>%
html_nodes(".home .teamname a") %>%
html_text()
visitor <- read %>%
html_nodes(".away .teamname a") %>%
html_text()
hgoal <- read %>%
html_nodes(".home .score") %>%
html_text() %>%
gsub(" \\(.*", "", .) %>%
as.numeric()
vgoal <- read %>%
html_nodes(".away .score") %>%
html_text() %>%
gsub(" \\(.*", "", .) %>%
as.numeric()
FT <- paste0(hgoal, "-", vgoal)
if(hgoal == vgoal) {
result = "D"
} else {
if(hgoal > vgoal) {
result = "H"
} else {
result = "A"
}
}
data <- data.frame(Date = date, Season = season,
home = home, visitor = visitor,
FT = FT,
hgoal = hgoal, vgoal = vgoal,
division = division, tier = tier,
totgoal = hgoal+vgoal,
goaldif = hgoal - vgoal,
result = result
)
}
|
calc_WodaFuchs2008 <- function(
data,
breaks = NULL,
plot = TRUE,
...
) {
if(is(data, "RLum.Results") == FALSE &
is(data, "data.frame") == FALSE &
is.numeric(data) == FALSE) {
warning(paste("[calc_WodaFuchs()] Input data format is neither",
"'data.frame', 'RLum.Results' nor 'numeric'.",
"No output generated!"))
return(NULL)
} else {
if(is(data, "RLum.Results") == TRUE) {
data <- get_RLum(data, "data")
}
if(length(data) < 2) {
data <- cbind(data,
rep(x = NA,
times = length(data)))
}
}
if("trace" %in% names(list(...))) {
trace <- list(...)$trace
} else {
trace <- FALSE
}
if(sum(is.na(data[,2]) == nrow(data))) {
message("[calc_WodFuchs2008()] No errors provided. Bin width set by 10 percent of input data!")
bin_width <- median(data[,1] / 10,
na.rm = TRUE)
} else {
bin_width <- median(data[,2],
na.rm = TRUE)
}
if(is.null(breaks)) {
n_breaks <- (max(data[,1],
na.rm = TRUE) -
min(data[,1],
na.rm = TRUE) / bin_width)
} else {
n_breaks <- breaks
}
H <- hist(x = data[,1],
breaks = n_breaks,
plot = FALSE)
if(n_breaks <= 3) {
warning("[calc_WodaFuchs()] Less than four bins, now set to four!")
H <- hist(x = data[,1],
breaks = 4,
plot = FALSE)
}
H_c <- H$counts
H_m <- H$mids
counts_log <- log(H_c)
curvature <- (counts_log[1] - counts_log[2]) /
(counts_log[1] - counts_log[3])
class_center <- H$mids[H_c == max(H_c)]
if(length(class_center) != 1) {
warning("[calc_WodaFuchs()] More than one maximum. Fit may be invalid!", call. = FALSE)
class_center <- class_center[1]
}
fit <- nls(H_c ~ (A / sqrt(2 * pi * sigma^2)) *
exp(-(H_m - class_center)^2 / (2 * sigma^2)),
start = c(A = mean(H_m),
sigma = bin_width),
control = c(maxiter = 5000),
algorithm = "port",
trace = trace)
A <- coef(fit)["A"]
sigma <- coef(fit)["sigma"]
D_estimate <- as.numeric(x = class_center - sigma)
count_ID <- length(which(H_m <= class_center))
H_m_smaller <- H_m[1:count_ID]
s <- round(sqrt(sum((H_m_smaller - D_estimate)^2) / (count_ID - 1)),
digits = 2)
if(plot) {
plot_settings <- list(
xlab = expression(paste(D[e], " [s]")),
ylab = "Frequency",
xlim = range(data[,1], na.rm = TRUE) + c(-10, 20),
ylim = NULL,
main = expression(paste(D[e]," applying Woda and Fuchs (2008)")),
sub = NULL
)
plot_settings <- modifyList(x = plot_settings, val = list(...), keep.null = TRUE)
plot(
x = H,
xlab = plot_settings$xlab,
ylab = plot_settings$ylab,
xlim = plot_settings$xlim,
ylim = plot_settings$ylim,
main = plot_settings$main,
sub = plot_settings$sub
)
x <- 0
rm(x)
curve((A / sqrt(2 * pi * sigma^2)) * exp(-(x- class_center)^2 / (2 * sigma^2)),
add = TRUE,
to = class_center,
col = "red"
)
}
return(set_RLum(
class = "RLum.Results",
data = list(
D_estimate = data.frame(
DP = D_estimate,
DP.ERROR = s,
CLASS_CENTER = class_center,
BIN_WIDTH = bin_width,
SIGMA = sigma,
A = A,
row.names = NULL
),
breaks = H$breaks
),
info = list(call = sys.call())
))
}
|
"who0607"
|
KernelESBoxKernel <- function(Ra, cl){
PandL <- as.vector(Ra)
n <- 1000
delta.cl <- (1 - cl) / n
VaR <- double(999)
for (i in 1:(n - 1)) {
if(i<(n-1)){
VaR[i] <- KernelVaRBoxKernel(PandL, cl + i * delta.cl, FALSE)
} else if (i == n-1) {
VaR[i] <- KernelVaRBoxKernel(PandL, cl + i * delta.cl, TRUE)
}
}
ES <- mean(VaR)
return(ES)
}
|
GiniIndex= function(Data,p){
V= ABCcurve(Data,p)
ABCx=V$Curve[,1]
ABCy=V$Curve[,2]
Gini = Gini4ABC(ABCx,ABCy )
if(missing(p)) p=ABCx
return(list(Gini=Gini,p=p,ABC=ABCy,CleanedData=V$CleanedData))
}
|
context("Population Transformation (function)")
test_that("setup function", {
simulator <- SimulatorReference$new()
transformation_function <- population_transformation(replicates = 4, time_steps = 10, years_per_step = 1,
populations = 7, demographic_stochasticity = TRUE,
density_stages = c(0, 1, 1),
transformation = function(params) 0.33,
simulator)
expect_is(transformation_function, "function")
expect_named(formals(transformation_function), c("r", "tm", "carrying_capacity", "stage_abundance", "occupied_indices"))
expect_named(environment(transformation_function)[["params"]],
c("replicates", "time_steps", "years_per_step", "populations", "stages", "demographic_stochasticity",
"density_stages", "simulator"))
expect_equal(environment(transformation_function)[["params"]][c("replicates", "time_steps", "years_per_step",
"populations", "stages", "demographic_stochasticity",
"density_stages")],
list(replicates = 4, time_steps = 10, years_per_step = 1, populations = 7, stages = 3,
demographic_stochasticity = TRUE, density_stages = c(0, 1, 1)))
transformation_function <- population_transformation(replicates = 4, time_steps = 10, years_per_step = 1,
populations = 7, demographic_stochasticity = TRUE,
density_stages = c(0, 1, 1),
transformation = list(a = 1, function(params) 0.33, b = 2),
simulator)
expect_is(transformation_function, "function")
expect_named(environment(transformation_function)[["params"]],
c("replicates", "time_steps", "years_per_step", "populations", "stages", "demographic_stochasticity",
"density_stages", "simulator", "a", "b"))
expect_equal(environment(transformation_function)[["params"]][c("a", "b")], list(a = 1, b = 2))
})
test_that("user-defined transformation", {
simulator <- SimulatorReference$new()
test_function_1 <- function(params) {
params$simulator$attached$params <- params
extra_stage_abundance <- params$stage_abundance
extra_stage_abundance[which(params$density_stages > 0), params$occupied_indices] <-
extra_stage_abundance[which(params$density_stages > 0), params$occupied_indices] + 1
return(extra_stage_abundance)
}
transformation_function <- population_transformation(replicates = 4, time_steps = 10, years_per_step = 1,
populations = 7, demographic_stochasticity = TRUE,
density_stages = c(0, 1, 1),
transformation = list(a = 1, test_function_1, b = 2),
simulator)
carrying_capacity <- rep(10, 7)
stage_abundance <- matrix(c(7, 13, 0, 26, 0, 39, 47,
2, 0, 6, 8, 0, 12, 13,
0, 3, 4, 6, 0, 9, 10), nrow = 3, ncol = 7, byrow = TRUE)
occupied_indices <- (1:7)[-5]
expected_stage_abundance <- stage_abundance
expected_stage_abundance[2:3, (1:7)[-5]] <- expected_stage_abundance[2:3, (1:7)[-5]] + 1
expect_equal(transformation_function(r = 2, tm = 6, carrying_capacity, stage_abundance, occupied_indices),
list(stage_abundance = expected_stage_abundance))
expect_named(simulator$attached$params, c("replicates", "time_steps", "years_per_step", "populations", "stages",
"demographic_stochasticity", "density_stages", "simulator", "a", "b", "r",
"tm", "carrying_capacity", "stage_abundance", "occupied_indices"))
expect_equal(simulator$attached$params[c("a", "b", "r", "tm", "carrying_capacity", "stage_abundance", "occupied_indices")],
list(a = 1, b = 2, r = 2, tm = 6, carrying_capacity = carrying_capacity,
stage_abundance = stage_abundance, occupied_indices = occupied_indices))
test_function_2 <- function(params) {
extra_stage_abundance <- params$stage_abundance
extra_stage_abundance[which(params$density_stages > 0), params$occupied_indices] <-
extra_stage_abundance[which(params$density_stages > 0), params$occupied_indices] + 1
return(list(stage_abundance = extra_stage_abundance, carrying_capacity = params$carrying_capacity + 10))
}
transformation_function <- population_transformation(replicates = 4, time_steps = 10, years_per_step = 1,
populations = 7, demographic_stochasticity = TRUE,
density_stages = c(0, 1, 1),
transformation = list(a = 1, test_function_2, b = 2),
simulator)
expect_equal(transformation_function(r = 2, tm = 6, carrying_capacity, stage_abundance, occupied_indices),
list(stage_abundance = expected_stage_abundance, carrying_capacity = carrying_capacity + 10))
test_function = function (params) stop("test error")
transformation_function <- population_transformation(replicates = 4, time_steps = 10, years_per_step = 1,
populations = 7, demographic_stochasticity = TRUE,
density_stages = c(0, 1, 1),
transformation = list(a = 1, test_function, b = 2),
simulator)
expect_error(transformation_function(r = 2, tm = 6, carrying_capacity, stage_abundance, occupied_indices),
"Error produced within user-defined transformation function")
test_function <- function(params) params$stage_abundance
transformation_function <- population_transformation(replicates = 4, time_steps = 10, years_per_step = 1,
populations = 7, demographic_stochasticity = TRUE,
density_stages = c(0, 1, 1),
transformation = list(a = 1, test_function, b = 2),
simulator, name = "test_transf")
stage_abundance[1] <- NA
expect_warning(transformation_function(r = 2, tm = 6, carrying_capacity, stage_abundance, occupied_indices),
"Non-finite stage abundances returned by user-defined test_transf function")
stage_abundance[2] <- -1
expect_warning(transformation_function(r = 2, tm = 6, carrying_capacity, stage_abundance, occupied_indices),
"Negative stage abundances returned by user-defined test_transf function")
test_function <- function(params) list(stage_abundance = params$stage_abundance, carrying_capacity = params$carrying_capacity)
transformation_function <- population_transformation(replicates = 4, time_steps = 10, years_per_step = 1,
populations = 7, demographic_stochasticity = TRUE,
density_stages = c(0, 1, 1),
transformation = list(a = 1, test_function, b = 2),
simulator, name = "test_transf")
carrying_capacity[1:2] <- c(NA, -10)
expect_warning(transformation_function(r = 2, tm = 6, carrying_capacity, stage_abundance, occupied_indices),
"Non-finite carrying capacities returned by user-defined test_transf function")
expect_warning(transformation_function(r = 2, tm = 6, carrying_capacity, stage_abundance, occupied_indices),
"Negative carrying capacities returned by user-defined test_transf function")
})
|
expected <- eval(parse(text="c(0.5, -0.5)"));
test(id=0, code={
argv <- eval(parse(text="list(0.5, -0.5)"));
do.call(`:`, argv);
}, o=expected);
|
library(otvPlots)
context("Run the main function: vlm")
drugSASDate <- read.csv("../testthat/drugSASDate.csv")
test_that("At most one of sortVars and sortFn is passed in", {
expect_error(vlm(dataFl = "../testthat/drugSASDate.csv",
dateNm = "date", sortVars = c("age", "residencecity")))
})
test_that("varNms is a subset of sortVars", {
expect_error(vlm(dataFl = drugSASDate, dateNm = "date",
sortVars = c("age", "residencecity"), varNms = c("age")))
})
test_that("Incorrect file input when prepData is False", {
expect_error(vlm(dataFl = "../testthat/drugRDate.csv", dateNm = "date",
prepData = FALSE))
})
test_that("selectCols and dropCols together give an error", {
expect_error(vlm("../testthat/rawData.csv", dateNm = "date", weightNm = "weight",
dateGp = "weeks", dateGpBp = "weeks", dateFt = "%d-%m-%Y",
selectCols = c("age", "balance", "date", "weight"),
dropCols = c("default"), varNms = c("age")))
expect_error(vlm("../testthat/rawData.rda", dateNm = "date", weightNm = "weight",
dateGp = "weeks", dateGpBp = "weeks", dateFt = "%d-%m-%Y",
selectCols = c("age", "balance", "date", "weight"),
dropCols = c("default")))
})
|
print.maxlikeFit <- function(x, ...) {
converge <- x$optim$converge
cat("\nCall:", paste(deparse(x$call)), "\n\n")
cat("Coefficients:\n")
print(x$Est, ...)
cat("\nAIC:", x$AIC, "\n\n")
if(converge != 0)
warning("Model did not converge")
}
coef.maxlikeFit <- function(object, ...) object$Est[,"Est"]
vcov.maxlikeFit <- function(object, ...) object$vcov
summary.maxlikeFit <- function(object, digits=3, ...) {
s <- object$Est
z <- s[,"Est"] / s[,"SE"]
p <- 2*pnorm(abs(z), lower.tail = FALSE)
s <- cbind(s, z=z, "P(>|z|)"=p)
converge <- object$optim$converge
cat("\nCall:", paste(deparse(object$call)), "\n", fill=TRUE)
cat("Coefficients:\n")
print(s, digits=digits, ...)
cat("\noptim convergence code:", converge, "\n")
cat("\nAIC:", object$AIC, "\n\n")
if(converge != 0)
warning("Model did not converge")
invisible(s)
}
logLik.maxlikeFit <- function(object, ...) {
-object$optim$value
}
AIC.maxlikeFit <- function(object, ..., k=2) {
2*object$optim$value + k*length(coef(object)[object$not.fixed])
}
predict.maxlikeFit <- function(object, newdata=NULL, ...) {
e <- coef(object)
if (is.null(newdata) == F) {
if ("RasterStack" %in% class(newdata)) {
rasters <- newdata
cd.names <- names(newdata)
npix <- prod(dim(newdata)[1:2])
z <- as.data.frame(matrix(getValues(newdata), npix))
names(z) <- cd.names
}else{
z <- newdata
}
cd.names <- names(z)
}else{
rasters <- object$rasters
if(is.null(rasters)) {
rasters <- try(get(as.character(object$call$rasters)))
if(identical(class(rasters)[1], "try-error"))
stop("could not find the raster data")
warning("raster data were not saved with object, using the data found in the workspace instead.")
}
cd.names <- names(rasters)
npix <- prod(dim(rasters)[1:2])
z <- as.data.frame(matrix(getValues(rasters), npix))
names(z) <- cd.names
}
formula <- object$call$formula
varnames <- all.vars(formula)
if(!all(varnames %in% cd.names)) {
if (is.null(newdata) == F) {
stop("at least 1 covariate in the formula is not in new data")
}else{
stop("at least 1 covariate in the formula is not in rasters")
}
}
Z.mf <- model.frame(formula, z, na.action="na.pass")
Z.terms <- attr(Z.mf, "terms")
Z <- model.matrix(Z.terms, Z.mf)
eta <- drop(Z %*% coef(object))
link <- object$link
if(identical(link, "logit"))
psi.hat <- plogis(eta)
else if(identical(link, "cloglog"))
psi.hat <- 1-exp(-exp(eta))
else
stop("link function should be either 'logit' or 'cloglog'")
if (is.null(newdata) == F && ("RasterStack" %in% class(newdata)) == F) {
return(psi.hat)
}else{
psi.mat <- matrix(psi.hat, dim(rasters)[1], dim(rasters)[2], byrow=TRUE)
psi.raster <- raster(psi.mat)
extent(psi.raster) <- extent(rasters)
return(psi.raster)
}
}
|
data_dir <- file.path("..", "testdata")
tempfile_nc <- function() {
tempfile_helper("selmon_")
}
file_in <- file.path(data_dir, "ex_normal1.nc")
file_out <- tempfile_nc()
selmon("SIS", 1, file_in, file_out)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp1 <- seq(250, 272)
expected_data <- c(temp1, temp1, temp1[1:3])
expected <- array(expected_data, dim = c(7, 7))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
actual <- ncatt_get(file, "SIS", "standard_name")$value
expect_equal(actual, "SIS_standard")
actual <- ncatt_get(file, "SIS", "long_name")$value
expect_equal(actual, "Surface Incoming Shortwave Radiation")
actual <- ncatt_get(file, "SIS", "units")$value
expect_equal(actual, "W m-2")
actual <- ncatt_get(file, "SIS", "_FillValue")$value
expect_equal(actual, -999)
actual <- ncatt_get(file, "SIS", "cmsaf_info")$value
expect_equal(actual, "cmsafops::selmon for variable SIS")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
cat(actual)
expect_equal(actual, array(c(149016)))
})
nc_close(file)
file_in <- file.path(data_dir, "ex_normal1.nc")
file_out <- tempfile_nc()
selmon("SIS", 1, file_in, file_out, nc34 = 4)
file <- nc_open(file_out)
test_that("data is correct in version 4", {
actual <- ncvar_get(file)
temp1 <- seq(250, 272)
expected_data <- c(temp1, temp1, temp1[1:3])
expected <- array(expected_data, dim = c(7, 7))
expect_equivalent(actual, expected)
})
test_that("attributes are correct in version 4", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct in version 4", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016)))
})
nc_close(file)
file_in <- file.path(data_dir, "ex_normal1.nc")
file_out <- tempfile_nc()
test_that("error is thrown if ncdf version is wrong", {
expect_error(
selmon("SIS", 1, file_in, file_out, nc34 = 7),
"nc version must be in c(3, 4), but was 7", fixed = TRUE
)
})
file_in <- file.path(data_dir, "ex_normal1.nc")
file_out <- tempfile_nc()
test_that("ncdf version NULL throws an error", {
expect_error(
selmon("SIS", 1, file_in, file_out, nc34 = NULL),
"nc_version must not be NULL"
)
})
file_in <- file.path(data_dir, "ex_normal1.nc")
file_out <- tempfile_nc()
test_that("warning is shown if var does not exist", {
expect_warning(
selmon("lat", 1, file_in, file_out),
"Variable 'lat' not found. Variable 'SIS' will be used instead."
)
})
file <- nc_open(file_out)
test_that("data is correct if non-existing variable is given", {
actual <- ncvar_get(file)
temp1 <- seq(250, 272)
expected_data <- c(temp1, temp1, temp1[1:3])
expected <- array(expected_data, dim = c(7, 7))
expect_equivalent(actual, expected)
})
test_that("attributes are correct if non-existing variable is given", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct if non-existing variable is given", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016)))
})
nc_close(file)
file_in <- file.path(data_dir, "ex_normal1.nc")
file_out <- tempfile_nc()
test_that("error is thrown if variable is NULL", {
expect_error(
selmon(NULL, 1, file_in, file_out),
"variable must not be NULL"
)
})
file_in <- file.path(data_dir, "ex_normal1.nc")
file_out <- tempfile_nc()
test_that("warning is shown if var is empty", {
expect_warning(
selmon("", 1, file_in, file_out),
"Variable '' not found. Variable 'SIS' will be used instead."
)
})
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp1 <- seq(250, 272)
expected_data <- c(temp1, temp1, temp1[1:3])
expected <- array(expected_data, dim = c(7, 7))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016)))
})
nc_close(file)
file_in <- file.path(data_dir, "xex_normal1.nc")
file_out <- tempfile_nc()
test_that("error is thrown if input file does not exist", {
expect_error(
selmon("SIS", 1, file_in, file_out),
"Input file does not exist")
})
file_in <- file.path(data_dir, NULL)
file_out <- tempfile_nc()
test_that("error is thrown if input filename is NULL", {
expect_error(
selmon("SIS", 1, file_in, file_out),
"Input filepath must be of length one and not NULL"
)
})
file_in <- file.path(data_dir, "ex_normal1.nc")
file_out <- tempfile_nc()
cat("test\n", file = file_out)
test_that("error is thrown if output file already exists", {
expect_error(
selmon("SIS", 1, file_in, file_out),
paste0("File '",
file_out,
"' already exists. Specify 'overwrite = TRUE' if you want to overwrite it."),
fixed = TRUE
)
expect_equal(readLines(con = file_out), "test")
})
file_in <- file.path(data_dir, "ex_normal1.nc")
file_out <- tempfile_nc()
cat("test\n", file = file_out)
test_that("no error is thrown if overwrite = TRUE", {
expect_error(
selmon("SIS", 1, file_in, file_out, overwrite = TRUE),
NA)
})
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp1 <- seq(250, 272)
expected_data <- c(temp1, temp1, temp1[1:3])
expected <- array(expected_data, dim = c(7, 7))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016)))
})
nc_close(file)
file_in <- file.path(data_dir, "ex_time_dim1.nc")
file_out <- tempfile_nc()
selmon("SIS", 1, file_in, file_out)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp1 <- seq(250, 272)
expected_data <- c(temp1, temp1, temp1[1:3])
expected <- array(expected_data, dim = c(7, 7))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016)))
})
nc_close(file)
file_in <- file.path(data_dir, "ex_time_dim1.nc")
file_out <- tempfile_nc()
selmon("SIS", 2, file_in, file_out)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp1 <- seq(250, 272)
expected_data <- c(temp1[4:length(temp1)], temp1, temp1[1:6])
expected <- array(expected_data, dim = c(7, 7))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(158544)))
})
nc_close(file)
file_in <- file.path(data_dir, "ex_time_dim1.nc")
file_out <- tempfile_nc()
selmon("SIS", c(1, 2), file_in, file_out)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp1 <- seq(250, 272)
expected_data <- c(rep(temp1, 4), temp1[1:6])
expected <- array(expected_data, dim = c(7, 7, 2))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016, 158544)))
})
nc_close(file)
file_in <- file.path(data_dir, "ex_time_dim1.nc")
file_out <- tempfile_nc()
test_that("no error is thrown if output file already exists", {
expect_error(
selmon("SIS", 3, file_in, file_out),
"No match. Months are: 1")
})
file_in <- file.path(data_dir, "ex_additional_attr.nc")
file_out <- tempfile_nc()
selmon("SIS", 1, file_in, file_out)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp1 <- seq(250, 272)
temp2 <- seq(230, 252)
expected_data <- c(temp1, temp1, temp1[1:3])
expected <- array(expected_data, dim = c(7, 7))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 2)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
actual <- names(global_attr[2])
expect_equal(actual, "institution")
actual <- global_attr[[2]]
expect_equal(actual, "This is a test attribute.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016)))
})
nc_close(file)
file_in <- file.path(data_dir, "ex_v4_1.nc")
file_out <- tempfile_nc()
selmon("SIS", 1, file_in, file_out)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp1 <- seq(250, 272)
temp2 <- seq(230, 252)
expected_data <- c(temp1, temp1, temp1[1:3])
expected <- array(expected_data, dim = c(7, 7))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016)))
})
nc_close(file)
file_in <- file.path(data_dir, "ex_normal1.nc")
file_out <- tempfile_nc()
test_that("no error is thrown if output file already exists", {
expect_error(
selmon("SIS", 2, file_in, file_out),
"No match. Months are: 1")
})
file_in <- file.path(data_dir, "ex_normal1.nc")
file_out <- tempfile_nc()
test_that("no error is thrown if output file already exists", {
expect_error(
selmon("SIS", NULL, file_in, file_out),
"No match. Months are: 1")
})
|
Sys.unsetenv("CONTENTID_HOME")
Sys.unsetenv("CONTENTID_REGISTRIES")
|
gx.ks.test <-
function (xx1, xx2, xlab = " ", x1lab = deparse(substitute(xx1)),
x2lab = deparse(substitute(xx2)), ylab = "Empirical Cumulative Distribution Function",
log = FALSE, main = "", pch1 = 3, col1 = 2, pch2 = 4, col2 = 4,
ifresult = TRUE, cex = 0.8, cexp = 0.9, ...)
{
temp.x <- remove.na(xx1)
x1 <- sort(temp.x$x[1:temp.x$n])
nx1 <- temp.x$n
y1 <- ((1:nx1) - 0.5)/nx1
temp.x <- remove.na(xx2)
x2 <- sort(temp.x$x[1:temp.x$n])
nx2 <- temp.x$n
y2 <- ((1:nx2) - 0.5)/nx2
xlim <- range(c(x1, x2))
if (log) {
logx <- "x"
if (xlim[1] <= 0)
stop("\n Values cannot be .le. zero for a log plot\n")
}
else logx <- ""
plot(x1, y1, log = logx, xlim = xlim, xlab = xlab, ylab = ylab,
main = main, type = "n", ...)
points(x1, y1, pch = pch1, col = col1, cex = cexp)
points(x2, y2, pch = pch2, col = col2, cex = cexp)
temp <- ks.test(x1, x2)
print(temp)
if (ifresult) {
H0 <- "accept"
if (temp$p.value < 0.05)
H0 <- "reject"
text(locator(1), adj = c(0, 1), paste("Two-Sample Kolmogorov-Smirnov Test",
"\nH0: The two data sets are drawn\nfrom the same population\n",
"\np-value = ", signif(temp$p.value, 4), "\n", H0,
" H0 at 0.05 level", sep = ""), cex = cex)
}
label1 <- paste(x1lab, ", N = ", nx1, sep = "")
label2 <- paste(x2lab, ", N = ", nx2, sep = "")
legend(locator(1), c(label1, label2), pch = c(pch1, pch2),
col = c(col1, col2), bty = "n", cex = cex)
invisible()
}
|
"REcoData_Panel_UR"
|
log_Vnk_PY <- function(n, k, Alpha, Gama) {
if (k == 1) {
lognum <- 0
}
else {
lognum <- sum(log(Alpha + Gama * 1:(k - 1)))
}
return(lognum - sum(log(Alpha + 1 + 0:(n - 2))))
}
Cnk <- function(n, k, Gama) {
factor_k <- gmp::factorialZ(k)
sum((-1)^(1:k) * gmp::chooseZ(n = k, k = 1:k) * Rmpfr::pochMpfr(-(1:k) * Gama, n) / factor_k)
}
log_Cnk <- function(n, k, Gama) {
log(Cnk(n, k, Gama))
}
Pkn_PY <- function(k, n, Alpha, Gama, silence = TRUE) {
if (!silence) print(k)
exp(log_Vnk_PY(n = n, k = k, Alpha = Alpha, Gama = Gama) - k * log(Gama)) * Cnk(n = n, k = k, Gama = Gama)
}
Pkn_Dirichlet <- function(k, n, Alpha) {
exp(k * log(Alpha) + log(abs(gmp::Stirling1(n, k))) - sum(log(Alpha + 0:(n - 1))))
}
expected_number_of_components_PY <- function(n, Alpha, Gama, ntrunc = NULL, silence = TRUE) {
if (is.null(ntrunc)) {
ntrunc <- n
} else if (ntrunc > n) ntrunc <- n
res <- 0
for (k in 1:ntrunc) {
if (!silence) print(k)
res <- res + k * Pkn_PY(k, n, Alpha, Gama)
}
return(res)
}
expected_number_of_components_Dirichlet <- function(n, Alpha, ntrunc = NULL, silence = TRUE) {
if (is.null(ntrunc)) {
ntrunc <- n
} else if (ntrunc > n) ntrunc <- n
res <- 0
for (k in 1:ntrunc) {
if (!silence) print(k)
res <- res + k * Pkn_Dirichlet(k, n, Alpha)
}
return(res)
}
expected_number_of_components_stable <- function(n, Gama, ntrunc = NULL) {
if (!requireNamespace("Rmpfr", quietly = TRUE) && !requireNamespace("gmp", quietly = TRUE)) {
stop("Packages Rmpfr and gmp are needed for this function to work. Please install them.",
call. = FALSE
)
}
expected_number_of_components_PY(n, 0, Gama, ntrunc = ntrunc)
}
plot_prior_number_of_components <- function(n, Gama, Alpha = 1, grid = NULL, silence = TRUE) {
if (!requireNamespace("Rmpfr", quietly = TRUE) && !requireNamespace("gmp", quietly = TRUE)) {
stop("Packages Rmpfr and gmp are needed for this function to work. Please install them.",
call. = FALSE
)
}
if (is.null(grid)) grid <- 1:n
grid <- unique(round(grid))
writeLines("Computing the prior probability on the number of clusters for the Dirichlet process")
Pk_Dirichlet <- data.frame(K = grid, Pk = Vectorize(Pkn_Dirichlet, vectorize.args = "k")(grid, n, Alpha), Process = "Dirichlet")
writeLines("Computing the prior probability on the number of clusters for the Stable process")
Pk_Stable <- data.frame(K = grid, Pk = unlist(lapply(Vectorize(Pkn_PY, vectorize.args = "k")(grid, n, 0, Gama, silence), asNumeric_no_warning)), Process = "Stable")
Pk_Stable$Pk <- convert_nan_to_0(Pk_Stable$Pk)
to_plot <- rbind(
Pk_Dirichlet,
Pk_Stable
)
ggplot(data = to_plot, aes_string(x = "K", y = "Pk", colour = "factor(Process)", group = "Process")) +
geom_point() +
geom_line() +
theme_classic() +
viridis::scale_colour_viridis(discrete = T, name = "Process") +
ylab(expression(P[K]))
}
asNumeric_no_warning <- function(x) {
tryCatch(
{
Rmpfr::asNumeric(x)
},
warning = function(w) {
if (grepl(pattern = "inefficient", x = as.character(w))) {
suppressWarnings(Rmpfr::asNumeric(x))
}
else {
w
}
},
error = function(e) {
print(paste("error:", e))
}
)
}
|
"UPrandomsystematic" <-
function(pik,eps=1e-6)
{
if(any(is.na(pik))) stop("there are missing values in the pik vector")
N=length(pik)
v=sample.int(N,N)
s=numeric(N)
s[v]=UPsystematic(pik[v],eps)
s
}
|
calf_internal <- function(data,
nMarkers,
randomize = FALSE,
proportion = NULL,
times,
targetVector = "binary",
optimize = "pval",
verbose = FALSE){
x = NULL
y = NULL
refx = NULL
refy = NULL
if (targetVector == "nonbinary")
optimize <- NULL
if (any(apply(data, 2, is.numeric) == FALSE)) {
stop("CALF ERROR: Data are not numeric. Please check that data were read in correctly.")
}
nVars <- ncol(data) - 1
dNeg <- data[ ,2:ncol(data)]
dNeg <- dNeg * - 1
data <- data.frame(data, dNeg, check.names = FALSE)
if (nMarkers > nVars){
stop(paste0("CALF ERROR: Requested number of markers is larger than the number of markers in data set. ",
"Please revise this value or make sure your data were read in properly."))
}
if (randomize == TRUE) data[ ,1] <- sample(data[ ,1])
if (!is.null(proportion)) {
if (targetVector == "binary") {
ctrlRows <- which(data[ ,1] == 0)
caseRows <- which(data[ ,1] == 1)
if(length(proportion) == 2) {
nCtrlKeep <- round(length(ctrlRows)*proportion[1], digits = 0)
nCaseKeep <- round(length(caseRows)*proportion[2], digits = 0)
} else {
nCtrlKeep <- round(length(ctrlRows)*proportion, digits = 0)
nCaseKeep <- round(length(caseRows)*proportion, digits = 0)
}
keepRows <- c(sample(ctrlRows)[1:nCtrlKeep], sample(caseRows)[1:nCaseKeep])
data <- data[keepRows, ]
} else {
nDataKeep <- round(nrow(data)*proportion, digits = 0)
keepRows <- sample(1:nrow(data))[1:nDataKeep]
data <- data[keepRows, ]
}
}
real <- data[ ,1]
realMarkers <- data[ , 2:ncol(data)]
ctrl <- data[data[ ,1] == 0, 2:ncol(data)]
case <- data[data[ ,1] == 1, 2:ncol(data)]
indexNegPos <- rep(0, (nVars*2))
allCrit <- numeric()
for (i in 1:(nVars*2)){
if (targetVector == "binary"){
caseVar <- case[ ,i]
ctrlVar <- ctrl[ ,i]
if (optimize == "pval"){
crit <- t.test(caseVar, ctrlVar, var.equal = FALSE)$p.value
} else if (optimize == "auc"){
crit <- compute.auc(caseVar, ctrlVar)
crit <- 1/crit
}
} else {
realVar <- realMarkers[ ,i]
crit <- suppressWarnings(cor(real, realVar, use = "complete.obs"))
crit <- 1/crit
}
allCrit[i] <- crit
}
allCrit[allCrit < 0] <- NA
keepMarkers <- names(realMarkers)[which.min(allCrit)]
bestCrit <- min(allCrit, na.rm = TRUE)
keepIndex <- which.min(allCrit)
if (verbose == TRUE) {
if(targetVector == "binary") {
if (optimize == "pval"){
cat("Selected:", keepMarkers,
paste0("p value = ", round(bestCrit, digits = 15), "\n"))
} else if (optimize == "auc"){
cat("Selected:", keepMarkers,
paste0("AUC = ", round((1/bestCrit), digits = 15), "\n"))
}
} else if (targetVector == "nonbinary") {
cat("Selected:", keepMarkers,
paste0("Correlation = ", round((1/bestCrit), digits = 15), "\n"))
}
}
if (nMarkers != 1){
allCrit <- numeric()
realPrev <- realMarkers[ ,keepIndex]
casePrev <- case[ ,keepIndex]
ctrlPrev <- ctrl[ ,keepIndex]
for (i in 1:(nVars*2)){
if (i != keepIndex){
caseVar <- casePrev + case[ ,i]
ctrlVar <- ctrlPrev + ctrl[ ,i]
realVar <- realPrev + realMarkers[ ,i]
if (targetVector == "binary"){
if (optimize == "pval"){
crit <- t.test(caseVar, ctrlVar, var.equal = FALSE)$p.value
} else if (optimize == "auc"){
crit <- compute.auc(caseVar, ctrlVar)
crit <- 1/crit
}
} else {
crit <- suppressWarnings(cor(real, realVar, use = "complete.obs"))
crit <- 1/crit
}
} else {
crit <- NA
}
allCrit[i] <- crit
}
allCrit[allCrit < 0] <- NA
continue <- ifelse(bestCrit[length(bestCrit)] > min(allCrit, na.rm = TRUE), TRUE, FALSE)
if (continue == TRUE){
keepMarkers <- append(keepMarkers, names(realMarkers)[which.min(allCrit)])
bestCrit <- append(bestCrit, min(allCrit, na.rm = TRUE))
keepIndex <- append(keepIndex, which.min(allCrit))
if (length(keepMarkers) == nMarkers) continue <- FALSE
}
if (verbose == TRUE) {
if(targetVector == "binary") {
if (optimize == "pval"){
cat("Selected:", keepMarkers[length(keepMarkers)],
paste0("p value = ", round(bestCrit[length(bestCrit)], digits = 15), "\n"))
} else if (optimize == "auc"){
cat("Selected:", keepMarkers[length(keepMarkers)],
paste0("AUC = ", round((1/bestCrit[length(bestCrit)]), digits = 15), "\n"))
}
} else if (targetVector == "nonbinary") {
cat("Selected:", keepMarkers[length(keepMarkers)],
paste0("Correlation = ", round((1/bestCrit[length(bestCrit)]), digits = 15), "\n"))
}
}
while (continue == TRUE){
allCrit <- numeric()
casePrev <- rowSums(case[ ,keepIndex], na.rm = TRUE)
ctrlPrev <- rowSums(ctrl[ ,keepIndex], na.rm = TRUE)
realPrev <- rowSums(realMarkers[ ,keepIndex], na.rm = TRUE)
for (i in 1:(nVars*2)){
if (!(i %in% keepIndex)){
caseVar <- casePrev + case[ ,i]
ctrlVar <- ctrlPrev + ctrl[ ,i]
realVar <- realPrev + realMarkers[ ,i]
if (targetVector == "binary"){
if (optimize == "pval"){
crit <- t.test(caseVar, ctrlVar, var.equal = FALSE)$p.value
} else if (optimize == "auc"){
crit <- compute.auc(caseVar, ctrlVar)
crit <- 1/crit
}
} else {
crit <- suppressWarnings(cor(real, realVar, use = "complete.obs"))
crit <- 1/crit
}
} else {
crit <- NA
}
allCrit[i] <- crit
}
allCrit[allCrit < 0] <- NA
continue <- ifelse(bestCrit[length(bestCrit)] > min(allCrit, na.rm = TRUE),
TRUE, FALSE)
if (continue == TRUE){
keepMarkers <- append(keepMarkers, names(realMarkers)[which.min(allCrit)])
bestCrit <- append(bestCrit, min(allCrit, na.rm = TRUE))
keepIndex <- append(keepIndex, which.min(allCrit))
continue <- bestCrit[length(bestCrit)] < bestCrit[length(bestCrit)-1]
if (verbose == TRUE) {
if(targetVector == "binary") {
if (optimize == "pval"){
cat("Selected:", keepMarkers[length(keepMarkers)],
paste0("p value = ", round(bestCrit[length(bestCrit)], digits = 15), "\n"))
} else if (optimize == "auc"){
cat("Selected:", keepMarkers[length(keepMarkers)],
paste0("AUC = ", round((1/bestCrit[length(bestCrit)]), digits = 15), "\n"))
}
} else if (targetVector == "nonbinary") {
cat("Selected:", keepMarkers[length(keepMarkers)],
paste0("Correlation = ", round((1/bestCrit[length(bestCrit)]), digits = 15), "\n"))
}
}
}
if (length(keepMarkers) == nMarkers) continue <- FALSE
}
}
if (verbose == TRUE) cat("\n")
indexNegPos[keepIndex] <- ifelse(keepIndex > nVars, -1, 1)
finalIndex <- ifelse(keepIndex <= nVars, keepIndex, keepIndex - nVars)
finalMarkers <- data.frame(names(case)[finalIndex], indexNegPos[keepIndex], check.names = FALSE)
names(finalMarkers) <- c("Marker","Weight")
if (targetVector == "nonbinary" || optimize == "auc") {
finalBestCrit <- 1 / bestCrit[length(bestCrit)]
} else {
finalBestCrit <- bestCrit[length(bestCrit)]
}
if (targetVector == "binary"){
if (nMarkers != 1 & length(keepIndex) != 1){
funcValue <- c(rowSums(case[,c(keepIndex)]), rowSums(ctrl[,c(keepIndex)]))
} else {
funcValue <- c(case[,c(keepIndex)], ctrl[,c(keepIndex)])
}
funcValue <- round(funcValue, digits = 8)
ranks <- rank(funcValue, ties.method = "average")
seqCaseCtrl <- c(rep(1, nrow(case)), rep(0, nrow(ctrl)))
all <- data.frame(funcValue,
seqCaseCtrl,
ranks)
all <- all[order(all$ranks),]
all$refx <- seq(0,1,1/(nrow(all)-1))
all$refy <- seq(0,1,1/(nrow(all)-1))
initVal <- all$seqCaseCtrl[1]
moveRight <- ifelse(initVal == 0, nrow(case), nrow(ctrl))
moveUp <- ifelse(initVal == 0, nrow(ctrl), nrow(case))
for (i in 2:nrow(all)){
all$x[1] <- 0
all$y[1] <- 0
if (all$seqCaseCtrl[i] == initVal){
all$x[i] = all$x[i-1]
all$y[i] = all$y[i-1] + 1/(moveUp-1)
} else {
all$x[i] = all$x[i-1] + 1/(moveRight)
all$y[i] = all$y[i-1]
}
}
n <- round(length(all$refy)/2, digits = 0)
if (all$refy[n] > all$y[n]){
all$a <- all$x
all$b <- all$y
all$x <- all$b
all$y <- all$a
}
rocPlot <- ggplot(all, aes(x = x, y = y)) +
geom_line(size = 1) +
geom_line(aes(x = refx, y = refy, colour = "red"), size = 1.5) +
scale_x_continuous(limits = c(0,1)) +
theme_bw() +
theme(legend.position = "none") +
ylab("True Positive Rate (Sensitivity)") +
xlab("False Positive Rate (1 - Specificity)")
caseFunc <- sum(ranks[1:nrow(case)]) - nrow(case)*(nrow(case)+1)/2
ctrlFunc <- sum(ranks[(nrow(case)+1):length(ranks)]) - nrow(ctrl)*(nrow(ctrl)+1)/2
auc <- round(max(ctrlFunc, caseFunc)/(caseFunc + ctrlFunc), digits = 4)
} else {
auc <- NULL
rocPlot <- NULL
}
est <- list(selection = finalMarkers,
auc = auc,
randomize = randomize,
proportion = proportion,
targetVec = targetVector,
rocPlot = rocPlot,
finalBest = finalBestCrit,
optimize = optimize)
class(est) <- "calf"
return(est)
}
compute.auc <- function(caseVar, ctrlVar){
funcValue <- c(caseVar, ctrlVar)
funcValue <- round(funcValue, digits = 8)
ranks <- rank(funcValue, ties.method = "average")
caseFunc <- sum(ranks[1:length(caseVar)]) - length(caseVar)*(length(caseVar)+1)/2
ctrlFunc <- sum(ranks[(length(caseVar)+1):length(ranks)]) - length(ctrlVar)*(length(ctrlVar)+1)/2
auc <- round(max(ctrlFunc, caseFunc)/(caseFunc + ctrlFunc), digits = 4)
return(auc)
}
|
lambda1_calculator <- function(dat_l, dim, nclust, nboot = 1000, alpha1 = 0.5,
delta =0.0000001){
temp_mat <- matrix(unlist(dat_l), nrow=nrow(dat_l[[1]]))
l1_vec <- rep(0, nboot)
n_d <- ncol(temp_mat)
for( i in 1:nboot){
t_clus <- sample(nclust, ncol(temp_mat), replace=TRUE)
clus_vals <- unique(t_clus)
l1_vec_boot <- matrix(0, ncol = max(t_clus), nrow=nrow(temp_mat))
for (k in clus_vals){
n_k <- sum(t_clus == k)
m_vals <- (rowMeans(temp_mat[,which(t_clus == k), drop=FALSE]) *
((n_k)/ (n_k + delta)))
l1_vec_boot[,k] <- abs(m_vals)
}
l1_vec[i] <- max(l1_vec_boot, na.rm =TRUE)
}
l1 <- unname(stats::quantile(l1_vec, alpha1))
return(rep(l1, dim))
}
|
test_that("test.is_batch_mode.any_mode.returns_true_if_called_from_batch_mode",
{
expected <- !is.na(Sys.getenv("R_BATCH", NA))
actual <- is_batch_mode()
expect_equal(strip_attributes(actual), expected)
if (!actual) {
expect_equal(cause(actual), noquote("R is not running in batch mode."))
}
})
test_that("test.is_interactive.any_mode.returns_true_if_r_runs_interactively",
{
expected <- interactive()
actual <- is_interactive()
expect_equal(strip_attributes(actual), expected)
if (!actual) {
expect_equal(cause(actual), noquote("R is not running interactively."))
}
})
test_that("test.is_r.r_or_s.returns_true_if_is_r", {
expected <- exists("is.R") && is.function(is.R) && is.R()
actual <- is_r()
expect_equal(strip_attributes(actual), expected)
if (!actual) {
expect_equal(cause(actual), noquote("You are not running R."))
}
})
test_that("test.is_r_slave.any_os.returns_true_if_slave_in_command_args", {
expected <- "--slave" %in% commandArgs()
actual <- is_r_slave()
expect_equal(strip_attributes(actual), expected)
if (!actual) {
expect_equal(
cause(actual),
noquote("You are not running a slave instance of R.")
)
}
})
|
rugarch.test12a = function(cluster=NULL)
{
tic = Sys.time()
data(sp500ret)
spec = ugarchspec(variance.model=list(model="csGARCH"), distribution="std")
fit = ugarchfit(spec, sp500ret, out.sample=500)
bootp = ugarchboot(fit, method = c("Partial", "Full")[1],
n.ahead = 500, n.bootpred = 500,
cluster = cluster, verbose = TRUE)
options(width=120)
zz <- file("test12a-1.txt", open="wt")
sink(zz)
show(bootp)
sink(type="message")
sink()
close(zz)
options(width=120)
zz <- file("test12a-2.txt", open="wt")
sink(zz)
cat("\nSeries Forecasts:\n")
print(head(ser<-as.data.frame(bootp, which = "series", type = "raw")))
cat("\nSeries Summary:\n")
print(as.data.frame(bootp, which = "series", type = "summary"))
cat("\nQuantile Summary:\n")
print(as.data.frame(bootp, which = "series", type = "q", qtile= c(0.25, 0.75)))
sink(type="message")
sink()
close(zz)
options(width=120)
zz <- file("test12a-3.txt", open="wt")
sink(zz)
cat("\nSigma Forecasts:\n")
print(head(sig<-as.data.frame(bootp, which = "sigma", type = "raw")))
cat("\nSigma Summary:\n")
print(as.data.frame(bootp, which = "sigma", type = "summary"))
sink(type="message")
sink()
close(zz)
postscript("test12a-1.eps")
plot(bootp, which = "all")
dev.off()
toc = Sys.time()-tic
cat("Elapsed:", toc, "\n")
return(toc)
}
rugarch.test12b = function(cluster=NULL)
{
tic = Sys.time()
data(sp500ret)
spec = ugarchspec(variance.model=list(model="csGARCH"), distribution="std")
fit = ugarchfit(spec, sp500ret, out.sample=10)
bootp = ugarchboot(fit, method = c("Partial", "Full")[2],
n.ahead = 10, n.bootpred = 500, n.bootfit = 100,
cluster = cluster)
options(width=120)
zz <- file("test12b-1.txt", open="wt")
sink(zz)
show(bootp)
sink(type="message")
sink()
close(zz)
options(width=120)
zz <- file("test12b-2.txt", open="wt")
sink(zz)
cat("\nSeries Forecasts:\n")
print(head(ser<-as.data.frame(bootp, which = "series", type = "raw")))
cat("\nSeries Summary:\n")
print(as.data.frame(bootp, which = "series", type = "summary"))
cat("\nQuantile Summary:\n")
print(as.data.frame(bootp, which = "series", type = "q", qtile= c(0.25, 0.75)))
sink(type="message")
sink()
close(zz)
options(width=120)
zz <- file("test12b-3.txt", open="wt")
sink(zz)
cat("\nSigma Forecasts:\n")
print(head(sig<-as.data.frame(bootp, which = "sigma", type = "raw")))
cat("\nSigma Summary:\n")
print(as.data.frame(bootp, which = "sigma", type = "summary"))
sink(type="message")
sink()
close(zz)
postscript("test12b-1.eps")
plot(bootp, which = "all")
dev.off()
toc = Sys.time()-tic
cat("Elapsed:", toc, "\n")
return(toc)
}
rugarch.test12c = function(cluster=NULL)
{
tic = Sys.time()
data(sp500ret)
library(spd)
spec = ugarchspec(variance.model=list(model="csGARCH"), distribution="std")
fit = ugarchfit(spec, sp500ret, out.sample=125)
bootp = ugarchboot(fit, method = c("Partial", "Full")[1],
sampling = "spd", n.ahead = 125, n.bootpred = 500,
cluster = cluster)
options(width=120)
zz <- file("test12c-1.txt", open="wt")
sink(zz)
show(bootp)
sink(type="message")
sink()
close(zz)
options(width=120)
zz <- file("test12c-2.txt", open="wt")
sink(zz)
cat("\nSeries Forecasts:\n")
print(head(ser<-as.data.frame(bootp, which = "series", type = "raw")))
cat("\nSeries Summary:\n")
print(as.data.frame(bootp, which = "series", type = "summary"))
cat("\nQuantile Summary:\n")
print(as.data.frame(bootp, which = "series", type = "q", qtile= c(0.25, 0.75)))
sink(type="message")
sink()
close(zz)
options(width=120)
zz <- file("test12c-3.txt", open="wt")
sink(zz)
cat("\nSigma Forecasts:\n")
print(head(sig<-as.data.frame(bootp, which = "sigma", type = "raw")))
cat("\nSigma Summary:\n")
print(as.data.frame(bootp, which = "sigma", type = "summary"))
sink(type="message")
sink()
close(zz)
postscript("test12c-1.eps")
plot(bootp, which = "all")
dev.off()
toc = Sys.time()-tic
cat("Elapsed:", toc, "\n")
return(toc)
}
rugarch.test12d = function(cluster=NULL)
{
tic = Sys.time()
data(sp500ret)
library(ks)
spec = ugarchspec(variance.model=list(model="csGARCH"), distribution="std")
fit = ugarchfit(spec, sp500ret, out.sample=125)
bootp = ugarchboot(fit, method = c("Partial", "Full")[1],
sampling = "kernel", n.ahead = 125, n.bootpred = 500,
cluster = cluster)
options(width=120)
zz <- file("test12d-1.txt", open="wt")
sink(zz)
show(bootp)
sink(type="message")
sink()
close(zz)
options(width=120)
zz <- file("test12d-2.txt", open="wt")
sink(zz)
cat("\nSeries Forecasts:\n")
print(head(ser<-as.data.frame(bootp, which = "series", type = "raw")))
cat("\nSeries Summary:\n")
print(as.data.frame(bootp, which = "series", type = "summary"))
cat("\nQuantile Summary:\n")
print(as.data.frame(bootp, which = "series", type = "q", qtile= c(0.25, 0.75)))
sink(type="message")
sink()
close(zz)
options(width=120)
zz <- file("test12d-3.txt", open="wt")
sink(zz)
cat("\nSigma Forecasts:\n")
print(head(sig<-as.data.frame(bootp, which = "sigma", type = "raw")))
cat("\nSigma Summary:\n")
print(as.data.frame(bootp, which = "sigma", type = "summary"))
sink(type="message")
sink()
close(zz)
postscript("test12d-1.eps")
plot(bootp, which = "all")
dev.off()
toc = Sys.time()-tic
cat("Elapsed:", toc, "\n")
return(toc)
}
|
"schoolfriends_vertices"
|
context("Test that data for standata parses correctly")
df <- data.frame(group = c(rep(1,5), rep(2, 7), rep(3, 12)))
df[1:5, "date"] <- as.Date("2020-05-01") + 0:4
df[6:12, "date"] <- as.Date("2020-05-02") + 0:6
df[13:24, "date"] <- as.Date("2020-05-03") + 0:11
df[1:5, "A"] <- 5
df[6:12, "A"] <- 12
df[13:24, "A"] <- 17
df$B <- df$A
df$B[1:5] <- df$B[1:5] - 1:5
df$B[6:12] <- df$B[6:12] - 1:7
df$B[13:24] <- df$B[13:24] - 1:12
df$group <- as.factor(df$group)
df <- dplyr::tibble(df) %>% dplyr::group_by(group)
test_that("data is as expected", {
inf <- epiinf(gen=1)
sdat <- standata_data(df, inf)
expect_equal(sdat$groups, c("1", "2", "3"))
expect_equal(sdat$M, 3)
expect_equal(sdat$NC, array(c(5,7,12)))
expect_equal(sdat$NS, 12)
expect_equal(sdat$N2, 14)
expect_equal(sdat$starts, array(c(1,2,3)))
expect_equal(sdat$begin, as.Date("2020-05-01"))
expect_equal(sdat$vacc, matrix(0, 14, 3))
})
test_that("pops populated correctly", {
sdat <- standata_data(df, epiinf(gen=1))
expect_equal(sdat$pops, array(numeric(3)))
sdat <- standata_data(df, epiinf(gen=1, pops=A))
expect_equal(sdat$pops, array(numeric(3)))
sdat <- standata_data(df, epiinf(gen=1, pop_adjust=T, pops=A))
expect_equal(sdat$pops, array(c(5,12,17)))
})
test_that("rm populated correctly", {
nrow <- as.numeric(max(df$date) - min(df$date) + 1)
sdat <- standata_data(df, epiinf(gen=1))
expect_equal(sdat$vacc, matrix(0, 14, 3))
sdat <- standata_data(df, epiinf(gen=1, rm=A))
expect_equal(sdat$vacc, matrix(0, 14, 3))
sdat <- standata_data(df, epiinf(gen=1, pop_adjust=T, pops=A))
expect_equal(sdat$vacc, matrix(0, 14, 3))
sdat <- standata_data(df, epiinf(gen=1, pop_adjust=T, pops=A, rm=A))
expect_equal(sum(sdat$vacc[,1] == 5), 5)
expect_equal(sum(sdat$vacc[,2] == 12), 7)
expect_equal(sum(sdat$vacc[,3] == 17), 12)
expect_equal(which(sdat$vacc[,1] != 0)[1], 1)
expect_equal(which(sdat$vacc[,2] != 0)[1], 2)
expect_equal(which(sdat$vacc[,3] != 0)[1], 3)
})
|
filename = btcore_file("ExcelSamples.xlsx")
expected_names = c("patient_id", "group", "minute", "pdr")
test_that("Several Excel formats are consistent after passing cleanup_data" , {
library(readxl)
sheets = excel_sheets(filename)
for (sheet in sheets[1:4]) {
data = read_breathtest_excel(filename, sheet = sheet)
cleanup_data(data)
bt = cleanup_data(read_breathtest_excel(filename, sheet = sheet))
expect_false(all(stringr::str_detect(bt$group, " ")))
expect_equal(names(bt), expected_names,
info = paste0("in sheet ", sheet, " of ", basename(filename)))
}
sheet = 5
bt = read_breathtest_excel(filename, sheet = sheet)
expect_equal(names(bt[[1]]), expected_names[-2],
info = paste0("in sheet ", sheet, " of ", basename(filename)))
bt_c = cleanup_data(bt)
expect_equal(names(bt_c), expected_names,
info = paste0("in sheet ", sheet, " of ", basename(filename)))
sheet = 6
bt = read_breathtest_excel(filename, sheet = sheet)
expect_equal(names(bt[[1]]), expected_names[-(1:2)],
info = paste0("in sheet ", sheet, " of ", basename(filename)))
bt_c = cleanup_data(bt)
expect_equal(names(bt_c), expected_names,
info = paste0("in sheet ", sheet, " of ", basename(filename)))
})
test_that("Invalid sheets rise error",{
sheet = "bad_header"
expect_error(read_breathtest_excel(filename, sheet = sheet),
"column names should be")
sheet = "bad_order"
expect_error(read_breathtest_excel(filename, sheet = sheet),
"column names should be")
sheet = "bad_columns"
expect_error(read_breathtest_excel(filename, sheet = sheet),
"has 1 column")
})
|
context("StockEvent setters (class unions)")
testthat::test_that("setStockGraph", {
testthat::expect_error(setStockGraph(.Object = stockEvent()))
testthat::expect_error(setStockGraph(.Object = stockEvent(), stockGraph = stockGraph_obj))
})
|
while(from!=0)
{
Sys.sleep(1)
from <- from - 1
print(from)
}
|
mice_multilevel_draw_binomial <- function( probs ){
N <- length(probs)
rn <- stats::runif(N, 0, 1)
res <- 1*(rn < probs)
return(res)
}
|
generate_id <- function() {
paste0(sample(letters, 26), collapse = "")
}
prep_element <- function (el) {
if (!grepl("(?:^\\.)|(?:^\\
}
`%||%` <- function(x, y) {
if (is.null(x))
y
else x
}
|
library(grid)
pushViewport(viewport(h = 0.8, w = 0.8, angle = 15))
grid.multipanel(newpage = FALSE)
|
get_omdb_item_actors<-function(omdb_id, API_KEY = Sys.getenv('API_KEY')){
info<-get_omdb_item(omdb_id, API_KEY = API_KEY)[[1]] %>% .$actors
actors<-str_split(info, pattern = ',') %>% flatten_chr() %>% str_trim(side = 'both')
return(actors)
}
|
Position <- ggproto("Position",
required_aes = character(),
setup_params = function(self, data) {
list()
},
setup_data = function(self, data, params) {
check_required_aesthetics(self$required_aes, names(data), snake_class(self))
data
},
compute_layer = function(self, data, params, layout) {
dapply(data, "PANEL", function(data) {
if (empty(data)) return(new_data_frame())
scales <- layout$get_scales(data$PANEL[1])
self$compute_panel(data = data, params = params, scales = scales)
})
},
compute_panel = function(self, data, params, scales) {
abort("Not implemented")
}
)
transform_position <- function(df, trans_x = NULL, trans_y = NULL, ...) {
oldclass <- class(df)
df <- unclass(df)
scales <- aes_to_scale(names(df))
if (!is.null(trans_x)) {
df[scales == "x"] <- lapply(df[scales == "x"], trans_x, ...)
}
if (!is.null(trans_y)) {
df[scales == "y"] <- lapply(df[scales == "y"], trans_y, ...)
}
class(df) <- oldclass
df
}
|
utils::globalVariables(c("parameters","initials","components"))
auto.vets <- function(data, model="PPP", lags=c(frequency(data)),
loss=c("likelihood","diagonal","trace"),
ic=c("AICc","AIC","BIC","BICc"), h=10, holdout=FALSE,
occurrence=c("none","fixed","logistic"),
bounds=c("admissible","usual","none"),
silent=TRUE, parallel=FALSE, ...){
startTime <- Sys.time();
ic <- match.arg(ic);
loss <- match.arg(loss);
architectorAutoVETS <- function(model){
if(nchar(model)==4){
Etype <- substring(model,1,1);
Ttype <- substring(model,2,2);
Stype <- substring(model,4,4);
damped <- TRUE;
if(substring(model,3,3)!="d"){
warning(paste0("You have defined a strange model: ",model));
sowhat(model);
model <- paste0(Etype,Ttype,"d",Stype);
}
}
else if(nchar(model)==3){
Etype <- substring(model,1,1);
Ttype <- substring(model,2,2);
Stype <- substring(model,3,3);
damped <- FALSE;
}
else{
warning(paste0("You have defined a strange model: ",model));
sowhat(model);
warning("Switching to 'PPP'");
model <- "PPP";
Etype <- "P";
Ttype <- "P";
Stype <- "P";
damped <- TRUE;
}
modelIsTrendy <- Ttype!="N";
modelIsSeasonal <- Stype!="N";
parametersToCheck <- c("l","t"[modelIsTrendy],"s"[modelIsSeasonal],"d"[modelIsTrendy]);
initialsToCheck <- c("l","t"[modelIsTrendy],"s"[modelIsSeasonal]);
componentsToCheck <- c("l","t"[modelIsTrendy],"s"[modelIsSeasonal]);
return(list(modelIsTrendy=modelIsTrendy,modelIsSeasonal=modelIsSeasonal,
parameters=parametersToCheck,initials=initialsToCheck,components=componentsToCheck))
}
vetsCall <- list(...);
vetsCall$data <- data;
vetsCall$model <- model;
vetsCall$lags <- lags;
vetsCall$ic <- ic;
vetsCall$h <- h;
vetsCall$holdout <- holdout;
vetsCall$occurrence <- occurrence;
vetsCall$bounds <- bounds
vetsCall$silent <- TRUE;
vetsCall$parameters <- "none";
vetsCall$initials <- "none";
vetsCall$components <- "none";
vetsCall$loss <- loss;
if(loss=="likelihood"){
vetsCall$loss <- "diagonal";
}
if(!silent){
cat("Selecting the best unrestricted model... \n");
}
initialModel <- do.call("vets",vetsCall);
vetsCall$model[] <- modelType(initialModel);
vetsCall$loss[] <- loss;
list2env(architectorAutoVETS(vetsCall$model),environment());
parametersCombinations <- choose(length(parameters),c(1:length(parameters)));
parametersCombinationNumber <- sum(parametersCombinations);
parametersToCheck <- vector("list",parametersCombinationNumber);
for(i in 1:length(parametersCombinations)){
if(i==1){
parametersToCheck[1:parametersCombinations[1]] <- as.list(as.data.frame(combn(parameters,i),stringsAsFactors=F));
}
else{
parametersToCheck[sum(parametersCombinations[1:(i-1)])+1:parametersCombinations[i]] <-
as.list(as.data.frame(combn(parameters,i),stringsAsFactors=F));
}
}
initialsCombinations <- choose(length(initials),c(1:length(initials)));
initialsCombinationNumber <- sum(initialsCombinations);
initialsToCheck <- vector("list",initialsCombinationNumber);
for(i in 1:length(initialsCombinations)){
if(i==1){
initialsToCheck[1:initialsCombinations[1]] <- as.list(as.data.frame(combn(initials,i),stringsAsFactors=F));
}
else{
initialsToCheck[sum(initialsCombinations[1:(i-1)])+1:initialsCombinations[i]] <-
as.list(as.data.frame(combn(initials,i),stringsAsFactors=F));
}
}
componentsCombinations <- choose(length(components),c(1:length(components)));
componentsCombinationNumber <- sum(componentsCombinations);
componentsToCheck <- vector("list",componentsCombinationNumber);
for(i in 1:length(componentsCombinations)){
if(i==1){
componentsToCheck[1:componentsCombinations[1]] <- as.list(as.data.frame(combn(components,i),stringsAsFactors=F));
}
else{
componentsToCheck[sum(componentsCombinations[1:(i-1)])+1:componentsCombinations[i]] <-
as.list(as.data.frame(combn(components,i),stringsAsFactors=F));
}
}
if(modelIsTrendy){
componentsToCheck[componentsToCheck %in% "l"][[1]] <- c("l","t");
if(modelIsSeasonal){
componentsToCheck[componentsToCheck %in% c("l","s")][[1]] <- c("l","t","s");
}
componentsToCheck <- unique(componentsToCheck);
componentsCombinationNumber <- length(componentsToCheck);
}
if(is.numeric(parallel)){
nCores <- parallel;
parallel <- TRUE
}
else{
if(parallel){
nCores <- min(parallel::detectCores() - 1, parametersCombinationNumber,
initialsCombinationNumber, componentsCombinationNumber);
}
}
if(parallel){
if(!requireNamespace("foreach", quietly = TRUE)){
stop("In order to run the function in parallel, 'foreach' package must be installed.", call. = FALSE);
}
if(!requireNamespace("parallel", quietly = TRUE)){
stop("In order to run the function in parallel, 'parallel' package must be installed.", call. = FALSE);
}
if(Sys.info()['sysname']=="Windows"){
if(requireNamespace("doParallel", quietly = TRUE)){
cat("Setting up", nCores, "clusters using 'doParallel'...\n");
cluster <- parallel::makeCluster(nCores);
doParallel::registerDoParallel(cluster);
}
else{
stop("Sorry, but in order to run the function in parallel, you need 'doParallel' package.",
call. = FALSE);
}
}
else{
if(requireNamespace("doMC", quietly = TRUE)){
doMC::registerDoMC(nCores);
cluster <- NULL;
}
else if(requireNamespace("doParallel", quietly = TRUE)){
cat("Setting up", nCores, "clusters using 'doParallel'...\n");
cluster <- parallel::makeCluster(nCores);
doParallel::registerDoParallel(cluster);
}
else{
stop(paste0("Sorry, but in order to run the function in parallel, you need either ",
"'doMC' (prefered) or 'doParallel' package."),
call. = FALSE);
}
}
}
else{
cluster <- NULL;
}
nToCheck <- length(parametersToCheck)+length(initialsToCheck)+length(componentsToCheck);
vetsModels <- vector("list",nToCheck+1);
vetsModels[[1]] <- initialModel;
rm(initialModel);
if(!silent){
cat(paste0("Initial model is VETS(",modelType(vetsModels[[1]]),"), ",ic," is: ", round(vetsModels[[1]]$ICs[ic],3),"\n"));
}
if(!silent){
cat("Testing initials restrictions... ");
}
if(!parallel){
j <- 2;
for(i in 1:initialsCombinationNumber){
if(!silent){
if(i>1){
cat(paste0(rep("\b",nchar(round((i-1)/initialsCombinationNumber,2)*100)+1),collapse=""));
}
cat(round(i/initialsCombinationNumber,2)*100,"\b%");
}
vetsCall$initials <- initialsToCheck[[i]];
vetsModels[[j]] <- do.call("vets",vetsCall);
j[] <- j+1;
}
}
else{
vetsModels[1+1:initialsCombinationNumber] <-
foreach::`%dopar%`(foreach::foreach(i=1:initialsCombinationNumber),{
vetsCall$initials <- initialsToCheck[[i]];
return(do.call("vets",vetsCall));
})
}
vetsICsInitials <- sapply(vetsModels[1+0:initialsCombinationNumber],"[[","ICs")[ic,];
jBest <- which.min(vetsICsInitials);
ICBest <- vetsICsInitials[jBest];
if(jBest==1){
vetsCall$initials <- "none";
}
else{
vetsCall$initials <- initialsToCheck[[jBest-1]];
}
if(!silent){
cat(paste0("\nInitials restrictions model is (",paste0(vetsCall$initials,collapse=","),
"), ",ic," is: ", round(ICBest,3),"\n"));
}
if(!silent){
cat("Testing parameters restrictions... ");
}
if(!parallel){
for(i in 1:parametersCombinationNumber){
if(!silent){
if(i>1){
cat(paste0(rep("\b",nchar(round((i-1)/parametersCombinationNumber,2)*100)+1),collapse=""));
}
cat(round(i/parametersCombinationNumber,2)*100,"\b%");
}
vetsCall$parameters <- parametersToCheck[[i]];
vetsModels[[j]] <- do.call("vets",vetsCall);
j[] <- j+1;
}
}
else{
vetsModels[1+initialsCombinationNumber+1:parametersCombinationNumber] <-
foreach::`%dopar%`(foreach::foreach(i=1:parametersCombinationNumber),{
vetsCall$parameters <- parametersToCheck[[i]];
return(do.call("vets",vetsCall));
})
}
vetsICsParameters <- sapply(vetsModels[1+initialsCombinationNumber+1:parametersCombinationNumber],"[[","ICs")[ic,];
jBestParameters <- which.min(vetsICsParameters);
if(vetsICsParameters[jBestParameters]<ICBest){
jBest <- jBestParameters+initialsCombinationNumber+1;
ICBest <- vetsICsParameters[jBestParameters];
vetsCall$parameters <- parametersToCheck[[jBestParameters]];
}
else{
vetsCall$parameters <- "none";
}
if(!silent){
cat(paste0("\nParameters restrictions model is (",paste0(vetsCall$parameters,collapse=","),
"), ",ic," is: ", round(ICBest,3),"\n"));
}
if(!silent){
cat("Testing components restrictions... ");
}
if(!parallel){
for(i in 1:componentsCombinationNumber){
if(!silent){
if(i>1){
cat(paste0(rep("\b",nchar(round((i-1)/componentsCombinationNumber,2)*100)+1),collapse=""));
}
cat(round(i/componentsCombinationNumber,2)*100,"\b%");
}
vetsCall$components <- componentsToCheck[[i]];
vetsModels[[j]] <- do.call("vets",vetsCall);
j[] <- j+1;
}
}
else{
vetsModels[1+initialsCombinationNumber+parametersCombinationNumber+1:componentsCombinationNumber] <-
foreach::`%dopar%`(foreach::foreach(i=1:componentsCombinationNumber),{
vetsCall$components <- componentsToCheck[[i]];
return(do.call("vets",vetsCall));
})
}
vetsICsComponents <- sapply(vetsModels[1+initialsCombinationNumber+parametersCombinationNumber+
1:componentsCombinationNumber],"[[","ICs")[ic,];
jBestComponents <- which.min(vetsICsComponents);
if(vetsICsComponents[jBestComponents]<ICBest){
jBest <- jBestComponents+1+initialsCombinationNumber+parametersCombinationNumber;
ICBest <- vetsICsComponents[jBestComponents];
vetsCall$components <- componentsToCheck[[jBestComponents]];
}
else{
vetsCall$components <- "none";
}
if(!silent){
cat(paste0("\nComponents restrictions model is (",paste0(vetsCall$components,collapse=","),
"), ",ic," is: ", round(ICBest,3),"\n"));
}
if(!is.null(cluster)){
parallel::stopCluster(cluster);
}
vetsModels[[jBest]]$timeElapsed <- Sys.time()-startTime;
return(vetsModels[[jBest]]);
}
|
NULL
setnew <- function(..., .ordered = FALSE)
{
if (.ordered)
OrderedSet$new(...)$clone(deep = TRUE)
else
Set$new(...)$clone(deep = TRUE)
}
as.set <- function(x) {
if (length(x) == 0)
return(setnew())
do.call(setnew, args = as.list(x))
}
as.orderedset <- function(x) {
newset = function(...) setnew(..., .ordered = TRUE)
if (length(x) == 0)
return(newset())
do.call(newset, args = as.list(x))
}
methods::setOldClass("Set")
methods::setAs("list", "Set", function(from) as.set(from))
is.set <- function(x) inherits(x, "Set")
is.orderedset <- function(x) inherits(x, "OrderedSet")
c.Set <- function(..., recursive = FALSE, use.names = TRUE)
{
concat = c.Container(..., recursive = recursive, use.names = use.names)
if (recursive)
concat
else
as.set(concat)
}
c.OrderedSet <- function(..., recursive = FALSE, use.names = TRUE)
{
concat = c.Container(..., recursive = recursive, use.names = use.names)
if (recursive)
concat
else {
as.orderedset(concat)
}
}
|
PresentationModel.Table = function(table, ...) {
presentationmodel = PresentationModel()
presentationmodel = presentationmodel + table
args = list(...)
if (length(args)>0) {
for (i in 1:length(args)){
presentationmodel = presentationmodel + args[[i]]
}
}
return(presentationmodel)
}
|
library(testthat)
source("utils.R")
invoke_test <- function(expected_res, ...) {
res <- seqR::count_kmers(hash_dim = 2,
verbose=FALSE,
...)
expect_matrices_equal(as.matrix(res), expected_res)
}
test_that("(string vector) count 3-mers for sequences A+", {
sq <- c("AAAAA", "AA", "AAAAAAA")
expected_res <- matrix(c(
3,
0,
5
), nrow=3)
colnames(expected_res) <- c("A.A.A_0.0")
invoke_test(expected_res=expected_res,
kmer_alphabet=c("A"),
sequences=sq,
k=3,
positional=FALSE,
with_kmer_counts=TRUE)
})
test_that("(string vector) count 3-mers for sequences A+ longer", {
sq <- c(strrep("A", 1000000), strrep("A", 1000), strrep("A", 100))
expected_res <- matrix(c(
999998,
998,
98
), nrow=3)
colnames(expected_res) <- c("A.A.A_0.0")
invoke_test(expected_res=expected_res,
kmer_alphabet=c("A"),
sequences=sq,
k=3,
positional=FALSE,
with_kmer_counts=TRUE)
})
test_that("(string vector) count non positional 10-mers sequences A+ longer", {
sq <- c(strrep("A", 1000000), strrep("A", 100))
expected_res <- matrix(c(
999991,
91
), nrow=2)
colnames(expected_res) <- paste0(
paste0(rep("A", 10), collapse="."),
"_",
paste0(rep("0", 9), collapse="."), collapse="")
invoke_test(expected_res=expected_res,
kmer_alphabet=c("A"),
sequences=sq,
k=10,
positional=FALSE,
with_kmer_counts=TRUE)
})
test_that("(string vector) find 3-mers for sequences A+ (without k-mer counts)", {
sq <- c("AAAAA", "AA", "AAAAAAA")
expected_res <- matrix(c(
1,
0,
1
), nrow=3)
colnames(expected_res) <- c("A.A.A_0.0")
invoke_test(expected_res=expected_res,
kmer_alphabet=c("A"),
sequences=sq,
k=3,
positional=FALSE,
with_kmer_counts=FALSE)
})
test_that("(string vector) find 15-mers for sequences (AC){1000000}", {
sq <- sapply(1:5, function(i) strrep("AC", 1000000))
expected_res <- matrix(c(
999993, 999993,
999993, 999993,
999993, 999993,
999993, 999993,
999993, 999993
), byrow=TRUE, nrow=5)
colnames(expected_res) <- c("A.C.A.C.A.C.A.C.A.C.A.C.A.C.A_0.0.0.0.0.0.0.0.0.0.0.0.0.0",
"C.A.C.A.C.A.C.A.C.A.C.A.C.A.C_0.0.0.0.0.0.0.0.0.0.0.0.0.0")
invoke_test(expected_res=expected_res,
kmer_alphabet=c("A", "C"),
sequences=sq,
k=15,
positional=FALSE,
with_kmer_counts=TRUE)
})
|
gigCheckPars <- function(param, ...) {
param <- as.numeric(param)
chi <- param[1]
psi <- param[2]
lambda <- param[3]
case <- "normal"
errMessage <- ""
if (length(param) != 3) {
case <- "error"
errMessage <- "param vector must contain 3 values"
} else {
if (chi < 0) {
case <- "error"
errMessage <- "chi must be non-negative"
} else if (psi < 0) {
case <- "error"
errMessage <- "psi must be non-negative"
} else if (isTRUE(all.equal(0, chi, ...))) {
if (lambda <= 0) {
case <- "error"
errMessage <- "lambda must be positive when chi = 0"
} else if (isTRUE(all.equal(0, psi, ...))) {
case <- "error"
errMessage <- "psi and chi cannot both be 0"
} else {
case <- "gamma"
}
} else if (isTRUE(all.equal(0, psi, ...))) {
if (lambda >= 0) {
case <- "error"
errMessage <- "lambda must be negative when psi = 0"
} else if (isTRUE(all.equal(0, chi, ...))) {
case <- "error"
errMessage <- "psi and chi cannot both be 0"
} else {
case <- "invgamma"
}
}
}
result <- list(case = case, errMessage = errMessage)
return(result)
}
|
print.infection.count <- function( x, ... ){
summary(x, ...)
}
|
survey <- function(participants, contacts, reference=NULL)
{
new_obj <-
structure(list(participants=data.table(participants),
contacts=data.table(contacts),
reference=reference),
class="survey")
return(new_obj)
}
|
observeEvent(input$reactive, {
updateButton(session, "submit", disabled = input$reactive)
if (input$reactive) {
output$plot <- renderPlot({
buildPlot()
}, height=700)
output$displayTable <- DT::renderDataTable({
DT::datatable(manAggDataset(), filter='top',
options = list(sDom = '<"top">lrt<"bottom">ip'))
})
} else {
output$plot <- renderPlot({
input$submit
isolate(buildPlot())
}, height=700)
output$displayTable <- DT::renderDataTable({
input$submit
isolate(DT::datatable(manAggDataset(), filter='top',
options = list(sDom = '<"top">lrt<"bottom">ip')))
})
}
})
observe({
nInp <- input$itersToDrawInp
isolate({
n <- reactVals$itersToDraw
if (notNulls(nInp, n) && n != 0) reactVals$itersToDraw <- n - 1
})
})
observe({
pTypes <- plotTypes()
isolate({
if (is.null(dataset())) return()
allDefTypes <- unlist(getStructListNames(curDatasetPlotInputs()))
needOneGroupOpts <- length(pTypes) == 1 &&
length(plotTypesOpts()) == length(allDefTypes)
if (is.null(pTypes) || needOneGroupOpts) {
reactVals$plotTypeOptsTrigger <- Sys.time()
}
})
})
observeEvent(input$reset_input, {
updateCheckboxInput(session, "reactive", value = FALSE)
Sys.sleep(0.5)
for (id in setdiff(names(input), 'datasetName')) {
reset(id)
}
Sys.sleep(0.5)
updateCheckboxInput(session, "reactive", value = TRUE)
})
observeEvent(buildPlot(), {
if (!isFacetSelected()) {
enable('facetRow')
enable('facetCol')
enable('facetWrap')
} else if (facetGridSelected()) {
enable('facetRow')
enable('facetCol')
disable('facetWrap')
} else if (facetWrapSelected()) {
disable('facetRow')
disable('facetCol')
enable('facetWrap')
}
})
observeEvent(buildPlot(), ({
if (length(reactVals$log) == 1) {
updateCollapse(session, "extraPlotBlocks", close = input$extraPlotBlocks)
}
}))
observeEvent(input$displayTable_search_columns, {
if (tolower(plotAggMeth()) != 'none') reset('plotAggMeth')
})
|
context("Loading US map data")
states_map <- us_map(regions = "states")
counties_map <- us_map(regions = "counties")
test_that("structure of states df is correct", {
expect_equal(length(unique(states_map$fips)), 51)
})
test_that("correct states are included", {
include_abbr <- c("AK", "AL", "AZ")
map_abbr <- us_map(regions = "states", include = include_abbr)
include_full <- c("Alaska", "Alabama", "Arizona")
map_full <- us_map(regions = "states", include = include_full)
include_fips <- c("02", "01", "04")
map_fips <- us_map(regions = "states", include = include_fips)
expect_equal(length(unique(map_abbr$fips)), length(include_abbr))
expect_equal(length(unique(map_full$fips)), length(include_full))
expect_equal(length(unique(map_fips$fips)), length(include_fips))
})
test_that("correct states are excluded", {
full_map <- us_map(regions = "states")
exclude_abbr <- c("AK", "AL", "AZ")
map_abbr <- us_map(regions = "states", exclude = exclude_abbr)
exclude_full <- c("Alaska", "Alabama", "Arizona")
map_full <- us_map(regions = "states", exclude = exclude_full)
exclude_fips <- c("02", "01", "04")
map_fips <- us_map(regions = "states", exclude = exclude_fips)
expect_equal(length(unique(full_map$fips)) - length(unique(map_abbr$fips)), length(exclude_abbr))
expect_equal(length(unique(full_map$fips)) - length(unique(map_full$fips)), length(exclude_full))
expect_equal(length(unique(full_map$fips)) - length(unique(map_fips$fips)), length(exclude_fips))
})
test_that("structure of counties df is correct", {
expect_equal(length(unique(counties_map$fips)), 3142)
})
test_that("correct counties are included", {
include_fips <- c("34021", "34023", "34025")
map_fips <- us_map(regions = "counties", include = include_fips)
expect_equal(length(unique(map_fips$fips)), length(include_fips))
})
test_that("correct counties are excluded", {
exclude_fips <- c("34021", "34023", "34025")
map_fips <- us_map(regions = "counties", include = "NJ", exclude = exclude_fips)
map_nj <- us_map(regions = "counties", include = "NJ")
expect_equal(length(unique(map_nj$fips)) - length(unique(map_fips$fips)), (length(exclude_fips)))
})
test_that("singular regions value returns same data frames as plural", {
state_map <- us_map(regions = "state")
county_map <- us_map(regions = "county")
expect_identical(states_map, state_map)
expect_identical(counties_map, county_map)
})
test_that("error occurs for invalid region", {
expect_error(us_map(regions = "cities"))
})
|
library(hamcrest)
test.namespaceLoads <- function() {
library(utils)
}
test.globalVariables <- function() {
assertThat(utils::globalVariables(c(".obj1", ".obj2")), instanceOf("character"))
}
test.suppressForeignCheck <- function() {
assertThat(utils::suppressForeignCheck(c(".obj1", ".obj2")), instanceOf("character"))
}
|
library(mistat)
data(YARNSTRG)
data(CYCLT)
install.packages("mistat",
dependencies=TRUE)
library(mistat)
data(CYCLT)
help(CYCLT)
CYCLT
set.seed(123)
X <-
rbinom(n = 50,
size = 1,
prob = 0.5)
X
ls()
rm(X)
data(STEELROD)
plot(STEELROD,
ylab = "Steel rod Length",
xlab = "Index")
data(STEELROD)
plot(STEELROD,
ylab = "Steel rod Length",
xlab = "Index")
X <- STEELROD
X[26:length(X)] <- X[26:length(X)] - 3
plot(X, ylab = "Length of steel rod", xlab = "Index" )
lines(x = c(1, 25), y = rep(mean(X[1:25]), 2))
lines(x = c(26, 50), y = rep(mean(X[26:50]), 2))
rm(X)
set.seed(123)
X <- seq(from=1,
to=50,
by=1)
X <- sin(
X*(2*pi)/50)
X <- X + rnorm(n=length(X),
mean=0,
sd=0.05)
plot(X,
ylab="Values")
abline(h=0,
lty="dashed",
col="lightgray")
set.seed(123)
X <- seq(from=1,
to=50,
by=1)
X <- sin(
X*(2*pi)/50)
X <- X + rnorm(n=length(X),
mean=0,
sd=0.05)
plot(X,
ylab="Values")
abline(h=0,
lty="dashed",
col="lightgray")
rm(X)
set.seed(123)
X <- rep(c(5, 2, 5), each=10)
X <- X + c(rnorm(10, sd=0.5), rnorm(10, sd=0.2), rnorm(10, sd=0.1))
plot(X,
ylim=c(0,8),
ylab="Weight")
lines(c(1,10), c(5,5))
lines(c(11,20), c(2,2))
lines(c(21,30), c(5,5))
text(5.5, 7, "A")
text(15.5, 4, "B")
text(25.5, 7, "C")
rm(X)
X <- matrix(c(5, 13, 45, 25, 12), nrow=1)
barplot(X,
width=1,
space=4,
col="grey50",
names.arg=c(10, 20, 30, 40, 50),
ylab="Frequency")
plot(c(10, 20, 30, 40, 50), cumsum(X),
type="s",
xlab="", ylab="Cumulative Frequency",
ylim=c(0,100))
rm(X)
data(BLEMISHES)
BLEMISHES[1:3, ]
head(BLEMISHES,
n=3)
X <- factor(BLEMISHES$count,
levels=0:5)
X <- table(X
)
X <- prop.table(X)
barplot(X,
width=1,
space=4,
col="grey50",
ylab="Proportional Frequency")
X <- factor(BLEMISHES$count,
levels=0:5)
X <- table(X
)
X <- prop.table(X)
barplot(X,
width=1,
space=4,
col="grey50",
ylab="Proportional Frequency")
plot(names(X), cumsum(X),
type="s",
xlab="", ylab="Cumulative Frequency")
rm(X)
hist(YARNSTRG,
breaks=6,
main="",
xlab = "Log yarn strength")
plot.ecdf(YARNSTRG,
pch=NA,
main="",
xlab="Log Yarn Strength")
data(YARNSTRG)
hist(YARNSTRG)
hist(YARNSTRG,
breaks=6,
main="",
xlab = "Log yarn strength")
plot.ecdf(YARNSTRG,
pch=NA,
main="",
xlab="Log Yarn Strength")
plot.ecdf(YARNSTRG,
main="")
abline(h=c(0.25,0.5,0.75),
lty=2,
col="gray70")
arrows(sort(YARNSTRG)[25], 0.25,
sort(YARNSTRG)[25], 0)
arrows(sort(YARNSTRG)[50], 0.50,
sort(YARNSTRG)[50], 0)
arrows(sort(YARNSTRG)[75], 0.75,
sort(YARNSTRG)[75], 0)
text(sort(YARNSTRG)[25] + 0.2, 0.09, "Q1")
text(sort(YARNSTRG)[50] + 0.2, 0.09, "Q2")
text(sort(YARNSTRG)[75] + 0.2, 0.09, "Q3")
quantile(CYCLT,
probs = seq(from=0,
to=1,
by=0.25),
type=6
)
mean(CYCLT,
trim=0.0,
na.rm=TRUE
)
library(e1071)
skewness(BLEMISHES$count)
kurtosis(BLEMISHES$count)
X <- seq(0, 1, length.out=200)
plot(X, dbeta(X, shape1=2, shape2=8),
type="l",
xlab=expression(x),
ylab=expression(y),
ylim=c(0, 4.5))
lines(X, dbeta(X, shape1=10, shape2=10))
lines(X, dbeta(X, shape1=8, shape2=2))
text(0.1, 4.2, labels="Positive \nSkewness")
text(0.5, 4.2, labels="Symmetric")
text(0.9, 4.2, labels="Negative \nSkewness")
X <- seq(0, 1, length.out=200)
plot(X*6-3, dbeta(X, shape1=8, shape2=8)/6,
type="l",
xlab=expression(x),
ylab=expression(y),
ylim=c(0, 0.55))
lines(X*6-3, dbeta(X, shape1=2.5, shape2=2.5)/6, lty="dotdash")
X <- seq(-3, 3, length.out=200)
lines(X, dnorm(X), lty="dashed")
text(1.0, 0.52, labels="Steep")
text(1.5, 0.40, labels="Normal")
text(2.5, 0.28, labels="Flat")
rm(X)
boxplot(YARNSTRG,
ylab="Log Yarn Strength")
boxplot(YARNSTRG,
ylab="Log Yarn Strength")
qqplot(qunif(seq(0,1,length.out=100)), YARNSTRG,
xlab="Fraction of Sample",
ylab="Sample Quantiles")
File <- paste(
path.package("mistat"),
"/csvFiles/OELECT.csv",
sep = "")
Oelect <- read.csv(file=File)
rm(File)
mySummary <- function(
x, trim=0, type=6 )
{
qq <-quantile(x, type=type)
qq <- c(qq[1L:3L],
mean(x, trim=trim),
qq[4L:5L])
names(qq) <- c("Min.", "1st Qu.",
"Median", "Mean",
"3rd Qu.", "Max.")
qq <- signif(qq)
return(qq)
}
mySummary(Oelect$OELECT)
mySummary(Oelect$OELECT,
trim=0.05)
sd(Oelect$OELECT)
OutVolt <- sort(Oelect$OELECT)
OutVolt[99] <- 2289.86
mySummary(OutVolt)
mySummary(OutVolt,
trim=0.05)
sd(OutVolt)
IQR(OutVolt)/1.349
rm(Oelect, OutVolt, mySummary)
detach(package:mistat)
|
load_pop <- function(icountry,input_poptables){
file_local <- input_poptables[[icountry]]
df <- utils::read.csv(file_local, stringsAsFactors=FALSE, header = FALSE)
colnames(df) <- c("ADMINID", "ADMINPOP")
return(df)
}
get_pop_census_all <- function(x) {
c <- names(x)
census_data <- load_pop(c[[1]], x)
for ( i in 1:length(c) ) {
if (i==1) next()
census_data <- rbind(census_data, load_pop(c[[i]], x))
}
return(census_data)
}
|
ts_compound <- function(x, denominator = 100) {
not_in_data <- NULL
value <- NULL
denominator <- as.numeric(denominator)
stopifnot(denominator > 0)
stopifnot(length(denominator) == 1L)
z <- ts_dts(x)
d <- dts_default(z)
z <- d$x
z <- ts_regular(ts_na_omit(z))
z[, value := value / denominator + 1]
z <- ts_bind(ts_lag(z, -1), -99999)
.by <- by_expr(dts_cname(z)$id)
z[
,
value := c(1, cumprod(value[-length(value)])),
by = eval(.by)
]
z <- dts_restore(z, d)
ts_na_omit(copy_class(z, x))
}
ts_index <- function(x, base = NULL) {
not_in_data <- NULL
value <- NULL
base_value <- NULL
.SD <- NULL
. <- NULL
z <- ts_dts(x)
if (nrow(z) == 0L) return(x)
d <- dts_default(z)
z <- d$x
cid <- dts_cname(z)$id
.by <- by_expr(cid)
if (all(is.na(d$x$value))) return(x)
if (is.null(base)) {
dt_min_time <- z[
!is.na(value),
list(min.time = min(time)),
by = eval(.by)
]
base <- max(dt_min_time$min.time)
z.base <- z[is_near(time, base), .(base_value = mean(value)), by = eval(.by)]
} else if (length(base) == 1L) {
base <- range(ts_span(z, start = base)$time)[1]
z.base <- z[is_near(time, base), .(base_value = mean(value)), by = eval(.by)]
} else if (length(base) == 2L) {
base <- range(ts_span(z, start = base[1], end = base[2])$time)
z.base <- z[
time >= base[1] & time <= base[2],
.(base_value = mean(value)),
by = eval(.by)
]
} else {
stop0("'base' must be of length 1 or 2, or NULL.")
}
if (length(cid) > 0) {
z <- merge(z, z.base, by = cid, sort = FALSE)
} else {
z$base_value <- z.base$base_value
}
z[, value := value / base_value][, base_value := NULL]
z <- dts_restore(z, d)
copy_class(z, x)
}
|
context("test pairwise Schur product")
test_that("computations", {
expect_equal(pairwise_Schur_product(cbind(rep(1, 4), 1:4, 4:1)), matrix(c(1:4,4:1, 4,6,6,4), ncol=3))
expect_equal(pairwise_Schur_product(cbind(rep(1, 4), 1:4, 4:1), self=TRUE), matrix(c(1, 1, 1, 1, 1:4,4:1, 1, 4, 9, 16, 4,6,6,4, 16, 9, 4, 1), ncol=6))
} )
test_that("input and output is the right type and dimension", {
expect_error(pairwise_Schur_product(data.frame(rep(1, 4), 1:4, 4:1)))
expect_error(pairwise_Schur_product(1:4))
expect_is(pairwise_Schur_product(cbind(rep(1, 4), 1:4, 4:1)), "matrix")
expect_is(pairwise_Schur_product(cbind(rep(1, 4), 1:4, 4:1), self=TRUE), "matrix")
expect_equal(dim(pairwise_Schur_product(cbind(rep(1, 4), 1:4, 4:1))), c(4,3))
expect_equal(dim(pairwise_Schur_product(cbind(rep(1, 4), 1:4, 4:1), self=TRUE)), c(4,6))
} )
|
minimizePI<-function(prime.out){
mat<-prime.out$mat.primes
vec.primes<-NULL
repeat{
ids.row<-which(rowSums(mat)==1)
if(length(ids.row)>0){
tmp<-matrix(mat[ids.row,],nrow=length(ids.row))
ids.prime<-which(diag(t(tmp)%*%tmp)!=0)
tmp<-mat[,ids.prime]%*%t(mat[,ids.prime])
ids.stay<-rowSums(tmp)==0
mat<-mat[ids.stay,,drop=FALSE]
vec.primes<-c(vec.primes,colnames(mat)[ids.prime])
if(nrow(mat)==0)
break
mat<-mat[,-ids.prime,drop=FALSE]
if(ncol(mat)==0)
break
}
dim.mat<-dim(mat)
mat<-rm.dom(mat)
mat<-rm.dom(mat,col=TRUE,dom=FALSE)
if(all(dim(mat)==dim.mat)){
vec.primes<-cyclic.covering(mat,vec.primes)
break
}
}
class(vec.primes)<-"minDNF"
vec.primes
}
|
"variable_label" <- function(x, ...){
UseMethod("variable_label")
}
variable_label.default <- function(x, ...){
attr(x, "label", exact = TRUE)
}
variable_label.data.frame <- function(x, ...){
mapply(FUN = variable_label, x, SIMPLIFY = FALSE, USE.NAMES = TRUE)
}
`variable_label<-` <- function(x, value){
UseMethod("variable_label<-")
}
`variable_label<-.default` <- function(x, value){
assign_label.default(x, value)
}
`variable_label<-.data.frame` <- function(x, value){
assign_label.data.frame(x, value)
}
label_variable <- function(x, ...){
assign_label(x, value = list(...))
}
"variable_labels" <- variable_label
`variable_labels<-` <- `variable_label<-`
"label_variables" <- label_variable
|
library(tidyverse)
library(readxl)
cat_height_raw <- read_excel("data-raw/caterpillars_raw.xlsx", sheet = "HEIGHT")
cat_spines_raw <- read_excel("data-raw/caterpillars_raw.xlsx", sheet = "SPINES")
cat_time_raw <- read_excel("data-raw/caterpillars_raw.xlsx", sheet = "TIME")
cat_height <-
cat_height_raw %>%
tidyr::pivot_longer(
tidyselect::everything(),
values_to = "height",
names_to = "progeny"
) %>%
tidyr::drop_na(height) %>%
dplyr::mutate(
progeny = stringr::str_remove(progeny, " height"),
progeny = case_when(
progeny == "inbred" ~ "self",
TRUE ~ "hybrid"
),
height = case_when(
height < 25 ~ "short",
height > 30 ~ "tall",
TRUE ~ "medium"
)
)
cat_spines <-
cat_spines_raw %>%
tidyr::pivot_longer(
tidyselect::everything(),
values_to = "spines",
names_to = "progeny"
) %>%
tidyr::drop_na(spines) %>%
dplyr::mutate(
progeny = stringr::str_remove(progeny, " spines"),
progeny = case_when(
progeny == "inbred" ~ "self",
TRUE ~ "hybrid"
)
)
cat_time <-
cat_time_raw %>%
tidyr::pivot_longer(
tidyselect::everything(),
values_to = "time",
names_to = "progeny"
) %>%
tidyr::drop_na(time) %>%
dplyr::mutate(
progeny = stringr::str_remove(progeny, " time"),
progeny = case_when(
progeny == "inbred" ~ "self",
TRUE ~ "hybrid"
)
)
caterpillars <-
bind_cols(cat_height, spines = cat_spines$spines, time = cat_time$time)
|
context("formatting properties")
test_that("text properties", {
skip_if_not(check_valid_java_version())
tp <- textProperties(color="red", font.weight = "bold",
font.style = "italic", underlined = TRUE )
tp_ <- chprop(tp, font.weight = "normal")
expect_equal(tp_$font.weight, "normal" )
})
test_that("par properties", {
skip_if_not(check_valid_java_version())
pp <- parRight( )
expect_equal(pp$text.align, "right" )
pp <- parLeft( )
expect_equal(pp$text.align, "left" )
pp_ <- chprop(pp, text.align = "center")
expect_equal(pp_$text.align, "center" )
})
|
ARI <- function(x, y) {
if (is.matrix(x))
x <- apply(x,2,which.max)
if (is.matrix(y))
y <- apply(y,2,which.max)
ctab <- table(x,y)
cellsum <- sum(ctab*(ctab-1)/2)
totsum <- sum(ctab)*(sum(ctab)-1)/2
rows <- ctab %*% rep(1,ncol(ctab))
rowsum <- sum(rows*(rows-1)/2)
cols <- rep(1,nrow(ctab)) %*% ctab
colsum <- sum(cols*(cols-1)/2)
adj.rand <- (cellsum - (rowsum*colsum/totsum))/(.5*(rowsum +colsum)-(rowsum*colsum/totsum))
return(adj.rand)
}
|
a = data({
n = 100
x = rnorm(n)
e = rnorm(n)
abc = 1
})
b = data({
y = 3 + 10*x + e
})
sim = simulation({
a = 1:3
b = sum(a)
k = rpois(3, b)
})
graphics = plot(model({
fit = lm(y ~ x)
plot(fit)
}))
foo({
source("foo.R")
})
|
fbGetCampaigns <- function(accounts_id = getOption("rfacebookstat.accounts_id"),
api_version = getOption("rfacebookstat.api_version"),
username = getOption("rfacebookstat.username"),
token_path = fbTokenPath(),
access_token = getOption("rfacebookstat.access_token")){
if ( is.null(access_token) ) {
if ( Sys.getenv("RFB_API_TOKEN") != "" ) {
access_token <- Sys.getenv("RFB_API_TOKEN")
} else {
access_token <- fbAuth(username = username,
token_path = token_path)$access_token
}
}
if ( class(access_token) == "fb_access_token" ) {
access_token <- access_token$access_token
}
if ( is.null(accounts_id) ) {
message("...Loading your account list.")
accounts_id <- suppressMessages(fbGetAdAccounts()$id)
message("...Loading campaigns from ", length(accounts_id), " account", ifelse( length(accounts_id) > 1, "s", "" ))
}
accounts_id <- ifelse(grepl("^act_", accounts_id), accounts_id, paste0("act_",accounts_id))
rq_ids <- list()
out_headers <- list()
result <- list()
if ( length(accounts_id) > 1 ) {
pgbar <- TRUE
pb_step <- 1
pb <- txtProgressBar(pb_step,
length(accounts_id),
style = 3,
title = "Loading:",
label = "load" )
} else {
pgbar <- FALSE
}
for( account_id in accounts_id ) {
QueryString <- paste0("https://graph.facebook.com/",api_version,"/",account_id,"/campaigns?fields=id,name,created_time,bid_strategy,daily_budget,budget_remaining,spend_cap,buying_type,status,configured_status,account_id,recommendations,source_campaign_id,start_time,stop_time&limit=1000",
"&filtering=[{'field':'campaign.delivery_info','operator':'NOT_IN','value':['stupid_filter']}]",
"&access_token=",access_token)
api_answer <- GET(QueryString)
rq_ids <- append(rq_ids, setNames(list(status_code(api_answer)), api_answer$headers$`x-fb-trace-id`))
out_headers <- append(out_headers, setNames(list(headers(api_answer)), api_answer$headers$`x-fb-trace-id`))
pars_answer <- content(api_answer, as = "parsed")
if(!is.null(pars_answer$error)) {
error <- pars_answer$error
stop(pars_answer$error)
}
result <- c(result, pars_answer$data)
while (!is.null(pars_answer$paging$`next`)) {
api_answer <- GET(pars_answer$paging$`next`)
rq_ids <- append(rq_ids, setNames(list(status_code(api_answer)), api_answer$headers$`x-fb-trace-id`))
out_headers <- append(out_headers, setNames(list(headers(api_answer)), api_answer$headers$`x-fb-trace-id`))
pars_answer <- content(api_answer, as = "parsed")
result <- c(result, pars_answer$data)
}
if( pgbar ) {
pb_step <- pb_step + 1
setTxtProgressBar(pb, pb_step)
}
}
result <- bind_rows(result)
attr(result, "request_ids") <- rq_ids
attr(result, "headers") <- out_headers
if( pgbar ) close(pb)
return(result)
}
|
test_that("rba_value_to_num() works", {
test_vec <- c(
"1.0", "-2", "1½", "1½–2½",
"1¾-2¾", "1¼-2½", "-3½--2¾", "-1½–-2½",
"1½–3½", "-52", "5-6", "-2--3",
"17 to 17.5",
"100",
paste0("\u2013", 5), paste0(intToUtf8(8722), 5),
paste0(3, intToUtf8(8722), 5)
)
fixed_vec <- rba_value_to_num(test_vec)
manually_fixed_vec <- c(
1, -2, 1.5, 2,
2.25, 1.875, -3.125, -2,
2.5, -52, 5.5, -2.5,
17.25,
100,
-5, -5,
4
)
expect_length(fixed_vec, length(test_vec))
expect_identical(fixed_vec, manually_fixed_vec)
expect_identical(
rba_value_to_num(c("17.00 to 17.50", "16.50 to 17.00")),
c(17.25, 16.75)
)
expect_identical(
rba_value_to_num(c(1, 1, "17 to 17.5", 5, 5, "20 to 25", "1½")),
c(1, 1, 17.25, 5, 5, 22.5, 1.5)
)
expect_error(rba_value_to_num(1))
})
|
CHI2 <- function(seqdata, breaks=NULL, step=1, with.missing=FALSE, norm=TRUE,
weighted=TRUE, overlap=FALSE, notC=FALSE, euclid=FALSE,
global.pdotj=NULL, refseq=NULL){
if(euclid){
weighted <- FALSE
}
if(is.null(breaks)){
breaks <- list()
if(step==1){
for(i in 1:ncol(seqdata)){
breaks[[i]] <- c(i, i)
}
}else if (step==ncol(seqdata)){
breaks[[1]] <- c(1, ncol(seqdata))
}else{
bb <- seq(from=1, to=ncol(seqdata), by=step)
if(bb[length(bb)]!=(1+ncol(seqdata)-step)){
msg.warn("With step=",step," last episode is shorter than the others")
}
bb <- c(bb, ncol(seqdata)+1)
bi <- 1
if(overlap){
breaks[[bi]] <- c(1, 1+step/2)
bi <- 2
}
for(i in 2:length(bb)){
breaks[[bi]] <- c(bb[(i-1)], bb[i]-1)
bi <- bi +1
if(overlap){
breaks[[bi]] <- pmin(breaks[[bi-1]]+step/2, ncol(seqdata))
bi <- bi +1
}
}
}
}
if(!is.list(breaks)){
msg.stop("breaks should be a list of couples: breaks=list(c(start1, end1), c(start2, end2), ...))")
}
labels <- attr(seqdata, "labels")
cpal <- cpal(seqdata)
alph <- alphabet(seqdata)
if(with.missing){
labels <- c(labels, "missing")
cpal <- c(cpal, attr(seqdata, "missing.color"))
alph <- c(alph, attr(seqdata, "nr"))
}
nalph <- length(alph)
if (!is.null(global.pdotj)){
if(length(global.pdotj)==1) {
if (global.pdotj[1] != "obs"){
msg.stop("global.pdotj shlould be either 'obs' or a vector of proportions summing up to 1")
}else {
global.pdotj <- seqmeant(seqdata, weighted=weighted, with.missing=with.missing, prop=TRUE)
}
} else {
if (!is.numeric(global.pdotj) || any(global.pdotj<0) || sum(global.pdotj) == 0)
msg.stop("When a vector, global.pdotj should be non negative with at least one strictly positive element.")
global.pdotj <- global.pdotj/sum(global.pdotj)
if (length(global.pdotj) != nalph)
msg.stop("When a vector, global.pdotj should conform the size of the alphabet including the missing state when applicable")
}
}
weights <- attr(seqdata, "weights")
if(is.null(weights)|| !weighted){
weights <- rep(1, nrow(seqdata))
}
seqdata <- as.matrix(seqdata)
dummies <- function(b){
lastbi <- breaks[[b]][1]
bi <- breaks[[b]][2]
bindice <- lastbi:bi
mat <- matrix(0, nrow=nrow(seqdata), ncol=nalph)
ndot <- vector("numeric", length=nalph)
bseq <- seqdata[, bindice]
myrowSums <- function(x){
if(!is.null(ncol(x))){
return(rowSums(x, na.rm=TRUE))
}else{
return(x)
}
}
for(i in 1:nalph){
mat[, i] <- myrowSums(bseq==alph[i])
}
ndot <- colSums(weights*mat, na.rm=TRUE)
mat <- rbind(mat,ndot)
non0rsum <- rowSums(mat, na.rm=TRUE) > 0
mat[non0rsum,] <- mat[non0rsum,]/rowSums(mat[non0rsum,], na.rm=TRUE)
if (euclid) {
maxd <- ifelse(norm, 2, 1)
mat[nrow(mat),] <- rep(maxd, length(ndot))
mat[nrow(mat),ndot==0] <- 0
}
else {
if(!is.null(global.pdotj)){
mat[nrow(mat),] <- global.pdotj
mat[nrow(mat),ndot==0] <- 0
}
pdot <- mat[nrow(mat),ndot!=0]
if(length(pdot)>1){
cmin <- c(min(pdot),min(pdot[-which.min(pdot)]))
maxd <- ifelse(norm, 1/cmin[1] + 1/cmin[2], 1)
mat[nrow(mat),] <- mat[nrow(mat),] * maxd
}
}
return(mat)
}
allmat <- list()
for(b in 1:length(breaks)){
allmat[[b]] <- dummies(b)
}
allmat <- do.call(cbind, allmat)
pdotj <- allmat[nrow(allmat),]
allmat <- allmat[-nrow(allmat),]
ndotj <- colSums(allmat)
cond <- pdotj>0
allmat <- allmat[, cond]
pdotj <- pdotj[cond]
n <- nrow(seqdata)
sets <- FALSE
if (inherits(refseq, "list")) {
allmat.r <- rbind(allmat[refseq[[1]],],allmat[refseq[[2]],])
n1 <- length(refseq[[1]])
n2 <- length(refseq[[2]])
refseq.id <- c(n1, n1 + n2)
allmat <- allmat[c(refseq[[1]],refseq[[2]]),]
sets <- TRUE
} else if (!is.null(refseq)) {
refseq.id <- c(refseq,refseq)
sets <- FALSE
}
if (is.null(refseq)) {
dd <- .Call(C_tmrChisq, as.double(allmat), as.integer(dim(allmat)), as.double(pdotj))
}
else{
dd <- .Call(C_tmrChisqRef, as.double(allmat), as.integer(dim(allmat)), as.double(pdotj), as.integer(refseq.id))
}
if (norm) dd <- dd/sqrt(length(breaks))
if (sets) {
dd <- matrix(dd, nrow=n1, ncol=n2, byrow=FALSE, dimnames=list(rownames(seqdata)[refseq[[1]]],rownames(seqdata)[refseq[[2]]]))
} else if (is.null(refseq)) {
attributes(dd) <- list(Size = n, Labels = rownames(seqdata), Diag = FALSE,
Upper = FALSE, method = "Chi square sequence", call = match.call(),
class = "dist")
} else {
names(dd) <- rownames(seqdata)
}
return(dd)
}
|
flip.matrix <-
function(x) {
mirror.matrix(rotate180.matrix(x))
}
|
dmbc_fit <- function(D, p, G, family, control, prior, start) {
S <- length(D)
n <- attr(D[[1]], "Size")
m <- n*(n - 1)/2
totiter <- control[["burnin"]] + control[["nsim"]]
p <- as.integer(p)
G <- as.integer(G)
z.chain <- z.chain.p <- array(NA, dim = c(totiter, n, p, G))
eta.chain <- alpha.chain <- sigma2.chain <- lambda.chain <- array(NA, dim = c(totiter, G))
x.chain <- array(NA, dim = c(totiter, S))
prob.chain <- x.ind.chain <- array(0, dim = c(totiter, S, G))
loglik <- logprior <- logpost <- numeric(totiter)
hyper.eta.a <- prior[["eta"]][["a"]]
hyper.eta.b <- prior[["eta"]][["b"]]
hyper.sigma2.a <- prior[["sigma2"]][["a"]]
hyper.sigma2.b <- prior[["sigma2"]][["b"]]
hyper.lambda <- prior[["lambda"]]
if (control[["verbose"]]) message("Running the MCMC simulation...")
res.mcmc <- .Call('dmbc_mcmc', PACKAGE = 'dmbc',
raiD = as.integer(unlist(D)),
raix = as.integer(start$x),
raing = as.integer(start$ng),
radalpha = as.double(start$alpha),
rn = as.integer(n),
rp = as.integer(p),
rG = as.integer(G),
rS = as.integer(S),
rtotiter = as.integer(totiter),
radZ = as.double(start$z),
rgamma_z = as.double(control[["z.prop"]]),
reta = as.double(start$eta),
rgamma_alpha = as.double(control[["alpha.prop"]]),
rsigma2 = as.double(start$sigma2),
rlambda = as.double(start$lambda),
rhyper_eta_a = as.double(hyper.eta.a),
rhyper_eta_b = as.double(hyper.eta.b),
rhyper_sigma2_a = as.double(hyper.sigma2.a),
rhyper_sigma2_b = as.double(hyper.sigma2.b),
rhyper_lambda = as.double(hyper.lambda),
rfamily = as.character(family),
rverbose = as.integer(control[["verbose"]])
)
z.chain <- z.chain.p <- array(res.mcmc[[1]], c(totiter, n, p, G))
alpha.chain <- array(res.mcmc[[2]], c(totiter, G))
eta.chain <- array(res.mcmc[[3]], c(totiter, G))
sigma2.chain <- array(res.mcmc[[4]], c(totiter, G))
lambda.chain <- array(res.mcmc[[5]], c(totiter, G))
prob.chain <- array(res.mcmc[[6]], c(totiter, S, G))
x.chain <- array(res.mcmc[[7]], c(totiter, S))
x.ind.chain <- array(res.mcmc[[8]], c(totiter, S, G))
accept <- t(array(res.mcmc[[9]], c(G, 2)))
loglik <- as.numeric(res.mcmc[[10]])
logprior <- as.numeric(res.mcmc[[11]])
logpost <- as.numeric(res.mcmc[[12]])
if (control[["procrustes"]] | control[["relabel"]]) {
if (control[["verbose"]]) message("Post-processing the chain:")
if (control[["procrustes"]]) {
if (control[["verbose"]]) message(" - applying Procrustes transformation...")
if (control[["verbose"]]) {
pb <- dmbc_pb(min = 0, max = (totiter*G - 1), width = 49)
}
no <- 0
for (niter in 1:totiter) {
for (g in 1:G) {
if (control[["verbose"]]) dmbc_setpb(pb, no)
if (p == 1) {
z.chain.p[niter, , , g] <- as.numeric(MCMCpack::procrustes(as.matrix(z.chain[niter, , , g]),
as.matrix(z.chain[totiter, , , g]), translation = TRUE, dilation = FALSE)$X.new)
} else {
z.chain.p[niter, , , g] <- MCMCpack::procrustes(z.chain[niter, , , g], z.chain[totiter, , , g],
translation = TRUE, dilation = FALSE)$X.new
}
no <- no + 1
}
}
if (control[["verbose"]]) {
close(pb)
}
}
if (control[["relabel"]]) {
if (G > 1) {
if (totiter > 10) {
if (control[["verbose"]]) message(" - relabeling the parameter chain...")
init <- ifelse(totiter <= 100, 5, 100)
theta <- .Call('dmbc_pack_par', PACKAGE = 'dmbc',
radz = as.double(z.chain.p),
radalpha = as.double(alpha.chain),
radlambda = as.double(lambda.chain),
rn = as.integer(n),
rp = as.integer(p),
rM = as.integer(totiter),
rG = as.integer(G)
)
theta.relab <- .Call('dmbc_relabel', PACKAGE = 'dmbc',
radtheta = as.double(theta),
radz = as.double(z.chain.p),
radalpha = as.double(alpha.chain),
radeta = as.double(eta.chain),
radsigma2 = as.double(sigma2.chain),
radlambda = as.double(lambda.chain),
radprob = as.double(prob.chain),
raix_ind = as.integer(x.ind.chain),
rinit = as.integer(init),
rn = as.integer(n),
rp = as.integer(p),
rS = as.integer(S),
rM = as.integer(totiter),
rR = as.integer(m + 1),
rG = as.integer(G),
rverbose = as.integer(control[["verbose"]])
)
theta <- array(theta.relab[[1]], c(totiter, (m + 1), G))
z.chain.p <- array(theta.relab[[2]], c(totiter, n, p, G))
alpha.chain <- array(theta.relab[[3]], c(totiter, G))
eta.chain <- array(theta.relab[[4]], c(totiter, G))
sigma2.chain <- array(theta.relab[[5]], c(totiter, G))
lambda.chain <- array(theta.relab[[6]], c(totiter, G))
prob.chain <- array(theta.relab[[7]], c(totiter, S, G))
x.ind.chain <- array(theta.relab[[8]], c(totiter, S, G))
x.chain <- t(apply(x.ind.chain, 1, function(x) as.integer(x %*% 1:G)))
} else {
warning("the number of iterations is too small for relabeling; relabeling skipped.", call. = FALSE,
immediate. = TRUE)
}
}
}
}
if (control[["thin"]] > 1) {
if (control[["store.burnin"]]) {
tokeep <- seq(1, totiter, by = control[["thin"]])
} else {
tokeep <- seq(control[["burnin"]] + 1, totiter, by = control[["thin"]])
}
} else {
if (control[["store.burnin"]]) {
tokeep <- seq(1, totiter, by = 1)
} else {
tokeep <- seq(control[["burnin"]] + 1, totiter, by = 1)
}
}
z.chain <- z.chain[tokeep, , , , drop = FALSE]
z.chain.p <- z.chain.p[tokeep, , , , drop = FALSE]
alpha.chain <- alpha.chain[tokeep, , drop = FALSE]
eta.chain <- eta.chain[tokeep, , drop = FALSE]
sigma2.chain <- sigma2.chain[tokeep, , drop = FALSE]
lambda.chain <- lambda.chain[tokeep, , drop = FALSE]
prob.chain <- prob.chain[tokeep, , , drop = FALSE]
x.ind.chain <- x.ind.chain[tokeep, , , drop = FALSE]
x.chain <- x.chain[tokeep, , drop = FALSE]
loglik <- loglik[tokeep]
logprior <- logprior[tokeep]
logpost <- logpost[tokeep]
out <- new("dmbc_fit",
z.chain = z.chain,
z.chain.p = z.chain.p,
alpha.chain = alpha.chain,
eta.chain = eta.chain,
sigma2.chain = sigma2.chain,
lambda.chain = lambda.chain,
prob.chain = prob.chain,
x.ind.chain = x.ind.chain,
x.chain = x.chain,
accept = accept,
diss = D,
dens = list(loglik = loglik, logprior = logprior, logpost = logpost),
control = control,
prior = prior,
dim = list(n = n, p = p, G = G, S = S),
model = new("dmbc_model", p = p, G = G, family = family)
)
return(out)
}
dmbc_logLik_rbmds <- function(D, Z, alpha) {
S <- length(D)
diss <- list.sum(D)
delta <- dist(Z)
pi <- expit(alpha + delta)
out <- sum(log((pi^diss)*((1 - pi)^(S - diss))))
return(out)
}
dmbc_logLik <- function(D, Z, alpha, lambda, x) {
G <- length(alpha)
ng <- as.numeric(table(factor(x, levels = 1:G)))
logfg <- numeric(G)
ll <- 0
for (g in 1:G) {
if (ng[g] > 0) {
xg <- which(x == g)
logfg[g] <- dmbc_logLik_rbmds(D[xg], Z[, , g], alpha[g])
ll <- ll + ng[g]*log(lambda[g]) + logfg[g]
}
}
return(ll)
}
|
funcc_biclust<-function(fun_mat,delta,theta=1,template.type='mean',number=100,alpha=0,beta=0,const_alpha=FALSE,const_beta=FALSE,shift.alignement=FALSE,shift.max = 0.1, max.iter.align=100){
if(length(dim(fun_mat))!=3){
stop('Error: fun_mat should be an array of three dimensions')
}
if(template.type=='medoid' & (alpha!=0 | beta!=0)){
stop('Error: Medoid template is defined only for alpha and beta equal to 0')
}
if(shift.max>1 | shift.max<0){
stop('Error: shift.max must be in [0,1]')
}
if(!(alpha %in% c(0,1)) | !(beta %in% c(0,1))){
stop('Error: alpha and beta must be 0 or 1')
}
if(!(template.type %in% c('mean','medoid'))){
stop(paste0('Error: template.type ',template.type,' is not defined'))
}
if(number<=0 | number%%1!=0){
stop('Error: number must be an integer greater than 0')
}
if(!(shift.alignement %in% c(TRUE,FALSE))){
stop(paste0('Error: shift.alignement should be a logicol variable'))
}
if(max.iter.align<=0 | max.iter.align%%1!=0){
stop('Error: max.iter.align must be an integer greater than 0')
}
if(base::length(dim(fun_mat))!=3){
stop('Error: fun_mat must an array of three dimensions')
}
if(!(const_alpha %in% c(FALSE,TRUE)) | !(const_beta %in% c(FALSE,TRUE))){
stop('Error: const_alpha and const_beta must TRUE or FALSE')
}
if(delta<0 | !is.numeric(delta)){
stop('Error: delta must be a number greater than 1')
}
count_null <- apply(fun_mat, c(1,2), function(x) sum(is.na(x)))
not_null <- count_null < dim(fun_mat)[3]
parameter_input <- data.frame(delta=delta,theta=theta,template.type=template.type,alpha=alpha,beta=beta,const_alpha=const_alpha,const_beta=const_beta,shift.alignement=shift.alignement,shift.max=shift.max,max.iter.align=max.iter.align)
only.one <- ifelse(alpha==0 & beta==0,'True',
ifelse(alpha==0 & beta!=0, 'True_beta',
ifelse(alpha!=0 & beta==0,'True_alpha',
ifelse(alpha!=0 & beta!=0,'False',NA))))
n=dim(fun_mat)[1]
m=dim(fun_mat)[2]
p=dim(fun_mat)[3]
MYCALL <- match.call()
ma=c()
mi=c()
for(tt in 1:p){
ma<-c(ma,max(fun_mat[,,tt]))
mi<-c(mi,min(fun_mat[,,tt]))
}
x<-matrix(FALSE,nrow=n,ncol=number)
y<-matrix(FALSE,nrow=number,ncol=m)
xy <- matrix(FALSE,nrow=nrow(fun_mat),ncol=ncol(fun_mat))
logr<-rep(TRUE,nrow(fun_mat))
logc<-rep(TRUE,ncol(fun_mat))
Stop <- FALSE
n_clust <- 2
k <- 0
for(i in 1:number)
{
logr[logr==TRUE] <- ifelse(rowSums(matrix(is.na(matrix(fun_mat[logr,logc,1],nrow=sum(logr),ncol=sum(logc))),nrow=sum(logr),ncol=sum(logc)))==sum(logc),FALSE,TRUE)
if(only.one=='False' & (sum(1-xy)<2 | sum(logr)<=1 | sum(logc)<=1))
{
Stop <- TRUE
break
}
if(only.one=='True' & (sum(1-xy)<2 | sum(logr)<1 | sum(logc)<1))
{
Stop <- TRUE
break
}
if(only.one=='True_alpha' & (sum(1-xy)<2 | sum(logr)<1 | sum(logc)<=1))
{
Stop <- TRUE
break
}
if(only.one=='True_beta' & (sum(1-xy)<2 | sum(logr)<=1 | sum(logc)<1))
{
Stop <- TRUE
break
}
logc[logc==TRUE] <- ifelse(colSums(matrix(is.na(matrix(fun_mat[logr,logc,1],nrow=sum(logr),ncol=sum(logc))),nrow=sum(logr),ncol=sum(logc)))==sum(logr),FALSE,TRUE)
if(only.one=='False' & (sum(1-xy)<2 | sum(logr)<=1 | sum(logc)<=1))
{
Stop <- TRUE
break
}
if(only.one=='True' & (sum(1-xy)<2 | sum(logr)<1 | sum(logc)<1))
{
Stop <- TRUE
break
}
if(only.one=='True_alpha' & (sum(1-xy)<2 | sum(logr)<1 | sum(logc)<=1))
{
Stop <- TRUE
break
}
if(only.one=='True_beta' & (sum(1-xy)<2 | sum(logr)<=1 | sum(logc)<1))
{
Stop <- TRUE
break
}
fun_mat_temp <- fun_mat
fun_mat_temp <- array(fun_mat_temp[logr,logc,],dim = c(sum(logr),sum(logc),dim(fun_mat)[3]))
erg<-bigcc_fun(fun_mat_temp,delta,theta,template.type,alpha,beta,const_alpha,const_beta,shift.alignement,shift.max, max.iter.align,only.one)
n_clust <- n_clust-1
if(sum(erg[[1]])==0 & n_clust==0 | sum(erg[[1]])==0 & i==1)
{
Stop <- TRUE
break
}
else if (sum(erg[[1]])==0 & n_clust>=1){
cl <- cl+1
logr <- rep(F,nrow(xy))
logr[clus_row[,cl]] <- T
logc <- rep(F,ncol(xy))
logc[clus_col[cl,]] <- T
}
else
{
k = k+1
x[logr,k]<-erg[[1]]
y[k,logc]<-erg[[2]]
xy <- xy + t(matrix(base::rep(x[,k],each=ncol(y)),nrow=ncol(y)))* matrix(base::rep(y[k,],each=nrow(x)),nrow=nrow(x))
if(only.one=='False'){ res <- biclust::biclust(1-xy, method=biclust::BCBimax(), minr=2, minc=2, number=100)}
if(only.one=='True'){res <- biclust::biclust(1-xy, method=biclust::BCBimax(), minr=1, minc=1, number=100)}
if(only.one=='True_alpha'){res <- biclust::biclust(1-xy, method=biclust::BCBimax(), minr=1, minc=2, number=100)}
if(only.one=='True_beta'){res <- biclust::biclust(1-xy, method=biclust::BCBimax(), minr=2, minc=1, number=100)}
n_clust <- res@Number
cl <- 1
if(n_clust==0){
Stop <- TRUE
break}
clus_row <- res@RowxNumber
clus_col <- res@NumberxCol
dimensioni <- colSums(clus_row) * rowSums(clus_col)
if_oneone <- which(dimensioni>1)
if(length(if_oneone)==0)
{Stop <- TRUE
break}
if(length(if_oneone)!=n_clust){
n_clust <- length(if_oneone)
clus_row <- matrix(clus_row[,if_oneone],nrow=nrow(clus_row),ncol=n_clust)
clus_col <- matrix(clus_col[if_oneone,],nrow=n_clust,ncol=ncol(clus_col))
}
if(n_clust==0){
Stop <- TRUE
break}
if(n_clust>1){
dim <- colSums(clus_row) * rowSums(clus_col)
clus_row <- clus_row[,order(dim,decreasing=TRUE)]
clus_col <- clus_col[order(dim,decreasing=TRUE),]
}
logr <- rep(F,nrow(xy))
logr[clus_row[,1]] <- T
logc <- rep(F,ncol(xy))
logc[clus_col[1,]] <- T
}
}
if(Stop)
{
clus_row <- x[,1:k]
clus_col <- y[1:k,]
if(k>1){
dim <- colSums(clus_row) * rowSums(clus_col)
clus_row <- clus_row[,order(dim,decreasing=TRUE)]
clus_col <- clus_col[order(dim,decreasing=TRUE),]
}
return(list(biclust::BiclustResult(as.list(MYCALL),as.matrix(clus_row),as.matrix(clus_col),(k),list(0)),parameter=parameter_input))
}
else
{
clus_row <- x[,1:k]
clus_col <- y[1:k,]
if(k>1){
dim <- colSums(clus_row) * rowSums(clus_col)
clus_row <- clus_row[,order(dim,decreasing=TRUE)]
clus_col <- clus_col[order(dim,decreasing=TRUE),]
}
return(list(biclust::BiclustResult(as.list(MYCALL),as.matrix(clus_row),as.matrix(clus_col),k,list(0)),parameter=parameter_input))
}
}
|
test_that("coordinates can be used as features", {
task = test_make_twoclass_task(coords_as_features = TRUE)
expect_names(c("x", "y"), subset.of = task$feature_names)
})
test_that("printing works", {
task = test_make_twoclass_task()
expect_output(print(task))
expect_data_table(task$coordinates())
expect_output(print(task$truth()))
})
test_that("Supplying a non-spatio temporal task gives descriptive error message", {
expect_error(
rsmp("spcv_coords")$instantiate(tsk("boston_housing")),
"Assertion on 'task' failed: Must inherit from class 'TaskClassifST'/'TaskRegrST'")
})
test_that("coordinates can be used as features", {
task = test_make_twoclass_task(coords_as_features = TRUE)
expect_names(c("x", "y"), subset.of = task$feature_names)
})
test_that("sf objects can be used for task creation", {
task = test_make_sf_twoclass_task()
expect_output(print(task))
expect_data_table(task$coordinates())
expect_output(print(task$truth()))
})
test_that("sf objects can be used for task creation", {
task = test_make_sf_regr_task()
expect_output(print(task))
expect_data_table(task$coordinates())
expect_output(print(task$truth()))
})
test_that("tasks created from sf objects do not duplicate rows", {
data = test_make_sf_twoclass_df()
task = TaskClassifST$new(
id = "sp_regression",
backend = data,
target = "response",
extra_args = list(
coordinate_names = c("x", "y"),
crs = "+proj=utm +zone=33 +datum=WGS84 +units=m +no_defs",
coords_as_features = FALSE)
)
expect_equal(nrow(task$data()), nrow(data))
})
|
sEddyProc <- setRefClass('sEddyProc', fields = list(
sID = 'character'
, sDATA = 'data.frame'
, sINFO = 'list'
, sLOCATION = 'list'
, sTEMP = 'data.frame'
, sUSTAR_DETAILS = 'list'
, sUSTAR = 'data.frame'
, sUSTAR_SCEN = 'data.frame'
))
sEddyProc_initialize <- function(
ID = ID.s
, Data = Data.F
, ColNames = c('NEE','Rg','Tair','VPD', 'Ustar')
, ColPOSIXTime = 'DateTime'
, DTS = if (!missing(DTS.n)) DTS.n else 48
, ColNamesNonNumeric = character(0)
, LatDeg = NA_real_
, LongDeg = if (!missing(Long_deg.n)) Long_deg.n else NA_real_
, TimeZoneHour = if (!missing(TimeZone_h.n)) TimeZone_h.n else NA_integer_
, ID.s
, Data.F
, ColNames.V.s
, ColPOSIXTime.s
, DTS.n
, ColNamesNonNumeric.V.s
, Lat_deg.n
, Long_deg.n
, TimeZone_h.n
, ...
) {
if (!missing(ColNames.V.s)) ColNames <- ColNames.V.s
if (!missing(ColNamesNonNumeric.V.s)) ColNamesNonNumeric <- ColNamesNonNumeric.V.s
if (!missing(ColPOSIXTime.s)) ColPOSIXTime <- ColPOSIXTime.s
if (!missing(Lat_deg.n)) LatDet <- Lat_deg.n
varNamesDepr <- c(
"ID.s","Data.F","ColNames.V.s","ColPOSIXTime.s","DTS.n"
,"ColNamesNonNumeric.V.s","Lat_deg.n","Long_deg.n","TimeZone_h.n")
varNamesNew <- c(
"ID","Data","ColNames","ColPOSIXTime","DTS"
,"ColNamesNonNumeric","LatDeg","LongDeg","TimeZoneHour")
iDepr = which(!c(
missing(ID.s),missing(Data.F),missing(ColNames.V.s),missing(ColPOSIXTime.s)
,missing(DTS.n),missing(ColNamesNonNumeric.V.s),missing(Lat_deg.n)
,missing(Long_deg.n),missing(TimeZone_h.n)))
if (length(iDepr)) warning(
"Argument names ",varNamesDepr[iDepr]," have been deprecated."
," Please, use instead ", varNamesNew[iDepr])
if (!fCheckValString(ID) || is.na(ID) )
stop('For ID, a character string must be provided!')
fCheckColNames(Data, c(ColPOSIXTime, ColNames), 'fNewSData')
fCheckHHTimeSeries(Data[[ColPOSIXTime]], DTS = DTS, 'sEddyProc.initialize')
Time.V.p <- Data[[ColPOSIXTime]] - (0.5 * 24 / DTS * 60 * 60)
fCheckColNum(
Data, setdiff(ColNames, union(ColPOSIXTime,ColNamesNonNumeric)), 'sEddyProc.initialize')
fCheckColPlausibility(Data, ColNames, 'sEddyProc.initialize')
sID <<- ID
sDATA <<- cbind(sDateTime = Time.V.p, as.data.frame(Data[, ColNames, drop = FALSE]))
sTEMP <<- data.frame(sDateTime = Time.V.p)
YStart.n <- as.numeric(format(sDATA$sDateTime[1], '%Y'))
YEnd.n <- as.numeric(format(sDATA$sDateTime[length(sDATA$sDateTime)], '%Y'))
YNums.n <- (YEnd.n - YStart.n + 1)
if (YNums.n > 1) {
YName.s <- paste(substr(YStart.n, 3, 4), '-', substr(YEnd.n, 3, 4), sep = '')
} else {
YName.s <- as.character(YStart.n)
}
sINFO <<- list(
DIMS = length(sDATA$sDateTime)
, DTS = DTS
, Y.START = YStart.n
, Y.END = YEnd.n
, Y.NUMS = YNums.n
, Y.NAME = YName.s
)
sUSTAR_SCEN <<- data.frame()
.self$sSetLocationInfo( LatDeg , LongDeg , TimeZoneHour)
message('New sEddyProc class for site \'', ID, '\'')
callSuper(...)
}
sEddyProc$methods( initialize = sEddyProc_initialize)
sEddyProc_sSetLocationInfo <- function(
LatDeg = if (!missing(Lat_deg.n)) Lat_deg.n else NA_real_
, LongDeg = if (!missing(Long_deg.n)) Long_deg.n else NA_real_
, TimeZoneHour = if (!missing(TimeZone_h.n)) TimeZone_h.n else NA_integer_
, Lat_deg.n
, Long_deg.n
, TimeZone_h.n
) {
varNamesDepr <- c("Lat_deg.n","Long_deg.n","TimeZone_h.n")
varNamesNew <- c("LatDeg","LongDeg","TimeZoneHour")
iDepr = which(!c(missing(Lat_deg.n),missing(Long_deg.n),missing(TimeZone_h.n)))
if (length(iDepr)) warning(
"Argument names ",varNamesDepr[iDepr]," have been deprecated."
," Please, use instead ", paste(varNamesNew[iDepr], collapse = ","))
if (!is.na(LatDeg) & (LatDeg < -90 | LatDeg > 90)) stop(
"Latitude must be in interval -90 to + 90")
if (!is.na(LongDeg) & (LongDeg < -180 | LongDeg > 180)) stop(
"Longitude must be in interval -180 to + 180")
if (!is.na(TimeZoneHour) &
(TimeZoneHour < -12 | TimeZoneHour > +12 |
TimeZoneHour != as.integer(TimeZoneHour))) stop(
"Timezone must be an integer in interval -12 to 12")
sLOCATION <<- list(
LatDeg = LatDeg
, LongDeg = LongDeg
, TimeZoneHour = TimeZoneHour
)
}
sEddyProc$methods(sSetLocationInfo = sEddyProc_sSetLocationInfo)
sEddyProc_sSetUstarScenarios <- function(
uStarTh
, uStarSuffixes =
colnames(uStarTh)[-1]
) {
if (!("season" %in% colnames(sTEMP)) ) stop(
"Seasons not defined yet. Add column 'season' to dataset with entries"
, " matching column season in UstarThres.df, e.g. by calling"
, " yourEddyProcClass$sSetUStarSeasons(...)")
if (!all(is.finite(as.matrix(uStarTh[, -1])))) warning(
"Provided non-finite uStarThreshold for some periods."
," All values in corresponding period will be marked as gap.")
if (nrow(uStarTh) == 1L) {
uStarTh <- cbind(data.frame(
season = levels(.self$sTEMP$season)), uStarTh[, -1], row.names = NULL)
}
iMissing <- which( !(levels(.self$sTEMP$season) %in% uStarTh[[1]]))
if (length(iMissing)) stop(
"Need to provide uStar threshold for all seasons, but was missing for seasons"
, paste(levels(.self$sTEMP$season)[iMissing], collapse = ","))
nEstimates <- ncol(uStarTh) - 1L
uStarSuffixes <- unique(uStarSuffixes)
if (length(uStarSuffixes) != nEstimates) stop(
"umber of unique suffixes must correspond to number of uStar-thresholds"
,", i.e. number of columns in uStarTh - 1.")
sUSTAR_SCEN <<- uStarTh
colnames(sUSTAR_SCEN)[-1] <<- uStarSuffixes
}
sEddyProc$methods(sSetUstarScenarios = sEddyProc_sSetUstarScenarios)
sEddyProc_useSeaonsalUStarThresholds <- function(
) {
uStarThAgg <- .self$sGetEstimatedUstarThresholdDistribution()
uStarMap <- usGetSeasonalSeasonUStarMap(uStarThAgg)
.self$sSetUstarScenarios(uStarMap)
}
sEddyProc$methods(useSeaonsalUStarThresholds = sEddyProc_useSeaonsalUStarThresholds)
sEddyProc_useAnnualUStarThresholds <- function(
) {
uStarThAgg <- .self$sGetEstimatedUstarThresholdDistribution()
uStarMap <- usGetAnnualSeasonUStarMap(uStarThAgg)
.self$sSetUstarScenarios(uStarMap)
}
sEddyProc$methods(useAnnualUStarThresholds = sEddyProc_useAnnualUStarThresholds)
sEddyProc_sGetUstarScenarios <- function(
) {
if (!nrow(.self$sUSTAR_SCEN)) {
warning("uStar scenarios not set yet. Setting to annual mapping.")
.self$useAnnualUStarThresholds()
}
.self$sUSTAR_SCEN
}
sEddyProc$methods(sGetUstarScenarios = sEddyProc_sGetUstarScenarios)
sEddyProc_sGetUstarSuffixes <- function(
){
if (nrow(.self$sUSTAR_SCEN) == 0) return(character(0))
names(.self$sGetUstarScenarios())[-1L]
}
sEddyProc$methods(sGetUstarSuffixes = sEddyProc_sGetUstarSuffixes)
sEddyProc_sGetData <- function(
) {
'Get class internal sDATA data frame'
sDATA
}
sEddyProc$methods( sGetData = sEddyProc_sGetData)
sEddyProc_update_ustarthreshold_columns <- function(){
uStarScen <- .self$sGetUstarScenarios()
prefix <- "Ustar_Thresh_"
names(uStarScen)[-1] <- paste0(prefix, names(uStarScen)[-1])
.self$sTEMP <- .self$sTEMP %>% select(-grep(paste0("^",prefix), names(.self$sTEMP)))
.self$sTEMP <- left_join(.self$sTEMP, uStarScen, by = "season")
invisible(.self)
}
sEddyProc$methods(update_ustarthreshold_columns =
sEddyProc_update_ustarthreshold_columns)
sEddyProc_sExportData <- function()
{
lDATA <- sDATA
lDATA$sDateTime <- lDATA$sDateTime + (15L * 60L)
colnames(lDATA) <- c('DateTime', colnames(lDATA)[-1])
lDATA
}
sEddyProc$methods( sExportData = sEddyProc_sExportData)
sEddyProc_sExportResults <- function(
isListColumnsExported = FALSE
) {
'Export class internal sTEMP data frame with result columns'
iListColumns <- which(sapply(sTEMP, is.list) )
iOmit <- if (isListColumnsExported) c(1L) else c(1L, iListColumns)
sTEMP[, -iOmit]
}
sEddyProc$methods(sExportResults = sEddyProc_sExportResults)
sEddyProc_sPrintFrames <- function(
nRows = if (!missing(NumRows.i)) NumRows.i else 100
, NumRows.i = 100
)
{
'Print class internal sDATA data frame'
nRows <- min(nrow(sDATA), nrow(sTEMP), nRows)
print(cbind(sDATA, sTEMP[, -1])[1:nRows, ])
}
sEddyProc$methods(sPrintFrames = sEddyProc_sPrintFrames)
|
biclustextraplots_WINDOW <- function(methodname){
new.frames <- .initialize.new.frames()
grid.config <- .initialize.grid.config()
grid.rows <- .initialize.grid.rows()
make.extra.results <- TRUE
list.methods.noextra <- c("Rqubic")
if(methodname %in% list.methods.noextra){make.extra.results <- FALSE}
toolname <- "Extra Plots from `biclust'"
toolhelp <- "bubbleplot"
input <- "plotdiagTab"
type <- "buttons"
frame.name <- "barchartbuttonframe"
button.name <- "Draw Plot"
button.function <- "biclustbarchart"
button.data <- "x"
button.biclust <- "Bicres"
save <- FALSE
arg.frames <- c()
new.frames <- .add.frame(input=input,save=save,frame.name=frame.name,type=type,button.name=button.name,button.function=button.function,button.data=button.data,button.biclust=button.biclust,arg.frames=arg.frames,new.frames=new.frames)
type <- "radiobuttons"
frame.name <- "bubbleplotprojframe"
argument.names <- c("Mean","Iso Mds","Cmd Scale")
arguments <- c("projection")
argument.values <- c("mean","isomds","cmdscale")
argument.types <- "char"
initial.values <- "mean"
title <- "Projection:"
border <- FALSE
new.frames <- .add.frame(input=input,type=type,frame.name=frame.name,argument.names=argument.names,arguments=arguments,argument.values=argument.values,initial.values=initial.values,title=title,border=border,new.frames=new.frames,argument.types=argument.types)
type <- "checkboxes"
frame.name <- "bubbleplotlabelframe"
argument.names <- c("Show Labels?")
arguments <- c("showLabels")
initial.values <- c(0)
title <- ""
border <- FALSE
new.frames <- .add.frame(input=input,type=type,frame.name=frame.name,argument.names=argument.names,arguments=arguments,initial.values=initial.values,title=title,border=border,new.frames=new.frames)
type <- "entryfields"
frame.name <- "bubbleplotentryframe"
argument.names <- c("bicResult2","bicResult3")
argument.types <- c("num","num")
arguments <- c("bicResult2","bicResult3")
initial.values <- c("NULL","NULL")
title <- "Extra Bicluster Results?"
border <- FALSE
entry.width <- c("8","8")
new.frames <- .add.frame(input=input,type=type,frame.name=frame.name,argument.names=argument.names,arguments=arguments,initial.values=initial.values,title=title,border=border,entry.width=entry.width,argument.types=argument.types ,new.frames=new.frames)
type <- "buttons"
frame.name <- "bubbleplotbuttonframe"
button.name <- "Draw Plot"
button.function <- "bubbleplot"
button.data <- "x"
button.biclust <- "bicResult1"
arg.frames <- c("bubbleplotentryframe","bubbleplotprojframe","bubbleplotlabelframe")
new.frames <- .add.frame(input=input,frame.name=frame.name,type=type,button.name=button.name,button.function=button.function,button.data=button.data,button.biclust=button.biclust,arg.frames=arg.frames,new.frames=new.frames)
type <- "entryfields"
frame.name <- "plotclustentryframe"
argument.names <- c("Total Number of Biclusters")
argument.types <- c("num")
arguments <- c("noC")
initial.values <- c("6")
title <- ""
border <- FALSE
entry.width <- c("4")
new.frames <- .add.frame(input=input,type=type,frame.name=frame.name,argument.names=argument.names,arguments=arguments,initial.values=initial.values,title=title,border=border,entry.width=entry.width,argument.types=argument.types ,new.frames=new.frames)
type <- "checkboxes"
frame.name <- "plotclustcheckframe"
argument.names <- c("Legend?")
arguments <- c("legende")
initial.values <- c(0)
title <- ""
border <- FALSE
new.frames <- .add.frame(input=input,type=type,frame.name=frame.name,argument.names=argument.names,arguments=arguments,initial.values=initial.values,title=title,border=border,new.frames=new.frames)
type <- "buttons"
frame.name <- "plotclustbuttonframe"
button.name <- "Draw Plot"
button.function <- "plotclust"
button.data <- "x"
button.biclust <- "res"
save <- FALSE
arg.frames <- c("plotclustcheckframe","plotclustentryframe")
new.frames <- .add.frame(input=input,save=save,frame.name=frame.name,type=type,button.name=button.name,button.function=button.function,button.data=button.data,button.biclust=button.biclust,arg.frames=arg.frames,new.frames=new.frames)
if(make.extra.results==TRUE){
grid.config <- .grid.matrix(input=input,c("bubbleplotprojframe","bubbleplotentryframe","bubbleplotbuttonframe","bubbleplotlabelframe",NA,NA,"plotclustentryframe","plotclustcheckframe","plotclustbuttonframe" ,"barchartbuttonframe",NA,NA) ,byrow=TRUE,nrow=4,ncol=3,grid.config=grid.config)
}
else{
grid.config <- .grid.matrix(input=input,c("bubbleplotprojframe",NA,"bubbleplotbuttonframe","bubbleplotlabelframe",NA,NA,"plotclustentryframe","plotclustcheckframe","plotclustbuttonframe" ,"barchartbuttonframe",NA,NA) ,byrow=TRUE,nrow=4,ncol=3,grid.config=grid.config)
}
grid.rows <- .combine.rows(input=input,rows=c(1,2),title="Biclust Bubble Plot",border=TRUE,grid.rows=grid.rows,grid.config=grid.config)
grid.rows <- .combine.rows(input=input,rows=c(3),title="Barplot of Bicluster",border=TRUE,grid.rows=grid.rows,grid.config=grid.config)
grid.rows <- .combine.rows(input=input,rows=c(4),title="Bar Chart Plot",border=TRUE,grid.rows=grid.rows,grid.config=grid.config)
newtool_template(toolname=toolname,methodname=methodname,toolhelp=toolhelp,grid.config=grid.config,grid.rows=grid.rows,new.frames=new.frames)
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
options(useFancyQuotes=FALSE, width=100)
library(hot.deck)
data(isq99)
out <- hot.deck(isq99, sdCutoff=3, IDvars = c("IDORIGIN", "YEAR"))
numdonors <- sapply(out$donors, length)
numdonors <- sapply(out$donors, length)
numdonors <- ifelse(numdonors > 5, 6, numdonors)
numdonors <- factor(numdonors, levels=1:6, labels=c(1:5, ">5"))
table(numdonors)
tscslag <- function(dat, x, id, time){
obs <- apply(dat[, c(id, time)], 1, paste, collapse=".")
tm1 <- dat[[time]] - 1
lagobs <- apply(cbind(dat[[id]], tm1), 1, paste, collapse=".")
lagx <- dat[match(lagobs, obs), x]
}
for(i in 1:length(out$data)){
out$data[[i]]$lagAI <- tscslag(out$data[[i]], "AI", "IDORIGIN", "YEAR")
out$data[[i]]$lagPCGNP <- tscslag(out$data[[i]], "PCGNP", "IDORIGIN", "YEAR")
out$data[[i]]$lagLPOP <- tscslag(out$data[[i]], "LPOP", "IDORIGIN", "YEAR")
}
for(i in 1:length(out$data)){
out$data[[i]]$pctchgPCGNP <- with(out$data[[i]], c(PCGNP-lagPCGNP)/lagPCGNP)
out$data[[i]]$pctchgLPOP <- with(out$data[[i]], c(LPOP-lagLPOP)/lagLPOP)
}
out <- hd2amelia(out)
results <- list()
for(i in 1:length(out$imputations)){
results[[i]] <- lm(AI ~ lagAI + pctchgPCGNP + PCGNP + pctchgLPOP + LPOP + MIL2 + LEFT +
BRIT + POLRT + CWARCOW + IWARCOW2, data=out$imputations[[i]])
}
summary(mitools::MIcombine(results))
out.mids <- miceadds::datalist2mids(out$imputations)
s <- summary(mice::pool(mice::lm.mids(AI ~ lagAI + pctchgPCGNP + PCGNP + pctchgLPOP + LPOP + MIL2 + LEFT +
BRIT + POLRT + CWARCOW + IWARCOW2, data=out.mids)))
print(s, digits=4)
|
SolarConstant <- 1366.1
|
plotly_POST <- function(x = last_plot(), filename = NULL, fileopt = "overwrite",
sharing = c("public", "private", "secret"), ...) {
.Deprecated("api_create")
api_create(x, filename = filename, sharing = sharing, fileopt = fileopt, ...)
}
get_figure <- function(username, id) {
.Deprecated("api_download_plot")
api_download_plot(id, username)
}
plotly <- function(username, key) {
if (!missing(username)) {
message("Storing 'username' as the environment variable 'plotly_username'")
Sys.setenv("plotly_username" = username)
} else {
usr <- verify("username")
}
if (!missing(key)) {
message("Storing 'key' as the environment variable 'plotly_api_key'")
Sys.setenv("plotly_api_key" = key)
} else {
key <- verify("api_key")
}
.Deprecated("ggplotly")
.Deprecated("plot_ly")
invisible(NULL)
}
offline <- function(p, height, width, out_dir, open_browser) {
.Deprecated("plot_ly")
p
}
as.widget <- function(x, ...) {
.Deprecated("as_widget")
x
}
toWidget <- as.widget
|
compute.beta.hat <- function(x, M){
l <- lm(x ~ M - 1)
return(as.numeric(l$coef))
}
compute.z <- function(x, M, beta=NULL){
if (!is.null(beta)) {
z <- x - M %*% beta
} else {
Q <- qr.Q(qr(M))
H <- Q %*% t(Q)
z <- x - H %*% x
}
return(as.numeric(z))
}
compute.sigma2.hat <- function(z){
drop(crossprod(z)/length(z))
}
computeAuxVariables <- function(model) {
aux <- covMatrix(model@covariance, X=model@X, [email protected])
C <- aux[[1]]
T <- chol(C)
x <- backsolve(t(T), model@y, upper.tri = FALSE)
M <- backsolve(t(T), model@F, upper.tri = FALSE)
model@T <- T
model@M <- M
if (length([email protected])>0){
z <- backsolve(t(T), model@y-model@F%*%as.matrix([email protected]), upper.tri=FALSE)
model@z <- as.numeric(z)
} else {
model@z <- numeric(0)
}
return(model)
}
|
getPrisma <- function(studyStatus =NULL, prismaFormat = NULL){
if(is.null(prismaFormat)){
reqNames <- c("Source", "Filter")
missNames <- setdiff(reqNames, names(studyStatus))
if(length(missNames) != 0 ) stop(sprintf("%s not in studyStatus argument.", paste(missNames, collapse = " and ")))
warning("prismaFormat is null so attempting to make automatic one from studyStatus")
prismaFormat <- getPrismaFormat(studyStatus)
}
reqNames <- c("Source", "Node","Filter", "End")
if(!all(prismaFormat$nodeType %in% reqNames) ) stop("Check nodeType some of these not allowed")
createPrisma(prismaFormat)
}
|
new.circle <- function(radius) structure(radius, class = "circle")
new.square <- function(width) structure(width, class = "square")
as.character.circle <- function(radius) sprintf("circle of radius %d", radius)
as.character.square <- function(width) sprintf("%dx%d square", width, width)
area <- function(animal) UseMethod("area")
area.circle <- function(radius) radius*radius*pi
area.square <- function(width) width*width
`%/%.circle` <- function(e1, e2) {
if(e1 == 1) {
return(e1+e2)
}
if(e1 == 2) {
return(42)
}
if(e1 == 3) {
return(43)
}
if(e1 == 4) {
return(44)
}
if(e1 == 3) {
return(43)
}
if(e1 == 4) {
return(44)
}
if(e1 == 3) {
return(43)
}
if(e1 == 4) {
return(44)
}
}
|
get_feature_snp <- function(snp_tbl, feature_tbl, extend=0.005) {
feature_tbl <- dplyr::filter(feature_tbl,
.data$type %in% c("exon","gene","pseudogene","pseudogenic_exon"))
if(!nrow(feature_tbl))
return(NULL)
genes <- dplyr::mutate(
dplyr::ungroup(
dplyr::summarize(
dplyr::group_by(feature_tbl, .data$Dbxref),
min_bp = min(.data$start) - extend,
max_bp = max(.data$stop) + extend)),
Dbxref = ifelse(is.na(.data$Dbxref), "NA", .data$Dbxref))
if(!nrow(genes))
return(NULL)
tmpfn <- function(x,snp_tbl) {
keep <- (x[1] <= snp_tbl$pos) & (x[2] >= snp_tbl$pos)
snp_tbl[keep,]
}
tmp <- apply(as.matrix(genes[,2:3]), 1, tmpfn, snp_tbl)
names(tmp) <- genes$Dbxref
tmp <- dplyr::bind_rows(tmp, .id = "Dbxref")
out <-
dplyr::arrange(
dplyr::select(
dplyr::mutate(
dplyr::inner_join(
dplyr::distinct(
feature_tbl,
.data$start, .data$stop, .data$strand, .data$type, .keep_all=TRUE),
tmp, by = "Dbxref"),
SNP = .data$snp_id),
-.data$snp_id),
.data$Name, .data$type)
if(!nrow(out))
return(NULL)
class(out) <- c("feature_snp", class(out))
out
}
summary.feature_snp <- function(object, ...) {
dplyr::ungroup(
dplyr::summarize(
dplyr::group_by(object, .data$type),
count = dplyr::n(),
minbp = min(.data$start),
maxbp = max(.data$stop)))
}
|
network.amendment <- function(x, membership, minus.log=TRUE){
oops <- requireNamespace("igraph", quietly = TRUE)
if (!oops) {
stop("igraph package missing: Please install, see: ?install.packages")
}
if(!inherits(x, "cna")){
stop("Input x must be a 'cna' class object as obtained from cna()")
}
if(!is.numeric(membership)){
stop("Input membership must be a numeric vector")
}
if(length(membership) != length(x$communities$membership)){
stop("Input membership and x$community$membership must be of the same length")
}
contract.matrix <- function(cij.network, membership,
collapse.method="max", minus.log=TRUE){
if(minus.log){
cij.network[cij.network>0] <- exp(-cij.network[cij.network>0])
}
collapse.options=c("max", "median", "mean", "trimmed")
collapse.method <- match.arg(tolower(collapse.method), collapse.options)
node.num <- max(x$communities$membership)
if(node.num > 1){
collapse.cij <- matrix(0, nrow=node.num, ncol=node.num)
inds <- pairwise(node.num)
for(i in 1:nrow(inds)) {
comms.1.inds <- which(membership==inds[i,1])
comms.2.inds <- which(membership==inds[i,2])
submatrix <- cij.network[comms.1.inds, comms.2.inds]
collapse.cij[ inds[i,1], inds[i,2] ] = switch(collapse.method,
max = max(submatrix),
median = median(submatrix),
mean = mean(submatrix),
trimmed = mean(submatrix, trim = 0.1))
}
if(minus.log){
collapse.cij[collapse.cij>0] <- -log(collapse.cij[collapse.cij>0])
}
collapse.cij[ inds[,c(2,1)] ] = collapse.cij[ inds ]
colnames(collapse.cij) <- 1:ncol(collapse.cij)
}
else{
warning("There is only one community in the $communities object.
$community.cij object will be set to 0 in the
contract.matrix() function.")
collapse.cij <- 0
}
class(collapse.cij) <- c("dccm", "matrix")
return(collapse.cij)
}
x$communities$membership <- membership
x$community.cij <- contract.matrix(x$cij, membership, minus.log=minus.log)
cols=vmd_colors()
x$community.network <- igraph::graph.adjacency(x$community.cij,
mode="undirected",
weighted=TRUE,
diag=FALSE)
if(max(x$communities$membership) > length(unique(cols)) ) {
warning("The number of communities is larger than the number of unique
'colors' provided as input. Colors will be recycled")
}
igraph::V(x$network)$color <- cols[x$communities$membership]
igraph::V(x$community.network)$color <- cols[ 1:max(x$communities$membership)]
igraph::V(x$network)$size <- 1
igraph::V(x$community.network)$size <- table(x$communities$membership)
return(x)
}
|
context("rptBinary")
data(BeetlesMale)
suppressWarnings(RNGversion("3.5.0"))
set.seed(23)
R_est_1 <- rptBinary(Colour ~ (1|Population), grname=c("Population"), data=BeetlesMale, nboot=0, npermut=0)
test_that("rpt estimation works for one random effect, no boot, no permut, no parallelisation, logit link", {
expect_that(is.numeric(unlist(R_est_1$R)), is_true())
expect_equal(R_est_1$R["R_org", "Population"], 0.1853978, tolerance = 0.001)
expect_equal(R_est_1$R["R_link", "Population"], 0.1879297, tolerance = 0.001)
})
test_that("LRT works", {
expect_that(is.numeric(unlist(R_est_1$R)), is_true())
expect_equal(R_est_1$P$LRT_P, 8.656602e-15, tolerance = 0.001)
})
R_est_2 <- rptBinary(Colour ~ (1|Population), grname=c("Population"), data=BeetlesMale, nboot=2, npermut=0)
test_that("rpt estimation works for one random effect, boot, no permut, no parallelisation, logit link", {
expect_that(is.numeric(unlist(R_est_2$R)), is_true())
expect_equal(R_est_2$R["R_org", "Population"], 0.1853978, tolerance = 0.001)
expect_equal(R_est_2$R["R_link", "Population"], 0.1879296, tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_org["Population", "2.5%"]), 0.1448806, tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_org["Population", "97.5%"]), 0.1660169, tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_link["Population", "2.5%"]), 0.1458783, tolerance = 0.001)
expect_equal(as.numeric(R_est_2$CI_emp$CI_link["Population", "97.5%"]), 0.1654149, tolerance = 0.001)
})
R_est_3 <- rptBinary(Colour ~ (1|Population), grname=c("Population"), data=BeetlesMale, nboot=0, npermut=2)
test_that("rpt estimation works for one random effect, no boot, permut, no parallelisation, logit link", {
expect_that(is.numeric(unlist(R_est_3$R)), is_true())
expect_equal(R_est_3$R["R_org", "Population"], 0.1853978, tolerance = 0.001)
expect_equal(R_est_3$R["R_link", "Population"], 0.1879296, tolerance = 0.001)
expect_equal(R_est_3$P$P_permut_org, 0.5, tolerance = 0.001)
expect_equal(R_est_3$P$P_permut_link, 0.5, tolerance = 0.001)
})
R_est_4 <- rptBinary(Colour ~ (1|Container) + (1|Population), grname=c("Container", "Population", "Residual"),
data=BeetlesMale, nboot=0, npermut=0)
test_that("rpt estimation works for two random effects plus residual, no boot, no permut, no parallelisation, logit link", {
expect_that(is.numeric(unlist(R_est_4$R)), is_true())
expect_equal(R_est_4$R["R_org", "Container"], 0, tolerance = 0.001)
expect_equal(R_est_4$R["R_link", "Container"], 0, tolerance = 0.001)
expect_equal(R_est_4$R["R_org", "Population"], 0.1854004, tolerance = 0.001)
expect_equal(R_est_4$R["R_link", "Population"], 0.1879323, tolerance = 0.001)
expect_equal(R_est_4$R["R_link", "Residual"], 0.8120677, tolerance = 0.001)
})
test_that("LRTs works", {
expect_that(is.numeric(unlist(R_est_4$R)), is_true())
expect_equal(R_est_4$P[1, "LRT_P"], 1, tolerance = 0.001)
expect_equal(R_est_4$P[2, "LRT_P"], 5.80928e-09, tolerance = 0.001)
})
test_that("random effect components sum to up to one", {
expect_equal(sum(R_est_4$R["R_link", ]), 1)
})
R_est_5 <- rptBinary(Colour ~ (1|Container) + (1|Population), grname=c("Residual", "Container", "Population"), data=BeetlesMale, nboot=2, npermut=0)
test_that("rpt estimation is independent of the order in grname", {
expect_equal(R_est_4$R["R_org", "Container"], R_est_5$R["R_org", "Container"], tolerance = 0.001)
expect_equal(R_est_4$R["R_link", "Container"], R_est_5$R["R_link", "Container"], tolerance = 0.001)
expect_equal(R_est_4$R["R_org", "Population"], R_est_5$R["R_org", "Population"], tolerance = 0.001)
expect_equal(R_est_4$R["R_link", "Population"], R_est_5$R["R_link", "Population"], tolerance = 0.001)
expect_equal(R_est_4$R["R_org", "Residual"], R_est_5$R["R_org", "Residual"], tolerance = 0.001)
expect_equal(R_est_4$R["R_link", "Residual"], R_est_5$R["R_link", "Residual"], tolerance = 0.001)
})
test_that("rpt estimation works for two random effect, boot, no permut, no parallelisation, logit link", {
expect_equal(as.numeric(R_est_5$CI_emp$CI_org["Container", "2.5%"]), 0.000214565 , tolerance = 0.001)
expect_equal(as.numeric(R_est_5$CI_emp$CI_org["Container", "97.5%"]),0.008368035, tolerance = 0.001)
expect_equal(as.numeric(R_est_5$CI_emp$CI_org["Population", "2.5%"]), 0.091740174, tolerance = 0.001)
expect_equal(as.numeric(R_est_5$CI_emp$CI_org["Population", "97.5%"]), 0.206301801, tolerance = 0.001)
expect_equal(as.numeric(R_est_5$CI_emp$CI_link["Container", "2.5%"]), 0.000215459, tolerance = 0.001)
expect_equal(as.numeric(R_est_5$CI_emp$CI_link["Container", "97.5%"]), 0.0084029, tolerance = 0.001)
expect_equal(as.numeric(R_est_5$CI_emp$CI_link["Population", "2.5%"]), 0.092182856, tolerance = 0.001)
expect_equal(as.numeric(R_est_5$CI_emp$CI_link["Population", "97.5%"]), 0.2095188, tolerance = 0.001)
expect_equal(as.numeric(R_est_5$CI_emp$CI_link["Residual", "2.5%"]), 0.790265699, tolerance = 0.001)
expect_equal(as.numeric(R_est_5$CI_emp$CI_link["Residual", "97.5%"]), 0.8994142, tolerance = 0.001)
})
R_est_6 <- rptBinary(Colour ~ (1|Container) + (1|Population), grname=c("Container", "Population"), data=BeetlesMale, nboot=0, npermut=2)
test_that("rpt estimation is independent of the presence of Residual in grname", {
expect_equal(R_est_4$R["R_org", "Container"], R_est_6$R["R_org", "Container"], tolerance = 0.001)
expect_equal(R_est_4$R["R_link", "Container"], R_est_6$R["R_link", "Container"], tolerance = 0.001)
expect_equal(R_est_4$R["R_org", "Population"], R_est_6$R["R_org", "Population"], tolerance = 0.001)
expect_equal(R_est_4$R["R_link", "Population"], R_est_6$R["R_link", "Population"], tolerance = 0.001)
})
test_that("rpt estimation works for two random effect, no boot, permut, no parallelisation, logit link", {
expect_equal(R_est_6$P["Container", "P_permut_org"], 1, tolerance = 0.001)
expect_equal(R_est_6$P["Population", "P_permut_org"], 0.5, tolerance = 0.001)
expect_equal(R_est_6$P["Container", "P_permut_link"], 1, tolerance = 0.001)
expect_equal(R_est_6$P["Population", "P_permut_link"], 0.5, tolerance = 0.001)
})
R_est_7 <- rptBinary(Colour ~ Treatment + (1|Container) + (1|Population), grname=c("Fixed", "Container", "Population", "Residual"),
data=BeetlesMale, nboot=2, npermut=2, ratio = FALSE)
test_that("Variance estimation works for two random effects, boot, permut, Residual and Fixed", {
expect_equal(R_est_7$R["R_link", "Container"], 7.902152e-10, tolerance = 0.001)
expect_equal(R_est_7$R["R_link", "Population"], 1.054672 , tolerance = 0.001)
expect_equal(R_est_7$R["R_link", "Residual"], 4.086918, tolerance = 0.001)
expect_equal(R_est_7$R["R_link", "Fixed"], 0.2438065, tolerance = 0.001)
})
R_est_8 <- rptBinary(Colour ~ (1|Container) + (1|Population), grname=c("Container", "Population", "Residual", "Fixed"),
data=BeetlesMale, nboot=0, npermut=0, ratio = TRUE, adjusted=FALSE)
R_est_9 <- rptBinary(Colour ~ (1|Container) + (1|Population), grname=c("Fixed", "Container"),
data=BeetlesMale, nboot=0, npermut=0, ratio = TRUE, adjusted=FALSE)
test_that("Repeatabilities are equal for grouping factors independent of residual specification", {
expect_false(any(R_est_8$R[,"Fixed"] == R_est_9$R[,"Fixed"]) == FALSE)
})
R_est_10 <- rptBinary(Colour ~ (1|Container) + (1|Population), grname=c("Population", "Container"),
data=BeetlesMale, nboot=0, npermut=0, ratio = TRUE, adjusted=FALSE)
test_that("Repeatabilities are equal for different order in grname argument", {
expect_equal(R_est_10$R[,"Container"], R_est_6$R[,"Container"])
expect_equal(R_est_10$R[,"Population"], R_est_6$R[,"Population"])
})
test_that("LRTs are equal for different order in grname argument", {
expect_equal(R_est_10$P["Container", "LRT_P"], R_est_6$P["Container", "LRT_P"])
expect_equal(R_est_10$P["Population", "LRT_P"], R_est_6$P["Population", "LRT_P"])
})
R_est_11 <- rptBinary(Colour ~ (1|Population) + (1|Container), grname=c("Container", "Population"),
data=BeetlesMale, nboot=0, npermut=0, ratio = TRUE)
test_that("Repeatabilities are equal for different order in formula argument", {
expect_equal(R_est_10$R[,"Container"], R_est_11$R[,"Container"])
expect_equal(R_est_10$R[,"Population"], R_est_11$R[,"Population"])
})
test_that("LRTs are equal for different order in formula argument", {
expect_equal(R_est_10$P["Container", "LRT_P"], R_est_11$P["Container", "LRT_P"])
expect_equal(R_est_10$P["Population", "LRT_P"], R_est_11$P["Population", "LRT_P"])
})
|
context("test-rx_not")
test_that("not rule works", {
expect_equal(rx_not(value = "") %>% as.character(), "(?!)")
expect_false(grepl(rx_find(value = "q") %>% rx_not("u"), "qu", perl = TRUE))
expect_true(grepl(rx_find(value = "q") %>% rx_not("u"), "qa", perl = TRUE))
})
|
bounds_hy <- function(es, ext)
{
yi <- es$yi
vi <- es$vi
ub <- max(yi + 1)
if(ext == FALSE)
{
lb <- max(yi - 38*sqrt(vi))
} else
{
lb <- -600
}
return(c(lb, ub))
}
|
cr_symb <- function(k = k, m = m) {
p_symb <- gtools::permutations(k, m, repeats.allowed = TRUE)
rownames(p_symb) <- paste("Perm", 1:nrow(p_symb), sep="")
c_symb0 <- gtools::combinations(k, m, repeats.allowed = TRUE)
rownames(c_symb0) <- paste("Comb", 1:nrow(c_symb0), sep="")
c_symb <- matrix(rep(0, nrow(c_symb0) * k), ncol = k)
colnames(c_symb) <- paste("level",1:ncol(c_symb), sep="")
for (i in 1:nrow(c_symb0)) {
for (j in 1:k) {
c_symb[i, j] = sum(c_symb0[i, ] == j)
}
}
symb <- list(p_symb, c_symb, c_symb0)
names(symb)[1] <- "p_symb"
names(symb)[2] <- "c_symb"
names(symb)[3] <- "c_symb0"
return(symb)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.