code
stringlengths
1
13.8M
dist.SM<-function(x) { if(is.data.frame(x)) x<-as.matrix(x) if(is.null(dim(x))){ dim(x)<-c(length(x),1) } nr=nrow(x) t<-.C("fng3",as.double(x),as.integer(nrow(x)),as.integer(ncol(x)),wynik=double(nrow(x)*nrow(x)),PACKAGE="clusterSim")$wynik wynik<-matrix(nrow=nr,ncol=nr,dimnames=names(x)) for (i in 1:nr) for (j in 1:nr) { wynik[i,j]=t[(i-1)*nr+j] wynik[j,i]=t[(j-1)*nr+i] } as.dist(wynik) }
print.labeling <- structure(function(x, ...) { output2 <- x$att.dist cat("-------------------------------------------\n") cat("labeling for ACTCD\n") cat(paste(paste("based on", x$label.method, "label method"),"\n")) cat("-------------------------------------------\n") cat("The distribution of attribute patterns:\n") print(output2) }, export = FALSE, S3class = "labeling", modifiers = "public")
Soap.model2 <- lm(I(weight^(1/3)) ~ day, data = Soap) msummary(Soap.model2)
data_dir <- file.path("..", "testdata") tempfile_nc <- function() { tempfile_helper("selpoint_") } tempfile_csv <- function() { tempfile_helper_csv("selpoint_") } file_in <- file.path(data_dir, "ex_normal1.nc") file_out <- tempfile_nc() selpoint("SIS", file_in, file_out, 6.2, 46.7) file <- nc_open(file_out) test_that("data is correct", { actual <- ncvar_get(file) expected_data <- c(250) expected <- array(expected_data) 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::selpoint 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(6.0)) actual <- ncvar_get(file, "lat") expect_identical(actual, array(46.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() selpoint("SIS", file_in, file_out, 6.2, 46.7, nc34 = 4) file <- nc_open(file_out) test_that("data is correct in version 4", { actual <- ncvar_get(file) expected_data <- c(250) expected <- array(expected_data) 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(6.0)) actual <- ncvar_get(file, "lat") expect_identical(actual, array(46.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( selpoint("SIS", file_in, file_out, 6.2, 46.7, 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( selpoint("SIS", file_in, file_out, 6.2, 46.7, 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( selpoint("lat", file_in, file_out, 6.2, 46.7), "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) expected_data <- c(250) expected <- array(expected_data) 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(6.0)) actual <- ncvar_get(file, "lat") expect_identical(actual, array(46.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( selpoint(NULL, file_in, file_out, 6.2, 46.7), "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( selpoint("", file_in, file_out, 6.2, 46.7), "Variable '' not found. Variable 'SIS' will be used instead." ) }) file <- nc_open(file_out) test_that("data is correct", { actual <- ncvar_get(file) expected_data <- c(250) expected <- array(expected_data) 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(6.0)) actual <- ncvar_get(file, "lat") expect_identical(actual, array(46.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( selpoint("SIS", file_in, file_out, 6.2, 46.7), "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( selpoint("SIS", file_in, file_out, 6.2, 46.7), "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( selpoint("SIS", file_in, file_out, 6.2, 46.7), 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( selpoint("SIS", file_in, file_out, 6.2, 46.7, overwrite = TRUE), NA) }) file <- nc_open(file_out) test_that("data is correct", { actual <- ncvar_get(file) expected_data <- c(250) expected <- array(expected_data) 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(6.0)) actual <- ncvar_get(file, "lat") expect_identical(actual, array(46.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() selpoint("SIS", file_in, file_out, 6.2, 46.7) file <- nc_open(file_out) test_that("data is correct", { actual <- ncvar_get(file) expected_data <- c(250, 253) expected <- array(expected_data) 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(6.0)) actual <- ncvar_get(file, "lat") expect_identical(actual, array(46.5)) actual <- ncvar_get(file, "time") expect_equal(actual, array(c(149016, 158544))) }) nc_close(file) file_in <- file.path(data_dir, "ex_additional_attr.nc") file_out <- tempfile_nc() selpoint("SIS", file_in, file_out, 6.2, 46.7) file <- nc_open(file_out) test_that("data is correct", { actual <- ncvar_get(file) expected_data <- c(250) expected <- array(expected_data) 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(6.0)) actual <- ncvar_get(file, "lat") expect_identical(actual, array(46.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() selpoint("SIS", file_in, file_out, 6.2, 46.7) file <- nc_open(file_out) test_that("data is correct", { actual <- ncvar_get(file) expected_data <- c(250) expected <- array(expected_data) 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(6.0)) actual <- ncvar_get(file, "lat") expect_identical(actual, array(46.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() selpoint("SIS", file_in, file_out, 6.2, 46.7) file <- nc_open(file_out) test_that("data is correct", { actual <- ncvar_get(file) expected_data <- c(250) expected <- array(expected_data) 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(6.0)) actual <- ncvar_get(file, "lat") expect_identical(actual, array(46.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("ncdf version NULL throws an error", { expect_error( selpoint("SIS", file_in, file_out, 45, 46.7), "Coordinates outside of the domain.") }) file_in <- file.path(data_dir, "ex_normal1.nc") file_out <- tempfile_nc() test_that("ncdf version NULL throws an error", { expect_error( selpoint("SIS", file_in, file_out, 6.2, 7), "Coordinates outside of the domain.") }) file_in <- file.path(data_dir, "ex_normal1.nc") file_out <- tempfile_nc() test_that("ncdf version NULL throws an error", { expect_error( selpoint("SIS", file_in, file_out, 45, 6), "Coordinates outside of the domain.") }) file_in <- file.path(data_dir, "ex_normal1.nc") file_out <- tempfile_nc() test_that("format NULL throws an error", { expect_error( selpoint("SIS", file_in, file_out, 6.2, 46.7, format = NULL), "format must not be NULL" ) }) file_in <- file.path(data_dir, "ex_normal1.nc") file_out <- tempfile_nc() test_that("format NULL throws an error", { expect_error( selpoint("SIS", file_in, file_out, 6.2, 46.7, format = "pdf"), "format must be either nc or csv, but was pdf" ) }) file_in <- file.path(data_dir, "ex_normal1.nc") file_out <- tempfile_csv() selpoint("SIS", file_in, file_out, 6.2, 46.7, format = "csv") test_that("data is correct", { actual <- read.csv2(file_out, dec = ".") expected_data <- data.frame("2000-01-01", 250) expected <- expected_data expect_equivalent(actual, expected) })
summary.ergm <- function (object, ..., correlation=FALSE, covariance=FALSE, total.variation=TRUE) { myver <- packageVersion("ergm") objver <- NVL(object$ergm_version, as.package_version("3.9.4")) nextver <- as.package_version(paste(objver$major, objver$minor+1, sep=".")) if(objver < paste(myver$major, myver$minor, sep=".")){ warn(paste0("This object was fit with ", sQuote("ergm"), " version ", objver, " or earlier. Summarizing it with version ", nextver, " or later may return incorrect results or fail.")) } if("digits" %in% names(list(...))) warn("summary.ergm() no lnger takes a digits= argument.") control <- object$control pseudolikelihood <- object$estimate=="MPLE" independence <- NVL(object$MPLE_is_MLE, is.dyad.independent(object)) coef <- coef(object) ans <- list(formula=object$formula, call=object$call, correlation=correlation, offset = object$offset, drop = NVL(object$drop, rep(0,length(object$offset))), estimable = NVL(object$estimable, rep(TRUE,length(object$offset))), covariance=covariance, pseudolikelihood=pseudolikelihood, independence=independence, estimate=object$estimate, estimate.desc=object$estimate.desc, control=object$control) asycov <- vcov(object, sources=if(total.variation) "all" else "model") asyse <- sqrt(diag(asycov)) est.se <- sqrt(diag(vcov(object, sources="estimation"))) mod.se <- sqrt(diag(vcov(object, sources="model"))) tot.se <- sqrt(diag(vcov(object, sources="all"))) est.pct <- rep(NA,length(est.se)) if(any(!is.na(est.se))){ est.pct[!is.na(est.se)] <- ifelse(est.se[!is.na(est.se)]>0, round(100*(tot.se[!is.na(est.se)]-mod.se[!is.na(est.se)])/tot.se[!is.na(est.se)]), 0) } zval <- coef / asyse pval <- 2 * pnorm(q=abs(zval), lower.tail=FALSE) count <- 1 coefmat <- cbind( `Estimate` = coef, `Std. Error` = asyse, `MCMC %` = est.pct, `z value` = zval, `Pr(>|z|)` = pval) rownames(coefmat) <- param_names(object) devtext <- "Deviance:" if (object$estimate!="MPLE" || !independence || object$reference != as.formula(~Bernoulli)) { if (pseudolikelihood) { devtext <- "Pseudo-deviance:" ans$message <- "\nWarning: The standard errors are based on naive pseudolikelihood and are suspect.\n" } else if(object$estimate == "MLE" && any(is.na(est.se) & !ans$offset & !ans$drop==0 & !ans$estimable) && (!independence || control$force.main) ) { ans$message <- "\nWarning: The standard errors are suspect due to possible poor convergence.\n" } } else { ans$message <- "\nFor this model, the pseudolikelihood is the same as the likelihood.\n" } mle.lik<-try(logLik(object,...), silent=TRUE) if(inherits(mle.lik,"try-error")) ans$objname<-deparse(substitute(object)) else if(!is.na(mle.lik)){ null.lik<-try(logLikNull(object,...), silent=TRUE) ans$null.lik.0 <- is.na(null.lik) df <- length(coef) dyads<- sum(as.rlebdm(object$constrained, object$constrained.obs, which="informative")) rdf <- dyads - df ans$devtable <- matrix(c(if(is.na(null.lik)) 0 else -2*null.lik, -2*mle.lik, c(dyads, rdf)), 2,2, dimnames=list(c("Null","Residual"), c("Resid. Dev", "Resid. Df"))) ans$devtext <- devtext ans$aic <- AIC(object) ans$bic <- BIC(object) ans$mle.lik <- ERRVL(mle.lik, NA) ans$null.lik <- ERRVL(null.lik, NA) }else ans$devtable <- NA ans$coefs <- as.data.frame(coefmat)[,-3] ans$coefficients <- coefmat ans$asycov <- asycov ans$asyse <- asyse class(ans) <- "summary.ergm" ans }
macrocaic <- function(formula, data, phy, names.col, macroMethod = "RRD", stand.contr = TRUE, robust=Inf, ref.var=NULL, node.depth=NULL, macroMinSize=3, equal.branch.length=FALSE) { if(! missing(data)){ if(! inherits(data, 'comparative.data')){ if(missing(names.col)) stop('names column is missing') names.col <- deparse(substitute(names.col)) data <- caicStyleArgs(data=data, phy=phy, names.col=names.col, warn.dropped=TRUE) } } cdata <- data phy <- data$phy data <- data$data if(! is.null(node.depth)){ if(node.depth%%1 != 0 || node.depth < 1) stop("node.depth must be a positive integer greater than 1.") } if(as.logical(equal.branch.length)) { phy$edge.length <- rep(2, nrow(phy$edge)) } else { if(is.null(phy$edge.length)) stop("The phylogeny does not contain branch lengths and macrocaic has not been set to use equal branch lengths.") if(any(phy$edge.length < 0)) stop("The phylogeny contains negative branch lengths and macrocaic has not been set to use equal branch lengths.") } root <- length(phy$tip.label) + 1 unionData <- nrow(data) crunch.brlen <- 0 resp.type <- match.arg(macroMethod, c("RRD", "PDI")) formula <- update(formula, . ~ . - 1) if(is.empty.model(formula)) stop("Macrocaic requires an explanatory variable to determine the direction of species richness contrasts.\nModels of the form nSpp ~ 1 are not meaningful.") initMf <- model.frame(formula, data, na.action="na.pass") initMfComplete <- complete.cases(initMf) if(sum(initMfComplete) < 2 ) stop("Fewer than two taxa contain complete data for this analysis") macroMf <- as.matrix(model.response(initMf)) colnames(macroMf) <- with(attributes(attr(initMf, "terms")), rownames(factors)[response]) if(any(is.na(macroMf))) stop("MacroCAIC analyses cannot have missing species richness values") if(any(macroMf <= 0)) stop("Species richness values cannot be negative or zero") if(any((macroMf %% 1) > 0)) stop("Non-integer species richness values present") mf <- model.frame(formula, data, na.action=na.pass) varClass <- attributes(attributes(mf)$terms)$dataClasses termFactors <- attributes(attributes(mf)$terms)$factors factorCols <- names(varClass)[varClass %in% c("ordered","factor")] if(any(varClass %in% c("ordered","factor") & rowSums(termFactors) > 1)){ stop("Interactions using categorical variables not supported in macrocaic analyses")} termClass <- apply(termFactors,2,function(X) unique(varClass[as.logical(X)])) for(fact in factorCols){ currFact <- with(mf, get(fact)) lev <- levels(currFact) ord <- is.ordered(currFact) if(length(lev) > 2 & ! ord) stop("Unordered non-binary factor included in model formula.") eval(parse(text=paste("mf$'", fact, "'<- as.numeric(currFact)", sep=""))) attr(mf, "dataClasses") <- rep("numeric", dim(termFactors)[2]) } mr <- model.response(mf) mr <- as.matrix(mr) colnames(mr) <- as.character(formula[2]) md <- model.matrix(formula, mf) if(! is.null(ref.var)){ ref.var <- deparse(substitute(ref.var)) if(is.na(match(ref.var, colnames(md)))) stop("Reference variable not found in the model predictors") } else { ref.var <- colnames(md)[1] } attrMD <- attributes(md) md <- cbind(mr, md) contr <- contrCalc(md, phy, ref.var, picMethod="crunch", crunch.brlen, macro=macroMethod) mrC <- contr$contr[,1,drop=FALSE] mdC <- contr$contr[,-1,drop=FALSE] if(stand.contr){ notCateg <- ! termClass %in% c("factor","ordered") mdC[,notCateg] <- mdC[,notCateg, drop=FALSE]/sqrt(contr$var.contr) } ContrObj <- list() ContrObj$contr$response <- mrC ContrObj$contr$explanatory <- mdC ContrObj$nodalVals$response <- contr$nodVal[,1,drop=FALSE] ContrObj$nodalVals$explanatory <- contr$nodVal[,-1,drop=FALSE] ContrObj$contrVar <- contr$var.contr ContrObj$nChild <- contr$nChild attr(ContrObj, 'assign') <- attrMD$assign if(! is.null(attrMD$contrasts)) attr(ContrObj, 'contrasts') <- attrMD$contrasts validNodes <- with(ContrObj$contr, complete.cases(explanatory) & complete.cases(response)) validNodes[which(ContrObj$nodalVal$response < macroMinSize)] <- FALSE if(! is.null(node.depth)){ validNodes[ContrObj$nodeDepth > node.depth] <- FALSE } ContrObj$validNodes <- validNodes contrMD <- ContrObj$contr$explanatory[validNodes,,drop=FALSE] contrRS <- ContrObj$contr$response[validNodes,,drop=FALSE] attr(contrMD, 'assign') <- attr(ContrObj, 'assign') if(! is.null(attr(ContrObj, 'contrasts'))) attr(contrMD, 'contrasts') <- attr(ContrObj, 'contrasts') mod <- with(ContrObj$contr, lm.fit(contrMD, contrRS)) class(mod) <- "lm" RET <- list(contrast.data=ContrObj, data=cdata, mod=mod) class(RET) <- c("caic") contrData <- with(ContrObj$contr, as.data.frame(cbind(response,explanatory))) contrData <- contrData[validNodes, ,drop=FALSE] RET$mod$call <- substitute(lm(FORM, data=contrData), list(FORM=formula)) RET$mod$terms <- attr(mf, "terms") RET$mod$model <- contrData attr(RET$mod$model, "terms") <- attr(mf, "terms") stRes <- rstudent(mod) SRallNodes <- rep(NA, length(RET$contrast.data$validNodes)) names(SRallNodes) <- names(RET$contrast.data$contrVar) SRallNodes[match(names(stRes), names(SRallNodes))] <- stRes RET$contrast.data$studentResid <- SRallNodes attr(RET, "contr.method") <- "crunch" attr(RET, "macro.method") <- macroMethod attr(RET, "stand.contr") <- stand.contr attr(RET, "robust") <- robust if(any(stRes > robust)){ RET <- caic.robust(RET, robust) } return(RET) }
cloudml_train <- function(file = "train.R", master_type = NULL, flags = NULL, region = NULL, config = NULL, collect = "ask", dry_run = FALSE) { if (dry_run) message("Dry running training job for CloudML...") else message("Submitting training job to CloudML...") gcloud <- gcloud_config() cloudml <- cloudml_config(config) if (!is.null(master_type)) cloudml$trainingInput$masterType <- master_type if (!is.null(cloudml$trainingInput$masterType) && !identical(cloudml$trainingInput$scaleTier, "CUSTOM")) cloudml$trainingInput$scaleTier <- "CUSTOM" if (length(cloudml) == 0L) cloudml$trainingInput <- list(scaleTier = "BASIC") custom_commands <- cloudml[["customCommands"]] cloudml[["customCommands"]] <- NULL application <- getwd() entrypoint <- file entrypoint <- gsub(paste0("^", getwd(), .Platform$file.sep), "", entrypoint) id <- unique_job_name("cloudml") deployment <- scope_deployment( id = id, application = application, context = "cloudml", overlay = flags, entrypoint = entrypoint, cloudml = cloudml, gcloud = gcloud, dry_run = dry_run ) cloudml_file <- deployment$cloudml_file storage <- gs_ensure_storage(gcloud) if (is.null(region)) region <- gcloud_default_region() job_yml <- file.path(deployment$directory, "job.yml") yaml::write_yaml(list( storage = storage, custom_commands = custom_commands ), job_yml) directory <- deployment$directory scope_setup_py(directory) setwd(dirname(directory)) cloudml_version <- cloudml$trainingInput$runtimeVersion %||% "1.9" if (utils::compareVersion(cloudml_version, "1.4") < 0) stop("CloudML version ", cloudml_version, " is unsupported, use 1.4 or newer.") arguments <- (MLArgumentsBuilder(gcloud) ("jobs") ("submit") ("training") (id) ("--job-dir=%s", file.path(storage, "staging")) ("--package-path=%s", basename(directory)) ("--module-name=%s.cloudml.deploy", basename(directory)) ("--runtime-version=%s", cloudml_version) ("--region=%s", region) ("--config=%s/%s", "cloudml-model", cloudml_file) ("--") ("Rscript")) gcloud_exec(args = arguments(), echo = FALSE, dry_run = dry_run) arguments <- (MLArgumentsBuilder(gcloud) ("jobs") ("describe") (id)) output <- gcloud_exec(args = arguments(), echo = FALSE, dry_run = dry_run) stdout <- output$stdout stderr <- output$stderr template <- c( "Job '%1$s' successfully submitted.", "%2$s", "Check job status with: job_status(\"%1$s\")", "", "Collect job output with: job_collect(\"%1$s\")", "", "After collect, view with: view_run(\"runs/%1$s\")", "" ) rendered <- sprintf(paste(template, collapse = "\n"), id, stderr) message(rendered) description <- yaml::yaml.load(stdout) job <- cloudml_job("train", id, description) register_job(job) if (dry_run) collect <- FALSE if (identical(collect, "ask")) { if (interactive()) { if (have_rstudio_terminal()) response <- readline("Monitor and collect job in RStudio Terminal? [Y/n]: ") else response <- readline("Wait and collect job when completed? [Y/n]: ") collect <- !nzchar(response) || (tolower(response) == 'y') } else { collect <- FALSE } } destination <- file.path(application, "runs") if (collect) { if (have_rstudio_terminal()) { job_collect_async( job, gcloud, destination = destination, view = identical(rstudioapi::versionInfo()$mode, "desktop") ) } else { job_collect( job, destination = destination, view = interactive() ) } } invisible(job) } job_cancel <- function(job = "latest") { gcloud <- gcloud_config() job <- as.cloudml_job(job) arguments <- (MLArgumentsBuilder(gcloud) ("jobs") ("cancel") (job)) gcloud_exec(args = arguments(), echo = FALSE) } job_list <- function(filter = NULL, limit = NULL, page_size = NULL, sort_by = NULL, uri = FALSE) { gcloud <- gcloud_config() arguments <- ( MLArgumentsBuilder(gcloud) ("jobs") ("list") ("--filter=%s", filter) ("--limit=%i", as.integer(limit)) ("--page-size=%i", as.integer(page_size)) ("--sort-by=%s", sort_by) (if (uri) "--uri")) output <- gcloud_exec(args = arguments(), echo = FALSE) if (!uri) { output_tmp <- tempfile() writeLines(output$stdout, output_tmp) jobs <- utils::read.table(output_tmp, header = TRUE, stringsAsFactors = FALSE) jobs$CREATED <- as.POSIXct(jobs$CREATED, format = "%Y-%m-%dT%H:%M:%S", tz = "GMT") output <- jobs } output } job_stream_logs <- function(job = "latest", polling_interval = getOption("cloudml.stream_logs.polling", 5), task_name = NULL, allow_multiline_logs = FALSE) { gcloud <- gcloud_config() job <- as.cloudml_job(job) arguments <- ( MLArgumentsBuilder(gcloud) ("jobs") ("stream-logs") (job$id) ("--polling-interval=%i", as.integer(polling_interval)) ("--task-name=%s", task_name)) if (allow_multiline_logs) arguments("--allow-multiline-logs") gcloud_exec(args = arguments(), echo = TRUE) invisible(NULL) } job_status <- function(job = "latest") { gcloud <- gcloud_config() job <- as.cloudml_job(job) arguments <- (MLArgumentsBuilder(gcloud) ("jobs") ("describe") (job)) output <- gcloud_exec(args = arguments(), echo = FALSE) status <- yaml::yaml.load(paste(output$stdout, collapse = "\n")) class(status) <- "cloudml_job_status" attr(status, "messages") <- output$stderr status } print.cloudml_job_status <- function(x, ...) { x$trainingInput$args <- NULL x$trainingInput$packageUris <- NULL x$trainingInput$pythonModule <- NULL str(x, give.attr = FALSE, no.list = TRUE) trials_data <- job_trials(x) if (!is.null(trials_data)) { cat("\n") cat("Hyperparameter Trials:\n") print(trials_data) } cat(attr(x, "messages"), "\n") } job_trials <- function(x) { UseMethod("job_trials") } job_trials_from_status <- function(status) { if (is.null(status$trainingOutput) || is.null(status$trainingOutput$trials)) return(NULL) df <- do.call("rbind", lapply(status$trainingOutput$trials, as.data.frame, stringsAsFactors = FALSE)) for(col in colnames(df)) { is_numeric <- suppressWarnings( !any(is.na( as.numeric(df[[col]]))) ) if (is_numeric) { df[[col]] <- as.numeric(df[[col]]) } } df } job_trials.default <- function(x = NULL) { if (is.null(x)) job_trials("latest") else stop("no applicable method for 'job_trials' to an object of class ", class(x)[[1]]) } job_trials.character <- function(x) { status <- job_status(x) job_trials_from_status(status) } job_trials.cloudml_job <- function(x) { job_trials_from_status(x$description) } job_trials.cloudml_job_status <- function(x) { job_trials_from_status(x) } job_validate_trials <- function(trials) { if (!is.null(trials)) { if (!is.numeric(trials) && !trials %in% c("best", "all")) stop("The 'trials' parameter must be numeric, 'best' or 'all'.") } } job_collect <- function(job = "latest", trials = "best", destination = "runs", timeout = NULL, view = interactive()) { gcloud <- gcloud_config() job <- as.cloudml_job(job) id <- job$id job_validate_trials(trials) write_status <- function(status, time) { fmt <- ">>> [state: %s; last updated %s]" msg <- sprintf(fmt, status$state, time) whitespace <- "" width <- getOption("width") if (nchar(msg) < width) whitespace <- paste(rep("", width - nchar(msg)), collapse = " ") output <- paste0("\r", msg, whitespace) cat(output, sep = "") } status <- job_status(job) time <- Sys.time() if (status$state %in% c("SUCCEEDED", "FAILED")) { return(job_download_multiple( job, trial = trials, destination = destination, view = view, status = status) ) } fmt <- ">>> Job '%s' is currently running -- please wait...\n" printf(fmt, id) write_status(status, time) start_time <- Sys.time() repeat { status <- job_status(job) time <- Sys.time() write_status(status, time) if (status$state %in% c("SUCCEEDED", "FAILED")) { printf("\n") return(job_download_multiple(job, trial = trials, destination = destination, view = view, gcloud = gcloud, status = status)) } Sys.sleep(30) if (!is.null(timeout) && time - start_time > timeout * 60) stop("Giving up after ", timeout, " minutes with job in status ", status$state) } stop("failed to receive job outputs") } job_collect_async <- function( job, gcloud = NULL, destination = "runs", polling_interval = getOption("cloudml.stream_logs.polling", 5), view = interactive() ) { if (!have_rstudio_terminal()) stop("job_collect_async requires a version of RStudio with terminals (>= v1.1)") gcloud <- gcloud_config() job <- as.cloudml_job(job) id <- job$id log_arguments <- (MLArgumentsBuilder(gcloud) ("jobs") ("stream-logs") (id) ("--polling-interval=%i", as.integer(polling_interval))) gcloud_quoted <- gcloud_binary() if (.Platform$OS.type == "windows") gcloud_quoted <- shQuote(gcloud_quoted) terminal_steps <- c( paste(gcloud_quoted, paste(log_arguments(), collapse = " ")) ) destination <- normalizePath(destination, mustWork = FALSE) if (!job_is_tuning(job)) { terminal_steps <- c(terminal_steps, collect_job_step(destination, job$id)) if (view) terminal_steps <- c(terminal_steps, view_job_step(destination, job$id)) } else { terminal_steps <- c( terminal_steps, paste("echo \"\""), paste( "echo \"To collect this job, run from R: job_collect('", job$id, "')\"", sep = "" ) ) } gcloud_terminal(terminal_steps, clear = TRUE) } job_download <- function(job, trial = "best", destination = "runs", view = interactive(), gcloud) { status <- job_status(job) trial_paths <- job_status_trial_dir(status, destination, trial, job) source <- trial_paths$source destination <- trial_paths$destination if (!is_gs_uri(source)) { fmt <- "job directory '%s' is not a Google Storage URI" stopf(fmt, source) } message(sprintf("Downloading job from %s...", source)) result <- gsutil_exec("ls", source) if (result$status != 0) { fmt <- "no directory at path '%s'" stopf(fmt, source) } ensure_directory(destination) gs_copy(source, destination, TRUE, echo = TRUE) run_dir <- destination as_date <- function(x) { tryCatch(as.double(as.POSIXct(x, tz = "GMT", format = "%Y-%m-%dT%H:%M:%SZ")), error = function(e) NULL) } properties <- list() properties$cloudml_job <- status$jobId properties$cloudml_state <- status$state properties$cloudml_error <- status$errorMessage properties$cloudml_created <- as_date(status$createTime) properties$cloudml_start <- as_date(status$startTime) properties$cloudml_end <- as_date(status$endTime) properties$cloudml_ml_units <- status$trainingOutput$consumedMLUnits properties$cloudml_master_type <- status$trainingInput$masterType messages <- trimws(strsplit(attr(status, "messages"), "\n")[[1]]) messages <- messages[grepl("^https://.*$", messages)] for (message in messages) { if (startsWith(message, "https://console.cloud.google.com/ml/jobs/")) properties$cloudml_console_url <- message else if (startsWith(message, "https://console.cloud.google.com/logs")) properties$cloudml_log_url <- message } tfruns::write_run_metadata("properties", properties, run_dir) if (isTRUE(view) && trial != "all") tfruns::view_run(run_dir) else if (view == "save") tfruns::save_run_view(run_dir, file.path(run_dir, "tfruns.d", "view.html")) invisible(status) } job_list_trials <- function(status) { as.numeric(sapply(status$trainingOutput$trials, function(e) e$trialId)) } job_download_multiple <- function(job, trial, destination, view, gcloud, status) { if (length(trial) <= 1 && trial != "all") job_download(job, trial, destination, view, gcloud) else { if (identical(trial, "all")) trial <- job_list_trials(status) lapply(trial, function(t) { job_download(job, t, destination, FALSE, gcloud) }) } } job_output_dir <- function(job) { job <- as.cloudml_job(job) storage <- dirname(job$description$trainingInput$jobDir) output_path <- file.path(storage, "runs", job$id) if (job_is_tuning(job) && !is.null(job$trainingOutput$finalMetric)) { output_path <- file.path(output_path, job$trainingOutput$finalMetric$trainingStep) } output_path } job_status_trial_dir <- function(status, destination, trial, job) { storage <- dirname(status$trainingInput$jobDir) output_path <- list( source = file.path(storage, "runs", status$jobId, "*", fsep = "/"), destination = file.path(destination, status$jobId) ) if (!is.null(trial) && job_is_tuning(job)) { trial_digits_format <- paste0("%0", nchar(max(job_list_trials(status))), "d") trial_parent <- file.path(storage, "runs", status$jobId) if (trial == "best") { if (job_status_is_tuning(status) && !is.null(status$trainingInput$hyperparameters$goal)) { if (length(status$trainingOutput$trials) == 0) { stop("Job contains no output trials.") } if (is.null(status$trainingOutput$trials[[1]]$finalMetric)) { stop( "Job is missing final metrics to retrieve best trial, ", "consider using 'all' or an specific trial instead." ) } decreasing <- if (status$trainingInput$hyperparameters$goal == "MINIMIZE") FALSE else TRUE ordered <- order(sapply(status$trainingOutput$trials, function(e) e$finalMetric$objectiveValue), decreasing = decreasing) if (length(ordered) > 0) { best_trial <- as.numeric(status$trainingOutput$trials[[ordered[[1]]]]$trialId) output_path <- list( source = file.path(trial_parent, best_trial, "*"), destination = file.path( destination, paste( status$jobId, sprintf(trial_digits_format, best_trial), sep = "-" ) ) ) } } } else if (is.numeric(trial)) { output_path <- list( source = file.path(trial_parent, trial, "*"), destination = file.path( destination, paste( status$jobId, sprintf(trial_digits_format, trial), sep = "-" ) ) ) } } output_path } job_is_tuning <- function(job) { !is.null(job$description$trainingInput$hyperparameters) } job_status_is_tuning <- function(status) { identical(status$trainingOutput$isHyperparameterTuningJob, TRUE) } collect_job_step <- function(destination, jobId) { r_job_step(paste0( "cloudml::job_collect('", jobId, "', destination = '", normalizePath(destination, winslash = "/", mustWork = FALSE), "', view = 'save')" )) } view_job_step <- function(destination, jobId) { r_job_step(paste0( "utils::browseURL('", file.path(normalizePath(destination, winslash = "/", mustWork = FALSE), jobId, "tfruns.d", "view.html"), "')" )) } r_job_step <- function(command) { paste( paste0("\"", file.path(R.home("bin"), "Rscript"), "\""), "-e", paste0("\"", command ,"\"") ) }
geom_point_s <- function(mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., nudge_x = 0, nudge_y = 0, arrow = NULL, add.segments = TRUE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) { if (!missing(nudge_x) || !missing(nudge_y)) { if (!missing(position)) { rlang::abort("You must specify either `position` or `nudge_x`/`nudge_y`.") } position <- position_nudge_center(nudge_x, nudge_y, kept.origin = ifelse(add.segments, "original", "none")) } layer( data = data, mapping = mapping, stat = stat, geom = GeomPointS, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( add.segments = add.segments, arrow = arrow, na.rm = na.rm, ... ) ) } GeomPointS <- ggplot2::ggproto("GeomPointS", Geom, required_aes = c("x", "y"), non_missing_aes = c("size", "shape", "colour"), default_aes = ggplot2::aes( shape = 19, colour = "black", size = 1.5, fill = NA, alpha = NA, stroke = 0.5, segment.linetype = 1, segment.colour = "grey33", segment.size = 0.5, segment.alpha = 1 ), draw_panel = function(data, panel_params, coord, na.rm = FALSE, arrow = NULL, add.segments = FALSE) { if (is.character(data$shape)) { data$shape <- ggplot2::translate_shape_string(data$shape) } if (nrow(data) == 0L) { return(nullGrob()) } add.segments <- add.segments && all(c("x_orig", "y_orig") %in% colnames(data)) coords <- coord$transform(data, panel_params) if (add.segments) { data_orig <- data.frame(x = data$x_orig, y = data$y_orig) data_orig <- coord$transform(data_orig, panel_params) } if(add.segments) { ggname("geom_point_s", grid::grobTree( grid::segmentsGrob( x0 = data_orig$x, y0 = data_orig$y, x1 = coords$x, y1 = coords$y, arrow = arrow, gp = grid::gpar(col = ggplot2::alpha(coords$segment.colour, coords$segment.alpha)) ), grid::pointsGrob( coords$x, coords$y, pch = coords$shape, gp = gpar( col = alpha(coords$colour, coords$alpha), fill = alpha(coords$fill, coords$alpha), fontsize = coords$size * .pt + coords$stroke * .stroke / 2, lwd = coords$stroke * .stroke / 2 ) ) ) ) } else { ggname("geom_point_s", grid::pointsGrob( coords$x, coords$y, pch = coords$shape, gp = gpar( col = alpha(coords$colour, coords$alpha), fill = alpha(coords$fill, coords$alpha), fontsize = coords$size * .pt + coords$stroke * .stroke / 2, lwd = coords$stroke * .stroke / 2 ) ) ) } }, draw_key = ggplot2::draw_key_point ) translate_shape_string <- function(shape_string) { if (nchar(shape_string[1]) <= 1) { return(shape_string) } pch_table <- c( "square open" = 0, "circle open" = 1, "triangle open" = 2, "plus" = 3, "cross" = 4, "diamond open" = 5, "triangle down open" = 6, "square cross" = 7, "asterisk" = 8, "diamond plus" = 9, "circle plus" = 10, "star" = 11, "square plus" = 12, "circle cross" = 13, "square triangle" = 14, "triangle square" = 14, "square" = 15, "circle small" = 16, "triangle" = 17, "diamond" = 18, "circle" = 19, "bullet" = 20, "circle filled" = 21, "square filled" = 22, "diamond filled" = 23, "triangle filled" = 24, "triangle down filled" = 25 ) shape_match <- charmatch(shape_string, names(pch_table)) invalid_strings <- is.na(shape_match) nonunique_strings <- shape_match == 0 if (any(invalid_strings)) { bad_string <- unique(shape_string[invalid_strings]) n_bad <- length(bad_string) collapsed_names <- sprintf("\n* '%s'", bad_string[1:min(5, n_bad)]) more_problems <- if (n_bad > 5) { sprintf("\n* ... and %d more problem%s", n_bad - 5, ifelse(n_bad > 6, "s", "")) } else { "" } stop(paste("Can't find shape name:", collapsed_names, more_problems)) } if (any(nonunique_strings)) { bad_string <- unique(shape_string[nonunique_strings]) n_bad <- length(bad_string) n_matches <- vapply( bad_string[1:min(5, n_bad)], function(shape_string) sum(grepl(paste0("^", shape_string), names(pch_table))), integer(1) ) collapsed_names <- sprintf( "\n* '%s' partially matches %d shape names", bad_string[1:min(5, n_bad)], n_matches ) more_problems <- if (n_bad > 5) { sprintf("\n* ... and %d more problem%s", n_bad - 5, ifelse(n_bad > 6, "s", "")) } else { "" } stop(paste("Shape names must be unambiguous:", collapsed_names, more_problems)) } unname(pch_table[shape_match]) }
pair_extremes <- function(data, col = NULL, unequal_method = "middle", num_pairings = 1, balance = "mean", order_by_aggregates = FALSE, shuffle_members = FALSE, shuffle_pairs = FALSE, factor_name = ifelse(num_pairings == 1, ".pair", ".pairing"), overwrite = FALSE) { extreme_pairing_rearranger_( data = data, col = col, unequal_method = unequal_method, num_pairings = num_pairings, balance = balance, order_by_aggregates = order_by_aggregates, shuffle_members = shuffle_members, shuffle_pairs = shuffle_pairs, factor_name = factor_name, overwrite = overwrite ) } pair_extremes_vec <- function(data, unequal_method = "middle", num_pairings = 1, balance = "mean", order_by_aggregates = FALSE, shuffle_members = FALSE, shuffle_pairs = FALSE){ checkmate::assert(checkmate::check_vector(data, strict = TRUE), checkmate::check_factor(data)) pair_extremes( data = data, unequal_method = unequal_method, num_pairings = num_pairings, balance = balance, order_by_aggregates = order_by_aggregates, shuffle_members = shuffle_members, shuffle_pairs = shuffle_pairs, factor_name = NULL, overwrite = TRUE ) }
calc.outbreakP.statistic <- function(x) { n <- length(x) x <- c(0,x) leftl <- numeric(n+1) y <- numeric(n+1) yhat <- numeric(n+1) sumwy <- numeric(n+1) sumwys <- numeric(n+1) sumw <- numeric(n+1) w <- numeric(n+1) meanl <- numeric(n+1) xbar <- 0 meanl[1] = -Inf leftl[1] = 0 for (i in 1:n) { yhat[i+1] <- x[i+1] sumwy[i+1] <- x[i+1] sumw[i+1] <- 1 meanl[i+1] <- x[i+1] leftl[i+1] <- i xbar=xbar+(x[i+1]-xbar)/i while (meanl[i+1] <= meanl[ (leftl[i+1] - 1) + 1]) { sumwy[i+1] = sumwy[i+1] + sumwy[(leftl[i+1] - 1)+1] sumw[i+1] = sumw[i+1] + sumw[(leftl[i+1] - 1)+1] meanl[i+1] = sumwy[i+1] / sumw[i+1] leftl[i+1] = leftl[(leftl[i+1] - 1)+1] } for (j in leftl[i+1]:i) { yhat[j+1] = meanl[i+1] } } alarm.stat <- 1 for (j in seq_len(n)) { div <- ifelse(yhat[j+1]==0 & xbar==0, 1, yhat[j+1]/xbar) alarm.stat <- alarm.stat * (div)^x[j+1] } return(alarm.stat) } algo.outbreakP <- function(disProgObj, control = list(range = range, k=100, ret=c("cases","value"),maxUpperboundCases=1e5)) { if(is.null(control[["k",exact=TRUE]])) control$k <- 100 if(is.null(control[["maxUpperboundCases",exact=TRUE]])) control$maxUpperboundCases <- 1e5 control$ret <- match.arg(control$ret, c("value","cases")) alarm <- matrix(data = 0, nrow = length(control$range), ncol = 1) upperbound <- matrix(data = 0, nrow = length(control$range), ncol = 1) observed <- disProgObj$observed count <- 1 for(i in control$range) { statistic <- calc.outbreakP.statistic( observed[seq_len(i)] ) alarm[count] <- statistic > control$k if (control$ret == "cases") { if (i<=1) { upperbound[count] <- ifelse(control$k>=1, NA, 0) } else { if (is.nan(statistic)) { upperbound[count] <- NA } else { delta <- ifelse(alarm[count], -1, 1) observedi <- observed[i] foundNNBA <- FALSE while ( ((delta == -1 & observedi > 0) | (delta == 1 & observedi < control$maxUpperboundCases)) & (!foundNNBA)) { observedi <- observedi + delta newObserved <- c(observed[seq_len(i-1)],observedi) statistic <- calc.outbreakP.statistic( newObserved ) if (is.nan(statistic)) { observedi <- control$maxUpperboundCases } else { foundNNBA <- (statistic > control$k) == ifelse(alarm[count],FALSE,TRUE) } } upperbound[count] <- ifelse( foundNNBA, observedi + ifelse(alarm[count],1,0), NA) } } } else { upperbound[count] <- statistic } count <- count + 1 } control$name <- paste("outbreakP(",control$k,")",sep="") control$data <- paste(deparse(substitute(disProgObj))) result <- list(alarm = alarm, upperbound = upperbound, disProgObj=disProgObj, control=control) class(result) = "survRes" return(result) }
ci.sc <- function(means=NULL, s.anova=NULL, c.weights=NULL, n=NULL, N=NULL, Psi=NULL, ncp=NULL, conf.level=.95, alpha.lower=NULL, alpha.upper=NULL, df.error=NULL, ...) { if(!identical(sum(c.weights[c.weights>0]), 1)) stop("Please use fractions to specify the contrast weights") if(!identical(round(sum(c.weights), 5), 0)) stop("The sum of the contrast weights ('c.weights') should equal zero.") if(length(n)==1) { n <- rep(n, length(means)) } if(length(n)!=length(c.weights)) stop("The lengths of 'n' and 'c.weights' differ, which should not be the case.") part.of.se <- sqrt(sum((c.weights^2)/n)) if(!is.null(Psi)) { if(!is.null(means)) stop("Since the contrast effect ('Psi') was specified, you should not specify the vector of means ('means').") if(!is.null(ncp)) stop("Since the contrast effect ('Psi') was specified, you should not specify the noncentral parameter ('ncp').") if(is.null(s.anova)) stop("You must specify the standard deviation of the errors (i.e., the square root of the error variance).") if(is.null(n)) stop("You must specify the vector per group/level sample size ('n').") if(is.null(c.weights)) stop("You must specify the vector of contrast weights ('c.weights').") psi <- Psi/s.anova lambda <- psi/part.of.se } if(!is.null(ncp)) { if(!is.null(means)) stop("Since the noncentral parameter was specified directly, you should not specify the vector of means ('means').") if(!is.null(Psi)) stop("Since the noncentral parameter was specified directly, you should not specify the the contrast effect ('Psi').") if(is.null(s.anova)) stop("You must specify the standard deviation of the errors (i.e., the square root of the error variance).") if(is.null(n)) stop("You must specify the vector per group/level sample size ('n').") if(is.null(c.weights)) stop("You must specify the vector of contrast weights ('c.weights'.") lambda <- ncp } if(!is.null(means)) { Psi <- sum(c.weights*means) psi <- Psi/s.anova lambda <- psi/part.of.se } if(is.null(alpha.lower) & is.null(alpha.upper)) { alpha.lower <- (1-conf.level)/2 alpha.upper <- (1-conf.level)/2 } if(is.null(N)) stop("You must specify the total sample size ('N').") if(is.null(df.error)) df.2 <- N - length(means) if(!is.null(df.error)) df.2 <- df.error Lims <- conf.limits.nct(ncp=lambda, df=df.2, conf.level = NULL, alpha.lower = alpha.lower, alpha.upper = alpha.upper, sup.int.warns=TRUE, method = "all", ...) Result <- list(Lower.Conf.Limit.Standardized.Contrast = Lims$Lower.Limit*part.of.se, Standardized.contrast = psi, Upper.Conf.Limit.Standardized.Contrast = Lims$Upper.Limit*part.of.se) return(Result) }
doc <- ' Usage: install [ --install-program INSTALL ] [ --prefix PREFIX ] Options: --install-program INSTALL `install` program to use [Default: install] --prefix PREFIX Installation prefix [Default: /usr] ' ARGS <- docopt::docopt(doc, strip_names=TRUE) system(paste(ARGS$`install-program`, "minionqc", paste0(ARGS$prefix, "/bin/"), sep=" "))
expected <- FALSE test(id=0, code={ argv <- list(2L, TRUE, FALSE, FALSE) do.call('switch', argv); }, o = expected);
carto.pal <- function(pal1, n1, pal2 = NULL, n2 = NULL, middle = FALSE, transparency = FALSE){ alphainit <- 30 alpha <- "FF" middlecol <- " if(is.null(pal2) & is.null(n2)){ pal<-as.character(unlist(cartography.colors[[pal1]][n1])) if(transparency == TRUE){ for ( i in 1:n1-1) { alpha <- as.hexmode(floor(alphainit+(255-alphainit)/n1*i)) pal[i] <- paste(pal[i],alpha,sep="") } alpha <- as.hexmode(alphainit) } } if(!is.null(pal2) & !is.null(n2)){ n <- max(n1,n2) pal1 <- as.character(unlist(cartography.colors[[pal1]][n])) pal2 <- as.character(unlist(cartography.colors[[pal2]][n])) if(transparency==TRUE){ for ( i in 1:n-1) { alpha <- as.hexmode(floor(alphainit+(255-alphainit)/n*i)) pal1[i] <- paste(pal1[i],alpha,sep="") pal2[i] <- paste(pal2[i],alpha,sep="") } alpha <- as.hexmode(alphainit) } pal1 <- pal1[1:n1] pal1 <- rev(pal1) pal2 <- pal2[1:n2] pal <- c(pal1,pal2) if(middle){pal <- c(pal1,paste(middlecol,alpha,sep=""),pal2)} } return(pal) } carto.pal.info <- function(){ names(cartography.colors) } display.carto.pal<-function(name) { old.par <- par(no.readonly = TRUE) par(mfrow=c(5,4)) par(mar=c(0.2, 0.2, 1, 0.2), xaxs='i', yaxs='i') for ( i in 1:20) { mypal <- carto.pal(name,i) k<-length(mypal) image(1:k, 1, as.matrix(1:k), col = mypal, xlab = paste(k," classes",sep=""), ylab = "", xaxt = "n", yaxt = "n",bty = "n") if (i==1){cl <- "classe"}else{cl <- "classes"} title(paste(i,cl,sep=" ")) } par(old.par) } display.carto.all <- function(n = 10) { nbpal <- length(cartography.colors) ncol <- 2 nrow <- round(nbpal/ncol+0.1) old.par <- par(no.readonly = TRUE) par(mfrow=c(nrow,ncol)) par(mar=c(0.2, 0.2, 1, 0.2), xaxs='i', yaxs='i') for ( i in 1:nbpal) { pal <- names(cartography.colors)[i] mypal <- carto.pal(pal,n) k<-length(mypal) image(1:k, 1, as.matrix(1:k), col =mypal, xlab = paste(k," classes",sep=""), ylab = "", xaxt = "n", yaxt = "n",bty = "n") title(names(cartography.colors)[i]) } par(old.par) }
summary.trial.fi <- function(object,se=TRUE,N=TRUE,fittedmodel=NULL,...){ model <- object avgp <- function(model,pdot,...){return(pdot)} newdat <- model$data newdat <- newdat[newdat$distance <= model$meta.data$width & newdat$distance >= model$meta.data$left, ] n <- length(newdat$distance)/2 timesdetected <- newdat$detected[newdat$observer == 1] + newdat$detected[newdat$observer == 2] n1 <- length(newdat$distance[newdat$observer == 1 & newdat$detected == 1]) n2 <- length(newdat$distance[newdat$observer == 2 & newdat$detected == 1]) n3 <- sum(timesdetected == 2) newdat <- newdat[newdat$observer == 1 & newdat$detected == 1, ] newdat$distance <- rep(0,length(newdat$distance)) pred.at0 <- predict(model$mr,newdat,type="response") if(is.null(fittedmodel)){ Nhat <- model$Nhat pdot <- model$fitted }else{ pdot <- fittedmodel$fitted Nhat <- fittedmodel$Nhat } average.p0.1 <- sum(avgp(model,pred.at0)/pdot) ans <- list(n = n, n1 = n1, n2 = n2, n3 = n3, average.p0.1 = average.p0.1/Nhat, cond.det.coef = coef(model), aic = model$criterion) if(N){ ans$average.p <- n1/Nhat ans$Nhat <- Nhat } if(se){ if(N | is.null(fittedmodel)){ se.obj <- calc.se.Np(model, avgp, n, ans$average.p) ans$average.p.se <- se.obj$average.p.se ans$Nhat.se <- se.obj$Nhat.se cvN <- se.obj$Nhat.se/Nhat Nhatvar.list <- se.obj$Nhatvar.list vcov <- se.obj$vcov } if(!is.null(fittedmodel)){ Nhat <- fittedmodel$Nhat vcov <- solvecov(fittedmodel$hessian)$inv Nhatvar.list <- DeltaMethod(fittedmodel$par,NCovered,vcov,.001, model=fittedmodel,group=TRUE) Nhatvar <- Nhatvar.list$variance + sum((1-fittedmodel$fitted)/ fittedmodel$fitted^2) cvN <- sqrt(Nhatvar)/Nhat } if(is.null(fittedmodel)){ var.pbar.list <- prob.se(model,avgp,vcov,fittedmodel=NULL) }else{ var.pbar.list <- prob.se(model,avgp,vcov,fittedmodel=fittedmodel) } covar <- t(Nhatvar.list$partial) %*% vcov %*% var.pbar.list$partial + var.pbar.list$covar var.pbar <- ans$average.p0.1^2*(cvN^2 + var.pbar.list$var/average.p0.1^2 - 2*covar/(average.p0.1*Nhat)) ans$average.p0.1.se <- sqrt(var.pbar) } class(ans) <- "summary.trial.fi" ans$mono <- model$ds$aux$mono ans$mono.strict <- model$ds$aux$mono.strict return(ans) }
print.rwty.chain <- function(x, ...){ print(summary(x)) }
.get_dot_data <- function(dat, dots, verbose = TRUE) { if (!is.data.frame(dat) || length(dots) == 0) { return(dat) } columns <- colnames(dat) x <- unlist(lapply(dots, function(i) { if (grepl("^contains\\(", i)) { pattern <- gsub("contains\\(\"(.*)\"\\)", "\\1", i) columns[string_contains(pattern, columns)] } else if (grepl("^starts\\(", i) || grepl("^starts_with\\(", i)) { pattern <- gsub("(.*)\\(\"(.*)\"\\)", "\\2", i) columns[string_starts_with(pattern, columns)] } else if (grepl("^ends\\(", i) || grepl("^ends_with\\(", i)) { pattern <- gsub("(.*)\\(\"(.*)\"\\)", "\\2", i) columns[string_ends_with(pattern, columns)] } else if (grepl("^one_of\\(", i)) { pattern <- gsub("(\"|\\s)", "", unlist(strsplit(gsub("one_of\\(\"(.*)\"\\)", "\\1", i), ","))) columns[string_one_of(pattern, columns)] } else if (grepl("^num_range\\(", i)) { columns[match(.get_num_range(i), columns)] } else if (grepl(":", i, fixed = TRUE)) { tmp <- unlist(strsplit(i, ":", fixed = TRUE)) start <- if (.is_num_chr(tmp[1])) as.numeric(tmp[1]) else which(columns == tmp[1]) end <- if (.is_num_chr(tmp[2])) as.numeric(tmp[2]) else which(columns == tmp[2]) columns[start:end] } else { i } })) x <- unlist(lapply(x, function(i) { if (.is_num_chr(i)) columns[as.numeric(i)] else if (.is_num_fac(i)) columns[as.numeric(as.character(i))] else i })) not_found <- setdiff(x, columns) if (length(not_found) && isTRUE(verbose)) { insight::print_color(sprintf( "%i variables were not found in the dataset: %s\n", length(not_found), paste0(not_found, collapse = ", ") ), color = "red") } dat[, intersect(x, columns), drop = FALSE] } .is_num_chr <- function(x) { is.character(x) && !anyNA(suppressWarnings(as.numeric(stats::na.omit(x)))) } .is_num_fac <- function(x) { is.factor(x) && !anyNA(suppressWarnings(as.numeric(levels(x)))) } .get_num_range <- function(i) { r1 <- trimws(unlist(strsplit(gsub("num_range\\((.*)\\)", "\\1", i), ","))) r2 <- gsub("\"", "", trimws(gsub("(.*)(=)(.*)", "\\3", r1)), fixed = TRUE) es <- grepl("=", r1) if (any(es)) { names(r2)[es] <- trimws(gsub("(.*)(=)(.*)", "\\1", r1[es])) } args <- c("prefix", "range", "width") if (is.null(names(r2))) { names(r2) <- args[1:length(r2)] } na_names <- which(is.na(names(r2))) if (length(na_names)) { names(r2)[na_names] <- args[na_names] } if (length(r2) > 3) { r2 <- r2[1:3] } from <- as.numeric(gsub("(\\d):(.*)", "\\1", r2["range"])) to <- as.numeric(gsub("(.*):(\\d)", "\\2", r2["range"])) width <- as.numeric(r2["width"]) if (is.na(width)) { sprintf("%s%i", r2["prefix"], from:to) } else { sprintf("%s%.*i", r2["prefix"], width, from:to) } }
sqrt_matrix <- function( V, tol = 1e-06 ){ if ( missing( V ) ) stop('`V` is missing!') obj <- eigen( V ) eigenvals <- obj$values eigenvecs <- obj$vectors if ( any( eigenvals < -tol * abs( eigenvals[ 1L ] ) ) ) stop("'V' is not positive definite") eigenvals[ eigenvals < 0 ] <- 0 V_sqrt <- eigenvecs %*% diag( sqrt( eigenvals ) ) return( V_sqrt ) }
mmgroupedplot <- function(stat.data, map.data, panel.types, panel.data, map.link=NULL, nPanels=length(panel.types), grp.by, cat, colors=brewer.pal(10, "Spectral"), map.color='lightyellow', map.all=FALSE, print.file='no', print.res=NA, panel.att=vector("list", nPanels), plot.header=NA, plot.header.size=NA, plot.header.color=NA, plot.footer=NA, plot.footer.size=NA, plot.footer.color=NA, plot.width=7, plot.height=7, map.spacing=1, plot.grp.spacing=1, plot.panel.spacing=1, plot.panel.margins=c(0,0,1,0) ){ dStats <- stat.data dMap <- map.data ncol <- length(unique(stat.data[, cat])) colors <- colorRampPalette(colors)(ncol) tPlot.header=plot.header iPlot.header.size=plot.header.size tPlot.header.color=plot.header.color tPlot.footer=plot.footer iPlot.footer.size=plot.footer.size tPlot.footer.color=plot.footer.color pps = plot.panel.spacing*.05 plot.atts <- list( plot.grp.spacing=plot.grp.spacing*.05, plot.pGrp.spacing=plot.grp.spacing*.05, plot.panel.margins=plot.panel.margins, grp.by=grp.by, colors=colors, map.color=map.color, map.spacing=map.spacing*.025, plot.width=plot.width, plot.height=plot.height) a <- vector("list", nPanels) for(p in 1:nPanels) { att.name <- paste(panel.types[p],'_att',sep='') att.function <- paste(panel.types[p],'_att()',sep='') if(exists(att.name)) a[[p]] <- eval(parse(text=att.function)) else a[[p]] <- eval(parse(text=standard_att)) } a <- append(a, plot.atts) for(j in 1:length(panel.types)) { a[[j]] <- append(a[[j]], list(panel.data=unlist(panel.data[[j]]))) } for(j in 1:length(panel.att)){ k <- unlist(panel.att[[j]][1], use.names=FALSE) for(s in names(panel.att[[j]])[-1]){ w <- match(s, right(names(a[[k]]), nchar(s))) if(is.na(w)) w <- match(paste('panel.',s,sep=''), names(a[[k]])) if(!is.na(w)) a[[k]][[w]] <- unlist(panel.att[[j]][s], use.names=FALSE) else print(paste('attribute:',s,'is not recognized for panel',j)) if(!is.null(k)){ w <- match('left.margin', names(a[[k]])) if(!is.na(w) & !is.na(a[[k]][[w]])) a[[k]]$panel.margins[4] <- a[[k]]$panel.margins[4] + a[[k]][[w]] w <- match('right.margin', names(a[[k]])) if(!is.na(w) & !is.na(a[[k]][[w]])) a[[k]]$panel.margins[2] <- a[[k]]$panel.margins[2] + a[[k]][[w]] } } } DF <- create_DF_cat(dStats, grp.by, cat) a$median.row <- FALSE a$two.ended.maps <- FALSE a$m.pGrp <- (max(DF$pGrp)+1)/2 a$m.rank <- NA DF.hold <- DF if(any(panel.types=='map')){ w <- match(dMap[,map.link[2]], unique(DF[,map.link[1]])) if(!map.all) mapDF <- dMap[!is.na(w),] else mapDF <- dMap if(!'hole'%in%names(mapDF)) mapDF$hole <- 0 if(!'plug'%in%names(mapDF)) mapDF$plug <- 0 tmpDF <- unique(DF[,c('pGrp', 'pGrpOrd', map.link[1])]) w <- match(mapDF[,map.link[2]], tmpDF[,map.link[1]]) mapDF <- cbind(pGrp=DF[w,'pGrp'], mapDF) mapDF <- cbind(pGrpOrd=DF$pGrpOrd[w], mapDF) mapPanelWidth <- as.numeric(a[[which(panel.types=='map')]]$panel.width) totalUnitWidth = pps * (length(all_atts(a,'panel.width'))+1) + sum(as.numeric(all_atts(a,'panel.width'))) mapPanelHeight <- max(DF$pGrpOrd[!is.na(DF$pGrpOrd)])+.5 totalUnitHeight = max(DF$pGrp[!is.na(DF$pGrp)]) * mapPanelHeight ns <- max(unlist(lapply(all_atts(a, 'panel.header'), function(x) length(strsplit(x, '\n')[[1]])))) adj.plot.height <- plot.height - ns*.2 + any(!is.na(all_atts(a, 'xaxis.title')))*.1 + .2 + .5 plot.h2w.ratio <- (mapPanelHeight/totalUnitHeight * adj.plot.height) / (mapPanelWidth/totalUnitWidth * plot.width) nYrows <- diff(range(mapDF$pGrpOrd[!is.na(mapDF$pGrpOrd)]) + c(-1,1) * .5) nXcols <- nYrows/plot.h2w.ratio limitingAxis <- ifelse(diff(range(mapDF$coordsy)) / diff(range(mapDF$coordsx)) > plot.h2w.ratio, 'y','x') if(limitingAxis=='y'){ redFact <- diff(range(mapDF$coordsy))/nYrows mapDF$coordsy <- (mapDF$coordsy - median(range(mapDF$coordsy)))/diff(range(mapDF$coordsy))*nYrows mapDF$coordsx <- (mapDF$coordsx - median(range(mapDF$coordsx)))/redFact } if(limitingAxis=='x'){ redFact <- diff(range(mapDF$coordsx))/nXcols mapDF$coordsx <- (mapDF$coordsx - median(range(mapDF$coordsx)))/diff(range(mapDF$coordsx))*nXcols mapDF$coordsy <- (mapDF$coordsy - median(range(mapDF$coordsy)))/redFact } a[[which(panel.types=='map')]]$bdrCoordsy <- c(-1,1) * nYrows/2 a[[which(panel.types=='map')]]$bdrCoordsx <- c(-1,1) * nXcols/2 rm(tmpDF, dMap) } plots <- vector("list", nPanels) for(p in 1:nPanels){ if (panel.types[p]=='map'){ plots[[p]] <- CatMaps(plots[[p]], p, mapDF, a) } else if(exists(as.character(paste(panel.types[p],'_build',sep='')))) { plots[[p]] <- eval(parse(text=paste(panel.types[p],'_build(plots[[p]], p, DF, a)',sep=''))) } else { stop(paste("unknown panel type -- '",panel.types[p],"'", sep='')) } DF <- DF.hold } lwidth <- pps for(w in 1:length(all_atts(a,'panel.width'))) lwidth <- c(lwidth, all_atts(a,'panel.width')[w], pps) lmLayout <- grid.layout(nrow = 1, ncol = length(lwidth), widths = unit(lwidth, rep("null", length(lwidth))), heights = unit(rep(1, length(lwidth)), rep("null", length(lwidth)))) plots$layout <- lmLayout plots$plot.width <- plot.width plots$plot.height <- plot.height class(plots) <- "mm" if(print.file=="no") print.file <- NULL print(plots, name=print.file, res=print.res) invisible(plots) }
set.seed(123) pm <- cbind( c(.1, .001), c(.001, .05) ) g<-sample_correlated_sbm_pair(10, pref.matrix=pm, block.sizes=c(3,7), corr=0.5,permutation=1:10,directed=TRUE,loops=TRUE) test_that("number of vertices", { expect_equal(igraph::vcount(g$graph1),10) expect_equal(igraph::vcount(g$graph2),10) }) test_that("number of edges", { expect_equal(igraph::ecount(g$graph1),2) expect_equal(igraph::ecount(g$graph2),2) }) test_that("degree of vertex in each graph", { expect_equal(igraph::degree(g$graph1),c(0,0,0,1,1,2,0,0,0,0)) expect_equal(igraph::degree(g$graph2),c(0,0,0,1,1,1,0,0,0,1)) }) set.seed(123) pm <- cbind( c(.1, .001), c(.001, .05) ) g1<-sample_correlated_sbm_pair_w_junk(10, pref.matrix=pm, block.sizes=c(3,7), corr=0.5,core.block.sizes=c(2,5),permutation=1:10,directed=TRUE,loops=TRUE) test_that("number of vertices", { expect_equal(igraph::vcount(g1$graph1),10) expect_equal(igraph::vcount(g1$graph2),10) }) test_that("number of edges", { expect_equal(igraph::ecount(g1$graph1),2) expect_equal(igraph::ecount(g1$graph2),1) }) test_that("degree of vertex in each graph", { expect_equal(igraph::degree(g1$graph1),c(0,0,1,0,1,0,0,0,0,2)) expect_equal(igraph::degree(g1$graph2),c(0,0,1,0,0,0,0,0,0,1)) })
`plot.cascadeKM` <- function (x, min.g, max.g, grpmts.plot = TRUE, sortg = FALSE, gridcol = NA, ...) { wrapres <- x number <- (as.numeric(gsub(" groups", "", colnames(wrapres$results)))) if (missing(min.g)) min.g <- min(number) if (missing(max.g)) max.g <- max(number) if (min.g < 2) min.g = 2 c.min <- which(number == min.g) c.max <- which(number == max.g) if (length(c.min) == 0) { stop("min.g value given has not been calculated by 'cascadeKM'\n") } if (length(c.max) == 0) { stop("max.g value given has not been calculated by 'cascadeKM'\n") } x <- wrapres$partition[, c.min:c.max] w <- wrapres$results[2, c.min:c.max] criterion <- wrapres$criterion x <- pregraphKM(x) if (sortg) { x <- orderingKM(x) } main = (paste("K-means partitions comparison")) xlab = ("Number of groups in each partition") ylab = ("Objects") nc = ncol(x) colo <- (rainbow(max.g + 1)) if (grpmts.plot) { def.par <- par(no.readonly = TRUE) nf <- layout(matrix(c(1, 2), 1, 2), widths = c(3, 1), TRUE) par(mar = c(5, 5, 5, 1), bg = "white", col = "black") image(1:nrow(x), 1:nc, x, col = colo, yaxt = "n", frame.plot = TRUE, main = main, xlab = ylab, ylab = xlab, bg = NA) grid(nx = nrow(x), ny = max.g - min.g + 1, col = gridcol) box() axis(2, seq(min.g - min.g + 1, max.g - min.g + 1, by = 1), labels = seq(min.g, max.g, by = 1)) axis(1) par(mar = c(5, 2, 5, 1)) par(bg = "white", fg = "black", col = "black") plot(y = min.g:max.g, x = w[1:nc], type = "b", main = paste(criterion, "\ncriterion", sep = ""), ylab = "", ylim = c(min.g - 0.5, max.g + 0.5), yaxs = "i", yaxt = "n", xlab = "Values") grid(nx = NULL, ny = max.g - min.g + 1, col = gridcol) box() axis(2, seq(min.g, max.g, by = 1), labels = seq(min.g, max.g, by = 1), col.axis = "black") axis(1) maxx = which.max(w[]) minx = which.min(w[]) tops <- which(w[c(2:nc)] - w[c(1:(nc - 1))] > 0) + 1 maxx.o <- NA if (length(tops) != 0) { if (length(which(tops > maxx)) != 0) maxx.o <- tops[which(tops > maxx)] } tops <- which(w[c(2:nc)] - w[c(1:(nc - 1))] < 0) + 1 minx.o <- NA if (length(tops) != 0) { if (length(which(tops > minx)) != 0) minx.o <- tops[which(tops > minx)] } if (tolower(criterion) == "calinski") { if (!is.na(maxx.o[1])) points(y = maxx.o + min.g - 1, x = w[maxx.o], col = "orange", pch = 19) points(y = maxx + min.g - 1, x = w[maxx], col = "red", pch = 19) } else if (tolower(criterion) == "likelihood") { if (!is.na(maxx.o[1])) { points(y = maxx.o + min.g - 1, x = w[maxx.o], col = "orange", pch = 19) } points(y = maxx + min.g - 1, x = w[maxx], col = "red", pch = 19) } else if (tolower(criterion) == "ssi") { if (!is.na(maxx.o[1])) { points(y = maxx.o + min.g - 1, x = w[maxx.o], col = "orange", pch = 19) } points(y = maxx + min.g - 1, x = w[maxx], col = "red", pch = 19) } else { cat("When using the", criterion, "criterion, no red marker is", "used to indicate the best value.\n") } par(def.par) } else { tops <- which(w[c(2:nc)] - w[c(1:(nc - 1))] > 0) + 1 if (length(tops) != 0) { maxx <- which.max(w[c(2:nc)] - w[c(1:nc - 1)]) + 1 } else { maxx <- which.max(w[]) tops = 1 } } out <- list(x = x, best.grps = maxx) if (grpmts.plot) invisible(out) else out }
SAS.ED2.param.Args <- function(decomp_scheme=2, kh_active_depth = -0.20, decay_rate_fsc=11, decay_rate_stsc=4.5, decay_rate_ssc=0.2, Lc=0.049787, c2n_slow=10.0, c2n_structural=150.0, r_stsc=0.3, rh_decay_low=0.24, rh_decay_high=0.60, rh_low_temp=18.0+273.15, rh_high_temp=45.0+273.15, rh_decay_dry=12.0, rh_decay_wet=36.0, rh_dry_smoist=0.48, rh_wet_smoist=0.98, resp_opt_water=0.8938, resp_water_below_opt=5.0786, resp_water_above_opt=4.5139, resp_temperature_increase=0.0757, rh_lloyd_1=308.56, rh_lloyd_2=1/56.02, rh_lloyd_3=227.15, yrs.met=30, sm_fire=0, fire_intensity=0, slxsand=0.33, slxclay=0.33) { return( data.frame( decomp_scheme = decomp_scheme, kh_active_depth = kh_active_depth, decay_rate_fsc = decay_rate_fsc, decay_rate_stsc = decay_rate_stsc, decay_rate_ssc = decay_rate_ssc, Lc = Lc, c2n_slow = c2n_slow, c2n_structural = c2n_structural, r_stsc = r_stsc, rh_decay_low = rh_decay_low, rh_decay_high = rh_decay_high, rh_low_temp = rh_low_temp, rh_high_temp = rh_high_temp, rh_decay_dry = rh_decay_dry, rh_decay_wet = rh_decay_wet, rh_dry_smoist = rh_dry_smoist, rh_wet_smoist = rh_wet_smoist, resp_opt_water = resp_opt_water, resp_water_below_opt = resp_water_below_opt, resp_water_above_opt = resp_water_above_opt, resp_temperature_increase = resp_temperature_increase, rh_lloyd_1 = rh_lloyd_1, rh_lloyd_2 = rh_lloyd_2, rh_lloyd_3 = rh_lloyd_3, yrs.met = yrs.met, sm_fire = sm_fire, fire_intensity = fire_intensity, slxsand = slxsand, slxclay = slxclay ) ) } calc.slmsts <- function(slxsand, slxclay){ (50.5 - 14.2*slxsand - 3.7*slxclay) / 100. } calc.slpots <- function(slxsand, slxclay){ -1. * (10.^(2.17 - 0.63*slxclay - 1.58*slxsand)) * 0.01 } calc.slbs <- function(slxsand, slxclay){ 3.10 + 15.7*slxclay - 0.3*slxsand } calc.soilcp <- function(slmsts, slpots, slbs){ soilcp_MPa = -3.1 wdns = 1.000e3 grav=9.80665 slmsts * (slpots / (soilcp_MPa * wdns / grav)) ^ (1./slbs) } smfire.neg <- function(slmsts, slpots, smfire, slbs){ grav=9.80665 soilfr <- slmsts*((slpots/(smfire * 1000/9.80665))^(1/slbs)) return(soilfr) } smfire.pos <- function(slmsts, soilcp, smfire){ soilfr <- soilcp + smfire * (slmsts - soilcp) return(soilfr) } SAS.ED2 <- function(dir.analy, dir.histo, outdir, lat, lon, blckyr, prefix, treefall, param.args = SAS.ED2.param.Args(), sufx = "g01.h5") { if(!param.args$decomp_scheme %in% 0:4) stop("Invalid decomp_scheme") dir.create(outdir, recursive=T, showWarnings=F) ann.files <- dir(dir.analy, "-Y-") yrind <- which(strsplit(ann.files,"-")[[1]] == "Y") yeara <- as.numeric(strsplit(ann.files,"-")[[1]][yrind+1]) yearz <- as.numeric(strsplit(ann.files,"-")[[length(ann.files)]][yrind+1]) yrs <- seq(yeara+1, yearz, by=blckyr) nsteps <- length(yrs) nc.temp <- ncdf4::nc_open(file.path(dir.analy, ann.files[1])) slz <- ncdf4::ncvar_get(nc.temp, "SLZ") ncdf4::nc_close(nc.temp) dslz <- vector(length=length(slz)) dslz[length(dslz)] <- 0-slz[length(dslz)] for(i in 1:(length(dslz)-1)){ dslz[i] <- slz[i+1] - slz[i] } nsoil=which(slz >= param.args$kh_active_depth-1e-3) pss.big <- matrix(nrow=length(yrs),ncol=13) colnames(pss.big) <- c("time","patch","trk","age","area","water","fsc","stsc","stsl", "ssc","psc","msn","fsn") soil.obj <- PEcAn.data.land::soil_params(sand = param.args$slxsand, clay = param.args$slxclay) slmsts <- calc.slmsts(param.args$slxsand, param.args$slxclay) slpots <- calc.slpots(param.args$slxsand, param.args$slxclay) slbs <- calc.slbs(param.args$slxsand, param.args$slxclay) soilcp <- calc.soilcp(slmsts, slpots, slbs) soilfr=0 if(abs(param.args$sm_fire)>0){ if(param.args$sm_fire>0){ soilfr <- smfire.pos(slmsts, soilcp, smfire=param.args$sm_fire) } else { soilfr <- smfire.neg(slmsts, slpots, smfire=param.args$sm_fire, slbs) } } month.begin = 1 month.end = 12 tempk.air <- tempk.soil <- moist.soil <- moist.soil.mx <- moist.soil.mn <- nfire <- vector() for(y in yrs){ air.temp.tmp <- soil.temp.tmp <- soil.moist.tmp <- soil.mmax.tmp <- soil.mmin.tmp <- vector() ind <- which(yrs == y) for(m in month.begin:month.end){ year.now <-sprintf("%4.4i",y) month.now <- sprintf("%2.2i",m) day.now <- sprintf("%2.2i",0) hour.now <- sprintf("%6.6i",0) file.now <- paste(prefix,"-E-",year.now,"-",month.now,"-",day.now,"-" ,hour.now,"-",sufx,sep="") now <- ncdf4::nc_open(file.path(dir.analy,file.now)) air.temp.tmp [m] <- ncdf4::ncvar_get(now, "MMEAN_ATM_TEMP_PY") soil.temp.tmp [m] <- sum(ncdf4::ncvar_get(now, "MMEAN_SOIL_TEMP_PY")[nsoil]*dslz[nsoil]/sum(dslz[nsoil])) soil.moist.tmp[m] <- sum(ncdf4::ncvar_get(now, "MMEAN_SOIL_WATER_PY")[nsoil]*dslz[nsoil]/sum(dslz[nsoil])) soil.mmax.tmp [m] <- max(ncdf4::ncvar_get(now, "MMEAN_SOIL_WATER_PY")) soil.mmin.tmp [m] <- min(ncdf4::ncvar_get(now, "MMEAN_SOIL_WATER_PY")) ncdf4::nc_close(now) } tempk.air [ind] <- mean(air.temp.tmp) tempk.soil [ind] <- mean(soil.temp.tmp) moist.soil [ind] <- mean(soil.moist.tmp) moist.soil.mx[ind] <- max(soil.mmax.tmp) moist.soil.mn[ind] <- min(soil.mmin.tmp) nfire [ind] <- length(which(soil.moist.tmp<soilfr)) } soil_tempk <- mean(tempk.soil) rel_soil_moist <- mean(moist.soil/slmsts) pfire = sum(nfire)/(length(nfire)*12) fire_return = ifelse(max(nfire)>0, length(nfire)/length(which(nfire>0)), 0) cat(paste0("mean soil temp : ", round(soil_tempk, 2), "\n")) cat(paste0("mean soil moist : ", round(rel_soil_moist, 3), "\n")) cat(paste0("fire return interval (yrs) : ", fire_return), "\n") fire_rate <- pfire * param.args$fire_intensity disturb <- treefall + fire_rate stand.age <- seq(yrs[1]-yeara,nrow(pss.big)*blckyr,by=blckyr) area.dist <- vector(length=nrow(pss.big)) area.dist[1] <- sum(stats::dgeom(0:(stand.age[2]-1), disturb)) for(i in 2:(length(area.dist)-1)){ area.dist[i] <- sum(stats::dgeom((stand.age[i]):(stand.age[i+1]-1),disturb)) } area.dist[length(area.dist)] <- 1 - sum(area.dist[1:(length(area.dist)-1)]) pss.big[,"area"] <- area.dist cat(" - Reading analy files ...","\n") for (y in yrs){ now <- ncdf4::nc_open(file.path(dir.analy,ann.files[y-yeara+1])) ind <- which(yrs == y) ipft <- ncdf4::ncvar_get(now,'PFT') css.tmp <- matrix(nrow=length(ipft),ncol=10) colnames(css.tmp) <- c("time", "patch", "cohort", "dbh", "hite", "pft", "n", "bdead", "balive", "Avgrg") css.tmp[,"time" ] <- rep(yeara,length(ipft)) css.tmp[,"patch" ] <- rep(floor((y-yeara)/blckyr)+1,length(ipft)) css.tmp[,"cohort"] <- 1:length(ipft) css.tmp[,"dbh" ] <- ncdf4::ncvar_get(now,'DBH') css.tmp[,"hite" ] <- ncdf4::ncvar_get(now,'HITE') css.tmp[,"pft" ] <- ipft css.tmp[,"n" ] <- ncdf4::ncvar_get(now,'NPLANT') css.tmp[,"bdead" ] <- ncdf4::ncvar_get(now,'BDEAD') css.tmp[,"balive"] <- ncdf4::ncvar_get(now,'BALIVE') css.tmp[,"Avgrg" ] <- rep(0,length(ipft)) if(y==yrs[1]){ css.big <- css.tmp } else{ css.big <- rbind(css.big,css.tmp) } pss.big[ind,"time"] <- 1800 pss.big[ind,"patch"] <- floor((y-yeara)/blckyr)+1 pss.big[ind,"trk"] <- 1 pss.big[ind,"age"] <- y-yeara pss.big[ind,"water"] <- 0.5 pss.big[ind,"fsc"] <- ncdf4::ncvar_get(now,"FAST_SOIL_C") pss.big[ind,"stsc"] <- ncdf4::ncvar_get(now,"STRUCTURAL_SOIL_C") pss.big[ind,"stsl"] <- ncdf4::ncvar_get(now,"STRUCTURAL_SOIL_L") pss.big[ind,"ssc"] <- ncdf4::ncvar_get(now,"SLOW_SOIL_C") pss.big[ind,"psc"] <- 0 pss.big[ind,"msn"] <- ncdf4::ncvar_get(now,"MINERALIZED_SOIL_N") pss.big[ind,"fsn"] <- ncdf4::ncvar_get(now,"FAST_SOIL_N") ncdf4::nc_close(now) } pss.big <- pss.big[stats::complete.cases(pss.big),] fsc_in_y <- ssc_in_y <- ssl_in_y <- fsn_in_y <- pln_up_y <- vector() fsc_in_m <- ssc_in_m <- ssl_in_m <- fsn_in_m <- pln_up_m <- vector() mon.files <- dir(dir.histo, "-S-") yeara <- as.numeric(strsplit(mon.files,"-")[[1]][yrind+1]) yearz <- as.numeric(strsplit(mon.files,"-")[[length(mon.files)-1]][yrind+1]) montha <- as.numeric(strsplit(mon.files,"-")[[1]][yrind+2]) monthz <- as.numeric(strsplit(mon.files,"-")[[length(mon.files)-1]][yrind+2]) cat(" - Processing History Files \n") for (y in yrs){ dpm <- lubridate::days_in_month(1:12) if(lubridate::leap_year(y)) dpm[2] <- dpm[2]+1 if (y == yrs[1]){ month.begin = montha }else{ month.begin = 1 } if (y == yrs[length(yrs)]){ month.end = monthz }else{ month.end = 12 } for(m in month.begin:month.end){ year.now <-sprintf("%4.4i",y) month.now <- sprintf("%2.2i",m) day.now <- sprintf("%2.2i",1) hour.now <- sprintf("%6.6i",0) file.now <- paste(prefix,"-S-",year.now,"-",month.now,"-",day.now,"-" ,hour.now,"-",sufx,sep="") now <- ncdf4::nc_open(file.path(dir.histo,file.now)) fsc_in_m[m-month.begin+1] <- ncdf4::ncvar_get(now,"FSC_IN")*dpm[m] ssc_in_m[m-month.begin+1] <- ncdf4::ncvar_get(now,"SSC_IN")*dpm[m] ssl_in_m[m-month.begin+1] <- ncdf4::ncvar_get(now,"SSL_IN")*dpm[m] fsn_in_m[m-month.begin+1] <- ncdf4::ncvar_get(now,"FSN_IN")*dpm[m] pln_up_m[m-month.begin+1] <- ncdf4::ncvar_get(now,"TOTAL_PLANT_NITROGEN_UPTAKE")*dpm[m] ncdf4::nc_close(now) } ind <- (y-yeara)/blckyr + 1 fsc_in_y[ind] <- sum(fsc_in_m,na.rm=TRUE) ssc_in_y[ind] <- sum(ssc_in_m,na.rm=TRUE) ssl_in_y[ind] <- sum(ssl_in_m,na.rm=TRUE) fsn_in_y[ind] <- sum(fsn_in_m,na.rm=TRUE) pln_up_y[ind] <- sum(pln_up_m,na.rm=TRUE) } fsc_loss <- param.args$decay_rate_fsc ssc_loss <- param.args$decay_rate_ssc ssl_loss <- param.args$decay_rate_stsc if(param.args$decomp_scheme %in% c(0, 3)){ temperature_limitation = min(1,exp(param.args$resp_temperature_increase * (soil_tempk-318.15))) } else if(param.args$decomp_scheme %in% c(1,4)){ lnexplloyd = param.args$rh_lloyd_1 * ( param.args$rh_lloyd_2 - 1. / (soil_tempk - param.args$rh_lloyd_3)) lnexplloyd = max(-38.,min(38,lnexplloyd)) temperature_limitation = min( 1.0, param.args$resp_temperature_increase * exp(lnexplloyd) ) } else if(param.args$decomp_scheme==2) { lnexplow <- param.args$rh_decay_low * (param.args$rh_low_temp - soil_tempk) lnexplow <- max(-38, min(38, lnexplow)) tlow_fun <- 1 + exp(lnexplow) lnexphigh <- param.args$rh_decay_high*(soil_tempk - param.args$rh_high_temp) lnexphigh <- max(-38, min(38, lnexphigh)) thigh_fun <- 1 + exp(lnexphigh) temperature_limitation <- 1/(tlow_fun*thigh_fun) } if(param.args$decomp_scheme %in% c(0,1)){ if (rel_soil_moist <= param.args$resp_opt_water){ water_limitation = exp( (rel_soil_moist - param.args$resp_opt_water) * param.args$resp_water_below_opt) } else { water_limitation = exp( (param.args$resp_opt_water - rel_soil_moist) * param.args$resp_water_above_opt) } } else if(param.args$decomp_scheme==2){ lnexpdry <- param.args$rh_decay_dry * (param.args$rh_dry_smoist - rel_soil_moist) lnexpdry <- max(-38, min(38, lnexpdry)) smdry_fun <- 1+exp(lnexpdry) lnexpwet <- param.args$rh_decay_wet * (rel_soil_moist - param.args$rh_wet_smoist) lnexpwet <- max(-38, min(38, lnexpwet)) smwet_fun <- 1+exp(lnexpwet) water_limitation <- 1/(smdry_fun * smwet_fun) } else { water_limitation = rel_soil_moist * 4.0893 - rel_soil_moist**2 * 3.1681 - 0.3195897 } A_decomp <- temperature_limitation * water_limitation fsc_ss <- fsc_in_y[length(fsc_in_y)]/(fsc_loss * A_decomp) ssl_ss <- ssl_in_y[length(ssl_in_y)]/(ssl_loss * A_decomp * param.args$Lc) ssc_ss <- ((ssl_loss * A_decomp * param.args$Lc * ssl_ss)*(1 - param.args$r_stsc))/(ssc_loss * A_decomp ) fsn_ss <- fsn_in_y[length(fsn_in_y)]/(fsc_loss * A_decomp) msn_loss <- pln_up_y[length(pln_up_y)] + A_decomp*param.args$Lc*ssl_loss*ssl_in_y[length(ssl_in_y)]* ((1.0-param.args$r_stsc)/param.args$c2n_slow - 1.0/param.args$c2n_structural) msn_med <- fsc_loss*A_decomp*fsn_in_y[length(fsn_in_y)]+ (ssc_loss * A_decomp)/param.args$c2n_slow msn_ss <- msn_med/msn_loss p.use <- 1 pss.big[,"patch"] <- 1:nrow(pss.big) pss.big[,"area"] <- area.dist pss.big[,"fsc"] <- rep(fsc_ss[p.use],nrow(pss.big)) pss.big[,"stsc"] <- rep(ssl_ss[p.use],nrow(pss.big)) pss.big[,"stsl"] <- rep(ssl_ss[p.use],nrow(pss.big)) pss.big[,"ssc"] <- rep(ssc_ss[p.use],nrow(pss.big)) pss.big[,"msn"] <- rep(msn_ss[p.use],nrow(pss.big)) pss.big[,"fsn"] <- rep(fsn_ss[p.use],nrow(pss.big)) file.prefix=paste0(prefix, "-lat", lat, "lon", lon) utils::write.table(css.big,file=file.path(outdir,paste0(file.prefix,".css")),row.names=FALSE,append=FALSE, col.names=TRUE,quote=FALSE) utils::write.table(pss.big,file=file.path(outdir,paste0(file.prefix,".pss")),row.names=FALSE,append=FALSE, col.names=TRUE,quote=FALSE) }
getsyn <- function(matrix){ if(length(colnames(matrix))==0){colnames(matrix) <- 1:dim(matrix)[2]} matrixone <- matrix if(length(matrixone)==0){return(list(mono=as.matrix(NaN),syn=as.matrix(NaN),nonsyn=as.matrix(NaN),monoid=NaN,synid=NaN,nonsynid=NaN,Codons=as.list(NaN)))} matrix <- codonise64(matrixone) monoid <- NULL synid <- NULL nonsynid <- NULL acc <- 1 Codons <- vector("list",dim(matrix)[2]) erg <- apply(matrix,2,function(vek){ uniquevek <- unique(vek) size <- length(uniquevek) if(size==1){ Codons[[acc]] <<- uniquevek acc <<- acc + 1 return(1) } if(size>1){ Codons[[acc]] <<- uniquevek acc <<- acc + 1 cc <- codontable() id65 <- which(uniquevek==65) if(length(id65)>0){vek <- uniquevek[-id65]} tt <- unique(cc$Protein[1,vek]) size <- length(tt) if(size==1){ return(2) } if(size>1){ return(3) } } }) rm(matrix) mono <- which(erg==1) syn <- which(erg==2) nonsyn <- which(erg==3) if(length(mono)>0){ monoid <- c(3*mono-2,3*mono-1,3*mono) monoid <- sort(monoid) } if(length(syn)>0){ synid <- c(3*syn-2,3*syn-1,3*syn) synid <- sort(synid) } if(length(nonsyn)>0){ nonsynid <- c(3*nonsyn-2,3*nonsyn-1,3*nonsyn) nonsynid <- sort(nonsynid) } monoid <- as.numeric(colnames(matrixone[,monoid])) synid <- as.numeric(colnames(matrixone[,synid])) nonsynid <- as.numeric(colnames(matrixone[,nonsynid])) return(list(monoid=monoid,synid=synid,nonsynid=nonsynid,Codons=Codons)) }
drive_mv <- function(file, path = NULL, name = NULL, overwrite = NA, verbose = deprecated()) { warn_for_verbose(verbose) file <- as_dribble(file) file <- confirm_single_file(file) if (is.null(path) && is.null(name)) { drive_bullets(c( "!" = "Nothing to be done." )) return(invisible(file)) } tmp <- rationalize_path_name(path, name) path <- tmp$path name <- tmp$name params <- list() parents_before <- pluck(file, "drive_resource", 1, "parents") if (!is.null(path)) { path <- as_parent(path) if (!path$id %in% parents_before) { params[["addParents"]] <- path$id } } if (!is.null(name) && name != file$name) { params[["name"]] <- name } if (length(params) == 0) { drive_bullets(c( "!" = "Nothing to be done." )) return(invisible(file)) } check_for_overwrite( parent = params[["addParents"]] %||% parents_before[[1]], name = params[["name"]] %||% file$name, overwrite = overwrite ) params[["fields"]] <- "*" out <- drive_update_metadata(file, params) actions <- c( renamed = !identical(out$name, file$name), moved = !is.null(params[["addParents"]]) ) action <- glue_collapse(names(actions)[actions], last = " and ") drive_bullets(c( "Original file:", bulletize(gargle_map_cli(file)), "Has been {action}:", bulletize(gargle_map_cli( drive_reveal_path(out, ancestors = path), template = c( id_string = "<id:\u00a0<<id>>>", out = "{.drivepath <<path>>} {cli::col_grey('<<id_string>>')}" ) )) )) invisible(out) }
options(tibble.print_min = 6) options(tibble.print_max = 6) library(nycflights13) ?flights ?airports ?airlines ?planes ?weather library(tidyverse) flights_base <- flights %>% select(year, month, day, carrier, tailnum, origin, dest) flights_base airlines flights_base %>% left_join(airlines) airlines[airlines$carrier == "UA", "name"] <- "United broke my guitar" flights_base %>% left_join(airlines) planes flights_base %>% left_join(planes) flights_base %>% left_join(planes) %>% count(is.na(type)) flights_base %>% left_join(planes, by = "tailnum") airports try( flights_base %>% left_join(airports) ) flights_base %>% left_join(airports, by = c("origin" = "faa")) rm(airlines) t1 <- tibble(a = 1, b = letters[1:3]) t1 t2 <- tibble(a = 1, c = 1:2) t2 left_join(t1, t2) airlines %>% count(carrier) airlines %>% count(carrier) %>% count(n) planes %>% count(tailnum) %>% count(n) planes %>% dm::check_key(tailnum) try( planes %>% dm::check_key(engines) ) airports %>% dm::check_key(faa) try( airports %>% dm::check_key(name) ) airports %>% add_count(name) %>% filter(n > 1) %>% arrange(name) rm(t1, t2) library(dm) dm_nycflights13(cycle = TRUE) dm_nycflights13(cycle = TRUE) %>% dm_draw() dm_nycflights13(cycle = TRUE) %>% dm_select_tbl(flights, airlines) %>% dm_draw() dm_nycflights13(cycle = TRUE) %>% dm_select_tbl(airports, airlines) %>% dm_draw() try( dm_nycflights13() %>% dm_select_tbl(bogus) ) dm_nycflights13() %>% tbl("airlines") dm_nycflights13() %>% src_tbls() x <- 1:5 y <- x + 1 z <- x * y w <- map(z, ~ runif(.)) tibble(x, y, z, w) tibble(x = 1:5) %>% mutate(y = x + 1) %>% mutate(z = x * y) %>% mutate(w = map(z, ~ runif(.))) dm_nycflights13() (dm_nyc_filtered <- dm_nycflights13() %>% dm_filter(airlines, carrier == "AA")) dm_nyc_filtered %>% dm_apply_filters() (dm_nyc_fail <- dm_nycflights13() %>% dm_filter(airports, origin == "EWR")) try( tbl(dm_nyc_fail, "flights") ) tbl(dm_nyc_fail, "weather") dm_nycflights13() %>% dm_filter(flights, origin == "EWR") %>% dm_apply_filters() dm_nycflights13() %>% dm_filter(airlines, name == "American Airlines Inc.") %>% dm_filter(airports, name != "John F Kennedy Intl") %>% dm_apply_filters() aa_non_jfk_january <- dm_nycflights13() %>% dm_filter(airlines, name == "American Airlines Inc.") %>% dm_filter(airports, name != "John F Kennedy Intl") %>% dm_filter(flights, month == 1) %>% dm_apply_filters() aa_non_jfk_january aa_non_jfk_january %>% tbl("planes") nycflights13_sqlite <- dm_nycflights13() %>% dm_select_tbl(-planes) %>% dm_filter(flights, month == 1) %>% dm_apply_filters() %>% copy_dm_to(dbplyr::src_memdb(), ., unique_table_names = TRUE) nycflights13_sqlite nycflights13_sqlite %>% dm_draw() nycflights13_sqlite %>% dm_get_tables() %>% map(dbplyr::sql_render) nycflights13_sqlite %>% dm_filter(airlines, name == "American Airlines Inc.") %>% dm_filter(airports, name != "John F Kennedy Intl") %>% dm_filter(flights, day == 1) %>% tbl("flights") nycflights13_sqlite %>% dm_filter(airlines, name == "American Airlines Inc.") %>% dm_filter(airports, name != "John F Kennedy Intl") %>% dm_filter(flights, day == 1) %>% tbl("flights") %>% dbplyr::sql_render() dm_nycflights13() %>% dm_join_to_tbl(airlines, flights, join = left_join) dm_nycflights13() %>% dm_join_to_tbl(flights, airlines, join = left_join) nycflights13_sqlite %>% dm_join_to_tbl(airlines, flights, join = left_join) aa_non_jfk_january %>% dm_join_to_tbl(flights, airlines, join = left_join) try( dm_nycflights13() %>% dm_join_to_tbl(airports, airlines, join = left_join) ) try( dm_nycflights13() %>% dm_join_to_tbl(flights, airports, airlines, join = left_join) ) weather %>% enum_pk_candidates() weather %>% enum_pk_candidates() %>% count(candidate) weather %>% unite("slot_id", origin, year, month, day, hour, remove = FALSE) %>% count(slot_id) %>% filter(n > 1) weather %>% count(origin, time_hour) %>% filter(n > 1) weather %>% count(origin, format(time_hour)) %>% filter(n > 1) weather %>% count(origin, format(time_hour, tz = "UTC")) %>% filter(n > 1) weather_link <- weather %>% mutate(time_hour_fmt = format(time_hour, tz = "UTC")) %>% unite("origin_slot_id", origin, time_hour_fmt, remove = FALSE) flights_link <- flights %>% mutate(time_hour_fmt = format(time_hour, tz = "UTC")) %>% unite("origin_slot_id", origin, time_hour_fmt, remove = FALSE) nycflights13_dm <- as_dm(list(airlines = airlines, airports = airports, flights = flights_link, planes = planes, weather = weather_link)) airlines_global <- airlines airports_global <- airports planes_global <- planes global <- dm_from_src(src_df(env = .GlobalEnv)) global global %>% dm_rename_tbl( airlines = airlines_global, airports = airports_global, planes = planes_global, flights = flights_link, weather = weather_link ) %>% dm_select_tbl(airlines, airports, planes, flights, weather) nycflights13_tbl <- global %>% dm_select_tbl( airlines = airlines_global, airports = airports_global, planes = planes_global, flights = flights_link, weather = weather_link ) nycflights13_tbl nycflights13_tbl %>% dm_draw() nycflights13_pk <- nycflights13_tbl %>% dm_add_pk(weather, origin_slot_id) %>% dm_add_pk(planes, tailnum) %>% dm_add_pk(airports, faa) %>% dm_add_pk(airlines, carrier) nycflights13_pk %>% dm_draw() nycflights13_fk <- nycflights13_pk %>% dm_add_fk(flights, origin_slot_id, weather, check = FALSE) %>% dm_add_fk(flights, tailnum, planes, check = FALSE) %>% dm_add_fk(flights, origin, airports) %>% dm_add_fk(flights, dest, airports, check = FALSE) %>% dm_add_fk(flights, carrier, airlines) nycflights13_fk %>% dm_draw() dm_get_available_colors() nycflights13_fk %>% dm_set_colors(airlines = , planes = , weather = , airports = "blue") %>% dm_draw() try({ dm_pq <- dm_nycflights13() %>% dm_select_tbl(-planes) %>% dm_filter(flights, month == 1) %>% copy_dm_to(src_postgres(), ., temporary = FALSE) dm_from_pq <- dm_learn_from_db(src_postgres()) })
mADCF <- function(x, lags, unbiased = FALSE, output = TRUE ) { if ( !is.matrix(x) ) x <- as.matrix(x) if ( (is.data.frame(x) ) | ( is.matrix(x) ) ) { if ( dim(x)[2] == 1 ) stop( 'Only multivariate time series with dimension d>2.' ) if ( !is.ts(x) ) x <- as.ts(x) } if ( !is.numeric(x) ) stop( "'x' must be numeric." ) if ( !all( is.finite(x) ) ) stop( 'Missing or infitive values.' ) if ( missing(lags) ) stop( "'lags' is missing with no default." ) dm <- dim(x) n <- dm[1] ; d <- dm[2] if ( length(lags) == 1 ) { if ( ( lags >= 0 ) && ( lags <= (n - 1) ) ) { X <- x[(1 + lags):n, ] Y <- x[1:(n - lags), ] } else if ( ( lags >= (-n + 1) ) && ( lags < 0 ) ) { X <- x[1:(n + lags), ] Y <- x[(1 - lags):n, ] } else { stop( "lags must be in the range of -(n-1) and (n-1)" ) } cross.adcf <- matrix(NA, d, d) if ( unbiased ) { for (i in 1:d) cross.adcf[i, ] <- dcov::mdcor(X[, i], Y, type = "U") } else { for (i in 1:d) cross.adcf[i, ] <- dcov::mdcor( X[, i], Y ) cross.adcf <- sqrt( cross.adcf ) } if ( output ) { cat( "Distance Correlation Matrix at lag: ", lags, "\n" ) print(cross.adcf) } } else if ( length(lags) > 1 ) { len <- length(lags) cross.adcf <- array( dim = c(d, d, len)) for ( j in 1:len ) { cross <- matrix(NA, d, d) lag <- lags[j] if ( ( lag >= 0 ) && ( lag <= (n - 1) ) ) { X <- x[(1 + lag):n, ] Y <- x[1:(n - lag), ] } else if ( ( lag >= (-n + 1) ) && ( lag < 0 ) ) { X <- x[1:(n + lag), ] Y <- x[(1 - lag):n, ] } else { stop( "lags must be in the range of -(n-1) and (n-1)" ) } if ( unbiased ) { for (i in 1:d) cross[i, ] <- dcov::mdcor(X[, i], Y, type = "U") } else { for (i in 1:d) cross[i, ] <- dcov::mdcor( X[, i], Y ) cross <- sqrt( cross ) } cross.adcf[, , j] <- cross } dimnames(cross.adcf)[[ 3 ]] <- paste( "Distance Correlation Matrix at lag: ", lags) if ( output ) print(cross.adcf) } mADCF <- cross.adcf }
library(boot) diff.means <- function(d, f) { n <- nrow(d) gp1 <- 1:table(as.numeric(d$series))[1] m1 <- sum(d[gp1,1] * f[gp1])/sum(f[gp1]) m2 <- sum(d[-gp1,1] * f[-gp1])/sum(f[-gp1]) ss1 <- sum(d[gp1,1]^2 * f[gp1]) - (m1 * m1 * sum(f[gp1])) ss2 <- sum(d[-gp1,1]^2 * f[-gp1]) - (m2 * m2 * sum(f[-gp1])) c(m1 - m2, (ss1 + ss2)/(sum(f) - 2)) } grav1 <- gravity[as.numeric(gravity[,2]) >= 7,] boot(grav1, diff.means, R = 999, stype = "f", strata = grav1[,2]) nuke <- nuclear[, c(1, 2, 5, 7, 8, 10, 11)] nuke.lm <- glm(log(cost) ~ date+log(cap)+ne+ct+log(cum.n)+pt, data = nuke) nuke.diag <- glm.diag(nuke.lm) nuke.res <- nuke.diag$res * nuke.diag$sd nuke.res <- nuke.res - mean(nuke.res) nuke.data <- data.frame(nuke, resid = nuke.res, fit = fitted(nuke.lm)) new.data <- data.frame(cost = 1, date = 73.00, cap = 886, ne = 0, ct = 0, cum.n = 11, pt = 1) new.fit <- predict(nuke.lm, new.data) nuke.fun <- function(dat, inds, i.pred, fit.pred, x.pred) { lm.b <- glm(fit+resid[inds] ~ date+log(cap)+ne+ct+log(cum.n)+pt, data = dat) pred.b <- predict(lm.b, x.pred) c(coef(lm.b), pred.b - (fit.pred + dat$resid[i.pred])) } nuke.boot <- boot(nuke.data, nuke.fun, R = 999, m = 1, fit.pred = new.fit, x.pred = new.data) mean(nuke.boot$t[, 8]^2) new.fit - sort(nuke.boot$t[, 8])[c(975, 25)] nuke.boot <- boot(nuke.data, nuke.fun, R = 999, m = 1, fit.pred = new.fit, x.pred = new.data) n <- 500000 p <- 10 X <- matrix(rnorm(n * p), n, p) y <- rnorm(n) + X[,1] fit <- lm(y ~ X)
nyquistplot <- function(sys, w = seq(0, 100, length=10000), subtitle = "In(1) Out(1)"){ if (issiso(sys)) { H <- nyquist(sys, w) Real_Axis <- H$h.real Imaginary_Axis <- H$h.imag graphics::plot.default(Real_Axis, Imaginary_Axis, main="Nyquist Plot for the System", sub = subtitle, col="blue", type = "l", ylim=range( c(Imaginary_Axis, -Imaginary_Axis) )) graphics::lines.default(Real_Axis, -Imaginary_Axis, col="blue", type = "l", lty =2) graphics::grid(10,10) } if (ismimo(sys)) { graphics::par(mfrow = c( nrow(sys[[4]]), ncol(sys[[4]]) ) ) for (i in 1:nrow(sys[[4]])) { for (j in 1:ncol(sys[[4]])) { nyquistplot(selectsys(sys,i,j), subtitle = paste("In -", i, "Out -", j)) } } } }
exp_clus_gpx<-function(AID, cn= "all", locs, cs, centroid_calc="mean", dir= NULL){ if(AID %in% cs$AID == FALSE){stop(paste("AID", AID, "not found", sep=" "))} if(cn[1] == "all"){cn<-cs[which(cs$AID == AID),"clus_ID"]} clus_sub<-cs[which(cs$AID == AID & cs$clus_ID %in% cn),] if(length(cn[-which(cn %in% cs$clus_ID)])>0){stop(paste("Cluster(s)", paste(cn[-which(cn %in% cs$clus_ID)], collapse=","), "do not exist in cluster summary", sep=" "))} out_all<- locs[which(locs$AID == AID),] sites<-NA for(p in 1:nrow(clus_sub)){ ind_clus<-out_all[which(out_all$clus_ID == clus_sub$clus_ID[p]),] ind_clus<-ind_clus[which(!is.na(ind_clus$Lat)),] ind_clus$AID2<-"" ind_clus<-ind_clus[,c("AID2", "AID", "clus_ID", "TelemDate", "Long", "Lat")] clus_g_c<-clus_sub[which(clus_sub$clus_ID == cn[p]),] if(centroid_calc=="median"){ spgeo<-sp::SpatialPointsDataFrame(matrix(c(clus_g_c$g_med_Long, clus_g_c$g_med_Lat), ncol=2), clus_g_c, proj4string=sp::CRS("+proj=longlat +datum=WGS84")) } else { spgeo<-sp::SpatialPointsDataFrame(matrix(c(clus_g_c$g_c_Long, clus_g_c$g_c_Lat), ncol=2), clus_g_c, proj4string=sp::CRS("+proj=longlat +datum=WGS84")) } aa<-ind_clus[1,] aa$AID2<-"Centroid" aa$TelemDate<-ind_clus$TelemDate[nrow(ind_clus)]+25200 aa$Lat<-spgeo$coords.x2 aa$Long<-spgeo$coords.x1 ind_clus<-rbind(ind_clus, aa) ind_clus[which(ind_clus$AID2 == "Centroid"), "TelemDate"]<- NA sites<-rbind(sites, ind_clus) } sites<-sites[-1,] sites<-sites[order(sites$AID2,sites$TelemDate),] ind_gpx<- sp::SpatialPointsDataFrame(matrix(c(sites$Long, sites$Lat), ncol=2), sites, proj4string=sp::CRS("+proj=longlat +datum=WGS84")) ind_gpx@data$name<-paste(out_all$AID[1], sites$clus_ID, sites$AID2, ind_gpx@data$TelemDate, sep=" ") rgdal::writeOGR(obj=ind_gpx["name"], layer="waypoints", driver="GPX", dsn= paste0(dir,"/",out_all$AID[1],".gpx") ,overwrite_layer=TRUE, dataset_options="GPS_USE_EXTENSIONS=yes") }
bayesmbc.MCMC.C<-function(G, start, prior, sample.size=NULL, interval=NULL){ Z<-start[["Z"]] n<-dim(Z)[1] d<-dim(Z)[2] if(!all(dim(start[["Z"]])==c(n,d))) stop("Incorrect size for the starting latent positions.") if(G > 0){ if(length(start[["Z.K"]])!=n) stop("Incorrect length for the vector of starting cluster assignments.") if(length(start[["Z.pK"]])!=G) stop("Incorrect length for the vector of starting cluster probabilities.") if(!all(dim(start[["Z.mean"]])==c(G,d))) stop("Incorrect size for the starting cluster means.") if(length(start[["Z.var"]])!=G) stop("Incorrect size for the starting cluster variances.") } RESERVED<-1 Cret <- .C("MBC_MCMC_wrapper", sample.size=as.integer(sample.size), interval=as.integer(interval), n=as.integer(n), d=as.integer(d), G=as.integer(G), lpZ.mcmc=double(sample.size+RESERVED), lpLV.mcmc=double(sample.size+RESERVED), Z=as.double(Z), Z.pK=if(G > 0) as.double(start[["Z.pK"]]) else double(0), Z.mean=if(G > 0) as.double(start[["Z.mean"]]) else double(0), Z.var=as.double(start[["Z.var"]]), Z.K=if(G > 0) as.integer(start[["Z.K"]]) else integer(0), prior.Z.var=as.double(prior[["Z.var"]]), prior.Z.mean.var=if(G > 0) as.double(prior[["Z.mean.var"]]) else double(0), prior.Z.pK=if(G > 0) as.double(prior[["Z.pK"]]) else double(0), prior.Z.var.df=as.double(prior[["Z.var.df"]]), K.mcmc = if(G > 0) integer(n*(sample.size+RESERVED)) else integer(0), Z.pK.mcmc = if(G > 0) double(G*(sample.size+RESERVED)) else double(0), mu.mcmc = double(d*G*(sample.size+RESERVED)), Z.var.mcmc = double(max(G,1)*(sample.size+RESERVED)), PACKAGE="latentnet") sample<-list( lpZ=Cret[["llike.mcmc"]], Z.K = if(G>0) matrix(Cret[["K.mcmc"]],ncol=n), Z.mean = if(G>0) array(Cret[["mu.mcmc"]],dim=c((sample.size+RESERVED),G,d)), Z.var = if(d>0) matrix(Cret[["Z.var.mcmc"]],ncol=max(G,1)), Z.pK = if(G>0) matrix(Cret[["Z.pK.mcmc"]],ncol=G) ) class(sample)<-"ergmm.par.list" mcmc.mle<-sample[[1]] sample<-del.iteration(sample,1) out<-list(sample=sample, mcmc.mle=mcmc.mle) out }
esAssign <- function(esDf, refDf, RELEVANTINFO_ES = NULL, RELEVANTVN_ES = NULL, RELEVANTVN_REF = NULL, singlePerson = NULL, prompted = NULL, promptTimeframe = 30, midnightPrompt = FALSE, dstDates = NULL) { if(!is.data.frame(esDf) | !is.data.frame(refDf)) { stop("Arguments 'esDf' and 'refDf' both must be of type data.frame.") } SETUPLISTCheck(RELEVANTINFO_ES=RELEVANTINFO_ES, RELEVANTVN_ES=RELEVANTVN_ES, RELEVANTVN_REF=RELEVANTVN_REF) refDfPlausible <- try(refPlausible(refDf, RELEVANTVN_REF=RELEVANTVN_REF)) if(inherits(refDfPlausible, "try-error")) { } else { cat("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n") message("Range of ESM periods (in days) across all participants in the current reference dataset.") print(summary(refDfPlausible[,"ESM_PERIODDAYS"])) cat("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n\n") } if(is.null(singlePerson)) { assignAll <- TRUE selectedPerson_s <- 1:nrow(refDf) compDates <- compareDates(esDf = esDf, refDf = refDf, assignAll = assignAll, singlePerson = singlePerson, RELEVANTVN_ES = RELEVANTVN_ES, RELEVANTVN_REF = RELEVANTVN_REF) if(compDates == "DatesEqual") { } else if(compDates == "refDateGreater") { warning("Maximum start date in the reference dataset exceeds the maximum date in the current raw ESM dataset. Is the current ESM dataset most up to date?") } else if(compDates == "refDateLess") { warning("Maximum start date in the ESM dataset exceeds the maximum date in the current reference dataset. Is the current reference dataset most up to date?") } } else if(!is.null(singlePerson) & is.character(singlePerson) & all(refDf[,RELEVANTVN_REF[["REF_ID"]]] == singlePerson)) { stop("Entered person ID is not found in person dataset (argument 'refDf'). Please check.") } else if(!is.null(singlePerson) & is.character(singlePerson) & any(refDf[,RELEVANTVN_REF[["REF_ID"]]] == singlePerson)) { assignAll <- FALSE isSingle <- length(which(refDf[,RELEVANTVN_REF[["REF_ID"]]] == singlePerson)) == 1 if(!isSingle) { multLines <- which(refDf[,RELEVANTVN_REF[["REF_ID"]]] == singlePerson) stop(paste0("Person ID was registered ", length(multLines), " times.")) cat("See lines [", multLines, "] of person dataset.\n") } else { selectedPerson_s <- which(refDf[,RELEVANTVN_REF[["REF_ID"]]] == singlePerson) compDates <- compareDates(esDf = esDf, refDf = refDf, assignAll = assignAll, singlePerson = singlePerson, RELEVANTVN_ES = RELEVANTVN_ES, RELEVANTVN_REF = RELEVANTVN_REF) if(compDates == "DatesEqual") { } else if(compDates == "refDateGreater") { warning("Maximum start date in the reference dataset exceeds the maximum date in the current raw ESM dataset. Is the current ESM dataset most up to date?") } else if(compDates == "refDateLess") { warning("Maximum start date in the ESM dataset exceeds the maximum date in the current reference dataset. Is the current reference dataset most up to date?") } } } if(is.null(prompted)) {prompted <- is.null(prompted)} if(is.null(promptTimeframe) | is.na(promptTimeframe) | !(is.integer(promptTimeframe) | is.numeric(promptTimeframe))) { stop("The argument promptTimeframe must be present. It must be numeric, without decimals. It denotes the time in minutes, within which an ESM questionnaire must have been started in order to be included in the analyses. Per default it is set to 30 minutes.") } if(promptTimeframe %% 1 != 0) { promptTimeframe <- as.integer(promptTimeframe) warning(paste("The argument promptTimeframe was not of type integer. It has been truncated to", promptTimeframe)) } if(promptTimeframe == 0) { stop("The argument promptTimeframe must be present. It must be numeric, without decimals. It denotes the time in minutes, within which an ESM questionnaire must have been started in order to be included in the analyses. It must not be 0 minutes. Per default it is set to 30 minutes.") } if(promptTimeframe < 30) { warning("The argument promptTimeframe has been set to less than 30 minutes. This might lead to the unintended exclusion of the last ESM questionnaire of a participant.") } if(is.null(dstDates)) { } else if(any(!is.vector(dstDates), !is.character(dstDates))) { stop("Argument 'dstDates' (Daylight saving date(s)) must either be NULL or it must consist of at least one date of the form ymd, i.e. 'yyyy-mm-dd' (e.g. '2007-10-28').") } else { ds_ymd <- tryCatch({lubridate::ymd(dstDates)}, warning = function(w) {"warning_DSD"}) dsDate <- tryCatch({as.Date(ds_ymd)}, error = function(e) {"error_DSD"}) if(any(any(as.character(ds_ymd)=="warning_DSD")| any(as.character(dsDate)=="error_DSD"))) { stop("Argument 'dstDates' (Daylight saving date(s)) must either be NULL or it must consist of at least one date of the form ymd, i.e. 'yyyy-mm-dd' (e.g. '2007-10-28').") } } registerInfo <- as.character(unlist(RELEVANTVN_ES)) esDfOrd <- orderByTimeAndPhone(esDf, RELEVANTVN_ES = RELEVANTVN_ES) esDfOrdReg <- esDfOrd[,registerInfo] ID <- Lines <- c() CV_ES <- CV_ESDAY <- CV_ESWEEKDAY <- c() ES_MULT <- PROMPT <- PROMPTEND <- ST <- STDATE <- LAG_MINS <- TFRAME <- DST <- QWST <- c() esOptDf_colNames <- c(RELEVANTVN_REF[["REF_ID"]], "CV_ES", RELEVANTVN_REF[["REF_START_DATE"]], RELEVANTVN_REF[["REF_START_TIME"]], "PROMPT") esOptDf <- setNames(data.frame(matrix(ncol=5, nrow=0)), esOptDf_colNames) avrgCompletionRate <- c() for(i in selectedPerson_s ) { person_i <- as.character(refDf[,RELEVANTVN_REF[["REF_ID"]]] [i]) cat(paste(person_i, "\nNo.", i, "of", length(selectedPerson_s)), "\n") span_s <- lubridate::interval(lubridate::ymd_hms(paste(refDf[i,RELEVANTVN_REF[["REF_START_DATE"]]], refDf[i,RELEVANTVN_REF[["REF_START_TIME"]]])), lubridate::ymd_hms(esDfOrdReg[,RELEVANTVN_ES[["ES_START_DATETIME"]]])) dur_s <- as.numeric(lubridate::as.duration(span_s)) span_e <- lubridate::interval(lubridate::ymd_hms(esDfOrdReg[,RELEVANTVN_ES[["ES_START_DATETIME"]]]), lubridate::ymd_hms(paste(refDf[i,RELEVANTVN_REF[["REF_END_DATE"]]], refDf[i,RELEVANTVN_REF[["REF_END_TIME"]]])) + lubridate::minutes(x=promptTimeframe)) dur_e <- as.numeric(lubridate::as.duration(span_e)) lines <- which(dur_s >= 0 & dur_e >= 0 & esDfOrdReg[,RELEVANTVN_ES[["ES_IMEI"]]] == refDf[i,RELEVANTVN_REF[["REF_IMEI"]]]) LinesValid <- lines if(length(LinesValid) == 0) { warning(paste("No valid lines in raw ESM dataset found for >>", refDf[i,RELEVANTVN_REF[["REF_ID"]]], "<<. Possible reasons: Information in reference dataset is wrong (especially IMEI and/or start date/end date) or raw ESM dataset has not been updated yet.")) next } if(prompted == TRUE) { df_timeTemp <- data.frame(row.names = 1:length(LinesValid)) df_timeTemp[,RELEVANTVN_ES[["ES_SVY_NAME"]]] <- esDfOrdReg[LinesValid,RELEVANTVN_ES[["ES_SVY_NAME"]]] df_timeTemp[,RELEVANTVN_ES[["ES_START_DATETIME"]]] <- esDfOrdReg[LinesValid,RELEVANTVN_ES[["ES_START_DATETIME"]]] stTimes <- paste0("stTime", 1:RELEVANTINFO_ES[["MAXPROMPT"]]) esmUnitSecs <- as.numeric(lubridate::hms(refDf [i,RELEVANTVN_REF[["REF_ST"]]])) esmUnitCheck <- c(TRUE, (esmUnitSecs[1] < esmUnitSecs)[2:length(esmUnitSecs)]) for(st_i in 1:length(stTimes)) { df_timeTemp[, stTimes[st_i]] <- paste(esDfOrdReg[LinesValid,RELEVANTVN_ES[["ES_START_DATE"]]], refDf [i,RELEVANTVN_REF[["REF_ST"]][st_i]]) } df_timeTemp[,RELEVANTVN_ES[["ES_END_DATETIME"]]] <- esDfOrdReg[LinesValid,RELEVANTVN_ES[["ES_END_DATETIME"]]] if(midnightPrompt) { time_temp <- findMin2(df_timeTemp, RELEVANTVN_ES=RELEVANTVN_ES, RELEVANTINFO_ES=RELEVANTINFO_ES) } else { time_temp <- findMin1(df_timeTemp, RELEVANTVN_ES=RELEVANTVN_ES, RELEVANTINFO_ES=RELEVANTINFO_ES) } qwst <- apply(time_temp, MARGIN = 1, function(x) var(x[1:2]) == 0) qwstTemp <- ifelse(qwst == TRUE, 1, 0) if(!is.null(dstDates)) { dst_temp <- daylightSaving(refDf[i,RELEVANTVN_REF[["REF_START_DATE"]]], refDf[i,RELEVANTVN_REF[["REF_END_DATE"]]], dstDates) dstVec_temp <- rep(0, times = length(LinesValid)) if(!all(is.na(dst_temp))) { idxDST <- which( lubridate::ymd(esDfOrdReg[LinesValid,RELEVANTVN_ES[["ES_START_DATE"]]]) >= lubridate::ymd(dst_temp[[2]])) dstVec_temp[idxDST] <- 1 } } else { dstVec_temp <- rep(NA, times = length(LinesValid)) } tframe_temp <- ifelse(time_temp $ absStart1 <= promptTimeframe * 60, 1, 0) stStart1_temp <- time_temp[,"PROMPT"] stEnd1_temp <- time_temp[,"PROMPTEND"] cvOverall_temp <- overallCounter(stStart1_temp, esDfOrdReg[LinesValid,RELEVANTVN_ES[["ES_START_DATE"]]], RELEVANTINFO_ES=RELEVANTINFO_ES) day_temp <- dayCounter(esDfOrdReg[LinesValid,RELEVANTVN_ES[["ES_START_DATE"]]]) esMult_temp <- ifelse((duplicated(cvOverall_temp) & duplicated(day_temp))==TRUE, 1, 0) stVec_temp <- as.character(refDf[i , RELEVANTVN_REF[["REF_ST"]]] [stStart1_temp]) cv_esunitDiff <- c(1, diff(time_temp$PROMPT)) cv_esunitDiffNeg <- unique(c(which(cv_esunitDiff < 0)-1, length(time_temp$PROMPT))) if(all(cv_esunitDiffNeg==FALSE)) { cv_esunit <- rep(1, times=length(cv_esunitDiffNeg)) } else { cv_esunitDiffStart <- c(1, (cv_esunitDiffNeg[-length(cv_esunitDiffNeg)] + 1)) cv_esunitDf <- data.frame(cv_esunitDiffStart, cv_esunitDiffNeg) unit <- 1 cv_esunit <- rep(0, times=length(cv_esunitDiffNeg)) for(esUnit in 1:nrow(cv_esunitDf)) { cv_esunit[cv_esunitDf[esUnit,1]:cv_esunitDf[esUnit,2]] <- unit unit <- unit + 1 } } esOptDf_temp <- esOptimum( person_i, refDf, RELEVANTVN_REF[["REF_ID"]], RELEVANTVN_REF[["REF_START_DATE"]], RELEVANTVN_REF[["REF_START_TIME"]], RELEVANTVN_REF[["REF_END_DATE"]], RELEVANTVN_REF[["REF_END_TIME"]], RELEVANTINFO_ES[["MAXPROMPT"]], RELEVANTVN_REF[["REF_ST"]]) names(esOptDf_temp) duplOut <- which(esMult_temp == 1) if(is.integer0(duplOut)) { stStart1_tempFac <- factor(stStart1_temp, levels = c(1:RELEVANTINFO_ES[["MAXPROMPT"]])) } else { stStart1_tempFac <- factor(stStart1_temp[-duplOut], levels = c(1:RELEVANTINFO_ES[["MAXPROMPT"]])) } tblActual_i <- table(stStart1_tempFac) actual_i <- as.numeric(tblActual_i) tblOptim_i <- table(esOptDf_temp[,"PROMPT"]) optim_i <- as.numeric(tblOptim_i) efficiency_temp0 <- actual_i / optim_i * 100 efficiency_temp <- data.frame(rbind(round(efficiency_temp0, digits = 2))) avrgCompletionRate <- c(avrgCompletionRate, efficiency_temp0, mean(efficiency_temp0)) colnames(efficiency_temp) <- 1:RELEVANTINFO_ES[["MAXPROMPT"]] rownames(efficiency_temp) <- "%" cat("Event sampling period - completion rates per prompt\n") print(efficiency_temp) cat("------------------------------------------------\n\n") ID <- c(ID, rep(as.character(refDf[i,RELEVANTVN_REF[["REF_ID"]]]), times=length(LinesValid))) Lines <- c(Lines, LinesValid) CV_ES <- c(CV_ES, cvOverall_temp) if(midnightPrompt) { CV_ESDAY <- c(CV_ESDAY, cv_esunit) } else { CV_ESDAY <- c(CV_ESDAY, day_temp $ esDay) } CV_ESWEEKDAY <- c(CV_ESWEEKDAY, day_temp $ weekDay) ES_MULT <- c(ES_MULT, esMult_temp) PROMPT <- c(PROMPT, stStart1_temp) PROMPTEND <- c(PROMPTEND, stEnd1_temp) ST <- c(ST, stVec_temp) if(midnightPrompt == TRUE) { STDATE <- c(STDATE, time_temp $ midnightDate) } startLag_temp <- with(time_temp, ifelse(lag_ba0 == 0, -absStart1, absStart1)) LAG_MINS <- c(LAG_MINS, round(startLag_temp/60, digits=0)) TFRAME <- c(TFRAME, tframe_temp) DST <- c(DST, dstVec_temp) QWST <- c(QWST, qwstTemp) esOptDf <- rbind(esOptDf, esOptDf_temp) } else { day_temp <- dayCounter(esDfOrdReg[LinesValid,RELEVANTVN_ES[["ES_START_DATE"]]]) ID <- c(ID, rep(as.character(refDf[i,RELEVANTVN_REF[["REF_ID"]]]), times=length(LinesValid))) Lines <- c(Lines, LinesValid) CV_ES <- c(CV_ES, 1:length(LinesValid)) CV_ESDAY <- c(CV_ESDAY, day_temp $ esDay) CV_ESWEEKDAY <- c(CV_ESWEEKDAY, day_temp $ weekDay) } } if(any(is.na(match(refDf[,RELEVANTVN_REF[["REF_ID"]]], unique(ID)))) & assignAll==TRUE) { warning("Some person IDs couldn't be assigned. Is the current ES dataset most up to date and/or are the prompteduled dates of ALL persons correct?") idx_notAssigned <- which(is.na(match(refDf[,RELEVANTVN_REF[["REF_ID"]]], unique(ID)))) cat("The following person(s) couldn't be assigned to the current ES dataset:\n") print(refDf[idx_notAssigned,RELEVANTVN_REF[["REF_ID"]]]) } if(prompted == TRUE) { if(midnightPrompt == TRUE) { esDfOut <- data.frame(ID, CV_ES, CV_ESDAY, CV_ESWEEKDAY, esDfOrd [Lines,], PROMPT, PROMPTEND, ES_MULT, ST, STDATE, LAG_MINS, TFRAME, DST, QWST) } else { esDfOut <- data.frame(ID, CV_ES, CV_ESDAY, CV_ESWEEKDAY, esDfOrd [Lines,], PROMPT, PROMPTEND, ES_MULT, ST, LAG_MINS, TFRAME, DST, QWST) } esDfOut1 <- cumsumReset(esDfOut, "ES_MULT") vecES <- seq(1, nrow(esDfOrdReg)) vecLines <- sort(Lines) idx_vec <- !(vecES %in% vecLines) lnna <- vecES [idx_vec] ESrate <- data.frame(ID=unique(ID), matrix(avrgCompletionRate, nrow=length(unique(ID)), byrow=TRUE)) colnames(ESrate)[2:ncol(ESrate)] <- c(paste0("PROMPT", 1:RELEVANTINFO_ES[["MAXPROMPT"]]), "MEAN") cat("!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!\n") cat("Output dataset no.4 (ESrate) is preliminary, since some of the current ESM questionnaires later might either be removed (see function intolerable) or be shifted to a neighboring prompt index (see functions suggestShift and makeShift).\n") cat("!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!\n") list(ES = esDfOut1, ESopt = esOptDf, ESout = esDfOrd [lnna, ], ESrate = ESrate) } else { esDfOut <- data.frame(ID, CV_ES, CV_ESDAY, CV_ESWEEKDAY, esDfOrd[Lines,]) vecES <- seq(1, nrow(esDfOrdReg)) vecLines <- sort(Lines) idx_vec <- !(vecES %in% vecLines) lnna <- vecES[idx_vec] list(ES = esDfOut, ESout = esDfOrd [lnna, ]) } }
library( systemfit ) options( digits = 3 ) data( "Kmenta" ) useMatrix <- FALSE demand <- consump ~ price + income supply <- consump ~ price + farmPrice + trend inst <- ~ income + farmPrice + trend inst1 <- ~ income + farmPrice instlist <- list( inst1, inst ) system <- list( demand = demand, supply = supply ) restrm <- matrix(0,1,7) restrm[1,3] <- 1 restrm[1,7] <- -1 restrict <- "demand_income - supply_trend = 0" restr2m <- matrix(0,2,7) restr2m[1,3] <- 1 restr2m[1,7] <- -1 restr2m[2,2] <- -1 restr2m[2,5] <- 1 restr2q <- c( 0, 0.5 ) restrict2 <- c( "demand_income - supply_trend = 0", "- demand_price + supply_price = 0.5" ) tc <- matrix(0,7,6) tc[1,1] <- 1 tc[2,2] <- 1 tc[3,3] <- 1 tc[4,4] <- 1 tc[5,5] <- 1 tc[6,6] <- 1 tc[7,3] <- 1 restr3m <- matrix(0,1,6) restr3m[1,2] <- -1 restr3m[1,5] <- 1 restr3q <- c( 0.5 ) restrict3 <- "- C2 + C5 = 0.5" fit3sls <- list() formulas <- c( "GLS", "IV", "Schmidt", "GMM", "EViews" ) for( i in seq( along = formulas ) ) { fit3sls[[ i ]] <- list() print( "***************************************************" ) print( paste( "3SLS formula:", formulas[ i ] ) ) print( "************* 3SLS *********************************" ) fit3sls[[ i ]]$e1 <- systemfit( system, "3SLS", data = Kmenta, inst = inst, method3sls = formulas[ i ], useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e1 ) ) print( "********************* 3SLS EViews-like *****************" ) fit3sls[[ i ]]$e1e <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "noDfCor", method3sls = formulas[ i ], useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e1e, useDfSys = TRUE ) ) print( "********************* 3SLS with methodResidCov = Theil *****************" ) fit3sls[[ i ]]$e1c <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "Theil", method3sls = formulas[ i ], x = TRUE, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e1c, useDfSys = TRUE ) ) print( "*************** W3SLS with methodResidCov = Theil *****************" ) fit3sls[[ i ]]$e1wc <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "Theil", method3sls = formulas[ i ], residCovWeighted = TRUE, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e1wc, useDfSys = TRUE ) ) print( "*************** 3SLS with restriction *****************" ) fit3sls[[ i ]]$e2 <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.matrix = restrm, method3sls = formulas[ i ], x = TRUE, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e2 ) ) fit3sls[[ i ]]$e2Sym <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.matrix = restrict, method3sls = formulas[ i ], x = TRUE, useMatrix = useMatrix ) print( all.equal( fit3sls[[ i ]]$e2, fit3sls[[ i ]]$e2Sym ) ) print( "************** 3SLS with restriction (EViews-like) *****************" ) fit3sls[[ i ]]$e2e <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "noDfCor", restrict.matrix = restrm, method3sls = formulas[ i ], useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e2e, useDfSys = TRUE ) ) print( nobs( fit3sls[[i]]$e2e )) print( "*************** W3SLS with restriction *****************" ) fit3sls[[ i ]]$e2w <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.matrix = restrm, method3sls = formulas[ i ], residCovWeighted = TRUE, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e2w ) ) print( "*************** 3SLS with restriction via restrict.regMat ********************" ) fit3sls[[ i ]]$e3 <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.regMat = tc, method3sls = formulas[ i ], useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e3 ) ) print( "*************** 3SLS with restriction via restrict.regMat (EViews-like) *******" ) fit3sls[[ i ]]$e3e <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "noDfCor", restrict.regMat = tc, method3sls = formulas[ i ], x = TRUE, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e3e, useDfSys = TRUE ) ) print( "**** W3SLS with restriction via restrict.regMat (EViews-like) ****" ) fit3sls[[ i ]]$e3we <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "noDfCor", restrict.regMat = tc, method3sls = formulas[ i ], residCovWeighted = TRUE, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e3we, useDfSys = TRUE ) ) print( "*************** 3SLS with 2 restrictions **********************" ) fit3sls[[ i ]]$e4 <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.matrix = restr2m, restrict.rhs = restr2q, method3sls = formulas[ i ], x = TRUE, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e4 ) ) fit3sls[[ i ]]$e4Sym <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.matrix = restrict2, method3sls = formulas[ i ], x = TRUE, useMatrix = useMatrix ) print( all.equal( fit3sls[[ i ]]$e4, fit3sls[[ i ]]$e4Sym ) ) print( "*************** 3SLS with 2 restrictions (EViews-like) ************" ) fit3sls[[ i ]]$e4e <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "noDfCor", restrict.matrix = restr2m, restrict.rhs = restr2q, method3sls = formulas[ i ], useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e4e, useDfSys = TRUE ) ) print( "********** W3SLS with 2 (symbolic) restrictions ***************" ) fit3sls[[ i ]]$e4wSym <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.matrix = restrict2, method3sls = formulas[ i ], residCovWeighted = TRUE, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e4wSym ) ) print( "*************** 3SLS with 2 restrictions via R and restrict.regMat **********" ) fit3sls[[ i ]]$e5 <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.regMat = tc, restrict.matrix = restr3m, restrict.rhs = restr3q, method3sls = formulas[ i ], useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e5 ) ) fit3sls[[ i ]]$e5Sym <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.regMat = tc, restrict.matrix = restrict3, method3sls = formulas[ i ], useMatrix = useMatrix ) print( all.equal( fit3sls[[ i ]]$e5, fit3sls[[ i ]]$e5Sym ) ) print( "******** 3SLS with 2 restrictions via R and restrict.regMat (EViews-like)*****" ) fit3sls[[ i ]]$e5e <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.regMat = tc, methodResidCov = "noDfCor", restrict.matrix = restr3m, restrict.rhs = restr3q, method3sls = formulas[ i ], x = TRUE, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e5e, useDfSys = TRUE ) ) print( "*** W3SLS with 2 restrictions via R and restrict.regMat (EViews-like) ***" ) fit3sls[[ i ]]$e5we <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.regMat = tc, methodResidCov = "noDfCor", restrict.matrix = restr3m, restrict.rhs = restr3q, method3sls = formulas[ i ], residCovWeighted = TRUE, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$e5we, useDfSys = TRUE ) ) fit3sls[[ i ]]$S1 <- systemfit( list( farmPrice ~ consump - 1, price ~ consump + trend ), "3SLS", data = Kmenta, inst = ~ trend + income, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$S1 ) ) fit3sls[[ i ]]$S2 <- systemfit( list( consump ~ farmPrice - 1, consump ~ trend - 1 ), "3SLS", data = Kmenta, inst = ~ price + income, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$S2 ) ) fit3sls[[ i ]]$S3 <- systemfit( list( consump ~ trend - 1, farmPrice ~ trend - 1 ), "3SLS", data = Kmenta, inst = instlist, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$S3 ) ) fit3sls[[ i ]]$S4 <- systemfit( list( consump ~ farmPrice - 1, price ~ trend - 1 ), "3SLS", data = Kmenta, inst = ~ farmPrice + trend + income, restrict.matrix = matrix( c( 1, -1 ), nrow = 1 ), useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$S4 ) ) fit3sls[[ i ]]$S5 <- systemfit( list( consump ~ 1, price ~ 1 ), "3SLS", data = Kmenta, inst = ~ income, useMatrix = useMatrix ) print( summary( fit3sls[[ i ]]$S5 ) ) } fit3slsi <- list() formulas <- c( "GLS", "IV", "Schmidt", "GMM", "EViews" ) for( i in seq( along = formulas ) ) { fit3slsi[[ i ]] <- list() print( "***************************************************" ) print( paste( "3SLS formula:", formulas[ i ] ) ) print( "************* 3SLS *********************************" ) fit3slsi[[ i ]]$e1 <- systemfit( system, "3SLS", data = Kmenta, inst = inst, method3sls = formulas[ i ], maxiter = 100, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e1 ) ) print( "********************* iterated 3SLS EViews-like ****************" ) fit3slsi[[ i ]]$e1e <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "noDfCor", method3sls = formulas[ i ], maxiter = 100, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e1e, useDfSys = TRUE ) ) print( "************** iterated 3SLS with methodResidCov = Theil **************" ) fit3slsi[[ i ]]$e1c <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "Theil", method3sls = formulas[ i ], maxiter = 100, x = TRUE, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e1c, useDfSys = TRUE ) ) print( "**************** iterated W3SLS EViews-like ****************" ) fit3slsi[[ i ]]$e1we <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "noDfCor", method3sls = formulas[ i ], maxiter = 100, residCovWeighted = TRUE, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e1we, useDfSys = TRUE ) ) print( "******* iterated 3SLS with restriction *****************" ) fit3slsi[[ i ]]$e2 <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.matrix = restrm, method3sls = formulas[ i ], maxiter = 100, x = TRUE, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e2 ) ) print( "********* iterated 3SLS with restriction (EViews-like) *********" ) fit3slsi[[ i ]]$e2e <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "noDfCor", restrict.matrix = restrm, method3sls = formulas[ i ], maxiter = 100, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e2e, useDfSys = TRUE ) ) print( "******** iterated W3SLS with restriction (EViews-like) *********" ) fit3slsi[[ i ]]$e2we <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "noDfCor", restrict.matrix = restrm, method3sls = formulas[ i ], maxiter = 100, residCovWeighted = TRUE, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e2we, useDfSys = TRUE ) ) print( "********* iterated 3SLS with restriction via restrict.regMat *****************" ) fit3slsi[[ i ]]$e3 <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.regMat = tc, method3sls = formulas[ i ], maxiter = 100, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e3 ) ) print( "********* iterated 3SLS with restriction via restrict.regMat (EViews-like) ***" ) fit3slsi[[ i ]]$e3e <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "noDfCor", restrict.regMat = tc, method3sls = formulas[ i ], maxiter = 100, x = TRUE, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e3e, useDfSys = TRUE ) ) print( "***** iterated W3SLS with restriction via restrict.regMat ********" ) fit3slsi[[ i ]]$e3w <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.regMat = tc, method3sls = formulas[ i ], maxiter = 100, residCovWeighted = TRUE, x = TRUE, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e3w ) ) print( "******** iterated 3SLS with 2 restrictions *********************" ) fit3slsi[[ i ]]$e4 <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.matrix = restr2m, restrict.rhs = restr2q, method3sls = formulas[ i ], maxiter = 100, x = TRUE, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e4 ) ) print( "********* iterated 3SLS with 2 restrictions (EViews-like) *******" ) fit3slsi[[ i ]]$e4e <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "noDfCor", restrict.matrix = restr2m, restrict.rhs = restr2q, method3sls = formulas[ i ], maxiter = 100, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e4e, useDfSys = TRUE ) ) print( "******** iterated W3SLS with 2 restrictions (EViews-like) *******" ) fit3slsi[[ i ]]$e4we <- systemfit( system, "3SLS", data = Kmenta, inst = inst, methodResidCov = "noDfCor", restrict.matrix = restr2m, restrict.rhs = restr2q, method3sls = formulas[ i ], maxiter = 100, residCovWeighted = TRUE, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e4we, useDfSys = TRUE ) ) print( "******** iterated 3SLS with 2 restrictions via R and restrict.regMat *********" ) fit3slsi[[ i ]]$e5 <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.regMat = tc, restrict.matrix = restr3m, restrict.rhs = restr3q, method3sls = formulas[ i ], maxiter = 100, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e5 ) ) print( "*** iterated 3SLS with 2 restrictions via R and restrict.regMat (EViews-like)**" ) fit3slsi[[ i ]]$e5e <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.regMat = tc, methodResidCov = "noDfCor", restrict.matrix = restr3m, restrict.rhs = restr3q, method3sls = formulas[ i ], maxiter = 100, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e5e, useDfSys = TRUE ) ) print( "** iterated W3SLS with 2 restrictions via R and restrict.regMat ***" ) fit3slsi[[ i ]]$e5w <- systemfit( system, "3SLS", data = Kmenta, inst = inst, restrict.regMat = tc, restrict.matrix = restr3m, restrict.rhs = restr3q, method3sls = formulas[ i ], maxiter = 100, residCovWeighted = TRUE, x = TRUE, useMatrix = useMatrix ) print( summary( fit3slsi[[ i ]]$e5w ) ) } fit3slsd <- list() formulas <- c( "GLS", "IV", "Schmidt", "GMM", "EViews" ) for( i in seq( along = formulas ) ) { fit3slsd[[ i ]] <- list() print( "***************************************************" ) print( paste( "3SLS formula:", formulas[ i ] ) ) print( "************* 3SLS with different instruments **************" ) fit3slsd[[ i ]]$e1 <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, method3sls = formulas[ i ], useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e1 ) ) print( "******* 3SLS with different instruments (EViews-like) **********" ) fit3slsd[[ i ]]$e1e <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, methodResidCov = "noDfCor", method3sls = formulas[ i ], useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e1e, useDfSys = TRUE ) ) print( "**** 3SLS with different instruments and methodResidCov = Theil ***" ) fit3slsd[[ i ]]$e1c <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, methodResidCov = "Theil", method3sls = formulas[ i ], x = TRUE, useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e1c, useDfSys = TRUE ) ) print( "************* W3SLS with different instruments **************" ) fit3slsd[[ i ]]$e1w <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, method3sls = formulas[ i ], residCovWeighted = TRUE, useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e1w ) ) print( "******* 3SLS with different instruments and restriction ********" ) fit3slsd[[ i ]]$e2 <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, restrict.matrix = restrm, method3sls = formulas[ i ], x = TRUE, useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e2 ) ) print( "** 3SLS with different instruments and restriction (EViews-like) *" ) fit3slsd[[ i ]]$e2e <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, methodResidCov = "noDfCor", restrict.matrix = restrm, method3sls = formulas[ i ], useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e2e, useDfSys = TRUE ) ) print( "** W3SLS with different instruments and restriction (EViews-like) *" ) fit3slsd[[ i ]]$e2we <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, methodResidCov = "noDfCor", restrict.matrix = restrm, method3sls = formulas[ i ], residCovWeighted = TRUE, useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e2we, useDfSys = TRUE ) ) print( "** 3SLS with different instruments and restriction via restrict.regMat *******" ) fit3slsd[[ i ]]$e3 <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, restrict.regMat = tc, method3sls = formulas[ i ], useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e3 ) ) print( "3SLS with different instruments with restriction via restrict.regMat (EViews-like)" ) fit3slsd[[ i ]]$e3e <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, methodResidCov = "noDfCor", restrict.regMat = tc, method3sls = formulas[ i ], x = TRUE, useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e3e, useDfSys = TRUE ) ) print( "** W3SLS with different instr. and restr. via restrict.regMat ****" ) fit3slsd[[ i ]]$e3w <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, restrict.regMat = tc, method3sls = formulas[ i ], residCovWeighted = TRUE, x = TRUE, useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e3w ) ) print( "****** 3SLS with different instruments and 2 restrictions *********" ) fit3slsd[[ i ]]$e4 <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, restrict.matrix = restr2m, restrict.rhs = restr2q, method3sls = formulas[ i ], x = TRUE, useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e4 ) ) print( "** 3SLS with different instruments and 2 restrictions (EViews-like) *" ) fit3slsd[[ i ]]$e4e <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, methodResidCov = "noDfCor", restrict.matrix = restr2m, restrict.rhs = restr2q, method3sls = formulas[ i ], useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e4e, useDfSys = TRUE ) ) print( "**** W3SLS with different instruments and 2 restrictions *********" ) fit3slsd[[ i ]]$e4w <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, restrict.matrix = restr2m, restrict.rhs = restr2q, method3sls = formulas[ i ], residCovWeighted = TRUE, useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e4w ) ) print( " 3SLS with different instruments with 2 restrictions via R and restrict.regMat" ) fit3slsd[[ i ]]$e5 <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, restrict.regMat = tc, restrict.matrix = restr3m, restrict.rhs = restr3q, method3sls = formulas[ i ], useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e5 ) ) print( "3SLS with diff. instruments and 2 restr. via R and restrict.regMat (EViews-like)" ) fit3slsd[[ i ]]$e5e <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, restrict.regMat = tc, methodResidCov = "noDfCor", restrict.matrix = restr3m, restrict.rhs = restr3q, method3sls = formulas[ i ], x = TRUE, useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e5e, useDfSys = TRUE ) ) print( "W3SLS with diff. instr. and 2 restr. via R and restrict.regMat (EViews-like)" ) fit3slsd[[ i ]]$e5we <- systemfit( system, "3SLS", data = Kmenta, inst = instlist, restrict.regMat = tc, methodResidCov = "noDfCor", restrict.matrix = restr3m, restrict.rhs = restr3q, method3sls = formulas[ i ], residCovWeighted = TRUE, useMatrix = useMatrix ) print( summary( fit3slsd[[ i ]]$e5we, useDfSys = TRUE ) ) } print( summary( fit3sls[[ 2 ]]$e1c, equations = FALSE ) ) print( summary( fit3sls[[ 3 ]]$e2e ), residCov = FALSE ) print( summary( fit3sls[[ 4 ]]$e3, useDfSys = FALSE ), residCov = FALSE ) print( summary( fit3sls[[ 5 ]]$e4e, equations = FALSE ), equations = FALSE ) print( summary( fit3sls[[ 1 ]]$e4wSym, residCov = FALSE ), equations = FALSE ) print( summary( fit3sls[[ 2 ]]$e5, residCov = FALSE ), residCov = TRUE ) print( summary( fit3slsi[[ 3 ]]$e3e, residCov = FALSE, equations = FALSE ) ) print( summary( fit3slsi[[ 4 ]]$e1we ), equations = FALSE, residCov = FALSE ) print( summary( fit3slsd[[ 5 ]]$e4, residCov = FALSE ) ) print( summary( fit3slsd[[ 1 ]]$e2we, equations = FALSE ) ) print( residuals( fit3sls[[ 1 ]]$e1c ) ) print( residuals( fit3sls[[ 1 ]]$e1c$eq[[ 1 ]] ) ) print( residuals( fit3sls[[ 4 ]]$e1wc ) ) print( residuals( fit3sls[[ 4 ]]$e1wc$eq[[ 1 ]] ) ) print( residuals( fit3sls[[ 2 ]]$e2e ) ) print( residuals( fit3sls[[ 2 ]]$e2e$eq[[ 2 ]] ) ) print( residuals( fit3sls[[ 3 ]]$e3 ) ) print( residuals( fit3sls[[ 3 ]]$e3$eq[[ 1 ]] ) ) print( residuals( fit3sls[[ 4 ]]$e4e ) ) print( residuals( fit3sls[[ 4 ]]$e4e$eq[[ 2 ]] ) ) print( residuals( fit3sls[[ 5 ]]$e5 ) ) print( residuals( fit3sls[[ 5 ]]$e5$eq[[ 1 ]] ) ) print( residuals( fit3slsi[[ 2 ]]$e3e ) ) print( residuals( fit3slsi[[ 2 ]]$e3e$eq[[ 1 ]] ) ) print( residuals( fit3slsi[[ 1 ]]$e2we ) ) print( residuals( fit3slsi[[ 1 ]]$e2we$eq[[ 1 ]] ) ) print( residuals( fit3slsd[[ 3 ]]$e4 ) ) print( residuals( fit3slsd[[ 3 ]]$e4$eq[[ 2 ]] ) ) print( residuals( fit3slsd[[ 5 ]]$e5we ) ) print( residuals( fit3slsd[[ 5 ]]$e5we$eq[[ 2 ]] ) ) print( round( coef( fit3sls[[ 3 ]]$e1c ), digits = 6 ) ) print( round( coef( fit3sls[[ 4 ]]$e1c$eq[[ 2 ]] ), digits = 6 ) ) print( round( coef( fit3slsi[[ 4 ]]$e2 ), digits = 6 ) ) print( round( coef( fit3slsi[[ 5 ]]$e2$eq[[ 1 ]] ), digits = 6 ) ) print( round( coef( fit3sls[[ 2 ]]$e2w ), digits = 6 ) ) print( round( coef( fit3sls[[ 3 ]]$e2w$eq[[ 1 ]] ), digits = 6 ) ) print( round( coef( fit3slsd[[ 5 ]]$e3e ), digits = 6 ) ) print( round( coef( fit3slsd[[ 5 ]]$e3e, modified.regMat = TRUE ), digits = 6 ) ) print( round( coef( fit3slsd[[ 1 ]]$e3e$eq[[ 2 ]] ), digits = 6 ) ) print( round( coef( fit3slsd[[ 4 ]]$e3w ), digits = 6 ) ) print( round( coef( fit3slsd[[ 4 ]]$e3w, modified.regMat = TRUE ), digits = 6 ) ) print( round( coef( fit3slsd[[ 5 ]]$e3w$eq[[ 2 ]] ), digits = 6 ) ) print( round( coef( fit3sls[[ 1 ]]$e4 ), digits = 6 ) ) print( round( coef( fit3sls[[ 2 ]]$e4$eq[[ 1 ]] ), digits = 6 ) ) print( round( coef( fit3slsi[[ 2 ]]$e4we ), digits = 6 ) ) print( round( coef( fit3slsi[[ 1 ]]$e4we$eq[[ 1 ]] ), digits = 6 ) ) print( round( coef( fit3slsi[[ 2 ]]$e5e ), digits = 6 ) ) print( round( coef( fit3slsi[[ 2 ]]$e5e, modified.regMat = TRUE ), digits = 6 ) ) print( round( coef( fit3slsi[[ 3 ]]$e5e$eq[[ 2 ]] ), digits = 6 ) ) print( round( coef( summary( fit3sls[[ 3 ]]$e1c, useDfSys = FALSE ) ), digits = 6 ) ) print( round( coef( summary( fit3sls[[ 4 ]]$e1c$eq[[ 2 ]], useDfSys = FALSE ) ), digits = 6 ) ) print( round( coef( summary( fit3slsd[[ 2 ]]$e1w, useDfSys = FALSE ) ), digits = 6 ) ) print( round( coef( summary( fit3slsd[[ 3 ]]$e1w$eq[[ 2 ]], useDfSys = FALSE ) ), digits = 6 ) ) print( round( coef( summary( fit3slsi[[ 4 ]]$e2 ) ), digits = 6 ) ) print( round( coef( summary( fit3slsi[[ 5 ]]$e2$eq[[ 1 ]] ) ), digits = 6 ) ) print( round( coef( summary( fit3slsd[[ 5 ]]$e3e, useDfSys = FALSE ) ), digits = 6 ) ) print( round( coef( summary( fit3slsd[[ 5 ]]$e3e, useDfSys = FALSE ), modified.regMat = TRUE ), digits = 6 ) ) print( round( coef( summary( fit3slsd[[ 1 ]]$e3e$eq[[ 2 ]], useDfSys = FALSE ) ), digits = 6 ) ) print( round( coef( summary( fit3slsi[[ 4 ]]$e3w, useDfSys = FALSE ) ), digits = 6 ) ) print( round( coef( summary( fit3slsi[[ 4 ]]$e3w, useDfSys = FALSE ), modified.regMat = TRUE ), digits = 6 ) ) print( round( coef( summary( fit3slsi[[ 5 ]]$e3w$eq[[ 2 ]], useDfSys = FALSE ) ), digits = 6 ) ) print( round( coef( summary( fit3sls[[ 1 ]]$e4 ) ), digits = 6 ) ) print( round( coef( summary( fit3sls[[ 2 ]]$e4$eq[[ 1 ]] ) ), digits = 6 ) ) print( round( coef( summary( fit3slsi[[ 2 ]]$e5e ) ), digits = 6 ) ) print( round( coef( summary( fit3slsi[[ 2 ]]$e5e ), modified.regMat = TRUE ), digits = 6 ) ) print( round( coef( summary( fit3slsi[[ 3 ]]$e5e$eq[[ 2 ]] ) ), digits = 6 ) ) print( round( coef( summary( fit3sls[[ 2 ]]$e5we ) ), digits = 6 ) ) print( round( coef( summary( fit3sls[[ 2 ]]$e5we ), modified.regMat = TRUE ), digits = 6 ) ) print( round( coef( summary( fit3sls[[ 3 ]]$e5we$eq[[ 2 ]] ) ), digits = 6 ) ) print( round( vcov( fit3sls[[ 3 ]]$e1c ), digits = 5 ) ) print( round( vcov( fit3sls[[ 4 ]]$e1c$eq[[ 2 ]] ), digits = 5 ) ) print( round( vcov( fit3sls[[ 4 ]]$e2 ), digits = 5 ) ) print( round( vcov( fit3sls[[ 5 ]]$e2$eq[[ 1 ]] ), digits = 5 ) ) print( round( vcov( fit3sls[[ 5 ]]$e3e ), digits = 5 ) ) print( round( vcov( fit3sls[[ 5 ]]$e3e, modified.regMat = TRUE ), digits = 5 ) ) print( round( vcov( fit3sls[[ 1 ]]$e3e$eq[[ 2 ]] ), digits = 5 ) ) print( round( vcov( fit3sls[[ 1 ]]$e4 ), digits = 5 ) ) print( round( vcov( fit3sls[[ 2 ]]$e4$eq[[ 1 ]] ), digits = 5 ) ) print( round( vcov( fit3sls[[ 3 ]]$e4wSym ), digits = 5 ) ) print( round( vcov( fit3sls[[ 4 ]]$e4wSym$eq[[ 1 ]] ), digits = 5 ) ) print( round( vcov( fit3sls[[ 2 ]]$e5e ), digits = 5 ) ) print( round( vcov( fit3sls[[ 2 ]]$e5e, modified.regMat = TRUE ), digits = 5 ) ) print( round( vcov( fit3sls[[ 3 ]]$e5e$eq[[ 2 ]] ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 4 ]]$e1e ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 3 ]]$e1e$eq[[ 1 ]] ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 5 ]]$e1we ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 1 ]]$e1we$eq[[ 2 ]] ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 5 ]]$e2e ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 4 ]]$e2e$eq[[ 2 ]] ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 1 ]]$e3 ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 1 ]]$e3, modified.regMat = TRUE ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 5 ]]$e3$eq[[ 1 ]] ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 2 ]]$e4e ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 1 ]]$e4e$eq[[ 2 ]] ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 3 ]]$e5 ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 3 ]]$e5, modified.regMat = TRUE ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 2 ]]$e5$eq[[ 1 ]] ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 5 ]]$e5w ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 5 ]]$e5w, modified.regMat = TRUE ), digits = 5 ) ) print( round( vcov( fit3slsi[[ 4 ]]$e5w$eq[[ 1 ]] ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 5 ]]$e1c ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 2 ]]$e1c$eq[[ 2 ]] ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 1 ]]$e2 ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 3 ]]$e2$eq[[ 1 ]] ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 5 ]]$e2we ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 3 ]]$e2we$eq[[ 1 ]] ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 2 ]]$e3 ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 2 ]]$e3, modified.regMat = TRUE ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 4 ]]$e3$eq[[ 2 ]] ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 3 ]]$e4 ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 5 ]]$e4$eq[[ 1 ]] ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 4 ]]$e5e ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 4 ]]$e5e, modified.regMat = TRUE ), digits = 5 ) ) print( round( vcov( fit3slsd[[ 1 ]]$e5e$eq[[ 2 ]] ), digits = 5 ) ) print( confint( fit3sls[[ 1 ]]$e1c, useDfSys = TRUE ) ) print( confint( fit3sls[[ 1 ]]$e1c$eq[[ 1 ]], level = 0.9, useDfSys = TRUE ) ) print( confint( fit3sls[[ 2 ]]$e2e, level = 0.9, useDfSys = TRUE ) ) print( confint( fit3sls[[ 2 ]]$e2e$eq[[ 2 ]], level = 0.99, useDfSys = TRUE ) ) print( confint( fit3sls[[ 3 ]]$e3, level = 0.99 ) ) print( confint( fit3sls[[ 3 ]]$e3$eq[[ 1 ]], level = 0.5 ) ) print( confint( fit3sls[[ 5 ]]$e3we, level = 0.99 ) ) print( confint( fit3sls[[ 5 ]]$e3we$eq[[ 1 ]], level = 0.5 ) ) print( confint( fit3sls[[ 4 ]]$e4e, level = 0.5, useDfSys = TRUE ) ) print( confint( fit3sls[[ 4 ]]$e4e$eq[[ 2 ]], level = 0.25, useDfSys = TRUE ) ) print( confint( fit3sls[[ 5 ]]$e5, level = 0.25 ) ) print( confint( fit3sls[[ 5 ]]$e5$eq[[ 1 ]], level = 0.975 ) ) print( confint( fit3slsi[[ 2 ]]$e3e, level = 0.975, useDfSys = TRUE ) ) print( confint( fit3slsi[[ 2 ]]$e3e$eq[[ 1 ]], level = 0.999, useDfSys = TRUE ) ) print( confint( fit3slsi[[ 1 ]]$e5w, level = 0.975, useDfSys = TRUE ) ) print( confint( fit3slsi[[ 1 ]]$e5w$eq[[ 1 ]], level = 0.999, useDfSys = TRUE ) ) print( confint( fit3slsd[[ 3 ]]$e4, level = 0.999 ) ) print( confint( fit3slsd[[ 3 ]]$e4$eq[[ 2 ]] ) ) print( confint( fit3slsd[[ 2 ]]$e4w, level = 0.999 ) ) print( confint( fit3slsd[[ 2 ]]$e4w$eq[[ 2 ]] ) ) print( fitted( fit3sls[[ 2 ]]$e1c ) ) print( fitted( fit3sls[[ 2 ]]$e1c$eq[[ 1 ]] ) ) print( fitted( fit3sls[[ 1 ]]$e1wc ) ) print( fitted( fit3sls[[ 1 ]]$e1wc$eq[[ 1 ]] ) ) print( fitted( fit3sls[[ 3 ]]$e2e ) ) print( fitted( fit3sls[[ 3 ]]$e2e$eq[[ 2 ]] ) ) print( fitted( fit3sls[[ 4 ]]$e3 ) ) print( fitted( fit3sls[[ 4 ]]$e3$eq[[ 1 ]] ) ) print( fitted( fit3sls[[ 5 ]]$e4e ) ) print( fitted( fit3sls[[ 5 ]]$e4e$eq[[ 2 ]] ) ) print( fitted( fit3sls[[ 1 ]]$e5 ) ) print( fitted( fit3sls[[ 1 ]]$e5$eq[[ 1 ]] ) ) print( fitted( fit3slsi[[ 3 ]]$e3e ) ) print( fitted( fit3slsi[[ 3 ]]$e3e$eq[[ 1 ]] ) ) print( fitted( fit3slsd[[ 4 ]]$e4 ) ) print( fitted( fit3slsd[[ 4 ]]$e4$eq[[ 2 ]] ) ) print( fitted( fit3slsd[[ 2 ]]$e3w ) ) print( fitted( fit3slsd[[ 2 ]]$e3w$eq[[ 2 ]] ) ) predictData <- Kmenta predictData$consump <- NULL predictData$price <- Kmenta$price * 0.9 predictData$income <- Kmenta$income * 1.1 print( predict( fit3sls[[ 2 ]]$e1c, se.fit = TRUE, interval = "prediction", useDfSys = TRUE ) ) print( predict( fit3sls[[ 2 ]]$e1c$eq[[ 1 ]], se.fit = TRUE, interval = "prediction", useDfSys = TRUE ) ) print( predict( fit3sls[[ 3 ]]$e2e, se.pred = TRUE, interval = "confidence", level = 0.999, newdata = predictData, useDfSys = TRUE ) ) print( predict( fit3sls[[ 3 ]]$e2e$eq[[ 2 ]], se.pred = TRUE, interval = "confidence", level = 0.999, newdata = predictData, useDfSys = TRUE ) ) print( predict( fit3sls[[ 5 ]]$e2w, se.pred = TRUE, interval = "confidence", level = 0.999, newdata = predictData, useDfSys = TRUE ) ) print( predict( fit3sls[[ 5 ]]$e2w$eq[[ 2 ]], se.pred = TRUE, interval = "confidence", level = 0.999, newdata = predictData, useDfSys = TRUE ) ) print( predict( fit3sls[[ 4 ]]$e3, se.pred = TRUE, interval = "prediction", level = 0.975 ) ) print( predict( fit3sls[[ 4 ]]$e3$eq[[ 1 ]], se.pred = TRUE, interval = "prediction", level = 0.975 ) ) print( predict( fit3sls[[ 5 ]]$e4e, se.fit = TRUE, interval = "confidence", level = 0.25, useDfSys = TRUE ) ) print( predict( fit3sls[[ 5 ]]$e4e$eq[[ 2 ]], se.fit = TRUE, interval = "confidence", level = 0.25, useDfSys = TRUE ) ) print( predict( fit3sls[[ 1 ]]$e5, se.fit = TRUE, se.pred = TRUE, interval = "prediction", level = 0.5, newdata = predictData ) ) print( predict( fit3sls[[ 1 ]]$e5$eq[[ 1 ]], se.fit = TRUE, se.pred = TRUE, interval = "prediction", level = 0.5, newdata = predictData ) ) print( predict( fit3slsi[[ 3 ]]$e3e, se.fit = TRUE, se.pred = TRUE, interval = "confidence", level = 0.99, useDfSys = TRUE ) ) print( predict( fit3slsi[[ 3 ]]$e3e$eq[[ 1 ]], se.fit = TRUE, se.pred = TRUE, interval = "confidence", level = 0.99, useDfSys = TRUE ) ) print( predict( fit3slsi[[ 1 ]]$e5w, se.fit = TRUE, se.pred = TRUE, interval = "prediction", level = 0.5, newdata = predictData ) ) print( predict( fit3slsi[[ 1 ]]$e5w$eq[[ 1 ]], se.fit = TRUE, se.pred = TRUE, interval = "prediction", level = 0.5, newdata = predictData ) ) print( predict( fit3slsd[[ 4 ]]$e4, se.fit = TRUE, interval = "prediction", level = 0.9, newdata = predictData ) ) print( predict( fit3slsd[[ 4 ]]$e4$eq[[ 2 ]], se.fit = TRUE, interval = "prediction", level = 0.9, newdata = predictData ) ) print( predict( fit3slsd[[ 2 ]]$e3w, se.fit = TRUE, se.pred = TRUE, interval = "confidence", level = 0.99, useDfSys = TRUE ) ) print( predict( fit3slsd[[ 2 ]]$e3w$eq[[ 1 ]], se.fit = TRUE, se.pred = TRUE, interval = "confidence", level = 0.99, useDfSys = TRUE ) ) smallData <- data.frame( price = 130, income = 150, farmPrice = 120, trend = 25 ) print( predict( fit3sls[[ 3 ]]$e1c, newdata = smallData ) ) print( predict( fit3sls[[ 3 ]]$e1c$eq[[ 1 ]], newdata = smallData ) ) print( predict( fit3sls[[ 4 ]]$e2e, se.fit = TRUE, level = 0.9, newdata = smallData ) ) print( predict( fit3sls[[ 5 ]]$e2e$eq[[ 1 ]], se.pred = TRUE, level = 0.99, newdata = smallData ) ) print( predict( fit3sls[[ 1]]$e3, interval = "prediction", level = 0.975, newdata = smallData ) ) print( predict( fit3sls[[ 1 ]]$e3$eq[[ 1 ]], interval = "confidence", level = 0.8, newdata = smallData ) ) print( predict( fit3sls[[ 4]]$e3we, interval = "prediction", level = 0.975, newdata = smallData ) ) print( predict( fit3sls[[ 4 ]]$e3we$eq[[ 1 ]], interval = "confidence", level = 0.8, newdata = smallData ) ) print( predict( fit3sls[[ 2 ]]$e4e, se.fit = TRUE, interval = "confidence", level = 0.999, newdata = smallData ) ) print( predict( fit3sls[[ 2 ]]$e4e$eq[[ 2 ]], se.pred = TRUE, interval = "prediction", level = 0.75, newdata = smallData ) ) print( predict( fit3sls[[ 3 ]]$e5, se.fit = TRUE, interval = "prediction", newdata = smallData ) ) print( predict( fit3sls[[ 3 ]]$e5$eq[[ 1 ]], se.pred = TRUE, interval = "confidence", newdata = smallData ) ) print( predict( fit3slsi[[ 4 ]]$e3e, se.fit = TRUE, se.pred = TRUE, interval = "prediction", level = 0.5, newdata = smallData ) ) print( predict( fit3slsd[[ 5 ]]$e4$eq[[ 1 ]], se.fit = TRUE, se.pred = TRUE, interval = "confidence", level = 0.25, newdata = smallData ) ) print( predict( fit3slsd[[ 2 ]]$e2we, se.fit = TRUE, se.pred = TRUE, interval = "prediction", level = 0.5, newdata = smallData ) ) print( predict( fit3slsi[[ 3 ]]$e4we$eq[[ 1 ]], se.fit = TRUE, se.pred = TRUE, interval = "confidence", level = 0.25, newdata = smallData ) ) print( correlation.systemfit( fit3sls[[ 1 ]]$e1c, 2, 1 ) ) print( correlation.systemfit( fit3sls[[ 2 ]]$e2e, 1, 2 ) ) print( correlation.systemfit( fit3sls[[ 5 ]]$e2w, 2, 1 ) ) print( correlation.systemfit( fit3sls[[ 3 ]]$e3, 2, 1 ) ) print( correlation.systemfit( fit3sls[[ 4 ]]$e4e, 1, 2 ) ) print( correlation.systemfit( fit3sls[[ 5 ]]$e5, 2, 1 ) ) print( correlation.systemfit( fit3slsi[[ 2 ]]$e3e, 1, 2 ) ) print( correlation.systemfit( fit3slsi[[ 4 ]]$e5w, 1, 2 ) ) print( correlation.systemfit( fit3slsd[[ 3 ]]$e4, 2, 1 ) ) print( logLik( fit3sls[[ 1 ]]$e1c ) ) print( logLik( fit3sls[[ 1 ]]$e1c, residCovDiag = TRUE ) ) print( logLik( fit3sls[[ 2 ]]$e2e ) ) print( logLik( fit3sls[[ 2 ]]$e2e, residCovDiag = TRUE ) ) print( logLik( fit3sls[[ 3 ]]$e3 ) ) print( logLik( fit3sls[[ 3 ]]$e3, residCovDiag = TRUE ) ) print( logLik( fit3sls[[ 4 ]]$e4e ) ) print( logLik( fit3sls[[ 4 ]]$e4e, residCovDiag = TRUE ) ) print( logLik( fit3sls[[ 2 ]]$e4wSym ) ) print( logLik( fit3sls[[ 2 ]]$e4wSym, residCovDiag = TRUE ) ) print( logLik( fit3sls[[ 5 ]]$e5 ) ) print( logLik( fit3sls[[ 5 ]]$e5, residCovDiag = TRUE ) ) print( logLik( fit3slsi[[ 2 ]]$e3e ) ) print( logLik( fit3slsi[[ 2 ]]$e3e, residCovDiag = TRUE ) ) print( logLik( fit3slsi[[ 1 ]]$e1we ) ) print( logLik( fit3slsi[[ 1 ]]$e1we, residCovDiag = TRUE ) ) print( logLik( fit3slsd[[ 3 ]]$e4 ) ) print( logLik( fit3slsd[[ 3 ]]$e4, residCovDiag = TRUE ) ) print( logLik( fit3slsd[[ 5 ]]$e2we ) ) print( logLik( fit3slsd[[ 5 ]]$e2we, residCovDiag = TRUE ) ) print( linearHypothesis( fit3sls[[ 1 ]]$e1, restrm ) ) linearHypothesis( fit3sls[[ 1 ]]$e1, restrict ) print( linearHypothesis( fit3sls[[ 2 ]]$e1e, restrm ) ) linearHypothesis( fit3sls[[ 2 ]]$e1e, restrict ) print( linearHypothesis( fit3sls[[ 3 ]]$e1c, restrm ) ) linearHypothesis( fit3sls[[ 3 ]]$e1c, restrict ) print( linearHypothesis( fit3slsi[[ 4 ]]$e1, restrm ) ) linearHypothesis( fit3slsi[[ 4 ]]$e1, restrict ) print( linearHypothesis( fit3slsd[[ 5 ]]$e1e, restrm ) ) linearHypothesis( fit3slsd[[ 5 ]]$e1e, restrict ) print( linearHypothesis( fit3slsd[[ 2 ]]$e1w, restrm ) ) linearHypothesis( fit3slsd[[ 2 ]]$e1w, restrict ) restrOnly2m <- matrix(0,1,7) restrOnly2q <- 0.5 restrOnly2m[1,2] <- -1 restrOnly2m[1,5] <- 1 restrictOnly2 <- "- demand_price + supply_price = 0.5" print( linearHypothesis( fit3sls[[ 5 ]]$e1c, restrOnly2m, restrOnly2q ) ) linearHypothesis( fit3sls[[ 5 ]]$e1c, restrictOnly2 ) print( linearHypothesis( fit3slsi[[ 1 ]]$e1e, restrOnly2m, restrOnly2q ) ) linearHypothesis( fit3slsi[[ 1 ]]$e1e, restrictOnly2 ) print( linearHypothesis( fit3slsi[[ 3 ]]$e1we, restrOnly2m, restrOnly2q ) ) linearHypothesis( fit3slsi[[ 3 ]]$e1we, restrictOnly2 ) print( linearHypothesis( fit3slsd[[ 2 ]]$e1, restrOnly2m, restrOnly2q ) ) linearHypothesis( fit3slsd[[ 2 ]]$e1, restrictOnly2 ) print( linearHypothesis( fit3sls[[ 4 ]]$e2, restrOnly2m, restrOnly2q ) ) linearHypothesis( fit3sls[[ 4 ]]$e2, restrictOnly2 ) print( linearHypothesis( fit3sls[[ 4 ]]$e3, restrOnly2m, restrOnly2q ) ) linearHypothesis( fit3sls[[ 4 ]]$e3, restrictOnly2 ) print( linearHypothesis( fit3sls[[ 1 ]]$e2w, restrOnly2m, restrOnly2q ) ) linearHypothesis( fit3sls[[ 1 ]]$e2w, restrictOnly2 ) print( linearHypothesis( fit3sls[[ 1 ]]$e3we, restrOnly2m, restrOnly2q ) ) linearHypothesis( fit3sls[[ 1 ]]$e3we, restrictOnly2 ) print( linearHypothesis( fit3slsi[[ 5 ]]$e2e, restrOnly2m, restrOnly2q ) ) linearHypothesis( fit3slsi[[ 5 ]]$e2e, restrictOnly2 ) print( linearHypothesis( fit3slsi[[ 5 ]]$e3e, restrOnly2m, restrOnly2q ) ) linearHypothesis( fit3slsi[[ 5 ]]$e3e, restrictOnly2 ) print( linearHypothesis( fit3slsd[[ 1 ]]$e2, restrOnly2m, restrOnly2q ) ) linearHypothesis( fit3slsd[[ 1 ]]$e2, restrictOnly2 ) print( linearHypothesis( fit3slsd[[ 1 ]]$e3, restrOnly2m, restrOnly2q ) ) linearHypothesis( fit3slsd[[ 1 ]]$e3, restrictOnly2 ) print( linearHypothesis( fit3sls[[ 2 ]]$e1e, restr2m, restr2q ) ) linearHypothesis( fit3sls[[ 2 ]]$e1e, restrict2 ) print( linearHypothesis( fit3slsi[[ 3 ]]$e1, restr2m, restr2q ) ) linearHypothesis( fit3slsi[[ 3 ]]$e1, restrict2 ) print( linearHypothesis( fit3slsd[[ 4 ]]$e1e, restr2m, restr2q ) ) linearHypothesis( fit3slsd[[ 4 ]]$e1e, restrict2 ) print( linearHypothesis( fit3slsd[[ 5 ]]$e1w, restr2m, restr2q ) ) linearHypothesis( fit3slsd[[ 5 ]]$e1w, restrict2 ) print( linearHypothesis( fit3sls[[ 1 ]]$e1, restrm, test = "Chisq" ) ) linearHypothesis( fit3sls[[ 1 ]]$e1, restrict, test = "Chisq" ) print( linearHypothesis( fit3sls[[ 2 ]]$e1e, restrm, test = "Chisq" ) ) linearHypothesis( fit3sls[[ 2 ]]$e1e, restrict, test = "Chisq" ) print( linearHypothesis( fit3sls[[ 3 ]]$e1c, restrm, test = "Chisq" ) ) linearHypothesis( fit3sls[[ 3 ]]$e1c, restrict, test = "Chisq" ) print( linearHypothesis( fit3slsi[[ 4 ]]$e1, restrm, test = "Chisq" ) ) linearHypothesis( fit3slsi[[ 4 ]]$e1, restrict, test = "Chisq" ) print( linearHypothesis( fit3slsi[[ 2 ]]$e1we, restrm, test = "Chisq" ) ) linearHypothesis( fit3slsi[[ 2 ]]$e1we, restrict, test = "Chisq" ) print( linearHypothesis( fit3slsd[[ 5 ]]$e1e, restrm, test = "Chisq" ) ) linearHypothesis( fit3slsd[[ 5 ]]$e1e, restrict, test = "Chisq" ) print( linearHypothesis( fit3sls[[ 5 ]]$e1c, restrOnly2m, restrOnly2q, test = "Chisq" ) ) linearHypothesis( fit3sls[[ 5 ]]$e1c, restrictOnly2, test = "Chisq" ) print( linearHypothesis( fit3sls[[ 3 ]]$e1wc, restrOnly2m, restrOnly2q, test = "Chisq" ) ) linearHypothesis( fit3sls[[ 3 ]]$e1wc, restrictOnly2, test = "Chisq" ) print( linearHypothesis( fit3slsi[[ 1 ]]$e1e, restrOnly2m, restrOnly2q, test = "Chisq" ) ) linearHypothesis( fit3slsi[[ 1 ]]$e1e, restrictOnly2, test = "Chisq" ) print( linearHypothesis( fit3slsd[[ 2 ]]$e1, restrOnly2m, restrOnly2q, test = "Chisq" ) ) linearHypothesis( fit3slsd[[ 2 ]]$e1, restrictOnly2, test = "Chisq" ) print( linearHypothesis( fit3sls[[ 4 ]]$e2, restrOnly2m, restrOnly2q, test = "Chisq" ) ) linearHypothesis( fit3sls[[ 4 ]]$e2, restrictOnly2, test = "Chisq" ) print( linearHypothesis( fit3sls[[ 4 ]]$e3, restrOnly2m, restrOnly2q, test = "Chisq" ) ) linearHypothesis( fit3sls[[ 4 ]]$e3, restrictOnly2, test = "Chisq" ) print( linearHypothesis( fit3slsi[[ 5 ]]$e2e, restrOnly2m, restrOnly2q, test = "Chisq" ) ) linearHypothesis( fit3slsi[[ 5 ]]$e2e, restrictOnly2, test = "Chisq" ) print( linearHypothesis( fit3slsi[[ 5 ]]$e3e, restrOnly2m, restrOnly2q, test = "Chisq" ) ) linearHypothesis( fit3slsi[[ 5 ]]$e3e, restrictOnly2, test = "Chisq" ) print( linearHypothesis( fit3slsd[[ 1 ]]$e2, restrOnly2m, restrOnly2q, test = "Chisq" ) ) linearHypothesis( fit3slsd[[ 1 ]]$e2, restrictOnly2, test = "Chisq" ) print( linearHypothesis( fit3slsd[[ 1 ]]$e3, restrOnly2m, restrOnly2q, test = "Chisq" ) ) linearHypothesis( fit3slsd[[ 1 ]]$e3, restrictOnly2, test = "Chisq" ) print( linearHypothesis( fit3slsd[[ 2 ]]$e2we, restrOnly2m, restrOnly2q, test = "Chisq" ) ) linearHypothesis( fit3slsd[[ 2 ]]$e2we, restrictOnly2, test = "Chisq" ) print( linearHypothesis( fit3slsd[[ 3 ]]$e3w, restrOnly2m, restrOnly2q, test = "Chisq" ) ) linearHypothesis( fit3slsd[[ 3 ]]$e3w, restrictOnly2, test = "Chisq" ) print( linearHypothesis( fit3sls[[ 2 ]]$e1e, restr2m, restr2q, test = "Chisq" ) ) linearHypothesis( fit3sls[[ 2 ]]$e1e, restrict2, test = "Chisq" ) print( linearHypothesis( fit3sls[[ 5 ]]$e1wc, restr2m, restr2q, test = "Chisq" ) ) linearHypothesis( fit3sls[[ 5 ]]$e1wc, restrict2, test = "Chisq" ) print( linearHypothesis( fit3slsi[[ 3 ]]$e1, restr2m, restr2q, test = "Chisq" ) ) linearHypothesis( fit3slsi[[ 3 ]]$e1, restrict2, test = "Chisq" ) print( linearHypothesis( fit3slsd[[ 4 ]]$e1e, restr2m, restr2q, test = "Chisq" ) ) linearHypothesis( fit3slsd[[ 4 ]]$e1e, restrict2, test = "Chisq" ) print( mf <- model.frame( fit3sls[[ 3 ]]$e1c ) ) print( mf1 <- model.frame( fit3sls[[ 3 ]]$e1c$eq[[ 1 ]] ) ) print( attributes( mf1 )$terms ) print( mf2 <- model.frame( fit3sls[[ 3 ]]$e1c$eq[[ 2 ]] ) ) print( attributes( mf2 )$terms ) print( all.equal( mf, model.frame( fit3sls[[ 3 ]]$e1wc ) ) ) print( all.equal( mf2, model.frame( fit3sls[[ 3 ]]$e1wc$eq[[ 2 ]] ) ) ) print( all.equal( mf, model.frame( fit3sls[[ 4 ]]$e2e ) ) ) print( all.equal( mf2, model.frame( fit3sls[[ 4 ]]$e2e$eq[[ 2 ]] ) ) ) print( all.equal( mf, model.frame( fit3sls[[ 5 ]]$e3 ) ) ) print( all.equal( mf1, model.frame( fit3sls[[ 5 ]]$e3$eq[[ 1 ]] ) ) ) print( all.equal( mf, model.frame( fit3sls[[ 1 ]]$e4e ) ) ) print( all.equal( mf2, model.frame( fit3sls[[ 1 ]]$e4e$eq[[ 2 ]] ) ) ) print( all.equal( mf, model.frame( fit3sls[[ 2 ]]$e5 ) ) ) print( all.equal( mf1, model.frame( fit3sls[[ 3 ]]$e5$eq[[ 1 ]] ) ) ) print( all.equal( mf, model.frame( fit3slsi[[ 4 ]]$e3e ) ) ) print( all.equal( mf1, model.frame( fit3slsi[[ 4 ]]$e3e$eq[[ 1 ]] ) ) ) print( all.equal( mf, model.frame( fit3slsd[[ 5 ]]$e4 ) ) ) print( all.equal( mf2, model.frame( fit3slsd[[ 5 ]]$e4$eq[[ 2 ]] ) ) ) fit3sls[[ 3 ]]$e1c$eq[[ 1 ]]$modelInst fit3sls[[ 3 ]]$e1c$eq[[ 2 ]]$modelInst fit3sls[[ 1 ]]$e3$eq[[ 1 ]]$modelInst fit3sls[[ 1 ]]$e3$eq[[ 2 ]]$modelInst fit3slsd[[ 5 ]]$e4$eq[[ 1 ]]$modelInst fit3slsd[[ 5 ]]$e4$eq[[ 2 ]]$modelInst print( !is.null( fit3sls[[ 4 ]]$e1c$eq[[ 1 ]]$x ) ) print( mm <- model.matrix( fit3sls[[ 4 ]]$e1c ) ) print( mm1 <- model.matrix( fit3sls[[ 4 ]]$e1c$eq[[ 1 ]] ) ) print( mm2 <- model.matrix( fit3sls[[ 4 ]]$e1c$eq[[ 2 ]] ) ) print( all.equal( mm, model.matrix( fit3sls[[ 4 ]]$e1wc ) ) ) print( all.equal( mm1, model.matrix( fit3sls[[ 4 ]]$e1wc$eq[[ 1 ]] ) ) ) print( all.equal( mm2, model.matrix( fit3sls[[ 4 ]]$e1wc$eq[[ 2 ]] ) ) ) print( !is.null( fit3sls[[ 4 ]]$e1wc$eq[[ 1 ]]$x ) ) print( !is.null( fit3sls[[ 5 ]]$e2$eq[[ 1 ]]$x ) ) print( all.equal( mm, model.matrix( fit3sls[[ 5 ]]$e2 ) ) ) print( all.equal( mm1, model.matrix( fit3sls[[ 5 ]]$e2$eq[[ 1 ]] ) ) ) print( all.equal( mm2, model.matrix( fit3sls[[ 5 ]]$e2$eq[[ 2 ]] ) ) ) print( all.equal( mm, model.matrix( fit3sls[[ 5 ]]$e2e ) ) ) print( all.equal( mm1, model.matrix( fit3sls[[ 5 ]]$e2e$eq[[ 1 ]] ) ) ) print( all.equal( mm2, model.matrix( fit3sls[[ 5 ]]$e2e$eq[[ 2 ]] ) ) ) print( !is.null( fit3sls[[ 5 ]]$e1wc$e2e[[ 1 ]]$x ) ) print( !is.null( fit3sls[[ 1 ]]$e3e$eq[[ 1 ]]$x ) ) print( all.equal( mm, model.matrix( fit3sls[[ 1 ]]$e3e ) ) ) print( all.equal( mm1, model.matrix( fit3sls[[ 1 ]]$e3e$eq[[ 1 ]] ) ) ) print( all.equal( mm2, model.matrix( fit3sls[[ 1 ]]$e3e$eq[[ 2 ]] ) ) ) print( all.equal( mm, model.matrix( fit3sls[[ 1 ]]$e3 ) ) ) print( all.equal( mm1, model.matrix( fit3sls[[ 1 ]]$e3$eq[[ 1 ]] ) ) ) print( all.equal( mm2, model.matrix( fit3sls[[ 1 ]]$e3$eq[[ 2 ]] ) ) ) print( !is.null( fit3sls[[ 1 ]]$e3$eq[[ 1 ]]$x ) ) print( !is.null( fit3slsi[[ 2 ]]$e4$eq[[ 1 ]]$x ) ) print( all.equal( mm, model.matrix( fit3slsi[[ 2 ]]$e4 ) ) ) print( all.equal( mm1, model.matrix( fit3slsi[[ 2 ]]$e4$eq[[ 1 ]] ) ) ) print( all.equal( mm2, model.matrix( fit3slsi[[ 2 ]]$e4$eq[[ 2 ]] ) ) ) print( all.equal( mm, model.matrix( fit3slsi[[ 2 ]]$e4we ) ) ) print( all.equal( mm1, model.matrix( fit3slsi[[ 2 ]]$e4we$eq[[ 1 ]] ) ) ) print( all.equal( mm2, model.matrix( fit3slsi[[ 2 ]]$e4we$eq[[ 2 ]] ) ) ) print( !is.null( fit3slsi[[ 2 ]]$e1wc$e4we[[ 1 ]]$x ) ) print( !is.null( fit3slsi[[ 5 ]]$e5w$eq[[ 1 ]]$x ) ) print( all.equal( mm, model.matrix( fit3slsi[[ 5 ]]$e5w ) ) ) print( all.equal( mm1, model.matrix( fit3slsi[[ 5 ]]$e5w$eq[[ 1 ]] ) ) ) print( all.equal( mm2, model.matrix( fit3slsi[[ 5 ]]$e5w$eq[[ 2 ]] ) ) ) print( all.equal( mm, model.matrix( fit3slsi[[ 5 ]]$e5 ) ) ) print( all.equal( mm1, model.matrix( fit3slsi[[ 5 ]]$e5$eq[[ 1 ]] ) ) ) print( all.equal( mm2, model.matrix( fit3slsi[[ 5 ]]$e5$eq[[ 2 ]] ) ) ) print( !is.null( fit3slsi[[ 5 ]]$e5$eq[[ 1 ]]$x ) ) print( !is.null( fit3slsd[[ 3 ]]$e5e$eq[[ 1 ]]$x ) ) print( all.equal( mm, model.matrix( fit3slsd[[ 3 ]]$e5e ) ) ) print( all.equal( mm1, model.matrix( fit3slsd[[ 3 ]]$e5e$eq[[ 1 ]] ) ) ) print( all.equal( mm2, model.matrix( fit3slsd[[ 3 ]]$e5e$eq[[ 2 ]] ) ) ) print( all.equal( mm, model.matrix( fit3slsd[[ 3 ]]$e5we ) ) ) print( all.equal( mm1, model.matrix( fit3slsd[[ 3 ]]$e5we$eq[[ 1 ]] ) ) ) print( all.equal( mm2, model.matrix( fit3slsd[[ 3 ]]$e5we$eq[[ 2 ]] ) ) ) print( !is.null( fit3sls[[ 3 ]]$e5we$eq[[ 1 ]]$x ) ) print( !is.null( fit3slsd[[ 2 ]]$e3w$eq[[ 1 ]]$x ) ) print( all.equal( mm, model.matrix( fit3slsd[[ 2 ]]$e3w ) ) ) print( all.equal( mm1, model.matrix( fit3slsd[[ 2 ]]$e3w$eq[[ 1 ]] ) ) ) print( all.equal( mm2, model.matrix( fit3slsd[[ 2 ]]$e3w$eq[[ 2 ]] ) ) ) print( all.equal( mm, model.matrix( fit3slsd[[ 2 ]]$e3 ) ) ) print( all.equal( mm1, model.matrix( fit3slsd[[ 2 ]]$e3$eq[[ 1 ]] ) ) ) print( all.equal( mm2, model.matrix( fit3slsd[[ 2 ]]$e3$eq[[ 2 ]] ) ) ) print( !is.null( fit3slsd[[ 2 ]]$e3$eq[[ 1 ]]$x ) ) model.matrix( fit3sls[[ 1 ]]$e1c, which = "z" ) model.matrix( fit3sls[[ 3 ]]$e1c$eq[[ 1 ]], which = "z" ) model.matrix( fit3sls[[ 4 ]]$e1c$eq[[ 2 ]], which = "z" ) model.matrix( fit3slsd[[ 1 ]]$e3w, which = "xHat" ) model.matrix( fit3slsd[[ 3 ]]$e3w$eq[[ 1 ]], which = "xHat" ) model.matrix( fit3slsd[[ 4 ]]$e3w$eq[[ 2 ]], which = "xHat" ) formula( fit3sls[[ 2 ]]$e1c ) formula( fit3sls[[ 2 ]]$e1c$eq[[ 1 ]] ) formula( fit3sls[[ 3 ]]$e2e ) formula( fit3sls[[ 3 ]]$e2e$eq[[ 2 ]] ) formula( fit3sls[[ 4 ]]$e3 ) formula( fit3sls[[ 4 ]]$e3$eq[[ 1 ]] ) formula( fit3sls[[ 5 ]]$e4e ) formula( fit3sls[[ 5 ]]$e4e$eq[[ 2 ]] ) formula( fit3sls[[ 1 ]]$e5 ) formula( fit3sls[[ 1 ]]$e5$eq[[ 1 ]] ) formula( fit3slsi[[ 3 ]]$e3e ) formula( fit3slsi[[ 3 ]]$e3e$eq[[ 1 ]] ) formula( fit3slsd[[ 4 ]]$e4 ) formula( fit3slsd[[ 4 ]]$e4$eq[[ 2 ]] ) formula( fit3slsd[[ 2 ]]$e1w ) formula( fit3slsd[[ 2 ]]$e1w$eq[[ 1 ]] ) terms( fit3sls[[ 2 ]]$e1c ) terms( fit3sls[[ 2 ]]$e1c$eq[[ 1 ]] ) terms( fit3sls[[ 3 ]]$e2e ) terms( fit3sls[[ 3 ]]$e2e$eq[[ 2 ]] ) terms( fit3sls[[ 4 ]]$e3 ) terms( fit3sls[[ 4 ]]$e3$eq[[ 1 ]] ) terms( fit3sls[[ 5 ]]$e4e ) terms( fit3sls[[ 5 ]]$e4e$eq[[ 2 ]] ) terms( fit3sls[[ 1 ]]$e5 ) terms( fit3sls[[ 1 ]]$e5$eq[[ 1 ]] ) terms( fit3sls[[ 2 ]]$e4wSym ) terms( fit3sls[[ 2 ]]$e4wSym$eq[[ 1 ]] ) terms( fit3slsi[[ 3 ]]$e3e ) terms( fit3slsi[[ 3 ]]$e3e$eq[[ 1 ]] ) terms( fit3slsd[[ 4 ]]$e4 ) terms( fit3slsd[[ 4 ]]$e4$eq[[ 2 ]] ) terms( fit3slsd[[ 5 ]]$e5we ) terms( fit3slsd[[ 5 ]]$e5we$eq[[ 2 ]] ) fit3sls[[ 2 ]]$e1c$eq[[ 1 ]]$termsInst fit3sls[[ 3 ]]$e2e$eq[[ 2 ]]$termsInst fit3sls[[ 4 ]]$e3$eq[[ 1 ]]$termsInst fit3sls[[ 5 ]]$e4e$eq[[ 2 ]]$termsInst fit3sls[[ 1 ]]$e5$eq[[ 1 ]]$termsInst fit3sls[[ 2 ]]$e4wSym$eq[[ 1 ]]$termsInst fit3slsi[[ 3 ]]$e3e$eq[[ 1 ]]$termsInst fit3slsd[[ 4 ]]$e4$eq[[ 2 ]]$termsInst fit3slsd[[ 5 ]]$e5we$eq[[ 2 ]]$termsInst library( "sandwich" ) estfun( fit3sls[[ 1 ]]$e1 ) round( colSums( estfun( fit3sls[[ 1 ]]$e1 ) ), digits = 7 ) estfun( fit3sls[[ 2 ]]$e1e ) round( colSums( estfun( fit3sls[[ 2 ]]$e1e ) ), digits = 7 ) estfun( fit3sls[[ 3 ]]$e1c ) round( colSums( estfun( fit3sls[[ 3 ]]$e1c ) ), digits = 7 ) estfun( fit3sls[[ 4 ]]$e1wc ) round( colSums( estfun( fit3sls[[ 5 ]]$e1wc ) ), digits = 7 ) round( colSums( estfun( fit3sls[[ 5 ]]$e1wc, residFit = FALSE ) ), digits = 7 ) round( colSums( estfun( fit3sls[[ 4 ]]$e1wc ) ), digits = 7 ) round( colSums( estfun( fit3sls[[ 4 ]]$e1wc, residFit = FALSE ) ), digits = 7 ) round( colSums( estfun( fit3sls[[ 3 ]]$e1wc ) ), digits = 7 ) round( colSums( estfun( fit3sls[[ 3 ]]$e1wc, residFit = FALSE ) ), digits = 7 ) round( colSums( estfun( fit3sls[[ 2 ]]$e1wc ) ), digits = 7 ) round( colSums( estfun( fit3sls[[ 2 ]]$e1wc, residFit = FALSE ) ), digits = 7 ) round( colSums( estfun( fit3sls[[ 1 ]]$e1wc ) ), digits = 7 ) round( colSums( estfun( fit3sls[[ 1 ]]$e1wc, residFit = FALSE ) ), digits = 7 ) estfun( fit3slsd[[ 5 ]]$e1w ) estfun( fit3slsd[[ 5 ]]$e1w, residFit = FALSE ) round( colSums( estfun( fit3slsd[[ 5 ]]$e1w ) ), digits = 7 ) round( colSums( estfun( fit3slsd[[ 5 ]]$e1w, residFit = FALSE ) ), digits = 7 ) round( colSums( estfun( fit3slsd[[ 4 ]]$e1w ) ), digits = 7 ) round( colSums( estfun( fit3slsd[[ 4 ]]$e1w, residFit = FALSE ) ), digits = 7 ) round( colSums( estfun( fit3slsd[[ 3 ]]$e1w ) ), digits = 7 ) round( colSums( estfun( fit3slsd[[ 3 ]]$e1w, residFit = FALSE ) ), digits = 7 ) round( colSums( estfun( fit3slsd[[ 2 ]]$e1w ) ), digits = 7 ) round( colSums( estfun( fit3slsd[[ 2 ]]$e1w, residFit = FALSE ) ), digits = 7 ) round( colSums( estfun( fit3slsd[[ 1 ]]$e1w ) ), digits = 7 ) round( colSums( estfun( fit3slsd[[ 1 ]]$e1w, residFit = FALSE ) ), digits = 7 ) bread( fit3sls[[ 1 ]]$e1 ) bread( fit3sls[[ 2 ]]$e1e ) bread( fit3sls[[ 3 ]]$e1c ) bread( fit3sls[[ 4 ]]$e1wc ) bread( fit3slsd[[ 5 ]]$e1w ) bread( fit3slsd[[ 4 ]]$e1w ) bread( fit3slsd[[ 3 ]]$e1w ) bread( fit3slsd[[ 2 ]]$e1w ) bread( fit3slsd[[ 1 ]]$e1w )
gridBy <- function(lim = c(0, 1), by = (lim[2] - lim[1]) / 10) { gridlist <- list() for (idx in 1:(length(lim)/2)) { if (length(by) == 1) { gridlist[[idx]] <- seq(lim[2 * idx - 1], lim[2 * idx], by = by) } else { gridlist[[idx]] <- seq(lim[2 * idx - 1], lim[2 * idx], by = by[idx]) } } grid <- as.matrix(expand.grid(gridlist)) colnames(grid) <- NULL dim <- sapply(gridlist, length) out <- list("dim" = dim, "lim" = lim, "grid" = grid) return(out) }
Gibbs_method = function(y, rho = NULL, n_rho = NULL, rho_ratio = NULL, Theta=NULL, ncores = 4, chain = 1, max.elongation = 10, em.tol=0.001) { p <- ncol(y) n <- nrow(y) lower.upper = lower.upper(y) if(is.null(rho)) { if(is.null(n_rho)) n_rho = 10 cr = cor(y, method="spearman") - diag(p) cr[is.na(cr)] <- 0 rho_max = max(max(cr),-min(cr)) if(rho_max == 0) { ty <- npn(y, npn.func= "shrinkage") cr = cor(ty, method="spearman") - diag(p) rho_max = max(max(cr),-min(cr)) } if(rho_max >= .7) rho_max = .7 rho_min = rho_ratio * rho_max rho = exp(seq(log(rho_max), log(rho_min), length = n_rho)) rm(cr, rho_max, rho_min, rho_ratio) } Gibbs.method <- calculate_EM_Gibbs(chain, y, rho = rho[chain], Theta=Theta, lower.upper = lower.upper, em.tol = em.tol, em.iter = max.elongation, gibbs.iter = 500, mc.iter = 1000, ncores = ncores) invisible(return(Gibbs.method)) }
idb1 <- function(country, year, variables = c('AGE', 'AREA_KM2', 'NAME', 'POP'), start_age = NULL, end_age = NULL, sex = NULL, api_key = NULL) { .Deprecated("get_idb") if (Sys.getenv('IDB_API') != '') { api_key <- Sys.getenv('IDB_API') } else if (is.null(api_key)) { if (Sys.getenv("CENSUS_API_KEY") != '') { api_key <- Sys.getenv("CENSUS_API_KEY") } else { stop('A Census API key is required. Obtain one at https://api.census.gov/data/key_signup.html, and then supply the key to the `idb_api_key` function to use it throughout your idbr session.') } } if (length(country) > 1) { multi <- purrr::map_df(country, ~{ idb1(country = .x, year = year, variables = variables, start_age = start_age, end_age = end_age, sex = sex, api_key = api_key) }) return(multi) } if (nchar(country) > 2) { country <- countrycode::countrycode(country, 'country.name', 'fips') } if (!(country %in% valid_countries)) { stop(paste0('The FIPS code ', country, ' is not available in the Census IDB.')) } variables <- paste(variables, sep = '', collapse = ',') if (length(year) == 1) { url <- paste0( 'https://api.census.gov/data/timeseries/idb/1year?get=', variables, '&FIPS=', country, '&time=', as.character(year), '&key=', api_key ) if (!is.null(start_age) & !is.null(end_age)) { url <- paste0(url, '&AGE=', as.character(start_age), ':', as.character(end_age)) } else if (!is.null(start_age) & is.null(end_age)) { url <- paste0(url, '&AGE=', as.character(start_age), ':100') } else if (is.null(start_age) & !is.null(end_age)) { url <- paste0(url, '&AGE=0:', as.character(end_age)) } if (!is.null(sex)) { if (sex == 'both') sex <- 0 if (sex == 'male') sex <- 1 if (sex == 'female') sex <- 2 url <- paste0(url, '&SEX=', as.character(sex)) } return(load_data(url)) } else if (length(year) > 1) { dfs <- lapply(year, function(x) { url <- paste0( 'https://api.census.gov/data/timeseries/idb/1year?get=', variables, '&FIPS=', country, '&time=', as.character(x), '&key=', api_key ) if (!is.null(start_age) & !is.null(end_age)) { url <- paste0(url, '&AGE=', as.character(start_age), ':', as.character(end_age)) } else if (!is.null(start_age) & is.null(end_age)) { url <- paste0(url, '&AGE=', as.character(start_age), ':100') } else if (is.null(start_age) & !is.null(end_age)) { url <- paste0(url, '&AGE=0:', as.character(end_age)) } if (!is.null(sex)) { if (sex == 'both') sex <- 0 if (sex == 'male') sex <- 1 if (sex == 'female') sex <- 2 url <- paste0(url, '&SEX=', as.character(sex)) } load_data(url) }) return(dplyr::bind_rows(dfs)) } } idb5 <- function(country, year, variables = NULL, concept = NULL, country_name = FALSE, api_key = NULL) { .Deprecated("get_idb") if (Sys.getenv('IDB_API') != '') { api_key <- Sys.getenv('IDB_API') } else if (is.null(api_key)) { if (Sys.getenv("CENSUS_API_KEY") != '') { api_key <- Sys.getenv("CENSUS_API_KEY") } else { stop('A Census API key is required. Obtain one at https://api.census.gov/data/key_signup.html, and then supply the key to the `idb_api_key` function to use it throughout your idbr session.') } } suppressWarnings(if (country == 'all') { country <- valid_countries } else { country <- purrr::map_chr(country, function(x) { if (nchar(x) > 2) { return(countrycode::countrycode(x, 'country.name', 'fips')) } else { return(x) } }) }) if (any(is.na(!match(country, valid_countries))) == TRUE) { nomatch <- country[is.na(!match(country, valid_countries))] country <- country[!country %in% nomatch] warning(paste0('The FIPS codes ', paste(nomatch, sep = ' ', collapse = ', '), ' are not available in the Census IDB, and have been removed from your query.')) } if (length(variables) > 50) { stop("Requests are limited to 50 variables. Consider using `idb_variables()` to identify which variables to select, or `idb_concepts()` to identify a concept by which you can subset.", call. = FALSE) } if (!is.null(variables)) { if (!is.null(concept)) { concept <- NULL warning('concept cannot be used with variables; using the specified variables instead.', call. = FALSE) } variables <- paste(variables, sep = '', collapse = ',') } else if (is.null(variables) & is.null(concept)) { stop("Requests are limited to 50 variables. Consider using `idb_variables()` to identify which variables to select, or `idb_concepts()` to identify a concept by which you can subset.", call. = FALSE) } else if (is.null(variables) & !is.null(concept)) { sub <- variables5[variables5$Concept == concept, ] vars <- unique(sub$Name) variables <- paste(vars, sep = '', collapse = ',') } if (country_name == TRUE) variables <- paste0(variables, ',NAME') if (length(country) == 1 & length(year) == 1) { url <- paste0( 'https://api.census.gov/data/timeseries/idb/5year?get=', variables, '&FIPS=', country, '&time=', as.character(year), '&key=', api_key ) return(load_data(url)) } else if (length(country) > 1 & length(year) == 1) { dfs <- lapply(country, function(x) { url <- paste0( 'https://api.census.gov/data/timeseries/idb/5year?get=', variables, '&FIPS=', x, '&time=', as.character(year), '&key=', api_key ) load_data(url) }) return(dplyr::bind_rows(dfs)) } else if (length(country) == 1 & length(year) > 1) { dfs <- lapply(year, function(x) { url <- paste0( 'https://api.census.gov/data/timeseries/idb/5year?get=', variables, '&FIPS=', country, '&time=', as.character(x), '&key=', api_key ) load_data(url) }) return(dplyr::bind_rows(dfs)) } else if (length(country) > 1 & length(year) > 1) { full <- lapply(country, function(x) { dfs <- lapply(year, function(y) { url <- paste0( 'https://api.census.gov/data/timeseries/idb/5year?get=', variables, '&FIPS=', x, '&time=', as.character(y), '&key=', api_key ) load_data(url) }) dplyr::bind_rows(dfs) }) return(dplyr::bind_rows(full)) } } idb_api_key <- function(api_key) { Sys.setenv(IDB_API = api_key) }
aformat <- function( md5hash = NULL) { elements <- strsplit(md5hash, "/")[[1]] stopifnot( length(elements) >= 3 | length(elements) == 1) if (length(elements) == 1) { tags <- getTagsLocal(md5hash, tag = "") } else { tags <- getTagsRemote(tail(elements,1), repo = elements[2], subdir = ifelse(length(elements) > 3, paste(elements[3:(length(elements)-1)], collapse="/"), "/"), user = elements[1], tag = "") } return(gsub(grep(tags, pattern="^format:", value = TRUE), pattern="^format:", replacement="")) }
library(shiny) library(shiny.i18n) i18n <- Translator$new(translation_json_path = "../data/translation.json") i18n$set_translation_language("pl") ui <- shinyUI(fluidPage( titlePanel(i18n$t("Hello Shiny!")), sidebarLayout( sidebarPanel( sliderInput("bins", i18n$t("Number of bins:"), min = 1, max = 50, value = 30) ), mainPanel( plotOutput("distPlot"), p(i18n$t("This is description of the plot.")) ) ) )) server <- function(input, output) { output$distPlot <- renderPlot({ x <- faithful[, 2] bins <- seq(min(x), max(x), length.out = input$bins + 1) hist(x, breaks = bins, col = "darkgray", border = "white", main = i18n$t("Histogram of x"), ylab = i18n$t("Frequency")) }) } shinyApp(ui = ui, server = server)
dateRefill.fromFileToExcel <- function(inPath, sheet, dateCol.index, outPath, fixedCol.index, uninterpolatedCol.index, uninterpolatedCol.newValue) { if(!requireNamespace("openxlsx",quietly = TRUE)){ install.packages("openxlsx"); requireNamespace("openxlsx", quietly = TRUE) }else{ requireNamespace("openxlsx", quietly = TRUE) } if(!requireNamespace("zoo", quietly = TRUE)){ install.packages("zoo"); requireNamespace("zoo", quietly = TRUE) }else{ requireNamespace("zoo", quietly = TRUE) } if(!requireNamespace("Hmisc",quietly = TRUE)){ install.packages("Hmisc"); requireNamespace("Hmisc", quietly = TRUE) }else{ requireNamespace("Hmisc", quietly = TRUE) } if(!requireNamespace("magrittr",quietly = TRUE)){ install.packages("magrittr"); requireNamespace("magrittr", quietly = TRUE) }else{ requireNamespace("magrittr", quietly = TRUE) } data <- openxlsx::read.xlsx(inPath, sheet) data[,dateCol.index] <- zoo::as.Date(data[,dateCol.index], origin = "1899-12-30") colNameVector <- colnames(data) colnames(data)[dateCol.index] <- "Date" data$Date <- as.POSIXlt(data$Date) year.list <- levels(factor(data$Date$year + 1900)) data <- data[order(data$Date, decreasing = FALSE),] final.data <- data.frame(data[,1:length(colNameVector)]) final.data[,] <- NA final.data$Date <- as.POSIXlt(final.data$Date) year <- substr(data[1, dateCol.index],1,4) origin <- paste(year, "-01-01", sep = "") origin <- zoo::as.Date(origin) diff <- zoo::as.Date(data[1, dateCol.index])-origin daySum <- sprintf("%s-01-01", year.list) %>% zoo::as.Date() daySum <- mapply(Hmisc::yearDays, daySum) %>% sum() daySum <- magrittr::subtract(daySum, diff) %>% as.numeric() final.data[1:daySum,] <- NA final.data[, dateCol.index] <- seq(data[1, dateCol.index], by = "1 days", length.out = daySum) colnames(data) <- names(final.data) my.index <- match(data$Date, as.POSIXlt(final.data$Date)) final.data[my.index,] <- data[,] final.data <- head(final.data, which(final.data$Date == data$Date[length(data$Date)])) final.data[which(is.na(final.data[, fixedCol.index[1]])), fixedCol.index] <- data[1, fixedCol.index] final.data[which(is.na(final.data[, uninterpolatedCol.index[1]])), uninterpolatedCol.index] <- uninterpolatedCol.newValue final.data$Date <- zoo::as.Date(final.data$Date) colnames(final.data) <- colNameVector openxlsx::write.xlsx(final.data, file = outPath) } dateRefill.fromData <- function(data, dateCol.index, fixedCol.index, uninterpolatedCol.index, uninterpolatedCol.newValue) { if(!requireNamespace("zoo", quietly = TRUE)){ install.packages("zoo"); requireNamespace("zoo", quietly = TRUE) }else{ requireNamespace("zoo", quietly = TRUE) } if(!requireNamespace("Hmisc",quietly = TRUE)){ install.packages("Hmisc"); requireNamespace("Hmisc", quietly = TRUE) }else{ requireNamespace("Hmisc", quietly = TRUE) } if(!requireNamespace("magrittr",quietly = TRUE)){ install.packages("magrittr"); requireNamespace("magrittr", quietly = TRUE) }else{ requireNamespace("magrittr", quietly = TRUE) } data <- data.frame(data) data[,dateCol.index] <- zoo::as.Date(data[,dateCol.index], origin = "1899-12-30") colNameVector <- colnames(data) colnames(data)[dateCol.index] <- "Date" data$Date <- as.POSIXlt(data$Date) year.list <- levels(factor(data$Date$year + 1900)) data <- data[order(data$Date, decreasing = FALSE),] final.data <- data.frame(data[,1:length(colNameVector)]) final.data[,] <- NA final.data$Date <- as.POSIXlt(final.data$Date) year <- substr(data[1, dateCol.index],1,4) origin <- paste(year, "-01-01", sep = "") origin <- zoo::as.Date(origin) diff <- zoo::as.Date(data[1, dateCol.index])-origin daySum <- sprintf("%s-01-01", year.list) %>% zoo::as.Date() daySum <- mapply(Hmisc::yearDays, daySum) %>% sum() daySum <- magrittr::subtract(daySum, diff) %>% as.numeric() final.data[1:daySum,] <- NA final.data[, dateCol.index] <- seq(data[1, dateCol.index], by = "1 days", length.out = daySum) colnames(data) <- names(final.data) my.index <- match(data$Date, as.POSIXlt(final.data$Date)) final.data[my.index,] <- data[,] final.data <- head(final.data, which(final.data$Date == data$Date[length(data$Date)])) final.data[which(is.na(final.data[, fixedCol.index[1]])), fixedCol.index] <- data[1, fixedCol.index] final.data[which(is.na(final.data[, uninterpolatedCol.index[1]])), uninterpolatedCol.index] <- uninterpolatedCol.newValue final.data$Date <- zoo::as.Date(final.data$Date) colnames(final.data) <- colNameVector return(final.data) }
gcloud_version <- function() { out <- gcloud_exec("version", echo = FALSE) version <- strsplit(unlist(strsplit(out$stdout, "\r?\n")), " (?=[^ ]+$)", perl = TRUE) v_numbers <- lapply(version, function(x) numeric_version(x[2])) names(v_numbers) <- sapply(version, function(x) x[1]) v_numbers }
context("compile reactions") params <- c( "a" = 1, "b" = 2, "c" = 3, "d" = 4.5321 ) state <- c( "a_very_long_state_name_value_is_just_to_try_and_see_if_it_works" = 12.34, "short_one" = 7, "x" = 1, "y" = 0, "z" = 0 ) reactions <- list( reaction("a", c(x = +1, y = +1), "react1"), reaction("b", c(x = +1, y = -1), "react2"), reaction("c", c(x = +1, z = +1), "react3"), reaction("d", c(x = +1, z = -1), "react4"), reaction("a_very_long_state_name_value_is_just_to_try_and_see_if_it_works", c(x = +1), "react5"), reaction("short_one", c(x = -1, y = +1), "react6"), reaction("x", c(x = -1, y = -1), "react7"), reaction("y", c(x = -1, z = +1), "react8"), reaction("z", c(x = -1, z = -1), "react9"), reaction( propensity = "a * b * c * d / a_very_long_state_name_value_is_just_to_try_and_see_if_it_works / short_one", effect = c(x = -1), name = "react10" ), reaction( propensity = "buf1 = a + 1; buf2 = buf1 + 1; buf3 = buf2 + 1; buf4 = buf3 + 1; buf4 + 1", effect = c(y = +1, z = +1), name = "react11" ), reaction( propensity = ~ (a * b + c) / d, effect = c(y = +1, z = -1), name = "react12" ) ) test_that("compilation works", { comp_reac <- compile_reactions( reactions = reactions, state_ids = names(state), params = params, hardcode_params = FALSE ) nu <- comp_reac$state_change expect_equal(nrow(nu), length(state)) expect_equal(ncol(nu), length(reactions)) expected_p <- reactions %>% map_int(~length(.$effect)) %>% cumsum %>% c(0, .) expect_equal(nu@p, expected_p) expected_i <- reactions %>% map(~names(.$effect)) %>% unlist() %>% match(names(state)) - 1 expect_equal(nu@i, expected_i) expected_x <- reactions %>% map(~.$effect) %>% unlist() %>% unname() expect_equal(expected_x, nu@x) expected_reac_ids <- map_chr(reactions, "name") expect_equal(comp_reac$reaction_ids, expected_reac_ids) expect_equal(comp_reac$buffer_ids, paste0("buf", 1:4)) expect_equal(comp_reac$buffer_size, 4) expect_equal(comp_reac$hardcode_params, FALSE) out <- test_propensity_calculation( comp_reac, params, state, 0 ) expected_prop <- with(as.list(c(params, state)), c( params, state, a * b * c * d / a_very_long_state_name_value_is_just_to_try_and_see_if_it_works / short_one, a + 5, (a * b + c) / d )) %>% unname() expect_equal(out$propensity, expected_prop, tolerance = .001) expect_equal(out$buffer, 2:5, tolerance = .001) }) test_that("compilation works when params are hardcoded", { comp_reac <- compile_reactions( reactions = reactions, state_ids = names(state), params = params, hardcode_params = TRUE ) out <- test_propensity_calculation( comp_reac, params, state, 0 ) expected_prop <- with(as.list(c(params, state)), c( params, state, a * b * c * d / a_very_long_state_name_value_is_just_to_try_and_see_if_it_works / short_one, a + 5, (a * b + c) / d )) %>% unname() expect_equal(out$propensity, expected_prop, tolerance = .001) expect_equal(out$buffer, 2:5, tolerance = .001) })
expected <- eval(parse(text="structure(c(\"a\", \"2\", \"3.14159265358979+2i\"), .Names = c(\"a\", \"b\", \"c\"))")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(a = \"a\", b = 2, c = 3.14159265358979+2i), .Names = c(\"a\", \"b\", \"c\")), TRUE, TRUE)")); .Internal(unlist(argv[[1]], argv[[2]], argv[[3]])); }, o=expected);
test_that("/events API get's datetime", { piwik_pro_credentials <- get_test_credentials() skip_if_missing_credentials(piwik_pro_credentials) skip_if_not_installed("piwikproRTests") skip_on_cran() piwikproRTests::datetime_for_events_api(piwik_pro_credentials) }) test_that("/sessions API get's datetime", { piwik_pro_credentials <- get_test_credentials() skip_if_missing_credentials(piwik_pro_credentials) skip_if_not_installed("piwikproRTests") skip_on_cran() piwikproRTests::datetime_for_sessions_api(piwik_pro_credentials) }) test_that("/query API get's date", { piwik_pro_credentials <- get_test_credentials() skip_if_missing_credentials(piwik_pro_credentials) skip_if_not_installed("piwikproRTests") skip_on_cran() piwikproRTests::no_datetime_for_query_api(piwik_pro_credentials) }) test_that("/events API can use fetch_by_day=TRUE ", { piwik_pro_credentials <- get_test_credentials() skip_if_missing_credentials(piwik_pro_credentials) skip_if_not_installed("piwikproRTests") skip_on_cran() piwikproRTests::fetch_by_day_for_events_api(piwik_pro_credentials) }) test_that("/sessions API can use fetch_by_day=TRUE ", { piwik_pro_credentials <- get_test_credentials() skip_if_missing_credentials(piwik_pro_credentials) skip_if_not_installed("piwikproRTests") skip_on_cran() piwikproRTests::fetch_by_day_for_sessions_api(piwik_pro_credentials) })
.VCFconnection <- function(file) { file <- path.expand(file) remote <- grepl("^(ht|f)tp(s|):", file) GZ <- grepl("\\.gz$", file, ignore.case = TRUE) if (GZ) { file <- if (remote) url(file) else gzfile(file) file <- gzcon(file) } x <- readChar(file, 16L, TRUE) if (!identical(x, " stop("file apparently not in VCF format") file } .getMETAvcf <- function(file) { f <- .VCFconnection(file) HEADER <- character(0) skip <- 0L repeat { x <- scan(file, "", sep = "\n", n = 1L, skip = skip, quiet = TRUE) if (substr(x, 1, 6) == " skip <- skip + 1L HEADER <- c(HEADER, x) } HEADER <- paste(paste0(HEADER, "\n"), collapse = "") j <- nchar(HEADER, "bytes") + 1L + nchar(x, "bytes") list(HEADER = HEADER, LABELS = x, position = j) } VCFheader <- function(file) .getMETAvcf(file)$HEADER VCFlabels <- function(file) strsplit(.getMETAvcf(file)$LABELS, "\t")[[1]][-(1:9)] VCFloci <- function(file, what = "all", chunk.size = 1e9, quiet = FALSE) { meta <- .getMETAvcf(file) f <- .VCFconnection(file) GZ <- if (inherits(f, "connection")) TRUE else FALSE FIELDS <- c("CHROM", "POS", "ID", "REF", "ALT", "QUAL", "FILTER", "INFO", "FORMAT") what <- if (identical(what, "all")) 1:9 else match(what, FIELDS) obj <- vector("list", 9L) if (GZ) open(f) else { sz <- file.info(file)$size if (is.na(sz)) stop(paste("cannot find information on file", sQuote(file))) left.to.scan <- sz } if (!quiet) cat("Scanning file", file, "\n") scanned <- 0 ncycle <- 0L FROM <- integer() TO <- integer() CHUNK.SIZES <- numeric() repeat { if (!GZ) { if (left.to.scan > chunk.size) { left.to.scan <- left.to.scan - chunk.size } else { chunk.size <- left.to.scan left.to.scan <- 0L } Y <- .Call(read_bin_pegas, file, chunk.size, scanned) } else { Y <- readBin(f, "raw", chunk.size) if (!length(Y)) break } nY <- length(Y) scanned <- scanned + nY if (!quiet) { if (GZ) cat("\r", scanned/1e6, "Mb") else cat("\r", scanned/1e6, "/", sz/1e6, "Mb") } ncycle <- ncycle + 1L if (ncycle == 1) { skip <- meta$position - 3L nCol <- length(gregexpr("\t", meta$LABELS)[[1]]) + 1L } else skip <- 0L hop <- 2L * nCol - 1L EOL <- .Call(findEOL_C, Y, skip, hop) ck <- nY if (exists("trail", inherits = FALSE)) { x <- c(trail, Y[1:EOL[1L]]) for (i in what) { tmp <- if (i %in% c(2, 6)) .Call(extract_POS, x, c(0L, length(trail)), i - 1L) else .Call(extract_REF, x, c(0L, length(trail)), i - 1L) obj[[i]] <- c(obj[[i]], tmp) } ck <- ck + length(trail) rm(trail) extra.locus <- 1L } else extra.locus <- 0L nEOL <- length(EOL) if (EOL[nEOL] != nY) { trail <- Y[(EOL[nEOL] + 1L):nY] ck <- ck - length(trail) } from <- if (ncycle == 1) 1L else TO[ncycle - 1L] + 1L to <- from + nEOL - 2L + extra.locus FROM <- c(FROM, from) TO <- c(TO, to) CHUNK.SIZES <- c(CHUNK.SIZES, ck) for (i in what) { tmp <- if (i %in% c(2, 6)) .Call(extract_POS, Y, EOL, i - 1L) else .Call(extract_REF, Y, EOL, i - 1L) obj[[i]] <- c(obj[[i]], tmp) } if (!GZ && !left.to.scan) break } if (GZ) close(f) else if (!quiet) cat("\r", scanned/1e6, "/", sz/1e6, "Mb") if (!quiet) cat("\nDone.\n") assign(file, data.frame(FROM = FROM, TO = TO, CHUNK.SIZES = CHUNK.SIZES), envir = .cacheVCF) names(obj) <- FIELDS obj <- obj[!sapply(obj, is.null)] obj <- as.data.frame(obj, stringsAsFactors = FALSE) class(obj) <- c("VCFinfo", "data.frame") obj } print.VCFinfo <- function(x, ...) { n <- length(x[[1]]) if (n < 10) print(as.data.frame(x)) else { x <- x[c(1:5, (n - 4):n), , drop = FALSE] x <- apply(x, 2, as.character) x <- as.data.frame(x, stringsAsFactors = FALSE) x[5:6, ] <- "" row.names(x) <- c(1:4, "....", ".....", (n - 3):n) print(x) } } is.snp.VCFinfo <- function(x) { REF <- x$REF if (is.null(REF)) stop("no REF allele(s)") ALT <- x$ALT if (is.null(ALT)) stop("no ALT allele(s)") nchar(REF) == 1 & nchar(ALT) == 1 } rangePOS <- function(x, from, to) { POS <- x$POS if (is.null(POS)) stop("no POS(isition)") which(from <= POS & POS <= to) } selectQUAL <- function(x, threshold = 20) { QUAL <- x$QUAL if (is.null(QUAL)) stop("no QUAL(ility)") which(QUAL >= threshold) } getINFO <- function(x, what = "DP", as.is = FALSE) { INFO <- x$INFO if (is.null(INFO)) stop("no INFO") regexp <- paste0("^.*", what, "=") tmp <- gsub(regexp, "", INFO) tmp <- gsub(";.+$", "", tmp) if (!as.is) { op <- options(warn = -1) on.exit(options(op)) if (!all(is.na(as.numeric(tmp[1:10])))) tmp <- as.numeric(tmp) } tmp }
tmGetViewports <- function(vp, fontsize.title, fontsize.labels, fontsize.legend, position.legend, type, aspRatio, title.legend, catLabels) { if (is.null(vp)) { grid.newpage() } else { if (is.character(vp)) seekViewport(vp) else pushViewport(vp) } width <- convertWidth(unit(1,"npc"), "inches",valueOnly = TRUE) height <- convertHeight(unit(1,"npc"), "inches",valueOnly = TRUE) plotMargin <- unit(0.5,"cm") fsTitle <- fontsize.title fsData <- 12 fsLegend <- fontsize.legend titleSpace <- convertHeight(unit(1.5* (fsTitle/get.gpar()$fontsize), "lines"), "inches") if (position.legend == "bottom") { legHeight <- unit(fsLegend * 0.03 + 0.4, "inches") legWidth <- unit(0, "npc") vpLeg <- viewport(name = "legenda", x = plotMargin, y = 0.5 * plotMargin + legHeight*0.3, width = unit(1, "npc") - 2 * plotMargin, height = legHeight*0.7, gp=gpar(fontsize=fsLegend), just = c("left", "bottom")) vpLegTitle <- viewport(name = "legenda_title", x = plotMargin, y = 0.5 * plotMargin, width = unit(1, "npc") - 2 * plotMargin, height = legHeight*0.3, gp=gpar(fontsize=fsLegend), just = c("left", "bottom")) } else if (position.legend == "right") { scale <- fsLegend / get.gpar()$fontsize maxStringWidth <- max(convertWidth(stringWidth(title.legend), "inches", valueOnly=TRUE)*scale+.5, 1) if (type %in% c("categorical", "index")) { maxStringWidth <- max(maxStringWidth, convertWidth(stringWidth(catLabels), "inches", valueOnly=TRUE)*scale+.75) } legWidth <- unit(maxStringWidth, "inches") legHeight <- unit(0, "npc") vpLeg <- viewport(name = "legenda", x = unit(1, "npc") - plotMargin - legWidth, y = 0.5 * plotMargin, width = legWidth, height = unit(1, "npc") - plotMargin - titleSpace, gp=gpar(fontsize=fsLegend), just = c("left", "bottom")) vpLegTitle <- viewport(name = "legenda_title", x = unit(1, "npc") - plotMargin - legWidth, y = unit(1, "npc") - 0.5 * plotMargin - titleSpace, width = legWidth, height = titleSpace, gp=gpar(fontsize=fsLegend), just = c("left", "bottom")) } else { legWidth <- unit(0, "npc") legHeight <- unit(0, "npc") vpLeg <- NA vpLegTitle <- NA } vpDat <- viewport(name = "data", x = plotMargin, y = legHeight + 0.5*plotMargin, width = unit(1, "npc") - 2 * plotMargin - legWidth, height = unit(1,"npc") - legHeight - plotMargin - titleSpace, gp=gpar(fontsize=fsData), just = c("left", "bottom")) vpDatTitle <- viewport(name = "data_title", x = plotMargin, y = unit(1, "npc") - .5*plotMargin - titleSpace, width = unit(1, "npc") - 2 * plotMargin - legWidth, height = titleSpace, gp=gpar(fontsize=fsTitle), just = c("left", "bottom")) pushViewport(vpDat) datWidth <- convertWidth(unit(1,"npc"), "inches", valueOnly=TRUE) datHeight <- convertHeight(unit(1,"npc"), "inches", valueOnly=TRUE) aspWindow <- datWidth / datHeight if (!is.na(aspRatio)) { if (aspRatio < aspWindow) { datWidth <- datHeight * aspRatio } else if (aspRatio > aspWindow) { datHeight <- datWidth / aspRatio } } else { aspRatio <- datWidth / datHeight } vpDatAsp <- viewport(name = "data_asp", x = unit(0.5, "npc"), y = unit(0.5, "npc"), width = unit(datWidth, "inches"), height = unit(datHeight,"inches"), gp=gpar(fontsize=fsData), just = c("centre", "centre")) upViewport() vpCoorY <- ((convertY(vpDat$y, unitTo="inch", valueOnly=TRUE) + convertHeight(vpDat$height, unitTo="inch", valueOnly=TRUE)/2) + c(-1, 1) * (datHeight/2)) / height vpCoorX <- ((convertX(vpDat$x, unitTo="inch", valueOnly=TRUE) + convertWidth(vpDat$width, unitTo="inch", valueOnly=TRUE)/2) + c(-1, 1) * (datWidth/2)) / width list(vpDat=vpDat, vpDatAsp=vpDatAsp, vpDatTitle=vpDatTitle, vpLeg=vpLeg, vpLegTitle=vpLegTitle, datWidth=datWidth, datHeight=datHeight, aspRatio=aspRatio, vpCoorX=vpCoorX, vpCoorY=vpCoorY) }
summary.polywog <- function(object, level = .95, prop0 = FALSE, ...) { ans <- list() cf <- coef(object) se <- sqrt(diag(vcov(object))) ans$coefficients <- cbind("Estimate" = cf, "Std. Error" = se) if (!is.null(object$boot.matrix)) { q <- 0.5 - (level/2) interval <- apply(object$boot.matrix, 1, quantile, probs = c(q, 1-q)) p0 <- rowMeans(object$boot.matrix == 0) ans$coefficients <- cbind(ans$coefficients, t(interval), "Prop. 0" = if (prop0) p0) } ans$call <- object$call ans$degree <- object$degree ans$family <- object$family ans$method <- object$method ans$penwt.method <- object$penwt.method ans$nobs <- object$nobs ans$nboot <- if (!is.null(object$boot.matrix)) ncol(object$boot.matrix) else 0 ans$lambda <- object$lambda class(ans) <- "summary.polywog" return(ans) } print.summary.polywog <- function(x, digits = max(3, getOption("digits") - 3), ...) { cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"), "\n\n", sep = "") cat("Coefficients:\n") printCoefmat(coef(x), digits = digits, ...) cat("\nRegularization method:", switch(x$method, alasso = "Adaptive LASSO", scad = "SCAD")) if (x$method == "alasso") { pname <- switch(x$penwt.method, lm = "inverse linear model coefficients", glm = "inverse logistic regression coefficients") cat("\nAdaptive weights:", pname) } cat("\nNumber of observations:", x$nobs) cat("\nPolynomial expansion degree:", x$degree) cat("\nModel family:", x$family) cat("\nBootstrap iterations:", x$nboot) cat("\nPenalization parameter (lambda):", format(x$lambda, digits = digits)) cat("\n\n") invisible(x) }
library(tiledb) array_name <- "quickstart_sparse_enc" uri <- file.path(getOption("TileDB_Data_Path", "."), array_name) encryption_key <- "0123456789abcdeF0123456789abcdeF" create_array <- function(array_name) { if (tiledb_object_type(array_name) == "ARRAY") { message("Array already exists, removing to create new one.") tiledb_vfs_remove_dir(array_name) } dom <- tiledb_domain(dims = c(tiledb_dim("rows", c(1L, 4L), 4L, "INT32"), tiledb_dim("cols", c(1L, 4L), 4L, "INT32"))) schema <- tiledb_array_schema(dom, attrs=c(tiledb_attr("a", type = "INT32")), sparse = TRUE) invisible( tiledb_array_create(array_name, schema, encryption_key) ) } write_array <- function(array_name) { I <- c(1, 2, 2) J <- c(1, 4, 3) data <- c(1L, 2L, 3L) A <- tiledb_array(uri = array_name, encryption_key = encryption_key) A[I, J] <- data } read_array <- function(array_name) { A <- tiledb_array(uri = array_name, as.data.frame=TRUE, encryption_key = encryption_key) A[1:2, 2:4] } read_via_query_object <- function(array_name) { arr <- tiledb_array(uri, encryption_key = encryption_key) qry <- tiledb_query(arr, "READ") rows <- integer(8) cols <- integer(8) values <- integer(8) tiledb_query_set_buffer(qry, "rows", rows) tiledb_query_set_buffer(qry, "cols", cols) tiledb_query_set_buffer(qry, "a", values) tiledb_query_submit(qry) tiledb_query_finalize(qry) stopifnot(tiledb_query_status(qry)=="COMPLETE") n <- tiledb_query_result_buffer_elements(qry, "a") print(data.frame(rows=rows,cols=cols,a=values)[1:n,]) } create_array(uri) write_array(uri) read_array(uri) read_via_query_object(uri)
summary.estLCCRcon <- function(object, ...){ cat("\nEstimation of latent class models for capture-recapture data\n") cat("\n") cat("Call:\n") print(object$call) cat("\nAvailable objects:\n") print(names(object)) cat("\n") print(c(LogLik=object$lk,np=object$np,AIC=object$AIC,BIC=object$BIC)) cat("\nPopulation size:\n") if(object$se_out){ Tab = cbind("est."=object$N,"s.e."=object$seN) rownames(Tab) = "N" print(Tab) }else{ print(c(Nh = object$N)) } if(object$H>1){ if(object$se_out){ cat("\nParameters affecting the class weights:\n") tt = object$be/object$sebe pv = 2*(1-pnorm(abs(tt))) Tab = cbind("est."=object$be,"s.e."=object$sebe,"t-test"=tt,"p-value"=pv) print(Tab) }else{ print(object$be) } } cat("\nParameters affecting the conditional capture probabilities given the latent class:\n") if(object$se_out){ tt = object$la/object$sela pv = 2*(1-pnorm(abs(tt))) Tab = cbind("est."=object$la,"s.e."=object$sela,"t-test"=tt,"p-value"=pv) print(Tab) }else{ print(object$la) } }
rda.tune <- function(x, ina, nfolds = 10, gam = seq(0, 1, by = 0.1), del = seq(0, 1, by = 0.1), ncores = 1, folds = NULL, stratified = TRUE, seed = FALSE) { ina <- as.numeric(ina) n <- dim(x)[1] nc <- max(ina) D <- dim(x)[2] sk <- array( dim = c(D, D, nc) ) lg <- length(gam) ; ld <- length(del) if ( is.null(folds) ) folds <- Compositional::makefolds(ina, nfolds = nfolds, stratified = stratified, seed = seed) nfolds <- length(folds) if (ncores > 1) { runtime <- proc.time() group <- matrix(nrow = length(gam), ncol = length(del) ) cl <- parallel::makePSOCKcluster(ncores) doParallel::registerDoParallel(cl) if ( is.null(folds) ) folds <- Compositional::makefolds(ina, nfolds = nfolds, stratified = stratified, seed = seed) ww <- foreach(vim = 1:nfolds, .combine = cbind, .export = c("mahala", "rowMaxs"), .packages = "Rfast") %dopar% { test <- x[ folds[[ vim ]], , drop = FALSE] id <- ina[ folds[[ vim ]] ] train <- x[ -folds[[ vim ]], , drop = FALSE] ida <- ina[ -folds[[ vim ]] ] na <- tabulate(ida) ci <- 2 * log(na / sum(na) ) mesi <- rowsum(train, ida) / na na <- rep(na - 1, each = D^2) for (m in 1:nc) sk[ , , m] <- Rfast::cova( train[ida == m, ] ) s <- na * sk Sp <- colSums( aperm(s) ) / (sum(na) - nc) sp <- diag( sum( diag( Sp ) ) / D, D ) gr <- matrix(nrow = length( folds[[ vim ]] ), ncol = nc) for ( k1 in 1:length(gam) ) { Sa <- gam[k1] * Sp + (1 - gam[k1]) * sp for ( k2 in 1:length(del) ) { for (j in 1:nc) { Ska <- del[k2] * sk[, , j] + (1 - del[k2]) * Sa gr[, j] <- ci[j] - log( det( Ska ) ) - Rfast::mahala( test, mesi[j, ], Ska ) } g <- Rfast::rowMaxs(gr) group[k1, k2] <- mean( g == id ) } } return( as.vector( group ) ) } stopCluster(cl) per <- array( dim = c( lg, ld, nfolds ) ) for ( i in 1:nfolds ) per[, , i] <- matrix( ww[, i], nrow = lg ) runtime <- proc.time() - runtime } else { runtime <- proc.time() per <- array( dim = c( lg, ld, nfolds ) ) for (vim in 1:nfolds) { test <- x[ folds[[ vim ]], , drop = FALSE ] id <- ina[ folds[[ vim ]] ] train <- x[ -folds[[ vim ]], , drop = FALSE] ida <- ina[ -folds[[ vim ]] ] na <- tabulate(ida) ci <- 2 * log(na / sum(na) ) mesi <- rowsum(train, ida) / na na <- rep(na - 1, each = D^2) for (m in 1:nc) sk[ , , m] <- Rfast::cova( train[ida == m, ] ) s <- na * sk Sp <- colSums( aperm(s) ) / (sum(na) - nc) sp <- diag( sum( diag( Sp ) ) / D, D ) gr <- matrix(nrow = length( folds[[ vim ]] ), ncol = nc) for ( k1 in 1:length(gam) ) { Sa <- gam[k1] * Sp + (1 - gam[k1]) * sp for ( k2 in 1:length(del) ) { for (j in 1:nc) { Ska <- del[k2] * sk[, , j] + (1 - del[k2]) * Sa gr[, j] <- ci[j] - log( det( Ska ) ) - Rfast::mahala( test, mesi[j, ], Ska ) } g <- Rfast::rowMaxs(gr) per[k1, k2, vim] <- mean( g == id ) } } } runtime <- proc.time() - runtime } percent <- t( colMeans( aperm(per) ) ) su <- apply(per, 1:2, sd) dimnames(percent) <- dimnames(su) <- list(gamma = gam, delta = del) confa <- as.vector( which(percent == max( percent ), arr.ind = TRUE )[1, ] ) result <- cbind( max(percent), gam[ confa[1] ], del[ confa[2] ] ) colnames(result) <- c('optimal', 'best gamma', 'best delta') list(per = per, percent = percent, se = su, result = result, runtime = runtime) }
icmis <- function(subject, testtime, result, data, sensitivity, specificity, formula = NULL, negpred = 1, time.varying = F, betai = NULL, initsurv = 0.5, param = 1, ...){ id <- eval(substitute(subject), data, parent.frame()) time <- eval(substitute(testtime), data, parent.frame()) result <- eval(substitute(result), data, parent.frame()) ord <- order(id, time) if (is.unsorted(ord)) { id <- id[ord] time <- time[ord] result <- result[ord] data <- data[ord, ] } utime <- sort(unique(time)) stopifnot(is.numeric(sensitivity), is.numeric(specificity), is.numeric(negpred), is.logical(time.varying), is.numeric(initsurv)) stopifnot(length(sensitivity) == 1, sensitivity >= 0, sensitivity <= 1, length(specificity) == 1, specificity >= 0, specificity <= 1, length(negpred) == 1, negpred >= 0, negpred <= 1) stopifnot(length(initsurv) == 1, initsurv > 0, initsurv < 1) if (!all(result %in% c(0, 1))) stop("result must be 0 or 1") if (any(is.na(time))) stop("Missing value found in testtime") if (any(tapply(time, id, anyDuplicated))) stop("existing duplicated visit times for some subjects") if (!all(utime >= 0 & utime < Inf)) stop("existing negative or infinite visit times") stopifnot(length(param) == 1, param %in% c(1, 2, 3)) if (param == 3 && time.varying) stop("parameterization 3 is not available for time varying model") if (any(time == 0 & result == 1)) { pre_ids <- id[time == 0 & result == 1] stop(sprintf( "Existing baseline prevalent subjects: %s; need to remove them", paste(pre_ids, collapse = ",")) ) } if (length(utime) > sqrt(length(time))) { warning(paste0( "There are too many distinct testtime values, consider", " rounding testtime, e.g. to year or month" )) } conv_msg <- paste0( "Model not converged, code: %s, refer to optim function for details. ", "Try to increase maxit in function argument, ", "e.g. using control = list(maxit = 500), and/or", " use different parameterization by changing param argument." ) timen0 <- (time != 0) Dm <- dmat(id[timen0], time[timen0], result[timen0], sensitivity, specificity, negpred) J <- ncol(Dm) - 1 nsub <- nrow(Dm) if (param == 1) { lami <- rep(-log(initsurv)/J, J) tosurv <- function(x) exp(-cumsum(x)) lowlam <- rep(0, J) surv95 <- function(lam, covm) { A <- matrix(0, nrow = J, ncol = J) idx <- cbind( unlist(sapply(1:J, function(i) rep(i, i))), unlist(sapply(1:J, function(i) 1:i)) ) A[idx] <- 1 covmt <- A %*% covm %*% t(A) lam_sd <- sqrt(diag(covmt)) low95 <- exp(-(cumsum(lam) + 1.96 * lam_sd)) high95 <- exp(-(cumsum(lam) - 1.96 * lam_sd)) data.frame( time = utime[utime!=0], surv = tosurv(lam), low95 = low95, high95 = high95) } } else if (param == 2) { lami <- log(rep(-log(initsurv)/J, J)) tosurv <- function(x) exp(-cumsum(exp(x))) surv95 <- function(lam, covm) { A <- matrix(0, nrow = J, ncol = J) idx <- cbind( unlist(sapply(1:J, function(i) rep(i, i))), unlist(sapply(1:J, function(i) 1:i)) ) A[idx] <- exp(lam[idx[, 2]]) covmt <- A %*% covm %*% t(A) lam_sd <- sqrt(diag(covmt)) low95 <- exp(-(cumsum(exp(lam)) + 1.96 * lam_sd)) high95 <- exp(-(cumsum(exp(lam)) - 1.96 * lam_sd)) data.frame( time = utime[utime!=0], surv = tosurv(lam), low95 = low95, high95 = high95) } } else if (param == 3) { lami <- log(-log(seq(1, initsurv, length.out = J + 1)[-1])) lami <- c(lami[1], diff(lami)) tosurv <- function(x) exp(-exp(cumsum(x))) lowlam <- c(-Inf, rep(0, J - 1)) surv95 <- function(lam, covm) { A <- matrix(0, nrow = J, ncol = J) idx <- cbind( unlist(sapply(1:J, function(i) rep(i, i))), unlist(sapply(1:J, function(i) 1:i)) ) A[idx] <- 1 covmt <- A %*% covm %*% t(A) lam_sd <- sqrt(diag(covmt)) low95 <- exp(-exp((cumsum(lam) + 1.96 * lam_sd))) high95 <- exp(-exp((cumsum(lam) - 1.96 * lam_sd))) data.frame( time = utime[utime!=0], surv = tosurv(lam), low95 = low95, high95 = high95) } } output <- function(q) { loglik <- -q$value cov_all <- as.matrix(solve(q$hessian)) lam <- q$par[1:J] survival <- surv95(lam, cov_all[1:J, 1:J]) if (!is.null(formula)) { cov <- cov_all[-(1:J), -(1:J), drop = FALSE] rownames(cov) <- colnames(cov) <- beta.nm beta.fit <- q$par[-(1:J)] beta.sd <- sqrt(diag(cov)) beta.z <- beta.fit/beta.sd p.value <- 2*(1-pnorm(abs(beta.z))) coef <- data.frame(coefficient = beta.fit, SE = beta.sd, z = beta.z, p.value = p.value) } else { cov <- NA coef <- NA } list(loglik = loglik, coefficient = coef, survival = survival, beta.cov = cov, nsub = nsub) } if (is.null(formula)) { if (param == 1) { q <- optim(lami, loglikA0, gradlikA0, lower = lowlam, Dm = Dm, method = "L-BFGS-B", hessian = T, ...) } else if (param == 2) { q <- optim(lami, loglikB0, gradlikB0, Dm = Dm, method = "BFGS", hessian = T, ...) } else if (param == 3) { q <- optim(lami, loglikC0, gradlikC0, lower = lowlam, Dm = Dm, method = "L-BFGS-B", hessian = T, ...) } if (q$convergence != 0) stop(sprintf(conv_msg, q$convergence)) return(output(q)) } Xmat <- model.matrix(formula, data = data)[, -1, drop = F] if (nrow(Xmat) < nrow(data)) stop("missing values in used covariates") beta.nm <- colnames(Xmat) nbeta <- ncol(Xmat) if (is.null(betai)) { parmi <- c(lami, rep(0, nbeta)) } else { if (length(betai) != nbeta) stop("length of betai does match number of beta") parmi <- c(lami, betai) } if (!time.varying) { uid <- getrids(id, nsub) Xmat <- Xmat[uid, , drop = F] if (param == 1) { q <- optim(parmi, loglikA, gradlikA, lower = c(lowlam, rep(-Inf, nbeta)), Dm = Dm, Xmat = Xmat, method = "L-BFGS-B", hessian = T, ...) } else if (param == 2) { q <- optim(parmi, loglikB, gradlikB, Dm = Dm, Xmat = Xmat, method = "BFGS", hessian = T, ...) } else if (param == 3) { q <- optim(parmi, loglikC, gradlikC, lower = c(lowlam, rep(-Inf, nbeta)), Dm = Dm, Xmat = Xmat, method = "L-BFGS-B", hessian = T, ...) } if (q$convergence != 0) stop(sprintf(conv_msg, q$convergence)) return(output(q)) } if (length(unique(id)) != length(unique(id[time==0]))) stop("some subject(s) miss baseline information (time=0) for time-varying model") TXmat <- timeMat(nsub, J+1, time, utime, Xmat) if (param == 1) { q <- optim(parmi, loglikTA, gradlikTA, lower = c(lowlam, rep(-Inf, nbeta)), Dm = Dm, TXmat = TXmat, method = "L-BFGS-B", hessian = T, ...) } else if (param == 2) { q <- optim(parmi, loglikTB, gradlikTB, Dm = Dm, TXmat = TXmat, method = "BFGS", hessian = T, ...) } if (q$convergence != 0) stop(sprintf(conv_msg, q$convergence)) return(output(q)) } plot_surv <- function(obj) { surv <- obj$survival surv <- rbind(c(0, 1, 1, 1), surv) plot(surv$time, surv$surv, type = "s", col = "red", xlab = "time", ylab = "Survival") lines(surv$time, surv$low95, type = "s", lty = 2) lines(surv$time, surv$high95, type = "s", lty = 2) }
summary.shrinklm <- function (object, correlation = FALSE, symbolic.cor = FALSE, ...) { z <- object p <- z$rank rdf <- z$df.residual if (p == 0) { r <- z$residuals n <- length(r) w <- z$weights if (is.null(w)) { rss <- sum(r^2) } else { rss <- sum(w * r^2) r <- sqrt(w) * r } resvar <- rss/rdf ans <- z[c("call", "terms", if (!is.null(z$weights)) "weights")] class(ans) <- "summary.lm" ans$aliased <- is.na(coef(z)) ans$residuals <- r ans$df <- c(0L, n, length(ans$aliased)) ans$coefficients <- matrix(NA, 0L, 4L) dimnames(ans$coefficients) <- list(NULL, c("Estimate", "Std. Error", "t value", "Pr(>|t|)")) ans$sigma <- sqrt(resvar) ans$r.squared <- ans$adj.r.squared <- 0 return(ans) } if (is.null(z$terms)) stop("invalid 'lm' object: no 'terms' component") if (!inherits(z, "lm")) warning("calling summary.lm(<fake-lm-object>) ...") if (is.na(z$df.residual)) warning(paste("residual degrees of freedom in object", "suggest this is not an \"lm\" fit")) r <- z$residuals f <- z$fitted.values w <- z$weights n <- length(r) if (is.null(w)) { mss <- if (attr(z$terms, "intercept")) sum( (f - mean(f))^2 ) else sum(f^2) rss <- sum(r^2) } else { mss <- if (attr(z$terms, "intercept")) { m <- sum(w * f/sum(w)) sum(w * (f - m)^2) } else sum(w * f^2) rss <- sum(w * r^2) r <- sqrt(w) * r } resvar <- rss/rdf if (is.finite(resvar) && resvar < (mean(f)^2 + var(f)) * 1e-30) warning("essentially perfect fit: summary may be unreliable") p1 <- (abs(z$svd$d) >= 1e-14) R <- z$svd$v[, p1, drop = FALSE] %*% ( (z$svd$d[p1]^2 / (z$svd$d[p1]^2 + z$lambda0)^2) * t(z$svd$v[, p1, drop = FALSE]) ) se <- if (nrow(R) < length(z$coefficients)) { m_u <- colMeans(z$svd$u[, p1, drop = FALSE]) se_const <- sqrt(resvar * (1 + sum(m_u^2 * z$svd$d[p1]^4 / (z$svd$d[p1]^2 + z$lambda0)^2))) c(sqrt(diag(R) * resvar), se_const) } else { sqrt(diag(R) * resvar) } est <- z$coefficients tval <- est/se ans <- z[c("call", "terms", if (!is.null(z$weights)) "weights")] ans$residuals <- r ans$coefficients <- cbind(Estimate = est, `Std. Error` = se, `t value` = tval, `Pr(>|t|)` = 2 * pt(abs(tval), rdf, lower.tail = FALSE)) ans$aliased <- is.na(coef(z)) ans$sigma <- sqrt(resvar) ans$df <- c(p, rdf, p) if (p != attr(z$terms, "intercept")) { df.int <- if (attr(z$terms, "intercept")) 1L else 0L ans$r.squared <- mss/(mss + rss) ans$adj.r.squared <- 1 - (1 - ans$r.squared) * ((n - df.int) / rdf) ans$fstatistic <- c(value = (mss/(n - rdf - df.int)) / resvar, numdf = n - rdf - df.int, dendf = rdf) } else ans$r.squared <- ans$adj.r.squared <- 0 ans$cov.unscaled <- R dimnames(ans$cov.unscaled) <- list(dimnames(ans$coefficients)[[1]][1:nrow(R)], dimnames(ans$coefficients)[[1]][1:nrow(R)]) if (correlation) { ans$correlation <- (R * resvar)/outer(se, se) dimnames(ans$correlation) <- dimnames(ans$cov.unscaled) ans$symbolic.cor <- symbolic.cor } if (!is.null(z$na.action)) ans$na.action <- z$na.action class(ans) <- "summary.lm" ans }
context("ct_get_reset_time") test_that("same test, different iteration", { expect_is(ct_get_reset_time(), "POSIXct") })
process_repeated_flag <- function(flag, val, narg) { if (is.matrix(val)) { m <- t(val) } else { if (narg == 1) { m <- matrix(val, nrow = 1) } else { m <- matrix(val, ncol = 1) } } as.vector(rbind(flag, m)) } process_args <- function(args, formalsTable) { ft <- formalsTable opts <- lapply(names(args), function(nm) { flag <- ft[ft$arg == nm, "flag"] narg <- ft[ft$arg == nm, "narg"] repeatable <- ft[ft$arg == nm, "repeatable"] val <- args[[nm]] if (repeatable) { process_repeated_flag(flag, val = val, narg = narg) } else { if (narg == 0) { if (val) flag else NULL } else { c(flag, val) } } }) opts <- c(character(0), unlist(opts)) opts <- Filter(nchar, opts) opts }
.simulate.synlik <- function(object, nsim, seed = NULL, param = object@param, stats = FALSE, clean = TRUE, verbose = TRUE, ...) { if(!is(object, "synlik")) stop("object has to be of class \"synlik\" ") if( !class(object)[[1]] != "synlik" ) object <- as(object, "synlik") if(is.null(seed) == FALSE) set.seed(seed) simulator <- object@simulator summaries <- object@summaries extraArgs <- object@extraArgs simul <- simulator(param = param, nsim = nsim, extraArgs = extraArgs, ...) if( stats == TRUE ) { if(!is.null(summaries) ) simul <- summaries(x = simul, extraArgs = extraArgs, ...) if( clean ) simul <- .clean(X = simul, verbose = verbose)$cleanX } return( simul ) } setMethod("simulate", signature = signature(object = "synlik"), definition = .simulate.synlik)
remove_noise_from_bams = function( bams, genes, expression, noise.thresholds, destination.files = base::paste0(base::basename(bams), ".noisefiltered.bam"), filter.by = c("gene", "exon"), make.index = FALSE, unique.only = TRUE, mapq.unique = 255, ... ){ if(base::is.matrix(expression)){ expression.matrix <- expression }else if(base::is.list(expression) & identical(names(expression)[1], "expression.matrix")){ expression.matrix <- expression$expression.matrix }else{ stop("Please provide an expression.matrix or an expression.summary list") } if(base::length(noise.thresholds) == 1){ base::message("noise.thresholds only has 1 value, using a fixed threshold...") noise.thresholds <- base::rep(noise.thresholds, base::ncol(expression.matrix)) }else if(base::length(noise.thresholds) != base::ncol(expression.matrix)){ base::stop("noise.thresholds needs to be length 1 or ncol(expression.matrix)") } base::message("Denoising ", base::length(bams), " BAM files...") genes.sub <- filter_genes_transcript( genes = genes, expression.matrix = expression.matrix, noise.thresholds = noise.thresholds, filter.by = filter.by ) bam.indexes <- base::paste(bams, ".bai", sep="") for(j in base::seq_len(base::length(bam.indexes))){ bam.index <- bam.indexes[j] if(!base::file.exists(bam.index)){ if(make.index){ base::message("Creating BAM index for ", bams[j]) bams[j] <- Rsamtools::sortBam(bams[j], destination=base::paste0(bams[j], ".sorted")) bam.index <- Rsamtools::indexBam(bams[j]) }else{ stop("BAM index not found. It can be generated by setting make.index = TRUE") } } } gr <- GenomicRanges::GRanges(seqnames = genes.sub$seqid, ranges = IRanges::IRanges(start=genes.sub$start, end=genes.sub$end)) params <- Rsamtools::ScanBamParam(which = gr, what = Rsamtools::scanBamWhat(), mapqFilter = ifelse(unique.only, mapq.unique, 0)) for(j in base::seq_len(base::length(bams))){ base::message(" denoising BAM file ", j, " of ", base::length(bams)) Rsamtools::filterBam(file = bams[j], destination = destination.files[j], indexDestination = make.index, param = params) } return(base::invisible(NULL)) }
context(".findLocalMaximaLogical") s <- createMassSpectrum(mass=1:5, intensity=c(1, 2, 1, 2, 1)) test_that(".findLocalMaximaLogical throws errors", { expect_error(MALDIquant:::.findLocalMaximaLogical(s, halfWindowSize=0), "too small") expect_error(MALDIquant:::.findLocalMaximaLogical(s, halfWindowSize=3), "too large") }) test_that(".findLocalMaxima(Logical) shows warnings", { expect_warning(MALDIquant:::.findLocalMaximaLogical( createMassSpectrum(mass=double(), intensity=double()), "empty")) expect_warning(MALDIquant:::.findLocalMaxima( createMassSpectrum(mass=double(), intensity=double()), "empty")) }) test_that(".findLocalMaximaLogical works with different window sizes", { expect_identical(suppressWarnings(MALDIquant:::.findLocalMaximaLogical( createMassSpectrum(mass=double(), intensity=double()), halfWindowSize=1)), logical()) expect_identical(MALDIquant:::.findLocalMaximaLogical(s, halfWindowSize=1), c(FALSE, TRUE, FALSE, TRUE, FALSE)) expect_identical(MALDIquant:::.findLocalMaximaLogical(s, halfWindowSize=2), c(FALSE, TRUE, FALSE, FALSE, FALSE)) }) test_that(".findLocalMaxima returns matrix", { m <- matrix(ncol=2, dimnames=list(list(), list("mass", "intensity"))) expect_equal(suppressWarnings(MALDIquant:::.findLocalMaxima( createMassSpectrum(mass=double(), intensity=double()), halfWindowSize=1)), m) m <- matrix(c(2, 2, 4, 2), ncol=2, byrow=TRUE, dimnames=list(list(), list("mass", "intensity"))) expect_identical(MALDIquant:::.findLocalMaxima(s, halfWindowSize=1), m) })
posterior_predictive <- function(simmr_out, group = 1, prob = 0.5, plot_ppc = TRUE) { UseMethod("posterior_predictive") } posterior_predictive.simmr_output <- function(simmr_out, group = 1, prob = 0.5, plot_ppc = TRUE) { assert_int(group, lower = 1, upper = simmr_out$input$n_groups) model_string_old <- simmr_out$output[[group]]$model$model() copy_lines <- model_string_old[6] copy_lines <- sub("y\\[i", "y_pred\\[i", copy_lines) model_string_new <- c(model_string_old[1:6], copy_lines, model_string_old[7:length(model_string_old)]) output <- R2jags::jags( data = simmr_out$output[[group]]$model$data(), parameters.to.save = c("y_pred"), model.file = textConnection(paste0(model_string_new, collapse = "\n")), n.chains = simmr_out$output[[group]]$BUGSoutput$n.chains, n.iter = simmr_out$output[[group]]$BUGSoutput$n.iter, n.burnin = simmr_out$output[[group]]$BUGSoutput$n.burnin, n.thin = simmr_out$output[[group]]$BUGSoutput$n.thin ) y_post_pred <- output$BUGSoutput$sims.list$y_pred low_prob <- 0.5 - prob / 2 high_prob <- 0.5 + prob / 2 y_post_pred_ci <- apply(y_post_pred, 2:3, "quantile", prob = c(low_prob, high_prob) ) y_post_pred_out <- data.frame( interval = matrix(y_post_pred_ci, ncol = simmr_out$input$n_tracers, byrow = TRUE ), data = as.vector(simmr_out$input$mixtures[simmr_out$input$group_int == group, ]) ) y_post_pred_out$outside <- y_post_pred_out[, 3] > y_post_pred_out[, 2] | y_post_pred_out[, 3] < y_post_pred_out[, 1] prop_outside <- mean(y_post_pred_out$outside) if (plot_ppc) { y_rep <- y_post_pred dim(y_rep) <- c(dim(y_post_pred)[1], dim(y_post_pred)[2] * dim(y_post_pred)[3]) curr_rows <- which(simmr_out$input$group_int == group) curr_mix <- simmr_out$input$mixtures[curr_rows, , drop = FALSE] g <- ppc_intervals( y = as.vector(curr_mix), yrep = y_rep, x = rep(1:nrow(curr_mix), simmr_out$input$n_tracers), prob = prob, fatten = 1 ) + ggplot2::ylab("Tracer value") + ggplot2::xlab("Observation") + ggplot2::ggtitle(paste0(prob * 100, "% posterior predictive")) + ggplot2::theme_bw() + ggplot2::scale_x_continuous(breaks = 1:simmr_out$input$n_obs) print(g) } invisible(list( table = y_post_pred_out, prop_outside = prop_outside )) }
context("NMscanData") fix.time <- function(x){ meta.x <- attr(x,"NMdata") meta.x$details$time.NMscanData <- NULL meta.x$details$file.lst <- NULL meta.x$details$file.mod <- NULL meta.x$details$file.input <- NULL meta.x$details$mtime.input <- NULL meta.x$details$mtime.lst <- NULL meta.x$details$mtime.mod <- NULL meta.x$datafile$path <- NULL meta.x$datafile$path.rds <- NULL meta.x$tables$file <- NULL meta.x$tables$file.mtime <- NULL setattr(x,"NMdata",meta.x) } NMdataConf(reset=TRUE) test_that("basic",{ fileRef <- "testReference/NMscanData1.rds" resRef <- if(file.exists(fileRef)) readRDS(fileRef) else NULL file.lst <- "testData/nonmem/xgxr001.lst" res <- NMscanData(file=file.lst, quiet=T, order.columns = F, merge.by.row=FALSE, check.time = FALSE) fix.time(res) expect_equal_to_reference(res,fileRef,version=2) }) test_that("Modifications to column names in $INPUT",{ fileRef <- "testReference/NMscanData2.rds" file.lst <- "testData/nonmem/xgxr002.lst" res1 <- NMscanData(file=file.lst, check.time = FALSE, merge.by.row=FALSE) res <- list( NMinfo(res1,"input.colnames"), NMinfo(res1,"columns"), colnames(res1) ) expect_equal_to_reference(res,fileRef,version=2) }) test_that("No translation of column names in $INPUT",{ fileRef <- "testReference/NMscanData2b.rds" file.lst <- "testData/nonmem/xgxr002.lst" res1 <- NMscanData(file=file.lst, check.time = FALSE, merge.by.row=FALSE, translate.input = T) res2 <- NMscanData(file=file.lst, check.time = FALSE, merge.by.row=FALSE, translate.input = F) dt.cnames <- data.table(colnames(res1),colnames(res2)) expect_equal_to_reference(dt.cnames,fileRef,version=2) }) test_that("Multiple output table formats",{ NMdataConf(reset=TRUE) fileRef <- "testReference/NMscanData3.rds" file.lst <- "testData/nonmem/xgxr003.lst" res <- NMscanData(file=file.lst, check.time = FALSE, merge.by.row=FALSE) fix.time(res) expect_equal_to_reference(res,fileRef,version=2) }) test_that("Interpret IGNORE statement",{ NMdataConf(reset=TRUE) fileRef <- "testReference/NMscanData4.rds" file.lst <- "testData/nonmem/xgxr004.lst" res <- NMscanData(file=file.lst,merge.by.row=FALSE,check.time = FALSE) fix.time(res) expect_equal_to_reference(res,fileRef,version=2) }) test_that("List of ACCEPT statements and vs separate statements",{ NMdataConf(reset=T) NMdataConf(as.fun="data.table") file1.lst <- "testData/nonmem/xgxr006.lst" file2.lst <- "testData/nonmem/xgxr007.lst" NMreadSection(file1.lst,section="PROBLEM") NMreadSection(file2.lst,section="PROBLEM") res1 <- NMscanData(file=file1.lst,merge.by.row=FALSE,col.model=NULL,check.time = FALSE) res2 <- NMscanData(file=file2.lst,merge.by.row=FALSE,col.model=NULL,check.time = FALSE) setattr(res1,"NMdata",NULL) setattr(res2,"NMdata",NULL) expect_identical(res1,res2) }) test_that("merge by filters or not",{ file1.lst <- "testData/nonmem/xgxr006.lst" file2.lst <- "testData/nonmem/xgxr008.lst" res1 <- NMscanData(file=file1.lst,merge.by.row=FALSE,col.model=NULL,check.time = FALSE) res2 <- NMscanData(file=file2.lst,merge.by.row=FALSE,col.model=NULL,check.time = FALSE) setnames(res2,"EFF0","eff0",skip_absent=T) setcolorder(res1,colnames(res2)) setattr(res1,"NMdata",NULL) setattr(res2,"NMdata",NULL) expect_equal(res1,res2) }) test_that("Only a firstonly without ID but with ROW",{ NMdataConf(reset=TRUE) fileRef <- "testReference/NMscanData11.rds" file.lst <- "testData/nonmem/xgxr011.lst" expect_error( expect_warning( NMscanData(file=file.lst,merge.by.row=FALSE,col.row="ROW",check.time = FALSE) ) ) res1 <- expect_warning( NMscanData(file=file.lst,merge.by.row=TRUE,col.row="ROW",check.time = FALSE) ) fix.time(res1) expect_equal_to_reference(res1,fileRef,version=2) }) test_that("Only a firstonly, no ID, no ROW",{ fileRef <- "testReference/NMscanData12.rds" file.lst <- "testData/nonmem/xgxr012.lst" expect_error( expect_warning( res1 <- NMscanData(file=file.lst,check.time = FALSE) ) ) }) test_that("FO and row-level output. No ID, no row.",{ fileRef <- "testReference/NMscanData13.rds" file.lst <- "testData/nonmem/xgxr013.lst" NMreadSection(file.lst,section="PROBLEM") NMreadSection(file.lst,section="TABLE") res1 <- expect_warning( NMscanData(file=file.lst,check.time = FALSE) ) fix.time(res1) expect_equal_to_reference( res1,fileRef,version=2 ) res2 <- expect_warning( NMscanData(file=file.lst,check.time = FALSE,merge.by.row=T) ) res2 <- expect_warning( NMscanData(file=file.lst,check.time = FALSE,use.input=F) ) }) test_that("FO and row-level output. No ID, no row. cbind.by.filters=T",{ fileRef <- "testReference/NMscanData14.rds" file.lst <- "testData/nonmem/xgxr013.lst" NMreadSection(file.lst,section="PROBLEM") res1 <- expect_warning( NMscanData(file=file.lst,merge.by.row=FALSE,check.time = FALSE) ) fix.time(res1) summary(res1)$variables summary(res1)$tables summary(res1) expect_equal_to_reference( res1,fileRef,version=2 ) }) test_that("Only a firstonly without ID but with ROW",{ fileRef <- "testReference/NMscanData15.rds" file.lst <- "testData/nonmem/xgxr011.lst" NMreadSection(file.lst,section="DATA") NMreadSection(file.lst,section="TABLE") res1 <- expect_error( NMscanData(file=file.lst,merge.by.row=FALSE,check.time = FALSE) ) }) test_that("Only a firstonly without ID but with ROW. Using merge.by.row=TRUE.",{ fileRef <- "testReference/NMscanData15b.rds" file.lst <- "testData/nonmem/xgxr011.lst" NMreadSection(file.lst,section="DATA") NMreadSection(file.lst,section="TABLE") res1 <- expect_warning( NMscanData(file=file.lst,col.row="ROW",merge.by.row=TRUE,check.time = FALSE) ) fix.time(res1) expect_equal_to_reference( res1,fileRef,version=2 ) }) test_that("recoverRows without a row identifier",{ fileRef <- "testReference/NMscanData16.rds" file.lst <- "testData/nonmem/xgxr004.lst" NMreadSection(file.lst,section="DATA") NMreadSection(file.lst,section="TABLE") res1 <- NMscanData(file=file.lst,merge.by.row=FALSE,recover.rows = T,as.fun="data.table",check.time = FALSE) dim(res1) res1[,table(nmout,DOSE)] fix.time(res1) expect_equal_to_reference( res1,fileRef,version=2 ) }) test_that("use as.fun to get a data.frame",{ fileRef <- "testReference/NMscanData17.rds" file.lst <- "testData/nonmem/xgxr004.lst" NMreadSection(file.lst,section="DATA") NMreadSection(file.lst,section="TABLE") res1 <- NMscanData(file=file.lst,merge.by.row=FALSE,recover.rows = T,as.fun=as.data.frame,check.time = FALSE) dim(res1) class(res1) with(res1,table(nmout,DOSE)) fix.time(res1) expect_equal_to_reference( res1,fileRef,version=2 ) }) test_that("use as.fun to get a tibble",{ fileRef <- "testReference/NMscanData18.rds" file.lst <- "testData/nonmem/xgxr004.lst" NMreadSection(file.lst,section="DATA") NMreadSection(file.lst,section="TABLE") res1 <- NMscanData(file=file.lst,merge.by.row=FALSE,recover.rows = T,as.fun=tibble::as_tibble,check.time = FALSE) dim(res1) class(res1) fix.time(res1) expect_equal_to_reference( res1,fileRef,version=2 ) }) test_that("dir structure with input.txt/output.txt",{ NMdataConf(reset=TRUE) NMdataConf(as.fun="data.table") NMdataConf(file.mod=identity) NMdataConf(modelname=function(file) basename(dirname(normalizePath(file)))) filedir.lst <- "testData/nonmem/xgxr001dir/output.txt" res1dir <- NMscanData(filedir.lst,check.time = FALSE,merge.by.row=F) expect_equal(NMinfo(res1dir,"details")$model,"xgxr001dir") umod <- unique(res1dir[,model]) expect_equal(length(umod),1) expect_equal(umod,"xgxr001dir") }) test_that("input.txt/output.txt - unset modelname",{ NMdataConf(reset=TRUE) NMdataConf(as.fun="data.table") NMdataConf(file.mod=identity) NMdataConf(modelname=function(file) basename(dirname(normalizePath(file)))) filedir.lst <- "testData/nonmem/xgxr001dir/output.txt" res1dir <- NMscanData(filedir.lst,check.time = FALSE,merge.by.row=T) NMdataConf(file.mod="default") NMdataConf(modelname=NULL) file.lst <- "testData/nonmem/xgxr001.lst" res1 <- NMscanData(file=file.lst,check.time = FALSE) els.details <- c("call","model","file.lst","file.mod") for(elem in els.details){ attributes(res1)$NMdata$details[elem] <- NULL attributes(res1dir)$NMdata$details[elem] <- NULL } attributes(res1)$NMdata$datafile$DATA <- NULL attributes(res1dir)$NMdata$datafile$DATA <- NULL attributes(res1)$NMdata$datafile$string <- NULL attributes(res1dir)$NMdata$datafile$string <- NULL fix.time(res1) fix.time(res1dir) cols.differ <- c("TVKA","TVCL","TVV3","TVQ","KA","CL","V3","Q","V2","IPRED","PRED","RES","WRES") res1[,(cols.differ):=NULL] res1dir[,(cols.differ):=NULL] expect_equal(res1[,!("model")],res1dir[,!("model")]) NMdataConf(as.fun=NULL) }) test_that("output.txt, file.mod=identity - NMinfo file.mod=output.txt?",{ NMdataConf(reset=TRUE) NMdataConf(as.fun="data.table") NMdataConf(file.mod=identity) NMdataConf(modelname=function(file) basename(dirname(normalizePath(file)))) filedir.lst <- "testData/nonmem/xgxr001dir/output.txt" res1 <- NMscanData(filedir.lst,check.time = FALSE,merge.by.row=F) expect_equal(basename(NMinfo(res1,"details")$file.lst),"output.txt") }) test_that("Duplicate columns in input data",{ NMdataConf(reset=TRUE) fileRef <- "testReference/NMscanData20.rds" file.lst <- "testData/nonmem/xgxr015.lst" res <- expect_warning( NMscanData(file=file.lst,merge.by.row=FALSE,check.time = FALSE) ) fix.time(res) expect_equal_to_reference(res,fileRef,version=2) }) test_that("Modifying row identifier",{ NMdataConf(reset=TRUE) file.lst <- "testData/nonmem/xgxr016.lst" res <- expect_error( NMscanData(file=file.lst,merge.by.row=TRUE,check.time = FALSE) ) }) test_that("merge.by.row=ifAvailable when available",{ fileRef <- "testReference/NMscanData21.rds" file.lst <- system.file("examples/nonmem/xgxr001.lst" ,package="NMdata") res1 <- NMscanData(file=file.lst,merge.by.row="ifAvailable",check.time=FALSE) unNMdata(res1) expect_equal_to_reference(res1,fileRef,version=2) }) test_that("merge.by.row=ifAvailable when not available",{ fileRef <- "testReference/NMscanData22.rds" file.lst <- "testData/nonmem/xgxr004.lst" res1 <- NMscanData(file=file.lst,merge.by.row="ifAvailable",recover.rows = T,as.fun="data.table",check.time = FALSE) dim(res1) res1[,table(nmout,DOSE)] fix.time(res1) expect_equal_to_reference( res1,fileRef,version=2 ) }) test_that(" col.row does not exist, but merge.by.row==TRUE",{ fileRef <- "testReference/NMscanData22b.rds" NMdataConf(reset=T) NMdataConf(check.time=F) file.lst <- system.file("examples/nonmem/xgxr001.lst" ,package="NMdata") res1 <- expect_warning( NMscanData(file=file.lst,col.row="NONEXIST",merge.by.row=TRUE) ) fix.time(res1) expect_equal_to_reference(res1,fileRef) }) test_that("col.row is NULL, but merge.by.row==TRUE",{ file.lst <- system.file("examples/nonmem/xgxr001.lst" ,package="NMdata") expect_error( res1=NMscanData(file=file.lst,col.row=NULL,merge.by.row=TRUE) ) }) test_that("A filter without operator",{ fileRef <- "testReference/NMscanData23.rds" file.lst <- "testData/nonmem/xgxr010.lst" res1 <- NMscanData(file=file.lst,merge.by.row="ifAvailable",as.fun="data.table",check.time = FALSE) res1[,.N,by=.(DOSE)] fix.time(res1) expect_equal_to_reference( res1,fileRef,version=2 ) }) test_that("Including a redundant output table",{ NMdataConf(reset=T) NMdataConf(as.fun="data.table") fileRef <- "testReference/NMscanData24.rds" file.lst <- "testData/nonmem/xgxr019.lst" res1 <- NMscanData(file=file.lst,merge.by.row="ifAvailable",as.fun="data.table",check.time = FALSE) fix.time(res1) expect_equal_to_reference( res1,fileRef,version=2 ) } ) test_that("redundant output",{ NMdataConf(reset=T) NMdataConf(as.fun="data.table") NMdataConf(file.mod=function(x)sub("\\.lst$",".ctl",x)) NMdataConf(check.time=FALSE) fileRef <- "testReference/NMscanData25.rds" file.lst <- "testData/nonmem/estim_debug.ctl" res1 <- expect_warning(NMscanData(file=file.lst)) fix.time(res1) expect_equal_to_reference( res1,fileRef,version=2 ) } ) if(FALSE){ test_that("check time warning",{ NMdataConf(reset=T) fileRef <- "testReference/NMscanData26.rds" dir.test <- "testData/nonmem/check.time" if(dir.exists(dir.test)) unlink(dir.test,recursive=TRUE) dir.create(dir.test) file.copy("testData/nonmem/xgxr001.lst",dir.test) file.copy("testData/nonmem/xgxr001_res.txt",dir.test) file.copy("testData/nonmem/xgxr001.mod",dir.test) file.lst <- file.path(dir.test,"xgxr001.lst") file.mod <- fnExtension(file.lst,".mod") data.new <- sub("../data","../../data",NMreadSection(file.mod,section="data")) NMwriteSection(file.mod,section="data",newlines=data.new) res1 <- expect_warning( NMscanData(file=file.lst, quiet=F, order.columns = F, merge.by.row=FALSE) ) expect_equal_to_reference(unNMdata(res1),fileRef) }) } test_that("$INPUT copy",{ NMdataConf(reset=T) NMdataConf(check.time=FALSE) file.lst.1 <- "testData/nonmem/xgxr022.lst" res.1 <- NMscanData(file.lst.1) NMinfo(res.1,"input.colnames") NMinfo(res.1,"columns") file.lst.2 <- "testData/nonmem/xgxr001.lst" res.2 <- NMscanData(file.lst.2) expect_equal(ncol(res.1)-ncol(res.2),1) expect_equal(setdiff(colnames(res.1),colnames(res.2)),c("COMP","EFF0")) cols.1 <- NMinfo(res.1,"columns") cols.2 <- NMinfo(res.2,"columns") expect_equal(setdiff(cols.1$variable,cols.2$variable),c("COMP","EFF0")) expect_equal(setdiff(cols.2$variable,cols.1$variable),c("eff0")) }) test_that("only firstonly. Has col.id, no col.row.",{ NMdataConf(reset=T) NMdataConf(check.time=FALSE) fileRef <- "testReference/NMscanData27.rds" file.lst <- "testData/nonmem/xgxr023.lst" res <- NMscanData(file.lst,quiet=F) res <- fix.time(res) expect_equal_to_reference(res,fileRef) })
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(abstr) library(abstr) library(tmap) tm_shape(montlake_zones) + tm_polygons(col = "grey") + tm_shape(montlake_buildings) + tm_polygons(col = "blue") + tm_style("classic") head(montlake_od) set.seed(42) montlake_od_minimal = subset(montlake_od, o_id == "373" |o_id == "402" | o_id == "281" | o_id == "588" | o_id == "301" | o_id == "314") output_sf = ab_scenario( od = montlake_od_minimal, zones = montlake_zones, zones_d = NULL, origin_buildings = montlake_buildings, destination_buildings = montlake_buildings, pop_var = 3, time_fun = ab_time_normal, output = "sf", modes = c("Walk", "Bike", "Drive", "Transit") ) tm_shape(output_sf) + tmap::tm_lines(col = "mode", lwd = .8, lwd.legeld.col = "black") + tm_shape(montlake_zones) + tmap::tm_borders(lwd = 1.2, col = "gray") + tm_text("id", size = 0.6) + tm_style("cobalt") output_json = ab_json(output_sf, time_fun = ab_time_normal, scenario_name = "Montlake Example") ab_save(output_json, f = "montlake_scenarios.json") file.remove("montlake_scenarios.json")
context("Geometric operators work with appropriate data") if (has_internet() && identical(Sys.getenv("NOT_CRAN"), "true")) { local <- bcdc_query_geodata("regional-districts-legally-defined-administrative-areas-of-bc") %>% filter(ADMIN_AREA_NAME == "Cariboo Regional District") %>% collect() } test_that("bcdc_check_geom_size outputs message with low threshold",{ skip_on_cran() skip_if_net_down() withr::local_options(list(bcdata.max_geom_pred_size = 1)) expect_message(bcdc_check_geom_size(local)) expect_false(bcdc_check_geom_size(local)) }) test_that("bcdc_check_geom_size is silent with high threshold",{ skip_on_cran() skip_if_net_down() withr::local_options(list(bcdata.max_geom_pred_size = 1E10)) expect_true(bcdc_check_geom_size(local)) }) test_that("WITHIN works",{ skip_on_cran() skip_if_net_down() remote <- suppressWarnings( bcdc_query_geodata("bc-airports") %>% filter(WITHIN(local)) %>% collect() ) expect_is(remote, "sf") expect_equal(attr(remote, "sf_column"), "geometry") }) test_that("INTERSECTS works",{ skip_on_cran() skip_if_net_down() remote <- suppressWarnings( bcdc_query_geodata("bc-parks-ecological-reserves-and-protected-areas") %>% filter(FEATURE_LENGTH_M <= 1000, INTERSECTS(local)) %>% collect() ) expect_is(remote, "sf") expect_equal(attr(remote, "sf_column"), "geometry") }) test_that("RELATE works", { skip("RELATE not supported. https://github.com/bcgov/bcdata/pull/154") skip_on_cran() skip_if_net_down() remote <- suppressWarnings( bcdc_query_geodata("bc-parks-ecological-reserves-and-protected-areas") %>% filter(RELATE(local, "*********")) %>% collect() ) expect_is(remote, "sf") expect_equal(attr(remote, "sf_column"), "geometry") }) test_that("DWITHIN works", { skip_on_cran() skip_if_net_down() remote <- suppressWarnings( bcdc_query_geodata("bc-parks-ecological-reserves-and-protected-areas") %>% filter(DWITHIN(local, 100, "meters")) %>% collect() ) expect_is(remote, "sf") expect_equal(attr(remote, "sf_column"), "geometry") }) test_that("BEYOND works", { skip("BEYOND currently not supported") skip_on_cran() skip_if_net_down() remote <- suppressWarnings( bcdc_query_geodata("bc-parks-ecological-reserves-and-protected-areas") %>% filter(BEYOND(local, 100, "meters")) %>% collect() ) expect_is(remote, "sf") expect_equal(attr(remote, "sf_column"), "geometry") }) test_that("BBOX works with an sf bbox", { skip_on_cran() skip_if_net_down() remote <- suppressWarnings( bcdc_query_geodata("bc-parks-ecological-reserves-and-protected-areas") %>% filter(FEATURE_LENGTH_M <= 1000, BBOX(sf::st_bbox(local))) %>% collect() ) expect_is(remote, "sf") expect_equal(attr(remote, "sf_column"), "geometry") }) test_that("BBOX works with an sf object", { skip_on_cran() skip_if_net_down() remote <- suppressWarnings( bcdc_query_geodata("bc-parks-ecological-reserves-and-protected-areas") %>% filter(FEATURE_LENGTH_M <= 1000, BBOX(local)) %>% collect() ) expect_is(remote, "sf") expect_equal(attr(remote, "sf_column"), "geometry") }) test_that("Other predicates work with an sf bbox", { skip_on_cran() skip_if_net_down() remote <- suppressWarnings( bcdc_query_geodata("bc-parks-ecological-reserves-and-protected-areas") %>% filter(FEATURE_LENGTH_M <= 1000, INTERSECTS(sf::st_bbox(local))) %>% collect() ) expect_is(remote, "sf") expect_equal(attr(remote, "sf_column"), "geometry") })
check_formula <- function(formula) { lf <- lhs(formula) lhC <-as.character(lf) if(is.null(lf)) { }else if(any(lhC == ".")) { lhs(formula) <- quote(NULL) } rh <- rhs(formula) rhC <-as.character(rh) if(is.null(rh)) { rhs(formula) <- quote(.) }else if(any(rhC == ".")) { if(is.null(lhs(formula))) { formula <- ~. }else{ rhs(formula) <- quote(.) } } if(!is.null(lhs(formula))) { lhV <- lhs.vars(formula) if(is.null(attr(lhV,"term.labels"))){ check <- NA for(i in lhV) { check <- (substring(i,1,2) == "I(") if(check) { stop(paste0("The left hand of the formula does not accept the following format: I(expression). Check the following entries: \n", i), call. = FALSE) } } }else{ stop(paste0("The left hand of the formula does not accept the following format: I(expression). Check the following entries: \n", i), call. = FALSE) } } if(rhs(formula) != ".") { rhV <- rhs.vars(formula) check <- NA for(i in rhV) { nch <- nchar(i) check <- (substring(i,1,2) == "I(" & substring(i,nch,nch) == ")") if(!check) { stop(paste0("The right and of the formula requires the following format: I(expression). Check the following entries: \n", i), call. = FALSE) } } } getsVars <- lhs.vars(formula) getsTransf <- formula lhs(getsTransf) <- quote(NULL) return(list(formula = formula, getsVars = getsVars, getsTransf = getsTransf)) } check_formula_names <- function(formula) { lf <- lhs(formula) lhC <-as.character(lf) if(is.null(lf)) { }else if(any(lhC == ".")) { lhs(formula) <- quote(NULL) } rh <- rhs(formula) rhC <-as.character(rh) if(is.null(rh)) { rhs(formula) <- quote(.) }else if(any(rhC == ".")) { } getsVars <- NULL getsTransf <- "." if(!is.null(lhs(formula)) | !rhs(formula) == ".") { if(!is.null(lhs(formula))) { lhV <- lhs.vars(formula) if(is.null(attr(lhV,"term.labels"))){ check <- NA for(i in lhV) { check <- (substring(i,1,2) == "I(") if(check) { stop(paste0("The left hand of the formula does not accept the following format: I(expression). Check the following entries: \n", i), call. = FALSE) } } }else{ stop(paste0("The left hand of the formula does not accept the following format: I(expression). Check the following entries: \n", i), call. = FALSE) } } if(!is.null(rhs(formula))) { rhV <- lhs.vars(formula) check <- NA for(i in rhV) { check <- (substring(i,1,2) == "I(") if(check) { stop(paste0("The right hand of the formula does not accept the following format: I(expression). Check the following entries: \n", i), call. = FALSE) } } } getsVars <- lhs.vars(formula) getsTransf <- rhs.vars(formula) } return(list(formula = formula, getsVars = getsVars, getsTransf = getsTransf)) } check_formula_add <- function(formula, from) { lf <- lhs(formula) lhC <-as.character(lf) if(!is.null(lf)) { if(any(lhC == ".")) { lhs(formula) <- quote(NULL) } } rh <- rhs(formula) rhC <-as.character(rh) if(is.null(rh)) { rhs(formula) <- quote(.) warning("Right side of formula does no allow 'NULL'. The original data are returned.") }else if(any(rhC == ".")) { warning("Right side of formula does no allow '.'. The original data are returned.") if(is.null(lhs(formula))) { formula <- ~. }else{ rhs(formula) <- quote(.) } } if(!is.null(lhs(formula))) { lhV <- lhs.vars(formula) if(is.null(attr(lhV,"term.labels"))){ check <- NA for(i in lhV) { check <- (substring(i,1,2) == "I(") if(check) { stop(paste0("The left hand of the formula does not accept the following format: I(expression). Check the following entries: \n", i), call. = FALSE) } } }else{ stop(paste0("The left hand of the formula does not accept the following format: I(expression). Check the following entries: \n", i), call. = FALSE) } } count <- 0 if(rhs(formula) != ".") { rhV <- rhs.vars(formula) check <- rep(NA,length(rhV)) for(i in rhV) { count <- count + 1 nch <- nchar(i) check[count] <- (substring(i,1,2) == "C(") if(check[count]) { rhV[count] <- paste("constant(","x=",substring(i,3,nch-1), ",nr=",nrow(from),")" ,sep = "") } } if(is.null(lhs(formula))) { colNames <- colnames(from) getsVars <- colNames formula <- as.formula(paste("~", paste(rhV,collapse="+"),sep = "")) }else{ colNames <- (lhs.vars(formula)) getsVars <- lhs.vars(formula) formula <- as.formula(paste("~", paste(rhV,collapse="+"),sep = "")) } count <- length(rhV) err <- NULL if(count == 1) { formula1 <- terms(formula, data = from) env <- environment(formula) vars <- attr(formula1, "variables") err <- try(eval(vars, from, env), silent = TRUE) if(class(err) == "try-error") { formula <- lh_formula_internal(Lnames = colNames, rhs_vars = rhV) } } } getsTransf <- formula lhs(getsTransf) <- quote(NULL) if(is.list(err)) { if(any(check)) { model_frame <- matrix(err[[1]], ncol = length(getsVars), nrow = nrow(from), byrow = FALSE) }else{ model_frame <- matrix(err[[1]], ncol = 1, nrow = nrow(from), byrow = FALSE) } }else{ whc <- getsVars if(is.null(getsVars)) { whc <- colnames(from) } model_frame <- model.frame(formula = getsTransf, data = from[whc], drop.unused.levels = FALSE, na.action = NULL) } return(list(formula = formula, getsVars = getsVars, getsTransf = getsTransf, model_frame = model_frame)) } check_formula_transf <- function(formula, from) { lf <- lhs(formula) lhC <-as.character(lf) if(!is.null(lf)) { if(any(lhC == ".")) { lhs(formula) <- quote(NULL) } } rh <- rhs(formula) rhC <-as.character(rh) if(is.null(rh)) { rhs(formula) <- quote(.) warning("Right side of formula does no allow 'NULL'. The original data are returned.") }else if(any(rhC == ".")) { warning("Right side of formula does no allow '.'. The original data are returned.") if(is.null(lhs(formula))) { formula <- ~. }else{ rhs(formula) <- quote(.) } } if(!is.null(lhs(formula))) { lhV <- lhs.vars(formula) if(is.null(attr(lhV,"term.labels"))){ check <- NA for(i in lhV) { check <- (substring(i,1,2) == "I(") if(check) { stop(paste0("The left hand of the formula does not accept the following format: I(expression). Check the following entries: \n", i), call. = FALSE) } } }else{ stop(paste0("The left hand of the formula does not accept the following format: I(expression). Check the following entries: \n", i), call. = FALSE) } } count <- 0 if(rhs(formula) != ".") { rhV <- rhs.vars(formula) check <- rep(NA,length(rhV)) for(i in rhV) { count <- count + 1 nch <- nchar(i) check[count] <- (substring(i,1,2) == "C(") if(check[count]) { rhV[count] <- paste("constant(","x=",substring(i,3,nch-1), ",nr=",nrow(from),")" ,sep = "") } } if(is.null(lhs(formula))) { colNames <- colnames(from) getsVars <- colNames formula <- as.formula(paste("~", paste(rhV,collapse="+"),sep = "")) }else{ colNames <- (lhs.vars(formula)) getsVars <- lhs.vars(formula) formula <- as.formula(paste("~", paste(rhV,collapse="+"),sep = "")) } count <- length(rhV) err <- NULL if(count == 1) { formula1 <- terms(formula, data = from) env <- environment(formula) vars <- attr(formula1, "variables") err <- try(eval(vars, from, env), silent = TRUE) if(class(err) == "try-error") { formula <- lh_formula_internal(Lnames = colNames, rhs_vars = rhV) } } } getsTransf <- formula lhs(getsTransf) <- quote(NULL) if(is.list(err)) { model_frame <- matrix(err[[1]], ncol = length(getsVars), nrow = nrow(from), byrow = FALSE) }else{ whc <- getsVars if(is.null(getsVars)) { whc <- colnames(from) } model_frame <- model.frame(formula = getsTransf, data = from[whc], drop.unused.levels = FALSE, na.action = NULL) } return(list(formula = formula, getsVars = getsVars, getsTransf = getsTransf, model_frame = model_frame)) } lh_formula_internal <- function(Lnames, rhs_vars) { lh <- paste(Lnames, collapse = "+") ncfunc <- nchar(rhs_vars) if(substring(rhs_vars,1,2) == "I(") { if(substring(rhs_vars,ncfunc-1,ncfunc-1) == ")") { func <- substring(rhs_vars, 3,ncfunc-1) temp <- grep("\\(",unlist(strsplit(func, "")))[1] subL <- substring(func, 1,temp) subR <- substring(func, temp+1,nchar(func)) rh <- paste0("I(",subL,Lnames,",",subR,")", collapse = "+") }else{ func <- substring(rhs_vars, 3, ncfunc-1) rh <- paste0("I(",func,"(",Lnames,"))", collapse = "+") } }else{ if(substring(rhs_vars,ncfunc,ncfunc) == ")") { func <- rhs_vars temp <- grep("\\(",unlist(strsplit(func, "")))[1] subL <- substring(func, 1,temp) subR <- substring(func, temp+1,nchar(func)) rh <- paste0(subL,Lnames,",",subR, collapse = "+") }else{ func <- substring(rhs_vars, 1, ncfunc-2) rh <- paste0(func,"(",Lnames,")", collapse = "+") } } formula <- as.formula(paste(lh,rh,sep = "~")) return(formula) } constant <- function(x, nr,...) { if((length(x)==1)) { x <- rep(x, nr) } return(x) }
testthat::test_that("tab_xl creates an Excel file", { tabs <- purrr::pmap( tibble::tribble( ~row_var, ~col_vars , ~pct , ~filter , ~subtext , "race" , "marital" , "row", NULL , "Source: GSS 2000-2014", "relig" , c("race", "age"), "row", "year %in% 2000:2010", "Source: GSS 2000-2010", NA_character_, "race" , "no" , NULL , "Source: GSS 2000-2014", ), .f = tab_many, data = forcats::gss_cat, color = "auto", chi2 = TRUE) test_path <- file.path(tempdir(), "tab_xl_test.xlsx") tabs %>% tab_xl(path = test_path, sheets = "unique", replace = TRUE, open = FALSE) %>% testthat::expect_invisible() testthat::expect_true(file.exists(test_path)) file.remove(test_path) }) testthat::test_that("tab_xl work with after_ci", { tabs <-tab(forcats::gss_cat, race, marital, pct = "row", color = "after_ci") test_path <- file.path(tempdir(), "tab_xl_test.xlsx") tabs %>% tab_xl(path = test_path, sheets = "unique", replace = TRUE, open = FALSE) %>% testthat::expect_invisible() testthat::expect_true(file.exists(test_path)) file.remove(test_path) })
IniListDims <- function(dims, lenlist) { indices <- as.list(rep(1, lenlist)) for (jdim in 1:min(length(dims), lenlist)) { indices[[jdim]] <- 1:dims[jdim] } indices }
opt.survSplinePH <- function (thetas) { thetas <- relist(thetas, skeleton = list.thetas) gammas <- thetas$gammas alpha <- thetas$alpha Dalpha <- thetas$Dalpha gammas.bs <- thetas$gammas.bs eta.tw1 <- if (!is.null(W1)) as.vector(W1 %*% gammas) else rep(0, n) eta.tw2 <- as.vector(W2 %*% gammas.bs) eta.t <- switch(parameterization, "value" = eta.tw2 + eta.tw1 + c(WintF.vl %*% alpha) * Y, "slope" = eta.tw2 + eta.tw1 + c(WintF.sl %*% Dalpha) * Y.deriv, "both" = eta.tw2 + eta.tw1 + c(WintF.vl %*% alpha) * Y + c(WintF.sl %*% Dalpha) * Y.deriv) eta.s <- switch(parameterization, "value" = c(Ws.intF.vl %*% alpha) * Ys, "slope" = c(Ws.intF.sl %*% Dalpha) * Ys.deriv, "both" = c(Ws.intF.vl %*% alpha) * Ys + c(Ws.intF.sl %*% Dalpha) * Ys.deriv) eta.ws <- as.vector(W2s %*% gammas.bs) log.hazard <- eta.t log.survival <- - exp(eta.tw1) * P * rowsum(wk * exp(eta.ws + eta.s), id.GK, reorder = FALSE) dimnames(log.survival) <- NULL log.p.tb <- rowsum(d * log.hazard + log.survival, idT, reorder = FALSE) p.bytn <- p.byt * log.p.tb -sum(p.bytn %*% wGH, na.rm = TRUE) }
NULL cor_gather <- function(data, drop.na = TRUE){ rowname <- column <- NULL if(inherits(data, "cor_mat")){ cor.value <- data p.value <- data %>% cor_get_pval() } else if(inherits(data, "cor_mat_tri")){ cor.value <- data %>% as_numeric_triangle() p.value <- data %>% cor_get_pval() %>% as_numeric_triangle() } else if(inherits(data, "rcorr")){ cor.value <- data$r %>% as_tibble(rownames = "rowname") p.value <- data$P %>% as_tibble(rownames = "rowname") } else { cor.value <- data %>% as_tibble(rownames = "rowname") p.value <- NULL } cor.value <- cor.value %>% keep_only_tbl_df_classes() %>% gather(key = "column", value = "cor", -rowname) if(!is.null(p.value)){ p.value <- p.value %>% keep_only_tbl_df_classes() %>% gather(key = "column", value = "p", -rowname) cor.value <- cor.value %>% left_join(p.value, by = c("rowname", "column")) colnames(cor.value) <- c("var1", "var2", "cor", "p") } else{ colnames(cor.value) <- c("var1", "var2", "cor") } if(drop.na) cor.value <- cor.value %>% drop_na() cor.value } cor_spread <- function(data, value = "cor"){ if(!(all(c("var1", "var2", value) %in% colnames(data)))){ stop("The input data should contains the columns: var1, var2 and cor") } var1 <- var2 <- cor <- p <- NULL row.vars <- data %>% pull(var1) %>% unique() col.vars <- data %>% pull(var2) %>% unique() res <- data %>% keep_only_tbl_df_classes() %>% select(var1, var2, !!value) %>% spread(key = "var2", value = value) %>% rename(rowname = var1) %>% respect_variables_order(row.vars = row.vars, col.vars = col.vars) colnames(res)[1] <- "rowname" res } respect_variables_order <- function(data, vars, row.vars = vars, col.vars = vars){ data %>% subset_matrix(row.vars = row.vars, col.vars = col.vars) }
`elassens` <- function(A,k,l){ rank <- dim(A)[1] ea <- eigen.analysis(A) lambda <- ea$lambda1 s <- ea$sensitivities skl <- s[k,l] d2 <- secder(A,k,l) delta.kl <- matrix(0,nrow=rank,ncol=rank) delta.kl[k,l] <- 1 es <- (A/lambda) * d2 - (A/lambda^2) * s*skl + delta.kl * s/lambda return(round(es,4)) }
MOs <- subset(microorganisms, !is.na(mo) & nchar(mo) > 3) expect_identical(as.character(MOs$mo), as.character(as.mo(MOs$mo))) expect_identical( as.character(as.mo(c("E. coli", "H. influenzae"))), c("B_ESCHR_COLI", "B_HMPHL_INFL")) expect_equal(as.character(as.mo("Escherichia coli")), "B_ESCHR_COLI") expect_equal(as.character(as.mo("Escherichia coli")), "B_ESCHR_COLI") expect_equal(as.character(as.mo(112283007)), "B_ESCHR_COLI") expect_equal(as.character(as.mo("Escherichia species")), "B_ESCHR") expect_equal(as.character(as.mo("Escherichia")), "B_ESCHR") expect_equal(as.character(as.mo("Esch spp.")), "B_ESCHR") expect_equal(as.character(as.mo(" B_ESCHR_COLI ")), "B_ESCHR_COLI") expect_equal(as.character(as.mo("e coli")), "B_ESCHR_COLI") expect_equal(as.character(as.mo("klpn")), "B_KLBSL_PNMN") expect_equal(as.character(as.mo("Klebsiella")), "B_KLBSL") expect_equal(as.character(as.mo("K. pneu rhino")), "B_KLBSL_PNMN_RHNS") expect_equal(as.character(as.mo("Bartonella")), "B_BRTNL") expect_equal(as.character(as.mo("C. difficile")), "B_CRDDS_DFFC") expect_equal(as.character(as.mo("L. pneumophila")), "B_LGNLL_PNMP") expect_equal(as.character(as.mo("Strepto")), "B_STRPT") expect_equal(as.character(as.mo("Streptococcus")), "B_STRPT") expect_equal(as.character(as.mo("Estreptococos grupo B")), "B_STRPT_GRPB") expect_equal(as.character(as.mo("Group B Streptococci")), "B_STRPT_GRPB") expect_equal(as.character(as.mo(c("mycobacterie", "mycobakterium"))), c("B_MYCBC", "B_MYCBC")) expect_equal(as.character(as.mo(c("GAS", "GBS", "a MGS", "haemoly strep"))), c("B_STRPT_GRPA", "B_STRPT_GRPB", "B_STRPT_MILL", "B_STRPT_HAEM")) expect_equal(as.character(as.mo("S. pyo")), "B_STRPT_PYGN") expect_equal(as.character(as.mo("bctfgr")), "B_BCTRD_FRGL") expect_equal(as.character(as.mo("MRSE")), "B_STPHY_EPDR") expect_equal(as.character(as.mo("VRE")), "B_ENTRC") expect_equal(as.character(as.mo("MRPA")), "B_PSDMN_AERG") expect_equal(as.character(as.mo("PISP")), "B_STRPT_PNMN") expect_equal(as.character(as.mo("PRSP")), "B_STRPT_PNMN") expect_equal(as.character(as.mo("VISP")), "B_STRPT_PNMN") expect_equal(as.character(as.mo("VRSP")), "B_STRPT_PNMN") expect_equal(as.character(as.mo("CNS")), "B_STPHY_CONS") expect_equal(as.character(as.mo("CoNS")), "B_STPHY_CONS") expect_equal(as.character(as.mo("CPS")), "B_STPHY_COPS") expect_equal(as.character(as.mo("CoPS")), "B_STPHY_COPS") expect_equal(as.character(as.mo("VGS")), "B_STRPT_VIRI") expect_equal(as.character(as.mo("streptococcus milleri")), "B_STRPT_MILL") expect_equal(as.character(as.mo(c("Gram negative", "Gram positive"))), c("B_GRAMN", "B_GRAMP")) expect_identical( suppressWarnings(as.character( as.mo(c("stau", "STAU", "staaur", "S. aureus", "S aureus", "Sthafilokkockus aureeuzz", "Staphylococcus aureus", "MRSA", "VISA")))), rep("B_STPHY_AURS", 9)) expect_identical( as.character( as.mo(c("EHEC", "EPEC", "EIEC", "STEC", "ATEC", "UPEC"))), rep("B_ESCHR_COLI", 6)) expect_identical( as.character( as.mo(c("parnod", "P. nodosa", "P nodosa", "Paraburkholderia nodosa"))), rep("B_PRBRK_NODS", 4)) expect_identical(as.character(as.mo(c("", " ", NA, NaN))), rep(NA_character_, 4)) expect_identical(as.character(as.mo(" ")), NA_character_) expect_warning(as.mo("ab")) expect_equal(suppressWarnings(as.character(as.mo(c("Qq species", "", "CRSM", "K. pneu rhino", "esco")))), c("UNKNOWN", NA_character_, "B_STNTR_MLTP", "B_KLBSL_PNMN_RHNS", "B_ESCHR_COLI")) expect_identical(as.character(as.mo("S. epidermidis", Becker = FALSE)), "B_STPHY_EPDR") expect_identical(as.character(as.mo("S. epidermidis", Becker = TRUE)), "B_STPHY_CONS") expect_identical(as.character(as.mo("STAEPI", Becker = TRUE)), "B_STPHY_CONS") expect_identical(as.character(as.mo("Sta intermedius", Becker = FALSE)), "B_STPHY_INTR") expect_identical(as.character(as.mo("Sta intermedius", Becker = TRUE)), "B_STPHY_COPS") expect_identical(as.character(as.mo("STAINT", Becker = TRUE)), "B_STPHY_COPS") expect_identical(as.character(as.mo("STAAUR", Becker = FALSE)), "B_STPHY_AURS") expect_identical(as.character(as.mo("STAAUR", Becker = TRUE)), "B_STPHY_AURS") expect_identical(as.character(as.mo("STAAUR", Becker = "all")), "B_STPHY_COPS") expect_identical(as.character(as.mo("S. pyogenes", Lancefield = FALSE)), "B_STRPT_PYGN") expect_identical(as.character(as.mo("S. pyogenes", Lancefield = TRUE)), "B_STRPT_GRPA") expect_identical(as.character(as.mo("STCPYO", Lancefield = TRUE)), "B_STRPT_GRPA") expect_identical(as.character(as.mo("S. agalactiae", Lancefield = FALSE)), "B_STRPT_AGLC") expect_identical(as.character(as.mo("S. agalactiae", Lancefield = TRUE)), "B_STRPT_GRPB") expect_identical(as.character(suppressWarnings(as.mo("estreptococos grupo B"))), "B_STRPT_GRPB") expect_identical(as.character(as.mo("S. equisimilis", Lancefield = FALSE)), "B_STRPT_DYSG_EQSM") expect_identical(as.character(as.mo("S. equisimilis", Lancefield = TRUE)), "B_STRPT_GRPC") expect_identical(as.character(as.mo("E. faecium", Lancefield = FALSE)), "B_ENTRC_FACM") expect_identical(as.character(as.mo("E. faecium", Lancefield = TRUE)), "B_ENTRC_FACM") expect_identical(as.character(as.mo("E. faecium", Lancefield = "all")), "B_STRPT_GRPD") expect_identical(as.character(as.mo("S. anginosus", Lancefield = FALSE)), "B_STRPT_ANGN") expect_identical(as.character(as.mo("S. anginosus", Lancefield = TRUE)), "B_STRPT_GRPF") expect_identical(as.character(as.mo("S. sanguinis", Lancefield = FALSE)), "B_STRPT_SNGN") expect_identical(as.character(as.mo("S. sanguinis", Lancefield = TRUE)), "B_STRPT_GRPH") expect_identical(as.character(as.mo("S. salivarius", Lancefield = FALSE)), "B_STRPT_SLVR") expect_identical(as.character(as.mo("S. salivarius", Lancefield = TRUE)), "B_STRPT_GRPK") if (AMR:::pkg_is_available("dplyr", min_version = "1.0.0")) { expect_identical( example_isolates[1:10, ] %>% left_join_microorganisms() %>% select(genus) %>% as.mo() %>% as.character(), c("B_ESCHR", "B_ESCHR", "B_STPHY", "B_STPHY", "B_STPHY", "B_STPHY", "B_STPHY", "B_STPHY", "B_STPHY", "B_STPHY")) expect_identical( example_isolates[1:10, ] %>% pull(mo), example_isolates[1:10, ] %>% left_join_microorganisms() %>% select(genus, species) %>% as.mo()) expect_error(example_isolates %>% select(1:3) %>% as.mo()) expect_equal(nrow(example_isolates %>% mutate(mo = as.mo(mo))), 2000) expect_true(example_isolates %>% pull(mo) %>% is.mo()) } expect_warning(as.mo(c("INVALID", "Yeah, unknown"))) expect_stdout(print(as.mo(c("B_ESCHR_COLI", NA)))) expect_equal(nrow(data.frame(test = as.mo("B_ESCHR_COLI"))), 1) expect_equal(as.character(suppressWarnings(as.mo(""))), NA_character_) expect_equal(as.character(as.mo("Gomphosphaeria aponina delicatula")), "B_GMPHS_APNN_DLCT") expect_equal(as.character(as.mo("Gomphosphaeria apo del")), "B_GMPHS_APNN_DLCT") expect_equal(as.character(as.mo("G apo deli")), "B_GMPHS_APNN_DLCT") expect_equal(as.character(as.mo("Gomphosphaeria aponina")), "B_GMPHS_APNN") expect_equal(as.character(as.mo("Gomphosphaeria species")), "B_GMPHS") expect_equal(as.character(as.mo("Gomphosphaeria")), "B_GMPHS") expect_equal(as.character(as.mo(" B_GMPHS_APNN ")), "B_GMPHS_APNN") expect_equal(as.character(as.mo("g aponina")), "B_GMPHS_APNN") expect_equal(suppressMessages(as.character(as.mo("Escherichia blattae"))), "B_SHMWL_BLTT") print(mo_renamed()) expect_equal(suppressMessages(as.character(as.mo(c("E. coli", "Chlamydo psittaci")))), c("B_ESCHR_COLI", "B_CHLMY_PSTT")) expect_equal(suppressMessages(as.character(as.mo("staaur extratest", allow_uncertain = TRUE))), "B_STPHY_AURS") expect_equal(suppressWarnings(as.character(as.mo("staaur extratest", allow_uncertain = FALSE))), "UNKNOWN") expect_message(as.mo("e coli extra_text", allow_uncertain = TRUE)) expect_equal(suppressMessages(as.character(as.mo("unexisting aureus", allow_uncertain = 3))), "B_STPHY_AURS") expect_equal(suppressMessages(as.character(as.mo("unexisting staphy", allow_uncertain = 3))), "B_STPHY_COPS") expect_equal(suppressMessages(as.character(as.mo(c("s aure THISISATEST", "Staphylococcus aureus unexisting"), allow_uncertain = 3))), c("B_STPHY_AURS_AURS", "B_STPHY_AURS_AURS")) expect_equal(as.character(as.mo("TestingOwnID", reference_df = data.frame(mycol = "TestingOwnID", mo = "B_ESCHR_COLI"))), "B_ESCHR_COLI") expect_equal(as.character(as.mo(c("TestingOwnID", "E. coli"), reference_df = data.frame(mycol = "TestingOwnID", mo = "B_ESCHR_COLI"))), c("B_ESCHR_COLI", "B_ESCHR_COLI")) expect_warning(as.mo("TestingOwnID", reference_df = NULL)) expect_error(as.mo("E. coli", reference_df = data.frame(mycol = "TestingOwnID"))) expect_identical(as.character(as.mo(c("B_ESCHR_COL", "ESCCOL"))), c("B_ESCHR_COLI", "B_ESCHR_COLI")) expect_equal(as.character(as.mo( c("PRTMIR", "bclcer", "B_ESCHR_COLI"))), c("B_PROTS_MRBL", "B_BCLLS_CERS", "B_ESCHR_COLI")) expect_equal(as.character(suppressMessages(as.mo( c("Microbacterium paraoxidans", "Streptococcus suis (bovis gr)", "Raoultella (here some text) terrigena")))), c("B_MCRBC_PRXY", "B_STRPT_SUIS", "B_RLTLL_TRRG")) expect_stdout(print(mo_uncertainties())) x <- as.mo("S. aur") expect_stdout(print(mo_uncertainties())) expect_equal(suppressMessages(as.mo(c("Salmonella Goettingen", "Salmonella Typhimurium", "Salmonella Group A"))), as.mo(c("Salmonella enterica", "Salmonella enterica", "Salmonella"))) expect_equal(as.character(as.mo("Virus")), NA_character_) expect_equal(length(summary(example_isolates$mo)), 6) expect_equal(as.character(as.mo(c("xxx", "na", "nan"), debug = TRUE)), rep(NA_character_, 3)) expect_equal(as.character(as.mo("con")), "UNKNOWN") expect_equal(as.character(as.mo("xxx")), NA_character_) expect_equal(as.character(as.mo(c("xxx", "con", "eco"))), c(NA_character_, "UNKNOWN", "B_ESCHR_COLI")) expect_equal(as.character(as.mo(c("other", "none", "unknown"))), rep("UNKNOWN", 3)) expect_null(mo_failures()) expect_error(translate_allow_uncertain(5)) expect_stdout(print(suppressMessages(suppressWarnings(as.mo("kshgcjkhsdgkshjdfsfvsdfv", debug = TRUE, allow_uncertain = 3))))) expect_equal(as.character(as.mo(c("meningococ", "gonococ", "pneumococ"))), c("B_NESSR_MNNG", "B_NESSR_GNRR", "B_STRPT_PNMN")) expect_equal(suppressWarnings(as.character(as.mo(c("yeasts", "fungi")))), c("F_YEAST", "F_FUNGUS")) if (AMR:::pkg_is_available("dplyr", min_version = "1.0.0")) { expect_stdout(print(tibble(mo = as.mo("B_ESCHR_COLI")))) } x <- example_isolates$mo expect_inherits(x[1], "mo") expect_inherits(x[[1]], "mo") expect_inherits(c(x[1], x[9]), "mo") expect_warning(x[1] <- "invalid code") expect_warning(x[[1]] <- "invalid code") expect_warning(c(x[1], "test")) expect_equal(as.character(as.mo(c("E. coli", "E. coli ignorethis"), ignore_pattern = "this")), c("B_ESCHR_COLI", NA)) if (AMR:::pkg_is_available("cleaner")) { expect_inherits(cleaner::freq(example_isolates$mo), "freq") }
DPMGibbsN_parallel <- function (Ncpus, type_connec, z, hyperG0, a=0.0001, b=0.0001, N, doPlot=TRUE, nbclust_init=30, plotevery=N/10, diagVar=TRUE, use_variance_hyperprior=TRUE, verbose=TRUE, monitorfile="", ...){ dpmclus <- NULL if(!requireNamespace("itertools", quietly=TRUE)){ stop("Package 'itertools' is not available.\n -> Try running 'install.packages(\"itertools\")'\n or use non parallel version of the function: 'DPMGibbsN'") }else{ requireNamespace("itertools", quietly=TRUE) } if(!requireNamespace("doParallel", quietly=TRUE)){ stop("Package 'doParallel' is not available.\n -> Try running 'install.packages(\"doParallel\")'\n or use non parallel version of the function: 'DPMGibbsN'") }else{ requireNamespace("doParallel", quietly=TRUE) cl <- parallel::makeCluster(Ncpus, type = type_connec, outfile=monitorfile) doParallel::registerDoParallel(cl) if(doPlot){requireNamespace("ggplot2", quietly=TRUE)} p <- dim(z)[1] n <- dim(z)[2] U_xi <- matrix(0, nrow=p, ncol=n) U_psi <- matrix(0, nrow=p, ncol=n) U_Sigma = array(0, dim=c(p, p, n)) U_df = rep(10,n) U_B = array(0, dim=c(2, 2, n)) U_nu <- rep(p,n) if(Ncpus<2){ warning("Only 1 core specified\n=> non-parallel version of the algorithm would be more efficient") } p <- nrow(z) n <- ncol(z) U_mu <- matrix(0, nrow=p, ncol=n) U_Sigma = array(0, dim=c(p, p, n)) listU_mu<-list() listU_Sigma<-list() par_ind <- list() temp_ind <- 0 if(Ncpus>1){ nb_simult <- floor(n%/%(Ncpus)) for(i in 1:(Ncpus-1)){ par_ind[[i]] <- temp_ind + 1:nb_simult temp_ind <- temp_ind + nb_simult } par_ind[[Ncpus]] <- (temp_ind+1):n } else{ cat("Only 1 core specified\n=> non-parallel version of the algorithm would be more efficient", file=monitorfile, append = TRUE) nb_simult <- n par_ind[[Ncpus]] <- (temp_ind+1):n } U_SS <- list() U_SS_list <- list() c_list <- list() weights_list <- list() logposterior_list <- list() m <- numeric(n) c <-numeric(n) i <- 1 if(n<nbclust_init){ for (k in 1:n){ c[k] <- k U_SS[[k]] <- update_SS(z=z[, k, drop=FALSE], S=hyperG0, hyperprior = NULL) NiW <- rNiW(U_SS[[k]], diagVar=diagVar) U_mu[, k] <- NiW[["mu"]] U_SS[[k]][["mu"]] <- NiW[["mu"]] U_Sigma[, , k] <- NiW[["S"]] U_SS[[k]][["S"]] <- NiW[["S"]] m[k] <- m[k]+1 U_SS[[k]][["weight"]] <- 1/n } } else{ c <- sample(x=1:nbclust_init, size=n, replace=TRUE) for (k in unique(c)){ obs_k <- which(c==k) U_SS[[k]] <- update_SS(z=z[, obs_k,drop=FALSE], S=hyperG0) NiW <- rNiW(U_SS[[k]], diagVar=diagVar) U_mu[, k] <- NiW[["mu"]] U_SS[[k]][["mu"]] <- NiW[["mu"]] U_Sigma[, , k] <- NiW[["S"]] U_SS[[k]][["S"]] <- NiW[["S"]] m[k] <- length(obs_k) U_SS[[k]][["weight"]] <- m[k]/n } } listU_mu[[i]]<-U_mu listU_Sigma[[i]]<-U_Sigma alpha <- c(log(n)) U_SS_list[[i]] <- U_SS c_list[[i]] <- c weights_list[[i]] <- numeric(length(m)) weights_list[[i]][unique(c)] <- table(c)/length(c) logposterior_list[[i]] <- logposterior_DPMG(z, mu=U_mu, Sigma=U_Sigma, hyper=hyperG0, c=c, m=m, alpha=alpha[i], n=n, a=a, b=b, diagVar) if(verbose){ cat(i, "/", N, " samplings:\n", sep="") cat(" logposterior = ", sum(logposterior_list[[i]]), "\n", sep="") cl2print <- unique(c) cat(" ",length(cl2print), "clusters:", cl2print[order(cl2print)], "\n\n") } if(doPlot){ plot_DPM(z=z, U_mu=U_mu, U_Sigma=U_Sigma, m=m, c=c, i=i, alpha=alpha[length(alpha)], U_SS=U_SS, ...) }else if(verbose){ cl2print <- unique(c) cat(length(cl2print), "clusters:", cl2print[order(cl2print)], "\n\n") } for(i in 2:N){ nbClust <- length(unique(c)) alpha <- c(alpha, sample_alpha(alpha_old=alpha[i-1], n=n, K=nbClust, a=a, b=b) ) slice <- sliceSampler_N_parallel(Ncpus=Ncpus, c=c, m=m, alpha=alpha[i], z=z, hyperG0=hyperG0, U_mu=U_mu, U_Sigma=U_Sigma, diagVar=diagVar) m <- slice[["m"]] c <- slice[["c"]] weights_list[[i]] <- slice[["weights"]] U_mu<-slice[["U_mu"]] U_Sigma<-slice[["U_Sigma"]] fullCl <- which(m!=0) for(j in fullCl){ obs_j <- which(c==j) if(use_variance_hyperprior){ U_SS[[j]] <- update_SS(z=z[, obs_j,drop=FALSE], S=hyperG0, hyperprior = list("Sigma"=U_Sigma[,,j])) }else{ U_SS[[j]] <- update_SS(z=z[, obs_j,drop=FALSE], S=hyperG0) } NiW <- rNiW(U_SS[[j]], diagVar=diagVar) U_mu[, j] <- NiW[["mu"]] U_SS[[j]][["mu"]] <- NiW[["mu"]] U_Sigma[, , j] <- NiW[["S"]] U_SS[[j]][["S"]] <- NiW[["S"]] U_SS[[j]][["weight"]] <- weights_list[[i]][j] } listU_mu[[i]]<-U_mu listU_Sigma[[i]]<-U_Sigma U_SS_list[[i]] <- U_SS[which(m!=0)] c_list[[i]] <- c logposterior_list[[i]] <- logposterior_DPMG(z, mu=U_mu, Sigma=U_Sigma, hyper=hyperG0, c=c, m=m, alpha=alpha[i], n=n, a=a, b=b, diagVar) if(verbose){ cat(i, "/", N, " samplings:\n", sep="") cat(" logposterior = ", sum(logposterior_list[[i]]) , "\n", sep="") cl2print <- unique(c) cat(" ",length(cl2print), "clusters:", cl2print[order(cl2print)], "\n\n") } if(doPlot && i/plotevery==floor(i/plotevery)){ plot_DPM(z=z, U_mu=U_mu, U_Sigma=U_Sigma, m=m, c=c, i=i, alpha=alpha[length(alpha)], U_SS=U_SS, ...) } } parallel::stopCluster(cl) dpmclus <- list("mcmc_partitions" = c_list, "alpha"=alpha, "listU_mu"=listU_mu, "listU_Sigma"=listU_Sigma, "U_SS_list"=U_SS_list, "weights_list"=weights_list, "logposterior_list"=logposterior_list, "data"=z, "nb_mcmcit"=N, "clust_distrib"="gaussian", "hyperG0"=hyperG0) class(dpmclus) <- "DPMMclust" } return(dpmclus) }
setGeneric( "descriptor", function(object, ...){ standardGeneric( "descriptor" ) } ) setMethod( "descriptor", "Message", function(object, ...){ .Call( "Message__descriptor", object@pointer, PACKAGE = "RProtoBuf" ) } ) setGeneric( "fileDescriptor", function(object, ...){ standardGeneric( "fileDescriptor" ) } ) setMethod( "fileDescriptor", "Message", function(object, ...){ .Call( "Message__fileDescriptor", object@pointer, PACKAGE = "RProtoBuf" ) } ) setMethod( "fileDescriptor", "Descriptor", function(object, ...){ .Call( "Descriptor__fileDescriptor", object@pointer, PACKAGE = "RProtoBuf" ) } ) setMethod( "fileDescriptor", "EnumDescriptor", function(object, ...){ .Call( "EnumDescriptor__fileDescriptor", object@pointer, PACKAGE = "RProtoBuf" ) } ) setMethod( "fileDescriptor", "FieldDescriptor", function(object, ...){ .Call( "FieldDescriptor__fileDescriptor", object@pointer, PACKAGE = "RProtoBuf" ) } ) setMethod( "fileDescriptor", "ServiceDescriptor", function(object, ...){ .Call( "ServiceDescriptor__fileDescriptor", object@pointer, PACKAGE = "RProtoBuf" ) } ) setMethod( "fileDescriptor", "MethodDescriptor", function(object, ...){ .Call( "MethodDescriptor__fileDescriptor", object@pointer, PACKAGE = "RProtoBuf" ) } )
context("random matrix") n=10 a=Matrix::Matrix(0, n, n) set.seed(7) ij=sample(1:(n*n), 5*n) a[ij]=runif(ij) diag(a)=0 diag(a)=-Matrix::rowSums(a) a[1,1]=a[1,1]-1 am=Rmumps$new(a) b=as.double(a%*%(1:n)) x=am$solve(b) test_that("first solving", { expect_equal(x, 1:n) }) bb=2*b xx=solve(am, bb) test_that("second solving", { expect_equal(xx, 2*(1:n)) }) bt=as.double(Matrix::crossprod(a, 1:n)) xt=solvet(am, bt) test_that("solving transposed system", { expect_equal(xt, 1:n) }) asy=a+Matrix::t(a) bsy=as.double(asy%*%(1:n)) asl=asy asl[row(asy)>col(asy)]=0. ams=Rmumps$new(asl, sym=1) xsy=solve(ams, bsy) test_that("solving symmetric-1 system", { expect_equal(xsy, 1:n) }) ams=Rmumps$new(asl, sym=2) xsy=solve(ams, bsy) test_that("solving symmetric-2 system", { expect_equal(xsy, 1:n) }) a=as(a, "dgTMatrix") ai=Rmumps$new(a@i, a@j, a@x, ncol(a)) ai$set_permutation(RMUMPS_PERM_SCOTCH) xi=solve(ai, b) test_that("testing a from i,j,v", { expect_equal(xi, 1:n) }) rm(ai) if (getRversion() >= "3.4.0") { asl=as.simple_triplet_matrix(a) ai=Rmumps$new(asl) xi=solve(ai, b) test_that("testing matrix from slam::simple_triplet_matrix", { expect_equal(xi, 1:n) }) code=' NumericVector solve_ptr(List a, NumericVector b) { IntegerVector ir=a["i"], jc=a["j"]; NumericVector v=a["v"]; int n=a["nrow"], nz=v.size(); Rmumps rmu((int *) ir.begin(), (int *) jc.begin(), (double *) v.begin(), n, nz, 0); rmu.set_permutation(RMUMPS_PERM_SCOTCH); rmu.solveptr((double *) b.begin(), n, 1); return(b); } ' if (FALSE && Sys.info()[["sysname"]] != "Darwin" && .Platform$r_arch != "i386") { rso=paste0("rmumps", .Platform$dynlib.ext) rso_path=file.path(path.package("rmumps"), "libs", .Platform$r_arch, rso) cat("rso_path=", rso_path, "\n") if (!file.exists(rso_path)) rso_path=file.path(path.package("rmumps"), "src", rso) Sys.setenv(PKG_LIBS=rso_path) cppFunction(code=code, depends="rmumps", verbose=TRUE) xe=as.double(1:n) b0=slam::tcrossprod_simple_triplet_matrix(asl, t(xe)) x=solve_ptr(asl, b0) test_that("testing solveptr() within Rcpp code", { expect_lt(diff(range(x-xe)), 1e-14) }) } rm(asl) asl=slam::as.simple_triplet_matrix(a) eye=solve(ai, asl) test_that("testing solve() on slam::simple_triplet_matrix", { expect_equal(eye, diag(n), tol=1e-14) }) rm(ai, asl) } rm(am) a=as(diag(n), "dgCMatrix") a@p[2L]=0L am=Rmumps$new(a) test_that("singular matrix", { expect_error(solve(am, b), "rmumps: job=6, info\\[1\\]=-10*") }) vkeep=am$get_keep() sizeint=Rcpp::evalCpp("sizeof(int)") test_that("int size", { expect_equal(vkeep[34], sizeint) expect_equal(vkeep[10], 8/sizeint) }) rm(a, asy, am) gc()
`print.rda_pertables` <- function (x, ...) { n <- x$simulation$rda.quant[, -3] cat("\n") cat("Confidence intervals of R-squared and pseudo-F values for RDA under different taxonomic scenarios", "\n\n") print(n) }
rm(list=ls()) setwd("C:/Users/Tom/Documents/Kaggle/Facebook/Exploratory analysis") library(data.table) library(bit64) library(ggplot2) library(plotly) library(viridis) library(ggvis) targetDate <- "23-05-2016" dayHourOffset <- 0 sampleSize <- NA train <- readRDS("../Data/train.rds") if(!is.na(sampleSize)){ train <- train[sample(1:nrow(train), sampleSize)] } train <- train[order(time)] summaryFilePath <- paste0("../Feature engineering/", targetDate, "/test summary features.rds") placeSummary <- readRDS(summaryFilePath) train[,totalDay := floor((time + dayHourOffset)/(1440))] train[,week := floor(time/(1440*7))] train[,matchIds := match(place_id, placeSummary$place_id)] train[,count := placeSummary[matchIds,count]] train[,xVar := abs(x-placeSummary[matchIds,medX])] train[,yVar := abs(y-placeSummary[matchIds,medY])] train <- train[count>=20,] train[,accuracyGroup := cut_number(accuracy, 30)] train[,timeGroup := cut_number(time, 6)] accSummary <- train[, list(.N, meanXVar = mean(xVar), medianXVar = median(xVar), meanYVar = mean(yVar), medianYVar = median(yVar)), by=accuracyGroup] accSummary <- accSummary[order(accuracyGroup),] xVarMax <- max(accSummary$medianXVar[1:(nrow(accSummary)-1)]) p <- ggplot(accSummary, aes(x=accuracyGroup, y=medianXVar)) + geom_point() + ylim(c(NA,xVarMax)) print(p) yVarMax <- max(accSummary$medianYVar[1:(nrow(accSummary)-1)]) q <- ggplot(accSummary, aes(x=accuracyGroup, y=medianYVar)) + geom_point() + ylim(c(NA,yVarMax)) print(q) accTimeSummary <- train[, list(.N, as.numeric(median(accuracy))), by=list(accuracyGroup, timeGroup)] accTimeSummary <- train[, list(meanXVar = mean(xVar), medianXVar = median(xVar), meanYVar = mean(yVar), medianYVar = median(yVar), count = length(x)), by=list(accuracyGroup, timeGroup)] accTimeSummary <- accTimeSummary[order(accuracyGroup),] r <- ggplot(accTimeSummary, aes(x=accuracyGroup, y=meanXVar, shape=timeGroup, col=timeGroup)) + geom_point() + theme(axis.text.x=element_text(angle = -90, hjust = 0)) print(r)
library(RProtoBuf) serialize_pb(c(1,2,pi, NA,NaN,Inf,-Inf), "double.msg") serialize_pb(c(1L, 2L, NA), "integer.msg") serialize_pb(c(TRUE, FALSE, NA), "logical.msg") serialize_pb(c("foo", "bar", NA), "character.msg") serialize_pb(charToRaw("This is a test"), "raw.msg") serialize_pb(list(foo=c(1,2,pi), bar=TRUE, baz="blabla", zoo=NULL), "list.msg") serialize_pb(iris[1:3,], "dataframe.msg")
library(fpp) plot(a10) tute1 = read.csv('tute1.csv') head(tute1) tail(tute1) tute1[,2] tute1[,"Sales"] tute1[5,] tute1[1:10,3:4] tute1[1:20,] tute1 <- ts(tute1[,-1], start=1981, frequency=4) plot(tute1) seasonplot(tute1[,"Sales"]) seasonplot(tute1[,"AdBudget"]) seasonplot(tute1[,"GDP"]) monthplot(tute1[,"Sales"]) monthplot(tute1[,"GDP"]) monthplot(tute1[,"AdBudget"]) plot(Sales ~ AdBudget, data=tute1) plot(Sales ~ GDP, data=tute1) pairs(as.data.frame(tute1)) summary(tute1) hist(tute1[,"Sales"]) hist(tute1[,"AdBudget"]) boxplot(tute1[,"Sales"]) boxplot(as.data.frame(tute1)) cor.test(tute1[,"Sales"],tute1[,"AdBudget"]) par(mfrow=c(2,2)) str(hsales) ;head(hsales) plot(hsales,xlab="Year",ylab="Monthly housing sales (millions)") str(ustreas) plot(ustreas,xlab="Day",ylab="US treasury bill contracts") str(elec) plot(elec,xlab="Year",ylab="Australian monthly electricity production") str(dj) plot(diff(dj),xlab="Day",ylab="Daily change in Dow Jones index") fit <- stl(elecequip, s.window=5) plot(elecequip, col="gray", main="Electrical equipment manufacturing", ylab="New orders index", xlab="") lines(fit$time.series[,2],col="red",ylab="Trend") plot(fit) monthplot(fit$time.series[,"seasonal"], main="", ylab="Seasonal") plot(elecequip, col="grey", main="Electrical equipment manufacturing", xlab="", ylab="New orders index") lines(seasadj(fit),col="red",ylab="Seasonally adjusted") ma(elecsales, order=5) str(ausbeer) beer2 <- window(ausbeer,start=1992) ma4 <- ma(beer2, order=4, centre=FALSE) ma4 ma2x4 <- ma(beer2, order=4, centre=TRUE) ma2x4 plot(elecequip, ylab="New orders index", col="gray", main="Electrical equipment manufacturing (Euro area)") lines(ma(elecequip, order=12), col="red") fit <- stl(elecequip, t.window=15, s.window="periodic", robust=TRUE) plot(fit) x = data1 x fit <- decompose(x, type="multiplicative") plot(fit) fit <- stl(elecequip, t.window=15, s.window="periodic", robust=TRUE) eeadj <- seasadj(fit) plot(naive(eeadj), xlab="New orders index", main="Naive forecasts of seasonally adjusted data") fcast <- forecast(fit, method="naive") plot(fcast, ylab="New orders index")
collapse_occurrences <- function(parsedSource, collapseBy = "stanzaId", columns = NULL, logical = FALSE) { if (!("rock_parsedSource" %in% class(parsedSource))) { stop("As argument `parsedSource`, you must specify a parsed source, ", "as provided by the `rock::parse_source` function!"); } if (is.null(columns)) { columns <- unlist(parsedSource$convenience$codingLeaves); } if (!(all(columns %in% names(parsedSource$sourceDf)))) { missingCols <- columns[which(!(columns %in% names(parsedSource$sourceDf)))]; stop("Not all columns specified in the `columns` argument exist in ", "the `sourceDf` in the `parsedSource` object you provided.\n\n", "Specifically, these columns were missing: ", vecTxtQ(missingCols), "\n\nAll existing columns are ", vecTxtQ(names(parsedSource$sourceDf)), ")."); } if (!(collapseBy %in% names(parsedSource$sourceDf))) { stop("The columns specified in the `collapseBy` argument does not exist in ", "the `sourceDf` in the `parsedSource` object you provided!"); } sourceDf <- parsedSource$sourceDf[, c(collapseBy, columns), drop=FALSE]; if (logical) { res <- stats::aggregate(sourceDf[, columns], sourceDf[, collapseBy, drop=FALSE], function(x) { if (sum(x) == 0) { return(0); } else { return(1); } }); } else { res <- stats::aggregate(sourceDf[, columns], sourceDf[, collapseBy, drop=FALSE], sum); } names(res)[1] <- collapseBy; return(res); }
marginal.lkl.pb <- function(dat , Nsim=10e+3 , displ=TRUE, Hpar = get("pb.Hpar") , Nsim.min=Nsim, precision=0, show.progress = floor(seq(1, Nsim, length.out = 20 ) ) ) { marginal.lkl(dat=dat, likelihood=dpairbeta, prior=prior.pb, Nsim=Nsim, displ=displ, Hpar=Hpar, Nsim.min=Nsim.min, precision=precision, show.progress=show.progress ) }
.units <- list( short=list( IEC=list( print = c("B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"), check = c("b", "kib", "mib", "gib", "tib", "pib", "eib", "zib", "yib") ), SI=list( print = c("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"), check = c("b", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb") ) ), long=list( IEC=list( print = c("bytes", "kibibytes", "mebibytes", "gibibytes", "tebibytes", "pebibytes", "exbibytes", "zebibytes", "yobibytes"), check = c("bytes", "kibibytes", "mebibytes", "gibibytes", "tebibytes", "pebibytes", "exbibytes", "zebibytes", "yobibytes") ), SI=list( print = c("bytes", "kilobytes", "megabytes", "gigabytes", "terabytes", "petabytes", "exabytes", "zettabytes", "yottabytes"), check = c("bytes", "kilobytes", "megabytes", "gigabytes", "terabytes", "petabytes", "exabytes", "zettabytes", "yottabytes") ) ) ) .units_bits <- list( short=list( IEC=list( print = c("b", "Kib", "Mib", "Gib", "Tib", "Pib", "Eib", "Zib", "Yib"), check = c("b", "kib", "mib", "gib", "tib", "pib", "eib", "zib", "yib") ), SI=list( print = c("b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb"), check = c("b", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb") ) ), long=list( IEC=list( print = c("bits", "kibibits", "mebibits", "gibibits", "tebibits", "pebibits", "exbibits", "zebibits", "yobibits"), check = c("bits", "kibibits", "mebibits", "gibibits", "tebibits", "pebibits", "exbibits", "zebibits", "yobibits") ), SI=list( print = c("bits", "kilobits", "megabits", "gigabits", "terabits", "petabits", "exabits", "zettabits", "yottabits"), check = c("bits", "kilobits", "megabits", "gigabits", "terabits", "petabits", "exabits", "zettabits", "yottabits") ) ) ) .numbers <- data.frame( name=c("Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion", "Sextillion", "Septillion", "Octillion", "Nonillion", "Decillion", "Undecillion", "Duodecillion", "Tredecillion", "Quattuordecillion", "Quindecillion", "Sexdecillion", "Septendecillion", "Octodecillion", "Novemdecillion", "Vigintillion", "Googol", "Centillion"), shorthand=c("k", "m", "b", "t", "q", "qt", "sx", "sp", "ot", "n", "d", "u", "dd", "td", "qtd", "qd", "sxd", "spd", "otd", "nd", "vg", "g", "ct"), exponent=c(3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 100, 303), stringsAsFactors=FALSE )
test_that("aggregation functions warn if na.rm = FALSE", { local_con(simulate_dbi()) sql_mean <- sql_aggregate("MEAN") expect_warning(sql_mean("x"), "Missing values") expect_warning(sql_mean("x", na.rm = TRUE), NA) }) test_that("missing window functions create a warning", { local_con(simulate_dbi()) sim_scalar <- sql_translator() sim_agg <- sql_translator(`+` = sql_infix("+")) sim_win <- sql_translator() expect_warning( sql_variant(sim_scalar, sim_agg, sim_win), "Translator is missing" ) }) test_that("missing aggregate functions filled in", { local_con(simulate_dbi()) sim_scalar <- sql_translator() sim_agg <- sql_translator() sim_win <- sql_translator(mean = function() {}) trans <- sql_variant(sim_scalar, sim_agg, sim_win) expect_error(trans$aggregate$mean(), "only available in a window") }) test_that("output of print method for sql_variant is correct", { sim_trans <- sql_translator(`+` = sql_infix("+")) expect_snapshot(sql_variant(sim_trans, sim_trans, sim_trans)) }) test_that("win_rank() is accepted by the sql_translator", { expect_snapshot( sql_variant( sql_translator( test = win_rank("test") ) ) ) }) test_that("can translate infix expression without parantheses", { expect_equal(translate_sql(!!expr(2 - 1) * x), sql("(2.0 - 1.0) * `x`")) expect_equal(translate_sql(!!expr(2 / 1) * x), sql("(2.0 / 1.0) * `x`")) expect_equal(translate_sql(!!expr(2 * 1) - x), sql("(2.0 * 1.0) - `x`")) }) test_that("unary minus works with expressions", { expect_equal(translate_sql(-!!expr(x+2)), sql("-(`x` + 2.0)")) expect_equal(translate_sql(--x), sql("-(-`x`)")) }) test_that("pad = FALSE works", { local_con(simulate_dbi()) subset <- sql_infix(".", pad = FALSE) expect_equal(subset(ident("df"), ident("x")), sql("`df`.`x`")) }) test_that("sql_prefix checks arguments", { local_con(simulate_dbi()) sin_db <- sql_prefix("SIN", 1) expect_snapshot(error = TRUE, sin_db(sin(1, 2))) expect_snapshot(error = TRUE, sin_db(sin(a = 1))) })
devtools::load_all() library(googledrive) library(tidyverse) googlesheets4:::gs4_auth_testing() ss <- test_sheet_create("googlesheets4-col-types") gs4_browse(ss) df <- tibble( A = list(1, "Missing", 3), B = list(1, "NA", 3), C = c(1, NA, 3), D = 1:3 ) sheet_add(ss, sheet = "NAs") sheet_write(df, ss, sheet = "NAs")
righttri <- function (a = NULL, b = NULL, c = NULL) { checks <- c(a, b, c) if (length(checks) < 2) { stop("There are not at least 2 sides. Try again with at least 2 sides.") } else { if (any(checks == 0)) { stop("Either a, b, or c is 0. Neither a nor b nor c can be 0. Try again.") } else { if (missing(c)) { csquared <- a ^ 2 + b ^ 2 c <- sqrt(csquared) } else if (missing(a)) { asquared <- c ^ 2 - b ^ 2 a <- sqrt(asquared) } else if (missing(b)) { bsquared <- c ^ 2 - a ^ 2 b <- sqrt(bsquared) } csquared <- a ^ 2 + b ^ 2 c <- sqrt(csquared) a1 <- a b1 <- b if (a <= b & b < c) { a <- a b <- b } else { a <- switch("a", a = b1) b <- switch("b", b = a1) } triarea <- 0.5 * a * b altitude <- (a * b) / c R <- c / 2 r <- (a + b - c) / 2 s <- (a + b + c) / 2 Aanglerad <- atan(a / b) Aangle <- Aanglerad * (180 / pi) Banglerad <- atan(b / a) Bangle <- Banglerad * (180 / pi) Cangle <- 180 - Aangle - Bangle check1a <- s == 2 * R + r check1b <- a ^ 2 + b ^ 2 + c ^ 2 == 8 * R ^ 2 check2 <- sin(Aangle * pi / 180) ^ 2 + sin(Bangle * pi / 180) ^ 2 + sin(Cangle * pi / 180) ^ 2 == 2 check3 <- triarea == r * (2 * R + r) check4 <- r == s - c check5 <- altitude == (a * b) / c check6 <- c == 2 * R check7 <- Aangle + Bangle + Cangle == 180 checked <- c(check1a, check1b, check2, check3, check4, check5, check6, check7) if (all(checked) == FALSE) { cat("This is not a right triangle so the Pythagorean theorem will not work.\n") } else { return(list(a = a, b = b, c = c, Aangle = Aangle, Bangle = Bangle, Cangle = Cangle)) } } } }
SparseMatrixVectorAllocator <- function(benchmarkParameters, index) { kernelParameters <- list() kernelParameters$A <- get(benchmarkParameters$matrixObjectName) if (nrow(kernelParameters$A) != benchmarkParameters$numberOfRows[index]) { warning("Actual number of rows in sparse matrix does not match expected number of rows in numberOfRows") } else if (ncol(kernelParameters$A) != benchmarkParameters$numberOfColumns[index]) { warning("Actual number of columns in sparse matrix does not match expected number of columns in numberOfColumns") } s <- ncol(kernelParameters$A) kernelParameters$x <- matrix(stats::rnorm(s), nrow=s, ncol=1) return (kernelParameters) } SparseMatrixVectorMicrobenchmark <- function(benchmarkParameters, kernelParameters) { timings <- system.time({b <- kernelParameters$A %*% kernelParameters$x}) return (timings) } SparseCholeskyAllocator <- function(benchmarkParameters, index) { kernelParameters <- list() kernelParameters$A <- get(benchmarkParameters$matrixObjectName) if (nrow(kernelParameters$A) != benchmarkParameters$numberOfRows[index]) { warning("Actual number of rows in sparse matrix does not match expected number of rows in numberOfRows") } else if (ncol(kernelParameters$A) != benchmarkParameters$numberOfColumns[index]) { warning("Actual number of columns in sparse matrix does not match expected number of columns in numberOfColumns") } return (kernelParameters) } SparseCholeskyMicrobenchmark <- function(benchmarkParameters, kernelParameters) { timings <- system.time({b <- Matrix::Cholesky(kernelParameters$A)}) return (timings) } SparseLuAllocator <- function(benchmarkParameters, index) { kernelParameters <- list() kernelParameters$A <- get(benchmarkParameters$matrixObjectName) kernelParameters$A@factors <- list() if (nrow(kernelParameters$A) != benchmarkParameters$numberOfRows[index]) { warning("Actual number of rows in sparse matrix does not match expected number of rows in numberOfRows") } else if (ncol(kernelParameters$A) != benchmarkParameters$numberOfColumns[index]) { warning("Actual number of columns in sparse matrix does not match expected number of columns in numberOfColumns") } return (kernelParameters) } SparseLuMicrobenchmark <- function(benchmarkParameters, kernelParameters) { timings <- system.time({b <- Matrix::lu(kernelParameters$A)}) return (timings) } SparseQrAllocator <- function(benchmarkParameters, index) { kernelParameters <- list() kernelParameters$A <- get(benchmarkParameters$matrixObjectName) if (nrow(kernelParameters$A) != benchmarkParameters$numberOfRows[index]) { warning("Actual number of rows in sparse matrix does not match expected number of rows in numberOfRows") } else if (ncol(kernelParameters$A) != benchmarkParameters$numberOfColumns[index]) { warning("Actual number of columns in sparse matrix does not match expected number of columns in numberOfColumns") } return (kernelParameters) } SparseQrMicrobenchmark <- function(benchmarkParameters, kernelParameters) { timings <- system.time({b <- Matrix::qr(kernelParameters$A)}) return (timings) }
tuneMultiCritRandom = function(learner, task, resampling, measures, par.set, control, opt.path, show.info, resample.fun) { vals = sampleValues(n = control$extra.args$maxit, par = par.set, trafo = FALSE) evalOptimizationStatesTune(learner, task, resampling, measures, par.set, control, opt.path, show.info, vals, dobs = seq_along(vals), eols = NA_integer_, remove.nas = TRUE, resample.fun = resample.fun) makeTuneMultiCritResultFromOptPath(learner, par.set, measures, resampling, control, opt.path) }
bayessurvreg1.writeHeaders <- function(dir, prior, store, nX, X, names.random, ncluster, nrandom, rnamesX, unique.cluster, nBetaBlocks, nbBlocks) { FILES <- dir(dir) sink(paste(dir, "/iteration.sim", sep = ""), append = FALSE) cat("iteration", "\n"); sink() sink(paste(dir, "/loglik.sim", sep = ""), append = FALSE) cat("loglik", "randomloglik", "\n", sep = " "); sink() sink(paste(dir, "/mweight.sim", sep = ""), append = FALSE) cat(paste("w", 1:prior$kmax, sep = ""), "\n", sep = " "); sink() sink(paste(dir, "/mmean.sim", sep = ""), append = FALSE) cat(paste("mu", 1:prior$kmax, sep = ""), "\n", sep = " "); sink() sink(paste(dir, "/mvariance.sim", sep = ""), append = FALSE) cat(paste("sigma2", 1:prior$kmax, sep = ""), "\n", sep = " "); sink() sink(paste(dir, "/mixmoment.sim", sep = ""), append = FALSE) cat(" k", " Intercept", " Scale", "\n", sep = " "); sink() if (nX){ sink(paste(dir, "/beta.sim", sep = ""), append = FALSE) cat(colnames(X), "\n", sep = " "); sink() } else if ("beta.sim" %in% FILES) file.remove(paste(dir, "/beta.sim", sep = "")) if (store$b){ sink(paste(dir, "/b.sim", sep = ""), append = FALSE) cat(paste(rep(names.random, ncluster), ".", rep(unique.cluster, rep(nrandom, ncluster)), sep = ""), "\n", sep = " "); sink() } else if ("b.sim" %in% FILES) file.remove(paste(dir, "/b.sim", sep = "")) if (nrandom){ sink(paste(dir, "/D.sim", sep = ""), append = FALSE) D <- diag(nrandom) rows <- row(D)[lower.tri(row(D), diag = TRUE)] cols <- col(D)[lower.tri(col(D), diag = TRUE)] cat("det", paste("D.", rows, ".", cols, sep = ""), "\n", sep = " "); sink() } else if ("D.sim" %in% FILES) file.remove(paste(dir, "/D.sim", sep = "")) if (store$y){sink(paste(dir, "/Y.sim", sep = ""), append = FALSE) cat(paste("Y", rnamesX, sep = ""), "\n", sep = " "); sink() } else if ("Y.sim" %in% FILES) file.remove(paste(dir, "/Y.sim", sep = "")) if (store$r){sink(paste(dir, "/r.sim", sep = ""), append = FALSE) cat(paste("r", rnamesX, sep = ""), "\n", sep = " "); sink() } else if ("r.sim" %in% FILES) file.remove(paste(dir, "/r.sim", sep = "")) sink(paste(dir, "/otherp.sim", sep = ""), append = FALSE) cat("eta", "\n", sep = " "); sink() sink(paste(dir, "/MHinfo.sim", sep = ""), append = FALSE) cat("accept.spl.comb", "split", "accept.birth.death", "birth ", sep = " ") if (nX > 0) cat(paste("beta.block.", 1:nBetaBlocks, sep = ""), " ", sep = " ") cat("\n", sep = " "); sink() if (store$MHb & nrandom > 0){ sink(paste(dir, "/MHbinfo.sim", sep = ""), append = FALSE) cat(paste("b.block.", rep(1:nbBlocks, ncluster), ".", rep(unique.cluster, rep(nbBlocks, ncluster)), "", sep = ""), sep = " ") cat("\n", sep = " "); sink() } else if ("MHbinfo.sim" %in% FILES) file.remove(paste(dir, "/MHbinfo.sim", sep = "")) if (store$u){ sink(paste(dir, "/u.sim", sep = ""), append = FALSE) headeru <- paste(" u.", rep(1:prior$kmax, rep(3, prior$kmax)), ".", rep(1:3, prior$kmax), sep = "") headeru[1] <- " mood"; headeru[2] <- " u.0.0"; headeru[3] <- " u.0.0" cat(headeru, "\n", sep = " "); sink() } else if ("u.sim" %in% FILES) file.remove(paste(dir, "/u.sim", sep = "")) if (store$regresres){sink(paste(dir, "/regresres.sim", sep = ""), append = FALSE) cat(paste("res", rnamesX, sep = ""), "\n", sep = " "); sink() } else if ("regresres.sim" %in% FILES) file.remove(paste(dir, "/regresres.sim", sep = "")) }
multisub <- function(pattern, replacement, x, ...) { if (length(pattern) != length(replacement)) { stop("The pattern and replacement vectors should have the same length.") } res <- x for (i in 1:length(pattern)) { res <- gsub(pattern[i], replacement[i], res, ...) } return(res) }
ardec.periodic <- function(x,per,tol=0.95){ fit=ardec.lm(x) comp=ardec(x,fit$coefficients) if(any(comp$period > (per-tol) & comp$period < (per+tol))) { candidates=which(comp$period > (per-tol) & comp$period < (per+tol)) lper=candidates[which.max(comp$modulus[candidates])] l=comp$period[lper] m=comp$modulus[lper] gt=Re(comp$comps[lper,]+comp$comps[lper+1,]) } return(list(period=l,modulus=m,component=gt)) }
backward_linkages <- function ( Im ) { Im <- mutate (Im, across(where(is.factor), as.character)) total_row <- data.frame ( name = "backward linkages" ) names(total_row)[1] <- names(Im[1]) total_row <- cbind ( total_row, t(colSums(Im[,2:ncol(Im)])) ) total_row }
library(urca) data(Raotbl3) attach(Raotbl3) lc <- ts(lc, start=c(1966,4), end=c(1991,2), frequency=4) lc.ct <- ur.pp(lc, type='Z-tau', model='trend', lags='long') lc.co <- ur.pp(lc, type='Z-tau', model='constant', lags='long') lc2 <- diff(lc) lc2.ct <- ur.pp(lc2, type='Z-tau', model='trend', lags='long')
library(qtl) data(hyper) write.cross(hyper, "tidy", "hyper_tidy") x <- read.cross("tidy", "", genfile="hyper_tidy_gen.csv", mapfile="hyper_tidy_map.csv", phefile="hyper_tidy_phe.csv", genotypes=c("BB", "BA", "AA")) comparecrosses(x, hyper)
context("test star_schema") test_that("star_schema works", { st <- star_schema(mrs_age_test, dm_mrs_age) expect_equal(nrow(st$fact$mrs_age), nrow(mrs_age_test)) expect_equal(nrow(st$dimension$when), 4) expect_equal(nrow(st$dimension$when_available), 6) expect_equal(nrow(st$dimension$where), 3) expect_equal(nrow(st$dimension$who), 5) })
NULL col_vals_regex <- function(x, columns, regex, na_pass = FALSE, preconditions = NULL, segments = NULL, actions = NULL, step_id = NULL, label = NULL, brief = NULL, active = TRUE) { columns_expr <- rlang::as_label(rlang::quo(!!enquo(columns))) %>% gsub("^\"|\"$", "", .) columns <- rlang::enquo(columns) columns <- resolve_columns(x = x, var_expr = columns, preconditions) segments_list <- resolve_segments( x = x, seg_expr = segments, preconditions = preconditions ) if (is_a_table_object(x)) { secret_agent <- create_agent(x, label = "::QUIET::") %>% col_vals_regex( columns = columns, regex = regex, na_pass = na_pass, preconditions = preconditions, segments = segments, label = label, brief = brief, actions = prime_actions(actions), active = active ) %>% interrogate() return(x) } agent <- x if (is.null(brief)) { brief <- generate_autobriefs( agent = agent, columns = columns, preconditions = preconditions, values = regex, assertion_type = "col_vals_regex" ) } step_id <- normalize_step_id(step_id, columns, agent) i_o <- get_next_validation_set_row(agent) check_step_id_duplicates(step_id, agent) for (i in seq_along(columns)) { for (j in seq_along(segments_list)) { seg_col <- names(segments_list[j]) seg_val <- unname(unlist(segments_list[j])) agent <- create_validation_step( agent = agent, assertion_type = "col_vals_regex", i_o = i_o, columns_expr = columns_expr, column = columns[i], values = regex, na_pass = na_pass, preconditions = preconditions, seg_expr = segments, seg_col = seg_col, seg_val = seg_val, actions = covert_actions(actions, agent), step_id = step_id[i], label = label, brief = brief[i], active = active ) } } agent } expect_col_vals_regex <- function(object, columns, regex, na_pass = FALSE, preconditions = NULL, threshold = 1) { fn_name <- "expect_col_vals_regex" vs <- create_agent(tbl = object, label = "::QUIET::") %>% col_vals_regex( columns = {{ columns }}, regex = {{ regex }}, na_pass = na_pass, preconditions = {{ preconditions }}, actions = action_levels(notify_at = threshold) ) %>% interrogate() %>% .$validation_set x <- vs$notify threshold_type <- get_threshold_type(threshold = threshold) if (threshold_type == "proportional") { failed_amount <- vs$f_failed } else { failed_amount <- vs$n_failed } if (length(x) > 1 && any(x)) { fail_idx <- which(x)[1] failed_amount <- failed_amount[fail_idx] x <- TRUE } else { x <- any(x) fail_idx <- 1 } if (inherits(vs$capture_stack[[1]]$warning, "simpleWarning")) { warning(conditionMessage(vs$capture_stack[[1]]$warning)) } if (inherits(vs$capture_stack[[1]]$error, "simpleError")) { stop(conditionMessage(vs$capture_stack[[1]]$error)) } act <- testthat::quasi_label(enquo(x), arg = "object") column_text <- prep_column_text(vs$column[[fail_idx]]) values_text <- prep_values_text(values = vs$values[[fail_idx]], limit = 3, lang = "en") testthat::expect( ok = identical(!as.vector(act$val), TRUE), failure_message = glue::glue( failure_message_gluestring( fn_name = fn_name, lang = "en" ) ) ) act$val <- object invisible(act$val) } test_col_vals_regex <- function(object, columns, regex, na_pass = FALSE, preconditions = NULL, threshold = 1) { vs <- create_agent(tbl = object, label = "::QUIET::") %>% col_vals_regex( columns = {{ columns }}, regex = {{ regex }}, na_pass = na_pass, preconditions = {{ preconditions }}, actions = action_levels(notify_at = threshold) ) %>% interrogate() %>% .$validation_set if (inherits(vs$capture_stack[[1]]$warning, "simpleWarning")) { warning(conditionMessage(vs$capture_stack[[1]]$warning)) } if (inherits(vs$capture_stack[[1]]$error, "simpleError")) { stop(conditionMessage(vs$capture_stack[[1]]$error)) } all(!vs$notify) }
splineAnalyze <- function(Y,map,smoothness=100,s2=NA,mean=NA,plotRaw=FALSE,plotWindows=FALSE, method=3){ roots <- function(data){ data1 <- c(NA,data[1:{length(data)-1}]) data2 <- data posneg <- which(data1>0 & data2<0) - 0.5 negpos <- which(data1<0 & data2>0) -0.5 zero <- which(data == 0) roots <- sort(c(posneg,negpos,zero)) return(roots) } rawData <- data.frame(Pos=map,Y=Y) data <- rawData[which(is.na(rawData$Y)==FALSE),] pspline <- smooth.Pspline(data[,1],data[,2],norder=2,method=method) predict <- predict(pspline,seq(0,max(pspline$x),by=smoothness)) psplinederiv <- predict(pspline,seq(0,max(pspline$x),by=smoothness),nderiv=2) psplineInflection <- roots(psplinederiv)*smoothness print(paste("Total number of windows = ", length(psplineInflection) + 1)) print(" ---- Computing window statistics ----") if(is.na(s2)) s2 <- var(Y) if(is.na(mean)) mean <- mean(Y,na.rm=TRUE) cat(1, "of", length(psplineInflection)+1, "\r") Distinct <- data.frame(WindowStart=rep(NA,length(psplineInflection)+1),WindowStop=NA,SNPcount=NA,MeanY=NA, Wstat=NA) Distinct$WindowStart[1] <- min(pspline$x) Distinct$WindowStop[1] <- psplineInflection[1] Distinct$SNPcount[1] <- length(which(data[,1] <= psplineInflection[1])) Distinct$MeanY[1] <- mean(data[which(data[,1] <= psplineInflection[1]),2],na.rm=TRUE) Distinct$Wstat[1] <- {mean(data[which(data[,1] <= psplineInflection[1]),2],na.rm=TRUE)-mean}/ sqrt(s2/length(which(data[,1] <= psplineInflection[1]))) for(i in 2:length(psplineInflection)){ cat(i, "of", length(psplineInflection)+1, "\r") Distinct$WindowStart[i] <- psplineInflection[i-1] Distinct$WindowStop[i] <- psplineInflection[i] Distinct$SNPcount[i] <- length(which(data[,1] >= psplineInflection[i-1] & data[,1] <= psplineInflection[i])) Distinct$MeanY[i] <- mean(data[which(data[,1] >= psplineInflection[i-1] & data[,1] <= psplineInflection[i]),2],na.rm=TRUE) Distinct$Wstat[i] <- {mean(data[which(data[,1] >= psplineInflection[i-1] & data[,1] <= psplineInflection[i]),2],na.rm=TRUE) - mean}/ sqrt(s2/length(which(data[,1] >= psplineInflection[i-1] & data[,1] <= psplineInflection[i]))) } i <- i+1 cat(i, "of", length(psplineInflection)+1, "\r") Distinct$WindowStart[i] <- psplineInflection[i-1] Distinct$WindowStop[i] <- max(data$Pos) Distinct$SNPcount[i] <- length(which(data[,1] >= psplineInflection[i-1] )) Distinct$MeanY[i] <- mean(data[which(data[,1] >= psplineInflection[i-1]),2],na.rm=TRUE) Distinct$Wstat[i] <- {mean(data[which(data[,1] >= psplineInflection[i-1]),2],na.rm=TRUE) - mean}/ sqrt(s2/length(which(data[,1] >= psplineInflection[i-1]))) print(" ---- done ---- ") if(plotRaw==TRUE & plotWindows==TRUE) par(mfrow=c(2,1)) if(plotRaw==TRUE){ plot(data,xlab="Position (bp)",ylab="Raw values") lines(seq(0,max(pspline$x),by=smoothness),predict,col="red") } if(plotWindows==TRUE){ plot((Distinct$WindowStop-Distinct$WindowStart)/2+Distinct$WindowStart,Distinct$Wstat,xlab="Position (bp)", ylab="Spline Wstat",pch=19) } return(list(rawSpline=pspline,breaks=psplineInflection,windowData=Distinct)) }
get_usage_logs <- function(startDate = Sys.Date()-91, endDate = Sys.Date()-1, login = NA, ip = NA , rsid = NA, eventType = NA, event = NA, limit = 100, page = 0, company_id = Sys.getenv("AW_COMPANY_ID") ) { vars <- tibble::tibble(login, ip, rsid, eventType, event, limit, page) prequery <- list(dplyr::select_if(vars, ~ !any(is.na(.)))) query_param <- stringr::str_remove_all(stringr::str_replace_all(stringr::str_remove_all(paste(prequery, collapse = ''), '\\"'), ', ', '&'), 'list\\(| |\\)') date_range <- make_startDate_endDate(startDate, endDate) urlstructure <- glue::glue('auditlogs/usage?startDate={date_range[[1]]}&endDate={date_range[[2]]}&{query_param}') res <- aw_call_api(req_path = urlstructure[1], company_id = company_id) res <- jsonlite::fromJSON(res) res <- res$content res }
cmd.help <- function(){ cat("\nUsage: time.tabix.r -G genome -R region -C [cov|config]file\n") cat(" [Options]\n") cat("\n cat(" -G Genome name, currently supported: mm9, hg19, rn4, sacCer3(ensembl only)\n") cat(" -R Genomic regions to plot: tss, tes, genebody, exon, cgi or *.bed\n") cat(" -C Tabix file\n") cat(" cat(" -E Gene list to subset regions\n") cat(" -T Image title\n") cat(" cat(" -F Further information can be provided to subset regions:\n") cat(" for genebody: chipseq(default), rnaseq.\n") cat(" for exon: canonical(default), variant, promoter, polyA,\n") cat(" altAcceptor, altDonor, altBoth.\n") cat(" for cgi: ProximalPromoter(default), Promoter1k, Promoter3k,\n") cat(" Genebody, Genedesert, OtherIntergenic, Pericentromere.\n") cat(" -D Gene database: refseq(default), ensembl\n") cat(" -I Shall interval be larger than flanking in plot?(0 or 1, default=automatic)\n") cat(" -L Flanking region size\n") cat(" -N Flanking region factor(will override flanking size)\n") cat(" -S Randomly sample the regions for plot, must be:(0, 1]\n") cat(" -P cat(" cat(" -GO Gene order algorithm used in heatmaps: total(default), hc, max,\n") cat(" prod, diff, pca and none(according to gene list supplied)\n") cat(" -CS Chunk size for loading genes in batch(default=100)\n") cat(" -FL Fragment length used to calculate physical coverage(default=150)\n") cat(" -MQ Mapping quality cutoff to filter reads(default=20)\n") cat(" -SE Shall standard errors be plotted?(0 or 1)\n") cat(" -RB The fraction of extreme values to be trimmed on both ends\n") cat(" default=0, 0.05 means 5% of extreme values will be trimmed\n") cat(" -FC Flooding fraction:[0, 1), default=0.02\n") cat(" -FI Forbid image output if set to 1(default=0)\n") cat(" -MW Moving window width to smooth avg. profiles, must be integer\n") cat(" 1=no(default); 3=slightly; 5=somewhat; 9=quite; 13=super.\n") cat(" -H Opacity of shaded area, suggested value:[0, 0.5]\n") cat(" default=0, i.e. no shading, just curves\n") cat("\n") } args <- commandArgs(T) progpath <- Sys.getenv('NGSPLOT') if(progpath == "") { stop("Set environment variable NGSPLOT before run the program. \ See README for details.\n") } source(file.path(progpath, 'lib', 'parse.args.r')) args.tbl <- parseArgs(args, c('-G', '-C', '-R')) if(is.null(args.tbl)){ cmd.help() stop('Error in parsing command line arguments. Stop.\n') } if(!suppressMessages(require(ShortRead, warn.conflicts=F))) { source("http://bioconductor.org/biocLite.R") biocLite(ShortRead) if(!suppressMessages(require(ShortRead, warn.conflicts=F))) { stop('Loading package ShortRead failed!') } } if(!suppressMessages(require(rtracklayer, warn.conflicts=F))) { source("http://bioconductor.org/biocLite.R") biocLite(rtracklayer) if(!suppressMessages(require(rtracklayer, warn.conflicts=F))) { stop('Loading package rtracklayer failed!') } } if(!suppressMessages(require(BSgenome, warn.conflicts=F))) { source("http://bioconductor.org/biocLite.R") biocLite(BSgenome) if(!suppressMessages(require(BSgenome, warn.conflicts=F))) { stop('Loading package BSgenome failed!') } } if(!suppressMessages(require(doMC, warn.conflicts=F))) { install.packages('doMC') if(!suppressMessages(require(doMC, warn.conflicts=F))) { stop('Loading package doMC failed!') } } if(!suppressMessages(require(caTools, warn.conflicts=F))) { install.packages('caTools') if(!suppressMessages(require(caTools, warn.conflicts=F))) { stop('Loading package caTools failed!') } } if(!suppressMessages(require(utils, warn.conflicts=F))) { install.packages('utils') if(!suppressMessages(require(utils, warn.conflicts=F))) { stop('Loading package utils failed!') } } default.tbl <- read.delim(file.path(progpath, 'database', 'default.tbl')) dbfile.tbl <- read.delim(file.path(progpath, 'database', 'dbfile.tbl')) argvar.list <- setupVars(args.tbl, default.tbl) genome <- argvar.list$genome reg2plot <- argvar.list$reg2plot bed.file <- argvar.list$bed.file oname <- argvar.list$oname fi_tag <- argvar.list$fi_tag lgint <- argvar.list$lgint flanksize <- argvar.list$flanksize flankfactor <- argvar.list$flankfactor samprate <- argvar.list$samprate shade.alp <- argvar.list$shade.alp mw <- argvar.list$mw cores.number <- argvar.list$cores.number se <- argvar.list$se robust <- argvar.list$robust flood.frac <- argvar.list$flood.frac go.algo <- argvar.list$go.algo gcs <- argvar.list$gcs fraglen <- argvar.list$fraglen map.qual <- argvar.list$map.qual bufsize <- argvar.list$bufsize ctg.tbl <- ConfigTbl(args.tbl, fraglen) if(cores.number == 0){ registerDoMC() } else { registerDoMC(cores.number) } source(file.path(progpath, 'lib', 'genedb.r')) plotvar.list <- SetupPlotCoord(args.tbl, ctg.tbl, default.tbl, dbfile.tbl, progpath, genome, reg2plot, lgint, flanksize, bed.file, samprate) coord.list <- plotvar.list$coord.list rnaseq.gb <- plotvar.list$rnaseq.gb lgint <- plotvar.list$lgint reg.list <- plotvar.list$reg.list uniq.reg <- plotvar.list$uniq.reg pint <- plotvar.list$pint exonmodel <- plotvar.list$exonmodel source(file.path(progpath, 'lib', 'plotlib.r')) pts.list <- SetPtsSpline(pint, lgint) pts <- pts.list$pts m.pts <- pts.list$m.pts f.pts <- pts.list$f.pts regcovMat <- CreatePlotMat(pts, ctg.tbl) confiMat <- CreateConfiMat(se, pts, ctg.tbl) enrichList <- vector('list', nrow(ctg.tbl)) source(file.path(progpath, 'lib', 'coverage.r')) bfl.res <- bamFileList(ctg.tbl) bam.pair <- bfl.res$bbp bam.list <- bfl.res$bam.list seqnamesBW <- function(bam.list) { sn.list <- lapply(bam.list, function(t) { seqnames(seqinfo(BigWigFile(t))) }) names(sn.list) <- bam.list sn.list } sn.list <- seqnamesBW(bam.list) covBW <- function(bw.file, sn.inbam, granges, fraglen, map.qual=20, bowtie=F) { g.start <- start(ranges(granges)) g.end <- end(ranges(granges)) gb.len <- g.end - g.start + 1 chr.name <- seqnames(granges) inbam.mask <- as.vector(seqnames(granges)) %in% sn.inbam if(!any(inbam.mask)) { return(genZeroList(length(granges), gb.len)) } rec.in.ranges <- import(bw.file, which=granges[inbam.mask], asRangedData=F) lapply(1:length(granges), function(i) { v <- Rle(0, gb.len[i]) if(!inbam.mask[i] || length(rec.in.ranges) == 0) { return(v) } rec.in.chrom <- rec.in.ranges[as.vector(seqnames(rec.in.ranges) == as.character(chr.name[i]))] if(length(rec.in.chrom) == 0) { return(v) } rec.in.gene <- rec.in.chrom[end(ranges(rec.in.chrom)) >= g.start[i] & start(ranges(rec.in.chrom)) <= g.end[i]] if(length(rec.in.gene) == 0) { return(v) } r.starts <- start(ranges(rec.in.gene)) r.ends <- end(ranges(rec.in.gene)) s.starts <- r.starts - g.start[i] + 1 s.ends <- r.ends - g.start[i] + 1 s.starts[s.starts <= 1] <- 1 s.ends[s.ends >= gb.len[i]] <- gb.len[i] for(j in 1:length(s.starts)) { v[s.starts[j]:s.ends[j]] <- score(rec.in.gene)[j] } v }) } extrCov3SecBW <- function(bw.file, sn.inbam, v.chrom, v.start, v.end, v.fls, bufsize, m.pts, f.pts, v.strand, fraglen, map.qual, bowtie) { interflank.gr <- GRanges(seqnames=v.chrom, ranges=IRanges( start=v.start - v.fls, end=v.end + v.fls)) interflank.cov <- covBW(bw.file, sn.inbam, interflank.gr, fraglen, map.qual, bowtie) SplineRev3Sec(interflank.cov, v.fls, list(l=f.pts, m=m.pts, r=f.pts), v.strand) } extrCovMidpBW <- function(bw.file, sn.inbam, v.chrom, v.midp, flanksize, bufsize, pts, v.strand, fraglen, map.qual, bowtie) { granges <- GRanges(seqnames=v.chrom, ranges=IRanges( start=v.midp - flanksize, end=v.midp + flanksize)) cov.list <- covBW(bw.file, sn.inbam, granges, fraglen, map.qual, bowtie) cov.mat <- matrix(nrow=length(cov.list), ncol=pts) for(i in 1:length(cov.list)) { if(is.null(cov.list[[i]])) { cov.mat[i, ] <- vector('integer', length=pts) } else { cov.mat[i, ] <- spline(1:length(cov.list[[i]]), cov.list[[i]], n=pts)$y if(v.strand[i] == '-') { cov.mat[i, ] <- rev(cov.mat[i, ]) } } } cov.mat } doCovBW <- function(coord.mat, chr.tag, reg2plot, pint, bw.file, sn.inbam, flanksize, flankfactor, bufsize, fraglen, map.qual, m.pts, f.pts, bowtie, exonranges.list=NULL) { v.chrom <- coord.mat$chrom if(!chr.tag) { v.chrom <- sub('chr', '', v.chrom) } v.chrom <- as.factor(v.chrom) v.strand <- as.factor(coord.mat$strand) if(!pint) { if(!is.null(exonranges.list)) { if(flankfactor > 0) { v.fls <- sapply(exonranges.list, function(t) { sum(end(t) - start(t) + 1) }) } else { v.fls <- rep(flanksize, length=nrow(coord.mat)) } } else { v.start <- coord.mat$start v.end <- coord.mat$end if(flankfactor > 0) { v.fls <- round((v.end - v.start + 1) * flankfactor) } else { v.fls <- rep(flanksize, length=nrow(coord.mat)) } extrCov3SecBW(bw.file, sn.inbam, v.chrom, v.start, v.end, v.fls, bufsize, m.pts, f.pts, v.strand, fraglen, map.qual, bowtie) } } else { v.midp <- vector('integer', length=nrow(coord.mat)) for(r in 1:nrow(coord.mat)) { if(reg2plot == 'tss' && v.strand[r] == '+' || reg2plot == 'tes' && v.strand[r] == '-') { v.midp[r] <- coord.mat$start[r] } else { v.midp[r] <- coord.mat$end[r] } } extrCovMidpBW(bw.file, sn.inbam, v.chrom, v.midp, flanksize, bufsize, m.pts + f.pts*2, v.strand, fraglen, map.qual, bowtie) } } covMatrixBW <- function(bw.file, libsize, sn.inbam, chr.tag, coord, chkidx.list, rnaseq.gb, exonmodel, reg2plot, pint, flanksize, flankfactor, bufsize, fraglen, map.qual, m.pts, f.pts, is.bowtie, spit.dot=T) { result.matrix <- foreach(chk=chkidx.list, .combine='rbind', .multicombine=T) %dopar% { if(spit.dot) { cat(".") } i <- chk[1]:chk[2] if(rnaseq.gb) { exonranges.list <- unlist(exonmodel[coord[i, ]$tid]) } else { exonranges.list <- NULL } doCovBW(coord[i, ], chr.tag, reg2plot, pint, bw.file, sn.inbam, flanksize, flankfactor, bufsize, fraglen, map.qual, m.pts, f.pts, is.bowtie, exonranges.list) } result.matrix[result.matrix < 0] <- 0 result.matrix } res.time <- system.time(for(r in 1:nrow(ctg.tbl)) { reg <- ctg.tbl$glist[r] chkidx.list <- chunkIndex(nrow(coord.list[[reg]]), gcs) bam.files <- unlist(strsplit(ctg.tbl$cov[r], ':')) sn.inbam <- sn.list[[bam.files[1]]] chr.tag <- chrTag(sn.inbam) is.bowtie <- F if(class(chr.tag) == 'character') { stop(sprintf("Read %s error: %s", bam.files[1], chr.tag)) } result.matrix <- covMatrixBW(bam.files[1], libsize, sn.inbam, chr.tag, coord.list[[reg]], chkidx.list, rnaseq.gb, exonmodel, reg2plot, pint, flanksize, flankfactor, bufsize, fraglen, map.qual, m.pts, f.pts, is.bowtie, spit.dot=F) if(bam.pair) { pseudo.rpm <- 1e-9 sn.inbam <- sn.list[[bam.files[2]]] chr.tag <- chrTag(sn.inbam) is.bowtie <- F if(class(chr.tag) == 'character') { stop(sprintf("Read %s error: %s", bam.files[2], chr.tag)) } bkg.matrix <- covMatrixBW(bam.files[2], libsize, sn.inbam, chr.tag, coord.list[[reg]], chkidx.list, rnaseq.gb, exonmodel, reg2plot, pint, flanksize, flankfactor, bufsize, fraglen, map.qual, m.pts, f.pts, is.bowtie, spit.dot=F) result.matrix <- log2((result.matrix + pseudo.rpm) / (bkg.matrix + pseudo.rpm)) } if(nrow(result.matrix) > 1 && se){ confiMat[, r] <- apply(result.matrix, 2, function(x) CalcSem(x, robust)) } enrichList[[r]] <- result.matrix regcovMat[, r] <- apply(result.matrix, 2, function(x) mean(x, trim=robust, na.rm=T)) }) print(res.time)
saveFunction = function(reg, fun, more.args) { fun = checkUserFunction(fun) fun.id = digest(list(fun, more.args)) save2(file = getFunFilePath(reg, fun.id), fun = fun, more.args = more.args) return(fun.id) }
freqFunPara <- function(data, n.boot, estimates, interval, omega.freq.method, item.dropped, alpha.int.analytic, omega.int.analytic, pairwise, callback = function(){}) { p <- ncol(data) n <- nrow(data) probs <- c((1 - interval) / 2, interval + (1 - interval) / 2) if (pairwise) { cc <- cov(data, use = "pairwise.complete.obs") } else{ cc <- cov(data) } res <- list() res$covsamp <- NULL boot_cov <- NULL if (("alpha" %in% estimates & !alpha.int.analytic) | "lambda2" %in% estimates | "lambda4" %in% estimates | "lambda6" %in% estimates | "glb" %in% estimates | ("omega" %in% estimates & omega.freq.method == "pfa")) { boot_cov <- array(0, c(n.boot, p, p)) for (i in 1:n.boot) { boot_data <- MASS::mvrnorm(n, colMeans(data, na.rm = TRUE), cc) boot_cov[i, , ] <- cov(boot_data) callback() } res$covsamp <- boot_cov } if (item.dropped) { Ctmp <- array(0, c(p, p - 1, p - 1)) for (i in 1:p) { Ctmp[i, , ] <- cc[-i, -i] } } if ("alpha" %in% estimates) { res$est$freq_alpha <- applyalpha(cc) if (alpha.int.analytic) { int <- ciAlpha(1 - interval, n, cc) res$conf$low$freq_alpha <- int[1] res$conf$up$freq_alpha <- int[2] } else { alpha_obj <- apply(boot_cov, 1, applyalpha, callback) if (length(unique(round(alpha_obj, 4))) == 1) { res$conf$low$freq_alpha <- 1 res$conf$up$freq_alpha <- 1 } else { res$conf$low$freq_alpha <- quantile(alpha_obj, probs = probs[1], na.rm = TRUE) res$conf$up$freq_alpha <- quantile(alpha_obj, probs = probs[2], na.rm = TRUE) } res$boot$alpha <- alpha_obj } if (item.dropped){ res$ifitem$alpha <- apply(Ctmp, 1, applyalpha) } } if ("lambda2" %in% estimates) { res$est$freq_lambda2 <- applylambda2(cc) lambda2_obj <- apply(boot_cov, 1, applylambda2, callback) if (length(unique(round(lambda2_obj, 4))) == 1) { res$conf$low$freq_lambda2 <- NA res$conf$up$freq_lambda2 <- NA } else { res$conf$low$freq_lambda2 <- quantile(lambda2_obj, probs = probs[1], na.rm = TRUE) res$conf$up$freq_lambda2 <- quantile(lambda2_obj, probs = probs[2], na.rm = TRUE) } res$boot$lambda2 <- lambda2_obj if (item.dropped) { res$ifitem$lambda2 <- apply(Ctmp, 1, applylambda2) } } if ("lambda4" %in% estimates) { res$est$freq_lambda4 <- applylambda4NoCpp(cc) lambda4_obj <- apply(boot_cov, 1, applylambda4NoCpp, callback) if (length(unique(round(lambda4_obj, 4))) == 1) { res$conf$low$freq_lambda4 <- NA res$conf$up$freq_lambda4 <- NA } else { res$conf$low$freq_lambda4 <- quantile(lambda4_obj, probs = probs[1], na.rm = TRUE) res$conf$up$freq_lambda4 <- quantile(lambda4_obj, probs = probs[2], na.rm = TRUE) } res$boot$lambda4 <- lambda4_obj if (item.dropped) { res$ifitem$lambda4 <- apply(Ctmp, 1, applylambda4NoCpp) } } if ("lambda6" %in% estimates) { res$est$freq_lambda6 <- applylambda6(cc) lambda6_obj <- apply(boot_cov, 1, applylambda6, callback) if (length(unique(round(lambda6_obj, 4))) == 1) { res$conf$low$freq_lambda6 <- NA res$conf$up$freq_lambda6 <- NA } else { res$conf$low$freq_lambda6 <- quantile(lambda6_obj, probs = probs[1], na.rm = TRUE) res$conf$up$freq_lambda6 <- quantile(lambda6_obj, probs = probs[2], na.rm = TRUE) } res$boot$lambda6 <- lambda6_obj if (item.dropped) { res$ifitem$lambda6 <- apply(Ctmp, 1, applylambda6) } } if ("glb" %in% estimates) { res$est$freq_glb <- glbOnArrayCustom(cc) glb_obj <- glbOnArrayCustom(boot_cov, callback) if (length(unique(round(glb_obj, 4))) == 1) { res$conf$low$freq_glb <- NA res$conf$up$freq_glb <- NA } else { res$conf$low$freq_glb <- quantile(glb_obj, probs = probs[1], na.rm = TRUE) res$conf$up$freq_glb <- quantile(glb_obj, probs = probs[2], na.rm = TRUE) } res$boot$glb <- glb_obj if (item.dropped) { res$ifitem$glb <- glbOnArrayCustom(Ctmp) } } if ("omega" %in% estimates) { if (omega.freq.method == "cfa") { out <- omegaFreqData(data, interval, omega.int.analytic, pairwise, n.boot, parametric= TRUE, callback) res$fit.object <- out$fit.object if (is.null(res$fit.object)) { if (is.null(boot_cov)) { boot_cov <- array(0, c(n.boot, p, p)) for (i in 1:n.boot) { boot_data<- MASS::mvrnorm(n, colMeans(data, na.rm = TRUE), cc) boot_cov[i, , ] <- cov(boot_data) callback() } } res$est$freq_omega <- applyomegaPFA(cc) omega_obj <- apply(boot_cov, 1, applyomegaPFA) if (length(unique(round(omega_obj, 4))) == 1) { res$conf$low$freq_omega <- NA res$conf$up$freq_omega <- NA } else { res$conf$low$freq_omega <- quantile(omega_obj, probs = probs[1], na.rm = TRUE) res$conf$up$freq_omega <- quantile(omega_obj, probs = probs[2], na.rm = TRUE) } res$boot$omega <- omega_obj res$omega.error <- TRUE res$omega.pfa <- TRUE if (item.dropped) { res$ifitem$omega <- apply(Ctmp, 1, applyomegaPFA) } } else { res$est$freq_omega <- out$omega res$loadings <- out$loadings res$resid_var <- out$errors res$conf$low$freq_omega <- out$omega_low res$conf$up$freq_omega <- out$omega_up res$omega_fit <- out$indices res$boot$omega <- out$omega_boot if (item.dropped) { res$ifitem$omega <- numeric(p) for (i in 1:p) { dtmp <- data[, -i] res$ifitem$omega[i] <- applyomegaCFAData(dtmp, interval = interval, pairwise = pairwise) } if (any(is.na(res$ifitem$omega))) { res$ifitem$omega <- apply(Ctmp, 1, applyomegaPFA) res$omega.item.error <- TRUE } } } } else if (omega.freq.method == "pfa") { res$est$freq_omega <- applyomegaPFA(cc) omega_obj <- apply(boot_cov, 1, applyomegaPFA, callback) res$omega.pfa <- TRUE if (length(unique(round(omega_obj, 4))) == 1) { res$conf$low$freq_omega <- NA res$conf$up$freq_omega <- NA } else { res$conf$low$freq_omega <- quantile(omega_obj, probs = probs[1], na.rm = TRUE) res$conf$up$freq_omega <- quantile(omega_obj, probs = probs[2], na.rm = TRUE) } res$boot$omega <- omega_obj if (item.dropped) { res$ifitem$omega <- apply(Ctmp, 1, applyomegaPFA) } } } return(res) }
tables_tab <- argonTabItem( tabName = "tables", radioButtons( inputId = "cardWrap", inline = TRUE, label = "Enable card wrap?", choices = c("Enable", "Disable"), selected = "Enable" ), uiOutput("argonTable") )
"extract.tsd" <- function(e, n, series=NULL, components=NULL, ...) { if (missing(n)) n <- length(e$ts) ns <- length(e$ts) if (is.null(series)) { if (n > ns) { warning(paste("Only", ns, "series exist in the object. Extract all series.")) n <- ns } series <- 1:n } else { if (is.character(series)) { names <- e$ts series <- pmatch(series, names, nomatch=0) } else { if (sum(series) > 0) series <- match(series, 1:ns, nomatch=0) else series <- c(1:ns)[match(-1:-ns, series, nomatch=0) == 0] } series <- series[series != 0] if (length(series) < 1) stop("series argument is invalid, or series does not exist in this object") } if (length(series) == 1) { if (ns == 1) { if (is.null(components)) res <- e$series else { if (is.character(components)) { names <- dimnames(e$series)[[2]] comp <- pmatch(components, names, nomatch=0) } else { if (sum(components) > 0) comp <- match(components, 1:ncol(e$series), nomatch=0) else comp <- c(1:ncol(e$series))[match(-1:-ncol(e$series), components, nomatch=0) == 0] } comp <- comp[comp != 0] if (length(comp) < 1) stop("No such components in the series") res <- e$series[, comp] } } else { if (is.null(components)) res <- e$series[[series]] else { if (is.character(components)) { names <- dimnames(e$series[[series]])[[2]] comp <- pmatch(components, names, nomatch=0) } else { if (sum(components) > 0) comp <- match(components, 1:ncol(e$series[[series]]), nomatch=0) else comp <- c(1:ncol(e$series[[series]]))[match(-1:-ncol(e$series[[series]]), components, nomatch=0) == 0] } comp <- comp[comp != 0] if (length(comp) < 1) stop("No such components in the series") res <- e$series[[series]][, comp] } } } else { res <- NULL for (i in series) { if (is.null(components)) ser <- e$series[[i]] else { if (is.character(components)) { names <- dimnames(e$series[[i]])[[2]] comp <- pmatch(components, names, nomatch=0) } else { if (sum(components) > 0) comp <- match(components, 1:ncol(e$series[[i]]), nomatch=0) else comp <- c(1:ncol(e$series[[i]]))[match(-1:-ncol(e$series[[i]]), components, nomatch=0) == 0] } comp <- comp[comp != 0] if (length(comp) > 0) { ser <- e$series[[i]][, comp] names <- dimnames(e$series[[i]])[[2]] names <- names[comp] if (is.null(res)) { res <- ser cnames <- paste(e$ts[i], ".", names, sep="") } else { res <- cbind(res, ser) cnames <- c(cnames, paste(e$ts[i], ".", names, sep="")) } } } } if (is.null(res)) stop("nothing to extract!") dimnames(res)[[2]] <- cnames } res <- as.ts(res) attr(res, "units") <- e$units res }
setClass("tskrrTuneHeterogeneous", contains = c("tskrrTune", "tskrrHeterogeneous")) validTskrrTuneHeterogeneous <- function(object){ lossval <- object@loss_values lgrid <- object@lambda_grid excl <- object@exclusion onedim <- object@onedim if(!onedim && any(names(lgrid) != c("k","g"))) return("lambda grid should be a list with two elements named k and g (in that order) for heterogeneous networks") else if(onedim && any(names(lgrid) != "k") && length(lgrid) > 1) return("in a one-dimensional search there should only be a single element named k in the lambda grid.") if(nrow(lossval) != length(lgrid$k)) return(paste("Loss values should have",length(lgrid$k),"rows to match the lambda grid.")) if(!onedim && ncol(lossval) != length(lgrid$g)) return(paste("Loss values should have",length(lgrid$g),"columns to match the lambda grid.")) else if(onedim && ncol(lossval) != 1) return(paste("Loss values should have one column in case of one-dimensional search.")) exclmatch <- match(excl, c("interaction","row","column","both"), nomatch = 0L) if(exclmatch == 0) return("exclusion should be one of 'interaction', 'row', 'column' or 'both'") if(object@replaceby0 && excl != "interaction") return("replaceby0 can only be used with interaction exclusion") else return(TRUE) } setValidity("tskrrTuneHeterogeneous", validTskrrTuneHeterogeneous)
sha1_hash <- function(key, string, method = "HMAC-SHA1") { if (is.character(string)) { string <- charToRaw(paste(string, collapse = "\n")) } if (is.character(key)) { key <- charToRaw(paste(key, collapse = "\n")) } if (!method %in% c("HMAC-SHA1", "RSA-SHA1")) { stop(paste0("Unsupported hashing method: ", method), call. = FALSE) } if (method == "HMAC-SHA1") { hash <- openssl::sha1(string, key = key) } else { hash <- openssl::signature_create(string, openssl::sha1, key = key) } openssl::base64_encode(hash) } hmac_sha1 <- function(key, string) { sha1_hash(key, string, "HMAC-SHA1") }
`%<-%` <- function(x, value) { target <- substitute(x) expr <- substitute(value) envir <- parent.frame(1) futureAssignInternal(target, expr, envir = envir, substitute = FALSE) } `%->%` <- function(value, x) { target <- substitute(x) expr <- substitute(value) envir <- parent.frame(1) futureAssignInternal(target, expr, envir = envir, substitute = FALSE) } futureAssignInternal <- function(target, expr, envir = parent.frame(), substitute = FALSE) { target <- parse_env_subset(target, envir = envir, substitute = substitute) assign.env <- target$envir name <- target$name if (inherits(target$envir, "listenv")) { n <- length(target$exists) if (n == 0L) { stop("Cannot future assign to an empty set") } else if (n > 1L) { stop("Cannot future assign to more than one element") } if (target$exists) { name <- get_variable(target$envir, target$idx, mustExist = TRUE, create = FALSE) } else { if (!is.na(name) && nzchar(name)) { name <- get_variable(target$envir, name, mustExist = FALSE, create = TRUE) } else if (all(is.finite(target$idx))) { name <- get_variable(target$envir, target$idx, mustExist = FALSE, create = TRUE) } else if (all(is.na(target$idx))) { stop("subscript out of bounds") } else { stop("INTERNAL ERROR: Zero length variable name and unknown index.") } } } futureAssign(name, expr, envir = envir, assign.env = assign.env, substitute = FALSE) }
`.colorselection` <- function (type = "cloud", index, cols, numpoints, labels, numlabels) { if (type == "bar") { if (length(cols) == length(labels)) { rcol <- (col2rgb(cols[index])/255)[1] gcol <- (col2rgb(cols[index])/255)[2] bcol <- (col2rgb(cols[index])/255)[3] } else if (length(cols) == 1) { rcol <- (col2rgb(cols[1])/255)[1] gcol <- (col2rgb(cols[1])/255)[2] bcol <- (col2rgb(cols[1])/255)[3] } else { rcol <- (col2rgb("black")/255)[1] gcol <- (col2rgb("black")/255)[2] bcol <- (col2rgb("black")/255)[3] } } else { if (!length(cols)) { rcol <- (col2rgb(rainbow(numpoints)[index])/255)[1] gcol <- (col2rgb(rainbow(numpoints)[index])/255)[2] bcol <- (col2rgb(rainbow(numpoints)[index])/255)[3] } else if ((length(cols) == 1) || ((length(cols) < numpoints) && !length(labels))) { rcol <- (col2rgb(cols[1])/255)[1] gcol <- (col2rgb(cols[1])/255)[2] bcol <- (col2rgb(cols[1])/255)[3] } else if (length(labels) && (length(cols) == length(unique(labels))) && (type != "mesh")) { rcol <- (col2rgb(cols[numlabels[index]])/255)[1] gcol <- (col2rgb(cols[numlabels[index]])/255)[2] bcol <- (col2rgb(cols[numlabels[index]])/255)[3] } else { rcol <- (col2rgb(cols[index])/255)[1] gcol <- (col2rgb(cols[index])/255)[2] bcol <- (col2rgb(cols[index])/255)[3] } } return(list(rcol = rcol, gcol = gcol, bcol = bcol)) } `.lbar` <- function (data, row.labels = rownames(data), col.labels = colnames(data), filename = "out.m", space = 0.5, cols = rainbow(length(as.matrix(data))), rcols = NULL, ccols = NULL, origin = c(0, 0, 0), scalefac = 4, autoscale = TRUE, ignore_zeros = TRUE, lab.axis = c("X-axis", "Y-axis", "Z-axis"), col.axis = "black", showaxis = TRUE, col.lab = "black", col.bg = "white", cex.lab = 1, cex.rowlab = 1, cex.collab = 1, ambientlight = 0.5, htmlout = NULL, hwidth = 1200, hheight = 800, showlegend = TRUE) { data <- as.matrix(data) curdir <- NULL if (!exists(".vrmlgenEnv")) { write("Graphics3D[\n{\n", file = filename, append = FALSE) bg_rcol <- (col2rgb(col.bg)/255)[1] bg_gcol <- (col2rgb(col.bg)/255)[2] bg_bcol <- (col2rgb(col.bg)/255)[3] write(paste("Background {\n\t skyColor [\n\t\t ", bg_rcol, bg_gcol, bg_bcol, " \n\t]\n}", sep = " "), file = filename, append = TRUE) } else { vrmlgenEnv <- get(".vrmlgenEnv",envir=.GlobalEnv) filename <- vrmlgenEnv$filename htmlout <- vrmlgenEnv$html hheight <- vrmlgenEnv$hheight hwidth <- vrmlgenEnv$hwidth curdir <- getwd() setwd(vrmlgenEnv$VRMLDir) } if(autoscale) data <- scalefac * (data/max(data)) if (!is.null(col.labels) && showlegend) col.labels <- sapply(strsplit(col.labels, " "), function(x) paste(x, collapse = "\n")) if (!is.null(row.labels) && showlegend) row.labels <- sapply(strsplit(row.labels, " "), function(x) paste(x, collapse = "\n")) blength <- scalefac/(nrow(data) * (1 + space)) bwidth <- scalefac/(ncol(data) * (1 + space)) if (showaxis) { axis3d(lab.axis, filename, type = "lg3d", col.lab, col.axis, cex.lab, local_scale = scalefac, global_scale = 1) } if (!is.null(row.labels) && showlegend) { for (j in 1:length(row.labels)) { colsel <- .colorselection(type = "bar", j, rcols, 1, row.labels, "") rcol <- colsel$rcol gcol <- colsel$gcol bcol <- colsel$bcol cur_xwidth <- j/nrow(data) * scalefac - blength/2 write(paste("RGBColor[", rcol, ",", gcol, ",", bcol, "], Text [ \"", row.labels[j], "\", {", cur_xwidth, ",", -0.4, ",", scalefac + 0.2, "}],\n", sep = ""), file = filename, append = TRUE) } } if (!is.null(col.labels) && showlegend) { for (j in 1:length(col.labels)) { colsel <- .colorselection(type = "bar", j, ccols, 1, col.labels, "") rcol <- colsel$rcol gcol <- colsel$gcol bcol <- colsel$bcol cur_ywidth <- j/ncol(data) * scalefac - bwidth/2 write(paste("RGBColor[", rcol, ",", gcol, ",", bcol, "], Text [ \"", col.labels[j], "\", {", -0.4, ",", cur_ywidth, ",", scalefac + 0.2, "}],\n", sep = ""), file = filename, append = TRUE) } } rcol <- NULL gcol <- NULL bcol <- NULL if (length(cols) >= (ncol(data) * nrow(data))) { rcol <- sapply(cols, function(x) (col2rgb(x)/255)[1]) gcol <- sapply(cols, function(x) (col2rgb(x)/255)[2]) bcol <- sapply(cols, function(x) (col2rgb(x)/255)[3]) } else { if (length(cols) >= 1) { rcol <- (col2rgb(cols[1])/255)[1] gcol <- (col2rgb(cols[1])/255)[2] bcol <- (col2rgb(cols[1])/255)[3] } else { rcol <- (col2rgb("lightblue")/255)[1] gcol <- (col2rgb("lightblue")/255)[2] bcol <- (col2rgb("lightblue")/255)[3] } } bwidth <- bwidth/2 for (k in 1:ncol(data)) { for (j in 1:nrow(data)) { x <- j/nrow(data) * scalefac y <- k/ncol(data) * scalefac z <- data[j, k] if(ignore_zeros && (z == 0)) next if (!is.null(ccols)) { rcol <- (col2rgb(ccols[k])/255)[1] gcol <- (col2rgb(ccols[k])/255)[2] bcol <- (col2rgb(ccols[k])/255)[3] } else if (!is.null(rcols)) { rcol <- (col2rgb(rcols[j])/255)[1] gcol <- (col2rgb(rcols[j])/255)[2] bcol <- (col2rgb(rcols[j])/255)[3] } else { if(length(rcol) > 1) { rcol <- rcol[(k - 1) * ncol(data) + j] gcol <- gcol[(k - 1) * ncol(data) + j] bcol <- bcol[(k - 1) * ncol(data) + j] } } write(paste("SurfaceColor[RGBColor[", rcol, ",", gcol, ",", bcol, "]], Cuboid[{", origin[1] + x - bwidth, ",", origin[2] + y - bwidth, ",", origin[3], "},{", origin[1] + x + bwidth, ",", origin[2] + y + bwidth, ",", origin[3] + z, "}],", sep = ""), file = filename, append = TRUE) } } write(paste("\n}, Boxed -> False, Axes -> False, AmbientLight->GrayLevel[", ambientlight, "], TextStyle -> {FontFamily -> \"TimesRoman\", FontSlant ->\"Italic\", FontSize -> ", 14 * cex.lab, "}, Lighting -> True, BoxRatios -> Automatic, PlotRange -> All ]\n", sep = ""), file = filename, append = TRUE) if (!exists(".vrmlgenEnv")) { if (!is.null(htmlout)) { cat("<HTML>", file = htmlout, append = FALSE) cat("<HEAD><TITLE>VRMLGen-visualization</TITLE></HEAD><BODY>", file = htmlout, append = TRUE) cat(paste("<APPLET ARCHIVE=\"live.jar\" CODE=\"Live.class\" WIDTH=", hwidth, " HEIGHT=", hheight, " ALIGN=LEFT>", sep = ""), file = htmlout, append = TRUE) coln <- col2rgb(col.bg) cat(paste("<PARAM NAME=\"BGCOLOR\" VALUE=\"", rgb(red = coln[1, ]/255, green = coln[2, ]/255, blue = coln[3, ]/255), "\">", sep = ""), file = htmlout, append = TRUE) cat("<PARAM NAME=\"MAGNIFICATION\" VALUE=1.0>", file = htmlout, append = TRUE) cat(paste("<PARAM NAME=\"INPUT_FILE\" VALUE=\"", filename, "\">", sep = ""), file = htmlout, append = TRUE) cat("</APPLET>", file = htmlout, append = TRUE) cat("</HTML>", file = htmlout, append = TRUE) } datadir <- system.file("extdata", package = "vrmlgen") curdir <- getwd() if (data.class(result<-try(file.copy(file.path(datadir, "live.jar"), file.path(curdir, "live.jar")), TRUE))=="try-error") { warning("\nCannot copy file live.jar from vrlmgen-folder to current directory. You might need to copy the file manually.") } cat(paste("\nOutput file \"", filename, "\" was generated in folder ", getwd(), ".\n", sep = "")) } else { setwd(curdir) } } `.lcloud` <- function (x, y = NULL, z = NULL, labels = rownames(data), metalabels = NULL, hyperlinks = NULL, filename = "out.m", pointstyle = c("s", "b", "t"), cols = rainbow(length(unique(labels))), scalefac = 4, autoscale = "independent", lab.axis = c("X-axis", "Y-axis", "Z-axis"), col.axis = "black", showaxis = TRUE, col.lab = "black", col.metalab = "black", col.bg = "white", cex.lab = 1, ambientlight = 0.5, htmlout = NULL, hwidth = 1200, hheight = 800, showlegend = TRUE) { xyz_parse <- xyz.coords(x, y, z) data <- cbind(xyz_parse$x, xyz_parse$y, xyz_parse$z) if (ncol(data) != 3) { stop("Data matrix does not have 3 columns!") } numlabels <- NULL if (length(labels)) { lab <- unique(unlist(labels)) numlabels <- apply(as.matrix(labels), 1, function(x) match(x, as.matrix(lab))) } curdir <- NULL if (!exists(".vrmlgenEnv")) { write("Graphics3D[\n{\n", file = filename, append = FALSE) bg_rcol <- (col2rgb(col.bg)/255)[1] bg_gcol <- (col2rgb(col.bg)/255)[2] bg_bcol <- (col2rgb(col.bg)/255)[3] write(paste("Background {\n\t skyColor [\n\t\t ", bg_rcol, bg_gcol, bg_bcol, " \n\t]\n}, \n", sep = " "), file = filename, append = TRUE) } else { vrmlgenEnv <- get(".vrmlgenEnv",envir=.GlobalEnv) filename <- vrmlgenEnv$filename htmlout <- vrmlgenEnv$html hheight <- vrmlgenEnv$hheight hwidth <- vrmlgenEnv$hwidth curdir <- getwd() setwd(vrmlgenEnv$VRMLDir) } scaledat <- function(data) { diff <- max(data) - min(data) if (diff == 0) return(data) else return(scalefac * (data - min(data))/(diff)) } if (autoscale == "independent") data <- apply(data, 2, scaledat) else if (autoscale == "equidist") data <- scalefac * (data/max(data)) if (length(labels) && showlegend) { cur_height <- scalefac + 1 + cex.lab/5 for (j in 1:length(unique(labels))) { .lg3dtext(0, 0, cur_height, unique(labels)[j], filename, cols[unique(numlabels)[j]], 1, "Arial", "Plain", NULL) cur_height <- cur_height + 0.4 } } lab_rcol <- NULL lab_gcol <- NULL lab_bcol <- NULL ax_rcol <- NULL ax_gcol <- NULL ax_bcol <- NULL if (showaxis) { axis3d(lab.axis, filename, type = "lg3d", col.lab, col.axis, cex.lab, local_scale = scalefac, global_scale = 1) } if ((length(metalabels) == 0) && (length(hyperlinks) >= 1)) { metalabels <- rep(" ", length(hyperlinks)) } for (j in 1:nrow(data)) { x <- data[j, 1] y <- data[j, 2] z <- data[j, 3] colsel <- .colorselection(type = "cloud", j, cols, nrow(data), labels, numlabels) rcol <- colsel$rcol gcol <- colsel$gcol bcol <- colsel$bcol if (length(pointstyle) == 1) { .lg3dpoints(x, y, z, filename, rcol, gcol, bcol, pointstyle, hyperlinks = NULL, local_scale = 1) } else if (length(pointstyle) >= length(unique(numlabels))) { if (length(labels)) { stylevec <- c("s", "b", "t") curstyle <- stylevec[numlabels[j]] .lg3dpoints(x, y, z, filename, rcol, gcol, bcol, curstyle, hyperlinks = NULL, local_scale = 1) } else { .lg3dpoints(x, y, z, filename, rcol, gcol, bcol, pointstyle[1], hyperlinks = NULL, local_scale = 1) } } else { .lg3dpoints(x, y, z, filename, rcol, gcol, bcol, pointstyle[1], hyperlinks = NULL, local_scale = 1) } if (length(metalabels) >= j) { frcol <- (col2rgb(col.metalab)/255)[1] fgcol <- (col2rgb(col.metalab)/255)[2] fbcol <- (col2rgb(col.metalab)/255)[3] write(paste("Text[StyleForm[\"", metalabels[j], "\",FontFamily -> \"Arial\", FontWeight->\"Bold\", FontColor -> RGBColor[", frcol, ",", fgcol, ",", fbcol, "], FontSize->9,", sep = ""), file = filename, append = TRUE) if (length(hyperlinks) >= j) { write(paste("URL -> \"", hyperlinks[j], ",target=_blank\",", sep = ""), file = filename, append = TRUE) } write(paste("],{", x, ",", y, ",", z, "}],", sep = ""), file = filename, append = TRUE) } } if (!exists(".vrmlgenEnv")) { write(paste("\n}, Boxed -> False, Axes -> False, AmbientLight->GrayLevel[", ambientlight, "], TextStyle -> {FontFamily -> \"TimesRoman\", FontSlant ->\"Italic\", FontSize -> ", 14 * cex.lab, "}, Lighting -> True, BoxRatios -> Automatic, PlotRange -> All ]\n", sep = ""), file = filename, append = TRUE) if (!is.null(htmlout)) { cat("<HTML>", file = htmlout, append = FALSE) cat("<HEAD><TITLE>VRMLGen-visualization</TITLE></HEAD><BODY>", file = htmlout, append = TRUE) cat(paste("<APPLET ARCHIVE=\"live.jar\" CODE=\"Live.class\" WIDTH=", hwidth, " HEIGHT=", hheight, " ALIGN=LEFT>", sep = ""), file = htmlout, append = TRUE) coln <- col2rgb(col.bg) cat(paste("<PARAM NAME=\"BGCOLOR\" VALUE=\"", rgb(red = coln[1, ]/255, green = coln[2, ]/255, blue = coln[3, ]/255), "\">", sep = ""), file = htmlout, append = TRUE) cat("<PARAM NAME=\"MAGNIFICATION\" VALUE=1.0>", file = htmlout, append = TRUE) cat(paste("<PARAM NAME=\"INPUT_FILE\" VALUE=\"", filename, "\">", sep = ""), file = htmlout, append = TRUE) cat("</APPLET></BODY>", file = htmlout, append = TRUE) cat("</HTML>", file = htmlout, append = TRUE) } datadir <- system.file("extdata", package = "vrmlgen") curdir <- getwd() if (data.class(result<-try(file.copy(file.path(datadir, "live.jar"), file.path(curdir, "live.jar")), TRUE))=="try-error") { warning("\nCannot copy file live.jar from vrlmgen-folder to current directory. You might need to copy the file manually.") } cat(paste("\nOutput file \"", filename, "\" was generated in folder ", getwd(), ".\n", sep = "")) } else { setwd(curdir) } } `.lg3dpoints` <- function (x, y, z, filename, rcol, gcol, bcol, pointstyle, hyperlinks = NULL, global_scale = 1, local_scale = 1) { if (pointstyle == "s") { for (i in 1:length(x)) write(paste("PointSize[", 0.02 * local_scale, "], RGBColor[", rcol, ",", gcol, ",", bcol, "], Point[{", x[i], ",", y[i], ",", z[i], "}],", sep = ""), file = filename, append = TRUE) } else if (pointstyle == "t") { for (i in 1:length(x)) write(paste("{ SurfaceColor[RGBColor[", rcol, ",", gcol, ",", bcol, "]], Polygon[{{", local_scale * x[i], ", ", local_scale * y[i], ",", local_scale * (z[i] + 0.06415), "}, {", local_scale * global_scale * (x[i] + 0.09072222), ",", local_scale * global_scale * y[i], ",", local_scale * global_scale * (z[i] - 0.096225), "}, {", local_scale * global_scale * x[i] - 0.09072222, ",", local_scale * global_scale * y[i] + 0.15713333, ",", local_scale * global_scale * z[i] - 0.096225, "}}], Polygon[{{", local_scale * global_scale * x[i], ",", local_scale * global_scale * y[i], ",", local_scale * global_scale * (z[i] + 0.06415), "}, {", local_scale * global_scale * (x[i] - 0.09072222), ",", local_scale * global_scale * (y[i] + 0.15713333), ",", local_scale * global_scale * (z[i] - 0.096225), "}, {", local_scale * global_scale * (x[i] - 0.09072222), ",", local_scale * global_scale * (y[i] - 0.15713333), ",", local_scale * global_scale * (z[i] - 0.096225), "}}], Polygon[{{", local_scale * global_scale * x[i], ",", local_scale * global_scale * y[i], ",", local_scale * global_scale * (z[i] + 0.06415), "}, {", local_scale * global_scale * (x[i] - 0.09072222), ",", local_scale * global_scale * (y[i] - 0.15713333), ",", local_scale * global_scale * (z[i] - 0.096225), "}, {", local_scale * global_scale * (x[i] + 0.09072222), ",", local_scale * global_scale * y[i], ",", local_scale * global_scale * (z[i] - 0.096225), "}}], Polygon[{{", local_scale * global_scale * (x[i] + 0.09072222), ",", local_scale * global_scale * y[i], ",", local_scale * global_scale * (z[i] - 0.096225), "}, {", local_scale * global_scale * (x[i] - 0.09072222), ",", local_scale * global_scale * (y[i] - 0.15713333), ",", local_scale * global_scale * (z[i] - 0.096225), "}, {", local_scale * global_scale * (x[i] - 0.09072222), ",", local_scale * global_scale * (y[i] + 0.15713333), ",", local_scale * global_scale * (z[i] - 0.096225), "}}] },\n", sep = ""), file = filename, append = TRUE) } else { for (i in 1:length(x)) write(paste("SurfaceColor[RGBColor[", rcol, ",", gcol, ",", bcol, "]], Cuboid[{", local_scale * (x[i] - 0.04), ",", local_scale * (y[i] - 0.04), ",", local_scale * (z[i] - 0.04), "},{", local_scale * global_scale * (x[i] + 0.04), ",", local_scale * global_scale * (y[i] + 0.04), ",", local_scale * global_scale * (z[i] + 0.04), "}],", sep = ""), file = filename, append = TRUE) } if (!is.null(hyperlinks)) { for (i in 1:length(hyperlinks)) write(paste("Text[StyleForm[\" \", URL -> \"", hyperlinks, "\"], {", local_scale * x[i], ",", local_scale * y[i], ",", local_scale * z[i], "}],", sep = ""), file = filename, append = TRUE) } } `.lg3dtext` <- function (x, y, z, text, filename, col, scale, fontfamily, fontweight, hyperlink) { rcol <- (col2rgb(col)/255)[1] gcol <- (col2rgb(col)/255)[2] bcol <- (col2rgb(col)/255)[3] if (is.null(hyperlink)) { for (i in 1:length(x)) write(paste("RGBColor[", rcol, ",", gcol, ",", bcol, "], Text [StyleForm[\"", text[i], "\", FontFamily -> \"", fontfamily, "\", FontSize-> ", 14 * scale, ", FontWeight->\"", fontweight, "\"], {", x[i], ",", y[i], ",", z[i], "}],\n", sep = ""), file = filename, append = TRUE) } else { for (i in 1:length(x)) write(paste("RGBColor[", rcol, ",", gcol, ",", bcol, "], Text [StyleForm[\"", text[i], "\", FontFamily -> \"", fontfamily, "\", FontSize-> ", 14 * scale, ", URL -> \"", hyperlink, "\", FontWeight->\"", fontweight, "\"], {", x[i], ",", y[i], ",", z[i], "}],\n", sep = ""), file = filename, append = TRUE) } } `.lmesh` <- function (xfun = "sin(v)*cos(u)", yfun = "sin(v)*sin(u)", zfun = "cos(v)", param1 = "u", param2 = "v", range1 = c(0, 2 * pi), range2 = c(0, pi), size1 = 30, size2 = 30, filename = "out.m", cols = "red", scalefac = 4, autoscale = "independent", lab.axis = c("X-axis", "Y-axis", "Z-axis"), col.axis = "black", showaxis = TRUE, col.lab = "black", col.bg = "white", cex.lab = 1, ambientlight = 0.5, htmlout = NULL, hwidth = 1200, hheight = 800) { if (is.null(xfun) || is.null(yfun) || is.null(zfun)) { stop("Either the paramater infile or data or the parameters xfun, yfun and zfun have to be specified.") } if (is.null(param1) || is.null(param2)) { stop("The parameter names param1 and param2 have not been specified") } x <- NULL y <- NULL z <- NULL smin <- range1[1] smax <- range1[2] tmin <- range2[1] tmax <- range2[2] sn <- size1 tn <- size2 ds <- (smax - smin)/sn dt <- (tmax - tmin)/tn for (i in seq(smin, (smax - ds/2), ds)) { for (j in seq(tmin, (tmax - dt/2), dt)) { eval(parse(text = paste(param1, " <- ", i))) eval(parse(text = paste(param2, " <- ", j))) x <- c(x, eval(parse(text = xfun))) y <- c(y, eval(parse(text = yfun))) z <- c(z, eval(parse(text = zfun))) eval(parse(text = paste(param1, " <- ", param1, " + ds"))) x <- c(x, eval(parse(text = xfun))) y <- c(y, eval(parse(text = yfun))) z <- c(z, eval(parse(text = zfun))) eval(parse(text = paste(param2, " <- ", param2, " + dt"))) x <- c(x, eval(parse(text = xfun))) y <- c(y, eval(parse(text = yfun))) z <- c(z, eval(parse(text = zfun))) eval(parse(text = paste(param1, " <- ", param1, " - ds"))) x <- c(x, eval(parse(text = xfun))) y <- c(y, eval(parse(text = yfun))) z <- c(z, eval(parse(text = zfun))) } } data <- as.matrix(cbind(x, y, z)) if (ncol(data) != 3) { stop("Data matrix does not have 3 columns!") } curdir <- NULL if (!exists(".vrmlgenEnv")) { write("Graphics3D[\n{\n", file = filename, append = FALSE) bg_rcol <- (col2rgb(col.bg)/255)[1] bg_gcol <- (col2rgb(col.bg)/255)[2] bg_bcol <- (col2rgb(col.bg)/255)[3] write(paste("Background {\n\t skyColor [\n\t\t ", bg_rcol, bg_gcol, bg_bcol, " \n\t]\n}", sep = " "), file = filename, append = TRUE) } else { vrmlgenEnv <- get(".vrmlgenEnv",envir=.GlobalEnv) filename <- vrmlgenEnv$filename htmlout <- vrmlgenEnv$html hheight <- vrmlgenEnv$hheight hwidth <- vrmlgenEnv$hwidth curdir <- getwd() setwd(vrmlgenEnv$VRMLDir) } scaledat <- function(data) { diff <- max(data) - min(data) if (diff == 0) return(data) else return(scalefac * (data - min(data))/(diff)) } if (autoscale == "independent") data <- apply(data, 2, scaledat) else if (autoscale == "equidist") data <- scalefac * (data/max(data)) else if (autoscale == "equicenter") data <- scalefac/2 * data/max(data) + scalefac/2 lab_rcol <- NULL lab_gcol <- NULL lab_bcol <- NULL ax_rcol <- NULL ax_gcol <- NULL ax_bcol <- NULL if (showaxis) { axis3d(lab.axis, filename, type = "lg3d", col.lab, col.axis, cex.lab, local_scale = scalefac, global_scale = 1) } for (j in 1:nrow(data)) { x <- data[j, 1] y <- data[j, 2] z <- data[j, 3] colsel <- .colorselection(type = "mesh", j, cols, nrow(data),"", "") rcol <- colsel$rcol gcol <- colsel$gcol bcol <- colsel$bcol if (j%%4 == 1) write(paste(" SurfaceColor[RGBColor[", rcol, ",", gcol, ",", bcol, "]], Polygon[{{", x, ",", y, ",", z, "},", sep = ""), file = filename, append = TRUE) else if (j%%4 == 0) write(paste(" {", x, ",", y, ",", z, "}}],", sep = ""), file = filename, append = TRUE) else write(paste(" {", x, ",", y, ",", z, "},", sep = ""), file = filename, append = TRUE) } write(paste("\n}, Boxed -> False, Axes -> False, AmbientLight->GrayLevel[", ambientlight, "], TextStyle -> {FontFamily -> \"TimesRoman\", FontSlant ->\"Italic\", FontSize -> ", 14 * cex.lab, "}, Lighting -> True, BoxRatios -> Automatic, PlotRange -> All ]\n", sep = ""), file = filename, append = TRUE) if (!exists(".vrmlgenEnv")) { if (!is.null(htmlout)) { cat("<HTML>", file = htmlout, append = FALSE) cat("<HEAD><TITLE>VRMLGen-visualization</TITLE></HEAD><BODY>", file = htmlout, append = TRUE) cat(paste("<APPLET ARCHIVE=\"live.jar\" CODE=\"Live.class\" WIDTH=", hwidth, " HEIGHT=", hheight, " ALIGN=LEFT>", sep = ""), file = htmlout, append = TRUE) coln <- col2rgb(col.bg) cat(paste("<PARAM NAME=\"BGCOLOR\" VALUE=\"", rgb(red = coln[1, ]/255, green = coln[2, ]/255, blue = coln[3, ]/255), "\">", sep = ""), file = htmlout, append = TRUE) cat("<PARAM NAME=\"MAGNIFICATION\" VALUE=1.0>", file = htmlout, append = TRUE) cat(paste("<PARAM NAME=\"INPUT_FILE\" VALUE=\"", filename, "\">", sep = ""), file = htmlout, append = TRUE) cat("</APPLET>", file = htmlout, append = TRUE) cat("</HTML>", file = htmlout, append = TRUE) } datadir <- system.file("extdata", package = "vrmlgen") curdir <- getwd() if (data.class(result<-try(file.copy(file.path(datadir, "live.jar"), file.path(curdir, "live.jar")), TRUE))=="try-error") { warning("\nCannot copy file live.jar from vrlmgen-folder to current directory. You might need to copy the file manually.") } cat(paste("\nOutput file \"", filename, "\" was generated in folder ", getwd(), ".\n", sep = "")) } else { setwd(curdir) } } `.multquaternion` <- function (q1, q2) { tmp <- numeric(4) tmp[1] = q2[4] * q1[1] + q2[1] * q1[4] + q2[2] * q1[3] - q2[3] * q1[2] tmp[2] = q2[4] * q1[2] + q2[2] * q1[4] + q2[3] * q1[1] - q2[1] * q1[3] tmp[3] = q2[4] * q1[3] + q2[3] * q1[4] + q2[1] * q1[2] - q2[2] * q1[1] tmp[4] = q2[4] * q1[4] - q2[1] * q1[1] - q2[2] * q1[2] - q2[3] * q1[3] return(tmp) } `.quaternion2rot` <- function (quat) { res <- numeric(4) res[4] = acos(quat[4]) * 2 for (i in 1:3) res[i] = quat[i]/sin(res[4]/2) return(res) } `.rot2quaternion` <- function (rot = c(1, 0, 0, pi)) { res <- numeric(4) for (i in 1:3) res[i] <- rot[i] * sin(rot[4]/2) res[4] <- cos(rot[4]/2) return(res) } `.vbar` <- function (data, row.labels = rownames(data), col.labels = colnames(data), metalabels = NULL, filename = "out.wrl", space = 0.5, cols = rainbow(length(as.matrix(data))), rcols = NULL, ccols = NULL, origin = c(0, 0, 0), scalefac = 4, autoscale = TRUE, ignore_zeros = TRUE, lab.axis = c("X-axis", "Y-axis", "Z-axis"), lab.vertical = FALSE, col.axis = "black", showaxis = TRUE, col.lab = "black", col.bg = "white", cex.lab = 1, cex.rowlab = 1, cex.collab = 1, navigation = "EXAMINE", fov = 0.785, pos = rep(scalefac + 4, 3), dir = c(0.19, 0.45, 0.87, 2.45), transparency = 0, htmlout = NULL, hwidth = 1200, hheight = 800, showlegend = TRUE) { data <- as.matrix(data) scale <- 1 curdir <- NULL if (!exists(".vrmlgenEnv")) { write(" write(paste("\nViewpoint {\n\tfieldOfView", fov, "\n\tposition", pos[1], pos[2], pos[3], "\n\torientation", dir[1], dir[2], dir[3], dir[4], "\n\tjump TRUE\n\tdescription \"viewpoint1\"\n}\n", sep = " "), file = filename, append = TRUE) write(paste("\nNavigationInfo { type \"", navigation, "\" }\n", sep = ""), file = filename, append = TRUE) bg_rcol <- (col2rgb(col.bg)/255)[1] bg_gcol <- (col2rgb(col.bg)/255)[2] bg_bcol <- (col2rgb(col.bg)/255)[3] write(paste("Background {\n\t skyColor [\n\t\t ", bg_rcol, bg_gcol, bg_bcol, " \n\t]\n}", sep = " "), file = filename, append = TRUE) } else { vrmlgenEnv <- get(".vrmlgenEnv",envir=.GlobalEnv) filename <- vrmlgenEnv$filename htmlout <- vrmlgenEnv$html hheight <- vrmlgenEnv$hheight hwidth <- vrmlgenEnv$hwidth scale <- vrmlgenEnv$scale curdir <- getwd() setwd(vrmlgenEnv$VRMLDir) } if(autoscale) data <- scale * scalefac * (data/max(data)) popuptext <- TRUE if (is.null(metalabels)) { popuptext <- FALSE } if (popuptext) write(paste("\n\nPROTO PopupText [\n\teventIn MFString showThis\n\texposedField SFNode fontStyle FontStyle {\n\t\t\t\tjustify [ \"MIDDLE\", \"MIDDLE\" ] }\n\texposedField SFNode appearance Appearance { material Material { } } \n\tfield SFString default \"\" \n\tfield MFString stringlist [ \"\" ] \n", paste(paste("eventIn SFBool over", 0:(length(metalabels) - 1), "\n\t", sep = "", collapse = ""), sep = "", collapse = ""), "\t] { \nGroup { children [ \n\tDEF POPIT Script { \n\t\tfield SFString defstring IS default \n\t\tfield MFString list IS stringlist \n\t\tfield MFString strout [ \"\" ] ", paste(paste("\n eventIn SFBool over", 0:(length(metalabels) - 1), " IS over", 0:(length(metalabels) - 1), sep = "", collapse = "")), "\n\t\teventOut MFString string_changed \n\t\turl [ \"javascript: \n\t\tfunction evtnum(num, value) \n\t\t{ \n\t\tif (value && (num < list.length)) \n\t\t\tstrout[0] = list[num]; \n\t\telse \n\t\t\tstrout[0] = defstring; \n\t\tstring_changed = strout; \n\t\t} \n \n\t", paste(paste("\tfunction over", 0:(length(metalabels) - 1), "(v, t) { evtnum(", 0:(length(metalabels) - 1), ", v); } \n", sep = "", collapse = "")), "\t\", \n\t\t\"Popup.class\"] \n\t} \n\t \n\tTransform { \n\ttranslation 0 0 ", scale * scalefac, " \n\trotation 0.28108 0.67860 0.67860 2.59356\n\t \n\tchildren Shape { \n\t\tappearance IS appearance \n\tgeometry DEF POPUP Text { \n\t\tstring \"\" \n\t\tset_string IS showThis \n\t\tfontStyle IS fontStyle \n\t\t} \n\t} \n\t} \n] } \nROUTE POPIT.string_changed TO POPUP.set_string \n} \n \n \nGroup { \nchildren DEF POP PopupText { \n\t\t paste(paste("\"", metalabels[1:(length(metalabels) - 1)], "\",", sep = "", collapse = " ")), "\"", metalabels[length(metalabels)], "\" ] \n\t} \n} \n\n", sep = "", collapse = ""), file = filename, append = TRUE) if (showaxis) { axis3d(lab.axis, filename, type = "vrml", col.lab, col.axis, cex.lab, local_scale = scalefac, global_scale = 1) } blength <- scale * scalefac/(nrow(data) * (1 + space)) bwidth <- scale * scalefac/(ncol(data) * (1 + space)) rot_vec <- c(0, 0.70711, 0.70711, 3.14159) if (lab.vertical) rot_vec <- c(0.57735, 0.57735, 0.57735, 4.18879) if (!is.null(row.labels) && showlegend) { for (j in 1:length(row.labels)) { colsel <- .colorselection(type = "bar", j, rcols, 1, row.labels, "") rcol <- colsel$rcol gcol <- colsel$gcol bcol <- colsel$bcol cur_xwidth <- j/nrow(data) * scale * scalefac - blength/2 write(paste("Transform {\n\ttranslation ", cur_xwidth, -0.4, scale * scalefac + 0.2, "\n\tscale ", cex.rowlab * 0.28, cex.rowlab * 0.28, cex.rowlab * 0.28, "\n\trotation ", rot_vec[1], rot_vec[2], rot_vec[3], rot_vec[4], "\n\tchildren Shape {\n\t\tappearance Appearance { material Material {diffuseColor ", rcol, " ", gcol, " ", bcol, " } }\n\t\tgeometry Text { string \"", row.labels[j], "\" }\n\t}\n}", sep = " "), file = filename, append = TRUE) } } rot_vec <- c(0.57735, 0.57735, 0.57735, 2.0944) if (lab.vertical) rot_vec <- c(0.707107, 0, 0.707107, 3.14159) if (!is.null(col.labels) && showlegend) { for (j in 1:length(col.labels)) { colsel <- .colorselection(type = "bar", j, ccols, 1, col.labels, "") rcol <- colsel$rcol gcol <- colsel$gcol bcol <- colsel$bcol cur_ywidth <- j/ncol(data) * scale * scalefac - bwidth/2 write(paste("Transform {\n\ttranslation ", -0.4, cur_ywidth, scale * scalefac + 0.2, "\n\tscale ", cex.collab * 0.28, cex.collab * 0.28, cex.collab * 0.28, "\n\trotation ", rot_vec[1], rot_vec[2], rot_vec[3], rot_vec[4], "\n\tchildren Shape {\n\t\tappearance Appearance { material Material {diffuseColor ", rcol, " ", gcol, " ", bcol, " } }\n\t\tgeometry Text { string \"", col.labels[j], "\" }\n\t}\n}", sep = " "), file = filename, append = TRUE) } } popup_txt_str <- "" popup_txt_str2 <- "" rcol <- NULL gcol <- NULL bcol <- NULL if (length(cols) >= (ncol(data) * nrow(data))) { rcol <- sapply(cols, function(x) (col2rgb(x)/255)[1]) gcol <- sapply(cols, function(x) (col2rgb(x)/255)[2]) bcol <- sapply(cols, function(x) (col2rgb(x)/255)[3]) } else { if (length(cols) >= 1) { rcol <- (col2rgb(cols[1])/255)[1] gcol <- (col2rgb(cols[1])/255)[2] bcol <- (col2rgb(cols[1])/255)[3] } else { rcol <- (col2rgb("lightblue")/255)[1] gcol <- (col2rgb("lightblue")/255)[2] bcol <- (col2rgb("lightblue")/255)[3] } } counter <- 0 for (j in 1:nrow(data)) { for (k in 1:ncol(data)) { x <- j/nrow(data) * scale * scalefac y <- k/ncol(data) * scale * scalefac z <- data[j, k] if(ignore_zeros && (z == 0)) next counter <- counter + 1 if (!is.null(ccols)) { rcol <- (col2rgb(ccols[k])/255)[1] gcol <- (col2rgb(ccols[k])/255)[2] bcol <- (col2rgb(ccols[k])/255)[3] } else if (!is.null(rcols)) { rcol <- (col2rgb(rcols[j])/255)[1] gcol <- (col2rgb(rcols[j])/255)[2] bcol <- (col2rgb(rcols[j])/255)[3] } else { if(length(rcol) > 1) { rcol <- rcol[(k - 1) * ncol(data) + j] gcol <- gcol[(k - 1) * ncol(data) + j] bcol <- bcol[(k - 1) * ncol(data) + j] } } if (popuptext) { popup_txt_str <- paste("Group {\n children [\n DEF Schalter", (k - 1) * ncol(data) + j - 1, " TouchSensor { }", sep = "", collapse = "") popup_txt_str2 <- "\n]\n}" } write(paste(popup_txt_str, "Transform {\n\ttranslation ", origin[1] + x, origin[2] + y, origin[3] + z/2, "\n\tchildren Shape {\n\t\tappearance Appearance { material Material { diffuseColor ", rcol, gcol, bcol, " } }\n\tgeometry Box { size ", blength, bwidth, z, "}\n\t\t}\n}", popup_txt_str2, sep = " "), file = filename, append = TRUE) } } write("\n", file = filename, append = TRUE) if (popuptext) write(paste("ROUTE Schalter", 0:(length(metalabels) - 1), ".isOver TO POP.over", 0:(length(metalabels) - 1), "\n", sep = "", collapse = ""), file = filename, append = TRUE) if (!exists(".vrmlgenEnv")) { if (!is.null(htmlout)) { cat("<HTML>", file = htmlout, append = FALSE) cat("<HEAD><TITLE>VRMLGen-visualization</TITLE></HEAD><BODY><br>", file = htmlout, append = FALSE) cat(paste("<object type=\"x-world/x-vrml\" data=\"", filename, "\" ", sep = ""), file = htmlout, append = TRUE) cat(paste("width=\"", hwidth, "\" height=\"", hheight, "\"><br>", sep = ""), file = htmlout, append = TRUE) cat(paste("<param name=\"src\" value=\"", filename, "\"><br>", sep = ""), file = htmlout, append = TRUE) cat("Your browser cannot display VRML files.<br>Please INSTALL a VRML-plugin or open the file in an external VRML-viewer.</object><br>", file = htmlout, append = TRUE) cat("</BODY></HTML>", file = htmlout, append = TRUE) } cat(paste("\nOutput file \"", filename, "\" was generated in folder ", getwd(), ".\n", sep = "")) } else { setwd(curdir) } } `.vcloud` <- function (x, y = NULL, z = NULL, labels = rownames(data), metalabels = NULL, hyperlinks = NULL, filename = "out.wrl", pointstyle = c("s", "b", "c"), cols = rainbow(length(unique(labels))), showdensity = FALSE, scalefac = 4, autoscale = "independent", lab.axis = c("X-axis", "Y-axis", "Z-axis"), col.axis = "black", showaxis = TRUE, col.lab = "black", col.bg = "white", cex.lab = 1, navigation = "EXAMINE", transparency = 0, fov = 0.785, pos = rep(scalefac + 4, 3), dir = c(0.19, 0.45, 0.87, 2.45), htmlout = NULL, hwidth = 1200, hheight = 800, showlegend = TRUE) { xyz_parse <- xyz.coords(x, y, z) data <- cbind(xyz_parse$x, xyz_parse$y, xyz_parse$z) if (ncol(data) != 3) { stop("Data matrix does not have 3 columns!") } numlabels <- NULL if (length(labels)) { lab <- unique(unlist(labels)) numlabels <- apply(as.matrix(labels), 1, function(x) match(x, as.matrix(lab))) } curdir <- NULL scale <- 1 if (!exists(".vrmlgenEnv")) { write(" write(paste("\nViewpoint {\n\tfieldOfView", fov, "\n\tposition", pos[1], pos[2], pos[3], "\n\torientation", dir[1], dir[2], dir[3], dir[4], "\n\tjump TRUE\n\tdescription \"viewpoint1\"\n}\n", sep = " "), file = filename, append = TRUE) write(paste("\nNavigationInfo { type \"", navigation, "\" }\n", sep = ""), file = filename, append = TRUE) bg_rcol <- (col2rgb(col.bg)/255)[1] bg_gcol <- (col2rgb(col.bg)/255)[2] bg_bcol <- (col2rgb(col.bg)/255)[3] write(paste("Background {\n\t skyColor [\n\t\t ", bg_rcol, bg_gcol, bg_bcol, " \n\t]\n}", sep = " "), file = filename, append = TRUE) } else { vrmlgenEnv <- get(".vrmlgenEnv",envir=.GlobalEnv) filename <- vrmlgenEnv$filename htmlout <- vrmlgenEnv$html VRMLDir <- vrmlgenEnv$VRMLDir hheight <- vrmlgenEnv$hheight hwidth <- vrmlgenEnv$hwidth scale <- vrmlgenEnv$scale curdir <- getwd() setwd(vrmlgenEnv$VRMLDir) } scaledat <- function(data) { diff <- max(data) - min(data) if (diff == 0) return(data) else return(scale * scalefac * (data - min(data))/(diff)) } if (autoscale == "independent") data <- apply(data, 2, scaledat) else if (autoscale == "equidist") data <- scale * scalefac * (data/max(data)) popuptext <- TRUE if (is.null(metalabels)) { popuptext <- FALSE } if (popuptext) write(paste("\n\nPROTO PopupText [\n\teventIn MFString showThis\n\texposedField SFNode fontStyle FontStyle {\n\t\t\t\tjustify [ \"MIDDLE\", \"MIDDLE\" ] }\n\texposedField SFNode appearance Appearance { material Material { } } \n\tfield SFString default \"\" \n\tfield MFString stringlist [ \"\" ] \n", paste(paste("eventIn SFBool over", 0:(nrow(data) - 1), "\n\t", sep = "", collapse = ""), sep = "", collapse = ""), "\t] { \nGroup { children [ \n\tDEF POPIT Script { \n\t\tfield SFString defstring IS default \n\t\tfield MFString list IS stringlist \n\t\tfield MFString strout [ \"\" ] ", paste(paste("\n eventIn SFBool over", 0:(nrow(data) - 1), " IS over", 0:(nrow(data) - 1), sep = "", collapse = "")), "\n\t\teventOut MFString string_changed \n\t\turl [ \"javascript: \n\t\tfunction evtnum(num, value) \n\t\t{ \n\t\tif (value && (num < list.length)) \n\t\t\tstrout[0] = list[num]; \n\t\telse \n\t\t\tstrout[0] = defstring; \n\t\tstring_changed = strout; \n\t\t} \n \n\t", paste(paste("\tfunction over", 0:(nrow(data) - 1), "(v, t) { evtnum(", 0:(nrow(data) - 1), ", v); } \n", sep = "", collapse = "")), "\t\", \n\t\t\"Popup.class\"] \n\t} \n\t \n\tTransform { \n\ttranslation 0 0 ", scale * scalefac, " \n\trotation 0.28108 0.67860 0.67860 2.59356\n\t \n\tchildren Shape { \n\t\tappearance IS appearance \n\tgeometry DEF POPUP Text { \n\t\tstring \"\" \n\t\tset_string IS showThis \n\t\tfontStyle IS fontStyle \n\t\t} \n\t} \n\t} \n] } \nROUTE POPIT.string_changed TO POPUP.set_string \n} \n \n \nGroup { \nchildren DEF POP PopupText { \n\t\t paste(paste("\"", metalabels[1:(nrow(data) - 1)], "\",", sep = "", collapse = " ")), "\"", metalabels[nrow(data)], "\" ] \n\t} \n} \n\n"), file = filename, append = TRUE) if (length(labels) && showlegend) { cur_height <- scale * scalefac + 1.2 for (j in 1:length(unique(labels))) { .vrmltext(0, 0, cur_height, unique(labels)[j], filename, cols[unique(numlabels)[j]], 1, c(0.28108, 0.6786, 0.6786, 2.59356), "SANS", "NONE", NULL) cur_height <- cur_height + 0.4 } } if (showaxis) { axis3d(lab.axis, filename, type = "vrml", col.lab, col.axis, cex.lab, local_scale = scalefac, global_scale = 1) } popup_txt_str <- "" popup_txt_str2 <- "" hyperlink <- NULL for (j in 1:nrow(data)) { x <- data[j, 1] y <- data[j, 2] z <- data[j, 3] colsel <- .colorselection(type = "cloud", j, cols, nrow(data), labels, numlabels) rcol <- colsel$rcol gcol <- colsel$gcol bcol <- colsel$bcol if (popuptext) { popup_txt_str <- paste("Group {\n children [\n DEF Schalter", j - 1, " TouchSensor { }", sep = "", collapse = "") popup_txt_str2 <- "\n]\n}" } if (!is.null(hyperlinks)) { hyperlink <- hyperlinks[j] } if (length(pointstyle) == 1) { write(popup_txt_str, file = filename, append = TRUE) .vrmlpoints(x, y, z, filename, rcol, gcol, bcol, pointstyle, hyperlinks = hyperlink, global_scale = 1, local_scale = 1, transparency) write(popup_txt_str2, file = filename, append = TRUE) } else if (length(pointstyle) >= length(unique(numlabels))) { if (length(labels)) { stylevec <- c("s", "b", "c") curstyle <- stylevec[numlabels[j]] write(popup_txt_str, file = filename, append = TRUE) .vrmlpoints(x, y, z, filename, rcol, gcol, bcol, curstyle, hyperlinks = hyperlink, global_scale = 1, local_scale = 1, transparency) write(popup_txt_str2, file = filename, append = TRUE) } else { popup_txt_str <- "" popup_txt_str2 <- "" write(popup_txt_str, file = filename, append = TRUE) .vrmlpoints(x, y, z, filename, rcol, gcol, bcol, pointstyle[1], hyperlinks = hyperlink, global_scale = 1, local_scale = 1, transparency) write(popup_txt_str2, file = filename, append = TRUE) } } else { write(popup_txt_str, file = filename, append = TRUE) .vrmlpoints(x, y, z, filename, rcol, gcol, bcol, pointstyle[1], hyperlinks = hyperlink, global_scale = 1, local_scale = 1, transparency) write(popup_txt_str2, file = filename, append = TRUE) } } write("\n", file = filename, append = TRUE) if (popuptext) write(paste("ROUTE Schalter", 0:(nrow(data) - 1), ".isOver TO POP.over", 0:(nrow(data) - 1), "\n", sep = "", collapse = ""), file = filename, append = TRUE) if (showdensity) est <- .vdense(data, filename) if (!exists(".vrmlgenEnv")) { if (!is.null(htmlout)) { cat("<HTML>", file = htmlout, append = FALSE) cat("<HEAD><TITLE>VRMLGen-visualization</TITLE></HEAD><BODY><br>", file = htmlout, append = FALSE) cat(paste("<object type=\"x-world/x-vrml\" data=\"", filename, "\" ", sep = ""), file = htmlout, append = TRUE) cat(paste("width=\"", hwidth, "\" height=\"", hheight, "\"><br>", sep = ""), file = htmlout, append = TRUE) cat(paste("<param name=\"src\" value=\"", filename, "\"><br>", sep = ""), file = htmlout, append = TRUE) cat("Your browser cannot display VRML files.<br>Please INSTALL a VRML-plugin or open the file in an external VRML-viewer.</object><br>", file = htmlout, append = TRUE) cat("</BODY></HTML>", file = htmlout, append = TRUE) } cat(paste("\nOutput file \"", filename, "\" was generated in folder ", getwd(), ".\n", sep = "")) } else { setwd(curdir) } } `.vdense` <- function (x, filename) { nobs <- nrow(x) ndim <- ncol(x) weights <- rep(1, nobs) nbins <- round((nobs > 500) * 8 * log(nobs)/ndim) if (nbins > 0) { breaks <- cbind(seq(min(x[, 1]), max(x[, 1]), length = nbins + 1), seq(min(x[, 2]), max(x[, 2]), length = nbins + 1)) f1 <- cut(x[, 1], breaks = breaks[, 1]) f2 <- cut(x[, 2], breaks = breaks[, 2]) f3 <- cut(x[, 3], breaks = breaks[, 3]) freq <- table(f1, f2, f3) dimnames(freq) <- NULL midpoints <- (breaks[-1, ] + breaks[-(nbins + 1), ])/2 z1 <- midpoints[, 1] z2 <- midpoints[, 2] z3 <- midpoints[, 3] X <- as.matrix(expand.grid(z1, z2, z3)) X.f <- as.vector(freq) id <- (X.f > 0) X <- X[id, ] dimnames(X) <- list(NULL, dimnames(x)[[2]]) X.f <- X.f[id] bins <- list(x = X, x.freq = X.f, midpoints = midpoints, breaks = breaks, table.freq = freq) x <- bins$x weights <- bins$x.freq nx <- length(bins$x.freq) } else nx <- nobs h <- .hnorm(x, weights) rawdata <- list(nbins = nbins, x = x, nobs = nobs, ndim = ndim) est <- .vdensecalc(x, h = h, weights = weights, rawdata = rawdata, filename = filename) return(TRUE) } `.vdensecalc` <- function (x, h = .hnorm(x, weights), eval.points = NULL, weights = rep(1, length(x)), rawdata = list(), eval.type = "grid", filename = "test.wrl") { xlim <- range(x[, 1]) ylim <- range(x[, 2]) zlim <- range(x[, 3]) ngrid <- 20 if (eval.type != "points") { evp <- cbind(seq(xlim[1], xlim[2], length = ngrid), seq(ylim[1], ylim[2], length = ngrid), seq(zlim[1], zlim[2], length = ngrid)) eval.points <- evp } h.weights <- rep(1, nrow(x)) n <- nrow(x) nnew <- nrow(eval.points) hmult <- 1 result <- list(eval.points = eval.points, h = h * hmult, h.weights = h.weights, weights = weights) Wh <- matrix(rep(h.weights, nnew), ncol = n, byrow = TRUE) W1 <- matrix(rep(eval.points[, 1], rep(n, nnew)), ncol = n, byrow = TRUE) W1 <- W1 - matrix(rep(x[, 1], nnew), ncol = n, byrow = TRUE) W1 <- exp(-0.5 * (W1/(hmult * h[1] * Wh))^2)/Wh W2 <- matrix(rep(eval.points[, 2], rep(n, nnew)), ncol = n, byrow = TRUE) W2 <- W2 - matrix(rep(x[, 2], nnew), ncol = n, byrow = TRUE) W2 <- exp(-0.5 * (W2/(hmult * h[2] * Wh))^2)/Wh W3 <- matrix(rep(eval.points[, 3], rep(n, nnew)), ncol = n, byrow = TRUE) W3 <- W3 - matrix(rep(x[, 3], nnew), ncol = n, byrow = TRUE) W3 <- exp(-0.5 * (W3/(hmult * h[3] * Wh))^2)/Wh if (eval.type == "points") { est <- as.vector(((W1 * W2 * W3) %*% weights)/(sum(weights) * (2 * pi)^1.5 * h[1] * h[2] * h[3] * hmult^3)) return(est) } est <- .vdensecalc(x, h, x, eval.type = "points", weights = weights, filename = filename) props <- c(75, 50, 25) cols <- topo.colors(length(props)) alpha <- seq(1, 0.5, length = length(props)) levels <- quantile(est, props/100) est <- apply(W3, 1, function(x) (W1 %*% (weights * x * t(W2)))/(sum(weights) * (2 * pi)^1.5 * h[1] * h[2] * h[3] * hmult^3)) est <- array(c(est), dim = rep(ngrid, 3)) struct <- NULL if (require(misc3d)) { struct <- contour3d(est, levels, eval.points[, 1], eval.points[, 2], eval.points[, 3], engine = "none") } else { stop("In order to draw contour surfaces, please first install the misc3d package!") } for (i in 1:length(props)) { if (length(props) > 1) strct <- struct[[i]] else strct <- struct trngs.x <- c(t(cbind(strct$v1[, 1], strct$v2[, 1], strct$v3[, 1]))) trngs.y <- c(t(cbind(strct$v1[, 2], strct$v2[, 2], strct$v3[, 2]))) trngs.z <- c(t(cbind(strct$v1[, 3], strct$v2[, 3], strct$v3[, 3]))) a <- list(x = trngs.x, y = trngs.y, z = trngs.z) rcol <- (col2rgb(cols[i])/255)[1] gcol <- (col2rgb(cols[i])/255)[2] bcol <- (col2rgb(cols[i])/255)[3] for (j in seq(1, length(trngs.x), 3)) { write(paste("\n Shape { \n\tappearance Appearance {\n\t\t material Material {\n\t\tdiffuseColor ", rcol, " ", gcol, " ", bcol, "\n\t\ttransparency ", alpha[i], " \n\t}\n\t}\t\n \n\t geometry IndexedFaceSet {\n\t \t\tsolid TRUE \t \n\t\tcoord Coordinate {\n\t\t\t point [\n\t\t\t ", trngs.x[j], trngs.y[j], trngs.z[j], " \n\t\t\t ", trngs.x[j + 1], trngs.y[j + 1], trngs.z[j + 1], " \n\t\t\t ", trngs.x[j + 2], trngs.y[j + 2], trngs.z[j + 2], " \n\t\t ]\n\t }\n\t coordIndex [\t0 1 2\t] \n\t}\t \n }\n ", sep = " "), file = filename, append = TRUE) } } return(est) } `.hnorm` <- function (x, weights = NA) { if (all(is.na(weights))) weights <- rep(1, nrow(x)) ndim <- ncol(as.matrix(x)) if (ndim != 3) stop("only data with 3 dimensions is allowed.") n <- sum(weights) sd <- sqrt(apply(x, 2, function(x, w) { sum(w * (x - sum(x * w)/sum(w))^2)/(sum(w) - 1) }, w = weights)) hh <- sd * (4/(5 * n))^(1/7) hh } `.vmesh` <- function (infile = NULL, x = NULL, y = NULL, z = NULL, edges = NULL, xfun = "sin(v)*cos(u)", yfun = "sin(v)*sin(u)", zfun = "cos(v)", param1 = "u", param2 = "v", range1 = c(0, 2 * pi), range2 = c(0, pi), size1 = 30, size2 = 30, write_obj = FALSE, filename = "out.wrl", cols = "red", scalefac = 4, autoscale = ifelse(is.null(infile), "independent", "equicenter"), lab.axis = c("X-axis", "Y-axis", "Z-axis"), col.axis = "black", showaxis = TRUE, col.lab = "black", col.bg = "white", cex.lab = 1, navigation = "EXAMINE", transparency = 0, fov = 0.785, pos = rep(scalefac + 4, 3), dir = c(0.19, 0.45, 0.87, 2.45), htmlout = NULL, hwidth = 1200, hheight = 800) { if (write_obj) { if (is.null(x) && is.null(edges)) { stop("\nThe generation of obj-files is currently only supported, when using vertex-coordinates (x, y, z-parameters) and polygonal face indices (edges-parameter) as input.") } write(" append = FALSE) xyz_parse <- xyz.coords(x, y, z) write(paste("v", xyz_parse$x, xyz_parse$y, xyz_parse$z, sep = " "), file = filename, append = TRUE) write("\n", file = filename, append = TRUE) for (i in 1:nrow(edges)) { write(paste("f", paste(edges[i, ], collapse = " "), sep = " "), file = filename, append = TRUE) } cat(paste("\nOutput file \"", filename, "\" was generated in folder ", getwd(), ".\n", sep = "")) } else { if (!is.null(infile)) { obj <- strsplit(readLines(infile), "\t") faces <- which(as.numeric(lapply(obj, function(x) grep("^f", x[1]))) == 1) nodes <- which(as.numeric(lapply(obj, function(x) grep("^v ", x[1]))) == 1) tmpmat <- lapply(obj[nodes], function(x) strsplit(x, " ")[[1]]) redmat <- t(sapply(tmpmat, function(x) as.numeric(x[2:length(x)]))) data <- redmat[, which(apply(redmat, 2, function(x) !any(is.na(x))))] edges_lst <- lapply(obj[faces], function(x) strsplit(x, " ")[[1]]) edges_filt1 <- lapply(edges_lst, function(y) as.numeric(sapply(y[2:length(y)], function(x) strsplit(x, "/")[[1]][1]))) edges_filt <- lapply(edges_filt1, function(x) x[which(!is.na(x))]) filter <- sapply(edges_filt, length) > 4 filt <- edges_filt[filter] reduced_lst <- NULL if (length(filt) > 0) { for (j in 1:length(filt)) { reduced_lst <- c(reduced_lst, list(filt[[j]][1:4])) for (k in seq(4, length(filt[[j]]), 3)) { if (!is.na(filt[[j]][k + 2])) { reduced_lst <- c(reduced_lst, list(c(filt[[j]][k:(k + 2)], filt[[j]][1]))) } else if (!is.na(filt[[j]][k + 1])) { reduced_lst <- c(reduced_lst, list(c(filt[[j]][k:(k + 1)], filt[[j]][1], 0))) break } else { break } } } } comb_lst <- c(edges_filt[!filter], reduced_lst) filtless <- which(sapply(comb_lst, length) < 4) comb_lst[filtless] <- lapply(comb_lst[filtless], function(x) c(x, 0)) all(sapply(comb_lst, length) == 4) edges <- t(sapply(comb_lst, rbind)) - 1 } else if (is.null(x)) { if (is.null(xfun) || is.null(yfun) || is.null(zfun)) { stop("Either the paramater infile or data or the parameters xfun, yfun and zfun have to be specified.") } if (is.null(param1) || is.null(param2)) { stop("The parameter names param1 and param2 have not been specified") } x <- NULL y <- NULL z <- NULL smin <- range1[1] smax <- range1[2] tmin <- range2[1] tmax <- range2[2] sn <- size1 tn <- size2 ds <- (smax - smin)/sn dt <- (tmax - tmin)/tn for (i in seq(smin, (smax - ds/2), ds)) { for (j in seq(tmin, (tmax - dt/2), dt)) { eval(parse(text = paste(param1, " <- ", i))) eval(parse(text = paste(param2, " <- ", j))) x <- c(x, eval(parse(text = xfun))) y <- c(y, eval(parse(text = yfun))) z <- c(z, eval(parse(text = zfun))) eval(parse(text = paste(param1, " <- ", param1, " + ds"))) x <- c(x, eval(parse(text = xfun))) y <- c(y, eval(parse(text = yfun))) z <- c(z, eval(parse(text = zfun))) eval(parse(text = paste(param2, " <- ", param2, " + dt"))) x <- c(x, eval(parse(text = xfun))) y <- c(y, eval(parse(text = yfun))) z <- c(z, eval(parse(text = zfun))) eval(parse(text = paste(param1, " <- ", param1, " - ds"))) x <- c(x, eval(parse(text = xfun))) y <- c(y, eval(parse(text = yfun))) z <- c(z, eval(parse(text = zfun))) } } data <- as.matrix(cbind(x, y, z)) } else { xyz_parse <- xyz.coords(x, y, z) data <- cbind(xyz_parse$x, xyz_parse$y, xyz_parse$z) } if (ncol(data) != 3) { stop("Data matrix does not have 3 columns!") } scale <- 1 curdir <- NULL if (!exists(".vrmlgenEnv")) { write(" write(paste("\nViewpoint {\n\tfieldOfView", fov, "\n\tposition", pos[1], pos[2], pos[3], "\n\torientation", dir[1], dir[2], dir[3], dir[4], "\n\tjump TRUE\n\tdescription \"viewpoint1\"\n}\n", sep = " "), file = filename, append = TRUE) write(paste("\nNavigationInfo { type \"", navigation, "\" }\n", sep = ""), file = filename, append = TRUE) bg_rcol <- (col2rgb(col.bg)/255)[1] bg_gcol <- (col2rgb(col.bg)/255)[2] bg_bcol <- (col2rgb(col.bg)/255)[3] write(paste("Background {\n\t skyColor [\n\t\t ", bg_rcol, bg_gcol, bg_bcol, " \n\t]\n}", sep = " "), file = filename, append = TRUE) } else { vrmlgenEnv <- get(".vrmlgenEnv",envir=.GlobalEnv) filename <- vrmlgenEnv$filename htmlout <- vrmlgenEnv$html hheight <- vrmlgenEnv$hheight hwidth <- vrmlgenEnv$hwidth scale <- vrmlgenEnv$scale curdir <- getwd() setwd(vrmlgenEnv$VRMLDir) } scaledat <- function(data) { diff <- max(data) - min(data) if (diff == 0) return(data) else return(scale * scalefac * (data - min(data))/(diff)) } if (autoscale == "independent") data <- apply(data, 2, scaledat) else if (autoscale == "equidist") data <- scale * scalefac * (data/max(data)) else if (autoscale == "equicenter") data <- scale * scalefac/2 * data/max(data) + scalefac/2 if (showaxis) { axis3d(lab.axis, filename, type = "vrml", col.lab, col.axis, cex.lab, local_scale = scalefac, global_scale = 1) } write(paste("Transform {\nscale 1.0 1.0 1.0\n\tchildren [\n\t\tShape {\n\t\t\tappearance Appearance{ material Material{ transparency ",transparency,"}}\n", sep = " "), file = filename, append = TRUE) write(paste("\n\t\t\tgeometry IndexedFaceSet {\n\t\t\tcoord DEF\n\tVertexArray Coordinate{\n\tpoint [\n", sep = " "), file = filename, append = TRUE) for (j in 1:nrow(data)) { write(paste(paste(data[j, ], collapse = " "), ",\n", sep = ""), file = filename, append = TRUE) } write("]\n}\n", file = filename, append = TRUE) write("coordIndex [\n", file = filename, append = TRUE) mat <- NULL if (!is.null(edges)) { mat <- edges while (ncol(mat) < 4) { mat <- cbind(mat, rep(-1, nrow(mat))) } } else { mat <- matrix(1:nrow(data), ncol = 4, byrow = TRUE) - 1 } for (j in 1:nrow(mat)) { write(paste(paste(mat[j, ], collapse = " "), "-1", sep = " "), file = filename, append = TRUE) } write(paste("]\n solid FALSE\n colorPerVertex TRUE\n color \nDEF VertexColorArray Color{\ncolor [", sep = ""), file = filename, append = TRUE) if (!length(cols) || (is.null(cols))) { cols <- rainbow(nrow(data)) mat <- sapply(cols, function(x) (col2rgb(x)/255)) for (j in 1:nrow(data)) { write(paste(mat[1, j], mat[2, j], mat[3, j], ",\n", collapse = " "), file = filename, append = TRUE) } } else if ((length(cols) == 1) || (length(cols) < nrow(data))) { rcol <- (col2rgb(cols[1])/255)[1] gcol <- (col2rgb(cols[1])/255)[2] bcol <- (col2rgb(cols[1])/255)[3] for (j in 1:nrow(data)) { write(paste(rcol, gcol, bcol, ",\n", collapse = " "), file = filename, append = TRUE) } } else { mat <- sapply(cols, function(x) (col2rgb(x)/255)) for (j in 1:nrow(data)) { write(paste(mat[1, j], mat[2, j], mat[3, j], ",\n", collapse = " "), file = filename, append = TRUE) } } write(paste("]\n}\n}\n}\n]\n}", sep = ""), file = filename, append = TRUE) if (!exists(".vrmlgenEnv")) { if (!is.null(htmlout)) { cat("<HTML>", file = htmlout, append = FALSE) cat("<HEAD><TITLE>VRMLGen-visualization</TITLE></HEAD><BODY><br>", file = htmlout, append = FALSE) cat(paste("<object type=\"x-world/x-vrml\" data=\"", filename, "\" ", sep = ""), file = htmlout, append = TRUE) cat(paste("width=\"", hwidth, "\" height=\"", hheight, "\"><br>", sep = ""), file = htmlout, append = TRUE) cat(paste("<param name=\"src\" value=\"", filename, "\"><br>", sep = ""), file = htmlout, append = TRUE) cat("Your browser cannot display VRML files.<br>Please INSTALL a VRML-plugin or open the file in an external VRML-viewer.</object><br>", file = htmlout, append = TRUE) cat("</BODY></HTML>", file = htmlout, append = TRUE) } cat(paste("\nOutput file \"", filename, "\" was generated in folder ", getwd(), ".\n", sep = "")) } else { setwd(curdir) } } } `.vrmlpoints` <- function (x, y, z, filename, rcol, gcol, bcol, pointstyle, hyperlinks = NULL, global_scale = 1, local_scale = 1, transparency = 0) { hyperlinks_start <- rep("", length(x)) hyperlinks_end <- rep("", length(x)) if (!is.null(hyperlinks)) { hyperlinks_start <- paste("\n\tchildren Anchor { url \"", hyperlinks, "\"", sep = "") hyperlinks_end <- rep("}", length(x)) } if (pointstyle == "s") { for (i in 1:length(x)) write(paste("\nTransform {\n\ttranslation ", x[i] * global_scale, y[i] * global_scale, z[i] * global_scale, hyperlinks_start[i], "\n\tchildren Shape {\n\t\tappearance Appearance { material Material { diffuseColor", rcol, gcol, bcol, "transparency", transparency, "} }\n\tgeometry Sphere { radius ", 0.08 * local_scale, "}\n\t\t}", hyperlinks_end[i], "\n}", sep = " "), file = filename, append = TRUE) } else if (pointstyle == "c") { for (i in 1:length(x)) write(paste("\nTransform {\n\trotation 1 0 0 1.5708\n\ttranslation ", x[i] * global_scale, y[i] * global_scale, z[i] * global_scale, hyperlinks_start[i], "\n\tchildren Shape {\n\t\tappearance Appearance { material Material { diffuseColor", rcol, gcol, bcol, "transparency", transparency, "} }\n\tgeometry Cone { bottomRadius ", 0.08 * local_scale, "height", 0.08 * local_scale, "\n\t\tside TRUE}\n\t\t}", hyperlinks_end[i], "\n}", sep = " "), file = filename, append = TRUE) } else { for (i in 1:length(x)) write(paste("\nTransform {\n\ttranslation ", x[i] * global_scale, y[i] * global_scale, z[i] * global_scale, hyperlinks_start[i], "\n\tchildren Shape {\n\t\tappearance Appearance { material Material { diffuseColor", rcol, gcol, bcol, "transparency", transparency, "} }\n\tgeometry Box { size ", 0.08 * local_scale, 0.08 * local_scale, 0.08 * local_scale, "}\n\t\t}", hyperlinks_end[i], "\n}", sep = " "), file = filename, append = TRUE) } } `.vrmltext` <- function (x, y, z, text, filename, col, scale, rot, fontfamily, fontweight, hyperlink) { rcol <- (col2rgb(col)/255)[1] gcol <- (col2rgb(col)/255)[2] bcol <- (col2rgb(col)/255)[3] if (is.null(hyperlink)) { for (i in 1:length(x)) write(paste("Transform {\n\ttranslation ", x[i], y[i], z[i], "\n\tscale ", 0.28, 0.28, 0.28, "\n\trotation ", rot[1], rot[2], rot[3], rot[4], "\n\tchildren Shape {\n\t\tappearance Appearance { material Material {diffuseColor ", rcol, gcol, bcol, " } }\n\tgeometry Text { string \"", text[i], "\"\nfontStyle FontStyle {\nsize ", scale, "\nfamily [\"", fontfamily, "\"]\njustify \"MIDDLE\"\n style \"", fontweight, "\" }\n }\n\t}\n}", sep = " "), file = filename, append = TRUE) } else { for (i in 1:length(x)) write(paste("Transform {\n\ttranslation ", x[i], y[i], z[i], "\n\tscale ", 0.28, 0.28, 0.28, "\n\trotation ", rot[1], rot[2], rot[3], rot[4], "\n\tchildren Anchor { url \"", hyperlink, "\" \n\tchildren Shape {\n\t\tappearance Appearance { material Material {diffuseColor ", rcol, gcol, bcol, " } }\n\tgeometry Text { string \"", text[i], "\"\nfontStyle FontStyle {\nsize ", scale, "\nfamily [\"SANS\"]\njustify \"MIDDLE\"\n style \"", fontweight, "\" }\n }\n\t}\n}\n}", sep = " "), file = filename, append = TRUE) } }