code
stringlengths
1
13.8M
unpipe <- function(expr) { if (length(expr) == 1) { return(expr) } else { if (expr[[1]] == quote(`%>%`)) { return(as.call(append(as.list(unpipe(expr[[3]])), unpipe(expr[[2]]), after = 1))) } else { return(as.call(lapply(expr, unpipe))) } } }
test_that("new solution-class", { x <- pproto(NULL, Solution, data = list()) expect_s3_class(x, "Solution") }) test_that("data.frame inputs", { data(sim_pu_data, sim_features_data, sim_dist_features_data, sim_threats_data, sim_dist_threats_data, sim_sensitivity_data, sim_boundary_data) sim_features_data$target_recovery <- c(40, 20, 50, 30) x <- suppressWarnings(inputData(pu = sim_pu_data, features = sim_features_data, dist_features = sim_dist_features_data, threats = sim_threats_data, dist_threats = sim_dist_threats_data, sensitivity = sim_sensitivity_data, boundary = sim_boundary_data)) p <- suppressWarnings(problem(x)) s <- solve(p, output_file = FALSE) expect_s3_class(s, "Solution") expect_equal(s$data$sol[1:10], c(0, 0, 0, 0, 0, 0, 0, 1, 1, 1)) }) test_that("verify gurobi and rphymphony", { skip_on_ci() skip_on_cran() data(sim_pu_data, sim_features_data, sim_dist_features_data, sim_threats_data, sim_dist_threats_data, sim_sensitivity_data, sim_boundary_data) sim_features_data$target_recovery <- c(40, 20, 50, 30) x <- suppressWarnings(inputData(pu = sim_pu_data, features = sim_features_data, dist_features = sim_dist_features_data, threats = sim_threats_data, dist_threats = sim_dist_threats_data, sensitivity = sim_sensitivity_data, boundary = sim_boundary_data)) p <- suppressWarnings(problem(x)) s1 <- solve(p, output_file = FALSE, solver = "gurobi") s2 <- solve(p, output_file = FALSE, solver = "symphony") expect_s3_class(s1, "Solution") expect_s3_class(s2, "Solution") expect_equal(s1$data$sol[1:10], s2$data$sol[1:10]) })
options(warn = 1) rm(list = ls(all = TRUE)) library(pls) library(RUnit) source("RUnit/common/utils.R") opts <- getOption("RUnit") opts$silent <- TRUE options(RUnit = opts) testdirs <- c("RUnit/common", "RUnit/library") plsTestSuite <- defineTestSuite("pls", testdirs) isValidTestSuite(plsTestSuite) printTextProtocol(res <- runTestSuite(plsTestSuite)) if (res$pls$nFail > 0 || res$pls$nErr > 0) stop("One or more tests failed")
miive <- function(model = model, data = NULL, instruments = NULL, sample.cov = NULL, sample.mean = NULL, sample.nobs = NULL, sample.cov.rescale = TRUE, estimator = "2SLS", se = "standard", bootstrap = 1000L, boot.ci = "norm", missing = "listwise", est.only = FALSE, var.cov = FALSE, miiv.check = TRUE, ordered = NULL, sarg.adjust = "none", overid.degree = NULL, overid.method = "stepwise.R2" ){ if(is.null(data)){ if (!is.null(ordered)){ stop(paste( "miive: raw data required when declaring factor variables.") ) } if(!is.null(sample.mean)){ if (!is.null(sample.mean) & !is.vector(sample.mean)){ stop(paste( "miive: sample.mean must be a vector.") ) } if (!all.equal( names(sample.mean), colnames(sample.cov), check.attributes = FALSE )){ stop(paste( "miive: names of sample.mean vector", "and sample.cov matrix must match.") ) } } if(sample.cov.rescale & !is.null(sample.cov)){ sample.cov <- sample.cov * (sample.nobs-1)/sample.nobs } } if ( "miivs" == class(model) ){ d <- model$eqns pt <- model$pt } else { res <- miivs(model) d <- res$eqns pt <- res$pt } d <- parseInstrumentSyntax(d, instruments, miiv.check) underid <- unlist(lapply(d, function(eq) { length(eq$MIIVs) < length(eq$IVobs) })) d.un <- d[underid]; d <- d[!underid] if(!is.null(data)){ obs.vars <- unique(unlist(lapply(d,"[", c("DVobs", "IVobs", "MIIVs")))) if (any(!obs.vars %in% colnames(data))){ stop(paste( "miive: model syntax contains variables not in data.") ) } data <- data[,colnames(data) %in% obs.vars] data <- as.data.frame(data) data[,ordered] <- lapply( data[,ordered, drop = FALSE], ordered ) } if (!is.null(data) & missing == "listwise"){ data <- data[stats::complete.cases(data),] } g <- processData(data, sample.cov, sample.mean, sample.nobs, ordered, missing, se, pt ) if (!is.null(overid.degree)){ d <- pruneExcessMIIVs(d, overid.degree, overid.method, data = data, sample.cov = g$sample.cov, sample.polychoric = g$sample.polychoric, sample.mean = g$sample.mean, sample.nobs = g$sample.nobs, cat.vars = g$var.categorical) } d <- lapply(d, function (eq) { eq$missing <- ifelse( any(g$var.nobs[c(eq$DVobs, eq$IVobs, eq$MIIVs)] < g$sample.nobs), TRUE, FALSE ) eq$categorical <- ifelse( any(g$var.categorical[c(eq$DVobs, eq$IVobs, eq$MIIVs)]), TRUE, FALSE ) eq$exogenous <- ifelse( any(g$var.exogenous[c(eq$DVobs, eq$IVobs, eq$MIIVs)]), TRUE, FALSE ) if (eq$categorical & eq$exogenous){ stop(paste("miive: exogenous variables in", "equations containing categorical", "variables (including MIIVs)", "are not currently supported.")) } eq }) r <- buildRestrictMat(d) d <- lapply(d, function (eq) { eq$restricted <- ifelse( r$eq.restricted[eq$DVobs], TRUE, FALSE ) if ((eq$categorical & eq$restricted) & se == "standard"){ stop(paste("miive: When SE = 'standard', restrictions", "on coefficients in equations containing", "categorical variables (including MIIVs)", "are not allowed. Remove restrictions or", "use se = 'bootstrap'.")) } eq }) results <- switch( estimator, "2SLS" = miive.2sls(d, g, r, est.only, se, missing, var.cov, sarg.adjust), stop( paste( "Invalid estimator:", estimator, "Valid estimators are: 2SLS" ) ) ) if (var.cov){ if(length(d.un) > 0){ stop(paste("MIIVsem: variance covariance esimtation not", "allowed in the presence of underidentified", "equations.")) } v <- estVarCovarCoef(data = data, g = g, eqns = results$eqn, pt = pt, ordered = ordered) } else { v <- NULL } results$boot <- NULL if(se == "boot" | se == "bootstrap"){ if(is.null(data)){ stop(paste("miive: raw data required for bootstrap SEs.")) } boot.results <- boot::boot(data, function(origData, indices){ bsample <- origData[indices,] g.b <- processData( data = bsample, sample.cov = NULL, sample.mean = NULL, sample.nobs = NULL, ordered = ordered, missing = missing, se = se, pt = pt ) brep <- switch( estimator, "2SLS" = miive.2sls(d, g.b, r, est.only = TRUE, se, missing, var.cov), stop(paste( "Invalid estimator:", estimator, "Valid estimators are: 2SLS") ) ) if (var.cov){ v.b <- estVarCovarCoef(bsample, g.b, brep$eqn, pt, ordered) c(brep$coefficients, v.b$coefficients) } else { brep$coefficients } }, bootstrap) boot.mat <- boot.results$t[ stats::complete.cases(boot.results$t), ] results$bootstrap.true <- nrow(boot.mat) if (results$bootstrap.true > 0){ nearZero <- apply(boot.mat , 2, stats::var, na.rm=TRUE) < 1e-16 } else { nearZero <- FALSE } coefCov <- stats::cov(boot.mat) if(any(nearZero)) { coefCov[nearZero,nearZero] <- round( coefCov[nearZero,nearZero], 1e-10 ) } rownames(coefCov) <- colnames(coefCov) <- c( names(results$coefficients), if (var.cov) { paste0(names(v$coefficients))} else { NULL } ) results$eqn <- lapply(results$eqn, function(eq) { eq$coefCov <- coefCov[ names(eq$coefficients), names(eq$coefficients), drop = FALSE ] eq }) results$coefCov <- coefCov[ names(results$coefficients), names(results$coefficients), drop = FALSE ] if (var.cov){ v$coefCov <- coefCov[ names(v$coefficients), names(v$coefficients), drop = FALSE ] } results$boot <- boot.results } if (missing == "twostage" & se == "standard" & var.cov == TRUE){ } results$model <- model results$estimator <- estimator results$se <- se results$var.cov <- var.cov results$missing <- missing results$boot.ci <- boot.ci results$bootstrap <- bootstrap results$call <- match.call() results$ordered <- ordered results$pt <- unclass(pt) results$eqn.unid <- d.un results$r <- r results$v <- v class(results) <- "miive" results }
Distmat <- methods::setRefClass("Distmat", fields = list( distmat = "ANY", series = "list", distfun = "function", dist_args = "list", id_cent = "integer" ), methods = list( initialize = function(..., distmat, series, distance, control, error.check = TRUE) { "Initialization based on needed parameters" if (missing(distmat)) { if (tolower(distance) == "dtw_lb") distance <- "dtw_basic" if (error.check) { check_consistency(series, "vltslist") check_consistency(distance, "dist", trace = FALSE, diff_lengths = different_lengths(series), silent = FALSE) if (class(control) != "PtCtrl") stop("Invalid control provided.") } control$distmat <- NULL initFields(..., series = series, distfun = ddist2(distance, control)) } else initFields(..., distmat = distmat) invisible(NULL) } ) ) NULL setMethod(`[`, "Distmat", function(x, i, j, ..., drop = TRUE) { if (inherits(x$distmat, "uninitializedField")) { if (inherits(x$distfun, "uninitializedField")) stop("Invalid internal Distmat instance.") centroids <- if (identical(i,j)) NULL else x$series[j] dm <- quoted_call(x$distfun, x = x$series[i], centroids = centroids, dots = x$dist_args) } else { dm <- x$distmat[i, j, drop = drop] if (identical(dim(dm), dim(x$distmat))) attributes(dm) <- attributes(x$distmat) } dm }) dim.Distmat <- function(x) { dim(x$distmat) }
docklet_create <- function(name = random_name(), size = getOption("do_size", "s-1vcpu-2gb"), region = getOption("do_region", "sfo3"), ssh_keys = getOption("do_ssh_keys", NULL), backups = getOption("do_backups", NULL), ipv6 = getOption("do_ipv6", NULL), private_networking = getOption("do_private_networking", NULL), tags = list(), wait = TRUE, image = "docker-18-04", ...) { droplet_create( name = name, size = size, image = image, region = region, ssh_keys = ssh_keys, backups = backups, ipv6 = ipv6, private_networking = private_networking, tags = tags, wait = wait, ... ) } docklet_ps <- function(droplet, all = TRUE, ssh_user = "root") { docklet_docker(droplet, "ps", if (all) "-a", ssh_user = ssh_user) } docklet_images <- function(droplet, all = TRUE, ssh_user = "root") { docklet_docker(droplet, "images", if (all) "-a", ssh_user = ssh_user) } docklet_pull <- function(droplet, repo, ssh_user = "root", keyfile = NULL, ssh_passwd = NULL, verbose = FALSE) { docklet_docker(droplet, "pull", repo, ssh_user = ssh_user, keyfile = keyfile, ssh_passwd = ssh_passwd, verbose = verbose) } docklet_run <- function(droplet, ..., rm = FALSE, name = NULL, ssh_user = "root", keyfile = NULL, ssh_passwd = NULL, verbose = FALSE) { docklet_docker(droplet, "run", c( if (rm) " --rm", if (!is.null(name)) paste0(" --name=", name), ... ), ssh_user = ssh_user, keyfile = keyfile, ssh_passwd = ssh_passwd, verbose = verbose ) } docklet_stop <- function(droplet, container, ssh_user = "root") { docklet_docker(droplet, "stop", container, ssh_user = ssh_user) } docklet_rm <- function(droplet, container, ssh_user = "root") { docklet_docker(droplet, "rm", container, ssh_user = ssh_user) } docklet_docker <- function(droplet, cmd, args = NULL, docker_args = NULL, ssh_user = "root", keyfile = NULL, ssh_passwd = NULL, verbose = FALSE) { check_for_a_pkg("ssh") args <- paste(args, collapse = " ") droplet_ssh( droplet, user = ssh_user, keyfile = keyfile, ssh_passwd = ssh_passwd, paste(c("docker", docker_args, cmd, args), collapse = " "), verbose = verbose) } docklet_rstudio <- function(droplet, user, password, email = '[email protected]', img = 'rocker/rstudio', port = '8787', volume = '', dir = '', browse = TRUE, add_users = FALSE, ssh_user = "root", keyfile = NULL, ssh_passwd = NULL, verbose = FALSE) { if (missing(user)) stop("'user' is required") if (missing(password)) stop("'password' is required") if (password == "rstudio") stop("supply a 'password' other than 'rstudio'") droplet <- as.droplet(droplet) docklet_pull(droplet, img, ssh_user, keyfile = keyfile, ssh_passwd = ssh_passwd, verbose = verbose) docklet_run(droplet, " -d", " -p ", paste0(port, ":8787"), cn(" -v ", volume), cn(" -w", dir), paste0(" -e USER=", user), paste0(" -e PASSWORD=", password), paste0(" -e EMAIL=", email), " ", img, ifelse(add_users, ' bash -c "add-students && supervisord" ', ' '), ssh_user = ssh_user, keyfile = keyfile, ssh_passwd = ssh_passwd ) url <- sprintf("http://%s:%s/", droplet_ip(droplet), port) if (browse) { Sys.sleep(4) browseURL(url) } invisible(droplet) } docklet_rstudio_addusers <- function(droplet, user, password, img = 'rocker/rstudio', port = '8787', ssh_user = "root", keyfile = NULL, ssh_passwd = NULL, verbose = FALSE) { check_for_a_pkg("ssh") if (missing(user)) stop("'user' is required") if (missing(password)) stop("'password' is required") if (password == "rstudio") stop("supply a 'password' other than 'rstudio'") droplet <- as.droplet(droplet) cons <- docklet_ps_data(droplet, ssh_user = ssh_user, keyfile = keyfile, ssh_passwd = ssh_passwd, verbose = verbose) id <- cons[ grep("rocker/rstudio:latest", cons$image), "container.id" ] if (length(id) > 0) { docklet_stop(droplet, container = id) docklet_rm(droplet, container = id) } docklet_run( droplet, " -d", " -p ", paste0(port, ":8787"), paste0(" -e USER=", user), paste0(" -e PASSWORD=", password), " ", img, ' bash -c "add-students && supervisord"', verbose = verbose ) } docklet_shinyserver <- function(droplet, img = 'rocker/shiny', port = '3838', volume = '', dir = '', browse = TRUE, ssh_user = "root") { droplet <- as.droplet(droplet) docklet_pull(droplet, img, ssh_user) docklet_run(droplet, " -d", " -p ", paste0(port, ":3838"), cn(" -v ", volume), cn(" -w", dir), " ", img, ssh_user = ssh_user ) url <- sprintf("http://%s:%s/", droplet_ip(droplet), port) if (browse) { Sys.sleep(4) browseURL(url) } invisible(droplet) } docklet_shinyapp <- function(droplet, path, img = 'rocker/shiny', port = '80', dir = '', browse = TRUE, ssh_user = "root") { check_for_a_pkg("ssh") droplet <- as.droplet(droplet) droplet_ssh(droplet, "mkdir -p /srv/shinyapps") droplet_upload(droplet, path, "/srv/shinyapps/") docklet_shinyserver( droplet, img, port, volume = '/srv/shinyapps/:/srv/shiny-server/', dir, browse, ssh_user) }
test_that("Model Workflow Regression KL", { set.seed(1234) dist.meas = 1 data(FAset) fa.set = as.vector(unlist(FAset)) data(predatorFAs) tombstone.info = predatorFAs[,1:4] predator.matrix = predatorFAs[,5:(ncol(predatorFAs))] npredators = nrow(predator.matrix) data(preyFAs) prey.sub=(preyFAs[,4:(ncol(preyFAs))])[fa.set] prey.sub=prey.sub/apply(prey.sub,1,sum) group=as.vector(preyFAs$Species) prey.matrix=cbind(group,prey.sub) prey.matrix=MEANmeth(prey.matrix) FC = preyFAs[,c(2,3)] FC = as.vector(tapply(FC$lipid,FC$Species,mean,na.rm=TRUE)) data(CC) cal.vec = CC[,2] cal.mat = replicate(npredators, cal.vec) Q = p.QFASA(predator.matrix, prey.matrix, cal.mat, dist.meas, gamma=1, FC, start.val = rep(1,nrow(prey.matrix)), fa.set) DietEst = Q$'Diet Estimates' DietEst = round(DietEst*100,digits=2) colnames(DietEst) = (as.vector(rownames(prey.matrix))) DietEst = cbind(tombstone.info,DietEst) DietEstCheck = read.csv(file=system.file("exdata", "DietEstKL.csv", package="QFASA"), as.is=TRUE) expect_equal(DietEst, DietEstCheck, tolerance=1e-6) AdditionalMeasures = plyr::ldply(Q$'Additional Measures', data.frame) AdditionalMeasuresCheck = read.csv(file=system.file("exdata", "AdditionalMeasuresKL.csv", package="QFASA"), as.is=TRUE) expect_equal(AdditionalMeasures, AdditionalMeasuresCheck, tolerance=1e-4) })
cover2incidence <- function(g) UseMethod("cover2incidence")
require(geometa, quietly = TRUE) require(testthat) context("ISOBoundFeatureAttribute") test_that("encoding",{ testthat::skip_on_cran() md <- ISOBoundFeatureAttribute$new() md$setDescription("description") fat <- ISOFeatureAttribute$new() fat$setMemberName("name 1") fat$setDefinition("definition 1") fat$setCardinality(lower=1,upper=1) fat$setCode("code 1") gml <- GMLBaseUnit$new(id = "ID1") gml$setDescriptionReference("someref") gml$setIdentifier("identifier", "codespace") gml$addName("name1", "codespace") gml$addName("name2", "codespace") gml$setQuantityTypeReference("someref") gml$setCatalogSymbol("symbol") gml$setUnitsSystem("somelink") fat$setValueMeasurementUnit(gml) val1 <- ISOListedValue$new() val1$setCode("code1") val1$setLabel("label1") val1$setDefinition("definition1") fat$addListedValue(val1) val2 <- ISOListedValue$new() val2$setCode("code2") val2$setLabel("label2") val2$setDefinition("definition2") fat$addListedValue(val2) fat$setValueType("typeName") md$setPropertyType(fat) md$setTypeName("name") expect_is(md, "ISOBoundFeatureAttribute") xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOBoundFeatureAttribute$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) }) test_that("encoding - i18n",{ testthat::skip_on_cran() md <- ISOBoundFeatureAttribute$new() md$setDescription( "description", locales = list( EN = "the description", FR = "la description", ES = "la descripción", AR = "الوصف", RU = "описание", ZH = "描述" ) ) fat <- ISOFeatureAttribute$new() fat$setMemberName("name1") fat$setDefinition( "description 1", locales = list( EN = "the description 1", FR = "la description 1", ES = "la descripción 1", AR = "1 الوصف", RU = "описание 1", ZH = "描述 1" ) ) fat$setCardinality(lower=1,upper=1) fat$setCode("code 1") gml <- GMLBaseUnit$new(id = "ID1") gml$setDescriptionReference("someref") gml$setIdentifier("identifier", "codespace") gml$addName("name1", "codespace") gml$addName("name2", "codespace") gml$setQuantityTypeReference("someref") gml$setCatalogSymbol("symbol") gml$setUnitsSystem("somelink") fat$setValueMeasurementUnit(gml) val1 <- ISOListedValue$new() val1$setCode("code1") val1$setLabel( "name in english 1", locales = list( EN = "name in english 1", FR = "nom en français 1", ES = "Nombre en español 1", AR = "1 الاسم باللغة العربية", RU = "имя на русском 1", ZH = "中文名 1" )) val1$setDefinition( "definition in english 1", locales = list( EN = "definition in english 1", FR = "définition en français 1", ES = "definición en español 1", AR = "1 التعريف باللغة العربية ", RU = "Русское определение 1", ZH = "中文定义1" )) fat$addListedValue(val1) val2 <- ISOListedValue$new() val2$setCode("code2") val2$setLabel( "name in english 2", locales = list( EN = "name in english 2", FR = "nom en français 2", ES = "Nombre en español 2", AR = "2 الاسم باللغة العربية", RU = "имя на русском 2", ZH = "中文名 2" )) val2$setDefinition( "definition in english 2", locales = list( EN = "definition in english 2", FR = "définition en français 2", ES = "definición en español 2", AR = "2 التعريف باللغة العربية ", RU = "Русское определение 2", ZH = "中文定义2" )) fat$addListedValue(val2) fat$setValueType("typeName") md$setPropertyType(fat) md$setTypeName("name") expect_is(md, "ISOBoundFeatureAttribute") xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOBoundFeatureAttribute$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) })
test_that("cross_join", { tab = cross_join(list(a = 1:3, b = 1:2)) expect_equal(tab, CJ(a = 1:3, b = 1:2)) tab = cross_join(list(sorted = 1:3, b = 1:2)) expect_equal(tab, setnames(CJ(a = 1:3, b = 1:2), "a", "sorted")) tab = cross_join(list(unique = 1:3, b = 1:2)) expect_equal(tab, setnames(CJ(a = 1:3, b = 1:2), "a", "unique")) })
knitr::opts_chunk$set(echo = TRUE) library(hydroGOF) require(zoo) data(EgaEnEstellaQts) obs <- EgaEnEstellaQts sim <- obs gof(sim=sim, obs=obs) sim[1:2000] <- obs[1:2000] + rnorm(2000, mean=10) ggof(sim=sim, obs=obs, ftype="dm", FUN=mean) ggof(sim=sim, obs=obs, ftype="dm", FUN=mean, cal.ini="1963-01-01") sim <- window(sim, start=as.Date("1963-01-01")) obs <- window(obs, start=as.Date("1963-01-01")) gof(sim, obs) r <- sim-obs library(hydroTSM) smry(r) hydroplot(r, FUN=mean) hydroplot(r, FUN=mean, pfreq="seasonal") sessionInfo()$platform sessionInfo()$R.version$version.string paste("hydroGOF", sessionInfo()$otherPkgs$hydroGOF$Version)
vpow <- function(x,sill,range) { if( range==0) return(rep(sill,length(x))) sill * x^range }
setGeneric("passage", function(x, origin, goal, theta, ...) { standardGeneric("passage") } ) setMethod("passage", signature(x = "TransitionLayer", origin = "Coords", goal = "Coords", theta="missing"), def = function(x, origin, goal, totalNet="net", output="RasterLayer") { .checkInputsPassage(totalNet, output) origin <- .coordsToMatrix(origin) goal <- .coordsToMatrix(goal) if(totalNet=="net" & output=="RasterLayer") { x <- .transitionSolidify(x) tc <- transitionCells(x) cellnri <- cellFromXY(x, origin) cellnrj <- cellFromXY(x, goal) ci <- match(cellnri,tc) cj <- match(cellnrj,tc) result <- .flowMap(x, ci, cj, tc) } else{ stop("no method available -- try a low value of theta instead") } return(result) } ) setMethod("passage", signature(x = "TransitionLayer", origin = "RasterLayer", goal = "RasterLayer", theta="missing"), def = function(x, origin, goal, totalNet="net", output="RasterLayer") { .checkInputsPassage(totalNet, output) if(totalNet=="net" & output=="RasterLayer") { x <- .transitionSolidify(x) tc <- transitionCells(x) ci <- which(getValues(origin)) cj <- which(getValues(goal)) result <- .flowMap(x, ci, cj, tc) } else{ stop("no method available -- try a low value of theta instead") } return(result) } ) .checkInputsPassage <- function(totalNet, output) { if(!(totalNet %in% c("total","net"))){ stop("totalNet should be either total or net") } if(!(output %in% c("RasterLayer","TransitionLayer"))){ stop("output should be either RasterLayer or TransitionLayer") } } .flowMap <- function(x, indexOrigin, indexGoal, tc) { L <- .Laplacian(x) Lr <- L[-dim(L)[1],-dim(L)[1]] A <- as(L,"lMatrix") A <- as(A,"dMatrix") n <- max(dim(Lr)) Current <- .currentR(L, Lr, A, n, indexOrigin, indexGoal) result <- as(x,"RasterLayer") dataVector <- rep(0,times=ncell(result)) dataVector[tc] <- Current result <- setValues(result, dataVector) return(result) } setMethod("passage", signature(x = "TransitionLayer", origin = "Coords", goal = "Coords", theta="numeric"), def = function(x, origin, goal, theta, totalNet="net", output="RasterLayer") { cellnri <- cellFromXY(x, origin) cellnrj <- cellFromXY(x, goal) x <- .transitionSolidify(x) tc <- transitionCells(x) ci <- match(cellnri,tc) cj <- match(cellnrj,tc) result <- .randomShPaths(x, ci, cj, theta, tc, totalNet, output) return(result) } ) setMethod("passage", signature(x = "TransitionLayer", origin = "RasterLayer", goal = "RasterLayer", theta="numeric"), def = function(x, origin, goal, theta, totalNet="net", output="RasterLayer") { ci <- which(getValues(origin)) cj <- which(getValues(goal)) x <- .transitionSolidify(x) tc <- transitionCells(x) result <- .randomShPaths(x, ci, cj, theta, tc, totalNet, output) return(result) } ) .randomShPaths <- function(x, ci, cj, theta, tc, totalNet, output) { if(theta < 0 | theta > 20 ) { stop("theta value out of range (between 0 and 20)") } tr <- transitionMatrix(x,inflate=FALSE) trR <- tr trR@x <- 1 / trR@x nr <- dim(tr)[1] Id <- Diagonal(nr) rs <- rowSums(tr) rs[rs>0] <- 1/rs[rs>0] P <- tr * rs W <- trR W@x <- exp(-theta * trR@x) W <- W * P return(.probPass(x, Id, W, nr, ci, cj, tc, totalNet, output)) } .probPass <- function(x, Id, W, nr, ci, cj, tc, totalNet, output) { nc <- ncell(x) Ij <- Diagonal(nr) Ij[cbind(cj,cj)] <- 1 - 1 / length(cj) Wj <- Ij %*% W ei <- rep(0,times=nr) ei[ci] <- 1 / length(ci) ej <- rep(0,times=nr) ej[cj] <- 1 / length(cj) IdMinusWj <- as((Id - Wj), "dgCMatrix") zci <- solve(t(IdMinusWj),ei) zcj <- solve(IdMinusWj, ej) zcij <- sum(ei*zcj) if(zcij < 1e-300) { if(output == "RasterLayer") { result <- as(x,"RasterLayer") result[] <- rep(0,times=nc) } if(output == "TransitionLayer") { result <- x transitionMatrix(result) <- Matrix(0, nc, nc) result@transitionCells <- 1:nc } } else { N <- (Diagonal(nr, as.vector(zci)) %*% Wj %*% Diagonal(nr, as.vector(zcj))) / zcij if(output == "RasterLayer") { if(totalNet == "total") { n <- pmax(rowSums(N),colSums(N)) } if(totalNet == "net") { nNet <- abs(skewpart(N)) n <- pmax(rowSums(nNet),colSums(nNet)) n[c(ci,cj)] <- 2 * n[c(ci,cj)] } result <- as(x,"RasterLayer") dataVector <- rep(NA,times=nc) dataVector[tc] <- n result <- setValues(result, dataVector) } if(output == "TransitionLayer") { result <- x if(totalNet == "total") { tr <- Matrix(0, nc, nc) tr[tc,tc] <- N } if(totalNet == "net") { nNet <- skewpart(N) * 2 nNet@x[nNet@x<0] <- 0 tr <- Matrix(0, nc, nc) tr[tc,tc] <- nNet } transitionMatrix(result) <- tr result@transitionCells <- 1:nc } } return(result) }
emma.MLE <- function (y, X, K, Z = NULL, ngrids = 100, llim = -10, ulim = 10, esp = 1e-10, eig.L = NULL, eig.R = NULL ) { n <- length(y) t <- nrow(K) q <- ncol(X) stopifnot(ncol(K) == t) stopifnot(nrow(X) == n) if (det(crossprod(X, X)) == 0) { warning("X is singular") return(list(ML = 0, delta = 0, ve = 0, vg = 0)) } if (is.null(Z)) { if (is.null(eig.L)) { eig.L <- emma.eigen.L.wo.Z(K ) } if (is.null(eig.R)) { eig.R <- emma.eigen.R.wo.Z(K, X ) } etas <- crossprod(eig.R$vectors, y) logdelta <- (0:ngrids)/ngrids * (ulim - llim) + llim m <- length(logdelta) delta <- exp(logdelta) Lambdas <- matrix(eig.R$values, n - q, m) + matrix(delta, n - q, m, byrow = TRUE) Xis <- matrix(eig.L$values, n, m) + matrix(delta, n, m, byrow = TRUE) Etasq <- matrix(etas * etas, n - q, m) LL <- 0.5 * (n * (log(n/(2 * pi)) - 1 - log(colSums(Etasq/Lambdas))) - colSums(log(Xis))) dLL <- 0.5 * delta * (n * colSums(Etasq/(Lambdas * Lambdas))/colSums(Etasq/Lambdas) - colSums(1/Xis)) optlogdelta <- vector(length = 0) optLL <- vector(length = 0) if (dLL[1] < esp) { optlogdelta <- append(optlogdelta, llim) optLL <- append(optLL, emma.delta.ML.LL.wo.Z(llim, eig.R$values, etas, eig.L$values)) } if (dLL[m - 1] > 0 - esp) { optlogdelta <- append(optlogdelta, ulim) optLL <- append(optLL, emma.delta.ML.LL.wo.Z(ulim, eig.R$values, etas, eig.L$values)) } for (i in 1:(m - 1)) { if ((dLL[i] * dLL[i + 1] < 0 - esp * esp) && (dLL[i] > 0) && (dLL[i + 1] < 0)) { r <- uniroot(emma.delta.ML.dLL.wo.Z, lower = logdelta[i], upper = logdelta[i + 1], lambda = eig.R$values, etas = etas, xi = eig.L$values) optlogdelta <- append(optlogdelta, r$root) optLL <- append(optLL, emma.delta.ML.LL.wo.Z(r$root, eig.R$values, etas, eig.L$values)) } } } else { if (is.null(eig.L)) { eig.L <- emma.eigen.L.w.Z(Z, K ) } if (is.null(eig.R)) { eig.R <- emma.eigen.R.w.Z(Z, K, X) } etas <- crossprod(eig.R$vectors, y) etas.1 <- etas[1:(t - q)] etas.2 <- etas[(t - q + 1):(n - q)] etas.2.sq <- sum(etas.2 * etas.2) logdelta <- (0:ngrids)/ngrids * (ulim - llim) + llim m <- length(logdelta) delta <- exp(logdelta) Lambdas <- matrix(eig.R$values, t - q, m) + matrix(delta, t - q, m, byrow = TRUE) Xis <- matrix(eig.L$values, t, m) + matrix(delta, t, m, byrow = TRUE) Etasq <- matrix(etas.1 * etas.1, t - q, m) dLL <- 0.5 * delta * (n * (colSums(Etasq/(Lambdas * Lambdas)) + etas.2.sq/(delta * delta))/(colSums(Etasq/Lambdas) + etas.2.sq/delta) - (colSums(1/Xis) + (n - t)/delta)) optlogdelta <- vector(length = 0) optLL <- vector(length = 0) if (dLL[1] < esp) { optlogdelta <- append(optlogdelta, llim) optLL <- append(optLL, emma.delta.ML.LL.w.Z(llim, eig.R$values, etas.1, eig.L$values, n, etas.2.sq)) } if (dLL[m - 1] > 0 - esp) { optlogdelta <- append(optlogdelta, ulim) optLL <- append(optLL, emma.delta.ML.LL.w.Z(ulim, eig.R$values, etas.1, eig.L$values, n, etas.2.sq)) } for (i in 1:(m - 1)) { if ((dLL[i] * dLL[i + 1] < 0 - esp * esp) && (dLL[i] > 0) && (dLL[i + 1] < 0)) { r <- uniroot(emma.delta.ML.dLL.w.Z, lower = logdelta[i], upper = logdelta[i + 1], lambda = eig.R$values, etas.1 = etas.1, xi.1 = eig.L$values, n = n, etas.2.sq = etas.2.sq) optlogdelta <- append(optlogdelta, r$root) optLL <- append(optLL, emma.delta.ML.LL.w.Z(r$root, eig.R$values, etas.1, eig.L$values, n, etas.2.sq)) } } } maxdelta <- exp(optlogdelta[which.max(optLL)]) maxLL <- max(optLL) if (is.null(Z)) { maxva <- sum(etas * etas/(eig.R$values + maxdelta))/n } else { maxva <- (sum(etas.1 * etas.1/(eig.R$values + maxdelta)) + etas.2.sq/maxdelta)/n } maxve <- maxva * maxdelta return(list(ML = maxLL, delta = maxdelta, ve = maxve, vg = maxva)) }
`JGET.seis` <- function(fnames, kind=1, Iendian=1, BIGLONG=FALSE, HEADONLY=FALSE , PLOT=-1, RAW=FALSE) { if(missing(PLOT)) { PLOT=-1 } if(missing(kind)) { kind=1 } if(missing(HEADONLY)) {HEADONLY=FALSE } if(missing(Iendian)) { Iendian=1 } if(missing(BIGLONG)) { BIGLONG=FALSE} if(missing(RAW)) { RAW=FALSE } tmpGIVE = as.list(1:length(fnames)) ii = 1 DATIM = rep(0,length=4) n=1 dt=0.025000 sec = 0 thesta="XXXXX" thecomp="XXXXX" for(i in 1:length(fnames)) { fn = fnames[i] infile = fn if(file.exists(infile)==FALSE) { print(paste(sep=' ', "file does not exist", fn) ); next; } else { } if(kind== -1) { DAT = readRDS(fn) if(is.null(names(DAT)) & length(DAT)>=1) { DAT = DAT[[1]] } if(HEADONLY) DAT$amp = NULL DAT$oldname = DAT$fn DAT$fn = fn tmpGIVE[[i]] = DAT next } if(kind==0) { DAT = list() GED = load(fn) assign("DAT", get(GED)) if(is.null(names(DAT)) & length(DAT)>=1) { DAT = DAT[[1]] } if(HEADONLY) DAT$amp = NULL DAT$oldname = DAT$fn DAT$fn = fn tmpGIVE[[i]] = DAT next } if(kind==1) { DAT = JSEGY.seis(fn, Iendian=Iendian, HEADONLY=HEADONLY , BIGLONG=BIGLONG, PLOT=PLOT, RAW=RAW) tmpGIVE[[i]] = DAT[[1]] next } if(kind==2) { DAT = JSAC.seis(fn, Iendian=Iendian, HEADONLY=HEADONLY , BIGLONG=BIGLONG, PLOT=PLOT, RAW=RAW) tmpGIVE[[i]] = DAT[[1]] next } if(kind==3) { print("AH format currently not available") tmpGIVE[[i]] = NA next } tmpGIVE[[i]] = NA } invisible(tmpGIVE) }
glue_safe <- function(..., .envir = parent.frame()) { glue(..., .envir = .envir, .transformer = get_transformer) } glue_data_safe <- function(.x, ..., .envir = parent.frame()) { glue_data(.x, ..., .envir = .envir, .transformer = get_transformer) } get_transformer <- function(text, envir) { if (!exists(text, envir = envir)) { stop("object '", text, "' not found", call. = FALSE) } else { get(text, envir = envir) } }
`[.EEM` <- function(x, i, ...) { r <- NextMethod("[") class(r) <- "EEM" r }
feature_hits <- function(x) { if(!check_geoserver()) { return(0) } x$query$resultType <- "hits" x$query$outputFormat <- "text/xml" x$query$version <- "2.0.0" request <- httr::build_url(x) response <- httr::GET(request) httr::stop_for_status(response) parsed <- httr::content(response, encoding = "UTF-8") n_hits <- as.numeric(xml2::xml_attrs(parsed)["numberMatched"]) return(n_hits) } geom_col_name <- function(x) { if(!check_geoserver(timeout = 10, quiet = TRUE)) { return(NULL) } geom_col <- get_col_df(x) %>% dplyr::filter(grepl(x = type, pattern = "gml:")) %>% dplyr::pull(name) return(geom_col) } feature_cols <- function(x) { return(get_col_df(x)$name) } specify_geom_name <- function(x, CQL_statement){ geom_col <- geom_col_name(x) dbplyr::sql(glue::glue(CQL_statement, geom_name = geom_col)) } get_col_df <- function(x) { if(!check_geoserver(timeout = 10, quiet = TRUE)) { return(NULL) } layer <- x$query$version base_url_n_wfs <- substr(getOption("vicmap.base_url", default = base_wfs_url), start = 0, stop = nchar(getOption("vicmap.base_url", default = base_wfs_url)) - 3) r <- httr::GET(paste0(base_url_n_wfs, x$query$typeNames, "/wfs?service=wfs&version=", x$query$version, "&request=DescribeFeatureType")) httr::stop_for_status(r) c <- httr::content(r, encoding = "UTF-8", type="text/xml") list <- xml2::xml_child(xml2::xml_child(xml2::xml_child(xml2::xml_child(c, "xsd:complexType"), "xsd:complexContent"), "xsd:extension"), "xsd:sequence") %>% xml2::as_list() data <- data.frame(name = sapply(list, function(x) attr(x, "name")), type = sapply(list, function(x) attr(x, "type")), stringsAsFactors = F) return(data) }
NULL kinesisvideo <- function(config = list()) { svc <- .kinesisvideo$operations svc <- set_config(svc, config) return(svc) } .kinesisvideo <- list() .kinesisvideo$operations <- list() .kinesisvideo$metadata <- list( service_name = "kinesisvideo", endpoints = list("*" = list(endpoint = "kinesisvideo.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "kinesisvideo.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "kinesisvideo.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "kinesisvideo.{region}.sc2s.sgov.gov", global = FALSE)), service_id = "Kinesis Video", api_version = "2017-09-30", signing_name = "kinesisvideo", json_version = "", target_prefix = "" ) .kinesisvideo$service <- function(config = list()) { handlers <- new_handlers("restjson", "v4") new_service(.kinesisvideo$metadata, handlers, config) }
FM.chi.pvalue <- function(x){ y=log(x) y=-2*sum(y) p.value=pchisq(y,df=2*length(x),lower.tail=FALSE) list("FMstatistic"=y, "FMpvalue"=p.value) }
"aanma" <- function(...) { UseMethod("aanma") }
panel.psyfun <- function(x, y, n, lnk = "logit", ...) { xy.glm <- glm(cbind(n * y, n * (1 - y)) ~ x, binomial(lnk)) rr <- lattice::current.panel.limits()$xlim xx <- seq(rr[1], rr[2], len = 100) yy <- predict(xy.glm, data.frame(x = xx), type = "response") lattice::panel.lines(xx, yy, ...) }
library(OpenMx) library(testthat) diagno <- toupper(c('alc', 'gad', 'mdd', 'pan', 'pho')) parent <- c('wife', 'husband') c1 <- apply(expand.grid(diagno, parent)[,c(2,1)], 1, paste, collapse='') wife <- c1[1:5] husband <- c1[6:10] c2 <- matrix(0, length(c1), length(c1), dimnames=list(c1,c1)) c2['wifeALC', 'wifeGAD'] <- .399 c2['wifeALC', 'wifeMDD'] <- .341 c2['wifeALC', 'wifePAN'] <- .276 c2['wifeALC', 'wifePHO'] <- .284 c2['wifeGAD', 'wifeMDD'] <- .582 c2['wifeGAD', 'wifePAN'] <- .372 c2['wifeGAD', 'wifePHO'] <- .394 c2['wifeMDD', 'wifePAN'] <- .31 c2['wifeMDD', 'wifePHO'] <- .304 c2['wifePAN', 'wifePHO'] <- .371 c2['husbandGAD', 'husbandALC'] <- .295 c2['husbandMDD', 'husbandALC'] <- .341 c2['husbandMDD', 'husbandGAD'] <- .576 c2['husbandPAN', 'husbandALC'] <- .283 c2['husbandPAN', 'husbandGAD'] <- .314 c2['husbandPAN', 'husbandMDD'] <- .576 c2['husbandPHO', 'husbandALC'] <- .249 c2['husbandPHO', 'husbandGAD'] <- .220 c2['husbandPHO', 'husbandMDD'] <- .181 c2['husbandPHO', 'husbandPAN'] <- .276 c2[wife,wife] + c2[husband, husband] c2['wifeALC', husband] <- c(.119, .064, .19, .029, .005) c2['wifeGAD', husband] <- c(.209, .208, .207, .119, .133) c2['wifeMDD', husband] <- c(.132, .088, .162, .112, .105) c2['wifePAN', husband] <- c(.064, .092, .151, .219, .102) c2['wifePHO', husband] <- c(-.079, .13, .221, -.016, .064) c2[husband,wife] <- t(c2[wife, husband]) c2[wife, wife][lower.tri(diag(length(diagno)))] <- t(c2[wife, wife])[lower.tri(diag(length(diagno)))] c2[husband, husband][upper.tri(diag(length(diagno)))] <- t(c2[husband, husband])[upper.tri(diag(length(diagno)))] diag(c2) <- 1 c3 <- matrix(0, length(c1), length(c1), dimnames=list(c1,c1)) c3['wifeALC', 'wifeGAD'] <- .378 c3['wifeALC', 'wifeMDD'] <- .313 c3['wifeALC', 'wifePAN'] <- .076 c3['wifeALC', 'wifePHO'] <- .095 c3['wifeGAD', 'wifeMDD'] <- .709 c3['wifeGAD', 'wifePAN'] <- .471 c3['wifeGAD', 'wifePHO'] <- .228 c3['wifeMDD', 'wifePAN'] <- .367 c3['wifeMDD', 'wifePHO'] <- .227 c3['wifePAN', 'wifePHO'] <- .371 c3['husbandGAD', 'husbandALC'] <- .125 c3['husbandMDD', 'husbandALC'] <- .185 c3['husbandMDD', 'husbandGAD'] <- .64 c3['husbandPAN', 'husbandALC'] <- .267 c3['husbandPAN', 'husbandGAD'] <- .483 c3['husbandPAN', 'husbandMDD'] <- .467 c3['husbandPHO', 'husbandALC'] <- .194 c3['husbandPHO', 'husbandGAD'] <- .312 c3['husbandPHO', 'husbandMDD'] <- .149 c3['husbandPHO', 'husbandPAN'] <- .344 c3[wife,wife] + c3[husband, husband] c3['wifeALC', husband] <- c(.068, .213, .267, -.047, -.078) c3['wifeGAD', husband] <- c(.107, -.014, .169, .116, -.006) c3['wifeMDD', husband] <- c(.251, .014, .121, -.196, .074) c3['wifePAN', husband] <- c(.002, .114, .015, .138, .062) c3['wifePHO', husband] <- c(.003, .14, .033, .028, .071) c3[husband,wife] <- t(c3[wife, husband]) c3[wife, wife][lower.tri(diag(length(diagno)))] <- t(c3[wife, wife])[lower.tri(diag(length(diagno)))] c3[husband, husband][upper.tri(diag(length(diagno)))] <- t(c3[husband, husband])[upper.tri(diag(length(diagno)))] diag(c3) <- 1 diag2d <- matrix(apply(expand.grid(diagno, diagno)[,c(2,1)], 1, paste, collapse=""), length(diagno), length(diagno)) paths <- c( mxPath(wife, arrows=2, connect="unique.bivariate", lbound=-.99, ubound=.99, labels=paste0('w', diag2d[lower.tri(diag2d)])), mxPath(husband, arrows=2, connect="unique.bivariate", lbound=-.99, ubound=.99, labels=paste0('h', diag2d[lower.tri(diag2d)])), mxPath(wife, husband, arrows=0, connect="unique.pairs", lbound=-.99, ubound=.99, labels=paste0('d', c(diag2d)))) abd <- mxModel( 'abd', type="RAM", manifestVars = c1, mxData(c2, type = "cov", numObs = 854), mxPath(c1, arrows=2, values=1, free=FALSE), paths) aft <- mxModel( 'aft', type="RAM", manifestVars = c1, mxData(c3, type = "cov", numObs = 568), mxPath(c1, arrows=2, values=1, free=FALSE), paths) fig6 <- mxModel("fig6", abd, aft, mxFitFunctionMultigroup(c("abd", "aft"))) if (0) { fig6 <- mxOption(fig6,"Always Checkpoint","Yes") fig6 <- mxOption(fig6,"Checkpoint Units","evaluations") fig6 <- mxOption(fig6,"Checkpoint Count",1) fig6 <- mxOption(fig6, "Checkpoint Fullpath", "/dev/fd/2") } fig6 <- mxRun(fig6) fig6r <- mxRefModels(fig6, run=TRUE) fig6s <- summary(fig6, refModels=fig6r) expect_equal(fig6s$ChiDoF, 65) expect_equal(fig6s$Chi, 544.0544, 1e-3) expect_equal(fig6s$CFI, .8756, 1e-4) expect_equal(length(mxGetExpected(fig6, "covariance")), 2)
NULL ml_validate_params <- function(expanded_params, stage_jobjs, current_param_list) { stage_uids <- names(stage_jobjs) stage_indices <- integer(0) expanded_params %>% purrr::imap(function(param_sets, user_input_name) { matched <- paste0("^", user_input_name) %>% grepl(stage_uids) %>% which() if (length(matched) > 1) { stop("The name ", user_input_name, " matches more than one stage in the pipeline.", call. = FALSE ) } if (length(matched) == 0) { stop("The name ", user_input_name, " matches no stages in the pipeline.", call. = FALSE ) } stage_indices[[user_input_name]] <<- matched stage_jobj <- stage_jobjs[[matched]] purrr::map(param_sets, function(params) { current_params <- current_param_list[[matched]] %>% ml_map_param_list_names() default_params <- stage_jobj %>% ml_get_stage_constructor() %>% formals() %>% as.list() %>% purrr::discard(~ is.symbol(.x) || is.language(.x)) %>% purrr::compact() input_param_names <- names(params) current_param_names <- names(current_params) default_param_names <- names(default_params) current_params_keep <- setdiff(current_param_names, input_param_names) default_params_keep <- setdiff(default_param_names, current_params_keep) args_to_validate <- c( params, current_params[current_params_keep], default_params[default_params_keep] ) do.call(ml_get_stage_validator(stage_jobj), list(args_to_validate)) %>% `[`(input_param_names) }) }) %>% rlang::set_names(stage_uids[stage_indices]) } ml_spark_param_map <- function(param_map, sc, stage_jobjs) { purrr::imap(param_map, function(param_set, stage_uid) { purrr::imap(param_set, function(value, param_name) { list( param_jobj = stage_jobjs[[stage_uid]] %>% invoke(ml_map_param_names(param_name, "rs")), value = value ) }) %>% purrr::discard(~ is.null(.x[["value"]])) }) %>% unname() %>% rlang::flatten() %>% purrr::reduce( function(x, pair) invoke(x, "put", pair$param_jobj, pair$value), .init = invoke_new(sc, "org.apache.spark.ml.param.ParamMap") ) } ml_get_estimator_param_maps <- function(jobj) { sc <- spark_connection(jobj) jobj %>% invoke("getEstimatorParamMaps") %>% purrr::map(~ invoke_static(sc, "sparklyr.MLUtils", "paramMapToNestedList", .x)) %>% purrr::map(~ lapply(.x, ml_map_param_list_names)) } ml_new_validator <- function(sc, class, uid, estimator, evaluator, estimator_param_maps, seed) { uid <- cast_string(uid) possibly_spark_jobj <- possibly_null(spark_jobj) param_maps <- if (!is.null(estimator) && !is.null(estimator_param_maps)) { stage_jobjs <- if (inherits(estimator, "ml_pipeline")) { invoke_static(sc, "sparklyr.MLUtils", "uidStagesMapping", spark_jobj(estimator)) } else { rlang::set_names(list(spark_jobj(estimator)), ml_uid(estimator)) } current_param_list <- stage_jobjs %>% purrr::map(invoke, "extractParamMap") %>% purrr::map(~ invoke_static(sc, "sparklyr.MLUtils", "paramMapToList", .x)) estimator_param_maps %>% purrr::map(purrr::cross) %>% ml_validate_params(stage_jobjs, current_param_list) %>% purrr::cross() %>% purrr::map(ml_spark_param_map, sc, stage_jobjs) } jobj <- invoke_new(sc, class, uid) %>% jobj_set_param("setEstimator", possibly_spark_jobj(estimator)) %>% jobj_set_param("setEvaluator", possibly_spark_jobj(evaluator)) %>% jobj_set_param("setSeed", seed) if (!is.null(param_maps)) { invoke_static( sc, "sparklyr.MLUtils", "setParamMaps", jobj, param_maps ) } else { jobj } } new_ml_tuning <- function(jobj, ..., class = character()) { new_ml_estimator( jobj, estimator = possibly_null( ~ invoke(jobj, "getEstimator") %>% ml_call_constructor() )(), evaluator = possibly_null( ~ invoke(jobj, "getEvaluator") %>% ml_call_constructor() )(), estimator_param_maps = possibly_null(ml_get_estimator_param_maps)(jobj), ..., class = c(class, "ml_tuning") ) } new_ml_tuning_model <- function(jobj, ..., class = character()) { new_ml_transformer( jobj, estimator = invoke(jobj, "getEstimator") %>% ml_call_constructor(), evaluator = invoke(jobj, "getEvaluator") %>% ml_call_constructor(), estimator_param_maps = ml_get_estimator_param_maps(jobj), best_model = ml_call_constructor(invoke(jobj, "bestModel")), ..., class = c(class, "ml_tuning_model") ) } print_tuning_info <- function(x, type = c("cv", "tvs")) { type <- match.arg(type) num_sets <- length(x$estimator_param_maps) ml_print_class(x) ml_print_uid(x) if (!num_sets) { return(invisible(NULL)) } cat(" (Parameters -- Tuning)\n") if (!is.null(x$estimator)) { cat(paste0(" estimator: ", ml_short_type(x$estimator), "\n")) cat(paste0(" ")) ml_print_uid(x$estimator) } if (!is.null(x$evaluator)) { cat(paste0(" evaluator: ", ml_short_type(x$evaluator), "\n")) cat(paste0(" ")) ml_print_uid(x$evaluator) cat(" with metric", ml_param(x$evaluator, "metric_name"), "\n") } if (identical(type, "cv")) { cat(" num_folds:", x$num_folds, "\n") } else { cat(" train_ratio:", x$train_ratio, "\n") } cat( " [Tuned over", num_sets, "hyperparameter", if (num_sets == 1) "set]" else "sets]" ) } print_best_model <- function(x) { cat("\n (Best Model)\n") best_model_output <- capture.output(print(x$best_model)) cat(paste0(" ", best_model_output), sep = "\n") } print_tuning_summary <- function(x, type = c("cv", "tvs")) { type <- match.arg(type) num_sets <- length(x$estimator_param_maps) cat(paste0("Summary for ", ml_short_type(x)), "\n") cat(paste0(" ")) ml_print_uid(x) cat("\n") cat(paste0("Tuned ", ml_short_type(x$estimator), "\n")) cat(paste0(" with metric ", ml_param(x$evaluator, "metric_name"), "\n")) cat(paste0( " over ", num_sets, " hyperparameter ", if (num_sets == 1) "set" else "sets" ), "\n") if (identical(type, "cv")) { cat(" via", paste0(x$num_folds, "-fold cross validation")) } else { cat(" via", paste0(x$train_ratio, "/", 1 - x$train_ratio, " train-validation split")) } cat("\n\n") cat(paste0("Estimator: ", ml_short_type(x$estimator), "\n")) cat(paste0(" ")) ml_print_uid(x$estimator) cat(paste0("Evaluator: ", ml_short_type(x$evaluator), "\n")) cat(paste0(" ")) ml_print_uid(x$evaluator) cat("\n") cat(paste0("Results Summary:"), "\n") if (identical(type, "cv")) { print(x$avg_metrics_df) } else { print(x$validation_metrics_df) } } ml_sub_models <- function(model) { fn <- model$sub_models %||% stop( "Cannot extract sub models. `collect_sub_models` must be set to TRUE in ", "ml_cross_validator() or ml_train_split_validation()." ) fn() } ml_validation_metrics <- function(model) { if (inherits(model, "ml_cross_validator_model")) { model$avg_metrics_df } else if (inherits(model, "ml_train_validation_split_model")) { model$validation_metrics_df } else { stop("ml_validation_metrics() must be called on `ml_cross_validator_model` ", "or `ml_train_validation_split_model`.", call. = FALSE ) } } param_maps_to_df <- function(param_maps) { param_maps %>% lapply(function(param_map) { param_map %>% lapply(data.frame, stringsAsFactors = FALSE) %>% (function(x) { lapply(seq_along(x), function(n) { fn <- function(x) paste(x, n, sep = "_") dplyr::rename_all(x[[n]], fn) }) }) %>% dplyr::bind_cols() }) %>% dplyr::bind_rows() } validate_args_tuning <- function(.args) { .args[["collect_sub_models"]] <- cast_scalar_logical(.args[["collect_sub_models"]]) .args[["parallelism"]] <- cast_scalar_integer(.args[["parallelism"]]) .args[["seed"]] <- cast_nullable_scalar_integer(.args[["seed"]]) if (!is.null(.args[["estimator"]]) && !inherits(.args[["estimator"]], "ml_estimator")) { stop("`estimator` must be an `ml_estimator`.") } if (!is.null(.args[["estimator_param_maps"]]) && !rlang::is_bare_list(.args[["estimator_param_maps"]])) { stop("`estimator_param_maps` must be a list.") } if (!is.null(.args[["evaluator"]]) && !inherits(.args[["evaluator"]], "ml_evaluator")) { stop("`evaluator` must be an `ml_evaluator`.") } .args }
allDijkstra = function(fromNode, relType, toNode, cost_property = character(), direction = "out") UseMethod("allDijkstra") allDijkstra.node = function(fromNode, relType, toNode, cost_property, direction = "out") { return(shortest_path_algo(all=T, algo="dijkstra", fromNode=fromNode, relType=relType, toNode=toNode, direction=direction, cost_property=cost_property)) }
tcplMthdAssign <- function(lvl, id, mthd_id, ordr = NULL, type) { exec_ordr <- modified_by <- NULL if (length(lvl) > 1) stop("'lvl' must be an integer of length 1.") if (!type %in% c("mc", "sc")) stop("Invalid 'type' value.") if (type == "mc" & !lvl %in% c(2, 3,4, 5, 6)) stop("Invalid 'lvl' value.") if (type == "sc" & !lvl %in% 1:2) stop("Invalid 'lvl' value.") id_name <- if (type == "mc" & lvl == 2) "acid" else "aeid" flds <- c(id_name, sprintf("%s%s_mthd_id", type, lvl)) dat <- expand.grid(id = id, mthd = mthd_id, stringsAsFactors = FALSE) dat <- as.data.table(dat) if ((lvl < 4 & type == "mc") | (lvl == 1 & type == "sc")) { if (is.null(ordr) | length(mthd_id) != length(ordr)) { stop("'ordr' must be specified and the same length as 'mthd_id'") } dat[ , "exec_ordr" := ordr[match(get("mthd"), mthd_id)]] } setnames(dat, old = c("id", "mthd"), flds) mb <- paste(Sys.info()[c("login", "user", "effective_user")], collapse = ".") dat[ , "modified_by" := mb] tcplAppend(dat = dat, tbl = paste0(type, lvl, "_", flds[1]), db = getOption("TCPL_DB")) tcplCascade(lvl = lvl, type = type, id = id) }
"fun4Kin" <- function(obj, ageClass, phen, N){ if(obj$breed=="across breeds"){ obj$d <- 0 obj$a <- 0*obj$a return(obj) } if(is.na(N)){stop("Parameter N is NA.\n")} ageClass <- ageClass[ageClass$Breed==obj$breed,] classes <- ageClass$Class r0 <- ageClass$rcont0 r1 <- ageClass$rcont1 diffF <- obj$mkin$diffF NIndiv0 <- pmax(N*r0,1) NIndiv1 <- pmax(N*r1,1) nIndiv <- pmax(ageClass$n,1) ra <- 1 - sum(r1) Delta00 <- ra^2*(1-sum((phen$c0*diag(obj$Q))[phen$Breed==obj$breed]))/(2*ra*N) if(ra>0.9999){ obj$a <- setNames(rep(0,nrow(phen)), phen$Indiv) obj$d <- Delta00 }else{ NPO <- pPOpop(ageClass, Breed=obj$breed, N0=ra*N) nPO <- NPOdata(phen, Classes=classes, symmetric=TRUE, quiet=TRUE) NPO <- NPO[classes,classes, drop=FALSE] diag(NPO) <- 1/NIndiv0 diag(nPO) <- 1/nIndiv u <- ageClass[phen$Class,"rcont1"] u <- u*(1/pmax(ageClass[phen$Class,"n"],1) - 1/pmax(N*ageClass[phen$Class,"rcont0"],1)) u <- u*(obj$mkin$selfkin[phen$Indiv]-obj$mkin$kinwac[phen$Indiv]) u[is.na(u)|phen$Breed!=obj$breed] <- 0 Delta01 <- 2*sum(phen$c1*u) Delta11 <- c(r1%*%(diag(1/NIndiv1-1/NIndiv0, nrow=length(NIndiv1))*diffF - (nPO-NPO)*diffF)%*%r1) obj$a <- setNames(-2*c(u), phen$Indiv) obj$d <- Delta00 + Delta01 + Delta11 } return(obj) }
library(tidymodels) library(doMC) library(tidyposterior) library(workflowsets) library(rstanarm) theme_set(theme_bw()) data(ames, package = "modeldata") ames <- mutate(ames, Sale_Price = log10(Sale_Price)) set.seed(123) ames_split <- initial_split(ames, prop = 0.80, strata = Sale_Price) ames_train <- training(ames_split) ames_test <- testing(ames_split) crs <- parallel::detectCores() registerDoMC(cores = crs) set.seed(55) ames_folds <- vfold_cv(ames_train, v = 10, repeats = 10) lm_model <- linear_reg() %>% set_engine("lm") rf_model <- rand_forest(trees = 1000) %>% set_engine("ranger") %>% set_mode("regression") basic_rec <- recipe(Sale_Price ~ Neighborhood + Gr_Liv_Area + Year_Built + Bldg_Type + Latitude + Longitude, data = ames_train) %>% step_log(Gr_Liv_Area, base = 10) %>% step_other(Neighborhood, threshold = 0.01) %>% step_dummy(all_nominal_predictors()) interaction_rec <- basic_rec %>% step_interact( ~ Gr_Liv_Area:starts_with("Bldg_Type_") ) spline_rec <- interaction_rec %>% step_ns(Latitude, Longitude, deg_free = 50) preproc <- list(basic = basic_rec, interact = interaction_rec, splines = spline_rec, formula = Sale_Price ~ Neighborhood + Gr_Liv_Area + Year_Built + Bldg_Type + Latitude + Longitude ) models <- list(lm = lm_model, lm = lm_model, lm = lm_model, rf = rf_model) four_models <- workflow_set(preproc, models, cross = FALSE) four_models posteriors <- NULL for(i in 11:100) { if (i %% 10 == 0) cat(i, "... ") tmp_rset <- rsample:::df_reconstruct(ames_folds %>% slice(1:i), ames_folds) four_resamples <- four_models %>% workflow_map("fit_resamples", seed = 1, resamples = tmp_rset) rsq_anova <- perf_mod( four_resamples, prior_intercept = student_t(df = 1), chains = crs - 2, iter = 5000, seed = 2, cores = crs - 2, refresh = 0 ) rqs_diff <- contrast_models(rsq_anova, list_1 = "splines_lm", list_2 = "basic_lm", seed = 3) %>% as_tibble() %>% mutate(label = paste(format(1:100)[i], "resamples"), resamples = i) posteriors <- bind_rows(posteriors, rqs_diff) rm(rqs_diff) } intervals <- posteriors %>% group_by(resamples) %>% summarize( mean = mean(difference), lower = quantile(difference, prob = 0.05), upper = quantile(difference, prob = 0.95), .groups = "drop" ) %>% ungroup() %>% mutate( mean = predict(loess(mean ~ resamples, span = .15)), lower = predict(loess(lower ~ resamples, span = .15)), upper = predict(loess(upper ~ resamples, span = .15)) ) save(intervals, file = "RData/post_intervals.RData")
forward.prepaid=function(S,t,r,position,div.structure="none",dividend=NA,df=1,D=NA,k=NA,plot=FALSE){ all=list(S,t,r,position,div.structure,dividend,df,D,k,plot) if(any(lapply(all,is.null)==T)) stop("Cannot input any variables as NULL.") if(any(lapply(all,length) != 1)==T) stop("All inputs must be of length 1.") num2=list(S,t,r,dividend,df,D,k) na.num2=num2[which(lapply(num2,is.na)==F)] if(any(lapply(na.num2,is.numeric)==F))stop("S, t, r, dividend, df, D, and k must be numeric.") nalist=list(S,t,r,position,div.structure,df,plot) if(any(lapply(nalist,is.na)==T)) stop("S, t, r, position, div.structure, df, and plot cannot be NA.") NA.Neg=array(c(S,t,r,dividend,D,k,df)) NA.Neg.Str=c("S","t","r","dividend","D","k","df") app=apply(NA.Neg,1,is.na) na.s=which(app==F & NA.Neg<=0) if(length(na.s)>0) {errs=paste(NA.Neg.Str[na.s],collapse=" & ") stop(cat("Error: '",errs, "' must be positive real number(s).\n"))} na.s2=which(app==F & NA.Neg==Inf) if(length(na.s2)>0) {errs=paste(NA.Neg.Str[na.s2],collapse=" & ") stop(cat("Error: '",errs, "' cannot be infinite.\n"))} stopifnot(is.logical(plot)) if(df != round(df)) stop("df must be an integer.") if(position != "short" & position != "long") stop("Invalid position.") if(div.structure != "none" & div.structure != "continuous" & div.structure != "discrete") stop("Invalid dividend structure.") if(div.structure=="continuous" & is.na(D)) stop("Missing D.") if(div.structure=="continuous" & is.na(D)==FALSE & D <=0) stop("D <=0") if((div.structure=="none" | div.structure=="continuous") & is.na(dividend)==FALSE ) warning("Dividend value will be ignored.") if((div.structure=="none" | div.structure=="discrete") & is.na(D)==FALSE ) warning("D value will be ignored.") if((div.structure=="none" | div.structure=="continuous") & is.na(k)==FALSE ) warning("k value will be ignored.") if(div.structure=="discrete"){ if(is.na(dividend)) stop("Dividend not specified.") if(is.na(dividend)==F & dividend<0) stop("Dividend < 0") if(is.na(dividend)==F & dividend==0) stop("Set div.structure = none") eff.i=exp(r)-1 int=(1+eff.i)^(1/df)-1 t1=t*df if(!is.na(k)){ if(int==k){ price=S*exp(r*t)-dividend*t1/(1+int)*exp(r*t) } if(int != k){ price=S*exp(r*t)-dividend*(1-((1+k)/(1+int))^t1)/(int-k)*exp(r*t) } } if(is.na(k)){ price=S*exp(r*t)-dividend*((1+int)^t1-1)/int } } if(div.structure=="none") price=S*exp(r*t) if(div.structure=="continuous") price=S*exp((r-D)*t) price=price*exp(-r*t) stock=seq(0,price,length.out=6) stock=c(stock,round(seq(price,price*2,length.out=6))) stock=sort(unique(round(stock))) if(position=="long") payoff=stock-price else payoff=price-stock if(plot==T){ if(position=="long") m="Long Prepaid Forward\nPayoff" else m="Short Prepaid Forward\nPayoff" plot(stock,payoff,type="l",xlab="Stock Price",main=m,ylab="Payoff", ylim=c(min(payoff),max(payoff)),xaxt='n',yaxt='n',col="steelblue",lwd=2) abline(h=0,lty=2,col="gray") x=round(seq(min(payoff),max(payoff),length.out=8)) axis(2,at=x,labels=x,las=2) axis(1,at=stock) } out1=data.frame(stock,payoff) names(out1)=c("Stock Price","Payoff") out=list(Payoff=out1,Price=price) return(out) }
skip_if_no_auth() test_that("measure_get_measures_by_year_state", { do_all <- sample(c(TRUE, FALSE), 1) res <- measure_get_measures_by_year_state( years = sample(2015:2020), state_ids = c(NA, sample(state.abb, 5)), all = do_all ) expect_length( names(res), 5 ) })
Mplus_eeal <-function(target, konstrukt = c("R","I","A","S","E","C"),... ) { temp2 <- readModels(target = target, what="parameters", ...)$parameters PI<-(temp2$unstandardized[(temp2$unstandardized$paramHeader=="Variances" & temp2$unstandardized$param=="PI"),3]) PA<-(temp2$unstandardized[(temp2$unstandardized$paramHeader=="Variances" & temp2$unstandardized$param=="PA"),3]) PS<-(temp2$unstandardized[(temp2$unstandardized$paramHeader=="Variances" & temp2$unstandardized$param=="PS"),3]) PE<-(temp2$unstandardized[(temp2$unstandardized$paramHeader=="Variances" & temp2$unstandardized$param=="PE"),3]) PC<-(temp2$unstandardized[(temp2$unstandardized$paramHeader=="Variances" & temp2$unstandardized$param=="PC"),3]) temperg2 <- c(0, PI,PA,PS,PE,PC) names(temperg2) <- konstrukt temperg1 <- (temperg2 * 180)/pi names(temperg1) <- konstrukt perf.circ.rad <- c(0, 1.047198, 2.094395, 3.141593, 4.18879, 5.235988) names(perf.circ.rad) <- konstrukt perf.circ.deg <- (perf.circ.rad * 180)/pi mat<-as.matrix(rbind(temperg2, perf.circ.rad)) dimnames(mat) <- list(c("empiric.circumplex","perfect.circumplex"),konstrukt) ergebnis<-list(Mplus.datei = target, emp.winkel.grad = temperg1, emp.winkel.rad = temperg2, perf.circ.deg = perf.circ.deg, perf.circ.rad = perf.circ.rad, mat = mat) class(ergebnis) <- c("empCirc","list") return (ergebnis) }
theme_latex = function(value = TRUE){ theme(tern.plot.latex = value) } theme_showlatex = function(){ theme_latex(TRUE) } theme_nolatex = function(){ theme_latex(FALSE) } theme_hidelatex = function(){ theme_latex(FALSE) }
.create_aemet_path <- function(api_options) { resolution <- api_options$resolution aemet_stamp <- lubridate::stamp("2020-12-25T00:00:00UTC", orders = "YOmdHMS", quiet = TRUE) if (resolution == 'current_day') { return(c('opendata', 'api', 'observacion', 'convencional', 'todas')) } if (resolution == 'daily') { return( c( 'opendata', 'api', 'valores', 'climatologicos', 'diarios', 'datos', 'fechaini', aemet_stamp(api_options$start_date), 'fechafin', aemet_stamp(api_options$end_date), 'todasestaciones' ) ) } stop( api_options$resolution, " is not a valid temporal resolution for AEMET. Please see aemet_options help for more information" ) } .check_status_aemet <- function(...) { api_response <- httr::GET(...) response_status <- httr::status_code(api_response) if (response_status == 404) { res <- list( status = 'Error', code = response_status, message = glue::glue( "Unable to connect to AEMET API at {api_response$url}: {httr::http_status(api_response)$message}" ) ) return(res) } if (response_status == 401) { res <- list( status = 'Error', code = response_status, message = glue::glue("Invalid API Key: {httr::http_status(api_response)$message}") ) return(res) } if (response_status == 429) { res <- list( status = 'Error', code = response_status, message = glue::glue( "API request limit reached: {httr::http_status(api_response)$message}" ) ) return(res) } if (stringr::str_detect(httr::http_type(api_response), "html")) { html_text <- httr::content(api_response, 'text') if (stringr::str_detect(html_text, "429 Too Many Requests")) { res <- list( status = 'Error', code = 429, message = "API request limit reached, taking a cooldown of 60 seconds to reset." ) } else { res <- list( status = 'Error', code = response_status, message = glue::glue("AEMET API returned an error: {html_text}") ) } return(res) } response_content <- jsonlite::fromJSON(httr::content(api_response, as = 'text', encoding = 'ISO-8859-15')) if (!rlang::is_null(response_content$estado) && response_content$estado != 200) { res <- list( status = 'Error', code = response_content$estado, message = glue::glue("AEMET API returned no data: {response_content$descripcion}") ) return(res) } res <- list( status = 'OK', code = response_status, message = "Data received", content = response_content ) return(res) } .get_info_aemet <- function(api_options) { path_resolution <- c( 'opendata', 'api', 'valores', 'climatologicos', 'inventarioestaciones', 'todasestaciones' ) config_httr_aemet <- switch( Sys.info()["sysname"], 'Linux' = httr::config(ssl_cipher_list = 'DEFAULT@SECLEVEL=1'), httr::config() ) api_status_check <- .check_status_aemet( "https://opendata.aemet.es", httr::add_headers(api_key = api_options$api_key), path = path_resolution, httr::user_agent('https://github.com/emf-creaf/meteospain'), config = config_httr_aemet ) if (api_status_check$status != 'OK') { if (api_status_check$code == 429) { return(.manage_429_errors(api_status_check, api_options, .get_info_aemet)) } else { stop(api_status_check$code, ':\n', api_status_check$message) } } response_content <- api_status_check$content stations_info_check <- .check_status_aemet( response_content$datos, httr::user_agent('https://github.com/emf-creaf/meteospain'), config = config_httr_aemet ) if (stations_info_check$status != 'OK') { if (stations_info_check$code == 429) { return(.manage_429_errors(api_status_check, api_options, .get_info_aemet)) } else { stop(stations_info_check$code, ':\n', stations_info_check$message) } } stations_info_check$content %>% dplyr::as_tibble() %>% dplyr::mutate(service = 'aemet') %>% dplyr::select( .data$service, station_id = .data$indicativo, station_name = .data$nombre, altitude = .data$altitud, latitude = .data$latitud, longitude = .data$longitud ) %>% dplyr::mutate( altitude = as.numeric(stringr::str_replace_all(.data$altitude, ',', '.')), altitude = units::set_units(.data$altitude, "m"), latitude = dplyr::if_else( stringr::str_detect(.data$latitude, 'S'), -as.numeric(stringr::str_remove_all(.data$latitude, '[A-Za-z]'))/10000, as.numeric(stringr::str_remove_all(.data$latitude, '[A-Za-z]'))/10000 ), longitude = dplyr::if_else( stringr::str_detect(.data$longitude, 'W'), -as.numeric(stringr::str_remove_all(.data$longitude, '[A-Za-z]'))/10000, as.numeric(stringr::str_remove_all(.data$longitude, '[A-Za-z]'))/10000 ) ) %>% sf::st_as_sf(coords = c('longitude', 'latitude'), crs = 4326) } .get_data_aemet <- function(api_options) { path_resolution <- .create_aemet_path(api_options) config_httr_aemet <- switch( Sys.info()["sysname"], 'Linux' = httr::config(ssl_cipher_list = 'DEFAULT@SECLEVEL=1'), httr::config() ) api_status_check <- .check_status_aemet( "https://opendata.aemet.es", httr::add_headers(api_key = api_options$api_key), path = path_resolution, httr::user_agent('https://github.com/emf-creaf/meteospain'), config = config_httr_aemet ) if (api_status_check$status != 'OK') { if (api_status_check$code == 429) { return(.manage_429_errors(api_status_check, api_options, .get_data_aemet)) } else { stop(api_status_check$code, ':\n', api_status_check$message) } } response_content <- api_status_check$content stations_data_check <- .check_status_aemet( response_content$datos, httr::user_agent('https://github.com/emf-creaf/meteospain'), config = config_httr_aemet ) if (stations_data_check$status != 'OK') { if (stations_data_check$code == 429) { return(.manage_429_errors(api_status_check, api_options, .get_data_aemet)) } else { stop(stations_data_check$code, ':\n', stations_data_check$message) } } stations_metadata_check <- .check_status_aemet( response_content$metadatos, httr::user_agent('https://github.com/emf-creaf/meteospain'), config = config_httr_aemet ) if (stations_metadata_check$status != 'OK') { if (stations_metadata_check$code == 429) { return(.manage_429_errors(api_status_check, api_options, .get_data_aemet)) } else { stop(stations_metadata_check$code, ':\n', stations_metadata_check$message) } } stations_info <- .get_info_aemet(api_options) filter_expression <- TRUE if (!rlang::is_null(api_options$stations)) { filter_expression <- switch( api_options$resolution, 'current_day' = rlang::expr(.data$idema %in% api_options$stations), 'daily' = rlang::expr(.data$indicativo %in% api_options$stations) ) } resolution_specific_carpentry <- switch( api_options$resolution, 'current_day' = .aemet_current_day_carpentry, 'daily' = .aemet_daily_carpentry ) res <- stations_data_check$content %>% dplyr::as_tibble() %>% dplyr::filter(!! filter_expression) %>% resolution_specific_carpentry(stations_info) %>% dplyr::arrange(.data$timestamp, .data$station_id) %>% relocate_vars() %>% sf::st_as_sf() if ((!is.null(api_options$stations)) & nrow(res) < 1) { stop( "Station(s) provided have no data for the dates selected.\n", "Available stations with data for the actual query are:\n", glue::glue_collapse( c(unique(stations_data_check$content$indicativo), unique(stations_data_check$content$idema)), sep = ', ', last = ' and ' ) ) } message( copyright_style(stations_metadata_check$content$copyright), '\n', legal_note_style(stations_metadata_check$content$notaLegal) ) return(res) } .aemet_current_day_carpentry <- function(data, stations_info) { data %>% dplyr::select( timestamp = .data$fint, station_id = .data$idema, station_name = .data$ubi, altitude = .data$alt, temperature = .data$ta, min_temperature = .data$tamin, max_temperature = .data$tamax, relative_humidity = .data$hr, precipitation = .data$prec, wind_speed = .data$vv, wind_direction = .data$dv, longitude = .data$lon, latitude = .data$lat, ) %>% dplyr::mutate( service = 'aemet', timestamp = lubridate::as_datetime(.data$timestamp), altitude = units::set_units(.data$altitude, "m"), temperature = units::set_units(.data$temperature, "degree_C"), min_temperature = units::set_units(.data$min_temperature, "degree_C"), max_temperature = units::set_units(.data$max_temperature, "degree_C"), relative_humidity = units::set_units(.data$relative_humidity, "%"), precipitation = units::set_units(.data$precipitation, "L/m^2"), wind_speed = units::set_units(.data$wind_speed, "m/s"), wind_direction = units::set_units(.data$wind_direction, "degree") ) %>% sf::st_as_sf(coords = c('longitude', 'latitude'), crs = 4326) } .aemet_daily_carpentry <- function(data, stations_info) { data %>% dplyr::select( timestamp = .data$fecha, station_id = .data$indicativo, station_name = .data$nombre, station_province = .data$provincia, mean_temperature = .data$tmed, min_temperature = .data$tmin, max_temperature = .data$tmax, precipitation = .data$prec, mean_wind_speed = .data$velmedia, insolation = .data$sol ) %>% dplyr::mutate( service = 'aemet', timestamp = lubridate::as_datetime(.data$timestamp), mean_temperature = as.numeric(stringr::str_replace_all(.data$mean_temperature, ',', '.')), min_temperature = as.numeric(stringr::str_replace_all(.data$min_temperature, ',', '.')), max_temperature = as.numeric(stringr::str_replace_all(.data$max_temperature, ',', '.')), precipitation = suppressWarnings(as.numeric(stringr::str_replace_all(.data$precipitation, ',', '.'))), mean_wind_speed = as.numeric(stringr::str_replace_all(.data$mean_wind_speed, ',', '.')), insolation = as.numeric(stringr::str_replace_all(.data$insolation, ',', '.')), mean_temperature = units::set_units(.data$mean_temperature, "degree_C"), min_temperature = units::set_units(.data$min_temperature, "degree_C"), max_temperature = units::set_units(.data$max_temperature, "degree_C"), precipitation = units::set_units(.data$precipitation, "L/m^2"), mean_wind_speed = units::set_units(.data$mean_wind_speed, "m/s"), insolation = units::set_units(.data$insolation, "h") ) %>% dplyr::left_join(stations_info, by = c('service', 'station_id', 'station_name')) }
context("species") test_that("We can extract generic information from the species table", { needs_api() df <- species(c("Oreochromis niloticus", "Bolbometopon muricatum")) expect_is(df, "data.frame") }) test_that("Check some classes and values of species table", { needs_api() df <- species(c("Oreochromis niloticus", "Bolbometopon muricatum")) expect_is(df, "data.frame") }) test_that("We can pass a species_list based on taxanomic group", { needs_api() fish <- species_list(Genus = "Labroides") df <- species(fish) expect_is(df, "data.frame") expect_gt(dim(df)[1], 0) }) test_that("We can pass a species_list based on taxanomic group", { needs_api() fish <- species_list(Genus = "Labroides") df <- species(fish) expect_is(df, "data.frame") expect_gt(dim(df)[1], 0) }) test_that("We can filter on certain fields",{ needs_api() df <- species(c("Oreochromis niloticus", "Bolbometopon muricatum"), fields=c('SpecCode', 'Species')) expect_is(df, "data.frame") expect_gt(dim(df)[1], 0) df <- load_species_meta() })
gge <- function(.data, env, gen, resp, centering = "environment", scaling = "none", svp = "environment", by = NULL, ...) { if (!missing(by)){ if(length(as.list(substitute(by))[-1L]) != 0){ stop("Only one grouping variable can be used in the argument 'by'.\nUse 'group_by()' to pass '.data' grouped by more than one variable.", call. = FALSE) } .data <- group_by(.data, {{by}}) } if(is_grouped_df(.data)){ results <- .data %>% doo(gge, env = {{env}}, gen = {{gen}}, resp = {{resp}}, centering = centering, scaling = scaling, svp = svp, ...) return(set_class(results, c("tbl_df", "gge_group", "tbl", "data.frame"))) } else{ factors <- .data %>% select({{env}}, {{gen}}) %>% mutate(across(everything(), as.factor)) vars <- .data %>% select({{resp}}, -names(factors)) vars %<>% select_numeric_cols() factors %<>% set_names("ENV", "GEN") listres <- list() nvar <- ncol(vars) for (var in 1:nvar) { ge_mat <- factors %>% mutate(Y = vars[[var]]) %>% make_mat(GEN, ENV, Y) %>% as.matrix() if(has_na(ge_mat)){ ge_mat <- impute_missing_val(ge_mat, verbose = FALSE, ...)$.data warning("Data imputation used to fill the GxE matrix", call. = FALSE) } grand_mean <- mean(ge_mat) mean_env <- colMeans(ge_mat) mean_gen <- rowMeans(ge_mat) scale_val <- apply(ge_mat, 2, sd) labelgen <- rownames(ge_mat) labelenv <- colnames(ge_mat) if (any(is.na(ge_mat))) { stop("missing data in input data frame") } if (any(apply(ge_mat, 2, is.numeric) == FALSE)) { stop("not all columns are of class 'numeric'") } if (!(centering %in% c("none", "environment", "global", "double") | centering %in% 0:3)) { warning(paste("Centering method", centering, "not found; defaulting to environment centered")) centering <- "environment" } if (!(svp %in% c("genotype", "environment", "symmetrical") | svp %in% 1:3)) { warning(paste("svp method", svp, "not found; defaulting to column metric preserving")) svp <- "environment" } if (!(scaling %in% c("none", "sd") | scaling %in% 0:1)) { warning(paste("scaling method", scaling, "not found; defaulting to no scaling")) sd <- "none" } labelaxes <- paste("PC", 1:ncol(diag(svd(ge_mat)$d)), sep = "") if (centering == 1 | centering == "global") { ge_mat <- ge_mat - mean(ge_mat) } if (centering == 2 | centering == "environment") { ge_mat <- sweep(ge_mat, 2, colMeans(ge_mat)) } if (centering == 3 | centering == "double") { grand_mean <- mean(ge_mat) mean_env <- colMeans(ge_mat) mean_gen <- rowMeans(ge_mat) for (i in 1:nrow(ge_mat)) { for (j in 1:ncol(ge_mat)) { ge_mat[i, j] <- ge_mat[i, j] + grand_mean - mean_env[j] - mean_gen[i] } } } if (scaling == 1 | scaling == "sd") { ge_mat <- sweep(ge_mat, 2, apply(ge_mat, 2, sd), FUN = "/") } if (svp == 1 | svp == "genotype") { coordgen <- svd(ge_mat)$u %*% diag(svd(ge_mat)$d) coordenv <- svd(ge_mat)$v d1 <- (max(coordenv[, 1]) - min(coordenv[, 1]))/(max(coordgen[, 1]) - min(coordgen[, 1])) d2 <- (max(coordenv[, 2]) - min(coordenv[, 2]))/(max(coordgen[, 2]) - min(coordgen[, 2])) coordenv <- coordenv/max(d1, d2) } if (svp == 2 | svp == "environment") { coordgen <- svd(ge_mat)$u coordenv <- svd(ge_mat)$v %*% diag(svd(ge_mat)$d) d1 <- (max(coordgen[, 1]) - min(coordgen[, 1]))/(max(coordenv[, 1]) - min(coordenv[, 1])) d2 <- (max(coordgen[, 2]) - min(coordgen[, 2]))/(max(coordenv[, 2]) - min(coordenv[, 2])) coordgen <- coordgen/max(d1, d2) } if (svp == 3 | svp == "symmetrical") { coordgen <- svd(ge_mat)$u %*% diag(sqrt(svd(ge_mat)$d)) coordenv <- svd(ge_mat)$v %*% diag(sqrt(svd(ge_mat)$d)) } eigenvalues <- svd(ge_mat)$d totalvar <- round(as.numeric(sum(eigenvalues^2)), 2) varexpl <- round(as.numeric((eigenvalues^2/totalvar) * 100), 2) if (svp == "genotype" | svp == "environment") { d <- max(d1, d2) } else { d <- NULL } tmp <- structure( list(coordgen = coordgen, coordenv = coordenv, eigenvalues = eigenvalues, totalvar = totalvar, varexpl = varexpl, labelgen = labelgen, labelenv = labelenv, labelaxes = labelaxes, ge_mat = ge_mat, centering = centering, scaling = scaling, svp = svp, d = d, grand_mean = grand_mean, mean_gen = mean_gen, mean_env = mean_env, scale_val = scale_val), class = "gge") if (nvar > 1) { listres[[paste(names(vars[var]))]] <- tmp } else { listres[[paste(names(vars[var]))]] <- tmp } } return(structure(listres, class = "gge")) } } plot.gge <- function(x, var = 1, type = 1, sel_env = NA, sel_gen = NA, sel_gen1 = NA, sel_gen2 = NA, shape.gen = 21, shape.env = 23, line.type.gen = "dotted", size.shape = 2.2, size.shape.win = 3.2, size.stroke = 0.3, col.stroke = "black", col.gen = "blue", col.env = "forestgreen", col.line = "forestgreen", col.alpha = 1, col.circle = "gray", col.alpha.circle = 0.5, leg.lab = NULL, size.text.gen = 3.5, size.text.env = 3.5, size.text.lab = 12, size.text.win = 4.5, size.line = 0.5, axis_expand = 1.2, title = TRUE, plot_theme = theme_metan(), ...) { if(is.null(leg.lab)){ leg.lab <- case_when( has_class(x, "gytb") ~ c("Y-Trait", "Gen"), has_class(x, "gtb") ~ c("Trait", "Gen"), TRUE ~ c("Env", "Gen") ) } else{ leg.lab <- leg.lab } model <- x[[var]] if (!has_class(model, c("gge", "gtb", "gytb"))) { stop("The model must be of class 'gge'") } coord_gen <- model$coordgen[, c(1, 2)] coord_env <- model$coordenv[, c(1, 2)] varexpl <- model$varexpl[c(1, 2)] labelgen <- model$labelgen labelenv <- model$labelenv labelaxes <- model$labelaxes[c(1, 2)] Data <- model$ge_mat centering <- model$centering svp <- model$svp scaling <- model$scaling ngen <- nrow(coord_gen) nenv <- nrow(coord_env) if (centering == "none") { stop("It is not possible to create a GGE biplot with a model produced without centering") } plotdata <- data.frame(rbind(data.frame(coord_gen, type = "genotype", label = labelgen), data.frame(coord_env, type = "environment", label = labelenv))) colnames(plotdata)[1:2] <- c("d1", "d2") xlim <- c(min(plotdata$d1 * axis_expand), max(plotdata$d1 * axis_expand)) ylim <- c(min(plotdata$d2 * axis_expand), max(plotdata$d2 * axis_expand)) if (which(c(diff(xlim), diff(ylim)) == max(c(diff(xlim), diff(ylim)))) == 1) { xlim1 <- xlim ylim1 <- c(ylim[1] - (diff(xlim) - diff(ylim))/2, ylim[2] + (diff(xlim) - diff(ylim))/2) } if (which(c(diff(xlim), diff(ylim)) == max(c(diff(xlim), diff(ylim)))) == 2) { ylim1 <- ylim xlim1 <- c(xlim[1] - (diff(ylim) - diff(xlim))/2, xlim[2] + (diff(ylim) - diff(xlim))/2) } P1 <- ggplot(data = plotdata, aes(x = d1, y = d2, group = "type")) + scale_color_manual(values = c(col.env, col.gen)) + scale_size_manual(values = c(size.text.env, size.text.gen)) + xlab(paste(labelaxes[1], " (", round(varexpl[1], 2), "%)", sep = "")) + ylab(paste(labelaxes[2]," (", round(varexpl[2], 2), "%)", sep = "")) + geom_hline(yintercept = 0) + geom_vline(xintercept = 0) + scale_x_continuous(limits = xlim1, expand = c(0, 0)) + scale_y_continuous(limits = ylim1, expand = c(0, 0)) + coord_fixed() + plot_theme %+replace% theme(axis.text = element_text(size = size.text.lab, colour = "black"), axis.title = element_text(size = size.text.lab, colour = "black")) if (type == 1) { if(has_class(model, c("gtb", "gytb"))){ P2 <- P1 + geom_segment(xend = 0, yend = 0, size = size.line, aes(col = type), data = plotdata, show.legend = FALSE) } else{ P2 <- P1 + geom_segment(xend = 0, yend = 0, size = size.line, col = alpha(col.line, col.alpha), data = subset(plotdata, type == "environment")) } P2 <- P2 + geom_segment(xend = 0, yend = 0, size = size.line, col = alpha(col.line, col.alpha), data = subset(plotdata, type == "environment")) + geom_point(aes(d1, d2, fill = type, shape = type), size = size.shape, stroke = size.stroke, color = col.stroke, alpha = col.alpha) + scale_shape_manual(labels = leg.lab, values = c(shape.env, shape.gen)) + scale_fill_manual(labels = leg.lab, values = c(col.env, col.gen)) + geom_text_repel(aes(col = type, label = label, size = type), show.legend = FALSE, col = c(rep(col.gen, ngen), rep(col.env, nenv))) + plot_theme %+replace% theme(axis.text = element_text(size = size.text.lab, colour = "black"), axis.title = element_text(size = size.text.lab, colour = "black")) if (title == TRUE) { ggt <- case_when( has_class(model, "gytb") ~ "GYT Biplot", has_class(model, "gtb") ~ "GT Biplot", TRUE ~ "GGE biplot" ) %>% ggtitle() } } if (type == 2) { med1 <- mean(coord_env[, 1]) med2 <- mean(coord_env[, 2]) x1 <- NULL for (i in 1:nrow(Data)) { x <- solve(matrix(c(-med2, med1, med1, med2), nrow = 2), matrix(c(0, med2 * coord_gen[i, 2] + med1 * coord_gen[i, 1]), ncol = 1)) x1 <- rbind(x1, t(x)) } plotdata$x1_x <- NA plotdata$x1_x[plotdata$type == "genotype"] <- x1[, 1] plotdata$x1_y <- NA plotdata$x1_y[plotdata$type == "genotype"] <- x1[, 2] P2 <- P1 + geom_segment(aes(xend = x1_x, yend = x1_y), color = col.gen, linetype = line.type.gen, size = size.line, data = subset(plotdata, type == "genotype")) + geom_abline(intercept = 0, slope = med2/med1, color = col.line, size = size.line) + geom_abline(intercept = 0, slope = -med1/med2, color = col.line, size = size.line) + geom_segment(x = 0, y = 0, xend = med1, yend = med2, arrow = arrow(length = unit(0.3, "cm")), size = size.line, color = col.line) + geom_text(aes(color = type, label = label, size = type), show.legend = FALSE) if (title == TRUE) { ggt <- case_when( has_class(model, "gytb") ~ "Average tester coordination view of the GYT biplot", has_class(model, "gtb") ~ "Average tester coordination form of the GT biplot", TRUE ~ "Mean vs. Stability" ) %>% ggtitle() } } if (type == 3) { indice <- c(grDevices::chull(coord_gen[, 1], coord_gen[, 2])) polign <- data.frame(coord_gen[indice, ]) indice <- c(indice, indice[1]) segs <- NULL limx <- layer_scales(P1)$x$limits limy <- layer_scales(P1)$y$limits i <- 1 while (is.na(indice[i + 1]) == FALSE) { m <- (coord_gen[indice[i], 2] - coord_gen[indice[i + 1], 2])/(coord_gen[indice[i], 1] - coord_gen[indice[i + 1], 1]) mperp <- -1/m c2 <- coord_gen[indice[i + 1], 2] - m * coord_gen[indice[i + 1], 1] xint <- -c2/(m - mperp) xint <- ifelse(xint < 0, min(coord_env[, 1], coord_gen[, 1]), max(coord_env[, 1], coord_gen[, 1])) yint <- mperp * xint xprop <- ifelse(xint < 0, xint/limx[1], xint/limx[2]) yprop <- ifelse(yint < 0, yint/limy[1], yint/limy[2]) m3 <- which(c(xprop, yprop) == max(c(xprop, yprop))) m2 <- abs(c(xint, yint)[m3]) if (m3 == 1 & xint < 0) sl1 <- (c(xint, yint)/m2) * abs(limx[1]) if (m3 == 1 & xint > 0) sl1 <- (c(xint, yint)/m2) * limx[2] if (m3 == 2 & yint < 0) sl1 <- (c(xint, yint)/m2) * abs(limy[1]) if (m3 == 2 & yint > 0) sl1 <- (c(xint, yint)/m2) * limy[2] segs <- rbind(segs, sl1) i <- i + 1 } rownames(segs) <- NULL colnames(segs) <- NULL segs <- data.frame(segs) colnames(polign) <- c("X1", "X2") winners <- plotdata[plotdata$type == "genotype", ][indice[-1], ] %>% add_cols(win = "yes") others <- anti_join(plotdata, winners, by = "label") %>% add_cols(win = "no") df_winners <- rbind(winners, others) P2 <- P1 + geom_polygon(data = polign, aes(x = X1, y = X2), fill = NA, col = col.gen, size = size.line) + geom_segment(data = segs, aes(x = X1, y = X2), xend = 0, yend = 0, linetype = line.type.gen, color = col.gen, size = size.line) + geom_point(data = subset(df_winners, win == "no"), aes(d1, d2, fill = type, shape = type), size = size.shape, stroke = size.stroke, alpha = col.alpha, color = col.stroke, show.legend = FALSE) + geom_text_repel(data = subset(df_winners, win == "no"), aes(col = type, label = label, size = type), show.legend = FALSE) + geom_point(data = subset(df_winners, win == "yes"), aes(d1, d2, fill = type, shape = type), size = size.shape.win, stroke = size.stroke, color = col.stroke, alpha = col.alpha) + geom_text_repel(data = subset(df_winners, win == "yes"), aes(col = type, label = label), show.legend = FALSE, fontface = "bold", size = size.text.win) if("genotype" %in% others$type){ P2 <- P2 + scale_shape_manual(labels = leg.lab, values = c(shape.env, shape.gen)) + scale_fill_manual(labels = leg.lab, values = c(col.env, col.gen)) } else{ P2 <- suppressMessages( P2 + scale_shape_manual(labels = leg.lab[c(2,1)], values = c(shape.env, shape.gen)) + scale_fill_manual(labels = leg.lab[c(2,1)], values = c(col.env, col.gen)) + scale_color_manual(labels = leg.lab[c(2,1)], values = c(col.env, col.gen)) + scale_size_manual(labels = leg.lab[c(2,1)], values = c(size.text.env, size.text.gen)) ) } if (title == TRUE) { ggt <- ggtitle("Which-won-where pattern") ggt <- case_when( has_class(x, "gytb") ~ "The which-won-where view of the GYT biplot", has_class(x, "gtb") ~ "The which-won-where view of the GT biplot", TRUE ~ "Which-won-where view of the GGE biplot" ) %>% ggtitle() } } if (type == 4) { circles <- data.frame(x0 = 0, y0 = 0, start = 0, end = pi * 2, radio = 1:5 * max((max(coord_env[1, ]) - min(coord_env[1, ])), (max(coord_env[2, ]) - min(coord_env[2, ])))/10) P2 <- P1 + geom_arc(data = circles, aes(r = radio, x0 = x0, y0 = y0, start = start, end = end), color = col.circle, alpha = col.alpha.circle, size = size.line, inherit.aes = F, na.rm = TRUE) + geom_segment(xend = 0, yend = 0, x = mean(coord_env[, 1]), y = mean(coord_env[, 2]), arrow = arrow(ends = "first", length = unit(0.1, "inches")), size = size.line, color = col.line) + geom_abline(intercept = 0, slope = mean(coord_env[, 2])/mean(coord_env[, 1]), color = col.line, size = size.line) + geom_point(aes(d1, d2, fill = type, shape = type), size = size.shape, stroke = size.stroke, color = col.stroke, alpha = col.alpha) + scale_shape_manual(labels = leg.lab, values = c(shape.env, shape.gen)) + scale_fill_manual(labels = leg.lab, values = c(col.env, col.gen)) + geom_segment(data = subset(plotdata, type == "environment"), xend = 0, yend = 0, color = alpha(col.line, col.alpha), size = size.line) + geom_text_repel(aes(col = type, label = label, size = type), show.legend = FALSE, color = c(rep(col.gen, ngen), rep(col.env, nenv))) if (title == TRUE) { ggt <- ggtitle("Discriminativeness vs. representativeness") } } if (type == 5) { if (!sel_env %in% labelenv) { stop(paste("The environment", sel_env, "is not in the list of environment labels")) } venvironment <- labelenv == sel_env x1 <- NULL for (i in 1:nrow(Data)) { x <- solve(matrix(c(-coord_env[venvironment, 2], coord_env[venvironment, 1], coord_env[venvironment, 1], coord_env[venvironment, 2]), nrow = 2), matrix(c(0, coord_env[venvironment, 1] * coord_gen[i, 1] + coord_env[venvironment, 2] * coord_gen[i, 2]), ncol = 1)) x1 <- rbind(x1, t(x)) } plotdata$x1_x <- NA plotdata$x1_x[plotdata$type == "genotype"] <- x1[, 1] plotdata$x1_y <- NA plotdata$x1_y[plotdata$type == "genotype"] <- x1[, 2] P2 <- P1 + geom_segment(data = subset(plotdata, type == "genotype"), aes(xend = x1_x, yend = x1_y), col = col.gen, linetype = line.type.gen) + geom_abline(slope = coord_env[venvironment, 2]/coord_env[venvironment, 1], intercept = 0, color = alpha(col.line, col.alpha), size = size.line) + geom_abline(slope = -coord_env[venvironment, 1]/coord_env[venvironment, 2], intercept = 0, col = alpha(col.line, col.alpha), size = size.line) + geom_segment(data = subset(plotdata, type == "environment" & label == sel_env),xend = 0, yend = 0, col = alpha(col.line, col.alpha), size = size.line, arrow = arrow(ends = "first", length = unit(0.5, "cm"))) + geom_text(data = subset(plotdata, type == "genotype"), aes(label = label), show.legend = FALSE, color = col.gen, size = size.text.gen) + geom_text(data = subset(plotdata, type == "environment" & label %in% sel_env), aes(label = label), show.legend = FALSE, col = col.env, size = size.text.env, fontface = "bold", hjust = "outward", vjust = "outward") + geom_point(data = subset(plotdata, type == "environment" & label == sel_env), aes(d1, d2), shape = 1, color = col.stroke, size = 4) if (title == TRUE) { ggt <- ggtitle(paste("Environment:", sel_env)) } } if (type == 6) { med1 <- mean(coord_env[, 1]) med2 <- mean(coord_env[, 2]) mod <- max((coord_env[, 1]^2 + coord_env[, 2]^2)^0.5) xcoord <- sign(med1) * (mod^2/(1 + med2^2/med1^2))^0.5 ycoord <- (med2/med1) * xcoord circles <- data.frame(x0 = xcoord, y0 = ycoord, start = 0, end = pi * 2, radio = 1:8 * ((xcoord - med1)^2 + (ycoord - med2)^2)^0.5/3) P2 <- P1 + geom_abline(intercept = 0, slope = med2/med1, col = col.line, size = size.line) + geom_abline(intercept = 0, slope = -med1/med2, color = col.line, size = size.line) + geom_arc(data = circles, aes(r = radio, x0 = x0, y0 = y0, start = start, end = end), col = col.circle, alpha = col.alpha.circle, inherit.aes = F, na.rm = TRUE) + geom_segment(x = 0, y = 0, xend = xcoord, yend = ycoord, arrow = arrow(length = unit(0.15, "inches")), size = size.line, color = col.line) + geom_point(fill = col.env, shape = shape.env, size = size.shape, stroke = size.stroke, color = col.stroke, alpha = col.alpha, data = subset(plotdata, type == "environment")) + geom_text_repel(data = subset(plotdata, type == "environment"), aes(label = label), size = size.text.env, show.legend = FALSE, col = col.env) + geom_point(aes(xcoord, ycoord), shape = 1, size = 4, color = col.stroke) if (title == TRUE) { ggt <- ggtitle("Ranking Environments") } } if (type == 7) { if (!sel_gen %in% labelgen) { stop(paste("The genotype", sel_gen, "is not in the list of genotype labels")) } vgenotype <- labelgen == sel_gen x1 <- NULL for (i in 1:ncol(Data)) { x <- solve(matrix(c(-coord_gen[vgenotype, 2], coord_gen[vgenotype, 1], coord_gen[vgenotype, 1], coord_gen[vgenotype, 2]), nrow = 2), matrix(c(0, coord_gen[vgenotype, 1] * coord_env[i, 1] + coord_gen[vgenotype, 2] * coord_env[i, 2]), ncol = 1)) x1 <- rbind(x1, t(x)) } plotdata$x1_x <- NA plotdata$x1_x[plotdata$type == "environment"] <- x1[, 1] plotdata$x1_y <- NA plotdata$x1_y[plotdata$type == "environment"] <- x1[, 2] P2 <- P1 + geom_segment(data = subset(plotdata, type == "environment"), aes(xend = x1_x, yend = x1_y), col = col.line, linetype = line.type.gen) + geom_abline(slope = coord_gen[vgenotype, 2]/coord_gen[vgenotype, 1], intercept = 0, color = alpha(col.gen, col.alpha), size = size.line) + geom_abline(slope = -coord_gen[vgenotype, 1]/coord_gen[vgenotype, 2], intercept = 0, col = alpha(col.gen, col.alpha), size = size.line) + geom_segment(data = subset(plotdata, type == "genotype" & label == sel_gen), xend = 0, yend = 0, col = alpha(col.gen, col.alpha), arrow = arrow(ends = "first", length = unit(0.5, "cm")), size = size.line) + geom_text(data = subset(plotdata, type == "environment"), aes(label = label), show.legend = FALSE, color = col.env, size = size.text.gen) + geom_text(data = subset(plotdata, type == "genotype" & label %in% sel_gen), aes(label = label), show.legend = FALSE, color = col.gen, size = size.text.gen, fontface = "bold", hjust = "outward", vjust = "outward") + geom_point(data = subset(plotdata, type == "genotype" & label == sel_gen), aes(d1, d2), shape = 1, color = col.stroke, size = 4) if (title == TRUE) { ggt <- ggtitle(paste("Genotype:", sel_gen)) } } if (type == 8) { med1 <- mean(coord_env[, 1]) med2 <- mean(coord_env[, 2]) coordx <- 0 coordy <- 0 for (i in 1:nrow(Data)) { x <- solve(matrix(c(-med2, med1, med1, med2), nrow = 2), matrix(c(0, med2 * coord_gen[i, 2] + med1 * coord_gen[i, 1]), ncol = 1)) if (sign(x[1]) == sign(med1)) { if (abs(x[1]) > abs(coordx)) { coordx <- x[1] coordy <- x[2] } } } circles <- data.frame(x0 = coordx, y0 = coordy, radio = 1:10 * ((coordx - med1)^2 + (coordy - med2)^2)^0.5/3) P2 <- P1 + geom_abline(intercept = 0, slope = med2/med1, col = col.gen, size = size.line) + geom_abline(intercept = 0, slope = -med1/med2, color = col.gen, size = size.line) + geom_arc(data = circles, aes(r = radio, x0 = x0, y0 = y0, start = 0, end = pi * 2), color = col.circle, alpha = col.alpha.circle, size = size.line, inherit.aes = F) + geom_segment(x = 0, y = 0, xend = coordx, yend = coordy, arrow = arrow(length = unit(0.15, "inches")), size = size.line, color = col.gen) + geom_point(aes(d1, d2, fill = type, shape = type), size = size.shape, stroke = size.stroke, color = col.stroke, alpha = col.alpha) + scale_shape_manual(labels = leg.lab, values = c(shape.env, shape.gen)) + scale_fill_manual(labels = leg.lab, values = c(col.env, col.gen)) + geom_text_repel(aes(col = type, label = label, size = type), show.legend = FALSE, color = c(rep(col.gen, ngen), rep(col.env, nenv))) + geom_point(aes(coordx, coordy), shape = 1, color = col.stroke, size = 3) if (title == TRUE) { ggt <- ggtitle("Ranking Genotypes") } } if (type == 9) { if (!sel_gen1 %in% labelgen) { stop(paste("The genotype", sel_gen1, "is not in the list of genotype labels")) } if (!sel_gen2 %in% labelgen) { stop(paste("The genotype", sel_gen2, "is not in the list of genotype labels")) } if (sel_gen1 == sel_gen2) { stop(paste("It is not possible to compare a genotype to itself")) } vgenotype1 <- labelgen == sel_gen1 vgenotype2 <- labelgen == sel_gen2 P2 <- P1 + geom_segment(x = plotdata$d1[plotdata$label == sel_gen1 & plotdata$type == "genotype"], xend = plotdata$d1[plotdata$label == sel_gen2 & plotdata$type == "genotype"], y = plotdata$d2[plotdata$label == sel_gen1 & plotdata$type == "genotype"], yend = plotdata$d2[plotdata$label == sel_gen2 & plotdata$type == "genotype"], col = col.gen, size = size.line) + geom_abline(intercept = 0, slope = -(coord_gen[vgenotype1, 1] - coord_gen[vgenotype2, 1])/ (coord_gen[vgenotype1, 2] - coord_gen[vgenotype2, 2]), color = col.gen, size = size.line) + geom_text(aes(label = label), show.legend = FALSE, data = subset(plotdata, type == "environment"), col = col.env, size = size.text.env) + geom_text(data = subset(plotdata, type == "genotype" & !label %in% c(sel_gen1, sel_gen2)), aes(label = label), show.legend = FALSE, col = alpha(col.gen, alpha = col.alpha), size = size.text.gen) + geom_text(data = subset(plotdata, type == "genotype" & label %in% c(sel_gen1, sel_gen2)), aes(label = label), show.legend = FALSE, col = col.gen, size = size.text.win, hjust = "outward", vjust = "outward") + geom_point(data = subset(plotdata, type == "genotype" & label %in% c(sel_gen1, sel_gen2)), shape = shape.gen, fill = col.gen, color = col.stroke, size = size.shape) + plot_theme if (title == TRUE) { ggt <- ggtitle(paste("Comparison of Genotype", sel_gen1, "with Genotype", sel_gen2)) } } if (type == 10) { P2 <- P1 + geom_segment(data = subset(plotdata, type == "environment"), xend = 0, yend = 0, col = alpha(col.line, col.alpha), size = size.line) + geom_point(data = subset(plotdata, type == "environment"), shape = shape.env, fill = col.env, size = size.shape, stroke = size.stroke, color = col.stroke, alpha = col.alpha) + geom_text_repel(data = subset(plotdata, type == "environment"), aes(label = label), show.legend = FALSE, col = col.env, size = size.text.env) if (title == TRUE) { if(any(class(x) == "gtb")){ ggt <- ggtitle("Relationship Among Traits") } else{ ggt <- ggtitle("Relationship Among Environments") } } } if (title == T) { scal_text <- ifelse(scaling == 1 | scaling == "sd", "Scaling = 1", "Scaling = 0") cent_text <- case_when( centering == 1 | centering == "global" ~ "Centering = 1", centering == 2 | centering == "environment" | centering == "trait" ~ "Centering = 2", centering == 3 | centering == "double" ~ "Centering = 3", FALSE ~ "No Centering" ) svp_text <- case_when( svp == 1 | svp == "genotype" ~ "SVP = 1", svp == 2 | svp == "environment" | svp == "trait" ~ "SVP = 2", svp == 3 | svp == "symmetrical" ~ "SVP = 3" ) annotationtxt <- paste(scal_text, ", ", cent_text, ", ", svp_text, sep = "") P2 <- P2 + ggtitle(label = ggt, subtitle = annotationtxt) } return(P2) } predict.gge <- function(object, naxis = 2, output = "wide", ...) { if (has_class(object, "gtb")) { stop("The object must be of class 'gge'.") } listres <- list() varin <- 1 for (var in 1:length(object)) { objectin <- object[[var]] if (naxis > min(dim(objectin$coordenv))) { stop("The number of principal components cannot be greater than min(g, e), in this case ", min(dim(objectin$coordenv))) } if (objectin$svp == "environment" | objectin$svp == 2) { pred <- (objectin$coordgen[, 1:naxis] * (objectin$d)) %*% t(objectin$coordenv[, 1:naxis]) } if (objectin$svp == "genotype" | objectin$svp == 1) { pred <- (objectin$coordgen[, 1:naxis] %*% t(objectin$coordenv[, 1:naxis] * (objectin$d))) } if (objectin$svp == "symmetrical" | objectin$svp == 3) { pred <- (objectin$coordgen[, 1:naxis] %*% t(objectin$coordenv[, 1:naxis])) } if (objectin$scaling == "sd" | objectin$scaling == 1) { pred <- sweep(pred, 2, objectin$scale_val, FUN = "*") } if (objectin$centering == "global" | objectin$centering == 1) { pred <- pred + objectin$grand_mean } if (objectin$centering == "environment" | objectin$centering == 2) { pred <- sweep(pred, 2, objectin$mean_env, FUN = "+") } if (objectin$centering == "double" | objectin$centering == 3) { for (i in 1:nrow(pred)) { for (j in 1:ncol(pred)) { pred[i, j] <- pred[i, j] - objectin$grand_mean + objectin$mean_env[j] + objectin$mean_gen[i] } } } rownames(pred) <- objectin$labelgen colnames(pred) <- objectin$labelenv if (output == "wide") { temp <- as_tibble(pred, rownames = NA) } if (output == "long") { temp <- pred %>% make_long() %>% as_tibble() } listres[[paste(names(object[var]))]] <- temp } return(listres) }
setCovf_under<-function(process,parameter,...){ if(missing(process)){ cat("Error from setCovf.R: parameter process is missing\n") return(NULL) } if(!isS4(process)){ cat("Error from setCovf.R: parameter process is not of type process\n") return(NULL) }else if(!class(process)[1]=="process"){ cat("Error from setCovf.R: parameter process is not of type process\n") return(NULL) } manifold<-process@manifold names=c("fBm","mBm", "2pfBm","stdfBm","fBs","afBf","bridge") typeproc<-process@name if(all(typeproc!=names)){ cat("Error from setCovf.R: parameter typeproc does not exist\n") return(NULL) } if (typeproc == "fBm"){ if (is.null(parameter)){ cat("Warning from setCovf.R: parameter has been set to 0.5\n") parameter<-0.5 } if (!is.numeric(parameter)){ cat("Error from constructcovf.R: parameter must be numeric\n") return(NULL) } if (parameter>=1|parameter<=0){ cat("Error from constructcovf.R: parameter must belong to (0,1)\n") return(NULL) } Origine<-manifold@origin d<-manifold@distance if (manifold@name=="sphere"&parameter>0.5){ cat("There is no fBm on the sphere for H>0.5") return(NULL) } R<-function(xi,xj){ return(1/2*(d(Origine,xi)^{2*parameter}+d(Origine,xj)^{2*parameter}-d(xi,xj)^{2*parameter})) } nameProcess<-deparse(substitute(process)) process@covf<-R process@parameter<-parameter assign (nameProcess,process,envir = parent.frame()) return(NULL) } if (typeproc=="mBm"){ if (is.null(parameter)){ cat("Warning from constructcovf.R: parameter has been set to constant function equal to 0.5\n") parameter<-function(x){return(0.5)} } if (!is.function(parameter)){ cat("Error from constructcovf.R: parameter must be a function\n") return(NULL) } Origine<-manifold@origin d<-manifold@distance R<-function(xi,xj){ H1<-parameter(xi) H2<-parameter(xj) alpha<-1/2*(H1+H2) return(C2D(alpha)^2/(2*C2D(H1)*C2D(H2))*(d(Origine,xi)^(2*alpha)+d(Origine,xj)^(2*alpha)-d(xi,xj)^(2*alpha))) } nameProcess<-deparse(substitute(process)) process@covf<-R process@parameter<-parameter assign (nameProcess,process,envir = parent.frame()) return(NULL) } if (typeproc=="2pfBm"){ if (missing(parameter)){ cat("Warning from constructcovf.R: parameter H and K has been set to constant equal to 0.5 and 1 respectively\n") parameter<-list(H<-0.5,K=1) } Origine<-manifold@origin d<-manifold@distance H<-parameter$H K<-parameter$K R<-function(xi,xj){ return(1/2*((d(Origine,xi)^(2*H)+d(Origine,xj)^(2*H))^K-d(xi,xj)^(2*H*K))) } nameProcess<-deparse(substitute(process)) process@covf<-R process@parameter<-parameter assign (nameProcess,process,envir = parent.frame()) return(NULL) } if (typeproc=="stdfBm"){ if (is.null(parameter)){ cat("Warning from constructcovf.R: parameter H, tau and sigma has been set to constant equal to 0.5, function equal to identity and function equal to 1 respectively\n") parameter<-list(H=0.5,tau=function(x){return(x)},sigma=function(x){return(1)}) } Origine<-manifold@origin d<-manifold@distance tau<-parameter$tau sigma<-parameter$sigma H<-parameter$H R<-function(xi,xj){ return(sigma(xi)*sigma(xj)/2*(d(Origine,tau(xi))^(2*H)+d(Origine,tau(xj))^(2*H)-d(tau(xi),tau(xj))^(2*H))) } nameProcess<-deparse(substitute(process)) process@covf<-R process@parameter<-parameter assign (nameProcess,process,envir = parent.frame()) return(NULL) } if (typeproc=="fBs"){ if (any(manifold@name==c("line","plane"))){ dimension<-dim(manifold@atlas)[1] if (is.null(parameter)){ cat("Warning from constructcovf.R: parameter H has been set to constant equal to (0.5,0.5)\n") parameter<-rep(0.5,dimension) } Origine<-manifold@origin d<-manifold@distance H<-parameter R<-function(xi,xj){ p<-1 for (i in 1:dimension){ p<-p*1/2*(abs(Origine[i]-xi[i])^{2*H[i]}+abs(Origine[i]-xj[i])^{2*H[i]}-abs(xi[i]-xj[i])^{2*H[i]}) } return(p) } nameProcess<-deparse(substitute(process)) process@covf<-R process@parameter<-parameter assign (nameProcess,process,envir = parent.frame()) }else{ cat("There is no fBs on this manifold") return(NULL) } } if (typeproc=="afBf"){ if (manifold@name=="plane"){ dimension<-2 if (missing(parameter)){ cat("Warning from constructcovf.R: parameters H, theta1 and theta2 have been set to 0.5, 0 and pi/2 respectively\n") parameter<-list(H=0.5, theta1=0, theta2=pi/2) } Origine<-manifold@origin d<-manifold@distance H<-parameter$H theta1<-parameter$theta1 theta2<-parameter$theta2 Ibeta <- function(x,a,b){ pbeta(x,a,b)*beta(a,b) } R<-function(xi,xj){ if ((xi[1]==0 & xi[2]==0)|(xj[1]==0 & xj[2]==0)){ return(0) } y <- atan(xi[2]/xi[1]) Ib<-0 if ((y+pi/2 >= theta1) & (y+pi/2 <= theta2)) { Ib<-Ibeta((1-sin(theta2-y))/2,H+1/2,H+1/2)+Ibeta((1-sin(theta1-y))/2,H+1/2,H+1/2) }else if (y-pi/2 >= theta1 & y-pi/2 <= theta2) { Ib<-Ibeta((1+sin(theta2-y))/2,H+1/2,H+1/2)+Ibeta((1+sin(theta1-y))/2,H+1/2,H+1/2) }else{ Ib<-abs(Ibeta((1-sin(theta2-y))/2,H+1/2,H+1/2)-Ibeta((1-sin(theta1-y))/2,H+1/2,H+1/2)) } A<-2^(2*H-1)*pi/H/gamma(2*H)/sin(pi*H)*Ib*(xi[1]^2+xi[2]^2)^H if (all(xi==xj)){ return(2*A) }else{ y <- atan(xj[2]/xj[1]) Ib<-0 if ((y+pi/2 >= theta1) & (y+pi/2 <= theta2)) { Ib<-Ibeta((1-sin(theta2-y))/2,H+1/2,H+1/2)+Ibeta((1-sin(theta1-y))/2,H+1/2,H+1/2) }else if (y-pi/2 >= theta1 & y-pi/2 <= theta2) { Ib<-Ibeta((1+sin(theta2-y))/2,H+1/2,H+1/2)+Ibeta((1+sin(theta1-y))/2,H+1/2,H+1/2) }else{ Ib<-abs(Ibeta((1-sin(theta2-y))/2,H+1/2,H+1/2)-Ibeta((1-sin(theta1-y))/2,H+1/2,H+1/2)) } B<-2^(2*H-1)*pi/H/gamma(2*H)/sin(pi*H)*Ib*(xj[1]^2+xj[2]^2)^H yd<-(xj[2]-xi[2]) xd<-(xj[1]-xi[1]) y <- atan(yd/xd) Ib<-0 if ((y+pi/2 >= theta1) & (y+pi/2 <= theta2)) { Ib<-Ibeta((1-sin(theta2-y))/2,H+1/2,H+1/2)+Ibeta((1-sin(theta1-y))/2,H+1/2,H+1/2) }else if (y-pi/2 >= theta1 & y-pi/2 <= theta2) { Ib<-Ibeta((1+sin(theta2-y))/2,H+1/2,H+1/2)+Ibeta((1+sin(theta1-y))/2,H+1/2,H+1/2) }else{ Ib<-abs(Ibeta((1-sin(theta2-y))/2,H+1/2,H+1/2)-Ibeta((1-sin(theta1-y))/2,H+1/2,H+1/2)) } C<-2^(2*H-1)*pi/H/gamma(2*H)/sin(pi*H)*Ib*(xd^2+yd^2)^H return(A+B-C) } } nameProcess<-deparse(substitute(process)) process@covf<-R process@parameter<-parameter assign (nameProcess,process,envir = parent.frame()) }else{ cat("There is no afBf on this manifold") return(NULL) } } if (typeproc=="bridge"){ Gamma<-parameter$Gamma R<-parameter$R M<-dim(Gamma)[2] taille<-dim(Gamma)[1]-1 CovaGam<-matrix(0,M,M) Tp<-CovaGam for (i in 1:M){ for (j in 1:M){ CovaGam[i,j]<-R(Gamma[1:taille,i],Gamma[1:taille,j]) } } DC<-det(CovaGam) if (DC==0){ cat("Warning from constructcovf.R: GammaT%*%Gamma is not invertible \n") return(NULL) }else{ Tp<-solve(CovaGam) } parameter$Tp=Tp Rgamma<-function(xi,xj){ Rtmp<-parameter$R S2<-matrix(0,M,1) S1<-t(S2) for (i in 1:M){ S1[1,i]<-Rtmp(xi,Gamma[1:taille,i]) S2[i,1]<-Rtmp(xj,Gamma[1:taille,i]) } return(Rtmp(xi,xj)-S1%*%parameter$Tp%*%S2) } nameProcess<-deparse(substitute(process)) process@parameter<-parameter process@covf<-Rgamma assign (nameProcess,process,envir = parent.frame()) return(Rgamma) } }
GMLTimeInstant <- R6Class("GMLTimeInstant", inherit = GMLAbstractTimeGeometricPrimitive, private = list( xmlElement = "TimeInstant", xmlNamespacePrefix = "GML" ), public = list( timePosition = NULL, initialize = function(xml = NULL, timePosition){ super$initialize(xml = xml) if(is.null(xml)){ self$setTimePosition(timePosition) } }, setTimePosition = function(timePosition){ timePos <- timePosition if(is(timePos, "numeric")) timePos <- as(timePos, "character") if(!(is(timePos, "character") & nchar(timePos)%in%c(4,7))){ if(!is(timePos,"POSIXt") && !is(timePos, "Date")){ stop("Value should be of class ('POSIXct','POSIXt') or 'Date'") } } self$timePosition <- GMLElement$create("timePosition", value = timePos) } ) )
pmtest_internal <- function(X, alpha = 0.05, GrpID, VarID, rtf){ outS <- data.frame( k = integer(), MESOR = numeric(), CI.M = numeric(), Amplitude = numeric(), CI.A = numeric(), PHI = numeric(), CI.PHI = character(), P = numeric(), errMsg = numeric() ) as.list(outS) pmc <- data.frame( k = integer(), MESOR = numeric(), Amplitude = numeric(), PHI = numeric(), P = numeric() ) as.list(pmc) K <- nrow(X) m <- length(unique(X[,GrpID])) k <- table(X[,GrpID]) vecLen<-length(k) phi1=vector(mode="logical",length=vecLen) phi2=vector(mode="logical",length=vecLen) den=vector(mode="logical",length=vecLen) an1=vector(mode="logical",length=vecLen) an2=vector(mode="logical",length=vecLen) rownames<-X[,GrpID] X_list <- split(X, rownames) beta_star <- X$amp*cos(X$phi * pi/180) gamma_star <- -X$amp*sin(X$phi * pi/180) beta <- sapply(X_list, function(x) x$amp*cos(x$phi * pi/180), simplify = FALSE) beta_hat <- sapply(beta, mean) gamma <- sapply(X_list, function(x) -x$amp*sin(x$phi * pi/180), simplify = FALSE) gamma_hat <- sapply(gamma, mean) M <- sapply(X_list, function(x) mean(x$mesor)) phi <- mapply(function(b, g) -phsrd(b, g), beta, gamma) phi_star <- -phsrd(beta_star, gamma_star) A <- mapply(function(b, g) module(b, g), beta, gamma) A_star <- module(beta_star, gamma_star) sigma_matrices <- sapply(names(X_list), function(i) {generate_sigma_matrix(X_list[[i]], beta[[i]], gamma[[i]])},simplify=FALSE, USE.NAMES=TRUE) df<-k-1 if (all(df>1)){ tval <- qt(1-alpha/2, df) cim <- sapply(names(X_list), function(i) {cimf(tval[i], sigma_matrices[[i]], k[i])}, USE.NAMES=TRUE) c22 <- sapply(names(X_list), function(i) {c22f(sigma_matrices[[i]], beta_hat[[i]], gamma_hat[[i]], k[i], A[[i]])}, USE.NAMES=TRUE) cia <- tval*sqrt(c22) cia[c22<=0]<--.1 c23 <- sapply(names(X_list), function(i) {c23f(sigma_matrices[[i]], beta_hat[[i]], gamma_hat[[i]], k[i], A[[i]])}, USE.NAMES=TRUE) c33 <- sapply(names(X_list), function(i) {c33f(sigma_matrices[[i]], beta_hat[[i]], gamma_hat[[i]], k[i], A[[i]])}, USE.NAMES=TRUE) names(c23)<-names(tval) names(c33)<-names(tval) an2 <- A^2 - (c22*c33 - c23^2) * (tval^2)/c33 an2LT0<-which(an2<0) an2GTE0<-which(an2>=0) if (length(an2LT0)!=length(an2)){ den<-(A^2)-c22*(tval^2) an2<-tval*sqrt(c33)*sqrt(an2) an1<-c23*(tval^2) names(an1)<-names(tval) names(den)<-names(tval) phi1[an2GTE0]=sapply(names(X_list)[an2GTE0], function(i) {phase(phix=(an1[i]+an2[i])/den[i],c33[i],c23[i],phi[i])}, USE.NAMES=TRUE) phi2[an2GTE0]=sapply(names(X_list)[an2GTE0], function(i) {phase(phix=(an1[i]-an2[i])/den[i],c33[i],c23[i],phi[i])}, USE.NAMES=TRUE) } phi1[an2LT0]<-NA phi2[an2LT0]<-NA r <- sapply(names(X_list), function(i) {r_f(sigma_matrices[[i]])}, USE.NAMES=TRUE) fval <- sapply(names(X_list), function(i) {fvalf(sigma_matrices[[i]],beta_hat[[i]],gamma_hat[[i]],k[i],r[i])},USE.NAMES=TRUE) names(fval)<-names(r) p <- sapply(names(X_list), function(i) pf(fval[i], df1 = 2, df2 = k[i] - 2, lower.tail = FALSE)) sigma_matrix_hat <- Reduce(`+`, lapply(1:m, function(j) (k[j] - 1) * sigma_matrices[[j]]/(K - m))) M_bar <- sum(k * M)/K beta_bar <- sum(k * beta_hat)/K gamma_bar <- sum(k * gamma_hat)/K print("meanM, A*, phi*") print(mean(X$mesor)) print(A_star) print(phi_star) t_mat <- matrix(0, nrow = 3, ncol = 3) t_mat[1,1] <- sum(k * (M - M_bar)^2) t_mat[1,2] <- sum(k * (M - M_bar) * (beta_hat - beta_bar)) t_mat[1,3] <- sum(k * (M - M_bar) * (gamma_hat - gamma_bar)) t_mat[2,2] <- sum(k * (beta_hat - beta_bar)^2) t_mat[2,3] <- sum(k * (beta_hat - beta_bar) * (gamma_hat - gamma_bar)) t_mat[3,3] <- sum(k * (gamma_hat - gamma_bar)^2) t_mat[lower.tri(t_mat)] <- t_mat[upper.tri(t_mat)] t1 <- t_mat[2:3, 2:3] m_fval <- t_mat[1,1]/((m - 1) * sigma_matrix_hat[1,1]) m_p <- pf(m_fval, df1 = m-1, df2 = K-m, lower.tail = FALSE) J <- solve(sigma_matrix_hat[2:3, 2:3]) %*% t1 print(J) D <- det(diag(2) + J/(K-m)) print(D) rhythm_fval <- (K-m-1)/(m-1) * (sqrt(D) - 1) rhythm_p <- pf(rhythm_fval, df1 = 2*m - 2, df2=2*K - 2*m - 2, lower.tail = FALSE) rhythm_df1<-2*m-2 rhythm_df2<-2*K - 2*m - 2 num <- sum(k * A^2 * sin(2*phi * pi/180)) den <- sum(k * A^2 * cos(2*phi * pi/180)) if (den==0){ populations<-paste(names(X_list),collapse=" ") paste("F and P cannot be calculated for PHI. The denominator for phi_tilda=0 for populations: ",populations) stop("This is a very rare case. Amplitudes and PHIs for all listed populations, together, result in 0 for sum(k * A^2 * cos(2*phi * pi/180))") } phi_tilda <- atan(num/den)/2 if(den < 0){ phi_tilda <- phi_tilda + pi/2 } phi_delta<-beta_hat*cos(phi_tilda)-gamma_hat*sin(phi_tilda) if (all(phi_delta>=0) || all(phi_delta<0)){ num <- sum(k * A^2 * sin((phi * pi/180) - phi_tilda)^2)/(m - 1) den <- (sigma_matrix_hat[2,2] * sin(phi_tilda)^2) + (2 * sigma_matrix_hat[2,3] * cos(phi_tilda) * sin(phi_tilda)) + (sigma_matrix_hat[3,3] * cos(phi_tilda)^2) phi_fval <- num/den phi_p <- pf(phi_fval, df1 = m-1, df2 = K-m, lower.tail = FALSE) } else { phi_tilda<-NA phi_fval<-NA phi_p<-NA } phi_same<-FALSE if ((abs(max(phi) - min(phi))) < .001 || (abs(max(phi) - min(phi)) > 359.99)){ phi_fval<-NA phi_p<-NA phi_same<-TRUE } if (abs(max(A) - min(A)) >= .0001){ num <- sum(k * (A - A_star)^2)/(m-1) den <- (sigma_matrix_hat[2,2] * (cos(phi_star * pi/180)^2)) - (2 * sigma_matrix_hat[2,3] * cos(phi_star * pi/180)*sin(phi_star * pi/180)) + (sigma_matrix_hat[3,3]*(sin(phi_star * pi/180)^2)) amp_fval <- num/den amp_p <- pf(amp_fval, df1 = m-1, df2 = K-m, lower.tail = FALSE) } else { amp_fval<-NA amp_p<-NA } print("Combined: meanM, A*, phi*") print(M_bar) print(A_star) print(phi_star) printp <- round(p, 4) printp[printp<.0005]<-c("<.001") if (A_star < .000000000001){ phi_star<-"--" } outS<-rbind.data.frame(outS, cbind(k,MESOR=formatC(M,digits=3,format="f"),CI.M=formatC(cim,digits=3,format="f"),Amplitude=formatC(A,digits=3,format="f"),CI.A=formatC(cia,digits=3,format="f"),PHI=formatC(phi,digits=1,format="f"),CI.PHI=paste("(",round(phi1,1),",",round(phi2,1),")"),P=printp)) pmc<-rbind.data.frame(pmc, cbind(k=NA,MESOR=formatC(M_bar,digits=3,format="f"),CI.M="",Amplitude=formatC(A_star,digits=3,format="f"),CI.A="",PHI=formatC(phi_star,digits=1,format="f"),CI.PHI="",P="")) rownames(pmc)[1]<-"Combined parameters:" outS[which(A-cia<0 & p<=alpha),"errMsg"]<-paste(outS[which(A-cia<0 & p<=alpha),"errMsg"],"Warn1") if (A_star < .000000000001){ pmc[1,"errMsg"]<- "Warn7" } else { pmc[1,"errMsg"]<-NA } outS<-rbind.data.frame(outS, pmc) if (exists("rtf")){ addParagraph(rtf,paste("\nPopulation Mean Cosinor (PMC)")) addTable(rtf,outS, col.justify='C',header.col.justify='C' ,font.size=11,row.names=TRUE,NA.string="--") } addParagraph(rtf,"\nTests of Equality of Parameters (PMC Test): ") P <- c(m_p, amp_p, phi_p, rhythm_p) printP <- formatC(P,digits=4,format="f") printP[P<.0005]<-c("<.001") out <- data.frame(df1 = c(m-1, m-1, m-1,rhythm_df1), df2 = c(K-m, K-m, K-m,rhythm_df2), F = formatC(c(m_fval, amp_fval, phi_fval, rhythm_fval),digits=4,format="f"), P=printP) row.names(out) <- c("MESOR", "Amplitude", "Acrophase", "(A, phi)") if (is.na(phi_tilda)){ out[3,"errMsg"]<-"Warn4" } else { out[1,"errMsg"]<-NA } if (is.na(amp_fval) && is.na(amp_p)){ out[2,"errMsg"]<-"Warn5" } if (phi_same){ if (is.na(out[3,"errMsg"])){ out[3,"errMsg"]<-"Warn6" } else { out[3,"errMsg"]<-paste(out[3,"errMsg"],"; Warn6",sep="") } } } else { outS<-rbind.data.frame(outS, cbind(k,MESOR=NA,CI.M=NA,Amplitude=NA,CI.A="",PHI=NA,CI.PHI=NA,P=NA,errMsg="")) pmc<-rbind.data.frame(pmc, cbind(k=NA,MESOR="--",CI.M="",Amplitude="--",CI.A="",PHI="--",CI.PHI="",P="",errMsg="Warn2")) rownames(pmc)[1]<-"Combined parameters:" outS<-rbind.data.frame(outS, pmc) if (exists("rtf")){ addParagraph(rtf,paste("\nPopulation Mean Cosinor (PMC)")) addTable(rtf,outS, col.justify='C',header.col.justify='C' ,font.size=11,row.names=TRUE,NA.string="--") } addParagraph(rtf,"\nTests of Equality of Parameters (PMC Test): ") out <- data.frame(df1 = NA, df2 = NA, F = NA, P=NA) out[1,"errMsg"]<-paste("Warn3") } return(out) }
roc_scores <- function(preds, actuals){ ROCPosition <- NULL Pred <- NULL Err <- NULL Actual <- NULL Count <- NULL Value <- NULL overall <- mean(actuals) dt <- data.table(Pred=preds, Actual=actuals) dt[, ROCPosition := (frank(Pred) - 1) / (.N - 1)] dt[, Err := abs(ROCPosition - overall)] dt[(Actual==0 & ROCPosition <= overall) | (Actual==1 & ROCPosition >= overall), Err := 0] return(dt$Err) }
anovatol.int <- function (lm.out, data, alpha = 0.05, P = 0.99, side = 1, method = c("HE", "HE2", "WBE", "ELL", "KM", "EXACT", "OCT"), m = 50) { method <- match.arg(method) out <- anova(lm.out) dims <- dim(out) s <- sqrt(out[dims[1], 3]) df <- out[, 1] xlev <- lm.out$xlevels resp <- names(attr(lm.out$terms, "dataClasses"))[1] resp.ind <- which(colnames(data) == resp) pred.ind <- c(1:ncol(data))[c(colnames(data) %in% names(xlev))] factors <- names(xlev) out.list <- list() bal <- NULL for (i in 1:length(xlev)) { ttt <- by(data[, resp.ind], data[, pred.ind[i]], mean) temp.means <- as.numeric(ttt) temp.eff <- as.numeric(by(data[, resp.ind], data[, pred.ind[i]], length)) K <- NULL for (j in 1:length(temp.eff)) { K <- c(K, K.factor(n = temp.eff[j], f=tail(df,1), alpha = alpha, P = P, side = side, method = method, m = m)) } temp.low <- temp.means - K * s temp.up <- temp.means + K * s temp.mat <- data.frame(cbind(temp.means, temp.eff, K, temp.low, temp.up)) rownames(temp.mat) <- names(ttt) if (side == 1) { colnames(temp.mat) <- c("mean", "n", "k", "1-sided.lower", "1-sided.upper") } else colnames(temp.mat) <- c("mean", "n", "k", "2-sided.lower", "2-sided.upper") out.list[[i]] <- temp.mat bal = c(bal, sum(abs(temp.eff - mean(temp.eff)) > 3)) } bal <- sum(bal) if (bal > 0) warning("This procedure should only be used for balanced (or nearly-balanced) designs.", call. = FALSE) names(out.list) <- names(xlev) if (side == 1) { message("These are ", (1 - alpha) * 100, "%/", P * 100, "% ", side, "-sided tolerance limits.") } else message("These are ", (1 - alpha) * 100, "%/", P * 100, "% ", side, "-sided tolerance intervals.") attr(out.list, "comment") <- c(resp, alpha, P) out.list }
llsearch.LE3.CDS <- function(x, y, n, jlo, jhi,start_1,start_2,start_3) { fj <- matrix(0, n) fxy <- matrix(0, jhi - jlo + 1) jgrid <- expand.grid(jlo:jhi) k.ll <- apply(jgrid, 1, p.estFUN.CDS.LE3, x = x, y = y, n = n,start_1=start_1,start_2=start_2,start_3=start_3) fxy <- matrix(k.ll, nrow = jhi-jlo+1) rownames(fxy) <- jlo:jhi z <- findmax(fxy) jcrit <- z$imax + jlo - 1 list(jhat = jcrit, value = max(fxy)) } p.estFUN.CDS.LE3 <- function(j, x, y, n,start_1,start_2,start_3){ a <- p.est.LE3.CDS(x,y,n,j,start_1,start_2,start_3) s2 <- a$sigma2 t2 <- a$tau2 return(p.ll.CDS(n, j, s2, t2)) } p.est.LE3.CDS <- function(x,y,n,j,start_1,start_2,start_3){ xa <- x[1:j] ya <- y[1:j] jp1 <- j+1 xb <- x[jp1:n] yb <- y[jp1:n] fun <- nls(y ~ I(x <= x[j])*(a0 + a1*x) + I(x > x[j])*(a0 + a1*x[j] - a1/b2 + a1/b2*exp(b2*(x-x[j]))), start = list(a0 = 10, a1 = -0.8, b2 = 0.5)) a0 <- summary(fun)$coe[1] a1 <- summary(fun)$coe[2] b2 <- summary(fun)$coe[3] b1 <- a1/b2 b0 <- a0 + a1 * x[j] - b1 beta <-c(a0,a1,b0,b1,b2) s2<- sum((ya-a0-a1*xa)^2)/j t2 <-sum(yb-b0-b1*exp(b2*(xb-x[j]))^2)/(n-j) list(a0=beta[1],a1=beta[2],b0=beta[3],b1=beta[4],b2=beta[5],sigma2=s2,tau2=t2,xj=x[j]) } p.ll.CDS <- function(n, j, s2, t2){ q1 <- n * log(sqrt(2 * pi)) q2 <- 0.5 * j * (1 + log(s2)) q3 <- 0.5 * (n - j) * (1 + log(t2)) - (q1 + q2 + q3) } findmax <-function(a) { maxa<-max(a) imax<- which(a==max(a),arr.ind=TRUE)[1] jmax<-which(a==max(a),arr.ind=TRUE)[2] list(imax = imax, jmax = jmax, value = maxa) }
preds <- function(model, newdata = NULL, what = "mean", vary_by = NULL) { if (is(newdata, "data.frame")) newdata <- as.data.frame(newdata) if (!is.null(newdata) && !is(newdata, "data.frame")) stop("Newdata has to be in a data.frame format") if (is.null(newdata)) newdata <- set_mean( model_data(model), vary_by = vary_by ) newdata <- na.omit(newdata) rnames <- row.names(newdata) if (is(model, "gamlss")) { if (what != "mean") stop("In gamlss models there are no samples") pred_par <- as.data.frame(predictAll(model, newdata = newdata, type = "response", data = model_data(model, incl_dep = TRUE)), row.names = rnames) pred_par <- pred_par[, !colnames(pred_par) %in% "y", drop = FALSE] } else if (is(model, "bamlss")) { if (what == "mean") { pred_par <- as.data.frame(predict(model, newdata = newdata, drop = FALSE, type = "parameter", intercept = TRUE), row.names = rnames) } if (what == "samples") { samples_raw <- predict(model, newdata = newdata, drop = FALSE, type = "parameter", intercept = TRUE, FUN = function(x) return(x)) pred_par <- preds_transformer(samples_raw, newdata = newdata) } } else if (is(model, "betareg") | is(model, "betatree")) { if (what == "mean") { pred_par <- data.frame( mu = stats::predict(model, newdata = newdata, type = "response"), phi = stats::predict(model, newdata = newdata, type = "precision")) } else if (what != "mean") { stop("betareg uses ML, so no samples available.") } } else { stop("Model class is not supported, so can't make predictions. \n See ?distreg_checker for supported models") } return(pred_par) } preds_transformer <- function(samp_list, newdata) { params <- names(samp_list) samp_list <- lapply(samp_list, FUN = t) samp_list <- lapply(samp_list, function(x) { colnames(x) <- row.names(newdata) x <- as.data.frame(x) return(x) }) resh <- lapply(seq_len(nrow(newdata)), FUN = function(num) { sapply(samp_list, function(df) { return(df[, num]) }) }) names(resh) <- row.names(newdata) return(resh) }
spmd.sendrecv.replace.default <- function(x, rank.dest = (comm.rank(.pbd_env$SPMD.CT$comm) + 1) %% comm.size(.pbd_env$SPMD.CT$comm), send.tag = .pbd_env$SPMD.CT$tag, rank.source = (comm.rank(.pbd_env$SPMD.CT$comm) - 1) %% comm.size(.pbd_env$SPMD.CT$comm), recv.tag = .pbd_env$SPMD.CT$tag, comm = .pbd_env$SPMD.CT$comm, status = .pbd_env$SPMD.CT$status){ x.raw <- serialize(x, NULL) total.org <- length(x.raw) total.new <- spmd.sendrecv.replace.integer(as.integer(total.org), rank.dest = rank.source, send.tag = send.tag, rank.source = rank.dest, recv.tag = recv.tag, comm = comm, status = status) if(total.org == total.new){ unserialize(spmd.sendrecv.replace.raw(x.raw, rank.dest = rank.dest, send.tag = send.tag, rank.source = rank.source, recv.tag = recv.tag, comm = comm, status = status)) } else{ stop("Objects are not consistent.") } } spmd.sendrecv.replace.integer <- function(x, rank.dest = (comm.rank(.pbd_env$SPMD.CT$comm) + 1) %% comm.size(.pbd_env$SPMD.CT$comm), send.tag = .pbd_env$SPMD.CT$tag, rank.source = (comm.rank(.pbd_env$SPMD.CT$comm) - 1) %% comm.size(.pbd_env$SPMD.CT$comm), recv.tag = .pbd_env$SPMD.CT$tag, comm = .pbd_env$SPMD.CT$comm, status = .pbd_env$SPMD.CT$status){ .Call("spmd_sendrecv_replace_integer", x, as.integer(rank.dest), as.integer(send.tag), as.integer(rank.source), as.integer(recv.tag), as.integer(comm), as.integer(status), PACKAGE = "pbdMPI") } spmd.sendrecv.replace.double <- function(x, rank.dest = (comm.rank(.pbd_env$SPMD.CT$comm) + 1) %% comm.size(.pbd_env$SPMD.CT$comm), send.tag = .pbd_env$SPMD.CT$tag, rank.source = (comm.rank(.pbd_env$SPMD.CT$comm) - 1) %% comm.size(.pbd_env$SPMD.CT$comm), recv.tag = .pbd_env$SPMD.CT$tag, comm = .pbd_env$SPMD.CT$comm, status = .pbd_env$SPMD.CT$status){ .Call("spmd_sendrecv_replace_double", x, as.integer(rank.dest), as.integer(send.tag), as.integer(rank.source), as.integer(recv.tag), as.integer(comm), as.integer(status), PACKAGE = "pbdMPI") } spmd.sendrecv.replace.raw <- function(x, rank.dest = (comm.rank(.pbd_env$SPMD.CT$comm) + 1) %% comm.size(.pbd_env$SPMD.CT$comm), send.tag = .pbd_env$SPMD.CT$tag, rank.source = (comm.rank(.pbd_env$SPMD.CT$comm) - 1) %% comm.size(.pbd_env$SPMD.CT$comm), recv.tag = .pbd_env$SPMD.CT$tag, comm = .pbd_env$SPMD.CT$comm, status = .pbd_env$SPMD.CT$status){ .Call("spmd_sendrecv_replace_raw", x, as.integer(rank.dest), as.integer(send.tag), as.integer(rank.source), as.integer(recv.tag), as.integer(comm), as.integer(status), PACKAGE = "pbdMPI") } setGeneric( name = "sendrecv.replace", useAsDefault = spmd.sendrecv.replace.default ) setMethod( f = "sendrecv.replace", signature = signature(x = "ANY"), definition = spmd.sendrecv.replace.default ) setMethod( f = "sendrecv.replace", signature = signature(x = "integer"), definition = spmd.sendrecv.replace.integer ) setMethod( f = "sendrecv.replace", signature = signature(x = "numeric"), definition = spmd.sendrecv.replace.double ) setMethod( f = "sendrecv.replace", signature = signature(x = "raw"), definition = spmd.sendrecv.replace.raw )
par.init <- function(degree,segments,monotone,monotone.lb) { dim.p <- degree+segments par.ub <- - sqrt(.Machine$double.eps) par.lb <- monotone.lb par.init <- c(runif(1,-10,par.ub),rnorm(dim.p-2),runif(1,-10,par.ub)) par.upper <- c(par.ub,rep(Inf,dim.p-2),par.ub) par.lower <- if(monotone){rep(-Inf,dim.p)}else{c(par.lb,rep(-Inf,dim.p-2),par.lb)} return(list(par.init=par.init, par.upper=par.upper, par.lower=par.lower)) } gen.xnorm <- function(x=NULL, xeval=NULL, lbound=NULL, ubound=NULL, er=NULL, n.integrate=NULL) { er <- extendrange(x,f=er) if(!is.null(lbound)) er[1] <- lbound if(!is.null(ubound)) er[2] <- ubound if(min(x) < er[1] | max(x) > er[2]) warning(" data extends beyond the range of `er'") xint <- sort(as.numeric(c(seq(er[1],er[2],length=round(n.integrate/2)), quantile(x,seq(sqrt(.Machine$double.eps),1-sqrt(.Machine$double.eps),length=round(n.integrate/2)))))) if(is.null(xeval)) { xnorm <- c(x,xint) } else { xnorm <- c(xeval,x,xint) if(min(xeval) < er[1] | max(xeval) > er[2]) warning(" evaluation data extends beyond the range of `er'") } return(list(xnorm=xnorm[order(xnorm)],rank.xnorm=rank(xnorm))) } density.basis <- function(x=NULL, xeval=NULL, xnorm=xnorm, degree=NULL, segments=NULL, basis="tensor", knots="quantiles", monotone=TRUE) { suppressWarnings(Pnorm <- prod.spline(x=x, xeval=xnorm, K=cbind(degree,segments+if(monotone){2}else{0}), knots=knots, basis=basis)) if(monotone) Pnorm <- Pnorm[,-c(2,degree+segments+1)] suppressWarnings(P.lin <- prod.spline(x=x, xeval=xnorm, K=cbind(1,1), knots=knots, basis=basis)) Pnorm[xnorm<min(x),] <- 0 Pnorm[xnorm>max(x),] <- 0 Pnorm[xnorm==max(x),-ncol(Pnorm)] <- 0 P.left <- as.matrix(P.lin[,1]) P.right <- as.matrix(P.lin[,2]) index <- which(xnorm==min(x)) index.l <- index+1 index.u <- index+5 x.l <- xnorm[index.l] x.u <- xnorm[index.u] slope.poly.left <- as.numeric((Pnorm[index.u,1]-Pnorm[index.l,1])/(x.u-x.l)) index.l <- index+1 index.u <- index+5 x.l <- xnorm[index.l] x.u <- xnorm[index.u] slope.linear.left <- as.numeric((P.left[index.u]-P.left[index.l])/(x.u-x.l)) index <- which(xnorm==max(x)) index.l <- index-1 index.u <- index-5 x.l <- xnorm[index.l] x.u <- xnorm[index.u] slope.poly.right <- as.numeric((Pnorm[index.u,ncol(Pnorm)]-Pnorm[index.l,ncol(Pnorm)])/(x.u-x.l)) index.l <- index-1 index.u <- index-5 x.l <- xnorm[index.l] x.u <- xnorm[index.u] slope.linear.right <- as.numeric((P.right[index.u]-P.right[index.l])/(x.u-x.l)) P.left <- as.matrix(P.left-1)*slope.poly.left/slope.linear.left+1 P.right <- as.matrix(P.right-1)*slope.poly.right/slope.linear.right+1 P.left[xnorm>=min(x),1] <- 0 P.right[xnorm<=max(x),1] <- 0 Pnorm[,1] <- Pnorm[,1]+P.left Pnorm[,ncol(Pnorm)] <- Pnorm[,ncol(Pnorm)]+P.right return(Pnorm) } density.deriv.basis <- function(x=NULL, xeval=NULL, xnorm=xnorm, degree=NULL, segments=NULL, basis="tensor", knots="quantiles", monotone=TRUE, deriv.index=1, deriv=1) { suppressWarnings(Pnorm.deriv <- prod.spline(x=x, xeval=xnorm, K=cbind(degree,segments+if(monotone){2}else{0}), knots=knots, basis=basis, deriv.index=deriv.index, deriv=deriv)) if(monotone) Pnorm.deriv <- Pnorm.deriv[,-c(2,degree+segments+1)] suppressWarnings(P.lin <- prod.spline(x=x, xeval=xnorm, K=cbind(1,1), knots=knots, basis=basis, deriv.index=deriv.index, deriv=deriv)) Pnorm.deriv[xnorm<min(x),] <- 0 Pnorm.deriv[xnorm>max(x),] <- 0 P.left <- as.matrix(P.lin[,1]) P.left[xnorm>=min(x),1] <- 0 P.right <- as.matrix(P.lin[,2]) P.right[xnorm<=max(x),1] <- 0 Pnorm.deriv[,1] <- Pnorm.deriv[,1]+P.left Pnorm.deriv[,ncol(Pnorm.deriv)] <- Pnorm.deriv[,ncol(Pnorm.deriv)]+P.right return(Pnorm.deriv) } clsd <- function(x=NULL, beta=NULL, xeval=NULL, degree=NULL, segments=NULL, degree.min=2, degree.max=25, segments.min=1, segments.max=100, lbound=NULL, ubound=NULL, basis="tensor", knots="quantiles", penalty=NULL, deriv.index=1, deriv=1, elastic.max=TRUE, elastic.diff=3, do.gradient=TRUE, er=NULL, monotone=TRUE, monotone.lb=-250, n.integrate=500, nmulti=1, method = c("L-BFGS-B", "Nelder-Mead", "BFGS", "CG", "SANN"), verbose=FALSE, quantile.seq=seq(.01,.99,by=.01), random.seed=42, maxit=10^5, max.attempts=25, NOMAD=FALSE) { if(elastic.max && !NOMAD) { degree.max <- 3 segments.max <- 3 } ptm <- system.time("") if(is.null(x)) stop(" You must provide data") if(!is.null(er) && er < 0) stop(" er must be non-negative") if(is.null(er)) er <- 1/log(length(x)) if(is.null(penalty)) penalty <- log(length(x))/2 method <- match.arg(method) fv <- NULL gen.xnorm.out <- gen.xnorm(x=x, lbound=lbound, ubound=ubound, er=er, n.integrate=n.integrate) xnorm <- gen.xnorm.out$xnorm rank.xnorm <- gen.xnorm.out$rank.xnorm if(is.null(beta)) { ptm <- ptm + system.time(ls.ml.out <- ls.ml(x=x, xnorm=xnorm, rank.xnorm=rank.xnorm, degree.min=degree.min, segments.min=segments.min, degree.max=degree.max, segments.max=segments.max, lbound=lbound, ubound=ubound, elastic.max=elastic.max, elastic.diff=elastic.diff, do.gradient=do.gradient, maxit=maxit, nmulti=nmulti, er=er, method=method, n.integrate=n.integrate, basis=basis, knots=knots, penalty=penalty, monotone=monotone, monotone.lb=monotone.lb, verbose=verbose, max.attempts=max.attempts, random.seed=random.seed, NOMAD=NOMAD)) beta <- ls.ml.out$beta degree <- ls.ml.out$degree segments <- ls.ml.out$segments fv <- ls.ml.out$fv } if(!is.null(xeval)) { gen.xnorm.out <- gen.xnorm(x=x, xeval=xeval, lbound=lbound, ubound=ubound, er=er, n.integrate=n.integrate) xnorm <- gen.xnorm.out$xnorm rank.xnorm <- gen.xnorm.out$rank.xnorm } if(is.null(degree)) stop(" You must provide spline degree") if(is.null(segments)) stop(" You must provide number of segments") ptm <- ptm + system.time(Pnorm <- density.basis(x=x, xeval=xeval, xnorm=xnorm, degree=degree, segments=segments, basis=basis, knots=knots, monotone=monotone)) if(ncol(Pnorm)!=length(beta)) stop(paste(" Incompatible arguments: beta must be of dimension ",ncol(Pnorm),sep="")) Pnorm.beta <- as.numeric(Pnorm%*%as.matrix(beta)) norm.constant <- integrate.trapezoidal.sum(xnorm,exp(Pnorm.beta)) log.norm.constant <- log(norm.constant) if(!is.finite(log.norm.constant)) stop(paste(" integration not finite - perhaps try reducing `er' (current value = ",round(er,3),")",sep="")) f.norm <- exp(Pnorm.beta-log.norm.constant) F.norm <- integrate.trapezoidal(xnorm,f.norm) if(deriv > 0) { ptm <- ptm + system.time(Pnorm.deriv <- density.deriv.basis(x=x, xeval=xeval, xnorm=xnorm, degree=degree, segments=segments, basis=basis, knots=knots, monotone=monotone, deriv.index=deriv.index, deriv=deriv)) f.norm.deriv <- as.numeric(f.norm*Pnorm.deriv%*%beta) } else { f.deriv <- NULL f.norm.deriv <- NULL } quantile.vec <- numeric(length(quantile.seq)) for(i in 1:length(quantile.seq)) { if(quantile.seq[i]>=0.5) { quantile.vec[i] <- max(xnorm[F.norm<=quantile.seq[i]]) } else { quantile.vec[i] <- min(xnorm[F.norm>=quantile.seq[i]]) } } if(is.null(xeval)) { f <- f.norm[rank.xnorm][1:length(x)] F <- F.norm[rank.xnorm][1:length(x)] f.norm <- f.norm[rank.xnorm][(length(x)+1):length(f.norm)] F.norm <- F.norm[rank.xnorm][(length(x)+1):length(F.norm)] xnorm <- xnorm[rank.xnorm][(length(x)+1):length(xnorm)] if(deriv>0) { f.deriv <- f.norm.deriv[rank.xnorm][1:length(x)] f.norm.deriv <- f.norm.deriv[rank.xnorm][(length(x)+1):length(f.norm.deriv)] } P <- Pnorm[rank.xnorm,][1:length(x),] P.beta <- Pnorm.beta[rank.xnorm][1:length(x)] } else { f <- f.norm[rank.xnorm][1:length(xeval)] F <- F.norm[rank.xnorm][1:length(xeval)] f.norm <- f.norm[rank.xnorm][(length(x)+length(xeval)+1):length(f.norm)] F.norm <- F.norm[rank.xnorm][(length(x)+length(xeval)+1):length(F.norm)] xnorm <- xnorm[rank.xnorm][(length(x)+length(xeval)+1):length(xnorm)] if(deriv>0) { f.deriv <- f.norm.deriv[rank.xnorm][1:length(xeval)] f.norm.deriv <- f.norm.deriv[rank.xnorm][(length(x)+length(xeval)+1):length(f.norm.deriv)] } P <- Pnorm[rank.xnorm,][1:length(xeval),] P.beta <- Pnorm.beta[rank.xnorm][1:length(xeval)] } clsd.return <- list(density=f, density.deriv=f.deriv, distribution=F, density.er=f.norm, density.deriv.er=f.norm.deriv, distribution.er=F.norm, xer=xnorm, Basis.beta=P.beta, Basis.beta.er=Pnorm.beta, P=P, Per=Pnorm, logl=sum(P.beta-log.norm.constant), constant=norm.constant, degree=degree, segments=segments, knots=knots, basis=basis, nobs=length(x), beta=beta, fv=fv, er=er, penalty=penalty, nmulti=nmulti, x=x, xq=quantile.vec, tau=quantile.seq, ptm=ptm) class(clsd.return) <- "clsd" return(clsd.return) } sum.log.density <- function(beta=NULL, P=NULL, Pint=NULL, xint=NULL, length.x=NULL, penalty=NULL, complexity=NULL, ...) { return(2*sum(P%*%beta)-2*length.x*log(integrate.trapezoidal.sum(xint,exp(Pint%*%beta)))-penalty*complexity) } sum.log.density.gradient <- function(beta=NULL, colSumsP=NULL, Pint=NULL, xint=NULL, length.x=NULL, penalty=NULL, complexity=NULL, ...) { exp.Pint.beta <- as.numeric(exp(Pint%*%beta)) exp.Pint.beta.Pint <- exp.Pint.beta*Pint int.exp.Pint.beta.Pint <- numeric() for(i in 1:complexity) int.exp.Pint.beta.Pint[i] <- integrate.trapezoidal.sum(xint,exp.Pint.beta.Pint[,i]) return(2*(colSumsP-length.x*int.exp.Pint.beta.Pint/integrate.trapezoidal.sum(xint,exp.Pint.beta))) } ls.ml <- function(x=NULL, xnorm=NULL, rank.xnorm=NULL, degree.min=NULL, segments.min=NULL, degree.max=NULL, segments.max=NULL, lbound=NULL, ubound=NULL, elastic.max=FALSE, elastic.diff=NULL, do.gradient=TRUE, maxit=NULL, nmulti=NULL, er=NULL, method=NULL, n.integrate=NULL, basis=NULL, knots=NULL, penalty=NULL, monotone=TRUE, monotone.lb=NULL, verbose=NULL, max.attempts=NULL, random.seed=NULL, NOMAD=FALSE) { if(exists(".Random.seed", .GlobalEnv)) { save.seed <- get(".Random.seed", .GlobalEnv) exists.seed = TRUE } else { exists.seed = FALSE } set.seed(random.seed) if(missing(x)) stop(" You must provide data") if(!NOMAD) { d.opt <- Inf s.opt <- Inf par.opt <- Inf value.opt <- -Inf length.x <- length(x) length.xnorm <- length(xnorm) d <- degree.min while(d <= degree.max) { s <- segments.min while(s <= segments.max) { if(options('crs.messages')$crs.messages) { if(verbose) cat("\n") cat("\r ") cat("\rOptimizing, degree = ",d,", segments = ",s,", degree.opt = ",d.opt, ", segments.opt = ",s.opt," ",sep="") } Pnorm <- density.basis(x=x, xnorm=xnorm, degree=d, segments=s, basis=basis, knots=knots, monotone=monotone) P <- Pnorm[rank.xnorm,][1:length.x,] colSumsP <- colSums(P) Pint <- Pnorm[rank.xnorm,][(length.x+1):nrow(Pnorm),] xint <- xnorm[rank.xnorm][(length.x+1):nrow(Pnorm)] complexity <- d+s for(n in 1:nmulti) { par.init.out <- par.init(d,s,monotone,monotone.lb) par.init <- par.init.out$par.init par.upper <- par.init.out$par.upper par.lower <- par.init.out$par.lower optim.out <- list() optim.out[[4]] <- 9999 optim.out$value <- -Inf m.attempts <- 0 while(tryCatch(suppressWarnings(optim.out <- optim(par=par.init, fn=sum.log.density, gr=if(do.gradient){sum.log.density.gradient}else{NULL}, upper=par.upper, lower=par.lower, method=method, penalty=penalty, P=P, colSumsP=colSumsP, Pint=Pint, length.x=length.x, xint=xint, complexity=complexity, control=list(fnscale=-1,maxit=maxit,if(verbose){trace=1}else{trace=0}))), error = function(e){return(optim.out)})[[4]]!=0 && m.attempts < max.attempts){ if(options('crs.messages')$crs.messages) { if(verbose && optim.out[[4]]!=0) { if(!is.null(optim.out$message)) cat("\n optim message = ",optim.out$message,sep="") cat("\n optim failed (degree = ",d,", segments = ",s,", convergence = ", optim.out[[4]],") re-running with new initial values",sep="") } } par.init.out <- par.init(d,s,monotone,monotone.lb) par.init <- par.init.out$par.init par.upper <- par.init.out$par.upper par.lower <- par.init.out$par.lower m.attempts <- m.attempts+1 } if(optim.out$value > value.opt) { if(options('crs.messages')$crs.messages) { if(verbose && n==1) cat("\n optim improved: d = ",d,", s = ",s,", old = ",formatC(value.opt,format="g",digits=6),", new = ",formatC(optim.out$value,format="g",digits=6),", diff = ",formatC(optim.out$value-value.opt,format="g",digits=6),sep="") if(verbose && n>1) cat("\n optim improved (ms ",n,"/",nmulti,"): d = ",d,", s = ",s,", old = ",formatC(value.opt,format="g",digits=6),", new = ",formatC(optim.out$value,format="g",digits=6),", diff = ",formatC(optim.out$value-value.opt,format="g",digits=6),sep="") } par.opt <- optim.out$par d.opt <- d s.opt <- s value.opt <- optim.out$value } } if(!(segments.min==segments.max) && elastic.max && s.opt == segments.max) segments.max <- segments.max+elastic.diff if(!(segments.min==segments.max) && elastic.max && s.opt < segments.max+elastic.diff) segments.max <- s.opt+elastic.diff s <- s+1 } d <- d+1 if(!(degree.min==degree.max) && elastic.max && d.opt == degree.max) degree.max <- degree.max+elastic.diff if(!(degree.min==degree.max) && elastic.max && d.opt < degree.max+elastic.diff) degree.max <- d.opt+elastic.diff } } else { eval.f <- function(input, params) { sum.log.density <- params$sum.log.density sum.log.density.gradient <- params$sum.log.density.gradient method <- params$method penalty <- params$penalty x <- params$x xnorm <- params$xnorm knots <- params$knots basis <- params$basis monotone <- params$monotone monotone.lb <- params$monotone.lb rank.xnorm <- params$rank.xnorm do.gradient <- params$do.gradient maxit <- params$maxit max.attempts <- params$max.attempts verbose <- params$verbose length.x <- length(x) length.xnorm <- length(xnorm) d <- input[1] s <- input[2] complexity <- d+s Pnorm <- density.basis(x=x, xnorm=xnorm, degree=d, segments=s, basis=basis, knots=knots, monotone=monotone) P <- Pnorm[rank.xnorm,][1:length.x,] colSumsP <- colSums(P) Pint <- Pnorm[rank.xnorm,][(length.x+1):nrow(Pnorm),] xint <- xnorm[rank.xnorm][(length.x+1):nrow(Pnorm)] optim.out <- list() optim.out[[4]] <- 9999 optim.out$value <- -Inf m.attempts <- 0 while(tryCatch(suppressWarnings(optim.out <- optim(par=par.init, fn=sum.log.density, gr=if(do.gradient){sum.log.density.gradient}else{NULL}, upper=par.upper, lower=par.lower, method=method, penalty=penalty, P=P, colSumsP=colSumsP, Pint=Pint, length.x=length.x, xint=xint, complexity=complexity, control=list(fnscale=-1,maxit=maxit,if(verbose){trace=1}else{trace=0}))), error = function(e){return(optim.out)})[[4]]!=0 && m.attempts < max.attempts){ if(verbose && optim.out[[4]]!=0) { if(options('crs.messages')$crs.messages) { if(!is.null(optim.out$message)) cat("\n optim message = ",optim.out$message,sep="") cat("\n optim failed (degree = ",d,", segments = ",s,", convergence = ", optim.out[[4]],") re-running with new initial values",sep="") } } par.init.out <- par.init(d,s,monotone,monotone.lb) par.init <- par.init.out$par.init par.upper <- par.init.out$par.upper par.lower <- par.init.out$par.lower m.attempts <- m.attempts+1 } if(options('crs.messages')$crs.messages) { if(verbose) cat("\n") cat("\r ") cat("\rOptimizing, degree = ",d,", segments = ",s,", log likelihood = ",optim.out$value,sep="") } fv <- -optim.out$value } x0 <- c(degree.min,segments.min) bbin <-c(1, 1) lb <- c(degree.min,segments.min) ub <- c(degree.max,segments.max) bbout <- c(0, 2, 1) opts <-list("MAX_BB_EVAL"=10000) params <- list() params$sum.log.density <- sum.log.density params$sum.log.density.gradient <- sum.log.density.gradient params$method <- method params$penalty <- penalty params$x <- x params$xnorm <- xnorm params$knots <- knots params$basis <- basis params$monotone <- monotone params$monotone.lb <- monotone.lb params$rank.xnorm <- rank.xnorm params$do.gradient <- do.gradient params$maxit <- maxit params$max.attempts <- max.attempts params$verbose <- verbose solution <- snomadr(eval.f=eval.f, n=2, x0=x0, bbin=bbin, bbout=bbout, lb=lb, ub=ub, nmulti=nmulti, print.output=FALSE, opts=opts, params=params) value.opt <- solution$objective d <- solution$solution[1] s <- solution$solution[2] length.x <- length(x) length.xnorm <- length(xnorm) complexity <- d+s par.init.out <- par.init(d,s,monotone,monotone.lb) par.init <- par.init.out$par.init par.upper <- par.init.out$par.upper par.lower <- par.init.out$par.lower Pnorm <- density.basis(x=x, xnorm=xnorm, degree=d, segments=s, basis=basis, knots=knots, monotone=monotone) P <- Pnorm[rank.xnorm,][1:length.x,] colSumsP <- colSums(P) Pint <- Pnorm[rank.xnorm,][(length.x+1):nrow(Pnorm),] xint <- xnorm[rank.xnorm][(length.x+1):nrow(Pnorm)] optim.out <- list() optim.out[[4]] <- 9999 optim.out$value <- -Inf m.attempts <- 0 while(tryCatch(suppressWarnings(optim.out <- optim(par=par.init, fn=sum.log.density, gr=if(do.gradient){sum.log.density.gradient}else{NULL}, upper=par.upper, lower=par.lower, method=method, penalty=penalty, P=P, colSumsP=colSumsP, Pint=Pint, length.x=length.x, xint=xint, complexity=complexity, control=list(fnscale=-1,maxit=maxit,if(verbose){trace=1}else{trace=0}))), error = function(e){return(optim.out)})[[4]]!=0 && m.attempts < max.attempts){ if(verbose && optim.out[[4]]!=0) { if(options('crs.messages')$crs.messages) { if(!is.null(optim.out$message)) cat("\n optim message = ",optim.out$message,sep="") cat("\n optim failed (degree = ",d,", segments = ",s,", convergence = ", optim.out[[4]],") re-running with new initial values",sep="") } } par.init.out <- par.init(d,s,monotone,monotone.lb) par.init <- par.init.out$par.init par.upper <- par.init.out$par.upper par.lower <- par.init.out$par.lower m.attempts <- m.attempts+1 } d.opt <- d s.opt <- s par.opt <- optim.out$par value.opt <- optim.out$value } if(options('crs.messages')$crs.messages) { cat("\r ") if(!(degree.min==degree.max) && (d.opt==degree.max)) warning(paste(" optimal degree equals search maximum (", d.opt,"): rerun with larger degree.max",sep="")) if(!(segments.min==segments.max) && (s.opt==segments.max)) warning(paste(" optimal segment equals search maximum (", s.opt,"): rerun with larger segments.max",sep="")) if(par.opt[1]>0|par.opt[length(par.opt)]>0) warning(" optim() delivered a positive weight for linear segment (supposed to be negative)") if(!monotone&&par.opt[1]<=monotone.lb) warning(paste(" optimal weight for left nonmonotone basis equals search minimum (",par.opt[1],"): rerun with smaller monotone.lb",sep="")) if(!monotone&&par.opt[length(par.opt)]<=monotone.lb) warning(paste(" optimal weight for right nonmonotone basis equals search minimum (",par.opt[length(par.opt)],"): rerun with smaller monotone.lb",sep="")) } if(exists.seed) assign(".Random.seed", save.seed, .GlobalEnv) return(list(degree=d.opt,segments=s.opt,beta=par.opt,fv=value.opt)) } summary.clsd <- function(object, ...) { cat("\nCategorical Logspline Density\n",sep="") cat(paste("\nModel penalty: ", format(object$penalty), sep="")) cat(paste("\nModel degree/segments: ", format(object$degree),"/",format(object$segments), sep="")) cat(paste("\nKnot type: ", format(object$knots), sep="")) cat(paste("\nBasis type: ",format(object$basis),sep="")) cat(paste("\nTraining observations: ", format(object$nobs), sep="")) cat(paste("\nLog-likelihood: ", format(object$logl), sep="")) cat(paste("\nNumber of multistarts: ", format(object$nmulti), sep="")) cat(paste("\nEstimation time: ", formatC(object$ptm[1],digits=1,format="f"), " seconds",sep="")) cat("\n\n") } print.clsd <- function(x,...) { summary.clsd(x) } plot.clsd <- function(x, er=TRUE, distribution=FALSE, derivative=FALSE, ylim, ylab, xlab, type, ...) { if(missing(xlab)) xlab <- "Data" if(missing(type)) type <- "l" if(!er) { order.x <- order(x$x) if(distribution){ y <- x$distribution[order.x] if(missing(ylab)) ylab <- "Distribution" if(missing(ylim)) ylim <- c(0,1) } if(!distribution&&!derivative) { y <- x$density[order.x] if(missing(ylab)) ylab <- "Density" if(missing(ylim)) ylim <- c(0,max(y)) } if(derivative) { y <- x$density.deriv[order.x] if(missing(ylab)) ylab <- "Density Derivative" if(missing(ylim)) ylim <- c(min(y),max(y)) } x <- x$x[order.x] } else { order.xer <- order(x$xer) if(distribution){ y <- x$distribution.er[order.xer] if(missing(ylab)) ylab <- "Distribution" if(missing(ylim)) ylim <- c(0,1) } if(!distribution&&!derivative) { y <- x$density.er[order.xer] if(missing(ylab)) ylab <- "Density" if(missing(ylim)) ylim <- c(0,max(y)) } if(derivative){ y <- x$density.deriv.er[order.xer] if(missing(ylab)) ylab <- "Density Derivative" if(missing(ylim)) ylim <- c(min(y),max(y)) } x <- x$xer[order.xer] } x <- plot(x, y, ylim=ylim, ylab=ylab, xlab=xlab, type=type, ...) } coef.clsd <- function(object, ...) { tc <- object$beta return(tc) } fitted.clsd <- function(object, ...){ object$density }
files_move <- function( path1, path2, file_sep="__", pattern=NULL, path2_name="__ARCH") { if ( missing(path2) ){ f1 <- list.files(path1, path2_name) path2 <- file.path(path1, f1) } files <- list.files( path1, "\\." ) if ( ! is.null( pattern) ){ files <- grep( pattern=pattern, x=files, value=TRUE) } NF <- length(files) if (NF > 1){ matr <- matrix( NA, nrow=NF, ncol=5) for (ff in 1:NF){ file_ff <- files[ff] res_ff <- filename_split( file_name=file_ff, file_sep=file_sep ) matr[ff,] <- unlist(res_ff) } matr <- as.data.frame(matr) colnames(matr) <- names(res_ff) matr$main_id <- match( matr$main, unique( matr$main) ) matr <- matr[ order( matr$main ), ] matr$eq <- c(0,matr$main[ - NF ] !=matr$main[-1]) t1 <- table( matr$main_id ) ind1 <- match( matr$main_id, names(t1)) matr$freq <- t1[ind1] for (ff in 2:NF){ if ( matr[ff,"main"]==matr[ ff -1, "main"] ){ file.rename( from=file.path( path1, matr[ff-1,"file_name"] ), to=file.path( path2, matr[ff-1,"file_name"] ) ) cat("*** Move ", paste0(matr[ff-1,"file_name"]), "\n" ) utils::flush.console() } } } }
LearnerRegrGlmnet = R6Class("LearnerRegrGlmnet", inherit = LearnerRegr, public = list( initialize = function() { ps = ps( alignment = p_fct(c("lambda", "fraction"), default = "lambda", tags = "train"), alpha = p_dbl(0, 1, default = 1, tags = "train"), big = p_dbl(default = 9.9e35, tags = "train"), devmax = p_dbl(0, 1, default = 0.999, tags = "train"), dfmax = p_int(0L, tags = "train"), eps = p_dbl(0, 1, default = 1.0e-6, tags = "train"), epsnr = p_dbl(0, 1, default = 1.0e-8, tags = "train"), exact = p_lgl(default = FALSE, tags = "predict"), exclude = p_int(1L, tags = "train"), exmx = p_dbl(default = 250.0, tags = "train"), family = p_fct(c("gaussian", "poisson"), default = "gaussian", tags = "train"), fdev = p_dbl(0, 1, default = 1.0e-5, tags = "train"), gamma = p_dbl(default = 1, tags = "train"), grouped = p_lgl(default = TRUE, tags = "train"), intercept = p_lgl(default = TRUE, tags = "train"), keep = p_lgl(default = FALSE, tags = "train"), lambda = p_uty(tags = "train"), lambda.min.ratio = p_dbl(0, 1, tags = "train"), lower.limits = p_uty(tags = "train"), maxit = p_int(1L, default = 100000L, tags = "train"), mnlam = p_int(1L, default = 5L, tags = "train"), mxit = p_int(1L, default = 100L, tags = "train"), mxitnr = p_int(1L, default = 25L, tags = "train"), newoffset = p_uty(tags = "predict"), nlambda = p_int(1L, default = 100L, tags = "train"), offset = p_uty(default = NULL, tags = "train"), parallel = p_lgl(default = FALSE, tags = "train"), penalty.factor = p_uty(tags = "train"), pmax = p_int(0L, tags = "train"), pmin = p_dbl(0, 1, default = 1.0e-9, tags = "train"), prec = p_dbl(default = 1e-10, tags = "train"), relax = p_lgl(default = FALSE, tags = "train"), s = p_dbl(0, default = 0.01, tags = "predict"), standardize = p_lgl(default = TRUE, tags = "train"), standardize.response = p_lgl(default = FALSE, tags = "train"), thresh = p_dbl(0, default = 1e-07, tags = "train"), trace.it = p_int(0, 1, default = 0, tags = "train"), type.gaussian = p_fct(c("covariance", "naive"), tags = "train"), type.logistic = p_fct(c("Newton", "modified.Newton"), tags = "train"), type.multinomial = p_fct(c("ungrouped", "grouped"), tags = "train"), upper.limits = p_uty(tags = "train") ) ps$add_dep("gamma", "relax", CondEqual$new(TRUE)) ps$add_dep("type.gaussian", "family", CondEqual$new("gaussian")) ps$values = list(family = "gaussian") super$initialize( id = "regr.glmnet", param_set = ps, feature_types = c("logical", "integer", "numeric"), properties = "weights", packages = c("mlr3learners", "glmnet"), man = "mlr3learners::mlr_learners_regr.glmnet" ) }, selected_features = function(lambda = NULL) { glmnet_selected_features(self, lambda) } ), private = list( .train = function(task) { data = as_numeric_matrix(task$data(cols = task$feature_names)) target = as_numeric_matrix(task$data(cols = task$target_names)) pv = self$param_set$get_values(tags = "train") if ("weights" %in% task$properties) { pv$weights = task$weights$weight } glmnet_invoke(data, target, pv) }, .predict = function(task) { newdata = as_numeric_matrix(ordered_features(task, self)) pv = self$param_set$get_values(tags = "predict") pv = rename(pv, "predict.gamma", "gamma") pv$s = glmnet_get_lambda(self, pv) response = invoke(predict, self$model, newx = newdata, type = "response", .args = pv) list(response = drop(response)) } ) )
"flood"
comm.sampling<-function(x,type=c("full","random"),size) { type <- match.arg(type) x2<-as.matrix(table(x[,"site"],x[,"species"])) if (type=="random") { if (size>=min(rowSums(x2))) warning("Sample size should be smaller than actual community size! Full sampling will be applied.") else x2<-vegan::rrarefy(x2,size) } return(x2) }
neptune_fetch <- function(x) { check_handler_or_run(x) x$fetch() }
fof_pc_real_time <- function(mfdobj_y_list, mfdobj_x_list, tot_variance_explained_x = 0.95, tot_variance_explained_y = 0.95, tot_variance_explained_res = 0.95, components_x = NULL, components_y = NULL, type_residuals = "standard", ncores = 1) { if (length(mfdobj_y_list) != length(mfdobj_x_list)) { stop("x and y lists must have the same length") } single_k <- function(ii) { fof_pc( mfdobj_y = mfdobj_y_list[[ii]], mfdobj_x = mfdobj_x_list[[ii]], tot_variance_explained_x = tot_variance_explained_x, tot_variance_explained_y = tot_variance_explained_y, tot_variance_explained_res = tot_variance_explained_res, components_x = components_x, components_y = components_y, type_residuals = type_residuals ) } if (ncores == 1) { mod_list <- lapply(seq_along(mfdobj_y_list), single_k) } else { if (.Platform$OS.type == "unix") { mod_list <- mclapply(seq_along(mfdobj_y_list), single_k, mc.cores = ncores) } else { cl <- makeCluster(ncores) clusterExport(cl, c("mfdobj_y_list", "mfdobj_x_list", "tot_variance_explained_x", "tot_variance_explained_y", "tot_variance_explained_res", "components_x", "components_y", "type_residuals", envir = environment())) mod_list <- parLapply(cl, seq_along(mfdobj_y_list), single_k) stopCluster(cl) } } names(mod_list) <- names(mfdobj_y_list) mod_list }
getPoly <- function(xdata = NULL, deg = 1, maxInteractDeg = deg, Xy = NULL, standardize = FALSE, noisy = TRUE, intercept = FALSE, returnDF = TRUE, modelFormula = NULL, retainedNames = NULL, ...) { if(sum(is.null(xdata) + is.null(Xy)) != 1) stop("please provide getPoly() xdata or Xy (but not both).") if (!is.null(xdata) && is.vector(xdata)) stop('xdata must be a matrix or data frame') W <- if(is.null(xdata)) Xy else xdata nX <- if(is.null(xdata)) ncol(Xy)-1 else ncol(xdata) if(noisy && !(is.matrix(W) || is.data.frame(W))){ cat('getPoly() expects a matrix or a data.frame.\n') cat('The input will be coerced to a data.frame \n') } W <- as.data.frame(W, stringsAsFactors=TRUE) namesW <- names(W) W <- complete(W, noisy=noisy) colnames(W) <- namesW if(standardize){ to_z <- which(unlist(lapply(W, is_continuous))) W[,to_z] <- scale(W[,to_z]) } RHS <- NULL if(is.null(modelFormula)){ x_cols <- 1:(ncol(W) - is.null(xdata)) y_name <- if(is.null(xdata)) colnames(Xy)[ncol(Xy)] else NULL remove(xdata) remove(Xy) W_distincts <- N_distinct(W) to_factor <- which((W_distincts == 2) | unlist(lapply(W, is.character))) for(i in to_factor) W[,i] <- as.factor(W[,i]) x_factors <- if(ncol(W) > 1) unlist(lapply(W[,x_cols], is.factor)) else is.factor(W[[1]]) P_factor <- sum(x_factors) factor_features <- c() for(i in which(x_factors)){ tmp <- paste(colnames(W)[i], "==", paste0("\'", levels(W[,i])[-1], "\'")) tmp <- paste0("(", tmp, ")") factor_features <- c(factor_features, tmp) } features <- factor_features P <- P_factor if(sum(x_factors) != ncol(W)){ cf <- colnames(W)[x_cols][!x_factors] P_continuous <- length(cf) P <- P_continuous + P_factor continuous_features <- c() for(i in 1:deg) continuous_features <- c(continuous_features, paste0("I(", cf, "^", i, ")")) features <- c(continuous_features, factor_features) } else cf <- NULL features <- get_interactions(features, maxInteractDeg, c(cf, names(x_factors[x_factors])), maxDeg = deg) if(noisy && (length(features) > nrow(W))) message("P > N. With polynomial terms and interactions, P is ", length(features), ".\n\n", sep="") RHS <- paste0("~", paste(features, collapse=" + ")) modelFormula <- as.formula(paste0(y_name, RHS)) } X <- model_matrix(modelFormula, W, intercept, noisy, ...) if (is.vector(X)) { nms <- names(X) X <- matrix(X,nrow=nrow(W)) colnames(X) <- nms } if(is.null(retainedNames)) retainedNames <- colnames(X) polyMat <- polyMatrix(xdata = X, modelFormula = modelFormula, XtestFormula = if(is.null(RHS)) modelFormula else as.formula(RHS), retainedNames = retainedNames) if(returnDF) return(polyDF(polyMat)) else return(polyMat) } gtPoly <- getPoly polyMatrix <- function(xdata, modelFormula, XtestFormula, retainedNames) { if(!is.matrix(xdata)){ xdata <- matrix(t(xdata), nrow=1) colnames(xdata) <- retainedNames } out <- list(xdata = xdata, modelFormula = modelFormula, XtestFormula = XtestFormula, retainedNames = retainedNames) class(out) <- "polyMatrix" return(out) } polyDF <- function(polyMat) { stopifnot(class(polyMat) == "polyMatrix") polyMat$xdata <- as.data.frame(polyMat$xdata, stringsAsFactors=polyMat$stringsAsFactors) if(length(polyMat$retainedNames) != length(colnames(polyMat$xdata))){ warning("xdata contains", length(colnames(polyMat$xdata)), "columns but retainedNames has", length(polyMat$retainedNames), "items") } class(polyMat) <- c("polyMatrix", "polyDataFrame") return(polyMat) } polyAllVsAll <- function(plm.xy, classes, stringsAsFactors=TRUE) { plm.xy <- as.data.frame(plm.xy, stringsAsFactors=TRUE) len <- length(classes) ft <- list() for (i in 1:len) { ft[[i]] <- list() for (j in 1:len) { if (i == j) next newxy <- plm.xy[plm.xy$y == classes[i] | plm.xy$y == classes[j],] newxy$y <- ifelse(newxy$y == classes[i], 1, 0) ft[[i]][[j]] <- glm(y~., family = binomial(link = "logit"), data = newxy) } } return(ft) } polyOneVsAll <- function(plm.xy, classes, cls=NULL) { plm.xy <- as.data.frame(plm.xy, stringsAsFactors=TRUE) ft <- list() predClassi <- function(i) { oneclass <- plm.xy[plm.xy$y == classes[i],] oneclass$y <- 1 allclass <- plm.xy[plm.xy$y != classes[i],] allclass$y <- 0 new_xy <- rbind(oneclass, allclass) glm(y~., family = binomial(link = "logit"), data = new_xy) } if (is.null(cls)) { for (i in 1:length(classes)) { ft[[i]] <- predClassi(i) } } else { clusterExport(cls,c('plm.xy','predClassi'),envir=environment()) ft <- clusterApply(cls,1:length(classes),predClassi) } return(ft) }
"permutation.test.discrete" <- function (x, y = NULL, scores, alternative = "greater", trials = 1000) { if (length(y)) { n <- length(y) if (length(x) != n) stop("x and y have different lengths") } else { if (ncol(x) != 2) stop("x does not have 2 columns and y is missing") y <- x[, 2] x <- x[, 1] n <- length(y) } x <- as.character(x) y <- as.character(y) if (length(alternative) != 1 || !is.character(alternative)) stop("alternative must be a single character string") altnum <- pmatch(alternative, c("greater", "less"), nomatch = NA) if (is.na(altnum)) stop("alternative must partially match 'greater' or 'less'") alternative <- c("greater", "less")[altnum] orig.tab <- table(x, y) otd <- dim(orig.tab) odnam <- dimnames(orig.tab) scnam <- dimnames(scores) if (!is.matrix(scores) || length(scnam) != 2 || !is.numeric(scores)) stop("scores must be a numeric matrix with dimnames") scd <- dim(scores) if (any(scd != otd) && any(rev(scd) != otd)) { stop(paste("scores is not the proper size, should be", otd[1], "by", otd[2])) } if (any(scd != otd)) { scores <- t(scores) scd <- dim(scores) scnam <- dimnames(scores) reverse <- TRUE } else { reverse <- FALSE } rownum <- match(scnam[[1]], odnam[[1]], nomatch = NA) if (any(is.na(rownum))) { if (reverse || otd[1] != otd[2]) stop("bad dimnames for scores") scores <- t(scores) scd <- dim(scores) scnam <- dimnames(scores) rownum <- match(scnam[[1]], odnam[[1]], nomatch = NA) if (any(is.na(rownum))) stop("bad dimnames for scores") } colnum <- match(scnam[[2]], odnam[[2]], nomatch = NA) if (any(is.na(colnum))) stop("bad dimnames for scores") scores <- scores[rownum, colnum] if(!exists(".Random.seed")) runif(1) ranseed <- .Random.seed orig.score <- sum(orig.tab * scores) perm.scores <- numeric(trials) for (i in 1:trials) { perm.scores[i] <- sum(table(x, sample(y)) * scores) } if (alternative == "greater") { extreme <- sum(perm.scores >= orig.score) } else { extreme <- sum(perm.scores <= orig.score) } ans <- list(original.score = orig.score, perm.scores = perm.scores, stats = c(nobs = n, trials = trials, extreme = extreme), alternative = alternative, random.seed = ranseed, call = match.call()) class(ans) <- "permtstBurSt" ans }
showGen <- function( data.in, design = "triad", n = 5, from, to, sex, markers = 1:5 ){ if( !is( data.in, "haplin.data" ) || !all( names( data.in ) == .haplinEnv$.haplin.data.names ) ){ stop( "The input data is not in the correct format!", call. = FALSE ) } cov.data <- data.in$cov.data gen.data <- data.in$gen.data n.given <- FALSE from.given <- FALSE which.rows.show <- TRUE if( !missing( sex ) ){ if( is.null( cov.data ) ){ stop( "There is no phenotypic/covariate information in your data!", call. = FALSE ) } if( !( "sex" %in% colnames( cov.data ) ) ){ stop( "There is no 'sex' column in the dataset!" ) } if( !( sex %in% as.numeric( unique( cov.data[ ,"sex" ] ) ) ) ){ stop( paste( "Wrong sex chosen - 'sex' column has the following categories:", paste( sort( unique( cov.data[ ,"sex" ] ) ), collapse = "," ) ), call. = FALSE ) } which.rows.show <- as.numeric( cov.data[ ,"sex" ] ) == sex } else { if( !missing( n ) ){ n.given <- TRUE if( is.numeric( n ) ){ if( n < 1 | n > nrow( gen.data[[ 1 ]] ) ){ stop( "Your specification of 'n' (number of rows to display) was wrong!", call. = FALSE ) } } else if( n != "all" ){ stop( "Could not understand the choice of 'n'", call. = FALSE ) } else { n <- nrow( gen.data[[ 1 ]] ) } } if( !missing( from ) ){ from.given <- TRUE if( !is.numeric( from ) ){ stop( "'From' should be numeric!", call. = FALSE ) } } if( !missing( to ) ){ if( !is.numeric( to ) ){ stop( "'To' should be numeric!", call. = FALSE ) } if( n.given & from.given ){ warning( "You specified too many parameters! Chosing only 'from' and 'to'." ) } else if( n.given ) { from <- to - n + 1 } else if( !from.given ) { from <- 1 } } else if( n.given & from.given ) { to <- from + n - 1 } else if( from.given ) { to <- nrow( gen.data[[ 1 ]] ) } else if( n.given ) { from <- 1 to <- from + n - 1 } else { from <- 1 to <- min( n, nrow( gen.data[[ 1 ]] ) ) } if( from < 1 | to > nrow( gen.data[[ 1 ]] ) | from > to ){ stop( paste0( "Wrong specification of 'from' (", from ,") and 'to' (", to, ")!" ), call. = FALSE ) } which.rows.show <- from:to } format <- data.in$aux$info$filespecs$format family <- "c" ncols.per.marker <- 2 if( design %in% c( "triad", "cc.triad" ) & format == "haplin" ){ family <- "mfc" ncols.per.marker <- 6 } max.markers <- nsnps( data.in ) all.markers <- max.markers*ncols.per.marker if( is.numeric( markers ) ){ markers.by.name <- FALSE if( max( markers ) > max.markers ){ warning( "It appears that your data has less markers (", max.markers,") than requested (", max( markers ), "), adjusting accordingly." ) orig.markers <- markers which.markers.higher.max <- orig.markers > max.markers markers <- orig.markers[ !which.markers.higher.max ] } markers <- f.sel.markers( n.vars = 0, markers = markers, family = family, split = TRUE, ncols = all.markers ) } else if( length( markers ) == 1 & markers == "all" ){ markers.by.name <- FALSE if( length( gen.data ) > 1 ){ answer <- readline( paste( "You are requesting a lot of data. Are you sure? (y/n)" ) ) if( tolower( answer ) != "y" ){ stop( "Stopped as per request.", call. = FALSE ) } } markers <- 1:all.markers } else { markers.by.name <- TRUE stop( "Not implemented yet!" ) } data.out <- f.get.gen.data.cols( gen.data, cols = markers, by.colname = markers.by.name ) data.out <- as.ff( data.out[ which.rows.show, ], vmode = .haplinEnv$.vmode.gen.data ) return( data.out ) }
print.ntestRes <- function(x, ...){ cat("Pearson's Chi-squared test for normality of residuals\n") t <- as.data.frame(cbind(x$p.value.res1,x$p.value.res2)) rownames(t) <- "p.value" colnames(t) <- c("time = 1", "time = 2") print(t) }
imganiso2D <- function(x,satexp=.25,g=3,rho=0){ if(class(x)=="adimpro") x <- tensor2D(x,g=g,rho=rho) x[c(1,3),,] <- x[c(1,3),,]*(1+1.e-8)+rho p <- x[1,,]+x[3,,] q <- x[1,,]*x[3,,]-x[2,,]^2 z <- p^2/4-q z[z<0] <- 0 ew <- p/2 + sqrt(z) ew2 <- p/2 - sqrt(z) theta <- acos(x[2,,]/sqrt((ew-x[1,,])^2+x[2,,]^2))/pi theta[is.na(theta)] <- 0 img <- array(0,c(dim(x)[2:3],3)) img[,,1] <- theta img[,,2] <- (ew/max(ew))^satexp img[,,3] <- log(ew/ew2) invisible(make.image(img,xmode="hsi")) } tensor2D <- function(x,g=0,rho=0){ if(class(x)=="adimpro") { x <- extract.image(x) } storage.mode(x) <- "numeric" ddim <- dim(x) n1 <- ddim[1] n2 <- ddim[2] if(length(ddim)==2){ dx <- rbind(x,x[n1,])-rbind(x[1,],x) dy <- cbind(x,x[,n2])-cbind(x[,1],x) dxx <- (dx[-1,]^2+dx[-n1-1,]^2)/2 dyy <- (dy[,-1]^2+dy[,-n2-1]^2)/2 dxy <- (dx[-1,]*dy[,-1]+dx[-n1-1,]*dy[,-1]+dx[-1,]*dy[,-n2-1]+dx[-n1,]*dy[,-n2-1])/4 z<-aperm(array(c(dxx,dxy,dyy),c(ddim,3)),c(3,1,2)) } else { z <- array(0,c(n1,n2,3)) for(i in 1:3) { dx <- rbind(x[,,i],x[n1,,i])-rbind(x[1,,i],x[,,i]) dy <- cbind(x[,,i],x[,n2,i])-cbind(x[,1,i],x[,,i]) dxx <- (dx[-1,]^2+dx[-n1-1,]^2)/2 dyy <- (dy[,-1]^2+dy[,-n2-1]^2)/2 dxy <- (dx[-1,]*dy[,-1]+dx[-n1-1,]*dy[,-1]+dx[-1,]*dy[,-n2-1]+dx[-n1,]*dy[,-n2-1])/4 z <- z+c(dxx,dxy,dyy) } z <- aperm(z/3,c(3,1,2)) } if(g>0){ z <- array(.Fortran(C_sm2dtens, as.double(z), as.integer(n1), as.integer(n2), as.double(g), as.double(rho), zhat=double(3*n1*n2), PACKAGE="adimpro")$zhat,dim(z)) z[is.na(z)] <- 0 } z } awsaniso <- function (object, hmax=4, g=3, rho=0, aws=TRUE, varmodel=NULL, ladjust=1.0, xind = NULL, yind = NULL, wghts=c(1,1,1,1), scorr=TRUE, lkern="Triangle", demo=FALSE, graph=FALSE, satexp=0.25, max.pixel=4.e2,clip=FALSE,compress=TRUE) { IQRdiff <- function(data) IQR(diff(data))/1.908 if(!check.adimpro(object)) { cat(" Consistency check for argument object failed (see warnings). object is returned.\"n") return(invisible(object)) } object <- switch(object$type, "hsi" = hsi2rgb(object), "yuv" = yuv2rgb(object), "yiq" = yiq2rgb(object), "xyz" = xyz2rgb(object), object) if(object$type=="RAW") stop("RAW-image, will be implemented in function awsraw later ") if(!is.null(object$call)) { warning("argument object is result of awsimage or awspimage. You should know what you do.") } args <- match.call() if(clip) { object <- clip.image(object,xind,yind,compress=FALSE) xind <- NULL yind <- NULL } if(object$compressed) object <- decompress.image(object) if(is.null(varmodel)) { varmodel <- if(object$gamma) "Constant" else "Linear" } bcf <- c(-.4724,1.1969,.22167,.48691,.13731,-1.0648) estvar <- toupper(varmodel) %in% c("CONSTANT","LINEAR") hpre <- 2. if(estvar) { dlw<-(2*trunc(hpre)+1) nvarpar <- switch(varmodel,Constant=1,Linear=2,1) } dimg <- dimg0 <- dim(object$img) imgtype <- object$type dv <- switch(imgtype,rgb=dimg[3],greyscale=1) if(length(wghts)<dv) wghts <- c(wghts,rep(1,dv-length(wghts))) else wghts <- pmin(.1,wghts) wghts <- switch(imgtype, greyscale=1, rgb = wghts[1:dv]) spcorr <- matrix(0,2,dv) h0 <- c(0,0) if(is.null(xind)) xind <- 1:dimg[1] if(is.null(yind)) yind <- 1:dimg[2] n1 <- length(xind) n2 <- length(yind) n <- n1*n2 dimg <- switch(imgtype,greyscale=c(n1,n2),rgb=c(n1,n2,dv)) ladjust <- max(1,ladjust) lkern <- switch(lkern, Triangle=1, Quadratic=2, Cubic=3, Plateau=4, 1) if (is.null(hmax)) hmax <- 4 wghts <- wghts/sum(wghts) dgf <- sum(wghts)^2/sum(wghts^2) if (aws) lambda <- ladjust*switch(imgtype, "greyscale" = 8.1, "rgb" = 4.4, 4.4) else lambda <- 1e50 sigma2 <- pmax(0.01,switch(imgtype, "greyscale" = IQRdiff(object$img)^2, "rgb" = apply(object$img,3,IQRdiff)^2, IQRdiff(object$img)^2)) cat("Estimated variance (assuming independence): ", signif(sigma2/65635^2,4),"\n") if (!estvar) { if (length(sigma2)==1) { if(dv>1) sigma2 <- rep(sigma2,1) lambda <- lambda*sigma2 } else if (length(sigma2)==dv) { wghts <- wghts[1:dv]/sigma2 } } lambda <- 2*lambda spmin <- 0 spmax <- 1 maxvol <- getvofh2(hmax,lkern) kstar <- as.integer(log(maxvol)/log(1.25)) if(aws){ k <- if(estvar) 6 else 1 } else { cat("No adaptation method specified. Calculate kernel estimate with bandwidth hmax.\n") k <- kstar } if (demo && !graph) graph <- TRUE if(graph){ oldpar <- par(mfrow=c(2,2),mar=c(1,1,3,.25),mgp=c(2,1,0)) on.exit(par(oldpar)) graphobj0 <- object[-(1:length(object))[names(object)=="img"]] graphobj0$dim <- c(n1,n2) if(!is.null(.Options$adimpro.xsize)) max.x <- trunc(.Options$adimpro.xsize/3.2) else max.x <- 600 if(!is.null(.Options$adimpro.ysize)) max.y <- trunc(.Options$adimpro.ysize/1.2) else max.y <- 900 } bi <- rep(1,n) theta <- switch(imgtype,greyscale=object$img[xind,yind],rgb=object$img[xind,yind,]) if(estvar){ coef <- matrix(0,nvarpar,dv) coef[1,] <- sigma2 vobj <- list(coef=coef,meanvar=sigma2) imgq995 <- switch(imgtype,greyscale=quantile(object$img[xind,yind],.995), rgb=apply(object$img[xind,yind,],3,quantile,.995)) } if(scorr){ twohp1 <- 2*trunc(hpre)+1 pretheta <- .Fortran(C_awsimg, as.integer(switch(imgtype, greyscale=object$img[xind,yind], rgb=object$img[xind,yind,])), as.integer(n1), as.integer(n2), as.integer(dv), as.double(hpre), theta=integer(prod(dimg)), double(n1*n2), as.integer(lkern), double(twohp1*twohp1), double(dv), PACKAGE="adimpro")$theta dim(pretheta) <- dimg spchcorr <- .Fortran(C_estcorr, as.double(switch(imgtype, greyscale=object$img[xind,yind], rgb=object$img[xind,yind,])-pretheta), as.integer(n1), as.integer(n2), as.integer(dv), scorr=double(2*dv), chcorr=double(max(1,dv*(dv-1)/2)), PACKAGE="adimpro")[c("scorr","chcorr")] spcorr <- spchcorr$scorr srh <- sqrt(hpre) spcorr <- matrix(pmin(.9,spcorr+ bcf[1]/srh+bcf[2]/hpre+ bcf[3]*spcorr/srh+bcf[4]*spcorr/hpre+ bcf[5]*spcorr^2/srh+bcf[6]*spcorr^2/hpre),2,dv) chcorr <- spchcorr$chcorr for(i in 1:dv) cat("Estimated spatial correlation in channel ",i,":",signif(spcorr[,i],2),"\n") if(dv>1) cat("Estimated correlation between channels (1,2):",signif(chcorr[1],2), " (1,3):",signif(chcorr[2],2), " (2,3):",signif(chcorr[3],2),"\n") } else { spcorr <- matrix(0,2,dv) chcorr <- numeric(max(1,dv*(dv-1)/2)) } lambda0 <- 1e50 total <- cumsum(1.25^(1:kstar))/sum(1.25^(1:kstar)) while (k<=kstar) { hakt0 <- geth2(1,10,lkern,1.25^(k-1),1e-4) hakt <- geth2(1,10,lkern,1.25^k,1e-4) twohp1 <- 2*trunc(hakt)+1 spcorr <- pmax(apply(spcorr,1,mean),0) if(any(spcorr>0)) { h0<-numeric(length(spcorr)) for(i in 1:length(h0)) h0[i]<-geth.gauss(spcorr[i]) if(length(h0)<2) h0<-rep(h0[1],2) } if (any(spcorr>0)) { lcorr <- Spatialvar.gauss(hakt0,h0)/ Spatialvar.gauss(h0,1e-5)/Spatialvar.gauss(hakt0,1e-5) lambda0 <-lambda0*lcorr if(varmodel=="None") lambda0 <- lambda0*Varcor.gauss(h0) } if(dv==1) dim(theta) <- c(n1,n2) else dim(theta) <- c(n1,n2,dv) anisoimg <- tensor2D(theta,g=g,rho=max(rho,1e-6)*mean(vobj$meanvar)/bi) anisoimg[1,,] <- anisoimg[1,,]+max(rho,1e-6)*mean(vobj$meanvar)/bi anisoimg[3,,] <- anisoimg[3,,]+max(rho,1e-6)*mean(vobj$meanvar)/bi hakt0 <- hakt if(estvar){ varcase <- 1 zobj <- .Fortran(C_aniawsv, as.integer(switch(imgtype, greyscale=object$img[xind,yind], rgb=object$img[xind,yind,])), as.integer(n1), as.integer(n2), as.integer(dv), as.double(anisoimg), as.double(vobj$coef), as.integer(nvarpar), as.double(vobj$meanvar), as.double(chcorr), hakt=as.double(hakt), as.double(lambda0), as.integer(theta), bi=as.double(bi), theta=integer(prod(dimg)), as.integer(lkern), as.integer(1), as.double(spmin), as.double(spmax), as.double(sqrt(wghts)), double(dv), PACKAGE="adimpro")[c("bi","theta","hakt")] } else { varcase <- 3 zobj <- .Fortran(C_aniawsim, as.integer(switch(imgtype, greyscale=object$img[xind,yind], rgb=object$img[xind,yind,])), as.integer(n1), as.integer(n2), as.integer(dv), as.double(anisoimg), hakt=as.double(hakt), as.double(lambda0), as.integer(theta), bi=as.double(bi), theta=integer(prod(dimg)), as.integer(lkern), as.integer(1), as.double(spmin), as.double(spmax), as.double(wghts), double(dv), PACKAGE="adimpro")[c("bi","theta","hakt")] } theta <- zobj$theta bi <- zobj$bi rm(zobj) gc() dim(bi) <- dimg[1:2] if (graph) { graphobj <- graphobj0 class(graphobj) <- "adimpro" graphobj$img <- switch(imgtype, greyscale=object$img[xind,yind], rgb=object$img[xind,yind,]) show.image(graphobj,max.x=max.x,max.y=max.y,xaxt="n",yaxt="n") title("Observed Image") graphobj$img <- array(as.integer(theta),dimg) show.image(graphobj,max.x=max.x,max.y=max.y,xaxt="n",yaxt="n") title(paste("Reconstruction h=",signif(hakt,3))) show.image(imganiso2D(anisoimg,satexp=satexp),max.x=max.x,max.y=max.y,xaxt="n",yaxt="n") title(paste("Estimated anisotropy g=",signif(g,3))) graphobj$img <- matrix(as.integer(65534*bi/max(bi)),n1,n2) graphobj$type <- "greyscale" graphobj$gamma <- FALSE show.image(graphobj,max.x=max.x,max.y=max.y,xaxt="n",yaxt="n") title(paste("Adaptation (rel. weights):",signif(mean(bi)/max(bi),3))) rm(graphobj) gc() } cat("Bandwidth",signif(hakt,3)," Progress",signif(total[k],2)*100,"% \n") if (scorr) { if(hakt > hpre){ spchcorr <- .Fortran(C_estcorr, as.double(switch(imgtype, greyscale=object$img[xind,yind], rgb=object$img[xind,yind,]) - theta), as.integer(n1), as.integer(n2), as.integer(dv), scorr=double(2*dv), chcorr=double(max(1,dv*(dv-1)/2)), PACKAGE="adimpro")[c("scorr","chcorr")] spcorr <- spchcorr$scorr srh <- sqrt(hakt) spcorr <- matrix(pmin(.9,spcorr+ bcf[1]/srh+bcf[2]/hakt+ bcf[3]*spcorr/srh+bcf[4]*spcorr/hakt+ bcf[5]*spcorr^2/srh+bcf[6]*spcorr^2/hakt),2,dv) chcorr <- spchcorr$chcorr for(i in 1:dv) cat("Estimated spatial correlation in channel ",i,":",signif(spcorr[,i],2),"\n") if(dv>1) cat("Estimated correlation between channels (1,2):",signif(chcorr[1],2), " (1,3):",signif(chcorr[2],2), " (2,3):",signif(chcorr[3],2),"\n") } else { spcorr <- matrix(pmin(.9,spchcorr$scorr+ bcf[1]/srh+bcf[2]/hpre+ bcf[3]*spchcorr$scorr/srh+bcf[4]*spchcorr$scorr/hpre+ bcf[5]*spchcorr$scorr^2/srh+bcf[6]*spchcorr$scorr^2/hpre),2,dv) chcorr <- spchcorr$chcorr } } else { spcorr <- matrix(0,2,dv) chcorr <- numeric(max(1,dv*(dv-1)/2)) } if (estvar) { vobj <- switch(toupper(varmodel), CONSTANT=.Fortran(C_esigmac, as.integer(switch(imgtype, greyscale=object$img[xind,yind], rgb=object$img[xind,yind,])), as.integer(n1*n2), as.integer(dv), as.integer(theta), as.double(bi), as.integer(imgq995), coef=double(nvarpar*dv), meanvar=double(dv), PACKAGE="adimpro")[c("coef","meanvar")], LINEAR=.Fortran(C_esigmac, as.integer(switch(imgtype, greyscale=object$img[xind,yind], rgb=object$img[xind,yind,])), as.integer(n1*n2), as.integer(dv), as.integer(theta), as.double(bi), as.integer(imgq995), coef=double(nvarpar*dv), meanvar=double(dv), PACKAGE="adimpro")[c("coef","meanvar")] ) dim(vobj$coef) <- c(nvarpar,dv) for(i in 1:dv){ if(any(spcorr[,i]>.1) & vobj$meanvar[i]<sigma2[i]) { vobj$coef[,i] <- vobj$coef[,i]*sigma2[i]/vobj$meanvar[i] vobj$meanvar[i] <- sigma2[i] } } cat("Estimated mean variance",signif(vobj$meanvar/65635^2,3),"\n") } k <- k + 1 if (demo) readline("Press return") lambda0 <- lambda*ladjust } if(graph) par(oldpar) if(imgtype=="rgb") { object$img[xind,yind,] <- theta } else if(imgtype=="greyscale") { object$img[xind,yind] <- theta } ni <- array(1,dimg0[1:2]) ni[xind,yind] <- bi object$ni <- ni object$ni0 <- max(ni) object$hmax <- hakt object$call <- args if(estvar) { if(varmodel=="Linear") { vobj$coef[1,] <- vobj$coef[1,]/65535^2 vobj$coef[2,] <- vobj$coef[2,]/65535 } else vobj$coef <- vobj$coef/65535^2 object$varcoef <- vobj$coef object$wghts <- vobj$wghts } if(scorr) { object$scorr <- spcorr object$chcorr <- chcorr } invisible(if(compress) compress.image(object) else object) }
'dse06d'
coxDT = function(formula,L,R,data,subset,time.var=FALSE,subject=NULL,B.SE.np=200,CI.boot=FALSE,B.CI.boot=2000,pvalue.boot=FALSE, B.pvalue.boot=500,B.pvalue.se.boot=100,trunc.weight=100,print.weights=FALSE,error=10^-6,n.iter=1000) { if(missing(data)==TRUE) stop("Must specify data fame in 'data =' statement"); set.seed(1312018) data=data[subset,] nrows.data=dim(data)[1]; data=na.omit(data); nrows.data.omit=dim(data)[1]; mf = model.frame(formula=formula,data=data) X=model.matrix(attr(mf,"terms"),data=mf)[,-1] p=1; n=length(X); if(length(dim(X))>0) {p=dim(X)[2]; n=dim(X)[1]} Y=as.numeric(model.response(mf))[1:n]; L=deparse(substitute(L)); R=deparse(substitute(R)); formula.temp=paste(L,R,sep="~") mf.temp=model.frame(formula=formula.temp,data=data) obs.data=sapply(rownames(mf),rownames(mf.temp),FUN=function(x,y) which(x==y)) L=mf.temp[obs.data,1]; R=mf.temp[obs.data,2]; P.obs.y.np=cdfDT(Y,L,R,error,n.iter,display=FALSE)$P.K weights.np=1/P.obs.y.np weights.np[which(weights.np>trunc.weight)]=trunc.weight P.obs.NP=n*(sum(1/P.obs.y.np))^(-1) data.new=data.frame(data,weights.np) beta.np=coxph(formula,data=data.new,weights=weights.np)$coefficients if(time.var==TRUE) { subject=deparse(substitute(subject)) formula.temp2=paste(subject,subject,sep="~"); subjects=model.response(model.frame(formula.temp2,data=data)); n.subject=length(unique(subjects)); } B=B.SE.np if(CI.boot==TRUE) B=max(B.SE.np,B.CI.boot) beta.boot.np=matrix(0,nrow=B,ncol=p) for(b in 1:B) { repeat{ if(time.var==FALSE) {temp.sample=sort(sample(n,replace=TRUE))}; if(time.var==TRUE) { temp.obs=sort(sample(n.subject,replace=TRUE)) temp.sample=unlist(sapply(temp.obs,subjects,FUN=function(x,y) which(x==y))) } Y.temp=Y[temp.sample]; L.temp=L[temp.sample]; R.temp=R[temp.sample]; if(p==1) X.temp=X[temp.sample]; if(p>=2) X.temp=X[temp.sample,]; out.temp=cdfDT(Y.temp,L.temp,R.temp,error,n.iter,display=FALSE) if(out.temp$max.iter_reached==0) {break} } P.obs.NP.temp=out.temp$P.K weights.np.temp=1/P.obs.NP.temp weights.np.temp[which(weights.np.temp>trunc.weight)]=trunc.weight data.temp=data.frame(data[temp.sample,],weights.np.temp) beta.boot.np[b,]=coxph(formula,data=data.temp,weights=weights.np.temp)$coefficients } se.beta.np=apply(beta.boot.np,2,sd); if(CI.boot==FALSE) { CI.lower=beta.np-1.96*se.beta.np; CI.upper=beta.np+1.96*se.beta.np; CI.beta.np=round(cbind(CI.lower,CI.upper),3) } if(pvalue.boot==FALSE) { Test.statistic=(beta.np/se.beta.np)^2; p.value=round(2*(1-pnorm(abs(beta.np/se.beta.np))),4) } if(CI.boot==TRUE) { CI.beta.np=matrix(0,nrow=p,ncol=2) for(k in 1:p) CI.beta.np[k,]=round(c(quantile(beta.boot.np[,k],seq(0,1,0.025))[2],quantile(beta.boot.np[,k],seq(0,1,0.025))[40]),3) } if(pvalue.boot==TRUE) { B1=B.pvalue.boot; B2=B.pvalue.se.boot; beta.boot.np1=matrix(0,nrow=B1,ncol=p); beta.boot.np2=matrix(0,nrow=B2,ncol=p); beta.boot.np.sd1=matrix(0,nrow=B1,ncol=p) for(b1 in 1:B1) { repeat{ if(time.var==FALSE) {temp.sample1=sort(sample(n,replace=TRUE))}; if(time.var==TRUE) { temp.obs1=sort(sample(n.subject,replace=TRUE)) temp.sample1=unlist(sapply(temp.obs1,subjects,FUN=function(x,y) which(x==y))) } Y.temp1=Y[temp.sample1]; L.temp1=L[temp.sample1]; R.temp1=R[temp.sample1]; if(p==1) X.temp1=X[temp.sample1]; if(p>=2) X.temp1=X[temp.sample1,]; out.temp1=cdfDT(Y.temp1,L.temp1,R.temp1,error,n.iter,display=FALSE) if(out.temp1$max.iter_reached==0) {break} } P.obs.NP.temp1=out.temp1$P.K weights.np.temp1=1/P.obs.NP.temp1 weights.np.temp1[which(weights.np.temp1>trunc.weight)]=trunc.weight data.temp1=data.frame(data[temp.sample1,],weights.np.temp1) beta.boot.np1[b1,]=coxph(formula,data=data.temp1,weights=weights.np.temp1)$coefficients for(b2 in 1:B2) { repeat{ if(time.var==FALSE) {temp.sample2=sort(sample(temp.sample1,replace=TRUE))}; if(time.var==TRUE) { temp.obs2=sort(sample(temp.obs1,replace=TRUE)) temp.sample2=unlist(sapply(temp.obs2,subjects,FUN=function(x,y) which(x==y))) } Y.temp2=Y[temp.sample2]; L.temp2=L[temp.sample2]; R.temp2=R[temp.sample2]; if(p==1) X.temp2=X[temp.sample2]; if(p>=2) X.temp2=X[temp.sample2,]; out.temp2=cdfDT(Y.temp2,L.temp2,R.temp2,error,n.iter,display=FALSE) if(out.temp2$max.iter_reached==0) {break} } P.obs.NP.temp2=out.temp2$P.K weights.np.temp2=1/P.obs.NP.temp2 weights.np.temp2[which(weights.np.temp2>trunc.weight)]=trunc.weight data.temp2=data.frame(data[temp.sample2,],weights.np.temp2) beta.boot.np2[b2,]=coxph(formula,data=data.temp2,weights=weights.np.temp2)$coefficients } beta.boot.np.sd1[b1,]=apply(beta.boot.np2,2,"sd") } test_statistic.beta.np=numeric(p) test_statistic.beta.np.boot=matrix(0,nrow=B1,ncol=p) p.value=numeric(p) for(k in 1:p) { test_statistic.beta.np[k]=(beta.np[k]/se.beta.np[k])^2 test_statistic.beta.np.boot[,k]=((beta.boot.np1[,k]-beta.np[k])/beta.boot.np.sd1[,k])^2 p.value[k]=round(length(which(test_statistic.beta.np.boot[,k]>test_statistic.beta.np[k]))/B1,4) } Test.statistic=test_statistic.beta.np } beta.np=round(beta.np,4); se.beta.np=round(se.beta.np,4); Test.statistic=round(Test.statistic,2) p.value[which(p.value==0)]="<.0005" results.beta=noquote(cbind(beta.np,se.beta.np,CI.beta.np,Test.statistic,p.value)) rownames(results.beta)=colnames(X); colnames(results.beta)=c("Estimate","SE","CI.lower","CI.upper","Wald statistic","p-value") weights="print option not requested"; if(print.weights==TRUE) weights=weights.np; cat("number of observations read:", nrows.data, "\n") cat("number of observations used:", nrows.data.omit, "\n\n") if((CI.boot==TRUE)&(pvalue.boot==FALSE)) return(list(results.beta=results.beta,CI="Bootstrap",p.value="Normal approximation",weights=weights)); if((CI.boot==FALSE)&(pvalue.boot==TRUE)) return(list(results.beta=results.beta,CI="Normal approximation",p.value="Bootstrap",weights=weights)); if((CI.boot==TRUE)&(pvalue.boot==TRUE)) return(list(results.beta=results.beta,CI="Bootstrap",p.value="Bootstrap",weights=weights)); if((CI.boot==FALSE)&(pvalue.boot==FALSE)) return(list(results.beta=results.beta,CI="Normal approximation",p.value="Normal approximation",weights=weights)); }
identifyTheEquivalent.glmm = function(queues, target, reps, group, dataset, cvar, z, test, wei, threshold, univariateModels, pvalues, hash, stat_hash, pvalue_hash, slopes) { z = t(z); for(i in 1:ncol(z)) { w = z[, i]; w = t(t(w)); zPrime = c(setdiff(z, w), cvar); cur_results = test(target, reps, group, dataset, w, zPrime, wei = wei, univariateModels, hash = hash, stat_hash, pvalue_hash, slopes = slopes); if ( cur_results$pvalue > threshold ) { queues[[w]] = as.matrix( c(queues[[w]], queues[[cvar]]) ); break; } } return(queues); }
lmt.I <- function(fcobj.0, fcobj.a, X.gbd, PV.gbd, tau = 0.5, n.mc.E.delta = 1000, n.mc.E.chi2 = 1000, verbose = FALSE){ if(class(fcobj.0) != "fclust" || class(fcobj.a) != "fclust"){ stop("fcobj.0 and fcobj.a should be both in \"fclust\" class.") } if(fcobj.0$param$K == fcobj.a$param$K){ stop("fcobj.0 and fcobj.a should have different numbers of clusters.") } set.global(X.gbd, PV.gbd) x <- list(X.gbd = X.gbd, PV.gbd = PV.gbd) k.0 <- fcobj.0$param$K k.a <- fcobj.a$param$K ll.0 <- fcobj.0$param$logL ll.a <- fcobj.a$param$logL delta.hat <- fcobj.a$param$logL - fcobj.0$param$logL E.delta <- get.E.delta.I(x, fcobj.0, fcobj.a, tau = tau, n.mc = n.mc.E.delta) E.chi2.0 <- get.E.chi2.I(x, fcobj.0, fcobj.a, "0", tau = tau, n.mc = n.mc.E.chi2, verbose = verbose) E.chi2.a <- get.E.chi2.I(x, fcobj.0, fcobj.a, "a", tau = tau, n.mc = n.mc.E.chi2, verbose = verbose) T <- 2 * (delta.hat - E.delta) pv.0 <- pchisq.my(T, E.chi2.0[1], E.chi2.0[2], lower.tail = FALSE) pv.a <- pchisq.my(T, E.chi2.a[1], E.chi2.a[2], lower.tail = FALSE) pv <- pv.0 * tau + pv.a * (1 - tau) ret <- list(K.0 = k.0, K.a = k.a, ll.0 = ll.0, ll.a = ll.a, delta.hat = delta.hat, E.delta = E.delta, E.chi2.0 = E.chi2.0, E.chi2.a = E.chi2.a, T = T, pv.0 = pv.0, pv.a = pv.a, pv = pv) class(ret) <- "lmt.I" ret } print.lmt.I <- function(x, digits = max(4, getOption("digits") - 3), ...){ K.0 <- x$K.0 K.a <- x$K.a ll.0 <- x$ll.0 ll.a <- x$ll.a delta.hat <- x$delta.hat E.delta <- x$E.delta E.chi2.0 <- x$E.chi2.0 E.chi2.a <- x$E.chi2.a T <- x$T pv.0 <- x$pv.0 pv.a <- x$pv.a pv <- x$pv cat("- H.0: K = ", K.0, " vs H.a: K = ", K.a, "\n", " ll.0 = ", ll.0, ", ll.a = ", ll.a, "\n", " df.0 = ", E.chi2.0[1], ", nc.0 = ", E.chi2.0[2], ", df.a = ", E.chi2.a[1], ", nc.a = ", E.chi2.a[2], "\n", " delta.hat = ", delta.hat, ", E.delta = ", E.delta, ", T = ", T, "\n", " pv.0 = ", pv.0, ", pv.a = ", pv.a, " pv = ", pv, "\n", sep = "") invisible() }
par(xaxt = "n", yaxt = "n", mar = c(2, 0.1, 3, 0.1)) y = seq(2 * pi, 0, length = 150) x = sin(y) plot(x, y, type = "n", xlim = c(-1.3, 1.3), ylim = c(-0.93, 7.21), xlab = "", ylab = "", main = "IN THE ORBIT OF STATISTICS", asp = 1 ) rx = seq(-2, 2, length = 300) ry = dnorm(rx, 0, 0.2) + y[75] rty = ry - y[75] agl = pi / 4 + ifelse(rty / rx > 0, atan(rty / rx), atan(rty / rx) + pi) r = sqrt(rx^2 + rty^2) rtx = r * cos(agl) rty = r * sin(agl) + y[75] lines(rtx, rty) segments(-0.45, y[75] - 0.45, 0.45, y[75] + 0.45, col = "white", lwd = 2) q95 = qnorm(0.025, 0, 0.2) d95 = dnorm(q95, 0, 0.2) rg = rx > q95 & rx < -q95 polygon(c(rtx[rg][1], rtx[rg], rtx[rg][length(rg)]), c(rty[rg][1], rty[rg], rty[rg][length(rg)]), col = "lavender" ) radius = ifelse(0.5 * abs(cos(y)) + 0.1 < 0.15, 0.15, 0.5 * abs(cos(y)) + 0.1 ) symbols(x, y, circles = radius, inches = FALSE, fg = heat.colors(150), add = TRUE ) idx = rep(c(TRUE, FALSE), 75) segments(x[idx], y[idx], x[!idx], y[!idx], col = heat.colors(200)[1:150][idx]) arrows(x[1], y[1], x[1] + 0.75, y[1] + 0.75, col = "red", lwd = 2, angle = 75 ) arrows(x[150] - 0.75, y[150] - 0.75, x[150], y[150], col = "yellow", lwd = 2, angle = 75 ) mtext("``STAT'' made by Yihui XIE using R, School of Statistics, RUC, 2007", side = 1, cex = 0.8 )
hgroups <- function(hmerge) { cc<-hmerge n1<-nrow(cc) clases= paste( -cc[1,1], -cc[1,2],sep="-") clases <-as.matrix(clases) for(i in 2:n1) { if ((cc[i,1] < 0) & (cc[i,2] < 0) ) { clases <-rbind(clases,paste( -cc[i,1], -cc[i,2],sep="-") ) } if ((cc[i,1]) < 0 & (cc[i,2] > 0)) { clave<- cc[i,2] parte<-clases[clave,] clases <-rbind(clases,paste( -cc[i,1], parte,sep="-") ) } if ((cc[i,1]) > 0 & (cc[i,2] < 0)) { clave<- cc[i,1] parte<-clases[clave,] clases <-rbind(clases,paste( parte,-cc[i,2],sep="-") ) } if ((cc[i,1]) > 0 & (cc[i,2] > 0)) { clave1<- cc[i,1] clave2<- cc[i,2] parte1<-clases[clave1,] parte2<-clases[clave2,] clases <-rbind(clases,paste( parte1,parte2,sep="-") ) } } for(i in 1:n1) { x<-strsplit(clases[i,1],split="-")[[1]] x unique(x) y<-as.numeric(unique(x)) y<-sort(y) y<-as.character(y) ny<- length(y) s<-y[1] for(j in 2:ny) s<-paste(s,y[j],sep="-") clases[i,1]<- s } return(clases) }
renv_description_read <- function(path = NULL, package = NULL, subdir = NULL, ...) { path <- path %||% find.package(package) if (!file.exists(path)) { fmt <- "%s does not exist" stopf(fmt, renv_path_pretty(path)) } if (!renv_path_absolute(path)) path <- renv_path_normalize(path) info <- renv_file_info(path) if (identical(info$isdir, TRUE)) { components <- c(path, if (nzchar(subdir %||% "")) subdir, "DESCRIPTION") path <- paste(components, collapse = "/") } filebacked( scope = "DESCRIPTION", path = path, callback = renv_description_read_impl, subdir = subdir, ... ) } renv_description_read_impl <- function(path = NULL, subdir = NULL, ...) { type <- renv_archive_type(path) if (type != "unknown") { files <- renv_archive_list(path) subdir <- subdir %||% "" parts <- c("^[^/]+", if (nzchar(subdir)) subdir, "DESCRIPTION$") pattern <- paste(parts, collapse = "/") descs <- grep(pattern, files, value = TRUE) if (empty(descs)) { fmt <- "archive '%s' does not appear to contain a DESCRIPTION file" stopf(fmt, aliased_path(path)) } file <- descs[[1]] exdir <- renv_scope_tempfile("renv-description-") renv_archive_decompress(path, files = file, exdir = exdir) path <- file.path(exdir, file) } dcf <- renv_dcf_read(path, ...) if (empty(dcf)) stopf("DESCRIPTION file at '%s' is empty", path) dcf } renv_description_path <- function(path) { childpath <- file.path(path, "DESCRIPTION") indirect <- file.exists(childpath) path[indirect] <- childpath[indirect] path } renv_description_type <- function(path = NULL, desc = NULL) { if (is.null(desc)) { desc <- catch(renv_description_read(path)) if (inherits(desc, "error")) { warning(desc) return("unknown") } } type <- desc$Type if (!is.null(type)) return(tolower(type)) package <- desc$Package if (!is.null(package)) return("package") "unknown" } renv_description_parse_field <- function(field) { if (is.na(field) || !nzchar(field)) return(data.frame()) pattern <- paste0( "([a-zA-Z0-9._]+)", "(?:\\s*\\(([><=]+)\\s*([0-9.-]+)\\))?" ) parts <- strsplit(field, "\\s*,\\s*")[[1]] x <- parts[nzchar(parts)] m <- regexec(pattern, x) matches <- regmatches(x, m) if (empty(matches)) return(data.frame()) data.frame( Package = extract_chr(matches, 2L), Require = extract_chr(matches, 3L), Version = extract_chr(matches, 4L), stringsAsFactors = FALSE ) } renv_description_remotes <- function(descpath) { desc <- renv_description_read(path = descpath) remotes <- desc[["Remotes"]] if (is.null(remotes)) return(NULL) entries <- strsplit(remotes, "\\s*,\\s*", perl = TRUE)[[1L]] parsed <- map(entries, renv_description_remotes_parse) names(parsed) <- map_chr(parsed, `[[`, "Package") parsed } renv_description_remotes_parse <- function(entry) { status <- catch(renv_remotes_resolve(entry)) if (inherits(status, "error")) { fmt <- "failed to resolve remote '%s' from project DESCRIPTION file; skipping" warningf(fmt, entry) return(NULL) } status } renv_description_resolve <- function(path) { case( is.list(path) ~ path, is.character(path) ~ renv_description_read(path = path) ) } renv_description_built_version <- function(desc = NULL) { desc <- renv_description_resolve(desc) built <- desc[["Built"]] if (is.null(built)) return(NA) substring(built, 3L, regexpr(";", built, fixed = TRUE) - 1L) }
sim.points <- function(object, n.points = 1000, seed = NA, sample.type = "ppp", replace = FALSE, threshold = NA, ...) { if(!is.na(seed)){ set.seed(seed) } suit <- object$suitability if(sample.type == "ppp"){ total.dens <- sum(na.omit(values(suit))) suit <- suit * (n.points / total.dens) * (1 / prod(res(suit))) suit.im <- raster.as.im(suit) pnts <- rpoispp(suit.im) pres.points <- data.frame(x = pnts$x, y = pnts$y) } if(sample.type == "thresh.pa"){ if(is.na(threshold) | !is.numeric(threshold)){ stop("Sample type is thresh.pa but thresdhold was not supplied or is not numeric!") } suit <- suit >= threshold } if(sample.type == "thresh.con"){ if(is.na(threshold) | !is.numeric(threshold)){ stop("Sample type is thresh.con but thresdhold was not supplied or is not numeric!") } suit <- suit * (suit > threshold) } if(sample.type %in% c("binomial", "thresh.pa", "thresh.con")){ suit <- suit/max(getValues(suit), na.rm = TRUE) sample.df <- rasterToPoints(suit) sample.df <- sample.df[sample(1:nrow(sample.df)),] pres.points <- data.frame(x = numeric(0), y = numeric(0)) npres <- 0 while(npres < n.points){ for(i in 1:nrow(sample.df)){ if(i >= nrow(sample.df)){ next } this.suit <- sample.df[i,"layer"] if(rbinom(1, 1, prob = this.suit) == 1){ this.row <- sample.df[i, 1:2] npres <- npres + 1 pres.points[npres,] <- this.row if(replace == FALSE){ sample.df <- sample.df[-i,] } } if(npres >= n.points){ break } } } } return(pres.points) } raster.as.im <- function(im) { r <- raster::res(im) orig <- sp::bbox(im)[, 1] + 0.5 * r dm <- dim(im)[2:1] xx <- unname(orig[1] + cumsum(c(0, rep(r[1], dm[1] - 1)))) yy <- unname(orig[2] + cumsum(c(0, rep(r[2], dm[2] - 1)))) return(spatstat.geom::im(matrix(raster::values(im), ncol = dm[1], nrow = dm[2], byrow = TRUE)[dm[2]:1, ], xcol = xx, yrow = yy)) }
context("dplyr-sample-n") sc <- testthat_spark_connection() iris_tbl <- testthat_tbl("iris") test_requires("dplyr") test_that("'sample_n' works as expected", { test_requires_version("2.0.0") skip_livy() test_requires("dplyr") for (weight in list(NULL, rlang::sym("Petal_Length"))) { for (replace in list(FALSE, TRUE)) { sample_sdf <- iris_tbl %>% sample_n(10, weight = !!weight, replace = replace) expect_equal(colnames(sample_sdf), colnames(iris_tbl)) expect_equal(sample_sdf %>% collect() %>% nrow(), 10) sample_sdf <- iris_tbl %>% select(Petal_Length) %>% sample_n(10, weight = !!weight, replace = replace) expect_equal(colnames(sample_sdf), "Petal_Length") expect_equal(sample_sdf %>% collect() %>% nrow(), 10) } } }) test_that("weighted sampling works as expected with integer weight columns", { test_requires_version("2.0.0") skip_livy() test_requires("dplyr") sdf <- copy_to(sc, tibble::tibble(id = seq(100), weight = seq(100))) for (replace in list(FALSE, TRUE)) { sample_sdf <- sdf %>% sample_n(20, weight = weight, replace = replace) expect_equal(colnames(sample_sdf), colnames(sdf)) expect_equal(sample_sdf %>% collect() %>% nrow(), 20) sample_sdf <- sdf %>% sample_frac(0.2, weight = weight, replace = replace) expect_equal(colnames(sample_sdf), colnames(sdf)) expect_equal(sample_sdf %>% collect() %>% nrow(), 20) } })
bootstrap_model <- function(seminr_model, nboot = 500, cores = NULL, seed = NULL, ...) { out <- tryCatch( { message("Bootstrapping model using seminr...") d <- seminr_model$rawdata measurement_model <- seminr_model$measurement_model structural_model <- seminr_model$smMatrix inner_weights <- seminr_model$inner_weights missing_value <- seminr_model$settings$missing_value maxIt <- seminr_model$settings$maxIt stopCriterion <- seminr_model$settings$stopCriterion missing <- seminr_model$settings$missing if (nboot > 0) { suppressWarnings(ifelse(is.null(cores), cl <- parallel::makeCluster(parallel::detectCores(), setup_strategy = "sequential"), cl <- parallel::makeCluster(cores, setup_strategy = "sequential"))) getRandomIndex <- function(d) {return(sample.int(nrow(d), replace = TRUE))} if (is.null(seed)) {seed <- sample.int(100000, size = 1)} parallel::clusterExport(cl=cl, varlist=c("measurement_model", "structural_model", "inner_weights", "getRandomIndex", "d", "HTMT", "seed", "total_effects", "missing_value", "maxIt", "stopCriterion", "missing"), envir=environment()) length <- 3*nrow(seminr_model$path_coef)^2 + 2*nrow(seminr_model$outer_loadings)*ncol(seminr_model$outer_loadings) getEstimateResults <- function(i, d = d, length) { set.seed(seed + i) tryCatch({ boot_model <- seminr::estimate_pls(data = d[getRandomIndex(d),], measurement_model, structural_model, inner_weights = inner_weights) boot_htmt <- HTMT(boot_model) boot_total <- total_effects(boot_model$path_coef) return(as.matrix(c(c(boot_model$path_coef), c(boot_model$outer_loadings), c(boot_model$outer_weights), c(boot_htmt), c(boot_total)))) }, error = function(cond) { message("Bootstrapping encountered an ERROR: ") message(cond) return(rep(NA, length)) }, warning = function(cond) { message("Bootstrapping encountered an ERROR: ") message(cond) return(rep(NA, length)) } ) } utils::capture.output(bootmatrix <- parallel::parSapply(cl, 1:nboot, getEstimateResults, d, length)) bootmatrix <- bootmatrix[,!is.na(bootmatrix[1,])] fails <- nboot - ncol(bootmatrix) nboot <- nboot - fails if (fails > 0) { message(paste("Bootstrapping encountered a WARNING: ", fails, "models failed to converge in PLSc. \nThese models are excluded from the reported bootstrap statistics.")) } means <- apply(bootmatrix,1,mean) sds <- apply(bootmatrix,1,stats::sd) path_cols <- ncol(seminr_model$path_coef) path_rows <- nrow(seminr_model$path_coef) start <- 1 end <- (path_cols*path_rows) boot_paths <- array(bootmatrix[start:end,1:nboot], dim = c(path_rows, path_cols, nboot), dimnames = list(rownames(seminr_model$path_coef), colnames(seminr_model$path_coef),1:nboot)) paths_means <- matrix(means[start:end], nrow = path_rows, ncol = path_cols) paths_sds <- matrix(sds[start:end], nrow = path_rows, ncol = path_cols) paths_descriptives <- cbind(seminr_model$path_coef, paths_means, paths_sds) filled_cols <- apply(paths_descriptives != 0, 2, any, na.rm=TRUE) filled_rows <- apply(paths_descriptives != 0, 1, any, na.rm=TRUE) paths_descriptives <- subset(paths_descriptives, filled_rows, filled_cols) if (length(unique(structural_model[,"target"])) == 1) { dependant <- unique(structural_model[,"target"]) } else { dependant <- colnames(paths_descriptives[, 1:length(unique(structural_model[,"target"]))]) } col_names <- c() for (parameter in c("PLS Est.", "Boot Mean", "Boot SD")) { for (i in 1:length(dependant)) { col_names <- c(col_names, paste(dependant[i], parameter, sep = " ")) } } colnames(paths_descriptives) <- col_names mm_cols <- ncol(seminr_model$outer_loadings) mm_rows <- nrow(seminr_model$outer_loadings) start <- end+1 end <- start+(mm_cols*mm_rows)-1 boot_loadings <- array(bootmatrix[start:end,1:nboot], dim = c(mm_rows, mm_cols, nboot), dimnames = list(rownames(seminr_model$outer_loadings), colnames(seminr_model$outer_loadings),1:nboot)) loadings_means <- matrix(means[start:end], nrow = mm_rows, ncol = mm_cols) loadings_sds <- matrix(sds[start:end], nrow = mm_rows, ncol = mm_cols) loadings_descriptives <- cbind(seminr_model$outer_loadings, loadings_means, loadings_sds) col_names2 <- c() for (parameter in c("PLS Est.", "Boot Mean", "Boot SD")) { for(i in colnames(seminr_model$outer_loadings)) { col_names2 <- c(col_names2, paste(i, parameter, sep = " ")) } } colnames(loadings_descriptives) <- col_names2 start <- end+1 end <- start+(mm_cols*mm_rows)-1 boot_weights <- array(bootmatrix[start:end,1:nboot], dim = c(mm_rows, mm_cols, nboot), dimnames = list(rownames(seminr_model$outer_loadings), colnames(seminr_model$outer_loadings),1:nboot)) weights_means <- matrix(means[start:end], nrow = mm_rows, ncol = mm_cols) weights_sds <- matrix(sds[start:end], nrow = mm_rows, ncol = mm_cols) weights_descriptives <- cbind(seminr_model$outer_weights, weights_means, weights_sds) colnames(weights_descriptives) <- col_names2 HTMT_matrix <- HTMT(seminr_model) start <- end+1 end <- start+(path_cols*path_rows)-1 boot_HTMT <- array(bootmatrix[start:end,1:nboot], dim = c(path_rows, path_cols, nboot), dimnames = list(rownames(HTMT_matrix), colnames(HTMT_matrix),1:nboot)) htmt_means <- matrix(means[start:end], nrow = path_rows, ncol = path_cols) htmt_sds <- matrix(sds[start:end], nrow = path_rows, ncol = path_cols) HTMT_descriptives <- cbind(HTMT_matrix, htmt_means, htmt_sds) col_names3 <- c() for (parameter in c("PLS Est.", "Boot Mean", "Boot SD")) { for(i in colnames(HTMT_matrix)) { col_names3 <- c(col_names3, paste(i, parameter, sep = " ")) } } colnames(HTMT_descriptives) <- col_names3 total_matrix <- total_effects(seminr_model$path_coef) start <- end+1 end <- start+(path_cols*path_rows)-1 boot_total_paths <- array(bootmatrix[start:end,1:nboot], dim = c(path_rows, path_cols, nboot), dimnames = list(rownames(total_matrix), colnames(total_matrix),1:nboot)) total_means <- matrix(means[start:end], nrow = path_rows, ncol = path_cols) total_sds <- matrix(sds[start:end], nrow = path_rows, ncol = path_cols) total_paths_descriptives <- cbind(total_matrix, total_means, total_sds) filled_cols <- apply(total_paths_descriptives != 0, 2, any, na.rm=TRUE) filled_rows <- apply(total_paths_descriptives != 0, 1, any, na.rm=TRUE) total_paths_descriptives <- subset(total_paths_descriptives, filled_rows, filled_cols) colnames(total_paths_descriptives) <- col_names class(paths_descriptives) <- append(class(paths_descriptives), "table_output") class(loadings_descriptives) <- append(class(loadings_descriptives), "table_output") class(weights_descriptives) <- append(class(weights_descriptives), "table_output") class(HTMT_descriptives) <- append(class(HTMT_descriptives), "table_output") class(total_paths_descriptives) <- append(class(total_paths_descriptives), "table_output") parallel::stopCluster(cl) } seminr_model$boot_paths <- boot_paths seminr_model$boot_loadings <- boot_loadings seminr_model$boot_weights <- boot_weights seminr_model$boot_HTMT <- boot_HTMT seminr_model$boot_total_paths <- boot_total_paths seminr_model$paths_descriptives <- paths_descriptives seminr_model$loadings_descriptives <- loadings_descriptives seminr_model$weights_descriptives <- weights_descriptives seminr_model$HTMT_descriptives <- HTMT_descriptives seminr_model$total_paths_descriptives <- total_paths_descriptives seminr_model$boots <- nboot seminr_model$seed <- seed class(seminr_model) <- c("boot_seminr_model", "seminr_model") message("SEMinR Model successfully bootstrapped") return(seminr_model) }, error = function(cond) { message("Bootstrapping encountered this ERROR: ") message(cond) parallel::stopCluster(cl) return(NULL) }, warning = function(cond) { message("Bootstrapping encountered this WARNING:") message(cond) parallel::stopCluster(cl) return(NULL) }, finally = { } ) }
print.VEwaningVariant <- function(x, ...) { attr(x = x, which = "gFunc") <- NULL attr(x = x, which = "maxTau") <- NULL attr(x = x, which = "lag") <- NULL attr(x = x, which = "v") <- NULL attr(x = x, which = "phaseType") <- NULL attr(x = x, which = "wgtType") <- NULL x <- unclass(x = x) print(x) return( NULL ) }
report_table <- function(x, ...) { UseMethod("report_table") } as.report_table <- function(x, ...) { UseMethod("as.report_table") } as.report_table.default <- function(x, summary = NULL, as_is = FALSE, ...) { if (as_is) { class(x) <- unique(c(class(x)[1], "report_table", utils::tail(class(x), -1))) } else { class(x) <- unique(c("report_table", class(x))) } attributes(x) <- c(attributes(x), list(...)) if (!is.null(summary)) { if (as_is) { class(summary) <- unique(c(class(summary)[1], "report_table", utils::tail(class(summary), -1))) } else { class(summary) <- unique(c("report_table", class(summary))) } attr(x, "summary") <- summary } x } as.report_table.report <- function(x, summary = NULL, ...) { if (is.null(summary) || isFALSE(summary)) { attributes(x)$table } else if (isTRUE(summary)) { summary(attributes(x)$table) } } summary.report_table <- function(object, ...) { if (is.null(attributes(object)$summary)) { object } else { attributes(object)$summary } } format.report_table <- function(x, ...) { insight::format_table(x, ...) } print.report_table <- function(x, ...) { cat(insight::export_table(format(x, ...), ...)) }
computePolicy <- function(x) { UseMethod("computePolicy", x) } computePolicy.matrix <- function(x) { policy <- colnames(x)[apply(x, 1, which.max)] names(policy) <- rownames(x) return(policy) } computePolicy.data.frame <- function(x) { return(computePolicy(as.matrix(x))) } computePolicy.rl <- function(x) { return(computePolicy(x$Q)) } computePolicy.default <- function(x) { stop("Argument invalid.") } policy <- function(x) { .Deprecated("computePolicy") computePolicy(x) }
ExpData <- function(data, type = 1, fun=NULL){ if (!is.data.frame(data)) stop("data must be a numeric vector or data.frame") xx <- as.data.frame(data) dd <- sapply( sapply(xx, function(x){ if(is.character(x)) { round((length(x[is.na(x)]) + length(x[x == '']))/ length(x), 5) } else { round((length(x[is.na(x)]))/ length(x), 5) } }), function(y) { if (y == 0.0) xx <- 1 else if (y > 0.9) xx <- 2 else if (y >= 0.5) xx <- 3 else if (y < 0.5) xx <- 4 } ) p1 <- paste0(round(length(dd[dd == 4]) / length(dd) * 100, 2), "%", " (", length(dd[dd == 4]), ")") p2 <- paste0(round(length(dd[dd == 3]) / length(dd) * 100, 2), "%", " (", length(dd[dd == 3]), ")") p3 <- paste0(round(length(dd[dd == 2]) / length(dd) * 100, 2), "%", " (", length(dd[dd == 2]), ")") p4 <- paste0(round(length(dd[dd == 1]) / length(dd) * 100, 2), "%", " (", length(dd[dd == 1]), ")") Date_cnt <- length(names(xx)[unlist(sapply(xx, function(x) { clsv <- class(x)[1] clsv %in% c("Date", "POSIXct", "POSIXt") }))]) Unif_cnt <- length(names(xx)[unlist(sapply(xx, function(x) length(unique(x[!is.na(x)])) == 1))]) Unvar_cnt <- length(names(xx)[unlist(sapply(xx, function(x) length(unique(x)) == length(x)))]) if (type == 1){ Out_put <- data.frame (rbind( c("Sample size (nrow)", nrow(xx)), c("No. of variables (ncol)", ncol(xx)), c("No. of numeric/interger variables", length(names(xx)[sapply(xx, is.numeric)])), c("No. of factor variables", length(names(xx)[sapply(xx, is.factor)])), c("No. of text variables", length(names(xx)[sapply(xx, is.character)])), c("No. of logical variables", length(names(xx)[sapply(xx, is.logical)])), c("No. of identifier variables", Unvar_cnt), c("No. of date variables", Date_cnt), c("No. of zero variance variables (uniform)", Unif_cnt), c("%. of variables having complete cases", p4), c("%. of variables having >0% and <50% missing cases", p1), c("%. of variables having >=50% and <90% missing cases", p2), c("%. of variables having >=90% missing cases", p3) ) ) names(Out_put) <- c("Descriptions", "Value") return(Out_put) } if (type == 2){ name_var <- names(xx) tt <- sapply(name_var, function(x){ expdatatype2(xx, x, myfun=fun) } ) op <- data.frame(t(tt)) op$Index <- seq(1, length(name_var), 1) rownames(op) <- NULL op[, 2] <- as.character(paste0(op[, 2])) op[, 3] <- as.character(paste0(op[, 3])) op[, 4] <- as.integer(paste0(op[, 4])) op[, 5] <- as.integer(paste0(op[, 5])) op[, 6] <- as.numeric(paste0(op[, 6])) op[, 7] <- as.integer(paste0(op[, 7])) if(!is.null(fun)) { for(j in 1:length(fun)) op[, 7+j] <- as.numeric(paste0(op[, 7+j])) } names(op) <- c("Index", "Variable_Name", "Variable_Type","Sample_n","Missing_Count", "Per_of_Missing", "No_of_distinct_values", fun) if(!is.null(fun)) op[!op$Variable_Type %in% c("integer", "numeric"), fun] <- NA return(op) } }
PlotFDRs <- function(lpcfdr.out, frac=.25){ CheckPlotFDRsFormat(lpcfdr.out,frac) lpcfdr <- lpcfdr.out$fdrlpc tfdr <- lpcfdr.out$fdrt tfdrs <- tfdr[tfdr<quantile(tfdr,frac)] lpcfdrs <- lpcfdr[lpcfdr<quantile(lpcfdr,frac)] plot(tfdrs[order(tfdrs, decreasing=FALSE)], type="l", ylim=range(c(tfdrs,lpcfdrs)), main="Estimated FDRs for T and LPC", xlab="Num Genes Called Significant", ylab="Estimated FDR") points(lpcfdrs[order(lpcfdrs,decreasing=FALSE)], type="l", col="red") legend("topleft", pch=15, col=c("black", "red"), c("T", "LPC")) }
"fun.theo.bi.mv.gld"<- function(L1,L2,L3,L4,param1,M1,M2,M3,M4,param2,p1,normalise="N"){ if(length(L1)>1){ p1<-L1[9] M4<-L1[8] M3<-L1[7] M2<-L1[6] M1<-L1[5] L4<-L1[4] L3<-L1[3] L2<-L1[2] L1<-L1[1] } raw.moment1<-fun.rawmoments(L1,L2,L3,L4,param1) raw.moment2<-fun.rawmoments(M1,M2,M3,M4,param2) p2<-1-p1 ex1<-p1*raw.moment1[1]+p2*raw.moment2[1] ex2<-p1*raw.moment1[2]+p2*raw.moment2[2] ex3<-p1*raw.moment1[3]+p2*raw.moment2[3] ex4<-p1*raw.moment1[4]+p2*raw.moment2[4] result <- rep(NA, 4) result[1]<-ex1 result[2]<-ex2-ex1^2 result[3]<-(ex3-3*ex2*ex1+2*ex1^3)/(result[2]^1.5) result[4]<-(ex4-4*ex3*ex1+6*ex2*ex1^2-3*ex1^4)/(result[2]^2) if(param1=="rs"){ check1<-!as.logical((L3 > -1/1:4) * (L4 > -1/1:4)) } else if(param1=="fmkl"){ check1<-as.logical(min(L3, L4) < (-1/1:4)) } if(param2=="rs"){ check2<-!as.logical((M3 > -1/1:4) * (M4 > -1/1:4)) } else if(param2=="fmkl"){ check2<-as.logical(min(M3, M4) < (-1/1:4)) } result[check1+check2!=0]<-NA if(normalise=="Y"){ result[4] <- result[4] - 3 } names(result) <- c("mean", "variance", "skewness", "kurtosis") return(result) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) wasoil <- system.file("exdat/wasoil.zip", package = "rassta") o <- tempdir() file.copy(from = wasoil, to = o) d <- paste(o, "/rassta", sep = "") unzip(paste(o, "/wasoil.zip", sep = ""), exdir = d) library(rassta) library(terra) cu <- c("climate.tif", "material.tif", "terrain.tif") cudir <- paste(d, cu, sep = "/") all.cu <- rast(cudir) par(mfrow = c(3, 1)) plot(all.cu[[1]], type = "classes", main = "Climatic Classification Units", col = hcl.colors(4, "spectral"), mar = c(1.5, 1.5, 1.5, 16), levels = c("1. Highest Rainfall and Lowest Temperature", "2. High Rainfall and Low Temperature", "3. Low Rainfall and High Temperature", "4. Lowest Rainfall and Highest Temperature" ) ) plot(all.cu[[2]], type = "classes", main = "Soil Parent Material Units", col = hcl.colors(6, "spectral"), mar = c(1.5, 1.5, 1.5, 16), levels = c("1. Igneous", "2. Sedimentary", "3. Alluvium - Moderately weathered ", "4. Alluvium - Somewhat weathered", "5. Alluvium - Rich in organic matter", "6. Alluvium - Rich in clay and organic matter" ) ) plot(all.cu[[3]], type = "classes", main = "Terrain Classification Units", col = hcl.colors(8, "spectral"), mar = c(1.5, 1.5, 1.5, 16), levels = c("1. Summit", "2. Shoulder", "3. Backslope", "4. Backslope - Steep", "5. Footslope", "6. Footslope - Steep", "7. Toeslope", "8. Floodplain" ) ) su <- strata(cu.rast = all.cu) plot(su$su.rast, type = "classes", main = "Stratification Units", col = hcl.colors(length(unique(su$su.rast)[, 1]), "spectral"), plg = list(ncol = 4), mar = c(1.5, 1.5, 1.5, 12) ) su$code.mult unlink(c(paste(o, "/wasoil.zip", sep = ""), d), recursive = TRUE)
timmean <- function(var, infile, outfile, nc34 = 4, overwrite = FALSE, verbose = FALSE, nc = NULL) { timx_wrapper("mean", var, infile, outfile, nc34, overwrite, verbose = verbose, nc = nc) }
library(testthat) library(CVXR) test_check("CVXR", filter="^g03")
smspline <- function(formula, data){ if(is.vector(formula)){ x <- formula }else{ if(missing(data)){ mf <- model.frame(formula) }else{ mf <- model.frame(formula,data) } if(ncol(mf) != 1)stop("formula can have only one variable") x <- mf[,1] } x.u <- sort(unique(x)) Zx <- smspline.v(x.u)$Zs Zx[match(x,x.u),] } smspline.v <- function(time) { t1 <- sort(unique(time)) p <- length(t1) h <- diff(t1) h1 <- h[1:(p - 2)] h2 <- h[2:(p - 1)] Q <- matrix(0, nrow = p, ncol = p - 2) Q[cbind(1:(p - 2), 1:(p - 2))] <- 1/h1 Q[cbind(1 + 1:(p - 2), 1:(p - 2))] <- -1/h1 - 1/h2 Q[cbind(2 + 1:(p - 2), 1:(p - 2))] <- 1/h2 Gs <- matrix(0, nrow = p - 2, ncol = p - 2) Gs[cbind(1:(p - 2), 1:(p - 2))] <- 1/3 * (h1 + h2) Gs[cbind(1 + 1:(p - 3), 1:(p - 3))] <- 1/6 * h2[1:(p - 3)] Gs[cbind(1:(p - 3), 1 + 1:(p - 3))] <- 1/6 * h2[1:(p - 3)] Gs Zus <- t(solve(t(Q) %*% Q, t(Q))) R <- chol(Gs, pivot = FALSE) tol <- max(1e-12,1e-8*mean(diag(R))) if(sum(abs(diag(R))) < tol) stop("singular G matrix") Zvs <- Zus %*% t(R) list(Xs = cbind(rep(1, p), t1), Zs = Zvs, Q = Q, Gs = Gs, R = R) } approx.Z <- function(Z,oldtimes,newtimes){ oldt.u <- sort(unique(oldtimes)) if(length(oldt.u) !=length(oldtimes) || any(oldt.u != oldtimes)){ Z <- Z[match(oldt.u,oldtimes),] oldtimes <- oldt.u } apply(Z,2,function(u,oldt,newt){ approx(oldt,u,xout=newt)$y}, oldt=oldtimes, newt=newtimes) }
res_sk_map <- function(nerr_site_id , stations , sk_result = NULL , bbox , shp , station_labs = TRUE , lab_loc = NULL , bg_map = NULL , zoom = NULL , maptype = "toner-lite") { abbrev <- lab_long <- lab_lat <- NULL if(class(shp) != 'SpatialPolygons') { if(class(shp) != 'sf') { stop('shapefile (shp) must be sf (preferred) or SpatialPolygons object') } } else { shp <- as(shp, "sf") } if(length(stations) != length(sk_result)) stop('Incorrect number of seasonal kendall results specified.') if(is.null(bbox)) stop('Specify a bounding box (bbox) in the form of c(X1, Y1, X2, Y2)') if(length(bbox) != 4) stop('Incorrect number of elements specified for bbox. Specify a bounding box (bbox) in the form of c(X1, Y1, X2, Y2)') xmin <- min(bbox[c(1,3)]) xmax <- max(bbox[c(1,3)]) ymin <- min(bbox[c(2,4)]) ymax <- max(bbox[c(2,4)]) bbox <- c(xmin, ymin, xmax, ymax) loc <- get('sampling_stations') loc <- loc[(loc$Station.Code %in% stations), ] loc$abbrev <- toupper(substr(loc$Station.Code, start = 4, stop = 5)) loc$sk_result <- sk_result loc$align <- -1.25 if(!is.null(lab_loc)) loc$align[lab_loc == 'R'] <- 1.25 loc <- loc[order(loc$Station.Code), ] loc$Longitude <- -loc$Longitude loc_sf <- sf::st_as_sf(loc, coords = c("Longitude","Latitude")) sf::st_crs(loc_sf) <- 4326 break_vals <- c("inc", "dec", "insig", "insuff") fill_colors <- c(' res_point_size <- c(6, 6, 6, 9) res_point_shape <- c(24, 25, 21, 13) master_key <- as.data.frame(cbind(break_vals, fill_colors, res_point_size, res_point_shape)) needed_keys <- left_join(loc, master_key, by = c("sk_result" = "break_vals")) use_shape <- unique(as.integer(needed_keys$res_point_shape)) use_color <- unique(needed_keys$fill_color) print(paste("maptype is ",maptype)) if(is.null(bg_map)) { bg_map <- base_map(bbox, crs = st_crs(shp), maptype = maptype, zoom = zoom) } m <- bg_map + geom_sf(data = shp, aes(), inherit.aes = FALSE, fill = "yellow", col = ' ggthemes::theme_map() + geom_sf(data = loc_sf, inherit.aes = FALSE, aes(color = .data$sk_result, fill = .data$sk_result, shape = .data$sk_result, size = .data$sk_result), stroke = 2, show.legend = FALSE) + scale_color_manual(values = fill_colors, breaks = break_vals) + scale_fill_manual(values = fill_colors, breaks = break_vals) + scale_size_manual(values = res_point_size, breaks = break_vals) + scale_shape_manual(values = res_point_shape, breaks = break_vals) if(station_labs) { loc$lab_long <- loc$Longitude + 0.045* loc$align * (bbox[3] - bbox[1]) loc$lab_lat <- loc$Latitude + 0.015 * (bbox[4] - bbox[2]) labels_sf <- loc %>% select(abbrev, lab_long, lab_lat) %>% sf::st_as_sf(coords = c("lab_long","lab_lat")) sf::st_crs(labels_sf) <- 4326 m <- m + geom_sf_label(data = labels_sf, inherit.aes = FALSE, aes(label = abbrev)) } m <- m + coord_sf( xlim = c(bbox[1], bbox[3]), ylim = c(bbox[2], bbox[4]), expand = FALSE, crs = st_crs(shp), default_crs = NULL, datum = sf::st_crs(4326), lims_method = c("cross", "box", "orthogonal", "geometry_bbox"), ndiscr = 100, default = FALSE, clip = "on" ) return(m) }
test_that("we can use ouch-based functions", { library("ouch") data(anoles) tree <- with(anoles, ouchtree(node, ancestor, time / max(time), species)) A <- pmc_fit(tree, log(anoles["size"]), "hansen", regimes = anoles["OU.LP"], sqrt.alpha = 1, sigma = 1) sims <- simulate(A) s <- format_sims(sims) ou3v4 <- pmc(tree, log(anoles["size"]), modelA = "hansen", modelB = "hansen", optionsA = list(regimes = anoles["OU.LP"]), optionsB = list(regimes = anoles["OU.4"]), nboot = 100, sqrt.alpha = 1, sigma = 1, mc.cores = 1) expect_is(ou3v4, "pmc") })
plot_optimization <- function( model, point.color = viridis::viridis( 100, option = "F", direction = -1 ), verbose = TRUE ){ moran.i <- NULL optimization <- NULL r.squared <- NULL spatial.predictor.index <- NULL if(inherits(model, "rf_spatial")){ x <- model$spatial$optimization } else { x <- model } p <- ggplot2::ggplot(data = x) + ggplot2::aes( y = moran.i, x = r.squared, color = optimization, size = spatial.predictor.index ) + ggplot2::geom_point() + ggplot2::scale_color_gradientn(colors = point.color) + ggplot2::geom_point( data = x[x$selected, ], aes( y = moran.i, x = r.squared), colour="black", size = 5, shape = 1, alpha = 0.3 ) + ggplot2::scale_x_reverse() + ggplot2::geom_path(data = x[x$selected, ], aes( y = moran.i, x = r.squared ), size = 0.5, color = "black", alpha = 0.3 ) + ggplot2::geom_hline( yintercept = 0, col = "gray10", size = 0.7, linetype = "dashed") + ggplot2::labs( size = "Number of \nspatial predictors", color = "Weighted \noptimization index" ) + ggplot2::ylab("Maximum Moran's I of the residuals") + ggplot2::xlab("Model's R squared (out-of-bag)") + ggplot2::ggtitle("Selection of spatial predictors (selection path shown in gray)") + ggplot2::theme_bw() + ggplot2::theme(plot.title = element_text(hjust = 0.5)) if(verbose == TRUE){ suppressMessages(print(p)) } }
get_processing_time_string <- function(time_start, time_end) { stopifnot(length(time_start) == 1) stopifnot(length(time_start) == 1) stopifnot("POSIXct" %in% class(time_start)) stopifnot("POSIXct" %in% class(time_start)) paste0("processing time: ", round(as.numeric(time_end - time_start, units = "secs"), digits = 2), " s") }
pivot_wider <- function(data, id_cols = NULL, id_expand = FALSE, names_from = name, names_prefix = "", names_sep = "_", names_glue = NULL, names_sort = FALSE, names_vary = "fastest", names_expand = FALSE, names_repair = "check_unique", values_from = value, values_fill = NULL, values_fn = NULL, unused_fn = NULL, ...) { check_dots_used() UseMethod("pivot_wider") } pivot_wider.data.frame <- function(data, id_cols = NULL, id_expand = FALSE, names_from = name, names_prefix = "", names_sep = "_", names_glue = NULL, names_sort = FALSE, names_vary = "fastest", names_expand = FALSE, names_repair = "check_unique", values_from = value, values_fill = NULL, values_fn = NULL, unused_fn = NULL, ...) { names_from <- enquo(names_from) values_from <- enquo(values_from) spec <- build_wider_spec( data = data, names_from = !!names_from, values_from = !!values_from, names_prefix = names_prefix, names_sep = names_sep, names_glue = names_glue, names_sort = names_sort, names_vary = names_vary, names_expand = names_expand ) id_cols <- build_wider_id_cols_expr( data = data, id_cols = {{id_cols}}, names_from = !!names_from, values_from = !!values_from ) pivot_wider_spec( data = data, spec = spec, id_cols = !!id_cols, id_expand = id_expand, names_repair = names_repair, values_fill = values_fill, values_fn = values_fn, unused_fn = unused_fn ) } pivot_wider_spec <- function(data, spec, names_repair = "check_unique", id_cols = NULL, id_expand = FALSE, values_fill = NULL, values_fn = NULL, unused_fn = NULL) { input <- data spec <- check_pivot_spec(spec) names_from_cols <- names(spec)[-(1:2)] values_from_cols <- vec_unique(spec$.value) id_cols <- select_wider_id_cols( data = data, id_cols = {{id_cols}}, names_from_cols = names_from_cols, values_from_cols = values_from_cols ) values_fn <- check_list_of_functions(values_fn, values_from_cols, "values_fn") unused_cols <- setdiff(names(data), c(id_cols, names_from_cols, values_from_cols)) unused_fn <- check_list_of_functions(unused_fn, unused_cols, "unused_fn") unused_cols <- names(unused_fn) if (is.null(values_fill)) { values_fill <- list() } if (is_scalar(values_fill)) { values_fill <- rep_named(values_from_cols, list(values_fill)) } if (!vec_is_list(values_fill)) { abort("`values_fill` must be NULL, a scalar, or a named list") } values_fill <- values_fill[intersect(names(values_fill), values_from_cols)] if (!is_bool(id_expand)) { abort("`id_expand` must be a single `TRUE` or `FALSE`.") } data <- as_tibble(data) data <- data[vec_unique(c(id_cols, names_from_cols, values_from_cols, unused_cols))] if (id_expand) { data <- complete(data, !!!syms(id_cols), fill = values_fill, explicit = FALSE) } rows <- data[id_cols] row_id <- vec_group_id(rows) nrow <- attr(row_id, "n") rows <- vec_slice(rows, vec_unique_loc(row_id)) n_unused_fn <- length(unused_fn) unused <- vector("list", length = n_unused_fn) names(unused) <- unused_cols if (n_unused_fn > 0L) { unused_locs <- vec_group_loc(row_id)$loc } for (i in seq_len(n_unused_fn)) { unused_col <- unused_cols[[i]] unused_fn_i <- unused_fn[[i]] unused_value <- data[[unused_col]] unused[[i]] <- value_summarize( value = unused_value, value_locs = unused_locs, value_name = unused_col, fn = unused_fn_i, fn_name = "unused_fn" ) } unused <- tibble::new_tibble(unused, nrow = nrow) duplicate_names <- character(0L) value_specs <- unname(split(spec, spec$.value)) value_out <- vec_init(list(), length(value_specs)) for (i in seq_along(value_out)) { value_spec <- value_specs[[i]] value_name <- value_spec$.value[[1]] value <- data[[value_name]] cols <- data[names(value_spec)[-(1:2)]] col_id <- vec_match(as_tibble(cols), value_spec[-(1:2)]) value_id <- data.frame(row = row_id, col = col_id) value_fn <- values_fn[[value_name]] if (is.null(value_fn) && vec_duplicate_any(value_id)) { value_fn <- list duplicate_names <- c(duplicate_names, value_name) } if (!is.null(value_fn)) { result <- vec_group_loc(value_id) value_id <- result$key value_locs <- result$loc value <- value_summarize( value = value, value_locs = value_locs, value_name = value_name, fn = value_fn, fn_name = "values_fn" ) } ncol <- nrow(value_spec) fill <- values_fill[[value_name]] if (is.null(fill)) { out <- vec_init(value, nrow * ncol) } else { stopifnot(vec_size(fill) == 1) fill <- vec_cast(fill, value) out <- vec_rep_each(fill, nrow * ncol) } vec_slice(out, value_id$row + nrow * (value_id$col - 1L)) <- value value_out[[i]] <- chop_rectangular_df(out, value_spec$.name) } if (length(duplicate_names) > 0L) { duplicate_names <- glue::backtick(duplicate_names) duplicate_names <- glue::glue_collapse(duplicate_names, sep = ", ", last = " and ") group_cols <- c(id_cols, names_from_cols) group_cols <- backtick_if_not_syntactic(group_cols) group_cols <- glue::glue_collapse(group_cols, sep = ", ") warn(glue::glue( "Values from {duplicate_names} are not uniquely identified; output will contain list-cols.\n", "* Use `values_fn = list` to suppress this warning.\n", "* Use `values_fn = {{summary_fun}}` to summarise duplicates.\n", "* Use the following dplyr code to identify duplicates.\n", " {{data}} %>%\n", " dplyr::group_by({group_cols}) %>%\n", " dplyr::summarise(n = dplyr::n(), .groups = \"drop\") %>%\n", " dplyr::filter(n > 1L)" )) } values <- vec_cbind(!!!value_out, .name_repair = "minimal") values <- values[spec$.name] out <- wrap_error_names(vec_cbind( rows, values, unused, .name_repair = names_repair )) reconstruct_tibble(input, out) } build_wider_spec <- function(data, names_from = name, values_from = value, names_prefix = "", names_sep = "_", names_glue = NULL, names_sort = FALSE, names_vary = "fastest", names_expand = FALSE) { names_from <- tidyselect::eval_select(enquo(names_from), data) values_from <- tidyselect::eval_select(enquo(values_from), data) if (is_empty(names_from)) { abort("`names_from` must select at least one column.") } if (is_empty(values_from)) { abort("`values_from` must select at least one column.") } names_vary <- arg_match0(names_vary, c("fastest", "slowest"), arg_nm = "names_vary") if (!is_bool(names_expand)) { abort("`names_expand` must be a single `TRUE` or `FALSE`.") } data <- as_tibble(data) data <- data[names_from] if (names_expand) { row_ids <- expand(data, !!!syms(names(data))) } else { row_ids <- vec_unique(data) if (names_sort) { row_ids <- vec_sort(row_ids) } } row_names <- exec(paste, !!!row_ids, sep = names_sep) out <- tibble( .name = vec_paste0(names_prefix, row_names) ) if (length(values_from) == 1) { out$.value <- names(values_from) } else { if (names_vary == "fastest") { out <- vec_rep(out, vec_size(values_from)) out$.value <- vec_rep_each(names(values_from), vec_size(row_ids)) row_ids <- vec_rep(row_ids, vec_size(values_from)) } else { out <- vec_rep_each(out, vec_size(values_from)) out$.value <- vec_rep(names(values_from), vec_size(row_ids)) row_ids <- vec_rep_each(row_ids, vec_size(values_from)) } out$.name <- vec_paste0(out$.value, names_sep, out$.name) } out <- vec_cbind(out, as_tibble(row_ids), .name_repair = "minimal") if (!is.null(names_glue)) { out$.name <- as.character(glue::glue_data(out, names_glue)) } out } build_wider_id_cols_expr <- function(data, id_cols = NULL, names_from = name, values_from = value) { names_from_cols <- names(tidyselect::eval_select(enquo(names_from), data)) values_from_cols <- names(tidyselect::eval_select(enquo(values_from), data)) out <- select_wider_id_cols( data = data, id_cols = {{id_cols}}, names_from_cols = names_from_cols, values_from_cols = values_from_cols ) expr(c(!!!out)) } select_wider_id_cols <- function(data, id_cols = NULL, names_from_cols = character(), values_from_cols = character()) { id_cols <- enquo(id_cols) data <- data[setdiff(names(data), c(names_from_cols, values_from_cols))] if (quo_is_null(id_cols)) { return(names(data)) } try_fetch( id_cols <- tidyselect::eval_select(enquo(id_cols), data), vctrs_error_subscript_oob = function(cnd) { rethrow_id_cols_oob(cnd, names_from_cols, values_from_cols) } ) names(id_cols) } rethrow_id_cols_oob <- function(cnd, names_from_cols, values_from_cols) { i <- cnd[["i"]] if (!is_string(i)) { abort("`i` is expected to be a string.", .internal = TRUE) } if (i %in% names_from_cols) { stop_id_cols_oob(i, "names_from") } else if (i %in% values_from_cols) { stop_id_cols_oob(i, "values_from") } else { zap() } } stop_id_cols_oob <- function(i, arg) { message <- c( glue("`id_cols` can't select a column already selected by `{arg}`."), i = glue("Column `{i}` has already been selected.") ) abort(message, parent = NA) } value_summarize <- function(value, value_locs, value_name, fn, fn_name) { value <- vec_chop(value, value_locs) if (identical(fn, list)) { return(value) } value <- map(value, fn) sizes <- list_sizes(value) invalid_sizes <- sizes != 1L if (any(invalid_sizes)) { size <- sizes[invalid_sizes][[1]] header <- glue( "Applying `{fn_name}` to `{value_name}` must result in ", "a single summary value per key." ) bullet <- c( x = glue("Applying `{fn_name}` resulted in a value with length {size}.") ) abort(c(header, bullet)) } value <- vec_c(!!!value) value } chop_rectangular_df <- function(x, names) { n_col <- vec_size(names) n_row <- vec_size(x) / n_col indices <- vector("list", n_col) start <- 1L stop <- n_row for (i in seq_len(n_col)) { indices[[i]] <- seq2(start, stop) start <- start + n_row stop <- stop + n_row } out <- vec_chop(x, indices) names(out) <- names tibble::new_tibble(out, nrow = n_row) } is_scalar <- function(x) { if (is.null(x)) { return(FALSE) } if (vec_is_list(x)) { (vec_size(x) == 1) && !have_name(x) } else { vec_size(x) == 1 } } backtick_if_not_syntactic <- function(x) { ok <- make.names(x) == x ok[is.na(x)] <- FALSE x[!ok] <- glue::backtick(x[!ok]) x }
zb_doughnut = function(x = NULL, area = NULL, n_circles = NA, distance = 1, distance_growth = 1) { zb_zone(x = x, area = area, n_circles = n_circles, distance = distance, distance_growth = distance_growth, n_segments = 1) } create_rings = function(point, n_circles, distance) { csdistance = cumsum(distance) circles = lapply(csdistance * 1000, function(d) { doughnut_i = sf::st_buffer(point, d) }) doughnuts_non_center = mapply(function(x, y) sf::st_sf(geometry = sf::st_difference(x, y)), circles[-1], circles[-n_circles], SIMPLIFY = FALSE) doughnuts = do.call(rbind, c(list(sf::st_sf(geometry = circles[[1]])), doughnuts_non_center)) doughnuts }
targets::tar_test("tar_group_count_run()", { skip_if_not_installed("dplyr") data <- expand.grid( var1 = c("a", "b"), var2 = c("c", "d"), rep = c(1, 2, 3), stringsAsFactors = FALSE ) out <- tar_group_count_run(data, 12) expect_equal(out$tar_group, seq_len(12)) out <- tar_group_count_run(data, 1) expect_equal(out$tar_group, rep(1, 12)) out <- tar_group_count_run(data, 4) expect_equal(out$tar_group, rep(seq_len(4), each = 3)) out <- tar_group_count_run(data, 3) expect_equal(out$tar_group, rep(seq_len(3), each = 4)) for (count in seq_len(20)) { out <- tar_group_count_run(data, count) expect_true(is.data.frame(out)) } }) targets::tar_test("tar_group_count()", { skip_if_not_installed("dplyr") targets::tar_script({ produce_data <- function() { expand.grid( var1 = c("a", "b"), var2 = c("c", "d"), rep = c(1, 2, 3), stringsAsFactors = FALSE ) } list( tarchetypes::tar_group_count(data, produce_data(), 3), tar_target(group, data, pattern = map(data)) ) }) targets::tar_make(callr_function = NULL) expect_equal(length(tar_meta(group)$children[[1]]), 3L) for (branch in seq_len(3L)) { out <- targets::tar_read(group, branches = branch) expect_equal(nrow(out), 4L) } out <- targets::tar_read(group) expect_equal(nrow(out), 12L) expect_equal(nrow(dplyr::distinct(out, var1, var2, rep)), 12L) })
bugsModel <- function(formula, fd, sd, random = NULL, modelname = "bugmodel", wd = getwd()) { fd <- tolower(fd) sd <- tolower(sd) modelpart01 <- "\n model {\n pi <- 3.14159265358979\n for (i in 1:N) { \n dummy[i] <- 0\n dummy[i] ~ dloglik(logLike[i]) \n " likelihood <- bugsLikelihood(fd, sd) nodes_sample <- c("b_0", "d_0") init1 <- list(0.1, 0.1) formula <- as.Formula(formula) lxterm <- labels(terms(formula, rhs = 1L)) if (length(attr(formula, "rhs")) > 1) { dxterm <- labels(terms(formula, rhs = 2L)) } else { dxterm <- list() } lm <- "mu[i] <- b_0" lp_prior <- "b_0 ~dnorm(0.0, 1.0E-6)" if (length(lxterm) != 0) { for (i in 1:length(lxterm)) { lm <- paste(lm, " + b_", gsub(":", "_", x = lxterm[i]), "*", gsub(":", "[i]*", x = lxterm[i]), "[i]", sep = "") lp_prior <- paste(lp_prior, "\nb_", gsub(":", "_", x = lxterm[i]), "~dnorm(0.0, 1.0E-6)", sep = "") init1 <- c(init1, 0.1) nodes_sample <- c(nodes_sample, paste("b_", gsub(":", "_", x = lxterm[i]), sep = "")) } } dm <- "log(sigma[i]) <- d_0" dp_prior <- "d_0 ~ dnorm(0.0, 1.0E-6)" if (length(dxterm) != 0) { for (i in 1:length(dxterm)) { dm <- paste(dm, " + d_", gsub(":", "_", x = dxterm[i]), "*", gsub(":", "[i]*", x = dxterm[i]), "[i]", sep = "") dp_prior <- paste(dp_prior, "\nd_", gsub(":", "_", x = dxterm[i]), "~dnorm(0.0, 1.0E-6)", sep = "") init1 <- c(init1, 0.1) nodes_sample <- c(nodes_sample, paste("d_", gsub(":", "_", x = dxterm[i]), sep = "")) } } if (!is.null(random)) { formulas_random <- NULL for (i in 1:length(random)) { lm <- paste(lm, " + u_", random[i], "[", random[i], "[i]]", sep = "") formulas_random <- paste(formulas_random, "\n for (j in 1:J_", random[i], ")\n {\n u_", random[i], "[j] ~ dnorm(0,tau_", random[i], ") \n", sep = "") lp_prior <- paste(lp_prior, "\ntau_", random[i], " <- exp(2*lsu_", random[i], ")\n lsu_", random[i], "~ dnorm(0.5, 1.0E-6)\n", sep = "") init1 <- c(init1, 0.5) nodes_sample <- c(nodes_sample, paste("lsu_", random[i], sep = "")) } formulas <- paste(lm, "\n", dm, "\n", "}\n", formulas_random, sep = "") } if (is.null(random)) formulas <- paste(lm, "\n", dm, "\n", sep = "") Priors <- paste("}\n", lp_prior, "\n", dp_prior, "\n", sep = "") model <- paste(modelpart01, likelihood, "\n", formulas, Priors, "\n}", sep = "") cat(model, file = paste(wd, "/", modelname, ".txt", sep = "")) names(init1) <- nodes_sample init2 <- init1 list(init1 = init1, init2 = init2, nodes_sample = nodes_sample, vars = attr(terms(formula), "variables")) }
looic <- function(model, verbose = TRUE) { insight::check_if_installed("loo") algorithm <- insight::find_algorithm(model) if (algorithm$algorithm != "sampling") { if (verbose) { warning(insight::format_message("`looic()` only available for models fit using the 'sampling' algorithm."), call. = FALSE) } return(NA) } res_loo <- tryCatch( { loo::loo(model) }, error = function(e) { if (inherits(e, c("simpleError", "error"))) { insight::print_color(e$message, "red") cat("\n") } NULL } ) loo_df <- res_loo$estimates if (is.null(loo_df)) { return(NULL) } out <- list( ELPD = loo_df["elpd_loo", "Estimate"], ELPD_SE = loo_df["elpd_loo", "SE"], LOOIC = loo_df["looic", "Estimate"], LOOIC_SE = loo_df["looic", "SE"] ) attr(out, "loo") <- res_loo[c("pointwise", "diagnostics")] structure(class = "looic", out) } as.data.frame.looic <- function(x, row.names = NULL, ...) { data.frame( ELPD = x$ELPD, ELPD_SE = x$ELPD_SE, LOOIC = x$LOOIC, LOOIC_SE = x$LOOIC_SE, stringsAsFactors = FALSE, row.names = row.names, ... ) }
heplot.cancor <- function ( mod, which=1:2, scale, asp=1, var.vectors = "Y", var.col=c("blue", "darkgreen"), var.lwd=par("lwd"), var.cex=par("cex"), var.xpd=TRUE, prefix = "Ycan", suffix = TRUE, terms=TRUE, ... ) { if (!inherits(mod, "cancor")) stop("Not a cancor object") if (mod$ndim < 2 || length(which)==1) { message("Can't do a 1 dimensional canonical HE plot") return() } Yvars <- mod$names$Y scores <- data.frame(mod$scores$X, mod$scores$Y) scores <- data.frame(scores, mod$X) Xcoef <- mod$coef$X Ycoef <- mod$coef$Y Ycan <- colnames(Ycoef) canr <- mod$cancor lambda <- canr^2 / (1-canr^2) pct = 100*lambda / sum(lambda) if ((is.logical(terms) && terms) || terms=="X") { terms <- mod$names$X } else if (length(terms)==1 && terms=="Xcan") terms=colnames(Xcoef) if (!all(terms %in% colnames(scores))) { stop(paste(setdiff(terms, colnames(scores) ), "are not among the available variables")) } txt <- paste( "lm( cbind(", paste(Ycan, collapse = ","), ") ~ ", paste( terms, collapse = "+"), ", data=scores)" ) can.mod <- eval(parse(text=txt)) canvar <- Ycan[which] if (is.logical(suffix) & suffix) suffix <- paste( " (", round(pct[which],1), "%)", sep="" ) else suffix <- NULL canlab <- paste(prefix, which, suffix, sep="") ellipses <- heplot(can.mod, terms=terms, xlab=canlab[1], ylab=canlab[2], asp=asp, ...) struc <- mod$structure Xstructure <- struc$X.yscores[,which] Ystructure <- struc$Y.yscores[,which] vec <- rbind( if ("Y" %in% var.vectors) Ystructure else NULL, if ("X" %in% var.vectors) Xstructure else NULL) maxrms <- function(x) { max(sqrt(apply(x^2, 1, sum))) } if (missing(scale)) { vecrange <- range(vec) ellrange <- lapply(ellipses, range) vecmax <- maxrms(vec) ellmax <- max( maxrms(ellipses$E), unlist(lapply(ellipses$H, maxrms)) ) scale <- floor( 0.9 * ellmax / vecmax ) cat("Vector scale factor set to ", scale, "\n") } if ("Y" %in% var.vectors) vectors(Ystructure, scale=scale, col=var.col[1], lwd=var.lwd, cex=var.cex, xpd=var.xpd) if ("X" %in% var.vectors) vectors(Xstructure, scale=scale, col=var.col[2], lwd=var.lwd, cex=var.cex, xpd=var.xpd) invisible(ellipses) }
test_that("getDailyMaxResults for OBK Data", { para <- babsimHospitalPara() conf <- babsimToolsConf() ICU <- FALSE set.seed(conf$seed) data <- dataCovidBeds20200624 conf$simulationDates$StartDate <- min(data$Day) arrivalTimes <- getArrivalTimes(data$Infected) envs <- babsimHospital( arrivalTimes = arrivalTimes, conf = conf, para = para ) fieldData <- getRealBeds( data = data, resource = c("bed", "intensiveBed", "intensiveBedVentilation") ) res <- getDailyMaxResults( envs = envs, fieldEvents = fieldData, conf = conf ) resources <- get_mon_resources(envs) resources$time <- round(resources$time) min(resources$time) max(resources$time) min(fieldData$time) max(fieldData$time) StartDate <- as.Date(min(fieldData$date)) EndDate <- as.Date(max(fieldData$date)) data <- babsim.hospital::dataCovidBeds20200624 conf$simulationDates$StartDate <- min(data$Day) amntDaysLateStart <- as.numeric(StartDate - conf$simulationDates$StartDate) resources <- resources %>% dplyr::filter(time >= amntDaysLateStart) observedPeriod <- as.numeric(EndDate - StartDate) finalTimeICU <- amntDaysLateStart + observedPeriod resources <- resources %>% dplyr::filter(time <= finalTimeICU) resourcesMaxSystem <- resources %>% dplyr::group_by(resource, time) %>% dplyr::mutate(upper = max(system)) %>% dplyr::mutate(lower = min(system)) %>% dplyr::mutate(med = median(system)) unique(resources$time == resourcesMaxSystem$time) expect_true(unique(resources$time == resourcesMaxSystem$time)) resourcesMaxSystem$date <- as.Date(as.POSIXct((resourcesMaxSystem$time) * 24 * 60 * 60, origin = conf$simulationDates$StartDate)) expect_true(StartDate <= min(resourcesMaxSystem$date)) expect_true(EndDate >= max(resourcesMaxSystem$date)) n <- dim(fieldData)[1] fieldData$server <- fieldData$med fieldData$queue <- rep(0, n) fieldData$capacity <- rep(Inf, n) fieldData$queue_size <- rep(Inf, n) fieldData$system <- fieldData$med fieldData$limit <- rep(Inf, n) fieldData$replication <- rep(1, n) fieldData$upper <- fieldData$med fieldData$lower <- fieldData$med resourcesMaxSystem$source <- "babsim" resourcesMaxSystem <- dplyr::bind_rows(resourcesMaxSystem, fieldData) expect_true(StartDate <= min(resourcesMaxSystem$date)) expect_true(EndDate >= max(resourcesMaxSystem$date)) })
date2winter<-function(x,first=10,last=4){ if(!first%in%1:12) stop("'first' must be a month number") if(!last%in%1:12) stop("'last' must be a month number") if (inherits(x,"POSIXct")) x<-as.POSIXlt(x) if (!inherits(x,"POSIXlt")) stop("x must be of class POSIXct or POSIXlt") res<-ifelse((x$mon+1)>last & (x$mon+1)<first,"Excluded",ifelse((x$mon+1)>=first,paste(x$year+1900,"-",x$year+1900+1,sep=""),paste(x$year+1900-1,"-",x$year+1900,sep=""))) attributes(res)$span<-c(first=first,last=last) res }
clme_em_fixed <- function( Y, X1, X2 = NULL, U = NULL, Nks = dim(X1)[1], Qs = dim(U)[2], constraints, mq.phi = NULL, tsf = lrt.stat, tsf.ind = w.stat.ind, mySolver="LS", em.iter = 500, em.eps = 0.0001, all_pair = FALSE, dvar = NULL, verbose = FALSE, ... ){ if( verbose==TRUE ){ message("Starting EM algorithm") } N <- sum(Nks) N1 <- 1 + cumsum(Nks) - Nks N2 <- cumsum(Nks) X <- as.matrix(cbind(X1, X2)) theta.names <- NULL if( is.null(colnames(X))==FALSE ){ theta.names <- colnames(X) } K <- length(Nks) P1 <- dim(X1)[2] P2 <- dim(X2)[2] if( is.null(constraints$A) ){ const <- create.constraints( P1, constraints) A <- const$A Anull <- const$Anull B <- const$B } else{ A <- constraints$A Anull <- constraints$Anull B <- constraints$B if( is.null(Anull) ){ Anull <- create.constraints( P1, list(order="simple", node=1, decreasing=TRUE) )$Anull } } theta <- ginv( t(X)%*%X) %*% ( t(X)%*%Y ) R <- Y-X%*%theta ssq <- apply( as.matrix(1:K, nrow=1), 1 , FUN=function(k, N1, N2, R ){ sum( R[N1[k]:N2[k]]^2 ) / Nks[k] } , N1, N2, R) var_fix <- (ssq <= .Machine$double.eps ) if( any(var_fix) ){ ssq[ var_fix==1 ] <- dvar[var_fix==1] } ssqvec <- rep( ssq, Nks ) tsq <- NULL theta1 <- theta ssq1 <- ssq tsq1 <- tsq CONVERGE <- 0 iteration <- 0 while( CONVERGE==0 ){ iteration <- iteration+1 R <- Y-X%*%theta if( verbose==TRUE ){ message( "EM iteration " , iteration) } trace.vec <- (R/ssqvec)^2 - 1/ssqvec ssq <- apply( as.matrix(1:K, nrow=1), 1 , FUN=function(k, ssq, Nks, N1, N2 , trv){ idx <- N1[k]:N2[k] ssq[k] + ( (ssq[k]^2)/(Nks[k]) )*sum( trv[idx] ) } , ssq , Nks , N1 , N2 , trace.vec ) if( any(var_fix) ){ ssq[ var_fix==1 ] <- dvar[ var_fix==1 ] } ssqvec <- rep( ssq, Nks) SiR <- R / ssqvec theta[1:P1] <- theta1[1:P1] + ginv( t(X1)%*%(X1/ssqvec) ) %*% (t(X1) %*% SiR) if( is.null(X2)==FALSE ){ X2SiR <- t(X2) %*% SiR theta[(P1+1):(P1+P2)] <- ( theta1[(P1+1):(P1+P2)] + ginv(t(X2)%*%(X2/ssqvec)) %*% (X2SiR) ) } cov.theta <- solve( t(X) %*% (X/ssqvec) ) if( all_pair==FALSE ){ if( mySolver=="GLS"){ wts <- solve( cov.theta )[1:P1, 1:P1, drop=FALSE] } else{ wts <- diag( solve(cov.theta) )[1:P1] } theta[1:P1] <- activeSet(A, y = theta[1:P1], weights = wts, mySolver=mySolver )$x } rel.change <- abs(theta - theta1)/theta1 if( mean(rel.change) < em.eps || iteration >= em.iter ){ CONVERGE <- 1 } else{ theta1 <- theta ssq1 <- ssq } } if( verbose==TRUE ){ message("EM Algorithm ran for " , iteration , " iterations." ) } wts <- diag( solve(cov.theta) )[1:P1] theta <- c(theta) names(theta) <- theta.names theta.null <- theta theta.null[1:P1] <- activeSet( Anull, y = theta[1:P1], weights = wts , mysolver=mySolver )$x ts.glb <- tsf( theta=theta, theta.null=theta.null, cov.theta=cov.theta, B=B, A=A, Y=Y, X1=X1, X2=X2, U=U, tsq=tsq, ssq=ssq, Nks=Nks, Qs=Qs ) ts.ind <- tsf.ind(theta=theta, theta.null=theta.null, cov.theta=cov.theta, B=B, A=A, Y=Y, X1=X1, X2=X2, U=U, tsq=tsq, ssq=ssq, Nks=Nks, Qs=Qs ) em.results <- list(theta=theta, theta.null=theta.null, ssq=ssq, tsq=tsq, cov.theta=cov.theta, ts.glb=ts.glb, ts.ind=ts.ind, mySolver=mySolver ) return( em.results ) }
opt_fill <- function( x , opts = commandArgs() , style = getOption('optigrab')$style ) { if( ! is.recursive(x) ) stop( "'opt_fill' only works for recursive structures: list, environment, etc.") for( nm in names(x) ) { default = x[[nm]] val = opt_get( name=nm, opts=opts, style=style, default=default ) x[[nm]] = ifelse( ! is.na(val), val, x[[nm]] ) } if( is.environment(x) ) return( invisible(x) ) else return(x) }
position_identity_ <- function() { PositionIdentity_ } PositionIdentity_ <- ggproto("PositionIdentity_", ggplot2::PositionIdentity, setup_params = function(self, data) { list(positive = has_positive(data), flipped_aes = ggplot2::has_flipped_aes(data)) }, compute_layer = function(data, params, scales) { data <- ggplot2::flip_data(data, flip = params$flipped_aes) positive <- data$positive %||% params$positive data %>% dplyr::mutate( positive = positive, y = ifelse(positive, y + location, -y + location), ymin = ifelse(positive, ymin + location, -ymin + location), ymax = ifelse(positive, ymax + location, -ymax + location) ) %>% ggplot2::flip_data(flip = params$flipped_aes) } )
NMixPlugDensJoint2.default <- function(x, scale, w, mu, Sigma, ...) { if (!is.list(x)) stop("x must be a list") p <- length(x) if (p < 2) stop("length of x must be 2 or more") LTp <- p * (p + 1)/2 if (is.null(names(x))) names(x) <- paste("x", (1:p), sep="") if (missing(scale)) scale <- list(shift=rep(0, p), scale=rep(1, p)) if (!is.list(scale)) stop("scale must be a list") if (length(scale) != 2) stop("scale must have 2 components") inscale <- names(scale) iscale.shift <- match("shift", inscale, nomatch=NA) iscale.scale <- match("scale", inscale, nomatch=NA) if (is.na(iscale.shift)) stop("scale$shift is missing") if (length(scale$shift) == 1) scale$shift <- rep(scale$shift, p) if (length(scale$shift) != p) stop(paste("scale$shift must be a vector of length ", p, sep="")) if (is.na(iscale.scale)) stop("scale$scale is missing") if (length(scale$scale) == 1) scale$scale <- rep(scale$scale, p) if (length(scale$scale) != p) stop(paste("scale$scale must be a vector of length ", p, sep="")) if (any(scale$scale <= 0)) stop("all elements of scale$scale must be positive") K <- length(w) if (any(w < 0) | any(w > 1)) stop("weights must lie between zero and 1") if (abs(sum(w) - 1) > 1e-5) warning("sum of weights differs from 1") if (K == 1){ if (length(mu) != p) stop("incorrect mu") mu <- matrix(mu, nrow=K, ncol=p) if (!is.list(Sigma)) Sigma <- list(Sigma) } if (nrow(mu) != K) stop(paste("mu must have ", K, " rows", sep="")) if (ncol(mu) != p) stop(paste("mu must have ", p, " columns", sep="")) if (any(!sapply(Sigma, is.matrix))) stop("all Sigma's must be matrices") if (any(sapply(Sigma, nrow) != p)) stop(paste("all Sigma's must have ", p, " rows", sep="")) if (any(sapply(Sigma, ncol) != p)) stop(paste("all Sigma's must have ", p, " columns", sep="")) mu <- mu * matrix(rep(scale$scale, K), nrow=K, ncol=p, byrow=TRUE) + matrix(rep(scale$shift, K), nrow=K, ncol=p, byrow=TRUE) for (k in 1:K) Sigma[[k]] <- diag(scale$scale) %*% Sigma[[k]] %*% diag(scale$scale) n <- sapply(x, length) if (any(n <= 0)) stop("incorrect x supplied") RET <- list(x=x, dens=list()) if (p == 2){ GRID <- cbind(rep(x[[1]], n[2]), rep(x[[2]], each=n[1])) RET$dens[[1]] <- matrix(dMVNmixture2(x=GRID, weight=w, mean=mu, Sigma=Sigma), nrow=n[1], ncol=n[2]) names(RET$dens) <- "1-2" }else{ pp <- 1 NAMEN <- character(0) for (m0 in 1:(p-1)){ for (m1 in (m0+1):p){ GRID <- cbind(rep(x[[m0]], n[m1]), rep(x[[m1]], each=n[m0])) MEAN <- mu[, c(m0, m1)] SIGMA <- list() for (k in 1:K) SIGMA[[k]] <- Sigma[[k]][c(m0, m1), c(m0, m1)] RET$dens[[pp]] <- matrix(dMVNmixture2(x=GRID, weight=w, mean=MEAN, Sigma=SIGMA), nrow=n[m0], ncol=n[m1]) NAMEN <- c(NAMEN, paste(m0, "-", m1, sep="")) pp <- pp + 1 } } names(RET$dens) <- NAMEN } class(RET) <- "NMixPlugDensJoint2" return(RET) }
rm(list=ls()) d<-read.csv("~/data/abomb/lsshempy.csv",header=T) head(d,2) d=d[d$mar_an>=0,] sum(d$cml) d=within(d,{rm(distcat,agxcat, agecat, dcat, time,upyr,subjects,year, nhl,hl,mye,all,oll,alltot,cll,hcl,clltot,atl,aml,oml,amol,amltot, othleuk,noncll,leuktot,hldtot,mar_ag,mar_an)}) head(d,2) d=within(d, {nic = as.numeric(gdist > 12000) over4gy = 1 - un4gy rm(gdist,un4gy) tsx = (age -agex) lt25 = log(tsx/25) a = log(age/70) a55 = log(age/55) ; age55=age-55 agex30=agex-30 ax30 = log(agex/30) ; py10k = pyr/10000 ; py = pyr; s=sex-1 c=city-1 sv=mar_ad10/1000; hiro = as.numeric(city == 1) naga = as.numeric(city ==2) rm(sex,city,pyr,mar_ad10) }) head(d) bk=d[d$sv<0.05,] library(bbmle) summary(pow1<-mle2(cml~dpois(lambda=py10k*A*exp(cs*s+(ca+csa*s)*a)), start=list(A=.22,cs=-0.06,ca=1.38,csa=1.75),data=bk) ) summary(exp1k<-mle2(cml~dpois(lambda=py10k*A*exp(cs*s+k*age55)), start=list(A=.22,cs=-0.6,k=0.04),data=bk) ) summary(exp2k<-mle2(cml~dpois(lambda=py10k*A*exp(cs*s+(k+ks*s)*age55)), start=list(A=.22,cs=-0.6,k=0.03,ks=.02),data=bk) ) AIC(pow1,exp1k,exp2k) ICtab(pow1,exp1k,exp2k) BIC(pow1,exp1k,exp2k) summary(err<-mle2(cml~dpois(lambda=py10k*(A1*exp(c1s*s+c1a*a+c1sa*a*s+c1nic0*hiro*nic+c1nic1*naga*nic)* (1+sv*A2*exp(c2c*c + c2t*lt25 + c2a*a55+c2o4g*over4gy) ) ) ), start=list(A1=.22,c1s=-0.06,c1a=1.38,c1sa=1.75,c1nic0=-0.2,c1nic1=-0.86, A2=5.24,c2c=-1.50,c2t=-1.59,c2a=-1.42,c2o4g=-0.3),data=d) ) AIC(err) logLik(err) deviance(err) prd=predict(err) -2*sum(d$cml*log(prd)) -2*sum(d$cml*log(prd))+2*length(coef(err)) -2*sum(d$cml*log(prd)-prd-log(factorial(d$cml))) -2*sum(d$cml*log(prd)-prd) sum(prd) summary(ear<-mle2(cml~dpois(lambda=py10k*(A1*exp(c1s*s+c1a*a+c1sa*a*s+c1nic0*hiro*nic+c1nic1*naga*nic) +sv*A2*exp(c2c*c + c2s*s+c2t*lt25 + c2a*a55+c2sa*s*a55+c2o4g*over4gy) ) ) , start=list(A1=.22,c1s=-0.06,c1a=1.38,c1sa=1.75,c1nic0=-0.2,c1nic1=-0.86, A2=5.24,c2c=-1.50,c2s=-0.18,c2t=-1.59,c2a=-1.42,c2sa=2.3,c2o4g=-0.3),data=d) ) prd=predict(ear) -2*sum(d$cml*log(prd)) -2*sum(d$cml*log(prd))+2*length(coef(ear)) AIC(err,ear) ICtab(err,ear) anova(err,ear) summary(s1<-mle2(cml~dpois(lambda=py*(exp(c10+c2c*c+c2s*s+k*age+ks*s*age) +sv*exp(c20+c2c*c + c2s*s+c2t*tsx+c2ts*s*tsx) ) ), start=list(c10=-12.4,k=0.025,ks=0,c20=-10.5,c2c=-1.50,c2s=-0.18,c2t=-0.4,c2ts=0.3),data=d) ) prd=predict(s1) -2*sum(d$cml*log(prd)) -2*sum(d$cml*log(prd))+2*length(coef(s1)) ICtab(err,s1) anova(err,s1) summary(s1a55<-mle2(cml~dpois(lambda=py*(exp(c10+c2c*c+c2s*s+k*age+ks*s*age) +sv*exp(c20+c2c*c + c2s*s+c2t*tsx+c2ts*s*tsx + c2a*a55+c2sa*s*a55 ) ) ), start=list(c10=-12.4,k=0.025,ks=0,c20=-10.5,c2c=-1.50, c2s=-0.18,c2t=-0.4,c2ts=0.3,c2a=-1.42,c2sa=2.3),data=d) ) prd=predict(s1a55) -2*sum(d$cml*log(prd)) -2*sum(d$cml*log(prd))+2*length(coef(s1a55)) ICtab(err,s1a55) anova(err,s1a55) summary(s1a55f<-mle2(cml~dpois(lambda=py*(exp(c10+c2c*c+c2s*s+(k+ks*s)*age) +sv*exp(c20+c2c*c + c2s*s+c2t*tsx+c2ts*s*tsx +c2sa*s*a55 ) ) ), start=list(c10=-12.4,k=0.025,ks=0,c20=-10.5,c2c=-1.50, c2s=-0.18,c2t=-0.4,c2ts=0.3,c2sa=2.3),data=d) ) prd=predict(s1a55f) -2*sum(d$cml*log(prd)) -2*sum(d$cml*log(prd))+2*length(coef(s1a55f)) ICtab(err,s1a55f) anova(err,s1a55f) summary(s1tsx<-mle2(cml~dpois(lambda=py*(exp(c10+c2c*c+c2s*s+(k+ks*s)*age) +sv*tsx*exp(c20+c2c*c + c2s*s+c2t*tsx+c2ts*s*tsx +c2sa*s*a55 ) ) ), start=list(c10=-12.4,k=0.025,ks=0,c20=-10.5,c2c=-1.50, c2s=-0.18,c2t=-0.4,c2ts=0.3,c2sa=2.3),data=d) ) prd=predict(s1tsx) -2*sum(d$cml*log(prd)) -2*sum(d$cml*log(prd))+2*length(coef(s1tsx)) ICtab(s1tsx,s1a55f) a55HMb<-mle2(cml~dpois(lambda=py*(exp(c10+c2c*c+c2s*s+k*age+ks*s*age) + sv*tsx*exp(c20+c2c*c + c2s*s+c2t*tsx+c2ts*s*tsx +c2sa*s*a55+ c2x*(1-c)*(1-s)*abs(agex-30)) ) ), start=list(c10=-12.4,k=0.025,ks=0,c20=-10.5,c2c=-1.50, c2s=-0.18,c2t=-0.4,c2ts=0.3,c2x=.1,c2sa=2.3),data=d) prd=predict(a55HMb) -2*sum(d$cml*log(prd)) -2*sum(d$cml*log(prd))+2*length(coef(a55HMb)) summary(a55HMb) AIC(a55HMb,s1tsx) ICtab(a55HMb,s1tsx) anova(a55HMb,s1tsx) summary(best<-mle2(cml~dpois(lambda=py*(exp(c10+c2c*c+c2s*s+k*age+ks*s*age) +sv*tsx*exp(c20+c2c*c + c2s*s-tsx/(c2t+c2ts*s) +c2sa*s*a55 ) ) ), start=list(c10=-12.4,k=0.025,ks=0,c20=-10.5,c2c=-1.50, c2s=-0.18,c2t=5,c2ts=10,c2sa=2.3),data=d) ) prd=predict(best) -2*sum(d$cml*log(prd)) -2*sum(d$cml*log(prd))+2*length(coef(best)) AIC(s1tsx,best) ICtab(err,best) anova(err,best) summary(best) summary(bestT<-mle2(cml~dpois(lambda=py*(exp(c10+c2c*c+c2s*s+k*age) +sv*tsx*exp(c20+c2c*c + c2s*s-tsx/(c2t+c2ts*s) +c2sa*s*a55 ) ) ), start=list(c10=-12.4,k=0.025,c20=-10.5,c2c=-1.50, c2s=-0.18,c2t=5,c2ts=10,c2sa=2.3),data=d) ) prd=predict(bestT) -2*sum(d$cml*log(prd)) anova(best,bestT) BICtab(best,bestT) ICtab(best,bestT) (sb=summary(best)) (outs=round(coef(sb),4)) rownames(outs)[c(1,4:8)]<-c("c1hm","c2hm","cn","cs","tau","taus") outs library(hwriter) sd=coef(sb)["c2ts",2] mn=coef(best)["c2ts"] (tauDiff=round(2*c(mn,mn-1.96*sd,mn+1.96*sd),2)) sprintf("%s (%s, %s)",tauDiff[1],tauDiff[2],tauDiff[3]) (Taum=coef(best)["c2t"]) (Tauf=Taum + mn) sdA=coef(sb)["c2s",2] mnA=coef(best)["c2s"] (MovF=round((Taum/Tauf)^2*exp(-c(mnA,mnA+1.96*sdA,mnA-1.96*sdA)),2)) sprintf("%s (%s, %s)",MovF[1],MovF[2],MovF[3]) d=transform(d,tsxf=cut(tsx,6),sex=as.factor(s)) head(d) summary(s3<-mle2(cml~dpois(lambda=py*(exp(c10 + c2c*c + c2s*s + k*age + ks*s*age) +sv*exp(c2c*c + f + c2sa*s*a55 ) ) ), parameters=list(f~-1 + tsxf:sex), start=list(c10=-12.4,k=0.025,ks=0,c2c=-1.50, c2s=-0.18,f=-5,c2sa=2),data=d) ) prd=predict(s3) -2*sum(d$cml*log(prd)) -2*sum(d$cml*log(prd))+2*length(coef(s3)) AIC(s3,best) ICtab(s3,best) anova(s3,best) ss3=summary(s3) wait=exp(coef(ss3)[6:17,1])*1e4 waitL=exp(coef(ss3)[6:17,1]-1.96*coef(ss3)[6:17,2])*1e4 waitU=exp(coef(ss3)[6:17,1]+1.96*coef(ss3)[6:17,2])*1e4 (lvls=levels(d$tsxf)) (Lvls=strsplit(lvls,",")) substring("(4.23",2) (lows=sapply(Lvls,function(x) as.numeric(substring(x[1],2)))) (ups=sapply(Lvls,function(x) as.numeric(substring(x[2],1,4)))) (mids=round(apply(rbind(lows,ups),2,mean),2)) (dfc=data.frame(mids,wait,waitL,waitU,Sex=gl(2,6,labels=c("Male","Female") ) ) ) graphics.off() if(length(grep("linux",R.Version()$os))) windows <- function( ... ) X11( ... ) if(length(grep("darwin",R.Version()$os))) windows <- function( ... ) quartz( ... ) windows(width=7,height=6) library(ggplot2) pd <- position_dodge(1) (p=ggplot(dfc, aes(x=mids, y=wait, shape=Sex, col=Sex, ymax=10)) + geom_point(size=6,position=pd) ) (p=p+labs(title="IR-to-CML Latency",x="Years since exposure", y=expression(paste("Cases per ",10^4," Person-Year-Sv") ) ) ) (p=p+geom_errorbar(aes(ymin=waitL, ymax=waitU),width=.01,position=pd)) (p=p+theme(plot.title = element_text(size = rel(2.3)), axis.title = element_text(size = rel(2.3)), axis.text = element_text(size = rel(2.3))) ) (p=p+theme(legend.position = c(0.8, .5), legend.title = element_text(size = rel(2)) , legend.text = element_text(size = rel(2)) ) ) waitm=exp(coef(ss3)[6:11,1]) waitf=exp(coef(ss3)[12:17,1]) (MovF<-format(sum(waitm)/sum(waitf),digits=3)) mns=coef(ss3)[6:17,1] sds=coef(ss3)[6:17,2] X=exp(matrix(rnorm(12*100000,mns,sds),byrow=T, ncol=12)) M=X[,1:6]; F=X[,7:12] Ms=apply(M,1,sum) Fs=apply(F,1,sum) MovF=Ms/Fs MF=round(quantile(MovF,c(0.5,0.025,0.975)),2) (MF=sprintf("%s (%s, %s)",MF[1],MF[2],MF[3])) pm=waitm/sum(waitm) pf=waitf/sum(waitf) (taum<-round(mids%*%pm,2)) (tauf<-round(mids%*%pf,2)) (p=p+annotate("text",x=15,y=10, hjust=0, label = paste("M/F =",MF),size=9) ) (lb1=paste0("tau[m] == ",taum,"*~Yrs")) (p=p+annotate("text",x=15,y=9, hjust=0, label = lb1,size=9,parse=T) ) (lb1=paste0("tau[f] == ",tauf,"*~Yrs")) (p=p+annotate("text",x=15,y=8, hjust=0, label = lb1,size=9,parse=T) ) rdiscrete <- function(n, probs,values) { cumprobs <- cumsum(probs) singlenumber <- function() { x <- runif(1) N <- sum(x > cumprobs) N } values[replicate(n, singlenumber())+1] } x=rdiscrete(1e5,pf,mids) summary(as.factor(x)) y=rdiscrete(1e5,pm,mids) summary(as.factor(y)) (delT=quantile(x-y,c(0.025,0.975))) (lb1=paste0("Delta*tau == ",tauf-taum,"(",delT[1],", ",delT[2],")")) (p=p+annotate("text",x=15,y=7, hjust=0, label = lb1,size=7,parse=T) ) sprintf("%s (%s, %s)",tauf-taum,delT[1],delT[2]) k=0.025 Tp=22.1 Rp=1.73 Tf=-15:23 fR=function(Tf) exp(-k*(Tf-Tp)) R=fR(Tf) par(mar=c(4.5,4.5,0,.5)) plot(Tf,R,type="l",lwd=2.5,cex.lab=1.6,cex.axis=1.5, ylab="(male risk)/(female risk) M/F", xlab="extra female latency time T in years",axes=F,font=2) mtext(side=3,line=-4,"Continuum of SEER CML\n Sex Difference Interpretations",cex=1.5,font=1) points(x=c(0,Tp),y=c(Rp,1),pch=1,cex=3,lwd=3) abline(h=1,v=0,lty=3) fT=function(R) Tp-log(R)/k x=seq(tauDiff[2],tauDiff[3],0.1) y=fR(x) points(x,y,type="l",lwd=7) rect(-1,1.13*Rp,23,1.26*Rp,lwd=2) text(12,1.2*Rp,"interpretations by\n a single cause",cex=1.4,font=1,bty="o") arrows(x0=0,y0=1.13*Rp,x1=0,y1=Rp+0.05,lwd=2,angle=20) arrows(x0=Tp,y0=1.13*Rp,x1=Tp,y1=1.05,lwd=2,angle=20) text(4,1.04*Rp,"higher\nmale\nrisk",cex=1.4,font=1) text(10,0.96*Rp,"or",cex=1.4,font=2) text(18,0.9*Rp,"shorter\nmale\nlatency",cex=1.4,font=1) text(-9,1.38, "interpretations\nconsistent with\ntime-since-\nexposure data\n(heavy line)", cex=1.4,font=1) arrows(x0=-2,y0=1.4,fT(1.4),y1=1.4,lwd=2,angle=20) graphics.off() if(length(grep("linux",R.Version()$os))) windows <- function( ... ) X11( ... ) if(length(grep("darwin",R.Version()$os))) windows <- function( ... ) quartz( ... ) windows(width=8,height=7) head(d) d$Dose<-cut(d$sv,c(-1,.02,1,100),labels=c("Low","Moderate","High")) d$Dose=factor(d$Dose,levels=c("High","Moderate","Low")) d$agexc<-cut(d$agex,c(0,20,40,180),labels=c("10","30","50")) d$Sex<-factor(d$s,labels=c("Male","Female")) head(d) library(plyr) (d2<-ddply(subset(d,c==0), .(Dose,Sex,agexc), summarise, PY=sum(py),cases=sum(cml),agex=weighted.mean(agex,py) )) (d2=within(d2,{incid=1e5*cases/PY})) library(ggplot2) (p <- ggplot(d2,aes(x=agex,y=incid,shape=Dose,col=Dose,group=Dose))+geom_point(size=5) +geom_line() + labs(title="Hiroshima A-bomb Survivors",x="Age-at-exposure (PY-weighted)", y=expression(paste("CML Cases per ",10^5," Person-Years"))) + scale_y_log10(limits=c(.1,130)) +xlim(8,52) ) (p=p + facet_grid(. ~ Sex)) (p=p+theme( legend.position = c(0.67, .85), legend.title = element_text(size = rel(2)) , legend.text = element_text(size = rel(1.3)) ) ) (p=p+theme(plot.title = element_text(size = rel(2)), strip.text = element_text(size = rel(2)), axis.title.y = element_text(size = rel(1.7)), axis.title.x = element_text(size = rel(1.7)), axis.text = element_text(size = rel(2))) ) if(length(grep("linux",R.Version()$os))) windows <- function( ... ) X11( ... ) if(length(grep("darwin",R.Version()$os))) windows <- function( ... ) quartz( ... ) windows(width=8,height=7) head(d) d$agec<-cut(d$age,c(0,30,60,180),labels=c("15","45","75")) d$Dose<-cut(d$sv,c(-1,.02,1,100),labels=c("Low","Moderate","High")) d$Sex<-factor(d$s,labels=c("Male","Female")) head(d) library(plyr) (d3<-ddply(subset(d,c==0), .(Dose,Sex,agec), summarise, PY=sum(py),cases=sum(cml),age=weighted.mean(age,py) )) (d3=within(d3,{incid=1e5*cases/PY})) library(ggplot2) (p <- ggplot(d3,aes(x=age,y=incid,shape=Dose,group=Dose))+geom_point(size=5) +geom_line() + labs(title="Hiroshima A-bomb Survivors",x="Attained-age (PY-weighted)", y=expression(paste("CML Cases per ",10^5," Person-Years"))) + scale_y_log10(limits=c(.1,130)) +xlim(8,90) ) (p=p + facet_grid(. ~ Sex)) (p=p+theme(legend.position = c(0.67, .85), legend.title = element_text(size = rel(2)) , legend.text = element_text(size = rel(1.7)) ) ) (p=p+theme(plot.title = element_text(size = rel(2.5)), strip.text = element_text(size = rel(2)), axis.title.y = element_text(size = rel(2.5)), axis.title.x = element_text(size = rel(2.3)), axis.text = element_text(size = rel(2.3))) )
httpget_session_zip <- function(sessionpath, requri){ setwd(sessionpath); allfiles <- list.files(all.files = TRUE, recursive = TRUE); tmpzip <- tempfile(fileext=".zip"); zip::zip(tmpzip, files = allfiles, recurse = FALSE); stoponwarn(utils::unzip(tmpzip)); res$setbody(file=tmpzip); res$setheader("Content-Type", "application/zip") res$setheader("Content-Disposition", paste('attachment; filename="', basename(sessionpath), '.zip"', sep="")); res$finish(); } stoponwarn <- function(...){ tryCatch(eval(...), warning=function(w){ stop("warning! ", w$message) }) }
NPMLE.Plackett <- function(x.trunc,y.trunc,x.fix = median(x.trunc), y.fix = median(y.trunc),plotX = TRUE){ m=length(x.trunc) x.ox=sort(unique(x.trunc)) y.oy=sort(unique(y.trunc)) nx=length(x.ox);ny=length(y.oy) dHx1=1;Hxn=0;Ay_1=0;dAyn=1 dHx_lyn=numeric(nx);dAy_lyn=numeric(ny) for(i in 1:nx){ tx=x.ox[nx-i+1] Rx=sum( (x.trunc<=tx)&(y.trunc>=tx) ) dHx_lyn[nx-i+1]=sum(tx==x.trunc)/Rx } for(i in 1:ny){ ty=y.oy[i] Ry=sum( (x.trunc<=ty)&(y.trunc>=ty) ) dAy_lyn[i]=sum(ty==y.trunc)/Ry } dL_lyn=log(c(dHx_lyn[-1],dAy_lyn[-ny])) l.plackett=function(dL){ dHx=c(dHx1,exp(dL[1:(nx-1)]));dAy=c(exp(dL[nx:(nx+ny-2)]),dAyn) Hx=c(rev(cumsum(rev(dHx)))[-1],Hxn);Ay_=c(Ay_1,cumsum(dAy)[-ny]) alpha=exp(dL[nx+ny-1]) prop=0 for(i in 1:nx){ temp_y=(y.oy>=x.ox[i]) dHxi=dHx[i];dAyi=dAy[temp_y] Fxi=exp(-Hx[i]);Sy_i=exp(-Ay_[temp_y]) B=1+(alpha-1)*(Fxi+Sy_i) C=(alpha-1)*Fxi*Sy_i c11=alpha*(B-2*C)/(B^2-4*alpha*C)^(3/2) prop=prop+sum(c11*Sy_i*dAyi*Fxi*dHxi) } l=-m*log(prop) for(i in 1:m){ x_num=sum(x.ox<=x.trunc[i]);y_num=sum(y.oy<=y.trunc[i]) Hxi=Hx[x_num];Ay_i=Ay_[y_num] dHxi=dHx[x_num];dAyi=dAy[y_num] Fxi=exp(-Hxi);Sy_i=exp(-Ay_i) B=1+(alpha-1)*(Fxi+Sy_i) C=(alpha-1)*Fxi*Sy_i l=l+log(alpha)+log(B-2*C)-3/2*log(B^2-4*alpha*C)-Hxi-Ay_i+log(dHxi)+log(dAyi) } -l } res=nlm(l.plackett,p=c(dL_lyn,log(0.9999)),hessian=TRUE) dL=res$estimate;conv=res$code alpha=exp(dL[nx+ny-1]) dHx=c(dHx1,exp(dL[1:(nx-1)])) dAy=c(exp(dL[nx:(nx+ny-2)]),dAyn) Hx_=rev(cumsum(rev(dHx)));Ay=cumsum(dAy) Fx=exp(-Hx_);Sy=exp(-Ay) Hx=c(Hx_[-1],Hxn) Ay_=c(Ay_1,Ay[-ny]) V_dL=solve(res$hessian) V=diag(exp(dL))%*%V_dL%*%diag(exp(dL)) SE_alpha=sqrt( V[nx+ny-1,nx+ny-1] ) Low=alpha*exp(-1.96*SE_alpha/alpha) Up=alpha*exp(1.96*SE_alpha/alpha) ML=-res$minimum iter=res$iterations Grad=res$gradient Min_eigen=min(eigen(res$hessian)$value) Hx_fix = Ay_fix = numeric(length(x.fix)) SE_Hx = SE_Ay = numeric(length(x.fix)) for (i in 1:length(x.fix)) { temp.x = c(x.ox >= x.fix[i]) Hx_fix[i] = Hx_[max(sum(x.ox <= x.fix[i]), 1)] SE_Hx[i] = sqrt((temp.x[-1]) %*% V[1:(nx - 1), 1:(nx - 1)] %*% (temp.x[-1])) } for (i in 1:length(y.fix)) { temp.y = c(y.oy <= y.fix[i]) Ay_fix[i] = Ay[max(sum(y.oy <= y.fix[i]), 1)] SE_Ay[i] = sqrt((temp.y[-ny]) %*% V[nx:(nx+ny-2),nx:(nx+ny-2)] %*% (temp.y[-ny])) } Fx_fix = exp(-Hx_fix) Sy_fix = exp(-Ay_fix) SE_Fx = Fx_fix * SE_Hx SE_Sy = Sy_fix * SE_Ay if (plotX == TRUE) { plot(x.ox, Fx, type = "s", xlab = "x", ylab = "Fx(x): Distribution function of X") } list( alpha = c(estimate=alpha, alpha_se = SE_alpha, Low95_alpha=Low, Up95_alpha=Up), Hx = c(estimate=Hx_fix, Hx_se = SE_Hx), Ay = c(estimate=Ay_fix, Ay_se = SE_Ay), Fx = c(estimate=Fx_fix, Fx_se = SE_Fx), Sy = c(estimate=Sy_fix, Sy_se = SE_Sy), ML=ML, convergence = conv,iteration=iter,Grad=sum(Grad^2),MinEigen=Min_eigen ) }
CNOT5_24 <- function(a){ cnot5_24=TensorProd(diag(2), CNOT4_13(diag(16))) result = cnot5_24 %*% a result }
seg2list <- function(data, segment="BATCH") { if (segment %in% names(data) != TRUE) { stop("Cannot find segment variable in data.frame.") } seg.ncol <- which(names(data) == segment) seg.col <- data[, seg.ncol] if (length(unique(seg.col)) == 1) { if (unique(seg.col) != 0) { return(list(data)) } else { return(NA) } } uni.seg <- unique(seg.col) uni.seg <- uni.seg[uni.seg != 0] n.seg <- length(uni.seg) result <- vector("list", n.seg) for (i in seq_len(n.seg)) { result[[i]] <- data[seg.col == uni.seg[i], ] } res_len <- sapply(result, nrow) result[which(res_len > 2)] } prepareSeasonalFit <- function(data, segment) { seg.col <- which(names(data[[1]]) == segment) data <- lapply(data, function(x) x[, -seg.col]) data <- lapply(data, as.matrix) lapply(data, function(x) apply(x, 2, diff)) } nllk_bmme_seasonal <- function(param, data) { n.year <- length(data) result <- lapply(data, nllk.bmme, param = param) sum(unlist(result)) } ncllk_m1_inc_seasonal <- function(theta, data, integrControl, logtr) { n.year <- length(data) result <- lapply(data, ncllk_m1_inc, theta = theta, integrControl = integrControl, logtr = logtr) sum(unlist(result)) } nllk_inc_seasonal <- function(theta, data, integrControl, logtr) { n.year <- length(data) result <- lapply(data, nllk_inc, theta = theta, integrControl = integrControl, logtr = logtr) sum(unlist(result)) } nllk_mrme_seasonal <- function(theta, data, integrControl) { n.year <- length(data) result <- lapply(data, nllk_mrme, theta = theta, integrControl = integrControl) sum(unlist(result)) } nllk_mrme_naive_cmp_seasonal <- function(theta, data, integrControl) { n.year <- length(data) result <- lapply(data, nllk_mrme_naive_cmp, theta = theta, integrControl = integrControl) sum(unlist(result)) } nllk_mrme_approx_seasonal <- function(theta, data, integrControl, approx_norm_even, approx_norm_odd) { n.year <- length(data) result <- lapply(data, nllk_mrme_approx, theta = theta, integrControl = integrControl, approx_norm_even = approx_norm_even, approx_norm_odd = approx_norm_odd) sum(unlist(result)) } bmme.start.seasonal <- function(dat, segment) { dif <- prepareSeasonalFit(dat, segment) dim <- ncol(dif[[1]]) - 1 numerator <- sum(unlist(lapply(dif, function(x) {sum(x[,-1]^2)}))) denominator <- sum(unlist(lapply(dif, function(x) {sum(2 + x[,1])}))) * dim st <- sqrt(numerator / denominator) c(st, st) } fitBMME_seasonal <- function(data, segment, start, method, optim.control) { data <- seg2list(data, segment) if (is.null(start)) start <- bmme.start.seasonal(data, segment) dinc <- prepareSeasonalFit(data, segment) fit <- optim(start, nllk_bmme_seasonal, data = dinc, method=method, control = optim.control) varest <- matrix(NA_real_, 2, 2) estimate <- fit$par hess <- tryCatch(numDeriv::hessian(nllk_bmme_seasonal, estimate, data = dinc), error = function(e) e) if (!is(hess, "error")) varest <- solve(hess) list(estimate = estimate, varest = varest, loglik = -fit$value, convergence = fit$convergence) } glue_list <- function(x) { n <- length(x) m <- sapply(x, nrow) result <- matrix(NA_real_, sum(m), 3) m <- c(0, cumsum(m)) for(i in 1:n) { result[(m[i]+1):m[i+1],] <- x[[i]] } result } movres.start.seasonal <- function(dat, segment) { dat <- prepareSeasonalFit(dat, segment) dinc <- glue_list(dinc) s1 <- coef(lm(dinc[, 2]^2 ~ dinc[, 1] - 1)) s2 <- coef(lm(dinc[, 3]^2 ~ dinc[, 1] - 1)) ss <- sqrt(mean(c(s1, s2))) c(0.5, 0.5, ss) } fitMR_seasonal <- function(data, segment, start, likelihood, logtr, method, optim.control, integrControl) { data <- seg2list(data, segment) if (is.null(start)) start <- movres.start.seasonal(data, segment) dinc <- prepareSeasonalFit(data, segment) objfun <- switch(likelihood, composite = ncllk_m1_inc_seasonal, full = nllk_inc_seasonal, stop("Not valid likelihood type.") ) integrControl <- unlist(integrControl) fit <- optim(start, objfun, data = dinc, method = method, control = optim.control, integrControl = integrControl, logtr = logtr) varest <- matrix(NA_real_, 3, 3) estimate <- if (logtr) exp(fit$par) else fit$par if (likelihood == "full") { hess <- tryCatch(numDeriv::hessian( objfun, estimate, data = dinc, integrControl = integrControl, logtr = FALSE), error = function(e) e) if (!is(hess, "error")) varest <- solve(hess) } list(estimate = estimate, varest = varest, loglik = -fit$value, convergence = fit$convergence, likelihood = likelihood) } fitMRME_seasonal <- function(data, segment, start, lower, upper, integrControl) { data <- seg2list(data, segment) if (is.null(start)) start <- movres.start.seasonal(data, segment) dinc <- prepareSeasonalFit(data, segment) integrControl <- unlist(integrControl) fit <- nloptr::nloptr(x0 = start, eval_f = nllk_mrme_seasonal, data = dinc, integrControl = integrControl, lb = lower, ub = upper, opts = list("algorithm" = "NLOPT_LN_COBYLA", "print_level" = 3, "maxeval" = -5)) result <- list(estimate = fit[[18]], loglik = -fit[[17]], convergence = fit[[14]]) return(result) } fitMRME_naive_seasonal <- function(data, segment, start, lower, upper, integrControl) { data <- seg2list(data, segment) if (is.null(start)) start <- movres.start.seasonal(data, segment) dinc <- prepareSeasonalFit(data, segment) integrControl <- unlist(integrControl) fit <- nloptr::nloptr(x0 = start, eval_f = nllk_mrme_naive_cmp_seasonal, data = dinc, integrControl = integrControl, lb = lower, ub = upper, opts = list("algorithm" = "NLOPT_LN_COBYLA", "print_level" = 3, "maxeval" = -5)) result <- list(estimate = fit[[18]], loglik = -fit[[17]], convergence = fit[[14]]) return(result) } fitMRMEapprox_seasonal <- function(data, segment, start, approx_norm_even, approx_norm_odd, method, optim.control, integrControl) { data <- seg2list(data, segment) if (is.null(start)) start <- movres.start.seasonal(data, segment) dinc <- prepareSeasonalFit(data, segment) integrControl <- unlist(integrControl) fit <- optim(start, nllk_mrme_approx_seasonal, data = dinc, method = method, control = optim.control, integrControl = integrControl, approx_norm_even = approx_norm_even, approx_norm_odd = approx_norm_odd) list(estimate = fit$par, loglik = -fit$value, convergence = fit$convergence) } nllk_seasonal_parallel <- function(theta, data, integrControl, numThreads) { n.year <- length(data) cl = parallel::makeCluster(numThreads); on.exit(parallel::stopCluster(cl)) doParallel::registerDoParallel(cl) i = 1 result <- foreach(i = 1:n.year) %dopar% { nllk_fwd_ths(theta, data[[i]], integrControl) } sum(unlist(result)) } fitMRH_seasonal <- function(data, segment, start, lower, upper, numThreads, integrControl) { data <- seg2list(data, segment) dinc <- prepareSeasonalFit(data, segment) integrControl <- unlist(integrControl) fit <- nloptr::nloptr(x0 = start, eval_f = nllk_seasonal_parallel, data = dinc, integrControl = integrControl, numThreads = numThreads, lb = lower, ub = upper, opts = list("algorithm" = "NLOPT_LN_COBYLA", "print_level" = 3, "maxeval" = -5)) result <- list(estimate = fit[[18]], loglik = -fit[[17]], convergence = fit[[14]]) result }
starts_uni_estimate_prepare_fitting_prior_model <- function( pars_est, prior_var_trait, prior_var_ar, prior_var_state, prior_a, sd0, estimator) { prior_model <- NULL if ( estimator !="ML"){ prior_model <- list() prior_model[[ "var_trait" ]] <- starts_uni_estimate_prepare_fitting_prior_variance( prior_var=prior_var_trait, sd0=sd0) prior_model[[ "var_ar" ]] <- starts_uni_estimate_prepare_fitting_prior_variance( prior_var=prior_var_ar, sd0=sd0) prior_model[[ "var_state" ]] <- starts_uni_estimate_prepare_fitting_prior_variance( prior_var=prior_var_state, sd0=sd0) vec <- round( c(NA, (prior_a[1]+1)*prior_a[2], (prior_a[1]+1)*(1-prior_a[2] ) ), 4 ) prior_model[[ "a" ]] <- list( "dbeta", as.list(vec) ) pars_remove <- names(pars_est)[ ! pars_est ] if ( length(pars_remove) > 0 ){ for (pp in pars_remove){ prior_model[[pp]] <- NULL } } } return(prior_model) }
bark2hz <- function(z){ if(!is.numeric(z) || z < 0) stop("frequencies have to be non-negative") 600 * sinh(z/6) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(ONEST) library(ONEST) data("sp142_bin") data('empirical') ONEST_vignettes(sp142_bin,empirical) data("sp142_bin") ONEST_inflation_test(sp142_bin)
clusterdist <- function(fit, ...) { if (!is(fit, "disclapmixfit")) { stop("fit must be a disclapmixfit") } if (nrow(fit$y) < 2L) { stop("Fit must have at least two clusters") } symDist <- function(p1, z1, p2, z2) { KL <- function(p1, p2, m) { a <- (2*p1*log(p1)) / (1 - p1^2) b <- log( ((1-p1)*(1+p2)) / ((1+p1)*(1-p2)) ) c <- (2*p1^(m+1) - m*(p1^2 - 1) ) / (1 - p1^2) return(a + b - c*log(p2)) } m <- abs(z1 - z2) return(KL(p1, p2, m) + KL(p2, p1, m)) } clusters <- nrow(fit$disclap_parameters) distmat <- matrix(NA, nrow = clusters, ncol = clusters) for (j1 in 1:(clusters-1)) { for (j2 in (j1+1):clusters) { kldist <- 0 for (k in 1:ncol(fit$disclap_parameters)) { pj1k <- fit$disclap_parameters[j1, k] pj2k <- fit$disclap_parameters[j2, k] kldist <- kldist + symDist(p1 = pj1k, z1 = fit$y[j1, k], p2 = pj2k, z2 = fit$y[j2, k]) } distmat[j2, j1] <- kldist } } distmat <- as.dist(distmat) return(distmat) }