code
stringlengths
1
13.8M
"ChemicalReaction"
library(corporaexplorer) abc <- test_data source("./global/backwards_compatibility.R", local = TRUE) DATE_BASED_CORPUS <- abc$date_based_corpus contains_grouping_variable <- !is.null(abc$original_data$grouping_variable) if (contains_grouping_variable == TRUE) { GROUPING_VARIABLE <- abc$original_data$grouping_variable } else { GROUPING_VARIABLE <- NA } INFO_COLUMNS <- abc$columns_for_info abc <- abc$original_data$data_dok abc$Text <- abc$Text_original_case my_colours <- rep(c("red", "blue", "green", "purple", "orange", "gray"), 10) MAX_DOCS_FOR_HTML <- 400
.downloader <- function(file) { network <- as.logical(Sys.getenv("NETWORK_UP", unset = TRUE)) aws <- as.logical(Sys.getenv("AWS_UP", unset = TRUE)) remote_path <- "https://rczechia.jla-data.net/" remote_file <- paste0(remote_path, file) local_file <- file.path(tempdir(), file) if (file.exists(local_file)) { message("RCzechia: using temporary local dataset.") } else { if (!.ok_to_proceed(remote_file) | !network) { message("No internet connection.") return(NULL) } if (!.ok_to_proceed(remote_file) | !aws) { message("Data source broken.") return(NULL) } message("RCzechia: downloading remote dataset.") curl::curl_download(url = remote_file, destfile = local_file, quiet = T) } local_df <- readRDS(local_file) local_df }
library(EnvStats) windows() with(Helsel.Cohn.88.silver.df, ecdfPlotCensored(Ag, Censored, xlab = expression(paste("Ag (", mu, "g/L)", sep = "")), main = "Empirical CDF Plot for Silver\n(Method of Michael-Schucany)", include.cen = TRUE)) windows() with(Helsel.Cohn.88.silver.df, ecdfPlotCensored(log.Ag, Censored, xlab = expression(paste("log [ Ag (", mu, "g/L) ]", sep = "")), main = "Empirical CDF Plot for Silver\n(Method of Michael-Schucany)", include.cen = TRUE)) windows() with(Helsel.Cohn.88.silver.df, cdfCompareCensored(Ag, Censored, distribution = "lnorm", xlab = expression(paste("Ag (", mu, "g/L)", sep = "")))) windows() with(Helsel.Cohn.88.silver.df, cdfCompareCensored(log(Ag), Censored, distribution="norm", xlab = expression(paste("log [ Ag (", mu, "g/L) ]", sep = "")))) attach(Millard.Deverel.88.df) Cu.Alluvial <- Cu[Zone == "Alluvial.Fan"] Cu.Alluvial.cen <- Cu.censored[Zone == "Alluvial.Fan"] Cu.Basin <- Cu[Zone == "Basin.Trough"] Cu.Basin.cen <- Cu.censored[Zone == "Basin.Trough"] windows() cdfCompareCensored(x = Cu.Alluvial, censored = Cu.Alluvial.cen, y = Cu.Basin, y.censored = Cu.Basin.cen) detach("Millard.Deverel.88.df") rm(Cu.Alluvial, Cu.Alluvial.cen, Cu.Basin, Cu.Basin.cen) windows() with(Modified.TcCB.df, qqPlotCensored(TcCB, Censored, distribution = "lnorm", add.line = TRUE, points.col = "blue")) boxcox.list <- with(Modified.TcCB.df, boxcoxCensored(TcCB, Censored)) windows() plot(boxcox.list) rm(boxcox.list) with(EPA.09.Ex.15.1.manganese.df, elnormCensored(Manganese.ppb, Censored)) with(EPA.09.Ex.15.1.manganese.df, elnormCensored(Manganese.ppb, Censored, method = "qq.reg")) with(EPA.09.Ex.15.1.manganese.df, elnormCensored(Manganese.ppb, Censored, method = "impute.w.qq.reg", prob.method = "hirsch-stedinger")) with(EPA.09.Ex.15.1.manganese.df, elnormCensored(Manganese.ppb, Censored, method = "impute.w.qq.reg", prob.method = "hirsch-stedinger", plot.pos.con = 0)) with(EPA.09.Ex.15.1.manganese.df, elnormCensored(Manganese.ppb, Censored, ci = TRUE)) with(Modified.TcCB.df, elnormAltCensored(TcCB, Censored, method = "mle", ci = TRUE)) with(Modified.TcCB.df, egammaAltCensored(TcCB, Censored, ci = TRUE, ci.method = "profile.likelihood")) with(EPA.09.Ex.15.1.manganese.df, enparCensored(log(Manganese.ppb), Censored, ci = TRUE)) with(EPA.09.Ex.15.1.manganese.df, enparCensored(Manganese.ppb, Censored, ci = TRUE)) with(EPA.94b.tccb.df, eqlnorm(TcCB[Area == "Reference"], p = 0.9, ci = TRUE)) with(Modified.TcCB.df, eqlnormCensored(TcCB, Censored, p = 0.9, ci = TRUE)) with(Modified.TcCB.df, eqlnormCensored(TcCB, Censored, p = 0.9, method = "impute.w.qq.reg", ci = TRUE, ci.method = "gpq", seed = 47)) egamma.list <- with(Modified.TcCB.df, egammaCensored(TcCB, Censored)) eqgamma(egamma.list, p = 0.9) rm(egamma.list) enorm.list <- with(EPA.09.Ex.18.3.TCE.df, enormCensored(TCE.ppb[Well.type == "Background"], Censored[Well.type == "Background"])) predIntNorm(enorm.list, k = 4, pi.type = "upper", conf.level = 0.95, method = "exact") rm(enorm.list) with(Modified.TcCB.df, tolIntLnormCensored(TcCB, Censored, ti.type = "upper")) with(Modified.TcCB.df, tolIntLnormCensored(TcCB, Censored, ti.type = "upper", method = "impute.w.qq.reg", ti.method = "gpq", seed = 47)) sw.list.norm <- with(Modified.TcCB.df, gofTestCensored(TcCB, Censored)) sw.list.norm sw.list.lnorm <- with(Modified.TcCB.df, gofTestCensored(TcCB, Censored, dist = "lnorm")) sw.list.lnorm windows() plot(sw.list.norm) windows() plot(sw.list.lnorm) rm(sw.list.norm, sw.list.lnorm) attach(Millard.Deverel.88.df) Cu.AF <- Cu[Zone=="Alluvial.Fan"] Cu.AF.cen <- Cu.censored[Zone=="Alluvial.Fan"] Cu.BT <- Cu[Zone=="Basin.Trough"] Cu.BT.cen <- Cu.censored[Zone=="Basin.Trough"] twoSampleLinearRankTestCensored(Cu.AF, Cu.AF.cen, Cu.BT, Cu.BT.cen, test = "normal.scores.2", var = "hypergeometric") rm(Cu.AF, Cu.AF.cen, Cu.BT, Cu.BT.cen) detach("Millard.Deverel.88.df")
create.buffer <- function(x, loc, radius, km=FALSE){ mat <- x if (!is(mat,"bathy")) stop("x must be an object of class bathy") if (!is.data.frame(loc)) stop("loc must be a two-column data.frame (longitude and latitude)") if (!is.numeric(radius)) stop("radius must be numeric") if (length(radius) > 1) warning("only the first value of radius was used") xyz <- as.xyz(mat) if (km) { radius.km <- radius radius <- 180 * radius.km/(pi*6372.798) } else { radius.km <- radius*pi*6372.798/180 } map <- sp::SpatialPixelsDataFrame(points = xyz[,1:2], data = xyz, tolerance = 0.006) lo2 <- sp::SpatialPointsDataFrame(loc, data = loc) adehabitatMA::adeoptions(epsilon=0.001) temp <- adehabitatMA::buffer(lo2, map, radius) adehabitatMA::adeoptions(epsilon=0.00000001) temp <- -as.bathy(as(temp,'SpatialGridDataFrame')) mat[temp==0] <- NA out <- list(buffer = mat, center = loc, radius = radius, radius.km = radius.km) class(out) <- "buffer" return(out) }
get.coverage.by.sample.statistics <- function(project.directory) { if( !is.character(project.directory) || length(project.directory) > 1 ) { stop('project.directory must be a string.'); } if( !file.exists(project.directory) ) { error.message <- paste('Directory', project.directory, 'does not exist'); stop(error.message); } total.coverage.statistics <- process.total.coverage.statistics(project.directory); coverage.report.data <- process.coverage.reports(project.directory); coverage.by.sample.statistics <- merge( total.coverage.statistics, coverage.report.data, by = "sample.id", all = TRUE ); return(coverage.by.sample.statistics); }
precess = function( ra, dec, equinox1, equinox2, fk4=F,radian=F) { deg_to_rad = pi/180 if(!radian ){ ra_rad = ra*deg_to_rad dec_rad = dec*deg_to_rad } else { ra_rad= ra dec_rad = dec } a = cos( dec_rad ) x = rbind(a*cos(ra_rad), a*sin(ra_rad), sin(dec_rad)) sec_to_rad = deg_to_rad/3600.e0 r = premat(equinox1, equinox2, fk4 = fk4) cat('precess:','equinox1=',equinox1,'\n') cat('precess:','equinox2=',equinox2,'\n') x2 = r%*%x cat('precess:','x2=',x2,'\n') ra_rad = atan2(x2[2,],x2[1,]) dec_rad = asin(x2[3,]) if(!radian ){ ra = ra_rad/deg_to_rad ra = ra + (ra<0.)*360 dec = dec_rad/deg_to_rad } else { ra = ra_rad dec = dec_rad ra = ra + (ra<0.)*2*pi } return(list(ra =ra, dec=dec)) }
CQL <- function(...) { sql <- dbplyr::sql(...) structure(sql, class = c("CQL", class(sql))) } vicmap_cql_string <- function(x, geometry_predicates, pattern = NULL, distance = NULL, units = NULL, coords = NULL, crs = NULL){ if (inherits(x, "sql")) { stop(glue::glue("object {as.character(x)} not found.\n The object passed to {geometry_predicates} needs to be valid sf object."), call. = FALSE) } if (inherits(x, "vicmap_promise")) { stop("To use spatial operators, you need to use collect() to retrieve the object used to filter", call. = FALSE) } match.arg(geometry_predicates, cql_geom_predicate_list()) if (!geometry_predicates == "BBOX") { x <- sf_text(x) } cql_args <- if (geometry_predicates == "BBOX") { paste0( paste0(coords, collapse = ", "), if (!is.null(crs)) paste0(", '", crs, "'") ) } else if (geometry_predicates %in% c("DWITHIN", "BEYOND")) { paste0(x, ", ", distance, ", ", units, "") } else if (geometry_predicates == "RELATE") { paste0(x, ", ", pattern) } else { x } CQL(paste0(geometry_predicates,"({geom_name}, ", cql_args, ")")) } cql_geom_predicate_list <- function() { c("EQUALS","DISJOINT","INTERSECTS", "TOUCHES", "CROSSES", "WITHIN", "CONTAINS","OVERLAPS", "RELATE", "DWITHIN", "BEYOND", "BBOX") } sf_text <- function(x) { if (!inherits(x, c("sf", "sfc", "sfg", "bbox"))) { stop(paste(deparse(substitute(x)), "is not a valid sf object"), call. = FALSE) } if (utils::object.size(x) > getOption("vicmap.max_geom_pred_size", 4400)) { message("The object is too large to perform exact spatial operations using VicmapR. To simplify the polygon, sf::st_simplify() was used to reduce the size of the query") x <- polygonFormat(x) } if (inherits(x, "bbox")) { x <- sf::st_as_sfc(x) } else { x <- sf::st_union(x) } if (sf::sf_extSoftVersion()["GDAL"] >= "3.0.0") { ao <- sf::st_axis_order() sf::st_axis_order(TRUE) x <- sf::st_transform(x, pipeline = "+proj=pipeline +step +proj=axisswap +order=2,1") filter_string <- sf::st_as_text(x) sf::st_axis_order(ao) } else { warning("GDAL > 3.0.0 is required") filter_string <- sf::st_as_text(x) } return(filter_string) } NULL EQUALS <- function(geom) { vicmap_cql_string(geom, "EQUALS") } DISJOINT <- function(geom) { vicmap_cql_string(geom, "DISJOINT") } INTERSECTS <- function(geom) { vicmap_cql_string(geom, "INTERSECTS") } TOUCHES <- function(geom) { vicmap_cql_string(geom, "TOUCHES") } CROSSES <- function(geom) { vicmap_cql_string(geom, "CROSSES") } WITHIN <- function(geom) { vicmap_cql_string(geom, "WITHIN") } CONTAINS <- function(geom) { vicmap_cql_string(geom, "CONTAINS") } OVERLAPS <- function(geom) { vicmap_cql_string(geom, "OVERLAPS") } RELATE <- function(geom, pattern) { if (!is.character(pattern) || length(pattern) != 1L || !grepl("^[*TF012]{9}$", pattern)) { stop("pattern must be a 9-character string using the characters '*TF012'", call. = FALSE) } vicmap_cql_string(geom, "RELATE", pattern = pattern) } BBOX <- function(coords, crs = NULL){ if (inherits(coords, c("sf", "sfc"))) { coords <- sf::st_bbox(coords) } if (!is.numeric(coords) || length(coords) != 4L) { stop("'coords' must be a length 4 numeric vector", call. = FALSE) } if (inherits(coords, "bbox")) { crs <- sf::st_crs(coords)$epsg coords <- as.numeric(coords) } if (is.numeric(crs)) { crs <- paste0("EPSG:", crs) } if (!is.null(crs) && !(is.character(crs) && length(crs) == 1L)) { stop("crs must be a character string denoting the CRS (e.g., 'EPSG:4326')", call. = FALSE) } vicmap_cql_string(x = NULL, "BBOX", coords = coords, crs = crs) } DWITHIN <- function(geom, distance, units = c("meters", "feet", "statute miles", "nautical miles", "kilometers")) { if (!is.numeric(distance)) { stop("'distance' must be numeric", call. = FALSE) } units <- match.arg(units) vicmap_cql_string(geom, "DWITHIN", distance = distance, units = units) } BEYOND <- function(geom, distance, units = c("meters", "feet", "statute miles", "nautical miles", "kilometers")) { if (!is.numeric(distance)) { stop("'distance' must be numeric", call. = FALSE) } units <- match.arg(units) vicmap_cql_string(geom, "BEYOND", distance = distance, units = units) }
infer_cochran_qtest <- function(data, ...) UseMethod("infer_cochran_qtest") infer_cochran_qtest.default <- function(data, ...) { vars <- vapply(substitute(...()), deparse, NA_character_) fdata <- data[vars] if (ncol(fdata) < 3) { stop("Please specify at least 3 variables.", call. = FALSE) } if (any(sapply(lapply(fdata, as.factor), nlevels) > 2)) { stop("Please specify dichotomous/binary variables only.", call. = FALSE) } k <- cochran_comp(fdata) result <- list( df = k$df, n = k$n, pvalue = k$pvalue, q = k$q) class(result) <- "infer_cochran_qtest" return(result) } print.infer_cochran_qtest <- function(x, ...) { print_cochran_test(x) } coch_data <- function(x, ...) { if (is.data.frame(x)) { data <- x %>% lapply(as.numeric) %>% as.data.frame() %>% `-`(1) } else { data <- cbind(x, ...) %>% apply(2, as.numeric) %>% `-`(1) %>% as.data.frame() } return(data) } cochran_comp <- function(data) { n <- nrow(data) k <- ncol(data) df <- k - 1 cs <- data %>% lapply(as.numeric) %>% as.data.frame() %>% subtract(1) %>% sums() q <- coch(k, cs$cls_sum, cs$cl, cs$g, cs$gs_sum) pvalue <- 1 - pchisq(q, df) list( df = df, n = n, pvalue = round(pvalue, 4), q = q) } sums <- function(data) { cl <- colSums(data) cls_sum <- sum(cl ^ 2) g <- rowSums(data) gs_sum <- sum(g ^ 2) list( cl = cl, cls_sum = cls_sum, g = g, gs_sum = gs_sum) } coch <- function(k, cls_sum, cl, g, gs_sum) { ((k - 1) * ((k * cls_sum) - (sum(cl) ^ 2))) / ((k * sum(g)) - gs_sum) }
GetAcquisitionPlan <- function(satellites = NULL, date = NULL) { endpoint <- "https://api.spectator.earth/acquisition-plan/" if (!is.null(date)) { date <- sprintf("%sT12:00:00", as.Date(date)) } if (!is.null(satellites)) { satellites <- FindSatelliteName(satellites) } qry <- list(satellites = satellites, datetime = date) resp <- httr::GET(url = endpoint, query = qry) CheckResponseSatus(resp) cnt <- httr::content(resp, type = "text", encoding = "UTF-8") plan <- geojsonsf::geojson_sf(cnt) if (!is.null(plan$begin_time)) { plan$begin_time <- as.POSIXct(gsub("Z", "", gsub("T", " ", plan$begin_time)), tz = "GMT") } if (!is.null(plan$end_time)) { plan$end_time <- as.POSIXct(gsub("Z", "", gsub("T", " ", plan$end_time)), tz = "GMT") } return(plan) }
densEstBayesVignette <- function() { vignette("manual",package="densEstBayes") }
findMin2 <- function(esTimesDf, RELEVANTVN_ES=NULL, RELEVANTINFO_ES=NULL) { if(!is.data.frame(esTimesDf)) { stop("Argument must be of type data.frame.") } PROMPT <- c() absStart1 <- c() PROMPTEND <- c() absEnd1 <- c() lag_ba0 <- c() midnightDate <- c() stTimes <- paste0("stTime", 1:RELEVANTINFO_ES[["MAXPROMPT"]]) for (j in 1 : nrow(esTimesDf)) { start_j1 <- lubridate::as.duration(lubridate::ymd_hms(esTimesDf[j,RELEVANTVN_ES[["ES_START_DATETIME"]]]) - lubridate::ymd_hms(unlist(esTimesDf[j, stTimes]))) absStart_j1 <- abs(start_j1) absStart_jSec1 <- as.numeric(absStart_j1) minAST1 <- min(absStart_jSec1) minStart1 <- which(minAST1 == absStart_jSec1)[1] start_j2 <- lubridate::as.duration(lubridate::ymd_hms(esTimesDf[j,RELEVANTVN_ES[["ES_START_DATETIME"]]]) - (lubridate::ymd_hms(unlist(esTimesDf[j, stTimes])) - lubridate::days(1))) absStart_j2 <- abs(start_j2) absStart_jSec2 <- as.numeric(absStart_j2) minAST2 <- min(absStart_jSec2) minStart2 <- which(minAST2 == absStart_jSec2)[1] start_j3 <- lubridate::as.duration(lubridate::ymd_hms(esTimesDf[j,RELEVANTVN_ES[["ES_START_DATETIME"]]]) - (lubridate::ymd_hms(unlist(esTimesDf[j, stTimes])) + lubridate::days(1))) absStart_j3 <- abs(start_j3) absStart_jSec3 <- as.numeric(absStart_j3) minAST3 <- min(absStart_jSec3) minStart3 <- which(minAST3 == absStart_jSec3)[1] minAST <- which(c(minAST1, minAST2, minAST3) == min(c(minAST1, minAST2, minAST3))) if(minAST == 1) { midnightDate <- c(midnightDate, 0) PROMPT <- c(PROMPT, minStart1) absStart1 <- c(absStart1, as.numeric(absStart_jSec1[minStart1])) start_j <- start_j1; minStart <- minStart1 } else if(minAST == 2) { midnightDate <- c(midnightDate, -1) PROMPT <- c(PROMPT, minStart2) absStart1 <- c(absStart1, as.numeric(absStart_jSec2[minStart2])) start_j <- start_j2; minStart <- minStart2 } else if(minAST == 3) { midnightDate <- c(midnightDate, 1) PROMPT <- c(PROMPT, minStart3) absStart1 <- c(absStart1, as.numeric(absStart_jSec3[minStart3])) start_j <- start_j3; minStart <- minStart3 } else { warning("Function findMin2 (not visible to the user) within function esAssign failed. Please report bug to the maintainer of the esmprep package (esmprep-at-gmail.com).") } if (is.na(nchar(as.character(esTimesDf[j, RELEVANTVN_ES[["ES_END_DATETIME"]]]))) | nchar(as.character(esTimesDf[j, RELEVANTVN_ES[["ES_END_DATETIME"]]])) < 19) { PROMPTEND <- c(PROMPTEND, NA) absEnd1 <- c(absEnd1, NA) } else { if(minAST == 1) { absEnd_i <- abs(lubridate::ymd_hms(esTimesDf[j, RELEVANTVN_ES[["ES_END_DATETIME"]]]) - lubridate::ymd_hms(unlist(esTimesDf[j, stTimes]) )) } else if(minAST == 2) { absEnd_i <- abs(lubridate::ymd_hms(esTimesDf[j, RELEVANTVN_ES[["ES_END_DATETIME"]]]) - (lubridate::ymd_hms(unlist(esTimesDf[j, stTimes])) - lubridate::days(1)) ) } else if(minAST == 3) { absEnd_i <- abs(lubridate::ymd_hms(esTimesDf[j, RELEVANTVN_ES[["ES_END_DATETIME"]]]) - (lubridate::ymd_hms(unlist(esTimesDf[j, stTimes])) + lubridate::days(1)) ) } absEnd_iSec <- as.numeric(lubridate::as.duration(absEnd_i)) minEnd <- min(absEnd_iSec) minEnd1 <- which(minEnd == absEnd_iSec)[1] PROMPTEND <- c(PROMPTEND, minEnd1) absEnd1 <- c(absEnd1, as.numeric(absEnd_iSec[minEnd1])) } lag_ba0 <- c(lag_ba0, ifelse(as.numeric(start_j)[minStart] < 0, 0, 1)) } return (data.frame(PROMPT, PROMPTEND, absStart1, absEnd1, lag_ba0, midnightDate)) }
`evalRedundancy` <- function(mat,ia,red=0){ vec.snps<-strsplit(ia," & ")[[1]] n.snps<-length(vec.snps) if(n.snps==1) return(ia) vec.jack<-character(n.snps) for(i in 1:n.snps) vec.jack[i]<-paste(vec.snps[-i],collapse=" & ") vec.red<-numeric(n.snps) full<-with(mat, sum(eval(parse(text=ia)))) for(i in 1:n.snps) vec.red[i]<-with(mat, sum(eval(parse(text=vec.jack[i])))) if(any(vec.red-full<=red)){ warning("A redundant SNP in the explanatory interactions is removed.",call.=FALSE) ids<-which.min(vec.red-full)[1] new.ia<-vec.jack[ids] ia<-evalRedundancy(mat,new.ia,red=red) } ia }
LOCAL <- identical(Sys.getenv("LOCAL"), "TRUE") knitr::opts_chunk$set(purl = LOCAL) knitr::opts_chunk$set( collapse = TRUE, comment = " ) require(Patterns) require(Patterns) CLLfile <- "https://github.com/fbertran/Patterns/raw/master/add_data/CLL.RData" repmis::source_data(CLLfile) CLL[1:10,1:5] hea_US<-CLL[,which((1:48)%%8<5&(1:48)%%8>0)+2] hea_S<-CLL[,which(!((1:48)%%8<5&(1:48)%%8>0))+2] agg_US<-CLL[,which((1:40)%%8<5&(1:40)%%8>0)+98] agg_S<-CLL[,which(!((1:40)%%8<5&(1:40)%%8>0))+98] m_hea_US<-as.micro_array(hea_US,c(60,90,210,390),6,name=CLL[,1],gene_ID=CLL[,2]) m_hea_S<- as.micro_array(hea_S,c(60,90,210,390),6,name=CLL[,1],gene_ID=CLL[,2]) m_agg_US<-as.micro_array((agg_US),c(60,90,210,390),5,name=CLL[,1],gene_ID=CLL[,2]) m_agg_S<- as.micro_array((agg_S),c(60,90,210,390),5,name=CLL[,1],gene_ID=CLL[,2]) matplot(t(log(agg_S[which(CLL[,2] %in% "EGR1"),])),type="l",lty=1) selection1<-geneSelection(list(m_agg_US,m_agg_S),list("condition&time",c(1,2),c(1,1)),-1,alpha=0.1) selection2<-geneSelection(list(m_agg_US,m_agg_S),list("condition&time",c(1,2),c(1,1)+1),-1,alpha=0.1) selection3<-geneSelection(list(m_agg_US,m_agg_S),list("condition&time",c(1,2),c(1,1)+2),50,alpha=0.005) selection4<-geneSelection(list(m_agg_US,m_agg_S),list("condition&time",c(1,2),c(1,1)+3),50,alpha=0.005) selection<-Patterns::unionMicro(list(selection1,selection2,selection3,selection4)) summary(selection) length(selection@gene_ID) require(biomaRt) affyids=c("202763_at","209310_s_at","207500_at") ensembl = useMart("ensembl",dataset="hsapiens_gene_ensembl") infos<-getBM(attributes=c("affy_hg_u133_plus_2","ensembl_gene_id","hgnc_symbol","chromosome_name","start_position","end_position","band"), filters = "affy_hg_u133_plus_2", values = CLL[CLL[,1] %in% selection@name,1] , mart = ensembl,uniqueRows=TRUE, checkFilters = TRUE) selection@gene_ID <- lapply(selection@name,function(x) {unique(infos[infos$affy_hg_u133_plus_2==x,"hgnc_symbol"])}) selection@group <- rep(NA, length(selection@name)) names(selection@group) <- selection@name selection@group[selection@name %in% selection4@name] <- 4 selection@group[selection@name %in% selection3@name] <- 3 selection@group[selection@name %in% selection2@name] <- 2 selection@group[selection@name %in% selection1@name] <- 1 plot(selection) length(selection@group) network<-inference(selection,fitfun="LASSO2",Finit=CascadeFinit(4,4),Fshape=CascadeFshape(4,4)) str(network) plotF(network@F, choice='F') doc <- read.delim("http://bioinfo.life.hust.edu.cn/static/AnimalTFDB3/download/Homo_sapiens_TF",encoding = "UTF-8", header=TRUE) TF<-as.character(doc[,"Symbol"]) TF<-TF[order(TF)] infos_selection <- infos[infos$affy_hg_u133_plus_2 %in% selection@name,] tfs<-which(infos_selection[,"hgnc_symbol"] %in% TF) matplot(t(selection@microarray[tfs,]),type="l",lty=1) kk<-kmeans((selection@microarray[tfs,]),10) matplot(t(kk$centers),type="l",lty=1)
listToXml <- function(x, ...) { UseMethod("listToXml") } listToXml.default <- function(item, tag) { if (typeof(item) != "list") { if (length(item) > 1) { xml <- XML::xmlNode(tag) for (name in names(item)) { XML::xmlAttrs(xml)[[name]] <- item[[name]] } return(xml) } else { return(XML::xmlNode(tag, item)) } } if (identical(names(item), c("text", ".attrs"))) { xml <- XML::xmlNode(tag, item[["text"]]) } else { xml <- XML::xmlNode(tag) for (i in seq_along(item)) { if (is.null(names(item)) || names(item)[i] != ".attrs") { xml <- XML::append.xmlNode(xml, listToXml(item[[i]], names(item)[i])) } } } attrs <- item[[".attrs"]] for (name in names(attrs)) { XML::xmlAttrs(xml)[[name]] <- attrs[[name]] } return(xml) }
create.life <- function(true.lv = NULL, lv.coefs, lv.control = list(num.lv = 0, type = "independent", lv.covparams = NULL, distmat = NULL), X = NULL, X.coefs = NULL, traits = NULL, traits.coefs = NULL, family, row.eff = "none", row.params = NULL, row.ids = NULL, true.ranef = NULL, ranef.params = NULL, ranef.ids = NULL, offset = NULL, trial.size = 1, cutoffs = NULL, powerparam = NULL, manual.dim = NULL, save.params = FALSE) { n <- max(nrow(true.lv), nrow(X)) p <- max(nrow(lv.coefs), nrow(X.coefs), length(cutoffs)) if(is.null(dim(lv.coefs))) lv.coefs <- as.matrix(lv.coefs) if((is.null(n) | is.null(p)) & is.null(manual.dim)) stop("Sorry, but boral cannot determine the number of rows and columns for the response matrix. Please supply manual.dim as vector containing n and p.") if((is.null(n) | is.null(p)) & !is.null(manual.dim)) { n <- manual.dim[1] p <- manual.dim[2] } if(!is.null(true.lv)) { lv.control <- list(num.lv = ncol(true.lv), type = "independent") } if(is.null(true.lv)) { if(lv.control$num.lv > 0) { if(lv.control$type != "independent" & (is.null(lv.control$distmat) || is.null(lv.control$lv.covparams))) stop("For structured latent variables are to be generated, please supply both lv.control$distmat and lv.control$lv.covparams") if(lv.control$type == "exponential") covmat_chol <- (chol(exp(-lv.control$distmat/lv.control$lv.covparams[1]))) if(lv.control$type == "squared.exponential") covmat_chol <- (chol(exp(-(lv.control$distmat/lv.control$lv.covparams[1])^2))) if(lv.control$type == "powered.exponential") covmat_chol <- (chol(exp(-(lv.control$distmat/lv.control$lv.covparams[1])^lv.control$lv.covparams[2]))) if(lv.control$type == "spherical") covmat_chol <- (chol((lv.control$distmat < lv.control$lv.covparams[1])*(1 - 1.5*lv.control$distmat/lv.control$lv.covparams[1] + 0.5*(lv.control$distmat/lv.control$lv.covparams[1])^3))) true.lv <- rmvnorm(n, mean = rep(0,lv.control$num.lv)) if(lv.control$type != "independent") true.lv <- crossprod(covmat_chol, true.lv) } } num.lv <- lv.control$num.lv if(!is.null(X)) { if(is.null(X.coefs) & is.null(traits)) stop("If X is supplied, then either X.coefs or traits and traits.coefs must be supplied.") } if(!is.null(X)) { if(!is.matrix(X)) X <- as.matrix(X) if(any(apply(X,2,function(x) all(x == 1)))) stop("No intercept column should be included in X.") } if((is.null(traits) & !is.null(traits.coefs)) | (!is.null(traits) & is.null(traits.coefs))) stop("If traits is supplied, then traits.coefs must also be supplied.") if(!is.null(traits.coefs)) message("Since trait.coefs has been supplied, then X.coefs will be ignored (it will instead be drawn as random effects based off trait.coefs).") check_traits <- function(traits = traits, y = matrix(NA,nrow=1,ncol=p)) if(length(family) != p & length(family) != 1) stop("Number of elements in family must be either 1 or equal to if(length(family) == 1) family <- rep(family, p) if(!all(family %in% c("negative.binomial", "ztnegative.binomial", "poisson", "ztpoisson", "binomial", "normal", "lnormal", "tweedie", "ordinal", "exponential", "beta"))) stop("One of the elements in family is not compatible with current version of boral...sorry!") check_trial_size(family = family, trial.size = trial.size) if(length(trial.size) == 1) trial.size <- rep(trial.size, p) if(any(family == "ordinal") & is.null(cutoffs)) stop("cutoffs (an ascending vector of intercepts for proportional odds regression) must be supplied if any columns are ordinal data.") if(any(family == "ordinal")) index.ord.cols <- which(family == "ordinal") if(!is.null(cutoffs)) { num.ord.levels <- length(cutoffs) + 1 cutoffs <- sort(cutoffs) message("Sorting cutoffs...just in case!") } if(any(family == "tweedie") & is.null(powerparam)) stop("Common powerparam must be supplied if any columns are tweedie data (Var = dispersion*mu^powerparam).") sim_y <- matrix(NA, nrow = n, ncol = p) check_offset(offset = offset, y = sim_y) row.coefs <- NULL if(row.eff != "none") { if(is.null(row.ids)) { row.ids <- matrix(1:nrow(sim_y), ncol = 1) colnames(row.ids) <- "ID1" } row.ids <- check_row_ids(row.ids = row.ids, y = sim_y) check_row_params(row.params = row.params, y = sim_y, row.ids = row.ids) } if(row.eff == "fixed") row.coefs <- row.params if(row.eff == "random") { row.coefs <- vector("list", ncol(row.ids)) for(k in 1:ncol(row.ids)) row.coefs[[k]] <- rnorm(length(unique(row.ids[,k])), mean = 0, sd = row.params[[k]]) } ranef_coefs <- NULL if(!is.null(ranef.ids) & (is.null(true.ranef) & is.null(ranef.params))) stop("If you want response-specific random intercepts in the model, then you need supply either true.ranef or ranef.params, in conjunction with ranef.ids") ranef.ids <- check_ranef_ids(ranef.ids = ranef.ids, y = sim_y) check_ranef_params(ranef.params = ranef.params, y = sim_y, ranef.ids = ranef.ids) if(!is.null(true.ranef) & !is.null(ranef.ids)) { if(is.null(ranef.ids)) stop("ranef.ids needs to be supplied if you want response-specific random intercepts in the model (as determined by true.ranef).") if(!is.list(true.ranef)) stop("true.ranef must be a list of length ncol(ranef.ids).") for(k0 in 1:length(true.ranef)) { if(nrow(true.ranef[[k0]]) != p) stop("The k-th element in the list true.ranef should be matrix of dimension p by length(unique(ranef.ids[,k])).") if(ncol(true.ranef[[k0]]) != length(unique(ranef.ids[,k0]))) stop("The k-th element in the list true.ranef should be matrix of dimension p by length(unique(ranef.ids[,k])).") } ranef_coefs <- true.ranef } if(is.null(true.ranef) & !is.null(ranef.ids)) { ranef_coefs <- vector("list", ncol(ranef.ids)) for(k in 1:ncol(ranef.ids)) ranef_coefs[[k]] <- t(sapply(1:p, function(j) rnorm(length(unique(ranef.ids[,k])), mean = 0, sd = ranef.params[j,k]))) } if(num.lv > 5) warnings("We won't stop you, but please consider if you really want more than five latent variables in the model", immediate. = TRUE) if(num.lv == 0) eta <- matrix(0, nrow = n, ncol = p) if(num.lv > 0) eta <- tcrossprod(true.lv, lv.coefs[,2:(num.lv + 1)]) if(is.null(traits.coefs)) eta <- eta + tcrossprod(rep(1,n), as.matrix(lv.coefs[,1])) if(!is.null(X.coefs) & is.null(traits.coefs)) eta <- eta + tcrossprod(as.matrix(X), X.coefs) if(!is.null(offset)) eta <- eta + offset if(!is.null(traits.coefs)) { X.coefs <- matrix(0, p, ncol(X)) lv.coefs[,1] <- rnorm(p, cbind(1,traits)%*%traits.coefs[1,-ncol(traits.coefs)], sd = traits.coefs[1,ncol(traits.coefs)]) if(any(family == "ordinal")) { if(length(index.ord.cols) == 1) lv.coefs[index.ord.cols,1] <- 0 } for(k in 1:ncol(X)) X.coefs[,k] <- rnorm(p, cbind(1,traits)%*%traits.coefs[k+1,-ncol(traits.coefs)], sd = traits.coefs[k+1,ncol(traits.coefs)]) eta <- eta + tcrossprod(cbind(1,as.matrix(X)), cbind(lv.coefs[,1],X.coefs)) } if(!is.null(row.coefs)) { for(k in 1:ncol(row.ids)) eta <- eta + row.coefs[[k]][row.ids[,k]] } if(!is.null(ranef_coefs)) { for(k in 1:ncol(ranef.ids)) eta <- eta + t(ranef_coefs[[k]])[ranef.ids[,k],] } for(j in 1:p) { if(family[j] == "binomial") sim_y[,j] <- rbinom(n, size = trial.size[j], prob = pnorm(eta[,j])) if(family[j] == "poisson") sim_y[,j] <- rpois(n, lambda = exp(eta[,j])) if(family[j] == "ztpoisson") sim_y[,j] <- rztpois(n, lambda = exp(eta[,j])) if(family[j] == "negative.binomial") sim_y[,j] <- rnbinom(n, mu = exp(eta[,j]), size = 1/(lv.coefs[j,ncol(lv.coefs)]+1e-5)) if(family[j] == "negative.binomial") sim_y[,j] <- rztnbinom(n, mu = exp(eta[,j]), size = 1/(lv.coefs[j,ncol(lv.coefs)]+1e-5)) if(family[j] == "exponential") sim_y[,j] <- rexp(n, rate = 1/exp(eta[, j])) if(family[j] == "gamma") sim_y[,j] <- rgamma(n, shape = exp(eta[, j])*lv.coefs[j,ncol(lv.coefs)], rate = lv.coefs[j, ncol(lv.coefs)]) if(family[j] == "beta") sim_y[, j] <- rbeta(n, shape1 = lv.coefs[j,ncol(lv.coefs)]*exp(eta[,j])/(1 + exp(eta[,j])), shape2 = lv.coefs[j,ncol(lv.coefs)]*(1-exp(eta[,j])/(1 +exp(eta[,j])))) if(family[j] == "normal") sim_y[, j] <- rnorm(n, mean = eta[, j], sd = (lv.coefs[j,ncol(lv.coefs)])) if(family[j] == "lnormal") sim_y[, j] <- rlnorm(n, meanlog = eta[, j], sdlog = (lv.coefs[j,ncol(lv.coefs)])) if(family[j] == "tweedie") sim_y[, j] <- rTweedie(n, mu = exp(eta[, j]), phi = lv.coefs[j,ncol(lv.coefs)], p = powerparam) if(family[j] == "ordinal") { get_probs <- ordinal_conversion(n = n, lv = true.lv, lv.coefs.j = lv.coefs[j, ], num.lv = num.lv, row.coefs = row.coefs, row.ids = row.ids, X = X, X.coefs.j = X.coefs[j,], cutoffs = cutoffs, est = "ignore") for(i in 1:n) sim_y[i, j] <- sample(1:num.ord.levels, 1, prob = get_probs[i,]) } } if(!save.params) out <- sim_y if(save.params) out <- list(resp = sim_y, true.lv = true.lv, lv.coefs = lv.coefs, lv.covparams = lv.control$lv.covparams, X.coefs = X.coefs, traits.coefs = traits.coefs, row.params = row.params, row.coefs = row.coefs, row.ids = row.ids, ranef.params = ranef.params, ranef.coefs = ranef_coefs, ranef.ids = ranef.ids, cutoffs = cutoffs, powerparam = powerparam) return(out) } function() { object <- spiderfit_nb nsims <- 1 seed = NULL new.lvs = FALSE new.ranefs = TRUE distmat = NULL est = "median" } simulate.boral <- function(object, nsim = 1, seed = NULL, new.lvs = FALSE, new.ranefs = FALSE, distmat = NULL, est = "median", ...) { if(class(object) != "boral") stop("object must be of class boral.") if(est == "mean") { true_mod <- list(lv.coefs = object$lv.coefs.mean, lv = object$lv.mean, X.coefs = object$X.coefs.mean, ranef.coefs = object$ranef.coefs.mean, ranef.params = object$ranef.params.mean, ranef.ids = object$ranef.ids, traits = object$traits, traits.coefs = object$traits.coefs.mean, cutoffs = object$cutoffs.mean, powerparam = object$powerparam.mean, lv.covparams = object$lv.covparams.mean) if(object$row.eff == "fixed") true_mod$row.params <- lapply(object$row.coefs, function(x) x$mean) if(object$row.eff == "random") true_mod$row.params <- lapply(object$row.sigma, function(x) x$mean) if(!is.null(object$ranef.ids)) true_mod$ranef.params <- object$ranef.sigma.mean } if(est == "median") { true_mod <- list(lv.coefs = object$lv.coefs.median, lv = object$lv.median, X.coefs = object$X.coefs.median, traits = object$traits, ranef.coefs = object$ranef.coefs.median, ranef.params = object$ranef.params.median, ranef.ids = object$ranef.ids, traits.coefs = object$traits.coefs.median, cutoffs = object$cutoffs.median, powerparam = object$powerparam.median, lv.covparams = object$lv.covparams.median) if(object$row.eff == "fixed") true_mod$row.params <- lapply(object$row.coefs, function(x) x$median) if(object$row.eff == "random") true_mod$row.params <- lapply(object$row.sigma, function(x) x$median) if(!is.null(object$ranef.ids)) true_mod$ranef.params <- object$ranef.sigma.median } if(!is.null(seed)) set.seed(seed) if(!new.lvs) { message("Same latent variables used across simulated datasets (if the model involves them).") if(!new.ranefs) { message("Same response-specific random intercepts used across simulated datasets (if the model involves them).") out <- replicate(nsim, create.life(true.lv = true_mod$lv, lv.coefs = true_mod$lv.coefs, X = object$X, X.coefs = true_mod$X.coefs, traits = object$traits, traits.coefs = true_mod$traits.coefs, family = object$family, row.eff = object$row.eff, row.params = true_mod$row.params, row.ids = object$row.ids, true.ranef = true_mod$ranef.coefs, ranef.ids = object$ranef.ids, offset = object$offset, trial.size = object$trial.size, cutoffs = true_mod$cutoffs, powerparam = true_mod$powerparam)) } if(new.ranefs) { message("New response-specific random intercepts used across simulated datasets (if the model involves them).") out <- replicate(nsim, create.life(true.lv = true_mod$lv, lv.coefs = true_mod$lv.coefs, X = object$X, X.coefs = true_mod$X.coefs, traits = object$traits, traits.coefs = true_mod$traits.coefs, family = object$family, row.eff = object$row.eff, row.params = true_mod$row.params, row.ids = object$row.ids, ranef.params = true_mod$ranef.params, ranef.ids = object$ranef.ids, offset = object$offset, trial.size = object$trial.size, cutoffs = true_mod$cutoffs, powerparam = true_mod$powerparam)) } } if(new.lvs) { message("New latent variables generated for each simulated dataset (if the model involves them).") lv.control <- object$lv.control lv.control$lv.covparams <- true_mod$lv.covparams if(lv.control$type != "independent" & is.null(distmat)) stop("For structured latent variables are to be generated, please supply distmat.") lv.control$distmat <- distmat if(!new.ranefs) { message("Same response-specific random intercepts used across simulated datasets (if the model involves them).") out <- replicate(nsim, create.life(true.lv = NULL, lv.coefs = true_mod$lv.coefs, lv.control = lv.control, X = object$X, X.coefs = true_mod$X.coefs, traits = object$traits, traits.coefs = true_mod$traits.coefs, family = object$family, row.eff = object$row.eff, row.params = true_mod$row.params, row.ids = object$row.ids, true.ranef = true_mod$ranef.coefs, ranef.ids = object$ranef.ids, offset = object$offset, trial.size = object$trial.size, cutoffs = true_mod$cutoffs, powerparam = true_mod$powerparam)) } if(new.ranefs) { message("New response-specific random intercepts used across simulated datasets (if the model involves them).") out <- replicate(nsim, create.life(true.lv = NULL, lv.coefs = true_mod$lv.coefs, lv.control = lv.control, X = object$X, X.coefs = true_mod$X.coefs, traits = object$traits, traits.coefs = true_mod$traits.coefs, family = object$family, row.eff = object$row.eff, row.params = true_mod$row.params, row.ids = object$row.ids, ranef.params = true_mod$ranef.params, ranef.ids = object$ranef.ids, offset = object$offset, trial.size = object$trial.size, cutoffs = true_mod$cutoffs, powerparam = true_mod$powerparam)) } } set.seed(NULL) return(out) }
compareData <- function(x, y, tolerance = 10^-5) { tDir <- tempdir() on.exit(unlink(tDir, recursive = TRUE, force = TRUE)) .rmag <- function(f) { x <- try(read.magpie(f), silent = TRUE) if (!is.magpie(x)) return(NULL) attr(x, "comment") <- NULL return(x) } .getDir <- function(tDir, file, name) { if (dir.exists(file)) return(file) d <- file.path(tDir, name) if (file.exists(d)) unlink(d, recursive = TRUE, force = TRUE) untar(file, exdir = d) return(d) } xDir <- .getDir(tDir, x, "x") yDir <- .getDir(tDir, y, "y") out <- list(ok = 0, skip = 0, diff = 0, miss = 0) out$files <- list(notInX = setdiff(list.files(yDir), list.files(xDir)), notInY = setdiff(list.files(xDir), list.files(yDir)), inBoth = intersect(list.files(xDir), list.files(yDir))) maxchar <- max(vapply(out$files$inBoth, nchar, integer(1))) out$miss <- length(out$files$notInA) + length(out$files$notInA) .reportMissingFiles <- function(x, name) { if (length(x) > 0) { message(length(x), " file(s) missing in ", name, ": ", paste(x, collapse = ", ")) } } .reportMissingFiles(out$files$notInX, "x") .reportMissingFiles(out$files$notInY, "y") .dimEqual <- function(x, y) { equal <- TRUE for (i in 1:3) { if (!setequal(dimnames(x)[[i]], dimnames(y)[[i]])) equal <- FALSE } return(equal) } i <- 1 for (f in out$files$inBoth) { counter <- format(paste0("(", i, "/", length(out$files$inBoth), ") "), width = 10) message(counter, format(f, width = maxchar), " ... ", appendLF = FALSE) i <- i + 1 x <- .rmag(file.path(xDir, f)) y <- .rmag(file.path(yDir, f)) if (is.null(x) && is.null(y)) { message("skipped") out$skip <- out$skip + 1 } else { if (!identical(dim(x), dim(y))) { message("!= dim") out$diff <- out$diff + 1 } else if (!.dimEqual(x, y)) { message("!= dimnames") out$diff <- out$diff + 1 } else { diff <- max(abs(x - y)) if (!identical(x, y) && diff > tolerance) { message("!= values (max diff = ", round(diff, 8), ")") out$diff <- out$diff + 1 } else { message("OK") out$ok <- out$ok + 1 } } } } message("[OK ", out$ok, " | DIFF ", out$diff, " | SKIP ", out$skip, " | MISS ", out$miss, "]") }
context("updown") test_that("updown", { d1 <- matrix(c(100, 101, -0.79, -0.86, -0.17, -0.14, 0.53, 0.46), nrow = 2, ncol = 4) colnames(d1) <- c("timestamp", "x", "y", "z") expect_that(updown(x = d1), equals(c(-10.13181226251, -8.16879677542))) d2 <- matrix(c(100, 101, 102, 103, 104, -0.79, -0.36, 0.03, -0.16, 0.54, -0.27, -0.14, -0.25, -0.10, 0.21, -0.53, -0.46, 0.13, 0.97, 0.43), nrow = 5, ncol = 4) colnames(d2) <- c("timestamp", "x", "y", "z") expect_that(updown(x = d2), equals(c(-15.84488046458, -13.4781485902239, -61.9126506176981, -5.80805273666503, 16.9208127620101))) rm(list = c("d1", "d2")) })
dataAugmentation <- function(images, rotation_angles = 0, flip = FALSE, flop = FALSE, brightness_shift_lim = c(90, 110), saturation_shift_lim = c(95, 105), hue_shift_lim = c(80, 120), fraction_random_BSH = 0) { if(fraction_random_BSH < 0) stop("fraction_random_BSH must be postive") if(fraction_random_BSH > 1) stop("fraction_random_BSH must be between 0 and 1") if(any(rotation_angles != 0)){ images_aug_info <- images$info if(unique(images_aug_info$width) != unique(images_aug_info$height)) message("width and height of images differs, and there are rotation angles that are not 0. This may lead to invalid model input. Make sure that rotating is valid for your input") } if(!0 %in% rotation_angles) warning("0 is not in rotation_angles. That will remove the original images from the augmented image set") if(any(rotation_angles %% 90 != 0)) warning("Some rotation_angles are not multiples of 90. These rotated images will have different dimensions than the originals and might not be valid model input. ") images_aug_list <- lapply(rotation_angles, FUN = function(degrees) magick::image_rotate(images$img, degrees = degrees)) images_aug_info <- lapply(rotation_angles, FUN = function(x) data.frame(cbind(images$info, rotation = x))) images_aug_info <- do.call(rbind, images_aug_info) if(isTRUE(flip)) { images_aug_list <- c(images_aug_list, magick::image_flip(images$img)) images_aug_info <- rbind(cbind(images_aug_info, flip = FALSE), cbind(images$info, rotation = 0, flip = TRUE)) } else { images_aug_info <- cbind(images_aug_info, flip = FALSE) } if(isTRUE(flop)){ images_aug_list <- c(images_aug_list, magick::image_flop(images$img)) images_aug_info <- rbind(cbind(images_aug_info, flop = FALSE), cbind(images$info, rotation = 0, flip = FALSE, flop = TRUE)) } else { images_aug_info <- cbind(images_aug_info, flop = FALSE) } images_aug <- do.call("c", images_aug_list) attr(images_aug, "info") <- images_aug_info if(fraction_random_BSH != 0) { out2 <- randomBSH(img = images_aug, fraction_random_BSH = fraction_random_BSH, brightness_shift_lim = brightness_shift_lim, saturation_shift_lim = saturation_shift_lim, hue_shift_lim = hue_shift_lim) } else { out2 <- list(info = images_aug_info, img = images_aug) } return(out2) } randomBSH <- function(img, fraction_random_BSH, brightness_shift_lim, saturation_shift_lim, hue_shift_lim) { modify_these <- sort(sample(1:length(img), size = round(fraction_random_BSH * length(img)))) df_info <- attr(img, "info") df_info$brightness_shift <- 100 df_info$saturation_shift <- 100 df_info$hue_shift <- 100 for(i in modify_these){ brightness_shift <- runif(1, brightness_shift_lim[1], brightness_shift_lim[2]) saturation_shift <- runif(1, saturation_shift_lim[1], saturation_shift_lim[2]) hue_shift <- runif(1, hue_shift_lim[1], hue_shift_lim[2]) img_modified <- magick::image_modulate(img[i], brightness = brightness_shift, saturation = saturation_shift, hue = hue_shift) img[i] <- img_modified df_info[i,]$brightness_shift <- brightness_shift df_info[i,]$saturation_shift <- saturation_shift df_info[i,]$hue_shift <- hue_shift } return(list(info = df_info, img = img)) }
formals <- function(fun = sys.function(sys.parent()), envir = parent.frame()) { if(is.character(fun)) fun <- get(fun, mode = "function", envir = envir) .Internal(formals(fun)) } body <- function(fun = sys.function(sys.parent())) { if(is.character(fun)) fun <- get(fun, mode = "function", envir = parent.frame()) .Internal(body(fun)) } alist <- function (...) as.list(sys.call())[-1L] `body<-` <- function (fun, envir = environment(fun), value) { if(!is.function(fun)) warning("'fun' is not a function") if (is.expression(value)) { if (length(value) > 1L) warning("using the first element of 'value' of type \"expression\"") value <- value[[1L]] } as.function(c(as.list(formals(fun)), list(value)), envir) } `formals<-` <- function (fun, envir = environment(fun), value) { if(!is.function(fun)) warning("'fun' is not a function") bd <- body(fun) as.function(c(value, if(is.null(bd) || is.list(bd)) list(bd) else bd), envir) }
time_apply <- function(data, target, period, .fun, ..., start_date = NULL, side = "end", clean = FALSE, message = TRUE) { UseMethod("time_apply", data) } time_apply.default <- function(data, target, period, .fun, ..., start_date = NULL, side = "end", clean = FALSE, message = TRUE) { stop("Object is not of class `tbl_df` or `tbl_time`.", call. = FALSE) } time_apply.data.frame <- function(data, target, period, .fun, ..., start_date = NULL, side = "end", clean = FALSE, message = TRUE) { if (missing(target)) stop('Error in time_apply(): argument "target" is missing, with no default', call. = FALSE) if (missing(period)) stop('Error in time_apply(): argument "period" is missing, with no default', call. = FALSE) if (missing(.fun)) stop('Error in time_apply(): argument ".fun" is missing, with no default', call. = FALSE) data <- prep_tbl_time(data, message = F) date_col_expr <- tibbletime::get_index_quo(data) date_col_name <- dplyr::quo_name(date_col_expr) target_expr <- dplyr::enquo(target) if (is.character(period)) { ret <- data %>% tibbletime::collapse_by(period = period, clean = clean, start_date = start_date, side = side) %>% dplyr::group_by(!! tibbletime::get_index_quo(.)) %>% dplyr::mutate(time_apply = .fun(!! target_expr, ...)) %>% dplyr::ungroup() %>% dplyr::mutate(!! date_col_name := data %>% dplyr::pull(!! date_col_expr)) } else { ret <- data %>% dplyr::mutate( .period_groups = c(0, (1:(nrow(.) - 1) %/% period)) ) %>% dplyr::group_by(.period_groups) %>% dplyr::mutate( time_apply = .fun(!! target_expr, ...) ) %>% dplyr::ungroup() %>% dplyr::select(-.period_groups) } return(ret) } time_apply.grouped_df <- function(data, target, period, .fun, ..., start_date = NULL, side = "end", clean = FALSE, message = TRUE) { if (missing(target)) stop('Error in time_apply(): argument "target" is missing, with no default', call. = FALSE) if (missing(period)) stop('Error in time_apply(): argument "period" is missing, with no default', call. = FALSE) if (missing(.fun)) stop('Error in time_apply(): argument ".fun" is missing, with no default', call. = FALSE) data <- prep_tbl_time(data, message = F) target_expr <- dplyr::enquo(target) ret <- data %>% grouped_mapper( .f = time_apply, target = !! target_expr, period = period, .fun = .fun, ... = ..., start_date = start_date, side = side, clean = clean, message = message) return(ret) }
partd <- function(x) { d <- attr(x, "d") if (!is.null(d)) d else 1 } add_area <- function(df) { df$area <- (df$r - df$l) * (df$t - df$b) df } squeeze <- function(pieces, bounds = bound()) { scale_x <- function(x) x * (bounds$r - bounds$l) + bounds$l scale_y <- function(y) y * (bounds$t - bounds$b) + bounds$b pieces$l <- scale_x(pieces$l) pieces$r <- scale_x(pieces$r) pieces$b <- scale_y(pieces$b) pieces$t <- scale_y(pieces$t) pieces } bound <- function(t = 1, r = 1, b = 0, l = 0) { data.frame(t = t, r = r, b = b, l = l) } set_offset <- function(dividers, offset = 0) { if (length(offset) < length(dividers)) { offset <- rep(offset, length = length(dividers)) } lapply(seq_along(dividers), function(i) { div <- dividers[[i]] if (is.character(div)) div <- match.fun(div) f <- function(...) div(..., offset = offset[[i]]) mostattributes(f) <- attributes(div) f }) }
context("unit test for {name} endpoint") testthat::setup({{ }}) httptest::with_mock_api({{ test_that("healthcheck returns a success", {{ url <- generate_url(config$host, config$port, "utility/healthcheck") expect_status_200(GET(url)) }}) }}) httptest::with_mock_api({{ describe("class", {{ it("POST with character returns a character", {{ input <- "Hello World!" x <- jsonlite::toJSON(input, auto_unbox = TRUE) url <- generate_url(config$host, config$port, "utility/class") expect_status_200(response <- POST(url, body = x)) output <- extract_content_text(response) %>% jsonlite::fromJSON(flatten = TRUE) %>% stringr::str_remove_all('\"') expect_match(output, "character") }}) it("POST with data.frame returns a data.frame", {{ input <- mtcars x <- jsonlite::toJSON(input, auto_unbox = TRUE) url <- generate_url(config$host, config$port, "utility/class") expect_status_200(response <- POST(url, body = x)) output <- extract_content_text(response) %>% jsonlite::fromJSON(flatten = TRUE) %>% stringr::str_remove_all('\"') expect_match(output, "data.frame") }}) }}) }}) testthat::teardown({{httptest::stop_capturing()}})
manylm.influence.measures <- function (model) { is.influential <- function(infmat, n) { k <- ncol(infmat) - 4 if (n <= k) stop("too few cases, n < k") absmat <- abs(infmat) result <- cbind(absmat[, 1:k] > 1, absmat[, k + 1] > 3 * sqrt(k/(n - k)), abs(1 - infmat[, k + 2]) > (3 * k)/(n - k), pf(infmat[, k + 3], k, n - k) > 0.5, infmat[, k + 4] > (3 * k)/n) dimnames(result) <- dimnames(infmat) result } infl <- manylm.influence(model) p <- model$rank e <- weighted.residuals(model) n.vars <- NCOL(e) n <- nrow(e) s <- sqrt(colSums(e^2, na.rm = TRUE)/df.residual(model)) s <- matrix( rep(s, each=n ) , nrow=n, ncol=n.vars ) xxi <- chol2inv(model$qr$qr, model$qr$rank) si <- infl$sigma h <- infl$hat vn <- variable.names(model) vn[vn == "(Intercept)"] <- "1_" dffits <- e * sqrt(h)/(si * (1 - h)) cov.ratio <- (si/s)^(2 * p)/(1 - h) cooks.d <- ((e/(s * (1 - h)))^2 * h)/p coefs <- infl$coefficients sigma <- infl$sigma dfbs <- infmat <- is.inf <- list() for(i in 1:n.vars) { dfbs[[i]] <- coefs[[i]]/outer(sigma[,i], sqrt(diag(xxi))) colnames(dfbs[[i]]) <- paste("dfb", abbreviate(vn), sep = ".") infmati <- cbind(dfbs[[i]], dffit = dffits[,i], cov.r = cov.ratio[,i], cook.d = cooks.d[,i], hat = h) infmati[is.infinite(infmati)] <- NaN infmat[[i]] <- infmati is.inf[[i]] <- is.influential(infmati, sum(h > 0)) } names(infmat) <- names(is.inf) <- colnames(e) ans <- list(infmat = infmat, is.inf = is.inf, call = model$call) class(ans) <- "infl.mvabund" ans }
hexagon_maze <- function(depth,unit_len,clockwise=TRUE,method=c('two_trapezoids','six_triangles','three_parallelograms','random'), start_from=c('midpoint','corner'), boustro=c(1,1), draw_boundary=FALSE,num_boundary_holes=2,boundary_lines=TRUE, boundary_holes=NULL,boundary_hole_color=NULL,boundary_hole_locations=NULL, boundary_hole_arrows=FALSE, end_side=1) { method <- match.arg(method) start_from <- match.arg(start_from) num_segs <- round(2^depth) multiplier <- ifelse(clockwise,1,-1) if (start_from=='corner') { turtle_forward(distance=unit_len * num_segs/2) } if (depth > 1) { turtle_up() my_method <- switch(method, random={ sample(c('two_trapezoids','six_triangles','three_parallelograms'),1) }, method) switch(my_method, two_trapezoids={ magic_ratio <- sqrt(3) / 4 .turn_right(multiplier * 90) turtle_forward(2*num_segs * unit_len * magic_ratio) .turn_left(multiplier * 90) iso_trapezoid_maze(depth=depth,unit_len=unit_len,clockwise=clockwise, start_from='midpoint', boustro=rev(boustro), draw_boundary=TRUE,boundary_lines=c(1),boundary_holes=c(1)) iso_trapezoid_maze(depth=depth,unit_len=unit_len,clockwise=!clockwise,draw_boundary=FALSE) .turn_left(multiplier * 90) turtle_forward(2*num_segs * unit_len * magic_ratio) .turn_right(multiplier * 90) }, six_triangles={ turtle_backward(distance=unit_len * num_segs/2) bholes <- sample.int(n=6,size=5) for (iii in c(1:6)) { eq_triangle_maze(depth=depth,unit_len=unit_len,clockwise=clockwise,method='random',draw_boundary=TRUE, start_from='corner', boustro=rev(boustro), boundary_lines=2,boundary_holes=iii %in% bholes) turtle_forward(distance=unit_len * num_segs) .turn_right(multiplier*60) } turtle_forward(distance=unit_len * num_segs/2) }, three_parallelograms={ bholes <- sample.int(n=3,size=2) for (iii in 1:3) { parallelogram_maze(unit_len=unit_len,height=num_segs,width=num_segs,angle=60,clockwise=clockwise, width_boustro=rev(boustro),height_boustro=rev(boustro), draw_boundary=TRUE,boundary_lines=3,num_boundary_holes=0,boundary_holes=iii %in% bholes) turtle_forward(num_segs * unit_len / 2) .turn_right(multiplier * 60) turtle_forward(num_segs * unit_len) .turn_right(multiplier * 60) turtle_forward(num_segs * unit_len / 2) } }) } if (draw_boundary) { turtle_backward(distance=unit_len * num_segs/2) if (is.null(boundary_hole_locations)) { boundary_hole_locations <- .rboustro(6,boustro=boustro,nsegs=num_segs) } .do_boundary(unit_len,lengths=rep(num_segs,6),angles=multiplier * 60, num_boundary_holes=num_boundary_holes,boundary_lines=boundary_lines, boundary_holes=boundary_holes,boundary_hole_color=boundary_hole_color, boundary_hole_locations=boundary_hole_locations,boundary_hole_arrows=boundary_hole_arrows) turtle_forward(distance=unit_len * num_segs/2) } if ((end_side != 1) && (!is.null(end_side))) { for (iii in 1:(end_side-1)) { turtle_forward(distance=unit_len * num_segs/2) .turn_right(multiplier * 60) turtle_forward(distance=unit_len * num_segs/2) } } if (start_from=='corner') { turtle_backward(distance=unit_len * num_segs/2) } }
library(purrr) data <- tbl_df(data) data %>% count(group) xuniques <- sort(unique(data$x)) maxx <- max(data$x) length(xuniques) dataadd <- map_df(unique(data$group), function(g){ datag <- filter(data, group == g) xgrup <- datag$x xlack <- setdiff(xuniques, xgrup) xgrup <- unique(c(0L, xgrup, maxx)) map_df(2:length(xgrup), function(place) { xlp <- xlack[xgrup[place- 1] < xlack & xlack < xgrup[place]] if(length(xlp) == 0) return(NULL) daux <- datag %>% filter(x == xgrup[place- 1]) %>% select(-x) if(nrow(daux) > 0) { return(cbind(data_frame(x = xlp), daux)) } else { NULL } }) }) data <- bind_rows(data, dataadd) distinct(bind_rows(data, dataadd))
library(dplyr) library(tidyr) test_that("combine_chains works on a simple example", { data(line, package = "coda") ref = line %>% tidy_draws() %>% mutate( .draw = as.integer(.iteration + (.chain - 1) * max(.iteration)) ) line %>% tidy_draws() %>% combine_chains() %>% expect_equal(ref) }) test_that("combine_chains works with a named output column", { data(line, package = "coda") ref = line %>% tidy_draws() %>% mutate(d = as.integer(.iteration + (.chain - 1) * max(.iteration))) line %>% tidy_draws() %>% combine_chains(into = "d") %>% expect_equal(ref) })
convert2Records <- function( infor, records ) { d.names <- names( records ) n.vars <- c( waGetPara( "records.index" ), waGetPara( "records.vars" ) ) if( !identical( n.vars %in% d.names, rep( TRUE, length( n.vars ) ) ) ) { stop( paste( "Records columns needed: ", paste( n.vars, collapse = ", ") ) ) } i.vars <- c( "Name", "Number", "Latitude", "Longitude" ) if( !identical( i.vars %in% names( infor ), rep( TRUE, length( i.vars ) ) ) ) { stop( paste( "Infor columns needed: ", paste( i.vars, collapse = ", ") ) ) } a <- NULL for ( i in seq ( along = n.vars ) ) { a[[n.vars[i]]] <- records[[n.vars[i]]] } extra <- NULL extra$avgt <- ( a$maxt + a$mint ) / 2 extra$vpd <- vpd.apsim( a$maxt, a$mint ) record <- methods::new( "WeaAnaSite", name = infor$Name, number = infor$Number, latitude = as.numeric( infor$Latitude ), longitude = as.numeric( infor$Longitude ), year = a$year, day = a$day, radn = a$radn, maxt = a$maxt, mint = a$mint, rain = a$rain, evap = a$evap, vp = a$vp, code = as.character( a$code ), extra = extra, file.path = as.character( NA ), data.format = as.character( NA ), load.later = FALSE ) result <- c(NULL, newPointer( methods::new( "result", name = as.character( NULL ), type = as.character( NULL ) ) ) ) records <- methods::new( "WeaAna", num = 1, records = c( NULL, newPointer( record ) ), result = result ) return( records ) }
context("Weight Calculations") test_that("weights calculations equal", { XXX <- cbind(rep(1, 10), seq(0, 1, length = 10)) AAA <- rep(c(0, 1), 5) fff <- c(.1, .1) aaa <- c(.1, .5, .9) GGG <- sort(rep(1:5, 2)) mmm2 <- matrix(c(0.616547184192009, 1.712631, 0.616547184192009, 0.614796738538913, 1.707769, 0.614796738538913, 0.613057773666495, 1.702938, 0.613057773666495, 0.611330209096351, 1.698139, 0.611330209096351, 0.609613965009724, 1.693372, 0.609613965009724), byrow = T, ncol = 3, dimnames = list(unique(GGG), aaa)) mmm3 <- array(c(-0.07902959, -0.01322103, 0.01576307, -0.07851113, -0.03058825, 0.01598160, -0.07799631, -0.04772718, 0.01619665, -0.07748510, -0.06464023, 0.01640826, -0.07697746, -0.08132978, 0.01661645, -0.2195266, -0.03672508, 0.04378631, -0.2180865, -0.08496735, 0.04439334, -0.2166564, -0.13257550, 0.04499070, -0.2152364, -0.17955620, 0.04557849, -0.2138263, -0.22591605, 0.04615682, -0.07902959, -0.01322103, 0.01576307, -0.07851113, -0.03058825, 0.01598160, -0.07799631, -0.04772718, 0.01619665, -0.07748510, -0.06464023, 0.01640826, -0.07697746, -0.08132978, 0.01661645), dim = c(3, 5, 3), dimnames = list(1:3, unique(GGG), aaa)) mmm3 <- aperm(mmm3, c(2,1,3)) expect_equal(wght_calc(integrand = logit_integrand, allocation = .9, X = XXX[1:2, ], A = AAA[1:2], parameters = fff, randomization = .5), 0.462462731646267) expect_equal(wght_calc(integrand = logit_integrand, allocation = .9, X = XXX[1:2, ], A = AAA[1:2], parameters = c(fff, 1), randomization = .5), 0.492904177726425) expect_equal(wght_calc(integrand = logit_integrand, allocation = .9, X = XXX[1:2, ], A = AAA[1:2], parameters = c(fff, 1), randomization = .5), 0.492904177726425) expect_equal(wght_deriv_calc(integrand = logit_integrand, allocation = .3, X = XXX[1:2, ], A = AAA[1:2], parameters = c(1, .5, 1), randomization = .5), c(-0.1277388445291851, -0.0280714662250347, 0.0947948595448454)) expect_equal(wght_matrix(integrand = logit_integrand, allocations = aaa, X = XXX, A = AAA, G = GGG, parameters = c(fff, 5), randomization = .5, runSilent = TRUE), mmm2, tolerance = 1e-6) expect_equal(wght_deriv_array(integrand = logit_integrand, allocations = aaa, X = XXX, A = AAA, G = GGG, parameters = c(fff, 5), randomization = .5, runSilent = TRUE), mmm3, tolerance = 1e-6, check.attributes = FALSE) })
QRWSimul <- function(VecX, tau, times, subj, X, y, d, kn, degree, lambda, gam){ dim = length(subj) X = matrix(X, nrow=dim) H = length(tau) px = ncol(X) n = length(unique(subj)) if(px != length(VecX)) stop("the length of VecX and the number of covariate(s) must match") XX = as.matrix(X) if(all(X[,1]==1)) VecX[1]=1 else VecX[1] = (VecX[1] - min(X[,1]))/(max(X[,1])-min(X[,1])) if(all(X[,1]==1)) X[,1]=X[,1] else X[,1] = (X[,1] - min(X[,1]))/(max(X[,1])-min(X[,1])) for(k in 2:px){ VecX[k] = (VecX[k] - min(X[,k]))/(max(X[,k])-min(X[,k])) X[,k] = (X[,k] - min(X[,k]))/(max(X[,k])-min(X[,k])) } hatVt = Vt(times, subj, X, y, d, tau, kn, degree, lambda, gam) hat_Vt = hatVt$hat_Vt r50 = hatVt$r50 Wtau = Wtau(times, subj, X=XX, y, d, tau, kn, degree, lambda, gam, hat_Vt, r50)$Wtau lambda_all = lambdak_wsimul(times, subj, X, y, d, tau, kn, degree, lambda, gam, hat_Vt, Wtau=Wtau) lambdasicr = lambda_all$lambdasicr lambdasic = lambda_all$lambdasic wsimul = ncqr_wsimul(times, subj, y, X, tau, kn, degree, lambda=lambdasicr, lambcross=lambdasic, hat_Vt, Wtau=Wtau, d) W = wsimul$W alpha = wsimul$alpha hat_bt = wsimul$hat_bt Hpx = rep(seq(1,px), H) Xbeta = matrix(NA, dim, H*px) for(h in 1:(H*px)) { Xbeta[,h]=hat_bt[,h]*VecX[Hpx[h]] } qhat_h = matrix(NA, dim, H) for(h in 1:H){ qhat_h[,h] = rowSums(Xbeta[,((h-1)*px+1):(px*h)]) } HpxB = rep(px,H) cum_HpxB = cumsum(HpxB) cum_HpxA = c(1, c(cum_HpxB[seq(1:(H-1))]+1)) hat_bt0_ori = hat_bt[,cum_HpxA] hat_btk_ori = hat_bt[,seq(2,px)] hat_btk = matrix(NA, dim, (px-1)) hat_btk0 = matrix(0, dim, (px-1)) for(k in 1:(px-1)){ hat_btk[,k] = hat_btk_ori[,k]/(max(XX[,(k+1)])-min(XX[,(k+1)])) hat_btk0[,k] = hat_btk_ori[,k]*min(XX[,(k+1)])/(max(XX[,(k+1)])-min(XX[,(k+1)])) } hat_bt0 = hat_bt0_ori - rowSums(hat_btk0) out = list(W=W, alpha=alpha, hat_bt0=hat_bt0, hat_btk=hat_btk, qhat_h = qhat_h, Wtau=Wtau, hat_Vt = hat_Vt) return(out) }
load("FH/milk.RData") test_that("Does the fh function in emdi return the same variance, EBLUP and MSE estimates as the function mseFH of package sae?",{ milk$var <- milk$SD^2 fh_reml <- fh(fixed = yi ~ as.factor(MajorArea), vardir = "var", combined_data = milk, domains = "SmallArea", method = "reml", interval = c(0, 1000), MSE = TRUE, B = c(0,0)) fh_reml_sae <- read.csv("FH/fh_reml_sae.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(fh_reml$model$variance, fh_reml_sae$variance[1], tolerance = 0.0001) expect_equal(fh_reml$ind$FH, as.vector(fh_reml_sae$EBLUP), tolerance = 0.0001) expect_equal(fh_reml$MSE$FH, fh_reml_sae$MSE, tolerance = 0.00001) fh_ml <- fh(fixed = yi ~ as.factor(MajorArea), vardir = "var", combined_data = milk, domains = "SmallArea", method = "ml", interval = c(0, 1000), MSE = TRUE, B = c(0,0)) fh_ml_sae <- read.csv("FH/fh_ml_sae.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(fh_ml$model$variance, fh_ml_sae$variance[1], tolerance = 0.0001) expect_equal(fh_ml$ind$FH, fh_ml_sae$EBLUP, tolerance = 0.0001) expect_equal(fh_ml$MSE$FH, fh_ml_sae$MSE, tolerance = 0.0001) }) load("FH/grapes.RData") load("FH/grapesprox.RData") test_that("Does the fh function in emdi return the same variance, correlation parameter, EBLUP and MSE estimates as the function mseSFH of package sae?",{ grapes$Domain <- c(1:15) fh_spatial_reml_analytical <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", tol = 0.0001, maxit = 100, combined_data = grapes, domains = "Domain", method = "reml", correlation = "spatial", corMatrix = as.matrix(grapesprox), MSE = TRUE, mse_type = "analytical") fh_spatial_reml_analytical_sae <- read.csv("FH/fh_spatial_reml_analytical_sae.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(fh_spatial_reml_analytical$model$variance[1,2], fh_spatial_reml_analytical_sae$variance[1]) expect_equal(fh_spatial_reml_analytical$model$variance[1,1], fh_spatial_reml_analytical_sae$correlation[1]) expect_equal(fh_spatial_reml_analytical$ind$FH, as.vector(fh_spatial_reml_analytical_sae$EBLUP)) expect_equal(fh_spatial_reml_analytical$MSE$FH, fh_spatial_reml_analytical_sae$MSE) fh_spatial_ml_analytical <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", tol = 0.0001, maxit = 100, combined_data = grapes, domains = "Domain", method = "ml", correlation = "spatial", corMatrix = as.matrix(grapesprox), MSE = TRUE, mse_type = "analytical") fh_spatial_ml_analytical_sae <- read.csv("FH/fh_spatial_ml_analytical_sae.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(fh_spatial_ml_analytical$model$variance[1,2], fh_spatial_ml_analytical_sae$variance[1]) expect_equal(fh_spatial_ml_analytical$model$variance[1,1], fh_spatial_ml_analytical_sae$correlation[1]) expect_equal(fh_spatial_ml_analytical$ind$FH, as.vector(fh_spatial_ml_analytical_sae$EBLUP)) expect_equal(fh_spatial_ml_analytical$MSE$FH, fh_spatial_ml_analytical_sae$MSE) }) test_that("Does the fh function in emdi return the same variance, correlation parameter, EBLUP and MSE estimates as the function npbmseSFH of package sae?",{ suppressWarnings(RNGversion("3.6.3")) grapes$Domain <- c(1:15) fh_spatial_reml_npb <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", tol = 0.0001, maxit = 100, combined_data = grapes, domains = "Domain", method = "reml", correlation = "spatial", corMatrix = as.matrix(grapesprox), MSE = TRUE, mse_type = "spatialnonparboot", B = 3, seed = 456) fh_spatial_reml_npb_bc <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", tol = 0.0001, maxit = 100, combined_data = grapes, domains = "Domain", method = "reml", correlation = "spatial", corMatrix = as.matrix(grapesprox), MSE = TRUE, mse_type = "spatialnonparbootbc", B = 3, seed = 456) fh_spatial_reml_npb_sae <- read.csv("FH/fh_spatial_reml_npb_sae.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(fh_spatial_reml_npb$model$variance[1,2], fh_spatial_reml_npb_sae$variance[1]) expect_equal(fh_spatial_reml_npb$model$variance[1,1], fh_spatial_reml_npb_sae$correlation[1]) expect_equal(fh_spatial_reml_npb$ind$FH, as.vector(fh_spatial_reml_npb_sae$EBLUP)) expect_equal(fh_spatial_reml_npb$MSE$FH, fh_spatial_reml_npb_sae$MSE, tolerance = 0.000001) expect_equal(fh_spatial_reml_npb_bc$MSE$FH, fh_spatial_reml_npb_sae$MSE.BC, tolerance = 0.000001) }) test_that("Does the fh function in emdi return the same variance, correlation parameter, EBLUP and MSE estimates as the function pbmseSFH of package sae?",{ grapes$Domain <- c(1:15) fh_spatial_reml_pb <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", tol = 0.0001, maxit = 100, combined_data = grapes, domains = "Domain", method = "reml", correlation = "spatial", corMatrix = as.matrix(grapesprox), MSE = TRUE, mse_type = "spatialparboot", B = 3, seed = 567) fh_spatial_reml_pb_bc <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", tol = 0.0001, maxit = 100, combined_data = grapes, domains = "Domain", method = "reml", correlation = "spatial", corMatrix = as.matrix(grapesprox), MSE = TRUE, mse_type = "spatialparbootbc", B = 3, seed = 567) fh_spatial_reml_pb_sae <- read.csv("FH/fh_spatial_reml_pb_sae.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(fh_spatial_reml_pb$model$variance[1,2], fh_spatial_reml_pb_sae$variance[1]) expect_equal(fh_spatial_reml_pb$model$variance[1,1], fh_spatial_reml_pb_sae$correlation[1]) expect_equal(fh_spatial_reml_pb$ind$FH, as.vector(fh_spatial_reml_pb_sae$EBLUP)) expect_equal(fh_spatial_reml_pb$MSE$FH, fh_spatial_reml_pb_sae$MSE) expect_equal(fh_spatial_reml_pb_bc$MSE$FH, fh_spatial_reml_pb_sae$MSE.BC) grapes$Domain <- c(1:15) fh_spatial_ml_pb <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", tol = 0.0001, maxit = 100, combined_data = grapes, domains = "Domain", method = "ml", correlation = "spatial", corMatrix = as.matrix(grapesprox), MSE = TRUE, mse_type = "spatialparboot", B = 3, seed = 123) fh_spatial_ml_pb_bc <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", tol = 0.0001, maxit = 100, combined_data = grapes, domains = "Domain", method = "ml", correlation = "spatial", corMatrix = as.matrix(grapesprox), MSE = TRUE, mse_type = "spatialparbootbc", B = 3, seed = 123) fh_spatial_ml_pb_sae <- read.csv("FH/fh_spatial_ml_pb_sae.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(fh_spatial_ml_pb$model$variance[1,2], fh_spatial_ml_pb_sae$variance[1]) expect_equal(fh_spatial_ml_pb$model$variance[1,1], fh_spatial_ml_pb_sae$correlation[1]) expect_equal(fh_spatial_ml_pb$ind$FH, fh_spatial_ml_pb_sae$EBLUP) expect_equal(fh_spatial_ml_pb$MSE$FH, fh_spatial_ml_pb_sae$MSE) expect_equal(fh_spatial_ml_pb_bc$MSE$FH, fh_spatial_ml_pb_sae$MSE.BC) }) test_that("Does the fh function in emdi return the same variance, EBLUP and MSE estimates as the functions rfh and mse (pseudo) of package saeRobust?",{ select <- as.logical(Sys.getenv("_R_TEST_ROBUST_TRUEFALSE_")) if (is.na(select)) { select <- FALSE } if (select) { grapes$Domain <- c(1:15) fh_robust <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", combined_data = grapes, domains = "Domain", method = "reblup", tol = 1e-06, maxit = 100, k = 1.345, MSE = TRUE, mse_type = "pseudo") fh_robust_saeRobust <- read.csv("FH/fh_robust_saeRobust.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(unname(fh_robust$model$variance), fh_robust_saeRobust$variance[1]) expect_equal(fh_robust$ind$FH, fh_robust_saeRobust$EBLUP) expect_equal(fh_robust$MSE$FH, fh_robust_saeRobust$MSE) grapes$Domain <- c(1:15) fh_robustbc <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", combined_data = grapes, domains = "Domain", method = "reblupbc", tol = 1e-06, maxit = 100, k = 1.345, mult_constant = 2, MSE = TRUE, mse_type = "pseudo") fh_robustbc_saeRobust <- read.csv("FH/fh_robustbc_saeRobust.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(unname(fh_robustbc$model$variance), fh_robust_saeRobust$variance[1]) expect_equal(fh_robustbc$ind$FH, fh_robustbc_saeRobust$EBLUP) expect_equal(fh_robustbc$MSE$FH, fh_robustbc_saeRobust$MSE) } else { expect_equal(TRUE, TRUE) } }) test_that("Does the fh function in emdi return the same variance, EBLUP and MSE estimates as the functions rfh and mse (boot) of package saeRobust?",{ select <- as.logical(Sys.getenv("_R_TEST_ROBUST_TRUEFALSE_")) if (is.na(select)) { select <- FALSE } if (select) { grapes$Domain <- c(1:15) fh_robust_boot <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", combined_data = grapes, domains = "Domain", method = "reblup", tol = 1e-06, maxit = 100, k = 1.345, MSE = TRUE, mse_type = "boot", B = 3, seed = 123) fh_robust_boot_saeRobust <- read.csv("FH/fh_robust_boot_saeRobust.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(unname(fh_robust_boot$model$variance), fh_robust_boot_saeRobust$variance[1]) expect_equal(fh_robust_boot$ind$FH, fh_robust_boot_saeRobust$EBLUP) expect_equal(fh_robust_boot$MSE$FH, fh_robust_boot_saeRobust$MSE) grapes$Domain <- c(1:15) fh_robustbc_boot <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", combined_data = grapes, domains = "Domain", method = "reblupbc", tol = 1e-06, maxit = 100, k = 1.345, mult_constant = 2, MSE = TRUE, mse_type = "boot", B = 3, seed = 123) fh_robustbc_boot_saeRobust <- read.csv("FH/fh_robustbc_boot_saeRobust.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(unname(fh_robustbc_boot$model$variance), fh_robust_boot_saeRobust$variance[1]) expect_equal(fh_robustbc_boot$ind$FH, fh_robustbc_boot_saeRobust$EBLUP) expect_equal(fh_robustbc_boot$MSE$FH, fh_robustbc_boot_saeRobust$MSE) } else { expect_equal(TRUE, TRUE) } }) test_that("Does the fh function in emdi return the same variance, correlation parameter, EBLUP and MSE estimates as the functions rfh and mse (pseudo) of package saeRobust?",{ select <- as.logical(Sys.getenv("_R_TEST_ROBUST_TRUEFALSE_")) if (is.na(select)) { select <- FALSE } if (select) { grapes$Domain <- c(1:15) fh_robust_spatial <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", combined_data = grapes, domains = "Domain", method = "reblup", tol = 1e-06, maxit = 100, k = 1.345, correlation = "spatial", corMatrix = grapesprox, MSE = TRUE, mse_type = "pseudo") fh_robust_spatial_saeRobust <- read.csv("FH/fh_robust_spatial_saeRobust.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(fh_robust_spatial$model$variance$variance, fh_robust_spatial_saeRobust$variance[1]) expect_equal(fh_robust_spatial$model$variance$correlation, fh_robust_spatial_saeRobust$correlation[1]) expect_equal(fh_robust_spatial$ind$FH, fh_robust_spatial_saeRobust$EBLUP) expect_equal(fh_robust_spatial$MSE$FH, fh_robust_spatial_saeRobust$MSE) grapes$Domain <- c(1:15) fh_robust_spatial_bc <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", combined_data = grapes, domains = "Domain", method = "reblupbc", tol = 1e-06, maxit = 100, k = 1.345, mult_constant = 2, correlation = "spatial", corMatrix = grapesprox, MSE = TRUE, mse_type = "pseudo") fh_robustbc_spatial_saeRobust <- read.csv("FH/fh_robustbc_spatial_saeRobust.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(fh_robust_spatial_bc$model$variance$variance, fh_robustbc_spatial_saeRobust$variance[1]) expect_equal(fh_robust_spatial_bc$model$variance$correlation, fh_robustbc_spatial_saeRobust$correlation[1]) expect_equal(fh_robust_spatial_bc$ind$FH, fh_robustbc_spatial_saeRobust$EBLUP) expect_equal(fh_robust_spatial_bc$MSE$FH, fh_robustbc_spatial_saeRobust$MSE) } else { expect_equal(TRUE, TRUE) } }) test_that("Does the fh function in emdi return the same variance, correlation parameter, EBLUP and MSE estimates as the functions rfh and mse (boot) of package saeRobust?",{ select <- as.logical(Sys.getenv("_R_TEST_ROBUST_TRUEFALSE_")) if (is.na(select)) { select <- FALSE } if (select) { grapes$Domain <- c(1:15) fh_robust_spatial_boot <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", combined_data = grapes, domains = "Domain", method = "reblup", tol = 1e-06, maxit = 100, k = 1.345, correlation = "spatial", corMatrix = grapesprox, MSE = TRUE, mse_type = "boot", B = 3, seed = 123) fh_robust_spatial_boot_saeRobust <- read.csv("FH/fh_robust_spatial_boot_saeRobust.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(fh_robust_spatial_boot$model$variance$variance, fh_robust_spatial_boot_saeRobust$variance[1]) expect_equal(fh_robust_spatial_boot$model$variance$correlation, fh_robust_spatial_boot_saeRobust$correlation[1]) expect_equal(fh_robust_spatial_boot$ind$FH, fh_robust_spatial_boot_saeRobust$EBLUP) expect_equal(fh_robust_spatial_boot$MSE$FH, fh_robust_spatial_boot_saeRobust$MSE) grapes$Domain <- c(1:15) fh_robust_spatial_bc_boot <- fh(fixed = grapehect ~ area + workdays - 1, vardir = "var", combined_data = grapes, domains = "Domain", method = "reblupbc", tol = 1e-06, maxit = 100, k = 1.345, mult_constant = 2, correlation = "spatial", corMatrix = grapesprox, MSE = TRUE, mse_type = "boot", B = 3, seed = 123) fh_robust_spatial_bc_boot_saeRobust <- read.csv("FH/fh_robust_spatial_bc_boot_saeRobust.csv", sep = ",", stringsAsFactors = TRUE) expect_equal(fh_robust_spatial_bc_boot$model$variance$variance, fh_robust_spatial_bc_boot_saeRobust$variance[1]) expect_equal(fh_robust_spatial_bc_boot$model$variance$correlation, fh_robust_spatial_bc_boot_saeRobust$correlation[1]) expect_equal(fh_robust_spatial_bc_boot$ind$FH, fh_robust_spatial_bc_boot_saeRobust$EBLUP) expect_equal(fh_robust_spatial_bc_boot$MSE$FH, fh_robust_spatial_bc_boot_saeRobust$MSE) } else { expect_equal(TRUE, TRUE) } })
TreeDep_plot <- function(my_data , variable1 , variable2 = "Non-existent", start_month , start_day , stop_month , stop_day){ units_names <- c("Hum", "Pres", "Precip", "Rad", "Temp", "Wind", "Daylight", "BAI", "LAI", "Conc_", "Dep_", "Res_", "Fric_") units_names4 <- substr(units_names, 1,4) units <- data.frame("%", "kPa", "mm", "W m-2", "Celsius", "m s-1", "unitless", "m2 bark m-2 tree covered area", "m2 leaf m-2 tree covered area", "micrograms m-3", "g m-2 h-1", "s m-1", "m s-1") colnames(units) <- units_names4 if(substr(variable1, 1,7)=="Dep_vel"){ variable1_units <- "m s-1" }else{ variable1_units <- as.character(units[,substr(variable1, 1,4)]) } if(variable1 %in% units_names[1:9]){ variable1_values <- my_data[,variable1] }else{ dep_df1 <- do.call(variable1, list(my_data)) variable1_values <- dep_df1[,2] } if(variable2=="Non-existent"){ my_df <- cbind.data.frame(Dates = my_data[,c("Dates")], variable1_values) colnames(my_df)[c(2)] <- c(variable1) my_df$year <- substr(my_df$Dates, 1, 4) my_df$month <- substr(my_df$Dates, 6, 7) my_df$day <- substr(my_df$Dates, 9, 10) my_df$hour <- substr(my_df$Dates, 12, 19) my_df$my_time <- as.POSIXct(strptime(paste(my_df$year,"-",my_df$month,"-",my_df$day, " ", my_df$hour, sep=""), "%Y-%m-%d %H:%M:%S")) my_dates <- c(as.character(start_month), as.character(start_day), as.character(stop_month), as.character(stop_day)) my_dates[nchar(my_dates)==1] <- paste(0, my_dates[nchar(my_dates)==1], sep="" ) ID_start_day <- which(as.character(my_df$day)==my_dates[2] & my_df$month==my_dates[1]) ID_stop_day <- which(as.character(my_df$day)==my_dates[4] & my_df$month==my_dates[3]) my_df_selected <- my_df[c(ID_start_day[1]:ID_stop_day[length(ID_stop_day)]),] ggplot2::ggplot(my_df_selected, aes_string(x = "my_time")) + geom_line(aes(y = my_df_selected[,c(variable1)], colour = c(variable1), linetype = c(variable1))) + scale_linetype_manual(values = c(2)) + scale_colour_manual(values = c("blue")) + labs(y = paste(variable1, " (", variable1_units, ")", sep=""), x = "Date and time",colour = "Legend", linetype = "Legend")+ theme(legend.key.height=unit(1, "cm"), plot.margin = unit(c(0.5,0.5,0.5,0.5), "lines"))+ ggtitle(paste("Hourly", variable1)) + theme(plot.title = element_text(hjust = 0.5)) }else{ if(substr(variable2, 1,7)=="Dep_vel"){ variable2_units <- "m s-1" }else{ variable2_units <- as.character(units[,substr(variable2, 1,4)]) } if(variable2 %in% units_names[1:9]){ variable2_values <- my_data[,variable2] }else{ dep_df2 <- do.call(variable2, list(my_data)) variable2_values <- dep_df2[,2] } my_df <- cbind.data.frame(Dates = my_data[,c("Dates")], variable1_values, variable2_values) colnames(my_df)[c(2:3)] <- c(variable1, variable2) my_df$year <- substr(my_df$Dates, 1, 4) my_df$month <- substr(my_df$Dates, 6, 7) my_df$day <- substr(my_df$Dates, 9, 10) my_df$hour <- substr(my_df$Dates, 12, 19) my_df$my_time <- as.POSIXct(strptime(paste(my_df$year,"-",my_df$month,"-",my_df$day, " ", my_df$hour, sep=""), "%Y-%m-%d %H:%M:%S")) my_dates <- c(as.character(start_month), as.character(start_day), as.character(stop_month), as.character(stop_day)) my_dates[nchar(my_dates)==1] <- paste(0, my_dates[nchar(my_dates)==1], sep="" ) ID_start_day <- which(as.character(my_df$day)==my_dates[2] & my_df$month==my_dates[1]) ID_stop_day <- which(as.character(my_df$day)==my_dates[4] & my_df$month==my_dates[3]) my_df_selected <- my_df[c(ID_start_day[1]:ID_stop_day[length(ID_stop_day)]),] range_var1 <- max(my_df_selected[,c(variable1)], na.rm = T) - min(my_df_selected[,c(variable1)], na.rm = T) if(range_var1==0){ range_var1 <- ceiling(max(my_df_selected[,c(variable1)], na.rm = T)) } range_var2 <- max(my_df_selected[,c(variable2)], na.rm = T) - min(my_df_selected[,c(variable2)], na.rm = T) if(range_var2==0){ range_var2 <- ceiling(max(my_df_selected[,c(variable2)], na.rm = T)) } ratio <- range_var1 / range_var2 ggplot2::ggplot(my_df_selected, aes_string(x = "my_time")) + geom_line(aes(y = my_df_selected[,c(variable1)], colour = c(variable1), linetype = c(variable1))) + geom_line(aes(y =my_df_selected[,c(variable2)] * ratio, colour = c(variable2), linetype = c(variable2))) + scale_y_continuous(sec.axis = sec_axis(~. / ratio, name = paste(variable2, " (", variable2_units, ")", sep=""))) + scale_linetype_manual(values = c(2,1)) + scale_colour_manual(values = c("blue", "red")) + labs(y = paste(variable1, " (", variable1_units, ")", sep=""), x = "Date and time",colour = "Legend", linetype = "Legend")+ theme(legend.key.height=unit(1, "cm"), plot.margin = unit(c(0.5,0.5,0.5,0.5), "lines"))+ ggtitle(paste("Hourly", variable1, " vs. Hourly", variable2)) + theme(plot.title = element_text(hjust = 0.5)) } }
get_predictions_bayesx <- function(model, data_grid, ...) { prdat <- suppressMessages( stats::predict( object = model, newdata = data_grid, type = "link" )) data_grid$predicted <- as.vector(prdat) data_grid$conf.low <- NA data_grid$conf.high <- NA data_grid }
library("devtools") revdep_check_resume() revdep_check_save_summary() revdep_check_print_problems()
GetHpltStats <- function(filepath) { file_names <- dir(filepath) mean_props <- numeric() for(i in 1:length(file_names)) { mean_props[i] <- readRDS(file.path(filepath, file_names[i]))$Mean_prop_incongr_seqs } MoM_props <- mean(mean_props) MoM_props }
ctStanData <- function(ctm, datalong,optimize,derrind='all'){ nsubjects <- length(unique(datalong[, ctm$subjectIDname])) mats <- ctStanMatricesList() driftdiagonly <- ifelse(all(!is.na(ctm$pars$value[ctm$pars$matrix == 'DRIFT' & ctm$pars$row != ctm$pars$col]) & all(ctm$pars$value[ctm$pars$matrix == 'DRIFT' & ctm$pars$row != ctm$pars$col] == 0) ), 1, 0) if(any(!c(ctm$manifestNames,ctm$TDpredNames,ctm$TIpredNames) %in% colnames(datalong))) stop(paste0(' variables: ', paste0(c(ctm$manifestNames,ctm$TDpredNames,ctm$TIpredNames)[ which(!c(ctm$manifestNames,ctm$TDpredNames,ctm$TIpredNames) %in% colnames(datalong))], ', '),' not in data')) if(!(ctm$subjectIDname %in% colnames(datalong))) stop(paste('id column', (ctm$subjectIDname), "not found in data")) if(ctm$nopriors==FALSE){ if(ctm$n.TIpred > 1 && any(abs(colMeans(datalong[,c(ctm$TIpredNames),drop=FALSE],na.rm=TRUE)) > .3)){ message('Uncentered TI predictors noted -- interpretability may be hindered and default priors may not be appropriate') } } original <- unique(datalong[,ctm$subjectIDname]) datalong <- makeNumericIDs(datalong,ctm$subjectIDname,ctm$timeName) new <- unique(datalong[,ctm$subjectIDname]) idmap <- data.frame(original, new) if( (nrow(ctm$t0varstationary) + nrow(ctm$t0meansstationary)) >0 && length(c(ctm$modelmats$calcs$driftcint, ctm$modelmats$calcs$diffusion)) > 0) message('Stationarity assumptions based on initial states when using non-linear dynamics') if(ctm$intoverstates==FALSE || all(derrind=='all') ) derrind = 1:ctm$n.latent derrind = as.integer(derrind) if(any(derrind > ctm$n.latent)) stop('derrind > than n.latent found!') if(length(derrind) > ctm$n.latent) stop('derrind vector cannot be longer than n.latent!') if(length(unique(derrind)) < length(derrind)) stop('derrind vector cannot contain duplicates or!') ndiffusion=length(derrind) nindvarying <- max(ctm$modelmats$matsetup$indvarying) nparams <- max(ctm$modelmats$matsetup$param[ctm$modelmats$matsetup$when %in% c(0,-1)]) nmatrices <- length(mats$base) ctm$modelmats$matsetup[which(ctm$modelmats$matsetup$indvarying > 0),] indvaryingindex <- ctm$modelmats$matsetup$param[which(ctm$modelmats$matsetup$indvarying > 0)] indvaryingindex <- array(indvaryingindex[!duplicated(indvaryingindex)]) sdscale <- array(ctm$modelmats$matvalues$sdscale[match(indvaryingindex,ctm$modelmats$matsetup$param)]) if(ctm$n.TIpred > 0) { tipreds <- datalong[match(unique(datalong[,ctm$subjectIDname]),datalong[,ctm$subjectIDname]),ctm$TIpredNames,drop=FALSE] if(any(is.na(tipreds))) { if(!optimize){ message(paste0("NA's in TIpreds - sampling ", sum(is.na(tipreds)),' values')) tipreds[is.na(tipreds)] = 99999 } if(optimize){ message(paste0("NA's in TIpreds - imputing ", sum(is.na(tipreds)),' NA\'s to allow optimization -- TIpred effect estimates may be overly confident.')) timu <- apply(tipreds,2,mean,na.rm=TRUE) tisd <- apply(tipreds,2,sd,na.rm=TRUE) meandat <- data.table((datalong))[ , lapply(.SD, function(x) sum(x,na.rm=TRUE)/sum(!is.na(x))) , by=c(ctm$subjectIDname)] meandat <- data.frame(scale(meandat[,apply(meandat,2,sd,na.rm=TRUE) > 1e-4,with=FALSE])) meandat[is.na(meandat)] <- 0 for(i in 1:ctm$n.TIpred){ lmform = formula(paste0(ctm$TIpredNames[i],' ~ 1 + ', paste0(colnames(meandat)[-which(colnames(meandat) %in% ctm$TIpredNames[i])], collapse=' + '))) lmf <- lm(formula = lmform,data = meandat,na.action=na.exclude) tipreds[is.na(tipreds[,i]),i] <- predict(lmf)[is.na(tipreds[,i])] * tisd[i] + timu[i] } } } } datalong[,ctm$manifestNames][is.na(datalong[,ctm$manifestNames])]<-99999 standata <- list( Y=cbind(as.matrix(datalong[,ctm$manifestNames])), subject=as.integer(datalong[,ctm$subjectIDname]), time=datalong[,ctm$timeName], ndatapoints=as.integer(nrow(datalong)), nobs_y=array(as.integer(apply(datalong[,ctm$manifestNames,drop=FALSE],1,function(x) length(x[x!=99999]))),dim=nrow(datalong)), whichobs_y=matrix(as.integer(t(apply(datalong[,ctm$manifestNames,drop=FALSE],1,function(x) { out<-as.numeric(which(x!=99999)) if(length(out)==0) out<-rep(0,ctm$n.manifest) if(length(out)<ctm$n.manifest) out<-c(out,rep(0,ctm$n.manifest-length(out))) out }) )),nrow=c(nrow(datalong),ncol=ctm$n.manifest)), nbinary_y=array(as.integer(apply(datalong[,ctm$manifestNames,drop=FALSE],1,function(x) length(x[ctm$manifesttype==1 & x!=99999]))),dim=nrow(datalong)), whichbinary_y=matrix(as.integer(t(apply(datalong[,ctm$manifestNames,drop=FALSE],1,function(x) { out<-as.numeric(which(ctm$manifesttype==1 & x!=99999)) if(length(out)==0) out<-rep(0,ctm$n.manifest) if(length(out)<ctm$n.manifest) out<-c(out,rep(0,ctm$n.manifest-length(out))) out }) )),nrow=c(nrow(datalong),ncol=ctm$n.manifest)), ncont_y=array(as.integer(apply(datalong[,ctm$manifestNames,drop=FALSE],1,function(x) length(x[(ctm$manifesttype==0 | ctm$manifesttype==2) & x!=99999]))),dim=nrow(datalong)), whichcont_y=matrix(as.integer(t(apply(datalong[,ctm$manifestNames,drop=FALSE],1,function(x) { out<-as.numeric(which( (ctm$manifesttype==0 | ctm$manifesttype==2) & x!=99999)) if(length(out)==0) out<-rep(0,ctm$n.manifest) if(length(out)<ctm$n.manifest) out<-c(out,rep(0,ctm$n.manifest-length(out))) out }) )),nrow=c(nrow(datalong),ncol=ctm$n.manifest)) ) if(ctm$n.TDpred > 0) { tdpreds <- datalong[,ctm$TDpredNames,drop=FALSE] if(any(is.na(tdpreds))) { message("NA's in TDpreds! Replaced by zeroes, consider appropriateness...") tdpreds[is.na(tdpreds)] <-0 } } if(ctm$n.TDpred ==0) tdpreds <- matrix(0,standata$ndatapoints,0) standata$tdpreds=array(as.matrix(tdpreds),dim=c(nrow(tdpreds),ncol(tdpreds))) if(is.null(ctm$dokalmanrows)) standata$dokalmanrows <- rep(1L, standata$ndatapoints) else standata$dokalmanrows <- as.integer(ctm$dokalmanrows) standata$priormod = 1L standata<-c(standata, list( nsubjects=as.integer(nsubjects), nmanifest=as.integer(ctm$n.manifest), nlatentpop = ctm$nlatentpop, Jstep = ctm$nlcontrol$Jstep, maxtimestep = ctm$nlcontrol$maxtimestep, dokalman=as.integer(is.null(ctm$dokalman)), intoverstates=as.integer(ctm$intoverstates), verbose=0L, manifesttype=array(as.integer(ctm$manifesttype),dim=length(ctm$manifesttype)), indvaryingindex=array(as.integer(indvaryingindex)), intoverpopindvaryingindex=array(as.integer(ctm$intoverpopindvaryingindex)), notindvaryingindex=array(as.integer(which(!(1:nparams) %in% indvaryingindex))), continuoustime=as.integer(sum(ctm$continuoustime)), nlatent=as.integer(ctm$n.latent), ntipred=as.integer(ctm$n.TIpred), ntdpred=as.integer(ctm$n.TDpred), nparams=as.integer(nparams), gendata=0L, nindvarying=as.integer(nindvarying), nindvaryingoffdiagonals=as.integer((nindvarying^2-nindvarying)/2), nt0varstationary=as.integer(nrow(ctm$t0varstationary)), nt0meansstationary=as.integer(nrow(ctm$t0meansstationary)), t0varstationary=matrix(as.integer(ctm$t0varstationary),ncol=2), t0meansstationary=matrix(as.integer(ctm$t0meansstationary),ncol=2), derrind=array(as.integer(derrind),dim=ndiffusion), ndiffusion=as.integer(ndiffusion), driftdiagonly = as.integer(driftdiagonly), intoverpop=as.integer(ctm$intoverpop), nopriors=as.integer(ctm$nopriors), savescores=0L, savesubjectmatrices=0L, nJAxfinite = ifelse(ctm$recompile,0L,length(ctm$JAxfinite)), nJyfinite = ifelse(ctm$recompile,0L,length(ctm$Jyfinite)) )) if(ctm$n.TIpred == 0) tipreds <- array(0,c(0,0)) standata$tipredsdata <- as.matrix(tipreds) standata$nmissingtipreds <- as.integer(length(tipreds[tipreds== 99999])) standata$ntipredeffects <- as.integer(ifelse(ctm$n.TIpred > 0, as.integer(max(ctm$modelmats$TIPREDEFFECTsetup)), 0)) standata$TIPREDEFFECTsetup <- apply(ctm$modelmats$TIPREDEFFECTsetup,c(1,2),as.integer,.drop=FALSE) standata$tipredsimputedscale <- ctm$tipredsimputedscale standata$tipredeffectscale <- ctm$tipredeffectscale standata$JAxfinite <- ctm$JAxfinite standata$Jyfinite <- ctm$Jyfinite standata$Jycolindexsize <- 1L standata$Jycolindex <- array(1L) standata$difftype <- 0L; standata$dotipred <- 1L; if(!ctm$timeName %in% colnames(datalong) && !ctm$continuoustime) { datalong[[ctm$timeName]] <- 1:nrow(datalong) } if (!(ctm$timeName %in% colnames(datalong))) stop(paste('time column', (ctm$timeName), "not found in data")) if(any(is.na(datalong[,ctm$timeName]))) stop('Missings in time column!') oldsubi<-datalong[1,ctm$subjectIDname]-1 dT<-rep(-1,length(datalong[,ctm$timeName])) for(rowi in 1:length(datalong[,ctm$timeName])) { subi<-datalong[rowi,ctm$subjectIDname] if(subi - oldsubi == 1) { dT[rowi]<-0 subistartrow<-rowi } if(subi - oldsubi == 0) { dT[rowi]<-datalong[rowi,ctm$timeName] - datalong[rowi-1,ctm$timeName] if(dT[rowi] < 0) stop(paste0('A time interval of ', dT[rowi],' was found at row ',rowi)) if(dT[rowi] == 0) warning(paste0('A time interval of ', dT[rowi],' was found at row ',rowi)) } oldsubi<-subi } subindices <- lapply(mats$base,function(x) 0) for(mati in mats$base){ if( (!ctm$intoverpop && any(ctm$pars$indvarying[ctm$pars$matrix %in% names(mats$base)[mati]])) || (ctm$n.TIpred >0 && ( any(unlist(ctm$pars[ctm$pars$matrix %in% names(mats$base)[mati],paste0(ctm$TIpredNames,'_effect')])) || any(ctm$pars$matrix %in% names(mats$base)[mati] & grepl('[',ctm$pars$param,fixed=TRUE)) ) )) subindex <- 1 else subindex <- 0 subindices[[names(mats$base)[mati]]] <- subindex } if(ctm$stationary || nrow(ctm$t0varstationary) > 0) subindices$T0VAR <- max(c(subindices$T0VAR,subindices$DRIFT,subindices$DIFFUSION)) if(ctm$stationary || nrow(ctm$t0meansstationary) > 0) subindices$T0MEANS <- max(c(subindices$T0MEANS,subindices$DRIFT,subindices$CINT)) standata$subindices <- as.integer(unlist(subindices))[order(mats$base)] statedep <- rep(0L,as.integer(max(mats$all))) lhscalcs <- sapply(unique(unlist(ctm$modelmats$calcs)),function(x) gsub('=.*','',x)) for(i in 1:length(statedep)){ matname <- try(names(mats$all[mats$all %in% i]),silent=TRUE) if(length(matname)==0) next statedep[i] <- ifelse(any( ctm$modelmats$matsetup$when >0 & ctm$modelmats$matsetup$matrix %in% i),1L,0L) if(any(sapply(lhscalcs,function(calci) grepl(matname,calci)))) statedep[i] <- 1L } standata$statedep <- statedep standata$choleskymats<- 0L if(!is.null(ctm$covmattransform)){ if(ctm$covmattransform=='rawcorr_indep') standata$choleskymats<- -1L if(ctm$covmattransform=='cholesky') standata$choleskymats<- 1L if(!ctm$covmattransform %in% c('rawcorr','rawcorr_indep','cholesky')) stop( 'covtransform must be either "rawcorr", "rawcorr_indep", or "cholesky"') } standata$matsetup <- apply(ctm$modelmats$matsetup[,-1],c(1,2),as.integer,.drop=FALSE) standata$matvalues <- apply(ctm$modelmats$matvalues,c(1,2),as.numeric) standata$nmatrices <- as.integer(nmatrices) standata$matrixdims <- ctm$modelmats$matrixdims standata$nrowmatsetup <- as.integer(nrow(ctm$modelmats$matsetup)) standata$sdscale <- array(as.numeric(sdscale),dim=length(sdscale)) standata$approxct <- 0L if(!is.null(ctm$approxct)) standata$approxct <- as.integer(ctm$approxct) standata$taylorheun <- 0L if(!is.null(ctm$taylorheun)) standata$taylorheun <- as.integer(ctm$taylorheun) standata$idmap <- idmap standata$popcovn=1000L standata$llsinglerow=0L if(any(ctm$manifesttype==1)){ standata$nJyfinite <- as.integer(ctm$n.latent) standata$Jyfinite <- array(as.integer(1:ctm$n.latent)) } if(!is.null(ctm$TIpredAuto) && ctm$TIpredAuto %in% c(1L,TRUE)) standata$TIpredAuto <- 1L else standata$TIpredAuto <- 0L mc=c(ctStanMatricesList()$all) ms=data.frame(standata$matsetup) ms=ms[order(ms$param),] standata$whenmat <- array(0L,dim=c(max(mc),5)) for(mi in mc){ mrows=which(ms$matrix==mi) for(wheni in 1:4){ standata$whenmat[mi,wheni] = as.integer(any( ms$when[mrows] %in% c(wheni,100))) } standata$whenmat[mi,5] = as.integer(any( ms$param[mrows] > 0 & ms$when[mrows] %in% c(0,100) & (ms$indvarying[mrows] > 1 | ms$tipred[mrows] > 0) )) } rownames(standata$whenmat)[mc] <- names(mc) standata$whenvecp <- array(0L, c(2,standata$nparams)) standata$whenvecp[1,] <- as.integer(1:standata$nparams) standata$whenvecp[2,ms$param[ms$when %in% c(0,100) & ms$copyrow <1 & (ms$tipred > 0 | ms$indvarying > 0) & ms$param > 0]] <- as.integer(ms$param[ms$when %in% c(0,100) & ms$copyrow <1 & (ms$tipred > 0 | ms$indvarying > 0) & ms$param > 0]) standata$whenvecs <- array(0L,dim=c(6,standata$nlatentpop)) for(wheni in 1:4){ standata$whenvecs[wheni,ms$param[ms$when %in% c(wheni,100) & ms$copyrow <=0 & ms$param > 0]] <- as.integer(ms$param[ms$when %in% c(wheni,100) & ms$copyrow <=0 & ms$param > 0]) } standata$whenmat[mc[names(mc) == 'asymDIFFUSIONcov'],] <- apply(standata$whenmat[ mc[names(mc) %in% c('DIFFUSION','DRIFT')],],2,max) standata$whenmat[mc[names(mc) == 'asymCINT'],] <- apply(standata$whenmat[mc[names(mc) %in% c('CINT','DRIFT')],],2,max) standata$whenmat[mc[names(mc) == 'DIFFUSIONcov'],] <- standata$whenmat[mc[names(mc) == 'DIFFUSION'],] standata$whenmat[mc[names(mc) == 'T0cov'],] <- standata$whenmat[mc[names(mc) == 'T0VAR'],] standata$whenmat[mc[names(mc) == 'MANIFESTcov'],] <- standata$whenmat[mc[names(mc) == 'MANIFESTVAR'],] standata$statedep[31:33] <- standata$statedep[c(4,5,8)] standata$laplaceprior <- rep(0L,standata$nparams) standata$laplacetipreds <- 0L if(!is.null(ctm$laplaceprior)){ if('tipreds' %in% ctm$laplaceprior) standata$laplacetipreds <- 1L ms <- data.frame(standata$matsetup) standata$laplaceprior[ ms$param[ ms$matrix %in% ctStanMatricesList()$all[names(ctStanMatricesList()$all) %in% ctm$laplaceprior] & ms$param > 0 & ms$row!=ms$col & ms$when==0 & ms$copyrow<1] ] <- 1L } standata$laplaceprioronly <- ifelse(is.null(ctm$laplaceprioronly),0L,as.integer(ctm$laplaceprioronly)) ms <- data.frame(standata$matsetup) CINTnonzero <- c() for(i in 1:standata$nlatent){ ri=which(ms$matrix %in% ctStanMatricesList()$all[names(ctStanMatricesList()$all) %in% 'CINT'] & ms$row %in% i) if(ms$param[ri]==0 && standata$matvalues[ri,'value']==0) next else CINTnonzero <- c(CINTnonzero,i) } standata$CINTnonzero <- array(as.integer(CINTnonzero)) standata$CINTnonzerosize <- length(CINTnonzero) standata$JAxDRIFTequiv <- 1L ml <- listOfMatrices(ctm$pars) for(i in 1:nrow(ml$JAx)){ for(j in 1:ncol(ml$JAx)){ if(i <= nrow(ml$DRIFT) && j <= nrow(ml$DRIFT)){ if(ml$JAx[i,j] != ml$DRIFT[i,j]) standata$JAxDRIFTequiv <- 0L } if(i > nrow(ml$DRIFT) || j > nrow(ml$DRIFT)){ if(i != j && !ml$JAx[i,j] %in% 0) standata$JAxDRIFTequiv <- 0L if(i == j && !ml$JAx[i,j] %in% ifelse(ctm$continuoustime,0,1)) standata$JAxDRIFTequiv <- 0L } } } standata$recompile <- as.integer(ctm$recompile) standata$nsubsets <- 1L return(standata) }
marginalized.risk=function(fit.risk, marker.name, data, categorical.s, weights=rep(1, nrow(data)), t=NULL, ss=NULL, verbose=FALSE) { if(categorical.s) { marginalized.risk.cat (fit.risk, marker.name, data, weights=weights, t=t, verbose=verbose) } else { marginalized.risk.cont (fit.risk, marker.name, data, weights=weights, t=t, ss=ss, verbose=verbose) } } marginalized.risk.cat=function(fit.risk, marker.name, data, weights=rep(1, nrow(data)), t=NULL, verbose=FALSE) { if("coxph" %in% class(fit.risk)) { time.var=as.character(fit.risk$terms[[2]][[2]]) y.var=as.character(fit.risk$terms[[2]][[3]]) } ss=unique(data[[marker.name]]); ss=sort(ss[!is.na(ss)]) if (!"coxph" %in% class(fit.risk)) { dat.tmp.mrc=data risks=sapply(ss, function(s) { dat.tmp.mrc[[marker.name]]=s risks = predict(fit.risk, newdata=dat.tmp.mrc, type="response") sum(weights * risks) / sum(weights) }) names(risks)=levels(ss) risks } else { if (is.null(t)) { tt=sort(unique(data[[time.var]][data[[y.var]]==1])) risks=sapply(tt, function (t) { dat.tmp.mrc=data dat.tmp.mrc[[time.var]]=t risks=sapply(ss, function(s) { dat.tmp.mrc[[marker.name]]=s risks = 1 - exp(-predict(fit.risk, newdata=dat.tmp.mrc, type="expected")) sum(weights * risks) / sum(weights) }) }) risks=t(risks) colnames(risks)=as.character(ss) list(time=tt, risk=risks) } else { if (verbose) print("return risk at time t") dat.tmp.mrc=data time.var=fit.risk$terms[[2]][[2]] dat.tmp.mrc[[time.var]]=t risks=sapply(ss, function(s) { dat.tmp.mrc[[marker.name]]=s risks = 1 - exp(-predict(fit.risk, newdata=dat.tmp.mrc, type="expected")) sum(weights * risks) / sum(weights) }) names(risks)=levels(ss) risks } } } marginalized.risk.cont=function(fit.risk, marker.name, data, weights=rep(1, nrow(data)), t=NULL, ss=NULL, verbose=FALSE) { ss.is.null=is.null(ss) if (ss.is.null) ss=quantile(data[[marker.name]], seq(.05,.95,by=0.01)) dat.tmp.mri=data if (!is.null(t)) { time.var=fit.risk$terms[[2]][[2]] dat.tmp.mri[[time.var]]=t } risks=sapply(ss, function(s) { dat.tmp.mri[[marker.name]]=s risks = if(is.null(t)) { predict(fit.risk, newdata=dat.tmp.mri, type="response") } else { 1 - exp(-predict(fit.risk, newdata=dat.tmp.mri, type="expected")) } sum(weights * risks) / sum(weights) }) if (ss.is.null) cbind(marker=ss, prob=risks) else risks }
print_windows <- function(x, file_path, blank_after, hide_notes, ...) { tryCatch( { f <- file(file_path, open = "a", encoding = "native.enc") if (all(class(x) == "character")) { if (length(x) == 1 && nchar(x) < 100) { writeLines(enc2utf8(x), con = f, useBytes = TRUE) } else { withr::with_options(c("crayon.colors" = 1), { strgs <- get_unicode_strings(x, ...) writeLines(strgs, con = f, useBytes = TRUE) }) } } else { withr::with_options(c("crayon.colors" = 1), { strgs <- get_unicode_strings(x, ...) writeLines(strgs, con = f, useBytes = TRUE) }) } if (blank_after == TRUE) writeLines("", con = f, useBytes = TRUE) }, error = function(cond) { print("Error: Object cannot be printed to log\n") }, finally = { if (hide_notes == FALSE) { tc <- Sys.time() if (e$log_show_notes == TRUE) { if (any(class(x) == "data.frame")) { writeLines(paste("NOTE: Data frame has", nrow(x), "rows and", ncol(x), "columns."), con = f, useBytes = TRUE) writeLines("", con = f, useBytes = TRUE) } writeLines(paste("NOTE: Log Print Time: ", tc), con = f, useBytes = TRUE) writeLines(paste("NOTE: Elapsed Time in seconds:", get_time_diff(tc)), con = f, useBytes = TRUE) writeLines("", con = f, useBytes = TRUE) } } close(f) } ) } print_other <- function(x, file_path, blank_after, hide_notes, ...) { tryCatch( { f <- file(file_path, open = "a", encoding = "UTF-8") sink(f, append = TRUE) if (all(class(x) == "character")) { if (length(x) == 1 && nchar(x) < 100) { cat(x, "\n") } else { withr::with_options(c("crayon.colors" = 1), { print(x, ..., ) }) } } else { withr::with_options(c("crayon.colors" = 1), { print(x, ...) }) } if (blank_after == TRUE) cat("\n") }, error = function(cond) { print("Error: Object cannot be printed to log\n") }, finally = { if (hide_notes == FALSE) { tc <- Sys.time() if (e$log_show_notes == TRUE) { if (any(class(x) == "data.frame")) { cat(paste("NOTE: Data frame has", nrow(x), "rows and", ncol(x), "columns."), "\n") cat("\n") } cat(paste("NOTE: Log Print Time: ", tc), "\n") cat(paste("NOTE: Elapsed Time in seconds:", get_time_diff(tc)), "\n") cat("\n") } } sink() close(f) } ) } get_unicode_strings <- function(obj, ...) { if (!all(class(obj) == "character")) { strgs <- utils::capture.output(print(obj, ...), file = NULL) ret <- get_unicode(strgs) } else { ret <- obj } return(ret) } get_unicode <- Vectorize(function(string){ ret <- string m <- gregexpr("<U\\+[0-9A-F]{4}>", string) if(m[[1]][1] != -1) { codes <- unlist(regmatches(string, m)) replacements <- codes N <- length(codes) for(i in 1:N){ replacements[i] <- intToUtf8(strtoi(paste0("0x", substring(codes[i], 4, 7)))) } if(1 != m[[1]][1]){ y <- substring(string, 1, m[[1]][1]-1) y <- paste0(y, replacements[1]) }else{ y <- replacements[1] } if(1 < N){ for(i in 2:N){ s <- gsub("<U\\+[0-9A-F]{4}>", replacements[i], substring(string, m[[1]][i-1]+8, m[[1]][i]+7)) Encoding(s) <- "UTF-8" y <- paste0(y, s) } } if( nchar(string)>(m[[1]][N]+8) ) ret <- paste0( y, substring(string, m[[1]][N]+8, nchar(string)) ) else ret <- y } return(ret) }, USE.NAMES = FALSE)
expect_equal(1+1,2) Sys.setenv("foo"="bar") expect_equal("a","b") report_side_effects(FALSE) Sys.setenv("foo"="baz") expect_equal(TRUE, TRUE)
context("Setting up custom test harness") test_that("Harness works", { expect_error(normal_print("x")) }) testthat_dir <- setwd(file.path("..","test_import")) test_files <- list.files(".","^test") for ( test_file in test_files ) { context(test_file) test_that(paste(test_file," works"), { if ( isTRUE(as.logical(Sys.getenv("CI"))) & tolower(Sys.info()[["sysname"]]) == "windows" ) { skip("Skipping on CI Windows Action") } rscript_file <- ifelse(Sys.info()['sysname']=="Windows","Rscript.exe","Rscript") rscript_path <- paste0("\"",file.path(R.home(),"bin",rscript_file),"\"") test_output <- system(paste(rscript_path, test_file), intern=TRUE) expect_match( test_output, "Import tests completed successfully ...", all=FALSE, label=paste(test_output,collapse="\n") ) }) } context("List any skipped tests") setwd(testthat_dir)
l_cget.l_tour <- function(target, state) { widget <- l_getPlots(target) target <- unclass(target) if(is.list(target) && "projection" %in% state) { return(target[["projection"]]) } loon::l_cget(widget, state) } l_cget.l_tour_compound <- function(target, state) { widget <- l_getPlots(target) names <- names(target) target <- unclass(target) if(is.list(target) && (state %in% names)) { if(state == "projection") return(target[[state]]) else return(widget[[state]]) } lapply(widget, function(w) { loon::l_cget(w, state) }) } l_configure.l_tour <- function(target, ...) { widget <- l_getPlots(target) target <- unclass(target) args <- list(...) name <- names(args) if(is.list(target)) { if("projection" %in% name) { target[["projection"]] <- args[["projection"]] args[["projection"]] <- NULL } if(length(args) == 0) return(invisible( structure( target, class = c("l_tour", "loon") ) )) widget_name <- setdiff(names(target), "projection") do.call(loon::l_configure, c(list(target = widget), args)) target[[widget_name]] <- widget return(invisible( structure( target, class = c("l_tour", "loon") ) )) } else { if("projection" %in% name) { args[["projection"]] <- NULL } if(length(args) == 0) return(invisible(target)) do.call(l_configure, c(list(target = widget), args)) return(invisible(target)) } } l_configure.l_tour_compound <- function(target, ...) { widget <- l_getPlots(target) target <- unclass(target) args <- list(...) name <- names(args) if(is.list(target)) { if("projection" %in% name) { target[["projection"]] <- args[["projection"]] args[["projection"]] <- NULL } if(length(args) == 0) return( invisible( structure( target, class = c("l_tour_compound", "loon") ) )) lapply(widget, function(w) { do.call(loon::l_configure, c(list(target = w), args)) }) target[[setdiff(names(target), "projection")]] <- widget return(invisible( structure( target, class = c("l_tour_compound", "loon") ) )) } else { if("projection" %in% name) { args[["projection"]] <- NULL } if(length(args) == 0) return(invisible(target)) do.call(l_configure, c(list(target = widget), args)) return(invisible(target)) } } names.l_tour <- function(x) { plot_name <- setdiff(names(unclass(x)), "projection") plot <- x[[plot_name]] c(names(plot), "projection") } names.l_tour_compound <- function(x) { plot_name <- setdiff(names(unclass(x)), "projection") plot <- x[[plot_name]] c(names(plot), "projection") } `names<-.l_tour` <- function(x, value) { stop("`l_tour` object is not allowed to set names") } `names<-.l_tour_compound` <- function(x, value) { stop("`l_tour_compound` object is not allowed to set names") } print.l_tour <- function(x, ...) { plot_name <- setdiff(names(unclass(x)), "projection") plot <- x[[plot_name]] print.default( structure( as.character(plot), class = class(x) ) ) } print.l_tour_compound <- function(x, ...) { plot_name <- setdiff(names(unclass(x)), "projection") print.default( structure( as.character(plot_name), class = class(x) ) ) } loonGrob.l_tour <- function(target, name = NULL, gp = NULL, vp = NULL) { plot_name <- setdiff(names(unclass(target)), "projection") plot <- target[[plot_name]] loonGrob(plot, name = name, gp = gp, vp = vp) } loonGrob.l_tour_compound <- function(target, name = NULL, gp = NULL, vp = NULL) { plot_name <- setdiff(names(unclass(target)), "projection") plot <- target[[plot_name]] loonGrob(plot, name = name, gp = gp, vp = vp) }
l_Rlist2nestedTclList <- function(x) { paste( vapply(x, function(x_el) { paste0('{',paste(x_el, collapse = ' '),'}') }, character(1)), collapse = ' ' ) } l_nestedTclList2Rlist <- function(tclobj, transform=function(x) {as.numeric(x)}) { n <- as.numeric(tcl('llength', tclobj)) x <- vector(mode = 'list', length = n) for (i in 1:n) { x[[i]] <- transform(tcl('lindex', tclobj, i-1)) } return(x) }
NULL plateau.quadratic=function(trat,resp, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, pointshape = 21, round=NA, yname.formula="y", xname.formula="x", comment=NA, fontfamily="sans"){ requireNamespace("minpack.lm") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("dplyr") requireNamespace("rcompanion") mod=nls(resp~plquadratic(trat,a,breakpoint,b,c)) model2=summary(mod) m.ini <- mean(resp) nullfunct <- function(x, m) { m} data=data.frame(trat,resp) null <- nls(resp~ nullfunct(trat, m), start = list(m = m.ini), trace = FALSE, data = data, nls.control(maxiter = 1000)) r2 <- nagelkerke(mod, null)$Pseudo.R.squared.for.model.vs.null[2] requireNamespace("drc") requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) r2=floor(r2*100)/100 if(is.na(round)==TRUE){ a=coef(mod)[1] breakpoint=coef(mod)[2] b=coef(mod)[3] c=coef(mod)[4]} if(is.na(round)==FALSE){ a=round(coef(mod)[1],round) breakpoint=round(coef(mod)[2],round) b=round(coef(mod)[3],round) c=round(coef(mod)[4],round)} s <- sprintf("~~~%s == %e %s %e * %s %s %e * %s^2~(%s>%e) ~~~~~ italic(R^2) == %0.2f", yname.formula, a, ifelse(b >= 0, "+", "-"), abs(b), xname.formula, ifelse(c >= 0, "+", "-"), abs(c), xname.formula, xname.formula, breakpoint, r2) equation=s if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} predesp=predict(mod) predobs=resp model=mod rmse=sqrt(mean((predesp-predobs)^2)) data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill="gray")} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill="gray")} xp=seq(min(trat),max(trat),length=1000) yp=predict(mod,newdata=data.frame(trat=xp)) preditos=data.frame(x=xp,y=yp) temp1=xp result=yp x=xp y=yp graph=graph+theme+ geom_line(data=preditos,aes(x=x, y=y, color="black"),size=linesize)+ scale_color_manual(name="",values="black",label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} aic=AIC(model) bic=BIC(model) minimo=NA respmin=NA ybreakpoint=predict(mod,newdata = data.frame(trat=breakpoint)) graphs=data.frame("Parameter"=c("Breakpoint", "Breakpoint response", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(breakpoint, ybreakpoint, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients quadratic model"=model2, "values"=graphs, graph) print(graficos) } pquadInit <- function(mCall, LHS, data, ...){ xy <- sortedXyData(mCall[["x"]], LHS, data) if(nrow(xy) < 4){ stop("Small sample size")} xy1 <- xy[1:floor(nrow(xy)/2),] xy2 <- xy[floor(nrow(xy)/2):nrow(xy),] xy2$x2 <- xy2[,"x"] - min(xy2[,"x"]) fit2 <- stats::lm(xy2[,"y"] ~ xy2[,"x2"] + I(xy2[,"x2"]^2)) a <- coef(fit2)[1] b <- coef(fit2)[2] c <- coef(fit2)[3] objfun <- function(cfs){ pred <- pquad(xy[,"x"], a=cfs[1], breakpoint=cfs[2], b=cfs[3], c=cfs[4]) ans <- sum((xy[,"y"] - pred)^2) ans} op <- try(stats::optim(c(a, mean(xy[,"x"]),b,c), objfun, method = "L-BFGS-B", upper = c(Inf, max(xy[,"x"]), Inf, Inf), lower = c(-Inf, min(xy[,"x"]), -Inf, -Inf)), silent = TRUE) if(class(op) != "try-error"){ a <- op$par[1] breakpoint <- op$par[2] b <- op$par[3] c <- op$par[4]}else{ a <- mean(xy1[,"y"]) breakpoint <- mean(xy[,"x"]) b <- b c <- c} value <- c(a, breakpoint, b, c) names(value) <- mCall[c("a","breakpoint","b","c")] value} pquad <- function(x, a, breakpoint, b, c){ .value <- (x < breakpoint) * a + (x >= breakpoint) * (a + b * (x - breakpoint) + c * (x - breakpoint)^2) .exp1 <- 1 .exp2 <- ifelse(x < breakpoint, 0, -b + -(c * (2 * (x - breakpoint)))) .exp3 <- ifelse(x < breakpoint, 0, x - breakpoint) .exp4 <- ifelse(x < breakpoint, 0, (x - breakpoint)^2) .actualArgs <- as.list(match.call()[c("a","breakpoint","b","c")]) if (all(unlist(lapply(.actualArgs, is.name)))) { .grad <- array(0, c(length(.value), 4L), list(NULL, c("a","breakpoint","b","c"))) .grad[, "a"] <- .exp1 .grad[, "breakpoint"] <- .exp2 .grad[, "b"] <- .exp3 .grad[, "c"] <- .exp4 dimnames(.grad) <- list(NULL, .actualArgs) attr(.value, "gradient") <- .grad} .value} plquadratic <- selfStart(model = pquad, initial = pquadInit, parameters = c("a","breakpoint","b","c"))
.dt_locale_key <- "_locale" dt_locale_get <- function(data) { dt__get(data, .dt_locale_key) } dt_locale_set <- function(data, locale) { dt__set(data, .dt_locale_key, locale) } dt_locale_init <- function(data, locale = NULL) { list( locale = locale ) %>% dt_locale_set(data = data) } dt_locale_get_value <- function(data) { dt_locale_get(data = data)$locale }
plot.ceteris_paribus_2d_explainer <- function(x, ..., facet_ncol = NULL, add_raster = TRUE, add_contour = TRUE, bins = 3, add_observation = TRUE, pch = "+", size = 6) { all_responses <- x class(all_responses) <- "data.frame" midpoint <- mean(all_responses$y_hat, na.rm = TRUE) new_x1 <- y_hat <- new_x2 <- NULL pred <- attr(x, "prediction")$observation all_pairs <- unique(all_responses[,c("vname1","vname2")]) observations <- lapply(1:nrow(all_pairs), function(i) { pair <- all_pairs[i,] data.frame(vname1 = pair$vname1, vname2 = pair$vname2, new_x1 = pred[,as.character(pair$vname1)], new_x2 = pred[,as.character(pair$vname2)], y_hat = midpoint) }) observation <- do.call(rbind, observations) pl <- ggplot(all_responses, aes(new_x1, new_x2, fill = y_hat, z = y_hat)) + facet_wrap(vname1 ~ vname2, scales = "free", ncol = facet_ncol) + xlab("") + ylab("") + scale_fill_gradient2(name = 'Prediction', midpoint = midpoint, low = " if (add_raster) { pl <- pl + geom_raster(data = all_responses) } if (add_contour) { pl <- pl + geom_contour(data = all_responses, color = "white", alpha = 0.5, bins = bins) } if (add_observation) { pl <- pl + geom_point(data = observation, fill = "black", pch = pch, size = size) } pl + theme_drwhy_blank() } theme_drwhy_blank <- function() { theme_bw(base_line_size = 0) %+replace% theme(axis.ticks = element_blank(), legend.background = element_blank(), legend.key = element_blank(), panel.background = element_blank(), panel.border = element_blank(), strip.background = element_blank(), plot.background = element_blank(), complete = TRUE, legend.direction = "horizontal", legend.position = "top", plot.title = element_text(color = " plot.subtitle = element_text(color = " axis.line.x = element_line(color = "white"), axis.ticks.x = element_line(color = "white"), axis.title = element_text(color = " axis.text = element_text(color = " strip.text = element_text(color = " }
calibrate_carbon <- function(inname, outname, site, method = "Bowling_2003", calibration_half_width = 0.5, force_cal_to_beginning = TRUE, force_cal_to_end = TRUE, gap_fill_parameters = FALSE, filter_ambient = TRUE, r2_thres = 0.95, correct_refData = TRUE, write_to_file = TRUE) { ciso <- ingest_data(inname, analyte = 'Co2') refe <- extract_carbon_calibration_data(ciso$refe_stacked) if (correct_refData == TRUE) { refe <- correct_carbon_ref_cval(refe,site) } cal_df <- fit_carbon_regression(ref_data = refe, method = method, calibration_half_width = calibration_half_width) ciso_subset <- ciso$ambient if (method == "Bowling_2003") { ciso_subset_cal <- lapply(names(ciso_subset), function(x) { calibrate_ambient_carbon_Bowling2003( amb_data_list = ciso_subset[[x]], caldf = cal_df, site = site, filter_data = filter_ambient, force_to_end = force_cal_to_end, force_to_beginning = force_cal_to_beginning, r2_thres = r2_thres) }) } else if (method == "linreg") { ciso_subset_cal <- lapply(names(ciso_subset), function(x) { calibrate_ambient_carbon_linreg( amb_data_list = ciso_subset[[x]], caldf = cal_df, site = site, filter_data = filter_ambient, force_to_end = force_cal_to_end, force_to_beginning = force_cal_to_beginning, r2_thres = r2_thres) }) } names(ciso_subset_cal) <- names(ciso_subset) if (write_to_file) { cal_df$timeBgn <- convert_POSIXct_to_NEONhdf5_time(cal_df$timeBgn) cal_df$timeEnd <- convert_POSIXct_to_NEONhdf5_time(cal_df$timeEnd) setup_output_file(inname, outname, site, 'co2') write_carbon_calibration_data(outname, site, cal_df, method = method) write_carbon_ambient_data(outname, site, ciso_subset_cal) write_carbon_reference_data2(outname, site, ciso, cal_df) rhdf5::h5closeAll() } }
fitted.l1ce <- function(object, ...){ object$fitted } fitted.l1celist <- function(object, ...){ do.call("cbind", lapply(object, "[[", "fitted")) }
multivariatePredictGlm <- function(Xnew,family,beta,offset=NULL){ prediction <- Xnew%*%beta if(!is.null(offset)) { if(is.vector(offset)) { offset <- matrix(offset,nrow(Xnew), sum(family=="poisson")) } else { offset <- as.matrix(offset) } } if(sum(family=="bernoulli")>0){ tmp <- prediction[,which(family=="bernoulli")] prediction[,which(family=="bernoulli")] <- exp(tmp)/(1+exp(tmp)) } if(sum(family=="binomial")>0){ tmp <- prediction[,which(family=="binomial")] prediction[,which(family=="binomial")] <- exp(tmp)/(1+exp(tmp)) } if(sum("poisson"%in%family)>0){ if(is.null(offset)){ tmp <- prediction[,which(family=="poisson")] }else{ tmp <- log(offset)+prediction[,which(family=="poisson")] } prediction[,which(family=="poisson")] <- exp(tmp) } return(prediction) }
visuEq <- function (K, nVar=NULL, dMax=NULL, substit = 0, approx = FALSE, selecmod = NULL) { if (is.list(K)) { if (is.null(selecmod)) { stop('The model number should be provided using option: selecmod = ') } if (length(selecmod)!=1) { stop('selecmod should be an integer. Only a single model can be displayed') } K <- K$models[[selecmod]] } if (is.vector(K)) { K <- cano2M(nVar, dMax, K) } if (is.matrix(K)) { if (is.null(nVar)) nVar <- dim(K)[2] if (is.null(dMax)) dMax <- p2dMax(nVar = nVar, pMaxKnown = dim(K)[1]) } if (dim(K)[2] != nVar) { stop('nVar = ', nVar, ' is not compatible with the model dimension dim(K)[2] = ', dim(K)[2]) } if (d2pMax(nVar,dMax) != dim(K)[1]) { stop('dMax = ', dMax, ' is not compatible with the model size dim(K)[1] = ', dim(K)[1]) } if (approx == TRUE) { lePlusPetit <- min(abs(K)[abs(K) != 0]) digits <- abs(floor(log10(lePlusPetit))) K <- round(K, digits) } else if ((approx %% 1) == 0 & approx != FALSE) { lePlusPetit <- min(abs(K)[abs(K) != 0]) digits <- abs(floor(log10(lePlusPetit))) K <- round(K, digits + approx) } else if ((approx %% 1) != 0 & !is.logical(approx)) { stop("parameter 'approx' should be either a logical or an integer value") } N <- list() for (i in 1:nVar) { if (!is.numeric(substit[1])) { varsList = substit } else { if (substit == 0) { varsList = c("X1", "X2", "X3", "X4", "X5", "X6", "X7", "X8", "X9") } else if (substit == 1) { varsList = c("x", "y", "z", "w", "u", "v", "r", "s", "q") } else if (substit == 2) { varsList = c("X_1", "X_2", "X_3", "X_4", "X_5", "X_6", "X_7", "X_8", "X_9") } else { stop("substit must be either a list of nVar values or equal to 0 or 1 or 2") } } dN <- paste("d", varsList[i],"/dt =", sep="") M <- cbind(K[K[,i]!=0,i], poLabs(nVar, dMax, K[,i]!=0, Xnote=varsList[1:nVar]), "+") M <- matrix(t(M), nrow=1, ncol=length(M)) M <- M[,1:(dim(M)[2]-1)] M <- cbind(dN, t(M)) M <- paste(M,collapse=" ") for (i in 1:nVar) { M <- gsub(paste("1 ", varsList[i]), varsList[i], M, fixed=TRUE) } M <- gsub(" + -", " -", M, fixed=TRUE) M <- gsub("+ -", " -", M, fixed=TRUE) M <- gsub("+ -", " -", M, fixed=TRUE) M <- gsub(" +-", " -", M, fixed=TRUE) M <- gsub("ct", "", M) M <- gsub("Ct", "", M) if (substit[1] == 2) { M <- gsub("e-0", "e-", M) M <- gsub("e+0", "e+", M) M <- gsub("e", ".10^{", M) M <- gsub("+-", "-", M) M <- gsub("+ -", "-", M) } cat(M, "\n\n") N[i] <- M } invisible(N) }
obfuscatePed <- function(ped, size = 6, maxDelta = 30, existingIds = character(0), map = FALSE ) { alias <- obfuscateId(ped$id, size = size, existingIds = existingIds) ped$sire <- alias[ped$sire] ped$dam <- alias[ped$dam] ped$id <- alias for (col in names(ped)) { if (any("Date" %in% class(ped[[col]]))) { ped[[col]] <- obfuscateDate(ped[[col]], maxDelta = maxDelta) } } if (any("age" %in% names(ped)) & any("birth" %in% names(ped)) & any("exit" %in% names(ped))) { if (all(is.Date(ped$birth))) ped["age"] <- calcAge(ped$birth, ped$exit) } if (map) { list(ped = ped, map = alias) } else { ped } }
caterpillar.plot <- function(x, Parms=NULL, Title=NULL) { if(missing(x)) stop("The x argument is required.") par(mfrow=c(1,1)) if(identical(class(x), "demonoid")) { if(any(is.na(x$Summary2))) { x <- x$Summary1 x.lab <- "All Samples"} else { x <- x$Summary2 x.lab <- "Stationary Samples"} if(!is.null(Parms)) { if(is.character(Parms)) { Parms <- sub("\\[","\\\\[",Parms) Parms <- sub("\\]","\\\\]",Parms) Parms <- sub("\\.","\\\\.",Parms) if(length(grep(Parms[1], rownames(x))) == 0) stop("Parameter in Parms does not exist.") keeprows <- grep(Parms[1], rownames(x)) if(length(Parms) > 1) { for (i in 2:length(Parms)) { if(length(grep(Parms[i], rownames(x))) == 0) stop("Parameter in Parms does not exist.") keeprows <- c(keeprows, grep(Parms[i], rownames(x)))} } } if(is.numeric(Parms)) keeprows <- Parms temp <- x x <- matrix(x[keeprows,], length(keeprows), ncol(temp)) rownames(x) <- rownames(temp)[keeprows] colnames(x) <- colnames(temp) } x.rows <- nrow(x) x.lim <- c(min(x[,5]), max(x[,7])) y.lim <- c(0, x.rows+1) plot(0, 0, ylim=y.lim, xlim=x.lim, main=Title, sub="", xlab=x.lab, ylab="", type="n", ann=TRUE, yaxt="n") abline(v=0, col="gray") points(x[,6], x.rows:1, pch=20) for (i in 1:x.rows) { lines(x[i,c(5,7)], c(x.rows-i+1, x.rows-i+1))} yy <- x.rows:1 cex.labels <- 1 / {log(x.rows)/5 + 1} axis(2, labels=rownames(x), tick=FALSE, las=1, at=yy, cex.axis=cex.labels) } else if(identical(class(x), "demonoid.hpc")) { Chains <- length(x) x.temp <- list() for (i in 1:Chains) {x.temp[[i]] <- x[[i]][["Summary1"]]} x <- x.temp; remove(x.temp) x.lab <- "All Samples" if(!is.null(Parms)) { if(is.character(Parms)) { Parms <- sub("\\[","\\\\[",Parms) Parms <- sub("\\]","\\\\]",Parms) Parms <- sub("\\.","\\\\.",Parms) if(length(grep(Parms[1], rownames(x[[1]]))) == 0) stop("Parameter in Parms does not exist.") keeprows <- grep(Parms[1], rownames(x[[1]])) if(length(Parms) > 1) { for (i in 2:length(Parms)) { if(length(grep(Parms[i], rownames(x[[1]]))) == 0) stop("Parameter in Parms does not exist.") keeprows <- c(keeprows, grep(Parms[i], rownames(x[[1]])))} } } if(is.numeric(Parms)) keeprows <- Parms temp <- x for (i in 1:Chains) { x[[i]] <- matrix(x[[i]][keeprows,], length(keeprows), ncol(temp[[1]]))} rownames(x[[1]]) <- rownames(temp[[1]])[keeprows] colnames(x[[1]]) <- colnames(temp[[1]]) } x.rows <- nrow(x[[1]]) x.lim <- c(min(x[[1]][,5]), max(x[[1]][,7])) y.lim <- c(0, x.rows+1) plot(0, 0, ylim=y.lim, xlim=x.lim, main=Title, sub="", xlab=x.lab, ylab="", type="n", ann=TRUE, yaxt="n") abline(v=0, col="gray") points(x[[1]][,6], x.rows:1, pch=20) for (i in 2:Chains) {points(x[[i]][,6], (x.rows:1)-(i/10), col=i, pch=20)} for (i in 1:x.rows) { lines(x[[1]][i,c(5,7)], c(x.rows-i+1, x.rows-i+1))} for (j in 2:Chains) {for (i in 1:x.rows) { lines(x[[j]][i,c(5,7)], c(x.rows-i+1-(j/10), x.rows-i+1-(j/10)), col=j)}} yy <- x.rows:1 cex.labels <- 1 / {log(x.rows)/5 + 1} axis(2, labels=rownames(x[[1]]), tick=FALSE, las=1, at=yy, cex.axis=cex.labels) } else if(identical(class(x), "iterquad")) { if(any(is.na(x$Posterior))) { x <- x$Summary1 x.lab <- "Point-Estimates"} else { x <- x$Summary2[1:length(x$Initial.Values),] x.lab <- "SIR Samples"} if(is.null(Parms)) { keeprows <- Parms <- 1:length(x$Initial.Values)} else { if(is.numeric(Parms)) keeprows <- Parms if(is.character(Parms)) { Parms <- sub("\\[","\\\\[",Parms) Parms <- sub("\\]","\\\\]",Parms) Parms <- sub("\\.","\\\\.",Parms) if(length(grep(Parms[1], rownames(x))) == 0) stop("Parameter in Parms does not exist.") keeprows <- grep(Parms[1], rownames(x)) if(length(Parms) > 1) { for (i in 2:length(Parms)) { if(length(grep(Parms[i], rownames(x))) == 0) stop("Parameter in Parms does not exist.") keeprows <- c(keeprows, grep(Parms[i], rownames(x)))} } } } temp <- x x <- matrix(x[keeprows,], length(keeprows), ncol(temp)) rownames(x) <- rownames(temp)[keeprows] colnames(x) <- colnames(temp) if(x.lab != "SIR Samples") Modes <- x[,1] else Modes <- x[,6] if(x.lab != "SIR Samples") LB <- x[,3] else LB <- x[,5] if(x.lab != "SIR Samples") UB <- x[,4] else UB <- x[,7] x.rows <- length(Modes) x.lim <- c(min(LB), max(UB)) y.lim <- c(0, x.rows+1) plot(0, 0, ylim=y.lim, xlim=x.lim, main=Title, sub="", xlab=x.lab, ylab="", type="n", ann=TRUE, yaxt="n") abline(v=0, col="gray") points(Modes, x.rows:1, pch=20) for (i in 1:x.rows) { lines(c(LB[i], UB[i]), c(x.rows-i+1, x.rows-i+1))} yy <- x.rows:1 cex.labels <- 1/{log(x.rows)/5 + 1} axis(2, labels=rownames(x), tick=FALSE, las=1, at=yy, cex.axis=cex.labels) } else if(identical(class(x), "laplace")) { if(any(is.na(x$Posterior))) { x <- x$Summary1 x.lab <- "Point-Estimates"} else { x <- x$Summary2[1:length(x$Initial.Values),] x.lab <- "SIR Samples"} if(is.null(Parms)) { keeprows <- Parms <- 1:length(x$Initial.Values)} else { if(is.numeric(Parms)) keeprows <- Parms if(is.character(Parms)) { Parms <- sub("\\[","\\\\[",Parms) Parms <- sub("\\]","\\\\]",Parms) Parms <- sub("\\.","\\\\.",Parms) if(length(grep(Parms[1], rownames(x))) == 0) stop("Parameter in Parms does not exist.") keeprows <- grep(Parms[1], rownames(x)) if(length(Parms) > 1) { for (i in 2:length(Parms)) { if(length(grep(Parms[i], rownames(x))) == 0) stop("Parameter in Parms does not exist.") keeprows <- c(keeprows, grep(Parms[i], rownames(x)))} } } } temp <- x x <- matrix(x[keeprows,], length(keeprows), ncol(temp)) rownames(x) <- rownames(temp)[keeprows] colnames(x) <- colnames(temp) if(x.lab != "SIR Samples") Modes <- x[,1] else Modes <- x[,6] if(x.lab != "SIR Samples") LB <- x[,3] else LB <- x[,5] if(x.lab != "SIR Samples") UB <- x[,4] else UB <- x[,7] x.rows <- length(Modes) x.lim <- c(min(LB), max(UB)) y.lim <- c(0, x.rows+1) plot(0, 0, ylim=y.lim, xlim=x.lim, main=Title, sub="", xlab=x.lab, ylab="", type="n", ann=TRUE, yaxt="n") abline(v=0, col="gray") points(Modes, x.rows:1, pch=20) for (i in 1:x.rows) { lines(c(LB[i], UB[i]), c(x.rows-i+1, x.rows-i+1))} yy <- x.rows:1 cex.labels <- 1/{log(x.rows)/5 + 1} axis(2, labels=rownames(x), tick=FALSE, las=1, at=yy, cex.axis=cex.labels) } else if(identical(class(x), "pmc")) { x <- x$Summary x.lab <- "All Samples" if(!is.null(Parms)) { if(is.character(Parms)) { Parms <- sub("\\[","\\\\[",Parms) Parms <- sub("\\]","\\\\]",Parms) Parms <- sub("\\.","\\\\.",Parms) if(length(grep(Parms[1], rownames(x))) == 0) stop("Parameter in Parms does not exist.") keeprows <- grep(Parms[1], rownames(x)) if(length(Parms) > 1) { for (i in 2:length(Parms)) { if(length(grep(Parms[i], rownames(x))) == 0) stop("Parameter in Parms does not exist.") keeprows <- c(keeprows, grep(Parms[i], rownames(x)))} } } if(is.numeric(Parms)) keeprows <- Parms temp <- x x <- matrix(x[keeprows,], length(keeprows), ncol(temp)) rownames(x) <- rownames(temp)[keeprows] colnames(x) <- colnames(temp) } x.rows <- nrow(x) x.lim <- c(min(x[,5]), max(x[,7])) y.lim <- c(0, x.rows+1) plot(0, 0, ylim=y.lim, xlim=x.lim, main=Title, sub="", xlab=x.lab, ylab="", type="n", ann=TRUE, yaxt="n") abline(v=0, col="gray") points(x[,6], x.rows:1, pch=20) for (i in 1:x.rows) { lines(x[i,c(5,7)], c(x.rows-i+1, x.rows-i+1))} yy <- x.rows:1 cex.labels <- 1 / {log(x.rows)/5 + 1} axis(2, labels=rownames(x), tick=FALSE, las=1, at=yy, cex.axis=cex.labels) } else if(identical(class(x), "vb")) { if(any(is.na(x$Posterior))) { x <- x$Summary1 x.lab <- "Point-Estimates"} else { x <- x$Summary2[1:length(x$Initial.Values),] x.lab <- "SIR Samples"} if(is.null(Parms)) { keeprows <- Parms <- 1:length(x$Initial.Values)} else { if(is.numeric(Parms)) keeprows <- Parms if(is.character(Parms)) { Parms <- sub("\\[","\\\\[",Parms) Parms <- sub("\\]","\\\\]",Parms) Parms <- sub("\\.","\\\\.",Parms) if(length(grep(Parms[1], rownames(x))) == 0) stop("Parameter in Parms does not exist.") keeprows <- grep(Parms[1], rownames(x)) if(length(Parms) > 1) { for (i in 2:length(Parms)) { if(length(grep(Parms[i], rownames(x))) == 0) stop("Parameter in Parms does not exist.") keeprows <- c(keeprows, grep(Parms[i], rownames(x)))} } } } temp <- x x <- matrix(x[keeprows,], length(keeprows), ncol(temp)) rownames(x) <- rownames(temp)[keeprows] colnames(x) <- colnames(temp) if(x.lab != "SIR Samples") Modes <- x[,1] else Modes <- x[,6] if(x.lab != "SIR Samples") LB <- x[,3] else LB <- x[,5] if(x.lab != "SIR Samples") UB <- x[,4] else UB <- x[,7] x.rows <- length(Modes) x.lim <- c(min(LB), max(UB)) y.lim <- c(0, x.rows+1) plot(0, 0, ylim=y.lim, xlim=x.lim, main=Title, sub="", xlab=x.lab, ylab="", type="n", ann=TRUE, yaxt="n") abline(v=0, col="gray") points(Modes, x.rows:1, pch=20) for (i in 1:x.rows) { lines(c(LB[i], UB[i]), c(x.rows-i+1, x.rows-i+1))} yy <- x.rows:1 cex.labels <- 1/{log(x.rows)/5 + 1} axis(2, labels=rownames(x), tick=FALSE, las=1, at=yy, cex.axis=cex.labels) } else { x <- as.matrix(x) x.hpd <- p.interval(x, HPD=TRUE, MM=FALSE, prob=0.95) x.median <- apply(x, 2, median) x <- cbind(colMeans(x), sqrt(.colVars(x)), apply(x, 2, MCSE), ESS(x), x.hpd[,1], apply(x, 2, median), x.hpd[,2]) rownames(x) <- rownames(x.hpd) colnames(x) <- c("Mean","SD","MCSE","ESS","LB","Median","UB") x.lab <- "All Samples" x.rows <- nrow(x) x.lim <- c(min(x[,5]), max(x[,7])) y.lim <- c(0, x.rows+1) plot(0, 0, ylim=y.lim, xlim=x.lim, main=Title, sub="", xlab=x.lab, ylab="", type="n", ann=TRUE, yaxt="n") abline(v=0, col="gray") points(x[,6], x.rows:1, pch=20) for (i in 1:x.rows) { lines(x[i,c(5,7)], c(x.rows-i+1, x.rows-i+1))} yy <- x.rows:1 cex.labels <- 1 / {log(x.rows)/5 + 1} axis(2, labels=rownames(x), tick=FALSE, las=1, at=yy, cex.axis=cex.labels) } }
knitr::opts_chunk$set(collapse = TRUE, comment = " library(lmem.qtler)
meanvarFESN_uni = function(mu,Sigma,lambda,tau){ s = sqrt(Sigma) slam = sqrt(1+lambda^2) tautil = tau/slam if(tautil< -35){ Gamma = Sigma/(1+lambda^2) mub = lambda*tau*Gamma/s return(meanvarFN(mu-mub,Gamma)) } phi = lambda/slam eta = invmills(tau,0,slam) gamma = sqrt(Sigma/slam^2) mub = lambda*tau*s/slam^2 m = mu - mub FFF = AcumESN(0,mu,Sigma,lambda,tau) eee = dnorm(0,m,gamma) FNNN = pnorm(0,m,gamma) ddd = dmvESN1(0,mu,Sigma,lambda,tau) first = mu*(1-2*FFF) + 2*Sigma*ddd + lambda*eta*s*(1-2*FNNN) second = mu^2 + Sigma + eta*lambda*s*(m + mu) third = (1-2*FFF)*mu*(mu^2 + 3*Sigma) + 2*ddd*s*(s*mu^2 + 2*s^3) + eta*lambda*s*(2*eee*gamma^2*(m + mu) + (1-2*FNNN)*(m^2 + gamma^2 + mu*(m + mu) + 2*Sigma)) fourth = mu^4 + 6*mu^2*Sigma + 3*Sigma^2 + eta*lambda*s*(m^3 + m^2*mu + m*(3*gamma^2 + mu^2 + 3*Sigma) + mu*(gamma^2 + mu^2 + 5*Sigma)) return(list(muY=first,EYY=second,varcov=second-first^2)) } onlymeanFESN_uni = function(mu,Sigma,lambda,tau){ s = sqrt(Sigma) slam = sqrt(1+lambda^2) tautil = tau/slam phi = lambda/slam eta = invmills(tau,0,slam) gamma = sqrt(Sigma/slam^2) mub = lambda*tau*s/slam^2 m = mu - mub FFF = AcumESN(0,mu,Sigma,lambda,tau) eee = dnorm(0,m,gamma) FNNN = pnorm(0,m,gamma) ddd = dmvESN1(0,mu,Sigma,lambda,tau) first = mu*(1-2*FFF) + 2*Sigma*ddd + lambda*eta*s*(1-2*FNNN) return(first) }
solutionFunctionGeneratorPermutation <- function(N){ N function()sample(1:N,replace=FALSE) } mutationPermutationInterchange <- function(population, parameters=list()){ N <- length(population[[1]]) if(is.null(parameters$mutationRate)) parameters$mutationRate <- 1/N mrate <- parameters$mutationRate popsize <- length(population) mutations <- ceiling(N * mrate) if(mutations<=0) return(population) samples <- mutations * popsize index1 <- sample.int(N,samples,TRUE,NULL) index2 <- sample.int(N,samples,TRUE,NULL) mutationPermutationInterchangeCore(population,popsize,mutations,index1,index2) } mutationPermutationInterchangeCore <- function(population,popsize,mutations,index1,index2){ newpop <- list() for(i in 1:popsize){ individual <- population[[i]] if(mutations == 1){ val1 <- individual[index1[i]] individual[index1[i]] <- individual[index2[i]] individual[index2[i]] <- val1 }else{ j <- ((i-1)*mutations+1) : (i*mutations) for(jj in j){ i1 <- index1[jj] i2 <- index2[jj] val1= individual[i1] individual[i1]= individual[i2] individual[i2]= val1 } } newpop <- c(newpop, list(individual)) } newpop } mutationPermutationSwap <- function(population,parameters=list()){ N <- length(population[[1]]) if(is.null(parameters$mutationRate)) parameters$mutationRate <- 1/N mrate <- parameters$mutationRate popsize <- length(population) mutations <- ceiling(N * mrate) if(mutations<=0) return(population) samples <- mutations * popsize index1 <- sample.int(N-1,samples,TRUE,NULL) index2 <- index1 +1 mutationPermutationInterchangeCore(population,popsize,mutations,index1,index2) } mutationPermutationReversal <- function(population, parameters=list()){ N <- length(population[[1]]) if(is.null(parameters$mutationRate)) parameters$mutationRate <- 1/N mrate <- parameters$mutationRate popsize <- length(population) mutations <- ceiling(N * mrate) if(mutations<=0) return(population) samples <- mutations * popsize newpop <- list() index1 <- sample.int(N,samples,TRUE,NULL) index2 <- sample.int(N,samples,TRUE,NULL) for(i in 1:popsize){ individual <- population[[i]] if(mutations == 1){ individual[index1[i]:index2[i]] <- individual[index2[i]:index1[i]] }else{ j <- ((i-1)*mutations+1) : (i*mutations) for(jj in j){ i1 <- index1[jj] i2 <- index2[jj] individual[i1:i2] <- individual[i2:i1] } } newpop <- c(newpop, list(individual)) } newpop } mutationPermutationInsert <- function(population, parameters=list()){ N <- length(population[[1]]) if(is.null(parameters$mutationRate)) parameters$mutationRate <- 1/N mrate <- parameters$mutationRate popsize <- length(population) mutations <- ceiling(N * mrate) if(mutations<=0) return(population) samples <- mutations * popsize newpop <- list() index1 <- sample.int(N,samples,TRUE,NULL) index2 <- sample.int(N,samples,TRUE,NULL) for(i in 1:popsize){ individual <- population[[i]] j <- ((i-1)*mutations+1) : (i*mutations) for(jj in j){ i1 <- index1[jj] i2 <- index2[jj] ind1 <- individual[i1] individual <- individual[-i1] if(i2==1) individual <- c(ind1,individual) else if(i2==N) individual <- c(individual,ind1) else individual <- c(individual[1:(i2-1)],ind1,individual[i2:(N-1)]) } newpop <- c(newpop, list(individual)) } newpop } recombinationPermutationCycleCrossover <- function(population, parameters){ popsize <- length(population)/2 newpop <- list() for(i in 1:popsize){ j <- popsize + i parent1 <- population[[i]] parent2 <- population[[j]] e1 <- parent1[1] e2 <- parent2[1] parent2[1] <- e1 while(e1 != e2){ e1 <- e2 rplc <- which(parent1==e1) e2 <- parent2[rplc] parent2[rplc] <- e1 } newpop <- c(newpop, list(parent2)) } newpop } recombinationPermutationOrderCrossover1 <- function(population, parameters){ popsize <- length(population)/2 N <- length(population[[1]]) newpop <- list() for(i in 1:popsize){ j <- popsize + i parent1 <- population[[i]] parent2 <- population[[j]] idx <- sort(sample(N,2) ) pnew <- setdiff(parent2,parent1[idx[1]:idx[2]]) parent1[-(idx[1]:idx[2])] <- pnew newpop <- c(newpop, list(parent1)) } newpop } recombinationPermutationPositionBased <- function(population, parameters){ popsize <- length(population)/2 N <- length(population[[1]]) newpop <- list() for(i in 1:popsize){ j <- popsize + i parent1 <- population[[i]] parent2 <- population[[j]] idx <- sample(N,N/2,replace=FALSE) parent1[-idx] <- setdiff(parent2,parent1[idx]) newpop <- c(newpop, list(parent1)) } newpop } recombinationPermutationAlternatingPosition <- function(population, parameters){ popsize <- length(population)/2 N <- length(population[[1]]) newpop <- list() for(i in 1:popsize){ j <- popsize + i parent1 <- population[[i]] parent2 <- population[[j]] pnew <- NULL for(i in 1:N){ if(i%%2==1) pnew <- c(pnew,setdiff(parent1,pnew)[1]) if(i%%2==0) pnew <- c(pnew,setdiff(parent2,pnew)[1]) } newpop <- c(newpop, list(pnew)) } newpop }
deriv(y1) <- sigma * (y2 - y1) deriv(y2) <- R * y1 - y2 - y1 * y3 deriv(y3) <- -b * y3 + y1 * y2 initial(y1) <- 10.0 initial(y2) <- 1.0 initial(y3) <- 1.0 sigma <- 10.0 R <- 28.0 b <- 8.0 / 3.0
StatOutlier <- ggproto("StatOutlier", Stat, required_aes = c("x", "y"), default_aes = aes(x = x, y = y, label = stat(outlier)), compute_group = function(data, scales, method = c("x13", "tramoseats"), spec = NULL, frequency = NULL, message = TRUE, first_date = NULL, last_date = NULL, coefficients = FALSE, digits = 1, new_data = TRUE){ result <- seasonal_adjustment(data = data, method = method, spec = spec, frequency = frequency, message = message, new_data = new_data) data <- result[["data"]] sa <- result[["sa"]] frequency <- result[["frequency"]] reg_names <- RJDemetra::get_indicators(sa, "preprocessing.model.description")[[1]] liste_outlier <- grep("(^LS )| (^AO )| (^TC )| (^SO )", reg_names) if (length(liste_outlier) == 0) return(NULL) liste_outlier_name <- reg_names[liste_outlier] date <- gsub("(^.* )|(\\()|(\\))", "", liste_outlier_name) date <- sapply(strsplit(date, "-"),function(x){ x <- as.numeric(x) x[2] + (x[1] - 1)/frequency }) out_to_keep <- 1:length(date) if (!is.null(first_date)) out_to_keep <- intersect(out_to_keep, which(date >= first_date)) if (!is.null(last_date)) out_to_keep <- intersect(out_to_keep, which(date <= last_date)) date <- date[out_to_keep] liste_outlier_name <- liste_outlier_name[out_to_keep] if (length(liste_outlier) == 0) return(NULL) label_outlier <- liste_outlier_name if (coefficients) { reg_coef <- RJDemetra::get_indicators(sa, "preprocessing.model.coefficients")[[1]][liste_outlier,1] reg_coef <- reg_coef[out_to_keep] label_outlier <- sprintf(paste0("%s: %.",digits,"f"), liste_outlier_name, reg_coef) } id_date <- match(as.character(round(date, 3)), as.character(round(result[["dates"]], 3))) data_final <- data.frame(x = data$x[id_date], y = data$y[id_date], outlier = label_outlier, stringsAsFactors = FALSE ) data_final } ) geom_outlier <- function(mapping = NULL, data = NULL, stat = "outlier", geom = c("text", "label", "text_repel", "label_repel"), position = "identity", ..., method = c("x13", "tramoseats"), spec = NULL, frequency = NULL, message = TRUE, first_date = NULL, last_date = NULL, coefficients = FALSE, digits = 1, show.legend = NA, inherit.aes = TRUE ) { geom <- match.arg(geom) if (geom == "label_repel") { geom <- GeomLabelRepel } else if (geom == "text_repel") { geom <- GeomTextRepel } else if (geom == "label") { geom <- GeomLabel } else { geom <- GeomText } ggplot2::layer(data = data, mapping = mapping, stat = stat, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(method = method, spec = spec, frequency = frequency, message = message, first_date = first_date, last_date = last_date, coefficients = coefficients, digits = digits, new_data = !missing(data) || !is.null(data), ...)) }
library(knitr) library(poweRlaw) options(replace.assign=FALSE,width=50) opts_chunk$set(fig.path = "knitr_figure_poweRlaw/graphicsc-", cache.path = "knitr_cache_poweRlaw_c/", fig.align = "center", dev = "pdf", fig.width = 5, fig.height = 5, fig.show = "hold", cache = FALSE, par = TRUE, out.width = "0.4\\textwidth") knit_hooks$set(crop = hook_pdfcrop) knit_hooks$set(par = function(before, options, envir) { if (before && options$fig.show != "none") { par(mar = c(3, 4, 2, 1), cex.lab = .95, cex.axis = .9, mgp = c(3, .7, 0), tcl = -.01, las = 1) }}, crop = hook_pdfcrop) set.seed(1) palette(c(rgb(170, 93, 152, maxColorValue = 255), rgb(103, 143, 57, maxColorValue = 255), rgb(196, 95, 46, maxColorValue = 255), rgb(79, 134, 165, maxColorValue = 255), rgb(205, 71, 103, maxColorValue = 255), rgb(203, 77, 202, maxColorValue = 255), rgb(115, 113, 206, maxColorValue = 255))) library("poweRlaw") set.seed(1) x = rpldis(1000, xmin = 2, alpha = 3) m1 = displ$new(x) m1$setPars(estimate_pars(m1)) m2 = dispois$new(x) m2$setPars(estimate_pars(m2)) plot(m2, ylab = "CDF") lines(m1) lines(m2, col = 2, lty = 2) grid() plot(m2, ylab = "CDF") lines(m1) lines(m2, col = 2, lty = 2) grid() comp = compare_distributions(m1, m2) comp$p_two_sided compare_distributions(m1, m2)$p_two_sided compare_distributions(m2, m1)$p_two_sided compare_distributions(m1, m2)$p_one_sided compare_distributions(m2, m1)$p_one_sided data("moby") m1 = displ$new(moby) m1$setXmin(estimate_xmin(m1)) m2 = dislnorm$new(moby) m2$setXmin(m1$getXmin()) m2$setPars(estimate_pars(m2)) plot(m2, ylab = "CDF") lines(m1) lines(m2, col = 2, lty = 2) grid() plot(m2, ylab = "CDF") lines(m1) lines(m2, col = 2, lty = 2) grid() comp = compare_distributions(m1, m2) comp$p_two_sided comp$test_statistic rm(list = ls(all = TRUE))
mlnormal_update_beta <- function( NB, Z_index, G, beta, Z_list, X_list, y_list, V1_list, theta, REML=FALSE, id_list, N, V1zero=NULL, REML_shortcut=FALSE, rcpp_args, X, y, use_Rcpp, prior_args, control_beta ) { beta0 <- beta P <- NULL if ( use_Rcpp ){ mlnormal_update_beta_XVX_ <- mlnormal_update_beta_XVX_Rcpp } else { mlnormal_update_beta_XVX_ <- mlnormal_update_beta_XVX_R } res <- mlnormal_update_beta_XVX_( NB=NB, Z_index=Z_index, G=G, V1_list=V1_list, X_list=X_list, y_list=y_list, rcpp_args=rcpp_args, X=X, y=y ) XVX <- res$XVX XVY <- res$XVY XV_list <- res$XV_list if ( ( ! REML_shortcut ) & REML ){ XVX1 <- solve(XVX) V1 <- mlnormal_fill_matrix_from_list( V1=V1zero, V1_list=V1_list, id_list=id_list, G=G ) H1 <- XVX1 %*% crossprod(X, V1 ) P <- V1 - V1 %*% X %*% H1 } if ( prior_args$use_GLS ){ beta <- mlnormal_update_beta_GLS( XVX=XVX, XVY=XVY, control_beta=control_beta) } if ( prior_args$use_prior ){ beta <- mlnormal_update_beta_iterations_priors(beta=beta0, prior_args=prior_args, XVX=XVX, XVY=XVY, control_beta=control_beta ) } if ( prior_args$use_penalty ){ beta <- mlnormal_update_beta_iterations_penalty(beta=beta0, prior_args=prior_args, XVX=XVX, XVY=XVY, control_beta=control_beta ) } beta <- mlnormal_as_vector_names(pars=beta, parnames=names(beta0) ) beta <- sirt::bounds_parameters( pars=beta, lower=control_beta$beta_lower, upper=control_beta$beta_upper ) beta_change <- mlnormal_parameter_change( pars=beta, pars0=beta0 ) res <- list("beta"=beta, "beta_change"=beta_change, XVX=XVX, XVY=XVY, P=P, beta_increment=beta - beta0 ) return(res) }
.accel_names <- c("Accelerometer_X", "Accelerometer_Y", "Accelerometer_Z") .gyro_names <- c("Gyroscope_X", "Gyroscope_Y", "Gyroscope_Z") .mag_names <- c("Magnetometer_X", "Magnetometer_Y", "Magnetometer_Z") empty_raw <- function( timestamps, empty_value = NA, info, empty_frame = NULL ) { if (!length(timestamps)) { return(structure( list( Timestamp = structure( numeric(0), class = c("POSIXct", "POSIXt") ), Accelerometer_X = numeric(0), Accelerometer_Y = numeric(0), Accelerometer_Z = numeric(0) ), row.names = integer(0), class = "data.frame" )) } milliseconds <- seq(info$Sample_Rate) - 1 milliseconds <- milliseconds / info$Sample_Rate missing_times <- sapply( timestamps, function(x) x + milliseconds, simplify = FALSE ) %>% {do.call(c, .)} if (is.null(empty_frame)) { missing_entries <- data.frame( Timestamp = missing_times, Accelerometer_X = empty_value, Accelerometer_Y = empty_value, Accelerometer_Z = empty_value ) } else { missing_entries <- data.frame( Timestamp = missing_times, empty_frame, row.names = NULL ) } missing_entries } tick_to_posix <- function(x, tz = "UTC", ...) { x <- as.numeric(as.character(x)) / 10000000 as.POSIXct(x, tz, origin = "0001-01-01", ...) } bin_int <- function(value_bin) { sum(2 ^ (length(value_bin) - which(value_bin))) } AG_binary <- function(value, n = 8) { binaryLogic::as.binary( unlist(binaryLogic::as.binary(rev(value), n = n)), logic = TRUE ) } get_value <- function(type, value) { switch( type, "float" = get_float_value(value), "int" = readBin(value, "integer", 4, 4) ) } get_float_value <- function(value) { n_bytes <- length(value) n_bits <- n_bytes * 8 exponent <- get_exponent(value, n_bytes) significand <- get_significand(value, n_bits, n_bytes) significand * (2^exponent) } get_exponent <- function(value, n_bytes) { x <- value[n_bytes] binx <- AG_binary(x, n = 8) is_negative <- binx[1] == binaryLogic::as.binary(1) exponent <- as.integer(binx) if (is_negative) { exponent <- exponent * -1 } return(as.double(exponent)) } get_significand <- function(value, n_bits, n_bytes) { FLOAT_MAXIMUM <- 2^((n_bits - 8) - 1) x <- value[rev(seq(value))[-1]] binx <- AG_binary(rev(x), n = 8) is_negative <- binx[1] == binaryLogic::as.binary(1) significand <- as.integer(binx) if (is_negative) { significand <- significand * -1 } as.double(significand) / FLOAT_MAXIMUM } update_key <- function(key, value) { key <- key[1, ] key$Range <- NA key$value <- value return(key) } capability_collapse <- function(caps) { cap_length <- length(caps) if (cap_length == 1) return (caps) last_cap <- caps[length(caps)] caps <- paste(caps[-length(caps)], collapse = ", ") caps <- paste(c(caps, ", and ", last_cap), collapse = "") if (cap_length == 2) caps <- gsub(", and", " and", caps) return(caps) } get_primary_accel_scale <- function(info) { scale_factor <- switch( substring(info$Serial_Number, 1, 3), "NEO" = 341, "CLE" = 341, "MOS" = 256 ) if ("Acceleration_Scale" %in% names(info)) { scale_factor <- info$Acceleration_Scale } stopifnot(all.equal( scale_factor, as.integer(scale_factor), scale = 1, tolerance = 0.0 )) as.integer(scale_factor) }
parallelTables=function(width,listTables,type="latex"){ a=length(width) if(class(listTables)!="list"){ cat("\nThe 2nd parameter listTables sholud be a list\n") return(invisible()) } b=length(listTables) if(a!=b) { cat("\nLengths of width and tables are different\n") cat(paste("length of width=",a,",length of tables=",b,sep="")) return(invisible()) } if(type=="html") parallelTablesHTML(width,listTables) else parallelTablesLatex(width,listTables) } parallelTablesLatex=function(width,listTables){ a=length(width) cat("\\begin{table}[!htb]\n") for(i in 1:a){ cat(paste("\\begin{minipage}{",width[i],"\\linewidth}\n\\centering\n", sep="")) if(class(listTables[[i]])=="ztable") print(listTables[[i]],type="latex") else if(class(listTables[[i]])=="character") { cat(paste("\\includegraphics[width=1\\linewidth]{", listTables[[i]],"}\n",sep="")) } cat("\\end{minipage}\n") } cat("\\end{table}") } parallelTablesHTML=function(width,listTables){ a=length(width) cat("<table width=\"100%\" cellspacing=\"5px\" cellpadding=\"5px\" border=\"0\"> \n<colgroup>\n") for(i in 1:a) cat(paste("<col width=", ifelse(width[i]<=1,width[i]*100,width[i]), "%>\n",sep="")) cat("</colgroup>\n<tr>") for(i in 1 :a){ cat("<td>") if(class(listTables[[i]])=="ztable") print(listTables[[i]],type="html") else if(class(listTables[[i]])=="character") cat(paste("<img src=\"",listTables[[i]],"\">",sep="")) cat("</td>\n") } cat("</tr>\n</table>\n") }
f_level_shift <- function(data_series,threshold1,threshold2,duration) { diff1 <- data_series[-1] - data_series[-length(data_series)] Index <- which(abs(diff1)>threshold1) diff2 <- rep(0, length(Index)) number_temp <- 0 number <- 0 LS_candidate <- c() LS_mag <- c() LS_point <- c() if(length(Index) > 0) { for(i in 1:length(Index)) { Up <- Index[i] + duration Down <- Index[i] - duration if ( (Up > length(data_series)) || (Down < 1) ) { diff2[i] <- 0 } else { diff2[i] <- mean( data_series[Index[i]:Up] ) - mean( data_series[Down:Index[i]] ) } if( (abs(diff2[i]) > threshold2) && (sign(diff1[Index[i]]) == sign(diff2[i])) ) { number_temp <- number_temp + 1 LS_candidate[number_temp] <- Index[i] LS_mag[number_temp] <- diff2[i] } } } if(number_temp > 0) { absLS_mag <- abs(LS_mag) LS_mag_sorted <- absLS_mag[order(-absLS_mag)] index_sort <- order(-absLS_mag) number <- 1 LS_point[number] <- LS_candidate[index_sort[1]] if(number_temp>1) { ci <- 2 for(i in 2:number_temp) { t <- 0 for(j in 1:number) { if( abs(LS_candidate[index_sort[ci]] - LS_point[j]) > duration ) { t <- t + 1 } } if (t == number) { number <- number + 1 LS_point[number] <- LS_candidate[index_sort[ci]] } ci <- ci + 1 } } } flevel.values <- list( "no" = number, "LS_point" = LS_point ) class(flevel.values) <- "flevel" return(flevel.values) }
write_idx = function(x, file_name, endian = "big") { if (!is.character(file_name)) stop("File_name must be character") file = file(file_name, "wb") writeBin(as.raw(0), file, size = 1, endian = endian) writeBin(as.raw(0), file, size = 1, endian = endian) if (typeof(x) == "integer") { type = 12 size = 4 } else if (typeof(x) == "double") { type = 14 size = 8 } else stop("Type of x must be integer or double") writeBin(as.raw(type), file, size = 1, endian = endian) if (is.array(x)) dim_x = dim(x) else if (is.vector(x)) dim_x = length(x) else stop("x must be a vector, a matrix or an array") writeBin(as.raw(length(dim_x)), file, size = 1, endian = endian) for (i in dim_x) { writeBin(i, file, size = 4, endian = endian) } if (length(dim_x) > 1) x = as.vector(aperm(x)) writeBin(x, file, size = size, endian = endian) close(file) }
invlogit <- function(x) { 1 - 1 / (1 + exp(x)) } get_exp_Xb <- function(y, x, pars) exp(get_Xb(y, x, pars)) get_Xb <- function(y, x, pars) { pars_betas <- pars[-1, ] x %*% pars_betas }
scales <- c(10,50,110) list_scales_phys <- purrr::map(scales, ne_find_vector_data, category = 'physical') df_layers_physical <- dplyr::full_join(list_scales_phys[[1]], list_scales_phys[[2]], by='layer') df_layers_physical <- dplyr::full_join(df_layers_physical, list_scales_phys[[3]], by='layer') names(df_layers_physical)[2:4] <- paste0('scale',scales) df_layers_physical[2:4] <- ifelse(is.na(df_layers_physical[2:4]),0,1) df_layers_physical <- dplyr::arrange(df_layers_physical, layer) list_scales_cult <- purrr::map(scales, ne_find_vector_data, category = 'cultural') df_layers_cultural <- dplyr::full_join(list_scales_cult[[1]], list_scales_cult[[2]], by='layer') df_layers_cultural <- dplyr::full_join(df_layers_cultural, list_scales_cult[[3]], by='layer') names(df_layers_cultural)[2:4] <- paste0('scale',scales) df_layers_cultural[2:4] <- ifelse(is.na(df_layers_cultural[2:4]),0,1) df_layers_cultural <- dplyr::arrange(df_layers_cultural, layer) devtools::use_data(df_layers_physical, overwrite=TRUE) devtools::use_data(df_layers_cultural, overwrite=TRUE)
test_that("defineModule correctly handles different inputs", { testInitOut <- testInit("raster", smcc = FALSE) on.exit({ testOnExit(testInitOut) }, add = TRUE) tmp <- simInit() x0 <- list() expect_warning(defineModule(tmp, x0)) expect_identical(suppressWarnings(defineModule(tmp, x0)), suppressWarnings(defineModule(tmp, .emptyMetadata()))) x1 <- list( name = "testModule", description = "this is a test.", keywords = c("test"), childModules = character(), authors = c(person(c("Alex", "M"), "Chubaty", email = "[email protected]", role = c("aut", "cre"))), version = list(testModule = "0.0.0.9000"), spatialExtent = raster::extent(rep(NA_real_, 4)), timeframe = as.POSIXlt(c(NA, NA)), timeunit = "year", citation = list(), documentation = list(), reqdPkgs = list("grid", "raster", "sp"), parameters = rbind( defineParameter("dummyVal", "numeric", 1.0, NA, NA, "vague description with spaces") ), inputObjects = bindrows( expectsInput(objectName = "testInput", objectClass = "list", sourceURL = "", desc = NA_character_), expectsInput(objectName = "testInput2", objectClass = "list", sourceURL = "", desc = "another vague description with spaces") ), outputObjects = bindrows( createsOutput(objectName = "testOutput", objectClass = "list", desc = NA_character_), createsOutput(objectName = "testOutput", objectClass = "list", desc = "another vague description with spaces for outputs another space") ) ) expect_false(any(unlist(lapply(x1, function(v) grepl(" |\n", v))))) x1 <- rmExtraSpacesEOLList(x1) expect_false(any(unlist(lapply(x1, function(v) grepl(" |\n", v))))) x2 <- x1 x2$name <- list("testModule") expect_identical(defineModule(tmp, x1), defineModule(tmp, x2)) x2 <- x1 x2$description <- list("this is a test.") expect_identical(defineModule(tmp, x1), defineModule(tmp, x2)) x2 <- x1 x2$keywords <- list("test") expect_identical(defineModule(tmp, x1), defineModule(tmp, x2)) x2 <- x1 x2$authors <- "not a person class" expect_true({defineModule(tmp, x2); TRUE}) x2 <- x1 x2$version <- "0.0.0.9000" expect_identical(defineModule(tmp, x1), defineModule(tmp, x2)) x2 <- x1 x2$spatialExtent <- NA expect_identical(defineModule(tmp, x1), defineModule(tmp, x2)) x2 <- x1 x2$timeframe <- NA expect_identical(defineModule(tmp, x1), defineModule(tmp, x2)) x2 <- x1 x2$timeunit <- NA expect_identical(defineModule(tmp, x1), defineModule(tmp, x2)) x2 <- x1 x2$citation <- character() expect_identical(defineModule(tmp, x1), defineModule(tmp, x2)) x2 <- x1 x2$reqdPkgs <- c("grid", "raster", "sp") expect_identical(defineModule(tmp, x1), defineModule(tmp, x2)) x2 <- x1 x2$parameters <- "not a data.frame" expect_true({defineModule(tmp, x2); TRUE}) x2 <- x1 x2$inputObjects <- "not a data.frame" expect_true({defineModule(tmp, x2); TRUE}) x2 <- x1 x2$outputObjects <- "not a person class" expect_true({defineModule(tmp, x2); TRUE}) }) test_that("depsEdgeList and depsGraph work", { times <- list(start = 0.0, end = 10) params <- list( .globals = list(burnStats = "npixelsburned", stackName = "landscape"), randomLandscapes = list(.plotInitialTime = NA, .plotInterval = NA), caribouMovement = list(.plotInitialTime = NA, .plotInterval = NA), fireSpread = list(.plotInitialTime = NA, .plotInterval = NA) ) modules <- list("randomLandscapes", "caribouMovement", "fireSpread") paths <- list(modulePath = system.file("sampleModules", package = "SpaDES.core")) mySim <- simInit(times, params, modules, paths = paths) el <- depsEdgeList(mySim) el_from <- c("caribouMovement", "fireSpread", "fireSpread", "fireSpread", "randomLandscapes", "randomLandscapes") el_to <- c("caribouMovement", "caribouMovement", "fireSpread", "fireSpread", "caribouMovement", "fireSpread") el_objName <- c("caribou", "landscape", "landscape", "npixelsburned", "landscape", "landscape") el_objClass <- c("SpatialPointsDataFrame", "RasterStack", "RasterStack", "numeric", "RasterStack", "RasterStack") expect_is(el, "data.table") expect_equal(names(el), c("from", "to", "objName", "objClass")) expect_equal(el$from, el_from) expect_equal(el$to, el_to) expect_equal(el$objName, el_objName) expect_equal(el$objClass, el_objClass) p <- .depsPruneEdges(el) p_from <- c("fireSpread", "randomLandscapes", "randomLandscapes") p_to <- c("caribouMovement", "caribouMovement", "fireSpread") p_objName <- c("landscape", "landscape", "landscape") p_objClass <- c("RasterStack", "RasterStack", "RasterStack") p_ <- data.table::data.table( from = p_from, to = p_to, objName = p_objName, objClass = p_objClass ) expect_is(p, "data.table") expect_equivalent(p, p_) expect_is(depsGraph(mySim), "igraph") }) test_that("3 levels of parent and child modules load and show correctly", { testInitOut <- testInit("raster", smcc = FALSE) on.exit({ testOnExit(testInitOut) }, add = TRUE) suppressMessages({ newModule("grandpar1", tmpdir, type = "parent", children = c("child1", "child2", "par1", "par2"), open = FALSE) newModule("par1", tmpdir, type = "parent", children = c("child4", "child3"), open = FALSE) newModule("par2", tmpdir, type = "parent", children = c("child5", "child6"), open = FALSE) newModule("child1", tmpdir, open = FALSE) newModule("child2", tmpdir, open = FALSE) newModule("child3", tmpdir, open = FALSE) newModule("child4", tmpdir, open = FALSE) newModule("child5", tmpdir, open = FALSE) newModule("child6", tmpdir, open = FALSE) }) fileName <- "child2/child2.R" xxx <- readLines(fileName) xxx1 <- gsub(xxx, pattern = 'timeunit = "year"', replacement = 'timeunit = "day"') cat(xxx1, file = fileName, sep = "\n") fileName <- "child3/child3.R" xxx <- readLines(fileName) xxx1 <- gsub(xxx, pattern = 'timeunit = "year"', replacement = 'timeunit = "week"') cat(xxx1, file = fileName, sep = "\n") fileName <- "child5/child5.R" xxx <- readLines(fileName) xxx1 <- gsub(xxx, pattern = 'timeunit = "year"', replacement = 'timeunit = "second"') cat(xxx1, file = fileName, sep = "\n") fileName <- "par1/par1.R" xxx <- readLines(fileName) xxx1 <- gsub(xxx, pattern = 'timeunit = "year"', replacement = 'timeunit = "month"') cat(xxx1, file = fileName, sep = "\n") if (Sys.which("glpsol") == "") { if (Sys.info()[['sysname']] == "Darwin") { skip("GLPK not available on macOS") } else if (Sys.info()[['sysname']] == "Linux") { skip("GLPK not available on Linux") } } else { mySim <- simInit(modules = list("grandpar1"), paths = list(modulePath = tmpdir)) mg <- moduleGraph(mySim, FALSE) if (is(mg, "list")) { expect_true(is(mg$graph, "igraph")) expect_true(is(mg$communities, "communities")) expect_true(length(unique(mg$communities$member)) == 3) comm <- try(communities(mg$communities)[["1"]]) if (!is(comm, "try-error")) { expect_true(any(grepl("grandpar1", comm))) expect_true(identical(basename(comm), c("grandpar1", "par1", "par2", "child1", "child2"))) } } } }) test_that("Test cleaning up of desc in createsOutputs, expectsInputs, defineParameters", { testInitOut <- testInit("raster", smcc = FALSE) on.exit({ testOnExit(testInitOut) }, add = TRUE) aList <- list() aList[[1]] <- expectsInput("ROCList", "list", sourceURL = NA, "Hi ", "Ho ", "its off to work we go", otherCol = "lala") aList[[2]] <- createsOutput("ROCList", "list", "Hi ", "Ho ", "its off to work we go", otherCol = "lala") aList[[3]] <- defineParameter("ROCList", "list", NA, NA, NA, "Hi ", "Ho ", "its off to work we go", otherCol = "lala") tests <- Map(a = aList, nam = c("expectsInput", "createsOutput", "defineParameter"), function(a, nam) { expect_true(is(a, "data.frame")) cn <- colnames(a) cn <- tolower(gsub("param", "", cn)) actuallyIs <- tolower(sort(c("...", cn))) shouldBe <- tolower(sort(c(formalArgs(get(nam))))) if (!grepl("Param", nam)) shouldBe <- sort(c(shouldBe, "othercol")) expect_true(identical(actuallyIs, shouldBe)) desc <- a[[grep("desc", tolower(colnames(a)))]] expect_false(grepl(" ", desc)) expect_false(grepl("\n", desc)) }) })
sim.HCAR <- function(psi, data, n.samples){ if (is.environment(data)) { y <- get("y", envir=data) X <- get("X", envir=data) W <- get("W", envir=data) M <- get("M", envir=data) Z <- get("Z", envir=data) n <- length(y) K <- nrow(M) In <- get("In", envir=data) Ik <- get("Ik", envir=data) } else { y <- data$y X <- data$X W <- data$W M <- data$M Z <- data$Z n <- length(y) K <- nrow(M) In <- data$In Ik <- data$Ik } if(is.null(W)){ lambda <- psi[1] sigma.e <- psi[2] sigma.u <- psi[3] beta <- psi[-c(1:3)] Qe.s <- In/sigma.e Qu.s <- (Ik - lambda*M)/sigma.u Xb <- X %*% beta Q.new <- crossprod(Z)/sigma.e + Qu.s b <- solve(Q.new, crossprod(Z, as.spam(Qe.s %*% (y-Xb)))) CholQ <- chol(Q.new, pivot = "MMD", memory = list(nnzcolindices = 6.25 * K)) z.err <- matrix(rnorm(K*n.samples), nrow = K, ncol = n.samples) u.y <- apply(z.err, 2, function(x) b + backsolve(CholQ, x)) log.uy <- function(u.y){ res <- y - Xb - Z%*%u.y as.numeric(-0.5 *(crossprod(res)/sigma.e + crossprod(u.y, Qu.s) %*% u.y)) } lpsi <- apply(u.y, 2, log.uy) logdetQes.half <- sum(log(diag(Qe.s)))/2 Lu.s <- chol(Qu.s, pivot = "MMD", memory = list(nnzcolindices = 6.25 * K)) logdetQus.half <- sum(log(diag(Lu.s))) const.psi <- logdetQes.half + logdetQus.half }else{ rho <- psi[1] lambda <- psi[2] sigma.e <- psi[3] sigma.u <- psi[4] beta <- psi[-c(1:4)] Qe.s <- as.spam((In - rho*W)/sigma.e) Qu.s <- as.spam((Ik - lambda*M)/sigma.u) Xb <- X %*% beta Q.new <- as.spam(crossprod(Z, Qe.s) %*% Z + Qu.s) b <- solve(Q.new, crossprod(Z, Qe.s %*% (y-Xb))) CholQ <- chol(Q.new, pivot = "MMD", memory = list(nnzcolindices = 6.25 * K)) z.err <- matrix(rnorm(K*n.samples), nrow = K, ncol = n.samples) u.y <- apply(z.err, 2, function(x) b + backsolve(CholQ, x)) log.uy <- function(u.y){ res <- y - Xb - Z%*%u.y as.numeric(-0.5 *(crossprod(res, Qe.s) %*% res + crossprod(u.y, Qu.s) %*% u.y)) } lpsi <- apply(u.y, 2, log.uy) Le.s <- chol(Qe.s, pivot = "MMD", memory = list(nnzcolindices = 6.25 * n)) logdetQes.half <- sum(log(diag(Le.s))) Lu.s <- chol(Qu.s, pivot = "MMD", memory = list(nnzcolindices = 6.25 * K)) logdetQus.half <- sum(log(diag(Lu.s))) const.psi <- logdetQes.half + logdetQus.half } return(list(psi = psi, n.samples = n.samples, u.y = u.y, lpsi = lpsi, const.psi = const.psi)) }
set.seed(123) dists <- list( dist(matrix(rnorm(1000), ncol = 4)), dist(matrix(rnorm(1000), ncol = 20)), dist(matrix(rnorm(10000), ncol = 40)), dist(matrix(sample(1:100000, 1000), ncol = 4)), dist(matrix(sample(1:100000, 1000), ncol = 20)), dist(matrix(sample(1:100000, 1000), ncol = 50)) ) referenceImplementation <- function(distance, dc, gaussian=FALSE) { if(missing(dc)) { dc <- reference_estimateDc(distance) } rho <- reference_localDensity(distance, dc, gaussian=gaussian) delta <- reference_distanceToPeak(distance, rho) res <- list(rho=rho, delta=delta, distance=distance, dc=dc, threshold=c(rho=NA, delta=NA), peaks=NA, clusters=NA, halo=NA, knn_graph = NA, nearest_higher_density_neighbor = NA, nn.index = NA, nn.dist = NA) class(res) <- 'densityCluster' res } reference_estimateDc <- function(distance, neighborRateLow=0.01, neighborRateHigh=0.02) { comb <- as.matrix(distance) size <- attr(distance, 'Size') dc <- min(distance) dcMod <- as.numeric(summary(distance)['Median']*0.01) while(TRUE) { neighborRate <- mean((apply(comb < dc, 1, sum)-1)/size) if(neighborRate > neighborRateLow && neighborRate < neighborRateHigh) break if(neighborRate > neighborRateHigh) { dc <- dc - dcMod dcMod <- dcMod/2 } dc <- dc + dcMod } cat('Distance cutoff calculated to', dc, '\n') dc } reference_distanceToPeak <- function(distance, rho) { comb <- as.matrix(distance) res <- sapply(1:length(rho), function(i) { peaks <- comb[rho>rho[i], i] if(length(peaks) == 0) { max(comb[,i]) } else { min(peaks) } }) names(res) <- names(rho) res } reference_localDensity <- function(distance, dc, gaussian=FALSE) { comb <- as.matrix(distance) if(gaussian) { res <- apply(exp(-(comb/dc)^2), 1, sum)-1 } else { res <- apply(comb < dc, 1, sum)-1 } if(is.null(attr(distance, 'Labels'))) { names(res) <- NULL } else { names(res) <- attr(distance, 'Labels') } res } dcs <- lapply(dists, estimateDc) referenceDcs <- lapply(dists, reference_estimateDc) densityClustReference <- Map(referenceImplementation, dists, dcs) gaussianDensityClustReference <- Map(referenceImplementation, dists, dcs, TRUE)
if_na = function(x, value, label = NULL){ stopifnot(length(label)<2) if (length(label) == 0 || label == ""){ recode(x) = c(NA, NaN) ~ value } else { args = list(c(NA, NaN) ~ value) names(args) = label recode(x) = args } x } 'if_na<-' = function(x, label = NULL, value){ fix_datatable(if_na(x, value, label = label)) } '%if_na%' = function(x, value) if_na(x, value) na_if = function(x, value, with_labels = FALSE){ if(!length(value)) return(x) recode(x, with_labels = with_labels) = value ~ NA x } 'na_if<-' = function(x, with_labels = FALSE, value){ fix_datatable(na_if(x, value, with_labels = with_labels)) } '%na_if%' = function(x, value) na_if(x, value) mis_val = na_if 'mis_val<-' = `na_if<-` '%mis_val%' = '%na_if%' valid = function(x){ UseMethod("valid") } valid.default = function(x){ !is.na(x) } valid.data.frame = function(x){ if (length(x)) { res = do.call(cbind, lapply(x, is.na)) } else { res = matrix(FALSE, NROW(x), 0) } !rowAlls(res) } valid.dichotomy = function(x){ if (length(x)) { res = do.call(cbind, lapply(x, function(x) x==1)) } else { res = matrix(FALSE, NROW(x), 0) } rowAnys(res, na.rm = TRUE) } valid.matrix = function(x){ !rowAlls(is.na(x)) }
OptimalSet <- function(object){ if(is.null(object$Psel)) out <- data.frame("Name"=object$Xopt,"Importance"=object$ranking[object$Xopt]) else out <- data.frame("Name"=object$Xopt,"Importance"=object$ranking[object$Xopt], "Prob.Selection"=object$Psel[object$Xopt]) rownames(out) <- NULL return(out) }
es10REF <- c("", "Formula: composite ~ dsex + b017451 ", "", "Plausible values: 5", "jrrIMax: 1", "Weight variable: 'origwt'", "Variance method: jackknife", "JK replicates: 62", "full data n: 17606", "n used: 16331", "", "", "Summary Table:", " dsex b017451 N WTD_N PCT SE(PCT) MEAN SE(MEAN)", " Male Never or hardly ever 2350 2434.844 29.00978 0.6959418 270.8243 1.057078", " Male Once every few weeks 1603 1638.745 19.52472 0.5020657 275.0807 1.305922", " Male About once a week 1384 1423.312 16.95795 0.5057265 281.5612 1.409587", " Male 2 or 3 times a week 1535 1563.393 18.62694 0.4811497 284.9066 1.546072", " Male Every day 1291 1332.890 15.88062 0.5872731 277.2597 1.795784", " Female Never or hardly ever 1487 1517.609 18.20203 0.5078805 266.7897 1.519020", " Female Once every few weeks 1544 1552.149 18.61630 0.4892491 271.2255 1.205528", " Female About once a week 1469 1514.403 18.16358 0.5782966 278.7502 1.719778", " Female 2 or 3 times a week 1827 1862.502 22.33864 0.4844840 282.7765 1.404107", " Female Every day 1841 1890.918 22.67945 0.6553039 275.4628 1.219439" ) es11REF2 <- c("", "Formula: composite ~ dsex + b017451 ", "", "Plausible values: 5", "jrrIMax: 1", "Weight variable: 'origwt'", "Variance method: jackknife", "JK replicates: 62", "full data n: 17606", "n used: 16331", "", "", "Summary Table:", " dsex b017451 N WTD_N PCT SE(PCT) MEAN SE(MEAN)", " Male Never or hardly ever 2350 2434.844 29.00978 0.6959418 270.8243 1.057078", " Male Once every few weeks 1603 1638.745 19.52472 0.5020657 275.0807 1.305922", " Male About once a week 1384 1423.312 16.95795 0.5057265 281.5612 1.409587", " Male 2 or 3 times a week 1535 1563.393 18.62694 0.4811497 284.9066 1.546072", " Male Every day 1291 1332.890 15.88062 0.5872731 277.2597 1.795784", " Female Never or hardly ever 1487 1517.609 18.20203 0.5078805 266.7897 1.519020", " Female Once every few weeks 1544 1552.149 18.61630 0.4892491 271.2255 1.205528", " Female About once a week 1469 1514.403 18.16358 0.5782966 278.7502 1.719778", " Female 2 or 3 times a week 1827 1862.502 22.33864 0.4844840 282.7765 1.404107", " Female Every day 1841 1890.918 22.67945 0.6553039 275.4628 1.219439" ) es2lREF <- c("", "Formula: composite ~ dsex + b017451 ", "", "Plausible values: 5", "jrrIMax: 5", "Weight variable: 'origwt'", "Variance method: jackknife", "JK replicates: 62", "full data n: 17606", "n used: 8163", "", "", "Summary Table:", " dsex b017451 N WTD_N PCT SE(PCT) MEAN SE(MEAN)", " Male Never or hardly ever 2350 2434.844 29.00978 0.6959418 270.8243 1.063871", " Male Once every few weeks 1603 1638.745 19.52472 0.5020657 275.0807 1.364160", " Male About once a week 1384 1423.312 16.95795 0.5057265 281.5612 1.418074", " Male 2 or 3 times a week 1535 1563.393 18.62694 0.4811497 284.9066 1.516851", " Male Every day 1291 1332.890 15.88062 0.5872731 277.2597 1.787613" ) es2lbREF <- c("", "Formula: composite ~ dsex + b017451 ", "", "Plausible values: 5", "jrrIMax: 5", "Weight variable: 'origwt'", "Variance method: jackknife", "JK replicates: 62", "full data n: 17606", "n used: 8163", "", "", "Summary Table:", " dsex b017451 N WTD_N PCT SE(PCT) MEAN SE(MEAN)", " Male Never or hardly ever 2350 2434.844 29.00978 0.6959418 270.8243 1.063871", " Male Once every few weeks 1603 1638.745 19.52472 0.5020657 275.0807 1.364160", " Male About once a week 1384 1423.312 16.95795 0.5057265 281.5612 1.418074", " Male 2 or 3 times a week 1535 1563.393 18.62694 0.4811497 284.9066 1.516851", " Male Every day 1291 1332.890 15.88062 0.5872731 277.2597 1.787613" )
gates_eff <- function(dx, dy, marks, par=list(a=1, b=4, smark=1)) { with(as.list(par), (pmax(0, 1 - (b * sqrt(dx^2 + dy^2) / marks[[smark]])^a))^(1/a) ) }
b_file_keyrings <- new.env(parent = emptyenv()) backend_file <- R6Class( "backend_file", inherit = backend_keyrings, public = list( name = "file", initialize = function(keyring = NULL) b_file_init(self, private, keyring), get = function(service, username = NULL, keyring = NULL) b_file_get(self, private, service, username, keyring), get_raw = function(service, username = NULL, keyring = NULL) b_file_get_raw(self, private, service, username, keyring), set = function(service, username = NULL, keyring = NULL, prompt = NULL) b_file_set(self, private, service, username, keyring, prompt), set_with_value = function(service, username = NULL, password = NULL, keyring = NULL) b_file_set_with_value(self, private, service, username, password, keyring), delete = function(service, username = NULL, keyring = NULL) b_file_delete(self, private, service, username, keyring), list = function(service = NULL, keyring = NULL) b_file_list(self, private, service, keyring), keyring_create = function(keyring = NULL, password = NULL) b_file_keyring_create(self, private, keyring, password), keyring_delete = function(keyring = NULL) b_file_keyring_delete(self, private, keyring), keyring_lock = function(keyring = NULL) b_file_keyring_lock(self, private, keyring), keyring_unlock = function(keyring = NULL, password = NULL) b_file_keyring_unlock(self, private, keyring, password), keyring_is_locked = function(keyring = NULL) b_file_keyring_is_locked(self, private, keyring), keyring_list = function() b_file_keyring_list(self, private), keyring_default = function() b_file_keyring_default(self, private), keyring_set_default = function(keyring) b_file_keyring_set_default(self, private, keyring), docs = function() { modifyList(super$docs(), list(. = paste0( "Store secrets in encrypted files.\n", private$keyring))) } ), private = list( keyring = NULL, keyring_create_direct = function(keyring = NULL, password = NULL, prompt = NULL) b__file_keyring_create_direct(self, private, keyring, password, prompt), keyring_autocreate = function(keyring = NULL) b__file_keyring_autocreate(self, private, keyring), keyring_file = function(keyring = NULL) b__file_keyring_file(self, private, keyring), keyring_read_file = function(keyring = NULL) b__file_keyring_read_file(self, private, keyring), keyring_write_file = function(keyring = NULL, nonce = NULL, items = NULL, key = NULL) b__file_keyring_write_file(self, private, keyring, nonce, items, key), get_keyring_pass = function(keyring = NULL) b__file_get_keyring_pass(self, private, keyring), set_keyring_pass = function(key = NULL, keyring = NULL) b__file_set_keyring_pass(self, private, key, keyring), unset_keyring_pass = function(keyring = NULL) b__file_unset_keyring_pass(self, private, keyring), is_set_keyring_pass = function(keyring = NULL) b__file_is_set_keyring_pass(self, private, keyring), update_cache = function(keyring = NULL, nonce = NULL, check = NULL, items = NULL) b__file_update_cache(self, private, keyring, nonce, check, items), get_cache = function(keyring = NULL) b__file_get_cache(self, private, keyring) ) ) b_file_init <- function(self, private, keyring) { self$keyring_set_default(keyring %||% "system") invisible(self) } b_file_get <- function(self, private, service, username, keyring) { private$keyring_autocreate(keyring) username <- username %||% getOption("keyring_username") if (self$keyring_is_locked(keyring)) self$keyring_unlock(keyring) cached <- private$get_cache(keyring) all_items <- cached$items all_services <- vapply(all_items, `[[`, character(1L), "service_name") item_matches <- all_services %in% service if (!is.null(username)) { all_users <- vapply(all_items, function(x) x$user_name %||% NA_character_, character(1L)) item_matches <- item_matches & all_users %in% username } if (sum(item_matches) < 1L) { b_file_error("cannot get secret", "The specified item could not be found in the keychain.") } vapply( lapply(all_items[item_matches], `[[`, "secret"), b_file_secret_decrypt, character(1L), cached$nonce, private$get_keyring_pass(keyring) ) } b_file_set <- function(self, private, service, username, keyring, prompt) { username <- username %||% getOption("keyring_username") keyring <- keyring %||% private$keyring file <- private$keyring_file(keyring) ex <- file.exists(file) prompt <- prompt %||% if (!ex && interactive()) { paste0( "Note: the specified keyring does not exist, you'll have to ", "create it in the next step. Key password: " ) } else { "Password: " } password <- get_pass(prompt) if (is.null(password)) stop("Aborted setting keyring key") private$keyring_autocreate() self$set_with_value(service, username, password, keyring) invisible(self) } b_file_set_with_value <- function(self, private, service, username, password, keyring) { private$keyring_autocreate(keyring) username <- username %||% getOption("keyring_username") if (self$keyring_is_locked(keyring)) self$keyring_unlock(keyring) keyring_file <- private$keyring_file(keyring) kr_env <- b_file_keyring_env(keyring_file) with_lock(keyring_file, { cached <- private$get_cache(keyring) all_items <- cached$items services <- vapply(all_items, `[[`, character(1L), "service_name") users <- vapply(all_items, function(x) x$user_name %||% NA_character_, character(1)) existing <- if (!is.null(username)) { services %in% service & users %in% username } else { services %in% service & is.na(users) } if (length(existing)) all_items <- all_items[!existing] new_item <- list( service_name = service, user_name = username, secret = b_file_secret_encrypt( password, cached$nonce, private$get_keyring_pass(keyring) ) ) items <- c(all_items, list(new_item)) private$keyring_write_file(keyring, items = items) kr_env$stamp <- file_stamp(keyring_file) }) kr_env <- b_file_keyring_env(keyring_file) kr_env$items <- items invisible(self) } b_file_delete <- function(self, private, service, username, keyring) { username <- username %||% getOption("keyring_username") if (self$keyring_is_locked(keyring)) self$keyring_unlock(keyring) keyring_file <- private$keyring_file(keyring) kr_env <- b_file_keyring_env(keyring_file) with_lock(keyring_file, { cached <- private$get_cache(keyring) all_items <- cached$items services <- vapply(all_items, `[[`, character(1L), "service_name") users <- vapply(all_items, function(x) x$user_name %||% NA_character_, character(1)) existing <- if (!is.null(username)) { services %in% service & users %in% username } else { services %in% service & is.na(users) } if (length(existing) == 0) return(invisible(self)) items <- all_items[!existing] private$keyring_write_file(keyring, items = items) kr_env$stamp <- file_stamp(keyring_file) }) kr_env$items <- items invisible(self) } b_file_list <- function(self, private, service, keyring) { private$keyring_autocreate(keyring) cached <- private$get_cache(keyring) all_items <- cached$items res <- data.frame( service = vapply(all_items, `[[`, character(1L), "service_name"), username = vapply(all_items, function(x) x$user_name %||% NA_character_, character(1)), stringsAsFactors = FALSE ) if (!is.null(service)) { res[res[["service"]] == service, ] } else { res } } b_file_keyring_create <- function(self, private, keyring, password) { private$keyring_create_direct(keyring, password) } b_file_keyring_delete <- function(self, private, keyring) { self$keyring_lock(keyring) kr_file <- private$keyring_file(keyring) unlink(kr_file, recursive = TRUE, force = TRUE) invisible(self) } b_file_keyring_lock <- function(self, private, keyring) { keyring <- keyring %||% private$keyring file <- private$keyring_file(keyring) if (!file.exists(file)) { stop("The '", keyring, "' keyring does not exists, create it first!") } private$unset_keyring_pass(keyring) invisible(self) } b_file_keyring_unlock <- function(self, private, keyring, password) { file <- private$keyring_file(keyring) if (!file.exists(file)) { stop("Keyring `", keyring, "` does not exist") } private$set_keyring_pass(password, keyring) if (self$keyring_is_locked(keyring)) { private$unset_keyring_pass(keyring) b_file_error( "cannot unlock keyring", "The supplied password does not work." ) } invisible(self) } b_file_keyring_is_locked <- function(self, private, keyring) { private$keyring_autocreate(keyring) keyring <- keyring %||% private$keyring file_name <- private$keyring_file(keyring) if (!file.exists(file_name)) { stop("Keyring `", keyring, "` does not exist") } if (!file.exists(file_name) || !private$is_set_keyring_pass(keyring)) { TRUE } else { tryCatch({ cached <- private$get_cache(keyring) b_file_secret_decrypt( cached$check, cached$nonce, private$get_keyring_pass(keyring) ) FALSE }, error = function(e) { if(conditionMessage(e) == "Failed to decrypt") TRUE else stop(e) } ) } } b_file_keyring_list <- function(self, private) { kr_dir <- dirname(private$keyring_file(NULL)) files <- dir(kr_dir, pattern = "\\.keyring$", full.names = TRUE) names <- sub("\\.keyring", "", basename(files)) num_secrets <- vapply( files, function(f) length(yaml::yaml.load_file(f)$items), integer(1)) locked <- vapply( names, function(k) self$keyring_is_locked(keyring = k), logical(1)) data.frame( keyring = unname(names), num_secrets = unname(num_secrets), locked = unname(locked), stringsAsFactors = FALSE ) } b_file_keyring_default <- function(self, private) { private$keyring } b_file_keyring_set_default <- function(self, private, keyring) { private$keyring <- keyring invisible(self) } b__file_keyring_create_direct <- function(self, private, keyring, password, prompt) { check_for_libsodium() keyring <- keyring %||% private$keyring prompt <- prompt %||% "Keyring password: " file_name <- private$keyring_file(keyring) if (file.exists(file_name)) { confirmation(paste("are you sure you want to overwrite", file_name, "(type `yes` if so)"), "yes") } password <- password %||% get_pass(prompt) if (is.null(password)) stop("Aborted creating keyring") dir.create(dirname(file_name), recursive = TRUE, showWarnings = FALSE) cat("", file = file_name) key <- private$set_keyring_pass(password, keyring) with_lock(file_name, private$keyring_write_file( keyring, nonce = sodium::random(24L), items = list(), key = key ) ) invisible(self) } b__file_keyring_file <- function(self, private, keyring) { keyring <- keyring %||% private$keyring keyring_dir <- getOption("keyring_file_dir", rappdirs::user_config_dir("r-keyring")) file.path(keyring_dir, paste0(keyring, ".keyring")) } b__file_keyring_read_file <- function(self, private, keyring) { check_for_libsodium() keyring <- keyring %||% private$keyring file_name <- private$keyring_file(keyring) with_lock(file_name, { stamp <- file_stamp(keyring) yml <- yaml::yaml.load_file(file_name) }) assert_that( is_list_with_names(yml, names = c("keyring_info", "items")), is_list_with_names( yml[["keyring_info"]], names = c("keyring_version", "nonce", "integrity_check") ) ) list( nonce = sodium::hex2bin(yml[["keyring_info"]][["nonce"]]), items = lapply(yml[["items"]], b__file_validate_item), check = yml[["keyring_info"]][["integrity_check"]], stamp = stamp ) } b__file_keyring_write_file <- function(self, private, keyring, nonce, items, key) { check_for_libsodium() keyring <- keyring %||% private$keyring file_name <- private$keyring_file(keyring) nonce <- nonce %||% private$get_cache(keyring)$nonce with_lock( file_name, yaml::write_yaml( list( keyring_info = list( keyring_version = as.character(getNamespaceVersion(.packageName)), nonce = sodium::bin2hex(nonce), integrity_check = b_file_secret_encrypt( paste(sample(letters, 22L, replace = TRUE), collapse = ""), nonce, key %||% private$get_keyring_pass(keyring) ) ), items = items %||% private$get_cache(keyring)$items ), file_name ) ) invisible(self) } b__file_get_keyring_pass <- function(self, private, keyring) { kr_env <- b_file_keyring_env(private$keyring_file(keyring)) if (is.null(kr_env$key)) { key <- private$set_keyring_pass(keyring = keyring) } else { key <- kr_env$key } assert_that(is.raw(key), length(key) > 0L) key } b__file_unset_keyring_pass <- function(self, private, keyring) { kr_env <- b_file_keyring_env(private$keyring_file(keyring)) kr_env$key <- NULL invisible(kr_env) } b__file_is_set_keyring_pass <- function(self, private, keyring) { !is.null(b_file_keyring_env(private$keyring_file(keyring))$key) } b__file_set_keyring_pass <- function(self, private, key, keyring) { check_for_libsodium() key <- key %||% get_pass("Keyring password: ") if (is.null(key)) stop("Aborted setting keyring password") assert_that(is_string(key)) key <- sodium::hash(charToRaw(key)) kr_env <- b_file_keyring_env(private$keyring_file(keyring)) kr_env$key <- key } b__file_update_cache <- function(self, private, keyring, nonce, check, items) { kr_env <- b_file_keyring_env(private$keyring_file(keyring)) kr <- private$keyring_read_file(keyring) nonce <- nonce %||% kr[["nonce"]] assert_that(is.raw(nonce), length(nonce) > 0L) kr_env$nonce <- nonce check <- check %||% kr[["check"]] assert_that(is.character(check), length(check) > 0L) kr_env$check <- check kr_env$items <- lapply(items %||% kr[["items"]], b__file_validate_item) kr_env$stamp <- kr$stamp kr_env } b__file_get_cache <- function(self, private, keyring) { keyring_file <- private$keyring_file(keyring) kr_env <- b_file_keyring_env(keyring_file) if (is.null(kr_env$nonce) || is.null(kr_env$stamp) || is.na(kr_env$stamp) || file_stamp(keyring_file) != kr_env$stamp) { kr_env <- private$update_cache(keyring) } assert_that(is.raw(kr_env$nonce), length(kr_env$nonce) > 0L) assert_that(is.character(kr_env$check), length(kr_env$check) > 0L) list( nonce = kr_env$nonce, items = lapply(kr_env$items, b__file_validate_item), check = kr_env$check) } b_file_secret_encrypt <- function(secret, nonce, key) { check_for_libsodium() res <- sodium::data_encrypt( charToRaw(secret), key, nonce ) b_file_split_string(sodium::bin2hex(res)) } b_file_secret_decrypt <- function(secret, nonce, key) { check_for_libsodium() rawToChar( sodium::data_decrypt( sodium::hex2bin(b_file_merge_string(secret)), key, nonce ) ) } b_file_keyring_env <- function(file_name) { env_name <- normalizePath(file_name, mustWork = TRUE) kr_env <- b_file_keyrings[[env_name]] if (is.null(kr_env)) { kr_env <- b_file_keyrings[[env_name]] <- new.env(parent = emptyenv()) } kr_env } b_file_error <- function(problem, reason = NULL) { if (is.null(reason)) { info <- problem } else { info <- paste0(problem, ": ", reason) } stop("keyring error (file-based keyring), ", info, call. = FALSE) } b__file_validate_item <- function(item) { assert_that( is_list_with_names(item, names = c("service_name", "user_name", "secret")), is_string(item[["service_name"]]), is_string_or_null(item[["user_name"]]), is_string_or_raw(item[["secret"]]) ) invisible(item) } b_file_split_string <- function(string, width = 78L) { assert_that(is_string(string)) paste( lapply( seq.int(ceiling(nchar(string) / width)) - 1L, function(x) substr(string, x * width + 1L, x * width + width) ), collapse = "\n" ) } b_file_merge_string <- function(string) { assert_that(is_string(string)) paste(strsplit(string, "\n")[[1L]], collapse = "") } b__file_keyring_autocreate <- function(self, private, keyring) { keyring <- keyring %||% private$keyring file <- private$keyring_file(keyring) if (!file.exists(file)) { if (is_interactive()) { private$keyring_create_direct( keyring, password = NULL, prompt = paste0( "The '", keyring, "' keyring does not exist, enter a keyring password to create it: " ) ) } else { stop("The '", keyring, "' keyring does not exists, create it first!") } } } with_lock <- function(file, expr) { timeout <- getOption("keyring_file_lock_timeout", 1000) lockfile <- paste0(file, ".lck") l <- filelock::lock(lockfile, timeout = timeout) if (is.null(l)) stop("Cannot lock keyring file") on.exit(filelock::unlock(l), add = TRUE) expr } check_for_libsodium <- function() { if ("sodium" %in% loadedNamespaces()) return() tryCatch( find.package("sodium"), error = function(err) { stop( "The 'file' keyring backend needs the sodium package, ", "please install it" ) } ) tryCatch( loadNamespace("sodium"), error = function(err) { if (Sys.info()[["sysname"]] == "Linux") { stop( call. = FALSE, "Cannot load the sodium package, please make sure that its ", "system libraries are installed.\n", "On Debian and Ubuntu systems you probably need the ", "'libsodium23' package.\n", "On Fedora, CentOS, RedHat and other RPM systems you need the ", "libsodium package. \n", "Error: ", conditionMessage(err) ) } else { stop( call. = FALSE, "Cannot load the sodium package, please make sure that its ", "system libraries are installed. \n", "Error: ", conditionMessage(err) ) } } ) }
expected <- eval(parse(text="NULL")); test(id=0, code={ argv <- eval(parse(text="list(NULL, NULL)")); do.call(`levels<-`, argv); }, o=expected);
ModulePopulationVariance3D <- function (modules) { m_arit = ArithmeticMean3D(modules) n = NumberOfElements3D(modules) return((sum((modules - m_arit)^2))/(n)) }
require('blockmodels') set.seed(12) npc <- 10 Q <- 2 n <- npc * Q Z<-diag(Q)%x%matrix(1,npc,1) P00<-matrix(runif(Q*Q),Q,Q) P10<-matrix(runif(Q*Q),Q,Q) P01<-matrix(runif(Q*Q),Q,Q) P11<-matrix(runif(Q*Q),Q,Q) SumP<-P00+P10+P01+P11 P00<-P00/SumP P01<-P01/SumP P10<-P10/SumP P11<-P11/SumP MU<-matrix(runif(n*n),n,n) M1<-1*(MU>Z%*%(P00+P01)%*%t(Z)) M2<-1*((MU>Z%*%P00%*%t(Z)) & (MU<Z%*%(P00+P01+P11)%*%t(Z))) my_model <- BM_bernoulli_multiplex("SBM",list(M1,M2) , plotting='', explore_min=2, explore_max=2, ncores=2, verbosity=0) my_model$estimate() which.max(my_model$ICL) npc <- 10 Q <- 2 n <- npc * Q Z<-diag(Q)%x%matrix(1,npc,1) P00<-matrix(runif(Q*Q),Q,Q) P10<-matrix(runif(Q*Q),Q,Q) P01<-matrix(runif(Q*Q),Q,Q) P11<-matrix(runif(Q*Q),Q,Q) SumP<-P00+P10+P01+P11 P00<-P00/SumP P01<-P01/SumP P10<-P10/SumP P11<-P11/SumP P00[lower.tri(P00)]<-t(P00)[lower.tri(P00)] P01[lower.tri(P01)]<-t(P01)[lower.tri(P01)] P10[lower.tri(P10)]<-t(P10)[lower.tri(P10)] P11[lower.tri(P11)]<-t(P11)[lower.tri(P11)] MU<-matrix(runif(n*n),n,n) MU[lower.tri(MU)]<-t(MU)[lower.tri(MU)] M1<-1*(MU>Z%*%(P00+P01)%*%t(Z)) M2<-1*((MU>Z%*%P00%*%t(Z)) & (MU<Z%*%(P00+P01+P11)%*%t(Z))) my_model <- BM_bernoulli_multiplex("SBM_sym",list(M1,M2) , plotting='', explore_min=2, explore_max=2, ncores=2, verbosity=0) my_model$estimate() which.max(my_model$ICL) npc <- c(20,10) Q <- c(1,2) n <- npc * Q Z1<-diag(Q[1])%x%matrix(1,npc[1],1) Z2<-diag(Q[2])%x%matrix(1,npc[2],1) P00<-matrix(runif(Q[1]*Q[2]),Q[1],Q[2]) P10<-matrix(runif(Q[1]*Q[2]),Q[1],Q[2]) P01<-matrix(runif(Q[1]*Q[2]),Q[1],Q[2]) P11<-matrix(runif(Q[1]*Q[2]),Q[1],Q[2]) SumP<-P00+P10+P01+P11 P00<-P00/SumP P01<-P01/SumP P10<-P10/SumP P11<-P11/SumP MU<-matrix(runif(n[1]*n[2]),n[1],n[2]) M1<-1*(MU>Z1%*%(P00+P01)%*%t(Z2)) M2<-1*((MU>Z1%*%P00%*%t(Z2)) & (MU<Z1%*%(P00+P01+P11)%*%t(Z2))) my_model <- BM_bernoulli_multiplex("LBM",list(M1,M2) , plotting='', explore_min=2, explore_max=2, ncores=2, verbosity=0) my_model$estimate() which.max(my_model$ICL)
NULL control_slider_pair <- function(.switchboard, ...) { switchboard_engine(.switchboard, constructor = control_slider_pair_construct(.switchboard, ...), updater = NULL, ...) } control_slider_pair_construct <- function(.switchboard, inject = c("", ""), minimum = c(0, 0), maximum = c(100, 100), label = c(" ", " "), size = 1, ...) { aCanvas <- tcltk::tkcanvas(.switchboard, width = 80 * size, height = 80 * size, background = switchboard.env$mainColors[2], borderwidth = 0, highlightthickness = 0) if(inject[1] != "") { if(as.integer(tcltk::tcl("info", "exists", inject[1])) == 1) tcltk::tcl("unset", inject[1]) tcltk::.Tcl(paste("set", inject[1], mget(inject[1], envir = parent.frame(n = 3), ifnotfound = NA))) tcltk::tkbind(inject[1], "<Destroy>", function(...) {tcltk::tcl("unset", inject[1])}) injectorSlider1 <- tcltk::ttkscale(aCanvas, from = minimum[1], to = maximum[1], variable = inject[1], value = tcltk::tclvalue(inject[1]), command = function(...){assign(inject[1], as.numeric(tcltk::tclvalue(inject[1])), envir = parent.frame(n = 5));}) tcltk::tkcreate(aCanvas, "window", 0, 10 * size - 5, width = 75 * size, anchor = "nw", window = injectorSlider1) } if(inject[2] != "") { if(as.integer(tcltk::tcl("info", "exists", inject[2] )) == 1) tcltk::tcl("unset", inject[2] ) tcltk::.Tcl(paste("set", inject[2], mget(inject[2], envir = parent.frame(n = 3), ifnotfound = NA))) tcltk::tkbind(inject[2], "<Destroy>", function(...) {tcltk::tcl("unset", inject[2])}) injectorSlider2 <- tcltk::ttkscale(aCanvas, from = minimum[2], to = maximum[2], variable = inject[2] , value = tcltk::tclvalue(inject[2]), command = function(...){assign(inject[2] , as.numeric(tcltk::tclvalue(inject[2])), envir = parent.frame(n = 5));}) tcltk::tkcreate(aCanvas, "window", 0, 52 * size - 5, width = 75 * size, anchor = "nw", window = injectorSlider2) } tcltk::tkcreate(aCanvas, "text", 37.5 * size, 10 * size + 25, text = label[1], anchor = "center", font = paste(switchboard.env$font, floor(9 / 1.2)), fill = switchboard.env$mainColors[4]) tcltk::tkcreate(aCanvas, "text", 37.5 * size, 52 * size + 25, text = label[2], anchor = "center", font = paste(switchboard.env$font, floor(9 / 1.2)), fill = switchboard.env$mainColors[4]) return(aCanvas) }
trig_asn <- function(x, ...) { 2 * asin(sqrt(x), ...) } trig_atahn <- function(x, ...) { atanh(x, ...) } dist_logit <- function(x, ...) { assert_uni_ts(x) out <- dist(x, "logis", ...) with_attrs(out, x) } dist_probit <- function(x, ...) { assert_uni_ts(x) out <- dist(x, "norm", ...) with_attrs(out, x) } dist <- function(x, dist, ...) { qfun <- match.fun(paste0("q", dist)) qfun(x, ...) } dist_inv <- function(x, dist, ...) { pfun <- match.fun(paste0("p", dist)) pfun(x, ...) }
bekk_fit <- function(spec, data, QML_t_ratios = FALSE, max_iter = 50, crit = 1e-9){ if (!inherits(spec, 'bekkSpec')) { stop('Please provide and object of class "bekkSpec" for spec.') } if (any(is.na(data))) { stop("\nNAs in data.\n") } if (ncol(data) < 2) { stop("The data matrix should contain at least two variables.") } if (is.null(colnames(data))) { colnames(data) <- paste("y", 1:ncol(data), sep = "") } UseMethod('bekk_fit') } bekk_fit.bekk <- function(spec, data, QML_t_ratios = FALSE, max_iter = 50, crit = 1e-9) { init_values <- spec$init_values N <- ncol(data) if(!is.numeric(init_values)) { if (is.null(init_values)) { theta <- gridSearch_BEKK(data) theta <- theta[[1]] } else if (init_values == 'random') { cat('Generating starting values \n') theta <- random_grid_search_BEKK(data) theta <- theta[[1]] } else if (init_values == 'simple') { uncond_var <- crossprod(data)/nrow(data) A <- matrix(0, ncol = N, nrow = N) G <- matrix(0, ncol = N, nrow = N) C <- matrix(0, ncol = N, nrow = N) diag(A) <- 0.3 diag(G) <- 0.92 diag(C) <- 0.05*diag(uncond_var) for (i in 1:N){ for (j in seq(i,N)){ cij <- uncond_var[i, j]/sqrt(uncond_var[i, i]*uncond_var[j, j]) C[i,j] <- cij*sqrt(C[i, i]*C[j, j]) C[j,i] <- C[i, j] } } C = t(chol(C)) C0 = C[,1] if (N > 2) { for (i in 2:(N-1)){ C0 = c(C0, C[i:N, i]) } } C0 = c(C0, C[N, N]) theta = c(C0, c(A), c(G)) } } else { if(length(init_values) != 2 * N^2 + N * (N + 1)/2) { stop('Number of initial parameter does not match dimension of data.') } theta <- init_values } theta <- matrix(theta, ncol =1) params <- bhh_bekk(data, theta, max_iter, crit) if (QML_t_ratios == TRUE) { tratios <- QML_t_ratios(params$theta, data) tratios_mat <- coef_mat(abs(tratios), N) } else { tratios_mat <- coef_mat(abs(params$t_val), N) } param_mat <- coef_mat(params$theta, N) var_process <- sigma_bekk(data, t(param_mat$c0), param_mat$a, param_mat$g) sigma_t <- as.data.frame(var_process$sigma_t) colnames(sigma_t) <- rep(1, N^2) k <- 1 k2 <- 1 for (i in 1:N) { for (j in 1:N) { if (i == j) { colnames(sigma_t)[k2] <- paste('Conditional standard deviation of \n', colnames(data)[k]) k <- k + 1 k2 <- k2 +1 } else { colnames(sigma_t)[k2] <- paste('Conditional correlation of \n', colnames(data)[i], ' and ', colnames(data)[j]) k2 <- k2 +1 } } } for (i in 1:nrow(sigma_t)) { tm <- matrix(unlist(sigma_t[i,]), N, N, byrow = T) tm2 <- sqrt(solve(diag(diag(tm))))%*%tm%*%sqrt(solve(diag(diag(tm)))) diag(tm2) <- sqrt(diag(tm)) sigma_t[i,] <- c(tm2) } elim <- elimination_mat(N) sigma_t <- sigma_t[, which(colSums(elim) == 1)] if (inherits(data, "ts")) { sigma_t <- ts(sigma_t, start = time(data)[1], frequency = frequency(data)) } else if(inherits(data, "xts") || inherits(data, "zoo") ){ sigma_t <- xts(sigma_t, order.by = time(data)) } BEKK_valid <- valid_bekk(param_mat$c0, param_mat$a, param_mat$g) params$likelihood_iter <- params$likelihood_iter[params$likelihood_iter != 0] result <- list(C0 = param_mat$c0, A = param_mat$a, G = param_mat$g, C0_t = tratios_mat$c0, A_t = tratios_mat$a, G_t = tratios_mat$g, theta = params$theta, log_likelihood = params$likelihood, BEKK_valid = BEKK_valid, sigma_t = sigma_t, H_t = var_process$sigma_t, e_t = var_process$e_t, Second_moments_of_residuals = cov(var_process$e_t), iter = params$iter, likelihood_iter = params$likelihood_iter, asymmetric = FALSE, data = data) class(result) <- c('bekkFit', 'bekk') return(result) } bekk_fit.bekka <- function(spec, data, QML_t_ratios = FALSE, max_iter = 50, crit = 1e-9) { init_values <- spec$init_values N <- ncol(data) if(is.null(spec$model$signs)){ spec$model$signs = matrix(rep(-1, N), ncol = 1) } if(length(spec$model$signs) != N){ stop('Length of "signs" does not match dimension of data.') } if(!is.numeric(init_values)) { if (is.null(init_values)) { theta <- gridSearch_asymmetricBEKK(data, spec$model$signs) theta <- theta[[1]] } else if (init_values == 'random') { cat('Generating starting values \n') theta = random_grid_search_asymmetric_BEKK(data, spec$model$signs)[[1]] } else if (init_values == 'simple') { uncond_var <- crossprod(data)/nrow(data) A <- matrix(0, ncol = N, nrow = N) B <- matrix(0, ncol = N, nrow = N) G <- matrix(0, ncol = N, nrow = N) C <- matrix(0, ncol = N, nrow = N) diag(A) <- 0.25 diag(B) <- 0.05 diag(G) <- 0.92 diag(C) <- 0.05*diag(uncond_var) for (i in 1:N){ for (j in seq(i,N)){ cij <- uncond_var[i, j]/sqrt(uncond_var[i, i]*uncond_var[j, j]) C[i,j] <- cij*sqrt(C[i, i]*C[j, j]) C[j,i] <- C[i, j] } } C = t(chol(C)) C0 = C[,1] if (N > 2) { for (i in 2:(N-1)){ C0 = c(C0, C[i:N, i]) } } C0 = c(C0, C[N, N]) theta = c(C0, c(A), c(G)) } } else { if(length(init_values) != 3 * N^2 + N * (N + 1)/2) { stop('Number of initial parameter does not match dimension of data.') } theta <- init_values } theta <- matrix(theta, ncol =1) params <- bhh_asymm_bekk(data, theta, max_iter, crit, spec$model$signs) if (QML_t_ratios == TRUE) { tratios <- QML_t_ratios_asymm(params$theta, data, spec$model$signs) tratios_mat <- coef_mat_asymm(abs(tratios), N) } else { tratios_mat <- coef_mat_asymm(abs(params$t_val), N) } param_mat <- coef_mat_asymm(params$theta, N) var_process <- sigma_bekk_asymm(data, t(param_mat$c0), param_mat$a, param_mat$b, param_mat$g, spec$model$signs) sigma_t <- as.data.frame(var_process$sigma_t) colnames(sigma_t) <- rep(1, N^2) k <- 1 k2 <- 1 for (i in 1:N) { for (j in 1:N) { if (i == j) { colnames(sigma_t)[k2] <- paste('Conditional SD of', colnames(data)[k]) k <- k + 1 k2 <- k2 +1 } else { colnames(sigma_t)[k2] <- paste('Conditional correlation of', colnames(data)[i], ' and ', colnames(data)[j]) k2 <- k2 +1 } } } for (i in 1:nrow(sigma_t)) { tm <- matrix(unlist(sigma_t[i,]), N, N, byrow = T) tm2 <- sqrt(solve(diag(diag(tm))))%*%tm%*%sqrt(solve(diag(diag(tm)))) diag(tm2) <- sqrt(diag(tm)) sigma_t[i,] <- c(tm2) } elim <- elimination_mat(N) sigma_t <- sigma_t[, which(colSums(elim) == 1)] if (inherits(data, "ts")) { sigma_t <- ts(sigma_t, start = time(data)[1], frequency = frequency(data)) } else if(inherits(data, "xts") || inherits(data, "zoo") ){ sigma_t <- xts(sigma_t, order.by = time(data)) } BEKK_valid <- valid_asymm_bekk(param_mat$c0, param_mat$a, param_mat$b, param_mat$g, data, spec$model$signs) expected_signs=expected_indicator_value(data,spec$model$signs) params$likelihood_iter <- params$likelihood_iter[params$likelihood_iter != 0] result <- list(C0 = param_mat$c0, A = param_mat$a, B = param_mat$b, G = param_mat$g, C0_t = tratios_mat$c0, A_t = tratios_mat$a, B_t = tratios_mat$b, G_t = tratios_mat$g, theta = params$theta, signs = spec$model$signs, log_likelihood = params$likelihood, BEKK_valid = BEKK_valid, sigma_t = sigma_t, H_t = var_process$sigma_t, e_t = var_process$e_t, Second_moments_of_residuals = cov(var_process$e_t), iter = params$iter, likelihood_iter = params$likelihood_iter, asymmetric = TRUE, expected_signs = expected_signs, data = data) class(result) <- c('bekkFit', 'bekka') return(result) }
devmode <- function( devmode = getOption("shiny.devmode", TRUE), verbose = getOption("shiny.devmode.verbose", TRUE) ) { options( shiny.devmode = devmode, shiny.devmode.verbose = verbose ) } in_devmode <- function() { isTRUE(getOption("shiny.devmode", FALSE)) && !identical(Sys.getenv("TESTTHAT"), "true") } with_devmode <- function( devmode, code, verbose = getOption("shiny.devmode.verbose", TRUE) ) { withr::with_options( list( shiny.devmode = devmode, shiny.devmode.verbose = verbose ), code ) } devmode_inform <- function( message, .frequency = "regularly", .frequency_id = message, .file = stderr(), ... ) { if (!( in_devmode() && isTRUE(getOption("shiny.devmode.verbose", TRUE)) )) { return() } if (is.null(message)) { return() } rlang::inform( message = paste0("shiny devmode - ", message), .frequency = .frequency, .frequency_id = .frequency_id, .file = .file, ... ) } registered_devmode_options <- Map$new() register_devmode_option <- function( name, devmode_message = NULL, devmode_default = NULL ) { if (!is.null(devmode_message)) { stopifnot(length(devmode_message) == 1 && is.character(devmode_message)) } registered_devmode_options$set( name, list(devmode_default = devmode_default, devmode_message = devmode_message) ) } get_devmode_option <- function( name, default = NULL, devmode_default = missing_arg(), devmode_message = missing_arg() ) { getOption( name, local({ if (!in_devmode()) { return(default) } info <- registered_devmode_options$get(name) if (is.null(info)) { rlang::warn( message = paste0( "`get_devmode_option(name)` could not find `name = \"", name, "\"`. ", "Returning `default` value" ) ) return(default) } devmode_inform( maybe_missing( devmode_message, default = info$devmode_message ) ) maybe_missing( devmode_default, default = info$devmode_default ) }) ) } register_devmode_option( "shiny.autoreload", "Turning on shiny autoreload. To disable, call `options(shiny.autoreload = FALSE)`", TRUE ) register_devmode_option( "shiny.minified", "Using full shiny javascript file. To use the minified version, call `options(shiny.minified = TRUE)`", FALSE ) register_devmode_option( "shiny.fullstacktrace", "Turning on full stack trace. To disable, call `options(shiny.fullstacktrace = FALSE)`", TRUE )
glm.summary <- function (in.object, alpha = 0.05){ lo <- in.object$coefficient - qnorm(1-alpha/2) * sqrt(diag(summary(in.object)$cov.unscaled)) hi <- in.object$coefficient + qnorm(1-alpha/2) * sqrt(diag(summary(in.object)$cov.unscaled)) out.mat <- round(cbind(in.object$coefficient, sqrt(diag(glm.vc(in.object))), lo, hi),5) dimnames(out.mat)[[2]] <- c("Coefficient","Std. Error", paste(1-alpha,"CI Lower"),paste(1-alpha,"CI Upper")) out.mat }
var_dif_fis <- function(n, r, rho) { 2/(n-3) - 2*((r*(-2*rho^2+1)-0.5*rho^2*(-r^2+1-2*rho^2))/(1-rho^2)^2/(n-3)) }
build_query_string <- function(country, povline, year, aggregate = FALSE, fill_gaps = FALSE, coverage = "all", ppp = NULL, format = "json") { check_build_query_string_inputs(country, povline, year, aggregate, fill_gaps, coverage, ppp ) i <- seq_along(country) - 1 if (aggregate == TRUE) { fill_gaps <- TRUE } country <- assign_country(country) country <- assign_coverage(country = country, coverage = coverage) if (fill_gaps == TRUE) { year_str <- "YearSelected=" } else { year_str <- "SurveyYears=" } year <- paste0(year_str, paste(year, collapse = ",")) povline <- paste0("PovertyLine=", povline) country <- paste0("Countries=", paste(country, collapse = ",")) format <- paste0("format=", format) display <- if (aggregate == TRUE) { display <- paste0("display=Regional") } else { display <- paste0("display=C") } if (!is.null(ppp)) { ppp <- purrr::map2_chr(i, ppp, function(x, y) {paste0("PPP", x, "=", y)}) ppp <- paste(ppp, collapse = "&") out <- paste(year, country, povline, ppp, display, format, collapse = "&") out <- stringr::str_replace_all(out, pattern = " ", replacement = "&") } else { out <- paste(year, country, povline, display, format, collapse = "&") out <- stringr::str_replace_all(out, pattern = " ", replacement = "&") } return(out) } check_build_query_string_inputs <- function(country, povline, year, aggregate, fill_gaps, coverage, ppp) { accepted_coverage <- c(names(coverage_lkup), "all") assertthat::assert_that(length(country) > 0, msg = "Please submit at least ONE country") assertthat::assert_that(length(year) > 0, msg = "Please submit at least ONE year") assertthat::assert_that(length(povline) > 0, msg = "Please submit ONE poverty line") assertthat::assert_that(length(povline) == 1, msg = "Please submit only one povline, for instance: povline = 1.9") assertthat::assert_that(coverage %in% accepted_coverage, msg = paste0("The 'coverage' argument only accepts one of the following values:\n", accepted_coverage)) assertthat::assert_that(length(coverage) == 1, msg = "Please submit only ONE coverage") assertthat::assert_that(is.null(ppp) | length(ppp) == length(country), msg = "When using custom ppp, please ensure you submit one ppp per country") assertthat::assert_that(is.null(ppp) | coverage != "all", msg = "Custom ppp are not allowed with `coverage` = `all`") if (aggregate == TRUE & fill_gaps == FALSE) { message("You specified `aggregate = TRUE`. Aggregation is only possible over a common reference year: The `fill_gaps` parameter will be forced to `TRUE`")} }
library(ranger) library(survival) context("ranger_treeInfo") rf.class.formula <- ranger(Species ~ ., iris, num.trees = 5) rf.class.first <- ranger(dependent.variable.name = "Species", data = iris[, c(5, 1:4)], num.trees = 5) rf.class.mid <- ranger(dependent.variable.name = "Species", data = iris[, c(1:2, 5, 3:4)], num.trees = 5) rf.class.last <- ranger(dependent.variable.name = "Species", data = iris, num.trees = 5) ti.class.formula <- treeInfo(rf.class.formula) ti.class.first <- treeInfo(rf.class.first) ti.class.mid <- treeInfo(rf.class.mid) ti.class.last <- treeInfo(rf.class.last) test_that("Terminal nodes have only prediction, non-terminal nodes all others, classification formula", { expect_true(all(is.na(ti.class.formula[ti.class.formula$terminal, 2:6]))) expect_true(all(!is.na(ti.class.formula[ti.class.formula$terminal, c(1, 7:8)]))) expect_true(all(!is.na(ti.class.formula[!ti.class.formula$terminal, -8]))) expect_true(all(is.na(ti.class.formula[!ti.class.formula$terminal, 8]))) }) test_that("Terminal nodes have only prediction, non-terminal nodes all others, classification depvarname first", { expect_true(all(is.na(ti.class.first[ti.class.first$terminal, 2:6]))) expect_true(all(!is.na(ti.class.first[ti.class.first$terminal, c(1, 7:8)]))) expect_true(all(!is.na(ti.class.first[!ti.class.first$terminal, -8]))) expect_true(all(is.na(ti.class.first[!ti.class.first$terminal, 8]))) }) test_that("Terminal nodes have only prediction, non-terminal nodes all others, classification depvarname mid", { expect_true(all(is.na(ti.class.mid[ti.class.mid$terminal, 2:6]))) expect_true(all(!is.na(ti.class.mid[ti.class.mid$terminal, c(1, 7:8)]))) expect_true(all(!is.na(ti.class.mid[!ti.class.mid$terminal, -8]))) expect_true(all(is.na(ti.class.mid[!ti.class.mid$terminal, 8]))) }) test_that("Terminal nodes have only prediction, non-terminal nodes all others, classification depvarname last", { expect_true(all(is.na(ti.class.last[ti.class.last$terminal, 2:6]))) expect_true(all(!is.na(ti.class.last[ti.class.last$terminal, c(1, 7:8)]))) expect_true(all(!is.na(ti.class.last[!ti.class.last$terminal, -8]))) expect_true(all(is.na(ti.class.last[!ti.class.last$terminal, 8]))) }) test_that("Names in treeInfo match, classification", { varnames <- colnames(iris)[1:4] expect_true(all(is.na(ti.class.formula$splitvarName) | ti.class.formula$splitvarName %in% varnames)) expect_true(all(is.na(ti.class.first$splitvarName) | ti.class.first$splitvarName %in% varnames)) expect_true(all(is.na(ti.class.mid$splitvarName) | ti.class.mid$splitvarName %in% varnames)) expect_true(all(is.na(ti.class.last$splitvarName) | ti.class.last$splitvarName %in% varnames)) }) test_that("Prediction for classification is factor with correct levels", { expect_is(ti.class.formula$prediction, "factor") expect_equal(levels(ti.class.formula$prediction), levels(iris$Species)) }) test_that("Prediction for matrix classification is integer with correct values", { rf <- ranger(dependent.variable.name = "Species", data = data.matrix(iris), num.trees = 5, classification = TRUE) ti <- treeInfo(rf, 1) expect_is(ti$prediction, "numeric") expect_equal(sort(unique(ti$prediction)), 1:3) }) n <- 20 dat <- data.frame(y = rnorm(n), replicate(2, runif(n)), replicate(2, rbinom(n, size = 1, prob = .5))) rf.regr.formula <- ranger(y ~ ., dat, num.trees = 5) rf.regr.first <- ranger(dependent.variable.name = "y", data = dat, num.trees = 5) rf.regr.mid <- ranger(dependent.variable.name = "y", data = dat[, c(2:3, 1, 4:5)], num.trees = 5) rf.regr.last <- ranger(dependent.variable.name = "y", data = dat[, c(2:5, 1)], num.trees = 5) ti.regr.formula <- treeInfo(rf.regr.formula) ti.regr.first <- treeInfo(rf.regr.first) ti.regr.mid <- treeInfo(rf.regr.mid) ti.regr.last <- treeInfo(rf.regr.last) test_that("Terminal nodes have only prediction, non-terminal nodes all others, regression formula", { expect_true(all(is.na(ti.regr.formula[ti.regr.formula$terminal, 2:6]))) expect_true(all(!is.na(ti.regr.formula[ti.regr.formula$terminal, c(1, 7:8)]))) expect_true(all(!is.na(ti.regr.formula[!ti.regr.formula$terminal, -8]))) expect_true(all(is.na(ti.regr.formula[!ti.regr.formula$terminal, 8]))) }) test_that("Terminal nodes have only prediction, non-terminal nodes all others, regression depvarname first", { expect_true(all(is.na(ti.regr.first[ti.regr.first$terminal, 2:6]))) expect_true(all(!is.na(ti.regr.first[ti.regr.first$terminal, c(1, 7:8)]))) expect_true(all(!is.na(ti.regr.first[!ti.regr.first$terminal, -8]))) expect_true(all(is.na(ti.regr.first[!ti.regr.first$terminal, 8]))) }) test_that("Terminal nodes have only prediction, non-terminal nodes all others, regression depvarname mid", { expect_true(all(is.na(ti.regr.mid[ti.regr.mid$terminal, 2:6]))) expect_true(all(!is.na(ti.regr.mid[ti.regr.mid$terminal, c(1, 7:8)]))) expect_true(all(!is.na(ti.regr.mid[!ti.regr.mid$terminal, -8]))) expect_true(all(is.na(ti.regr.mid[!ti.regr.mid$terminal, 8]))) }) test_that("Terminal nodes have only prediction, non-terminal nodes all others, regression depvarname last", { expect_true(all(is.na(ti.regr.last[ti.regr.last$terminal, 2:6]))) expect_true(all(!is.na(ti.regr.last[ti.regr.last$terminal, c(1, 7:8)]))) expect_true(all(!is.na(ti.regr.last[!ti.regr.last$terminal, -8]))) expect_true(all(is.na(ti.regr.last[!ti.regr.last$terminal, 8]))) }) test_that("Names in treeInfo match, regression", { varnames <- c("X1", "X2", "X1.1", "X2.1") expect_true(all(is.na(ti.regr.formula$splitvarName) | ti.regr.formula$splitvarName %in% varnames)) expect_true(all(is.na(ti.regr.first$splitvarName) | ti.regr.first$splitvarName %in% varnames)) expect_true(all(is.na(ti.regr.mid$splitvarName) | ti.regr.mid$splitvarName %in% varnames)) expect_true(all(is.na(ti.regr.last$splitvarName) | ti.regr.last$splitvarName %in% varnames)) }) test_that("Prediction for regression is numeric in correct range", { expect_is(ti.regr.formula$prediction, "numeric") expect_true(all(is.na(ti.regr.formula$prediction) | ti.regr.formula$prediction >= min(dat$y))) expect_true(all(is.na(ti.regr.formula$prediction) | ti.regr.formula$prediction <= max(dat$y))) }) rf.prob.formula <- ranger(Species ~ ., iris, num.trees = 5, probability = TRUE) rf.prob.first <- ranger(dependent.variable.name = "Species", data = iris[, c(5, 1:4)], num.trees = 5, probability = TRUE) rf.prob.mid <- ranger(dependent.variable.name = "Species", data = iris[, c(1:2, 5, 3:4)], num.trees = 5, probability = TRUE) rf.prob.last <- ranger(dependent.variable.name = "Species", data = iris, num.trees = 5, probability = TRUE) ti.prob.formula <- treeInfo(rf.prob.formula) ti.prob.first <- treeInfo(rf.prob.first) ti.prob.mid <- treeInfo(rf.prob.mid) ti.prob.last <- treeInfo(rf.prob.last) test_that("Terminal nodes have only prediction, non-terminal nodes all others, probability formula", { expect_true(all(is.na(ti.prob.formula[ti.prob.formula$terminal, 2:6]))) expect_true(all(!is.na(ti.prob.formula[ti.prob.formula$terminal, c(1, 7:10)]))) expect_true(all(!is.na(ti.prob.formula[!ti.prob.formula$terminal, c(-8, -9, -10)]))) expect_true(all(is.na(ti.prob.formula[!ti.prob.formula$terminal, 8:10]))) }) test_that("Terminal nodes have only prediction, non-terminal nodes all others, probability depvarname first", { expect_true(all(is.na(ti.prob.first[ti.prob.first$terminal, 2:6]))) expect_true(all(!is.na(ti.prob.first[ti.prob.first$terminal, c(1, 7:8)]))) expect_true(all(!is.na(ti.prob.first[!ti.prob.first$terminal, c(-8, -9, -10)]))) expect_true(all(is.na(ti.prob.first[!ti.prob.first$terminal, 8:10]))) }) test_that("Terminal nodes have only prediction, non-terminal nodes all others, probability depvarname mid", { expect_true(all(is.na(ti.prob.mid[ti.prob.mid$terminal, 2:6]))) expect_true(all(!is.na(ti.prob.mid[ti.prob.mid$terminal, c(1, 7:8)]))) expect_true(all(!is.na(ti.prob.mid[!ti.prob.mid$terminal, c(-8, -9, -10)]))) expect_true(all(is.na(ti.prob.mid[!ti.prob.mid$terminal, 8:10]))) }) test_that("Terminal nodes have only prediction, non-terminal nodes all others, probability depvarname last", { expect_true(all(is.na(ti.prob.last[ti.prob.last$terminal, 2:6]))) expect_true(all(!is.na(ti.prob.last[ti.prob.last$terminal, c(1, 7:8)]))) expect_true(all(!is.na(ti.prob.last[!ti.prob.last$terminal, c(-8, -9, -10)]))) expect_true(all(is.na(ti.prob.last[!ti.prob.last$terminal, 8:10]))) }) test_that("Names in treeInfo match, probability", { varnames <- colnames(iris)[1:4] expect_true(all(is.na(ti.prob.formula$splitvarName) | ti.prob.formula$splitvarName %in% varnames)) expect_true(all(is.na(ti.prob.first$splitvarName) | ti.prob.first$splitvarName %in% varnames)) expect_true(all(is.na(ti.prob.mid$splitvarName) | ti.prob.mid$splitvarName %in% varnames)) expect_true(all(is.na(ti.prob.last$splitvarName) | ti.prob.last$splitvarName %in% varnames)) }) test_that("Prediction for probability is one probability per class, sum to 1", { expect_equal(ncol(ti.prob.formula), 10) expect_is(ti.prob.formula$pred.setosa, "numeric") expect_true(all(!ti.prob.formula$terminal | rowSums(ti.prob.formula[, 8:10]) == 1)) }) test_that("Prediction for probability has correct factor levels", { dat <- iris[c(101:150, 1:100), ] rf <- ranger(dependent.variable.name = "Species", data = dat, num.trees = 5, probability = TRUE) pred_rf <- predict(rf, dat, num.trees = 1)$predictions ti <- treeInfo(rf) terminal_nodes <- predict(rf, dat, type = "terminalNodes")$predictions[, 1] pred_ti <- as.matrix(ti[terminal_nodes + 1, grep("pred", colnames(ti))]) colnames(pred_ti) <- gsub("pred\\.", "", colnames(pred_ti)) rownames(pred_ti) <- NULL expect_equal(pred_rf, pred_ti) }) rf.surv.formula <- ranger(Surv(time, status) ~ ., veteran, num.trees = 5) rf.surv.first <- ranger(dependent.variable.name = "time", status.variable.name = "status", data = veteran[, c(3:4, 1:2, 5:8)], num.trees = 5) rf.surv.mid <- ranger(dependent.variable.name = "time", status.variable.name = "status", data = veteran, num.trees = 5) rf.surv.last <- ranger(dependent.variable.name = "time", status.variable.name = "status", data = veteran[, c(2, 1, 5:8, 3:4)], num.trees = 5) ti.surv.formula <- treeInfo(rf.surv.formula) ti.surv.first <- treeInfo(rf.surv.first) ti.surv.mid <- treeInfo(rf.surv.mid) ti.surv.last <- treeInfo(rf.surv.last) test_that("Terminal nodes have only nodeID, non-terminal nodes all, survival formula", { expect_true(all(is.na(ti.surv.formula[ti.surv.formula$terminal, 2:6]))) expect_true(all(!is.na(ti.surv.formula[ti.surv.formula$terminal, c(1, 7)]))) expect_true(all(!is.na(ti.surv.formula[!ti.surv.formula$terminal, ]))) }) test_that("Terminal nodes have only prediction, non-terminal nodes all others, survival depvarname first", { expect_true(all(is.na(ti.surv.first[ti.surv.first$terminal, 2:6]))) expect_true(all(!is.na(ti.surv.first[ti.surv.first$terminal, c(1, 7)]))) expect_true(all(!is.na(ti.surv.first[!ti.surv.first$terminal, ]))) }) test_that("Terminal nodes have only prediction, non-terminal nodes all others, survival depvarname mid", { expect_true(all(is.na(ti.surv.mid[ti.surv.mid$terminal, 2:6]))) expect_true(all(!is.na(ti.surv.mid[ti.surv.mid$terminal, c(1, 7)]))) expect_true(all(!is.na(ti.surv.mid[!ti.surv.mid$terminal, ]))) }) test_that("Terminal nodes have only prediction, non-terminal nodes all others, survival depvarname last", { expect_true(all(is.na(ti.surv.last[ti.surv.last$terminal, 2:6]))) expect_true(all(!is.na(ti.surv.last[ti.surv.last$terminal, c(1, 7)]))) expect_true(all(!is.na(ti.surv.last[!ti.surv.last$terminal, ]))) }) test_that("Names in treeInfo match, survival", { varnames <- colnames(veteran)[c(1:2, 5:8)] expect_true(all(is.na(ti.surv.formula$splitvarName) | ti.surv.formula$splitvarName %in% varnames)) expect_true(all(is.na(ti.surv.first$splitvarName) | ti.surv.first$splitvarName %in% varnames)) expect_true(all(is.na(ti.surv.mid$splitvarName) | ti.surv.mid$splitvarName %in% varnames)) expect_true(all(is.na(ti.surv.last$splitvarName) | ti.surv.last$splitvarName %in% varnames)) }) test_that("No prediction for Survival", { expect_equal(ncol(ti.surv.formula), 7) }) test_that("Error if no saved forest", { expect_error(treeInfo(ranger(Species ~ ., iris, write.forest = FALSE)), "Error\\: No saved forest in ranger object\\. Please set write.forest to TRUE when calling ranger\\.") }) test_that("Spitting value is comma separated list for partition splitting", { n <- 50 dat <- data.frame(x = sample(c("A", "B", "C", "D", "E"), n, replace = TRUE), y = rbinom(n, 1, 0.5), stringsAsFactors = FALSE) rf.partition <- ranger(y ~ ., dat, num.trees = 5, respect.unordered.factors = "partition") ti.partition <- treeInfo(rf.partition) expect_is(ti.partition$splitval, "character") expect_true(all(is.na(ti.partition$splitval) | grepl("^\\d+(?:,\\d+)*$", ti.partition$splitval))) }) test_that("Spitting value is numeric for order splitting", { set.seed(100) rf.order <- ranger(Sepal.Length ~ ., iris, num.trees = 5, respect.unordered.factors = "order") ti.order <- treeInfo(rf.order) expect_is(ti.order$splitval[!ti.order$terminal & ti.order$splitvarName == "Species"], "numeric") }) test_that("treeInfo works for 31 unordered factor levels but not for 32", { n <- 31 dt <- data.frame(x = factor(1:n, ordered = FALSE), y = rbinom(n, 1, 0.5)) rf <- ranger(y ~ ., data = dt, num.trees = 10, splitrule = "extratrees") expect_silent(treeInfo(rf)) n <- 32 dt <- data.frame(x = factor(1:n, ordered = FALSE), y = rbinom(n, 1, 0.5)) rf <- ranger(y ~ ., data = dt, num.trees = 10, splitrule = "extratrees") expect_warning(treeInfo(rf), "Unordered splitting levels can only be shown for up to 31 levels.") })
context("lsat_scenes") test_that("lsat_scenes, n_max parameter usage", { skip_on_cran() a <- lsat_scenes(n_max = 3) expect_is(a, "data.frame") expect_is(a, "tbl_df") expect_is(a$entityId, "character") expect_is(a$acquisitionDate, "POSIXct") expect_equal(NROW(a), 3) }) test_that("lsat_scenes, skip parameter usage", { expect_warning(lsat_scenes(n_max = 3, skip = 3), "you probably don't want to use 'skip'") })
reintegrate <- function(ag, to, time_var = "Timestamp", direction = c("forwards", "backwards"), verbose = FALSE) { direction <- try( match.arg(direction, c("forwards", "backwards", "error")), silent = TRUE) if (class(direction) == "try-error") { warning(paste("Argument `direction` must be exactly one of", "\"forwards\" or \"backwards\". Defaulting to forwards.")) direction <- "forwards" } start_epoch <- unique(diff.POSIXt(ag[ ,time_var])) if (start_epoch == to) { if (verbose) cat( "\nReturning original data --", "already in desired epoch length" ) return(ag) } stopifnot(length(start_epoch) == 1, (to / start_epoch) %% 1 == 0) block_size <- to / start_epoch ag <- get_blocks(ag, time_var, to, start_epoch, block_size, direction) col_classes <- sapply(ag, function(x) class(x)[1]) col_numeric <- col_classes %in% c("numeric", "integer") first_vars <- names(col_classes)[!col_numeric] sum_vars <- names(col_classes)[col_numeric] ag[ ,time_var] <- as.character(ag[ ,time_var]) firsts <- sapply(match(first_vars, names(ag)), function(x) tapply(ag[ ,x], ag$block_no, function(y) switch(direction, "forwards" = y[1], "backwards" = y[length(y)]))) firsts <- stats::setNames(data.frame(firsts, stringsAsFactors = FALSE), first_vars) sums <- sapply(match(sum_vars, names(ag)), function(x) tapply(ag[ ,x], ag$block_no, sum, na.rm = TRUE)) sums <- stats::setNames(data.frame(sums, stringsAsFactors = FALSE), sum_vars) ag <- data.frame(cbind(firsts, sums), stringsAsFactors = FALSE) ag[ ,sum_vars] <- sapply(ag[ ,sum_vars], as.numeric) ag[ ,time_var] <- as.POSIXct(ag$Timestamp, "UTC") ag$block_no <- NULL triaxial_vars <- c("Axis1", "Axis2", "Axis3") if (all(triaxial_vars %in% names(ag))) { ag$Vector.Magnitude <- round(get_VM(ag[ ,triaxial_vars]), 2) } return(ag) }
.runThisTest <- Sys.getenv("RunAllinsightTests") == "yes" .runStanTest <- Sys.getenv("RunAllinsightStanTests") == "yes" if (.runThisTest && .runStanTest && requiet("testthat") && requiet("insight") && requiet("brms")) { data(mtcars) set.seed(123) model <- brms::brm(mpg ~ wt, data = mtcars, seed = 1, refresh = 0) priors <- insight::get_priors(model) test_that("get_priors", { expect_equal(priors$Location, c(19.2, NA, 0), tolerance = 1e-3) expect_equal(priors$Distribution, c("student_t", "uniform", "student_t")) expect_equal(priors$Parameter, c("b_Intercept", "b_wt", "sigma")) }) }
.path_to_gb.dmp <- function(package="ncbit"){ path=paste(system.file(package=package), "data", sep="/") nd=paste(path, "nodes.dmp", sep="/") nm=paste(path, "names.dmp", sep="/") ncbi=paste(path, "ncbi.rda", sep="/") return(c(ncbi=ncbi, names=nm, nodes=nd, base=path)) }
library(testthat) library(seriation) library(dendextend) set.seed(0) context("ser_permutation_vector") p <- sample(1:10) sp <- ser_permutation_vector(p, method="valid") expect_identical(length(sp), 10L) expect_identical(get_order(sp), p) expect_identical(get_order(rev(sp)), rev(p)) expect_error(ser_permutation_vector(c(1:10, 12L), method="invalid"), "Invalid permutation vector!") expect_error(ser_permutation_vector(c(1:10, 3L), method="invalid"), "Invalid permutation vector!") context("ser_permutation") expect_identical(length(ser_permutation(sp)), 1L) expect_identical(length(ser_permutation(sp, sp)), 2L) hc <- hclust(dist(runif(10))) expect_identical(length(ser_permutation(sp, hc)), 2L) hc <- ser_permutation_vector(hc, method="hc") expect_identical(length(ser_permutation(sp, hc, sp)), 3L) expect_identical(length(ser_permutation(ser_permutation(sp), 1:10)), 2L) context("permute") v <- structure(1:10, names = LETTERS[1:10]) expect_identical(permute(v, ser_permutation(1:10)), v[1:10]) expect_identical(permute(LETTERS[1:10], ser_permutation(1:10)), LETTERS[1:10]) expect_identical(permute(v, ser_permutation(10:1)), v[10:1]) expect_identical(permute(LETTERS[1:10], ser_permutation(10:1)), LETTERS[10:1]) expect_error(permute(v, ser_permutation(1:11))) m <- matrix(runif(9), ncol=3, dimnames = list(1:3, LETTERS[1:3])) expect_identical(permute(m, ser_permutation(1:3, 3:1)), m[,3:1]) expect_identical(permute(m, ser_permutation(3:1, 3:1)), m[3:1,3:1]) expect_error(permute(m, ser_permutation(1:10, 1:9))) expect_error(permute(m, ser_permutation(1:9, 1:11))) expect_identical(permute(m, ser_permutation(3:1, 3:1), margin = 1), m[3:1, ]) expect_identical(permute(m, ser_permutation(3:1, 3:1), margin = 2), m[ , 3:1]) expect_identical(permute(m, ser_permutation(3:1), margin = 1), m[3:1, ]) expect_identical(permute(m, ser_permutation(3:1), margin = 2), m[, 3:1]) df <- as.data.frame(m) expect_identical(permute(df, ser_permutation(1:3, 3:1)), df[,3:1]) expect_identical(permute(df, ser_permutation(3:1, 3:1)), df[3:1,3:1]) d <- dist(matrix(runif(25), ncol=5)) attr(d, "call") <- NULL expect_identical(permute(d, ser_permutation(1:5)), d) expect_equivalent(permute(d, ser_permutation(5:1)), as.dist(as.matrix(d)[5:1,5:1])) expect_error(permute(d, ser_permutation(1:8))) l <- list(a = 1:10, b = letters[1:5], 25) expect_identical(permute(l, 3:1), rev(l)) dend <- as.dendrogram(hclust(d)) expect_equal(dend, permute(dend, get_order(dend))) expect_equal(rev(dend), permute(dend, rev(get_order(dend)))) o <- sample(5) expect_warning(permute(dend, o)) hc <- hclust(d) expect_equal(hc, permute(hc, get_order(hc))) expect_equal(as.hclust(rev(as.dendrogram(hc)))[1:3], permute(hc, rev(get_order(hc)))[1:3]) expect_warning(permute(hc, o)) context("permutation_matrix2vector") pv <- 1:5 pm <- permutation_vector2matrix(pv) expect_true(all(diag(pm) == 1)) pv <- sample(1:100) pm <- permutation_vector2matrix(pv) expect_identical(permutation_matrix2vector(pm), pv)
{ } seq_consecutive <- function(x,...){ stopifnot(is.vector(x)) y <- integer(length(x)) y[1] <- 1 if(length(x)>1)for(i in seq_len(length(x))[-1]){ if(x[i]==x[i-1]) y[i] <- y[i-1] else y[i] <- y[i-1] +1 } return(y) }
cubeClvR2 <- function(cF = 1, crF = 0, ccF = cF, ccrF = crF, cM = 1, crM = 0, ccM = cM, ccrM = crM, dW = 0, drW = 0, ddW = dW, ddrW = drW, hSuf = 1, crossF = 0.5, crossM = 0.5, eta=NULL, phi=NULL,omega=NULL, xiF=NULL, xiM=NULL, s=NULL){ params <- c(cF,crF,ccF,ccrF,cM,crM,ccM,ccrM,dW,drW,ddW,ddrW,hSuf,crossF,crossM) if(any(params>1) || any(params<0)){ stop("Parameters are rates, they must be between 0 and 1.") } gTypes <- list(c('W', 'C'), c('W', 'G')) gTypes2 <- c('W', 'R', 'B') genotypes <- c('WWWWWW','WWWWRW','WWWWBW','WWWWRR','WWWWBR','WWWWBB', 'CWWWWW','CWWWRW','CWWWBW','CWWWRR','CWWWBR','CWWWBB', 'WGWWWW','WGWWRW','WGWWBW','WGWWRR','WGWWBR','WGWWBB', 'CGWWWW','CGWWRW','CGWWBW','CGWWRR','CGWWBR','CGWWBB', 'CWCWWW','CWCWRW','CWCWBW','CWCWRR','CWCWBR','CWCWBB', 'CWWGWW','CWWGRW','CWWGBW','CWWGRR','CWWGBR','CWWGBB', 'CGCWWW','CGCWRW','CGCWBW','CGCWRR','CGCWBR','CGCWBB', 'WGWGWW','WGWGRW','WGWGBW','WGWGRR','WGWGBR','WGWGBB', 'CGWGWW','CGWGRW','CGWGBW','CGWGRR','CGWGBR','CGWGBB', 'CGCGWW','CGCGRW','CGCGBW','CGCGRR','CGCGBR','CGCGBB') locus12 <- list("W"=c("W"=1), "C"=c("C"=1), "G"=c("G"=1)) fLocus3 <- list() fLocus3$mendelian <- list("W"=c("W"=1), "R"=c("R"=1), "B"=c("B"=1)) fLocus3$oneCas <- list("W"=c("W"=1-cF, "R"=cF*crF, "B"=cF*(1-crF)), "R"=c("R"=1), "B"=c("B"=1)) fLocus3$twoCas <- list("W"=c("W"=1-ccF, "R"=ccF*ccrF, "B"=ccF*(1-ccrF)), "R"=c("R"=1), "B"=c("B"=1)) mLocus3 <- list() mLocus3$zero <- list("W"=c("W"=1), "R"=c("R"=1), "B"=c("B"=1)) mLocus3$zeroOne <- list("W"=c("W"=1-dW, "R"=dW*drW, "B"=dW*(1-drW)), "R"=c("R"=1), "B"=c("B"=1)) mLocus3$zeroTwo <- list("W"=c("W"=1-ddW, "R"=ddW*ddrW, "B"=ddW*(1-ddrW)), "R"=c("R"=1), "B"=c("B"=1)) mLocus3$one <- list("W"=c("W"=1-cM, "R"=cM*crM, "B"=cM*(1-crM)), "R"=c("R"=1), "B"=c("B"=1)) mLocus3$oneOne <- list("W"=c("W"=(1-cM)*(1-dW), "R"=cM*crM + dW*drW, "B"=cM*(1-crM) + dW*(1-drW)), "R"=c("R"=1), "B"=c("B"=1)) mLocus3$oneTwo <- list("W"=c("W"=(1-cM)*(1-ddW), "R"=cM*crM + ddW*ddrW, "B"=cM*(1-crM) + ddW*(1-ddrW)), "R"=c("R"=1), "B"=c("B"=1)) mLocus3$two <- list("W"=c("W"=1-ccM, "R"=ccM*ccrM, "B"=ccM*(1-ccrM)), "R"=c("R"=1), "B"=c("B"=1)) mLocus3$twoOne <- list("W"=c("W"=(1-ccM)*(1-dW), "R"=ccM*ccrM + dW*drW, "B"=ccM*(1-ccrM) + dW*(1-drW)), "R"=c("R"=1), "B"=c("B"=1)) mLocus3$twoTwo <- list("W"=c("W"=(1-ccM)*(1-ddW), "R"=ccM*ccrM + ddW*ddrW, "B"=ccM*(1-ccrM) + ddW*(1-ddrW)), "R"=c("R"=1), "B"=c("B"=1)) numGen <- length(genotypes) tMatrix <- array(data = 0, dim = c(numGen,numGen,numGen), dimnames = list(genotypes,genotypes,genotypes)) numAlleles <- 2 numLoci <- 3 fScore <- mScore <- integer(length = numAlleles) for(fi in 1:numGen){ fSplit <- strsplit(x = genotypes[fi], split = "", useBytes = TRUE)[[1]] fAlleleMat <- matrix(data = fSplit, nrow = numAlleles, ncol = numLoci) fScore[1] <- sum('C' == fAlleleMat) fScore[2] <- any('G' == fAlleleMat) fPHold <- rep(x = list(list()), times = numLoci) fAllele <- character(length = 0L) fProbs <- numeric(length = 0L) fPHold[[1]] <- locus12[ fAlleleMat[ ,1] ] fPHold[[2]] <- locus12[ fAlleleMat[ ,2] ] if(all(fScore)){ if(fScore[1] == 1){ fPHold[[3]] <- fLocus3$oneCas[ fAlleleMat[ ,3] ] } else { fPHold[[3]] <- fLocus3$twoCas[ fAlleleMat[ ,3] ] } } else { fPHold[[3]] <- fLocus3$mendelian[ fAlleleMat[ ,3] ] } hold1 <- fPHold[[1]][[1]] fPHold[[1]][[1]] <- c((1-crossF)*hold1, crossF*fPHold[[2]][[1]]) fPHold[[2]][[1]] <- c((1-crossF)*fPHold[[2]][[1]], crossF*hold1) for(allele in 1:numAlleles){ holdProbs <- expand.grid(fPHold[[allele]],KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE) holdAllele <- expand.grid(names(fPHold[[allele]][[1]]), names(fPHold[[allele]][[2]]), KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE) fProbs <- c(fProbs, holdProbs[,1]*holdProbs[,2]) fAllele <- c(fAllele, file.path(holdAllele[,1], holdAllele[,2], fsep = "")) } fAllele <- fAllele[fProbs!=0] fProbs <- fProbs[fProbs!=0] for(mi in 1:numGen){ mSplit <- strsplit(x = genotypes[mi], split = "", useBytes = TRUE)[[1]] mAlleleMat <- matrix(data = mSplit, nrow = numAlleles, ncol = numLoci) mScore[1] <- sum('C' == mAlleleMat) mScore[2] <- any('G' == mAlleleMat) mPHold <- rep(x = list(list()), times = numLoci) mAllele <- character(length = 0L) mProbs <- numeric(length = 0L) mPHold[[1]] <- locus12[ mAlleleMat[ ,1] ] mPHold[[2]] <- locus12[ mAlleleMat[ ,2] ] if(all(mScore)){ if(mScore[1] == 1){ if(all(fScore)){ if(fScore[1]== 1){ mPHold[[3]] <- mLocus3$oneOne[ mAlleleMat[ ,3] ] } else { mPHold[[3]] <- mLocus3$oneTwo[ mAlleleMat[ ,3] ] } } else { mPHold[[3]] <- mLocus3$one[ mAlleleMat[ ,3] ] } } else { if(all(fScore)){ if(fScore[1]== 1){ mPHold[[3]] <- mLocus3$twoOne[ mAlleleMat[ ,3] ] } else { mPHold[[3]] <- mLocus3$twoTwo[ mAlleleMat[ ,3] ] } } else { mPHold[[3]] <- mLocus3$two[ mAlleleMat[ ,3] ] } } } else { if(all(fScore)){ if(fScore[1]== 1){ mPHold[[3]] <- mLocus3$zeroOne[ mAlleleMat[ ,3] ] } else { mPHold[[3]] <- mLocus3$zeroTwo[ mAlleleMat[ ,3] ] } } else { mPHold[[3]] <- mLocus3$zero[ mAlleleMat[ ,3] ] } } hold1 <- mPHold[[1]][[1]] mPHold[[1]][[1]] <- c((1-crossM)*hold1, crossM*mPHold[[2]][[1]]) mPHold[[2]][[1]] <- c((1-crossM)*mPHold[[2]][[1]], crossM*hold1) for(allele in 1:numAlleles){ holdProbs <- expand.grid(mPHold[[allele]],KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE) holdAllele <- expand.grid(names(mPHold[[allele]][[1]]), names(mPHold[[allele]][[2]]), KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE) mProbs <- c(mProbs, holdProbs[,1]*holdProbs[,2]) mAllele <- c(mAllele, file.path(holdAllele[,1], holdAllele[,2], fsep = "")) } mAllele <- mAllele[mProbs!=0] mProbs <- mProbs[mProbs!=0] holdProbs <- expand.grid(fProbs, mProbs, KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE) holdAllele <- expand.grid(fAllele, mAllele, KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE) holdAllele <- apply(X = holdAllele, MARGIN = 1, FUN = sort.int) holdProbs <- holdProbs[ ,1]*holdProbs[ ,2] holdAllele <- file.path(holdAllele[1,], holdAllele[2,], fsep = "") reducedOneTwo <- vapply(X = unique(holdAllele), FUN = function(x){ sum(holdProbs[holdAllele==x])}, FUN.VALUE = numeric(length = 1L)) holdProbs <- expand.grid(unlist(fPHold[[3]], use.names = FALSE), unlist(mPHold[[3]], use.names = FALSE), KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE) holdAllele <- expand.grid(names(c(fPHold[[3]][[1]], fPHold[[3]][[2]])), names(c(mPHold[[3]][[1]], mPHold[[3]][[2]])), KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE) holdAllele <- apply(X = holdAllele, MARGIN = 1, FUN = sort.int) holdProbs <- holdProbs[ ,1]*holdProbs[ ,2] holdAllele <- file.path(holdAllele[1,], holdAllele[2,], fsep = "") reducedThree <- vapply(X = unique(holdAllele), FUN = function(x){ sum(holdProbs[holdAllele==x])}, FUN.VALUE = numeric(length = 1L)) alleles <- as.vector(outer(X = names(reducedOneTwo), Y = names(reducedThree), FUN = file.path, fsep = "")) probs <- as.vector(outer(X = reducedOneTwo, Y = reducedThree, FUN = '*')) probs <- probs/sum(probs) tMatrix[fi,mi, alleles ] <- probs } } tMatrix[tMatrix < .Machine$double.eps] <- 0 viabilityVec <- c(1,1,hSuf,1,hSuf,0, 1,1,hSuf,1,hSuf,0, 1,1,1,1,1,hSuf, 1,1,1,1,1,hSuf, 1,1,hSuf,1,hSuf,0, 1,1,1,1,1,hSuf, 1,1,1,1,1,hSuf, 1,1,1,1,1,1, 1,1,1,1,1,1, 1,1,1,1,1,1) viabilityMask <- aperm(a = array(data = viabilityVec, dim = c(numGen,numGen,numGen), dimnames = list(genotypes, genotypes, genotypes)), perm = c(3,2,1),resize = TRUE) modifiers = cubeModifiers(genotypes, eta = eta, phi = phi, omega = omega, xiF = xiF, xiM = xiM, s = s) return(list( ih = tMatrix, tau = viabilityMask, genotypesID = genotypes, genotypesN = numGen, wildType = "WWWWWW", eta = modifiers$eta, phi = modifiers$phi, omega = modifiers$omega, xiF = modifiers$xiF, xiM = modifiers$xiM, s = modifiers$s, releaseType = "CGCGWW" )) }
context("nlm_distancegradient") test_that("nlm_distancegradient behaves like it should", { suppressWarnings(distance_gradient <- nlm_distancegradient(ncol = 9, nrow = 12, origin = c(5, 5, 5, 5))) expect_that(distance_gradient, is_a("RasterLayer")) }) test_that("nlm_distancegradient sets origin right", { suppressWarnings(distance_gradient <- nlm_distancegradient(ncol = 9, nrow = 12, origin = c(5, 5, 5, 5))) expect_equal(raster::as.matrix(distance_gradient)[5, 5], 0) }) test_that("nlm_distancegradient produces the right number of rows", { suppressWarnings(distance_gradient <- nlm_distancegradient(ncol = 9, nrow = 12, origin = c(5, 5, 5, 5))) expect_equal(distance_gradient@nrows, 12) }) test_that("nlm_distancegradient produces the right number of columns", { suppressWarnings(distance_gradient <- nlm_distancegradient(ncol = 9, nrow = 12, origin = c(5, 5, 5, 5))) expect_equal(distance_gradient@ncols, 9) })
module.readable <- function(module) { return (file.access(module, mode=4) == 0 && !file.info(module)$isdir) } find.first.R <- function(module, character.only = FALSE, warn.not.found = TRUE) { if (character.only || length(substitute(module)) > 1) { module <- as.character(module) } else { module <- as.character(substitute(module)) } module <- gsub('\\\\', '/', module) module.paths <- get('.:module.paths', envir = module.cache) search.for.r <- (toupper(substr(module, nchar(module)-1, nchar(module))) != '.R') files <- c() if ((substr(module, 1, 1) == '/') || (substr(module, 2, 2) == ':')) { files <- append(files, ifelse(search.for.r, paste(module, 'R', sep='.'), module)) } else { files <- append(files, file.path('.', ifelse(search.for.r, paste(module, 'R', sep='.'), module))) files <- append(files, file.path(module.paths, module)) if (search.for.r) { files <- append(files, file.path(module.paths, paste(module, 'R', sep='.'))) } } files <- gsub('(?<!\\.)\\./', '', files, perl=TRUE) for (filepath in files) { if ((substr(filepath, 1, 1) == '/') || (substr(filepath, 2, 2) == ':')) { } else { filepath <- path.expand(file.path(getwd(), filepath)) filepath <- gsub('/(?<!\\.)[^/]+/\\.\\.', '', filepath, perl=TRUE) } if (module.readable(filepath)) { return (filepath) } } if (missing(warn.not.found)) { warn.not.found <- get('.:warn.not.found', envir = module.cache) } if (warn.not.found) { warning('No module named ', module, ifelse(search.for.r, paste0(' or ', module, '.R'), ''), ' in: ', paste(c('.', module.paths), collapse='/, '), '/.') } return(NA) } hide.not.found.warnings <- function() { assign('.:warn.not.found', FALSE, envir = module.cache) } show.not.found.warnings <- function() { assign('.:warn.not.found', TRUE, envir = module.cache) }
skda<-function(x, y, tau, method="Bayes") { nclass=length(unique(y)) if(length(setdiff(y,1:nclass))>0.5) {stop("The categorical response must be coded as 1, 2, ..., K!!!")} y=y-1 n=length(y) p=dim(as.matrix(x))[2] lam=matrix(0, p,1) phat=matrix(0,n,nclass) maxct=40; priorporp=switch(method, mle=matrix(1/nclass, nclass,1), Bayes=matrix(as.vector(table(y)/length(y)), nclass,1) ) wu=.C("coordescent", as.integer(n), as.integer(p), as.integer(nclass), as.double(x), as.integer(y), as.double(tau), as.integer(maxct), as.double(priorporp), as.double(lam), as.double(phat)); lam=wu[[9]] phat=matrix(wu[[10]],n,nclass) return(list(lam=lam, phat=phat)) } predprob<-function(x,y,lam,xnew, method="Bayes") { nclass=length(unique(y)) if(length(setdiff(y,1:nclass))>0.5) {stop("The categorical response must be coded as 1, 2, ..., K!!!")} y=y-1 n=length(y); p=dim(as.matrix(x))[2]; m=dim(as.matrix(xnew))[1]; priorporp=switch(method, mle=matrix(1/nclass, nclass,1), Bayes=matrix(as.vector(table(y)/length(y)), nclass,1) ) phat=matrix(0,m,nclass); result=.C("condprob", as.integer(n), as.integer(p),as.integer(nclass), as.integer(y), as.double(x), as.double(lam), as.integer(m), as.double(xnew), as.double(priorporp), as.double(phat)); phat=matrix(result[[10]], m, nclass); return(phat); } evalonefold<-function(i,j,n,k,x,y,taus,nclass,method){ tuind=seq(i,n,k); trind=setdiff(1:n,tuind) xtr=x[trind,]; ytr=y[trind]; xtu=x[tuind,]; ytu=y[tuind]; temp=skda(xtr, ytr, taus[j], method); lam=temp$lam; ptuhat=predprob(xtr,ytr,lam,xtu, method); fer=0 for (m in 1:nclass) {ind=which(ytu==m); fer=fer+sum(log(ptuhat[ind,m])); } fer } cvskda<-function(x,y,taus,nfolds=10, method="Bayes") { nclass=length(unique(y)) if(length(setdiff(y,1:nclass))>0.5) {stop("The categorical response must be coded as 1, 2, ..., K!!!")} if(length(taus)<1.5) {stop("There must be more than one taus!!!") } n=length(y); tmpord=sample(n); x=x[tmpord,]; y=y[tmpord]; er=matrix(0,nfolds,length(taus)); mc = detectCores() if(.Platform$OS.type=="windows") { cl <- makeCluster(getOption("cl.cores", mc)) } er=NULL for(j in 1:length(taus)) { if(.Platform$OS.type=="windows") { a=clusterApplyLB (cl, 1:nfolds, function(t)evalonefold(t,j,n,nfolds,x,y,taus,nclass,method)) } else { a=mclapply(1:nfolds, function(t)evalonefold(t,j,n,nfolds,x,y,taus,nclass,method), mc.cores = mc) } er=cbind(er,unlist(a)) if((j>1.5)&(sum(er[,j])<sum(er[,j-1]))) {break; } } if(.Platform$OS.type=="windows") { stopCluster(cl) } cver=apply(er[,1:min(j,length(taus))],2,sum); jbest=which.max(cver); temp=skda(x, y, taus[jbest], method); lam=temp$lam lam }
texmexFamily <- function(name, log.lik, param, info=NULL, sandwich = NULL, start=NULL, resid=NULL, rl, delta, endpoint, density, rng, prob, quant){ res <- list(name=name, log.lik=log.lik, param=param, info=info, sandwich = sandwich, start=start, resid=resid, rl=rl, delta=delta, endpoint=endpoint, density=density, rng=rng, prob=prob, quant=quant) oldClass(res) <- 'texmexFamily' res } print.texmexFamily <- function(x, ...){ cat('Family: ', x$name, '\n') invisible(x) } summary.texmexFamily <- function(object, ...){ res <- list(object=object) if (is.null(object$info)){ res$info <- 'Numerical approximation' } else { res$info <- 'Closed form' } oldClass(res) <- "summary.texmexFamily" res } print.summary.texmexFamily <- function(x, ...){ print.texmexFamily(x$object, ...) cat('Parameters: ', x$object$param, '\n') cat('Information: ', x$info, '\n') invisible(x) }
library(rmarkdown) test_that("documents with spaces in names can be rendered", { the_test <- "citeall" dir_name <- file.path(tempdir(), the_test) if(dir.exists(dir_name)) unlink(dir_name, recursive = TRUE) file_name <- file.path(dir_name, "test.Rmd") dir.create(dir_name) on.exit(unlink(dir_name, recursive = TRUE), add = TRUE) draft(file_name, template = "github_document", package = "rmarkdown", create_dir = FALSE, edit = FALSE) write(c("", "Optional reference: @@reference2020"), file = file_name, append = TRUE) if (rmarkdown::pandoc_available("1.14")){ sink_out <- capture_output(cite_all(file_name)) contents <- readLines(gsub("Rmd$", "md", file_name), encoding = "UTF-8") expect_true(any(contents == "Optional reference: @reference2020")) sink_out <- capture_output(cite_essential(file_name)) contents <- readLines(gsub("Rmd$", "md", file_name), encoding = "UTF-8") expect_true(!any(contents == "Optional reference: @reference2020")) expect_true(any(contents == "Optional reference:")) } }) test_that("cite_* work with umlaute", { the_test <- "citeall" dir_name <- file.path(tempdir(), the_test) if(dir.exists(dir_name)) unlink(dir_name, recursive = TRUE) file_name <- file.path(dir_name, "test.Rmd") dir.create(dir_name) on.exit(unlink(dir_name, recursive = TRUE), add = TRUE) draft(file_name, template = "github_document", package = "rmarkdown", create_dir = FALSE, edit = FALSE) worcs:::write_as_utf(c("", "Optional räference: @@reference2020"), con = file_name, append = TRUE) if (rmarkdown::pandoc_available("1.14")){ sink_out <- capture_output(cite_all(file_name)) md_file <- force(gsub("Rmd$", "md", file_name)) contents <- worcs:::read_as_utf(md_file) expect_true(any(contents == "Optional räference: @reference2020")) sink_out <- capture_output(cite_essential(file_name)) contents <- worcs:::read_as_utf(gsub("Rmd$", "md", file_name)) expect_true(!any(contents == "Optional räference: @reference2020")) expect_true(any(contents == "Optional räference:")) } }) test_that("cite_* retain relative paths", { the_test <- "relative" dir_name <- file.path(tempdir(), the_test) if(dir.exists(dir_name)) unlink(dir_name, recursive = TRUE) file_name <- file.path(dir_name, "test.Rmd") dir.create(dir_name) on.exit(unlink(dir_name, recursive = TRUE), add = TRUE) draft(file_name, template = "github_document", package = "rmarkdown", create_dir = FALSE, edit = FALSE) write(c("", "Optional reference: @@reference2020"), file = file_name, append = TRUE) write.csv(iris, file.path(dir_name, "iris.csv")) write(c("", " ```{r} myiris <- read.csv('iris.csv') ``` "), file = file_name, append = TRUE) if (rmarkdown::pandoc_available("1.14")){ sink_out <- capture_output(cite_all(file_name)) contents <- readLines(normalizePath(gsub("\\.Rmd", "\\.md", file_name))) expect_true(any(contents == "Optional reference: @reference2020")) sink_out <- capture_output(cite_essential(file_name)) contents <- readLines(normalizePath(gsub("\\.Rmd", "\\.md", file_name))) expect_true(!any(contents == "Optional reference: @reference2020")) expect_true(any(grepl("myiris", contents, fixed = TRUE))) expect_true(any(contents == "Optional reference:")) } }) test_that("cite_* retain double @", { the_test <- "citeall" dir_name <- file.path(tempdir(), the_test) if(dir.exists(dir_name)) unlink(dir_name, recursive = TRUE) file_name <- file.path(dir_name, "test.Rmd") dir.create(dir_name) on.exit(unlink(dir_name, recursive = TRUE), add = TRUE) draft(file_name, template = "github_document", package = "rmarkdown", create_dir = FALSE, edit = FALSE) write(c("", "Optional reference: @@reference2020"), file = file_name, append = TRUE) if (rmarkdown::pandoc_available("1.14")){ sink_out <- capture_output(cite_all(file_name)) contents <- readLines(file_name, encoding = "UTF-8") expect_true(any(contents == "Optional reference: @@reference2020")) sink_out <- capture_output(cite_essential(file_name)) contents <- readLines(file_name, encoding = "UTF-8") expect_true(any(contents == "Optional reference: @@reference2020")) } })
getLikes <- function(user="me", n=500, token){ query <- paste0('https://graph.facebook.com/', user, '?fields=likes.limit(', n, ').fields(id,name,website)') content <- callAPI(query, token) if ('data' %in% names(content$likes) == FALSE){ stop("User not found, or token is not authorized.") } df <- userLikesToDF(content$likes$data) next_url <- content$likes$paging$`next` while (!is.null(next_url)){ content <- callAPI(next_url, token) df <- rbind(df, userLikesToDF(content$data)) next_url <- content$paging$`next` } return(df) }
library(caret) data(GermanCredit) ?GermanCredit str(GermanCredit) Train <- createDataPartition(GermanCredit$Class, p=0.6, list=FALSE) training <- GermanCredit[ Train, ] testing <- GermanCredit[ -Train, ] mod_fit <- train(Class ~ Age + ForeignWorker + Property.RealEstate + Housing.Own + CreditHistory.Critical, data=training, method="glm", family="binomial") exp(coef(mod_fit$finalModel)) predict(mod_fit, newdata=testing) predict(mod_fit, newdata=testing, type="prob") mod_fit_one <- glm(Class ~ Age + ForeignWorker + Property.RealEstate + Housing.Own + CreditHistory.Critical, data=training, family="binomial") predict(mod_fit_one, newdata=testing) mod_fit_two <- glm(Class ~ Age + ForeignWorker, data=training, family="binomial") anova(mod_fit_one, mod_fit_two, test ="Chisq") library(lmtest) lrtest(mod_fit_one, mod_fit_two) library(pscl) pR2(mod_fit_one) library(MKmisc) HLgof.test(fit = fitted(mod_fit_one), obs = training$Class) library(ResourceSelection) hoslem.test(training$Class, fitted(mod_fit_one), g=10) library(survey) regTermTest(mod_fit_one, "ForeignWorker") regTermTest(mod_fit_one, "CreditHistory.Critical") varImp(mod_fit) red = predict(mod_fit, newdata=testing) accuracy <- table(pred, testing[,"Class"]) sum(diag(accuracy))/sum(accuracy) pred = predict(mod_fit, newdata=testing) confusionMatrix(data=pred, testing$Class) ibrary(pROC) f1 = roc(Class ~ CreditHistory.Critical, data=training) plot(f1, col="red") library(ROCR) prob <- predict(mod_fit_one, newdata=testing, type="response") pred <- prediction(prob, testing$Class) perf <- performance(pred, measure = "tpr", x.measure = "fpr") plot(perf) auc <- performance(pred, measure = "auc") auc <- [email protected][[1]] auc ctrl <- trainControl(method = "repeatedcv", number = 10, savePredictions = TRUE) mod_fit <- train(Class ~ Age + ForeignWorker + Property.RealEstate + Housing.Own + CreditHistory.Critical, data=GermanCredit, method="glm", family="binomial", trControl = ctrl, tuneLength = 5) pred = predict(mod_fit, newdata=testing) confusionMatrix(data=pred, testing$Class)
scatter_plot <- function(x, y, title = NA, sub = NA, xlab = NA, ylab = NA, colours = "black", fill = NULL, shape = 18, xlim_min = NULL, xlim_max = NULL, ylim_min = NULL, ylim_max = NULL, size = 1, colmain = "black", colsub = "black", colaxis = "black", collab = "black", fontmain = 1, fontsub = 1, fontaxis = 1, fontlab = 1, cexmain = 1, cexsub = 1, cexaxis = 1, cexlab = 1, text_p = NA, text_x_loc = NA, text_y_loc = NA, text_col = "black", text_font = NA, text_size = NA, m_text = NA, m_side = 3, m_line = 0.5, m_adj = 0.5, m_col = "black", m_font = 1, m_cex = 1, fitline = FALSE, col_abline = 'black', lty_abline = 1, lwd_abline = 1) { plot(x = x, y = y, type = 'p', main = title, sub = sub, xlab = xlab, ylab = ylab, xlim = c(xlim_min, xlim_max), ylim = c(ylim_min, ylim_max), col = colours, bg = fill, pch = shape, cex = size, col.main = colmain, col.sub = colsub, col.axis = colaxis, col.lab = collab, font.main = fontmain, font.sub = fontsub, font.axis = fontaxis, font.lab = fontlab, cex.main = cexmain, cex.sub = cexsub, cex.axis = cexaxis, cex.lab = cexlab) text(text_x_loc, text_y_loc, text_p, font = text_font, col = text_col, cex = text_size) mtext(m_text, side = m_side, line = m_line, adj = m_adj, col = m_col, font = m_font, cex = m_cex) if (fitline) { abline(lm(y ~ x), col = col_abline, lty = lty_abline, lwd = lwd_abline) } }
load("../data/data-filterMS.RData") out_filterMS <- filterMS(msDatObj, paste0("frac", 3:4), "all", 0.05, 1000, 7L) out_filterMS_bord_none <- filterMS(msDatObj, paste0("frac", 3:4), "none", 0.05, 1000, 7L) out_filterMS_bord_1val <- filterMS(msDatObj, paste0("frac", 3:4), 0, 0.05, 1000, 7L) out_filterMS_bord_2val <- filterMS(msDatObj, paste0("frac", 3:4), c(1, 99), 0.05, 1000, 7L) out_filterMS_nfinal_none <- filterMS(msDatObj, paste0("frac", 3:4), c(1, 99), 0.05, 1e9, 7L) out_v1 <- format(out_filterMS) out_bord_none <- format(out_filterMS_bord_none) out_bord_1val <- format(out_filterMS_bord_1val) out_bord_2val <- format(out_filterMS_bord_2val) out_nfinal_none <- format(out_filterMS_nfinal_none) target_v1 <- list() target_v1$newl <- "\n" target_v1$regn <- paste0( "The region of interest was specified as (2 fractions):\n", "------------------------------------------------------\n", " frac3\n", " frac4\n", "\n") target_v1$bord <- paste0( "The bordering regions were specified as \"all\"\n", "---------------------------------------------\n", " frac1\n", " frac2\n", " frac5\n", " frac6\n", "\n") target_v1$fcri <- paste0( "The filtering criteria was specified as:\n", "----------------------------------------\n", " minimum intensity: 1,000 \n", " maximum charge: 7 \n", " bordering region ratio: 0.05\n", "\n") target_v1$prir <- paste0( "The mass spectrometry data prior to filtering had:\n", "--------------------------------------------------\n", " 24 compounds\n", " 6 fractions\n", "\n") target_v1$frem <- paste0( "Individually, each criterion reduced the 24 m/z levels to the following number:\n", "-------------------------------------------------------------------------------\n", " criterion 1: 20 (fraction with max. abundance is in region of interest)\n", " criterion 2: 13 (fractions in bordering region have < 5 of max. abundance)\n", " criterion 3: 18 (nonzero abundance in right adjacent fraction to max.)\n", " criterion 4: 20 (at least 1 intensity > 1,000 in region of interest)\n", " criterion 5: 20 (must have charge <= 7)\n", "\n") target_v1$ffin <- paste0( "The total number of candidate compounds was reduced to:\n", "-------------------------------------------------------\n", " 4\n", "\n") target_v1 <- unlist(target_v1) target_bord_none <- c(bord = paste0( "The bordering regions were specified as \"none\"\n", "----------------------------------------------\n", " * no fraction names to show *\n", "\n")) target_bord_1val <- c(bord = paste0( "The bordering regions were specified as each having length 0:\n", "-------------------------------------------------------------\n", " * no fraction names to show *\n", "\n")) target_bord_2val <- c(bord = paste0( "The bordering regions were specified as having lengths 1 and 99:\n", "----------------------------------------------------------------\n", " frac2\n", " frac5\n", " frac6\n", "\n")) target_nfinal_none <- c(ffin = paste0( "The total number of candidate compounds was reduced to:\n", "-------------------------------------------------------\n", " 0\n", "\n")) save(out_v1, out_bord_none, out_bord_1val, out_bord_2val, out_nfinal_none, target_v1, target_bord_none, target_bord_1val, target_bord_2val, target_nfinal_none, file="tests/data/data-summary-filterMS.RData")
upload_video <- function( file, snippet = NULL, status = list(privacyStatus = "public"), query = NULL, open_url = FALSE, ... ) { if ("privacyStatus" %in% names(status)) { p <- status$privacyStatus p <- match.arg(p, choices = c("private", "public", "unlisted")) } if ("license" %in% names(status)) { p <- status$license p <- match.arg(p, choices = c("creativeCommon", "youtube")) } if ("tags" %in% names(snippet)) { tags <- snippet$tags if (length(tags) == 1) { tags <- list(tags) } snippet$tags <- tags } metadata <- tempfile() body <- list() if (length(snippet) == 0) { snippet <- NULL } if (length(status) == 0) { status <- NULL } body$snippet <- snippet body$status <- status part <- paste(names(body), collapse = ",") query <- as.list(query) query$part <- part body <- jsonlite::toJSON(body, auto_unbox = TRUE) writeLines(body, metadata) body <- list( metadata = upload_file(metadata, type = "application/json; charset=UTF-8"), y = httr::upload_file(file)) yt_check_token() req <- httr::POST("https://www.googleapis.com/upload/youtube/v3/videos", body = body, query = query, config(token = getOption("google_token")), ...) if (httr::status_code(req) > 300) { print(body) print(paste0("File is: ", metadata)) cat(readLines(metadata)) cat("\n") print(query) print(httr::content(req)$error) stop("Request was bad") } tuber_check(req) res <- content(req) url <- paste0("https://www.youtube.com/watch?v=", res$id) if (open_url) { browseURL(url) } list(request = req, content = res, url = url) }